ftpsrvr.c 155 KB
Newer Older
1 2 3 4 5 6
/* Synchronet FTP server */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
7
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *																			*
 * 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										*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

rswindell's avatar
rswindell committed
22
/* ANSI C Library headers */
rswindell's avatar
rswindell committed
23
#include <stdio.h>
24 25 26 27 28 29
#include <stdlib.h>			/* ltoa in GNU C lib */
#include <stdarg.h>			/* va_list, varargs */
#include <string.h>			/* strrchr */
#include <fcntl.h>			/* O_WRONLY, O_RDONLY, etc. */
#include <errno.h>			/* EACCES */
#include <ctype.h>			/* toupper */
30 31
#include <sys/types.h>
#include <sys/stat.h>
rswindell's avatar
rswindell committed
32 33

/* Synchronet-specific headers */
34
#undef SBBS	/* this shouldn't be defined unless building sbbs.dll/libsbbs.so */
35
#include "sbbs.h"
36
#include "text.h"			/* TOTAL_TEXT */
rswindell's avatar
rswindell committed
37
#include "ftpsrvr.h"
38
#include "filedat.h"
39
#include "telnet.h"
deuce's avatar
deuce committed
40
#include "multisock.h"
deuce's avatar
deuce committed
41 42
#include "ssl.h"
#include "cryptlib.h"
43
#include "xpprintf.h"		// vasprintf
44
#include "md5.h"
45
#include "sauce.h"
46 47
#include "git_branch.h"
#include "git_hash.h"
48 49 50

/* Constants */

51
#define FTP_SERVER				"Synchronet FTP Server"
52 53

#define STATUS_WFC				"Listening"
54
#define ANONYMOUS				"anonymous"
55 56 57 58

#define BBS_VIRTUAL_PATH		"bbs:/""/"	/* this is actually bbs:<slash><slash> */
#define LOCAL_FSYS_DIR			"local:"
#define BBS_FSYS_DIR			"bbs:"
59
#define BBS_HIDDEN_ALIAS		"hidden"
60

61
#define TIMEOUT_THREAD_WAIT		60		/* Seconds */
62

63 64
#define TIMEOUT_SOCKET_LISTEN	30		/* Seconds */

65 66 67 68 69 70
#define XFER_REPORT_INTERVAL	60		/* Seconds */

#define INDEX_FNAME_LEN			15

#define	NAME_LEN				15		/* User name length for listings */

deuce's avatar
deuce committed
71 72 73 74 75
#define MLSX_TYPE	(1<<0)
#define MLSX_PERM	(1<<1)
#define MLSX_SIZE	(1<<2)
#define MLSX_MODIFY	(1<<3)
#define MLSX_OWNER	(1<<4)
76
#define MLSX_UNIQUE	(1<<5)
deuce's avatar
deuce committed
77
#define MLSX_CREATE	(1<<6)
deuce's avatar
deuce committed
78

79
static ftp_startup_t*	startup=NULL;
80
static scfg_t	scfg;
deuce's avatar
deuce committed
81
static struct xpms_set *ftp_set = NULL;
82 83
static protected_uint32_t active_clients;
static protected_uint32_t thread_count;
84 85 86
static volatile time_t	uptime=0;
static volatile ulong	served=0;
static volatile BOOL	terminate_server=FALSE;
87
static char 	*text[TOTAL_TEXT];
88 89
static str_list_t recycle_semfiles;
static str_list_t shutdown_semfiles;
90
static link_list_t current_connections;
91

92
#ifdef SOCKET_DEBUG
93
	static BYTE 	socket_debug[0x10000]={0};
94

95 96 97 98 99 100 101 102
	#define	SOCKET_DEBUG_CTRL		(1<<0)	/* 0x01 */
	#define SOCKET_DEBUG_SEND		(1<<1)	/* 0x02 */
	#define SOCKET_DEBUG_READLINE	(1<<2)	/* 0x04 */
	#define SOCKET_DEBUG_ACCEPT		(1<<3)	/* 0x08 */
	#define SOCKET_DEBUG_SENDTHREAD	(1<<4)	/* 0x10 */
	#define SOCKET_DEBUG_TERMINATE	(1<<5)	/* 0x20 */
	#define SOCKET_DEBUG_RECV_CHAR	(1<<6)	/* 0x40 */
	#define SOCKET_DEBUG_FILEXFER	(1<<7)	/* 0x80 */
103
#endif
104

105
char* genvpath(int lib, int dir, char* str);
106 107 108

typedef struct {
	SOCKET			socket;
deuce's avatar
deuce committed
109 110
	union xp_sockaddr	client_addr;
	socklen_t		client_addr_len;
111 112
} ftp_t;

113

