forked from libevent/libevent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.c
3162 lines (2660 loc) · 75.4 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-2007 Niels Provos <[email protected]>
* Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
*
* 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 "event-config.h"
#define _REENTRANT
#ifdef _EVENT_HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef _EVENT_HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef _EVENT_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>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include <sys/queue.h>
#ifdef _EVENT_HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef _EVENT_HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef WIN32
#include <winsock2.h>
#endif
#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 _EVENT_HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _EVENT_HAVE_FCNTL_H
#include <fcntl.h>
#endif
#undef timeout_pending
#undef timeout_initialized
#include "strlcpy-internal.h"
#include "event2/http.h"
#include "event2/event.h"
#include "event2/buffer.h"
#include "event2/bufferevent.h"
#include "event2/bufferevent_compat.h"
#include "event2/http_struct.h"
#include "event2/http_compat.h"
#include "event2/util.h"
#include "event2/listener.h"
#include "log-internal.h"
#include "util-internal.h"
#include "http-internal.h"
#include "mm-internal.h"
#ifndef _EVENT_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 MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
extern int debug;
static evutil_socket_t bind_socket_ai(struct evutil_addrinfo *, int reuse);
static evutil_socket_t bind_socket(const char *, ev_uint16_t, int reuse);
static void name_from_addr(struct sockaddr *, ev_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);
/* callbacks for bufferevent */
static void evhttp_read_cb(struct bufferevent *, void *);
static void evhttp_write_cb(struct bufferevent *, void *);
static void evhttp_error_cb(struct bufferevent *bufev, short what, void *arg);
static int evhttp_decode_uri_internal(const char *uri, size_t length,
char *ret, int always_decode_plus);
#ifndef _EVENT_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;
EVUTIL_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 = mm_malloc(new_size + 1);
if (escaped_html == NULL) {
event_warn("%s: malloc(%d)", __func__, new_size + 1);
return (NULL);
}
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;
case EVHTTP_REQ_PUT:
method = "PUT";
break;
case EVHTTP_REQ_DELETE:
method = "DELETE";
break;
default:
method = NULL;
break;
}
return (method);
}
/**
* Determines if a response should have a body.
* Follows the rules in RFC 2616 section 4.3.
* @return 1 if the response MUST have a body; 0 if the response MUST NOT have
* a body.
*/
static int
evhttp_response_needs_body(struct evhttp_request *req)
{
return (req->response_code != HTTP_NOCONTENT &&
req->response_code != HTTP_NOTMODIFIED &&
(req->response_code < 100 || req->response_code >= 200) &&
req->type != EVHTTP_REQ_HEAD);
}
static int
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;
return event_add(ev, &tv);
} else {
return 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;
bufferevent_disable(evcon->bufev, EV_READ);
bufferevent_enable(evcon->bufev, EV_WRITE);
}
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(bufferevent_get_output(evcon->bufev),
"%s %s HTTP/%d.%d\r\n",
method, req->uri, req->major, req->minor);
/* Add the content length on a post or put request if missing */
if ((req->type == EVHTTP_REQ_POST || req->type == EVHTTP_REQ_PUT) &&
evhttp_find_header(req->output_headers, "Content-Length") == NULL){
char size[12];
evutil_snprintf(size, sizeof(size), "%ld",
(long)evbuffer_get_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 || evutil_ascii_strcasecmp(connection, "keep-alive") != 0);
} else {
const char *connection = evhttp_find_header(headers, "Connection");
return (connection != NULL && evutil_ascii_strcasecmp(connection, "close") == 0);
}
}
static int
evhttp_is_connection_keepalive(struct evkeyvalq* headers)
{
const char *connection = evhttp_find_header(headers, "Connection");
return (connection != NULL
&& evutil_ascii_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[12];
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(bufferevent_get_output(evcon->bufev),
"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) &&
evhttp_response_needs_body(req)) {
/*
* 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_get_length(req->output_buffer));
}
}
/* Potentially add headers for unidentified content. */
if (evhttp_response_needs_body(req)) {
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;
struct evbuffer *output = bufferevent_get_output(evcon->bufev);
/*
* 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(output, "%s: %s\r\n",
header->key, header->value);
}
evbuffer_add(output, "\r\n", 2);
if (evbuffer_get_length(req->output_buffer) > 0) {
/*
* For a request, we add the POST data, for a reply, this
* is the regular data.
*/
evbuffer_add_buffer(output, req->output_buffer);
}
}
void
evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
ev_ssize_t new_max_headers_size)
{
if (new_max_headers_size<0)
evcon->max_headers_size = EV_SIZE_MAX;
else
evcon->max_headers_size = new_max_headers_size;
}
void
evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
ev_ssize_t new_max_body_size)
{
if (new_max_body_size<0)
evcon->max_body_size = EV_UINT64_MAX;
else
evcon->max_body_size = new_max_body_size;
}
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:
case EVCON_HTTP_BUFFER_ERROR:
case EVCON_HTTP_REQUEST_CANCEL:
default: /* xxx: probably should just error on default */
/* the callback looks at the uri to determine errors */
if (req->uri) {
mm_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;
EVUTIL_ASSERT(req != NULL);
bufferevent_disable(evcon->bufev, EV_READ|EV_WRITE);
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;
}
/* when the request was canceled, the callback is not executed */
if (error != EVCON_HTTP_REQUEST_CANCEL) {
/* save the callback for later; the cb might free our object */
cb = req->cb;
cb_arg = req->cb_arg;
} else {
cb = NULL;
cb_arg = NULL;
}
/* 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);
}
static void
evhttp_write_cb(struct bufferevent *bufev, void *arg)
{
struct evhttp_connection *evcon = arg;
/* 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 {
/*
* 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.
* unless the callback specifically requested to own the request.
*/
if (con_outgoing && ((req->flags & EVHTTP_USER_OWNED) == 0)) {
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_CANCELED:
* request was canceled by the user calling evhttp_cancel_request
* return DATA_TOO_LONG:
* ran over the maximum limit
*/
static enum message_read_status
evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
{
int len;
while ((len = evbuffer_get_length(buf)) > 0) {
if (req->ntoread < 0) {
/* Read chunk size */
ev_int64_t ntoread;
char *p = evbuffer_readln(buf, NULL, EVBUFFER_EOL_CRLF);
char *endp;
int error;
if (p == NULL)
break;
/* the last chunk is on a new line? */
if (strlen(p) == 0) {
mm_free(p);
continue;
}
ntoread = evutil_strtoll(p, &endp, 16);
error = (*p == '\0' ||
(*endp != '\0' && *endp != ' ') ||
ntoread < 0);
mm_free(p);
if (error) {
/* could not get chunk size */
return (DATA_CORRUPTED);
}
if (req->body_size + (size_t)ntoread > req->evcon->max_body_size) {
/* failed body length test */
event_debug(("Request body is too long"));
return (DATA_TOO_LONG);
}
req->body_size += (size_t)ntoread;
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 */
/* XXXX fixme: what if req->ntoread is > SIZE_T_MAX? */
evbuffer_remove_buffer(buf, req->input_buffer, (size_t)req->ntoread);
req->ntoread = -1;
if (req->chunk_cb != NULL) {
req->flags |= EVHTTP_REQ_DEFER_FREE;
(*req->chunk_cb)(req, req->cb_arg);
evbuffer_drain(req->input_buffer,
evbuffer_get_length(req->input_buffer));
req->flags &= ~EVHTTP_REQ_DEFER_FREE;
if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
return (REQUEST_CANCELED);
}
}
}
return (MORE_DATA_EXPECTED);
}
static void
evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
{
struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
switch (evhttp_parse_headers(req, buf)) {
case DATA_CORRUPTED:
case DATA_TOO_LONG:
evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
break;
case ALL_DATA_READ:
bufferevent_disable(evcon->bufev, EV_READ);
evhttp_connection_done(evcon);
break;
case MORE_DATA_EXPECTED:
case REQUEST_CANCELED: /* ??? */
default:
bufferevent_enable(evcon->bufev, EV_READ);
break;
}
}
static void
evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
{
struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
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:
case DATA_TOO_LONG:/*separate error for this? XXX */
/* 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);
req->body_size += evbuffer_get_length(buf);
} else if (req->chunk_cb != NULL ||
evbuffer_get_length(buf) >= req->ntoread) {
/* We've postponed moving the data until now, but we're
* about to use it. */
req->ntoread -= evbuffer_get_length(buf);
req->body_size += evbuffer_get_length(buf);
evbuffer_add_buffer(req->input_buffer, buf);
}
if (req->body_size > req->evcon->max_body_size) {
/* failed body length test */
event_debug(("Request body is too long"));
evhttp_connection_fail(evcon,
EVCON_HTTP_INVALID_HEADER);
return;
}
if (evbuffer_get_length(req->input_buffer) > 0 && req->chunk_cb != NULL) {
req->flags |= EVHTTP_REQ_DEFER_FREE;
(*req->chunk_cb)(req, req->cb_arg);
req->flags &= ~EVHTTP_REQ_DEFER_FREE;
evbuffer_drain(req->input_buffer,
evbuffer_get_length(req->input_buffer));
if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
evhttp_request_free(req);
return;
}
}
if (req->ntoread == 0) {
bufferevent_disable(evcon->bufev, EV_READ);
/* Completed content length */
evhttp_connection_done(evcon);
return;
}
/* Read more! */
bufferevent_enable(evcon->bufev, EV_READ);
}
/*
* Gets called when more data becomes available
*/
static void
evhttp_read_cb(struct bufferevent *bufev, void *arg)
{
struct evhttp_connection *evcon = arg;
struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
switch (evcon->state) {
case EVCON_READING_FIRSTLINE:
evhttp_read_firstline(evcon, req);
/* note the request may have been freed in
* evhttp_read_body */
break;
case EVCON_READING_HEADERS:
evhttp_read_header(evcon, req);
/* note the request may have been freed in
* evhttp_read_body */
break;
case EVCON_READING_BODY:
evhttp_read_body(evcon, req);
/* note the request may have been freed in
* evhttp_read_body */
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);
EVUTIL_ASSERT(req != NULL);
EVUTIL_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
*/
void
evhttp_connection_free(struct evhttp_connection *evcon)
{
struct evhttp_request *req;
/* notify interested parties that this connection is going down */
if (evcon->fd != -1) {
if (evhttp_connected(evcon) && evcon->closecb != NULL)
(*evcon->closecb)(evcon, evcon->closecb_arg);
}
/* remove all requests that might be queued on this
* connection. for server connections, this should be empty.
* because it gets dequeued either in evhttp_connection_done or
* evhttp_connection_fail.
*/
while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
TAILQ_REMOVE(&evcon->requests, req, next);
evhttp_request_free(req);
}
if (evcon->http_server != NULL) {
struct evhttp *http = evcon->http_server;
TAILQ_REMOVE(&http->connections, evcon, next);
}
if (event_initialized(&evcon->retry_ev)) {
event_del(&evcon->retry_ev);
event_debug_unassign(&evcon->retry_ev);
}
if (evcon->bufev != NULL)
bufferevent_free(evcon->bufev);
if (evcon->fd != -1)
EVUTIL_CLOSESOCKET(evcon->fd);
if (evcon->bind_address != NULL)
mm_free(evcon->bind_address);
if (evcon->address != NULL)
mm_free(evcon->address);
mm_free(evcon);
}
void
evhttp_connection_set_local_address(struct evhttp_connection *evcon,
const char *address)
{
EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
if (evcon->bind_address)
mm_free(evcon->bind_address);
if ((evcon->bind_address = mm_strdup(address)) == NULL)
event_err(1, "%s: strdup", __func__);
}