pjsip_distributor.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2013, Digium, Inc.
  5. *
  6. * Mark Michelson <mmichelson@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. #include "asterisk.h"
  19. #include <pjsip.h>
  20. #include "asterisk/res_pjsip.h"
  21. #include "asterisk/acl.h"
  22. #include "include/res_pjsip_private.h"
  23. #include "asterisk/taskprocessor.h"
  24. #include "asterisk/threadpool.h"
  25. #include "asterisk/res_pjsip_cli.h"
  26. static int distribute(void *data);
  27. static pj_bool_t distributor(pjsip_rx_data *rdata);
  28. static pjsip_module distributor_mod = {
  29. .name = {"Request Distributor", 19},
  30. .priority = PJSIP_MOD_PRIORITY_TSX_LAYER - 6,
  31. .on_tx_request = ast_sip_record_request_serializer,
  32. .on_rx_request = distributor,
  33. .on_rx_response = distributor,
  34. };
  35. struct ast_sched_context *prune_context;
  36. /* From the auth/realm realtime column size */
  37. #define MAX_REALM_LENGTH 40
  38. #define DEFAULT_SUSPECTS_BUCKETS 53
  39. static struct ao2_container *unidentified_requests;
  40. static unsigned int unidentified_count;
  41. static unsigned int unidentified_period;
  42. static unsigned int unidentified_prune_interval;
  43. static int using_auth_username;
  44. struct unidentified_request{
  45. struct timeval first_seen;
  46. int count;
  47. char src_name[];
  48. };
  49. /*! Number of serializers in pool if one not otherwise known. (Best if prime number) */
  50. #define DISTRIBUTOR_POOL_SIZE 31
  51. /*! Pool of serializers to use if not supplied. */
  52. static struct ast_taskprocessor *distributor_pool[DISTRIBUTOR_POOL_SIZE];
  53. pj_status_t ast_sip_record_request_serializer(pjsip_tx_data *tdata)
  54. {
  55. struct ast_taskprocessor *serializer;
  56. serializer = ast_threadpool_serializer_get_current();
  57. if (serializer) {
  58. const char *name;
  59. name = ast_taskprocessor_name(serializer);
  60. if (!ast_strlen_zero(name)
  61. && (!tdata->mod_data[distributor_mod.id]
  62. || strcmp(tdata->mod_data[distributor_mod.id], name))) {
  63. char *tdata_name;
  64. /* The serializer in use changed. */
  65. tdata_name = pj_pool_alloc(tdata->pool, strlen(name) + 1);
  66. strcpy(tdata_name, name);/* Safe */
  67. tdata->mod_data[distributor_mod.id] = tdata_name;
  68. }
  69. }
  70. return PJ_SUCCESS;
  71. }
  72. /*!
  73. * \internal
  74. * \brief Find the request tdata to get the serializer it used.
  75. * \since 14.0.0
  76. *
  77. * \param rdata The incoming message.
  78. *
  79. * \retval serializer on success.
  80. * \retval NULL on error or could not find the serializer.
  81. */
  82. static struct ast_taskprocessor *find_request_serializer(pjsip_rx_data *rdata)
  83. {
  84. struct ast_taskprocessor *serializer = NULL;
  85. pj_str_t tsx_key;
  86. pjsip_transaction *tsx;
  87. pjsip_tsx_create_key(rdata->tp_info.pool, &tsx_key, PJSIP_ROLE_UAC,
  88. &rdata->msg_info.cseq->method, rdata);
  89. tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE);
  90. if (!tsx) {
  91. ast_debug(1, "Could not find transaction for %s.\n",
  92. pjsip_rx_data_get_info(rdata));
  93. return NULL;
  94. }
  95. ast_debug(3, "Found transaction %s for %s.\n",
  96. tsx->obj_name, pjsip_rx_data_get_info(rdata));
  97. if (tsx->last_tx) {
  98. const char *serializer_name;
  99. serializer_name = tsx->last_tx->mod_data[distributor_mod.id];
  100. if (!ast_strlen_zero(serializer_name)) {
  101. serializer = ast_taskprocessor_get(serializer_name, TPS_REF_IF_EXISTS);
  102. if (serializer) {
  103. ast_debug(3, "Found serializer %s on transaction %s\n",
  104. serializer_name, tsx->obj_name);
  105. }
  106. }
  107. }
  108. #ifdef HAVE_PJ_TRANSACTION_GRP_LOCK
  109. pj_grp_lock_release(tsx->grp_lock);
  110. #else
  111. pj_mutex_unlock(tsx->mutex);
  112. #endif
  113. return serializer;
  114. }
  115. /*! Dialog-specific information the distributor uses */
  116. struct distributor_dialog_data {
  117. /*! dialog_associations ao2 container key */
  118. pjsip_dialog *dlg;
  119. /*! Serializer to distribute tasks to for this dialog */
  120. struct ast_taskprocessor *serializer;
  121. /*! Endpoint associated with this dialog */
  122. struct ast_sip_endpoint *endpoint;
  123. };
  124. #define DIALOG_ASSOCIATIONS_BUCKETS 251
  125. static struct ao2_container *dialog_associations;
  126. /*!
  127. * \internal
  128. * \brief Compute a hash value on an arbitrary buffer.
  129. * \since 13.17.0
  130. *
  131. * \param[in] pos The buffer to add to the hash
  132. * \param[in] len The buffer length to add to the hash
  133. * \param[in] hash The hash value to add to
  134. *
  135. * \details
  136. * This version of the function is for when you need to compute a
  137. * hash of more than one buffer.
  138. *
  139. * This famous hash algorithm was written by Dan Bernstein and is
  140. * commonly used.
  141. *
  142. * \sa http://www.cse.yorku.ca/~oz/hash.html
  143. */
  144. static int buf_hash_add(const char *pos, size_t len, int hash)
  145. {
  146. while (len--) {
  147. hash = hash * 33 ^ *pos++;
  148. }
  149. return hash;
  150. }
  151. /*!
  152. * \internal
  153. * \brief Compute a hash value on an arbitrary buffer.
  154. * \since 13.17.0
  155. *
  156. * \param[in] pos The buffer to add to the hash
  157. * \param[in] len The buffer length to add to the hash
  158. *
  159. * \details
  160. * This version of the function is for when you need to compute a
  161. * hash of more than one buffer.
  162. *
  163. * This famous hash algorithm was written by Dan Bernstein and is
  164. * commonly used.
  165. *
  166. * \sa http://www.cse.yorku.ca/~oz/hash.html
  167. */
  168. static int buf_hash(const char *pos, size_t len)
  169. {
  170. return buf_hash_add(pos, len, 5381);
  171. }
  172. static int dialog_associations_hash(const void *obj, int flags)
  173. {
  174. const struct distributor_dialog_data *object;
  175. union {
  176. const pjsip_dialog *dlg;
  177. const char buf[sizeof(pjsip_dialog *)];
  178. } key;
  179. switch (flags & OBJ_SEARCH_MASK) {
  180. case OBJ_SEARCH_KEY:
  181. key.dlg = obj;
  182. break;
  183. case OBJ_SEARCH_OBJECT:
  184. object = obj;
  185. key.dlg = object->dlg;
  186. break;
  187. default:
  188. /* Hash can only work on something with a full key. */
  189. ast_assert(0);
  190. return 0;
  191. }
  192. return ast_str_hash_restrict(buf_hash(key.buf, sizeof(key.buf)));
  193. }
  194. static int dialog_associations_cmp(void *obj, void *arg, int flags)
  195. {
  196. const struct distributor_dialog_data *object_left = obj;
  197. const struct distributor_dialog_data *object_right = arg;
  198. const pjsip_dialog *right_key = arg;
  199. int cmp = 0;
  200. switch (flags & OBJ_SEARCH_MASK) {
  201. case OBJ_SEARCH_OBJECT:
  202. right_key = object_right->dlg;
  203. /* Fall through */
  204. case OBJ_SEARCH_KEY:
  205. if (object_left->dlg == right_key) {
  206. cmp = CMP_MATCH;
  207. }
  208. break;
  209. case OBJ_SEARCH_PARTIAL_KEY:
  210. /* There is no such thing for this container. */
  211. ast_assert(0);
  212. break;
  213. default:
  214. cmp = 0;
  215. break;
  216. }
  217. return cmp;
  218. }
  219. void ast_sip_dialog_set_serializer(pjsip_dialog *dlg, struct ast_taskprocessor *serializer)
  220. {
  221. struct distributor_dialog_data *dist;
  222. ao2_wrlock(dialog_associations);
  223. dist = ao2_find(dialog_associations, dlg, OBJ_SEARCH_KEY | OBJ_NOLOCK);
  224. if (!dist) {
  225. if (serializer) {
  226. dist = ao2_alloc(sizeof(*dist), NULL);
  227. if (dist) {
  228. dist->dlg = dlg;
  229. dist->serializer = serializer;
  230. ao2_link_flags(dialog_associations, dist, OBJ_NOLOCK);
  231. ao2_ref(dist, -1);
  232. }
  233. }
  234. } else {
  235. ao2_lock(dist);
  236. dist->serializer = serializer;
  237. if (!dist->serializer && !dist->endpoint) {
  238. ao2_unlink_flags(dialog_associations, dist, OBJ_NOLOCK);
  239. }
  240. ao2_unlock(dist);
  241. ao2_ref(dist, -1);
  242. }
  243. ao2_unlock(dialog_associations);
  244. }
  245. void ast_sip_dialog_set_endpoint(pjsip_dialog *dlg, struct ast_sip_endpoint *endpoint)
  246. {
  247. struct distributor_dialog_data *dist;
  248. ao2_wrlock(dialog_associations);
  249. dist = ao2_find(dialog_associations, dlg, OBJ_SEARCH_KEY | OBJ_NOLOCK);
  250. if (!dist) {
  251. if (endpoint) {
  252. dist = ao2_alloc(sizeof(*dist), NULL);
  253. if (dist) {
  254. dist->dlg = dlg;
  255. dist->endpoint = endpoint;
  256. ao2_link_flags(dialog_associations, dist, OBJ_NOLOCK);
  257. ao2_ref(dist, -1);
  258. }
  259. }
  260. } else {
  261. ao2_lock(dist);
  262. dist->endpoint = endpoint;
  263. if (!dist->serializer && !dist->endpoint) {
  264. ao2_unlink_flags(dialog_associations, dist, OBJ_NOLOCK);
  265. }
  266. ao2_unlock(dist);
  267. ao2_ref(dist, -1);
  268. }
  269. ao2_unlock(dialog_associations);
  270. }
  271. struct ast_sip_endpoint *ast_sip_dialog_get_endpoint(pjsip_dialog *dlg)
  272. {
  273. struct distributor_dialog_data *dist;
  274. struct ast_sip_endpoint *endpoint;
  275. dist = ao2_find(dialog_associations, dlg, OBJ_SEARCH_KEY);
  276. if (dist) {
  277. ao2_lock(dist);
  278. endpoint = ao2_bump(dist->endpoint);
  279. ao2_unlock(dist);
  280. ao2_ref(dist, -1);
  281. } else {
  282. endpoint = NULL;
  283. }
  284. return endpoint;
  285. }
  286. static pjsip_dialog *find_dialog(pjsip_rx_data *rdata)
  287. {
  288. pj_str_t tsx_key;
  289. pjsip_transaction *tsx;
  290. pjsip_dialog *dlg;
  291. pj_str_t *local_tag;
  292. pj_str_t *remote_tag;
  293. if (!rdata->msg_info.msg) {
  294. return NULL;
  295. }
  296. if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
  297. local_tag = &rdata->msg_info.to->tag;
  298. remote_tag = &rdata->msg_info.from->tag;
  299. } else {
  300. local_tag = &rdata->msg_info.from->tag;
  301. remote_tag = &rdata->msg_info.to->tag;
  302. }
  303. /* We can only call the convenient method for
  304. * 1) responses
  305. * 2) non-CANCEL requests
  306. * 3) CANCEL requests with a to-tag
  307. */
  308. if (rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG ||
  309. pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_cancel_method) ||
  310. rdata->msg_info.to->tag.slen != 0) {
  311. dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, local_tag,
  312. remote_tag, PJ_FALSE);
  313. if (dlg) {
  314. return dlg;
  315. }
  316. }
  317. /*
  318. * There may still be a matching dialog if this is
  319. * 1) an incoming CANCEL request without a to-tag
  320. * 2) an incoming response to a dialog-creating request.
  321. */
  322. if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
  323. /* CANCEL requests will need to match the INVITE we initially received. Any
  324. * other request type will either have been matched already or is not in
  325. * dialog
  326. */
  327. pjsip_tsx_create_key(rdata->tp_info.pool, &tsx_key, PJSIP_ROLE_UAS,
  328. pjsip_get_invite_method(), rdata);
  329. } else {
  330. pjsip_tsx_create_key(rdata->tp_info.pool, &tsx_key, PJSIP_ROLE_UAC,
  331. &rdata->msg_info.cseq->method, rdata);
  332. }
  333. tsx = pjsip_tsx_layer_find_tsx(&tsx_key, PJ_TRUE);
  334. if (!tsx) {
  335. ast_debug(3, "Could not find matching transaction for %s\n",
  336. pjsip_rx_data_get_info(rdata));
  337. return NULL;
  338. }
  339. dlg = pjsip_tsx_get_dlg(tsx);
  340. #ifdef HAVE_PJ_TRANSACTION_GRP_LOCK
  341. pj_grp_lock_release(tsx->grp_lock);
  342. #else
  343. pj_mutex_unlock(tsx->mutex);
  344. #endif
  345. return dlg;
  346. }
  347. /*!
  348. * \internal
  349. * \brief Compute a hash value on a pjlib string
  350. * \since 13.10.0
  351. *
  352. * \param[in] str The pjlib string to add to the hash
  353. * \param[in] hash The hash value to add to
  354. *
  355. * \details
  356. * This version of the function is for when you need to compute a
  357. * string hash of more than one string.
  358. *
  359. * This famous hash algorithm was written by Dan Bernstein and is
  360. * commonly used.
  361. *
  362. * \sa http://www.cse.yorku.ca/~oz/hash.html
  363. */
  364. static int pjstr_hash_add(pj_str_t *str, int hash)
  365. {
  366. return buf_hash_add(pj_strbuf(str), pj_strlen(str), hash);
  367. }
  368. /*!
  369. * \internal
  370. * \brief Compute a hash value on a pjlib string
  371. * \since 13.10.0
  372. *
  373. * \param[in] str The pjlib string to hash
  374. *
  375. * This famous hash algorithm was written by Dan Bernstein and is
  376. * commonly used.
  377. *
  378. * http://www.cse.yorku.ca/~oz/hash.html
  379. */
  380. static int pjstr_hash(pj_str_t *str)
  381. {
  382. return pjstr_hash_add(str, 5381);
  383. }
  384. struct ast_taskprocessor *ast_sip_get_distributor_serializer(pjsip_rx_data *rdata)
  385. {
  386. int hash;
  387. pj_str_t *remote_tag;
  388. struct ast_taskprocessor *serializer;
  389. if (!rdata->msg_info.msg) {
  390. return NULL;
  391. }
  392. if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
  393. remote_tag = &rdata->msg_info.from->tag;
  394. } else {
  395. remote_tag = &rdata->msg_info.to->tag;
  396. }
  397. /* Compute the hash from the SIP message call-id and remote-tag */
  398. hash = pjstr_hash(&rdata->msg_info.cid->id);
  399. hash = pjstr_hash_add(remote_tag, hash);
  400. hash = ast_str_hash_restrict(hash);
  401. serializer = ao2_bump(distributor_pool[hash % ARRAY_LEN(distributor_pool)]);
  402. if (serializer) {
  403. ast_debug(3, "Calculated serializer %s to use for %s\n",
  404. ast_taskprocessor_name(serializer), pjsip_rx_data_get_info(rdata));
  405. }
  406. return serializer;
  407. }
  408. static pj_bool_t endpoint_lookup(pjsip_rx_data *rdata);
  409. static pjsip_module endpoint_mod = {
  410. .name = {"Endpoint Identifier", 19},
  411. .priority = PJSIP_MOD_PRIORITY_TSX_LAYER - 3,
  412. .on_rx_request = endpoint_lookup,
  413. };
  414. static pj_bool_t distributor(pjsip_rx_data *rdata)
  415. {
  416. pjsip_dialog *dlg;
  417. struct distributor_dialog_data *dist = NULL;
  418. struct ast_taskprocessor *serializer = NULL;
  419. pjsip_rx_data *clone;
  420. if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
  421. /*
  422. * Ignore everything until we are fully booted. Let the
  423. * peer retransmit messages until we are ready.
  424. */
  425. return PJ_TRUE;
  426. }
  427. dlg = find_dialog(rdata);
  428. if (dlg) {
  429. ast_debug(3, "Searching for serializer associated with dialog %s for %s\n",
  430. dlg->obj_name, pjsip_rx_data_get_info(rdata));
  431. dist = ao2_find(dialog_associations, dlg, OBJ_SEARCH_KEY);
  432. if (dist) {
  433. ao2_lock(dist);
  434. serializer = ao2_bump(dist->serializer);
  435. ao2_unlock(dist);
  436. if (serializer) {
  437. ast_debug(3, "Found serializer %s associated with dialog %s\n",
  438. ast_taskprocessor_name(serializer), dlg->obj_name);
  439. }
  440. }
  441. }
  442. if (serializer) {
  443. /* We have a serializer so we know where to send the message. */
  444. } else if (rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG) {
  445. ast_debug(3, "No dialog serializer for %s. Using request transaction as basis.\n",
  446. pjsip_rx_data_get_info(rdata));
  447. serializer = find_request_serializer(rdata);
  448. if (!serializer) {
  449. /*
  450. * Pick a serializer for the unmatched response.
  451. * We couldn't determine what serializer originally
  452. * sent the request or the serializer is gone.
  453. */
  454. serializer = ast_sip_get_distributor_serializer(rdata);
  455. }
  456. } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_cancel_method)
  457. || !pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_bye_method)) {
  458. /* We have a BYE or CANCEL request without a serializer. */
  459. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata,
  460. PJSIP_SC_CALL_TSX_DOES_NOT_EXIST, NULL, NULL, NULL);
  461. ao2_cleanup(dist);
  462. return PJ_TRUE;
  463. } else {
  464. if (ast_taskprocessor_alert_get()) {
  465. /*
  466. * When taskprocessors get backed up, there is a good chance that
  467. * we are being overloaded and need to defer adding new work to
  468. * the system. To defer the work we will ignore the request and
  469. * rely on the peer's transport layer to retransmit the message.
  470. * We usually work off the overload within a few seconds.
  471. * If transport is non-UDP we send a 503 response instead.
  472. */
  473. switch (rdata->tp_info.transport->key.type) {
  474. case PJSIP_TRANSPORT_UDP6:
  475. case PJSIP_TRANSPORT_UDP:
  476. ast_debug(3, "Taskprocessor overload alert: Ignoring '%s'.\n",
  477. pjsip_rx_data_get_info(rdata));
  478. break;
  479. default:
  480. ast_debug(3, "Taskprocessor overload on non-udp transport. Received:'%s'. "
  481. "Responding with a 503.\n", pjsip_rx_data_get_info(rdata));
  482. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata,
  483. PJSIP_SC_SERVICE_UNAVAILABLE, NULL, NULL, NULL);
  484. break;
  485. }
  486. ao2_cleanup(dist);
  487. return PJ_TRUE;
  488. }
  489. /* Pick a serializer for the out-of-dialog request. */
  490. serializer = ast_sip_get_distributor_serializer(rdata);
  491. }
  492. if (pjsip_rx_data_clone(rdata, 0, &clone) != PJ_SUCCESS) {
  493. ast_taskprocessor_unreference(serializer);
  494. ao2_cleanup(dist);
  495. return PJ_TRUE;
  496. }
  497. if (dist) {
  498. ao2_lock(dist);
  499. clone->endpt_info.mod_data[endpoint_mod.id] = ao2_bump(dist->endpoint);
  500. ao2_unlock(dist);
  501. ao2_cleanup(dist);
  502. }
  503. if (ast_sip_push_task(serializer, distribute, clone)) {
  504. ao2_cleanup(clone->endpt_info.mod_data[endpoint_mod.id]);
  505. pjsip_rx_data_free_cloned(clone);
  506. }
  507. ast_taskprocessor_unreference(serializer);
  508. return PJ_TRUE;
  509. }
  510. static struct ast_sip_auth *alloc_artificial_auth(char *default_realm)
  511. {
  512. struct ast_sip_auth *fake_auth;
  513. fake_auth = ast_sorcery_alloc(ast_sip_get_sorcery(), SIP_SORCERY_AUTH_TYPE,
  514. "artificial");
  515. if (!fake_auth) {
  516. return NULL;
  517. }
  518. ast_string_field_set(fake_auth, realm, default_realm);
  519. ast_string_field_set(fake_auth, auth_user, "");
  520. ast_string_field_set(fake_auth, auth_pass, "");
  521. fake_auth->type = AST_SIP_AUTH_TYPE_ARTIFICIAL;
  522. return fake_auth;
  523. }
  524. static AO2_GLOBAL_OBJ_STATIC(artificial_auth);
  525. static int create_artificial_auth(void)
  526. {
  527. char default_realm[MAX_REALM_LENGTH + 1];
  528. struct ast_sip_auth *fake_auth;
  529. ast_sip_get_default_realm(default_realm, sizeof(default_realm));
  530. fake_auth = alloc_artificial_auth(default_realm);
  531. if (!fake_auth) {
  532. ast_log(LOG_ERROR, "Unable to create artificial auth\n");
  533. return -1;
  534. }
  535. ao2_global_obj_replace_unref(artificial_auth, fake_auth);
  536. ao2_ref(fake_auth, -1);
  537. return 0;
  538. }
  539. struct ast_sip_auth *ast_sip_get_artificial_auth(void)
  540. {
  541. return ao2_global_obj_ref(artificial_auth);
  542. }
  543. static struct ast_sip_endpoint *artificial_endpoint = NULL;
  544. static int create_artificial_endpoint(void)
  545. {
  546. artificial_endpoint = ast_sorcery_alloc(ast_sip_get_sorcery(), "endpoint", NULL);
  547. if (!artificial_endpoint) {
  548. return -1;
  549. }
  550. AST_VECTOR_INIT(&artificial_endpoint->inbound_auths, 1);
  551. /* Pushing a bogus value into the vector will ensure that
  552. * the proper size of the vector is returned. This value is
  553. * not actually used anywhere
  554. */
  555. AST_VECTOR_APPEND(&artificial_endpoint->inbound_auths, ast_strdup("artificial-auth"));
  556. return 0;
  557. }
  558. struct ast_sip_endpoint *ast_sip_get_artificial_endpoint(void)
  559. {
  560. ao2_ref(artificial_endpoint, +1);
  561. return artificial_endpoint;
  562. }
  563. static void log_failed_request(pjsip_rx_data *rdata, char *msg, unsigned int count, unsigned int period)
  564. {
  565. char from_buf[PJSIP_MAX_URL_SIZE];
  566. char callid_buf[PJSIP_MAX_URL_SIZE];
  567. char method_buf[PJSIP_MAX_URL_SIZE];
  568. char src_addr_buf[AST_SOCKADDR_BUFLEN];
  569. pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, rdata->msg_info.from->uri, from_buf, PJSIP_MAX_URL_SIZE);
  570. ast_copy_pj_str(callid_buf, &rdata->msg_info.cid->id, PJSIP_MAX_URL_SIZE);
  571. ast_copy_pj_str(method_buf, &rdata->msg_info.msg->line.req.method.name, PJSIP_MAX_URL_SIZE);
  572. if (count) {
  573. ast_log(LOG_NOTICE, "Request '%s' from '%s' failed for '%s' (callid: %s) - %s"
  574. " after %u tries in %.3f ms\n",
  575. method_buf, from_buf,
  576. pj_sockaddr_print(&rdata->pkt_info.src_addr, src_addr_buf, sizeof(src_addr_buf), 3),
  577. callid_buf, msg, count, period / 1000.0);
  578. } else {
  579. ast_log(LOG_NOTICE, "Request '%s' from '%s' failed for '%s' (callid: %s) - %s\n",
  580. method_buf, from_buf,
  581. pj_sockaddr_print(&rdata->pkt_info.src_addr, src_addr_buf, sizeof(src_addr_buf), 3),
  582. callid_buf, msg);
  583. }
  584. }
  585. static void check_endpoint(pjsip_rx_data *rdata, struct unidentified_request *unid,
  586. const char *name)
  587. {
  588. int64_t ms = ast_tvdiff_ms(ast_tvnow(), unid->first_seen);
  589. ao2_wrlock(unid);
  590. unid->count++;
  591. if (ms < (unidentified_period * 1000) && unid->count >= unidentified_count) {
  592. log_failed_request(rdata, "No matching endpoint found", unid->count, ms);
  593. ast_sip_report_invalid_endpoint(name, rdata);
  594. }
  595. ao2_unlock(unid);
  596. }
  597. static int apply_endpoint_acl(pjsip_rx_data *rdata, struct ast_sip_endpoint *endpoint);
  598. static int apply_endpoint_contact_acl(pjsip_rx_data *rdata, struct ast_sip_endpoint *endpoint);
  599. static void apply_acls(pjsip_rx_data *rdata)
  600. {
  601. struct ast_sip_endpoint *endpoint;
  602. /* Is the endpoint allowed with the source or contact address? */
  603. endpoint = rdata->endpt_info.mod_data[endpoint_mod.id];
  604. if (endpoint != artificial_endpoint
  605. && (apply_endpoint_acl(rdata, endpoint)
  606. || apply_endpoint_contact_acl(rdata, endpoint))) {
  607. ast_debug(1, "Endpoint '%s' not allowed by ACL\n",
  608. ast_sorcery_object_get_id(endpoint));
  609. /* Replace the rdata endpoint with the artificial endpoint. */
  610. ao2_replace(rdata->endpt_info.mod_data[endpoint_mod.id], artificial_endpoint);
  611. }
  612. }
  613. static pj_bool_t endpoint_lookup(pjsip_rx_data *rdata)
  614. {
  615. struct ast_sip_endpoint *endpoint;
  616. struct unidentified_request *unid;
  617. int is_ack = rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD;
  618. endpoint = rdata->endpt_info.mod_data[endpoint_mod.id];
  619. if (endpoint) {
  620. /*
  621. * ao2_find with OBJ_UNLINK always write locks the container before even searching
  622. * for the object. Since the majority case is that the object won't be found, do
  623. * the find without OBJ_UNLINK to prevent the unnecessary write lock, then unlink
  624. * if needed.
  625. */
  626. unid = ao2_find(unidentified_requests, rdata->pkt_info.src_name, OBJ_SEARCH_KEY);
  627. if (unid) {
  628. ao2_unlink(unidentified_requests, unid);
  629. ao2_ref(unid, -1);
  630. }
  631. apply_acls(rdata);
  632. return PJ_FALSE;
  633. }
  634. endpoint = ast_sip_identify_endpoint(rdata);
  635. if (endpoint) {
  636. unid = ao2_find(unidentified_requests, rdata->pkt_info.src_name, OBJ_SEARCH_KEY);
  637. if (unid) {
  638. ao2_unlink(unidentified_requests, unid);
  639. ao2_ref(unid, -1);
  640. }
  641. }
  642. if (!endpoint) {
  643. /* always use an artificial endpoint - per discussion no reason
  644. to have "alwaysauthreject" as an option. It is felt using it
  645. was a bug fix and it is not needed since we are not worried about
  646. breaking old stuff and we really don't want to enable the discovery
  647. of SIP accounts */
  648. endpoint = ast_sip_get_artificial_endpoint();
  649. }
  650. /* endpoint ref held by mod_data[] */
  651. rdata->endpt_info.mod_data[endpoint_mod.id] = endpoint;
  652. if (endpoint == artificial_endpoint && !is_ack) {
  653. char name[AST_UUID_STR_LEN] = "";
  654. pjsip_uri *from = rdata->msg_info.from->uri;
  655. if (PJSIP_URI_SCHEME_IS_SIP(from) || PJSIP_URI_SCHEME_IS_SIPS(from)) {
  656. pjsip_sip_uri *sip_from = pjsip_uri_get_uri(from);
  657. ast_copy_pj_str(name, &sip_from->user, sizeof(name));
  658. }
  659. unid = ao2_find(unidentified_requests, rdata->pkt_info.src_name, OBJ_SEARCH_KEY);
  660. if (unid) {
  661. check_endpoint(rdata, unid, name);
  662. ao2_ref(unid, -1);
  663. } else if (using_auth_username) {
  664. ao2_wrlock(unidentified_requests);
  665. /* Checking again with the write lock held allows us to eliminate the DUPS_REPLACE and sort_fn */
  666. unid = ao2_find(unidentified_requests, rdata->pkt_info.src_name,
  667. OBJ_SEARCH_KEY | OBJ_NOLOCK);
  668. if (unid) {
  669. check_endpoint(rdata, unid, name);
  670. } else {
  671. unid = ao2_alloc_options(sizeof(*unid) + strlen(rdata->pkt_info.src_name) + 1,
  672. NULL, AO2_ALLOC_OPT_LOCK_RWLOCK);
  673. if (!unid) {
  674. ao2_unlock(unidentified_requests);
  675. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  676. return PJ_TRUE;
  677. }
  678. strcpy(unid->src_name, rdata->pkt_info.src_name); /* Safe */
  679. unid->first_seen = ast_tvnow();
  680. unid->count = 1;
  681. ao2_link_flags(unidentified_requests, unid, OBJ_NOLOCK);
  682. }
  683. ao2_ref(unid, -1);
  684. ao2_unlock(unidentified_requests);
  685. } else {
  686. log_failed_request(rdata, "No matching endpoint found", 0, 0);
  687. ast_sip_report_invalid_endpoint(name, rdata);
  688. }
  689. }
  690. apply_acls(rdata);
  691. return PJ_FALSE;
  692. }
  693. static int apply_endpoint_acl(pjsip_rx_data *rdata, struct ast_sip_endpoint *endpoint)
  694. {
  695. struct ast_sockaddr addr;
  696. if (ast_acl_list_is_empty(endpoint->acl)) {
  697. return 0;
  698. }
  699. memset(&addr, 0, sizeof(addr));
  700. ast_sockaddr_parse(&addr, rdata->pkt_info.src_name, PARSE_PORT_FORBID);
  701. ast_sockaddr_set_port(&addr, rdata->pkt_info.src_port);
  702. if (ast_apply_acl(endpoint->acl, &addr, "SIP ACL: ") != AST_SENSE_ALLOW) {
  703. log_failed_request(rdata, "Not match Endpoint ACL", 0, 0);
  704. ast_sip_report_failed_acl(endpoint, rdata, "not_match_endpoint_acl");
  705. return 1;
  706. }
  707. return 0;
  708. }
  709. static int extract_contact_addr(pjsip_contact_hdr *contact, struct ast_sockaddr **addrs)
  710. {
  711. pjsip_sip_uri *sip_uri;
  712. char host[256];
  713. if (!contact || contact->star) {
  714. *addrs = NULL;
  715. return 0;
  716. }
  717. if (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri)) {
  718. *addrs = NULL;
  719. return 0;
  720. }
  721. sip_uri = pjsip_uri_get_uri(contact->uri);
  722. ast_copy_pj_str(host, &sip_uri->host, sizeof(host));
  723. return ast_sockaddr_resolve(addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC);
  724. }
  725. static int apply_endpoint_contact_acl(pjsip_rx_data *rdata, struct ast_sip_endpoint *endpoint)
  726. {
  727. int num_contact_addrs;
  728. int forbidden = 0;
  729. struct ast_sockaddr *contact_addrs;
  730. int i;
  731. pjsip_contact_hdr *contact = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
  732. if (ast_acl_list_is_empty(endpoint->contact_acl)) {
  733. return 0;
  734. }
  735. while ((contact = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact->next))) {
  736. num_contact_addrs = extract_contact_addr(contact, &contact_addrs);
  737. if (num_contact_addrs <= 0) {
  738. continue;
  739. }
  740. for (i = 0; i < num_contact_addrs; ++i) {
  741. if (ast_apply_acl(endpoint->contact_acl, &contact_addrs[i], "SIP Contact ACL: ") != AST_SENSE_ALLOW) {
  742. log_failed_request(rdata, "Not match Endpoint Contact ACL", 0, 0);
  743. ast_sip_report_failed_acl(endpoint, rdata, "not_match_endpoint_contact_acl");
  744. forbidden = 1;
  745. break;
  746. }
  747. }
  748. ast_free(contact_addrs);
  749. if (forbidden) {
  750. /* No use checking other contacts if we already have failed ACL check */
  751. break;
  752. }
  753. }
  754. return forbidden;
  755. }
  756. static pj_bool_t authenticate(pjsip_rx_data *rdata)
  757. {
  758. RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
  759. int is_ack = rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD;
  760. ast_assert(endpoint != NULL);
  761. if (is_ack) {
  762. return PJ_FALSE;
  763. }
  764. if (ast_sip_requires_authentication(endpoint, rdata)) {
  765. pjsip_tx_data *tdata;
  766. struct unidentified_request *unid;
  767. pjsip_endpt_create_response(ast_sip_get_pjsip_endpoint(), rdata, 401, NULL, &tdata);
  768. switch (ast_sip_check_authentication(endpoint, rdata, tdata)) {
  769. case AST_SIP_AUTHENTICATION_CHALLENGE:
  770. /* Send the 401 we created for them */
  771. ast_sip_report_auth_challenge_sent(endpoint, rdata, tdata);
  772. if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
  773. pjsip_tx_data_dec_ref(tdata);
  774. }
  775. return PJ_TRUE;
  776. case AST_SIP_AUTHENTICATION_SUCCESS:
  777. /* See note in endpoint_lookup about not holding an unnecessary write lock */
  778. unid = ao2_find(unidentified_requests, rdata->pkt_info.src_name, OBJ_SEARCH_KEY);
  779. if (unid) {
  780. ao2_unlink(unidentified_requests, unid);
  781. ao2_ref(unid, -1);
  782. }
  783. ast_sip_report_auth_success(endpoint, rdata);
  784. break;
  785. case AST_SIP_AUTHENTICATION_FAILED:
  786. log_failed_request(rdata, "Failed to authenticate", 0, 0);
  787. ast_sip_report_auth_failed_challenge_response(endpoint, rdata);
  788. if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
  789. pjsip_tx_data_dec_ref(tdata);
  790. }
  791. return PJ_TRUE;
  792. case AST_SIP_AUTHENTICATION_ERROR:
  793. log_failed_request(rdata, "Error to authenticate", 0, 0);
  794. ast_sip_report_auth_failed_challenge_response(endpoint, rdata);
  795. pjsip_tx_data_dec_ref(tdata);
  796. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  797. return PJ_TRUE;
  798. }
  799. pjsip_tx_data_dec_ref(tdata);
  800. } else if (endpoint == artificial_endpoint) {
  801. /* Uh. Oh. The artificial endpoint couldn't challenge so block the request. */
  802. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  803. return PJ_TRUE;
  804. }
  805. return PJ_FALSE;
  806. }
  807. static pjsip_module auth_mod = {
  808. .name = {"Request Authenticator", 21},
  809. .priority = PJSIP_MOD_PRIORITY_APPLICATION - 2,
  810. .on_rx_request = authenticate,
  811. };
  812. static int distribute(void *data)
  813. {
  814. static pjsip_process_rdata_param param = {
  815. .start_mod = &distributor_mod,
  816. .idx_after_start = 1,
  817. };
  818. pj_bool_t handled = PJ_FALSE;
  819. pjsip_rx_data *rdata = data;
  820. int is_request = rdata->msg_info.msg->type == PJSIP_REQUEST_MSG;
  821. int is_ack = is_request ? rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD : 0;
  822. struct ast_sip_endpoint *endpoint;
  823. pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(), rdata, &param, &handled);
  824. if (!handled && is_request && !is_ack) {
  825. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 501, NULL, NULL, NULL);
  826. }
  827. /* The endpoint_mod stores an endpoint reference in the mod_data of rdata. This
  828. * is the only appropriate spot to actually decrement the reference.
  829. */
  830. endpoint = rdata->endpt_info.mod_data[endpoint_mod.id];
  831. ao2_cleanup(endpoint);
  832. pjsip_rx_data_free_cloned(rdata);
  833. return 0;
  834. }
  835. struct ast_sip_endpoint *ast_pjsip_rdata_get_endpoint(pjsip_rx_data *rdata)
  836. {
  837. struct ast_sip_endpoint *endpoint = rdata->endpt_info.mod_data[endpoint_mod.id];
  838. if (endpoint) {
  839. ao2_ref(endpoint, +1);
  840. }
  841. return endpoint;
  842. }
  843. static int suspects_sort(const void *obj, const void *arg, int flags)
  844. {
  845. const struct unidentified_request *object_left = obj;
  846. const struct unidentified_request *object_right = arg;
  847. const char *right_key = arg;
  848. int cmp;
  849. switch (flags & OBJ_SEARCH_MASK) {
  850. case OBJ_SEARCH_OBJECT:
  851. right_key = object_right->src_name;
  852. /* Fall through */
  853. case OBJ_SEARCH_KEY:
  854. cmp = strcmp(object_left->src_name, right_key);
  855. break;
  856. case OBJ_SEARCH_PARTIAL_KEY:
  857. cmp = strncmp(object_left->src_name, right_key, strlen(right_key));
  858. break;
  859. default:
  860. cmp = 0;
  861. break;
  862. }
  863. return cmp;
  864. }
  865. static int suspects_compare(void *obj, void *arg, int flags)
  866. {
  867. const struct unidentified_request *object_left = obj;
  868. const struct unidentified_request *object_right = arg;
  869. const char *right_key = arg;
  870. int cmp = 0;
  871. switch (flags & OBJ_SEARCH_MASK) {
  872. case OBJ_SEARCH_OBJECT:
  873. right_key = object_right->src_name;
  874. /* Fall through */
  875. case OBJ_SEARCH_KEY:
  876. if (strcmp(object_left->src_name, right_key) == 0) {
  877. cmp = CMP_MATCH;
  878. }
  879. break;
  880. case OBJ_SEARCH_PARTIAL_KEY:
  881. if (strncmp(object_left->src_name, right_key, strlen(right_key)) == 0) {
  882. cmp = CMP_MATCH;
  883. }
  884. break;
  885. default:
  886. cmp = 0;
  887. break;
  888. }
  889. return cmp;
  890. }
  891. static int suspects_hash(const void *obj, int flags)
  892. {
  893. const struct unidentified_request *object;
  894. const char *key;
  895. switch (flags & OBJ_SEARCH_MASK) {
  896. case OBJ_SEARCH_KEY:
  897. key = obj;
  898. break;
  899. case OBJ_SEARCH_OBJECT:
  900. object = obj;
  901. key = object->src_name;
  902. break;
  903. default:
  904. /* Hash can only work on something with a full key. */
  905. ast_assert(0);
  906. return 0;
  907. }
  908. return ast_str_hash(key);
  909. }
  910. static struct ao2_container *cli_unid_get_container(const char *regex)
  911. {
  912. struct ao2_container *s_container;
  913. s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
  914. suspects_sort, suspects_compare);
  915. if (!s_container) {
  916. return NULL;
  917. }
  918. if (ao2_container_dup(s_container, unidentified_requests, 0)) {
  919. ao2_ref(s_container, -1);
  920. return NULL;
  921. }
  922. return s_container;
  923. }
  924. static int cli_unid_iterate(void *container, ao2_callback_fn callback, void *args)
  925. {
  926. ao2_callback(container, 0, callback, args);
  927. return 0;
  928. }
  929. static void *cli_unid_retrieve_by_id(const char *id)
  930. {
  931. return ao2_find(unidentified_requests, id, OBJ_SEARCH_KEY);
  932. }
  933. static const char *cli_unid_get_id(const void *obj)
  934. {
  935. const struct unidentified_request *unid = obj;
  936. return unid->src_name;
  937. }
  938. static int cli_unid_print_header(void *obj, void *arg, int flags)
  939. {
  940. struct ast_sip_cli_context *context = arg;
  941. RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
  942. int indent = CLI_INDENT_TO_SPACES(context->indent_level);
  943. int filler = CLI_LAST_TABSTOP - indent - 7;
  944. ast_assert(context->output_buffer != NULL);
  945. ast_str_append(&context->output_buffer, 0,
  946. "%*s: <IP Address%*.*s> <Count> <Age(sec)>\n",
  947. indent, "Request", filler, filler, CLI_HEADER_FILLER);
  948. return 0;
  949. }
  950. static int cli_unid_print_body(void *obj, void *arg, int flags)
  951. {
  952. struct unidentified_request *unid = obj;
  953. struct ast_sip_cli_context *context = arg;
  954. int indent;
  955. int flexwidth;
  956. int64_t ms = ast_tvdiff_ms(ast_tvnow(), unid->first_seen);
  957. ast_assert(context->output_buffer != NULL);
  958. indent = CLI_INDENT_TO_SPACES(context->indent_level);
  959. flexwidth = CLI_LAST_TABSTOP - 4;
  960. ast_str_append(&context->output_buffer, 0, "%*s: %-*.*s %7d %10.3f\n",
  961. indent,
  962. "Request",
  963. flexwidth, flexwidth,
  964. unid->src_name, unid->count, ms / 1000.0);
  965. return 0;
  966. }
  967. static struct ast_cli_entry cli_commands[] = {
  968. AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Unidentified Requests",
  969. .command = "pjsip show unidentified_requests",
  970. .usage = "Usage: pjsip show unidentified_requests\n"
  971. " Show the PJSIP Unidentified Requests\n"),
  972. };
  973. struct ast_sip_cli_formatter_entry *unid_formatter;
  974. static int expire_requests(void *object, void *arg, int flags)
  975. {
  976. struct unidentified_request *unid = object;
  977. int *maxage = arg;
  978. int64_t ms = ast_tvdiff_ms(ast_tvnow(), unid->first_seen);
  979. if (ms > (*maxage) * 2 * 1000) {
  980. return CMP_MATCH;
  981. }
  982. return 0;
  983. }
  984. static int prune_task(const void *data)
  985. {
  986. unsigned int maxage;
  987. ast_sip_get_unidentified_request_thresholds(&unidentified_count, &unidentified_period, &unidentified_prune_interval);
  988. maxage = unidentified_period * 2;
  989. ao2_callback(unidentified_requests, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, expire_requests, &maxage);
  990. return unidentified_prune_interval * 1000;
  991. }
  992. static int clean_task(const void *data)
  993. {
  994. return 0;
  995. }
  996. static void global_loaded(const char *object_type)
  997. {
  998. char default_realm[MAX_REALM_LENGTH + 1];
  999. struct ast_sip_auth *fake_auth;
  1000. char *identifier_order;
  1001. /* Update using_auth_username */
  1002. identifier_order = ast_sip_get_endpoint_identifier_order();
  1003. if (identifier_order) {
  1004. char *identify_method;
  1005. char *io_copy = ast_strdupa(identifier_order);
  1006. int new_using = 0;
  1007. ast_free(identifier_order);
  1008. while ((identify_method = ast_strip(strsep(&io_copy, ",")))) {
  1009. if (!strcmp(identify_method, "auth_username")) {
  1010. new_using = 1;
  1011. break;
  1012. }
  1013. }
  1014. using_auth_username = new_using;
  1015. }
  1016. /* Update default_realm of artificial_auth */
  1017. ast_sip_get_default_realm(default_realm, sizeof(default_realm));
  1018. fake_auth = ast_sip_get_artificial_auth();
  1019. if (!fake_auth || strcmp(fake_auth->realm, default_realm)) {
  1020. ao2_cleanup(fake_auth);
  1021. fake_auth = alloc_artificial_auth(default_realm);
  1022. if (fake_auth) {
  1023. ao2_global_obj_replace_unref(artificial_auth, fake_auth);
  1024. }
  1025. }
  1026. ao2_cleanup(fake_auth);
  1027. ast_sip_get_unidentified_request_thresholds(&unidentified_count, &unidentified_period, &unidentified_prune_interval);
  1028. /* Clean out the old task, if any */
  1029. ast_sched_clean_by_callback(prune_context, prune_task, clean_task);
  1030. /* Have to do something with the return value to shut up the stupid compiler. */
  1031. if (ast_sched_add_variable(prune_context, unidentified_prune_interval * 1000, prune_task, NULL, 1) < 0) {
  1032. return;
  1033. }
  1034. }
  1035. /*! \brief Observer which is used to update our interval and default_realm when the global setting changes */
  1036. static struct ast_sorcery_observer global_observer = {
  1037. .loaded = global_loaded,
  1038. };
  1039. /*!
  1040. * \internal
  1041. * \brief Shutdown the serializers in the distributor pool.
  1042. * \since 13.10.0
  1043. *
  1044. * \return Nothing
  1045. */
  1046. static void distributor_pool_shutdown(void)
  1047. {
  1048. int idx;
  1049. for (idx = 0; idx < ARRAY_LEN(distributor_pool); ++idx) {
  1050. ast_taskprocessor_unreference(distributor_pool[idx]);
  1051. distributor_pool[idx] = NULL;
  1052. }
  1053. }
  1054. /*!
  1055. * \internal
  1056. * \brief Setup the serializers in the distributor pool.
  1057. * \since 13.10.0
  1058. *
  1059. * \retval 0 on success.
  1060. * \retval -1 on error.
  1061. */
  1062. static int distributor_pool_setup(void)
  1063. {
  1064. char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
  1065. int idx;
  1066. for (idx = 0; idx < ARRAY_LEN(distributor_pool); ++idx) {
  1067. /* Create name with seq number appended. */
  1068. ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/distributor");
  1069. distributor_pool[idx] = ast_sip_create_serializer_named(tps_name);
  1070. if (!distributor_pool[idx]) {
  1071. return -1;
  1072. }
  1073. }
  1074. return 0;
  1075. }
  1076. int ast_sip_initialize_distributor(void)
  1077. {
  1078. unidentified_requests = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK, 0,
  1079. DEFAULT_SUSPECTS_BUCKETS, suspects_hash, NULL, suspects_compare);
  1080. if (!unidentified_requests) {
  1081. return -1;
  1082. }
  1083. dialog_associations = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK, 0,
  1084. DIALOG_ASSOCIATIONS_BUCKETS, dialog_associations_hash, NULL,
  1085. dialog_associations_cmp);
  1086. if (!dialog_associations) {
  1087. ast_sip_destroy_distributor();
  1088. return -1;
  1089. }
  1090. if (distributor_pool_setup()) {
  1091. ast_sip_destroy_distributor();
  1092. return -1;
  1093. }
  1094. prune_context = ast_sched_context_create();
  1095. if (!prune_context) {
  1096. ast_sip_destroy_distributor();
  1097. return -1;
  1098. }
  1099. if (ast_sched_start_thread(prune_context)) {
  1100. ast_sip_destroy_distributor();
  1101. return -1;
  1102. }
  1103. ast_sorcery_observer_add(ast_sip_get_sorcery(), "global", &global_observer);
  1104. ast_sorcery_reload_object(ast_sip_get_sorcery(), "global");
  1105. if (create_artificial_endpoint() || create_artificial_auth()) {
  1106. ast_sip_destroy_distributor();
  1107. return -1;
  1108. }
  1109. if (internal_sip_register_service(&distributor_mod)) {
  1110. ast_sip_destroy_distributor();
  1111. return -1;
  1112. }
  1113. if (internal_sip_register_service(&endpoint_mod)) {
  1114. ast_sip_destroy_distributor();
  1115. return -1;
  1116. }
  1117. if (internal_sip_register_service(&auth_mod)) {
  1118. ast_sip_destroy_distributor();
  1119. return -1;
  1120. }
  1121. unid_formatter = ao2_alloc_options(sizeof(struct ast_sip_cli_formatter_entry), NULL,
  1122. AO2_ALLOC_OPT_LOCK_NOLOCK);
  1123. if (!unid_formatter) {
  1124. ast_sip_destroy_distributor();
  1125. ast_log(LOG_ERROR, "Unable to allocate memory for unid_formatter\n");
  1126. return -1;
  1127. }
  1128. unid_formatter->name = "unidentified_request";
  1129. unid_formatter->print_header = cli_unid_print_header;
  1130. unid_formatter->print_body = cli_unid_print_body;
  1131. unid_formatter->get_container = cli_unid_get_container;
  1132. unid_formatter->iterate = cli_unid_iterate;
  1133. unid_formatter->get_id = cli_unid_get_id;
  1134. unid_formatter->retrieve_by_id = cli_unid_retrieve_by_id;
  1135. ast_sip_register_cli_formatter(unid_formatter);
  1136. ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands));
  1137. return 0;
  1138. }
  1139. void ast_sip_destroy_distributor(void)
  1140. {
  1141. ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
  1142. ast_sip_unregister_cli_formatter(unid_formatter);
  1143. internal_sip_unregister_service(&auth_mod);
  1144. internal_sip_unregister_service(&endpoint_mod);
  1145. internal_sip_unregister_service(&distributor_mod);
  1146. ao2_global_obj_release(artificial_auth);
  1147. ao2_cleanup(artificial_endpoint);
  1148. ast_sorcery_observer_remove(ast_sip_get_sorcery(), "global", &global_observer);
  1149. if (prune_context) {
  1150. ast_sched_context_destroy(prune_context);
  1151. }
  1152. distributor_pool_shutdown();
  1153. ao2_cleanup(dialog_associations);
  1154. ao2_cleanup(unidentified_requests);
  1155. }