114
static const char *ftp_mon[]={"Jan","Feb","Mar","Apr","May","Jun"
115 116 117 118 119 120 121 122 123 124
            ,"Jul","Aug","Sep","Oct","Nov","Dec"};

BOOL direxist(char *dir)
{
	if(access(dir,0)==0)
		return(TRUE);
	else
		return(FALSE);
}

rswindell's avatar
rswindell committed
125
BOOL dir_op(scfg_t* cfg, user_t* user, client_t* client, uint dirnum)
126
{
127
	return(user->level>=SYSOP_LEVEL
Rob Swindell's avatar
Rob Swindell committed
128
		|| (cfg->dir[dirnum]->op_ar[0] && chk_ar(cfg,cfg->dir[dirnum]->op_ar,user,client)));
129 130
}

131 132 133
#if defined(__GNUC__)	// Catch printf-format errors with lprintf
static int lprintf(int level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
#endif
134
static int lprintf(int level, const char *fmt, ...)
135 136 137 138 139
{
	va_list argptr;
	char sbuf[1024];

    va_start(argptr,fmt);
140 141
    vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
	sbuf[sizeof(sbuf)-1]=0;
142 143
    va_end(argptr);

144
	if(level <= LOG_ERR) {
145
		char errmsg[sizeof(sbuf)+16];
146
		SAFEPRINTF(errmsg, "ftp  %s", sbuf);
147
		errorlog(&scfg, level, startup==NULL ? NULL:startup->host_name, errmsg);
148
		if(startup!=NULL && startup->errormsg!=NULL)
149
			startup->errormsg(startup->cbdata,level,errmsg);
150
	}
151 152 153 154 155 156 157 158 159 160

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

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

    return startup->lputs(startup->cbdata,level,sbuf);
161 162 163 164 165
}

#ifdef _WINSOCKAPI_

static WSADATA WSAData;
166 167
#define SOCKLIB_DESC WSAData.szDescription

168
static BOOL WSAInitialized=FALSE;
169 170 171 172 173 174

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

    if((status = WSAStartup(MAKEWORD(1,1), &WSAData))==0) {
175
		lprintf(LOG_DEBUG,"%s %s",WSAData.szDescription, WSAData.szSystemStatus);
176
		WSAInitialized=TRUE;
177 178 179
		return (TRUE);
	}

180
    lprintf(LOG_CRIT,"!WinSock startup ERROR %d", status);
181 182 183
	return (FALSE);
}

184
#else /* No WINSOCK */
185

186
#define winsock_startup()	(TRUE)
187
#define SOCKLIB_DESC		NULL
188 189 190

#endif

191 192 193 194 195
static char* server_host_name(void)
{
	return startup->host_name[0] ? startup->host_name : scfg.sys_inetaddr;
}

196 197 198
static void status(char* str)
{
	if(startup!=NULL && startup->status!=NULL)
199
	    startup->status(startup->cbdata,str);
200 201 202 203 204
}

static void update_clients(void)
{
	if(startup!=NULL && startup->clients!=NULL)
205
		startup->clients(startup->cbdata,protected_uint32_value(active_clients));
206 207
}

208
static void client_on(SOCKET sock, client_t* client, BOOL update)
209
{
210 211
	if(!update)
		listAddNodeData(&current_connections, client->addr, strlen(client->addr) + 1, sock, LAST_NODE);
212
	if(startup!=NULL && startup->client_on!=NULL)
213
		startup->client_on(startup->cbdata,TRUE,sock,client,update);
214 215 216 217
}

static void client_off(SOCKET sock)
{
218
	listRemoveTaggedNode(&current_connections, sock, /* free_data */TRUE);
219
	if(startup!=NULL && startup->client_on!=NULL)
220
		startup->client_on(startup->cbdata,FALSE,sock,NULL,FALSE);
221 222
}

223
static void thread_up(BOOL setuid)
224 225
{
	if(startup!=NULL && startup->thread_up!=NULL)
226
		startup->thread_up(startup->cbdata,TRUE, setuid);
227 228
}

229
static int32_t thread_down(void)
230
{
231
	int32_t count = protected_uint32_adjust_fetch(&thread_count,-1);
232
	if(startup!=NULL && startup->thread_up!=NULL)
233
		startup->thread_up(startup->cbdata,FALSE, FALSE);
234
	return count;
235 236
}

deuce's avatar
deuce committed
237
static void ftp_open_socket_cb(SOCKET sock, void *cbdata)
238
{
239
	char	error[256];
240

deuce's avatar
deuce committed
241
	if(startup!=NULL && startup->socket_open!=NULL)
242
		startup->socket_open(startup->cbdata,TRUE);
deuce's avatar
deuce committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
	if(set_socket_options(&scfg, sock, "FTP", error, sizeof(error)))
		lprintf(LOG_ERR,"%04d !ERROR %s",sock, error);
}

