sockwrap.c 10.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/* sockwrap.c */

/* Berkley/WinSock socket API wrappers */

/* $Id$ */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
11
 * Copyright 2011 Rob Swindell - http://www.synchro.net/copyright.html		*
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
37
 *																			*
 * This library is free software; you can redistribute it and/or			*
 * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details: lgpl.txt or	*
 * http://www.fsf.org/copyleft/lesser.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.	*
 ****************************************************************************/

deuce's avatar
deuce committed
38
#include <ctype.h>		/* isdigit */
39
#include <stdlib.h>		/* alloca/free on FreeBSD */
40
#include <string.h>		/* bzero (for FD_ZERO) on FreeBSD */
41
#include <errno.h>		/* ENOMEM */
42
#include <stdio.h>		/* SEEK_SET */
43
#include <string.h>
44
#if defined(_WIN32)
45
46
 #undef socklen_t
 #include <ws2tcpip.h>
47
48
 #include <malloc.h>	/* alloca() on Win32 */
#endif
49

50
#include "genwrap.h"	/* SLEEP */
deuce's avatar
deuce committed
51
#include "gen_defs.h"	/* BOOL/LOG_WARNING */
52
53
54
#include "sockwrap.h"	/* sendsocket */
#include "filewrap.h"	/* filelength */

