-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.c
2883 lines (2415 loc) · 67.8 KB
/
http.c
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_IOCCOM_H
#include <sys/ioccom.h>
#endif
#ifndef WIN32
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#endif
#include <sys/queue.h>
#ifndef WIN32
#include <netinet/in.h>
#include <netdb.h>
#endif
#ifdef WIN32
#include <winsock2.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <syslog.h>
#endif
#include <signal.h>
#include <time.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#undef timeout_pending
#undef timeout_initialized
#include "strlcpy-internal.h"
#include "event.h"
#include "evhttp.h"
#include "evutil.h"
#include "log.h"
#include "http-internal.h"
#ifdef WIN32
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#define strdup _strdup
#endif
#ifndef HAVE_GETNAMEINFO
#define NI_MAXSERV 32
#define NI_MAXHOST 1025
#ifndef NI_NUMERICHOST
#define NI_NUMERICHOST 1
#endif
#ifndef NI_NUMERICSERV
#define NI_NUMERICSERV 2
#endif
static int
fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
size_t hostlen, char *serv, size_t servlen, int flags)
{
struct sockaddr_in *sin = (struct sockaddr_in *)sa;
if (serv != NULL) {
char tmpserv[16];
evutil_snprintf(tmpserv, sizeof(tmpserv),
"%d", ntohs(sin->sin_port));
if (strlcpy(serv, tmpserv, servlen) >= servlen)
return (-1);
}
if (host != NULL) {
if (flags & NI_NUMERICHOST) {
if (strlcpy(host, inet_ntoa(sin->sin_addr),
hostlen) >= hostlen)
return (-1);
else
return (0);
} else {
struct hostent *hp;
hp = gethostbyaddr((char *)&sin->sin_addr,
sizeof(struct in_addr), AF_INET);
if (hp == NULL)
return (-2);
if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
return (-1);
else
return (0);
}
}
return (0);
}
#endif
#ifndef HAVE_GETADDRINFO
/* Apparently msvc2010 does have an addrinfo definition visible here */
#if !defined(WIN32) || !defined(_MSC_VER) || (_MSC_VER < 1600)
struct addrinfo {
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
struct sockaddr *ai_addr;
struct addrinfo *ai_next;
};
#endif
static int
fake_getaddrinfo(const char *hostname, struct addrinfo *ai)
{
struct hostent *he = NULL;
struct sockaddr_in *sa;
if (hostname) {
he = gethostbyname(hostname);
if (!he)
return (-1);
}
ai->ai_family = he ? he->h_addrtype : AF_INET;
ai->ai_socktype = SOCK_STREAM;
ai->ai_protocol = 0;
ai->ai_addrlen = sizeof(struct sockaddr_in);
if (NULL == (ai->ai_addr = malloc(ai->ai_addrlen)))
return (-1);
sa = (struct sockaddr_in*)ai->ai_addr;
memset(sa, 0, ai->ai_addrlen);
if (he) {
sa->sin_family = he->h_addrtype;
memcpy(&sa->sin_addr, he->h_addr_list[0], he->h_length);
} else {
sa->sin_family = AF_INET;
sa->sin_addr.s_addr = INADDR_ANY;
}
ai->ai_next = NULL;
return (0);
}
static void
fake_freeaddrinfo(struct addrinfo *ai)
{
free(ai->ai_addr);
}
#endif
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
/* wrapper for setting the base from the http server */
#define EVHTTP_BASE_SET(x, y) do { \
if ((x)->base != NULL) event_base_set((x)->base, y); \
} while (0)
extern int debug;
static int socket_connect(int fd, const char *address, unsigned short port);
static int bind_socket_ai(struct addrinfo *, int reuse);
static int bind_socket(const char *, u_short, int reuse);
static void name_from_addr(struct sockaddr *, socklen_t, char **, char **);
static int evhttp_associate_new_request_with_connection(
struct evhttp_connection *evcon);
static void evhttp_connection_start_detectclose(
struct evhttp_connection *evcon);
static void evhttp_connection_stop_detectclose(
struct evhttp_connection *evcon);
static void evhttp_request_dispatch(struct evhttp_connection* evcon);
static void evhttp_read_firstline(struct evhttp_connection *evcon,
struct evhttp_request *req);
static void evhttp_read_header(struct evhttp_connection *evcon,
struct evhttp_request *req);
static int evhttp_add_header_internal(struct evkeyvalq *headers,
const char *key, const char *value);
static int evhttp_decode_uri_internal(const char *uri, size_t length,
char *ret, int always_decode_plus);
void evhttp_read(int, short, void *);
void evhttp_write(int, short, void *);
#ifndef HAVE_STRSEP
/* strsep replacement for platforms that lack it. Only works if
* del is one character long. */
static char *
strsep(char **s, const char *del)
{
char *d, *tok;
assert(strlen(del) == 1);
if (!s || !*s)
return NULL;
tok = *s;
d = strstr(tok, del);
if (d) {
*d = '\0';
*s = d + 1;
} else
*s = NULL;
return tok;
}
#endif
static const char *
html_replace(char ch, char *buf)
{
switch (ch) {
case '<':
return "<";
case '>':
return ">";
case '"':
return """;
case '\'':
return "'";
case '&':
return "&";
default:
break;
}
/* Echo the character back */
buf[0] = ch;
buf[1] = '\0';
return buf;
}
/*
* Replaces <, >, ", ' and & with <, >, ",
* ' and & correspondingly.
*
* The returned string needs to be freed by the caller.
*/
char *
evhttp_htmlescape(const char *html)
{
int i, new_size = 0, old_size = strlen(html);
char *escaped_html, *p;
char scratch_space[2];
for (i = 0; i < old_size; ++i)
new_size += strlen(html_replace(html[i], scratch_space));
p = escaped_html = malloc(new_size + 1);
if (escaped_html == NULL)
event_err(1, "%s: malloc(%d)", __func__, new_size + 1);
for (i = 0; i < old_size; ++i) {
const char *replaced = html_replace(html[i], scratch_space);
/* this is length checked */
strcpy(p, replaced);
p += strlen(replaced);
}
*p = '\0';
return (escaped_html);
}
static const char *
evhttp_method(enum evhttp_cmd_type type)
{
const char *method;
switch (type) {
case EVHTTP_REQ_GET:
method = "GET";
break;
case EVHTTP_REQ_POST:
method = "POST";
break;
case EVHTTP_REQ_HEAD:
method = "HEAD";
break;
default:
method = NULL;
break;
}
return (method);
}
static void
evhttp_add_event(struct event *ev, int timeout, int default_timeout)
{
if (timeout != 0) {
struct timeval tv;
evutil_timerclear(&tv);
tv.tv_sec = timeout != -1 ? timeout : default_timeout;
event_add(ev, &tv);
} else {
event_add(ev, NULL);
}
}
void
evhttp_write_buffer(struct evhttp_connection *evcon,
void (*cb)(struct evhttp_connection *, void *), void *arg)
{
event_debug(("%s: preparing to write buffer\n", __func__));
/* Set call back */
evcon->cb = cb;
evcon->cb_arg = arg;
/* check if the event is already pending */
if (event_pending(&evcon->ev, EV_WRITE|EV_TIMEOUT, NULL))
event_del(&evcon->ev);
event_set(&evcon->ev, evcon->fd, EV_WRITE, evhttp_write, evcon);
EVHTTP_BASE_SET(evcon, &evcon->ev);
evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_WRITE_TIMEOUT);
}
static int
evhttp_connected(struct evhttp_connection *evcon)
{
switch (evcon->state) {
case EVCON_DISCONNECTED:
case EVCON_CONNECTING:
return (0);
case EVCON_IDLE:
case EVCON_READING_FIRSTLINE:
case EVCON_READING_HEADERS:
case EVCON_READING_BODY:
case EVCON_READING_TRAILER:
case EVCON_WRITING:
default:
return (1);
}
}
/*
* Create the headers needed for an HTTP request
*/
static void
evhttp_make_header_request(struct evhttp_connection *evcon,
struct evhttp_request *req)
{
const char *method;
evhttp_remove_header(req->output_headers, "Proxy-Connection");
/* Generate request line */
method = evhttp_method(req->type);
evbuffer_add_printf(evcon->output_buffer, "%s %s HTTP/%d.%d\r\n",
method, req->uri, req->major, req->minor);
/* Add the content length on a post request if missing */
if (req->type == EVHTTP_REQ_POST &&
evhttp_find_header(req->output_headers, "Content-Length") == NULL){
char size[22];
evutil_snprintf(size, sizeof(size), "%ld",
(long)EVBUFFER_LENGTH(req->output_buffer));
evhttp_add_header(req->output_headers, "Content-Length", size);
}
}
static int
evhttp_is_connection_close(int flags, struct evkeyvalq* headers)
{
if (flags & EVHTTP_PROXY_REQUEST) {
/* proxy connection */
const char *connection = evhttp_find_header(headers, "Proxy-Connection");
return (connection == NULL || strcasecmp(connection, "keep-alive") != 0);
} else {
const char *connection = evhttp_find_header(headers, "Connection");
return (connection != NULL && strcasecmp(connection, "close") == 0);
}
}
static int
evhttp_is_connection_keepalive(struct evkeyvalq* headers)
{
const char *connection = evhttp_find_header(headers, "Connection");
return (connection != NULL
&& strncasecmp(connection, "keep-alive", 10) == 0);
}
static void
evhttp_maybe_add_date_header(struct evkeyvalq *headers)
{
if (evhttp_find_header(headers, "Date") == NULL) {
char date[50];
#ifndef WIN32
struct tm cur;
#endif
struct tm *cur_p;
time_t t = time(NULL);
#ifdef WIN32
cur_p = gmtime(&t);
#else
gmtime_r(&t, &cur);
cur_p = &cur;
#endif
if (strftime(date, sizeof(date),
"%a, %d %b %Y %H:%M:%S GMT", cur_p) != 0) {
evhttp_add_header(headers, "Date", date);
}
}
}
static void
evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
long content_length)
{
if (evhttp_find_header(headers, "Transfer-Encoding") == NULL &&
evhttp_find_header(headers, "Content-Length") == NULL) {
char len[22];
evutil_snprintf(len, sizeof(len), "%ld", content_length);
evhttp_add_header(headers, "Content-Length", len);
}
}
/*
* Create the headers needed for an HTTP reply
*/
static void
evhttp_make_header_response(struct evhttp_connection *evcon,
struct evhttp_request *req)
{
int is_keepalive = evhttp_is_connection_keepalive(req->input_headers);
evbuffer_add_printf(evcon->output_buffer, "HTTP/%d.%d %d %s\r\n",
req->major, req->minor, req->response_code,
req->response_code_line);
if (req->major == 1) {
if (req->minor == 1)
evhttp_maybe_add_date_header(req->output_headers);
/*
* if the protocol is 1.0; and the connection was keep-alive
* we need to add a keep-alive header, too.
*/
if (req->minor == 0 && is_keepalive)
evhttp_add_header(req->output_headers,
"Connection", "keep-alive");
if (req->minor == 1 || is_keepalive) {
/*
* we need to add the content length if the
* user did not give it, this is required for
* persistent connections to work.
*/
evhttp_maybe_add_content_length_header(
req->output_headers,
(long)EVBUFFER_LENGTH(req->output_buffer));
}
}
/* Potentially add headers for unidentified content. */
if (EVBUFFER_LENGTH(req->output_buffer)) {
if (evhttp_find_header(req->output_headers,
"Content-Type") == NULL) {
evhttp_add_header(req->output_headers,
"Content-Type", "text/html; charset=ISO-8859-1");
}
}
/* if the request asked for a close, we send a close, too */
if (evhttp_is_connection_close(req->flags, req->input_headers)) {
evhttp_remove_header(req->output_headers, "Connection");
if (!(req->flags & EVHTTP_PROXY_REQUEST))
evhttp_add_header(req->output_headers, "Connection", "close");
evhttp_remove_header(req->output_headers, "Proxy-Connection");
}
}
void
evhttp_make_header(struct evhttp_connection *evcon, struct evhttp_request *req)
{
struct evkeyval *header;
/*
* Depending if this is a HTTP request or response, we might need to
* add some new headers or remove existing headers.
*/
if (req->kind == EVHTTP_REQUEST) {
evhttp_make_header_request(evcon, req);
} else {
evhttp_make_header_response(evcon, req);
}
TAILQ_FOREACH(header, req->output_headers, next) {
evbuffer_add_printf(evcon->output_buffer, "%s: %s\r\n",
header->key, header->value);
}
evbuffer_add(evcon->output_buffer, "\r\n", 2);
if (EVBUFFER_LENGTH(req->output_buffer) > 0) {
/*
* For a request, we add the POST data, for a reply, this
* is the regular data.
*/
evbuffer_add_buffer(evcon->output_buffer, req->output_buffer);
}
}
/* Separated host, port and file from URI */
int
evhttp_hostportfile(char *url, char **phost, u_short *pport, char **pfile)
{
/* XXX not threadsafe. */
static char host[1024];
static char file[1024];
char *p;
const char *p2;
int len;
u_short port;
len = strlen(HTTP_PREFIX);
if (strncasecmp(url, HTTP_PREFIX, len))
return (-1);
url += len;
/* We might overrun */
if (strlcpy(host, url, sizeof (host)) >= sizeof(host))
return (-1);
p = strchr(host, '/');
if (p != NULL) {
*p = '\0';
p2 = p + 1;
} else
p2 = NULL;
if (pfile != NULL) {
/* Generate request file */
if (p2 == NULL)
p2 = "";
evutil_snprintf(file, sizeof(file), "/%s", p2);
}
p = strchr(host, ':');
if (p != NULL) {
*p = '\0';
port = atoi(p + 1);
if (port == 0)
return (-1);
} else
port = HTTP_DEFAULTPORT;
if (phost != NULL)
*phost = host;
if (pport != NULL)
*pport = port;
if (pfile != NULL)
*pfile = file;
return (0);
}
static int
evhttp_connection_incoming_fail(struct evhttp_request *req,
enum evhttp_connection_error error)
{
switch (error) {
case EVCON_HTTP_TIMEOUT:
case EVCON_HTTP_EOF:
/*
* these are cases in which we probably should just
* close the connection and not send a reply. this
* case may happen when a browser keeps a persistent
* connection open and we timeout on the read. when
* the request is still being used for sending, we
* need to disassociated it from the connection here.
*/
if (!req->userdone) {
/* remove it so that it will not be freed */
TAILQ_REMOVE(&req->evcon->requests, req, next);
/* indicate that this request no longer has a
* connection object
*/
req->evcon = NULL;
}
return (-1);
case EVCON_HTTP_INVALID_HEADER:
default: /* xxx: probably should just error on default */
/* the callback looks at the uri to determine errors */
if (req->uri) {
free(req->uri);
req->uri = NULL;
}
/*
* the callback needs to send a reply, once the reply has
* been send, the connection should get freed.
*/
(*req->cb)(req, req->cb_arg);
}
return (0);
}
void
evhttp_connection_fail(struct evhttp_connection *evcon,
enum evhttp_connection_error error)
{
struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
void (*cb)(struct evhttp_request *, void *);
void *cb_arg;
assert(req != NULL);
if (evcon->flags & EVHTTP_CON_INCOMING) {
/*
* for incoming requests, there are two different
* failure cases. it's either a network level error
* or an http layer error. for problems on the network
* layer like timeouts we just drop the connections.
* For HTTP problems, we might have to send back a
* reply before the connection can be freed.
*/
if (evhttp_connection_incoming_fail(req, error) == -1)
evhttp_connection_free(evcon);
return;
}
/* save the callback for later; the cb might free our object */
cb = req->cb;
cb_arg = req->cb_arg;
/* do not fail all requests; the next request is going to get
* send over a new connection. when a user cancels a request,
* all other pending requests should be processed as normal
*/
TAILQ_REMOVE(&evcon->requests, req, next);
evhttp_request_free(req);
/* reset the connection */
evhttp_connection_reset(evcon);
/* We are trying the next request that was queued on us */
if (TAILQ_FIRST(&evcon->requests) != NULL)
evhttp_connection_connect(evcon);
/* inform the user */
if (cb != NULL)
(*cb)(NULL, cb_arg);
}
void
evhttp_write(int fd, short what, void *arg)
{
struct evhttp_connection *evcon = arg;
int n;
if (what == EV_TIMEOUT) {
evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
return;
}
n = evbuffer_write(evcon->output_buffer, fd);
if (n == -1) {
event_debug(("%s: evbuffer_write", __func__));
evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
return;
}
if (n == 0) {
event_debug(("%s: write nothing", __func__));
evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
return;
}
if (EVBUFFER_LENGTH(evcon->output_buffer) != 0) {
evhttp_add_event(&evcon->ev,
evcon->timeout, HTTP_WRITE_TIMEOUT);
return;
}
/* Activate our call back */
if (evcon->cb != NULL)
(*evcon->cb)(evcon, evcon->cb_arg);
}
/**
* Advance the connection state.
* - If this is an outgoing connection, we've just processed the response;
* idle or close the connection.
* - If this is an incoming connection, we've just processed the request;
* respond.
*/
static void
evhttp_connection_done(struct evhttp_connection *evcon)
{
struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
int con_outgoing = evcon->flags & EVHTTP_CON_OUTGOING;
if (con_outgoing) {
/* idle or close the connection */
int need_close;
TAILQ_REMOVE(&evcon->requests, req, next);
req->evcon = NULL;
evcon->state = EVCON_IDLE;
need_close =
evhttp_is_connection_close(req->flags, req->input_headers)||
evhttp_is_connection_close(req->flags, req->output_headers);
/* check if we got asked to close the connection */
if (need_close)
evhttp_connection_reset(evcon);
if (TAILQ_FIRST(&evcon->requests) != NULL) {
/*
* We have more requests; reset the connection
* and deal with the next request.
*/
if (!evhttp_connected(evcon))
evhttp_connection_connect(evcon);
else
evhttp_request_dispatch(evcon);
} else if (!need_close) {
/*
* The connection is going to be persistent, but we
* need to detect if the other side closes it.
*/
evhttp_connection_start_detectclose(evcon);
}
} else if (evcon->state != EVCON_DISCONNECTED) {
/*
* incoming connection - we need to leave the request on the
* connection so that we can reply to it.
*/
evcon->state = EVCON_WRITING;
}
/* notify the user of the request */
(*req->cb)(req, req->cb_arg);
/* if this was an outgoing request, we own and it's done. so free it */
if (con_outgoing) {
evhttp_request_free(req);
}
}
/*
* Handles reading from a chunked request.
* return ALL_DATA_READ:
* all data has been read
* return MORE_DATA_EXPECTED:
* more data is expected
* return DATA_CORRUPTED:
* data is corrupted
* return REQUEST_CANCLED:
* request was canceled by the user calling evhttp_cancel_request
*/
static enum message_read_status
evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
{
int len;
while ((len = EVBUFFER_LENGTH(buf)) > 0) {
if (req->ntoread < 0) {
/* Read chunk size */
ev_int64_t ntoread;
char *p = evbuffer_readline(buf);
char *endp;
int error;
if (p == NULL)
break;
/* the last chunk is on a new line? */
if (strlen(p) == 0) {
free(p);
continue;
}
ntoread = evutil_strtoll(p, &endp, 16);
error = (*p == '\0' ||
(*endp != '\0' && *endp != ' ') ||
ntoread < 0);
free(p);
if (error) {
/* could not get chunk size */
return (DATA_CORRUPTED);
}
req->ntoread = ntoread;
if (req->ntoread == 0) {
/* Last chunk */
return (ALL_DATA_READ);
}
continue;
}
/* don't have enough to complete a chunk; wait for more */
if (len < req->ntoread)
return (MORE_DATA_EXPECTED);
/* Completed chunk */
evbuffer_add(req->input_buffer,
EVBUFFER_DATA(buf), (size_t)req->ntoread);
evbuffer_drain(buf, (size_t)req->ntoread);
req->ntoread = -1;
if (req->chunk_cb != NULL) {
(*req->chunk_cb)(req, req->cb_arg);
evbuffer_drain(req->input_buffer,
EVBUFFER_LENGTH(req->input_buffer));
}
}
return (MORE_DATA_EXPECTED);
}
static void
evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
{
struct evbuffer *buf = evcon->input_buffer;
switch (evhttp_parse_headers(req, buf)) {
case DATA_CORRUPTED:
evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
break;
case ALL_DATA_READ:
event_del(&evcon->ev);
evhttp_connection_done(evcon);
break;
case MORE_DATA_EXPECTED:
default:
evhttp_add_event(&evcon->ev, evcon->timeout,
HTTP_READ_TIMEOUT);
break;
}
}
static void
evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
{
struct evbuffer *buf = evcon->input_buffer;
if (req->chunked) {
switch (evhttp_handle_chunked_read(req, buf)) {
case ALL_DATA_READ:
/* finished last chunk */
evcon->state = EVCON_READING_TRAILER;
evhttp_read_trailer(evcon, req);
return;
case DATA_CORRUPTED:
/* corrupted data */
evhttp_connection_fail(evcon,
EVCON_HTTP_INVALID_HEADER);
return;
case REQUEST_CANCELED:
/* request canceled */
evhttp_request_free(req);
return;
case MORE_DATA_EXPECTED:
default:
break;
}
} else if (req->ntoread < 0) {
/* Read until connection close. */
evbuffer_add_buffer(req->input_buffer, buf);
} else if (EVBUFFER_LENGTH(buf) >= req->ntoread) {
/* Completed content length */
evbuffer_add(req->input_buffer, EVBUFFER_DATA(buf),
(size_t)req->ntoread);
evbuffer_drain(buf, (size_t)req->ntoread);
req->ntoread = 0;
evhttp_connection_done(evcon);
return;
}
/* Read more! */
event_set(&evcon->ev, evcon->fd, EV_READ, evhttp_read, evcon);
EVHTTP_BASE_SET(evcon, &evcon->ev);
evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_READ_TIMEOUT);
}
/*
* Reads data into a buffer structure until no more data
* can be read on the file descriptor or we have read all
* the data that we wanted to read.
* Execute callback when done.
*/
void
evhttp_read(int fd, short what, void *arg)
{
struct evhttp_connection *evcon = arg;
struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
struct evbuffer *buf = evcon->input_buffer;
int n, len;
if (what == EV_TIMEOUT) {
evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
return;
}
n = evbuffer_read(buf, fd, -1);
len = EVBUFFER_LENGTH(buf);
event_debug(("%s: got %d on %d\n", __func__, n, fd));
if (n == -1) {
if (errno != EINTR && errno != EAGAIN) {
event_debug(("%s: evbuffer_read", __func__));
evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
} else {
evhttp_add_event(&evcon->ev, evcon->timeout,
HTTP_READ_TIMEOUT);
}
return;
} else if (n == 0) {
/* Connection closed */
evcon->state = EVCON_DISCONNECTED;
evhttp_connection_done(evcon);
return;
}
switch (evcon->state) {
case EVCON_READING_FIRSTLINE:
evhttp_read_firstline(evcon, req);
break;
case EVCON_READING_HEADERS:
evhttp_read_header(evcon, req);
break;
case EVCON_READING_BODY:
evhttp_read_body(evcon, req);
break;
case EVCON_READING_TRAILER:
evhttp_read_trailer(evcon, req);
break;
case EVCON_DISCONNECTED:
case EVCON_CONNECTING:
case EVCON_IDLE:
case EVCON_WRITING:
default:
event_errx(1, "%s: illegal connection state %d",
__func__, evcon->state);
}
}
static void
evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
{
/* This is after writing the request to the server */
struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
assert(req != NULL);
assert(evcon->state == EVCON_WRITING);
/* We are done writing our header and are now expecting the response */
req->kind = EVHTTP_RESPONSE;
evhttp_start_read(evcon);
}
/*
* Clean up a connection object
*/