sock.c 10.6 KB
Newer Older
Jack Moffitt's avatar
Jack Moffitt committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* sock.c
 * - General Socket Functions
 *
 * Copyright (c) 1999 the icecast team
 *
 * 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.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include <fcntl.h>
29
#include <errno.h>
Jack Moffitt's avatar
Jack Moffitt committed
30
31
32
33
34
35
36
37

#ifndef _WIN32
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <netdb.h>
38
#include <sys/poll.h>
Jack Moffitt's avatar
Jack Moffitt committed
39
#else
40
#include <winsock2.h>
Jack Moffitt's avatar
Jack Moffitt committed
41
42
43
#define vsnprintf _vsnprintf
#define EINPROGRESS WSAEINPROGRESS
#define ENOTSOCK WSAENOTSOCK
44
#define EWOULDBLOCK WSAEWOULDBLOCK
Jack Moffitt's avatar
Jack Moffitt committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#endif

#include "sock.h"
#include "resolver.h"

#ifndef _WIN32
extern int errno;
#endif

/* sock_initialize
**
** initializes the socket library.  you must call this
** before using the library!
*/
void sock_initialize(void)
{
#ifdef _WIN32
	WSADATA wsad;
	WSAStartup(0x0101, &wsad);
#endif

	resolver_initialize();
}

/* sock_shutdown
**
** shutdown the socket library.  remember to call this when you're
** through using the lib
*/
void sock_shutdown(void)
{
#ifdef _WIN32
	WSACleanup();
#endif
}

/* sock_get_localip
**
** gets the local ip address for the machine
** the ip it returns *should* be on the internet.
** in any case, it's as close as we can hope to get
** unless someone has better ideas on how to do this
*/
char *sock_get_localip(char *buff, int len)
{
	char temp[1024];

	if (gethostname(temp, 1024) != 0)
		return NULL;

	if (resolver_getip(temp, buff, len))
		return buff;

	return NULL;
}

/* sock_error
** 
** returns the last socket error
*/
int sock_error(void)
{
#ifdef _WIN32
	return WSAGetLastError();
#else
	return errno;
#endif
}

/* sock_recoverable
**
** determines if the socket error is recoverable
** in terms of non blocking sockets
*/
int sock_recoverable(int error)
{
121
	return (error == 0 || error == EAGAIN || error == EINTR || error == EINPROGRESS || error == EWOULDBLOCK);
Jack Moffitt's avatar
Jack Moffitt committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
169
170
171
172
173
174
175
176
177
178
179
}

/* sock_valid_socket
**
** determines if a sock_t represents a valid socket
*/
int sock_valid_socket(sock_t sock)
{
	int ret;
	int optval, optlen;

	optlen = sizeof(int);
	ret = getsockopt(sock, SOL_SOCKET, SO_TYPE, &optval, &optlen);

	return (ret == 0);
}

/* inet_aton
**
** turns an ascii ip address into a binary representation
*/
#ifdef _WIN32
int inet_aton(const char *s, struct in_addr *a)
{
	int lsb, b2, b3, msb;

	if (sscanf(s, "%d.%d.%d.%d", &lsb, &b2, &b3, &msb) < 4) {
		return 0;
	}

	a->s_addr = inet_addr(s);
    
	return (a->s_addr != INADDR_NONE);
}
#endif /* _WIN32 */

/* sock_set_blocking
**
** set the sock blocking or nonblocking
** SOCK_BLOCK for blocking
** SOCK_NONBLOCK for nonblocking
*/
int sock_set_blocking(sock_t sock, const int block)
{
#ifdef _WIN32
	int varblock = block;
#endif

	if ((!sock_valid_socket(sock)) || (block < 0) || (block > 1))
		return SOCK_ERROR;

#ifdef _WIN32
	return ioctlsocket(sock, FIONBIO, &varblock);
#else
	return fcntl(sock, F_SETFL, (block == SOCK_BLOCK) ? 0 : O_NONBLOCK);
#endif
}

180
181
182
183
184
185
186
187
188
189
190
191
int sock_set_nolinger(sock_t sock)
{
	struct linger lin = { 0, 0 };
	return setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&lin, sizeof(struct linger));
}

int sock_set_keepalive(sock_t sock)
{
	int keepalive = 1;
	return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int));
}

Jack Moffitt's avatar
Jack Moffitt committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/* sock_close
**
** close the socket
*/
int sock_close(sock_t sock)
{
#ifdef _WIN32
	return closesocket(sock);
#else
	return close(sock);
#endif
}

