0.9.5claws4
[claws.git] / src / rfc2015.c
index a285c7d638338f5250c1c6140dd9efe98bb0cbce..d90d1dba141326d6f8fa141292e0f2437d7f7185 100644 (file)
@@ -61,13 +61,17 @@ static char *mime_version_name[] = {
     NULL
 };
 
-
-struct passphrase_cb_info_s {
-    GpgmeCtx c;
-    int did_it;
-};
-
-static char *create_boundary (void);
+static void sig_expiration_check       (GString        *str,
+                                        GpgmeCtx        ctx,
+                                        GpgmeKey        key, 
+                                        GpgmeSigStat    status,
+                                        int             idx);
+static void sig_expired                        (GString        *str,
+                                        GpgmeCtx        ctx,
+                                        int             idx);
+static void sig_key_expired            (GString        *str,
+                                        GpgmeKey        key,
+                                        int             idx);
 
 #if 0
 static void dump_mimeinfo (const char *text, MimeInfo *x)
@@ -144,6 +148,12 @@ sig_status_to_string (GpgmeSigStat status)
       case GPGME_SIG_STAT_GOOD:
         result = _("Good signature");
         break;
+      case GPGME_SIG_STAT_GOOD_EXP:    
+       result = _("Good signature but it has expired");
+       break;
+      case GPGME_SIG_STAT_GOOD_EXPKEY:
+       result = _("Good signature but the key has expired");
+       break;
       case GPGME_SIG_STAT_BAD:
         result = _("BAD signature");
         break;
@@ -179,8 +189,14 @@ sig_status_with_name (GpgmeSigStat status)
       case GPGME_SIG_STAT_GOOD:
         result = _("Good signature from \"%s\"");
         break;
+      case GPGME_SIG_STAT_GOOD_EXP:
+        result = _("Good signature from \"%s\" but it has expired");
+        break;
+      case GPGME_SIG_STAT_GOOD_EXPKEY:
+        result = _("Good signature from \"%s\" but the key has expired");
+        break;
       case GPGME_SIG_STAT_BAD:
-        result = _("BAD signature  from \"%s\"");
+        result = _("BAD signature from \"%s\"");
         break;
       case GPGME_SIG_STAT_NOKEY:
         result = _("No public key to verify the signature");
@@ -213,6 +229,7 @@ sig_status_for_key(GString *str, GpgmeCtx ctx, GpgmeSigStat status,
                if ((fpr != NULL) && (*fpr != '\0'))
                        g_string_sprintfa (str, "Key fingerprint: %s\n", fpr);
                g_string_append (str, _("Cannot find user ID for this key."));
+               sig_expiration_check(str, ctx, key, status, 0);
                return;
        }
        g_string_sprintfa (str, sig_status_with_name (status), uid);
@@ -226,6 +243,33 @@ sig_status_for_key(GString *str, GpgmeCtx ctx, GpgmeSigStat status,
                g_string_sprintfa (str, _("                aka \"%s\"\n"),
                                   uid);
        }
+       sig_expiration_check(str, ctx, key, status, 0);
+}
+
+static void
+sig_expiration_check(GString *str, GpgmeCtx ctx, GpgmeKey key, 
+                    GpgmeSigStat status, int idx)
+{
+       if (status == GPGME_SIG_STAT_GOOD_EXP)
+               sig_expired(str, ctx, idx);
+       else if (status == GPGME_SIG_STAT_GOOD_EXPKEY)
+               sig_key_expired(str, key, idx);
+}
+
+static void
+sig_expired(GString *str, GpgmeCtx ctx, int idx)
+{
+       unsigned long exp_time;
+       exp_time = gpgme_get_sig_ulong_attr(ctx, idx, GPGME_ATTR_EXPIRE, 0);
+       g_string_sprintfa(str, _("Signature expired %s"), ctime(&exp_time));    
+}
+
+static void
+sig_key_expired(GString *str, GpgmeKey key, int idx)
+{
+       unsigned long exp_time;
+       exp_time = gpgme_key_get_ulong_attr(key, GPGME_ATTR_EXPIRE, NULL, idx);
+       g_string_sprintfa(str, _("Key expired %s"), ctime(&exp_time));  
 }
 
 static gchar *
