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