Merge "chan_sip.c: Prevent address change on unauthenticated SIP request."
[asterisk/asterisk.git] / res / res_fax.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008-2009, Digium, Inc.
5  *
6  * Dwayne M. Hubbard <dhubbard@digium.com>
7  * Kevin P. Fleming <kpfleming@digium.com>
8  * Matthew Nicholson <mnicholson@digium.com>
9  *
10  * Initial T.38-gateway code
11  * 2008, Daniel Ferenci <daniel.ferenci@nethemba.com>
12  * Created by Nethemba s.r.o. http://www.nethemba.com
13  * Sponsored by IPEX a.s. http://www.ipex.cz
14  *
15  * T.38-gateway integration into asterisk app_fax and rework
16  * 2008-2011, Gregory Hinton Nietsky <gregory@distrotech.co.za>
17  * dns Telecom http://www.dnstelecom.co.za
18  *
19  * Modified to make T.38-gateway compatible with Asterisk 1.6.2
20  * 2010, Anton Verevkin <mymail@verevkin.it>
21  * ViaNetTV http://www.vianettv.com
22  *
23  * Modified to make T.38-gateway work
24  * 2010, Klaus Darilion, IPCom GmbH, www.ipcom.at
25  *
26  * See http://www.asterisk.org for more information about
27  * the Asterisk project. Please do not directly contact
28  * any of the maintainers of this project for assistance;
29  * the project provides a web site, mailing lists and IRC
30  * channels for your use.
31  *
32  * This program is free software, distributed under the terms of
33  * the GNU General Public License Version 2. See the LICENSE file
34  * at the top of the source tree.
35  */
36
37 /*** MODULEINFO
38         <conflict>app_fax</conflict>
39         <support_level>core</support_level>
40 ***/
41
42 /*! \file
43  *
44  * \brief Generic FAX Resource for FAX technology resource modules
45  *
46  * \author Dwayne M. Hubbard <dhubbard@digium.com>
47  * \author Kevin P. Fleming <kpfleming@digium.com>
48  * \author Matthew Nicholson <mnicholson@digium.com>
49  * \author Gregory H. Nietsky  <gregory@distrotech.co.za>
50  *
51  * A generic FAX resource module that provides SendFAX and ReceiveFAX applications.
52  * This module requires FAX technology modules, like res_fax_spandsp, to register with it
53  * so it can use the technology modules to perform the actual FAX transmissions.
54  * \ingroup applications
55  */
56
57 /*! \li \ref res_fax.c uses the configuration file \ref res_fax.conf
58  * \addtogroup configuration_file Configuration Files
59  */
60
61 /*!
62  * \page res_fax.conf res_fax.conf
63  * \verbinclude res_fax.conf.sample
64  */
65
66 #include "asterisk.h"
67
68 #include "asterisk/io.h"
69 #include "asterisk/file.h"
70 #include "asterisk/logger.h"
71 #include "asterisk/module.h"
72 #include "asterisk/app.h"
73 #include "asterisk/lock.h"
74 #include "asterisk/options.h"
75 #include "asterisk/strings.h"
76 #include "asterisk/cli.h"
77 #include "asterisk/utils.h"
78 #include "asterisk/config.h"
79 #include "asterisk/astobj2.h"
80 #include "asterisk/res_fax.h"
81 #include "asterisk/file.h"
82 #include "asterisk/channel.h"
83 #include "asterisk/pbx.h"
84 #include "asterisk/dsp.h"
85 #include "asterisk/indications.h"
86 #include "asterisk/ast_version.h"
87 #include "asterisk/translate.h"
88 #include "asterisk/stasis.h"
89 #include "asterisk/stasis_channels.h"
90 #include "asterisk/smoother.h"
91 #include "asterisk/format_cache.h"
92
93 /*** DOCUMENTATION
94         <application name="ReceiveFAX" language="en_US" module="res_fax">
95                 <synopsis>
96                         Receive a FAX and save as a TIFF/F file.
97                 </synopsis>
98                 <syntax>
99                         <parameter name="filename" required="true" />
100                         <parameter name="options">
101                                 <optionlist>
102                                         <option name="d">
103                                                 <para>Enable FAX debugging.</para>
104                                         </option>
105                                         <option name="f">
106                                                 <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
107                                         </option>
108                                         <option name="F">
109                                                 <para>Force usage of audio mode on T.38 capable channels.</para>
110                                         </option>
111                                         <option name="s">
112                                                 <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
113                                         </option>
114                                 </optionlist>
115                         </parameter>
116                 </syntax>
117                 <description>
118                         <para>This application is provided by res_fax, which is a FAX technology agnostic module
119                         that utilizes FAX technology resource modules to complete a FAX transmission.</para>
120                         <para>Session arguments can be set by the FAXOPT function and to check results of the ReceiveFax() application.</para>
121                 </description>
122                 <see-also>
123                         <ref type="function">FAXOPT</ref>
124                 </see-also>
125         </application>
126         <application name="SendFAX" language="en_US" module="res_fax">
127                 <synopsis>
128                         Sends a specified TIFF/F file as a FAX.
129                 </synopsis>
130                 <syntax>
131                         <parameter name="filename" required="true" argsep="&amp;">
132                                 <argument name="filename2" multiple="true">
133                                         <para>TIFF file to send as a FAX.</para>
134                                 </argument>
135                         </parameter>
136                         <parameter name="options">
137                                 <optionlist>
138                                         <option name="d">
139                                                 <para>Enable FAX debugging.</para>
140                                         </option>
141                                         <option name="f">
142                                                 <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
143                                         </option>
144                                         <option name="F">
145                                                 <para>Force usage of audio mode on T.38 capable channels.</para>
146                                         </option>
147                                         <option name="s">
148                                                 <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
149                                         </option>
150                                         <option name="z">
151                                                 <para>Initiate a T.38 reinvite on the channel if the remote end does not.</para>
152                                         </option>
153                                 </optionlist>
154                         </parameter>
155                 </syntax>
156                 <description>
157                         <para>This application is provided by res_fax, which is a FAX technology agnostic module
158                         that utilizes FAX technology resource modules to complete a FAX transmission.</para>
159                         <para>Session arguments can be set by the FAXOPT function and to check results of the SendFax() application.</para>
160                 </description>
161                 <see-also>
162                         <ref type="function">FAXOPT</ref>
163                 </see-also>
164         </application>
165         <function name="FAXOPT" language="en_US" module="res_fax">
166                 <synopsis>
167                         Gets/sets various pieces of information about a fax session.
168                 </synopsis>
169                 <syntax>
170                         <parameter name="item" required="true">
171                                 <enumlist>
172                                         <enum name="ecm">
173                                                 <para>R/W Error Correction Mode (ECM) enable with 'yes', disable with 'no'.</para>
174                                         </enum>
175                                         <enum name="error">
176                                                 <para>R/O FAX transmission error code upon failure.</para>
177                                         </enum>
178                                         <enum name="filename">
179                                                 <para>R/O Filename of the first file of the FAX transmission.</para>
180                                         </enum>
181                                         <enum name="filenames">
182                                                 <para>R/O Filenames of all of the files in the FAX transmission (comma separated).</para>
183                                         </enum>
184                                         <enum name="headerinfo">
185                                                 <para>R/W FAX header information.</para>
186                                         </enum>
187                                         <enum name="localstationid">
188                                                 <para>R/W Local Station Identification.</para>
189                                         </enum>
190                                         <enum name="minrate">
191                                                 <para>R/W Minimum transfer rate set before transmission.</para>
192                                         </enum>
193                                         <enum name="maxrate">
194                                                 <para>R/W Maximum transfer rate set before transmission.</para>
195                                         </enum>
196                                         <enum name="modem">
197                                                 <para>R/W Modem type (v17/v27/v29).</para>
198                                         </enum>
199                                         <enum name="gateway">
200                                                 <para>R/W T38 fax gateway, with optional fax activity timeout in seconds (yes[,timeout]/no)</para>
201                                         </enum>
202                                         <enum name="faxdetect">
203                                                 <para>R/W Enable FAX detect with optional timeout in seconds (yes,t38,cng[,timeout]/no)</para>
204                                         </enum>
205                                         <enum name="pages">
206                                                 <para>R/O Number of pages transferred.</para>
207                                         </enum>
208                                         <enum name="rate">
209                                                 <para>R/O Negotiated transmission rate.</para>
210                                         </enum>
211                                         <enum name="remotestationid">
212                                                 <para>R/O Remote Station Identification after transmission.</para>
213                                         </enum>
214                                         <enum name="resolution">
215                                                 <para>R/O Negotiated image resolution after transmission.</para>
216                                         </enum>
217                                         <enum name="sessionid">
218                                                 <para>R/O Session ID of the FAX transmission.</para>
219                                         </enum>
220                                         <enum name="status">
221                                                 <para>R/O Result Status of the FAX transmission.</para>
222                                         </enum>
223                                         <enum name="statusstr">
224                                                 <para>R/O Verbose Result Status of the FAX transmission.</para>
225                                         </enum>
226                                         <enum name="t38timeout">
227                                                 <para>R/W The timeout used for T.38 negotiation.</para>
228                                         </enum>
229                                 </enumlist>
230                         </parameter>
231                 </syntax>
232                 <description>
233                         <para>FAXOPT can be used to override the settings for a FAX session listed in <filename>res_fax.conf</filename>,
234                         it can also be used to retrieve information about a FAX session that has finished eg. pages/status.</para>
235                 </description>
236                 <see-also>
237                         <ref type="application">ReceiveFax</ref>
238                         <ref type="application">SendFax</ref>
239                 </see-also>
240         </function>
241         <manager name="FAXSessions" language="en_US">
242                 <synopsis>
243                         Lists active FAX sessions
244                 </synopsis>
245                 <syntax>
246                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
247                 </syntax>
248                 <description>
249                         <para>Will generate a series of FAXSession events with information about each FAXSession. Closes with
250                         a FAXSessionsComplete event which includes a count of the included FAX sessions. This action works in
251                         the same manner as the CLI command 'fax show sessions'</para>
252                 </description>
253         </manager>
254         <managerEvent language="en_US" name="FAXSessionsEntry">
255                 <managerEventInstance class="EVENT_FLAG_REPORTING">
256                         <synopsis>A single list item for the FAXSessions AMI command</synopsis>
257                         <syntax>
258                                 <parameter name="ActionID" required="false"/>
259                                 <parameter name="Channel">
260                                         <para>Name of the channel responsible for the FAX session</para>
261                                 </parameter>
262                                 <parameter name="Technology">
263                                         <para>The FAX technology that the FAX session is using</para>
264                                 </parameter>
265                                 <parameter name="SessionNumber">
266                                         <para>The numerical identifier for this particular session</para>
267                                 </parameter>
268                                 <parameter name="SessionType">
269                                         <para>FAX session passthru/relay type</para>
270                                         <enumlist>
271                                                 <enum name="G.711" />
272                                                 <enum name="T.38" />
273                                         </enumlist>
274                                 </parameter>
275                                 <parameter name="Operation">
276                                         <para>FAX session operation type</para>
277                                         <enumlist>
278                                                 <enum name="gateway" />
279                                                 <enum name="V.21" />
280                                                 <enum name="send" />
281                                                 <enum name="receive" />
282                                                 <enum name="none" />
283                                         </enumlist>
284                                 </parameter>
285                                 <parameter name="State">
286                                         <para>Current state of the FAX session</para>
287                                         <enumlist>
288                                                 <enum name="Uninitialized" />
289                                                 <enum name="Initialized" />
290                                                 <enum name="Open" />
291                                                 <enum name="Active" />
292                                                 <enum name="Complete" />
293                                                 <enum name="Reserved" />
294                                                 <enum name="Inactive" />
295                                                 <enum name="Unknown" />
296                                         </enumlist>
297                                 </parameter>
298                                 <parameter name="Files">
299                                         <para>File or list of files associated with this FAX session</para>
300                                 </parameter>
301                         </syntax>
302                 </managerEventInstance>
303         </managerEvent>
304         <managerEvent language="en_US" name="FAXSessionsComplete">
305                 <managerEventInstance class="EVENT_FLAG_CALL">
306                         <synopsis>Raised when all FAXSession events are completed for a FAXSessions command</synopsis>
307                         <syntax>
308                                 <parameter name="ActionID" required="false"/>
309                                 <parameter name="Total">
310                                         <para>Count of FAXSession events sent in response to FAXSessions action</para>
311                                 </parameter>
312                         </syntax>
313                 </managerEventInstance>
314         </managerEvent>
315         <manager name="FAXSession" language="en_US">
316                 <synopsis>
317                         Responds with a detailed description of a single FAX session
318                 </synopsis>
319                 <syntax>
320                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
321                         <parameter name="SessionNumber" required="true">
322                                 <para>The session ID of the fax the user is interested in.</para>
323                         </parameter>
324                 </syntax>
325                 <description>
326                         <para>Provides details about a specific FAX session. The response will include a common subset of
327                         the output from the CLI command 'fax show session &lt;session_number&gt;' for each technology. If the
328                         FAX technolgy used by this session does not include a handler for FAXSession, then this action
329                         will fail.</para>
330                 </description>
331         </manager>
332         <managerEvent language="en_US" name="FAXSession">
333                 <managerEventInstance class="EVENT_FLAG_REPORTING">
334                         <synopsis>Raised in response to FAXSession manager command</synopsis>
335                         <syntax>
336                                 <parameter name="ActionID" required="false"/>
337                                 <parameter name="SessionNumber">
338                                         <para>The numerical identifier for this particular session</para>
339                                 </parameter>
340                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='FAXSessionsEntry']/managerEventInstance/syntax/parameter[@name='Operation'])" />
341                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='FAXSessionsEntry']/managerEventInstance/syntax/parameter[@name='State'])" />
342                                 <parameter name="ErrorCorrectionMode" required="false">
343                                         <para>Whether error correcting mode is enabled for the FAX session. This field is not
344                                         included when operation is 'V.21 Detect' or if operation is 'gateway' and state is
345                                         'Uninitialized'
346                                         </para>
347                                         <enumlist>
348                                                 <enum name="yes" />
349                                                 <enum name="no" />
350                                         </enumlist>
351                                 </parameter>
352                                 <parameter name="DataRate" required="false">
353                                         <para>Bit rate of the FAX. This field is not included when operation is 'V.21 Detect' or
354                                         if operation is 'gateway' and state is 'Uninitialized'.</para>
355                                 </parameter>
356                                 <parameter name="ImageResolution" required="false">
357                                         <para>Resolution of each page of the FAX. Will be in the format of X_RESxY_RES. This field
358                                         is not included if the operation is anything other than Receive/Transmit.</para>
359                                 </parameter>
360                                 <parameter name="PageNumber" required="false">
361                                         <para>Current number of pages transferred during this FAX session. May change as the FAX
362                                         progresses. This field is not included when operation is 'V.21 Detect' or if operation is
363                                         'gateway' and state is 'Uninitialized'.</para>
364                                 </parameter>
365                                 <parameter name="FileName" required="false">
366                                         <para>Filename of the image being sent/received for this FAX session. This field is not
367                                         included if Operation isn't 'send' or 'receive'.</para>
368                                 </parameter>
369                                 <parameter name="PagesTransmitted" required="false">
370                                         <para>Total number of pages sent during this session. This field is not included if
371                                         Operation isn't 'send' or 'receive'. Will always be 0 for 'receive'.</para>
372                                 </parameter>
373                                 <parameter name="PagesReceived" required="false">
374                                         <para>Total number of pages received during this session. This field is not included if
375                                         Operation is not 'send' or 'receive'. Will be 0 for 'send'.</para>
376                                 </parameter>
377                                 <parameter name="TotalBadLines" required="false">
378                                         <para>Total number of bad lines sent/received during this session. This field is not
379                                         included if Operation is not 'send' or 'received'.</para>
380                                 </parameter>
381                         </syntax>
382                 </managerEventInstance>
383         </managerEvent>
384         <manager name="FAXStats" language="en_US">
385                 <synopsis>
386                         Responds with fax statistics
387                 </synopsis>
388                 <syntax>
389                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
390                 </syntax>
391                 <description>
392                         <para>Provides FAX statistics including the number of active sessions, reserved sessions, completed
393                         sessions, failed sessions, and the number of receive/transmit attempts. This command provides all
394                         of the non-technology specific information provided by the CLI command 'fax show stats'</para>
395                 </description>
396         </manager>
397         <managerEvent language="en_US" name="FAXStats">
398                 <managerEventInstance class="EVENT_FLAG_REPORTING">
399                         <synopsis>Raised in response to FAXStats manager command</synopsis>
400                         <syntax>
401                                 <parameter name="ActionID" required="false"/>
402                                 <parameter name="CurrentSessions" required="true">
403                                         <para>Number of active FAX sessions</para>
404                                 </parameter>
405                                 <parameter name="ReservedSessions" required="true">
406                                         <para>Number of reserved FAX sessions</para>
407                                 </parameter>
408                                 <parameter name="TransmitAttempts" required="true">
409                                         <para>Total FAX sessions for which Asterisk is/was the transmitter</para>
410                                 </parameter>
411                                 <parameter name="ReceiveAttempts" required="true">
412                                         <para>Total FAX sessions for which Asterisk is/was the recipient</para>
413                                 </parameter>
414                                 <parameter name="CompletedFAXes" required="true">
415                                         <para>Total FAX sessions which have been completed successfully</para>
416                                 </parameter>
417                                 <parameter name="FailedFAXes" required="true">
418                                         <para>Total FAX sessions which failed to complete successfully</para>
419                                 </parameter>
420                         </syntax>
421                 </managerEventInstance>
422         </managerEvent>
423 ***/
424
425 static const char app_receivefax[] = "ReceiveFAX";
426 static const char app_sendfax[] = "SendFAX";
427
428 struct debug_info_history {
429         unsigned int consec_frames;
430         unsigned int consec_ms;
431         unsigned char silence;
432 };
433
434 struct ast_fax_debug_info {
435         struct timeval base_tv;
436         struct debug_info_history c2s, s2c;
437         struct ast_dsp *dsp;
438 };
439
440 /*! \brief used for gateway framehook */
441 struct fax_gateway {
442         /*! \brief FAX Session */
443         struct ast_fax_session *s;
444         struct ast_fax_session *peer_v21_session;
445         struct ast_fax_session *chan_v21_session;
446         /*! \brief reserved fax session token */
447         struct ast_fax_tech_token *token;
448         /*! \brief the start of our timeout counter */
449         struct timeval timeout_start;
450         /*! \brief framehook used in gateway mode */
451         int framehook;
452         /*! \brief bridged */
453         int bridged:1;
454         /*! \brief 1 if a v21 preamble has been detected */
455         int detected_v21:1;
456         /*! \brief a flag to track the state of our negotiation */
457         enum ast_t38_state t38_state;
458         /*! \brief original audio formats */
459         struct ast_format *chan_read_format;
460         struct ast_format *chan_write_format;
461         struct ast_format *peer_read_format;
462         struct ast_format *peer_write_format;
463 };
464
465 /*! \brief used for fax detect framehook */
466 struct fax_detect {
467         /*! \brief the start of our timeout counter */
468         struct timeval timeout_start;
469         /*! \brief DSP Processor */
470         struct ast_dsp *dsp;
471         /*! \brief original audio formats */
472         struct ast_format *orig_format;
473         /*! \brief fax session details */
474         struct ast_fax_session_details *details;
475         /*! \brief mode */
476         int flags;
477 };
478
479 /*! \brief FAX Detect flags */
480 #define FAX_DETECT_MODE_CNG     (1 << 0)
481 #define FAX_DETECT_MODE_T38     (1 << 1)
482 #define FAX_DETECT_MODE_BOTH    (FAX_DETECT_MODE_CNG | FAX_DETECT_MODE_T38)
483
484 static int fax_logger_level = -1;
485
486 /*! \brief maximum buckets for res_fax ao2 containers */
487 #define FAX_MAXBUCKETS 10
488
489 #define RES_FAX_TIMEOUT 10000
490 #define FAX_GATEWAY_TIMEOUT RES_FAX_TIMEOUT
491
492 /*! \brief The faxregistry is used to manage information and statistics for all FAX sessions. */
493 static struct {
494         /*! The number of active FAX sessions */
495         int active_sessions;
496         /*! The number of reserved FAX sessions */
497         int reserved_sessions;
498         /*! active sessions are astobj2 objects */
499         struct ao2_container *container;
500         /*! Total number of Tx FAX attempts */
501         int fax_tx_attempts;
502         /*! Total number of Rx FAX attempts */
503         int fax_rx_attempts;
504         /*! Number of successful FAX transmissions */
505         int fax_complete;
506         /*! Number of failed FAX transmissions */
507         int fax_failures;
508         /*! the next unique session name */
509         int nextsessionname;
510 } faxregistry;
511
512 /*! \brief registered FAX technology modules are put into this list */
513 struct fax_module {
514         const struct ast_fax_tech *tech;
515         AST_RWLIST_ENTRY(fax_module) list;
516 };
517 static AST_RWLIST_HEAD_STATIC(faxmodules, fax_module);
518
519 #define RES_FAX_MINRATE 4800
520 #define RES_FAX_MAXRATE 14400
521 #define RES_FAX_STATUSEVENTS 0
522 #define RES_FAX_MODEM (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27TER | AST_FAX_MODEM_V29)
523 #define RES_FAX_T38TIMEOUT 5000
524
525 struct fax_options {
526         enum ast_fax_modems modems;
527         uint32_t statusevents:1;
528         uint32_t ecm:1;
529         unsigned int minrate;
530         unsigned int maxrate;
531         unsigned int t38timeout;
532 };
533
534 static struct fax_options general_options;
535
536 static const struct fax_options default_options = {
537         .minrate = RES_FAX_MINRATE,
538         .maxrate = RES_FAX_MAXRATE,
539         .statusevents = RES_FAX_STATUSEVENTS,
540         .modems = RES_FAX_MODEM,
541         .ecm = AST_FAX_OPTFLAG_TRUE,
542         .t38timeout = RES_FAX_T38TIMEOUT,
543 };
544
545 AST_RWLOCK_DEFINE_STATIC(options_lock);
546
547 static void get_general_options(struct fax_options* options);
548 static void set_general_options(const struct fax_options* options);
549
550 static const char *config = "res_fax.conf";
551
552 static int global_fax_debug = 0;
553
554 enum {
555         OPT_CALLEDMODE  = (1 << 0),
556         OPT_CALLERMODE  = (1 << 1),
557         OPT_DEBUG       = (1 << 2),
558         OPT_STATUS      = (1 << 3),
559         OPT_ALLOWAUDIO  = (1 << 5),
560         OPT_REQUEST_T38 = (1 << 6),
561         OPT_FORCE_AUDIO = (1 << 7),
562 };
563
564 AST_APP_OPTIONS(fax_exec_options, BEGIN_OPTIONS
565         AST_APP_OPTION('a', OPT_CALLEDMODE),
566         AST_APP_OPTION('c', OPT_CALLERMODE),
567         AST_APP_OPTION('d', OPT_DEBUG),
568         AST_APP_OPTION('f', OPT_ALLOWAUDIO),
569         AST_APP_OPTION('F', OPT_FORCE_AUDIO),
570         AST_APP_OPTION('s', OPT_STATUS),
571         AST_APP_OPTION('z', OPT_REQUEST_T38),
572 END_OPTIONS);
573
574 static void debug_check_frame_for_silence(struct ast_fax_session *s, unsigned int c2s, struct ast_frame *frame)
575 {
576         struct debug_info_history *history = c2s ? &s->debug_info->c2s : &s->debug_info->s2c;
577         int dspsilence;
578         unsigned int last_consec_frames, last_consec_ms;
579         unsigned char wassil;
580         struct timeval diff;
581
582         diff = ast_tvsub(ast_tvnow(), s->debug_info->base_tv);
583
584         ast_dsp_reset(s->debug_info->dsp);
585         ast_dsp_silence(s->debug_info->dsp, frame, &dspsilence);
586
587         wassil = history->silence;
588         history->silence = (dspsilence != 0) ? 1 : 0;
589         if (history->silence != wassil) {
590                 last_consec_frames = history->consec_frames;
591                 last_consec_ms = history->consec_ms;
592                 history->consec_frames = 0;
593                 history->consec_ms = 0;
594
595                 if ((last_consec_frames != 0)) {
596                         ast_verb(0, "Channel '%s' fax session '%u', [ %.3ld.%.6ld ], %s sent %u frames (%u ms) of %s.\n",
597                                  s->channame, s->id, (long) diff.tv_sec, (long int) diff.tv_usec,
598                                  (c2s) ? "channel" : "stack", last_consec_frames, last_consec_ms,
599                                  (wassil) ? "silence" : "energy");
600                 }
601         }
602
603         history->consec_frames++;
604         history->consec_ms += (frame->samples / 8);
605 }
606
607 static void destroy_callback(void *data)
608 {
609         if (data) {
610                 ao2_ref(data, -1);
611         }
612 }
613
614 static void fixup_callback(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan);
615
616 static const struct ast_datastore_info fax_datastore = {
617         .type = "res_fax",
618         .destroy = destroy_callback,
619         .chan_fixup = fixup_callback,
620 };
621
622 static int fax_gateway_attach(struct ast_channel *chan, struct ast_fax_session_details *details);
623 static int fax_detect_attach(struct ast_channel *chan, int timeout, int flags);
624 static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan);
625 static struct ast_fax_session *fax_v21_session_new (struct ast_channel *chan);
626
627
628 /*! \brief Copies fax detection and gateway framehooks during masquerades
629  *
630  * \note must be called with both old_chan and new_chan locked. Since this
631  *       is only called by do_masquerade, that shouldn't be an issue.
632  */
633 static void fixup_callback(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
634 {
635         struct ast_fax_session_details *old_details = data;
636         struct ast_datastore *datastore = ast_channel_datastore_find(old_chan, &fax_datastore, NULL);
637
638         if (old_details->gateway_id >= 0) {
639                 struct ast_fax_session_details *new_details = find_or_create_details(new_chan);
640
641                 ast_framehook_detach(old_chan, old_details->gateway_id);
642                 new_details->is_t38_negotiated = old_details->is_t38_negotiated;
643                 fax_gateway_attach(new_chan, new_details);
644                 ao2_cleanup(new_details);
645         }
646
647         if (old_details->faxdetect_id >= 0) {
648                 ast_framehook_detach(old_chan, old_details->faxdetect_id);
649                 fax_detect_attach(new_chan, old_details->faxdetect_timeout, old_details->faxdetect_flags);
650         }
651
652         if (datastore) {
653                 ast_channel_datastore_remove(old_chan, datastore);
654                 ast_datastore_free(datastore);
655         }
656 }
657
658 /*! \brief returns a reference counted pointer to a fax datastore, if it exists */
659 static struct ast_fax_session_details *find_details(struct ast_channel *chan)
660 {
661         struct ast_fax_session_details *details;
662         struct ast_datastore *datastore;
663
664         ast_channel_lock(chan);
665         if (!(datastore = ast_channel_datastore_find(chan, &fax_datastore, NULL))) {
666                 ast_channel_unlock(chan);
667                 return NULL;
668         }
669         if (!(details = datastore->data)) {
670                 ast_log(LOG_WARNING, "Huh?  channel '%s' has a FAX datastore without data!\n", ast_channel_name(chan));
671                 ast_channel_unlock(chan);
672                 return NULL;
673         }
674         ao2_ref(details, 1);
675         ast_channel_unlock(chan);
676
677         return details;
678 }
679
680 /*! \brief destroy a FAX session details structure */
681 static void destroy_session_details(void *details)
682 {
683         struct ast_fax_session_details *d = details;
684         struct ast_fax_document *doc;
685
686         while ((doc = AST_LIST_REMOVE_HEAD(&d->documents, next))) {
687                 ast_free(doc);
688         }
689         ast_string_field_free_memory(d);
690 }
691
692 /*! \brief create a FAX session details structure */
693 static struct ast_fax_session_details *session_details_new(void)
694 {
695         struct ast_fax_session_details *d;
696         struct fax_options options;
697
698         if (!(d = ao2_alloc(sizeof(*d), destroy_session_details))) {
699                 return NULL;
700         }
701
702         if (ast_string_field_init(d, 512)) {
703                 ao2_ref(d, -1);
704                 return NULL;
705         }
706
707         get_general_options(&options);
708
709         AST_LIST_HEAD_INIT_NOLOCK(&d->documents);
710
711         /* These options need to be set to the configured default and may be overridden by
712          * SendFAX, ReceiveFAX, or FAXOPT */
713         d->option.request_t38 = AST_FAX_OPTFLAG_FALSE;
714         d->option.send_cng = AST_FAX_OPTFLAG_FALSE;
715         d->option.send_ced = AST_FAX_OPTFLAG_FALSE;
716         d->option.ecm = options.ecm;
717         d->option.statusevents = options.statusevents;
718         d->modems = options.modems;
719         d->minrate = options.minrate;
720         d->maxrate = options.maxrate;
721         d->t38timeout = options.t38timeout;
722         d->gateway_id = -1;
723         d->faxdetect_id = -1;
724         d->gateway_timeout = 0;
725
726         return d;
727 }
728
729 static struct ast_control_t38_parameters our_t38_parameters = {
730         .version = 0,
731         .max_ifp = 400,
732         .rate = AST_T38_RATE_14400,
733         .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
734 };
735
736 static void t38_parameters_ast_to_fax(struct ast_fax_t38_parameters *dst, const struct ast_control_t38_parameters *src)
737 {
738         dst->version = src->version;
739         dst->max_ifp = src->max_ifp;
740         dst->rate = src->rate;
741         dst->rate_management = src->rate_management;
742         dst->fill_bit_removal = src->fill_bit_removal;
743         dst->transcoding_mmr = src->transcoding_mmr;
744         dst->transcoding_jbig = src->transcoding_jbig;
745 }
746
747 static void t38_parameters_fax_to_ast(struct ast_control_t38_parameters *dst, const struct ast_fax_t38_parameters *src)
748 {
749         dst->version = src->version;
750         dst->max_ifp = src->max_ifp;
751         dst->rate = src->rate;
752         dst->rate_management = src->rate_management;
753         dst->fill_bit_removal = src->fill_bit_removal;
754         dst->transcoding_mmr = src->transcoding_mmr;
755         dst->transcoding_jbig = src->transcoding_jbig;
756 }
757
758 /*! \brief returns a reference counted details structure from the channel's fax datastore.  If the datastore
759  * does not exist it will be created */
760 static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan)
761 {
762         struct ast_fax_session_details *details;
763         struct ast_datastore *datastore;
764
765         if ((details = find_details(chan))) {
766                 return details;
767         }
768         /* channel does not have one so we must create one */
769         if (!(details = session_details_new())) {
770                 ast_log(LOG_WARNING, "channel '%s' can't get a FAX details structure for the datastore!\n", ast_channel_name(chan));
771                 return NULL;
772         }
773         if (!(datastore = ast_datastore_alloc(&fax_datastore, NULL))) {
774                 ao2_ref(details, -1);
775                 ast_log(LOG_WARNING, "channel '%s' can't get a datastore!\n", ast_channel_name(chan));
776                 return NULL;
777         }
778         /* add the datastore to the channel and increment the refcount */
779         datastore->data = details;
780
781         /* initialize default T.38 parameters */
782         t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
783         t38_parameters_ast_to_fax(&details->their_t38_parameters, &our_t38_parameters);
784
785         ao2_ref(details, 1);
786         ast_channel_lock(chan);
787         ast_channel_datastore_add(chan, datastore);
788         ast_channel_unlock(chan);
789         return details;
790 }
791
792 unsigned int ast_fax_maxrate(void)
793 {
794         struct fax_options options;
795         get_general_options(&options);
796
797         return options.maxrate;
798 }
799
800 unsigned int ast_fax_minrate(void)
801 {
802         struct fax_options options;
803         get_general_options(&options);
804
805         return options.minrate;
806 }
807
808 static int update_modem_bits(enum ast_fax_modems *bits, const char *value)
809 {
810         char *m[5], *tok, *v = (char *) value, *rest;
811         int i = 0, j;
812
813         if (!strchr(v, ',')) {
814                 m[i++] = v;
815                 m[i] = NULL;
816         } else {
817                 tok = strtok_r(v, ", ", &rest);
818                 while (tok && i < ARRAY_LEN(m) - 1) {
819                         m[i++] = tok;
820                         tok = strtok_r(NULL, ", ", &rest);
821                 }
822                 m[i] = NULL;
823         }
824
825         *bits = 0;
826         for (j = 0; j < i; j++) {
827                 if (!strcasecmp(m[j], "v17")) {
828                         *bits |= AST_FAX_MODEM_V17;
829                 } else if (!strcasecmp(m[j], "v27")) {
830                         *bits |= AST_FAX_MODEM_V27TER;
831                 } else if (!strcasecmp(m[j], "v29")) {
832                         *bits |= AST_FAX_MODEM_V29;
833                 } else if (!strcasecmp(m[j], "v34")) {
834                         *bits |= AST_FAX_MODEM_V34;
835                 } else {
836                         ast_log(LOG_WARNING, "ignoring invalid modem setting: '%s', valid options {v17 | v27 | v29 | v34}\n", m[j]);
837                 }
838         }
839         return 0;
840 }
841
842 static char *ast_fax_caps_to_str(enum ast_fax_capabilities caps, char *buf, size_t bufsize)
843 {
844         char *out = buf;
845         size_t size = bufsize;
846         int first = 1;
847
848         if (caps & AST_FAX_TECH_SEND) {
849                 if (!first) {
850                         ast_build_string(&buf, &size, ",");
851                 }
852                 ast_build_string(&buf, &size, "SEND");
853                 first = 0;
854         }
855         if (caps & AST_FAX_TECH_RECEIVE) {
856                 if (!first) {
857                         ast_build_string(&buf, &size, ",");
858                 }
859                 ast_build_string(&buf, &size, "RECEIVE");
860                 first = 0;
861         }
862         if (caps & AST_FAX_TECH_AUDIO) {
863                 if (!first) {
864                         ast_build_string(&buf, &size, ",");
865                 }
866                 ast_build_string(&buf, &size, "AUDIO");
867                 first = 0;
868         }
869         if (caps & AST_FAX_TECH_T38) {
870                 if (!first) {
871                         ast_build_string(&buf, &size, ",");
872                 }
873                 ast_build_string(&buf, &size, "T38");
874                 first = 0;
875         }
876         if (caps & AST_FAX_TECH_MULTI_DOC) {
877                 if (!first) {
878                         ast_build_string(&buf, &size, ",");
879                 }
880                 ast_build_string(&buf, &size, "MULTI_DOC");
881                 first = 0;
882         }
883         if (caps & AST_FAX_TECH_GATEWAY) {
884                 if (!first) {
885                         ast_build_string(&buf, &size, ",");
886                 }
887                 ast_build_string(&buf, &size, "GATEWAY");
888                 first = 0;
889         }
890         if (caps & AST_FAX_TECH_V21_DETECT) {
891                 if (!first) {
892                         ast_build_string(&buf, &size, ",");
893                 }
894                 ast_build_string(&buf, &size, "V21");
895                 first = 0;
896         }
897
898         return out;
899 }
900
901 static int ast_fax_modem_to_str(enum ast_fax_modems bits, char *tbuf, size_t bufsize)
902 {
903         int count = 0;
904
905         if (bits & AST_FAX_MODEM_V17) {
906                 strcat(tbuf, "V17");
907                 count++;
908         }
909         if (bits & AST_FAX_MODEM_V27TER) {
910                 if (count) {
911                         strcat(tbuf, ",");
912                 }
913                 strcat(tbuf, "V27");
914                 count++;
915         }
916         if (bits & AST_FAX_MODEM_V29) {
917                 if (count) {
918                         strcat(tbuf, ",");
919                 }
920                 strcat(tbuf, "V29");
921                 count++;
922         }
923         if (bits & AST_FAX_MODEM_V34) {
924                 if (count) {
925                         strcat(tbuf, ",");
926                 }
927                 strcat(tbuf, "V34");
928                 count++;
929         }
930
931         return 0;
932 }
933
934 static int check_modem_rate(enum ast_fax_modems modems, unsigned int rate)
935 {
936         switch (rate) {
937         case 2400:
938         case 4800:
939                 if (!(modems & (AST_FAX_MODEM_V27TER | AST_FAX_MODEM_V34))) {
940                         return 1;
941                 }
942                 break;
943         case 7200:
944         case 9600:
945                 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
946                         return 1;
947                 }
948                 break;
949         case 12000:
950         case 14400:
951                 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V34))) {
952                         return 1;
953                 }
954                 break;
955         case 28800:
956         case 33600:
957                 if (!(modems & AST_FAX_MODEM_V34)) {
958                         return 1;
959                 }
960                 break;
961         default:
962                 /* this should never happen */
963                 return 1;
964         }
965
966         return 0;
967 }
968
969 /*! \brief register a FAX technology module */
970 int ast_fax_tech_register(struct ast_fax_tech *tech)
971 {
972         struct fax_module *fax;
973
974         if (!(fax = ast_calloc(1, sizeof(*fax)))) {
975                 return -1;
976         }
977         fax->tech = tech;
978         AST_RWLIST_WRLOCK(&faxmodules);
979         AST_RWLIST_INSERT_TAIL(&faxmodules, fax, list);
980         AST_RWLIST_UNLOCK(&faxmodules);
981
982         ast_verb(3, "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
983
984         return 0;
985 }
986
987 /*! \brief unregister a FAX technology module */
988 void ast_fax_tech_unregister(struct ast_fax_tech *tech)
989 {
990         struct fax_module *fax;
991
992         ast_verb(3, "Unregistering FAX module type '%s'\n", tech->type);
993
994         AST_RWLIST_WRLOCK(&faxmodules);
995         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
996                 if (fax->tech != tech) {
997                         continue;
998                 }
999                 AST_RWLIST_REMOVE_CURRENT(list);
1000                 ast_free(fax);
1001                 ast_verb(4, "Unregistered FAX module type '%s'\n", tech->type);
1002                 break;
1003         }
1004         AST_RWLIST_TRAVERSE_SAFE_END;
1005         AST_RWLIST_UNLOCK(&faxmodules);
1006 }
1007
1008 /*! \brief convert a ast_fax_state to a string */
1009 const char *ast_fax_state_to_str(enum ast_fax_state state)
1010 {
1011         switch (state) {
1012         case AST_FAX_STATE_UNINITIALIZED:
1013                 return "Uninitialized";
1014         case AST_FAX_STATE_INITIALIZED:
1015                 return "Initialized";
1016         case AST_FAX_STATE_OPEN:
1017                 return "Open";
1018         case AST_FAX_STATE_ACTIVE:
1019                 return "Active";
1020         case AST_FAX_STATE_COMPLETE:
1021                 return "Complete";
1022         case AST_FAX_STATE_RESERVED:
1023                 return "Reserved";
1024         case AST_FAX_STATE_INACTIVE:
1025                 return "Inactive";
1026         default:
1027                 ast_log(LOG_WARNING, "unhandled FAX state: %u\n", state);
1028                 return "Unknown";
1029         }
1030 }
1031
1032 void ast_fax_log(int level, const char *file, const int line, const char *function, const char *msg)
1033 {
1034         if (fax_logger_level != -1) {
1035                 ast_log_dynamic_level(fax_logger_level, "%s", msg);
1036         } else {
1037                 ast_log(level, file, line, function, "%s", msg);
1038         }
1039 }
1040
1041 /*! \brief convert a rate string to a rate */
1042 static unsigned int fax_rate_str_to_int(const char *ratestr)
1043 {
1044         int rate;
1045
1046         if (sscanf(ratestr, "%d", &rate) != 1) {
1047                 ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
1048                 return 0;
1049         }
1050         switch (rate) {
1051         case 2400:
1052         case 4800:
1053         case 7200:
1054         case 9600:
1055         case 12000:
1056         case 14400:
1057         case 28800:
1058         case 33600:
1059                 return rate;
1060         default:
1061                 ast_log(LOG_WARNING, "ignoring invalid rate '%s'.  Valid options are {2400 | 4800 | 7200 | 9600 | 12000 | 14400 | 28800 | 33600}\n", ratestr);
1062                 return 0;
1063         }
1064 }
1065
1066 /*! \brief Release a session token.
1067  * \param s a session returned from fax_session_reserve()
1068  * \param token a token generated from fax_session_reserve()
1069  *
1070  * This function releases the given token and marks the given session as no
1071  * longer reserved. It is safe to call on a session that is not actually
1072  * reserved and with a NULL token. This is so that sessions returned by
1073  * technologies that do not support reserved sessions don't require extra logic
1074  * to handle.
1075  *
1076  * \note This function DOES NOT release the given fax session, only the given
1077  * token.
1078  */
1079 static void fax_session_release(struct ast_fax_session *s, struct ast_fax_tech_token *token)
1080 {
1081         if (token) {
1082                 s->tech->release_token(token);
1083         }
1084
1085         if (s->state == AST_FAX_STATE_RESERVED) {
1086                 ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
1087                 s->state = AST_FAX_STATE_INACTIVE;
1088         }
1089 }
1090
1091 /*! \brief destroy a FAX session structure */
1092 static void destroy_session(void *session)
1093 {
1094         struct ast_fax_session *s = session;
1095
1096         if (s->tech) {
1097                 fax_session_release(s, NULL);
1098                 if (s->tech_pvt) {
1099                         s->tech->destroy_session(s);
1100                 }
1101                 ast_module_unref(s->tech->module);
1102         }
1103
1104         if (s->details) {
1105                 if (s->details->caps & AST_FAX_TECH_GATEWAY) {
1106                         s->details->caps &= ~AST_FAX_TECH_GATEWAY;
1107                 }
1108                 ao2_ref(s->details, -1);
1109                 s->details = NULL;
1110         }
1111
1112         if (s->debug_info) {
1113                 ast_dsp_free(s->debug_info->dsp);
1114                 ast_free(s->debug_info);
1115         }
1116
1117         if (s->smoother) {
1118                 ast_smoother_free(s->smoother);
1119         }
1120
1121         if (s->state != AST_FAX_STATE_INACTIVE) {
1122                 ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
1123         }
1124
1125         ast_free(s->channame);
1126         ast_free(s->chan_uniqueid);
1127 }
1128
1129 /*! \brief Reserve a fax session.
1130  * \param details the fax session details
1131  * \param token a pointer to a place to store a token to be passed to fax_session_new() later
1132  *
1133  * This function reserves a fax session for use later. If the selected fax
1134  * technology does not support reserving sessions a session will still be
1135  * returned but token will not be set.
1136  *
1137  * \note The reference returned by this function does not get consumed by
1138  * fax_session_new() and must always be dereferenced separately.
1139  *
1140  * \return NULL or an uninitialized and possibly reserved session
1141  */
1142 static struct ast_fax_session *fax_session_reserve(struct ast_fax_session_details *details, struct ast_fax_tech_token **token)
1143 {
1144         struct ast_fax_session *s;
1145         struct fax_module *faxmod;
1146
1147         if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
1148                 return NULL;
1149         }
1150
1151         s->state = AST_FAX_STATE_INACTIVE;
1152         s->details = details;
1153         ao2_ref(s->details, 1);
1154
1155         /* locate a FAX technology module that can handle said requirements
1156          * Note: the requirements have not yet been finalized as T.38
1157          * negotiation has not yet occured. */
1158         AST_RWLIST_RDLOCK(&faxmodules);
1159         AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
1160                 if ((faxmod->tech->caps & details->caps) != details->caps) {
1161                         continue;
1162                 }
1163                 if (!ast_module_running_ref(faxmod->tech->module)) {
1164                         continue;
1165                 }
1166                 ast_debug(4, "Reserving a FAX session from '%s'.\n", faxmod->tech->description);
1167                 s->tech = faxmod->tech;
1168                 break;
1169         }
1170         AST_RWLIST_UNLOCK(&faxmodules);
1171
1172         if (!faxmod) {
1173                 char caps[128] = "";
1174                 ast_log(LOG_ERROR, "Could not locate a FAX technology module with capabilities (%s)\n", ast_fax_caps_to_str(details->caps, caps, sizeof(caps)));
1175                 ao2_ref(s, -1);
1176                 return NULL;
1177         }
1178
1179         if (!s->tech->reserve_session) {
1180                 ast_debug(1, "Selected FAX technology module (%s) does not support reserving sessions.\n", s->tech->description);
1181                 return s;
1182         }
1183
1184         if (!(*token = s->tech->reserve_session(s))) {
1185                 ao2_ref(s, -1);
1186                 return NULL;
1187         }
1188
1189         s->state = AST_FAX_STATE_RESERVED;
1190         ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, 1);
1191
1192         return s;
1193 }
1194
1195 /*! \brief create a FAX session
1196  *
1197  * \param details details for the session
1198  * \param chan the channel the session will run on
1199  * \param reserved a reserved session to base this session on (can be NULL)
1200  * \param token the token for a reserved session (can be NULL)
1201  *
1202  * Create a new fax session based on the given details structure.
1203  *
1204  * \note The given token is always consumed (by tech->new_session() or by
1205  * fax_session_release() in the event of a failure). The given reference to a
1206  * reserved session is never consumed and must be dereferenced separately from
1207  * the reference returned by this function.
1208  *
1209  * \return NULL or a reference to a new fax session
1210  */
1211 static struct ast_fax_session *fax_session_new(struct ast_fax_session_details *details, struct ast_channel *chan, struct ast_fax_session *reserved, struct ast_fax_tech_token *token)
1212 {
1213         struct ast_fax_session *s = NULL;
1214         struct fax_module *faxmod;
1215
1216         if (reserved) {
1217                 s = reserved;
1218                 ao2_ref(reserved, +1);
1219                 ao2_unlink(faxregistry.container, reserved);
1220
1221                 /* NOTE: we don't consume the reference to the reserved
1222                  * session. The session returned from fax_session_new() is a
1223                  * new reference and must be derefed in addition to the
1224                  * reserved session.
1225                  */
1226
1227                 if (s->state == AST_FAX_STATE_RESERVED) {
1228                         ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
1229                         s->state = AST_FAX_STATE_UNINITIALIZED;
1230                 }
1231         }
1232
1233         if (!s && !(s = ao2_alloc(sizeof(*s), destroy_session))) {
1234                 return NULL;
1235         }
1236
1237         ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
1238         s->state = AST_FAX_STATE_UNINITIALIZED;
1239
1240         if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
1241                 if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
1242                         fax_session_release(s, token);
1243                         ao2_ref(s, -1);
1244                         return NULL;
1245                 }
1246                 if (!(s->debug_info->dsp = ast_dsp_new())) {
1247                         ast_free(s->debug_info);
1248                         s->debug_info = NULL;
1249                         fax_session_release(s, token);
1250                         ao2_ref(s, -1);
1251                         return NULL;
1252                 }
1253                 ast_dsp_set_threshold(s->debug_info->dsp, 128);
1254         }
1255
1256         if (!(s->channame = ast_strdup(ast_channel_name(chan)))) {
1257                 fax_session_release(s, token);
1258                 ao2_ref(s, -1);
1259                 return NULL;
1260         }
1261
1262         if (!(s->chan_uniqueid = ast_strdup(ast_channel_uniqueid(chan)))) {
1263                 fax_session_release(s, token);
1264                 ao2_ref(s, -1);
1265                 return NULL;
1266         }
1267
1268         s->chan = chan;
1269         if (!s->details) {
1270                 s->details = details;
1271                 ao2_ref(s->details, 1);
1272         }
1273
1274         details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
1275
1276         if (!token) {
1277                 /* locate a FAX technology module that can handle said requirements */
1278                 AST_RWLIST_RDLOCK(&faxmodules);
1279                 AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
1280                         if ((faxmod->tech->caps & details->caps) != details->caps) {
1281                                 continue;
1282                         }
1283                         if (!ast_module_running_ref(faxmod->tech->module)) {
1284                                 continue;
1285                         }
1286                         ast_debug(4, "Requesting a new FAX session from '%s'.\n", faxmod->tech->description);
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)
1421                         ? "gateway"
1422                         : (details->caps & AST_FAX_TECH_RECEIVE) ? "receive" : "send",
1423                 "status", status,
1424                 "local_station_id", AST_JSON_UTF8_VALIDATE(details->localstationid),
1425                 "filenames", json_filenames);
1426         if (!json_object) {
1427                 return -1;
1428         }
1429
1430         {
1431                 SCOPED_CHANNELLOCK(lock, chan);
1432
1433                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
1434                 if (!message) {
1435                         return -1;
1436                 }
1437                 stasis_publish(ast_channel_topic(chan), message);
1438         }
1439         return 0;
1440 }
1441
1442 /*! \brief Set fax related channel variables. */
1443 static void set_channel_variables(struct ast_channel *chan, struct ast_fax_session_details *details)
1444 {
1445         char buf[10];
1446
1447         pbx_builtin_setvar_helper(chan, "FAXSTATUS", S_OR(details->result, NULL));
1448         pbx_builtin_setvar_helper(chan, "FAXERROR", S_OR(details->error, NULL));
1449         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", S_OR(details->resultstr, NULL));
1450         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", S_OR(details->remotestationid, NULL));
1451         pbx_builtin_setvar_helper(chan, "LOCALSTATIONID", S_OR(details->localstationid, NULL));
1452         pbx_builtin_setvar_helper(chan, "FAXBITRATE", S_OR(details->transfer_rate, NULL));
1453         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", S_OR(details->resolution, NULL));
1454
1455         if (details->is_t38_negotiated) {
1456                 pbx_builtin_setvar_helper(chan, "FAXMODE", "T38");
1457         } else {
1458                 pbx_builtin_setvar_helper(chan, "FAXMODE", "audio");
1459         }
1460
1461         snprintf(buf, sizeof(buf), "%u", details->pages_transferred);
1462         pbx_builtin_setvar_helper(chan, "FAXPAGES", buf);
1463 }
1464
1465 #define GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason) \
1466         do {    \
1467                 if (ast_strlen_zero(fax->details->result)) \
1468                         ast_string_field_set(fax->details, result, "FAILED"); \
1469                 if (ast_strlen_zero(fax->details->resultstr)) \
1470                         ast_string_field_set(fax->details, resultstr, reason); \
1471                 if (ast_strlen_zero(fax->details->error)) \
1472                         ast_string_field_set(fax->details, error, errorstr); \
1473                 set_channel_variables(chan, fax->details); \
1474         } while (0)
1475
1476 #define GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason) \
1477         do {    \
1478                 GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason); \
1479         } while (0)
1480
1481 #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason)     \
1482         do {    \
1483                 ast_log(LOG_ERROR, "channel '%s' FAX session '%u' failure, reason: '%s' (%s)\n", ast_channel_name(chan), fax->id, reason, errorstr); \
1484                 GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason); \
1485         } while (0)
1486
1487 static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
1488 {
1489         switch (ast_channel_get_t38_state(chan)) {
1490         case T38_STATE_UNKNOWN:
1491                 details->caps |= AST_FAX_TECH_T38;
1492                 break;
1493         case T38_STATE_REJECTED:
1494         case T38_STATE_UNAVAILABLE:
1495                 details->caps |= AST_FAX_TECH_AUDIO;
1496                 break;
1497         case T38_STATE_NEGOTIATED:
1498                 /* already in T.38 mode? This should not happen. */
1499         case T38_STATE_NEGOTIATING: {
1500                 /* the other end already sent us a T.38 reinvite, so we need to prod the channel
1501                  * driver into resending their parameters to us if it supports doing so... if
1502                  * not, we can't proceed, because we can't create a proper reply without them.
1503                  * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
1504                  * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
1505                  * that gets called after this one completes
1506                  */
1507                 struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
1508                 if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
1509                         ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1510                         return -1;
1511                 }
1512                 details->caps |= AST_FAX_TECH_T38;
1513                 break;
1514         }
1515         default:
1516                 ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1517                 return -1;
1518         }
1519
1520         return 0;
1521 }
1522
1523 static int disable_t38(struct ast_channel *chan)
1524 {
1525         int timeout_ms;
1526         struct ast_frame *frame = NULL;
1527         struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
1528         struct timeval start;
1529         int ms;
1530
1531         ast_debug(1, "Shutting down T.38 on %s\n", ast_channel_name(chan));
1532         if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
1533                 ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1534                 return -1;
1535         }
1536
1537         /* wait up to five seconds for negotiation to complete */
1538         timeout_ms = 5000;
1539         start = ast_tvnow();
1540         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1541                 ms = ast_waitfor(chan, ms);
1542
1543                 if (ms == 0) {
1544                         break;
1545                 }
1546                 if (ms < 0) {
1547                         ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1548                         return -1;
1549                 }
1550
1551                 if (!(frame = ast_read(chan))) {
1552                         return -1;
1553                 }
1554                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1555                     (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1556                     (frame->datalen == sizeof(t38_parameters))) {
1557                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1558
1559                         switch (parameters->request_response) {
1560                         case AST_T38_TERMINATED:
1561                                 ast_debug(1, "Shut down T.38 on %s\n", ast_channel_name(chan));
1562                                 break;
1563                         case AST_T38_REFUSED:
1564                                 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", ast_channel_name(chan));
1565                                 ast_frfree(frame);
1566                                 return -1;
1567                         default:
1568                                 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", ast_channel_name(chan));
1569                                 ast_frfree(frame);
1570                                 return -1;
1571                         }
1572                         ast_frfree(frame);
1573                         break;
1574                 }
1575                 ast_frfree(frame);
1576         }
1577
1578         if (ms == 0) { /* all done, nothing happened */
1579                 ast_debug(1, "channel '%s' timed-out during T.38 shutdown\n", ast_channel_name(chan));
1580         }
1581
1582         return 0;
1583 }
1584
1585 /*! \brief this is the generic FAX session handling function */
1586 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)
1587 {
1588         int ms;
1589         int timeout = RES_FAX_TIMEOUT;
1590         int chancount;
1591         unsigned int expected_frametype = -1;
1592         struct ast_frame_subclass expected_framesubclass = { .integer = 0, };
1593         unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
1594         struct ast_control_t38_parameters t38_parameters;
1595         const char *tempvar;
1596         struct ast_fax_session *fax = NULL;
1597         struct ast_frame *frame = NULL;
1598         struct ast_channel *c = chan;
1599         RAII_VAR(struct ast_format *, orig_write_format, NULL, ao2_cleanup);
1600         RAII_VAR(struct ast_format *, orig_read_format, NULL, ao2_cleanup);
1601         int remaining_time;
1602         struct timeval start;
1603
1604         chancount = 1;
1605
1606         /* Make sure one or the other is set to avoid race condition */
1607         if (t38negotiated) {
1608                 details->caps |= AST_FAX_TECH_T38;
1609         } else {
1610                 details->caps |= AST_FAX_TECH_AUDIO;
1611         }
1612
1613         /* create the FAX session */
1614         if (!(fax = fax_session_new(details, chan, reserved, token))) {
1615                 ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
1616                 report_fax_status(chan, details, "No Available Resource");
1617                 return -1;
1618         }
1619
1620         ast_channel_lock(chan);
1621         /* update session details */
1622         if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
1623                 ast_string_field_set(details, headerinfo, tempvar);
1624         }
1625         if (ast_strlen_zero(details->localstationid)) {
1626                 tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
1627                 ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
1628         }
1629         ast_channel_unlock(chan);
1630
1631         report_fax_status(chan, details, "Allocating Resources");
1632
1633         if (details->caps & AST_FAX_TECH_AUDIO) {
1634                 expected_frametype = AST_FRAME_VOICE;
1635                 expected_framesubclass.format = ast_format_slin;
1636                 orig_write_format = ao2_bump(ast_channel_writeformat(chan));
1637                 if (ast_set_write_format(chan, ast_format_slin) < 0) {
1638                         ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", ast_channel_name(chan));
1639                         ao2_unlink(faxregistry.container, fax);
1640                         ao2_ref(fax, -1);
1641                         return -1;
1642                 }
1643                 orig_read_format = ao2_bump(ast_channel_readformat(chan));
1644                 if (ast_set_read_format(chan, ast_format_slin) < 0) {
1645                         ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", ast_channel_name(chan));
1646                         ao2_unlink(faxregistry.container, fax);
1647                         ao2_ref(fax, -1);
1648                         return -1;
1649                 }
1650                 if (fax->smoother) {
1651                         ast_smoother_free(fax->smoother);
1652                         fax->smoother = NULL;
1653                 }
1654                 if (!(fax->smoother = ast_smoother_new(320))) {
1655                         ast_log(LOG_WARNING, "Channel '%s' FAX session '%u' failed to obtain a smoother.\n", ast_channel_name(chan), fax->id);
1656                 }
1657         } else {
1658                 expected_frametype = AST_FRAME_MODEM;
1659                 expected_framesubclass.integer = AST_MODEM_T38;
1660         }
1661
1662         if (fax->debug_info) {
1663                 fax->debug_info->base_tv = ast_tvnow();
1664         }
1665
1666         /* reset our result fields just in case the fax tech driver wants to
1667          * set custom error messages */
1668         ast_string_field_set(details, result, "");
1669         ast_string_field_set(details, resultstr, "");
1670         ast_string_field_set(details, error, "");
1671         details->is_t38_negotiated = t38negotiated;
1672         set_channel_variables(chan, details);
1673
1674         if (fax->tech->start_session(fax) < 0) {
1675                 GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
1676         }
1677
1678         report_fax_status(chan, details, "FAX Transmission In Progress");
1679
1680         ast_debug(5, "channel %s will wait on FAX fd %d\n", ast_channel_name(chan), fax->fd);
1681
1682         /* handle frames for the session */
1683         remaining_time = timeout;
1684         start = ast_tvnow();
1685         while (remaining_time > 0) {
1686                 struct ast_channel *ready_chan;
1687                 int ofd, exception;
1688
1689                 ms = 1000;
1690                 errno = 0;
1691                 ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
1692                 if (ready_chan) {
1693                         if (!(frame = ast_read(chan))) {
1694                                 /* the channel is probably gone, so lets stop polling on it and let the
1695                                  * FAX session complete before we exit the application.  if needed,
1696                                  * send the FAX stack silence so the modems can finish their session without
1697                                  * any problems */
1698                                 ast_debug(1, "Channel '%s' did not return a frame; probably hung up.\n", ast_channel_name(chan));
1699                                 GENERIC_FAX_EXEC_SET_VARS(fax, chan, "HANGUP", "remote channel hungup");
1700                                 c = NULL;
1701                                 chancount = 0;
1702                                 remaining_time = ast_remaining_ms(start, timeout);
1703                                 fax->tech->cancel_session(fax);
1704                                 if (fax->tech->generate_silence) {
1705                                         fax->tech->generate_silence(fax);
1706                                 }
1707                                 continue;
1708                         }
1709
1710                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1711                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1712                             (frame->datalen == sizeof(t38_parameters))) {
1713                                 unsigned int was_t38 = t38negotiated;
1714                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1715
1716                                 switch (parameters->request_response) {
1717                                 case AST_T38_REQUEST_NEGOTIATE:
1718                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1719                                          * do T.38 as well
1720                                          */
1721                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1722                                         if (details->caps & AST_FAX_TECH_T38) {
1723                                                 details->is_t38_negotiated = 1;
1724                                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
1725                                         } else {
1726                                                 t38_parameters.request_response = AST_T38_REFUSED;
1727                                         }
1728                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1729                                         break;
1730                                 case AST_T38_NEGOTIATED:
1731                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1732                                         t38negotiated = 1;
1733                                         details->is_t38_negotiated = 1;
1734                                         break;
1735                                 default:
1736                                         break;
1737                                 }
1738                                 if (t38negotiated && !was_t38) {
1739                                         if (fax->tech->switch_to_t38(fax)) {
1740                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "T.38 switch failed");
1741                                                 break;
1742                                         }
1743                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1744                                         expected_frametype = AST_FRAME_MODEM;
1745                                         expected_framesubclass.integer = AST_MODEM_T38;
1746                                         if (fax->smoother) {
1747                                                 ast_smoother_free(fax->smoother);
1748                                                 fax->smoother = NULL;
1749                                         }
1750
1751                                         report_fax_status(chan, details, "T.38 Negotiated");
1752
1753                                         ast_verb(3, "Channel '%s' switched to T.38 FAX session '%u'.\n", ast_channel_name(chan), fax->id);
1754                                 }
1755                         } else if ((frame->frametype == expected_frametype) && (expected_framesubclass.integer == frame->subclass.integer) &&
1756                                 ((!frame->subclass.format && !expected_framesubclass.format) ||
1757                                 (frame->subclass.format && expected_framesubclass.format &&
1758                                         (ast_format_cmp(frame->subclass.format, expected_framesubclass.format) != AST_FORMAT_CMP_NOT_EQUAL)))) {
1759                                 struct ast_frame *f;
1760
1761                                 if (fax->smoother) {
1762                                         /* push the frame into a smoother */
1763                                         if (ast_smoother_feed(fax->smoother, frame) < 0) {
1764                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
1765                                         }
1766                                         while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
1767                                                 if (fax->debug_info) {
1768                                                         debug_check_frame_for_silence(fax, 1, f);
1769                                                 }
1770                                                 /* write the frame to the FAX stack */
1771                                                 fax->tech->write(fax, f);
1772                                                 fax->frames_received++;
1773                                                 if (f != frame) {
1774                                                         ast_frfree(f);
1775                                                 }
1776                                         }
1777                                 } else {
1778                                         /* write the frame to the FAX stack */
1779                                         fax->tech->write(fax, frame);
1780                                         fax->frames_received++;
1781                                 }
1782                                 start = ast_tvnow();
1783                         }
1784                         ast_frfree(frame);
1785                 } else if (ofd == fax->fd) {
1786                         /* read a frame from the FAX stack and send it out the channel.
1787                          * the FAX stack will return a NULL if the FAX session has already completed */
1788                         if (!(frame = fax->tech->read(fax))) {
1789                                 break;
1790                         }
1791
1792                         if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
1793                                 debug_check_frame_for_silence(fax, 0, frame);
1794                         }
1795
1796                         ast_write(chan, frame);
1797                         fax->frames_sent++;
1798                         ast_frfree(frame);
1799                         start = ast_tvnow();
1800                 } else {
1801                         if (ms && (ofd < 0)) {
1802                                 if ((errno == 0) || (errno == EINTR)) {
1803                                         remaining_time = ast_remaining_ms(start, timeout);
1804                                         if (remaining_time <= 0)
1805                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1806                                         continue;
1807                                 } else {
1808                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(chan));
1809                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "error polling data");
1810                                         break;
1811                                 }
1812                         } else {
1813                                 /* nothing happened */
1814                                 remaining_time = ast_remaining_ms(start, timeout);
1815                                 if (remaining_time <= 0) {
1816                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1817                                         break;
1818                                 }
1819                         }
1820                 }
1821         }
1822         ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, remaining_time: %d }\n", ast_channel_name(chan), timeout, remaining_time);
1823
1824         set_channel_variables(chan, details);
1825
1826         ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
1827         if (!strcasecmp(details->result, "FAILED")) {
1828                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1829         }
1830
1831         if (fax) {
1832                 ao2_unlink(faxregistry.container, fax);
1833                 ao2_ref(fax, -1);
1834         }
1835
1836         /* if the channel is still alive, and we changed its read/write formats,
1837          * restore them now
1838          */
1839         if (chancount) {
1840                 if (orig_read_format) {
1841                         ast_set_read_format(chan, orig_read_format);
1842                 }
1843                 if (orig_write_format) {
1844                         ast_set_write_format(chan, orig_write_format);
1845                 }
1846         }
1847
1848         /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
1849         return chancount;
1850 }
1851
1852 static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1853 {
1854         int timeout_ms;
1855         struct ast_frame *frame = NULL;
1856         struct ast_control_t38_parameters t38_parameters;
1857         struct timeval start;
1858         int ms;
1859
1860         /* don't send any audio if we've already received a T.38 reinvite */
1861         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1862                 /* generate 3 seconds of CED */
1863                 if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
1864                         ast_log(LOG_ERROR, "error generating CED tone on %s\n", ast_channel_name(chan));
1865                         return -1;
1866                 }
1867
1868                 timeout_ms = 3000;
1869                 start = ast_tvnow();
1870                 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1871                         ms = ast_waitfor(chan, ms);
1872
1873                         if (ms < 0) {
1874                                 ast_log(LOG_ERROR, "error while generating CED tone on %s\n", ast_channel_name(chan));
1875                                 ast_playtones_stop(chan);
1876                                 return -1;
1877                         }
1878
1879                         if (ms == 0) { /* all done, nothing happened */
1880                                 break;
1881                         }
1882
1883                         if (!(frame = ast_read(chan))) {
1884                                 ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", ast_channel_name(chan));
1885                                 ast_playtones_stop(chan);
1886                                 return -1;
1887                         }
1888
1889                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1890                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1891                             (frame->datalen == sizeof(t38_parameters))) {
1892                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1893
1894                                 switch (parameters->request_response) {
1895                                 case AST_T38_REQUEST_NEGOTIATE:
1896                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1897                                          * do T.38 as well
1898                                          */
1899                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1900                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1901                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1902                                         ast_playtones_stop(chan);
1903                                         break;
1904                                 case AST_T38_NEGOTIATED:
1905                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1906                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1907                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1908                                         report_fax_status(chan, details, "T.38 Negotiated");
1909                                         break;
1910                                 default:
1911                                         break;
1912                                 }
1913                         }
1914                         ast_frfree(frame);
1915                 }
1916
1917                 ast_playtones_stop(chan);
1918         }
1919
1920         /* if T.38 was negotiated, we are done initializing */
1921         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1922                 return 0;
1923         }
1924
1925         /* request T.38 */
1926         ast_debug(1, "Negotiating T.38 for receive on %s\n", ast_channel_name(chan));
1927
1928         /* wait for negotiation to complete */
1929         timeout_ms = details->t38timeout;
1930
1931         /* set parameters based on the session's parameters */
1932         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1933         t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
1934         if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
1935                 return -1;
1936         }
1937
1938         start = ast_tvnow();
1939         while ((ms = ast_remaining_ms(start, timeout_ms))) {
1940                 int break_loop = 0;
1941
1942                 ms = ast_waitfor(chan, ms);
1943                 if (ms < 0) {
1944                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1945                         return -1;
1946                 }
1947                 if (ms == 0) { /* all done, nothing happened */
1948                         ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
1949                         details->caps &= ~AST_FAX_TECH_T38;
1950                         break;
1951                 }
1952
1953                 if (!(frame = ast_read(chan))) {
1954                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1955                         return -1;
1956                 }
1957
1958                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1959                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1960                                 (frame->datalen == sizeof(t38_parameters))) {
1961                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1962
1963                         switch (parameters->request_response) {
1964                         case AST_T38_REQUEST_NEGOTIATE:
1965                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1966                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
1967                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1968                                 break;
1969                         case AST_T38_NEGOTIATED:
1970                                 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1971                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1972                                 details->caps &= ~AST_FAX_TECH_AUDIO;
1973                                 report_fax_status(chan, details, "T.38 Negotiated");
1974                                 break_loop = 1;
1975                                 break;
1976                         case AST_T38_REFUSED:
1977                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
1978                                 details->caps &= ~AST_FAX_TECH_T38;
1979                                 break_loop = 1;
1980                                 break;
1981                         default:
1982                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
1983                                 details->caps &= ~AST_FAX_TECH_T38;
1984                                 break_loop = 1;
1985                                 break;
1986                         }
1987                 }
1988                 ast_frfree(frame);
1989                 if (break_loop) {
1990                         break;
1991                 }
1992         }
1993
1994         /* if T.38 was negotiated, we are done initializing */
1995         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1996                 return 0;
1997         }
1998
1999         /* if we made it here, then T.38 failed, check the 'f' flag */
2000         if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
2001                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
2002                 return -1;
2003         }
2004
2005         /* ok, audio fallback is allowed */
2006         details->caps |= AST_FAX_TECH_AUDIO;
2007
2008         return 0;
2009 }
2010
2011 /*! \brief Report on the final state of a receive fax operation
2012  * \note This will lock the \ref ast_channel
2013  */
2014 static int report_receive_fax_status(struct ast_channel *chan, const char *filename)
2015 {
2016         RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
2017         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
2018         RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
2019         struct ast_json *json_filename = ast_json_string_create(filename);
2020
2021         if (!json_array || !json_filename) {
2022                 ast_json_unref(json_filename);
2023                 return -1;
2024         }
2025         ast_json_array_append(json_array, json_filename);
2026
2027         {
2028                 const char *remote_station_id;
2029                 const char *local_station_id;
2030                 const char *fax_pages;
2031                 const char *fax_resolution;
2032                 const char *fax_bitrate;
2033                 SCOPED_CHANNELLOCK(lock, chan);
2034
2035                 remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
2036                 if (!ast_strlen_zero(remote_station_id)) {
2037                         remote_station_id = ast_strdupa(remote_station_id);
2038                 }
2039                 local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
2040                 if (!ast_strlen_zero(local_station_id)) {
2041                         local_station_id = ast_strdupa(local_station_id);
2042                 }
2043                 fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
2044                 if (!ast_strlen_zero(fax_pages)) {
2045                         fax_pages = ast_strdupa(fax_pages);
2046                 }
2047                 fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
2048                 if (!ast_strlen_zero(fax_resolution)) {
2049                         fax_resolution = ast_strdupa(fax_resolution);
2050                 }
2051                 fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
2052                 if (!ast_strlen_zero(fax_bitrate)) {
2053                         fax_bitrate = ast_strdupa(fax_bitrate);
2054                 }
2055
2056                 json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: o}",
2057                                 "type", "receive",
2058                                 "remote_station_id", S_OR(remote_station_id, ""),
2059                                 "local_station_id", S_OR(local_station_id, ""),
2060                                 "fax_pages", S_OR(fax_pages, ""),
2061                                 "fax_resolution", S_OR(fax_resolution, ""),
2062                                 "fax_bitrate", S_OR(fax_bitrate, ""),
2063                                 "filenames", ast_json_ref(json_array));
2064                 if (!json_object) {
2065                         return -1;
2066                 }
2067
2068                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
2069                 if (!message) {
2070                         return -1;
2071                 }
2072                 stasis_publish(ast_channel_topic(chan), message);
2073         }
2074         return 0;
2075 }
2076
2077 /*! \brief initiate a receive FAX session */
2078 static int receivefax_exec(struct ast_channel *chan, const char *data)
2079 {
2080         char *parse, modems[128] = "";
2081         int channel_alive;
2082         RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
2083         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
2084         struct ast_fax_tech_token *token = NULL;
2085         struct ast_fax_document *doc;
2086         AST_DECLARE_APP_ARGS(args,
2087                 AST_APP_ARG(filename);
2088                 AST_APP_ARG(options);
2089         );
2090         struct ast_flags opts = { 0, };
2091         enum ast_t38_state t38state;
2092
2093         /* initialize output channel variables */
2094         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
2095         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
2096         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
2097         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
2098         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
2099         pbx_builtin_setvar_helper(chan, "FAXMODE", NULL);
2100
2101         /* Get a FAX session details structure from the channel's FAX datastore and create one if
2102          * it does not already exist. */
2103         if (!(details = find_or_create_details(chan))) {
2104                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
2105                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
2106                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2107                 return -1;
2108         }
2109
2110         ast_string_field_set(details, result, "FAILED");
2111         ast_string_field_set(details, resultstr, "error starting fax session");
2112         ast_string_field_set(details, error, "INIT_ERROR");
2113         set_channel_variables(chan, details);
2114
2115         if (details->gateway_id > 0) {
2116                 ast_string_field_set(details, resultstr, "can't receive a fax on a channel with a T.38 gateway");
2117                 set_channel_variables(chan, details);
2118                 ast_log(LOG_ERROR, "executing ReceiveFAX on a channel with a T.38 Gateway is not supported\n");
2119                 return -1;
2120         }
2121
2122         if (details->maxrate < details->minrate) {
2123                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2124                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
2125                 set_channel_variables(chan, details);
2126                 ast_log(LOG_ERROR, "maxrate %u is less than minrate %u\n", details->maxrate, details->minrate);
2127                 return -1;
2128         }
2129
2130         if (check_modem_rate(details->modems, details->minrate)) {
2131                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2132                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %u\n", modems, details->minrate);
2133                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2134                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
2135                 set_channel_variables(chan, details);
2136                 return -1;
2137         }
2138
2139         if (check_modem_rate(details->modems, details->maxrate)) {
2140                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2141                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %u\n", modems, details->maxrate);
2142                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2143                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
2144                 set_channel_variables(chan, details);
2145                 return -1;
2146         }
2147
2148         if (ast_strlen_zero(data)) {
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         parse = ast_strdupa(data);
2156         AST_STANDARD_APP_ARGS(args, parse);
2157
2158         if (!ast_strlen_zero(args.options) &&
2159             ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
2160                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2161                 ast_string_field_set(details, resultstr, "invalid arguments");
2162                 set_channel_variables(chan, details);
2163                 return -1;
2164         }
2165         if (ast_strlen_zero(args.filename)) {
2166                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2167                 ast_string_field_set(details, resultstr, "invalid arguments");
2168                 set_channel_variables(chan, details);
2169                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
2170                 return -1;
2171         }
2172
2173         /* check for unsupported FAX application options */
2174         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
2175                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2176                 ast_string_field_set(details, resultstr, "invalid arguments");
2177                 set_channel_variables(chan, details);
2178                 ast_log(LOG_WARNING, "%s does not support polling\n", app_receivefax);
2179                 return -1;
2180         }
2181
2182         ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
2183
2184         pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
2185         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
2186
2187         if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
2188                 ast_string_field_set(details, error, "MEMORY_ERROR");
2189                 ast_string_field_set(details, resultstr, "error allocating memory");
2190                 set_channel_variables(chan, details);
2191                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2192                 return -1;
2193         }
2194
2195         strcpy(doc->filename, args.filename);
2196         AST_LIST_INSERT_TAIL(&details->documents, doc, next);
2197
2198         ast_verb(3, "Channel '%s' receiving FAX '%s'\n", ast_channel_name(chan), args.filename);
2199
2200         details->caps = AST_FAX_TECH_RECEIVE;
2201         details->option.send_ced = AST_FAX_OPTFLAG_TRUE;
2202
2203         /* check for debug */
2204         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
2205                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
2206         }
2207
2208         /* check for request for status events */
2209         if (ast_test_flag(&opts, OPT_STATUS)) {
2210                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
2211         }
2212
2213         t38state = ast_channel_get_t38_state(chan);
2214         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
2215             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
2216             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2217                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
2218         }
2219
2220         if (!(s = fax_session_reserve(details, &token))) {
2221                 ast_string_field_set(details, resultstr, "error reserving fax session");
2222                 set_channel_variables(chan, details);
2223                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
2224                 return -1;
2225         }
2226
2227         /* make sure the channel is up */
2228         if (ast_channel_state(chan) != AST_STATE_UP) {
2229                 if (ast_answer(chan)) {
2230                         ast_string_field_set(details, resultstr, "error answering channel");
2231                         set_channel_variables(chan, details);
2232                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
2233                         fax_session_release(s, token);
2234                         return -1;
2235                 }
2236         }
2237
2238         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2239                 if (set_fax_t38_caps(chan, details)) {
2240                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2241                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2242                         set_channel_variables(chan, details);
2243                         fax_session_release(s, token);
2244                         return -1;
2245                 }
2246         } else {
2247                 details->caps |= AST_FAX_TECH_AUDIO;
2248         }
2249
2250         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2251                 if (receivefax_t38_init(chan, details)) {
2252                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2253                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2254                         set_channel_variables(chan, details);
2255                         fax_session_release(s, token);
2256                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2257                         return -1;
2258                 }
2259         }
2260
2261         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2262                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2263         }
2264
2265         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2266                 if (disable_t38(chan)) {
2267                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2268                 }
2269         }
2270
2271         if (report_receive_fax_status(chan, args.filename)) {
2272                 ast_log(AST_LOG_ERROR, "Error publishing ReceiveFax status message\n");
2273         }
2274
2275         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2276         return (!channel_alive) ? -1 : 0;
2277 }
2278
2279 static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
2280 {
2281         int timeout_ms;
2282         struct ast_frame *frame = NULL;
2283         struct ast_control_t38_parameters t38_parameters;
2284         struct timeval start;
2285         int ms;
2286
2287         /* send CNG tone while listening for the receiver to initiate a switch
2288          * to T.38 mode; if they do, stop sending the CNG tone and proceed with
2289          * the switch.
2290          *
2291          * 10500 is enough time for 3 CNG tones
2292          */
2293         timeout_ms = 10500;
2294
2295         /* don't send any audio if we've already received a T.38 reinvite */
2296         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
2297                 if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
2298                         ast_log(LOG_ERROR, "error generating CNG tone on %s\n", ast_channel_name(chan));
2299                         return -1;
2300                 }
2301         }
2302
2303         start = ast_tvnow();
2304         while ((ms = ast_remaining_ms(start, timeout_ms))) {
2305                 int break_loop = 0;
2306                 ms = ast_waitfor(chan, ms);
2307
2308                 if (ms < 0) {
2309                         ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", ast_channel_name(chan));
2310                         ast_playtones_stop(chan);
2311                         return -1;
2312                 }
2313
2314                 if (ms == 0) { /* all done, nothing happened */
2315                         break;
2316                 }
2317
2318                 if (!(frame = ast_read(chan))) {
2319                         ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", ast_channel_name(chan));
2320                         ast_playtones_stop(chan);
2321                         return -1;
2322                 }
2323
2324                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2325                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2326                                 (frame->datalen == sizeof(t38_parameters))) {
2327                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2328
2329                         switch (parameters->request_response) {
2330                         case AST_T38_REQUEST_NEGOTIATE:
2331                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2332                                  * do T.38 as well
2333                                  */
2334                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2335                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2336                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2337                                 ast_playtones_stop(chan);
2338                                 break;
2339                         case AST_T38_NEGOTIATED:
2340                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2341                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2342                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2343                                 report_fax_status(chan, details, "T.38 Negotiated");
2344                                 break_loop = 1;
2345                                 break;
2346                         default:
2347                                 break;
2348                         }
2349                 }
2350                 ast_frfree(frame);
2351                 if (break_loop) {
2352                         break;
2353                 }
2354         }
2355
2356         ast_playtones_stop(chan);
2357
2358         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2359                 return 0;
2360         }
2361
2362         /* T.38 negotiation did not happen, initiate a switch if requested */
2363         if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
2364                 ast_debug(1, "Negotiating T.38 for send on %s\n", ast_channel_name(chan));
2365
2366                 /* wait up to five seconds for negotiation to complete */
2367                 timeout_ms = 5000;
2368
2369                 /* set parameters based on the session's parameters */
2370                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2371                 t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
2372                 if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
2373                         return -1;
2374                 }
2375
2376                 start = ast_tvnow();
2377                 while ((ms = ast_remaining_ms(start, timeout_ms))) {
2378                         int break_loop = 0;
2379
2380                         ms = ast_waitfor(chan, ms);
2381                         if (ms < 0) {
2382                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2383                                 return -1;
2384                         }
2385                         if (ms == 0) { /* all done, nothing happened */
2386                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
2387                                 details->caps &= ~AST_FAX_TECH_T38;
2388                                 break;
2389                         }
2390
2391                         if (!(frame = ast_read(chan))) {
2392                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2393                                 return -1;
2394                         }
2395
2396                         if ((frame->frametype == AST_FRAME_CONTROL) &&
2397                                         (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2398                                         (frame->datalen == sizeof(t38_parameters))) {
2399                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
2400
2401                                 switch (parameters->request_response) {
2402                                 case AST_T38_REQUEST_NEGOTIATE:
2403                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2404                                         t38_parameters.request_response = AST_T38_NEGOTIATED;
2405                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2406                                         break;
2407                                 case AST_T38_NEGOTIATED:
2408                                         ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
2409                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2410                                         details->caps &= ~AST_FAX_TECH_AUDIO;
2411                                         report_fax_status(chan, details, "T.38 Negotiated");
2412                                         break_loop = 1;
2413                                         break;
2414                                 case AST_T38_REFUSED:
2415                                         ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
2416                                         details->caps &= ~AST_FAX_TECH_T38;
2417                                         break_loop = 1;
2418                                         break;
2419                                 default:
2420                                         ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
2421                                         details->caps &= ~AST_FAX_TECH_T38;
2422                                         break_loop = 1;
2423                                         break;
2424                                 }
2425                         }
2426                         ast_frfree(frame);
2427                         if (break_loop) {
2428                                 break;
2429                         }
2430                 }
2431
2432                 /* if T.38 was negotiated, we are done initializing */
2433                 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2434                         return 0;
2435                 }
2436
2437                 /* send one more CNG tone to get audio going again for some
2438                  * carriers if we are going to fall back to audio mode */
2439                 if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
2440                         if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
2441                                 ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", ast_channel_name(chan));
2442                                 return -1;
2443                         }
2444
2445                         timeout_ms = 3500;
2446                         start = ast_tvnow();
2447                         while ((ms = ast_remaining_ms(start, timeout_ms))) {
2448                                 int break_loop = 0;
2449
2450                                 ms = ast_waitfor(chan, ms);
2451                                 if (ms < 0) {
2452                                         ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", ast_channel_name(chan));
2453                                         ast_playtones_stop(chan);
2454                                         return -1;
2455                                 }
2456                                 if (ms == 0) { /* all done, nothing happened */
2457                                         break;
2458                                 }
2459
2460                                 if (!(frame = ast_read(chan))) {
2461                                         ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", ast_channel_name(chan));
2462                                         ast_playtones_stop(chan);
2463                                         return -1;
2464                                 }
2465
2466                                 if ((frame->frametype == AST_FRAME_CONTROL) &&
2467                                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2468                                                 (frame->datalen == sizeof(t38_parameters))) {
2469                                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
2470
2471                                         switch (parameters->request_response) {
2472                                         case AST_T38_REQUEST_NEGOTIATE:
2473                                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2474                                                  * do T.38 as well
2475                                                  */
2476                                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2477                                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2478                                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2479                                                 ast_playtones_stop(chan);
2480                                                 break;
2481                                         case AST_T38_NEGOTIATED:
2482                                                 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2483                                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2484                                                 details->caps &= ~AST_FAX_TECH_AUDIO;
2485                                                 report_fax_status(chan, details, "T.38 Negotiated");
2486                                                 break_loop = 1;
2487                                                 break;
2488                                         default:
2489                                                 break;
2490                                         }
2491                                 }
2492                                 ast_frfree(frame);
2493                                 if (break_loop) {
2494                                         break;
2495                                 }
2496                         }
2497
2498                         ast_playtones_stop(chan);
2499
2500                         /* if T.38 was negotiated, we are done initializing */
2501                         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2502                                 return 0;
2503                         }
2504                 }
2505         }
2506
2507         /* if we made it here, then T.38 failed, check the 'f' flag */
2508         if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
2509                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
2510                 return -1;
2511         }
2512
2513         /* ok, audio fallback is allowed */
2514         details->caps |= AST_FAX_TECH_AUDIO;
2515
2516         return 0;
2517 }
2518
2519 /*!
2520  * \brief Report on the status of a completed fax send attempt
2521  * \note This will lock the \ref ast_channel
2522  */
2523 static int report_send_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details)
2524 {
2525         RAII_VAR(struct ast_json *, json_obj, NULL, ast_json_unref);
2526         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
2527         struct ast_json *json_filenames;
2528
2529         json_filenames = generate_filenames_json(details);
2530         if (!json_filenames) {
2531                 return -1;
2532         }
2533
2534         {
2535                 const char *remote_station_id;
2536                 const char *local_station_id;
2537                 const char *fax_pages;
2538                 const char *fax_resolution;
2539                 const char *fax_bitrate;
2540                 SCOPED_CHANNELLOCK(lock, chan);
2541
2542                 remote_station_id = S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), "");
2543                 if (!ast_strlen_zero(remote_station_id)) {
2544                         remote_station_id = ast_strdupa(remote_station_id);
2545                 }
2546                 local_station_id = S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), "");
2547                 if (!ast_strlen_zero(local_station_id)) {
2548                         local_station_id = ast_strdupa(local_station_id);
2549                 }
2550                 fax_pages = S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), "");
2551                 if (!ast_strlen_zero(fax_pages)) {
2552                         fax_pages = ast_strdupa(fax_pages);
2553                 }
2554                 fax_resolution = S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), "");
2555                 if (!ast_strlen_zero(fax_resolution)) {
2556                         fax_resolution = ast_strdupa(fax_resolution);
2557                 }
2558                 fax_bitrate = S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), "");
2559                 if (!ast_strlen_zero(fax_bitrate)) {
2560                         fax_bitrate = ast_strdupa(fax_bitrate);
2561                 }
2562                 json_obj = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: o}",
2563                                 "type", "send",
2564                                 "remote_station_id", S_OR(remote_station_id, ""),
2565                                 "local_station_id", S_OR(local_station_id, ""),
2566                                 "fax_pages", S_OR(fax_pages, ""),
2567                                 "fax_resolution", S_OR(fax_resolution, ""),
2568                                 "fax_bitrate", S_OR(fax_bitrate, ""),
2569                                 "filenames", json_filenames);
2570                 if (!json_obj) {
2571                         return -1;
2572                 }
2573
2574                 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_obj);
2575                 if (!message) {
2576                         return -1;
2577                 }
2578                 stasis_publish(ast_channel_topic(chan), message);
2579         }
2580         return 0;
2581 }
2582
2583
2584
2585 /*! \brief initiate a send FAX session */
2586 static int sendfax_exec(struct ast_channel *chan, const char *data)
2587 {
2588         char *parse, *filenames, *c, modems[128] = "";
2589         int channel_alive, file_count;
2590         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
2591         RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
2592         struct ast_fax_tech_token *token = NULL;
2593         struct ast_fax_document *doc;
2594         AST_DECLARE_APP_ARGS(args,
2595                 AST_APP_ARG(filenames);
2596                 AST_APP_ARG(options);
2597         );
2598         struct ast_flags opts = { 0, };
2599         enum ast_t38_state t38state;
2600
2601         /* initialize output channel variables */
2602         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
2603         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
2604         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
2605         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
2606         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
2607         pbx_builtin_setvar_helper(chan, "FAXMODE", NULL);
2608
2609         /* Get a requirement structure and set it.  This structure is used
2610          * to tell the FAX technology module about the higher level FAX session */
2611         if (!(details = find_or_create_details(chan))) {
2612                 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
2613                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
2614                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2615                 return -1;
2616         }
2617
2618         ast_string_field_set(details, result, "FAILED");
2619         ast_string_field_set(details, resultstr, "error starting fax session");
2620         ast_string_field_set(details, error, "INIT_ERROR");
2621         set_channel_variables(chan, details);
2622
2623         if (details->gateway_id > 0) {
2624                 ast_string_field_set(details, resultstr, "can't send a fax on a channel with a T.38 gateway");
2625                 set_channel_variables(chan, details);
2626                 ast_log(LOG_ERROR, "executing SendFAX on a channel with a T.38 Gateway is not supported\n");
2627                 return -1;
2628         }
2629
2630         if (details->maxrate < details->minrate) {
2631                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2632                 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
2633                 set_channel_variables(chan, details);
2634                 ast_log(LOG_ERROR, "maxrate %u is less than minrate %u\n", details->maxrate, details->minrate);
2635                 return -1;
2636         }
2637
2638         if (check_modem_rate(details->modems, details->minrate)) {
2639                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2640                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %u\n", modems, details->minrate);
2641                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2642                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
2643                 set_channel_variables(chan, details);
2644                 return -1;
2645         }
2646
2647         if (check_modem_rate(details->modems, details->maxrate)) {
2648                 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2649                 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %u\n", modems, details->maxrate);
2650                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2651                 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
2652                 set_channel_variables(chan, details);
2653                 return -1;
2654         }
2655
2656         if (ast_strlen_zero(data)) {
2657                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2658                 ast_string_field_set(details, resultstr, "invalid arguments");
2659                 set_channel_variables(chan, details);
2660                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
2661                 return -1;
2662         }
2663         parse = ast_strdupa(data);
2664         AST_STANDARD_APP_ARGS(args, parse);
2665
2666
2667         if (!ast_strlen_zero(args.options) &&
2668                 ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
2669                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2670                 ast_string_field_set(details, resultstr, "invalid arguments");
2671                 set_channel_variables(chan, details);
2672                 return -1;
2673         }
2674         if (ast_strlen_zero(args.filenames)) {
2675                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2676                 ast_string_field_set(details, resultstr, "invalid arguments");
2677                 set_channel_variables(chan, details);
2678                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
2679                 return -1;
2680         }
2681
2682         /* check for unsupported FAX application options */
2683         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
2684                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2685                 ast_string_field_set(details, resultstr, "invalid arguments");
2686                 set_channel_variables(chan, details);
2687                 ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
2688                 return -1;
2689         }
2690
2691         ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
2692
2693         file_count = 0;
2694         filenames = args.filenames;
2695         while ((c = strsep(&filenames, "&"))) {
2696                 if (access(c, (F_OK | R_OK)) < 0) {
2697                         ast_string_field_set(details, error, "FILE_ERROR");
2698                         ast_string_field_set(details, resultstr, "error reading file");
2699                         set_channel_variables(chan, details);
2700                         ast_log(LOG_ERROR, "access failure.  Verify '%s' exists and check permissions.\n", args.filenames);
2701                         return -1;
2702                 }
2703
2704                 if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
2705                         ast_string_field_set(details, error, "MEMORY_ERROR");
2706                         ast_string_field_set(details, resultstr, "error allocating memory");
2707                         set_channel_variables(chan, details);
2708                         ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2709                         return -1;
2710                 }
2711
2712                 strcpy(doc->filename, c);
2713                 AST_LIST_INSERT_TAIL(&details->documents, doc, next);
2714                 file_count++;
2715         }
2716
2717         ast_verb(3, "Channel '%s' sending FAX:\n", ast_channel_name(chan));
2718         AST_LIST_TRAVERSE(&details->documents, doc, next) {
2719                 ast_verb(3, "   %s\n", doc->filename);
2720         }
2721
2722         details->caps = AST_FAX_TECH_SEND;
2723
2724         if (file_count > 1) {
2725                 details->caps |= AST_FAX_TECH_MULTI_DOC;
2726         }
2727
2728         /* check for debug */
2729         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
2730                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
2731         }
2732
2733         /* check for request for status events */
2734         if (ast_test_flag(&opts, OPT_STATUS)) {
2735                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
2736         }
2737
2738         t38state = ast_channel_get_t38_state(chan);
2739         if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
2740             ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
2741             ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2742                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
2743         }
2744
2745         if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
2746                 details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
2747         }
2748
2749         if (!(s = fax_session_reserve(details, &token))) {
2750                 ast_string_field_set(details, resultstr, "error reserving fax session");
2751                 set_channel_variables(chan, details);
2752                 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
2753                 return -1;
2754         }
2755
2756         /* make sure the channel is up */
2757         if (ast_channel_state(chan) != AST_STATE_UP) {
2758                 if (ast_answer(chan)) {
2759                         ast_string_field_set(details, resultstr, "error answering channel");
2760                         set_channel_variables(chan, details);
2761                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
2762                         fax_session_release(s, token);
2763                         return -1;
2764                 }
2765         }
2766
2767         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2768                 if (set_fax_t38_caps(chan, details)) {
2769                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2770                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2771                         set_channel_variables(chan, details);
2772                         fax_session_release(s, token);
2773                         return -1;
2774                 }
2775         } else {
2776                 details->caps |= AST_FAX_TECH_AUDIO;
2777         }
2778
2779         if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2780                 if (sendfax_t38_init(chan, details)) {
2781                         ast_string_field_set(details, error, "T38_NEG_ERROR");
2782                         ast_string_field_set(details, resultstr, "error negotiating T.38");
2783                         set_channel_variables(chan, details);
2784                         fax_session_release(s, token);
2785                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2786                         return -1;
2787                 }
2788         } else {
2789                 details->option.send_cng = 1;
2790         }
2791
2792         if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2793                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2794         }
2795
2796         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2797                 if (disable_t38(chan)) {
2798                         ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2799                 }
2800         }
2801
2802         if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
2803                 ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
2804                 return (!channel_alive) ? -1 : 0;
2805         }
2806
2807         /* send out the AMI completion event */
2808         if (report_send_fax_status(chan, details)) {
2809                 ast_log(AST_LOG_ERROR, "Error publishing SendFAX status message\n");
2810         }
2811
2812         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2813         return (!channel_alive) ? -1 : 0;
2814 }
2815
2816 /*! \brief destroy the v21 detection parts of a fax gateway session */
2817 static void destroy_v21_sessions(struct fax_gateway *gateway)
2818 {
2819         if (gateway->chan_v21_session) {
2820                 ao2_unlink(faxregistry.container, gateway->chan_v21_session);
2821
2822                 ao2_ref(gateway->chan_v21_session, -1);
2823                 gateway->chan_v21_session = NULL;
2824         }
2825
2826         if (gateway->peer_v21_session) {
2827                 ao2_unlink(faxregistry.container, gateway->peer_v21_session);
2828
2829                 ao2_ref(gateway->peer_v21_session, -1);
2830                 gateway->peer_v21_session = NULL;
2831         }
2832 }
2833
2834 /*! \brief destroy a FAX gateway session structure */
2835 static void destroy_gateway(void *data)
2836 {
2837         struct fax_gateway *gateway = data;
2838
2839         destroy_v21_sessions(gateway);
2840
2841         if (gateway->s) {
2842                 fax_session_release(gateway->s, gateway->token);
2843                 gateway->token = NULL;
2844
2845                 ao2_unlink(faxregistry.container, gateway->s);
2846
2847                 ao2_ref(gateway->s, -1);
2848                 gateway->s = NULL;
2849         }
2850
2851         ao2_cleanup(gateway->chan_read_format);
2852         ao2_cleanup(gateway->chan_write_format);
2853         ao2_cleanup(gateway->peer_read_format);
2854         ao2_cleanup(gateway->peer_write_format);
2855 }
2856
2857 static struct ast_fax_session *fax_v21_session_new (struct ast_channel *chan) {
2858         struct ast_fax_session_details *v21_details;
2859         struct ast_fax_session *v21_session;
2860
2861         if (!chan || !(v21_details = session_details_new())) {
2862                 return NULL;
2863         }
2864
2865         v21_details->caps = AST_FAX_TECH_V21_DETECT;
2866         v21_session = fax_session_new(v21_details, chan, NULL, NULL);
2867         ao2_ref(v21_details, -1);
2868         return v21_session;
2869 }
2870
2871 /*! \brief Create a new fax gateway object.
2872  * \param chan the channel the gateway object will be attached to
2873  * \param details the fax session details
2874  * \return NULL or a fax gateway object
2875  */
2876 static struct fax_gateway *fax_gateway_new(struct ast_channel *chan, struct ast_fax_session_details *details)
2877 {
2878         struct fax_gateway *gateway = ao2_alloc(sizeof(*gateway), destroy_gateway);
2879         if (!gateway) {
2880                 return NULL;
2881         }
2882
2883         if (!(gateway->chan_v21_session = fax_v21_session_new(chan))) {
2884                 ast_log(LOG_ERROR, "Can't create V21 session on chan %s for T.38 gateway session\n", ast_channel_name(chan));
2885                 ao2_ref(gateway, -1);
2886                 return NULL;
2887         }
2888
2889         gateway->framehook = -1;
2890
2891         details->caps = AST_FAX_TECH_GATEWAY;
2892         if (details->gateway_timeout && !(gateway->s = fax_session_reserve(details, &gateway->token))) {
2893                 details->caps &= ~AST_FAX_TECH_GATEWAY;
2894                 ast_log(LOG_ERROR, "Can't reserve a FAX session, gateway attempt failed.\n");
2895                 ao2_ref(gateway, -1);
2896                 return NULL;
2897         }
2898
2899         return gateway;
2900 }
2901
2902 /*!
2903  * \brief Create a fax session and start T.30<->T.38 gateway mode
2904  *
2905  * \param gateway a fax gateway object
2906  * \param details fax session details
2907  * \param chan active channel
2908  *
2909  * \pre chan is locked on entry
2910  *
2911  * \return 0 on error 1 on success
2912  */
2913 static int fax_gateway_start(struct fax_gateway *gateway, struct ast_fax_session_details *details, struct ast_channel *chan)
2914 {
2915         struct ast_fax_session *s;
2916         int start_res;
2917
2918         /* if the fax gateway is already started then do nothing */
2919         if (gateway->s &&
2920                 gateway->s->state != AST_FAX_STATE_RESERVED && gateway->s->state != AST_FAX_STATE_INACTIVE) {
2921                 return 0;
2922         }
2923
2924         /* if we start gateway we don't need v21 detection sessions any more */
2925         destroy_v21_sessions(gateway);
2926
2927         /* create the FAX session */
2928         if (!(s = fax_session_new(details, chan, gateway->s, gateway->token))) {
2929                 gateway->token = NULL;
2930                 ast_string_field_set(details, result, "FAILED");
2931                 ast_string_field_set(details, resultstr, "error starting gateway session");
2932                 ast_string_field_set(details, error, "INIT_ERROR");
2933                 details->is_t38_negotiated = 0;
2934                 set_channel_variables(chan, details);
2935                 report_fax_status(chan, details, "No Available Resource");
2936                 ast_log(LOG_ERROR, "Can't create a FAX session, gateway attempt failed.\n");
2937                 return -1;
2938         }
2939         /* release the reference for the reserved session and replace it with
2940          * the real session */
2941         if (gateway->s) {
2942                 ao2_ref(gateway->s, -1);
2943         }
2944         gateway->s = s;
2945         gateway->token = NULL;
2946
2947         ast_channel_unlock(chan);
2948         start_res = gateway->s->tech->start_session(gateway->s);
2949         ast_channel_lock(chan);
2950         if (start_res < 0) {
2951                 ast_string_field_set(details, result, "FAILED");
2952                 ast_string_field_set(details, resultstr, "error starting gateway session");
2953                 ast_string_field_set(details, error, "INIT_ERROR");
2954                 details->is_t38_negotiated = 0;
2955                 set_channel_variables(chan, details);
2956                 return -1;
2957         }
2958
2959         gateway->timeout_start.tv_sec = 0;
2960         gateway->timeout_start.tv_usec = 0;
2961
2962         report_fax_status(chan, details, "FAX Transmission In Progress");
2963
2964         return 0;
2965 }
2966
2967 /*! \pre chan is locked on entry */
2968 static struct ast_frame *fax_gateway_request_t38(struct fax_gateway *gateway, struct ast_channel *chan)
2969 {
2970         struct ast_frame *fp;
2971         struct ast_control_t38_parameters t38_parameters = {
2972                 .request_response = AST_T38_REQUEST_NEGOTIATE,
2973         };
2974         struct ast_frame control_frame = {
2975                 .src = "res_fax",
2976                 .frametype = AST_FRAME_CONTROL,
2977                 .datalen = sizeof(t38_parameters),
2978                 .subclass.integer = AST_CONTROL_T38_PARAMETERS,
2979                 .data.ptr = &t38_parameters,
2980         };
2981
2982         struct ast_fax_session_details *details = find_details(chan);
2983
2984         if (!details) {
2985                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2986                 ast_framehook_detach(chan, gateway->framehook);
2987                 return NULL;
2988         }
2989
2990         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2991         ao2_ref(details, -1);
2992
2993         if (!(fp = ast_frisolate(&control_frame))) {
2994                 ast_log(LOG_ERROR, "error generating T.38 request control frame on chan %s for T.38 gateway session\n", ast_channel_name(chan));
2995                 return NULL;
2996         }
2997
2998         gateway->t38_state = T38_STATE_NEGOTIATING;
2999         gateway->timeout_start = ast_tvnow();
3000         details->is_t38_negotiated = 0;
3001         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
3002
3003         ast_debug(1, "requesting T.38 for gateway session for %s\n", ast_channel_name(chan));
3004         return fp;
3005 }
3006
3007 /*! \pre chan is locked on entry */
3008 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)
3009 {
3010         struct ast_channel *other = (active == chan) ? peer : chan;
3011         struct ast_fax_session *active_v21_session = (active == chan) ? gateway->chan_v21_session : gateway->peer_v21_session;
3012
3013         if (!active_v21_session || gateway->detected_v21) {
3014                 return f;
3015         }
3016
3017         if (active_v21_session->tech->write(active_v21_session, f) == 0 &&
3018             active_v21_session->details->option.v21_detected) {
3019                 gateway->detected_v21 = 1;
3020         }
3021
3022         if (gateway->detected_v21) {
3023                 enum ast_t38_state state_other;
3024                 enum ast_t38_state state_active;
3025                 struct ast_frame *fp;
3026
3027                 destroy_v21_sessions(gateway);
3028
3029                 ast_channel_unlock(chan);
3030                 state_active = ast_channel_get_t38_state(active);
3031                 state_other = ast_channel_get_t38_state(other);
3032                 ast_channel_lock(chan);
3033
3034                 ast_debug(1, "detected v21 preamble from %s\n", ast_channel_name(active));
3035
3036                 if (state_active == T38_STATE_UNKNOWN || state_other == T38_STATE_UNKNOWN) {
3037                         if (!(fp = fax_gateway_request_t38(gateway, chan))) {
3038                                 return f;
3039                         }
3040                         /* May be called endpoint is improperly configured to rely on the calling endpoint
3041                          * to initiate T.38 re-INVITEs, send T.38 negotiation request to called endpoint */
3042                         if (state_active == T38_STATE_UNKNOWN) {
3043                                 ast_debug(1, "sending T.38 negotiation request to %s\n", ast_channel_name(active));
3044                                 if (active == chan) {
3045                                         ast_channel_unlock(chan);
3046                                 }
3047                                 ast_write(active, fp);
3048                                 if (active == chan) {
3049                                         ast_channel_lock(chan);
3050                                 }
3051                         }
3052                         if (state_other == T38_STATE_UNKNOWN) {
3053                                 ast_debug(1, "sending T.38 negotiation request to %s\n", ast_channel_name(other));
3054                                 return fp;
3055                         }
3056                 } else {
3057                         ast_debug(1, "neither %s nor %s support T.38 for T.38 gateway session\n", ast_channel_name(active), ast_channel_name(other));
3058                 }
3059         }
3060
3061         return f;
3062 }
3063
3064 /*! \pre chan is locked on entry */
3065 static void fax_gateway_indicate_t38(struct ast_channel *chan, struct ast_channel *active, struct ast_control_t38_parameters *control_params)
3066 {
3067         if (active == chan) {
3068                 ast_channel_unlock(chan);
3069                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
3070                 ast_channel_lock(chan);
3071         } else {
3072                 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
3073         }
3074 }
3075
3076 /*!
3077  * \brief T38 Gateway Negotiate t38 parameters
3078  *
3079  * \param gateway gateway object
3080  * \param chan channel running the gateway
3081  * \param peer channel im bridged too
3082  * \param active channel the frame originated on
3083  * \param f the control frame to process
3084  *
3085  * \pre chan is locked on entry
3086  *
3087  * \return processed control frame or null frame
3088  */
3089 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)
3090 {
3091         struct ast_control_t38_parameters *control_params = f->data.ptr;
3092         struct ast_channel *other = (active == chan) ? peer : chan;
3093         struct ast_fax_session_details *details;
3094         enum ast_t38_state state_other;
3095
3096         if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
3097                 /* invalaid AST_CONTROL_T38_PARAMETERS frame, we can't
3098                  * do anything with it, pass it on */
3099                 return f;
3100         }
3101
3102         /* ignore frames from ourselves */
3103         if ((gateway->t38_state == T38_STATE_NEGOTIATED && control_params->request_response == AST_T38_NEGOTIATED)
3104                 || (gateway->t38_state == T38_STATE_REJECTED && control_params->request_response == AST_T38_REFUSED)
3105                 || (gateway->t38_state == T38_STATE_NEGOTIATING && control_params->request_response == AST_T38_REQUEST_TERMINATE)) {
3106
3107                 return f;
3108         }
3109
3110         if (!(details = find_details(chan))) {
3111                 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
3112                 ast_framehook_detach(chan, gateway->framehook);
3113                 return f;
3114         }
3115
3116         if (control_params->request_response == AST_T38_REQUEST_NEGOTIATE) {
3117                 ast_channel_unlock(chan);
3118                 state_other = ast_channel_get_t38_state(other);
3119                 ast_channel_lock(chan);
3120
3121                 if (state_other == T38_STATE_UNKNOWN) {
3122                         /* we detected a request to negotiate T.38 and the
3123                          * other channel appears to support T.38, we'll pass
3124                          * the request through and only step in if the other
3125                          * channel rejects the request */
3126                         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));
3127                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
3128                         gateway->t38_state = T38_STATE_UNKNOWN;
3129                         gateway->timeout_start = ast_tvnow();
3130                         details->is_t38_negotiated = 0;
3131                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
3132                         ao2_ref(details, -1);
3133                         return f;
3134                 } else if (state_other == T38_STATE_UNAVAILABLE || state_other == T38_STATE_REJECTED) {
3135                         /* the other channel does not support T.38, we need to
3136                          * step in here */
3137                         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));
3138                         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));
3139
3140                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
3141                         t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
3142
3143                         if (fax_gateway_start(gateway, details, chan)) {
3144                                 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));
3145                                 gateway->t38_state = T38_STATE_REJECTED;
3146                                 details->is_t38_negotiated = 0;
3147                                 control_params->request_response = AST_T38_REFUSED;
3148
3149                                 ast_framehook_detach(chan, details->gateway_id);
3150                                 details->gateway_id = -1;
3151                         } else {
3152                                 gateway->t38_state = T38_STATE_NEGOTIATED;
3153                                 details->is_t38_negotiated = chan == active;
3154                                 control_params->request_response = AST_T38_NEGOTIATED;
3155                                 report_fax_status(chan, details, "T.38 Negotiated");
3156                         }
3157
3158                         fax_gateway_indicate_t38(chan, active, control_params);
3159
3160                         ao2_ref(details, -1);
3161                         return &ast_null_frame;
3162                 } else if (gateway->t38_state == T38_STATE_NEGOTIATING) {
3163                         /* we got a request to negotiate T.38 after we already
3164                          * sent one to the other party based on v21 preamble
3165                          * detection. We'll just pretend we passed this request
3166                          * through in the first place. */
3167
3168                         t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
3169                         gateway->t38_state = T38_STATE_UNKNOWN;
3170                         gateway->timeout_start = ast_tvnow();
3171                         details->is_t38_negotiated = 0;
3172                         details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
3173
3174                         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));
3175                         ao2_ref(details, -1);
3176                         return &ast_null_frame;
3177                 } else if (gateway->t38_state == T38_STATE_NEGOTIATED) {
3178                         /* we got a request to negotiate T.38 after we already
3179                          * sent one to the other party based on v21 preamble
3180                          * detection and received a response. We need to
3181                          * respond to this and shut down the gateway. */
3182
3183                         t38_parameters_fax_to_ast(control_params, &details->their_t38_parameters);
3184                         ast_framehook_detach(chan, details->gateway_id);
3185                         details->gateway_id = -1;
3186
3187                         control_params->request_response = AST_T38_NEGOTIATED;
3188
3189                         fax_gateway_indicate_t38(chan, active, control_params);
3190
3191                         ast_string_field_set(details, result, "SUCCESS");
3192                         ast_string_field_set(details, resultstr, "no gateway necessary");
3193                         ast_string_field_set(details, error, "NATIVE_T38");
3194                         details->is_t38_negotiated = 1;
3195                         set_channel_variables(chan, details);
3196
3197                         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));
3198                         ao2_ref(details, -1);
3199                         return &ast_null_frame;
3200                 } else {
3201                         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));
3202                         ao2_ref(details, -1);
3203                         return f;
3204                 }
3205         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
3206                 && control_params->request_response == AST_T38_REFUSED) {
3207
3208                 ast_debug(1, "unable to negotiate T.38 on %s for fax gateway\n", ast_channel_name(active));
3209                 details->is_t38_negotiated = 0;
3210
3211                 /* our request to negotiate T.38 was refused, if the other
3212                  * channel supports T.38, they might still reinvite and save
3213                  * the day.  Otherwise disable the gateway. */
3214                 ast_channel_unlock(chan);
3215                 state_other = ast_channel_get_t38_state(other);
3216                 ast_channel_lock(chan);
3217                 if (state_other == T38_STATE_UNKNOWN) {
3218                         gateway->t38_state = T38_STATE_UNAVAILABLE;
3219                 } else if (state_other != T38_STATE_NEGOTIATING) {
3220                         ast_framehook_detach(chan, details->gateway_id);
3221                         details->gateway_id = -1;
3222
3223                         ast_string_field_set(details, result, "FAILED");
3224                         ast_string_field_set(details, resultstr, "unable to negotiate T.38");
3225                         ast_string_field_set(details, error, "T38_NEG_ERROR");
3226                         set_channel_variables(chan, details);
3227                 }
3228
3229                 ao2_ref(details, -1);
3230                 return &ast_null_frame;
3231         } else if (gateway->t38_state == T38_STATE_NEGOTIATING
3232                 && control_params->request_response == AST_T38_NEGOTIATED) {
3233
3234                 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));
3235
3236                 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
3237
3238                 if (fax_gateway_start(gateway, details, chan)) {
3239                         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));
3240                         gateway->t38_state = T38_STATE_NEGOTIATING;
3241                         details->is_t38_negotiated = 0;
3242                         control_params->request_response = AST_T38_REQUEST_TERMINATE;
3243
3244                         fax_gateway_indicate_t38(chan, active, control_params);
3245                 } else {
3246                         gateway->t38_state = T38_STATE_NEGOTIATED;
3247                         details->is_t38_negotiated = chan == active;
3248                         report_fax_status(chan, details, "T.38 Negotiated");
3249                 }
3250
3251                 ao2_ref(details, -1);
3252                 return &ast_null_frame;
3253         } else if (control_params->request_response == AST_T38_REFUSED) {
3254                 /* the other channel refused the request to negotiate T.38,
3255                  * we'll step in here and pretend the request was accepted */
3256
3257                 ast_debug(1, "%s attempted to negotiate T.38 but %s refused the request\n", ast_channel_name(other), ast_channel_name(active));
3258                 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));
3259
3260                 t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
3261
3262                 if (fax_gateway_start(gateway, details, chan)) {
3263                         ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(other), ast_channel_name(active));
3264                         gateway->t38_state = T38_STATE_REJECTED;
3265                         details->is_t38_negotiated = 0;
3266                         control_params->request_response = AST_T38_REFUSED;
3267
3268                         ast_framehook_detach(chan, details->gateway_id);
3269                         details->gateway_id = -1;
3270                 } else {
3271                         gateway->t38_state = T38_STATE_NEGOTIATED;
3272                         details->is_t38_negotiated = chan == other;
3273                         control_params->request_response = AST_T38_NEGOTIATED;
3274                 }
3275
3276                 ao2_ref(details, -1);
3277                 return f;
3278         } else if (control_params->request_response == AST_T38_REQUEST_TERMINATE) {
3279                 /* the channel wishes to end our short relationship, we shall
3280                  * oblige */
3281
3282                 ast_debug(1, "T.38 channel %s is requesting a shutdown of T.38, disabling the gateway\n", ast_channel_name(active));
3283
3284                 ast_framehook_detach(chan, details->gateway_id);
3285                 details->gateway_id = -1;
3286
3287                 gateway->t38_state = T38_STATE_REJECTED;
3288                 details->is_t38_negotiated = 0;
3289                 control_params->request_response = AST_T38_TERMINATED;
3290
3291                 fax_gateway_indicate_t38(chan, active, control_params);
3292
3293                 ao2_ref(details, -1);
3294                 return &ast_null_frame;
3295         } else if (control_params->request_response == AST_T38_NEGOTIATED) {
3296                 ast_debug(1, "T.38 successfully negotiated between %s and %s, no gateway necessary\n", ast_channel_name(active), ast_channel_name(other));
3297
3298                 ast_framehook_detach(chan, details->gateway_id);
3299                 details->gateway_id = -1;
3300
3301                 ast_string_field_set(details, result, "SUCCESS");
3302                 ast_string_field_set(details, resultstr, "no gateway necessary");
3303                 ast_string_field_set(details, error, "NATIVE_T38");
3304                 details->is_t38_negotiated = 1;
3305                 set_channel_variables(chan, details);
3306
3307                 ao2_ref(details, -1);
3308                 return f;
3309         } else if (control_params->request_response == AST_T38_TERMINATED) {
3310                 ast_debug(1, "T.38 disabled on channel %s\n", ast_channel_name(active));
3311
3312                 ast_framehook_detach(chan, details->gateway_id);
3313                 details->gateway_id = -1;
3314
3315                 ao2_ref(details, -1);
3316                 return &ast_null_frame;
3317         }
3318
3319         ao2_ref(details, -1);
3320         return f;
3321 }
3322
3323 /*! \brief Destroy the gateway data structure when the framehook is detached
3324  * \param data framehook data (gateway data)*/
3325 static void fax_gateway_framehook_destroy(void *data)
3326 {
3327         struct fax_gateway *gateway = data;
3328
3329         if (gateway->s) {
3330                 switch (gateway->s->state) {
3331                 case AST_FAX_STATE_INITIALIZED:
3332                 case AST_FAX_STATE_OPEN:
3333                 case AST_FAX_STATE_ACTIVE:
3334                 case AST_FAX_STATE_COMPLETE:
3335                         if (gateway->s->tech->cancel_session) {
3336                                 gateway->s->tech->cancel_session(gateway->s);
3337                         }
3338                         /* fall through */
3339                 default:
3340                         break;
3341                 }
3342         }
3343
3344         ao2_ref(gateway, -1);
3345 }
3346
3347 /*!
3348  * \brief T.30<->T.38 gateway framehook.
3349  *
3350  * Intercept packets on bridged channels and determine if a T.38 gateway is
3351  * required. If a gateway is required, start a gateway and handle T.38
3352  * negotiation if necessary.
3353  *
3354  * \param chan channel running the gateway
3355  * \param f frame to handle may be NULL
3356  * \param event framehook event
3357  * \param data framehook data (struct fax_gateway *)
3358  *
3359  * \pre chan is locked on entry
3360  *
3361  * \return processed frame or NULL when f is NULL or a null frame
3362  */
3363 static struct ast_frame *fax_gateway_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data)
3364 {
3365         struct fax_gateway *gateway = data;
3366         struct ast_channel *active;
3367         RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
3368         RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
3369         RAII_VAR(struct ast_channel *, chan_ref, chan, ao2_cleanup);
3370
3371         /* Ref bump channel for when we have to unlock it */
3372         ao2_ref(chan_ref, 1);
3373
3374         if (gateway->s) {
3375                 details = gateway->s->details;
3376                 ao2_ref(details, 1);
3377         } else {
3378                 if (!(details = find_details(chan))) {
3379                         ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
3380                         ast_framehook_detach(chan, gateway->framehook);
3381                         return f;
3382                 }
3383         }
3384
3385         /* restore audio formats when we are detached */
3386         if (event == AST_FRAMEHOOK_EVENT_DETACHED) {
3387                 set_channel_variables(chan, details);
3388
3389                 if (gateway->bridged) {
3390                         ast_set_read_format(chan, gateway->chan_read_format);
3391                         ast_set_write_format(chan, gateway->chan_write_format);
3392
3393                         ast_channel_unlock(chan);
3394                         peer = ast_channel_bridge_peer(chan);
3395                         if (peer) {
3396                                 ast_set_read_format(peer, gateway->peer_read_format);
3397                                 ast_set_write_format(peer, gateway->peer_write_format);
3398                                 ast_channel_make_compatible(chan, peer);
3399                         }
3400                         ast_channel_lock(chan);
3401                 }
3402                 return NULL;
3403         }
3404
3405         if (!f || (event == AST_FRAMEHOOK_EVENT_ATTACHED)) {
3406                 return NULL;
3407         };
3408
3409         /* this frame was generated by the fax gateway, pass it on */
3410         if (ast_test_flag(f, AST_FAX_FRFLAG_GATEWAY)) {
3411                 return f;
3412         }
3413
3414         /* If we aren't bridged or we don't have a peer, don't do anything */
3415         ast_channel_unlock(chan);
3416         peer = ast_channel_bridge_peer(chan);
3417         ast_channel_lock(chan);
3418         if (!peer) {
3419                 return f;
3420         }
3421
3422         if (!gateway->bridged) {
3423                 enum ast_t38_state state_chan;
3424                 enum ast_t38_state state_peer;
3425
3426                 ast_channel_unlock(chan);
3427                 state_chan = ast_channel_get_t38_state(chan);
3428                 state_peer = ast_channel_get_t38_state(peer);
3429                 ast_channel_lock(chan);
3430
3431                 /* don't start a gateway if neither channel can handle T.38 */
3432                 if (state_chan == T38_STATE_UNAVAILABLE && state_peer == T38_STATE_UNAVAILABLE) {
3433                         ast_debug(1, "not starting gateway for %s and %s; neither channel supports T.38\n", ast_channel_name(chan), ast_channel_name(peer));
3434                         ast_framehook_detach(chan, gateway->framehook);
3435                         details->gateway_id = -1;
3436
3437                         ast_string_field_set(details, result, "FAILED");
3438                         ast_string_field_set(details, resultstr, "neither channel supports T.38");
3439                         ast_string_field_set(details, error, "T38_NEG_ERROR");
3440                         details->is_t38_negotiated = 0;
3441                         set_channel_variables(chan, details);
3442                         return f;
3443                 }
3444
3445                 if (details->gateway_timeout) {
3446                         gateway->timeout_start = ast_tvnow();
3447                 }
3448
3449                 ast_channel_unlock(chan);
3450                 ast_channel_lock_both(chan, peer);
3451
3452                 /* we are bridged, change r/w formats to SLIN for v21 preamble
3453                  * detection and T.30 */
3454                 ao2_replace(gateway->chan_read_format, ast_channel_readformat(chan));
3455                 ao2_replace(gateway->chan_write_format, ast_channel_writeformat(chan));
3456
3457                 ao2_replace(gateway->peer_read_format, ast_channel_readformat(peer));
3458                 ao2_replace(gateway->peer_write_format, ast_channel_writeformat(peer));
3459
3460                 ast_set_read_format(chan, ast_format_slin);
3461                 ast_set_write_format(chan, ast_format_slin);
3462
3463                 ast_set_read_format(peer, ast_format_slin);
3464                 ast_set_write_format(peer, ast_format_slin);
3465
3466                 ast_channel_unlock(peer);
3467
3468                 gateway->bridged = 1;
3469                 if (!(gateway->peer_v21_session = fax_v21_session_new(peer))) {
3470                         ast_log(LOG_ERROR, "Can't create V21 session on chan %s for T.38 gateway session\n", ast_channel_name(peer));
3471                         ast_framehook_detach(chan, gateway->framehook);
3472                         return f;
3473                 }
3474         }
3475
3476         if (gateway->bridged && !ast_tvzero(gateway->timeout_start)) {
3477                 if (ast_tvdiff_ms(ast_tvnow(), gateway->timeout_start) > details->gateway_timeout) {
3478                         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);
3479                         ast_framehook_detach(chan, gateway->framehook);
3480                         details->gateway_id = -1;
3481
3482                         ast_string_field_set(details, result, "FAILED");
3483                         ast_string_field_build(details, resultstr, "no fax activity after %d ms", details->gateway_timeout);
3484                         ast_string_field_set(details, error, "TIMEOUT");
3485                         details->is_t38_negotiated = 0;
3486                         set_channel_variables(chan, details);
3487                         return f;
3488                 }
3489         }
3490
3491         /* only handle VOICE, MODEM, and CONTROL frames*/
3492         switch (f->frametype) {
3493         case AST_FRAME_VOICE:
3494                 if ((ast_format_cmp(f->subclass.format, ast_format_slin) != AST_FORMAT_CMP_EQUAL) &&
3495                         (ast_format_cmp(f->subclass.format, ast_format_alaw) != AST_FORMAT_CMP_EQUAL) &&
3496                         (ast_format_cmp(f->subclass.format, ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
3497                         return f;
3498                 }
3499                 break;
3500         case AST_FRAME_MODEM:
3501                 if (f->subclass.integer == AST_MODEM_T38) {
3502                         break;
3503                 }
3504                 return f;
3505         case AST_FRAME_CONTROL:
3506                 if (f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
3507                         break;
3508                 }
3509                 return f;
3510         default:
3511                 return f;
3512         }
3513
3514         /* detect the active channel */
3515         switch (event) {
3516         case AST_FRAMEHOOK_EVENT_WRITE:
3517                 active = peer;
3518                 break;
3519         case AST_FRAMEHOOK_EVENT_READ:
3520                 active = chan;
3521                 break;
3522         default:
3523                 ast_log(LOG_WARNING, "unhandled framehook event %u\n", event);
3524                 return f;
3525         }
3526
3527         /* handle control frames */
3528         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
3529                 return fax_gateway_detect_t38(gateway, chan, peer, active, f);
3530         }
3531
3532         if (!gateway->detected_v21 && gateway->t38_state == T38_STATE_UNAVAILABLE && f->frametype == AST_FRAME_VOICE) {
3533                 /* not in gateway mode and have not detected v21 yet, listen
3534                  * for v21 */
3535                 return fax_gateway_detect_v21(gateway, chan, peer, active, f);
3536         }
3537
3538         /* in gateway mode, gateway some packets */
3539         if (gateway->t38_state == T38_STATE_NEGOTIATED) {
3540                 struct ast_trans_pvt *readtrans;
3541
3542                 if (!gateway->s || !gateway->s->tech_pvt) {
3543                         ast_log(LOG_ERROR, "no FAX session on chan %s for T.38 gateway session, odd", ast_channel_name(chan));
3544                         return f;
3545                 }
3546
3547                 /* framehooks are called in __ast_read() before frame format
3548                  * translation is done, so we need to translate here */
3549                 if ((f->frametype == AST_FRAME_VOICE) && (ast_format_cmp(f->subclass.format, ast_format_slin) != AST_FORMAT_CMP_EQUAL)
3550                         && (readtrans = ast_channel_readtrans(active))) {
3551                         if ((f = ast_translate(readtrans, f, 1)) == NULL) {
3552                                 f = &ast_null_frame;
3553                                 return f;
3554                         }
3555                         /* XXX we ignore the return value here, perhaps we should
3556                          * disable the gateway if a write fails. I am not sure how a
3557                          * write would fail, or even if a failure would be fatal so for
3558                          * now we'll just ignore the return value. */
3559                         gateway->s->tech->write(gateway->s, f);
3560                         ast_frfree(f);
3561                 } else {
3562                         gateway->s->tech->write(gateway->s, f);
3563                 }
3564
3565                 f = &ast_null_frame;
3566                 return f;
3567         }
3568
3569         /* force silence on the line if T.38 negotiation might be taking place */
3570         if (gateway->t38_state != T38_STATE_UNAVAILABLE && gateway->t38_state != T38_STATE_REJECTED) {
3571                 if (f->frametype == AST_FRAME_VOICE &&
3572                         (ast_format_cmp(f->subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL)) {
3573                         short silence_buf[f->samples];
3574                         struct ast_frame silence_frame = {
3575                                 .frametype = AST_FRAME_VOICE,
3576                                 .subclass.format = ast_format_slin,
3577                                 .data.ptr = silence_buf,
3578                                 .samples = f->samples,
3579                                 .datalen = sizeof(silence_buf),
3580                         };
3581                         memset(silence_buf, 0, sizeof(silence_buf));
3582                         return ast_frisolate(&silence_frame);
3583                 } else {
3584                         return &ast_null_frame;
3585                 }
3586         }
3587
3588         return f;
3589 }
3590
3591 /*! \brief Attach a gateway framehook object to a channel.
3592  * \param chan the channel to attach to
3593  * \param details fax session details
3594  * \return the framehook id of the attached framehook or -1 on error
3595  * \retval -1 error
3596  */
3597 static int fax_gateway_attach(struct ast_channel *chan, struct ast_fax_session_details *details)
3598 {
3599         struct fax_gateway *gateway;
3600         struct ast_framehook_interface fr_hook = {
3601                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
3602                 .event_cb = fax_gateway_framehook,
3603                 .destroy_cb = fax_gateway_framehook_destroy,
3604                 .disable_inheritance = 1, /* Masquerade inheritance is handled through the datastore fixup */
3605         };
3606
3607         if (global_fax_debug) {
3608                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
3609         }
3610
3611         ast_string_field_set(details, result, "SUCCESS");
3612         ast_string_field_set(details, resultstr, "gateway operation started successfully");
3613         ast_string_field_set(details, error, "NO_ERROR");
3614         set_channel_variables(chan, details);
3615
3616         /* set up the frame hook*/
3617         gateway = fax_gateway_new(chan, details);
3618         if (!gateway) {
3619                 ast_string_field_set(details, result, "FAILED");
3620                 ast_string_field_set(details, resultstr, "error initializing gateway session");
3621                 ast_string_field_set(details, error, "INIT_ERROR");
3622                 details->is_t38_negotiated = 0;
3623                 set_channel_variables(chan, details);
3624                 report_fax_status(chan, details, "No Available Resource");
3625                 return -1;
3626         }
3627
3628         fr_hook.data = gateway;
3629         ast_channel_lock(chan);
3630         gateway->framehook = ast_framehook_attach(chan, &fr_hook);
3631         ast_channel_unlock(chan);
3632
3633         if (gateway->framehook < 0) {
3634                 ao2_ref(gateway, -1);
3635                 ast_string_field_set(details, result, "FAILED");
3636                 ast_string_field_set(details, resultstr, "error attaching gateway to channel");
3637                 ast_string_field_set(details, error, "INIT_ERROR");
3638                 details->is_t38_negotiated = 0;
3639                 set_channel_variables(chan, details);
3640                 return -1;
3641         }
3642
3643         return gateway->framehook;
3644 }
3645
3646 /*! \brief destroy a FAX detect structure */
3647 static void destroy_faxdetect(void *data)
3648 {
3649         struct fax_detect *faxdetect = data;
3650
3651         if (faxdetect->dsp) {
3652                 ast_dsp_free(faxdetect->dsp);
3653                 faxdetect->dsp = NULL;
3654         }
3655         ao2_cleanup(faxdetect->details);
3656         ao2_cleanup(faxdetect->orig_format);
3657 }
3658
3659 /*! \brief Create a new fax detect object.
3660  * \param chan the channel attaching to
3661  * \param timeout in ms to remove framehook in this time if not zero
3662  * \param flags required options
3663  * \return NULL or a fax gateway object
3664  */
3665 static struct fax_detect *fax_detect_new(struct ast_channel *chan, int timeout, int flags)
3666 {
3667         struct fax_detect *faxdetect = ao2_alloc(sizeof(*faxdetect), destroy_faxdetect);
3668         if (!faxdetect) {
3669                 return NULL;
3670         }
3671
3672         faxdetect->flags = flags;
3673
3674         if (timeout) {
3675                 faxdetect->timeout_start = ast_tvnow();
3676         } else {
3677                 faxdetect->timeout_start.tv_sec = 0;
3678                 faxdetect->timeout_start.tv_usec = 0;
3679         }
3680
3681         if (faxdetect->flags & FAX_DETECT_MODE_CNG) {
3682                 faxdetect->dsp = ast_dsp_new();
3683                 if (!faxdetect->dsp) {
3684                         ao2_ref(faxdetect, -1);
3685                         return NULL;
3686                 }
3687                 ast_dsp_set_features(faxdetect->dsp, DSP_FEATURE_FAX_DETECT);
3688                 ast_dsp_set_faxmode(faxdetect->dsp, DSP_FAXMODE_DETECT_CNG | DSP_FAXMODE_DETECT_SQUELCH);
3689         } else {
3690                 faxdetect->dsp = NULL;
3691         }
3692
3693         return faxdetect;
3694 }
3695
3696 /*! \brief Deref the faxdetect data structure when the faxdetect framehook is detached
3697  * \param data framehook data (faxdetect data)*/
3698 static void fax_detect_framehook_destroy(void *data)
3699 {
3700         struct fax_detect *faxdetect = data;
3701
3702         ao2_ref(faxdetect, -1);
3703 }
3704
3705 /*! \brief Fax Detect Framehook
3706  *
3707  * Listen for fax tones in audio path and enable jumping to a extension when detected.
3708  *
3709  * \param chan channel
3710  * \param f frame to handle may be NULL
3711  * \param event framehook event
3712  * \param data framehook data (struct fax_detect *)
3713  *
3714  * \return processed frame or NULL when f is NULL or a null frame
3715  */
3716 static struct ast_frame *fax_detect_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data)
3717 {
3718         struct fax_detect *faxdetect = data;
3719         struct ast_fax_session_details *details;
3720         struct ast_control_t38_parameters *control_params;
3721         RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
3722         RAII_VAR(struct ast_channel *, chan_ref, chan, ao2_cleanup);
3723         int result = 0;
3724
3725         /* Ref bump the channel for when we have to unlock it */
3726         ao2_ref(chan, 1);
3727
3728         details = faxdetect->details;
3729
3730         switch (event) {
3731         case AST_FRAMEHOOK_EVENT_ATTACHED:
3732                 /* Setup format for DSP on ATTACH*/
3733                 ao2_replace(faxdetect->orig_format, ast_channel_readformat(chan));
3734
3735                 if ((ast_format_cmp(ast_channel_readformat(chan), ast_format_slin) != AST_FORMAT_CMP_EQUAL) &&
3736                         (ast_format_cmp(ast_channel_readformat(chan), ast_format_alaw) != AST_FORMAT_CMP_EQUAL) &&
3737                         (ast_format_cmp(ast_channel_readformat(chan), ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
3738                         if (ast_set_read_format(chan, ast_format_slin)) {
3739                                 ast_framehook_detach(chan, details->faxdetect_id);
3740                                 details->faxdetect_id = -1;
3741                                 return f;
3742                         }
3743                 }
3744
3745                 return NULL;
3746         case AST_FRAMEHOOK_EVENT_DETACHED:
3747                 /* restore audio formats when we are detached */
3748                 ast_set_read_format(chan, faxdetect->orig_format);
3749                 ast_channel_unlock(chan);
3750                 peer = ast_channel_bridge_peer(chan);
3751                 if (peer) {
3752                         ast_channel_make_compatible(chan, peer);
3753                 }
3754                 ast_channel_lock(chan);
3755                 return NULL;
3756         case AST_FRAMEHOOK_EVENT_READ:
3757                 if (f) {
3758                         break;
3759                 }
3760         default:
3761                 return f;
3762         };
3763
3764         if (details->faxdetect_id < 0) {
3765                 return f;
3766         }
3767
3768         if (!ast_tvzero(faxdetect->timeout_start)
3769                 && ast_tvdiff_ms(ast_tvnow(), faxdetect->timeout_start) > details->faxdetect_timeout) {
3770                 ast_debug(1, "FAXOPT(faxdetect) timeout on %s\n", ast_channel_name(chan));
3771                 ast_framehook_detach(chan, details->faxdetect_id);
3772                 details->faxdetect_id = -1;
3773                 return f;
3774         }
3775
3776         /* only handle VOICE and CONTROL frames*/
3777         switch (f->frametype) {
3778         case AST_FRAME_VOICE:
3779                 /* we have no DSP this means we not detecting CNG */
3780                 if (!faxdetect->dsp) {
3781                         return f;
3782                 }
3783                 /* We can only process some formats*/
3784                 if ((ast_format_cmp(f->subclass.format, ast_format_slin) != AST_FORMAT_CMP_EQUAL) &&
3785                         (ast_format_cmp(f->subclass.format, ast_format_alaw) != AST_FORMAT_CMP_EQUAL) &&
3786                         (ast_format_cmp(f->subclass.format, ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
3787                         return f;
3788                 }
3789                 break;
3790         case AST_FRAME_CONTROL:
3791                 if ((f->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
3792                     (faxdetect->flags & FAX_DETECT_MODE_T38)) {
3793                         break;
3794                 }
3795                 return f;
3796         default:
3797                 return f;
3798         }
3799
3800         if (f->frametype == AST_FRAME_VOICE) {
3801                 f = ast_dsp_process(chan, faxdetect->dsp, f);
3802                 if (f->frametype == AST_FRAME_DTMF) {
3803                         result = f->subclass.integer;
3804                 }
3805         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->datalen == sizeof(struct ast_control_t38_parameters))) {
3806                 control_params = f->data.ptr;
3807                 switch (control_params->request_response) {
3808                 case AST_T38_NEGOTIATED:
3809                 case AST_T38_REQUEST_NEGOTIATE:
3810                         result = 't';
3811                         break;
3812                 default:
3813                         break;
3814                 }
3815         }
3816
3817         if (result) {
3818                 const char *target_context;
3819
3820                 switch (result) {
3821                 case 'f':
3822                 case 't':
3823                         target_context = S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan));
3824
3825                         ast_channel_unlock(chan);
3826                         ast_frfree(f);
3827                         f = &ast_null_frame;
3828                         if (ast_exists_extension(chan, target_context, "fax", 1,
3829                             S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
3830                                 ast_verb(2, "Redirecting '%s' to fax extension due to %s detection\n",
3831                                         ast_channel_name(chan), (result == 'f') ? "CNG" : "T38");
3832                                 pbx_builtin_setvar_helper(chan, "FAXEXTEN", ast_channel_exten(chan));
3833                                 if (ast_async_goto(chan, target_context, "fax", 1)) {
3834                                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(chan), target_context);
3835                                 }
3836                         } else {
3837                                 ast_log(LOG_NOTICE, "FAX %s detected but no fax extension in context (%s)\n",
3838                                         (result == 'f') ? "CNG" : "T38", target_context);
3839                         }
3840                         ast_channel_lock(chan);
3841
3842                         ast_framehook_detach(chan, details->faxdetect_id);
3843                         details->faxdetect_id = -1;
3844                         break;
3845                 default:
3846                         break;
3847                 }
3848         }
3849
3850         return f;
3851 }
3852
3853 /*! \brief Attach a faxdetect framehook object to a channel.
3854  * \param chan the channel to attach to
3855  * \param timeout in ms to remove framehook in this time if not zero
3856  * \return the faxdetect structure or NULL on error
3857  * \param flags required options
3858  * \retval -1 error
3859  */
3860 static int fax_detect_attach(struct ast_channel *chan, int timeout, int flags)
3861 {
3862         struct fax_detect *faxdetect;
3863         struct ast_fax_session_details *details;
3864         struct ast_framehook_interface fr_hook = {
3865                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
3866                 .event_cb = fax_detect_framehook,
3867                 .destroy_cb = fax_detect_framehook_destroy,
3868         };
3869
3870         if (!(details = find_or_create_details(chan))) {
3871                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
3872                 return -1;
3873         }
3874
3875         /* set up the frame hook*/
3876         faxdetect = fax_detect_new(chan, timeout, flags);
3877         if (!faxdetect) {
3878                 ao2_ref(details, -1);
3879                 return -1;
3880         }
3881
3882         fr_hook.data = faxdetect;
3883         faxdetect->details = details;
3884         ast_channel_lock(chan);
3885         details->faxdetect_id = ast_framehook_attach(chan, &fr_hook);
3886         details->faxdetect_timeout = timeout;
3887         details->faxdetect_flags = flags;
3888         ast_channel_unlock(chan);
3889
3890         if (details->faxdetect_id < 0) {
3891                 ao2_ref(faxdetect, -1);
3892         }
3893
3894         return details->faxdetect_id;
3895 }
3896
3897 /*! \brief hash callback for ao2 */
3898 static int session_hash_cb(const void *obj, const int flags)
3899 {
3900         const struct ast_fax_session *s = obj;