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