forked from The-McGrail-Foundation/MIMEDefang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mimedefang-multiplexor.c
5037 lines (4575 loc) · 139 KB
/
mimedefang-multiplexor.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************
*
* mimedefang-multiplexor.c
*
* Master program which manages a pool of e-mail scanning processes.
*
* Copyright (C) 2001-2005 Roaring Penguin Software Inc.
* http://www.roaringpenguin.com
*
* This program may be distributed under the terms of the GNU General
* Public License, Version 2, or (at your option) any later version.
*
***********************************************************************/
#include "config.h"
#include "event_tcp.h"
#include "mimedefang.h"
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#include <inttypes.h>
#define BIG_INT int64_t
#define BIG_INT_FMT PRIi64
#elif HAVE_LONG_LONG_INT
#define BIG_INT long long
#define BIG_INT_FMT "lld"
#else
#define BIG_INT long
#define BIG_INT_FMT "ld"
#endif
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <syslog.h>
#include <stdarg.h>
#include <pwd.h>
#ifdef HAVE_SETRLIMIT
#include <sys/resource.h>
static void limit_mem_usage(unsigned long rss, unsigned long as);
#endif
static char *pidfile = NULL;
static char *lockfile = NULL;
/* Number of file descriptors to close when forking */
#define CLOSEFDS 256
/* Weird case, but hey... */
#if defined(HAVE_WAIT3) && !defined(HAVE_SETRLIMIT)
#include <sys/resource.h>
#endif
#define STR(x) STR2(x)
#define STR2(x) #x
#define MAX_CMD_LEN 4096 /* Maximum length of command from mimedefang */
#define MAX_DIR_LEN 511 /* Maximum length of working directory */
#define MAX_QID_LEN 31 /* Maximum length of a Sendmail queue-id */
#define MAX_STATUS_LEN 64 /* Maximum length of status tag */
#define MAX_UNPRIV_CONNS 20 /* Maximum number of simultaneous unprivileged connections */
#define MAX_DOMAIN_LEN 128 /* Maximum length of a domain name for tracking per-domain recipok workers */
#define DOLOG Settings.doSyslog
#define WORKERNO(s) ((int) ((s) - AllWorkers))
/* A worker can be in one of four states:
Stopped -- Worker has no associated Perl process
Idle -- Worker has an associated process, but is not doing work
Busy -- Worker is processing a command
Killed -- Worker has been killed, but we're waiting for it to exit */
#define STATE_STOPPED 0
#define STATE_IDLE 1
#define STATE_BUSY 2
#define STATE_KILLED 3
#define NUM_WORKER_STATES 4
/* Structure of a worker process */
typedef struct Worker_t {
struct Worker_t *next; /* Link in free/busy list */
EventSelector *es; /* Event selector */
pid_t pid; /* Process ID of worker process */
int numRequests; /* Number of requests handled by worker */
int numScans; /* Number of messages scanned */
time_t idleTime; /* Time when worker became idle */
time_t activationTime; /* Time when worker was activated */
time_t firstReqTime; /* Time when worker received its first job */
time_t lastStateChange; /* Time when worker last changed state */
unsigned int activated; /* Activation order */
int workerStdin; /* Worker's stdin descriptor */
int workerStdout; /* Worker's stdout descriptor */
int workerStderr; /* Worker's stderr descriptor */
int workerStatusFD; /* File descriptor for worker status reports */
int clientFD; /* Client file descriptor */
int oom; /* Did worker run out of memory? */
EventTcpState *event; /* Pending event handler */
EventHandler *errHandler; /* Read handler for stderr */
EventHandler *statusHandler; /* Read handler for status descriptor */
EventHandler *termHandler; /* Timer after which we send SIGTERM */
char workdir[MAX_DIR_LEN+1]; /* Working directory for current scan */
char qid[MAX_QID_LEN+1]; /* Current Sendmail queue ID */
char status_tag[MAX_STATUS_LEN]; /* Status tag */
char domain[MAX_DOMAIN_LEN]; /* Current domain for recipok */
int generation; /* Worker's generation */
int state; /* Worker's state */
unsigned int histo; /* Kind of double-duty as histogram value */
int tick_no; /* Which tick are we handling? */
struct timeval start_cmd; /* Time when current command started */
int cmd; /* Which of the 4 commands with history? */
int last_cmd; /* Last command executed */
} Worker;
/* A queued request */
typedef struct Request_t {
struct Request_t *next; /* Next request in linked list */
EventSelector *es; /* Event selector */
EventHandler *timeoutHandler; /* Time out if we're queued too long */
int fd; /* File descriptor for client communication */
char *cmd; /* Command to send to worker */
} Request;
#define MAX_QUEUE_SIZE 128 /* Hard-coded limit */
Request RequestQueue[MAX_QUEUE_SIZE];
int NumQueuedRequests = 0;
Request *RequestHead;
Request *RequestTail;
Worker *AllWorkers; /* Array of all workers */
Worker *Workers[NUM_WORKER_STATES]; /* Lists of workers in each state */
int WorkerCount[NUM_WORKER_STATES]; /* Count of workers in each state */
int Generation = 0; /* Current generation */
int NumMsgsProcessed = 0; /* Number of messages processed since last
"msgs" query */
unsigned int Activations = 0; /* Incremented when a worker is activated */
static int Old_NumFreeWorkers = -1;
int NumUnprivConnections = 0;
static pid_t ParentPid = (pid_t) -1;
static char **Env;
struct Settings_t {
int minWorkers; /* Minimum number of workers to keep running */
int maxWorkers; /* Maximum possible number of workers */
int maxRecipokPerDomain; /* Maximum workers doing recipok for a given domain */
int maxRequests; /* Maximum number of requests per worker */
int maxLifetime; /* Maximum lifetime of a worker in seconds. */
int maxIdleTime; /* Excess workers should be killed after time */
int busyTimeout; /* Timeout after which we kill scanner */
int clientTimeout; /* Timeout for client request/reply */
int slewTime; /* Time to wait between workers' activation */
int waitTime; /* Minimum time to wait between activations */
int doSyslog; /* If true, log various things with syslog */
char const *sockName; /* Socket name for talking to mimedefang */
char const *progPath; /* Program to execute for filter */
char const *statsFile; /* File name for logging statistics */
char const *subFilter; /* Sub-filter to pass to filter */
char const *unprivSockName; /* Socket for unprivileged commands */
char const *spoolDir; /* Spool directory to chdir into */
FILE *statsFP; /* File pointer for stats file */
int statsToSyslog; /* If true, log stats using syslog */
int flushStats; /* If non-zero, flush stats file after write*/
unsigned long maxRSS; /* Maximum RSS for workers (if supported) */
unsigned long maxAS; /* Maximum address space for workers */
int logStatusInterval; /* How often to log status to syslog */
char const *mapSock; /* Socket for Sendmail TCP map requests */
int requestQueueSize;
int requestQueueTimeout;
int listenBacklog; /* Listen backlog */
int useEmbeddedPerl; /* Use embedded Perl interpreter */
char const *notifySock; /* Socket for notifications */
int tick_interval; /* Do "tick" request every tick_interval s */
int num_ticks; /* How many tick types to cycle through */
char const *syslog_label; /* Syslog label */
int wantStatusReports; /* Do we want status reports from workers? */
int debugWorkerScheduling; /* Log details about worker scheduling */
} Settings;
/* Structure for keeping statistics on number of messages processed in
last 10 minutes */
#define NO_CMD -2
#define OTHER_CMD -1
#define MIN_CMD 0
#define SCAN_CMD 0
#define RELAYOK_CMD 1
#define SENDEROK_CMD 2
#define RECIPOK_CMD 3
#define MAX_CMD 3
#define NUM_CMDS (MAX_CMD+1)
static char *CmdName[] = {
"scan",
"relayok",
"senderok",
"recipok"
};
/* Not real commands */
#define HISTORY_SECONDS (10*60)
#define HISTORY_HOURS 24
typedef struct {
time_t first; /* Time at which first entry was made */
time_t last; /* Time at which last entry was made */
int elapsed; /* Seconds or hours since epoch for this bucket */
int count; /* Number of messages processed */
int workers; /* TOTAL number of workers (active workers * count) */
int ms; /* TOTAL scan time in milliseconds */
int activated; /* Number of workers activated */
int reaped; /* Number of workers reaped */
} HistoryBucket;
static HistoryBucket history[NUM_CMDS][HISTORY_SECONDS];
static HistoryBucket hourly_history[NUM_CMDS][HISTORY_HOURS];
/* Pipe written on reception of SIGCHLD */
static int Pipe[2] = {-1, -1};
#ifndef HAVE_SIG_ATOMIC_T
#define sig_atomic_t int
#endif
static volatile sig_atomic_t ReapPending = 0;
static volatile sig_atomic_t HupPending = 0;
static volatile sig_atomic_t IntPending = 0;
static volatile sig_atomic_t CharPending = 0;
static int DebugEvents = 0;
static time_t LastWorkerActivation = (time_t) 0;
static time_t TimeOfProgramStart = (time_t) 0;
extern int drop_privs(char const *user, uid_t uid, gid_t gid);
extern int find_syslog_facility(char const *facility_name);
/* Prototypes */
#ifdef HAVE_WAIT3
static void log_worker_resource_usage(Worker *s, struct rusage *usage);
#endif
extern int make_notifier_socket(EventSelector *es, char const *name);
extern void notify_listeners(EventSelector *es, char const *msg);
extern void notify_worker_status(EventSelector *es, int workerno,
char const *status);
extern void notify_worker_state_change(EventSelector *es,
int workerno,
char const *old_state,
char const *new_state);
static Worker *findFreeWorker(int cmdno);
static void shutDescriptors(Worker *s);
static void reapTerminatedWorkers(int killed);
static Worker *findWorkerByPid(pid_t pid);
static int update_worker_status(Worker *s, char const *buf);
static void set_worker_status_from_command(Worker *s, char const *buf);
static pid_t activateWorker(Worker *s, char const *reason);
static void killWorker(Worker *s, char const *reason);
static void terminateWorker(EventSelector *es, int fd, unsigned int flags,
void *data);
static void nukeWorker(EventSelector *es, int fd, unsigned int flags,
void *data);
/* List-management functions */
static void unlinkFromList(Worker *s);
static void putOnList(Worker *s, int state);
static void handleAccept(EventSelector *es, int fd);
static void handleUnprivAccept(EventSelector *es, int fd);
static void handleCommand(EventSelector *es, int fd,
char *buf, int len, int flag, void *data);
static void handleWorkerReceivedCommand(EventSelector *es, int fd,
char *buf, int len, int flag,
void *data);
static void handleWorkerReceivedTick(EventSelector *es, int fd,
char *buf, int len, int flag,
void *data);
static void handleWorkerReceivedAnswer(EventSelector *es, int fd,
char *buf, int len, int flag,
void *data);
static void handleWorkerReceivedAnswerFromTick(EventSelector *es, int fd,
char *buf, int len, int flag,
void *data);
static void doScan(EventSelector *es, int fd, char *cmd);
static void doWorkerInfo(EventSelector *es, int fd, char *cmd);
static void doScanAux(EventSelector *es, int fd, char *cmd, int queueable);
static void doStatus(EventSelector *es, int fd);
static void doHelp(EventSelector *es, int fd, int unpriv);
static void doWorkerReport(EventSelector *es, int fd, int only_busy);
static void doLoad(EventSelector *es, int fd, int cmd);
static void doLoad1(EventSelector *es, int fd, int back);
static void doHourlyLoad(EventSelector *es, int fd, int cmd);
static void doHistogram(EventSelector *es, int fd);
static void doWorkerCommand(EventSelector *es, int fd, char *cmd);
static void doWorkerCommandAux(EventSelector *es, int fd, char *cmd, int queueable);
static void checkWorkerForExpiry(Worker *s);
static void handlePipe(EventSelector *es,
int fd, unsigned int flags, void *data);
static void handleWorkerStderr(EventSelector *es,
int fd,
unsigned int flags,
void *data);
static void handleWorkerStatusFD(EventSelector *es,
int fd,
unsigned int flags,
void *data);
static void childHandler(int sig);
static void hupHandler(int sig);
static void intHandler(int sig);
static void sigterm(int sig);
static void newGeneration(void);
static void handleIdleTimeout(EventSelector *es, int fd, unsigned int flags,
void *data);
static void doStatusLog(EventSelector *es, int fd, unsigned int flags,
void *data);
static void logWorkerReaped(Worker *s, int status);
static int queue_request(EventSelector *es, int fd, char *cmd);
static int handle_queued_request(void);
static void handleRequestQueueTimeout(EventSelector *es, int fd,
unsigned int flags, void *data);
static void statsReopenFile(void);
static void statsLog(char const *event, int workerno, char const *fmt, ...);
static void bringWorkersUpToMin(EventSelector *es, int fd, unsigned int flags,
void *data);
static void scheduleBringWorkersUpToMin(EventSelector *es);
static int minScheduled = 0;
static void schedule_tick(EventSelector *es, int tick_no);
static void handleMapAccept(EventSelector *es, int fd);
static void init_history(void);
static HistoryBucket *get_history_bucket(int cmd);
static HistoryBucket *get_hourly_history_bucket(int cmd);
static int get_history_totals(int cmd, time_t now, int back, int *total, int *workers, BIG_INT *ms, int *activated, int *reaped);
static int get_hourly_history_totals(int cmd, time_t now, int hours, int *total, int *workers, BIG_INT *ms, int *secs);
#define NUM_FREE_WORKERS (WorkerCount[STATE_IDLE] + WorkerCount[STATE_STOPPED])
#define NUM_RUNNING_WORKERS (WorkerCount[STATE_IDLE] + WorkerCount[STATE_BUSY] + WorkerCount[STATE_KILLED])
#define REPORT_FAILURE(msg) do { if (kidpipe[1] >= 0) { write(kidpipe[1], "E" msg, strlen(msg)+1); } else { fprintf(stderr, "%s\n", msg); } } while(0)
/**********************************************************************
* %FUNCTION: state_name
* %ARGUMENTS:
* state -- a state number
* %RETURNS:
* A string representing the name of the state
***********************************************************************/
static char const *
state_name(int state)
{
switch(state) {
case STATE_STOPPED: return "Stopped";
case STATE_IDLE: return "Idle";
case STATE_BUSY: return "Busy";
case STATE_KILLED: return "Killed";
}
return "Unknown";
}
/**********************************************************************
* %FUNCTION: state_name_lc
* %ARGUMENTS:
* state -- a state number
* %RETURNS:
* A string representing the name of the state in all lower-case
***********************************************************************/
static char const *
state_name_lc(int state)
{
switch(state) {
case STATE_STOPPED: return "stopped";
case STATE_IDLE: return "idle";
case STATE_BUSY: return "busy";
case STATE_KILLED: return "killed";
}
return "unknown";
}
/**********************************************************************
* %FUNCTION: reply_to_mimedefang_with_len
* %ARGUMENTS:
* es -- event selector
* fd -- file descriptor
* msg -- message to send back
* len -- length of message
* %RETURNS:
* The event associated with the reply, or NULL.
* %DESCRIPTION:
* Sends a final message back to mimedefang. Closes fd after message has
* been sent.
***********************************************************************/
static EventTcpState *
reply_to_mimedefang_with_len(EventSelector *es,
int fd,
char const *msg,
int len)
{
EventTcpState *e;
if (len == 0) {
/* Nothing to say. */
close(fd);
return NULL;
}
e = EventTcp_WriteBuf(es, fd, msg, len, NULL,
Settings.clientTimeout, NULL);
if (!e) {
if (DOLOG) {
syslog(LOG_ERR, "reply_to_mimedefang: EventTcp_WriteBuf failed: %m");
}
close(fd);
}
return e;
}
/**********************************************************************
* %FUNCTION: reply_to_mimedefang
* %ARGUMENTS:
* es -- event selector
* fd -- file descriptor
* msg -- message to send back
* %RETURNS:
* The event associated with the reply, or NULL.
* %DESCRIPTION:
* Sends a final message back to mimedefang.
***********************************************************************/
EventTcpState *
reply_to_mimedefang(EventSelector *es,
int fd,
char const *msg)
{
return reply_to_mimedefang_with_len(es, fd, msg, strlen(msg));
}
/**********************************************************************
* %FUNCTION: findWorkerByPid
* %ARGUMENTS:
* pid -- Process-ID we're looking for
* %RETURNS:
* The worker with given pid, or NULL if not found
* %DESCRIPTION:
* Searches the killed, idle and busy lists for specified worker.
***********************************************************************/
static Worker *
findWorkerByPid(pid_t pid)
{
Worker *s;
/* Most likely to be on killed list, so search there first */
s = Workers[STATE_KILLED];
while(s) {
if (s->pid == pid) return s;
s = s->next;
}
s = Workers[STATE_IDLE];
while(s) {
if (s->pid == pid) return s;
s = s->next;
}
s = Workers[STATE_BUSY];
while(s) {
if (s->pid == pid) return s;
s = s->next;
}
return NULL;
}
/**********************************************************************
* %FUNCTION: usage
* %ARGUMENTS:
* None
* %RETURNS:
* Nothing (exits)
* %DESCRIPTION:
* Prints usage information
***********************************************************************/
static void
usage(void)
{
fprintf(stderr, "mimedefang-multiplexor version %s\n", VERSION);
fprintf(stderr, "Usage: mimedefang-multiplexor [options]\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, " -h -- Print usage info and exit\n");
fprintf(stderr, " -v -- Print version and exit\n");
fprintf(stderr, " -t filename -- Log statistics to filename\n");
fprintf(stderr, " -p filename -- Write process-ID in filename\n");
fprintf(stderr, " -o file -- Use specified file as a lock file\n");
fprintf(stderr, " -T -- Log statistics to syslog\n");
fprintf(stderr, " -u -- Flush stats file after each write\n");
fprintf(stderr, " -Z -- Accept and process status updates from busy workers\n");
fprintf(stderr, " -U username -- Run as username, not root\n");
fprintf(stderr, " -m minWorkers -- Minimum number of workers\n");
fprintf(stderr, " -x maxWorkers -- Maximum number of workers\n");
fprintf(stderr, " -y recipokPerDom -- Maximum concurrent recipoks per domain\n");
fprintf(stderr, " -r maxRequests -- Maximum number of requests per worker\n");
fprintf(stderr, " -V maxLifetime -- Maximum lifetime of a worker in seconds\n");
fprintf(stderr, " -i idleTime -- Idle time (seconds) for killing excess workers\n");
fprintf(stderr, " -b busyTime -- Busy time (seconds) for killing hung workers\n");
fprintf(stderr, " -c cmdTime -- Request/reply transmission timeout (seconds)\n");
fprintf(stderr, " -w waitTime -- How long to wait between worker activations (seconds)\n");
fprintf(stderr, " -W waitTime -- Absolute minimum to wait between worker activations\n");
fprintf(stderr, " -z dir -- Spool directory\n");
fprintf(stderr, " -s sock -- UNIX-domain socket for communication\n");
fprintf(stderr, " -a u_sock -- Socket for unprivileged communication\n");
fprintf(stderr, " -f /dir/filter -- Specify full path of filter program\n");
fprintf(stderr, " -d -- Debug events in /var/log/mdefang-event-debug.log\n");
fprintf(stderr, " -l -- Log events with syslog\n");
#ifdef HAVE_SETRLIMIT
fprintf(stderr, " -R size -- Limit RSS to size kB (if supported on your OS)\n");
fprintf(stderr, " -M size -- Limit memory address space to size kB\n");
#endif
fprintf(stderr, " -L interval -- Log worker status every interval seconds\n");
fprintf(stderr, " -S facility -- Set syslog(3) facility\n");
fprintf(stderr, " -N sock -- Listen for Sendmail map requests on sock\n");
fprintf(stderr, " -O sock -- Listen for notification requests on sock\n");
fprintf(stderr, " -q size -- Size of request queue (default 0)\n");
fprintf(stderr, " -Q timeout -- Timeout for queued requests\n");
fprintf(stderr, " -I backlog -- 'backlog' argument for listen on multiplexor socket\n");
fprintf(stderr, " -D -- Do not become a daemon (stay in foreground)\n");
fprintf(stderr, " -X interval -- Run a 'tick' request every interval seconds\n");
fprintf(stderr, " -P n -- Run 'n' parallel tick requests\n");
fprintf(stderr, " -Y label -- Set syslog label to 'label'\n");
fprintf(stderr, " -G -- Make sockets group-writable\n");
#ifdef EMBED_PERL
fprintf(stderr, " -E -- Use embedded Perl interpreter\n");
#endif
exit(EXIT_FAILURE);
}
static int
set_sigchld_handler(void)
{
struct sigaction act;
/* Set signal handler for SIGCHLD */
act.sa_handler = childHandler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NOCLDSTOP | SA_RESTART;
return sigaction(SIGCHLD, &act, NULL);
}
/**********************************************************************
* %FUNCTION: main
* %ARGUMENTS:
* argc, argv -- usual suspects
* %RETURNS:
* Nothing -- runs in an infinite loop
* %DESCRIPTION:
* Main program
***********************************************************************/
int
main(int argc, char *argv[], char **env)
{
int i;
int sock, unpriv_sock;
int c;
int n;
int pidfile_fd = -1;
int lockfile_fd = -1;
char *user = NULL;
char *options;
int facility = LOG_MAIL;
int kidpipe[2] = {-1, -1};
char kidmsg[256];
time_t now;
mode_t socket_umask = 077;
mode_t file_umask = 077;
EventSelector *es;
struct sigaction act;
struct timeval t;
struct passwd *pw = NULL;
int nodaemon = 0;
/* Record program start time */
TimeOfProgramStart = time(NULL);
Env = env;
/* Paranoia time */
umask(077);
/* Paranoia time II */
if (getuid() != geteuid()) {
fprintf(stderr, "ERROR: %s is NOT intended to run suid! Exiting.\n",
argv[0]);
exit(EXIT_FAILURE);
}
if (getgid() != getegid()) {
fprintf(stderr, "ERROR: %s is NOT intended to run sgid! Exiting.\n",
argv[0]);
exit(EXIT_FAILURE);
}
Settings.minWorkers = 0;
Settings.maxWorkers = 2;
Settings.maxRecipokPerDomain = 0;
Settings.maxRequests = 500;
Settings.maxLifetime = 0; /* Unlimited */
Settings.maxIdleTime = 300;
Settings.busyTimeout = 120;
Settings.slewTime = 3;
Settings.waitTime = 0;
Settings.clientTimeout = 10;
Settings.doSyslog = 0;
Settings.spoolDir = NULL;
Settings.sockName = NULL;
Settings.unprivSockName = NULL;
Settings.progPath = MIMEDEFANG_PL;
Settings.subFilter = NULL;
Settings.statsFile = NULL;
Settings.statsFP = NULL;
Settings.flushStats = 0;
Settings.statsToSyslog = 0;
Settings.maxRSS = 0;
Settings.maxAS = 0;
Settings.logStatusInterval = 0;
Settings.requestQueueSize = 0;
Settings.requestQueueTimeout = 30;
Settings.listenBacklog = -1;
Settings.useEmbeddedPerl = 0;
Settings.notifySock = NULL;
Settings.tick_interval = 0;
Settings.num_ticks = 1;
Settings.mapSock = NULL;
Settings.wantStatusReports = 0;
Settings.debugWorkerScheduling = 0;
#ifndef HAVE_SETRLIMIT
options = "GAa:Tt:um:x:y:r:i:b:c:s:hdlf:p:o:w:F:W:U:S:q:Q:I:DEO:X:Y:N:vZP:z:V:";
#else
options = "GAa:Tt:um:x:y:r:i:b:c:s:hdlf:p:o:w:F:W:U:S:q:Q:L:R:M:I:DEO:X:Y:N:vZP:z:V:";
#endif
while((c = getopt(argc, argv, options)) != -1) {
switch(c) {
case 'G':
socket_umask = 007;
file_umask = 027;
break;
case 'A':
Settings.debugWorkerScheduling = 1;
break;
case 'z':
Settings.spoolDir = strdup(optarg);
if (!Settings.spoolDir) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'Z':
Settings.wantStatusReports = 1;
break;
case 'a':
Settings.unprivSockName = strdup(optarg);
if (!Settings.unprivSockName) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'v':
printf("mimedefang-multiplexor version %s\n", VERSION);
exit(EXIT_SUCCESS);
case 'E':
#ifdef EMBED_PERL
Settings.useEmbeddedPerl = 1;
#else
fprintf(stderr, "mimedefang-multiplexor compiled without support for embedded perl. Ignoring -E flag.\n");
#endif
break;
case 'D':
nodaemon = 1;
break;
case 'P':
if (sscanf(optarg, "%d", &n) != 1) usage();
if (n < 1) {
n = 1;
} else if (n > 30) {
n = 30;
}
Settings.num_ticks = n;
break;
case 'I':
if (sscanf(optarg, "%d", &n) != 1) usage();
if (n < 5) {
n = 5;
} else if (n > 200) {
n = 200;
}
Settings.listenBacklog = n;
break;
case 'q':
if (sscanf(optarg, "%d", &n) != 1) usage();
if (n <= 0) {
n = 0;
} else if (n > MAX_QUEUE_SIZE) {
fprintf(stderr, "%s: Request queue size %d too big (%d max)\n",
argv[0], n, MAX_QUEUE_SIZE);
exit(EXIT_FAILURE);
}
Settings.requestQueueSize = n;
break;
case 'X':
if (sscanf(optarg, "%d", &n) != 1) usage();
if (n < 0) {
n = 0;
}
Settings.tick_interval = n;
break;
case 'Q':
if (sscanf(optarg, "%d", &n) != 1) usage();
if (n <= 1) {
n = 1;
} else if (n > 600) {
n = 600;
}
Settings.requestQueueTimeout = n;
break;
case 'S':
facility = find_syslog_facility(optarg);
if (facility < 0) {
fprintf(stderr, "%s: Unknown syslog facility %s\n",
argv[0], optarg);
exit(EXIT_FAILURE);
}
break;
case 'L':
if (sscanf(optarg, "%d", &n) != 1) usage();
if (n <= 0) {
n = 0;
} else if (n < 5) {
n = 5;
}
Settings.logStatusInterval = n;
break;
case 'R':
case 'M':
if (sscanf(optarg, "%d", &n) != 1) usage();
if (c == 'R') {
Settings.maxRSS = (unsigned long) n;
} else {
Settings.maxAS = (unsigned long) n;
}
break;
case 'Y':
Settings.syslog_label = strdup(optarg);
if (!Settings.syslog_label) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'O':
Settings.notifySock = strdup(optarg);
if (!Settings.notifySock) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'N':
Settings.mapSock = strdup(optarg);
if (!Settings.mapSock) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'U':
/* User to run as */
if (user) {
free(user);
}
user = strdup(optarg);
if (!user) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'F':
/* Sub-filter */
if (Settings.subFilter) {
free((void *) Settings.subFilter);
}
Settings.subFilter = strdup(optarg);
if (!Settings.subFilter) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'W':
/* Absolute minimum to wait between each worker's start-up */
if (sscanf(optarg, "%d", &Settings.waitTime) != 1) usage();
if (Settings.waitTime < 0) {
Settings.waitTime = 0;
}
break;
case 'w':
/* How long to wait between each worker's start-up */
if (sscanf(optarg, "%d", &Settings.slewTime) != 1) usage();
if (Settings.slewTime < 1) {
Settings.slewTime = 1;
}
break;
case 'p':
/* Write our pid to this file */
if (pidfile != NULL) free(pidfile);
pidfile = strdup(optarg);
if (!pidfile) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'o':
/* Use this as our lock file */
if (lockfile != NULL) free(lockfile);
lockfile = strdup(optarg);
if (!lockfile) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'f':
/* Filter program */
if (optarg[0] != '/') {
fprintf(stderr, "%s: -f: You must supply an absolute path for filter program\n", argv[0]);
exit(EXIT_FAILURE);
}
Settings.progPath = strdup(optarg);
if (!Settings.progPath) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'u':
Settings.flushStats = 1;
break;
case 't':
Settings.statsFile = strdup(optarg);
if (!Settings.statsFile) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'T':
Settings.statsToSyslog = 1;
break;
case 'l':
Settings.doSyslog = 1;
break;
case 'd':
DebugEvents = 1;
break;
case 'h':
usage();
break;
case 'm':
if (sscanf(optarg, "%d", &Settings.minWorkers) != 1) usage();
if (Settings.minWorkers < 1) Settings.minWorkers = 1;
break;
case 'x':
if (sscanf(optarg, "%d", &Settings.maxWorkers) != 1) usage();
break;
case 'y':
if (sscanf(optarg, "%d", &Settings.maxRecipokPerDomain) != 1) usage();
break;
case 'r':
if (sscanf(optarg, "%d", &Settings.maxRequests) != 1) usage();
if (Settings.maxRequests < 1) Settings.maxRequests = 1;
break;
case 'V':
if (sscanf(optarg, "%d", &Settings.maxLifetime) != 1) usage();
if (Settings.maxLifetime <= 0) {
Settings.maxLifetime = -1;
}
break;
case 'i':
if (sscanf(optarg, "%d", &Settings.maxIdleTime) != 1) usage();
if (Settings.maxIdleTime < 10) Settings.maxIdleTime = 10;
break;
case 'b':
if (sscanf(optarg, "%d", &Settings.busyTimeout) != 1) usage();
if (Settings.busyTimeout < 10) Settings.busyTimeout = 10;
break;
case 'c':
if (sscanf(optarg, "%d", &Settings.clientTimeout) != 1) usage();
if (Settings.clientTimeout < 10) Settings.clientTimeout = 10;
break;
case 's':
Settings.sockName = strdup(optarg);
if (!Settings.sockName) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
default:
fprintf(stderr, "\n");
usage();
}
}
/* Set spooldir, if it's not set */
if (!Settings.spoolDir) {
Settings.spoolDir = SPOOLDIR;
}
/* Set sockName, if it's not set */
if (!Settings.sockName) {
Settings.sockName = malloc(strlen(Settings.spoolDir) + strlen("/mimedefang-multiplexor.sock") + 1);
if (!Settings.sockName) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
exit(EXIT_FAILURE);
}
strcpy((char *) Settings.sockName, Settings.spoolDir);
strcat((char *) Settings.sockName, "/mimedefang-multiplexor.sock");
}
/* Open the pidfile as root. We'll write the pid later on in the grandchild */
if (pidfile) {
pidfile_fd = open(pidfile, O_RDWR|O_CREAT, 0666);
if (pidfile_fd < 0) {
syslog(LOG_ERR, "Could not open PID file %s: %m", pidfile);
exit(EXIT_FAILURE);
}
/* It needs to be world-readable */
fchmod(pidfile_fd, 0644);
}
/* Drop privileges */
if (user) {
pw = getpwnam(user);
if (!pw) {
fprintf(stderr, "%s: Unknown user '%s'\n", argv[0], user);
exit(EXIT_FAILURE);
}
if (drop_privs(user, pw->pw_uid, pw->pw_gid) < 0) {
exit(EXIT_FAILURE);
}
free(user);
}
/* Warn */
if (!getuid() || !geteuid()) {
fprintf(stderr,
"ERROR: You must not run mimedefang-multiplexor as root.\n"
"Use the -U option to set a non-root user.\n");
exit(EXIT_FAILURE);
}
if (chdir(Settings.spoolDir) < 0) {
fprintf(stderr, "%s: Unable to chdir(%s): %s\n",
argv[0], Settings.spoolDir, strerror(errno));
exit(EXIT_FAILURE);
}
/* Fix obvious stupidities */
if (Settings.maxWorkers < 1) {
Settings.maxWorkers = 1;
}
if (Settings.minWorkers < 1) {
Settings.minWorkers = 1;
}
if (Settings.minWorkers > Settings.maxWorkers) {
Settings.minWorkers = Settings.maxWorkers;
}