Synchronet now requires the libarchive development package (e.g. libarchive-dev on Debian-based Linux distros, libarchive.org for more info) to build successfully.

mailsrvr.c 202 KB
Newer Older
1 2 3
/* Synchronet Mail (SMTP/POP3) server and sendmail threads */

/* $Id$ */
4
// vi: tabstop=4
5 6 7 8 9

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
10
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
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
 *																			*
 * This program is free software; you can redistribute it and/or			*
 * modify it under the terms of the GNU General Public License				*
 * as published by the Free Software Foundation; either version 2			*
 * of the License, or (at your option) any later version.					*
 * See the GNU General Public License for more details: gpl.txt or			*
 * http://www.fsf.org/copyleft/gpl.html										*
 *																			*
 * Anonymous FTP access to the most recent released source is available at	*
 * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net	*
 *																			*
 * Anonymous CVS access to the development source and modification history	*
 * is available at cvs.synchro.net:/cvsroot/sbbs, example:					*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login			*
 *     (just hit return, no password is necessary)							*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src		*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * You are encouraged to submit any modifications (preferably in Unix diff	*
 * format) via e-mail to mods@synchro.net									*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

rswindell's avatar
rswindell committed
37
/* ANSI C Library headers */
deuce's avatar
deuce committed
38
#include <limits.h>			/* UINT_MAX */
rswindell's avatar
rswindell committed
39
#include <stdio.h>
40 41 42 43 44 45
#include <stdlib.h>			/* ltoa in GNU C lib */
#include <stdarg.h>			/* va_list */
#include <string.h>			/* strrchr */
#include <ctype.h>			/* isdigit */
#include <fcntl.h>			/* Open flags */
#include <errno.h>			/* errno */
rswindell's avatar
rswindell committed
46 47

/* Synchronet-specific headers */
48
#undef SBBS	/* this shouldn't be defined unless building sbbs.dll/libsbbs.so */
49
#include "sbbs.h"
rswindell's avatar
rswindell committed
50
#include "mailsrvr.h"
51
#include "utf8.h"
52
#include "mime.h"
53
#include "md5.h"
54
#include "crc32.h"
55
#include "base64.h"
56
#include "ini_file.h"
57
#include "netwrap.h"	/* getNameServerList() */
58
#include "xpendian.h"
59
#include "js_rtpool.h"
60
#include "js_request.h"
deuce's avatar
deuce committed
61
#include "multisock.h"
62 63
#include "ssl.h"
#include "cryptlib.h"
64

rswindell's avatar
rswindell committed
65
/* Constants */
66
static const char*	server_name="Synchronet Mail Server";
67 68
#define FORWARD			"forward:"
#define NO_FORWARD		"local:"
69
#define NO_SPAM			"#nospam"
70

71 72
int dns_getmx(char* name, char* mx, char* mx2
			  ,DWORD intf, DWORD ip_addr, BOOL use_tcp, int timeout);
73

74 75 76 77 78 79 80 81 82 83
#define pop_err			"-ERR"
#define ok_rsp			"250 OK"
#define auth_ok			"235 User Authenticated"
#define sys_error		"421 System error"
#define sys_unavail		"421 System unavailable, try again later"
#define insuf_stor		"452 Insufficient system storage"
#define badarg_rsp 		"501 Bad argument"
#define badseq_rsp		"503 Bad sequence of commands"
#define badauth_rsp		"535 Authentication failure"
#define badrsp_err		"%s replied with:\r\n\"%s\"\r\ninstead of the expected reply:\r\n\"%s ...\""
84

85
#define TIMEOUT_THREAD_WAIT		60		/* Seconds */
86
#define DNSBL_THROTTLE_VALUE	1000	/* Milliseconds */
87 88 89 90 91

#define STATUS_WFC	"Listening"

static mail_startup_t* startup=NULL;
static scfg_t	scfg;
deuce's avatar
deuce committed
92 93
static struct xpms_set	*mail_set=NULL;
static BOOL terminated=FALSE;
94 95
static protected_uint32_t active_clients;
static protected_uint32_t thread_count;
96 97 98 99
static volatile int		active_sendmail=0;
static volatile BOOL	sendmail_running=FALSE;
static volatile BOOL	terminate_server=FALSE;
static volatile BOOL	terminate_sendmail=FALSE;
100
static sem_t	sendmail_wakeup_sem;
101
static char		revision[16];
102
static volatile time_t	uptime;
103 104
static str_list_t recycle_semfiles;
static str_list_t shutdown_semfiles;
105
static int		mailproc_count;
106
static js_server_props_t js_server_props;
107

