Let ncurses deal with that properly.
[apps/madmutt.git] / main.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2002 Thomas Roessler <roessler@does-not-exist.org>
5  * Copyright (C) 2004 g10 Code GmbH
6  *
7  * Parts written/modified by:
8  * Nico Golde <nion@muttng.org>
9  * Andreas Krennmair <ak@synflood.at>
10  *
11  * This file is part of mutt-ng, see http://www.muttng.org/.
12  * It's licensed under the GNU General Public License,
13  * please see the file GPL in the top level source directory.
14  */
15
16 #define MAIN_C 1
17
18 #include <lib-lib/lib-lib.h>
19
20 #include <sys/utsname.h>
21
22 #include <lib-lua/lib-lua.h>
23 #include <lib-sys/mutt_signal.h>
24 #include <lib-mime/mime.h>
25 #include <lib-ui/curses.h>
26 #include <lib-mx/mx.h>
27
28 #include "mutt.h"
29 #include "crypt.h"
30 #include "alias.h"
31 #include "buffy.h"
32 #include "sort.h"
33 #include "keymap.h"
34 #include "mutt_idna.h"
35 #include "mutt_sasl.h"
36
37 #ifdef HAVE_GETOPT_H
38 #include <getopt.h>
39 #else
40 extern char *optarg;
41 extern int optind;
42 #endif
43
44 #ifdef HAVE_LIBIDN
45 #include <stringprep.h>
46 #endif
47
48 #ifdef USE_NNTP
49 #include "nntp.h"
50 #endif
51
52 #ifdef USE_HCACHE
53 #if defined(HAVE_QDBM)
54 #include <depot.h>
55 #elif defined(HAVE_GDBM)
56 #include <gdbm.h>
57 #endif
58 #endif
59
60 #include <gnutls/gnutls.h>
61 #include <gpgme.h>
62
63 static const char *Notice = N_("\
64 Copyright (C) 1996-2002 Michael R. Elkins and others.\n\
65 Copyright (C) 2005 The Mutt-ng Team\n\
66 Copyright (C) 2006 Pierre Habouzit undation, Inc.\n\
67 This is free software.  You may redistribute copies of it under the terms of\n\
68 the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.\n\
69 There is NO WARRANTY, to the extent permitted by law.\n");
70
71 void mutt_exit (int code)
72 {
73   mutt_endwin (NULL);
74   exit (code);
75 }
76
77 static void mutt_usage (void)
78 {
79   puts (mutt_make_version());
80
81   puts
82     _("usage: madmutt [ -nRyzZ ] [ -e <cmd> ] [ -F <file> ] [ -m <type> ] [ -f <file> ]\n\
83        madmutt [ -nR ] [ -e <cmd> ] [ -F <file> ] -Q <query> [ -Q <query> ] [...]\n\
84        madmutt [ -nR ] [ -e <cmd> ] [ -F <file> ] -A <alias> [ -A <alias> ] [...]\n\
85        madmutt [ -nR ] [ -e <cmd> ] [ -F <file> ] -t");
86   puts
87     _("\
88        madmutt [ -nR ] [ -e <cmd> ] [ -F <file> ] -T\n\
89        madmutt [ -nx ] [ -e <cmd> ] [ -a <file> ] [ -F <file> ] [ -H <file> ] [ -i <file> ] [ -s <subj> ] [ -b <addr> ] [ -c <addr> ] <addr> [ ... ]\n\
90        madmutt [ -n ] [ -e <cmd> ] [ -F <file> ] -p\n\
91        madmutt -v\n\
92 \n\
93 options:\n\
94   -A <alias>\texpand the given alias\n\
95   -a <file>\tattach a file to the message\n\
96   -b <address>\tspecify a blind carbon-copy (BCC) address\n\
97   -c <address>\tspecify a carbon-copy (CC) address");
98   puts _("\
99   -e <command>\tspecify a command to be executed after initialization\n\
100   -f <file>\tspecify which mailbox to read\n\
101   -F <file>\tspecify an alternate muttrngc file\n\
102   -g <server>\tspecify a newsserver (if compiled with NNTP)\n\
103   -G\t\tselect a newsgroup (if compiled with NNTP)\n\
104   -H <file>\tspecify a draft file to read header and body from\n\
105   -i <file>\tspecify a file which Madmutt should include in the body");
106   puts _("\
107   -d <level>\t specify debugging level of Madmutt\n\
108   -m <type>\tspecify a default mailbox type\n\
109   -n\t\tcauses Madmutt not to read the system Madmuttrc\n\
110   -p\t\trecall a postponed message\n\
111   -Q <variable>\tquery a configuration variable\n\
112   -R\t\topen mailbox in read-only mode\n\
113   -s <subj>\tspecify a subject (must be in quotes if it has spaces)");
114   puts _("\
115   -t\t\tprint the value of all variables to stdout\n\
116   -T\t\tprint the value of all changed variables to stdout\n\
117   -v\t\tshow version and compile-time definitions\n\
118   -y\t\tselect a mailbox specified in your `mailboxes' list\n\
119   -z\t\texit immediately if there are no messages in the mailbox\n\
120   -Z\t\topen the first folder with new message, exit immediately if none\n\
121   -h\t\tthis help message");
122
123   exit (0);
124 }
125
126 static void show_version (void)
127 {
128   struct utsname uts;
129
130   puts (mutt_make_version());
131   puts (_(Notice));
132
133   uname (&uts);
134
135 #ifdef _AIX
136   printf ("System:\n  %s %s.%s", uts.sysname, uts.version, uts.release);
137 #elif defined (SCO)
138   printf ("System:\n  SCO %s", uts.release);
139 #else
140   printf ("System:\n  %s %s", uts.sysname, uts.release);
141 #endif
142
143   printf (" (%s)\nExternal Libraries:\n", uts.machine);
144
145 #ifdef NCURSES_VERSION
146   printf ("  ncurses %s\n", NCURSES_VERSION);
147 #endif
148
149 #ifdef _LIBICONV_VERSION
150   printf ("  libiconv %d.%d\n", _LIBICONV_VERSION >> 8,
151           _LIBICONV_VERSION & 0xff);
152 #endif
153
154 #ifdef HAVE_LIBIDN
155   printf ("  libidn %s (compiled with %s)\n",
156           stringprep_check_version (NULL), STRINGPREP_VERSION);
157 #endif
158
159 #ifdef USE_HCACHE
160 #if defined(HAVE_QDBM)
161   printf ("  qdbm %s\n", dpversion);
162 #elif defined(HAVE_GDBM)
163   printf ("  gdbm %s\n", gdbm_version);
164 #endif
165 #endif
166
167   printf ("  gnutls %s\n", LIBGNUTLS_VERSION);
168   printf ("  gpgme %s\n", GPGME_VERSION);
169   puts (_("Compile Options:"));
170
171   puts (
172 #ifdef USE_SETGID
173          "+USE_SETGID  "
174 #else
175          "-USE_SETGID  "
176 #endif
177 #ifdef USE_FCNTL
178          "+USE_FCNTL  "
179 #else
180          "-USE_FCNTL  "
181 #endif
182 #ifdef USE_FLOCK
183          "+USE_FLOCK   "
184 #else
185          "-USE_FLOCK   "
186 #endif
187 #ifdef USE_HCACHE
188          "+USE_HCACHE  "
189 #else
190          "-USE_HCACHE  "
191 #endif
192     );
193   puts (
194 #ifdef USE_NNTP
195          "+USE_NNTP  "
196 #else
197          "-USE_NNTP  "
198 #endif
199 #ifdef HAVE_LIBIDN
200          "+HAVE_LIBIDN  "
201 #else
202          "-HAVE_LIBIDN  "
203 #endif
204     );
205
206   puts (_("Built-In Defaults:"));
207   printf ("  +SENDMAIL=\"%s\"\n", SENDMAIL);
208   printf ("  +MAILPATH=\"%s\"\n", MAILPATH);
209   printf ("  +PKGDATADIR=\"%s\"\n", PKGDATADIR);
210   printf ("  +PKGDOCDIR=\"%s\"\n", PKGDOCDIR);
211   printf ("  +SYSCONFDIR=\"%s\"\n", SYSCONFDIR);
212   printf ("  +MIXMASTER=\"%s\"\n\n", MIXMASTER);
213
214   puts (_("MadMutt is based on Madmutt wich was based on Mutt before\n"));
215
216   exit (0);
217 }
218
219 static void start_curses (void)
220 {
221   km_init ();                   /* must come before mutt_init */
222   mutt_signal_initialize ();
223   if (initscr () == NULL) {
224     puts _("Error initializing terminal.");
225
226     exit (1);
227   }
228   mutt_signal_initialize ();
229   ci_start_color ();
230   keypad (stdscr, TRUE);
231   cbreak ();
232   noecho ();
233   typeahead (-1);               /* simulate smooth scrolling */
234   meta (stdscr, TRUE);
235 }
236
237 #define M_IGNORE  (1<<0)        /* -z */
238 #define M_BUFFY   (1<<1)        /* -Z */
239 #define M_NOSYSRC (1<<2)        /* -n */
240 #define M_RO      (1<<3)        /* -R */
241 #define M_SELECT  (1<<4)        /* -y */
242 #ifdef USE_NNTP
243 #define M_NEWS    (1<<5)        /* -g and -G */
244 #endif
245
246 __attribute__((format(printf, 1, 0)))
247 static void mutt_nocurses_error (const char *fmt, ...)
248 {
249     va_list ap;
250
251     va_start(ap, fmt);
252     vfprintf(stderr, fmt, ap);
253     va_end(ap);
254     fputc('\n', stderr);
255 }
256
257 int main (int argc, char **argv)
258 {
259   char folder[_POSIX_PATH_MAX] = "";
260   char *subject = NULL;
261   char *includeFile = NULL;
262   char *draftFile = NULL;
263   char *newMagic = NULL;
264   HEADER *msg = NULL;
265   string_list_t *attach = NULL;
266   string_list_t *commands = NULL;
267   string_list_t *queries = NULL;
268   string_list_t *alias_queries = NULL;
269   int sendflags = 0;
270   int flags = 0;
271   int version = 0;
272   int i;
273   int explicit_folder = 0;
274   int dump_variables = -1;
275
276   /* initialize random number for tmp file creation */ 
277   srand48((unsigned int) time (NULL));
278   
279   /* sanity check against stupid administrators */
280   
281   if (getegid () != getgid ()) {
282     fprintf (stderr, "%s: I don't want to run with privileges!\n", argv[0]);
283     exit (1);
284   }
285
286   setlocale (LC_ALL, "");
287   bindtextdomain (PACKAGE, MUTTLOCALEDIR);
288   textdomain (PACKAGE);
289   setlocale (LC_CTYPE, "");
290
291   mutt_error = mutt_message = mutt_nocurses_error;
292   srand48 (time (NULL));
293   umask (077);
294
295   p_clear(Options, countof(Options));
296   p_clear(QuadOptions, countof(QuadOptions));
297
298   while ((i = getopt(argc, argv, "A:a:b:F:f:c:e:H:s:i:hm:npQ:RTtvyzZ"
299 #ifdef USE_NNTP
300                                                                     "g:G"
301 #endif
302                     )) >= 0)
303     switch (i) {
304     case 'A':
305       alias_queries = mutt_add_list (alias_queries, optarg);
306       break;
307     case 'a':
308       if (strlen(optarg)<=512)
309         attach = mutt_add_list (attach, optarg);
310       else{
311         printf("too long arguments. exiting ...\n");
312         exit(1);
313       }
314       break;
315
316     case 'F':
317       m_strreplace(&Muttrc, optarg);
318       break;
319
320     case 'f':
321       m_strcpy(folder, sizeof(folder), optarg);
322       explicit_folder = 1;
323       break;
324
325     case 'b':
326     case 'c':
327       if (!msg)
328         msg = header_new();
329       if (!msg->env)
330         msg->env = envelope_new();
331       if (i == 'b')
332         msg->env->bcc = rfc822_parse_adrlist (msg->env->bcc, optarg);
333       else
334         msg->env->cc = rfc822_parse_adrlist (msg->env->cc, optarg);
335       break;
336
337     case 't':
338       dump_variables = 2;
339       break;
340
341     case 'T':
342       dump_variables = 1;
343       break;
344
345     case 'e':
346       commands = mutt_add_list (commands, optarg);
347       break;
348
349     case 'H':
350       draftFile = optarg;
351       break;
352
353     case 'i':
354       includeFile = optarg;
355       break;
356
357     case 'm':
358       /* should take precedence over .muttrc setting, so save it for later */
359       newMagic = optarg;
360       break;
361
362     case 'n':
363       flags |= M_NOSYSRC;
364       break;
365
366     case 'p':
367       sendflags |= SENDPOSTPONED;
368       break;
369
370     case 'Q':
371       queries = mutt_add_list (queries, optarg);
372       break;
373
374     case 'R':
375       flags |= M_RO;            /* read-only mode */
376       break;
377
378     case 's':
379       subject = optarg;
380       break;
381
382     case 'v':
383       version++;
384       break;
385
386     case 'y':                  /* My special hack mode */
387       flags |= M_SELECT;
388       break;
389
390 #ifdef USE_NNTP
391     case 'g':                  /* Specify a newsserver */
392       {
393         char buf[LONG_STRING];
394
395         snprintf (buf, sizeof (buf), "set nntp_host=%s", optarg);
396         commands = mutt_add_list (commands, buf);
397       }
398
399     case 'G':                  /* List of newsgroups */
400       flags |= M_SELECT | M_NEWS;
401       break;
402 #endif
403
404     case 'z':
405       flags |= M_IGNORE;
406       break;
407
408     case 'Z':
409       flags |= M_BUFFY | M_IGNORE;
410       break;
411
412     default:
413       mutt_usage ();
414     }
415
416   if (version) {
417     show_version ();
418   }
419
420   /* Check for a batch send. */
421   if (!isatty (0) || queries || alias_queries || dump_variables > 0) {
422     set_option (OPTNOCURSES);
423     sendflags = SENDBATCH;
424   }
425
426   /* This must come before mutt_init() because curses needs to be started
427      before calling the init_pair() function to set the color scheme.  */
428   if (!option (OPTNOCURSES))
429     start_curses ();
430
431   /* set defaults and read init files */
432   mutt_init (flags & M_NOSYSRC, commands);
433   string_list_wipe(&commands);
434
435   if (queries)
436     return mutt_query_variables (queries);
437   if (dump_variables > 0)
438     return (mutt_dump_variables (dump_variables-1));
439
440   if (alias_queries) {
441     int rv = 0;
442     address_t *a;
443
444     for (; alias_queries; alias_queries = alias_queries->next) {
445       if ((a = address_list_dup(alias_lookup(alias_queries->data)))) {
446         /* output in machine-readable form */
447         mutt_addrlist_to_idna (a, NULL);
448         mutt_write_address_list (a, stdout, 0, 0);
449         address_list_wipe(&a);
450       } else {
451         rv = 1;
452         printf ("%s\n", alias_queries->data);
453       }
454     }
455     return rv;
456   }
457
458   if (newMagic)
459     mx_set_magic (newMagic);
460
461   if (!option (OPTNOCURSES)) {
462     SETCOLOR (MT_COLOR_NORMAL);
463     clear ();
464     mutt_error = mutt_curses_error;
465     mutt_message = mutt_curses_message;
466   }
467
468   /* Create the Maildir directory if it doesn't exist. */
469   if (!option (OPTNOCURSES) && Maildir) {
470     struct stat sb;
471     char fpath[_POSIX_PATH_MAX];
472     char mesg[STRING];
473
474     m_strcpy(fpath, sizeof(fpath), Maildir);
475     mutt_expand_path (fpath, sizeof (fpath));
476     /* we're not connected yet - skip mail folder creation */
477     if (mx_get_magic (fpath) != M_IMAP)
478       if (stat (fpath, &sb) == -1 && errno == ENOENT) {
479         snprintf (mesg, sizeof (mesg), _("%s does not exist. Create it?"),
480                   Maildir);
481         if (mutt_yesorno (mesg, M_YES) == M_YES) {
482           if (mkdir (fpath, 0700) == -1 && errno != EEXIST)
483             mutt_error (_("Can't create %s: %s."), Maildir, strerror (errno));
484         }
485       }
486   }
487
488   if (sendflags & SENDPOSTPONED) {
489     if (!option (OPTNOCURSES))
490       mutt_flushinp ();
491     ci_send_message (SENDPOSTPONED, NULL, NULL, NULL, NULL);
492     mutt_endwin (NULL);
493   }
494   else if (subject || msg || sendflags || draftFile || includeFile || attach
495            || optind < argc) {
496     FILE *fin = NULL;
497     char buf[LONG_STRING];
498     char *tempfile = NULL, *infile = NULL;
499     char *bodytext = NULL;
500     FILE *fout;
501
502     if (!option (OPTNOCURSES))
503       mutt_flushinp ();
504
505     if (!msg)
506       msg = header_new();
507
508     if (draftFile)
509       infile = draftFile;
510     else {
511       if (!msg->env)
512         msg->env = envelope_new();
513
514       for (i = optind; i < argc; i++) {
515         if (url_check_scheme (argv[i]) == U_MAILTO)
516           url_parse_mailto (msg->env, &bodytext, argv[i]);
517         else
518           msg->env->to = rfc822_parse_adrlist (msg->env->to, argv[i]);
519       }
520
521       if (option (OPTAUTOEDIT) && !msg->env->to && !msg->env->cc) {
522         if (!option (OPTNOCURSES))
523           mutt_endwin (NULL);
524         fputs (_("No recipients specified.\n"), stderr);
525         exit (1);
526       }
527
528       if (subject)
529         msg->env->subject = m_strdup(subject);
530
531       if (includeFile)
532         infile = includeFile;
533     }
534
535     if (infile || bodytext) {
536       if (infile) {
537         if (m_strcmp("-", infile) == 0)
538           fin = stdin;
539         else {
540           char path[_POSIX_PATH_MAX];
541
542           m_strcpy(path, sizeof(path), infile);
543           mutt_expand_path (path, sizeof (path));
544           if ((fin = fopen (path, "r")) == NULL) {
545             if (!option (OPTNOCURSES))
546               mutt_endwin (NULL);
547             perror (path);
548             exit (1);
549           }
550         }
551       }
552       else
553         fin = NULL;
554
555       if (draftFile)
556         msg->env = mutt_read_rfc822_header (fin, NULL, 1, 0);
557
558       /* is the following if still needed? */
559
560       fout = m_tempfile(buf, sizeof(buf), NONULL(mod_core.tmpdir), NULL);
561       tempfile = m_strdup(buf);
562
563       if (tempfile) {
564         if (!fout) {
565           if (!option (OPTNOCURSES))
566             mutt_endwin (NULL);
567           perror (tempfile);
568           m_fclose(&fin);
569           p_delete(&tempfile);
570           exit (1);
571         }
572         if (fin)
573           mutt_copy_stream (fin, fout);
574         else if (bodytext)
575           fputs (bodytext, fout);
576         m_fclose(&fout);
577         if (fin && fin != stdin)
578           m_fclose(&fin);
579       }
580     }
581
582     p_delete(&bodytext);
583
584     if (attach) {
585       string_list_t *t = attach;
586       BODY *a = NULL;
587
588       while (t) {
589         if (a) {
590           a->next = mutt_make_file_attach (t->data);
591           a = a->next;
592         }
593         else
594           msg->content = a = mutt_make_file_attach (t->data);
595         if (!a) {
596           if (!option (OPTNOCURSES))
597             mutt_endwin (NULL);
598           fprintf (stderr, _("%s: unable to attach file.\n"), t->data);
599           string_list_wipe(&attach);
600           exit (1);
601         }
602         t = t->next;
603       }
604       string_list_wipe(&attach);
605     }
606
607     ci_send_message (sendflags, msg, tempfile, NULL, NULL);
608
609     if (!option (OPTNOCURSES))
610       mutt_endwin (NULL);
611   }
612   else {
613     if (flags & M_BUFFY) {
614       if (!buffy_check (0)) {
615         mutt_endwin _("No mailbox with new mail.");
616
617         exit (1);
618       }
619       folder[0] = 0;
620       buffy_next (folder, sizeof (folder));
621     }
622     else if (flags & M_SELECT) {
623 #ifdef USE_NNTP
624       if (flags & M_NEWS) {
625         set_option (OPTNEWS);
626         if (!(CurrentNewsSrv = mutt_select_newsserver (NewsServer))) {
627           mutt_endwin (Errorbuf);
628           exit (1);
629         }
630       } else
631 #endif
632       if (!Incoming.len) {
633         mutt_endwin _("No incoming mailboxes defined.");
634
635         exit (1);
636       }
637       folder[0] = 0;
638       mutt_select_file(folder, sizeof(folder), M_SEL_FOLDER | M_SEL_BUFFY,
639                        NULL, NULL);
640       if (!folder[0]) {
641         mutt_endwin (NULL);
642         exit (0);
643       }
644     }
645
646     if (!folder[0])
647       m_strcpy(folder, sizeof(folder), NONULL(Spoolfile));
648
649 #ifdef USE_NNTP
650     if (option (OPTNEWS)) {
651       unset_option (OPTNEWS);
652       nntp_expand_path (folder, sizeof (folder),
653                         &CurrentNewsSrv->conn->account);
654     } else
655 #endif
656       mutt_expand_path (folder, sizeof (folder));
657
658     m_strreplace(&CurrentFolder, folder);
659     m_strreplace(&LastFolder, folder);
660
661     if (flags & M_IGNORE) {
662       /* check to see if there are any messages in the folder */
663       switch (mx_check_empty (folder)) {
664       case -1:
665         mutt_endwin (strerror (errno));
666         exit (1);
667       case 1:
668         mutt_endwin _("Mailbox is empty.");
669         exit (1);
670       }
671     }
672
673     mutt_folder_hook (folder);
674
675     if ((Context = mx_open_mailbox (folder, ((flags & M_RO)
676                                              || option (OPTREADONLY)) ?
677                                     M_READONLY : 0, NULL))
678         || !explicit_folder) {
679       mutt_index_menu ();
680       if (option (OPTXTERMSETTITLES))
681         printf("\033]2;%s\007", NONULL(XtermLeave));
682       if (Context)
683         p_delete(&Context);
684     }
685     mutt_endwin (Errorbuf);
686   }
687
688   luaM_shutdown();
689   mutt_sasl_shutdown();
690   exit (0);
691 }