@@ -251,7 +295,7 @@ sig_status_full (GpgmeCtx ctx)
                        strftime (ctime_str, sizeof (ctime_str), "%c", 
                                  ctime_val);
                        g_string_sprintfa (str,
-                                          _("Signature made %s\n"),
+                                          _("Signature made at %s\n"),
                                           ctime_str);
                }
                err = gpgme_get_sig_key (ctx, sig_idx, &key);
@@ -284,6 +328,8 @@ static void check_signature (MimeInfo *mimeinfo, MimeInfo *partinfo, FILE *fp)
     GpgmeSigStat status = GPGME_SIG_STAT_NONE;
     GpgmegtkSigStatus statuswindow = NULL;
     const char *result = NULL;
+    gchar *tmp_file;
+    gint n_exclude_chars = 0;
 
     if (prefs_common.gpg_signature_popup)
        statuswindow = gpgmegtk_sig_status_create ();
@@ -294,12 +340,47 @@ static void check_signature (MimeInfo *mimeinfo, MimeInfo *partinfo, FILE *fp)
        goto leave;
     }
 
-    /* don't include the last character (LF). It does not belong to the
-     * signed text */
-    err = gpgme_data_new_from_filepart (&text, NULL, fp,
-                                       mimeinfo->children->fpos,
-                                       mimeinfo->children->size ?
-                                       (mimeinfo->children->size - 1) : 0 );
+    /* don't include the last empty line.
+       It does not belong to the signed text */
+    if (mimeinfo->children->size > 0) {
+       if (fseek(fp, mimeinfo->children->fpos + mimeinfo->children->size - 1,
+                 SEEK_SET) < 0) {
+           perror("fseek");
+           goto leave;
+       }
+       if (fgetc(fp) == '\n') {
+           n_exclude_chars++;
+           if (mimeinfo->children->size > 1) {
+               if (fseek(fp, mimeinfo->children->fpos + mimeinfo->children->size - 2,
+                         SEEK_SET) < 0) {
+                   perror("fseek");
+                   goto leave;
+               }
+               if (fgetc(fp) == '\r')
+                   n_exclude_chars++;
+           }
+       }
+    }
+
+    /* canonicalize the file part. */
+    tmp_file = get_tmp_file();
+    if (copy_file_part(fp, mimeinfo->children->fpos,
+                      mimeinfo->children->size - n_exclude_chars,
+                      tmp_file) < 0) {
+       g_free(tmp_file);
+       goto leave;
+    }
+    if (canonicalize_file_replace(tmp_file) < 0) {
+       unlink(tmp_file);
+       g_free(tmp_file);
+       goto leave;
+    }
+
+    err = gpgme_data_new_from_file(&text, tmp_file, 1);
+
+    unlink(tmp_file);
+    g_free(tmp_file);
+
     if (!err)
        err = gpgme_data_new_from_filepart (&sig, NULL, fp,
                                            partinfo->fpos, partinfo->size);
@@ -310,8 +391,10 @@ static void check_signature (MimeInfo *mimeinfo, MimeInfo *partinfo, FILE *fp)
     }
 
     err = gpgme_op_verify (ctx, sig, text, &status);
-    if (err) 
+    if (err)  {
         debug_print ("gpgme_op_verify failed: %s\n", gpgme_strerror (err));
+        goto leave;
+    }
 
     /* FIXME: check what the heck this sig_status_full stuff is.
      * it should better go into sigstatus.c */
@@ -322,11 +405,14 @@ leave:
     result = gpgmegtk_sig_status_to_string(status);
     debug_print("verification status: %s\n", result);
     if (prefs_common.gpg_signature_popup)
-       gpgmegtk_sig_status_update (statuswindow,ctx);
+       gpgmegtk_sig_status_update (statuswindow, ctx);
 
-    g_assert (!err); /* FIXME: Hey: this may indeed happen */
     g_free (partinfo->sigstatus);
     partinfo->sigstatus = g_strdup (result);
+    partinfo->sig_ok = (status == GPGME_SIG_STAT_GOOD);
+    partinfo->sig_unknown = (status == GPGME_SIG_STAT_NOKEY);
+    partinfo->sig_expired = (status == GPGME_SIG_STAT_GOOD_EXP);
+    partinfo->key_expired = (status == GPGME_SIG_STAT_GOOD_EXPKEY);
 
     gpgme_data_release (sig);
     gpgme_data_release (text);
@@ -335,31 +421,6 @@ leave:
        gpgmegtk_sig_status_destroy (statuswindow);
 }
 
