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