2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2008-2009, Digium, Inc.
6 * Dwayne M. Hubbard <dhubbard@digium.com>
7 * Kevin P. Fleming <kpfleming@digium.com>
8 * Matthew Nicholson <mnicholson@digium.com>
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
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
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
23 * Modified to make T.38-gateway work
24 * 2010, Klaus Darilion, IPCom GmbH, www.ipcom.at
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.
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.
38 <conflict>app_fax</conflict>
39 <support_level>core</support_level>
44 * \brief Generic FAX Resource for FAX technology resource modules
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>
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
57 /*! \li \ref res_fax.c uses the configuration file \ref res_fax.conf
58 * \addtogroup configuration_file Configuration Files
62 * \page res_fax.conf res_fax.conf
63 * \verbinclude res_fax.conf.sample
68 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
70 #include "asterisk/io.h"
71 #include "asterisk/file.h"
72 #include "asterisk/logger.h"
73 #include "asterisk/module.h"
74 #include "asterisk/app.h"
75 #include "asterisk/lock.h"
76 #include "asterisk/options.h"
77 #include "asterisk/strings.h"
78 #include "asterisk/cli.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/config.h"
81 #include "asterisk/astobj2.h"
82 #include "asterisk/res_fax.h"
83 #include "asterisk/file.h"
84 #include "asterisk/channel.h"
85 #include "asterisk/pbx.h"
86 #include "asterisk/dsp.h"
87 #include "asterisk/indications.h"
88 #include "asterisk/ast_version.h"
89 #include "asterisk/translate.h"
90 #include "asterisk/stasis.h"
91 #include "asterisk/stasis_channels.h"
94 <application name="ReceiveFAX" language="en_US" module="res_fax">
96 Receive a FAX and save as a TIFF/F file.
99 <parameter name="filename" required="true" />
100 <parameter name="options">
103 <para>Enable FAX debugging.</para>
106 <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
109 <para>Force usage of audio mode on T.38 capable channels.</para>
112 <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
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>
123 <ref type="function">FAXOPT</ref>
126 <application name="SendFAX" language="en_US" module="res_fax">
128 Sends a specified TIFF/F file as a FAX.
131 <parameter name="filename" required="true" argsep="&">
132 <argument name="filename2" multiple="true">
133 <para>TIFF file to send as a FAX.</para>
136 <parameter name="options">
139 <para>Enable FAX debugging.</para>
142 <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
145 <para>Force usage of audio mode on T.38 capable channels.</para>
148 <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
151 <para>Initiate a T.38 reinvite on the channel if the remote end does not.</para>
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>
162 <ref type="function">FAXOPT</ref>
165 <function name="FAXOPT" language="en_US" module="res_fax">
167 Gets/sets various pieces of information about a fax session.
170 <parameter name="item" required="true">
173 <para>R/W Error Correction Mode (ECM) enable with 'yes', disable with 'no'.</para>
176 <para>R/O FAX transmission error code upon failure.</para>
178 <enum name="filename">
179 <para>R/O Filename of the first file of the FAX transmission.</para>
181 <enum name="filenames">
182 <para>R/O Filenames of all of the files in the FAX transmission (comma separated).</para>
184 <enum name="headerinfo">
185 <para>R/W FAX header information.</para>
187 <enum name="localstationid">
188 <para>R/W Local Station Identification.</para>
190 <enum name="minrate">
191 <para>R/W Minimum transfer rate set before transmission.</para>
193 <enum name="maxrate">
194 <para>R/W Maximum transfer rate set before transmission.</para>
197 <para>R/W Modem type (v17/v27/v29).</para>
199 <enum name="gateway">
200 <para>R/W T38 fax gateway, with optional fax activity timeout in seconds (yes[,timeout]/no)</para>
202 <enum name="faxdetect">
203 <para>R/W Enable FAX detect with optional timeout in seconds (yes,t38,cng[,timeout]/no)</para>
206 <para>R/O Number of pages transferred.</para>
209 <para>R/O Negotiated transmission rate.</para>
211 <enum name="remotestationid">
212 <para>R/O Remote Station Identification after transmission.</para>
214 <enum name="resolution">
215 <para>R/O Negotiated image resolution after transmission.</para>
217 <enum name="sessionid">
218 <para>R/O Session ID of the FAX transmission.</para>
221 <para>R/O Result Status of the FAX transmission.</para>
223 <enum name="statusstr">
224 <para>R/O Verbose Result Status of the FAX transmission.</para>
230 <para>FAXOPT can be used to override the settings for a FAX session listed in <filename>res_fax.conf</filename>,
231 it can also be used to retreive information about a FAX session that has finished eg. pages/status.</para>
234 <ref type="application">ReceiveFax</ref>
235 <ref type="application">SendFax</ref>
240 static const char app_receivefax[] = "ReceiveFAX";
241 static const char app_sendfax[] = "SendFAX";
243 struct debug_info_history {
244 unsigned int consec_frames;
245 unsigned int consec_ms;
246 unsigned char silence;
249 struct ast_fax_debug_info {
250 struct timeval base_tv;
251 struct debug_info_history c2s, s2c;
255 /*! \brief used for gateway framehook */
257 /*! \brief FAX Session */
258 struct ast_fax_session *s;
259 struct ast_fax_session *peer_v21_session;
260 struct ast_fax_session *chan_v21_session;
261 /*! \brief reserved fax session token */
262 struct ast_fax_tech_token *token;
263 /*! \brief the start of our timeout counter */
264 struct timeval timeout_start;
265 /*! \brief framehook used in gateway mode */
267 /*! \brief bridged */
269 /*! \brief 1 if a v21 preamble has been detected */
271 /*! \brief a flag to track the state of our negotiation */
272 enum ast_t38_state t38_state;
273 /*! \brief original audio formats */
274 struct ast_format chan_read_format;
275 struct ast_format chan_write_format;
276 struct ast_format peer_read_format;
277 struct ast_format peer_write_format;
280 /*! \brief used for fax detect framehook */
282 /*! \brief the start of our timeout counter */
283 struct timeval timeout_start;
284 /*! \brief faxdetect timeout */
286 /*! \brief DSP Processor */
288 /*! \brief original audio formats */
289 struct ast_format orig_format;
290 /*! \brief fax session details */
291 struct ast_fax_session_details *details;
296 /*! \brief FAX Detect flags */
297 #define FAX_DETECT_MODE_CNG (1 << 0)
298 #define FAX_DETECT_MODE_T38 (1 << 1)
299 #define FAX_DETECT_MODE_BOTH (FAX_DETECT_MODE_CNG | FAX_DETECT_MODE_T38)
301 static int fax_logger_level = -1;
303 /*! \brief maximum buckets for res_fax ao2 containers */
304 #define FAX_MAXBUCKETS 10
306 #define RES_FAX_TIMEOUT 10000
307 #define FAX_GATEWAY_TIMEOUT RES_FAX_TIMEOUT
309 /*! \brief The faxregistry is used to manage information and statistics for all FAX sessions. */
311 /*! The number of active FAX sessions */
313 /*! The number of reserved FAX sessions */
314 int reserved_sessions;
315 /*! active sessions are astobj2 objects */
316 struct ao2_container *container;
317 /*! Total number of Tx FAX attempts */
319 /*! Total number of Rx FAX attempts */
321 /*! Number of successful FAX transmissions */
323 /*! Number of failed FAX transmissions */
325 /*! the next unique session name */
329 /*! \brief registered FAX technology modules are put into this list */
331 const struct ast_fax_tech *tech;
332 AST_RWLIST_ENTRY(fax_module) list;
334 static AST_RWLIST_HEAD_STATIC(faxmodules, fax_module);
336 #define RES_FAX_MINRATE 2400
337 #define RES_FAX_MAXRATE 14400
338 #define RES_FAX_STATUSEVENTS 0
339 #define RES_FAX_MODEM (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29)
342 enum ast_fax_modems modems;
343 uint32_t statusevents:1;
345 unsigned int minrate;
346 unsigned int maxrate;
349 static struct fax_options general_options;
351 static const struct fax_options default_options = {
352 .minrate = RES_FAX_MINRATE,
353 .maxrate = RES_FAX_MAXRATE,
354 .statusevents = RES_FAX_STATUSEVENTS,
355 .modems = RES_FAX_MODEM,
356 .ecm = AST_FAX_OPTFLAG_TRUE,
359 AST_RWLOCK_DEFINE_STATIC(options_lock);
361 static void get_general_options(struct fax_options* options);
362 static void set_general_options(const struct fax_options* options);
364 static const char *config = "res_fax.conf";
366 static int global_fax_debug = 0;
369 OPT_CALLEDMODE = (1 << 0),
370 OPT_CALLERMODE = (1 << 1),
371 OPT_DEBUG = (1 << 2),
372 OPT_STATUS = (1 << 3),
373 OPT_ALLOWAUDIO = (1 << 5),
374 OPT_REQUEST_T38 = (1 << 6),
375 OPT_FORCE_AUDIO = (1 << 7),
378 AST_APP_OPTIONS(fax_exec_options, BEGIN_OPTIONS
379 AST_APP_OPTION('a', OPT_CALLEDMODE),
380 AST_APP_OPTION('c', OPT_CALLERMODE),
381 AST_APP_OPTION('d', OPT_DEBUG),
382 AST_APP_OPTION('f', OPT_ALLOWAUDIO),
383 AST_APP_OPTION('F', OPT_FORCE_AUDIO),
384 AST_APP_OPTION('s', OPT_STATUS),
385 AST_APP_OPTION('z', OPT_REQUEST_T38),
388 static void debug_check_frame_for_silence(struct ast_fax_session *s, unsigned int c2s, struct ast_frame *frame)
390 struct debug_info_history *history = c2s ? &s->debug_info->c2s : &s->debug_info->s2c;
392 unsigned int last_consec_frames, last_consec_ms;
393 unsigned char wassil;
396 diff = ast_tvsub(ast_tvnow(), s->debug_info->base_tv);
398 ast_dsp_reset(s->debug_info->dsp);
399 ast_dsp_silence(s->debug_info->dsp, frame, &dspsilence);
401 wassil = history->silence;
402 history->silence = (dspsilence != 0) ? 1 : 0;
403 if (history->silence != wassil) {
404 last_consec_frames = history->consec_frames;
405 last_consec_ms = history->consec_ms;
406 history->consec_frames = 0;
407 history->consec_ms = 0;
409 if ((last_consec_frames != 0)) {
410 ast_verb(6, "Channel '%s' fax session '%d', [ %.3ld.%.6ld ], %s sent %d frames (%d ms) of %s.\n",
411 s->channame, s->id, (long) diff.tv_sec, (long int) diff.tv_usec,
412 (c2s) ? "channel" : "stack", last_consec_frames, last_consec_ms,
413 (wassil) ? "silence" : "energy");
417 history->consec_frames++;
418 history->consec_ms += (frame->samples / 8);
421 static void destroy_callback(void *data)
428 static const struct ast_datastore_info fax_datastore = {
430 .destroy = destroy_callback,
433 /*! \brief returns a reference counted pointer to a fax datastore, if it exists */
434 static struct ast_fax_session_details *find_details(struct ast_channel *chan)
436 struct ast_fax_session_details *details;
437 struct ast_datastore *datastore;
439 ast_channel_lock(chan);
440 if (!(datastore = ast_channel_datastore_find(chan, &fax_datastore, NULL))) {
441 ast_channel_unlock(chan);
444 if (!(details = datastore->data)) {
445 ast_log(LOG_WARNING, "Huh? channel '%s' has a FAX datastore without data!\n", ast_channel_name(chan));
446 ast_channel_unlock(chan);
450 ast_channel_unlock(chan);
455 /*! \brief destroy a FAX session details structure */
456 static void destroy_session_details(void *details)
458 struct ast_fax_session_details *d = details;
459 struct ast_fax_document *doc;
461 while ((doc = AST_LIST_REMOVE_HEAD(&d->documents, next))) {
464 ast_string_field_free_memory(d);
467 /*! \brief create a FAX session details structure */
468 static struct ast_fax_session_details *session_details_new(void)
470 struct ast_fax_session_details *d;
471 struct fax_options options;
473 if (!(d = ao2_alloc(sizeof(*d), destroy_session_details))) {
477 if (ast_string_field_init(d, 512)) {
482 get_general_options(&options);
484 AST_LIST_HEAD_INIT_NOLOCK(&d->documents);
486 /* These options need to be set to the configured default and may be overridden by
487 * SendFAX, ReceiveFAX, or FAXOPT */
488 d->option.request_t38 = AST_FAX_OPTFLAG_FALSE;
489 d->option.send_cng = AST_FAX_OPTFLAG_FALSE;
490 d->option.send_ced = AST_FAX_OPTFLAG_FALSE;
491 d->option.ecm = options.ecm;
492 d->option.statusevents = options.statusevents;
493 d->modems = options.modems;
494 d->minrate = options.minrate;
495 d->maxrate = options.maxrate;
497 d->faxdetect_id = -1;
498 d->gateway_timeout = 0;
503 static struct ast_control_t38_parameters our_t38_parameters = {
506 .rate = AST_T38_RATE_14400,
507 .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
510 static void t38_parameters_ast_to_fax(struct ast_fax_t38_parameters *dst, const struct ast_control_t38_parameters *src)
512 dst->version = src->version;
513 dst->max_ifp = src->max_ifp;
514 dst->rate = src->rate;
515 dst->rate_management = src->rate_management;
516 dst->fill_bit_removal = src->fill_bit_removal;
517 dst->transcoding_mmr = src->transcoding_mmr;
518 dst->transcoding_jbig = src->transcoding_jbig;
521 static void t38_parameters_fax_to_ast(struct ast_control_t38_parameters *dst, const struct ast_fax_t38_parameters *src)
523 dst->version = src->version;
524 dst->max_ifp = src->max_ifp;
525 dst->rate = src->rate;
526 dst->rate_management = src->rate_management;
527 dst->fill_bit_removal = src->fill_bit_removal;
528 dst->transcoding_mmr = src->transcoding_mmr;
529 dst->transcoding_jbig = src->transcoding_jbig;
532 /*! \brief returns a reference counted details structure from the channel's fax datastore. If the datastore
533 * does not exist it will be created */
534 static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan)
536 struct ast_fax_session_details *details;
537 struct ast_datastore *datastore;
539 if ((details = find_details(chan))) {
542 /* channel does not have one so we must create one */
543 if (!(details = session_details_new())) {
544 ast_log(LOG_WARNING, "channel '%s' can't get a FAX details structure for the datastore!\n", ast_channel_name(chan));
547 if (!(datastore = ast_datastore_alloc(&fax_datastore, NULL))) {
548 ao2_ref(details, -1);
549 ast_log(LOG_WARNING, "channel '%s' can't get a datastore!\n", ast_channel_name(chan));
552 /* add the datastore to the channel and increment the refcount */
553 datastore->data = details;
555 /* initialize default T.38 parameters */
556 t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
557 t38_parameters_ast_to_fax(&details->their_t38_parameters, &our_t38_parameters);
560 ast_channel_lock(chan);
561 ast_channel_datastore_add(chan, datastore);
562 ast_channel_unlock(chan);
566 unsigned int ast_fax_maxrate(void)
568 struct fax_options options;
569 get_general_options(&options);
571 return options.maxrate;
574 unsigned int ast_fax_minrate(void)
576 struct fax_options options;
577 get_general_options(&options);
579 return options.minrate;
582 static int update_modem_bits(enum ast_fax_modems *bits, const char *value)
584 char *m[5], *tok, *v = (char *)value;
587 if (!strchr(v, ',')) {
591 tok = strtok(v, ", ");
592 while (tok && (i < 5)) {
594 tok = strtok(NULL, ", ");
600 for (j = 0; j < i; j++) {
601 if (!strcasecmp(m[j], "v17")) {
602 *bits |= AST_FAX_MODEM_V17;
603 } else if (!strcasecmp(m[j], "v27")) {
604 *bits |= AST_FAX_MODEM_V27;
605 } else if (!strcasecmp(m[j], "v29")) {
606 *bits |= AST_FAX_MODEM_V29;
607 } else if (!strcasecmp(m[j], "v34")) {
608 *bits |= AST_FAX_MODEM_V34;
610 ast_log(LOG_WARNING, "ignoring invalid modem setting: '%s', valid options {v17 | v27 | v29 | v34}\n", m[j]);
615 static char *ast_fax_caps_to_str(enum ast_fax_capabilities caps, char *buf, size_t bufsize)
618 size_t size = bufsize;
621 if (caps & AST_FAX_TECH_SEND) {
623 ast_build_string(&buf, &size, ",");
625 ast_build_string(&buf, &size, "SEND");
628 if (caps & AST_FAX_TECH_RECEIVE) {
630 ast_build_string(&buf, &size, ",");
632 ast_build_string(&buf, &size, "RECEIVE");
635 if (caps & AST_FAX_TECH_AUDIO) {
637 ast_build_string(&buf, &size, ",");
639 ast_build_string(&buf, &size, "AUDIO");
642 if (caps & AST_FAX_TECH_T38) {
644 ast_build_string(&buf, &size, ",");
646 ast_build_string(&buf, &size, "T38");
649 if (caps & AST_FAX_TECH_MULTI_DOC) {
651 ast_build_string(&buf, &size, ",");
653 ast_build_string(&buf, &size, "MULTI_DOC");
656 if (caps & AST_FAX_TECH_GATEWAY) {
658 ast_build_string(&buf, &size, ",");
660 ast_build_string(&buf, &size, "GATEWAY");
663 if (caps & AST_FAX_TECH_V21_DETECT) {
665 ast_build_string(&buf, &size, ",");
667 ast_build_string(&buf, &size, "V21");
674 static int ast_fax_modem_to_str(enum ast_fax_modems bits, char *tbuf, size_t bufsize)
678 if (bits & AST_FAX_MODEM_V17) {
682 if (bits & AST_FAX_MODEM_V27) {
689 if (bits & AST_FAX_MODEM_V29) {
696 if (bits & AST_FAX_MODEM_V34) {
707 static int check_modem_rate(enum ast_fax_modems modems, unsigned int rate)
711 if (!(modems & (AST_FAX_MODEM_V27 | AST_FAX_MODEM_V34))) {
716 if (!(modems & (AST_FAX_MODEM_V27 | AST_FAX_MODEM_V34))) {
722 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
728 if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V34))) {
734 if (!(modems & AST_FAX_MODEM_V34)) {
739 /* this should never happen */
746 /*! \brief register a FAX technology module */
747 int ast_fax_tech_register(struct ast_fax_tech *tech)
749 struct fax_module *fax;
751 if (!(fax = ast_calloc(1, sizeof(*fax)))) {
755 AST_RWLIST_WRLOCK(&faxmodules);
756 AST_RWLIST_INSERT_TAIL(&faxmodules, fax, list);
757 AST_RWLIST_UNLOCK(&faxmodules);
758 ast_module_ref(ast_module_info->self);
760 ast_verb(3, "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
765 /*! \brief unregister a FAX technology module */
766 void ast_fax_tech_unregister(struct ast_fax_tech *tech)
768 struct fax_module *fax;
770 ast_verb(3, "Unregistering FAX module type '%s'\n", tech->type);
772 AST_RWLIST_WRLOCK(&faxmodules);
773 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
774 if (fax->tech != tech) {
777 AST_RWLIST_REMOVE_CURRENT(list);
778 ast_module_unref(ast_module_info->self);
780 ast_verb(4, "Unregistered FAX module type '%s'\n", tech->type);
783 AST_RWLIST_TRAVERSE_SAFE_END;
784 AST_RWLIST_UNLOCK(&faxmodules);
787 /*! \brief convert a ast_fax_state to a string */
788 const char *ast_fax_state_to_str(enum ast_fax_state state)
791 case AST_FAX_STATE_UNINITIALIZED:
792 return "Uninitialized";
793 case AST_FAX_STATE_INITIALIZED:
794 return "Initialized";
795 case AST_FAX_STATE_OPEN:
797 case AST_FAX_STATE_ACTIVE:
799 case AST_FAX_STATE_COMPLETE:
801 case AST_FAX_STATE_RESERVED:
803 case AST_FAX_STATE_INACTIVE:
806 ast_log(LOG_WARNING, "unhandled FAX state: %d\n", state);
811 void ast_fax_log(int level, const char *file, const int line, const char *function, const char *msg)
813 if (fax_logger_level != -1) {
814 ast_log_dynamic_level(fax_logger_level, "%s", msg);
816 ast_log(level, file, line, function, "%s", msg);
820 /*! \brief convert a rate string to a rate */
821 static unsigned int fax_rate_str_to_int(const char *ratestr)
825 if (sscanf(ratestr, "%d", &rate) != 1) {
826 ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
840 ast_log(LOG_WARNING, "ignoring invalid rate '%s'. Valid options are {2400 | 4800 | 7200 | 9600 | 12000 | 14400 | 28800 | 33600}\n", ratestr);
845 /*! \brief Release a session token.
846 * \param s a session returned from fax_session_reserve()
847 * \param token a token generated from fax_session_reserve()
849 * This function releases the given token and marks the given session as no
850 * longer reserved. It is safe to call on a session that is not actually
851 * reserved and with a NULL token. This is so that sessions returned by
852 * technologies that do not support reserved sessions don't require extra logic
855 * \note This function DOES NOT release the given fax session, only the given
858 static void fax_session_release(struct ast_fax_session *s, struct ast_fax_tech_token *token)
861 s->tech->release_token(token);
864 if (s->state == AST_FAX_STATE_RESERVED) {
865 ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
866 s->state = AST_FAX_STATE_INACTIVE;
870 /*! \brief destroy a FAX session structure */
871 static void destroy_session(void *session)
873 struct ast_fax_session *s = session;
876 fax_session_release(s, NULL);
878 s->tech->destroy_session(s);
880 ast_module_unref(s->tech->module);
884 if (s->details->caps & AST_FAX_TECH_GATEWAY) {
885 s->details->caps &= ~AST_FAX_TECH_GATEWAY;
887 ao2_ref(s->details, -1);
891 ast_dsp_free(s->debug_info->dsp);
892 ast_free(s->debug_info);
896 ast_smoother_free(s->smoother);
899 if (s->state != AST_FAX_STATE_INACTIVE) {
900 ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
903 ast_free(s->channame);
904 ast_free(s->chan_uniqueid);
907 /*! \brief Reserve a fax session.
908 * \param details the fax session details
909 * \param token a pointer to a place to store a token to be passed to fax_session_new() later
911 * This function reserves a fax session for use later. If the selected fax
912 * technology does not support reserving sessions a session will still be
913 * returned but token will not be set.
915 * \note The reference returned by this function does not get consumed by
916 * fax_session_new() and must always be dereferenced separately.
918 * \return NULL or an uninitialized and possibly reserved session
920 static struct ast_fax_session *fax_session_reserve(struct ast_fax_session_details *details, struct ast_fax_tech_token **token)
922 struct ast_fax_session *s;
923 struct fax_module *faxmod;
925 if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
929 s->state = AST_FAX_STATE_INACTIVE;
930 s->details = details;
931 ao2_ref(s->details, 1);
933 /* locate a FAX technology module that can handle said requirements
934 * Note: the requirements have not yet been finalized as T.38
935 * negotiation has not yet occured. */
936 AST_RWLIST_RDLOCK(&faxmodules);
937 AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
938 if ((faxmod->tech->caps & details->caps) != details->caps) {
941 ast_debug(4, "Reserving a FAX session from '%s'.\n", faxmod->tech->description);
942 ast_module_ref(faxmod->tech->module);
943 s->tech = faxmod->tech;
946 AST_RWLIST_UNLOCK(&faxmodules);
950 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)));
955 if (!s->tech->reserve_session) {
956 ast_debug(1, "Selected FAX technology module (%s) does not support reserving sessions.\n", s->tech->description);
960 if (!(*token = s->tech->reserve_session(s))) {
965 s->state = AST_FAX_STATE_RESERVED;
966 ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, 1);
971 /*! \brief create a FAX session
973 * \param details details for the session
974 * \param chan the channel the session will run on
975 * \param reserved a reserved session to base this session on (can be NULL)
976 * \param token the token for a reserved session (can be NULL)
978 * Create a new fax session based on the given details structure.
980 * \note The given token is always consumed (by tech->new_session() or by
981 * fax_session_release() in the event of a failure). The given reference to a
982 * reserved session is never consumed and must be dereferenced separately from
983 * the reference returned by this function.
985 * \return NULL or a reference to a new fax session
987 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)
989 struct ast_fax_session *s = NULL;
990 struct fax_module *faxmod;
994 ao2_ref(reserved, +1);
996 /* NOTE: we don't consume the reference to the reserved
997 * session. The session returned from fax_session_new() is a
998 * new reference and must be derefed in addition to the
1002 if (s->state == AST_FAX_STATE_RESERVED) {
1003 ast_atomic_fetchadd_int(&faxregistry.reserved_sessions, -1);
1004 s->state = AST_FAX_STATE_UNINITIALIZED;
1008 if (!s && !(s = ao2_alloc(sizeof(*s), destroy_session))) {
1012 ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
1013 s->state = AST_FAX_STATE_UNINITIALIZED;
1015 if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
1016 if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
1017 fax_session_release(s, token);
1021 if (!(s->debug_info->dsp = ast_dsp_new())) {
1022 ast_free(s->debug_info);
1023 s->debug_info = NULL;
1024 fax_session_release(s, token);
1028 ast_dsp_set_threshold(s->debug_info->dsp, 128);
1031 if (!(s->channame = ast_strdup(ast_channel_name(chan)))) {
1032 fax_session_release(s, token);
1037 if (!(s->chan_uniqueid = ast_strdup(ast_channel_uniqueid(chan)))) {
1038 fax_session_release(s, token);
1045 s->details = details;
1046 ao2_ref(s->details, 1);
1049 details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
1052 /* locate a FAX technology module that can handle said requirements */
1053 AST_RWLIST_RDLOCK(&faxmodules);
1054 AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
1055 if ((faxmod->tech->caps & details->caps) != details->caps) {
1058 ast_debug(4, "Requesting a new FAX session from '%s'.\n", faxmod->tech->description);
1059 ast_module_ref(faxmod->tech->module);
1060 s->tech = faxmod->tech;
1063 AST_RWLIST_UNLOCK(&faxmodules);
1066 char caps[128] = "";
1067 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)));
1073 if (!(s->tech_pvt = s->tech->new_session(s, token))) {
1074 ast_log(LOG_ERROR, "FAX session failed to initialize.\n");
1078 /* link the session to the session container */
1079 if (!(ao2_link(faxregistry.container, s))) {
1080 ast_log(LOG_ERROR, "failed to add FAX session '%d' to container.\n", s->id);
1084 ast_debug(4, "channel '%s' using FAX session '%d'\n", s->channame, s->id);
1091 * \brief Convert the filenames in a fax session into a JSON array
1092 * \retval NULL on error
1093 * \retval A \ref ast_json array on success
1095 static struct ast_json *generate_filenames_json(struct ast_fax_session_details *details)
1097 RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
1098 struct ast_fax_document *doc;
1100 if (!details || !json_array) {
1104 /* don't process empty lists */
1105 if (AST_LIST_EMPTY(&details->documents)) {
1109 AST_LIST_TRAVERSE(&details->documents, doc, next) {
1110 struct ast_json *entry = ast_json_string_create(doc->filename);
1114 if (ast_json_array_append(json_array, entry)) {
1119 ast_json_ref(json_array);
1123 /* \brief Generate a string of filenames using the given prefix and separator.
1124 * \param details the fax session details
1125 * \param prefix the prefix to each filename
1126 * \param separator the separator between filenames
1128 * This function generates a string of filenames from the given details
1129 * structure and using the given prefix and separator.
1131 * \retval NULL there was an error generating the string
1132 * \return the string generated string
1134 static char *generate_filenames_string(struct ast_fax_session_details *details, char *prefix, char *separator)
1136 char *filenames, *c;
1139 struct ast_fax_document *doc;
1141 /* don't process empty lists */
1142 if (AST_LIST_EMPTY(&details->documents)) {
1146 /* Calculate the total length of all of the file names */
1147 AST_LIST_TRAVERSE(&details->documents, doc, next) {
1148 size += strlen(separator) + strlen(prefix) + strlen(doc->filename);
1150 size += 1; /* add space for the terminating null */
1152 if (!(filenames = ast_malloc(size))) {
1157 ast_build_string(&c, &size, "%s%s", prefix, AST_LIST_FIRST(&details->documents)->filename);
1158 AST_LIST_TRAVERSE(&details->documents, doc, next) {
1164 ast_build_string(&c, &size, "%s%s%s", separator, prefix, doc->filename);
1170 /*! \brief send a FAX status manager event */
1171 static int report_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details, const char *status)
1173 RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
1174 RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1175 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1176 struct ast_json *json_filenames = NULL;
1178 if (!details->option.statusevents) {
1182 json_filenames = generate_filenames_json(details);
1183 if (!json_filenames) {
1187 json_object = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: o}",
1189 "operation", (details->caps & AST_FAX_TECH_GATEWAY) ? "gateway" : (details->caps & AST_FAX_TECH_RECEIVE) ? "receive" : "send",
1191 "local_station_id", details->localstationid,
1192 "filenames", json_filenames);
1198 SCOPED_CHANNELLOCK(lock, chan);
1200 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
1204 stasis_publish(ast_channel_topic(chan), message);
1209 /*! \brief Set fax related channel variables. */
1210 static void set_channel_variables(struct ast_channel *chan, struct ast_fax_session_details *details)
1213 pbx_builtin_setvar_helper(chan, "FAXSTATUS", S_OR(details->result, NULL));
1214 pbx_builtin_setvar_helper(chan, "FAXERROR", S_OR(details->error, NULL));
1215 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", S_OR(details->resultstr, NULL));
1216 pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", S_OR(details->remotestationid, NULL));
1217 pbx_builtin_setvar_helper(chan, "LOCALSTATIONID", S_OR(details->localstationid, NULL));
1218 pbx_builtin_setvar_helper(chan, "FAXBITRATE", S_OR(details->transfer_rate, NULL));
1219 pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", S_OR(details->resolution, NULL));
1221 snprintf(buf, sizeof(buf), "%d", details->pages_transferred);
1222 pbx_builtin_setvar_helper(chan, "FAXPAGES", buf);
1225 #define GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason) \
1227 if (ast_strlen_zero(fax->details->result)) \
1228 ast_string_field_set(fax->details, result, "FAILED"); \
1229 if (ast_strlen_zero(fax->details->resultstr)) \
1230 ast_string_field_set(fax->details, resultstr, reason); \
1231 if (ast_strlen_zero(fax->details->error)) \
1232 ast_string_field_set(fax->details, error, errorstr); \
1233 set_channel_variables(chan, fax->details); \
1236 #define GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason) \
1238 GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason); \
1241 #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason) \
1243 ast_log(LOG_ERROR, "channel '%s' FAX session '%d' failure, reason: '%s' (%s)\n", ast_channel_name(chan), fax->id, reason, errorstr); \
1244 GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason); \
1247 static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
1249 switch (ast_channel_get_t38_state(chan)) {
1250 case T38_STATE_UNKNOWN:
1251 details->caps |= AST_FAX_TECH_T38;
1253 case T38_STATE_REJECTED:
1254 case T38_STATE_UNAVAILABLE:
1255 details->caps |= AST_FAX_TECH_AUDIO;
1257 case T38_STATE_NEGOTIATED:
1258 /* already in T.38 mode? This should not happen. */
1259 case T38_STATE_NEGOTIATING: {
1260 /* the other end already sent us a T.38 reinvite, so we need to prod the channel
1261 * driver into resending their parameters to us if it supports doing so... if
1262 * not, we can't proceed, because we can't create a proper reply without them.
1263 * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
1264 * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
1265 * that gets called after this one completes
1267 struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
1268 if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
1269 ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1272 details->caps |= AST_FAX_TECH_T38;
1276 ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", ast_channel_name(chan));
1283 static int disable_t38(struct ast_channel *chan)
1286 struct ast_frame *frame = NULL;
1287 struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
1288 struct timeval start;
1291 ast_debug(1, "Shutting down T.38 on %s\n", ast_channel_name(chan));
1292 if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
1293 ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1297 /* wait up to five seconds for negotiation to complete */
1299 start = ast_tvnow();
1300 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1301 ms = ast_waitfor(chan, ms);
1307 ast_debug(1, "error while disabling T.38 on channel '%s'\n", ast_channel_name(chan));
1311 if (!(frame = ast_read(chan))) {
1314 if ((frame->frametype == AST_FRAME_CONTROL) &&
1315 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1316 (frame->datalen == sizeof(t38_parameters))) {
1317 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1319 switch (parameters->request_response) {
1320 case AST_T38_TERMINATED:
1321 ast_debug(1, "Shut down T.38 on %s\n", ast_channel_name(chan));
1323 case AST_T38_REFUSED:
1324 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", ast_channel_name(chan));
1328 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", ast_channel_name(chan));
1338 if (ms == 0) { /* all done, nothing happened */
1339 ast_debug(1, "channel '%s' timed-out during T.38 shutdown\n", ast_channel_name(chan));
1345 /*! \brief this is the generic FAX session handling function */
1346 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)
1349 int timeout = RES_FAX_TIMEOUT;
1351 unsigned int expected_frametype = -1;
1352 union ast_frame_subclass expected_framesubclass = { .integer = -1 };
1353 unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
1354 struct ast_control_t38_parameters t38_parameters;
1355 const char *tempvar;
1356 struct ast_fax_session *fax = NULL;
1357 struct ast_frame *frame = NULL;
1358 struct ast_channel *c = chan;
1359 struct ast_format orig_write_format;
1360 struct ast_format orig_read_format;
1362 struct timeval start;
1364 ast_format_clear(&orig_write_format);
1365 ast_format_clear(&orig_read_format);
1368 /* create the FAX session */
1369 if (!(fax = fax_session_new(details, chan, reserved, token))) {
1370 ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
1371 report_fax_status(chan, details, "No Available Resource");
1375 ast_channel_lock(chan);
1376 /* update session details */
1377 if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
1378 ast_string_field_set(details, headerinfo, tempvar);
1380 if (ast_strlen_zero(details->localstationid)) {
1381 tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
1382 ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
1384 ast_channel_unlock(chan);
1386 report_fax_status(chan, details, "Allocating Resources");
1388 if (details->caps & AST_FAX_TECH_AUDIO) {
1389 expected_frametype = AST_FRAME_VOICE;;
1390 ast_format_set(&expected_framesubclass.format, AST_FORMAT_SLINEAR, 0);
1391 ast_format_copy(&orig_write_format, ast_channel_writeformat(chan));
1392 if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1393 ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", ast_channel_name(chan));
1394 ao2_lock(faxregistry.container);
1395 ao2_unlink(faxregistry.container, fax);
1396 ao2_unlock(faxregistry.container);
1398 ast_channel_unlock(chan);
1401 ast_format_copy(&orig_read_format, ast_channel_readformat(chan));
1402 if (ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR) < 0) {
1403 ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", ast_channel_name(chan));
1404 ao2_lock(faxregistry.container);
1405 ao2_unlink(faxregistry.container, fax);
1406 ao2_unlock(faxregistry.container);
1408 ast_channel_unlock(chan);
1411 if (fax->smoother) {
1412 ast_smoother_free(fax->smoother);
1413 fax->smoother = NULL;
1415 if (!(fax->smoother = ast_smoother_new(320))) {
1416 ast_log(LOG_WARNING, "Channel '%s' FAX session '%d' failed to obtain a smoother.\n", ast_channel_name(chan), fax->id);
1419 expected_frametype = AST_FRAME_MODEM;
1420 expected_framesubclass.integer = AST_MODEM_T38;
1423 if (fax->debug_info) {
1424 fax->debug_info->base_tv = ast_tvnow();
1427 /* reset our result fields just in case the fax tech driver wants to
1428 * set custom error messages */
1429 ast_string_field_set(details, result, "");
1430 ast_string_field_set(details, resultstr, "");
1431 ast_string_field_set(details, error, "");
1432 set_channel_variables(chan, details);
1434 if (fax->tech->start_session(fax) < 0) {
1435 GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
1438 report_fax_status(chan, details, "FAX Transmission In Progress");
1440 ast_debug(5, "channel %s will wait on FAX fd %d\n", ast_channel_name(chan), fax->fd);
1442 /* handle frames for the session */
1443 remaining_time = timeout;
1444 start = ast_tvnow();
1445 while (remaining_time > 0) {
1446 struct ast_channel *ready_chan;
1451 ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
1453 if (!(frame = ast_read(chan))) {
1454 /* the channel is probably gone, so lets stop polling on it and let the
1455 * FAX session complete before we exit the application. if needed,
1456 * send the FAX stack silence so the modems can finish their session without
1458 ast_debug(1, "Channel '%s' did not return a frame; probably hung up.\n", ast_channel_name(chan));
1459 GENERIC_FAX_EXEC_SET_VARS(fax, chan, "HANGUP", "remote channel hungup");
1462 remaining_time = ast_remaining_ms(start, timeout);
1463 fax->tech->cancel_session(fax);
1464 if (fax->tech->generate_silence) {
1465 fax->tech->generate_silence(fax);
1470 if ((frame->frametype == AST_FRAME_CONTROL) &&
1471 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1472 (frame->datalen == sizeof(t38_parameters))) {
1473 unsigned int was_t38 = t38negotiated;
1474 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1476 switch (parameters->request_response) {
1477 case AST_T38_REQUEST_NEGOTIATE:
1478 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1481 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1482 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1483 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1485 case AST_T38_NEGOTIATED:
1486 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1492 if (t38negotiated && !was_t38) {
1493 fax->tech->switch_to_t38(fax);
1494 details->caps &= ~AST_FAX_TECH_AUDIO;
1495 expected_frametype = AST_FRAME_MODEM;
1496 expected_framesubclass.integer = AST_MODEM_T38;
1497 if (fax->smoother) {
1498 ast_smoother_free(fax->smoother);
1499 fax->smoother = NULL;
1502 report_fax_status(chan, details, "T.38 Negotiated");
1504 ast_verb(3, "Channel '%s' switched to T.38 FAX session '%d'.\n", ast_channel_name(chan), fax->id);
1506 } else if ((frame->frametype == expected_frametype) &&
1507 (!memcmp(&frame->subclass, &expected_framesubclass, sizeof(frame->subclass)))) {
1508 struct ast_frame *f;
1510 if (fax->smoother) {
1511 /* push the frame into a smoother */
1512 if (ast_smoother_feed(fax->smoother, frame) < 0) {
1513 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
1515 while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
1516 if (fax->debug_info) {
1517 debug_check_frame_for_silence(fax, 1, f);
1519 /* write the frame to the FAX stack */
1520 fax->tech->write(fax, f);
1521 fax->frames_received++;
1527 /* write the frame to the FAX stack */
1528 fax->tech->write(fax, frame);
1529 fax->frames_received++;
1531 start = ast_tvnow();
1534 } else if (ofd == fax->fd) {
1535 /* read a frame from the FAX stack and send it out the channel.
1536 * the FAX stack will return a NULL if the FAX session has already completed */
1537 if (!(frame = fax->tech->read(fax))) {
1541 if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
1542 debug_check_frame_for_silence(fax, 0, frame);
1545 ast_write(chan, frame);
1548 start = ast_tvnow();
1550 if (ms && (ofd < 0)) {
1551 if ((errno == 0) || (errno == EINTR)) {
1552 remaining_time = ast_remaining_ms(start, timeout);
1553 if (remaining_time <= 0)
1554 GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1557 ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(chan));
1558 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "error polling data");
1562 /* nothing happened */
1563 remaining_time = ast_remaining_ms(start, timeout);
1564 if (remaining_time <= 0) {
1565 GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1571 ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, remaining_time: %d }\n", ast_channel_name(chan), timeout, remaining_time);
1573 set_channel_variables(chan, details);
1575 ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
1576 if (!strcasecmp(details->result, "FAILED")) {
1577 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1581 ao2_lock(faxregistry.container);
1582 ao2_unlink(faxregistry.container, fax);
1583 ao2_unlock(faxregistry.container);
1587 /* if the channel is still alive, and we changed its read/write formats,
1591 if (orig_read_format.id) {
1592 ast_set_read_format(chan, &orig_read_format);
1594 if (orig_write_format.id) {
1595 ast_set_write_format(chan, &orig_write_format);
1599 /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
1603 static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1606 struct ast_frame *frame = NULL;
1607 struct ast_control_t38_parameters t38_parameters;
1608 struct timeval start;
1611 /* don't send any audio if we've already received a T.38 reinvite */
1612 if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1613 /* generate 3 seconds of CED */
1614 if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
1615 ast_log(LOG_ERROR, "error generating CED tone on %s\n", ast_channel_name(chan));
1620 start = ast_tvnow();
1621 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1622 ms = ast_waitfor(chan, ms);
1625 ast_log(LOG_ERROR, "error while generating CED tone on %s\n", ast_channel_name(chan));
1626 ast_playtones_stop(chan);
1630 if (ms == 0) { /* all done, nothing happened */
1634 if (!(frame = ast_read(chan))) {
1635 ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", ast_channel_name(chan));
1636 ast_playtones_stop(chan);
1640 if ((frame->frametype == AST_FRAME_CONTROL) &&
1641 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1642 (frame->datalen == sizeof(t38_parameters))) {
1643 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1645 switch (parameters->request_response) {
1646 case AST_T38_REQUEST_NEGOTIATE:
1647 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1650 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1651 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1652 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1653 ast_playtones_stop(chan);
1655 case AST_T38_NEGOTIATED:
1656 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1657 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1658 details->caps &= ~AST_FAX_TECH_AUDIO;
1659 report_fax_status(chan, details, "T.38 Negotiated");
1668 ast_playtones_stop(chan);
1671 /* if T.38 was negotiated, we are done initializing */
1672 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1677 ast_debug(1, "Negotiating T.38 for receive on %s\n", ast_channel_name(chan));
1679 /* wait up to five seconds for negotiation to complete */
1682 /* set parameters based on the session's parameters */
1683 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1684 t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
1685 if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
1689 start = ast_tvnow();
1690 while ((ms = ast_remaining_ms(start, timeout_ms))) {
1693 ms = ast_waitfor(chan, ms);
1695 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1698 if (ms == 0) { /* all done, nothing happened */
1699 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
1700 details->caps &= ~AST_FAX_TECH_T38;
1704 if (!(frame = ast_read(chan))) {
1705 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
1709 if ((frame->frametype == AST_FRAME_CONTROL) &&
1710 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1711 (frame->datalen == sizeof(t38_parameters))) {
1712 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1714 switch (parameters->request_response) {
1715 case AST_T38_REQUEST_NEGOTIATE:
1716 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1717 t38_parameters.request_response = AST_T38_NEGOTIATED;
1718 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1720 case AST_T38_NEGOTIATED:
1721 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
1722 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1723 details->caps &= ~AST_FAX_TECH_AUDIO;
1724 report_fax_status(chan, details, "T.38 Negotiated");
1727 case AST_T38_REFUSED:
1728 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
1729 details->caps &= ~AST_FAX_TECH_T38;
1733 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
1734 details->caps &= ~AST_FAX_TECH_T38;
1745 /* if T.38 was negotiated, we are done initializing */
1746 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1750 /* if we made it here, then T.38 failed, check the 'f' flag */
1751 if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
1752 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
1756 /* ok, audio fallback is allowed */
1757 details->caps |= AST_FAX_TECH_AUDIO;
1762 /*! \brief Report on the final state of a receive fax operation
1763 * \note This will lock the \ref ast_channel
1765 static int report_receive_fax_status(struct ast_channel *chan, const char *filename)
1767 RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
1768 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1769 RAII_VAR(struct ast_json *, json_array, ast_json_array_create(), ast_json_unref);
1770 struct ast_json *json_filename = ast_json_string_create(filename);
1772 if (!json_array || !json_filename) {
1775 ast_json_array_append(json_array, json_filename);
1778 SCOPED_CHANNELLOCK(lock, chan);
1780 json_object = ast_json_pack("s: s, s: s, s: s, s: s, s: s, s: s, s: s, s: o",
1782 "remote_station_id", S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), ""),
1783 "local_station_id", S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), ""),
1784 "fax_pages", S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), ""),
1785 "fax_resolution", S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), ""),
1786 "fax_bitrate", S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), ""),
1787 "filenames", json_array);
1792 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_object);
1797 stasis_publish(ast_channel_topic(chan), message);
1802 /*! \brief initiate a receive FAX session */
1803 static int receivefax_exec(struct ast_channel *chan, const char *data)
1805 char *parse, modems[128] = "";
1807 RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
1808 RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
1809 struct ast_fax_tech_token *token = NULL;
1810 struct ast_fax_document *doc;
1811 AST_DECLARE_APP_ARGS(args,
1812 AST_APP_ARG(filename);
1813 AST_APP_ARG(options);
1815 struct ast_flags opts = { 0, };
1816 enum ast_t38_state t38state;
1818 /* initialize output channel variables */
1819 pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
1820 pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
1821 pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
1822 pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
1823 pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
1825 /* Get a FAX session details structure from the channel's FAX datastore and create one if
1826 * it does not already exist. */
1827 if (!(details = find_or_create_details(chan))) {
1828 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
1829 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
1830 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1834 ast_string_field_set(details, result, "FAILED");
1835 ast_string_field_set(details, resultstr, "error starting fax session");
1836 ast_string_field_set(details, error, "INIT_ERROR");
1837 set_channel_variables(chan, details);
1839 if (details->gateway_id > 0) {
1840 ast_string_field_set(details, resultstr, "can't receive a fax on a channel with a T.38 gateway");
1841 set_channel_variables(chan, details);
1842 ast_log(LOG_ERROR, "executing ReceiveFAX on a channel with a T.38 Gateway is not supported\n");
1846 if (details->maxrate < details->minrate) {
1847 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1848 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
1849 set_channel_variables(chan, details);
1850 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
1854 if (check_modem_rate(details->modems, details->minrate)) {
1855 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1856 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
1857 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1858 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
1859 set_channel_variables(chan, details);
1863 if (check_modem_rate(details->modems, details->maxrate)) {
1864 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
1865 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
1866 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1867 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
1868 set_channel_variables(chan, details);
1872 if (ast_strlen_zero(data)) {
1873 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1874 ast_string_field_set(details, resultstr, "invalid arguments");
1875 set_channel_variables(chan, details);
1876 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1879 parse = ast_strdupa(data);
1880 AST_STANDARD_APP_ARGS(args, parse);
1882 if (!ast_strlen_zero(args.options) &&
1883 ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
1884 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1885 ast_string_field_set(details, resultstr, "invalid arguments");
1886 set_channel_variables(chan, details);
1889 if (ast_strlen_zero(args.filename)) {
1890 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1891 ast_string_field_set(details, resultstr, "invalid arguments");
1892 set_channel_variables(chan, details);
1893 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1897 /* check for unsupported FAX application options */
1898 if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
1899 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1900 ast_string_field_set(details, resultstr, "invalid arguments");
1901 set_channel_variables(chan, details);
1902 ast_log(LOG_WARNING, "%s does not support polling\n", app_receivefax);
1906 ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
1908 pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
1909 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
1911 if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
1912 ast_string_field_set(details, error, "MEMORY_ERROR");
1913 ast_string_field_set(details, resultstr, "error allocating memory");
1914 set_channel_variables(chan, details);
1915 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1919 strcpy(doc->filename, args.filename);
1920 AST_LIST_INSERT_TAIL(&details->documents, doc, next);
1922 ast_verb(3, "Channel '%s' receiving FAX '%s'\n", ast_channel_name(chan), args.filename);
1924 details->caps = AST_FAX_TECH_RECEIVE;
1925 details->option.send_ced = AST_FAX_OPTFLAG_TRUE;
1927 /* check for debug */
1928 if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
1929 details->option.debug = AST_FAX_OPTFLAG_TRUE;
1932 /* check for request for status events */
1933 if (ast_test_flag(&opts, OPT_STATUS)) {
1934 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
1937 t38state = ast_channel_get_t38_state(chan);
1938 if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
1939 ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
1940 ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1941 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
1944 if (!(s = fax_session_reserve(details, &token))) {
1945 ast_string_field_set(details, resultstr, "error reserving fax session");
1946 set_channel_variables(chan, details);
1947 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
1951 /* make sure the channel is up */
1952 if (ast_channel_state(chan) != AST_STATE_UP) {
1953 if (ast_answer(chan)) {
1954 ast_string_field_set(details, resultstr, "error answering channel");
1955 set_channel_variables(chan, details);
1956 ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
1957 fax_session_release(s, token);
1962 if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
1963 if (set_fax_t38_caps(chan, details)) {
1964 ast_string_field_set(details, error, "T38_NEG_ERROR");
1965 ast_string_field_set(details, resultstr, "error negotiating T.38");
1966 set_channel_variables(chan, details);
1967 fax_session_release(s, token);
1971 details->caps |= AST_FAX_TECH_AUDIO;
1974 if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
1975 if (receivefax_t38_init(chan, details)) {
1976 ast_string_field_set(details, error, "T38_NEG_ERROR");
1977 ast_string_field_set(details, resultstr, "error negotiating T.38");
1978 set_channel_variables(chan, details);
1979 fax_session_release(s, token);
1980 ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
1985 if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
1986 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1989 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1990 if (disable_t38(chan)) {
1991 ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
1995 if (report_receive_fax_status(chan, args.filename)) {
1996 ast_log(AST_LOG_ERROR, "Error publishing ReceiveFax status message\n");
1999 /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2000 return (!channel_alive) ? -1 : 0;
2003 static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
2006 struct ast_frame *frame = NULL;
2007 struct ast_control_t38_parameters t38_parameters;
2008 struct timeval start;
2011 /* send CNG tone while listening for the receiver to initiate a switch
2012 * to T.38 mode; if they do, stop sending the CNG tone and proceed with
2015 * 10500 is enough time for 3 CNG tones
2019 /* don't send any audio if we've already received a T.38 reinvite */
2020 if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
2021 if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
2022 ast_log(LOG_ERROR, "error generating CNG tone on %s\n", ast_channel_name(chan));
2027 start = ast_tvnow();
2028 while ((ms = ast_remaining_ms(start, timeout_ms))) {
2030 ms = ast_waitfor(chan, ms);
2033 ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", ast_channel_name(chan));
2034 ast_playtones_stop(chan);
2038 if (ms == 0) { /* all done, nothing happened */
2042 if (!(frame = ast_read(chan))) {
2043 ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", ast_channel_name(chan));
2044 ast_playtones_stop(chan);
2048 if ((frame->frametype == AST_FRAME_CONTROL) &&
2049 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2050 (frame->datalen == sizeof(t38_parameters))) {
2051 struct ast_control_t38_parameters *parameters = frame->data.ptr;
2053 switch (parameters->request_response) {
2054 case AST_T38_REQUEST_NEGOTIATE:
2055 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2058 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2059 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2060 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2061 ast_playtones_stop(chan);
2063 case AST_T38_NEGOTIATED:
2064 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2065 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2066 details->caps &= ~AST_FAX_TECH_AUDIO;
2067 report_fax_status(chan, details, "T.38 Negotiated");
2080 ast_playtones_stop(chan);
2082 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2086 /* T.38 negotiation did not happen, initiate a switch if requested */
2087 if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
2088 ast_debug(1, "Negotiating T.38 for send on %s\n", ast_channel_name(chan));
2090 /* wait up to five seconds for negotiation to complete */
2093 /* set parameters based on the session's parameters */
2094 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2095 t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
2096 if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
2100 start = ast_tvnow();
2101 while ((ms = ast_remaining_ms(start, timeout_ms))) {
2104 ms = ast_waitfor(chan, ms);
2106 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2109 if (ms == 0) { /* all done, nothing happened */
2110 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(chan));
2111 details->caps &= ~AST_FAX_TECH_T38;
2115 if (!(frame = ast_read(chan))) {
2116 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", ast_channel_name(chan));
2120 if ((frame->frametype == AST_FRAME_CONTROL) &&
2121 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2122 (frame->datalen == sizeof(t38_parameters))) {
2123 struct ast_control_t38_parameters *parameters = frame->data.ptr;
2125 switch (parameters->request_response) {
2126 case AST_T38_REQUEST_NEGOTIATE:
2127 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2128 t38_parameters.request_response = AST_T38_NEGOTIATED;
2129 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2131 case AST_T38_NEGOTIATED:
2132 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(chan));
2133 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2134 details->caps &= ~AST_FAX_TECH_AUDIO;
2135 report_fax_status(chan, details, "T.38 Negotiated");
2138 case AST_T38_REFUSED:
2139 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(chan));
2140 details->caps &= ~AST_FAX_TECH_T38;
2144 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(chan));
2145 details->caps &= ~AST_FAX_TECH_T38;
2156 /* if T.38 was negotiated, we are done initializing */
2157 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2161 /* send one more CNG tone to get audio going again for some
2162 * carriers if we are going to fall back to audio mode */
2163 if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
2164 if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
2165 ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", ast_channel_name(chan));
2170 start = ast_tvnow();
2171 while ((ms = ast_remaining_ms(start, timeout_ms))) {
2174 ms = ast_waitfor(chan, ms);
2176 ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", ast_channel_name(chan));
2177 ast_playtones_stop(chan);
2180 if (ms == 0) { /* all done, nothing happened */
2184 if (!(frame = ast_read(chan))) {
2185 ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", ast_channel_name(chan));
2186 ast_playtones_stop(chan);
2190 if ((frame->frametype == AST_FRAME_CONTROL) &&
2191 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
2192 (frame->datalen == sizeof(t38_parameters))) {
2193 struct ast_control_t38_parameters *parameters = frame->data.ptr;
2195 switch (parameters->request_response) {
2196 case AST_T38_REQUEST_NEGOTIATE:
2197 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
2200 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2201 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
2202 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
2203 ast_playtones_stop(chan);
2205 case AST_T38_NEGOTIATED:
2206 ast_debug(1, "Negotiated T.38 for send on %s\n", ast_channel_name(chan));
2207 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
2208 details->caps &= ~AST_FAX_TECH_AUDIO;
2209 report_fax_status(chan, details, "T.38 Negotiated");
2222 ast_playtones_stop(chan);
2224 /* if T.38 was negotiated, we are done initializing */
2225 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2231 /* if we made it here, then T.38 failed, check the 'f' flag */
2232 if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
2233 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", ast_channel_name(chan));
2237 /* ok, audio fallback is allowed */
2238 details->caps |= AST_FAX_TECH_AUDIO;
2244 * \brief Report on the status of a completed fax send attempt
2245 * \note This will lock the \ref ast_channel
2247 static int report_send_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details)
2249 RAII_VAR(struct ast_json *, json_obj, NULL, ast_json_unref);
2250 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
2251 struct ast_json *json_filenames;
2253 json_filenames = generate_filenames_json(details);
2254 if (!json_filenames) {
2259 SCOPED_CHANNELLOCK(lock, chan);
2260 json_obj = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: o}",
2262 "remote_station_id", S_OR(pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"), ""),
2263 "local_station_id", S_OR(pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"), ""),
2264 "fax_pages", S_OR(pbx_builtin_getvar_helper(chan, "FAXPAGES"), ""),
2265 "fax_resolution", S_OR(pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"), ""),
2266 "fax_bitrate", S_OR(pbx_builtin_getvar_helper(chan, "FAXBITRATE"), ""),
2267 "filenames", json_filenames);
2272 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_fax_type(), json_obj);
2276 stasis_publish(ast_channel_topic(chan), message);
2283 /*! \brief initiate a send FAX session */
2284 static int sendfax_exec(struct ast_channel *chan, const char *data)
2286 char *parse, *filenames, *c, modems[128] = "";
2287 int channel_alive, file_count;
2288 RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
2289 RAII_VAR(struct ast_fax_session *, s, NULL, ao2_cleanup);
2290 struct ast_fax_tech_token *token = NULL;
2291 struct ast_fax_document *doc;
2292 AST_DECLARE_APP_ARGS(args,
2293 AST_APP_ARG(filenames);
2294 AST_APP_ARG(options);
2296 struct ast_flags opts = { 0, };
2297 enum ast_t38_state t38state;
2299 /* initialize output channel variables */
2300 pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
2301 pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
2302 pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
2303 pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
2304 pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
2306 /* Get a requirement structure and set it. This structure is used
2307 * to tell the FAX technology module about the higher level FAX session */
2308 if (!(details = find_or_create_details(chan))) {
2309 pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
2310 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
2311 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2315 ast_string_field_set(details, result, "FAILED");
2316 ast_string_field_set(details, resultstr, "error starting fax session");
2317 ast_string_field_set(details, error, "INIT_ERROR");
2318 set_channel_variables(chan, details);
2320 if (details->gateway_id > 0) {
2321 ast_string_field_set(details, resultstr, "can't send a fax on a channel with a T.38 gateway");
2322 set_channel_variables(chan, details);
2323 ast_log(LOG_ERROR, "executing SendFAX on a channel with a T.38 Gateway is not supported\n");
2327 if (details->maxrate < details->minrate) {
2328 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2329 ast_string_field_set(details, resultstr, "maxrate is less than minrate");
2330 set_channel_variables(chan, details);
2331 ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
2335 if (check_modem_rate(details->modems, details->minrate)) {
2336 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2337 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
2338 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2339 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
2340 set_channel_variables(chan, details);
2344 if (check_modem_rate(details->modems, details->maxrate)) {
2345 ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
2346 ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
2347 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2348 ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
2349 set_channel_variables(chan, details);
2353 if (ast_strlen_zero(data)) {
2354 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2355 ast_string_field_set(details, resultstr, "invalid arguments");
2356 set_channel_variables(chan, details);
2357 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
2360 parse = ast_strdupa(data);
2361 AST_STANDARD_APP_ARGS(args, parse);
2364 if (!ast_strlen_zero(args.options) &&
2365 ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
2366 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2367 ast_string_field_set(details, resultstr, "invalid arguments");
2368 set_channel_variables(chan, details);
2371 if (ast_strlen_zero(args.filenames)) {
2372 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2373 ast_string_field_set(details, resultstr, "invalid arguments");
2374 set_channel_variables(chan, details);
2375 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
2379 /* check for unsupported FAX application options */
2380 if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
2381 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
2382 ast_string_field_set(details, resultstr, "invalid arguments");
2383 set_channel_variables(chan, details);
2384 ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
2388 ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
2391 filenames = args.filenames;
2392 while ((c = strsep(&filenames, "&"))) {
2393 if (access(c, (F_OK | R_OK)) < 0) {
2394 ast_string_field_set(details, error, "FILE_ERROR");
2395 ast_string_field_set(details, resultstr, "error reading file");
2396 set_channel_variables(chan, details);
2397 ast_log(LOG_ERROR, "access failure. Verify '%s' exists and check permissions.\n", args.filenames);
2401 if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
2402 ast_string_field_set(details, error, "MEMORY_ERROR");
2403 ast_string_field_set(details, resultstr, "error allocating memory");
2404 set_channel_variables(chan, details);
2405 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
2409 strcpy(doc->filename, c);
2410 AST_LIST_INSERT_TAIL(&details->documents, doc, next);
2414 ast_verb(3, "Channel '%s' sending FAX:\n", ast_channel_name(chan));
2415 AST_LIST_TRAVERSE(&details->documents, doc, next) {
2416 ast_verb(3, " %s\n", doc->filename);
2419 details->caps = AST_FAX_TECH_SEND;
2421 if (file_count > 1) {
2422 details->caps |= AST_FAX_TECH_MULTI_DOC;
2425 /* check for debug */
2426 if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
2427 details->option.debug = AST_FAX_OPTFLAG_TRUE;
2430 /* check for request for status events */
2431 if (ast_test_flag(&opts, OPT_STATUS)) {
2432 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
2435 t38state = ast_channel_get_t38_state(chan);
2436 if ((t38state == T38_STATE_UNAVAILABLE) || (t38state == T38_STATE_REJECTED) ||
2437 ast_test_flag(&opts, OPT_ALLOWAUDIO) ||
2438 ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2439 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
2442 if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
2443 details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
2446 if (!(s = fax_session_reserve(details, &token))) {
2447 ast_string_field_set(details, resultstr, "error reserving fax session");
2448 set_channel_variables(chan, details);
2449 ast_log(LOG_ERROR, "Unable to reserve FAX session.\n");
2453 /* make sure the channel is up */
2454 if (ast_channel_state(chan) != AST_STATE_UP) {
2455 if (ast_answer(chan)) {
2456 ast_string_field_set(details, resultstr, "error answering channel");
2457 set_channel_variables(chan, details);
2458 ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", ast_channel_name(chan));
2459 fax_session_release(s, token);
2464 if (!ast_test_flag(&opts, OPT_FORCE_AUDIO)) {
2465 if (set_fax_t38_caps(chan, details)) {
2466 ast_string_field_set(details, error, "T38_NEG_ERROR");
2467 ast_string_field_set(details, resultstr, "error negotiating T.38");
2468 set_channel_variables(chan, details);
2469 fax_session_release(s, token);
2473 details->caps |= AST_FAX_TECH_AUDIO;
2476 if (!ast_test_flag(&opts, OPT_FORCE_AUDIO) && (details->caps & AST_FAX_TECH_T38)) {
2477 if (sendfax_t38_init(chan, details)) {
2478 ast_string_field_set(details, error, "T38_NEG_ERROR");
2479 ast_string_field_set(details, resultstr, "error negotiating T.38");
2480 set_channel_variables(chan, details);
2481 fax_session_release(s, token);
2482 ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", ast_channel_name(chan));
2486 details->option.send_cng = 1;
2489 if ((channel_alive = generic_fax_exec(chan, details, s, token)) < 0) {
2490 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
2493 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
2494 if (disable_t38(chan)) {
2495 ast_debug(1, "error disabling T.38 mode on %s\n", ast_channel_name(chan));
2499 if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
2500 ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
2501 return (!channel_alive) ? -1 : 0;
2504 /* send out the AMI completion event */
2505 if (report_send_fax_status(chan, details)) {
2506 ast_log(AST_LOG_ERROR, "Error publishing SendFAX status message\n");
2509 /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
2510 return (!channel_alive) ? -1 : 0;
2513 /*! \brief destroy the v21 detection parts of a fax gateway session */
2514 static void destroy_v21_sessions(struct fax_gateway *gateway)
2516 if (gateway->chan_v21_session) {
2517 ao2_lock(faxregistry.container);
2518 ao2_unlink(faxregistry.container, gateway->chan_v21_session);
2519 ao2_unlock(faxregistry.container);
2521 ao2_ref(gateway->chan_v21_session, -1);
2522 gateway->chan_v21_session = NULL;
2525 if (gateway->peer_v21_session) {
2526 ao2_lock(faxregistry.container);
2527 ao2_unlink(faxregistry.container, gateway->peer_v21_session);
2528 ao2_unlock(faxregistry.container);
2530 ao2_ref(gateway->peer_v21_session, -1);
2531 gateway->peer_v21_session = NULL;
2535 /*! \brief destroy a FAX gateway session structure */
2536 static void destroy_gateway(void *data)
2538 struct fax_gateway *gateway = data;
2540 destroy_v21_sessions(gateway);
2543 fax_session_release(gateway->s, gateway->token);
2544 gateway->token = NULL;
2546 ao2_lock(faxregistry.container);
2547 ao2_unlink(faxregistry.container, gateway->s);
2548 ao2_unlock(faxregistry.container);
2550 ao2_ref(gateway->s, -1);
2555 /*! \brief Create a new fax gateway object.
2556 * \param chan the channel the gateway object will be attached to
2557 * \param details the fax session details
2558 * \return NULL or a fax gateway object
2560 static struct fax_gateway *fax_gateway_new(struct ast_channel *chan, struct ast_fax_session_details *details)
2562 struct fax_gateway *gateway = ao2_alloc(sizeof(*gateway), destroy_gateway);
2563 struct ast_fax_session_details *v21_details;
2568 if (!(v21_details = session_details_new())) {
2569 ao2_ref(gateway, -1);
2573 v21_details->caps = AST_FAX_TECH_V21_DETECT;
2574 if (!(gateway->chan_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2575 ao2_ref(v21_details, -1);
2576 ao2_ref(gateway, -1);
2580 if (!(gateway->peer_v21_session = fax_session_new(v21_details, chan, NULL, NULL))) {
2581 ao2_ref(v21_details, -1);
2582 ao2_ref(gateway, -1);
2585 ao2_ref(v21_details, -1);
2587 gateway->framehook = -1;
2589 details->caps = AST_FAX_TECH_GATEWAY;
2590 if (details->gateway_timeout && !(gateway->s = fax_session_reserve(details, &gateway->token))) {
2591 details->caps &= ~AST_FAX_TECH_GATEWAY;
2592 ast_log(LOG_ERROR, "Can't reserve a FAX session, gateway attempt failed.\n");
2593 ao2_ref(gateway, -1);
2600 /*! \brief Create a fax session and start T.30<->T.38 gateway mode
2601 * \param gateway a fax gateway object
2602 * \param details fax session details
2603 * \param chan active channel
2604 * \return 0 on error 1 on success*/
2605 static int fax_gateway_start(struct fax_gateway *gateway, struct ast_fax_session_details *details, struct ast_channel *chan)
2607 struct ast_fax_session *s;
2609 /* create the FAX session */
2610 if (!(s = fax_session_new(details, chan, gateway->s, gateway->token))) {
2611 gateway->token = NULL;
2612 ast_string_field_set(details, result, "FAILED");
2613 ast_string_field_set(details, resultstr, "error starting gateway session");
2614 ast_string_field_set(details, error, "INIT_ERROR");
2615 set_channel_variables(chan, details);
2616 report_fax_status(chan, details, "No Available Resource");
2617 ast_log(LOG_ERROR, "Can't create a FAX session, gateway attempt failed.\n");
2620 /* release the reference for the reserved session and replace it with
2621 * the real session */
2623 ao2_ref(gateway->s, -1);
2626 gateway->token = NULL;
2628 if (gateway->s->tech->start_session(gateway->s) < 0) {
2629 ast_string_field_set(details, result, "FAILED");
2630 ast_string_field_set(details, resultstr, "error starting gateway session");
2631 ast_string_field_set(details, error, "INIT_ERROR");
2632 set_channel_variables(chan, details);
2636 gateway->timeout_start.tv_sec = 0;
2637 gateway->timeout_start.tv_usec = 0;
2639 report_fax_status(chan, details, "FAX Transmission In Progress");
2644 static struct ast_frame *fax_gateway_request_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_frame *f)
2646 struct ast_frame *fp;
2647 struct ast_control_t38_parameters t38_parameters = {
2648 .request_response = AST_T38_REQUEST_NEGOTIATE,
2650 struct ast_frame control_frame = {
2652 .frametype = AST_FRAME_CONTROL,
2653 .datalen = sizeof(t38_parameters),
2654 .subclass.integer = AST_CONTROL_T38_PARAMETERS,
2655 .data.ptr = &t38_parameters,
2658 struct ast_fax_session_details *details = find_details(chan);
2661 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2662 ast_framehook_detach(chan, gateway->framehook);
2666 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
2667 ao2_ref(details, -1);
2669 if (!(fp = ast_frisolate(&control_frame))) {
2670 ast_log(LOG_ERROR, "error generating T.38 request control frame on chan %s for T.38 gateway session\n", ast_channel_name(chan));
2674 gateway->t38_state = T38_STATE_NEGOTIATING;
2675 gateway->timeout_start = ast_tvnow();
2676 details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2678 ast_debug(1, "requesting T.38 for gateway session for %s\n", ast_channel_name(chan));
2682 static struct ast_frame *fax_gateway_detect_v21(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *active, struct ast_frame *f)
2684 struct ast_channel *other = (active == chan) ? peer : chan;
2685 struct ast_fax_session *active_v21_session = (active == chan) ? gateway->chan_v21_session : gateway->peer_v21_session;
2687 if (!active_v21_session || gateway->detected_v21) {
2691 if (active_v21_session->tech->write(active_v21_session, f) == 0 &&
2692 active_v21_session->details->option.v21_detected) {
2693 gateway->detected_v21 = 1;
2696 if (gateway->detected_v21) {
2697 destroy_v21_sessions(gateway);
2698 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2699 ast_debug(1, "detected v21 preamble from %s\n", ast_channel_name(active));
2700 return fax_gateway_request_t38(gateway, chan, f);
2702 ast_debug(1, "detected v21 preamble on %s, but %s does not support T.38 for T.38 gateway session\n", ast_channel_name(active), ast_channel_name(other));
2709 static int fax_gateway_indicate_t38(struct ast_channel *chan, struct ast_channel *active, struct ast_control_t38_parameters *control_params)
2711 if (active == chan) {
2712 return ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2714 return ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, control_params, sizeof(*control_params));
2718 /*! \brief T38 Gateway Negotiate t38 parameters
2719 * \param gateway gateway object
2720 * \param chan channel running the gateway
2721 * \param peer channel im bridged too
2722 * \param active channel the frame originated on
2723 * \param f the control frame to process
2724 * \return processed control frame or null frame
2726 static struct ast_frame *fax_gateway_detect_t38(struct fax_gateway *gateway, struct ast_channel *chan, struct ast_channel *peer, struct ast_channel *active, struct ast_frame *f)
2728 struct ast_control_t38_parameters *control_params = f->data.ptr;
2729 struct ast_channel *other = (active == chan) ? peer : chan;
2730 struct ast_fax_session_details *details;
2732 if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
2733 /* invalaid AST_CONTROL_T38_PARAMETERS frame, we can't
2734 * do anything with it, pass it on */
2738 /* ignore frames from ourselves */
2739 if ((gateway->t38_state == T38_STATE_NEGOTIATED && control_params->request_response == AST_T38_NEGOTIATED)
2740 || (gateway->t38_state == T38_STATE_REJECTED && control_params->request_response == AST_T38_REFUSED)
2741 || (gateway->t38_state == T38_STATE_NEGOTIATING && control_params->request_response == AST_T38_REQUEST_TERMINATE)) {
2746 if (!(details = find_details(chan))) {
2747 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2748 ast_framehook_detach(chan, gateway->framehook);
2752 if (control_params->request_response == AST_T38_REQUEST_NEGOTIATE) {
2753 enum ast_t38_state state = ast_channel_get_t38_state(other);
2755 if (state == T38_STATE_UNKNOWN) {
2756 /* we detected a request to negotiate T.38 and the
2757 * other channel appears to support T.38, we'll pass
2758 * the request through and only step in if the other
2759 * channel rejects the request */
2760 ast_debug(1, "%s is attempting to negotiate T.38 with %s, we'll see what happens\n", ast_channel_name(active), ast_channel_name(other));
2761 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2762 gateway->t38_state = T38_STATE_UNKNOWN;
2763 gateway->timeout_start = ast_tvnow();
2764 details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2765 ao2_ref(details, -1);
2767 } else if (state == T38_STATE_UNAVAILABLE || state == T38_STATE_REJECTED) {
2768 /* the other channel does not support T.38, we need to
2770 ast_debug(1, "%s is attempting to negotiate T.38 but %s does not support it\n", ast_channel_name(active), ast_channel_name(other));
2771 ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2773 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2774 t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2776 if (fax_gateway_start(gateway, details, chan)) {
2777 ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2778 gateway->t38_state = T38_STATE_REJECTED;
2779 control_params->request_response = AST_T38_REFUSED;
2781 ast_framehook_detach(chan, details->gateway_id);
2782 details->gateway_id = -1;
2784 gateway->t38_state = T38_STATE_NEGOTIATED;
2785 control_params->request_response = AST_T38_NEGOTIATED;
2786 report_fax_status(chan, details, "T.38 Negotiated");
2789 fax_gateway_indicate_t38(chan, active, control_params);
2791 ao2_ref(details, -1);
2792 return &ast_null_frame;
2793 } else if (gateway->t38_state == T38_STATE_NEGOTIATING) {
2794 /* we got a request to negotiate T.38 after we already
2795 * sent one to the other party based on v21 preamble
2796 * detection. We'll just pretend we passed this request
2797 * through in the first place. */
2799 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2800 gateway->t38_state = T38_STATE_UNKNOWN;
2801 gateway->timeout_start = ast_tvnow();
2802 details->gateway_timeout = FAX_GATEWAY_TIMEOUT;
2804 ast_debug(1, "%s is attempting to negotiate T.38 after we already sent a negotiation request based on v21 preamble detection\n", ast_channel_name(active));
2805 ao2_ref(details, -1);
2806 return &ast_null_frame;
2807 } else if (gateway->t38_state == T38_STATE_NEGOTIATED) {
2808 /* we got a request to negotiate T.38 after we already
2809 * sent one to the other party based on v21 preamble
2810 * detection and received a response. We need to
2811 * respond to this and shut down the gateway. */
2813 t38_parameters_fax_to_ast(control_params, &details->their_t38_parameters);
2814 ast_framehook_detach(chan, details->gateway_id);
2815 details->gateway_id = -1;
2817 control_params->request_response = AST_T38_NEGOTIATED;
2819 fax_gateway_indicate_t38(chan, active, control_params);
2821 ast_string_field_set(details, result, "SUCCESS");
2822 ast_string_field_set(details, resultstr, "no gateway necessary");
2823 ast_string_field_set(details, error, "NATIVE_T38");
2824 set_channel_variables(chan, details);
2826 ast_debug(1, "%s is attempting to negotiate T.38 after we already negotiated T.38 with %s, disabling the gateway\n", ast_channel_name(active), ast_channel_name(other));
2827 ao2_ref(details, -1);
2828 return &ast_null_frame;
2830 ast_log(LOG_WARNING, "%s is attempting to negotiate T.38 while %s is in an unsupported state\n", ast_channel_name(active), ast_channel_name(other));
2831 ao2_ref(details, -1);
2834 } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2835 && control_params->request_response == AST_T38_REFUSED) {
2837 ast_debug(1, "unable to negotiate T.38 on %s for fax gateway\n", ast_channel_name(active));
2839 /* our request to negotiate T.38 was refused, if the other
2840 * channel supports T.38, they might still reinvite and save
2841 * the day. Otherwise disable the gateway. */
2842 if (ast_channel_get_t38_state(other) == T38_STATE_UNKNOWN) {
2843 gateway->t38_state = T38_STATE_UNAVAILABLE;
2845 ast_framehook_detach(chan, details->gateway_id);
2846 details->gateway_id = -1;
2848 ast_string_field_set(details, result, "FAILED");
2849 ast_string_field_set(details, resultstr, "unable to negotiate T.38");
2850 ast_string_field_set(details, error, "T38_NEG_ERROR");
2851 set_channel_variables(chan, details);
2854 ao2_ref(details, -1);
2855 return &ast_null_frame;
2856 } else if (gateway->t38_state == T38_STATE_NEGOTIATING
2857 && control_params->request_response == AST_T38_NEGOTIATED) {
2859 ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2861 t38_parameters_ast_to_fax(&details->their_t38_parameters, control_params);
2863 if (fax_gateway_start(gateway, details, chan)) {
2864 ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2865 gateway->t38_state = T38_STATE_NEGOTIATING;
2866 control_params->request_response = AST_T38_REQUEST_TERMINATE;
2868 fax_gateway_indicate_t38(chan, active, control_params);
2870 gateway->t38_state = T38_STATE_NEGOTIATED;
2871 report_fax_status(chan, details, "T.38 Negotiated");
2874 ao2_ref(details, -1);
2875 return &ast_null_frame;
2876 } else if (control_params->request_response == AST_T38_REFUSED) {
2877 /* the other channel refused the request to negotiate T.38,
2878 * we'll step in here and pretend the request was accepted */
2880 ast_debug(1, "%s attempted to negotiate T.38 but %s refused the request\n", ast_channel_name(other), ast_channel_name(active));
2881 ast_debug(1, "starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(other), ast_channel_name(active));
2883 t38_parameters_fax_to_ast(control_params, &details->our_t38_parameters);
2885 if (fax_gateway_start(gateway, details, chan)) {
2886 ast_log(LOG_ERROR, "error starting T.38 gateway for T.38 channel %s and G.711 channel %s\n", ast_channel_name(active), ast_channel_name(other));
2887 gateway->t38_state = T38_STATE_REJECTED;
2888 control_params->request_response = AST_T38_REFUSED;
2890 ast_framehook_detach(chan, details->gateway_id);
2891 details->gateway_id = -1;
2893 gateway->t38_state = T38_STATE_NEGOTIATED;
2894 control_params->request_response = AST_T38_NEGOTIATED;
2897 ao2_ref(details, -1);
2899 } else if (control_params->request_response == AST_T38_REQUEST_TERMINATE) {
2900 /* the channel wishes to end our short relationship, we shall
2903 ast_debug(1, "T.38 channel %s is requesting a shutdown of T.38, disabling the gateway\n", ast_channel_name(active));
2905 ast_framehook_detach(chan, details->gateway_id);
2906 details->gateway_id = -1;
2908 gateway->t38_state = T38_STATE_REJECTED;
2909 control_params->request_response = AST_T38_TERMINATED;
2911 fax_gateway_indicate_t38(chan, active, control_params);
2913 ao2_ref(details, -1);
2914 return &ast_null_frame;
2915 } else if (control_params->request_response == AST_T38_NEGOTIATED) {
2916 ast_debug(1, "T.38 successfully negotiated between %s and %s, no gateway necessary\n", ast_channel_name(active), ast_channel_name(other));
2918 ast_framehook_detach(chan, details->gateway_id);
2919 details->gateway_id = -1;
2921 ast_string_field_set(details, result, "SUCCESS");
2922 ast_string_field_set(details, resultstr, "no gateway necessary");
2923 ast_string_field_set(details, error, "NATIVE_T38");
2924 set_channel_variables(chan, details);
2926 ao2_ref(details, -1);
2928 } else if (control_params->request_response == AST_T38_TERMINATED) {
2929 ast_debug(1, "T.38 disabled on channel %s\n", ast_channel_name(active));
2931 ast_framehook_detach(chan, details->gateway_id);
2932 details->gateway_id = -1;
2934 ao2_ref(details, -1);
2935 return &ast_null_frame;
2938 ao2_ref(details, -1);
2942 /*! \brief Destroy the gateway data structure when the framehook is detached
2943 * \param data framehook data (gateway data)*/
2944 static void fax_gateway_framehook_destroy(void *data) {
2945 struct fax_gateway *gateway = data;
2948 switch (gateway->s->state) {
2949 case AST_FAX_STATE_INITIALIZED:
2950 case AST_FAX_STATE_OPEN:
2951 case AST_FAX_STATE_ACTIVE:
2952 case AST_FAX_STATE_COMPLETE:
2953 if (gateway->s->tech->cancel_session) {
2954 gateway->s->tech->cancel_session(gateway->s);
2962 ao2_ref(gateway, -1);
2965 /*! \brief T.30<->T.38 gateway framehook.
2967 * Intercept packets on bridged channels and determine if a T.38 gateway is
2968 * required. If a gateway is required, start a gateway and handle T.38
2969 * negotiation if necessary.
2971 * \param chan channel running the gateway
2972 * \param f frame to handle may be NULL
2973 * \param event framehook event
2974 * \param data framehook data (struct fax_gateway *)
2976 * \return processed frame or NULL when f is NULL or a null frame
2978 static struct ast_frame *fax_gateway_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data) {
2979 struct fax_gateway *gateway = data;
2980 struct ast_channel *active;
2981 RAII_VAR(struct ast_fax_session_details *, details, NULL, ao2_cleanup);
2982 RAII_VAR(struct ast_channel *, peer, NULL, ao2_cleanup);
2985 details = gateway->s->details;
2986 ao2_ref(details, 1);
2988 if (!(details = find_details(chan))) {
2989 ast_log(LOG_ERROR, "no FAX session details found on chan %s for T.38 gateway session, odd\n", ast_channel_name(chan));
2990 ast_framehook_detach(chan, gateway->framehook);
2995 /* restore audio formats when we are detached */
2996 if (event == AST_FRAMEHOOK_EVENT_DETACHED) {
2997 set_channel_variables(chan, details);
2999 if (gateway->bridged) {
3000 ast_set_read_format(chan, &gateway->chan_read_format);
3001 ast_set_read_format(chan, &gateway->chan_write_format);
3003 if ((peer = ast_channel_bridge_peer(chan))) {
3004 ast_set_read_format(peer, &gateway->peer_read_format);
3005 ast_set_read_format(peer, &gateway->peer_write_format);
3006 ast_channel_make_compatible(chan, peer);
3012 if (!f || (event == AST_FRAMEHOOK_EVENT_ATTACHED)) {
3016 /* this frame was generated by the fax gateway, pass it on */
3017 if (ast_test_flag(f, AST_FAX_FRFLAG_GATEWAY)) {
3021 /* If we aren't bridged or we don't have a peer, don't do anything */
3022 if (!(peer = ast_channel_bridge_peer(chan))) {
3026 if (!gateway->bridged && peer) {
3027 /* don't start a gateway if neither channel can handle T.38 */
3028 if (ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE && ast_channel_get_t38_state(peer) == T38_STATE_UNAVAILABLE) {
3029 ast_debug(1, "not starting gateway for %s and %s; neither channel supports T.38\n", ast_channel_name(chan), ast_channel_name(peer));
3030 ast_framehook_detach(chan, gateway->framehook);
3031 details->gateway_id = -1;
3033 ast_string_field_set(details, result, "FAILED");
3034 ast_string_field_set(details, resultstr, "neither channel supports T.38");
3035 ast_string_field_set(details, error, "T38_NEG_ERROR");
3036 set_channel_variables(chan, details);
3040 if (details->gateway_timeout) {
3041 gateway->timeout_start = ast_tvnow();
3044 /* we are bridged, change r/w formats to SLIN for v21 preamble
3045 * detection and T.30 */
3046 ast_format_copy(&gateway->chan_read_format, ast_channel_readformat(chan));
3047 ast_format_copy(&gateway->chan_write_format, ast_channel_readformat(chan));
3049 ast_format_copy(&gateway->peer_read_format, ast_channel_readformat(peer));