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