-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.c
5423 lines (4664 loc) · 137 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-2012 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 "event2/event-config.h"
#include "evconfig-private.h"
#ifdef EVENT__HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef EVENT__HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_IOCCOM_H
#include <sys/ioccom.h>
#endif
#ifdef EVENT__HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#ifdef EVENT__HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef EVENT__HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifndef _WIN32
#include <sys/socket.h>
#include <sys/stat.h>
#else /* _WIN32 */
#include <winsock2.h>
#include <ws2tcpip.h>
#endif /* _WIN32 */
#ifdef EVENT__HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#ifdef EVENT__HAVE_AFUNIX_H
#include <afunix.h>
#endif
#include <sys/queue.h>
#ifdef EVENT__HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef EVENT__HAVE_ARPA_INET_H
#include <arpa/inet.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 /* !_WIN32 */
#include <signal.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/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"
#include "bufferevent-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
#define REQ_VERSION_BEFORE(req, major_v, minor_v) \
((req)->major < (major_v) || \
((req)->major == (major_v) && (req)->minor < (minor_v)))
#define REQ_VERSION_ATLEAST(req, major_v, minor_v) \
((req)->major > (major_v) || \
((req)->major == (major_v) && (req)->minor >= (minor_v)))
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
extern int debug;
static evutil_socket_t create_bind_socket_nonblock(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 struct evhttp_uri *evhttp_uri_parse_authority(char *source_uri, unsigned flags);
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 const char *evhttp_response_phrase_internal(int code);
static void evhttp_get_request(struct evhttp *, evutil_socket_t, struct sockaddr *, ev_socklen_t);
static void evhttp_write_buffer(struct evhttp_connection *,
void (*)(struct evhttp_connection *, void *), void *);
static void evhttp_make_header(struct evhttp_connection *, struct evhttp_request *);
static int evhttp_method_may_have_body_(struct evhttp_connection *, enum evhttp_cmd_type);
/* 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_find_vhost(struct evhttp *http, struct evhttp **outhttp, const char *hostname);
static const char *evhttp_method_(struct evhttp_connection *evcon,
enum evhttp_cmd_type type, ev_uint16_t *flags);
#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 size_t
html_replace(const char ch, const char **escaped)
{
switch (ch) {
case '<':
*escaped = "<";
return 4;
case '>':
*escaped = ">";
return 4;
case '"':
*escaped = """;
return 6;
case '\'':
*escaped = "'";
return 6;
case '&':
*escaped = "&";
return 5;
default:
break;
}
return 1;
}
/*
* Replaces <, >, ", ' and & with <, >, ",
* ' and & correspondingly.
*
* The returned string needs to be freed by the caller.
*/
char *
evhttp_htmlescape(const char *html)
{
size_t i;
size_t new_size = 0, old_size = 0;
char *escaped_html, *p;
if (html == NULL)
return (NULL);
old_size = strlen(html);
for (i = 0; i < old_size; ++i) {
const char *replaced = NULL;
const size_t replace_size = html_replace(html[i], &replaced);
if (replace_size > EV_SIZE_MAX - new_size) {
event_warn("%s: html_replace overflow", __func__);
return (NULL);
}
new_size += replace_size;
}
if (new_size == EV_SIZE_MAX)
return (NULL);
p = escaped_html = mm_malloc(new_size + 1);
if (escaped_html == NULL) {
event_warn("%s: malloc(%lu)", __func__,
(unsigned long)(new_size + 1));
return (NULL);
}
for (i = 0; i < old_size; ++i) {
const char *replaced = &html[i];
const size_t len = html_replace(html[i], &replaced);
memcpy(p, replaced, len);
p += len;
}
*p = '\0';
return (escaped_html);
}
/** Given an evhttp_cmd_type, returns a constant string containing the
* equivalent HTTP command, or NULL if the evhttp_cmd_type is
* unrecognized. */
static const char *
evhttp_method_(struct evhttp_connection *evcon,
enum evhttp_cmd_type type, ev_uint16_t *flags)
{
struct evhttp_ext_method ext_method;
const char *method = NULL;
ev_uint16_t tmp_flags = EVHTTP_METHOD_HAS_BODY;
switch (type) {
case EVHTTP_REQ_GET:
method = "GET";
break;
case EVHTTP_REQ_POST:
method = "POST";
break;
case EVHTTP_REQ_HEAD:
method = "HEAD";
tmp_flags &= ~EVHTTP_METHOD_HAS_BODY;
break;
case EVHTTP_REQ_PUT:
method = "PUT";
break;
case EVHTTP_REQ_DELETE:
method = "DELETE";
break;
case EVHTTP_REQ_OPTIONS:
method = "OPTIONS";
break;
case EVHTTP_REQ_TRACE:
method = "TRACE";
tmp_flags &= ~EVHTTP_METHOD_HAS_BODY;
break;
case EVHTTP_REQ_CONNECT:
method = "CONNECT";
break;
case EVHTTP_REQ_PATCH:
method = "PATCH";
break;
case EVHTTP_REQ_PROPFIND:
method = "PROPFIND";
break;
case EVHTTP_REQ_PROPPATCH:
method = "PROPPATCH";
break;
case EVHTTP_REQ_MKCOL:
method = "MKCOL";
break;
case EVHTTP_REQ_LOCK:
method = "LOCK";
break;
case EVHTTP_REQ_UNLOCK:
method = "UNLOCK";
break;
case EVHTTP_REQ_COPY:
method = "COPY";
break;
case EVHTTP_REQ_MOVE:
method = "MOVE";
break;
default:
/* setup the structure to allow for the cmp.
*
* if the cmp function is set, it has the ability to
* modify method and flags. Other fields will be
* ignored.
*
* NOTE: the flags returned are OR'd with the current
* flags.
*/
tmp_flags = 0;
ext_method.method = NULL;
ext_method.type = type;
ext_method.flags = tmp_flags;
if (evcon->ext_method_cmp != NULL &&
evcon->ext_method_cmp(&ext_method) == 0) {
if (ext_method.type != type) {
event_debug(("%s: callback modified type from %u to %u, not allowed",
__func__, type, ext_method.type));
return NULL;
}
method = ext_method.method;
tmp_flags |= ext_method.flags;
}
break;
}
event_debug(("%s: type=%04x => '%s' flags=%04x",
__func__, (int)type, method, tmp_flags));
if (flags)
*flags = tmp_flags;
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_CONNECT &&
req->type != EVHTTP_REQ_HEAD);
}
/** Helper: called after we've added some data to an evcon's bufferevent's
* output buffer. Sets the evconn's writing-is-done callback, and puts
* the bufferevent into writing mode.
*/
static 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;
/* Disable the read callback: we don't actually care about data;
* we only care about close detection. (We don't disable reading --
* EV_READ, since we *do* want to learn about any close events.) */
bufferevent_setcb(evcon->bufev,
NULL, /*read*/
evhttp_write_cb,
evhttp_error_cb,
evcon);
bufferevent_enable(evcon->bufev, EV_READ|EV_WRITE);
}
static void
evhttp_send_continue_done(struct evhttp_connection *evcon, void *arg)
{
bufferevent_disable(evcon->bufev, EV_WRITE);
}
static void
evhttp_send_continue(struct evhttp_connection *evcon,
struct evhttp_request *req)
{
bufferevent_enable(evcon->bufev, EV_WRITE);
evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
"HTTP/%d.%d 100 Continue\r\n\r\n",
req->major, req->minor);
evcon->cb = evhttp_send_continue_done;
evcon->cb_arg = NULL;
bufferevent_setcb(evcon->bufev,
evhttp_read_cb,
evhttp_write_cb,
evhttp_error_cb,
evcon);
}
/** Helper: returns true iff evconn is in any connected state. */
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 outgoing HTTP request, adds them to
* the request's header list, and writes the request line to the
* connection's output buffer.
*/
static void
evhttp_make_header_request(struct evhttp_connection *evcon,
struct evhttp_request *req)
{
const char *method;
ev_uint16_t flags;
evhttp_remove_header(req->output_headers, "Proxy-Connection");
/* Generate request line */
if (!(method = evhttp_method_(evcon, req->type, &flags))) {
method = "NULL";
}
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 request if missing
* Always add it for POST and PUT requests as clients expect it */
if ((flags & EVHTTP_METHOD_HAS_BODY) &&
(evbuffer_get_length(req->output_buffer) > 0 ||
req->type == EVHTTP_REQ_POST || req->type == EVHTTP_REQ_PUT) &&
evhttp_find_header(req->output_headers, "Content-Length") == NULL) {
char size[22];
evutil_snprintf(size, sizeof(size), EV_SIZE_FMT,
EV_SIZE_ARG(evbuffer_get_length(req->output_buffer)));
evhttp_add_header(req->output_headers, "Content-Length", size);
}
}
/** Return true if the list of headers in 'headers', intepreted with respect
* to flags, means that we should send a "connection: close" when the request
* is done. */
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_request_connection_close(struct evhttp_request *req)
{
if (req->type == EVHTTP_REQ_CONNECT)
return 0;
return
evhttp_is_connection_close(req->flags, req->input_headers) ||
evhttp_is_connection_close(req->flags, req->output_headers);
}
/* Return true iff 'headers' contains 'Connection: keep-alive' */
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);
}
/* Add a correct "Date" header to headers, unless it already has one. */
static void
evhttp_maybe_add_date_header(struct evkeyvalq *headers)
{
if (evhttp_find_header(headers, "Date") == NULL) {
char date[50];
if (sizeof(date) - evutil_date_rfc1123(date, sizeof(date), NULL) > 0) {
evhttp_add_header(headers, "Date", date);
}
}
}
/* Add a "Content-Length" header with value 'content_length' to headers,
* unless it already has a content-length or transfer-encoding header. */
static void
evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
size_t 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), EV_SIZE_FMT,
EV_SIZE_ARG(content_length));
evhttp_add_header(headers, "Content-Length", len);
}
}
/*
* Create the headers needed for an HTTP reply in req->output_headers,
* and write the first HTTP response for req line to evcon.
*/
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,
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
&& evcon->http_server->default_content_type) {
evhttp_add_header(req->output_headers,
"Content-Type",
evcon->http_server->default_content_type);
}
}
/* 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");
}
}
enum expect { NO, CONTINUE, OTHER };
static enum expect evhttp_have_expect(struct evhttp_request *req, int input)
{
const char *expect;
struct evkeyvalq *h = input ? req->input_headers : req->output_headers;
if (!(req->kind == EVHTTP_REQUEST) || !REQ_VERSION_ATLEAST(req, 1, 1))
return NO;
expect = evhttp_find_header(h, "Expect");
if (!expect)
return NO;
return !evutil_ascii_strcasecmp(expect, "100-continue") ? CONTINUE : OTHER;
}
/** Generate all headers appropriate for sending the http request in req (or
* the response, if we're sending a response), and write them to evcon's
* bufferevent. Also writes all data from req->output_buffer */
static 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 (evhttp_have_expect(req, 0) != CONTINUE &&
evbuffer_get_length(req->output_buffer)) {
/*
* 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_request_error error)
{
switch (error) {
case EVREQ_HTTP_DATA_TOO_LONG:
req->response_code = HTTP_ENTITYTOOLARGE;
break;
default:
req->response_code = HTTP_BADREQUEST;
}
switch (error) {
case EVREQ_HTTP_TIMEOUT:
case EVREQ_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 EVREQ_HTTP_INVALID_HEADER:
case EVREQ_HTTP_BUFFER_ERROR:
case EVREQ_HTTP_REQUEST_CANCEL:
case EVREQ_HTTP_DATA_TOO_LONG:
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;
}
if (req->uri_elems) {
evhttp_uri_free(req->uri_elems);
req->uri_elems = 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);
}
/* Free connection ownership of which can be acquired by user using
* evhttp_request_own(). */
static inline void
evhttp_request_free_auto(struct evhttp_request *req)
{
if (!(req->flags & EVHTTP_USER_OWNED))
evhttp_request_free(req);
}
static void
evhttp_request_free_(struct evhttp_connection *evcon, struct evhttp_request *req)
{
TAILQ_REMOVE(&evcon->requests, req, next);
evhttp_request_free_auto(req);
}
static void
evhttp_set_timeout_tv_(struct timeval *tv, const struct timeval *timeout, int def)
{
if (timeout == NULL && def != -1) {
tv->tv_sec = def;
tv->tv_usec = 0;
return;
}
if (timeout) {
*tv = *timeout;
} else {
evutil_timerclear(tv);
}
}
static void
evhttp_set_timeout_(struct timeval *tv, int timeout, int def)
{
if (timeout == -1) {
timeout = def;
}
if (timeout == -1) {
evutil_timerclear(tv);
} else {
struct timeval timeout_tv;
timeout_tv.tv_sec = timeout;
timeout_tv.tv_usec = 0;
*tv = timeout_tv;
}
}
/* Called when evcon has experienced a (non-recoverable? -NM) error, as
* given in error. If it's an outgoing connection, reset the connection,
* retry any pending requests, and inform the user. If it's incoming,
* delegates to evhttp_connection_incoming_fail(). */
void
evhttp_connection_fail_(struct evhttp_connection *evcon,
enum evhttp_request_error error)
{
const int errsave = EVUTIL_SOCKET_ERROR();
struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
void (*cb)(struct evhttp_request *, void *);
void *cb_arg;
void (*error_cb)(enum evhttp_request_error, void *);
void *error_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;
}
error_cb = req->error_cb;
error_cb_arg = req->cb_arg;
/* when the request was canceled, the callback is not executed */
if (error != EVREQ_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
*/
evhttp_request_free_(evcon, req);
/* reset the connection */
evhttp_connection_reset_(evcon, 1);
/* We are trying the next request that was queued on us */
if (TAILQ_FIRST(&evcon->requests) != NULL)
evhttp_connection_connect_(evcon);
else
if ((evcon->flags & EVHTTP_CON_OUTGOING) &&
(evcon->flags & EVHTTP_CON_AUTOFREE)) {
evhttp_connection_free(evcon);
}
/* The call to evhttp_connection_reset_ overwrote errno.
* Let's restore the original errno, so that the user's
* callback can have a better idea of what the error was.
*/
EVUTIL_SET_SOCKET_ERROR(errsave);
/* inform the user */
if (error_cb != NULL)
error_cb(error, error_cb_arg);
if (cb != NULL)
(*cb)(NULL, cb_arg);
}
/* Bufferevent callback: invoked when any data has been written from an
* http connection's bufferevent */
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;
int free_evcon = 0;
if (con_outgoing) {
/* idle or close the connection */
int need_close = evhttp_is_request_connection_close(req);
TAILQ_REMOVE(&evcon->requests, req, next);
req->evcon = NULL;
evcon->state = EVCON_IDLE;
/* check if we got asked to close the connection */
if (need_close)
evhttp_connection_reset_(evcon, 1);
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->flags & EVHTTP_CON_AUTOFREE)) {
/*
* If we have no more requests that need completion
* and we're not waiting for the connection to close
*/
free_evcon = 1;
}
} 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. */
if (con_outgoing) {
evhttp_request_free_auto(req);
}
/* If this was the last request of an outgoing connection and we're
* not waiting to receive a connection close event and we want to
* automatically free the connection. We check to ensure our request
* list is empty one last time just in case our callback added a
* new request.
*/
if (free_evcon && TAILQ_FIRST(&evcon->requests) == NULL) {
evhttp_connection_free(evcon);
}
}
/*
* 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