l2cap.c 178 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122
  1. /*
  2. * Copyright (C) 2014 BlueKitchen GmbH
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. Neither the name of the copyright holders nor the names of
  14. * contributors may be used to endorse or promote products derived
  15. * from this software without specific prior written permission.
  16. * 4. Any redistribution, use, or modification is done solely for
  17. * personal benefit and not for any commercial purpose or for
  18. * monetary gain.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
  21. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  23. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
  24. * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  25. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  26. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  27. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  28. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  29. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. * SUCH DAMAGE.
  32. *
  33. * Please inquire about commercial licensing options at
  34. * contact@bluekitchen-gmbh.com
  35. *
  36. */
  37. #define BTSTACK_FILE__ "l2cap.c"
  38. /*
  39. * l2cap.c
  40. *
  41. * Logical Link Control and Adaption Protocl (L2CAP)
  42. *
  43. * Created by Matthias Ringwald on 5/16/09.
  44. */
  45. #include "l2cap.h"
  46. #include "hci.h"
  47. #include "hci_dump.h"
  48. #include "bluetooth_sdp.h"
  49. #include "bluetooth_psm.h"
  50. #include "btstack_bool.h"
  51. #include "btstack_debug.h"
  52. #include "btstack_event.h"
  53. #include "btstack_memory.h"
  54. #include <stdarg.h>
  55. #include <string.h>
  56. /*
  57. * @brief L2CAP Supervisory function in S-Frames
  58. */
  59. typedef enum {
  60. L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
  61. L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
  62. L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
  63. L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
  64. } l2cap_supervisory_function_t;
  65. /**
  66. * @brief L2CAP Information Types used in Information Request & Response
  67. */
  68. typedef enum {
  69. L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
  70. L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
  71. L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
  72. } l2cap_info_type_t;
  73. /**
  74. * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
  75. */
  76. typedef enum {
  77. L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
  78. L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
  79. L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
  80. L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
  81. L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
  82. L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
  83. L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
  84. } l2cap_config_option_type_t;
  85. #define L2CAP_SIG_ID_INVALID 0
  86. // size of HCI ACL + L2CAP Header for regular data packets (8)
  87. #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
  88. // L2CAP Configuration Result Codes
  89. #define L2CAP_CONF_RESULT_SUCCESS 0x0000
  90. #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS 0x0001
  91. #define L2CAP_CONF_RESULT_REJECT 0x0002
  92. #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS 0x0003
  93. #define L2CAP_CONF_RESULT_PENDING 0x0004
  94. #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED 0x0005
  95. // L2CAP Reject Result Codes
  96. #define L2CAP_REJ_CMD_UNKNOWN 0x0000
  97. // Response Timeout eXpired
  98. #define L2CAP_RTX_TIMEOUT_MS 10000
  99. // Extended Response Timeout eXpired
  100. #define L2CAP_ERTX_TIMEOUT_MS 120000
  101. // nr of buffered acl packets in outgoing queue to get max performance
  102. #define NR_BUFFERED_ACL_PACKETS 3
  103. // used to cache l2cap rejects, echo, and informational requests
  104. #define NR_PENDING_SIGNALING_RESPONSES 3
  105. // nr of credits provided to remote if credits fall below watermark
  106. #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
  107. #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
  108. // offsets for L2CAP SIGNALING COMMANDS
  109. #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET 0
  110. #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET 1
  111. #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
  112. #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET 4
  113. #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
  114. #define L2CAP_USES_CHANNELS
  115. #endif
  116. // prototypes
  117. static void l2cap_run(void);
  118. static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
  119. static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
  120. static void l2cap_notify_channel_can_send(void);
  121. static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
  122. static uint8_t l2cap_next_sig_id(void);
  123. static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
  124. #ifdef ENABLE_CLASSIC
  125. static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
  126. static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
  127. static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
  128. static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
  129. static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
  130. static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
  131. static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
  132. static int l2cap_channel_ready_for_open(l2cap_channel_t *channel);
  133. #endif
  134. #ifdef ENABLE_LE_DATA_CHANNELS
  135. static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
  136. static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel);
  137. static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
  138. static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
  139. static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
  140. static void l2cap_le_send_pdu(l2cap_channel_t *channel);
  141. static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
  142. #endif
  143. #ifdef L2CAP_USES_CHANNELS
  144. static uint16_t l2cap_next_local_cid(void);
  145. static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
  146. static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
  147. static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
  148. static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
  149. static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
  150. uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
  151. static void l2cap_free_channel_entry(l2cap_channel_t * channel);
  152. #endif
  153. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  154. static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
  155. static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
  156. static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
  157. #endif
  158. // l2cap_fixed_channel_t entries
  159. #ifdef ENABLE_BLE
  160. static l2cap_fixed_channel_t l2cap_fixed_channel_att;
  161. static l2cap_fixed_channel_t l2cap_fixed_channel_sm;
  162. #endif
  163. #ifdef ENABLE_CLASSIC
  164. static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless;
  165. #endif
  166. #ifdef ENABLE_CLASSIC
  167. static btstack_linked_list_t l2cap_services;
  168. static uint8_t require_security_level2_for_outgoing_sdp;
  169. static bd_addr_t l2cap_outgoing_classic_addr;
  170. #endif
  171. #ifdef ENABLE_LE_DATA_CHANNELS
  172. static btstack_linked_list_t l2cap_le_services;
  173. #endif
  174. // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM
  175. static btstack_linked_list_t l2cap_channels;
  176. #ifdef L2CAP_USES_CHANNELS
  177. // next channel id for new connections
  178. static uint16_t local_source_cid = 0x40;
  179. #endif
  180. // next signaling sequence number
  181. static uint8_t sig_seq_nr = 0xff;
  182. // used to cache l2cap rejects, echo, and informational requests
  183. static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
  184. static int signaling_responses_pending;
  185. static btstack_packet_callback_registration_t hci_event_callback_registration;
  186. #ifdef ENABLE_BLE
  187. // only used for connection parameter update events
  188. static btstack_packet_handler_t l2cap_event_packet_handler;
  189. static uint16_t l2cap_le_custom_max_mtu;
  190. #endif
  191. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  192. // enable for testing
  193. // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
  194. /*
  195. * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
  196. */
  197. static const uint16_t crc16_table[256] = {
  198. 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
  199. 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
  200. 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
  201. 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
  202. 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
  203. 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
  204. 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
  205. 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
  206. 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
  207. 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
  208. 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
  209. 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
  210. 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
  211. 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
  212. 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
  213. 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
  214. };
  215. static uint16_t crc16_calc(uint8_t * data, uint16_t len){
  216. uint16_t crc = 0; // initial value = 0
  217. while (len--){
  218. crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
  219. }
  220. return crc;
  221. }
  222. static inline uint16_t l2cap_encanced_control_field_for_information_frame(uint8_t tx_seq, int final, uint8_t req_seq, l2cap_segmentation_and_reassembly_t sar){
  223. return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
  224. }
  225. static inline uint16_t l2cap_encanced_control_field_for_supevisor_frame(l2cap_supervisory_function_t supervisory_function, int poll, int final, uint8_t req_seq){
  226. return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
  227. }
  228. static int l2cap_next_ertm_seq_nr(int seq_nr){
  229. return (seq_nr + 1) & 0x3f;
  230. }
  231. static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
  232. // get num free tx buffers
  233. int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
  234. // calculate num tx buffers for remote MTU
  235. int num_tx_buffers_for_max_remote_mtu;
  236. uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
  237. if (channel->remote_mtu <= effective_mps){
  238. // MTU fits into single packet
  239. num_tx_buffers_for_max_remote_mtu = 1;
  240. } else {
  241. // include SDU Length
  242. num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
  243. }
  244. log_debug("num_free_tx_buffers %u, num_tx_buffers_for_max_remote_mtu %u", num_free_tx_buffers, num_tx_buffers_for_max_remote_mtu);
  245. return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
  246. }
  247. static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
  248. log_info("Retransmit unacknowleged frames");
  249. l2cap_channel->unacked_frames = 0;;
  250. l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
  251. }
  252. static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
  253. channel->tx_write_index++;
  254. if (channel->tx_write_index < channel->num_tx_buffers) return;
  255. channel->tx_write_index = 0;
  256. }
  257. static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
  258. log_info("Start Monitor timer");
  259. btstack_run_loop_remove_timer(&channel->monitor_timer);
  260. btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
  261. btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
  262. btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
  263. btstack_run_loop_add_timer(&channel->monitor_timer);
  264. }
  265. static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
  266. log_info("Stop Monitor timer");
  267. btstack_run_loop_remove_timer(&channel->monitor_timer);
  268. }
  269. static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
  270. log_info("Start Retransmission timer");
  271. btstack_run_loop_remove_timer(&channel->retransmission_timer);
  272. btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
  273. btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
  274. btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
  275. btstack_run_loop_add_timer(&channel->retransmission_timer);
  276. }
  277. static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
  278. log_info("Stop Retransmission timer");
  279. btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
  280. }
  281. static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
  282. log_info("Monitor timeout");
  283. l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
  284. // TODO: we assume that it's the oldest packet
  285. l2cap_ertm_tx_packet_state_t * tx_state;
  286. tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
  287. // check retry count
  288. if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
  289. // increment retry count
  290. tx_state->retry_count++;
  291. // start retransmit
  292. l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
  293. // start monitor timer
  294. l2cap_ertm_start_monitor_timer(l2cap_channel);
  295. // send RR/P=1
  296. l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
  297. } else {
  298. log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
  299. l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  300. }
  301. l2cap_run();
  302. }
  303. static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
  304. log_info("Retransmission timeout");
  305. l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
  306. // TODO: we assume that it's the oldest packet
  307. l2cap_ertm_tx_packet_state_t * tx_state;
  308. tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
  309. // set retry count = 1
  310. tx_state->retry_count = 1;
  311. // start retransmit
  312. l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
  313. // start monitor timer
  314. l2cap_ertm_start_monitor_timer(l2cap_channel);
  315. // send RR/P=1
  316. l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
  317. l2cap_run();
  318. }
  319. static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
  320. l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
  321. hci_reserve_packet_buffer();
  322. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  323. uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
  324. log_info("I-Frame: control 0x%04x", control);
  325. little_endian_store_16(acl_buffer, 8, control);
  326. (void)memcpy(&acl_buffer[8 + 2],
  327. &channel->tx_packets_data[index * channel->local_mps],
  328. tx_state->len);
  329. // (re-)start retransmission timer on
  330. l2cap_ertm_start_retransmission_timer(channel);
  331. // send
  332. return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
  333. }
  334. static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){
  335. // get next index for storing packets
  336. int index = channel->tx_write_index;
  337. l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
  338. tx_state->tx_seq = channel->next_tx_seq;
  339. tx_state->sar = sar;
  340. tx_state->retry_count = 0;
  341. uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
  342. log_debug("index %u, local mps %u, remote mps %u, packet tx %p, len %u", index, channel->local_mps, channel->remote_mps, tx_packet, len);
  343. int pos = 0;
  344. if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
  345. little_endian_store_16(tx_packet, 0, sdu_length);
  346. pos += 2;
  347. }
  348. (void)memcpy(&tx_packet[pos], data, len);
  349. tx_state->len = pos + len;
  350. // update
  351. channel->num_stored_tx_frames++;
  352. channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
  353. l2cap_ertm_next_tx_write_index(channel);
  354. log_info("l2cap_ertm_store_fragment: tx_read_index %u, tx_write_index %u, num stored %u", channel->tx_read_index, channel->tx_write_index, channel->num_stored_tx_frames);
  355. }
  356. static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
  357. if (len > channel->remote_mtu){
  358. log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
  359. return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
  360. }
  361. if (!l2cap_ertm_can_store_packet_now(channel)){
  362. log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
  363. return BTSTACK_ACL_BUFFERS_FULL;
  364. }
  365. // check if it needs to get fragmented
  366. uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
  367. if (len > effective_mps){
  368. // fragmentation needed.
  369. l2cap_segmentation_and_reassembly_t sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
  370. int chunk_len;
  371. while (len){
  372. switch (sar){
  373. case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
  374. chunk_len = effective_mps - 2; // sdu_length
  375. l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
  376. len -= chunk_len;
  377. sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
  378. break;
  379. case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
  380. chunk_len = effective_mps;
  381. if (chunk_len >= len){
  382. sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
  383. chunk_len = len;
  384. }
  385. l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
  386. len -= chunk_len;
  387. break;
  388. default:
  389. break;
  390. }
  391. }
  392. } else {
  393. l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
  394. }
  395. // try to send
  396. l2cap_notify_channel_can_send();
  397. return 0;
  398. }
  399. static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
  400. int pos = 0;
  401. config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
  402. config_options[pos++] = 9; // length
  403. config_options[pos++] = (uint8_t) channel->mode;
  404. config_options[pos++] = channel->num_rx_buffers; // == TxWindows size
  405. config_options[pos++] = channel->local_max_transmit;
  406. little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
  407. pos += 2;
  408. little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
  409. pos += 2;
  410. little_endian_store_16( config_options, pos, channel->local_mps);
  411. pos += 2;
  412. //
  413. config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
  414. config_options[pos++] = 2; // length
  415. little_endian_store_16(config_options, pos, channel->local_mtu);
  416. pos += 2;
  417. // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
  418. // Workaround: try to actively negotiate FCS option
  419. config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
  420. config_options[pos++] = 1; // length
  421. config_options[pos++] = channel->fcs_option;
  422. return pos; // 11+4+3=18
  423. }
  424. static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
  425. int pos = 0;
  426. config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
  427. config_options[pos++] = 9; // length
  428. config_options[pos++] = (uint8_t) channel->mode;
  429. // less or equal to remote tx window size
  430. config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
  431. // max transmit in response shall be ignored -> use sender values
  432. config_options[pos++] = channel->remote_max_transmit;
  433. // A value for the Retransmission time-out shall be sent in a positive Configuration Response
  434. // and indicates the value that will be used by the sender of the Configuration Response -> use our value
  435. little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
  436. pos += 2;
  437. // A value for the Monitor time-out shall be sent in a positive Configuration Response
  438. // and indicates the value that will be used by the sender of the Configuration Response -> use our value
  439. little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
  440. pos += 2;
  441. // less or equal to remote mps
  442. uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
  443. little_endian_store_16( config_options, pos, effective_mps);
  444. pos += 2;
  445. //
  446. config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
  447. config_options[pos++] = 2; // length
  448. little_endian_store_16(config_options, pos, channel->remote_mtu);
  449. pos += 2;
  450. #if 0
  451. //
  452. config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
  453. config_options[pos++] = 1; // length
  454. config_options[pos++] = channel->fcs_option;
  455. #endif
  456. return pos; // 11+4=15
  457. }
  458. static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
  459. hci_reserve_packet_buffer();
  460. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  461. log_info("S-Frame: control 0x%04x", control);
  462. little_endian_store_16(acl_buffer, 8, control);
  463. return l2cap_send_prepared(channel->local_cid, 2);
  464. }
  465. static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
  466. uint8_t result = ERROR_CODE_SUCCESS;
  467. if (ertm_config->max_transmit < 1){
  468. log_error("max_transmit must be >= 1");
  469. result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
  470. }
  471. if (ertm_config->retransmission_timeout_ms < 2000){
  472. log_error("retransmission_timeout_ms must be >= 2000 ms");
  473. result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
  474. }
  475. if (ertm_config->monitor_timeout_ms < 12000){
  476. log_error("monitor_timeout_ms must be >= 12000 ms");
  477. result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
  478. }
  479. if (ertm_config->local_mtu < 48){
  480. log_error("local_mtu must be >= 48");
  481. result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
  482. }
  483. if (ertm_config->num_rx_buffers < 1){
  484. log_error("num_rx_buffers must be >= 1");
  485. result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
  486. }
  487. if (ertm_config->num_tx_buffers < 1){
  488. log_error("num_rx_buffers must be >= 1");
  489. result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
  490. }
  491. return result;
  492. }
  493. static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
  494. channel->mode = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
  495. channel->ertm_mandatory = ertm_config->ertm_mandatory;
  496. channel->local_max_transmit = ertm_config->max_transmit;
  497. channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
  498. channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
  499. channel->local_mtu = ertm_config->local_mtu;
  500. channel->num_rx_buffers = ertm_config->num_rx_buffers;
  501. channel->num_tx_buffers = ertm_config->num_tx_buffers;
  502. // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
  503. int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
  504. buffer += bytes_till_alignment;
  505. size -= bytes_till_alignment;
  506. // setup state buffers - use void cast to avoid -Wcast-align warning
  507. uint32_t pos = 0;
  508. channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
  509. pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
  510. channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
  511. pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
  512. // setup reassembly buffer
  513. channel->reassembly_buffer = &buffer[pos];
  514. pos += ertm_config->local_mtu;
  515. // divide rest of data equally
  516. channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
  517. log_info("Local MPS: %u", channel->local_mps);
  518. channel->rx_packets_data = &buffer[pos];
  519. pos += ertm_config->num_rx_buffers * channel->local_mps;
  520. channel->tx_packets_data = &buffer[pos];
  521. channel->fcs_option = ertm_config->fcs_option;
  522. }
  523. uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
  524. l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
  525. log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
  526. // validate local config
  527. uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
  528. if (result) return result;
  529. l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0);
  530. if (!channel) {
  531. return BTSTACK_MEMORY_ALLOC_FAILED;
  532. }
  533. // configure ERTM
  534. l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
  535. // add to connections list
  536. btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
  537. // store local_cid
  538. if (out_local_cid){
  539. *out_local_cid = channel->local_cid;
  540. }
  541. // check if hci connection is already usable
  542. hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
  543. if (conn){
  544. log_info("l2cap_create_channel, hci connection already exists");
  545. l2cap_handle_connection_complete(conn->con_handle, channel);
  546. // check if remote supported fearures are already received
  547. if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
  548. l2cap_handle_remote_supported_features_received(channel);
  549. }
  550. }
  551. l2cap_run();
  552. return 0;
  553. }
  554. static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
  555. if (l2cap_ertm_can_store_packet_now(channel)){
  556. channel->waiting_for_can_send_now = 0;
  557. l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
  558. }
  559. }
  560. uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
  561. log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
  562. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  563. if (!channel) {
  564. log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
  565. return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  566. }
  567. // validate local config
  568. uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
  569. if (result) return result;
  570. // configure L2CAP ERTM
  571. l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
  572. // default: continue
  573. channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
  574. // verify remote ERTM support
  575. hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
  576. if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
  577. if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
  578. // ERTM not possible, select basic mode and release buffer
  579. channel->mode = L2CAP_CHANNEL_MODE_BASIC;
  580. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
  581. // bail if ERTM is mandatory
  582. if (channel->ertm_mandatory){
  583. // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
  584. log_info("ERTM mandatory -> reject connection");
  585. channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
  586. channel->reason = 0x04; // no resources available
  587. } else {
  588. log_info("ERTM not supported by remote -> use Basic mode");
  589. }
  590. }
  591. // process
  592. l2cap_run();
  593. return ERROR_CODE_SUCCESS;
  594. }
  595. uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
  596. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
  597. if (!channel) {
  598. log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
  599. return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  600. }
  601. if (!channel->local_busy){
  602. channel->local_busy = 1;
  603. channel->send_supervisor_frame_receiver_not_ready = 1;
  604. l2cap_run();
  605. }
  606. return ERROR_CODE_SUCCESS;
  607. }
  608. uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
  609. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
  610. if (!channel) {
  611. log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
  612. return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  613. }
  614. if (channel->local_busy){
  615. channel->local_busy = 0;
  616. channel->send_supervisor_frame_receiver_ready_poll = 1;
  617. l2cap_run();
  618. }
  619. return ERROR_CODE_SUCCESS;
  620. }
  621. // Process-ReqSeq
  622. static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
  623. int num_buffers_acked = 0;
  624. l2cap_ertm_tx_packet_state_t * tx_state;
  625. log_info("l2cap_ertm_process_req_seq: tx_read_index %u, tx_write_index %u, req_seq %u", l2cap_channel->tx_read_index, l2cap_channel->tx_write_index, req_seq);
  626. while (true){
  627. // no unack packets left
  628. if (l2cap_channel->unacked_frames == 0) {
  629. // stop retransmission timer
  630. l2cap_ertm_stop_retransmission_timer(l2cap_channel);
  631. break;
  632. }
  633. tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
  634. // calc delta
  635. int delta = (req_seq - tx_state->tx_seq) & 0x03f;
  636. if (delta == 0) break; // all packets acknowledged
  637. if (delta > l2cap_channel->remote_tx_window_size) break;
  638. num_buffers_acked++;
  639. l2cap_channel->num_stored_tx_frames--;
  640. l2cap_channel->unacked_frames--;
  641. log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
  642. l2cap_channel->tx_read_index++;
  643. if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
  644. l2cap_channel->tx_read_index = 0;
  645. }
  646. }
  647. if (num_buffers_acked){
  648. log_info("num_buffers_acked %u", num_buffers_acked);
  649. l2cap_ertm_notify_channel_can_send(l2cap_channel);
  650. }
  651. }
  652. static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
  653. int i;
  654. for (i=0;i<l2cap_channel->num_tx_buffers;i++){
  655. l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
  656. if (tx_state->tx_seq == tx_seq) return tx_state;
  657. }
  658. return NULL;
  659. }
  660. // @param delta number of frames in the future, >= 1
  661. // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
  662. static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, const uint8_t * payload, uint16_t size){
  663. log_info("Store SDU with delta %u", delta);
  664. // get rx state for packet to store
  665. int index = l2cap_channel->rx_store_index + delta - 1;
  666. if (index > l2cap_channel->num_rx_buffers){
  667. index -= l2cap_channel->num_rx_buffers;
  668. }
  669. log_info("Index of packet to store %u", index);
  670. l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
  671. // check if buffer is free
  672. if (rx_state->valid){
  673. log_error("Packet buffer already used");
  674. return;
  675. }
  676. rx_state->valid = 1;
  677. rx_state->sar = sar;
  678. rx_state->len = size;
  679. uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
  680. (void)memcpy(rx_buffer, payload, size);
  681. }
  682. // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
  683. static void l2cap_ertm_handle_in_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, const uint8_t * payload, uint16_t size){
  684. uint16_t reassembly_sdu_length;
  685. switch (sar){
  686. case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
  687. // assert total packet size <= our mtu
  688. if (size > l2cap_channel->local_mtu) break;
  689. // packet complete -> disapatch
  690. l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
  691. break;
  692. case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
  693. // read SDU len
  694. reassembly_sdu_length = little_endian_read_16(payload, 0);
  695. payload += 2;
  696. size -= 2;
  697. // assert reassembled size <= our mtu
  698. if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
  699. // store start segment
  700. l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
  701. (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
  702. l2cap_channel->reassembly_pos = size;
  703. break;
  704. case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
  705. // assert size of reassembled data <= our mtu
  706. if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
  707. // store continuation segment
  708. (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
  709. payload, size);
  710. l2cap_channel->reassembly_pos += size;
  711. break;
  712. case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
  713. // assert size of reassembled data <= our mtu
  714. if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
  715. // store continuation segment
  716. (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
  717. payload, size);
  718. l2cap_channel->reassembly_pos += size;
  719. // assert size of reassembled data matches announced sdu length
  720. if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
  721. // packet complete -> disapatch
  722. l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
  723. l2cap_channel->reassembly_pos = 0;
  724. break;
  725. }
  726. }
  727. static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
  728. channel->unacked_frames++;
  729. int index = channel->tx_send_index;
  730. channel->tx_send_index++;
  731. if (channel->tx_send_index >= channel->num_tx_buffers){
  732. channel->tx_send_index = 0;
  733. }
  734. l2cap_ertm_send_information_frame(channel, index, 0); // final = 0
  735. }
  736. #endif
  737. #ifdef L2CAP_USES_CHANNELS
  738. static uint16_t l2cap_next_local_cid(void){
  739. do {
  740. if (local_source_cid == 0xffffu) {
  741. local_source_cid = 0x40;
  742. } else {
  743. local_source_cid++;
  744. }
  745. } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
  746. return local_source_cid;
  747. }
  748. #endif
  749. static uint8_t l2cap_next_sig_id(void){
  750. if (sig_seq_nr == 0xffu) {
  751. sig_seq_nr = 1;
  752. } else {
  753. sig_seq_nr++;
  754. }
  755. return sig_seq_nr;
  756. }
  757. void l2cap_init(void){
  758. signaling_responses_pending = 0;
  759. l2cap_channels = NULL;
  760. #ifdef ENABLE_CLASSIC
  761. l2cap_services = NULL;
  762. require_security_level2_for_outgoing_sdp = 0;
  763. // Setup Connectionless Channel
  764. l2cap_fixed_channel_connectionless.local_cid = L2CAP_CID_CONNECTIONLESS_CHANNEL;
  765. l2cap_fixed_channel_connectionless.channel_type = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
  766. btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
  767. #endif
  768. #ifdef ENABLE_LE_DATA_CHANNELS
  769. l2cap_le_services = NULL;
  770. #endif
  771. #ifdef ENABLE_BLE
  772. l2cap_event_packet_handler = NULL;
  773. l2cap_le_custom_max_mtu = 0;
  774. // Setup fixed ATT Channel
  775. l2cap_fixed_channel_att.local_cid = L2CAP_CID_ATTRIBUTE_PROTOCOL;
  776. l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
  777. btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
  778. // Setup fixed SM Channel
  779. l2cap_fixed_channel_sm.local_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
  780. l2cap_fixed_channel_sm.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
  781. btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
  782. #endif
  783. //
  784. // register callback with HCI
  785. //
  786. hci_event_callback_registration.callback = &l2cap_hci_event_handler;
  787. hci_add_event_handler(&hci_event_callback_registration);
  788. hci_register_acl_packet_handler(&l2cap_acl_handler);
  789. #ifdef ENABLE_CLASSIC
  790. gap_connectable_control(0); // no services yet
  791. #endif
  792. }
  793. void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
  794. #ifdef ENABLE_BLE
  795. l2cap_event_packet_handler = handler;
  796. #else
  797. UNUSED(handler); // ok: no code
  798. #endif
  799. }
  800. void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
  801. UNUSED(con_handle); // ok: there is no con handle
  802. l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
  803. if (!channel) return;
  804. channel->waiting_for_can_send_now = 1;
  805. l2cap_notify_channel_can_send();
  806. }
  807. int l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
  808. UNUSED(channel_id); // ok: only depends on Controller LE buffers
  809. return hci_can_send_acl_packet_now(con_handle);
  810. }
  811. uint8_t *l2cap_get_outgoing_buffer(void){
  812. return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
  813. }
  814. // only for L2CAP Basic Channels
  815. int l2cap_reserve_packet_buffer(void){
  816. return hci_reserve_packet_buffer();
  817. }
  818. // only for L2CAP Basic Channels
  819. void l2cap_release_packet_buffer(void){
  820. hci_release_packet_buffer();
  821. }
  822. static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){
  823. // 0 - Connection handle : PB=pb : BC=00
  824. little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u));
  825. // 2 - ACL length
  826. little_endian_store_16(acl_buffer, 2u, len + 4u);
  827. // 4 - L2CAP packet length
  828. little_endian_store_16(acl_buffer, 4u, len + 0u);
  829. // 6 - L2CAP channel DEST
  830. little_endian_store_16(acl_buffer, 6, remote_cid);
  831. }
  832. // assumption - only on LE connections
  833. int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
  834. if (!hci_is_packet_buffer_reserved()){
  835. log_error("l2cap_send_prepared_connectionless called without reserving packet first");
  836. return BTSTACK_ACL_BUFFERS_FULL;
  837. }
  838. if (!hci_can_send_prepared_acl_packet_now(con_handle)){
  839. log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
  840. return BTSTACK_ACL_BUFFERS_FULL;
  841. }
  842. log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
  843. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  844. l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
  845. // send
  846. return hci_send_acl_packet_buffer(len+8u);
  847. }
  848. // assumption - only on LE connections
  849. int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
  850. if (!hci_can_send_acl_packet_now(con_handle)){
  851. log_info("l2cap_send cid 0x%02x, cannot send", cid);
  852. return BTSTACK_ACL_BUFFERS_FULL;
  853. }
  854. hci_reserve_packet_buffer();
  855. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  856. (void)memcpy(&acl_buffer[8], data, len);
  857. return l2cap_send_prepared_connectionless(con_handle, cid, len);
  858. }
  859. static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
  860. log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
  861. uint8_t event[4];
  862. event[0] = L2CAP_EVENT_CAN_SEND_NOW;
  863. event[1] = sizeof(event) - 2u;
  864. little_endian_store_16(event, 2, channel);
  865. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  866. packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
  867. }
  868. #ifdef L2CAP_USES_CHANNELS
  869. static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
  870. (* (channel->packet_handler))(type, channel->local_cid, data, size);
  871. }
  872. static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
  873. uint8_t event[4];
  874. event[0] = event_code;
  875. event[1] = sizeof(event) - 2u;
  876. little_endian_store_16(event, 2, channel->local_cid);
  877. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  878. l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
  879. }
  880. #endif
  881. #ifdef ENABLE_CLASSIC
  882. void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
  883. log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u",
  884. status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
  885. channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
  886. uint8_t event[26];
  887. event[0] = L2CAP_EVENT_CHANNEL_OPENED;
  888. event[1] = sizeof(event) - 2;
  889. event[2] = status;
  890. reverse_bd_addr(channel->address, &event[3]);
  891. little_endian_store_16(event, 9, channel->con_handle);
  892. little_endian_store_16(event, 11, channel->psm);
  893. little_endian_store_16(event, 13, channel->local_cid);
  894. little_endian_store_16(event, 15, channel->remote_cid);
  895. little_endian_store_16(event, 17, channel->local_mtu);
  896. little_endian_store_16(event, 19, channel->remote_mtu);
  897. little_endian_store_16(event, 21, channel->flush_timeout);
  898. event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
  899. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  900. log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
  901. event[24] = channel->mode;
  902. event[25] = channel->fcs_option;
  903. #else
  904. event[24] = L2CAP_CHANNEL_MODE_BASIC;
  905. event[25] = 0;
  906. #endif
  907. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  908. l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
  909. }
  910. static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
  911. log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
  912. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
  913. }
  914. static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
  915. log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
  916. bd_addr_to_str(channel->address), channel->con_handle, channel->psm, channel->local_cid, channel->remote_cid);
  917. uint8_t event[16];
  918. event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
  919. event[1] = sizeof(event) - 2;
  920. reverse_bd_addr(channel->address, &event[2]);
  921. little_endian_store_16(event, 8, channel->con_handle);
  922. little_endian_store_16(event, 10, channel->psm);
  923. little_endian_store_16(event, 12, channel->local_cid);
  924. little_endian_store_16(event, 14, channel->remote_cid);
  925. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  926. l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
  927. }
  928. static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
  929. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  930. // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
  931. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  932. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
  933. }
  934. #endif
  935. l2cap_emit_channel_opened(channel, status);
  936. }
  937. static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
  938. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  939. // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
  940. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  941. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
  942. }
  943. #endif
  944. l2cap_emit_channel_closed(channel);
  945. }
  946. #endif
  947. static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
  948. btstack_linked_list_iterator_t it;
  949. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  950. while (btstack_linked_list_iterator_has_next(&it)){
  951. l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
  952. if (channel->local_cid == cid) {
  953. return channel;
  954. }
  955. }
  956. return NULL;
  957. }
  958. // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
  959. static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
  960. if (local_cid >= 0x40u) return NULL;
  961. return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
  962. }
  963. // used for Classic Channels + LE Data Channels. local_cid >= 0x40
  964. #ifdef L2CAP_USES_CHANNELS
  965. static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
  966. if (local_cid < 0x40u) return NULL;
  967. return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
  968. }
  969. void l2cap_request_can_send_now_event(uint16_t local_cid){
  970. l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
  971. if (!channel) return;
  972. channel->waiting_for_can_send_now = 1;
  973. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  974. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  975. l2cap_ertm_notify_channel_can_send(channel);
  976. return;
  977. }
  978. #endif
  979. l2cap_notify_channel_can_send();
  980. }
  981. int l2cap_can_send_packet_now(uint16_t local_cid){
  982. l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
  983. if (!channel) return 0;
  984. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  985. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  986. return l2cap_ertm_can_store_packet_now(channel);
  987. }
  988. #endif
  989. return hci_can_send_acl_packet_now(channel->con_handle);
  990. }
  991. int l2cap_can_send_prepared_packet_now(uint16_t local_cid){
  992. l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
  993. if (!channel) return 0;
  994. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  995. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  996. return 0;
  997. }
  998. #endif
  999. return hci_can_send_prepared_acl_packet_now(channel->con_handle);
  1000. }
  1001. uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
  1002. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  1003. if (channel) {
  1004. return channel->remote_mtu;
  1005. }
  1006. return 0;
  1007. }
  1008. #endif
  1009. #ifdef L2CAP_USES_CHANNELS
  1010. static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
  1011. switch (channel_type){
  1012. case L2CAP_CHANNEL_TYPE_CLASSIC:
  1013. case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
  1014. return 1;
  1015. default:
  1016. return 0;
  1017. }
  1018. }
  1019. #endif
  1020. #ifdef ENABLE_CLASSIC
  1021. // RTX Timer only exist for dynamic channels
  1022. static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
  1023. btstack_linked_list_iterator_t it;
  1024. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  1025. while (btstack_linked_list_iterator_has_next(&it)){
  1026. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  1027. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  1028. if (&channel->rtx == ts) {
  1029. return channel;
  1030. }
  1031. }
  1032. return NULL;
  1033. }
  1034. static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
  1035. l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
  1036. if (!channel) return;
  1037. log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
  1038. // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
  1039. // and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
  1040. // notify client
  1041. l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
  1042. // discard channel
  1043. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  1044. l2cap_free_channel_entry(channel);
  1045. }
  1046. #endif
  1047. #ifdef L2CAP_USES_CHANNELS
  1048. static void l2cap_stop_rtx(l2cap_channel_t * channel){
  1049. log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
  1050. btstack_run_loop_remove_timer(&channel->rtx);
  1051. }
  1052. #endif
  1053. #ifdef ENABLE_CLASSIC
  1054. static void l2cap_start_rtx(l2cap_channel_t * channel){
  1055. l2cap_stop_rtx(channel);
  1056. log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
  1057. btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
  1058. btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
  1059. btstack_run_loop_add_timer(&channel->rtx);
  1060. }
  1061. static void l2cap_start_ertx(l2cap_channel_t * channel){
  1062. log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
  1063. l2cap_stop_rtx(channel);
  1064. btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
  1065. btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
  1066. btstack_run_loop_add_timer(&channel->rtx);
  1067. }
  1068. void l2cap_require_security_level_2_for_outgoing_sdp(void){
  1069. require_security_level2_for_outgoing_sdp = 1;
  1070. }
  1071. static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
  1072. return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
  1073. }
  1074. static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
  1075. if (!hci_can_send_acl_packet_now(handle)){
  1076. log_info("l2cap_send_signaling_packet, cannot send");
  1077. return BTSTACK_ACL_BUFFERS_FULL;
  1078. }
  1079. // log_info("l2cap_send_signaling_packet type %u", cmd);
  1080. hci_reserve_packet_buffer();
  1081. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  1082. va_list argptr;
  1083. va_start(argptr, identifier);
  1084. uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
  1085. va_end(argptr);
  1086. // log_info("l2cap_send_signaling_packet con %u!", handle);
  1087. return hci_send_acl_packet_buffer(len);
  1088. }
  1089. // assumption - only on Classic connections
  1090. // cannot be used for L2CAP ERTM
  1091. int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
  1092. if (!hci_is_packet_buffer_reserved()){
  1093. log_error("l2cap_send_prepared called without reserving packet first");
  1094. return BTSTACK_ACL_BUFFERS_FULL;
  1095. }
  1096. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  1097. if (!channel) {
  1098. log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
  1099. return -1; // TODO: define error
  1100. }
  1101. if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
  1102. log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
  1103. return BTSTACK_ACL_BUFFERS_FULL;
  1104. }
  1105. log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
  1106. int fcs_size = 0;
  1107. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1108. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
  1109. fcs_size = 2;
  1110. }
  1111. #endif
  1112. // set non-flushable packet boundary flag if supported on Controller
  1113. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  1114. uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
  1115. l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
  1116. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1117. if (fcs_size){
  1118. // calculate FCS over l2cap data
  1119. uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
  1120. log_info("I-Frame: fcs 0x%04x", fcs);
  1121. little_endian_store_16(acl_buffer, 8 + len, fcs);
  1122. }
  1123. #endif
  1124. // send
  1125. return hci_send_acl_packet_buffer(len+8+fcs_size);
  1126. }
  1127. // assumption - only on Classic connections
  1128. int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
  1129. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  1130. if (!channel) {
  1131. log_error("l2cap_send no channel for cid 0x%02x", local_cid);
  1132. return -1; // TODO: define error
  1133. }
  1134. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1135. // send in ERTM
  1136. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  1137. return l2cap_ertm_send(channel, data, len);
  1138. }
  1139. #endif
  1140. if (len > channel->remote_mtu){
  1141. log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
  1142. return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
  1143. }
  1144. if (!hci_can_send_acl_packet_now(channel->con_handle)){
  1145. log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
  1146. return BTSTACK_ACL_BUFFERS_FULL;
  1147. }
  1148. hci_reserve_packet_buffer();
  1149. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  1150. (void)memcpy(&acl_buffer[8], data, len);
  1151. return l2cap_send_prepared(local_cid, len);
  1152. }
  1153. int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
  1154. return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
  1155. }
  1156. static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
  1157. channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
  1158. }
  1159. static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
  1160. channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
  1161. }
  1162. #endif
  1163. #ifdef ENABLE_BLE
  1164. static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
  1165. if (!hci_can_send_acl_packet_now(handle)){
  1166. log_info("l2cap_send_le_signaling_packet, cannot send");
  1167. return BTSTACK_ACL_BUFFERS_FULL;
  1168. }
  1169. // log_info("l2cap_send_le_signaling_packet type %u", cmd);
  1170. hci_reserve_packet_buffer();
  1171. uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
  1172. va_list argptr;
  1173. va_start(argptr, identifier);
  1174. uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
  1175. va_end(argptr);
  1176. // log_info("l2cap_send_le_signaling_packet con %u!", handle);
  1177. return hci_send_acl_packet_buffer(len);
  1178. }
  1179. #endif
  1180. uint16_t l2cap_max_mtu(void){
  1181. return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
  1182. }
  1183. #ifdef ENABLE_BLE
  1184. uint16_t l2cap_max_le_mtu(void){
  1185. if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
  1186. return l2cap_max_mtu();
  1187. }
  1188. void l2cap_set_max_le_mtu(uint16_t max_mtu){
  1189. if (max_mtu < l2cap_max_mtu()){
  1190. l2cap_le_custom_max_mtu = max_mtu;
  1191. }
  1192. }
  1193. #endif
  1194. #ifdef ENABLE_CLASSIC
  1195. static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
  1196. config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
  1197. config_options[1] = 2; // len param
  1198. little_endian_store_16(config_options, 2, mtu);
  1199. return 4;
  1200. }
  1201. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1202. static int l2cap_ertm_mode(l2cap_channel_t * channel){
  1203. hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
  1204. return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
  1205. && (connection->l2cap_state.extended_feature_mask & 0x08));
  1206. }
  1207. #endif
  1208. static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
  1209. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1210. // use ERTM options if supported by remote and channel ready to use it
  1211. if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  1212. return l2cap_setup_options_ertm_request(channel, config_options);
  1213. }
  1214. #endif
  1215. uint16_t mtu = channel->local_mtu;
  1216. return l2cap_setup_options_mtu(config_options, mtu);
  1217. }
  1218. static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
  1219. uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
  1220. return l2cap_setup_options_mtu(config_options, mtu);
  1221. }
  1222. static uint32_t l2cap_extended_features_mask(void){
  1223. // extended features request supported, features: fixed channels, unicast connectionless data reception
  1224. uint32_t features = 0x280;
  1225. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1226. features |= 0x0028;
  1227. #endif
  1228. return features;
  1229. }
  1230. #endif
  1231. //
  1232. #ifdef ENABLE_CLASSIC
  1233. // returns true if channel was finalized
  1234. static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
  1235. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1236. uint8_t config_options[18];
  1237. #else
  1238. uint8_t config_options[10];
  1239. #endif
  1240. switch (channel->state){
  1241. case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
  1242. case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
  1243. if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
  1244. if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
  1245. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
  1246. l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
  1247. }
  1248. break;
  1249. case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
  1250. if (!hci_can_send_command_packet_now()) break;
  1251. // send connection request - set state first
  1252. channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
  1253. // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
  1254. (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
  1255. hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
  1256. break;
  1257. case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
  1258. if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
  1259. channel->state = L2CAP_STATE_INVALID;
  1260. l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
  1261. // discard channel - l2cap_finialize_channel_close without sending l2cap close event
  1262. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  1263. l2cap_free_channel_entry(channel);
  1264. channel = NULL;
  1265. break;
  1266. case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
  1267. if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
  1268. channel->state = L2CAP_STATE_CONFIG;
  1269. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
  1270. l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
  1271. break;
  1272. case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
  1273. if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
  1274. // success, start l2cap handshake
  1275. channel->local_sig_id = l2cap_next_sig_id();
  1276. channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
  1277. l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
  1278. l2cap_start_rtx(channel);
  1279. break;
  1280. case L2CAP_STATE_CONFIG:
  1281. if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
  1282. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1283. // fallback to basic mode if ERTM requested but not not supported by remote
  1284. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  1285. if (!l2cap_ertm_mode(channel)){
  1286. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
  1287. channel->mode = L2CAP_CHANNEL_MODE_BASIC;
  1288. }
  1289. }
  1290. #endif
  1291. if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
  1292. uint16_t flags = 0;
  1293. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
  1294. if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
  1295. flags = 1;
  1296. } else {
  1297. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
  1298. }
  1299. if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
  1300. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
  1301. l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
  1302. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1303. } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
  1304. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
  1305. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
  1306. uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
  1307. l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size, &config_options);
  1308. } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
  1309. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
  1310. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
  1311. uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
  1312. l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options);
  1313. #endif
  1314. } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
  1315. channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
  1316. uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
  1317. l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options);
  1318. } else {
  1319. l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
  1320. }
  1321. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
  1322. }
  1323. else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
  1324. channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
  1325. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
  1326. channel->local_sig_id = l2cap_next_sig_id();
  1327. uint16_t options_size = l2cap_setup_options_request(channel, config_options);
  1328. l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
  1329. l2cap_start_rtx(channel);
  1330. }
  1331. if (l2cap_channel_ready_for_open(channel)){
  1332. channel->state = L2CAP_STATE_OPEN;
  1333. l2cap_emit_channel_opened(channel, 0); // success
  1334. }
  1335. break;
  1336. case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
  1337. if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
  1338. channel->state = L2CAP_STATE_INVALID;
  1339. l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
  1340. // we don't start an RTX timer for a disconnect - there's no point in closing the channel if the other side doesn't respond :)
  1341. l2cap_finialize_channel_close(channel); // -- remove from list
  1342. channel = NULL;
  1343. break;
  1344. case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
  1345. if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
  1346. channel->local_sig_id = l2cap_next_sig_id();
  1347. channel->state = L2CAP_STATE_WAIT_DISCONNECT;
  1348. l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
  1349. break;
  1350. default:
  1351. break;
  1352. }
  1353. // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
  1354. return channel == NULL;
  1355. }
  1356. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1357. static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
  1358. // ERTM mode
  1359. if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
  1360. // check if we can still send
  1361. if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
  1362. if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
  1363. if (channel->send_supervisor_frame_receiver_ready){
  1364. channel->send_supervisor_frame_receiver_ready = 0;
  1365. log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
  1366. uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->req_seq);
  1367. channel->set_final_bit_after_packet_with_poll_bit_set = 0;
  1368. l2cap_ertm_send_supervisor_frame(channel, control);
  1369. return;
  1370. }
  1371. if (channel->send_supervisor_frame_receiver_ready_poll){
  1372. channel->send_supervisor_frame_receiver_ready_poll = 0;
  1373. log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
  1374. uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
  1375. l2cap_ertm_send_supervisor_frame(channel, control);
  1376. return;
  1377. }
  1378. if (channel->send_supervisor_frame_receiver_not_ready){
  1379. channel->send_supervisor_frame_receiver_not_ready = 0;
  1380. log_info("Send S-Frame: RNR %u", channel->req_seq);
  1381. uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
  1382. l2cap_ertm_send_supervisor_frame(channel, control);
  1383. return;
  1384. }
  1385. if (channel->send_supervisor_frame_reject){
  1386. channel->send_supervisor_frame_reject = 0;
  1387. log_info("Send S-Frame: REJ %u", channel->req_seq);
  1388. uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
  1389. l2cap_ertm_send_supervisor_frame(channel, control);
  1390. return;
  1391. }
  1392. if (channel->send_supervisor_frame_selective_reject){
  1393. channel->send_supervisor_frame_selective_reject = 0;
  1394. log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
  1395. uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->expected_tx_seq);
  1396. channel->set_final_bit_after_packet_with_poll_bit_set = 0;
  1397. l2cap_ertm_send_supervisor_frame(channel, control);
  1398. return;
  1399. }
  1400. if (channel->srej_active){
  1401. int i;
  1402. for (i=0;i<channel->num_tx_buffers;i++){
  1403. l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
  1404. if (tx_state->retransmission_requested) {
  1405. tx_state->retransmission_requested = 0;
  1406. uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
  1407. channel->set_final_bit_after_packet_with_poll_bit_set = 0;
  1408. l2cap_ertm_send_information_frame(channel, i, final);
  1409. break;
  1410. }
  1411. }
  1412. if (i == channel->num_tx_buffers){
  1413. // no retransmission request found
  1414. channel->srej_active = 0;
  1415. } else {
  1416. // packet was sent
  1417. return;
  1418. }
  1419. }
  1420. }
  1421. #endif /* ERTM */
  1422. #endif /* Classic */
  1423. static void l2cap_run_signaling_response(void) {
  1424. // check pending signaling responses
  1425. while (signaling_responses_pending){
  1426. hci_con_handle_t handle = signaling_responses[0].handle;
  1427. if (!hci_can_send_acl_packet_now(handle)) break;
  1428. uint8_t sig_id = signaling_responses[0].sig_id;
  1429. uint8_t response_code = signaling_responses[0].code;
  1430. uint16_t result = signaling_responses[0].data; // CONNECTION_REQUEST, COMMAND_REJECT
  1431. #ifdef ENABLE_CLASSIC
  1432. uint16_t info_type = signaling_responses[0].data; // INFORMATION_REQUEST
  1433. uint16_t source_cid = signaling_responses[0].cid; // CONNECTION_REQUEST
  1434. #endif
  1435. // remove first item before sending (to avoid sending response mutliple times)
  1436. signaling_responses_pending--;
  1437. int i;
  1438. for (i=0; i < signaling_responses_pending; i++){
  1439. (void)memcpy(&signaling_responses[i],
  1440. &signaling_responses[i + 1],
  1441. sizeof(l2cap_signaling_response_t));
  1442. }
  1443. switch (response_code){
  1444. #ifdef ENABLE_CLASSIC
  1445. case CONNECTION_REQUEST:
  1446. l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
  1447. // also disconnect if result is 0x0003 - security blocked
  1448. if (result == 0x0003){
  1449. hci_disconnect_security_block(handle);
  1450. }
  1451. break;
  1452. case ECHO_REQUEST:
  1453. l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
  1454. break;
  1455. case INFORMATION_REQUEST:
  1456. switch (info_type){
  1457. case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
  1458. uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
  1459. l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
  1460. }
  1461. break;
  1462. case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
  1463. uint32_t features = l2cap_extended_features_mask();
  1464. l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
  1465. }
  1466. break;
  1467. case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
  1468. uint8_t map[8];
  1469. memset(map, 0, 8);
  1470. map[0] = 0x06; // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
  1471. l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
  1472. }
  1473. break;
  1474. default:
  1475. // all other types are not supported
  1476. l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
  1477. break;
  1478. }
  1479. break;
  1480. case COMMAND_REJECT:
  1481. l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
  1482. break;
  1483. #endif
  1484. #ifdef ENABLE_BLE
  1485. case LE_CREDIT_BASED_CONNECTION_REQUEST:
  1486. l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
  1487. break;
  1488. case COMMAND_REJECT_LE:
  1489. l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
  1490. break;
  1491. #endif
  1492. default:
  1493. // should not happen
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1499. static bool l2ap_run_ertm(void){
  1500. // send l2cap information request if neccessary
  1501. btstack_linked_list_iterator_t it;
  1502. hci_connections_get_iterator(&it);
  1503. while(btstack_linked_list_iterator_has_next(&it)){
  1504. hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
  1505. if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
  1506. if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
  1507. connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
  1508. uint8_t sig_id = l2cap_next_sig_id();
  1509. uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
  1510. l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
  1511. return true;
  1512. }
  1513. }
  1514. return false;
  1515. }
  1516. #endif
  1517. #ifdef ENABLE_LE_DATA_CHANNELS
  1518. static void l2cap_run_le_data_channels(void){
  1519. btstack_linked_list_iterator_t it;
  1520. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  1521. while (btstack_linked_list_iterator_has_next(&it)){
  1522. uint16_t mps;
  1523. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  1524. if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
  1525. // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
  1526. switch (channel->state){
  1527. case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
  1528. if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
  1529. channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
  1530. // le psm, source cid, mtu, mps, initial credits
  1531. channel->local_sig_id = l2cap_next_sig_id();
  1532. channel->credits_incoming = channel->new_credits_incoming;
  1533. channel->new_credits_incoming = 0;
  1534. mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
  1535. l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming);
  1536. break;
  1537. case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
  1538. if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
  1539. // TODO: support larger MPS
  1540. channel->state = L2CAP_STATE_OPEN;
  1541. channel->credits_incoming = channel->new_credits_incoming;
  1542. channel->new_credits_incoming = 0;
  1543. mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
  1544. l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming, 0);
  1545. // notify client
  1546. l2cap_emit_le_channel_opened(channel, 0);
  1547. break;
  1548. case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
  1549. if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
  1550. channel->state = L2CAP_STATE_INVALID;
  1551. l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
  1552. // discard channel - l2cap_finialize_channel_close without sending l2cap close event
  1553. btstack_linked_list_iterator_remove(&it);
  1554. l2cap_free_channel_entry(channel);
  1555. break;
  1556. case L2CAP_STATE_OPEN:
  1557. if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
  1558. // send credits
  1559. if (channel->new_credits_incoming){
  1560. log_info("l2cap: sending %u credits", channel->new_credits_incoming);
  1561. channel->local_sig_id = l2cap_next_sig_id();
  1562. uint16_t new_credits = channel->new_credits_incoming;
  1563. channel->new_credits_incoming = 0;
  1564. channel->credits_incoming += new_credits;
  1565. l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
  1566. }
  1567. break;
  1568. case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
  1569. if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
  1570. channel->local_sig_id = l2cap_next_sig_id();
  1571. channel->state = L2CAP_STATE_WAIT_DISCONNECT;
  1572. l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
  1573. break;
  1574. case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
  1575. if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
  1576. channel->state = L2CAP_STATE_INVALID;
  1577. l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
  1578. l2cap_le_finialize_channel_close(channel); // -- remove from list
  1579. break;
  1580. default:
  1581. break;
  1582. }
  1583. }
  1584. }
  1585. #endif
  1586. // MARK: L2CAP_RUN
  1587. // process outstanding signaling tasks
  1588. static void l2cap_run(void){
  1589. // log_info("l2cap_run: entered");
  1590. l2cap_run_signaling_response();
  1591. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1592. bool done = l2ap_run_ertm();
  1593. if (done) return;
  1594. #endif
  1595. #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
  1596. btstack_linked_list_iterator_t it;
  1597. #endif
  1598. #ifdef ENABLE_CLASSIC
  1599. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  1600. while (btstack_linked_list_iterator_has_next(&it)){
  1601. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  1602. if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
  1603. // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
  1604. bool finalized = l2cap_run_for_classic_channel(channel);
  1605. if (!finalized) {
  1606. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1607. l2cap_run_for_classic_channel_ertm(channel);
  1608. #endif
  1609. }
  1610. }
  1611. #endif
  1612. #ifdef ENABLE_LE_DATA_CHANNELS
  1613. l2cap_run_le_data_channels();
  1614. #endif
  1615. #ifdef ENABLE_BLE
  1616. // send l2cap con paramter update if necessary
  1617. hci_connections_get_iterator(&it);
  1618. while(btstack_linked_list_iterator_has_next(&it)){
  1619. hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
  1620. if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
  1621. if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
  1622. switch (connection->le_con_parameter_update_state){
  1623. case CON_PARAMETER_UPDATE_SEND_REQUEST:
  1624. connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
  1625. l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
  1626. connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
  1627. break;
  1628. case CON_PARAMETER_UPDATE_SEND_RESPONSE:
  1629. connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
  1630. l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
  1631. break;
  1632. case CON_PARAMETER_UPDATE_DENY:
  1633. connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
  1634. l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
  1635. break;
  1636. default:
  1637. break;
  1638. }
  1639. }
  1640. #endif
  1641. // log_info("l2cap_run: exit");
  1642. }
  1643. #ifdef ENABLE_CLASSIC
  1644. static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
  1645. if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
  1646. log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
  1647. // success, start l2cap handshake
  1648. channel->con_handle = con_handle;
  1649. // check remote SSP feature first
  1650. channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
  1651. }
  1652. }
  1653. static void l2cap_ready_to_connect(l2cap_channel_t * channel){
  1654. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1655. // assumption: outgoing connection
  1656. hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
  1657. if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
  1658. connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
  1659. channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
  1660. return;
  1661. }
  1662. #endif
  1663. // fine, go ahead
  1664. channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
  1665. }
  1666. static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
  1667. if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
  1668. // we have been waiting for remote supported features
  1669. log_info("l2cap received remote supported features, sec_level_0_allowed for psm %u = %u", channel->psm, l2cap_security_level_0_allowed_for_PSM(channel->psm));
  1670. if (l2cap_security_level_0_allowed_for_PSM(channel->psm) == 0){
  1671. // request security level 2
  1672. channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
  1673. channel->required_security_level = gap_get_security_level();
  1674. gap_request_security_level(channel->con_handle, gap_get_security_level());
  1675. return;
  1676. }
  1677. l2cap_ready_to_connect(channel);
  1678. }
  1679. #endif
  1680. #ifdef L2CAP_USES_CHANNELS
  1681. static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
  1682. uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
  1683. l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
  1684. if (!channel) {
  1685. return NULL;
  1686. }
  1687. // fill in
  1688. channel->packet_handler = packet_handler;
  1689. channel->channel_type = channel_type;
  1690. bd_addr_copy(channel->address, address);
  1691. channel->address_type = address_type;
  1692. channel->psm = psm;
  1693. channel->local_mtu = local_mtu;
  1694. channel->remote_mtu = L2CAP_DEFAULT_MTU;
  1695. channel->required_security_level = security_level;
  1696. //
  1697. channel->local_cid = l2cap_next_local_cid();
  1698. channel->con_handle = HCI_CON_HANDLE_INVALID;
  1699. // set initial state
  1700. channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
  1701. channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
  1702. channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
  1703. channel->local_sig_id = L2CAP_SIG_ID_INVALID;
  1704. log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
  1705. return channel;
  1706. }
  1707. static void l2cap_free_channel_entry(l2cap_channel_t * channel){
  1708. log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
  1709. // assert all timers are stopped
  1710. l2cap_stop_rtx(channel);
  1711. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1712. l2cap_ertm_stop_retransmission_timer(channel);
  1713. l2cap_ertm_stop_monitor_timer(channel);
  1714. #endif
  1715. // free memory
  1716. btstack_memory_l2cap_channel_free(channel);
  1717. }
  1718. #endif
  1719. #ifdef ENABLE_CLASSIC
  1720. /**
  1721. * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
  1722. * @param packet_handler
  1723. * @param address
  1724. * @param psm
  1725. * @param mtu
  1726. * @param local_cid
  1727. */
  1728. uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t mtu, uint16_t * out_local_cid){
  1729. // limit MTU to the size of our outtgoing HCI buffer
  1730. uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
  1731. log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
  1732. l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, LEVEL_0);
  1733. if (!channel) {
  1734. return BTSTACK_MEMORY_ALLOC_FAILED;
  1735. }
  1736. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1737. channel->mode = L2CAP_CHANNEL_MODE_BASIC;
  1738. #endif
  1739. // add to connections list
  1740. btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
  1741. // store local_cid
  1742. if (out_local_cid){
  1743. *out_local_cid = channel->local_cid;
  1744. }
  1745. // check if hci connection is already usable
  1746. hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
  1747. if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
  1748. log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
  1749. l2cap_handle_connection_complete(conn->con_handle, channel);
  1750. // check if remote supported fearures are already received
  1751. if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
  1752. l2cap_handle_remote_supported_features_received(channel);
  1753. }
  1754. }
  1755. l2cap_run();
  1756. return ERROR_CODE_SUCCESS;
  1757. }
  1758. void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
  1759. log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
  1760. // find channel for local_cid
  1761. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  1762. if (channel) {
  1763. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  1764. }
  1765. // process
  1766. l2cap_run();
  1767. }
  1768. static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
  1769. // mark all channels before emitting open events as these could trigger new connetion requests to the same device
  1770. btstack_linked_list_iterator_t it;
  1771. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  1772. while (btstack_linked_list_iterator_has_next(&it)){
  1773. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  1774. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  1775. if (bd_addr_cmp( channel->address, address) != 0) continue;
  1776. // channel for this address found
  1777. switch (channel->state){
  1778. case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
  1779. case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
  1780. channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
  1781. break;
  1782. default:
  1783. break;
  1784. }
  1785. }
  1786. // emit and free marked entries. restart loop to deal with list changes
  1787. int done = 0;
  1788. while (!done) {
  1789. done = 1;
  1790. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  1791. while (btstack_linked_list_iterator_has_next(&it)){
  1792. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  1793. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  1794. if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
  1795. done = 0;
  1796. // failure, forward error code
  1797. l2cap_handle_channel_open_failed(channel, status);
  1798. // discard channel
  1799. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  1800. l2cap_free_channel_entry(channel);
  1801. break;
  1802. }
  1803. }
  1804. }
  1805. }
  1806. static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
  1807. btstack_linked_list_iterator_t it;
  1808. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  1809. while (btstack_linked_list_iterator_has_next(&it)){
  1810. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  1811. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  1812. if ( ! bd_addr_cmp( channel->address, address) ){
  1813. l2cap_handle_connection_complete(handle, channel);
  1814. }
  1815. }
  1816. // process
  1817. l2cap_run();
  1818. }
  1819. #endif
  1820. static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
  1821. switch (channel->channel_type){
  1822. #ifdef ENABLE_CLASSIC
  1823. case L2CAP_CHANNEL_TYPE_CLASSIC:
  1824. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1825. // send if we have more data and remote windows isn't full yet
  1826. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
  1827. if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
  1828. return hci_can_send_acl_classic_packet_now() != 0;
  1829. }
  1830. #endif
  1831. if (!channel->waiting_for_can_send_now) return false;
  1832. return (hci_can_send_acl_classic_packet_now() != 0);
  1833. case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
  1834. if (!channel->waiting_for_can_send_now) return false;
  1835. return hci_can_send_acl_classic_packet_now() != 0;
  1836. #endif
  1837. #ifdef ENABLE_BLE
  1838. case L2CAP_CHANNEL_TYPE_LE_FIXED:
  1839. if (!channel->waiting_for_can_send_now) return false;
  1840. return hci_can_send_acl_le_packet_now() != 0;
  1841. #ifdef ENABLE_LE_DATA_CHANNELS
  1842. case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
  1843. if (channel->send_sdu_buffer == NULL) return false;
  1844. if (channel->credits_outgoing == 0u) return false;
  1845. return hci_can_send_acl_le_packet_now() != 0;
  1846. #endif
  1847. #endif
  1848. default:
  1849. return false;
  1850. }
  1851. }
  1852. static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
  1853. switch (channel->channel_type){
  1854. #ifdef ENABLE_CLASSIC
  1855. case L2CAP_CHANNEL_TYPE_CLASSIC:
  1856. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  1857. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
  1858. l2cap_ertm_channel_send_information_frame(channel);
  1859. return;
  1860. }
  1861. #endif
  1862. channel->waiting_for_can_send_now = 0;
  1863. l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
  1864. break;
  1865. case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
  1866. channel->waiting_for_can_send_now = 0;
  1867. l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
  1868. break;
  1869. #endif
  1870. #ifdef ENABLE_BLE
  1871. case L2CAP_CHANNEL_TYPE_LE_FIXED:
  1872. channel->waiting_for_can_send_now = 0;
  1873. l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
  1874. break;
  1875. #ifdef ENABLE_LE_DATA_CHANNELS
  1876. case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
  1877. l2cap_le_send_pdu(channel);
  1878. break;
  1879. #endif
  1880. #endif
  1881. default:
  1882. break;
  1883. }
  1884. }
  1885. static void l2cap_notify_channel_can_send(void){
  1886. bool done = false;
  1887. while (!done){
  1888. done = true;
  1889. btstack_linked_list_iterator_t it;
  1890. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  1891. while (btstack_linked_list_iterator_has_next(&it)){
  1892. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  1893. bool ready = l2cap_channel_ready_to_send(channel);
  1894. if (!ready) continue;
  1895. // requeue channel for fairness
  1896. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  1897. btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
  1898. // trigger sending
  1899. l2cap_channel_trigger_send(channel);
  1900. // exit inner loop as we just broke the iterator, but try again
  1901. done = false;
  1902. break;
  1903. }
  1904. }
  1905. }
  1906. #ifdef L2CAP_USES_CHANNELS
  1907. static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
  1908. // open cannot fail for for incoming connections
  1909. if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
  1910. // check state
  1911. switch (channel->state){
  1912. case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
  1913. case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
  1914. case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
  1915. case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
  1916. case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
  1917. case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
  1918. case L2CAP_STATE_WAIT_CONNECT_RSP:
  1919. case L2CAP_STATE_CONFIG:
  1920. case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
  1921. case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
  1922. case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
  1923. case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
  1924. return 1;
  1925. case L2CAP_STATE_OPEN:
  1926. case L2CAP_STATE_CLOSED:
  1927. case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
  1928. case L2CAP_STATE_WAIT_DISCONNECT:
  1929. case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
  1930. case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
  1931. case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
  1932. case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
  1933. case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
  1934. case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
  1935. case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
  1936. case L2CAP_STATE_INVALID:
  1937. case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
  1938. return 0;
  1939. // no default here, to get a warning about new states
  1940. }
  1941. // still, the compiler insists on a return value
  1942. return 0;
  1943. }
  1944. #endif
  1945. #ifdef ENABLE_CLASSIC
  1946. static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
  1947. if (l2cap_send_open_failed_on_hci_disconnect(channel)){
  1948. l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
  1949. } else {
  1950. l2cap_handle_channel_closed(channel);
  1951. }
  1952. l2cap_free_channel_entry(channel);
  1953. }
  1954. #endif
  1955. #ifdef ENABLE_LE_DATA_CHANNELS
  1956. static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
  1957. if (l2cap_send_open_failed_on_hci_disconnect(channel)){
  1958. l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
  1959. } else {
  1960. l2cap_emit_le_channel_closed(channel);
  1961. }
  1962. l2cap_free_channel_entry(channel);
  1963. }
  1964. #endif
  1965. static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
  1966. UNUSED(packet_type); // ok: registered with hci_event_callback_registration
  1967. UNUSED(cid); // ok: there is no channel
  1968. UNUSED(size); // ok: fixed format events read from HCI buffer
  1969. #ifdef ENABLE_CLASSIC
  1970. bd_addr_t address;
  1971. hci_connection_t * hci_connection;
  1972. int hci_con_used;
  1973. #endif
  1974. #ifdef L2CAP_USES_CHANNELS
  1975. hci_con_handle_t handle;
  1976. btstack_linked_list_iterator_t it;
  1977. #endif
  1978. switch(hci_event_packet_get_type(packet)){
  1979. // Notify channel packet handler if they can send now
  1980. case HCI_EVENT_TRANSPORT_PACKET_SENT:
  1981. case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
  1982. case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
  1983. l2cap_run(); // try sending signaling packets first
  1984. l2cap_notify_channel_can_send();
  1985. break;
  1986. case HCI_EVENT_COMMAND_STATUS:
  1987. #ifdef ENABLE_CLASSIC
  1988. // check command status for create connection for errors
  1989. if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
  1990. // cache outgoing address and reset
  1991. (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
  1992. memset(l2cap_outgoing_classic_addr, 0, 6);
  1993. // error => outgoing connection failed
  1994. uint8_t status = hci_event_command_status_get_status(packet);
  1995. if (status){
  1996. l2cap_handle_connection_failed_for_addr(address, status);
  1997. }
  1998. }
  1999. #endif
  2000. l2cap_run(); // try sending signaling packets first
  2001. break;
  2002. #ifdef ENABLE_CLASSIC
  2003. // handle connection complete events
  2004. case HCI_EVENT_CONNECTION_COMPLETE:
  2005. reverse_bd_addr(&packet[5], address);
  2006. if (packet[2] == 0){
  2007. handle = little_endian_read_16(packet, 3);
  2008. l2cap_handle_connection_success_for_addr(address, handle);
  2009. } else {
  2010. l2cap_handle_connection_failed_for_addr(address, packet[2]);
  2011. }
  2012. break;
  2013. // handle successful create connection cancel command
  2014. case HCI_EVENT_COMMAND_COMPLETE:
  2015. if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
  2016. if (packet[5] == 0){
  2017. reverse_bd_addr(&packet[6], address);
  2018. // CONNECTION TERMINATED BY LOCAL HOST (0X16)
  2019. l2cap_handle_connection_failed_for_addr(address, 0x16);
  2020. }
  2021. }
  2022. l2cap_run(); // try sending signaling packets first
  2023. break;
  2024. #endif
  2025. #ifdef L2CAP_USES_CHANNELS
  2026. // handle disconnection complete events
  2027. case HCI_EVENT_DISCONNECTION_COMPLETE:
  2028. handle = little_endian_read_16(packet, 3);
  2029. // send l2cap open failed or closed events for all channels on this handle and free them
  2030. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2031. while (btstack_linked_list_iterator_has_next(&it)){
  2032. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2033. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  2034. if (channel->con_handle != handle) continue;
  2035. btstack_linked_list_iterator_remove(&it);
  2036. switch(channel->channel_type){
  2037. #ifdef ENABLE_CLASSIC
  2038. case L2CAP_CHANNEL_TYPE_CLASSIC:
  2039. l2cap_handle_hci_disconnect_event(channel);
  2040. break;
  2041. #endif
  2042. #ifdef ENABLE_LE_DATA_CHANNELS
  2043. case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
  2044. l2cap_handle_hci_le_disconnect_event(channel);
  2045. break;
  2046. #endif
  2047. default:
  2048. break;
  2049. }
  2050. }
  2051. break;
  2052. #endif
  2053. // HCI Connection Timeouts
  2054. #ifdef ENABLE_CLASSIC
  2055. case L2CAP_EVENT_TIMEOUT_CHECK:
  2056. handle = little_endian_read_16(packet, 2);
  2057. if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
  2058. if (hci_authentication_active_for_handle(handle)) break;
  2059. hci_con_used = 0;
  2060. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2061. while (btstack_linked_list_iterator_has_next(&it)){
  2062. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2063. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  2064. if (channel->con_handle != handle) continue;
  2065. hci_con_used = 1;
  2066. break;
  2067. }
  2068. if (hci_con_used) break;
  2069. if (!hci_can_send_command_packet_now()) break;
  2070. hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
  2071. break;
  2072. case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
  2073. case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
  2074. handle = little_endian_read_16(packet, 3);
  2075. hci_connection = hci_connection_for_handle(handle);
  2076. if (hci_connection == NULL) break;
  2077. if ((hci_connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) == 0) break;
  2078. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2079. while (btstack_linked_list_iterator_has_next(&it)){
  2080. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2081. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  2082. if (channel->con_handle != handle) continue;
  2083. log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
  2084. l2cap_handle_remote_supported_features_received(channel);
  2085. }
  2086. break;
  2087. case GAP_EVENT_SECURITY_LEVEL:
  2088. handle = little_endian_read_16(packet, 2);
  2089. log_info("l2cap - security level update for handle 0x%04x", handle);
  2090. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2091. while (btstack_linked_list_iterator_has_next(&it)){
  2092. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2093. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  2094. if (channel->con_handle != handle) continue;
  2095. gap_security_level_t actual_level = (gap_security_level_t) packet[4];
  2096. gap_security_level_t required_level = channel->required_security_level;
  2097. log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
  2098. switch (channel->state){
  2099. case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
  2100. if (actual_level >= required_level){
  2101. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2102. // we need to know if ERTM is supported before sending a config response
  2103. hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
  2104. if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_DONE){
  2105. connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
  2106. channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
  2107. break;
  2108. }
  2109. #endif
  2110. channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
  2111. l2cap_emit_incoming_connection(channel);
  2112. } else {
  2113. channel->reason = 0x0003; // security block
  2114. channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
  2115. }
  2116. break;
  2117. case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
  2118. if (actual_level >= required_level){
  2119. l2cap_ready_to_connect(channel);
  2120. } else {
  2121. // disconnnect, authentication not good enough
  2122. hci_disconnect_security_block(handle);
  2123. }
  2124. break;
  2125. default:
  2126. break;
  2127. }
  2128. }
  2129. break;
  2130. #endif
  2131. default:
  2132. break;
  2133. }
  2134. l2cap_run();
  2135. }
  2136. static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
  2137. // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
  2138. if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
  2139. signaling_responses[signaling_responses_pending].handle = handle;
  2140. signaling_responses[signaling_responses_pending].code = code;
  2141. signaling_responses[signaling_responses_pending].sig_id = sig_id;
  2142. signaling_responses[signaling_responses_pending].cid = cid;
  2143. signaling_responses[signaling_responses_pending].data = data;
  2144. signaling_responses_pending++;
  2145. l2cap_run();
  2146. }
  2147. }
  2148. #ifdef ENABLE_CLASSIC
  2149. static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
  2150. channel->remote_sig_id = identifier;
  2151. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
  2152. l2cap_run();
  2153. }
  2154. static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
  2155. // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
  2156. l2cap_service_t *service = l2cap_get_service(psm);
  2157. if (!service) {
  2158. // 0x0002 PSM not supported
  2159. l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
  2160. return;
  2161. }
  2162. hci_connection_t * hci_connection = hci_connection_for_handle( handle );
  2163. if (!hci_connection) {
  2164. //
  2165. log_error("no hci_connection for handle %u", handle);
  2166. return;
  2167. }
  2168. // alloc structure
  2169. // log_info("l2cap_handle_connection_request register channel");
  2170. l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
  2171. psm, service->mtu, service->required_security_level);
  2172. if (!channel){
  2173. // 0x0004 No resources available
  2174. l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
  2175. return;
  2176. }
  2177. channel->con_handle = handle;
  2178. channel->remote_cid = source_cid;
  2179. channel->remote_sig_id = sig_id;
  2180. // limit local mtu to max acl packet length - l2cap header
  2181. if (channel->local_mtu > l2cap_max_mtu()) {
  2182. channel->local_mtu = l2cap_max_mtu();
  2183. }
  2184. // set initial state
  2185. channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
  2186. channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
  2187. // add to connections list
  2188. btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
  2189. // assert security requirements
  2190. gap_request_security_level(handle, channel->required_security_level);
  2191. }
  2192. void l2cap_accept_connection(uint16_t local_cid){
  2193. log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
  2194. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  2195. if (!channel) {
  2196. log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
  2197. return;
  2198. }
  2199. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2200. // configure L2CAP Basic mode
  2201. channel->mode = L2CAP_CHANNEL_MODE_BASIC;
  2202. #endif
  2203. channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
  2204. // process
  2205. l2cap_run();
  2206. }
  2207. void l2cap_decline_connection(uint16_t local_cid){
  2208. log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
  2209. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
  2210. if (!channel) {
  2211. log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
  2212. return;
  2213. }
  2214. channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
  2215. channel->reason = 0x04; // no resources available
  2216. l2cap_run();
  2217. }
  2218. // @pre command len is valid, see check in l2cap_signaling_handler_channel
  2219. static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
  2220. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2221. uint8_t use_fcs = 1;
  2222. #endif
  2223. channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
  2224. uint16_t flags = little_endian_read_16(command, 6);
  2225. if (flags & 1) {
  2226. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
  2227. }
  2228. // accept the other's configuration options
  2229. uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
  2230. uint16_t pos = 8;
  2231. while (pos < end_pos){
  2232. uint8_t option_hint = command[pos] >> 7;
  2233. uint8_t option_type = command[pos] & 0x7f;
  2234. // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
  2235. pos++;
  2236. uint8_t length = command[pos++];
  2237. // MTU { type(8): 1, len(8):2, MTU(16) }
  2238. if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
  2239. channel->remote_mtu = little_endian_read_16(command, pos);
  2240. log_info("Remote MTU %u", channel->remote_mtu);
  2241. if (channel->remote_mtu > l2cap_max_mtu()){
  2242. log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
  2243. channel->remote_mtu = l2cap_max_mtu();
  2244. }
  2245. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
  2246. }
  2247. // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
  2248. if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
  2249. channel->flush_timeout = little_endian_read_16(command, pos);
  2250. log_info("Flush timeout: %u ms", channel->flush_timeout);
  2251. }
  2252. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2253. // Retransmission and Flow Control Option
  2254. if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
  2255. l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
  2256. switch(channel->mode){
  2257. case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
  2258. // Store remote config
  2259. channel->remote_tx_window_size = command[pos+1];
  2260. channel->remote_max_transmit = command[pos+2];
  2261. channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
  2262. channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
  2263. channel->remote_mps = little_endian_read_16(command, pos + 7);
  2264. log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
  2265. channel->remote_tx_window_size,
  2266. channel->remote_max_transmit,
  2267. channel->remote_retransmission_timeout_ms,
  2268. channel->remote_monitor_timeout_ms,
  2269. channel->remote_mps);
  2270. // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
  2271. if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  2272. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  2273. } else {
  2274. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
  2275. }
  2276. break;
  2277. case L2CAP_CHANNEL_MODE_BASIC:
  2278. switch (mode){
  2279. case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
  2280. // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
  2281. if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
  2282. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  2283. }
  2284. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
  2285. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
  2286. break;
  2287. default: // case L2CAP_CHANNEL_MODE_BASIC:
  2288. // TODO store and evaluate configuration
  2289. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
  2290. break;
  2291. }
  2292. break;
  2293. default:
  2294. break;
  2295. }
  2296. }
  2297. if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
  2298. use_fcs = command[pos];
  2299. }
  2300. #endif
  2301. // check for unknown options
  2302. if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
  2303. log_info("l2cap cid %u, unknown options", channel->local_cid);
  2304. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
  2305. }
  2306. pos += length;
  2307. }
  2308. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2309. // "FCS" has precedence over "No FCS"
  2310. uint8_t update = channel->fcs_option || use_fcs;
  2311. log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
  2312. channel->fcs_option = update;
  2313. // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
  2314. if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
  2315. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  2316. }
  2317. #endif
  2318. }
  2319. // @pre command len is valid, see check in l2cap_signaling_handler_channel
  2320. static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
  2321. log_info("l2cap_signaling_handle_configure_response");
  2322. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2323. uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
  2324. uint16_t pos = 10;
  2325. while (pos < end_pos){
  2326. uint8_t option_hint = command[pos] >> 7;
  2327. uint8_t option_type = command[pos] & 0x7f;
  2328. // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
  2329. pos++;
  2330. uint8_t length = command[pos++];
  2331. // Retransmission and Flow Control Option
  2332. if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
  2333. switch (channel->mode){
  2334. case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
  2335. if (channel->ertm_mandatory){
  2336. // ??
  2337. } else {
  2338. // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
  2339. if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
  2340. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
  2341. channel->mode = L2CAP_CHANNEL_MODE_BASIC;
  2342. }
  2343. }
  2344. break;
  2345. case L2CAP_CHANNEL_MODE_BASIC:
  2346. if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
  2347. // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
  2348. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  2349. }
  2350. break;
  2351. default:
  2352. break;
  2353. }
  2354. }
  2355. // check for unknown options
  2356. if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
  2357. log_info("l2cap cid %u, unknown options", channel->local_cid);
  2358. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
  2359. }
  2360. pos += length;
  2361. }
  2362. #else
  2363. UNUSED(channel); // ok: no code
  2364. UNUSED(result); // ok: no code
  2365. UNUSED(command); // ok: no code
  2366. #endif
  2367. }
  2368. static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
  2369. // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
  2370. if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
  2371. if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
  2372. // addition check that fixes re-entrance issue causing l2cap event channel opened twice
  2373. if (channel->state == L2CAP_STATE_OPEN) return 0;
  2374. return 1;
  2375. }
  2376. // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
  2377. static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
  2378. uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
  2379. uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
  2380. uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
  2381. uint16_t result = 0;
  2382. log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
  2383. // handle DISCONNECT REQUESTS seperately
  2384. if (code == DISCONNECTION_REQUEST){
  2385. switch (channel->state){
  2386. case L2CAP_STATE_CONFIG:
  2387. case L2CAP_STATE_OPEN:
  2388. case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
  2389. case L2CAP_STATE_WAIT_DISCONNECT:
  2390. l2cap_handle_disconnect_request(channel, identifier);
  2391. break;
  2392. default:
  2393. // ignore in other states
  2394. break;
  2395. }
  2396. return;
  2397. }
  2398. // @STATEMACHINE(l2cap)
  2399. switch (channel->state) {
  2400. case L2CAP_STATE_WAIT_CONNECT_RSP:
  2401. switch (code){
  2402. case CONNECTION_RESPONSE:
  2403. if (cmd_len < 8){
  2404. // command imcomplete
  2405. l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
  2406. break;
  2407. }
  2408. l2cap_stop_rtx(channel);
  2409. result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
  2410. switch (result) {
  2411. case 0:
  2412. // successful connection
  2413. channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
  2414. channel->state = L2CAP_STATE_CONFIG;
  2415. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
  2416. break;
  2417. case 1:
  2418. // connection pending. get some coffee, but start the ERTX
  2419. l2cap_start_ertx(channel);
  2420. break;
  2421. default:
  2422. // channel closed
  2423. channel->state = L2CAP_STATE_CLOSED;
  2424. // map l2cap connection response result to BTstack status enumeration
  2425. l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
  2426. // drop link key if security block
  2427. if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
  2428. gap_drop_link_key_for_bd_addr(channel->address);
  2429. }
  2430. // discard channel
  2431. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  2432. l2cap_free_channel_entry(channel);
  2433. break;
  2434. }
  2435. break;
  2436. default:
  2437. //@TODO: implement other signaling packets
  2438. break;
  2439. }
  2440. break;
  2441. case L2CAP_STATE_CONFIG:
  2442. switch (code) {
  2443. case CONFIGURE_REQUEST:
  2444. if (cmd_len < 4){
  2445. // command incomplete
  2446. l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
  2447. break;
  2448. }
  2449. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
  2450. l2cap_signaling_handle_configure_request(channel, command);
  2451. if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
  2452. // only done if continuation not set
  2453. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
  2454. }
  2455. break;
  2456. case CONFIGURE_RESPONSE:
  2457. if (cmd_len < 6){
  2458. // command incomplete
  2459. l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
  2460. break;
  2461. }
  2462. result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
  2463. l2cap_stop_rtx(channel);
  2464. l2cap_signaling_handle_configure_response(channel, result, command);
  2465. switch (result){
  2466. case 0: // success
  2467. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
  2468. break;
  2469. case 4: // pending
  2470. l2cap_start_ertx(channel);
  2471. break;
  2472. default:
  2473. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2474. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
  2475. // remote does not offer ertm but it's required
  2476. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  2477. break;
  2478. }
  2479. #endif
  2480. // retry on negative result
  2481. channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
  2482. break;
  2483. }
  2484. break;
  2485. default:
  2486. break;
  2487. }
  2488. if (l2cap_channel_ready_for_open(channel)){
  2489. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2490. // assert that packet can be stored in fragment buffers in ertm
  2491. if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  2492. uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
  2493. uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
  2494. if (usable_mtu < channel->remote_mtu){
  2495. log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
  2496. channel->remote_mtu = usable_mtu;
  2497. }
  2498. }
  2499. #endif
  2500. // for open:
  2501. channel->state = L2CAP_STATE_OPEN;
  2502. l2cap_emit_channel_opened(channel, 0);
  2503. }
  2504. break;
  2505. case L2CAP_STATE_WAIT_DISCONNECT:
  2506. switch (code) {
  2507. case DISCONNECTION_RESPONSE:
  2508. l2cap_finialize_channel_close(channel);
  2509. break;
  2510. default:
  2511. //@TODO: implement other signaling packets
  2512. break;
  2513. }
  2514. break;
  2515. case L2CAP_STATE_CLOSED:
  2516. // @TODO handle incoming requests
  2517. break;
  2518. case L2CAP_STATE_OPEN:
  2519. //@TODO: implement other signaling packets, e.g. re-configure
  2520. break;
  2521. default:
  2522. break;
  2523. }
  2524. // log_info("new state %u", channel->state);
  2525. }
  2526. // @pre command len is valid, see check in l2cap_acl_classic_handler
  2527. static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
  2528. btstack_linked_list_iterator_t it;
  2529. // get code, signalind identifier and command len
  2530. uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
  2531. uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
  2532. uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
  2533. // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
  2534. if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
  2535. l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
  2536. return;
  2537. }
  2538. // general commands without an assigned channel
  2539. switch(code) {
  2540. case CONNECTION_REQUEST:
  2541. if (cmd_len == 4){
  2542. uint16_t psm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
  2543. uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
  2544. l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
  2545. } else {
  2546. l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
  2547. }
  2548. return;
  2549. case ECHO_REQUEST:
  2550. l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
  2551. return;
  2552. case INFORMATION_REQUEST:
  2553. if (cmd_len == 2) {
  2554. uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
  2555. l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
  2556. } else {
  2557. l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
  2558. }
  2559. return;
  2560. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2561. case INFORMATION_RESPONSE: {
  2562. hci_connection_t * connection = hci_connection_for_handle(handle);
  2563. if (!connection) return;
  2564. if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
  2565. // get extended features from response if valid
  2566. connection->l2cap_state.extended_feature_mask = 0;
  2567. if (cmd_len >= 6) {
  2568. uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
  2569. uint16_t result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
  2570. if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
  2571. connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
  2572. }
  2573. }
  2574. connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
  2575. log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
  2576. // trigger connection request
  2577. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2578. while (btstack_linked_list_iterator_has_next(&it)){
  2579. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2580. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  2581. if (channel->con_handle != handle) continue;
  2582. // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
  2583. if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
  2584. channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
  2585. l2cap_emit_incoming_connection(channel);
  2586. continue;
  2587. }
  2588. // outgoing connection
  2589. if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
  2590. // if ERTM was requested, but is not listed in extended feature mask:
  2591. if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
  2592. if (channel->ertm_mandatory){
  2593. // bail if ERTM is mandatory
  2594. channel->state = L2CAP_STATE_CLOSED;
  2595. // map l2cap connection response result to BTstack status enumeration
  2596. l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
  2597. // discard channel
  2598. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  2599. l2cap_free_channel_entry(channel);
  2600. continue;
  2601. } else {
  2602. // fallback to Basic mode
  2603. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
  2604. channel->mode = L2CAP_CHANNEL_MODE_BASIC;
  2605. }
  2606. }
  2607. // respond to connection request
  2608. channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
  2609. continue;
  2610. }
  2611. }
  2612. return;
  2613. }
  2614. #endif
  2615. default:
  2616. break;
  2617. }
  2618. // Get potential destination CID
  2619. uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
  2620. // Find channel for this sig_id and connection handle
  2621. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2622. while (btstack_linked_list_iterator_has_next(&it)){
  2623. l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2624. if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
  2625. if (channel->con_handle != handle) continue;
  2626. if (code & 1) {
  2627. // match odd commands (responses) by previous signaling identifier
  2628. if (channel->local_sig_id == sig_id) {
  2629. l2cap_signaling_handler_channel(channel, command);
  2630. break;
  2631. }
  2632. } else {
  2633. // match even commands (requests) by local channel id
  2634. if (channel->local_cid == dest_cid) {
  2635. l2cap_signaling_handler_channel(channel, command);
  2636. break;
  2637. }
  2638. }
  2639. }
  2640. }
  2641. #endif
  2642. #ifdef ENABLE_BLE
  2643. static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
  2644. uint8_t event[6];
  2645. event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
  2646. event[1] = 4;
  2647. little_endian_store_16(event, 2, con_handle);
  2648. little_endian_store_16(event, 4, result);
  2649. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  2650. if (!l2cap_event_packet_handler) return;
  2651. (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
  2652. }
  2653. // @returns valid
  2654. static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
  2655. hci_connection_t * connection;
  2656. uint16_t result;
  2657. uint8_t event[12];
  2658. #ifdef ENABLE_LE_DATA_CHANNELS
  2659. btstack_linked_list_iterator_t it;
  2660. l2cap_channel_t * channel;
  2661. uint16_t local_cid;
  2662. uint16_t le_psm;
  2663. uint16_t new_credits;
  2664. uint16_t credits_before;
  2665. l2cap_service_t * service;
  2666. uint16_t source_cid;
  2667. #endif
  2668. uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
  2669. uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
  2670. log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
  2671. switch (code){
  2672. case CONNECTION_PARAMETER_UPDATE_REQUEST:
  2673. // check size
  2674. if (len < 8u) return 0u;
  2675. connection = hci_connection_for_handle(handle);
  2676. if (connection){
  2677. if (connection->role != HCI_ROLE_MASTER){
  2678. // reject command without notifying upper layer when not in master role
  2679. return 0;
  2680. }
  2681. le_connection_parameter_range_t existing_range;
  2682. gap_get_connection_parameter_range(&existing_range);
  2683. uint16_t le_conn_interval_min = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
  2684. uint16_t le_conn_interval_max = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
  2685. uint16_t le_conn_latency = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
  2686. uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
  2687. int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
  2688. if (update_parameter){
  2689. connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
  2690. connection->le_conn_interval_min = le_conn_interval_min;
  2691. connection->le_conn_interval_max = le_conn_interval_max;
  2692. connection->le_conn_latency = le_conn_latency;
  2693. connection->le_supervision_timeout = le_supervision_timeout;
  2694. } else {
  2695. connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
  2696. }
  2697. connection->le_con_param_update_identifier = sig_id;
  2698. }
  2699. if (!l2cap_event_packet_handler) break;
  2700. event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
  2701. event[1] = 8;
  2702. little_endian_store_16(event, 2, handle);
  2703. (void)memcpy(&event[4], &command[4], 8);
  2704. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  2705. (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
  2706. break;
  2707. case CONNECTION_PARAMETER_UPDATE_RESPONSE:
  2708. // check size
  2709. if (len < 2u) return 0u;
  2710. result = little_endian_read_16(command, 4);
  2711. l2cap_emit_connection_parameter_update_response(handle, result);
  2712. break;
  2713. #ifdef ENABLE_LE_DATA_CHANNELS
  2714. case COMMAND_REJECT:
  2715. // Find channel for this sig_id and connection handle
  2716. channel = NULL;
  2717. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2718. while (btstack_linked_list_iterator_has_next(&it)){
  2719. l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2720. if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
  2721. if (a_channel->con_handle != handle) continue;
  2722. if (a_channel->local_sig_id != sig_id) continue;
  2723. channel = a_channel;
  2724. break;
  2725. }
  2726. if (!channel) break;
  2727. // if received while waiting for le connection response, assume legacy device
  2728. if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
  2729. channel->state = L2CAP_STATE_CLOSED;
  2730. // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
  2731. l2cap_emit_le_channel_opened(channel, 0x0002);
  2732. // discard channel
  2733. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  2734. l2cap_free_channel_entry(channel);
  2735. break;
  2736. }
  2737. break;
  2738. case LE_CREDIT_BASED_CONNECTION_REQUEST:
  2739. // check size
  2740. if (len < 10u) return 0u;
  2741. // get hci connection, bail if not found (must not happen)
  2742. connection = hci_connection_for_handle(handle);
  2743. if (!connection) return 0;
  2744. // check if service registered
  2745. le_psm = little_endian_read_16(command, 4);
  2746. service = l2cap_le_get_service(le_psm);
  2747. source_cid = little_endian_read_16(command, 6);
  2748. if (service){
  2749. if (source_cid < 0x40u){
  2750. // 0x0009 Connection refused - Invalid Source CID
  2751. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
  2752. return 1;
  2753. }
  2754. // go through list of channels for this ACL connection and check if we get a match
  2755. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2756. while (btstack_linked_list_iterator_has_next(&it)){
  2757. l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2758. if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
  2759. if (a_channel->con_handle != handle) continue;
  2760. if (a_channel->remote_cid != source_cid) continue;
  2761. // 0x000a Connection refused - Source CID already allocated
  2762. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
  2763. return 1;
  2764. }
  2765. // security: check encryption
  2766. if (service->required_security_level >= LEVEL_2){
  2767. if (gap_encryption_key_size(handle) == 0){
  2768. // 0x0008 Connection refused - insufficient encryption
  2769. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
  2770. return 1;
  2771. }
  2772. // anything less than 16 byte key size is insufficient
  2773. if (gap_encryption_key_size(handle) < 16){
  2774. // 0x0007 Connection refused – insufficient encryption key size
  2775. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
  2776. return 1;
  2777. }
  2778. }
  2779. // security: check authencation
  2780. if (service->required_security_level >= LEVEL_3){
  2781. if (!gap_authenticated(handle)){
  2782. // 0x0005 Connection refused – insufficient authentication
  2783. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
  2784. return 1;
  2785. }
  2786. }
  2787. // security: check authorization
  2788. if (service->required_security_level >= LEVEL_4){
  2789. if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
  2790. // 0x0006 Connection refused – insufficient authorization
  2791. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
  2792. return 1;
  2793. }
  2794. }
  2795. // allocate channel
  2796. channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
  2797. BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
  2798. if (!channel){
  2799. // 0x0004 Connection refused – no resources available
  2800. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
  2801. return 1;
  2802. }
  2803. channel->con_handle = handle;
  2804. channel->remote_cid = source_cid;
  2805. channel->remote_sig_id = sig_id;
  2806. channel->remote_mtu = little_endian_read_16(command, 8);
  2807. channel->remote_mps = little_endian_read_16(command, 10);
  2808. channel->credits_outgoing = little_endian_read_16(command, 12);
  2809. // set initial state
  2810. channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
  2811. channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
  2812. // add to connections list
  2813. btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
  2814. // post connection request event
  2815. l2cap_emit_le_incoming_connection(channel);
  2816. } else {
  2817. // Connection refused – LE_PSM not supported
  2818. l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
  2819. }
  2820. break;
  2821. case LE_CREDIT_BASED_CONNECTION_RESPONSE:
  2822. // check size
  2823. if (len < 10u) return 0u;
  2824. // Find channel for this sig_id and connection handle
  2825. channel = NULL;
  2826. btstack_linked_list_iterator_init(&it, &l2cap_channels);
  2827. while (btstack_linked_list_iterator_has_next(&it)){
  2828. l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
  2829. if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
  2830. if (a_channel->con_handle != handle) continue;
  2831. if (a_channel->local_sig_id != sig_id) continue;
  2832. channel = a_channel;
  2833. break;
  2834. }
  2835. if (!channel) break;
  2836. // cid + 0
  2837. result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
  2838. if (result){
  2839. channel->state = L2CAP_STATE_CLOSED;
  2840. // map l2cap connection response result to BTstack status enumeration
  2841. l2cap_emit_le_channel_opened(channel, result);
  2842. // discard channel
  2843. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  2844. l2cap_free_channel_entry(channel);
  2845. break;
  2846. }
  2847. // success
  2848. channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
  2849. channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
  2850. channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
  2851. channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
  2852. channel->state = L2CAP_STATE_OPEN;
  2853. l2cap_emit_le_channel_opened(channel, result);
  2854. break;
  2855. case LE_FLOW_CONTROL_CREDIT:
  2856. // check size
  2857. if (len < 4u) return 0u;
  2858. // find channel
  2859. local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
  2860. channel = l2cap_get_channel_for_local_cid(local_cid);
  2861. if (!channel) {
  2862. log_error("l2cap: no channel for cid 0x%02x", local_cid);
  2863. break;
  2864. }
  2865. new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
  2866. credits_before = channel->credits_outgoing;
  2867. channel->credits_outgoing += new_credits;
  2868. // check for credit overrun
  2869. if (credits_before > channel->credits_outgoing){
  2870. log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
  2871. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  2872. break;
  2873. }
  2874. log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
  2875. break;
  2876. case DISCONNECTION_REQUEST:
  2877. // check size
  2878. if (len < 4u) return 0u;
  2879. // find channel
  2880. local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
  2881. channel = l2cap_get_channel_for_local_cid(local_cid);
  2882. if (!channel) {
  2883. log_error("l2cap: no channel for cid 0x%02x", local_cid);
  2884. break;
  2885. }
  2886. channel->remote_sig_id = sig_id;
  2887. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
  2888. break;
  2889. #endif
  2890. case DISCONNECTION_RESPONSE:
  2891. break;
  2892. default:
  2893. // command unknown -> reject command
  2894. return 0;
  2895. }
  2896. return 1;
  2897. }
  2898. #endif
  2899. #ifdef ENABLE_CLASSIC
  2900. static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
  2901. #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
  2902. if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
  2903. int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
  2904. // assert control + FCS fields are inside
  2905. if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
  2906. if (l2cap_channel->fcs_option){
  2907. // verify FCS (required if one side requested it)
  2908. uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
  2909. uint16_t fcs_packet = little_endian_read_16(packet, size-2);
  2910. #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
  2911. // simulate fcs error
  2912. static int counter = 0;
  2913. if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
  2914. log_info("Simulate fcs error");
  2915. fcs_calculated++;
  2916. counter = 0;
  2917. }
  2918. #endif
  2919. if (fcs_calculated == fcs_packet){
  2920. log_info("Packet FCS 0x%04x verified", fcs_packet);
  2921. } else {
  2922. log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
  2923. // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
  2924. return;
  2925. }
  2926. }
  2927. // switch on packet type
  2928. uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
  2929. uint8_t req_seq = (control >> 8) & 0x3f;
  2930. int final = (control >> 7) & 0x01;
  2931. if (control & 1){
  2932. // S-Frame
  2933. int poll = (control >> 4) & 0x01;
  2934. l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
  2935. log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
  2936. l2cap_ertm_tx_packet_state_t * tx_state;
  2937. switch (s){
  2938. case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
  2939. log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
  2940. l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
  2941. if (poll && final){
  2942. // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
  2943. log_error("P=F=1 in S-Frame");
  2944. break;
  2945. }
  2946. if (poll){
  2947. // check if we did request selective retransmission before <==> we have stored SDU segments
  2948. int i;
  2949. int num_stored_out_of_order_packets = 0;
  2950. for (i=0;i<l2cap_channel->num_rx_buffers;i++){
  2951. int index = l2cap_channel->rx_store_index + i;
  2952. if (index >= l2cap_channel->num_rx_buffers){
  2953. index -= l2cap_channel->num_rx_buffers;
  2954. }
  2955. l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
  2956. if (!rx_state->valid) continue;
  2957. num_stored_out_of_order_packets++;
  2958. }
  2959. if (num_stored_out_of_order_packets){
  2960. l2cap_channel->send_supervisor_frame_selective_reject = 1;
  2961. } else {
  2962. l2cap_channel->send_supervisor_frame_receiver_ready = 1;
  2963. }
  2964. l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
  2965. }
  2966. if (final){
  2967. // Stop-MonitorTimer
  2968. l2cap_ertm_stop_monitor_timer(l2cap_channel);
  2969. // If UnackedFrames > 0 then Start-RetransTimer
  2970. if (l2cap_channel->unacked_frames){
  2971. l2cap_ertm_start_retransmission_timer(l2cap_channel);
  2972. }
  2973. // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
  2974. l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
  2975. }
  2976. break;
  2977. case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
  2978. log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
  2979. l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
  2980. // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
  2981. l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
  2982. break;
  2983. case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
  2984. log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
  2985. break;
  2986. case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
  2987. log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
  2988. if (poll){
  2989. l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
  2990. }
  2991. // find requested i-frame
  2992. tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
  2993. if (tx_state){
  2994. log_info("Retransmission for tx_seq %u requested", req_seq);
  2995. l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
  2996. tx_state->retransmission_requested = 1;
  2997. l2cap_channel->srej_active = 1;
  2998. }
  2999. break;
  3000. default:
  3001. break;
  3002. }
  3003. } else {
  3004. // I-Frame
  3005. // get control
  3006. l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
  3007. uint8_t tx_seq = (control >> 1) & 0x3f;
  3008. log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
  3009. log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
  3010. log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
  3011. l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
  3012. if (final){
  3013. // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
  3014. l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
  3015. }
  3016. // get SDU
  3017. const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
  3018. uint16_t payload_len = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
  3019. // assert SDU size is smaller or equal to our buffers
  3020. uint16_t max_payload_size = 0;
  3021. switch (sar){
  3022. case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
  3023. case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
  3024. // SDU Length + MPS
  3025. max_payload_size = l2cap_channel->local_mps + 2;
  3026. break;
  3027. case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
  3028. case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
  3029. max_payload_size = l2cap_channel->local_mps;
  3030. break;
  3031. }
  3032. if (payload_len > max_payload_size){
  3033. log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
  3034. return;
  3035. }
  3036. // check ordering
  3037. if (l2cap_channel->expected_tx_seq == tx_seq){
  3038. log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
  3039. l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
  3040. l2cap_channel->req_seq = l2cap_channel->expected_tx_seq;
  3041. // process SDU
  3042. l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
  3043. // process stored segments
  3044. while (true){
  3045. int index = l2cap_channel->rx_store_index;
  3046. l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
  3047. if (!rx_state->valid) break;
  3048. log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
  3049. l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
  3050. l2cap_channel->req_seq = l2cap_channel->expected_tx_seq;
  3051. rx_state->valid = 0;
  3052. l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
  3053. // update rx store index
  3054. index++;
  3055. if (index >= l2cap_channel->num_rx_buffers){
  3056. index = 0;
  3057. }
  3058. l2cap_channel->rx_store_index = index;
  3059. }
  3060. //
  3061. l2cap_channel->send_supervisor_frame_receiver_ready = 1;
  3062. } else {
  3063. int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
  3064. if (delta < 2){
  3065. // store segment
  3066. l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
  3067. log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
  3068. l2cap_channel->send_supervisor_frame_selective_reject = 1;
  3069. } else {
  3070. log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
  3071. l2cap_channel->send_supervisor_frame_reject = 1;
  3072. }
  3073. }
  3074. }
  3075. return;
  3076. }
  3077. #endif
  3078. l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
  3079. }
  3080. #endif
  3081. static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
  3082. #ifdef ENABLE_CLASSIC
  3083. l2cap_channel_t * l2cap_channel;
  3084. l2cap_fixed_channel_t * l2cap_fixed_channel;
  3085. uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
  3086. switch (channel_id) {
  3087. case L2CAP_CID_SIGNALING: {
  3088. uint32_t command_offset = 8;
  3089. while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
  3090. // assert signaling command is fully inside packet
  3091. uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
  3092. uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
  3093. if (next_command_offset > size){
  3094. log_error("l2cap signaling command len invalid -> drop");
  3095. break;
  3096. }
  3097. // handle signaling command
  3098. l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
  3099. // go to next command
  3100. command_offset = next_command_offset;
  3101. }
  3102. break;
  3103. }
  3104. case L2CAP_CID_CONNECTIONLESS_CHANNEL:
  3105. l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
  3106. if (!l2cap_fixed_channel) break;
  3107. if (!l2cap_fixed_channel->packet_handler) break;
  3108. (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
  3109. break;
  3110. default:
  3111. // Find channel for this channel_id and connection handle
  3112. l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
  3113. if (l2cap_channel) {
  3114. l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
  3115. }
  3116. break;
  3117. }
  3118. #else
  3119. UNUSED(handle); // ok: no code
  3120. UNUSED(packet); // ok: no code
  3121. UNUSED(size); // ok: no code
  3122. #endif
  3123. }
  3124. static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
  3125. #ifdef ENABLE_BLE
  3126. l2cap_fixed_channel_t * l2cap_fixed_channel;
  3127. #ifdef ENABLE_LE_DATA_CHANNELS
  3128. l2cap_channel_t * l2cap_channel;
  3129. #endif
  3130. uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
  3131. switch (channel_id) {
  3132. case L2CAP_CID_SIGNALING_LE: {
  3133. uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
  3134. uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
  3135. if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
  3136. int valid = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
  3137. if (!valid){
  3138. l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
  3139. }
  3140. break;
  3141. }
  3142. case L2CAP_CID_ATTRIBUTE_PROTOCOL:
  3143. l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
  3144. if (!l2cap_fixed_channel) break;
  3145. if (!l2cap_fixed_channel->packet_handler) break;
  3146. (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
  3147. break;
  3148. case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
  3149. l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
  3150. if (!l2cap_fixed_channel) break;
  3151. if (!l2cap_fixed_channel->packet_handler) break;
  3152. (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
  3153. break;
  3154. default:
  3155. #ifdef ENABLE_LE_DATA_CHANNELS
  3156. l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
  3157. if (l2cap_channel) {
  3158. // credit counting
  3159. if (l2cap_channel->credits_incoming == 0u){
  3160. log_error("LE Data Channel packet received but no incoming credits");
  3161. l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  3162. break;
  3163. }
  3164. l2cap_channel->credits_incoming--;
  3165. // automatic credits
  3166. if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
  3167. l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
  3168. }
  3169. // first fragment
  3170. uint16_t pos = 0;
  3171. if (!l2cap_channel->receive_sdu_len){
  3172. uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
  3173. if(sdu_len > l2cap_channel->local_mtu) break; // SDU would be larger than our buffer
  3174. l2cap_channel->receive_sdu_len = sdu_len;
  3175. l2cap_channel->receive_sdu_pos = 0;
  3176. pos += 2u;
  3177. size -= 2u;
  3178. }
  3179. uint16_t fragment_size = size-COMPLETE_L2CAP_HEADER;
  3180. uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
  3181. if (fragment_size > remaining_space) break; // SDU would cause buffer overrun
  3182. (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
  3183. &packet[COMPLETE_L2CAP_HEADER + pos],
  3184. fragment_size);
  3185. l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
  3186. // done?
  3187. log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
  3188. if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
  3189. l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
  3190. l2cap_channel->receive_sdu_len = 0;
  3191. }
  3192. } else {
  3193. log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
  3194. }
  3195. #endif
  3196. break;
  3197. }
  3198. #else
  3199. UNUSED(handle); // ok: no code
  3200. UNUSED(packet); // ok: no code
  3201. UNUSED(size); // ok: no code
  3202. #endif
  3203. }
  3204. static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  3205. UNUSED(packet_type); // ok: registered with hci_register_acl_packet_handler
  3206. UNUSED(channel); // ok: there is no channel
  3207. // Assert full L2CAP header present
  3208. if (size < COMPLETE_L2CAP_HEADER) return;
  3209. // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
  3210. hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
  3211. hci_connection_t *conn = hci_connection_for_handle(handle);
  3212. if (!conn) return;
  3213. if (conn->address_type == BD_ADDR_TYPE_ACL){
  3214. l2cap_acl_classic_handler(handle, packet, size);
  3215. } else {
  3216. l2cap_acl_le_handler(handle, packet, size);
  3217. }
  3218. l2cap_run();
  3219. }
  3220. // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
  3221. void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
  3222. l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
  3223. if (!channel) return;
  3224. channel->packet_handler = the_packet_handler;
  3225. }
  3226. #ifdef ENABLE_CLASSIC
  3227. // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
  3228. void l2cap_finialize_channel_close(l2cap_channel_t * channel){
  3229. channel->state = L2CAP_STATE_CLOSED;
  3230. l2cap_handle_channel_closed(channel);
  3231. // discard channel
  3232. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  3233. l2cap_free_channel_entry(channel);
  3234. }
  3235. #endif
  3236. #ifdef L2CAP_USES_CHANNELS
  3237. static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
  3238. btstack_linked_list_iterator_t it;
  3239. btstack_linked_list_iterator_init(&it, services);
  3240. while (btstack_linked_list_iterator_has_next(&it)){
  3241. l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
  3242. if ( service->psm == psm){
  3243. return service;
  3244. };
  3245. }
  3246. return NULL;
  3247. }
  3248. #endif
  3249. #ifdef ENABLE_CLASSIC
  3250. static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
  3251. return l2cap_get_service_internal(&l2cap_services, psm);
  3252. }
  3253. uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
  3254. log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
  3255. // check for alread registered psm
  3256. l2cap_service_t *service = l2cap_get_service(psm);
  3257. if (service) {
  3258. log_error("l2cap_register_service: PSM %u already registered", psm);
  3259. return L2CAP_SERVICE_ALREADY_REGISTERED;
  3260. }
  3261. // alloc structure
  3262. service = btstack_memory_l2cap_service_get();
  3263. if (!service) {
  3264. log_error("l2cap_register_service: no memory for l2cap_service_t");
  3265. return BTSTACK_MEMORY_ALLOC_FAILED;
  3266. }
  3267. // fill in
  3268. service->psm = psm;
  3269. service->mtu = mtu;
  3270. service->packet_handler = service_packet_handler;
  3271. service->required_security_level = security_level;
  3272. // add to services list
  3273. btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
  3274. // enable page scan
  3275. gap_connectable_control(1);
  3276. return ERROR_CODE_SUCCESS;
  3277. }
  3278. uint8_t l2cap_unregister_service(uint16_t psm){
  3279. log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
  3280. l2cap_service_t *service = l2cap_get_service(psm);
  3281. if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
  3282. btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
  3283. btstack_memory_l2cap_service_free(service);
  3284. // disable page scan when no services registered
  3285. if (btstack_linked_list_empty(&l2cap_services)) {
  3286. gap_connectable_control(0);
  3287. }
  3288. return ERROR_CODE_SUCCESS;
  3289. }
  3290. #endif
  3291. #ifdef ENABLE_LE_DATA_CHANNELS
  3292. static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
  3293. if (!channel->waiting_for_can_send_now) return;
  3294. if (channel->send_sdu_buffer) return;
  3295. channel->waiting_for_can_send_now = 0;
  3296. log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
  3297. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
  3298. }
  3299. // 1BH2222
  3300. static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
  3301. log_info("L2CAP_EVENT_LE_INCOMING_CONNECTION addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
  3302. channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
  3303. uint8_t event[19];
  3304. event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
  3305. event[1] = sizeof(event) - 2u;
  3306. event[2] = channel->address_type;
  3307. reverse_bd_addr(channel->address, &event[3]);
  3308. little_endian_store_16(event, 9, channel->con_handle);
  3309. little_endian_store_16(event, 11, channel->psm);
  3310. little_endian_store_16(event, 13, channel->local_cid);
  3311. little_endian_store_16(event, 15, channel->remote_cid);
  3312. little_endian_store_16(event, 17, channel->remote_mtu);
  3313. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  3314. l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
  3315. }
  3316. // 11BH22222
  3317. static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
  3318. log_info("L2CAP_EVENT_LE_CHANNEL_OPENED status 0x%x addr_type %u addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u",
  3319. status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
  3320. channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
  3321. uint8_t event[23];
  3322. event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
  3323. event[1] = sizeof(event) - 2u;
  3324. event[2] = status;
  3325. event[3] = channel->address_type;
  3326. reverse_bd_addr(channel->address, &event[4]);
  3327. little_endian_store_16(event, 10, channel->con_handle);
  3328. event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
  3329. little_endian_store_16(event, 13, channel->psm);
  3330. little_endian_store_16(event, 15, channel->local_cid);
  3331. little_endian_store_16(event, 17, channel->remote_cid);
  3332. little_endian_store_16(event, 19, channel->local_mtu);
  3333. little_endian_store_16(event, 21, channel->remote_mtu);
  3334. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  3335. l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
  3336. }
  3337. // 2
  3338. static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
  3339. log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
  3340. uint8_t event[4];
  3341. event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
  3342. event[1] = sizeof(event) - 2u;
  3343. little_endian_store_16(event, 2, channel->local_cid);
  3344. hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
  3345. l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
  3346. }
  3347. static void l2cap_le_send_pdu(l2cap_channel_t *channel){
  3348. btstack_assert(channel != NULL);
  3349. btstack_assert(channel->send_sdu_buffer != NULL);
  3350. btstack_assert(channel->credits_outgoing > 0);
  3351. // send part of SDU
  3352. hci_reserve_packet_buffer();
  3353. uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
  3354. uint8_t * l2cap_payload = acl_buffer + 8;
  3355. uint16_t pos = 0;
  3356. if (!channel->send_sdu_pos){
  3357. // store SDU len
  3358. channel->send_sdu_pos += 2u;
  3359. little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
  3360. pos += 2u;
  3361. }
  3362. uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
  3363. log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
  3364. (void)memcpy(&l2cap_payload[pos],
  3365. &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
  3366. payload_size); // -2 for virtual SDU len
  3367. pos += payload_size;
  3368. channel->send_sdu_pos += payload_size;
  3369. l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
  3370. channel->credits_outgoing--;
  3371. hci_send_acl_packet_buffer(8u + pos);
  3372. if (channel->send_sdu_pos >= (channel->send_sdu_len + 2u)){
  3373. channel->send_sdu_buffer = NULL;
  3374. // send done event
  3375. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
  3376. // inform about can send now
  3377. l2cap_le_notify_channel_can_send(channel);
  3378. }
  3379. }
  3380. // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
  3381. void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
  3382. channel->state = L2CAP_STATE_CLOSED;
  3383. l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
  3384. // discard channel
  3385. btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
  3386. l2cap_free_channel_entry(channel);
  3387. }
  3388. static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
  3389. return l2cap_get_service_internal(&l2cap_le_services, le_psm);
  3390. }
  3391. uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
  3392. log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
  3393. // check for alread registered psm
  3394. l2cap_service_t *service = l2cap_le_get_service(psm);
  3395. if (service) {
  3396. return L2CAP_SERVICE_ALREADY_REGISTERED;
  3397. }
  3398. // alloc structure
  3399. service = btstack_memory_l2cap_service_get();
  3400. if (!service) {
  3401. log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
  3402. return BTSTACK_MEMORY_ALLOC_FAILED;
  3403. }
  3404. // fill in
  3405. service->psm = psm;
  3406. service->mtu = 0;
  3407. service->packet_handler = packet_handler;
  3408. service->required_security_level = security_level;
  3409. // add to services list
  3410. btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
  3411. // done
  3412. return ERROR_CODE_SUCCESS;
  3413. }
  3414. uint8_t l2cap_le_unregister_service(uint16_t psm) {
  3415. log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
  3416. l2cap_service_t *service = l2cap_le_get_service(psm);
  3417. if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
  3418. btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
  3419. btstack_memory_l2cap_service_free(service);
  3420. return ERROR_CODE_SUCCESS;
  3421. }
  3422. uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
  3423. // get channel
  3424. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  3425. if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  3426. // validate state
  3427. if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
  3428. return ERROR_CODE_COMMAND_DISALLOWED;
  3429. }
  3430. // set state accept connection
  3431. channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
  3432. channel->receive_sdu_buffer = receive_sdu_buffer;
  3433. channel->local_mtu = mtu;
  3434. channel->new_credits_incoming = initial_credits;
  3435. channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
  3436. // test
  3437. // channel->new_credits_incoming = 1;
  3438. // go
  3439. l2cap_run();
  3440. return ERROR_CODE_SUCCESS;
  3441. }
  3442. /**
  3443. * @brief Deny incoming LE Data Channel connection due to resource constraints
  3444. * @param local_cid L2CAP LE Data Channel Identifier
  3445. */
  3446. uint8_t l2cap_le_decline_connection(uint16_t local_cid){
  3447. // get channel
  3448. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  3449. if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  3450. // validate state
  3451. if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
  3452. return ERROR_CODE_COMMAND_DISALLOWED;
  3453. }
  3454. // set state decline connection
  3455. channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
  3456. channel->reason = 0x04; // no resources available
  3457. l2cap_run();
  3458. return ERROR_CODE_SUCCESS;
  3459. }
  3460. uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
  3461. uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
  3462. uint16_t * out_local_cid) {
  3463. log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
  3464. hci_connection_t * connection = hci_connection_for_handle(con_handle);
  3465. if (!connection) {
  3466. log_error("no hci_connection for handle 0x%04x", con_handle);
  3467. return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
  3468. }
  3469. l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address, connection->address_type, psm, mtu, security_level);
  3470. if (!channel) {
  3471. return BTSTACK_MEMORY_ALLOC_FAILED;
  3472. }
  3473. log_info("l2cap_le_create_channel %p", channel);
  3474. // store local_cid
  3475. if (out_local_cid){
  3476. *out_local_cid = channel->local_cid;
  3477. }
  3478. // provide buffer
  3479. channel->con_handle = con_handle;
  3480. channel->receive_sdu_buffer = receive_sdu_buffer;
  3481. channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
  3482. channel->new_credits_incoming = initial_credits;
  3483. channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
  3484. // add to connections list
  3485. btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
  3486. // go
  3487. l2cap_run();
  3488. return ERROR_CODE_SUCCESS;
  3489. }
  3490. /**
  3491. * @brief Provide credtis for LE Data Channel
  3492. * @param local_cid L2CAP LE Data Channel Identifier
  3493. * @param credits Number additional credits for peer
  3494. */
  3495. uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
  3496. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  3497. if (!channel) {
  3498. log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
  3499. return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  3500. }
  3501. // check state
  3502. if (channel->state != L2CAP_STATE_OPEN){
  3503. log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
  3504. }
  3505. // assert incoming credits + credits <= 0xffff
  3506. uint32_t total_credits = channel->credits_incoming;
  3507. total_credits += channel->new_credits_incoming;
  3508. total_credits += credits;
  3509. if (total_credits > 0xffffu){
  3510. log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
  3511. channel->new_credits_incoming, credits);
  3512. }
  3513. // set credits_granted
  3514. channel->new_credits_incoming += credits;
  3515. // go
  3516. l2cap_run();
  3517. return ERROR_CODE_SUCCESS;
  3518. }
  3519. /**
  3520. * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
  3521. * @param local_cid L2CAP LE Data Channel Identifier
  3522. */
  3523. int l2cap_le_can_send_now(uint16_t local_cid){
  3524. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  3525. if (!channel) {
  3526. log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
  3527. return 0;
  3528. }
  3529. // check state
  3530. if (channel->state != L2CAP_STATE_OPEN) return 0;
  3531. // check queue
  3532. if (channel->send_sdu_buffer) return 0;
  3533. // fine, go ahead
  3534. return 1;
  3535. }
  3536. /**
  3537. * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
  3538. * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
  3539. * so packet handler should be ready to handle it
  3540. * @param local_cid L2CAP LE Data Channel Identifier
  3541. */
  3542. uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
  3543. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  3544. if (!channel) {
  3545. log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
  3546. return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  3547. }
  3548. channel->waiting_for_can_send_now = 1;
  3549. l2cap_le_notify_channel_can_send(channel);
  3550. return ERROR_CODE_SUCCESS;
  3551. }
  3552. /**
  3553. * @brief Send data via LE Data Channel
  3554. * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
  3555. * @param local_cid L2CAP LE Data Channel Identifier
  3556. * @param data data to send
  3557. * @param size data size
  3558. */
  3559. uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
  3560. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  3561. if (!channel) {
  3562. log_error("l2cap_send no channel for cid 0x%02x", local_cid);
  3563. return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  3564. }
  3565. if (len > channel->remote_mtu){
  3566. log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
  3567. return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
  3568. }
  3569. if (channel->send_sdu_buffer){
  3570. log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
  3571. return BTSTACK_ACL_BUFFERS_FULL;
  3572. }
  3573. channel->send_sdu_buffer = data;
  3574. channel->send_sdu_len = len;
  3575. channel->send_sdu_pos = 0;
  3576. l2cap_notify_channel_can_send();
  3577. return ERROR_CODE_SUCCESS;
  3578. }
  3579. /**
  3580. * @brief Disconnect from LE Data Channel
  3581. * @param local_cid L2CAP LE Data Channel Identifier
  3582. */
  3583. uint8_t l2cap_le_disconnect(uint16_t local_cid)
  3584. {
  3585. l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
  3586. if (!channel) {
  3587. log_error("l2cap_send no channel for cid 0x%02x", local_cid);
  3588. return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
  3589. }
  3590. channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
  3591. l2cap_run();
  3592. return ERROR_CODE_SUCCESS;
  3593. }
  3594. #endif