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