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