static void ftp_close_socket_cb(SOCKET sock, void *cbdata)
{
	if(startup!=NULL && startup->socket_open!=NULL)
		startup->socket_open(startup->cbdata,FALSE);
}

static SOCKET ftp_open_socket(int domain, int type)
{
	SOCKET	sock;

	sock=socket(domain, type, IPPROTO_IP);
	if(sock != INVALID_SOCKET)
		ftp_open_socket_cb(sock, NULL);
260 261 262 263 264 265
	return(sock);
}

#ifdef __BORLANDC__
#pragma argsused
#endif
deuce's avatar
deuce committed
266
static int ftp_close_socket(SOCKET* sock, CRYPT_SESSION *sess, int line)
267 268 269
{
	int		result;

deuce's avatar
deuce committed
270 271 272 273 274
	if (*sess != -1) {
		cryptDestroySession(*sess);
		*sess = -1;
	}

275
	if((*sock)==INVALID_SOCKET) {
276
		lprintf(LOG_WARNING,"0000 !INVALID_SOCKET in close_socket from line %u",line);
277 278 279
		return(-1);
	}

280 281
	shutdown(*sock,SHUT_RDWR);	/* required on Unix */

282
	result=closesocket(*sock);
283
	if(startup!=NULL && startup->socket_open!=NULL) 
284
		startup->socket_open(startup->cbdata,FALSE);
285

286 287
	if(result!=0) {
		if(ERROR_VALUE!=ENOTSOCK)
288
			lprintf(LOG_WARNING,"%04d !ERROR %d closing socket from line %u",*sock,ERROR_VALUE,line);
289
	}
290 291 292 293 294
	*sock=INVALID_SOCKET;

	return(result);
}

295
#define GCES(status, sock, session, estr, action) do {                  \
deuce's avatar
deuce committed
296 297
	int GCES_level;                                                     \
	get_crypt_error_string(status, session, &estr, action, &GCES_level);\
298
	if (estr != NULL) {                                                 \
299
		lprintf(GCES_level, "%04d TLS %s", sock, estr);                 \
300 301
		free_crypt_attrstr(estr);										\
		estr=NULL;														\
deuce's avatar
deuce committed
302 303 304 305
	}                                                                   \
} while (0)


306 307 308
#if defined(__GNUC__)	// Catch printf-format errors with sockprintf
static int sockprintf(SOCKET sock, CRYPT_SESSION sess, char *fmt, ...) __attribute__ ((format (printf, 3, 4)));
#endif
deuce's avatar
deuce committed
309
static int sockprintf(SOCKET sock, CRYPT_SESSION sess, char *fmt, ...)
310 311
{
	int		len;
312
	int		maxlen;
313 314 315
	int		result;
	va_list argptr;
	char	sbuf[1024];
deuce's avatar
deuce committed
316
	char	*estr;
317 318

    va_start(argptr,fmt);
319 320 321
    len=vsnprintf(sbuf,maxlen=sizeof(sbuf)-2,fmt,argptr);
    va_end(argptr);

322
	if(len<0 || len>maxlen) /* format error or output truncated */
323
		len=maxlen;
324
	if(startup!=NULL && startup->options&FTP_OPT_DEBUG_TX)
deuce's avatar
deuce committed
325
		lprintf(LOG_DEBUG,"%04d TX%s: %.*s", sock, sess != -1 ? "S" : "", len, sbuf);
326
	memcpy(sbuf+len,"\r\n",2);
327
	len+=2;
328

329
	if(sock==INVALID_SOCKET) {
330
		lprintf(LOG_WARNING,"!INVALID SOCKET in call to sockprintf");
331 332 333
		return(0);
	}

Deucе's avatar
Deucе committed
334 335 336
	/* Check socket for writability */
	if(!socket_writable(sock, 300000)) {
		lprintf(LOG_WARNING,"%04d !WARNING socket not ready for write" ,sock);
337 338
		return(0);
	}
deuce's avatar
deuce committed
339 340 341 342 343 344 345 346 347

	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;
			else {
deuce's avatar
deuce committed
348
				GCES(result, sock, sess, estr, "sending data");
349 350
				if (result != CRYPT_ERROR_TIMEOUT)
					return 0;
351
			}
deuce's avatar
deuce committed
352 353
			result = cryptFlushData(sess);
			if (result != CRYPT_OK) {
deuce's avatar
deuce committed
354
				GCES(result, sock, sess, estr, "flushing data");
deuce's avatar
deuce committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
				return 0;
			}
		}
	}
	else {
		while((result=sendsocket(sock,sbuf,len))!=len) {
			if(result==SOCKET_ERROR) {
				if(ERROR_VALUE==EWOULDBLOCK) {
					YIELD();
					continue;
				}
				if(ERROR_VALUE==ECONNRESET) 
					lprintf(LOG_WARNING,"%04d Connection reset by peer on send",sock);
				else if(ERROR_VALUE==ECONNABORTED)
					lprintf(LOG_WARNING,"%04d Connection aborted by peer on send",sock);
				else
					lprintf(LOG_WARNING,"%04d !ERROR %d sending",sock,ERROR_VALUE);
				return(0);
			}
			lprintf(LOG_WARNING,"%04d !ERROR: short send: %u instead of %u",sock,result,len);
375 376 377 378 379
		}
	}
	return(len);
}

