File: smtpctl.c

package info (click to toggle)
opensmtpd 6.0.2p1-2%2Bdeb9u3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 4,144 kB
  • sloc: ansic: 36,913; sh: 11,163; yacc: 2,333; makefile: 413; awk: 339
file content (1437 lines) | stat: -rw-r--r-- 30,541 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
/*	$OpenBSD: smtpctl.c,v 1.149 2016/04/29 08:55:08 eric Exp $	*/

/*
 * Copyright (c) 2013 Eric Faurot <eric@openbsd.org>
 * Copyright (c) 2006 Gilles Chehade <gilles@poolp.org>
 * Copyright (c) 2006 Pierre-Yves Ritschard <pyr@openbsd.org>
 * Copyright (c) 2005 Claudio Jeker <claudio@openbsd.org>
 * Copyright (c) 2004, 2005 Esben Norby <norby@openbsd.org>
 * Copyright (c) 2003 Henning Brauer <henning@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "includes.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/queue.h>
#include <sys/tree.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <sys/stat.h>

#include <net/if.h>
/* #include <net/if_media.h> */
/* #include <net/if_types.h> */
#include <netinet/in.h>
#include <arpa/inet.h>

#include <err.h>
#include <errno.h>
#include <event.h>
#include <fts.h>
#include <imsg.h>
#include <inttypes.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <limits.h>

#include "smtpd.h"
#include "parser.h"
#include "log.h"

#ifndef PATH_GZCAT
#define PATH_GZCAT	"/usr/bin/gzcat"
#endif
#define	PATH_CAT	"/bin/cat"
#define PATH_QUEUE	"/queue"
#ifndef PATH_ENCRYPT
#define PATH_ENCRYPT	"/usr/bin/encrypt"
#endif

#ifndef HAVE_DB_API
#define	makemap(x, y, z)	1
#endif


int srv_connect(void);
int srv_connected(void);

void usage(void);
static void show_queue_envelope(struct envelope *, int);
static void getflag(uint *, int, char *, char *, size_t);
static void display(const char *);
static int str_to_trace(const char *);
static int str_to_profile(const char *);
static void show_offline_envelope(uint64_t);
static int is_gzip_fp(FILE *);
static int is_encrypted_fp(FILE *);
static int is_encrypted_buffer(const char *);
static int is_gzip_buffer(const char *);
static FILE *offline_file(void);
static void sendmail_compat(int, char **);

extern char	*__progname;
int		 sendmail;
struct smtpd	*env;
struct imsgbuf	*ibuf;
struct imsg	 imsg;
char		*rdata;
size_t		 rlen;
time_t		 now;

struct queue_backend queue_backend_null;
struct queue_backend queue_backend_proc;
struct queue_backend queue_backend_ram;

__dead void
usage(void)
{
	if (sendmail)
		fprintf(stderr, "usage: %s [-tv] [-f from] [-F name] to ...\n",
		    __progname);
	else
		fprintf(stderr, "usage: %s command [argument ...]\n",
		    __progname);
	exit(1);
}

void stat_increment(const char *k, size_t v)
{
}

void stat_decrement(const char *k, size_t v)
{
}

int
srv_connect(void)
{
	struct sockaddr_un	s_un;
	int			ctl_sock, saved_errno;

	/* connect to smtpd control socket */
	if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
		err(1, "socket");

	memset(&s_un, 0, sizeof(s_un));
	s_un.sun_family = AF_UNIX;
	(void)strlcpy(s_un.sun_path, SMTPD_SOCKET, sizeof(s_un.sun_path));
	if (connect(ctl_sock, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) {
		saved_errno = errno;
		close(ctl_sock);
		errno = saved_errno;
		return (0);
	}

	ibuf = xcalloc(1, sizeof(struct imsgbuf), "smtpctl:srv_connect");
	imsg_init(ibuf, ctl_sock);

	return (1);
}

int
srv_connected(void)
{
	return ibuf != NULL ? 1 : 0;
}

FILE *
offline_file(void)
{
	char	path[PATH_MAX];
	int	fd;
	FILE   *fp;

	if (!bsnprintf(path, sizeof(path), "%s%s/%lld.XXXXXXXXXX", PATH_SPOOL,
		PATH_OFFLINE, (long long int) time(NULL)))
		err(EX_UNAVAILABLE, "snprintf");

	if ((fd = mkstemp(path)) == -1 || (fp = fdopen(fd, "w+")) == NULL) {
		if (fd != -1)
			unlink(path);
		err(EX_UNAVAILABLE, "cannot create temporary file %s", path);
	}

	if (fchmod(fd, 0600) == -1) {
		unlink(path);
		err(EX_SOFTWARE, "fchmod");
	}

	return fp;
}


static void
srv_flush(void)
{
	if (imsg_flush(ibuf) == -1)
		err(1, "write error");
}

static void
srv_send(int msg, const void *data, size_t len)
{
	if (ibuf == NULL && !srv_connect())
		errx(1, "smtpd doesn't seem to be running");
	imsg_compose(ibuf, msg, IMSG_VERSION, 0, -1, data, len);
}

static void
srv_recv(int type)
{
	ssize_t	n;

	srv_flush();

	while (1) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			errx(1, "imsg_get error");
		if (n) {
			if (imsg.hdr.type == IMSG_CTL_FAIL &&
			    imsg.hdr.peerid != 0 &&
			    imsg.hdr.peerid != IMSG_VERSION)
				errx(1, "incompatible smtpctl and smtpd");
			if (type != -1 && type != (int)imsg.hdr.type)
				errx(1, "bad message type");
			rdata = imsg.data;
			rlen = imsg.hdr.len - sizeof(imsg.hdr);
			break;
		}

		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
			errx(1, "imsg_read error");
		if (n == 0)
			errx(1, "pipe closed");
	}
}

