9cb8292f011b3c67a352c5cbc9343285618964dc
[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                 res = ms = -1; \
1219         } while (0)
1220
1221 #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason)     \
1222         do {    \
1223                 ast_log(LOG_ERROR, "channel '%s' FAX session '%d' failure, reason: '%s' (%s)\n", ast_channel_name(chan), fax->id, reason, errorstr); \
1224                 GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason); \
1225         } while (0)
1226
1227 static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
1228 {
1229         switch (ast_channel_get_t38_state(chan)) {
1230         case T38_STATE_UNKNOWN:
1231                 details->caps |= AST_FAX_TECH_T38;
1232                 break;
1233         case T38_STATE_REJECTED:
1234         case T38_STATE_UNAVAILABLE:
1235                 details->caps |= AST_FAX_TECH_AUDIO;
1236                 break;
1237         case T38_STATE_NEGOTIATED:
1238                 /* already in T.38 mode? This should not happen. */
1239         case T38_STATE_NEGOTIATING: {
1240                 /* the other end already sent us a T.38 reinvite, so we need to prod the channel
1241                  * driver into resending their parameters to us if it supports doing so... if
1242                  * not, we can't proceed, because we can't create a proper reply without them.
1243                  * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
1244                  * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
1245                  * that gets called after this one completes
1246                  */
1247                 struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
1248                 if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
1249                         ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1250                         return -1;
1251                 }
1252                 details->caps |= AST_FAX_TECH_T38;
1253                 break;
1254         }
1255         default:
1256                 ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1257                 return -1;
1258         }
1259
1260         return 0;
1261 }
1262
1263 static int disable_t38(struct ast_channel *chan)
1264 {
1265         int ms;
1266         struct ast_frame *frame = NULL;
1267         struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
1268
1269         ast_debug(1, "Shutting down T.38 on %s\n", ast_channel_name(chan));
1270         if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
1271                 ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1272                 return -1;
1273         }
1274
1275         /* wait up to five seconds for negotiation to complete */
1276         ms = 5000;
1277
1278         while (ms > 0) {
1279                 ms = ast_waitfor(chan, ms);
1280                 if (ms < 0) {
1281                         ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1282                         return -1;
1283                 }
1284
1285                 if (ms == 0) { /* all done, nothing happened */
1286                         ast_debug(1, "channel '%s' timed-out during T.38 shutdown\n", ast_channel_name(chan));
1287                         break;
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         return 0;
1318 }
1319
1320 /*! \brief this is the generic FAX session handling function */
1321 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)
1322 {
1323         int ms;
1324         int timeout = RES_FAX_TIMEOUT;
1325         int res = 0, chancount;
1326         unsigned int expected_frametype = -1;
1327         union ast_frame_subclass expected_framesubclass = { .integer = -1 };
1328         unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
1329         struct ast_control_t38_parameters t38_parameters;
1330         const char *tempvar;
1331         struct ast_fax_session *fax = NULL;
1332         struct ast_frame *frame = NULL;
1333         struct ast_channel *c = chan;
1334         struct ast_format orig_write_format;
1335         struct ast_format orig_read_format;
1336
1337         ast_format_clear(&orig_write_format);
1338         ast_format_clear(&orig_read_format);
1339         chancount = 1;
1340
1341         /* create the FAX session */
1342         if (!(fax = fax_session_new(details, chan, reserved, token))) {
1343                 ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
1344                 report_fax_status(chan, details, "No Available Resource");
1345                 return -1;
1346         }
1347
1348         ast_channel_lock(chan);
1349         /* update session details */
1350         if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
1351                 ast_string_field_set(details, headerinfo, tempvar);
1352         }
1353         if (ast_strlen_zero(details->localstationid)) {
1354                 tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
1355                 ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
1356         }
1357         ast_channel_unlock(chan);
1358
1359         report_fax_status(chan, details, "Allocating Resources");
1360
1361         if (details->caps & AST_FAX_TECH_AUDIO) {
1362                 expected_frametype = AST_FRAME_VOICE;;
1363                 ast_format_set(&expected_framesubclass.format, AST_FORMAT_SLINEAR, 0);
1364                 ast_format_copy(&orig_write_format, ast_channel_writeformat(chan));
1365                 if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1366                         ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", ast_channel_name(chan));
1367                         ao2_lock(faxregistry.container);
1368                         ao2_unlink(faxregistry.container, fax);
1369                         ao2_unlock(faxregistry.container);
1370                         ao2_ref(fax, -1);
1371                         ast_channel_unlock(chan);
1372                         return -1;
1373                 }
1374                 ast_format_copy(&orig_read_format, ast_channel_readformat(chan));
1375                 if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1376                         ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", ast_channel_name(chan));
1377                         ao2_lock(faxregistry.container);
1378                         ao2_unlink(faxregistry.container, fax);
1379                         ao2_unlock(faxregistry.container);
1380                         ao2_ref(fax, -1);
1381                         ast_channel_unlock(chan);
1382                         return -1;
1383                 }
1384                 if (fax->smoother) {
1385                         ast_smoother_free(fax->smoother);
1386                         fax->smoother = NULL;
1387                 }
1388                 if (!(fax->smoother = ast_smoother_new(320))) {
1389                         ast_log(LOG_WARNING, "Channel '%s' FAX session '%d' failed to obtain a smoother.\n", ast_channel_name(chan), fax->id);
1390                 }
1391         } else {
1392                 expected_frametype = AST_FRAME_MODEM;
1393                 expected_framesubclass.integer = AST_MODEM_T38;
1394         }
1395
1396         if (fax->debug_info) {
1397                 fax->debug_info->base_tv = ast_tvnow();
1398         }
1399
1400         /* reset our result fields just in case the fax tech driver wants to
1401          * set custom error messages */
1402         ast_string_field_set(details, result, "");
1403         ast_string_field_set(details, resultstr, "");
1404         ast_string_field_set(details, error, "");
1405         set_channel_variables(chan, details);
1406
1407         if (fax->tech->start_session(fax) < 0) {
1408                 GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
1409         }
1410
1411         report_fax_status(chan, details, "FAX Transmission In Progress");
1412
1413         ast_debug(5, "channel %s will wait on FAX fd %d\n", ast_channel_name(chan), fax->fd);
1414
1415         /* handle frames for the session */
1416         ms = 1000;
1417         while ((res > -1) && (ms > -1) && (timeout > 0)) {
1418                 struct ast_channel *ready_chan;
1419                 int ofd, exception;
1420
1421                 ms = 1000;
1422                 errno = 0;
1423                 ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
1424                 if (ready_chan) {
1425                         if (!(frame = ast_read(chan))) {
1426                                 /* the channel is probably gone, so lets stop polling on it and let the
1427                                  * FAX session complete before we exit the application.  if needed,
1428                                  * send the FAX stack silence so the modems can finish their session without
1429                                  * any problems */
1430                                 ast_debug(1, "Channel '%s' did not return a frame; probably hung up.\n", ast_channel_name(chan));
1431                                 GENERIC_FAX_EXEC_SET_VARS(fax, chan, "HANGUP", "remote channel hungup");
1432                                 c = NULL;
1433                                 chancount = 0;
1434                                 timeout -= (1000 - ms);
1435                                 fax->tech->cancel_session(fax);
1436                                 if (fax->tech->generate_silence) {
1437                                         fax->tech->generate_silence(fax);
1438                                 }
1439                                 continue;
1440                         }
1441
1442                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1443                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1444                             (frame->datalen == sizeof(t38_parameters))) {
1445                                 unsigned int was_t38 = t38negotiated;
1446                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1447
1448                                 switch (parameters->request_response) {
1449                                 case AST_T38_REQUEST_NEGOTIATE:
1450                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1451                                          * do T.38 as well
1452                                          */
1453                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1454                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1455                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1456                                         break;
1457                                 case AST_T38_NEGOTIATED:
1458                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1459                                         t38negotiated = 1;
1460                                         break;
1461                                 default:
1462                                         break;
1463                                 }
1464                                 if (t38negotiated && !was_t38) {
1465                                         fax->tech->switch_to_t38(fax);
1466                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1467                                         expected_frametype = AST_FRAME_MODEM;
1468                                         expected_framesubclass.integer = AST_MODEM_T38;
1469                                         if (fax->smoother) {
1470                                                 ast_smoother_free(fax->smoother);
1471                                                 fax->smoother = NULL;
1472                                         }
1473
1474                                         report_fax_status(chan, details, "T.38 Negotiated");
1475
1476                                         ast_verb(3, "Channel '%s' switched to T.38 FAX session '%d'.\n", ast_channel_name(chan), fax->id);
1477                                 }
1478                         } else if ((frame->frametype == expected_frametype) &&
1479                                    (!memcmp(&frame->subclass, &expected_framesubclass, sizeof(frame->subclass)))) {
1480                                 struct ast_frame *f;
1481
1482                                 if (fax->smoother) {
1483                                         /* push the frame into a smoother */
1484                                         if (ast_smoother_feed(fax->smoother, frame) < 0) {
1485                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
1486                                         }
1487                                         while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
1488                                                 if (fax->debug_info) {
1489                                                         debug_check_frame_for_silence(fax, 1, f);
1490                                                 }
1491                                                 /* write the frame to the FAX stack */
1492                                                 fax->tech->write(fax, f);
1493                                                 fax->frames_received++;
1494                                                 if (f != frame) {
1495                                                         ast_frfree(f);
1496                                                 }
1497                                         }
1498                                 } else {
1499                                         /* write the frame to the FAX stack */
1500                                         fax->tech->write(fax, frame);
1501                                         fax->frames_received++;
1502                                 }
1503                                 timeout = RES_FAX_TIMEOUT;
1504                         }
1505                         ast_frfree(frame);
1506                 } else if (ofd == fax->fd) {
1507                         /* read a frame from the FAX stack and send it out the channel.
1508                          * the FAX stack will return a NULL if the FAX session has already completed */
1509                         if (!(frame = fax->tech->read(fax))) {
1510                                 break;
1511                         }
1512
1513                         if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
1514                                 debug_check_frame_for_silence(fax, 0, frame);
1515                         }
1516
1517                         ast_write(chan, frame);
1518                         fax->frames_sent++;
1519                         ast_frfree(frame);
1520                         timeout = RES_FAX_TIMEOUT;
1521                 } else {
1522                         if (ms && (ofd < 0)) {
1523                                 if ((errno == 0) || (errno == EINTR)) {
1524                                         timeout -= (1000 - ms);
1525                                         if (timeout <= 0)
1526                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1527                                         continue;
1528                                 } else {
1529                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(chan));
1530                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "error polling data");
1531                                         res = ms;
1532                                         break;
1533                                 }
1534                         } else {
1535                                 /* nothing happened */
1536                                 if (timeout > 0) {
1537                                         timeout -= 1000;
1538                                         if (timeout <= 0)
1539                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1540                                         continue;
1541                                 } else {
1542                                         ast_log(LOG_WARNING, "channel '%s' timed-out during the FAX transmission.\n", ast_channel_name(chan));
1543                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1544                                         break;
1545                                 }
1546                         }
1547                 }
1548         }
1549         ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, ms: %d, res: %d }\n", ast_channel_name(chan), timeout, ms, res);
1550
1551         set_channel_variables(chan, details);
1552
1553         ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
1554         if (!strcasecmp(details->result, "FAILED")) {
1555                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1556         }
1557
1558         if (fax) {
1559                 ao2_lock(faxregistry.container);
1560                 ao2_unlink(faxregistry.container, fax);
1561                 ao2_unlock(faxregistry.container);
1562                 ao2_ref(fax, -1);
1563         }
1564
1565         /* if the channel is still alive, and we changed its read/write formats,
1566          * restore them now
1567          */
1568         if (chancount) {
1569                 if (orig_read_format.id) {
1570                         ast_set_read_format(chan, &orig_read_format);
1571                 }
1572                 if (orig_write_format.id) {
1573                         ast_set_write_format(chan, &orig_write_format);
1574                 }
1575         }
1576
1577         /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
1578         return chancount;
1579 }
1580
1581 static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1582 {
1583         int ms;
1584         struct ast_frame *frame = NULL;
1585         struct ast_control_t38_parameters t38_parameters;
1586
1587         /* don't send any audio if we've already received a T.38 reinvite */
1588         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1589                 /* generate 3 seconds of CED */
1590                 if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
1591                         ast_log(LOG_ERROR, "error generating CED tone on %s\n", ast_channel_name(chan));
1592                         return -1;
1593                 }
1594
1595                 ms = 3000;
1596                 while (ms > 0) {
1597                         ms = ast_waitfor(chan, ms);
1598                         if (ms < 0) {
1599                                 ast_log(LOG_ERROR, "error while generating CED tone on %s\n", ast_channel_name(chan));
1600                                 ast_playtones_stop(chan);
1601                                 return -1;
1602                         }
1603
1604                         if (ms == 0) { /* all done, nothing happened */
1605                                 break;
1606                         }
1607
1608                         if (!(frame = ast_read(chan))) {
1609                                 ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", ast_channel_name(chan));
1610                                 ast_playtones_stop(chan);
1611                                 return -1;
1612                         }
1613
1614                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1615                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1616                             (frame->datalen == sizeof(t38_parameters))) {
1617                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1618
1619                                 switch (parameters->request_response) {
1620                                 case AST_T38_REQUEST_NEGOTIATE:
1621                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1622                                          * do T.38 as well
1623                                          */
1624                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1625                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1626                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1627                                         ast_playtones_stop(chan);
1628                                         break;
1629                                 case AST_T38_NEGOTIATED:
1630                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1631                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1632                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1633                                         report_fax_status(chan, details, "T.38 Negotiated");
1634                                         break;
1635                                 default:
1636                                         break;
1637                                 }
1638                         }
1639                         ast_frfree(frame);
1640                 }
1641
1642                 ast_playtones_stop(chan);
1643         }
1644
1645         /* if T.38 was negotiated, we are done initializing */
1646         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1647                 return 0;
1648         }
1649
1650         /* request T.38 */
1651         ast_debug(1, "Negotiating T.38 for receive on %s\n", ast_channel_name(chan));
1652
1653         /* wait up to five seconds for negotiation to complete */
1654         ms = 5000;
1655
1656         /* set parameters based on the session's parameters */
1657         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1658         t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
1659         if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
1660                 return -1;
1661         }
1662
1663         while (ms > 0) {
1664                 ms = ast_waitfor(chan, ms);
1665                 if (ms < 0) {
1666                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1667                         return -1;
1668                 }
1669
1670                 if (ms == 0) { /* all done, nothing happened */
1671                         ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
1672                         details->caps &= ~AST_FAX_TECH_T38;
1673                         break;
1674                 }
1675
1676                 if (!(frame = ast_read(chan))) {
1677                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1678                         return -1;
1679                 }
1680
1681                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1682                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1683                                 (frame->datalen == sizeof(t38_parameters))) {
1684                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1685
1686                         switch (parameters->request_response) {
1687                         case AST_T38_REQUEST_NEGOTIATE:
1688                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1689                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
1690                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1691                                 break;
1692                         case AST_T38_NEGOTIATED:
1693                                 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1694                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1695                                 details->caps &= ~AST_FAX_TECH_AUDIO;
1696                                 report_fax_status(chan, details, "T.38 Negotiated");
1697                                 ms = 0;
1698                                 break;
1699                         case AST_T38_REFUSED:
1700                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
1701                                 details->caps &= ~AST_FAX_TECH_T38;
1702                                 ms = 0;
1703                                 break;
1704                         default:
1705                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
1706                                 details->caps &= ~AST_FAX_TECH_T38;
1707                                 ms = 0;
1708                                 break;
1709                         }
1710                 }
1711                 ast_frfree(frame);
1712         }
1713
1714         /* if T.38 was negotiated, we are done initializing */
1715         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1716                 return 0;
1717         }
1718
1719         /* if we made it here, then T.38 failed, check the 'f' flag */
1720         if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
1721                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
1722                 return -1;
1723         }
1724
1725         /* ok, audio fallback is allowed */
1726         details->caps |= AST_FAX_TECH_AUDIO;
1727
1728         return 0;
1729 }
1730
1731 /*! \brief initiate a receive FAX session */
1732 static int receivefax_exec(struct ast_channel *chan, const char *data)
1733 {
1734         char *parse, modems[128] = "";
1735         int channel_alive;
1736         struct ast_fax_session_details *details;
1737         struct ast_fax_session *s;
1738         struct ast_fax_tech_token *token = NULL;
1739         struct ast_fax_document *doc;
1740         AST_DECLARE_APP_ARGS(args,
1741                 AST_APP_ARG(filename);
1742                 AST_APP_ARG(options);
1743         );
1744         struct ast_flags opts = { 0, };
1745         struct manager_event_info info;
1746         enum ast_t38_state t38state;
1747
1748         /* initialize output channel variables */
1749         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
1750         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
1751         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
1752         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
1753         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
1754
1755         /* Get a FAX session details structure from the channel's FAX datastore and create one if
1756          * it does not already exist. */
1757         if (!(details = find_or_create_details(chan))) {
1758                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
1759                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
1760                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1761                 return -1;
1762         }
1763
1764         ast_string_field_set(details, result, "FAILED");
1765         ast_string_field_set(details, resultstr, "error starting fax session");
1766         ast_string_field_set(details, error, "INIT_ERROR");
1767         set_channel_variables(chan, details);
1768
1769         if (details->gateway_id > 0) {
1770                 ast_string_field_set(details, resultstr, "can't receive a fax on a channel with a T.38 gateway");
1771                 set_channel_variables(chan, details);
1772                 ast_log(LOG_ERROR, "executing ReceiveFAX on a channel with a T.38 Gateway is not supported\n");
1773                 ao2_ref(details, -1);
1774                 return -1;
1775         }
1776
1777         if (details->maxrate < details->minrate) {
1778                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1779                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
1780                 set_channel_variables(chan, details);
1781                 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
1782                 ao2_ref(details, -1);
1783                 return -1;
1784         }
1785
1786         if (check_modem_rate(details->modems, details->minrate)) {
1787                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1788                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
1789                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1790                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
1791                 set_channel_variables(chan, details);
1792                 ao2_ref(details, -1);
1793                 return -1;
1794         }
1795
1796         if (check_modem_rate(details->modems, details->maxrate)) {
1797                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1798                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
1799                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1800                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
1801                 set_channel_variables(chan, details);
1802                 ao2_ref(details, -1);
1803                 return -1;
1804         }
1805
1806         if (ast_strlen_zero(data)) {
1807                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1808                 ast_string_field_set(details, resultstr, "invalid arguments");
1809                 set_channel_variables(chan, details);
1810                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1811                 ao2_ref(details, -1);
1812                 return -1;
1813         }
1814         parse = ast_strdupa(data);
1815         AST_STANDARD_APP_ARGS(args, parse);
1816
1817         if (!ast_strlen_zero(args.options) &&
1818             ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
1819                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1820                 ast_string_field_set(details, resultstr, "invalid arguments");
1821                 set_channel_variables(chan, details);
1822                 ao2_ref(details, -1);
1823                 return -1;
1824         }
1825         if (ast_strlen_zero(args.filename)) {
1826                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1827                 ast_string_field_set(details, resultstr, "invalid arguments");
1828                 set_channel_variables(chan, details);
1829                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1830                 ao2_ref(details, -1);
1831                 return -1;
1832         }
1833
1834         /* check for unsupported FAX application options */
1835         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
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 does not support polling\n", app_receivefax);
1840                 ao2_ref(details, -1);
1841                 return -1;
1842         }
1843
1844         ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
1845
1846         pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
1847         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
1848
1849         if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
1850                 ast_string_field_set(details, error, "MEMORY_ERROR");
1851                 ast_string_field_set(details, resultstr, "error allocating memory");
1852                 set_channel_variables(chan, details);
1853                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1854                 ao2_ref(details, -1);
1855                 return -1;
1856         }
1857
1858         strcpy(doc->filename, args.filename);
1859         AST_LIST_INSERT_TAIL(&details->documents, doc, next);
1860
1861         ast_verb(3, "Channel '%s' receiving FAX '%s'\n", ast_channel_name(chan), args.filename);
1862
1863         details->caps = AST_FAX_TECH_RECEIVE;
1864
1865         /* check for debug */
1866         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
1867                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
1868         }
1869
1870         /* check for request for status events */
1871         if (ast_test_flag(&opts, OPT_STATUS)) {
1872                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
1873         }
1874
1875         t38state = ast_channel_get_t38_state(chan);
1876         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
1877             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
1878             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1879                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
1880         }
1881
1882         if (!(s = fax_session_reserve(details, &token))) {
1883                 ast_string_field_set(details, resultstr, "error reserving fax session");
1884                 set_channel_variables(chan, details);
1885                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
1886                 ao2_ref(details, -1);
1887                 return -1;
1888         }
1889
1890         /* make sure the channel is up */
1891         if (ast_channel_state(chan) != AST_STATE_UP) {
1892                 if (ast_answer(chan)) {
1893                         ast_string_field_set(details, resultstr, "error answering channel");
1894                         set_channel_variables(chan, details);
1895                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
1896                         fax_session_release(s, token);
1897                         ao2_ref(s, -1);
1898                         ao2_ref(details, -1);
1899                         return -1;
1900                 }
1901         }
1902
1903         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1904                 if (set_fax_t38_caps(chan, details)) {
1905                         ast_string_field_set(details, error, "T38_NEG_ERROR");
1906                         ast_string_field_set(details, resultstr, "error negotiating T.38");
1907                         set_channel_variables(chan, details);
1908                         fax_session_release(s, token);
1909                         ao2_ref(s, -1);
1910                         ao2_ref(details, -1);
1911                         return -1;
1912                 }
1913         } else {
1914                 details->caps |= AST_FAX_TECH_AUDIO;
1915         }
1916
1917         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
1918                 if (receivefax_t38_init(chan, details)) {
1919                         ast_string_field_set(details, error, "T38_NEG_ERROR");
1920                         ast_string_field_set(details, resultstr, "error negotiating T.38");
1921                         set_channel_variables(chan, details);
1922                         fax_session_release(s, token);
1923                         ao2_ref(s, -1);
1924                         ao2_ref(details, -1);
1925                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
1926                         return -1;
1927                 }
1928         } else {
1929                 details->option.send_ced = 1;
1930         }
1931
1932         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
1933                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1934         }
1935
1936         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1937                 if (disable_t38(chan)) {
1938                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
1939                 }
1940         }
1941
1942         /* send out the AMI completion event */
1943         ast_channel_lock(chan);
1944
1945         get_manager_event_info(chan, &info);
1946         manager_event(EVENT_FLAG_CALL,
1947                       "ReceiveFAX",
1948                       "Channel: %s\r\n"
1949                       "Context: %s\r\n"
1950                       "Exten: %s\r\n"
1951                       "CallerID: %s\r\n"
1952                       "RemoteStationID: %s\r\n"
1953                       "LocalStationID: %s\r\n"
1954                       "PagesTransferred: %s\r\n"
1955                       "Resolution: %s\r\n"
1956                       "TransferRate: %s\r\n"
1957                       "FileName: %s\r\n",
1958                       ast_channel_name(chan),
1959                       info.context,
1960                       info.exten,
1961                       info.cid,
1962                       S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), ""),
1963                       S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), ""),
1964                       S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), ""),
1965                       S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), ""),
1966                       S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), ""),
1967                       args.filename);
1968         ast_channel_unlock(chan);
1969
1970         ao2_ref(s, -1);
1971         ao2_ref(details, -1);
1972
1973         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
1974         return (!channel_alive) ? -1 : 0;
1975 }
1976
1977 static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1978 {
1979         int ms;
1980         struct ast_frame *frame = NULL;
1981         struct ast_control_t38_parameters t38_parameters;
1982
1983         /* send CNG tone while listening for the receiver to initiate a switch
1984          * to T.38 mode; if they do, stop sending the CNG tone and proceed with
1985          * the switch.
1986          *
1987          * 10500 is enough time for 3 CNG tones
1988          */
1989         ms = 10500;
1990
1991         /* don't send any audio if we've already received a T.38 reinvite */
1992         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1993                 if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
1994                         ast_log(LOG_ERROR, "error generating CNG tone on %s\n", ast_channel_name(chan));
1995                         return -1;
1996                 }
1997         }
1998
1999         while (ms > 0) {
2000                 ms = ast_waitfor(chan, ms);
2001                 if (ms < 0) {
2002                         ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", ast_channel_name(chan));
2003                         ast_playtones_stop(chan);
2004                         return -1;
2005                 }
2006
2007                 if (ms == 0) { /* all done, nothing happened */
2008                         break;
2009                 }
2010
2011                 if (!(frame = ast_read(chan))) {
2012                         ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", ast_channel_name(chan));
2013                         ast_playtones_stop(chan);
2014                         return -1;
2015                 }
2016
2017                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2018                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2019                                 (frame->datalen == sizeof(t38_parameters))) {
2020                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2021
2022                         switch (parameters->request_response) {
2023                         case AST_T38_REQUEST_NEGOTIATE:
2024                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2025                                  * do T.38 as well
2026                                  */
2027                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2028                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2029                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2030                                 ast_playtones_stop(chan);
2031                                 break;
2032                         case AST_T38_NEGOTIATED:
2033                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2034                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2035                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2036                                 report_fax_status(chan, details, "T.38 Negotiated");
2037                                 ms = 0;
2038                                 break;
2039                         default:
2040                                 break;
2041                         }
2042                 }
2043                 ast_frfree(frame);
2044         }
2045
2046         ast_playtones_stop(chan);
2047
2048         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2049                 return 0;
2050         }
2051
2052         /* T.38 negotiation did not happen, initiate a switch if requested */
2053         if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
2054                 ast_debug(1, "Negotiating T.38 for send on %s\n", ast_channel_name(chan));
2055
2056                 /* wait up to five seconds for negotiation to complete */
2057                 ms = 5000;
2058
2059                 /* set parameters based on the session's parameters */
2060                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2061                 t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
2062                 if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
2063                         return -1;
2064                 }
2065
2066                 while (ms > 0) {
2067                         ms = ast_waitfor(chan, ms);
2068                         if (ms < 0) {
2069                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2070                                 return -1;
2071                         }
2072
2073                         if (ms == 0) { /* all done, nothing happened */
2074                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
2075                                 details->caps &= ~AST_FAX_TECH_T38;
2076                                 break;
2077                         }
2078
2079                         if (!(frame = ast_read(chan))) {
2080                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2081                                 return -1;
2082                         }
2083
2084                         if ((frame->frametype == AST_FRAME_CONTROL) &&
2085                                         (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2086                                         (frame->datalen == sizeof(t38_parameters))) {
2087                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
2088
2089                                 switch (parameters->request_response) {
2090                                 case AST_T38_REQUEST_NEGOTIATE:
2091                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2092                                         t38_parameters.request_response = AST_T38_NEGOTIATED;
2093                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2094                                         break;
2095                                 case AST_T38_NEGOTIATED:
2096                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
2097                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2098                                         details->caps &= ~AST_FAX_TECH_AUDIO;
2099                                         report_fax_status(chan, details, "T.38 Negotiated");
2100                                         ms = 0;
2101                                         break;
2102                                 case AST_T38_REFUSED:
2103                                         ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
2104                                         details->caps &= ~AST_FAX_TECH_T38;
2105                                         ms = 0;
2106                                         break;
2107                                 default:
2108                                         ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
2109                                         details->caps &= ~AST_FAX_TECH_T38;
2110                                         ms = 0;
2111                                         break;
2112                                 }
2113                         }
2114                         ast_frfree(frame);
2115                 }
2116
2117                 /* if T.38 was negotiated, we are done initializing */
2118                 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2119                         return 0;
2120                 }
2121
2122                 /* send one more CNG tone to get audio going again for some
2123                  * carriers if we are going to fall back to audio mode */
2124                 if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
2125                         if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
2126                                 ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", ast_channel_name(chan));
2127                                 return -1;
2128                         }
2129
2130                         ms = 3500;
2131                         while (ms > 0) {
2132                                 ms = ast_waitfor(chan, ms);
2133                                 if (ms < 0) {
2134                                         ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", ast_channel_name(chan));
2135                                         ast_playtones_stop(chan);
2136                                         return -1;
2137                                 }
2138
2139                                 if (ms == 0) { /* all done, nothing happened */
2140                                         break;
2141                                 }
2142
2143                                 if (!(frame = ast_read(chan))) {
2144                                         ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", ast_channel_name(chan));
2145                                         ast_playtones_stop(chan);
2146                                         return -1;
2147                                 }
2148
2149                                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2150                                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2151                                                 (frame->datalen == sizeof(t38_parameters))) {
2152                                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2153
2154                                         switch (parameters->request_response) {
2155                                         case AST_T38_REQUEST_NEGOTIATE:
2156                                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2157                                                  * do T.38 as well
2158                                                  */
2159                                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2160                                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2161                                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2162                                                 ast_playtones_stop(chan);
2163                                                 break;
2164                                         case AST_T38_NEGOTIATED:
2165                                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2166                                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2167                                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2168                                                 report_fax_status(chan, details, "T.38 Negotiated");
2169                                                 ms = 0;
2170                                                 break;
2171                                         default:
2172                                                 break;
2173                                         }
2174                                 }
2175                                 ast_frfree(frame);
2176                         }
2177
2178                         ast_playtones_stop(chan);
2179
2180                         /* if T.38 was negotiated, we are done initializing */
2181                         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2182                                 return 0;
2183                         }
2184                 }
2185         }
2186
2187         /* if we made it here, then T.38 failed, check the 'f' flag */
2188         if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
2189                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
2190                 return -1;
2191         }
2192
2193         /* ok, audio fallback is allowed */
2194         details->caps |= AST_FAX_TECH_AUDIO;
2195
2196         return 0;
2197 }
2198
2199
2200 /*! \brief initiate a send FAX session */
2201 static int sendfax_exec(struct ast_channel *chan, const char *data)
2202 {
2203         char *parse, *filenames, *c, modems[128] = "";
2204         int channel_alive, file_count;
2205         struct ast_fax_session_details *details;
2206         struct ast_fax_session *s;
2207         struct ast_fax_tech_token *token = NULL;
2208         struct ast_fax_document *doc;
2209         AST_DECLARE_APP_ARGS(args,
2210                 AST_APP_ARG(filenames);
2211                 AST_APP_ARG(options);
2212         );
2213         struct ast_flags opts = { 0, };
2214         struct manager_event_info info;
2215         enum ast_t38_state t38state;
2216
2217         /* initialize output channel variables */
2218         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
2219         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
2220         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
2221         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
2222         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
2223
2224         /* Get a requirement structure and set it.  This structure is used
2225          * to tell the FAX technology module about the higher level FAX session */
2226         if (!(details = find_or_create_details(chan))) {
2227                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
2228                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
2229                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2230                 return -1;
2231         }
2232
2233         ast_string_field_set(details, result, "FAILED");
2234         ast_string_field_set(details, resultstr, "error starting fax session");
2235         ast_string_field_set(details, error, "INIT_ERROR");
2236         set_channel_variables(chan, details);
2237
2238         if (details->gateway_id > 0) {
2239                 ast_string_field_set(details, resultstr, "can't send a fax on a channel with a T.38 gateway");
2240                 set_channel_variables(chan, details);
2241                 ast_log(LOG_ERROR, "executing SendFAX on a channel with a T.38 Gateway is not supported\n");
2242                 ao2_ref(details, -1);
2243                 return -1;
2244         }
2245
2246         if (details->maxrate < details->minrate) {
2247                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2248                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
2249                 set_channel_variables(chan, details);
2250                 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
2251                 ao2_ref(details, -1);
2252                 return -1;
2253         }
2254
2255         if (check_modem_rate(details->modems, details->minrate)) {
2256                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2257                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
2258                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2259                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
2260                 set_channel_variables(chan, details);
2261                 ao2_ref(details, -1);
2262                 return -1;
2263         }
2264
2265         if (check_modem_rate(details->modems, details->maxrate)) {
2266                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2267                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
2268                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2269                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
2270                 set_channel_variables(chan, details);
2271                 ao2_ref(details, -1);
2272                 return -1;
2273         }
2274
2275         if (ast_strlen_zero(data)) {
2276                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2277                 ast_string_field_set(details, resultstr, "invalid arguments");
2278                 set_channel_variables(chan, details);
2279                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
2280                 ao2_ref(details, -1);
2281                 return -1;
2282         }
2283         parse = ast_strdupa(data);
2284         AST_STANDARD_APP_ARGS(args, parse);
2285
2286
2287         if (!ast_strlen_zero(args.options) &&
2288             ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
2289                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2290                 ast_string_field_set(details, resultstr, "invalid arguments");
2291                 set_channel_variables(chan, details);
2292                 ao2_ref(details, -1);
2293                 return -1;
2294         }
2295         if (ast_strlen_zero(args.filenames)) {
2296                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2297                 ast_string_field_set(details, resultstr, "invalid arguments");
2298                 set_channel_variables(chan, details);
2299                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
2300                 ao2_ref(details, -1);
2301                 return -1;
2302         }
2303
2304         /* check for unsupported FAX application options */
2305         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
2306                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2307                 ast_string_field_set(details, resultstr, "invalid arguments");
2308                 set_channel_variables(chan, details);
2309                 ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
2310                 ao2_ref(details, -1);
2311                 return -1;
2312         }
2313
2314         ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
2315
2316         file_count = 0;
2317         filenames = args.filenames;
2318         while ((c = strsep(&filenames, "&"))) {
2319                 if (access(c, (F_OK | R_OK)) < 0) {
2320                         ast_string_field_set(details, error, "FILE_ERROR");
2321                         ast_string_field_set(details, resultstr, "error reading file");
2322                         set_channel_variables(chan, details);
2323                         ast_log(LOG_ERROR, "access failure.  Verify '%s' exists and check permissions.\n", args.filenames);
2324                         ao2_ref(details, -1);
2325                         return -1;
2326                 }
2327
2328                 if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
2329                         ast_string_field_set(details, error, "MEMORY_ERROR");
2330                         ast_string_field_set(details, resultstr, "error allocating memory");
2331                         set_channel_variables(chan, details);
2332                         ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2333                         ao2_ref(details, -1);
2334                         return -1;
2335                 }
2336
2337                 strcpy(doc->filename, c);
2338                 AST_LIST_INSERT_TAIL(&details->documents, doc, next);
2339                 file_count++;
2340         }
2341
2342         ast_verb(3, "Channel '%s' sending FAX:\n", ast_channel_name(chan));
2343         AST_LIST_TRAVERSE(&details->documents, doc, next) {
2344                 ast_verb(3, "   %s\n", doc->filename);
2345         }
2346
2347         details->caps = AST_FAX_TECH_SEND;
2348
2349         if (file_count > 1) {
2350                 details->caps |= AST_FAX_TECH_MULTI_DOC;
2351         }
2352
2353         /* check for debug */
2354         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
2355                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
2356         }
2357
2358         /* check for request for status events */
2359         if (ast_test_flag(&opts, OPT_STATUS)) {
2360                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
2361         }
2362
2363         t38state = ast_channel_get_t38_state(chan);
2364         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
2365             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
2366             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2367                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
2368         }
2369
2370         if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
2371                 details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
2372         }
2373
2374         if (!(s = fax_session_reserve(details, &token))) {
2375                 ast_string_field_set(details, resultstr, "error reserving fax session");
2376                 set_channel_variables(chan, details);
2377                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
2378                 ao2_ref(details, -1);
2379                 return -1;
2380         }
2381
2382         /* make sure the channel is up */
2383         if (ast_channel_state(chan) != AST_STATE_UP) {
2384                 if (ast_answer(chan)) {
2385                         ast_string_field_set(details, resultstr, "error answering channel");
2386                         set_channel_variables(chan, details);
2387                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
2388                         fax_session_release(s, token);
2389                         ao2_ref(s, -1);
2390                         ao2_ref(details, -1);
2391                         return -1;
2392                 }
2393         }
2394
2395         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2396                 if (set_fax_t38_caps(chan, details)) {
2397                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2398                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2399                         set_channel_variables(chan, details);
2400                         fax_session_release(s, token);
2401                         ao2_ref(s, -1);
2402                         ao2_ref(details, -1);
2403                         return -1;
2404                 }
2405         } else {
2406                 details->caps |= AST_FAX_TECH_AUDIO;
2407         }
2408
2409         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2410                 if (sendfax_t38_init(chan, details)) {
2411                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2412                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2413                         set_channel_variables(chan, details);
2414                         fax_session_release(s, token);
2415                         ao2_ref(s, -1);
2416                         ao2_ref(details, -1);
2417                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2418                         return -1;
2419                 }
2420         } else {
2421                 details->option.send_cng = 1;
2422         }
2423
2424         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2425                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2426         }
2427
2428         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2429                 if (disable_t38(chan)) {
2430                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2431                 }
2432         }
2433
2434         if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
2435                 ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
2436                 ao2_ref(s, -1);
2437                 ao2_ref(details, -1);
2438                 return (!channel_alive) ? -1 : 0;
2439         }
2440
2441         /* send out the AMI completion event */
2442         ast_channel_lock(chan);
2443         get_manager_event_info(chan, &info);
2444         manager_event(EVENT_FLAG_CALL,
2445                       "SendFAX",
2446                       "Channel: %s\r\n"
2447                       "Context: %s\r\n"
2448                       "Exten: %s\r\n"
2449                       "CallerID: %s\r\n"
2450                       "RemoteStationID: %s\r\n"
2451                       "LocalStationID: %s\r\n"
2452                       "PagesTransferred: %s\r\n"
2453                       "Resolution: %s\r\n"
2454                       "TransferRate: %s\r\n"
2455                       "%s\r\n",
2456                       ast_channel_name(chan),
2457                       info.context,
2458                       info.exten,
2459                       info.cid,
2460                       S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), ""),
2461                       S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), ""),
2462                       S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), ""),
2463                       S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), ""),
2464                       S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), ""),
2465                       filenames);
2466         ast_channel_unlock(chan);
2467
2468         ast_free(filenames);
2469
2470         ao2_ref(s, -1);
2471         ao2_ref(details, -1);
2472
2473         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2474         return (!channel_alive) ? -1 : 0;
2475 }
2476
2477 /*! \brief destroy the v21 detection parts of a fax gateway session */
2478 static void destroy_v21_sessions(struct fax_gateway *gateway)
2479 {
2480         if (gateway->chan_v21_session) {
2481                 ao2_lock(faxregistry.container);
2482                 ao2_unlink(faxregistry.container, gateway->chan_v21_session);
2483                 ao2_unlock(faxregistry.container);
2484
2485                 ao2_ref(gateway->chan_v21_session, -1);
2486                 gateway->chan_v21_session = NULL;
2487         }
2488
2489         if (gateway->peer_v21_session) {
2490                 ao2_lock(faxregistry.container);
2491                 ao2_unlink(faxregistry.container, gateway->peer_v21_session);
2492                 ao2_unlock(faxregistry.container);
2493
2494                 ao2_ref(gateway->peer_v21_session, -1);
2495                 gateway->peer_v21_session = NULL;
2496         }
2497 }
2498
2499 /*! \brief destroy a FAX gateway session structure */
2500 static void destroy_gateway(void *data)
2501 {
2502         struct fax_gateway *gateway = data;
2503
2504         destroy_v21_sessions(gateway);
2505
2506         if (gateway->s) {
2507                 fax_session_release(gateway->s, gateway->token);
2508                 gateway->token = NULL;
2509
2510                 ao2_lock(faxregistry.container);
2511                 ao2_unlink(faxregistry.container, gateway->s);
2512                 ao2_unlock(faxregistry.container);
2513
2514                 ao2_ref(gateway->s, -1);
2515                 gateway->s = NULL;
2516         }
2517 }
2518
2519 /*! \brief Create a new fax gateway object.
2520  * \param chan the channel the gateway object will be attached to
2521  * \param details the fax session details
2522  * \return NULL or a fax gateway object
2523  */
2524 static struct fax_gateway *fax_gateway_new(struct ast_channel *chan, struct ast_fax_session_details *details)
2525 {
2526         struct fax_gateway *gateway = ao2_alloc(sizeof(*gateway), destroy_gateway);
2527         struct ast_fax_session_details *v21_details;
2528         if (!gateway) {
2529                 return NULL;
2530         }
2531
2532         if (!(v21_details = session_details_new())) {
2533                 ao2_ref(gateway, -1);
2534                 return NULL;
2535         }
2536
2537         v21_details->caps = AST_FAX_TECH_V21_DETECT;
2538         if (!(gateway->chan_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2539                 ao2_ref(v21_details, -1);
2540                 ao2_ref(gateway, -1);
2541                 return NULL;
2542         }
2543
2544         if (!(gateway->peer_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2545                 ao2_ref(v21_details, -1);
2546                 ao2_ref(gateway, -1);
2547                 return NULL;
2548         }
2549         ao2_ref(v21_details, -1);
2550
2551         gateway->framehook = -1;
2552
2553         details->caps = AST_FAX_TECH_GATEWAY;
2554         if (details->gateway_timeout && !(gateway->s = fax_session_reserve(details, &gateway->token))) {
2555                 details->caps &= ~AST_FAX_TECH_GATEWAY;
2556                 ast_log(LOG_ERROR, "Can't reserve a FAX session, gateway attempt failed.\n");
2557                 ao2_ref(gateway, -1);
2558                 return NULL;
2559         }
2560
2561         return gateway;
2562 }
2563
2564 /*! \brief Create a fax session and start T.30<->T.38 gateway mode
2565  * \param gateway a fax gateway object
2566  * \param details fax session details
2567  * \param chan active channel
2568  * \return 0 on error 1 on success*/
2569 static int fax_gateway_start(struct fax_gateway *gateway, struct ast_fax_session_details *details, struct ast_channel *chan)
2570 {
2571         struct ast_fax_session *s;
2572
2573         /* create the FAX session */
2574         if (!(s = fax_session_new(details, chan, gateway->s, gateway->token))) {
2575                 gateway->token = NULL;
2576                 ast_string_field_set(details, result, "FAILED");
2577                 ast_string_field_set(details, resultstr, "error starting gateway session");
2578                 ast_string_field_set(details, error, "INIT_ERROR");
2579                 set_channel_variables(chan, details);
2580                 report_fax_status(chan, details, "No Available Resource");
2581                 ast_log(LOG_ERROR, "Can't create a FAX session, gateway attempt failed.\n");
2582                 return -1;
2583         }
2584         /* release the reference for the reserved session and replace it with
2585          * the real session */
2586         ao2_ref(gateway->s, -1);
2587         gateway->s = s;
2588         gateway->token = NULL;
2589
2590         if (gateway->s->tech->start_session(gateway->s) < 0) {
2591                 ast_string_field_set(details, result, "FAILED");
2592                 ast_string_field_set(details, resultstr, "error starting gateway session");
2593                 ast_string_field_set(details, error, "INIT_ERROR");
2594                 set_channel_variables(chan, details);
2595                 return -1;
2596         }
2597
2598         gateway->timeout_start.tv_sec = 0;
2599         gateway->timeout_start.tv_usec = 0;
2600
2601         report_fax_status(chan, details, "FAX Transmission In Progress");
2602
2603         return 0;
2604 }
2605
2606 static struct ast_frame *fax_gateway_request_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_frame *f)
2607 {
2608         struct ast_frame *fp;
2609         struct ast_control_t38_parameters t38_parameters = {
2610                 .request_response = AST_T38_REQUEST_NEGOTIATE,
2611         };
2612         struct ast_frame control_frame = {
2613                 .src = "res_fax",
2614                 .frametype = AST_FRAME_CONTROL,
2615                 .datalen = sizeof(t38_parameters),
2616                 .subclass.integer = AST_CONTROL_T38_PARAMETERS,
2617                 .data.ptr = &t38_parameters,
2618         };
2619
2620         struct ast_fax_session_details *details = find_details(chan);
2621
2622         if (!details) {
2623                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2624                 ast_framehook_detach(chan, gateway->framehook);
2625                 return f;
2626         }
2627
2628         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2629         ao2_ref(details, -1);
2630
2631         if (!(fp = ast_frisolate(&control_frame))) {
2632                 ast_log(LOG_ERROR, "error generating T.38 request control frame on chan %s for T.38 gateway session\n", ast_channel_name(chan));
2633                 return f;
2634         }
2635
2636         gateway->t38_state = T38_STATE_NEGOTIATING;
2637         gateway->timeout_start = ast_tvnow();
2638         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2639
2640         ast_debug(1, "requesting T.38 for gateway session for %s\n", ast_channel_name(chan));
2641         return fp;
2642 }
2643
2644 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)
2645 {
2646         struct ast_channel *other = (active == chan) ? peer : chan;
2647         struct ast_fax_session *active_v21_session = (active == chan) ? gateway->chan_v21_session : gateway->peer_v21_session;
2648
2649         if (!active_v21_session || gateway->detected_v21) {
2650                 return f;
2651         }
2652
2653         if (active_v21_session->tech->write(active_v21_session, f) == 0 &&
2654             active_v21_session->details->option.v21_detected) {
2655                 gateway->detected_v21 = 1;
2656         }
2657
2658         if (gateway->detected_v21) {
2659                 destroy_v21_sessions(gateway);
2660                 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2661                         ast_debug(1, "detected v21 preamble from %s\n", ast_channel_name(active));
2662                         return fax_gateway_request_t38(gateway, chan, f);
2663                 } else {
2664                         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));
2665                 }
2666         }
2667
2668         return f;
2669 }
2670
2671 static int fax_gateway_indicate_t38(struct ast_channel *chan, struct ast_channel *active, struct ast_control_t38_parameters *control_params)
2672 {
2673         if (active == chan) {
2674                 return ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2675         } else {
2676                 return ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2677         }
2678 }
2679
2680 /*! \brief T38 Gateway Negotiate t38 parameters
2681  * \param gateway gateway object
2682  * \param chan channel running the gateway
2683  * \param peer channel im bridged too
2684  * \param active channel the frame originated on
2685  * \param f the control frame to process
2686  * \return processed control frame or null frame
2687  */
2688 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)
2689 {
2690         struct ast_control_t38_parameters *control_params = f->data.ptr;
2691         struct ast_channel *other = (active == chan) ? peer : chan;
2692         struct ast_fax_session_details *details;
2693
2694         if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
2695                 /* invalaid AST_CONTROL_T38_PARAMETERS frame, we can't
2696                  * do anything with it, pass it on */
2697                 return f;
2698         }
2699
2700         /* ignore frames from ourselves */
2701         if ((gateway->t38_state == T38_STATE_NEGOTIATED && control_params->request_response == AST_T38_NEGOTIATED)
2702                 || (gateway->t38_state == T38_STATE_REJECTED && control_params->request_response == AST_T38_REFUSED)
2703                 || (gateway->t38_state == T38_STATE_NEGOTIATING && control_params->request_response == AST_T38_REQUEST_TERMINATE)) {
2704
2705                 return f;
2706         }
2707
2708         if (!(details = find_details(chan))) {
2709                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2710                 ast_framehook_detach(chan, gateway->framehook);
2711                 return f;
2712         }
2713
2714         if (control_params->request_response == AST_T38_REQUEST_NEGOTIATE) {
2715                 enum ast_t38_state state = ast_channel_get_t38_state(other);
2716
2717                 if (state == T38_STATE_UNKNOWN) {
2718                         /* we detected a request to negotiate T.38 and the
2719                          * other channel appears to support T.38, we'll pass
2720                          * the request through and only step in if the other
2721                          * channel rejects the request */
2722                         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));
2723                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2724                         gateway->t38_state = T38_STATE_UNKNOWN;
2725                         gateway->timeout_start = ast_tvnow();
2726                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2727                         ao2_ref(details, -1);
2728                         return f;
2729                 } else if (state == T38_STATE_UNAVAILABLE || state == T38_STATE_REJECTED) {
2730                         /* the other channel does not support T.38, we need to
2731                          * step in here */
2732                         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));
2733                         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));
2734
2735                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2736                         t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2737
2738                         if (fax_gateway_start(gateway, details, chan)) {
2739                                 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));
2740                                 gateway->t38_state = T38_STATE_REJECTED;
2741                                 control_params->request_response = AST_T38_REFUSED;
2742
2743                                 ast_framehook_detach(chan, details->gateway_id);
2744                                 details->gateway_id = -1;
2745                         } else {
2746                                 gateway->t38_state = T38_STATE_NEGOTIATED;
2747                                 control_params->request_response = AST_T38_NEGOTIATED;
2748                                 report_fax_status(chan, details, "T.38 Negotiated");
2749                         }
2750
2751                         fax_gateway_indicate_t38(chan, active, control_params);
2752
2753                         ao2_ref(details, -1);
2754                         return &ast_null_frame;
2755                 } else if (gateway->t38_state == T38_STATE_NEGOTIATING) {
2756                         /* we got a request to negotiate T.38 after we already
2757                          * sent one to the other party based on v21 preamble
2758                          * detection. We'll just pretend we passed this request
2759                          * through in the first place. */
2760
2761                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2762                         gateway->t38_state = T38_STATE_UNKNOWN;
2763                         gateway->timeout_start = ast_tvnow();
2764                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2765
2766                         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));
2767                         ao2_ref(details, -1);
2768                         return &ast_null_frame;
2769                 } else if (gateway->t38_state == T38_STATE_NEGOTIATED) {
2770                         /* we got a request to negotiate T.38 after we already
2771                          * sent one to the other party based on v21 preamble
2772                          * detection and received a response. We need to
2773                          * respond to this and shut down the gateway. */
2774
2775                         t38_parameters_fax_to_ast(control_params, &details->their_t38_parameters);
2776                         ast_framehook_detach(chan, details->gateway_id);
2777                         details->gateway_id = -1;
2778
2779                         control_params->request_response = AST_T38_NEGOTIATED;
2780
2781                         fax_gateway_indicate_t38(chan, active, control_params);
2782
2783                         ast_string_field_set(details, result, "SUCCESS");
2784                         ast_string_field_set(details, resultstr, "no gateway necessary");
2785                         ast_string_field_set(details, error, "NATIVE_T38");
2786                         set_channel_variables(chan, details);
2787
2788                         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));
2789                         ao2_ref(details, -1);
2790                         return &ast_null_frame;
2791                 } else {
2792                         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));
2793                         ao2_ref(details, -1);
2794                         return f;
2795                 }
2796         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2797                 && control_params->request_response == AST_T38_REFUSED) {
2798
2799                 ast_debug(1, "unable to negotiate T.38 on %s for fax gateway\n", ast_channel_name(active));
2800
2801                 /* our request to negotiate T.38 was refused, if the other
2802                  * channel supports T.38, they might still reinvite and save
2803                  * the day.  Otherwise disable the gateway. */
2804                 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2805                         gateway->t38_state = T38_STATE_UNAVAILABLE;
2806                 } else {
2807                         ast_framehook_detach(chan, details->gateway_id);
2808                         details->gateway_id = -1;
2809
2810                         ast_string_field_set(details, result, "FAILED");
2811                         ast_string_field_set(details, resultstr, "unable to negotiate T.38");
2812                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2813                         set_channel_variables(chan, details);
2814                 }
2815
2816                 ao2_ref(details, -1);
2817                 return &ast_null_frame;
2818         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2819                 && control_params->request_response == AST_T38_NEGOTIATED) {
2820
2821                 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));
2822
2823                 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2824
2825                 if (fax_gateway_start(gateway, details, chan)) {
2826                         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));
2827                         gateway->t38_state = T38_STATE_NEGOTIATING;
2828                         control_params->request_response = AST_T38_REQUEST_TERMINATE;
2829
2830                         fax_gateway_indicate_t38(chan, active, control_params);
2831                 } else {
2832                         gateway->t38_state = T38_STATE_NEGOTIATED;
2833                         report_fax_status(chan, details, "T.38 Negotiated");
2834                 }
2835
2836                 ao2_ref(details, -1);
2837                 return &ast_null_frame;
2838         } else if (control_params->request_response == AST_T38_REFUSED) {
2839                 /* the other channel refused the request to negotiate T.38,
2840                  * we'll step in here and pretend the request was accepted */
2841
2842                 ast_debug(1, "%s attempted to negotiate T.38 but %s refused the request\n", ast_channel_name(other), ast_channel_name(active));
2843                 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));
2844
2845                 t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2846
2847                 if (fax_gateway_start(gateway, details, chan)) {
2848                         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));
2849                         gateway->t38_state = T38_STATE_REJECTED;
2850                         control_params->request_response = AST_T38_REFUSED;
2851
2852                         ast_framehook_detach(chan, details->gateway_id);
2853                         details->gateway_id = -1;
2854                 } else {
2855                         gateway->t38_state = T38_STATE_NEGOTIATED;
2856                         control_params->request_response = AST_T38_NEGOTIATED;
2857                 }
2858
2859                 ao2_ref(details, -1);
2860                 return f;
2861         } else if (control_params->request_response == AST_T38_REQUEST_TERMINATE) {
2862                 /* the channel wishes to end our short relationship, we shall
2863                  * oblige */
2864
2865                 ast_debug(1, "T.38 channel %s is requesting a shutdown of T.38, disabling the gateway\n", ast_channel_name(active));
2866
2867                 ast_framehook_detach(chan, details->gateway_id);
2868                 details->gateway_id = -1;
2869
2870                 gateway->t38_state = T38_STATE_REJECTED;
2871                 control_params->request_response = AST_T38_TERMINATED;
2872
2873                 fax_gateway_indicate_t38(chan, active, control_params);
2874
2875                 ao2_ref(details, -1);
2876                 return &ast_null_frame;
2877         } else if (control_params->request_response == AST_T38_NEGOTIATED) {
2878                 ast_debug(1, "T.38 successfully negotiated between %s and %s, no gateway necessary\n", ast_channel_name(active), ast_channel_name(other));
2879
2880                 ast_framehook_detach(chan, details->gateway_id);
2881                 details->gateway_id = -1;
2882
2883                 ast_string_field_set(details, result, "SUCCESS");
2884                 ast_string_field_set(details, resultstr, "no gateway necessary");
2885                 ast_string_field_set(details, error, "NATIVE_T38");
2886                 set_channel_variables(chan, details);
2887
2888                 ao2_ref(details, -1);
2889                 return f;
2890         } else if (control_params->request_response == AST_T38_TERMINATED) {
2891                 ast_debug(1, "T.38 disabled on channel %s\n", ast_channel_name(active));
2892
2893                 ast_framehook_detach(chan, details->gateway_id);
2894                 details->gateway_id = -1;
2895
2896                 ao2_ref(details, -1);
2897                 return &ast_null_frame;
2898         }
2899
2900         ao2_ref(details, -1);
2901         return f;
2902 }
2903
2904 /*! \brief Destroy the gateway data structure when the framehook is detached
2905  * \param data framehook data (gateway data)*/
2906 static void fax_gateway_framehook_destroy(void *data) {
2907         struct fax_gateway *gateway = data;
2908
2909         if (gateway->s) {
2910                 switch (gateway->s->state) {
2911                 case AST_FAX_STATE_INITIALIZED:
2912                 case AST_FAX_STATE_OPEN:
2913                 case AST_FAX_STATE_ACTIVE:
2914                 case AST_FAX_STATE_COMPLETE:
2915                         if (gateway->s->tech->cancel_session) {
2916                                 gateway->s->tech->cancel_session(gateway->s);
2917                         }
2918                         /* fall through */
2919                 default:
2920                         break;
2921                 }
2922         }
2923
2924         ao2_ref(gateway, -1);
2925 }
2926
2927 /*! \brief T.30<->T.38 gateway framehook.
2928  *
2929  * Intercept packets on bridged channels and determine if a T.38 gateway is
2930  * required. If a gateway is required, start a gateway and handle T.38
2931  * negotiation if necessary.
2932  *
2933  * \param chan channel running the gateway
2934  * \param f frame to handle may be NULL
2935  * \param event framehook event
2936  * \param data framehook data (struct fax_gateway *)
2937  *
2938  * \return processed frame or NULL when f is NULL or a null frame
2939  */
2940 static struct ast_frame *fax_gateway_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
2941         struct fax_gateway *gateway = data;
2942         struct ast_channel *peer, *active;
2943         struct ast_fax_session_details *details;
2944
2945         if (gateway->s) {
2946                 details = gateway->s->details;
2947                 ao2_ref(details, 1);
2948         } else {
2949                 if (!(details = find_details(chan))) {
2950                         ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2951                         ast_framehook_detach(chan, gateway->framehook);
2952                         return f;
2953                 }
2954         }
2955
2956         /* restore audio formats when we are detached */
2957         if (event == AST_FRAMEHOOK_EVENT_DETACHED) {
2958                 set_channel_variables(chan, details);
2959
2960                 if (gateway->bridged) {
2961                         ast_set_read_format(chan, &gateway->chan_read_format);
2962                         ast_set_read_format(chan, &gateway->chan_write_format);
2963
2964                         if ((peer = ast_bridged_channel(chan))) {
2965                                 ast_set_read_format(peer, &gateway->peer_read_format);
2966                                 ast_set_read_format(peer, &gateway->peer_write_format);
2967                                 ast_channel_make_compatible(chan, peer);
2968                         }
2969                 }
2970
2971                 ao2_ref(details, -1);
2972                 return NULL;
2973         }
2974
2975         if (!f || (event == AST_FRAMEHOOK_EVENT_ATTACHED)) {
2976                 ao2_ref(details, -1);
2977                 return NULL;
2978         };
2979
2980         /* this frame was generated by the fax gateway, pass it on */
2981         if (ast_test_flag(f, AST_FAX_FRFLAG_GATEWAY)) {
2982                 ao2_ref(details, -1);
2983                 return f;
2984         }
2985
2986         if (!(peer = ast_bridged_channel(chan))) {
2987                 /* not bridged, don't do anything */
2988                 ao2_ref(details, -1);
2989                 return f;
2990         }
2991
2992         if (!gateway->bridged && peer) {
2993                 /* don't start a gateway if neither channel can handle T.38 */
2994                 if (ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE && ast_channel_get_t38_state(peer) == T38_STATE_UNAVAILABLE) {
2995                         ast_debug(1, "not starting gateway for %s and %s; neither channel supports T.38\n", ast_channel_name(chan), ast_channel_name(peer));
2996                         ast_framehook_detach(chan, gateway->framehook);
2997                         details->gateway_id = -1;
2998
2999                         ast_string_field_set(details, result, "FAILED");
3000                         ast_string_field_set(details, resultstr, "neither channel supports T.38");
3001                         ast_string_field_set(details, error, "T38_NEG_ERROR");
3002                         set_channel_variables(chan, details);
3003                         ao2_ref(details, -1);
3004                         return f;
3005                 }
3006
3007                 if (details->gateway_timeout) {
3008                         gateway->timeout_start = ast_tvnow();
3009                 }
3010
3011                 /* we are bridged, change r/w formats to SLIN for v21 preamble
3012                  * detection and T.30 */
3013                 ast_format_copy(&gateway->chan_read_format, ast_channel_readformat(chan));
3014                 ast_format_copy(&gateway->chan_write_format, ast_channel_readformat(chan));
3015
3016                 ast_format_copy(&gateway->peer_read_format, ast_channel_readformat(peer));
3017                 ast_format_copy(&gateway->peer_write_format, ast_channel_readformat(peer));
3018
3019                 ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
3020                 ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR);
3021
3022                 ast_set_read_format_by_id(peer, AST_FORMAT_SLINEAR);
3023                 ast_set_write_format_by_id(peer, AST_FORMAT_SLINEAR);
3024
3025                 ast_channel_make_compatible(chan, peer);
3026                 gateway->bridged = 1;
3027         }
3028
3029         if (gateway->bridged && !ast_tvzero(gateway->timeout_start)) {
3030                 if (ast_tvdiff_ms(ast_tvnow(), gateway->timeout_start) > details->gateway_timeout) {
3031                         ast_debug(1, "no fax activity between %s and %s after %d ms, disabling gateway\n", ast_channel_name(chan), ast_channel_name(peer), details->gateway_timeout);
3032                         ast_framehook_detach(chan, gateway->framehook);
3033                         details->gateway_id = -1;
3034
3035                         ast_string_field_set(details, result, "FAILED");
3036                         ast_string_field_build(details, resultstr, "no fax activity after %d ms", details->gateway_timeout);
3037                         ast_string_field_set(details, error, "TIMEOUT");
3038                         set_channel_variables(chan, details);
3039                         ao2_ref(details, -1);
3040                         return f;
3041                 }
3042         }
3043
3044         /* only handle VOICE, MODEM, and CONTROL frames*/
3045         switch (f->frametype) {
3046         case AST_FRAME_VOICE:
3047                 switch (f->subclass.format.id) {
3048                 case AST_FORMAT_SLINEAR:
3049                 case AST_FORMAT_ALAW:
3050                 case AST_FORMAT_ULAW:
3051                         break;
3052                 default:
3053                         ao2_ref(details, -1);
3054                         return f;
3055                 }
3056                 break;
3057         case AST_FRAME_MODEM:
3058                 if (f->subclass.integer == AST_MODEM_T38) {
3059                         break;
3060                 }
3061                 ao2_ref(details, -1);
3062                 return f;
3063         case AST_FRAME_CONTROL:
3064                 if (f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
3065                         break;
3066                 }
3067                 ao2_ref(details, -1);
3068                 return f;
3069         default:
3070                 ao2_ref(details, -1);
3071                 return f;
3072         }
3073
3074         /* detect the active channel */
3075         switch (event) {
3076         case AST_FRAMEHOOK_EVENT_WRITE:
3077                 active = peer;
3078                 break;
3079         case AST_FRAMEHOOK_EVENT_READ:
3080                 active = chan;
3081                 break;
3082         default:
3083                 ast_log(LOG_WARNING, "unhandled framehook event %i\n", event);
3084                 ao2_ref(details, -1);
3085                 return f;
3086         }
3087
3088         /* handle control frames */
3089         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
3090                 ao2_ref(details, -1);
3091                 return fax_gateway_detect_t38(gateway, chan, peer, active, f);
3092         }
3093
3094         if (!gateway->detected_v21 && gateway->t38_state == T38_STATE_UNAVAILABLE && f->frametype == AST_FRAME_VOICE) {
3095                 /* not in gateway mode and have not detected v21 yet, listen
3096                  * for v21 */
3097                 ao2_ref(details, -1);
3098                 return fax_gateway_detect_v21(gateway, chan, peer, active, f);
3099         }
3100
3101         /* in gateway mode, gateway some packets */
3102         if (gateway->t38_state == T38_STATE_NEGOTIATED) {
3103                 /* framehooks are called in __ast_read() before frame format
3104                  * translation is done, so we need to translate here */
3105                 if ((f->frametype == AST_FRAME_VOICE) && (f->subclass.format.id != AST_FORMAT_SLINEAR)) {
3106                         if (ast_channel_readtrans(active) && (f = ast_translate(ast_channel_readtrans(active), f, 1)) == NULL) {
3107                                 f = &ast_null_frame;
3108                                 ao2_ref(details, -1);
3109                                 return f;
3110                         }
3111                 }
3112
3113                 /* XXX we ignore the return value here, perhaps we should
3114                  * disable the gateway if a write fails. I am not sure how a
3115                  * write would fail, or even if a failure would be fatal so for
3116                  * now we'll just ignore the return value. */
3117                 gateway->s->tech->write(gateway->s, f);
3118                 if ((f->frametype == AST_FRAME_VOICE) && (f->subclass.format.id != AST_FORMAT_SLINEAR) && ast_channel_readtrans(active)) {
3119                         /* Only free the frame if we translated / duplicated it - otherwise,
3120                          * let whatever is outside the frame hook do it */
3121                         ast_frfree(f);
3122                 }
3123                 f = &ast_null_frame;
3124                 ao2_ref(details, -1);
3125                 return f;
3126         }
3127
3128         /* force silence on the line if T.38 negotiation might be taking place */
3129         if (gateway->t38_state != T38_STATE_UNAVAILABLE && gateway->t38_state != T38_STATE_REJECTED) {
3130                 if (f->frametype == AST_FRAME_VOICE && f->subclass.format.id == AST_FORMAT_SLINEAR) {
3131                         short silence_buf[f->samples];
3132                         struct ast_frame silence_frame = {
3133                                 .frametype = AST_FRAME_VOICE,
3134                                 .data.ptr = silence_buf,
3135                                 .samples = f->samples,
3136                                 .datalen = sizeof(silence_buf),
3137                         };
3138                         ast_format_set(&silence_frame.subclass.format, AST_FORMAT_SLINEAR, 0);
3139                         memset(silence_buf, 0, sizeof(silence_buf));
3140
3141                         ao2_ref(details, -1);
3142                         return ast_frisolate(&silence_frame);
3143                 } else {
3144                         ao2_ref(details, -1);
3145                         return &ast_null_frame;
3146                 }
3147         }
3148
3149         ao2_ref(details, -1);
3150         return f;
3151 }
3152
3153 /*! \brief Attach a gateway framehook object to a channel.
3154  * \param chan the channel to attach to
3155  * \param details fax session details
3156  * \return the framehook id of the attached framehook or -1 on error
3157  * \retval -1 error
3158  */
3159 static int fax_gateway_attach(struct ast_channel *chan, struct ast_fax_session_details *details)
3160 {
3161         struct fax_gateway *gateway;
3162         struct ast_framehook_interface fr_hook = {
3163                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
3164                 .event_cb = fax_gateway_framehook,
3165                 .destroy_cb = fax_gateway_framehook_destroy,
3166         };
3167
3168         ast_string_field_set(details, result, "SUCCESS");
3169         ast_string_field_set(details, resultstr, "gateway operation started successfully");
3170         ast_string_field_set(details, error, "NO_ERROR");
3171         set_channel_variables(chan, details);
3172
3173         /* set up the frame hook*/
3174         gateway = fax_gateway_new(chan, details);
3175         if (!gateway) {
3176                 ast_string_field_set(details, result, "FAILED");
3177                 ast_string_field_set(details, resultstr, "error initializing gateway session");
3178                 ast_string_field_set(details, error, "INIT_ERROR");
3179                 set_channel_variables(chan, details);
3180                 report_fax_status(chan, details, "No Available Resource");
3181                 return -1;
3182         }
3183
3184         fr_hook.data = gateway;
3185         ast_channel_lock(chan);
3186         gateway->framehook = ast_framehook_attach(chan, &fr_hook);
3187         ast_channel_unlock(chan);
3188
3189         if (gateway->framehook < 0) {
3190                 ao2_ref(gateway, -1);
3191                 ast_string_field_set(details, result, "FAILED");
3192                 ast_string_field_set(details, resultstr, "error attaching gateway to channel");
3193                 ast_string_field_set(details, error, "INIT_ERROR");
3194                 set_channel_variables(chan, details);
3195                 return -1;
3196         }
3197
3198         return gateway->framehook;
3199 }
3200
3201 /*! \brief destroy a FAX detect structure */
3202 static void destroy_faxdetect(void *data)
3203 {
3204         struct fax_detect *faxdetect = data;
3205
3206         if (faxdetect->dsp) {
3207                 ast_dsp_free(faxdetect->dsp);
3208                 faxdetect->dsp = NULL;
3209         }
3210         ao2_ref(faxdetect->details, -1);
3211 }
3212
3213 /*! \brief Create a new fax detect object.
3214  * \param chan the channel attaching to
3215  * \param timeout remove framehook in this time if set
3216  * \param flags required options
3217  * \return NULL or a fax gateway object
3218  */
3219 static struct fax_detect *fax_detect_new(struct ast_channel *chan, int timeout, int flags)
3220 {
3221         struct fax_detect *faxdetect = ao2_alloc(sizeof(*faxdetect), destroy_faxdetect);
3222         if (!faxdetect) {
3223                 return NULL;
3224         }
3225
3226         faxdetect->flags = flags;
3227
3228         if (timeout) {
3229                 faxdetect->timeout_start = ast_tvnow();
3230         } else {
3231                 faxdetect->timeout_start.tv_sec = 0;
3232                 faxdetect->timeout_start.tv_usec = 0;
3233         }
3234
3235         if (faxdetect->flags & FAX_DETECT_MODE_CNG) {
3236                 faxdetect->dsp = ast_dsp_new();
3237                 if (!faxdetect->dsp) {
3238                         ao2_ref(faxdetect, -1);
3239                         return NULL;
3240                 }
3241                 ast_dsp_set_features(faxdetect->dsp, DSP_FEATURE_FAX_DETECT);
3242                 ast_dsp_set_faxmode(faxdetect->dsp, DSP_FAXMODE_DETECT_CNG | DSP_FAXMODE_DETECT_SQUELCH);
3243         } else {
3244                 faxdetect->dsp = NULL;
3245         }
3246
3247         return faxdetect;
3248 }
3249
3250 /*! \brief Deref the faxdetect data structure when the faxdetect framehook is detached
3251  * \param data framehook data (faxdetect data)*/
3252 static void fax_detect_framehook_destroy(void *data) {
3253         struct fax_detect *faxdetect = data;
3254
3255         ao2_ref(faxdetect, -1);
3256 }
3257
3258 /*! \brief Fax Detect Framehook
3259  *
3260  * Listen for fax tones in audio path and enable jumping to a extension when detected.
3261  *
3262  * \param chan channel
3263  * \param f frame to handle may be NULL
3264  * \param event framehook event
3265  * \param data framehook data (struct fax_detect *)
3266  *
3267  * \return processed frame or NULL when f is NULL or a null frame
3268  */
3269 static struct ast_frame *fax_detect_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
3270         struct fax_detect *faxdetect = data;
3271         struct ast_fax_session_details *details;
3272         struct ast_control_t38_parameters *control_params;
3273         struct ast_channel *peer;
3274         int result = 0;
3275
3276         details = faxdetect->details;
3277
3278         switch (event) {
3279         case AST_FRAMEHOOK_EVENT_ATTACHED:
3280                 /* Setup format for DSP on ATTACH*/
3281                 ast_format_copy(&faxdetect->orig_format, ast_channel_readformat(chan));
3282                 switch (ast_channel_readformat(chan)->id) {
3283                         case AST_FORMAT_SLINEAR:
3284                         case AST_FORMAT_ALAW:
3285                         case AST_FORMAT_ULAW:
3286                                 break;
3287                         default:
3288                                 if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR)) {
3289                                         ast_framehook_detach(chan, details->faxdetect_id);
3290                                         details->faxdetect_id = -1;
3291                                         return f;
3292                                 }
3293                 }
3294                 return NULL;
3295         case AST_FRAMEHOOK_EVENT_DETACHED:
3296                 /* restore audio formats when we are detached */
3297                 ast_set_read_format(chan, &faxdetect->orig_format);
3298                 if ((peer = ast_bridged_channel(chan))) {
3299                         ast_channel_make_compatible(chan, peer);
3300                 }
3301                 return NULL;
3302         case AST_FRAMEHOOK_EVENT_READ:
3303                 if (f) {
3304                         break;
3305                 }
3306         default:
3307                 return f;
3308         };
3309
3310         if (details->faxdetect_id < 0) {
3311                 return f;
3312         }
3313
3314         if ((!ast_tvzero(faxdetect->timeout_start) &&
3315             (ast_tvdiff_ms(ast_tvnow(), faxdetect->timeout_start) > faxdetect->timeout))) {
3316                 ast_framehook_detach(chan, details->faxdetect_id);
3317                 details->faxdetect_id = -1;
3318                 return f;
3319         }
3320
3321         /* only handle VOICE and CONTROL frames*/
3322         switch (f->frametype) {
3323         case AST_FRAME_VOICE:
3324                 /* we have no DSP this means we not detecting CNG */
3325                 if (!faxdetect->dsp) {
3326                         break;
3327                 }
3328                 /* We can only process some formats*/
3329                 switch (f->subclass.format.id) {
3330                         case AST_FORMAT_SLINEAR:
3331                         case AST_FORMAT_ALAW:
3332                         case AST_FORMAT_ULAW:
3333                                 break;
3334                         default:
3335                                 return f;
3336                 }
3337                 break;
3338         case AST_FRAME_CONTROL:
3339                 if ((f->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
3340                     (faxdetect->flags & FAX_DETECT_MODE_T38)) {
3341                         break;
3342                 }
3343                 return f;
3344         default:
3345                 return f;
3346         }
3347
3348         if (f->frametype == AST_FRAME_VOICE) {
3349                 f = ast_dsp_process(chan, faxdetect->dsp, f);
3350                 if (f->frametype == AST_FRAME_DTMF) {
3351                         result = f->subclass.integer;
3352                 }
3353         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->datalen == sizeof(struct ast_control_t38_parameters))) {
3354                 control_params = f->data.ptr;
3355                 switch (control_params->request_response) {
3356                 case AST_T38_NEGOTIATED:
3357                 case AST_T38_REQUEST_NEGOTIATE:
3358                         result = 't';
3359                         break;
3360                 default:
3361                         break;
3362                 }
3363         }
3364
3365         if (result) {
3366                 const char *target_context = S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan));
3367                 switch (result) {
3368                 case 'f':
3369                 case 't':
3370                         ast_channel_unlock(chan);
3371                         if (ast_exists_extension(chan, target_context, "fax", 1,
3372                             S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
3373                                 ast_channel_lock(chan);
3374                                 ast_verb(2, "Redirecting '%s' to fax extension due to %s detection\n",
3375                                         ast_channel_name(chan), (result == 'f') ? "CNG" : "T38");
3376                                 pbx_builtin_setvar_helper(chan, "FAXEXTEN", ast_channel_exten(chan));
3377                                 if (ast_async_goto(chan, target_context, "fax", 1)) {
3378                                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(chan), target_context);
3379                                 }
3380                                 ast_frfree(f);
3381                                 f = &ast_null_frame;
3382                         } else {
3383                                 ast_channel_lock(chan);
3384                                 ast_log(LOG_NOTICE, "FAX %s detected but no fax extension in context (%s)\n",
3385                                         (result == 'f') ? "CNG" : "T38", target_context);
3386                         }
3387                 }
3388                 ast_framehook_detach(chan, details->faxdetect_id);
3389                 details->faxdetect_id = -1;
3390         }
3391
3392         return f;
3393 }
3394
3395 /*! \brief Attach a faxdetect framehook object to a channel.
3396  * \param chan the channel to attach to
3397  * \param timeout remove framehook in this time if set
3398  * \return the faxdetect structure or NULL on error
3399  * \param flags required options
3400  * \retval -1 error
3401  */
3402 static int fax_detect_attach(struct ast_channel *chan, int timeout, int flags)
3403 {
3404         struct fax_detect *faxdetect;
3405         struct ast_fax_session_details *details;
3406         struct ast_framehook_interface fr_hook = {
3407                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
3408                 .event_cb = fax_detect_framehook,
3409                 .destroy_cb = fax_detect_framehook_destroy,
3410         };
3411
3412         if (!(details = find_or_create_details(chan))) {
3413                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
3414                 return -1;
3415         }
3416
3417         /* set up the frame hook*/
3418         faxdetect = fax_detect_new(chan, timeout, flags);
3419         if (!faxdetect) {
3420                 ao2_ref(details, -1);
3421                 return -1;
3422         }
3423
3424         fr_hook.data = faxdetect;
3425         faxdetect->details = details;
3426         ast_channel_lock(chan);
3427         details->faxdetect_id = ast_framehook_attach(chan, &fr_hook);
3428         ast_channel_unlock(chan);
3429
3430         if (details->faxdetect_id < 0) {
3431                 ao2_ref(faxdetect, -1);
3432         }
3433
3434         return details->faxdetect_id;
3435 }
3436
3437 /*! \brief hash callback for ao2 */
3438 static int session_hash_cb(const void *obj, const int flags)
3439 {
3440         const struct ast_fax_session *s = obj;
3441
3442         return s->id;
3443 }
3444
3445 /*! \brief compare callback for ao2 */
3446 static int session_cmp_cb(void *obj, void *arg, int flags)
3447 {
3448         struct ast_fax_session *lhs = obj, *rhs = arg;
3449
3450         return (lhs->id == rhs->id) ? CMP_MATCH | CMP_STOP : 0;
3451 }
3452
3453 /*! \brief fax session tab completion */
3454 static char *fax_session_tab_complete(struct ast_cli_args *a)
3455 {
3456         int tklen;
3457         int wordnum = 0;
3458         char *name = NULL;
3459         struct ao2_iterator i;
3460         struct ast_fax_session *s;
3461         char tbuf[5];
3462
3463         if (a->pos != 3) {
3464                 return NULL;
3465         }
3466
3467         tklen = strlen(a->word);
3468         i = ao2_iterator_init(faxregistry.container, 0);
3469         while ((s = ao2_iterator_next(&i))) {
3470                 snprintf(tbuf, sizeof(tbuf), "%d", s->id);
3471                 if (!strncasecmp(a->word, tbuf, tklen) && ++wordnum > a->n) {
3472                         name = ast_strdup(tbuf);
3473                         ao2_ref(s, -1);
3474                         break;
3475                 }
3476                 ao2_ref(s, -1);
3477         }
3478         ao2_iterator_destroy(&i);
3479         return name;
3480 }
3481
3482 static char *cli_fax_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3483 {
3484         struct fax_module *fax;
3485
3486         switch(cmd) {
3487         case CLI_INIT:
3488                 e->command = "fax show version";
3489                 e->usage =
3490                         "Usage: fax show version\n"
3491                         "       Show versions of FAX For Asterisk components.\n";
3492                 return NULL;
3493         case CLI_GENERATE:
3494                 return NULL;
3495         }
3496
3497         if (a->argc != 3) {
3498                 return CLI_SHOWUSAGE;
3499         }
3500
3501         ast_cli(a->fd, "FAX For Asterisk Components:\n");
3502         ast_cli(a->fd, "\tApplications: %s\n", ast_get_version());
3503         AST_RWLIST_RDLOCK(&faxmodules);
3504         AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
3505                 ast_cli(a->fd, "\t%s: %s\n", fax->tech->description, fax->tech->version);
3506         }
3507         AST_RWLIST_UNLOCK(&faxmodules);
3508         ast_cli(a->fd, "\n");
3509
3510         return CLI_SUCCESS;
3511 }
3512
3513 /*! \brief enable FAX debugging */