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