49a03b57b90fbac6a7e9b422be6b6fc3d4130126
[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 (header = procheader_parse_header(buf))
215                         hlist = g_slist_append(hlist, header);
216                 /*
217                 if (*buf == ':') continue;
218                 for (p = buf; *p && *p != ' '; p++) {
219                         if (*p == ':') {
220                                 header = g_new(Header, 1);
221                                 header->name = g_strndup(buf, p - buf);
222                                 p++;
223                                 while (*p == ' ' || *p == '\t') p++;
224                                 conv_unmime_header(tmp, sizeof(tmp), p, NULL);
225                                 header->body = g_strdup(tmp);
226
227                                 hlist = g_slist_append(hlist, header);
228                                 break;
229                         }
230                 }
231                 */
232         }
233
234         return hlist;
235 }
236
237 GPtrArray *procheader_get_header_array(FILE *fp)
238 {
239         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
240         gchar *p;
241         GPtrArray *headers;
242         Header *header;
243
244         g_return_val_if_fail(fp != NULL, NULL);
245
246         headers = g_ptr_array_new();
247
248         while (procheader_get_unfolded_line(buf, sizeof(buf), fp) != NULL) {
249                 if (header = procheader_parse_header(buf))
250                         g_ptr_array_add(headers, header);
251                 /*
252                 if (*buf == ':') continue;
253                 for (p = buf; *p && *p != ' '; p++) {
254                         if (*p == ':') {
255                                 header = g_new(Header, 1);
256                                 header->name = g_strndup(buf, p - buf);
257                                 p++;
258                                 while (*p == ' ' || *p == '\t') p++;
259                                 conv_unmime_header(tmp, sizeof(tmp), p, NULL);
260                                 header->body = g_strdup(tmp);
261
262                                 g_ptr_array_add(headers, header);
263                                 break;
264                         }
265                 }
266                 */
267         }
268
269         return headers;
270 }
271
272 GPtrArray *procheader_get_header_array_asis(FILE *fp)
273 {
274         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
275         gchar *p;
276         GPtrArray *headers;
277         Header *header;
278
279         g_return_val_if_fail(fp != NULL, NULL);
280
281         headers = g_ptr_array_new();
282
283         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1) {
284                 if (header = procheader_parse_header(buf))
285                         g_ptr_array_add(headers, header);
286                         /*
287                 if (*buf == ':') continue;
288                 for (p = buf; *p && *p != ' '; p++) {
289                         if (*p == ':') {
290                                 header = g_new(Header, 1);
291                                 header->name = g_strndup(buf, p - buf);
292                                 p++;
293                                 conv_unmime_header(tmp, sizeof(tmp), p, NULL);
294                                 header->body = g_strdup(tmp);
295
296                                 g_ptr_array_add(headers, header);
297                                 break;
298                         }
299                 }
300                         */
301         }
302
303         return headers;
304 }
305
306 void procheader_header_list_destroy(GSList *hlist)
307 {
308         Header *header;
309
310         while (hlist != NULL) {
311                 header = hlist->data;
312                 procheader_header_free(header);
313                 hlist = g_slist_remove(hlist, header);
314         }
315 }
316
317 void procheader_header_array_destroy(GPtrArray *harray)
318 {
319         gint i;
320         Header *header;
321
322         for (i = 0; i < harray->len; i++) {
323                 header = g_ptr_array_index(harray, i);
324                 procheader_header_free(header);
325         }
326
327         g_ptr_array_free(harray, TRUE);
328 }
329
330 void procheader_header_free(Header *header)
331 {
332         if (!header) return;
333
334         g_free(header->name);
335         g_free(header->body);
336         g_free(header);
337 }
338
339 /*
340   tests whether two headers' names are equal
341   remove the trailing ':' or ' ' before comparing
342 */
343
344 gboolean procheader_headername_equal(char * hdr1, char * hdr2)
345 {
346         int len1;
347         int len2;
348
349         len1 = strlen(hdr1);
350         len2 = strlen(hdr2);
351         if ((hdr1[len1 - 1] == ':') || (hdr1[len1 - 1] == ' '))
352                 len1--;
353         if ((hdr2[len2 - 1] == ':') || (hdr2[len2 - 1] == ' '))
354                 len2--;
355         if (len1 != len2)
356                 return 0;
357         return (g_strncasecmp(hdr1, hdr2, len1) == 0);
358 }
359
360 /*
361   parse headers, for example :
362   From: dinh@enseirb.fr becomes :
363   header->name = "From:"
364   header->body = "dinh@enseirb.fr"
365  */
366
367 Header * procheader_parse_header(gchar * buf)
368 {
369         gchar tmp[BUFFSIZE];
370         gchar *p = buf;
371         Header * header;
372
373         if ((*buf == ':') || (*buf == ' '))
374                 return NULL;
375
376         for (p = buf; *p ; p++) {
377                 if ((*p == ':') || (*p == ' ')) {
378                         header = g_new(Header, 1);
379                         header->name = g_strndup(buf, p - buf + 1);
380                         p++;
381                         while (*p == ' ' || *p == '\t') p++;
382                         conv_unmime_header(tmp, sizeof(tmp), p, NULL);
383                         header->body = g_strdup(tmp);
384                         return header;
385                 }
386         }
387         return NULL;
388 }
389
390 void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
391 {
392         gchar buf[BUFFSIZE];
393         HeaderEntry *hp;
394         gint hnum;
395         gchar *p;
396
397         if (hentry == NULL) return;
398
399         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
400                != -1) {
401                 hp = hentry + hnum;
402
403                 p = buf + strlen(hp->name);
404                 while (*p == ' ' || *p == '\t') p++;
405
406                 if (hp->body == NULL)
407                         hp->body = g_strdup(p);
408                 else if (procheader_headername_equal(hp->name, "To") ||
409                          procheader_headername_equal(hp->name, "Cc")) {
410                         gchar *tp = hp->body;
411                         hp->body = g_strconcat(tp, ", ", p, NULL);
412                         g_free(tp);
413                 }
414         }
415 }
416
417 enum
418 {
419         H_DATE          = 0,
420         H_FROM          = 1,
421         H_TO            = 2,
422         H_CC            = 3,
423         H_NEWSGROUPS    = 4,
424         H_SUBJECT       = 5,
425         H_MSG_ID        = 6,
426         H_REFERENCES    = 7,
427         H_IN_REPLY_TO   = 8,
428         H_CONTENT_TYPE  = 9,
429         H_SEEN          = 10,
430         H_X_FACE        = 11,
431         H_DISPOSITION_NOTIFICATION_TO = 12,
432         H_RETURN_RECEIPT_TO = 13
433 };
434
435 MsgInfo *procheader_parse(const gchar *file, MsgFlags flags, gboolean full)
436 {
437         static HeaderEntry hentry_full[] = {{"Date:",           NULL, FALSE},
438                                            {"From:",            NULL, TRUE},
439                                            {"To:",              NULL, TRUE},
440                                            {"Cc:",              NULL, TRUE},
441                                            {"Newsgroups:",      NULL, TRUE},
442                                            {"Subject:",         NULL, TRUE},
443                                            {"Message-Id:",      NULL, FALSE},
444                                            {"References:",      NULL, FALSE},
445                                            {"In-Reply-To:",     NULL, FALSE},
446                                            {"Content-Type:",    NULL, FALSE},
447                                            {"Seen:",            NULL, FALSE},
448                                            {"X-Face:",          NULL, FALSE},
449                                            {"Disposition-Notification-To:", NULL, FALSE},
450                                            {"Return-Receipt-To:", NULL, FALSE},
451                                            {NULL,               NULL, FALSE}};
452
453         static HeaderEntry hentry_short[] = {{"Date:",          NULL, FALSE},
454                                             {"From:",           NULL, TRUE},
455                                             {"To:",             NULL, TRUE},
456                                             {"Cc:",             NULL, TRUE},
457                                             {"Newsgroups:",     NULL, TRUE},
458                                             {"Subject:",        NULL, TRUE},
459                                             {"Message-Id:",     NULL, FALSE},
460                                             {"References:",     NULL, FALSE},
461                                             {"In-Reply-To:",    NULL, FALSE},
462                                             {"Content-Type:",   NULL, FALSE},
463                                             {"Seen:",           NULL, FALSE},
464                                             {NULL,              NULL, FALSE}};
465
466         FILE *fp;
467         MsgInfo *msginfo;
468         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
469         gchar *reference = NULL;
470         gchar *p;
471         gchar *hp;
472         HeaderEntry *hentry;
473         gint hnum;
474
475         hentry = full ? hentry_full : hentry_short;
476
477         if ((fp = fopen(file, "r")) == NULL) {
478                 FILE_OP_ERROR(file, "fopen");
479                 return NULL;
480         }
481         if (MSG_IS_QUEUED(flags)) {
482                 while (fgets(buf, sizeof(buf), fp) != NULL)
483                         if (buf[0] == '\r' || buf[0] == '\n') break;
484         }
485
486         msginfo = g_new0(MsgInfo, 1);
487         msginfo->flags = flags != 0 ? flags : MSG_NEW|MSG_UNREAD;
488         msginfo->inreplyto = NULL;
489
490         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
491                != -1) {
492                 hp = buf + strlen(hentry[hnum].name);
493                 while (*hp == ' ' || *hp == '\t') hp++;
494
495                 switch (hnum) {
496                 case H_DATE:
497                         if (msginfo->date) break;
498                         msginfo->date_t =
499                                 procheader_date_parse(NULL, hp, 0);
500                         msginfo->date = g_strdup(hp);
501                         break;
502                 case H_FROM:
503                         if (msginfo->from) break;
504                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
505                         msginfo->from = g_strdup(tmp);
506                         msginfo->fromname = procheader_get_fromname(tmp);
507                         break;
508                 case H_TO:
509                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
510                         if (msginfo->to) {
511                                 p = msginfo->to;
512                                 msginfo->to =
513                                         g_strconcat(p, ", ", tmp, NULL);
514                                 g_free(p);
515                         } else
516                                 msginfo->to = g_strdup(tmp);
517                         break;
518                 case H_CC:
519                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
520                         if (msginfo->cc) {
521                                 p = msginfo->cc;
522                                 msginfo->cc =
523                                         g_strconcat(p, ", ", tmp, NULL);
524                                 g_free(p);
525                         } else
526                                 msginfo->cc = g_strdup(tmp);
527                         break;
528                 case H_NEWSGROUPS:
529                         if (msginfo->newsgroups) {
530                                 p = msginfo->newsgroups;
531                                 msginfo->newsgroups =
532                                         g_strconcat(p, ",", hp, NULL);
533                                 g_free(p);
534                         } else
535                                 msginfo->newsgroups = g_strdup(buf + 12);
536                         break;
537                 case H_SUBJECT:
538                         if (msginfo->subject) break;
539                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
540                         msginfo->subject = g_strdup(tmp);
541                         break;
542                 case H_MSG_ID:
543                         if (msginfo->msgid) break;
544
545                         extract_parenthesis(hp, '<', '>');
546                         remove_space(hp);
547                         msginfo->msgid = g_strdup(hp);
548                         break;
549                 case H_REFERENCES:
550                         if (!reference) {
551                                 msginfo->references = g_strdup(hp);
552                                 eliminate_parenthesis(hp, '(', ')');
553                                 if ((p = strrchr(hp, '<')) != NULL &&
554                                     strchr(p + 1, '>') != NULL) {
555                                         extract_parenthesis(p, '<', '>');
556                                         remove_space(p);
557                                         if (*p != '\0')
558                                                 reference = g_strdup(p);
559                                 }
560                         }
561                         break;
562                 case H_IN_REPLY_TO:
563                         if (!reference) {
564                                 eliminate_parenthesis(hp, '(', ')');
565                                 extract_parenthesis(hp, '<', '>');
566                                 remove_space(hp);
567                                 if (*hp != '\0')
568                                         reference = g_strdup(hp);
569                         }
570                         break;
571                 case H_CONTENT_TYPE:
572                         if (!strncasecmp(hp, "multipart", 9))
573                                 msginfo->flags |= MSG_MIME;
574                         break;
575                 case H_SEEN:
576                         /* mnews Seen header */
577                         MSG_UNSET_FLAGS(msginfo->flags, MSG_NEW|MSG_UNREAD);
578                         break;
579                 case H_X_FACE:
580                         if (msginfo->xface) break;
581                         msginfo->xface = g_strdup(hp);
582                         break;
583                 case H_DISPOSITION_NOTIFICATION_TO:
584                         if (msginfo->dispositionnotificationto) break;
585                         msginfo->dispositionnotificationto = g_strdup(hp);
586                         break;
587                 case H_RETURN_RECEIPT_TO:
588                         if (msginfo->returnreceiptto) break;
589                         msginfo->returnreceiptto = g_strdup(hp);
590                         break;
591                 default:
592                 }
593         }
594         msginfo->inreplyto = reference;
595
596         fclose(fp);
597
598         return msginfo;
599 }
600
601 gchar *procheader_get_fromname(const gchar *str)
602 {
603         gchar *tmp, *name;
604
605         Xalloca(tmp, strlen(str) + 1, return NULL);
606         strcpy(tmp, str);
607
608         if (*tmp == '\"') {
609                 extract_quote(tmp, '\"');
610                 g_strstrip(tmp);
611         } else if (strchr(tmp, '<')) {
612                 eliminate_parenthesis(tmp, '<', '>');
613                 g_strstrip(tmp);
614                 if (*tmp == '\0') {
615                         strcpy(tmp, str);
616                         extract_parenthesis(tmp, '<', '>');
617                         g_strstrip(tmp);
618                 }
619         } else if (strchr(tmp, '(')) {
620                 extract_parenthesis(tmp, '(', ')');
621                 g_strstrip(tmp);
622         }
623
624         if (*tmp == '\0')
625                 name = g_strdup(str);
626         else
627                 name = g_strdup(tmp);
628
629         return name;
630 }
631
632 time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
633 {
634         static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
635         gchar weekday[4];
636         gint day;
637         gchar month[4];
638         gint year;
639         gint hh, mm, ss;
640         gchar zone[6];
641         gint result;
642         GDateMonth dmonth;
643         struct tm t;
644         gchar *p;
645         time_t timer;
646
647         /* parsing date field... */
648         result = sscanf(src, "%3s, %d %3s %d %2d:%2d:%2d %5s",
649                         weekday, &day, month, &year, &hh, &mm, &ss, zone);
650         if (result != 8) {
651                 result = sscanf(src, "%d %3s %d %2d:%2d:%2d %5s",
652                                 &day, month, &year, &hh, &mm, &ss, zone);
653                 if (result != 7) {
654                         ss = 0;
655                         result = sscanf(src, "%3s, %d %3s %d %2d:%2d %5s",
656                                         weekday, &day, month, &year, &hh, &mm, zone);
657                         if (result != 7) {
658                                 result = sscanf(src, "%d %3s %d %2d:%2d %5s",
659                                                 &day, month, &year, &hh, &mm,
660                                                 zone);
661                                 if (result != 6) {
662                                         g_warning("Invalid date: %s\n", src);
663                                         if (dest && len > 0)
664                                                 strncpy2(dest, src, len);
665                                         return 0;
666                                 }
667                         }
668                 }
669         }
670
671         /* Y2K compliant :) */
672         if (year < 100) {
673                 if (year < 70)
674                         year += 2000;
675                 else
676                         year += 1900;
677         }
678
679         if ((p = strstr(monthstr, month)) != NULL)
680                 dmonth = (gint)(p - monthstr) / 3 + 1;
681         else {
682                 g_warning("Invalid month: %s\n", month);
683                 dmonth = G_DATE_BAD_MONTH;
684         }
685
686         t.tm_sec = ss;
687         t.tm_min = mm;
688         t.tm_hour = hh;
689         t.tm_mday = day;
690         t.tm_mon = dmonth - 1;
691         t.tm_year = year - 1900;
692         t.tm_wday = 0;
693         t.tm_yday = 0;
694         t.tm_isdst = -1;
695
696         timer = mktime(&t);
697         timer += tzoffset_sec(&timer) - remote_tzoffset_sec(zone);
698
699         if (dest)
700                 procheader_date_get_localtime(dest, len, timer);
701
702         return timer;
703 }
704
705 void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
706 {
707         struct tm *lt;
708         gchar *default_format = "%y/%m/%d(%a) %H:%M";
709
710         lt = localtime(&timer);
711
712         if (prefs_common.date_format)
713                 strftime(dest, len, prefs_common.date_format, lt);
714         else
715                 strftime(dest, len, default_format, lt);
716 }