aboutsummaryrefslogtreecommitdiff
path: root/src/spdy2http/proxy.c
blob: 0c303823510445e1d38abdc75ccb33553b6f3a33 (plain) (blame)
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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*
    This file is part of libmicrospdy
    Copyright (C) 2013 Andrey Uzunov

    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 3 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, see <http://www.gnu.org/licenses/>.
*/

/**
 * @file proxy.c
 * @brief   Translates incoming SPDY requests to http server on localhost.
 * 			Uses libcurl.
 * 			No error handling for curl requests.
 * @author Andrey Uzunov
 */
 
#include "platform.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include "microspdy.h"
#include <curl/curl.h>
#include <assert.h>


#define PRINT_INFO(msg) do{\
	printf("%i:%s\n", __LINE__, msg);\
	fflush(stdout);\
	}\
	while(0)


#define PRINT_INFO2(fmt, ...) do{\
	printf("%i\n", __LINE__);\
	printf(fmt,##__VA_ARGS__);\
	printf("\n");\
	fflush(stdout);\
	}\
	while(0)


#define CURL_SETOPT(handle, opt, val) do{\
	int ret; \
	if(CURLE_OK != (ret = curl_easy_setopt(handle, opt, val))) \
	{ \
		PRINT_INFO2("curl_easy_setopt failed (%i = %i)", opt, ret); \
		abort(); \
	} \
	}\
	while(0)


int run = 1;
char* http_host;
CURLM *multi_handle;
int still_running = 0; /* keep number of running handles */
int http10=0;

struct Proxy
{
	char *path;
	struct SPDY_Request *request;
	struct SPDY_Response *response;
	CURL *curl_handle;
	struct curl_slist *curl_headers;
	struct SPDY_NameValue *headers;
	char *version;
	char *status_msg;
	void *http_body;
	size_t http_body_size;
	//ssize_t length;
	int status;
  bool done;
};


ssize_t
response_callback (void *cls,
						void *buffer,
						size_t max,
						bool *more)
{
	int ret;
	struct Proxy *proxy = (struct Proxy *)cls;
	void *newbody;
	
	//printf("response_callback\n");
  
  *more = true;
	
	if(!proxy->http_body_size)//nothing to write now
  {
    if(proxy->done) *more = false;
		return 0;
  }
	
	if(max >= proxy->http_body_size)
	{
		ret = proxy->http_body_size;
		newbody = NULL;
	}
	else
	{
		ret = max;
		if(NULL == (newbody = malloc(proxy->http_body_size - max)))
		{
			PRINT_INFO("no memory");
			return -1;
		}
		memcpy(newbody, proxy->http_body + max, proxy->http_body_size - max);
	}
	memcpy(buffer, proxy->http_body, ret);
	free(proxy->http_body);
	proxy->http_body = newbody;
	proxy->http_body_size -= ret;
	
  if(proxy->done && 0 == proxy->http_body_size) *more = false;
	
	return ret;
}


void
response_done_callback(void *cls,
						struct SPDY_Response *response,
						struct SPDY_Request *request,
						enum SPDY_RESPONSE_RESULT status,
						bool streamopened)
{
	(void)streamopened;
	struct Proxy *proxy = (struct Proxy *)cls;
	int ret;
	
	//printf("response_done_callback\n");
	
	//printf("answer for %s was sent\n", (char *)cls);
	
	if(SPDY_RESPONSE_RESULT_SUCCESS != status)
	{
		printf("answer was NOT sent, %i\n",status);
	}
	if(CURLM_OK != (ret = curl_multi_remove_handle(multi_handle, proxy->curl_handle)))
	{
		PRINT_INFO2("curl_multi_remove_handle failed (%i)", ret);
	}
	curl_slist_free_all(proxy->curl_headers);
	curl_easy_cleanup(proxy->curl_handle);
	
	SPDY_destroy_request(request);
	SPDY_destroy_response(response);
	if(!strcmp("/close",proxy->path)) run = 0;
	free(proxy->path);
	free(proxy);
}


