File: socklib.c

package info (click to toggle)
streamripper 1.61.7-1sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,216 kB
  • ctags: 757
  • sloc: sh: 8,778; ansic: 6,138; makefile: 236
file content (407 lines) | stat: -rw-r--r-- 9,908 bytes parent folder | download
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
121
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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
402
403
404
405
406
407
/* socklib.c - jonclegg@yahoo.com
 * library routines for handling socket stuff
 *
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#if WIN32
#include <winsock2.h>
#else
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <netinet/in.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#endif

#if __UNIX__
#include <arpa/inet.h>
#elif __BEOS__
#include <be/net/netdb.h>   
#endif

#include "types.h"
#include "util.h"
#include "socklib.h"
#include "threadlib.h"
#include "compat.h"
#include "debug.h"

#define DEFAULT_TIMEOUT		15

#if WIN32
#define FIRST_READ_TIMEOUT	(30 * 1000)
#elif __UNIX__
#define FIRST_READ_TIMEOUT	30
#endif


/*********************************************************************************
 * Public functions
 *********************************************************************************/
error_code socklib_init();
error_code socklib_open(HSOCKET *socket_handle, char *host, int port,
			char *if_name);
void socklib_close(HSOCKET *socket_handle);
void socklib_cleanup();
error_code socklib_read_header(HSOCKET *socket_handle, char *buffer, int size, 
			       int (*recvall)(HSOCKET *socket_handle, 
					      char* buffer, int size, 
					      int timeout));
int socklib_recvall(HSOCKET *socket_handle, char* buffer, int size,
		    int timeout);
int socklib_sendall(HSOCKET *socket_handle, char* buffer, int size);
error_code socklib_recvall_alloc(HSOCKET *socket_handle, char** buffer, 
				 unsigned long *size, 
				 int (*recvall)(HSOCKET *socket_handle, 
						char* buffer, int size, 
						int timeout));
error_code read_interface(char *if_name, u_int32_t *addr);

/*********************************************************************************
 * Private Vars 
 *********************************************************************************/
static BOOL m_done_init = FALSE; // so we don't init the mutex twice.. arg.

/*
 * Init socket stuff
 */
error_code socklib_init()
{
#if WIN32
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
#endif

    if (m_done_init)
	return SR_SUCCESS;

#if WIN32
    wVersionRequested = MAKEWORD( 2, 2 );
    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 )
        return SR_ERROR_WIN32_INIT_FAILURE;
#endif

    m_done_init = TRUE;
    return SR_SUCCESS;
}


/*
 * try to find the local interface to bind to
 */
error_code read_interface(char *if_name, u_int32_t *addr)
{
#if defined (WIN32)
    return -1;
#else
    int fd;
    struct ifreq ifr;

    memset(&ifr, 0, sizeof(struct ifreq));
    if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) >= 0) {
	ifr.ifr_addr.sa_family = AF_INET;
	strcpy(ifr.ifr_name, if_name);
	if (ioctl(fd, SIOCGIFADDR, &ifr) == 0)
	    *addr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr;
	else {
	    close(fd);
	    return -2;
	}
    } else
	return -1;
    close(fd);
    return 0;
#endif
}

/*
 * open's a tcp connection to host at port, host can be a dns name or IP,
 * socket_handle gets assigned to the handle for the connection
 */