55
static socket_option_t socket_options[] = {
56
	{ "TYPE",				0,				SOL_SOCKET,		SO_TYPE				},
57
	{ "ERROR",				0,				SOL_SOCKET,		SO_ERROR			},
58
59
60
61
	{ "DEBUG",				0,				SOL_SOCKET,		SO_DEBUG			},
	{ "LINGER",				SOCK_STREAM,	SOL_SOCKET,		SO_LINGER			},
	{ "SNDBUF",				0,				SOL_SOCKET,		SO_SNDBUF			},
	{ "RCVBUF",				0,				SOL_SOCKET,		SO_RCVBUF			},
62
63

#ifndef _WINSOCKAPI_	/* Defined, but not supported, by WinSock */
64
65
66
67
	{ "SNDLOWAT",			0,				SOL_SOCKET,		SO_SNDLOWAT			},
	{ "RCVLOWAT",			0,				SOL_SOCKET,		SO_RCVLOWAT			},
	{ "SNDTIMEO",			0,				SOL_SOCKET,		SO_SNDTIMEO			},
	{ "RCVTIMEO",			0,				SOL_SOCKET,		SO_RCVTIMEO			},
68
69
70
#ifdef SO_USELOOPBACK	/* SunOS */
	{ "USELOOPBACK",		0,				SOL_SOCKET,		SO_USELOOPBACK		},
#endif
71
#endif
72

73
	{ "REUSEADDR",			0,				SOL_SOCKET,		SO_REUSEADDR		},	
deuce's avatar
deuce committed
74
75
76
#ifdef SO_REUSEPORT	/* BSD */
	{ "REUSEPORT",			0,				SOL_SOCKET,		SO_REUSEPORT		},	
#endif
77
78
79
80
	{ "KEEPALIVE",			SOCK_STREAM,	SOL_SOCKET,		SO_KEEPALIVE		},
	{ "DONTROUTE",			0,				SOL_SOCKET,		SO_DONTROUTE		},
	{ "BROADCAST",			SOCK_DGRAM,		SOL_SOCKET,		SO_BROADCAST		},
	{ "OOBINLINE",			SOCK_STREAM,	SOL_SOCKET,		SO_OOBINLINE		},
81

82
#ifdef SO_ACCEPTCONN											
83
	{ "ACCEPTCONN",			SOCK_STREAM,	SOL_SOCKET,		SO_ACCEPTCONN		},
84
#endif
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#ifdef SO_PRIORITY		/* Linux */
	{ "PRIORITY",			0,				SOL_SOCKET,		SO_PRIORITY			},
#endif
#ifdef SO_NO_CHECK		/* Linux */
	{ "NO_CHECK",			0,				SOL_SOCKET,		SO_NO_CHECK			},
#endif
#ifdef SO_PROTOTYPE		/* SunOS */
	{ "PROTOTYPE",			0,				SOL_SOCKET,		SO_PROTOTYPE		},
#endif
#ifdef SO_MAX_MSG_SIZE	/* WinSock2 */
	{ "MAX_MSG_SIZE",		SOCK_DGRAM,		SOL_SOCKET,		SO_MAX_MSG_SIZE		},
#endif
#ifdef SO_CONNECT_TIME	/* WinSock2 */
	{ "CONNECT_TIME",		SOCK_STREAM,	SOL_SOCKET,		SO_CONNECT_TIME		},
#endif
100
101

	/* IPPROTO-level socket options */
102
	{ "TCP_NODELAY",		SOCK_STREAM,	IPPROTO_TCP,	TCP_NODELAY			},
103
104
	/* The following are platform-specific */					
#ifdef TCP_MAXSEG											
105
	{ "TCP_MAXSEG",			SOCK_STREAM,	IPPROTO_TCP,	TCP_MAXSEG			},
106
107
#endif															
#ifdef TCP_CORK													
108
	{ "TCP_CORK",			SOCK_STREAM,	IPPROTO_TCP,	TCP_CORK			},
109
110
#endif															
#ifdef TCP_KEEPIDLE												
111
	{ "TCP_KEEPIDLE",		SOCK_STREAM,	IPPROTO_TCP,	TCP_KEEPIDLE		},
112
113
#endif															
#ifdef TCP_KEEPINTVL											
114
	{ "TCP_KEEPINTVL",		SOCK_STREAM,	IPPROTO_TCP,	TCP_KEEPINTVL		},
115
116
#endif															
#ifdef TCP_KEEPCNT												
117
	{ "TCP_KEEPCNT",		SOCK_STREAM,	IPPROTO_TCP,	TCP_KEEPCNT			},
118
#endif															
119
120
121
#ifdef TCP_KEEPALIVE	/* SunOS */
	{ "TCP_KEEPALIVE",		SOCK_STREAM,	IPPROTO_TCP,	TCP_KEEPALIVE		},
#endif															
122
#ifdef TCP_SYNCNT												
123
	{ "TCP_SYNCNT",			SOCK_STREAM,	IPPROTO_TCP,	TCP_SYNCNT			},
124
125
#endif															
#ifdef TCP_LINGER2												
126
	{ "TCP_LINGER2",		SOCK_STREAM,	IPPROTO_TCP,	TCP_LINGER2			},
127
128
#endif														
#ifdef TCP_DEFER_ACCEPT										
129
	{ "TCP_DEFER_ACCEPT",	SOCK_STREAM,	IPPROTO_TCP,	TCP_DEFER_ACCEPT	},
130
131
#endif															
#ifdef TCP_WINDOW_CLAMP											
132
	{ "TCP_WINDOW_CLAMP",	SOCK_STREAM,	IPPROTO_TCP,	TCP_WINDOW_CLAMP	},
133
134
#endif														
#ifdef TCP_QUICKACK											
135
	{ "TCP_QUICKACK",		SOCK_STREAM,	IPPROTO_TCP,	TCP_QUICKACK		},
136
137
#endif						
#ifdef TCP_NOPUSH			
138
	{ "TCP_NOPUSH",			SOCK_STREAM,	IPPROTO_TCP,	TCP_NOPUSH			},
139
140
#endif						
#ifdef TCP_NOOPT			
141
	{ "TCP_NOOPT",			SOCK_STREAM,	IPPROTO_TCP,	TCP_NOOPT			},
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#endif
	{ NULL }
};

int getSocketOptionByName(const char* name, int* level)
{
	int i;

	if(level!=NULL)
		*level=SOL_SOCKET;	/* default option level */
	for(i=0;socket_options[i].name;i++) {
		if(stricmp(name,socket_options[i].name)==0) {
			if(level!=NULL)
				*level = socket_options[i].level;
			return(socket_options[i].value);
		}
	}
	if(!isdigit(*name))	/* unknown option name */
		return(-1);
	return(strtol(name,NULL,0));
}

socket_option_t* getSocketOptionList(void)
{
	return(socket_options);
}

