mqtt5_client.c 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/mqtt/v5/mqtt5_client.h>
  6. #include <aws/common/clock.h>
  7. #include <aws/common/string.h>
  8. #include <aws/http/proxy.h>
  9. #include <aws/http/request_response.h>
  10. #include <aws/http/websocket.h>
  11. #include <aws/io/channel_bootstrap.h>
  12. #include <aws/io/event_loop.h>
  13. #include <aws/mqtt/private/shared_constants.h>
  14. #include <aws/mqtt/private/v5/mqtt5_client_impl.h>
  15. #include <aws/mqtt/private/v5/mqtt5_options_storage.h>
  16. #include <aws/mqtt/private/v5/mqtt5_utils.h>
  17. #include <inttypes.h>
  18. #ifdef _MSC_VER
  19. # pragma warning(push)
  20. # pragma warning(disable : 4232) /* function pointer to dll symbol */
  21. #endif
  22. #define AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH 4096
  23. #define AWS_MQTT5_DEFAULT_CONNACK_PACKET_TIMEOUT_MS 10000
  24. const char *aws_mqtt5_client_state_to_c_string(enum aws_mqtt5_client_state state) {
  25. switch (state) {
  26. case AWS_MCS_STOPPED:
  27. return "STOPPED";
  28. case AWS_MCS_CONNECTING:
  29. return "CONNECTING";
  30. case AWS_MCS_MQTT_CONNECT:
  31. return "MQTT_CONNECT";
  32. case AWS_MCS_CONNECTED:
  33. return "CONNECTED";
  34. case AWS_MCS_CLEAN_DISCONNECT:
  35. return "CLEAN_DISCONNECT";
  36. case AWS_MCS_CHANNEL_SHUTDOWN:
  37. return "CHANNEL_SHUTDOWN";
  38. case AWS_MCS_PENDING_RECONNECT:
  39. return "PENDING_RECONNECT";
  40. case AWS_MCS_TERMINATED:
  41. return "TERMINATED";
  42. default:
  43. return "UNKNOWN";
  44. }
  45. }
  46. static bool s_aws_mqtt5_operation_is_retainable(struct aws_mqtt5_operation *operation) {
  47. switch (operation->packet_type) {
  48. case AWS_MQTT5_PT_PUBLISH:
  49. case AWS_MQTT5_PT_SUBSCRIBE:
  50. case AWS_MQTT5_PT_UNSUBSCRIBE:
  51. return true;
  52. default:
  53. return false;
  54. }
  55. }
  56. static void s_init_statistics(struct aws_mqtt5_client_operation_statistics_impl *stats) {
  57. aws_atomic_store_int(&stats->incomplete_operation_count_atomic, 0);
  58. aws_atomic_store_int(&stats->incomplete_operation_size_atomic, 0);
  59. aws_atomic_store_int(&stats->unacked_operation_count_atomic, 0);
  60. aws_atomic_store_int(&stats->unacked_operation_size_atomic, 0);
  61. }
  62. static bool s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(
  63. struct aws_mqtt5_operation *operation,
  64. enum aws_mqtt5_client_operation_queue_behavior_type queue_behavior) {
  65. switch (aws_mqtt5_client_operation_queue_behavior_type_to_non_default(queue_behavior)) {
  66. case AWS_MQTT5_COQBT_FAIL_ALL_ON_DISCONNECT:
  67. return false;
  68. case AWS_MQTT5_COQBT_FAIL_QOS0_PUBLISH_ON_DISCONNECT:
  69. if (!s_aws_mqtt5_operation_is_retainable(operation)) {
  70. return false;
  71. }
  72. if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
  73. const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
  74. if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
  75. return false;
  76. }
  77. }
  78. return true;
  79. case AWS_MQTT5_COQBT_FAIL_NON_QOS1_PUBLISH_ON_DISCONNECT:
  80. if (!s_aws_mqtt5_operation_is_retainable(operation)) {
  81. return false;
  82. }
  83. if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
  84. const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
  85. if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
  86. return true;
  87. }
  88. }
  89. return false;
  90. default:
  91. return false;
  92. }
  93. }
  94. typedef bool(mqtt5_operation_filter)(struct aws_mqtt5_operation *operation, void *filter_context);
  95. static void s_filter_operation_list(
  96. struct aws_linked_list *source_operations,
  97. mqtt5_operation_filter *filter_fn,
  98. struct aws_linked_list *filtered_operations,
  99. void *filter_context) {
  100. struct aws_linked_list_node *node = aws_linked_list_begin(source_operations);
  101. while (node != aws_linked_list_end(source_operations)) {
  102. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
  103. node = aws_linked_list_next(node);
  104. if (filter_fn(operation, filter_context)) {
  105. aws_linked_list_remove(&operation->node);
  106. aws_linked_list_push_back(filtered_operations, &operation->node);
  107. }
  108. }
  109. }
  110. typedef void(mqtt5_operation_applicator)(struct aws_mqtt5_operation *operation, void *applicator_context);
  111. static void s_apply_to_operation_list(
  112. struct aws_linked_list *operations,
  113. mqtt5_operation_applicator *applicator_fn,
  114. void *applicator_context) {
  115. struct aws_linked_list_node *node = aws_linked_list_begin(operations);
  116. while (node != aws_linked_list_end(operations)) {
  117. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
  118. node = aws_linked_list_next(node);
  119. applicator_fn(operation, applicator_context);
  120. }
  121. }
  122. static int s_aws_mqtt5_client_change_desired_state(
  123. struct aws_mqtt5_client *client,
  124. enum aws_mqtt5_client_state desired_state,
  125. struct aws_mqtt5_operation_disconnect *disconnect_operation);
  126. static uint64_t s_hash_uint16_t(const void *item) {
  127. return *(uint16_t *)item;
  128. }
  129. static bool s_uint16_t_eq(const void *a, const void *b) {
  130. return *(uint16_t *)a == *(uint16_t *)b;
  131. }
  132. static uint64_t s_aws_mqtt5_client_compute_operational_state_service_time(
  133. const struct aws_mqtt5_client_operational_state *client_operational_state,
  134. uint64_t now);
  135. static int s_submit_operation(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation);
  136. static void s_complete_operation(
  137. struct aws_mqtt5_client *client,
  138. struct aws_mqtt5_operation *operation,
  139. int error_code,
  140. enum aws_mqtt5_packet_type packet_type,
  141. const void *view) {
  142. if (client != NULL) {
  143. aws_mqtt5_client_statistics_change_operation_statistic_state(client, operation, AWS_MQTT5_OSS_NONE);
  144. }
  145. aws_mqtt5_operation_complete(operation, error_code, packet_type, view);
  146. aws_mqtt5_operation_release(operation);
  147. }
  148. static void s_complete_operation_list(
  149. struct aws_mqtt5_client *client,
  150. struct aws_linked_list *operation_list,
  151. int error_code) {
  152. struct aws_linked_list_node *node = aws_linked_list_begin(operation_list);
  153. while (node != aws_linked_list_end(operation_list)) {
  154. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
  155. node = aws_linked_list_next(node);
  156. s_complete_operation(client, operation, error_code, AWS_MQTT5_PT_NONE, NULL);
  157. }
  158. /* we've released everything, so reset the list to empty */
  159. aws_linked_list_init(operation_list);
  160. }
  161. static void s_check_timeouts(struct aws_mqtt5_client *client, uint64_t now) {
  162. if (client->config->ack_timeout_seconds == 0) {
  163. return;
  164. }
  165. struct aws_linked_list_node *node = aws_linked_list_begin(&client->operational_state.unacked_operations);
  166. while (node != aws_linked_list_end(&client->operational_state.unacked_operations)) {
  167. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
  168. node = aws_linked_list_next(node);
  169. if (operation->ack_timeout_timepoint_ns < now) {
  170. /* Timeout for this packet has been reached */
  171. aws_mqtt5_packet_id_t packet_id = aws_mqtt5_operation_get_packet_id(operation);
  172. switch (operation->packet_type) {
  173. case AWS_MQTT5_PT_SUBSCRIBE:
  174. /* SUBSCRIBE has timed out. */
  175. AWS_LOGF_INFO(
  176. AWS_LS_MQTT5_CLIENT,
  177. "id=%p: SUBSCRIBE packet with id:%d has timed out",
  178. (void *)client,
  179. packet_id);
  180. break;
  181. case AWS_MQTT5_PT_UNSUBSCRIBE:
  182. /* UNSUBSCRIBE has timed out. */
  183. AWS_LOGF_INFO(
  184. AWS_LS_MQTT5_CLIENT,
  185. "id=%p: UNSUBSCRIBE packet with id:%d has timed out",
  186. (void *)client,
  187. packet_id);
  188. break;
  189. case AWS_MQTT5_PT_PUBLISH:
  190. /* PUBLISH has timed out. */
  191. AWS_LOGF_INFO(
  192. AWS_LS_MQTT5_CLIENT,
  193. "id=%p: PUBLISH packet with id:%d has timed out",
  194. (void *)client,
  195. packet_id);
  196. aws_mqtt5_client_flow_control_state_on_puback(client);
  197. break;
  198. default:
  199. /* something is wrong, there should be no other packet type in this linked list */
  200. break;
  201. }
  202. struct aws_hash_element *elem = NULL;
  203. aws_hash_table_find(&client->operational_state.unacked_operations_table, &packet_id, &elem);
  204. if (elem == NULL || elem->value == NULL) {
  205. AWS_LOGF_ERROR(
  206. AWS_LS_MQTT5_CLIENT,
  207. "id=%p: timeout for unknown operation with id %d",
  208. (void *)client,
  209. (int)packet_id);
  210. return;
  211. }
  212. aws_linked_list_remove(&operation->node);
  213. aws_hash_table_remove(&client->operational_state.unacked_operations_table, &packet_id, NULL, NULL);
  214. s_complete_operation(client, operation, AWS_ERROR_MQTT_TIMEOUT, AWS_MQTT5_PT_NONE, NULL);
  215. } else {
  216. break;
  217. }
  218. }
  219. }
  220. static void s_mqtt5_client_final_destroy(struct aws_mqtt5_client *client) {
  221. if (client == NULL) {
  222. return;
  223. }
  224. aws_mqtt5_client_termination_completion_fn *client_termination_handler = NULL;
  225. void *client_termination_handler_user_data = NULL;
  226. if (client->config != NULL) {
  227. client_termination_handler = client->config->client_termination_handler;
  228. client_termination_handler_user_data = client->config->client_termination_handler_user_data;
  229. }
  230. aws_mqtt5_callback_set_manager_clean_up(&client->callback_manager);
  231. aws_mqtt5_client_operational_state_clean_up(&client->operational_state);
  232. aws_mqtt5_client_options_storage_destroy((struct aws_mqtt5_client_options_storage *)client->config);
  233. aws_mqtt5_negotiated_settings_clean_up(&client->negotiated_settings);
  234. aws_http_message_release(client->handshake);
  235. aws_mqtt5_encoder_clean_up(&client->encoder);
  236. aws_mqtt5_decoder_clean_up(&client->decoder);
  237. aws_mqtt5_inbound_topic_alias_resolver_clean_up(&client->inbound_topic_alias_resolver);
  238. aws_mqtt5_outbound_topic_alias_resolver_destroy(client->outbound_topic_alias_resolver);
  239. aws_mem_release(client->allocator, client);
  240. if (client_termination_handler != NULL) {
  241. (*client_termination_handler)(client_termination_handler_user_data);
  242. }
  243. }
  244. static void s_on_mqtt5_client_zero_ref_count(void *user_data) {
  245. struct aws_mqtt5_client *client = user_data;
  246. s_aws_mqtt5_client_change_desired_state(client, AWS_MCS_TERMINATED, NULL);
  247. }
  248. static void s_aws_mqtt5_client_emit_stopped_lifecycle_event(struct aws_mqtt5_client *client) {
  249. AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: emitting stopped lifecycle event", (void *)client);
  250. struct aws_mqtt5_client_lifecycle_event event;
  251. AWS_ZERO_STRUCT(event);
  252. event.event_type = AWS_MQTT5_CLET_STOPPED;
  253. event.client = client;
  254. aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
  255. }
  256. static void s_aws_mqtt5_client_emit_connecting_lifecycle_event(struct aws_mqtt5_client *client) {
  257. AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: emitting connecting lifecycle event", (void *)client);
  258. client->lifecycle_state = AWS_MQTT5_LS_CONNECTING;
  259. struct aws_mqtt5_client_lifecycle_event event;
  260. AWS_ZERO_STRUCT(event);
  261. event.event_type = AWS_MQTT5_CLET_ATTEMPTING_CONNECT;
  262. event.client = client;
  263. aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
  264. }
  265. static void s_aws_mqtt5_client_emit_connection_success_lifecycle_event(
  266. struct aws_mqtt5_client *client,
  267. const struct aws_mqtt5_packet_connack_view *connack_view) {
  268. AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: emitting connection success lifecycle event", (void *)client);
  269. client->lifecycle_state = AWS_MQTT5_LS_CONNECTED;
  270. struct aws_mqtt5_client_lifecycle_event event;
  271. AWS_ZERO_STRUCT(event);
  272. event.event_type = AWS_MQTT5_CLET_CONNECTION_SUCCESS;
  273. event.client = client;
  274. event.settings = &client->negotiated_settings;
  275. event.connack_data = connack_view;
  276. aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
  277. }
  278. /*
  279. * Emits either a CONNECTION_FAILED or DISCONNECT event based on the current life cycle state. Once a "final"
  280. * event is emitted by the client, it must attempt to reconnect before another one will be emitted, since the
  281. * lifecycle state check will early out until then. It is expected that this function may get called unnecessarily
  282. * often during various channel shutdown or disconnection/failure flows. This will not affect overall correctness.
  283. */
  284. static void s_aws_mqtt5_client_emit_final_lifecycle_event(
  285. struct aws_mqtt5_client *client,
  286. int error_code,
  287. const struct aws_mqtt5_packet_connack_view *connack_view,
  288. const struct aws_mqtt5_packet_disconnect_view *disconnect_view) {
  289. if (client->lifecycle_state == AWS_MQTT5_LS_NONE) {
  290. /* we already emitted a final event earlier */
  291. return;
  292. }
  293. struct aws_mqtt5_client_lifecycle_event event;
  294. AWS_ZERO_STRUCT(event);
  295. if (client->lifecycle_state == AWS_MQTT5_LS_CONNECTING) {
  296. AWS_FATAL_ASSERT(disconnect_view == NULL);
  297. event.event_type = AWS_MQTT5_CLET_CONNECTION_FAILURE;
  298. AWS_LOGF_INFO(
  299. AWS_LS_MQTT5_CLIENT,
  300. "id=%p: emitting connection failure lifecycle event with error code %d(%s)",
  301. (void *)client,
  302. error_code,
  303. aws_error_debug_str(error_code));
  304. } else {
  305. AWS_FATAL_ASSERT(client->lifecycle_state == AWS_MQTT5_LS_CONNECTED);
  306. AWS_FATAL_ASSERT(connack_view == NULL);
  307. event.event_type = AWS_MQTT5_CLET_DISCONNECTION;
  308. AWS_LOGF_INFO(
  309. AWS_LS_MQTT5_CLIENT,
  310. "id=%p: emitting disconnection lifecycle event with error code %d(%s)",
  311. (void *)client,
  312. error_code,
  313. aws_error_debug_str(error_code));
  314. }
  315. event.error_code = error_code;
  316. event.connack_data = connack_view;
  317. event.disconnect_data = disconnect_view;
  318. client->lifecycle_state = AWS_MQTT5_LS_NONE;
  319. aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
  320. }
  321. /*
  322. * next_service_time == 0 means to not service the client, i.e. a state that only cares about external events
  323. *
  324. * This includes connecting and channel shutdown. Terminated is also included, but it's a state that only exists
  325. * instantaneously before final destruction.
  326. */
  327. static uint64_t s_compute_next_service_time_client_stopped(struct aws_mqtt5_client *client, uint64_t now) {
  328. /* have we been told to connect or terminate? */
  329. if (client->desired_state != AWS_MCS_STOPPED) {
  330. return now;
  331. }
  332. return 0;
  333. }
  334. static uint64_t s_compute_next_service_time_client_connecting(struct aws_mqtt5_client *client, uint64_t now) {
  335. (void)client;
  336. (void)now;
  337. return 0;
  338. }
  339. static uint64_t s_compute_next_service_time_client_mqtt_connect(struct aws_mqtt5_client *client, uint64_t now) {
  340. /* This state is interruptable by a stop/terminate */
  341. if (client->desired_state != AWS_MCS_CONNECTED) {
  342. return now;
  343. }
  344. uint64_t operation_processing_time =
  345. s_aws_mqtt5_client_compute_operational_state_service_time(&client->operational_state, now);
  346. if (operation_processing_time == 0) {
  347. return client->next_mqtt_connect_packet_timeout_time;
  348. }
  349. return aws_min_u64(client->next_mqtt_connect_packet_timeout_time, operation_processing_time);
  350. }
  351. static uint64_t s_min_non_0_64(uint64_t a, uint64_t b) {
  352. if (a == 0) {
  353. return b;
  354. }
  355. if (b == 0) {
  356. return a;
  357. }
  358. return aws_min_u64(a, b);
  359. }
  360. static uint64_t s_compute_next_service_time_client_connected(struct aws_mqtt5_client *client, uint64_t now) {
  361. /* ping and ping timeout */
  362. uint64_t next_service_time = client->next_ping_time;
  363. if (client->next_ping_timeout_time != 0) {
  364. next_service_time = aws_min_u64(next_service_time, client->next_ping_timeout_time);
  365. }
  366. /* unacked operations timeout */
  367. if (client->config->ack_timeout_seconds != 0 &&
  368. !aws_linked_list_empty(&client->operational_state.unacked_operations)) {
  369. struct aws_linked_list_node *node = aws_linked_list_begin(&client->operational_state.unacked_operations);
  370. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
  371. next_service_time = aws_min_u64(next_service_time, operation->ack_timeout_timepoint_ns);
  372. }
  373. if (client->desired_state != AWS_MCS_CONNECTED) {
  374. next_service_time = now;
  375. }
  376. uint64_t operation_processing_time =
  377. s_aws_mqtt5_client_compute_operational_state_service_time(&client->operational_state, now);
  378. next_service_time = s_min_non_0_64(operation_processing_time, next_service_time);
  379. /* reset reconnect delay interval */
  380. next_service_time = s_min_non_0_64(client->next_reconnect_delay_reset_time_ns, next_service_time);
  381. return next_service_time;
  382. }
  383. static uint64_t s_compute_next_service_time_client_clean_disconnect(struct aws_mqtt5_client *client, uint64_t now) {
  384. uint64_t ack_timeout_time = 0;
  385. /* unacked operations timeout */
  386. if (client->config->ack_timeout_seconds != 0 &&
  387. !aws_linked_list_empty(&client->operational_state.unacked_operations)) {
  388. struct aws_linked_list_node *node = aws_linked_list_begin(&client->operational_state.unacked_operations);
  389. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
  390. ack_timeout_time = operation->ack_timeout_timepoint_ns;
  391. }
  392. uint64_t operation_processing_time =
  393. s_aws_mqtt5_client_compute_operational_state_service_time(&client->operational_state, now);
  394. return s_min_non_0_64(ack_timeout_time, operation_processing_time);
  395. }
  396. static uint64_t s_compute_next_service_time_client_channel_shutdown(struct aws_mqtt5_client *client, uint64_t now) {
  397. (void)client;
  398. (void)now;
  399. return 0;
  400. }
  401. static uint64_t s_compute_next_service_time_client_pending_reconnect(struct aws_mqtt5_client *client, uint64_t now) {
  402. if (client->desired_state != AWS_MCS_CONNECTED) {
  403. return now;
  404. }
  405. return client->next_reconnect_time_ns;
  406. }
  407. static uint64_t s_compute_next_service_time_client_terminated(struct aws_mqtt5_client *client, uint64_t now) {
  408. (void)client;
  409. (void)now;
  410. return 0;
  411. }
  412. static uint64_t s_compute_next_service_time_by_current_state(struct aws_mqtt5_client *client, uint64_t now) {
  413. switch (client->current_state) {
  414. case AWS_MCS_STOPPED:
  415. return s_compute_next_service_time_client_stopped(client, now);
  416. case AWS_MCS_CONNECTING:
  417. return s_compute_next_service_time_client_connecting(client, now);
  418. case AWS_MCS_MQTT_CONNECT:
  419. return s_compute_next_service_time_client_mqtt_connect(client, now);
  420. case AWS_MCS_CONNECTED:
  421. return s_compute_next_service_time_client_connected(client, now);
  422. case AWS_MCS_CLEAN_DISCONNECT:
  423. return s_compute_next_service_time_client_clean_disconnect(client, now);
  424. case AWS_MCS_CHANNEL_SHUTDOWN:
  425. return s_compute_next_service_time_client_channel_shutdown(client, now);
  426. case AWS_MCS_PENDING_RECONNECT:
  427. return s_compute_next_service_time_client_pending_reconnect(client, now);
  428. case AWS_MCS_TERMINATED:
  429. return s_compute_next_service_time_client_terminated(client, now);
  430. }
  431. return 0;
  432. }
  433. static void s_reevaluate_service_task(struct aws_mqtt5_client *client) {
  434. /*
  435. * This causes the client to only reevaluate service schedule time at the end of the service call or in
  436. * a callback from an external event.
  437. */
  438. if (client->in_service) {
  439. return;
  440. }
  441. uint64_t now = (*client->vtable->get_current_time_fn)();
  442. uint64_t next_service_time = s_compute_next_service_time_by_current_state(client, now);
  443. /*
  444. * This catches both the case when there's an existing service schedule and we either want to not
  445. * perform it (next_service_time == 0) or need to run service at a different time than the current scheduled time.
  446. */
  447. if (next_service_time != client->next_service_task_run_time && client->next_service_task_run_time > 0) {
  448. aws_event_loop_cancel_task(client->loop, &client->service_task);
  449. client->next_service_task_run_time = 0;
  450. AWS_LOGF_TRACE(AWS_LS_MQTT5_CLIENT, "id=%p: cancelling previously scheduled service task", (void *)client);
  451. }
  452. if (next_service_time > 0 &&
  453. (next_service_time < client->next_service_task_run_time || client->next_service_task_run_time == 0)) {
  454. aws_event_loop_schedule_task_future(client->loop, &client->service_task, next_service_time);
  455. AWS_LOGF_TRACE(
  456. AWS_LS_MQTT5_CLIENT, "id=%p: scheduled service task for time %" PRIu64, (void *)client, next_service_time);
  457. }
  458. client->next_service_task_run_time = next_service_time;
  459. }
  460. static void s_enqueue_operation_back(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
  461. AWS_LOGF_DEBUG(
  462. AWS_LS_MQTT5_CLIENT,
  463. "id=%p: enqueuing %s operation to back",
  464. (void *)client,
  465. aws_mqtt5_packet_type_to_c_string(operation->packet_type));
  466. aws_linked_list_push_back(&client->operational_state.queued_operations, &operation->node);
  467. s_reevaluate_service_task(client);
  468. }
  469. static void s_enqueue_operation_front(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
  470. AWS_LOGF_DEBUG(
  471. AWS_LS_MQTT5_CLIENT,
  472. "id=%p: enqueuing %s operation to front",
  473. (void *)client,
  474. aws_mqtt5_packet_type_to_c_string(operation->packet_type));
  475. aws_linked_list_push_front(&client->operational_state.queued_operations, &operation->node);
  476. s_reevaluate_service_task(client);
  477. }
  478. static void s_aws_mqtt5_client_operational_state_reset(
  479. struct aws_mqtt5_client_operational_state *client_operational_state,
  480. int completion_error_code,
  481. bool is_final) {
  482. struct aws_mqtt5_client *client = client_operational_state->client;
  483. s_complete_operation_list(client, &client_operational_state->queued_operations, completion_error_code);
  484. s_complete_operation_list(client, &client_operational_state->write_completion_operations, completion_error_code);
  485. s_complete_operation_list(client, &client_operational_state->unacked_operations, completion_error_code);
  486. if (is_final) {
  487. aws_hash_table_clean_up(&client_operational_state->unacked_operations_table);
  488. } else {
  489. aws_hash_table_clear(&client_operational_state->unacked_operations_table);
  490. }
  491. }
  492. static void s_change_current_state(struct aws_mqtt5_client *client, enum aws_mqtt5_client_state next_state);
  493. static void s_change_current_state_to_stopped(struct aws_mqtt5_client *client) {
  494. client->current_state = AWS_MCS_STOPPED;
  495. s_aws_mqtt5_client_operational_state_reset(&client->operational_state, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, false);
  496. /* Stop works as a complete session wipe, and so the next time we connect, we want it to be clean */
  497. client->has_connected_successfully = false;
  498. s_aws_mqtt5_client_emit_stopped_lifecycle_event(client);
  499. }
  500. static void s_aws_mqtt5_client_shutdown_channel(struct aws_mqtt5_client *client, int error_code) {
  501. if (error_code == AWS_ERROR_SUCCESS) {
  502. error_code = AWS_ERROR_UNKNOWN;
  503. }
  504. s_aws_mqtt5_client_emit_final_lifecycle_event(client, error_code, NULL, NULL);
  505. if (client->current_state != AWS_MCS_MQTT_CONNECT && client->current_state != AWS_MCS_CONNECTED &&
  506. client->current_state != AWS_MCS_CLEAN_DISCONNECT) {
  507. AWS_LOGF_ERROR(
  508. AWS_LS_MQTT5_CLIENT,
  509. "id=%p: client channel shutdown invoked from unexpected state %d(%s)",
  510. (void *)client,
  511. (int)client->current_state,
  512. aws_mqtt5_client_state_to_c_string(client->current_state));
  513. return;
  514. }
  515. if (client->slot == NULL || client->slot->channel == NULL) {
  516. AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: client channel shutdown invoked without a channel", (void *)client);
  517. return;
  518. }
  519. s_change_current_state(client, AWS_MCS_CHANNEL_SHUTDOWN);
  520. (*client->vtable->channel_shutdown_fn)(client->slot->channel, error_code);
  521. }
  522. static void s_aws_mqtt5_client_shutdown_channel_with_disconnect(
  523. struct aws_mqtt5_client *client,
  524. int error_code,
  525. struct aws_mqtt5_operation_disconnect *disconnect_op) {
  526. if (client->current_state != AWS_MCS_CONNECTED && client->current_state != AWS_MCS_MQTT_CONNECT) {
  527. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  528. return;
  529. }
  530. aws_linked_list_push_front(&client->operational_state.queued_operations, &disconnect_op->base.node);
  531. aws_mqtt5_operation_disconnect_acquire(disconnect_op);
  532. client->clean_disconnect_error_code = error_code;
  533. s_change_current_state(client, AWS_MCS_CLEAN_DISCONNECT);
  534. }
  535. static void s_on_disconnect_operation_complete(int error_code, void *user_data) {
  536. struct aws_mqtt5_client *client = user_data;
  537. s_aws_mqtt5_client_shutdown_channel(
  538. client, (error_code != AWS_ERROR_SUCCESS) ? error_code : client->clean_disconnect_error_code);
  539. }
  540. static void s_aws_mqtt5_client_shutdown_channel_clean(
  541. struct aws_mqtt5_client *client,
  542. int error_code,
  543. enum aws_mqtt5_disconnect_reason_code reason_code) {
  544. struct aws_mqtt5_packet_disconnect_view disconnect_options = {
  545. .reason_code = reason_code,
  546. };
  547. struct aws_mqtt5_disconnect_completion_options internal_completion_options = {
  548. .completion_callback = s_on_disconnect_operation_complete,
  549. .completion_user_data = client,
  550. };
  551. struct aws_mqtt5_operation_disconnect *disconnect_op =
  552. aws_mqtt5_operation_disconnect_new(client->allocator, &disconnect_options, NULL, &internal_completion_options);
  553. if (disconnect_op == NULL) {
  554. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  555. return;
  556. }
  557. s_aws_mqtt5_client_shutdown_channel_with_disconnect(client, error_code, disconnect_op);
  558. aws_mqtt5_operation_disconnect_release(disconnect_op);
  559. }
  560. struct aws_mqtt5_shutdown_task {
  561. struct aws_task task;
  562. struct aws_allocator *allocator;
  563. int error_code;
  564. struct aws_mqtt5_client *client;
  565. };
  566. static void s_mqtt5_client_shutdown_final(int error_code, struct aws_mqtt5_client *client);
  567. static void s_shutdown_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
  568. (void)task;
  569. struct aws_mqtt5_shutdown_task *shutdown_task = arg;
  570. if (status != AWS_TASK_STATUS_RUN_READY) {
  571. goto done;
  572. }
  573. s_mqtt5_client_shutdown_final(shutdown_task->error_code, shutdown_task->client);
  574. done:
  575. aws_mem_release(shutdown_task->allocator, shutdown_task);
  576. }
  577. static void s_mqtt5_client_shutdown_final(int error_code, struct aws_mqtt5_client *client) {
  578. AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
  579. s_aws_mqtt5_client_emit_final_lifecycle_event(client, error_code, NULL, NULL);
  580. AWS_LOGF_INFO(
  581. AWS_LS_MQTT5_CLIENT,
  582. "id=%p: channel tore down with error code %d(%s)",
  583. (void *)client,
  584. error_code,
  585. aws_error_debug_str(error_code));
  586. if (client->slot) {
  587. aws_channel_slot_remove(client->slot);
  588. AWS_LOGF_TRACE(AWS_LS_MQTT5_CLIENT, "id=%p: slot removed successfully", (void *)client);
  589. client->slot = NULL;
  590. }
  591. aws_mqtt5_client_on_disconnection_update_operational_state(client);
  592. if (client->desired_state == AWS_MCS_CONNECTED) {
  593. s_change_current_state(client, AWS_MCS_PENDING_RECONNECT);
  594. } else {
  595. s_change_current_state(client, AWS_MCS_STOPPED);
  596. }
  597. }
  598. static void s_mqtt5_client_shutdown(
  599. struct aws_client_bootstrap *bootstrap,
  600. int error_code,
  601. struct aws_channel *channel,
  602. void *user_data) {
  603. (void)bootstrap;
  604. (void)channel;
  605. struct aws_mqtt5_client *client = user_data;
  606. if (error_code == AWS_ERROR_SUCCESS) {
  607. error_code = AWS_ERROR_MQTT_UNEXPECTED_HANGUP;
  608. }
  609. if (aws_event_loop_thread_is_callers_thread(client->loop)) {
  610. s_mqtt5_client_shutdown_final(error_code, client);
  611. return;
  612. }
  613. struct aws_mqtt5_shutdown_task *shutdown_task =
  614. aws_mem_calloc(client->allocator, 1, sizeof(struct aws_mqtt5_shutdown_task));
  615. aws_task_init(&shutdown_task->task, s_shutdown_task_fn, (void *)shutdown_task, "ShutdownTask");
  616. shutdown_task->allocator = client->allocator;
  617. shutdown_task->client = client;
  618. shutdown_task->error_code = error_code;
  619. aws_event_loop_schedule_task_now(client->loop, &shutdown_task->task);
  620. }
  621. static void s_mqtt5_client_setup(
  622. struct aws_client_bootstrap *bootstrap,
  623. int error_code,
  624. struct aws_channel *channel,
  625. void *user_data) {
  626. (void)bootstrap;
  627. /* Setup callback contract is: if error_code is non-zero then channel is NULL. */
  628. AWS_FATAL_ASSERT((error_code != 0) == (channel == NULL));
  629. struct aws_mqtt5_client *client = user_data;
  630. if (error_code != AWS_OP_SUCCESS) {
  631. /* client shutdown already handles this case, so just call that. */
  632. s_mqtt5_client_shutdown(bootstrap, error_code, channel, user_data);
  633. return;
  634. }
  635. AWS_FATAL_ASSERT(client->current_state == AWS_MCS_CONNECTING);
  636. AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
  637. if (client->desired_state != AWS_MCS_CONNECTED) {
  638. aws_raise_error(AWS_ERROR_MQTT5_USER_REQUESTED_STOP);
  639. goto error;
  640. }
  641. client->slot = aws_channel_slot_new(channel); /* allocs or crashes */
  642. if (aws_channel_slot_insert_end(channel, client->slot)) {
  643. AWS_LOGF_ERROR(
  644. AWS_LS_MQTT5_CLIENT,
  645. "id=%p: Failed to insert slot into channel %p, error %d (%s).",
  646. (void *)client,
  647. (void *)channel,
  648. aws_last_error(),
  649. aws_error_name(aws_last_error()));
  650. goto error;
  651. }
  652. if (aws_channel_slot_set_handler(client->slot, &client->handler)) {
  653. AWS_LOGF_ERROR(
  654. AWS_LS_MQTT5_CLIENT,
  655. "id=%p: Failed to set MQTT handler into slot on channel %p, error %d (%s).",
  656. (void *)client,
  657. (void *)channel,
  658. aws_last_error(),
  659. aws_error_name(aws_last_error()));
  660. goto error;
  661. }
  662. s_change_current_state(client, AWS_MCS_MQTT_CONNECT);
  663. return;
  664. error:
  665. s_change_current_state(client, AWS_MCS_CHANNEL_SHUTDOWN);
  666. (*client->vtable->channel_shutdown_fn)(channel, aws_last_error());
  667. }
  668. static void s_on_websocket_shutdown(struct aws_websocket *websocket, int error_code, void *user_data) {
  669. struct aws_mqtt5_client *client = user_data;
  670. struct aws_channel *channel = client->slot ? client->slot->channel : NULL;
  671. s_mqtt5_client_shutdown(client->config->bootstrap, error_code, channel, client);
  672. if (websocket) {
  673. aws_websocket_release(websocket);
  674. }
  675. }
  676. static void s_on_websocket_setup(const struct aws_websocket_on_connection_setup_data *setup, void *user_data) {
  677. struct aws_mqtt5_client *client = user_data;
  678. client->handshake = aws_http_message_release(client->handshake);
  679. /* Setup callback contract is: if error_code is non-zero then websocket is NULL. */
  680. AWS_FATAL_ASSERT((setup->error_code != 0) == (setup->websocket == NULL));
  681. struct aws_channel *channel = NULL;
  682. if (setup->websocket) {
  683. channel = aws_websocket_get_channel(setup->websocket);
  684. AWS_ASSERT(channel);
  685. /* Websocket must be "converted" before the MQTT handler can be installed next to it. */
  686. if (aws_websocket_convert_to_midchannel_handler(setup->websocket)) {
  687. AWS_LOGF_ERROR(
  688. AWS_LS_MQTT5_CLIENT,
  689. "id=%p: Failed converting websocket, error %d (%s)",
  690. (void *)client,
  691. aws_last_error(),
  692. aws_error_name(aws_last_error()));
  693. (*client->vtable->channel_shutdown_fn)(channel, aws_last_error());
  694. return;
  695. }
  696. }
  697. /* Call into the channel-setup callback, the rest of the logic is the same. */
  698. s_mqtt5_client_setup(client->config->bootstrap, setup->error_code, channel, client);
  699. }
  700. struct aws_mqtt5_websocket_transform_complete_task {
  701. struct aws_task task;
  702. struct aws_allocator *allocator;
  703. struct aws_mqtt5_client *client;
  704. int error_code;
  705. struct aws_http_message *handshake;
  706. };
  707. void s_websocket_transform_complete_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
  708. (void)task;
  709. struct aws_mqtt5_websocket_transform_complete_task *websocket_transform_complete_task = arg;
  710. if (status != AWS_TASK_STATUS_RUN_READY) {
  711. goto done;
  712. }
  713. struct aws_mqtt5_client *client = websocket_transform_complete_task->client;
  714. aws_http_message_release(client->handshake);
  715. client->handshake = aws_http_message_acquire(websocket_transform_complete_task->handshake);
  716. int error_code = websocket_transform_complete_task->error_code;
  717. if (error_code == 0 && client->desired_state == AWS_MCS_CONNECTED) {
  718. struct aws_websocket_client_connection_options websocket_options = {
  719. .allocator = client->allocator,
  720. .bootstrap = client->config->bootstrap,
  721. .socket_options = &client->config->socket_options,
  722. .tls_options = client->config->tls_options_ptr,
  723. .host = aws_byte_cursor_from_string(client->config->host_name),
  724. .port = client->config->port,
  725. .handshake_request = websocket_transform_complete_task->handshake,
  726. .initial_window_size = 0, /* Prevent websocket data from arriving before the MQTT handler is installed */
  727. .user_data = client,
  728. .on_connection_setup = s_on_websocket_setup,
  729. .on_connection_shutdown = s_on_websocket_shutdown,
  730. .requested_event_loop = client->loop,
  731. };
  732. if (client->config->http_proxy_config != NULL) {
  733. websocket_options.proxy_options = &client->config->http_proxy_options;
  734. }
  735. if (client->vtable->websocket_connect_fn(&websocket_options)) {
  736. AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: Failed to initiate websocket connection.", (void *)client);
  737. error_code = aws_last_error();
  738. goto error;
  739. }
  740. goto done;
  741. } else {
  742. if (error_code == AWS_ERROR_SUCCESS) {
  743. AWS_ASSERT(client->desired_state != AWS_MCS_CONNECTED);
  744. error_code = AWS_ERROR_MQTT5_USER_REQUESTED_STOP;
  745. }
  746. }
  747. error:;
  748. struct aws_websocket_on_connection_setup_data websocket_setup = {.error_code = error_code};
  749. s_on_websocket_setup(&websocket_setup, client);
  750. done:
  751. aws_http_message_release(websocket_transform_complete_task->handshake);
  752. aws_mqtt5_client_release(websocket_transform_complete_task->client);
  753. aws_mem_release(websocket_transform_complete_task->allocator, websocket_transform_complete_task);
  754. }
  755. static void s_websocket_handshake_transform_complete(
  756. struct aws_http_message *handshake_request,
  757. int error_code,
  758. void *complete_ctx) {
  759. struct aws_mqtt5_client *client = complete_ctx;
  760. struct aws_mqtt5_websocket_transform_complete_task *task =
  761. aws_mem_calloc(client->allocator, 1, sizeof(struct aws_mqtt5_websocket_transform_complete_task));
  762. aws_task_init(
  763. &task->task, s_websocket_transform_complete_task_fn, (void *)task, "WebsocketHandshakeTransformComplete");
  764. task->allocator = client->allocator;
  765. task->client = aws_mqtt5_client_acquire(client);
  766. task->error_code = error_code;
  767. task->handshake = handshake_request;
  768. aws_event_loop_schedule_task_now(client->loop, &task->task);
  769. aws_mqtt5_client_release(client);
  770. }
  771. static int s_websocket_connect(struct aws_mqtt5_client *client) {
  772. AWS_ASSERT(client);
  773. AWS_ASSERT(client->config->websocket_handshake_transform);
  774. /* Build websocket handshake request */
  775. struct aws_http_message *handshake = aws_http_message_new_websocket_handshake_request(
  776. client->allocator, *g_websocket_handshake_default_path, aws_byte_cursor_from_string(client->config->host_name));
  777. if (handshake == NULL) {
  778. AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: Failed to generate websocket handshake request", (void *)client);
  779. return AWS_OP_ERR;
  780. }
  781. if (aws_http_message_add_header(handshake, *g_websocket_handshake_default_protocol_header)) {
  782. AWS_LOGF_ERROR(
  783. AWS_LS_MQTT5_CLIENT, "id=%p: Failed to add default header to websocket handshake request", (void *)client);
  784. goto on_error;
  785. }
  786. AWS_LOGF_TRACE(AWS_LS_MQTT5_CLIENT, "id=%p: Transforming websocket handshake request.", (void *)client);
  787. aws_mqtt5_client_acquire(client);
  788. client->config->websocket_handshake_transform(
  789. handshake,
  790. client->config->websocket_handshake_transform_user_data,
  791. s_websocket_handshake_transform_complete,
  792. client);
  793. return AWS_OP_SUCCESS;
  794. on_error:
  795. aws_http_message_release(handshake);
  796. return AWS_OP_ERR;
  797. }
  798. static void s_change_current_state_to_connecting(struct aws_mqtt5_client *client) {
  799. AWS_ASSERT(client->current_state == AWS_MCS_STOPPED || client->current_state == AWS_MCS_PENDING_RECONNECT);
  800. client->current_state = AWS_MCS_CONNECTING;
  801. client->clean_disconnect_error_code = AWS_ERROR_SUCCESS;
  802. s_aws_mqtt5_client_emit_connecting_lifecycle_event(client);
  803. int result = 0;
  804. if (client->config->websocket_handshake_transform != NULL) {
  805. result = s_websocket_connect(client);
  806. } else {
  807. struct aws_socket_channel_bootstrap_options channel_options;
  808. AWS_ZERO_STRUCT(channel_options);
  809. channel_options.bootstrap = client->config->bootstrap;
  810. channel_options.host_name = aws_string_c_str(client->config->host_name);
  811. channel_options.port = client->config->port;
  812. channel_options.socket_options = &client->config->socket_options;
  813. channel_options.tls_options = client->config->tls_options_ptr;
  814. channel_options.setup_callback = &s_mqtt5_client_setup;
  815. channel_options.shutdown_callback = &s_mqtt5_client_shutdown;
  816. channel_options.user_data = client;
  817. channel_options.requested_event_loop = client->loop;
  818. if (client->config->http_proxy_config == NULL) {
  819. result = (*client->vtable->client_bootstrap_new_socket_channel_fn)(&channel_options);
  820. } else {
  821. result = (*client->vtable->http_proxy_new_socket_channel_fn)(
  822. &channel_options, &client->config->http_proxy_options);
  823. }
  824. }
  825. if (result) {
  826. int error_code = aws_last_error();
  827. AWS_LOGF_INFO(
  828. AWS_LS_MQTT5_CLIENT,
  829. "id=%p: failed to kick off connection with error %d(%s)",
  830. (void *)client,
  831. error_code,
  832. aws_error_debug_str(error_code));
  833. s_aws_mqtt5_client_emit_final_lifecycle_event(client, aws_last_error(), NULL, NULL);
  834. s_change_current_state(client, AWS_MCS_PENDING_RECONNECT);
  835. }
  836. }
  837. static int s_aws_mqtt5_client_set_current_operation(
  838. struct aws_mqtt5_client *client,
  839. struct aws_mqtt5_operation *operation) {
  840. if (aws_mqtt5_operation_bind_packet_id(operation, &client->operational_state)) {
  841. int error_code = aws_last_error();
  842. AWS_LOGF_ERROR(
  843. AWS_LS_MQTT5_CLIENT,
  844. "id=%p: failed to bind mqtt packet id for current operation, with error %d(%s)",
  845. (void *)client,
  846. error_code,
  847. aws_error_debug_str(error_code));
  848. return AWS_OP_ERR;
  849. }
  850. if (aws_mqtt5_encoder_append_packet_encoding(&client->encoder, operation->packet_type, operation->packet_view)) {
  851. int error_code = aws_last_error();
  852. AWS_LOGF_ERROR(
  853. AWS_LS_MQTT5_CLIENT,
  854. "id=%p: failed to append packet encoding sequence for current operation with error %d(%s)",
  855. (void *)client,
  856. error_code,
  857. aws_error_debug_str(error_code));
  858. return AWS_OP_ERR;
  859. }
  860. client->operational_state.current_operation = operation;
  861. return AWS_OP_SUCCESS;
  862. }
  863. static void s_reset_ping(struct aws_mqtt5_client *client) {
  864. uint64_t now = (*client->vtable->get_current_time_fn)();
  865. uint16_t keep_alive_seconds = client->negotiated_settings.server_keep_alive;
  866. uint64_t keep_alive_interval_nanos =
  867. aws_timestamp_convert(keep_alive_seconds, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
  868. client->next_ping_time = aws_add_u64_saturating(now, keep_alive_interval_nanos);
  869. AWS_LOGF_DEBUG(
  870. AWS_LS_MQTT5_CLIENT, "id=%p: next PINGREQ scheduled for time %" PRIu64, (void *)client, client->next_ping_time);
  871. }
  872. static void s_aws_mqtt5_on_socket_write_completion_mqtt_connect(struct aws_mqtt5_client *client, int error_code) {
  873. if (error_code != AWS_ERROR_SUCCESS) {
  874. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  875. return;
  876. }
  877. s_reevaluate_service_task(client);
  878. }
  879. static void s_aws_mqtt5_on_socket_write_completion_connected(struct aws_mqtt5_client *client, int error_code) {
  880. if (error_code != AWS_ERROR_SUCCESS) {
  881. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  882. return;
  883. }
  884. s_reevaluate_service_task(client);
  885. }
  886. static void s_aws_mqtt5_on_socket_write_completion(
  887. struct aws_channel *channel,
  888. struct aws_io_message *message,
  889. int error_code,
  890. void *user_data) {
  891. (void)channel;
  892. (void)message;
  893. struct aws_mqtt5_client *client = user_data;
  894. client->operational_state.pending_write_completion = false;
  895. if (error_code != AWS_ERROR_SUCCESS) {
  896. AWS_LOGF_INFO(
  897. AWS_LS_MQTT5_CLIENT,
  898. "id=%p: socket write completion invoked with error %d(%s)",
  899. (void *)client,
  900. error_code,
  901. aws_error_debug_str(error_code));
  902. }
  903. switch (client->current_state) {
  904. case AWS_MCS_MQTT_CONNECT:
  905. s_aws_mqtt5_on_socket_write_completion_mqtt_connect(client, error_code);
  906. break;
  907. case AWS_MCS_CONNECTED:
  908. s_aws_mqtt5_on_socket_write_completion_connected(client, error_code);
  909. break;
  910. case AWS_MCS_CLEAN_DISCONNECT:
  911. /* the CONNECTED callback works just fine for CLEAN_DISCONNECT */
  912. s_aws_mqtt5_on_socket_write_completion_connected(client, error_code);
  913. break;
  914. default:
  915. break;
  916. }
  917. s_complete_operation_list(client, &client->operational_state.write_completion_operations, error_code);
  918. }
  919. static bool s_should_resume_session(const struct aws_mqtt5_client *client) {
  920. enum aws_mqtt5_client_session_behavior_type session_behavior =
  921. aws_mqtt5_client_session_behavior_type_to_non_default(client->config->session_behavior);
  922. return (session_behavior == AWS_MQTT5_CSBT_REJOIN_POST_SUCCESS && client->has_connected_successfully) ||
  923. (session_behavior == AWS_MQTT5_CSBT_REJOIN_ALWAYS);
  924. }
  925. static void s_change_current_state_to_mqtt_connect(struct aws_mqtt5_client *client) {
  926. AWS_FATAL_ASSERT(client->current_state == AWS_MCS_CONNECTING);
  927. AWS_FATAL_ASSERT(client->operational_state.current_operation == NULL);
  928. client->current_state = AWS_MCS_MQTT_CONNECT;
  929. client->operational_state.pending_write_completion = false;
  930. aws_mqtt5_encoder_reset(&client->encoder);
  931. aws_mqtt5_decoder_reset(&client->decoder);
  932. bool resume_session = s_should_resume_session(client);
  933. struct aws_mqtt5_packet_connect_view connect_view = client->config->connect.storage_view;
  934. connect_view.clean_start = !resume_session;
  935. if (aws_mqtt5_inbound_topic_alias_behavior_type_to_non_default(
  936. client->config->topic_aliasing_options.inbound_topic_alias_behavior) == AWS_MQTT5_CITABT_ENABLED) {
  937. connect_view.topic_alias_maximum = &client->config->topic_aliasing_options.inbound_alias_cache_size;
  938. }
  939. aws_mqtt5_negotiated_settings_reset(&client->negotiated_settings, &connect_view);
  940. connect_view.client_id = aws_byte_cursor_from_buf(&client->negotiated_settings.client_id_storage);
  941. struct aws_mqtt5_operation_connect *connect_op = aws_mqtt5_operation_connect_new(client->allocator, &connect_view);
  942. if (connect_op == NULL) {
  943. int error_code = aws_last_error();
  944. AWS_LOGF_ERROR(
  945. AWS_LS_MQTT5_CLIENT,
  946. "id=%p: failed to create CONNECT operation with error %d(%s)",
  947. (void *)client,
  948. error_code,
  949. aws_error_debug_str(error_code));
  950. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  951. return;
  952. }
  953. s_enqueue_operation_front(client, &connect_op->base);
  954. uint32_t timeout_ms = client->config->connack_timeout_ms;
  955. if (timeout_ms == 0) {
  956. timeout_ms = AWS_MQTT5_DEFAULT_CONNACK_PACKET_TIMEOUT_MS;
  957. }
  958. uint64_t now = (*client->vtable->get_current_time_fn)();
  959. client->next_mqtt_connect_packet_timeout_time =
  960. now + aws_timestamp_convert(timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
  961. AWS_LOGF_DEBUG(
  962. AWS_LS_MQTT5_CLIENT,
  963. "id=%p: setting CONNECT timeout to %" PRIu64,
  964. (void *)client,
  965. client->next_mqtt_connect_packet_timeout_time);
  966. }
  967. static void s_reset_reconnection_delay_time(struct aws_mqtt5_client *client) {
  968. uint64_t now = (*client->vtable->get_current_time_fn)();
  969. uint64_t reset_reconnection_delay_time_nanos = aws_timestamp_convert(
  970. client->config->min_connected_time_to_reset_reconnect_delay_ms,
  971. AWS_TIMESTAMP_MILLIS,
  972. AWS_TIMESTAMP_NANOS,
  973. NULL);
  974. client->next_reconnect_delay_reset_time_ns = aws_add_u64_saturating(now, reset_reconnection_delay_time_nanos);
  975. AWS_LOGF_DEBUG(
  976. AWS_LS_MQTT5_CLIENT,
  977. "id=%p: reconnection delay reset time set to %" PRIu64,
  978. (void *)client,
  979. client->next_reconnect_delay_reset_time_ns);
  980. }
  981. static void s_change_current_state_to_connected(struct aws_mqtt5_client *client) {
  982. AWS_FATAL_ASSERT(client->current_state == AWS_MCS_MQTT_CONNECT);
  983. client->current_state = AWS_MCS_CONNECTED;
  984. aws_mqtt5_client_on_connection_update_operational_state(client);
  985. client->has_connected_successfully = true;
  986. client->next_ping_timeout_time = 0;
  987. s_reset_ping(client);
  988. s_reset_reconnection_delay_time(client);
  989. }
  990. static void s_change_current_state_to_clean_disconnect(struct aws_mqtt5_client *client) {
  991. (void)client;
  992. AWS_FATAL_ASSERT(client->current_state == AWS_MCS_MQTT_CONNECT || client->current_state == AWS_MCS_CONNECTED);
  993. client->current_state = AWS_MCS_CLEAN_DISCONNECT;
  994. }
  995. static void s_change_current_state_to_channel_shutdown(struct aws_mqtt5_client *client) {
  996. enum aws_mqtt5_client_state current_state = client->current_state;
  997. AWS_FATAL_ASSERT(
  998. current_state == AWS_MCS_MQTT_CONNECT || current_state == AWS_MCS_CONNECTING ||
  999. current_state == AWS_MCS_CONNECTED || current_state == AWS_MCS_CLEAN_DISCONNECT);
  1000. client->current_state = AWS_MCS_CHANNEL_SHUTDOWN;
  1001. /*
  1002. * Critical requirement: The caller must invoke the channel shutdown function themselves (with the desired error
  1003. * code) *after* changing state.
  1004. *
  1005. * The caller is the only one with the error context and we want to be safe and avoid the possibility of a
  1006. * synchronous channel shutdown (mocks) leading to a situation where we get the shutdown callback before we've
  1007. * transitioned into the CHANNEL_SHUTDOWN state.
  1008. *
  1009. * We could relax this if a synchronous channel shutdown is literally impossible even with mocked channels.
  1010. */
  1011. }
  1012. /* TODO: refactor and reunify with internals of retry strategy to expose these as usable functions in aws-c-io */
  1013. static uint64_t s_aws_mqtt5_compute_reconnect_backoff_no_jitter(struct aws_mqtt5_client *client) {
  1014. uint64_t retry_count = aws_min_u64(client->reconnect_count, 63);
  1015. return aws_mul_u64_saturating((uint64_t)1 << retry_count, client->config->min_reconnect_delay_ms);
  1016. }
  1017. static uint64_t s_aws_mqtt5_compute_reconnect_backoff_full_jitter(struct aws_mqtt5_client *client) {
  1018. uint64_t non_jittered = s_aws_mqtt5_compute_reconnect_backoff_no_jitter(client);
  1019. return aws_mqtt5_client_random_in_range(0, non_jittered);
  1020. }
  1021. static uint64_t s_compute_deccorelated_jitter(struct aws_mqtt5_client *client) {
  1022. uint64_t last_backoff_val = client->current_reconnect_delay_ms;
  1023. if (!last_backoff_val) {
  1024. return s_aws_mqtt5_compute_reconnect_backoff_full_jitter(client);
  1025. }
  1026. return aws_mqtt5_client_random_in_range(
  1027. client->config->min_reconnect_delay_ms, aws_mul_u64_saturating(last_backoff_val, 3));
  1028. }
  1029. static void s_update_reconnect_delay_for_pending_reconnect(struct aws_mqtt5_client *client) {
  1030. uint64_t delay_ms = 0;
  1031. switch (client->config->retry_jitter_mode) {
  1032. case AWS_EXPONENTIAL_BACKOFF_JITTER_DECORRELATED:
  1033. delay_ms = s_compute_deccorelated_jitter(client);
  1034. break;
  1035. case AWS_EXPONENTIAL_BACKOFF_JITTER_NONE:
  1036. delay_ms = s_aws_mqtt5_compute_reconnect_backoff_no_jitter(client);
  1037. break;
  1038. case AWS_EXPONENTIAL_BACKOFF_JITTER_FULL:
  1039. case AWS_EXPONENTIAL_BACKOFF_JITTER_DEFAULT:
  1040. default:
  1041. delay_ms = s_aws_mqtt5_compute_reconnect_backoff_full_jitter(client);
  1042. break;
  1043. }
  1044. delay_ms = aws_min_u64(delay_ms, client->config->max_reconnect_delay_ms);
  1045. uint64_t now = (*client->vtable->get_current_time_fn)();
  1046. client->next_reconnect_time_ns =
  1047. aws_add_u64_saturating(now, aws_timestamp_convert(delay_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL));
  1048. AWS_LOGF_DEBUG(
  1049. AWS_LS_MQTT5_CLIENT, "id=%p: next connection attempt in %" PRIu64 " milliseconds", (void *)client, delay_ms);
  1050. client->reconnect_count++;
  1051. }
  1052. static void s_change_current_state_to_pending_reconnect(struct aws_mqtt5_client *client) {
  1053. client->current_state = AWS_MCS_PENDING_RECONNECT;
  1054. s_update_reconnect_delay_for_pending_reconnect(client);
  1055. }
  1056. static void s_change_current_state_to_terminated(struct aws_mqtt5_client *client) {
  1057. client->current_state = AWS_MCS_TERMINATED;
  1058. s_mqtt5_client_final_destroy(client);
  1059. }
  1060. static void s_change_current_state(struct aws_mqtt5_client *client, enum aws_mqtt5_client_state next_state) {
  1061. AWS_ASSERT(next_state != client->current_state);
  1062. if (next_state == client->current_state) {
  1063. return;
  1064. }
  1065. AWS_LOGF_DEBUG(
  1066. AWS_LS_MQTT5_CLIENT,
  1067. "id=%p: switching current state from %s to %s",
  1068. (void *)client,
  1069. aws_mqtt5_client_state_to_c_string(client->current_state),
  1070. aws_mqtt5_client_state_to_c_string(next_state));
  1071. if (client->vtable->on_client_state_change_callback_fn != NULL) {
  1072. (*client->vtable->on_client_state_change_callback_fn)(
  1073. client, client->current_state, next_state, client->vtable->vtable_user_data);
  1074. }
  1075. switch (next_state) {
  1076. case AWS_MCS_STOPPED:
  1077. s_change_current_state_to_stopped(client);
  1078. break;
  1079. case AWS_MCS_CONNECTING:
  1080. s_change_current_state_to_connecting(client);
  1081. break;
  1082. case AWS_MCS_MQTT_CONNECT:
  1083. s_change_current_state_to_mqtt_connect(client);
  1084. break;
  1085. case AWS_MCS_CONNECTED:
  1086. s_change_current_state_to_connected(client);
  1087. break;
  1088. case AWS_MCS_CLEAN_DISCONNECT:
  1089. s_change_current_state_to_clean_disconnect(client);
  1090. break;
  1091. case AWS_MCS_CHANNEL_SHUTDOWN:
  1092. s_change_current_state_to_channel_shutdown(client);
  1093. break;
  1094. case AWS_MCS_PENDING_RECONNECT:
  1095. s_change_current_state_to_pending_reconnect(client);
  1096. break;
  1097. case AWS_MCS_TERMINATED:
  1098. s_change_current_state_to_terminated(client);
  1099. return;
  1100. }
  1101. s_reevaluate_service_task(client);
  1102. }
  1103. static bool s_service_state_stopped(struct aws_mqtt5_client *client) {
  1104. enum aws_mqtt5_client_state desired_state = client->desired_state;
  1105. if (desired_state == AWS_MCS_CONNECTED) {
  1106. s_change_current_state(client, AWS_MCS_CONNECTING);
  1107. } else if (desired_state == AWS_MCS_TERMINATED) {
  1108. s_change_current_state(client, AWS_MCS_TERMINATED);
  1109. return true;
  1110. }
  1111. return false;
  1112. }
  1113. static void s_service_state_connecting(struct aws_mqtt5_client *client) {
  1114. (void)client;
  1115. }
  1116. static void s_service_state_mqtt_connect(struct aws_mqtt5_client *client, uint64_t now) {
  1117. enum aws_mqtt5_client_state desired_state = client->desired_state;
  1118. if (desired_state != AWS_MCS_CONNECTED) {
  1119. s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, NULL, NULL);
  1120. s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP);
  1121. return;
  1122. }
  1123. if (now >= client->next_mqtt_connect_packet_timeout_time) {
  1124. s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_CONNACK_TIMEOUT, NULL, NULL);
  1125. AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: shutting down channel due to CONNACK timeout", (void *)client);
  1126. s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_CONNACK_TIMEOUT);
  1127. return;
  1128. }
  1129. if (aws_mqtt5_client_service_operational_state(&client->operational_state)) {
  1130. int error_code = aws_last_error();
  1131. AWS_LOGF_ERROR(
  1132. AWS_LS_MQTT5_CLIENT,
  1133. "id=%p: failed to service outgoing CONNECT packet to channel with error %d(%s)",
  1134. (void *)client,
  1135. error_code,
  1136. aws_error_debug_str(error_code));
  1137. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  1138. return;
  1139. }
  1140. }
  1141. static int s_aws_mqtt5_client_queue_ping(struct aws_mqtt5_client *client) {
  1142. s_reset_ping(client);
  1143. AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: queuing PINGREQ", (void *)client);
  1144. struct aws_mqtt5_operation_pingreq *pingreq_op = aws_mqtt5_operation_pingreq_new(client->allocator);
  1145. s_enqueue_operation_front(client, &pingreq_op->base);
  1146. return AWS_OP_SUCCESS;
  1147. }
  1148. static void s_service_state_connected(struct aws_mqtt5_client *client, uint64_t now) {
  1149. enum aws_mqtt5_client_state desired_state = client->desired_state;
  1150. if (desired_state != AWS_MCS_CONNECTED) {
  1151. s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, NULL, NULL);
  1152. AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: channel shutdown due to user Stop request", (void *)client);
  1153. s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP);
  1154. return;
  1155. }
  1156. if (now >= client->next_ping_timeout_time && client->next_ping_timeout_time != 0) {
  1157. s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_PING_RESPONSE_TIMEOUT, NULL, NULL);
  1158. AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: channel shutdown due to PINGRESP timeout", (void *)client);
  1159. s_aws_mqtt5_client_shutdown_channel_clean(
  1160. client, AWS_ERROR_MQTT5_PING_RESPONSE_TIMEOUT, AWS_MQTT5_DRC_KEEP_ALIVE_TIMEOUT);
  1161. return;
  1162. }
  1163. if (now >= client->next_ping_time) {
  1164. if (s_aws_mqtt5_client_queue_ping(client)) {
  1165. int error_code = aws_last_error();
  1166. AWS_LOGF_ERROR(
  1167. AWS_LS_MQTT5_CLIENT,
  1168. "id=%p: failed to queue PINGREQ with error %d(%s)",
  1169. (void *)client,
  1170. error_code,
  1171. aws_error_debug_str(error_code));
  1172. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  1173. return;
  1174. }
  1175. }
  1176. if (now >= client->next_reconnect_delay_reset_time_ns && client->next_reconnect_delay_reset_time_ns != 0) {
  1177. AWS_LOGF_DEBUG(
  1178. AWS_LS_MQTT5_CLIENT,
  1179. "id=%p: connected sufficiently long that reconnect backoff delay has been reset back to "
  1180. "minimum value",
  1181. (void *)client);
  1182. client->reconnect_count = 0;
  1183. client->current_reconnect_delay_ms = 0;
  1184. client->next_reconnect_delay_reset_time_ns = 0;
  1185. }
  1186. s_check_timeouts(client, now);
  1187. if (aws_mqtt5_client_service_operational_state(&client->operational_state)) {
  1188. int error_code = aws_last_error();
  1189. AWS_LOGF_ERROR(
  1190. AWS_LS_MQTT5_CLIENT,
  1191. "id=%p: failed to service CONNECTED operation queue with error %d(%s)",
  1192. (void *)client,
  1193. error_code,
  1194. aws_error_debug_str(error_code));
  1195. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  1196. return;
  1197. }
  1198. }
  1199. static void s_service_state_clean_disconnect(struct aws_mqtt5_client *client, uint64_t now) {
  1200. if (aws_mqtt5_client_service_operational_state(&client->operational_state)) {
  1201. int error_code = aws_last_error();
  1202. AWS_LOGF_ERROR(
  1203. AWS_LS_MQTT5_CLIENT,
  1204. "id=%p: failed to service CLEAN_DISCONNECT operation queue with error %d(%s)",
  1205. (void *)client,
  1206. error_code,
  1207. aws_error_debug_str(error_code));
  1208. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  1209. return;
  1210. }
  1211. s_check_timeouts(client, now);
  1212. }
  1213. static void s_service_state_channel_shutdown(struct aws_mqtt5_client *client) {
  1214. (void)client;
  1215. }
  1216. static void s_service_state_pending_reconnect(struct aws_mqtt5_client *client, uint64_t now) {
  1217. if (client->desired_state != AWS_MCS_CONNECTED) {
  1218. s_change_current_state(client, AWS_MCS_STOPPED);
  1219. return;
  1220. }
  1221. if (now >= client->next_reconnect_time_ns) {
  1222. s_change_current_state(client, AWS_MCS_CONNECTING);
  1223. return;
  1224. }
  1225. }
  1226. static void s_mqtt5_service_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
  1227. (void)task;
  1228. if (status != AWS_TASK_STATUS_RUN_READY) {
  1229. return;
  1230. }
  1231. struct aws_mqtt5_client *client = arg;
  1232. client->next_service_task_run_time = 0;
  1233. client->in_service = true;
  1234. uint64_t now = (*client->vtable->get_current_time_fn)();
  1235. bool terminated = false;
  1236. switch (client->current_state) {
  1237. case AWS_MCS_STOPPED:
  1238. terminated = s_service_state_stopped(client);
  1239. break;
  1240. case AWS_MCS_CONNECTING:
  1241. s_service_state_connecting(client);
  1242. break;
  1243. case AWS_MCS_MQTT_CONNECT:
  1244. s_service_state_mqtt_connect(client, now);
  1245. break;
  1246. case AWS_MCS_CONNECTED:
  1247. s_service_state_connected(client, now);
  1248. break;
  1249. case AWS_MCS_CLEAN_DISCONNECT:
  1250. s_service_state_clean_disconnect(client, now);
  1251. break;
  1252. case AWS_MCS_CHANNEL_SHUTDOWN:
  1253. s_service_state_channel_shutdown(client);
  1254. break;
  1255. case AWS_MCS_PENDING_RECONNECT:
  1256. s_service_state_pending_reconnect(client, now);
  1257. break;
  1258. default:
  1259. break;
  1260. }
  1261. /*
  1262. * We can only enter the terminated state from stopped. If we do so, the client memory is now freed and we
  1263. * will crash if we access anything anymore.
  1264. */
  1265. if (terminated) {
  1266. return;
  1267. }
  1268. /* we're not scheduled anymore, reschedule as needed */
  1269. client->in_service = false;
  1270. s_reevaluate_service_task(client);
  1271. }
  1272. static bool s_should_client_disconnect_cleanly(struct aws_mqtt5_client *client) {
  1273. enum aws_mqtt5_client_state current_state = client->current_state;
  1274. return current_state == AWS_MCS_CONNECTED;
  1275. }
  1276. static int s_process_read_message(
  1277. struct aws_channel_handler *handler,
  1278. struct aws_channel_slot *slot,
  1279. struct aws_io_message *message) {
  1280. struct aws_mqtt5_client *client = handler->impl;
  1281. if (message->message_type != AWS_IO_MESSAGE_APPLICATION_DATA) {
  1282. AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: unexpected io message data", (void *)client);
  1283. return AWS_OP_ERR;
  1284. }
  1285. AWS_LOGF_TRACE(
  1286. AWS_LS_MQTT5_CLIENT, "id=%p: processing read message of size %zu", (void *)client, message->message_data.len);
  1287. struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&message->message_data);
  1288. int result = aws_mqtt5_decoder_on_data_received(&client->decoder, message_cursor);
  1289. if (result != AWS_OP_SUCCESS) {
  1290. int error_code = aws_last_error();
  1291. AWS_LOGF_ERROR(
  1292. AWS_LS_MQTT5_CLIENT,
  1293. "id=%p: decode failure with error %d(%s)",
  1294. (void *)client,
  1295. error_code,
  1296. aws_error_debug_str(error_code));
  1297. if (error_code == AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR && s_should_client_disconnect_cleanly(client)) {
  1298. s_aws_mqtt5_client_shutdown_channel_clean(client, error_code, AWS_MQTT5_DRC_PROTOCOL_ERROR);
  1299. } else {
  1300. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  1301. }
  1302. goto done;
  1303. }
  1304. aws_channel_slot_increment_read_window(slot, message->message_data.len);
  1305. done:
  1306. aws_mem_release(message->allocator, message);
  1307. return AWS_OP_SUCCESS;
  1308. }
  1309. static int s_shutdown(
  1310. struct aws_channel_handler *handler,
  1311. struct aws_channel_slot *slot,
  1312. enum aws_channel_direction dir,
  1313. int error_code,
  1314. bool free_scarce_resources_immediately) {
  1315. (void)handler;
  1316. return aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, free_scarce_resources_immediately);
  1317. }
  1318. static size_t s_initial_window_size(struct aws_channel_handler *handler) {
  1319. (void)handler;
  1320. return SIZE_MAX;
  1321. }
  1322. static void s_destroy(struct aws_channel_handler *handler) {
  1323. (void)handler;
  1324. }
  1325. static size_t s_message_overhead(struct aws_channel_handler *handler) {
  1326. (void)handler;
  1327. return 0;
  1328. }
  1329. static struct aws_channel_handler_vtable s_mqtt5_channel_handler_vtable = {
  1330. .process_read_message = &s_process_read_message,
  1331. .process_write_message = NULL,
  1332. .increment_read_window = NULL,
  1333. .shutdown = &s_shutdown,
  1334. .initial_window_size = &s_initial_window_size,
  1335. .message_overhead = &s_message_overhead,
  1336. .destroy = &s_destroy,
  1337. };
  1338. static bool s_aws_is_successful_reason_code(int value) {
  1339. return value < 128;
  1340. }
  1341. static void s_aws_mqtt5_client_on_connack(
  1342. struct aws_mqtt5_client *client,
  1343. struct aws_mqtt5_packet_connack_view *connack_view) {
  1344. AWS_FATAL_ASSERT(client->current_state == AWS_MCS_MQTT_CONNECT);
  1345. bool is_successful = s_aws_is_successful_reason_code((int)connack_view->reason_code);
  1346. if (!is_successful) {
  1347. s_aws_mqtt5_client_emit_final_lifecycle_event(
  1348. client, AWS_ERROR_MQTT5_CONNACK_CONNECTION_REFUSED, connack_view, NULL);
  1349. enum aws_mqtt5_connect_reason_code reason_code = connack_view->reason_code;
  1350. AWS_LOGF_INFO(
  1351. AWS_LS_MQTT5_CLIENT,
  1352. "id=%p: connection refused (via failed CONNACK) by remote host with reason code %d(%s)",
  1353. (void *)client,
  1354. (int)reason_code,
  1355. aws_mqtt5_connect_reason_code_to_c_string(reason_code));
  1356. s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_CONNACK_CONNECTION_REFUSED);
  1357. return;
  1358. }
  1359. aws_mqtt5_negotiated_settings_apply_connack(&client->negotiated_settings, connack_view);
  1360. /* Check if a session is being rejoined and perform associated rejoin connect logic here */
  1361. if (client->negotiated_settings.rejoined_session) {
  1362. /* Disconnect if the server is attempting to connect the client to an unexpected session */
  1363. if (!s_should_resume_session(client)) {
  1364. s_aws_mqtt5_client_emit_final_lifecycle_event(
  1365. client, AWS_ERROR_MQTT_CANCELLED_FOR_CLEAN_SESSION, connack_view, NULL);
  1366. s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT_CANCELLED_FOR_CLEAN_SESSION);
  1367. return;
  1368. } else if (!client->has_connected_successfully) {
  1369. /*
  1370. * We were configured with REJOIN_ALWAYS and this is the first connection. This is technically not safe
  1371. * and so let's log a warning for future diagnostics should it cause the user problems.
  1372. */
  1373. AWS_LOGF_WARN(
  1374. AWS_LS_MQTT5_CLIENT,
  1375. "id=%p: initial connection rejoined existing session. This may cause packet id collisions.",
  1376. (void *)client);
  1377. }
  1378. }
  1379. s_change_current_state(client, AWS_MCS_CONNECTED);
  1380. s_aws_mqtt5_client_emit_connection_success_lifecycle_event(client, connack_view);
  1381. }
  1382. static void s_aws_mqtt5_client_log_received_packet(
  1383. struct aws_mqtt5_client *client,
  1384. enum aws_mqtt5_packet_type type,
  1385. void *packet_view) {
  1386. AWS_LOGF_DEBUG(
  1387. AWS_LS_MQTT5_CLIENT, "id=%p: Received %s packet", (void *)client, aws_mqtt5_packet_type_to_c_string(type));
  1388. switch (type) {
  1389. case AWS_MQTT5_PT_CONNACK:
  1390. aws_mqtt5_packet_connack_view_log(packet_view, AWS_LL_DEBUG);
  1391. break;
  1392. case AWS_MQTT5_PT_PUBLISH:
  1393. aws_mqtt5_packet_publish_view_log(packet_view, AWS_LL_DEBUG);
  1394. break;
  1395. case AWS_MQTT5_PT_PUBACK:
  1396. aws_mqtt5_packet_puback_view_log(packet_view, AWS_LL_DEBUG);
  1397. break;
  1398. case AWS_MQTT5_PT_SUBACK:
  1399. aws_mqtt5_packet_suback_view_log(packet_view, AWS_LL_DEBUG);
  1400. break;
  1401. case AWS_MQTT5_PT_UNSUBACK:
  1402. aws_mqtt5_packet_unsuback_view_log(packet_view, AWS_LL_DEBUG);
  1403. break;
  1404. case AWS_MQTT5_PT_PINGRESP:
  1405. break; /* nothing to log */
  1406. case AWS_MQTT5_PT_DISCONNECT:
  1407. aws_mqtt5_packet_disconnect_view_log(packet_view, AWS_LL_DEBUG);
  1408. break;
  1409. default:
  1410. break;
  1411. }
  1412. }
  1413. static void s_aws_mqtt5_client_mqtt_connect_on_packet_received(
  1414. struct aws_mqtt5_client *client,
  1415. enum aws_mqtt5_packet_type type,
  1416. void *packet_view) {
  1417. if (type == AWS_MQTT5_PT_CONNACK) {
  1418. s_aws_mqtt5_client_on_connack(client, (struct aws_mqtt5_packet_connack_view *)packet_view);
  1419. } else {
  1420. AWS_LOGF_ERROR(
  1421. AWS_LS_MQTT5_CLIENT, "id=%p: Invalid packet type received while in MQTT_CONNECT state", (void *)client);
  1422. s_aws_mqtt5_client_shutdown_channel_clean(
  1423. client, AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR, AWS_MQTT5_DRC_PROTOCOL_ERROR);
  1424. }
  1425. }
  1426. typedef bool(aws_linked_list_node_predicate_fn)(struct aws_linked_list_node *);
  1427. /*
  1428. * This predicate finds the first (if any) operation in the queue that is not a PUBACK or a PINGREQ.
  1429. */
  1430. static bool s_is_ping_or_puback(struct aws_linked_list_node *operation_node) {
  1431. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(operation_node, struct aws_mqtt5_operation, node);
  1432. return operation->packet_type == AWS_MQTT5_PT_PUBACK || operation->packet_type == AWS_MQTT5_PT_PINGREQ;
  1433. }
  1434. /*
  1435. * Helper function to insert a node (operation) into a list (operation queue) in the correct spot. Currently, this
  1436. * is only used to enqueue PUBACKs after existing PUBACKs and PINGREQs. This ensure that PUBACKs go out in the order
  1437. * the corresponding PUBLISH was received, regardless of whether or not there was an intervening service call.
  1438. */
  1439. static void s_insert_node_before_predicate_failure(
  1440. struct aws_linked_list *list,
  1441. struct aws_linked_list_node *node,
  1442. aws_linked_list_node_predicate_fn predicate) {
  1443. struct aws_linked_list_node *current_node = NULL;
  1444. for (current_node = aws_linked_list_begin(list); current_node != aws_linked_list_end(list);
  1445. current_node = aws_linked_list_next(current_node)) {
  1446. if (!predicate(current_node)) {
  1447. break;
  1448. }
  1449. }
  1450. AWS_FATAL_ASSERT(current_node != NULL);
  1451. aws_linked_list_insert_before(current_node, node);
  1452. }
  1453. static int s_aws_mqtt5_client_queue_puback(struct aws_mqtt5_client *client, uint16_t packet_id) {
  1454. AWS_PRECONDITION(client != NULL);
  1455. const struct aws_mqtt5_packet_puback_view puback_view = {
  1456. .packet_id = packet_id,
  1457. .reason_code = AWS_MQTT5_PARC_SUCCESS,
  1458. };
  1459. struct aws_mqtt5_operation_puback *puback_op = aws_mqtt5_operation_puback_new(client->allocator, &puback_view);
  1460. if (puback_op == NULL) {
  1461. return AWS_OP_ERR;
  1462. }
  1463. AWS_LOGF_DEBUG(
  1464. AWS_LS_MQTT5_CLIENT,
  1465. "id=%p: enqueuing PUBACK operation to first position in queue that is not a PUBACK or PINGREQ",
  1466. (void *)client);
  1467. /*
  1468. * Put the PUBACK ahead of all user-submitted operations (PUBLISH, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT), but behind
  1469. * all pre-existing "internal" operations (PINGREQ, PUBACK).
  1470. *
  1471. * Qos 2 support will need to extend the predicate to include Qos 2 publish packets.
  1472. */
  1473. s_insert_node_before_predicate_failure(
  1474. &client->operational_state.queued_operations, &puback_op->base.node, s_is_ping_or_puback);
  1475. s_reevaluate_service_task(client);
  1476. return AWS_OP_SUCCESS;
  1477. }
  1478. static void s_aws_mqtt5_client_connected_on_packet_received(
  1479. struct aws_mqtt5_client *client,
  1480. enum aws_mqtt5_packet_type type,
  1481. void *packet_view) {
  1482. switch (type) {
  1483. case AWS_MQTT5_PT_PINGRESP:
  1484. AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: resetting PINGREQ timer", (void *)client);
  1485. client->next_ping_timeout_time = 0;
  1486. break;
  1487. case AWS_MQTT5_PT_DISCONNECT:
  1488. s_aws_mqtt5_client_emit_final_lifecycle_event(
  1489. client, AWS_ERROR_MQTT5_DISCONNECT_RECEIVED, NULL, packet_view);
  1490. AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: shutting down channel due to DISCONNECT", (void *)client);
  1491. s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_DISCONNECT_RECEIVED);
  1492. break;
  1493. case AWS_MQTT5_PT_SUBACK: {
  1494. uint16_t packet_id = ((const struct aws_mqtt5_packet_suback_view *)packet_view)->packet_id;
  1495. aws_mqtt5_client_operational_state_handle_ack(
  1496. &client->operational_state, packet_id, AWS_MQTT5_PT_SUBACK, packet_view, AWS_ERROR_SUCCESS);
  1497. break;
  1498. }
  1499. case AWS_MQTT5_PT_UNSUBACK: {
  1500. uint16_t packet_id = ((const struct aws_mqtt5_packet_unsuback_view *)packet_view)->packet_id;
  1501. aws_mqtt5_client_operational_state_handle_ack(
  1502. &client->operational_state, packet_id, AWS_MQTT5_PT_UNSUBACK, packet_view, AWS_ERROR_SUCCESS);
  1503. break;
  1504. }
  1505. case AWS_MQTT5_PT_PUBLISH: {
  1506. const struct aws_mqtt5_packet_publish_view *publish_view = packet_view;
  1507. aws_mqtt5_callback_set_manager_on_publish_received(&client->callback_manager, publish_view);
  1508. /* Send a puback if QoS 1+ */
  1509. if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
  1510. int result = s_aws_mqtt5_client_queue_puback(client, publish_view->packet_id);
  1511. if (result != AWS_OP_SUCCESS) {
  1512. int error_code = aws_last_error();
  1513. AWS_LOGF_ERROR(
  1514. AWS_LS_MQTT5_CLIENT,
  1515. "id=%p: decode failure with error %d(%s)",
  1516. (void *)client,
  1517. error_code,
  1518. aws_error_debug_str(error_code));
  1519. s_aws_mqtt5_client_shutdown_channel(client, error_code);
  1520. }
  1521. }
  1522. break;
  1523. }
  1524. case AWS_MQTT5_PT_PUBACK: {
  1525. uint16_t packet_id = ((const struct aws_mqtt5_packet_puback_view *)packet_view)->packet_id;
  1526. aws_mqtt5_client_operational_state_handle_ack(
  1527. &client->operational_state, packet_id, AWS_MQTT5_PT_PUBACK, packet_view, AWS_ERROR_SUCCESS);
  1528. break;
  1529. }
  1530. default:
  1531. break;
  1532. }
  1533. }
  1534. static int s_aws_mqtt5_client_on_packet_received(
  1535. enum aws_mqtt5_packet_type type,
  1536. void *packet_view,
  1537. void *decoder_callback_user_data) {
  1538. struct aws_mqtt5_client *client = decoder_callback_user_data;
  1539. s_aws_mqtt5_client_log_received_packet(client, type, packet_view);
  1540. switch (client->current_state) {
  1541. case AWS_MCS_MQTT_CONNECT:
  1542. s_aws_mqtt5_client_mqtt_connect_on_packet_received(client, type, packet_view);
  1543. break;
  1544. case AWS_MCS_CONNECTED:
  1545. case AWS_MCS_CLEAN_DISCONNECT:
  1546. s_aws_mqtt5_client_connected_on_packet_received(client, type, packet_view);
  1547. break;
  1548. default:
  1549. break;
  1550. }
  1551. s_reevaluate_service_task(client);
  1552. return AWS_OP_SUCCESS;
  1553. }
  1554. static uint64_t s_aws_high_res_clock_get_ticks_proxy(void) {
  1555. uint64_t current_time = 0;
  1556. AWS_FATAL_ASSERT(aws_high_res_clock_get_ticks(&current_time) == AWS_OP_SUCCESS);
  1557. return current_time;
  1558. }
  1559. struct aws_io_message *s_aws_channel_acquire_message_from_pool_default(
  1560. struct aws_channel *channel,
  1561. enum aws_io_message_type message_type,
  1562. size_t size_hint,
  1563. void *user_data) {
  1564. (void)user_data;
  1565. return aws_channel_acquire_message_from_pool(channel, message_type, size_hint);
  1566. }
  1567. static int s_aws_channel_slot_send_message_default(
  1568. struct aws_channel_slot *slot,
  1569. struct aws_io_message *message,
  1570. enum aws_channel_direction dir,
  1571. void *user_data) {
  1572. (void)user_data;
  1573. return aws_channel_slot_send_message(slot, message, dir);
  1574. }
  1575. static struct aws_mqtt5_client_vtable s_default_client_vtable = {
  1576. .get_current_time_fn = s_aws_high_res_clock_get_ticks_proxy,
  1577. .channel_shutdown_fn = aws_channel_shutdown,
  1578. .websocket_connect_fn = aws_websocket_client_connect,
  1579. .client_bootstrap_new_socket_channel_fn = aws_client_bootstrap_new_socket_channel,
  1580. .http_proxy_new_socket_channel_fn = aws_http_proxy_new_socket_channel,
  1581. .on_client_state_change_callback_fn = NULL,
  1582. .aws_channel_acquire_message_from_pool_fn = s_aws_channel_acquire_message_from_pool_default,
  1583. .aws_channel_slot_send_message_fn = s_aws_channel_slot_send_message_default,
  1584. .vtable_user_data = NULL,
  1585. };
  1586. void aws_mqtt5_client_set_vtable(struct aws_mqtt5_client *client, const struct aws_mqtt5_client_vtable *vtable) {
  1587. client->vtable = vtable;
  1588. }
  1589. const struct aws_mqtt5_client_vtable *aws_mqtt5_client_get_default_vtable(void) {
  1590. return &s_default_client_vtable;
  1591. }
  1592. struct aws_mqtt5_client *aws_mqtt5_client_new(
  1593. struct aws_allocator *allocator,
  1594. const struct aws_mqtt5_client_options *options) {
  1595. AWS_FATAL_ASSERT(allocator != NULL);
  1596. AWS_FATAL_ASSERT(options != NULL);
  1597. struct aws_mqtt5_client *client = aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt5_client));
  1598. if (client == NULL) {
  1599. return NULL;
  1600. }
  1601. aws_task_init(&client->service_task, s_mqtt5_service_task_fn, client, "Mqtt5Service");
  1602. client->allocator = allocator;
  1603. client->vtable = &s_default_client_vtable;
  1604. aws_ref_count_init(&client->ref_count, client, s_on_mqtt5_client_zero_ref_count);
  1605. aws_mqtt5_callback_set_manager_init(&client->callback_manager, client);
  1606. if (aws_mqtt5_client_operational_state_init(&client->operational_state, allocator, client)) {
  1607. goto on_error;
  1608. }
  1609. client->config = aws_mqtt5_client_options_storage_new(allocator, options);
  1610. if (client->config == NULL) {
  1611. goto on_error;
  1612. }
  1613. aws_mqtt5_client_flow_control_state_init(client);
  1614. /* all client activity will take place on this event loop, serializing things like reconnect, ping, etc... */
  1615. client->loop = aws_event_loop_group_get_next_loop(client->config->bootstrap->event_loop_group);
  1616. if (client->loop == NULL) {
  1617. goto on_error;
  1618. }
  1619. client->desired_state = AWS_MCS_STOPPED;
  1620. client->current_state = AWS_MCS_STOPPED;
  1621. client->lifecycle_state = AWS_MQTT5_LS_NONE;
  1622. struct aws_mqtt5_decoder_options decoder_options = {
  1623. .callback_user_data = client,
  1624. .on_packet_received = s_aws_mqtt5_client_on_packet_received,
  1625. };
  1626. if (aws_mqtt5_decoder_init(&client->decoder, allocator, &decoder_options)) {
  1627. goto on_error;
  1628. }
  1629. struct aws_mqtt5_encoder_options encoder_options = {
  1630. .client = client,
  1631. };
  1632. if (aws_mqtt5_encoder_init(&client->encoder, allocator, &encoder_options)) {
  1633. goto on_error;
  1634. }
  1635. if (aws_mqtt5_inbound_topic_alias_resolver_init(&client->inbound_topic_alias_resolver, allocator)) {
  1636. goto on_error;
  1637. }
  1638. client->outbound_topic_alias_resolver = aws_mqtt5_outbound_topic_alias_resolver_new(
  1639. allocator, client->config->topic_aliasing_options.outbound_topic_alias_behavior);
  1640. if (client->outbound_topic_alias_resolver == NULL) {
  1641. goto on_error;
  1642. }
  1643. if (aws_mqtt5_negotiated_settings_init(
  1644. allocator, &client->negotiated_settings, &options->connect_options->client_id)) {
  1645. goto on_error;
  1646. }
  1647. client->current_reconnect_delay_ms = 0;
  1648. client->handler.alloc = client->allocator;
  1649. client->handler.vtable = &s_mqtt5_channel_handler_vtable;
  1650. client->handler.impl = client;
  1651. aws_mqtt5_client_options_storage_log(client->config, AWS_LL_DEBUG);
  1652. s_init_statistics(&client->operation_statistics_impl);
  1653. return client;
  1654. on_error:
  1655. /* release isn't usable here since we may not even have an event loop */
  1656. s_mqtt5_client_final_destroy(client);
  1657. return NULL;
  1658. }
  1659. struct aws_mqtt5_client *aws_mqtt5_client_acquire(struct aws_mqtt5_client *client) {
  1660. if (client != NULL) {
  1661. aws_ref_count_acquire(&client->ref_count);
  1662. }
  1663. return client;
  1664. }
  1665. struct aws_mqtt5_client *aws_mqtt5_client_release(struct aws_mqtt5_client *client) {
  1666. if (client != NULL) {
  1667. aws_ref_count_release(&client->ref_count);
  1668. }
  1669. return NULL;
  1670. }
  1671. struct aws_mqtt_change_desired_state_task {
  1672. struct aws_task task;
  1673. struct aws_allocator *allocator;
  1674. struct aws_mqtt5_client *client;
  1675. enum aws_mqtt5_client_state desired_state;
  1676. struct aws_mqtt5_operation_disconnect *disconnect_operation;
  1677. };
  1678. static void s_change_state_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
  1679. (void)task;
  1680. struct aws_mqtt_change_desired_state_task *change_state_task = arg;
  1681. struct aws_mqtt5_client *client = change_state_task->client;
  1682. enum aws_mqtt5_client_state desired_state = change_state_task->desired_state;
  1683. if (status != AWS_TASK_STATUS_RUN_READY) {
  1684. goto done;
  1685. }
  1686. if (client->desired_state != desired_state) {
  1687. AWS_LOGF_INFO(
  1688. AWS_LS_MQTT5_CLIENT,
  1689. "id=%p: changing desired client state from %s to %s",
  1690. (void *)client,
  1691. aws_mqtt5_client_state_to_c_string(client->desired_state),
  1692. aws_mqtt5_client_state_to_c_string(desired_state));
  1693. client->desired_state = desired_state;
  1694. struct aws_mqtt5_operation_disconnect *disconnect_op = change_state_task->disconnect_operation;
  1695. if (desired_state == AWS_MCS_STOPPED && disconnect_op != NULL) {
  1696. s_aws_mqtt5_client_shutdown_channel_with_disconnect(
  1697. client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, disconnect_op);
  1698. }
  1699. s_reevaluate_service_task(client);
  1700. }
  1701. done:
  1702. aws_mqtt5_operation_disconnect_release(change_state_task->disconnect_operation);
  1703. if (desired_state != AWS_MCS_TERMINATED) {
  1704. aws_mqtt5_client_release(client);
  1705. }
  1706. aws_mem_release(change_state_task->allocator, change_state_task);
  1707. }
  1708. static struct aws_mqtt_change_desired_state_task *s_aws_mqtt_change_desired_state_task_new(
  1709. struct aws_allocator *allocator,
  1710. struct aws_mqtt5_client *client,
  1711. enum aws_mqtt5_client_state desired_state,
  1712. struct aws_mqtt5_operation_disconnect *disconnect_operation) {
  1713. struct aws_mqtt_change_desired_state_task *change_state_task =
  1714. aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_change_desired_state_task));
  1715. if (change_state_task == NULL) {
  1716. return NULL;
  1717. }
  1718. aws_task_init(&change_state_task->task, s_change_state_task_fn, (void *)change_state_task, "ChangeStateTask");
  1719. change_state_task->allocator = client->allocator;
  1720. change_state_task->client = (desired_state == AWS_MCS_TERMINATED) ? client : aws_mqtt5_client_acquire(client);
  1721. change_state_task->desired_state = desired_state;
  1722. change_state_task->disconnect_operation = aws_mqtt5_operation_disconnect_acquire(disconnect_operation);
  1723. return change_state_task;
  1724. }
  1725. static bool s_is_valid_desired_state(enum aws_mqtt5_client_state desired_state) {
  1726. switch (desired_state) {
  1727. case AWS_MCS_STOPPED:
  1728. case AWS_MCS_CONNECTED:
  1729. case AWS_MCS_TERMINATED:
  1730. return true;
  1731. default:
  1732. return false;
  1733. }
  1734. }
  1735. static int s_aws_mqtt5_client_change_desired_state(
  1736. struct aws_mqtt5_client *client,
  1737. enum aws_mqtt5_client_state desired_state,
  1738. struct aws_mqtt5_operation_disconnect *disconnect_operation) {
  1739. AWS_FATAL_ASSERT(client != NULL);
  1740. AWS_FATAL_ASSERT(client->loop != NULL);
  1741. AWS_FATAL_ASSERT(disconnect_operation == NULL || desired_state == AWS_MCS_STOPPED);
  1742. if (!s_is_valid_desired_state(desired_state)) {
  1743. AWS_LOGF_ERROR(
  1744. AWS_LS_MQTT5_CLIENT,
  1745. "id=%p: invalid desired state argument %d(%s)",
  1746. (void *)client,
  1747. (int)desired_state,
  1748. aws_mqtt5_client_state_to_c_string(desired_state));
  1749. return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
  1750. }
  1751. struct aws_mqtt_change_desired_state_task *task =
  1752. s_aws_mqtt_change_desired_state_task_new(client->allocator, client, desired_state, disconnect_operation);
  1753. if (task == NULL) {
  1754. AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: failed to create change desired state task", (void *)client);
  1755. return AWS_OP_ERR;
  1756. }
  1757. aws_event_loop_schedule_task_now(client->loop, &task->task);
  1758. return AWS_OP_SUCCESS;
  1759. }
  1760. int aws_mqtt5_client_start(struct aws_mqtt5_client *client) {
  1761. return s_aws_mqtt5_client_change_desired_state(client, AWS_MCS_CONNECTED, NULL);
  1762. }
  1763. int aws_mqtt5_client_stop(
  1764. struct aws_mqtt5_client *client,
  1765. const struct aws_mqtt5_packet_disconnect_view *options,
  1766. const struct aws_mqtt5_disconnect_completion_options *completion_options) {
  1767. AWS_FATAL_ASSERT(client != NULL);
  1768. struct aws_mqtt5_operation_disconnect *disconnect_op = NULL;
  1769. if (options != NULL) {
  1770. struct aws_mqtt5_disconnect_completion_options internal_completion_options = {
  1771. .completion_callback = s_on_disconnect_operation_complete,
  1772. .completion_user_data = client,
  1773. };
  1774. disconnect_op = aws_mqtt5_operation_disconnect_new(
  1775. client->allocator, options, completion_options, &internal_completion_options);
  1776. if (disconnect_op == NULL) {
  1777. AWS_LOGF_ERROR(
  1778. AWS_LS_MQTT5_CLIENT, "id=%p: failed to create requested DISCONNECT operation", (void *)client);
  1779. return AWS_OP_ERR;
  1780. }
  1781. AWS_LOGF_DEBUG(
  1782. AWS_LS_MQTT5_CLIENT,
  1783. "id=%p: Stopping client via DISCONNECT operation (%p)",
  1784. (void *)client,
  1785. (void *)disconnect_op);
  1786. aws_mqtt5_packet_disconnect_view_log(disconnect_op->base.packet_view, AWS_LL_DEBUG);
  1787. } else {
  1788. AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: Stopping client immediately", (void *)client);
  1789. }
  1790. int result = s_aws_mqtt5_client_change_desired_state(client, AWS_MCS_STOPPED, disconnect_op);
  1791. aws_mqtt5_operation_disconnect_release(disconnect_op);
  1792. return result;
  1793. }
  1794. struct aws_mqtt5_submit_operation_task {
  1795. struct aws_task task;
  1796. struct aws_allocator *allocator;
  1797. struct aws_mqtt5_client *client;
  1798. struct aws_mqtt5_operation *operation;
  1799. };
  1800. static void s_mqtt5_submit_operation_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
  1801. (void)task;
  1802. int completion_error_code = AWS_ERROR_MQTT5_CLIENT_TERMINATED;
  1803. struct aws_mqtt5_submit_operation_task *submit_operation_task = arg;
  1804. /*
  1805. * Take a ref to the operation that represents the client taking ownership
  1806. * If we subsequently reject it (task cancel or offline queue policy), then the operation completion
  1807. * will undo this ref acquisition.
  1808. */
  1809. aws_mqtt5_operation_acquire(submit_operation_task->operation);
  1810. if (status != AWS_TASK_STATUS_RUN_READY) {
  1811. goto error;
  1812. }
  1813. /*
  1814. * If we're offline and this operation doesn't meet the requirements of the offline queue retention policy,
  1815. * fail it immediately.
  1816. */
  1817. struct aws_mqtt5_client *client = submit_operation_task->client;
  1818. struct aws_mqtt5_operation *operation = submit_operation_task->operation;
  1819. if (client->current_state != AWS_MCS_CONNECTED) {
  1820. if (!s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(
  1821. operation, client->config->offline_queue_behavior)) {
  1822. completion_error_code = AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY;
  1823. goto error;
  1824. }
  1825. }
  1826. /* newly-submitted operations must have a 0 packet id */
  1827. aws_mqtt5_operation_set_packet_id(submit_operation_task->operation, 0);
  1828. s_enqueue_operation_back(submit_operation_task->client, submit_operation_task->operation);
  1829. aws_mqtt5_client_statistics_change_operation_statistic_state(
  1830. submit_operation_task->client, submit_operation_task->operation, AWS_MQTT5_OSS_INCOMPLETE);
  1831. goto done;
  1832. error:
  1833. s_complete_operation(NULL, submit_operation_task->operation, completion_error_code, AWS_MQTT5_PT_NONE, NULL);
  1834. done:
  1835. aws_mqtt5_operation_release(submit_operation_task->operation);
  1836. aws_mqtt5_client_release(submit_operation_task->client);
  1837. aws_mem_release(submit_operation_task->allocator, submit_operation_task);
  1838. }
  1839. static int s_submit_operation(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
  1840. struct aws_mqtt5_submit_operation_task *submit_task =
  1841. aws_mem_calloc(client->allocator, 1, sizeof(struct aws_mqtt5_submit_operation_task));
  1842. if (submit_task == NULL) {
  1843. return AWS_OP_ERR;
  1844. }
  1845. aws_task_init(&submit_task->task, s_mqtt5_submit_operation_task_fn, submit_task, "Mqtt5SubmitOperation");
  1846. submit_task->allocator = client->allocator;
  1847. submit_task->client = aws_mqtt5_client_acquire(client);
  1848. submit_task->operation = operation;
  1849. aws_event_loop_schedule_task_now(client->loop, &submit_task->task);
  1850. return AWS_OP_SUCCESS;
  1851. }
  1852. int aws_mqtt5_client_publish(
  1853. struct aws_mqtt5_client *client,
  1854. const struct aws_mqtt5_packet_publish_view *publish_options,
  1855. const struct aws_mqtt5_publish_completion_options *completion_options) {
  1856. AWS_PRECONDITION(client != NULL);
  1857. AWS_PRECONDITION(publish_options != NULL);
  1858. struct aws_mqtt5_operation_publish *publish_op =
  1859. aws_mqtt5_operation_publish_new(client->allocator, client, publish_options, completion_options);
  1860. if (publish_op == NULL) {
  1861. return AWS_OP_ERR;
  1862. }
  1863. AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: Submitting PUBLISH operation (%p)", (void *)client, (void *)publish_op);
  1864. aws_mqtt5_packet_publish_view_log(publish_op->base.packet_view, AWS_LL_DEBUG);
  1865. if (s_submit_operation(client, &publish_op->base)) {
  1866. goto error;
  1867. }
  1868. return AWS_OP_SUCCESS;
  1869. error:
  1870. aws_mqtt5_operation_release(&publish_op->base);
  1871. return AWS_OP_ERR;
  1872. }
  1873. int aws_mqtt5_client_subscribe(
  1874. struct aws_mqtt5_client *client,
  1875. const struct aws_mqtt5_packet_subscribe_view *subscribe_options,
  1876. const struct aws_mqtt5_subscribe_completion_options *completion_options) {
  1877. AWS_PRECONDITION(client != NULL);
  1878. AWS_PRECONDITION(subscribe_options != NULL);
  1879. struct aws_mqtt5_operation_subscribe *subscribe_op =
  1880. aws_mqtt5_operation_subscribe_new(client->allocator, client, subscribe_options, completion_options);
  1881. if (subscribe_op == NULL) {
  1882. return AWS_OP_ERR;
  1883. }
  1884. AWS_LOGF_DEBUG(
  1885. AWS_LS_MQTT5_CLIENT, "id=%p: Submitting SUBSCRIBE operation (%p)", (void *)client, (void *)subscribe_op);
  1886. aws_mqtt5_packet_subscribe_view_log(subscribe_op->base.packet_view, AWS_LL_DEBUG);
  1887. if (s_submit_operation(client, &subscribe_op->base)) {
  1888. goto error;
  1889. }
  1890. return AWS_OP_SUCCESS;
  1891. error:
  1892. aws_mqtt5_operation_release(&subscribe_op->base);
  1893. return AWS_OP_ERR;
  1894. }
  1895. int aws_mqtt5_client_unsubscribe(
  1896. struct aws_mqtt5_client *client,
  1897. const struct aws_mqtt5_packet_unsubscribe_view *unsubscribe_options,
  1898. const struct aws_mqtt5_unsubscribe_completion_options *completion_options) {
  1899. AWS_PRECONDITION(client != NULL);
  1900. AWS_PRECONDITION(unsubscribe_options != NULL);
  1901. struct aws_mqtt5_operation_unsubscribe *unsubscribe_op =
  1902. aws_mqtt5_operation_unsubscribe_new(client->allocator, client, unsubscribe_options, completion_options);
  1903. if (unsubscribe_op == NULL) {
  1904. return AWS_OP_ERR;
  1905. }
  1906. AWS_LOGF_DEBUG(
  1907. AWS_LS_MQTT5_CLIENT, "id=%p: Submitting UNSUBSCRIBE operation (%p)", (void *)client, (void *)unsubscribe_op);
  1908. aws_mqtt5_packet_unsubscribe_view_log(unsubscribe_op->base.packet_view, AWS_LL_DEBUG);
  1909. if (s_submit_operation(client, &unsubscribe_op->base)) {
  1910. goto error;
  1911. }
  1912. return AWS_OP_SUCCESS;
  1913. error:
  1914. aws_mqtt5_operation_release(&unsubscribe_op->base);
  1915. return AWS_OP_ERR;
  1916. }
  1917. static bool s_needs_packet_id(const struct aws_mqtt5_operation *operation) {
  1918. switch (operation->packet_type) {
  1919. case AWS_MQTT5_PT_SUBSCRIBE:
  1920. case AWS_MQTT5_PT_UNSUBSCRIBE:
  1921. return aws_mqtt5_operation_get_packet_id(operation) == 0;
  1922. case AWS_MQTT5_PT_PUBLISH: {
  1923. const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
  1924. if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
  1925. return false;
  1926. }
  1927. return aws_mqtt5_operation_get_packet_id(operation) == 0;
  1928. }
  1929. default:
  1930. return false;
  1931. }
  1932. }
  1933. static uint16_t s_next_packet_id(uint16_t current_id) {
  1934. if (++current_id == 0) {
  1935. current_id = 1;
  1936. }
  1937. return current_id;
  1938. }
  1939. int aws_mqtt5_operation_bind_packet_id(
  1940. struct aws_mqtt5_operation *operation,
  1941. struct aws_mqtt5_client_operational_state *client_operational_state) {
  1942. if (!s_needs_packet_id(operation)) {
  1943. return AWS_OP_SUCCESS;
  1944. }
  1945. uint16_t current_id = client_operational_state->next_mqtt_packet_id;
  1946. struct aws_hash_element *elem = NULL;
  1947. for (uint16_t i = 0; i < UINT16_MAX; ++i) {
  1948. aws_hash_table_find(&client_operational_state->unacked_operations_table, &current_id, &elem);
  1949. if (elem == NULL) {
  1950. aws_mqtt5_operation_set_packet_id(operation, current_id);
  1951. client_operational_state->next_mqtt_packet_id = s_next_packet_id(current_id);
  1952. return AWS_OP_SUCCESS;
  1953. }
  1954. current_id = s_next_packet_id(current_id);
  1955. }
  1956. aws_raise_error(AWS_ERROR_INVALID_STATE);
  1957. return AWS_OP_ERR;
  1958. }
  1959. int aws_mqtt5_client_operational_state_init(
  1960. struct aws_mqtt5_client_operational_state *client_operational_state,
  1961. struct aws_allocator *allocator,
  1962. struct aws_mqtt5_client *client) {
  1963. aws_linked_list_init(&client_operational_state->queued_operations);
  1964. aws_linked_list_init(&client_operational_state->write_completion_operations);
  1965. aws_linked_list_init(&client_operational_state->unacked_operations);
  1966. if (aws_hash_table_init(
  1967. &client_operational_state->unacked_operations_table,
  1968. allocator,
  1969. sizeof(struct aws_mqtt5_operation *),
  1970. s_hash_uint16_t,
  1971. s_uint16_t_eq,
  1972. NULL,
  1973. NULL)) {
  1974. return AWS_OP_ERR;
  1975. }
  1976. client_operational_state->next_mqtt_packet_id = 1;
  1977. client_operational_state->current_operation = NULL;
  1978. client_operational_state->client = client;
  1979. return AWS_OP_SUCCESS;
  1980. }
  1981. void aws_mqtt5_client_operational_state_clean_up(struct aws_mqtt5_client_operational_state *client_operational_state) {
  1982. AWS_ASSERT(client_operational_state->current_operation == NULL);
  1983. s_aws_mqtt5_client_operational_state_reset(client_operational_state, AWS_ERROR_MQTT5_CLIENT_TERMINATED, true);
  1984. }
  1985. static bool s_filter_queued_operations_for_offline(struct aws_mqtt5_operation *operation, void *context) {
  1986. struct aws_mqtt5_client *client = context;
  1987. enum aws_mqtt5_client_operation_queue_behavior_type queue_behavior = client->config->offline_queue_behavior;
  1988. return !s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(operation, queue_behavior);
  1989. }
  1990. static void s_process_unacked_operations_for_disconnect(struct aws_mqtt5_operation *operation, void *context) {
  1991. (void)context;
  1992. if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
  1993. struct aws_mqtt5_packet_publish_view *publish_view =
  1994. (struct aws_mqtt5_packet_publish_view *)operation->packet_view;
  1995. if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
  1996. publish_view->duplicate = true;
  1997. return;
  1998. }
  1999. }
  2000. aws_mqtt5_operation_set_packet_id(operation, 0);
  2001. }
  2002. static bool s_filter_unacked_operations_for_offline(struct aws_mqtt5_operation *operation, void *context) {
  2003. struct aws_mqtt5_client *client = context;
  2004. enum aws_mqtt5_client_operation_queue_behavior_type queue_behavior = client->config->offline_queue_behavior;
  2005. if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
  2006. const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
  2007. if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
  2008. return false;
  2009. }
  2010. }
  2011. return !s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(operation, queue_behavior);
  2012. }
  2013. /*
  2014. * Resets the client's operational state based on a disconnection (from above comment):
  2015. *
  2016. * If current_operation
  2017. * move current_operation to head of queued_operations
  2018. * Fail all operations in the pending write completion list
  2019. * Fail, remove, and release operations in queued_operations where they fail the offline queue policy
  2020. * Iterate unacked_operations:
  2021. * If qos1+ publish
  2022. * set dup flag
  2023. * else
  2024. * unset/release packet id
  2025. * Fail, remove, and release unacked_operations if:
  2026. * (1) They fail the offline queue policy AND
  2027. * (2) the operation is not Qos 1+ publish
  2028. *
  2029. * Clears the unacked_operations table
  2030. */
  2031. void aws_mqtt5_client_on_disconnection_update_operational_state(struct aws_mqtt5_client *client) {
  2032. struct aws_mqtt5_client_operational_state *client_operational_state = &client->operational_state;
  2033. /* move current operation to the head of the queue */
  2034. if (client_operational_state->current_operation != NULL) {
  2035. aws_linked_list_push_front(
  2036. &client_operational_state->queued_operations, &client_operational_state->current_operation->node);
  2037. client_operational_state->current_operation = NULL;
  2038. }
  2039. /* fail everything in pending write completion */
  2040. s_complete_operation_list(
  2041. client,
  2042. &client_operational_state->write_completion_operations,
  2043. AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
  2044. struct aws_linked_list operations_to_fail;
  2045. AWS_ZERO_STRUCT(operations_to_fail);
  2046. aws_linked_list_init(&operations_to_fail);
  2047. /* fail everything in the pending queue that doesn't meet the offline queue behavior retention requirements */
  2048. s_filter_operation_list(
  2049. &client_operational_state->queued_operations,
  2050. s_filter_queued_operations_for_offline,
  2051. &operations_to_fail,
  2052. client);
  2053. s_complete_operation_list(
  2054. client, &operations_to_fail, AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
  2055. /* Mark unacked qos1+ publishes as duplicate and release packet ids for non qos1+ publish */
  2056. s_apply_to_operation_list(
  2057. &client_operational_state->unacked_operations, s_process_unacked_operations_for_disconnect, NULL);
  2058. /*
  2059. * fail everything in the pending queue that
  2060. * (1) isn't a qos1+ publish AND
  2061. * (2) doesn't meet the offline queue behavior retention requirements
  2062. */
  2063. s_filter_operation_list(
  2064. &client_operational_state->unacked_operations,
  2065. s_filter_unacked_operations_for_offline,
  2066. &operations_to_fail,
  2067. client);
  2068. s_complete_operation_list(
  2069. client, &operations_to_fail, AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
  2070. aws_hash_table_clear(&client->operational_state.unacked_operations_table);
  2071. /*
  2072. * Prevents inbound resolution on the highly unlikely, illegal server behavior of sending a PUBLISH before
  2073. * a CONNACK on next connection establishment.
  2074. */
  2075. aws_mqtt5_decoder_set_inbound_topic_alias_resolver(&client->decoder, NULL);
  2076. }
  2077. static void s_set_operation_list_statistic_state(
  2078. struct aws_mqtt5_client *client,
  2079. struct aws_linked_list *operation_list,
  2080. enum aws_mqtt5_operation_statistic_state_flags new_state_flags) {
  2081. struct aws_linked_list_node *node = aws_linked_list_begin(operation_list);
  2082. while (node != aws_linked_list_end(operation_list)) {
  2083. struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
  2084. node = aws_linked_list_next(node);
  2085. aws_mqtt5_client_statistics_change_operation_statistic_state(client, operation, new_state_flags);
  2086. }
  2087. }
  2088. static bool s_filter_unacked_operations_for_session_rejoin(struct aws_mqtt5_operation *operation, void *context) {
  2089. (void)context;
  2090. if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
  2091. const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
  2092. if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
  2093. return false;
  2094. }
  2095. }
  2096. return true;
  2097. }
  2098. /*
  2099. * Updates the client's operational state based on a successfully established connection event:
  2100. *
  2101. * if rejoined_session:
  2102. * Move-and-append all non-qos1+-publishes in unacked_operations to the front of queued_operations
  2103. * Move-and-append remaining operations (qos1+ publishes) to the front of queued_operations
  2104. * else:
  2105. * Fail, remove, and release unacked_operations that fail the offline queue policy
  2106. * Move and append unacked operations to front of queued_operations
  2107. */
  2108. void aws_mqtt5_client_on_connection_update_operational_state(struct aws_mqtt5_client *client) {
  2109. struct aws_mqtt5_client_operational_state *client_operational_state = &client->operational_state;
  2110. if (client->negotiated_settings.rejoined_session) {
  2111. struct aws_linked_list requeued_operations;
  2112. AWS_ZERO_STRUCT(requeued_operations);
  2113. aws_linked_list_init(&requeued_operations);
  2114. /*
  2115. * qos1+ publishes must go out first, so split the unacked operation list into two sets: qos1+ publishes and
  2116. * everything else.
  2117. */
  2118. s_filter_operation_list(
  2119. &client_operational_state->unacked_operations,
  2120. s_filter_unacked_operations_for_session_rejoin,
  2121. &requeued_operations,
  2122. client);
  2123. /*
  2124. * Put non-qos1+ publishes on the front of the pending queue
  2125. */
  2126. aws_linked_list_move_all_front(&client->operational_state.queued_operations, &requeued_operations);
  2127. /*
  2128. * Put qos1+ publishes on the front of the pending queue
  2129. */
  2130. aws_linked_list_move_all_front(
  2131. &client->operational_state.queued_operations, &client_operational_state->unacked_operations);
  2132. } else {
  2133. struct aws_linked_list failed_operations;
  2134. AWS_ZERO_STRUCT(failed_operations);
  2135. aws_linked_list_init(&failed_operations);
  2136. s_filter_operation_list(
  2137. &client_operational_state->unacked_operations,
  2138. s_filter_queued_operations_for_offline,
  2139. &failed_operations,
  2140. client);
  2141. /*
  2142. * fail operations that we aren't going to requeue. In this particular case it's only qos1+ publishes
  2143. * that we didn't fail because we didn't know if we were going to rejoin a sesison or not.
  2144. */
  2145. s_complete_operation_list(
  2146. client, &failed_operations, AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
  2147. /* requeue operations that we are going to perform again */
  2148. aws_linked_list_move_all_front(
  2149. &client->operational_state.queued_operations, &client->operational_state.unacked_operations);
  2150. }
  2151. /* set everything remaining to incomplete */
  2152. s_set_operation_list_statistic_state(
  2153. client, &client->operational_state.queued_operations, AWS_MQTT5_OSS_INCOMPLETE);
  2154. aws_mqtt5_client_flow_control_state_reset(client);
  2155. uint16_t inbound_alias_maximum = client->negotiated_settings.topic_alias_maximum_to_client;
  2156. if (aws_mqtt5_inbound_topic_alias_resolver_reset(&client->inbound_topic_alias_resolver, inbound_alias_maximum)) {
  2157. AWS_LOGF_ERROR(
  2158. AWS_LS_MQTT5_CLIENT,
  2159. "id=%p: client unable to reset inbound alias resolver",
  2160. (void *)client_operational_state->client);
  2161. goto on_error;
  2162. }
  2163. if (inbound_alias_maximum > 0) {
  2164. aws_mqtt5_decoder_set_inbound_topic_alias_resolver(&client->decoder, &client->inbound_topic_alias_resolver);
  2165. } else {
  2166. aws_mqtt5_decoder_set_inbound_topic_alias_resolver(&client->decoder, NULL);
  2167. }
  2168. uint16_t outbound_alias_maximum = client->negotiated_settings.topic_alias_maximum_to_server;
  2169. if (aws_mqtt5_outbound_topic_alias_resolver_reset(client->outbound_topic_alias_resolver, outbound_alias_maximum)) {
  2170. AWS_LOGF_ERROR(
  2171. AWS_LS_MQTT5_CLIENT,
  2172. "id=%p: client unable to reset outbound alias resolver",
  2173. (void *)client_operational_state->client);
  2174. goto on_error;
  2175. }
  2176. aws_mqtt5_encoder_set_outbound_topic_alias_resolver(&client->encoder, client->outbound_topic_alias_resolver);
  2177. return;
  2178. on_error:
  2179. s_aws_mqtt5_client_shutdown_channel(client, aws_last_error());
  2180. }
  2181. static bool s_aws_mqtt5_client_has_pending_operational_work(
  2182. const struct aws_mqtt5_client_operational_state *client_operational_state,
  2183. enum aws_mqtt5_client_state client_state) {
  2184. if (aws_linked_list_empty(&client_operational_state->queued_operations)) {
  2185. return false;
  2186. }
  2187. struct aws_linked_list_node *next_operation_node =
  2188. aws_linked_list_front(&client_operational_state->queued_operations);
  2189. struct aws_mqtt5_operation *next_operation =
  2190. AWS_CONTAINER_OF(next_operation_node, struct aws_mqtt5_operation, node);
  2191. switch (client_state) {
  2192. case AWS_MCS_MQTT_CONNECT:
  2193. /* Only allowed to send a CONNECT packet in this state */
  2194. return next_operation->packet_type == AWS_MQTT5_PT_CONNECT;
  2195. case AWS_MCS_CLEAN_DISCONNECT:
  2196. /* Except for finishing the current operation, only allowed to send a DISCONNECT packet in this state */
  2197. return next_operation->packet_type == AWS_MQTT5_PT_DISCONNECT;
  2198. case AWS_MCS_CONNECTED:
  2199. return true;
  2200. default:
  2201. return false;
  2202. }
  2203. }
  2204. static uint64_t s_aws_mqtt5_client_compute_next_operation_flow_control_service_time(
  2205. struct aws_mqtt5_client *client,
  2206. struct aws_mqtt5_operation *operation,
  2207. uint64_t now) {
  2208. (void)operation;
  2209. switch (client->current_state) {
  2210. case AWS_MCS_MQTT_CONNECT:
  2211. case AWS_MCS_CLEAN_DISCONNECT:
  2212. return now;
  2213. case AWS_MCS_CONNECTED:
  2214. return aws_mqtt5_client_flow_control_state_get_next_operation_service_time(client, operation, now);
  2215. default:
  2216. /* no outbound traffic is allowed outside of the above states */
  2217. return 0;
  2218. }
  2219. }
  2220. /*
  2221. * We don't presently know if IoT Core's throughput limit is on the plaintext or encrypted data stream. Assume
  2222. * it's on the encrypted stream for now and make a reasonable guess at the additional cost TLS imposes on data size:
  2223. *
  2224. * This calculation is intended to be a reasonable default but will not be accurate in all cases
  2225. *
  2226. * Estimate the # of ethernet frames (max 1444 bytes) and add in potential TLS framing and padding values per.
  2227. *
  2228. * TODO: query IoT Core to determine if this calculation is needed after all
  2229. * TODO: may eventually want to expose the ethernet frame size here as a configurable option for networks that have a
  2230. * lower MTU
  2231. *
  2232. * References:
  2233. * https://tools.ietf.org/id/draft-mattsson-uta-tls-overhead-01.xml#rfc.section.3
  2234. *
  2235. */
  2236. #define ETHERNET_FRAME_MAX_PAYLOAD_SIZE 1500
  2237. #define TCP_SIZE_OVERESTIMATE 72
  2238. #define TLS_FRAMING_AND_PADDING_OVERESTIMATE 64
  2239. #define AVAILABLE_ETHERNET_FRAME_SIZE \
  2240. (ETHERNET_FRAME_MAX_PAYLOAD_SIZE - (TCP_SIZE_OVERESTIMATE + TLS_FRAMING_AND_PADDING_OVERESTIMATE))
  2241. #define ETHERNET_FRAMES_PER_IO_MESSAGE_ESTIMATE \
  2242. ((AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH + AVAILABLE_ETHERNET_FRAME_SIZE - 1) / AVAILABLE_ETHERNET_FRAME_SIZE)
  2243. #define THROUGHPUT_TOKENS_PER_IO_MESSAGE_OVERESTIMATE \
  2244. (AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH + \
  2245. ETHERNET_FRAMES_PER_IO_MESSAGE_ESTIMATE * TLS_FRAMING_AND_PADDING_OVERESTIMATE)
  2246. static uint64_t s_compute_throughput_throttle_wait(const struct aws_mqtt5_client *client, uint64_t now) {
  2247. /* flow control only applies during CONNECTED/CLEAN_DISCONNECT */
  2248. if (!aws_mqtt5_client_are_negotiated_settings_valid(client)) {
  2249. return now;
  2250. }
  2251. uint64_t throughput_wait = 0;
  2252. if (client->config->extended_validation_and_flow_control_options != AWS_MQTT5_EVAFCO_NONE) {
  2253. throughput_wait = aws_rate_limiter_token_bucket_compute_wait_for_tokens(
  2254. (struct aws_rate_limiter_token_bucket *)&client->flow_control_state.throughput_throttle,
  2255. THROUGHPUT_TOKENS_PER_IO_MESSAGE_OVERESTIMATE);
  2256. }
  2257. return aws_add_u64_saturating(now, throughput_wait);
  2258. }
  2259. static uint64_t s_aws_mqtt5_client_compute_operational_state_service_time(
  2260. const struct aws_mqtt5_client_operational_state *client_operational_state,
  2261. uint64_t now) {
  2262. /* If an io message is in transit down the channel, then wait for it to complete */
  2263. if (client_operational_state->pending_write_completion) {
  2264. return 0;
  2265. }
  2266. /* Throughput flow control check */
  2267. uint64_t next_throttled_time = s_compute_throughput_throttle_wait(client_operational_state->client, now);
  2268. if (next_throttled_time > now) {
  2269. return next_throttled_time;
  2270. }
  2271. /* If we're in the middle of something, keep going */
  2272. if (client_operational_state->current_operation != NULL) {
  2273. return now;
  2274. }
  2275. /* If nothing is queued, there's nothing to do */
  2276. enum aws_mqtt5_client_state client_state = client_operational_state->client->current_state;
  2277. if (!s_aws_mqtt5_client_has_pending_operational_work(client_operational_state, client_state)) {
  2278. return 0;
  2279. }
  2280. AWS_FATAL_ASSERT(!aws_linked_list_empty(&client_operational_state->queued_operations));
  2281. struct aws_linked_list_node *next_operation_node =
  2282. aws_linked_list_front(&client_operational_state->queued_operations);
  2283. struct aws_mqtt5_operation *next_operation =
  2284. AWS_CONTAINER_OF(next_operation_node, struct aws_mqtt5_operation, node);
  2285. AWS_FATAL_ASSERT(next_operation != NULL);
  2286. /*
  2287. * Check the head of the pending operation queue against flow control and client state restrictions
  2288. */
  2289. return s_aws_mqtt5_client_compute_next_operation_flow_control_service_time(
  2290. client_operational_state->client, next_operation, now);
  2291. }
  2292. static bool s_aws_mqtt5_client_should_service_operational_state(
  2293. const struct aws_mqtt5_client_operational_state *client_operational_state,
  2294. uint64_t now) {
  2295. return now == s_aws_mqtt5_client_compute_operational_state_service_time(client_operational_state, now);
  2296. }
  2297. static bool s_operation_requires_ack(const struct aws_mqtt5_operation *operation) {
  2298. switch (operation->packet_type) {
  2299. case AWS_MQTT5_PT_SUBSCRIBE:
  2300. case AWS_MQTT5_PT_UNSUBSCRIBE:
  2301. return true;
  2302. case AWS_MQTT5_PT_PUBLISH: {
  2303. const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
  2304. return publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE;
  2305. }
  2306. default:
  2307. return false;
  2308. }
  2309. }
  2310. static void s_on_pingreq_send(struct aws_mqtt5_client *client) {
  2311. uint64_t now = client->vtable->get_current_time_fn();
  2312. uint64_t ping_timeout_nanos =
  2313. aws_timestamp_convert(client->config->ping_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
  2314. client->next_ping_timeout_time = aws_add_u64_saturating(now, ping_timeout_nanos);
  2315. }
  2316. static int s_apply_throughput_flow_control(struct aws_mqtt5_client *client) {
  2317. /* flow control only applies during CONNECTED/CLEAN_DISCONNECT */
  2318. if (!aws_mqtt5_client_are_negotiated_settings_valid(client)) {
  2319. return AWS_OP_SUCCESS;
  2320. }
  2321. if (client->config->extended_validation_and_flow_control_options == AWS_MQTT5_EVAFCO_NONE) {
  2322. return AWS_OP_SUCCESS;
  2323. }
  2324. return aws_rate_limiter_token_bucket_take_tokens(
  2325. (struct aws_rate_limiter_token_bucket *)&client->flow_control_state.throughput_throttle,
  2326. THROUGHPUT_TOKENS_PER_IO_MESSAGE_OVERESTIMATE);
  2327. }
  2328. static int s_apply_publish_tps_flow_control(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
  2329. if (client->config->extended_validation_and_flow_control_options == AWS_MQTT5_EVAFCO_NONE) {
  2330. return AWS_OP_SUCCESS;
  2331. }
  2332. if (operation->packet_type != AWS_MQTT5_PT_PUBLISH) {
  2333. return AWS_OP_SUCCESS;
  2334. }
  2335. return aws_rate_limiter_token_bucket_take_tokens(
  2336. (struct aws_rate_limiter_token_bucket *)&client->flow_control_state.publish_throttle, 1);
  2337. }
  2338. int aws_mqtt5_client_service_operational_state(struct aws_mqtt5_client_operational_state *client_operational_state) {
  2339. struct aws_mqtt5_client *client = client_operational_state->client;
  2340. struct aws_channel_slot *slot = client->slot;
  2341. const struct aws_mqtt5_client_vtable *vtable = client->vtable;
  2342. uint64_t now = (*vtable->get_current_time_fn)();
  2343. /* Should we write data? */
  2344. bool should_service = s_aws_mqtt5_client_should_service_operational_state(client_operational_state, now);
  2345. if (!should_service) {
  2346. return AWS_OP_SUCCESS;
  2347. }
  2348. if (s_apply_throughput_flow_control(client)) {
  2349. return AWS_OP_SUCCESS;
  2350. }
  2351. /* If we're going to write data, we need something to write to */
  2352. struct aws_io_message *io_message = (*vtable->aws_channel_acquire_message_from_pool_fn)(
  2353. slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH, vtable->vtable_user_data);
  2354. if (io_message == NULL) {
  2355. return AWS_OP_ERR;
  2356. }
  2357. int operational_error_code = AWS_ERROR_SUCCESS;
  2358. do {
  2359. /* if no current operation, pull one in and setup encode */
  2360. if (client_operational_state->current_operation == NULL) {
  2361. /*
  2362. * Loop through queued operations, discarding ones that fail validation, until we run out or find
  2363. * a good one. Failing validation against negotiated settings is expected to be a rare event.
  2364. */
  2365. struct aws_mqtt5_operation *next_operation = NULL;
  2366. while (!aws_linked_list_empty(&client_operational_state->queued_operations)) {
  2367. struct aws_linked_list_node *next_operation_node =
  2368. aws_linked_list_pop_front(&client_operational_state->queued_operations);
  2369. struct aws_mqtt5_operation *operation =
  2370. AWS_CONTAINER_OF(next_operation_node, struct aws_mqtt5_operation, node);
  2371. if (s_apply_publish_tps_flow_control(client, operation)) {
  2372. break;
  2373. }
  2374. if (!aws_mqtt5_operation_validate_vs_connection_settings(operation, client)) {
  2375. next_operation = operation;
  2376. break;
  2377. }
  2378. enum aws_mqtt5_packet_type packet_type = operation->packet_type;
  2379. int validation_error_code = aws_last_error();
  2380. s_complete_operation(client, operation, validation_error_code, AWS_MQTT5_PT_NONE, NULL);
  2381. /* A DISCONNECT packet failing dynamic validation should shut down the whole channel */
  2382. if (packet_type == AWS_MQTT5_PT_DISCONNECT) {
  2383. operational_error_code = AWS_ERROR_MQTT5_OPERATION_PROCESSING_FAILURE;
  2384. break;
  2385. }
  2386. }
  2387. if (next_operation != NULL && s_aws_mqtt5_client_set_current_operation(client, next_operation)) {
  2388. operational_error_code = AWS_ERROR_MQTT5_OPERATION_PROCESSING_FAILURE;
  2389. break;
  2390. }
  2391. }
  2392. struct aws_mqtt5_operation *current_operation = client_operational_state->current_operation;
  2393. if (current_operation == NULL) {
  2394. break;
  2395. }
  2396. /* write current operation to message, handle errors */
  2397. enum aws_mqtt5_encoding_result encoding_result =
  2398. aws_mqtt5_encoder_encode_to_buffer(&client->encoder, &io_message->message_data);
  2399. if (encoding_result == AWS_MQTT5_ER_ERROR) {
  2400. operational_error_code = AWS_ERROR_MQTT5_ENCODE_FAILURE;
  2401. break;
  2402. }
  2403. /* if encoding finished:
  2404. * push to write completion or unacked
  2405. * clear current
  2406. * else (message full)
  2407. * break
  2408. */
  2409. if (encoding_result == AWS_MQTT5_ER_FINISHED) {
  2410. aws_mqtt5_client_flow_control_state_on_outbound_operation(client, current_operation);
  2411. if (s_operation_requires_ack(current_operation)) {
  2412. /* track the operation in the unacked data structures by packet id */
  2413. AWS_FATAL_ASSERT(aws_mqtt5_operation_get_packet_id(current_operation) != 0);
  2414. if (aws_hash_table_put(
  2415. &client_operational_state->unacked_operations_table,
  2416. aws_mqtt5_operation_get_packet_id_address(current_operation),
  2417. current_operation,
  2418. NULL)) {
  2419. operational_error_code = aws_last_error();
  2420. break;
  2421. }
  2422. if (client->config->ack_timeout_seconds != 0) {
  2423. current_operation->ack_timeout_timepoint_ns =
  2424. now + aws_timestamp_convert(
  2425. client->config->ack_timeout_seconds, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
  2426. }
  2427. aws_linked_list_push_back(&client_operational_state->unacked_operations, &current_operation->node);
  2428. aws_mqtt5_client_statistics_change_operation_statistic_state(
  2429. client, current_operation, AWS_MQTT5_OSS_INCOMPLETE | AWS_MQTT5_OSS_UNACKED);
  2430. } else {
  2431. /* no ack is necessary, just add to socket write completion list */
  2432. aws_linked_list_push_back(
  2433. &client_operational_state->write_completion_operations, &current_operation->node);
  2434. /*
  2435. * We special-case setting the ping timeout here. Other possible places are not appropriate:
  2436. *
  2437. * (1) Socket write completion - this leads to a race condition where our domain socket tests can
  2438. * sporadically fail because the PINGRESP is processed before the write completion callback is
  2439. * invoked.
  2440. *
  2441. * (2) Enqueue the ping - if the current operation is a large payload over a poor connection, it may
  2442. * be an arbitrarily long time before the current operation completes and the ping even has a chance
  2443. * to go out, meaning we will trigger a ping time out before it's even sent.
  2444. *
  2445. * Given a reasonable io message size, this is the best place to set the timeout.
  2446. */
  2447. if (current_operation->packet_type == AWS_MQTT5_PT_PINGREQ) {
  2448. s_on_pingreq_send(client);
  2449. }
  2450. }
  2451. client->operational_state.current_operation = NULL;
  2452. } else {
  2453. AWS_FATAL_ASSERT(encoding_result == AWS_MQTT5_ER_OUT_OF_ROOM);
  2454. break;
  2455. }
  2456. now = (*vtable->get_current_time_fn)();
  2457. should_service = s_aws_mqtt5_client_should_service_operational_state(client_operational_state, now);
  2458. } while (should_service);
  2459. if (operational_error_code != AWS_ERROR_SUCCESS) {
  2460. aws_mem_release(io_message->allocator, io_message);
  2461. return aws_raise_error(operational_error_code);
  2462. }
  2463. /* It's possible for there to be no data if we serviced operations that failed validation */
  2464. if (io_message->message_data.len == 0) {
  2465. aws_mem_release(io_message->allocator, io_message);
  2466. return AWS_OP_SUCCESS;
  2467. }
  2468. /* send io_message down channel in write direction, handle errors */
  2469. io_message->on_completion = s_aws_mqtt5_on_socket_write_completion;
  2470. io_message->user_data = client_operational_state->client;
  2471. client_operational_state->pending_write_completion = true;
  2472. if ((*vtable->aws_channel_slot_send_message_fn)(
  2473. slot, io_message, AWS_CHANNEL_DIR_WRITE, vtable->vtable_user_data)) {
  2474. client_operational_state->pending_write_completion = false;
  2475. aws_mem_release(io_message->allocator, io_message);
  2476. return AWS_OP_ERR;
  2477. }
  2478. return AWS_OP_SUCCESS;
  2479. }
  2480. void aws_mqtt5_client_operational_state_handle_ack(
  2481. struct aws_mqtt5_client_operational_state *client_operational_state,
  2482. aws_mqtt5_packet_id_t packet_id,
  2483. enum aws_mqtt5_packet_type packet_type,
  2484. const void *packet_view,
  2485. int error_code) {
  2486. if (packet_type == AWS_MQTT5_PT_PUBACK) {
  2487. aws_mqtt5_client_flow_control_state_on_puback(client_operational_state->client);
  2488. }
  2489. struct aws_hash_element *elem = NULL;
  2490. aws_hash_table_find(&client_operational_state->unacked_operations_table, &packet_id, &elem);
  2491. if (elem == NULL || elem->value == NULL) {
  2492. AWS_LOGF_ERROR(
  2493. AWS_LS_MQTT5_CLIENT,
  2494. "id=%p: received an ACK for an unknown operation with id %d",
  2495. (void *)client_operational_state->client,
  2496. (int)packet_id);
  2497. return;
  2498. } else {
  2499. AWS_LOGF_TRACE(
  2500. AWS_LS_MQTT5_CLIENT,
  2501. "id=%p: Processing ACK with id %d",
  2502. (void *)client_operational_state->client,
  2503. (int)packet_id);
  2504. }
  2505. struct aws_mqtt5_operation *operation = elem->value;
  2506. aws_linked_list_remove(&operation->node);
  2507. aws_hash_table_remove(&client_operational_state->unacked_operations_table, &packet_id, NULL, NULL);
  2508. s_complete_operation(client_operational_state->client, operation, error_code, packet_type, packet_view);
  2509. }
  2510. bool aws_mqtt5_client_are_negotiated_settings_valid(const struct aws_mqtt5_client *client) {
  2511. return client->current_state == AWS_MCS_CONNECTED || client->current_state == AWS_MCS_CLEAN_DISCONNECT;
  2512. }
  2513. void aws_mqtt5_client_flow_control_state_init(struct aws_mqtt5_client *client) {
  2514. struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
  2515. struct aws_rate_limiter_token_bucket_options publish_throttle_config = {
  2516. .tokens_per_second = AWS_IOT_CORE_PUBLISH_PER_SECOND_LIMIT,
  2517. .maximum_token_count = AWS_IOT_CORE_PUBLISH_PER_SECOND_LIMIT,
  2518. .initial_token_count = 0,
  2519. };
  2520. aws_rate_limiter_token_bucket_init(&flow_control->publish_throttle, &publish_throttle_config);
  2521. struct aws_rate_limiter_token_bucket_options throughput_throttle_config = {
  2522. .tokens_per_second = AWS_IOT_CORE_THROUGHPUT_LIMIT,
  2523. .maximum_token_count = AWS_IOT_CORE_THROUGHPUT_LIMIT,
  2524. .initial_token_count = 0,
  2525. };
  2526. aws_rate_limiter_token_bucket_init(&flow_control->throughput_throttle, &throughput_throttle_config);
  2527. }
  2528. void aws_mqtt5_client_flow_control_state_reset(struct aws_mqtt5_client *client) {
  2529. struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
  2530. AWS_FATAL_ASSERT(aws_mqtt5_client_are_negotiated_settings_valid(client));
  2531. flow_control->unacked_publish_token_count = client->negotiated_settings.receive_maximum_from_server;
  2532. aws_rate_limiter_token_bucket_reset(&client->flow_control_state.publish_throttle);
  2533. aws_rate_limiter_token_bucket_reset(&client->flow_control_state.throughput_throttle);
  2534. }
  2535. void aws_mqtt5_client_flow_control_state_on_puback(struct aws_mqtt5_client *client) {
  2536. struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
  2537. bool was_zero = flow_control->unacked_publish_token_count == 0;
  2538. flow_control->unacked_publish_token_count = aws_min_u32(
  2539. client->negotiated_settings.receive_maximum_from_server, flow_control->unacked_publish_token_count + 1);
  2540. if (was_zero) {
  2541. s_reevaluate_service_task(client);
  2542. }
  2543. }
  2544. void aws_mqtt5_client_flow_control_state_on_outbound_operation(
  2545. struct aws_mqtt5_client *client,
  2546. struct aws_mqtt5_operation *operation) {
  2547. if (operation->packet_type != AWS_MQTT5_PT_PUBLISH) {
  2548. return;
  2549. }
  2550. const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
  2551. if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
  2552. return;
  2553. }
  2554. struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
  2555. AWS_FATAL_ASSERT(flow_control->unacked_publish_token_count > 0);
  2556. --flow_control->unacked_publish_token_count;
  2557. }
  2558. uint64_t aws_mqtt5_client_flow_control_state_get_next_operation_service_time(
  2559. struct aws_mqtt5_client *client,
  2560. struct aws_mqtt5_operation *next_operation,
  2561. uint64_t now) {
  2562. if (next_operation->packet_type != AWS_MQTT5_PT_PUBLISH) {
  2563. return now;
  2564. }
  2565. /* publish tps check */
  2566. if (client->config->extended_validation_and_flow_control_options != AWS_MQTT5_EVAFCO_NONE) {
  2567. uint64_t publish_wait =
  2568. aws_rate_limiter_token_bucket_compute_wait_for_tokens(&client->flow_control_state.publish_throttle, 1);
  2569. if (publish_wait > 0) {
  2570. return now + publish_wait;
  2571. }
  2572. }
  2573. /* receive maximum check */
  2574. const struct aws_mqtt5_packet_publish_view *publish_view = next_operation->packet_view;
  2575. if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
  2576. return now;
  2577. }
  2578. if (client->flow_control_state.unacked_publish_token_count > 0) {
  2579. return now;
  2580. }
  2581. return 0;
  2582. }
  2583. void aws_mqtt5_client_statistics_change_operation_statistic_state(
  2584. struct aws_mqtt5_client *client,
  2585. struct aws_mqtt5_operation *operation,
  2586. enum aws_mqtt5_operation_statistic_state_flags new_state_flags) {
  2587. enum aws_mqtt5_packet_type packet_type = operation->packet_type;
  2588. if (packet_type != AWS_MQTT5_PT_PUBLISH && packet_type != AWS_MQTT5_PT_SUBSCRIBE &&
  2589. packet_type != AWS_MQTT5_PT_UNSUBSCRIBE) {
  2590. return;
  2591. }
  2592. if (operation->packet_size == 0) {
  2593. if (aws_mqtt5_packet_view_get_encoded_size(packet_type, operation->packet_view, &operation->packet_size)) {
  2594. return;
  2595. }
  2596. }
  2597. AWS_FATAL_ASSERT(operation->packet_size > 0);
  2598. uint64_t packet_size = (uint64_t)operation->packet_size;
  2599. enum aws_mqtt5_operation_statistic_state_flags old_state_flags = operation->statistic_state_flags;
  2600. if (new_state_flags == old_state_flags) {
  2601. return;
  2602. }
  2603. struct aws_mqtt5_client_operation_statistics_impl *stats = &client->operation_statistics_impl;
  2604. if ((old_state_flags & AWS_MQTT5_OSS_INCOMPLETE) != (new_state_flags & AWS_MQTT5_OSS_INCOMPLETE)) {
  2605. if ((new_state_flags & AWS_MQTT5_OSS_INCOMPLETE) != 0) {
  2606. aws_atomic_fetch_add(&stats->incomplete_operation_count_atomic, 1);
  2607. aws_atomic_fetch_add(&stats->incomplete_operation_size_atomic, (size_t)packet_size);
  2608. } else {
  2609. aws_atomic_fetch_sub(&stats->incomplete_operation_count_atomic, 1);
  2610. aws_atomic_fetch_sub(&stats->incomplete_operation_size_atomic, (size_t)packet_size);
  2611. }
  2612. }
  2613. if ((old_state_flags & AWS_MQTT5_OSS_UNACKED) != (new_state_flags & AWS_MQTT5_OSS_UNACKED)) {
  2614. if ((new_state_flags & AWS_MQTT5_OSS_UNACKED) != 0) {
  2615. aws_atomic_fetch_add(&stats->unacked_operation_count_atomic, 1);
  2616. aws_atomic_fetch_add(&stats->unacked_operation_size_atomic, (size_t)packet_size);
  2617. } else {
  2618. aws_atomic_fetch_sub(&stats->unacked_operation_count_atomic, 1);
  2619. aws_atomic_fetch_sub(&stats->unacked_operation_size_atomic, (size_t)packet_size);
  2620. }
  2621. }
  2622. operation->statistic_state_flags = new_state_flags;
  2623. if (client->vtable != NULL && client->vtable->on_client_statistics_changed_callback_fn != NULL) {
  2624. (*client->vtable->on_client_statistics_changed_callback_fn)(
  2625. client, operation, client->vtable->vtable_user_data);
  2626. }
  2627. }
  2628. void aws_mqtt5_client_get_stats(struct aws_mqtt5_client *client, struct aws_mqtt5_client_operation_statistics *stats) {
  2629. stats->incomplete_operation_count =
  2630. (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.incomplete_operation_count_atomic);
  2631. stats->incomplete_operation_size =
  2632. (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.incomplete_operation_size_atomic);
  2633. stats->unacked_operation_count =
  2634. (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.unacked_operation_count_atomic);
  2635. stats->unacked_operation_size =
  2636. (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.unacked_operation_size_atomic);
  2637. }