380
void recverror(SOCKET socket, int rd, int line)
381 382
{
	if(rd==0) 
383
		lprintf(LOG_NOTICE,"%04d Socket closed by peer on receive (line %u)"
384
			,socket, line);
385
	else if(rd==SOCKET_ERROR) {
rswindell's avatar
rswindell committed
386
		if(ERROR_VALUE==ECONNRESET) 
387
			lprintf(LOG_NOTICE,"%04d Connection reset by peer on receive (line %u)"
388
				,socket, line);
389
		else if(ERROR_VALUE==ECONNABORTED) 
390
			lprintf(LOG_NOTICE,"%04d Connection aborted by peer on receive (line %u)"
391
				,socket, line);
392
		else
393
			lprintf(LOG_NOTICE,"%04d !ERROR %d receiving on socket (line %u)"
394
				,socket, ERROR_VALUE, line);
395
	} else
396
		lprintf(LOG_WARNING,"%04d !ERROR: recv on socket returned unexpected value: %d (line %u)"
397
			,socket, rd, line);
398 399
}

deuce's avatar
deuce committed
400
static int sock_recvbyte(SOCKET sock, CRYPT_SESSION sess, char *buf, time_t *lastactive)
401
{
deuce's avatar
deuce committed
402 403 404
	int len=0;
	int ret;
	int i;
deuce's avatar
deuce committed
405
	char *estr;
406
	BOOL first = TRUE;
407

deuce's avatar
deuce committed
408 409 410
	if(ftp_set==NULL || terminate_server) {
		sockprintf(sock,sess,"421 Server downed, aborting.");
		lprintf(LOG_WARNING,"%04d Server downed, aborting",sock);
411 412
		return(0);
	}
deuce's avatar
deuce committed
413 414
	if (sess > -1) {
		/* Try a read with no timeout first. */
deuce's avatar
deuce committed
415 416
		if ((ret = cryptSetAttribute(sess, CRYPT_OPTION_NET_READTIMEOUT, 0)) != CRYPT_OK)
			GCES(ret, sock, sess, estr, "setting read timeout");
deuce's avatar
deuce committed
417 418
		while (1) {
			ret = cryptPopData(sess, buf, 1, &len);
Deucе's avatar
Deucе committed
419
			/* Successive reads will be with the full timeout after a socket_readable() */
deuce's avatar
deuce committed
420 421 422 423 424
			cryptSetAttribute(sess, CRYPT_OPTION_NET_READTIMEOUT, startup->max_inactivity);
			switch(ret) {
				case CRYPT_OK:
					break;
				case CRYPT_ERROR_TIMEOUT:
425 426 427 428 429
					if (!first) {
						GCES(ret, sock, sess, estr, "popping data");
						return -1;
					}
					break;
deuce's avatar
deuce committed
430 431 432
				case CRYPT_ERROR_COMPLETE:
					return 0;
				default:
deuce's avatar
deuce committed
433
					GCES(ret, sock, sess, estr, "popping data");
deuce's avatar
deuce committed
434 435 436 437
					if (ret < -1)
						return ret;
					return -2;
			}
438
			first = FALSE;
deuce's avatar
deuce committed
439 440 441 442 443 444 445 446 447
			if (len)
				return len;
			
			if((time(NULL)-(*lastactive))>startup->max_inactivity) {
				lprintf(LOG_WARNING,"%04d Disconnecting due to to inactivity",sock);
				sockprintf(sock,sess,"421 Disconnecting due to inactivity (%u seconds)."
					,startup->max_inactivity);
				return(0);
			}
448

Deucе's avatar
Deucе committed
449 450 451 452 453 454
			if (!socket_readable(sock, startup->max_inactivity * 1000)) {
				if((time(NULL)-(*lastactive))>startup->max_inactivity) {
					lprintf(LOG_WARNING,"%04d Disconnecting due to to inactivity",sock);
					sockprintf(sock,sess,"421 Disconnecting due to inactivity (%u seconds)."
						,startup->max_inactivity);
					return(0);
deuce's avatar
deuce committed
455 456
				}
			}
457
		}
deuce's avatar
deuce committed
458 459 460
	}
	else {
		while (1) {
Deucе's avatar
Deucе committed
461 462 463 464 465 466
			if (!socket_readable(sock, startup->max_inactivity * 1000)) {
				if((time(NULL)-(*lastactive))>startup->max_inactivity) {
					lprintf(LOG_WARNING,"%04d Disconnecting due to to inactivity",sock);
					sockprintf(sock,sess,"421 Disconnecting due to inactivity (%u seconds)."
						,startup->max_inactivity);
					return(0);
467
				}
Deucе's avatar
Deucе committed
468
				continue;
469
			}
deuce's avatar
deuce committed
470 471 472 473 474 475 476 477
	#ifdef SOCKET_DEBUG_RECV_CHAR
			socket_debug[sock]|=SOCKET_DEBUG_RECV_CHAR;
	#endif
			i=recv(sock, buf, 1, 0);
	#ifdef SOCKET_DEBUG_RECV_CHAR
			socket_debug[sock]&=~SOCKET_DEBUG_RECV_CHAR;
	#endif
			return i;
478
		}
deuce's avatar
deuce committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	}
}