169
int sendfilesocket(int sock, int file, off_t *offset, off_t count)
170
{
171
	char		buf[1024*16];
172
	off_t		len;
173
174
175
176
	int			rd;
	int			wr=0;
	int			total=0;
	int			i;
177

178
179
180
/* sendfile() on Linux may or may not work with non-blocking sockets ToDo */
	len=filelength(file);

181
182
183
184
	if(offset!=NULL)
		if(lseek(file,*offset,SEEK_SET)<0)
			return(-1);

185
	if(count<1 || count>len) {
186
		count=len;
187
188
		count-=tell(file);		/* don't try to read beyond EOF */
	}
189
190
191
192
193
194
195
196
#if USE_SENDFILE
	while((i=sendfile(file,sock,(offset==NULL?0:*offset)+total,count-total,NULL,&wr,0))==-1 && errno==EAGAIN)  {
		total+=wr;
		SLEEP(1);
	}
	if(i==0)
		return((int)count);
#endif
197

198
199
200
201
202
203
	if(count<0) {
		errno=EINVAL;
		return(-1);
	}

	while(total<count) {
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
		rd=read(file,buf,sizeof(buf));
		if(rd==-1)
			return(-1);
		if(rd==0)
			break;
		for(i=wr=0;i<rd;i+=wr) {
			wr=sendsocket(sock,buf+i,rd-i);
			if(wr>0)
				continue;
			if(wr==SOCKET_ERROR && ERROR_VALUE==EWOULDBLOCK) {
				wr=0;
				SLEEP(1);
				continue;
			}
			return(wr);
219
		}
220
221
222
		if(i!=rd)
			return(-1);
		total+=rd;
223
224
	}

225
	if(offset!=NULL)
226
227
228
		(*offset)+=total;

	return(total);
229
230
}

231
int recvfilesocket(int sock, int file, off_t *offset, off_t count)
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
{
	/* Writes a file from a socket -
	 *
	 * sock		- Socket to read from
	 * file		- File descriptior to write to
	 *				MUST be open and writeable
	 * offset	- pointer to file offset to start writing at
	 *				is set to offset writing STOPPED
	 *				on return
	 * count	- number of bytes to read/write
	 *
	 * returns -1 if an error occurse, otherwise
	 * returns number ob bytes written and sets offset
	 * to the new offset
	 */
	 
	char*	buf;
	int		rd;
	int		wr;

	if(count<1) {
		errno=ERANGE;
		return(-1);
	}
		
257
	if((buf=(char*)malloc((size_t)count))==NULL) {
258
259
260
261
262
263
264
265
		errno=ENOMEM;
		return(-1);
	}

	if(offset!=NULL)
		if(lseek(file,*offset,SEEK_SET)<0)
			return(-1);

266
	rd=read(sock,buf,(size_t)count);
267
268
	if(rd!=count) {
		free(buf);
269
		return(-1);
270
	}
271
272
273
274
275
276

	wr=write(file,buf,rd);

	if(offset!=NULL)
		(*offset)+=wr;

277
	free(buf);
278
279
280
281
	return(wr);
}


282
/* Return true if connected, optionally sets *rd_p to true if read data available */
283
BOOL socket_check(SOCKET sock, BOOL* rd_p, BOOL* wr_p, DWORD timeout)
284
285
286
{
	char	ch;
	int		i,rd;
287
	fd_set	rd_set;
288
	fd_set*	rd_set_p=&rd_set;
289
290
	fd_set	wr_set;
	fd_set*	wr_set_p=NULL;
291
292
293
294
295
	struct	timeval tv;

	if(rd_p!=NULL)
		*rd_p=FALSE;

296
297
298
	if(wr_p!=NULL)
		*wr_p=FALSE;

299
300
301
	if(sock==INVALID_SOCKET)
		return(FALSE);

302
303
304
305
306
307
	FD_ZERO(&rd_set);
	FD_SET(sock,&rd_set);
	if(wr_p!=NULL) {
		wr_set_p=&wr_set;
		FD_ZERO(wr_set_p);
		FD_SET(sock,wr_set_p);
308
		if(rd_p==NULL)
309
			rd_set_p=NULL;
310
	}
311

312
313
314
	/* Convert timeout from ms to sec/usec */
	tv.tv_sec=timeout/1000;
	tv.tv_usec=(timeout%1000)*1000;
315

316
	i=select(sock+1,rd_set_p,wr_set_p,NULL,&tv);
317
318
319
320
321
322
	if(i==SOCKET_ERROR)
		return(FALSE);

	if(i==0) 
		return(TRUE);

323
324
325
326
327
328
	if(wr_p!=NULL && FD_ISSET(sock,wr_set_p)) {
		*wr_p=TRUE;
		if(i==1)
			return(TRUE);
	}

329
	if(rd_p !=NULL || wr_p==NULL)  {
330
331
332
333
334
335
336
		rd=recv(sock,&ch,1,MSG_PEEK);
		if(rd==1 
			|| (rd==SOCKET_ERROR && ERROR_VALUE==EMSGSIZE)) {
			if(rd_p!=NULL)
				*rd_p=TRUE;
			return(TRUE);
		}
337
338
339
340
	}

	return(FALSE);
}
deuce's avatar
deuce committed
341

