Merge "res_pjsip: New endpoint option "refer_blind_progress""
[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_channel *chan,
402         struct ast_sip_session *session, struct ast_frame *f)
403 {
404         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_T38_PARAMETERS &&
405                 session->endpoint->media.t38.enabled) {
406                 struct t38_parameters_task_data *data = t38_parameters_task_data_alloc(session, f);
407
408                 if (!data) {
409                         return f;
410                 }
411
412                 if (ast_sip_push_task(session->serializer, t38_interpret_parameters, data)) {
413                         ao2_ref(data, -1);
414                 }
415         } else if (f->frametype == AST_FRAME_MODEM) {
416                 struct ast_sip_session_media *session_media;
417
418                 /* Avoid deadlock between chan and the session->media container lock */
419                 ast_channel_unlock(chan);
420                 session_media = ao2_find(session->media, "image", OBJ_SEARCH_KEY);
421                 ast_channel_lock(chan);
422                 if (session_media && session_media->udptl) {
423                         ast_udptl_write(session_media->udptl, f);
424                 }
425                 ao2_cleanup(session_media);
426         }
427
428         return f;
429 }
430
431 /*! \brief Frame hook callback for reading */
432 static struct ast_frame *t38_framehook_read(struct ast_channel *chan,
433         struct ast_sip_session *session, struct ast_frame *f)
434 {
435         if (ast_channel_fdno(session->channel) == 5) {
436                 struct ast_sip_session_media *session_media;
437
438                 /* Avoid deadlock between chan and the session->media container lock */
439                 ast_channel_unlock(chan);
440                 session_media = ao2_find(session->media, "image", OBJ_SEARCH_KEY);
441                 ast_channel_lock(chan);
442                 if (session_media && session_media->udptl) {
443                         f = ast_udptl_read(session_media->udptl);
444                 }
445                 ao2_cleanup(session_media);
446         }
447
448         return f;
449 }
450
451 /*! \brief Frame hook callback for T.38 related stuff */
452 static struct ast_frame *t38_framehook(struct ast_channel *chan, struct ast_frame *f,
453         enum ast_framehook_event event, void *data)
454 {
455         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
456
457         if (event == AST_FRAMEHOOK_EVENT_READ) {
458                 f = t38_framehook_read(chan, channel->session, f);
459         } else if (event == AST_FRAMEHOOK_EVENT_WRITE) {
460                 f = t38_framehook_write(chan, channel->session, f);
461         }
462
463         return f;
464 }
465
466 static void t38_masq(void *data, int framehook_id,
467         struct ast_channel *old_chan, struct ast_channel *new_chan)
468 {
469         if (ast_channel_tech(old_chan) == ast_channel_tech(new_chan)) {
470                 return;
471         }
472
473         /* This framehook is only applicable to PJSIP channels */
474         ast_framehook_detach(new_chan, framehook_id);
475 }
476
477 static int t38_consume(void *data, enum ast_frame_type type)
478 {
479         return 0;
480 }
481
482 static const struct ast_datastore_info t38_framehook_datastore = {
483         .type = "T38 framehook",
484 };
485
486 /*! \brief Function called to attach T.38 framehook to channel when appropriate */
487 static void t38_attach_framehook(struct ast_sip_session *session)
488 {
489         int framehook_id;
490         struct ast_datastore *datastore = NULL;
491         static struct ast_framehook_interface hook = {
492                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
493                 .event_cb = t38_framehook,
494                 .consume_cb = t38_consume,
495                 .chan_fixup_cb = t38_masq,
496                 .chan_breakdown_cb = t38_masq,
497         };
498
499         /* If the channel's already gone, bail */
500         if (!session->channel) {
501                 return;
502         }
503
504         /* Only attach the framehook if t38 is enabled for the endpoint */
505         if (!session->endpoint->media.t38.enabled) {
506                 return;
507         }
508
509         ast_channel_lock(session->channel);
510
511         /* Skip attaching the framehook if the T.38 datastore already exists for the channel */
512         datastore = ast_channel_datastore_find(session->channel, &t38_framehook_datastore,
513                 NULL);
514         if (datastore) {
515                 ast_channel_unlock(session->channel);
516                 return;
517         }
518
519         framehook_id = ast_framehook_attach(session->channel, &hook);
520         if (framehook_id < 0) {
521                 ast_log(LOG_WARNING, "Could not attach T.38 Frame hook, T.38 will be unavailable on '%s'\n",
522                         ast_channel_name(session->channel));
523                 ast_channel_unlock(session->channel);
524                 return;
525         }
526
527         datastore = ast_datastore_alloc(&t38_framehook_datastore, NULL);
528         if (!datastore) {
529                 ast_log(LOG_ERROR, "Could not alloc T.38 Frame hook datastore, T.38 will be unavailable on '%s'\n",
530                         ast_channel_name(session->channel));
531                 ast_framehook_detach(session->channel, framehook_id);
532                 ast_channel_unlock(session->channel);
533                 return;
534         }
535
536         ast_channel_datastore_add(session->channel, datastore);
537         ast_channel_unlock(session->channel);
538 }
539
540 /*! \brief Function called when an INVITE arrives */
541 static int t38_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
542 {
543         t38_attach_framehook(session);
544         return 0;
545 }
546
547 /*! \brief Function called when an INVITE is sent */
548 static void t38_outgoing_invite_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
549 {
550         t38_attach_framehook(session);
551 }
552
553 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
554 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
555 {
556         switch (rate) {
557         case AST_T38_RATE_2400:
558                 return 2400;
559         case AST_T38_RATE_4800:
560                 return 4800;
561         case AST_T38_RATE_7200:
562                 return 7200;
563         case AST_T38_RATE_9600:
564                 return 9600;
565         case AST_T38_RATE_12000:
566                 return 12000;
567         case AST_T38_RATE_14400:
568                 return 14400;
569         default:
570                 return 0;
571         }
572 }
573
574 /*! \brief Supplement for adding framehook to session channel */
575 static struct ast_sip_session_supplement t38_supplement = {
576         .method = "INVITE",
577         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL + 1,
578         .incoming_request = t38_incoming_invite_request,
579         .outgoing_request = t38_outgoing_invite_request,
580 };
581
582 /*! \brief Parse a T.38 image stream and store the attribute information */
583 static void t38_interpret_sdp(struct t38_state *state, struct ast_sip_session *session, struct ast_sip_session_media *session_media,
584         const struct pjmedia_sdp_media *stream)
585 {
586         unsigned int attr_i;
587
588         for (attr_i = 0; attr_i < stream->attr_count; attr_i++) {
589                 pjmedia_sdp_attr *attr = stream->attr[attr_i];
590
591                 if (!pj_stricmp2(&attr->name, "t38faxmaxbuffer")) {
592                         /* This is purposely left empty, it is unused */
593                 } else if (!pj_stricmp2(&attr->name, "t38maxbitrate") || !pj_stricmp2(&attr->name, "t38faxmaxrate")) {
594                         switch (pj_strtoul(&attr->value)) {
595                         case 14400:
596                                 state->their_parms.rate = AST_T38_RATE_14400;
597                                 break;
598                         case 12000:
599                                 state->their_parms.rate = AST_T38_RATE_12000;
600                                 break;
601                         case 9600:
602                                 state->their_parms.rate = AST_T38_RATE_9600;
603                                 break;
604                         case 7200:
605                                 state->their_parms.rate = AST_T38_RATE_7200;
606                                 break;
607                         case 4800:
608                                 state->their_parms.rate = AST_T38_RATE_4800;
609                                 break;
610                         case 2400:
611                                 state->their_parms.rate = AST_T38_RATE_2400;
612                                 break;
613                         }
614                 } else if (!pj_stricmp2(&attr->name, "t38faxversion")) {
615                         state->their_parms.version = pj_strtoul(&attr->value);
616                 } else if (!pj_stricmp2(&attr->name, "t38faxmaxdatagram") || !pj_stricmp2(&attr->name, "t38maxdatagram")) {
617                         if (!session->endpoint->media.t38.maxdatagram) {
618                                 ast_udptl_set_far_max_datagram(session_media->udptl, pj_strtoul(&attr->value));
619                         }
620                 } else if (!pj_stricmp2(&attr->name, "t38faxfillbitremoval")) {
621                         state->their_parms.fill_bit_removal = 1;
622                 } else if (!pj_stricmp2(&attr->name, "t38faxtranscodingmmr")) {
623                         state->their_parms.transcoding_mmr = 1;
624                 } else if (!pj_stricmp2(&attr->name, "t38faxtranscodingjbig")) {
625                         state->their_parms.transcoding_jbig = 1;
626                 } else if (!pj_stricmp2(&attr->name, "t38faxratemanagement")) {
627                         if (!pj_stricmp2(&attr->value, "localTCF")) {
628                                 state->their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
629                         } else if (!pj_stricmp2(&attr->value, "transferredTCF")) {
630                                 state->their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
631                         }
632                 } else if (!pj_stricmp2(&attr->name, "t38faxudpec")) {
633                         if (!pj_stricmp2(&attr->value, "t38UDPRedundancy")) {
634                                 ast_udptl_set_error_correction_scheme(session_media->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
635                         } else if (!pj_stricmp2(&attr->value, "t38UDPFEC")) {
636                                 ast_udptl_set_error_correction_scheme(session_media->udptl, UDPTL_ERROR_CORRECTION_FEC);
637                         } else {
638                                 ast_udptl_set_error_correction_scheme(session_media->udptl, UDPTL_ERROR_CORRECTION_NONE);
639                         }
640                 }
641
642         }
643 }
644
645 /*! \brief Function which defers an incoming media stream */
646 static enum ast_sip_session_sdp_stream_defer defer_incoming_sdp_stream(
647         struct ast_sip_session *session, struct ast_sip_session_media *session_media,
648         const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
649 {
650         struct t38_state *state;
651
652         if (!session->endpoint->media.t38.enabled) {
653                 ast_debug(3, "Not deferring incoming SDP stream: T.38 not enabled on %s\n", ast_channel_name(session->channel));
654                 return AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED;
655         }
656
657         if (t38_initialize_session(session, session_media)) {
658                 ast_debug(3, "Not deferring incoming SDP stream: Failed to initialize UDPTL on %s\n", ast_channel_name(session->channel));
659                 return AST_SIP_SESSION_SDP_DEFER_ERROR;
660         }
661
662         if (!(state = t38_state_get_or_alloc(session))) {
663                 return AST_SIP_SESSION_SDP_DEFER_ERROR;
664         }
665
666         t38_interpret_sdp(state, session, session_media, stream);
667
668         /* If they are initiating the re-invite we need to defer responding until later */
669         if (session->t38state == T38_DISABLED) {
670                 t38_change_state(session, session_media, state, T38_PEER_REINVITE);
671                 ast_debug(3, "Deferring incoming SDP stream on %s for peer re-invite\n", ast_channel_name(session->channel));
672                 return AST_SIP_SESSION_SDP_DEFER_NEEDED;
673         }
674
675         return AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED;
676 }
677
678 /*! \brief Function which negotiates an incoming media stream */
679 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
680                                          const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
681 {
682         struct t38_state *state;
683         char host[NI_MAXHOST];
684         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
685
686         if (!session->endpoint->media.t38.enabled) {
687                 ast_debug(3, "Declining; T.38 not enabled on session\n");
688                 return -1;
689         }
690
691         if (!(state = t38_state_get_or_alloc(session))) {
692                 return -1;
693         }
694
695         if ((session->t38state == T38_REJECTED) || (session->t38state == T38_DISABLED)) {
696                 ast_debug(3, "Declining; T.38 state is rejected or declined\n");
697                 t38_change_state(session, session_media, state, T38_DISABLED);
698                 return -1;
699         }
700
701         ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
702
703         /* Ensure that the address provided is valid */
704         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_INET) <= 0) {
705                 /* The provided host was actually invalid so we error out this negotiation */
706                 ast_debug(3, "Declining; provided host is invalid\n");
707                 return -1;
708         }
709
710         /* Check the address family to make sure it matches configured */
711         if ((ast_sockaddr_is_ipv6(addrs) && !session->endpoint->media.t38.ipv6) ||
712                 (ast_sockaddr_is_ipv4(addrs) && session->endpoint->media.t38.ipv6)) {
713                 /* The address does not match configured */
714                 ast_debug(3, "Declining, provided host does not match configured address family\n");
715                 return -1;
716         }
717
718         return 1;
719 }
720
721 /*! \brief Function which creates an outgoing stream */
722 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
723                                       struct pjmedia_sdp_session *sdp)
724 {
725         pj_pool_t *pool = session->inv_session->pool_prov;
726         static const pj_str_t STR_IN = { "IN", 2 };
727         static const pj_str_t STR_IP4 = { "IP4", 3};
728         static const pj_str_t STR_IP6 = { "IP6", 3};
729         static const pj_str_t STR_UDPTL = { "udptl", 5 };
730         static const pj_str_t STR_T38 = { "t38", 3 };
731         static const pj_str_t STR_TRANSFERREDTCF = { "transferredTCF", 14 };
732         static const pj_str_t STR_LOCALTCF = { "localTCF", 8 };
733         static const pj_str_t STR_T38UDPFEC = { "t38UDPFEC", 9 };
734         static const pj_str_t STR_T38UDPREDUNDANCY = { "t38UDPRedundancy", 16 };
735         struct t38_state *state;
736         pjmedia_sdp_media *media;
737         const char *hostip = NULL;
738         struct ast_sockaddr addr;
739         char tmp[512];
740         pj_str_t stmp;
741
742         if (!session->endpoint->media.t38.enabled) {
743                 ast_debug(3, "Not creating outgoing SDP stream: T.38 not enabled\n");
744                 return 1;
745         } else if ((session->t38state != T38_LOCAL_REINVITE) && (session->t38state != T38_PEER_REINVITE) &&
746                 (session->t38state != T38_ENABLED)) {
747                 ast_debug(3, "Not creating outgoing SDP stream: T.38 not enabled\n");
748                 return 1;
749         } else if (!(state = t38_state_get_or_alloc(session))) {
750                 return -1;
751         } else if (t38_initialize_session(session, session_media)) {
752                 ast_debug(3, "Not creating outgoing SDP stream: Failed to initialize T.38 session\n");
753                 return -1;
754         }
755
756         if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
757                 !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
758                 return -1;
759         }
760
761         media->desc.media = pj_str(session_media->stream_type);
762         media->desc.transport = STR_UDPTL;
763
764         if (ast_strlen_zero(session->endpoint->media.address)) {
765                 hostip = ast_sip_get_host_ip_string(session->endpoint->media.t38.ipv6 ? pj_AF_INET6() : pj_AF_INET());
766         } else {
767                 hostip = session->endpoint->media.address;
768         }
769
770         if (ast_strlen_zero(hostip)) {
771                 ast_debug(3, "Not creating outgoing SDP stream: no known host IP\n");
772                 return -1;
773         }
774
775         media->conn->net_type = STR_IN;
776         media->conn->addr_type = session->endpoint->media.t38.ipv6 ? STR_IP6 : STR_IP4;
777         pj_strdup2(pool, &media->conn->addr, hostip);
778         ast_udptl_get_us(session_media->udptl, &addr);
779         media->desc.port = (pj_uint16_t) ast_sockaddr_port(&addr);
780         media->desc.port_count = 1;
781         media->desc.fmt[media->desc.fmt_count++] = STR_T38;
782
783         snprintf(tmp, sizeof(tmp), "%u", state->our_parms.version);
784         media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxVersion", pj_cstr(&stmp, tmp));
785
786         snprintf(tmp, sizeof(tmp), "%u", t38_get_rate(state->our_parms.rate));
787         media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38MaxBitRate", pj_cstr(&stmp, tmp));
788
789         if (state->our_parms.fill_bit_removal) {
790                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxFillBitRemoval", NULL);
791         }
792
793         if (state->our_parms.transcoding_mmr) {
794                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxTranscodingMMR", NULL);
795         }
796
797         if (state->our_parms.transcoding_jbig) {
798                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxTranscodingJBIG", NULL);
799         }
800
801         switch (state->our_parms.rate_management) {
802         case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
803                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxRateManagement", &STR_TRANSFERREDTCF);
804                 break;
805         case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
806                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxRateManagement", &STR_LOCALTCF);
807                 break;
808         }
809
810         snprintf(tmp, sizeof(tmp), "%u", ast_udptl_get_local_max_datagram(session_media->udptl));
811         media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxMaxDatagram", pj_cstr(&stmp, tmp));
812
813         switch (ast_udptl_get_error_correction_scheme(session_media->udptl)) {
814         case UDPTL_ERROR_CORRECTION_NONE:
815                 break;
816         case UDPTL_ERROR_CORRECTION_FEC:
817                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxUdpEC", &STR_T38UDPFEC);
818                 break;
819         case UDPTL_ERROR_CORRECTION_REDUNDANCY:
820                 media->attr[media->attr_count++] = pjmedia_sdp_attr_create(pool, "T38FaxUdpEC", &STR_T38UDPREDUNDANCY);
821                 break;
822         }
823
824         sdp->media[sdp->media_count++] = media;
825
826         return 1;
827 }
828
829 /*! \brief Function which applies a negotiated stream */
830 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
831                                        const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
832                                        const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
833 {
834         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
835         char host[NI_MAXHOST];
836         struct t38_state *state;
837
838         if (!session_media->udptl) {
839                 ast_debug(3, "Not applying negotiated SDP stream: no UDTPL session\n");
840                 return 0;
841         }
842
843         if (!(state = t38_state_get_or_alloc(session))) {
844                 return -1;
845         }
846
847         ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
848
849         /* Ensure that the address provided is valid */
850         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
851                 /* The provided host was actually invalid so we error out this negotiation */
852                 ast_debug(3, "Not applying negotiated SDP stream: failed to resolve remote stream host\n");
853                 return -1;
854         }
855
856         ast_sockaddr_set_port(addrs, remote_stream->desc.port);
857         ast_udptl_set_peer(session_media->udptl, addrs);
858
859         t38_interpret_sdp(state, session, session_media, remote_stream);
860
861         return 0;
862 }
863
864 /*! \brief Function which updates the media stream with external media address, if applicable */
865 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
866 {
867         RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);
868         char host[NI_MAXHOST];
869         struct ast_sockaddr addr = { { 0, } };
870
871         /* If the stream has been rejected there will be no connection line */
872         if (!stream->conn || !transport_state) {
873                 return;
874         }
875
876         ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
877         ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
878
879         /* Is the address within the SDP inside the same network? */
880         if (transport_state->localnet
881                 && ast_apply_ha(transport_state->localnet, &addr) == AST_SENSE_ALLOW) {
882                 return;
883         }
884         ast_debug(5, "Setting media address to %s\n", transport->external_media_address);
885         pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
886 }
887
888 /*! \brief Function which destroys the UDPTL instance when session ends */
889 static void stream_destroy(struct ast_sip_session_media *session_media)
890 {
891         if (session_media->udptl) {
892                 ast_udptl_destroy(session_media->udptl);
893         }
894         session_media->udptl = NULL;
895 }
896
897 /*! \brief SDP handler for 'image' media stream */
898 static struct ast_sip_session_sdp_handler image_sdp_handler = {
899         .id = "image",
900         .defer_incoming_sdp_stream = defer_incoming_sdp_stream,
901         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
902         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
903         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
904         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
905         .stream_destroy = stream_destroy,
906 };
907
908 /*! \brief Unloads the SIP T.38 module from Asterisk */
909 static int unload_module(void)
910 {
911         ast_sip_session_unregister_sdp_handler(&image_sdp_handler, "image");
912         ast_sip_session_unregister_supplement(&t38_supplement);
913
914         return 0;
915 }
916
917 /*!
918  * \brief Load the module
919  *
920  * Module loading including tests for configuration or dependencies.
921  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
922  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
923  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
924  * configuration file or other non-critical problem return
925  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
926  */
927 static int load_module(void)
928 {
929         CHECK_PJSIP_SESSION_MODULE_LOADED();
930
931         if (ast_check_ipv6()) {
932                 ast_sockaddr_parse(&address, "::", 0);
933         } else {
934                 ast_sockaddr_parse(&address, "0.0.0.0", 0);
935         }
936
937         if (ast_sip_session_register_supplement(&t38_supplement)) {
938                 ast_log(LOG_ERROR, "Unable to register T.38 session supplement\n");
939                 goto end;
940         }
941
942         if (ast_sip_session_register_sdp_handler(&image_sdp_handler, "image")) {
943                 ast_log(LOG_ERROR, "Unable to register SDP handler for image stream type\n");
944                 goto end;
945         }
946
947         return AST_MODULE_LOAD_SUCCESS;
948 end:
949         unload_module();
950
951         return AST_MODULE_LOAD_DECLINE;
952 }
953
954 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP T.38 UDPTL Support",
955         .support_level = AST_MODULE_SUPPORT_CORE,
956         .load = load_module,
957         .unload = unload_module,
958         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
959 );