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