2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2013, Digium, Inc.
6 * Mark Michelson <mmichelson@digium.com>
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.
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.
20 <depend>pjproject</depend>
21 <depend>res_pjsip</depend>
22 <support_level>core</support_level>
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"
49 #define SDP_HANDLER_BUCKETS 11
51 #define MOD_DATA_ON_RESPONSE "on_response"
52 #define MOD_DATA_NAT_HOOK "nat_hook"
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);
64 /*! \brief NAT hook for modifying outgoing messages with SDP */
65 static struct ast_sip_nat_hook *nat_hook;
68 * \brief Registered SDP stream handlers
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.
74 static struct ao2_container *sdp_handlers;
77 * These are the objects in the sdp_handlers container
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 */
86 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer);
88 static int sdp_handler_list_hash(const void *obj, int flags)
90 const struct sdp_handler_list *handler_list = obj;
91 const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;
93 return ast_str_hash(stream_type);
96 static int sdp_handler_list_cmp(void *obj, void *arg, int flags)
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;
102 return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
105 static int session_media_hash(const void *obj, int flags)
107 const struct ast_sip_session_media *session_media = obj;
108 const char *stream_type = flags & OBJ_KEY ? obj : session_media->stream_type;
110 return ast_str_hash(stream_type);
113 static int session_media_cmp(void *obj, void *arg, int flags)
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;
119 return strcmp(session_media1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
122 int ast_sip_session_register_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
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);
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);
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);
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);
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)) {
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);
160 static int remove_handler(void *obj, void *arg, void *data, int flags)
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;
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);
174 AST_LIST_TRAVERSE_SAFE_END;
176 if (AST_LIST_EMPTY(&handler_list->list)) {
177 ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);
184 void ast_sip_session_unregister_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
186 ao2_callback_data(sdp_handlers, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, remove_handler, (void *)stream_type, handler);
190 * \brief Set an SDP stream handler for a corresponding session media.
192 * \note Always use this function to set the SDP handler for a session media.
194 * This function will properly free resources on the SDP handler currently being
195 * used by the session media, then set the session media to use the new SDP
198 static void session_media_set_handler(struct ast_sip_session_media *session_media,
199 struct ast_sip_session_sdp_handler *handler)
201 ast_assert(session_media->handler != handler);
203 if (session_media->handler) {
204 session_media->handler->stream_destroy(session_media);
206 session_media->handler = handler;
209 static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
214 for (i = 0; i < sdp->media_count; ++i) {
215 /* See if there are registered handlers for this media stream type */
217 struct ast_sip_session_sdp_handler *handler;
218 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
219 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
222 /* We need a null-terminated version of the media string */
223 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
225 session_media = ao2_find(session->media, media, OBJ_KEY);
226 if (!session_media) {
227 /* if the session_media doesn't exist, there weren't
228 * any handlers at the time of its creation */
232 if (session_media->handler) {
233 handler = session_media->handler;
234 ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
235 session_media->stream_type,
236 session_media->handler->id);
237 res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
240 /* Catastrophic failure. Abort! */
242 } else if (res > 0) {
243 ast_debug(1, "Media stream '%s' handled by %s\n",
244 session_media->stream_type,
245 session_media->handler->id);
246 /* Handled by this handler. Move to the next stream */
252 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
254 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
257 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
258 if (handler == session_media->handler) {
261 ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
262 session_media->stream_type,
264 res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
267 /* Catastrophic failure. Abort! */
271 ast_debug(1, "Media stream '%s' handled by %s\n",
272 session_media->stream_type,
274 /* Handled by this handler. Move to the next stream */
275 session_media_set_handler(session_media, handler);
287 struct handle_negotiated_sdp_cb {
288 struct ast_sip_session *session;
289 const pjmedia_sdp_session *local;
290 const pjmedia_sdp_session *remote;
293 static int handle_negotiated_sdp_session_media(void *obj, void *arg, int flags)
295 struct ast_sip_session_media *session_media = obj;
296 struct handle_negotiated_sdp_cb *callback_data = arg;
297 struct ast_sip_session *session = callback_data->session;
298 const pjmedia_sdp_session *local = callback_data->local;
299 const pjmedia_sdp_session *remote = callback_data->remote;
302 for (i = 0; i < local->media_count; ++i) {
303 /* See if there are registered handlers for this media stream type */
305 struct ast_sip_session_sdp_handler *handler;
306 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
309 if (!remote->media[i]) {
313 /* We need a null-terminated version of the media string */
314 ast_copy_pj_str(media, &local->media[i]->desc.media, sizeof(media));
316 /* stream type doesn't match the one we're looking to fill */
317 if (strcasecmp(session_media->stream_type, media)) {
321 handler = session_media->handler;
323 ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
324 session_media->stream_type,
326 res = handler->apply_negotiated_sdp_stream(session, session_media, local,
327 local->media[i], remote, remote->media[i]);
329 ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
330 session_media->stream_type,
337 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
339 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
342 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
343 if (handler == session_media->handler) {
346 ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
347 session_media->stream_type,
349 res = handler->apply_negotiated_sdp_stream(session, session_media, local,
350 local->media[i], remote, remote->media[i]);
352 /* Catastrophic failure. Abort! */
356 ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
357 session_media->stream_type,
359 /* Handled by this handler. Move to the next stream */
360 session_media_set_handler(session_media, handler);
368 static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)
370 RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
371 struct handle_negotiated_sdp_cb callback_data = {
377 successful = ao2_callback(session->media, OBJ_MULTIPLE, handle_negotiated_sdp_session_media, &callback_data);
378 if (successful && ao2_iterator_count(successful) == ao2_container_count(session->media)) {
379 /* Nothing experienced a catastrophic failure */
380 ast_queue_frame(session->channel, &ast_null_frame);
386 AST_RWLIST_HEAD_STATIC(session_supplements, ast_sip_session_supplement);
388 int ast_sip_session_register_supplement(struct ast_sip_session_supplement *supplement)
390 struct ast_sip_session_supplement *iter;
392 SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
394 if (!supplement->response_priority) {
395 supplement->response_priority = AST_SIP_SESSION_BEFORE_MEDIA;
398 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
399 if (iter->priority > supplement->priority) {
400 AST_RWLIST_INSERT_BEFORE_CURRENT(supplement, next);
405 AST_RWLIST_TRAVERSE_SAFE_END;
408 AST_RWLIST_INSERT_TAIL(&session_supplements, supplement, next);
410 ast_module_ref(ast_module_info->self);
414 void ast_sip_session_unregister_supplement(struct ast_sip_session_supplement *supplement)
416 struct ast_sip_session_supplement *iter;
417 SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
418 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
419 if (supplement == iter) {
420 AST_RWLIST_REMOVE_CURRENT(next);
421 ast_module_unref(ast_module_info->self);
425 AST_RWLIST_TRAVERSE_SAFE_END;
428 static struct ast_sip_session_supplement *supplement_dup(const struct ast_sip_session_supplement *src)
430 struct ast_sip_session_supplement *dst = ast_calloc(1, sizeof(*dst));
434 /* Will need to revisit if shallow copy becomes an issue */
439 #define DATASTORE_BUCKETS 53
440 #define MEDIA_BUCKETS 7
442 static void session_datastore_destroy(void *obj)
444 struct ast_datastore *datastore = obj;
446 /* Using the destroy function (if present) destroy the data */
447 if (datastore->info->destroy != NULL && datastore->data != NULL) {
448 datastore->info->destroy(datastore->data);
449 datastore->data = NULL;
452 ast_free((void *) datastore->uid);
453 datastore->uid = NULL;
456 struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
458 RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
459 char uuid_buf[AST_UUID_STR_LEN];
460 const char *uid_ptr = uid;
466 datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
471 datastore->info = info;
472 if (ast_strlen_zero(uid)) {
473 /* They didn't provide an ID so we'll provide one ourself */
474 uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
477 datastore->uid = ast_strdup(uid_ptr);
478 if (!datastore->uid) {
482 ao2_ref(datastore, +1);
486 int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)
488 ast_assert(datastore != NULL);
489 ast_assert(datastore->info != NULL);
490 ast_assert(ast_strlen_zero(datastore->uid) == 0);
492 if (!ao2_link(session->datastores, datastore)) {
498 struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)
500 return ao2_find(session->datastores, name, OBJ_KEY);
503 void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)
505 ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
508 enum delayed_method {
509 DELAYED_METHOD_INVITE,
510 DELAYED_METHOD_UPDATE,
516 * \brief Convert delayed method enum value to to a string.
519 * \param method Delayed method enum value to convert to a string.
521 * \return String value of delayed method.
523 static const char *delayed_method2str(enum delayed_method method)
525 const char *str = "<unknown>";
528 case DELAYED_METHOD_INVITE:
531 case DELAYED_METHOD_UPDATE:
534 case DELAYED_METHOD_BYE:
543 * \brief Structure used for sending delayed requests
545 * Requests are typically delayed because the current transaction
546 * state of an INVITE. Once the pending INVITE transaction terminates,
547 * the delayed request will be sent
549 struct ast_sip_session_delayed_request {
550 /*! Method of the request */
551 enum delayed_method method;
552 /*! Callback to call when the delayed request is created. */
553 ast_sip_session_request_creation_cb on_request_creation;
554 /*! Callback to call when the delayed request SDP is created */
555 ast_sip_session_sdp_creation_cb on_sdp_creation;
556 /*! Callback to call when the delayed request receives a response */
557 ast_sip_session_response_cb on_response;
558 /*! Whether to generate new SDP */
559 int generate_new_sdp;
560 AST_LIST_ENTRY(ast_sip_session_delayed_request) next;
563 static struct ast_sip_session_delayed_request *delayed_request_alloc(
564 enum delayed_method method,
565 ast_sip_session_request_creation_cb on_request_creation,
566 ast_sip_session_sdp_creation_cb on_sdp_creation,
567 ast_sip_session_response_cb on_response,
568 int generate_new_sdp)
570 struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
575 delay->method = method;
576 delay->on_request_creation = on_request_creation;
577 delay->on_sdp_creation = on_sdp_creation;
578 delay->on_response = on_response;
579 delay->generate_new_sdp = generate_new_sdp;
583 static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
585 ast_debug(3, "Endpoint '%s(%s)' sending delayed %s request.\n",
586 ast_sorcery_object_get_id(session->endpoint),
587 session->channel ? ast_channel_name(session->channel) : "",
588 delayed_method2str(delay->method));
590 switch (delay->method) {
591 case DELAYED_METHOD_INVITE:
592 ast_sip_session_refresh(session, delay->on_request_creation,
593 delay->on_sdp_creation, delay->on_response,
594 AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp);
596 case DELAYED_METHOD_UPDATE:
597 ast_sip_session_refresh(session, delay->on_request_creation,
598 delay->on_sdp_creation, delay->on_response,
599 AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp);
601 case DELAYED_METHOD_BYE:
602 ast_sip_session_terminate(session, 0);
605 ast_log(LOG_WARNING, "Don't know how to send delayed %s(%d) request.\n",
606 delayed_method2str(delay->method), delay->method);
612 * \brief The current INVITE transaction is in the PROCEEDING state.
615 * \param vsession Session object.
617 * \retval 0 on success.
618 * \retval -1 on error.
620 static int invite_proceeding(void *vsession)
622 struct ast_sip_session *session = vsession;
623 struct ast_sip_session_delayed_request *delay;
627 AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
628 switch (delay->method) {
629 case DELAYED_METHOD_INVITE:
631 case DELAYED_METHOD_UPDATE:
632 AST_LIST_REMOVE_CURRENT(next);
633 res = send_delayed_request(session, delay);
637 case DELAYED_METHOD_BYE:
638 /* A BYE is pending so don't bother anymore. */
646 AST_LIST_TRAVERSE_SAFE_END;
648 ao2_ref(session, -1);
654 * \brief The current INVITE transaction is in the TERMINATED state.
657 * \param vsession Session object.
659 * \retval 0 on success.
660 * \retval -1 on error.
662 static int invite_terminated(void *vsession)
664 struct ast_sip_session *session = vsession;
665 struct ast_sip_session_delayed_request *delay;
670 /* re-INVITE collision timer running? */
671 timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);
673 AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
674 switch (delay->method) {
675 case DELAYED_METHOD_INVITE:
676 if (!timer_running) {
680 case DELAYED_METHOD_UPDATE:
681 case DELAYED_METHOD_BYE:
686 AST_LIST_REMOVE_CURRENT(next);
687 res = send_delayed_request(session, delay);
692 AST_LIST_TRAVERSE_SAFE_END;
694 ao2_ref(session, -1);
700 * \brief INVITE collision timeout.
703 * \param vsession Session object.
705 * \retval 0 on success.
706 * \retval -1 on error.
708 static int invite_collision_timeout(void *vsession)
710 struct ast_sip_session *session = vsession;
713 if (session->inv_session->invite_tsx) {
715 * INVITE transaction still active. Let it send
716 * the collision re-INVITE when it terminates.
718 ao2_ref(session, -1);
721 res = invite_terminated(session);
729 * \brief The current UPDATE transaction is in the COMPLETED state.
732 * \param vsession Session object.
734 * \retval 0 on success.
735 * \retval -1 on error.
737 static int update_completed(void *vsession)
739 struct ast_sip_session *session = vsession;
742 if (session->inv_session->invite_tsx) {
743 res = invite_proceeding(session);
745 res = invite_terminated(session);
751 static void check_delayed_requests(struct ast_sip_session *session,
752 int (*cb)(void *vsession))
754 ao2_ref(session, +1);
755 if (ast_sip_push_task(session->serializer, cb, session)) {
756 ao2_ref(session, -1);
760 static int delay_request(struct ast_sip_session *session,
761 ast_sip_session_request_creation_cb on_request,
762 ast_sip_session_sdp_creation_cb on_sdp_creation,
763 ast_sip_session_response_cb on_response,
764 int generate_new_sdp,
765 enum delayed_method method)
767 struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,
768 on_request, on_sdp_creation, on_response, generate_new_sdp);
774 if (method == DELAYED_METHOD_BYE) {
775 /* Send BYE as early as possible */
776 AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);
778 AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
783 static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
785 pjsip_inv_session *inv_session = session->inv_session;
786 const pjmedia_sdp_session *previous_sdp;
788 if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
789 pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
791 pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
793 return create_local_sdp(inv_session, session, previous_sdp);
796 int ast_sip_session_refresh(struct ast_sip_session *session,
797 ast_sip_session_request_creation_cb on_request_creation,
798 ast_sip_session_sdp_creation_cb on_sdp_creation,
799 ast_sip_session_response_cb on_response,
800 enum ast_sip_session_refresh_method method, int generate_new_sdp)
802 pjsip_inv_session *inv_session = session->inv_session;
803 pjmedia_sdp_session *new_sdp = NULL;
804 pjsip_tx_data *tdata;
806 if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
807 /* Don't try to do anything with a hung-up call */
808 ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
809 ast_sorcery_object_get_id(session->endpoint));
813 /* If the dialog has not yet been established we have to defer until it has */
814 if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
815 ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",
816 ast_sorcery_object_get_id(session->endpoint));
817 return delay_request(session, on_request_creation, on_sdp_creation, on_response,
819 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
820 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);
823 if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
824 if (inv_session->invite_tsx) {
825 /* We can't send a reinvite yet, so delay it */
826 ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",
827 ast_sorcery_object_get_id(session->endpoint));
828 return delay_request(session, on_request_creation, on_sdp_creation,
829 on_response, generate_new_sdp, DELAYED_METHOD_INVITE);
830 } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
831 /* Initial INVITE transaction failed to progress us to a confirmed state
832 * which means re-invites are not possible
834 ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
835 ast_sorcery_object_get_id(session->endpoint));
840 if (generate_new_sdp) {
841 /* SDP can only be generated if current negotiation has already completed */
842 if (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {
843 ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",
844 ast_sorcery_object_get_id(session->endpoint));
845 return delay_request(session, on_request_creation, on_sdp_creation,
846 on_response, generate_new_sdp,
847 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
848 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);
851 new_sdp = generate_session_refresh_sdp(session);
853 ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
856 if (on_sdp_creation) {
857 if (on_sdp_creation(session, new_sdp)) {
863 if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
864 if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
865 ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
868 } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
869 ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
872 if (on_request_creation) {
873 if (on_request_creation(session, tdata)) {
877 ast_debug(3, "Sending session refresh SDP via %s to %s\n",
878 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
879 ast_sorcery_object_get_id(session->endpoint));
880 ast_sip_session_send_request_with_cb(session, tdata, on_response);
884 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
886 handle_outgoing_response(session, tdata);
887 pjsip_inv_send_msg(session->inv_session, tdata);
891 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
893 static pjsip_module session_module = {
894 .name = {"Session Module", 14},
895 .priority = PJSIP_MOD_PRIORITY_APPLICATION,
896 .on_rx_request = session_on_rx_request,
899 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
901 * \retval 1 re-invite should be deferred and resumed later
902 * \retval 0 re-invite should not be deferred
904 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
908 for (i = 0; i < sdp->media_count; ++i) {
909 /* See if there are registered handlers for this media stream type */
911 struct ast_sip_session_sdp_handler *handler;
912 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
913 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
914 enum ast_sip_session_sdp_stream_defer res;
916 /* We need a null-terminated version of the media string */
917 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
919 session_media = ao2_find(session->media, media, OBJ_KEY);
920 if (!session_media) {
921 /* if the session_media doesn't exist, there weren't
922 * any handlers at the time of its creation */
926 if (session_media->handler) {
927 handler = session_media->handler;
928 if (handler->defer_incoming_sdp_stream) {
929 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
932 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
934 case AST_SIP_SESSION_SDP_DEFER_ERROR:
936 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
938 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
942 /* Handled by this handler. Move to the next stream */
946 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
948 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
951 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
952 if (handler == session_media->handler) {
955 if (!handler->defer_incoming_sdp_stream) {
958 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
961 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
963 case AST_SIP_SESSION_SDP_DEFER_ERROR:
964 session_media_set_handler(session_media, handler);
966 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
967 /* Handled by this handler. */
968 session_media_set_handler(session_media, handler);
970 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
971 /* Handled by this handler. */
972 session_media_set_handler(session_media, handler);
975 /* Move to the next stream */
982 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
985 RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
986 pjsip_rdata_sdp_info *sdp_info;
988 if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
989 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
990 !(session = ast_sip_dialog_get_session(dlg)) ||
995 if (session->deferred_reinvite) {
996 pj_str_t key, deferred_key;
997 pjsip_tx_data *tdata;
999 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
1000 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
1001 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
1002 session->deferred_reinvite);
1004 /* If this is a retransmission ignore it */
1005 if (!pj_strcmp(&key, &deferred_key)) {
1009 /* Otherwise this is a new re-invite, so reject it */
1010 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
1011 pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1017 if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
1018 (sdp_info->sdp_err != PJ_SUCCESS)) {
1022 if (!sdp_info->sdp) {
1023 ast_queue_unhold(session->channel);
1027 if (!sdp_requires_deferral(session, sdp_info->sdp)) {
1031 pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
1036 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
1038 if (!session->deferred_reinvite) {
1042 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(), session->deferred_reinvite, NULL, NULL);
1043 pjsip_rx_data_free_cloned(session->deferred_reinvite);
1044 session->deferred_reinvite = NULL;
1047 static pjsip_module session_reinvite_module = {
1048 .name = { "Session Re-Invite Module", 24 },
1049 .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
1050 .on_rx_request = session_reinvite_on_rx_request,
1053 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
1054 ast_sip_session_response_cb on_response)
1056 pjsip_inv_session *inv_session = session->inv_session;
1058 if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1059 /* Don't try to do anything with a hung-up call */
1063 ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
1064 MOD_DATA_ON_RESPONSE, on_response);
1066 if (!ast_strlen_zero(session->endpoint->fromuser) ||
1067 !ast_strlen_zero(session->endpoint->fromdomain)) {
1068 pjsip_fromto_hdr *from = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_FROM, tdata->msg->hdr.next);
1069 pjsip_sip_uri *uri = pjsip_uri_get_uri(from->uri);
1071 if (!ast_strlen_zero(session->endpoint->fromuser)) {
1072 pj_strdup2(tdata->pool, &uri->user, session->endpoint->fromuser);
1074 if (!ast_strlen_zero(session->endpoint->fromdomain)) {
1075 pj_strdup2(tdata->pool, &uri->host, session->endpoint->fromdomain);
1079 handle_outgoing_request(session, tdata);
1080 pjsip_inv_send_msg(session->inv_session, tdata);
1084 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
1086 ast_sip_session_send_request_with_cb(session, tdata, NULL);
1089 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
1091 pjmedia_sdp_session *offer;
1093 if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
1094 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
1098 pjsip_inv_set_local_sdp(session->inv_session, offer);
1099 pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
1100 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1101 pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
1103 if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
1109 static int datastore_hash(const void *obj, int flags)
1111 const struct ast_datastore *datastore = obj;
1112 const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
1114 ast_assert(uid != NULL);
1116 return ast_str_hash(uid);
1119 static int datastore_cmp(void *obj, void *arg, int flags)
1121 const struct ast_datastore *datastore1 = obj;
1122 const struct ast_datastore *datastore2 = arg;
1123 const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
1125 ast_assert(datastore1->uid != NULL);
1126 ast_assert(uid2 != NULL);
1128 return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
1131 static void session_media_dtor(void *obj)
1133 struct ast_sip_session_media *session_media = obj;
1134 struct sdp_handler_list *handler_list;
1135 /* It is possible for SDP handlers to allocate memory on a session_media but
1136 * not end up getting set as the handler for this session_media. This traversal
1137 * ensures that all memory allocated by SDP handlers on the session_media is
1138 * cleared (as well as file descriptors, etc.).
1140 handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
1142 struct ast_sip_session_sdp_handler *handler;
1144 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1145 handler->stream_destroy(session_media);
1148 ao2_cleanup(handler_list);
1149 if (session_media->srtp) {
1150 ast_sdp_srtp_destroy(session_media->srtp);
1154 static void session_destructor(void *obj)
1156 struct ast_sip_session *session = obj;
1157 struct ast_sip_session_supplement *supplement;
1158 struct ast_sip_session_delayed_request *delay;
1160 ast_debug(3, "Destroying SIP session with endpoint %s\n",
1161 ast_sorcery_object_get_id(session->endpoint));
1163 while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
1164 if (supplement->session_destroy) {
1165 supplement->session_destroy(session);
1167 ast_free(supplement);
1170 ast_taskprocessor_unreference(session->serializer);
1171 ao2_cleanup(session->datastores);
1172 ao2_cleanup(session->media);
1174 AST_LIST_HEAD_DESTROY(&session->supplements);
1175 while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1178 ast_party_id_free(&session->id);
1179 ao2_cleanup(session->endpoint);
1180 ao2_cleanup(session->aor);
1181 ao2_cleanup(session->contact);
1182 ao2_cleanup(session->req_caps);
1183 ao2_cleanup(session->direct_media_cap);
1186 ast_dsp_free(session->dsp);
1189 if (session->inv_session) {
1190 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
1194 static int add_supplements(struct ast_sip_session *session)
1196 struct ast_sip_session_supplement *iter;
1197 SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1199 AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
1200 struct ast_sip_session_supplement *copy = supplement_dup(iter);
1204 AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
1209 static int add_session_media(void *obj, void *arg, int flags)
1211 struct sdp_handler_list *handler_list = obj;
1212 struct ast_sip_session * session = arg;
1213 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
1214 session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);
1215 if (!session_media) {
1218 session_media->encryption = session->endpoint->media.rtp.encryption;
1219 /* Safe use of strcpy */
1220 strcpy(session_media->stream_type, handler_list->stream_type);
1221 ao2_link(session->media, session_media);
1225 /*! \brief Destructor for SIP channel */
1226 static void sip_channel_destroy(void *obj)
1228 struct ast_sip_channel_pvt *channel = obj;
1230 ao2_cleanup(channel->pvt);
1231 ao2_cleanup(channel->session);
1234 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
1236 struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
1244 ao2_ref(session, +1);
1245 channel->session = session;
1250 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
1251 struct ast_sip_contact *contact, pjsip_inv_session *inv_session)
1253 RAII_VAR(struct ast_sip_session *, session, ao2_alloc(sizeof(*session), session_destructor), ao2_cleanup);
1254 struct ast_sip_session_supplement *iter;
1255 int dsp_features = 0;
1259 AST_LIST_HEAD_INIT(&session->supplements);
1260 session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
1261 if (!session->datastores) {
1265 session->endpoint = ao2_bump(endpoint);
1267 session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);
1268 if (!session->media) {
1271 /* fill session->media with available types */
1272 ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);
1274 session->serializer = ast_sip_create_serializer();
1275 if (!session->serializer) {
1278 ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
1279 ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
1280 pjsip_dlg_inc_session(inv_session->dlg, &session_module);
1281 inv_session->mod_data[session_module.id] = ao2_bump(session);
1282 session->contact = ao2_bump(contact);
1283 session->inv_session = inv_session;
1284 session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1286 if ((endpoint->dtmf == AST_SIP_DTMF_INBAND) || (endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
1287 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
1290 if (endpoint->faxdetect) {
1291 dsp_features |= DSP_FEATURE_FAX_DETECT;
1295 if (!(session->dsp = ast_dsp_new())) {
1296 ao2_ref(session, -1);
1300 ast_dsp_set_features(session->dsp, dsp_features);
1303 if (add_supplements(session)) {
1304 ao2_ref(session, -1);
1307 AST_LIST_TRAVERSE(&session->supplements, iter, next) {
1308 if (iter->session_begin) {
1309 iter->session_begin(session);
1312 session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1313 AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
1314 ast_party_id_init(&session->id);
1315 ao2_ref(session, +1);
1319 /*! \brief struct controlling the suspension of the session's serializer. */
1320 struct ast_sip_session_suspender {
1321 ast_cond_t cond_suspended;
1322 ast_cond_t cond_complete;
1327 static void sip_session_suspender_dtor(void *vdoomed)
1329 struct ast_sip_session_suspender *doomed = vdoomed;
1331 ast_cond_destroy(&doomed->cond_suspended);
1332 ast_cond_destroy(&doomed->cond_complete);
1337 * \brief Block the session serializer thread task.
1339 * \param data Pushed serializer task data for suspension.
1343 static int sip_session_suspend_task(void *data)
1345 struct ast_sip_session_suspender *suspender = data;
1347 ao2_lock(suspender);
1349 /* Signal that the serializer task is now suspended. */
1350 suspender->suspended = 1;
1351 ast_cond_signal(&suspender->cond_suspended);
1353 /* Wait for the the serializer suspension to be completed. */
1354 while (!suspender->complete) {
1355 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
1358 ao2_unlock(suspender);
1359 ao2_ref(suspender, -1);
1364 void ast_sip_session_suspend(struct ast_sip_session *session)
1366 struct ast_sip_session_suspender *suspender;
1369 ast_assert(session->suspended == NULL);
1371 if (ast_taskprocessor_is_task(session->serializer)) {
1372 /* I am the session's serializer thread so I cannot suspend. */
1376 suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
1378 /* We will just have to hope that the system does not deadlock */
1381 ast_cond_init(&suspender->cond_suspended, NULL);
1382 ast_cond_init(&suspender->cond_complete, NULL);
1384 ao2_ref(suspender, +1);
1385 res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
1387 /* We will just have to hope that the system does not deadlock */
1388 ao2_ref(suspender, -2);
1392 session->suspended = suspender;
1394 /* Wait for the serializer to get suspended. */
1395 ao2_lock(suspender);
1396 while (!suspender->suspended) {
1397 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
1399 ao2_unlock(suspender);
1402 void ast_sip_session_unsuspend(struct ast_sip_session *session)
1404 struct ast_sip_session_suspender *suspender = session->suspended;
1410 session->suspended = NULL;
1412 /* Signal that the serializer task suspension is now complete. */
1413 ao2_lock(suspender);
1414 suspender->complete = 1;
1415 ast_cond_signal(&suspender->cond_complete);
1416 ao2_unlock(suspender);
1418 ao2_ref(suspender, -1);
1423 * \brief Handle initial INVITE challenge response message.
1426 * \param rdata PJSIP receive response message data.
1428 * \retval PJ_FALSE Did not handle message.
1429 * \retval PJ_TRUE Handled message.
1431 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
1433 pjsip_transaction *tsx;
1435 pjsip_inv_session *inv;
1436 pjsip_tx_data *tdata;
1437 struct ast_sip_session *session;
1439 if (rdata->msg_info.msg->line.status.code != 401
1440 && rdata->msg_info.msg->line.status.code != 407) {
1441 /* Doesn't pertain to us. Move on */
1445 tsx = pjsip_rdata_get_tsx(rdata);
1446 dlg = pjsip_rdata_get_dlg(rdata);
1451 if (tsx->method.id != PJSIP_INVITE_METHOD) {
1452 /* Not an INVITE that needs authentication */
1456 inv = pjsip_dlg_get_inv_session(dlg);
1457 if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
1459 * We cannot handle reINVITE authentication at this
1460 * time because the reINVITE transaction is still in
1463 ast_debug(1, "A reINVITE is being challenged.\n");
1466 ast_debug(1, "Initial INVITE is being challenged.\n");
1468 session = inv->mod_data[session_module.id];
1470 if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
1471 tsx->last_tx, &tdata)) {
1476 * Restart the outgoing initial INVITE transaction to deal
1477 * with authentication.
1479 pjsip_inv_uac_restart(inv, PJ_FALSE);
1481 ast_sip_session_send_request(session, tdata);
1485 static pjsip_module outbound_invite_auth_module = {
1486 .name = {"Outbound INVITE Auth", 20},
1487 .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
1488 .on_rx_response = outbound_invite_auth,
1493 * \brief Setup outbound initial INVITE authentication.
1496 * \param dlg PJSIP dialog to attach outbound authentication.
1498 * \retval 0 on success.
1499 * \retval -1 on error.
1501 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
1506 status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
1509 return status != PJ_SUCCESS ? -1 : 0;
1512 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
1513 struct ast_sip_contact *contact, const char *location, const char *request_user,
1514 struct ast_format_cap *req_caps)
1516 const char *uri = NULL;
1517 RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
1518 RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
1519 pjsip_timer_setting timer;
1521 struct pjsip_inv_session *inv_session;
1522 RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1524 /* If no location has been provided use the AOR list from the endpoint itself */
1525 if (location || !contact) {
1526 location = S_OR(location, endpoint->aors);
1528 ast_sip_location_retrieve_contact_and_aor_from_list(location, &found_aor, &found_contact);
1529 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
1532 uri = found_contact->uri;
1538 /* If we still have no URI to dial fail to create the session */
1539 if (ast_strlen_zero(uri)) {
1543 if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
1547 if (setup_outbound_invite_auth(dlg)) {
1548 pjsip_dlg_terminate(dlg);
1552 if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
1553 pjsip_dlg_terminate(dlg);
1556 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1557 inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1560 pjsip_timer_setting_default(&timer);
1561 timer.min_se = endpoint->extensions.timer.min_se;
1562 timer.sess_expires = endpoint->extensions.timer.sess_expires;
1563 pjsip_timer_init_session(inv_session, &timer);
1565 if (!(session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact, inv_session))) {
1566 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1569 session->aor = ao2_bump(found_aor);
1570 ast_party_id_copy(&session->id, &endpoint->id.self);
1572 if (ast_format_cap_count(req_caps)) {
1573 /* get joint caps between req_caps and endpoint caps */
1574 struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1575 ast_format_cap_get_compatible(req_caps, session->endpoint->media.codecs, joint_caps);
1578 if (ast_format_cap_count(joint_caps)) {
1579 /* copy endpoint caps into session->req_caps */
1580 ast_format_cap_append_from_cap(session->req_caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
1581 /* replace instances of joint caps equivalents in session->req_caps */
1582 ast_format_cap_replace_from_cap(session->req_caps, joint_caps, AST_MEDIA_TYPE_UNKNOWN);
1584 ao2_cleanup(joint_caps);
1587 if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1588 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1589 /* Since we are not notifying ourselves that the INVITE session is being terminated
1590 * we need to manually drop its reference to session
1592 ao2_ref(session, -1);
1596 ao2_ref(session, +1);
1600 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
1603 pjsip_tx_data *packet = NULL;
1605 if (session->defer_terminate) {
1606 session->terminate_while_deferred = 1;
1614 if ((session->inv_session->state == PJSIP_INV_STATE_CONFIRMED) && session->inv_session->invite_tsx) {
1615 ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
1616 ast_sorcery_object_get_id(session->endpoint));
1617 /* If this is delayed the only thing that will happen is a BYE request so we don't
1618 * actually need to store the response code for when it happens.
1620 delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE);
1621 } else if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
1622 pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
1623 } else if (((status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet)) == PJ_SUCCESS)
1625 struct ast_sip_session_delayed_request *delay;
1627 /* Flush any delayed requests so they cannot overlap this transaction. */
1628 while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1632 if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1633 ast_sip_session_send_response(session, packet);
1635 ast_sip_session_send_request(session, packet);
1640 static int session_termination_task(void *data)
1642 struct ast_sip_session *session = data;
1644 if (session->defer_terminate) {
1645 session->defer_terminate = 0;
1646 if (session->inv_session) {
1647 ast_sip_session_terminate(session, 0);
1651 ao2_ref(session, -1);
1655 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
1657 struct ast_sip_session *session = entry->user_data;
1659 if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
1660 ao2_cleanup(session);
1664 int ast_sip_session_defer_termination(struct ast_sip_session *session)
1666 pj_time_val delay = { .sec = 60, };
1669 /* The session should not have an active deferred termination request. */
1670 ast_assert(!session->defer_terminate);
1672 session->defer_terminate = 1;
1674 session->scheduled_termination.id = 0;
1675 ao2_ref(session, +1);
1676 session->scheduled_termination.user_data = session;
1677 session->scheduled_termination.cb = session_termination_cb;
1679 res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
1680 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
1682 session->defer_terminate = 0;
1683 ao2_ref(session, -1);
1688 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
1690 if (!session->defer_terminate) {
1691 /* Already canceled or timer fired. */
1694 session->defer_terminate = 0;
1696 if (session->terminate_while_deferred) {
1697 /* Complete the termination started by the upper layer. */
1698 ast_sip_session_terminate(session, 0);
1701 /* Stop the termination timer if it is still running. */
1702 if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
1703 &session->scheduled_termination)) {
1704 ao2_ref(session, -1);
1708 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
1710 pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
1711 struct ast_sip_session *session;
1714 !(session = inv_session->mod_data[session_module.id])) {
1718 ao2_ref(session, +1);
1723 enum sip_get_destination_result {
1724 /*! The extension was successfully found */
1725 SIP_GET_DEST_EXTEN_FOUND,
1726 /*! The extension specified in the RURI was not found */
1727 SIP_GET_DEST_EXTEN_NOT_FOUND,
1728 /*! The extension specified in the RURI was a partial match */
1729 SIP_GET_DEST_EXTEN_PARTIAL,
1730 /*! The RURI is of an unsupported scheme */
1731 SIP_GET_DEST_UNSUPPORTED_URI,
1735 * \brief Determine where in the dialplan a call should go
1737 * This uses the username in the request URI to try to match
1738 * an extension in the endpoint's configured context in order
1739 * to route the call.
1741 * \param session The inbound SIP session
1742 * \param rdata The SIP INVITE
1744 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
1746 pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
1747 pjsip_sip_uri *sip_ruri;
1748 struct ast_features_pickup_config *pickup_cfg;
1749 const char *pickupexten;
1751 if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
1752 return SIP_GET_DEST_UNSUPPORTED_URI;
1755 sip_ruri = pjsip_uri_get_uri(ruri);
1756 ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
1758 pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
1760 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
1763 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
1764 ao2_ref(pickup_cfg, -1);
1767 if (!strcmp(session->exten, pickupexten) ||
1768 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
1769 return SIP_GET_DEST_EXTEN_FOUND;
1771 /* XXX In reality, we'll likely have further options so that partial matches
1772 * can be indicated here, but for getting something up and running, we're going
1773 * to return a "not exists" error here.
1775 return SIP_GET_DEST_EXTEN_NOT_FOUND;
1778 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
1780 pjsip_tx_data *tdata;
1782 pjsip_inv_session *inv_session;
1783 unsigned int options = endpoint->extensions.flags;
1784 pj_status_t dlg_status;
1786 if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
1788 pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1790 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1794 dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
1796 if (dlg_status != PJ_EEXISTS) {
1797 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1801 if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
1802 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1803 pjsip_dlg_terminate(dlg);
1807 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1808 inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1810 if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1811 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
1812 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1814 pjsip_inv_send_msg(inv_session, tdata);
1821 /*! \brief Session created for the new INVITE */
1822 struct ast_sip_session *session;
1824 /*! \brief INVITE request itself */
1825 pjsip_rx_data *rdata;
1828 static void new_invite_destroy(void *obj)
1830 struct new_invite *invite = obj;
1832 ao2_cleanup(invite->session);
1834 if (invite->rdata) {
1835 pjsip_rx_data_free_cloned(invite->rdata);
1839 static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
1841 struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
1847 ao2_ref(session, +1);
1848 invite->session = session;
1850 if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
1851 ao2_ref(invite, -1);
1858 static int new_invite(void *data)
1860 RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
1861 pjsip_tx_data *tdata = NULL;
1862 pjsip_timer_setting timer;
1863 pjsip_rdata_sdp_info *sdp_info;
1864 pjmedia_sdp_session *local = NULL;
1866 /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
1867 * so that we will be notified so we can destroy the session properly
1870 switch (get_destination(invite->session, invite->rdata)) {
1871 case SIP_GET_DEST_EXTEN_FOUND:
1872 /* Things worked. Keep going */
1874 case SIP_GET_DEST_UNSUPPORTED_URI:
1875 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
1876 ast_sip_session_send_response(invite->session, tdata);
1878 pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
1881 case SIP_GET_DEST_EXTEN_NOT_FOUND:
1882 case SIP_GET_DEST_EXTEN_PARTIAL:
1884 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
1885 ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
1886 invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
1888 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
1889 ast_sip_session_send_response(invite->session, tdata);
1891 pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
1896 if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
1897 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
1898 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
1899 ast_sip_session_send_response(invite->session, tdata);
1901 pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
1905 /* We are creating a local SDP which is an answer to their offer */
1906 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
1908 /* We are creating a local SDP which is an offer */
1909 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
1912 /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
1914 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1915 ast_sip_session_send_response(invite->session, tdata);
1917 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1921 pjsip_inv_set_local_sdp(invite->session->inv_session, local);
1922 pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
1923 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1924 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
1928 pjsip_timer_setting_default(&timer);
1929 timer.min_se = invite->session->endpoint->extensions.timer.min_se;
1930 timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
1931 pjsip_timer_init_session(invite->session->inv_session, &timer);
1933 /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
1934 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
1935 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1938 ast_sip_session_send_response(invite->session, tdata);
1940 handle_incoming_request(invite->session, invite->rdata, PJSIP_EVENT_RX_MSG);
1945 static void handle_new_invite_request(pjsip_rx_data *rdata)
1947 RAII_VAR(struct ast_sip_endpoint *, endpoint,
1948 ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
1949 pjsip_tx_data *tdata = NULL;
1950 pjsip_inv_session *inv_session = NULL;
1951 struct ast_sip_session *session;
1952 struct new_invite *invite;
1954 ast_assert(endpoint != NULL);
1956 inv_session = pre_session_setup(rdata, endpoint);
1958 /* pre_session_setup() returns a response on failure */
1962 session = ast_sip_session_alloc(endpoint, NULL, inv_session);
1964 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1965 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1967 pjsip_inv_send_msg(inv_session, tdata);
1972 invite = new_invite_alloc(session, rdata);
1973 if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
1974 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1975 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1977 pjsip_inv_send_msg(inv_session, tdata);
1979 ao2_cleanup(invite);
1981 ao2_ref(session, -1);
1984 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
1988 if (ast_strlen_zero(supplement_method)) {
1992 pj_cstr(&method, supplement_method);
1994 return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
1997 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
1999 struct ast_sip_session_supplement *supplement;
2000 struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
2006 AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2007 if (does_method_match(&method->name, supplement->method)) {
2014 * \brief Called when a new SIP request comes into PJSIP
2016 * This function is called under two circumstances
2017 * 1) An out-of-dialog request is received by PJSIP
2018 * 2) An in-dialog request that the inv_session layer does not
2019 * handle is received (such as an in-dialog INFO)
2021 * In all cases, there is very little we actually do in this function
2022 * 1) For requests we don't handle, we return PJ_FALSE
2023 * 2) For new INVITEs, throw the work into the SIP threadpool to be done
2024 * there to free up the thread(s) handling incoming requests
2025 * 3) For in-dialog requests we handle, we defer handling them until the
2026 * on_inv_state_change() callback instead (where we will end up putting
2027 * them into the threadpool).
2029 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
2031 pj_status_t handled = PJ_FALSE;
2032 pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
2033 pjsip_inv_session *inv_session;
2035 switch (rdata->msg_info.msg->line.req.method.id) {
2036 case PJSIP_INVITE_METHOD:
2038 ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
2042 handle_new_invite_request(rdata);
2045 /* Handle other in-dialog methods if their supplements have been registered */
2046 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
2047 has_supplement(inv_session->mod_data[session_module.id], rdata);
2054 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
2056 struct ast_sip_session *session = entry->user_data;
2058 ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",
2059 ast_sorcery_object_get_id(session->endpoint),
2060 session->channel ? ast_channel_name(session->channel) : "");
2062 if (AST_LIST_EMPTY(&session->delayed_requests)) {
2063 /* No delayed request pending, so just return */
2064 ao2_ref(session, -1);
2067 if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {
2069 * Uh oh. We now have nothing in the foreseeable future
2070 * to trigger sending the delayed requests.
2072 ao2_ref(session, -1);
2076 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)
2078 pjsip_inv_session *inv = session->inv_session;
2081 ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",
2082 ast_sorcery_object_get_id(session->endpoint),
2083 session->channel ? ast_channel_name(session->channel) : "");
2084 if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE)) {
2087 if (pj_timer_entry_running(&session->rescheduled_reinvite)) {
2088 /* Timer already running. Something weird is going on. */
2089 ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",
2090 ast_sorcery_object_get_id(session->endpoint),
2091 session->channel ? ast_channel_name(session->channel) : "");
2096 if (inv->role == PJSIP_ROLE_UAC) {
2097 tv.msec = 2100 + ast_random() % 2000;
2099 tv.msec = ast_random() % 2000;
2101 pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);
2103 ao2_ref(session, +1);
2104 if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2105 &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {
2106 ao2_ref(session, -1);
2110 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2112 struct ast_sip_session *session;
2114 if (!DEBUG_ATLEAST(5)) {
2115 /* Debug not spamy enough */
2119 ast_log(LOG_DEBUG, "Function %s called on event %s\n",
2120 function, pjsip_event_str(e->type));
2122 ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);
2123 ast_log(LOG_DEBUG, "The transaction state is %s\n",
2124 pjsip_tsx_state_str(tsx->state));
2127 session = inv->mod_data[session_module.id];
2129 ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);
2131 ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",
2132 ast_sorcery_object_get_id(session->endpoint),
2133 session->channel ? ast_channel_name(session->channel) : "");
2135 if (inv->invite_tsx) {
2136 ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",
2139 ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");
2142 ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",
2143 pjsip_role_name(tsx->role),
2144 (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2146 ast_log(LOG_DEBUG, "The current transaction state is %s\n",
2147 pjsip_tsx_state_str(tsx->state));
2148 ast_log(LOG_DEBUG, "The transaction state change event is %s\n",
2149 pjsip_event_str(e->body.tsx_state.type));
2151 ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");
2153 ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
2156 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
2158 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type)
2160 struct ast_sip_session_supplement *supplement;
2161 struct pjsip_request_line req = rdata->msg_info.msg->line.req;
2163 ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2164 AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2165 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
2166 if (supplement->incoming_request(session, rdata)) {
2173 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
2174 enum ast_sip_session_response_priority response_priority)
2176 struct ast_sip_session_supplement *supplement;
2177 struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2179 ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
2180 pj_strbuf(&status.reason));
2182 AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2183 if (!(supplement->response_priority & response_priority)) {
2186 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
2187 supplement->incoming_response(session, rdata);
2192 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
2193 enum ast_sip_session_response_priority response_priority)
2195 ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
2196 "request" : "response");
2198 if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
2199 handle_incoming_request(session, rdata, type);
2201 handle_incoming_response(session, rdata, type, response_priority);
2207 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
2209 struct ast_sip_session_supplement *supplement;
2210 struct pjsip_request_line req = tdata->msg->line.req;
2212 ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2213 AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2214 if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
2215 supplement->outgoing_request(session, tdata);
2220 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
2222 struct ast_sip_session_supplement *supplement;
2223 struct pjsip_status_line status = tdata->msg->line.status;
2224 pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
2225 ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
2226 pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
2227 pj_strbuf(&status.reason));
2229 AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2230 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
2231 supplement->outgoing_response(session, tdata);
2236 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
2238 ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
2239 "request" : "response");
2240 if (tdata->msg->type == PJSIP_REQUEST_MSG) {
2241 handle_outgoing_request(session, tdata);
2243 handle_outgoing_response(session, tdata);
2247 static int session_end(struct ast_sip_session *session)
2249 struct ast_sip_session_supplement *iter;
2251 /* Stop the scheduled termination */
2252 if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &session->scheduled_termination)) {
2253 ao2_ref(session, -1);
2256 /* Session is dead. Let's get rid of the reference to the session */
2257 AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2258 if (iter->session_end) {
2259 iter->session_end(session);
2263 session->inv_session->mod_data[session_module.id] = NULL;
2264 ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
2265 ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
2266 ao2_cleanup(session);
2270 static int check_request_status(pjsip_inv_session *inv, pjsip_event *e)
2272 struct ast_sip_session *session = inv->mod_data[session_module.id];
2273 pjsip_transaction *tsx = e->body.tsx_state.tsx;
2275 if (tsx->status_code != 503 && tsx->status_code != 408) {
2279 if (!ast_sip_failover_request(tsx->last_tx)) {
2283 pjsip_inv_uac_restart(inv, PJ_FALSE);
2285 * Bump the ref since it will be on a new transaction and
2286 * we don't want it to go away along with the old transaction.
2288 pjsip_tx_data_add_ref(tsx->last_tx);
2289 ast_sip_session_send_request(session, tsx->last_tx);
2293 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
2295 struct ast_sip_session *session = inv->mod_data[session_module.id];
2296 pjsip_event_id_e type;
2299 print_debug_details(inv, NULL, e);
2302 type = PJSIP_EVENT_UNKNOWN;
2310 case PJSIP_EVENT_TX_MSG:
2311 handle_outgoing(session, e->body.tx_msg.tdata);
2313 case PJSIP_EVENT_RX_MSG:
2314 handle_incoming(session, e->body.rx_msg.rdata, type,
2315 AST_SIP_SESSION_BEFORE_MEDIA);
2317 case PJSIP_EVENT_TSX_STATE:
2318 ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
2319 /* Transaction state changes are prompted by some other underlying event. */
2320 switch(e->body.tsx_state.type) {
2321 case PJSIP_EVENT_TX_MSG:
2322 handle_outgoing(session, e->body.tsx_state.src.tdata);
2324 case PJSIP_EVENT_RX_MSG:
2325 if (!check_request_status(inv, e)) {
2326 handle_incoming(session, e->body.tsx_state.src.rdata, type,
2327 AST_SIP_SESSION_BEFORE_MEDIA);
2330 case PJSIP_EVENT_TRANSPORT_ERROR:
2331 case PJSIP_EVENT_TIMER:
2333 * Check the request status on transport error or timeout. A transport
2334 * error can occur when a TCP socket closes and that can be the result
2335 * of a 503. Also we may need to failover on a timeout (408).
2337 check_request_status(inv, e);
2339 case PJSIP_EVENT_USER:
2340 case PJSIP_EVENT_UNKNOWN:
2341 case PJSIP_EVENT_TSX_STATE:
2346 case PJSIP_EVENT_TRANSPORT_ERROR:
2347 case PJSIP_EVENT_TIMER:
2348 case PJSIP_EVENT_UNKNOWN:
2349 case PJSIP_EVENT_USER:
2354 if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
2355 session_end(session);
2359 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
2364 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2366 ast_sip_session_response_cb cb;
2367 struct ast_sip_session *session = inv->mod_data[session_module.id];
2368 pjsip_tx_data *tdata;
2370 print_debug_details(inv, tsx, e);
2372 /* Transaction likely timed out after the call was hung up. Just
2373 * ignore such transaction changes
2377 switch (e->body.tsx_state.type) {
2378 case PJSIP_EVENT_TX_MSG:
2379 handle_outgoing(session, e->body.tsx_state.src.tdata);
2380 /* When we create an outgoing request, we do not have access to the transaction that
2381 * is created. Instead, We have to place transaction-specific data in the tdata. Here,
2382 * we transfer the data into the transaction. This way, when we receive a response, we
2383 * can dig this data out again
2385 tsx->mod_data[session_module.id] = e->body.tsx_state.src.tdata->mod_data[session_module.id];
2387 case PJSIP_EVENT_RX_MSG:
2388 cb = ast_sip_mod_data_get(tsx->mod_data, session_module.id, MOD_DATA_ON_RESPONSE);
2389 handle_incoming(session, e->body.tsx_state.src.rdata, e->type,
2390 AST_SIP_SESSION_AFTER_MEDIA);
2391 if (tsx->method.id == PJSIP_INVITE_METHOD) {
2392 if (tsx->role == PJSIP_ROLE_UAC) {
2393 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2394 /* This means we got a non 2XX final response to our outgoing INVITE */
2395 if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
2396 reschedule_reinvite(session, cb);
2399 if (inv->state == PJSIP_INV_STATE_CONFIRMED) {
2400 ast_debug(1, "reINVITE received final response code %d\n",
2402 if ((tsx->status_code == 401 || tsx->status_code == 407)
2403 && !ast_sip_create_request_with_auth(
2404 &session->endpoint->outbound_auths,
2405 e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2406 /* Send authed reINVITE */
2407 ast_sip_session_send_request_with_cb(session, tdata, cb);
2410 if (tsx->status_code != 488) {
2411 /* Other reinvite failures (except 488) result in destroying the session. */
2412 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
2413 ast_sip_session_send_request(session, tdata);
2417 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2418 if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {
2419 /* This is a race condition detailed in RFC 5407 section 3.1.2.
2420 * We sent a CANCEL at the same time that the UAS sent us a 200 OK for
2421 * the original INVITE. As a result, we have now received a 200 OK for
2422 * a cancelled call. Our role is to immediately send a BYE to end the
2425 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
2426 ast_sip_session_send_request(session, tdata);
2432 /* All other methods */
2433 if (tsx->role == PJSIP_ROLE_UAC) {
2434 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2435 /* This means we got a final response to our outgoing method */
2436 ast_debug(1, "%.*s received final response code %d\n",
2437 (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2439 if ((tsx->status_code == 401 || tsx->status_code == 407)
2440 && !ast_sip_create_request_with_auth(
2441 &session->endpoint->outbound_auths,
2442 e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2443 /* Send authed version of the method */
2444 ast_sip_session_send_request_with_cb(session, tdata, cb);
2451 cb(session, e->body.tsx_state.src.rdata);
2454 case PJSIP_EVENT_TRANSPORT_ERROR:
2455 case PJSIP_EVENT_TIMER:
2456 case PJSIP_EVENT_USER:
2457 case PJSIP_EVENT_UNKNOWN:
2458 case PJSIP_EVENT_TSX_STATE:
2463 if (AST_LIST_EMPTY(&session->delayed_requests)) {
2464 /* No delayed request pending, so just return */
2468 if (tsx->method.id == PJSIP_INVITE_METHOD) {
2469 if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {
2470 ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2471 ast_sorcery_object_get_id(session->endpoint),
2472 session->channel ? ast_channel_name(session->channel) : "",
2473 pjsip_tsx_state_str(tsx->state));
2474 check_delayed_requests(session, invite_proceeding);
2475 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2477 * Terminated INVITE transactions always should result in
2478 * queuing delayed requests, no matter what event caused
2479 * the transaction to terminate.
2481 ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2482 ast_sorcery_object_get_id(session->endpoint),
2483 session->channel ? ast_channel_name(session->channel) : "",
2484 pjsip_tsx_state_str(tsx->state));
2485 check_delayed_requests(session, invite_terminated);
2487 } else if (tsx->role == PJSIP_ROLE_UAC
2488 && tsx->state == PJSIP_TSX_STATE_COMPLETED
2489 && !pj_strcmp2(&tsx->method.name, "UPDATE")) {
2490 ast_debug(3, "Endpoint '%s(%s)' UPDATE delay check. tsx-state:%s\n",
2491 ast_sorcery_object_get_id(session->endpoint),
2492 session->channel ? ast_channel_name(session->channel) : "",
2493 pjsip_tsx_state_str(tsx->state));
2494 check_delayed_requests(session, update_completed);
2498 static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
2500 struct ast_sip_session_media *session_media = obj;
2501 pjmedia_sdp_session *answer = arg;
2502 struct ast_sip_session *session = data;
2503 struct ast_sip_session_sdp_handler *handler = session_media->handler;
2504 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2508 /* if an already assigned handler reports a catastrophic error, fail */
2509 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2516 handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
2517 if (!handler_list) {
2521 /* no handler for this stream type and we have a list to search */
2522 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2523 if (handler == session_media->handler) {
2526 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2528 /* catastrophic error */
2532 /* Handled by this handler. Move to the next stream */
2533 session_media_set_handler(session_media, handler);
2538 /* streams that weren't handled won't be included in generated outbound SDP */
2542 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
2544 RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
2545 static const pj_str_t STR_IN = { "IN", 2 };
2546 static const pj_str_t STR_IP4 = { "IP4", 3 };
2547 static const pj_str_t STR_IP6 = { "IP6", 3 };
2548 pjmedia_sdp_session *local;
2550 if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
2555 local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
2557 local->origin.version = offer->origin.version + 1;
2558 local->origin.id = offer->origin.id;
2561 pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);
2562 pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);
2564 /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
2565 successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
2566 if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {
2567 /* Something experienced a catastrophic failure */
2571 /* Use the connection details of the first media stream if possible for SDP level */
2572 if (local->media_count) {
2575 /* Since we are using the first media stream as the SDP level we can get rid of it
2576 * from the stream itself
2578 local->conn = local->media[0]->conn;
2579 local->media[0]->conn = NULL;
2580 pj_strassign(&local->origin.net_type, &local->conn->net_type);
2581 pj_strassign(&local->origin.addr_type, &local->conn->addr_type);
2582 pj_strassign(&local->origin.addr, &local->conn->addr);
2584 /* Go through each media stream seeing if the connection details actually differ,
2585 * if not just use SDP level and reduce the SDP size
2587 for (stream = 1; stream < local->media_count; stream++) {
2588 if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&
2589 !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&
2590 !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {
2591 local->media[stream]->conn = NULL;
2595 local->origin.net_type = STR_IN;
2596 local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
2598 if (!ast_strlen_zero(session->endpoint->media.address)) {
2599 pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);
2601 pj_sockaddr localaddr;
2602 char our_ip[PJ_INET6_ADDRSTRLEN];
2604 pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr);
2605 pj_sockaddr_print(&localaddr, our_ip, sizeof(our_ip), 0);
2606 pj_strdup2(inv->pool_prov, &local->origin.addr, our_ip);
2613 static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
2615 struct ast_sip_session *session = inv->mod_data[session_module.id];
2616 pjmedia_sdp_session *answer;
2618 if (handle_incoming_sdp(session, offer)) {
2622 if ((answer = create_local_sdp(inv, session, offer))) {
2623 pjsip_inv_set_sdp_answer(inv, answer);
2628 static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
2634 static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
2636 struct ast_sip_session *session = inv->mod_data[session_module.id];
2637 const pjmedia_sdp_session *local, *remote;
2639 if (!session->channel) {
2640 /* If we don't have a channel. We really don't care about media updates.
2646 if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
2647 (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
2648 ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
2649 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2650 ast_queue_hangup(session->channel);
2654 handle_negotiated_sdp(session, local, remote);
2657 static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
2659 struct ast_sip_session *session = inv->mod_data[session_module.id];
2660 const pjsip_sip_uri *uri;
2662 if (!session->channel) {
2663 return PJSIP_REDIRECT_STOP;
2666 if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {
2667 return PJSIP_REDIRECT_ACCEPT;
2670 if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {
2671 return PJSIP_REDIRECT_STOP;
2674 handle_incoming(session, e->body.rx_msg.rdata, PJSIP_EVENT_RX_MSG,
2675 AST_SIP_SESSION_BEFORE_REDIRECTING);
2677 uri = pjsip_uri_get_uri(target);
2679 if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {
2680 char exten[AST_MAX_EXTENSION];
2682 ast_copy_pj_str(exten, &uri->user, sizeof(exten));
2683 ast_channel_call_forward_set(session->channel, exten);
2684 } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {
2685 char target_uri[PJSIP_MAX_URL_SIZE];
2686 /* PJSIP/ + endpoint length + / + max URL size */
2687 char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];
2689 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));
2690 sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);
2691 ast_channel_call_forward_set(session->channel, forward);
2694 return PJSIP_REDIRECT_STOP;
2697 static pjsip_inv_callback inv_callback = {
2698 .on_state_changed = session_inv_on_state_changed,
2699 .on_new_session = session_inv_on_new_session,
2700 .on_tsx_state_changed = session_inv_on_tsx_state_changed,
2701 .on_rx_offer = session_inv_on_rx_offer,
2702 .on_media_update = session_inv_on_media_update,
2703 .on_redirected = session_inv_on_redirected,
2706 /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
2707 static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
2709 struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(
2710 tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);
2711 struct pjmedia_sdp_session *sdp;
2714 /* SDP produced by us directly will never be multipart */
2715 if (hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
2716 pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
2720 sdp = tdata->msg->body->data;
2723 char host[NI_MAXHOST];
2724 struct ast_sockaddr addr = { { 0, } };
2726 ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));
2727 ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
2729 if (ast_apply_ha(transport->localnet, &addr) != AST_SENSE_ALLOW) {
2730 pj_strdup2(tdata->pool, &sdp->conn->addr, transport->external_media_address);
2734 for (stream = 0; stream < sdp->media_count; ++stream) {
2735 /* See if there are registered handlers for this media stream type */
2737 struct ast_sip_session_sdp_handler *handler;
2738 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2740 /* We need a null-terminated version of the media string */
2741 ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
2743 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
2744 if (!handler_list) {
2745 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
2748 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2749 if (handler->change_outgoing_sdp_stream_media_address) {
2750 handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
2755 /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
2756 ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);
2759 static int load_module(void)
2761 pjsip_endpoint *endpt;
2763 CHECK_PJSIP_MODULE_LOADED();
2765 if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
2766 return AST_MODULE_LOAD_DECLINE;
2768 if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
2769 return AST_MODULE_LOAD_DECLINE;
2771 nat_hook->outgoing_external_message = session_outgoing_nat_hook;
2772 ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
2773 sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
2774 sdp_handler_list_hash, sdp_handler_list_cmp);
2775 if (!sdp_handlers) {
2776 return AST_MODULE_LOAD_DECLINE;
2778 endpt = ast_sip_get_pjsip_endpoint();
2779 pjsip_inv_usage_init(endpt, &inv_callback);
2780 pjsip_100rel_init_module(endpt);
2781 pjsip_timer_init_module(endpt);
2782 if (ast_sip_register_service(&session_module)) {
2783 return AST_MODULE_LOAD_DECLINE;
2785 ast_sip_register_service(&session_reinvite_module);
2786 ast_sip_register_service(&outbound_invite_auth_module);
2788 ast_module_shutdown_ref(ast_module_info->self);
2790 return AST_MODULE_LOAD_SUCCESS;
2793 static int unload_module(void)
2795 ast_sip_unregister_service(&outbound_invite_auth_module);
2796 ast_sip_unregister_service(&session_reinvite_module);
2797 ast_sip_unregister_service(&session_module);
2798 ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);
2799 ao2_cleanup(nat_hook);
2800 ao2_cleanup(sdp_handlers);
2804 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
2805 .support_level = AST_MODULE_SUPPORT_CORE,
2806 .load = load_module,
2807 .unload = unload_module,
2808 .load_pri = AST_MODPRI_APP_DEPEND,