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