123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291(*----------------------------------------------------------------------------
* Copyright (c) 2019-2020 António Nuno Monteiro
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*---------------------------------------------------------------------------*)moduleWindowSize=structtypet=int32(* From RFC7540§6.9.2:
* When an HTTP/2 connection is first established, new streams are created
* with an initial flow-control window size of 65,535 octets. *)letdefault_initial_window_size=65535l(* From RFC7540§6.9:
* The legal range for the increment to the flow-control window is 1 to
* 2^31-1 (2,147,483,647) octets. *)letmax_window_size=Int32.max_int(* Ideally `n` here would be an unsigned 32-bit integer, but OCaml doesn't
* support them. We avoid introducing a new dependency on an unsigned integer
* library by letting it overflow at parse time and checking if bit 31 is set
* here, since * `Window.max_window_size` is never allowed to be above
* 2^31-1 (see `max_window_size` above).
* See http://caml.inria.fr/pub/ml-archives/caml-list/2004/07/f1c483068cc62075c916f7ad7d640ce0.fr.html
* for more info. *)letis_window_overflown=Util.test_bit_int32n31endtypesetting=|HeaderTableSizeofint|EnablePushofint|MaxConcurrentStreamsofint32|InitialWindowSizeofint32|MaxFrameSize(* this means payload size *)ofint|MaxHeaderListSizeofinttypesettings_list=settinglist(* From RFC7540§6.5.1:
* The payload of a SETTINGS frame consists of zero or more parameters,
* each consisting of an unsigned 16-bit setting identifier and an
* unsigned 32-bit value. *)letoctets_per_setting=6letserialize_key=function|HeaderTableSize_->0x1|EnablePush_->0x2|MaxConcurrentStreams_->0x3|InitialWindowSize_->0x4|MaxFrameSize_->0x5|MaxHeaderListSize_->0x6letcheck_value~is_client=function|EnablePushv->ifv<>0&&v<>1then(* From RFC7540§6.5.2
* The initial value is 1, which indicates that server push is
* permitted. Any value other than 0 or 1 MUST be treated as a
* connection error (Section 5.4.1) of type PROTOCOL_ERROR. *)ErrorError.(ConnectionError(ProtocolError,"SETTINGS_ENABLE_PUSH must be 0 or 1"))elseifis_client&&v=1then(* From RFC7540§8.2:
* Clients MUST reject any attempt to change the
* SETTINGS_ENABLE_PUSH setting to a value other than 0 by
* treating the message as a connection error (Section 5.4.1) of
* type PROTOCOL_ERROR. *)ErrorError.(ConnectionError(ProtocolError,"Server must not try to enable SETTINGS_ENABLE_PUSH"))elseOk()|InitialWindowSizevwhenWindowSize.is_window_overflowv->(* From RFC7540§6.5.2
* Values above the maximum flow-control window size of 2^31-1 MUST be
* treated as a connection error (Section 5.4.1) of type
* FLOW_CONTROL_ERROR. *)ErrorError.(ConnectionError(FlowControlError,Format.sprintf"Window size must be less than or equal to %ld"WindowSize.max_window_size))|MaxFrameSizevwhenv<16384||v>16777215->(* From RFC7540§6.5.2
* The initial value is 214 (16,384) octets. The value advertised by an
* endpoint MUST be between this initial value and the maximum allowed
* frame size (224-1 or 16,777,215 octets), inclusive. Values outside
* this range MUST be treated as a connection error (Section 5.4.1) of
* type PROTOCOL_ERROR. *)ErrorError.(ConnectionError(ProtocolError,"Max frame size must be in the 16384 - 16777215 range"))|_->Ok()(* Check incoming settings and report an error if any. *)letcheck_settings_list?(is_client=false)settings=letrecloop=function|[]->Ok()|x::xs->(matchcheck_value~is_clientxwith|Ok()->loopxs|Error_aserr->err)inloopsettingstypet={header_table_size:int;enable_push:bool;max_concurrent_streams:int32;(* Indicates the amount tokens the peer allows an H2 endpoint to send. *)initial_window_size:WindowSize.t;max_frame_size:int;max_header_list_size:intoption}(* From RFC7540§11.3 *)letdefault={header_table_size=0x1000;enable_push=true(* From RFC7540§6.5.2:
* SETTINGS_MAX_CONCURRENT_STREAMS (0x3): [...] Initially, there is no
* limit to this value. *);max_concurrent_streams=Int32.max_int;initial_window_size=WindowSize.default_initial_window_size;max_frame_size=0x4000;max_header_list_size=None}letsettings_for_the_connectionsettings=letsettings_list=ifsettings.max_frame_size<>default.max_frame_sizethen[MaxFrameSizesettings.max_frame_size]else[]inletsettings_list=ifsettings.max_concurrent_streams<>default.max_concurrent_streamsthenMaxConcurrentStreamssettings.max_concurrent_streams::settings_listelsesettings_listinletsettings_list=ifsettings.initial_window_size<>default.initial_window_sizethen(* FIXME: don't convert *)InitialWindowSizesettings.initial_window_size::settings_listelsesettings_listinletsettings_list=ifsettings.enable_push<>default.enable_pushthenEnablePush(ifsettings.enable_pushthen1else0)::settings_listelsesettings_listinsettings_listletparse_settings_payloadnum_settings=letopenAngstrominletrecparse_inneraccremaining=(* From RFC7540§6.5.3:
* The values in the SETTINGS frame MUST be processed in the order
* they appear, with no other frame processing between values. *)ifremaining<=0thenreturn(List.revacc)elselift2(funk(v:int32)->matchkwith|0x1->HeaderTableSize(Int32.to_intv)::acc|0x2->EnablePush(Int32.to_intv)::acc|0x3->MaxConcurrentStreamsv::acc|0x4->InitialWindowSizev::acc|0x5->MaxFrameSize(Int32.to_intv)::acc|0x6->MaxHeaderListSize(Int32.to_intv)::acc|_->(* Note: This ignores unknown settings.
*
* From RFC7540§6.5.3:
* Unsupported parameters MUST be ignored.
*)acc)BE.any_uint16BE.any_int32>>=funacc'->parse_inneracc'(remaining-1)inparse_inner[]num_settingsletwrite_settings_payloadtsettings_list=letopenFaradayinList.iter(funsetting->(* From RFC7540§6.5.1:
* The payload of a SETTINGS frame consists of zero or more parameters,
* each consisting of an unsigned 16-bit setting identifier and an
* unsigned 32-bit value. *)BE.write_uint16t(serialize_keysetting);matchsettingwith|MaxConcurrentStreamsvalue|InitialWindowSizevalue->BE.write_uint32tvalue|HeaderTableSizevalue|EnablePushvalue|MaxFrameSizevalue|MaxHeaderListSizevalue->BE.write_uint32t(Int32.of_intvalue))settings_listletof_settings_listsettings=List.fold_left(fun(acc:t)item->matchitemwith|HeaderTableSizex->{accwithheader_table_size=x}|EnablePushx->{accwithenable_push=x=1}|MaxConcurrentStreamsx->{accwithmax_concurrent_streams=x}|InitialWindowSizenew_val->{accwithinitial_window_size=new_val}|MaxFrameSizex->{accwithmax_frame_size=x}|MaxHeaderListSizex->{accwithmax_header_list_size=Somex})defaultsettingsletof_base64encoded=matchBase64.decode~alphabet:Base64.uri_safe_alphabetencodedwith|Oksettings_payload->letsettings_payload_length=String.lengthsettings_payload/octets_per_settingin(matchAngstrom.parse_string~consume:All(parse_settings_payloadsettings_payload_length)settings_payloadwith|Oksettings->Ok(of_settings_listsettings)|Error_ase->e)|Error(`Msgmsg)->Errormsgletto_base64t=letsettings=settings_for_the_connectiontinletfaraday=Faraday.create(List.lengthsettings*6)inwrite_settings_payloadfaradaysettings;letsettings_hex=Faraday.serialize_to_stringfaradayinmatchBase64.encode~alphabet:Base64.uri_safe_alphabetsettings_hexwith|Okr->Okr|Error(`Msgmsg)->Errormsgletpp_humformattert=letpp_elemformattersetting=letkey,value=matchsettingwith|HeaderTableSizev->"HEADER_TABLE_SIZE",Int64.of_intv|EnablePushv->"ENABLE_PUSH",Int64.of_intv|MaxConcurrentStreamsv->"MAX_CONCURRENT_STREAMS",Int64.of_int32v|InitialWindowSizev->"INITIAL_WINDOW_SIZE",Int64.of_int32v|MaxFrameSizev->"MAX_FRAME_SIZE",Int64.of_intv|MaxHeaderListSizev->"MAX_HEADER_LIST_SIZE",Int64.of_intvinFormat.fprintfformatter"@[(%S %Ld)@]"keyvalueinFormat.fprintfformatter"@[(";Format.pp_print_listpp_elemformatter(settings_for_the_connectiont);Format.fprintfformatter")@]"