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