int sockreadline(SOCKET socket, CRYPT_SESSION sess, char* buf, int len, time_t* lastactive)
{
	char	ch;
	int		i,rd=0;

	buf[0]=0;

	if(socket==INVALID_SOCKET) {
		lprintf(LOG_WARNING,"INVALID SOCKET in call to sockreadline");
		return(0);
	}

	while(rd<len-1) {
		i = sock_recvbyte(socket, sess, &ch, lastactive);

497 498 499
		if(i<1) {
			if (sess != -1)
				recverror(socket,i,__LINE__);
500 501
			return(i);
		}
502
		if(ch=='\n' /* && rd>=1 */) { /* Mar-9-2003: terminate on sole LF */
503 504 505 506
			break;
		}	
		buf[rd++]=ch;
	}
507 508 509 510
	if(rd>0 && buf[rd-1]=='\r')
		buf[rd-1]=0;
	else
		buf[rd]=0;
deuce's avatar
deuce committed
511

512 513 514
	return(rd);
}

Rob Swindell's avatar
Rob Swindell committed
515
void ftp_terminate(void)
516
{
deuce's avatar
deuce committed
517
   	lprintf(LOG_INFO,"FTP Server terminate");
518
	terminate_server=TRUE;
519 520
}

521
int ftp_remove(SOCKET sock, int line, const char* fname, const char* username)
522 523 524
{
	int ret=0;

525 526
	if(fexist(fname) && (ret=remove(fname))!=0) {
		if(fexist(fname))	// In case there was a race condition (other host deleted file first)
527
			lprintf(LOG_ERR,"%04d <%s> !ERROR %d (%s) (line %d) removing file: %s", sock, username, errno, STRERROR(errno), line, fname);
528
	}
529 530
	return ret;
}
531 532

typedef struct {
rswindell's avatar
rswindell committed
533
	SOCKET		ctrl_sock;
deuce's avatar
deuce committed
534
	CRYPT_SESSION	ctrl_sess;
rswindell's avatar
rswindell committed
535
	SOCKET*		data_sock;
deuce's avatar
deuce committed
536
	CRYPT_SESSION*	data_sess;
rswindell's avatar
rswindell committed
537 538 539 540 541 542
	BOOL*		inprogress;
	BOOL*		aborted;
	BOOL		delfile;
	BOOL		tmpfile;
	BOOL		credits;
	BOOL		append;
543
	off_t		filepos;
rswindell's avatar
rswindell committed
544 545 546 547 548 549
	char		filename[MAX_PATH+1];
	time_t*		lastactive;
	user_t*		user;
	client_t*	client;
	int			dir;
	char*		desc;
550 551 552 553 554
} xfer_t;