error_code socklib_open(HSOCKET *socket_handle, char *host, int port, char *if_name)
{
    struct sockaddr_in address, local;
    struct hostent *hp;
    int len;

    if (!socket_handle || !host)
	return SR_ERROR_INVALID_PARAM;

    socket_handle->s = socket(AF_INET, SOCK_STREAM, 0);

    if (if_name) {
	if (read_interface(if_name,&local.sin_addr.s_addr) != 0)
	    local.sin_addr.s_addr = htonl(INADDR_ANY);
	local.sin_family = AF_INET;
	local.sin_port = htons(0);
	if (bind(socket_handle->s, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR) {
	    WSACleanup();
	    closesocket(socket_handle->s);
	    return SR_ERROR_CANT_BIND_ON_INTERFACE;
	}
    }

    if ((address.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE)
    {
	hp = gethostbyname(host);
	if (hp)
	    memcpy(&address.sin_addr, hp->h_addr_list[0], hp->h_length);
	else
	{
	    debug_printf("resolving hostname: %s failed\n", host);
	    WSACleanup();
	    return SR_ERROR_CANT_RESOLVE_HOSTNAME;
	}
    }
    address.sin_family = AF_INET;
    address.sin_port = htons((unsigned short)port);
    len = sizeof(address);

    if (connect(socket_handle->s, (struct sockaddr *)&address, len) == SOCKET_ERROR)
    {
	return SR_ERROR_CONNECT_FAILED;
    }

#ifdef WIN32
    {
	struct timeval timeout = {DEFAULT_TIMEOUT*1000, 0};
	if (setsockopt(socket_handle->s, SOL_SOCKET,  SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) == SOCKET_ERROR)
	    return SR_ERROR_CANT_SET_SOCKET_OPTIONS;
    }
#endif

    socket_handle->closed = FALSE;
    return SR_SUCCESS;
}

void socklib_cleanup()
{
    WSACleanup();
    m_done_init = FALSE;
}

void socklib_close(HSOCKET *socket_handle)
{
    closesocket(socket_handle->s);
    socket_handle->closed = TRUE;
}

error_code
socklib_read_header(HSOCKET *socket_handle, char *buffer, int size, 
		    int (*recvall)(HSOCKET *socket_handle, char* buffer,
				   int size, int timeout))
{
    int i;
#ifdef WIN32
    struct timeval timeout = {FIRST_READ_TIMEOUT, 0};
#endif
    int ret;
    char *t;
    int (*myrecv)(HSOCKET *socket_handle, char* buffer, int size, int timeout);

    if (socket_handle->closed)
	return SR_ERROR_SOCKET_CLOSED;

    if (recvall)
	myrecv = recvall;
    else
	myrecv = socklib_recvall;
#ifdef WIN32
    if (setsockopt(socket_handle->s, SOL_SOCKET,  SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) == SOCKET_ERROR)
	return SR_ERROR_CANT_SET_SOCKET_OPTIONS;
#endif

    memset(buffer, 0, size);
    for(i = 0; i < size; i++)
    {
	if ((ret = (*myrecv)(socket_handle, &buffer[i], 1, 0)) < 0)
	    return ret;

	if (ret == 0) {
	    debug_printf("http header:\n%s\n", buffer);
	    return SR_ERROR_NO_HTTP_HEADER;
	}

	if (socket_handle->closed)
	    return SR_ERROR_SOCKET_CLOSED;

	/* GCS: This patch is too restrictive. */
#if defined (commentout)
	//look for the end of the icy-header
	if (!strstr(buffer, "icy-") && !strstr(buffer,"ice-"))
	    continue;
#endif

	t = buffer + (i > 3 ? i - 3: i);

	if (strncmp(t, "\r\n\r\n", 4) == 0)
	    break;

	if (strncmp(t, "\n\0\r\n", 4) == 0)	// wtf? live365 seems to do this
	    break;
    }

    if (i == size) {
	debug_printf("http header:\n%s\n", buffer);
	return SR_ERROR_NO_HTTP_HEADER;
    }

    buffer[i] = '\0';

#ifdef WIN32
    timeout.tv_sec = DEFAULT_TIMEOUT*1000;
    if (setsockopt(socket_handle->s, SOL_SOCKET,  SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) == SOCKET_ERROR)
	return SR_ERROR_CANT_SET_SOCKET_OPTIONS;
#endif

    return SR_SUCCESS;
}


/*
 * Default recv
 */
int socklib_recvall(HSOCKET *socket_handle, char* buffer, int size, int timeout)
{
    int ret = 0, read = 0;
    int sock;
    fd_set fds;
    struct timeval tv;
    
    sock = socket_handle->s;
    FD_ZERO(&fds);
    while(size)
    {
	if (socket_handle->closed)
	    return SR_ERROR_SOCKET_CLOSED;
	
	if (timeout > 0)
	{
	    // Wait up to 'timeout' seconds for data on socket to be ready for read
	    FD_SET(sock, &fds);
	    tv.tv_sec = timeout;
	    tv.tv_usec = 0;
	    ret = select(sock + 1, &fds, NULL, NULL, &tv);
	    if (ret == SOCKET_ERROR)
		return SR_ERROR_SELECT_FAILED;
	    if (ret != 1)
		return SR_ERROR_TIMEOUT;
	}
		
	//		DEBUG2(("calling recv for %d bytes", size));
        ret = recv(socket_handle->s, &buffer[read], size, 0);
	//		DEBUG2(("recv: %d", ret));
	debug_printf ("RECV req %5d bytes, got %5d bytes\n", size, ret);

        if (ret == SOCKET_ERROR)
	    return SR_ERROR_RECV_FAILED;

	/* GCS: Jun 5, 2004.  If we don't get any bytes, what does that 
	   mean?  This is supposed to be a blocking read. */
	if (ret == 0) {
	    debug_printf ("recv recieved zero bytes!\n");
	    break;
	}

	read += ret;
	size -= ret;
    }

    return read;
}

int socklib_sendall(HSOCKET *socket_handle, char* buffer, int size)
{
    int ret = 0, sent = 0;

    while(size)
    {
	if (socket_handle->closed)
	    return SR_ERROR_SOCKET_CLOSED;

        ret = send(socket_handle->s, &buffer[sent], size, 0);
        if (ret == SOCKET_ERROR)
	    return SR_ERROR_SEND_FAILED;

	if (ret == 0)
	    break;

	sent += ret;
	size -= ret;
    }

    return sent;
	
}

error_code
socklib_recvall_alloc(HSOCKET *socket_handle, char** buffer, 
		      unsigned long *size, 
		      int (*recvall)(HSOCKET *socket_handle, char* buffer, 
				     int size, int timeout))
{
    const int CHUNK_SIZE = 8192;
    int (*myrecv)(HSOCKET *socket_handle, char* buffer, int size, int timeout);
    int ret;
    unsigned long mysize = 0;
    int chunks = 1;
    char *temp = (char *)malloc(CHUNK_SIZE);

    if (socket_handle->closed)
	return SR_ERROR_SOCKET_CLOSED;

    if (!size)
	return SR_ERROR_INVALID_PARAM;

    if (recvall)
	myrecv = recvall;
    else
	myrecv = socklib_recvall;

    while((ret = myrecv(socket_handle, &temp[mysize], (CHUNK_SIZE*chunks)-mysize, 0)) >= 0)
    {
	mysize += ret;

	if (ret == 0)
	    break;

	if ((mysize % CHUNK_SIZE) == 0)
	{
	    chunks++;
	    temp = (char *)realloc(temp, CHUNK_SIZE*chunks);
	}
    }
    if (mysize == 0)
	return SR_ERROR_RECV_FAILED;

    temp[mysize] = '\0';
    *size = mysize;
    *buffer = temp;
    return SR_SUCCESS;
}