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	5.33 (Berkeley) 12/15/91 (with SMTP)";
14 #else
15 static char sccsid[] = "@(#)srvrsmtp.c	5.33 (Berkeley) 12/15/91 (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()
90 {
91 	register char *p;
92 	register struct cmd *c;
93 	char *cmd;
94 	static char *skipword();
95 	bool hasmail;			/* mail command received */
96 	auto ADDRESS *vrfyqueue;
97 	ADDRESS *a;
98 	char *sendinghost;
99 	char inp[MAXLINE];
100 	char cmdbuf[100];
101 	extern char Version[];
102 	extern char *macvalue();
103 	extern ADDRESS *recipient();
104 	extern ENVELOPE BlankEnvelope;
105 	extern ENVELOPE *newenvelope();
106 
107 	hasmail = FALSE;
108 	if (OutChannel != stdout)
109 	{
110 		/* arrange for debugging output to go to remote host */
111 		(void) close(1);
112 		(void) dup(fileno(OutChannel));
113 	}
114 	settime();
115 	if (RealHostName != NULL)
116 	{
117 		CurHostName = RealHostName;
118 		setproctitle("srvrsmtp %s", CurHostName);
119 	}
120 	else
121 	{
122 		/* this must be us!! */
123 		CurHostName = MyHostName;
124 	}
125 	expand("\001e", inp, &inp[sizeof inp], CurEnv);
126 	message("220", inp);
127 	SmtpPhase = "startup";
128 	sendinghost = NULL;
129 	for (;;)
130 	{
131 		/* arrange for backout */
132 		if (setjmp(TopFrame) > 0 && InChild)
133 			finis();
134 		QuickAbort = FALSE;
135 		HoldErrs = FALSE;
136 		LogUsrErrs = FALSE;
137 
138 		/* setup for the read */
139 		CurEnv->e_to = NULL;
140 		Errors = 0;
141 		(void) fflush(stdout);
142 
143 		/* read the input line */
144 		p = sfgets(inp, sizeof inp, InChannel);
145 
146 		/* handle errors */
147 		if (p == NULL)
148 		{
149 			/* end of file, just die */
150 			message("421", "%s Lost input channel from %s",
151 				MyHostName, CurHostName);
152 			finis();
153 		}
154 
155 		/* clean up end of line */
156 		fixcrlf(inp, TRUE);
157 
158 		/* echo command to transcript */
159 		if (CurEnv->e_xfp != NULL)
160 			fprintf(CurEnv->e_xfp, "<<< %s\n", inp);
161 
162 		/* break off command */
163 		for (p = inp; isspace(*p); p++)
164 			continue;
165 		cmd = p;
166 		for (cmd = cmdbuf; *p != '\0' && !isspace(*p); )
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', CurEnv) == 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") > 0)
235 				break;
236 			define('s', sendinghost, CurEnv);
237 			define('r', "SMTP", CurEnv);
238 			initsys();
239 			setproctitle("%s %s: %s", CurEnv->e_id,
240 				CurHostName, inp);
241 
242 			/* child -- go do the processing */
243 			p = skipword(p, "from");
244 			if (p == NULL)
245 				break;
246 			setsender(p);
247 			if (Errors == 0)
248 			{
249 				message("250", "Sender ok");
250 				hasmail = TRUE;
251 			}
252 			else if (InChild)
253 				finis();
254 			break;
255 
256 		  case CMDRCPT:		/* rcpt -- designate recipient */
257 			SmtpPhase = "RCPT";
258 			setproctitle("%s %s: %s", CurEnv->e_id,
259 				CurHostName, inp);
260 			if (setjmp(TopFrame) > 0)
261 			{
262 				CurEnv->e_flags &= ~EF_FATALERRS;
263 				break;
264 			}
265 			QuickAbort = TRUE;
266 			LogUsrErrs = TRUE;
267 			p = skipword(p, "to");
268 			if (p == NULL)
269 				break;
270 			a = parseaddr(p, (ADDRESS *) NULL, 1, '\0');
271 			if (a == NULL)
272 				break;
273 			a->q_flags |= QPRIMARY;
274 			a = recipient(a, &CurEnv->e_sendqueue);
275 			if (Errors != 0)
276 				break;
277 
278 			/* no errors during parsing, but might be a duplicate */
279 			CurEnv->e_to = p;
280 			if (!bitset(QBADADDR, a->q_flags))
281 				message("250", "Recipient ok");
282 			else
283 			{
284 				/* punt -- should keep message in ADDRESS.... */
285 				message("550", "Addressee unknown");
286 			}
287 			CurEnv->e_to = NULL;
288 			break;
289 
290 		  case CMDDATA:		/* data -- text of mail */
291 			SmtpPhase = "DATA";
292 			if (!hasmail)
293 			{
294 				message("503", "Need MAIL command");
295 				break;
296 			}
297 			else if (CurEnv->e_nrcpts <= 0)
298 			{
299 				message("503", "Need RCPT (recipient)");
300 				break;
301 			}
302 
303 			/* collect the text of the message */
304 			SmtpPhase = "collect";
305 			setproctitle("%s %s: %s", CurEnv->e_id,
306 				CurHostName, inp);
307 			collect(TRUE);
308 			if (Errors != 0)
309 				break;
310 
311 			/*
312 			**  Arrange to send to everyone.
313 			**	If sending to multiple people, mail back
314 			**		errors rather than reporting directly.
315 			**	In any case, don't mail back errors for
316 			**		anything that has happened up to
317 			**		now (the other end will do this).
318 			**	Truncate our transcript -- the mail has gotten
319 			**		to us successfully, and if we have
320 			**		to mail this back, it will be easier
321 			**		on the reader.
322 			**	Then send to everyone.
323 			**	Finally give a reply code.  If an error has
324 			**		already been given, don't mail a
325 			**		message back.
326 			**	We goose error returns by clearing error bit.
327 			*/
328 
329 			SmtpPhase = "delivery";
330 			if (CurEnv->e_nrcpts != 1)
331 			{
332 				HoldErrs = TRUE;
333 				ErrorMode = EM_MAIL;
334 			}
335 			CurEnv->e_flags &= ~EF_FATALERRS;
336 			CurEnv->e_xfp = freopen(queuename(CurEnv, 'x'), "w", CurEnv->e_xfp);
337 
338 			/* send to all recipients */
339 			sendall(CurEnv, SM_DEFAULT);
340 			CurEnv->e_to = NULL;
341 
342 			/* save statistics */
343 			markstats(CurEnv, (ADDRESS *) NULL);
344 
345 			/* issue success if appropriate and reset */
346 			if (Errors == 0 || HoldErrs)
347 				message("250", "Ok");
348 			else
349 				CurEnv->e_flags &= ~EF_FATALERRS;
350 
351 			/* if in a child, pop back to our parent */
352 			if (InChild)
353 				finis();
354 
355 			/* clean up a bit */
356 			hasmail = 0;
357 			dropenvelope(CurEnv);
358 			CurEnv = newenvelope(CurEnv);
359 			CurEnv->e_flags = BlankEnvelope.e_flags;
360 			break;
361 
362 		  case CMDRSET:		/* rset -- reset state */
363 			message("250", "Reset state");
364 			if (InChild)
365 				finis();
366 			break;
367 
368 		  case CMDVRFY:		/* vrfy -- verify address */
369 			if (runinchild("SMTP-VRFY") > 0)
370 				break;
371 			setproctitle("%s: %s", CurHostName, inp);
372 			vrfyqueue = NULL;
373 			QuickAbort = TRUE;
374 			sendtolist(p, (ADDRESS *) NULL, &vrfyqueue);
375 			if (Errors != 0)
376 			{
377 				if (InChild)
378 					finis();
379 				break;
380 			}
381 			while (vrfyqueue != NULL)
382 			{
383 				register ADDRESS *a = vrfyqueue->q_next;
384 				char *code;
385 
386 				while (a != NULL && bitset(QDONTSEND|QBADADDR, a->q_flags))
387 					a = a->q_next;
388 
389 				if (!bitset(QDONTSEND|QBADADDR, vrfyqueue->q_flags))
390 				{
391 					if (a != NULL)
392 						code = "250-";
393 					else
394 						code = "250";
395 					if (vrfyqueue->q_fullname == NULL)
396 						message(code, "<%s>", vrfyqueue->q_paddr);
397 					else
398 						message(code, "%s <%s>",
399 						    vrfyqueue->q_fullname, vrfyqueue->q_paddr);
400 				}
401 				else if (a == NULL)
402 					message("554", "Self destructive alias loop");
403 				vrfyqueue = a;
404 			}
405 			if (InChild)
406 				finis();
407 			break;
408 
409 		  case CMDHELP:		/* help -- give user info */
410 			help(p);
411 			break;
412 
413 		  case CMDNOOP:		/* noop -- do nothing */
414 			message("200", "OK");
415 			break;
416 
417 		  case CMDQUIT:		/* quit -- leave mail */
418 			message("221", "%s closing connection", MyHostName);
419 			if (InChild)
420 				ExitStat = EX_QUIT;
421 			finis();
422 
423 		  case CMDVERB:		/* set verbose mode */
424 			Verbose = TRUE;
425 			SendMode = SM_DELIVER;
426 			message("200", "Verbose mode");
427 			break;
428 
429 		  case CMDONEX:		/* doing one transaction only */
430 			OneXact = TRUE;
431 			message("200", "Only one transaction");
432 			break;
433 
434 # ifdef SMTPDEBUG
435 		  case CMDDBGQSHOW:	/* show queues */
436 			printf("Send Queue=");
437 			printaddr(CurEnv->e_sendqueue, TRUE);
438 			break;
439 
440 		  case CMDDBGDEBUG:	/* set debug mode */
441 			tTsetup(tTdvect, sizeof tTdvect, "0-99.1");
442 			tTflag(p);
443 			message("200", "Debug set");
444 			break;
445 
446 # else /* not SMTPDEBUG */
447 
448 		  case CMDDBGQSHOW:	/* show queues */
449 		  case CMDDBGDEBUG:	/* set debug mode */
450 # ifdef LOG
451 			if (RealHostName != NULL && LogLevel > 0)
452 				syslog(LOG_NOTICE,
453 				    "\"%s\" command from %s (%s)\n",
454 				    c->cmdname, RealHostName,
455 				    inet_ntoa(RealHostAddr.sin_addr));
456 # endif
457 			/* FALL THROUGH */
458 # endif /* SMTPDEBUG */
459 
460 		  case CMDERROR:	/* unknown command */
461 			message("500", "Command unrecognized");
462 			break;
463 
464 		  default:
465 			errno = 0;
466 			syserr("smtp: unknown code %d", c->cmdcode);
467 			break;
468 		}
469 	}
470 }
471 /*
472 **  SKIPWORD -- skip a fixed word.
473 **
474 **	Parameters:
475 **		p -- place to start looking.
476 **		w -- word to skip.
477 **
478 **	Returns:
479 **		p following w.
480 **		NULL on error.
481 **
482 **	Side Effects:
483 **		clobbers the p data area.
484 */
485 
486 static char *
487 skipword(p, w)
488 	register char *p;
489 	char *w;
490 {
491 	register char *q;
492 
493 	/* find beginning of word */
494 	while (isspace(*p))
495 		p++;
496 	q = p;
497 
498 	/* find end of word */
499 	while (*p != '\0' && *p != ':' && !isspace(*p))
500 		p++;
501 	while (isspace(*p))
502 		*p++ = '\0';
503 	if (*p != ':')
504 	{
505 	  syntax:
506 		message("501", "Syntax error");
507 		Errors++;
508 		return (NULL);
509 	}
510 	*p++ = '\0';
511 	while (isspace(*p))
512 		p++;
513 
514 	/* see if the input word matches desired word */
515 	if (strcasecmp(q, w))
516 		goto syntax;
517 
518 	return (p);
519 }
520 /*
521 **  HELP -- implement the HELP command.
522 **
523 **	Parameters:
524 **		topic -- the topic we want help for.
525 **
526 **	Returns:
527 **		none.
528 **
529 **	Side Effects:
530 **		outputs the help file to message output.
531 */
532 
533 help(topic)
534 	char *topic;
535 {
536 	register FILE *hf;
537 	int len;
538 	char buf[MAXLINE];
539 	bool noinfo;
540 
541 	if (HelpFile == NULL || (hf = fopen(HelpFile, "r")) == NULL)
542 	{
543 		/* no help */
544 		errno = 0;
545 		message("502", "HELP not implemented");
546 		return;
547 	}
548 
549 	if (topic == NULL || *topic == '\0')
550 		topic = "smtp";
551 	else
552 		makelower(topic);
553 
554 	len = strlen(topic);
555 	noinfo = TRUE;
556 
557 	while (fgets(buf, sizeof buf, hf) != NULL)
558 	{
559 		if (strncmp(buf, topic, len) == 0)
560 		{
561 			register char *p;
562 
563 			p = index(buf, '\t');
564 			if (p == NULL)
565 				p = buf;
566 			else
567 				p++;
568 			fixcrlf(p, TRUE);
569 			message("214-", p);
570 			noinfo = FALSE;
571 		}
572 	}
573 
574 	if (noinfo)
575 		message("504", "HELP topic unknown");
576 	else
577 		message("214", "End of HELP info");
578 	(void) fclose(hf);
579 }
580 /*
581 **  RUNINCHILD -- return twice -- once in the child, then in the parent again
582 **
583 **	Parameters:
584 **		label -- a string used in error messages
585 **
586 **	Returns:
587 **		zero in the child
588 **		one in the parent
589 **
590 **	Side Effects:
591 **		none.
592 */
593 
594 runinchild(label)
595 	char *label;
596 {
597 	int childpid;
598 
599 	if (!OneXact)
600 	{
601 		childpid = dofork();
602 		if (childpid < 0)
603 		{
604 			syserr("%s: cannot fork", label);
605 			return (1);
606 		}
607 		if (childpid > 0)
608 		{
609 			auto int st;
610 
611 			/* parent -- wait for child to complete */
612 			st = waitfor(childpid);
613 			if (st == -1)
614 				syserr("%s: lost child", label);
615 
616 			/* if we exited on a QUIT command, complete the process */
617 			if (st == (EX_QUIT << 8))
618 				finis();
619 
620 			return (1);
621 		}
622 		else
623 		{
624 			/* child */
625 			InChild = TRUE;
626 			QuickAbort = FALSE;
627 			clearenvelope(CurEnv, FALSE);
628 		}
629 	}
630 
631 	/* open alias database */
632 	initaliases(AliasFile, FALSE);
633 
634 	return (0);
635 }
636 
637 # endif SMTP
638