6341a55ff182bc8e52eb1c106669d0748d7d121f
[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 2400
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_V27 | 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         case 9600:
722                 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
723                         return 1;
724                 }
725                 break;
726         case 12000:
727         case 14400:
728                 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V34))) {
729                         return 1;
730                 }
731                 break;
732         case 28800:
733         case 33600:
734                 if (!(modems & AST_FAX_MODEM_V34)) {
735                         return 1;
736                 }
737                 break;
738         default:
739                 /* this should never happen */
740                 return 1;
741         }
742
743         return 0;
744 }
745
746 /*! \brief register a FAX technology module */
747 int ast_fax_tech_register(struct ast_fax_tech *tech)
748 {
749         struct fax_module *fax;
750
751         if (!(fax = ast_calloc(1, sizeof(*fax)))) {
752                 return -1;
753         }
754         fax->tech = tech;
755         AST_RWLIST_WRLOCK(&faxmodules);
756         AST_RWLIST_INSERT_TAIL(&faxmodules, fax, list);
757         AST_RWLIST_UNLOCK(&faxmodules);
758         ast_module_ref(ast_module_info->self);
759
760         ast_verb(3, "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
761
762         return 0;
763 }
764
765 /*! \brief unregister a FAX technology module */
766 void ast_fax_tech_unregister(struct ast_fax_tech *tech)
767 {
768         struct fax_module *fax;
769
770         ast_verb(3, "Unregistering FAX module type '%s'\n", tech->type);
771
772         AST_RWLIST_WRLOCK(&faxmodules);
773         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
774                 if (fax->tech != tech) {
775                         continue;
776                 }
777                 AST_RWLIST_REMOVE_CURRENT(list);
778                 ast_module_unref(ast_module_info->self);
779                 ast_free(fax);
780                 ast_verb(4, "Unregistered FAX module type '%s'\n", tech->type);
781                 break;
782         }
783         AST_RWLIST_TRAVERSE_SAFE_END;
784         AST_RWLIST_UNLOCK(&faxmodules);
785 }
786
787 /*! \brief convert a ast_fax_state to a string */
788 const char *ast_fax_state_to_str(enum ast_fax_state state)
789 {
790         switch (state) {
791         case AST_FAX_STATE_UNINITIALIZED:
792                 return "Uninitialized";
793         case AST_FAX_STATE_INITIALIZED:
794                 return "Initialized";
795         case AST_FAX_STATE_OPEN:
796                 return "Open";
797         case AST_FAX_STATE_ACTIVE:
798                 return "Active";
799         case AST_FAX_STATE_COMPLETE:
800                 return "Complete";
801         case AST_FAX_STATE_RESERVED:
802                 return "Reserved";
803         case AST_FAX_STATE_INACTIVE:
804                 return "Inactive";
805         default:
806                 ast_log(LOG_WARNING, "unhandled FAX state: %d\n", state);
807                 return "Unknown";
808         }
809 }
810
811 void ast_fax_log(int level, const char *file, const int line, const char *function, const char *msg)
812 {
813         if (fax_logger_level != -1) {
814                 ast_log_dynamic_level(fax_logger_level, "%s", msg);
815         } else {
816                 ast_log(level, file, line, function, "%s", msg);
817         }
818 }
819
820 /*! \brief convert a rate string to a rate */
821 static unsigned int fax_rate_str_to_int(const char *ratestr)
822 {
823         int rate;
824
825         if (sscanf(ratestr, "%d", &rate) != 1) {
826                 ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
827                 return 0;
828         }
829         switch (rate) {
830         case 2400:
831         case 4800:
832         case 7200:
833         case 9600:
834         case 12000:
835         case 14400:
836         case 28800:
837         case 33600:
838                 return rate;
839         default:
840                 ast_log(LOG_WARNING, "ignoring invalid rate '%s'.  Valid options are {2400 | 4800 | 7200 | 9600 | 12000 | 14400 | 28800 | 33600}\n", ratestr);
841                 return 0;
842         }
843 }
844
845 /*! \brief Release a session token.
846  * \param s a session returned from fax_session_reserve()
847  * \param token a token generated from fax_session_reserve()
848  *
849  * This function releases the given token and marks the given session as no
850  * longer reserved. It is safe to call on a session that is not actually
851  * reserved and with a NULL token. This is so that sessions returned by
852  * technologies that do not support reserved sessions don't require extra logic
853  * to handle.
854  *
855  * \note This function DOES NOT release the given fax session, only the given
856  * token.
857  */
858 static void fax_session_release(struct ast_fax_session *s, struct ast_fax_tech_token *token)
859 {
860         if (token) {
861                 s->tech->release_token(token);
862         }
863
864         if (s->state == AST_FAX_STATE_RESERVED) {
865                 ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
866                 s->state = AST_FAX_STATE_INACTIVE;
867         }
868 }
869
870 /*! \brief destroy a FAX session structure */
871 static void destroy_session(void *session)
872 {
873         struct ast_fax_session *s = session;
874
875         if (s->tech) {
876                 fax_session_release(s, NULL);
877                 if (s->tech_pvt) {
878                         s->tech->destroy_session(s);
879                 }
880                 ast_module_unref(s->tech->module);
881         }
882
883         if (s->details) {
884                 if (s->details->caps & AST_FAX_TECH_GATEWAY) {
885                         s->details->caps &= ~AST_FAX_TECH_GATEWAY;
886                 }
887                 ao2_ref(s->details, -1);
888         }
889
890         if (s->debug_info) {
891                 ast_dsp_free(s->debug_info->dsp);
892                 ast_free(s->debug_info);
893         }
894
895         if (s->smoother) {
896                 ast_smoother_free(s->smoother);
897         }
898
899         if (s->state != AST_FAX_STATE_INACTIVE) {
900                 ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
901         }
902
903         ast_free(s->channame);
904         ast_free(s->chan_uniqueid);
905 }
906
907 /*! \brief Reserve a fax session.
908  * \param details the fax session details
909  * \param token a pointer to a place to store a token to be passed to fax_session_new() later
910  *
911  * This function reserves a fax session for use later. If the selected fax
912  * technology does not support reserving sessions a session will still be
913  * returned but token will not be set.
914  *
915  * \note The reference returned by this function does not get consumed by
916  * fax_session_new() and must always be dereferenced separately.
917  *
918  * \return NULL or an uninitialized and possibly reserved session
919  */
920 static struct ast_fax_session *fax_session_reserve(struct ast_fax_session_details *details, struct ast_fax_tech_token **token)
921 {
922         struct ast_fax_session *s;
923         struct fax_module *faxmod;
924
925         if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
926                 return NULL;
927         }
928
929         s->state = AST_FAX_STATE_INACTIVE;
930         s->details = details;
931         ao2_ref(s->details, 1);
932
933         /* locate a FAX technology module that can handle said requirements
934          * Note: the requirements have not yet been finalized as T.38
935          * negotiation has not yet occured. */
936         AST_RWLIST_RDLOCK(&faxmodules);
937         AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
938                 if ((faxmod->tech->caps & details->caps) != details->caps) {
939                         continue;
940                 }
941                 ast_debug(4, "Reserving a FAX session from '%s'.\n", faxmod->tech->description);
942                 ast_module_ref(faxmod->tech->module);
943                 s->tech = faxmod->tech;
944                 break;
945         }
946         AST_RWLIST_UNLOCK(&faxmodules);
947
948         if (!faxmod) {
949                 char caps[128] = "";
950                 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)));
951                 ao2_ref(s, -1);
952                 return NULL;
953         }
954
955         if (!s->tech->reserve_session) {
956                 ast_debug(1, "Selected FAX technology module (%s) does not support reserving sessions.\n", s->tech->description);
957                 return s;
958         }
959
960         if (!(*token = s->tech->reserve_session(s))) {
961                 ao2_ref(s, -1);
962                 return NULL;
963         }
964
965         s->state = AST_FAX_STATE_RESERVED;
966         ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, 1);
967
968         return s;
969 }
970
971 /*! \brief create a FAX session
972  *
973  * \param details details for the session
974  * \param chan the channel the session will run on
975  * \param reserved a reserved session to base this session on (can be NULL)
976  * \param token the token for a reserved session (can be NULL)
977  *
978  * Create a new fax session based on the given details structure.
979  *
980  * \note The given token is always consumed (by tech->new_session() or by
981  * fax_session_release() in the event of a failure). The given reference to a
982  * reserved session is never consumed and must be dereferenced separately from
983  * the reference returned by this function.
984  *
985  * \return NULL or a reference to a new fax session
986  */
987 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)
988 {
989         struct ast_fax_session *s = NULL;
990         struct fax_module *faxmod;
991
992         if (reserved) {
993                 s = reserved;
994                 ao2_ref(reserved, +1);
995
996                 /* NOTE: we don't consume the reference to the reserved
997                  * session. The session returned from fax_session_new() is a
998                  * new reference and must be derefed in addition to the
999                  * reserved session.
1000                  */
1001
1002                 if (s->state == AST_FAX_STATE_RESERVED) {
1003                         ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
1004                         s->state = AST_FAX_STATE_UNINITIALIZED;
1005                 }
1006         }
1007
1008         if (!s && !(s = ao2_alloc(sizeof(*s), destroy_session))) {
1009                 return NULL;
1010         }
1011
1012         ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
1013         s->state = AST_FAX_STATE_UNINITIALIZED;
1014
1015         if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
1016                 if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
1017                         fax_session_release(s, token);
1018                         ao2_ref(s, -1);
1019                         return NULL;
1020                 }
1021                 if (!(s->debug_info->dsp = ast_dsp_new())) {
1022                         ast_free(s->debug_info);
1023                         s->debug_info = NULL;
1024                         fax_session_release(s, token);
1025                         ao2_ref(s, -1);
1026                         return NULL;
1027                 }
1028                 ast_dsp_set_threshold(s->debug_info->dsp, 128);
1029         }
1030
1031         if (!(s->channame = ast_strdup(ast_channel_name(chan)))) {
1032                 fax_session_release(s, token);
1033                 ao2_ref(s, -1);
1034                 return NULL;
1035         }
1036
1037         if (!(s->chan_uniqueid = ast_strdup(ast_channel_uniqueid(chan)))) {
1038                 fax_session_release(s, token);
1039                 ao2_ref(s, -1);
1040                 return NULL;
1041         }
1042
1043         s->chan = chan;
1044         if (!s->details) {
1045                 s->details = details;
1046                 ao2_ref(s->details, 1);
1047         }
1048
1049         details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
1050
1051         if (!token) {
1052                 /* locate a FAX technology module that can handle said requirements */
1053                 AST_RWLIST_RDLOCK(&faxmodules);
1054                 AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
1055                         if ((faxmod->tech->caps & details->caps) != details->caps) {
1056                                 continue;
1057                         }
1058                         ast_debug(4, "Requesting a new FAX session from '%s'.\n", faxmod->tech->description);
1059                         ast_module_ref(faxmod->tech->module);
1060                         s->tech = faxmod->tech;
1061                         break;
1062                 }
1063                 AST_RWLIST_UNLOCK(&faxmodules);
1064
1065                 if (!faxmod) {
1066                         char caps[128] = "";
1067                         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)));
1068                         ao2_ref(s, -1);
1069                         return NULL;
1070                 }
1071         }
1072
1073         if (!(s->tech_pvt = s->tech->new_session(s, token))) {
1074                 ast_log(LOG_ERROR, "FAX session failed to initialize.\n");
1075                 ao2_ref(s, -1);
1076                 return NULL;
1077         }
1078         /* link the session to the session container */
1079         if (!(ao2_link(faxregistry.container, s))) {
1080                 ast_log(LOG_ERROR, "failed to add FAX session '%d' to container.\n", s->id);
1081                 ao2_ref(s, -1);
1082                 return NULL;
1083         }
1084         ast_debug(4, "channel '%s' using FAX session '%d'\n", s->channame, s->id);
1085
1086         return s;
1087 }
1088
1089 /*!
1090  * \internal
1091  * \brief Convert the filenames in a fax session into a JSON array
1092  * \retval NULL on error
1093  * \retval A \ref ast_json array on success
1094  */
1095 static struct ast_json *generate_filenames_json(struct ast_fax_session_details *details)
1096 {
1097         RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
1098         struct ast_fax_document *doc;
1099
1100         if (!details || !json_array) {
1101                 return NULL;
1102         }
1103
1104         /* don't process empty lists */
1105         if (AST_LIST_EMPTY(&details->documents)) {
1106                 return NULL;
1107         }
1108
1109         AST_LIST_TRAVERSE(&details->documents, doc, next) {
1110                 struct ast_json *entry = ast_json_string_create(doc->filename);
1111                 if (!entry) {
1112                         return NULL;
1113                 }
1114                 if (ast_json_array_append(json_array, entry)) {
1115                         return NULL;
1116                 }
1117         }
1118
1119         ast_json_ref(json_array);
1120         return json_array;
1121 }
1122
1123 /* \brief Generate a string of filenames using the given prefix and separator.
1124  * \param details the fax session details
1125  * \param prefix the prefix to each filename
1126  * \param separator the separator between filenames
1127  *
1128  * This function generates a string of filenames from the given details
1129  * structure and using the given prefix and separator.
1130  *
1131  * \retval NULL there was an error generating the string
1132  * \return the string generated string
1133  */
1134 static char *generate_filenames_string(struct ast_fax_session_details *details, char *prefix, char *separator)
1135 {
1136         char *filenames, *c;
1137         size_t size = 0;
1138         int first = 1;
1139         struct ast_fax_document *doc;
1140
1141         /* don't process empty lists */
1142         if (AST_LIST_EMPTY(&details->documents)) {
1143                 return NULL;
1144         }
1145
1146         /* Calculate the total length of all of the file names */
1147         AST_LIST_TRAVERSE(&details->documents, doc, next) {
1148                 size += strlen(separator) + strlen(prefix) + strlen(doc->filename);
1149         }
1150         size += 1; /* add space for the terminating null */
1151
1152         if (!(filenames = ast_malloc(size))) {
1153                 return NULL;
1154         }
1155         c = filenames;
1156
1157         ast_build_string(&c, &size, "%s%s", prefix, AST_LIST_FIRST(&details->documents)->filename);
1158         AST_LIST_TRAVERSE(&details->documents, doc, next) {
1159                 if (first) {
1160                         first = 0;
1161                         continue;
1162                 }
1163
1164                 ast_build_string(&c, &size, "%s%s%s", separator, prefix, doc->filename);
1165         }
1166
1167         return filenames;
1168 }
1169
1170 /*! \brief send a FAX status manager event */
1171 static int report_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details, const char *status)
1172 {
1173         RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
1174         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1175         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1176         struct ast_json *json_filenames = NULL;
1177
1178         if (!details->option.statusevents) {
1179                 return 0;
1180         }
1181
1182         json_filenames = generate_filenames_json(details);
1183         if (!json_filenames) {
1184                 return -1;
1185         }
1186
1187         json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: o}",
1188                         "type", "status",
1189                         "operation", (details->caps & AST_FAX_TECH_GATEWAY) ? "gateway" : (details->caps & AST_FAX_TECH_RECEIVE) ? "receive" : "send",
1190                         "status", status,
1191                         "local_station_id", details->localstationid,
1192                         "filenames", json_filenames);
1193         if (!json_object) {
1194                 return -1;
1195         }
1196
1197         {
1198                 SCOPED_CHANNELLOCK(lock, chan);
1199
1200                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
1201                 if (!message) {
1202                         return -1;
1203                 }
1204                 stasis_publish(ast_channel_topic(chan), message);
1205         }
1206         return 0;
1207 }
1208
1209 /*! \brief Set fax related channel variables. */
1210 static void set_channel_variables(struct ast_channel *chan, struct ast_fax_session_details *details)
1211 {
1212         char buf[10];
1213         pbx_builtin_setvar_helper(chan, "FAXSTATUS", S_OR(details->result, NULL));
1214         pbx_builtin_setvar_helper(chan, "FAXERROR", S_OR(details->error, NULL));
1215         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", S_OR(details->resultstr, NULL));
1216         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", S_OR(details->remotestationid, NULL));
1217         pbx_builtin_setvar_helper(chan, "LOCALSTATIONID", S_OR(details->localstationid, NULL));
1218         pbx_builtin_setvar_helper(chan, "FAXBITRATE", S_OR(details->transfer_rate, NULL));
1219         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", S_OR(details->resolution, NULL));
1220
1221         snprintf(buf, sizeof(buf), "%d", details->pages_transferred);
1222         pbx_builtin_setvar_helper(chan, "FAXPAGES", buf);
1223 }
1224
1225 #define GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason) \
1226         do {    \
1227                 if (ast_strlen_zero(fax->details->result)) \
1228                         ast_string_field_set(fax->details, result, "FAILED"); \
1229                 if (ast_strlen_zero(fax->details->resultstr)) \
1230                         ast_string_field_set(fax->details, resultstr, reason); \
1231                 if (ast_strlen_zero(fax->details->error)) \
1232                         ast_string_field_set(fax->details, error, errorstr); \
1233                 set_channel_variables(chan, fax->details); \
1234         } while (0)
1235
1236 #define GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason) \
1237         do {    \
1238                 GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason); \
1239         } while (0)
1240
1241 #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason)     \
1242         do {    \
1243                 ast_log(LOG_ERROR, "channel '%s' FAX session '%d' failure, reason: '%s' (%s)\n", ast_channel_name(chan), fax->id, reason, errorstr); \
1244                 GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason); \
1245         } while (0)
1246
1247 static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
1248 {
1249         switch (ast_channel_get_t38_state(chan)) {
1250         case T38_STATE_UNKNOWN:
1251                 details->caps |= AST_FAX_TECH_T38;
1252                 break;
1253         case T38_STATE_REJECTED:
1254         case T38_STATE_UNAVAILABLE:
1255                 details->caps |= AST_FAX_TECH_AUDIO;
1256                 break;
1257         case T38_STATE_NEGOTIATED:
1258                 /* already in T.38 mode? This should not happen. */
1259         case T38_STATE_NEGOTIATING: {
1260                 /* the other end already sent us a T.38 reinvite, so we need to prod the channel
1261                  * driver into resending their parameters to us if it supports doing so... if
1262                  * not, we can't proceed, because we can't create a proper reply without them.
1263                  * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
1264                  * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
1265                  * that gets called after this one completes
1266                  */
1267                 struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
1268                 if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
1269                         ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1270                         return -1;
1271                 }
1272                 details->caps |= AST_FAX_TECH_T38;
1273                 break;
1274         }
1275         default:
1276                 ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1277                 return -1;
1278         }
1279
1280         return 0;
1281 }
1282
1283 static int disable_t38(struct ast_channel *chan)
1284 {
1285         int timeout_ms;
1286         struct ast_frame *frame = NULL;
1287         struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
1288         struct timeval start;
1289         int ms;
1290
1291         ast_debug(1, "Shutting down T.38 on %s\n", ast_channel_name(chan));
1292         if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
1293                 ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1294                 return -1;
1295         }
1296
1297         /* wait up to five seconds for negotiation to complete */
1298         timeout_ms = 5000;
1299         start = ast_tvnow();
1300         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1301                 ms = ast_waitfor(chan, ms);
1302
1303                 if (ms == 0) {
1304                         break;
1305                 }
1306                 if (ms < 0) {
1307                         ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1308                         return -1;
1309                 }
1310
1311                 if (!(frame = ast_read(chan))) {
1312                         return -1;
1313                 }
1314                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1315                     (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1316                     (frame->datalen == sizeof(t38_parameters))) {
1317                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1318
1319                         switch (parameters->request_response) {
1320                         case AST_T38_TERMINATED:
1321                                 ast_debug(1, "Shut down T.38 on %s\n", ast_channel_name(chan));
1322                                 break;
1323                         case AST_T38_REFUSED:
1324                                 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", ast_channel_name(chan));
1325                                 ast_frfree(frame);
1326                                 return -1;
1327                         default:
1328                                 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", ast_channel_name(chan));
1329                                 ast_frfree(frame);
1330                                 return -1;
1331                         }
1332                         ast_frfree(frame);
1333                         break;
1334                 }
1335                 ast_frfree(frame);
1336         }
1337
1338         if (ms == 0) { /* all done, nothing happened */
1339                 ast_debug(1, "channel '%s' timed-out during T.38 shutdown\n", ast_channel_name(chan));
1340         }
1341
1342         return 0;
1343 }
1344
1345 /*! \brief this is the generic FAX session handling function */
1346 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)
1347 {
1348         int ms;
1349         int timeout = RES_FAX_TIMEOUT;
1350         int chancount;
1351         unsigned int expected_frametype = -1;
1352         union ast_frame_subclass expected_framesubclass = { .integer = -1 };
1353         unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
1354         struct ast_control_t38_parameters t38_parameters;
1355         const char *tempvar;
1356         struct ast_fax_session *fax = NULL;
1357         struct ast_frame *frame = NULL;
1358         struct ast_channel *c = chan;
1359         struct ast_format orig_write_format;
1360         struct ast_format orig_read_format;
1361         int remaining_time;
1362         struct timeval start;
1363
1364         ast_format_clear(&orig_write_format);
1365         ast_format_clear(&orig_read_format);
1366         chancount = 1;
1367
1368         /* create the FAX session */
1369         if (!(fax = fax_session_new(details, chan, reserved, token))) {
1370                 ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
1371                 report_fax_status(chan, details, "No Available Resource");
1372                 return -1;
1373         }
1374
1375         ast_channel_lock(chan);
1376         /* update session details */
1377         if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
1378                 ast_string_field_set(details, headerinfo, tempvar);
1379         }
1380         if (ast_strlen_zero(details->localstationid)) {
1381                 tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
1382                 ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
1383         }
1384         ast_channel_unlock(chan);
1385
1386         report_fax_status(chan, details, "Allocating Resources");
1387
1388         if (details->caps & AST_FAX_TECH_AUDIO) {
1389                 expected_frametype = AST_FRAME_VOICE;;
1390                 ast_format_set(&expected_framesubclass.format, AST_FORMAT_SLINEAR, 0);
1391                 ast_format_copy(&orig_write_format, ast_channel_writeformat(chan));
1392                 if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1393                         ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", ast_channel_name(chan));
1394                         ao2_lock(faxregistry.container);
1395                         ao2_unlink(faxregistry.container, fax);
1396                         ao2_unlock(faxregistry.container);
1397                         ao2_ref(fax, -1);
1398                         ast_channel_unlock(chan);
1399                         return -1;
1400                 }
1401                 ast_format_copy(&orig_read_format, ast_channel_readformat(chan));
1402                 if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1403                         ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", ast_channel_name(chan));
1404                         ao2_lock(faxregistry.container);
1405                         ao2_unlink(faxregistry.container, fax);
1406                         ao2_unlock(faxregistry.container);
1407                         ao2_ref(fax, -1);
1408                         ast_channel_unlock(chan);
1409                         return -1;
1410                 }
1411                 if (fax->smoother) {
1412                         ast_smoother_free(fax->smoother);
1413                         fax->smoother = NULL;
1414                 }
1415                 if (!(fax->smoother = ast_smoother_new(320))) {
1416                         ast_log(LOG_WARNING, "Channel '%s' FAX session '%d' failed to obtain a smoother.\n", ast_channel_name(chan), fax->id);
1417                 }
1418         } else {
1419                 expected_frametype = AST_FRAME_MODEM;
1420                 expected_framesubclass.integer = AST_MODEM_T38;
1421         }
1422
1423         if (fax->debug_info) {
1424                 fax->debug_info->base_tv = ast_tvnow();
1425         }
1426
1427         /* reset our result fields just in case the fax tech driver wants to
1428          * set custom error messages */
1429         ast_string_field_set(details, result, "");
1430         ast_string_field_set(details, resultstr, "");
1431         ast_string_field_set(details, error, "");
1432         set_channel_variables(chan, details);
1433
1434         if (fax->tech->start_session(fax) < 0) {
1435                 GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
1436         }
1437
1438         report_fax_status(chan, details, "FAX Transmission In Progress");
1439
1440         ast_debug(5, "channel %s will wait on FAX fd %d\n", ast_channel_name(chan), fax->fd);
1441
1442         /* handle frames for the session */
1443         remaining_time = timeout;
1444         start = ast_tvnow();
1445         while (remaining_time > 0) {
1446                 struct ast_channel *ready_chan;
1447                 int ofd, exception;
1448
1449                 ms = 1000;
1450                 errno = 0;
1451                 ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
1452                 if (ready_chan) {
1453                         if (!(frame = ast_read(chan))) {
1454                                 /* the channel is probably gone, so lets stop polling on it and let the
1455                                  * FAX session complete before we exit the application.  if needed,
1456                                  * send the FAX stack silence so the modems can finish their session without
1457                                  * any problems */
1458                                 ast_debug(1, "Channel '%s' did not return a frame; probably hung up.\n", ast_channel_name(chan));
1459                                 GENERIC_FAX_EXEC_SET_VARS(fax, chan, "HANGUP", "remote channel hungup");
1460                                 c = NULL;
1461                                 chancount = 0;
1462                                 remaining_time = ast_remaining_ms(start, timeout);
1463                                 fax->tech->cancel_session(fax);
1464                                 if (fax->tech->generate_silence) {
1465                                         fax->tech->generate_silence(fax);
1466                                 }
1467                                 continue;
1468                         }
1469
1470                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1471                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1472                             (frame->datalen == sizeof(t38_parameters))) {
1473                                 unsigned int was_t38 = t38negotiated;
1474                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1475
1476                                 switch (parameters->request_response) {
1477                                 case AST_T38_REQUEST_NEGOTIATE:
1478                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1479                                          * do T.38 as well
1480                                          */
1481                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1482                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1483                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1484                                         break;
1485                                 case AST_T38_NEGOTIATED:
1486                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1487                                         t38negotiated = 1;
1488                                         break;
1489                                 default:
1490                                         break;
1491                                 }
1492                                 if (t38negotiated && !was_t38) {
1493                                         fax->tech->switch_to_t38(fax);
1494                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1495                                         expected_frametype = AST_FRAME_MODEM;
1496                                         expected_framesubclass.integer = AST_MODEM_T38;
1497                                         if (fax->smoother) {
1498                                                 ast_smoother_free(fax->smoother);
1499                                                 fax->smoother = NULL;
1500                                         }
1501
1502                                         report_fax_status(chan, details, "T.38 Negotiated");
1503
1504                                         ast_verb(3, "Channel '%s' switched to T.38 FAX session '%d'.\n", ast_channel_name(chan), fax->id);
1505                                 }
1506                         } else if ((frame->frametype == expected_frametype) &&
1507                                    (!memcmp(&frame->subclass, &expected_framesubclass, sizeof(frame->subclass)))) {
1508                                 struct ast_frame *f;
1509
1510                                 if (fax->smoother) {
1511                                         /* push the frame into a smoother */
1512                                         if (ast_smoother_feed(fax->smoother, frame) < 0) {
1513                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
1514                                         }
1515                                         while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
1516                                                 if (fax->debug_info) {
1517                                                         debug_check_frame_for_silence(fax, 1, f);
1518                                                 }
1519                                                 /* write the frame to the FAX stack */
1520                                                 fax->tech->write(fax, f);
1521                                                 fax->frames_received++;
1522                                                 if (f != frame) {
1523                                                         ast_frfree(f);
1524                                                 }
1525                                         }
1526                                 } else {
1527                                         /* write the frame to the FAX stack */
1528                                         fax->tech->write(fax, frame);
1529                                         fax->frames_received++;
1530                                 }
1531                                 start = ast_tvnow();
1532                         }
1533                         ast_frfree(frame);
1534                 } else if (ofd == fax->fd) {
1535                         /* read a frame from the FAX stack and send it out the channel.
1536                          * the FAX stack will return a NULL if the FAX session has already completed */
1537                         if (!(frame = fax->tech->read(fax))) {
1538                                 break;
1539                         }
1540
1541                         if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
1542                                 debug_check_frame_for_silence(fax, 0, frame);
1543                         }
1544
1545                         ast_write(chan, frame);
1546                         fax->frames_sent++;
1547                         ast_frfree(frame);
1548                         start = ast_tvnow();
1549                 } else {
1550                         if (ms && (ofd < 0)) {
1551                                 if ((errno == 0) || (errno == EINTR)) {
1552                                         remaining_time = ast_remaining_ms(start, timeout);
1553                                         if (remaining_time <= 0)
1554                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1555                                         continue;
1556                                 } else {
1557                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(chan));
1558                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "error polling data");
1559                                         break;
1560                                 }
1561                         } else {
1562                                 /* nothing happened */
1563                                 remaining_time = ast_remaining_ms(start, timeout);
1564                                 if (remaining_time <= 0) {
1565                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1566                                         break;
1567                                 }
1568                         }
1569                 }
1570         }
1571         ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, remaining_time: %d }\n", ast_channel_name(chan), timeout, remaining_time);
1572
1573         set_channel_variables(chan, details);
1574
1575         ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
1576         if (!strcasecmp(details->result, "FAILED")) {
1577                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1578         }
1579
1580         if (fax) {
1581                 ao2_lock(faxregistry.container);
1582                 ao2_unlink(faxregistry.container, fax);
1583                 ao2_unlock(faxregistry.container);
1584                 ao2_ref(fax, -1);
1585         }
1586
1587         /* if the channel is still alive, and we changed its read/write formats,
1588          * restore them now
1589          */
1590         if (chancount) {
1591                 if (orig_read_format.id) {
1592                         ast_set_read_format(chan, &orig_read_format);
1593                 }
1594                 if (orig_write_format.id) {
1595                         ast_set_write_format(chan, &orig_write_format);
1596                 }
1597         }
1598
1599         /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
1600         return chancount;
1601 }
1602
1603 static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1604 {
1605         int timeout_ms;
1606         struct ast_frame *frame = NULL;
1607         struct ast_control_t38_parameters t38_parameters;
1608         struct timeval start;
1609         int ms;
1610
1611         /* don't send any audio if we've already received a T.38 reinvite */
1612         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1613                 /* generate 3 seconds of CED */
1614                 if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
1615                         ast_log(LOG_ERROR, "error generating CED tone on %s\n", ast_channel_name(chan));
1616                         return -1;
1617                 }
1618
1619                 timeout_ms = 3000;
1620                 start = ast_tvnow();
1621                 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1622                         ms = ast_waitfor(chan, ms);
1623
1624                         if (ms < 0) {
1625                                 ast_log(LOG_ERROR, "error while generating CED tone on %s\n", ast_channel_name(chan));
1626                                 ast_playtones_stop(chan);
1627                                 return -1;
1628                         }
1629
1630                         if (ms == 0) { /* all done, nothing happened */
1631                                 break;
1632                         }
1633
1634                         if (!(frame = ast_read(chan))) {
1635                                 ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", ast_channel_name(chan));
1636                                 ast_playtones_stop(chan);
1637                                 return -1;
1638                         }
1639
1640                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1641                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1642                             (frame->datalen == sizeof(t38_parameters))) {
1643                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1644
1645                                 switch (parameters->request_response) {
1646                                 case AST_T38_REQUEST_NEGOTIATE:
1647                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1648                                          * do T.38 as well
1649                                          */
1650                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1651                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1652                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1653                                         ast_playtones_stop(chan);
1654                                         break;
1655                                 case AST_T38_NEGOTIATED:
1656                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1657                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1658                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1659                                         report_fax_status(chan, details, "T.38 Negotiated");
1660                                         break;
1661                                 default:
1662                                         break;
1663                                 }
1664                         }
1665                         ast_frfree(frame);
1666                 }
1667
1668                 ast_playtones_stop(chan);
1669         }
1670
1671         /* if T.38 was negotiated, we are done initializing */
1672         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1673                 return 0;
1674         }
1675
1676         /* request T.38 */
1677         ast_debug(1, "Negotiating T.38 for receive on %s\n", ast_channel_name(chan));
1678
1679         /* wait up to five seconds for negotiation to complete */
1680         timeout_ms = 5000;
1681
1682         /* set parameters based on the session's parameters */
1683         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1684         t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
1685         if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
1686                 return -1;
1687         }
1688
1689         start = ast_tvnow();
1690         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1691                 int break_loop = 0;
1692
1693                 ms = ast_waitfor(chan, ms);
1694                 if (ms < 0) {
1695                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1696                         return -1;
1697                 }
1698                 if (ms == 0) { /* all done, nothing happened */
1699                         ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
1700                         details->caps &= ~AST_FAX_TECH_T38;
1701                         break;
1702                 }
1703
1704                 if (!(frame = ast_read(chan))) {
1705                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1706                         return -1;
1707                 }
1708
1709                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1710                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1711                                 (frame->datalen == sizeof(t38_parameters))) {
1712                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1713
1714                         switch (parameters->request_response) {
1715                         case AST_T38_REQUEST_NEGOTIATE:
1716                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1717                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
1718                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1719                                 break;
1720                         case AST_T38_NEGOTIATED:
1721                                 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1722                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1723                                 details->caps &= ~AST_FAX_TECH_AUDIO;
1724                                 report_fax_status(chan, details, "T.38 Negotiated");
1725                                 break_loop = 1;
1726                                 break;
1727                         case AST_T38_REFUSED:
1728                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
1729                                 details->caps &= ~AST_FAX_TECH_T38;
1730                                 break_loop = 1;
1731                                 break;
1732                         default:
1733                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
1734                                 details->caps &= ~AST_FAX_TECH_T38;
1735                                 break_loop = 1;
1736                                 break;
1737                         }
1738                 }
1739                 ast_frfree(frame);
1740                 if (break_loop) {
1741                         break;
1742                 }
1743         }
1744
1745         /* if T.38 was negotiated, we are done initializing */
1746         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1747                 return 0;
1748         }
1749
1750         /* if we made it here, then T.38 failed, check the 'f' flag */
1751         if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
1752                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
1753                 return -1;
1754         }
1755
1756         /* ok, audio fallback is allowed */
1757         details->caps |= AST_FAX_TECH_AUDIO;
1758
1759         return 0;
1760 }
1761
1762 /*! \brief Report on the final state of a receive fax operation
1763  * \note This will lock the \ref ast_channel
1764  */
1765 static int report_receive_fax_status(struct ast_channel *chan, const char *filename)
1766 {
1767         RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
1768         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1769         RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
1770         struct ast_json *json_filename = ast_json_string_create(filename);
1771
1772         if (!json_array || !json_filename) {
1773                 return -1;
1774         }
1775         ast_json_array_append(json_array, json_filename);
1776
1777         {
1778                 const char *remote_station_id;
1779                 const char *local_station_id;
1780                 const char *fax_pages;
1781                 const char *fax_resolution;
1782                 const char *fax_bitrate;
1783                 SCOPED_CHANNELLOCK(lock, chan);
1784
1785                 remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
1786                 if (!ast_strlen_zero(remote_station_id)) {
1787                         remote_station_id = ast_strdupa(remote_station_id);
1788                 }
1789                 local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
1790                 if (!ast_strlen_zero(local_station_id)) {
1791                         local_station_id = ast_strdupa(local_station_id);
1792                 }
1793                 fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
1794                 if (!ast_strlen_zero(fax_pages)) {
1795                         fax_pages = ast_strdupa(fax_pages);
1796                 }
1797                 fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
1798                 if (!ast_strlen_zero(fax_resolution)) {
1799                         fax_resolution = ast_strdupa(fax_resolution);
1800                 }
1801                 fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
1802                 if (!ast_strlen_zero(fax_bitrate)) {
1803                         fax_bitrate = ast_strdupa(fax_bitrate);
1804                 }
1805
1806                 json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: O}",
1807                                 "type", "receive",
1808                                 "remote_station_id", S_OR(remote_station_id, ""),
1809                                 "local_station_id", S_OR(local_station_id, ""),
1810                                 "fax_pages", S_OR(fax_pages, ""),
1811                                 "fax_resolution", S_OR(fax_resolution, ""),
1812                                 "fax_bitrate", S_OR(fax_bitrate, ""),
1813                                 "filenames", json_array);
1814                 if (!json_object) {
1815                         return -1;
1816                 }
1817
1818                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
1819                 if (!message) {
1820                         return -1;
1821                 }
1822                 stasis_publish(ast_channel_topic(chan), message);
1823         }
1824         return 0;
1825 }
1826
1827 /*! \brief initiate a receive FAX session */
1828 static int receivefax_exec(struct ast_channel *chan, const char *data)
1829 {
1830         char *parse, modems[128] = "";
1831         int channel_alive;
1832         RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
1833         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
1834         struct ast_fax_tech_token *token = NULL;
1835         struct ast_fax_document *doc;
1836         AST_DECLARE_APP_ARGS(args,
1837                 AST_APP_ARG(filename);
1838                 AST_APP_ARG(options);
1839         );
1840         struct ast_flags opts = { 0, };
1841         enum ast_t38_state t38state;
1842
1843         /* initialize output channel variables */
1844         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
1845         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
1846         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
1847         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
1848         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
1849
1850         /* Get a FAX session details structure from the channel's FAX datastore and create one if
1851          * it does not already exist. */
1852         if (!(details = find_or_create_details(chan))) {
1853                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
1854                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
1855                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1856                 return -1;
1857         }
1858
1859         ast_string_field_set(details, result, "FAILED");
1860         ast_string_field_set(details, resultstr, "error starting fax session");
1861         ast_string_field_set(details, error, "INIT_ERROR");
1862         set_channel_variables(chan, details);
1863
1864         if (details->gateway_id > 0) {
1865                 ast_string_field_set(details, resultstr, "can't receive a fax on a channel with a T.38 gateway");
1866                 set_channel_variables(chan, details);
1867                 ast_log(LOG_ERROR, "executing ReceiveFAX on a channel with a T.38 Gateway is not supported\n");
1868                 return -1;
1869         }
1870
1871         if (details->maxrate < details->minrate) {
1872                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1873                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
1874                 set_channel_variables(chan, details);
1875                 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
1876                 return -1;
1877         }
1878
1879         if (check_modem_rate(details->modems, details->minrate)) {
1880                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1881                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
1882                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1883                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
1884                 set_channel_variables(chan, details);
1885                 return -1;
1886         }
1887
1888         if (check_modem_rate(details->modems, details->maxrate)) {
1889                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1890                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
1891                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1892                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
1893                 set_channel_variables(chan, details);
1894                 return -1;
1895         }
1896
1897         if (ast_strlen_zero(data)) {
1898                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1899                 ast_string_field_set(details, resultstr, "invalid arguments");
1900                 set_channel_variables(chan, details);
1901                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1902                 return -1;
1903         }
1904         parse = ast_strdupa(data);
1905         AST_STANDARD_APP_ARGS(args, parse);
1906
1907         if (!ast_strlen_zero(args.options) &&
1908             ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
1909                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1910                 ast_string_field_set(details, resultstr, "invalid arguments");
1911                 set_channel_variables(chan, details);
1912                 return -1;
1913         }
1914         if (ast_strlen_zero(args.filename)) {
1915                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1916                 ast_string_field_set(details, resultstr, "invalid arguments");
1917                 set_channel_variables(chan, details);
1918                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1919                 return -1;
1920         }
1921
1922         /* check for unsupported FAX application options */
1923         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
1924                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1925                 ast_string_field_set(details, resultstr, "invalid arguments");
1926                 set_channel_variables(chan, details);
1927                 ast_log(LOG_WARNING, "%s does not support polling\n", app_receivefax);
1928                 return -1;
1929         }
1930
1931         ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
1932
1933         pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
1934         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
1935
1936         if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
1937                 ast_string_field_set(details, error, "MEMORY_ERROR");
1938                 ast_string_field_set(details, resultstr, "error allocating memory");
1939                 set_channel_variables(chan, details);
1940                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1941                 return -1;
1942         }
1943
1944         strcpy(doc->filename, args.filename);
1945         AST_LIST_INSERT_TAIL(&details->documents, doc, next);
1946
1947         ast_verb(3, "Channel '%s' receiving FAX '%s'\n", ast_channel_name(chan), args.filename);
1948
1949         details->caps = AST_FAX_TECH_RECEIVE;
1950         details->option.send_ced = AST_FAX_OPTFLAG_TRUE;
1951
1952         /* check for debug */
1953         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
1954                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
1955         }
1956
1957         /* check for request for status events */
1958         if (ast_test_flag(&opts, OPT_STATUS)) {
1959                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
1960         }
1961
1962         t38state = ast_channel_get_t38_state(chan);
1963         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
1964             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
1965             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1966                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
1967         }
1968
1969         if (!(s = fax_session_reserve(details, &token))) {
1970                 ast_string_field_set(details, resultstr, "error reserving fax session");
1971                 set_channel_variables(chan, details);
1972                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
1973                 return -1;
1974         }
1975
1976         /* make sure the channel is up */
1977         if (ast_channel_state(chan) != AST_STATE_UP) {
1978                 if (ast_answer(chan)) {
1979                         ast_string_field_set(details, resultstr, "error answering channel");
1980                         set_channel_variables(chan, details);
1981                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
1982                         fax_session_release(s, token);
1983                         return -1;
1984                 }
1985         }
1986
1987         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1988                 if (set_fax_t38_caps(chan, details)) {
1989                         ast_string_field_set(details, error, "T38_NEG_ERROR");
1990                         ast_string_field_set(details, resultstr, "error negotiating T.38");
1991                         set_channel_variables(chan, details);
1992                         fax_session_release(s, token);
1993                         return -1;
1994                 }
1995         } else {
1996                 details->caps |= AST_FAX_TECH_AUDIO;
1997         }
1998
1999         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2000                 if (receivefax_t38_init(chan, details)) {
2001                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2002                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2003                         set_channel_variables(chan, details);
2004                         fax_session_release(s, token);
2005                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2006                         return -1;
2007                 }
2008         }
2009
2010         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2011                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2012         }
2013
2014         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2015                 if (disable_t38(chan)) {
2016                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2017                 }
2018         }
2019
2020         if (report_receive_fax_status(chan, args.filename)) {
2021                 ast_log(AST_LOG_ERROR, "Error publishing ReceiveFax status message\n");
2022         }
2023
2024         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2025         return (!channel_alive) ? -1 : 0;
2026 }
2027
2028 static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
2029 {
2030         int timeout_ms;
2031         struct ast_frame *frame = NULL;
2032         struct ast_control_t38_parameters t38_parameters;
2033         struct timeval start;
2034         int ms;
2035
2036         /* send CNG tone while listening for the receiver to initiate a switch
2037          * to T.38 mode; if they do, stop sending the CNG tone and proceed with
2038          * the switch.
2039          *
2040          * 10500 is enough time for 3 CNG tones
2041          */
2042         timeout_ms = 10500;
2043
2044         /* don't send any audio if we've already received a T.38 reinvite */
2045         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
2046                 if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
2047                         ast_log(LOG_ERROR, "error generating CNG tone on %s\n", ast_channel_name(chan));
2048                         return -1;
2049                 }
2050         }
2051
2052         start = ast_tvnow();
2053         while ((ms = ast_remaining_ms(start, timeout_ms))) {
2054                 int break_loop = 0;
2055                 ms = ast_waitfor(chan, ms);
2056
2057                 if (ms < 0) {
2058                         ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", ast_channel_name(chan));
2059                         ast_playtones_stop(chan);
2060                         return -1;
2061                 }
2062
2063                 if (ms == 0) { /* all done, nothing happened */
2064                         break;
2065                 }
2066
2067                 if (!(frame = ast_read(chan))) {
2068                         ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", ast_channel_name(chan));
2069                         ast_playtones_stop(chan);
2070                         return -1;
2071                 }
2072
2073                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2074                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2075                                 (frame->datalen == sizeof(t38_parameters))) {
2076                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2077
2078                         switch (parameters->request_response) {
2079                         case AST_T38_REQUEST_NEGOTIATE:
2080                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2081                                  * do T.38 as well
2082                                  */
2083                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2084                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2085                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2086                                 ast_playtones_stop(chan);
2087                                 break;
2088                         case AST_T38_NEGOTIATED:
2089                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2090                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2091                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2092                                 report_fax_status(chan, details, "T.38 Negotiated");
2093                                 break_loop = 1;
2094                                 break;
2095                         default:
2096                                 break;
2097                         }
2098                 }
2099                 ast_frfree(frame);
2100                 if (break_loop) {
2101                         break;
2102                 }
2103         }
2104
2105         ast_playtones_stop(chan);
2106
2107         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2108                 return 0;
2109         }
2110
2111         /* T.38 negotiation did not happen, initiate a switch if requested */
2112         if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
2113                 ast_debug(1, "Negotiating T.38 for send on %s\n", ast_channel_name(chan));
2114
2115                 /* wait up to five seconds for negotiation to complete */
2116                 timeout_ms = 5000;
2117
2118                 /* set parameters based on the session's parameters */
2119                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2120                 t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
2121                 if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
2122                         return -1;
2123                 }
2124
2125                 start = ast_tvnow();
2126                 while ((ms = ast_remaining_ms(start, timeout_ms))) {
2127                         int break_loop = 0;
2128
2129                         ms = ast_waitfor(chan, ms);
2130                         if (ms < 0) {
2131                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2132                                 return -1;
2133                         }
2134                         if (ms == 0) { /* all done, nothing happened */
2135                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
2136                                 details->caps &= ~AST_FAX_TECH_T38;
2137                                 break;
2138                         }
2139
2140                         if (!(frame = ast_read(chan))) {
2141                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2142                                 return -1;
2143                         }
2144
2145                         if ((frame->frametype == AST_FRAME_CONTROL) &&
2146                                         (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2147                                         (frame->datalen == sizeof(t38_parameters))) {
2148                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
2149
2150                                 switch (parameters->request_response) {
2151                                 case AST_T38_REQUEST_NEGOTIATE:
2152                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2153                                         t38_parameters.request_response = AST_T38_NEGOTIATED;
2154                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2155                                         break;
2156                                 case AST_T38_NEGOTIATED:
2157                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
2158                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2159                                         details->caps &= ~AST_FAX_TECH_AUDIO;
2160                                         report_fax_status(chan, details, "T.38 Negotiated");
2161                                         break_loop = 1;
2162                                         break;
2163                                 case AST_T38_REFUSED:
2164                                         ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
2165                                         details->caps &= ~AST_FAX_TECH_T38;
2166                                         break_loop = 1;
2167                                         break;
2168                                 default:
2169                                         ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
2170                                         details->caps &= ~AST_FAX_TECH_T38;
2171                                         break_loop = 1;
2172                                         break;
2173                                 }
2174                         }
2175                         ast_frfree(frame);
2176                         if (break_loop) {
2177                                 break;
2178                         }
2179                 }
2180
2181                 /* if T.38 was negotiated, we are done initializing */
2182                 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2183                         return 0;
2184                 }
2185
2186                 /* send one more CNG tone to get audio going again for some
2187                  * carriers if we are going to fall back to audio mode */
2188                 if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
2189                         if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
2190                                 ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", ast_channel_name(chan));
2191                                 return -1;
2192                         }
2193
2194                         timeout_ms = 3500;
2195                         start = ast_tvnow();
2196                         while ((ms = ast_remaining_ms(start, timeout_ms))) {
2197                                 int break_loop = 0;
2198
2199                                 ms = ast_waitfor(chan, ms);
2200                                 if (ms < 0) {
2201                                         ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", ast_channel_name(chan));
2202                                         ast_playtones_stop(chan);
2203                                         return -1;
2204                                 }
2205                                 if (ms == 0) { /* all done, nothing happened */
2206                                         break;
2207                                 }
2208
2209                                 if (!(frame = ast_read(chan))) {
2210                                         ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", ast_channel_name(chan));
2211                                         ast_playtones_stop(chan);
2212                                         return -1;
2213                                 }
2214
2215                                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2216                                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2217                                                 (frame->datalen == sizeof(t38_parameters))) {
2218                                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2219
2220                                         switch (parameters->request_response) {
2221                                         case AST_T38_REQUEST_NEGOTIATE:
2222                                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2223                                                  * do T.38 as well
2224                                                  */
2225                                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2226                                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2227                                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2228                                                 ast_playtones_stop(chan);
2229                                                 break;
2230                                         case AST_T38_NEGOTIATED:
2231                                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2232                                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2233                                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2234                                                 report_fax_status(chan, details, "T.38 Negotiated");
2235                                                 break_loop = 1;
2236                                                 break;
2237                                         default:
2238                                                 break;
2239                                         }
2240                                 }
2241                                 ast_frfree(frame);
2242                                 if (break_loop) {
2243                                         break;
2244                                 }
2245                         }
2246
2247                         ast_playtones_stop(chan);
2248
2249                         /* if T.38 was negotiated, we are done initializing */
2250                         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2251                                 return 0;
2252                         }
2253                 }
2254         }
2255
2256         /* if we made it here, then T.38 failed, check the 'f' flag */
2257         if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
2258                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
2259                 return -1;
2260         }
2261
2262         /* ok, audio fallback is allowed */
2263         details->caps |= AST_FAX_TECH_AUDIO;
2264
2265         return 0;
2266 }
2267
2268 /*!
2269  * \brief Report on the status of a completed fax send attempt
2270  * \note This will lock the \ref ast_channel
2271  */
2272 static int report_send_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details)
2273 {
2274         RAII_VAR(struct ast_json *, json_obj, NULL, ast_json_unref);
2275         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
2276         struct ast_json *json_filenames;
2277
2278         json_filenames = generate_filenames_json(details);
2279         if (!json_filenames) {
2280                 return -1;
2281         }
2282
2283         {
2284                 const char *remote_station_id;
2285                 const char *local_station_id;
2286                 const char *fax_pages;
2287                 const char *fax_resolution;
2288                 const char *fax_bitrate;
2289                 SCOPED_CHANNELLOCK(lock, chan);
2290
2291                 remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
2292                 if (!ast_strlen_zero(remote_station_id)) {
2293                         remote_station_id = ast_strdupa(remote_station_id);
2294                 }
2295                 local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
2296                 if (!ast_strlen_zero(local_station_id)) {
2297                         local_station_id = ast_strdupa(local_station_id);
2298                 }
2299                 fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
2300                 if (!ast_strlen_zero(fax_pages)) {
2301                         fax_pages = ast_strdupa(fax_pages);
2302                 }
2303                 fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
2304                 if (!ast_strlen_zero(fax_resolution)) {
2305                         fax_resolution = ast_strdupa(fax_resolution);
2306                 }
2307                 fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
2308                 if (!ast_strlen_zero(fax_bitrate)) {
2309                         fax_bitrate = ast_strdupa(fax_bitrate);
2310                 }
2311                 json_obj = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: o}",
2312                                 "type", "send",
2313                                 "remote_station_id", S_OR(remote_station_id, ""),
2314                                 "local_station_id", S_OR(local_station_id, ""),
2315                                 "fax_pages", S_OR(fax_pages, ""),
2316                                 "fax_resolution", S_OR(fax_resolution, ""),
2317                                 "fax_bitrate", S_OR(fax_bitrate, ""),
2318                                 "filenames", json_filenames);
2319                 if (!json_obj) {
2320                         return -1;
2321                 }
2322
2323                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_obj);
2324                 if (!message) {
2325                         return -1;
2326                 }
2327                 stasis_publish(ast_channel_topic(chan), message);
2328         }
2329         return 0;
2330 }
2331
2332
2333
2334 /*! \brief initiate a send FAX session */
2335 static int sendfax_exec(struct ast_channel *chan, const char *data)
2336 {
2337         char *parse, *filenames, *c, modems[128] = "";
2338         int channel_alive, file_count;
2339         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
2340         RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
2341         struct ast_fax_tech_token *token = NULL;
2342         struct ast_fax_document *doc;
2343         AST_DECLARE_APP_ARGS(args,
2344                 AST_APP_ARG(filenames);
2345                 AST_APP_ARG(options);
2346         );
2347         struct ast_flags opts = { 0, };
2348         enum ast_t38_state t38state;
2349
2350         /* initialize output channel variables */
2351         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
2352         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
2353         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
2354         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
2355         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
2356
2357         /* Get a requirement structure and set it.  This structure is used
2358          * to tell the FAX technology module about the higher level FAX session */
2359         if (!(details = find_or_create_details(chan))) {
2360                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
2361                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
2362                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2363                 return -1;
2364         }
2365
2366         ast_string_field_set(details, result, "FAILED");
2367         ast_string_field_set(details, resultstr, "error starting fax session");
2368         ast_string_field_set(details, error, "INIT_ERROR");
2369         set_channel_variables(chan, details);
2370
2371         if (details->gateway_id > 0) {
2372                 ast_string_field_set(details, resultstr, "can't send a fax on a channel with a T.38 gateway");
2373                 set_channel_variables(chan, details);
2374                 ast_log(LOG_ERROR, "executing SendFAX on a channel with a T.38 Gateway is not supported\n");
2375                 return -1;
2376         }
2377
2378         if (details->maxrate < details->minrate) {
2379                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2380                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
2381                 set_channel_variables(chan, details);
2382                 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
2383                 return -1;
2384         }
2385
2386         if (check_modem_rate(details->modems, details->minrate)) {
2387                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2388                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
2389                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2390                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
2391                 set_channel_variables(chan, details);
2392                 return -1;
2393         }
2394
2395         if (check_modem_rate(details->modems, details->maxrate)) {
2396                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2397                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
2398                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2399                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
2400                 set_channel_variables(chan, details);
2401                 return -1;
2402         }
2403
2404         if (ast_strlen_zero(data)) {
2405                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2406                 ast_string_field_set(details, resultstr, "invalid arguments");
2407                 set_channel_variables(chan, details);
2408                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
2409                 return -1;
2410         }
2411         parse = ast_strdupa(data);
2412         AST_STANDARD_APP_ARGS(args, parse);
2413
2414
2415         if (!ast_strlen_zero(args.options) &&
2416                 ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
2417                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2418                 ast_string_field_set(details, resultstr, "invalid arguments");
2419                 set_channel_variables(chan, details);
2420                 return -1;
2421         }
2422         if (ast_strlen_zero(args.filenames)) {
2423                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2424                 ast_string_field_set(details, resultstr, "invalid arguments");
2425                 set_channel_variables(chan, details);
2426                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
2427                 return -1;
2428         }
2429
2430         /* check for unsupported FAX application options */
2431         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
2432                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2433                 ast_string_field_set(details, resultstr, "invalid arguments");
2434                 set_channel_variables(chan, details);
2435                 ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
2436                 return -1;
2437         }
2438
2439         ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
2440
2441         file_count = 0;
2442         filenames = args.filenames;
2443         while ((c = strsep(&filenames, "&"))) {
2444                 if (access(c, (F_OK | R_OK)) < 0) {
2445                         ast_string_field_set(details, error, "FILE_ERROR");
2446                         ast_string_field_set(details, resultstr, "error reading file");
2447                         set_channel_variables(chan, details);
2448                         ast_log(LOG_ERROR, "access failure.  Verify '%s' exists and check permissions.\n", args.filenames);
2449                         return -1;
2450                 }
2451
2452                 if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
2453                         ast_string_field_set(details, error, "MEMORY_ERROR");
2454                         ast_string_field_set(details, resultstr, "error allocating memory");
2455                         set_channel_variables(chan, details);
2456                         ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2457                         return -1;
2458                 }
2459
2460                 strcpy(doc->filename, c);
2461                 AST_LIST_INSERT_TAIL(&details->documents, doc, next);
2462                 file_count++;
2463         }
2464
2465         ast_verb(3, "Channel '%s' sending FAX:\n", ast_channel_name(chan));
2466         AST_LIST_TRAVERSE(&details->documents, doc, next) {
2467                 ast_verb(3, "   %s\n", doc->filename);
2468         }
2469
2470         details->caps = AST_FAX_TECH_SEND;
2471
2472         if (file_count > 1) {
2473                 details->caps |= AST_FAX_TECH_MULTI_DOC;
2474         }
2475
2476         /* check for debug */
2477         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
2478                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
2479         }
2480
2481         /* check for request for status events */
2482         if (ast_test_flag(&opts, OPT_STATUS)) {
2483                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
2484         }
2485
2486         t38state = ast_channel_get_t38_state(chan);
2487         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
2488             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
2489             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2490                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
2491         }
2492
2493         if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
2494                 details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
2495         }
2496
2497         if (!(s = fax_session_reserve(details, &token))) {
2498                 ast_string_field_set(details, resultstr, "error reserving fax session");
2499                 set_channel_variables(chan, details);
2500                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
2501                 return -1;
2502         }
2503
2504         /* make sure the channel is up */
2505         if (ast_channel_state(chan) != AST_STATE_UP) {
2506                 if (ast_answer(chan)) {
2507                         ast_string_field_set(details, resultstr, "error answering channel");
2508                         set_channel_variables(chan, details);
2509                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
2510                         fax_session_release(s, token);
2511                         return -1;
2512                 }
2513         }
2514
2515         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2516                 if (set_fax_t38_caps(chan, details)) {
2517                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2518                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2519                         set_channel_variables(chan, details);
2520                         fax_session_release(s, token);
2521                         return -1;
2522                 }
2523         } else {
2524                 details->caps |= AST_FAX_TECH_AUDIO;
2525         }
2526
2527         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2528                 if (sendfax_t38_init(chan, details)) {
2529                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2530                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2531                         set_channel_variables(chan, details);
2532                         fax_session_release(s, token);
2533                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2534                         return -1;
2535                 }
2536         } else {
2537                 details->option.send_cng = 1;
2538         }
2539
2540         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2541                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2542         }
2543
2544         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2545                 if (disable_t38(chan)) {
2546                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2547                 }
2548         }
2549
2550         if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
2551                 ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
2552                 return (!channel_alive) ? -1 : 0;
2553         }
2554
2555         /* send out the AMI completion event */
2556         if (report_send_fax_status(chan, details)) {
2557                 ast_log(AST_LOG_ERROR, "Error publishing SendFAX status message\n");
2558         }
2559
2560         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2561         return (!channel_alive) ? -1 : 0;
2562 }
2563
2564 /*! \brief destroy the v21 detection parts of a fax gateway session */
2565 static void destroy_v21_sessions(struct fax_gateway *gateway)
2566 {
2567         if (gateway->chan_v21_session) {
2568                 ao2_lock(faxregistry.container);
2569                 ao2_unlink(faxregistry.container, gateway->chan_v21_session);
2570                 ao2_unlock(faxregistry.container);
2571
2572                 ao2_ref(gateway->chan_v21_session, -1);
2573                 gateway->chan_v21_session = NULL;
2574         }
2575
2576         if (gateway->peer_v21_session) {
2577                 ao2_lock(faxregistry.container);
2578                 ao2_unlink(faxregistry.container, gateway->peer_v21_session);
2579                 ao2_unlock(faxregistry.container);
2580
2581                 ao2_ref(gateway->peer_v21_session, -1);
2582                 gateway->peer_v21_session = NULL;
2583         }
2584 }
2585
2586 /*! \brief destroy a FAX gateway session structure */
2587 static void destroy_gateway(void *data)
2588 {
2589         struct fax_gateway *gateway = data;
2590
2591         destroy_v21_sessions(gateway);
2592
2593         if (gateway->s) {
2594                 fax_session_release(gateway->s, gateway->token);
2595                 gateway->token = NULL;
2596
2597                 ao2_lock(faxregistry.container);
2598                 ao2_unlink(faxregistry.container, gateway->s);
2599                 ao2_unlock(faxregistry.container);
2600
2601                 ao2_ref(gateway->s, -1);
2602                 gateway->s = NULL;
2603         }
2604 }
2605
2606 /*! \brief Create a new fax gateway object.
2607  * \param chan the channel the gateway object will be attached to
2608  * \param details the fax session details
2609  * \return NULL or a fax gateway object
2610  */
2611 static struct fax_gateway *fax_gateway_new(struct ast_channel *chan, struct ast_fax_session_details *details)
2612 {
2613         struct fax_gateway *gateway = ao2_alloc(sizeof(*gateway), destroy_gateway);
2614         struct ast_fax_session_details *v21_details;
2615         if (!gateway) {
2616                 return NULL;
2617         }
2618
2619         if (!(v21_details = session_details_new())) {
2620                 ao2_ref(gateway, -1);
2621                 return NULL;
2622         }
2623
2624         v21_details->caps = AST_FAX_TECH_V21_DETECT;
2625         if (!(gateway->chan_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2626                 ao2_ref(v21_details, -1);
2627                 ao2_ref(gateway, -1);
2628                 return NULL;
2629         }
2630
2631         if (!(gateway->peer_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2632                 ao2_ref(v21_details, -1);
2633                 ao2_ref(gateway, -1);
2634                 return NULL;
2635         }
2636         ao2_ref(v21_details, -1);
2637
2638         gateway->framehook = -1;
2639
2640         details->caps = AST_FAX_TECH_GATEWAY;
2641         if (details->gateway_timeout && !(gateway->s = fax_session_reserve(details, &gateway->token))) {
2642                 details->caps &= ~AST_FAX_TECH_GATEWAY;
2643                 ast_log(LOG_ERROR, "Can't reserve a FAX session, gateway attempt failed.\n");
2644                 ao2_ref(gateway, -1);
2645                 return NULL;
2646         }
2647
2648         return gateway;
2649 }
2650
2651 /*! \brief Create a fax session and start T.30<->T.38 gateway mode
2652  * \param gateway a fax gateway object
2653  * \param details fax session details
2654  * \param chan active channel
2655  * \return 0 on error 1 on success*/
2656 static int fax_gateway_start(struct fax_gateway *gateway, struct ast_fax_session_details *details, struct ast_channel *chan)
2657 {
2658         struct ast_fax_session *s;
2659
2660         /* create the FAX session */
2661         if (!(s = fax_session_new(details, chan, gateway->s, gateway->token))) {
2662                 gateway->token = NULL;
2663                 ast_string_field_set(details, result, "FAILED");
2664                 ast_string_field_set(details, resultstr, "error starting gateway session");
2665                 ast_string_field_set(details, error, "INIT_ERROR");
2666                 set_channel_variables(chan, details);
2667                 report_fax_status(chan, details, "No Available Resource");
2668                 ast_log(LOG_ERROR, "Can't create a FAX session, gateway attempt failed.\n");
2669                 return -1;
2670         }
2671         /* release the reference for the reserved session and replace it with
2672          * the real session */
2673         if (gateway->s) {
2674                 ao2_ref(gateway->s, -1);
2675         }
2676         gateway->s = s;
2677         gateway->token = NULL;
2678
2679         if (gateway->s->tech->start_session(gateway->s) < 0) {
2680                 ast_string_field_set(details, result, "FAILED");
2681                 ast_string_field_set(details, resultstr, "error starting gateway session");
2682                 ast_string_field_set(details, error, "INIT_ERROR");
2683                 set_channel_variables(chan, details);
2684                 return -1;
2685         }
2686
2687         gateway->timeout_start.tv_sec = 0;
2688         gateway->timeout_start.tv_usec = 0;
2689
2690         report_fax_status(chan, details, "FAX Transmission In Progress");
2691
2692         return 0;
2693 }
2694
2695 static struct ast_frame *fax_gateway_request_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_frame *f)
2696 {
2697         struct ast_frame *fp;
2698         struct ast_control_t38_parameters t38_parameters = {
2699                 .request_response = AST_T38_REQUEST_NEGOTIATE,
2700         };
2701         struct ast_frame control_frame = {
2702                 .src = "res_fax",
2703                 .frametype = AST_FRAME_CONTROL,
2704                 .datalen = sizeof(t38_parameters),
2705                 .subclass.integer = AST_CONTROL_T38_PARAMETERS,
2706                 .data.ptr = &t38_parameters,
2707         };
2708
2709         struct ast_fax_session_details *details = find_details(chan);
2710
2711         if (!details) {
2712                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2713                 ast_framehook_detach(chan, gateway->framehook);
2714                 return f;
2715         }
2716
2717         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2718         ao2_ref(details, -1);
2719
2720         if (!(fp = ast_frisolate(&control_frame))) {
2721                 ast_log(LOG_ERROR, "error generating T.38 request control frame on chan %s for T.38 gateway session\n", ast_channel_name(chan));
2722                 return f;
2723         }
2724
2725         gateway->t38_state = T38_STATE_NEGOTIATING;
2726         gateway->timeout_start = ast_tvnow();
2727         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2728
2729         ast_debug(1, "requesting T.38 for gateway session for %s\n", ast_channel_name(chan));
2730         return fp;
2731 }
2732
2733 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)
2734 {
2735         struct ast_channel *other = (active == chan) ? peer : chan;
2736         struct ast_fax_session *active_v21_session = (active == chan) ? gateway->chan_v21_session : gateway->peer_v21_session;
2737
2738         if (!active_v21_session || gateway->detected_v21) {
2739                 return f;
2740         }
2741
2742         if (active_v21_session->tech->write(active_v21_session, f) == 0 &&
2743             active_v21_session->details->option.v21_detected) {
2744                 gateway->detected_v21 = 1;
2745         }
2746
2747         if (gateway->detected_v21) {
2748                 destroy_v21_sessions(gateway);
2749                 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2750                         ast_debug(1, "detected v21 preamble from %s\n", ast_channel_name(active));
2751                         return fax_gateway_request_t38(gateway, chan, f);
2752                 } else {
2753                         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));
2754                 }
2755         }
2756
2757         return f;
2758 }
2759
2760 static int fax_gateway_indicate_t38(struct ast_channel *chan, struct ast_channel *active, struct ast_control_t38_parameters *control_params)
2761 {
2762         if (active == chan) {
2763                 return ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2764         } else {
2765                 return ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2766         }
2767 }
2768
2769 /*! \brief T38 Gateway Negotiate t38 parameters
2770  * \param gateway gateway object
2771  * \param chan channel running the gateway
2772  * \param peer channel im bridged too
2773  * \param active channel the frame originated on
2774  * \param f the control frame to process
2775  * \return processed control frame or null frame
2776  */
2777 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)
2778 {
2779         struct ast_control_t38_parameters *control_params = f->data.ptr;
2780         struct ast_channel *other = (active == chan) ? peer : chan;
2781         struct ast_fax_session_details *details;
2782
2783         if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
2784                 /* invalaid AST_CONTROL_T38_PARAMETERS frame, we can't
2785                  * do anything with it, pass it on */
2786                 return f;
2787         }
2788
2789         /* ignore frames from ourselves */
2790         if ((gateway->t38_state == T38_STATE_NEGOTIATED && control_params->request_response == AST_T38_NEGOTIATED)
2791                 || (gateway->t38_state == T38_STATE_REJECTED && control_params->request_response == AST_T38_REFUSED)
2792                 || (gateway->t38_state == T38_STATE_NEGOTIATING && control_params->request_response == AST_T38_REQUEST_TERMINATE)) {
2793
2794                 return f;
2795         }
2796
2797         if (!(details = find_details(chan))) {
2798                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2799                 ast_framehook_detach(chan, gateway->framehook);
2800                 return f;
2801         }
2802
2803         if (control_params->request_response == AST_T38_REQUEST_NEGOTIATE) {
2804                 enum ast_t38_state state = ast_channel_get_t38_state(other);
2805
2806                 if (state == T38_STATE_UNKNOWN) {
2807                         /* we detected a request to negotiate T.38 and the
2808                          * other channel appears to support T.38, we'll pass
2809                          * the request through and only step in if the other
2810                          * channel rejects the request */
2811                         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));
2812                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2813                         gateway->t38_state = T38_STATE_UNKNOWN;
2814                         gateway->timeout_start = ast_tvnow();
2815                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2816                         ao2_ref(details, -1);
2817                         return f;
2818                 } else if (state == T38_STATE_UNAVAILABLE || state == T38_STATE_REJECTED) {
2819                         /* the other channel does not support T.38, we need to
2820                          * step in here */
2821                         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));
2822                         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));
2823
2824                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2825                         t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2826
2827                         if (fax_gateway_start(gateway, details, chan)) {
2828                                 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));
2829                                 gateway->t38_state = T38_STATE_REJECTED;
2830                                 control_params->request_response = AST_T38_REFUSED;
2831
2832                                 ast_framehook_detach(chan, details->gateway_id);
2833                                 details->gateway_id = -1;
2834                         } else {
2835                                 gateway->t38_state = T38_STATE_NEGOTIATED;
2836                                 control_params->request_response = AST_T38_NEGOTIATED;
2837                                 report_fax_status(chan, details, "T.38 Negotiated");
2838                         }
2839
2840                         fax_gateway_indicate_t38(chan, active, control_params);
2841
2842                         ao2_ref(details, -1);
2843                         return &ast_null_frame;
2844                 } else if (gateway->t38_state == T38_STATE_NEGOTIATING) {
2845                         /* we got a request to negotiate T.38 after we already
2846                          * sent one to the other party based on v21 preamble
2847                          * detection. We'll just pretend we passed this request
2848                          * through in the first place. */
2849
2850                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2851                         gateway->t38_state = T38_STATE_UNKNOWN;
2852                         gateway->timeout_start = ast_tvnow();
2853                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2854
2855                         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));
2856                         ao2_ref(details, -1);
2857                         return &ast_null_frame;
2858                 } else if (gateway->t38_state == T38_STATE_NEGOTIATED) {
2859                         /* we got a request to negotiate T.38 after we already
2860                          * sent one to the other party based on v21 preamble
2861                          * detection and received a response. We need to
2862                          * respond to this and shut down the gateway. */
2863
2864                         t38_parameters_fax_to_ast(control_params, &details->their_t38_parameters);
2865                         ast_framehook_detach(chan, details->gateway_id);
2866                         details->gateway_id = -1;
2867
2868                         control_params->request_response = AST_T38_NEGOTIATED;
2869
2870                         fax_gateway_indicate_t38(chan, active, control_params);
2871
2872                         ast_string_field_set(details, result, "SUCCESS");
2873                         ast_string_field_set(details, resultstr, "no gateway necessary");
2874                         ast_string_field_set(details, error, "NATIVE_T38");
2875                         set_channel_variables(chan, details);
2876
2877                         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));
2878                         ao2_ref(details, -1);
2879                         return &ast_null_frame;
2880                 } else {
2881                         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));
2882                         ao2_ref(details, -1);
2883                         return f;
2884                 }
2885         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2886                 && control_params->request_response == AST_T38_REFUSED) {
2887
2888                 ast_debug(1, "unable to negotiate T.38 on %s for fax gateway\n", ast_channel_name(active));
2889
2890                 /* our request to negotiate T.38 was refused, if the other
2891                  * channel supports T.38, they might still reinvite and save
2892                  * the day.  Otherwise disable the gateway. */
2893                 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2894                         gateway->t38_state = T38_STATE_UNAVAILABLE;
2895                 } else {
2896                         ast_framehook_detach(chan, details->gateway_id);
2897                         details->gateway_id = -1;
2898
2899                         ast_string_field_set(details, result, "FAILED");
2900                         ast_string_field_set(details, resultstr, "unable to negotiate T.38");
2901                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2902                         set_channel_variables(chan, details);
2903                 }
2904
2905                 ao2_ref(details, -1);
2906                 return &ast_null_frame;
2907         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2908                 && control_params->request_response == AST_T38_NEGOTIATED) {
2909
2910                 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));
2911
2912                 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2913
2914                 if (fax_gateway_start(gateway, details, chan)) {
2915                         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));
2916                         gateway->t38_state = T38_STATE_NEGOTIATING;
2917                         control_params->request_response = AST_T38_REQUEST_TERMINATE;
2918
2919                         fax_gateway_indicate_t38(chan, active, control_params);
2920                 } else {
2921                         gateway->t38_state = T38_STATE_NEGOTIATED;
2922                         report_fax_status(chan, details, "T.38 Negotiated");
2923                 }
2924
2925                 ao2_ref(details, -1);
2926                 return &ast_null_frame;
2927         } else if (control_params->request_response == AST_T38_REFUSED) {
2928                 /* the other channel refused the request to negotiate T.38,
2929                  * we'll step in here and pretend the request was accepted */
2930
2931                 ast_debug(1, "%s attempted to negotiate T.38 but %s refused the request\n", ast_channel_name(other), ast_channel_name(active));
2932                 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));
2933
2934                 t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2935
2936                 if (fax_gateway_start(gateway, details, chan)) {
2937                         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));
2938                         gateway->t38_state = T38_STATE_REJECTED;
2939                         control_params->request_response = AST_T38_REFUSED;
2940
2941                         ast_framehook_detach(chan, details->gateway_id);
2942                         details->gateway_id = -1;
2943                 } else {
2944                         gateway->t38_state = T38_STATE_NEGOTIATED;
2945                         control_params->request_response = AST_T38_NEGOTIATED;
2946                 }
2947
2948                 ao2_ref(details, -1);
2949                 return f;
2950         } else if (control_params->request_response == AST_T38_REQUEST_TERMINATE) {
2951                 /* the channel wishes to end our short relationship, we shall
2952                  * oblige */
2953
2954                 ast_debug(1, "T.38 channel %s is requesting a shutdown of T.38, disabling the gateway\n", ast_channel_name(active));
2955
2956                 ast_framehook_detach(chan, details->gateway_id);
2957                 details->gateway_id = -1;
2958
2959                 gateway->t38_state = T38_STATE_REJECTED;
2960                 control_params->request_response = AST_T38_TERMINATED;
2961
2962                 fax_gateway_indicate_t38(chan, active, control_params);
2963
2964                 ao2_ref(details, -1);
2965                 return &ast_null_frame;
2966         } else if (control_params->request_response == AST_T38_NEGOTIATED) {
2967                 ast_debug(1, "T.38 successfully negotiated between %s and %s, no gateway necessary\n", ast_channel_name(active), ast_channel_name(other));
2968
2969                 ast_framehook_detach(chan, details->gateway_id);
2970                 details->gateway_id = -1;
2971
2972                 ast_string_field_set(details, result, "SUCCESS");
2973                 ast_string_field_set(details, resultstr, "no gateway necessary");
2974                 ast_string_field_set(details, error, "NATIVE_T38");
2975                 set_channel_variables(chan, details);
2976
2977                 ao2_ref(details, -1);
2978                 return f;
2979         } else if (control_params->request_response == AST_T38_TERMINATED) {
2980                 ast_debug(1, "T.38 disabled on channel %s\n", ast_channel_name(active));
2981
2982                 ast_framehook_detach(chan, details->gateway_id);
2983                 details->gateway_id = -1;
2984
2985                 ao2_ref(details, -1);
2986                 return &ast_null_frame;
2987         }
2988
2989         ao2_ref(details, -1);
2990         return f;
2991 }
2992
2993 /*! \brief Destroy the gateway data structure when the framehook is detached
2994  * \param data framehook data (gateway data)*/
2995 static void fax_gateway_framehook_destroy(void *data) {
2996         struct fax_gateway *gateway = data;
2997
2998         if (gateway->s) {
2999                 switch (gateway->s->state) {
3000                 case AST_FAX_STATE_INITIALIZED:
3001                 case AST_FAX_STATE_OPEN:
3002                 case AST_FAX_STATE_ACTIVE:
3003                 case AST_FAX_STATE_COMPLETE:
3004                         if (gateway->s->tech->cancel_session) {
3005                                 gateway->s->tech->cancel_session(gateway->s);
3006                         }
3007                         /* fall through */
3008                 default:
3009                         break;
3010                 }
3011         }
3012
3013         ao2_ref(gateway, -1);
3014 }
3015
3016 /*! \brief T.30<->T.38 gateway framehook.
3017  *
3018  * Intercept packets on bridged channels and determine if a T.38 gateway is
3019  * required. If a gateway is required, start a gateway and handle T.38
3020  * negotiation if necessary.
3021  *
3022  * \param chan channel running the gateway
3023  * \param f frame to handle may be NULL
3024  * \param event framehook event
3025  * \param data framehook data (struct fax_gateway *)
3026  *
3027  * \return processed frame or NULL when f is NULL or a null frame
3028  */
3029 static struct ast_frame *fax_gateway_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
3030         struct fax_gateway *gateway = data;
3031         struct ast_channel *active;
3032         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
3033         RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
3034         RAII_VAR(struct ast_channel *, chan_ref, chan, ao2_cleanup);
3035
3036         /* Ref bump channel for when we have to unlock it */
3037         ao2_ref(chan_ref, 1);
3038
3039         if (gateway->s) {
3040                 details = gateway->s->details;
3041                 ao2_ref(details, 1);
3042         } else {
3043                 if (!(details = find_details(chan))) {
3044                         ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
3045                         ast_framehook_detach(chan, gateway->framehook);
3046                         return f;
3047                 }
3048         }
3049
3050         /* restore audio formats when we are detached */
3051         if (event == AST_FRAMEHOOK_EVENT_DETACHED) {
3052                 set_channel_variables(chan, details);
3053
3054                 if (gateway->bridged) {
3055                         ast_set_read_format(chan, &gateway->chan_read_format);
3056                         ast_set_read_format(chan, &gateway->chan_write_format);
3057
3058                         ast_channel_unlock(chan);
3059                         peer = ast_channel_bridge_peer(chan);
3060                         ast_channel_lock(chan);
3061                         if (peer) {
3062                                 ast_set_read_format(peer, &gateway->peer_read_format);
3063                                 ast_set_read_format(peer, &gateway->peer_write_format);
3064                                 ast_channel_make_compatible(chan, peer);
3065                         }
3066                 }
3067                 return NULL;
3068         }
3069
3070         if (!f || (event == AST_FRAMEHOOK_EVENT_ATTACHED)) {
3071                 return NULL;
3072         };
3073
3074         /* this frame was generated by the fax gateway, pass it on */
3075         if (ast_test_flag(f, AST_FAX_FRFLAG_GATEWAY)) {
3076                 return f;
3077         }
3078
3079         /* If we aren't bridged or we don't have a peer, don't do anything */
3080         ast_channel_unlock(chan);
3081         peer = ast_channel_bridge_peer(chan);
3082         ast_channel_lock(chan);
3083         if (!peer) {
3084                 return f;
3085         }
3086
3087         if (!gateway->bridged && peer) {
3088                 /* don't start a gateway if neither channel can handle T.38 */
3089                 if (ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE && ast_channel_get_t38_state(peer) == T38_STATE_UNAVAILABLE) {
3090                         ast_debug(1, "not starting gateway for %s and %s; neither channel supports T.38\n", ast_channel_name(chan), ast_channel_name(peer));
3091                         ast_framehook_detach(chan, gateway->framehook);
3092                         details->gateway_id = -1;
3093
3094                         ast_string_field_set(details, result, "FAILED");
3095                         ast_string_field_set(details, resultstr, "neither channel supports T.38");
3096                         ast_string_field_set(details, error, "T38_NEG_ERROR");
3097                         set_channel_variables(chan, details);
3098                         return f;
3099                 }
3100
3101                 if (details->gateway_timeout) {
3102                         gateway->timeout_start = ast_tvnow();
3103                 }
3104
3105                 /* we are bridged, change r/w formats to SLIN for v21 preamble
3106                  * detection and T.30 */
3107                 ast_format_copy(&gateway->chan_read_format, ast_channel_readformat(chan));
3108                 ast_format_copy(&gateway->chan_write_format, ast_channel_readformat(chan));
3109
3110                 ast_format_copy(&gateway->peer_read_format, ast_channel_readformat(peer));
3111                 ast_format_copy(&gateway->peer_write_format, ast_channel_readformat(peer));
3112
3113                 ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
3114                 ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR);
3115
3116                 ast_set_read_format_by_id(peer, AST_FORMAT_SLINEAR);
3117                 ast_set_write_format_by_id(peer, AST_FORMAT_SLINEAR);
3118
3119                 ast_channel_make_compatible(chan, peer);
3120                 gateway->bridged = 1;
3121         }
3122
3123         if (gateway->bridged && !ast_tvzero(gateway->timeout_start)) {
3124                 if (ast_tvdiff_ms(ast_tvnow(), gateway->timeout_start) > details->gateway_timeout) {
3125                         ast_debug(1, "no fax activity between %s and %s after %d ms, disabling gateway\n", ast_channel_name(chan), ast_channel_name(peer), details->gateway_timeout);
3126                         ast_framehook_detach(chan, gateway->framehook);
3127                         details->gateway_id = -1;
3128
3129                         ast_string_field_set(details, result, "FAILED");
3130                         ast_string_field_build(details, resultstr, "no fax activity after %d ms", details->gateway_timeout);
3131                         ast_string_field_set(details, error, "TIMEOUT");
3132                         set_channel_variables(chan, details);
3133                         return f;
3134                 }
3135         }
3136
3137         /* only handle VOICE, MODEM, and CONTROL frames*/
3138         switch (f->frametype) {
3139         case AST_FRAME_VOICE:
3140                 switch (f->subclass.format.id) {
3141                 case AST_FORMAT_SLINEAR:
3142                 case AST_FORMAT_ALAW:
3143                 case AST_FORMAT_ULAW:
3144                         break;
3145                 default:
3146                         return f;
3147                 }
3148                 break;
3149         case AST_FRAME_MODEM:
3150                 if (f->subclass.integer == AST_MODEM_T38) {
3151                         break;
3152                 }
3153                 return f;
3154         case AST_FRAME_CONTROL:
3155                 if (f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
3156                         break;
3157                 }
3158                 return f;
3159         default:
3160                 return f;
3161         }
3162
3163         /* detect the active channel */
3164         switch (event) {
3165         case AST_FRAMEHOOK_EVENT_WRITE:
3166                 active = peer;
3167                 break;
3168         case AST_FRAMEHOOK_EVENT_READ:
3169                 active = chan;
3170                 break;
3171         default:
3172                 ast_log(LOG_WARNING, "unhandled framehook event %i\n", event);
3173                 return f;
3174         }
3175
3176         /* handle control frames */
3177         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
3178                 return fax_gateway_detect_t38(gateway, chan, peer, active, f);
3179         }
3180
3181         if (!gateway->detected_v21 && gateway->t38_state == T38_STATE_UNAVAILABLE && f->frametype == AST_FRAME_VOICE) {
3182                 /* not in gateway mode and have not detected v21 yet, listen
3183                  * for v21 */
3184                 return fax_gateway_detect_v21(gateway, chan, peer, active, f);
3185         }
3186
3187         /* in gateway mode, gateway some packets */
3188         if (gateway->t38_state == T38_STATE_NEGOTIATED) {
3189                 /* framehooks are called in __ast_read() before frame format
3190                  * translation is done, so we need to translate here */
3191                 if ((f->frametype == AST_FRAME_VOICE) && (f->subclass.format.id != AST_FORMAT_SLINEAR)) {
3192                         if (ast_channel_readtrans(active) && (f = ast_translate(ast_channel_readtrans(active), f, 1)) == NULL) {
3193                                 f = &ast_null_frame;
3194                                 return f;
3195                         }
3196                 }
3197
3198                 /* XXX we ignore the return value here, perhaps we should
3199                  * disable the gateway if a write fails. I am not sure how a
3200                  * write would fail, or even if a failure would be fatal so for
3201                  * now we'll just ignore the return value. */
3202                 gateway->s->tech->write(gateway->s, f);
3203                 if ((f->frametype == AST_FRAME_VOICE) && (f->subclass.format.id != AST_FORMAT_SLINEAR) && ast_channel_readtrans(active)) {
3204                         /* Only free the frame if we translated / duplicated it - otherwise,
3205                          * let whatever is outside the frame hook do it */
3206                         ast_frfree(f);
3207                 }
3208                 f = &ast_null_frame;
3209                 return f;
3210         }
3211
3212         /* force silence on the line if T.38 negotiation might be taking place */
3213         if (gateway->t38_state != T38_STATE_UNAVAILABLE && gateway->t38_state != T38_STATE_REJECTED) {
3214                 if (f->frametype == AST_FRAME_VOICE && f->subclass.format.id == AST_FORMAT_SLINEAR) {
3215                         short silence_buf[f->samples];
3216                         struct ast_frame silence_frame = {
3217                                 .frametype = AST_FRAME_VOICE,
3218                                 .data.ptr = silence_buf,
3219                                 .samples = f->samples,
3220                                 .datalen = sizeof(silence_buf),
3221                         };
3222                         ast_format_set(&silence_frame.subclass.format, AST_FORMAT_SLINEAR, 0);
3223                         memset(silence_buf, 0, sizeof(silence_buf));
3224                         return ast_frisolate(&silence_frame);
3225                 } else {
3226                         return &ast_null_frame;
3227                 }
3228         }
3229
3230         return f;
3231 }
3232
3233 /*! \brief Attach a gateway framehook object to a channel.
3234  * \param chan the channel to attach to
3235  * \param details fax session details
3236  * \return the framehook id of the attached framehook or -1 on error
3237  * \retval -1 error
3238  */
3239 static int fax_gateway_attach(struct ast_channel *chan, struct ast_fax_session_details *details)
3240 {
3241         struct fax_gateway *gateway;
3242         struct ast_framehook_interface fr_hook = {
3243                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
3244                 .event_cb = fax_gateway_framehook,
3245                 .destroy_cb = fax_gateway_framehook_destroy,
3246         };
3247
3248         ast_string_field_set(details, result, "SUCCESS");
3249         ast_string_field_set(details, resultstr, "gateway operation started successfully");
3250         ast_string_field_set(details, error, "NO_ERROR");
3251         set_channel_variables(chan, details);
3252
3253         /* set up the frame hook*/
3254         gateway = fax_gateway_new(chan, details);
3255         if (!gateway) {
3256                 ast_string_field_set(details, result, "FAILED");
3257                 ast_string_field_set(details, resultstr, "error initializing gateway session");
3258                 ast_string_field_set(details, error, "INIT_ERROR");
3259                 set_channel_variables(chan, details);
3260                 report_fax_status(chan, details, "No Available Resource");
3261                 return -1;
3262         }
3263
3264         fr_hook.data = gateway;
3265         ast_channel_lock(chan);
3266         gateway->framehook = ast_framehook_attach(chan, &fr_hook);
3267         ast_channel_unlock(chan);
3268
3269         if (gateway->framehook < 0) {
3270                 ao2_ref(gateway, -1);
3271                 ast_string_field_set(details, result, "FAILED");
3272                 ast_string_field_set(details, resultstr, "error attaching gateway to channel");
3273                 ast_string_field_set(details, error, "INIT_ERROR");
3274                 set_channel_variables(chan, details);
3275                 return -1;
3276         }
3277
3278         return gateway->framehook;
3279 }
3280
3281 /*! \brief destroy a FAX detect structure */
3282 static void destroy_faxdetect(void *data)
3283 {
3284         struct fax_detect *faxdetect = data;
3285
3286         if (faxdetect->dsp) {
3287                 ast_dsp_free(faxdetect->dsp);
3288                 faxdetect->dsp = NULL;
3289         }
3290         ao2_ref(faxdetect->details, -1);
3291 }
3292
3293 /*! \brief Create a new fax detect object.
3294  * \param chan the channel attaching to
3295  * \param timeout remove framehook in this time if set
3296  * \param flags required options
3297  * \return NULL or a fax gateway object
3298  */
3299 static struct fax_detect *fax_detect_new(struct ast_channel *chan, int timeout, int flags)
3300 {
3301         struct fax_detect *faxdetect = ao2_alloc(sizeof(*faxdetect), destroy_faxdetect);
3302         if (!faxdetect) {
3303                 return NULL;
3304         }
3305
3306         faxdetect->flags = flags;
3307
3308         if (timeout) {
3309                 faxdetect->timeout_start = ast_tvnow();
3310         } else {
3311                 faxdetect->timeout_start.tv_sec = 0;
3312                 faxdetect->timeout_start.tv_usec = 0;
3313         }
3314
3315         if (faxdetect->flags & FAX_DETECT_MODE_CNG) {
3316                 faxdetect->dsp = ast_dsp_new();
3317                 if (!faxdetect->dsp) {
3318                         ao2_ref(faxdetect, -1);
3319                         return NULL;
3320                 }
3321                 ast_dsp_set_features(faxdetect->dsp, DSP_FEATURE_FAX_DETECT);
3322                 ast_dsp_set_faxmode(faxdetect->dsp, DSP_FAXMODE_DETECT_CNG | DSP_FAXMODE_DETECT_SQUELCH);
3323         } else {
3324                 faxdetect->dsp = NULL;
3325         }
3326
3327         return faxdetect;
3328 }
3329
3330 /*! \brief Deref the faxdetect data structure when the faxdetect framehook is detached
3331  * \param data framehook data (faxdetect data)*/
3332 static void fax_detect_framehook_destroy(void *data) {
3333         struct fax_detect *faxdetect = data;
3334
3335         ao2_ref(faxdetect, -1);
3336 }
3337
3338 /*! \brief Fax Detect Framehook
3339  *
3340  * Listen for fax tones in audio path and enable jumping to a extension when detected.
3341  *
3342  * \param chan channel
3343  * \param f frame to handle may be NULL
3344  * \param event framehook event
3345  * \param data framehook data (struct fax_detect *)
3346  *
3347  * \return processed frame or NULL when f is NULL or a null frame
3348  */
3349 static struct ast_frame *fax_detect_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
3350         struct fax_detect *faxdetect = data;
3351         struct ast_fax_session_details *details;
3352         struct ast_control_t38_parameters *control_params;
3353         RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
3354         RAII_VAR(struct ast_channel *, chan_ref, chan, ao2_cleanup);
3355         int result = 0;
3356
3357         /* Ref bump the channel for when we have to unlock it */
3358         ao2_ref(chan, 1);
3359
3360         details = faxdetect->details;
3361
3362         switch (event) {
3363         case AST_FRAMEHOOK_EVENT_ATTACHED:
3364                 /* Setup format for DSP on ATTACH*/
3365                 ast_format_copy(&faxdetect->orig_format, ast_channel_readformat(chan));
3366                 switch (ast_channel_readformat(chan)->id) {
3367                         case AST_FORMAT_SLINEAR:
3368                         case AST_FORMAT_ALAW:
3369                         case AST_FORMAT_ULAW:
3370                                 break;
3371                         default:
3372                                 if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR)) {
3373                                         ast_framehook_detach(chan, details->faxdetect_id);
3374                                         details->faxdetect_id = -1;
3375                                         return f;
3376                                 }
3377                 }
3378                 return NULL;
3379         case AST_FRAMEHOOK_EVENT_DETACHED:
3380                 /* restore audio formats when we are detached */
3381                 ast_set_read_format(chan, &faxdetect->orig_format);
3382                 ast_channel_unlock(chan);
3383                 peer = ast_channel_bridge_peer(chan);
3384                 ast_channel_lock(chan);
3385                 if (peer) {
3386                         ast_channel_make_compatible(chan, peer);
3387                 }
3388                 return NULL;
3389         case AST_FRAMEHOOK_EVENT_READ:
3390                 if (f) {
3391                         break;
3392                 }
3393         default:
3394                 return f;
3395         };
3396
3397         if (details->faxdetect_id < 0) {
3398                 return f;
3399         }
3400
3401         if ((!ast_tvzero(faxdetect->timeout_start) &&
3402             (ast_tvdiff_ms(ast_tvnow(), faxdetect->timeout_start) > faxdetect->timeout))) {
3403                 ast_framehook_detach(chan, details->faxdetect_id);
3404                 details->faxdetect_id = -1;
3405                 return f;
3406         }
3407
3408         /* only handle VOICE and CONTROL frames*/
3409         switch (f->frametype) {
3410         case AST_FRAME_VOICE:
3411                 /* we have no DSP this means we not detecting CNG */
3412                 if (!faxdetect->dsp) {
3413                         break;
3414                 }
3415                 /* We can only process some formats*/
3416                 switch (f->subclass.format.id) {
3417                         case AST_FORMAT_SLINEAR:
3418                         case AST_FORMAT_ALAW:
3419                         case AST_FORMAT_ULAW:
3420                                 break;
3421                         default:
3422                                 return f;
3423                 }
3424                 break;
3425         case AST_FRAME_CONTROL:
3426                 if ((f->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
3427                     (faxdetect->flags & FAX_DETECT_MODE_T38)) {
3428                         break;
3429                 }
3430                 return f;
3431         default:
3432                 return f;
3433         }
3434
3435         if (f->frametype == AST_FRAME_VOICE) {
3436                 f = ast_dsp_process(chan, faxdetect->dsp, f);
3437                 if (f->frametype == AST_FRAME_DTMF) {
3438                         result = f->subclass.integer;
3439                 }
3440         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->datalen == sizeof(struct ast_control_t38_parameters))) {
3441                 control_params = f->data.ptr;
3442                 switch (control_params->request_response) {
3443                 case AST_T38_NEGOTIATED:
3444                 case AST_T38_REQUEST_NEGOTIATE:
3445                         result = 't';
3446                         break;
3447                 default:
3448                         break;
3449                 }
3450         }
3451
3452         if (result) {
3453                 const char *target_context = S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan));
3454                 switch (result) {
3455                 case 'f':
3456                 case 't':
3457                         ast_channel_unlock(chan);
3458                         if (ast_exists_extension(chan, target_context, "fax", 1,
3459                             S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
3460                                 ast_channel_lock(chan);
3461                                 ast_verb(2, "Redirecting '%s' to fax extension due to %s detection\n",
3462                                         ast_channel_name(chan), (result == 'f') ? "CNG" : "T38");
3463                                 pbx_builtin_setvar_helper(chan, "FAXEXTEN", ast_channel_exten(chan));
3464                                 if (ast_async_goto(chan, target_context, "fax", 1)) {
3465                                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(chan), target_context);
3466                                 }
3467                                 ast_frfree(f);
3468                                 f = &ast_null_frame;
3469                         } else {
3470                                 ast_channel_lock(chan);
3471                                 ast_log(LOG_NOTICE, "FAX %s detected but no fax extension in context (%s)\n",
3472                                         (result == 'f') ? "CNG" : "T38", target_context);
3473                         }
3474                 }
3475                 ast_framehook_detach(chan, details->faxdetect_id);
3476                 details->faxdetect_id = -1;
3477         }
3478
3479         return f;
3480 }
3481
3482 /*! \brief Attach a faxdetect framehook object to a channel.
3483  * \param chan the channel to attach to
3484  * \param timeout remove framehook in this time if set
3485  * \return the faxdetect structure or NULL on error
3486  * \param flags required options
3487  * \retval -1 error
3488  */
3489 static int fax_detect_attach(struct ast_channel *chan, int timeout, int flags)
3490 {
3491         struct fax_detect *faxdetect;
3492         struct ast_fax_session_details *details;
3493         struct ast_framehook_interface fr_hook = {
3494                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
3495                 .event_cb = fax_detect_framehook,
3496                 .destroy_cb = fax_detect_framehook_destroy,
3497         };
3498
3499         if (!(details = find_or_create_details(chan))) {
3500                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
3501                 return -1;
3502         }
3503
3504         /* set up the frame hook*/
3505         faxdetect = fax_detect_new(chan, timeout, flags);
3506         if (!faxdetect) {
3507                 ao2_ref(details, -1);
3508                 return -1;
3509         }
3510
3511         fr_hook.data = faxdetect;
3512         faxdetect->details = details;