/* sock_write_bytes
**
** write bytes to the socket
208
** this function will _NOT_ block
Jack Moffitt's avatar
Jack Moffitt committed
209
210
211
212
213
214
215
216
217
218
219
220
*/
int sock_write_bytes(sock_t sock, const char *buff, const int len)
{
	/* sanity check */
	if (!buff) {
		return SOCK_ERROR;
	} else if (len <= 0) {
		return SOCK_ERROR;
	} else if (!sock_valid_socket(sock)) {
		return SOCK_ERROR;
	}

221
	return send(sock, buff, len, 0);
Jack Moffitt's avatar
Jack Moffitt committed
222
223
224
225
226
227
228
229
230
231
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
}

/* sock_write_string
**
** writes a string to a socket
** this function always blocks even if the socket is nonblocking
*/
int sock_write_string(sock_t sock, const char *buff)
{
	return (sock_write_bytes(sock, buff, strlen(buff)) > 0);
}

/* sock_write
**
** write a formatted string to the socket
** this function will always block, even if the socket is nonblocking
** will truncate the string if it's greater than 1024 chars.
*/
int sock_write(sock_t sock, const char *fmt, ...)
{
	char buff[1024];
	va_list ap;

	va_start(ap, fmt);
	vsnprintf(buff, 1024, fmt, ap);
	va_end(ap);
	
	return sock_write_bytes(sock, buff, strlen(buff));
}

int sock_read_bytes(sock_t sock, char *buff, const int len)
{
//	int ret;

	if (!sock_valid_socket(sock)) return 0;
	if (!buff) return 0;
	if (len <= 0) return 0;

	return recv(sock, buff, len, 0);
}

/* sock_read_line
**
** Read one line of at max len bytes from sock into buff.
** If ok, return 1 and nullterminate buff. Otherwize return 0.
** Terminating \n is not put into the buffer.
**
** this function will probably not work on sockets in nonblocking mode
*/
int sock_read_line(sock_t sock, char *buff, const int len)
{
	char c = '\0';
	int read_bytes, pos;
  
	if (!sock_valid_socket(sock)) {
		return 0;
	} else if (!buff) {
		return 0;
	} else if (len <= 0) {
		return 0;
	}

	pos = 0;
	read_bytes = recv(sock, &c, 1, 0);

	if (read_bytes < 0) {
		return 0;
	}

	while ((c != '\n') && (pos < len) && (read_bytes == 1)) {
		if (c != '\r')
			buff[pos++] = c;
		read_bytes = recv(sock, &c, 1, 0);
	}
	
	if (read_bytes == 1) {
		buff[pos] = '\0';
		return 1;
	} else {
		return 0;
	}
}

/* sock_connect_wto
**
** Connect to hostname on specified port and return the created socket.
** timeout specifies the maximum time to wait for this to finish and
** returns when it expires whether it connected or not
** setting timeout to 0 disable the timeout.
*/
sock_t sock_connect_wto(const char *hostname, const int port, const int timeout)
{
	sock_t  sock;
	struct sockaddr_in sin, server;
	char ip[20];

	if (!hostname || !hostname[0]) {
		return SOCK_ERROR;
	} else if (port <= 0) {
		return SOCK_ERROR;
	}
		
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == SOCK_ERROR) { 
		sock_close(sock); 
		return SOCK_ERROR; 
	}

	memset(&sin, 0, sizeof(struct sockaddr_in));
	memset(&server, 0, sizeof(struct sockaddr_in));

	if (!resolver_getip(hostname, ip, 20))
		return SOCK_ERROR;
	
	if (inet_aton(ip, (struct in_addr *)&sin.sin_addr) == 0) {
		sock_close(sock);
		return SOCK_ERROR;
	}

	memcpy(&server.sin_addr, &sin.sin_addr, sizeof(struct sockaddr_in));

	server.sin_family = AF_INET;
	server.sin_port = htons(port);

	/* if we have a timeout, use select, if not, use connect straight. */
	/* dunno if this is portable, and it sure is complicated for such a 
	   simple thing to want to do.  damn BSD sockets! */
	if (timeout > 0) {
		fd_set wfds;
		struct timeval tv;
		int retval;
		int val;
		int valsize = sizeof(int);

		FD_ZERO(&wfds);
		FD_SET(sock, &wfds);
		tv.tv_sec = timeout;
		tv.tv_usec = 0;

		sock_set_blocking(sock, SOCK_NONBLOCK);
		retval = connect(sock, (struct sockaddr *)&server, sizeof(server));
		if (retval == 0) {
			sock_set_blocking(sock, SOCK_BLOCK);
			return sock;
		} else {
			if (!sock_recoverable(sock_error())) {
				sock_close(sock);
				return SOCK_ERROR;
			}
		}

		if (select(sock + 1, NULL, &wfds, NULL, &tv)) {
			retval = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&val, (int *)&valsize);
			if ((retval == 0) && (val == 0)) {
				sock_set_blocking(sock, SOCK_BLOCK);
				return sock;
			} else {
				sock_close(sock);
				return SOCK_ERROR;
			}
		} else {
			sock_close(sock);
			return SOCK_ERROR;
		}
       } else {
	  	if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == 0) {
			return sock;
		} else {
			sock_close(sock);
			return SOCK_ERROR;
		}
       }
}