108
struct {
109 110 111 112 113 114 115 116
	volatile ulong	sockets;
	volatile ulong	errors;
	volatile ulong	crit_errors;
	volatile ulong	connections_ignored;
	volatile ulong	connections_refused;
	volatile ulong	connections_served;
	volatile ulong	pop3_served;
	volatile ulong	smtp_served;
117
	/* SMTP: */
118 119 120 121
	volatile ulong	sessions_refused;
	volatile ulong	msgs_ignored;
	volatile ulong	msgs_refused;
	volatile ulong	msgs_received;
122 123
} stats;

124
struct mailproc {
rswindell's avatar
rswindell committed
125
	char		name[INI_MAX_VALUE_LEN];
126
	char		cmdline[INI_MAX_VALUE_LEN];
rswindell's avatar
rswindell committed
127
	char		eval[INI_MAX_VALUE_LEN];
128
	str_list_t	to;
129
	str_list_t	from;
130 131
	BOOL		passthru;
	BOOL		native;
132
	BOOL		ignore_on_error;	/* Ignore mail message if cmdline fails */
133
	BOOL		disabled;
134 135
	BOOL		process_spam;
	BOOL		process_dnsbl;
136
	uint8_t*	ar;
137
	ulong		handled;			/* counter (for stats display) */
138
} *mailproc_list;
139 140 141

typedef struct {
	SOCKET			socket;
deuce's avatar
deuce committed
142 143
	union xp_sockaddr	client_addr;
	socklen_t		client_addr_len;
144
	BOOL			tls_port;
145 146
} smtp_t,pop3_t;

deuce's avatar
deuce committed
147
#define GCES(status, server, sock, sess, action) do {                             \
deuce's avatar
deuce committed
148 149
	char *GCES_estr;                                                               \
	int GCES_level;                                                                 \
deuce's avatar
deuce committed
150
	get_crypt_error_string(status, sess, &GCES_estr, action, &GCES_level);  \
deuce's avatar
deuce committed
151
	if (GCES_estr) {                                                                  \
152
		lprintf(GCES_level, "%04d %s/TLS %s", sock, server, GCES_estr);                     \
deuce's avatar
deuce committed
153
		free_crypt_attrstr(GCES_estr);                                                  \
154 155 156
	}                                                                                    \
} while(0)

deuce's avatar
deuce committed
157
#define GCESH(status, server, sock, host, sess, action) do {                      \
deuce's avatar
deuce committed
158 159
	char *GCES_estr;                                                               \
	int GCES_level;                                                                 \
deuce's avatar
deuce committed
160
	get_crypt_error_string(status, sess, &GCES_estr, action, &GCES_level);  \
deuce's avatar
deuce committed
161
	if (GCES_estr) {                                                                  \
162
		lprintf(GCES_level, "%04d %s/TLS [%s] %s", sock, server, host, GCES_estr);         \
deuce's avatar
deuce committed
163
		free_crypt_attrstr(GCES_estr);                                                  \
164 165 166
	}                                                                                    \
} while(0)

