res/res_pjsip_session: Only check localnet if it is defined
[asterisk/asterisk.git] / res / res_pjsip_t38.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \author Joshua Colp <jcolp@digium.com>
22  *
23  * \brief SIP T.38 handling
24  */
25
26 /*** MODULEINFO
27         <depend>pjproject</depend>
28         <depend>res_pjsip</depend>
29         <depend>res_pjsip_session</depend>
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 #include <pjsip.h>
36 #include <pjsip_ua.h>
37 #include <pjmedia.h>
38 #include <pjlib.h>
39
40 #include "asterisk/utils.h"
41 #include "asterisk/module.h"
42 #include "asterisk/udptl.h"
43 #include "asterisk/netsock2.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/acl.h"
46
47 #include "asterisk/res_pjsip.h"
48 #include "asterisk/res_pjsip_session.h"
49
50 /*! \brief The number of seconds after receiving a T.38 re-invite before automatically rejecting it */
51 #define T38_AUTOMATIC_REJECTION_SECONDS 5
52
53 /*! \brief Address for UDPTL */
54 static struct ast_sockaddr address;
55
56 /*! \brief T.38 state information */
57 struct t38_state {
58         /*! \brief Current state */
59         enum ast_sip_session_t38state state;
60         /*! \brief Our T.38 parameters */
61         struct ast_control_t38_parameters our_parms;
62         /*! \brief Their T.38 parameters */
63         struct ast_control_t38_parameters their_parms;
64         /*! \brief Timer entry for automatically rejecting an inbound re-invite */
65         pj_timer_entry timer;
66 };
67
68 /*! \brief Destructor for T.38 state information */
69 static void t38_state_destroy(void *obj)
70 {
71         ast_free(obj);
72 }
73
74 /*! \brief Datastore for attaching T.38 state information */
75 static const struct ast_datastore_info t38_datastore = {
76         .type = "t38",
77         .destroy = t38_state_destroy,
78 };
79
80 /*! \brief Structure for T.38 parameters task data */
81 struct t38_parameters_task_data {
82         /*! \brief Session itself */
83         struct ast_sip_session *session;
84         /*! \brief T.38 control frame */
85         struct ast_frame *frame;
86 };
87
88 /*! \brief Destructor for T.38 data */
89 static void t38_parameters_task_data_destroy(void *obj)
90 {
91         struct t38_parameters_task_data *data = obj;
92
93         ao2_cleanup(data->session);
94
95         if (data->frame) {
96                 ast_frfree(data->frame);
97         }
98 }
99
100 /*! \brief Allocator for T.38 data */
101 static struct t38_parameters_task_data *t38_parameters_task_data_alloc(struct ast_sip_session *session,
102         struct ast_frame *frame)
103 {
104         struct t38_parameters_task_data *data = ao2_alloc(sizeof(*data), t38_parameters_task_data_destroy);
105
106         if (!data) {
107                 return NULL;
108         }
109
110         data->session = session;
111         ao2_ref(session, +1);
112         data->frame = ast_frdup(frame);
113         if (!data->frame) {
114                 ao2_ref(data, -1);
115                 data = NULL;
116         }
117
118         return data;
119 }
120
121 /*! \brief Helper function for changing the T.38 state */
122 static void t38_change_state(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
123         struct t38_state *state, enum ast_sip_session_t38state new_state)
124 {
125         enum ast_sip_session_t38state old_state = session->t38state;
126         struct ast_control_t38_parameters parameters = { .request_response = 0, };
127         pj_time_val delay = { .sec = T38_AUTOMATIC_REJECTION_SECONDS };
128
129         if (old_state == new_state) {
130                 return;
131         }
132
133         session->t38state = new_state;
134         ast_debug(2, "T.38 state changed to '%u' from '%u' on channel '%s'\n",
135                 new_state, old_state,
136                 session->channel ? ast_channel_name(session->channel) : "<gone>");
137
138         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &state->timer)) {
139                 ast_debug(2, "Automatic T.38 rejection on channel '%s' terminated\n",
140                         session->channel ? ast_channel_name(session->channel) : "<gone>");
141                 ao2_ref(session, -1);
142         }
143
144         if (!session->channel) {
145                 return;
146         }
147
148         switch (new_state) {
149         case T38_PEER_REINVITE:
150                 ao2_ref(session, +1);
151                 if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &state->timer, &delay) != PJ_SUCCESS) {
152                         ast_log(LOG_WARNING, "Scheduling of automatic T.38 rejection for channel '%s' failed\n",
153                                 ast_channel_name(session->channel));
154                         ao2_ref(session, -1);
155                 }
156                 parameters = state->their_parms;
157                 parameters.max_ifp = ast_udptl_get_far_max_ifp(session_media->udptl);
158                 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
159                 ast_udptl_set_tag(session_media->udptl, "%s", ast_channel_name(session->channel));
160
161                 /* Inform the bridge the channel is in that it needs to be reconfigured */
162                 ast_channel_set_unbridged(session->channel, 1);
163                 break;
164         case T38_ENABLED:
165                 parameters = state->their_parms;
166                 parameters.max_ifp = ast_udptl_get_far_max_ifp(session_media->udptl);
167                 parameters.request_response = AST_T38_NEGOTIATED;
168                 ast_udptl_set_tag(session_media->udptl, "%s", ast_channel_name(session->channel));
169                 break;
170         case T38_REJECTED:
171         case T38_DISABLED:
172                 if (old_state == T38_ENABLED) {
173                         parameters.request_response = AST_T38_TERMINATED;
174                 } else if (old_state == T38_LOCAL_REINVITE) {
175                         parameters.request_response = AST_T38_REFUSED;
176                 }
177                 break;
178         case T38_LOCAL_REINVITE:
179                 /* Inform the bridge the channel is in that it needs to be reconfigured */
180                 ast_channel_set_unbridged(session->channel, 1);
181                 break;
182         case T38_MAX_ENUM:
183                 /* Well, that shouldn't happen */
184                 ast_assert(0);
185                 break;
186         }
187
188         if (parameters.request_response) {
189                 ast_queue_control_data(session->channel, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
190         }
191 }
192
193 /*! \brief Task function which rejects a T.38 re-invite and resumes handling it */
194 static int t38_automatic_reject(void *obj)
195 {
196         RAII_VAR(struct ast_sip_session *, session, obj, ao2_cleanup);
197         RAII_VAR(struct ast_datastore *, datastore, ast_sip_session_get_datastore(session, "t38"), ao2_cleanup);
198         RAII_VAR(struct ast_sip_session_media *, session_media, ao2_find(session->media, "image", OBJ_KEY), ao2_cleanup);
199
200         if (!datastore) {
201                 return 0;
202         }
203
204         ast_debug(2, "Automatically rejecting T.38 request on channel '%s'\n",
205                 session->channel ? ast_channel_name(session->channel) : "<gone>");
206
207         t38_change_state(session, session_media, datastore->data, T38_REJECTED);
208         ast_sip_session_resume_reinvite(session);
209
210         return 0;
211 }
212
213 /*! \brief Timer entry callback which queues a task to reject a T.38 re-invite and resume handling it */
214 static void t38_automatic_reject_timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
215 {
216         struct ast_sip_session *session = entry->user_data;
217
218         if (ast_sip_push_task(session->serializer, t38_automatic_reject, session)) {
219                 ao2_ref(session, -1);
220         }
221 }
222
223 /*! \brief Helper function which retrieves or allocates a T.38 state information datastore */
224 static struct t38_state *t38_state_get_or_alloc(struct ast_sip_session *session)
225 {
226         RAII_VAR(struct ast_datastore *, datastore, ast_sip_session_get_datastore(session, "t38"), ao2_cleanup);
227         struct t38_state *state;
228
229         /* While the datastore refcount is decremented this is operating in the serializer so it will remain valid regardless */
230         if (datastore) {
231                 return datastore->data;
232         }
233
234         if (!(datastore = ast_sip_session_alloc_datastore(&t38_datastore, "t38"))
235                 || !(datastore->data = ast_calloc(1, sizeof(struct t38_state)))
236                 || ast_sip_session_add_datastore(session, datastore)) {
237                 return NULL;
238         }
239
240         state = datastore->data;
241
242         /* This will get bumped up before scheduling */
243         state->timer.user_data = session;
244         state->timer.cb = t38_automatic_reject_timer_cb;
245
246         datastore->data = state;
247
248         return state;
249 }
250
251 /*! \brief Initializes UDPTL support on a session, only done when actually needed */
252 static int t38_initialize_session(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
253 {
254         if (session_media->udptl) {
255                 return 0;
256         }
257
258         if (!(session_media->udptl = ast_udptl_new_with_bindaddr(NULL, NULL, 0, &address))) {
259                 return -1;
260         }
261
262         ast_channel_set_fd(session->channel, 5, ast_udptl_fd(session_media->udptl));
263         ast_udptl_set_error_correction_scheme(session_media->udptl, session->endpoint->media.t38.error_correction);
264         ast_udptl_setnat(session_media->udptl, session->endpoint->media.t38.nat);
265         ast_udptl_set_far_max_datagram(session_media->udptl, session->endpoint->media.t38.maxdatagram);
266         ast_debug(3, "UDPTL initialized on session for %s\n", ast_channel_name(session->channel));
267
268         return 0;
269 }
270
271 /*! \brief Callback for when T.38 reinvite SDP is created */
272 static int t38_reinvite_sdp_cb(struct ast_sip_session *session, pjmedia_sdp_session *sdp)
273 {
274         int stream;
275
276         /* Move the image media stream to the front and have it as the only stream, pjmedia will fill in
277          * dummy streams for the rest
278          */
279         for (stream = 0; stream < sdp->media_count++; ++stream) {
280                 if (!pj_strcmp2(&sdp->media[stream]->desc.media, "image")) {
281                         sdp->media[0] = sdp->media[stream];
282                         sdp->media_count = 1;
283                         break;
284                 }
285         }
286
287         return 0;
288 }
289
290 /*! \brief Callback for when a response is received for a T.38 re-invite */
291 static int t38_reinvite_response_cb(struct ast_sip_session *session, pjsip_rx_data *rdata)
292 {
293         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
294         struct t38_state *state;
295         RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
296
297         if (status.code == 100) {
298                 return 0;
299         }
300
301         if (!(state = t38_state_get_or_alloc(session)) ||
302                 !(session_media = ao2_find(session->media, "image", OBJ_KEY))) {
303                 ast_log(LOG_WARNING, "Received response to T.38 re-invite on '%s' but state unavailable\n",
304                         ast_channel_name(session->channel));
305                 return 0;
306         }
307
308         t38_change_state(session, session_media, state, (status.code == 200) ? T38_ENABLED : T38_REJECTED);
309
310         return 0;
311 }
312
313 /*! \brief Task for reacting to T.38 control frame */
314 static int t38_interpret_parameters(void *obj)
315 {
316         RAII_VAR(struct t38_parameters_task_data *, data, obj, ao2_cleanup);
317         const struct ast_control_t38_parameters *parameters = data->frame->data.ptr;
318         struct t38_state *state = t38_state_get_or_alloc(data->session);
319         RAII_VAR(struct ast_sip_session_media *, session_media, ao2_find(data->session->media, "image", OBJ_KEY), ao2_cleanup);
320
321         /* Without session media or state we can't interpret parameters */
322         if (!session_media || !state) {
323                 return 0;
324         }
325
326         switch (parameters->request_response) {
327         case AST_T38_NEGOTIATED:
328         case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
329                 /* Negotiation can not take place without a valid max_ifp value. */
330                 if (!parameters->max_ifp) {
331                         if (data->session->t38state == T38_PEER_REINVITE) {
332                                 t38_change_state(data->session, session_media, state, T38_REJECTED);
333                                 ast_sip_session_resume_reinvite(data->session);
334                         } else if (data->session->t38state == T38_ENABLED) {
335                                 t38_change_state(data->session, session_media, state, T38_DISABLED);
336                                 ast_sip_session_refresh(data->session, NULL, NULL, NULL,
337                                         AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1);
338                         }
339                         break;
340                 } else if (data->session->t38state == T38_PEER_REINVITE) {
341                         state->our_parms = *parameters;
342                         /* modify our parameters to conform to the peer's parameters,
343                          * based on the rules in the ITU T.38 recommendation
344                          */
345                         if (!state->their_parms.fill_bit_removal) {
346                                 state->our_parms.fill_bit_removal = 0;
347                         }
348                         if (!state->their_parms.transcoding_mmr) {
349                                 state->our_parms.transcoding_mmr = 0;
350                         }
351                         if (!state->their_parms.transcoding_jbig) {
352                                 state->our_parms.transcoding_jbig = 0;
353                         }
354                         state->our_parms.version = MIN(state->our_parms.version, state->their_parms.version);
355                         state->our_parms.rate_management = state->their_parms.rate_management;
356                         ast_udptl_set_local_max_ifp(session_media->udptl, state->our_parms.max_ifp);
357                         t38_change_state(data->session, session_media, state, T38_ENABLED);
358                         ast_sip_session_resume_reinvite(data->session);
359                 } else if ((data->session->t38state != T38_ENABLED) ||
360                                 ((data->session->t38state == T38_ENABLED) &&
361                                 (parameters->request_response == AST_T38_REQUEST_NEGOTIATE))) {
362                         if (t38_initialize_session(data->session, session_media)) {
363                                 break;
364                         }
365                         state->our_parms = *parameters;
366                         ast_udptl_set_local_max_ifp(session_media->udptl, state->our_parms.max_ifp);
367                         t38_change_state(data->session, session_media, state, T38_LOCAL_REINVITE);
368                         ast_sip_session_refresh(data->session, NULL, t38_reinvite_sdp_cb, t38_reinvite_response_cb,
369                                 AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1);
370                 }
371                 break;
372         case AST_T38_TERMINATED:
373         case AST_T38_REFUSED:
374         case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
375                 if (data->session->t38state == T38_PEER_REINVITE) {
376                         t38_change_state(data->session, session_media, state, T38_REJECTED);
377                         ast_sip_session_resume_reinvite(data->session);
378                 } else if (data->session->t38state == T38_ENABLED) {
379                         t38_change_state(data->session, session_media, state, T38_DISABLED);
380                         ast_sip_session_refresh(data->session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1);
381                 }
382                 break;
383         case AST_T38_REQUEST_PARMS: {           /* Application wants remote's parameters re-sent */
384                 struct ast_control_t38_parameters parameters = state->their_parms;
385
386                 if (data->session->t38state == T38_PEER_REINVITE) {
387                         parameters.max_ifp = ast_udptl_get_far_max_ifp(session_media->udptl);
388                         parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
389                         ast_queue_control_data(data->session->channel, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
390                 }
391                 break;
392         }
393         default:
394                 break;
395         }
396
397         return 0;
398 }
399
400 /*! \brief Frame hook callback for writing */
401 static struct ast_frame *t38_framehook_write(struct ast_sip_session *session, struct ast_frame *f)
402 {
403         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_T38_PARAMETERS &&
404                 session->endpoint->media.t38.enabled) {
405                 struct t38_parameters_task_data *data = t38_parameters_task_data_alloc(session, f);
406
407                 if (!data) {
408                         return f;
409                 }
410
411                 if (ast_sip_push_task(session->serializer, t38_interpret_parameters, data)) {
412                         ao2_ref(data, -1);
413                 }
414         } else if (f->frametype == AST_FRAME_MODEM) {
415                 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
416
417                 if ((session_media = ao2_find(session->media, "image", OBJ_KEY)) &&
418                         session_media->udptl) {
419                         ast_udptl_write(session_media->udptl, f);
420                 }
421         }
422
423         return f;
424 }
425
426 /*! \brief Frame hook callback for reading */
427 static struct ast_frame *t38_framehook_read(struct ast_sip_session *session, struct ast_frame *f)
428 {
429         if (ast_channel_fdno(session->channel) == 5) {
430                 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
431
432                 if ((session_media = ao2_find(session->media, "image", OBJ_KEY)) &&
433                         session_media->udptl) {
434                         f = ast_udptl_read(session_media->udptl);
435                 }
436         }
437
438         return f;
439 }
440
441 /*! \brief Frame hook callback for T.38 related stuff */
442 static struct ast_frame *t38_framehook(struct ast_channel *chan, struct ast_frame *f,
443         enum ast_framehook_event event, void *data)
444 {
445         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
446
447         if (event == AST_FRAMEHOOK_EVENT_READ) {
448                 f = t38_framehook_read(channel->session, f);
449         } else if (event == AST_FRAMEHOOK_EVENT_WRITE) {
450                 f = t38_framehook_write(channel->session, f);
451         }
452
453         return f;
454 }
455
456 static void t38_masq(void *data, int framehook_id,
457         struct ast_channel *old_chan, struct ast_channel *new_chan)
458 {
459         if (ast_channel_tech(old_chan) == ast_channel_tech(new_chan)) {
460                 return;
461         }
462
463         /* This framehook is only applicable to PJSIP channels */
464         ast_framehook_detach(new_chan, framehook_id);
465 }
466
467 static int t38_consume(void *data, enum ast_frame_type type)
468 {
469         return 0;
470 }
471
472 static const struct ast_datastore_info t38_framehook_datastore = {
473         .type = "T38 framehook",
474 };
475
476 /*! \brief Function called to attach T.38 framehook to channel when appropriate */
477 static void t38_attach_framehook(struct ast_sip_session *session)
478 {
479         int framehook_id;
480         struct ast_datastore *datastore = NULL;
481         static struct ast_framehook_interface hook = {
482                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
483                 .event_cb = t38_framehook,
484                 .consume_cb = t38_consume,
485                 .chan_fixup_cb = t38_masq,
486                 .chan_breakdown_cb = t38_masq,
487         };
488
489         /* If the channel's already gone, bail */
490         if (!session->channel) {
491                 return;
492         }
493
494         /* Only attach the framehook if t38 is enabled for the endpoint */
495         if (!session->endpoint->media.t38.enabled) {
496                 return;
497         }
498
499         ast_channel_lock(session->channel);
500
501         /* Skip attaching the framehook if the T.38 datastore already exists for the channel */
502         datastore = ast_channel_datastore_find(session->channel, &t38_framehook_datastore,
503                 NULL);
504         if (datastore) {
505                 ast_channel_unlock(session->channel);
506                 return;
507         }
508
509         framehook_id = ast_framehook_attach(session->channel, &hook);
510         if (framehook_id < 0) {
511                 ast_log(LOG_WARNING, "Could not attach T.38 Frame hook, T.38 will be unavailable on '%s'\n",
512                         ast_channel_name(session->channel));
513                 ast_channel_unlock(session->channel);
514                 return;
515         }
516
517         datastore = ast_datastore_alloc(&t38_framehook_datastore, NULL);
518         if (!datastore) {
519                 ast_log(LOG_ERROR, "Could not alloc T.38 Frame hook datastore, T.38 will be unavailable on '%s'\n",
520                         ast_channel_name(session->channel));
521                 ast_framehook_detach(session->channel, framehook_id);
522                 ast_channel_unlock(session->channel);
523                 return;
524         }
525
526         ast_channel_datastore_add(session->channel, datastore);
527         ast_channel_unlock(session->channel);
528 }
529
530 /*! \brief Function called when an INVITE arrives */
531 static int t38_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
532 {
533         t38_attach_framehook(session);
534         return 0;
535 }
536
537 /*! \brief Function called when an INVITE is sent */
538 static void t38_outgoing_invite_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
539 {
540         t38_attach_framehook(session);
541 }
542
543 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
544 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
545 {
546         switch (rate) {
547         case AST_T38_RATE_2400:
548                 return 2400;
549         case AST_T38_RATE_4800:
550                 return 4800;
551         case AST_T38_RATE_7200:
552                 return 7200;
553         case AST_T38_RATE_9600:
554                 return 9600;
555         case AST_T38_RATE_12000:
556                 return 12000;
557         case AST_T38_RATE_14400:
558                 return 14400;
559         default:
560                 return 0;
561         }
562 }
563
564 /*! \brief Supplement for adding framehook to session channel */
565 static struct ast_sip_session_supplement t38_supplement = {
566         .method = "INVITE",
567         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL + 1,
568         .incoming_request = t38_incoming_invite_request,
569         .outgoing_request = t38_outgoing_invite_request,
570 };
571
572 /*! \brief Parse a T.38 image stream and store the attribute information */
573 static void t38_interpret_sdp(struct t38_state *state, struct ast_sip_session *session, struct ast_sip_session_media *session_media,
574         const struct pjmedia_sdp_media *stream)
575 {
576         unsigned int attr_i;
577
578         for (attr_i = 0; attr_i < stream->attr_count; attr_i++) {
579                 pjmedia_sdp_attr *attr = stream->attr[attr_i];
580
581                 if (!pj_stricmp2(&attr->name, "t38faxmaxbuffer")) {
582                         /* This is purposely left empty, it is unused */
583                 } else if (!pj_stricmp2(&attr->name, "t38maxbitrate") || !pj_stricmp2(&attr->name, "t38faxmaxrate")) {
584                         switch (pj_strtoul(&attr->value)) {
585                         case 14400:
586                                 state->their_parms.rate = AST_T38_RATE_14400;
587                                 break;
588                         case 12000:
589                                 state->their_parms.rate = AST_T38_RATE_12000;
590                                 break;
591                         case 9600:
592                                 state->their_parms.rate = AST_T38_RATE_9600;
593                                 break;
594                         case 7200:
595                                 state->their_parms.rate = AST_T38_RATE_7200;
596                                 break;
597                         case 4800:
598                                 state->their_parms.rate = AST_T38_RATE_4800;
599                                 break;
600                         case 2400:
601                                 state->their_parms.rate = AST_T38_RATE_2400;
602                                 break;
603                         }
604                 } else if (!pj_stricmp2(&attr->name, "t38faxversion")) {
605                         state->their_parms.version = pj_strtoul(&attr->value);
606                 } else if (!pj_stricmp2(&attr->name, "t38faxmaxdatagram") || !pj_stricmp2(&attr->name, "t38maxdatagram")) {
607                         if (!session->endpoint->media.t38.maxdatagram) {
608                                 ast_udptl_set_far_max_datagram(session_media->udptl, pj_strtoul(&attr->value));
609                         }
610                 } else if (!pj_stricmp2(&attr->name, "t38faxfillbitremoval")) {
611                         state->their_parms.fill_bit_removal = 1;
612                 } else if (!pj_stricmp2(&attr->name, "t38faxtranscodingmmr")) {
613                         state->their_parms.transcoding_mmr = 1;
614                 } else if (!pj_stricmp2(&attr->name, "t38faxtranscodingjbig")) {
615                         state->their_parms.transcoding_jbig = 1;
616                 } else if (!pj_stricmp2(&attr->name, "t38faxratemanagement")) {
617                         if (!pj_stricmp2(&attr->value, "localTCF")) {
618                                 state->their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
619                         } else if (!pj_stricmp2(&attr->value, "transferredTCF")) {
620                                 state->their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
621                         }
622                 } else if (!pj_stricmp2(&attr->name, "t38faxudpec")) {
623                         if (!pj_stricmp2(&attr->value, "t38UDPRedundancy")) {
624                                 ast_udptl_set_error_correction_scheme(session_media->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
625                         } else if (!pj_stricmp2(&attr->value, "t38UDPFEC")) {
626                                 ast_udptl_set_error_correction_scheme(session_media->udptl, UDPTL_ERROR_CORRECTION_FEC);
627                         } else {
628                                 ast_udptl_set_error_correction_scheme(session_media->udptl, UDPTL_ERROR_CORRECTION_NONE);
629                         }
630                 }
631
632         }
633 }
634
635 /*! \brief Function which defers an incoming media stream */
636 static enum ast_sip_session_sdp_stream_defer defer_incoming_sdp_stream(
637         struct ast_sip_session *session, struct ast_sip_session_media *session_media,
638         const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
639 {
640         struct t38_state *state;
641
642         if (!session->endpoint->media.t38.enabled) {
643                 ast_debug(3, "Not deferring incoming SDP stream: T.38 not enabled on %s\n", ast_channel_name(session->channel));
644                 return AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED;
645         }
646
647         if (t38_initialize_session(session, session_media)) {
648                 ast_debug(3, "Not deferring incoming SDP stream: Failed to initialize UDPTL on %s\n", ast_channel_name(session->channel));
649                 return AST_SIP_SESSION_SDP_DEFER_ERROR;
650         }
651
652         if (!(state = t38_state_get_or_alloc(session))) {
653                 return AST_SIP_SESSION_SDP_DEFER_ERROR;
654         }
655
656         t38_interpret_sdp(state, session, session_media, stream);
657
658         /* If they are initiating the re-invite we need to defer responding until later */
659         if (session->t38state == T38_DISABLED) {
660                 t38_change_state(session, session_media, state, T38_PEER_REINVITE);
661                 ast_debug(3, "Deferring incoming SDP stream on %s for peer re-invite\n", ast_channel_name(session->channel));
662                 return AST_SIP_SESSION_SDP_DEFER_NEEDED;
663         }
664
665         return AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED;
666 }
667
668 /*! \brief Function which negotiates an incoming media stream */
669 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
670                                          const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
671 {
672         struct t38_state *state;
673         char host[NI_MAXHOST];
674         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
675
676         if (!session->endpoint->media.t38.enabled) {
677                 ast_debug(3, "Declining; T.38 not enabled on session\n");
678                 return -1;
679         }
680
681         if (!(state = t38_state_get_or_alloc(session))) {
682                 return -1;
683         }
684
685         if ((session->t38state == T38_REJECTED) || (session->t38state == T38_DISABLED)) {
686                 ast_debug(3, "Declining; T.38 state is rejected or declined\n");
687                 t38_change_state(session, session_media, state, T38_DISABLED);
688                 return -1;
689         }
690
691         ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
692
693         /* Ensure that the address provided is valid */
694         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_INET) <= 0) {
695                 /* The provided host was actually invalid so we error out this negotiation */
696                 ast_debug(3, "Declining; provided host is invalid\n");
697                 return -1;
698         }
699
700         /* Check the address family to make sure it matches configured */
701         if ((ast_sockaddr_is_ipv6(addrs) && !session->endpoint->media.t38.ipv6) ||
702                 (ast_sockaddr_is_ipv4(addrs) && session->endpoint->media.t38.ipv6)) {
703                 /* The address does not match configured */
704                 ast_debug(3, "Declining, provided host does not match configured address family\n");
705                 return -1;
706         }
707
708         return 1;
709 }
710
711 /*! \brief Function which creates an outgoing stream */
712 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
713                                       struct pjmedia_sdp_session *sdp)
714 {
715         pj_pool_t *pool = session->inv_session->pool_prov;
716         static const pj_str_t STR_IN = { "IN", 2 };
717         static const pj_str_t STR_IP4 = { "IP4", 3};
718         static const pj_str_t STR_IP6 = { "IP6", 3};
719         static const pj_str_t STR_UDPTL = { "udptl", 5 };
720         static const pj_str_t STR_T38 = { "t38", 3 };
721         static const pj_str_t STR_TRANSFERREDTCF = { "transferredTCF", 14 };
722         static const pj_str_t STR_LOCALTCF = { "localTCF", 8 };
723         static const pj_str_t STR_T38UDPFEC = { "t38UDPFEC", 9 };
724         static const pj_str_t STR_T38UDPREDUNDANCY = { "t38UDPRedundancy", 16 };
725         struct t38_state *state;
726         pjmedia_sdp_media *media;
727         const char *hostip = NULL;
728         struct ast_sockaddr addr;
729         char tmp[512];
730         pj_str_t stmp;
731
732         if (!session->endpoint->media.t38.enabled) {
733                 ast_debug(3, "Not creating outgoing SDP stream: T.38 not enabled\n");
734                 return 1;
735         } else if ((session->t38state != T38_LOCAL_REINVITE) && (session->t38state != T38_PEER_REINVITE) &&
736                 (session->t38state != T38_ENABLED)) {
737                 ast_debug(3, "Not creating outgoing SDP stream: T.38 not enabled\n");
738                 return 1;
739         } else if (!(state = t38_state_get_or_alloc(session))) {
740                 return -1;
741         } else if (t38_initialize_session(session, session_media)) {
742                 ast_debug(3, "Not creating outgoing SDP stream: Failed to initialize T.38 session\n");
743                 return -1;
744         }
745
746         if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
747                 !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
748                 return -1;
749         }
750
751         media->desc.media = pj_str(session_media->stream_type);
752         media->desc.transport = STR_UDPTL;
753
754         if (ast_strlen_zero(session->endpoint->media.address)) {
755                 hostip = ast_sip_get_host_ip_string(session->endpoint->media.t38.ipv6 ? pj_AF_INET6() : pj_AF_INET());
756         } else {
757                 hostip = session->endpoint->media.address;
758         }
759
760         if (ast_strlen_zero(hostip)) {
761                 ast_debug(3, "Not creating outgoing SDP stream: no known host IP\n");
762                 return -1;
763         }
764
765         media->conn->net_type = STR_IN;
766         media->conn->addr_type = session->endpoint->media.t38.ipv6 ? STR_IP6 : STR_IP4;
767         pj_strdup2(pool, &media->conn->addr, hostip);
768         ast_udptl_get_us(session_media->udptl, &addr);
769         media->desc.port = (pj_uint16_t) ast_sockaddr_port(&addr);
770         media->desc.port_count = 1;
771         media->desc.fmt[media->desc.fmt_count++] = STR_T38;
772
773         snprintf(tmp, sizeof(tmp), "%u", state->our_parms.version);
774         media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxVersion", pj_cstr(&stmp, tmp));
775
776         snprintf(tmp, sizeof(tmp), "%u", t38_get_rate(state->our_parms.rate));
777         media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38MaxBitRate", pj_cstr(&stmp, tmp));
778
779         if (state->our_parms.fill_bit_removal) {
780                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxFillBitRemoval", NULL);
781         }
782
783         if (state->our_parms.transcoding_mmr) {
784                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxTranscodingMMR", NULL);
785         }
786
787         if (state->our_parms.transcoding_jbig) {
788                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxTranscodingJBIG", NULL);
789         }
790
791         switch (state->our_parms.rate_management) {
792         case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
793                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxRateManagement", &STR_TRANSFERREDTCF);
794                 break;
795         case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
796                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxRateManagement", &STR_LOCALTCF);
797                 break;
798         }
799
800         snprintf(tmp, sizeof(tmp), "%u", ast_udptl_get_local_max_datagram(session_media->udptl));
801         media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxMaxDatagram", pj_cstr(&stmp, tmp));
802
803         switch (ast_udptl_get_error_correction_scheme(session_media->udptl)) {
804         case UDPTL_ERROR_CORRECTION_NONE:
805                 break;
806         case UDPTL_ERROR_CORRECTION_FEC:
807                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxUdpEC", &STR_T38UDPFEC);
808                 break;
809         case UDPTL_ERROR_CORRECTION_REDUNDANCY:
810                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxUdpEC", &STR_T38UDPREDUNDANCY);
811                 break;
812         }
813
814         sdp->media[sdp->media_count++] = media;
815
816         return 1;
817 }
818
819 /*! \brief Function which applies a negotiated stream */
820 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
821                                        const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
822                                        const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
823 {
824         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
825         char host[NI_MAXHOST];
826         struct t38_state *state;
827
828         if (!session_media->udptl) {
829                 ast_debug(3, "Not applying negotiated SDP stream: no UDTPL session\n");
830                 return 0;
831         }
832
833         if (!(state = t38_state_get_or_alloc(session))) {
834                 return -1;
835         }
836
837         ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
838
839         /* Ensure that the address provided is valid */
840         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
841                 /* The provided host was actually invalid so we error out this negotiation */
842                 ast_debug(3, "Not applying negotiated SDP stream: failed to resolve remote stream host\n");
843                 return -1;
844         }
845
846         ast_sockaddr_set_port(addrs, remote_stream->desc.port);
847         ast_udptl_set_peer(session_media->udptl, addrs);
848
849         t38_interpret_sdp(state, session, session_media, remote_stream);
850
851         return 0;
852 }
853
854 /*! \brief Function which updates the media stream with external media address, if applicable */
855 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
856 {
857         RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);
858         char host[NI_MAXHOST];
859         struct ast_sockaddr addr = { { 0, } };
860
861         /* If the stream has been rejected there will be no connection line */
862         if (!stream->conn || !transport_state) {
863                 return;
864         }
865
866         ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
867         ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
868
869         /* Is the address within the SDP inside the same network? */
870         if (transport_state->localnet
871                 && ast_apply_ha(transport_state->localnet, &addr) == AST_SENSE_ALLOW) {
872                 return;
873         }
874         ast_debug(5, "Setting media address to %s\n", transport->external_media_address);
875         pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
876 }
877
878 /*! \brief Function which destroys the UDPTL instance when session ends */
879 static void stream_destroy(struct ast_sip_session_media *session_media)
880 {
881         if (session_media->udptl) {
882                 ast_udptl_destroy(session_media->udptl);
883         }
884         session_media->udptl = NULL;
885 }
886
887 /*! \brief SDP handler for 'image' media stream */
888 static struct ast_sip_session_sdp_handler image_sdp_handler = {
889         .id = "image",
890         .defer_incoming_sdp_stream = defer_incoming_sdp_stream,
891         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
892         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
893         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
894         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
895         .stream_destroy = stream_destroy,
896 };
897
898 /*! \brief Unloads the SIP T.38 module from Asterisk */
899 static int unload_module(void)
900 {
901         ast_sip_session_unregister_sdp_handler(&image_sdp_handler, "image");
902         ast_sip_session_unregister_supplement(&t38_supplement);
903
904         return 0;
905 }
906
907 /*!
908  * \brief Load the module
909  *
910  * Module loading including tests for configuration or dependencies.
911  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
912  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
913  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
914  * configuration file or other non-critical problem return
915  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
916  */
917 static int load_module(void)
918 {
919         CHECK_PJSIP_SESSION_MODULE_LOADED();
920
921         if (ast_check_ipv6()) {
922                 ast_sockaddr_parse(&address, "::", 0);
923         } else {
924                 ast_sockaddr_parse(&address, "0.0.0.0", 0);
925         }
926
927         if (ast_sip_session_register_supplement(&t38_supplement)) {
928                 ast_log(LOG_ERROR, "Unable to register T.38 session supplement\n");
929                 goto end;
930         }
931
932         if (ast_sip_session_register_sdp_handler(&image_sdp_handler, "image")) {
933                 ast_log(LOG_ERROR, "Unable to register SDP handler for image stream type\n");
934                 goto end;
935         }
936
937         return AST_MODULE_LOAD_SUCCESS;
938 end:
939         unload_module();
940
941         return AST_MODULE_LOAD_FAILURE;
942 }
943
944 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP T.38 UDPTL Support",
945         .support_level = AST_MODULE_SUPPORT_CORE,
946         .load = load_module,
947         .unload = unload_module,
948         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
949 );