static void send_thread(void* arg)
{
	char		buf[8192];
555
	char		str[256];
556
	char		tmp[128];
557
	char		username[128];
deuce's avatar
deuce committed
558
	char		host_ip[INET6_ADDRSTRLEN];
559
	int			i;
560 561
	int			rd;
	int			wr;
562 563
	long		mod;
	ulong		l;
564 565
	off_t		total=0;
	off_t		last_total=0;
566 567
	ulong		dur;
	ulong		cps;
568
	off_t		length;
569 570 571 572 573 574 575
	BOOL		error=FALSE;
	FILE*		fp;
	file_t		f;
	xfer_t		xfer;
	time_t		now;
	time_t		start;
	time_t		last_report;
576
	user_t		uploader;
deuce's avatar
deuce committed
577
	union xp_sockaddr	addr;
578
	socklen_t	addr_len;
deuce's avatar
deuce committed
579
	char		*estr;
580 581

	xfer=*(xfer_t*)arg;
582
	free(arg);
583

584
	SetThreadName("sbbs/ftpSend");
585
	thread_up(TRUE /* setuid */);
586

587 588
	length=flength(xfer.filename);

589
	if(length < 1) {
590 591 592 593 594 595 596 597 598
		if(xfer.tmpfile) {
			if(!(startup->options&FTP_OPT_KEEP_TEMP_FILES))
				ftp_remove(xfer.ctrl_sock, __LINE__, xfer.filename, xfer.user->alias);
			sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"450 No files");
		} else {
			lprintf(LOG_WARNING, "%04d <%s> !DATA cannot send file (%s) with size of %"PRIdOFF" bytes"
				,xfer.ctrl_sock, xfer.user->alias, xfer.filename, length);
			sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"450 Invalid file size: %"PRIdOFF, length);
		}
599 600 601 602 603 604
		ftp_close_socket(xfer.data_sock,xfer.data_sess,__LINE__);
		*xfer.inprogress=FALSE;
		thread_down();
		return;
	}

605 606
	if((fp=fnopen(NULL,xfer.filename,O_RDONLY|O_BINARY))==NULL	/* non-shareable open failed */
		&& (fp=fopen(xfer.filename,"rb"))==NULL) {				/* shareable open failed */
607 608
		lprintf(LOG_ERR,"%04d <%s> !DATA ERROR %d (%s) line %d opening %s"
			,xfer.ctrl_sock, xfer.user->alias, errno, strerror(errno), __LINE__, xfer.filename);
rswindell's avatar
rswindell committed
609
		sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"450 ERROR %d (%s) opening %s", errno, strerror(errno), xfer.filename);
rswindell's avatar
rswindell committed
610
		if(xfer.tmpfile && !(startup->options&FTP_OPT_KEEP_TEMP_FILES))
Rob Swindell's avatar
Rob Swindell committed
611
			(void)ftp_remove(xfer.ctrl_sock, __LINE__, xfer.filename, xfer.user->alias);
deuce's avatar
deuce committed
612
		ftp_close_socket(xfer.data_sock,xfer.data_sess,__LINE__);
613
		*xfer.inprogress=FALSE;
614
		thread_down();
615 616 617
		return;
	}

618
#ifdef SOCKET_DEBUG_SENDTHREAD
rswindell's avatar
rswindell committed
619 620 621
			socket_debug[xfer.ctrl_sock]|=SOCKET_DEBUG_SENDTHREAD;
#endif

622
	*xfer.aborted=FALSE;
623 624
	if(xfer.filepos < 0)
		xfer.filepos = 0;
625
	if(startup->options&FTP_OPT_DEBUG_DATA || xfer.filepos)
626
		lprintf(LOG_DEBUG,"%04d <%s> DATA socket %d sending %s from offset %"PRIdOFF
627
			,xfer.ctrl_sock, xfer.user->alias, *xfer.data_sock,xfer.filename,xfer.filepos);
628

629
	fseeko(fp,xfer.filepos,SEEK_SET);
630
	last_report=start=time(NULL);
631
	while((xfer.filepos+total)<length) {
632

633
		now=time(NULL);
634 635 636 637

		/* Periodic progress report */
		if(total && now>=last_report+XFER_REPORT_INTERVAL) {
			if(xfer.filepos)
638
				sprintf(str," from offset %"PRIdOFF,xfer.filepos);
639 640
			else
				str[0]=0;
641
			lprintf(LOG_INFO,"%04d <%s> DATA Sent %"PRIdOFF" bytes (%"PRIdOFF" total) of %s (%lu cps)%s"
642
				,xfer.ctrl_sock, xfer.user->alias, total,length,xfer.filename
643
				,(ulong)((total-last_total)/(now-last_report))
644 645 646 647 648
				,str);
			last_total=total;
			last_report=now;
		}

649
		if(*xfer.aborted==TRUE) {
650
			lprintf(LOG_WARNING,"%04d <%s> !DATA Transfer aborted",xfer.ctrl_sock, xfer.user->alias);
deuce's avatar
deuce committed
651
			sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"426 Transfer aborted.");
652 653 654
			error=TRUE;
			break;
		}
deuce's avatar
deuce committed
655
		if(ftp_set==NULL || terminate_server) {
656
			lprintf(LOG_WARNING,"%04d <%s> !DATA Transfer locally aborted",xfer.ctrl_sock, xfer.user->alias);
deuce's avatar
deuce committed
657
			sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"426 Transfer locally aborted.");
658 659 660
			error=TRUE;
			break;
		}
661

Deucе's avatar
Deucе committed
662 663
		/* Check socket for writability */
		if (!socket_writable(*xfer.data_sock, 1000))
