Fix stuck channel in ARI through the introduction of synchronous bridge actions.
[asterisk/asterisk.git] / res / res_fax.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008-2009, Digium, Inc.
5  *
6  * Dwayne M. Hubbard <dhubbard@digium.com>
7  * Kevin P. Fleming <kpfleming@digium.com>
8  * Matthew Nicholson <mnicholson@digium.com>
9  *
10  * Initial T.38-gateway code
11  * 2008, Daniel Ferenci <daniel.ferenci@nethemba.com>
12  * Created by Nethemba s.r.o. http://www.nethemba.com
13  * Sponsored by IPEX a.s. http://www.ipex.cz
14  *
15  * T.38-gateway integration into asterisk app_fax and rework
16  * 2008-2011, Gregory Hinton Nietsky <gregory@distrotech.co.za>
17  * dns Telecom http://www.dnstelecom.co.za
18  *
19  * Modified to make T.38-gateway compatible with Asterisk 1.6.2
20  * 2010, Anton Verevkin <mymail@verevkin.it>
21  * ViaNetTV http://www.vianettv.com
22  *
23  * Modified to make T.38-gateway work
24  * 2010, Klaus Darilion, IPCom GmbH, www.ipcom.at
25  *
26  * See http://www.asterisk.org for more information about
27  * the Asterisk project. Please do not directly contact
28  * any of the maintainers of this project for assistance;
29  * the project provides a web site, mailing lists and IRC
30  * channels for your use.
31  *
32  * This program is free software, distributed under the terms of
33  * the GNU General Public License Version 2. See the LICENSE file
34  * at the top of the source tree.
35  */
36
37 /*** MODULEINFO
38         <conflict>app_fax</conflict>
39         <support_level>core</support_level>
40 ***/
41
42 /*! \file
43  *
44  * \brief Generic FAX Resource for FAX technology resource modules
45  *
46  * \author Dwayne M. Hubbard <dhubbard@digium.com>
47  * \author Kevin P. Fleming <kpfleming@digium.com>
48  * \author Matthew Nicholson <mnicholson@digium.com>
49  * \author Gregory H. Nietsky  <gregory@distrotech.co.za>
50  *
51  * A generic FAX resource module that provides SendFAX and ReceiveFAX applications.
52  * This module requires FAX technology modules, like res_fax_spandsp, to register with it
53  * so it can use the technology modules to perform the actual FAX transmissions.
54  * \ingroup applications
55  */
56
57 /*! \li \ref res_fax.c uses the configuration file \ref res_fax.conf
58  * \addtogroup configuration_file Configuration Files
59  */
60
61 /*!
62  * \page res_fax.conf res_fax.conf
63  * \verbinclude res_fax.conf.sample
64  */
65
66 #include "asterisk.h"
67
68 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
69
70 #include "asterisk/io.h"
71 #include "asterisk/file.h"
72 #include "asterisk/logger.h"
73 #include "asterisk/module.h"
74 #include "asterisk/app.h"
75 #include "asterisk/lock.h"
76 #include "asterisk/options.h"
77 #include "asterisk/strings.h"
78 #include "asterisk/cli.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/config.h"
81 #include "asterisk/astobj2.h"
82 #include "asterisk/res_fax.h"
83 #include "asterisk/file.h"
84 #include "asterisk/channel.h"
85 #include "asterisk/pbx.h"
86 #include "asterisk/dsp.h"
87 #include "asterisk/indications.h"
88 #include "asterisk/ast_version.h"
89 #include "asterisk/translate.h"
90 #include "asterisk/stasis.h"
91 #include "asterisk/stasis_channels.h"
92
93 /*** DOCUMENTATION
94         <application name="ReceiveFAX" language="en_US" module="res_fax">
95                 <synopsis>
96                         Receive a FAX and save as a TIFF/F file.
97                 </synopsis>
98                 <syntax>
99                         <parameter name="filename" required="true" />
100                         <parameter name="options">
101                                 <optionlist>
102                                         <option name="d">
103                                                 <para>Enable FAX debugging.</para>
104                                         </option>
105                                         <option name="f">
106                                                 <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
107                                         </option>
108                                         <option name="F">
109                                                 <para>Force usage of audio mode on T.38 capable channels.</para>
110                                         </option>
111                                         <option name="s">
112                                                 <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
113                                         </option>
114                                 </optionlist>
115                         </parameter>
116                 </syntax>
117                 <description>
118                         <para>This application is provided by res_fax, which is a FAX technology agnostic module
119                         that utilizes FAX technology resource modules to complete a FAX transmission.</para>
120                         <para>Session arguments can be set by the FAXOPT function and to check results of the ReceiveFax() application.</para>
121                 </description>
122                 <see-also>
123                         <ref type="function">FAXOPT</ref>
124                 </see-also>
125         </application>
126         <application name="SendFAX" language="en_US" module="res_fax">
127                 <synopsis>
128                         Sends a specified TIFF/F file as a FAX.
129                 </synopsis>
130                 <syntax>
131                         <parameter name="filename" required="true" argsep="&amp;">
132                                 <argument name="filename2" multiple="true">
133                                         <para>TIFF file to send as a FAX.</para>
134                                 </argument>
135                         </parameter>
136                         <parameter name="options">
137                                 <optionlist>
138                                         <option name="d">
139                                                 <para>Enable FAX debugging.</para>
140                                         </option>
141                                         <option name="f">
142                                                 <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
143                                         </option>
144                                         <option name="F">
145                                                 <para>Force usage of audio mode on T.38 capable channels.</para>
146                                         </option>
147                                         <option name="s">
148                                                 <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
149                                         </option>
150                                         <option name="z">
151                                                 <para>Initiate a T.38 reinvite on the channel if the remote end does not.</para>
152                                         </option>
153                                 </optionlist>
154                         </parameter>
155                 </syntax>
156                 <description>
157                         <para>This application is provided by res_fax, which is a FAX technology agnostic module
158                         that utilizes FAX technology resource modules to complete a FAX transmission.</para>
159                         <para>Session arguments can be set by the FAXOPT function and to check results of the SendFax() application.</para>
160                 </description>
161                 <see-also>
162                         <ref type="function">FAXOPT</ref>
163                 </see-also>
164         </application>
165         <function name="FAXOPT" language="en_US" module="res_fax">
166                 <synopsis>
167                         Gets/sets various pieces of information about a fax session.
168                 </synopsis>
169                 <syntax>
170                         <parameter name="item" required="true">
171                                 <enumlist>
172                                         <enum name="ecm">
173                                                 <para>R/W Error Correction Mode (ECM) enable with 'yes', disable with 'no'.</para>
174                                         </enum>
175                                         <enum name="error">
176                                                 <para>R/O FAX transmission error code upon failure.</para>
177                                         </enum>
178                                         <enum name="filename">
179                                                 <para>R/O Filename of the first file of the FAX transmission.</para>
180                                         </enum>
181                                         <enum name="filenames">
182                                                 <para>R/O Filenames of all of the files in the FAX transmission (comma separated).</para>
183                                         </enum>
184                                         <enum name="headerinfo">
185                                                 <para>R/W FAX header information.</para>
186                                         </enum>
187                                         <enum name="localstationid">
188                                                 <para>R/W Local Station Identification.</para>
189                                         </enum>
190                                         <enum name="minrate">
191                                                 <para>R/W Minimum transfer rate set before transmission.</para>
192                                         </enum>
193                                         <enum name="maxrate">
194                                                 <para>R/W Maximum transfer rate set before transmission.</para>
195                                         </enum>
196                                         <enum name="modem">
197                                                 <para>R/W Modem type (v17/v27/v29).</para>
198                                         </enum>
199                                         <enum name="gateway">
200                                                 <para>R/W T38 fax gateway, with optional fax activity timeout in seconds (yes[,timeout]/no)</para>
201                                         </enum>
202                                         <enum name="faxdetect">
203                                                 <para>R/W Enable FAX detect with optional timeout in seconds (yes,t38,cng[,timeout]/no)</para>
204                                         </enum>
205                                         <enum name="pages">
206                                                 <para>R/O Number of pages transferred.</para>
207                                         </enum>
208                                         <enum name="rate">
209                                                 <para>R/O Negotiated transmission rate.</para>
210                                         </enum>
211                                         <enum name="remotestationid">
212                                                 <para>R/O Remote Station Identification after transmission.</para>
213                                         </enum>
214                                         <enum name="resolution">
215                                                 <para>R/O Negotiated image resolution after transmission.</para>
216                                         </enum>
217                                         <enum name="sessionid">
218                                                 <para>R/O Session ID of the FAX transmission.</para>
219                                         </enum>
220                                         <enum name="status">
221                                                 <para>R/O Result Status of the FAX transmission.</para>
222                                         </enum>
223                                         <enum name="statusstr">
224                                                 <para>R/O Verbose Result Status of the FAX transmission.</para>
225                                         </enum>
226                                 </enumlist>
227                         </parameter>
228                 </syntax>
229                 <description>
230                         <para>FAXOPT can be used to override the settings for a FAX session listed in <filename>res_fax.conf</filename>,
231                         it can also be used to retreive information about a FAX session that has finished eg. pages/status.</para>
232                 </description>
233                 <see-also>
234                         <ref type="application">ReceiveFax</ref>
235                         <ref type="application">SendFax</ref>
236                 </see-also>
237         </function>
238 ***/
239
240 static const char app_receivefax[] = "ReceiveFAX";
241 static const char app_sendfax[] = "SendFAX";
242
243 struct debug_info_history {
244         unsigned int consec_frames;
245         unsigned int consec_ms;
246         unsigned char silence;
247 };
248
249 struct ast_fax_debug_info {
250         struct timeval base_tv;
251         struct debug_info_history c2s, s2c;
252         struct ast_dsp *dsp;
253 };
254
255 /*! \brief used for gateway framehook */
256 struct fax_gateway {
257         /*! \brief FAX Session */
258         struct ast_fax_session *s;
259         struct ast_fax_session *peer_v21_session;
260         struct ast_fax_session *chan_v21_session;
261         /*! \brief reserved fax session token */
262         struct ast_fax_tech_token *token;
263         /*! \brief the start of our timeout counter */
264         struct timeval timeout_start;
265         /*! \brief framehook used in gateway mode */
266         int framehook;
267         /*! \brief bridged */
268         int bridged:1;
269         /*! \brief 1 if a v21 preamble has been detected */
270         int detected_v21:1;
271         /*! \brief a flag to track the state of our negotiation */
272         enum ast_t38_state t38_state;
273         /*! \brief original audio formats */
274         struct ast_format chan_read_format;
275         struct ast_format chan_write_format;
276         struct ast_format peer_read_format;
277         struct ast_format peer_write_format;
278 };
279
280 /*! \brief used for fax detect framehook */
281 struct fax_detect {
282         /*! \brief the start of our timeout counter */
283         struct timeval timeout_start;
284         /*! \brief faxdetect timeout */
285         int timeout;
286         /*! \brief DSP Processor */
287         struct ast_dsp *dsp;
288         /*! \brief original audio formats */
289         struct ast_format orig_format;
290         /*! \brief fax session details */
291         struct ast_fax_session_details *details;
292         /*! \brief mode */
293         int flags;
294 };
295
296 /*! \brief FAX Detect flags */
297 #define FAX_DETECT_MODE_CNG     (1 << 0)
298 #define FAX_DETECT_MODE_T38     (1 << 1)
299 #define FAX_DETECT_MODE_BOTH    (FAX_DETECT_MODE_CNG | FAX_DETECT_MODE_T38)
300
301 static int fax_logger_level = -1;
302
303 /*! \brief maximum buckets for res_fax ao2 containers */
304 #define FAX_MAXBUCKETS 10
305
306 #define RES_FAX_TIMEOUT 10000
307 #define FAX_GATEWAY_TIMEOUT RES_FAX_TIMEOUT
308
309 /*! \brief The faxregistry is used to manage information and statistics for all FAX sessions. */
310 static struct {
311         /*! The number of active FAX sessions */
312         int active_sessions;
313         /*! The number of reserved FAX sessions */
314         int reserved_sessions;
315         /*! active sessions are astobj2 objects */
316         struct ao2_container *container;
317         /*! Total number of Tx FAX attempts */
318         int fax_tx_attempts;
319         /*! Total number of Rx FAX attempts */
320         int fax_rx_attempts;
321         /*! Number of successful FAX transmissions */
322         int fax_complete;
323         /*! Number of failed FAX transmissions */
324         int fax_failures;
325         /*! the next unique session name */
326         int nextsessionname;
327 } faxregistry;
328
329 /*! \brief registered FAX technology modules are put into this list */
330 struct fax_module {
331         const struct ast_fax_tech *tech;
332         AST_RWLIST_ENTRY(fax_module) list;
333 };
334 static AST_RWLIST_HEAD_STATIC(faxmodules, fax_module);
335
336 #define RES_FAX_MINRATE 4800
337 #define RES_FAX_MAXRATE 14400
338 #define RES_FAX_STATUSEVENTS 0
339 #define RES_FAX_MODEM (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29)
340
341 struct fax_options {
342         enum ast_fax_modems modems;
343         uint32_t statusevents:1;
344         uint32_t ecm:1;
345         unsigned int minrate;
346         unsigned int maxrate;
347 };
348
349 static struct fax_options general_options;
350
351 static const struct fax_options default_options = {
352         .minrate = RES_FAX_MINRATE,
353         .maxrate = RES_FAX_MAXRATE,
354         .statusevents = RES_FAX_STATUSEVENTS,
355         .modems = RES_FAX_MODEM,
356         .ecm = AST_FAX_OPTFLAG_TRUE,
357 };
358
359 AST_RWLOCK_DEFINE_STATIC(options_lock);
360
361 static void get_general_options(struct fax_options* options);
362 static void set_general_options(const struct fax_options* options);
363
364 static const char *config = "res_fax.conf";
365
366 static int global_fax_debug = 0;
367
368 enum {
369         OPT_CALLEDMODE  = (1 << 0),
370         OPT_CALLERMODE  = (1 << 1),
371         OPT_DEBUG       = (1 << 2),
372         OPT_STATUS      = (1 << 3),
373         OPT_ALLOWAUDIO  = (1 << 5),
374         OPT_REQUEST_T38 = (1 << 6),
375         OPT_FORCE_AUDIO = (1 << 7),
376 };
377
378 AST_APP_OPTIONS(fax_exec_options, BEGIN_OPTIONS
379         AST_APP_OPTION('a', OPT_CALLEDMODE),
380         AST_APP_OPTION('c', OPT_CALLERMODE),
381         AST_APP_OPTION('d', OPT_DEBUG),
382         AST_APP_OPTION('f', OPT_ALLOWAUDIO),
383         AST_APP_OPTION('F', OPT_FORCE_AUDIO),
384         AST_APP_OPTION('s', OPT_STATUS),
385         AST_APP_OPTION('z', OPT_REQUEST_T38),
386 END_OPTIONS);
387
388 static void debug_check_frame_for_silence(struct ast_fax_session *s, unsigned int c2s, struct ast_frame *frame)
389 {
390         struct debug_info_history *history = c2s ? &s->debug_info->c2s : &s->debug_info->s2c;
391         int dspsilence;
392         unsigned int last_consec_frames, last_consec_ms;
393         unsigned char wassil;
394         struct timeval diff;
395
396         diff = ast_tvsub(ast_tvnow(), s->debug_info->base_tv);
397
398         ast_dsp_reset(s->debug_info->dsp);
399         ast_dsp_silence(s->debug_info->dsp, frame, &dspsilence);
400
401         wassil = history->silence;
402         history->silence = (dspsilence != 0) ? 1 : 0;
403         if (history->silence != wassil) {
404                 last_consec_frames = history->consec_frames;
405                 last_consec_ms = history->consec_ms;
406                 history->consec_frames = 0;
407                 history->consec_ms = 0;
408
409                 if ((last_consec_frames != 0)) {
410                         ast_verb(6, "Channel '%s' fax session '%d', [ %.3ld.%.6ld ], %s sent %d frames (%d ms) of %s.\n",
411                                  s->channame, s->id, (long) diff.tv_sec, (long int) diff.tv_usec,
412                                  (c2s) ? "channel" : "stack", last_consec_frames, last_consec_ms,
413                                  (wassil) ? "silence" : "energy");
414                 }
415         }
416
417         history->consec_frames++;
418         history->consec_ms += (frame->samples / 8);
419 }
420
421 static void destroy_callback(void *data)
422 {
423         if (data) {
424                 ao2_ref(data, -1);
425         }
426 }
427
428 static const struct ast_datastore_info fax_datastore = {
429         .type = "res_fax",
430         .destroy = destroy_callback,
431 };
432
433 /*! \brief returns a reference counted pointer to a fax datastore, if it exists */
434 static struct ast_fax_session_details *find_details(struct ast_channel *chan)
435 {
436         struct ast_fax_session_details *details;
437         struct ast_datastore *datastore;
438
439         ast_channel_lock(chan);
440         if (!(datastore = ast_channel_datastore_find(chan, &fax_datastore, NULL))) {
441                 ast_channel_unlock(chan);
442                 return NULL;
443         }
444         if (!(details = datastore->data)) {
445                 ast_log(LOG_WARNING, "Huh?  channel '%s' has a FAX datastore without data!\n", ast_channel_name(chan));
446                 ast_channel_unlock(chan);
447                 return NULL;
448         }
449         ao2_ref(details, 1);
450         ast_channel_unlock(chan);
451
452         return details;
453 }
454
455 /*! \brief destroy a FAX session details structure */
456 static void destroy_session_details(void *details)
457 {
458         struct ast_fax_session_details *d = details;
459         struct ast_fax_document *doc;
460
461         while ((doc = AST_LIST_REMOVE_HEAD(&d->documents, next))) {
462                 ast_free(doc);
463         }
464         ast_string_field_free_memory(d);
465 }
466
467 /*! \brief create a FAX session details structure */
468 static struct ast_fax_session_details *session_details_new(void)
469 {
470         struct ast_fax_session_details *d;
471         struct fax_options options;
472
473         if (!(d = ao2_alloc(sizeof(*d), destroy_session_details))) {
474                 return NULL;
475         }
476
477         if (ast_string_field_init(d, 512)) {
478                 ao2_ref(d, -1);
479                 return NULL;
480         }
481
482         get_general_options(&options);
483
484         AST_LIST_HEAD_INIT_NOLOCK(&d->documents);
485
486         /* These options need to be set to the configured default and may be overridden by
487          * SendFAX, ReceiveFAX, or FAXOPT */
488         d->option.request_t38 = AST_FAX_OPTFLAG_FALSE;
489         d->option.send_cng = AST_FAX_OPTFLAG_FALSE;
490         d->option.send_ced = AST_FAX_OPTFLAG_FALSE;
491         d->option.ecm = options.ecm;
492         d->option.statusevents = options.statusevents;
493         d->modems = options.modems;
494         d->minrate = options.minrate;
495         d->maxrate = options.maxrate;
496         d->gateway_id = -1;
497         d->faxdetect_id = -1;
498         d->gateway_timeout = 0;
499
500         return d;
501 }
502
503 static struct ast_control_t38_parameters our_t38_parameters = {
504         .version = 0,
505         .max_ifp = 400,
506         .rate = AST_T38_RATE_14400,
507         .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
508 };
509
510 static void t38_parameters_ast_to_fax(struct ast_fax_t38_parameters *dst, const struct ast_control_t38_parameters *src)
511 {
512         dst->version = src->version;
513         dst->max_ifp = src->max_ifp;
514         dst->rate = src->rate;
515         dst->rate_management = src->rate_management;
516         dst->fill_bit_removal = src->fill_bit_removal;
517         dst->transcoding_mmr = src->transcoding_mmr;
518         dst->transcoding_jbig = src->transcoding_jbig;
519 }
520
521 static void t38_parameters_fax_to_ast(struct ast_control_t38_parameters *dst, const struct ast_fax_t38_parameters *src)
522 {
523         dst->version = src->version;
524         dst->max_ifp = src->max_ifp;
525         dst->rate = src->rate;
526         dst->rate_management = src->rate_management;
527         dst->fill_bit_removal = src->fill_bit_removal;
528         dst->transcoding_mmr = src->transcoding_mmr;
529         dst->transcoding_jbig = src->transcoding_jbig;
530 }
531
532 /*! \brief returns a reference counted details structure from the channel's fax datastore.  If the datastore
533  * does not exist it will be created */
534 static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan)
535 {
536         struct ast_fax_session_details *details;
537         struct ast_datastore *datastore;
538
539         if ((details = find_details(chan))) {
540                 return details;
541         }
542         /* channel does not have one so we must create one */
543         if (!(details = session_details_new())) {
544                 ast_log(LOG_WARNING, "channel '%s' can't get a FAX details structure for the datastore!\n", ast_channel_name(chan));
545                 return NULL;
546         }
547         if (!(datastore = ast_datastore_alloc(&fax_datastore, NULL))) {
548                 ao2_ref(details, -1);
549                 ast_log(LOG_WARNING, "channel '%s' can't get a datastore!\n", ast_channel_name(chan));
550                 return NULL;
551         }
552         /* add the datastore to the channel and increment the refcount */
553         datastore->data = details;
554
555         /* initialize default T.38 parameters */
556         t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
557         t38_parameters_ast_to_fax(&details->their_t38_parameters, &our_t38_parameters);
558
559         ao2_ref(details, 1);
560         ast_channel_lock(chan);
561         ast_channel_datastore_add(chan, datastore);
562         ast_channel_unlock(chan);
563         return details;
564 }
565
566 unsigned int ast_fax_maxrate(void)
567 {
568         struct fax_options options;
569         get_general_options(&options);
570
571         return options.maxrate;
572 }
573
574 unsigned int ast_fax_minrate(void)
575 {
576         struct fax_options options;
577         get_general_options(&options);
578
579         return options.minrate;
580 }
581
582 static int update_modem_bits(enum ast_fax_modems *bits, const char *value)
583 {
584         char *m[5], *tok, *v = (char *)value;
585         int i = 0, j;
586
587         if (!strchr(v, ',')) {
588                 m[i++] = v;
589                 m[i] = NULL;
590         } else {
591                 tok = strtok(v, ", ");
592                 while (tok && (i < 5)) {
593                         m[i++] = tok;
594                         tok = strtok(NULL, ", ");
595                 }
596                 m[i] = NULL;
597         }
598
599         *bits = 0;
600         for (j = 0; j < i; j++) {
601                 if (!strcasecmp(m[j], "v17")) {
602                         *bits |= AST_FAX_MODEM_V17;
603                 } else if (!strcasecmp(m[j], "v27")) {
604                         *bits |= AST_FAX_MODEM_V27;
605                 } else if (!strcasecmp(m[j], "v29")) {
606                         *bits |= AST_FAX_MODEM_V29;
607                 } else if (!strcasecmp(m[j], "v34")) {
608                         *bits |= AST_FAX_MODEM_V34;
609                 } else {
610                         ast_log(LOG_WARNING, "ignoring invalid modem setting: '%s', valid options {v17 | v27 | v29 | v34}\n", m[j]);
611                 }
612         }
613         return 0;
614 }
615 static char *ast_fax_caps_to_str(enum ast_fax_capabilities caps, char *buf, size_t bufsize)
616 {
617         char *out = buf;
618         size_t size = bufsize;
619         int first = 1;
620
621         if (caps & AST_FAX_TECH_SEND) {
622                 if (!first) {
623                         ast_build_string(&buf, &size, ",");
624                 }
625                 ast_build_string(&buf, &size, "SEND");
626                 first = 0;
627         }
628         if (caps & AST_FAX_TECH_RECEIVE) {
629                 if (!first) {
630                         ast_build_string(&buf, &size, ",");
631                 }
632                 ast_build_string(&buf, &size, "RECEIVE");
633                 first = 0;
634         }
635         if (caps & AST_FAX_TECH_AUDIO) {
636                 if (!first) {
637                         ast_build_string(&buf, &size, ",");
638                 }
639                 ast_build_string(&buf, &size, "AUDIO");
640                 first = 0;
641         }
642         if (caps & AST_FAX_TECH_T38) {
643                 if (!first) {
644                         ast_build_string(&buf, &size, ",");
645                 }
646                 ast_build_string(&buf, &size, "T38");
647                 first = 0;
648         }
649         if (caps & AST_FAX_TECH_MULTI_DOC) {
650                 if (!first) {
651                         ast_build_string(&buf, &size, ",");
652                 }
653                 ast_build_string(&buf, &size, "MULTI_DOC");
654                 first = 0;
655         }
656         if (caps & AST_FAX_TECH_GATEWAY) {
657                 if (!first) {
658                         ast_build_string(&buf, &size, ",");
659                 }
660                 ast_build_string(&buf, &size, "GATEWAY");
661                 first = 0;
662         }
663         if (caps & AST_FAX_TECH_V21_DETECT) {
664                 if (!first) {
665                         ast_build_string(&buf, &size, ",");
666                 }
667                 ast_build_string(&buf, &size, "V21");
668                 first = 0;
669         }
670
671         return out;
672 }
673
674 static int ast_fax_modem_to_str(enum ast_fax_modems bits, char *tbuf, size_t bufsize)
675 {
676         int count = 0;
677
678         if (bits & AST_FAX_MODEM_V17) {
679                 strcat(tbuf, "V17");
680                 count++;
681         }
682         if (bits & AST_FAX_MODEM_V27) {
683                 if (count) {
684                         strcat(tbuf, ",");
685                 }
686                 strcat(tbuf, "V27");
687                 count++;
688         }
689         if (bits & AST_FAX_MODEM_V29) {
690                 if (count) {
691                         strcat(tbuf, ",");
692                 }
693                 strcat(tbuf, "V29");
694                 count++;
695         }
696         if (bits & AST_FAX_MODEM_V34) {
697                 if (count) {
698                         strcat(tbuf, ",");
699                 }
700                 strcat(tbuf, "V34");
701                 count++;
702         }
703
704         return 0;
705 }
706
707 static int check_modem_rate(enum ast_fax_modems modems, unsigned int rate)
708 {
709         switch (rate) {
710         case 2400:
711                 if (!(modems & (AST_FAX_MODEM_V34))) {
712                         return 1;
713                 }
714                 break;
715         case 4800:
716                 if (!(modems & (AST_FAX_MODEM_V27 | AST_FAX_MODEM_V34))) {
717                         return 1;
718                 }
719                 break;
720         case 7200:
721                 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
722                         return 1;
723                 }
724                 break;
725         case 9600:
726                 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
727                         return 1;
728                 }
729                 break;
730         case 12000:
731         case 14400:
732                 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V34))) {
733                         return 1;
734                 }
735                 break;
736         case 28800:
737         case 33600:
738                 if (!(modems & AST_FAX_MODEM_V34)) {
739                         return 1;
740                 }
741                 break;
742         default:
743                 /* this should never happen */
744                 return 1;
745         }
746
747         return 0;
748 }
749
750 /*! \brief register a FAX technology module */
751 int ast_fax_tech_register(struct ast_fax_tech *tech)
752 {
753         struct fax_module *fax;
754
755         if (!(fax = ast_calloc(1, sizeof(*fax)))) {
756                 return -1;
757         }
758         fax->tech = tech;
759         AST_RWLIST_WRLOCK(&faxmodules);
760         AST_RWLIST_INSERT_TAIL(&faxmodules, fax, list);
761         AST_RWLIST_UNLOCK(&faxmodules);
762         ast_module_ref(ast_module_info->self);
763
764         ast_verb(3, "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
765
766         return 0;
767 }
768
769 /*! \brief unregister a FAX technology module */
770 void ast_fax_tech_unregister(struct ast_fax_tech *tech)
771 {
772         struct fax_module *fax;
773
774         ast_verb(3, "Unregistering FAX module type '%s'\n", tech->type);
775
776         AST_RWLIST_WRLOCK(&faxmodules);
777         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
778                 if (fax->tech != tech) {
779                         continue;
780                 }
781                 AST_RWLIST_REMOVE_CURRENT(list);
782                 ast_module_unref(ast_module_info->self);
783                 ast_free(fax);
784                 ast_verb(4, "Unregistered FAX module type '%s'\n", tech->type);
785                 break;
786         }
787         AST_RWLIST_TRAVERSE_SAFE_END;
788         AST_RWLIST_UNLOCK(&faxmodules);
789 }
790
791 /*! \brief convert a ast_fax_state to a string */
792 const char *ast_fax_state_to_str(enum ast_fax_state state)
793 {
794         switch (state) {
795         case AST_FAX_STATE_UNINITIALIZED:
796                 return "Uninitialized";
797         case AST_FAX_STATE_INITIALIZED:
798                 return "Initialized";
799         case AST_FAX_STATE_OPEN:
800                 return "Open";
801         case AST_FAX_STATE_ACTIVE:
802                 return "Active";
803         case AST_FAX_STATE_COMPLETE:
804                 return "Complete";
805         case AST_FAX_STATE_RESERVED:
806                 return "Reserved";
807         case AST_FAX_STATE_INACTIVE:
808                 return "Inactive";
809         default:
810                 ast_log(LOG_WARNING, "unhandled FAX state: %d\n", state);
811                 return "Unknown";
812         }
813 }
814
815 void ast_fax_log(int level, const char *file, const int line, const char *function, const char *msg)
816 {
817         if (fax_logger_level != -1) {
818                 ast_log_dynamic_level(fax_logger_level, "%s", msg);
819         } else {
820                 ast_log(level, file, line, function, "%s", msg);
821         }
822 }
823
824 /*! \brief convert a rate string to a rate */
825 static unsigned int fax_rate_str_to_int(const char *ratestr)
826 {
827         int rate;
828
829         if (sscanf(ratestr, "%d", &rate) != 1) {
830                 ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
831                 return 0;
832         }
833         switch (rate) {
834         case 2400:
835         case 4800:
836         case 7200:
837         case 9600:
838         case 12000:
839         case 14400:
840         case 28800:
841         case 33600:
842                 return rate;
843         default:
844                 ast_log(LOG_WARNING, "ignoring invalid rate '%s'.  Valid options are {2400 | 4800 | 7200 | 9600 | 12000 | 14400 | 28800 | 33600}\n", ratestr);
845                 return 0;
846         }
847 }
848
849 /*! \brief Release a session token.
850  * \param s a session returned from fax_session_reserve()
851  * \param token a token generated from fax_session_reserve()
852  *
853  * This function releases the given token and marks the given session as no
854  * longer reserved. It is safe to call on a session that is not actually
855  * reserved and with a NULL token. This is so that sessions returned by
856  * technologies that do not support reserved sessions don't require extra logic
857  * to handle.
858  *
859  * \note This function DOES NOT release the given fax session, only the given
860  * token.
861  */
862 static void fax_session_release(struct ast_fax_session *s, struct ast_fax_tech_token *token)
863 {
864         if (token) {
865                 s->tech->release_token(token);
866         }
867
868         if (s->state == AST_FAX_STATE_RESERVED) {
869                 ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
870                 s->state = AST_FAX_STATE_INACTIVE;
871         }
872 }
873
874 /*! \brief destroy a FAX session structure */
875 static void destroy_session(void *session)
876 {
877         struct ast_fax_session *s = session;
878
879         if (s->tech) {
880                 fax_session_release(s, NULL);
881                 if (s->tech_pvt) {
882                         s->tech->destroy_session(s);
883                 }
884                 ast_module_unref(s->tech->module);
885         }
886
887         if (s->details) {
888                 if (s->details->caps & AST_FAX_TECH_GATEWAY) {
889                         s->details->caps &= ~AST_FAX_TECH_GATEWAY;
890                 }
891                 ao2_ref(s->details, -1);
892         }
893
894         if (s->debug_info) {
895                 ast_dsp_free(s->debug_info->dsp);
896                 ast_free(s->debug_info);
897         }
898
899         if (s->smoother) {
900                 ast_smoother_free(s->smoother);
901         }
902
903         if (s->state != AST_FAX_STATE_INACTIVE) {
904                 ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
905         }
906
907         ast_free(s->channame);
908         ast_free(s->chan_uniqueid);
909 }
910
911 /*! \brief Reserve a fax session.
912  * \param details the fax session details
913  * \param token a pointer to a place to store a token to be passed to fax_session_new() later
914  *
915  * This function reserves a fax session for use later. If the selected fax
916  * technology does not support reserving sessions a session will still be
917  * returned but token will not be set.
918  *
919  * \note The reference returned by this function does not get consumed by
920  * fax_session_new() and must always be dereferenced separately.
921  *
922  * \return NULL or an uninitialized and possibly reserved session
923  */
924 static struct ast_fax_session *fax_session_reserve(struct ast_fax_session_details *details, struct ast_fax_tech_token **token)
925 {
926         struct ast_fax_session *s;
927         struct fax_module *faxmod;
928
929         if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
930                 return NULL;
931         }
932
933         s->state = AST_FAX_STATE_INACTIVE;
934         s->details = details;
935         ao2_ref(s->details, 1);
936
937         /* locate a FAX technology module that can handle said requirements
938          * Note: the requirements have not yet been finalized as T.38
939          * negotiation has not yet occured. */
940         AST_RWLIST_RDLOCK(&faxmodules);
941         AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
942                 if ((faxmod->tech->caps & details->caps) != details->caps) {
943                         continue;
944                 }
945                 ast_debug(4, "Reserving a FAX session from '%s'.\n", faxmod->tech->description);
946                 ast_module_ref(faxmod->tech->module);
947                 s->tech = faxmod->tech;
948                 break;
949         }
950         AST_RWLIST_UNLOCK(&faxmodules);
951
952         if (!faxmod) {
953                 char caps[128] = "";
954                 ast_log(LOG_ERROR, "Could not locate a FAX technology module with capabilities (%s)\n", ast_fax_caps_to_str(details->caps, caps, sizeof(caps)));
955                 ao2_ref(s, -1);
956                 return NULL;
957         }
958
959         if (!s->tech->reserve_session) {
960                 ast_debug(1, "Selected FAX technology module (%s) does not support reserving sessions.\n", s->tech->description);
961                 return s;
962         }
963
964         if (!(*token = s->tech->reserve_session(s))) {
965                 ao2_ref(s, -1);
966                 return NULL;
967         }
968
969         s->state = AST_FAX_STATE_RESERVED;
970         ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, 1);
971
972         return s;
973 }
974
975 /*! \brief create a FAX session
976  *
977  * \param details details for the session
978  * \param chan the channel the session will run on
979  * \param reserved a reserved session to base this session on (can be NULL)
980  * \param token the token for a reserved session (can be NULL)
981  *
982  * Create a new fax session based on the given details structure.
983  *
984  * \note The given token is always consumed (by tech->new_session() or by
985  * fax_session_release() in the event of a failure). The given reference to a
986  * reserved session is never consumed and must be dereferenced separately from
987  * the reference returned by this function.
988  *
989  * \return NULL or a reference to a new fax session
990  */
991 static struct ast_fax_session *fax_session_new(struct ast_fax_session_details *details, struct ast_channel *chan, struct ast_fax_session *reserved, struct ast_fax_tech_token *token)
992 {
993         struct ast_fax_session *s = NULL;
994         struct fax_module *faxmod;
995
996         if (reserved) {
997                 s = reserved;
998                 ao2_ref(reserved, +1);
999
1000                 /* NOTE: we don't consume the reference to the reserved
1001                  * session. The session returned from fax_session_new() is a
1002                  * new reference and must be derefed in addition to the
1003                  * reserved session.
1004                  */
1005
1006                 if (s->state == AST_FAX_STATE_RESERVED) {
1007                         ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
1008                         s->state = AST_FAX_STATE_UNINITIALIZED;
1009                 }
1010         }
1011
1012         if (!s && !(s = ao2_alloc(sizeof(*s), destroy_session))) {
1013                 return NULL;
1014         }
1015
1016         ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
1017         s->state = AST_FAX_STATE_UNINITIALIZED;
1018
1019         if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
1020                 if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
1021                         fax_session_release(s, token);
1022                         ao2_ref(s, -1);
1023                         return NULL;
1024                 }
1025                 if (!(s->debug_info->dsp = ast_dsp_new())) {
1026                         ast_free(s->debug_info);
1027                         s->debug_info = NULL;
1028                         fax_session_release(s, token);
1029                         ao2_ref(s, -1);
1030                         return NULL;
1031                 }
1032                 ast_dsp_set_threshold(s->debug_info->dsp, 128);
1033         }
1034
1035         if (!(s->channame = ast_strdup(ast_channel_name(chan)))) {
1036                 fax_session_release(s, token);
1037                 ao2_ref(s, -1);
1038                 return NULL;
1039         }
1040
1041         if (!(s->chan_uniqueid = ast_strdup(ast_channel_uniqueid(chan)))) {
1042                 fax_session_release(s, token);
1043                 ao2_ref(s, -1);
1044                 return NULL;
1045         }
1046
1047         s->chan = chan;
1048         if (!s->details) {
1049                 s->details = details;
1050                 ao2_ref(s->details, 1);
1051         }
1052
1053         details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
1054
1055         if (!token) {
1056                 /* locate a FAX technology module that can handle said requirements */
1057                 AST_RWLIST_RDLOCK(&faxmodules);
1058                 AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
1059                         if ((faxmod->tech->caps & details->caps) != details->caps) {
1060                                 continue;
1061                         }
1062                         ast_debug(4, "Requesting a new FAX session from '%s'.\n", faxmod->tech->description);
1063                         ast_module_ref(faxmod->tech->module);
1064                         s->tech = faxmod->tech;
1065                         break;
1066                 }
1067                 AST_RWLIST_UNLOCK(&faxmodules);
1068
1069                 if (!faxmod) {
1070                         char caps[128] = "";
1071                         ast_log(LOG_ERROR, "Could not locate a FAX technology module with capabilities (%s)\n", ast_fax_caps_to_str(details->caps, caps, sizeof(caps)));
1072                         ao2_ref(s, -1);
1073                         return NULL;
1074                 }
1075         }
1076
1077         if (!(s->tech_pvt = s->tech->new_session(s, token))) {
1078                 ast_log(LOG_ERROR, "FAX session failed to initialize.\n");
1079                 ao2_ref(s, -1);
1080                 return NULL;
1081         }
1082         /* link the session to the session container */
1083         if (!(ao2_link(faxregistry.container, s))) {
1084                 ast_log(LOG_ERROR, "failed to add FAX session '%d' to container.\n", s->id);
1085                 ao2_ref(s, -1);
1086                 return NULL;
1087         }
1088         ast_debug(4, "channel '%s' using FAX session '%d'\n", s->channame, s->id);
1089
1090         return s;
1091 }
1092
1093 /*!
1094  * \internal
1095  * \brief Convert the filenames in a fax session into a JSON array
1096  * \retval NULL on error
1097  * \retval A \ref ast_json array on success
1098  */
1099 static struct ast_json *generate_filenames_json(struct ast_fax_session_details *details)
1100 {
1101         RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
1102         struct ast_fax_document *doc;
1103
1104         if (!details || !json_array) {
1105                 return NULL;
1106         }
1107
1108         /* don't process empty lists */
1109         if (AST_LIST_EMPTY(&details->documents)) {
1110                 return NULL;
1111         }
1112
1113         AST_LIST_TRAVERSE(&details->documents, doc, next) {
1114                 struct ast_json *entry = ast_json_string_create(doc->filename);
1115                 if (!entry) {
1116                         return NULL;
1117                 }
1118                 if (ast_json_array_append(json_array, entry)) {
1119                         return NULL;
1120                 }
1121         }
1122
1123         ast_json_ref(json_array);
1124         return json_array;
1125 }
1126
1127 /* \brief Generate a string of filenames using the given prefix and separator.
1128  * \param details the fax session details
1129  * \param prefix the prefix to each filename
1130  * \param separator the separator between filenames
1131  *
1132  * This function generates a string of filenames from the given details
1133  * structure and using the given prefix and separator.
1134  *
1135  * \retval NULL there was an error generating the string
1136  * \return the string generated string
1137  */
1138 static char *generate_filenames_string(struct ast_fax_session_details *details, char *prefix, char *separator)
1139 {
1140         char *filenames, *c;
1141         size_t size = 0;
1142         int first = 1;
1143         struct ast_fax_document *doc;
1144
1145         /* don't process empty lists */
1146         if (AST_LIST_EMPTY(&details->documents)) {
1147                 return NULL;
1148         }
1149
1150         /* Calculate the total length of all of the file names */
1151         AST_LIST_TRAVERSE(&details->documents, doc, next) {
1152                 size += strlen(separator) + strlen(prefix) + strlen(doc->filename);
1153         }
1154         size += 1; /* add space for the terminating null */
1155
1156         if (!(filenames = ast_malloc(size))) {
1157                 return NULL;
1158         }
1159         c = filenames;
1160
1161         ast_build_string(&c, &size, "%s%s", prefix, AST_LIST_FIRST(&details->documents)->filename);
1162         AST_LIST_TRAVERSE(&details->documents, doc, next) {
1163                 if (first) {
1164                         first = 0;
1165                         continue;
1166                 }
1167
1168                 ast_build_string(&c, &size, "%s%s%s", separator, prefix, doc->filename);
1169         }
1170
1171         return filenames;
1172 }
1173
1174 /*! \brief send a FAX status manager event */
1175 static int report_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details, const char *status)
1176 {
1177         RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
1178         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1179         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1180         struct ast_json *json_filenames = NULL;
1181
1182         if (!details->option.statusevents) {
1183                 return 0;
1184         }
1185
1186         json_filenames = generate_filenames_json(details);
1187         if (!json_filenames) {
1188                 return -1;
1189         }
1190
1191         json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: o}",
1192                         "type", "status",
1193                         "operation", (details->caps & AST_FAX_TECH_GATEWAY) ? "gateway" : (details->caps & AST_FAX_TECH_RECEIVE) ? "receive" : "send",
1194                         "status", status,
1195                         "local_station_id", details->localstationid,
1196                         "filenames", json_filenames);
1197         if (!json_object) {
1198                 return -1;
1199         }
1200
1201         {
1202                 SCOPED_CHANNELLOCK(lock, chan);
1203
1204                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
1205                 if (!message) {
1206                         return -1;
1207                 }
1208                 stasis_publish(ast_channel_topic(chan), message);
1209         }
1210         return 0;
1211 }
1212
1213 /*! \brief Set fax related channel variables. */
1214 static void set_channel_variables(struct ast_channel *chan, struct ast_fax_session_details *details)
1215 {
1216         char buf[10];
1217         pbx_builtin_setvar_helper(chan, "FAXSTATUS", S_OR(details->result, NULL));
1218         pbx_builtin_setvar_helper(chan, "FAXERROR", S_OR(details->error, NULL));
1219         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", S_OR(details->resultstr, NULL));
1220         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", S_OR(details->remotestationid, NULL));
1221         pbx_builtin_setvar_helper(chan, "LOCALSTATIONID", S_OR(details->localstationid, NULL));
1222         pbx_builtin_setvar_helper(chan, "FAXBITRATE", S_OR(details->transfer_rate, NULL));
1223         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", S_OR(details->resolution, NULL));
1224
1225         snprintf(buf, sizeof(buf), "%d", details->pages_transferred);
1226         pbx_builtin_setvar_helper(chan, "FAXPAGES", buf);
1227 }
1228
1229 #define GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason) \
1230         do {    \
1231                 if (ast_strlen_zero(fax->details->result)) \
1232                         ast_string_field_set(fax->details, result, "FAILED"); \
1233                 if (ast_strlen_zero(fax->details->resultstr)) \
1234                         ast_string_field_set(fax->details, resultstr, reason); \
1235                 if (ast_strlen_zero(fax->details->error)) \
1236                         ast_string_field_set(fax->details, error, errorstr); \
1237                 set_channel_variables(chan, fax->details); \
1238         } while (0)
1239
1240 #define GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason) \
1241         do {    \
1242                 GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason); \
1243         } while (0)
1244
1245 #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason)     \
1246         do {    \
1247                 ast_log(LOG_ERROR, "channel '%s' FAX session '%d' failure, reason: '%s' (%s)\n", ast_channel_name(chan), fax->id, reason, errorstr); \
1248                 GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason); \
1249         } while (0)
1250
1251 static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
1252 {
1253         switch (ast_channel_get_t38_state(chan)) {
1254         case T38_STATE_UNKNOWN:
1255                 details->caps |= AST_FAX_TECH_T38;
1256                 break;
1257         case T38_STATE_REJECTED:
1258         case T38_STATE_UNAVAILABLE:
1259                 details->caps |= AST_FAX_TECH_AUDIO;
1260                 break;
1261         case T38_STATE_NEGOTIATED:
1262                 /* already in T.38 mode? This should not happen. */
1263         case T38_STATE_NEGOTIATING: {
1264                 /* the other end already sent us a T.38 reinvite, so we need to prod the channel
1265                  * driver into resending their parameters to us if it supports doing so... if
1266                  * not, we can't proceed, because we can't create a proper reply without them.
1267                  * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
1268                  * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
1269                  * that gets called after this one completes
1270                  */
1271                 struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
1272                 if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
1273                         ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1274                         return -1;
1275                 }
1276                 details->caps |= AST_FAX_TECH_T38;
1277                 break;
1278         }
1279         default:
1280                 ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1281                 return -1;
1282         }
1283
1284         return 0;
1285 }
1286
1287 static int disable_t38(struct ast_channel *chan)
1288 {
1289         int timeout_ms;
1290         struct ast_frame *frame = NULL;
1291         struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
1292         struct timeval start;
1293         int ms;
1294
1295         ast_debug(1, "Shutting down T.38 on %s\n", ast_channel_name(chan));
1296         if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
1297                 ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1298                 return -1;
1299         }
1300
1301         /* wait up to five seconds for negotiation to complete */
1302         timeout_ms = 5000;
1303         start = ast_tvnow();
1304         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1305                 ms = ast_waitfor(chan, ms);
1306
1307                 if (ms == 0) {
1308                         break;
1309                 }
1310                 if (ms < 0) {
1311                         ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1312                         return -1;
1313                 }
1314
1315                 if (!(frame = ast_read(chan))) {
1316                         return -1;
1317                 }
1318                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1319                     (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1320                     (frame->datalen == sizeof(t38_parameters))) {
1321                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1322
1323                         switch (parameters->request_response) {
1324                         case AST_T38_TERMINATED:
1325                                 ast_debug(1, "Shut down T.38 on %s\n", ast_channel_name(chan));
1326                                 break;
1327                         case AST_T38_REFUSED:
1328                                 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", ast_channel_name(chan));
1329                                 ast_frfree(frame);
1330                                 return -1;
1331                         default:
1332                                 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", ast_channel_name(chan));
1333                                 ast_frfree(frame);
1334                                 return -1;
1335                         }
1336                         ast_frfree(frame);
1337                         break;
1338                 }
1339                 ast_frfree(frame);
1340         }
1341
1342         if (ms == 0) { /* all done, nothing happened */
1343                 ast_debug(1, "channel '%s' timed-out during T.38 shutdown\n", ast_channel_name(chan));
1344         }
1345
1346         return 0;
1347 }
1348
1349 /*! \brief this is the generic FAX session handling function */
1350 static int generic_fax_exec(struct ast_channel *chan, struct ast_fax_session_details *details, struct ast_fax_session *reserved, struct ast_fax_tech_token *token)
1351 {
1352         int ms;
1353         int timeout = RES_FAX_TIMEOUT;
1354         int chancount;
1355         unsigned int expected_frametype = -1;
1356         union ast_frame_subclass expected_framesubclass = { .integer = -1 };
1357         unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
1358         struct ast_control_t38_parameters t38_parameters;
1359         const char *tempvar;
1360         struct ast_fax_session *fax = NULL;
1361         struct ast_frame *frame = NULL;
1362         struct ast_channel *c = chan;
1363         struct ast_format orig_write_format;
1364         struct ast_format orig_read_format;
1365         int remaining_time;
1366         struct timeval start;
1367
1368         ast_format_clear(&orig_write_format);
1369         ast_format_clear(&orig_read_format);
1370         chancount = 1;
1371
1372         /* create the FAX session */
1373         if (!(fax = fax_session_new(details, chan, reserved, token))) {
1374                 ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
1375                 report_fax_status(chan, details, "No Available Resource");
1376                 return -1;
1377         }
1378
1379         ast_channel_lock(chan);
1380         /* update session details */
1381         if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
1382                 ast_string_field_set(details, headerinfo, tempvar);
1383         }
1384         if (ast_strlen_zero(details->localstationid)) {
1385                 tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
1386                 ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
1387         }
1388         ast_channel_unlock(chan);
1389
1390         report_fax_status(chan, details, "Allocating Resources");
1391
1392         if (details->caps & AST_FAX_TECH_AUDIO) {
1393                 expected_frametype = AST_FRAME_VOICE;;
1394                 ast_format_set(&expected_framesubclass.format, AST_FORMAT_SLINEAR, 0);
1395                 ast_format_copy(&orig_write_format, ast_channel_writeformat(chan));
1396                 if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1397                         ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", ast_channel_name(chan));
1398                         ao2_lock(faxregistry.container);
1399                         ao2_unlink(faxregistry.container, fax);
1400                         ao2_unlock(faxregistry.container);
1401                         ao2_ref(fax, -1);
1402                         ast_channel_unlock(chan);
1403                         return -1;
1404                 }
1405                 ast_format_copy(&orig_read_format, ast_channel_readformat(chan));
1406                 if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1407                         ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", ast_channel_name(chan));
1408                         ao2_lock(faxregistry.container);
1409                         ao2_unlink(faxregistry.container, fax);
1410                         ao2_unlock(faxregistry.container);
1411                         ao2_ref(fax, -1);
1412                         ast_channel_unlock(chan);
1413                         return -1;
1414                 }
1415                 if (fax->smoother) {
1416                         ast_smoother_free(fax->smoother);
1417                         fax->smoother = NULL;
1418                 }
1419                 if (!(fax->smoother = ast_smoother_new(320))) {
1420                         ast_log(LOG_WARNING, "Channel '%s' FAX session '%d' failed to obtain a smoother.\n", ast_channel_name(chan), fax->id);
1421                 }
1422         } else {
1423                 expected_frametype = AST_FRAME_MODEM;
1424                 expected_framesubclass.integer = AST_MODEM_T38;
1425         }
1426
1427         if (fax->debug_info) {
1428                 fax->debug_info->base_tv = ast_tvnow();
1429         }
1430
1431         /* reset our result fields just in case the fax tech driver wants to
1432          * set custom error messages */
1433         ast_string_field_set(details, result, "");
1434         ast_string_field_set(details, resultstr, "");
1435         ast_string_field_set(details, error, "");
1436         set_channel_variables(chan, details);
1437
1438         if (fax->tech->start_session(fax) < 0) {
1439                 GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
1440         }
1441
1442         report_fax_status(chan, details, "FAX Transmission In Progress");
1443
1444         ast_debug(5, "channel %s will wait on FAX fd %d\n", ast_channel_name(chan), fax->fd);
1445
1446         /* handle frames for the session */
1447         remaining_time = timeout;
1448         start = ast_tvnow();
1449         while (remaining_time > 0) {
1450                 struct ast_channel *ready_chan;
1451                 int ofd, exception;
1452
1453                 ms = 1000;
1454                 errno = 0;
1455                 ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
1456                 if (ready_chan) {
1457                         if (!(frame = ast_read(chan))) {
1458                                 /* the channel is probably gone, so lets stop polling on it and let the
1459                                  * FAX session complete before we exit the application.  if needed,
1460                                  * send the FAX stack silence so the modems can finish their session without
1461                                  * any problems */
1462                                 ast_debug(1, "Channel '%s' did not return a frame; probably hung up.\n", ast_channel_name(chan));
1463                                 GENERIC_FAX_EXEC_SET_VARS(fax, chan, "HANGUP", "remote channel hungup");
1464                                 c = NULL;
1465                                 chancount = 0;
1466                                 remaining_time = ast_remaining_ms(start, timeout);
1467                                 fax->tech->cancel_session(fax);
1468                                 if (fax->tech->generate_silence) {
1469                                         fax->tech->generate_silence(fax);
1470                                 }
1471                                 continue;
1472                         }
1473
1474                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1475                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1476                             (frame->datalen == sizeof(t38_parameters))) {
1477                                 unsigned int was_t38 = t38negotiated;
1478                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1479
1480                                 switch (parameters->request_response) {
1481                                 case AST_T38_REQUEST_NEGOTIATE:
1482                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1483                                          * do T.38 as well
1484                                          */
1485                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1486                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1487                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1488                                         break;
1489                                 case AST_T38_NEGOTIATED:
1490                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1491                                         t38negotiated = 1;
1492                                         break;
1493                                 default:
1494                                         break;
1495                                 }
1496                                 if (t38negotiated && !was_t38) {
1497                                         fax->tech->switch_to_t38(fax);
1498                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1499                                         expected_frametype = AST_FRAME_MODEM;
1500                                         expected_framesubclass.integer = AST_MODEM_T38;
1501                                         if (fax->smoother) {
1502                                                 ast_smoother_free(fax->smoother);
1503                                                 fax->smoother = NULL;
1504                                         }
1505
1506                                         report_fax_status(chan, details, "T.38 Negotiated");
1507
1508                                         ast_verb(3, "Channel '%s' switched to T.38 FAX session '%d'.\n", ast_channel_name(chan), fax->id);
1509                                 }
1510                         } else if ((frame->frametype == expected_frametype) &&
1511                                    (!memcmp(&frame->subclass, &expected_framesubclass, sizeof(frame->subclass)))) {
1512                                 struct ast_frame *f;
1513
1514                                 if (fax->smoother) {
1515                                         /* push the frame into a smoother */
1516                                         if (ast_smoother_feed(fax->smoother, frame) < 0) {
1517                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
1518                                         }
1519                                         while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
1520                                                 if (fax->debug_info) {
1521                                                         debug_check_frame_for_silence(fax, 1, f);
1522                                                 }
1523                                                 /* write the frame to the FAX stack */
1524                                                 fax->tech->write(fax, f);
1525                                                 fax->frames_received++;
1526                                                 if (f != frame) {
1527                                                         ast_frfree(f);
1528                                                 }
1529                                         }
1530                                 } else {
1531                                         /* write the frame to the FAX stack */
1532                                         fax->tech->write(fax, frame);
1533                                         fax->frames_received++;
1534                                 }
1535                                 start = ast_tvnow();
1536                         }
1537                         ast_frfree(frame);
1538                 } else if (ofd == fax->fd) {
1539                         /* read a frame from the FAX stack and send it out the channel.
1540                          * the FAX stack will return a NULL if the FAX session has already completed */
1541                         if (!(frame = fax->tech->read(fax))) {
1542                                 break;
1543                         }
1544
1545                         if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
1546                                 debug_check_frame_for_silence(fax, 0, frame);
1547                         }
1548
1549                         ast_write(chan, frame);
1550                         fax->frames_sent++;
1551                         ast_frfree(frame);
1552                         start = ast_tvnow();
1553                 } else {
1554                         if (ms && (ofd < 0)) {
1555                                 if ((errno == 0) || (errno == EINTR)) {
1556                                         remaining_time = ast_remaining_ms(start, timeout);
1557                                         if (remaining_time <= 0)
1558                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1559                                         continue;
1560                                 } else {
1561                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(chan));
1562                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "error polling data");
1563                                         break;
1564                                 }
1565                         } else {
1566                                 /* nothing happened */
1567                                 remaining_time = ast_remaining_ms(start, timeout);
1568                                 if (remaining_time <= 0) {
1569                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1570                                         break;
1571                                 }
1572                         }
1573                 }
1574         }
1575         ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, remaining_time: %d }\n", ast_channel_name(chan), timeout, remaining_time);
1576
1577         set_channel_variables(chan, details);
1578
1579         ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
1580         if (!strcasecmp(details->result, "FAILED")) {
1581                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1582         }
1583
1584         if (fax) {
1585                 ao2_lock(faxregistry.container);
1586                 ao2_unlink(faxregistry.container, fax);
1587                 ao2_unlock(faxregistry.container);
1588                 ao2_ref(fax, -1);
1589         }
1590
1591         /* if the channel is still alive, and we changed its read/write formats,
1592          * restore them now
1593          */
1594         if (chancount) {
1595                 if (orig_read_format.id) {
1596                         ast_set_read_format(chan, &orig_read_format);
1597                 }
1598                 if (orig_write_format.id) {
1599                         ast_set_write_format(chan, &orig_write_format);
1600                 }
1601         }
1602
1603         /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
1604         return chancount;
1605 }
1606
1607 static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1608 {
1609         int timeout_ms;
1610         struct ast_frame *frame = NULL;
1611         struct ast_control_t38_parameters t38_parameters;
1612         struct timeval start;
1613         int ms;
1614
1615         /* don't send any audio if we've already received a T.38 reinvite */
1616         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1617                 /* generate 3 seconds of CED */
1618                 if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
1619                         ast_log(LOG_ERROR, "error generating CED tone on %s\n", ast_channel_name(chan));
1620                         return -1;
1621                 }
1622
1623                 timeout_ms = 3000;
1624                 start = ast_tvnow();
1625                 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1626                         ms = ast_waitfor(chan, ms);
1627
1628                         if (ms < 0) {
1629                                 ast_log(LOG_ERROR, "error while generating CED tone on %s\n", ast_channel_name(chan));
1630                                 ast_playtones_stop(chan);
1631                                 return -1;
1632                         }
1633
1634                         if (ms == 0) { /* all done, nothing happened */
1635                                 break;
1636                         }
1637
1638                         if (!(frame = ast_read(chan))) {
1639                                 ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", ast_channel_name(chan));
1640                                 ast_playtones_stop(chan);
1641                                 return -1;
1642                         }
1643
1644                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1645                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1646                             (frame->datalen == sizeof(t38_parameters))) {
1647                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1648
1649                                 switch (parameters->request_response) {
1650                                 case AST_T38_REQUEST_NEGOTIATE:
1651                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1652                                          * do T.38 as well
1653                                          */
1654                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1655                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1656                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1657                                         ast_playtones_stop(chan);
1658                                         break;
1659                                 case AST_T38_NEGOTIATED:
1660                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1661                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1662                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1663                                         report_fax_status(chan, details, "T.38 Negotiated");
1664                                         break;
1665                                 default:
1666                                         break;
1667                                 }
1668                         }
1669                         ast_frfree(frame);
1670                 }
1671
1672                 ast_playtones_stop(chan);
1673         }
1674
1675         /* if T.38 was negotiated, we are done initializing */
1676         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1677                 return 0;
1678         }
1679
1680         /* request T.38 */
1681         ast_debug(1, "Negotiating T.38 for receive on %s\n", ast_channel_name(chan));
1682
1683         /* wait up to five seconds for negotiation to complete */
1684         timeout_ms = 5000;
1685
1686         /* set parameters based on the session's parameters */
1687         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1688         t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
1689         if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
1690                 return -1;
1691         }
1692
1693         start = ast_tvnow();
1694         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1695                 int break_loop = 0;
1696
1697                 ms = ast_waitfor(chan, ms);
1698                 if (ms < 0) {
1699                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1700                         return -1;
1701                 }
1702                 if (ms == 0) { /* all done, nothing happened */
1703                         ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
1704                         details->caps &= ~AST_FAX_TECH_T38;
1705                         break;
1706                 }
1707
1708                 if (!(frame = ast_read(chan))) {
1709                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1710                         return -1;
1711                 }
1712
1713                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1714                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1715                                 (frame->datalen == sizeof(t38_parameters))) {
1716                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1717
1718                         switch (parameters->request_response) {
1719                         case AST_T38_REQUEST_NEGOTIATE:
1720                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1721                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
1722                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1723                                 break;
1724                         case AST_T38_NEGOTIATED:
1725                                 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1726                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1727                                 details->caps &= ~AST_FAX_TECH_AUDIO;
1728                                 report_fax_status(chan, details, "T.38 Negotiated");
1729                                 break_loop = 1;
1730                                 break;
1731                         case AST_T38_REFUSED:
1732                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
1733                                 details->caps &= ~AST_FAX_TECH_T38;
1734                                 break_loop = 1;
1735                                 break;
1736                         default:
1737                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
1738                                 details->caps &= ~AST_FAX_TECH_T38;
1739                                 break_loop = 1;
1740                                 break;
1741                         }
1742                 }
1743                 ast_frfree(frame);
1744                 if (break_loop) {
1745                         break;
1746                 }
1747         }
1748
1749         /* if T.38 was negotiated, we are done initializing */
1750         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1751                 return 0;
1752         }
1753
1754         /* if we made it here, then T.38 failed, check the 'f' flag */
1755         if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
1756                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
1757                 return -1;
1758         }
1759
1760         /* ok, audio fallback is allowed */
1761         details->caps |= AST_FAX_TECH_AUDIO;
1762
1763         return 0;
1764 }
1765
1766 /*! \brief Report on the final state of a receive fax operation
1767  * \note This will lock the \ref ast_channel
1768  */
1769 static int report_receive_fax_status(struct ast_channel *chan, const char *filename)
1770 {
1771         RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
1772         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1773         RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
1774         struct ast_json *json_filename = ast_json_string_create(filename);
1775
1776         if (!json_array || !json_filename) {
1777                 ast_json_unref(json_filename);
1778                 return -1;
1779         }
1780         ast_json_array_append(json_array, json_filename);
1781
1782         {
1783                 const char *remote_station_id;
1784                 const char *local_station_id;
1785                 const char *fax_pages;
1786                 const char *fax_resolution;
1787                 const char *fax_bitrate;
1788                 SCOPED_CHANNELLOCK(lock, chan);
1789
1790                 remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
1791                 if (!ast_strlen_zero(remote_station_id)) {
1792                         remote_station_id = ast_strdupa(remote_station_id);
1793                 }
1794                 local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
1795                 if (!ast_strlen_zero(local_station_id)) {
1796                         local_station_id = ast_strdupa(local_station_id);
1797                 }
1798                 fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
1799                 if (!ast_strlen_zero(fax_pages)) {
1800                         fax_pages = ast_strdupa(fax_pages);
1801                 }
1802                 fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
1803                 if (!ast_strlen_zero(fax_resolution)) {
1804                         fax_resolution = ast_strdupa(fax_resolution);
1805                 }
1806                 fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
1807                 if (!ast_strlen_zero(fax_bitrate)) {
1808                         fax_bitrate = ast_strdupa(fax_bitrate);
1809                 }
1810
1811                 json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: O}",
1812                                 "type", "receive",
1813                                 "remote_station_id", S_OR(remote_station_id, ""),
1814                                 "local_station_id", S_OR(local_station_id, ""),
1815                                 "fax_pages", S_OR(fax_pages, ""),
1816                                 "fax_resolution", S_OR(fax_resolution, ""),
1817                                 "fax_bitrate", S_OR(fax_bitrate, ""),
1818                                 "filenames", json_array);
1819                 if (!json_object) {
1820                         return -1;
1821                 }
1822
1823                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
1824                 if (!message) {
1825                         return -1;
1826                 }
1827                 stasis_publish(ast_channel_topic(chan), message);
1828         }
1829         return 0;
1830 }
1831
1832 /*! \brief initiate a receive FAX session */
1833 static int receivefax_exec(struct ast_channel *chan, const char *data)
1834 {
1835         char *parse, modems[128] = "";
1836         int channel_alive;
1837         RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
1838         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
1839         struct ast_fax_tech_token *token = NULL;
1840         struct ast_fax_document *doc;
1841         AST_DECLARE_APP_ARGS(args,
1842                 AST_APP_ARG(filename);
1843                 AST_APP_ARG(options);
1844         );
1845         struct ast_flags opts = { 0, };
1846         enum ast_t38_state t38state;
1847
1848         /* initialize output channel variables */
1849         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
1850         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
1851         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
1852         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
1853         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
1854
1855         /* Get a FAX session details structure from the channel's FAX datastore and create one if
1856          * it does not already exist. */
1857         if (!(details = find_or_create_details(chan))) {
1858                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
1859                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
1860                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1861                 return -1;
1862         }
1863
1864         ast_string_field_set(details, result, "FAILED");
1865         ast_string_field_set(details, resultstr, "error starting fax session");
1866         ast_string_field_set(details, error, "INIT_ERROR");
1867         set_channel_variables(chan, details);
1868
1869         if (details->gateway_id > 0) {
1870                 ast_string_field_set(details, resultstr, "can't receive a fax on a channel with a T.38 gateway");
1871                 set_channel_variables(chan, details);
1872                 ast_log(LOG_ERROR, "executing ReceiveFAX on a channel with a T.38 Gateway is not supported\n");
1873                 return -1;
1874         }
1875
1876         if (details->maxrate < details->minrate) {
1877                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1878                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
1879                 set_channel_variables(chan, details);
1880                 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
1881                 return -1;
1882         }
1883
1884         if (check_modem_rate(details->modems, details->minrate)) {
1885                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1886                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
1887                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1888                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
1889                 set_channel_variables(chan, details);
1890                 return -1;
1891         }
1892
1893         if (check_modem_rate(details->modems, details->maxrate)) {
1894                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1895                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
1896                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1897                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
1898                 set_channel_variables(chan, details);
1899                 return -1;
1900         }
1901
1902         if (ast_strlen_zero(data)) {
1903                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1904                 ast_string_field_set(details, resultstr, "invalid arguments");
1905                 set_channel_variables(chan, details);
1906                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1907                 return -1;
1908         }
1909         parse = ast_strdupa(data);
1910         AST_STANDARD_APP_ARGS(args, parse);
1911
1912         if (!ast_strlen_zero(args.options) &&
1913             ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
1914                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1915                 ast_string_field_set(details, resultstr, "invalid arguments");
1916                 set_channel_variables(chan, details);
1917                 return -1;
1918         }
1919         if (ast_strlen_zero(args.filename)) {
1920                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1921                 ast_string_field_set(details, resultstr, "invalid arguments");
1922                 set_channel_variables(chan, details);
1923                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1924                 return -1;
1925         }
1926
1927         /* check for unsupported FAX application options */
1928         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
1929                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1930                 ast_string_field_set(details, resultstr, "invalid arguments");
1931                 set_channel_variables(chan, details);
1932                 ast_log(LOG_WARNING, "%s does not support polling\n", app_receivefax);
1933                 return -1;
1934         }
1935
1936         ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
1937
1938         pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
1939         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
1940
1941         if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
1942                 ast_string_field_set(details, error, "MEMORY_ERROR");
1943                 ast_string_field_set(details, resultstr, "error allocating memory");
1944                 set_channel_variables(chan, details);
1945                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1946                 return -1;
1947         }
1948
1949         strcpy(doc->filename, args.filename);
1950         AST_LIST_INSERT_TAIL(&details->documents, doc, next);
1951
1952         ast_verb(3, "Channel '%s' receiving FAX '%s'\n", ast_channel_name(chan), args.filename);
1953
1954         details->caps = AST_FAX_TECH_RECEIVE;
1955         details->option.send_ced = AST_FAX_OPTFLAG_TRUE;
1956
1957         /* check for debug */
1958         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
1959                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
1960         }
1961
1962         /* check for request for status events */
1963         if (ast_test_flag(&opts, OPT_STATUS)) {
1964                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
1965         }
1966
1967         t38state = ast_channel_get_t38_state(chan);
1968         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
1969             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
1970             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1971                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
1972         }
1973
1974         if (!(s = fax_session_reserve(details, &token))) {
1975                 ast_string_field_set(details, resultstr, "error reserving fax session");
1976                 set_channel_variables(chan, details);
1977                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
1978                 return -1;
1979         }
1980
1981         /* make sure the channel is up */
1982         if (ast_channel_state(chan) != AST_STATE_UP) {
1983                 if (ast_answer(chan)) {
1984                         ast_string_field_set(details, resultstr, "error answering channel");
1985                         set_channel_variables(chan, details);
1986                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
1987                         fax_session_release(s, token);
1988                         return -1;
1989                 }
1990         }
1991
1992         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1993                 if (set_fax_t38_caps(chan, details)) {
1994                         ast_string_field_set(details, error, "T38_NEG_ERROR");
1995                         ast_string_field_set(details, resultstr, "error negotiating T.38");
1996                         set_channel_variables(chan, details);
1997                         fax_session_release(s, token);
1998                         return -1;
1999                 }
2000         } else {
2001                 details->caps |= AST_FAX_TECH_AUDIO;
2002         }
2003
2004         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2005                 if (receivefax_t38_init(chan, details)) {
2006                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2007                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2008                         set_channel_variables(chan, details);
2009                         fax_session_release(s, token);
2010                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2011                         return -1;
2012                 }
2013         }
2014
2015         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2016                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2017         }
2018
2019         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2020                 if (disable_t38(chan)) {
2021                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2022                 }
2023         }
2024
2025         if (report_receive_fax_status(chan, args.filename)) {
2026                 ast_log(AST_LOG_ERROR, "Error publishing ReceiveFax status message\n");
2027         }
2028
2029         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2030         return (!channel_alive) ? -1 : 0;
2031 }
2032
2033 static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
2034 {
2035         int timeout_ms;
2036         struct ast_frame *frame = NULL;
2037         struct ast_control_t38_parameters t38_parameters;
2038         struct timeval start;
2039         int ms;
2040
2041         /* send CNG tone while listening for the receiver to initiate a switch
2042          * to T.38 mode; if they do, stop sending the CNG tone and proceed with
2043          * the switch.
2044          *
2045          * 10500 is enough time for 3 CNG tones
2046          */
2047         timeout_ms = 10500;
2048
2049         /* don't send any audio if we've already received a T.38 reinvite */
2050         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
2051                 if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
2052                         ast_log(LOG_ERROR, "error generating CNG tone on %s\n", ast_channel_name(chan));
2053                         return -1;
2054                 }
2055         }
2056
2057         start = ast_tvnow();
2058         while ((ms = ast_remaining_ms(start, timeout_ms))) {
2059                 int break_loop = 0;
2060                 ms = ast_waitfor(chan, ms);
2061
2062                 if (ms < 0) {
2063                         ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", ast_channel_name(chan));
2064                         ast_playtones_stop(chan);
2065                         return -1;
2066                 }
2067
2068                 if (ms == 0) { /* all done, nothing happened */
2069                         break;
2070                 }
2071
2072                 if (!(frame = ast_read(chan))) {
2073                         ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", ast_channel_name(chan));
2074                         ast_playtones_stop(chan);
2075                         return -1;
2076                 }
2077
2078                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2079                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2080                                 (frame->datalen == sizeof(t38_parameters))) {
2081                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2082
2083                         switch (parameters->request_response) {
2084                         case AST_T38_REQUEST_NEGOTIATE:
2085                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2086                                  * do T.38 as well
2087                                  */
2088                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2089                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2090                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2091                                 ast_playtones_stop(chan);
2092                                 break;
2093                         case AST_T38_NEGOTIATED:
2094                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2095                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2096                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2097                                 report_fax_status(chan, details, "T.38 Negotiated");
2098                                 break_loop = 1;
2099                                 break;
2100                         default:
2101                                 break;
2102                         }
2103                 }
2104                 ast_frfree(frame);
2105                 if (break_loop) {
2106                         break;
2107                 }
2108         }
2109
2110         ast_playtones_stop(chan);
2111
2112         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2113                 return 0;
2114         }
2115
2116         /* T.38 negotiation did not happen, initiate a switch if requested */
2117         if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
2118                 ast_debug(1, "Negotiating T.38 for send on %s\n", ast_channel_name(chan));
2119
2120                 /* wait up to five seconds for negotiation to complete */
2121                 timeout_ms = 5000;
2122
2123                 /* set parameters based on the session's parameters */
2124                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2125                 t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
2126                 if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
2127                         return -1;
2128                 }
2129
2130                 start = ast_tvnow();
2131                 while ((ms = ast_remaining_ms(start, timeout_ms))) {
2132                         int break_loop = 0;
2133
2134                         ms = ast_waitfor(chan, ms);
2135                         if (ms < 0) {
2136                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2137                                 return -1;
2138                         }
2139                         if (ms == 0) { /* all done, nothing happened */
2140                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
2141                                 details->caps &= ~AST_FAX_TECH_T38;
2142                                 break;
2143                         }
2144
2145                         if (!(frame = ast_read(chan))) {
2146                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2147                                 return -1;
2148                         }
2149
2150                         if ((frame->frametype == AST_FRAME_CONTROL) &&
2151                                         (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2152                                         (frame->datalen == sizeof(t38_parameters))) {
2153                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
2154
2155                                 switch (parameters->request_response) {
2156                                 case AST_T38_REQUEST_NEGOTIATE:
2157                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2158                                         t38_parameters.request_response = AST_T38_NEGOTIATED;
2159                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2160                                         break;
2161                                 case AST_T38_NEGOTIATED:
2162                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
2163                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2164                                         details->caps &= ~AST_FAX_TECH_AUDIO;
2165                                         report_fax_status(chan, details, "T.38 Negotiated");
2166                                         break_loop = 1;
2167                                         break;
2168                                 case AST_T38_REFUSED:
2169                                         ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
2170                                         details->caps &= ~AST_FAX_TECH_T38;
2171                                         break_loop = 1;
2172                                         break;
2173                                 default:
2174                                         ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
2175                                         details->caps &= ~AST_FAX_TECH_T38;
2176                                         break_loop = 1;
2177                                         break;
2178                                 }
2179                         }
2180                         ast_frfree(frame);
2181                         if (break_loop) {
2182                                 break;
2183                         }
2184                 }
2185
2186                 /* if T.38 was negotiated, we are done initializing */
2187                 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2188                         return 0;
2189                 }
2190
2191                 /* send one more CNG tone to get audio going again for some
2192                  * carriers if we are going to fall back to audio mode */
2193                 if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
2194                         if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
2195                                 ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", ast_channel_name(chan));
2196                                 return -1;
2197                         }
2198
2199                         timeout_ms = 3500;
2200                         start = ast_tvnow();
2201                         while ((ms = ast_remaining_ms(start, timeout_ms))) {
2202                                 int break_loop = 0;
2203
2204                                 ms = ast_waitfor(chan, ms);
2205                                 if (ms < 0) {
2206                                         ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", ast_channel_name(chan));
2207                                         ast_playtones_stop(chan);
2208                                         return -1;
2209                                 }
2210                                 if (ms == 0) { /* all done, nothing happened */
2211                                         break;
2212                                 }
2213
2214                                 if (!(frame = ast_read(chan))) {
2215                                         ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", ast_channel_name(chan));
2216                                         ast_playtones_stop(chan);
2217                                         return -1;
2218                                 }
2219
2220                                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2221                                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2222                                                 (frame->datalen == sizeof(t38_parameters))) {
2223                                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2224
2225                                         switch (parameters->request_response) {
2226                                         case AST_T38_REQUEST_NEGOTIATE:
2227                                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2228                                                  * do T.38 as well
2229                                                  */
2230                                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2231                                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2232                                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2233                                                 ast_playtones_stop(chan);
2234                                                 break;
2235                                         case AST_T38_NEGOTIATED:
2236                                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2237                                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2238                                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2239                                                 report_fax_status(chan, details, "T.38 Negotiated");
2240                                                 break_loop = 1;
2241                                                 break;
2242                                         default:
2243                                                 break;
2244                                         }
2245                                 }
2246                                 ast_frfree(frame);
2247                                 if (break_loop) {
2248                                         break;
2249                                 }
2250                         }
2251
2252                         ast_playtones_stop(chan);
2253
2254                         /* if T.38 was negotiated, we are done initializing */
2255                         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2256                                 return 0;
2257                         }
2258                 }
2259         }
2260
2261         /* if we made it here, then T.38 failed, check the 'f' flag */
2262         if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
2263                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
2264                 return -1;
2265         }
2266
2267         /* ok, audio fallback is allowed */
2268         details->caps |= AST_FAX_TECH_AUDIO;
2269
2270         return 0;
2271 }
2272
2273 /*!
2274  * \brief Report on the status of a completed fax send attempt
2275  * \note This will lock the \ref ast_channel
2276  */
2277 static int report_send_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details)
2278 {
2279         RAII_VAR(struct ast_json *, json_obj, NULL, ast_json_unref);
2280         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
2281         struct ast_json *json_filenames;
2282
2283         json_filenames = generate_filenames_json(details);
2284         if (!json_filenames) {
2285                 return -1;
2286         }
2287
2288         {
2289                 const char *remote_station_id;
2290                 const char *local_station_id;
2291                 const char *fax_pages;
2292                 const char *fax_resolution;
2293                 const char *fax_bitrate;
2294                 SCOPED_CHANNELLOCK(lock, chan);
2295
2296                 remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
2297                 if (!ast_strlen_zero(remote_station_id)) {
2298                         remote_station_id = ast_strdupa(remote_station_id);
2299                 }
2300                 local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
2301                 if (!ast_strlen_zero(local_station_id)) {
2302                         local_station_id = ast_strdupa(local_station_id);
2303                 }
2304                 fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
2305                 if (!ast_strlen_zero(fax_pages)) {
2306                         fax_pages = ast_strdupa(fax_pages);
2307                 }
2308                 fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
2309                 if (!ast_strlen_zero(fax_resolution)) {
2310                         fax_resolution = ast_strdupa(fax_resolution);
2311                 }
2312                 fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
2313                 if (!ast_strlen_zero(fax_bitrate)) {
2314                         fax_bitrate = ast_strdupa(fax_bitrate);
2315                 }
2316                 json_obj = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: o}",
2317                                 "type", "send",
2318                                 "remote_station_id", S_OR(remote_station_id, ""),
2319                                 "local_station_id", S_OR(local_station_id, ""),
2320                                 "fax_pages", S_OR(fax_pages, ""),
2321                                 "fax_resolution", S_OR(fax_resolution, ""),
2322                                 "fax_bitrate", S_OR(fax_bitrate, ""),
2323                                 "filenames", json_filenames);
2324                 if (!json_obj) {
2325                         return -1;
2326                 }
2327
2328                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_obj);
2329                 if (!message) {
2330                         return -1;
2331                 }
2332                 stasis_publish(ast_channel_topic(chan), message);
2333         }
2334         return 0;
2335 }
2336
2337
2338
2339 /*! \brief initiate a send FAX session */
2340 static int sendfax_exec(struct ast_channel *chan, const char *data)
2341 {
2342         char *parse, *filenames, *c, modems[128] = "";
2343         int channel_alive, file_count;
2344         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
2345         RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
2346         struct ast_fax_tech_token *token = NULL;
2347         struct ast_fax_document *doc;
2348         AST_DECLARE_APP_ARGS(args,
2349                 AST_APP_ARG(filenames);
2350                 AST_APP_ARG(options);
2351         );
2352         struct ast_flags opts = { 0, };
2353         enum ast_t38_state t38state;
2354
2355         /* initialize output channel variables */
2356         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
2357         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
2358         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
2359         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
2360         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
2361
2362         /* Get a requirement structure and set it.  This structure is used
2363          * to tell the FAX technology module about the higher level FAX session */
2364         if (!(details = find_or_create_details(chan))) {
2365                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
2366                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
2367                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2368                 return -1;
2369         }
2370
2371         ast_string_field_set(details, result, "FAILED");
2372         ast_string_field_set(details, resultstr, "error starting fax session");
2373         ast_string_field_set(details, error, "INIT_ERROR");
2374         set_channel_variables(chan, details);
2375
2376         if (details->gateway_id > 0) {
2377                 ast_string_field_set(details, resultstr, "can't send a fax on a channel with a T.38 gateway");
2378                 set_channel_variables(chan, details);
2379                 ast_log(LOG_ERROR, "executing SendFAX on a channel with a T.38 Gateway is not supported\n");
2380                 return -1;
2381         }
2382
2383         if (details->maxrate < details->minrate) {
2384                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2385                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
2386                 set_channel_variables(chan, details);
2387                 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
2388                 return -1;
2389         }
2390
2391         if (check_modem_rate(details->modems, details->minrate)) {
2392                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2393                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
2394                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2395                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
2396                 set_channel_variables(chan, details);
2397                 return -1;
2398         }
2399
2400         if (check_modem_rate(details->modems, details->maxrate)) {
2401                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2402                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
2403                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2404                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
2405                 set_channel_variables(chan, details);
2406                 return -1;
2407         }
2408
2409         if (ast_strlen_zero(data)) {
2410                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2411                 ast_string_field_set(details, resultstr, "invalid arguments");
2412                 set_channel_variables(chan, details);
2413                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
2414                 return -1;
2415         }
2416         parse = ast_strdupa(data);
2417         AST_STANDARD_APP_ARGS(args, parse);
2418
2419
2420         if (!ast_strlen_zero(args.options) &&
2421                 ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
2422                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2423                 ast_string_field_set(details, resultstr, "invalid arguments");
2424                 set_channel_variables(chan, details);
2425                 return -1;
2426         }
2427         if (ast_strlen_zero(args.filenames)) {
2428                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2429                 ast_string_field_set(details, resultstr, "invalid arguments");
2430                 set_channel_variables(chan, details);
2431                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
2432                 return -1;
2433         }
2434
2435         /* check for unsupported FAX application options */
2436         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
2437                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2438                 ast_string_field_set(details, resultstr, "invalid arguments");
2439                 set_channel_variables(chan, details);
2440                 ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
2441                 return -1;
2442         }
2443
2444         ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
2445
2446         file_count = 0;
2447         filenames = args.filenames;
2448         while ((c = strsep(&filenames, "&"))) {
2449                 if (access(c, (F_OK | R_OK)) < 0) {
2450                         ast_string_field_set(details, error, "FILE_ERROR");
2451                         ast_string_field_set(details, resultstr, "error reading file");
2452                         set_channel_variables(chan, details);
2453                         ast_log(LOG_ERROR, "access failure.  Verify '%s' exists and check permissions.\n", args.filenames);
2454                         return -1;
2455                 }
2456
2457                 if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
2458                         ast_string_field_set(details, error, "MEMORY_ERROR");
2459                         ast_string_field_set(details, resultstr, "error allocating memory");
2460                         set_channel_variables(chan, details);
2461                         ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2462                         return -1;
2463                 }
2464
2465                 strcpy(doc->filename, c);
2466                 AST_LIST_INSERT_TAIL(&details->documents, doc, next);
2467                 file_count++;
2468         }
2469
2470         ast_verb(3, "Channel '%s' sending FAX:\n", ast_channel_name(chan));
2471         AST_LIST_TRAVERSE(&details->documents, doc, next) {
2472                 ast_verb(3, "   %s\n", doc->filename);
2473         }
2474
2475         details->caps = AST_FAX_TECH_SEND;
2476
2477         if (file_count > 1) {
2478                 details->caps |= AST_FAX_TECH_MULTI_DOC;
2479         }
2480
2481         /* check for debug */
2482         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
2483                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
2484         }
2485
2486         /* check for request for status events */
2487         if (ast_test_flag(&opts, OPT_STATUS)) {
2488                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
2489         }
2490
2491         t38state = ast_channel_get_t38_state(chan);
2492         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
2493             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
2494             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2495                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
2496         }
2497
2498         if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
2499                 details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
2500         }
2501
2502         if (!(s = fax_session_reserve(details, &token))) {
2503                 ast_string_field_set(details, resultstr, "error reserving fax session");
2504                 set_channel_variables(chan, details);
2505                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
2506                 return -1;
2507         }
2508
2509         /* make sure the channel is up */
2510         if (ast_channel_state(chan) != AST_STATE_UP) {
2511                 if (ast_answer(chan)) {
2512                         ast_string_field_set(details, resultstr, "error answering channel");
2513                         set_channel_variables(chan, details);
2514                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
2515                         fax_session_release(s, token);
2516                         return -1;
2517                 }
2518         }
2519
2520         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2521                 if (set_fax_t38_caps(chan, details)) {
2522                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2523                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2524                         set_channel_variables(chan, details);
2525                         fax_session_release(s, token);
2526                         return -1;
2527                 }
2528         } else {
2529                 details->caps |= AST_FAX_TECH_AUDIO;
2530         }
2531
2532         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2533                 if (sendfax_t38_init(chan, details)) {
2534                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2535                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2536                         set_channel_variables(chan, details);
2537                         fax_session_release(s, token);
2538                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2539                         return -1;
2540                 }
2541         } else {
2542                 details->option.send_cng = 1;
2543         }
2544
2545         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2546                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2547         }
2548
2549         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2550                 if (disable_t38(chan)) {
2551                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2552                 }
2553         }
2554
2555         if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
2556                 ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
2557                 return (!channel_alive) ? -1 : 0;
2558         }
2559
2560         /* send out the AMI completion event */
2561         if (report_send_fax_status(chan, details)) {
2562                 ast_log(AST_LOG_ERROR, "Error publishing SendFAX status message\n");
2563         }
2564
2565         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2566         return (!channel_alive) ? -1 : 0;
2567 }
2568
2569 /*! \brief destroy the v21 detection parts of a fax gateway session */
2570 static void destroy_v21_sessions(struct fax_gateway *gateway)
2571 {
2572         if (gateway->chan_v21_session) {
2573                 ao2_lock(faxregistry.container);
2574                 ao2_unlink(faxregistry.container, gateway->chan_v21_session);
2575                 ao2_unlock(faxregistry.container);
2576
2577                 ao2_ref(gateway->chan_v21_session, -1);
2578                 gateway->chan_v21_session = NULL;
2579         }
2580
2581         if (gateway->peer_v21_session) {
2582                 ao2_lock(faxregistry.container);
2583                 ao2_unlink(faxregistry.container, gateway->peer_v21_session);
2584                 ao2_unlock(faxregistry.container);
2585
2586                 ao2_ref(gateway->peer_v21_session, -1);
2587                 gateway->peer_v21_session = NULL;
2588         }
2589 }
2590
2591 /*! \brief destroy a FAX gateway session structure */
2592 static void destroy_gateway(void *data)
2593 {
2594         struct fax_gateway *gateway = data;
2595
2596         destroy_v21_sessions(gateway);
2597
2598         if (gateway->s) {
2599                 fax_session_release(gateway->s, gateway->token);
2600                 gateway->token = NULL;
2601
2602                 ao2_lock(faxregistry.container);
2603                 ao2_unlink(faxregistry.container, gateway->s);
2604                 ao2_unlock(faxregistry.container);
2605
2606                 ao2_ref(gateway->s, -1);
2607                 gateway->s = NULL;
2608         }
2609 }
2610
2611 /*! \brief Create a new fax gateway object.
2612  * \param chan the channel the gateway object will be attached to
2613  * \param details the fax session details
2614  * \return NULL or a fax gateway object
2615  */
2616 static struct fax_gateway *fax_gateway_new(struct ast_channel *chan, struct ast_fax_session_details *details)
2617 {
2618         struct fax_gateway *gateway = ao2_alloc(sizeof(*gateway), destroy_gateway);
2619         struct ast_fax_session_details *v21_details;
2620         if (!gateway) {
2621                 return NULL;
2622         }
2623
2624         if (!(v21_details = session_details_new())) {
2625                 ao2_ref(gateway, -1);
2626                 return NULL;
2627         }
2628
2629         v21_details->caps = AST_FAX_TECH_V21_DETECT;
2630         if (!(gateway->chan_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2631                 ao2_ref(v21_details, -1);
2632                 ao2_ref(gateway, -1);
2633                 return NULL;
2634         }
2635
2636         if (!(gateway->peer_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2637                 ao2_ref(v21_details, -1);
2638                 ao2_ref(gateway, -1);
2639                 return NULL;
2640         }
2641         ao2_ref(v21_details, -1);
2642
2643         gateway->framehook = -1;
2644
2645         details->caps = AST_FAX_TECH_GATEWAY;
2646         if (details->gateway_timeout && !(gateway->s = fax_session_reserve(details, &gateway->token))) {
2647                 details->caps &= ~AST_FAX_TECH_GATEWAY;
2648                 ast_log(LOG_ERROR, "Can't reserve a FAX session, gateway attempt failed.\n");
2649                 ao2_ref(gateway, -1);
2650                 return NULL;
2651         }
2652
2653         return gateway;
2654 }
2655
2656 /*! \brief Create a fax session and start T.30<->T.38 gateway mode
2657  * \param gateway a fax gateway object
2658  * \param details fax session details
2659  * \param chan active channel
2660  * \return 0 on error 1 on success*/
2661 static int fax_gateway_start(struct fax_gateway *gateway, struct ast_fax_session_details *details, struct ast_channel *chan)
2662 {
2663         struct ast_fax_session *s;
2664
2665         /* create the FAX session */
2666         if (!(s = fax_session_new(details, chan, gateway->s, gateway->token))) {
2667                 gateway->token = NULL;
2668                 ast_string_field_set(details, result, "FAILED");
2669                 ast_string_field_set(details, resultstr, "error starting gateway session");
2670                 ast_string_field_set(details, error, "INIT_ERROR");
2671                 set_channel_variables(chan, details);
2672                 report_fax_status(chan, details, "No Available Resource");
2673                 ast_log(LOG_ERROR, "Can't create a FAX session, gateway attempt failed.\n");
2674                 return -1;
2675         }
2676         /* release the reference for the reserved session and replace it with
2677          * the real session */
2678         if (gateway->s) {
2679                 ao2_ref(gateway->s, -1);
2680         }
2681         gateway->s = s;
2682         gateway->token = NULL;
2683
2684         if (gateway->s->tech->start_session(gateway->s) < 0) {
2685                 ast_string_field_set(details, result, "FAILED");
2686                 ast_string_field_set(details, resultstr, "error starting gateway session");
2687                 ast_string_field_set(details, error, "INIT_ERROR");
2688                 set_channel_variables(chan, details);
2689                 return -1;
2690         }
2691
2692         gateway->timeout_start.tv_sec = 0;
2693         gateway->timeout_start.tv_usec = 0;
2694
2695         report_fax_status(chan, details, "FAX Transmission In Progress");
2696
2697         return 0;
2698 }
2699
2700 static struct ast_frame *fax_gateway_request_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_frame *f)
2701 {
2702         struct ast_frame *fp;
2703         struct ast_control_t38_parameters t38_parameters = {
2704                 .request_response = AST_T38_REQUEST_NEGOTIATE,
2705         };
2706         struct ast_frame control_frame = {
2707                 .src = "res_fax",
2708                 .frametype = AST_FRAME_CONTROL,
2709                 .datalen = sizeof(t38_parameters),
2710                 .subclass.integer = AST_CONTROL_T38_PARAMETERS,
2711                 .data.ptr = &t38_parameters,
2712         };
2713
2714         struct ast_fax_session_details *details = find_details(chan);
2715
2716         if (!details) {
2717                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2718                 ast_framehook_detach(chan, gateway->framehook);
2719                 return f;
2720         }
2721
2722         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2723         ao2_ref(details, -1);
2724
2725         if (!(fp = ast_frisolate(&control_frame))) {
2726                 ast_log(LOG_ERROR, "error generating T.38 request control frame on chan %s for T.38 gateway session\n", ast_channel_name(chan));
2727                 return f;
2728         }
2729
2730         gateway->t38_state = T38_STATE_NEGOTIATING;
2731         gateway->timeout_start = ast_tvnow();
2732         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2733
2734         ast_debug(1, "requesting T.38 for gateway session for %s\n", ast_channel_name(chan));
2735         return fp;
2736 }
2737
2738 static struct ast_frame *fax_gateway_detect_v21(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *active, struct ast_frame *f)
2739 {
2740         struct ast_channel *other = (active == chan) ? peer : chan;
2741         struct ast_fax_session *active_v21_session = (active == chan) ? gateway->chan_v21_session : gateway->peer_v21_session;
2742
2743         if (!active_v21_session || gateway->detected_v21) {
2744                 return f;
2745         }
2746
2747         if (active_v21_session->tech->write(active_v21_session, f) == 0 &&
2748             active_v21_session->details->option.v21_detected) {
2749                 gateway->detected_v21 = 1;
2750         }
2751
2752         if (gateway->detected_v21) {
2753                 destroy_v21_sessions(gateway);
2754                 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2755                         ast_debug(1, "detected v21 preamble from %s\n", ast_channel_name(active));
2756                         return fax_gateway_request_t38(gateway, chan, f);
2757                 } else {
2758                         ast_debug(1, "detected v21 preamble on %s, but %s does not support T.38 for T.38 gateway session\n", ast_channel_name(active), ast_channel_name(other));
2759                 }
2760         }
2761
2762         return f;
2763 }
2764
2765 static int fax_gateway_indicate_t38(struct ast_channel *chan, struct ast_channel *active, struct ast_control_t38_parameters *control_params)
2766 {
2767         if (active == chan) {
2768                 return ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2769         } else {
2770                 return ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2771         }
2772 }
2773
2774 /*! \brief T38 Gateway Negotiate t38 parameters
2775  * \param gateway gateway object
2776  * \param chan channel running the gateway
2777  * \param peer channel im bridged too
2778  * \param active channel the frame originated on
2779  * \param f the control frame to process
2780  * \return processed control frame or null frame
2781  */
2782 static struct ast_frame *fax_gateway_detect_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *active, struct ast_frame *f)
2783 {
2784         struct ast_control_t38_parameters *control_params = f->data.ptr;
2785         struct ast_channel *other = (active == chan) ? peer : chan;
2786         struct ast_fax_session_details *details;
2787
2788         if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
2789                 /* invalaid AST_CONTROL_T38_PARAMETERS frame, we can't
2790                  * do anything with it, pass it on */
2791                 return f;
2792         }
2793
2794         /* ignore frames from ourselves */
2795         if ((gateway->t38_state == T38_STATE_NEGOTIATED && control_params->request_response == AST_T38_NEGOTIATED)
2796                 || (gateway->t38_state == T38_STATE_REJECTED && control_params->request_response == AST_T38_REFUSED)
2797                 || (gateway->t38_state == T38_STATE_NEGOTIATING && control_params->request_response == AST_T38_REQUEST_TERMINATE)) {
2798
2799                 return f;
2800         }
2801
2802         if (!(details = find_details(chan))) {
2803                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2804                 ast_framehook_detach(chan, gateway->framehook);
2805                 return f;
2806         }
2807
2808         if (control_params->request_response == AST_T38_REQUEST_NEGOTIATE) {
2809                 enum ast_t38_state state = ast_channel_get_t38_state(other);
2810
2811                 if (state == T38_STATE_UNKNOWN) {
2812                         /* we detected a request to negotiate T.38 and the
2813                          * other channel appears to support T.38, we'll pass
2814                          * the request through and only step in if the other
2815                          * channel rejects the request */
2816                         ast_debug(1, "%s is attempting to negotiate T.38 with %s, we'll see what happens\n", ast_channel_name(active), ast_channel_name(other));
2817                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2818                         gateway->t38_state = T38_STATE_UNKNOWN;
2819                         gateway->timeout_start = ast_tvnow();
2820                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2821                         ao2_ref(details, -1);
2822                         return f;
2823                 } else if (state == T38_STATE_UNAVAILABLE || state == T38_STATE_REJECTED) {
2824                         /* the other channel does not support T.38, we need to
2825                          * step in here */
2826                         ast_debug(1, "%s is attempting to negotiate T.38 but %s does not support it\n", ast_channel_name(active), ast_channel_name(other));
2827                         ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2828
2829                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2830                         t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2831
2832                         if (fax_gateway_start(gateway, details, chan)) {
2833                                 ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2834                                 gateway->t38_state = T38_STATE_REJECTED;
2835                                 control_params->request_response = AST_T38_REFUSED;
2836
2837                                 ast_framehook_detach(chan, details->gateway_id);
2838                                 details->gateway_id = -1;
2839                         } else {
2840                                 gateway->t38_state = T38_STATE_NEGOTIATED;
2841                                 control_params->request_response = AST_T38_NEGOTIATED;
2842                                 report_fax_status(chan, details, "T.38 Negotiated");
2843                         }
2844
2845                         fax_gateway_indicate_t38(chan, active, control_params);
2846
2847                         ao2_ref(details, -1);
2848                         return &ast_null_frame;
2849                 } else if (gateway->t38_state == T38_STATE_NEGOTIATING) {
2850                         /* we got a request to negotiate T.38 after we already
2851                          * sent one to the other party based on v21 preamble
2852                          * detection. We'll just pretend we passed this request
2853                          * through in the first place. */
2854
2855                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2856                         gateway->t38_state = T38_STATE_UNKNOWN;
2857                         gateway->timeout_start = ast_tvnow();
2858                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2859
2860                         ast_debug(1, "%s is attempting to negotiate T.38 after we already sent a negotiation request based on v21 preamble detection\n", ast_channel_name(active));
2861                         ao2_ref(details, -1);
2862                         return &ast_null_frame;
2863                 } else if (gateway->t38_state == T38_STATE_NEGOTIATED) {
2864                         /* we got a request to negotiate T.38 after we already
2865                          * sent one to the other party based on v21 preamble
2866                          * detection and received a response. We need to
2867                          * respond to this and shut down the gateway. */
2868
2869                         t38_parameters_fax_to_ast(control_params, &details->their_t38_parameters);
2870                         ast_framehook_detach(chan, details->gateway_id);
2871                         details->gateway_id = -1;
2872
2873                         control_params->request_response = AST_T38_NEGOTIATED;
2874
2875                         fax_gateway_indicate_t38(chan, active, control_params);
2876
2877                         ast_string_field_set(details, result, "SUCCESS");
2878                         ast_string_field_set(details, resultstr, "no gateway necessary");
2879                         ast_string_field_set(details, error, "NATIVE_T38");
2880                         set_channel_variables(chan, details);
2881
2882                         ast_debug(1, "%s is attempting to negotiate T.38 after we already negotiated T.38 with %s, disabling the gateway\n", ast_channel_name(active), ast_channel_name(other));
2883                         ao2_ref(details, -1);
2884                         return &ast_null_frame;
2885                 } else {
2886                         ast_log(LOG_WARNING, "%s is attempting to negotiate T.38 while %s is in an unsupported state\n", ast_channel_name(active), ast_channel_name(other));
2887                         ao2_ref(details, -1);
2888                         return f;
2889                 }
2890         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2891                 && control_params->request_response == AST_T38_REFUSED) {
2892
2893                 ast_debug(1, "unable to negotiate T.38 on %s for fax gateway\n", ast_channel_name(active));
2894
2895                 /* our request to negotiate T.38 was refused, if the other
2896                  * channel supports T.38, they might still reinvite and save
2897                  * the day.  Otherwise disable the gateway. */
2898                 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2899                         gateway->t38_state = T38_STATE_UNAVAILABLE;
2900                 } else {
2901                         ast_framehook_detach(chan, details->gateway_id);
2902                         details->gateway_id = -1;
2903
2904                         ast_string_field_set(details, result, "FAILED");
2905                         ast_string_field_set(details, resultstr, "unable to negotiate T.38");
2906                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2907                         set_channel_variables(chan, details);
2908                 }
2909
2910                 ao2_ref(details, -1);
2911                 return &ast_null_frame;
2912         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2913                 && control_params->request_response == AST_T38_NEGOTIATED) {
2914
2915                 ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2916
2917                 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2918
2919                 if (fax_gateway_start(gateway, details, chan)) {
2920                         ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2921                         gateway->t38_state = T38_STATE_NEGOTIATING;
2922                         control_params->request_response = AST_T38_REQUEST_TERMINATE;
2923
2924                         fax_gateway_indicate_t38(chan, active, control_params);
2925                 } else {
2926                         gateway->t38_state = T38_STATE_NEGOTIATED;
2927                         report_fax_status(chan, details, "T.38 Negotiated");
2928                 }
2929
2930                 ao2_ref(details, -1);
2931                 return &ast_null_frame;
2932         } else if (control_params->request_response == AST_T38_REFUSED) {
2933                 /* the other channel refused the request to negotiate T.38,
2934                  * we'll step in here and pretend the request was accepted */
2935
2936                 ast_debug(1, "%s attempted to negotiate T.38 but %s refused the request\n", ast_channel_name(other), ast_channel_name(active));
2937                 ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(other), ast_channel_name(active));
2938
2939                 t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2940
2941                 if (fax_gateway_start(gateway, details, chan)) {
2942                         ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2943                         gateway->t38_state = T38_STATE_REJECTED;
2944                         control_params->request_response = AST_T38_REFUSED;
2945
2946                         ast_framehook_detach(chan, details->gateway_id);
2947                         details->gateway_id = -1;
2948                 } else {
2949                         gateway->t38_state = T38_STATE_NEGOTIATED;
2950                         control_params->request_response = AST_T38_NEGOTIATED;
2951                 }
2952
2953                 ao2_ref(details, -1);
2954                 return f;
2955         } else if (control_params->request_response == AST_T38_REQUEST_TERMINATE) {
2956                 /* the channel wishes to end our short relationship, we shall
2957                  * oblige */
2958
2959                 ast_debug(1, "T.38 channel %s is requesting a shutdown of T.38, disabling the gateway\n", ast_channel_name(active));
2960
2961                 ast_framehook_detach(chan, details->gateway_id);
2962                 details->gateway_id = -1;
2963
2964                 gateway->t38_state = T38_STATE_REJECTED;
2965                 control_params->request_response = AST_T38_TERMINATED;
2966
2967                 fax_gateway_indicate_t38(chan, active, control_params);
2968
2969                 ao2_ref(details, -1);
2970                 return &ast_null_frame;
2971         } else if (control_params->request_response == AST_T38_NEGOTIATED) {
2972                 ast_debug(1, "T.38 successfully negotiated between %s and %s, no gateway necessary\n", ast_channel_name(active), ast_channel_name(other));
2973
2974                 ast_framehook_detach(chan, details->gateway_id);
2975                 details->gateway_id = -1;
2976
2977                 ast_string_field_set(details, result, "SUCCESS");
2978                 ast_string_field_set(details, resultstr, "no gateway necessary");
2979                 ast_string_field_set(details, error, "NATIVE_T38");
2980                 set_channel_variables(chan, details);
2981
2982                 ao2_ref(details, -1);
2983                 return f;
2984         } else if (control_params->request_response == AST_T38_TERMINATED) {
2985                 ast_debug(1, "T.38 disabled on channel %s\n", ast_channel_name(active));
2986
2987                 ast_framehook_detach(chan, details->gateway_id);
2988                 details->gateway_id = -1;
2989
2990                 ao2_ref(details, -1);
2991                 return &ast_null_frame;
2992         }
2993
2994         ao2_ref(details, -1);
2995         return f;
2996 }
2997
2998 /*! \brief Destroy the gateway data structure when the framehook is detached
2999  * \param data framehook data (gateway data)*/
3000 static void fax_gateway_framehook_destroy(void *data) {
3001         struct fax_gateway *gateway = data;
3002
3003         if (gateway->s) {
3004                 switch (gateway->s->state) {
3005                 case AST_FAX_STATE_INITIALIZED:
3006                 case AST_FAX_STATE_OPEN:
3007                 case AST_FAX_STATE_ACTIVE:
3008                 case AST_FAX_STATE_COMPLETE:
3009                         if (gateway->s->tech->cancel_session) {
3010                                 gateway->s->tech->cancel_session(gateway->s);
3011                         }
3012                         /* fall through */
3013                 default:
3014                         break;
3015                 }
3016         }
3017
3018         ao2_ref(gateway, -1);
3019 }
3020
3021 /*! \brief T.30<->T.38 gateway framehook.
3022  *
3023  * Intercept packets on bridged channels and determine if a T.38 gateway is
3024  * required. If a gateway is required, start a gateway and handle T.38
3025  * negotiation if necessary.
3026  *
3027  * \param chan channel running the gateway
3028  * \param f frame to handle may be NULL
3029  * \param event framehook event
3030  * \param data framehook data (struct fax_gateway *)
3031  *
3032  * \return processed frame or NULL when f is NULL or a null frame
3033  */
3034 static struct ast_frame *fax_gateway_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
3035         struct fax_gateway *gateway = data;
3036         struct ast_channel *active;
3037         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
3038         RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
3039         RAII_VAR(struct ast_channel *, chan_ref, chan, ao2_cleanup);
3040
3041         /* Ref bump channel for when we have to unlock it */
3042         ao2_ref(chan_ref, 1);
3043
3044         if (gateway->s) {
3045                 details = gateway->s->details;
3046                 ao2_ref(details, 1);
3047         } else {
3048                 if (!(details = find_details(chan))) {