res_http_websocket.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2012, Digium, Inc.
  5. *
  6. * Joshua Colp <jcolp@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief WebSocket support for the Asterisk internal HTTP server
  21. *
  22. * \author Joshua Colp <jcolp@digium.com>
  23. */
  24. /*** MODULEINFO
  25. <support_level>extended</support_level>
  26. ***/
  27. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include "asterisk/module.h"
  30. #include "asterisk/http.h"
  31. #include "asterisk/astobj2.h"
  32. #include "asterisk/strings.h"
  33. #include "asterisk/file.h"
  34. #include "asterisk/unaligned.h"
  35. #include "asterisk/uri.h"
  36. #define AST_API_MODULE
  37. #include "asterisk/http_websocket.h"
  38. /*! \brief GUID used to compute the accept key, defined in the specifications */
  39. #define WEBSOCKET_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  40. /*! \brief Length of a websocket's client key */
  41. #define CLIENT_KEY_SIZE 16
  42. /*! \brief Number of buckets for registered protocols */
  43. #define MAX_PROTOCOL_BUCKETS 7
  44. /*! \brief Size of the pre-determined buffer for WebSocket frames */
  45. #define MAXIMUM_FRAME_SIZE 8192
  46. /*! \brief Default reconstruction size for multi-frame payload reconstruction. If exceeded the next frame will start a
  47. * payload.
  48. */
  49. #define DEFAULT_RECONSTRUCTION_CEILING 16384
  50. /*! \brief Maximum reconstruction size for multi-frame payload reconstruction. */
  51. #define MAXIMUM_RECONSTRUCTION_CEILING 16384
  52. /*! \brief Maximum size of a websocket frame header
  53. * 1 byte flags and opcode
  54. * 1 byte mask flag + payload len
  55. * 8 bytes max extended length
  56. * 4 bytes optional masking key
  57. * ... payload follows ...
  58. * */
  59. #define MAX_WS_HDR_SZ 14
  60. #define MIN_WS_HDR_SZ 2
  61. /*! \brief Structure definition for session */
  62. struct ast_websocket {
  63. FILE *f; /*!< Pointer to the file instance used for writing and reading */
  64. int fd; /*!< File descriptor for the session, only used for polling */
  65. struct ast_sockaddr address; /*!< Address of the remote client */
  66. enum ast_websocket_opcode opcode; /*!< Cached opcode for multi-frame messages */
  67. size_t payload_len; /*!< Length of the payload */
  68. char *payload; /*!< Pointer to the payload */
  69. size_t reconstruct; /*!< Number of bytes before a reconstructed payload will be returned and a new one started */
  70. int timeout; /*!< The timeout for operations on the socket */
  71. unsigned int secure:1; /*!< Bit to indicate that the transport is secure */
  72. unsigned int closing:1; /*!< Bit to indicate that the session is in the process of being closed */
  73. unsigned int close_sent:1; /*!< Bit to indicate that the session close opcode has been sent and no further data will be sent */
  74. struct websocket_client *client; /*!< Client object when connected as a client websocket */
  75. };
  76. /*! \brief Structure definition for protocols */
  77. struct websocket_protocol {
  78. char *name; /*!< Name of the protocol */
  79. ast_websocket_callback callback; /*!< Callback called when a new session is established */
  80. };
  81. /*! \brief Hashing function for protocols */
  82. static int protocol_hash_fn(const void *obj, const int flags)
  83. {
  84. const struct websocket_protocol *protocol = obj;
  85. const char *name = obj;
  86. return ast_str_case_hash(flags & OBJ_KEY ? name : protocol->name);
  87. }
  88. /*! \brief Comparison function for protocols */
  89. static int protocol_cmp_fn(void *obj, void *arg, int flags)
  90. {
  91. const struct websocket_protocol *protocol1 = obj, *protocol2 = arg;
  92. const char *protocol = arg;
  93. return !strcasecmp(protocol1->name, flags & OBJ_KEY ? protocol : protocol2->name) ? CMP_MATCH | CMP_STOP : 0;
  94. }
  95. /*! \brief Destructor function for protocols */
  96. static void protocol_destroy_fn(void *obj)
  97. {
  98. struct websocket_protocol *protocol = obj;
  99. ast_free(protocol->name);
  100. }
  101. /*! \brief Structure for a WebSocket server */
  102. struct ast_websocket_server {
  103. struct ao2_container *protocols; /*!< Container for registered protocols */
  104. };
  105. static void websocket_server_internal_dtor(void *obj)
  106. {
  107. struct ast_websocket_server *server = obj;
  108. ao2_cleanup(server->protocols);
  109. server->protocols = NULL;
  110. }
  111. static void websocket_server_dtor(void *obj)
  112. {
  113. websocket_server_internal_dtor(obj);
  114. ast_module_unref(ast_module_info->self);
  115. }
  116. static struct ast_websocket_server *websocket_server_create_impl(void (*dtor)(void *))
  117. {
  118. RAII_VAR(struct ast_websocket_server *, server, NULL, ao2_cleanup);
  119. server = ao2_alloc(sizeof(*server), dtor);
  120. if (!server) {
  121. return NULL;
  122. }
  123. server->protocols = ao2_container_alloc(MAX_PROTOCOL_BUCKETS, protocol_hash_fn, protocol_cmp_fn);
  124. if (!server->protocols) {
  125. return NULL;
  126. }
  127. ao2_ref(server, +1);
  128. return server;
  129. }
  130. static struct ast_websocket_server *websocket_server_internal_create(void)
  131. {
  132. return websocket_server_create_impl(websocket_server_internal_dtor);
  133. }
  134. struct ast_websocket_server *AST_OPTIONAL_API_NAME(ast_websocket_server_create)(void)
  135. {
  136. ast_module_ref(ast_module_info->self);
  137. return websocket_server_create_impl(websocket_server_dtor);
  138. }
  139. /*! \brief Destructor function for sessions */
  140. static void session_destroy_fn(void *obj)
  141. {
  142. struct ast_websocket *session = obj;
  143. if (session->f) {
  144. ast_websocket_close(session, 0);
  145. fclose(session->f);
  146. ast_verb(2, "WebSocket connection %s '%s' closed\n", session->client ? "to" : "from",
  147. ast_sockaddr_stringify(&session->address));
  148. }
  149. ao2_cleanup(session->client);
  150. ast_free(session->payload);
  151. }
  152. int AST_OPTIONAL_API_NAME(ast_websocket_server_add_protocol)(struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
  153. {
  154. struct websocket_protocol *protocol;
  155. if (!server->protocols) {
  156. return -1;
  157. }
  158. ao2_lock(server->protocols);
  159. /* Ensure a second protocol handler is not registered for the same protocol */
  160. if ((protocol = ao2_find(server->protocols, name, OBJ_KEY | OBJ_NOLOCK))) {
  161. ao2_ref(protocol, -1);
  162. ao2_unlock(server->protocols);
  163. return -1;
  164. }
  165. if (!(protocol = ao2_alloc(sizeof(*protocol), protocol_destroy_fn))) {
  166. ao2_unlock(server->protocols);
  167. return -1;
  168. }
  169. if (!(protocol->name = ast_strdup(name))) {
  170. ao2_ref(protocol, -1);
  171. ao2_unlock(server->protocols);
  172. return -1;
  173. }
  174. protocol->callback = callback;
  175. ao2_link_flags(server->protocols, protocol, OBJ_NOLOCK);
  176. ao2_unlock(server->protocols);
  177. ao2_ref(protocol, -1);
  178. ast_verb(2, "WebSocket registered sub-protocol '%s'\n", name);
  179. return 0;
  180. }
  181. int AST_OPTIONAL_API_NAME(ast_websocket_server_remove_protocol)(struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
  182. {
  183. struct websocket_protocol *protocol;
  184. if (!(protocol = ao2_find(server->protocols, name, OBJ_KEY))) {
  185. return -1;
  186. }
  187. if (protocol->callback != callback) {
  188. ao2_ref(protocol, -1);
  189. return -1;
  190. }
  191. ao2_unlink(server->protocols, protocol);
  192. ao2_ref(protocol, -1);
  193. ast_verb(2, "WebSocket unregistered sub-protocol '%s'\n", name);
  194. return 0;
  195. }
  196. /*! \brief Close function for websocket session */
  197. int AST_OPTIONAL_API_NAME(ast_websocket_close)(struct ast_websocket *session, uint16_t reason)
  198. {
  199. char frame[4] = { 0, }; /* The header is 2 bytes and the reason code takes up another 2 bytes */
  200. int res;
  201. if (session->close_sent) {
  202. return 0;
  203. }
  204. frame[0] = AST_WEBSOCKET_OPCODE_CLOSE | 0x80;
  205. frame[1] = 2; /* The reason code is always 2 bytes */
  206. /* If no reason has been specified assume 1000 which is normal closure */
  207. put_unaligned_uint16(&frame[2], htons(reason ? reason : 1000));
  208. session->closing = 1;
  209. session->close_sent = 1;
  210. ao2_lock(session);
  211. res = ast_careful_fwrite(session->f, session->fd, frame, 4, session->timeout);
  212. ao2_unlock(session);
  213. return res;
  214. }
  215. /*! \brief Write function for websocket traffic */
  216. int AST_OPTIONAL_API_NAME(ast_websocket_write)(struct ast_websocket *session, enum ast_websocket_opcode opcode, char *payload, uint64_t actual_length)
  217. {
  218. size_t header_size = 2; /* The minimum size of a websocket frame is 2 bytes */
  219. char *frame;
  220. uint64_t length = 0;
  221. if (actual_length < 126) {
  222. length = actual_length;
  223. } else if (actual_length < (1 << 16)) {
  224. length = 126;
  225. /* We need an additional 2 bytes to store the extended length */
  226. header_size += 2;
  227. } else {
  228. length = 127;
  229. /* We need an additional 8 bytes to store the really really extended length */
  230. header_size += 8;
  231. }
  232. frame = ast_alloca(header_size);
  233. memset(frame, 0, sizeof(*frame));
  234. frame[0] = opcode | 0x80;
  235. frame[1] = length;
  236. /* Use the additional available bytes to store the length */
  237. if (length == 126) {
  238. put_unaligned_uint16(&frame[2], htons(actual_length));
  239. } else if (length == 127) {
  240. put_unaligned_uint64(&frame[2], htonl(actual_length));
  241. }
  242. ao2_lock(session);
  243. if (session->closing) {
  244. ao2_unlock(session);
  245. return -1;
  246. }
  247. if (ast_careful_fwrite(session->f, session->fd, frame, header_size, session->timeout)) {
  248. ao2_unlock(session);
  249. return -1;
  250. }
  251. if (ast_careful_fwrite(session->f, session->fd, payload, actual_length, session->timeout)) {
  252. ao2_unlock(session);
  253. return -1;
  254. }
  255. fflush(session->f);
  256. ao2_unlock(session);
  257. return 0;
  258. }
  259. void AST_OPTIONAL_API_NAME(ast_websocket_reconstruct_enable)(struct ast_websocket *session, size_t bytes)
  260. {
  261. session->reconstruct = MIN(bytes, MAXIMUM_RECONSTRUCTION_CEILING);
  262. }
  263. void AST_OPTIONAL_API_NAME(ast_websocket_reconstruct_disable)(struct ast_websocket *session)
  264. {
  265. session->reconstruct = 0;
  266. }
  267. void AST_OPTIONAL_API_NAME(ast_websocket_ref)(struct ast_websocket *session)
  268. {
  269. ao2_ref(session, +1);
  270. }
  271. void AST_OPTIONAL_API_NAME(ast_websocket_unref)(struct ast_websocket *session)
  272. {
  273. ao2_cleanup(session);
  274. }
  275. int AST_OPTIONAL_API_NAME(ast_websocket_fd)(struct ast_websocket *session)
  276. {
  277. return session->closing ? -1 : session->fd;
  278. }
  279. struct ast_sockaddr * AST_OPTIONAL_API_NAME(ast_websocket_remote_address)(struct ast_websocket *session)
  280. {
  281. return &session->address;
  282. }
  283. int AST_OPTIONAL_API_NAME(ast_websocket_is_secure)(struct ast_websocket *session)
  284. {
  285. return session->secure;
  286. }
  287. int AST_OPTIONAL_API_NAME(ast_websocket_set_nonblock)(struct ast_websocket *session)
  288. {
  289. int flags;
  290. if ((flags = fcntl(session->fd, F_GETFL)) == -1) {
  291. return -1;
  292. }
  293. flags |= O_NONBLOCK;
  294. if ((flags = fcntl(session->fd, F_SETFL, flags)) == -1) {
  295. return -1;
  296. }
  297. return 0;
  298. }
  299. int AST_OPTIONAL_API_NAME(ast_websocket_set_timeout)(struct ast_websocket *session, int timeout)
  300. {
  301. session->timeout = timeout;
  302. return 0;
  303. }
  304. /* MAINTENANCE WARNING on ast_websocket_read()!
  305. *
  306. * We have to keep in mind during this function that the fact that session->fd seems ready
  307. * (via poll) does not necessarily mean we have application data ready, because in the case
  308. * of an SSL socket, there is some encryption data overhead that needs to be read from the
  309. * TCP socket, so poll() may say there are bytes to be read, but whether it is just 1 byte
  310. * or N bytes we do not know that, and we do not know how many of those bytes (if any) are
  311. * for application data (for us) and not just for the SSL protocol consumption
  312. *
  313. * There used to be a couple of nasty bugs here that were fixed in last refactoring but I
  314. * want to document them so the constraints are clear and we do not re-introduce them:
  315. *
  316. * - This function would incorrectly assume that fread() would necessarily return more than
  317. * 1 byte of data, just because a websocket frame is always >= 2 bytes, but the thing
  318. * is we're dealing with a TCP bitstream here, we could read just one byte and that's normal.
  319. * The problem before was that if just one byte was read, the function bailed out and returned
  320. * an error, effectively dropping the first byte of a websocket frame header!
  321. *
  322. * - Another subtle bug was that it would just read up to MAX_WS_HDR_SZ (14 bytes) via fread()
  323. * then assume that executing poll() would tell you if there is more to read, but since
  324. * we're dealing with a buffered stream (session->f is a FILE*), poll would say there is
  325. * nothing else to read (in the real tcp socket session->fd) and we would get stuck here
  326. * without processing the rest of the data in session->f internal buffers until another packet
  327. * came on the network to unblock us!
  328. *
  329. * Note during the header parsing stage we try to read in small chunks just what we need, this
  330. * is buffered data anyways, no expensive syscall required most of the time ...
  331. */
  332. static inline int ws_safe_read(struct ast_websocket *session, char *buf, int len, enum ast_websocket_opcode *opcode)
  333. {
  334. int sanity;
  335. size_t rlen;
  336. int xlen = len;
  337. char *rbuf = buf;
  338. for (sanity = 10; sanity; sanity--) {
  339. clearerr(session->f);
  340. rlen = fread(rbuf, 1, xlen, session->f);
  341. if (0 == rlen && ferror(session->f) && errno != EAGAIN) {
  342. ast_log(LOG_ERROR, "Error reading from web socket: %s\n", strerror(errno));
  343. (*opcode) = AST_WEBSOCKET_OPCODE_CLOSE;
  344. session->closing = 1;
  345. return -1;
  346. }
  347. xlen = (xlen - rlen);
  348. rbuf = rbuf + rlen;
  349. if (0 == xlen) {
  350. break;
  351. }
  352. if (ast_wait_for_input(session->fd, 1000) < 0) {
  353. ast_log(LOG_ERROR, "ast_wait_for_input returned err: %s\n", strerror(errno));
  354. (*opcode) = AST_WEBSOCKET_OPCODE_CLOSE;
  355. session->closing = 1;
  356. return -1;
  357. }
  358. }
  359. if (!sanity) {
  360. ast_log(LOG_WARNING, "Websocket seems unresponsive, disconnecting ...\n");
  361. (*opcode) = AST_WEBSOCKET_OPCODE_CLOSE;
  362. session->closing = 1;
  363. return -1;
  364. }
  365. return 0;
  366. }
  367. int AST_OPTIONAL_API_NAME(ast_websocket_read)(struct ast_websocket *session, char **payload, uint64_t *payload_len, enum ast_websocket_opcode *opcode, int *fragmented)
  368. {
  369. char buf[MAXIMUM_FRAME_SIZE] = "";
  370. int fin = 0;
  371. int mask_present = 0;
  372. char *mask = NULL, *new_payload = NULL;
  373. size_t options_len = 0, frame_size = 0;
  374. *payload = NULL;
  375. *payload_len = 0;
  376. *fragmented = 0;
  377. if (ws_safe_read(session, &buf[0], MIN_WS_HDR_SZ, opcode)) {
  378. return 0;
  379. }
  380. frame_size += MIN_WS_HDR_SZ;
  381. /* ok, now we have the first 2 bytes, so we know some flags, opcode and payload length (or whether payload length extension will be required) */
  382. *opcode = buf[0] & 0xf;
  383. *payload_len = buf[1] & 0x7f;
  384. if (*opcode == AST_WEBSOCKET_OPCODE_TEXT || *opcode == AST_WEBSOCKET_OPCODE_BINARY || *opcode == AST_WEBSOCKET_OPCODE_CONTINUATION ||
  385. *opcode == AST_WEBSOCKET_OPCODE_PING || *opcode == AST_WEBSOCKET_OPCODE_PONG) {
  386. fin = (buf[0] >> 7) & 1;
  387. mask_present = (buf[1] >> 7) & 1;
  388. /* Based on the mask flag and payload length, determine how much more we need to read before start parsing the rest of the header */
  389. options_len += mask_present ? 4 : 0;
  390. options_len += (*payload_len == 126) ? 2 : (*payload_len == 127) ? 8 : 0;
  391. if (options_len) {
  392. /* read the rest of the header options */
  393. if (ws_safe_read(session, &buf[frame_size], options_len, opcode)) {
  394. return 0;
  395. }
  396. frame_size += options_len;
  397. }
  398. if (*payload_len == 126) {
  399. /* Grab the 2-byte payload length */
  400. *payload_len = ntohs(get_unaligned_uint16(&buf[2]));
  401. mask = &buf[4];
  402. } else if (*payload_len == 127) {
  403. /* Grab the 8-byte payload length */
  404. *payload_len = ntohl(get_unaligned_uint64(&buf[2]));
  405. mask = &buf[10];
  406. } else {
  407. /* Just set the mask after the small 2-byte header */
  408. mask = &buf[2];
  409. }
  410. /* Now read the rest of the payload */
  411. *payload = &buf[frame_size]; /* payload will start here, at the end of the options, if any */
  412. frame_size = frame_size + (*payload_len); /* final frame size is header + optional headers + payload data */
  413. if (frame_size > MAXIMUM_FRAME_SIZE) {
  414. ast_log(LOG_WARNING, "Cannot fit huge websocket frame of %zu bytes\n", frame_size);
  415. /* The frame won't fit :-( */
  416. ast_websocket_close(session, 1009);
  417. return -1;
  418. }
  419. if (ws_safe_read(session, (*payload), (*payload_len), opcode)) {
  420. return 0;
  421. }
  422. /* If a mask is present unmask the payload */
  423. if (mask_present) {
  424. unsigned int pos;
  425. for (pos = 0; pos < *payload_len; pos++) {
  426. (*payload)[pos] ^= mask[pos % 4];
  427. }
  428. }
  429. /* Per the RFC for PING we need to send back an opcode with the application data as received */
  430. if ((*opcode == AST_WEBSOCKET_OPCODE_PING) && (ast_websocket_write(session, AST_WEBSOCKET_OPCODE_PONG, *payload, *payload_len))) {
  431. *payload_len = 0;
  432. ast_websocket_close(session, 1009);
  433. return 0;
  434. }
  435. if (*payload_len) {
  436. if (!(new_payload = ast_realloc(session->payload, (session->payload_len + *payload_len)))) {
  437. ast_log(LOG_WARNING, "Failed allocation: %p, %zu, %"PRIu64"\n",
  438. session->payload, session->payload_len, *payload_len);
  439. *payload_len = 0;
  440. ast_websocket_close(session, 1009);
  441. return 0;
  442. }
  443. session->payload = new_payload;
  444. memcpy((session->payload + session->payload_len), (*payload), (*payload_len));
  445. session->payload_len += *payload_len;
  446. } else if (!session->payload_len && session->payload) {
  447. ast_free(session->payload);
  448. session->payload = NULL;
  449. }
  450. if (!fin && session->reconstruct && (session->payload_len < session->reconstruct)) {
  451. /* If this is not a final message we need to defer returning it until later */
  452. if (*opcode != AST_WEBSOCKET_OPCODE_CONTINUATION) {
  453. session->opcode = *opcode;
  454. }
  455. *opcode = AST_WEBSOCKET_OPCODE_CONTINUATION;
  456. *payload_len = 0;
  457. *payload = NULL;
  458. } else {
  459. if (*opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
  460. if (!fin) {
  461. /* If this was not actually the final message tell the user it is fragmented so they can deal with it accordingly */
  462. *fragmented = 1;
  463. } else {
  464. /* Final frame in multi-frame so push up the actual opcode */
  465. *opcode = session->opcode;
  466. }
  467. }
  468. *payload_len = session->payload_len;
  469. *payload = session->payload;
  470. session->payload_len = 0;
  471. }
  472. } else if (*opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
  473. /* Make the payload available so the user can look at the reason code if they so desire */
  474. if ((*payload_len) && (new_payload = ast_realloc(session->payload, *payload_len))) {
  475. if (ws_safe_read(session, &buf[frame_size], (*payload_len), opcode)) {
  476. return 0;
  477. }
  478. session->payload = new_payload;
  479. memcpy(session->payload, &buf[frame_size], *payload_len);
  480. *payload = session->payload;
  481. frame_size += (*payload_len);
  482. }
  483. session->closing = 1;
  484. } else {
  485. ast_log(LOG_WARNING, "WebSocket unknown opcode %u\n", *opcode);
  486. /* We received an opcode that we don't understand, the RFC states that 1003 is for a type of data that can't be accepted... opcodes
  487. * fit that, I think. */
  488. ast_websocket_close(session, 1003);
  489. }
  490. return 0;
  491. }
  492. /*!
  493. * \brief If the server has exactly one configured protocol, return it.
  494. */
  495. static struct websocket_protocol *one_protocol(
  496. struct ast_websocket_server *server)
  497. {
  498. SCOPED_AO2LOCK(lock, server->protocols);
  499. if (ao2_container_count(server->protocols) != 1) {
  500. return NULL;
  501. }
  502. return ao2_callback(server->protocols, OBJ_NOLOCK, NULL, NULL);
  503. }
  504. static char *websocket_combine_key(const char *key, char *res, int res_size)
  505. {
  506. char *combined;
  507. unsigned combined_length = strlen(key) + strlen(WEBSOCKET_GUID) + 1;
  508. uint8_t sha[20];
  509. combined = ast_alloca(combined_length);
  510. snprintf(combined, combined_length, "%s%s", key, WEBSOCKET_GUID);
  511. ast_sha1_hash_uint(sha, combined);
  512. ast_base64encode(res, (const unsigned char*)sha, 20, res_size);
  513. return res;
  514. }
  515. static void websocket_bad_request(struct ast_tcptls_session_instance *ser)
  516. {
  517. struct ast_str *http_header = ast_str_create(64);
  518. if (!http_header) {
  519. ast_http_request_close_on_completion(ser);
  520. ast_http_error(ser, 500, "Server Error", "Out of memory");
  521. return;
  522. }
  523. ast_str_set(&http_header, 0, "Sec-WebSocket-Version: 7, 8, 13\r\n");
  524. ast_http_send(ser, AST_HTTP_UNKNOWN, 400, "Bad Request", http_header, NULL, 0, 0);
  525. }
  526. int AST_OPTIONAL_API_NAME(ast_websocket_uri_cb)(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_vars, struct ast_variable *headers)
  527. {
  528. struct ast_variable *v;
  529. char *upgrade = NULL, *key = NULL, *key1 = NULL, *key2 = NULL, *protos = NULL, *requested_protocols = NULL, *protocol = NULL;
  530. int version = 0, flags = 1;
  531. struct websocket_protocol *protocol_handler = NULL;
  532. struct ast_websocket *session;
  533. struct ast_websocket_server *server;
  534. SCOPED_MODULE_USE(ast_module_info->self);
  535. /* Upgrade requests are only permitted on GET methods */
  536. if (method != AST_HTTP_GET) {
  537. ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
  538. return 0;
  539. }
  540. server = urih->data;
  541. /* Get the minimum headers required to satisfy our needs */
  542. for (v = headers; v; v = v->next) {
  543. if (!strcasecmp(v->name, "Upgrade")) {
  544. upgrade = ast_strip(ast_strdupa(v->value));
  545. } else if (!strcasecmp(v->name, "Sec-WebSocket-Key")) {
  546. key = ast_strip(ast_strdupa(v->value));
  547. } else if (!strcasecmp(v->name, "Sec-WebSocket-Key1")) {
  548. key1 = ast_strip(ast_strdupa(v->value));
  549. } else if (!strcasecmp(v->name, "Sec-WebSocket-Key2")) {
  550. key2 = ast_strip(ast_strdupa(v->value));
  551. } else if (!strcasecmp(v->name, "Sec-WebSocket-Protocol")) {
  552. requested_protocols = ast_strip(ast_strdupa(v->value));
  553. protos = ast_strdupa(requested_protocols);
  554. } else if (!strcasecmp(v->name, "Sec-WebSocket-Version")) {
  555. if (sscanf(v->value, "%30d", &version) != 1) {
  556. version = 0;
  557. }
  558. }
  559. }
  560. /* If this is not a websocket upgrade abort */
  561. if (!upgrade || strcasecmp(upgrade, "websocket")) {
  562. ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - did not request WebSocket\n",
  563. ast_sockaddr_stringify(&ser->remote_address));
  564. ast_http_error(ser, 426, "Upgrade Required", NULL);
  565. return 0;
  566. } else if (ast_strlen_zero(requested_protocols)) {
  567. /* If there's only a single protocol registered, and the
  568. * client doesn't specify what protocol it's using, go ahead
  569. * and accept the connection */
  570. protocol_handler = one_protocol(server);
  571. if (!protocol_handler) {
  572. /* Multiple registered subprotocols; client must specify */
  573. ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols requested\n",
  574. ast_sockaddr_stringify(&ser->remote_address));
  575. websocket_bad_request(ser);
  576. return 0;
  577. }
  578. } else if (key1 && key2) {
  579. /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 and
  580. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 -- not currently supported*/
  581. ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '00/76' chosen\n",
  582. ast_sockaddr_stringify(&ser->remote_address));
  583. websocket_bad_request(ser);
  584. return 0;
  585. }
  586. /* Iterate through the requested protocols trying to find one that we have a handler for */
  587. while (!protocol_handler && (protocol = strsep(&requested_protocols, ","))) {
  588. protocol_handler = ao2_find(server->protocols, ast_strip(protocol), OBJ_KEY);
  589. }
  590. /* If no protocol handler exists bump this back to the requester */
  591. if (!protocol_handler) {
  592. ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols out of '%s' supported\n",
  593. ast_sockaddr_stringify(&ser->remote_address), protos);
  594. websocket_bad_request(ser);
  595. return 0;
  596. }
  597. /* Determine how to respond depending on the version */
  598. if (version == 7 || version == 8 || version == 13) {
  599. char base64[64];
  600. if (!key || strlen(key) + strlen(WEBSOCKET_GUID) + 1 > 8192) { /* no stack overflows please */
  601. websocket_bad_request(ser);
  602. ao2_ref(protocol_handler, -1);
  603. return 0;
  604. }
  605. if (ast_http_body_discard(ser)) {
  606. websocket_bad_request(ser);
  607. ao2_ref(protocol_handler, -1);
  608. return 0;
  609. }
  610. if (!(session = ao2_alloc(sizeof(*session), session_destroy_fn))) {
  611. ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted\n",
  612. ast_sockaddr_stringify(&ser->remote_address));
  613. websocket_bad_request(ser);
  614. ao2_ref(protocol_handler, -1);
  615. return 0;
  616. }
  617. session->timeout = AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
  618. fprintf(ser->f, "HTTP/1.1 101 Switching Protocols\r\n"
  619. "Upgrade: %s\r\n"
  620. "Connection: Upgrade\r\n"
  621. "Sec-WebSocket-Accept: %s\r\n",
  622. upgrade,
  623. websocket_combine_key(key, base64, sizeof(base64)));
  624. /* RFC 6455, Section 4.1:
  625. *
  626. * 6. If the response includes a |Sec-WebSocket-Protocol| header
  627. * field and this header field indicates the use of a
  628. * subprotocol that was not present in the client's handshake
  629. * (the server has indicated a subprotocol not requested by
  630. * the client), the client MUST _Fail the WebSocket
  631. * Connection_.
  632. */
  633. if (protocol) {
  634. fprintf(ser->f, "Sec-WebSocket-Protocol: %s\r\n",
  635. protocol);
  636. }
  637. fprintf(ser->f, "\r\n");
  638. fflush(ser->f);
  639. } else {
  640. /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 or completely unknown */
  641. ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '%d' chosen\n",
  642. ast_sockaddr_stringify(&ser->remote_address), version ? version : 75);
  643. websocket_bad_request(ser);
  644. ao2_ref(protocol_handler, -1);
  645. return 0;
  646. }
  647. /* Enable keepalive on all sessions so the underlying user does not have to */
  648. if (setsockopt(ser->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
  649. ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to enable keepalive\n",
  650. ast_sockaddr_stringify(&ser->remote_address));
  651. websocket_bad_request(ser);
  652. ao2_ref(session, -1);
  653. ao2_ref(protocol_handler, -1);
  654. return 0;
  655. }
  656. ast_verb(2, "WebSocket connection from '%s' for protocol '%s' accepted using version '%d'\n", ast_sockaddr_stringify(&ser->remote_address), protocol ? : "", version);
  657. /* Populate the session with all the needed details */
  658. session->f = ser->f;
  659. session->fd = ser->fd;
  660. ast_sockaddr_copy(&session->address, &ser->remote_address);
  661. session->opcode = -1;
  662. session->reconstruct = DEFAULT_RECONSTRUCTION_CEILING;
  663. session->secure = ser->ssl ? 1 : 0;
  664. /* Give up ownership of the socket and pass it to the protocol handler */
  665. ast_tcptls_stream_set_exclusive_input(ser->stream_cookie, 0);
  666. protocol_handler->callback(session, get_vars, headers);
  667. ao2_ref(protocol_handler, -1);
  668. /*
  669. * By dropping the FILE* and fd from the session the connection
  670. * won't get closed when the HTTP server cleans up because we
  671. * passed the connection to the protocol handler.
  672. */
  673. ser->f = NULL;
  674. ser->fd = -1;
  675. return 0;
  676. }
  677. static struct ast_http_uri websocketuri = {
  678. .callback = AST_OPTIONAL_API_NAME(ast_websocket_uri_cb),
  679. .description = "Asterisk HTTP WebSocket",
  680. .uri = "ws",
  681. .has_subtree = 0,
  682. .data = NULL,
  683. .key = __FILE__,
  684. };
  685. /*! \brief Simple echo implementation which echoes received text and binary frames */
  686. static void websocket_echo_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
  687. {
  688. int flags, res;
  689. ast_debug(1, "Entering WebSocket echo loop\n");
  690. if ((flags = fcntl(ast_websocket_fd(session), F_GETFL)) == -1) {
  691. goto end;
  692. }
  693. flags |= O_NONBLOCK;
  694. if (fcntl(ast_websocket_fd(session), F_SETFL, flags) == -1) {
  695. goto end;
  696. }
  697. while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
  698. char *payload;
  699. uint64_t payload_len;
  700. enum ast_websocket_opcode opcode;
  701. int fragmented;
  702. if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
  703. /* We err on the side of caution and terminate the session if any error occurs */
  704. ast_log(LOG_WARNING, "Read failure during WebSocket echo loop\n");
  705. break;
  706. }
  707. if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
  708. ast_websocket_write(session, opcode, payload, payload_len);
  709. } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
  710. break;
  711. } else {
  712. ast_debug(1, "Ignored WebSocket opcode %u\n", opcode);
  713. }
  714. }
  715. end:
  716. ast_debug(1, "Exitting WebSocket echo loop\n");
  717. ast_websocket_unref(session);
  718. }
  719. static int websocket_add_protocol_internal(const char *name, ast_websocket_callback callback)
  720. {
  721. struct ast_websocket_server *ws_server = websocketuri.data;
  722. if (!ws_server) {
  723. return -1;
  724. }
  725. return ast_websocket_server_add_protocol(ws_server, name, callback);
  726. }
  727. int AST_OPTIONAL_API_NAME(ast_websocket_add_protocol)(const char *name, ast_websocket_callback callback)
  728. {
  729. int res = websocket_add_protocol_internal(name, callback);
  730. if (res == 0) {
  731. ast_module_ref(ast_module_info->self);
  732. }
  733. return res;
  734. }
  735. static int websocket_remove_protocol_internal(const char *name, ast_websocket_callback callback)
  736. {
  737. struct ast_websocket_server *ws_server = websocketuri.data;
  738. if (!ws_server) {
  739. return -1;
  740. }
  741. return ast_websocket_server_remove_protocol(ws_server, name, callback);
  742. }
  743. int AST_OPTIONAL_API_NAME(ast_websocket_remove_protocol)(const char *name, ast_websocket_callback callback)
  744. {
  745. int res = websocket_remove_protocol_internal(name, callback);
  746. if (res == 0) {
  747. ast_module_unref(ast_module_info->self);
  748. }
  749. return res;
  750. }
  751. /*! \brief Parse the given uri into a path and remote address.
  752. *
  753. * Expected uri form: [ws[s]]://<host>[:port][/<path>]
  754. *
  755. * The returned host will contain the address and optional port while
  756. * path will contain everything after the address/port if included.
  757. */
  758. static int websocket_client_parse_uri(const char *uri, char **host, struct ast_str **path)
  759. {
  760. struct ast_uri *parsed_uri = ast_uri_parse_websocket(uri);
  761. if (!parsed_uri) {
  762. return -1;
  763. }
  764. *host = ast_uri_make_host_with_port(parsed_uri);
  765. if (ast_uri_path(parsed_uri) || ast_uri_query(parsed_uri)) {
  766. *path = ast_str_create(64);
  767. if (!*path) {
  768. ao2_ref(parsed_uri, -1);
  769. return -1;
  770. }
  771. if (ast_uri_path(parsed_uri)) {
  772. ast_str_set(path, 0, "%s", ast_uri_path(parsed_uri));
  773. }
  774. if (ast_uri_query(parsed_uri)) {
  775. ast_str_append(path, 0, "?%s", ast_uri_query(parsed_uri));
  776. }
  777. }
  778. ao2_ref(parsed_uri, -1);
  779. return 0;
  780. }
  781. static void websocket_client_args_destroy(void *obj)
  782. {
  783. struct ast_tcptls_session_args *args = obj;
  784. if (args->tls_cfg) {
  785. ast_free(args->tls_cfg->certfile);
  786. ast_free(args->tls_cfg->pvtfile);
  787. ast_free(args->tls_cfg->cipher);
  788. ast_free(args->tls_cfg->cafile);
  789. ast_free(args->tls_cfg->capath);
  790. ast_ssl_teardown(args->tls_cfg);
  791. }
  792. ast_free(args->tls_cfg);
  793. }
  794. static struct ast_tcptls_session_args *websocket_client_args_create(
  795. const char *host, struct ast_tls_config *tls_cfg,
  796. enum ast_websocket_result *result)
  797. {
  798. struct ast_sockaddr *addr;
  799. struct ast_tcptls_session_args *args = ao2_alloc(
  800. sizeof(*args), websocket_client_args_destroy);
  801. if (!args) {
  802. *result = WS_ALLOCATE_ERROR;
  803. return NULL;
  804. }
  805. args->accept_fd = -1;
  806. args->tls_cfg = tls_cfg;
  807. args->name = "websocket client";
  808. if (!ast_sockaddr_resolve(&addr, host, 0, 0)) {
  809. ast_log(LOG_ERROR, "Unable to resolve address %s\n",
  810. host);
  811. ao2_ref(args, -1);
  812. *result = WS_URI_RESOLVE_ERROR;
  813. return NULL;
  814. }
  815. ast_sockaddr_copy(&args->remote_address, addr);
  816. ast_free(addr);
  817. return args;
  818. }
  819. static char *websocket_client_create_key(void)
  820. {
  821. static int encoded_size = CLIENT_KEY_SIZE * 2 * sizeof(char) + 1;
  822. /* key is randomly selected 16-byte base64 encoded value */
  823. unsigned char key[CLIENT_KEY_SIZE + sizeof(long) - 1];
  824. char *encoded = ast_malloc(encoded_size);
  825. long i = 0;
  826. if (!encoded) {
  827. ast_log(LOG_ERROR, "Unable to allocate client websocket key\n");
  828. return NULL;
  829. }
  830. while (i < CLIENT_KEY_SIZE) {
  831. long num = ast_random();
  832. memcpy(key + i, &num, sizeof(long));
  833. i += sizeof(long);
  834. }
  835. ast_base64encode(encoded, key, CLIENT_KEY_SIZE, encoded_size);
  836. return encoded;
  837. }
  838. struct websocket_client {
  839. /*! host portion of client uri */
  840. char *host;
  841. /*! path for logical websocket connection */
  842. struct ast_str *resource_name;
  843. /*! unique key used during server handshaking */
  844. char *key;
  845. /*! container for registered protocols */
  846. char *protocols;
  847. /*! the protocol accepted by the server */
  848. char *accept_protocol;
  849. /*! websocket protocol version */
  850. int version;
  851. /*! tcptls connection arguments */
  852. struct ast_tcptls_session_args *args;
  853. /*! tcptls connection instance */
  854. struct ast_tcptls_session_instance *ser;
  855. };
  856. static void websocket_client_destroy(void *obj)
  857. {
  858. struct websocket_client *client = obj;
  859. ao2_cleanup(client->ser);
  860. ao2_cleanup(client->args);
  861. ast_free(client->accept_protocol);
  862. ast_free(client->protocols);
  863. ast_free(client->key);
  864. ast_free(client->resource_name);
  865. ast_free(client->host);
  866. }
  867. static struct ast_websocket * websocket_client_create(
  868. const char *uri, const char *protocols, struct ast_tls_config *tls_cfg,
  869. enum ast_websocket_result *result)
  870. {
  871. struct ast_websocket *ws = ao2_alloc(sizeof(*ws), session_destroy_fn);
  872. if (!ws) {
  873. ast_log(LOG_ERROR, "Unable to allocate websocket\n");
  874. *result = WS_ALLOCATE_ERROR;
  875. return NULL;
  876. }
  877. if (!(ws->client = ao2_alloc(
  878. sizeof(*ws->client), websocket_client_destroy))) {
  879. ast_log(LOG_ERROR, "Unable to allocate websocket client\n");
  880. *result = WS_ALLOCATE_ERROR;
  881. return NULL;
  882. }
  883. if (!(ws->client->key = websocket_client_create_key())) {
  884. ao2_ref(ws, -1);
  885. *result = WS_KEY_ERROR;
  886. return NULL;
  887. }
  888. if (websocket_client_parse_uri(
  889. uri, &ws->client->host, &ws->client->resource_name)) {
  890. ao2_ref(ws, -1);
  891. *result = WS_URI_PARSE_ERROR;
  892. return NULL;
  893. }
  894. if (!(ws->client->args = websocket_client_args_create(
  895. ws->client->host, tls_cfg, result))) {
  896. ao2_ref(ws, -1);
  897. return NULL;
  898. }
  899. ws->client->protocols = ast_strdup(protocols);
  900. ws->client->version = 13;
  901. ws->opcode = -1;
  902. ws->reconstruct = DEFAULT_RECONSTRUCTION_CEILING;
  903. return ws;
  904. }
  905. const char * AST_OPTIONAL_API_NAME(
  906. ast_websocket_client_accept_protocol)(struct ast_websocket *ws)
  907. {
  908. return ws->client->accept_protocol;
  909. }
  910. static enum ast_websocket_result websocket_client_handle_response_code(
  911. struct websocket_client *client, int response_code)
  912. {
  913. if (response_code <= 0) {
  914. return WS_INVALID_RESPONSE;
  915. }
  916. switch (response_code) {
  917. case 101:
  918. return 0;
  919. case 400:
  920. ast_log(LOG_ERROR, "Received response 400 - Bad Request "
  921. "- from %s\n", client->host);
  922. return WS_BAD_REQUEST;
  923. case 404:
  924. ast_log(LOG_ERROR, "Received response 404 - Request URL not "
  925. "found - from %s\n", client->host);
  926. return WS_URL_NOT_FOUND;
  927. }
  928. ast_log(LOG_ERROR, "Invalid HTTP response code %d from %s\n",
  929. response_code, client->host);
  930. return WS_INVALID_RESPONSE;
  931. }
  932. static enum ast_websocket_result websocket_client_handshake_get_response(
  933. struct websocket_client *client)
  934. {
  935. enum ast_websocket_result res;
  936. char buf[4096];
  937. char base64[64];
  938. int has_upgrade = 0;
  939. int has_connection = 0;
  940. int has_accept = 0;
  941. int has_protocol = 0;
  942. if (!fgets(buf, sizeof(buf), client->ser->f)) {
  943. ast_log(LOG_ERROR, "Unable to retrieve HTTP status line.");
  944. return WS_BAD_STATUS;
  945. }
  946. if ((res = websocket_client_handle_response_code(client,
  947. ast_http_response_status_line(
  948. buf, "HTTP/1.1", 101))) != WS_OK) {
  949. return res;
  950. }
  951. /* Ignoring line folding - assuming header field values are contained
  952. within a single line */
  953. while (fgets(buf, sizeof(buf), client->ser->f)) {
  954. char *name, *value;
  955. int parsed = ast_http_header_parse(buf, &name, &value);
  956. if (parsed < 0) {
  957. break;
  958. }
  959. if (parsed > 0) {
  960. continue;
  961. }
  962. if (!has_upgrade &&
  963. (has_upgrade = ast_http_header_match(
  964. name, "upgrade", value, "websocket")) < 0) {
  965. return WS_HEADER_MISMATCH;
  966. } else if (!has_connection &&
  967. (has_connection = ast_http_header_match(
  968. name, "connection", value, "upgrade")) < 0) {
  969. return WS_HEADER_MISMATCH;
  970. } else if (!has_accept &&
  971. (has_accept = ast_http_header_match(
  972. name, "sec-websocket-accept", value,
  973. websocket_combine_key(
  974. client->key, base64, sizeof(base64)))) < 0) {
  975. return WS_HEADER_MISMATCH;
  976. } else if (!has_protocol &&
  977. (has_protocol = ast_http_header_match_in(
  978. name, "sec-websocket-protocol", value, client->protocols))) {
  979. if (has_protocol < 0) {
  980. return WS_HEADER_MISMATCH;
  981. }
  982. client->accept_protocol = ast_strdup(value);
  983. } else if (!strcasecmp(name, "sec-websocket-extensions")) {
  984. ast_log(LOG_ERROR, "Extensions received, but not "
  985. "supported by client\n");
  986. return WS_NOT_SUPPORTED;
  987. }
  988. }
  989. return has_upgrade && has_connection && has_accept ?
  990. WS_OK : WS_HEADER_MISSING;
  991. }
  992. static enum ast_websocket_result websocket_client_handshake(
  993. struct websocket_client *client)
  994. {
  995. char protocols[100] = "";
  996. if (!ast_strlen_zero(client->protocols)) {
  997. sprintf(protocols, "Sec-WebSocket-Protocol: %s\r\n",
  998. client->protocols);
  999. }
  1000. if (fprintf(client->ser->f,
  1001. "GET /%s HTTP/1.1\r\n"
  1002. "Sec-WebSocket-Version: %d\r\n"
  1003. "Upgrade: websocket\r\n"
  1004. "Connection: Upgrade\r\n"
  1005. "Host: %s\r\n"
  1006. "Sec-WebSocket-Key: %s\r\n"
  1007. "%s\r\n",
  1008. client->resource_name ? ast_str_buffer(client->resource_name) : "",
  1009. client->version,
  1010. client->host,
  1011. client->key,
  1012. protocols) < 0) {
  1013. ast_log(LOG_ERROR, "Failed to send handshake.\n");
  1014. return WS_WRITE_ERROR;
  1015. }
  1016. /* wait for a response before doing anything else */
  1017. return websocket_client_handshake_get_response(client);
  1018. }
  1019. static enum ast_websocket_result websocket_client_connect(struct ast_websocket *ws)
  1020. {
  1021. enum ast_websocket_result res;
  1022. /* create and connect the client - note client_start
  1023. releases the session instance on failure */
  1024. if (!(ws->client->ser = ast_tcptls_client_start(
  1025. ast_tcptls_client_create(ws->client->args)))) {
  1026. return WS_CLIENT_START_ERROR;
  1027. }
  1028. if ((res = websocket_client_handshake(ws->client)) != WS_OK) {
  1029. ao2_ref(ws->client->ser, -1);
  1030. ws->client->ser = NULL;
  1031. return res;
  1032. }
  1033. ws->f = ws->client->ser->f;
  1034. ws->fd = ws->client->ser->fd;
  1035. ws->secure = ws->client->ser->ssl ? 1 : 0;
  1036. ast_sockaddr_copy(&ws->address, &ws->client->ser->remote_address);
  1037. return WS_OK;
  1038. }
  1039. struct ast_websocket *AST_OPTIONAL_API_NAME(ast_websocket_client_create)
  1040. (const char *uri, const char *protocols, struct ast_tls_config *tls_cfg,
  1041. enum ast_websocket_result *result)
  1042. {
  1043. struct ast_websocket *ws = websocket_client_create(
  1044. uri, protocols, tls_cfg, result);
  1045. if (!ws) {
  1046. return NULL;
  1047. }
  1048. if ((*result = websocket_client_connect(ws)) != WS_OK) {
  1049. ao2_ref(ws, -1);
  1050. return NULL;
  1051. }
  1052. return ws;
  1053. }
  1054. int AST_OPTIONAL_API_NAME(ast_websocket_read_string)
  1055. (struct ast_websocket *ws, char **buf)
  1056. {
  1057. char *payload;
  1058. uint64_t payload_len;
  1059. enum ast_websocket_opcode opcode;
  1060. int fragmented = 1;
  1061. while (fragmented) {
  1062. if (ast_websocket_read(ws, &payload, &payload_len,
  1063. &opcode, &fragmented)) {
  1064. ast_log(LOG_ERROR, "Client WebSocket string read - "
  1065. "error reading string data\n");
  1066. return -1;
  1067. }
  1068. if (opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
  1069. continue;
  1070. }
  1071. if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
  1072. return -1;
  1073. }
  1074. if (opcode != AST_WEBSOCKET_OPCODE_TEXT) {
  1075. ast_log(LOG_ERROR, "Client WebSocket string read - "
  1076. "non string data received\n");
  1077. return -1;
  1078. }
  1079. }
  1080. if (!(*buf = ast_malloc(payload_len + 1))) {
  1081. return -1;
  1082. }
  1083. ast_copy_string(*buf, payload, payload_len + 1);
  1084. return payload_len + 1;
  1085. }
  1086. int AST_OPTIONAL_API_NAME(ast_websocket_write_string)
  1087. (struct ast_websocket *ws, const char *buf)
  1088. {
  1089. return ast_websocket_write(ws, AST_WEBSOCKET_OPCODE_TEXT,
  1090. (char *)buf, strlen(buf));
  1091. }
  1092. static int load_module(void)
  1093. {
  1094. websocketuri.data = websocket_server_internal_create();
  1095. if (!websocketuri.data) {
  1096. return AST_MODULE_LOAD_FAILURE;
  1097. }
  1098. ast_http_uri_link(&websocketuri);
  1099. websocket_add_protocol_internal("echo", websocket_echo_callback);
  1100. return 0;
  1101. }
  1102. static int unload_module(void)
  1103. {
  1104. ast_websocket_remove_protocol("echo", websocket_echo_callback);
  1105. ast_http_uri_unlink(&websocketuri);
  1106. ao2_ref(websocketuri.data, -1);
  1107. websocketuri.data = NULL;
  1108. return 0;
  1109. }
  1110. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "HTTP WebSocket Support",
  1111. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  1112. .load = load_module,
  1113. .unload = unload_module,
  1114. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  1115. );