res_pjsip_session.c 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335
  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. /*** MODULEINFO
  19. <depend>pjproject</depend>
  20. <depend>res_pjsip</depend>
  21. <support_level>core</support_level>
  22. ***/
  23. #include "asterisk.h"
  24. #include <pjsip.h>
  25. #include <pjsip_ua.h>
  26. #include <pjlib.h>
  27. #include "asterisk/res_pjsip.h"
  28. #include "asterisk/res_pjsip_session.h"
  29. #include "asterisk/datastore.h"
  30. #include "asterisk/module.h"
  31. #include "asterisk/logger.h"
  32. #include "asterisk/res_pjsip.h"
  33. #include "asterisk/astobj2.h"
  34. #include "asterisk/lock.h"
  35. #include "asterisk/uuid.h"
  36. #include "asterisk/pbx.h"
  37. #include "asterisk/taskprocessor.h"
  38. #include "asterisk/causes.h"
  39. #include "asterisk/sdp_srtp.h"
  40. #include "asterisk/dsp.h"
  41. #include "asterisk/acl.h"
  42. #include "asterisk/features_config.h"
  43. #include "asterisk/pickup.h"
  44. #define SDP_HANDLER_BUCKETS 11
  45. #define MOD_DATA_ON_RESPONSE "on_response"
  46. #define MOD_DATA_NAT_HOOK "nat_hook"
  47. /* Some forward declarations */
  48. static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type);
  49. static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
  50. enum ast_sip_session_response_priority response_priority);
  51. static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
  52. enum ast_sip_session_response_priority response_priority);
  53. static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata);
  54. static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata);
  55. static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata);
  56. /*! \brief NAT hook for modifying outgoing messages with SDP */
  57. static struct ast_sip_nat_hook *nat_hook;
  58. /*!
  59. * \brief Registered SDP stream handlers
  60. *
  61. * This container is keyed on stream types. Each
  62. * object in the container is a linked list of
  63. * handlers for the stream type.
  64. */
  65. static struct ao2_container *sdp_handlers;
  66. /*!
  67. * These are the objects in the sdp_handlers container
  68. */
  69. struct sdp_handler_list {
  70. /* The list of handlers to visit */
  71. AST_LIST_HEAD_NOLOCK(, ast_sip_session_sdp_handler) list;
  72. /* The handlers in this list handle streams of this type */
  73. char stream_type[1];
  74. };
  75. static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer);
  76. static int sdp_handler_list_hash(const void *obj, int flags)
  77. {
  78. const struct sdp_handler_list *handler_list = obj;
  79. const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;
  80. return ast_str_hash(stream_type);
  81. }
  82. static int sdp_handler_list_cmp(void *obj, void *arg, int flags)
  83. {
  84. struct sdp_handler_list *handler_list1 = obj;
  85. struct sdp_handler_list *handler_list2 = arg;
  86. const char *stream_type2 = flags & OBJ_KEY ? arg : handler_list2->stream_type;
  87. return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
  88. }
  89. static int session_media_hash(const void *obj, int flags)
  90. {
  91. const struct ast_sip_session_media *session_media = obj;
  92. const char *stream_type = flags & OBJ_KEY ? obj : session_media->stream_type;
  93. return ast_str_hash(stream_type);
  94. }
  95. static int session_media_cmp(void *obj, void *arg, int flags)
  96. {
  97. struct ast_sip_session_media *session_media1 = obj;
  98. struct ast_sip_session_media *session_media2 = arg;
  99. const char *stream_type2 = flags & OBJ_KEY ? arg : session_media2->stream_type;
  100. return strcmp(session_media1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
  101. }
  102. int ast_sip_session_register_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
  103. {
  104. RAII_VAR(struct sdp_handler_list *, handler_list,
  105. ao2_find(sdp_handlers, stream_type, OBJ_KEY), ao2_cleanup);
  106. SCOPED_AO2LOCK(lock, sdp_handlers);
  107. if (handler_list) {
  108. struct ast_sip_session_sdp_handler *iter;
  109. /* Check if this handler is already registered for this stream type */
  110. AST_LIST_TRAVERSE(&handler_list->list, iter, next) {
  111. if (!strcmp(iter->id, handler->id)) {
  112. ast_log(LOG_WARNING, "Handler '%s' already registered for stream type '%s'.\n", handler->id, stream_type);
  113. return -1;
  114. }
  115. }
  116. AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
  117. ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
  118. ast_module_ref(ast_module_info->self);
  119. return 0;
  120. }
  121. /* No stream of this type has been registered yet, so we need to create a new list */
  122. handler_list = ao2_alloc(sizeof(*handler_list) + strlen(stream_type), NULL);
  123. if (!handler_list) {
  124. return -1;
  125. }
  126. /* Safe use of strcpy */
  127. strcpy(handler_list->stream_type, stream_type);
  128. AST_LIST_HEAD_INIT_NOLOCK(&handler_list->list);
  129. AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
  130. if (!ao2_link(sdp_handlers, handler_list)) {
  131. return -1;
  132. }
  133. ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
  134. ast_module_ref(ast_module_info->self);
  135. return 0;
  136. }
  137. static int remove_handler(void *obj, void *arg, void *data, int flags)
  138. {
  139. struct sdp_handler_list *handler_list = obj;
  140. struct ast_sip_session_sdp_handler *handler = data;
  141. struct ast_sip_session_sdp_handler *iter;
  142. const char *stream_type = arg;
  143. AST_LIST_TRAVERSE_SAFE_BEGIN(&handler_list->list, iter, next) {
  144. if (!strcmp(iter->id, handler->id)) {
  145. AST_LIST_REMOVE_CURRENT(next);
  146. ast_debug(1, "Unregistered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
  147. ast_module_unref(ast_module_info->self);
  148. }
  149. }
  150. AST_LIST_TRAVERSE_SAFE_END;
  151. if (AST_LIST_EMPTY(&handler_list->list)) {
  152. ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);
  153. return CMP_MATCH;
  154. } else {
  155. return CMP_STOP;
  156. }
  157. }
  158. void ast_sip_session_unregister_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
  159. {
  160. ao2_callback_data(sdp_handlers, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, remove_handler, (void *)stream_type, handler);
  161. }
  162. static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
  163. {
  164. int i;
  165. int handled = 0;
  166. for (i = 0; i < sdp->media_count; ++i) {
  167. /* See if there are registered handlers for this media stream type */
  168. char media[20];
  169. struct ast_sip_session_sdp_handler *handler;
  170. RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
  171. RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
  172. int res;
  173. /* We need a null-terminated version of the media string */
  174. ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
  175. session_media = ao2_find(session->media, media, OBJ_KEY);
  176. if (!session_media) {
  177. /* if the session_media doesn't exist, there weren't
  178. * any handlers at the time of its creation */
  179. continue;
  180. }
  181. if (session_media->handler) {
  182. handler = session_media->handler;
  183. ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
  184. session_media->stream_type,
  185. session_media->handler->id);
  186. res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
  187. sdp->media[i]);
  188. if (res < 0) {
  189. /* Catastrophic failure. Abort! */
  190. return -1;
  191. } else if (res > 0) {
  192. ast_debug(1, "Media stream '%s' handled by %s\n",
  193. session_media->stream_type,
  194. session_media->handler->id);
  195. /* Handled by this handler. Move to the next stream */
  196. handled = 1;
  197. continue;
  198. }
  199. }
  200. handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
  201. if (!handler_list) {
  202. ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
  203. continue;
  204. }
  205. AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
  206. ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
  207. session_media->stream_type,
  208. handler->id);
  209. res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
  210. sdp->media[i]);
  211. if (res < 0) {
  212. /* Catastrophic failure. Abort! */
  213. return -1;
  214. }
  215. if (res > 0) {
  216. ast_debug(1, "Media stream '%s' handled by %s\n",
  217. session_media->stream_type,
  218. handler->id);
  219. /* Handled by this handler. Move to the next stream */
  220. session_media->handler = handler;
  221. handled = 1;
  222. break;
  223. }
  224. }
  225. }
  226. if (!handled) {
  227. return -1;
  228. }
  229. return 0;
  230. }
  231. struct handle_negotiated_sdp_cb {
  232. struct ast_sip_session *session;
  233. const pjmedia_sdp_session *local;
  234. const pjmedia_sdp_session *remote;
  235. };
  236. static int handle_negotiated_sdp_session_media(void *obj, void *arg, int flags)
  237. {
  238. struct ast_sip_session_media *session_media = obj;
  239. struct handle_negotiated_sdp_cb *callback_data = arg;
  240. struct ast_sip_session *session = callback_data->session;
  241. const pjmedia_sdp_session *local = callback_data->local;
  242. const pjmedia_sdp_session *remote = callback_data->remote;
  243. int i;
  244. for (i = 0; i < local->media_count; ++i) {
  245. /* See if there are registered handlers for this media stream type */
  246. char media[20];
  247. struct ast_sip_session_sdp_handler *handler;
  248. RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
  249. int res;
  250. if (!remote->media[i]) {
  251. continue;
  252. }
  253. /* We need a null-terminated version of the media string */
  254. ast_copy_pj_str(media, &local->media[i]->desc.media, sizeof(media));
  255. /* stream type doesn't match the one we're looking to fill */
  256. if (strcasecmp(session_media->stream_type, media)) {
  257. continue;
  258. }
  259. handler = session_media->handler;
  260. if (handler) {
  261. ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
  262. session_media->stream_type,
  263. handler->id);
  264. res = handler->apply_negotiated_sdp_stream(session, session_media, local,
  265. local->media[i], remote, remote->media[i]);
  266. if (res >= 0) {
  267. ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
  268. session_media->stream_type,
  269. handler->id);
  270. return CMP_MATCH;
  271. }
  272. return 0;
  273. }
  274. handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
  275. if (!handler_list) {
  276. ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
  277. continue;
  278. }
  279. AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
  280. ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
  281. session_media->stream_type,
  282. handler->id);
  283. res = handler->apply_negotiated_sdp_stream(session, session_media, local,
  284. local->media[i], remote, remote->media[i]);
  285. if (res < 0) {
  286. /* Catastrophic failure. Abort! */
  287. return 0;
  288. }
  289. if (res > 0) {
  290. ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
  291. session_media->stream_type,
  292. handler->id);
  293. /* Handled by this handler. Move to the next stream */
  294. session_media->handler = handler;
  295. return CMP_MATCH;
  296. }
  297. }
  298. }
  299. return CMP_MATCH;
  300. }
  301. static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)
  302. {
  303. RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
  304. struct handle_negotiated_sdp_cb callback_data = {
  305. .session = session,
  306. .local = local,
  307. .remote = remote,
  308. };
  309. successful = ao2_callback(session->media, OBJ_MULTIPLE, handle_negotiated_sdp_session_media, &callback_data);
  310. if (successful && ao2_iterator_count(successful) == ao2_container_count(session->media)) {
  311. /* Nothing experienced a catastrophic failure */
  312. ast_queue_frame(session->channel, &ast_null_frame);
  313. return 0;
  314. }
  315. return -1;
  316. }
  317. AST_RWLIST_HEAD_STATIC(session_supplements, ast_sip_session_supplement);
  318. int ast_sip_session_register_supplement(struct ast_sip_session_supplement *supplement)
  319. {
  320. struct ast_sip_session_supplement *iter;
  321. int inserted = 0;
  322. SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  323. if (!supplement->response_priority) {
  324. supplement->response_priority = AST_SIP_SESSION_BEFORE_MEDIA;
  325. }
  326. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
  327. if (iter->priority > supplement->priority) {
  328. AST_RWLIST_INSERT_BEFORE_CURRENT(supplement, next);
  329. inserted = 1;
  330. break;
  331. }
  332. }
  333. AST_RWLIST_TRAVERSE_SAFE_END;
  334. if (!inserted) {
  335. AST_RWLIST_INSERT_TAIL(&session_supplements, supplement, next);
  336. }
  337. ast_module_ref(ast_module_info->self);
  338. return 0;
  339. }
  340. void ast_sip_session_unregister_supplement(struct ast_sip_session_supplement *supplement)
  341. {
  342. struct ast_sip_session_supplement *iter;
  343. SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  344. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
  345. if (supplement == iter) {
  346. AST_RWLIST_REMOVE_CURRENT(next);
  347. ast_module_unref(ast_module_info->self);
  348. break;
  349. }
  350. }
  351. AST_RWLIST_TRAVERSE_SAFE_END;
  352. }
  353. static struct ast_sip_session_supplement *supplement_dup(const struct ast_sip_session_supplement *src)
  354. {
  355. struct ast_sip_session_supplement *dst = ast_calloc(1, sizeof(*dst));
  356. if (!dst) {
  357. return NULL;
  358. }
  359. /* Will need to revisit if shallow copy becomes an issue */
  360. *dst = *src;
  361. return dst;
  362. }
  363. #define DATASTORE_BUCKETS 53
  364. #define MEDIA_BUCKETS 7
  365. static void session_datastore_destroy(void *obj)
  366. {
  367. struct ast_datastore *datastore = obj;
  368. /* Using the destroy function (if present) destroy the data */
  369. if (datastore->info->destroy != NULL && datastore->data != NULL) {
  370. datastore->info->destroy(datastore->data);
  371. datastore->data = NULL;
  372. }
  373. ast_free((void *) datastore->uid);
  374. datastore->uid = NULL;
  375. }
  376. struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
  377. {
  378. RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
  379. char uuid_buf[AST_UUID_STR_LEN];
  380. const char *uid_ptr = uid;
  381. if (!info) {
  382. return NULL;
  383. }
  384. datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
  385. if (!datastore) {
  386. return NULL;
  387. }
  388. datastore->info = info;
  389. if (ast_strlen_zero(uid)) {
  390. /* They didn't provide an ID so we'll provide one ourself */
  391. uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
  392. }
  393. datastore->uid = ast_strdup(uid_ptr);
  394. if (!datastore->uid) {
  395. return NULL;
  396. }
  397. ao2_ref(datastore, +1);
  398. return datastore;
  399. }
  400. int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)
  401. {
  402. ast_assert(datastore != NULL);
  403. ast_assert(datastore->info != NULL);
  404. ast_assert(ast_strlen_zero(datastore->uid) == 0);
  405. if (!ao2_link(session->datastores, datastore)) {
  406. return -1;
  407. }
  408. return 0;
  409. }
  410. struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)
  411. {
  412. return ao2_find(session->datastores, name, OBJ_KEY);
  413. }
  414. void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)
  415. {
  416. ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
  417. }
  418. /*!
  419. * \brief Structure used for sending delayed requests
  420. *
  421. * Requests are typically delayed because the current transaction
  422. * state of an INVITE. Once the pending INVITE transaction terminates,
  423. * the delayed request will be sent
  424. */
  425. struct ast_sip_session_delayed_request {
  426. /*! Method of the request */
  427. char method[15];
  428. /*! Callback to call when the delayed request is created. */
  429. ast_sip_session_request_creation_cb on_request_creation;
  430. /*! Callback to call when the delayed request SDP is created */
  431. ast_sip_session_sdp_creation_cb on_sdp_creation;
  432. /*! Callback to call when the delayed request receives a response */
  433. ast_sip_session_response_cb on_response;
  434. /*! Whether to generate new SDP */
  435. int generate_new_sdp;
  436. /*! Request to send */
  437. pjsip_tx_data *tdata;
  438. AST_LIST_ENTRY(ast_sip_session_delayed_request) next;
  439. };
  440. static struct ast_sip_session_delayed_request *delayed_request_alloc(const char *method,
  441. ast_sip_session_request_creation_cb on_request_creation,
  442. ast_sip_session_sdp_creation_cb on_sdp_creation,
  443. ast_sip_session_response_cb on_response,
  444. int generate_new_sdp,
  445. pjsip_tx_data *tdata)
  446. {
  447. struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
  448. if (!delay) {
  449. return NULL;
  450. }
  451. ast_copy_string(delay->method, method, sizeof(delay->method));
  452. delay->on_request_creation = on_request_creation;
  453. delay->on_sdp_creation = on_sdp_creation;
  454. delay->on_response = on_response;
  455. delay->generate_new_sdp = generate_new_sdp;
  456. delay->tdata = tdata;
  457. return delay;
  458. }
  459. static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
  460. {
  461. ast_debug(3, "Sending delayed %s request to %s\n", delay->method, ast_sorcery_object_get_id(session->endpoint));
  462. if (delay->tdata) {
  463. ast_sip_session_send_request_with_cb(session, delay->tdata, delay->on_response);
  464. return 0;
  465. }
  466. if (!strcmp(delay->method, "INVITE")) {
  467. ast_sip_session_refresh(session, delay->on_request_creation,
  468. delay->on_sdp_creation, delay->on_response, AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp);
  469. } else if (!strcmp(delay->method, "UPDATE")) {
  470. ast_sip_session_refresh(session, delay->on_request_creation,
  471. delay->on_sdp_creation, delay->on_response, AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp);
  472. } else {
  473. ast_log(LOG_WARNING, "Unexpected delayed %s request with no existing request structure\n", delay->method);
  474. return -1;
  475. }
  476. return 0;
  477. }
  478. static int queued_delayed_request_send(void *data)
  479. {
  480. RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
  481. RAII_VAR(struct ast_sip_session_delayed_request *, delay, NULL, ast_free_ptr);
  482. delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next);
  483. if (!delay) {
  484. return 0;
  485. }
  486. return send_delayed_request(session, delay);
  487. }
  488. static void queue_delayed_request(struct ast_sip_session *session)
  489. {
  490. if (AST_LIST_EMPTY(&session->delayed_requests)) {
  491. /* No delayed request to send, so just return */
  492. return;
  493. }
  494. ast_debug(3, "Queuing delayed request to run for %s\n",
  495. ast_sorcery_object_get_id(session->endpoint));
  496. ao2_ref(session, +1);
  497. ast_sip_push_task(session->serializer, queued_delayed_request_send, session);
  498. }
  499. static int delay_request(struct ast_sip_session *session, ast_sip_session_request_creation_cb on_request,
  500. ast_sip_session_sdp_creation_cb on_sdp_creation, ast_sip_session_response_cb on_response,
  501. int generate_new_sdp, const char *method, pjsip_tx_data *tdata)
  502. {
  503. struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,
  504. on_request, on_sdp_creation, on_response, generate_new_sdp, tdata);
  505. if (!delay) {
  506. return -1;
  507. }
  508. AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
  509. return 0;
  510. }
  511. static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
  512. {
  513. pjsip_inv_session *inv_session = session->inv_session;
  514. const pjmedia_sdp_session *previous_sdp;
  515. if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
  516. pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
  517. } else {
  518. pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
  519. }
  520. return create_local_sdp(inv_session, session, previous_sdp);
  521. }
  522. int ast_sip_session_refresh(struct ast_sip_session *session,
  523. ast_sip_session_request_creation_cb on_request_creation,
  524. ast_sip_session_sdp_creation_cb on_sdp_creation,
  525. ast_sip_session_response_cb on_response,
  526. enum ast_sip_session_refresh_method method, int generate_new_sdp)
  527. {
  528. pjsip_inv_session *inv_session = session->inv_session;
  529. pjmedia_sdp_session *new_sdp = NULL;
  530. pjsip_tx_data *tdata;
  531. if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
  532. /* Don't try to do anything with a hung-up call */
  533. ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
  534. ast_sorcery_object_get_id(session->endpoint));
  535. return 0;
  536. }
  537. /* If the dialog has not yet been established we have to defer until it has */
  538. if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
  539. ast_debug(3, "Delaying sending request to %s because dialog has not been established...\n",
  540. ast_sorcery_object_get_id(session->endpoint));
  541. return delay_request(session, on_request_creation, on_sdp_creation, on_response, generate_new_sdp,
  542. method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "INVITE" : "UPDATE", NULL);
  543. }
  544. if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
  545. if (inv_session->invite_tsx) {
  546. /* We can't send a reinvite yet, so delay it */
  547. ast_debug(3, "Delaying sending reinvite to %s because of outstanding transaction...\n",
  548. ast_sorcery_object_get_id(session->endpoint));
  549. return delay_request(session, on_request_creation, on_sdp_creation, on_response,
  550. generate_new_sdp, "INVITE", NULL);
  551. } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
  552. /* Initial INVITE transaction failed to progress us to a confirmed state
  553. * which means re-invites are not possible
  554. */
  555. ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
  556. ast_sorcery_object_get_id(session->endpoint));
  557. return 0;
  558. }
  559. }
  560. if (generate_new_sdp) {
  561. /* SDP can only be generated if current negotiation has already completed */
  562. if (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {
  563. ast_debug(3, "Delaying session refresh with new SDP to %s because SDP negotiation is not yet done...\n",
  564. ast_sorcery_object_get_id(session->endpoint));
  565. return delay_request(session, on_request_creation, on_sdp_creation, on_response, generate_new_sdp,
  566. method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "INVITE" : "UPDATE", NULL);
  567. }
  568. new_sdp = generate_session_refresh_sdp(session);
  569. if (!new_sdp) {
  570. ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
  571. return -1;
  572. }
  573. if (on_sdp_creation) {
  574. if (on_sdp_creation(session, new_sdp)) {
  575. return -1;
  576. }
  577. }
  578. }
  579. if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
  580. if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
  581. ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
  582. return -1;
  583. }
  584. } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
  585. ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
  586. return -1;
  587. }
  588. if (on_request_creation) {
  589. if (on_request_creation(session, tdata)) {
  590. return -1;
  591. }
  592. }
  593. ast_debug(3, "Sending session refresh SDP via %s to %s\n",
  594. method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
  595. ast_sorcery_object_get_id(session->endpoint));
  596. ast_sip_session_send_request_with_cb(session, tdata, on_response);
  597. return 0;
  598. }
  599. void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
  600. {
  601. handle_outgoing_response(session, tdata);
  602. pjsip_inv_send_msg(session->inv_session, tdata);
  603. return;
  604. }
  605. static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
  606. static pjsip_module session_module = {
  607. .name = {"Session Module", 14},
  608. .priority = PJSIP_MOD_PRIORITY_APPLICATION,
  609. .on_rx_request = session_on_rx_request,
  610. };
  611. /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
  612. *
  613. * \retval 1 re-invite should be deferred and resumed later
  614. * \retval 0 re-invite should not be deferred
  615. */
  616. static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
  617. {
  618. int i;
  619. for (i = 0; i < sdp->media_count; ++i) {
  620. /* See if there are registered handlers for this media stream type */
  621. char media[20];
  622. struct ast_sip_session_sdp_handler *handler;
  623. RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
  624. RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
  625. enum ast_sip_session_sdp_stream_defer res;
  626. /* We need a null-terminated version of the media string */
  627. ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
  628. session_media = ao2_find(session->media, media, OBJ_KEY);
  629. if (!session_media) {
  630. /* if the session_media doesn't exist, there weren't
  631. * any handlers at the time of its creation */
  632. continue;
  633. }
  634. if (session_media->handler) {
  635. handler = session_media->handler;
  636. if (handler->defer_incoming_sdp_stream) {
  637. res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
  638. sdp->media[i]);
  639. switch (res) {
  640. case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
  641. break;
  642. case AST_SIP_SESSION_SDP_DEFER_ERROR:
  643. return 0;
  644. case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
  645. break;
  646. case AST_SIP_SESSION_SDP_DEFER_NEEDED:
  647. return 1;
  648. }
  649. }
  650. /* Handled by this handler. Move to the next stream */
  651. continue;
  652. }
  653. handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
  654. if (!handler_list) {
  655. ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
  656. continue;
  657. }
  658. AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
  659. if (!handler->defer_incoming_sdp_stream) {
  660. continue;
  661. }
  662. res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
  663. sdp->media[i]);
  664. switch (res) {
  665. case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
  666. continue;
  667. case AST_SIP_SESSION_SDP_DEFER_ERROR:
  668. session_media->handler = handler;
  669. return 0;
  670. case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
  671. /* Handled by this handler. */
  672. session_media->handler = handler;
  673. break;
  674. case AST_SIP_SESSION_SDP_DEFER_NEEDED:
  675. /* Handled by this handler. */
  676. session_media->handler = handler;
  677. return 1;
  678. }
  679. /* Move to the next stream */
  680. break;
  681. }
  682. }
  683. return 0;
  684. }
  685. static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
  686. {
  687. pjsip_dialog *dlg;
  688. RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
  689. pjsip_rdata_sdp_info *sdp_info;
  690. if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
  691. !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
  692. !(session = ast_sip_dialog_get_session(dlg))) {
  693. return PJ_FALSE;
  694. }
  695. if (session->deferred_reinvite) {
  696. pj_str_t key, deferred_key;
  697. pjsip_tx_data *tdata;
  698. /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
  699. pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
  700. pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
  701. session->deferred_reinvite);
  702. /* If this is a retransmission ignore it */
  703. if (!pj_strcmp(&key, &deferred_key)) {
  704. return PJ_TRUE;
  705. }
  706. /* Otherwise this is a new re-invite, so reject it */
  707. if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
  708. pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
  709. }
  710. return PJ_TRUE;
  711. }
  712. if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
  713. (sdp_info->sdp_err != PJ_SUCCESS)) {
  714. return PJ_FALSE;
  715. }
  716. if (!sdp_info->sdp) {
  717. ast_queue_unhold(session->channel);
  718. return PJ_FALSE;
  719. }
  720. if (!sdp_requires_deferral(session, sdp_info->sdp)) {
  721. return PJ_FALSE;
  722. }
  723. pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
  724. return PJ_TRUE;
  725. }
  726. void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
  727. {
  728. if (!session->deferred_reinvite) {
  729. return;
  730. }
  731. pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(), session->deferred_reinvite, NULL, NULL);
  732. pjsip_rx_data_free_cloned(session->deferred_reinvite);
  733. session->deferred_reinvite = NULL;
  734. }
  735. static pjsip_module session_reinvite_module = {
  736. .name = { "Session Re-Invite Module", 24 },
  737. .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
  738. .on_rx_request = session_reinvite_on_rx_request,
  739. };
  740. void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
  741. ast_sip_session_response_cb on_response)
  742. {
  743. pjsip_inv_session *inv_session = session->inv_session;
  744. if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
  745. /* Don't try to do anything with a hung-up call */
  746. return;
  747. }
  748. ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
  749. MOD_DATA_ON_RESPONSE, on_response);
  750. if (!ast_strlen_zero(session->endpoint->fromuser) ||
  751. !ast_strlen_zero(session->endpoint->fromdomain)) {
  752. pjsip_fromto_hdr *from = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_FROM, tdata->msg->hdr.next);
  753. pjsip_sip_uri *uri = pjsip_uri_get_uri(from->uri);
  754. if (!ast_strlen_zero(session->endpoint->fromuser)) {
  755. pj_strdup2(tdata->pool, &uri->user, session->endpoint->fromuser);
  756. }
  757. if (!ast_strlen_zero(session->endpoint->fromdomain)) {
  758. pj_strdup2(tdata->pool, &uri->host, session->endpoint->fromdomain);
  759. }
  760. }
  761. handle_outgoing_request(session, tdata);
  762. pjsip_inv_send_msg(session->inv_session, tdata);
  763. return;
  764. }
  765. void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
  766. {
  767. ast_sip_session_send_request_with_cb(session, tdata, NULL);
  768. }
  769. int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
  770. {
  771. pjmedia_sdp_session *offer;
  772. if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
  773. pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
  774. return -1;
  775. }
  776. pjsip_inv_set_local_sdp(session->inv_session, offer);
  777. pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
  778. #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
  779. pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
  780. #endif
  781. if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
  782. return -1;
  783. }
  784. return 0;
  785. }
  786. static int datastore_hash(const void *obj, int flags)
  787. {
  788. const struct ast_datastore *datastore = obj;
  789. const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
  790. ast_assert(uid != NULL);
  791. return ast_str_hash(uid);
  792. }
  793. static int datastore_cmp(void *obj, void *arg, int flags)
  794. {
  795. const struct ast_datastore *datastore1 = obj;
  796. const struct ast_datastore *datastore2 = arg;
  797. const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
  798. ast_assert(datastore1->uid != NULL);
  799. ast_assert(uid2 != NULL);
  800. return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
  801. }
  802. static void session_media_dtor(void *obj)
  803. {
  804. struct ast_sip_session_media *session_media = obj;
  805. if (session_media->handler) {
  806. session_media->handler->stream_destroy(session_media);
  807. }
  808. if (session_media->srtp) {
  809. ast_sdp_srtp_destroy(session_media->srtp);
  810. }
  811. }
  812. static void session_destructor(void *obj)
  813. {
  814. struct ast_sip_session *session = obj;
  815. struct ast_sip_session_supplement *supplement;
  816. struct ast_sip_session_delayed_request *delay;
  817. ast_debug(3, "Destroying SIP session with endpoint %s\n",
  818. ast_sorcery_object_get_id(session->endpoint));
  819. while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
  820. if (supplement->session_destroy) {
  821. supplement->session_destroy(session);
  822. }
  823. ast_free(supplement);
  824. }
  825. ast_taskprocessor_unreference(session->serializer);
  826. ao2_cleanup(session->datastores);
  827. ao2_cleanup(session->media);
  828. AST_LIST_HEAD_DESTROY(&session->supplements);
  829. while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
  830. ast_free(delay);
  831. }
  832. ast_party_id_free(&session->id);
  833. ao2_cleanup(session->endpoint);
  834. ao2_cleanup(session->contact);
  835. ao2_cleanup(session->req_caps);
  836. ao2_cleanup(session->direct_media_cap);
  837. if (session->dsp) {
  838. ast_dsp_free(session->dsp);
  839. }
  840. if (session->inv_session) {
  841. pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
  842. }
  843. }
  844. static int add_supplements(struct ast_sip_session *session)
  845. {
  846. struct ast_sip_session_supplement *iter;
  847. SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
  848. AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
  849. struct ast_sip_session_supplement *copy = supplement_dup(iter);
  850. if (!copy) {
  851. return -1;
  852. }
  853. AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
  854. }
  855. return 0;
  856. }
  857. static int add_session_media(void *obj, void *arg, int flags)
  858. {
  859. struct sdp_handler_list *handler_list = obj;
  860. struct ast_sip_session * session = arg;
  861. RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
  862. session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);
  863. if (!session_media) {
  864. return CMP_STOP;
  865. }
  866. /* Safe use of strcpy */
  867. strcpy(session_media->stream_type, handler_list->stream_type);
  868. ao2_link(session->media, session_media);
  869. return 0;
  870. }
  871. /*! \brief Destructor for SIP channel */
  872. static void sip_channel_destroy(void *obj)
  873. {
  874. struct ast_sip_channel_pvt *channel = obj;
  875. ao2_cleanup(channel->pvt);
  876. ao2_cleanup(channel->session);
  877. }
  878. struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
  879. {
  880. struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
  881. if (!channel) {
  882. return NULL;
  883. }
  884. ao2_ref(pvt, +1);
  885. channel->pvt = pvt;
  886. ao2_ref(session, +1);
  887. channel->session = session;
  888. return channel;
  889. }
  890. struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
  891. struct ast_sip_contact *contact, pjsip_inv_session *inv_session)
  892. {
  893. RAII_VAR(struct ast_sip_session *, session, ao2_alloc(sizeof(*session), session_destructor), ao2_cleanup);
  894. struct ast_sip_session_supplement *iter;
  895. int dsp_features = 0;
  896. if (!session) {
  897. return NULL;
  898. }
  899. AST_LIST_HEAD_INIT(&session->supplements);
  900. session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
  901. if (!session->datastores) {
  902. return NULL;
  903. }
  904. session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);
  905. if (!session->media) {
  906. return NULL;
  907. }
  908. /* fill session->media with available types */
  909. ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);
  910. session->serializer = ast_sip_create_serializer();
  911. if (!session->serializer) {
  912. return NULL;
  913. }
  914. ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
  915. ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
  916. pjsip_dlg_inc_session(inv_session->dlg, &session_module);
  917. inv_session->mod_data[session_module.id] = ao2_bump(session);
  918. session->endpoint = ao2_bump(endpoint);
  919. session->contact = ao2_bump(contact);
  920. session->inv_session = inv_session;
  921. session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  922. if (endpoint->dtmf == AST_SIP_DTMF_INBAND) {
  923. dsp_features |= DSP_FEATURE_DIGIT_DETECT;
  924. }
  925. if (endpoint->faxdetect) {
  926. dsp_features |= DSP_FEATURE_FAX_DETECT;
  927. }
  928. if (dsp_features) {
  929. if (!(session->dsp = ast_dsp_new())) {
  930. ao2_ref(session, -1);
  931. return NULL;
  932. }
  933. ast_dsp_set_features(session->dsp, dsp_features);
  934. }
  935. if (add_supplements(session)) {
  936. ao2_ref(session, -1);
  937. return NULL;
  938. }
  939. AST_LIST_TRAVERSE(&session->supplements, iter, next) {
  940. if (iter->session_begin) {
  941. iter->session_begin(session);
  942. }
  943. }
  944. session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  945. AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
  946. ast_party_id_init(&session->id);
  947. ao2_ref(session, +1);
  948. return session;
  949. }
  950. /*! \brief struct controlling the suspension of the session's serializer. */
  951. struct ast_sip_session_suspender {
  952. ast_cond_t cond_suspended;
  953. ast_cond_t cond_complete;
  954. int suspended;
  955. int complete;
  956. };
  957. static void sip_session_suspender_dtor(void *vdoomed)
  958. {
  959. struct ast_sip_session_suspender *doomed = vdoomed;
  960. ast_cond_destroy(&doomed->cond_suspended);
  961. ast_cond_destroy(&doomed->cond_complete);
  962. }
  963. /*!
  964. * \internal
  965. * \brief Block the session serializer thread task.
  966. *
  967. * \param data Pushed serializer task data for suspension.
  968. *
  969. * \retval 0
  970. */
  971. static int sip_session_suspend_task(void *data)
  972. {
  973. struct ast_sip_session_suspender *suspender = data;
  974. ao2_lock(suspender);
  975. /* Signal that the serializer task is now suspended. */
  976. suspender->suspended = 1;
  977. ast_cond_signal(&suspender->cond_suspended);
  978. /* Wait for the the serializer suspension to be completed. */
  979. while (!suspender->complete) {
  980. ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
  981. }
  982. ao2_unlock(suspender);
  983. ao2_ref(suspender, -1);
  984. return 0;
  985. }
  986. void ast_sip_session_suspend(struct ast_sip_session *session)
  987. {
  988. struct ast_sip_session_suspender *suspender;
  989. int res;
  990. ast_assert(session->suspended == NULL);
  991. if (ast_taskprocessor_is_task(session->serializer)) {
  992. /* I am the session's serializer thread so I cannot suspend. */
  993. return;
  994. }
  995. suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
  996. if (!suspender) {
  997. /* We will just have to hope that the system does not deadlock */
  998. return;
  999. }
  1000. ast_cond_init(&suspender->cond_suspended, NULL);
  1001. ast_cond_init(&suspender->cond_complete, NULL);
  1002. ao2_ref(suspender, +1);
  1003. res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
  1004. if (res) {
  1005. /* We will just have to hope that the system does not deadlock */
  1006. ao2_ref(suspender, -2);
  1007. return;
  1008. }
  1009. session->suspended = suspender;
  1010. /* Wait for the serializer to get suspended. */
  1011. ao2_lock(suspender);
  1012. while (!suspender->suspended) {
  1013. ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
  1014. }
  1015. ao2_unlock(suspender);
  1016. }
  1017. void ast_sip_session_unsuspend(struct ast_sip_session *session)
  1018. {
  1019. struct ast_sip_session_suspender *suspender = session->suspended;
  1020. if (!suspender) {
  1021. /* Nothing to do */
  1022. return;
  1023. }
  1024. session->suspended = NULL;
  1025. /* Signal that the serializer task suspension is now complete. */
  1026. ao2_lock(suspender);
  1027. suspender->complete = 1;
  1028. ast_cond_signal(&suspender->cond_complete);
  1029. ao2_unlock(suspender);
  1030. ao2_ref(suspender, -1);
  1031. }
  1032. static int session_outbound_auth(pjsip_dialog *dlg, pjsip_tx_data *tdata, void *user_data)
  1033. {
  1034. pjsip_inv_session *inv = pjsip_dlg_get_inv_session(dlg);
  1035. struct ast_sip_session *session = inv->mod_data[session_module.id];
  1036. if (inv->state < PJSIP_INV_STATE_CONFIRMED && tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD) {
  1037. pjsip_inv_uac_restart(inv, PJ_FALSE);
  1038. }
  1039. ast_sip_session_send_request(session, tdata);
  1040. return 0;
  1041. }
  1042. struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
  1043. struct ast_sip_contact *contact, const char *location, const char *request_user,
  1044. struct ast_format_cap *req_caps)
  1045. {
  1046. const char *uri = NULL;
  1047. RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
  1048. pjsip_timer_setting timer;
  1049. pjsip_dialog *dlg;
  1050. struct pjsip_inv_session *inv_session;
  1051. RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
  1052. /* If no location has been provided use the AOR list from the endpoint itself */
  1053. if (location || !contact) {
  1054. location = S_OR(location, endpoint->aors);
  1055. found_contact = ast_sip_location_retrieve_contact_from_aor_list(location);
  1056. if (!found_contact || ast_strlen_zero(found_contact->uri)) {
  1057. uri = location;
  1058. } else {
  1059. uri = found_contact->uri;
  1060. }
  1061. } else {
  1062. uri = contact->uri;
  1063. }
  1064. /* If we still have no URI to dial fail to create the session */
  1065. if (ast_strlen_zero(uri)) {
  1066. return NULL;
  1067. }
  1068. if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
  1069. return NULL;
  1070. }
  1071. if (ast_sip_dialog_setup_outbound_authentication(dlg, endpoint, session_outbound_auth, NULL)) {
  1072. pjsip_dlg_terminate(dlg);
  1073. return NULL;
  1074. }
  1075. if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
  1076. pjsip_dlg_terminate(dlg);
  1077. return NULL;
  1078. }
  1079. #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
  1080. inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
  1081. #endif
  1082. pjsip_timer_setting_default(&timer);
  1083. timer.min_se = endpoint->extensions.timer.min_se;
  1084. timer.sess_expires = endpoint->extensions.timer.sess_expires;
  1085. pjsip_timer_init_session(inv_session, &timer);
  1086. if (!(session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact, inv_session))) {
  1087. pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
  1088. return NULL;
  1089. }
  1090. ast_party_id_copy(&session->id, &endpoint->id.self);
  1091. if (ast_format_cap_count(req_caps)) {
  1092. /* get joint caps between req_caps and endpoint caps */
  1093. struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  1094. ast_format_cap_get_compatible(req_caps, session->endpoint->media.codecs, joint_caps);
  1095. /* if joint caps */
  1096. if (ast_format_cap_count(joint_caps)) {
  1097. /* copy endpoint caps into session->req_caps */
  1098. ast_format_cap_append_from_cap(session->req_caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
  1099. /* replace instances of joint caps equivalents in session->req_caps */
  1100. ast_format_cap_replace_from_cap(session->req_caps, joint_caps, AST_MEDIA_TYPE_UNKNOWN);
  1101. }
  1102. ao2_cleanup(joint_caps);
  1103. }
  1104. if ((pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS)) {
  1105. pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
  1106. /* Since we are not notifying ourselves that the INVITE session is being terminated
  1107. * we need to manually drop its reference to session
  1108. */
  1109. ao2_ref(session, -1);
  1110. return NULL;
  1111. }
  1112. ao2_ref(session, +1);
  1113. return session;
  1114. }
  1115. static int session_termination_task(void *data)
  1116. {
  1117. RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
  1118. pjsip_tx_data *packet = NULL;
  1119. if (!session->inv_session) {
  1120. return 0;
  1121. }
  1122. if (pjsip_inv_end_session(session->inv_session, 603, NULL, &packet) == PJ_SUCCESS) {
  1123. ast_sip_session_send_request(session, packet);
  1124. }
  1125. return 0;
  1126. }
  1127. static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
  1128. {
  1129. struct ast_sip_session *session = entry->user_data;
  1130. if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
  1131. ao2_cleanup(session);
  1132. }
  1133. }
  1134. void ast_sip_session_defer_termination(struct ast_sip_session *session)
  1135. {
  1136. pj_time_val delay = { .sec = 60, };
  1137. session->defer_terminate = 1;
  1138. session->scheduled_termination.id = 0;
  1139. ao2_ref(session, +1);
  1140. session->scheduled_termination.user_data = session;
  1141. session->scheduled_termination.cb = session_termination_cb;
  1142. if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &session->scheduled_termination, &delay) != PJ_SUCCESS) {
  1143. ao2_ref(session, -1);
  1144. }
  1145. }
  1146. struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
  1147. {
  1148. pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
  1149. struct ast_sip_session *session;
  1150. if (!inv_session ||
  1151. !(session = inv_session->mod_data[session_module.id])) {
  1152. return NULL;
  1153. }
  1154. ao2_ref(session, +1);
  1155. return session;
  1156. }
  1157. enum sip_get_destination_result {
  1158. /*! The extension was successfully found */
  1159. SIP_GET_DEST_EXTEN_FOUND,
  1160. /*! The extension specified in the RURI was not found */
  1161. SIP_GET_DEST_EXTEN_NOT_FOUND,
  1162. /*! The extension specified in the RURI was a partial match */
  1163. SIP_GET_DEST_EXTEN_PARTIAL,
  1164. /*! The RURI is of an unsupported scheme */
  1165. SIP_GET_DEST_UNSUPPORTED_URI,
  1166. };
  1167. /*!
  1168. * \brief Determine where in the dialplan a call should go
  1169. *
  1170. * This uses the username in the request URI to try to match
  1171. * an extension in the endpoint's configured context in order
  1172. * to route the call.
  1173. *
  1174. * \param session The inbound SIP session
  1175. * \param rdata The SIP INVITE
  1176. */
  1177. static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
  1178. {
  1179. pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
  1180. pjsip_sip_uri *sip_ruri;
  1181. struct ast_features_pickup_config *pickup_cfg;
  1182. const char *pickupexten;
  1183. if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
  1184. return SIP_GET_DEST_UNSUPPORTED_URI;
  1185. }
  1186. sip_ruri = pjsip_uri_get_uri(ruri);
  1187. ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
  1188. pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
  1189. if (!pickup_cfg) {
  1190. ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
  1191. pickupexten = "";
  1192. } else {
  1193. pickupexten = ast_strdupa(pickup_cfg->pickupexten);
  1194. ao2_ref(pickup_cfg, -1);
  1195. }
  1196. if (!strcmp(session->exten, pickupexten) ||
  1197. ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
  1198. return SIP_GET_DEST_EXTEN_FOUND;
  1199. }
  1200. /* XXX In reality, we'll likely have further options so that partial matches
  1201. * can be indicated here, but for getting something up and running, we're going
  1202. * to return a "not exists" error here.
  1203. */
  1204. return SIP_GET_DEST_EXTEN_NOT_FOUND;
  1205. }
  1206. static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
  1207. {
  1208. pjsip_tx_data *tdata;
  1209. pjsip_dialog *dlg;
  1210. pjsip_inv_session *inv_session;
  1211. unsigned int options = endpoint->extensions.flags;
  1212. if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
  1213. if (tdata) {
  1214. pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
  1215. } else {
  1216. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  1217. }
  1218. return NULL;
  1219. }
  1220. dlg = ast_sip_create_dialog_uas(endpoint, rdata);
  1221. if (!dlg) {
  1222. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  1223. return NULL;
  1224. }
  1225. if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
  1226. pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
  1227. pjsip_dlg_terminate(dlg);
  1228. return NULL;
  1229. }
  1230. #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
  1231. inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
  1232. #endif
  1233. if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
  1234. if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
  1235. pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
  1236. }
  1237. pjsip_inv_send_msg(inv_session, tdata);
  1238. return NULL;
  1239. }
  1240. return inv_session;
  1241. }
  1242. struct new_invite {
  1243. /*! \brief Session created for the new INVITE */
  1244. struct ast_sip_session *session;
  1245. /*! \brief INVITE request itself */
  1246. pjsip_rx_data *rdata;
  1247. };
  1248. static void new_invite_destroy(void *obj)
  1249. {
  1250. struct new_invite *invite = obj;
  1251. ao2_cleanup(invite->session);
  1252. if (invite->rdata) {
  1253. pjsip_rx_data_free_cloned(invite->rdata);
  1254. }
  1255. }
  1256. static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
  1257. {
  1258. struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
  1259. if (!invite) {
  1260. return NULL;
  1261. }
  1262. ao2_ref(session, +1);
  1263. invite->session = session;
  1264. if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
  1265. ao2_ref(invite, -1);
  1266. return NULL;
  1267. }
  1268. return invite;
  1269. }
  1270. static int new_invite(void *data)
  1271. {
  1272. RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
  1273. pjsip_tx_data *tdata = NULL;
  1274. pjsip_timer_setting timer;
  1275. pjsip_rdata_sdp_info *sdp_info;
  1276. pjmedia_sdp_session *local = NULL;
  1277. /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
  1278. * so that we will be notified so we can destroy the session properly
  1279. */
  1280. switch (get_destination(invite->session, invite->rdata)) {
  1281. case SIP_GET_DEST_EXTEN_FOUND:
  1282. /* Things worked. Keep going */
  1283. break;
  1284. case SIP_GET_DEST_UNSUPPORTED_URI:
  1285. if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
  1286. ast_sip_session_send_response(invite->session, tdata);
  1287. } else {
  1288. pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
  1289. }
  1290. return 0;
  1291. case SIP_GET_DEST_EXTEN_NOT_FOUND:
  1292. case SIP_GET_DEST_EXTEN_PARTIAL:
  1293. default:
  1294. ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
  1295. ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
  1296. invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
  1297. if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
  1298. ast_sip_session_send_response(invite->session, tdata);
  1299. } else {
  1300. pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
  1301. }
  1302. return 0;
  1303. };
  1304. if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
  1305. if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
  1306. if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
  1307. ast_sip_session_send_response(invite->session, tdata);
  1308. } else {
  1309. pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
  1310. }
  1311. return 0;
  1312. }
  1313. /* We are creating a local SDP which is an answer to their offer */
  1314. local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
  1315. } else {
  1316. /* We are creating a local SDP which is an offer */
  1317. local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
  1318. }
  1319. /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
  1320. if (!local) {
  1321. if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
  1322. ast_sip_session_send_response(invite->session, tdata);
  1323. } else {
  1324. pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
  1325. }
  1326. return 0;
  1327. } else {
  1328. pjsip_inv_set_local_sdp(invite->session->inv_session, local);
  1329. pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
  1330. #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
  1331. pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
  1332. #endif
  1333. }
  1334. pjsip_timer_setting_default(&timer);
  1335. timer.min_se = invite->session->endpoint->extensions.timer.min_se;
  1336. timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
  1337. pjsip_timer_init_session(invite->session->inv_session, &timer);
  1338. /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
  1339. if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
  1340. pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
  1341. return 0;
  1342. }
  1343. ast_sip_session_send_response(invite->session, tdata);
  1344. handle_incoming_request(invite->session, invite->rdata, PJSIP_EVENT_RX_MSG);
  1345. return 0;
  1346. }
  1347. static void handle_new_invite_request(pjsip_rx_data *rdata)
  1348. {
  1349. RAII_VAR(struct ast_sip_endpoint *, endpoint,
  1350. ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
  1351. pjsip_tx_data *tdata = NULL;
  1352. pjsip_inv_session *inv_session = NULL;
  1353. RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
  1354. struct new_invite *invite;
  1355. ast_assert(endpoint != NULL);
  1356. inv_session = pre_session_setup(rdata, endpoint);
  1357. if (!inv_session) {
  1358. /* pre_session_setup() returns a response on failure */
  1359. return;
  1360. }
  1361. session = ast_sip_session_alloc(endpoint, NULL, inv_session);
  1362. if (!session) {
  1363. if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
  1364. pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
  1365. } else {
  1366. pjsip_inv_send_msg(inv_session, tdata);
  1367. }
  1368. return;
  1369. }
  1370. invite = new_invite_alloc(session, rdata);
  1371. if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
  1372. if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
  1373. pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
  1374. } else {
  1375. pjsip_inv_send_msg(inv_session, tdata);
  1376. }
  1377. ao2_ref(session, -1);
  1378. ao2_cleanup(invite);
  1379. return;
  1380. }
  1381. }
  1382. static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
  1383. {
  1384. pj_str_t method;
  1385. if (ast_strlen_zero(supplement_method)) {
  1386. return PJ_TRUE;
  1387. }
  1388. pj_cstr(&method, supplement_method);
  1389. return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
  1390. }
  1391. static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
  1392. {
  1393. struct ast_sip_session_supplement *supplement;
  1394. struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
  1395. if (!session) {
  1396. return PJ_FALSE;
  1397. }
  1398. AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
  1399. if (does_method_match(&method->name, supplement->method)) {
  1400. return PJ_TRUE;
  1401. }
  1402. }
  1403. return PJ_FALSE;
  1404. }
  1405. /*!
  1406. * \brief Called when a new SIP request comes into PJSIP
  1407. *
  1408. * This function is called under two circumstances
  1409. * 1) An out-of-dialog request is received by PJSIP
  1410. * 2) An in-dialog request that the inv_session layer does not
  1411. * handle is received (such as an in-dialog INFO)
  1412. *
  1413. * In all cases, there is very little we actually do in this function
  1414. * 1) For requests we don't handle, we return PJ_FALSE
  1415. * 2) For new INVITEs, throw the work into the SIP threadpool to be done
  1416. * there to free up the thread(s) handling incoming requests
  1417. * 3) For in-dialog requests we handle, we defer handling them until the
  1418. * on_inv_state_change() callback instead (where we will end up putting
  1419. * them into the threadpool).
  1420. */
  1421. static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
  1422. {
  1423. pj_status_t handled = PJ_FALSE;
  1424. pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
  1425. pjsip_inv_session *inv_session;
  1426. switch (rdata->msg_info.msg->line.req.method.id) {
  1427. case PJSIP_INVITE_METHOD:
  1428. if (dlg) {
  1429. ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
  1430. break;
  1431. }
  1432. handled = PJ_TRUE;
  1433. handle_new_invite_request(rdata);
  1434. break;
  1435. default:
  1436. /* Handle other in-dialog methods if their supplements have been registered */
  1437. handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
  1438. has_supplement(inv_session->mod_data[session_module.id], rdata);
  1439. break;
  1440. }
  1441. return handled;
  1442. }
  1443. struct reschedule_reinvite_data {
  1444. struct ast_sip_session *session;
  1445. struct ast_sip_session_delayed_request *delay;
  1446. };
  1447. static struct reschedule_reinvite_data *reschedule_reinvite_data_alloc(
  1448. struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
  1449. {
  1450. struct reschedule_reinvite_data *rrd = ast_malloc(sizeof(*rrd));
  1451. if (!rrd) {
  1452. return NULL;
  1453. }
  1454. ao2_ref(session, +1);
  1455. rrd->session = session;
  1456. rrd->delay = delay;
  1457. return rrd;
  1458. }
  1459. static void reschedule_reinvite_data_destroy(struct reschedule_reinvite_data *rrd)
  1460. {
  1461. ao2_cleanup(rrd->session);
  1462. ast_free(rrd->delay);
  1463. ast_free(rrd);
  1464. }
  1465. static int really_resend_reinvite(void *data)
  1466. {
  1467. RAII_VAR(struct reschedule_reinvite_data *, rrd, data, reschedule_reinvite_data_destroy);
  1468. return send_delayed_request(rrd->session, rrd->delay);
  1469. }
  1470. static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
  1471. {
  1472. struct reschedule_reinvite_data *rrd = entry->user_data;
  1473. ast_sip_push_task(rrd->session->serializer, really_resend_reinvite, entry->user_data);
  1474. }
  1475. static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response, pjsip_tx_data *tdata)
  1476. {
  1477. struct ast_sip_session_delayed_request *delay = delayed_request_alloc("INVITE",
  1478. NULL, NULL, on_response, 1, tdata);
  1479. pjsip_inv_session *inv = session->inv_session;
  1480. struct reschedule_reinvite_data *rrd = reschedule_reinvite_data_alloc(session, delay);
  1481. pj_time_val tv;
  1482. if (!rrd || !delay) {
  1483. return;
  1484. }
  1485. tv.sec = 0;
  1486. if (inv->role == PJSIP_ROLE_UAC) {
  1487. tv.msec = 2100 + ast_random() % 2000;
  1488. } else {
  1489. tv.msec = ast_random() % 2000;
  1490. }
  1491. pj_timer_entry_init(&session->rescheduled_reinvite, 0, rrd, resend_reinvite);
  1492. pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &session->rescheduled_reinvite, &tv);
  1493. }
  1494. static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
  1495. {
  1496. struct ast_sip_session *session;
  1497. ast_debug(5, "Function %s called on event %s\n", function, pjsip_event_str(e->type));
  1498. if (!inv) {
  1499. ast_debug(5, "Transaction %p does not belong to an inv_session?\n", tsx);
  1500. ast_debug(5, "The transaction state is %s\n", pjsip_tsx_state_str(tsx->state));
  1501. return;
  1502. }
  1503. session = inv->mod_data[session_module.id];
  1504. if (!session) {
  1505. ast_debug(5, "inv_session %p has no ast session\n", inv);
  1506. } else {
  1507. ast_debug(5, "The state change pertains to the session with %s\n",
  1508. ast_sorcery_object_get_id(session->endpoint));
  1509. }
  1510. if (inv->invite_tsx) {
  1511. ast_debug(5, "The inv session still has an invite_tsx (%p)\n", inv->invite_tsx);
  1512. } else {
  1513. ast_debug(5, "The inv session does NOT have an invite_tsx\n");
  1514. }
  1515. if (tsx) {
  1516. ast_debug(5, "The transaction involved in this state change is %p\n", tsx);
  1517. ast_debug(5, "The current transaction state is %s\n", pjsip_tsx_state_str(tsx->state));
  1518. ast_debug(5, "The transaction state change event is %s\n", pjsip_event_str(e->body.tsx_state.type));
  1519. } else {
  1520. ast_debug(5, "There is no transaction involved in this state change\n");
  1521. }
  1522. ast_debug(5, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
  1523. }
  1524. #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
  1525. static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type)
  1526. {
  1527. struct ast_sip_session_supplement *supplement;
  1528. struct pjsip_request_line req = rdata->msg_info.msg->line.req;
  1529. ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
  1530. AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
  1531. if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
  1532. if (supplement->incoming_request(session, rdata)) {
  1533. break;
  1534. }
  1535. }
  1536. }
  1537. }
  1538. static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
  1539. enum ast_sip_session_response_priority response_priority)
  1540. {
  1541. struct ast_sip_session_supplement *supplement;
  1542. struct pjsip_status_line status = rdata->msg_info.msg->line.status;
  1543. ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
  1544. pj_strbuf(&status.reason));
  1545. AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
  1546. if (!(supplement->response_priority & response_priority)) {
  1547. continue;
  1548. }
  1549. if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
  1550. supplement->incoming_response(session, rdata);
  1551. }
  1552. }
  1553. }
  1554. static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
  1555. enum ast_sip_session_response_priority response_priority)
  1556. {
  1557. ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
  1558. "request" : "response");
  1559. if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
  1560. handle_incoming_request(session, rdata, type);
  1561. } else {
  1562. handle_incoming_response(session, rdata, type, response_priority);
  1563. }
  1564. return 0;
  1565. }
  1566. static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
  1567. {
  1568. struct ast_sip_session_supplement *supplement;
  1569. struct pjsip_request_line req = tdata->msg->line.req;
  1570. ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
  1571. AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
  1572. if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
  1573. supplement->outgoing_request(session, tdata);
  1574. }
  1575. }
  1576. }
  1577. static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
  1578. {
  1579. struct ast_sip_session_supplement *supplement;
  1580. struct pjsip_status_line status = tdata->msg->line.status;
  1581. pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
  1582. ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
  1583. pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
  1584. pj_strbuf(&status.reason));
  1585. AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
  1586. if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
  1587. supplement->outgoing_response(session, tdata);
  1588. }
  1589. }
  1590. }
  1591. static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
  1592. {
  1593. ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
  1594. "request" : "response");
  1595. if (tdata->msg->type == PJSIP_REQUEST_MSG) {
  1596. handle_outgoing_request(session, tdata);
  1597. } else {
  1598. handle_outgoing_response(session, tdata);
  1599. }
  1600. }
  1601. static int session_end(struct ast_sip_session *session)
  1602. {
  1603. struct ast_sip_session_supplement *iter;
  1604. /* Stop the scheduled termination */
  1605. if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &session->scheduled_termination)) {
  1606. ao2_ref(session, -1);
  1607. }
  1608. /* Session is dead. Let's get rid of the reference to the session */
  1609. AST_LIST_TRAVERSE(&session->supplements, iter, next) {
  1610. if (iter->session_end) {
  1611. iter->session_end(session);
  1612. }
  1613. }
  1614. session->inv_session->mod_data[session_module.id] = NULL;
  1615. ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
  1616. ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
  1617. ao2_cleanup(session);
  1618. return 0;
  1619. }
  1620. static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
  1621. {
  1622. struct ast_sip_session *session = inv->mod_data[session_module.id];
  1623. pjsip_event_id_e type;
  1624. if (e) {
  1625. print_debug_details(inv, NULL, e);
  1626. type = e->type;
  1627. } else {
  1628. type = PJSIP_EVENT_UNKNOWN;
  1629. }
  1630. if (!session) {
  1631. return;
  1632. }
  1633. switch(type) {
  1634. case PJSIP_EVENT_TX_MSG:
  1635. handle_outgoing(session, e->body.tx_msg.tdata);
  1636. break;
  1637. case PJSIP_EVENT_RX_MSG:
  1638. handle_incoming(session, e->body.rx_msg.rdata, type,
  1639. AST_SIP_SESSION_BEFORE_MEDIA);
  1640. break;
  1641. case PJSIP_EVENT_TSX_STATE:
  1642. ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
  1643. /* Transaction state changes are prompted by some other underlying event. */
  1644. switch(e->body.tsx_state.type) {
  1645. case PJSIP_EVENT_TX_MSG:
  1646. handle_outgoing(session, e->body.tsx_state.src.tdata);
  1647. break;
  1648. case PJSIP_EVENT_RX_MSG:
  1649. handle_incoming(session, e->body.tsx_state.src.rdata, type,
  1650. AST_SIP_SESSION_BEFORE_MEDIA);
  1651. break;
  1652. case PJSIP_EVENT_TRANSPORT_ERROR:
  1653. case PJSIP_EVENT_TIMER:
  1654. case PJSIP_EVENT_USER:
  1655. case PJSIP_EVENT_UNKNOWN:
  1656. case PJSIP_EVENT_TSX_STATE:
  1657. /* Inception? */
  1658. break;
  1659. }
  1660. break;
  1661. case PJSIP_EVENT_TRANSPORT_ERROR:
  1662. case PJSIP_EVENT_TIMER:
  1663. case PJSIP_EVENT_UNKNOWN:
  1664. case PJSIP_EVENT_USER:
  1665. default:
  1666. break;
  1667. }
  1668. if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
  1669. session_end(session);
  1670. }
  1671. }
  1672. static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
  1673. {
  1674. /* XXX STUB */
  1675. }
  1676. static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
  1677. {
  1678. ast_sip_session_response_cb cb;
  1679. struct ast_sip_session *session = inv->mod_data[session_module.id];
  1680. print_debug_details(inv, tsx, e);
  1681. if (!session) {
  1682. /* Transaction likely timed out after the call was hung up. Just
  1683. * ignore such transaction changes
  1684. */
  1685. return;
  1686. }
  1687. switch (e->body.tsx_state.type) {
  1688. case PJSIP_EVENT_TX_MSG:
  1689. handle_outgoing(session, e->body.tsx_state.src.tdata);
  1690. /* When we create an outgoing request, we do not have access to the transaction that
  1691. * is created. Instead, We have to place transaction-specific data in the tdata. Here,
  1692. * we transfer the data into the transaction. This way, when we receive a response, we
  1693. * can dig this data out again
  1694. */
  1695. tsx->mod_data[session_module.id] = e->body.tsx_state.src.tdata->mod_data[session_module.id];
  1696. break;
  1697. case PJSIP_EVENT_RX_MSG:
  1698. handle_incoming(session, e->body.tsx_state.src.rdata, e->type,
  1699. AST_SIP_SESSION_AFTER_MEDIA);
  1700. if (tsx->method.id == PJSIP_INVITE_METHOD) {
  1701. if (tsx->role == PJSIP_ROLE_UAC) {
  1702. if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
  1703. /* This means we got a non 2XX final response to our outgoing INVITE */
  1704. if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
  1705. reschedule_reinvite(session, tsx->mod_data[session_module.id], tsx->last_tx);
  1706. return;
  1707. } else if (inv->state == PJSIP_INV_STATE_CONFIRMED &&
  1708. tsx->status_code != 488) {
  1709. /* Other reinvite failures (except 488) result in destroying the session. */
  1710. pjsip_tx_data *tdata;
  1711. if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
  1712. ast_sip_session_send_request(session, tdata);
  1713. }
  1714. }
  1715. } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
  1716. if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {
  1717. /* This is a race condition detailed in RFC 5407 section 3.1.2.
  1718. * We sent a CANCEL at the same time that the UAS sent us a 200 OK for
  1719. * the original INVITE. As a result, we have now received a 200 OK for
  1720. * a cancelled call. Our role is to immediately send a BYE to end the
  1721. * dialog.
  1722. */
  1723. pjsip_tx_data *tdata;
  1724. if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
  1725. ast_sip_session_send_request(session, tdata);
  1726. }
  1727. }
  1728. }
  1729. }
  1730. }
  1731. if ((cb = ast_sip_mod_data_get(tsx->mod_data, session_module.id,
  1732. MOD_DATA_ON_RESPONSE))) {
  1733. cb(session, e->body.tsx_state.src.rdata);
  1734. }
  1735. case PJSIP_EVENT_TRANSPORT_ERROR:
  1736. case PJSIP_EVENT_TIMER:
  1737. case PJSIP_EVENT_USER:
  1738. case PJSIP_EVENT_UNKNOWN:
  1739. case PJSIP_EVENT_TSX_STATE:
  1740. /* Inception? */
  1741. break;
  1742. }
  1743. /* Terminated INVITE transactions always should result in queuing delayed requests,
  1744. * no matter what event caused the transaction to terminate
  1745. */
  1746. if (tsx->method.id == PJSIP_INVITE_METHOD &&
  1747. ((tsx->state == PJSIP_TSX_STATE_TERMINATED) ||
  1748. (tsx->state == PJSIP_TSX_STATE_PROCEEDING))) {
  1749. queue_delayed_request(session);
  1750. }
  1751. }
  1752. static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
  1753. {
  1754. struct ast_sip_session_media *session_media = obj;
  1755. pjmedia_sdp_session *answer = arg;
  1756. struct ast_sip_session *session = data;
  1757. struct ast_sip_session_sdp_handler *handler = session_media->handler;
  1758. RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
  1759. int res;
  1760. if (handler) {
  1761. /* if an already assigned handler does not handle the session_media or reports a catastrophic error, fail */
  1762. res = handler->create_outgoing_sdp_stream(session, session_media, answer);
  1763. if (res <= 0) {
  1764. return 0;
  1765. }
  1766. return CMP_MATCH;
  1767. }
  1768. handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
  1769. if (!handler_list) {
  1770. return CMP_MATCH;
  1771. }
  1772. /* no handler for this stream type and we have a list to search */
  1773. AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
  1774. res = handler->create_outgoing_sdp_stream(session, session_media, answer);
  1775. if (res < 0) {
  1776. /* catastrophic error */
  1777. return 0;
  1778. }
  1779. if (res > 0) {
  1780. /* Handled by this handler. Move to the next stream */
  1781. session_media->handler = handler;
  1782. return CMP_MATCH;
  1783. }
  1784. }
  1785. /* streams that weren't handled won't be included in generated outbound SDP */
  1786. return CMP_MATCH;
  1787. }
  1788. static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
  1789. {
  1790. RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
  1791. static const pj_str_t STR_IN = { "IN", 2 };
  1792. static const pj_str_t STR_IP4 = { "IP4", 3 };
  1793. static const pj_str_t STR_IP6 = { "IP6", 3 };
  1794. pjmedia_sdp_session *local;
  1795. if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
  1796. return NULL;
  1797. }
  1798. if (!offer) {
  1799. local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
  1800. } else {
  1801. local->origin.version = offer->origin.version + 1;
  1802. local->origin.id = offer->origin.id;
  1803. }
  1804. pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);
  1805. pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);
  1806. /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
  1807. successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
  1808. if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {
  1809. /* Something experienced a catastrophic failure */
  1810. return NULL;
  1811. }
  1812. /* Use the connection details of the first media stream if possible for SDP level */
  1813. if (local->media_count) {
  1814. int stream;
  1815. /* Since we are using the first media stream as the SDP level we can get rid of it
  1816. * from the stream itself
  1817. */
  1818. local->conn = local->media[0]->conn;
  1819. local->media[0]->conn = NULL;
  1820. pj_strassign(&local->origin.net_type, &local->conn->net_type);
  1821. pj_strassign(&local->origin.addr_type, &local->conn->addr_type);
  1822. pj_strassign(&local->origin.addr, &local->conn->addr);
  1823. /* Go through each media stream seeing if the connection details actually differ,
  1824. * if not just use SDP level and reduce the SDP size
  1825. */
  1826. for (stream = 1; stream < local->media_count; stream++) {
  1827. if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&
  1828. !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&
  1829. !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {
  1830. local->media[stream]->conn = NULL;
  1831. }
  1832. }
  1833. } else {
  1834. local->origin.net_type = STR_IN;
  1835. local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
  1836. if (!ast_strlen_zero(session->endpoint->media.address)) {
  1837. pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);
  1838. } else {
  1839. pj_sockaddr localaddr;
  1840. char our_ip[PJ_INET6_ADDRSTRLEN];
  1841. pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr);
  1842. pj_sockaddr_print(&localaddr, our_ip, sizeof(our_ip), 0);
  1843. pj_strdup2(inv->pool_prov, &local->origin.addr, our_ip);
  1844. }
  1845. }
  1846. return local;
  1847. }
  1848. static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
  1849. {
  1850. struct ast_sip_session *session = inv->mod_data[session_module.id];
  1851. pjmedia_sdp_session *answer;
  1852. if (handle_incoming_sdp(session, offer)) {
  1853. return;
  1854. }
  1855. if ((answer = create_local_sdp(inv, session, offer))) {
  1856. pjsip_inv_set_sdp_answer(inv, answer);
  1857. }
  1858. }
  1859. #if 0
  1860. static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
  1861. {
  1862. /* XXX STUB */
  1863. }
  1864. #endif
  1865. static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
  1866. {
  1867. struct ast_sip_session *session = inv->mod_data[session_module.id];
  1868. const pjmedia_sdp_session *local, *remote;
  1869. if (!session->channel) {
  1870. /* If we don't have a channel. We really don't care about media updates.
  1871. * Just ignore
  1872. */
  1873. return;
  1874. }
  1875. if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
  1876. (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
  1877. ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
  1878. ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
  1879. ast_queue_hangup(session->channel);
  1880. return;
  1881. }
  1882. handle_negotiated_sdp(session, local, remote);
  1883. }
  1884. static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
  1885. {
  1886. struct ast_sip_session *session = inv->mod_data[session_module.id];
  1887. const pjsip_sip_uri *uri;
  1888. if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {
  1889. return PJSIP_REDIRECT_ACCEPT;
  1890. }
  1891. if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {
  1892. return PJSIP_REDIRECT_STOP;
  1893. }
  1894. handle_incoming(session, e->body.rx_msg.rdata, PJSIP_EVENT_RX_MSG,
  1895. AST_SIP_SESSION_BEFORE_REDIRECTING);
  1896. uri = pjsip_uri_get_uri(target);
  1897. if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {
  1898. char exten[AST_MAX_EXTENSION];
  1899. ast_copy_pj_str(exten, &uri->user, sizeof(exten));
  1900. ast_channel_call_forward_set(session->channel, exten);
  1901. } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {
  1902. char target_uri[PJSIP_MAX_URL_SIZE];
  1903. /* PJSIP/ + endpoint length + / + max URL size */
  1904. char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];
  1905. pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));
  1906. sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);
  1907. ast_channel_call_forward_set(session->channel, forward);
  1908. }
  1909. return PJSIP_REDIRECT_STOP;
  1910. }
  1911. static pjsip_inv_callback inv_callback = {
  1912. .on_state_changed = session_inv_on_state_changed,
  1913. .on_new_session = session_inv_on_new_session,
  1914. .on_tsx_state_changed = session_inv_on_tsx_state_changed,
  1915. .on_rx_offer = session_inv_on_rx_offer,
  1916. .on_media_update = session_inv_on_media_update,
  1917. .on_redirected = session_inv_on_redirected,
  1918. };
  1919. /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
  1920. static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
  1921. {
  1922. struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(
  1923. tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);
  1924. struct pjmedia_sdp_session *sdp;
  1925. int stream;
  1926. /* SDP produced by us directly will never be multipart */
  1927. if (hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
  1928. pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
  1929. return;
  1930. }
  1931. sdp = tdata->msg->body->data;
  1932. if (sdp->conn) {
  1933. char host[NI_MAXHOST];
  1934. struct ast_sockaddr addr = { { 0, } };
  1935. ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));
  1936. ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
  1937. if (ast_apply_ha(transport->localnet, &addr) != AST_SENSE_ALLOW) {
  1938. pj_strdup2(tdata->pool, &sdp->conn->addr, transport->external_media_address);
  1939. }
  1940. }
  1941. for (stream = 0; stream < sdp->media_count; ++stream) {
  1942. /* See if there are registered handlers for this media stream type */
  1943. char media[20];
  1944. struct ast_sip_session_sdp_handler *handler;
  1945. RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
  1946. /* We need a null-terminated version of the media string */
  1947. ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
  1948. handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
  1949. if (!handler_list) {
  1950. ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
  1951. continue;
  1952. }
  1953. AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
  1954. if (handler->change_outgoing_sdp_stream_media_address) {
  1955. handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
  1956. }
  1957. }
  1958. }
  1959. /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
  1960. ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);
  1961. }
  1962. static int load_module(void)
  1963. {
  1964. pjsip_endpoint *endpt;
  1965. CHECK_PJSIP_MODULE_LOADED();
  1966. if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
  1967. return AST_MODULE_LOAD_DECLINE;
  1968. }
  1969. if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
  1970. return AST_MODULE_LOAD_DECLINE;
  1971. }
  1972. nat_hook->outgoing_external_message = session_outgoing_nat_hook;
  1973. ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
  1974. sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
  1975. sdp_handler_list_hash, sdp_handler_list_cmp);
  1976. if (!sdp_handlers) {
  1977. return AST_MODULE_LOAD_DECLINE;
  1978. }
  1979. endpt = ast_sip_get_pjsip_endpoint();
  1980. pjsip_inv_usage_init(endpt, &inv_callback);
  1981. pjsip_100rel_init_module(endpt);
  1982. pjsip_timer_init_module(endpt);
  1983. if (ast_sip_register_service(&session_module)) {
  1984. return AST_MODULE_LOAD_DECLINE;
  1985. }
  1986. ast_sip_register_service(&session_reinvite_module);
  1987. ast_module_ref(ast_module_info->self);
  1988. return AST_MODULE_LOAD_SUCCESS;
  1989. }
  1990. static int unload_module(void)
  1991. {
  1992. /* This will never get called as this module can't be unloaded */
  1993. return 0;
  1994. }
  1995. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
  1996. .support_level = AST_MODULE_SUPPORT_CORE,
  1997. .load = load_module,
  1998. .unload = unload_module,
  1999. .load_pri = AST_MODPRI_APP_DEPEND,
  2000. );