Fix bug #3055, "Claws segfaults when cancelling a sticky search
[claws.git] / src / procheader.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 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         struct stat 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          = 1,
377         H_TO            = 2,
378         H_CC            = 3,
379         H_NEWSGROUPS    = 4,
380         H_SUBJECT       = 5,
381         H_MSG_ID        = 6,
382         H_REFERENCES    = 7,
383         H_IN_REPLY_TO   = 8,
384         H_CONTENT_TYPE  = 9,
385         H_SEEN          = 10,
386         H_STATUS        = 11,
387         H_X_STATUS      = 12,
388         H_FROM_SPACE    = 13,
389         H_SC_PLANNED_DOWNLOAD = 14,
390         H_SC_MESSAGE_SIZE = 15,
391         H_FACE          = 16,
392         H_X_FACE        = 17,
393         H_DISPOSITION_NOTIFICATION_TO = 18,
394         H_RETURN_RECEIPT_TO = 19,
395         H_SC_PARTIALLY_RETRIEVED = 20,
396         H_SC_ACCOUNT_SERVER = 21,
397         H_SC_ACCOUNT_LOGIN = 22,
398         H_LIST_POST        = 23,
399         H_LIST_SUBSCRIBE   = 24,
400         H_LIST_UNSUBSCRIBE = 25,
401         H_LIST_HELP        = 26,
402         H_LIST_ARCHIVE     = 27,
403         H_LIST_OWNER       = 28,
404         H_RESENT_FROM      = 29,
405 };
406
407 static HeaderEntry hentry_full[] = {{"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                                    {"X-Status:",        NULL, FALSE},
420                                    {"From ",            NULL, FALSE},
421                                    {"SC-Marked-For-Download:", NULL, FALSE},
422                                    {"SC-Message-Size:", NULL, FALSE},
423                                    {"Face:",            NULL, FALSE},
424                                    {"X-Face:",          NULL, FALSE},
425                                    {"Disposition-Notification-To:", NULL, FALSE},
426                                    {"Return-Receipt-To:", NULL, FALSE},
427                                    {"SC-Partially-Retrieved:", NULL, FALSE},
428                                    {"SC-Account-Server:", NULL, FALSE},
429                                    {"SC-Account-Login:",NULL, FALSE},
430                                    {"List-Post:",       NULL, TRUE},
431                                    {"List-Subscribe:",  NULL, TRUE},
432                                    {"List-Unsubscribe:",NULL, TRUE},
433                                    {"List-Help:",       NULL, TRUE},
434                                    {"List-Archive:",    NULL, TRUE},
435                                    {"List-Owner:",      NULL, TRUE},
436                                    {"Resent-From:",     NULL, TRUE},
437                                    {NULL,               NULL, FALSE}};
438
439 static HeaderEntry hentry_short[] = {{"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                                     {"X-Status:",       NULL, FALSE},
452                                     {"From ",           NULL, FALSE},
453                                     {"SC-Marked-For-Download:", NULL, FALSE},
454                                     {"SC-Message-Size:",NULL, FALSE},
455                                     {NULL,              NULL, FALSE}};
456
457 static HeaderEntry* procheader_get_headernames(gboolean full)
458 {
459         return full ? hentry_full : hentry_short;
460 }
461
462 MsgInfo *procheader_parse_stream(FILE *fp, MsgFlags flags, gboolean full,
463                                  gboolean decrypted)
464 {
465         return parse_stream(fp, FALSE, flags, full, decrypted);
466 }
467
468 static gboolean avatar_from_some_face(gpointer source, gpointer userdata)
469 {
470         AvatarCaptureData *acd = (AvatarCaptureData *)source;
471         
472         if (*(acd->content) == '\0') /* won't be null, but may be empty */
473                 return FALSE;
474
475         if (!strcmp(acd->header, hentry_full[H_FACE].name)) {
476                 debug_print("avatar_from_some_face: found 'Face' header\n");
477                 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_FACE, acd->content);
478         }
479 #if HAVE_LIBCOMPFACE
480         else if (!strcmp(acd->header, hentry_full[H_X_FACE].name)) {
481                 debug_print("avatar_from_some_face: found 'X-Face' header\n");
482                 procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_XFACE, acd->content);
483         }
484 #endif
485         return FALSE;
486 }
487
488 static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
489                              gboolean full, gboolean decrypted)
490 {
491         MsgInfo *msginfo;
492         gchar buf[BUFFSIZE];
493         gchar *p, *tmp;
494         gchar *hp;
495         HeaderEntry *hentry;
496         gint hnum;
497         void *orig_data = data;
498         guint hook_id = -1;
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 (prefs_common.enable_avatars | AVATARS_ENABLE_CAPTURE) {
537                 hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_from_some_face, NULL);
538         }
539
540         while ((hnum = get_one_field(buf, sizeof(buf), data, hentry))
541                != -1) {
542                 hp = buf + strlen(hentry[hnum].name);
543                 while (*hp == ' ' || *hp == '\t') hp++;
544
545                 switch (hnum) {
546                 case H_DATE:
547                         if (msginfo->date) break;
548                         msginfo->date_t =
549                                 procheader_date_parse(NULL, hp, 0);
550                         if (g_utf8_validate(hp, -1, NULL)) {
551                                 msginfo->date = g_strdup(hp);
552                         } else {
553                                 gchar *utf = conv_codeset_strdup(
554                                         hp, 
555                                         conv_get_locale_charset_str_no_utf8(),
556                                         CS_INTERNAL);
557                                 if (utf == NULL || 
558                                     !g_utf8_validate(utf, -1, NULL)) {
559                                         g_free(utf);
560                                         utf = g_malloc(strlen(buf)*2+1);
561                                         conv_localetodisp(utf, 
562                                                 strlen(hp)*2+1, hp);
563                                 }
564                                 msginfo->date = utf;
565                         }
566                         break;
567                 case H_FROM:
568                         if (msginfo->from) break;
569                         msginfo->from = conv_unmime_header(hp, NULL, TRUE);
570                         msginfo->fromname = procheader_get_fromname(msginfo->from);
571                         remove_return(msginfo->from);
572                         remove_return(msginfo->fromname);
573                         break;
574                 case H_TO:
575                         tmp = conv_unmime_header(hp, NULL, TRUE);
576                         remove_return(tmp);
577                         if (msginfo->to) {
578                                 p = msginfo->to;
579                                 msginfo->to =
580                                         g_strconcat(p, ", ", tmp, NULL);
581                                 g_free(p);
582                         } else
583                                 msginfo->to = g_strdup(tmp);
584                         g_free(tmp);                                
585                         break;
586                 case H_CC:
587                         tmp = conv_unmime_header(hp, NULL, TRUE);
588                         remove_return(tmp);
589                         if (msginfo->cc) {
590                                 p = msginfo->cc;
591                                 msginfo->cc =
592                                         g_strconcat(p, ", ", tmp, NULL);
593                                 g_free(p);
594                         } else
595                                 msginfo->cc = g_strdup(tmp);
596                         g_free(tmp);                                
597                         break;
598                 case H_NEWSGROUPS:
599                         if (msginfo->newsgroups) {
600                                 p = msginfo->newsgroups;
601                                 msginfo->newsgroups =
602                                         g_strconcat(p, ",", hp, NULL);
603                                 g_free(p);
604                         } else
605                                 msginfo->newsgroups = g_strdup(hp);
606                         break;
607                 case H_SUBJECT:
608                         if (msginfo->subject) break;
609                         msginfo->subject = conv_unmime_header(hp, NULL, FALSE);
610                         unfold_line(msginfo->subject);
611                        break;
612                 case H_MSG_ID:
613                         if (msginfo->msgid) break;
614
615                         extract_parenthesis(hp, '<', '>');
616                         remove_space(hp);
617                         msginfo->msgid = g_strdup(hp);
618                         break;
619                 case H_REFERENCES:
620                         msginfo->references =
621                                 references_list_prepend(msginfo->references,
622                                                         hp);
623                         break;
624                 case H_IN_REPLY_TO:
625                         if (msginfo->inreplyto) break;
626
627                         eliminate_parenthesis(hp, '(', ')');
628                         if ((p = strrchr(hp, '<')) != NULL &&
629                             strchr(p + 1, '>') != NULL) {
630                                 extract_parenthesis(p, '<', '>');
631                                 remove_space(p);
632                                 if (*p != '\0')
633                                         msginfo->inreplyto = g_strdup(p);
634                         }
635                         break;
636                 case H_CONTENT_TYPE:
637                         if (!g_ascii_strncasecmp(hp, "multipart/", 10))
638                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_MULTIPART);
639                         break;
640 #ifdef ALLOW_HEADER_HINT                        
641                 case H_SEEN:
642                         /* mnews Seen header */
643                         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_NEW|MSG_UNREAD);
644                         break;
645 #endif                  
646                 case H_DISPOSITION_NOTIFICATION_TO:
647                         if (!msginfo->extradata)
648                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
649                         if (msginfo->extradata->dispositionnotificationto) break;
650                         msginfo->extradata->dispositionnotificationto = g_strdup(hp);
651                         break;
652                 case H_RETURN_RECEIPT_TO:
653                         if (!msginfo->extradata)
654                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
655                         if (msginfo->extradata->returnreceiptto) break;
656                         msginfo->extradata->returnreceiptto = g_strdup(hp);
657                         break;
658 /* partial download infos */                    
659                 case H_SC_PARTIALLY_RETRIEVED:
660                         if (!msginfo->extradata)
661                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
662                         if (msginfo->extradata->partial_recv) break;
663                         msginfo->extradata->partial_recv = g_strdup(hp);
664                         break;
665                 case H_SC_ACCOUNT_SERVER:
666                         if (!msginfo->extradata)
667                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
668                         if (msginfo->extradata->account_server) break;
669                         msginfo->extradata->account_server = g_strdup(hp);
670                         break;
671                 case H_SC_ACCOUNT_LOGIN:
672                         if (!msginfo->extradata)
673                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
674                         if (msginfo->extradata->account_login) break;
675                         msginfo->extradata->account_login = g_strdup(hp);
676                         break;
677                 case H_SC_MESSAGE_SIZE:
678                         if (msginfo->total_size) break;
679                         msginfo->total_size = atoi(hp);
680                         break;
681                 case H_SC_PLANNED_DOWNLOAD:
682                         msginfo->planned_download = atoi(hp);
683                         break;
684 /* end partial download infos */
685 #ifdef ALLOW_HEADER_HINT                        
686                 case H_STATUS:
687                         if (strchr(hp, 'R') != NULL)
688                                 MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_UNREAD);
689                         if (strchr(hp, 'O') != NULL)
690                                 MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_NEW);
691                         if (strchr(hp, 'U') != NULL)
692                                 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_UNREAD);
693                         break;
694                 case H_X_STATUS:
695                         if (strchr(hp, 'D') != NULL)
696                                 MSG_SET_PERM_FLAGS(msginfo->flags,
697                                               MSG_REALLY_DELETED);
698                         if (strchr(hp, 'F') != NULL)
699                                 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_MARKED);
700                         if (strchr(hp, 'd') != NULL)
701                                 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_DELETED);
702                         if (strchr(hp, 'r') != NULL)
703                                 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
704                         if (strchr(hp, 'f') != NULL)
705                                 MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
706                         break;
707 #endif                  
708                 case H_FROM_SPACE:
709                         if (msginfo->fromspace) break;
710                         msginfo->fromspace = g_strdup(hp);
711                         remove_return(msginfo->fromspace);
712                         break;
713 /* list infos */
714                 case H_LIST_POST:
715                         if (!msginfo->extradata)
716                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
717                         if (msginfo->extradata->list_post) break;
718                         msginfo->extradata->list_post = g_strdup(hp);
719                         break;
720                 case H_LIST_SUBSCRIBE:
721                         if (!msginfo->extradata)
722                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
723                         if (msginfo->extradata->list_subscribe) break;
724                         msginfo->extradata->list_subscribe = g_strdup(hp);
725                         break;
726                 case H_LIST_UNSUBSCRIBE:
727                         if (!msginfo->extradata)
728                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
729                         if (msginfo->extradata->list_unsubscribe) break;
730                         msginfo->extradata->list_unsubscribe = g_strdup(hp);
731                         break;
732                 case H_LIST_HELP:
733                         if (!msginfo->extradata)
734                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
735                         if (msginfo->extradata->list_help) break;
736                         msginfo->extradata->list_help = g_strdup(hp);
737                         break;
738                 case H_LIST_ARCHIVE:
739                         if (!msginfo->extradata)
740                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
741                         if (msginfo->extradata->list_archive) break;
742                         msginfo->extradata->list_archive = g_strdup(hp);
743                         break;
744                 case H_LIST_OWNER:
745                         if (!msginfo->extradata)
746                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
747                         if (msginfo->extradata->list_owner) break;
748                         msginfo->extradata->list_owner = g_strdup(hp);
749                         break;
750                 case H_RESENT_FROM:
751                         if (!msginfo->extradata)
752                                 msginfo->extradata = g_new0(MsgInfoExtraData, 1);
753                         if (msginfo->extradata->resent_from) break;
754                         msginfo->extradata->resent_from = g_strdup(hp);
755                         break;
756 /* end list infos */
757                 default:
758                         break;
759                 }
760                 /* to avoid performance penalty hooklist is invoked only for
761                    headers known to be able to generate avatars */
762                 if (hnum == H_FROM || hnum == H_X_FACE || hnum == H_FACE) {
763                         AvatarCaptureData *acd = g_new0(AvatarCaptureData, 1);
764                         /* no extra memory is wasted, hooks are expected to
765                            take care of copying members when needed */
766                         acd->msginfo = msginfo;
767                         acd->header  = hentry_full[hnum].name;
768                         acd->content = hp;
769                         hooks_invoke(AVATAR_HEADER_UPDATE_HOOKLIST, (gpointer)acd);
770                         g_free(acd);
771                 }
772         }
773
774         if (!msginfo->inreplyto && msginfo->references)
775                 msginfo->inreplyto =
776                         g_strdup((gchar *)msginfo->references->data);
777
778         if (hook_id != -1) {
779                 hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST, hook_id);
780         }
781
782         return msginfo;
783 }
784
785 gchar *procheader_get_fromname(const gchar *str)
786 {
787         gchar *tmp, *name;
788
789         Xstrdup_a(tmp, str, return NULL);
790
791         if (*tmp == '\"') {
792                 extract_quote(tmp, '\"');
793                 g_strstrip(tmp);
794         } else if (strchr(tmp, '<')) {
795                 eliminate_parenthesis(tmp, '<', '>');
796                 g_strstrip(tmp);
797                 if (*tmp == '\0') {
798                         strcpy(tmp, str);
799                         extract_parenthesis(tmp, '<', '>');
800                         g_strstrip(tmp);
801                 }
802         } else if (strchr(tmp, '(')) {
803                 extract_parenthesis(tmp, '(', ')');
804                 g_strstrip(tmp);
805         }
806
807         if (*tmp == '\0')
808                 name = g_strdup(str);
809         else
810                 name = g_strdup(tmp);
811
812         return name;
813 }
814
815 static gint procheader_scan_date_string(const gchar *str,
816                                         gchar *weekday, gint *day,
817                                         gchar *month, gint *year,
818                                         gint *hh, gint *mm, gint *ss,
819                                         gchar *zone)
820 {
821         gint result;
822         gint month_n;
823         gchar zone1[3];
824         gchar zone2[3];
825
826         if (str == NULL)
827                 return -1;
828
829         result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d %5s",
830                         weekday, day, month, year, hh, mm, ss, zone);
831         if (result == 8) return 0;
832
833         /* RFC2822 */
834         result = sscanf(str, "%3s,%d %9s %d %2d:%2d:%2d %5s",
835                         weekday, day, month, year, hh, mm, ss, zone);
836         if (result == 8) return 0;
837
838         result = sscanf(str, "%d %9s %d %2d:%2d:%2d %5s",
839                         day, month, year, hh, mm, ss, zone);
840         if (result == 7) return 0;
841
842         *zone = '\0';
843         result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d",
844                         weekday, day, month, year, hh, mm, ss);
845         if (result == 7) return 0;
846
847         result = sscanf(str, "%d %9s %d %2d:%2d:%2d",
848                         day, month, year, hh, mm, ss);
849         if (result == 6) return 0;
850
851         *ss = 0;
852         result = sscanf(str, "%10s %d %9s %d %2d:%2d %5s",
853                         weekday, day, month, year, hh, mm, zone);
854         if (result == 7) return 0;
855
856         result = sscanf(str, "%d %9s %d %2d:%2d %5s",
857                         day, month, year, hh, mm, zone);
858         if (result == 6) return 0;
859
860         *zone = '\0';
861         result = sscanf(str, "%10s %d %9s %d %2d:%2d",
862                         weekday, day, month, year, hh, mm);
863         if (result == 6) return 0;
864
865         result = sscanf(str, "%d %9s %d %2d:%2d",
866                         day, month, year, hh, mm);
867         if (result == 5) return 0;
868
869         /* RFC3339 subset */
870         *weekday = '\0';
871         result = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d+%2s:%2s",
872                         year, &month_n, day, hh, mm, ss, zone1, zone2);
873         if (result == 8) {
874                 if (1 <= month_n && month_n <= 12) {
875                         strncpy2(month, monthstr+((month_n-1)*3), 4);
876                         *zone = '+';
877                         strncpy2(zone+1, zone1, 3);
878                         strncpy2(zone+3, zone2, 3);
879                         return 0;
880                 }
881         }
882
883         /* RFC3339 subset */
884         *zone = '\0';
885         *weekday = '\0';
886         result = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d",
887                         year, &month_n, day, hh, mm, ss);
888         if (result == 6) {
889                 if (1 <= month_n && month_n <= 12) {
890                         strncpy2(month, monthstr+((month_n-1)*3), 4);
891                         return 0;
892                 }
893         }
894
895         return -1;
896 }
897
898 /*
899  * Hiro, most UNIXen support this function:
900  * http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?getdate
901  */
902 gboolean procheader_date_parse_to_tm(const gchar *src, struct tm *t, char *zone)
903 {
904         gchar weekday[11];
905         gint day;
906         gchar month[10];
907         gint year;
908         gint hh, mm, ss;
909         GDateMonth dmonth;
910         gchar *p;
911
912         if (!t)
913                 return FALSE;
914         
915         memset(t, 0, sizeof *t);        
916
917         if (procheader_scan_date_string(src, weekday, &day, month, &year,
918                                         &hh, &mm, &ss, zone) < 0) {
919                 g_warning("Invalid date: %s\n", src);
920                 return FALSE;
921         }
922
923         /* Y2K compliant :) */
924         if (year < 100) {
925                 if (year < 70)
926                         year += 2000;
927                 else
928                         year += 1900;
929         }
930
931         month[3] = '\0';
932         if ((p = strstr(monthstr, month)) != NULL)
933                 dmonth = (gint)(p - monthstr) / 3 + 1;
934         else {
935                 g_warning("Invalid month: %s\n", month);
936                 dmonth = G_DATE_BAD_MONTH;
937         }
938
939         t->tm_sec = ss;
940         t->tm_min = mm;
941         t->tm_hour = hh;
942         t->tm_mday = day;
943         t->tm_mon = dmonth - 1;
944         t->tm_year = year - 1900;
945         t->tm_wday = 0;
946         t->tm_yday = 0;
947         t->tm_isdst = -1;
948
949         mktime(t);
950
951         return TRUE;
952 }
953
954 time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
955 {
956         gchar weekday[11];
957         gint day;
958         gchar month[10];
959         gint year;
960         gint hh, mm, ss;
961         gchar zone[6];
962         GDateMonth dmonth = G_DATE_BAD_MONTH;
963         struct tm t;
964         gchar *p;
965         time_t timer;
966         time_t tz_offset;
967
968         if (procheader_scan_date_string(src, weekday, &day, month, &year,
969                                         &hh, &mm, &ss, zone) < 0) {
970                 if (dest && len > 0)
971                         strncpy2(dest, src, len);
972                 return 0;
973         }
974
975         /* Y2K compliant :) */
976         if (year < 1000) {
977                 if (year < 50)
978                         year += 2000;
979                 else
980                         year += 1900;
981         }
982
983         month[3] = '\0';
984         for (p = monthstr; *p != '\0'; p += 3) {
985                 if (!g_ascii_strncasecmp(p, month, 3)) {
986                         dmonth = (gint)(p - monthstr) / 3 + 1;
987                         break;
988                 }
989         }
990
991         t.tm_sec = ss;
992         t.tm_min = mm;
993         t.tm_hour = hh;
994         t.tm_mday = day;
995         t.tm_mon = dmonth - 1;
996         t.tm_year = year - 1900;
997         t.tm_wday = 0;
998         t.tm_yday = 0;
999         t.tm_isdst = -1;
1000
1001         timer = mktime(&t);
1002         tz_offset = remote_tzoffset_sec(zone);
1003         if (tz_offset != -1)
1004                 timer += tzoffset_sec(&timer) - tz_offset;
1005
1006         if (dest)
1007                 procheader_date_get_localtime(dest, len, timer);
1008
1009         return timer;
1010 }
1011
1012 void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
1013 {
1014         struct tm *lt;
1015         gchar *default_format = "%y/%m/%d(%a) %H:%M";
1016         gchar *str;
1017         const gchar *src_codeset, *dest_codeset;
1018         struct tm buf;
1019
1020         if (timer > 0)
1021                 lt = localtime_r(&timer, &buf);
1022         else {
1023                 time_t dummy = 1;
1024                 lt = localtime_r(&dummy, &buf);
1025         }
1026
1027         if (prefs_common.date_format)
1028                 fast_strftime(dest, len, prefs_common.date_format, lt);
1029         else
1030                 fast_strftime(dest, len, default_format, lt);
1031
1032         if (!g_utf8_validate(dest, -1, NULL)) {
1033                 src_codeset = conv_get_locale_charset_str_no_utf8();
1034                 dest_codeset = CS_UTF_8;
1035                 str = conv_codeset_strdup(dest, src_codeset, dest_codeset);
1036                 if (str) {
1037                         strncpy2(dest, str, len);
1038                         g_free(str);
1039                 }
1040         }
1041 }
1042
1043 /* Added by Mel Hadasht on 27 Aug 2001 */
1044 /* Get a header from msginfo */
1045 gint procheader_get_header_from_msginfo(MsgInfo *msginfo, gchar *buf, gint len, gchar *header)
1046 {
1047         gchar *file;
1048         FILE *fp;
1049         HeaderEntry hentry[]={ { NULL, NULL, TRUE  },
1050                                { NULL, NULL, FALSE } };
1051         gint val;
1052
1053         hentry[0].name = header;
1054        
1055         cm_return_val_if_fail(msginfo != NULL, -1);
1056         file = procmsg_get_message_file_path(msginfo);
1057         if ((fp = g_fopen(file, "rb")) == NULL) {
1058                FILE_OP_ERROR(file, "fopen");
1059                g_free(file);
1060                return -1;
1061         }
1062         val = procheader_get_one_field(buf,len, fp, hentry);
1063         if (fclose(fp) == EOF) {
1064                 FILE_OP_ERROR(file, "fclose");
1065                 claws_unlink(file);
1066                 g_free(file);
1067                 return -1;
1068         }
1069
1070         g_free(file);
1071         if (val == -1)
1072                 return -1;
1073
1074         return 0;
1075 }
1076
1077 HeaderEntry *procheader_entries_from_str(const gchar *str)
1078 {
1079         HeaderEntry *entries = NULL, *he;
1080         int numh = 0, i = 0;
1081         gchar **names = NULL;
1082         const gchar *s = str;
1083
1084         if (s == NULL) {
1085                 return NULL;
1086         }
1087         while (*s != '\0') {
1088                 if (*s == ' ') ++numh;
1089                 ++s;
1090         }
1091         if (numh == 0) {
1092                 return NULL;
1093         }
1094         entries = g_new0(HeaderEntry, numh + 1); /* room for last NULL */
1095         s = str;
1096         ++s; /* skip first space */
1097         names = g_strsplit(s, " ", numh);
1098         he = entries;
1099         while (names[i]) {
1100                 he->name = g_strdup_printf("%s:", names[i]);
1101                 he->body = NULL;
1102                 he->unfold = FALSE;
1103                 ++i, ++he;
1104         }
1105         he->name = NULL;
1106         g_strfreev(names);
1107         return entries;
1108 }
1109
1110 void procheader_entries_free (HeaderEntry *entries)
1111 {
1112         if (entries != NULL) {
1113                 HeaderEntry *he = entries;
1114                 while (he->name != NULL) {
1115                         g_free(he->name);
1116                         if (he->body != NULL)
1117                                 g_free(he->body);
1118                         ++he;                   
1119                 }
1120                 g_free(entries);
1121         }
1122 }
1123