-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.cpp
4448 lines (4407 loc) · 129 KB
/
server.cpp
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
#include "common.cpp"
using namespace ngtcp2;
struct Config
{
Address preferred_ipv4_addr;
Address preferred_ipv6_addr;
double tx_loss_prob;
double rx_loss_prob;
const char *ciphers;
const char *groups;
std::string htdocs;
const char *mime_types_file;
std::unordered_map<std::string, std::string> mime_types;
uint16_t port;
bool quiet;
ngtcp2_duration timeout;
bool show_secret;
bool validate_addr;
bool early_response;
bool verify_client;
std::string_view qlog_dir;
bool no_quic_dump;
bool no_http_dump;
uint64_t max_data;
uint64_t max_stream_data_bidi_local;
uint64_t max_stream_data_bidi_remote;
uint64_t max_stream_data_uni;
uint64_t max_streams_bidi;
uint64_t max_streams_uni;
uint64_t max_window;
uint64_t max_stream_window;
uint64_t max_dyn_length;
std::array<uint8_t, 32> static_secret;
std::string_view cc;
ngtcp2_duration initial_rtt;
size_t max_udp_payload_size;
bool send_trailers;
};
struct Buffer
{
Buffer(const uint8_t *data, size_t datalen);
explicit Buffer(size_t datalen);
size_t size() const { return tail - begin; }
size_t left() const { return buf.data() + buf.size() - tail; }
uint8_t *const wpos() { return tail; }
const uint8_t *rpos() const { return begin; }
void push(size_t len) { tail += len; }
void reset() { tail = begin; }
std::vector<uint8_t> buf;
uint8_t *begin;
uint8_t *tail;
};
struct HTTPHeader
{
HTTPHeader(const std::string_view &name, const std::string_view &value)
: name(name), value(value) {}
std::string_view name;
std::string_view value;
};
class Handler;
struct FileEntry;
struct Stream
{
Stream(int64_t stream_id, Handler *handler);
int start_response(nghttp3_conn *conn);
std::pair<FileEntry, int> open_file(const std::string &path);
void map_file(const FileEntry &fe);
int send_status_response(nghttp3_conn *conn, unsigned int status_code,
const std::vector<HTTPHeader> &extra_headers = {});
int send_redirect_response(nghttp3_conn *conn, unsigned int status_code,
const std::string_view &path);
int64_t find_dyn_length(const std::string_view &path);
void http_acked_stream_data(size_t datalen);
int64_t stream_id;
Handler *handler;
std::string uri;
std::string method;
std::string authority;
std::string status_resp_body;
uint8_t *data;
uint64_t datalen;
bool dynresp;
uint64_t dyndataleft;
uint64_t dynbuflen;
};
class Server;
struct Endpoint
{
Address addr;
ev_io rev;
Server *server;
int fd;
unsigned int ecn;
};
struct Crypto
{
std::deque<Buffer> data;
uint64_t acked_offset;
};
class Handler
{
public:
Handler(struct ev_loop *loop, SSL_CTX *ssl_ctx, Server *server,
const ngtcp2_cid *rcid);
~Handler();
int init(const Endpoint &ep, const sockaddr *sa, socklen_t salen,
const ngtcp2_cid *dcid, const ngtcp2_cid *scid,
const ngtcp2_cid *ocid, const uint8_t *token, size_t tokenlen,
uint32_t version);
int on_read(const Endpoint &ep, const sockaddr *sa, socklen_t salen,
const ngtcp2_pkt_info *pi, uint8_t *data, size_t datalen);
int on_write();
int write_streams();
int feed_data(const Endpoint &ep, const sockaddr *sa, socklen_t salen,
const ngtcp2_pkt_info *pi, uint8_t *data, size_t datalen);
void schedule_retransmit();
int handle_expiry();
void signal_write();
int handshake_completed();
void write_server_handshake(ngtcp2_crypto_level crypto_level,
const uint8_t *data, size_t datalen);
int recv_crypto_data(ngtcp2_crypto_level crypto_level, const uint8_t *data,
size_t datalen);
Server *server() const;
const Address &remote_addr() const;
ngtcp2_conn *conn() const;
int recv_stream_data(uint32_t flags, int64_t stream_id, const uint8_t *data,
size_t datalen);
int acked_stream_data_offset(int64_t stream_id, uint64_t datalen);
const ngtcp2_cid *scid() const;
const ngtcp2_cid *pscid() const;
const ngtcp2_cid *rcid() const;
uint32_t version() const;
void remove_tx_crypto_data(ngtcp2_crypto_level crypto_level, uint64_t offset,
uint64_t datalen);
void on_stream_open(int64_t stream_id);
int on_stream_close(int64_t stream_id, uint64_t app_error_code);
void start_draining_period();
int start_closing_period();
bool draining() const;
int handle_error();
int send_conn_close();
void update_endpoint(const ngtcp2_addr *addr);
void update_remote_addr(const ngtcp2_addr *addr, const ngtcp2_pkt_info *pi);
int on_key(ngtcp2_crypto_level level, const uint8_t *rsecret,
const uint8_t *wsecret, size_t secretlen);
void set_tls_alert(uint8_t alert);
int update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret,
const uint8_t *current_tx_secret, size_t secretlen);
int setup_httpconn();
void http_consume(int64_t stream_id, size_t nconsumed);
void extend_max_remote_streams_bidi(uint64_t max_streams);
Stream *find_stream(int64_t stream_id);
void http_begin_request_headers(int64_t stream_id);
void http_recv_request_header(Stream *stream, int32_t token,
nghttp3_rcbuf *name, nghttp3_rcbuf *value);
int http_end_request_headers(Stream *stream);
int http_end_stream(Stream *stream);
int start_response(Stream *stream);
int on_stream_reset(int64_t stream_id);
int extend_max_stream_data(int64_t stream_id, uint64_t max_data);
void shutdown_read(int64_t stream_id, int app_error_code);
void http_acked_stream_data(Stream *stream, size_t datalen);
int push_content(int64_t stream_id, const std::string_view &authority,
const std::string_view &path);
void http_stream_close(int64_t stream_id, uint64_t app_error_code);
int http_send_stop_sending(int64_t stream_id, uint64_t app_error_code);
int http_reset_stream(int64_t stream_id, uint64_t app_error_code);
void reset_idle_timer();
void write_qlog(const void *data, size_t datalen);
void singal_write();
private:
Endpoint *endpoint_;
Address remote_addr_;
unsigned int ecn_;
size_t max_pktlen_;
struct ev_loop *loop_;
SSL_CTX *ssl_ctx_;
SSL *ssl_;
Server *server_;
ev_io wev_;
ev_timer timer_;
ev_timer rttimer_;
FILE *qlog_;
Crypto crypto_[3];
ngtcp2_conn *conn_;
ngtcp2_cid scid_;
ngtcp2_cid pscid_;
ngtcp2_cid rcid_;
nghttp3_conn *httpconn_;
std::unordered_map<int64_t, std::unique_ptr<Stream>> streams_;
std::unique_ptr<Buffer> conn_closebuf_;
QUICError last_error_;
size_t nkey_update_;
bool draining_;
};
class Server
{
public:
Server(struct ev_loop *loop, SSL_CTX *ssl_ctx);
~Server();
int init(const char *addr, const char *port);
void disconnect();
void close();
int on_read(Endpoint &ep);
int send_version_negotiation(uint32_t version, const uint8_t *dcid,
size_t dcidlen, const uint8_t *scid,
size_t scidlen, Endpoint &ep, const sockaddr *sa,
socklen_t salen);
int send_retry(const ngtcp2_pkt_hd *chd, Endpoint &ep, const sockaddr *sa,
socklen_t salen);
int send_stateless_connection_close(const ngtcp2_pkt_hd *chd, Endpoint &ep,
const sockaddr *sa, socklen_t salen);
int generate_retry_token(uint8_t *token, size_t &tokenlen, const sockaddr *sa,
socklen_t salen, const ngtcp2_cid *scid,
const ngtcp2_cid *ocid);
int verify_retry_token(ngtcp2_cid *ocid, const ngtcp2_pkt_hd *hd,
const sockaddr *sa, socklen_t salen);
int generate_token(uint8_t *token, size_t &tokenlen, const sockaddr *sa);
int verify_token(const ngtcp2_pkt_hd *hd, const sockaddr *sa,
socklen_t salen);
int send_packet(Endpoint &ep, const Address &remote_addr, unsigned int ecn,
const uint8_t *data, size_t datalen, size_t gso_size);
void remove(const Handler *h);
int derive_token_key(uint8_t *key, size_t &keylen, uint8_t *iv, size_t &ivlen,
const uint8_t *rand_data, size_t rand_datalen);
void generate_rand_data(uint8_t *buf, size_t len);
void associate_cid(const ngtcp2_cid *cid, Handler *h);
void dissociate_cid(const ngtcp2_cid *cid);
private:
std::unordered_map<std::string, std::unique_ptr<Handler>> handlers_;
std::unordered_map<std::string, std::string> ctos_;
struct ev_loop *loop_;
std::vector<Endpoint> endpoints_;
SSL_CTX *ssl_ctx_;
ngtcp2_crypto_aead token_aead_;
ngtcp2_crypto_md token_md_;
ev_signal sigintev_;
};
namespace ngtcp2
{
namespace debug
{
int handshake_completed(ngtcp2_conn *conn, void *user_data);
int handshake_confirmed(ngtcp2_conn *conn, void *user_data);
bool packet_lost(double prob);
void print_crypto_data(ngtcp2_crypto_level crypto_level, const uint8_t *data,
size_t datalen);
void print_stream_data(int64_t stream_id, const uint8_t *data, size_t datalen);
void print_initial_secret(const uint8_t *data, size_t len);
void print_client_in_secret(const uint8_t *data, size_t len);
void print_server_in_secret(const uint8_t *data, size_t len);
void print_handshake_secret(const uint8_t *data, size_t len);
void print_client_hs_secret(const uint8_t *data, size_t len);
void print_server_hs_secret(const uint8_t *data, size_t len);
void print_client_0rtt_secret(const uint8_t *data, size_t len);
void print_client_1rtt_secret(const uint8_t *data, size_t len);
void print_server_1rtt_secret(const uint8_t *data, size_t len);
void print_client_pp_key(const uint8_t *data, size_t len);
void print_server_pp_key(const uint8_t *data, size_t len);
void print_client_pp_iv(const uint8_t *data, size_t len);
void print_server_pp_iv(const uint8_t *data, size_t len);
void print_client_pp_hp(const uint8_t *data, size_t len);
void print_server_pp_hp(const uint8_t *data, size_t len);
void print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,
size_t keylen, const uint8_t *iv, size_t ivlen,
const uint8_t *hp, size_t hplen);
void print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,
size_t keylen, const uint8_t *iv, size_t ivlen);
void print_hp_mask(const uint8_t *mask, size_t masklen, const uint8_t *sample,
size_t samplelen);
void log_printf(void *user_data, const char *fmt, ...);
void path_validation(const ngtcp2_path *path,
ngtcp2_path_validation_result res);
void print_http_begin_request_headers(int64_t stream_id);
void print_http_begin_response_headers(int64_t stream_id);
void print_http_header(int64_t stream_id, const nghttp3_rcbuf *name,
const nghttp3_rcbuf *value, uint8_t flags);
void print_http_end_headers(int64_t stream_id);
void print_http_data(int64_t stream_id, const uint8_t *data, size_t datalen);
void print_http_begin_trailers(int64_t stream_id);
void print_http_end_trailers(int64_t stream_id);
void print_http_begin_push_promise(int64_t stream_id, int64_t push_id);
void print_http_push_promise(int64_t stream_id, int64_t push_id,
const nghttp3_rcbuf *name,
const nghttp3_rcbuf *value, uint8_t flags);
void print_http_end_push_promise(int64_t stream_id, int64_t push_id);
void cancel_push(int64_t push_id, int64_t stream_id);
void push_stream(int64_t push_id, int64_t stream_id);
void print_http_request_headers(int64_t stream_id, const nghttp3_nv *nva,
size_t nvlen);
void print_http_response_headers(int64_t stream_id, const nghttp3_nv *nva,
size_t nvlen);
void print_http_push_promise(int64_t stream_id, int64_t push_id,
const nghttp3_nv *nva, size_t nvlen);
} // namespace debug
} // namespace ngtcp2
using namespace ngtcp2;
using namespace std::literals;
namespace
{
constexpr size_t NGTCP2_SV_SCIDLEN = 18;
}
namespace
{
constexpr size_t TOKEN_RAND_DATALEN = 16;
}
namespace
{
constexpr size_t MAX_DYNBUFLEN = 10 * 1024 * 1024;
}
namespace
{
auto randgen = util::make_mt19937();
}
namespace
{
constexpr uint8_t RETRY_TOKEN_MAGIC = 0xb6;
constexpr size_t MAX_RETRY_TOKENLEN =
1 + sizeof(uint64_t) + 20 +
16 + TOKEN_RAND_DATALEN;
constexpr uint8_t TOKEN_MAGIC = 0x36;
constexpr size_t MAX_TOKENLEN =
1 + sizeof(uint64_t) + 16 + TOKEN_RAND_DATALEN;
} // namespace
namespace
{
Config config{};
}
Buffer::Buffer(const uint8_t *data, size_t datalen)
: buf{data, data + datalen}, begin(buf.data()), tail(begin + datalen) {}
Buffer::Buffer(size_t datalen) : buf(datalen), begin(buf.data()), tail(begin) {}
int Handler::on_key(ngtcp2_crypto_level level, const uint8_t *rx_secret,
const uint8_t *tx_secret, size_t secretlen)
{
std::array<uint8_t, 64> rx_key, rx_iv, rx_hp_key, tx_key, tx_iv, tx_hp_key;
if (ngtcp2_crypto_derive_and_install_rx_key(
conn_, rx_key.data(), rx_iv.data(), rx_hp_key.data(), level,
rx_secret, secretlen) != 0)
{
return -1;
}
if (ngtcp2_crypto_derive_and_install_tx_key(
conn_, tx_key.data(), tx_iv.data(), tx_hp_key.data(), level,
tx_secret, secretlen) != 0)
{
return -1;
}
auto crypto_ctx = ngtcp2_conn_get_crypto_ctx(conn_);
auto aead = &crypto_ctx->aead;
auto keylen = ngtcp2_crypto_aead_keylen(aead);
auto ivlen = ngtcp2_crypto_packet_protection_ivlen(aead);
const char *title = nullptr;
switch (level)
{
case NGTCP2_CRYPTO_LEVEL_EARLY:
title = "early_traffic";
keylog::log_secret(ssl_, keylog::QUIC_CLIENT_EARLY_TRAFFIC_SECRET,
rx_secret, secretlen);
break;
case NGTCP2_CRYPTO_LEVEL_HANDSHAKE:
title = "handshake_traffic";
keylog::log_secret(ssl_, keylog::QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET,
rx_secret, secretlen);
keylog::log_secret(ssl_, keylog::QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET,
tx_secret, secretlen);
break;
case NGTCP2_CRYPTO_LEVEL_APP:
title = "application_traffic";
keylog::log_secret(ssl_, keylog::QUIC_CLIENT_TRAFFIC_SECRET_0, rx_secret,
secretlen);
keylog::log_secret(ssl_, keylog::QUIC_SERVER_TRAFFIC_SECRET_0, tx_secret,
secretlen);
break;
default:
(static_cast<bool>(
0)
? void(0)
: __assert_fail(
"0", "all.cpp", 40891, __extension__ __PRETTY_FUNCTION__));
}
if (!config.quiet && config.show_secret)
{
std::cerr << title << " rx secret" << std::endl;
debug::print_secrets(rx_secret, secretlen, rx_key.data(), keylen,
rx_iv.data(), ivlen, rx_hp_key.data(), keylen);
if (tx_secret)
{
std::cerr << title << " tx secret" << std::endl;
debug::print_secrets(tx_secret, secretlen, tx_key.data(), keylen,
tx_iv.data(), ivlen, tx_hp_key.data(), keylen);
}
}
if (level == NGTCP2_CRYPTO_LEVEL_APP && setup_httpconn() != 0)
{
return -1;
}
return 0;
}
Stream::Stream(int64_t stream_id, Handler *handler)
: stream_id(stream_id),
handler(handler),
data(nullptr),
datalen(0),
dynresp(false),
dyndataleft(0),
dynbuflen(0) {}
namespace
{
constexpr char NGTCP2_SERVER[] = "nghttp3/ngtcp2 server";
}
namespace
{
std::string make_status_body(unsigned int status_code)
{
auto status_string = std::to_string(status_code);
auto reason_phrase = http::get_reason_phrase(status_code);
std::string body;
body = "<html><head><title>";
body += status_string;
body += ' ';
body += reason_phrase;
body += "</title></head><body><h1>";
body += status_string;
body += ' ';
body += reason_phrase;
body += "</h1><hr><address>";
body += NGTCP2_SERVER;
body += " at port ";
body += std::to_string(config.port);
body += "</address>";
body += "</body></html>";
return body;
}
} // namespace
struct Request
{
std::string path;
std::vector<std::string> pushes;
struct
{
int32_t urgency;
int inc;
} pri;
};
namespace
{
Request request_path(const std::string_view &uri, bool is_connect)
{
http_parser_url u;
Request req;
req.pri.urgency = -1;
req.pri.inc = -1;
http_parser_url_init(&u);
if (auto rv = http_parser_parse_url(uri.data(), uri.size(), is_connect, &u);
rv != 0)
{
return req;
}
if (u.field_set & (1 << UF_PATH))
{
req.path = std::string(uri.data() + u.field_data[UF_PATH].off,
u.field_data[UF_PATH].len);
if (req.path.find('%') != std::string::npos)
{
req.path = util::percent_decode(std::begin(req.path), std::end(req.path));
}
if (!req.path.empty() && req.path.back() == '/')
{
req.path += "index.html";
}
}
else
{
req.path = "/index.html";
}
req.path = util::normalize_path(req.path);
if (req.path == "/")
{
req.path = "/index.html";
}
if (u.field_set & (1 << UF_QUERY))
{
static constexpr char push_prefix[] = "push=";
static constexpr char urgency_prefix[] = "u=";
static constexpr char inc_prefix[] = "i=";
auto q = std::string(uri.data() + u.field_data[UF_QUERY].off,
u.field_data[UF_QUERY].len);
for (auto p = std::begin(q); p != std::end(q);)
{
if (util::istarts_with(p, std::end(q), std::begin(push_prefix),
std::end(push_prefix) - 1))
{
auto path_start = p + sizeof(push_prefix) - 1;
auto path_end = std::find(path_start, std::end(q), '&');
if (path_start != path_end && *path_start == '/')
{
req.pushes.emplace_back(path_start, path_end);
}
if (path_end == std::end(q))
{
break;
}
p = path_end + 1;
continue;
}
if (util::istarts_with(p, std::end(q), std::begin(urgency_prefix),
std::end(urgency_prefix) - 1))
{
auto urgency_start = p + sizeof(urgency_prefix) - 1;
auto urgency_end = std::find(urgency_start, std::end(q), '&');
if (urgency_start + 1 == urgency_end && '0' <= *urgency_start &&
*urgency_start <= '7')
{
req.pri.urgency = *urgency_start - '0';
}
if (urgency_end == std::end(q))
{
break;
}
p = urgency_end + 1;
continue;
}
if (util::istarts_with(p, std::end(q), std::begin(inc_prefix),
std::end(inc_prefix) - 1))
{
auto inc_start = p + sizeof(inc_prefix) - 1;
auto inc_end = std::find(inc_start, std::end(q), '&');
if (inc_start + 1 == inc_end &&
(*inc_start == '0' || *inc_start == '1'))
{
req.pri.inc = *inc_start - '0';
}
if (inc_end == std::end(q))
{
break;
}
p = inc_end + 1;
continue;
}
p = std::find(p, std::end(q), '&');
if (p == std::end(q))
{
break;
}
++p;
}
}
return req;
}
} // namespace
enum FileEntryFlag
{
FILE_ENTRY_TYPE_DIR = 0x1,
};
struct FileEntry
{
uint64_t len;
void *map;
int fd;
uint8_t flags;
};
namespace
{
std::unordered_map<std::string, FileEntry> file_cache;
}
std::pair<FileEntry, int> Stream::open_file(const std::string &path)
{
auto it = file_cache.find(path);
if (it != std::end(file_cache))
{
return {(*it).second, 0};
}
auto fd = open(path.c_str(),
00);
if (fd == -1)
{
return {{}, -1};
}
struct stat st
{
};
if (fstat(fd, &st) != 0)
{
close(fd);
return {{}, -1};
}
FileEntry fe{};
if (st.st_mode &
0040000)
{
fe.flags |= FILE_ENTRY_TYPE_DIR;
fe.fd = -1;
close(fd);
}
else
{
fe.fd = fd;
fe.len = st.st_size;
fe.map = mmap(nullptr, fe.len,
0x1,
0x01, fd, 0);
if (fe.map ==
((void *)-1))
{
std::cerr << "mmap: " << strerror((*__errno_location())) << std::endl;
close(fd);
return {{}, -1};
}
}
file_cache.emplace(path, fe);
return {std::move(fe), 0};
}
void Stream::map_file(const FileEntry &fe)
{
data = static_cast<uint8_t *>(fe.map);
datalen = fe.len;
}
int64_t Stream::find_dyn_length(const std::string_view &path)
{
(static_cast<bool>(
path[0] == '/')
? void(0)
: __assert_fail(
"path[0] == '/'", "all.cpp", 41138, __extension__ __PRETTY_FUNCTION__));
if (path.size() == 1)
{
return -1;
}
uint64_t n = 0;
for (auto it = std::begin(path) + 1; it != std::end(path); ++it)
{
if (*it < '0' || '9' < *it)
{
return -1;
}
auto d = *it - '0';
if (n > (((1ull << 62) - 1) - d) / 10)
{
return -1;
}
n = n * 10 + d;
if (n > config.max_dyn_length)
{
return -1;
}
}
return static_cast<int64_t>(n);
}
namespace
{
nghttp3_ssize read_data(nghttp3_conn *conn, int64_t stream_id, nghttp3_vec *vec,
size_t veccnt, uint32_t *pflags, void *user_data,
void *stream_user_data)
{
auto stream = static_cast<Stream *>(stream_user_data);
vec[0].base = stream->data;
vec[0].len = stream->datalen;
*pflags |= NGHTTP3_DATA_FLAG_EOF;
if (config.send_trailers)
{
*pflags |= NGHTTP3_DATA_FLAG_NO_END_STREAM;
}
return 1;
}
} // namespace
auto dyn_buf = std::make_unique<std::array<uint8_t, 16_k>>();
namespace
{
nghttp3_ssize dyn_read_data(nghttp3_conn *conn, int64_t stream_id,
nghttp3_vec *vec, size_t veccnt, uint32_t *pflags,
void *user_data, void *stream_user_data)
{
auto stream = static_cast<Stream *>(stream_user_data);
if (stream->dynbuflen > MAX_DYNBUFLEN)
{
return NGHTTP3_ERR_WOULDBLOCK;
}
auto len =
std::min(dyn_buf->size(), static_cast<size_t>(stream->dyndataleft));
vec[0].base = dyn_buf->data();
vec[0].len = len;
stream->dynbuflen += len;
stream->dyndataleft -= len;
if (stream->dyndataleft == 0)
{
*pflags |= NGHTTP3_DATA_FLAG_EOF;
if (config.send_trailers)
{
*pflags |= NGHTTP3_DATA_FLAG_NO_END_STREAM;
auto stream_id_str = std::to_string(stream_id);
std::array<nghttp3_nv, 1> trailers{
util::make_nv("x-ngtcp2-stream-id", stream_id_str),
};
if (auto rv = nghttp3_conn_submit_trailers(
conn, stream_id, trailers.data(), trailers.size());
rv != 0)
{
std::cerr << "nghttp3_conn_submit_trailers: " << nghttp3_strerror(rv)
<< std::endl;
return NGHTTP3_ERR_CALLBACK_FAILURE;
}
}
}
return 1;
}
} // namespace
void Stream::http_acked_stream_data(size_t datalen)
{
if (!dynresp)
{
return;
}
(static_cast<bool>(
dynbuflen >= datalen)
? void(0)
: __assert_fail(
"dynbuflen >= datalen", "all.cpp", 41231, __extension__ __PRETTY_FUNCTION__));
dynbuflen -= datalen;
}
int Stream::send_status_response(nghttp3_conn *httpconn,
unsigned int status_code,
const std::vector<HTTPHeader> &extra_headers)
{
status_resp_body = make_status_body(status_code);
auto status_code_str = std::to_string(status_code);
auto content_length_str = std::to_string(status_resp_body.size());
std::vector<nghttp3_nv> nva(4 + extra_headers.size());
nva[0] = util::make_nv(":status", status_code_str);
nva[1] = util::make_nv("server", NGTCP2_SERVER);
nva[2] = util::make_nv("content-type", "text/html; charset=utf-8");
nva[3] = util::make_nv("content-length", content_length_str);
for (size_t i = 0; i < extra_headers.size(); ++i)
{
auto &hdr = extra_headers[i];
auto &nv = nva[4 + i];
nv = util::make_nv(hdr.name, hdr.value);
}
data = (uint8_t *)status_resp_body.data();
datalen = status_resp_body.size();
nghttp3_data_reader dr{};
dr.read_data = read_data;
if (auto rv = nghttp3_conn_submit_response(httpconn, stream_id, nva.data(),
nva.size(), &dr);
rv != 0)
{
std::cerr << "nghttp3_conn_submit_response: " << nghttp3_strerror(rv)
<< std::endl;
return -1;
}
if (config.send_trailers)
{
auto stream_id_str = std::to_string(stream_id);
std::array<nghttp3_nv, 1> trailers{
util::make_nv("x-ngtcp2-stream-id", stream_id_str),
};
if (auto rv = nghttp3_conn_submit_trailers(
httpconn, stream_id, trailers.data(), trailers.size());
rv != 0)
{
std::cerr << "nghttp3_conn_submit_trailers: " << nghttp3_strerror(rv)
<< std::endl;
return -1;
}
}
handler->shutdown_read(stream_id, 0x0100);
return 0;
}
int Stream::send_redirect_response(nghttp3_conn *httpconn,
unsigned int status_code,
const std::string_view &path)
{
return send_status_response(httpconn, status_code, {{"location", path}});
}
int Stream::start_response(nghttp3_conn *httpconn)
{
if (uri.empty() || method.empty())
{
return send_status_response(httpconn, 400);
}
auto req = request_path(uri, method == "CONNECT");
if (req.path.empty())
{
return send_status_response(httpconn, 400);
}
auto dyn_len = find_dyn_length(req.path);
int64_t content_length = -1;
nghttp3_data_reader dr{};
std::string content_type = "text/plain";
if (dyn_len == -1)
{
auto path = config.htdocs + req.path;
auto [fe, rv] = open_file(path);
if (rv != 0)
{
send_status_response(httpconn, 404);
return 0;
}
if (fe.flags & FILE_ENTRY_TYPE_DIR)
{
send_redirect_response(httpconn, 308,
path.substr(config.htdocs.size() - 1) + '/');
return 0;
}
content_length = fe.len;
if (method != "HEAD")
{
map_file(fe);
}
dr.read_data = read_data;
auto ext = std::end(req.path) - 1;
for (; ext != std::begin(req.path) && *ext != '.' && *ext != '/'; --ext)
;
if (*ext == '.')
{
++ext;
auto it = config.mime_types.find(std::string{ext, std::end(req.path)});
if (it != std::end(config.mime_types))
{
content_type = (*it).second;
}
}
}
else
{
content_length = dyn_len;
datalen = dyn_len;
dynresp = true;
dyndataleft = dyn_len;
dr.read_data = dyn_read_data;
content_type = "application/octet-stream";
}
if ((stream_id & 0x3) == 0 && !authority.empty())
{
for (const auto &push : req.pushes)
{
if (handler->push_content(stream_id, authority, push) != 0)
{
return -1;
}
}
}
auto content_length_str = std::to_string(content_length);
std::array<nghttp3_nv, 5> nva{
util::make_nv(":status", "200"),
util::make_nv("server", NGTCP2_SERVER),
util::make_nv("content-type", content_type),
util::make_nv("content-length", content_length_str),
};
size_t nvlen = 4;
std::string prival;
if (req.pri.urgency != -1 || req.pri.inc != -1)
{
nghttp3_pri pri;
if (auto rv = nghttp3_conn_get_stream_priority(httpconn, &pri, stream_id);
rv != 0)
{
std::cerr << "nghttp3_conn_get_stream_priority: " << nghttp3_strerror(rv)
<< std::endl;
return -1;
}
if (req.pri.urgency != -1)
{
pri.urgency = req.pri.urgency;
}
if (req.pri.inc != -1)
{
pri.inc = req.pri.inc;
}
if (auto rv = nghttp3_conn_set_stream_priority(httpconn, stream_id, &pri);
rv != 0)
{
std::cerr << "nghttp3_conn_set_stream_priority: " << nghttp3_strerror(rv)
<< std::endl;
return -1;
}
prival = "u=";
prival += pri.urgency + '0';
prival += ",i";
if (!pri.inc)
{
prival += "=?0";
}
nva[nvlen++] = util::make_nv("priority", prival);
}
if (!config.quiet)
{
debug::print_http_response_headers(stream_id, nva.data(), nvlen);
}
if (auto rv = nghttp3_conn_submit_response(httpconn, stream_id, nva.data(),
nvlen, &dr);
rv != 0)
{
std::cerr << "nghttp3_conn_submit_response: " << nghttp3_strerror(rv)
<< std::endl;
return -1;
}
if (config.send_trailers && dyn_len == -1)
{
auto stream_id_str = std::to_string(stream_id);
std::array<nghttp3_nv, 1> trailers{
util::make_nv("x-ngtcp2-stream-id", stream_id_str),
};
if (auto rv = nghttp3_conn_submit_trailers(
httpconn, stream_id, trailers.data(), trailers.size());
rv != 0)
{
std::cerr << "nghttp3_conn_submit_trailers: " << nghttp3_strerror(rv)
<< std::endl;
return -1;
}
handler->shutdown_read(stream_id, 0x0100);
}
return 0;
}
namespace
{
void writecb(struct ev_loop *loop, ev_io *w, int revents)
{
ev_io_stop(loop, w);
auto h = static_cast<Handler *>(w->data);
auto s = h->server();
switch (h->on_write())
{
case 0:
case NETWORK_ERR_CLOSE_WAIT:
return;
default:
s->remove(h);
}
}
} // namespace
namespace
{
void timeoutcb(struct ev_loop *loop, ev_timer *w, int revents)
{
auto h = static_cast<Handler *>(w->data);
auto s = h->server();
if (ngtcp2_conn_is_in_closing_period(h->conn()))
{
if (!config.quiet)
{
std::cerr << "Closing Period is over" << std::endl;
}
s->remove(h);
return;
}
if (h->draining())
{
if (!config.quiet)
{
std::cerr << "Draining Period is over" << std::endl;
}
s->remove(h);
return;
}
if (!config.quiet)
{
std::cerr << "Timeout" << std::endl;
}
h->start_draining_period();
}
} // namespace
namespace
{
void retransmitcb(struct ev_loop *loop, ev_timer *w, int revents)
{
int rv;
auto h = static_cast<Handler *>(w->data);
auto s = h->server();
if (!config.quiet)
{
std::cerr << "Timer expired" << std::endl;
}
rv = h->handle_expiry();
if (rv != 0)
{
goto fail;
}
rv = h->on_write();
if (rv != 0)
{
goto fail;
}
return;
fail:
switch (rv)
{
case NETWORK_ERR_CLOSE_WAIT:
ev_timer_stop(loop, w);