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