-static const char *
-passphrase_cb (void *opaque, const char *desc, void **r_hd)
-{
-    struct passphrase_cb_info_s *info = opaque;
-    GpgmeCtx ctx = info ? info->c : NULL;
-    const char *pass;
-
-    if (!desc) {
-        /* FIXME: cleanup by looking at **r_hd */
-        return NULL;
-    }
-
-    gpgmegtk_set_passphrase_grab (prefs_common.passphrase_grab);
-    debug_print ("%% requesting passphrase for `%s': ", desc );
-    pass = gpgmegtk_passphrase_mbox (desc);
-    if (!pass) {
-        debug_print ("%% cancel passphrase entry");
-        gpgme_cancel (ctx);
-    }
-    else
-        debug_print ("%% sending passphrase");
-
-    return pass;
-}
-
 /*
  * Copy a gpgme data object to a temporary file and
  * return this filename 
@@ -378,7 +439,7 @@ copy_gpgmedata_to_temp (GpgmeData data, guint *length)
     tmp = g_strdup_printf("%s%cgpgtmp.%08x",
                           get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
 
-    if ((fp = fopen(tmp, "w")) == NULL) {
+    if ((fp = fopen(tmp, "wb")) == NULL) {
         FILE_OP_ERROR(tmp, "fopen");
         g_free(tmp);
         return NULL;
@@ -434,7 +495,7 @@ pgp_decrypt (MimeInfo *partinfo, FILE *fp)
 
     if (!getenv("GPG_AGENT_INFO")) {
         info.c = ctx;
-        gpgme_set_passphrase_cb (ctx, passphrase_cb, &info);
+        gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
     } 
 
     err = gpgme_op_decrypt (ctx, cipher, plain);
@@ -442,12 +503,13 @@ pgp_decrypt (MimeInfo *partinfo, FILE *fp)
 leave:
     gpgme_data_release (cipher);
     if (err) {
+        gpgmegtk_free_passphrase();
         debug_print ("decryption failed: %s\n", gpgme_strerror (err));
         gpgme_data_release (plain);
         plain = NULL;
     }
     else
-        debug_print ("** decryption succeeded");
+        debug_print ("** decryption succeeded\n");
 
     gpgme_release (ctx);
     return plain;
@@ -463,7 +525,7 @@ MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
     if (g_strcasecmp (mimeinfo->content_type, "multipart/signed"))
         return NULL;
 
-    debug_print ("** multipart/signed encountered");
+    debug_print ("** multipart/signed encountered\n");
 
     /* check that we have at least 2 parts of the correct type */
     for (partinfo = mimeinfo->children;
@@ -502,14 +564,34 @@ void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
 
 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
 {
-    if (!mimeinfo)
+    if (!mimeinfo || mimeinfo->mime_type != MIME_MULTIPART)
         return 0;
     if (g_strcasecmp (mimeinfo->content_type, "multipart/encrypted"))
         return 0;
-    /* fixme: we should schek the protocol parameter */
+    /* fixme: we should check the protocol parameter */
     return 1;
 }
 
+gboolean rfc2015_msg_is_encrypted (const gchar *file)
+{
+       FILE *fp;
+       MimeInfo *mimeinfo;
+       int ret;
+
+       if ((fp = fopen(file, "rb")) == NULL)
+               return FALSE;
+
+       mimeinfo = procmime_scan_mime_header(fp);
+       if(!mimeinfo) {
+               fclose(fp);
+               return FALSE;
+       }
+
+       ret = rfc2015_is_encrypted(mimeinfo);
+       procmime_mimeinfo_free_all(mimeinfo);
+       return ret != 0 ? TRUE : FALSE;
+}
+
 static int
 name_cmp(const char *a, const char *b)
 {
@@ -575,7 +657,7 @@ void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
     g_return_if_fail (fp != NULL);
     g_return_if_fail (mimeinfo->mime_type == MIME_MULTIPART);
 
-    debug_print ("** decrypting multipart/encrypted message");
+    debug_print ("** decrypting multipart/encrypted message\n");
 
     /* skip headers */
     if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
@@ -606,7 +688,7 @@ void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
         DECRYPTION_ABORT();
     }
 
-    debug_print ("** yep, it is pgp encrypted");
+    debug_print ("** yep, it is pgp encrypted\n");
 
     plain = pgp_decrypt (partinfo, fp);
     if (!plain) {
@@ -616,7 +698,7 @@ void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
     fname = g_strdup_printf("%s%cplaintext.%08x",
                            get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
 
-    if ((dstfp = fopen(fname, "w")) == NULL) {
+    if ((dstfp = fopen(fname, "wb")) == NULL) {
         FILE_OP_ERROR(fname, "fopen");
         g_free(fname);
         DECRYPTION_ABORT();
@@ -682,7 +764,7 @@ pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
         cipher = NULL;
     }
     else {
-        debug_print ("** encryption succeeded");
+        debug_print ("** encryption succeeded\n");
     }
 
     gpgme_release (ctx);
@@ -747,7 +829,7 @@ rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
     GpgmeRecipients rset = NULL;
     size_t nread;
     int mime_version_seen = 0;
-    char *boundary = create_boundary ();
+    char *boundary = generate_mime_boundary ("Encrypt");
 
     /* Create the list of recipients */
     rset = gpgmegtk_recipient_selection (recp_list);
@@ -875,7 +957,7 @@ rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
 
     if (ascii_armored) {
         fprintf(fp, 
-            "Content-Type: text/plain; charset=us-ascii\r\n"
+            "Content-Type: text/plain; charset=US-ASCII\r\n"
             "Content-Transfer-Encoding: 7bit\r\n"  
             "\r\n");
     } else {
@@ -914,10 +996,9 @@ rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
     /* and the final boundary */
     if (!ascii_armored) {
         fprintf (fp,
-               "\r\n"
-               "--%s--\r\n"
-               "\r\n",
-            boundary);
+                "\r\n"
+                "--%s--\r\n",
+                boundary);
     }
     fflush (fp);
     if (ferror (fp)) {
@@ -942,9 +1023,11 @@ failure:
 /* 
  * plain contains an entire mime object.  Sign it and return an
  * GpgmeData object with the signature of it or NULL in case of error.
+ * r_siginfo returns an XML object with information about the signature.
  */
 static GpgmeData
-pgp_sign (GpgmeData plain, GSList *key_list)
+pgp_sign (GpgmeData plain, GSList *key_list, gboolean clearsign,
+         char **r_siginfo)
 {
     GSList *p;
     GpgmeCtx ctx = NULL;
@@ -952,6 +1035,7 @@ pgp_sign (GpgmeData plain, GSList *key_list)
     GpgmeData sig = NULL;
     struct passphrase_cb_info_s info;
 
+    *r_siginfo = NULL;
     memset (&info, 0, sizeof info);
 
     err = gpgme_new (&ctx);
@@ -963,7 +1047,7 @@ pgp_sign (GpgmeData plain, GSList *key_list)
 
     if (!getenv("GPG_AGENT_INFO")) {
         info.c = ctx;
-        gpgme_set_passphrase_cb (ctx, passphrase_cb, &info);
+        gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
     }
     gpgme_set_textmode (ctx, 1);
     gpgme_set_armor (ctx, 1);
@@ -979,10 +1063,15 @@ pgp_sign (GpgmeData plain, GSList *key_list)
 
     if (err)
        goto leave;
-    err = gpgme_op_sign (ctx, plain, sig, GPGME_SIG_MODE_DETACH);
+    err = gpgme_op_sign
+       (ctx, plain, sig,
+        clearsign ? GPGME_SIG_MODE_CLEAR : GPGME_SIG_MODE_DETACH);
+    if (!err)
+        *r_siginfo = gpgme_get_op_info (ctx, 0);
 
 leave:
     if (err) {
+        gpgmegtk_free_passphrase();
         debug_print ("signing failed: %s\n", gpgme_strerror (err));
         gpgme_data_release (sig);
         sig = NULL;
@@ -995,6 +1084,67 @@ leave:
     return sig;
 }
 
+/*
+ * Find TAG in XML and return a pointer into xml set just behind the
+ * closing angle.  Return NULL if not found. 
+ */
+static const char *
+find_xml_tag (const char *xml, const char *tag)
+{
+    int taglen = strlen (tag);
+    const char *s = xml;
+    while ( (s = strchr (s, '<')) ) {
+        s++;
+        if (!strncmp (s, tag, taglen)) {
+            const char *s2 = s + taglen;
+            if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
+                /* found */
+                while (*s2 && *s2 != '>') /* skip attributes */
+                    s2++;
+                /* fixme: do need to handle angles inside attribute vallues? */
+                return *s2? (s2+1):NULL;
+            }
+        }
+        while (*s && *s != '>') /* skip to end of tag */
+            s++;
+    }
+    return NULL;
+}
+
+
+/*
+ * Extract the micalg from an GnupgOperationInfo XML container.
+ */
+static char *
+extract_micalg (char *xml)
+{
+    const char *s;
+
+    s = find_xml_tag (xml, "GnupgOperationInfo");
+    if (s) {
+        const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
+        s = find_xml_tag (s, "signature");
+        if (s && s_end && s < s_end) {
+            const char *s_end2 = find_xml_tag (s, "/signature");
+            if (s_end2 && s_end2 < s_end) {
+                s = find_xml_tag (s, "micalg");
+                if (s && s < s_end2) {
+                    s_end = strchr (s, '<');
+                    if (s_end) {
+                        char *p = g_malloc (s_end - s + 1);
+                        memcpy (p, s, s_end - s);
+                        p[s_end-s] = 0;
+                        return p;
+                    }
+                }
+            }
+        }
+    }
+    return NULL;
+}
+
+
 /*
  * Sign the file and replace its content with the signed one.
  */
@@ -1011,7 +1161,9 @@ rfc2015_sign (const char *file, GSList *key_list)
     GpgmeData sigdata = NULL;
     size_t nread;
     int mime_version_seen = 0;
-    char *boundary = create_boundary ();
+    char *boundary = generate_mime_boundary ("Signature");
+    char *micalg = NULL;
+    char *siginfo;
 
     /* Open the source file */
     if ((fp = fopen(file, "rb")) == NULL) {
@@ -1081,7 +1233,11 @@ rfc2015_sign (const char *file, GSList *key_list)
         goto failure;
     }
 
-    sigdata = pgp_sign (plain, key_list);
+    sigdata = pgp_sign (plain, key_list, FALSE, &siginfo); 
+    if (siginfo) {
+       micalg = extract_micalg (siginfo);
+       free (siginfo);
+    }
     if (!sigdata) 
         goto failure;
 
@@ -1117,13 +1273,17 @@ rfc2015_sign (const char *file, GSList *key_list)
     header = NULL;
 
     if (!mime_version_seen) 
-        fputs ("MIME-Version: 1\r\n", fp);
+        fputs ("MIME-Version: 1.0\r\n", fp);
     fprintf (fp, "Content-Type: multipart/signed; "
-                "protocol=\"application/pgp-signature\";\r\n"
-                " boundary=\"%s\"\r\n", boundary );
+             "protocol=\"application/pgp-signature\";\r\n");
+    if (micalg)
+        fprintf (fp, " micalg=\"%s\";", micalg);
+    fprintf (fp, " boundary=\"%s\"\r\n", boundary);
 
     /* Part 1: signed material */
-    fprintf (fp, "\r\n--%s\r\n", boundary);
+    fprintf (fp, "\r\n"
+                 "--%s\r\n",
+                 boundary);
     err = gpgme_data_rewind (plain);
     if (err) {
         debug_print ("gpgme_data_rewind on plain failed: %s\n",
@@ -1139,7 +1299,9 @@ rfc2015_sign (const char *file, GSList *key_list)
     }
 
     /* Part 2: signature */
-    fprintf (fp, "\r\n--%s\r\n", boundary);
+    fprintf (fp, "\r\n"
+                 "--%s\r\n",
+                 boundary);
     fputs ("Content-Type: application/pgp-signature\r\n"
           "\r\n", fp);
 
@@ -1159,7 +1321,9 @@ rfc2015_sign (const char *file, GSList *key_list)
     }
 
     /* Final boundary */
-    fprintf (fp, "\r\n--%s--\r\n\r\n", boundary);
+    fprintf (fp, "\r\n"
+                 "--%s--\r\n",
+                 boundary);
     fflush (fp);
     if (ferror (fp)) {
         FILE_OP_ERROR (file, "fwrite");
@@ -1170,6 +1334,7 @@ rfc2015_sign (const char *file, GSList *key_list)
     gpgme_data_release (plain);
     gpgme_data_release (sigdata);
     g_free (boundary);
+    g_free (micalg);
     return 0;
 
 failure:
@@ -1179,62 +1344,95 @@ failure:
     gpgme_data_release (plain);
     gpgme_data_release (sigdata);
     g_free (boundary);
+    g_free (micalg);
     return -1; /* error */
 }
 
 
-/****************
- * Create a new boundary in a way that it is very unlikely that this
- * will occur in the following text.  It would be easy to ensure
- * uniqueness if everything is either quoted-printable or base64
- * encoded (note that conversion is allowed), but because MIME bodies
- * may be nested, it may happen that the same boundary has already
- * been used. We avoid scanning the message for conflicts and hope the
- * best.
- *
- *   boundary := 0*69<bchars> bcharsnospace
- *   bchars := bcharsnospace / " "
- *   bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
- *                    "+" / "_" / "," / "-" / "." /
- *                    "/" / ":" / "=" / "?"  
+/*
+ * Sign the file with clear text and replace its content with the signed one.
  */
-
-static char *
-create_boundary (void)
+gint
+rfc2015_clearsign (const gchar *file, GSList *key_list)
 {
-    static char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-                       "abcdefghijklmnopqrstuvwxyz"
-                       "1234567890'()+_,./:=?";
-    char buf[17];
-    int i, equal;
-    int pid;
-
-    pid = getpid();
-
-    /* We make the boundary depend on the pid, so that all running
-     * processed generate different values even when they have been
-     * started within the same second and srand48(time(NULL)) has been
-     * used.  I can't see whether this is really an advantage but it
-     * doesn't do any harm.
-     */
-    equal = -1;
-    for(i = 0; i < sizeof(buf) - 1; i++) {
-       buf[i] = tbl[(lrand48() ^ pid) % (sizeof(tbl) - 1)]; /* fill with random */
-       if(buf[i] == '=' && equal == -1)
-           equal = i;
-    }
-    buf[i] = 0;
-
-    /* now make sure that we do have the sequence "=." in it which cannot
-     * be matched by quoted-printable or base64 encoding */
-    if(equal != -1 && (equal+1) < i)
-       buf[equal+1] = '.';
-    else {
-       buf[0] = '=';
-       buf[1] = '.';
+    FILE *fp;
+    gchar buf[BUFFSIZE];
+    GpgmeError err;
+    GpgmeData text = NULL;
+    GpgmeData sigdata = NULL;
+    size_t nread;
+    gchar *siginfo;
+
+    if ((fp = fopen(file, "rb")) == NULL) {
+       FILE_OP_ERROR(file, "fopen");
+       goto failure;
+    }
+
+    err = gpgme_data_new(&text);
+    if (err) {
+       debug_print("gpgme_data_new failed: %s\n", gpgme_strerror(err));
+       goto failure;
+    }
+
+    while (!err && fgets(buf, sizeof(buf), fp)) {
+       err = gpgme_data_write(text, buf, strlen(buf));
+    }
+    if (ferror(fp)) {
+       FILE_OP_ERROR(file, "fgets");
+       goto failure;
+    }
+    if (err) {
+       debug_print("gpgme_data_write failed: %s\n", gpgme_strerror(err));
+       goto failure;
+    }
+
+    sigdata = pgp_sign(text, key_list, TRUE, &siginfo);
+    if (siginfo) {
+       g_free(siginfo);
+    }
+    if (!sigdata)
+       goto failure;
+
+    if (fclose(fp) == EOF) {
+       FILE_OP_ERROR(file, "fclose");
+       fp = NULL;
+       goto failure;
+    }
+    if ((fp = fopen(file, "wb")) == NULL) {
+       FILE_OP_ERROR(file, "fopen");
+       goto failure;
+    }
+
+    err = gpgme_data_rewind(sigdata);
+    if (err) {
+       debug_print("gpgme_data_rewind on sigdata failed: %s\n",
+                   gpgme_strerror(err));
+       goto failure;
+    }
+
+    while (!(err = gpgme_data_read(sigdata, buf, sizeof(buf), &nread))) {
+       fwrite(buf, nread, 1, fp);
+    }
+    if (err != GPGME_EOF) {
+       debug_print("gpgme_data_read failed: %s\n", gpgme_strerror(err));
+       goto failure;
     }
 
-    return g_strdup(buf);
+    if (fclose(fp) == EOF) {
+       FILE_OP_ERROR(file, "fclose");
+       fp = NULL;
+       goto failure;
+    }
+    gpgme_data_release(text);
+    gpgme_data_release(sigdata);
+    return 0;
+
+failure:
+    if (fp)
+       fclose(fp);
+    gpgme_data_release(text);
+    gpgme_data_release(sigdata);
+    return -1;
 }
 
 #endif /* USE_GPGME */