static void
srv_read(void *dst, size_t sz)
{
	if (sz == 0)
		return;
	if (rlen < sz)
		errx(1, "message too short");
	if (dst)
		memmove(dst, rdata, sz);
	rlen -= sz;
	rdata += sz;
}

static void
srv_get_int(int *i)
{
	uint8_t type;

	srv_read(&type, 1);
	srv_read(i, sizeof(*i));
}

static void
srv_get_time(time_t *t)
{
	uint8_t type;

	srv_read(&type, 1);
	srv_read(t, sizeof(*t));
}

static void
srv_get_evpid(uint64_t *evpid)
{
	uint8_t type;

	srv_read(&type, 1);
	srv_read(evpid, sizeof(*evpid));
}

static void
srv_get_envelope(struct envelope *evp)
{
	uint64_t	 evpid;
	uint8_t		 type;
	size_t		 s;
	const void	*d;

	srv_get_evpid(&evpid);
	srv_read(&type, sizeof(type));
	srv_read(&s, sizeof(s));
	d = rdata;
	srv_read(NULL, s);

	envelope_load_buffer(evp, d, s - 1);
	evp->id = evpid;
}

static void
srv_end(void)
{
	if (rlen)
		errx(1, "bogus data");
	imsg_free(&imsg);
}

static int
srv_check_result(int verbose_)
{
	srv_recv(-1);
	srv_end();

	switch (imsg.hdr.type) {
	case IMSG_CTL_OK:
		if (verbose_)
			printf("command succeeded\n");
		return (0);
	case IMSG_CTL_FAIL:
		if (verbose_) {
			if (rlen)
				printf("command failed: %s\n", rdata);
			else
				printf("command failed\n");
		}
		return (1);
	default:
		errx(1, "wrong message in response: %u", imsg.hdr.type);
	}
	return (0);
}

static int
srv_iter_messages(uint32_t *res)
{
	static uint32_t	*msgids = NULL, from = 0;
	static size_t	 n, curr;
	static int	 done = 0;

	if (done)
		return (0);

	if (msgids == NULL) {
		srv_send(IMSG_CTL_LIST_MESSAGES, &from, sizeof(from));
		srv_recv(IMSG_CTL_LIST_MESSAGES);
		if (rlen == 0) {
			srv_end();
			done = 1;
			return (0);
		}
		msgids = malloc(rlen);
		n = rlen / sizeof(*msgids);
		srv_read(msgids, rlen);
		srv_end();

		curr = 0;
		from = msgids[n - 1] + 1;
		if (from == 0)
			done = 1;
	}

	*res = msgids[curr++];
	if (curr == n) {
		free(msgids);
		msgids = NULL;
	}

	return (1);
}

static int
srv_iter_envelopes(uint32_t msgid, struct envelope *evp)
{
	static uint32_t	currmsgid = 0;
	static uint64_t	from = 0;
	static int	done = 0, need_send = 1, found;
	int		flags;
	time_t		nexttry;

	if (currmsgid != msgid) {
		if (currmsgid != 0 && !done)
			errx(1, "must finish current iteration first");
		currmsgid = msgid;
		from = msgid_to_evpid(msgid);
		done = 0;
		found = 0;
		need_send = 1;
	}

	if (done)
		return (0);

    again:
	if (need_send) {
		found = 0;
		srv_send(IMSG_CTL_LIST_ENVELOPES, &from, sizeof(from));
	}
	need_send = 0;

	srv_recv(IMSG_CTL_LIST_ENVELOPES);
	if (rlen == 0) {
		srv_end();
		if (!found || evpid_to_msgid(from) != msgid) {
			done = 1;
			return (0);
		}
		need_send = 1;
		goto again;
	}

	srv_get_int(&flags);
	srv_get_time(&nexttry);
	srv_get_envelope(evp);
	srv_end();

	evp->flags |= flags;
	evp->nexttry = nexttry;

	from = evp->id + 1;
	found++;
	return (1);
}

static int
srv_iter_evpids(uint32_t msgid, uint64_t *evpid, int *offset)
{
	static uint64_t	*evpids = NULL, *tmp;
	static int	 n, alloc = 0;
	struct envelope	 evp;

	if (evpids == NULL) {
		alloc = 1000;
		evpids = calloc(alloc, sizeof(*evpids));
		if (evpids == NULL)
			err(1, "calloc");
	}

	if (*offset == 0) {
		n = 0;
		while (srv_iter_envelopes(msgid, &evp)) {
			if (n == alloc) {
				alloc += 256;
				tmp = reallocarray(evpids, alloc,
				    sizeof(*evpids));
				if (tmp == NULL)
					err(1, "reallocarray");
				evpids = tmp;
			}
			evpids[n++] = evp.id;
		}
	}

	if (*offset >= n)
		return (0);
	*evpid = evpids[*offset];
	*offset += 1;
	return (1);
}

