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