res_pjsip_registrar.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2013, 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_pjproject</depend>
  21. <depend>res_pjsip</depend>
  22. <support_level>core</support_level>
  23. ***/
  24. #include "asterisk.h"
  25. #include <signal.h>
  26. #include <pjsip.h>
  27. #include <pjsip_ua.h>
  28. #include "asterisk/res_pjsip.h"
  29. #include "asterisk/module.h"
  30. #include "asterisk/paths.h"
  31. #include "asterisk/test.h"
  32. #include "asterisk/taskprocessor.h"
  33. #include "asterisk/manager.h"
  34. #include "asterisk/named_locks.h"
  35. #include "asterisk/res_pjproject.h"
  36. #include "res_pjsip/include/res_pjsip_private.h"
  37. /*** DOCUMENTATION
  38. <manager name="PJSIPShowRegistrationsInbound" language="en_US">
  39. <synopsis>
  40. Lists PJSIP inbound registrations.
  41. </synopsis>
  42. <syntax />
  43. <description>
  44. <para>
  45. In response, <literal>InboundRegistrationDetail</literal> events showing configuration
  46. and status information are raised for all contacts, static or dynamic. Once all events
  47. are completed an <literal>InboundRegistrationDetailComplete</literal> is issued.
  48. </para>
  49. <warning><para>
  50. This command just dumps all coonfigured AORs with contacts, even if the contact
  51. is a permanent one. To really get just inbound registrations, use
  52. <literal>PJSIPShowRegistrationInboundContactStatuses</literal>.
  53. </para>
  54. </warning>
  55. </description>
  56. <see-also>
  57. <ref type="manager" module="res_pjsip_registrar">PJSIPShowRegistrationInboundContactStatuses</ref>
  58. </see-also>
  59. </manager>
  60. <manager name="PJSIPShowRegistrationInboundContactStatuses" language="en_US">
  61. <synopsis>
  62. Lists ContactStatuses for PJSIP inbound registrations.
  63. </synopsis>
  64. <syntax />
  65. <description>
  66. <para>
  67. In response, <literal>ContactStatusDetail</literal> events showing status information
  68. are raised for each inbound registration (dynamic contact) object. Once all events
  69. are completed a <literal>ContactStatusDetailComplete</literal> event is issued.
  70. </para>
  71. </description>
  72. </manager>
  73. ***/
  74. static int pj_max_hostname = PJ_MAX_HOSTNAME;
  75. static int pjsip_max_url_size = PJSIP_MAX_URL_SIZE;
  76. /*! \brief Internal function which returns the expiration time for a contact */
  77. static unsigned int registrar_get_expiration(const struct ast_sip_aor *aor, const pjsip_contact_hdr *contact, const pjsip_rx_data *rdata)
  78. {
  79. pjsip_expires_hdr *expires;
  80. unsigned int expiration = aor->default_expiration;
  81. if (contact && contact->expires != PJSIP_EXPIRES_NOT_SPECIFIED) {
  82. /* Expiration was provided with the contact itself */
  83. expiration = contact->expires;
  84. } else if ((expires = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL))) {
  85. /* Expiration was provided using the Expires header */
  86. expiration = expires->ivalue;
  87. }
  88. /* If the value has explicitly been set to 0, do not enforce */
  89. if (!expiration) {
  90. return expiration;
  91. }
  92. /* Enforce the range that we will allow for expiration */
  93. if (expiration < aor->minimum_expiration) {
  94. expiration = aor->minimum_expiration;
  95. } else if (expiration > aor->maximum_expiration) {
  96. expiration = aor->maximum_expiration;
  97. }
  98. return expiration;
  99. }
  100. /*! \brief Structure used for finding contact */
  101. struct registrar_contact_details {
  102. /*! \brief Pool used for parsing URI */
  103. pj_pool_t *pool;
  104. /*! \brief URI being looked for */
  105. pjsip_sip_uri *uri;
  106. };
  107. /*! \brief Callback function for finding a contact */
  108. static int registrar_find_contact(void *obj, void *arg, int flags)
  109. {
  110. struct ast_sip_contact *contact = obj;
  111. const struct registrar_contact_details *details = arg;
  112. pjsip_uri *contact_uri;
  113. if (ast_tvzero(contact->expiration_time)) {
  114. return 0;
  115. }
  116. contact_uri = pjsip_parse_uri(details->pool, (char*)contact->uri, strlen(contact->uri), 0);
  117. if (!contact_uri) {
  118. ast_log(LOG_WARNING, "Unable to parse contact URI from '%s'.\n", contact->uri);
  119. return 0;
  120. }
  121. return (pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, details->uri, contact_uri) == PJ_SUCCESS) ? CMP_MATCH : 0;
  122. }
  123. /*! \brief Internal function which validates provided Contact headers to confirm that they are acceptable, and returns number of contacts */
  124. static int registrar_validate_contacts(const pjsip_rx_data *rdata, pj_pool_t *pool, struct ao2_container *contacts,
  125. struct ast_sip_aor *aor, int permanent, int *added, int *updated, int *deleted)
  126. {
  127. pjsip_contact_hdr *previous = NULL;
  128. pjsip_contact_hdr *contact = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
  129. struct registrar_contact_details details = {
  130. .pool = pool,
  131. };
  132. for (; (contact = (pjsip_contact_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact->next)); pj_pool_reset(pool)) {
  133. unsigned int expiration = registrar_get_expiration(aor, contact, rdata);
  134. struct ast_sip_contact *existing;
  135. char contact_uri[pjsip_max_url_size];
  136. if (contact->star) {
  137. /* The expiration MUST be 0 when a '*' contact is used and there must be no other contact */
  138. if (expiration != 0 || previous) {
  139. return -1;
  140. }
  141. /* Count all contacts to delete */
  142. *deleted = ao2_container_count(contacts) - permanent;
  143. previous = contact;
  144. continue;
  145. } else if (previous && previous->star) {
  146. /* If there is a previous contact and it is a '*' this is a deal breaker */
  147. return -1;
  148. }
  149. previous = contact;
  150. if (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri)) {
  151. continue;
  152. }
  153. details.uri = pjsip_uri_get_uri(contact->uri);
  154. /* pjsip_uri_print returns -1 if there's not enough room in the buffer */
  155. if (pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri)) < 0) {
  156. /* If the total length of the uri is greater than pjproject can handle, go no further */
  157. return -1;
  158. }
  159. if (details.uri->host.slen >= pj_max_hostname) {
  160. /* If the length of the hostname is greater than pjproject can handle, go no further */
  161. return -1;
  162. }
  163. /* Determine if this is an add, update, or delete for policy enforcement purposes */
  164. existing = ao2_callback(contacts, 0, registrar_find_contact, &details);
  165. ao2_cleanup(existing);
  166. if (!existing) {
  167. if (expiration) {
  168. ++*added;
  169. }
  170. } else if (expiration) {
  171. ++*updated;
  172. } else {
  173. ++*deleted;
  174. }
  175. }
  176. return 0;
  177. }
  178. enum contact_delete_type {
  179. CONTACT_DELETE_ERROR,
  180. CONTACT_DELETE_EXISTING,
  181. CONTACT_DELETE_UNAVAILABLE,
  182. CONTACT_DELETE_EXPIRE,
  183. CONTACT_DELETE_REQUEST,
  184. CONTACT_DELETE_SHUTDOWN,
  185. };
  186. static int registrar_contact_delete(enum contact_delete_type type, pjsip_transport *transport,
  187. struct ast_sip_contact *contact, const char *aor_name);
  188. /*! \brief Internal function used to delete a contact from an AOR */
  189. static int registrar_delete_contact(void *obj, void *arg, int flags)
  190. {
  191. return registrar_contact_delete(
  192. CONTACT_DELETE_REQUEST, NULL, obj, arg) ? 0 : CMP_MATCH;
  193. }
  194. /*! \brief Internal function which adds a contact to a response */
  195. static int registrar_add_contact(void *obj, void *arg, int flags)
  196. {
  197. struct ast_sip_contact *contact = obj;
  198. pjsip_tx_data *tdata = arg;
  199. pj_str_t uri;
  200. pjsip_uri *parsed;
  201. pj_strdup2_with_null(tdata->pool, &uri, contact->uri);
  202. parsed = pjsip_parse_uri(tdata->pool, uri.ptr, uri.slen, PJSIP_PARSE_URI_AS_NAMEADDR);
  203. if (parsed && (PJSIP_URI_SCHEME_IS_SIP(parsed) || PJSIP_URI_SCHEME_IS_SIPS(parsed))) {
  204. pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(tdata->pool);
  205. hdr->uri = parsed;
  206. if (!ast_tvzero(contact->expiration_time)) {
  207. hdr->expires = ast_tvdiff_ms(contact->expiration_time, ast_tvnow()) / 1000;
  208. } else {
  209. hdr->expires = PJSIP_EXPIRES_NOT_SPECIFIED;
  210. }
  211. pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) hdr);
  212. } else {
  213. ast_log(LOG_WARNING, "Skipping invalid Contact URI \"%.*s\" for AOR %s\n",
  214. (int) uri.slen, uri.ptr, contact->aor);
  215. }
  216. return 0;
  217. }
  218. static const pj_str_t path_hdr_name = { "Path", 4 };
  219. static int build_path_data(pjsip_rx_data *rdata, struct ast_str **path_str)
  220. {
  221. pjsip_generic_string_hdr *path_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &path_hdr_name, NULL);
  222. if (!path_hdr) {
  223. return 0;
  224. }
  225. *path_str = ast_str_create(64);
  226. if (!*path_str) {
  227. return -1;
  228. }
  229. ast_str_set(path_str, 0, "%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
  230. while ((path_hdr = (pjsip_generic_string_hdr *) pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &path_hdr_name, path_hdr->next))) {
  231. ast_str_append(path_str, 0, ",%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
  232. }
  233. return 0;
  234. }
  235. static int registrar_validate_path(pjsip_rx_data *rdata, struct ast_sip_aor *aor, struct ast_str **path_str)
  236. {
  237. const pj_str_t path_supported_name = { "path", 4 };
  238. pjsip_supported_hdr *supported_hdr;
  239. int i;
  240. if (!aor->support_path) {
  241. return 0;
  242. }
  243. if (build_path_data(rdata, path_str)) {
  244. return -1;
  245. }
  246. if (!*path_str) {
  247. return 0;
  248. }
  249. supported_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_SUPPORTED, NULL);
  250. if (!supported_hdr) {
  251. return -1;
  252. }
  253. /* Find advertised path support */
  254. for (i = 0; i < supported_hdr->count; i++) {
  255. if (!pj_stricmp(&supported_hdr->values[i], &path_supported_name)) {
  256. return 0;
  257. }
  258. }
  259. /* Path header present, but support not advertised */
  260. return -1;
  261. }
  262. /*! Transport monitor for incoming REGISTER contacts */
  263. struct contact_transport_monitor {
  264. /*!
  265. * \brief Sorcery contact name to remove on transport shutdown
  266. * \note Stored after aor_name in space reserved when struct allocated.
  267. */
  268. char *contact_name;
  269. /*! Indicates that the monitor is in the process of removing a contact */
  270. int removing;
  271. /*! AOR name the contact is associated */
  272. char aor_name[0];
  273. };
  274. static int contact_transport_monitor_matcher(void *a, void *b)
  275. {
  276. struct contact_transport_monitor *ma = a;
  277. struct contact_transport_monitor *mb = b;
  278. return strcmp(ma->aor_name, mb->aor_name) == 0
  279. && strcmp(ma->contact_name, mb->contact_name) == 0;
  280. }
  281. static int register_contact_transport_remove_cb(void *data)
  282. {
  283. struct contact_transport_monitor *monitor = data;
  284. struct ast_sip_contact *contact;
  285. struct ast_sip_aor *aor;
  286. aor = ast_sip_location_retrieve_aor(monitor->aor_name);
  287. if (!aor) {
  288. ao2_lock(monitor);
  289. monitor->removing = 0;
  290. ao2_unlock(monitor);
  291. ao2_ref(monitor, -1);
  292. return 0;
  293. }
  294. ao2_lock(aor);
  295. contact = ast_sip_location_retrieve_contact(monitor->contact_name);
  296. if (contact) {
  297. registrar_contact_delete(CONTACT_DELETE_SHUTDOWN, NULL, contact, monitor->aor_name);
  298. ao2_ref(contact, -1);
  299. }
  300. ao2_unlock(aor);
  301. ao2_ref(aor, -1);
  302. ao2_ref(monitor, -1);
  303. return 0;
  304. }
  305. /*!
  306. * \internal
  307. * \brief The reliable transport we registered as a contact has shutdown.
  308. *
  309. * \param data What contact needs to be removed.
  310. *
  311. * \note Normally executed by the pjsip monitor thread.
  312. */
  313. static void register_contact_transport_shutdown_cb(void *data)
  314. {
  315. struct contact_transport_monitor *monitor = data;
  316. /*
  317. * It's possible for this shutdown handler to get called multiple times for the
  318. * same monitor from different threads. Only one of the calls needs to do the
  319. * actual removing of the contact, so if one is currently removing then any
  320. * subsequent calls can skip.
  321. */
  322. ao2_lock(monitor);
  323. if (monitor->removing) {
  324. ao2_unlock(monitor);
  325. return;
  326. }
  327. monitor->removing = 1;
  328. /*
  329. * Push off to a default serializer. This is in case sorcery
  330. * does database accesses for contacts. Database accesses may
  331. * not be on this machine. We don't want to tie up the pjsip
  332. * monitor thread with potentially long access times.
  333. */
  334. ao2_ref(monitor, +1);
  335. if (ast_sip_push_task(NULL, register_contact_transport_remove_cb, monitor)) {
  336. monitor->removing = 0;
  337. ao2_ref(monitor, -1);
  338. }
  339. ao2_unlock(monitor);
  340. }
  341. static int registrar_contact_delete(enum contact_delete_type type, pjsip_transport *transport,
  342. struct ast_sip_contact *contact, const char *aor_name)
  343. {
  344. int aor_size;
  345. /* Permanent contacts can't be deleted */
  346. if (ast_tvzero(contact->expiration_time)) {
  347. return -1;
  348. }
  349. aor_size = aor_name ? strlen(aor_name) : 0;
  350. if (contact->prune_on_boot && type != CONTACT_DELETE_SHUTDOWN && aor_size) {
  351. const char *contact_name = ast_sorcery_object_get_id(contact);
  352. size_t contact_name_len = strlen(contact_name) + 1;
  353. struct contact_transport_monitor *monitor = ast_alloca(
  354. sizeof(*monitor) + 1 + aor_size + contact_name_len);
  355. strcpy(monitor->aor_name, aor_name); /* Safe */
  356. monitor->contact_name = monitor->aor_name + aor_size + 1;
  357. ast_copy_string(monitor->contact_name, contact_name, contact_name_len); /* Safe */
  358. if (transport) {
  359. ast_sip_transport_monitor_unregister(transport,
  360. register_contact_transport_shutdown_cb, monitor,
  361. contact_transport_monitor_matcher);
  362. } else {
  363. /*
  364. * If a specific transport is not supplied then unregister the matching
  365. * monitor from all reliable transports.
  366. */
  367. ast_sip_transport_monitor_unregister_all(register_contact_transport_shutdown_cb,
  368. monitor, contact_transport_monitor_matcher);
  369. }
  370. }
  371. ast_sip_location_delete_contact(contact);
  372. if (aor_size) {
  373. if (VERBOSITY_ATLEAST(3)) {
  374. const char *reason = "none";
  375. switch (type) {
  376. case CONTACT_DELETE_ERROR:
  377. reason = "registration failure";
  378. break;
  379. case CONTACT_DELETE_EXISTING:
  380. reason = "remove existing";
  381. break;
  382. case CONTACT_DELETE_UNAVAILABLE:
  383. reason = "remove unavailable";
  384. break;
  385. case CONTACT_DELETE_EXPIRE:
  386. reason = "expiration";
  387. break;
  388. case CONTACT_DELETE_REQUEST:
  389. reason = "request";
  390. break;
  391. case CONTACT_DELETE_SHUTDOWN:
  392. reason = "shutdown";
  393. break;
  394. }
  395. ast_verb(3, "Removed contact '%s' from AOR '%s' due to %s\n",
  396. contact->uri, aor_name, reason);
  397. }
  398. ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
  399. "Contact: %s\r\n"
  400. "AOR: %s\r\n"
  401. "UserAgent: %s",
  402. contact->uri,
  403. aor_name,
  404. contact->user_agent);
  405. }
  406. return 0;
  407. }
  408. AST_VECTOR(excess_contact_vector, struct ast_sip_contact *);
  409. static int vec_contact_cmp(struct ast_sip_contact *left, struct ast_sip_contact *right)
  410. {
  411. struct ast_sip_contact *left_contact = left;
  412. struct ast_sip_contact *right_contact = right;
  413. /* Sort from soonest to expire to last to expire */
  414. int time_sorted = ast_tvcmp(left_contact->expiration_time, right_contact->expiration_time);
  415. struct ast_sip_aor *aor = ast_sip_location_retrieve_aor(left_contact->aor);
  416. struct ast_sip_contact_status *left_status;
  417. struct ast_sip_contact_status *right_status;
  418. int remove_unavailable = 0;
  419. int left_unreachable;
  420. int right_unreachable;
  421. if (aor) {
  422. remove_unavailable = aor->remove_unavailable;
  423. ao2_ref(aor, -1);
  424. }
  425. if (!remove_unavailable) {
  426. return time_sorted;
  427. }
  428. /* Get contact status if available */
  429. left_status = ast_sip_get_contact_status(left_contact);
  430. if (!left_status) {
  431. return time_sorted;
  432. }
  433. right_status = ast_sip_get_contact_status(right_contact);
  434. if (!right_status) {
  435. ao2_ref(left_status, -1);
  436. return time_sorted;
  437. }
  438. left_unreachable = (left_status->status == UNAVAILABLE);
  439. right_unreachable = (right_status->status == UNAVAILABLE);
  440. ao2_ref(left_status, -1);
  441. ao2_ref(right_status, -1);
  442. if (left_unreachable != right_unreachable) {
  443. /* Set unavailable contact to top of vector */
  444. if (left_unreachable) return -1;
  445. if (right_unreachable) return 1;
  446. }
  447. /* Either both available or both unavailable */
  448. return time_sorted;
  449. }
  450. static int vec_contact_add(void *obj, void *arg, int flags)
  451. {
  452. struct ast_sip_contact *contact = obj;
  453. struct excess_contact_vector *contact_vec = arg;
  454. /*
  455. * Performance wise, an insertion sort is fine because we
  456. * shouldn't need to remove more than a handful of contacts.
  457. * I expect we'll typically be removing only one contact.
  458. */
  459. AST_VECTOR_ADD_SORTED(contact_vec, contact, vec_contact_cmp);
  460. if (AST_VECTOR_SIZE(contact_vec) == AST_VECTOR_MAX_SIZE(contact_vec)) {
  461. /*
  462. * We added a contact over the number we need to remove.
  463. * Remove the longest to expire contact from the vector
  464. * which is the last element in the vector. It may be
  465. * the one we just added or the one we just added pushed
  466. * out an earlier contact from removal consideration.
  467. */
  468. --AST_VECTOR_SIZE(contact_vec);
  469. }
  470. return 0;
  471. }
  472. /*!
  473. * \internal
  474. * \brief Remove excess existing contacts that are unavailable or expire soonest.
  475. * \since 13.18.0
  476. *
  477. * \param contacts Container of unmodified contacts that could remove.
  478. * \param to_remove Maximum number of contacts to remove.
  479. * \param response_contacts, remove_existing
  480. */
  481. static void remove_excess_contacts(struct ao2_container *contacts, struct ao2_container *response_contacts,
  482. unsigned int to_remove, unsigned int remove_existing)
  483. {
  484. struct excess_contact_vector contact_vec;
  485. /*
  486. * Create a sorted vector to hold the to_remove soonest to
  487. * expire contacts. The vector has an extra space to
  488. * temporarily hold the longest to expire contact that we
  489. * won't remove.
  490. */
  491. if (AST_VECTOR_INIT(&contact_vec, to_remove + 1)) {
  492. return;
  493. }
  494. ao2_callback(contacts, OBJ_NODATA | OBJ_MULTIPLE, vec_contact_add, &contact_vec);
  495. /*
  496. * The vector should always be populated with the number
  497. * of contacts we need to remove. Just in case, we will
  498. * remove all contacts in the vector even if the contacts
  499. * container had fewer contacts than there should be.
  500. */
  501. ast_assert(AST_VECTOR_SIZE(&contact_vec) == to_remove);
  502. to_remove = AST_VECTOR_SIZE(&contact_vec);
  503. /* Remove the excess contacts that are unavailable or expire the soonest */
  504. while (to_remove--) {
  505. struct ast_sip_contact *contact;
  506. contact = AST_VECTOR_GET(&contact_vec, to_remove);
  507. if (!remove_existing) {
  508. registrar_contact_delete(CONTACT_DELETE_UNAVAILABLE, NULL, contact, contact->aor);
  509. } else {
  510. registrar_contact_delete(CONTACT_DELETE_EXISTING, NULL, contact, contact->aor);
  511. }
  512. ao2_unlink(response_contacts, contact);
  513. }
  514. AST_VECTOR_FREE(&contact_vec);
  515. }
  516. /*! \brief Callback function which adds non-permanent contacts to a container */
  517. static int registrar_add_non_permanent(void *obj, void *arg, int flags)
  518. {
  519. struct ast_sip_contact *contact = obj;
  520. struct ao2_container *container = arg;
  521. if (ast_tvzero(contact->expiration_time)) {
  522. return 0;
  523. }
  524. ao2_link(container, contact);
  525. return 0;
  526. }
  527. /*! \brief Internal callback function which adds any contact which is unreachable */
  528. static int registrar_add_unreachable(void *obj, void *arg, int flags)
  529. {
  530. struct ast_sip_contact *contact = obj;
  531. struct ao2_container *container = arg;
  532. struct ast_sip_contact_status *status;
  533. int unreachable;
  534. status = ast_sip_get_contact_status(contact);
  535. if (!status) {
  536. return 0;
  537. }
  538. unreachable = (status->status == UNAVAILABLE);
  539. ao2_ref(status, -1);
  540. if (unreachable) {
  541. ao2_link(container, contact);
  542. }
  543. return 0;
  544. }
  545. struct aor_core_response {
  546. /*! Tx data to use for statefull response. NULL for stateless response. */
  547. pjsip_tx_data *tdata;
  548. /*! SIP response code to send in stateless response */
  549. int code;
  550. };
  551. static void register_aor_core(pjsip_rx_data *rdata,
  552. struct ast_sip_endpoint *endpoint,
  553. struct ast_sip_aor *aor,
  554. const char *aor_name,
  555. struct ao2_container *contacts,
  556. struct aor_core_response *response)
  557. {
  558. static const pj_str_t USER_AGENT = { "User-Agent", 10 };
  559. int added = 0;
  560. int updated = 0;
  561. int deleted = 0;
  562. int permanent = 0;
  563. int contact_count;
  564. struct ao2_container *existing_contacts = NULL;
  565. struct ao2_container *unavail_contacts = NULL;
  566. pjsip_contact_hdr *contact_hdr = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
  567. struct registrar_contact_details details = { 0, };
  568. pjsip_tx_data *tdata;
  569. RAII_VAR(struct ast_str *, path_str, NULL, ast_free);
  570. struct ast_sip_contact *response_contact;
  571. char *user_agent = NULL;
  572. pjsip_user_agent_hdr *user_agent_hdr;
  573. pjsip_expires_hdr *expires_hdr;
  574. pjsip_via_hdr *via_hdr;
  575. pjsip_via_hdr *via_hdr_last;
  576. char *via_addr = NULL;
  577. int via_port = 0;
  578. pjsip_cid_hdr *call_id_hdr;
  579. char *call_id = NULL;
  580. size_t alloc_size;
  581. /* We create a single pool and use it throughout this function where we need one */
  582. details.pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(),
  583. "Contact Comparison", 1024, 256);
  584. if (!details.pool) {
  585. response->code = 500;
  586. return;
  587. }
  588. /* If there are any permanent contacts configured on the AOR we need to take them
  589. * into account when counting contacts.
  590. */
  591. if (aor->permanent_contacts) {
  592. permanent = ao2_container_count(aor->permanent_contacts);
  593. }
  594. if (registrar_validate_contacts(rdata, details.pool, contacts, aor, permanent, &added, &updated, &deleted)) {
  595. /* The provided Contact headers do not conform to the specification */
  596. ast_sip_report_failed_acl(endpoint, rdata, "registrar_invalid_contacts_provided");
  597. ast_log(LOG_WARNING, "Failed to validate contacts in REGISTER request from '%s'\n",
  598. ast_sorcery_object_get_id(endpoint));
  599. response->code = 400;
  600. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
  601. return;
  602. }
  603. if (registrar_validate_path(rdata, aor, &path_str)) {
  604. /* Ensure that intervening proxies did not make invalid modifications to the request */
  605. ast_log(LOG_WARNING, "Invalid modifications made to REGISTER request from '%s' by intervening proxy\n",
  606. ast_sorcery_object_get_id(endpoint));
  607. response->code = 420;
  608. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
  609. return;
  610. }
  611. if (aor->remove_existing) {
  612. /* Cumulative number of contacts affected by this registration */
  613. contact_count = MAX(updated + added - deleted, 0);
  614. /* We need to keep track of only existing contacts so we can later
  615. * remove them if need be.
  616. */
  617. existing_contacts = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
  618. NULL, ast_sorcery_object_id_compare);
  619. if (!existing_contacts) {
  620. response->code = 500;
  621. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
  622. return;
  623. }
  624. ao2_callback(contacts, OBJ_NODATA, registrar_add_non_permanent, existing_contacts);
  625. } else {
  626. /* Total contacts after this registration */
  627. contact_count = ao2_container_count(contacts) - permanent + added - deleted;
  628. }
  629. if (contact_count > aor->max_contacts && aor->remove_unavailable) {
  630. /* Get unavailable contact total */
  631. int unavail_count = 0;
  632. unavail_contacts = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
  633. NULL, ast_sorcery_object_id_compare);
  634. if (!unavail_contacts) {
  635. response->code = 500;
  636. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
  637. return;
  638. }
  639. ao2_callback(contacts, OBJ_NODATA, registrar_add_unreachable, unavail_contacts);
  640. if (unavail_contacts) {
  641. unavail_count = ao2_container_count(unavail_contacts);
  642. }
  643. /* Check to see if removing unavailable contacts will help */
  644. if (contact_count - unavail_count <= aor->max_contacts) {
  645. /* Remove any unavailable contacts */
  646. remove_excess_contacts(unavail_contacts, contacts, contact_count - aor->max_contacts, aor->remove_existing);
  647. ao2_cleanup(unavail_contacts);
  648. /* We're only here if !aor->remove_existing so this count is correct */
  649. contact_count = ao2_container_count(contacts) - permanent + added - deleted;
  650. }
  651. }
  652. if (contact_count > aor->max_contacts) {
  653. /* Enforce the maximum number of contacts */
  654. ast_sip_report_failed_acl(endpoint, rdata, "registrar_attempt_exceeds_maximum_configured_contacts");
  655. ast_log(LOG_WARNING, "Registration attempt from endpoint '%s' (%s:%d) to AOR '%s' will exceed max contacts of %u\n",
  656. ast_sorcery_object_get_id(endpoint), rdata->pkt_info.src_name, rdata->pkt_info.src_port,
  657. aor_name, aor->max_contacts);
  658. response->code = 403;
  659. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
  660. ao2_cleanup(existing_contacts);
  661. return;
  662. }
  663. user_agent_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &USER_AGENT, NULL);
  664. if (user_agent_hdr) {
  665. alloc_size = pj_strlen(&user_agent_hdr->hvalue) + 1;
  666. user_agent = ast_alloca(alloc_size);
  667. ast_copy_pj_str(user_agent, &user_agent_hdr->hvalue, alloc_size);
  668. }
  669. /* Find the first Via header */
  670. via_hdr = via_hdr_last = (pjsip_via_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_VIA, NULL);
  671. if (via_hdr) {
  672. /* Find the last Via header */
  673. while ( (via_hdr = (pjsip_via_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg,
  674. PJSIP_H_VIA, via_hdr->next)) != NULL) {
  675. via_hdr_last = via_hdr;
  676. }
  677. alloc_size = pj_strlen(&via_hdr_last->sent_by.host) + 1;
  678. via_addr = ast_alloca(alloc_size);
  679. ast_copy_pj_str(via_addr, &via_hdr_last->sent_by.host, alloc_size);
  680. via_port=via_hdr_last->sent_by.port;
  681. }
  682. call_id_hdr = (pjsip_cid_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CALL_ID, NULL);
  683. if (call_id_hdr) {
  684. alloc_size = pj_strlen(&call_id_hdr->id) + 1;
  685. call_id = ast_alloca(alloc_size);
  686. ast_copy_pj_str(call_id, &call_id_hdr->id, alloc_size);
  687. }
  688. /* Iterate each provided Contact header and add, update, or delete */
  689. for (; (contact_hdr = (pjsip_contact_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact_hdr->next)); pj_pool_reset(details.pool)) {
  690. int expiration;
  691. char contact_uri[pjsip_max_url_size];
  692. RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
  693. if (contact_hdr->star) {
  694. /* A star means to unregister everything, so do so for the possible contacts */
  695. ao2_callback(contacts, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
  696. registrar_delete_contact, (void *)aor_name);
  697. /* If we are keeping track of existing contacts for removal then, well, there is
  698. * absolutely nothing left so no need to try to remove any.
  699. */
  700. if (existing_contacts) {
  701. ao2_ref(existing_contacts, -1);
  702. existing_contacts = NULL;
  703. }
  704. break;
  705. }
  706. if (!PJSIP_URI_SCHEME_IS_SIP(contact_hdr->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact_hdr->uri)) {
  707. /* This registrar only currently supports sip: and sips: URI schemes */
  708. continue;
  709. }
  710. expiration = registrar_get_expiration(aor, contact_hdr, rdata);
  711. details.uri = pjsip_uri_get_uri(contact_hdr->uri);
  712. pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri));
  713. contact = ao2_callback(contacts, OBJ_UNLINK, registrar_find_contact, &details);
  714. /* If a contact was returned and we need to keep track of existing contacts then it
  715. * should be removed.
  716. */
  717. if (contact && existing_contacts) {
  718. ao2_unlink(existing_contacts, contact);
  719. }
  720. if (!contact) {
  721. int prune_on_boot;
  722. /* If they are actually trying to delete a contact that does not exist... be forgiving */
  723. if (!expiration) {
  724. ast_verb(3, "Attempted to remove non-existent contact '%s' from AOR '%s' by request\n",
  725. contact_uri, aor_name);
  726. continue;
  727. }
  728. prune_on_boot = !ast_sip_will_uri_survive_restart(details.uri, endpoint, rdata);
  729. contact = ast_sip_location_create_contact(aor, contact_uri,
  730. ast_tvadd(ast_tvnow(), ast_samp2tv(expiration, 1)),
  731. path_str ? ast_str_buffer(path_str) : NULL,
  732. user_agent, via_addr, via_port, call_id, prune_on_boot, endpoint);
  733. if (!contact) {
  734. ast_log(LOG_ERROR, "Unable to bind contact '%s' to AOR '%s'\n",
  735. contact_uri, aor_name);
  736. continue;
  737. }
  738. if (prune_on_boot) {
  739. size_t contact_name_len;
  740. const char *contact_name;
  741. struct contact_transport_monitor *monitor;
  742. /*
  743. * Monitor the transport in case it gets disconnected because
  744. * the contact won't be valid anymore if that happens.
  745. */
  746. contact_name = ast_sorcery_object_get_id(contact);
  747. contact_name_len = strlen(contact_name) + 1;
  748. monitor = ao2_alloc(sizeof(*monitor) + 1 + strlen(aor_name)
  749. + contact_name_len, NULL);
  750. if (monitor) {
  751. strcpy(monitor->aor_name, aor_name);/* Safe */
  752. monitor->contact_name = monitor->aor_name + strlen(aor_name) + 1;
  753. ast_copy_string(monitor->contact_name, contact_name, contact_name_len);/* Safe */
  754. ast_sip_transport_monitor_register_replace(rdata->tp_info.transport,
  755. register_contact_transport_shutdown_cb, monitor, contact_transport_monitor_matcher);
  756. ao2_ref(monitor, -1);
  757. }
  758. }
  759. ast_verb(3, "Added contact '%s' to AOR '%s' with expiration of %d seconds\n",
  760. contact_uri, aor_name, expiration);
  761. ast_test_suite_event_notify("AOR_CONTACT_ADDED",
  762. "Contact: %s\r\n"
  763. "AOR: %s\r\n"
  764. "Expiration: %d\r\n"
  765. "UserAgent: %s",
  766. contact_uri,
  767. aor_name,
  768. expiration,
  769. user_agent);
  770. ao2_link(contacts, contact);
  771. } else if (expiration) {
  772. struct ast_sip_contact *contact_update;
  773. contact_update = ast_sorcery_copy(ast_sip_get_sorcery(), contact);
  774. if (!contact_update) {
  775. ast_log(LOG_ERROR, "Failed to update contact '%s' expiration time to %d seconds.\n",
  776. contact->uri, expiration);
  777. continue;
  778. }
  779. contact_update->expiration_time = ast_tvadd(ast_tvnow(), ast_samp2tv(expiration, 1));
  780. contact_update->qualify_frequency = aor->qualify_frequency;
  781. contact_update->authenticate_qualify = aor->authenticate_qualify;
  782. if (path_str) {
  783. ast_string_field_set(contact_update, path, ast_str_buffer(path_str));
  784. }
  785. if (user_agent) {
  786. ast_string_field_set(contact_update, user_agent, user_agent);
  787. }
  788. if (!ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
  789. ast_string_field_set(contact_update, reg_server, ast_config_AST_SYSTEM_NAME);
  790. }
  791. if (ast_sip_location_update_contact(contact_update)) {
  792. ast_log(LOG_ERROR, "Failed to update contact '%s' expiration time to %d seconds.\n",
  793. contact->uri, expiration);
  794. registrar_contact_delete(CONTACT_DELETE_ERROR, rdata->tp_info.transport,
  795. contact, aor_name);
  796. continue;
  797. }
  798. ast_debug(3, "Refreshed contact '%s' on AOR '%s' with new expiration of %d seconds\n",
  799. contact_uri, aor_name, expiration);
  800. ast_test_suite_event_notify("AOR_CONTACT_REFRESHED",
  801. "Contact: %s\r\n"
  802. "AOR: %s\r\n"
  803. "Expiration: %d\r\n"
  804. "UserAgent: %s",
  805. contact_uri,
  806. aor_name,
  807. expiration,
  808. contact_update->user_agent);
  809. ao2_link(contacts, contact_update);
  810. ao2_cleanup(contact_update);
  811. } else {
  812. registrar_contact_delete(CONTACT_DELETE_REQUEST, rdata->tp_info.transport,
  813. contact, aor_name);
  814. }
  815. }
  816. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
  817. /*
  818. * If the AOR is configured to remove any contacts over max_contacts
  819. * that have not been updated/added/deleted as a result of this
  820. * REGISTER do so.
  821. *
  822. * The existing contacts container holds all contacts that were not
  823. * involved in this REGISTER.
  824. * The contacts container holds the current contacts of the AOR.
  825. */
  826. if (aor->remove_existing && existing_contacts) {
  827. /* Total contacts after this registration */
  828. contact_count = ao2_container_count(existing_contacts) + updated + added;
  829. if (contact_count > aor->max_contacts) {
  830. /* Remove excess existing contacts that are unavailable or expire soonest */
  831. remove_excess_contacts(existing_contacts, contacts, contact_count - aor->max_contacts,
  832. aor->remove_existing);
  833. }
  834. ao2_ref(existing_contacts, -1);
  835. }
  836. response_contact = ao2_callback(contacts, 0, NULL, NULL);
  837. /* Send a response containing all of the contacts (including static) that are present on this AOR */
  838. if (ast_sip_create_response(rdata, 200, response_contact, &tdata) != PJ_SUCCESS) {
  839. ao2_cleanup(response_contact);
  840. ao2_cleanup(contacts);
  841. response->code = 500;
  842. return;
  843. }
  844. ao2_cleanup(response_contact);
  845. /* Add the date header to the response, some UAs use this to set their date and time */
  846. ast_sip_add_date_header(tdata);
  847. ao2_callback(contacts, 0, registrar_add_contact, tdata);
  848. if ((expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL))) {
  849. expires_hdr = pjsip_expires_hdr_create(tdata->pool, registrar_get_expiration(aor, NULL, rdata));
  850. pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)expires_hdr);
  851. }
  852. response->tdata = tdata;
  853. }
  854. static int register_aor(pjsip_rx_data *rdata,
  855. struct ast_sip_endpoint *endpoint,
  856. struct ast_sip_aor *aor,
  857. const char *aor_name)
  858. {
  859. struct aor_core_response response = {
  860. .code = 500,
  861. };
  862. struct ao2_container *contacts = NULL;
  863. ao2_lock(aor);
  864. contacts = ast_sip_location_retrieve_aor_contacts_nolock(aor);
  865. if (!contacts) {
  866. ao2_unlock(aor);
  867. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(),
  868. rdata, response.code, NULL, NULL, NULL);
  869. return PJ_TRUE;
  870. }
  871. register_aor_core(rdata, endpoint, aor, aor_name, contacts, &response);
  872. ao2_cleanup(contacts);
  873. ao2_unlock(aor);
  874. /* Now send the REGISTER response to the peer */
  875. if (response.tdata) {
  876. ast_sip_send_stateful_response(rdata, response.tdata, endpoint);
  877. } else {
  878. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(),
  879. rdata, response.code, NULL, NULL, NULL);
  880. }
  881. return PJ_TRUE;
  882. }
  883. static int match_aor(const char *aor_name, const char *id)
  884. {
  885. if (ast_strlen_zero(aor_name)) {
  886. return 0;
  887. }
  888. if (!strcmp(aor_name, id)) {
  889. ast_debug(3, "Matched id '%s' to aor '%s'\n", id, aor_name);
  890. return 1;
  891. }
  892. return 0;
  893. }
  894. static char *find_aor_name(const pj_str_t *pj_username, const pj_str_t *pj_domain, const char *aors)
  895. {
  896. char *configured_aors;
  897. char *aors_buf;
  898. char *aor_name;
  899. char *id_domain;
  900. char *username, *domain;
  901. struct ast_sip_domain_alias *alias;
  902. /* Turn these into C style strings for convenience */
  903. username = ast_alloca(pj_strlen(pj_username) + 1);
  904. ast_copy_pj_str(username, pj_username, pj_strlen(pj_username) + 1);
  905. domain = ast_alloca(pj_strlen(pj_domain) + 1);
  906. ast_copy_pj_str(domain, pj_domain, pj_strlen(pj_domain) + 1);
  907. id_domain = ast_alloca(strlen(username) + strlen(domain) + 2);
  908. sprintf(id_domain, "%s@%s", username, domain);
  909. aors_buf = ast_strdupa(aors);
  910. /* Look for exact match on username@domain */
  911. configured_aors = aors_buf;
  912. while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
  913. if (match_aor(aor_name, id_domain)) {
  914. return ast_strdup(aor_name);
  915. }
  916. }
  917. /* If there's a domain alias, look for exact match on username@domain_alias */
  918. alias = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "domain_alias", domain);
  919. if (alias) {
  920. char *id_domain_alias = ast_alloca(strlen(username) + strlen(alias->domain) + 2);
  921. sprintf(id_domain_alias, "%s@%s", username, alias->domain);
  922. ao2_cleanup(alias);
  923. configured_aors = strcpy(aors_buf, aors);/* Safe */
  924. while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
  925. if (match_aor(aor_name, id_domain_alias)) {
  926. return ast_strdup(aor_name);
  927. }
  928. }
  929. }
  930. if (ast_strlen_zero(username)) {
  931. /* No username, no match */
  932. return NULL;
  933. }
  934. /* Look for exact match on username only */
  935. configured_aors = strcpy(aors_buf, aors);/* Safe */
  936. while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
  937. if (match_aor(aor_name, username)) {
  938. return ast_strdup(aor_name);
  939. }
  940. }
  941. return NULL;
  942. }
  943. static struct ast_sip_aor *find_registrar_aor(struct pjsip_rx_data *rdata, struct ast_sip_endpoint *endpoint)
  944. {
  945. struct ast_sip_aor *aor = NULL;
  946. char *aor_name = NULL;
  947. int i;
  948. for (i = 0; i < AST_VECTOR_SIZE(&endpoint->ident_method_order); ++i) {
  949. pj_str_t username;
  950. pjsip_sip_uri *uri;
  951. pjsip_authorization_hdr *header = NULL;
  952. switch (AST_VECTOR_GET(&endpoint->ident_method_order, i)) {
  953. case AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME:
  954. uri = pjsip_uri_get_uri(rdata->msg_info.to->uri);
  955. pj_strassign(&username, &uri->user);
  956. /*
  957. * We may want to match without any user options getting
  958. * in the way.
  959. *
  960. * Logic adapted from AST_SIP_USER_OPTIONS_TRUNCATE_CHECK for pj_str_t.
  961. */
  962. if (ast_sip_get_ignore_uri_user_options()) {
  963. pj_ssize_t semi = pj_strcspn2(&username, ";");
  964. if (semi < pj_strlen(&username)) {
  965. username.slen = semi;
  966. }
  967. }
  968. aor_name = find_aor_name(&username, &uri->host, endpoint->aors);
  969. if (aor_name) {
  970. ast_debug(3, "Matched aor '%s' by To username\n", aor_name);
  971. }
  972. break;
  973. case AST_SIP_ENDPOINT_IDENTIFY_BY_AUTH_USERNAME:
  974. while ((header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_AUTHORIZATION,
  975. header ? header->next : NULL))) {
  976. if (header && !pj_stricmp2(&header->scheme, "digest")) {
  977. aor_name = find_aor_name(&header->credential.digest.username,
  978. &header->credential.digest.realm, endpoint->aors);
  979. if (aor_name) {
  980. ast_debug(3, "Matched aor '%s' by Authentication username\n", aor_name);
  981. break;
  982. }
  983. }
  984. }
  985. break;
  986. default:
  987. continue;
  988. }
  989. if (aor_name) {
  990. break;
  991. }
  992. }
  993. if (ast_strlen_zero(aor_name) || !(aor = ast_sip_location_retrieve_aor(aor_name))) {
  994. /* The provided AOR name was not found (be it within the configuration or sorcery itself) */
  995. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
  996. ast_sip_report_req_no_support(endpoint, rdata, "registrar_requested_aor_not_found");
  997. ast_log(LOG_WARNING, "AOR '%s' not found for endpoint '%s' (%s:%d)\n",
  998. aor_name ?: "", ast_sorcery_object_get_id(endpoint),
  999. rdata->pkt_info.src_name, rdata->pkt_info.src_port);
  1000. }
  1001. ast_free(aor_name);
  1002. return aor;
  1003. }
  1004. static pj_bool_t registrar_on_rx_request(struct pjsip_rx_data *rdata)
  1005. {
  1006. RAII_VAR(struct ast_sip_endpoint *, endpoint,
  1007. ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
  1008. struct ast_sip_aor *aor;
  1009. const char *aor_name;
  1010. if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_register_method) || !endpoint) {
  1011. return PJ_FALSE;
  1012. }
  1013. if (ast_strlen_zero(endpoint->aors)) {
  1014. /* Short circuit early if the endpoint has no AORs configured on it, which means no registration possible */
  1015. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
  1016. ast_sip_report_failed_acl(endpoint, rdata, "registrar_attempt_without_configured_aors");
  1017. ast_log(LOG_WARNING, "Endpoint '%s' (%s:%d) has no configured AORs\n", ast_sorcery_object_get_id(endpoint),
  1018. rdata->pkt_info.src_name, rdata->pkt_info.src_port);
  1019. return PJ_TRUE;
  1020. }
  1021. if (!PJSIP_URI_SCHEME_IS_SIP(rdata->msg_info.to->uri) && !PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.to->uri)) {
  1022. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
  1023. ast_sip_report_failed_acl(endpoint, rdata, "registrar_invalid_uri_in_to_received");
  1024. ast_log(LOG_WARNING, "Endpoint '%s' (%s:%d) attempted to register to an AOR with a non-SIP URI\n", ast_sorcery_object_get_id(endpoint),
  1025. rdata->pkt_info.src_name, rdata->pkt_info.src_port);
  1026. return PJ_TRUE;
  1027. }
  1028. aor = find_registrar_aor(rdata, endpoint);
  1029. if (!aor) {
  1030. /* We've already responded about not finding an AOR. */
  1031. return PJ_TRUE;
  1032. }
  1033. aor_name = ast_sorcery_object_get_id(aor);
  1034. if (!aor->max_contacts) {
  1035. /* Registration is not permitted for this AOR */
  1036. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
  1037. ast_sip_report_req_no_support(endpoint, rdata, "registrar_attempt_without_registration_permitted");
  1038. ast_log(LOG_WARNING, "AOR '%s' has no configured max_contacts. Endpoint '%s' (%s:%d) unable to register\n",
  1039. aor_name, ast_sorcery_object_get_id(endpoint),
  1040. rdata->pkt_info.src_name, rdata->pkt_info.src_port);
  1041. } else {
  1042. register_aor(rdata, endpoint, aor, aor_name);
  1043. }
  1044. ao2_ref(aor, -1);
  1045. return PJ_TRUE;
  1046. }
  1047. /* function pointer to callback needs to be within the module
  1048. in order to avoid problems with an undefined symbol */
  1049. static int sip_contact_to_str(void *acp, void *arg, int flags)
  1050. {
  1051. return ast_sip_contact_to_str(acp, arg, flags);
  1052. }
  1053. static int ami_registrations_aor(void *obj, void *arg, int flags)
  1054. {
  1055. struct ast_sip_aor *aor = obj;
  1056. struct ast_sip_ami *ami = arg;
  1057. int *count = ami->arg;
  1058. RAII_VAR(struct ast_str *, buf,
  1059. ast_sip_create_ami_event("InboundRegistrationDetail", ami), ast_free);
  1060. if (!buf) {
  1061. return -1;
  1062. }
  1063. ast_sip_sorcery_object_to_ami(aor, &buf);
  1064. ast_str_append(&buf, 0, "Contacts: ");
  1065. ast_sip_for_each_contact(aor, sip_contact_to_str, &buf);
  1066. ast_str_append(&buf, 0, "\r\n");
  1067. astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
  1068. (*count)++;
  1069. return 0;
  1070. }
  1071. static int ami_registrations_endpoint(void *obj, void *arg, int flags)
  1072. {
  1073. struct ast_sip_endpoint *endpoint = obj;
  1074. return ast_sip_for_each_aor(
  1075. endpoint->aors, ami_registrations_aor, arg);
  1076. }
  1077. static int ami_registrations_endpoints(void *arg)
  1078. {
  1079. RAII_VAR(struct ao2_container *, endpoints,
  1080. ast_sip_get_endpoints(), ao2_cleanup);
  1081. if (!endpoints) {
  1082. return 0;
  1083. }
  1084. ao2_callback(endpoints, OBJ_NODATA, ami_registrations_endpoint, arg);
  1085. return 0;
  1086. }
  1087. static int ami_show_registrations(struct mansession *s, const struct message *m)
  1088. {
  1089. int count = 0;
  1090. struct ast_sip_ami ami = { .s = s, .m = m, .arg = &count, .action_id = astman_get_header(m, "ActionID"), };
  1091. astman_send_listack(s, m, "Following are Events for each Inbound registration",
  1092. "start");
  1093. ami_registrations_endpoints(&ami);
  1094. astman_send_list_complete_start(s, m, "InboundRegistrationDetailComplete", count);
  1095. astman_send_list_complete_end(s);
  1096. return 0;
  1097. }
  1098. static int ami_show_registration_contact_statuses(struct mansession *s, const struct message *m)
  1099. {
  1100. int count = 0;
  1101. struct ast_sip_ami ami = { .s = s, .m = m, .arg = NULL, .action_id = astman_get_header(m, "ActionID"), };
  1102. struct ao2_container *contacts = ast_sorcery_retrieve_by_fields(
  1103. ast_sip_get_sorcery(), "contact", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  1104. struct ao2_iterator i;
  1105. struct ast_sip_contact *contact;
  1106. astman_send_listack(s, m, "Following are ContactStatusEvents for each Inbound "
  1107. "registration", "start");
  1108. if (contacts) {
  1109. i = ao2_iterator_init(contacts, 0);
  1110. while ((contact = ao2_iterator_next(&i))) {
  1111. struct ast_sip_contact_wrapper wrapper;
  1112. wrapper.aor_id = (char *)contact->aor;
  1113. wrapper.contact = contact;
  1114. wrapper.contact_id = (char *)ast_sorcery_object_get_id(contact);
  1115. ast_sip_format_contact_ami(&wrapper, &ami, 0);
  1116. count++;
  1117. ao2_ref(contact, -1);
  1118. }
  1119. ao2_iterator_destroy(&i);
  1120. ao2_ref(contacts, -1);
  1121. }
  1122. astman_send_list_complete_start(s, m, "ContactStatusDetailComplete", count);
  1123. astman_send_list_complete_end(s);
  1124. return 0;
  1125. }
  1126. #define AMI_SHOW_REGISTRATION_CONTACT_STATUSES "PJSIPShowRegistrationInboundContactStatuses"
  1127. #define AMI_SHOW_REGISTRATIONS "PJSIPShowRegistrationsInbound"
  1128. static pjsip_module registrar_module = {
  1129. .name = { "Registrar", 9 },
  1130. .id = -1,
  1131. .priority = PJSIP_MOD_PRIORITY_APPLICATION,
  1132. .on_rx_request = registrar_on_rx_request,
  1133. };
  1134. /*! \brief Thread keeping things alive */
  1135. static pthread_t check_thread = AST_PTHREADT_NULL;
  1136. /*! \brief The global interval at which to check for contact expiration */
  1137. static unsigned int check_interval;
  1138. /*! \brief Callback function which deletes a contact */
  1139. static int expire_contact(void *obj, void *arg, int flags)
  1140. {
  1141. struct ast_sip_contact *contact = obj;
  1142. struct ast_named_lock *lock;
  1143. lock = ast_named_lock_get(AST_NAMED_LOCK_TYPE_MUTEX, "aor", contact->aor);
  1144. if (!lock) {
  1145. return 0;
  1146. }
  1147. /*
  1148. * We need to check the expiration again with the aor lock held
  1149. * in case another thread is attempting to renew the contact.
  1150. */
  1151. ao2_lock(lock);
  1152. if (ast_tvdiff_ms(ast_tvnow(), contact->expiration_time) > 0) {
  1153. registrar_contact_delete(CONTACT_DELETE_EXPIRE, NULL, contact, contact->aor);
  1154. }
  1155. ao2_unlock(lock);
  1156. ast_named_lock_put(lock);
  1157. return 0;
  1158. }
  1159. static void *check_expiration_thread(void *data)
  1160. {
  1161. struct ao2_container *contacts;
  1162. struct ast_variable *var;
  1163. char time[AST_TIME_T_LEN];
  1164. while (check_interval) {
  1165. sleep(check_interval);
  1166. ast_time_t_to_string(ast_tvnow().tv_sec, time, sizeof(time));
  1167. var = ast_variable_new("expiration_time <=", time, "");
  1168. ast_debug(4, "Woke up at %s Interval: %d\n", time, check_interval);
  1169. contacts = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "contact",
  1170. AST_RETRIEVE_FLAG_MULTIPLE, var);
  1171. ast_variables_destroy(var);
  1172. if (contacts) {
  1173. ast_debug(3, "Expiring %d contacts\n", ao2_container_count(contacts));
  1174. ao2_callback(contacts, OBJ_NODATA, expire_contact, NULL);
  1175. ao2_ref(contacts, -1);
  1176. }
  1177. }
  1178. return NULL;
  1179. }
  1180. static void expiration_global_loaded(const char *object_type)
  1181. {
  1182. check_interval = ast_sip_get_contact_expiration_check_interval();
  1183. /* Observer calls are serialized so this is safe without it's own lock */
  1184. if (check_interval) {
  1185. if (check_thread == AST_PTHREADT_NULL) {
  1186. if (ast_pthread_create_background(&check_thread, NULL, check_expiration_thread, NULL)) {
  1187. ast_log(LOG_ERROR, "Could not create thread for checking contact expiration.\n");
  1188. return;
  1189. }
  1190. ast_debug(3, "Interval = %d, starting thread\n", check_interval);
  1191. }
  1192. } else {
  1193. if (check_thread != AST_PTHREADT_NULL) {
  1194. pthread_kill(check_thread, SIGURG);
  1195. pthread_join(check_thread, NULL);
  1196. check_thread = AST_PTHREADT_NULL;
  1197. ast_debug(3, "Interval = 0, shutting thread down\n");
  1198. }
  1199. }
  1200. }
  1201. /*! \brief Observer which is used to update our interval when the global setting changes */
  1202. static struct ast_sorcery_observer expiration_global_observer = {
  1203. .loaded = expiration_global_loaded,
  1204. };
  1205. static int load_module(void)
  1206. {
  1207. const pj_str_t STR_REGISTER = { "REGISTER", 8 };
  1208. ast_pjproject_get_buildopt("PJ_MAX_HOSTNAME", "%d", &pj_max_hostname);
  1209. /* As of pjproject 2.4.5, PJSIP_MAX_URL_SIZE isn't exposed yet but we try anyway. */
  1210. ast_pjproject_get_buildopt("PJSIP_MAX_URL_SIZE", "%d", &pjsip_max_url_size);
  1211. if (ast_sip_register_service(&registrar_module)) {
  1212. return AST_MODULE_LOAD_DECLINE;
  1213. }
  1214. if (pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_ALLOW, NULL, 1, &STR_REGISTER) != PJ_SUCCESS) {
  1215. ast_sip_unregister_service(&registrar_module);
  1216. return AST_MODULE_LOAD_DECLINE;
  1217. }
  1218. ast_manager_register_xml(AMI_SHOW_REGISTRATIONS, EVENT_FLAG_SYSTEM,
  1219. ami_show_registrations);
  1220. ast_manager_register_xml(AMI_SHOW_REGISTRATION_CONTACT_STATUSES, EVENT_FLAG_SYSTEM,
  1221. ami_show_registration_contact_statuses);
  1222. ast_sorcery_observer_add(ast_sip_get_sorcery(), "global", &expiration_global_observer);
  1223. ast_sorcery_reload_object(ast_sip_get_sorcery(), "global");
  1224. return AST_MODULE_LOAD_SUCCESS;
  1225. }
  1226. static int unload_module(void)
  1227. {
  1228. if (check_thread != AST_PTHREADT_NULL) {
  1229. check_interval = 0;
  1230. pthread_kill(check_thread, SIGURG);
  1231. pthread_join(check_thread, NULL);
  1232. check_thread = AST_PTHREADT_NULL;
  1233. }
  1234. ast_sorcery_observer_remove(ast_sip_get_sorcery(), "global", &expiration_global_observer);
  1235. ast_manager_unregister(AMI_SHOW_REGISTRATIONS);
  1236. ast_manager_unregister(AMI_SHOW_REGISTRATION_CONTACT_STATUSES);
  1237. ast_sip_unregister_service(&registrar_module);
  1238. ast_sip_transport_monitor_unregister_all(register_contact_transport_shutdown_cb, NULL, NULL);
  1239. return 0;
  1240. }
  1241. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Registrar Support",
  1242. .support_level = AST_MODULE_SUPPORT_CORE,
  1243. .load = load_module,
  1244. .unload = unload_module,
  1245. .load_pri = AST_MODPRI_CHANNEL_DEPEND - 3,
  1246. .requires = "res_pjproject,res_pjsip",
  1247. );