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