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