static size_t
curl_header_cb(void *ptr, size_t size, size_t nmemb, void *userp)
{
	size_t realsize = size * nmemb;
	struct Proxy *proxy = (struct Proxy *)userp;
	char *line = (char *)ptr;
	char *name;
	char *value;
	char *status;
	int i;
	int pos;
	int ret;
  int num_values;
  const char * const * values;
  bool abort_it;
	
	//printf("curl_header_cb %s\n", line);
  
  //trailer
  if(NULL != proxy->response) return 0;

	if('\r' == line[0])
	{
		//all headers were already handled; prepare spdy frames
		if(NULL == (proxy->response = SPDY_build_response_with_callback(proxy->status,
							proxy->status_msg,
							proxy->version,
							proxy->headers,
							&response_callback,
							proxy,
							0)))
		{
			PRINT_INFO("no response");
			abort();
		}
    
		SPDY_name_value_destroy(proxy->headers);
		free(proxy->status_msg);
		free(proxy->version);
		
		if(SPDY_YES != SPDY_queue_response(proxy->request,
							proxy->response,
							true,
							false,
							&response_done_callback,
							proxy))
		{
			PRINT_INFO("no queue");
			abort();
		}
		
		return realsize;
	}
	
	pos = 0;
	if(NULL == proxy->version)
	{
		//first line from headers
		//version
		for(i=pos; i<realsize && ' '!=line[i]; ++i);
		if(i == realsize)
		{
			PRINT_INFO("error on parsing headers");
			abort();
		}
		if(NULL == (proxy->version = strndup(line, i - pos)))
		{
			PRINT_INFO("no memory");
			abort();
		}
		pos = i+1;
		
		//status (number)
		for(i=pos; i<realsize && ' '!=line[i] && '\r'!=line[i]; ++i);
		if(NULL == (status = strndup(&(line[pos]), i - pos)))
		{
			PRINT_INFO("no memory");
			abort();
		}
		proxy->status = atoi(status);
		free(status);
		if(i<realsize && '\r'!=line[i])
		{
			//status (message)
			pos = i+1;
			for(i=pos; i<realsize && '\r'!=line[i]; ++i);
			if(NULL == (proxy->status_msg = strndup(&(line[pos]), i - pos)))
			{
				PRINT_INFO("no memory");
				abort();
			}
		}
		return realsize;
	}
	
	//other lines
	//header name
	for(i=pos; i<realsize && ':'!=line[i] && '\r'!=line[i]; ++i)
		line[i] = tolower(line[i]); //spdy requires lower case
	if(NULL == (name = strndup(line, i - pos)))
	{
		PRINT_INFO("no memory");
		abort();
	}
	if(0 == strcmp(SPDY_HTTP_HEADER_CONNECTION, name)
		|| 0 == strcmp(SPDY_HTTP_HEADER_KEEP_ALIVE, name))
	{
		//forbidden in spdy, ignore
		free(name);
		return realsize;
	}
	if(i == realsize || '\r'==line[i])
	{
		//no value. is it possible?
		if(SPDY_YES != SPDY_name_value_add(proxy->headers, name, ""))
		{
			PRINT_INFO("SPDY_name_value_add failed");
			abort();
		}
		return realsize;
	}
	
	//header value
	pos = i+1;
	while(pos<realsize && isspace(line[pos])) ++pos; //remove leading space
	for(i=pos; i<realsize && '\r'!=line[i]; ++i);
	if(NULL == (value = strndup(&(line[pos]), i - pos)))
	{
		PRINT_INFO("no memory");
		abort();
	}
	if(SPDY_YES != (ret = SPDY_name_value_add(proxy->headers, name, value)))
	{
    abort_it=true;
    if(NULL != (values = SPDY_name_value_lookup(proxy->headers, name, &num_values)))
      for(i=0; i<num_values; ++i)
        if(0 == strcasecmp(value, values[i]))
        {
          abort_it=false;
          PRINT_INFO2("header appears more than once with same value '%s: %s'", name, value);
          break;
        }
    
    if(abort_it)
    {
      PRINT_INFO2("SPDY_name_value_add failed (%i) for '%s'", ret, name);
      abort();
    }
	}
	free(name);
	free(value);

	return realsize;
}


static size_t
curl_write_cb(void *contents, size_t size, size_t nmemb, void *userp)
{
	size_t realsize = size * nmemb;
	struct Proxy *proxy = (struct Proxy *)userp;
	
	//printf("curl_write_cb %i\n", realsize);
  
	if(NULL == proxy->http_body)
		proxy->http_body = malloc(realsize);
	else
		proxy->http_body = realloc(proxy->http_body, proxy->http_body_size + realsize);
	if(NULL == proxy->http_body)
	{
		PRINT_INFO("not enough memory (realloc returned NULL)");
		return 0;
	}

	memcpy(proxy->http_body + proxy->http_body_size, contents, realsize);
	proxy->http_body_size += realsize;

	return realsize;
}