/* sock_get_server_socket
**
** create a socket for incoming requests on a specified port and
** interface.  if interface is null, listen on all interfaces.
** returns the socket, or SOCK_ERROR on failure
*/
402
sock_t sock_get_server_socket(const int port, char *sinterface)
Jack Moffitt's avatar
Jack Moffitt committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
{
#ifdef HAVE_IPV6
	struct sockaddr_storage sa;
#else	
	struct sockaddr_in sa;
#endif
	int sa_family, sa_len, error, opt;
	sock_t sock;
	char ip[40];

	if (port < 0)
		return SOCK_ERROR;

	/* defaults */
	memset(&sa, 0, sizeof(sa));
	sa_family = AF_INET;
419
	sa_len = sizeof(struct sockaddr_in);
Jack Moffitt's avatar
Jack Moffitt committed
420
421

	/* set the interface to bind to if specified */
422
423
	if (sinterface != NULL) {
		if (!resolver_getip(sinterface, ip, sizeof (ip)))
Jack Moffitt's avatar
Jack Moffitt committed
424
425
426
427
428
429
430
431
432
433
434
			return SOCK_ERROR;

#ifdef HAVE_IPV6
		if (inet_pton(AF_INET, ip, &((struct sockaddr_in*)&sa)->sin_addr) > 0) {
			((struct sockaddr_in*)&sa)->sin_family = AF_INET;
			((struct sockaddr_in*)&sa)->sin_port = htons(port);
		} else if (inet_pton(AF_INET6, ip, &((struct sockaddr_in6*)&sa)->sin6_addr) > 0) {
			sa_family = AF_INET6;
			sa_len = sizeof (struct sockaddr_in6);
			((struct sockaddr_in6*)&sa)->sin6_family = AF_INET6;
			((struct sockaddr_in6*)&sa)->sin6_port = htons(port);
435
		} else {
Jack Moffitt's avatar
Jack Moffitt committed
436
			return SOCK_ERROR;
437
		}
Jack Moffitt's avatar
Jack Moffitt committed
438
#else
439
		if (!inet_aton(ip, &sa.sin_addr)) {
Jack Moffitt's avatar
Jack Moffitt committed
440
			return SOCK_ERROR;
441
		} else {
Jack Moffitt's avatar
Jack Moffitt committed
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
			sa.sin_family = AF_INET;
			sa.sin_port = htons(port);
		}
#endif
	} else {
		((struct sockaddr_in*)&sa)->sin_addr.s_addr = INADDR_ANY;
		((struct sockaddr_in*)&sa)->sin_family = AF_INET;
		((struct sockaddr_in*)&sa)->sin_port = htons(port);
	}

	/* get a socket */
	sock = socket(sa_family, SOCK_STREAM, 0);
	if (sock == -1)
		return SOCK_ERROR;

	/* reuse it if we can */
	opt = 1;
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(int));
	
	/* bind socket to port */
	error = bind(sock, (struct sockaddr *)&sa, sa_len);
	if (error == -1)
		return SOCK_ERROR;

	return sock;
}

int sock_listen(sock_t serversock, int backlog)
{
	if (!sock_valid_socket(serversock))
		return 0;

	if (backlog <= 0)
		backlog = 10;

	return (listen(serversock, backlog) == 0);
}

int sock_accept(sock_t serversock, char *ip, int len)
{
	struct sockaddr_in sin;
	int ret;
	int slen;

	if (!sock_valid_socket(serversock))
		return SOCK_ERROR;

	slen = sizeof(struct sockaddr_in);
	ret = accept(serversock, (struct sockaddr *)&sin, &slen);

492
	if (ret >= 0 && ip != NULL) {
Jack Moffitt's avatar
Jack Moffitt committed
493
		strncpy(ip, inet_ntoa(sin.sin_addr), len);
494
495
496
		sock_set_nolinger(ret);
		sock_set_keepalive(ret);
	}
Jack Moffitt's avatar
Jack Moffitt committed
497
498
499

	return ret;
}