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