167 168 169
#if defined(__GNUC__)   // Catch printf-format errors with lprintf
static int lprintf(int level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
#endif
170
static int lprintf(int level, const char *fmt, ...)
171 172 173 174 175
{
	va_list argptr;
	char sbuf[1024];

	va_start(argptr,fmt);
176 177
    vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
	sbuf[sizeof(sbuf)-1]=0;
178
    va_end(argptr);
179

180
	if(level <= LOG_ERR) {
181 182 183
		char errmsg[sizeof(sbuf)+16];
		SAFEPRINTF(errmsg, "mail %s", sbuf);
		errorlog(&scfg,startup==NULL ? NULL:startup->host_name,errmsg), stats.errors++;
184
		if(startup!=NULL && startup->errormsg!=NULL)
185
			startup->errormsg(startup->cbdata,level,errmsg);
186
	}
187 188 189

	if(level <= LOG_CRIT)
		stats.crit_errors++;
190 191 192 193 194 195 196 197 198

    if(startup==NULL || startup->lputs==NULL || level > startup->log_level)
		return(0);

#if defined(_WIN32)
	if(IsBadCodePtr((FARPROC)startup->lputs))
		return(0);
#endif

199
    return(startup->lputs(startup->cbdata,level,sbuf));
200 201 202 203 204
}

#ifdef _WINSOCKAPI_

static WSADATA WSAData;
205
#define SOCKLIB_DESC WSAData.szDescription
206
static BOOL WSAInitialized=FALSE;
207 208 209 210 211 212

static BOOL winsock_startup(void)
{
	int		status;             /* Status Code */

    if((status = WSAStartup(MAKEWORD(1,1), &WSAData))==0) {
213
		lprintf(LOG_DEBUG,"%s %s",WSAData.szDescription, WSAData.szSystemStatus);
214
		WSAInitialized=TRUE;
215 216 217
		return (TRUE);
	}

218
    lprintf(LOG_CRIT,"!WinSock startup ERROR %d", status);
219 220 221 222 223
	return (FALSE);
}

#else /* No WINSOCK */

rswindell's avatar
rswindell committed
224
#define winsock_startup()	(TRUE)
225
#define SOCKLIB_DESC NULL
226 227 228 229 230

#endif

static void update_clients(void)
{
231
	if(startup!=NULL && startup->clients!=NULL)
232
		startup->clients(startup->cbdata,protected_uint32_value(active_clients)+active_sendmail);
233 234
}

235
static void client_on(SOCKET sock, client_t* client, BOOL update)
236
{
237
	if(startup!=NULL && startup->client_on!=NULL)
238
		startup->client_on(startup->cbdata,TRUE,sock,client,update);
239 240 241 242
}

static void client_off(SOCKET sock)
{
243
	if(startup!=NULL && startup->client_on!=NULL)
244
		startup->client_on(startup->cbdata,FALSE,sock,NULL,FALSE);
245 246
}

247
static void thread_up(BOOL setuid)
248 249
{
	if(startup!=NULL && startup->thread_up!=NULL)
250
		startup->thread_up(startup->cbdata,TRUE,setuid);
251 252
}

253
static int32_t thread_down(void)
254
{
255
	int32_t count = protected_uint32_adjust(&thread_count,-1);
256
	if(startup!=NULL && startup->thread_up!=NULL)
257
		startup->thread_up(startup->cbdata,FALSE,FALSE);
258
	return count;
259 260
}

deuce's avatar
deuce committed
261
void mail_open_socket(SOCKET sock, void* cb_protocol)
262
{
deuce's avatar
deuce committed
263
	char	*protocol=(char *)cb_protocol;
264
	char	error[256];
265
	char	section[128];
266

deuce's avatar
deuce committed
267
	if(startup!=NULL && startup->socket_open!=NULL)
268
		startup->socket_open(startup->cbdata,TRUE);
deuce's avatar
deuce committed
269 270
	SAFEPRINTF(section,"mail|%s",protocol);
	if(set_socket_options(&scfg, sock, section, error, sizeof(error)))
271
		lprintf(LOG_ERR,"%04d %s !ERROR %s", sock, protocol, error);
272

deuce's avatar
deuce committed
273 274 275 276 277 278 279 280
	stats.sockets++;
}

void mail_close_socket_cb(SOCKET sock, void* cb_protocol)
{
	if(startup!=NULL && startup->socket_open!=NULL)
		startup->socket_open(startup->cbdata,FALSE);
	stats.sockets--;
281 282
}

283
int mail_close_socket(SOCKET *sock, int *sess)
284 285 286
{
	int		result;

287 288 289 290 291
	if (*sess != -1) {
		cryptDestroySession(*sess);
		*sess = -1;
	}
	if(*sock==INVALID_SOCKET)
292 293
		return(-1);

294 295
	shutdown(*sock,SHUT_RDWR);	/* required on Unix */
	result=closesocket(*sock);
296
	if(startup!=NULL && startup->socket_open!=NULL)
297
		startup->socket_open(startup->cbdata,FALSE);
298
	stats.sockets--;
299 300
	if(result!=0) {
		if(ERROR_VALUE!=ENOTSOCK)
301
			lprintf(LOG_WARNING,"%04d !ERROR %d closing socket",*sock, ERROR_VALUE);
302
	}
303
#if 0 /*def _DEBUG */
304
	else 
305
		lprintf(LOG_DEBUG,"%04d Socket closed (%d sockets in use)",*sock,stats.sockets);
306 307
#endif

308 309
	*sock = -1;

310 311 312 313 314
	return(result);
}

static void status(char* str)
{
315
	if(startup!=NULL && startup->status!=NULL)
316
	    startup->status(startup->cbdata,str);
317 318
}

319
int sockprintf(SOCKET sock, const char* prot, CRYPT_SESSION sess, char *fmt, ...)
320 321
{
	int		len;
322
	int		maxlen;
323 324 325
	int		result;
	va_list argptr;
	char	sbuf[1024];
326 327
	fd_set	socket_set;
	struct timeval tv;
328 329

    va_start(argptr,fmt);
330 331 332
    len=vsnprintf(sbuf,maxlen=sizeof(sbuf)-2,fmt,argptr);
    va_end(argptr);

333
	if(len<0 || len > maxlen) /* format error or output truncated */
334
		len=maxlen;
335
	if(startup->options&MAIL_OPT_DEBUG_TX)
336
		lprintf(LOG_DEBUG,"%04d %s TX: %.*s", sock, prot, len, sbuf);
337
	memcpy(sbuf+len,"\r\n",2);
338
	len+=2;
339

340
	if(sock==INVALID_SOCKET) {
341
		lprintf(LOG_WARNING,"%s !INVALID SOCKET in call to sockprintf", prot);
342 343 344
		return(0);
	}

345
	/* Check socket for writability (using select) */
346
	tv.tv_sec=300;
347 348 349 350 351 352
	tv.tv_usec=0;

	FD_ZERO(&socket_set);
	FD_SET(sock,&socket_set);

	if((result=select(sock+1,NULL,&socket_set,NULL,&tv))<1) {
353
		if(result==0)
354 355
			lprintf(LOG_NOTICE,"%04d %s !TIMEOUT selecting socket for send"
				,sock, prot);
356
		else
357 358
			lprintf(LOG_NOTICE,"%04d %s !ERROR %d selecting socket for send"
				,sock, prot, ERROR_VALUE);
359 360 361
		return(0);
	}

362 363 364 365 366 367 368
	if (sess != -1) {
		int tls_sent;
		int sent = 0;
		while (sent < len) {
			result = cryptPushData(sess, sbuf+sent, len-sent, &tls_sent);
			if (result == CRYPT_OK)
				sent += tls_sent;
369
			else {
370
				GCES(result, prot, sock, sess, "pushing data");
371
				return 0;
372
			}
373
		}
374
		if ((result = cryptFlushData(sess)) != CRYPT_OK) {
375
			GCES(result, prot, sock, sess, "flushing data");
376
			return 0;
377
		}
378 379 380 381 382 383 384 385 386 387
	}
	else {
		// It looks like this could stutter on partial sends -- Deuce
		while((result=sendsocket(sock,sbuf,len))!=len) {
			if(result==SOCKET_ERROR) {
				if(ERROR_VALUE==EWOULDBLOCK) {
					YIELD();
					continue;
				}
				if(ERROR_VALUE==ECONNRESET) 
388
					lprintf(LOG_NOTICE,"%04d %s Connection reset by peer on send",sock,prot);
389
				else if(ERROR_VALUE==ECONNABORTED) 
390
					lprintf(LOG_NOTICE,"%04d %s Connection aborted by peer on send",sock, prot);
391
				else
392
					lprintf(LOG_NOTICE,"%04d %s !ERROR %d sending on socket",sock,prot,ERROR_VALUE);
393 394
				return(0);
			}
395
			lprintf(LOG_WARNING,"%04d %s !ERROR: short send on socket: %d instead of %d",sock,prot,result,len);
396 397 398 399 400
		}
	}
	return(len);
}

401
static void sockerror(SOCKET socket, const char* prot, int rd, const char* action)
402 403
{
	if(rd==0) 
404 405
		lprintf(LOG_NOTICE,"%04d %s Socket closed by peer on %s"
			,socket, prot, action);
406
	else if(rd==SOCKET_ERROR) {
rswindell's avatar
rswindell committed
407
		if(ERROR_VALUE==ECONNRESET) 
408 409
			lprintf(LOG_NOTICE,"%04d %s Connection reset by peer on %s"
				,socket, prot, action);
410
		else if(ERROR_VALUE==ECONNABORTED) 
411 412
			lprintf(LOG_NOTICE,"%04d %s Connection aborted by peer on %s"
				,socket, prot, action);
413
		else
414 415
			lprintf(LOG_NOTICE,"%04d %s !SOCKET ERROR %d on %s"
				,socket, prot, ERROR_VALUE, action);
416
	} else
417 418
		lprintf(LOG_WARNING,"%04d %s !SOCKET ERROR: unexpected return value %d from %s"
			,socket, prot, rd, action);
419 420
}

421
static int sock_recvbyte(SOCKET sock, const char* prot, CRYPT_SESSION sess, char *buf, time_t start)
422 423 424 425 426 427 428 429 430 431
{
	int len=0;
	fd_set	socket_set;
	struct	timeval	tv;
	int ret;
	int i;

	if (sess > -1) {
		while (1) {
			ret = cryptPopData(sess, buf, 1, &len);
432
			GCES(ret, prot, sock, sess, "popping data");
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
			switch(ret) {
				case CRYPT_OK:
					break;
				case CRYPT_ERROR_TIMEOUT:
					return -1;
				case CRYPT_ERROR_COMPLETE:
					return 0;
				default:
					if (ret < -1)
						return ret;
					return -2;
			}
			if (len)
				return len;
			if(startup->max_inactivity && (time(NULL)-start)>startup->max_inactivity) {
448 449
				lprintf(LOG_WARNING,"%04d %s !TIMEOUT in sock_recvbyte (%u seconds):  INACTIVE SOCKET"
					,sock, prot, startup->max_inactivity);
450 451 452 453 454 455 456 457 458 459 460 461
				return(-1);
			}
		}
	}
	else {
		tv.tv_sec=startup->max_inactivity;
		tv.tv_usec=0;

		FD_ZERO(&socket_set);
		FD_SET(sock,&socket_set);

		i=select(sock+1,&socket_set,NULL,NULL,&tv);
462

463 464 465
		if(i<1) {
			if(i==0) {
				if(startup->max_inactivity && (time(NULL)-start)>startup->max_inactivity) {
466 467
					lprintf(LOG_WARNING,"%04d %s !TIMEOUT in sock_recvbyte (%u seconds):  INACTIVE SOCKET"
						,sock, prot, startup->max_inactivity);
468 469 470 471
					return(-1);
				}
				return 0;
			}
472
			sockerror(sock,prot,i,"select");
473 474 475 476
			return 0;
		}
		i=recv(sock, buf, 1, 0);
		if(i<1)
477
			sockerror(sock,prot,i,"receive");
478 479 480 481
		return i;
	}
}

482
static int sockreadline(SOCKET socket, const char* prot, CRYPT_SESSION sess, char* buf, int len)
483 484 485 486 487
{
	char	ch;
	int		i,rd=0;
	time_t	start;

488 489
	buf[0]=0;

490
	start=time(NULL);
491 492

	if(socket==INVALID_SOCKET) {
493
		lprintf(LOG_WARNING,"%s !INVALID SOCKET in call to sockreadline", prot);
494
		return(-1);
495
	}
496 497
	
	while(rd<len-1) {
498

deuce's avatar
deuce committed
499
		if(terminated || terminate_server) {
500
			lprintf(LOG_WARNING,"%04d %s !ABORTING sockreadline",socket, prot);
501 502 503
			return(-1);
		}

504
		i = sock_recvbyte(socket, prot, sess, &ch, start);
505

506
		if(i<1)
507
			return(-1);
508

509
		if(ch=='\n' /* && rd>=1 */ ) { /* Mar-9-2003: terminate on sole LF */
510
			break;
511
		}
512 513
		buf[rd++]=ch;
	}
514
	if(rd>0 && buf[rd-1]=='\r')
515 516
		rd--;
	buf[rd]=0;
517 518 519 520
	
	return(rd);
}

521
static BOOL sockgetrsp(SOCKET socket, const char* prot, CRYPT_SESSION sess, char* rsp, char *buf, int len)
522 523 524 525
{
	int rd;

	while(1) {
526
		rd = sockreadline(socket, prot, sess, buf, len);
527
		if(rd<1) {
528
			if(rd==0 && rsp != NULL)
529
				lprintf(LOG_WARNING,"%04d %s !RECEIVED BLANK RESPONSE, Expected '%s'", socket, prot, rsp);
530
			return(FALSE);
531
		}
532 533
		if(buf[3]=='-')	{ /* Multi-line response */
			if(startup->options&MAIL_OPT_DEBUG_RX_RSP) 
534
				lprintf(LOG_DEBUG,"%04d %s RX: %s",socket, prot, buf);
535 536
			continue;
		}
537
		if(rsp!=NULL && strnicmp(buf,rsp,strlen(rsp))) {
538
			lprintf(LOG_WARNING,"%04d %s !INVALID RESPONSE: '%s' Expected: '%s'", socket, prot, buf, rsp);
539 540 541 542 543
			return(FALSE);
		}
		break;
	}
	if(startup->options&MAIL_OPT_DEBUG_RX_RSP) 
544
		lprintf(LOG_DEBUG,"%04d %s RX: %s",socket, prot, buf);
545 546 547
	return(TRUE);
}

548
static int sockgetrsp_opt(SOCKET socket, const char* prot, CRYPT_SESSION sess, char* rsp, char *opt, char *buf, int len)
549 550 551 552 553 554
{
	int rd;
	int ret = 0;
	size_t moptlen;
	char *mopt;

555
	moptlen = strlen(rsp)+strlen(opt) + 1;
556 557 558 559 560
	mopt = malloc(moptlen+1);
	if (mopt == NULL)
		return -1;
	sprintf(mopt, "%s-%s", rsp, opt);
	while(1) {
561
		rd = sockreadline(socket, prot, sess, buf, len);
562 563
		if(rd<1) {
			if(rd==0)
564
				lprintf(LOG_WARNING,"%04d %s !RECEIVED BLANK RESPONSE, Expected '%s'", socket, prot, rsp);
565 566 567 568 569 570 571
			free(mopt);
			return(-1);
		}
		if(buf[3]=='-')	{ /* Multi-line response */
			if (strncmp(buf, mopt, moptlen) == 0)
				ret = 1;
			if(startup->options&MAIL_OPT_DEBUG_RX_RSP) 
572
				lprintf(LOG_DEBUG,"%04d %s RX: %s",socket, prot, buf);
573 574 575
			continue;
		}
		if(rsp!=NULL && strnicmp(buf,rsp,strlen(rsp))) {
576
			lprintf(LOG_WARNING,"%04d %s !INVALID RESPONSE: '%s' Expected: '%s'", socket, prot, buf, rsp);
577 578 579 580 581
			free(mopt);
			return(-1);
		}
		break;
	}
582
	mopt[strlen(rsp)] = ' ';
583
	if (strncmp(buf, mopt, moptlen) == 0)
584
		ret = 1;
585 586
	free(mopt);
	if(startup->options&MAIL_OPT_DEBUG_RX_RSP)
587
		lprintf(LOG_DEBUG,"%04d %s RX: %s",socket, prot, buf);
588 589 590
	return(ret);
}

rswindell's avatar
rswindell committed
591
/* non-standard, but documented (mostly) in draft-newman-msgheader-originfo-05 */
592
void originator_info(SOCKET socket, const char* protocol, CRYPT_SESSION sess, smbmsg_t* msg)
rswindell's avatar
rswindell committed
593 594 595 596 597 598 599 600 601 602 603
{
	char* user		= msg->from_ext;
	char* login		= smb_get_hfield(msg,SENDERUSERID,NULL);
	char* server	= smb_get_hfield(msg,SENDERSERVER,NULL);
	char* client	= smb_get_hfield(msg,SENDERHOSTNAME,NULL);
	char* addr		= smb_get_hfield(msg,SENDERIPADDR,NULL);
	char* prot		= smb_get_hfield(msg,SENDERPROTOCOL,NULL);
	char* port		= smb_get_hfield(msg,SENDERPORT,NULL);
	char* time		= smb_get_hfield(msg,SENDERTIME,NULL);

	if(user || login || server || client || addr || prot || port || time)
604
		sockprintf(socket, protocol, sess
rswindell's avatar
rswindell committed
605 606 607 608 609 610 611 612 613 614 615 616
			,"X-Originator-Info: account=%s; login-id=%s; server=%s; client=%s; addr=%s; prot=%s; port=%s; time=%s"
			,user
			,login
			,server
			,client
			,addr
			,prot
			,port
			,time
			);
}

617 618 619 620 621 622 623
/* RFC822: The maximum total length of a text line including the
   <CRLF> is 1000 characters (but not counting the leading
   dot duplicated for transparency). 

   POP3 (RFC1939) actually calls for a 512 byte line length limit!
*/
#define MAX_LINE_LEN	998		
624

625
static ulong sockmimetext(SOCKET socket, const char* prot, CRYPT_SESSION sess, smbmsg_t* msg, char* msgtxt, ulong maxlines
626
						  ,str_list_t file_list, char* mime_boundary)
627
{
628 629
	char		toaddr[256]="";
	char		fromaddr[256]="";
630
	char		fromhost[256];
rswindell's avatar
rswindell committed
631
	char		msgid[256];
632
	char		date[64];
rswindell's avatar
rswindell committed
633
	char*		p;
634
	char*		np;
635
	char*		content_type=NULL;
636
	int			i;
637
	int			s;
638
	ulong		lines;
639
	int			len,tlen;
640

641
	/* HEADERS (in recommended order per RFC822 4.1) */
642 643

	if(msg->reverse_path!=NULL)
644
		if(!sockprintf(socket,prot,sess,"Return-Path: %s", msg->reverse_path))
645 646
			return(0);

647 648
	for(i=0;i<msg->total_hfields;i++)
		if(msg->hfield[i].type == SMTPRECEIVED && msg->hfield_dat[i]!=NULL) 
649
			if(!sockprintf(socket,prot,sess,"Received: %s", (char*)msg->hfield_dat[i]))
650 651
				return(0);

652
	if(!sockprintf(socket,prot,sess,"Date: %s",msgdate(msg->hdr.when_written,date)))
653
		return(0);
654 655

	if((p=smb_get_hfield(msg,RFC822FROM,NULL))!=NULL)
656
		s=sockprintf(socket,prot,sess,"From: %s",p);	/* use original RFC822 header field */
657
	else {
rswindell's avatar
rswindell committed
658
		char fromname[256];
rswindell's avatar
rswindell committed
659
		SAFEPRINTF(fromname, "\"%s\"", msg->from);
660
		if(msg->from_net.type==NET_QWK && msg->from_net.addr!=NULL)
661
			SAFEPRINTF2(fromaddr,"%s!%s"
662 663
				,(char*)msg->from_net.addr
				,usermailaddr(&scfg,fromhost,msg->from));
rswindell's avatar
rswindell committed
664 665 666
		else if(msg->from_net.type==NET_FIDO && msg->from_net.addr!=NULL) {
			faddr_t* faddr = (faddr_t *)msg->from_net.addr;
			char faddrstr[128];
rswindell's avatar
rswindell committed
667
			SAFEPRINTF2(fromname,"\"%s\" (%s)", msg->from, smb_faddrtoa(faddr, NULL));
rswindell's avatar
rswindell committed
668 669 670 671 672 673 674 675
			if(faddr->point)
				SAFEPRINTF4(faddrstr,"p%hu.f%hu.n%hu.z%hu"FIDO_TLD
					,faddr->point, faddr->node, faddr->net, faddr->zone);
			else
				SAFEPRINTF3(faddrstr,"f%hu.n%hu.z%hu"FIDO_TLD
					,faddr->node, faddr->net, faddr->zone);
			SAFEPRINTF2(fromaddr,"%s@%s", usermailaddr(NULL,fromhost,msg->from), faddrstr);
		} else if(msg->from_net.type!=NET_NONE && msg->from_net.addr!=NULL)
676
			SAFECOPY(fromaddr,(char*)msg->from_net.addr);
677 678 679
		else 
			usermailaddr(&scfg,fromaddr,msg->from);
		if(fromaddr[0]=='<')
680
			s=sockprintf(socket,prot,sess,"From: %s %s",fromname,fromaddr);
681
		else
682
			s=sockprintf(socket,prot,sess,"From: %s <%s>",fromname,fromaddr);
683
	}
684 685
	if(!s)
		return(0);
686

687 688
	if((p = smb_get_hfield(msg, RFC822ORG, NULL)) != NULL) {
		if(!sockprintf(socket,prot,sess,"Organization: %s", p))
689
			return(0);
690 691 692 693 694 695
	} else {
		if(msg->from_org!=NULL || msg->from_net.type==NET_NONE)
			if(!sockprintf(socket,prot,sess,"Organization: %s"
				,msg->from_org==NULL ? scfg.sys_name : msg->from_org))
				return(0);
	}
696

697 698
	p = smb_get_hfield(msg, RFC822SUBJECT, NULL);
	if(!sockprintf(socket,prot,sess,"Subject: %s", p == NULL ? msg->subj : p))
699
		return(0);
700

701 702
	if((p = smb_get_hfield(msg, RFC822TO, NULL)) != NULL)
		s=sockprintf(socket,prot,sess,"To: %s", p);	/* use original RFC822 header field */
703 704
	else {
		if(strchr(msg->to,'@')!=NULL || msg->to_net.addr==NULL)
705
			s=sockprintf(socket,prot,sess,"To: %s",msg->to);	/* Avoid double-@ */
706 707
		else if(msg->to_net.type==NET_INTERNET || msg->to_net.type==NET_QWK) {
			if(strchr((char*)msg->to_net.addr,'<')!=NULL)
708
				s=sockprintf(socket,prot,sess,"To: %s",(char*)msg->to_net.addr);
709
			else
710
				s=sockprintf(socket,prot,sess,"To: \"%s\" <%s>",msg->to,(char*)msg->to_net.addr);
rswindell's avatar
rswindell committed
711
		} else if(msg->to_net.type==NET_FIDO) {
712
			s=sockprintf(socket,prot,sess,"To: \"%s\" (%s)",msg->to, smb_faddrtoa((fidoaddr_t*)msg->to_net.addr, NULL));
713 714
		} else {
			usermailaddr(&scfg,toaddr,msg->to);
715
			s=sockprintf(socket,prot,sess,"To: \"%s\" <%s>",msg->to,toaddr);
716
		}
717
	}
718 719
	if(!s)
		return(0);
720 721
	if((p = smb_get_hfield(msg, RFC822CC, NULL)) != NULL || msg->cc_list != NULL)
		if(!sockprintf(socket,prot,sess,"Cc: %s", p == NULL ? msg->cc_list : p))
722
			return(0);
723
	np=NULL;
724
	if((p = smb_get_hfield(msg, RFC822REPLYTO, NULL)) == NULL) {
725
		np=msg->replyto;
726
		if(msg->replyto_net.type==NET_INTERNET)
rswindell's avatar
rswindell committed
727
			p=msg->replyto_net.addr;
728
	}
rswindell's avatar
rswindell committed
729
	if(p!=NULL && strchr((char*)p, '@') != NULL) {
730
		if(np!=NULL)
731
			s=sockprintf(socket,prot,sess,"Reply-To: \"%s\" <%s>",np,p);
732
		else 
733
			s=sockprintf(socket,prot,sess,"Reply-To: %s",p);
734
	}
735 736
	if(!s)
		return(0);
737
	if(!sockprintf(socket,prot,sess,"Message-ID: %s",get_msgid(&scfg,INVALID_SUB,msg,msgid,sizeof(msgid))))
738
		return(0);
739
	if(msg->reply_id!=NULL)
740
		if(!sockprintf(socket,prot,sess,"In-Reply-To: %s",msg->reply_id))
741
			return(0);
742

743 744 745 746
	if(msg->hdr.priority != SMB_PRIORITY_UNSPECIFIED)
		if(!sockprintf(socket,prot,sess,"X-Priority: %u", (uint)msg->hdr.priority))
			return(0);

747
	originator_info(socket, prot, sess, msg);
748

749 750 751 752 753 754 755 756 757 758 759 760
	/* Include all possible FidoNet header fields here */
	for(i=0;i<msg->total_hfields;i++) {
		switch(msg->hfield[i].type) {
			case FIDOCTRL:
			case FIDOAREA:	
			case FIDOSEENBY:
			case FIDOPATH:
			case FIDOMSGID:
			case FIDOREPLYID:
			case FIDOPID:
			case FIDOFLAGS:
			case FIDOTID:
761
				if(!sockprintf(socket, prot, sess, "%s: %s", smb_hfieldtype(msg->hfield[i].type), (char*)msg->hfield_dat[i]))
762 763 764 765 766
					return(0);
				break;
		}
	}
	for(i=0;i<msg->total_hfields;i++) { 
767
		if(msg->hfield[i].type==RFC822HEADER) { 
768 769
			if(strnicmp((char*)msg->hfield_dat[i],"Content-Type:",13)==0)
				content_type=msg->hfield_dat[i];
770
			if(!sockprintf(socket,prot, sess,"%s",(char*)msg->hfield_dat[i]))
771
				return(0);
772
        }
773
    }
774
	/* Default MIME Content-Type for non-Internet messages */
775 776 777 778
	if(msg->from_net.type!=NET_INTERNET && content_type==NULL) {
		const char* charset =  smb_msg_is_utf8(msg) ? "UTF-8" : startup->default_charset;
		if(*charset)
			sockprintf(socket,prot,sess,"Content-Type: text/plain; charset=%s", charset);
779
		sockprintf(socket,prot,sess,"Content-Transfer-Encoding: 8bit");
780 781
	}

782
	if(strListCount(file_list)) {	/* File attachments */
783 784 785 786 787
        mimeheaders(socket,prot,sess,mime_boundary);
        sockprintf(socket,prot,sess,"");
        mimeblurb(socket,prot,sess,mime_boundary);
        sockprintf(socket,prot,sess,"");
        mimetextpartheader(socket,prot,sess,mime_boundary, startup->default_charset);
788
	}
rswindell's avatar