int
iterate_cb (void *cls, const char *name, const char * const * value, int num_values)
{
	struct Proxy *proxy = (struct Proxy *)cls;
  struct curl_slist **curl_headers = (&(proxy->curl_headers));
  char *line;
  int line_len = strlen(name) + 3; //+ ": \0"
  int i;
  
  for(i=0; i<num_values; ++i)
  {
		if(i) line_len += 2; //", "
		line_len += strlen(value[i]);
	}
	
	if(NULL == (line = malloc(line_len)))
	{
		//no recovory
		PRINT_INFO("no memory");
		abort();
	}
	line[0] = 0;
    
    strcat(line, name);
    strcat(line, ": ");
    //all spdy header names are lower case;
    //for simplicity here we just capitalize the first letter
    line[0] = toupper(line[0]);
    
	for(i=0; i<num_values; ++i)
	{
		if(i) strcat(line, ", ");
		strcat(line, value[i]);
	}
    if(NULL == (*curl_headers = curl_slist_append(*curl_headers, line)))
    {
		PRINT_INFO("curl_slist_append failed");
		abort();
	}
	free(line);
	
	return SPDY_YES;
}


void
standard_request_handler(void *cls,
                        struct SPDY_Request * request,
                        uint8_t priority,
                        const char *method,
                        const char *path,
                        const char *version,
                        const char *host,
                        const char *scheme,
                        struct SPDY_NameValue * headers)
{
	(void)cls;
	(void)priority;
	(void)host;
	(void)scheme;
	
	char *url;
	struct Proxy *proxy;
	int ret;
	
	//printf("received request for '%s %s %s'\n", method, path, version);
	if(NULL == (proxy = malloc(sizeof(struct Proxy))))
	{
		PRINT_INFO("No memory");
		abort();
	}
	memset(proxy, 0, sizeof(struct Proxy));
	proxy->request = request;
	if(NULL == (proxy->headers = SPDY_name_value_create()))
	{
		PRINT_INFO("No memory");
		abort();
	}
	
  //TODO add https
	if(0 == strcmp(http_host, "any"))
		ret = asprintf(&url,"%s%s%s","http://", host, path);
	else
		ret = asprintf(&url,"%s%s%s","http://", http_host, path);
		
	if(-1 == ret)
	{
		PRINT_INFO("No memory");
		abort();
	}
	
	if(NULL == (proxy->path = strdup(path)))
	{
		PRINT_INFO("No memory");
		abort();
	}
    
    SPDY_name_value_iterate(headers, &iterate_cb, proxy);
	
	if(NULL == (proxy->curl_handle = curl_easy_init()))
    {
		PRINT_INFO("curl_easy_init failed");
		abort();
	}
	
