2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2013, Digium, Inc.
6 * Kevin Harwell <kharwell@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 <depend>res_pjsip_session</depend>
23 <support_level>core</support_level>
27 <info name="PJSIPMessageFromInfo" language="en_US" tech="PJSIP">
28 <para>The <literal>from</literal> parameter can be a configured endpoint
29 or in the form of "display-name" <URI>.</para>
31 <info name="PJSIPMessageToInfo" language="en_US" tech="PJSIP">
32 <para>Specifying a prefix of <literal>pjsip:</literal> will send the
33 message as a SIP MESSAGE request.</para>
38 #include "pjsua-lib/pjsua.h"
40 #include "asterisk/message.h"
41 #include "asterisk/module.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/res_pjsip.h"
44 #include "asterisk/res_pjsip_session.h"
46 const pjsip_method pjsip_message_method = {PJSIP_OTHER_METHOD, {"MESSAGE", 7} };
48 #define MAX_HDR_SIZE 512
49 #define MAX_BODY_SIZE 1024
50 #define MAX_EXTEN_SIZE 256
51 #define MAX_USER_SIZE 128
55 * \brief Determine where in the dialplan a call should go
57 * \details This uses the username in the request URI to try to match
58 * an extension in an endpoint's context in order to route the call.
60 * \param rdata The SIP request
61 * \param context The context to use
62 * \param exten The extension to use
64 static enum pjsip_status_code get_destination(const pjsip_rx_data *rdata, const char *context, char *exten)
66 pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
67 pjsip_sip_uri *sip_ruri;
69 if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
70 return PJSIP_SC_UNSUPPORTED_URI_SCHEME;
73 sip_ruri = pjsip_uri_get_uri(ruri);
74 ast_copy_pj_str(exten, &sip_ruri->user, MAX_EXTEN_SIZE);
76 if (ast_exists_extension(NULL, context, exten, 1, NULL)) {
79 return PJSIP_SC_NOT_FOUND;
84 * \brief Checks to make sure the request has the correct content type.
86 * \details This module supports the following media types: "text/plain".
87 * Return unsupported otherwise.
89 * \param rdata The SIP request
91 static enum pjsip_status_code check_content_type(const pjsip_rx_data *rdata)
94 if (rdata->msg_info.msg->body && rdata->msg_info.msg->body->len) {
95 res = ast_sip_is_content_type(
96 &rdata->msg_info.msg->body->content_type, "text", "plain");
98 res = rdata->msg_info.ctype &&
99 !pj_strcmp2(&rdata->msg_info.ctype->media.type, "text") &&
100 !pj_strcmp2(&rdata->msg_info.ctype->media.subtype, "plain");
103 return res ? PJSIP_SC_OK : PJSIP_SC_UNSUPPORTED_MEDIA_TYPE;
108 * \brief Puts pointer past 'sip[s]:' string that should be at the
109 * front of the given 'fromto' parameter
111 * \param fromto 'From' or 'To' field containing 'sip:'
113 static char* skip_sip(char *fromto)
117 /* need to be one past 'sip:' or 'sips:' */
118 if (!(p = strstr(fromto, "sip"))) {
131 * \brief Retrieves an endpoint if specified in the given 'fromto'
133 * Expects the given 'fromto' to be in one of the following formats:
134 * sip[s]:endpoint[/aor]
135 * sip[s]:endpoint[/uri]
136 * sip[s]:uri <-- will use default outbound endpoint
138 * If an optional aor is given it will try to find an associated uri
139 * to return. If an optional uri is given then that will be returned,
140 * otherwise uri will be NULL.
142 * \param fromto 'From' or 'To' field with possible endpoint
143 * \param uri Optional uri to return
145 static struct ast_sip_endpoint* get_endpoint(char *fromto, char **uri)
147 char *name, *aor_uri;
148 struct ast_sip_endpoint* endpoint;
149 RAII_VAR(struct ast_sip_aor *, aor, NULL, ao2_cleanup);
150 RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
152 name = skip_sip(fromto);
153 if ((aor_uri = strchr(name, '/'))) {
155 } else if ((aor_uri = strchr(name, '@'))) {
156 /* format was endpoint@ */
160 if (ast_strlen_zero(name) || !(endpoint = ast_sorcery_retrieve_by_id(
161 ast_sip_get_sorcery(), "endpoint", name))) {
162 /* assume sending to direct uri -
163 use default outbound endpoint */
164 *uri = ast_strdup(fromto);
165 return ast_sip_default_outbound_endpoint();
170 if ((aor = ast_sip_location_retrieve_aor(*uri)) &&
171 (contact = ast_sip_location_retrieve_first_aor_contact(aor))) {
172 *uri = (char*)contact->uri;
174 /* need to copy because contact-uri might go away*/
175 *uri = ast_strdup(*uri);
183 * \brief Updates fields in an outgoing 'From' header.
185 * \param tdata The outgoing message data structure
186 * \param from Info to potentially copy into the 'From' header
188 static void update_from(pjsip_tx_data *tdata, char *from)
190 pjsip_name_addr *from_name_addr;
191 pjsip_sip_uri *from_uri;
193 RAII_VAR(char *, uri, NULL, ast_free);
194 RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
196 if (ast_strlen_zero(from)) {
200 if (!(endpoint = get_endpoint(from, &uri))) {
204 if (ast_strlen_zero(uri)) {
205 /* if no aor/uri was specified get one from the endpoint */
206 RAII_VAR(struct ast_sip_contact *, contact,
207 ast_sip_location_retrieve_contact_from_aor_list(
208 endpoint->aors), ao2_cleanup);
210 if (!contact || ast_strlen_zero(contact->uri)) {
211 ast_log(LOG_WARNING, "No contact found for endpoint %s\n",
212 ast_sorcery_object_get_id(endpoint));
219 uri = ast_strdup(contact->uri);
222 /* get current 'from' hdr & uri - going to overwrite some fields */
223 from_name_addr = (pjsip_name_addr *)PJSIP_MSG_FROM_HDR(tdata->msg)->uri;
224 from_uri = pjsip_uri_get_uri(from_name_addr);
226 /* check to see if uri is in 'name <sip:user@domain>' format */
227 if ((parsed = pjsip_parse_uri(tdata->pool, uri, strlen(uri), PJSIP_PARSE_URI_AS_NAMEADDR))) {
228 pjsip_name_addr *name_addr = (pjsip_name_addr *)parsed;
229 pjsip_sip_uri *sip_uri = pjsip_uri_get_uri(name_addr->uri);
231 pj_strdup(tdata->pool, &from_name_addr->display, &name_addr->display);
232 pj_strdup(tdata->pool, &from_uri->user, &sip_uri->user);
233 pj_strdup(tdata->pool, &from_uri->host, &sip_uri->host);
234 from_uri->port = sip_uri->port;
236 /* assume it is 'user[@domain]' format */
237 char *domain = strchr(uri, '@');
240 pj_strdup2(tdata->pool, &from_uri->host, domain);
242 pj_strdup2(tdata->pool, &from_uri->user, uri);
246 static char *scheme_sip_to_pjsip(pjsip_rx_data *rdata, char *buf, unsigned int size)
249 pjsip_name_addr *name_addr = (pjsip_name_addr *)rdata->msg_info.to->uri;
250 pjsip_sip_uri *sip_uri = pjsip_uri_get_uri(name_addr->uri);
252 const pj_str_t *scheme = pjsip_uri_get_scheme(rdata->msg_info.to->uri);
253 size_t size_scheme = pj_strlen(scheme);
254 size_t size_user = pj_strlen(&sip_uri->user);
255 size_t size_host = pj_strlen(&sip_uri->host);
257 /* 5 = count of 'p' 'j' ':' '@' '\0' */
258 if (size < size_scheme + size_user + size_host + 5) {
260 ast_log(LOG_WARNING, "Unable to handle MESSAGE- incoming uri "
261 "too large for given buffer\n");
268 memcpy(buf, pj_strbuf(scheme), size_scheme);
272 memcpy(buf, pj_strbuf(&sip_uri->user), size_user);
276 memcpy(buf, pj_strbuf(&sip_uri->host), size_host);
283 static char *scheme_pjsip_to_sip(const char *uri)
285 ast_assert(!strncmp(uri, "pjsip", 5));
286 return ast_strdup(uri + 2);
291 * \brief Checks if the given msg var name should be blocked.
293 * \details Some headers are not allowed to be overriden by the user.
294 * Determine if the given var header name from the user is blocked for
295 * an outgoing MESSAGE.
297 * \param name name of header to see if it is blocked.
299 * \retval TRUE if the given header is blocked.
301 static int is_msg_var_blocked(const char *name)
306 * Don't block Content-Type or Max-Forwards headers because the
307 * user can override them.
309 static const char *hdr[] = {
322 for (i = 0; i < ARRAY_LEN(hdr); ++i) {
323 if (!strcasecmp(name, hdr[i])) {
324 /* Block addition of this header. */
333 * \brief Copies any other msg vars over to the request headers.
335 * \param msg The msg structure to copy headers from
336 * \param tdata The SIP transmission data
338 static enum pjsip_status_code vars_to_headers(const struct ast_msg *msg, pjsip_tx_data *tdata)
344 RAII_VAR(struct ast_msg_var_iterator *, i, ast_msg_var_iterator_init(msg), ast_msg_var_iterator_destroy);
345 while (ast_msg_var_iterator_next(msg, i, &name, &value)) {
346 if (!strcasecmp(name, "Max-Forwards")) {
347 /* Decrement Max-Forwards for SIP loop prevention. */
348 if (sscanf(value, "%30d", &max_forwards) != 1 || --max_forwards == 0) {
349 ast_log(LOG_NOTICE, "MESSAGE(Max-Forwards) reached zero. MESSAGE not sent.\n");
352 sprintf((char*)value, "%d", max_forwards);
353 ast_sip_add_header(tdata, name, value);
354 } else if (!strcasecmp(name, "To")) {
355 char *to = scheme_pjsip_to_sip(value);
357 ast_sip_add_header(tdata, name, to);
360 } else if (!is_msg_var_blocked(name)) {
361 ast_sip_add_header(tdata, name, value);
363 ast_msg_var_unref_current(i);
370 * \brief Copies any other request header data over to ast_msg structure.
372 * \param rdata The SIP request
373 * \param msg The msg structure to copy headers into
375 static int headers_to_vars(const pjsip_rx_data *rdata, struct ast_msg *msg)
378 char name[MAX_HDR_SIZE];
379 char buf[MAX_HDR_SIZE];
381 pjsip_hdr *h = rdata->msg_info.msg->hdr.next;
382 pjsip_hdr *end= &rdata->msg_info.msg->hdr;
385 if ((res = pjsip_hdr_print_on(h, buf, sizeof(buf)-1)) > 0) {
387 if ((c = strchr(buf, ':'))) {
388 ast_copy_string(buf, ast_skip_blanks(c + 1), sizeof(buf));
391 ast_copy_pj_str(name, &h->name, sizeof(name));
392 if ((res = ast_msg_set_var(msg, name, buf)) != 0) {
403 * \brief Prints the message body into the given char buffer.
405 * \details Copies body content from the received data into the given
406 * character buffer removing any extra carriage return/line feeds.
408 * \param rdata The SIP request
409 * \param buf Buffer to fill
410 * \param len The length of the buffer
412 static int print_body(pjsip_rx_data *rdata, char *buf, int len)
416 if (!rdata->msg_info.msg->body || !rdata->msg_info.msg->body->len) {
420 if ((res = rdata->msg_info.msg->body->print_body(
421 rdata->msg_info.msg->body, buf, len)) < 0) {
425 /* remove any trailing carriage return/line feeds */
426 while (res > 0 && ((buf[--res] == '\r') || (buf[res] == '\n')));
435 * \brief Converts a pjsip_rx_data structure to an ast_msg structure.
437 * \details Attempts to fill in as much information as possible into the given
438 * msg structure copied from the given request data.
440 * \param rdata The SIP request
441 * \param msg The asterisk message structure to fill in.
443 static enum pjsip_status_code rx_data_to_ast_msg(pjsip_rx_data *rdata, struct ast_msg *msg)
446 #define CHECK_RES(z_) do { if (z_) { ast_msg_destroy(msg); \
447 return PJSIP_SC_INTERNAL_SERVER_ERROR; } } while (0)
450 char buf[MAX_BODY_SIZE];
451 pjsip_name_addr *name_addr;
453 pjsip_status_code code;
454 struct ast_sip_endpoint *endpt = ast_pjsip_rdata_get_endpoint(rdata);
456 /* make sure there is an appropriate context and extension*/
457 if ((code = get_destination(rdata, endpt->context, buf)) != PJSIP_SC_OK) {
461 CHECK_RES(ast_msg_set_context(msg, "%s", endpt->context));
462 CHECK_RES(ast_msg_set_exten(msg, "%s", buf));
465 CHECK_RES(ast_msg_set_to(msg, "%s", scheme_sip_to_pjsip(rdata, buf, sizeof(buf))));
468 name_addr = (pjsip_name_addr *)rdata->msg_info.from->uri;
469 if ((size = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, name_addr, buf, sizeof(buf)-1)) > 0) {
471 CHECK_RES(ast_msg_set_from(msg, "%s", buf));
474 /* receive address */
475 field = pj_sockaddr_print(&rdata->pkt_info.src_addr, buf, sizeof(buf)-1, 1);
476 CHECK_RES(ast_msg_set_var(msg, "PJSIP_RECVADDR", field));
479 if (print_body(rdata, buf, sizeof(buf) - 1) > 0) {
480 CHECK_RES(ast_msg_set_body(msg, "%s", buf));
484 if (endpt->id.self.name.valid) {
485 CHECK_RES(ast_msg_set_var(msg, "PJSIP_PEERNAME", endpt->id.self.name.str));
488 CHECK_RES(headers_to_vars(rdata, msg));
499 static void msg_data_destroy(void *obj)
501 struct msg_data *mdata = obj;
503 ast_free(mdata->from);
506 ast_msg_destroy(mdata->msg);
509 static struct msg_data* msg_data_create(const struct ast_msg *msg, const char *to, const char *from)
512 struct msg_data *mdata = ao2_alloc(sizeof(*mdata), msg_data_destroy);
518 /* typecast to suppress const warning */
519 mdata->msg = ast_msg_ref((struct ast_msg*)msg);
521 mdata->to = scheme_pjsip_to_sip(to);
522 mdata->from = ast_strdup(from);
524 /* sometimes from can still contain the tag at this point, so remove it */
525 if ((tag = strchr(mdata->from, ';'))) {
532 static int msg_send(void *data)
534 RAII_VAR(struct msg_data *, mdata, data, ao2_cleanup);
536 const struct ast_sip_body body = {
539 .body_text = ast_msg_get_body(mdata->msg)
542 pjsip_tx_data *tdata;
543 RAII_VAR(char *, uri, NULL, ast_free);
544 RAII_VAR(struct ast_sip_endpoint *, endpoint, get_endpoint(
545 mdata->to, &uri), ao2_cleanup);
548 ast_log(LOG_ERROR, "PJSIP MESSAGE - Could not find endpoint and "
549 "no default outbound endpoint configured\n");
553 if (ast_sip_create_request("MESSAGE", NULL, endpoint, uri, &tdata)) {
554 ast_log(LOG_ERROR, "PJSIP MESSAGE - Could not create request\n");
558 if (ast_sip_add_body(tdata, &body)) {
559 pjsip_tx_data_dec_ref(tdata);
560 ast_log(LOG_ERROR, "PJSIP MESSAGE - Could not add body to request\n");
564 update_from(tdata, mdata->from);
565 vars_to_headers(mdata->msg, tdata);
567 if (ast_sip_send_request(tdata, NULL, endpoint)) {
568 ast_log(LOG_ERROR, "PJSIP MESSAGE - Could not send request\n");
575 static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from)
577 struct msg_data *mdata;
579 if (ast_strlen_zero(to)) {
580 ast_log(LOG_ERROR, "SIP MESSAGE - a 'To' URI must be specified\n");
584 if (!(mdata = msg_data_create(msg, to, from)) ||
585 ast_sip_push_task(NULL, msg_send, mdata)) {
592 static const struct ast_msg_tech msg_tech = {
594 .msg_send = sip_msg_send,
597 static pj_status_t send_response(pjsip_rx_data *rdata, enum pjsip_status_code code,
598 pjsip_dialog *dlg, pjsip_transaction *tsx)
600 pjsip_tx_data *tdata;
602 pjsip_response_addr res_addr;
604 pjsip_endpoint *endpt = ast_sip_get_pjsip_endpoint();
606 status = pjsip_endpt_create_response(endpt, rdata, code, NULL, &tdata);
607 if (status != PJ_SUCCESS) {
608 ast_log(LOG_ERROR, "Unable to create response (%d)\n", status);
613 status = pjsip_dlg_send_response(dlg, tsx, tdata);
615 /* Get where to send request. */
616 status = pjsip_get_response_addr(tdata->pool, rdata, &res_addr);
617 if (status != PJ_SUCCESS) {
618 ast_log(LOG_ERROR, "Unable to get response address (%d)\n", status);
621 status = pjsip_endpt_send_response(endpt, &res_addr, tdata, NULL, NULL);
624 if (status != PJ_SUCCESS) {
625 ast_log(LOG_ERROR, "Unable to send response (%d)\n", status);
631 static pj_bool_t module_on_rx_request(pjsip_rx_data *rdata)
633 enum pjsip_status_code code;
636 /* if not a MESSAGE, don't handle */
637 if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_message_method)) {
641 msg = ast_msg_alloc();
643 send_response(rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL);
647 if ((code = check_content_type(rdata)) != PJSIP_SC_OK) {
648 send_response(rdata, code, NULL, NULL);
652 if ((code = rx_data_to_ast_msg(rdata, msg)) == PJSIP_SC_OK) {
653 /* send it to the dialplan */
655 code = PJSIP_SC_ACCEPTED;
658 send_response(rdata, code, NULL, NULL);
662 static int incoming_in_dialog_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
664 char buf[MAX_BODY_SIZE];
665 enum pjsip_status_code code;
668 pjsip_dialog *dlg = session->inv_session->dlg;
669 pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata);
671 if ((code = check_content_type(rdata)) != PJSIP_SC_OK) {
672 send_response(rdata, code, dlg, tsx);
676 if (print_body(rdata, buf, sizeof(buf)-1) < 1) {
677 /* invalid body size */
681 ast_debug(3, "Received in dialog SIP message\n");
683 memset(&f, 0, sizeof(f));
684 f.frametype = AST_FRAME_TEXT;
685 f.subclass.integer = 0;
688 f.datalen = strlen(buf) + 1;
689 ast_queue_frame(session->channel, &f);
691 send_response(rdata, PJSIP_SC_ACCEPTED, dlg, tsx);
695 static struct ast_sip_session_supplement messaging_supplement = {
697 .incoming_request = incoming_in_dialog_request
700 static pjsip_module messaging_module = {
701 .name = {"Messaging Module", 16},
703 .priority = PJSIP_MOD_PRIORITY_APPLICATION,
704 .on_rx_request = module_on_rx_request,
707 static int load_module(void)
709 if (ast_sip_register_service(&messaging_module) != PJ_SUCCESS) {
710 return AST_MODULE_LOAD_DECLINE;
713 if (pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(),
714 NULL, PJSIP_H_ALLOW, NULL, 1,
715 &pjsip_message_method.name) != PJ_SUCCESS) {
717 ast_sip_unregister_service(&messaging_module);
718 return AST_MODULE_LOAD_DECLINE;
721 if (ast_msg_tech_register(&msg_tech)) {
722 ast_sip_unregister_service(&messaging_module);
723 return AST_MODULE_LOAD_DECLINE;
726 ast_sip_session_register_supplement(&messaging_supplement);
727 return AST_MODULE_LOAD_SUCCESS;
730 static int unload_module(void)
732 ast_sip_session_unregister_supplement(&messaging_supplement);
733 ast_msg_tech_unregister(&msg_tech);
734 ast_sip_unregister_service(&messaging_module);
738 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Messaging Support",
740 .unload = unload_module,
741 .load_pri = AST_MODPRI_APP_DEPEND,