static void
srv_foreach_envelope(struct parameter *argv, int ctl, size_t *total, size_t *ok)
{
	uint32_t	msgid;
	uint64_t	evpid;
	int		i;

	*total = 0;
	*ok = 0;

	if (argv == NULL) {
		while (srv_iter_messages(&msgid)) {
			i = 0;
			while (srv_iter_evpids(msgid, &evpid, &i)) {
				*total += 1;
				srv_send(ctl, &evpid, sizeof(evpid));
				if (srv_check_result(0) == 0)
					*ok += 1;
			}
		}
	} else if (argv->type == P_MSGID) {
		i = 0;
		while (srv_iter_evpids(argv->u.u_msgid, &evpid, &i)) {
			srv_send(ctl, &evpid, sizeof(evpid));
			if (srv_check_result(0) == 0)
				*ok += 1;
		}
	} else {
		*total += 1;
		srv_send(ctl, &argv->u.u_evpid, sizeof(evpid));
		if (srv_check_result(0) == 0)
			*ok += 1;
	}
}

static void
srv_show_cmd(int cmd, const void *data, size_t len)
{
	int	done = 0;

	srv_send(cmd, data, len);

	do {
		srv_recv(cmd);
		if (rlen) {
			printf("%s\n", rdata);
			srv_read(NULL, rlen);
		}
		else
			done = 1;
		srv_end();
	} while (!done);
}

static int
do_log_brief(int argc, struct parameter *argv)
{
	int	v = 0;

	srv_send(IMSG_CTL_VERBOSE, &v, sizeof(v));
	return srv_check_result(1);
}

static int
do_log_verbose(int argc, struct parameter *argv)
{
	int	v = TRACE_DEBUG;

	srv_send(IMSG_CTL_VERBOSE, &v, sizeof(v));
	return srv_check_result(1);
}

static int
do_monitor(int argc, struct parameter *argv)
{
	struct stat_digest	last, digest;
	size_t			count;

	memset(&last, 0, sizeof(last));
	count = 0;

	while (1) {
		srv_send(IMSG_CTL_GET_DIGEST, NULL, 0);
		srv_recv(IMSG_CTL_GET_DIGEST);
		srv_read(&digest, sizeof(digest));
		srv_end();

		if (count % 25 == 0) {
			if (count != 0)
				printf("\n");
			printf("--- client ---  "
			    "-- envelope --   "
			    "---- relay/delivery --- "
			    "------- misc -------\n"
			    "curr conn disc  "
			    "curr  enq  deq   "
			    "ok tmpfail prmfail loop "
			    "expire remove bounce\n");
		}
		printf("%4zu %4zu %4zu  "
		    "%4zu %4zu %4zu "
		    "%4zu    %4zu    %4zu %4zu   "
		    "%4zu   %4zu   %4zu\n",
		    digest.clt_connect - digest.clt_disconnect,
		    digest.clt_connect - last.clt_connect,
		    digest.clt_disconnect - last.clt_disconnect,

		    digest.evp_enqueued - digest.evp_dequeued,
		    digest.evp_enqueued - last.evp_enqueued,
		    digest.evp_dequeued - last.evp_dequeued,

		    digest.dlv_ok - last.dlv_ok,
		    digest.dlv_tempfail - last.dlv_tempfail,
		    digest.dlv_permfail - last.dlv_permfail,
		    digest.dlv_loop - last.dlv_loop,

		    digest.evp_expired - last.evp_expired,
		    digest.evp_removed - last.evp_removed,
		    digest.evp_bounce - last.evp_bounce);

		last = digest;
		count++;
		sleep(1);
	}

	return (0);
}

static int
do_pause_envelope(int argc, struct parameter *argv)
{
	size_t	total, ok;

	srv_foreach_envelope(argv, IMSG_CTL_PAUSE_EVP, &total, &ok);
	printf("%zu envelope%s paused\n", ok, (ok > 1) ? "s" : "");

	return (0);
}

static int
do_pause_mda(int argc, struct parameter *argv)
{
	srv_send(IMSG_CTL_PAUSE_MDA, NULL, 0);
	return srv_check_result(1);
}

static int
do_pause_mta(int argc, struct parameter *argv)
{
	srv_send(IMSG_CTL_PAUSE_MTA, NULL, 0);
	return srv_check_result(1);
}

static int
do_pause_smtp(int argc, struct parameter *argv)
{
	srv_send(IMSG_CTL_PAUSE_SMTP, NULL, 0);
	return srv_check_result(1);
}

static int
do_profile(int argc, struct parameter *argv)
{
	int	v;

	v = str_to_profile(argv[0].u.u_str);

	srv_send(IMSG_CTL_PROFILE_ENABLE, &v, sizeof(v));
	return srv_check_result(1);
}