342
343
344
int retry_bind(SOCKET s, const struct sockaddr *addr, socklen_t addrlen
			   ,uint retries, uint wait_secs
			   ,const char* prot
345
			   ,int (*lprintf)(int level, const char *fmt, ...))
deuce's avatar
deuce committed
346
{
347
	char	port_str[128];
deuce's avatar
deuce committed
348
	int		result=-1;
349
	uint	i;
deuce's avatar
deuce committed
350

351
	if(addr->sa_family==AF_INET)
deuce's avatar
deuce committed
352
		SAFEPRINTF(port_str," to port %u",ntohs(((SOCKADDR_IN *)(addr))->sin_port));
353
354
	else
		port_str[0]=0;
deuce's avatar
deuce committed
355
	for(i=0;i<=retries;i++) {
356
		if((result=bind(s,addr,addrlen))==0)
deuce's avatar
deuce committed
357
			break;
358
		if(lprintf!=NULL)
359
			lprintf(i<retries ? LOG_WARNING:LOG_CRIT
360
361
362
				,"%04d !ERROR %d binding %s socket%s", s, ERROR_VALUE, prot, port_str);
		if(i<retries) {
			if(lprintf!=NULL)
363
364
				lprintf(LOG_WARNING,"%04d Will retry in %u seconds (%u of %u)"
					,s, wait_secs, i+1, retries);
365
366
			SLEEP(wait_secs*1000);
		}
deuce's avatar
deuce committed
367
368
369
	}
	return(result);
}
370
371
372
373
374
375
376
377
378
379
380

int nonblocking_connect(SOCKET sock, struct sockaddr* addr, size_t size, unsigned timeout)
{
	int result;

	result=connect(sock, addr, size);

	if(result==SOCKET_ERROR
		&& (ERROR_VALUE==EWOULDBLOCK || ERROR_VALUE==EINPROGRESS)) {
		fd_set		socket_set;
		struct		timeval tv;
rswindell's avatar
rswindell committed
381
		socklen_t	optlen=sizeof(result);
382
383
384
385
		tv.tv_sec = timeout;
		tv.tv_usec = 0;
		FD_ZERO(&socket_set);
		FD_SET(sock,&socket_set);
386
		if(select(sock+1,NULL,&socket_set,NULL,&tv)==1)
rswindell's avatar
rswindell committed
387
			getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&result, &optlen);
388
389
390
	}
	return result;
}
391
392
393
394
395
396
397
398
399

const char *inet_addrtop(SOCKADDR *in, char *dest, size_t size)
{
	switch(in->sa_family) {
		case AF_INET:
			return inet_ntop(in->sa_family, &((struct sockaddr_in *)in)->sin_addr, dest, size);
		case AF_INET6:
			return inet_ntop(in->sa_family, &((struct sockaddr_in6 *)in)->sin6_addr, dest, size);
		default:
400
			safe_snprintf(dest, size, "<unknown address>");
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
			return NULL;
	}
}

uint16_t inet_addrport(SOCKADDR *in)
{
	switch(in->sa_family) {
		case AF_INET:
			return ntohs(((struct sockaddr_in *)in)->sin_port);
		case AF_INET6:
			return ntohs(((struct sockaddr_in6 *)in)->sin6_port);
		default:
			return 0;
	}
}