664 665
			continue;

666
		fseeko(fp,xfer.filepos+total,SEEK_SET);
667
		rd=fread(buf,sizeof(char),sizeof(buf),fp);
668
		if(rd<1) /* EOF or READ error */
669
			break;
670

671
#ifdef SOCKET_DEBUG_SEND
672 673
		socket_debug[xfer.ctrl_sock]|=SOCKET_DEBUG_SEND;
#endif
deuce's avatar
deuce committed
674 675 676
		if (*xfer.data_sess != -1) {
			int status = cryptPushData(*xfer.data_sess, buf, rd, &wr);
			if (status != CRYPT_OK) {
deuce's avatar
deuce committed
677
				GCES(status, *xfer.data_sock, *xfer.data_sess, estr, "pushing data");
deuce's avatar
deuce committed
678 679 680 681 682
				wr = -1;
			}
			else {
				status = cryptFlushData(*xfer.data_sess);
				if (status != CRYPT_OK) {
deuce's avatar
deuce committed
683
					GCES(status, *xfer.data_sock, *xfer.data_sess, estr, "flushing data");
deuce's avatar
deuce committed
684 685 686 687 688 689
					wr = -1;
				}
			}
		}
		else
			wr=sendsocket(*xfer.data_sock,buf,rd);
690
#ifdef SOCKET_DEBUG_SEND
691 692
		socket_debug[xfer.ctrl_sock]&=~SOCKET_DEBUG_SEND;
#endif
693
		if(wr<1) {
694
			if(wr==SOCKET_ERROR) {
695
				if(ERROR_VALUE==EWOULDBLOCK) {
696
					/*lprintf(LOG_WARNING,"%04d DATA send would block, retrying",xfer.ctrl_sock);*/
697
					YIELD();
698 699 700
					continue;
				}
				else if(ERROR_VALUE==ECONNRESET) 
701 702
					lprintf(LOG_WARNING,"%04d <%s> DATA Connection reset by peer, sending on socket %d"
						,xfer.ctrl_sock, xfer.user->alias,*xfer.data_sock);
703
				else if(ERROR_VALUE==ECONNABORTED) 
704 705
					lprintf(LOG_WARNING,"%04d <%s> DATA Connection aborted by peer, sending on socket %d"
						,xfer.ctrl_sock, xfer.user->alias,*xfer.data_sock);
706
				else
707 708
					lprintf(LOG_WARNING,"%04d <%s> !DATA ERROR %d sending on data socket %d"
						,xfer.ctrl_sock, xfer.user->alias,ERROR_VALUE,*xfer.data_sock);
709
				/* Send NAK */
deuce's avatar
deuce committed
710
				sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"426 Error %d sending on DATA channel"
711
					,ERROR_VALUE);
712 713 714 715
				error=TRUE;
				break;
			}
			if(wr==0) {
716
				lprintf(LOG_WARNING,"%04d <%s> !DATA socket %d disconnected",xfer.ctrl_sock, xfer.user->alias, *xfer.data_sock);
deuce's avatar
deuce committed
717
				sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"426 DATA channel disconnected");
718 719 720
				error=TRUE;
				break;
			}
721 722
			lprintf(LOG_ERR,"%04d <%s> !DATA ERROR %d (%d) sending on socket %d"
				,xfer.ctrl_sock, xfer.user->alias, wr, ERROR_VALUE, *xfer.data_sock);
deuce's avatar
deuce committed
723
			sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"451 DATA send error");
724 725 726 727
			error=TRUE;
			break;
		}
		total+=wr;
728
		*xfer.lastactive=time(NULL);
729
		//YIELD();
730 731
	}

732
	if((i=ferror(fp))!=0) 
733 734
		lprintf(LOG_ERR,"%04d <%s> !DATA FILE ERROR %d (%d, %s)"
			,xfer.ctrl_sock, xfer.user->alias, i, errno, strerror(errno));
735

deuce's avatar
deuce committed
736
	ftp_close_socket(xfer.data_sock,xfer.data_sess,__LINE__);	/* Signal end of file */
737
	if(startup->options&FTP_OPT_DEBUG_DATA)
738
		lprintf(LOG_DEBUG,"%04d <%s> DATA socket closed",xfer.ctrl_sock, xfer.user->alias);
