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