masqmail

view src/masqmail.c @ 281:ea5f86e0a81c

modes are now enforced exclusive Other MTAs (exim, postfix) are more relaxing, but as combinations of exclusive modes are senseless we behave more obvious if we fail early. This makes understanding the behavior easier too.
author markus schnalke <meillo@marmaro.de>
date Tue, 07 Dec 2010 14:04:56 -0300
parents c35c59a36a2a
children ba53e648906f
line source
1 /* MasqMail
2 Copyright (C) 1999-2001 Oliver Kurth
3 Copyright (C) 2010 markus schnalke <meillo@marmaro.de>
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.
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.
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 */
20 #include <stdio.h>
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <netinet/in.h>
29 #include <netdb.h>
30 #include <syslog.h>
31 #include <signal.h>
33 #include <glib.h>
35 #include "masqmail.h"
37 /* mutually exclusive modes. Note that there is no 'queue daemon' mode.
38 It, as well as the distinction beween the two (non exclusive) daemon
39 (queue and listen) modes, is handled by flags.*/
40 enum mta_mode {
41 MODE_NONE = 0, /* to check if a mode was set */
42 MODE_ACCEPT, /* accept message on stdin (fallback mode) */
43 MODE_DAEMON, /* run as daemon */
44 MODE_RUNQUEUE, /* single queue run, online or offline */
45 MODE_SMTP, /* accept SMTP on stdin */
46 MODE_LIST, /* list queue */
47 MODE_MCMD, /* do queue manipulation */
48 MODE_VERSION, /* show version */
49 MODE_BI, /* fake ;-) */
50 };
51 enum mta_mode mta_mode = MODE_NONE;
53 char *pidfile = NULL;
54 volatile int sigterm_in_progress = 0;
56 static void
57 sigterm_handler(int sig)
58 {
59 if (sigterm_in_progress)
60 raise(sig);
61 sigterm_in_progress = 1;
63 if (pidfile) {
64 uid_t uid;
65 uid = seteuid(0);
66 if (unlink(pidfile) != 0)
67 logwrite(LOG_WARNING, "could not delete pid file %s: %s\n", pidfile, strerror(errno));
68 seteuid(uid); /* we exit anyway after this, just to be sure */
69 }
71 signal(sig, SIG_DFL);
72 raise(sig);
73 }
75 #ifdef ENABLE_IDENT /* so far used for that only */
76 static gboolean
77 is_in_netlist(gchar * host, GList * netlist)
78 {
79 guint hostip = inet_addr(host);
80 struct in_addr addr;
82 addr.s_addr = hostip;
83 if (addr.s_addr != INADDR_NONE) {
84 GList *node;
85 foreach(netlist, node) {
86 struct in_addr *net = (struct in_addr *) (node->data);
87 if ((addr.s_addr & net->s_addr) == net->s_addr)
88 return TRUE;
89 }
90 }
91 return FALSE;
92 }
93 #endif
95 /*
96 argv: the original argv
97 argp: number of arg (may get modified!)
98 cp: pointing to the char after the option
99 e.g. `-d 6' `-d6'
100 ^ ^
101 */
102 gchar*
103 get_optarg(char* argv[], gint* argp, char* cp)
104 {
105 if (*cp) {
106 /* this kind: -xval */
107 return cp;
108 }
109 cp = argv[*argp+1];
110 if (cp && (*cp != '-')) {
111 /* this kind: -x val */
112 (*argp)++;
113 return cp;
114 }
115 return NULL;
116 }
118 gboolean
119 write_pidfile(gchar * name)
120 {
121 FILE *fptr;
123 if ((fptr = fopen(name, "wt"))) {
124 fprintf(fptr, "%d\n", getpid());
125 fclose(fptr);
126 pidfile = strdup(name);
127 return TRUE;
128 }
129 logwrite(LOG_WARNING, "could not write pid file: %s\n", strerror(errno));
130 return FALSE;
131 }
133 /* on -bd or if -q has an argument */
134 static void
135 mode_daemon(gboolean do_listen, gint queue_interval, char *argv[])
136 {
137 guint pid;
139 /* daemon */
140 if (!conf.run_as_user) {
141 if ((conf.orig_uid != 0) && (conf.orig_uid != conf.mail_uid)) {
142 fprintf(stderr, "must be root or %s for daemon.\n", DEF_MAIL_USER);
143 exit(1);
144 }
145 }
147 /* reparent to init only if init is not already the parent */
148 if (getppid() != 1) {
149 if ((pid = fork()) > 0) {
150 exit(0);
151 } else if (pid < 0) {
152 logwrite(LOG_ALERT, "could not fork!\n");
153 exit(1);
154 }
155 }
157 signal(SIGTERM, sigterm_handler);
158 write_pidfile(PIDFILEDIR "/masqmail.pid");
160 conf.do_verbose = FALSE;
162 /* closing and reopening the log ensures that it is open afterwards
163 because it is possible that the log is assigned to fd 1 and gets
164 thus closes by fclose(stdout). Similar for the debugfile.
165 */
166 logclose();
167 fclose(stdin);
168 fclose(stdout);
169 fclose(stderr);
170 logopen();
172 logwrite(LOG_NOTICE, "%s %s daemon starting\n", PACKAGE, VERSION);
173 listen_port(do_listen ? conf.listen_addresses : NULL, queue_interval, argv);
174 }
176 /* -bs or called as smtpd or in.smtpd */
177 static void
178 mode_smtp()
179 {
180 /* accept smtp message on stdin */
181 /* write responses to stderr. */
183 struct sockaddr_in saddr;
184 gchar *peername = NULL;
185 int dummy = sizeof(saddr);
187 conf.do_verbose = FALSE;
189 if (!conf.run_as_user) {
190 seteuid(conf.orig_uid);
191 setegid(conf.orig_gid);
192 }
194 DEBUG(5) debugf("accepting smtp message on stdin\n");
196 if (getpeername(0, (struct sockaddr *) (&saddr), &dummy) == 0) {
197 peername = g_strdup(inet_ntoa(saddr.sin_addr));
198 } else if (errno != ENOTSOCK)
199 exit(1);
201 smtp_in(stdin, stderr, peername, NULL);
202 }
204 /* default mode if address args or -t is specified, or called as rmail */
205 static void
206 mode_accept(address * return_path, gchar * full_sender_name, guint accept_flags, char **addresses, int addr_cnt)
207 {
208 /* accept message on stdin */
209 accept_error err;
210 message *msg = create_message();
211 gint i;
212 pid_t pid;
214 if (return_path && !is_privileged_user(conf.orig_uid)) {
215 fprintf(stderr, "must be root, %s or in group %s for setting return path.\n", DEF_MAIL_USER, DEF_MAIL_GROUP);
216 exit(1);
217 }
219 if (!conf.run_as_user) {
220 seteuid(conf.orig_uid);
221 setegid(conf.orig_gid);
222 }
224 DEBUG(5) debugf("accepting message on stdin\n");
226 msg->received_prot = PROT_LOCAL;
228 /* warn if -t option and cmdline addr args */
229 if (addr_cnt && (accept_flags & ACC_RCPT_FROM_HEAD)) {
230 logwrite(LOG_ALERT, "command line address arguments are now *added* to the mail header\\\n");
231 logwrite(LOG_ALERT, " recipient addresses (instead of substracted) when -t is given.\\\n");
232 logwrite(LOG_ALERT, " this changed with version 0.3.1\n");
233 }
235 for (i = 0; i < addr_cnt; i++) {
236 if (addresses[i][0] == '|') {
237 logwrite(LOG_ALERT, "no pipe allowed as recipient address: %s\n", addresses[i]);
238 /* should we better ignore this one addr? */
239 exit(1);
240 }
241 msg->rcpt_list = g_list_append(msg->rcpt_list, create_address_qualified(addresses[i], TRUE, conf.host_name));
242 }
244 /* -f option */
245 msg->return_path = return_path;
247 /* -F option */
248 msg->full_sender_name = full_sender_name;
250 err = accept_message(stdin, msg, accept_flags);
252 switch (err) {
253 case AERR_OK:
254 /* to continue; all other cases exit */
255 break;
256 case AERR_EOF:
257 fprintf(stderr, "unexpected EOF.\n");
258 exit(1);
259 case AERR_NORCPT:
260 fprintf(stderr, "no recipients.\n");
261 exit(1);
262 case AERR_SIZE:
263 fprintf(stderr, "max message size exceeded.\n");
264 exit(1);
265 default:
266 /* should never happen: */
267 fprintf(stderr, "Unknown error (%d)\r\n", err);
268 exit(1);
269 }
271 if (!spool_write(msg, TRUE)) {
272 fprintf(stderr, "Could not write spool file\n");
273 exit(1);
274 }
276 /* here the mail is queued and thus in our responsibility */
277 logwrite(LOG_NOTICE, "%s <= %s with %s\n", msg->uid, addr_string(msg->return_path), prot_names[PROT_LOCAL]);
279 if (conf.do_queue) {
280 /* we're finished as we only need to queue it */
281 return;
282 }
284 /* deliver at once */
285 if ((pid = fork()) < 0) {
286 logwrite(LOG_ALERT, "could not fork for delivery, id = %s\n", msg->uid);
287 } else if (pid == 0) {
288 conf.do_verbose = FALSE;
289 fclose(stdin);
290 fclose(stdout);
291 fclose(stderr);
292 if (deliver(msg)) {
293 exit(0);
294 } else {
295 /*
296 TODO:
297 Should we really fail here? Because the mail is queued
298 already. If we fail the client might submit it again.
299 If at-once-delivery is seen as an additional best-effort
300 service, then we should still exit successful here.
301 */
302 exit(1);
303 }
304 }
305 }
307 /*
308 if -Mrm is given
310 currently only the `rm' command is supported
311 until this changes, we don't need any facility for further commands
312 return success if at least one message had been deleted
313 */
314 static int
315 manipulate_queue(char* cmd, char* id[])
316 {
317 gboolean ok = FALSE;
319 if (strcmp(cmd, "rm") != 0) {
320 fprintf(stderr, "unknown command %s\n", cmd);
321 return FALSE;
322 }
324 set_euidgid(conf.mail_uid, conf.mail_gid, NULL, NULL);
326 /* privileged users may delete any mail */
327 if (is_privileged_user(conf.orig_uid)) {
328 for (; *id; id++) {
329 fprintf(stderr, "id: %s\n", *id);
330 if (queue_delete(*id)) {
331 ok = TRUE;
332 }
333 }
334 return ok;
335 }
337 struct passwd *pw = getpwuid(conf.orig_uid);
338 if (!pw) {
339 fprintf(stderr, "could not find a passwd entry for uid %d: %s\n",
340 conf.orig_uid, strerror(errno));
341 return FALSE;
342 }
344 /* non-privileged users may only delete their own messages */
345 for (; *id; id++) {
346 message *msg = msg_spool_read(*id, FALSE);
348 fprintf(stderr, "id: %s\n", *id);
350 if (!msg->ident) {
351 fprintf(stderr, "message %s does not have an ident\n", *id);
352 continue;
353 }
354 if (strcmp(pw->pw_name, msg->ident) != 0) {
355 fprintf(stderr, "you do not own message id %s\n", *id);
356 continue;
357 }
359 if ( (msg->received_host || (msg->received_prot != PROT_LOCAL))
360 #ifdef ENABLE_IDENT
361 && !is_in_netlist(msg->received_host, conf.ident_trusted_nets)
362 #endif
363 ) {
364 fprintf(stderr, "message %s was not received locally or from a trusted network\n", *id);
365 continue;
366 }
368 ok = queue_delete(*id);
369 }
370 return ok;
371 }
373 /* -qo, -q (without argument), or called as runq */
374 /* TODO: are -qo and -q exclusively or not?
375 And how is this related to being a daemon? */
376 static int
377 run_queue(gboolean do_runq, gboolean do_runq_online, char* route_name)
378 {
379 int ret;
381 /* queue runs */
382 set_identity(conf.orig_uid, "queue run");
384 if (do_runq) {
385 ret = queue_run();
386 }
388 if (do_runq_online) {
389 if (route_name) {
390 conf.online_detect = g_strdup("argument");
391 set_online_name(route_name);
392 }
393 ret = queue_run_online();
394 }
395 return ret;
396 }
398 /* -bV or default mode if neither addr arg nor -t */
399 static void
400 mode_version(void)
401 {
402 gchar *with_resolver = "";
403 gchar *with_auth = "";
404 gchar *with_ident = "";
406 #ifdef ENABLE_RESOLVER
407 with_resolver = " +resolver";
408 #endif
409 #ifdef ENABLE_AUTH
410 with_auth = " +auth";
411 #endif
412 #ifdef ENABLE_IDENT
413 with_ident = " +ident";
414 #endif
416 printf("%s %s%s%s%s\n", PACKAGE, VERSION, with_resolver, with_auth, with_ident);
417 }
419 void
420 set_mode(enum mta_mode mode)
421 {
422 if (mta_mode && mta_mode!=mode) {
423 fprintf(stderr, "operation mode was already specified (%d vs. %d)\n", mta_mode, mode);
424 exit(1);
425 }
427 mta_mode = mode;
428 return;
429 }
431 int
432 main(int argc, char *argv[])
433 {
434 gchar *progname;
435 char* opt;
436 gint arg;
438 gboolean do_listen = FALSE;
439 gboolean do_runq = FALSE;
440 gboolean do_runq_online = FALSE;
441 gboolean do_queue = FALSE;
442 gint queue_interval = 0;
443 gchar *M_cmd = NULL;
444 gboolean opt_t = FALSE;
445 gboolean opt_i = FALSE;
446 gchar *conf_file = CONF_FILE;
447 gchar *route_name = NULL;
448 gchar *f_address = NULL;
449 address *return_path = NULL; /* may be changed by -f option */
450 gchar *full_sender_name = NULL;
451 gboolean do_verbose = FALSE;
452 gint debug_level = -1;
454 /* strip the path part */
455 progname = strrchr(argv[0], '/');
456 progname = (progname) ? progname+1 : argv[0];
458 if (strcmp(progname, "mailq") == 0) {
459 mta_mode = MODE_LIST;
460 } else if (strcmp(progname, "mailrm") == 0) {
461 mta_mode = MODE_MCMD;
462 M_cmd = "rm";
463 } else if (strcmp(progname, "runq") == 0) {
464 mta_mode = MODE_RUNQUEUE;
465 do_runq = TRUE;
466 } else if (strcmp(progname, "rmail") == 0) {
467 /* the `rmail' alias should probably be removed now
468 that we have the rmail script. But let's keep it
469 for some while for compatibility. 2010-06-19 */
470 mta_mode = MODE_ACCEPT;
471 opt_i = TRUE;
472 } else if (strcmp(progname, "smtpd") == 0 || strcmp(progname, "in.smtpd") == 0) {
473 mta_mode = MODE_SMTP;
474 }
476 /* parse cmd line */
477 for (arg=1; arg<argc && argv[arg][0]=='-'; arg++) {
478 opt = argv[arg] + 1; /* points to the char after the dash */
480 if (strcmp(opt, "-") == 0) {
481 /* everything after `--' are address arguments */
482 arg++;
483 break;
485 } else if (strcmp(opt, "bm") == 0) {
486 set_mode(MODE_ACCEPT);
488 } else if (strcmp(opt, "bd") == 0) {
489 set_mode(MODE_DAEMON);
490 do_listen = TRUE;
492 } else if (strcmp(opt, "bi") == 0) {
493 set_mode(MODE_BI);
495 } else if (strcmp(opt, "bs") == 0) {
496 set_mode(MODE_SMTP);
498 } else if (strcmp(opt, "bp") == 0) {
499 set_mode(MODE_LIST);
501 } else if (strcmp(opt, "bV") == 0) {
502 set_mode(MODE_VERSION);
504 } else if (strncmp(opt, "B", 1) == 0) {
505 /* we ignore this and throw the argument away */
506 get_optarg(argv, &arg, opt+1);
508 } else if (strncmp(opt, "C", 1) == 0) {
509 conf_file = get_optarg(argv, &arg, opt+1);
510 if (!conf_file) {
511 fprintf(stderr, "-C requires a filename as argument.\n");
512 exit(1);
513 }
515 } else if (strncmp(opt, "d", 1) == 0) {
516 if (getuid() != 0) {
517 fprintf(stderr, "only root may set the debug level.\n");
518 exit(1);
519 }
520 char *lvl = get_optarg(argv, &arg, opt+1);
521 if (!lvl) {
522 fprintf(stderr, "-d requires a number argument.\n");
523 exit(1);
524 }
525 debug_level = atoi(lvl);
527 } else if (strncmp(opt, "f", 1) == 0) {
528 /* set return path */
529 gchar *address = get_optarg(argv, &arg, opt+1);
530 if (!address) {
531 fprintf(stderr, "-f requires an address argument\n");
532 exit(1);
533 }
534 f_address = g_strdup(address);
536 } else if (strncmp(opt, "F", 1) == 0) {
537 full_sender_name = get_optarg(argv, &arg, opt+1);
538 if (!full_sender_name) {
539 fprintf(stderr, "-F requires a name argument\n");
540 exit(1);
541 }
543 } else if (strcmp(opt, "i") == 0) {
544 opt_i = TRUE;
546 } else if (strcmp(opt, "m") == 0) {
547 /* ignore -m (me too) switch (see man page) */
549 } else if (strcmp(opt, "Mrm") == 0) {
550 set_mode(MODE_MCMD);
551 M_cmd = "rm";
553 } else if (strcmp(opt, "odq") == 0) {
554 do_queue = TRUE;
556 } else if (strcmp(opt, "oi") == 0) {
557 opt_i = TRUE;
559 } else if (strncmp(opt, "o", 1) == 0) {
560 /* ignore all other -oXXX options */
562 } else if (strncmp(opt, "qo", 2) == 0) {
563 /* must be before the `q' check */
564 set_mode(MODE_RUNQUEUE);
565 do_runq = FALSE;
566 do_runq_online = TRUE;
567 /* can be NULL, then we use online detection method */
568 route_name = get_optarg(argv, &arg, opt+2);
570 } else if (strncmp(opt, "q", 1) == 0) {
571 /* must be after the `qo' check */
572 gchar *optarg;
574 optarg = get_optarg(argv, &arg, opt+1);
575 if (optarg) {
576 /* not just one single queue run but regular runs */
577 set_mode(MODE_DAEMON);
578 queue_interval = time_interval(optarg);
579 } else {
580 set_mode(MODE_RUNQUEUE);
581 do_runq = TRUE;
582 }
584 } else if (strcmp(opt, "t") == 0) {
585 opt_t = TRUE;
587 } else if (strcmp(opt, "v") == 0) {
588 do_verbose = TRUE;
590 } else {
591 fprintf(stderr, "unrecognized option `-%s'\n", opt);
592 exit(1);
593 }
594 }
596 if (!mta_mode && arg==argc && !opt_t) {
597 /*
598 In this case no rcpts can be found, thus no mail
599 can be sent, thus masqmail will always fail. We
600 rather do something better instead. This covers
601 also the case of calling masqmail without args.
602 */
603 mode_version();
604 exit(0);
605 }
607 if (mta_mode == MODE_VERSION) {
608 mode_version();
609 exit(0);
610 }
612 if (!mta_mode) {
613 mta_mode = MODE_ACCEPT;
614 }
616 /* initialize random generator */
617 srand(time(NULL));
618 /* ignore SIGPIPE signal */
619 signal(SIGPIPE, SIG_IGN);
621 /* close all possibly open file descriptors, except std{in,out,err} */
622 {
623 int i, max_fd = sysconf(_SC_OPEN_MAX);
625 if (max_fd <= 0) {
626 max_fd = 64;
627 }
628 for (i=3; i<max_fd; i++) {
629 close(i);
630 }
631 }
633 init_conf();
635 /* if we are not privileged, and the config file was changed we
636 implicetely set the the run_as_user flag and give up all
637 privileges.
639 So it is possible for a user to run his own daemon without
640 breaking security.
641 */
642 if ((strcmp(conf_file, CONF_FILE) != 0) && (conf.orig_uid != 0)) {
643 conf.run_as_user = TRUE;
644 seteuid(conf.orig_uid);
645 setegid(conf.orig_gid);
646 setuid(conf.orig_uid);
647 setgid(conf.orig_gid);
648 }
650 conf.log_dir = LOG_DIR;
651 logopen();
652 if (!read_conf(conf_file)) {
653 logwrite(LOG_ALERT, "SHUTTING DOWN due to problems reading config\n");
654 exit(5);
655 }
656 logclose();
658 if (do_queue) {
659 conf.do_queue = TRUE;
660 }
661 if (do_verbose) {
662 conf.do_verbose = TRUE;
663 }
664 if (debug_level >= 0) { /* if >= 0, it was given by argument */
665 conf.debug_level = debug_level;
666 }
668 /* It appears that changing to / ensures that we are never in
669 a directory which we cannot access. This situation could be
670 possible after changing identity.
671 Maybe we should only change to / if we not run as user, to
672 allow relative paths for log files in test setups for
673 instance.
674 */
675 chdir("/");
677 if (!conf.run_as_user) {
678 if (setgid(0) != 0) {
679 fprintf(stderr, "could not set gid to 0. Is the setuid bit set? : %s\n", strerror(errno));
680 exit(1);
681 }
682 if (setuid(0) != 0) {
683 fprintf(stderr, "could not gain root privileges. Is the setuid bit set? : %s\n", strerror(errno));
684 exit(1);
685 }
686 }
688 if (!logopen()) {
689 fprintf(stderr, "could not open log file\n");
690 exit(1);
691 }
693 DEBUG(1) debugf("masqmail %s starting\n", VERSION);
695 DEBUG(5) {
696 gchar **str = argv;
697 debugf("args: \n");
698 while (*str) {
699 debugf("%s \n", *str);
700 str++;
701 }
702 }
703 DEBUG(5) debugf("queue_interval = %d\n", queue_interval);
705 if (f_address) {
706 return_path = create_address_qualified(f_address, TRUE, conf.host_name);
707 g_free(f_address);
708 if (!return_path) {
709 fprintf(stderr, "invalid RFC821 address: %s\n", f_address);
710 exit(1);
711 }
712 }
714 switch (mta_mode) {
715 case MODE_DAEMON:
716 mode_daemon(do_listen, queue_interval, argv);
717 break;
719 case MODE_RUNQUEUE:
720 exit(run_queue(do_runq, do_runq_online, route_name) ? 0 : 1);
721 break;
723 case MODE_SMTP:
724 mode_smtp();
725 break;
727 case MODE_LIST:
728 queue_list();
729 break;
731 case MODE_BI:
732 exit(0);
733 break; /* well... */
735 case MODE_MCMD:
736 exit(manipulate_queue(M_cmd, &argv[arg]) ? 0 : 1);
737 break;
739 case MODE_ACCEPT:
740 {
741 guint accept_flags = (opt_t ? ACC_RCPT_FROM_HEAD : 0)
742 | (opt_i ? ACC_DOT_IGNORE : ACC_NODOT_RELAX);
743 mode_accept(return_path, full_sender_name, accept_flags, &(argv[arg]), argc - arg);
744 exit(0);
745 }
746 break;
748 default:
749 fprintf(stderr, "unknown mode: %d\n", mta_mode);
750 break;
751 }
753 logclose();
755 exit(0);
756 }