forked from nghttp2/nghttp2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nghttp2.pyx
1656 lines (1301 loc) · 57.9 KB
/
nghttp2.pyx
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
# nghttp2 - HTTP/2 C Library
# Copyright (c) 2013 Tatsuhiro Tsujikawa
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
cimport cnghttp2
from libc.stdlib cimport malloc, free
from libc.string cimport memcpy, memset
from libc.stdint cimport uint8_t, uint16_t, uint32_t, int32_t
import logging
DEFAULT_HEADER_TABLE_SIZE = cnghttp2.NGHTTP2_DEFAULT_HEADER_TABLE_SIZE
DEFLATE_MAX_HEADER_TABLE_SIZE = 4096
HD_ENTRY_OVERHEAD = 32
class HDTableEntry:
def __init__(self, name, namelen, value, valuelen):
self.name = name
self.namelen = namelen
self.value = value
self.valuelen = valuelen
def space(self):
return self.namelen + self.valuelen + HD_ENTRY_OVERHEAD
cdef _get_pybytes(uint8_t *b, uint16_t blen):
return b[:blen]
cdef class HDDeflater:
'''Performs header compression. The constructor takes
|hd_table_bufsize_max| parameter, which limits the usage of header
table in the given amount of bytes. This is necessary because the
header compressor and decompressor share the same amount of
header table and the decompressor decides that number. The
compressor may not want to use all header table size because of
limited memory availability. In that case, the
|hd_table_bufsize_max| can be used to cap the upper limit of table
size whatever the header table size is chosen by the decompressor.
The default value of |hd_table_bufsize_max| is 4096 bytes.
The following example shows how to compress request header sets:
import binascii, nghttp2
deflater = nghttp2.HDDeflater()
res = deflater.deflate([(b'foo', b'bar'),
(b'baz', b'buz')])
print(binascii.b2a_hex(res))
'''
cdef cnghttp2.nghttp2_hd_deflater *_deflater
def __cinit__(self, hd_table_bufsize_max = DEFLATE_MAX_HEADER_TABLE_SIZE):
rv = cnghttp2.nghttp2_hd_deflate_new(&self._deflater,
hd_table_bufsize_max)
if rv != 0:
raise Exception(_strerror(rv))
def __dealloc__(self):
cnghttp2.nghttp2_hd_deflate_del(self._deflater)
def deflate(self, headers):
'''Compresses the |headers|. The |headers| must be sequence of tuple
of name/value pair, which are sequence of bytes (not unicode
string).
This function returns the encoded header block in byte string.
An exception will be raised on error.
'''
cdef cnghttp2.nghttp2_nv *nva = <cnghttp2.nghttp2_nv*>\
malloc(sizeof(cnghttp2.nghttp2_nv)*\
len(headers))
cdef cnghttp2.nghttp2_nv *nvap = nva
for k, v in headers:
nvap[0].name = k
nvap[0].namelen = len(k)
nvap[0].value = v
nvap[0].valuelen = len(v)
nvap[0].flags = cnghttp2.NGHTTP2_NV_FLAG_NONE
nvap += 1
cdef size_t outcap = 0
cdef ssize_t rv
cdef uint8_t *out
cdef size_t outlen
outlen = cnghttp2.nghttp2_hd_deflate_bound(self._deflater,
nva, len(headers))
out = <uint8_t*>malloc(outlen)
rv = cnghttp2.nghttp2_hd_deflate_hd(self._deflater, out, outlen,
nva, len(headers))
free(nva)
if rv < 0:
free(out)
raise Exception(_strerror(rv))
cdef bytes res
try:
res = out[:rv]
finally:
free(out)
return res
def change_table_size(self, hd_table_bufsize_max):
'''Changes header table size to |hd_table_bufsize_max| byte.
An exception will be raised on error.
'''
cdef int rv
rv = cnghttp2.nghttp2_hd_deflate_change_table_size(self._deflater,
hd_table_bufsize_max)
if rv != 0:
raise Exception(_strerror(rv))
def get_hd_table(self):
'''Returns copy of current dynamic header table.'''
cdef size_t length = cnghttp2.nghttp2_hd_deflate_get_num_table_entries(
self._deflater)
cdef const cnghttp2.nghttp2_nv *nv
res = []
for i in range(62, length + 1):
nv = cnghttp2.nghttp2_hd_deflate_get_table_entry(self._deflater, i)
k = _get_pybytes(nv.name, nv.namelen)
v = _get_pybytes(nv.value, nv.valuelen)
res.append(HDTableEntry(k, nv.namelen, v, nv.valuelen))
return res
cdef class HDInflater:
'''Performs header decompression.
The following example shows how to compress request header sets:
data = b'0082c5ad82bd0f000362617a0362757a'
inflater = nghttp2.HDInflater()
hdrs = inflater.inflate(data)
print(hdrs)
'''
cdef cnghttp2.nghttp2_hd_inflater *_inflater
def __cinit__(self):
rv = cnghttp2.nghttp2_hd_inflate_new(&self._inflater)
if rv != 0:
raise Exception(_strerror(rv))
def __dealloc__(self):
cnghttp2.nghttp2_hd_inflate_del(self._inflater)
def inflate(self, data):
'''Decompresses the compressed header block |data|. The |data| must be
byte string (not unicode string).
'''
cdef cnghttp2.nghttp2_nv nv
cdef int inflate_flags
cdef ssize_t rv
cdef uint8_t *buf = data
cdef size_t buflen = len(data)
res = []
while True:
inflate_flags = 0
rv = cnghttp2.nghttp2_hd_inflate_hd2(self._inflater, &nv,
&inflate_flags,
buf, buflen, 1)
if rv < 0:
raise Exception(_strerror(rv))
buf += rv
buflen -= rv
if inflate_flags & cnghttp2.NGHTTP2_HD_INFLATE_EMIT:
# may throw
res.append((nv.name[:nv.namelen], nv.value[:nv.valuelen]))
if inflate_flags & cnghttp2.NGHTTP2_HD_INFLATE_FINAL:
break
cnghttp2.nghttp2_hd_inflate_end_headers(self._inflater)
return res
def change_table_size(self, hd_table_bufsize_max):
'''Changes header table size to |hd_table_bufsize_max| byte.
An exception will be raised on error.
'''
cdef int rv
rv = cnghttp2.nghttp2_hd_inflate_change_table_size(self._inflater,
hd_table_bufsize_max)
if rv != 0:
raise Exception(_strerror(rv))
def get_hd_table(self):
'''Returns copy of current dynamic header table.'''
cdef size_t length = cnghttp2.nghttp2_hd_inflate_get_num_table_entries(
self._inflater)
cdef const cnghttp2.nghttp2_nv *nv
res = []
for i in range(62, length + 1):
nv = cnghttp2.nghttp2_hd_inflate_get_table_entry(self._inflater, i)
k = _get_pybytes(nv.name, nv.namelen)
v = _get_pybytes(nv.value, nv.valuelen)
res.append(HDTableEntry(k, nv.namelen, v, nv.valuelen))
return res
cdef _strerror(int liberror_code):
return cnghttp2.nghttp2_strerror(liberror_code).decode('utf-8')
def print_hd_table(hdtable):
'''Convenient function to print |hdtable| to the standard output. This
function does not work if header name/value cannot be decoded using
UTF-8 encoding.
s=N means the entry occupies N bytes in header table.
'''
idx = 0
for entry in hdtable:
idx += 1
print('[{}] (s={}) {}: {}'\
.format(idx, entry.space(),
entry.name.decode('utf-8'),
entry.value.decode('utf-8')))
try:
import socket
import io
import asyncio
import traceback
import sys
import email.utils
import datetime
import time
import ssl as tls
from urllib.parse import urlparse
except ImportError:
asyncio = None
# body generator flags
DATA_OK = 0
DATA_EOF = 1
DATA_DEFERRED = 2
class _ByteIOWrapper:
def __init__(self, b):
self.b = b
def generate(self, n):
data = self.b.read1(n)
if not data:
return None, DATA_EOF
return data, DATA_OK
def wrap_body(body):
if body is None:
return body
elif isinstance(body, str):
return _ByteIOWrapper(io.BytesIO(body.encode('utf-8'))).generate
elif isinstance(body, bytes):
return _ByteIOWrapper(io.BytesIO(body)).generate
elif isinstance(body, io.IOBase):
return _ByteIOWrapper(body).generate
else:
# assume that callable in the form f(n) returning tuple byte
# string and flag.
return body
def negotiated_protocol(ssl_obj):
protocol = ssl_obj.selected_alpn_protocol()
if protocol:
logging.info('alpn, protocol:%s', protocol)
return protocol
protocol = ssl_obj.selected_npn_protocol()
if protocol:
logging.info('npn, protocol:%s', protocol)
return protocol
return None
def set_application_protocol(ssl_ctx):
app_protos = [cnghttp2.NGHTTP2_PROTO_VERSION_ID.decode('utf-8')]
ssl_ctx.set_npn_protocols(app_protos)
if tls.HAS_ALPN:
ssl_ctx.set_alpn_protocols(app_protos)
cdef _get_stream_user_data(cnghttp2.nghttp2_session *session,
int32_t stream_id):
cdef void *stream_user_data
stream_user_data = cnghttp2.nghttp2_session_get_stream_user_data\
(session, stream_id)
if stream_user_data == NULL:
return None
return <object>stream_user_data
cdef size_t _make_nva(cnghttp2.nghttp2_nv **nva_ptr, headers):
cdef cnghttp2.nghttp2_nv *nva
cdef size_t nvlen
nvlen = len(headers)
nva = <cnghttp2.nghttp2_nv*>malloc(sizeof(cnghttp2.nghttp2_nv) * nvlen)
for i, (k, v) in enumerate(headers):
nva[i].name = k
nva[i].namelen = len(k)
nva[i].value = v
nva[i].valuelen = len(v)
nva[i].flags = cnghttp2.NGHTTP2_NV_FLAG_NONE
nva_ptr[0] = nva
return nvlen
cdef int server_on_header(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
uint8_t flags,
void *user_data):
cdef http2 = <_HTTP2SessionCoreBase>user_data
logging.debug('server_on_header, type:%s, stream_id:%s', frame.hd.type, frame.hd.stream_id)
handler = _get_stream_user_data(session, frame.hd.stream_id)
return on_header(name, namelen, value, valuelen, flags, handler)
cdef int client_on_header(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
uint8_t flags,
void *user_data):
cdef http2 = <_HTTP2SessionCoreBase>user_data
logging.debug('client_on_header, type:%s, stream_id:%s', frame.hd.type, frame.hd.stream_id)
if frame.hd.type == cnghttp2.NGHTTP2_HEADERS:
handler = _get_stream_user_data(session, frame.hd.stream_id)
elif frame.hd.type == cnghttp2.NGHTTP2_PUSH_PROMISE:
handler = _get_stream_user_data(session, frame.push_promise.promised_stream_id)
return on_header(name, namelen, value, valuelen, flags, handler)
cdef int on_header(const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
uint8_t flags,
object handler):
if not handler:
return 0
key = name[:namelen]
values = value[:valuelen].split(b'\x00')
if key == b':scheme':
handler.scheme = values[0]
elif key == b':method':
handler.method = values[0]
elif key == b':authority' or key == b'host':
handler.host = values[0]
elif key == b':path':
handler.path = values[0]
elif key == b':status':
handler.status = values[0]
if key == b'cookie':
handler.cookies.extend(values)
else:
for v in values:
handler.headers.append((key, v))
return 0
cdef int server_on_begin_request_headers(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
void *user_data):
cdef http2 = <_HTTP2SessionCore>user_data
handler = http2._make_handler(frame.hd.stream_id)
cnghttp2.nghttp2_session_set_stream_user_data(session, frame.hd.stream_id,
<void*>handler)
return 0
cdef int server_on_begin_headers(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
void *user_data):
if frame.hd.type == cnghttp2.NGHTTP2_HEADERS:
if frame.headers.cat == cnghttp2.NGHTTP2_HCAT_REQUEST:
return server_on_begin_request_headers(session, frame, user_data)
return 0
cdef int server_on_frame_recv(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
void *user_data):
cdef http2 = <_HTTP2SessionCore>user_data
logging.debug('server_on_frame_recv, type:%s, stream_id:%s', frame.hd.type, frame.hd.stream_id)
if frame.hd.type == cnghttp2.NGHTTP2_DATA:
if frame.hd.flags & cnghttp2.NGHTTP2_FLAG_END_STREAM:
handler = _get_stream_user_data(session, frame.hd.stream_id)
if not handler:
return 0
try:
handler.on_request_done()
except:
sys.stderr.write(traceback.format_exc())
return http2._rst_stream(frame.hd.stream_id)
elif frame.hd.type == cnghttp2.NGHTTP2_HEADERS:
if frame.headers.cat == cnghttp2.NGHTTP2_HCAT_REQUEST:
handler = _get_stream_user_data(session, frame.hd.stream_id)
if not handler:
return 0
if handler.cookies:
handler.headers.append((b'cookie',
b'; '.join(handler.cookies)))
handler.cookies = None
try:
handler.on_headers()
if frame.hd.flags & cnghttp2.NGHTTP2_FLAG_END_STREAM:
handler.on_request_done()
except:
sys.stderr.write(traceback.format_exc())
return http2._rst_stream(frame.hd.stream_id)
elif frame.hd.type == cnghttp2.NGHTTP2_SETTINGS:
if (frame.hd.flags & cnghttp2.NGHTTP2_FLAG_ACK):
http2._stop_settings_timer()
return 0
cdef int on_data_chunk_recv(cnghttp2.nghttp2_session *session,
uint8_t flags,
int32_t stream_id, const uint8_t *data,
size_t length, void *user_data):
cdef http2 = <_HTTP2SessionCoreBase>user_data
handler = _get_stream_user_data(session, stream_id)
if not handler:
return 0
try:
handler.on_data(data[:length])
except:
sys.stderr.write(traceback.format_exc())
return http2._rst_stream(stream_id)
return 0
cdef int server_on_frame_send(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
void *user_data):
cdef http2 = <_HTTP2SessionCore>user_data
logging.debug('server_on_frame_send, type:%s, stream_id:%s', frame.hd.type, frame.hd.stream_id)
if frame.hd.type == cnghttp2.NGHTTP2_PUSH_PROMISE:
# For PUSH_PROMISE, send push response immediately
handler = _get_stream_user_data\
(session, frame.push_promise.promised_stream_id)
if not handler:
return 0
http2.send_response(handler)
elif frame.hd.type == cnghttp2.NGHTTP2_SETTINGS:
if (frame.hd.flags & cnghttp2.NGHTTP2_FLAG_ACK) != 0:
return 0
http2._start_settings_timer()
elif frame.hd.type == cnghttp2.NGHTTP2_HEADERS:
if (frame.hd.flags & cnghttp2.NGHTTP2_FLAG_END_STREAM) and \
cnghttp2.nghttp2_session_check_server_session(session):
# Send RST_STREAM if remote is not closed yet
if cnghttp2.nghttp2_session_get_stream_remote_close(
session, frame.hd.stream_id) == 0:
http2._rst_stream(frame.hd.stream_id, cnghttp2.NGHTTP2_NO_ERROR)
cdef int server_on_frame_not_send(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
int lib_error_code,
void *user_data):
cdef http2 = <_HTTP2SessionCore>user_data
logging.debug('server_on_frame_not_send, type:%s, stream_id:%s', frame.hd.type, frame.hd.stream_id)
if frame.hd.type == cnghttp2.NGHTTP2_PUSH_PROMISE:
# We have to remove handler here. Without this, it is not
# removed until session is terminated.
handler = _get_stream_user_data\
(session, frame.push_promise.promised_stream_id)
if not handler:
return 0
http2._remove_handler(handler)
cdef int on_stream_close(cnghttp2.nghttp2_session *session,
int32_t stream_id,
uint32_t error_code,
void *user_data):
cdef http2 = <_HTTP2SessionCoreBase>user_data
logging.debug('on_stream_close, stream_id:%s', stream_id)
handler = _get_stream_user_data(session, stream_id)
if not handler:
return 0
try:
handler.on_close(error_code)
except:
sys.stderr.write(traceback.format_exc())
http2._remove_handler(handler)
return 0
cdef ssize_t data_source_read(cnghttp2.nghttp2_session *session,
int32_t stream_id,
uint8_t *buf, size_t length,
uint32_t *data_flags,
cnghttp2.nghttp2_data_source *source,
void *user_data):
cdef http2 = <_HTTP2SessionCoreBase>user_data
generator = <object>source.ptr
http2.enter_callback()
try:
data, flag = generator(length)
except:
sys.stderr.write(traceback.format_exc())
return cnghttp2.NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
finally:
http2.leave_callback()
if flag == DATA_DEFERRED:
return cnghttp2.NGHTTP2_ERR_DEFERRED
if data:
nread = len(data)
memcpy(buf, <uint8_t*>data, nread)
else:
nread = 0
if flag == DATA_EOF:
data_flags[0] = cnghttp2.NGHTTP2_DATA_FLAG_EOF
if cnghttp2.nghttp2_session_check_server_session(session):
# Send RST_STREAM if remote is not closed yet
if cnghttp2.nghttp2_session_get_stream_remote_close(
session, stream_id) == 0:
http2._rst_stream(stream_id, cnghttp2.NGHTTP2_NO_ERROR)
elif flag != DATA_OK:
return cnghttp2.NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE
return nread
cdef int client_on_begin_headers(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
void *user_data):
cdef http2 = <_HTTP2ClientSessionCore>user_data
if frame.hd.type == cnghttp2.NGHTTP2_PUSH_PROMISE:
# Generate a temporary handler until the headers are all received
push_handler = BaseResponseHandler()
http2._add_handler(push_handler, frame.push_promise.promised_stream_id)
cnghttp2.nghttp2_session_set_stream_user_data(session, frame.push_promise.promised_stream_id,
<void*>push_handler)
return 0
cdef int client_on_frame_recv(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
void *user_data):
cdef http2 = <_HTTP2ClientSessionCore>user_data
logging.debug('client_on_frame_recv, type:%s, stream_id:%s', frame.hd.type, frame.hd.stream_id)
if frame.hd.type == cnghttp2.NGHTTP2_DATA:
if frame.hd.flags & cnghttp2.NGHTTP2_FLAG_END_STREAM:
handler = _get_stream_user_data(session, frame.hd.stream_id)
if not handler:
return 0
try:
handler.on_response_done()
except:
sys.stderr.write(traceback.format_exc())
return http2._rst_stream(frame.hd.stream_id)
elif frame.hd.type == cnghttp2.NGHTTP2_HEADERS:
if frame.headers.cat == cnghttp2.NGHTTP2_HCAT_RESPONSE or frame.headers.cat == cnghttp2.NGHTTP2_HCAT_PUSH_RESPONSE:
handler = _get_stream_user_data(session, frame.hd.stream_id)
if not handler:
return 0
# TODO handle 1xx non-final response
if handler.cookies:
handler.headers.append((b'cookie',
b'; '.join(handler.cookies)))
handler.cookies = None
try:
handler.on_headers()
if frame.hd.flags & cnghttp2.NGHTTP2_FLAG_END_STREAM:
handler.on_response_done()
except:
sys.stderr.write(traceback.format_exc())
return http2._rst_stream(frame.hd.stream_id)
elif frame.hd.type == cnghttp2.NGHTTP2_SETTINGS:
if (frame.hd.flags & cnghttp2.NGHTTP2_FLAG_ACK):
http2._stop_settings_timer()
elif frame.hd.type == cnghttp2.NGHTTP2_PUSH_PROMISE:
handler = _get_stream_user_data(session, frame.hd.stream_id)
if not handler:
return 0
# Get the temporary push_handler which now should have all of the header data
push_handler = _get_stream_user_data(session, frame.push_promise.promised_stream_id)
if not push_handler:
return 0
# Remove the temporary handler
http2._remove_handler(push_handler)
cnghttp2.nghttp2_session_set_stream_user_data(session, frame.push_promise.promised_stream_id,
<void*>NULL)
try:
handler.on_push_promise(push_handler)
except:
sys.stderr.write(traceback.format_exc())
return http2._rst_stream(frame.hd.stream_id)
return 0
cdef int client_on_frame_send(cnghttp2.nghttp2_session *session,
const cnghttp2.nghttp2_frame *frame,
void *user_data):
cdef http2 = <_HTTP2ClientSessionCore>user_data
logging.debug('client_on_frame_send, type:%s, stream_id:%s', frame.hd.type, frame.hd.stream_id)
if frame.hd.type == cnghttp2.NGHTTP2_SETTINGS:
if (frame.hd.flags & cnghttp2.NGHTTP2_FLAG_ACK) != 0:
return 0
http2._start_settings_timer()
cdef class _HTTP2SessionCoreBase:
cdef cnghttp2.nghttp2_session *session
cdef transport
cdef handler_class
cdef handlers
cdef settings_timer
cdef inside_callback
def __cinit__(self, transport, handler_class=None):
self.session = NULL
self.transport = transport
self.handler_class = handler_class
self.handlers = set()
self.settings_timer = None
self.inside_callback = False
def __dealloc__(self):
cnghttp2.nghttp2_session_del(self.session)
def data_received(self, data):
cdef ssize_t rv
rv = cnghttp2.nghttp2_session_mem_recv(self.session, data, len(data))
if rv < 0:
raise Exception('nghttp2_session_mem_recv failed: {}'.format\
(_strerror(rv)))
self.send_data()
OUTBUF_MAX = 65535
SETTINGS_TIMEOUT = 5.0
def send_data(self):
cdef ssize_t outbuflen
cdef const uint8_t *outbuf
while True:
if self.transport.get_write_buffer_size() > self.OUTBUF_MAX:
break
outbuflen = cnghttp2.nghttp2_session_mem_send(self.session, &outbuf)
if outbuflen == 0:
break
if outbuflen < 0:
raise Exception('nghttp2_session_mem_send faild: {}'.format\
(_strerror(outbuflen)))
self.transport.write(outbuf[:outbuflen])
if self.transport.get_write_buffer_size() == 0 and \
cnghttp2.nghttp2_session_want_read(self.session) == 0 and \
cnghttp2.nghttp2_session_want_write(self.session) == 0:
self.transport.close()
def resume(self, stream_id):
cnghttp2.nghttp2_session_resume_data(self.session, stream_id)
if not self.inside_callback:
self.send_data()
def enter_callback(self):
self.inside_callback = True
def leave_callback(self):
self.inside_callback = False
def _make_handler(self, stream_id):
logging.debug('_make_handler, stream_id:%s', stream_id)
handler = self.handler_class(self, stream_id)
self.handlers.add(handler)
return handler
def _remove_handler(self, handler):
logging.debug('_remove_handler, stream_id:%s', handler.stream_id)
self.handlers.remove(handler)
def _add_handler(self, handler, stream_id):
logging.debug('_add_handler, stream_id:%s', stream_id)
handler.stream_id = stream_id
handler.http2 = self
handler.remote_address = self._get_remote_address()
handler.client_certificate = self._get_client_certificate()
self.handlers.add(handler)
def _rst_stream(self, stream_id,
error_code=cnghttp2.NGHTTP2_INTERNAL_ERROR):
cdef int rv
rv = cnghttp2.nghttp2_submit_rst_stream\
(self.session, cnghttp2.NGHTTP2_FLAG_NONE,
stream_id, error_code)
return rv
def _get_remote_address(self):
return self.transport.get_extra_info('peername')
def _get_client_certificate(self):
sock = self.transport.get_extra_info('socket')
try:
return sock.getpeercert()
except AttributeError:
return None
def _start_settings_timer(self):
loop = asyncio.get_event_loop()
self.settings_timer = loop.call_later(self.SETTINGS_TIMEOUT,
self._settings_timeout)
def _stop_settings_timer(self):
if self.settings_timer:
self.settings_timer.cancel()
self.settings_timer = None
def _settings_timeout(self):
cdef int rv
logging.debug('_settings_timeout')
self.settings_timer = None
rv = cnghttp2.nghttp2_session_terminate_session\
(self.session, cnghttp2.NGHTTP2_SETTINGS_TIMEOUT)
try:
self.send_data()
except Exception as err:
sys.stderr.write(traceback.format_exc())
self.transport.close()
return
def _log_request(self, handler):
now = datetime.datetime.now()
tv = time.mktime(now.timetuple())
datestr = email.utils.formatdate(timeval=tv, localtime=False,
usegmt=True)
try:
method = handler.method.decode('utf-8')
except:
method = handler.method
try:
path = handler.path.decode('utf-8')
except:
path = handler.path
logging.info('%s - - [%s] "%s %s HTTP/2" %s - %s', handler.remote_address[0],
datestr, method, path, handler.status,
'P' if handler.pushed else '-')
def close(self):
rv = cnghttp2.nghttp2_session_terminate_session\
(self.session, cnghttp2.NGHTTP2_NO_ERROR)
try:
self.send_data()
except Exception as err:
sys.stderr.write(traceback.format_exc())
self.transport.close()
return
cdef class _HTTP2SessionCore(_HTTP2SessionCoreBase):
def __cinit__(self, *args, **kwargs):
cdef cnghttp2.nghttp2_session_callbacks *callbacks
cdef cnghttp2.nghttp2_settings_entry iv[2]
cdef int rv
super(_HTTP2SessionCore, self).__init__(*args, **kwargs)
rv = cnghttp2.nghttp2_session_callbacks_new(&callbacks)
if rv != 0:
raise Exception('nghttp2_session_callbacks_new failed: {}'.format\
(_strerror(rv)))
cnghttp2.nghttp2_session_callbacks_set_on_header_callback(
callbacks, server_on_header)
cnghttp2.nghttp2_session_callbacks_set_on_begin_headers_callback(
callbacks, server_on_begin_headers)
cnghttp2.nghttp2_session_callbacks_set_on_frame_recv_callback(
callbacks, server_on_frame_recv)
cnghttp2.nghttp2_session_callbacks_set_on_stream_close_callback(
callbacks, on_stream_close)
cnghttp2.nghttp2_session_callbacks_set_on_frame_send_callback(
callbacks, server_on_frame_send)
cnghttp2.nghttp2_session_callbacks_set_on_frame_not_send_callback(
callbacks, server_on_frame_not_send)
cnghttp2.nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
callbacks, on_data_chunk_recv)
rv = cnghttp2.nghttp2_session_server_new(&self.session, callbacks,
<void*>self)
cnghttp2.nghttp2_session_callbacks_del(callbacks)
if rv != 0:
raise Exception('nghttp2_session_server_new failed: {}'.format\
(_strerror(rv)))
iv[0].settings_id = cnghttp2.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS
iv[0].value = 100
iv[1].settings_id = cnghttp2.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE
iv[1].value = cnghttp2.NGHTTP2_INITIAL_WINDOW_SIZE
rv = cnghttp2.nghttp2_submit_settings(self.session,
cnghttp2.NGHTTP2_FLAG_NONE,
iv, sizeof(iv) / sizeof(iv[0]))
if rv != 0:
raise Exception('nghttp2_submit_settings failed: {}'.format\
(_strerror(rv)))
def send_response(self, handler):
cdef cnghttp2.nghttp2_data_provider prd
cdef cnghttp2.nghttp2_data_provider *prd_ptr
cdef cnghttp2.nghttp2_nv *nva
cdef size_t nvlen
cdef int rv
logging.debug('send_response, stream_id:%s', handler.stream_id)
nva = NULL
nvlen = _make_nva(&nva, handler.response_headers)
if handler.response_body:
prd.source.ptr = <void*>handler.response_body
prd.read_callback = data_source_read
prd_ptr = &prd
else:
prd_ptr = NULL
rv = cnghttp2.nghttp2_submit_response(self.session, handler.stream_id,
nva, nvlen, prd_ptr)
free(nva)
if rv != 0:
# TODO Ignore return value
self._rst_stream(handler.stream_id)
raise Exception('nghttp2_submit_response failed: {}'.format\
(_strerror(rv)))
self._log_request(handler)
def push(self, handler, promised_handler):
cdef cnghttp2.nghttp2_nv *nva
cdef size_t nvlen
cdef int32_t promised_stream_id
self.handlers.add(promised_handler)
nva = NULL
nvlen = _make_nva(&nva, promised_handler.headers)
promised_stream_id = cnghttp2.nghttp2_submit_push_promise\
(self.session,
cnghttp2.NGHTTP2_FLAG_NONE,
handler.stream_id,
nva, nvlen,
<void*>promised_handler)
if promised_stream_id < 0:
raise Exception('nghttp2_submit_push_promise failed: {}'.format\
(_strerror(promised_stream_id)))
promised_handler.stream_id = promised_stream_id
logging.debug('push, stream_id:%s', promised_stream_id)
return promised_handler
def connection_lost(self):
self._stop_settings_timer()
for handler in self.handlers:
handler.on_close(cnghttp2.NGHTTP2_INTERNAL_ERROR)
self.handlers = set()
cdef class _HTTP2ClientSessionCore(_HTTP2SessionCoreBase):
def __cinit__(self, *args, **kwargs):
cdef cnghttp2.nghttp2_session_callbacks *callbacks
cdef cnghttp2.nghttp2_settings_entry iv[2]
cdef int rv
super(_HTTP2ClientSessionCore, self).__init__(*args, **kwargs)
rv = cnghttp2.nghttp2_session_callbacks_new(&callbacks)
if rv != 0:
raise Exception('nghttp2_session_callbacks_new failed: {}'.format\
(_strerror(rv)))
cnghttp2.nghttp2_session_callbacks_set_on_header_callback(
callbacks, client_on_header)
cnghttp2.nghttp2_session_callbacks_set_on_begin_headers_callback(
callbacks, client_on_begin_headers)
cnghttp2.nghttp2_session_callbacks_set_on_frame_recv_callback(
callbacks, client_on_frame_recv)
cnghttp2.nghttp2_session_callbacks_set_on_stream_close_callback(
callbacks, on_stream_close)
cnghttp2.nghttp2_session_callbacks_set_on_frame_send_callback(
callbacks, client_on_frame_send)
cnghttp2.nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
callbacks, on_data_chunk_recv)
rv = cnghttp2.nghttp2_session_client_new(&self.session, callbacks,
<void*>self)
cnghttp2.nghttp2_session_callbacks_del(callbacks)
if rv != 0:
raise Exception('nghttp2_session_client_new failed: {}'.format\
(_strerror(rv)))
iv[0].settings_id = cnghttp2.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS
iv[0].value = 100
iv[1].settings_id = cnghttp2.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE
iv[1].value = cnghttp2.NGHTTP2_INITIAL_WINDOW_SIZE
rv = cnghttp2.nghttp2_submit_settings(self.session,
cnghttp2.NGHTTP2_FLAG_NONE,
iv, sizeof(iv) / sizeof(iv[0]))
if rv != 0:
raise Exception('nghttp2_submit_settings failed: {}'.format\
(_strerror(rv)))
def send_request(self, method, scheme, host, path, headers, body, handler):
cdef cnghttp2.nghttp2_data_provider prd
cdef cnghttp2.nghttp2_data_provider *prd_ptr
cdef cnghttp2.nghttp2_priority_spec *pri_ptr
cdef cnghttp2.nghttp2_nv *nva
cdef size_t nvlen
cdef int32_t stream_id
body = wrap_body(body)
custom_headers = _encode_headers(headers)
headers = [
(b':method', method.encode('utf-8')),
(b':scheme', scheme.encode('utf-8')),
(b':authority', host.encode('utf-8')),
(b':path', path.encode('utf-8'))
]
headers.extend(custom_headers)
nva = NULL
nvlen = _make_nva(&nva, headers)