739 740
	
	if(!error) {
741
		dur=(long)(time(NULL)-start);
742
		cps=(ulong)(dur ? total/dur : total*2);
743
		lprintf(LOG_INFO,"%04d <%s> DATA Transfer successful: %"PRIdOFF" bytes sent in %lu seconds (%lu cps)"
744
			,xfer.ctrl_sock
745
			,xfer.user->alias
746
			,total,dur,cps);
deuce's avatar
deuce committed
747
		sockprintf(xfer.ctrl_sock,xfer.ctrl_sess,"226 Download complete (%lu cps).",cps);
748 749 750

		if(xfer.dir>=0) {
			memset(&f,0,sizeof(f));
751 752 753 754
			if(loadfile(&scfg, xfer.dir, xfer.filename, &f, file_detail_normal) == TRUE) {
				f.hdr.times_downloaded++;
				f.hdr.last_downloaded = time32(NULL);
				updatefile(&scfg, &f);
755

756
				lprintf(LOG_INFO,"%04d <%s> DATA downloaded: %s (%u times total)"
757 758 759
					,xfer.ctrl_sock
					,xfer.user->alias
					,xfer.filename
760
					,f.hdr.times_downloaded);
761 762 763
				/**************************/
				/* Update Uploader's Info */
				/**************************/
764 765 766 767 768
				uploader.number = 0;
				if(f.from_ext != NULL)
					uploader.number = atoi(f.from_ext);
				if(uploader.number == 0)
					uploader.number=matchuser(&scfg, f.from, TRUE /*sysop_alias*/);
769 770 771
				if(uploader.number
					&& uploader.number!=xfer.user->number 
					&& getuserdat(&scfg,&uploader)==0
772 773
					&& uploader.firston < (time_t)f.hdr.when_imported.time) {
					l=f.cost;
774 775 776 777 778 779 780 781 782 783 784
					if(!(scfg.dir[f.dir]->misc&DIR_CDTDL))	/* Don't give credits on d/l */
						l=0;
					if(scfg.dir[f.dir]->misc&DIR_CDTMIN && cps) { /* Give min instead of cdt */
						mod=((ulong)(l*(scfg.dir[f.dir]->dn_pct/100.0))/cps)/60;
						adjustuserrec(&scfg,uploader.number,U_MIN,10,mod);
						sprintf(tmp,"%lu minute",mod);
					} else {
						mod=(ulong)(l*(scfg.dir[f.dir]->dn_pct/100.0));
						adjustuserrec(&scfg,uploader.number,U_CDT,10,mod);
						ultoac(mod,tmp);
					}
785
					if(!(scfg.dir[f.dir]->misc&DIR_QUIET)) {
786 787
						addr_len = sizeof(addr);
						if(uploader.level>=SYSOP_LEVEL
deuce's avatar
deuce committed
788 789 790
							&& getpeername(xfer.ctrl_sock,&addr.addr,&addr_len)==0
							&& inet_addrtop(&addr, host_ip, sizeof(host_ip))!=NULL)
							SAFEPRINTF2(username,"%s [%s]",xfer.user->alias,host_ip);
791 792
						else
							SAFECOPY(username,xfer.user->alias);
793
						/* Inform uploader of downloaded file */
794
						safe_snprintf(str,sizeof(str),text[DownloadUserMsg]
795 796
							,getfname(xfer.filename)
							,xfer.filepos ? "partially FTP-" : "FTP-"
797
							,username,tmp); 
798 799
						putsmsg(&scfg,uploader.number,str); 
					}
800
				}
801
			}
802
			if(!xfer.tmpfile && !xfer.delfile && !(scfg.dir[f.dir]->misc&DIR_NOSTAT))
803
				inc_sys_download_stats(&scfg, 1, (ulong)total);
804 805 806
		}	

		if(xfer.credits) {
807
			user_downloaded(&scfg, xfer.user, 1, total);
rswindell's avatar
rswindell committed
808
			if(xfer.dir>=0 && !is_download_free(&scfg,xfer.dir,xfer.user,xfer.client))
809 810 811 812 813
				subtract_cdt(&scfg, xfer.user, xfer.credits);
		}
	}

	fclose(fp);
deuce's avatar
deuce committed
814
	if(ftp_set!=NULL && !terminate_server)
815
		*xfer.inprogress=FALSE;
rswindell's avatar
rswindell committed
816 817
	if(xfer.tmpfile) {
		if(!(startup->options&FTP_OPT_KEEP_TEMP_FILES))
Rob Swindell's avatar
Rob Swindell committed
818
			(void)ftp_remove(xfer.ctrl_sock, __LINE__, xfer.filename, xfer.user->alias);
rswindell's avatar
rswindell committed
819 820
	} 
	else if(xfer.delfile && !error)
Rob Swindell's avatar
Rob Swindell committed
821
		(void)ftp_remove(xfer.ctrl_sock, __LINE__, xfer.filename, xfer.user->alias);
822

823
#if defined(SOCKET_DEBUG_SENDTHREAD)
rswindell's avatar
rswindell committed
824 825 826
			socket_debug[xfer.ctrl_sock]&=~SOCKET_DEBUG_SENDTHREAD;
#endif