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