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