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