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