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