Allow 'Z' as time zone in procheader_scan_date_string()
[claws.git] / src / procheader.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <time.h>
31 #include <sys/stat.h>
32
33 #ifdef G_OS_WIN32
34 #  include <w32lib.h>
35 #endif
36
37 #include "procheader.h"
38 #include "procmsg.h"
39 #include "codeconv.h"
40 #include "prefs_common.h"
41 #include "hooks.h"
42 #include "utils.h"
43 #include "defs.h"
44
45 #define BUFFSIZE        8192
46
47 static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
48
49 typedef char *(*getlinefunc) (char *, size_t, void *);
50 typedef int (*peekcharfunc) (void *);
51 typedef int (*getcharfunc) (void *);
52 typedef gint (*get_one_field_func) (gchar *, size_t, void *, HeaderEntry[]);
53
54 static gint string_get_one_field(gchar *buf, size_t len, char **str,
55                                  HeaderEntry hentry[]);
56
57 static char *string_getline(char *buf, size_t len, char **str);
58 static int string_peekchar(char **str);
59 static int file_peekchar(FILE *fp);
60 static gint generic_get_one_field(gchar *buf, size_t len, void *data,
61                                   HeaderEntry hentry[],
62                                   getlinefunc getline, 
63                                   peekcharfunc peekchar,
64                                   gboolean unfold);
65 static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
66                              gboolean full, gboolean decrypted);
67
68
69 gint procheader_get_one_field(gchar *buf, size_t len, FILE *fp,
70                               HeaderEntry hentry[])
71 {
72         return generic_get_one_field(buf, len, fp, hentry,
73                                      (getlinefunc)fgets_crlf, (peekcharfunc)file_peekchar,
74                                      TRUE);
75 }
76
77 static gint string_get_one_field(gchar *buf, size_t len, char **str,
78                                  HeaderEntry hentry[])
79 {
80         return generic_get_one_field(buf, len, str, hentry,
81                                      (getlinefunc)string_getline,
82                                      (peekcharfunc)string_peekchar,
83                                      TRUE);
84 }
85
86 static char *string_getline(char *buf, size_t len, char **str)
87 {
88         gboolean is_cr = FALSE;
89         gboolean last_was_cr = FALSE;
90
91         if (!*str || !**str)
92                 return NULL;
93
94         for (; **str && len > 1; --len) {
95                 is_cr = (**str == '\r');
96                 if ((*buf++ = *(*str)++) == '\n') {
97                     break;
98                 }
99                 if (last_was_cr) {
100                         *(--buf) = '\n';
101                         buf++;
102                     break;
103                 }
104                 last_was_cr = is_cr;
105         }
106                 
107         *buf = '\0';
108
109         return buf;
110 }
111
112 static int string_peekchar(char **str)
113 {
114         return **str;
115 }
116
117 static int file_peekchar(FILE *fp)
118 {
119         return ungetc(getc(fp), fp);
120 }
121
122 static gint generic_get_one_field(gchar *buf, size_t len, void *data,
123                           HeaderEntry *hentry,
124                           getlinefunc getline, peekcharfunc peekchar,
125                           gboolean unfold)
126 {
127         gint nexthead;
128         gint hnum = 0;
129         HeaderEntry *hp = NULL;
130
131         if (hentry != NULL) {
132                 /* skip non-required headers */
133                 do {
134                         do {
135                                 if (getline(buf, len, data) == NULL)
136                                         return -1;
137                                 if (buf[0] == '\r' || buf[0] == '\n')
138                                         return -1;
139                         } while (buf[0] == ' ' || buf[0] == '\t');
140
141                         for (hp = hentry, hnum = 0; hp->name != NULL;
142                              hp++, hnum++) {
143                                 if (!g_ascii_strncasecmp(hp->name, buf,
144                                                  strlen(hp->name)))
145                                         break;
146                         }
147                 } while (hp->name == NULL);
148         } else {
149                 if (getline(buf, len, data) == NULL) return -1;
150                 if (buf[0] == '\r' || buf[0] == '\n') return -1;
151         }
152
153         /* unfold line */
154         while (1) {
155                 nexthead = peekchar(data);
156                 /* ([*WSP CRLF] 1*WSP) */
157                 if (nexthead == ' ' || nexthead == '\t') {
158                         size_t buflen;
159                         gboolean skiptab = (nexthead == '\t');
160                         /* trim previous trailing \n if requesting one header or
161                          * unfolding was requested */
162                         if ((!hentry && unfold) || (hp && hp->unfold))
163                                 strretchomp(buf);
164
165                         buflen = strlen(buf);
166                         
167                         /* concatenate next line */
168                         if ((len - buflen) > 2) {
169                                 if (getline(buf + buflen, len - buflen, data) == NULL)
170                                         break;
171                                 if (skiptab) { /* replace tab with space */
172                                         *(buf + buflen) = ' ';
173                                 }
174                         } else
175                                 break;
176                 } else {
177                         /* remove trailing new line */
178                         strretchomp(buf);
179                         break;
180                 }
181         }
182
183         return hnum;
184 }
185
186 gint procheader_get_one_field_asis(gchar *buf, size_t len, FILE *fp)
187 {
188         return generic_get_one_field(buf, len, fp, NULL,
189                                      (getlinefunc)fgets_crlf, 
190                                      (peekcharfunc)file_peekchar,
191                                      FALSE);
192 }
193
194 GPtrArray *procheader_get_header_array_asis(FILE *fp)
195 {
196         gchar buf[BUFFSIZE];
197         GPtrArray *headers;
198         Header *header;
199
200         cm_return_val_if_fail(fp != NULL, NULL);
201
202         headers = g_ptr_array_new();
203
204         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
205                 if ((header = procheader_parse_header(buf)) != NULL)
206                         g_ptr_array_add(headers, header);
207         }
208
209         return headers;
210 }
211
212 void procheader_header_array_destroy(GPtrArray *harray)
213 {
214         gint i;
215         Header *header;
216
217         for (i = 0; i < harray->len; i++) {
218                 header = g_ptr_array_index(harray, i);
219                 procheader_header_free(header);
220         }
221
222         g_ptr_array_free(harray, TRUE);
223 }
224
225 void procheader_header_free(Header *header)
226 {
227         if (!header) return;
228
229         g_free(header->name);
230         g_free(header->body);
231         g_free(header);
232 }
233
234 /*
235   tests whether two headers' names are equal
236   remove the trailing ':' or ' ' before comparing
237 */
238
239 gboolean procheader_headername_equal(char * hdr1, char * hdr2)
240 {
241         int len1;
242         int len2;
243
244         len1 = strlen(hdr1);
245         len2 = strlen(hdr2);
246         if (hdr1[len1 - 1] == ':')
247                 len1--;
248         if (hdr2[len2 - 1] == ':')
249                 len2--;
250         if (len1 != len2)
251                 return 0;
252
253         return (g_ascii_strncasecmp(hdr1, hdr2, len1) == 0);
254 }
255
256 /*
257   parse headers, for example :
258   From: dinh@enseirb.fr becomes :
259   header->name = "From:"
260   header->body = "dinh@enseirb.fr"
261  */
262 static gboolean header_is_addr_field(const gchar *hdr)
263 {
264         static char *addr_headers[] = {
265                                 "To:",
266                                 "Cc:",
267                                 "Bcc:",
268                                 "From:",
269                                 "Reply-To:",
270                                 "Followup-To:",
271                                 "Followup-and-Reply-To:",
272                                 "Disposition-Notification-To:",
273                                 "Return-Receipt-To:",
274                                 NULL};
275         int i;
276
277         if (!hdr)
278                 return FALSE;
279
280         for (i = 0; addr_headers[i] != NULL; i++)
281                 if (!strcasecmp(hdr, addr_headers[i]))
282                         return FALSE;
283
284         return FALSE;
285 }
286
287 Header * procheader_parse_header(gchar * buf)
288 {
289         gchar *p;
290         Header * header;
291         gboolean addr_field = FALSE;
292
293         if ((*buf == ':') || (*buf == ' '))
294                 return NULL;
295
296         for (p = buf; *p ; p++) {
297                 if ((*p == ':') || (*p == ' ')) {
298                         header = g_new(Header, 1);
299                         header->name = g_strndup(buf, p - buf + 1);
300                         addr_field = header_is_addr_field(header->name);
301                         p++;
302                         while (*p == ' ' || *p == '\t') p++;
303                         header->body = conv_unmime_header(p, NULL, addr_field);
304                         return header;
305                 }
306         }
307         return NULL;
308 }
309
310 void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
311 {
312         gchar buf[BUFFSIZE];
313         HeaderEntry *hp;
314         gint hnum;
315         gchar *p;
316
317         if (hentry == NULL) return;
318
319         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
320                != -1) {
321                 hp = hentry + hnum;
322
323                 p = buf + strlen(hp->name);
324                 while (*p == ' ' || *p == '\t') p++;
325
326                 if (hp->body == NULL)
327                         hp->body = g_strdup(p);
328                 else if (procheader_headername_equal(hp->name, "To") ||
329                          procheader_headername_equal(hp->name, "Cc")) {
330                         gchar *tp = hp->body;
331                         hp->body = g_strconcat(tp, ", ", p, NULL);
332                         g_free(tp);
333                 }
334         }
335 }
336
337 MsgInfo *procheader_parse_file(const gchar *file, MsgFlags flags,
338                                gboolean full, gboolean decrypted)
339 {
340         GStatBuf s;
341         FILE *fp;
342         MsgInfo *msginfo;
343
344         if (g_stat(file, &s) < 0) {
345                 FILE_OP_ERROR(file, "stat");
346                 return NULL;
347         }
348         if (!S_ISREG(s.st_mode))
349                 return NULL;
350
351         if ((fp = g_fopen(file, "rb")) == NULL) {
352                 FILE_OP_ERROR(file, "fopen");
353                 return NULL;
354         }
355
356         msginfo = procheader_parse_stream(fp, flags, full, decrypted);
357         fclose(fp);
358
359         if (msginfo) {
360                 msginfo->size = s.st_size;
361                 msginfo->mtime = s.st_mtime;
362         }
363
364         return msginfo;
365 }
366
367 MsgInfo *procheader_parse_str(const gchar *str, MsgFlags flags, gboolean full,
368                               gboolean decrypted)
369 {
370         return parse_stream(&str, TRUE, flags, full, decrypted);
371 }
372
373 enum
374 {
375         H_DATE = 0,
376         H_FROM,
377         H_TO,
378         H_CC,
379         H_NEWSGROUPS,
380         H_SUBJECT,
381         H_MSG_ID,
382         H_REFERENCES,
383         H_IN_REPLY_TO,
384         H_CONTENT_TYPE,
385         H_SEEN,
386         H_STATUS,
387         H_FROM_SPACE,
388         H_SC_PLANNED_DOWNLOAD,
389         H_SC_MESSAGE_SIZE,
390         H_FACE,
391         H_X_FACE,
392         H_DISPOSITION_NOTIFICATION_TO,
393         H_RETURN_RECEIPT_TO,
394         H_SC_PARTIALLY_RETRIEVED,
395         H_SC_ACCOUNT_SERVER,
396         H_SC_ACCOUNT_LOGIN,
397         H_LIST_POST,
398         H_LIST_SUBSCRIBE,
399         H_LIST_UNSUBSCRIBE,
400         H_LIST_HELP,
401         H_LIST_ARCHIVE,
402         H_LIST_OWNER,
403         H_RESENT_FROM,
404 };
405
406 static HeaderEntry hentry_full[] = {
407                                    {"Date:",            NULL, FALSE},
408                                    {"From:",            NULL, TRUE},
409                                    {"To:",              NULL, TRUE},
410                                    {"Cc:",              NULL, TRUE},
411                                    {"Newsgroups:",      NULL, TRUE},
412                                    {"Subject:",         NULL, TRUE},
413                                    {"Message-ID:",      NULL, FALSE},
414                                    {"References:",      NULL, FALSE},
415                                    {"In-Reply-To:",     NULL, FALSE},
416                                    {"Content-Type:",    NULL, FALSE},
417                                    {"Seen:",            NULL, FALSE},
418                                    {"Status:",          NULL, FALSE},
419                                    {"From ",            NULL, FALSE},
420                                    {"SC-Marked-For-Download:", NULL, FALSE},
421                                    {"SC-Message-Size:", NULL, FALSE},
422                                    {"Face:",            NULL, FALSE},
423                                    {"X-Face:",          NULL, FALSE},
424                                    {"Disposition-Notification-To:", NULL, FALSE},
425                                    {"Return-Receipt-To:", NULL, FALSE},
426                                    {"SC-Partially-Retrieved:", NULL, FALSE},
427                                    {"SC-Account-Server:", NULL, FALSE},
428                                    {"SC-Account-Login:",NULL, FALSE},
429                                    {"List-Post:",       NULL, TRUE},
430                                    {"List-Subscribe:",  NULL, TRUE},
431                                    {"List-Unsubscribe:",NULL, TRUE},
432                                    {"List-Help:",       NULL, TRUE},
433                                    {"List-Archive:",    NULL, TRUE},
434                                    {"List-Owner:",      NULL, TRUE},
435                                    {"Resent-From:",     NULL, TRUE},
436                                    {NULL,               NULL, FALSE}};
437
438 static HeaderEntry hentry_short[] = {
439                                     {"Date:",           NULL, FALSE},
440                                     {"From:",           NULL, TRUE},
441                                     {"To:",             NULL, TRUE},
442                                     {"Cc:",             NULL, TRUE},
443                                     {"Newsgroups:",     NULL, TRUE},
444                                     {"Subject:",        NULL, TRUE},
445                                     {"Message-ID:",     NULL, FALSE},
446                                     {"References:",     NULL, FALSE},
447                                     {"In-Reply-To:",    NULL, FALSE},
448                                     {"Content-Type:",   NULL, FALSE},
449                                     {"Seen:",           NULL, FALSE},
450                                     {"Status:",         NULL, FALSE},
451                                     {"From ",           NULL, FALSE},
452                                     {"SC-Marked-For-Download:", NULL, FALSE},
453                                     {"SC-Message-Size:",NULL, FALSE},
454                                     {NULL,              NULL, FALSE}};
455
456 static HeaderEntry* procheader_get_headernames(gboolean full)
457 {
458         return full ? hentry_full : hentry_short;
459 }
460
461 MsgInfo *procheader_parse_stream(FILE *fp, MsgFlags flags, gboolean full,
462                                  gboolean decrypted)
463 {
464         return parse_stream(fp, FALSE, flags, full, decrypted);
465 }
466
467 static gboolean avatar_from_some_face(gpointer source, gpointer userdata)
468 {
469         AvatarCaptureData *acd = (AvatarCaptureData *)source;
470         
471         if (*(acd->content) == '\0') /* won't be null, but may be empty */
472                 return FALSE;
473
474         if (!strcmp(acd->header, hentry_full[H_FACE].name)) {
475                 debug_print("avatar_from_some_face: found 'Face' header\n");
476                 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_FACE, acd->content);
477         }
478 #if HAVE_LIBCOMPFACE
479         else if (!strcmp(acd->header, hentry_full[H_X_FACE].name)) {
480                 debug_print("avatar_from_some_face: found 'X-Face' header\n");
481                 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_XFACE, acd->content);
482         }
483 #endif
484         return FALSE;
485 }
486
487 static guint avatar_hook_id = 0;
488
489 static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
490                              gboolean full, gboolean decrypted)
491 {
492         MsgInfo *msginfo;
493         gchar buf[BUFFSIZE];
494         gchar *p, *tmp;
495         gchar *hp;
496         HeaderEntry *hentry;
497         gint hnum;
498         void *orig_data = data;
499
500         get_one_field_func get_one_field =
501                 isstring ? (get_one_field_func)string_get_one_field
502                          : (get_one_field_func)procheader_get_one_field;
503
504         hentry = procheader_get_headernames(full);
505
506         if (MSG_IS_QUEUED(flags) || MSG_IS_DRAFT(flags)) {
507                 while (get_one_field(buf, sizeof(buf), data, NULL) != -1) {
508                         if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
509                                 strlen("X-Claws-End-Special-Headers:"))) ||
510                             (!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
511                                 strlen("X-Sylpheed-End-Special-Headers:"))))
512                                 break;
513                         /* from other mailers */
514                         if (!strncmp(buf, "Date: ", 6)
515                         ||  !strncmp(buf, "To: ", 4)
516                         ||  !strncmp(buf, "From: ", 6)
517                         ||  !strncmp(buf, "Subject: ", 9)) {
518                                 if (isstring)
519                                         data = orig_data;
520                                 else 
521                                         rewind((FILE *)data);
522                                 break;
523                         }
524                 }
525         }
526
527         msginfo = procmsg_msginfo_new();
528         
529         if (flags.tmp_flags || flags.perm_flags) 
530                 msginfo->flags = flags;
531         else 
532                 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_NEW | MSG_UNREAD);
533         
534         msginfo->inreplyto = NULL;
535
536         if (avatar_hook_id == 0 && (prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
537                 avatar_hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_from_some_face, NULL);
538         } else if (avatar_hook_id != 0 && !(prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
539                 hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_hook_id);
540                 avatar_hook_id = 0;
541         }
542
543         while ((hnum = get_one_field(buf, sizeof(buf), data, hentry))
544                != -1) {
545                 hp = buf + strlen(hentry[hnum].name);
546                 while (*hp == ' ' || *hp == '\t') hp++;
547
548                 switch (hnum) {
549                 case H_DATE:
550                         if (msginfo->date) break;
551                         msginfo->date_t =
552                                 procheader_date_parse(NULL, hp, 0);
553                         if (g_utf8_validate(hp, -1, NULL)) {
554                                 msginfo->date = g_strdup(hp);
555                         } else {
556                                 gchar *utf = conv_codeset_strdup(
557                                         hp, 
558                                         conv_get_locale_charset_str_no_utf8(),
559                                         CS_INTERNAL);
560                                 if (utf == NULL || 
561                                     !g_utf8_validate(utf, -1, NULL)) {
562                                         g_free(utf);
563                                         utf = g_malloc(strlen(buf)*2+1);
564                                         conv_localetodisp(utf, 
565                                                 strlen(hp)*2+1, hp);
566                                 }
567                                 msginfo->date = utf;
568                         }
569                         break;
570                 case H_FROM:
571                         if (msginfo->from) break;
572                         msginfo->from = conv_unmime_header(hp, NULL, TRUE);
573                         msginfo->fromname = procheader_get_fromname(msginfo->from);
574                         remove_return(msginfo->from);
575                         remove_return(msginfo->fromname);
576                         break;
577                 case H_TO:
578                         tmp = conv_unmime_header(hp, NULL, TRUE);
579                         remove_return(tmp);
580                         if (msginfo->to) {
581                                 p = msginfo->to;
582                                 msginfo->to =
583                                         g_strconcat(p, ", ", tmp, NULL);
584                                 g_free(p);
585                         } else
586                                 msginfo->to = g_strdup(tmp);
587                         g_free(tmp);                                
588                         break;
589                 case H_CC:
590                         tmp = conv_unmime_header(hp, NULL, TRUE);
591                         remove_return(tmp);
592                         if (msginfo->cc) {
593                                 p = msginfo->cc;
594                                 msginfo->cc =
595                                         g_strconcat(p, ", ", tmp, NULL);
596                                 g_free(p);
597                         } else
598                                 msginfo->cc = g_strdup(tmp);
599                         g_free(tmp);                                
600                         break;
601                 case H_NEWSGROUPS:
602                         if (msginfo->newsgroups) {
603                                 p = msginfo->newsgroups;
604                                 msginfo->newsgroups =
605                                         g_strconcat(p, ",", hp, NULL);
606                                 g_free(p);
607                         } else
608                                 msginfo->newsgroups = g_strdup(hp);
609                         break;
610                 case H_SUBJECT:
611                         if (msginfo->subject) break;
612                         msginfo->subject = conv_unmime_header(hp, NULL, FALSE);
613                         unfold_line(msginfo->subject);
614                        break;
615                 case H_MSG_ID:
616                         if (msginfo->msgid) break;
617
618                         extract_parenthesis(hp, '<', '>');
619                         remove_space(hp);
620                         msginfo->msgid = g_strdup(hp);
621                         break;
622                 case H_REFERENCES:
623                         msginfo->references =
624                                 references_list_prepend(msginfo->references,
625                                                         hp);
626                         break;
627                 case H_IN_REPLY_TO:
628                         if (msginfo->inreplyto) break;
629
630                         eliminate_parenthesis(hp, '(', ')');
631                         if ((p = strrchr(hp, '<')) != NULL &&
632                             strchr(p + 1, '>') != NULL) {
633                                 extract_parenthesis(p, '<', '>');
634                                 remove_space(p);
635                                 if (*p != '\0')
636                                         msginfo->inreplyto = g_strdup(p);
637                         }
638                         break;
639                 case H_CONTENT_TYPE:
640                         if (!g_ascii_strncasecmp(hp, "multipart/", 10))
641                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_MULTIPART);
642                         break;
643                 case H_DISPOSITION_NOTIFICATION_TO:
644                         if (!msginfo->extradata)
645                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
646                         if (msginfo->extradata->dispositionnotificationto) break;
647                         msginfo->extradata->dispositionnotificationto = g_strdup(hp);
648                         break;
649                 case H_RETURN_RECEIPT_TO:
650                         if (!msginfo->extradata)
651                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
652                         if (msginfo->extradata->returnreceiptto) break;
653                         msginfo->extradata->returnreceiptto = g_strdup(hp);
654                         break;
655 /* partial download infos */                    
656                 case H_SC_PARTIALLY_RETRIEVED:
657                         if (!msginfo->extradata)
658                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
659                         if (msginfo->extradata->partial_recv) break;
660                         msginfo->extradata->partial_recv = g_strdup(hp);
661                         break;
662                 case H_SC_ACCOUNT_SERVER:
663                         if (!msginfo->extradata)
664                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
665                         if (msginfo->extradata->account_server) break;
666                         msginfo->extradata->account_server = g_strdup(hp);
667                         break;
668                 case H_SC_ACCOUNT_LOGIN:
669                         if (!msginfo->extradata)
670                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
671                         if (msginfo->extradata->account_login) break;
672                         msginfo->extradata->account_login = g_strdup(hp);
673                         break;
674                 case H_SC_MESSAGE_SIZE:
675                         if (msginfo->total_size) break;
676                         msginfo->total_size = atoi(hp);
677                         break;
678                 case H_SC_PLANNED_DOWNLOAD:
679                         msginfo->planned_download = atoi(hp);
680                         break;
681 /* end partial download infos */
682                 case H_FROM_SPACE:
683                         if (msginfo->fromspace) break;
684                         msginfo->fromspace = g_strdup(hp);
685                         remove_return(msginfo->fromspace);
686                         break;
687 /* list infos */
688                 case H_LIST_POST:
689                         if (!msginfo->extradata)
690                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
691                         if (msginfo->extradata->list_post) break;
692                         msginfo->extradata->list_post = g_strdup(hp);
693                         break;
694                 case H_LIST_SUBSCRIBE:
695                         if (!msginfo->extradata)
696                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
697                         if (msginfo->extradata->list_subscribe) break;
698                         msginfo->extradata->list_subscribe = g_strdup(hp);
699                         break;
700                 case H_LIST_UNSUBSCRIBE:
701                         if (!msginfo->extradata)
702                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
703                         if (msginfo->extradata->list_unsubscribe) break;
704                         msginfo->extradata->list_unsubscribe = g_strdup(hp);
705                         break;
706                 case H_LIST_HELP:
707                         if (!msginfo->extradata)
708                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
709                         if (msginfo->extradata->list_help) break;
710                         msginfo->extradata->list_help = g_strdup(hp);
711                         break;
712                 case H_LIST_ARCHIVE:
713                         if (!msginfo->extradata)
714                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
715                         if (msginfo->extradata->list_archive) break;
716                         msginfo->extradata->list_archive = g_strdup(hp);
717                         break;
718                 case H_LIST_OWNER:
719                         if (!msginfo->extradata)
720                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
721                         if (msginfo->extradata->list_owner) break;
722                         msginfo->extradata->list_owner = g_strdup(hp);
723                         break;
724                 case H_RESENT_FROM:
725                         if (!msginfo->extradata)
726                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
727                         if (msginfo->extradata->resent_from) break;
728                         msginfo->extradata->resent_from = g_strdup(hp);
729                         break;
730 /* end list infos */
731                 default:
732                         break;
733                 }
734                 /* to avoid performance penalty hooklist is invoked only for
735                    headers known to be able to generate avatars */
736                 if (hnum == H_FROM || hnum == H_X_FACE || hnum == H_FACE) {
737                         AvatarCaptureData *acd = g_new0(AvatarCaptureData, 1);
738                         /* no extra memory is wasted, hooks are expected to
739                            take care of copying members when needed */
740                         acd->msginfo = msginfo;
741                         acd->header  = hentry_full[hnum].name;
742                         acd->content = hp;
743                         hooks_invoke(AVATAR_HEADER_UPDATE_HOOKLIST, (gpointer)acd);
744                         g_free(acd);
745                 }
746         }
747
748         if (!msginfo->inreplyto && msginfo->references)
749                 msginfo->inreplyto =
750                         g_strdup((gchar *)msginfo->references->data);
751
752         return msginfo;
753 }
754
755 gchar *procheader_get_fromname(const gchar *str)
756 {
757         gchar *tmp, *name;
758
759         Xstrdup_a(tmp, str, return NULL);
760
761         if (*tmp == '\"') {
762                 extract_quote(tmp, '\"');
763                 g_strstrip(tmp);
764         } else if (strchr(tmp, '<')) {
765                 eliminate_parenthesis(tmp, '<', '>');
766                 g_strstrip(tmp);
767                 if (*tmp == '\0') {
768                         strcpy(tmp, str);
769                         extract_parenthesis(tmp, '<', '>');
770                         g_strstrip(tmp);
771                 }
772         } else if (strchr(tmp, '(')) {
773                 extract_parenthesis(tmp, '(', ')');
774                 g_strstrip(tmp);
775         }
776
777         if (*tmp == '\0')
778                 name = g_strdup(str);
779         else
780                 name = g_strdup(tmp);
781
782         return name;
783 }
784
785 static gint procheader_scan_date_string(const gchar *str,
786                                         gchar *weekday, gint *day,
787                                         gchar *month, gint *year,
788                                         gint *hh, gint *mm, gint *ss,
789                                         gchar *zone)
790 {
791         gint result;
792         gint month_n;
793         gint secfract;
794         gint zone1 = 0, zone2 = 0;
795         gchar offset_sign, zonestr[7];
796         gchar sep1;
797
798         if (str == NULL)
799                 return -1;
800
801         result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d %6s",
802                         weekday, day, month, year, hh, mm, ss, zone);
803         if (result == 8) return 0;
804
805         /* RFC2822 */
806         result = sscanf(str, "%3s,%d %9s %d %2d:%2d:%2d %6s",
807                         weekday, day, month, year, hh, mm, ss, zone);
808         if (result == 8) return 0;
809
810         result = sscanf(str, "%d %9s %d %2d:%2d:%2d %6s",
811                         day, month, year, hh, mm, ss, zone);
812         if (result == 7) return 0;
813
814         *zone = '\0';
815         result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d",
816                         weekday, day, month, year, hh, mm, ss);
817         if (result == 7) return 0;
818
819         result = sscanf(str, "%d %9s %d %2d:%2d:%2d",
820                         day, month, year, hh, mm, ss);
821         if (result == 6) return 0;
822
823         *ss = 0;
824         result = sscanf(str, "%10s %d %9s %d %2d:%2d %6s",
825                         weekday, day, month, year, hh, mm, zone);
826         if (result == 7) return 0;
827
828         result = sscanf(str, "%d %9s %d %2d:%2d %5s",
829                         day, month, year, hh, mm, zone);
830         if (result == 6) return 0;
831
832         *zone = '\0';
833         result = sscanf(str, "%10s %d %9s %d %2d:%2d",
834                         weekday, day, month, year, hh, mm);
835         if (result == 6) return 0;
836
837         result = sscanf(str, "%d %9s %d %2d:%2d",
838                         day, month, year, hh, mm);
839         if (result == 5) return 0;
840
841         *weekday = '\0';
842
843         /* RFC3339 subset, with fraction of second */
844         result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d.%1d%6s",
845                         year, &month_n, day, &sep1, hh, mm, ss, &secfract, zonestr);
846         debug_print("str |%s|, result %d\n", str, result);
847         if (result == 9
848                         && (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
849                 if (month_n >= 1 && month_n <= 12) {
850                         strncpy2(month, monthstr+((month_n-1)*3), 4);
851                         if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
852                                 strcat(zone, "+00:00");
853                         } else if (sscanf(zonestr, "%c%2d:%2d",
854                                                 &offset_sign, &zone1, &zone2) == 3) {
855                                 strcat(zone, zonestr);
856                         }
857                         return 0;
858                 }
859         }
860
861         /* RFC3339 subset, no fraction of second */
862         result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d%6s",
863                         year, &month_n, day, &sep1, hh, mm, ss, zonestr);
864         debug_print("str |%s|, result %d\n", str, result);
865         if (result == 8
866                         && (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
867                 if (month_n >= 1 && month_n <= 12) {
868                         strncpy2(month, monthstr+((month_n-1)*3), 4);
869                         if (offset_sign == 'z' || offset_sign == 'Z') {
870                                 strcat(zone, "+00:00");
871                         } else if (sscanf(zonestr, "%c%2d:%2d",
872                                                 &offset_sign, &zone1, &zone2) == 3) {
873                                 strcat(zone, zonestr);
874                         }
875                         return 0;
876                 }
877         }
878
879         *zone = '\0';
880
881         /* RFC3339 subset */
882         /* This particular "subset" is invalid, RFC requires the time offset */
883         result = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d",
884                         year, &month_n, day, hh, mm, ss);
885         if (result == 6) {
886                 if (1 <= month_n && month_n <= 12) {
887                         strncpy2(month, monthstr+((month_n-1)*3), 4);
888                         return 0;
889                 }
890         }
891
892         return -1;
893 }
894
895 /*
896  * Hiro, most UNIXen support this function:
897  * http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?getdate
898  */
899 gboolean procheader_date_parse_to_tm(const gchar *src, struct tm *t, char *zone)
900 {
901         gchar weekday[11];
902         gint day;
903         gchar month[10];
904         gint year;
905         gint hh, mm, ss;
906         GDateMonth dmonth;
907         gchar *p;
908
909         if (!t)
910                 return FALSE;
911         
912         memset(t, 0, sizeof *t);        
913
914         if (procheader_scan_date_string(src, weekday, &day, month, &year,
915                                         &hh, &mm, &ss, zone) < 0) {
916                 g_warning("Invalid date: %s\n", src);
917                 return FALSE;
918         }
919
920         /* Y2K compliant :) */
921         if (year < 100) {
922                 if (year < 70)
923                         year += 2000;
924                 else
925                         year += 1900;
926         }
927
928         month[3] = '\0';
929         if ((p = strstr(monthstr, month)) != NULL)
930                 dmonth = (gint)(p - monthstr) / 3 + 1;
931         else {
932                 g_warning("Invalid month: %s\n", month);
933                 dmonth = G_DATE_BAD_MONTH;
934         }
935
936         t->tm_sec = ss;
937         t->tm_min = mm;
938         t->tm_hour = hh;
939         t->tm_mday = day;
940         t->tm_mon = dmonth - 1;
941         t->tm_year = year - 1900;
942         t->tm_wday = 0;
943         t->tm_yday = 0;
944         t->tm_isdst = -1;
945
946         mktime(t);
947
948         return TRUE;
949 }
950
951 time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
952 {
953         gchar weekday[11];
954         gint day;
955         gchar month[10];
956         gint year;
957         gint hh, mm, ss;
958         gchar zone[7];
959         GDateMonth dmonth = G_DATE_BAD_MONTH;
960         struct tm t;
961         gchar *p;
962         time_t timer;
963         time_t tz_offset;
964
965         if (procheader_scan_date_string(src, weekday, &day, month, &year,
966                                         &hh, &mm, &ss, zone) < 0) {
967                 if (dest && len > 0)
968                         strncpy2(dest, src, len);
969                 return 0;
970         }
971
972         /* Y2K compliant :) */
973         if (year < 1000) {
974                 if (year < 50)
975                         year += 2000;
976                 else
977                         year += 1900;
978         }
979
980         month[3] = '\0';
981         for (p = monthstr; *p != '\0'; p += 3) {
982                 if (!g_ascii_strncasecmp(p, month, 3)) {
983                         dmonth = (gint)(p - monthstr) / 3 + 1;
984                         break;
985                 }
986         }
987
988         t.tm_sec = ss;
989         t.tm_min = mm;
990         t.tm_hour = hh;
991         t.tm_mday = day;
992         t.tm_mon = dmonth - 1;
993         t.tm_year = year - 1900;
994         t.tm_wday = 0;
995         t.tm_yday = 0;
996         t.tm_isdst = -1;
997
998         timer = mktime(&t);
999         tz_offset = remote_tzoffset_sec(zone);
1000         if (tz_offset != -1)
1001                 timer += tzoffset_sec(&timer) - tz_offset;
1002
1003         if (dest)
1004                 procheader_date_get_localtime(dest, len, timer);
1005
1006         return timer;
1007 }
1008
1009 void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
1010 {
1011         struct tm *lt;
1012         gchar *default_format = "%y/%m/%d(%a) %H:%M";
1013         gchar *str;
1014         const gchar *src_codeset, *dest_codeset;
1015         struct tm buf;
1016
1017         if (timer > 0)
1018                 lt = localtime_r(&timer, &buf);
1019         else {
1020                 time_t dummy = 1;
1021                 lt = localtime_r(&dummy, &buf);
1022         }
1023
1024         if (prefs_common.date_format)
1025                 fast_strftime(dest, len, prefs_common.date_format, lt);
1026         else
1027                 fast_strftime(dest, len, default_format, lt);
1028
1029         if (!g_utf8_validate(dest, -1, NULL)) {
1030                 src_codeset = conv_get_locale_charset_str_no_utf8();
1031                 dest_codeset = CS_UTF_8;
1032                 str = conv_codeset_strdup(dest, src_codeset, dest_codeset);
1033                 if (str) {
1034                         strncpy2(dest, str, len);
1035                         g_free(str);
1036                 }
1037         }
1038 }
1039
1040 /* Added by Mel Hadasht on 27 Aug 2001 */
1041 /* Get a header from msginfo */
1042 gint procheader_get_header_from_msginfo(MsgInfo *msginfo, gchar *buf, gint len, gchar *header)
1043 {
1044         gchar *file;
1045         FILE *fp;
1046         HeaderEntry hentry[]={ { NULL, NULL, TRUE  },
1047                                { NULL, NULL, FALSE } };
1048         gint val;
1049
1050         hentry[0].name = header;
1051        
1052         cm_return_val_if_fail(msginfo != NULL, -1);
1053         file = procmsg_get_message_file_path(msginfo);
1054         if ((fp = g_fopen(file, "rb")) == NULL) {
1055                FILE_OP_ERROR(file, "fopen");
1056                g_free(file);
1057                return -1;
1058         }
1059         val = procheader_get_one_field(buf,len, fp, hentry);
1060         if (fclose(fp) == EOF) {
1061                 FILE_OP_ERROR(file, "fclose");
1062                 claws_unlink(file);
1063                 g_free(file);
1064                 return -1;
1065         }
1066
1067         g_free(file);
1068         if (val == -1)
1069                 return -1;
1070
1071         return 0;
1072 }
1073
1074 HeaderEntry *procheader_entries_from_str(const gchar *str)
1075 {
1076         HeaderEntry *entries = NULL, *he;
1077         int numh = 0, i = 0;
1078         gchar **names = NULL;
1079         const gchar *s = str;
1080
1081         if (s == NULL) {
1082                 return NULL;
1083         }
1084         while (*s != '\0') {
1085                 if (*s == ' ') ++numh;
1086                 ++s;
1087         }
1088         if (numh == 0) {
1089                 return NULL;
1090         }
1091         entries = g_new0(HeaderEntry, numh + 1); /* room for last NULL */
1092         s = str;
1093         ++s; /* skip first space */
1094         names = g_strsplit(s, " ", numh);
1095         he = entries;
1096         while (names[i]) {
1097                 he->name = g_strdup_printf("%s:", names[i]);
1098                 he->body = NULL;
1099                 he->unfold = FALSE;
1100                 ++i, ++he;
1101         }
1102         he->name = NULL;
1103         g_strfreev(names);
1104         return entries;
1105 }
1106
1107 void procheader_entries_free (HeaderEntry *entries)
1108 {
1109         if (entries != NULL) {
1110                 HeaderEntry *he = entries;
1111                 while (he->name != NULL) {
1112                         g_free(he->name);
1113                         if (he->body != NULL)
1114                                 g_free(he->body);
1115                         ++he;                   
1116                 }
1117                 g_free(entries);
1118         }
1119 }
1120
1121 gboolean procheader_header_is_internal(const gchar *hdr_name)
1122 {
1123         const gchar *internal_hdrs[] = {
1124                 "AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", "CFG:",
1125                 "PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", "R:", "MAID:",
1126                 "SCF:", "RMID:", "FMID:", "NAID:",
1127                 "X-Claws-Account-Id:",
1128                 "X-Claws-Sign:",
1129                 "X-Claws-Encrypt:",
1130                 "X-Claws-Privacy-System:",
1131                 "X-Claws-Auto-Wrapping:",
1132                 "X-Claws-Auto-Indent:",
1133                 "X-Claws-End-Special-Headers:",
1134                 "X-Sylpheed-Account-Id:",
1135                 "X-Sylpheed-Sign:",
1136                 "X-Sylpheed-Encrypt:",
1137                 "X-Sylpheed-Privacy-System:",
1138                 "X-Sylpheed-End-Special-Headers:",
1139                  NULL
1140         };
1141         int i;
1142
1143         for (i = 0; internal_hdrs[i]; i++) {
1144                 if (!strcmp(hdr_name, internal_hdrs[i]))
1145                         return TRUE;
1146         }
1147         return FALSE;
1148 }