static int
do_remove(int argc, struct parameter *argv)
{
	size_t	total, ok;

	srv_foreach_envelope(argv, IMSG_CTL_REMOVE, &total, &ok);
	printf("%zu envelope%s removed\n", ok, (ok > 1) ? "s" : "");

	return (0);
}

static int
do_resume_envelope(int argc, struct parameter *argv)
{
	size_t	total, ok;

	srv_foreach_envelope(argv, IMSG_CTL_RESUME_EVP, &total, &ok);
	printf("%zu envelope%s resumed\n", ok, (ok > 1) ? "s" : "");

	return (0);
}

static int
do_resume_mda(int argc, struct parameter *argv)
{
	srv_send(IMSG_CTL_RESUME_MDA, NULL, 0);
	return srv_check_result(1);
}

static int
do_resume_mta(int argc, struct parameter *argv)
{
	srv_send(IMSG_CTL_RESUME_MTA, NULL, 0);
	return srv_check_result(1);
}

static int
do_resume_route(int argc, struct parameter *argv)
{
	uint64_t	v;

	if (argc == 0)
		v = 0;
	else
		v = argv[0].u.u_routeid;

	srv_send(IMSG_CTL_RESUME_ROUTE, &v, sizeof(v));
	return srv_check_result(1);
}

static int
do_resume_smtp(int argc, struct parameter *argv)
{
	srv_send(IMSG_CTL_RESUME_SMTP, NULL, 0);
	return srv_check_result(1);
}

static int
do_schedule(int argc, struct parameter *argv)
{
	size_t	total, ok;

	srv_foreach_envelope(argv, IMSG_CTL_SCHEDULE, &total, &ok);
	printf("%zu envelope%s scheduled\n", ok, (ok > 1) ? "s" : "");

	return (0);
}

static int
do_show_envelope(int argc, struct parameter *argv)
{
	char	 buf[PATH_MAX];

	if (!bsnprintf(buf, sizeof(buf), "%s%s/%02x/%08x/%016" PRIx64,
	    PATH_SPOOL,
	    PATH_QUEUE,
	    (evpid_to_msgid(argv[0].u.u_evpid) & 0xff000000) >> 24,
	    evpid_to_msgid(argv[0].u.u_evpid),
	    argv[0].u.u_evpid))
		errx(1, "unable to retrieve envelope");

	display(buf);

	return (0);
}

static int
do_show_hoststats(int argc, struct parameter *argv)
{
	srv_show_cmd(IMSG_CTL_MTA_SHOW_HOSTSTATS, NULL, 0);

	return (0);
}

static int
do_show_message(int argc, struct parameter *argv)
{
	char	 buf[PATH_MAX];
	uint32_t msgid;

	if (argv[0].type == P_EVPID)
		msgid = evpid_to_msgid(argv[0].u.u_evpid);
	else
		msgid = argv[0].u.u_msgid;

	if (!bsnprintf(buf, sizeof(buf), "%s%s/%02x/%08x/message",
		PATH_SPOOL,
		PATH_QUEUE,
		(msgid & 0xff000000) >> 24,
		msgid))
		errx(1, "unable to retrieve message");

	display(buf);

	return (0);
}

static int
do_show_queue(int argc, struct parameter *argv)
{
	struct envelope	 evp;
	uint32_t	 msgid;
	FTS		*fts;
	FTSENT		*ftse;
	char		*qpath[] = {"/queue", NULL};
	char		*tmp;
	uint64_t	 evpid;

	now = time(NULL);

	if (!srv_connect()) {
		log_init(1);
		queue_init("fs", 0);
		if (chroot(PATH_SPOOL) == -1 || chdir("/") == -1)
			err(1, "%s", PATH_SPOOL);
		fts = fts_open(qpath, FTS_PHYSICAL|FTS_NOCHDIR, NULL);
		if (fts == NULL)
			err(1, "%s/queue", PATH_SPOOL);

		while ((ftse = fts_read(fts)) != NULL) {
			switch (ftse->fts_info) {
			case FTS_DP:
			case FTS_DNR:
				break;
			case FTS_F:
				tmp = NULL;
				evpid = strtoull(ftse->fts_name, &tmp, 16);
				if (tmp && *tmp != '\0')
					break;
				show_offline_envelope(evpid);
			}
		}

		fts_close(fts);
		return (0);
	}

	if (argc == 0) {
		msgid = 0;
		while (srv_iter_messages(&msgid))
			while (srv_iter_envelopes(msgid, &evp))
				show_queue_envelope(&evp, 1);
	} else if (argv[0].type == P_MSGID) {
		while (srv_iter_envelopes(argv[0].u.u_msgid, &evp))
			show_queue_envelope(&evp, 1);
	}

	return (0);
}

static int
do_show_hosts(int argc, struct parameter *argv)
{
	srv_show_cmd(IMSG_CTL_MTA_SHOW_HOSTS, NULL, 0);

	return (0);
}

static int
do_show_relays(int argc, struct parameter *argv)
{
	srv_show_cmd(IMSG_CTL_MTA_SHOW_RELAYS, NULL, 0);

	return (0);
}

