wibble
[apps/madmutt.git] / muttlib.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #include <lib-lib/lib-lib.h>
12
13 #include <grp.h>
14 #include <pwd.h>
15
16 #include <lib-ui/lib-ui.h>
17 #include <lib-sys/unix.h>
18 #include <imap/imap.h>
19
20 #include "alias.h"
21 #include "mutt.h"
22 #include "attach.h"
23
24 /* Modified by blong to accept a "suggestion" for file name.  If
25  * that file exists, then construct one with unique name but 
26  * keep any extension.  This might fail, I guess.
27  * Renamed to mutt_adv_mktemp so I only have to change where it's
28  * called, and not all possible cases.
29  */
30 void mutt_adv_mktemp (const char* dir, char *s, ssize_t l)
31 {
32     int fd;
33
34     fd = m_tempfd(s, l, m_strisempty(dir) ? NONULL(mod_core.tmpdir) : dir, s);
35     if (fd < 0) {
36         *s = '\0';
37     } else {
38         close(fd);
39         unlink(s);
40     }
41 }
42
43 void mutt_mktemp(char *s)
44 {
45     int fd = m_tempfd(s, _POSIX_PATH_MAX, NONULL(mod_core.tmpdir), NULL);
46     if (fd < 0) {
47         *s = '\0';
48     } else {
49         close(fd);
50         unlink(s);
51     }
52 }
53
54 ssize_t _mutt_expand_path(char *buf, ssize_t len, const char *s, int rx)
55 {
56     char p[_POSIX_PATH_MAX] = "";
57     char tmp[_POSIX_PATH_MAX];
58     const char *tail = "";
59     const address_t *alias;
60
61     switch (*s) {
62       case '~':
63         if (s[1] == '/' || s[1] == '\0') {
64             m_strcpy(p, sizeof(p), mod_core.homedir);
65             tail = s + 1;
66         } else {
67             struct passwd *pw;
68             tail = m_strchrnul(s + 1, '/');
69
70             m_strncpy(tmp, sizeof(tmp), s + 1, tail - s - 1);
71
72             if ((pw = getpwnam(tmp))) {
73                 m_strcpy(p, sizeof(p), pw->pw_dir);
74             } else {
75                 /* user not found! */
76                 tail = s;
77             }
78         }
79         break;
80
81       case '=':
82       case '+':
83         /* if folder = imap[s]://host/: don't append slash */
84         if (imap_is_magic(NONULL(Maildir), NULL) == M_IMAP
85         &&  Maildir[m_strlen(Maildir) - 1] == '/') {
86             m_strcpy(p, sizeof(p), Maildir);
87         } else {
88             snprintf(p, sizeof(p), "%s/", NONULL(Maildir));
89         }
90
91         tail = s + 1;
92         break;
93
94         /* elm compatibility, @ expands alias to user name */
95
96       case '@':
97         if ((alias = alias_lookup(s + 1))) {
98             HEADER h;
99             header_init(&h);
100             h.env = envelope_new();
101             h.env->from = h.env->to = (address_t *)alias;
102             mutt_default_save(p, sizeof (p), &h);
103             h.env->from = h.env->to = NULL;
104             header_wipe(&h);
105
106             if (*p != '@')
107                 return _mutt_expand_path(buf, len, p, rx);
108         }
109         break;
110
111       case '>':
112         m_strcpy(p, sizeof(p), Inbox);
113         tail = s + 1;
114         break;
115
116       case '<':
117         m_strcpy(p, sizeof(p), MAlias.record);
118         tail = s + 1;
119         break;
120
121       case '!':
122         if (s[1] == '!') {
123             m_strcpy(p, sizeof(p), LastFolder);
124             tail = s + 2;
125         } else {
126             m_strcpy(p, sizeof(p), Spoolfile);
127             tail = s + 1;
128         }
129         break;
130
131       case '-':
132         m_strcpy(p, sizeof(p), NONULL(LastFolder));
133         tail = s + 1;
134         break;
135
136       case '^':
137         m_strcpy(p, sizeof(p), NONULL(CurrentFolder));
138         tail = s + 1;
139         break;
140
141       default:
142         *p = '\0';
143         tail = s;
144     }
145
146     if (rx) {
147         char q[_POSIX_PATH_MAX];
148         rx_sanitize_string(q, sizeof(q), p);
149         snprintf(tmp, sizeof(tmp), "%s%s", q, tail);
150     } else {
151         snprintf(tmp, sizeof(tmp), "%s%s", p, tail);
152     }
153
154     return m_strcpy(buf, len, tmp);
155 }
156
157 /* collapse the pathname using ~ or = when possible */
158 void mutt_pretty_mailbox (char *s)
159 {
160   char *p = s, *q = s;
161   ssize_t len;
162   url_scheme_t scheme;
163
164   scheme = url_check_scheme (s);
165
166   if (scheme == U_IMAP || scheme == U_IMAPS) {
167     imap_pretty_mailbox (s);
168     return;
169   }
170
171   /* if s is an url, only collapse path component */
172   if (scheme != U_UNKNOWN) {
173     p = strchr (s, ':') + 1;
174     if (!m_strncmp (p, "//", 2))
175       q = strchr (p + 2, '/');
176     if (!q)
177       q = strchr (p, '\0');
178     p = q;
179   }
180
181   /* first attempt to collapse the pathname */
182   while (*p) {
183     if (*p == '/' && p[1] == '/') {
184       *q++ = '/';
185       p += 2;
186     }
187     else if (p[0] == '/' && p[1] == '.' && p[2] == '/') {
188       *q++ = '/';
189       p += 3;
190     }
191     else
192       *q++ = *p++;
193   }
194   *q = 0;
195
196   if (m_strncmp(s, Maildir, (len = m_strlen(Maildir))) == 0 &&
197       s[len] == '/') {
198     *s++ = '=';
199     memmove (s, s + len, m_strlen(s + len) + 1);
200   }
201   else if (m_strncmp(s, mod_core.homedir, (len = m_strlen(mod_core.homedir))) == 0
202            && s[len] == '/') {
203     *s++ = '~';
204     memmove (s, s + len - 1, m_strlen(s + len - 1) + 1);
205   }
206 }
207
208 /* return 0 on success, -1 on abort, 1 on error */
209 int mutt_check_overwrite (const char *attname, const char *path,
210                           char *fname, ssize_t flen, int *append,
211                           char **directory)
212 {
213   int rc = 0;
214   char tmp[_POSIX_PATH_MAX];
215   struct stat st;
216
217   m_strcpy(fname, flen, path);
218   if (access (fname, F_OK) != 0)
219     return 0;
220   if (stat (fname, &st) != 0)
221     return -1;
222   if (S_ISDIR (st.st_mode)) {
223     if (directory) {
224       switch (mutt_multi_choice
225               (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"),
226                _("yna"))) {
227       case 3:                  /* all */
228         m_strreplace(directory, fname);
229         break;
230       case 1:                  /* yes */
231         p_delete(directory);
232         break;
233       case -1:                 /* abort */
234         p_delete(directory);
235         return -1;
236       case 2:                  /* no */
237         p_delete(directory);
238         return 1;
239       }
240     }
241     else
242       if ((rc = mutt_yesorno(_("File is a directory, save under it?"),
243                              M_YES)) != M_YES)
244       return (rc == M_NO) ? 1 : -1;
245
246     if (!attname || !attname[0]) {
247       tmp[0] = 0;
248       if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
249                           M_FILE | M_CLEAR) != 0 || !tmp[0])
250         return (-1);
251       mutt_concat_path(fname, flen, path, tmp);
252     }
253     else
254       mutt_concat_path(fname, flen, path, mutt_basename(attname));
255   }
256
257   if (*append == 0 && access (fname, F_OK) == 0) {
258     switch (mutt_multi_choice
259             (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
260     {
261     case -1:                   /* abort */
262       return -1;
263     case 3:                    /* cancel */
264       return 1;
265
266     case 2:                    /* append */
267       *append = M_SAVE_APPEND;
268       break;
269     case 1:                    /* overwrite */
270       *append = M_SAVE_OVERWRITE;
271       break;
272     }
273   }
274   return 0;
275 }
276
277 void mutt_save_path(char *d, ssize_t dsize, address_t *a)
278 {
279     if (a && a->mailbox) {
280         m_strncpy(d, dsize, a->mailbox, strcspn(d, "%@"));
281         m_strtolower(d);
282     } else {
283         *d = '\0';
284     }
285 }
286
287 void mutt_safe_path(char *s, ssize_t l, address_t *a)
288 {
289     mutt_save_path(s, l, a);
290
291     while (*s) {
292         if (*s == '/' || ISSPACE(*s) || !isprint((unsigned char)*s))
293             *s = '_';
294         s++;
295     }
296 }
297
298 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
299 int mutt_save_confirm (const char *s, struct stat *st)
300 {
301   char tmp[_POSIX_PATH_MAX];
302   int ret = 0;
303   int rc;
304   int magic = 0;
305
306   magic = mx_get_magic (s);
307
308   if (magic == M_POP) {
309     mutt_error _("Can't save message to POP mailbox.");
310
311     return 1;
312   }
313
314   if (magic > 0 && !mx_access (s, W_OK)) {
315     if (option (OPTCONFIRMAPPEND) &&
316         (!TrashPath || (m_strcmp(s, TrashPath) != 0))) {
317       /* if we're appending to the trash, there's no point in asking */
318       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
319       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
320         ret = 1;
321       else if (rc == -1)
322         ret = -1;
323     }
324   }
325
326   if (stat (s, st) != -1) {
327     if (magic == -1) {
328       mutt_error (_("%s is not a mailbox!"), s);
329       return 1;
330     }
331   } else {
332     if (magic != M_IMAP)
333     {
334       st->st_mtime = 0;
335       st->st_atime = 0;
336
337       if (errno == ENOENT) {
338         if (option (OPTCONFIRMCREATE)) {
339           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
340           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
341             ret = 1;
342           else if (rc == -1)
343             ret = -1;
344         }
345       } else {
346         mutt_perror (s);
347         return 1;
348       }
349     }
350   }
351   return (ret);
352 }
353
354 void mutt_sleep (short s)
355 {
356     sleep(MAX(s, SleepTime));
357 }
358
359 const char *mutt_make_version(void)
360 {
361   static char vstring[STRING];
362   snprintf(vstring, sizeof (vstring), "Madmutt/%s", MUTT_VERSION);
363   return vstring;
364 }
365
366 /* return 1 if address lists are strictly identical */
367 static int mutt_cmp_addr (const address_t * a, const address_t * b)
368 {
369   while (a && b) {
370     if (m_strcmp(a->mailbox, b->mailbox) ||
371         m_strcmp(a->personal, b->personal))
372       return (0);
373
374     a = a->next;
375     b = b->next;
376   }
377   if (a || b)
378     return (0);
379
380   return (1);
381 }
382
383 static int mutt_cmp_list (const string_list_t * a, const string_list_t * b)
384 {
385   while (a && b) {
386     if (m_strcmp(a->data, b->data))
387       return (0);
388
389     a = a->next;
390     b = b->next;
391   }
392   if (a || b)
393     return (0);
394
395   return (1);
396 }
397
398 static int mutt_cmp_env (const ENVELOPE * e1, const ENVELOPE * e2)
399 {
400   if (e1 && e2) {
401     if (m_strcmp(e1->message_id, e2->message_id) ||
402         m_strcmp(e1->subject, e2->subject) ||
403         !mutt_cmp_list (e1->references, e2->references) ||
404         !mutt_cmp_addr (e1->from, e2->from) ||
405         !mutt_cmp_addr (e1->sender, e2->sender) ||
406         !mutt_cmp_addr (e1->reply_to, e2->reply_to) ||
407         !mutt_cmp_addr (e1->to, e2->to) ||
408         !mutt_cmp_addr (e1->cc, e2->cc) ||
409         !mutt_cmp_addr (e1->return_path, e2->return_path))
410       return (0);
411     else
412       return (1);
413   }
414   else {
415     if (e1 == NULL && e2 == NULL)
416       return (1);
417     else
418       return (0);
419   }
420 }
421
422 static int mutt_cmp_body (const BODY * b1, const BODY * b2)
423 {
424   if (b1->type != b2->type ||
425       b1->encoding != b2->encoding ||
426       m_strcmp(b1->subtype, b2->subtype) ||
427       m_strcmp(b1->description, b2->description) ||
428       !parameter_equal(b1->parameter, b2->parameter) ||
429       b1->length != b2->length)
430     return (0);
431   return (1);
432 }
433 int mutt_cmp_header (const HEADER * h1, const HEADER * h2) {
434   if (h1 && h2) {
435     if (h1->received != h2->received ||
436         h1->date_sent != h2->date_sent ||
437         h1->content->length != h2->content->length ||
438         h1->lines != h2->lines ||
439         h1->zhours != h2->zhours ||
440         h1->zminutes != h2->zminutes ||
441         h1->zoccident != h2->zoccident ||
442         h1->mime != h2->mime ||
443         !mutt_cmp_env (h1->env, h2->env) ||
444         !mutt_cmp_body (h1->content, h2->content))
445       return (0);
446     else
447       return (1);
448   }
449   else {
450     if (h1 == NULL && h2 == NULL)
451       return (1);
452     else
453       return (0);
454   }
455 }
456
457
458 int mutt_extract_token(BUFFER *dest, BUFFER *tok, int flags)
459 {
460     char ch;
461     char qc = 0;                  /* quote char */
462     char *pc;
463
464     /* reset the destination pointer to the beginning of the buffer */
465     dest->dptr = dest->data;
466
467     tok->dptr = vskipspaces(tok->dptr);
468     while ((ch = *tok->dptr)) {
469         if (!qc) {
470             if ((ISSPACE(ch) && !(flags & M_TOKEN_SPACE))
471             || (ch == '#' && !(flags & M_TOKEN_COMMENT))
472             || (ch == '=' && (flags & M_TOKEN_EQUAL))
473             || ((flags & M_TOKEN_PATTERN) && strchr("~=!|", ch)))
474             {
475                 break;
476             }
477         }
478
479         tok->dptr++;
480
481         if (ch == qc) {
482             qc = 0;                     /* end of quote */
483         } else
484         if (!qc && (ch == '\'' || ch == '"') && !(flags & M_TOKEN_QUOTE)) {
485             qc = ch;
486         } else
487         if (ch == '\\' && qc != '\'') {
488             if (!*tok->dptr)
489                 return -1;              /* premature end of token */
490
491             switch (ch = *tok->dptr++) {
492               case 'c':
493               case 'C':
494                 if (!*tok->dptr)
495                     return -1;          /* premature end of token */
496                 mutt_buffer_addch(dest,
497                                   (toupper((unsigned char)*tok->dptr) - 'A' + 1) & 0x7f);
498                 tok->dptr++;
499                 break;
500               case 'r':
501                 mutt_buffer_addch(dest, '\r');
502                 break;
503               case 'n':
504                 mutt_buffer_addch(dest, '\n');
505                 break;
506               case 't':
507                 mutt_buffer_addch(dest, '\t');
508                 break;
509               case 'f':
510                 mutt_buffer_addch(dest, '\f');
511                 break;
512               case 'e':
513                 mutt_buffer_addch(dest, '\033');
514                 break;
515               default:
516                 if (isdigit((unsigned char)ch)
517                 &&  isdigit((unsigned char)*tok->dptr)
518                 &&  isdigit((unsigned char)*(tok->dptr + 1)))
519                 {
520                     mutt_buffer_addch(dest, (ch << 6) + (*tok->dptr << 3) +
521                                             *(tok->dptr + 1) - 3504);
522                     tok->dptr += 2;
523                 } else {
524                     mutt_buffer_addch(dest, ch);
525                 }
526             }
527         } else
528         if (ch == '^' && (flags & M_TOKEN_CONDENSE)) {
529             if (!*tok->dptr)
530                 return -1;              /* premature end of token */
531             ch = *tok->dptr++;
532             if (ch == '^') {
533                 mutt_buffer_addch(dest, ch);
534             } else
535             if (ch == '[') {
536                 mutt_buffer_addch(dest, '\033');
537             } else
538             if (isalpha((unsigned char)ch)) {
539                 mutt_buffer_addch(dest, toupper((unsigned char)ch) - 'A' + 1);
540             } else {
541                 mutt_buffer_addch(dest, '^');
542                 mutt_buffer_addch(dest, ch);
543             }
544         } else
545         if (ch == '`' && (!qc || qc == '"')) {
546             FILE *fp;
547             pid_t pid;
548             char *cmd, *ptr;
549             ssize_t expnlen;
550             BUFFER expn;
551             int line = 0;
552
553             pc = tok->dptr;
554             do {
555                 if ((pc = strpbrk(pc, "\\`"))) {
556                     /* skip any quoted chars */
557                     if (*pc == '\\')
558                         pc += 2;
559                 }
560             } while (pc && *pc != '`');
561             if (!pc) {
562                 return (-1);
563             }
564
565             cmd = p_dupstr(tok->dptr, pc - tok->dptr);
566             if ((pid = mutt_create_filter(cmd, NULL, &fp, NULL)) < 0) {
567                 p_delete(&cmd);
568                 return -1;
569             }
570             p_delete(&cmd);
571
572             tok->dptr = pc + 1;
573
574             /* read line */
575             p_clear(&expn, 1);
576             expn.data = mutt_read_line(NULL, &expn.dsize, fp, &line);
577             m_fclose(&fp);
578             mutt_wait_filter(pid);
579
580             /* if we got output, make a new string consiting of the shell ouptput
581                plus whatever else was left on the original line */
582             /* BUT: If this is inside a quoted string, directly add output to 
583              * the token */
584             if (expn.data && qc) {
585                 mutt_buffer_addstr(dest, expn.data);
586                 p_delete(&expn.data);
587             } else
588             if (expn.data) {
589                 expnlen = m_strlen(expn.data);
590                 tok->dsize = expnlen + m_strlen(tok->dptr) + 1;
591                 ptr = xmalloc(tok->dsize);
592                 memcpy(ptr, expn.data, expnlen);
593                 m_strcpy(ptr + expnlen, tok->dsize - expnlen, tok->dptr);
594                 if (tok->destroy)
595                     p_delete(&tok->data);
596                 tok->data = ptr;
597                 tok->dptr = ptr;
598                 tok->destroy = 1;       /* mark that the caller should destroy this data */
599                 ptr = NULL;
600                 p_delete(&expn.data);
601             }
602         } else
603         if (ch == '$' && (!qc || qc == '"')
604         && (*tok->dptr == '{' || isalpha((unsigned char)*tok->dptr)))
605         {
606             char *env = NULL, *var = NULL;
607
608             if (*tok->dptr == '{') {
609                 tok->dptr++;
610                 if ((pc = strchr (tok->dptr, '}'))) {
611                     var = p_dupstr(tok->dptr, pc - tok->dptr);
612                     tok->dptr = pc + 1;
613                 }
614             } else {
615                 for (pc = tok->dptr; isalnum((unsigned char)*pc) || *pc == '_';
616                      pc++);
617                 var = p_dupstr(tok->dptr, pc - tok->dptr);
618                 tok->dptr = pc;
619             }
620             if (var) {
621                 char tmp[STRING];
622                 if ((env = getenv (var))
623                 || (mutt_option_value (var, tmp, sizeof (tmp)) && (env = tmp)))
624                 {
625                     mutt_buffer_addstr (dest, env);
626                 }
627             }
628             p_delete(&var);
629         } else {
630             mutt_buffer_addch(dest, ch);
631         }
632     }
633     mutt_buffer_addch(dest, 0);  /* terminate the string */
634     tok->dptr = vskipspaces(tok->dptr);
635     return 0;
636 }