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