	//CURL_SETOPT(proxy->curl_handle, CURLOPT_VERBOSE, 1);
	CURL_SETOPT(proxy->curl_handle, CURLOPT_URL, url);
	free(url);
	if(http10)
		CURL_SETOPT(proxy->curl_handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
	CURL_SETOPT(proxy->curl_handle, CURLOPT_WRITEFUNCTION, curl_write_cb);
	CURL_SETOPT(proxy->curl_handle, CURLOPT_WRITEDATA, proxy);
	CURL_SETOPT(proxy->curl_handle, CURLOPT_HEADERFUNCTION, curl_header_cb);
	CURL_SETOPT(proxy->curl_handle, CURLOPT_HEADERDATA, proxy);
	CURL_SETOPT(proxy->curl_handle, CURLOPT_PRIVATE, proxy);
	CURL_SETOPT(proxy->curl_handle, CURLOPT_HTTPHEADER, proxy->curl_headers);
  CURL_SETOPT(proxy->curl_handle, CURLOPT_SSL_VERIFYPEER, 0L);
  CURL_SETOPT(proxy->curl_handle, CURLOPT_SSL_VERIFYHOST, 0L);
	
	if(CURLM_OK != (ret = curl_multi_add_handle(multi_handle, proxy->curl_handle)))
	{
		PRINT_INFO2("curl_multi_add_handle failed (%i)", ret);
		abort();
	}
	
	if(CURLM_OK != (ret = curl_multi_perform(multi_handle, &still_running))
		&& CURLM_CALL_MULTI_PERFORM != ret)
	{
		PRINT_INFO2("curl_multi_perform failed (%i)", ret);
		abort();
	}
}

int
main (int argc, char *const *argv)
{	
	unsigned long long timeoutlong=0;
  long curl_timeo = -1;
	struct timeval timeout;
	int ret;
	fd_set rs;
	fd_set ws;
	fd_set es;
	fd_set curl_rs;
	fd_set curl_ws;
	fd_set curl_es;
	int maxfd = -1;
	struct SPDY_Daemon *daemon;
  CURLMsg *msg;
  int msgs_left;
  struct Proxy *proxy;

	signal(SIGPIPE, SIG_IGN);
	
	if(argc != 6)
	{
		printf("Usage: %s cert-file key-file host port http/1.0(yes/no)\n\
\n\
Example for transparent proxy (':host' header is used to know which HTTP server to connect):\n\
%s cert.pem key.pem any 8080 no\n", argv[0], argv[0]);
		return 1;
	}
	
	SPDY_init();
	
	daemon = SPDY_start_daemon(atoi(argv[4]),
								argv[1],
								argv[2],
								NULL,
								NULL,
								&standard_request_handler,
								NULL,
								NULL,
								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
								1800,
								SPDY_DAEMON_OPTION_END);
	
	if(NULL==daemon){
		printf("no daemon\n");
		return 1;
	}
	
	multi_handle = curl_multi_init();
	
	if(NULL==multi_handle){
		PRINT_INFO("no multi_handle");
		abort();
	}
	
	if(!strcmp("yes", argv[5]))
		http10 = 1;
	
	http_host = argv[3];
	timeout.tv_usec = 0;

	do
	{
		//printf("still %i\n", still_running);
		FD_ZERO(&rs);
		FD_ZERO(&ws);
		FD_ZERO(&es);
		FD_ZERO(&curl_rs);
		FD_ZERO(&curl_ws);
		FD_ZERO(&curl_es);

		if(still_running > 0)
			timeout.tv_sec = 0; //return immediately
		else
		{
			ret = SPDY_get_timeout(daemon, &timeoutlong);
			if(SPDY_NO == ret)
				timeout.tv_sec = 1;
			else
				timeout.tv_sec = timeoutlong;
		}
		timeout.tv_usec = 0;
		
		maxfd = SPDY_get_fdset (daemon,
								&rs,
								&ws, 
								&es);	
		assert(-1 != maxfd);
		
		ret = select(maxfd+1, &rs, &ws, &es, &timeout);
		
		switch(ret) {
			case -1:
				PRINT_INFO2("select error: %i", errno);
				break;
			case 0:
				break;
			default:
				SPDY_run(daemon);
			break;
		}
		
		timeout.tv_sec = 0;
		if(still_running > 0)
		{
			if(CURLM_OK != (ret = curl_multi_timeout(multi_handle, &curl_timeo)))
			{
				PRINT_INFO2("curl_multi_timeout failed (%i)", ret);
				abort();
			}
			if(curl_timeo >= 0 && curl_timeo < 500)
				timeout.tv_usec = curl_timeo * 1000;
			else
				timeout.tv_usec = 500000;
		}
		else continue;
		//else timeout.tv_usec = 500000;

		if(CURLM_OK != (ret = curl_multi_fdset(multi_handle, &curl_rs, &curl_ws, &curl_es, &maxfd)))
		{
			PRINT_INFO2("curl_multi_fdset failed (%i)", ret);
			abort();
		}
		if(-1 == maxfd)
		{
			PRINT_INFO("maxfd is -1");
			//continue;
			ret = 0;
		}
		else
		ret = select(maxfd+1, &curl_rs, &curl_ws, &curl_es, &timeout);

		switch(ret) {
			case -1:
				PRINT_INFO2("select error: %i", errno);
				break;
			case 0: /* timeout */
				//break or not
			default: /* action */
				if(CURLM_OK != (ret = curl_multi_perform(multi_handle, &still_running))
					&& CURLM_CALL_MULTI_PERFORM != ret)
				{
					PRINT_INFO2("curl_multi_perform failed (%i)", ret);
					abort();
				}
				break;
		}
    
    while ((msg = curl_multi_info_read(multi_handle, &msgs_left))) {
      if (msg->msg == CURLMSG_DONE) {
        if(CURLE_OK == msg->data.result)
        {
          if(CURLE_OK != (ret = curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &proxy)))
          {
            PRINT_INFO2("err %i",ret);
            abort();
          }

          proxy->done = true;
        }
        else
        {
          //TODO handle error
          PRINT_INFO("bad curl result");
        }
      }
      else PRINT_INFO("shouldn't happen");
    }
  }
  while(run);
	
	curl_multi_cleanup(multi_handle);

	SPDY_stop_daemon(daemon);
	
	SPDY_deinit();
	
	return 0;
}