remove most of the debug code: often makes the code unreadable, for little
[apps/madmutt.git] / rfc1524.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 /* 
11  * rfc1524 defines a format for the Multimedia Mail Configuration, which
12  * is the standard mailcap file format under Unix which specifies what 
13  * external programs should be used to view/compose/edit multimedia files
14  * based on content type.
15  *
16  * This file contains various functions for implementing a fair subset of 
17  * rfc1524.
18  */
19
20 #if HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27
28 #include <sys/stat.h>
29 #include <sys/wait.h>
30 #include <errno.h>
31 #include <unistd.h>
32
33 #include <lib-lib/mem.h>
34 #include <lib-lib/str.h>
35 #include <lib-lib/ascii.h>
36 #include <lib-lib/macros.h>
37 #include <lib-lib/file.h>
38
39 #include <lib-sys/unix.h>
40
41 #include "mutt.h"
42 #include "rfc1524.h"
43 #include "attach.h"
44
45 /* The command semantics include the following:
46  * %s is the filename that contains the mail body data
47  * %t is the content type, like text/plain
48  * %{parameter} is replaced by the parameter value from the content-type field
49  * \% is %
50  * Unsupported rfc1524 parameters: these would probably require some doing
51  * by mutt, and can probably just be done by piping the message to metamail
52  * %n is the integer number of sub-parts in the multipart
53  * %F is "content-type filename" repeated for each sub-part
54  *
55  * In addition, this function returns a 0 if the command works on a file,
56  * and 1 if the command works on a pipe.
57  */
58 int rfc1524_expand_command (BODY * a, char *filename, char *_type,
59                             char *command, int clen)
60 {
61   int x = 0, y = 0;
62   int needspipe = TRUE;
63   char buf[LONG_STRING];
64   char type[LONG_STRING];
65
66   m_strcpy(type, sizeof(type), _type);
67
68   if (option (OPTMAILCAPSANITIZE))
69     mutt_sanitize_filename (type, 0);
70
71   while (command[x] && x < clen && y < ssizeof (buf)) {
72     if (command[x] == '\\') {
73       x++;
74       buf[y++] = command[x++];
75     }
76     else if (command[x] == '%') {
77       x++;
78       if (command[x] == '{') {
79         char param[STRING];
80         char pvalue[STRING];
81         char *_pvalue;
82         int z = 0;
83
84         x++;
85         while (command[x] && command[x] != '}' && z < ssizeof (param))
86           param[z++] = command[x++];
87         param[z] = '\0';
88
89         _pvalue = mutt_get_parameter (param, a->parameter);
90         m_strcpy(pvalue, sizeof(pvalue), NONULL(_pvalue));
91         if (option (OPTMAILCAPSANITIZE))
92           mutt_sanitize_filename (pvalue, 0);
93
94         y += mutt_quote_filename (buf + y, sizeof (buf) - y, pvalue);
95       }
96       else if (command[x] == 's' && filename != NULL) {
97         y += mutt_quote_filename (buf + y, sizeof (buf) - y, filename);
98         needspipe = FALSE;
99       }
100       else if (command[x] == 't') {
101         y += mutt_quote_filename (buf + y, sizeof (buf) - y, type);
102       }
103       x++;
104     }
105     else
106       buf[y++] = command[x++];
107   }
108   buf[y] = '\0';
109   m_strcpy(command, clen, buf);
110
111   return needspipe;
112 }
113
114 /* NUL terminates a rfc 1524 field,
115  * returns start of next field or NULL */
116 static char *get_field (char *s)
117 {
118   char *ch;
119
120   if (!s)
121     return NULL;
122
123   while ((ch = strpbrk (s, ";\\")) != NULL) {
124     if (*ch == '\\') {
125       s = ch + 1;
126       if (*s)
127         s++;
128     }
129     else {
130       *ch++ = '\0';
131       ch = vskipspaces(ch);
132       break;
133     }
134   }
135   m_strrtrim(s);
136   return ch;
137 }
138
139 static int get_field_text (char *field, char **entry,
140                            char *type, char *filename, int line)
141 {
142   field = vskipspaces(field);
143   if (*field == '=') {
144     if (entry) {
145       field = vskipspaces(field + 1);
146       m_strreplace(entry, field);
147     }
148     return 1;
149   }
150   else {
151     mutt_error (_("Improperly formated entry for type %s in \"%s\" line %d"),
152                 type, filename, line);
153     return 0;
154   }
155 }
156
157 static int rfc1524_mailcap_parse (BODY * a,
158                                   char *filename,
159                                   char *type, rfc1524_entry * entry, int opt)
160 {
161   FILE *fp;
162   char *buf = NULL;
163   ssize_t buflen;
164   char *ch;
165   char *field;
166   int found = FALSE;
167   int copiousoutput;
168   int composecommand;
169   int editcommand;
170   int printcommand;
171   int btlen;
172   int line = 0;
173
174   /* rfc1524 mailcap file is of the format:
175    * base/type; command; extradefs
176    * type can be * for matching all
177    * base with no /type is an implicit wild
178    * command contains a %s for the filename to pass, default to pipe on stdin
179    * extradefs are of the form:
180    *  def1="definition"; def2="define \;";
181    * line wraps with a \ at the end of the line
182    * # for comments
183    */
184
185   /* find length of basetype */
186   if ((ch = strchr (type, '/')) == NULL)
187     return FALSE;
188   btlen = ch - type;
189
190   if ((fp = fopen (filename, "r")) != NULL) {
191     while (!found && (buf = mutt_read_line(buf, &buflen, fp, &line)) != NULL) {
192       /* ignore comments */
193       if (*buf == '#')
194         continue;
195
196       /* check type */
197       ch = get_field (buf);
198       if (ascii_strcasecmp (buf, type) && (ascii_strncasecmp (buf, type, btlen) || (buf[btlen] != 0 &&  /* implicit wild */
199                                                                                     m_strcmp(buf + btlen, "/*"))))  /* wildsubtype */
200         continue;
201
202       /* next field is the viewcommand */
203       field = ch;
204       ch = get_field (ch);
205       if (entry)
206         entry->command = m_strdup(field);
207
208       /* parse the optional fields */
209       found = TRUE;
210       copiousoutput = FALSE;
211       composecommand = FALSE;
212       editcommand = FALSE;
213       printcommand = FALSE;
214
215       while (ch) {
216         field = ch;
217         ch = get_field (ch);
218
219         if (!ascii_strcasecmp (field, "needsterminal")) {
220           if (entry)
221             entry->needsterminal = TRUE;
222         }
223         else if (!ascii_strcasecmp (field, "copiousoutput")) {
224           copiousoutput = TRUE;
225           if (entry)
226             entry->copiousoutput = TRUE;
227         }
228         else if (!ascii_strncasecmp (field, "composetyped", 12)) {
229           /* this compare most occur before compose to match correctly */
230           if (get_field_text
231               (field + 12, entry ? &entry->composetypecommand : NULL, type,
232                filename, line))
233             composecommand = TRUE;
234         }
235         else if (!ascii_strncasecmp (field, "compose", 7)) {
236           if (get_field_text
237               (field + 7, entry ? &entry->composecommand : NULL, type,
238                filename, line))
239             composecommand = TRUE;
240         }
241         else if (!ascii_strncasecmp (field, "print", 5)) {
242           if (get_field_text (field + 5, entry ? &entry->printcommand : NULL,
243                               type, filename, line))
244             printcommand = TRUE;
245         }
246         else if (!ascii_strncasecmp (field, "edit", 4)) {
247           if (get_field_text (field + 4, entry ? &entry->editcommand : NULL,
248                               type, filename, line))
249             editcommand = TRUE;
250         }
251         else if (!ascii_strncasecmp (field, "nametemplate", 12)) {
252           get_field_text (field + 12, entry ? &entry->nametemplate : NULL,
253                           type, filename, line);
254         }
255         else if (!ascii_strncasecmp (field, "x-convert", 9)) {
256           get_field_text (field + 9, entry ? &entry->convert : NULL,
257                           type, filename, line);
258         }
259         else if (!ascii_strncasecmp (field, "test", 4)) {
260           /* 
261            * This routine executes the given test command to determine
262            * if this is the right entry.
263            */
264           char *test_command = NULL;
265           ssize_t len;
266
267           if (get_field_text (field + 4, &test_command, type, filename, line)
268               && test_command) {
269             len = m_strlen(test_command) + STRING;
270             p_realloc(&test_command, len);
271             rfc1524_expand_command (a, a->filename, type, test_command, len);
272             if (mutt_system (test_command)) {
273               /* a non-zero exit code means test failed */
274               found = FALSE;
275             }
276             p_delete(&test_command);
277           }
278         }
279       }                         /* while (ch) */
280
281       if (opt == M_AUTOVIEW) {
282         if (!copiousoutput)
283           found = FALSE;
284       }
285       else if (opt == M_COMPOSE) {
286         if (!composecommand)
287           found = FALSE;
288       }
289       else if (opt == M_EDIT) {
290         if (!editcommand)
291           found = FALSE;
292       }
293       else if (opt == M_PRINT) {
294         if (!printcommand)
295           found = FALSE;
296       }
297
298       if (!found) {
299         /* reset */
300         if (entry) {
301           p_delete(&entry->command);
302           p_delete(&entry->composecommand);
303           p_delete(&entry->composetypecommand);
304           p_delete(&entry->editcommand);
305           p_delete(&entry->printcommand);
306           p_delete(&entry->nametemplate);
307           p_delete(&entry->convert);
308           entry->needsterminal = 0;
309           entry->copiousoutput = 0;
310         }
311       }
312     }                           /* while (!found && (buf = mutt_read_line ())) */
313     fclose (fp);
314   }                             /* if ((fp = fopen ())) */
315   p_delete(&buf);
316   return found;
317 }
318
319 rfc1524_entry *rfc1524_new_entry (void)
320 {
321   return p_new(rfc1524_entry, 1);
322 }
323
324 void rfc1524_free_entry (rfc1524_entry ** entry)
325 {
326   rfc1524_entry *p = *entry;
327
328   p_delete(&p->command);
329   p_delete(&p->testcommand);
330   p_delete(&p->composecommand);
331   p_delete(&p->composetypecommand);
332   p_delete(&p->editcommand);
333   p_delete(&p->printcommand);
334   p_delete(&p->nametemplate);
335   p_delete(entry);
336 }
337
338 /*
339  * rfc1524_mailcap_lookup attempts to find the given type in the
340  * list of mailcap files.  On success, this returns the entry information
341  * in *entry, and returns 1.  On failure (not found), returns 0.
342  * If entry == NULL just return 1 if the given type is found.
343  */
344 int rfc1524_mailcap_lookup (BODY * a, char *type, rfc1524_entry * entry,
345                             int opt)
346 {
347   char path[_POSIX_PATH_MAX];
348   int x;
349   int found = FALSE;
350   char *curr = MailcapPath;
351
352   /* rfc1524 specifies that a path of mailcap files should be searched.
353    * joy.  They say 
354    * $HOME/.mailcap:/etc/mailcap:/usr/etc/mailcap:/usr/local/etc/mailcap, etc
355    * and overriden by the MAILCAPS environment variable, and, just to be nice, 
356    * we'll make it specifiable in .muttrc
357    */
358   if (!curr || !*curr) {
359     mutt_error _("No mailcap path specified");
360
361     return 0;
362   }
363
364   mutt_check_lookup_list (a, type, SHORT_STRING);
365
366   while (!found && *curr) {
367     x = 0;
368     while (*curr && *curr != ':' && x < ssizeof (path) - 1) {
369       path[x++] = *curr;
370       curr++;
371     }
372     if (*curr)
373       curr++;
374
375     if (!x)
376       continue;
377
378     path[x] = '\0';
379     mutt_expand_path (path, sizeof (path));
380
381     found = rfc1524_mailcap_parse (a, path, type, entry, opt);
382   }
383
384   if (entry && !found)
385     mutt_error (_("mailcap entry for type %s not found"), type);
386
387   return found;
388 }
389
390
391 /* This routine will create a _temporary_ filename matching the
392  * name template given if this needs to be done.
393  * 
394  * Please note that only the last path element of the
395  * template and/or the old file name will be used for the
396  * comparison and the temporary file name.
397  * 
398  * Returns 0 if oldfile is fine as is.
399  * Returns 1 if newfile specified
400  */
401
402 int rfc1524_expand_filename (char *nametemplate,
403                              char *oldfile, char *newfile, ssize_t nflen)
404 {
405   int i, j, k, ps, r;
406   char *s;
407   short lmatch = 0, rmatch = 0;
408   char left[_POSIX_PATH_MAX];
409   char right[_POSIX_PATH_MAX];
410
411   newfile[0] = 0;
412
413   /* first, ignore leading path components.
414    */
415
416   if (nametemplate && (s = strrchr (nametemplate, '/')))
417     nametemplate = s + 1;
418
419   if (oldfile && (s = strrchr (oldfile, '/')))
420     oldfile = s + 1;
421
422   if (!nametemplate) {
423     if (oldfile)
424       m_strcpy(newfile, nflen, oldfile);
425   }
426   else if (!oldfile) {
427     mutt_expand_fmt (newfile, nflen, nametemplate, "mutt");
428   }
429   else {                        /* oldfile && nametemplate */
430
431
432     /* first, compare everything left from the "%s" 
433      * (if there is one).
434      */
435
436     lmatch = 1;
437     ps = 0;
438     for (i = 0; nametemplate[i]; i++) {
439       if (nametemplate[i] == '%' && nametemplate[i + 1] == 's') {
440         ps = 1;
441         break;
442       }
443
444       /* note that the following will _not_ read beyond oldfile's end. */
445
446       if (lmatch && nametemplate[i] != oldfile[i])
447         lmatch = 0;
448     }
449
450     if (ps) {
451
452       /* If we had a "%s", check the rest. */
453
454       /* now, for the right part: compare everything right from 
455        * the "%s" to the final part of oldfile.
456        * 
457        * The logic here is as follows:
458        * 
459        * - We start reading from the end.
460        * - There must be a match _right_ from the "%s",
461        *   thus the i + 2.  
462        * - If there was a left hand match, this stuff
463        *   must not be counted again.  That's done by the
464        *   condition (j >= (lmatch ? i : 0)).
465        */
466
467       rmatch = 1;
468
469       for (r = 0, j = m_strlen(oldfile) - 1, k =
470            m_strlen(nametemplate) - 1;
471            j >= (lmatch ? i : 0) && k >= i + 2; j--, k--) {
472         if (nametemplate[k] != oldfile[j]) {
473           rmatch = 0;
474           break;
475         }
476       }
477
478       /* Now, check if we had a full match. */
479
480       if (k >= i + 2)
481         rmatch = 0;
482
483       if (lmatch)
484         *left = 0;
485       else
486         m_strncpy(left, sizeof(left), nametemplate, i);
487
488       if (rmatch)
489         *right = 0;
490       else
491         m_strcpy(right, sizeof(right), nametemplate + i + 2);
492
493       snprintf (newfile, nflen, "%s%s%s", left, oldfile, right);
494     }
495     else {
496       /* no "%s" in the name template. */
497       m_strcpy(newfile, nflen, nametemplate);
498     }
499   }
500
501   mutt_adv_mktemp (NULL, newfile, nflen);
502
503   if (rmatch && lmatch)
504     return 0;
505   else
506     return 1;
507
508 }
509
510 /* If rfc1524_expand_command() is used on a recv'd message, then
511  * the filename doesn't exist yet, but if its used while sending a message,
512  * then we need to rename the existing file.
513  *
514  * This function returns 0 on successful move, 1 on old file doesn't exist,
515  * 2 on new file already exists, and 3 on other failure.
516  */
517
518 /* note on access(2) use: No dangling symlink problems here due to
519  * safe_fopen().
520  */
521
522 int _mutt_rename_file (char *oldfile, char *newfile, int overwrite)
523 {
524   FILE *ofp, *nfp;
525
526   if (access (oldfile, F_OK) != 0)
527     return 1;
528   if (!overwrite && access (newfile, F_OK) == 0)
529     return 2;
530   if ((ofp = fopen (oldfile, "r")) == NULL)
531     return 3;
532   if ((nfp = safe_fopen (newfile, "w")) == NULL) {
533     fclose (ofp);
534     return 3;
535   }
536   mutt_copy_stream (ofp, nfp);
537   fclose (nfp);
538   fclose (ofp);
539   mutt_unlink (oldfile);
540   return 0;
541 }
542
543 int mutt_rename_file (char *oldfile, char *newfile)
544 {
545   return _mutt_rename_file (oldfile, newfile, 0);
546 }