File: Http.cpp

package info (click to toggle)
blockout2 2.4%2Bdfsg1-7
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 5,492 kB
  • sloc: cpp: 8,694; ansic: 147; makefile: 106
file content (447 lines) | stat: -rw-r--r-- 8,935 bytes parent folder | download | duplicates (2)
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
 	File:        Http.cpp 
  Description: Contains routines for accessing HTTP sites
  Program:     BlockOut
  Author:      Jean-Luc PONS

  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.
*/


#include "GLApp/GLApp.h"
#include "Http.h"
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>


#define WAIT_FOR_READ  1
#define WAIT_FOR_WRITE 2

// -------------------------------------------------------

Http::Http() {
  strcpy(err_str,"No error");
  useProxy = FALSE;
  strcpy(proxyName,"");
  proxyPort=0;
}

// -------------------------------------------------------

void Http::SetProxy(BOOL enable) {
  useProxy = enable;
}

// -------------------------------------------------------

void Http::SetProxyName(char *name) {
  strncpy(proxyName,name,255);
  proxyName[255]=0;
}

// -------------------------------------------------------

void Http::SetProxyPort(int port) {
  proxyPort = port;
}


// -------------------------------------------------------

int Http::WaitFor(int sock,DWORD timeout,int mode) {

  fd_set fdset;
  fd_set *rd = NULL, *wr = NULL;
  struct timeval tmout;
  int result;

  FD_ZERO (&fdset);
  FD_SET (sock, &fdset);
  if (mode == WAIT_FOR_READ)
    rd = &fdset;
  if (mode == WAIT_FOR_WRITE)
    wr = &fdset;

  tmout.tv_sec  = (long)(timeout / 1000);
  tmout.tv_usec = (long)(timeout % 1000) * 1000;

  do
    result = select (sock + 1, rd, wr, NULL, &tmout);
  while (result < 0 && errno == EINTR);

	if( result==0 ) {
		sprintf(err_str,"The operation timed out");
	} else if ( result < 0 ) {
		sprintf(err_str,"Tranmission error");
		return 0;
	}

  return result;

}

// -------------------------------------------------------

int Http::Write(int sock, char *buf, int bufsize,DWORD timeout) {

	int total_written = 0;
	int written = 0;

  while( bufsize > 0 )
  {
		// Wait
    if (!WaitFor(sock, timeout, WAIT_FOR_WRITE))
	    return -1;

		// Write
    do
      written = send(sock, buf, bufsize, 0);
    while (written == -1 && errno == EINTR);

		if( written <= 0 )
 	    break;

    buf += written;
		total_written += written;
    bufsize -= written;
  }

	if( written < 0 ) {
		sprintf(err_str,"Tranmission error");
		return -1;
	}

  return total_written;

}

// -------------------------------------------------------

int Http::Read(int sock, char *buf, int bufsize,DWORD timeout) {

	int rd = 0;
	int total_read = 0;

	while( bufsize>0 ) {

    // Wait
    if (!WaitFor(sock, timeout, WAIT_FOR_READ))
	    return -1;

		// Read
    do
      rd = recv(sock, buf, bufsize, 0);
    while (rd == -1 && errno == EINTR);

    if( rd <= 0 )
			break;

    buf += rd;
		total_read += rd;
    bufsize -= rd;
	
	}

	if( rd < 0 ) {
		sprintf(err_str,"Tranmission error");
		return -1;
	}

  return total_read;

}

// -------------------------------------------------------

int Http::Connect(char *site, int port) {

	struct hostent *host_info;
  struct sockaddr_in server;

	// Resolve IP
  host_info = gethostbyname(site);
  if (host_info == NULL) {	
     sprintf(err_str, "Unknown host: %s", site);
     return -1; 
  }

	// Build TCP connection
	int sock = socket(AF_INET, SOCK_STREAM,0);
  if (sock < 0 ) {
		switch(errno) {
			case EACCES:
				sprintf(err_str,"Socket error: Permission denied");
				break;
			case EMFILE:
        sprintf(err_str,"Socket error: Descriptor table is full");
				break;
			case ENOMEM:
        sprintf(err_str,"Socket error: Insufficient user memory is available");
				break;
#ifdef ENOSR
			case ENOSR:
				sprintf(err_str,"Socket error: Insufficient STREAMS resources available");
				break;
#endif
			case EPROTONOSUPPORT:
        sprintf(err_str,"Socket error: Specified protocol is not supported");
				break;
			default:
				sprintf(err_str,"Socket error: Unknow code:%d",errno);
				break;
		}
    return -1;
  }  

  // Connect
  memset(&server,0,sizeof(sockaddr_in));
  server.sin_family = host_info->h_addrtype;
  memcpy((char*)&server.sin_addr, host_info->h_addr,host_info->h_length);
  server.sin_port=htons(port);
  if( connect(sock,(struct sockaddr *)&server, sizeof(server) ) < 0 ) {
    sprintf(err_str, "Cannot connect to host: %s\n", site);
		close(sock);
    return -1;
  }

	// Sucess
	return sock;

}

// -------------------------------------------------------

