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