Sat Mar 26 11:08:06 2011

Asterisk developer's documentation


res_fax.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2008-2009, Digium, Inc.
00005  *
00006  * Dwayne M. Hubbard <dhubbard@digium.com>
00007  * Kevin P. Fleming <kpfleming@digium.com>
00008  *
00009  * See http://www.asterisk.org for more information about
00010  * the Asterisk project. Please do not directly contact
00011  * any of the maintainers of this project for assistance;
00012  * the project provides a web site, mailing lists and IRC
00013  * channels for your use.
00014  *
00015  * This program is free software, distributed under the terms of
00016  * the GNU General Public License Version 2. See the LICENSE file
00017  * at the top of the source tree.
00018  */
00019 
00020 /*** MODULEINFO
00021    <conflict>app_fax</conflict>
00022 ***/
00023 
00024 /*! \file
00025  *
00026  * \brief Generic FAX Resource for FAX technology resource modules
00027  *
00028  * \author Dwayne M. Hubbard <dhubbard@digium.com>
00029  * \author Kevin P. Fleming <kpfleming@digium.com>
00030  * 
00031  * A generic FAX resource module that provides SendFAX and ReceiveFAX applications.
00032  * This module requires FAX technology modules, like res_fax_spandsp, to register with it
00033  * so it can use the technology modules to perform the actual FAX transmissions.
00034  * \ingroup applications
00035  */
00036 
00037 #include "asterisk.h"
00038 
00039 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 281358 $")
00040 
00041 #include "asterisk/io.h"
00042 #include "asterisk/file.h"
00043 #include "asterisk/logger.h"
00044 #include "asterisk/module.h"
00045 #include "asterisk/app.h"
00046 #include "asterisk/lock.h"
00047 #include "asterisk/options.h"
00048 #include "asterisk/strings.h"
00049 #include "asterisk/cli.h"
00050 #include "asterisk/utils.h"
00051 #include "asterisk/config.h"
00052 #include "asterisk/astobj2.h"
00053 #include "asterisk/res_fax.h"
00054 #include "asterisk/file.h"
00055 #include "asterisk/channel.h"
00056 #include "asterisk/pbx.h"
00057 #include "asterisk/manager.h"
00058 #include "asterisk/dsp.h"
00059 #include "asterisk/indications.h"
00060 #include "asterisk/ast_version.h"
00061 
00062 /*** DOCUMENTATION
00063    <application name="ReceiveFax" language="en_US">
00064       <synopsis>
00065          Receive a FAX and save as a TIFF/F file.
00066       </synopsis>
00067       <syntax>
00068          <parameter name="filename" required="true" />
00069          <parameter name="options">
00070             <optionlist>
00071                <option name="d">
00072                   <para>Enable FAX debugging.</para>
00073                </option>
00074                <option name="f">
00075                   <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
00076                </option>
00077                <option name="s">
00078                   <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
00079                </option>
00080             </optionlist>
00081          </parameter>
00082       </syntax>
00083       <description>
00084          <para>This application is provided by res_fax, which is a FAX technology agnostic module
00085          that utilizes FAX technology resource modules to complete a FAX transmission.</para>
00086          <para>Session arguments can be set by the FAXOPT function and to check results of the ReceiveFax() application.</para>
00087       </description>
00088       <see-also>
00089          <ref type="function">FAXOPT</ref>
00090       </see-also>
00091    </application>
00092    <application name="SendeFax" language="en_US">
00093       <synopsis>
00094          Sends a specified TIFF/F file as a FAX.
00095       </synopsis>
00096       <syntax>
00097          <parameter name="filename" required="true" argsep="&amp;">
00098             <argument name="filename2" multiple="true">
00099                <para>TIFF file to send as a FAX.</para>
00100             </argument>
00101          </parameter>
00102          <parameter name="options">
00103             <optionlist>
00104                <option name="d">
00105                   <para>Enable FAX debugging.</para>
00106                </option>
00107                <option name="f">
00108                   <para>Allow audio fallback FAX transfer on T.38 capable channels.</para>
00109                </option>
00110                <option name="s">
00111                   <para>Send progress Manager events (overrides statusevents setting in res_fax.conf).</para>
00112                </option>
00113                <option name="z">
00114                   <para>Initiate a T.38 reinvite on the channel if the remote end does not.</para>
00115                </option>
00116             </optionlist>
00117          </parameter>
00118       </syntax>
00119       <description>
00120          <para>This application is provided by res_fax, which is a FAX technology agnostic module
00121          that utilizes FAX technology resource modules to complete a FAX transmission.</para>
00122          <para>Session arguments can be set by the FAXOPT function and to check results of the SendFax() application.</para>
00123       </description>
00124       <see-also>
00125          <ref type="function">FAXOPT</ref>
00126       </see-also>
00127    </application>
00128    <function name="FAXOPT" language="en_US">
00129       <synopsis>
00130          Gets/sets various pieces of information about a fax session.
00131       </synopsis>
00132       <syntax>
00133          <parameter name="item" required="true">
00134             <enumlist>
00135                <enum name="ecm">
00136                   <para>R/W Error Correction Mode (ECM) enable with 'yes', disable with 'no'.</para>
00137                </enum>
00138                <enum name="error">
00139                   <para>R/O FAX transmission error code upon failure.</para>
00140                </enum>
00141                <enum name="filename">
00142                   <para>R/O Filename of the first file of the FAX transmission.</para>
00143                </enum>
00144                <enum name="filenames">
00145                   <para>R/O Filenames of all of the files in the FAX transmission (comma separated).</para>
00146                </enum>
00147                <enum name="headerinfo">
00148                   <para>R/W FAX header information.</para>
00149                </enum>
00150                <enum name="localstationid">
00151                   <para>R/W Local Station Identification.</para>
00152                </enum>
00153                <enum name="minrate">
00154                   <para>R/W Minimum transfer rate set before transmission.</para>
00155                </enum>
00156                <enum name="maxrate">
00157                   <para>R/W Maximum transfer rate set before transmission.</para>
00158                </enum>
00159                <enum name="modem">
00160                   <para>R/W Modem type (v17/v27/v29).</para>
00161                </enum>
00162                <enum name="pages">
00163                   <para>R/O Number of pages transferred.</para>
00164                </enum>
00165                <enum name="rate">
00166                   <para>R/O Negotiated transmission rate.</para>
00167                </enum>
00168                <enum name="remotestationid">
00169                   <para>R/O Remote Station Identification after transmission.</para>
00170                </enum>
00171                <enum name="resolution">
00172                   <para>R/O Negotiated image resolution after transmission.</para>
00173                </enum>
00174                <enum name="sessionid">
00175                   <para>R/O Session ID of the FAX transmission.</para>
00176                </enum>
00177                <enum name="status">
00178                   <para>R/O Result Status of the FAX transmission.</para>
00179                </enum>
00180                <enum name="statusstr">
00181                   <para>R/O Verbose Result Status of the FAX transmission.</para>
00182                </enum>
00183             </enumlist>
00184          </parameter>
00185       </syntax>
00186       <description>
00187          <para>FAXOPT can be used to override the settings for a FAX session listed in <filename>res_fax.conf</filename>,
00188             it can also be used to retreive information about a FAX session that has finished eg. pages/status.</para>
00189       </description>
00190       <see-also>
00191          <ref type="application">ReceiveFax</ref>
00192          <ref type="application">SendFax</ref>
00193       </see-also>
00194    </function>
00195 ***/
00196 
00197 static const char app_receivefax[] = "ReceiveFAX";
00198 static const char app_sendfax[] = "SendFAX";
00199 
00200 struct debug_info_history {
00201    unsigned int consec_frames;
00202    unsigned int consec_ms;
00203    unsigned char silence;
00204 };
00205 
00206 struct ast_fax_debug_info {
00207    struct timeval base_tv;
00208    struct debug_info_history c2s, s2c;
00209    struct ast_dsp *dsp;
00210 };
00211 
00212 static int fax_logger_level = -1;
00213 
00214 /*! \brief maximum buckets for res_fax ao2 containers */
00215 #define FAX_MAXBUCKETS 10
00216 
00217 #define RES_FAX_TIMEOUT 10000
00218 
00219 /*! \brief The faxregistry is used to manage information and statistics for all FAX sessions. */
00220 static struct {
00221    /*! The number of active FAX sessions */
00222    int active_sessions;
00223    /*! active sessions are astobj2 objects */
00224    struct ao2_container *container;
00225    /*! Total number of Tx FAX attempts */
00226    int fax_tx_attempts;
00227    /*! Total number of Rx FAX attempts */
00228    int fax_rx_attempts;
00229    /*! Number of successful FAX transmissions */
00230    int fax_complete;
00231    /*! Number of failed FAX transmissions */
00232    int fax_failures;
00233    /*! the next unique session name */
00234    int nextsessionname;
00235 } faxregistry;
00236 
00237 /*! \brief registered FAX technology modules are put into this list */
00238 struct fax_module {
00239    const struct ast_fax_tech *tech;
00240    AST_RWLIST_ENTRY(fax_module) list;
00241 };
00242 static AST_RWLIST_HEAD_STATIC(faxmodules, fax_module);
00243 
00244 #define RES_FAX_MINRATE 2400
00245 #define RES_FAX_MAXRATE 14400
00246 #define RES_FAX_STATUSEVENTS 0
00247 #define RES_FAX_MODEM (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29)
00248 
00249 static struct {
00250    enum ast_fax_modems modems;
00251    uint32_t statusevents:1;
00252    uint32_t ecm:1;
00253    unsigned int minrate;   
00254    unsigned int maxrate;
00255 } general_options;
00256 
00257 static const char *config = "res_fax.conf";
00258 
00259 static int global_fax_debug = 0;
00260 
00261 enum {
00262    OPT_CALLEDMODE  = (1 << 0),
00263    OPT_CALLERMODE  = (1 << 1),
00264    OPT_DEBUG       = (1 << 2),
00265    OPT_STATUS      = (1 << 3),
00266    OPT_ALLOWAUDIO  = (1 << 5),
00267    OPT_REQUEST_T38 = (1 << 6),
00268 };
00269 
00270 AST_APP_OPTIONS(fax_exec_options, BEGIN_OPTIONS
00271    AST_APP_OPTION('a', OPT_CALLEDMODE),
00272    AST_APP_OPTION('c', OPT_CALLERMODE),
00273    AST_APP_OPTION('d', OPT_DEBUG),
00274    AST_APP_OPTION('f', OPT_ALLOWAUDIO),
00275    AST_APP_OPTION('s', OPT_STATUS),
00276    AST_APP_OPTION('z', OPT_REQUEST_T38),
00277 END_OPTIONS);
00278 
00279 struct manager_event_info {
00280    char context[AST_MAX_CONTEXT];
00281    char exten[AST_MAX_EXTENSION];
00282    char cid[128];
00283 };
00284 
00285 static void debug_check_frame_for_silence(struct ast_fax_session *s, unsigned int c2s, struct ast_frame *frame)
00286 {  
00287    struct debug_info_history *history = c2s ? &s->debug_info->c2s : &s->debug_info->s2c;
00288    int dspsilence;
00289    unsigned int last_consec_frames, last_consec_ms;
00290    unsigned char wassil;
00291    struct timeval diff;
00292 
00293    diff = ast_tvsub(ast_tvnow(), s->debug_info->base_tv);
00294 
00295    ast_dsp_reset(s->debug_info->dsp);
00296    ast_dsp_silence(s->debug_info->dsp, frame, &dspsilence);
00297 
00298    wassil = history->silence;
00299    history->silence = (dspsilence != 0) ? 1 : 0;
00300    if (history->silence != wassil) {
00301       last_consec_frames = history->consec_frames;
00302       last_consec_ms = history->consec_ms;
00303       history->consec_frames = 0;
00304       history->consec_ms = 0;
00305 
00306       if ((last_consec_frames != 0)) {
00307          ast_verb(6, "Channel '%s' fax session '%d', [ %.3ld.%.6ld ], %s sent %d frames (%d ms) of %s.\n",
00308              s->channame, s->id, (long) diff.tv_sec, (long int) diff.tv_usec,
00309              (c2s) ? "channel" : "stack", last_consec_frames, last_consec_ms,
00310              (wassil) ? "silence" : "energy");
00311       }
00312    }
00313 
00314    history->consec_frames++;
00315    history->consec_ms += (frame->samples / 8);
00316 }
00317 
00318 static void destroy_callback(void *data) 
00319 {
00320    if (data) {
00321       ao2_ref(data, -1);
00322    }
00323 }
00324 
00325 static const struct ast_datastore_info fax_datastore = {
00326    .type = "res_fax",
00327    .destroy = destroy_callback,
00328 };
00329 
00330 /*! \brief returns a reference counted pointer to a fax datastore, if it exists */
00331 static struct ast_fax_session_details *find_details(struct ast_channel *chan)
00332 {
00333    struct ast_fax_session_details *details;
00334    struct ast_datastore *datastore;
00335 
00336    ast_channel_lock(chan); 
00337    if (!(datastore = ast_channel_datastore_find(chan, &fax_datastore, NULL))) {
00338       ast_channel_unlock(chan);  
00339       return NULL;
00340    }
00341    if (!(details = datastore->data)) {
00342       ast_log(LOG_WARNING, "Huh?  channel '%s' has a FAX datastore without data!\n", chan->name);
00343       ast_channel_unlock(chan);
00344       return NULL;
00345    }
00346    ao2_ref(details, 1); 
00347    ast_channel_unlock(chan);  
00348 
00349    return details;
00350 }
00351 
00352 /*! \brief destroy a FAX session details structure */
00353 static void destroy_session_details(void *details)
00354 {
00355    struct ast_fax_session_details *d = details;
00356    struct ast_fax_document *doc;
00357    
00358    while ((doc = AST_LIST_REMOVE_HEAD(&d->documents, next))) {
00359       ast_free(doc);
00360    }
00361    ast_string_field_free_memory(d); 
00362 }
00363 
00364 /*! \brief create a FAX session details structure */
00365 static struct ast_fax_session_details *session_details_new(void)
00366 {
00367    struct ast_fax_session_details *d;
00368 
00369    if (!(d = ao2_alloc(sizeof(*d), destroy_session_details))) {
00370       return NULL;
00371    }
00372    
00373    if (ast_string_field_init(d, 512)) {
00374       ao2_ref(d, -1);
00375       return NULL;
00376    }
00377 
00378    AST_LIST_HEAD_INIT_NOLOCK(&d->documents);
00379 
00380    /* These options need to be set to the configured default and may be overridden by
00381     * SendFAX, ReceiveFAX, or FAXOPT */
00382    d->option.request_t38 = AST_FAX_OPTFLAG_FALSE;
00383    d->option.send_cng = AST_FAX_OPTFLAG_FALSE;
00384    d->option.send_ced = AST_FAX_OPTFLAG_FALSE;
00385    d->option.ecm = general_options.ecm;
00386    d->option.statusevents = general_options.statusevents;
00387    d->modems = general_options.modems;
00388    d->minrate = general_options.minrate;
00389    d->maxrate = general_options.maxrate;
00390 
00391    return d;
00392 }
00393 
00394 /*! \brief returns a reference counted details structure from the channel's fax datastore.  If the datastore
00395  * does not exist it will be created */   
00396 static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan)
00397 {
00398    struct ast_fax_session_details *details;
00399    struct ast_datastore *datastore;
00400 
00401    if ((details = find_details(chan))) {
00402       return details;
00403    }
00404    /* channel does not have one so we must create one */
00405    if (!(details = session_details_new())) {
00406       ast_log(LOG_WARNING, "channel '%s' can't get a FAX details structure for the datastore!\n", chan->name);
00407       return NULL;
00408    }
00409    if (!(datastore = ast_datastore_alloc(&fax_datastore, NULL))) {
00410       ao2_ref(details, -1);
00411       ast_log(LOG_WARNING, "channel '%s' can't get a datastore!\n", chan->name);
00412       return NULL;
00413    }
00414    /* add the datastore to the channel and increment the refcount */
00415    datastore->data = details;
00416    ao2_ref(details, 1);
00417    ast_channel_lock(chan);
00418    ast_channel_datastore_add(chan, datastore);
00419    ast_channel_unlock(chan);
00420    return details;
00421 }
00422 
00423 unsigned int ast_fax_maxrate(void)
00424 {
00425    return general_options.maxrate;
00426 }
00427 
00428 unsigned int ast_fax_minrate(void)
00429 {
00430    return general_options.minrate;
00431 }
00432 
00433 static int update_modem_bits(enum ast_fax_modems *bits, const char *value)
00434 {     
00435    char *m[5], *tok, *v = (char *)value;
00436    int i = 0, j;
00437 
00438    if (!(tok = strchr(v, ','))) {
00439       m[i++] = v;
00440       m[i] = NULL;
00441    } else {
00442       tok = strtok(v, ", ");
00443       while (tok && (i < 5)) {
00444          m[i++] = tok;
00445          tok = strtok(NULL, ", ");
00446       }
00447       m[i] = NULL;
00448    }
00449 
00450    *bits = 0;
00451    for (j = 0; j < i; j++) {
00452       if (!strcasecmp(m[j], "v17")) {
00453          *bits |= AST_FAX_MODEM_V17;
00454       } else if (!strcasecmp(m[j], "v27")) {
00455          *bits |= AST_FAX_MODEM_V27;
00456       } else if (!strcasecmp(m[j], "v29")) {
00457          *bits |= AST_FAX_MODEM_V29;
00458       } else if (!strcasecmp(m[j], "v34")) {
00459          *bits |= AST_FAX_MODEM_V34;
00460       } else {
00461          ast_log(LOG_WARNING, "ignoring invalid modem setting: '%s', valid options {v17 | v27 | v29 | v34}\n", m[j]);
00462       }
00463    }
00464    return 0;
00465 }
00466 
00467 static int ast_fax_modem_to_str(enum ast_fax_modems bits, char *tbuf, size_t bufsize)
00468 {
00469    int count = 0;
00470 
00471    if (bits & AST_FAX_MODEM_V17) {
00472       strcat(tbuf, "V17");
00473       count++;
00474    }
00475    if (bits & AST_FAX_MODEM_V27) {
00476       if (count) {
00477          strcat(tbuf, ",");
00478       }
00479       strcat(tbuf, "V27");
00480       count++;
00481    }
00482    if (bits & AST_FAX_MODEM_V29) {
00483       if (count) {
00484          strcat(tbuf, ",");
00485       }
00486       strcat(tbuf, "V29");
00487       count++;
00488    }
00489    if (bits & AST_FAX_MODEM_V34) {
00490       if (count) {
00491          strcat(tbuf, ",");
00492       }
00493       strcat(tbuf, "V34");
00494       count++;
00495    }
00496 
00497    return 0;
00498 }
00499 
00500 static int check_modem_rate(enum ast_fax_modems modems, unsigned int rate)
00501 {
00502    switch (rate) {
00503    case 2400:
00504       if (!(modems & (AST_FAX_MODEM_V27 | AST_FAX_MODEM_V34))) {
00505          return 1;
00506       }
00507       break;
00508    case 4800:
00509       if (!(modems & (AST_FAX_MODEM_V27 | AST_FAX_MODEM_V34))) {
00510          return 1;
00511       }
00512       break;
00513    case 7200:
00514    case 9600:
00515       if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V29 | AST_FAX_MODEM_V34))) {
00516          return 1;
00517       }
00518       break;
00519    case 12000:
00520    case 14400:
00521       if (!(modems & (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V34))) {
00522          return 1;
00523       }
00524       break;
00525    case 28800:
00526    case 33600:
00527       if (!(modems & AST_FAX_MODEM_V34)) {
00528          return 1;
00529       }
00530       break;
00531    default:
00532       /* this should never happen */
00533       return 1;
00534    }
00535 
00536    return 0;
00537 }
00538 
00539 /*! \brief register a FAX technology module */
00540 int ast_fax_tech_register(struct ast_fax_tech *tech)
00541 {
00542    struct fax_module *fax;
00543 
00544    if (!(fax = ast_calloc(1, sizeof(*fax)))) {
00545       return -1;
00546    }
00547    fax->tech = tech;
00548    AST_RWLIST_WRLOCK(&faxmodules);
00549    AST_RWLIST_INSERT_TAIL(&faxmodules, fax, list);
00550    AST_RWLIST_UNLOCK(&faxmodules);
00551    ast_module_ref(ast_module_info->self);
00552 
00553    ast_verb(3, "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
00554 
00555    return 0;
00556 }
00557 
00558 /*! \brief unregister a FAX technology module */
00559 void ast_fax_tech_unregister(struct ast_fax_tech *tech)
00560 {
00561    struct fax_module *fax;
00562 
00563    ast_verb(3, "Unregistering FAX module type '%s'\n", tech->type);
00564 
00565    AST_RWLIST_WRLOCK(&faxmodules);
00566    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
00567       if (fax->tech != tech) {
00568          continue;
00569       }
00570       AST_RWLIST_REMOVE_CURRENT(list);
00571       ast_module_unref(ast_module_info->self);
00572       ast_free(fax);
00573       ast_verb(4, "Unregistered FAX module type '%s'\n", tech->type);
00574       break;   
00575    }
00576    AST_RWLIST_TRAVERSE_SAFE_END;
00577    AST_RWLIST_UNLOCK(&faxmodules);
00578 }
00579 
00580 /*! \brief convert a ast_fax_state to a string */
00581 const char *ast_fax_state_to_str(enum ast_fax_state state)
00582 {
00583    switch (state) {
00584    case AST_FAX_STATE_UNINITIALIZED:
00585       return "Uninitialized";
00586    case AST_FAX_STATE_INITIALIZED:
00587       return "Initialized";
00588    case AST_FAX_STATE_OPEN:
00589       return "Open";
00590    case AST_FAX_STATE_ACTIVE:
00591       return "Active";
00592    case AST_FAX_STATE_COMPLETE:
00593       return "Complete";
00594    default:
00595       ast_log(LOG_WARNING, "unhandled FAX state: %d\n", state);
00596       return "Unknown";
00597    }
00598 }
00599 
00600 void ast_fax_log(int level, const char *file, const int line, const char *function, const char *msg)
00601 {
00602    if (fax_logger_level != -1) {
00603       ast_log_dynamic_level(fax_logger_level, "%s", msg);
00604    } else {
00605       ast_log(level, file, line, function, "%s", msg);
00606    }
00607 }
00608 
00609 /*! \brief convert a rate string to a rate */
00610 static unsigned int fax_rate_str_to_int(const char *ratestr)
00611 {
00612    int rate;
00613 
00614    if (sscanf(ratestr, "%d", &rate) != 1) {
00615       ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
00616       return 0;
00617    }
00618    switch (rate) {
00619    case 2400:
00620    case 4800:
00621    case 7200:
00622    case 9600:
00623    case 12000:
00624    case 14400:
00625    case 28800:
00626    case 33600:
00627       return rate;
00628    default:
00629       ast_log(LOG_WARNING, "ignoring invalid rate '%s'.  Valid options are {2400 | 4800 | 7200 | 9600 | 12000 | 14400 | 28800 | 33600}\n", ratestr);
00630       return 0;
00631    }
00632 }
00633 
00634 /*! \brief destroy a FAX session structure */
00635 static void destroy_session(void *session)
00636 {
00637    struct ast_fax_session *s = session;
00638 
00639    if (s->tech) {
00640       if (s->tech_pvt) {
00641          s->tech->destroy_session(s);
00642       }
00643       ast_module_unref(s->tech->module);
00644    }
00645 
00646    if (s->details) {
00647       ao2_ref(s->details, -1);
00648    }
00649    
00650    if (s->debug_info) {
00651       ast_dsp_free(s->debug_info->dsp);
00652       ast_free(s->debug_info);
00653    }
00654 
00655    if (s->smoother) {
00656       ast_smoother_free(s->smoother);
00657    }
00658 
00659    ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
00660 
00661    ast_free(s->channame);
00662    ast_free(s->chan_uniqueid);
00663 }
00664 
00665 /*! \brief create a FAX session */
00666 static struct ast_fax_session *fax_session_new(struct ast_fax_session_details *details, struct ast_channel *chan)
00667 {
00668    struct ast_fax_session *s;
00669    struct fax_module *faxmod;
00670 
00671    if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
00672       return NULL;
00673    }
00674 
00675    ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
00676 
00677    if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
00678       if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
00679          ao2_ref(s, -1);
00680          return NULL;
00681       }
00682       if (!(s->debug_info->dsp = ast_dsp_new())) {
00683          ast_free(s->debug_info);
00684          s->debug_info = NULL;
00685          ao2_ref(s, -1);
00686          return NULL;
00687       }
00688       ast_dsp_set_threshold(s->debug_info->dsp, 128);
00689    }  
00690 
00691    if (!(s->channame = ast_strdup(chan->name))) {
00692       ao2_ref(s, -1);
00693       return NULL;
00694    }
00695 
00696    if (!(s->chan_uniqueid = ast_strdup(chan->uniqueid))) {
00697       ao2_ref(s, -1);
00698       return NULL;
00699    }
00700 
00701    s->chan = chan;
00702    s->details = details;
00703    ao2_ref(s->details, 1);
00704    s->state = AST_FAX_STATE_UNINITIALIZED;
00705 
00706    details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
00707 
00708    /* locate a FAX technology module that can handle said requirements */
00709    AST_RWLIST_RDLOCK(&faxmodules);
00710    AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
00711       if ((faxmod->tech->caps & details->caps) != details->caps) {
00712          continue;
00713       }
00714       ast_debug(4, "Requesting a new FAX session from '%s'.\n", faxmod->tech->description);
00715       ast_module_ref(faxmod->tech->module);
00716       s->tech = faxmod->tech;
00717       break;
00718    }
00719    AST_RWLIST_UNLOCK(&faxmodules);
00720 
00721    if (!faxmod) {
00722       ast_log(LOG_ERROR, "Could not locate a FAX technology module with capabilities (0x%X)\n", details->caps);
00723       ao2_ref(s, -1);
00724       return NULL;
00725    }
00726    if (!(s->tech_pvt = s->tech->new_session(s, NULL))) {
00727       ast_log(LOG_ERROR, "FAX session failed to initialize.\n");
00728       ao2_ref(s, -1);
00729       ast_module_unref(faxmod->tech->module);
00730       return NULL;
00731    }
00732    /* link the session to the session container */
00733    if (!(ao2_link(faxregistry.container, s))) {
00734       ast_log(LOG_ERROR, "failed to add FAX session '%d' to container.\n", s->id);
00735       ao2_ref(s, -1);
00736       ast_module_unref(faxmod->tech->module);
00737       return NULL;
00738    }
00739    ast_debug(4, "channel '%s' using FAX session '%d'\n", s->channame, s->id);
00740 
00741    return s;
00742 }
00743 
00744 static void get_manager_event_info(struct ast_channel *chan, struct manager_event_info *info)
00745 {
00746    pbx_substitute_variables_helper(chan, "${CONTEXT}", info->context, sizeof(info->context));
00747    pbx_substitute_variables_helper(chan, "${EXTEN}", info->exten, sizeof(info->exten));
00748    pbx_substitute_variables_helper(chan, "${CALLERID(num)}", info->cid, sizeof(info->cid));
00749 }
00750 
00751 
00752 /* \brief Generate a string of filenames using the given prefix and separator.
00753  * \param details the fax session details
00754  * \param prefix the prefix to each filename
00755  * \param separator the separator between filenames
00756  *
00757  * This function generates a string of filenames from the given details
00758  * structure and using the given prefix and separator.
00759  *
00760  * \retval NULL there was an error generating the string
00761  * \return the string generated string
00762  */
00763 static char *generate_filenames_string(struct ast_fax_session_details *details, char *prefix, char *separator)
00764 {
00765    char *filenames, *c;
00766    size_t size = 0;
00767    int first = 1;
00768    struct ast_fax_document *doc;
00769 
00770    /* don't process empty lists */
00771    if (AST_LIST_EMPTY(&details->documents)) {
00772       return NULL;
00773    }
00774 
00775    /* Calculate the total length of all of the file names */
00776    AST_LIST_TRAVERSE(&details->documents, doc, next) {
00777       size += strlen(separator) + strlen(prefix) + strlen(doc->filename);
00778    }
00779    size += 1; /* add space for the terminating null */
00780 
00781    if (!(filenames = ast_malloc(size))) {
00782       return NULL;
00783    }
00784    c = filenames;
00785 
00786    ast_build_string(&c, &size, "%s%s", prefix, AST_LIST_FIRST(&details->documents)->filename);
00787    AST_LIST_TRAVERSE(&details->documents, doc, next) {
00788       if (first) {
00789          first = 0;
00790          continue;
00791       }
00792 
00793       ast_build_string(&c, &size, "%s%s%s", separator, prefix, doc->filename);
00794    }
00795 
00796    return filenames;
00797 }
00798 
00799 /*! \brief send a FAX status manager event */
00800 static int report_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details, const char *status)
00801 {
00802    char *filenames = generate_filenames_string(details, "FileName: ", "\r\n");
00803    if (!filenames) {
00804       return 1;
00805    }
00806 
00807    ast_channel_lock(chan);
00808    if (details->option.statusevents) {
00809       struct manager_event_info info;
00810 
00811       get_manager_event_info(chan, &info);
00812       manager_event(EVENT_FLAG_CALL,
00813                (details->caps & AST_FAX_TECH_RECEIVE) ? "ReceiveFAXStatus" : "SendFAXStatus",
00814                "Status: %s\r\n"
00815                "Channel: %s\r\n"
00816                "Context: %s\r\n"
00817                "Exten: %s\r\n"
00818                "CallerID: %s\r\n"
00819                "LocalStationID: %s\r\n"
00820                "%s\r\n",
00821                status,
00822                chan->name,
00823                info.context,
00824                info.exten,
00825                info.cid,
00826                details->localstationid,
00827                filenames);
00828    }
00829    ast_channel_unlock(chan);
00830    ast_free(filenames);
00831 
00832    return 0;
00833 }
00834 
00835 /*! \brief Set fax related channel variables. */
00836 static void set_channel_variables(struct ast_channel *chan, struct ast_fax_session_details *details)
00837 {
00838    char buf[10];
00839    pbx_builtin_setvar_helper(chan, "FAXSTATUS", S_OR(details->result, NULL));
00840    pbx_builtin_setvar_helper(chan, "FAXERROR", S_OR(details->error, NULL));
00841    pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", S_OR(details->resultstr, NULL));
00842    pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", S_OR(details->remotestationid, NULL));
00843    pbx_builtin_setvar_helper(chan, "FAXBITRATE", S_OR(details->transfer_rate, NULL));
00844    pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", S_OR(details->resolution, NULL));
00845 
00846    snprintf(buf, sizeof(buf), "%d", details->pages_transferred);
00847    pbx_builtin_setvar_helper(chan, "FAXPAGES", buf);
00848 }
00849 
00850 #define GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason) \
00851    do {  \
00852       ast_string_field_set(fax->details, result, S_OR(fax->details->result, "FAILED")); \
00853       ast_string_field_set(fax->details, resultstr, S_OR(fax->details->resultstr, reason)); \
00854       ast_string_field_set(fax->details, error, S_OR(fax->details->error, errorstr)); \
00855       set_channel_variables(chan, fax->details); \
00856    } while (0)
00857 
00858 #define GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason) \
00859    do {  \
00860       GENERIC_FAX_EXEC_SET_VARS(fax, chan, errorstr, reason); \
00861       res = ms = -1; \
00862    } while (0)
00863 
00864 #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason) \
00865    do {  \
00866       ast_log(LOG_ERROR, "channel '%s' FAX session '%d' failure, reason: '%s' (%s)\n", chan->name, fax->id, reason, errorstr); \
00867       GENERIC_FAX_EXEC_ERROR_QUIET(fax, chan, errorstr, reason); \
00868    } while (0)
00869 
00870 static void t38_parameters_ast_to_fax(struct ast_fax_t38_parameters *dst, const struct ast_control_t38_parameters *src)
00871 {
00872    dst->version = src->version;
00873    dst->max_ifp = src->max_ifp;
00874    dst->rate = src->rate;
00875    dst->rate_management = src->rate_management;
00876    dst->fill_bit_removal = src->fill_bit_removal;
00877    dst->transcoding_mmr = src->transcoding_mmr;
00878    dst->transcoding_jbig = src->transcoding_jbig;
00879 }
00880 
00881 static void t38_parameters_fax_to_ast(struct ast_control_t38_parameters *dst, const struct ast_fax_t38_parameters *src)
00882 {
00883    dst->version = src->version;
00884    dst->max_ifp = src->max_ifp;
00885    dst->rate = src->rate;
00886    dst->rate_management = src->rate_management;
00887    dst->fill_bit_removal = src->fill_bit_removal;
00888    dst->transcoding_mmr = src->transcoding_mmr;
00889    dst->transcoding_jbig = src->transcoding_jbig;
00890 }
00891 
00892 static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
00893 {
00894    switch (ast_channel_get_t38_state(chan)) {
00895    case T38_STATE_UNKNOWN:
00896       details->caps |= AST_FAX_TECH_T38;
00897       break;
00898    case T38_STATE_UNAVAILABLE:
00899       details->caps |= AST_FAX_TECH_AUDIO;
00900       break;
00901    case T38_STATE_NEGOTIATING: {
00902       /* the other end already sent us a T.38 reinvite, so we need to prod the channel
00903        * driver into resending their parameters to us if it supports doing so... if
00904        * not, we can't proceed, because we can't create a proper reply without them.
00905        * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
00906        * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
00907        * that gets called after this one completes
00908        */
00909       struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
00910       if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
00911          ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", chan->name);
00912          return -1;
00913       }
00914       details->caps |= AST_FAX_TECH_T38;
00915       break;
00916    }
00917    default:
00918       ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", chan->name);
00919       return -1;
00920    }
00921 
00922    return 0;
00923 }
00924 
00925 static int disable_t38(struct ast_channel *chan)
00926 {
00927    int ms;
00928    struct ast_frame *frame = NULL;
00929    struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
00930 
00931    ast_debug(1, "Shutting down T.38 on %s\n", chan->name);
00932    if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
00933       ast_log(LOG_WARNING, "error while disabling T.38 on channel '%s'\n", chan->name);
00934       return -1;
00935    }
00936 
00937    /* wait up to five seconds for negotiation to complete */
00938    ms = 5000;
00939 
00940    while (ms > 0) {
00941       ms = ast_waitfor(chan, ms);
00942       if (ms < 0) {
00943          ast_log(LOG_WARNING, "error while disabling T.38 on channel '%s'\n", chan->name);
00944          return -1;
00945       }
00946 
00947       if (ms == 0) { /* all done, nothing happened */
00948          ast_log(LOG_WARNING, "channel '%s' timed-out during T.38 shutdown\n", chan->name);
00949          break;
00950       }
00951 
00952       if (!(frame = ast_read(chan))) {
00953          return -1;
00954       }
00955       if ((frame->frametype == AST_FRAME_CONTROL) &&
00956           (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
00957           (frame->datalen == sizeof(t38_parameters))) {
00958          struct ast_control_t38_parameters *parameters = frame->data.ptr;
00959 
00960          switch (parameters->request_response) {
00961          case AST_T38_TERMINATED:
00962             ast_debug(1, "Shut down T.38 on %s\n", chan->name);
00963             break;
00964          case AST_T38_REFUSED:
00965             ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", chan->name);
00966             ast_frfree(frame);
00967             return -1;
00968          default:
00969             ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", chan->name);
00970             ast_frfree(frame);
00971             return -1;
00972          }
00973          ast_frfree(frame);
00974          break;
00975       }
00976       ast_frfree(frame);
00977    }
00978 
00979    return 0;
00980 }
00981 
00982 static struct ast_control_t38_parameters our_t38_parameters = {
00983    .version = 0,
00984    .max_ifp = 400,
00985    .rate = AST_T38_RATE_14400,
00986    .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
00987 };
00988 
00989 /*! \brief this is the generic FAX session handling function */
00990 static int generic_fax_exec(struct ast_channel *chan, struct ast_fax_session_details *details)
00991 {
00992    int ms;
00993    int timeout = RES_FAX_TIMEOUT;
00994    int res = 0, chancount;
00995    unsigned int expected_frametype = -1;
00996    union ast_frame_subclass expected_framesubclass = { .integer = -1 };
00997    unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
00998    struct ast_control_t38_parameters t38_parameters;
00999    const char *tempvar;
01000    struct ast_fax_session *fax = NULL;
01001    struct ast_frame *frame = NULL;
01002    struct ast_channel *c = chan;
01003    unsigned int orig_write_format = 0, orig_read_format = 0;
01004 
01005    chancount = 1;
01006 
01007    /* create the FAX session */
01008    if (!(fax = fax_session_new(details, chan))) {
01009       ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
01010       report_fax_status(chan, details, "No Available Resource");
01011       return -1;
01012    }
01013 
01014    ast_channel_lock(chan);
01015    /* update session details */  
01016    if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
01017       ast_string_field_set(details, headerinfo, tempvar);
01018    }
01019    if (ast_strlen_zero(details->localstationid)) {
01020       tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
01021       ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
01022    }
01023    ast_channel_unlock(chan);
01024 
01025    report_fax_status(chan, details, "Allocating Resources");
01026 
01027    if (details->caps & AST_FAX_TECH_AUDIO) {
01028       expected_frametype = AST_FRAME_VOICE;;
01029       expected_framesubclass.codec = AST_FORMAT_SLINEAR;
01030       orig_write_format = chan->writeformat;
01031       if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
01032          ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", chan->name);
01033          ao2_lock(faxregistry.container);
01034          ao2_unlink(faxregistry.container, fax);
01035          ao2_unlock(faxregistry.container);
01036          ao2_ref(fax, -1);
01037          ast_channel_unlock(chan);
01038          return -1;
01039       }
01040       orig_read_format = chan->readformat;
01041       if (ast_set_read_format(chan, AST_FORMAT_SLINEAR) < 0) {
01042          ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", chan->name);
01043          ao2_lock(faxregistry.container);
01044          ao2_unlink(faxregistry.container, fax);
01045          ao2_unlock(faxregistry.container);
01046          ao2_ref(fax, -1);
01047          ast_channel_unlock(chan);
01048          return -1;
01049       }
01050       if (fax->smoother) {
01051          ast_smoother_free(fax->smoother);
01052          fax->smoother = NULL;
01053       }
01054       if (!(fax->smoother = ast_smoother_new(320))) {
01055          ast_log(LOG_WARNING, "Channel '%s' FAX session '%d' failed to obtain a smoother.\n", chan->name, fax->id);
01056       }
01057    } else {
01058       expected_frametype = AST_FRAME_MODEM;
01059       expected_framesubclass.codec = AST_MODEM_T38;
01060    }
01061 
01062    if (fax->debug_info) {
01063       fax->debug_info->base_tv = ast_tvnow();
01064    }
01065 
01066    /* reset our result fields just in case the fax tech driver wants to
01067     * set custom error messages */
01068    ast_string_field_set(details, result, "");
01069    ast_string_field_set(details, resultstr, "");
01070    ast_string_field_set(details, error, "");
01071    set_channel_variables(chan, details);
01072 
01073    if (fax->tech->start_session(fax) < 0) {
01074       GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
01075    }
01076 
01077    report_fax_status(chan, details, "FAX Transmission In Progress");
01078 
01079    ast_debug(5, "channel %s will wait on FAX fd %d\n", chan->name, fax->fd);
01080 
01081    /* handle frames for the session */
01082    ms = 1000;
01083    while ((res > -1) && (ms > -1) && (timeout > 0)) {
01084       struct ast_channel *ready_chan;
01085       int ofd, exception;
01086 
01087       ms = 1000;
01088       errno = 0;
01089       ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
01090       if (ready_chan) {
01091          if (!(frame = ast_read(chan))) {
01092             /* the channel is probably gone, so lets stop polling on it and let the
01093              * FAX session complete before we exit the application.  if needed,
01094              * send the FAX stack silence so the modems can finish their session without
01095              * any problems */
01096             ast_log(LOG_NOTICE, "Channel '%s' did not return a frame; probably hung up.\n", chan->name);
01097             GENERIC_FAX_EXEC_SET_VARS(fax, chan, "HANGUP", "remote channel hungup");
01098             c = NULL;
01099             chancount = 0;
01100             timeout -= (1000 - ms);
01101             fax->tech->cancel_session(fax);
01102             if (fax->tech->generate_silence) {
01103                fax->tech->generate_silence(fax);
01104             }
01105             continue;
01106          }
01107 
01108          if ((frame->frametype == AST_FRAME_CONTROL) &&
01109              (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
01110              (frame->datalen == sizeof(t38_parameters))) {
01111             unsigned int was_t38 = t38negotiated;
01112             struct ast_control_t38_parameters *parameters = frame->data.ptr;
01113             
01114             switch (parameters->request_response) {
01115             case AST_T38_REQUEST_NEGOTIATE:
01116                /* the other end has requested a switch to T.38, so reply that we are willing, if we can
01117                 * do T.38 as well
01118                 */
01119                t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01120                t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
01121                ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
01122                break;
01123             case AST_T38_NEGOTIATED:
01124                t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
01125                t38negotiated = 1;
01126                break;
01127             default:
01128                break;
01129             }
01130             if (t38negotiated && !was_t38) {
01131                fax->tech->switch_to_t38(fax);
01132                details->caps &= ~AST_FAX_TECH_AUDIO;
01133                expected_frametype = AST_FRAME_MODEM;
01134                expected_framesubclass.codec = AST_MODEM_T38;
01135                if (fax->smoother) {
01136                   ast_smoother_free(fax->smoother);
01137                   fax->smoother = NULL;
01138                }
01139                
01140                report_fax_status(chan, details, "T.38 Negotiated");
01141                
01142                ast_verb(3, "Channel '%s' switched to T.38 FAX session '%d'.\n", chan->name, fax->id);
01143             }
01144          } else if ((frame->frametype == expected_frametype) &&
01145                (!memcmp(&frame->subclass, &expected_framesubclass, sizeof(frame->subclass)))) {
01146             struct ast_frame *f;
01147             
01148             if (fax->smoother) {
01149                /* push the frame into a smoother */
01150                if (ast_smoother_feed(fax->smoother, frame) < 0) {
01151                   GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
01152                }
01153                while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
01154                   if (fax->debug_info) {
01155                      debug_check_frame_for_silence(fax, 1, f);
01156                   }
01157                   /* write the frame to the FAX stack */
01158                   fax->tech->write(fax, f);
01159                   fax->frames_received++;
01160                   if (f != frame) {
01161                      ast_frfree(f);
01162                   }
01163                }
01164             } else {
01165                /* write the frame to the FAX stack */
01166                fax->tech->write(fax, frame);
01167                fax->frames_received++;
01168             }
01169             timeout = RES_FAX_TIMEOUT;
01170          }
01171          ast_frfree(frame);
01172       } else if (ofd == fax->fd) {
01173          /* read a frame from the FAX stack and send it out the channel.
01174           * the FAX stack will return a NULL if the FAX session has already completed */
01175          if (!(frame = fax->tech->read(fax))) {
01176             break;
01177          }
01178 
01179          if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
01180             debug_check_frame_for_silence(fax, 0, frame);
01181          }
01182 
01183          ast_write(chan, frame);
01184          fax->frames_sent++;
01185          ast_frfree(frame);
01186          timeout = RES_FAX_TIMEOUT;
01187       } else {
01188          if (ms && (ofd < 0)) {
01189             if ((errno == 0) || (errno == EINTR)) {
01190                timeout -= (1000 - ms);
01191                if (timeout <= 0)
01192                   GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
01193                continue;
01194             } else {
01195                ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", chan->name);
01196                GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "error polling data");
01197                res = ms;
01198                break;
01199             }
01200          } else {
01201             /* nothing happened */
01202             if (timeout > 0) {
01203                timeout -= 1000;
01204                if (timeout <= 0)
01205                   GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
01206                continue;
01207             } else {
01208                ast_log(LOG_WARNING, "channel '%s' timed-out during the FAX transmission.\n", chan->name);
01209                GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
01210                break;
01211             }
01212          }
01213       }
01214    }
01215    ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, ms: %d, res: %d }\n", chan->name, timeout, ms, res);
01216 
01217    set_channel_variables(chan, details);
01218 
01219    ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
01220    if (!strcasecmp(details->result, "FAILED")) {
01221       ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
01222    }
01223 
01224    if (fax) {
01225       ao2_lock(faxregistry.container);
01226       ao2_unlink(faxregistry.container, fax);
01227       ao2_unlock(faxregistry.container);
01228       ao2_ref(fax, -1);
01229    }
01230 
01231    /* if the channel is still alive, and we changed its read/write formats,
01232     * restore them now
01233     */
01234    if (chancount) {
01235       if (orig_read_format) {
01236          ast_set_read_format(chan, orig_read_format);
01237       }
01238       if (orig_write_format) {
01239          ast_set_write_format(chan, orig_write_format);
01240       }
01241    }
01242 
01243    /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
01244    return chancount;
01245 }
01246 
01247 static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
01248 {
01249    int ms;
01250    struct ast_frame *frame = NULL;
01251    struct ast_control_t38_parameters t38_parameters;
01252 
01253    t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
01254 
01255    /* don't send any audio if we've already received a T.38 reinvite */
01256    if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
01257       /* generate 3 seconds of CED */
01258       if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
01259          ast_log(LOG_ERROR, "error generating CED tone on %s\n", chan->name);
01260          return -1;
01261       }
01262 
01263       ms = 3000;
01264       while (ms > 0) {
01265          ms = ast_waitfor(chan, ms);
01266          if (ms < 0) {
01267             ast_log(LOG_ERROR, "error while generating CED tone on %s\n", chan->name);
01268             ast_playtones_stop(chan);
01269             return -1;
01270          }
01271 
01272          if (ms == 0) { /* all done, nothing happened */
01273             break;
01274          }
01275 
01276          if (!(frame = ast_read(chan))) {
01277             ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", chan->name);
01278             ast_playtones_stop(chan);
01279             return -1;
01280          }
01281 
01282          if ((frame->frametype == AST_FRAME_CONTROL) &&
01283              (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
01284              (frame->datalen == sizeof(t38_parameters))) {
01285             struct ast_control_t38_parameters *parameters = frame->data.ptr;
01286 
01287             switch (parameters->request_response) {
01288             case AST_T38_REQUEST_NEGOTIATE:
01289                /* the other end has requested a switch to T.38, so reply that we are willing, if we can
01290                 * do T.38 as well
01291                 */
01292                t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01293                t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
01294                ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
01295                ast_playtones_stop(chan);
01296                break;
01297             case AST_T38_NEGOTIATED:
01298                ast_log(LOG_NOTICE, "Negotiated T.38 for receive on %s\n", chan->name);
01299                t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
01300                details->caps &= ~AST_FAX_TECH_AUDIO;
01301                report_fax_status(chan, details, "T.38 Negotiated");
01302                break;
01303             default:
01304                break;
01305             }
01306          }
01307          ast_frfree(frame);
01308       }
01309 
01310       ast_playtones_stop(chan);
01311    }
01312 
01313    /* if T.38 was negotiated, we are done initializing */
01314    if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
01315       return 0;
01316    }
01317 
01318    /* request T.38 */
01319    ast_log(LOG_NOTICE, "Negotiating T.38 for receive on %s\n", chan->name);
01320 
01321    /* wait up to five seconds for negotiation to complete */
01322    ms = 5000;
01323 
01324    /* set parameters based on the session's parameters */
01325    t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01326    t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
01327    if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
01328       return -1;
01329    }
01330 
01331    while (ms > 0) {
01332       ms = ast_waitfor(chan, ms);
01333       if (ms < 0) {
01334          ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
01335          return -1;
01336       }
01337 
01338       if (ms == 0) { /* all done, nothing happened */
01339          ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", chan->name);
01340          details->caps &= ~AST_FAX_TECH_T38;
01341          break;
01342       }
01343 
01344       if (!(frame = ast_read(chan))) {
01345          ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
01346          return -1;
01347       }
01348 
01349       if ((frame->frametype == AST_FRAME_CONTROL) &&
01350             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
01351             (frame->datalen == sizeof(t38_parameters))) {
01352          struct ast_control_t38_parameters *parameters = frame->data.ptr;
01353 
01354          switch (parameters->request_response) {
01355          case AST_T38_REQUEST_NEGOTIATE:
01356             t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01357             t38_parameters.request_response = AST_T38_NEGOTIATED;
01358             ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
01359             break;
01360          case AST_T38_NEGOTIATED:
01361             ast_log(LOG_NOTICE, "Negotiated T.38 for receive on %s\n", chan->name);
01362             t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
01363             details->caps &= ~AST_FAX_TECH_AUDIO;
01364             report_fax_status(chan, details, "T.38 Negotiated");
01365             ms = 0;
01366             break;
01367          case AST_T38_REFUSED:
01368             ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", chan->name);
01369             details->caps &= ~AST_FAX_TECH_T38;
01370             ms = 0;
01371             break;
01372          default:
01373             ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", chan->name);
01374             details->caps &= ~AST_FAX_TECH_T38;
01375             ms = 0;
01376             break;
01377          }
01378       }
01379       ast_frfree(frame);
01380    }
01381 
01382    /* if T.38 was negotiated, we are done initializing */
01383    if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
01384       return 0;
01385    }
01386 
01387    /* if we made it here, then T.38 failed, check the 'f' flag */
01388    if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
01389       ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", chan->name);
01390       return -1;
01391    }
01392 
01393    /* ok, audio fallback is allowed */
01394    details->caps |= AST_FAX_TECH_AUDIO;
01395 
01396    return 0;
01397 }
01398 
01399 /*! \brief initiate a receive FAX session */
01400 static int receivefax_exec(struct ast_channel *chan, const char *data)
01401 {
01402    char *parse, modems[128] = "";
01403    int channel_alive;
01404    struct ast_fax_session_details *details;
01405    struct ast_fax_document *doc;
01406    AST_DECLARE_APP_ARGS(args,
01407       AST_APP_ARG(filename);
01408       AST_APP_ARG(options);
01409    );
01410    struct ast_flags opts = { 0, };
01411    struct manager_event_info info;
01412 
01413    /* initialize output channel variables */
01414    pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
01415    pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
01416    pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
01417    pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
01418    pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
01419 
01420    /* Get a FAX session details structure from the channel's FAX datastore and create one if
01421     * it does not already exist. */
01422    if (!(details = find_or_create_details(chan))) {
01423       pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
01424       pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
01425       ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
01426       return -1;
01427    }
01428 
01429    ast_string_field_set(details, result, "FAILED");
01430    ast_string_field_set(details, resultstr, "error starting fax session");
01431    ast_string_field_set(details, error, "INIT_ERROR");
01432    set_channel_variables(chan, details);
01433 
01434    if (details->maxrate < details->minrate) {
01435       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01436       ast_string_field_set(details, resultstr, "maxrate is less than minrate");
01437       set_channel_variables(chan, details);
01438       ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
01439       ao2_ref(details, -1);
01440       return -1;
01441    }
01442 
01443    if (check_modem_rate(details->modems, details->minrate)) {
01444       ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
01445       ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
01446       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01447       ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
01448       set_channel_variables(chan, details);
01449       ao2_ref(details, -1);
01450       return -1;
01451    }
01452 
01453    if (check_modem_rate(details->modems, details->maxrate)) {
01454       ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
01455       ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
01456       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01457       ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
01458       set_channel_variables(chan, details);
01459       ao2_ref(details, -1);
01460       return -1;
01461    }
01462 
01463    if (ast_strlen_zero(data)) {
01464       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01465       ast_string_field_set(details, resultstr, "invalid arguments");
01466       set_channel_variables(chan, details);
01467       ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
01468       ao2_ref(details, -1);
01469       return -1;
01470    }
01471    parse = ast_strdupa(data);
01472    AST_STANDARD_APP_ARGS(args, parse);
01473 
01474    if (!ast_strlen_zero(args.options) &&
01475        ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
01476       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01477       ast_string_field_set(details, resultstr, "invalid arguments");
01478       set_channel_variables(chan, details);
01479       ao2_ref(details, -1);
01480       return -1;
01481    }
01482    if (ast_strlen_zero(args.filename)) {
01483       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01484       ast_string_field_set(details, resultstr, "invalid arguments");
01485       set_channel_variables(chan, details);
01486       ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
01487       ao2_ref(details, -1);
01488       return -1;
01489    }
01490 
01491    /* check for unsupported FAX application options */
01492    if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
01493       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01494       ast_string_field_set(details, resultstr, "invalid arguments");
01495       set_channel_variables(chan, details);
01496       ast_log(LOG_WARNING, "%s does not support polling\n", app_receivefax);
01497       ao2_ref(details, -1);
01498       return -1;
01499    }
01500    
01501    /* make sure the channel is up */
01502    if (chan->_state != AST_STATE_UP) {
01503       if (ast_answer(chan)) {
01504          ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", chan->name);
01505          ao2_ref(details, -1);
01506          return -1;
01507       }
01508    }
01509 
01510    ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
01511 
01512    pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
01513    pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
01514 
01515    if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
01516       ast_string_field_set(details, error, "MEMORY_ERROR");
01517       ast_string_field_set(details, resultstr, "error allocating memory");
01518       set_channel_variables(chan, details);
01519       ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
01520       ao2_ref(details, -1);
01521       return -1;
01522    }
01523 
01524    strcpy(doc->filename, args.filename);
01525    AST_LIST_INSERT_TAIL(&details->documents, doc, next);
01526 
01527    ast_verb(3, "Channel '%s' receiving FAX '%s'\n", chan->name, args.filename);
01528 
01529    details->caps = AST_FAX_TECH_RECEIVE;
01530 
01531    /* check for debug */
01532    if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
01533       details->option.debug = AST_FAX_OPTFLAG_TRUE;
01534    }
01535 
01536    /* check for request for status events */
01537    if (ast_test_flag(&opts, OPT_STATUS)) {
01538       details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
01539    }
01540 
01541    if ((ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE) ||
01542        ast_test_flag(&opts, OPT_ALLOWAUDIO)) {
01543       details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
01544    }
01545 
01546    if (set_fax_t38_caps(chan, details)) {
01547       ast_string_field_set(details, error, "T38_NEG_ERROR");
01548       ast_string_field_set(details, resultstr, "error negotiating T.38");
01549       set_channel_variables(chan, details);
01550       ao2_ref(details, -1);
01551       return -1;
01552    }
01553 
01554    if (details->caps & AST_FAX_TECH_T38) {
01555       if (receivefax_t38_init(chan, details)) {
01556          ast_string_field_set(details, error, "T38_NEG_ERROR");
01557          ast_string_field_set(details, resultstr, "error negotiating T.38");
01558          set_channel_variables(chan, details);
01559          ao2_ref(details, -1);
01560          ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", chan->name);
01561          return -1;
01562       }
01563    } else {
01564       details->option.send_ced = 1;
01565    }
01566 
01567    if ((channel_alive = generic_fax_exec(chan, details)) < 0) {
01568       ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
01569    }
01570 
01571    if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
01572       if (disable_t38(chan)) {
01573          ast_log(LOG_WARNING, "error disabling T.38 mode on %s\n", chan->name);
01574       }
01575    }
01576 
01577    /* send out the AMI completion event */
01578    ast_channel_lock(chan);
01579 
01580    get_manager_event_info(chan, &info);
01581    manager_event(EVENT_FLAG_CALL,
01582             "ReceiveFAX", 
01583             "Channel: %s\r\n"
01584             "Context: %s\r\n"
01585             "Exten: %s\r\n"
01586             "CallerID: %s\r\n"
01587             "RemoteStationID: %s\r\n"
01588             "LocalStationID: %s\r\n"
01589             "PagesTransferred: %s\r\n"
01590             "Resolution: %s\r\n"
01591             "TransferRate: %s\r\n"
01592             "FileName: %s\r\n",
01593             chan->name,
01594             info.context,
01595             info.exten,
01596             info.cid,
01597             pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"),
01598             pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"),
01599             pbx_builtin_getvar_helper(chan, "FAXPAGES"),
01600             pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"),
01601             pbx_builtin_getvar_helper(chan, "FAXBITRATE"),
01602             args.filename);
01603    ast_channel_unlock(chan);
01604 
01605    ao2_ref(details, -1);
01606 
01607    /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
01608    return (!channel_alive) ? -1 : 0;
01609 }
01610 
01611 static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
01612 {
01613    int ms;
01614    struct ast_frame *frame = NULL;
01615    struct ast_control_t38_parameters t38_parameters;
01616 
01617    t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
01618 
01619    /* send CNG tone while listening for the receiver to initiate a switch
01620     * to T.38 mode; if they do, stop sending the CNG tone and proceed with
01621     * the switch.
01622     *
01623     * 10500 is enough time for 3 CNG tones
01624     */
01625    ms = 10500;
01626 
01627    /* don't send any audio if we've already received a T.38 reinvite */
01628    if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
01629       if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
01630          ast_log(LOG_ERROR, "error generating CNG tone on %s\n", chan->name);
01631          return -1;
01632       }
01633    }
01634 
01635    while (ms > 0) {
01636       ms = ast_waitfor(chan, ms);
01637       if (ms < 0) {
01638          ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", chan->name);
01639          ast_playtones_stop(chan);
01640          return -1;
01641       }
01642 
01643       if (ms == 0) { /* all done, nothing happened */
01644          break;
01645       }
01646 
01647       if (!(frame = ast_read(chan))) {
01648          ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", chan->name);
01649          ast_playtones_stop(chan);
01650          return -1;
01651       }
01652 
01653       if ((frame->frametype == AST_FRAME_CONTROL) &&
01654             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
01655             (frame->datalen == sizeof(t38_parameters))) {
01656          struct ast_control_t38_parameters *parameters = frame->data.ptr;
01657 
01658          switch (parameters->request_response) {
01659          case AST_T38_REQUEST_NEGOTIATE:
01660             /* the other end has requested a switch to T.38, so reply that we are willing, if we can
01661              * do T.38 as well
01662              */
01663             t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01664             t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
01665             ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
01666             ast_playtones_stop(chan);
01667             break;
01668          case AST_T38_NEGOTIATED:
01669             ast_log(LOG_NOTICE, "Negotiated T.38 for send on %s\n", chan->name);
01670             t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
01671             details->caps &= ~AST_FAX_TECH_AUDIO;
01672             report_fax_status(chan, details, "T.38 Negotiated");
01673             ms = 0;
01674             break;
01675          default:
01676             break;
01677          }
01678       }
01679       ast_frfree(frame);
01680    }
01681 
01682    ast_playtones_stop(chan);
01683 
01684    if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
01685       return 0;
01686    }
01687 
01688    /* T.38 negotiation did not happen, initiate a switch if requested */
01689    if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
01690       ast_log(LOG_NOTICE, "Negotiating T.38 for send on %s\n", chan->name);
01691 
01692       /* wait up to five seconds for negotiation to complete */
01693       ms = 5000;
01694 
01695       /* set parameters based on the session's parameters */
01696       t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01697       t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
01698       if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
01699          return -1;
01700       }
01701 
01702       while (ms > 0) {
01703          ms = ast_waitfor(chan, ms);
01704          if (ms < 0) {
01705             ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
01706             return -1;
01707          }
01708 
01709          if (ms == 0) { /* all done, nothing happened */
01710             ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", chan->name);
01711             details->caps &= ~AST_FAX_TECH_T38;
01712             break;
01713          }
01714 
01715          if (!(frame = ast_read(chan))) {
01716             ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
01717             return -1;
01718          }
01719 
01720          if ((frame->frametype == AST_FRAME_CONTROL) &&
01721                (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
01722                (frame->datalen == sizeof(t38_parameters))) {
01723             struct ast_control_t38_parameters *parameters = frame->data.ptr;
01724 
01725             switch (parameters->request_response) {
01726             case AST_T38_REQUEST_NEGOTIATE:
01727                t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01728                t38_parameters.request_response = AST_T38_NEGOTIATED;
01729                ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
01730                break;
01731             case AST_T38_NEGOTIATED:
01732                ast_log(LOG_NOTICE, "Negotiated T.38 for receive on %s\n", chan->name);
01733                t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
01734                details->caps &= ~AST_FAX_TECH_AUDIO;
01735                report_fax_status(chan, details, "T.38 Negotiated");
01736                ms = 0;
01737                break;
01738             case AST_T38_REFUSED:
01739                ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", chan->name);
01740                details->caps &= ~AST_FAX_TECH_T38;
01741                ms = 0;
01742                break;
01743             default:
01744                ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", chan->name);
01745                details->caps &= ~AST_FAX_TECH_T38;
01746                ms = 0;
01747                break;
01748             }
01749          }
01750          ast_frfree(frame);
01751       }
01752 
01753       /* if T.38 was negotiated, we are done initializing */
01754       if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
01755          return 0;
01756       }
01757 
01758       /* send one more CNG tone to get audio going again for some
01759        * carriers if we are going to fall back to audio mode */
01760       if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
01761          if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
01762             ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", chan->name);
01763             return -1;
01764          }
01765 
01766          ms = 3500;
01767          while (ms > 0) {
01768             ms = ast_waitfor(chan, ms);
01769             if (ms < 0) {
01770                ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", chan->name);
01771                ast_playtones_stop(chan);
01772                return -1;
01773             }
01774 
01775             if (ms == 0) { /* all done, nothing happened */
01776                break;
01777             }
01778 
01779             if (!(frame = ast_read(chan))) {
01780                ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", chan->name);
01781                ast_playtones_stop(chan);
01782                return -1;
01783             }
01784 
01785             if ((frame->frametype == AST_FRAME_CONTROL) &&
01786                   (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
01787                   (frame->datalen == sizeof(t38_parameters))) {
01788                struct ast_control_t38_parameters *parameters = frame->data.ptr;
01789 
01790                switch (parameters->request_response) {
01791                case AST_T38_REQUEST_NEGOTIATE:
01792                   /* the other end has requested a switch to T.38, so reply that we are willing, if we can
01793                    * do T.38 as well
01794                    */
01795                   t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
01796                   t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
01797                   ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
01798                   ast_playtones_stop(chan);
01799                   break;
01800                case AST_T38_NEGOTIATED:
01801                   ast_log(LOG_NOTICE, "Negotiated T.38 for send on %s\n", chan->name);
01802                   t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
01803                   details->caps &= ~AST_FAX_TECH_AUDIO;
01804                   report_fax_status(chan, details, "T.38 Negotiated");
01805                   ms = 0;
01806                   break;
01807                default:
01808                   break;
01809                }
01810             }
01811             ast_frfree(frame);
01812          }
01813 
01814          ast_playtones_stop(chan);
01815 
01816          /* if T.38 was negotiated, we are done initializing */
01817          if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
01818             return 0;
01819          }
01820       }
01821    }
01822 
01823    /* if we made it here, then T.38 failed, check the 'f' flag */
01824    if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
01825       ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", chan->name);
01826       return -1;
01827    }
01828 
01829    /* ok, audio fallback is allowed */
01830    details->caps |= AST_FAX_TECH_AUDIO;
01831 
01832    return 0;
01833 }
01834 
01835 
01836 /*! \brief initiate a send FAX session */
01837 static int sendfax_exec(struct ast_channel *chan, const char *data)
01838 {
01839    char *parse, *filenames, *c, modems[128] = "";
01840    int channel_alive, file_count;
01841    struct ast_fax_session_details *details;
01842    struct ast_fax_document *doc;
01843    AST_DECLARE_APP_ARGS(args,
01844       AST_APP_ARG(filenames);
01845       AST_APP_ARG(options);
01846    );
01847    struct ast_flags opts = { 0, };
01848    struct manager_event_info info;
01849 
01850    /* initialize output channel variables */
01851    pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
01852    pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
01853    pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
01854    pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
01855    pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
01856 
01857    /* Get a requirement structure and set it.  This structure is used
01858     * to tell the FAX technology module about the higher level FAX session */
01859    if (!(details = find_or_create_details(chan))) {
01860       pbx_builtin_setvar_helper(chan, "FAXERROR", "MEMORY_ERROR");
01861       pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "error allocating memory");
01862       ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
01863       return -1;
01864    }
01865 
01866    ast_string_field_set(details, result, "FAILED");
01867    ast_string_field_set(details, resultstr, "error starting fax session");
01868    ast_string_field_set(details, error, "INIT_ERROR");
01869    set_channel_variables(chan, details);
01870 
01871    if (details->maxrate < details->minrate) {
01872       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01873       ast_string_field_set(details, resultstr, "maxrate is less than minrate");
01874       set_channel_variables(chan, details);
01875       ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", details->maxrate, details->minrate);
01876       ao2_ref(details, -1);
01877       return -1;
01878    }
01879 
01880    if (check_modem_rate(details->modems, details->minrate)) {
01881       ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
01882       ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, details->minrate);
01883       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01884       ast_string_field_set(details, resultstr, "incompatible 'modems' and 'minrate' settings");
01885       set_channel_variables(chan, details);
01886       ao2_ref(details, -1);
01887       return -1;
01888    }
01889 
01890    if (check_modem_rate(details->modems, details->maxrate)) {
01891       ast_fax_modem_to_str(details->modems, modems, sizeof(modems));
01892       ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, details->maxrate);
01893       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01894       ast_string_field_set(details, resultstr, "incompatible 'modems' and 'maxrate' settings");
01895       set_channel_variables(chan, details);
01896       ao2_ref(details, -1);
01897       return -1;
01898    }
01899 
01900    if (ast_strlen_zero(data)) {
01901       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01902       ast_string_field_set(details, resultstr, "invalid arguments");
01903       set_channel_variables(chan, details);
01904       ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
01905       ao2_ref(details, -1);
01906       return -1;
01907    }
01908    parse = ast_strdupa(data);
01909    AST_STANDARD_APP_ARGS(args, parse);
01910 
01911 
01912    if (!ast_strlen_zero(args.options) &&
01913        ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
01914       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01915       ast_string_field_set(details, resultstr, "invalid arguments");
01916       set_channel_variables(chan, details);
01917       ao2_ref(details, -1);
01918       return -1;
01919    }
01920    if (ast_strlen_zero(args.filenames)) {
01921       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01922       ast_string_field_set(details, resultstr, "invalid arguments");
01923       set_channel_variables(chan, details);
01924       ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
01925       ao2_ref(details, -1);
01926       return -1;
01927    }
01928    
01929    /* check for unsupported FAX application options */
01930    if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
01931       ast_string_field_set(details, error, "INVALID_ARGUMENTS");
01932       ast_string_field_set(details, resultstr, "invalid arguments");
01933       set_channel_variables(chan, details);
01934       ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
01935       ao2_ref(details, -1);
01936       return -1;
01937    }
01938 
01939    /* make sure the channel is up */
01940    if (chan->_state != AST_STATE_UP) {
01941       if (ast_answer(chan)) {
01942          ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", chan->name);
01943          ao2_ref(details, -1);
01944          return -1;
01945       }
01946    }
01947 
01948    ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
01949 
01950    file_count = 0;
01951    filenames = args.filenames;
01952    while ((c = strsep(&filenames, "&"))) {
01953       if (access(c, (F_OK | R_OK)) < 0) {
01954          ast_string_field_set(details, error, "FILE_ERROR");
01955          ast_string_field_set(details, resultstr, "error reading file");
01956          set_channel_variables(chan, details);
01957          ast_log(LOG_ERROR, "access failure.  Verify '%s' exists and check permissions.\n", args.filenames);
01958          ao2_ref(details, -1);
01959          return -1;
01960       }
01961 
01962       if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
01963          ast_string_field_set(details, error, "MEMORY_ERROR");
01964          ast_string_field_set(details, resultstr, "error allocating memory");
01965          set_channel_variables(chan, details);
01966          ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
01967          ao2_ref(details, -1);
01968          return -1;
01969       }
01970 
01971       strcpy(doc->filename, c);
01972       AST_LIST_INSERT_TAIL(&details->documents, doc, next);
01973       file_count++;
01974    }
01975 
01976    if (file_count > 1) {
01977       details->caps |= AST_FAX_TECH_MULTI_DOC;
01978    }
01979 
01980    ast_verb(3, "Channel '%s' sending FAX:\n", chan->name);
01981    AST_LIST_TRAVERSE(&details->documents, doc, next) {
01982       ast_verb(3, "   %s\n", doc->filename);
01983    }
01984 
01985    details->caps = AST_FAX_TECH_SEND;
01986 
01987    /* check for debug */
01988    if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
01989       details->option.debug = AST_FAX_OPTFLAG_TRUE;
01990    }
01991 
01992    /* check for request for status events */
01993    if (ast_test_flag(&opts, OPT_STATUS)) {
01994       details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
01995    }
01996 
01997    if ((ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE) ||
01998        ast_test_flag(&opts, OPT_ALLOWAUDIO)) {
01999       details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
02000    }
02001 
02002    if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
02003       details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
02004    }
02005 
02006    if (set_fax_t38_caps(chan, details)) {
02007       ast_string_field_set(details, error, "T38_NEG_ERROR");
02008       ast_string_field_set(details, resultstr, "error negotiating T.38");
02009       set_channel_variables(chan, details);
02010       ao2_ref(details, -1);
02011       return -1;
02012    }
02013 
02014    if (details->caps & AST_FAX_TECH_T38) {
02015       if (sendfax_t38_init(chan, details)) {
02016          ast_string_field_set(details, error, "T38_NEG_ERROR");
02017          ast_string_field_set(details, resultstr, "error negotiating T.38");
02018          set_channel_variables(chan, details);
02019          ao2_ref(details, -1);
02020          ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", chan->name);
02021          return -1;
02022       }
02023    } else {
02024       details->option.send_cng = 1;
02025    }
02026 
02027    if ((channel_alive = generic_fax_exec(chan, details)) < 0) {
02028       ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
02029    }
02030 
02031    if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
02032       if (disable_t38(chan)) {
02033          ast_log(LOG_WARNING, "error disabling T.38 mode on %s\n", chan->name);
02034       }
02035    }
02036 
02037    if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
02038       ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
02039       ao2_ref(details, -1);
02040       return (!channel_alive) ? -1 : 0;
02041    }
02042 
02043    /* send out the AMI completion event */
02044    ast_channel_lock(chan);
02045    get_manager_event_info(chan, &info);
02046    manager_event(EVENT_FLAG_CALL,
02047             "SendFAX", 
02048             "Channel: %s\r\n"
02049             "Context: %s\r\n"
02050             "Exten: %s\r\n"
02051             "CallerID: %s\r\n"
02052             "RemoteStationID: %s\r\n"
02053             "LocalStationID: %s\r\n"
02054             "PagesTransferred: %s\r\n"
02055             "Resolution: %s\r\n"
02056             "TransferRate: %s\r\n"
02057             "%s\r\n",
02058             chan->name,
02059             info.context,
02060             info.exten,
02061             info.cid,
02062             pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"),
02063             pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"),
02064             pbx_builtin_getvar_helper(chan, "FAXPAGES"),
02065             pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"),
02066             pbx_builtin_getvar_helper(chan, "FAXBITRATE"),
02067             filenames);
02068    ast_channel_unlock(chan);
02069 
02070    ast_free(filenames);
02071 
02072    ao2_ref(details, -1);
02073 
02074    /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
02075    return (!channel_alive) ? -1 : 0;
02076 }
02077 
02078 /*! \brief hash callback for ao2 */
02079 static int session_hash_cb(const void *obj, const int flags)
02080 {
02081    const struct ast_fax_session *s = obj;
02082 
02083    return s->id;
02084 }
02085 
02086 /*! \brief compare callback for ao2 */
02087 static int session_cmp_cb(void *obj, void *arg, int flags)
02088 {
02089    struct ast_fax_session *lhs = obj, *rhs = arg;
02090 
02091    return (lhs->id == rhs->id) ? CMP_MATCH | CMP_STOP : 0;
02092 }
02093 
02094 /*! \brief fax session tab completion */
02095 static char *fax_session_tab_complete(struct ast_cli_args *a)
02096 {
02097    int tklen;
02098    int wordnum = 0;
02099    char *name = NULL;
02100    struct ao2_iterator i;
02101    struct ast_fax_session *s;
02102    char tbuf[5];
02103 
02104    if (a->pos != 3) {
02105       return NULL;
02106    }
02107 
02108    tklen = strlen(a->word);
02109    i = ao2_iterator_init(faxregistry.container, 0);
02110    while ((s = ao2_iterator_next(&i))) {
02111       snprintf(tbuf, sizeof(tbuf), "%d", s->id);
02112       if (!strncasecmp(a->word, tbuf, tklen) && ++wordnum > a->n) {
02113          name = ast_strdup(tbuf);
02114          ao2_ref(s, -1);
02115          break;
02116       }
02117       ao2_ref(s, -1);
02118    }
02119    if (ao2_iterator_destroy != NULL) {
02120       ao2_iterator_destroy(&i);
02121    }
02122    return name;
02123 }
02124 
02125 static char *cli_fax_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02126 {
02127    struct fax_module *fax;
02128 
02129    switch(cmd) {
02130    case CLI_INIT:
02131       e->command = "fax show version";
02132       e->usage =
02133          "Usage: fax show version\n"
02134          "       Show versions of FAX For Asterisk components.\n";
02135       return NULL;
02136    case CLI_GENERATE:
02137       return NULL;
02138    }
02139 
02140    if (a->argc != 3) {
02141       return CLI_SHOWUSAGE;
02142    }
02143 
02144    ast_cli(a->fd, "FAX For Asterisk Components:\n");
02145    ast_cli(a->fd, "\tApplications: %s\n", ast_get_version());
02146    AST_RWLIST_RDLOCK(&faxmodules);
02147    AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
02148       ast_cli(a->fd, "\t%s: %s\n", fax->tech->description, fax->tech->version);
02149    }
02150    AST_RWLIST_UNLOCK(&faxmodules);
02151    ast_cli(a->fd, "\n");
02152 
02153    return CLI_SUCCESS;
02154 }
02155 
02156 /*! \brief enable FAX debugging */
02157 static char *cli_fax_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02158 {
02159    int flag;
02160    const char *what;
02161 
02162    switch (cmd) {
02163    case CLI_INIT:
02164       e->command = "fax set debug {on|off}";
02165       e->usage = 
02166          "Usage: fax set debug { on | off }\n"
02167          "       Enable/Disable FAX debugging on new FAX sessions.  The basic FAX debugging will result in\n"
02168          "       additional events sent to manager sessions with 'call' class permissions.  When\n"
02169          "       verbosity is greater than '5' events will be displayed to the console and audio versus\n"
02170          "       energy analysis will be performed and displayed to the console.\n";
02171       return NULL;
02172    case CLI_GENERATE:
02173       return NULL;
02174    }
02175 
02176    what = a->argv[e->args-1];      /* guaranteed to exist */
02177    if (!strcasecmp(what, "on")) {
02178       flag = 1;
02179    } else if (!strcasecmp(what, "off")) {
02180       flag = 0;
02181    } else {
02182       return CLI_SHOWUSAGE;
02183    }
02184 
02185    global_fax_debug = flag;
02186    ast_cli(a->fd, "\n\nFAX Debug %s\n\n", (flag) ? "Enabled" : "Disabled");
02187 
02188    return CLI_SUCCESS;
02189 }
02190 
02191 /*! \brief display registered FAX capabilities */
02192 static char *cli_fax_show_capabilities(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02193 {
02194    struct fax_module *fax;
02195    unsigned int num_modules = 0;
02196    
02197    switch (cmd) {
02198    case CLI_INIT:
02199       e->command = "fax show capabilities";
02200       e->usage = 
02201          "Usage: fax show capabilities\n"
02202          "       Shows the capabilities of the registered FAX technology modules\n";
02203       return NULL;
02204    case CLI_GENERATE:
02205       return NULL;
02206    }
02207 
02208    ast_cli(a->fd, "\n\nRegistered FAX Technology Modules:\n\n");
02209    AST_RWLIST_RDLOCK(&faxmodules);
02210    AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
02211       ast_cli(a->fd, "%-15s : %s\n%-15s : %s\n%-15s : ", "Type", fax->tech->type, "Description", fax->tech->description, "Capabilities");
02212       fax->tech->cli_show_capabilities(a->fd);
02213       num_modules++;
02214    }
02215    AST_RWLIST_UNLOCK(&faxmodules);
02216    ast_cli(a->fd, "%d registered modules\n\n", num_modules);
02217 
02218    return CLI_SUCCESS;
02219 }
02220 
02221 /*! \brief display global defaults and settings */
02222 static char *cli_fax_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02223 {
02224    struct fax_module *fax;
02225    char modems[128] = "";
02226 
02227    switch (cmd) {
02228    case CLI_INIT:
02229       e->command = "fax show settings";
02230       e->usage =
02231          "Usage: fax show settings\n"
02232          "       Show the global settings and defaults of both the FAX core and technology modules\n";
02233       return NULL;
02234    case CLI_GENERATE:
02235       return NULL;
02236    }
02237 
02238    ast_cli(a->fd, "FAX For Asterisk Settings:\n");
02239    ast_cli(a->fd, "\tECM: %s\n", general_options.ecm ? "Enabled" : "Disabled");
02240    ast_cli(a->fd, "\tStatus Events: %s\n",  general_options.statusevents ? "On" : "Off");
02241    ast_cli(a->fd, "\tMinimum Bit Rate: %d\n", general_options.minrate);
02242    ast_cli(a->fd, "\tMaximum Bit Rate: %d\n", general_options.maxrate);
02243    ast_fax_modem_to_str(general_options.modems, modems, sizeof(modems));
02244    ast_cli(a->fd, "\tModem Modulations Allowed: %s\n", modems);
02245    ast_cli(a->fd, "\n\nFAX Technology Modules:\n\n");
02246    AST_RWLIST_RDLOCK(&faxmodules);
02247    AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
02248       ast_cli(a->fd, "%s (%s) Settings:\n", fax->tech->type, fax->tech->description);
02249       fax->tech->cli_show_settings(a->fd);
02250    }
02251    AST_RWLIST_UNLOCK(&faxmodules);
02252 
02253    return CLI_SUCCESS;
02254 }
02255 
02256 /*! \brief display details of a specified fax session */
02257 static char *cli_fax_show_session(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02258 {
02259    struct ast_fax_session *s, tmp;
02260 
02261    switch (cmd) {
02262    case CLI_INIT:
02263       e->command = "fax show session";
02264       e->usage =
02265          "Usage: fax show session <session number>\n"
02266          "       Shows status of the named FAX session\n";
02267       return NULL;
02268    case CLI_GENERATE:
02269       return fax_session_tab_complete(a);
02270    }
02271 
02272    if (a->argc != 4) {
02273       return CLI_SHOWUSAGE;
02274    }
02275 
02276    if (sscanf(a->argv[3], "%d", &tmp.id) != 1) {
02277       ast_log(LOG_ERROR, "invalid session id: '%s'\n", a->argv[3]);
02278       return RESULT_SUCCESS;
02279    }
02280 
02281    ast_cli(a->fd, "\nFAX Session Details:\n--------------------\n\n");
02282    s = ao2_find(faxregistry.container, &tmp, OBJ_POINTER);
02283    if (s) {
02284       s->tech->cli_show_session(s, a->fd);
02285       ao2_ref(s, -1);
02286    }
02287    ast_cli(a->fd, "\n\n");
02288 
02289    return CLI_SUCCESS;
02290 }
02291    
02292 /*! \brief display fax stats */
02293 static char *cli_fax_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02294 {
02295    struct fax_module *fax;
02296    
02297    switch (cmd) {
02298    case CLI_INIT:
02299       e->command = "fax show stats";
02300       e->usage =
02301          "Usage: fax show stats\n"
02302          "       Shows a statistical summary of FAX transmissions\n";
02303       return NULL;
02304    case CLI_GENERATE:
02305       return NULL;
02306    }
02307 
02308    ast_cli(a->fd, "\nFAX Statistics:\n---------------\n\n");
02309    ast_cli(a->fd, "%-20.20s : %d\n", "Current Sessions", faxregistry.active_sessions);
02310    ast_cli(a->fd, "%-20.20s : %d\n", "Transmit Attempts", faxregistry.fax_tx_attempts);
02311    ast_cli(a->fd, "%-20.20s : %d\n", "Receive Attempts", faxregistry.fax_rx_attempts);
02312    ast_cli(a->fd, "%-20.20s : %d\n", "Completed FAXes", faxregistry.fax_complete);
02313    ast_cli(a->fd, "%-20.20s : %d\n", "Failed FAXes", faxregistry.fax_failures);
02314    AST_RWLIST_RDLOCK(&faxmodules);
02315    AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
02316       fax->tech->cli_show_stats(a->fd);
02317    }
02318    AST_RWLIST_UNLOCK(&faxmodules);
02319    ast_cli(a->fd, "\n\n");
02320 
02321    return CLI_SUCCESS;
02322 }
02323 
02324 /*! \brief display fax sessions */
02325 static char *cli_fax_show_sessions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02326 {
02327    struct ast_fax_session *s;
02328    struct ao2_iterator i;
02329    int session_count;
02330    char *filenames;
02331 
02332    switch (cmd) {
02333    case CLI_INIT:
02334       e->command = "fax show sessions";
02335       e->usage =
02336          "Usage: fax show sessions\n"
02337          "       Shows the current FAX sessions\n";
02338       return NULL;
02339    case CLI_GENERATE:
02340       return NULL;
02341    }
02342 
02343    ast_cli(a->fd, "\nCurrent FAX Sessions:\n\n");
02344    ast_cli(a->fd, "%-20.20s %-10.10s %-10.10s %-5.5s %-10.10s %-15.15s %-30.30s\n",
02345       "Channel", "Tech", "FAXID", "Type", "Operation", "State", "File(s)");
02346    i = ao2_iterator_init(faxregistry.container, 0);
02347    while ((s = ao2_iterator_next(&i))) {
02348       ao2_lock(s);
02349 
02350       if (!(filenames = generate_filenames_string(s->details, "", ", "))) {
02351          ast_log(LOG_ERROR, "error printing filenames for 'fax show sessions' command");
02352          ao2_unlock(s);
02353          ao2_ref(s, -1);
02354          if (ao2_iterator_destroy != NULL) {
02355             ao2_iterator_destroy(&i);
02356          }
02357          return CLI_FAILURE;
02358       }
02359 
02360       ast_cli(a->fd, "%-20.20s %-10.10s %-10d %-5.5s %-10.10s %-15.15s %-30s\n",
02361          s->channame, s->tech->type, s->id,
02362          (s->details->caps & AST_FAX_TECH_AUDIO) ? "G.711" : "T.38",
02363          (s->details->caps & AST_FAX_TECH_SEND) ? "send" : "receive",
02364          ast_fax_state_to_str(s->state), filenames);
02365 
02366       ast_free(filenames);
02367       ao2_unlock(s);
02368       ao2_ref(s, -1);
02369    }
02370    if (ao2_iterator_destroy != NULL) {
02371       ao2_iterator_destroy(&i);
02372    }
02373    session_count = ao2_container_count(faxregistry.container);
02374    ast_cli(a->fd, "\n%d FAX sessions\n\n", session_count);
02375 
02376    return CLI_SUCCESS;
02377 }
02378 
02379 static struct ast_cli_entry fax_cli[] = {
02380    AST_CLI_DEFINE(cli_fax_show_version, "Show versions of FAX For Asterisk components"),
02381    AST_CLI_DEFINE(cli_fax_set_debug, "Enable/Disable FAX debugging on new FAX sessions"),
02382    AST_CLI_DEFINE(cli_fax_show_capabilities, "Show the capabilities of the registered FAX technology modules"),
02383    AST_CLI_DEFINE(cli_fax_show_settings, "Show the global settings and defaults of both the FAX core and technology modules"),
02384    AST_CLI_DEFINE(cli_fax_show_session, "Show the status of the named FAX sessions"),
02385    AST_CLI_DEFINE(cli_fax_show_sessions, "Show the current FAX sessions"),
02386    AST_CLI_DEFINE(cli_fax_show_stats, "Summarize FAX session history"),
02387 };
02388 
02389 /*! \brief configure res_fax */
02390 static int set_config(const char *config_file)
02391 {
02392    struct ast_config *cfg;
02393    struct ast_variable *v;
02394    struct ast_flags config_flags = { 0 };
02395    char modems[128] = "";
02396 
02397    /* set defaults */   
02398    general_options.minrate = RES_FAX_MINRATE;
02399    general_options.maxrate = RES_FAX_MAXRATE;   
02400    general_options.statusevents = RES_FAX_STATUSEVENTS;
02401    general_options.modems = RES_FAX_MODEM;
02402    general_options.ecm = AST_FAX_OPTFLAG_TRUE;
02403 
02404    /* read configuration */
02405    if (!(cfg = ast_config_load2(config_file, "res_fax", config_flags))) {
02406       ast_log(LOG_NOTICE, "Configuration file '%s' not found, using default options.\n", config_file);
02407       return 0;
02408    }
02409    if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
02410       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
02411       cfg = ast_config_load2(config_file, "res_fax", config_flags);
02412    }
02413 
02414    /* create configuration */
02415    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
02416       int rate;
02417 
02418       if (!strcasecmp(v->name, "minrate")) {
02419          ast_debug(3, "reading minrate '%s' from configuration file\n", v->value);
02420          if ((rate = fax_rate_str_to_int(v->value)) == 0) {
02421             ast_config_destroy(cfg);
02422             return -1;
02423          }
02424          general_options.minrate = rate;
02425       } else if (!strcasecmp(v->name, "maxrate")) {
02426          ast_debug(3, "reading maxrate '%s' from configuration file\n", v->value);
02427          if ((rate = fax_rate_str_to_int(v->value)) == 0) {
02428             ast_config_destroy(cfg);
02429             return -1;
02430          }
02431          general_options.maxrate = rate;
02432       } else if (!strcasecmp(v->name, "statusevents")) {
02433          ast_debug(3, "reading statusevents '%s' from configuration file\n", v->value);
02434          general_options.statusevents = ast_true(v->value);
02435       } else if (!strcasecmp(v->name, "ecm")) {
02436          ast_debug(3, "reading ecm '%s' from configuration file\n", v->value);
02437          general_options.ecm = ast_true(v->value);
02438       } else if ((!strcasecmp(v->name, "modem")) || (!strcasecmp(v->name, "modems"))) {
02439          general_options.modems = 0;
02440          update_modem_bits(&general_options.modems, v->value);
02441       }
02442    }
02443 
02444    ast_config_destroy(cfg);
02445 
02446    if (general_options.maxrate < general_options.minrate) {
02447       ast_log(LOG_ERROR, "maxrate %d is less than minrate %d\n", general_options.maxrate, general_options.minrate);
02448       return -1;
02449    }
02450 
02451    if (check_modem_rate(general_options.modems, general_options.minrate)) {
02452       ast_fax_modem_to_str(general_options.modems, modems, sizeof(modems));
02453       ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'minrate' setting %d\n", modems, general_options.minrate);
02454       return -1;
02455    }
02456 
02457    if (check_modem_rate(general_options.modems, general_options.maxrate)) {
02458       ast_fax_modem_to_str(general_options.modems, modems, sizeof(modems));
02459       ast_log(LOG_ERROR, "'modems' setting '%s' is incompatible with 'maxrate' setting %d\n", modems, general_options.maxrate);
02460       return -1;
02461    }
02462 
02463    return 0;
02464 }
02465 
02466 /*! \brief FAXOPT read function returns the contents of a FAX option */
02467 static int acf_faxopt_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
02468 {
02469    struct ast_fax_session_details *details = find_details(chan);
02470    int res = 0;
02471    char *filenames;
02472 
02473    if (!details) {
02474       ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", chan->name, data);
02475       return -1;
02476    }
02477    if (!strcasecmp(data, "ecm")) {
02478       ast_copy_string(buf, details->option.ecm ? "yes" : "no", len);
02479    } else if (!strcasecmp(data, "error")) {
02480       ast_copy_string(buf, details->error, len);
02481    } else if (!strcasecmp(data, "filename")) {
02482       if (AST_LIST_EMPTY(&details->documents)) {
02483          ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", chan->name, data);
02484          res = -1;
02485       } else {
02486          ast_copy_string(buf, AST_LIST_FIRST(&details->documents)->filename, len);
02487       }
02488    } else if (!strcasecmp(data, "filenames")) {
02489       if (AST_LIST_EMPTY(&details->documents)) {
02490          ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", chan->name, data);
02491          res = -1;
02492       } else if ((filenames = generate_filenames_string(details, "", ","))) {
02493          ast_copy_string(buf, filenames, len);
02494          ast_free(filenames);
02495       } else {
02496          ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s), there was an error generating the filenames list.\n", chan->name, data);
02497          res = -1;
02498       }
02499    } else if (!strcasecmp(data, "headerinfo")) {
02500       ast_copy_string(buf, details->headerinfo, len);
02501    } else if (!strcasecmp(data, "localstationid")) {
02502       ast_copy_string(buf, details->localstationid, len);
02503    } else if (!strcasecmp(data, "maxrate")) {
02504       snprintf(buf, len, "%d", details->maxrate);
02505    } else if (!strcasecmp(data, "minrate")) {
02506       snprintf(buf, len, "%d", details->minrate);
02507    } else if (!strcasecmp(data, "pages")) {
02508       snprintf(buf, len, "%d", details->pages_transferred);
02509    } else if (!strcasecmp(data, "rate")) {
02510       ast_copy_string(buf, details->transfer_rate, len);
02511    } else if (!strcasecmp(data, "remotestationid")) {
02512       ast_copy_string(buf, details->remotestationid, len);
02513    } else if (!strcasecmp(data, "resolution")) {
02514       ast_copy_string(buf, details->resolution, len);
02515    } else if (!strcasecmp(data, "sessionid")) {
02516       snprintf(buf, len, "%d", details->id);
02517    } else if (!strcasecmp(data, "status")) {
02518       ast_copy_string(buf, details->result, len);
02519    } else if (!strcasecmp(data, "statusstr")) {
02520       ast_copy_string(buf, details->resultstr, len);
02521    } else if ((!strcasecmp(data, "modem")) || (!strcasecmp(data, "modems"))) {
02522       ast_fax_modem_to_str(details->modems, buf, len);
02523    } else {
02524       ast_log(LOG_WARNING, "channel '%s' can't read FAXOPT(%s) because it is unhandled!\n", chan->name, data);
02525       res = -1;
02526    }
02527    ao2_ref(details, -1);
02528 
02529    return res;
02530 }
02531 
02532 /*! \brief FAXOPT write function modifies the contents of a FAX option */
02533 static int acf_faxopt_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
02534 {
02535    int res = 0;
02536    struct ast_fax_session_details *details;
02537 
02538    if (!(details = find_or_create_details(chan))) {
02539       ast_log(LOG_WARNING, "channel '%s' can't set FAXOPT(%s) to '%s' because it failed to create a datastore.\n", chan->name, data, value);
02540       return -1;
02541    }
02542    ast_debug(3, "channel '%s' setting FAXOPT(%s) to '%s'\n", chan->name, data, value);
02543 
02544    if (!strcasecmp(data, "ecm")) {
02545       const char *val = ast_skip_blanks(value);
02546       if (ast_true(val)) {
02547          details->option.ecm = AST_FAX_OPTFLAG_TRUE;
02548       } else if (ast_false(val)) {
02549          details->option.ecm = AST_FAX_OPTFLAG_FALSE;
02550       } else {
02551          ast_log(LOG_WARNING, "Unsupported value '%s' passed to FAXOPT(ecm).\n", value);
02552       }
02553    } else if (!strcasecmp(data, "headerinfo")) {
02554       ast_string_field_set(details, headerinfo, value);
02555    } else if (!strcasecmp(data, "localstationid")) {
02556       ast_string_field_set(details, localstationid, value);
02557    } else if (!strcasecmp(data, "maxrate")) {
02558       details->maxrate = fax_rate_str_to_int(value);
02559       if (!details->maxrate) {
02560          details->maxrate = ast_fax_maxrate();
02561       }
02562    } else if (!strcasecmp(data, "minrate")) {
02563       details->minrate = fax_rate_str_to_int(value);
02564       if (!details->minrate) {
02565          details->minrate = ast_fax_minrate();
02566       }
02567    } else if ((!strcasecmp(data, "modem")) || (!strcasecmp(data, "modems"))) {
02568       update_modem_bits(&details->modems, value);
02569    } else {
02570       ast_log(LOG_WARNING, "channel '%s' set FAXOPT(%s) to '%s' is unhandled!\n", chan->name, data, value);
02571       res = -1;
02572    }
02573 
02574    ao2_ref(details, -1);
02575 
02576    return res;
02577 }
02578 
02579 /*! \brief FAXOPT dialplan function */
02580 struct ast_custom_function acf_faxopt = {
02581    .name = "FAXOPT",
02582    .read = acf_faxopt_read,
02583    .write = acf_faxopt_write,
02584 };
02585 
02586 /*! \brief unload res_fax */
02587 static int unload_module(void)
02588 {
02589    ast_cli_unregister_multiple(fax_cli, ARRAY_LEN(fax_cli));
02590    
02591    if (ast_custom_function_unregister(&acf_faxopt) < 0) {
02592       ast_log(LOG_WARNING, "failed to unregister function '%s'\n", acf_faxopt.name);
02593    }
02594 
02595    if (ast_unregister_application(app_sendfax) < 0) {
02596       ast_log(LOG_WARNING, "failed to unregister '%s'\n", app_sendfax);
02597    }
02598 
02599    if (ast_unregister_application(app_receivefax) < 0) {
02600       ast_log(LOG_WARNING, "failed to unregister '%s'\n", app_receivefax);
02601    }
02602 
02603    if (fax_logger_level != -1) {
02604       ast_logger_unregister_level("FAX");
02605    }
02606 
02607    ao2_ref(faxregistry.container, -1);
02608 
02609    return 0;
02610 }
02611 
02612 /*! \brief load res_fax */
02613 static int load_module(void)
02614 {
02615    int res;
02616 
02617    /* initialize the registry */
02618    faxregistry.active_sessions = 0;
02619    if (!(faxregistry.container = ao2_container_alloc(FAX_MAXBUCKETS, session_hash_cb, session_cmp_cb))) {
02620       return AST_MODULE_LOAD_DECLINE;
02621    }
02622    
02623    if (set_config(config) < 0) {
02624       ast_log(LOG_ERROR, "failed to load configuration file '%s'\n", config);
02625       ao2_ref(faxregistry.container, -1);
02626       return AST_MODULE_LOAD_DECLINE;
02627    }
02628 
02629    /* register CLI operations and applications */
02630    if (ast_register_application_xml(app_sendfax, sendfax_exec) < 0) {
02631       ast_log(LOG_WARNING, "failed to register '%s'.\n", app_sendfax);
02632       ao2_ref(faxregistry.container, -1);
02633       return AST_MODULE_LOAD_DECLINE;
02634    }
02635    if (ast_register_application_xml(app_receivefax, receivefax_exec) < 0) {
02636       ast_log(LOG_WARNING, "failed to register '%s'.\n", app_receivefax);
02637       ast_unregister_application(app_sendfax);
02638       ao2_ref(faxregistry.container, -1);
02639       return AST_MODULE_LOAD_DECLINE;
02640    }
02641    ast_cli_register_multiple(fax_cli, ARRAY_LEN(fax_cli));
02642    res = ast_custom_function_register(&acf_faxopt);   
02643    fax_logger_level = ast_logger_register_level("FAX");
02644 
02645    return res;
02646 }
02647 
02648 
02649 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Generic FAX Applications",
02650       .load = load_module,
02651       .unload = unload_module,
02652       .load_pri = AST_MODPRI_APP_DEPEND,
02653           );

Generated on Sat Mar 26 11:08:06 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9