static int
do_show_routes(int argc, struct parameter *argv)
{
	srv_show_cmd(IMSG_CTL_MTA_SHOW_ROUTES, NULL, 0);

	return (0);
}

static int
do_show_stats(int argc, struct parameter *argv)
{
	struct stat_kv	kv;
	time_t		duration;

	memset(&kv, 0, sizeof kv);

	while (1) {
		srv_send(IMSG_CTL_GET_STATS, &kv, sizeof kv);
		srv_recv(IMSG_CTL_GET_STATS);
		srv_read(&kv, sizeof(kv));
		srv_end();

		if (kv.iter == NULL)
			break;

		if (strcmp(kv.key, "uptime") == 0) {
			duration = time(NULL) - kv.val.u.counter;
			printf("uptime=%lld\n", (long long)duration);
			printf("uptime.human=%s\n",
			    duration_to_text(duration));
		}
		else {
			switch (kv.val.type) {
			case STAT_COUNTER:
				printf("%s=%zd\n",
				    kv.key, kv.val.u.counter);
				break;
			case STAT_TIMESTAMP:
				printf("%s=%" PRId64 "\n",
				    kv.key, (int64_t)kv.val.u.timestamp);
				break;
			case STAT_TIMEVAL:
				printf("%s=%lld.%lld\n",
				    kv.key, (long long)kv.val.u.tv.tv_sec,
				    (long long)kv.val.u.tv.tv_usec);
				break;
			case STAT_TIMESPEC:
				printf("%s=%lld.%06ld\n",
				    kv.key,
				    (long long)kv.val.u.ts.tv_sec * 1000000 +
				    kv.val.u.ts.tv_nsec / 1000000,
				    kv.val.u.ts.tv_nsec % 1000000);
				break;
			}
		}
	}

	return (0);
}

static int
do_show_status(int argc, struct parameter *argv)
{
	uint32_t	sc_flags;

	srv_send(IMSG_CTL_SHOW_STATUS, NULL, 0);
	srv_recv(IMSG_CTL_SHOW_STATUS);
	srv_read(&sc_flags, sizeof(sc_flags));
	srv_end();
	printf("MDA %s\n",
	    (sc_flags & SMTPD_MDA_PAUSED) ? "paused" : "running");
	printf("MTA %s\n",
	    (sc_flags & SMTPD_MTA_PAUSED) ? "paused" : "running");
	printf("SMTP %s\n",
	    (sc_flags & SMTPD_SMTP_PAUSED) ? "paused" : "running");
	return (0);
}

static int
do_stop(int argc, struct parameter *argv)
{
	srv_send(IMSG_CTL_SHUTDOWN, NULL, 0);
	return srv_check_result(1);
}

static int
do_trace(int argc, struct parameter *argv)
{
	int	v;

	v = str_to_trace(argv[0].u.u_str);

	srv_send(IMSG_CTL_TRACE_ENABLE, &v, sizeof(v));
	return srv_check_result(1);
}

static int
do_unprofile(int argc, struct parameter *argv)
{
	int	v;

	v = str_to_profile(argv[0].u.u_str);

	srv_send(IMSG_CTL_PROFILE_DISABLE, &v, sizeof(v));
	return srv_check_result(1);
}

static int
do_untrace(int argc, struct parameter *argv)
{
	int	v;

	v = str_to_trace(argv[0].u.u_str);

	srv_send(IMSG_CTL_TRACE_DISABLE, &v, sizeof(v));
	return srv_check_result(1);
}

static int
do_update_table(int argc, struct parameter *argv)
{
	const char	*name = argv[0].u.u_str;

	srv_send(IMSG_CTL_UPDATE_TABLE, name, strlen(name) + 1);
	return srv_check_result(1);
}

static int
do_encrypt(int argc, struct parameter *argv)
{
	const char *p = NULL;

	if (argv)
		p = argv[0].u.u_str;
	execl(PATH_ENCRYPT, "encrypt", p, (char *)NULL);
	errx(1, "execl");
}

static int
do_block_mta(int argc, struct parameter *argv)
{
	struct ibuf *m;

	if (ibuf == NULL && !srv_connect())
		errx(1, "smtpd doesn't seem to be running");
	m = imsg_create(ibuf, IMSG_CTL_MTA_BLOCK, IMSG_VERSION, 0,
	    sizeof(argv[0].u.u_ss) + strlen(argv[1].u.u_str) + 1);
	if (imsg_add(m, &argv[0].u.u_ss, sizeof(argv[0].u.u_ss)) == -1)
		errx(1, "imsg_add");
	if (imsg_add(m, argv[1].u.u_str, strlen(argv[1].u.u_str) + 1) == -1)
		errx(1, "imsg_add");
	imsg_close(ibuf, m);

	return srv_check_result(1);
}