int Http::GetHttpCode() {

  char err[4];
  strncpy( err , &(response[9]) , 3);
  err[3]=0;
  return atoi(err);

}

// -------------------------------------------------------

BOOL Http::CheckProxy() {

  if( useProxy ) {

    if( strlen(proxyName)==0 ) {
      sprintf(err_str,"Invalid HTTP proxy name");
      return FALSE;
    }

    if( proxyPort<=0 || proxyPort>65535 ) {
      sprintf(err_str,"Invalid HTTP proxy port number");
      return FALSE;
    }

  }

  return TRUE;

}

// -------------------------------------------------------

char *Http::UploadFile(char *url,char *remotePHP,BYTE *buffer,DWORD length,DWORD timeout)
{

	char page[256];
	char req[1024];
	strcpy(err_str,"");
  char link[512];

  if( !CheckProxy() ) return FALSE;

	if( remotePHP[0]=='/' ) {
		strcpy(page,remotePHP);
	} else {
		sprintf(page,"/%s",remotePHP);
	}

	// Connect
  int sock;
  if( useProxy ) {
    // Connect to the proxy
    sock  = Connect(proxyName,proxyPort);
    sprintf(link,"http://%s%s",url,page);
  } else {
    // Default HTTP connection
    sock  = Connect(url,80);
  }
	if( sock < 0 )
		return NULL;

	// Send the request
	sprintf(req,"PUT %s HTTP/1.0\r\n"
              "User-Agent: BlockOut\r\n"
					    "Host: %s\r\n"
					    "Content-Length: %d\r\n"
					 	  "Cache-Control: no-cache\r\n"
						  "\r\n",
						  (useProxy?link:page),url,length);

	int lgth = strlen(req);
	int w = Write(sock,req,lgth,timeout);
	if( w != lgth ) {
		if( strlen(err_str)==0 ) 
			sprintf(err_str,"HTTP send error");
    close(sock);
		return NULL;
	}

	// Write PUT Data
	w = Write(sock,(char *)buffer,length,timeout);
	if( w != length ) {
		if( strlen(err_str)==0 ) 
			sprintf(err_str,"HTTP send error");
    close(sock);
		return NULL;
	}

	// Get the response
	int r = Read(sock,response,262143,timeout);
	if( r<=0 ) {
		if( strlen(err_str)==0 ) 
			sprintf(err_str,"HTTP receive error");
    close(sock);
		return NULL;
	}

	close(sock);
	response[r]=0;

	// Check HTTP response
	int httpCode = GetHttpCode();

	if( httpCode>=300 ) {
  	sprintf(err_str,"HTTP error code %d",httpCode);
		return NULL;
	}

	// Get RecResp
	char *p = strstr(response,"RecResp:");
	if( p==NULL ) {
  	sprintf(err_str,"Invalid HTTP response");
		return NULL;
	}
	char *rr = p + 8;
	while( *p>=32 ) p++;
	*p=0;

  return rr;

}

// -------------------------------------------------------

char *Http::Get(char *link,DWORD timeout,DWORD *outLength) {

	char site[256];
	char page[256];
	char req[1024];
	strcpy(err_str,"");
	
	if( outLength ) *outLength = 0;

  if( !CheckProxy() ) return FALSE;

	if( strncmp(link,"http://",7) != 0 ) {
    sprintf(err_str,"Invalid URL address");
		return NULL;
	}

	strcpy(site,link+7);
	char *p = strchr(site,'/');
	if( !p ) {
    sprintf(err_str,"Invalid URL address");
		return NULL;
	}

	strcpy(page,p);
	*p = 0;

	// Connect
	int sock;
  if( useProxy ) {
    // Connect to the proxy
    sock  = Connect(proxyName,proxyPort);
  } else {
    // Default HTTP connection
    sock  = Connect(site,80);
  }
  
	if( sock < 0 )
		return NULL;

  // Build the request
	sprintf(req,"GET %s HTTP/1.0\r\n"
              "User-Agent: BlockOut\r\n"
					    "Host: %s\r\n"
					 	  "Cache-Control: no-cache\r\n"
						  "\r\n",
              (useProxy?link:page),site);

	// Send the request
	int lgth = strlen(req);
	int w = Write(sock,req,lgth,timeout);
	if( w != lgth ) {
		if( strlen(err_str)==0 ) 
			sprintf(err_str,"HTTP send error");
    close(sock);
		return NULL;
	}

	// Get the response
	int r = Read(sock,response,262143,timeout);
	if( r<=0 ) {
		if( strlen(err_str)==0 ) 
			sprintf(err_str,"HTTP receive error");
    close(sock);
		return NULL;
	}

	close(sock);
	response[r]=0;

	// Check HTTP response
	int httpCode = GetHttpCode();

	if( httpCode>=300 ) {
  	sprintf(err_str,"HTTP error code %d",httpCode);
		return NULL;
	}

	// Jump headers
	p = strstr(response,"\r\n\r\n");
	if( p==NULL ) {
  	sprintf(err_str,"Invalid HTTP response");
		return NULL;
	}
	
	if( outLength ) *outLength = r - (int)((p+4)-response);

  return p+4;

}

// -------------------------------------------------------

char *Http::GetError() {

  return err_str;

}