sync with sylpheed 0.4.66cvs3-5
[claws.git] / src / procheader.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 Hiroyuki Yamamoto
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 2 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, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <glib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <time.h>
29
30 #include "intl.h"
31 #include "procheader.h"
32 #include "procmsg.h"
33 #include "codeconv.h"
34 #include "prefs_common.h"
35 #include "utils.h"
36
37 #define BUFFSIZE        8192
38
39 gint procheader_get_one_field(gchar *buf, gint len, FILE *fp,
40                               HeaderEntry hentry[])
41 {
42         gint nexthead;
43         gint hnum = 0;
44         HeaderEntry *hp = NULL;
45
46         if (hentry != NULL) {
47                 /* skip non-required headers */
48                 do {
49                         do {
50                                 if (fgets(buf, len, fp) == NULL)
51                                         return -1;
52                                 if (buf[0] == '\r' || buf[0] == '\n')
53                                         return -1;
54                         } while (buf[0] == ' ' || buf[0] == '\t');
55
56                         for (hp = hentry, hnum = 0; hp->name != NULL;
57                              hp++, hnum++) {
58                                 if (!strncasecmp(hp->name, buf,
59                                                  strlen(hp->name)))
60                                         break;
61                         }
62                 } while (hp->name == NULL);
63         } else {
64                 if (fgets(buf, len, fp) == NULL) return -1;
65                 if (buf[0] == '\r' || buf[0] == '\n') return -1;
66         }
67
68         /* unfold the specified folded line */
69         if (hp && hp->unfold) {
70                 gboolean folded = FALSE;
71                 gchar *bufp = buf + strlen(buf);
72
73                 while (1) {
74                         nexthead = fgetc(fp);
75
76                         /* folded */
77                         if (nexthead == ' ' || nexthead == '\t')
78                                 folded = TRUE;
79                         else if (nexthead == EOF)
80                                 break;
81                         else if (folded == TRUE) {
82                                 /* concatenate next line */
83                                 if ((len - (bufp - buf)) <= 2) break;
84
85                                 /* replace return code on the tail end
86                                    with space */
87                                 *(bufp - 1) = ' ';
88                                 *bufp++ = nexthead;
89                                 *bufp = '\0';
90                                 if (nexthead == '\r' || nexthead == '\n') {
91                                         folded = FALSE;
92                                         continue;
93                                 }
94                                 if (fgets(bufp, len - (bufp - buf), fp)
95                                     == NULL) break;
96                                 bufp += strlen(bufp);
97
98                                 folded = FALSE;
99                         } else {
100                                 ungetc(nexthead, fp);
101                                 break;
102                         }
103                 }
104
105                 /* remove trailing return code */
106                 strretchomp(buf);
107
108                 return hnum;
109         }
110
111         while (1) {
112                 nexthead = fgetc(fp);
113                 if (nexthead == ' ' || nexthead == '\t') {
114                         size_t buflen = strlen(buf);
115
116                         /* concatenate next line */
117                         if ((len - buflen) > 2) {
118                                 gchar *p = buf + buflen;
119
120                                 *p++ = nexthead;
121                                 *p = '\0';
122                                 buflen++;
123                                 if (fgets(p, len - buflen, fp) == NULL)
124                                         break;
125                         } else
126                                 break;
127                 } else {
128                         if (nexthead != EOF)
129                                 ungetc(nexthead, fp);
130                         break;
131                 }
132         }
133
134         /* remove trailing return code */
135         strretchomp(buf);
136
137         return hnum;
138 }
139
140 gchar *procheader_get_unfolded_line(gchar *buf, gint len, FILE *fp)
141 {
142         gboolean folded = FALSE;
143         gint nexthead;
144         gchar *bufp;
145
146         if (fgets(buf, len, fp) == NULL) return NULL;
147         if (buf[0] == '\r' || buf[0] == '\n') return NULL;
148         bufp = buf + strlen(buf);
149
150         while (1) {
151                 nexthead = fgetc(fp);
152
153                 /* folded */
154                 if (nexthead == ' ' || nexthead == '\t')
155                         folded = TRUE;
156                 else if (nexthead == EOF)
157                         break;
158                 else if (folded == TRUE) {
159                         /* concatenate next line */
160                         if ((len - (bufp - buf)) <= 2) break;
161
162                         /* replace return code on the tail end
163                            with space */
164                         *(bufp - 1) = ' ';
165                         *bufp++ = nexthead;
166                         *bufp = '\0';
167                         if (nexthead == '\r' || nexthead == '\n') {
168                                 folded = FALSE;
169                                 continue;
170                         }
171                         if (fgets(bufp, len - (bufp - buf), fp)
172                             == NULL) break;
173                         bufp += strlen(bufp);
174
175                         folded = FALSE;
176                 } else {
177                         ungetc(nexthead, fp);
178                         break;
179                 }
180         }
181
182         /* remove trailing return code */
183         strretchomp(buf);
184
185         return buf;
186 }
187
188 GSList *procheader_get_header_list_from_file(const gchar *file)
189 {
190         FILE *fp;
191         GSList *hlist;
192
193         if ((fp = fopen(file, "r")) == NULL) {
194                 FILE_OP_ERROR(file, "fopen");
195                 return NULL;
196         }
197
198         hlist = procheader_get_header_list(fp);
199
200         fclose(fp);
201         return hlist;
202 }
203
204 GSList *procheader_get_header_list(FILE *fp)
205 {
206         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
207         gchar *p;
208         GSList *hlist = NULL;
209         Header *header;
210
211         g_return_val_if_fail(fp != NULL, NULL);
212
213         while (procheader_get_unfolded_line(buf, sizeof(buf), fp) != NULL) {
214                 if (*buf == ':') continue;
215                 for (p = buf; *p && *p != ' '; p++) {
216                         if (*p == ':') {
217                                 header = g_new(Header, 1);
218                                 header->name = g_strndup(buf, p - buf);
219                                 p++;
220                                 while (*p == ' ' || *p == '\t') p++;
221                                 conv_unmime_header(tmp, sizeof(tmp), p, NULL);
222                                 header->body = g_strdup(tmp);
223
224                                 hlist = g_slist_append(hlist, header);
225                                 break;
226                         }
227                 }
228         }
229
230         return hlist;
231 }
232
233 GPtrArray *procheader_get_header_array(FILE *fp)
234 {
235         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
236         gchar *p;
237         GPtrArray *headers;
238         Header *header;
239
240         g_return_val_if_fail(fp != NULL, NULL);
241
242         headers = g_ptr_array_new();
243
244         while (procheader_get_unfolded_line(buf, sizeof(buf), fp) != NULL) {
245                 if (*buf == ':') continue;
246                 for (p = buf; *p && *p != ' '; p++) {
247                         if (*p == ':') {
248                                 header = g_new(Header, 1);
249                                 header->name = g_strndup(buf, p - buf);
250                                 p++;
251                                 while (*p == ' ' || *p == '\t') p++;
252                                 conv_unmime_header(tmp, sizeof(tmp), p, NULL);
253                                 header->body = g_strdup(tmp);
254
255                                 g_ptr_array_add(headers, header);
256                                 break;
257                         }
258                 }
259         }
260
261         return headers;
262 }
263
264 GPtrArray *procheader_get_header_array_asis(FILE *fp)
265 {
266         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
267         gchar *p;
268         GPtrArray *headers;
269         Header *header;
270
271         g_return_val_if_fail(fp != NULL, NULL);
272
273         headers = g_ptr_array_new();
274
275         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1) {
276                 if (*buf == ':') continue;
277                 for (p = buf; *p && *p != ' '; p++) {
278                         if (*p == ':') {
279                                 header = g_new(Header, 1);
280                                 header->name = g_strndup(buf, p - buf);
281                                 p++;
282                                 conv_unmime_header(tmp, sizeof(tmp), p, NULL);
283                                 header->body = g_strdup(tmp);
284
285                                 g_ptr_array_add(headers, header);
286                                 break;
287                         }
288                 }
289         }
290
291         return headers;
292 }
293
294 void procheader_header_list_destroy(GSList *hlist)
295 {
296         Header *header;
297
298         while (hlist != NULL) {
299                 header = hlist->data;
300                 procheader_header_free(header);
301                 hlist = g_slist_remove(hlist, header);
302         }
303 }
304
305 void procheader_header_array_destroy(GPtrArray *harray)
306 {
307         gint i;
308         Header *header;
309
310         for (i = 0; i < harray->len; i++) {
311                 header = g_ptr_array_index(harray, i);
312                 procheader_header_free(header);
313         }
314
315         g_ptr_array_free(harray, TRUE);
316 }
317
318 void procheader_header_free(Header *header)
319 {
320         if (!header) return;
321
322         g_free(header->name);
323         g_free(header->body);
324         g_free(header);
325 }
326
327 /*
328   tests whether two headers' names are equal
329   remove the trailing ':' or ' ' before comparing
330 */
331
332 gboolean procheader_headername_equal(char * hdr1, char * hdr2)
333 {
334         int len1;
335         int len2;
336
337         len1 = strlen(hdr1);
338         len2 = strlen(hdr2);
339         if ((hdr1[len1 - 1] == ':') || (hdr1[len1 - 1] == ' '))
340                 len1--;
341         if ((hdr2[len2 - 1] == ':') || (hdr2[len2 - 1] == ' '))
342                 len2--;
343         if (len1 != len2)
344                 return 0;
345         return (strncasecmp(hdr1, hdr2, len1) == 0);
346 }
347
348 /*
349   parse headers, for example :
350   From: dinh@enseirb.fr becomes :
351   header->name = "From:"
352   header->body = "dinh@enseirb.fr"
353  */
354
355 Header * procheader_parse_header(gchar * buf)
356 {
357         gchar tmp[BUFFSIZE];
358         gchar *p = buf;
359         Header * header;
360
361         if ((*buf == ':') || (*buf == ' '))
362                 return NULL;
363
364         for (p = buf; *p ; p++) {
365                 if ((*p == ':') || (*p == ' ')) {
366                         header = g_new(Header, 1);
367                         header->name = g_strndup(buf, p - buf + 1);
368                         p++;
369                         while (*p == ' ' || *p == '\t') p++;
370                         conv_unmime_header(tmp, sizeof(tmp), p, NULL);
371                         header->body = g_strdup(tmp);
372                         return header;
373                 }
374         }
375         return NULL;
376 }
377
378 void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
379 {
380         gchar buf[BUFFSIZE];
381         HeaderEntry *hp;
382         gint hnum;
383         gchar *p;
384
385         if (hentry == NULL) return;
386
387         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
388                != -1) {
389                 hp = hentry + hnum;
390
391                 p = buf + strlen(hp->name);
392                 while (*p == ' ' || *p == '\t') p++;
393
394                 if (hp->body == NULL)
395                         hp->body = g_strdup(p);
396                 else if (!strcasecmp(hp->name, "To:") ||
397                          !strcasecmp(hp->name, "Cc:")) {
398                         gchar *tp = hp->body;
399                         hp->body = g_strconcat(tp, ", ", p, NULL);
400                         g_free(tp);
401                 }
402         }
403 }
404
405 enum
406 {
407         H_DATE          = 0,
408         H_FROM          = 1,
409         H_TO            = 2,
410         H_CC            = 3,
411         H_NEWSGROUPS    = 4,
412         H_SUBJECT       = 5,
413         H_MSG_ID        = 6,
414         H_REFERENCES    = 7,
415         H_IN_REPLY_TO   = 8,
416         H_CONTENT_TYPE  = 9,
417         H_SEEN          = 10,
418         H_X_FACE        = 11,
419         H_DISPOSITION_NOTIFICATION_TO = 12
420 };
421
422 MsgInfo *procheader_parse(const gchar *file, MsgFlags flags, gboolean full)
423 {
424         static HeaderEntry hentry_full[] = {{"Date:",           NULL, FALSE},
425                                            {"From:",            NULL, TRUE},
426                                            {"To:",              NULL, TRUE},
427                                            {"Cc:",              NULL, TRUE},
428                                            {"Newsgroups:",      NULL, TRUE},
429                                            {"Subject:",         NULL, TRUE},
430                                            {"Message-Id:",      NULL, FALSE},
431                                            {"References:",      NULL, FALSE},
432                                            {"In-Reply-To:",     NULL, FALSE},
433                                            {"Content-Type:",    NULL, FALSE},
434                                            {"Seen:",            NULL, FALSE},
435                                            {"X-Face:",          NULL, FALSE},
436                                            {"Disposition-Notification-To:",NULL, FALSE},
437                                            {NULL,               NULL, FALSE}};
438
439         static HeaderEntry hentry_short[] = {{"Date:",          NULL, FALSE},
440                                             {"From:",           NULL, TRUE},
441                                             {"To:",             NULL, TRUE},
442                                             {"Cc:",             NULL, TRUE},
443                                             {"Newsgroups:",     NULL, TRUE},
444                                             {"Subject:",        NULL, TRUE},
445                                             {"Message-Id:",     NULL, FALSE},
446                                             {"References:",     NULL, FALSE},
447                                             {"In-Reply-To:",    NULL, FALSE},
448                                             {"Content-Type:",   NULL, FALSE},
449                                             {"Seen:",           NULL, FALSE},
450                                             {NULL,              NULL, FALSE}};
451
452         FILE *fp;
453         MsgInfo *msginfo;
454         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
455         gchar *reference = NULL;
456         gchar *p;
457         gchar *hp;
458         HeaderEntry *hentry;
459         gint hnum;
460
461         hentry = full ? hentry_full : hentry_short;
462
463         if ((fp = fopen(file, "r")) == NULL) {
464                 FILE_OP_ERROR(file, "fopen");
465                 return NULL;
466         }
467         if (MSG_IS_QUEUED(flags)) {
468                 while (fgets(buf, sizeof(buf), fp) != NULL)
469                         if (buf[0] == '\r' || buf[0] == '\n') break;
470         }
471
472         msginfo = g_new0(MsgInfo, 1);
473         msginfo->flags = flags != 0 ? flags : MSG_NEW|MSG_UNREAD;
474         msginfo->inreplyto = NULL;
475
476         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
477                != -1) {
478                 hp = buf + strlen(hentry[hnum].name);
479                 while (*hp == ' ' || *hp == '\t') hp++;
480
481                 switch (hnum) {
482                 case H_DATE:
483                         if (msginfo->date) break;
484                         msginfo->date_t =
485                                 procheader_date_parse(NULL, hp, 0);
486                         msginfo->date = g_strdup(hp);
487                         break;
488                 case H_FROM:
489                         if (msginfo->from) break;
490                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
491                         msginfo->from = g_strdup(tmp);
492                         msginfo->fromname = procheader_get_fromname(tmp);
493                         break;
494                 case H_TO:
495                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
496                         if (msginfo->to) {
497                                 p = msginfo->to;
498                                 msginfo->to =
499                                         g_strconcat(p, ", ", tmp, NULL);
500                                 g_free(p);
501                         } else
502                                 msginfo->to = g_strdup(tmp);
503                         break;
504                 case H_CC:
505                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
506                         if (msginfo->cc) {
507                                 p = msginfo->cc;
508                                 msginfo->cc =
509                                         g_strconcat(p, ", ", tmp, NULL);
510                                 g_free(p);
511                         } else
512                                 msginfo->cc = g_strdup(tmp);
513                         break;
514                 case H_NEWSGROUPS:
515                         if (msginfo->newsgroups) {
516                                 p = msginfo->newsgroups;
517                                 msginfo->newsgroups =
518                                         g_strconcat(p, ",", hp, NULL);
519                                 g_free(p);
520                         } else
521                                 msginfo->newsgroups = g_strdup(buf + 12);
522                         break;
523                 case H_SUBJECT:
524                         if (msginfo->subject) break;
525                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
526                         msginfo->subject = g_strdup(tmp);
527                         break;
528                 case H_MSG_ID:
529                         if (msginfo->msgid) break;
530
531                         extract_parenthesis(hp, '<', '>');
532                         remove_space(hp);
533                         msginfo->msgid = g_strdup(hp);
534                         break;
535                 case H_REFERENCES:
536                         if (!reference) {
537                                 eliminate_parenthesis(hp, '(', ')');
538                                 if ((p = strrchr(hp, '<')) != NULL &&
539                                     strchr(p + 1, '>') != NULL) {
540                                         extract_parenthesis(p, '<', '>');
541                                         remove_space(p);
542                                         if (*p != '\0')
543                                                 reference = g_strdup(p);
544                                 }
545                         }
546                         break;
547                 case H_IN_REPLY_TO:
548                         if (!reference) {
549                                 eliminate_parenthesis(hp, '(', ')');
550                                 extract_parenthesis(hp, '<', '>');
551                                 remove_space(hp);
552                                 if (*hp != '\0')
553                                         reference = g_strdup(hp);
554                         }
555                         break;
556                 case H_CONTENT_TYPE:
557                         if (!strncasecmp(hp, "multipart", 9))
558                                 msginfo->flags |= MSG_MIME;
559                         break;
560                 case H_SEEN:
561                         /* mnews Seen header */
562                         MSG_UNSET_FLAGS(msginfo->flags, MSG_NEW|MSG_UNREAD);
563                         break;
564                 case H_X_FACE:
565                         if (msginfo->xface) break;
566                         msginfo->xface = g_strdup(hp);
567                         break;
568                 case H_DISPOSITION_NOTIFICATION_TO:
569                         if (msginfo->dispositionnotificationto) break;
570                         msginfo->dispositionnotificationto = g_strdup(hp);
571                         break;
572                 default:
573                 }
574         }
575         msginfo->inreplyto = reference;
576
577         fclose(fp);
578
579         return msginfo;
580 }
581
582 gchar *procheader_get_fromname(const gchar *str)
583 {
584         gchar *tmp, *name;
585
586         Xalloca(tmp, strlen(str) + 1, return NULL);
587         strcpy(tmp, str);
588
589         if (*tmp == '\"') {
590                 extract_quote(tmp, '\"');
591                 g_strstrip(tmp);
592         } else if (strchr(tmp, '<')) {
593                 eliminate_parenthesis(tmp, '<', '>');
594                 g_strstrip(tmp);
595                 if (*tmp == '\0') {
596                         strcpy(tmp, str);
597                         extract_parenthesis(tmp, '<', '>');
598                         g_strstrip(tmp);
599                 }
600         } else if (strchr(tmp, '(')) {
601                 extract_parenthesis(tmp, '(', ')');
602                 g_strstrip(tmp);
603         }
604
605         if (*tmp == '\0')
606                 name = g_strdup(str);
607         else
608                 name = g_strdup(tmp);
609
610         return name;
611 }
612
613 time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
614 {
615         static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
616         gchar weekday[4];
617         gint day;
618         gchar month[4];
619         gint year;
620         gint hh, mm, ss;
621         gchar zone[6];
622         gint result;
623         GDateMonth dmonth;
624         struct tm t;
625         gchar *p;
626         time_t timer;
627
628         /* parsing date field... */
629         result = sscanf(src, "%3s, %d %3s %d %2d:%2d:%2d %5s",
630                         weekday, &day, month, &year, &hh, &mm, &ss, zone);
631         if (result != 8) {
632                 result = sscanf(src, "%d %3s %d %2d:%2d:%2d %5s",
633                                 &day, month, &year, &hh, &mm, &ss, zone);
634                 if (result != 7) {
635                         ss = 0;
636                         result = sscanf(src, "%3s, %d %3s %d %2d:%2d %5s",
637                                         weekday, &day, month, &year, &hh, &mm, zone);
638                         if (result != 7) {
639                                 result = sscanf(src, "%d %3s %d %2d:%2d %5s",
640                                                 &day, month, &year, &hh, &mm,
641                                                 zone);
642                                 if (result != 6) {
643                                         g_warning("Invalid date: %s\n", src);
644                                         if (dest && len > 0)
645                                                 strncpy2(dest, src, len);
646                                         return 0;
647                                 }
648                         }
649                 }
650         }
651
652         /* Y2K compliant :) */
653         if (year < 100) {
654                 if (year < 70)
655                         year += 2000;
656                 else
657                         year += 1900;
658         }
659
660         if ((p = strstr(monthstr, month)) != NULL)
661                 dmonth = (gint)(p - monthstr) / 3 + 1;
662         else {
663                 g_warning("Invalid month: %s\n", month);
664                 dmonth = G_DATE_BAD_MONTH;
665         }
666
667         t.tm_sec = ss;
668         t.tm_min = mm;
669         t.tm_hour = hh;
670         t.tm_mday = day;
671         t.tm_mon = dmonth - 1;
672         t.tm_year = year - 1900;
673         t.tm_wday = 0;
674         t.tm_yday = 0;
675         t.tm_isdst = -1;
676
677         timer = mktime(&t);
678         timer += tzoffset_sec(&timer) - remote_tzoffset_sec(zone);
679
680         if (dest)
681                 procheader_date_get_localtime(dest, len, timer);
682
683         return timer;
684 }
685
686 void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
687 {
688         struct tm *lt;
689         gchar *default_format = "%y/%m/%d(%a) %H:%M";
690
691         lt = localtime(&timer);
692
693         if (prefs_common.date_format)
694                 strftime(dest, len, prefs_common.date_format, lt);
695         else
696                 strftime(dest, len, default_format, lt);
697 }