static int
do_unblock_mta(int argc, struct parameter *argv)
{
	struct ibuf *m;

	if (ibuf == NULL && !srv_connect())
		errx(1, "smtpd doesn't seem to be running");

	m = imsg_create(ibuf, IMSG_CTL_MTA_UNBLOCK, IMSG_VERSION, 0,
	    sizeof(argv[0].u.u_ss) + strlen(argv[1].u.u_str) + 1);
	if (imsg_add(m, &argv[0].u.u_ss, sizeof(argv[0].u.u_ss)) == -1)
		errx(1, "imsg_add");
	if (imsg_add(m, argv[1].u.u_str, strlen(argv[1].u.u_str) + 1) == -1)
		errx(1, "imsg_add");
	imsg_close(ibuf, m);

	return srv_check_result(1);
}

static int
do_show_mta_block(int argc, struct parameter *argv)
{
	srv_show_cmd(IMSG_CTL_MTA_SHOW_BLOCK, NULL, 0);

	return (0);
}

static int
do_discover(int argc, struct parameter *argv)
{
	uint64_t evpid;
	uint32_t msgid;
	size_t	 n_evp;

	if (ibuf == NULL && !srv_connect())
		errx(1, "smtpd doesn't seem to be running");

	if (argv[0].type == P_EVPID) {
		evpid = argv[0].u.u_evpid;
		srv_send(IMSG_CTL_DISCOVER_EVPID, &evpid, sizeof evpid);
		srv_recv(IMSG_CTL_DISCOVER_EVPID);
	} else {
		msgid = argv[0].u.u_msgid;
		srv_send(IMSG_CTL_DISCOVER_MSGID, &msgid, sizeof msgid);
		srv_recv(IMSG_CTL_DISCOVER_MSGID);
	}

	if (rlen == 0) {
		srv_end();
		return (0);
	} else {
		srv_read(&n_evp, sizeof n_evp);
		srv_end();
	}

	printf("%zu envelope%s discovered\n", n_evp, (n_evp != 1) ? "s" : "");
	return (0);
}

static int
do_uncorrupt(int argc, struct parameter *argv)
{
	uint32_t msgid;
	int	 ret;

	if (ibuf == NULL && !srv_connect())
		errx(1, "smtpd doesn't seem to be running");

	msgid = argv[0].u.u_msgid;
	srv_send(IMSG_CTL_UNCORRUPT_MSGID, &msgid, sizeof msgid);
	srv_recv(IMSG_CTL_UNCORRUPT_MSGID);

	if (rlen == 0) {
		srv_end();
		return (0);
	} else {
		srv_read(&ret, sizeof ret);
		srv_end();
	}

	printf("command %s\n", ret ? "succeeded" : "failed");
	return (0);
}

int
main(int argc, char **argv)
{
	gid_t		 gid;
	char		*argv_mailq[] = { "show", "queue", NULL };

	sendmail_compat(argc, argv);
	if (geteuid())
		errx(1, "need root privileges");

	gid = getgid();
	if (setresgid(gid, gid, gid) == -1)
		err(1, "setresgid");

	cmd_install("discover <evpid>",		do_discover);
	cmd_install("discover <msgid>",		do_discover);
	cmd_install("encrypt",			do_encrypt);
	cmd_install("encrypt <str>",		do_encrypt);
	cmd_install("pause mta from <addr> for <str>", do_block_mta);
	cmd_install("resume mta from <addr> for <str>", do_unblock_mta);
	cmd_install("show mta paused",		do_show_mta_block);
	cmd_install("log brief",		do_log_brief);
	cmd_install("log verbose",		do_log_verbose);
	cmd_install("monitor",			do_monitor);
	cmd_install("pause envelope <evpid>",	do_pause_envelope);
	cmd_install("pause envelope <msgid>",	do_pause_envelope);
	cmd_install("pause envelope all",	do_pause_envelope);
	cmd_install("pause mda",		do_pause_mda);
	cmd_install("pause mta",		do_pause_mta);
	cmd_install("pause smtp",		do_pause_smtp);
	cmd_install("profile <str>",		do_profile);
	cmd_install("remove <evpid>",		do_remove);
	cmd_install("remove <msgid>",		do_remove);
	cmd_install("remove all",		do_remove);
	cmd_install("resume envelope <evpid>",	do_resume_envelope);
	cmd_install("resume envelope <msgid>",	do_resume_envelope);
	cmd_install("resume envelope all",	do_resume_envelope);
	cmd_install("resume mda",		do_resume_mda);
	cmd_install("resume mta",		do_resume_mta);
	cmd_install("resume route <routeid>",	do_resume_route);
	cmd_install("resume smtp",		do_resume_smtp);
	cmd_install("schedule <msgid>",		do_schedule);
	cmd_install("schedule <evpid>",		do_schedule);
	cmd_install("schedule all",		do_schedule);
	cmd_install("show envelope <evpid>",	do_show_envelope);
	cmd_install("show hoststats",		do_show_hoststats);
	cmd_install("show message <msgid>",	do_show_message);
	cmd_install("show message <evpid>",	do_show_message);
	cmd_install("show queue",		do_show_queue);
	cmd_install("show queue <msgid>",	do_show_queue);
	cmd_install("show hosts",		do_show_hosts);
	cmd_install("show relays",		do_show_relays);
	cmd_install("show routes",		do_show_routes);
	cmd_install("show stats",		do_show_stats);
	cmd_install("show status",		do_show_status);
	cmd_install("stop",			do_stop);
	cmd_install("trace <str>",		do_trace);
	cmd_install("uncorrupt <msgid>",	do_uncorrupt);
	cmd_install("unprofile <str>",		do_unprofile);
	cmd_install("untrace <str>",		do_untrace);
	cmd_install("update table <str>",	do_update_table);

	if (strcmp(__progname, "mailq") == 0)
		return cmd_run(2, argv_mailq);
	if (strcmp(__progname, "smtpctl") == 0)
		return cmd_run(argc - 1, argv + 1);

	errx(1, "unsupported mode");
	return (0);
}

