res_pjsip_outbound_publish.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2014, 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. /*** MODULEINFO
  19. <depend>pjproject</depend>
  20. <depend>res_pjsip</depend>
  21. <support_level>core</support_level>
  22. ***/
  23. #include "asterisk.h"
  24. #include <pjsip.h>
  25. #include <pjsip_simple.h>
  26. #include "asterisk/res_pjsip.h"
  27. #include "asterisk/res_pjsip_outbound_publish.h"
  28. #include "asterisk/module.h"
  29. #include "asterisk/taskprocessor.h"
  30. #include "asterisk/datastore.h"
  31. /*** DOCUMENTATION
  32. <configInfo name="res_pjsip_outbound_publish" language="en_US">
  33. <synopsis>SIP resource for outbound publish</synopsis>
  34. <description><para>
  35. <emphasis>Outbound Publish</emphasis>
  36. </para>
  37. <para>This module allows <literal>res_pjsip</literal> to publish to other SIP servers.</para>
  38. </description>
  39. <configFile name="pjsip.conf">
  40. <configObject name="outbound-publish">
  41. <synopsis>The configuration for outbound publish</synopsis>
  42. <description><para>
  43. Publish is <emphasis>COMPLETELY</emphasis> separate from the rest of
  44. <literal>pjsip.conf</literal>. A minimal configuration consists of
  45. setting a <literal>server_uri</literal> and <literal>event</literal>.
  46. </para></description>
  47. <configOption name="expiration" default="3600">
  48. <synopsis>Expiration time for publications in seconds</synopsis>
  49. </configOption>
  50. <configOption name="outbound_auth" default="">
  51. <synopsis>Authentication object to be used for outbound publishes.</synopsis>
  52. </configOption>
  53. <configOption name="outbound_proxy" default="">
  54. <synopsis>SIP URI of the outbound proxy used to send publishes</synopsis>
  55. </configOption>
  56. <configOption name="server_uri">
  57. <synopsis>SIP URI of the server and entity to publish to</synopsis>
  58. <description><para>
  59. This is the URI at which to find the entity and server to send the outbound PUBLISH to.
  60. This URI is used as the request URI of the outbound PUBLISH request from Asterisk.
  61. </para></description>
  62. </configOption>
  63. <configOption name="from_uri">
  64. <synopsis>SIP URI to use in the From header</synopsis>
  65. <description><para>
  66. This is the URI that will be placed into the From header of outgoing PUBLISH
  67. messages. If no URI is specified then the URI provided in <literal>server_uri</literal>
  68. will be used.
  69. </para></description>
  70. </configOption>
  71. <configOption name="to_uri">
  72. <synopsis>SIP URI to use in the To header</synopsis>
  73. <description><para>
  74. This is the URI that will be placed into the To header of outgoing PUBLISH
  75. messages. If no URI is specified then the URI provided in <literal>server_uri</literal>
  76. will be used.
  77. </para></description>
  78. </configOption>
  79. <configOption name="event" default="">
  80. <synopsis>Event type of the PUBLISH.</synopsis>
  81. </configOption>
  82. <configOption name="max_auth_attempts" default="5">
  83. <synopsis>Maximum number of authentication attempts before stopping the publication.</synopsis>
  84. </configOption>
  85. <configOption name="type">
  86. <synopsis>Must be of type 'outbound-publish'.</synopsis>
  87. </configOption>
  88. </configObject>
  89. </configFile>
  90. </configInfo>
  91. ***/
  92. /*! \brief Queued outbound publish message */
  93. struct sip_outbound_publish_message {
  94. /*! \brief Optional body */
  95. struct ast_sip_body body;
  96. /*! \brief Linked list information */
  97. AST_LIST_ENTRY(sip_outbound_publish_message) entry;
  98. /*! \brief Extra space for body contents */
  99. char body_contents[0];
  100. };
  101. /*! \brief Outbound publish client state information (persists for lifetime that publish should exist) */
  102. struct ast_sip_outbound_publish_client {
  103. /*! \brief Underlying publish client */
  104. pjsip_publishc *client;
  105. /*! \brief Timer entry for refreshing publish */
  106. pj_timer_entry timer;
  107. /*! \brief Publisher datastores set up by handlers */
  108. struct ao2_container *datastores;
  109. /*! \brief The number of auth attempts done */
  110. unsigned int auth_attempts;
  111. /*! \brief Queue of outgoing publish messages to send*/
  112. AST_LIST_HEAD_NOLOCK(, sip_outbound_publish_message) queue;
  113. /*! \brief The message currently being sent */
  114. struct sip_outbound_publish_message *sending;
  115. /*! \brief Publish client has been fully started and event type informed */
  116. unsigned int started;
  117. /*! \brief Publish client should be destroyed */
  118. unsigned int destroy;
  119. };
  120. /*! \brief Outbound publish information */
  121. struct ast_sip_outbound_publish {
  122. /*! \brief Sorcery object details */
  123. SORCERY_OBJECT(details);
  124. /*! \brief Stringfields */
  125. AST_DECLARE_STRING_FIELDS(
  126. /*! \brief URI for the entity and server */
  127. AST_STRING_FIELD(server_uri);
  128. /*! \brief URI for the From header */
  129. AST_STRING_FIELD(from_uri);
  130. /*! \brief URI for the To header */
  131. AST_STRING_FIELD(to_uri);
  132. /*! \brief Outbound proxy to use */
  133. AST_STRING_FIELD(outbound_proxy);
  134. /*! \brief The event type to publish */
  135. AST_STRING_FIELD(event);
  136. );
  137. /*! \brief Requested expiration time */
  138. unsigned int expiration;
  139. /*! \brief Maximum number of auth attempts before stopping the publish client */
  140. unsigned int max_auth_attempts;
  141. /*! \brief Configured authentication credentials */
  142. struct ast_sip_auth_vector outbound_auths;
  143. /*! \brief Outbound publish state */
  144. struct ast_sip_outbound_publish_client *state;
  145. };
  146. AST_RWLIST_HEAD_STATIC(publisher_handlers, ast_sip_event_publisher_handler);
  147. /*! \brief Container of currently active publish clients */
  148. static AO2_GLOBAL_OBJ_STATIC(active);
  149. static void sub_add_handler(struct ast_sip_event_publisher_handler *handler)
  150. {
  151. AST_RWLIST_INSERT_TAIL(&publisher_handlers, handler, next);
  152. ast_module_ref(ast_module_info->self);
  153. }
  154. static struct ast_sip_event_publisher_handler *find_publisher_handler_for_event_name(const char *event_name)
  155. {
  156. struct ast_sip_event_publisher_handler *iter;
  157. AST_RWLIST_TRAVERSE(&publisher_handlers, iter, next) {
  158. if (!strcmp(iter->event_name, event_name)) {
  159. break;
  160. }
  161. }
  162. return iter;
  163. }
  164. /*! \brief Helper function which cancels the refresh timer on a client */
  165. static void cancel_publish_refresh(struct ast_sip_outbound_publish_client *client)
  166. {
  167. if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &client->timer)) {
  168. /* The timer was successfully cancelled, drop the refcount of the client */
  169. ao2_ref(client, -1);
  170. }
  171. }
  172. /*! \brief Helper function which sets up the timer to send publication */
  173. static void schedule_publish_refresh(struct ast_sip_outbound_publish *publish, pjsip_rx_data *rdata)
  174. {
  175. pj_time_val delay = { .sec = 0, };
  176. pjsip_expires_hdr *expires;
  177. cancel_publish_refresh(publish->state);
  178. /* Determine when we should refresh - we favor the Expires header if possible */
  179. expires = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL);
  180. if (expires) {
  181. delay.sec = expires->ivalue - PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH;
  182. }
  183. if (publish->expiration && ((delay.sec > publish->expiration) || !delay.sec)) {
  184. delay.sec = publish->expiration;
  185. }
  186. if (delay.sec < PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH) {
  187. delay.sec = PJSIP_PUBLISHC_DELAY_BEFORE_REFRESH;
  188. }
  189. ao2_ref(publish->state, +1);
  190. if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &publish->state->timer, &delay) != PJ_SUCCESS) {
  191. ast_log(LOG_WARNING, "Failed to pass timed publish refresh to scheduler\n");
  192. ao2_ref(publish->state, -1);
  193. }
  194. }
  195. /*! \brief Publish client timer callback function */
  196. static void sip_outbound_publish_timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
  197. {
  198. struct ast_sip_outbound_publish_client *client = entry->user_data;
  199. ao2_lock(client);
  200. if (AST_LIST_EMPTY(&client->queue)) {
  201. /* If there are no outstanding messages send an empty PUBLISH message so our publication doesn't expire */
  202. ast_sip_publish_client_send(client, NULL);
  203. }
  204. ao2_unlock(client);
  205. ao2_ref(client, -1);
  206. }
  207. /*! \brief Task for cancelling a refresh timer */
  208. static int cancel_refresh_timer_task(void *data)
  209. {
  210. struct ast_sip_outbound_publish_client *state = data;
  211. cancel_publish_refresh(state);
  212. ao2_ref(state, -1);
  213. return 0;
  214. }
  215. /*! \brief Task for sending an unpublish */
  216. static int send_unpublish_task(void *data)
  217. {
  218. struct ast_sip_outbound_publish_client *state = data;
  219. pjsip_tx_data *tdata;
  220. if (pjsip_publishc_unpublish(state->client, &tdata) == PJ_SUCCESS) {
  221. pjsip_publishc_send(state->client, tdata);
  222. }
  223. ao2_ref(state, -1);
  224. return 0;
  225. }
  226. /*! \brief Helper function which starts or stops publish clients when applicable */
  227. static void sip_outbound_publish_synchronize(struct ast_sip_event_publisher_handler *removed)
  228. {
  229. RAII_VAR(struct ao2_container *, publishes, ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "outbound-publish", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL), ao2_cleanup);
  230. struct ao2_iterator i;
  231. struct ast_sip_outbound_publish *publish;
  232. if (!publishes) {
  233. return;
  234. }
  235. i = ao2_iterator_init(publishes, 0);
  236. while ((publish = ao2_iterator_next(&i))) {
  237. struct ast_sip_event_publisher_handler *handler = find_publisher_handler_for_event_name(publish->event);
  238. if (!publish->state->started) {
  239. /* If the publisher client has not yet been started try to start it */
  240. if (!handler) {
  241. ast_debug(2, "Could not find handler for event '%s' for outbound publish client '%s'\n",
  242. publish->event, ast_sorcery_object_get_id(publish));
  243. } else if (handler->start_publishing(publish, publish->state)) {
  244. ast_log(LOG_ERROR, "Failed to start outbound publish with event '%s' for client '%s'\n",
  245. publish->event, ast_sorcery_object_get_id(publish));
  246. } else {
  247. publish->state->started = 1;
  248. }
  249. } else if (publish->state->started && !handler && removed && !strcmp(publish->event, removed->event_name)) {
  250. /* If the publisher client has been started but it is going away stop it */
  251. removed->stop_publishing(publish->state);
  252. publish->state->started = 0;
  253. if (ast_sip_push_task(NULL, cancel_refresh_timer_task, ao2_bump(publish->state))) {
  254. ast_log(LOG_WARNING, "Could not stop refresh timer on client '%s'\n",
  255. ast_sorcery_object_get_id(publish));
  256. ao2_ref(publish->state, -1);
  257. }
  258. }
  259. ao2_ref(publish, -1);
  260. }
  261. ao2_iterator_destroy(&i);
  262. }
  263. struct ast_sip_outbound_publish_client *ast_sip_publish_client_get(const char *name)
  264. {
  265. RAII_VAR(struct ast_sip_outbound_publish *, publish, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "outbound-publish", name), ao2_cleanup);
  266. if (!publish) {
  267. return NULL;
  268. }
  269. return ao2_bump(publish->state);
  270. }
  271. int ast_sip_register_event_publisher_handler(struct ast_sip_event_publisher_handler *handler)
  272. {
  273. struct ast_sip_event_publisher_handler *existing;
  274. SCOPED_LOCK(lock, &publisher_handlers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  275. if (!handler->start_publishing || !handler->stop_publishing) {
  276. ast_log(LOG_ERROR, "Handler does not implement required callbacks. Cannot register\n");
  277. return -1;
  278. } else if (ast_strlen_zero(handler->event_name)) {
  279. ast_log(LOG_ERROR, "No event package specified for event publisher handler. Cannot register\n");
  280. return -1;
  281. }
  282. existing = find_publisher_handler_for_event_name(handler->event_name);
  283. if (existing) {
  284. ast_log(LOG_ERROR, "Unable to register event publisher handler for event %s. "
  285. "A handler is already registered\n", handler->event_name);
  286. return -1;
  287. }
  288. sub_add_handler(handler);
  289. sip_outbound_publish_synchronize(NULL);
  290. return 0;
  291. }
  292. void ast_sip_unregister_event_publisher_handler(struct ast_sip_event_publisher_handler *handler)
  293. {
  294. struct ast_sip_event_publisher_handler *iter;
  295. SCOPED_LOCK(lock, &publisher_handlers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  296. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&publisher_handlers, iter, next) {
  297. if (handler == iter) {
  298. AST_RWLIST_REMOVE_CURRENT(next);
  299. ast_module_unref(ast_module_info->self);
  300. break;
  301. }
  302. }
  303. AST_RWLIST_TRAVERSE_SAFE_END;
  304. sip_outbound_publish_synchronize(handler);
  305. }
  306. /*! \brief Destructor function for publish information */
  307. static void sip_outbound_publish_destroy(void *obj)
  308. {
  309. struct ast_sip_outbound_publish *publish = obj;
  310. SCOPED_LOCK(lock, &publisher_handlers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
  311. struct ast_sip_event_publisher_handler *handler = find_publisher_handler_for_event_name(publish->event);
  312. if (handler) {
  313. handler->stop_publishing(publish->state);
  314. }
  315. if (publish->state) {
  316. cancel_publish_refresh(publish->state);
  317. ao2_ref(publish->state, -1);
  318. }
  319. ast_sip_auth_vector_destroy(&publish->outbound_auths);
  320. ast_string_field_free_memory(publish);
  321. }
  322. /*! \brief Allocator function for publish information */
  323. static void *sip_outbound_publish_alloc(const char *name)
  324. {
  325. struct ast_sip_outbound_publish *publish = ast_sorcery_generic_alloc(sizeof(*publish),
  326. sip_outbound_publish_destroy);
  327. if (!publish || ast_string_field_init(publish, 256)) {
  328. ao2_cleanup(publish);
  329. return NULL;
  330. }
  331. return publish;
  332. }
  333. static void sip_outbound_publish_datastore_destroy(void *obj)
  334. {
  335. struct ast_datastore *datastore = obj;
  336. /* Using the destroy function (if present) destroy the data */
  337. if (datastore->info->destroy != NULL && datastore->data != NULL) {
  338. datastore->info->destroy(datastore->data);
  339. datastore->data = NULL;
  340. }
  341. ast_free((void *) datastore->uid);
  342. datastore->uid = NULL;
  343. }
  344. struct ast_datastore *ast_sip_publish_client_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
  345. {
  346. RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
  347. const char *uid_ptr = uid;
  348. char uuid_buf[AST_UUID_STR_LEN];
  349. if (!info) {
  350. return NULL;
  351. }
  352. datastore = ao2_alloc(sizeof(*datastore), sip_outbound_publish_datastore_destroy);
  353. if (!datastore) {
  354. return NULL;
  355. }
  356. datastore->info = info;
  357. if (ast_strlen_zero(uid)) {
  358. /* They didn't provide an ID so we'll provide one ourself */
  359. uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
  360. }
  361. datastore->uid = ast_strdup(uid_ptr);
  362. if (!datastore->uid) {
  363. return NULL;
  364. }
  365. ao2_ref(datastore, +1);
  366. return datastore;
  367. }
  368. int ast_sip_publish_client_add_datastore(struct ast_sip_outbound_publish_client *client,
  369. struct ast_datastore *datastore)
  370. {
  371. ast_assert(datastore != NULL);
  372. ast_assert(datastore->info != NULL);
  373. ast_assert(!ast_strlen_zero(datastore->uid));
  374. if (!ao2_link(client->datastores, datastore)) {
  375. return -1;
  376. }
  377. return 0;
  378. }
  379. struct ast_datastore *ast_sip_publish_client_get_datastore(struct ast_sip_outbound_publish_client *client,
  380. const char *name)
  381. {
  382. return ao2_find(client->datastores, name, OBJ_SEARCH_KEY);
  383. }
  384. void ast_sip_publish_client_remove_datastore(struct ast_sip_outbound_publish_client *client,
  385. const char *name)
  386. {
  387. ao2_find(client->datastores, name, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
  388. }
  389. static int sip_publish_client_service_queue(void *data)
  390. {
  391. RAII_VAR(struct ast_sip_outbound_publish_client *, client, data, ao2_cleanup);
  392. SCOPED_AO2LOCK(lock, client);
  393. struct sip_outbound_publish_message *message;
  394. pjsip_tx_data *tdata;
  395. pj_status_t status;
  396. if (client->destroy || client->sending || !(message = AST_LIST_FIRST(&client->queue))) {
  397. return 0;
  398. }
  399. if (pjsip_publishc_publish(client->client, PJ_FALSE, &tdata) != PJ_SUCCESS) {
  400. goto fatal;
  401. }
  402. if (!ast_strlen_zero(message->body.type) && !ast_strlen_zero(message->body.subtype) &&
  403. ast_sip_add_body(tdata, &message->body)) {
  404. pjsip_tx_data_dec_ref(tdata);
  405. goto fatal;
  406. }
  407. status = pjsip_publishc_send(client->client, tdata);
  408. if (status == PJ_EBUSY) {
  409. /* We attempted to send the message but something else got there first */
  410. goto service;
  411. } else if (status != PJ_SUCCESS) {
  412. goto fatal;
  413. }
  414. client->sending = message;
  415. return 0;
  416. fatal:
  417. AST_LIST_REMOVE_HEAD(&client->queue, entry);
  418. ast_free(message);
  419. service:
  420. if (ast_sip_push_task(NULL, sip_publish_client_service_queue, ao2_bump(client))) {
  421. ao2_ref(client, -1);
  422. }
  423. return -1;
  424. }
  425. int ast_sip_publish_client_send(struct ast_sip_outbound_publish_client *client,
  426. const struct ast_sip_body *body)
  427. {
  428. SCOPED_AO2LOCK(lock, client);
  429. struct sip_outbound_publish_message *message;
  430. size_t type_len = 0, subtype_len = 0, body_text_len = 0;
  431. int res;
  432. if (!client->client) {
  433. return -1;
  434. }
  435. /* If a body is present we need more space for the contents of it */
  436. if (body) {
  437. type_len = strlen(body->type) + 1;
  438. subtype_len = strlen(body->subtype) + 1;
  439. body_text_len = strlen(body->body_text) + 1;
  440. }
  441. message = ast_calloc(1, sizeof(*message) + type_len + subtype_len + body_text_len);
  442. if (!message) {
  443. return -1;
  444. }
  445. if (body) {
  446. char *dst = message->body_contents;
  447. message->body.type = strcpy(dst, body->type);
  448. dst += type_len;
  449. message->body.subtype = strcpy(dst, body->subtype);
  450. dst += subtype_len;
  451. message->body.body_text = strcpy(dst, body->body_text);
  452. }
  453. AST_LIST_INSERT_TAIL(&client->queue, message, entry);
  454. res = ast_sip_push_task(NULL, sip_publish_client_service_queue, ao2_bump(client));
  455. if (res) {
  456. ao2_ref(client, -1);
  457. }
  458. return res;
  459. }
  460. /*! \brief Destructor function for publish state */
  461. static void sip_outbound_publish_client_destroy(void *obj)
  462. {
  463. struct ast_sip_outbound_publish_client *state = obj;
  464. struct sip_outbound_publish_message *message;
  465. /* You might be tempted to think "the publish client isn't being destroyed" but it actually is - just elsewhere */
  466. while ((message = AST_LIST_REMOVE_HEAD(&state->queue, entry))) {
  467. ast_free(message);
  468. }
  469. ao2_cleanup(state->datastores);
  470. }
  471. /*!
  472. * \internal
  473. * \brief Check if a publish can be reused
  474. *
  475. * This checks if the existing outbound publish's configuration differs from a newly-applied
  476. * outbound publish.
  477. *
  478. * \param existing The pre-existing outbound publish
  479. * \param applied The newly-created publish
  480. */
  481. static int can_reuse_publish(struct ast_sip_outbound_publish *existing, struct ast_sip_outbound_publish *applied)
  482. {
  483. int i;
  484. if (strcmp(existing->server_uri, applied->server_uri) || strcmp(existing->from_uri, applied->from_uri) ||
  485. strcmp(existing->to_uri, applied->to_uri) || strcmp(existing->outbound_proxy, applied->outbound_proxy) ||
  486. strcmp(existing->event, applied->event) ||
  487. AST_VECTOR_SIZE(&existing->outbound_auths) != AST_VECTOR_SIZE(&applied->outbound_auths)) {
  488. return 0;
  489. }
  490. for (i = 0; i < AST_VECTOR_SIZE(&existing->outbound_auths); ++i) {
  491. if (strcmp(AST_VECTOR_GET(&existing->outbound_auths, i), AST_VECTOR_GET(&applied->outbound_auths, i))) {
  492. return 0;
  493. }
  494. }
  495. return 1;
  496. }
  497. static void sip_outbound_publish_callback(struct pjsip_publishc_cbparam *param);
  498. /*! \brief Helper function that allocates a pjsip publish client and configures it */
  499. static int sip_outbound_publish_client_alloc(void *data)
  500. {
  501. struct ast_sip_outbound_publish *publish = data;
  502. pjsip_publishc_opt opt = {
  503. .queue_request = PJ_FALSE,
  504. };
  505. pj_str_t event, server_uri, to_uri, from_uri;
  506. pj_status_t status;
  507. if (publish->state->client) {
  508. return 0;
  509. } else if (pjsip_publishc_create(ast_sip_get_pjsip_endpoint(), &opt, ao2_bump(publish), sip_outbound_publish_callback,
  510. &publish->state->client) != PJ_SUCCESS) {
  511. ao2_ref(publish, -1);
  512. return -1;
  513. }
  514. if (!ast_strlen_zero(publish->outbound_proxy)) {
  515. pjsip_route_hdr route_set, *route;
  516. static const pj_str_t ROUTE_HNAME = { "Route", 5 };
  517. pj_list_init(&route_set);
  518. if (!(route = pjsip_parse_hdr(pjsip_publishc_get_pool(publish->state->client), &ROUTE_HNAME,
  519. (char*)publish->outbound_proxy, strlen(publish->outbound_proxy), NULL))) {
  520. pjsip_publishc_destroy(publish->state->client);
  521. return -1;
  522. }
  523. pj_list_insert_nodes_before(&route_set, route);
  524. pjsip_publishc_set_route_set(publish->state->client, &route_set);
  525. }
  526. pj_cstr(&event, publish->event);
  527. pj_cstr(&server_uri, publish->server_uri);
  528. pj_cstr(&to_uri, S_OR(publish->to_uri, publish->server_uri));
  529. pj_cstr(&from_uri, S_OR(publish->from_uri, publish->server_uri));
  530. status = pjsip_publishc_init(publish->state->client, &event, &server_uri, &from_uri, &to_uri,
  531. publish->expiration);
  532. if (status == PJSIP_EINVALIDURI) {
  533. pj_pool_t *pool;
  534. pj_str_t tmp;
  535. pjsip_uri *uri;
  536. pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "URI Validation", 256, 256);
  537. if (!pool) {
  538. ast_log(LOG_ERROR, "Could not create pool for URI validation on outbound publish '%s'\n",
  539. ast_sorcery_object_get_id(publish));
  540. pjsip_publishc_destroy(publish->state->client);
  541. return -1;
  542. }
  543. pj_strdup2_with_null(pool, &tmp, publish->server_uri);
  544. uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
  545. if (!uri) {
  546. ast_log(LOG_ERROR, "Invalid server URI '%s' specified on outbound publish '%s'\n",
  547. publish->server_uri, ast_sorcery_object_get_id(publish));
  548. }
  549. if (!ast_strlen_zero(publish->to_uri)) {
  550. pj_strdup2_with_null(pool, &tmp, publish->to_uri);
  551. uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
  552. if (!uri) {
  553. ast_log(LOG_ERROR, "Invalid to URI '%s' specified on outbound publish '%s'\n",
  554. publish->to_uri, ast_sorcery_object_get_id(publish));
  555. }
  556. }
  557. if (!ast_strlen_zero(publish->from_uri)) {
  558. pj_strdup2_with_null(pool, &tmp, publish->from_uri);
  559. uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
  560. if (!uri) {
  561. ast_log(LOG_ERROR, "Invalid from URI '%s' specified on outbound publish '%s'\n",
  562. publish->from_uri, ast_sorcery_object_get_id(publish));
  563. }
  564. }
  565. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  566. pjsip_publishc_destroy(publish->state->client);
  567. return -1;
  568. } else if (status != PJ_SUCCESS) {
  569. pjsip_publishc_destroy(publish->state->client);
  570. return -1;
  571. }
  572. return 0;
  573. }
  574. /*! \brief Callback function for publish client responses */
  575. static void sip_outbound_publish_callback(struct pjsip_publishc_cbparam *param)
  576. {
  577. RAII_VAR(struct ast_sip_outbound_publish *, publish, ao2_bump(param->token), ao2_cleanup);
  578. SCOPED_AO2LOCK(lock, publish->state);
  579. pjsip_tx_data *tdata;
  580. if (publish->state->destroy) {
  581. if (publish->state->sending) {
  582. publish->state->sending = NULL;
  583. if (!ast_sip_push_task(NULL, send_unpublish_task, ao2_bump(publish->state))) {
  584. return;
  585. }
  586. ast_log(LOG_WARNING, "Could not send unpublish message on outbound publish '%s'\n",
  587. ast_sorcery_object_get_id(publish));
  588. ao2_ref(publish->state, -1);
  589. }
  590. /* Once the destroy is called this callback will not get called any longer, so drop the publish ref */
  591. pjsip_publishc_destroy(publish->state->client);
  592. ao2_ref(publish, -1);
  593. return;
  594. }
  595. if (param->code == 401 || param->code == 407) {
  596. if (!ast_sip_create_request_with_auth(&publish->outbound_auths,
  597. param->rdata, pjsip_rdata_get_tsx(param->rdata), &tdata)) {
  598. pjsip_publishc_send(publish->state->client, tdata);
  599. }
  600. publish->state->auth_attempts++;
  601. if (publish->state->auth_attempts == publish->max_auth_attempts) {
  602. pjsip_publishc_destroy(publish->state->client);
  603. publish->state->client = NULL;
  604. ast_log(LOG_ERROR, "Reached maximum number of PUBLISH authentication attempts on outbound publish '%s'\n",
  605. ast_sorcery_object_get_id(publish));
  606. goto end;
  607. }
  608. return;
  609. }
  610. publish->state->auth_attempts = 0;
  611. if (param->code == 412) {
  612. pjsip_publishc_destroy(publish->state->client);
  613. publish->state->client = NULL;
  614. if (sip_outbound_publish_client_alloc(publish)) {
  615. ast_log(LOG_ERROR, "Failed to create a new outbound publish client for '%s' on 412 response\n",
  616. ast_sorcery_object_get_id(publish));
  617. goto end;
  618. }
  619. /* Setting this to NULL will cause a new PUBLISH to get created and sent for the same underlying body */
  620. publish->state->sending = NULL;
  621. } else if (param->code == 423) {
  622. /* Update the expiration with the new expiration time if available */
  623. pjsip_expires_hdr *expires;
  624. expires = pjsip_msg_find_hdr(param->rdata->msg_info.msg, PJSIP_H_MIN_EXPIRES, NULL);
  625. if (!expires || !expires->ivalue) {
  626. ast_log(LOG_ERROR, "Received 423 response on outbound publish '%s' without a Min-Expires header\n",
  627. ast_sorcery_object_get_id(publish));
  628. pjsip_publishc_destroy(publish->state->client);
  629. publish->state->client = NULL;
  630. goto end;
  631. }
  632. pjsip_publishc_update_expires(publish->state->client, expires->ivalue);
  633. publish->state->sending = NULL;
  634. } else if (publish->state->sending) {
  635. /* Remove the message currently being sent so that when the queue is serviced another will get sent */
  636. AST_LIST_REMOVE_HEAD(&publish->state->queue, entry);
  637. ast_free(publish->state->sending);
  638. publish->state->sending = NULL;
  639. }
  640. if (AST_LIST_EMPTY(&publish->state->queue)) {
  641. schedule_publish_refresh(publish, param->rdata);
  642. }
  643. end:
  644. if (!publish->state->client) {
  645. struct sip_outbound_publish_message *message;
  646. while ((message = AST_LIST_REMOVE_HEAD(&publish->state->queue, entry))) {
  647. ast_free(message);
  648. }
  649. } else {
  650. if (ast_sip_push_task(NULL, sip_publish_client_service_queue, ao2_bump(publish->state))) {
  651. ao2_ref(publish->state, -1);
  652. }
  653. }
  654. }
  655. #define DATASTORE_BUCKETS 53
  656. static int datastore_hash(const void *obj, int flags)
  657. {
  658. const struct ast_datastore *datastore;
  659. const char *uid;
  660. switch (flags & OBJ_SEARCH_MASK) {
  661. case OBJ_SEARCH_KEY:
  662. uid = obj;
  663. break;
  664. case OBJ_SEARCH_OBJECT:
  665. datastore = obj;
  666. uid = datastore->uid;
  667. break;
  668. default:
  669. /* Hash can only work on something with a full key. */
  670. ast_assert(0);
  671. return 0;
  672. }
  673. return ast_str_hash(uid);
  674. }
  675. static int datastore_cmp(void *obj, void *arg, int flags)
  676. {
  677. const struct ast_datastore *object_left = obj;
  678. const struct ast_datastore *object_right = arg;
  679. const char *right_key = arg;
  680. int cmp;
  681. switch (flags & OBJ_SEARCH_MASK) {
  682. case OBJ_SEARCH_OBJECT:
  683. right_key = object_right->uid;
  684. /* Fall through */
  685. case OBJ_SEARCH_KEY:
  686. cmp = strcmp(object_left->uid, right_key);
  687. break;
  688. case OBJ_SEARCH_PARTIAL_KEY:
  689. cmp = strncmp(object_left->uid, right_key, strlen(right_key));
  690. break;
  691. default:
  692. /*
  693. * What arg points to is specific to this traversal callback
  694. * and has no special meaning to astobj2.
  695. */
  696. cmp = 0;
  697. break;
  698. }
  699. if (cmp) {
  700. return 0;
  701. }
  702. /*
  703. * At this point the traversal callback is identical to a sorted
  704. * container.
  705. */
  706. return CMP_MATCH;
  707. }
  708. /*! \brief Allocator function for publish client state */
  709. static struct ast_sip_outbound_publish_client *sip_outbound_publish_state_alloc(void)
  710. {
  711. struct ast_sip_outbound_publish_client *state = ao2_alloc(sizeof(*state), sip_outbound_publish_client_destroy);
  712. if (!state) {
  713. return NULL;
  714. }
  715. state->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
  716. if (!state->datastores) {
  717. ao2_ref(state, -1);
  718. return NULL;
  719. }
  720. state->timer.user_data = state;
  721. state->timer.cb = sip_outbound_publish_timer_cb;
  722. return state;
  723. }
  724. /*! \brief Apply function which finds or allocates a state structure */
  725. static int sip_outbound_publish_apply(const struct ast_sorcery *sorcery, void *obj)
  726. {
  727. RAII_VAR(struct ast_sip_outbound_publish *, existing, ast_sorcery_retrieve_by_id(sorcery, "outbound-publish", ast_sorcery_object_get_id(obj)), ao2_cleanup);
  728. struct ast_sip_outbound_publish *applied = obj;
  729. if (ast_strlen_zero(applied->server_uri)) {
  730. ast_log(LOG_ERROR, "No server URI specified on outbound publish '%s'\n",
  731. ast_sorcery_object_get_id(applied));
  732. return -1;
  733. } else if (ast_strlen_zero(applied->event)) {
  734. ast_log(LOG_ERROR, "No event type specified for outbound publish '%s'\n",
  735. ast_sorcery_object_get_id(applied));
  736. return -1;
  737. }
  738. if (!existing) {
  739. /* If no existing publish exists we can just start fresh easily */
  740. applied->state = sip_outbound_publish_state_alloc();
  741. } else {
  742. /* If there is an existing publish things are more complicated, we can immediately reuse this state if most stuff remains unchanged */
  743. if (can_reuse_publish(existing, applied)) {
  744. applied->state = existing->state;
  745. ao2_ref(applied->state, +1);
  746. } else {
  747. applied->state = sip_outbound_publish_state_alloc();
  748. }
  749. }
  750. if (!applied->state) {
  751. return -1;
  752. }
  753. return ast_sip_push_task_synchronous(NULL, sip_outbound_publish_client_alloc, applied);
  754. }
  755. static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
  756. {
  757. struct ast_sip_outbound_publish *publish = obj;
  758. return ast_sip_auth_vector_init(&publish->outbound_auths, var->value);
  759. }
  760. /*! \brief Helper function which prunes old publish clients */
  761. static void prune_publish_clients(const char *object_type)
  762. {
  763. struct ao2_container *old, *current;
  764. old = ao2_global_obj_ref(active);
  765. if (old) {
  766. struct ao2_iterator i;
  767. struct ast_sip_outbound_publish *existing;
  768. i = ao2_iterator_init(old, 0);
  769. for (; (existing = ao2_iterator_next(&i)); ao2_ref(existing, -1)) {
  770. struct ast_sip_outbound_publish *created;
  771. created = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "outbound-publish",
  772. ast_sorcery_object_get_id(existing));
  773. if (created) {
  774. if (created->state == existing->state) {
  775. ao2_ref(created, -1);
  776. continue;
  777. }
  778. ao2_ref(created, -1);
  779. }
  780. ao2_lock(existing->state);
  781. /* If this publish client is currently publishing stop and terminate any refresh timer */
  782. if (existing->state->started) {
  783. struct ast_sip_event_publisher_handler *handler = find_publisher_handler_for_event_name(existing->event);
  784. if (handler) {
  785. handler->stop_publishing(existing->state);
  786. }
  787. if (ast_sip_push_task(NULL, cancel_refresh_timer_task, ao2_bump(existing->state))) {
  788. ast_log(LOG_WARNING, "Could not stop refresh timer on outbound publish '%s'\n",
  789. ast_sorcery_object_get_id(existing));
  790. ao2_ref(existing->state, -1);
  791. }
  792. }
  793. /* If nothing is being sent right now send the unpublish - the destroy will happen in the subsequent callback */
  794. if (!existing->state->sending) {
  795. if (ast_sip_push_task(NULL, send_unpublish_task, ao2_bump(existing->state))) {
  796. ast_log(LOG_WARNING, "Could not send unpublish message on outbound publish '%s'\n",
  797. ast_sorcery_object_get_id(existing));
  798. ao2_ref(existing->state, -1);
  799. }
  800. }
  801. existing->state->destroy = 1;
  802. ao2_unlock(existing->state);
  803. }
  804. ao2_iterator_destroy(&i);
  805. ao2_ref(old, -1);
  806. }
  807. current = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "outbound-publish", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  808. ao2_global_obj_replace_unref(active, current);
  809. }
  810. static struct ast_sorcery_observer outbound_publish_observer = {
  811. .loaded = prune_publish_clients,
  812. };
  813. static int load_module(void)
  814. {
  815. ast_sorcery_apply_default(ast_sip_get_sorcery(), "outbound-publish", "config", "pjsip.conf,criteria=type=outbound-publish");
  816. if (ast_sorcery_object_register(ast_sip_get_sorcery(), "outbound-publish", sip_outbound_publish_alloc, NULL,
  817. sip_outbound_publish_apply)) {
  818. return AST_MODULE_LOAD_DECLINE;
  819. }
  820. ast_sorcery_observer_add(ast_sip_get_sorcery(), "outbound-publish", &outbound_publish_observer);
  821. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "type", "", OPT_NOOP_T, 0, 0);
  822. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "server_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_outbound_publish, server_uri));
  823. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "from_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_outbound_publish, from_uri));
  824. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "event", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_outbound_publish, event));
  825. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "to_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_outbound_publish, to_uri));
  826. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_outbound_publish, outbound_proxy));
  827. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "expiration", "3600", OPT_UINT_T, 0, FLDSET(struct ast_sip_outbound_publish, expiration));
  828. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "outbound-publish", "max_auth_attempts", "5", OPT_UINT_T, 0, FLDSET(struct ast_sip_outbound_publish, max_auth_attempts));
  829. ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "outbound-publish", "outbound_auth", "", outbound_auth_handler, NULL, NULL, 0, 0);
  830. ast_sorcery_reload_object(ast_sip_get_sorcery(), "outbound-publish");
  831. AST_RWLIST_RDLOCK(&publisher_handlers);
  832. sip_outbound_publish_synchronize(NULL);
  833. AST_RWLIST_UNLOCK(&publisher_handlers);
  834. pjsip_publishc_init_module(ast_sip_get_pjsip_endpoint());
  835. return AST_MODULE_LOAD_SUCCESS;
  836. }
  837. static int reload_module(void)
  838. {
  839. ast_sorcery_reload_object(ast_sip_get_sorcery(), "outbound-publish");
  840. AST_RWLIST_RDLOCK(&publisher_handlers);
  841. sip_outbound_publish_synchronize(NULL);
  842. AST_RWLIST_UNLOCK(&publisher_handlers);
  843. return 0;
  844. }
  845. static int unload_module(void)
  846. {
  847. return 0;
  848. }
  849. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Outbound Publish Support",
  850. .load = load_module,
  851. .reload = reload_module,
  852. .unload = unload_module,
  853. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  854. );