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