void
sendmail_compat(int argc, char **argv)
{
	FILE	*offlinefp = NULL;
	gid_t	 gid;
	int	 i;

	if (strcmp(__progname, "sendmail") == 0 ||
	    strcmp(__progname, "send-mail") == 0) {
		/*
		 * determine whether we are called with flags
		 * that should invoke makemap/newaliases.
		 */
		for (i = 1; i < argc; i++)
			if (strncmp(argv[i], "-bi", 3) == 0)
				exit(makemap(P_SENDMAIL, argc, argv));

		if (!srv_connect())
			offlinefp = offline_file();

		gid = getgid();
		if (setresgid(gid, gid, gid) == -1)
			err(1, "setresgid");

		/* we'll reduce further down the road */
		if (pledge("stdio rpath wpath cpath tmppath flock "
			"dns getpw recvfd", NULL) == -1)
			err(1, "pledge");

		sendmail = 1;
		exit(enqueue(argc, argv, offlinefp));
	} else if (strcmp(__progname, "makemap") == 0)
		exit(makemap(P_MAKEMAP, argc, argv));
	else if (strcmp(__progname, "newaliases") == 0)
		exit(makemap(P_NEWALIASES, argc, argv));
}

static void
show_queue_envelope(struct envelope *e, int online)
{
	const char	*src = "?", *agent = "?";
	char		 status[128], runstate[128];

	status[0] = '\0';

	getflag(&e->flags, EF_BOUNCE, "bounce", status, sizeof(status));
	getflag(&e->flags, EF_AUTHENTICATED, "auth", status, sizeof(status));
	getflag(&e->flags, EF_INTERNAL, "internal", status, sizeof(status));
	getflag(&e->flags, EF_SUSPEND, "suspend", status, sizeof(status));
	getflag(&e->flags, EF_HOLD, "hold", status, sizeof(status));

	if (online) {
		if (e->flags & EF_PENDING)
			(void)snprintf(runstate, sizeof runstate, "pending|%zd",
			    (ssize_t)(e->nexttry - now));
		else if (e->flags & EF_INFLIGHT)
			(void)snprintf(runstate, sizeof runstate,
			    "inflight|%zd", (ssize_t)(now - e->lasttry));
		else
			(void)snprintf(runstate, sizeof runstate, "invalid|");
		e->flags &= ~(EF_PENDING|EF_INFLIGHT);
	}
	else
		(void)strlcpy(runstate, "offline|", sizeof runstate);

	if (e->flags)
		errx(1, "%016" PRIx64 ": unexpected flags 0x%04x", e->id,
		    e->flags);

	if (status[0])
		status[strlen(status) - 1] = '\0';

	if (e->type == D_MDA)
		agent = "mda";
	else if (e->type == D_MTA)
		agent = "mta";
	else if (e->type == D_BOUNCE)
		agent = "bounce";

	if (e->ss.ss_family == AF_LOCAL)
		src = "local";
	else if (e->ss.ss_family == AF_INET)
		src = "inet4";
	else if (e->ss.ss_family == AF_INET6)
		src = "inet6";

	printf("%016"PRIx64
	    "|%s|%s|%s|%s@%s|%s@%s|%s@%s"
	    "|%zu|%zu|%zu|%zu|%s|%s\n",

	    e->id,

	    src,
	    agent,
	    status,
	    e->sender.user, e->sender.domain,
	    e->rcpt.user, e->rcpt.domain,
	    e->dest.user, e->dest.domain,

	    (size_t) e->creation,
	    (size_t) (e->creation + e->expire),
	    (size_t) e->lasttry,
	    (size_t) e->retry,
	    runstate,
	    e->errorline);
}

static void
getflag(uint *bitmap, int bit, char *bitstr, char *buf, size_t len)
{
	if (*bitmap & bit) {
		*bitmap &= ~bit;
		(void)strlcat(buf, bitstr, len);
		(void)strlcat(buf, ",", len);
	}
}

static void
show_offline_envelope(uint64_t evpid)
{
	FILE   *fp = NULL;
	char	pathname[PATH_MAX];
	size_t	plen;
	char   *p;
	size_t	buflen;
	char	buffer[sizeof(struct envelope)];

	struct envelope	evp;

	if (!bsnprintf(pathname, sizeof pathname,
		"/queue/%02x/%08x/%016"PRIx64,
		(evpid_to_msgid(evpid) & 0xff000000) >> 24,
		evpid_to_msgid(evpid), evpid))
		goto end;
	fp = fopen(pathname, "r");
	if (fp == NULL)
		goto end;

	buflen = fread(buffer, 1, sizeof (buffer) - 1, fp);
	p = buffer;
	plen = buflen;
	buffer[buflen] = '\0';

	if (is_encrypted_buffer(p)) {
		warnx("offline encrypted queue is not supported yet");
		goto end;
	}

	if (is_gzip_buffer(p)) {
		warnx("offline compressed queue is not supported yet");
		goto end;
	}

	if (!envelope_load_buffer(&evp, p, plen))
		goto end;
	evp.id = evpid;
	show_queue_envelope(&evp, 0);

end:
	if (fp)
		fclose(fp);
}

