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