2363c03597e3fe475ed0b0e3f9c1a51a2f5f521e
[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 };
433
434 MsgInfo *procheader_parse(const gchar *file, MsgFlags flags, gboolean full)
435 {
436         static HeaderEntry hentry_full[] = {{"Date:",           NULL, FALSE},
437                                            {"From:",            NULL, TRUE},
438                                            {"To:",              NULL, TRUE},
439                                            {"Cc:",              NULL, TRUE},
440                                            {"Newsgroups:",      NULL, TRUE},
441                                            {"Subject:",         NULL, TRUE},
442                                            {"Message-Id:",      NULL, FALSE},
443                                            {"References:",      NULL, FALSE},
444                                            {"In-Reply-To:",     NULL, FALSE},
445                                            {"Content-Type:",    NULL, FALSE},
446                                            {"Seen:",            NULL, FALSE},
447                                            {"X-Face:",          NULL, FALSE},
448                                            {"Disposition-Notification-To:",NULL, FALSE},
449                                            {NULL,               NULL, FALSE}};
450
451         static HeaderEntry hentry_short[] = {{"Date:",          NULL, FALSE},
452                                             {"From:",           NULL, TRUE},
453                                             {"To:",             NULL, TRUE},
454                                             {"Cc:",             NULL, TRUE},
455                                             {"Newsgroups:",     NULL, TRUE},
456                                             {"Subject:",        NULL, TRUE},
457                                             {"Message-Id:",     NULL, FALSE},
458                                             {"References:",     NULL, FALSE},
459                                             {"In-Reply-To:",    NULL, FALSE},
460                                             {"Content-Type:",   NULL, FALSE},
461                                             {"Seen:",           NULL, FALSE},
462                                             {NULL,              NULL, FALSE}};
463
464         FILE *fp;
465         MsgInfo *msginfo;
466         gchar buf[BUFFSIZE], tmp[BUFFSIZE];
467         gchar *reference = NULL;
468         gchar *p;
469         gchar *hp;
470         HeaderEntry *hentry;
471         gint hnum;
472
473         hentry = full ? hentry_full : hentry_short;
474
475         if ((fp = fopen(file, "r")) == NULL) {
476                 FILE_OP_ERROR(file, "fopen");
477                 return NULL;
478         }
479         if (MSG_IS_QUEUED(flags)) {
480                 while (fgets(buf, sizeof(buf), fp) != NULL)
481                         if (buf[0] == '\r' || buf[0] == '\n') break;
482         }
483
484         msginfo = g_new0(MsgInfo, 1);
485         msginfo->flags = flags != 0 ? flags : MSG_NEW|MSG_UNREAD;
486         msginfo->inreplyto = NULL;
487
488         while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
489                != -1) {
490                 hp = buf + strlen(hentry[hnum].name);
491                 while (*hp == ' ' || *hp == '\t') hp++;
492
493                 switch (hnum) {
494                 case H_DATE:
495                         if (msginfo->date) break;
496                         msginfo->date_t =
497                                 procheader_date_parse(NULL, hp, 0);
498                         msginfo->date = g_strdup(hp);
499                         break;
500                 case H_FROM:
501                         if (msginfo->from) break;
502                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
503                         msginfo->from = g_strdup(tmp);
504                         msginfo->fromname = procheader_get_fromname(tmp);
505                         break;
506                 case H_TO:
507                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
508                         if (msginfo->to) {
509                                 p = msginfo->to;
510                                 msginfo->to =
511                                         g_strconcat(p, ", ", tmp, NULL);
512                                 g_free(p);
513                         } else
514                                 msginfo->to = g_strdup(tmp);
515                         break;
516                 case H_CC:
517                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
518                         if (msginfo->cc) {
519                                 p = msginfo->cc;
520                                 msginfo->cc =
521                                         g_strconcat(p, ", ", tmp, NULL);
522                                 g_free(p);
523                         } else
524                                 msginfo->cc = g_strdup(tmp);
525                         break;
526                 case H_NEWSGROUPS:
527                         if (msginfo->newsgroups) {
528                                 p = msginfo->newsgroups;
529                                 msginfo->newsgroups =
530                                         g_strconcat(p, ",", hp, NULL);
531                                 g_free(p);
532                         } else
533                                 msginfo->newsgroups = g_strdup(buf + 12);
534                         break;
535                 case H_SUBJECT:
536                         if (msginfo->subject) break;
537                         conv_unmime_header(tmp, sizeof(tmp), hp, NULL);
538                         msginfo->subject = g_strdup(tmp);
539                         break;
540                 case H_MSG_ID:
541                         if (msginfo->msgid) break;
542
543                         extract_parenthesis(hp, '<', '>');
544                         remove_space(hp);
545                         msginfo->msgid = g_strdup(hp);
546                         break;
547                 case H_REFERENCES:
548                         if (!reference) {
549                                 eliminate_parenthesis(hp, '(', ')');
550                                 if ((p = strrchr(hp, '<')) != NULL &&
551                                     strchr(p + 1, '>') != NULL) {
552                                         extract_parenthesis(p, '<', '>');
553                                         remove_space(p);
554                                         if (*p != '\0')
555                                                 reference = g_strdup(p);
556                                 }
557                         }
558                         break;
559                 case H_IN_REPLY_TO:
560                         if (!reference) {
561                                 eliminate_parenthesis(hp, '(', ')');
562                                 extract_parenthesis(hp, '<', '>');
563                                 remove_space(hp);
564                                 if (*hp != '\0')
565                                         reference = g_strdup(hp);
566                         }
567                         break;
568                 case H_CONTENT_TYPE:
569                         if (!strncasecmp(hp, "multipart", 9))
570                                 msginfo->flags |= MSG_MIME;
571                         break;
572                 case H_SEEN:
573                         /* mnews Seen header */
574                         MSG_UNSET_FLAGS(msginfo->flags, MSG_NEW|MSG_UNREAD);
575                         break;
576                 case H_X_FACE:
577                         if (msginfo->xface) break;
578                         msginfo->xface = g_strdup(hp);
579                         break;
580                 case H_DISPOSITION_NOTIFICATION_TO:
581                         if (msginfo->dispositionnotificationto) break;
582                         msginfo->dispositionnotificationto = g_strdup(hp);
583                         break;
584                 default:
585                 }
586         }
587         msginfo->inreplyto = reference;
588
589         fclose(fp);
590
591         return msginfo;
592 }
593
594 gchar *procheader_get_fromname(const gchar *str)
595 {
596         gchar *tmp, *name;
597
598         Xalloca(tmp, strlen(str) + 1, return NULL);
599         strcpy(tmp, str);
600
601         if (*tmp == '\"') {
602                 extract_quote(tmp, '\"');
603                 g_strstrip(tmp);
604         } else if (strchr(tmp, '<')) {
605                 eliminate_parenthesis(tmp, '<', '>');
606                 g_strstrip(tmp);
607                 if (*tmp == '\0') {
608                         strcpy(tmp, str);
609                         extract_parenthesis(tmp, '<', '>');
610                         g_strstrip(tmp);
611                 }
612         } else if (strchr(tmp, '(')) {
613                 extract_parenthesis(tmp, '(', ')');
614                 g_strstrip(tmp);
615         }
616
617         if (*tmp == '\0')
618                 name = g_strdup(str);
619         else
620                 name = g_strdup(tmp);
621
622         return name;
623 }
624
625 time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
626 {
627         static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
628         gchar weekday[4];
629         gint day;
630         gchar month[4];
631         gint year;
632         gint hh, mm, ss;
633         gchar zone[6];
634         gint result;
635         GDateMonth dmonth;
636         struct tm t;
637         gchar *p;
638         time_t timer;
639
640         /* parsing date field... */
641         result = sscanf(src, "%3s, %d %3s %d %2d:%2d:%2d %5s",
642                         weekday, &day, month, &year, &hh, &mm, &ss, zone);
643         if (result != 8) {
644                 result = sscanf(src, "%d %3s %d %2d:%2d:%2d %5s",
645                                 &day, month, &year, &hh, &mm, &ss, zone);
646                 if (result != 7) {
647                         ss = 0;
648                         result = sscanf(src, "%3s, %d %3s %d %2d:%2d %5s",
649                                         weekday, &day, month, &year, &hh, &mm, zone);
650                         if (result != 7) {
651                                 result = sscanf(src, "%d %3s %d %2d:%2d %5s",
652                                                 &day, month, &year, &hh, &mm,
653                                                 zone);
654                                 if (result != 6) {
655                                         g_warning("Invalid date: %s\n", src);
656                                         if (dest && len > 0)
657                                                 strncpy2(dest, src, len);
658                                         return 0;
659                                 }
660                         }
661                 }
662         }
663
664         /* Y2K compliant :) */
665         if (year < 100) {
666                 if (year < 70)
667                         year += 2000;
668                 else
669                         year += 1900;
670         }
671
672         if ((p = strstr(monthstr, month)) != NULL)
673                 dmonth = (gint)(p - monthstr) / 3 + 1;
674         else {
675                 g_warning("Invalid month: %s\n", month);
676                 dmonth = G_DATE_BAD_MONTH;
677         }
678
679         t.tm_sec = ss;
680         t.tm_min = mm;
681         t.tm_hour = hh;
682         t.tm_mday = day;
683         t.tm_mon = dmonth - 1;
684         t.tm_year = year - 1900;
685         t.tm_wday = 0;
686         t.tm_yday = 0;
687         t.tm_isdst = -1;
688
689         timer = mktime(&t);
690         timer += tzoffset_sec(&timer) - remote_tzoffset_sec(zone);
691
692         if (dest)
693                 procheader_date_get_localtime(dest, len, timer);
694
695         return timer;
696 }
697
698 void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
699 {
700         struct tm *lt;
701         gchar *default_format = "%y/%m/%d(%a) %H:%M";
702
703         lt = localtime(&timer);
704
705         if (prefs_common.date_format)
706                 strftime(dest, len, prefs_common.date_format, lt);
707         else
708                 strftime(dest, len, default_format, lt);
709 }