static void
display(const char *s)
{
	FILE   *fp;
#ifdef HAVE_GCM_CRYPTO
	char   *key;
#endif
	int	gzipped;
	char   *gzcat_argv0 = strrchr(PATH_GZCAT, '/') + 1;

	if ((fp = fopen(s, "r")) == NULL)
		err(1, "fopen");

	if (is_encrypted_fp(fp)) {
#ifdef HAVE_GCM_CRYPTO
		int	i;
		int	fd;
		FILE   *ofp = NULL;
		char	sfn[] = "/tmp/smtpd.XXXXXXXXXX";

		if ((fd = mkstemp(sfn)) == -1 ||
		    (ofp = fdopen(fd, "w+")) == NULL) {
			int saved_errno = errno;
			if (fd != -1) {
				unlink(sfn);
				close(fd);
			}
			errc(1, saved_errno, "mkstemp");
		}
		unlink(sfn);

		for (i = 0; i < 3; i++) {
			key = getpass("key> ");
			if (crypto_setup(key, strlen(key)))
				break;
		}
		if (i == 3)
			errx(1, "crypto-setup: invalid key");

		if (!crypto_decrypt_file(fp, ofp)) {
			printf("object is encrypted: %s\n", key);
			exit(1);
		}

		fclose(fp);
		fp = ofp;
		fseek(fp, 0, SEEK_SET);
#else
	       	printf("GCM crypto not supported!\n");
       		exit(1);
#endif
	}
	gzipped = is_gzip_fp(fp);

	lseek(fileno(fp), 0, SEEK_SET);
	(void)dup2(fileno(fp), STDIN_FILENO);
	if (gzipped)
		execl(PATH_GZCAT, gzcat_argv0, (char *)NULL);
	else
		execl(PATH_CAT, "cat", (char *)NULL);
	err(1, "execl");
}

static int
str_to_trace(const char *str)
{
	if (!strcmp(str, "imsg"))
		return TRACE_IMSG;
	if (!strcmp(str, "io"))
		return TRACE_IO;
	if (!strcmp(str, "smtp"))
		return TRACE_SMTP;
	if (!strcmp(str, "filters"))
		return TRACE_FILTERS;
	if (!strcmp(str, "mta"))
		return TRACE_MTA;
	if (!strcmp(str, "bounce"))
		return TRACE_BOUNCE;
	if (!strcmp(str, "scheduler"))
		return TRACE_SCHEDULER;
	if (!strcmp(str, "lookup"))
		return TRACE_LOOKUP;
	if (!strcmp(str, "stat"))
		return TRACE_STAT;
	if (!strcmp(str, "rules"))
		return TRACE_RULES;
	if (!strcmp(str, "mproc"))
		return TRACE_MPROC;
	if (!strcmp(str, "expand"))
		return TRACE_EXPAND;
	if (!strcmp(str, "all"))
		return ~TRACE_DEBUG;
	errx(1, "invalid trace keyword: %s", str);
	return (0);
}

static int
str_to_profile(const char *str)
{
	if (!strcmp(str, "imsg"))
		return PROFILE_IMSG;
	if (!strcmp(str, "queue"))
		return PROFILE_QUEUE;
	errx(1, "invalid profile keyword: %s", str);
	return (0);
}

static int
is_gzip_buffer(const char *buffer)
{
	uint16_t	magic;

	memcpy(&magic, buffer, sizeof magic);
#define	GZIP_MAGIC	0x8b1f
	return (magic == GZIP_MAGIC);
}

static int
is_gzip_fp(FILE *fp)
{
	uint8_t		magic[2];
	int		ret = 0;

	if (fread(&magic, 1, sizeof magic, fp) != sizeof magic)
		goto end;

	ret = is_gzip_buffer((const char *)&magic);
end:
	fseek(fp, 0, SEEK_SET);
	return ret;
}


/* XXX */
/*
 * queue supports transparent encryption.
 * encrypted chunks are prefixed with an API version byte
 * which we ensure is unambiguous with gzipped / plain
 * objects.
 */

static int
is_encrypted_buffer(const char *buffer)
{
	uint8_t	magic;

	magic = *buffer;
#define	ENCRYPTION_MAGIC	0x1
	return (magic == ENCRYPTION_MAGIC);
}

static int
is_encrypted_fp(FILE *fp)
{
	uint8_t	magic;
	int	ret = 0;

	if (fread(&magic, 1, sizeof magic, fp) != sizeof magic)
		goto end;

	ret = is_encrypted_buffer((const char *)&magic);
end:
	fseek(fp, 0, SEEK_SET);
	return ret;
}