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