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