1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 # include "sendmail.h"
10 
11 #ifndef lint
12 #ifdef SMTP
13 static char sccsid[] = "@(#)srvrsmtp.c	6.3 (Berkeley) 01/21/93 (with SMTP)";
14 #else
15 static char sccsid[] = "@(#)srvrsmtp.c	6.3 (Berkeley) 01/21/93 (without SMTP)";
16 #endif
17 #endif /* not lint */
18 
19 # include <errno.h>
20 # include <signal.h>
21 
22 # ifdef SMTP
23 
24 /*
25 **  SMTP -- run the SMTP protocol.
26 **
27 **	Parameters:
28 **		none.
29 **
30 **	Returns:
31 **		never.
32 **
33 **	Side Effects:
34 **		Reads commands from the input channel and processes
35 **			them.
36 */
37 
38 struct cmd
39 {
40 	char	*cmdname;	/* command name */
41 	int	cmdcode;	/* internal code, see below */
42 };
43 
44 /* values for cmdcode */
45 # define CMDERROR	0	/* bad command */
46 # define CMDMAIL	1	/* mail -- designate sender */
47 # define CMDRCPT	2	/* rcpt -- designate recipient */
48 # define CMDDATA	3	/* data -- send message text */
49 # define CMDRSET	4	/* rset -- reset state */
50 # define CMDVRFY	5	/* vrfy -- verify address */
51 # define CMDHELP	6	/* help -- give usage info */
52 # define CMDNOOP	7	/* noop -- do nothing */
53 # define CMDQUIT	8	/* quit -- close connection and die */
54 # define CMDHELO	9	/* helo -- be polite */
55 # define CMDONEX	10	/* onex -- sending one transaction only */
56 # define CMDVERB	11	/* verb -- go into verbose mode */
57 /* debugging-only commands, only enabled if SMTPDEBUG is defined */
58 # define CMDDBGQSHOW	12	/* showq -- show send queue */
59 # define CMDDBGDEBUG	13	/* debug -- set debug mode */
60 
61 static struct cmd	CmdTab[] =
62 {
63 	"mail",		CMDMAIL,
64 	"rcpt",		CMDRCPT,
65 	"data",		CMDDATA,
66 	"rset",		CMDRSET,
67 	"vrfy",		CMDVRFY,
68 	"expn",		CMDVRFY,
69 	"help",		CMDHELP,
70 	"noop",		CMDNOOP,
71 	"quit",		CMDQUIT,
72 	"helo",		CMDHELO,
73 	"verb",		CMDVERB,
74 	"onex",		CMDONEX,
75 	/*
76 	 * remaining commands are here only
77 	 * to trap and log attempts to use them
78 	 */
79 	"showq",	CMDDBGQSHOW,
80 	"debug",	CMDDBGDEBUG,
81 	NULL,		CMDERROR,
82 };
83 
84 bool	InChild = FALSE;		/* true if running in a subprocess */
85 bool	OneXact = FALSE;		/* one xaction only this run */
86 
87 #define EX_QUIT		22		/* special code for QUIT command */
88 
89 smtp(e)
90 	register ENVELOPE *e;
91 {
92 	register char *p;
93 	register struct cmd *c;
94 	char *cmd;
95 	static char *skipword();
96 	bool hasmail;			/* mail command received */
97 	auto ADDRESS *vrfyqueue;
98 	ADDRESS *a;
99 	char *sendinghost;
100 	char inp[MAXLINE];
101 	char cmdbuf[MAXLINE];
102 	extern char Version[];
103 	extern char *macvalue();
104 	extern ADDRESS *recipient();
105 	extern ENVELOPE BlankEnvelope;
106 	extern ENVELOPE *newenvelope();
107 
108 	hasmail = FALSE;
109 	if (OutChannel != stdout)
110 	{
111 		/* arrange for debugging output to go to remote host */
112 		(void) close(1);
113 		(void) dup(fileno(OutChannel));
114 	}
115 	settime(e);
116 	if (RealHostName == NULL)
117 		RealHostName = MyHostName;
118 	CurHostName = RealHostName;
119 	setproctitle("srvrsmtp %s", CurHostName);
120 	expand("\001e", inp, &inp[sizeof inp], e);
121 	message("220", "%s", inp);
122 	SmtpPhase = "startup";
123 	sendinghost = NULL;
124 	for (;;)
125 	{
126 		/* arrange for backout */
127 		if (setjmp(TopFrame) > 0 && InChild)
128 			finis();
129 		QuickAbort = FALSE;
130 		HoldErrs = FALSE;
131 		LogUsrErrs = FALSE;
132 
133 		/* setup for the read */
134 		e->e_to = NULL;
135 		Errors = 0;
136 		(void) fflush(stdout);
137 
138 		/* read the input line */
139 		p = sfgets(inp, sizeof inp, InChannel, ReadTimeout);
140 
141 		/* handle errors */
142 		if (p == NULL)
143 		{
144 			/* end of file, just die */
145 			message("421", "%s Lost input channel from %s",
146 				MyHostName, CurHostName);
147 #ifdef LOG
148 			if (LogLevel >= 4)
149 				syslog(LOG_NOTICE, "lost input channel from %s",
150 					CurHostName);
151 #endif
152 			finis();
153 		}
154 
155 		/* clean up end of line */
156 		fixcrlf(inp, TRUE);
157 
158 		/* echo command to transcript */
159 		if (e->e_xfp != NULL)
160 			fprintf(e->e_xfp, "<<< %s\n", inp);
161 
162 		/* break off command */
163 		for (p = inp; isspace(*p); p++)
164 			continue;
165 		cmd = cmdbuf;
166 		while (*p != '\0' && !isspace(*p) && cmd < &cmdbuf[sizeof cmdbuf - 2])
167 			*cmd++ = *p++;
168 		*cmd = '\0';
169 
170 		/* throw away leading whitespace */
171 		while (isspace(*p))
172 			p++;
173 
174 		/* decode command */
175 		for (c = CmdTab; c->cmdname != NULL; c++)
176 		{
177 			if (!strcasecmp(c->cmdname, cmdbuf))
178 				break;
179 		}
180 
181 		/* reset errors */
182 		errno = 0;
183 
184 		/* process command */
185 		switch (c->cmdcode)
186 		{
187 		  case CMDHELO:		/* hello -- introduce yourself */
188 			SmtpPhase = "HELO";
189 			setproctitle("%s: %s", CurHostName, inp);
190 			if (!strcasecmp(p, MyHostName))
191 			{
192 				/*
193 				 * didn't know about alias,
194 				 * or connected to an echo server
195 				 */
196 				message("553", "%s config error: mail loops back to myself",
197 					MyHostName);
198 				break;
199 			}
200 			if (RealHostName != NULL && strcasecmp(p, RealHostName))
201 			{
202 				char hostbuf[MAXNAME];
203 
204 				(void) sprintf(hostbuf, "%s (%s)", p, RealHostName);
205 				sendinghost = newstr(hostbuf);
206 			}
207 			else
208 				sendinghost = newstr(p);
209 			message("250", "%s Hello %s, pleased to meet you",
210 				MyHostName, sendinghost);
211 			break;
212 
213 		  case CMDMAIL:		/* mail -- designate sender */
214 			SmtpPhase = "MAIL";
215 
216 			/* force a sending host even if no HELO given */
217 			if (RealHostName != NULL && macvalue('s', e) == NULL)
218 				sendinghost = RealHostName;
219 
220 			/* check for validity of this command */
221 			if (hasmail)
222 			{
223 				message("503", "Sender already specified");
224 				break;
225 			}
226 			if (InChild)
227 			{
228 				errno = 0;
229 				syserr("Nested MAIL command");
230 				exit(0);
231 			}
232 
233 			/* fork a subprocess to process this command */
234 			if (runinchild("SMTP-MAIL", e) > 0)
235 				break;
236 			define('s', sendinghost, e);
237 			define('r', "SMTP", e);
238 			initsys(e);
239 			setproctitle("%s %s: %s", e->e_id, CurHostName, inp);
240 
241 			/* child -- go do the processing */
242 			p = skipword(p, "from");
243 			if (p == NULL)
244 				break;
245 			setsender(p, e);
246 			if (Errors == 0)
247 			{
248 				message("250", "Sender ok");
249 				hasmail = TRUE;
250 			}
251 			else if (InChild)
252 				finis();
253 			break;
254 
255 		  case CMDRCPT:		/* rcpt -- designate recipient */
256 			SmtpPhase = "RCPT";
257 			setproctitle("%s %s: %s", e->e_id, CurHostName, inp);
258 			if (setjmp(TopFrame) > 0)
259 			{
260 				e->e_flags &= ~EF_FATALERRS;
261 				break;
262 			}
263 			QuickAbort = TRUE;
264 			LogUsrErrs = TRUE;
265 			p = skipword(p, "to");
266 			if (p == NULL)
267 				break;
268 			a = parseaddr(p, (ADDRESS *) NULL, 1, '\0', e);
269 			if (a == NULL)
270 				break;
271 			a->q_flags |= QPRIMARY;
272 			a = recipient(a, &e->e_sendqueue, e);
273 			if (Errors != 0)
274 				break;
275 
276 			/* no errors during parsing, but might be a duplicate */
277 			e->e_to = p;
278 			if (!bitset(QBADADDR, a->q_flags))
279 				message("250", "Recipient ok");
280 			else
281 			{
282 				/* punt -- should keep message in ADDRESS.... */
283 				message("550", "Addressee unknown");
284 			}
285 			e->e_to = NULL;
286 			break;
287 
288 		  case CMDDATA:		/* data -- text of mail */
289 			SmtpPhase = "DATA";
290 			if (!hasmail)
291 			{
292 				message("503", "Need MAIL command");
293 				break;
294 			}
295 			else if (e->e_nrcpts <= 0)
296 			{
297 				message("503", "Need RCPT (recipient)");
298 				break;
299 			}
300 
301 			/* collect the text of the message */
302 			SmtpPhase = "collect";
303 			setproctitle("%s %s: %s", e->e_id, CurHostName, inp);
304 			collect(TRUE, e);
305 			if (Errors != 0)
306 				break;
307 
308 			/*
309 			**  Arrange to send to everyone.
310 			**	If sending to multiple people, mail back
311 			**		errors rather than reporting directly.
312 			**	In any case, don't mail back errors for
313 			**		anything that has happened up to
314 			**		now (the other end will do this).
315 			**	Truncate our transcript -- the mail has gotten
316 			**		to us successfully, and if we have
317 			**		to mail this back, it will be easier
318 			**		on the reader.
319 			**	Then send to everyone.
320 			**	Finally give a reply code.  If an error has
321 			**		already been given, don't mail a
322 			**		message back.
323 			**	We goose error returns by clearing error bit.
324 			*/
325 
326 			SmtpPhase = "delivery";
327 			if (e->e_nrcpts != 1)
328 			{
329 				HoldErrs = TRUE;
330 				ErrorMode = EM_MAIL;
331 			}
332 			e->e_flags &= ~EF_FATALERRS;
333 			e->e_xfp = freopen(queuename(e, 'x'), "w", e->e_xfp);
334 
335 			/* send to all recipients */
336 			sendall(e, SM_DEFAULT);
337 			e->e_to = NULL;
338 
339 			/* save statistics */
340 			markstats(e, (ADDRESS *) NULL);
341 
342 			/* issue success if appropriate and reset */
343 			if (Errors == 0 || HoldErrs)
344 				message("250", "Ok");
345 			else
346 				e->e_flags &= ~EF_FATALERRS;
347 
348 			/* if in a child, pop back to our parent */
349 			if (InChild)
350 				finis();
351 
352 			/* clean up a bit */
353 			hasmail = 0;
354 			dropenvelope(e);
355 			CurEnv = e = newenvelope(e);
356 			e->e_flags = BlankEnvelope.e_flags;
357 			break;
358 
359 		  case CMDRSET:		/* rset -- reset state */
360 			message("250", "Reset state");
361 			if (InChild)
362 				finis();
363 			break;
364 
365 		  case CMDVRFY:		/* vrfy -- verify address */
366 			if (runinchild("SMTP-VRFY", e) > 0)
367 				break;
368 			setproctitle("%s: %s", CurHostName, inp);
369 #ifdef LOG
370 			if (LogLevel >= 9)
371 				syslog(LOG_INFO, "%s: %s", CurHostName, inp);
372 #endif
373 			vrfyqueue = NULL;
374 			QuickAbort = TRUE;
375 			sendtolist(p, (ADDRESS *) NULL, &vrfyqueue, e);
376 			if (Errors != 0)
377 			{
378 				if (InChild)
379 					finis();
380 				break;
381 			}
382 			while (vrfyqueue != NULL)
383 			{
384 				register ADDRESS *a = vrfyqueue->q_next;
385 				char *code;
386 
387 				while (a != NULL && bitset(QDONTSEND|QBADADDR, a->q_flags))
388 					a = a->q_next;
389 
390 				if (!bitset(QDONTSEND|QBADADDR, vrfyqueue->q_flags))
391 				{
392 					if (a != NULL)
393 						code = "250-";
394 					else
395 						code = "250";
396 					if (vrfyqueue->q_fullname == NULL)
397 						message(code, "<%s>", vrfyqueue->q_paddr);
398 					else
399 						message(code, "%s <%s>",
400 						    vrfyqueue->q_fullname, vrfyqueue->q_paddr);
401 				}
402 				else if (a == NULL)
403 					message("554", "Self destructive alias loop");
404 				vrfyqueue = a;
405 			}
406 			if (InChild)
407 				finis();
408 			break;
409 
410 		  case CMDHELP:		/* help -- give user info */
411 			help(p);
412 			break;
413 
414 		  case CMDNOOP:		/* noop -- do nothing */
415 			message("200", "OK");
416 			break;
417 
418 		  case CMDQUIT:		/* quit -- leave mail */
419 			message("221", "%s closing connection", MyHostName);
420 			if (InChild)
421 				ExitStat = EX_QUIT;
422 			finis();
423 
424 		  case CMDVERB:		/* set verbose mode */
425 			Verbose = TRUE;
426 			SendMode = SM_DELIVER;
427 			message("200", "Verbose mode");
428 			break;
429 
430 		  case CMDONEX:		/* doing one transaction only */
431 			OneXact = TRUE;
432 			message("200", "Only one transaction");
433 			break;
434 
435 # ifdef SMTPDEBUG
436 		  case CMDDBGQSHOW:	/* show queues */
437 			printf("Send Queue=");
438 			printaddr(e->e_sendqueue, TRUE);
439 			break;
440 
441 		  case CMDDBGDEBUG:	/* set debug mode */
442 			tTsetup(tTdvect, sizeof tTdvect, "0-99.1");
443 			tTflag(p);
444 			message("200", "Debug set");
445 			break;
446 
447 # else /* not SMTPDEBUG */
448 
449 		  case CMDDBGQSHOW:	/* show queues */
450 		  case CMDDBGDEBUG:	/* set debug mode */
451 # ifdef LOG
452 			if (RealHostName != NULL && LogLevel > 0)
453 				syslog(LOG_NOTICE,
454 				    "\"%s\" command from %s (%s)\n",
455 				    c->cmdname, RealHostName,
456 				    inet_ntoa(RealHostAddr.sin_addr));
457 # endif
458 			/* FALL THROUGH */
459 # endif /* SMTPDEBUG */
460 
461 		  case CMDERROR:	/* unknown command */
462 			message("500", "Command unrecognized");
463 			break;
464 
465 		  default:
466 			errno = 0;
467 			syserr("smtp: unknown code %d", c->cmdcode);
468 			break;
469 		}
470 	}
471 }
472 /*
473 **  SKIPWORD -- skip a fixed word.
474 **
475 **	Parameters:
476 **		p -- place to start looking.
477 **		w -- word to skip.
478 **
479 **	Returns:
480 **		p following w.
481 **		NULL on error.
482 **
483 **	Side Effects:
484 **		clobbers the p data area.
485 */
486 
487 static char *
488 skipword(p, w)
489 	register char *p;
490 	char *w;
491 {
492 	register char *q;
493 
494 	/* find beginning of word */
495 	while (isspace(*p))
496 		p++;
497 	q = p;
498 
499 	/* find end of word */
500 	while (*p != '\0' && *p != ':' && !isspace(*p))
501 		p++;
502 	while (isspace(*p))
503 		*p++ = '\0';
504 	if (*p != ':')
505 	{
506 	  syntax:
507 		message("501", "Syntax error");
508 		Errors++;
509 		return (NULL);
510 	}
511 	*p++ = '\0';
512 	while (isspace(*p))
513 		p++;
514 
515 	/* see if the input word matches desired word */
516 	if (strcasecmp(q, w))
517 		goto syntax;
518 
519 	return (p);
520 }
521 /*
522 **  HELP -- implement the HELP command.
523 **
524 **	Parameters:
525 **		topic -- the topic we want help for.
526 **
527 **	Returns:
528 **		none.
529 **
530 **	Side Effects:
531 **		outputs the help file to message output.
532 */
533 
534 help(topic)
535 	char *topic;
536 {
537 	register FILE *hf;
538 	int len;
539 	char buf[MAXLINE];
540 	bool noinfo;
541 
542 	if (HelpFile == NULL || (hf = fopen(HelpFile, "r")) == NULL)
543 	{
544 		/* no help */
545 		errno = 0;
546 		message("502", "HELP not implemented");
547 		return;
548 	}
549 
550 	if (topic == NULL || *topic == '\0')
551 		topic = "smtp";
552 	else
553 		makelower(topic);
554 
555 	len = strlen(topic);
556 	noinfo = TRUE;
557 
558 	while (fgets(buf, sizeof buf, hf) != NULL)
559 	{
560 		if (strncmp(buf, topic, len) == 0)
561 		{
562 			register char *p;
563 
564 			p = strchr(buf, '\t');
565 			if (p == NULL)
566 				p = buf;
567 			else
568 				p++;
569 			fixcrlf(p, TRUE);
570 			message("214-", p);
571 			noinfo = FALSE;
572 		}
573 	}
574 
575 	if (noinfo)
576 		message("504", "HELP topic unknown");
577 	else
578 		message("214", "End of HELP info");
579 	(void) fclose(hf);
580 }
581 /*
582 **  RUNINCHILD -- return twice -- once in the child, then in the parent again
583 **
584 **	Parameters:
585 **		label -- a string used in error messages
586 **
587 **	Returns:
588 **		zero in the child
589 **		one in the parent
590 **
591 **	Side Effects:
592 **		none.
593 */
594 
595 runinchild(label, e)
596 	char *label;
597 	register ENVELOPE *e;
598 {
599 	int childpid;
600 
601 	if (!OneXact)
602 	{
603 		childpid = dofork();
604 		if (childpid < 0)
605 		{
606 			syserr("%s: cannot fork", label);
607 			return (1);
608 		}
609 		if (childpid > 0)
610 		{
611 			auto int st;
612 
613 			/* parent -- wait for child to complete */
614 			st = waitfor(childpid);
615 			if (st == -1)
616 				syserr("%s: lost child", label);
617 
618 			/* if we exited on a QUIT command, complete the process */
619 			if (st == (EX_QUIT << 8))
620 				finis();
621 
622 			return (1);
623 		}
624 		else
625 		{
626 			/* child */
627 			InChild = TRUE;
628 			QuickAbort = FALSE;
629 			clearenvelope(e, FALSE);
630 		}
631 	}
632 
633 	/* open alias database */
634 	initaliases(AliasFile, FALSE, e);
635 
636 	return (0);
637 }
638 
639 # endif /* SMTP */
640