841d7ef7ef6e4287d9d7a9315c5f291efbc8b7e0
[asterisk/asterisk.git] / res / res_fax.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008-2009, Digium, Inc.
5  *
6  * Dwayne M. Hubbard <dhubbard@digium.com>
7  * Kevin P. Fleming <kpfleming@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*** MODULEINFO
21         <conflict>app_fax</conflict>
22 ***/
23
24 /*! \file
25  *
26  * \brief Generic FAX Resource for FAX technology resource modules
27  *
28  * \author Dwayne M. Hubbard <dhubbard@digium.com>
29  * \author Kevin P. Fleming <kpfleming@digium.com>
30  * 
31  * A generic FAX resource module that provides SendFAX and ReceiveFAX applications.
32  * This module requires FAX technology modules, like res_fax_spandsp, to register with it
33  * so it can use the technology modules to perform the actual FAX transmissions.
34  * \ingroup applications
35  */
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40
41 #include "asterisk/io.h"
42 #include "asterisk/file.h"
43 #include "asterisk/logger.h"
44 #include "asterisk/module.h"
45 #include "asterisk/app.h"
46 #include "asterisk/lock.h"
47 #include "asterisk/options.h"
48 #include "asterisk/strings.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/utils.h"
51 #include "asterisk/config.h"
52 #include "asterisk/astobj2.h"
53 #include "asterisk/res_fax.h"
54 #include "asterisk/file.h"
55 #include "asterisk/channel.h"
56 #include "asterisk/pbx.h"
57 #include "asterisk/manager.h"
58 #include "asterisk/dsp.h"
59 #include "asterisk/indications.h"
60 #include "asterisk/ast_version.h"
61
62 static const char app_receivefax[] = "ReceiveFAX";
63 static const char synopsis_receivefax[] = "Receive a FAX and save as a TIFF/F file.";
64 static const char descrip_receivefax[] = "ReceiveFAX(filename[,options]):\n"
65  " The ReceiveFAX() application receives a FAX as a TIFF/F file with specified filename.\n"
66  " The application arguments are:\n"
67  "    'd' - enables FAX debugging\n"
68  "    'f' - allow audio fallback FAX transfer on T.38 capable channels\n"
69  "    's' - send progress Manager events (overrides statusevents setting in res_fax.conf)\n"
70  "\n"
71  " Use the FAXOPT function to specify session arguments prior to calling ReceiveFAX()\n"
72  " and use FAXOPT after ReceiveFAX completes to query result status for the session.\n"
73  " The ReceiveFAX() is provided by res_fax, which is a FAX technology agnostic module\n"
74  " that utilizes FAX technology resource modules to complete a FAX transmission.\n";
75
76 static const char app_sendfax[] = "SendFAX";
77 static const char synopsis_sendfax[] = "Sends a specified TIFF/F file as a FAX.";
78 static const char descrip_sendfax[] = "SendFAX(filename[&filename[&filename]][,options]):\n"
79  " The SendFAX() application sends the specified TIFF/F file(s) as a FAX.\n"
80  " The application arguments are:\n"
81  "    'd' - enables FAX debugging\n"
82  "    'f' - allow audio fallback FAX transfer on T.38 capable channels\n"
83  "    'z' - initiate a T.38 reinvite on the channel if the remote end does not\n"
84  "    's' - send progress Manager events (overrides statusevents setting in res_fax.conf)\n"
85  "\n"
86  " Use the FAXOPT function to specify session arguments prior to calling SendFAX()\n"
87  " and use FAXOPT after SendFAX completes to query result status for the session.\n"
88  " The SendFAX() application is provided by res_fax, which is a FAX technology agnostic module\n"
89  " that utilizes FAX technology resource modules to complete a FAX transmission.\n";
90
91 struct debug_info_history {
92         unsigned int consec_frames;
93         unsigned int consec_ms;
94         unsigned char silence;
95 };
96
97 struct ast_fax_debug_info {
98         struct timeval base_tv;
99         struct debug_info_history c2s, s2c;
100         struct ast_dsp *dsp;
101 };
102
103 static int fax_logger_level = -1;
104
105 /*! \brief maximum buckets for res_fax ao2 containers */
106 #define FAX_MAXBUCKETS 10
107
108 #define RES_FAX_TIMEOUT 10000
109
110 /*! \brief The faxregistry is used to manage information and statistics for all FAX sessions. */
111 static struct {
112         /*! The number of active FAX sessions */
113         int active_sessions;
114         /*! active sessions are astobj2 objects */
115         struct ao2_container *container;
116         /*! Total number of Tx FAX attempts */
117         int fax_tx_attempts;
118         /*! Total number of Rx FAX attempts */
119         int fax_rx_attempts;
120         /*! Number of successful FAX transmissions */
121         int fax_complete;
122         /*! Number of failed FAX transmissions */
123         int fax_failures;
124         /*! the next unique session name */
125         int nextsessionname;
126 } faxregistry;
127
128 /*! \brief registered FAX technology modules are put into this list */
129 struct fax_module {
130         const struct ast_fax_tech *tech;
131         AST_RWLIST_ENTRY(fax_module) list;
132 };
133 static AST_RWLIST_HEAD_STATIC(faxmodules, fax_module);
134
135 #define RES_FAX_MINRATE 2400
136 #define RES_FAX_MAXRATE 14400
137 #define RES_FAX_STATUSEVENTS 0
138 #define RES_FAX_MODEM (AST_FAX_MODEM_V17 | AST_FAX_MODEM_V27 | AST_FAX_MODEM_V29)
139
140 static struct {
141         enum ast_fax_modems modems;
142         uint32_t statusevents:1;
143         uint32_t ecm:1;
144         unsigned int minrate;   
145         unsigned int maxrate;
146 } general_options;
147
148 static const char *config = "res_fax.conf";
149
150 static int global_fax_debug = 0;
151
152 enum {
153         OPT_CALLEDMODE  = (1 << 0),
154         OPT_CALLERMODE  = (1 << 1),
155         OPT_DEBUG       = (1 << 2),
156         OPT_STATUS      = (1 << 3),
157         OPT_ALLOWAUDIO  = (1 << 5),
158         OPT_REQUEST_T38 = (1 << 6),
159 };
160
161 AST_APP_OPTIONS(fax_exec_options, BEGIN_OPTIONS
162         AST_APP_OPTION('a', OPT_CALLEDMODE),
163         AST_APP_OPTION('c', OPT_CALLERMODE),
164         AST_APP_OPTION('d', OPT_DEBUG),
165         AST_APP_OPTION('f', OPT_ALLOWAUDIO),
166         AST_APP_OPTION('s', OPT_STATUS),
167         AST_APP_OPTION('z', OPT_REQUEST_T38),
168 END_OPTIONS);
169
170 struct manager_event_info {
171         char context[AST_MAX_CONTEXT];
172         char exten[AST_MAX_EXTENSION];
173         char cid[128];
174 };
175
176 static void debug_check_frame_for_silence(struct ast_fax_session *s, unsigned int c2s, struct ast_frame *frame)
177 {       
178         struct debug_info_history *history = c2s ? &s->debug_info->c2s : &s->debug_info->s2c;
179         int dspsilence;
180         unsigned int last_consec_frames, last_consec_ms;
181         unsigned char wassil;
182         struct timeval diff;
183
184         diff = ast_tvsub(ast_tvnow(), s->debug_info->base_tv);
185
186         ast_dsp_reset(s->debug_info->dsp);
187         ast_dsp_silence(s->debug_info->dsp, frame, &dspsilence);
188
189         wassil = history->silence;
190         history->silence = (dspsilence != 0) ? 1 : 0;
191         if (history->silence != wassil) {
192                 last_consec_frames = history->consec_frames;
193                 last_consec_ms = history->consec_ms;
194                 history->consec_frames = 0;
195                 history->consec_ms = 0;
196
197                 if ((last_consec_frames != 0)) {
198                         ast_verb(6, "Channel '%s' fax session '%d', [ %.3ld.%.6ld ], %s sent %d frames (%d ms) of %s.\n",
199                                  s->channame, s->id, (long) diff.tv_sec, (long int) diff.tv_usec,
200                                  (c2s) ? "channel" : "stack", last_consec_frames, last_consec_ms,
201                                  (wassil) ? "silence" : "energy");
202                 }
203         }
204
205         history->consec_frames++;
206         history->consec_ms += (frame->samples / 8);
207 }
208
209 static void destroy_callback(void *data) 
210 {
211         if (data) {
212                 ao2_ref(data, -1);
213         }
214 }
215
216 static const struct ast_datastore_info fax_datastore = {
217         .type = "res_fax",
218         .destroy = destroy_callback,
219 };
220
221 /*! \brief returns a reference counted pointer to a fax datastore, if it exists */
222 static struct ast_fax_session_details *find_details(struct ast_channel *chan)
223 {
224         struct ast_fax_session_details *details;
225         struct ast_datastore *datastore;
226
227         ast_channel_lock(chan); 
228         if (!(datastore = ast_channel_datastore_find(chan, &fax_datastore, NULL))) {
229                 ast_channel_unlock(chan);       
230                 return NULL;
231         }
232         if (!(details = datastore->data)) {
233                 ast_log(LOG_WARNING, "Huh?  channel '%s' has a FAX datastore without data!\n", chan->name);
234                 ast_channel_unlock(chan);
235                 return NULL;
236         }
237         ao2_ref(details, 1);    
238         ast_channel_unlock(chan);       
239
240         return details;
241 }
242
243 /*! \brief destroy a FAX session details structure */
244 static void destroy_session_details(void *details)
245 {
246         struct ast_fax_session_details *d = details;
247         struct ast_fax_document *doc;
248         
249         while ((doc = AST_LIST_REMOVE_HEAD(&d->documents, next))) {
250                 ast_free(doc);
251         }
252         ast_string_field_free_memory(d);        
253 }
254
255 /*! \brief create a FAX session details structure */
256 static struct ast_fax_session_details *session_details_new(void)
257 {
258         struct ast_fax_session_details *d;
259
260         if (!(d = ao2_alloc(sizeof(*d), destroy_session_details))) {
261                 return NULL;
262         }
263         
264         if (ast_string_field_init(d, 512)) {
265                 ao2_ref(d, -1);
266                 return NULL;
267         }
268
269         AST_LIST_HEAD_INIT_NOLOCK(&d->documents);
270
271         /* These options need to be set to the configured default and may be overridden by
272          * SendFAX, ReceiveFAX, or FAXOPT */
273         d->option.request_t38 = AST_FAX_OPTFLAG_FALSE;
274         d->option.send_cng = AST_FAX_OPTFLAG_FALSE;
275         d->option.send_ced = AST_FAX_OPTFLAG_FALSE;
276         d->option.ecm = general_options.ecm;
277         d->option.statusevents = general_options.statusevents;
278         d->modems = general_options.modems;
279         d->minrate = general_options.minrate;
280         d->maxrate = general_options.maxrate;
281         ast_string_field_set(d, result, "FAILED");
282         ast_string_field_set(d, resultstr, "error starting fax session");
283         ast_string_field_set(d, error, "INIT_ERROR");
284
285         return d;
286 }
287
288 /*! \brief returns a reference counted details structure from the channel's fax datastore.  If the datastore
289  * does not exist it will be created */ 
290 static struct ast_fax_session_details *find_or_create_details(struct ast_channel *chan)
291 {
292         struct ast_fax_session_details *details;
293         struct ast_datastore *datastore;
294
295         if ((details = find_details(chan))) {
296                 return details;
297         }
298         /* channel does not have one so we must create one */
299         if (!(details = session_details_new())) {
300                 ast_log(LOG_WARNING, "channel '%s' can't get a FAX details structure for the datastore!\n", chan->name);
301                 return NULL;
302         }
303         if (!(datastore = ast_datastore_alloc(&fax_datastore, NULL))) {
304                 ao2_ref(details, -1);
305                 ast_log(LOG_WARNING, "channel '%s' can't get a datastore!\n", chan->name);
306                 return NULL;
307         }
308         /* add the datastore to the channel and increment the refcount */
309         datastore->data = details;
310         ao2_ref(details, 1);
311         ast_channel_lock(chan);
312         ast_channel_datastore_add(chan, datastore);
313         ast_channel_unlock(chan);
314         return details;
315 }
316
317 unsigned int ast_fax_maxrate(void)
318 {
319         return general_options.maxrate;
320 }
321
322 unsigned int ast_fax_minrate(void)
323 {
324         return general_options.minrate;
325 }
326
327 static int update_modem_bits(enum ast_fax_modems *bits, const char *value)
328 {               
329         char *m[5], *tok, *v = (char *)value;
330         int i = 0, j;
331
332         if (!(tok = strchr(v, ','))) {
333                 m[i++] = v;
334                 m[i] = NULL;
335         } else {
336                 tok = strtok(v, ", ");
337                 while (tok && (i < 5)) {
338                         m[i++] = tok;
339                         tok = strtok(NULL, ", ");
340                 }
341                 m[i] = NULL;
342         }
343
344         *bits = 0;
345         for (j = 0; j < i; j++) {
346                 if (!strcasecmp(m[j], "v17")) {
347                         *bits |= AST_FAX_MODEM_V17;
348                 } else if (!strcasecmp(m[j], "v27")) {
349                         *bits |= AST_FAX_MODEM_V27;
350                 } else if (!strcasecmp(m[j], "v29")) {
351                         *bits |= AST_FAX_MODEM_V29;
352                 } else if (!strcasecmp(m[j], "v34")) {
353                         *bits |= AST_FAX_MODEM_V34;
354                 } else {
355                         ast_log(LOG_WARNING, "ignoring invalid modem setting: '%s', valid options {v17 | v27 | v29 | v34}\n", m[j]);
356                 }
357         }
358         return 0;
359 }
360
361 static int ast_fax_modem_to_str(enum ast_fax_modems bits, char *tbuf, size_t bufsize)
362 {
363         int count = 0;
364
365         if (bits & AST_FAX_MODEM_V17) {
366                 strcat(tbuf, "V17");
367                 count++;
368         }
369         if (bits & AST_FAX_MODEM_V27) {
370                 if (count) {
371                         strcat(tbuf, ",");
372                 }
373                 strcat(tbuf, "V27");
374                 count++;
375         }
376         if (bits & AST_FAX_MODEM_V29) {
377                 if (count) {
378                         strcat(tbuf, ",");
379                 }
380                 strcat(tbuf, "V29");
381                 count++;
382         }
383         if (bits & AST_FAX_MODEM_V34) {
384                 if (count) {
385                         strcat(tbuf, ",");
386                 }
387                 strcat(tbuf, "V34");
388                 count++;
389         }
390
391         return 0;
392 }
393
394 /*! \brief register a FAX technology module */
395 int ast_fax_tech_register(struct ast_fax_tech *tech)
396 {
397         struct fax_module *fax;
398
399         if (!(fax = ast_calloc(1, sizeof(*fax)))) {
400                 return -1;
401         }
402         fax->tech = tech;
403         AST_RWLIST_WRLOCK(&faxmodules);
404         AST_RWLIST_INSERT_TAIL(&faxmodules, fax, list);
405         AST_RWLIST_UNLOCK(&faxmodules);
406         ast_module_ref(ast_module_info->self);
407
408         ast_verb(3, "Registered handler for '%s' (%s)\n", fax->tech->type, fax->tech->description);
409
410         return 0;
411 }
412
413 /*! \brief unregister a FAX technology module */
414 void ast_fax_tech_unregister(struct ast_fax_tech *tech)
415 {
416         struct fax_module *fax;
417
418         ast_verb(3, "Unregistering FAX module type '%s'\n", tech->type);
419
420         AST_RWLIST_WRLOCK(&faxmodules);
421         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&faxmodules, fax, list) {
422                 if (fax->tech != tech) {
423                         continue;
424                 }
425                 AST_RWLIST_REMOVE_CURRENT(list);
426                 ast_module_unref(ast_module_info->self);
427                 ast_free(fax);
428                 ast_verb(4, "Unregistered FAX module type '%s'\n", tech->type);
429                 break;  
430         }
431         AST_RWLIST_TRAVERSE_SAFE_END;
432         AST_RWLIST_UNLOCK(&faxmodules);
433 }
434
435 /*! \brief convert a ast_fax_state to a string */
436 const char *ast_fax_state_to_str(enum ast_fax_state state)
437 {
438         switch (state) {
439         case AST_FAX_STATE_UNINITIALIZED:
440                 return "Uninitialized";
441         case AST_FAX_STATE_INITIALIZED:
442                 return "Initialized";
443         case AST_FAX_STATE_OPEN:
444                 return "Open";
445         case AST_FAX_STATE_ACTIVE:
446                 return "Active";
447         case AST_FAX_STATE_COMPLETE:
448                 return "Complete";
449         default:
450                 ast_log(LOG_WARNING, "unhandled FAX state: %d\n", state);
451                 return "Unknown";
452         }
453 }
454
455 void ast_fax_log(int level, const char *file, const int line, const char *function, const char *msg)
456 {
457         if (fax_logger_level != -1) {
458                 ast_log_dynamic_level(fax_logger_level, "%s", msg);
459         } else {
460                 ast_log(level, file, line, function, "%s", msg);
461         }
462 }
463
464 /*! \brief convert a rate string to a rate */
465 static unsigned int fax_rate_str_to_int(const char *ratestr)
466 {
467         int rate;
468
469         if (sscanf(ratestr, "%d", &rate) != 1) {
470                 ast_log(LOG_ERROR, "failed to sscanf '%s' to rate\n", ratestr);
471                 return 0;
472         }
473         switch (rate) {
474         case 2400:
475         case 4800:
476         case 7200:
477         case 9600:
478         case 12000:
479         case 14400:
480         case 28800:
481         case 33600:
482                 return rate;
483         default:
484                 ast_log(LOG_WARNING, "ignoring invalid rate '%s'.  Valid options are {2400 | 4800 | 7200 | 9600 | 12000 | 14400 | 28800 | 33600}\n", ratestr);
485                 return 0;
486         }
487 }
488
489 /*! \brief destroy a FAX session structure */
490 static void destroy_session(void *session)
491 {
492         struct ast_fax_session *s = session;
493
494         if (s->tech) {
495                 if (s->tech_pvt) {
496                         s->tech->destroy_session(s);
497                 }
498                 ast_module_unref(s->tech->module);
499         }
500
501         if (s->details) {
502                 ao2_ref(s->details, -1);
503         }
504         
505         if (s->debug_info) {
506                 ast_dsp_free(s->debug_info->dsp);
507                 ast_free(s->debug_info);
508         }
509
510         if (s->smoother) {
511                 ast_smoother_free(s->smoother);
512         }
513
514         ast_atomic_fetchadd_int(&faxregistry.active_sessions, -1);
515
516         ast_free(s->channame);
517         ast_free(s->chan_uniqueid);
518 }
519
520 /*! \brief create a FAX session */
521 static struct ast_fax_session *fax_session_new(struct ast_fax_session_details *details, struct ast_channel *chan)
522 {
523         struct ast_fax_session *s;
524         struct fax_module *faxmod;
525
526         if (!(s = ao2_alloc(sizeof(*s), destroy_session))) {
527                 return NULL;
528         }
529
530         ast_atomic_fetchadd_int(&faxregistry.active_sessions, 1);
531
532         if (details->option.debug && (details->caps & AST_FAX_TECH_AUDIO)) {
533                 if (!(s->debug_info = ast_calloc(1, sizeof(*(s->debug_info))))) {
534                         ao2_ref(s, -1);
535                         return NULL;
536                 }
537                 if (!(s->debug_info->dsp = ast_dsp_new())) {
538                         ast_free(s->debug_info);
539                         s->debug_info = NULL;
540                         ao2_ref(s, -1);
541                         return NULL;
542                 }
543                 ast_dsp_set_threshold(s->debug_info->dsp, 128);
544         }       
545
546         if (!(s->channame = ast_strdup(chan->name))) {
547                 ao2_ref(s, -1);
548                 return NULL;
549         }
550
551         if (!(s->chan_uniqueid = ast_strdup(chan->uniqueid))) {
552                 ao2_ref(s, -1);
553                 return NULL;
554         }
555
556         s->chan = chan;
557         s->details = details;
558         ao2_ref(s->details, 1);
559         s->state = AST_FAX_STATE_UNINITIALIZED;
560
561         details->id = s->id = ast_atomic_fetchadd_int(&faxregistry.nextsessionname, 1);
562
563         /* locate a FAX technology module that can handle said requirements */
564         AST_RWLIST_RDLOCK(&faxmodules);
565         AST_RWLIST_TRAVERSE(&faxmodules, faxmod, list) {
566                 if ((faxmod->tech->caps & details->caps) != details->caps) {
567                         continue;
568                 }
569                 ast_debug(4, "Requesting a new FAX session from '%s'.\n", faxmod->tech->description);
570                 ast_module_ref(faxmod->tech->module);
571                 s->tech = faxmod->tech;
572                 break;
573         }
574         AST_RWLIST_UNLOCK(&faxmodules);
575
576         if (!faxmod) {
577                 ast_log(LOG_ERROR, "Could not locate a FAX technology module with capabilities (0x%X)\n", details->caps);
578                 ao2_ref(s, -1);
579                 return NULL;
580         }
581         if (!(s->tech_pvt = s->tech->new_session(s, NULL))) {
582                 ast_log(LOG_ERROR, "FAX session failed to initialize.\n");
583                 ao2_ref(s, -1);
584                 ast_module_unref(faxmod->tech->module);
585                 return NULL;
586         }
587         /* link the session to the session container */
588         if (!(ao2_link(faxregistry.container, s))) {
589                 ast_log(LOG_ERROR, "failed to add FAX session '%d' to container.\n", s->id);
590                 ao2_ref(s, -1);
591                 ast_module_unref(faxmod->tech->module);
592                 return NULL;
593         }
594         ast_debug(4, "channel '%s' using FAX session '%d'\n", s->channame, s->id);
595
596         return s;
597 }
598
599 static void get_manager_event_info(struct ast_channel *chan, struct manager_event_info *info)
600 {
601         pbx_substitute_variables_helper(chan, "${CONTEXT}", info->context, sizeof(info->context));
602         pbx_substitute_variables_helper(chan, "${EXTEN}", info->exten, sizeof(info->exten));
603         pbx_substitute_variables_helper(chan, "${CALLERID(num)}", info->cid, sizeof(info->cid));
604 }
605
606
607 /* \brief Generate a string of filenames using the given prefix and separator.
608  * \param details the fax session details
609  * \param prefix the prefix to each filename
610  * \param separator the separator between filenames
611  *
612  * This function generates a string of filenames from the given details
613  * structure and using the given prefix and separator.
614  *
615  * \retval NULL there was an error generating the string
616  * \return the string generated string
617  */
618 static char *generate_filenames_string(struct ast_fax_session_details *details, char *prefix, char *separator)
619 {
620         char *filenames, *c;
621         size_t size = 0;
622         int first = 1;
623         struct ast_fax_document *doc;
624
625         /* don't process empty lists */
626         if (AST_LIST_EMPTY(&details->documents)) {
627                 return NULL;
628         }
629
630         /* Calculate the total length of all of the file names */
631         AST_LIST_TRAVERSE(&details->documents, doc, next) {
632                 size += strlen(separator) + strlen(prefix) + strlen(doc->filename);
633         }
634         size += 1; /* add space for the terminating null */
635
636         if (!(filenames = ast_malloc(size))) {
637                 return NULL;
638         }
639         c = filenames;
640
641         ast_build_string(&c, &size, "%s%s", prefix, AST_LIST_FIRST(&details->documents)->filename);
642         AST_LIST_TRAVERSE(&details->documents, doc, next) {
643                 if (first) {
644                         first = 0;
645                         continue;
646                 }
647
648                 ast_build_string(&c, &size, "%s%s%s", separator, prefix, doc->filename);
649         }
650
651         return filenames;
652 }
653
654 /*! \brief send a FAX status manager event */
655 static int report_fax_status(struct ast_channel *chan, struct ast_fax_session_details *details, const char *status)
656 {
657         char *filenames = generate_filenames_string(details, "FileName: ", "\r\n");
658         if (!filenames) {
659                 return 1;
660         }
661
662         ast_channel_lock(chan);
663         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", status);
664         if (details->option.statusevents) {
665                 struct manager_event_info info;
666
667                 get_manager_event_info(chan, &info);
668                 manager_event(EVENT_FLAG_CALL,
669                               (details->caps & AST_FAX_TECH_RECEIVE) ? "ReceiveFAXStatus" : "SendFAXStatus",
670                               "Status: %s\r\n"
671                               "Channel: %s\r\n"
672                               "Context: %s\r\n"
673                               "Exten: %s\r\n"
674                               "CallerID: %s\r\n"
675                               "LocalStationID: %s\r\n"
676                               "%s\r\n",
677                               status,
678                               chan->name,
679                               info.context,
680                               info.exten,
681                               info.cid,
682                               details->localstationid,
683                               filenames);
684         }
685         ast_channel_unlock(chan);
686         ast_free(filenames);
687
688         return 0;
689 }
690
691 #define GENERIC_FAX_EXEC_ERROR(fax, chan, errorstr, reason)     \
692         do {    \
693                 ast_log(LOG_ERROR, "channel '%s' FAX session '%d' failure, reason: '%s' (%s)\n", chan->name, fax->id, reason, errorstr); \
694                 pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", reason); \
695                 if (ast_strlen_zero(fax->details->result)) ast_string_field_set(fax->details, result, "FAILED"); \
696                 if (ast_strlen_zero(fax->details->resultstr)) ast_string_field_set(fax->details, resultstr, reason); \
697                 if (ast_strlen_zero(fax->details->error)) ast_string_field_set(fax->details, error, errorstr); \
698                 res = ms = -1; \
699         } while (0)
700
701 static void t38_parameters_ast_to_fax(struct ast_fax_t38_parameters *dst, const struct ast_control_t38_parameters *src)
702 {
703         dst->version = src->version;
704         dst->max_ifp = src->max_ifp;
705         dst->rate = src->rate;
706         dst->rate_management = src->rate_management;
707         dst->fill_bit_removal = src->fill_bit_removal;
708         dst->transcoding_mmr = src->transcoding_mmr;
709         dst->transcoding_jbig = src->transcoding_jbig;
710 }
711
712 static void t38_parameters_fax_to_ast(struct ast_control_t38_parameters *dst, const struct ast_fax_t38_parameters *src)
713 {
714         dst->version = src->version;
715         dst->max_ifp = src->max_ifp;
716         dst->rate = src->rate;
717         dst->rate_management = src->rate_management;
718         dst->fill_bit_removal = src->fill_bit_removal;
719         dst->transcoding_mmr = src->transcoding_mmr;
720         dst->transcoding_jbig = src->transcoding_jbig;
721 }
722
723 static int set_fax_t38_caps(struct ast_channel *chan, struct ast_fax_session_details *details)
724 {
725         switch (ast_channel_get_t38_state(chan)) {
726         case T38_STATE_UNKNOWN:
727                 details->caps |= AST_FAX_TECH_T38;
728                 break;
729         case T38_STATE_UNAVAILABLE:
730                 details->caps |= AST_FAX_TECH_AUDIO;
731                 break;
732         case T38_STATE_NEGOTIATING: {
733                 /* the other end already sent us a T.38 reinvite, so we need to prod the channel
734                  * driver into resending their parameters to us if it supports doing so... if
735                  * not, we can't proceed, because we can't create a proper reply without them.
736                  * if it does work, the channel driver will send an AST_CONTROL_T38_PARAMETERS
737                  * with a request of AST_T38_REQUEST_NEGOTIATE, which will be read by the function
738                  * that gets called after this one completes
739                  */
740                 struct ast_control_t38_parameters parameters = { .request_response = AST_T38_REQUEST_PARMS, };
741                 if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters)) != AST_T38_REQUEST_PARMS) {
742                         ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", chan->name);
743                         return -1;
744                 }
745                 details->caps |= AST_FAX_TECH_T38;
746                 break;
747         }
748         default:
749                 ast_log(LOG_ERROR, "channel '%s' is in an unsupported T.38 negotiation state, cannot continue.\n", chan->name);
750                 return -1;
751         }
752
753         return 0;
754 }
755
756 static int disable_t38(struct ast_channel *chan)
757 {
758         int ms;
759         struct ast_frame *frame = NULL;
760         struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
761
762         ast_debug(1, "Shutting down T.38 on %s\n", chan->name);
763         if (ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0) {
764                 ast_log(LOG_WARNING, "error while disabling T.38 on channel '%s'\n", chan->name);
765                 return -1;
766         }
767
768         /* wait up to five seconds for negotiation to complete */
769         ms = 5000;
770
771         while (ms > 0) {
772                 ms = ast_waitfor(chan, ms);
773                 if (ms < 0) {
774                         ast_log(LOG_WARNING, "error while disabling T.38 on channel '%s'\n", chan->name);
775                         return -1;
776                 }
777
778                 if (ms == 0) { /* all done, nothing happened */
779                         ast_log(LOG_WARNING, "channel '%s' timed-out during T.38 shutdown\n", chan->name);
780                         break;
781                 }
782
783                 if (!(frame = ast_read(chan))) {
784                         return -1;
785                 }
786                 if ((frame->frametype == AST_FRAME_CONTROL) &&
787                     (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
788                     (frame->datalen == sizeof(t38_parameters))) {
789                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
790
791                         switch (parameters->request_response) {
792                         case AST_T38_TERMINATED:
793                                 ast_debug(1, "Shut down T.38 on %s\n", chan->name);
794                                 break;
795                         case AST_T38_REFUSED:
796                                 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", chan->name);
797                                 ast_frfree(frame);
798                                 return -1;
799                         default:
800                                 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", chan->name);
801                                 ast_frfree(frame);
802                                 return -1;
803                         }
804                         ast_frfree(frame);
805                         break;
806                 }
807                 ast_frfree(frame);
808         }
809
810         return 0;
811 }
812
813 static struct ast_control_t38_parameters our_t38_parameters = {
814         .version = 0,
815         .max_ifp = 400,
816         .rate = AST_T38_RATE_14400,
817         .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
818 };
819
820 /*! \brief this is the generic FAX session handling function */
821 static int generic_fax_exec(struct ast_channel *chan, struct ast_fax_session_details *details)
822 {
823         int ms;
824         int timeout = RES_FAX_TIMEOUT;
825         int res = 0, chancount;
826         unsigned int expected_frametype = -1;
827         union ast_frame_subclass expected_framesubclass = { .integer = -1 };
828         char tbuf[10];
829         unsigned int t38negotiated = (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED);
830         struct ast_control_t38_parameters t38_parameters;
831         const char *tempvar;
832         struct ast_fax_session *fax = NULL;
833         struct ast_frame *frame = NULL;
834         struct ast_channel *c = chan;
835         unsigned int orig_write_format = 0, orig_read_format = 0;
836
837         chancount = 1;
838
839         /* create the FAX session */
840         if (!(fax = fax_session_new(details, chan))) {
841                 ast_log(LOG_ERROR, "Can't create a FAX session, FAX attempt failed.\n");
842                 report_fax_status(chan, details, "No Available Resource");
843                 return -1;
844         }
845
846         ast_channel_lock(chan);
847         /* update session details */    
848         if (ast_strlen_zero(details->headerinfo) && (tempvar = pbx_builtin_getvar_helper(chan, "LOCALHEADERINFO"))) {
849                 ast_string_field_set(details, headerinfo, tempvar);
850         }
851         if (ast_strlen_zero(details->localstationid)) {
852                 tempvar = pbx_builtin_getvar_helper(chan, "LOCALSTATIONID");
853                 ast_string_field_set(details, localstationid, tempvar ? tempvar : "unknown");
854         }
855         ast_channel_unlock(chan);
856
857         report_fax_status(chan, details, "Allocating Resources");
858
859         if (details->caps & AST_FAX_TECH_AUDIO) {
860                 expected_frametype = AST_FRAME_VOICE;;
861                 expected_framesubclass.codec = AST_FORMAT_SLINEAR;
862                 orig_write_format = chan->writeformat;
863                 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
864                         ast_log(LOG_ERROR, "channel '%s' failed to set write format to signed linear'.\n", chan->name);
865                         ao2_lock(faxregistry.container);
866                         ao2_unlink(faxregistry.container, fax);
867                         ao2_unlock(faxregistry.container);
868                         ao2_ref(fax, -1);
869                         ast_channel_unlock(chan);
870                         return -1;
871                 }
872                 orig_read_format = chan->readformat;
873                 if (ast_set_read_format(chan, AST_FORMAT_SLINEAR) < 0) {
874                         ast_log(LOG_ERROR, "channel '%s' failed to set read format to signed linear.\n", chan->name);
875                         ao2_lock(faxregistry.container);
876                         ao2_unlink(faxregistry.container, fax);
877                         ao2_unlock(faxregistry.container);
878                         ao2_ref(fax, -1);
879                         ast_channel_unlock(chan);
880                         return -1;
881                 }
882                 if (fax->smoother) {
883                         ast_smoother_free(fax->smoother);
884                         fax->smoother = NULL;
885                 }
886                 if (!(fax->smoother = ast_smoother_new(320))) {
887                         ast_log(LOG_WARNING, "Channel '%s' FAX session '%d' failed to obtain a smoother.\n", chan->name, fax->id);
888                 }
889         } else {
890                 expected_frametype = AST_FRAME_MODEM;
891                 expected_framesubclass.codec = AST_MODEM_T38;
892         }
893
894         if (fax->debug_info) {
895                 fax->debug_info->base_tv = ast_tvnow();
896         }
897
898         /* reset our result fields just in case the fax tech driver wants to
899          * set custom error messages */
900         ast_string_field_set(details, result, "");
901         ast_string_field_set(details, resultstr, "");
902         ast_string_field_set(details, error, "");
903
904         if (fax->tech->start_session(fax) < 0) {
905                 GENERIC_FAX_EXEC_ERROR(fax, chan, "INIT_ERROR", "failed to start FAX session");
906         }
907
908         pbx_builtin_setvar_helper(chan, "FAXSTATUS", NULL);
909         pbx_builtin_setvar_helper(chan, "FAXERROR", NULL);
910         report_fax_status(chan, details, "FAX Transmission In Progress");
911
912         ast_debug(5, "channel %s will wait on FAX fd %d\n", chan->name, fax->fd);
913
914         /* handle frames for the session */
915         ms = 1000;
916         while ((res > -1) && (ms > -1) && (timeout > 0)) {
917                 struct ast_channel *ready_chan;
918                 int ofd, exception;
919
920                 ms = 1000;
921                 errno = 0;
922                 ready_chan = ast_waitfor_nandfds(&c, chancount, &fax->fd, 1, &exception, &ofd, &ms);
923                 if (ready_chan) {
924                         if (!(frame = ast_read(chan))) {
925                                 /* the channel is probably gone, so lets stop polling on it and let the
926                                  * FAX session complete before we exit the application.  if needed,
927                                  * send the FAX stack silence so the modems can finish their session without
928                                  * any problems */
929                                 ast_log(LOG_NOTICE, "Channel '%s' did not return a frame; probably hung up.\n", chan->name);
930                                 c = NULL;
931                                 chancount = 0;
932                                 timeout -= (1000 - ms);
933                                 fax->tech->cancel_session(fax);
934                                 if (fax->tech->generate_silence) {
935                                         fax->tech->generate_silence(fax);
936                                 }
937                                 continue;
938                         }
939
940                         if ((frame->frametype == AST_FRAME_CONTROL) &&
941                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
942                             (frame->datalen == sizeof(t38_parameters))) {
943                                 unsigned int was_t38 = t38negotiated;
944                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
945                                 
946                                 switch (parameters->request_response) {
947                                 case AST_T38_REQUEST_NEGOTIATE:
948                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
949                                          * do T.38 as well
950                                          */
951                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
952                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
953                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
954                                         break;
955                                 case AST_T38_NEGOTIATED:
956                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
957                                         t38negotiated = 1;
958                                         break;
959                                 default:
960                                         break;
961                                 }
962                                 if (t38negotiated && !was_t38) {
963                                         fax->tech->switch_to_t38(fax);
964                                         details->caps &= ~AST_FAX_TECH_AUDIO;
965                                         expected_frametype = AST_FRAME_MODEM;
966                                         expected_framesubclass.codec = AST_MODEM_T38;
967                                         if (fax->smoother) {
968                                                 ast_smoother_free(fax->smoother);
969                                                 fax->smoother = NULL;
970                                         }
971                                         
972                                         report_fax_status(chan, details, "T.38 Negotiated");
973                                         
974                                         ast_verb(3, "Channel '%s' switched to T.38 FAX session '%d'.\n", chan->name, fax->id);
975                                 }
976                         } else if ((frame->frametype == expected_frametype) &&
977                                    (!memcmp(&frame->subclass, &expected_framesubclass, sizeof(frame->subclass)))) {
978                                 struct ast_frame *f;
979                                 
980                                 if (fax->smoother) {
981                                         /* push the frame into a smoother */
982                                         if (ast_smoother_feed(fax->smoother, frame) < 0) {
983                                                 GENERIC_FAX_EXEC_ERROR(fax, chan, "UNKNOWN", "Failed to feed the smoother");
984                                         }
985                                         while ((f = ast_smoother_read(fax->smoother)) && (f->data.ptr)) {
986                                                 if (fax->debug_info) {
987                                                         debug_check_frame_for_silence(fax, 1, f);
988                                                 }
989                                                 /* write the frame to the FAX stack */
990                                                 fax->tech->write(fax, f);
991                                                 fax->frames_received++;
992                                                 if (f != frame) {
993                                                         ast_frfree(f);
994                                                 }
995                                         }
996                                 } else {
997                                         /* write the frame to the FAX stack */
998                                         fax->tech->write(fax, frame);
999                                         fax->frames_received++;
1000                                 }
1001                                 timeout = RES_FAX_TIMEOUT;
1002                         }
1003                         ast_frfree(frame);
1004                 } else if (ofd == fax->fd) {
1005                         /* read a frame from the FAX stack and send it out the channel.
1006                          * the FAX stack will return a NULL if the FAX session has already completed */
1007                         if (!(frame = fax->tech->read(fax))) {
1008                                 break;
1009                         }
1010
1011                         if (fax->debug_info && (frame->frametype == AST_FRAME_VOICE)) {
1012                                 debug_check_frame_for_silence(fax, 0, frame);
1013                         }
1014
1015                         ast_write(chan, frame);
1016                         fax->frames_sent++;
1017                         ast_frfree(frame);
1018                         timeout = RES_FAX_TIMEOUT;
1019                 } else {
1020                         if (ms && (ofd < 0)) {
1021                                 if ((errno == 0) || (errno == EINTR)) {
1022                                         timeout -= (1000 - ms);
1023                                         continue;
1024                                 } else {
1025                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", chan->name);
1026                                         res = ms;
1027                                         break;
1028                                 }
1029                         } else {
1030                                 /* nothing happened */
1031                                 if (timeout > 0) {
1032                                         timeout -= 1000;
1033                                         continue;
1034                                 } else {
1035                                         ast_log(LOG_WARNING, "channel '%s' timed-out during the FAX transmission.\n", chan->name);
1036                                         GENERIC_FAX_EXEC_ERROR(fax, chan, "TIMEOUT", "fax session timed-out");
1037                                         break;
1038                                 }
1039                         }
1040                 }
1041         }
1042         ast_debug(3, "channel '%s' - event loop stopped { timeout: %d, ms: %d, res: %d }\n", chan->name, timeout, ms, res);
1043
1044         pbx_builtin_setvar_helper(chan, "FAXSTATUS", details->result);
1045         pbx_builtin_setvar_helper(chan, "FAXERROR", details->error);
1046         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", details->resultstr);
1047         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", details->remotestationid);
1048         pbx_builtin_setvar_helper(chan, "FAXBITRATE", details->transfer_rate);
1049         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", details->resolution);
1050
1051         snprintf(tbuf, sizeof(tbuf), "%d", details->pages_transferred);
1052         pbx_builtin_setvar_helper(chan, "FAXPAGES", tbuf);
1053
1054         ast_atomic_fetchadd_int(&faxregistry.fax_complete, 1);
1055         if (!strcasecmp(details->result, "FAILED")) {
1056                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1057         }
1058
1059         if (fax) {
1060                 ao2_lock(faxregistry.container);
1061                 ao2_unlink(faxregistry.container, fax);
1062                 ao2_unlock(faxregistry.container);
1063                 ao2_ref(fax, -1);
1064         }
1065
1066         /* if the channel is still alive, and we changed its read/write formats,
1067          * restore them now
1068          */
1069         if (chancount) {
1070                 if (orig_read_format) {
1071                         ast_set_read_format(chan, orig_read_format);
1072                 }
1073                 if (orig_write_format) {
1074                         ast_set_write_format(chan, orig_write_format);
1075                 }
1076         }
1077
1078         /* return the chancount so the calling function can determine if the channel hungup during this FAX session or not */
1079         return chancount;
1080 }
1081
1082 static int receivefax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1083 {
1084         int ms;
1085         struct ast_frame *frame = NULL;
1086         struct ast_control_t38_parameters t38_parameters;
1087
1088         t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
1089
1090         /* don't send any audio if we've already received a T.38 reinvite */
1091         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1092                 /* generate 3 seconds of CED */
1093                 if (ast_playtones_start(chan, 1024, "!2100/3000", 1)) {
1094                         ast_log(LOG_ERROR, "error generating CED tone on %s\n", chan->name);
1095                         return -1;
1096                 }
1097
1098                 ms = 3000;
1099                 while (ms > 0) {
1100                         ms = ast_waitfor(chan, ms);
1101                         if (ms < 0) {
1102                                 ast_log(LOG_ERROR, "error while generating CED tone on %s\n", chan->name);
1103                                 ast_playtones_stop(chan);
1104                                 return -1;
1105                         }
1106
1107                         if (ms == 0) { /* all done, nothing happened */
1108                                 break;
1109                         }
1110
1111                         if (!(frame = ast_read(chan))) {
1112                                 ast_log(LOG_ERROR, "error reading frame while generating CED tone on %s\n", chan->name);
1113                                 ast_playtones_stop(chan);
1114                                 return -1;
1115                         }
1116
1117                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1118                             (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1119                             (frame->datalen == sizeof(t38_parameters))) {
1120                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1121
1122                                 switch (parameters->request_response) {
1123                                 case AST_T38_REQUEST_NEGOTIATE:
1124                                         /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1125                                          * do T.38 as well
1126                                          */
1127                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1128                                         t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1129                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1130                                         ast_playtones_stop(chan);
1131                                         break;
1132                                 case AST_T38_NEGOTIATED:
1133                                         ast_log(LOG_NOTICE, "Negotiated T.38 for receive on %s\n", chan->name);
1134                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1135                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1136                                         report_fax_status(chan, details, "T.38 Negotiated");
1137                                         break;
1138                                 default:
1139                                         break;
1140                                 }
1141                         }
1142                         ast_frfree(frame);
1143                 }
1144
1145                 ast_playtones_stop(chan);
1146         }
1147
1148         /* if T.38 was negotiated, we are done initializing */
1149         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1150                 return 0;
1151         }
1152
1153         /* request T.38 */
1154         ast_log(LOG_NOTICE, "Negotiating T.38 for receive on %s\n", chan->name);
1155
1156         /* wait up to five seconds for negotiation to complete */
1157         ms = 5000;
1158
1159         /* set parameters based on the session's parameters */
1160         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1161         t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
1162         if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
1163                 return -1;
1164         }
1165
1166         while (ms > 0) {
1167                 ms = ast_waitfor(chan, ms);
1168                 if (ms < 0) {
1169                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
1170                         return -1;
1171                 }
1172
1173                 if (ms == 0) { /* all done, nothing happened */
1174                         ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", chan->name);
1175                         details->caps &= ~AST_FAX_TECH_T38;
1176                         break;
1177                 }
1178
1179                 if (!(frame = ast_read(chan))) {
1180                         ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
1181                         return -1;
1182                 }
1183
1184                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1185                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1186                                 (frame->datalen == sizeof(t38_parameters))) {
1187                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1188
1189                         switch (parameters->request_response) {
1190                         case AST_T38_REQUEST_NEGOTIATE:
1191                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1192                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
1193                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1194                                 break;
1195                         case AST_T38_NEGOTIATED:
1196                                 ast_log(LOG_NOTICE, "Negotiated T.38 for receive on %s\n", chan->name);
1197                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1198                                 details->caps &= ~AST_FAX_TECH_AUDIO;
1199                                 report_fax_status(chan, details, "T.38 Negotiated");
1200                                 ms = 0;
1201                                 break;
1202                         case AST_T38_REFUSED:
1203                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", chan->name);
1204                                 details->caps &= ~AST_FAX_TECH_T38;
1205                                 ms = 0;
1206                                 break;
1207                         default:
1208                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", chan->name);
1209                                 details->caps &= ~AST_FAX_TECH_T38;
1210                                 ms = 0;
1211                                 break;
1212                         }
1213                 }
1214                 ast_frfree(frame);
1215         }
1216
1217         /* if T.38 was negotiated, we are done initializing */
1218         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1219                 return 0;
1220         }
1221
1222         /* if we made it here, then T.38 failed, check the 'f' flag */
1223         if (details->option.allow_audio != AST_FAX_OPTFLAG_TRUE) {
1224                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", chan->name);
1225                 return -1;
1226         }
1227
1228         /* ok, audio fallback is allowed */
1229         details->caps |= AST_FAX_TECH_AUDIO;
1230
1231         return 0;
1232 }
1233
1234 /*! \brief initiate a receive FAX session */
1235 static int receivefax_exec(struct ast_channel *chan, const char *data)
1236 {
1237         char *parse;
1238         int channel_alive;
1239         struct ast_fax_session_details *details;
1240         struct ast_fax_document *doc;
1241         AST_DECLARE_APP_ARGS(args,
1242                 AST_APP_ARG(filename);
1243                 AST_APP_ARG(options);
1244         );
1245         struct ast_flags opts = { 0, };
1246         struct manager_event_info info;
1247
1248         /* Get a FAX session details structure from the channel's FAX datastore and create one if
1249          * it does not already exist. */
1250         if (!(details = find_or_create_details(chan))) {
1251                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1252                 return -1;
1253         }
1254
1255
1256         if (ast_strlen_zero(data)) {
1257                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1258                 ast_string_field_set(details, resultstr, "invalid arguments");
1259                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1260                 return -1;
1261         }
1262         parse = ast_strdupa(data);
1263         AST_STANDARD_APP_ARGS(args, parse);
1264         
1265         /* initialize output channel variables */
1266         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
1267         pbx_builtin_setvar_helper(chan, "FAXERROR", "Application Problems");
1268         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Invalid application arguments.");
1269         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
1270         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
1271         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
1272         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
1273
1274         if (!ast_strlen_zero(args.options) &&
1275             ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
1276                 return -1;
1277         }
1278         if (ast_strlen_zero(args.filename)) {
1279                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1280                 ast_string_field_set(details, resultstr, "invalid arguments");
1281                 ast_log(LOG_WARNING, "%s requires an argument (filename[,options])\n", app_receivefax);
1282                 return -1;
1283         }
1284
1285         /* check for unsupported FAX application options */
1286         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
1287                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1288                 ast_string_field_set(details, resultstr, "invalid arguments");
1289                 ast_log(LOG_WARNING, "%s does not support polling\n", app_receivefax);
1290                 return -1;
1291         }
1292         
1293         /* make sure the channel is up */
1294         if (chan->_state != AST_STATE_UP) {
1295                 if (ast_answer(chan)) {
1296                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", chan->name);
1297                         return -1;
1298                 }
1299         }
1300
1301         ast_atomic_fetchadd_int(&faxregistry.fax_rx_attempts, 1);
1302
1303         pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
1304         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
1305
1306         if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(args.filename) + 1))) {
1307                 ast_string_field_set(details, error, "MEMORY_ERROR");
1308                 ast_string_field_set(details, resultstr, "error allocating memory");
1309                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1310                 ao2_ref(details, -1);
1311                 return -1;
1312         }
1313
1314         strcpy(doc->filename, args.filename);
1315         AST_LIST_INSERT_TAIL(&details->documents, doc, next);
1316
1317         ast_verb(3, "Channel '%s' receiving FAX '%s'\n", chan->name, args.filename);
1318
1319         details->caps = AST_FAX_TECH_RECEIVE;
1320
1321         /* check for debug */
1322         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
1323                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
1324         }
1325
1326         /* check for request for status events */
1327         if (ast_test_flag(&opts, OPT_STATUS)) {
1328                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
1329         }
1330
1331         if ((ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE) ||
1332             ast_test_flag(&opts, OPT_ALLOWAUDIO)) {
1333                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
1334         }
1335
1336         if (set_fax_t38_caps(chan, details)) {
1337                 ast_string_field_set(details, error, "T38_NEG_ERROR");
1338                 ast_string_field_set(details, resultstr, "error negotiating T.38");
1339                 ao2_ref(details, -1);
1340                 return -1;
1341         }
1342
1343         if (details->caps & AST_FAX_TECH_T38) {
1344                 if (receivefax_t38_init(chan, details)) {
1345                         ast_string_field_set(details, error, "T38_NEG_ERROR");
1346                         ast_string_field_set(details, resultstr, "error negotiating T.38");
1347                         ao2_ref(details, -1);
1348                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", chan->name);
1349                         return -1;
1350                 }
1351         } else {
1352                 details->option.send_ced = 1;
1353         }
1354
1355         if ((channel_alive = generic_fax_exec(chan, details)) < 0) {
1356                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1357         }
1358
1359         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1360                 if (disable_t38(chan)) {
1361                         ast_log(LOG_WARNING, "error disabling T.38 mode on %s\n", chan->name);
1362                 }
1363         }
1364
1365         /* send out the AMI completion event */
1366         ast_channel_lock(chan);
1367
1368         get_manager_event_info(chan, &info);
1369         manager_event(EVENT_FLAG_CALL,
1370                       "ReceiveFAX", 
1371                       "Channel: %s\r\n"
1372                       "Context: %s\r\n"
1373                       "Exten: %s\r\n"
1374                       "CallerID: %s\r\n"
1375                       "RemoteStationID: %s\r\n"
1376                       "LocalStationID: %s\r\n"
1377                       "PagesTransferred: %s\r\n"
1378                       "Resolution: %s\r\n"
1379                       "TransferRate: %s\r\n"
1380                       "FileName: %s\r\n",
1381                       chan->name,
1382                       info.context,
1383                       info.exten,
1384                       info.cid,
1385                       pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"),
1386                       pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"),
1387                       pbx_builtin_getvar_helper(chan, "FAXPAGES"),
1388                       pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"),
1389                       pbx_builtin_getvar_helper(chan, "FAXBITRATE"),
1390                       args.filename);
1391         ast_channel_unlock(chan);
1392
1393         ao2_ref(details, -1);
1394
1395         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
1396         return (!channel_alive) ? -1 : 0;
1397 }
1398
1399 static int sendfax_t38_init(struct ast_channel *chan, struct ast_fax_session_details *details)
1400 {
1401         int ms;
1402         struct ast_frame *frame = NULL;
1403         struct ast_control_t38_parameters t38_parameters;
1404
1405         t38_parameters_ast_to_fax(&details->our_t38_parameters, &our_t38_parameters);
1406
1407         /* send CNG tone while listening for the receiver to initiate a switch
1408          * to T.38 mode; if they do, stop sending the CNG tone and proceed with
1409          * the switch.
1410          *
1411          * 10500 is enough time for 3 CNG tones
1412          */
1413         ms = 10500;
1414
1415         /* don't send any audio if we've already received a T.38 reinvite */
1416         if (ast_channel_get_t38_state(chan) != T38_STATE_NEGOTIATING) {
1417                 if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000,!1100/500,!0/3000,!1100/500,!0/3000", 1)) {
1418                         ast_log(LOG_ERROR, "error generating CNG tone on %s\n", chan->name);
1419                         return -1;
1420                 }
1421         }
1422
1423         while (ms > 0) {
1424                 ms = ast_waitfor(chan, ms);
1425                 if (ms < 0) {
1426                         ast_log(LOG_ERROR, "error while generating CNG tone on %s\n", chan->name);
1427                         ast_playtones_stop(chan);
1428                         return -1;
1429                 }
1430
1431                 if (ms == 0) { /* all done, nothing happened */
1432                         break;
1433                 }
1434
1435                 if (!(frame = ast_read(chan))) {
1436                         ast_log(LOG_ERROR, "error reading frame while generating CNG tone on %s\n", chan->name);
1437                         ast_playtones_stop(chan);
1438                         return -1;
1439                 }
1440
1441                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1442                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1443                                 (frame->datalen == sizeof(t38_parameters))) {
1444                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1445
1446                         switch (parameters->request_response) {
1447                         case AST_T38_REQUEST_NEGOTIATE:
1448                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1449                                  * do T.38 as well
1450                                  */
1451                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1452                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1453                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1454                                 ast_playtones_stop(chan);
1455                                 break;
1456                         case AST_T38_NEGOTIATED:
1457                                 ast_log(LOG_NOTICE, "Negotiated T.38 for send on %s\n", chan->name);
1458                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1459                                 details->caps &= ~AST_FAX_TECH_AUDIO;
1460                                 report_fax_status(chan, details, "T.38 Negotiated");
1461                                 ms = 0;
1462                                 break;
1463                         default:
1464                                 break;
1465                         }
1466                 }
1467                 ast_frfree(frame);
1468         }
1469
1470         ast_playtones_stop(chan);
1471
1472         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1473                 return 0;
1474         }
1475
1476         /* T.38 negotiation did not happen, initiate a switch if requested */
1477         if (details->option.request_t38 == AST_FAX_OPTFLAG_TRUE) {
1478                 ast_log(LOG_NOTICE, "Negotiating T.38 for send on %s\n", chan->name);
1479
1480                 /* wait up to five seconds for negotiation to complete */
1481                 ms = 5000;
1482
1483                 /* set parameters based on the session's parameters */
1484                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1485                 t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
1486                 if ((ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) != 0)) {
1487                         return -1;
1488                 }
1489
1490                 while (ms > 0) {
1491                         ms = ast_waitfor(chan, ms);
1492                         if (ms < 0) {
1493                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
1494                                 return -1;
1495                         }
1496
1497                         if (ms == 0) { /* all done, nothing happened */
1498                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", chan->name);
1499                                 details->caps &= ~AST_FAX_TECH_T38;
1500                                 break;
1501                         }
1502
1503                         if (!(frame = ast_read(chan))) {
1504                                 ast_log(LOG_WARNING, "error on '%s' while waiting for T.38 negotiation.\n", chan->name);
1505                                 return -1;
1506                         }
1507
1508                         if ((frame->frametype == AST_FRAME_CONTROL) &&
1509                                         (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1510                                         (frame->datalen == sizeof(t38_parameters))) {
1511                                 struct ast_control_t38_parameters *parameters = frame->data.ptr;
1512
1513                                 switch (parameters->request_response) {
1514                                 case AST_T38_REQUEST_NEGOTIATE:
1515                                         t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1516                                         t38_parameters.request_response = AST_T38_NEGOTIATED;
1517                                         ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1518                                         break;
1519                                 case AST_T38_NEGOTIATED:
1520                                         ast_log(LOG_NOTICE, "Negotiated T.38 for receive on %s\n", chan->name);
1521                                         t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1522                                         details->caps &= ~AST_FAX_TECH_AUDIO;
1523                                         report_fax_status(chan, details, "T.38 Negotiated");
1524                                         ms = 0;
1525                                         break;
1526                                 case AST_T38_REFUSED:
1527                                         ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", chan->name);
1528                                         details->caps &= ~AST_FAX_TECH_T38;
1529                                         ms = 0;
1530                                         break;
1531                                 default:
1532                                         ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", chan->name);
1533                                         details->caps &= ~AST_FAX_TECH_T38;
1534                                         ms = 0;
1535                                         break;
1536                                 }
1537                         }
1538                         ast_frfree(frame);
1539                 }
1540
1541                 /* if T.38 was negotiated, we are done initializing */
1542                 if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1543                         return 0;
1544                 }
1545
1546                 /* send one more CNG tone to get audio going again for some
1547                  * carriers if we are going to fall back to audio mode */
1548                 if (details->option.allow_audio == AST_FAX_OPTFLAG_TRUE) {
1549                         if (ast_playtones_start(chan, 1024, "!1100/500,!0/3000", 1)) {
1550                                 ast_log(LOG_ERROR, "error generating second CNG tone on %s\n", chan->name);
1551                                 return -1;
1552                         }
1553
1554                         ms = 3500;
1555                         while (ms > 0) {
1556                                 ms = ast_waitfor(chan, ms);
1557                                 if (ms < 0) {
1558                                         ast_log(LOG_ERROR, "error while generating second CNG tone on %s\n", chan->name);
1559                                         ast_playtones_stop(chan);
1560                                         return -1;
1561                                 }
1562
1563                                 if (ms == 0) { /* all done, nothing happened */
1564                                         break;
1565                                 }
1566
1567                                 if (!(frame = ast_read(chan))) {
1568                                         ast_log(LOG_ERROR, "error reading frame while generating second CNG tone on %s\n", chan->name);
1569                                         ast_playtones_stop(chan);
1570                                         return -1;
1571                                 }
1572
1573                                 if ((frame->frametype == AST_FRAME_CONTROL) &&
1574                                                 (frame->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
1575                                                 (frame->datalen == sizeof(t38_parameters))) {
1576                                         struct ast_control_t38_parameters *parameters = frame->data.ptr;
1577
1578                                         switch (parameters->request_response) {
1579                                         case AST_T38_REQUEST_NEGOTIATE:
1580                                                 /* the other end has requested a switch to T.38, so reply that we are willing, if we can
1581                                                  * do T.38 as well
1582                                                  */
1583                                                 t38_parameters_fax_to_ast(&t38_parameters, &details->our_t38_parameters);
1584                                                 t38_parameters.request_response = (details->caps & AST_FAX_TECH_T38) ? AST_T38_NEGOTIATED : AST_T38_REFUSED;
1585                                                 ast_indicate_data(chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
1586                                                 ast_playtones_stop(chan);
1587                                                 break;
1588                                         case AST_T38_NEGOTIATED:
1589                                                 ast_log(LOG_NOTICE, "Negotiated T.38 for send on %s\n", chan->name);
1590                                                 t38_parameters_ast_to_fax(&details->their_t38_parameters, parameters);
1591                                                 details->caps &= ~AST_FAX_TECH_AUDIO;
1592                                                 report_fax_status(chan, details, "T.38 Negotiated");
1593                                                 ms = 0;
1594                                                 break;
1595                                         default:
1596                                                 break;
1597                                         }
1598                                 }
1599                                 ast_frfree(frame);
1600                         }
1601
1602                         ast_playtones_stop(chan);
1603
1604                         /* if T.38 was negotiated, we are done initializing */
1605                         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1606                                 return 0;
1607                         }
1608                 }
1609         }
1610
1611         /* if we made it here, then T.38 failed, check the 'f' flag */
1612         if (details->option.allow_audio == AST_FAX_OPTFLAG_FALSE) {
1613                 ast_log(LOG_WARNING, "Audio FAX not allowed on channel '%s' and T.38 negotiation failed; aborting.\n", chan->name);
1614                 return -1;
1615         }
1616
1617         /* ok, audio fallback is allowed */
1618         details->caps |= AST_FAX_TECH_AUDIO;
1619
1620         return 0;
1621 }
1622
1623
1624 /*! \brief initiate a send FAX session */
1625 static int sendfax_exec(struct ast_channel *chan, const char *data)
1626 {
1627         char *parse, *filenames, *c;
1628         int channel_alive, file_count;
1629         struct ast_fax_session_details *details;
1630         struct ast_fax_document *doc;
1631         AST_DECLARE_APP_ARGS(args,
1632                 AST_APP_ARG(filenames);
1633                 AST_APP_ARG(options);
1634         );
1635         struct ast_flags opts = { 0, };
1636         struct manager_event_info info;
1637
1638         /* Get a requirement structure and set it.  This structure is used
1639          * to tell the FAX technology module about the higher level FAX session */
1640         if (!(details = find_or_create_details(chan))) {
1641                 ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1642                 return -1;
1643         }
1644
1645         if (ast_strlen_zero(data)) {
1646                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1647                 ast_string_field_set(details, resultstr, "invalid arguments");
1648                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]][,options])\n", app_sendfax);
1649                 return -1;
1650         }
1651         parse = ast_strdupa(data);
1652         AST_STANDARD_APP_ARGS(args, parse);
1653
1654         /* initialize output channel variables */
1655         pbx_builtin_setvar_helper(chan, "FAXSTATUS", "FAILED");
1656         pbx_builtin_setvar_helper(chan, "FAXERROR", "Application Problems");
1657         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Invalid application arguments.");
1658         pbx_builtin_setvar_helper(chan, "REMOTESTATIONID", NULL);
1659         pbx_builtin_setvar_helper(chan, "FAXPAGES", "0");
1660         pbx_builtin_setvar_helper(chan, "FAXBITRATE", NULL);
1661         pbx_builtin_setvar_helper(chan, "FAXRESOLUTION", NULL);
1662
1663         if (!ast_strlen_zero(args.options) &&
1664             ast_app_parse_options(fax_exec_options, &opts, NULL, args.options)) {
1665                 return -1;
1666         }
1667         if (ast_strlen_zero(args.filenames)) {
1668                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1669                 ast_string_field_set(details, resultstr, "invalid arguments");
1670                 ast_log(LOG_WARNING, "%s requires an argument (filename[&filename[&filename]],options])\n", app_sendfax);
1671                 return -1;
1672         }
1673         
1674         /* check for unsupported FAX application options */
1675         if (ast_test_flag(&opts, OPT_CALLERMODE) || ast_test_flag(&opts, OPT_CALLEDMODE)) {
1676                 ast_string_field_set(details, error, "INVALID_ARGUMENTS");
1677                 ast_string_field_set(details, resultstr, "invalid arguments");
1678                 ast_log(LOG_WARNING, "%s does not support polling\n", app_sendfax);
1679                 return -1;
1680         }
1681
1682         /* make sure the channel is up */
1683         if (chan->_state != AST_STATE_UP) {
1684                 if (ast_answer(chan)) {
1685                         ast_log(LOG_WARNING, "Channel '%s' failed answer attempt.\n", chan->name);
1686                         return -1;
1687                 }
1688         }
1689
1690         ast_atomic_fetchadd_int(&faxregistry.fax_tx_attempts, 1);
1691         
1692         pbx_builtin_setvar_helper(chan, "FAXERROR", "Channel Problems");
1693         pbx_builtin_setvar_helper(chan, "FAXSTATUSSTRING", "Error before FAX transmission started.");
1694
1695         file_count = 0;
1696         filenames = args.filenames;
1697         while ((c = strsep(&filenames, "&"))) {
1698                 if (access(c, (F_OK | R_OK)) < 0) {
1699                         ast_string_field_set(details, error, "FILE_ERROR");
1700                         ast_string_field_set(details, resultstr, "error reading file");
1701                         ast_log(LOG_ERROR, "access failure.  Verify '%s' exists and check permissions.\n", args.filenames);
1702                         ao2_ref(details, -1);
1703                         return -1;
1704                 }
1705
1706                 if (!(doc = ast_calloc(1, sizeof(*doc) + strlen(c) + 1))) {
1707                         ast_string_field_set(details, error, "MEMORY_ERROR");
1708                         ast_string_field_set(details, resultstr, "error allocating memory");
1709                         ast_log(LOG_ERROR, "System cannot provide memory for session requirements.\n");
1710                         ao2_ref(details, -1);
1711                         return -1;
1712                 }
1713
1714                 strcpy(doc->filename, c);
1715                 AST_LIST_INSERT_TAIL(&details->documents, doc, next);
1716                 file_count++;
1717         }
1718
1719         if (file_count > 1) {
1720                 details->caps |= AST_FAX_TECH_MULTI_DOC;
1721         }
1722
1723         ast_verb(3, "Channel '%s' sending FAX:\n", chan->name);
1724         AST_LIST_TRAVERSE(&details->documents, doc, next) {
1725                 ast_verb(3, "   %s\n", doc->filename);
1726         }
1727
1728         details->caps = AST_FAX_TECH_SEND;
1729
1730         /* check for debug */
1731         if (ast_test_flag(&opts, OPT_DEBUG) || global_fax_debug) {
1732                 details->option.debug = AST_FAX_OPTFLAG_TRUE;
1733         }
1734
1735         /* check for request for status events */
1736         if (ast_test_flag(&opts, OPT_STATUS)) {
1737                 details->option.statusevents = AST_FAX_OPTFLAG_TRUE;
1738         }
1739
1740         if ((ast_channel_get_t38_state(chan) == T38_STATE_UNAVAILABLE) ||
1741             ast_test_flag(&opts, OPT_ALLOWAUDIO)) {
1742                 details->option.allow_audio = AST_FAX_OPTFLAG_TRUE;
1743         }
1744
1745         if (ast_test_flag(&opts, OPT_REQUEST_T38)) {
1746                 details->option.request_t38 = AST_FAX_OPTFLAG_TRUE;
1747         }
1748
1749         if (set_fax_t38_caps(chan, details)) {
1750                 ast_string_field_set(details, error, "T38_NEG_ERROR");
1751                 ast_string_field_set(details, resultstr, "error negotiating T.38");
1752                 ao2_ref(details, -1);
1753                 return -1;
1754         }
1755
1756         if (details->caps & AST_FAX_TECH_T38) {
1757                 if (sendfax_t38_init(chan, details)) {
1758                         ast_string_field_set(details, error, "T38_NEG_ERROR");
1759                         ast_string_field_set(details, resultstr, "error negotiating T.38");
1760                         ao2_ref(details, -1);
1761                         ast_log(LOG_ERROR, "error initializing channel '%s' in T.38 mode\n", chan->name);
1762                         return -1;
1763                 }
1764         } else {
1765                 details->option.send_cng = 1;
1766         }
1767
1768         if ((channel_alive = generic_fax_exec(chan, details)) < 0) {
1769                 ast_atomic_fetchadd_int(&faxregistry.fax_failures, 1);
1770         }
1771
1772         if (ast_channel_get_t38_state(chan) == T38_STATE_NEGOTIATED) {
1773                 if (disable_t38(chan)) {
1774                         ast_log(LOG_WARNING, "error disabling T.38 mode on %s\n", chan->name);
1775                 }
1776         }
1777
1778         if (!(filenames = generate_filenames_string(details, "FileName: ", "\r\n"))) {
1779                 ast_log(LOG_ERROR, "Error generating SendFAX manager event\n");
1780                 ao2_ref(details, -1);
1781                 return (!channel_alive) ? -1 : 0;
1782         }
1783
1784         /* send out the AMI completion event */
1785         ast_channel_lock(chan);
1786         get_manager_event_info(chan, &info);
1787         manager_event(EVENT_FLAG_CALL,
1788                       "SendFAX", 
1789                       "Channel: %s\r\n"
1790                       "Context: %s\r\n"
1791                       "Exten: %s\r\n"
1792                       "CallerID: %s\r\n"
1793                       "RemoteStationID: %s\r\n"
1794                       "LocalStationID: %s\r\n"
1795                       "PagesTransferred: %s\r\n"
1796                       "Resolution: %s\r\n"
1797                       "TransferRate: %s\r\n"
1798                       "%s\r\n",
1799                       chan->name,
1800                       info.context,
1801                       info.exten,
1802                       info.cid,
1803                       pbx_builtin_getvar_helper(chan, "REMOTESTATIONID"),
1804                       pbx_builtin_getvar_helper(chan, "LOCALSTATIONID"),
1805                       pbx_builtin_getvar_helper(chan, "FAXPAGES"),
1806                       pbx_builtin_getvar_helper(chan, "FAXRESOLUTION"),
1807                       pbx_builtin_getvar_helper(chan, "FAXBITRATE"),
1808                       filenames);
1809         ast_channel_unlock(chan);
1810
1811         ast_free(filenames);
1812
1813         ao2_ref(details, -1);
1814
1815         /* If the channel hungup return -1; otherwise, return 0 to continue in the dialplan */
1816         return (!channel_alive) ? -1 : 0;
1817 }
1818
1819 /*! \brief hash callback for ao2 */
1820 static int session_hash_cb(const void *obj, const int flags)
1821 {
1822         const struct ast_fax_session *s = obj;
1823
1824         return s->id;
1825 }
1826
1827 /*! \brief compare callback for ao2 */
1828 static int session_cmp_cb(void *obj, void *arg, int flags)
1829 {
1830         struct ast_fax_session *lhs = obj, *rhs = arg;
1831
1832         return (lhs->id == rhs->id) ? CMP_MATCH | CMP_STOP : 0;
1833 }
1834
1835 /*! \brief fax session tab completion */
1836 static char *fax_session_tab_complete(struct ast_cli_args *a)
1837 {
1838         int tklen;
1839         int wordnum = 0;
1840         char *name = NULL;
1841         struct ao2_iterator i;
1842         struct ast_fax_session *s;
1843         char tbuf[5];
1844
1845         if (a->pos != 3) {
1846                 return NULL;
1847         }
1848
1849         tklen = strlen(a->word);
1850         i = ao2_iterator_init(faxregistry.container, 0);
1851         while ((s = ao2_iterator_next(&i))) {
1852                 snprintf(tbuf, sizeof(tbuf), "%d", s->id);
1853                 if (!strncasecmp(a->word, tbuf, tklen) && ++wordnum > a->n) {
1854                         name = ast_strdup(tbuf);
1855                         ao2_ref(s, -1);
1856                         break;
1857                 }
1858                 ao2_ref(s, -1);
1859         }
1860         if (ao2_iterator_destroy != NULL) {
1861                 ao2_iterator_destroy(&i);
1862         }
1863         return name;
1864 }
1865
1866 static char *cli_fax_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1867 {
1868         struct fax_module *fax;
1869
1870         switch(cmd) {
1871         case CLI_INIT:
1872                 e->command = "fax show version";
1873                 e->usage =
1874                         "Usage: fax show version\n"
1875                         "       Show versions of FAX For Asterisk components.\n";
1876                 return NULL;
1877         case CLI_GENERATE:
1878                 return NULL;
1879         }
1880
1881         if (a->argc != 3) {
1882                 return CLI_SHOWUSAGE;
1883         }
1884
1885         ast_cli(a->fd, "FAX For Asterisk Components:\n");
1886         ast_cli(a->fd, "\tApplications: %s\n", ast_get_version());
1887         AST_RWLIST_RDLOCK(&faxmodules);
1888         AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
1889                 ast_cli(a->fd, "\t%s: %s\n", fax->tech->description, fax->tech->version);
1890         }
1891         AST_RWLIST_UNLOCK(&faxmodules);
1892         ast_cli(a->fd, "\n");
1893
1894         return CLI_SUCCESS;
1895 }
1896
1897 /*! \brief enable FAX debugging */
1898 static char *cli_fax_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1899 {
1900         int flag;
1901         const char *what;
1902
1903         switch (cmd) {
1904         case CLI_INIT:
1905                 e->command = "fax set debug {on|off}";
1906                 e->usage = 
1907                         "Usage: fax set debug { on | off }\n"
1908                         "       Enable/Disable FAX debugging on new FAX sessions.  The basic FAX debugging will result in\n"
1909                         "       additional events sent to manager sessions with 'call' class permissions.  When\n"
1910                         "       verbosity is greater than '5' events will be displayed to the console and audio versus\n"
1911                         "       energy analysis will be performed and displayed to the console.\n";
1912                 return NULL;
1913         case CLI_GENERATE:
1914                 return NULL;
1915         }
1916
1917         what = a->argv[e->args-1];      /* guaranteed to exist */
1918         if (!strcasecmp(what, "on")) {
1919                 flag = 1;
1920         } else if (!strcasecmp(what, "off")) {
1921                 flag = 0;
1922         } else {
1923                 return CLI_SHOWUSAGE;
1924         }
1925
1926         global_fax_debug = flag;
1927         ast_cli(a->fd, "\n\nFAX Debug %s\n\n", (flag) ? "Enabled" : "Disabled");
1928
1929         return CLI_SUCCESS;
1930 }
1931
1932 /*! \brief display registered FAX capabilities */
1933 static char *cli_fax_show_capabilities(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1934 {
1935         struct fax_module *fax;
1936         unsigned int num_modules = 0;
1937         
1938         switch (cmd) {
1939         case CLI_INIT:
1940                 e->command = "fax show capabilities";
1941                 e->usage = 
1942                         "Usage: fax show capabilities\n"
1943                         "       Shows the capabilities of the registered FAX technology modules\n";
1944                 return NULL;
1945         case CLI_GENERATE:
1946                 return NULL;
1947         }
1948
1949         ast_cli(a->fd, "\n\nRegistered FAX Technology Modules:\n\n");
1950         AST_RWLIST_RDLOCK(&faxmodules);
1951         AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
1952                 ast_cli(a->fd, "%-15s : %s\n%-15s : %s\n%-15s : ", "Type", fax->tech->type, "Description", fax->tech->description, "Capabilities");
1953                 fax->tech->cli_show_capabilities(a->fd);
1954                 num_modules++;
1955         }
1956         AST_RWLIST_UNLOCK(&faxmodules);
1957         ast_cli(a->fd, "%d registered modules\n\n", num_modules);
1958
1959         return CLI_SUCCESS;
1960 }
1961
1962 /*! \brief display global defaults and settings */
1963 static char *cli_fax_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1964 {
1965         struct fax_module *fax;
1966         char modems[128] = "";
1967
1968         switch (cmd) {
1969         case CLI_INIT:
1970                 e->command = "fax show settings";
1971                 e->usage =
1972                         "Usage: fax show settings\n"
1973                         "       Show the global settings and defaults of both the FAX core and technology modules\n";
1974                 return NULL;
1975         case CLI_GENERATE:
1976                 return NULL;
1977         }
1978
1979         ast_cli(a->fd, "FAX For Asterisk Settings:\n");
1980         ast_cli(a->fd, "\tECM: %s\n", general_options.ecm ? "Enabled" : "Disabled");
1981         ast_cli(a->fd, "\tStatus Events: %s\n",  general_options.statusevents ? "On" : "Off");
1982         ast_cli(a->fd, "\tMinimum Bit Rate: %d\n", general_options.minrate);
1983         ast_cli(a->fd, "\tMaximum Bit Rate: %d\n", general_options.maxrate);
1984         ast_fax_modem_to_str(general_options.modems, modems, sizeof(modems));
1985         ast_cli(a->fd, "\tModem Modulations Allowed: %s\n", modems);
1986         ast_cli(a->fd, "\n\nFAX Technology Modules:\n\n");
1987         AST_RWLIST_RDLOCK(&faxmodules);
1988         AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
1989                 ast_cli(a->fd, "%s (%s) Settings:\n", fax->tech->type, fax->tech->description);
1990                 fax->tech->cli_show_settings(a->fd);
1991         }
1992         AST_RWLIST_UNLOCK(&faxmodules);
1993
1994         return CLI_SUCCESS;
1995 }
1996
1997 /*! \brief display details of a specified fax session */
1998 static char *cli_fax_show_session(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1999 {
2000         struct ast_fax_session *s, tmp;
2001
2002         switch (cmd) {
2003         case CLI_INIT:
2004                 e->command = "fax show session";
2005                 e->usage =
2006                         "Usage: fax show session <session number>\n"
2007                         "       Shows status of the named FAX session\n";
2008                 return NULL;
2009         case CLI_GENERATE:
2010                 return fax_session_tab_complete(a);
2011         }
2012
2013         if (a->argc != 4) {
2014                 return CLI_SHOWUSAGE;
2015         }
2016
2017         if (sscanf(a->argv[3], "%d", &tmp.id) != 1) {
2018                 ast_log(LOG_ERROR, "invalid session id: '%s'\n", a->argv[3]);
2019                 return RESULT_SUCCESS;
2020         }
2021
2022         ast_cli(a->fd, "\nFAX Session Details:\n--------------------\n\n");
2023         s = ao2_find(faxregistry.container, &tmp, OBJ_POINTER);
2024         if (s) {
2025                 s->tech->cli_show_session(s, a->fd);
2026                 ao2_ref(s, -1);
2027         }
2028         ast_cli(a->fd, "\n\n");
2029
2030         return CLI_SUCCESS;
2031 }
2032         
2033 /*! \brief display fax stats */
2034 static char *cli_fax_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2035 {
2036         struct fax_module *fax;
2037         
2038         switch (cmd) {
2039         case CLI_INIT:
2040                 e->command = "fax show stats";
2041                 e->usage =
2042                         "Usage: fax show stats\n"
2043                         "       Shows a statistical summary of FAX transmissions\n";
2044                 return NULL;
2045         case CLI_GENERATE:
2046                 return NULL;
2047         }
2048
2049         ast_cli(a->fd, "\nFAX Statistics:\n---------------\n\n");
2050         ast_cli(a->fd, "%-20.20s : %d\n", "Current Sessions", faxregistry.active_sessions);
2051         ast_cli(a->fd, "%-20.20s : %d\n", "Transmit Attempts", faxregistry.fax_tx_attempts);
2052         ast_cli(a->fd, "%-20.20s : %d\n", "Receive Attempts", faxregistry.fax_rx_attempts);
2053         ast_cli(a->fd, "%-20.20s : %d\n", "Completed FAXes", faxregistry.fax_complete);
2054         ast_cli(a->fd, "%-20.20s : %d\n", "Failed FAXes", faxregistry.fax_failures);
2055         AST_RWLIST_RDLOCK(&faxmodules);
2056         AST_RWLIST_TRAVERSE(&faxmodules, fax, list) {
2057                 fax->tech->cli_show_stats(a->fd);
2058         }
2059         AST_RWLIST_UNLOCK(&faxmodules);
2060         ast_cli(a->fd, "\n\n");
2061
2062         return CLI_SUCCESS;
2063 }
2064
2065 /*! \brief display fax sessions */
2066 static char *cli_fax_show_sessions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2067 {
2068         struct ast_fax_session *s;
2069         struct ao2_iterator i;
2070         int session_count;
2071         char *filenames;
2072
2073         switch (cmd) {
2074         case CLI_INIT:
2075                 e->command = "fax show sessions";
2076                 e->usage =
2077                         "Usage: fax show sessions\n"
2078                         "       Shows the current FAX sessions\n";
2079                 return NULL;
2080         case CLI_GENERATE:
2081                 return NULL;
2082         }
2083
2084         ast_cli(a->fd, "\nCurrent FAX Sessions:\n\n");
2085         ast_cli(a->fd, "%-20.20s %-10.10s %-10.10s %-5.5s %-10.10s %-15.15s %-30.30s\n",
2086                 "Channel", "Tech", "FAXID", "Type", "Operation", "State", "File(s)");
2087         i = ao2_iterator_init(faxregistry.container, 0);
2088         while ((s = ao2_iterator_next(&i))) {
2089                 ao2_lock(s);
2090
2091                 if (!(filenames = generate_filenames_string(s->details, "", ", "))) {
2092                         ast_log(LOG_ERROR, "error printing filenames for 'fax show sessions' command");
2093                         ao2_unlock(s);
2094                         ao2_ref(s, -1);
2095                         if (ao2_iterator_destroy != NULL) {
2096                                 ao2_iterator_destroy(&i);
2097                         }
2098                         return CLI_FAILURE;
2099                 }
2100
2101                 ast_cli(a->fd, "%-20.20s %-10.10s %-10d %-5.5s %-10.10s %-15.15s %-30s\n",
2102                         s->channame, s->tech->type, s->id,
2103                         (s->details->caps & AST_FAX_TECH_AUDIO) ? "G.711" : "T.38",
2104                         (s->details->caps & AST_FAX_TECH_SEND) ? "send" : "receive",
2105                         ast_fax_state_to_str(s->state), filenames);
2106
2107                 ast_free(filenames);
2108                 ao2_unlock(s);
2109                 ao2_ref(s, -1);
2110         }
2111         if (ao2_iterator_destroy != NULL) {
2112                 ao2_iterator_destroy(&i);
2113         }
2114         session_count = ao2_container_count(faxregistry.container);
2115         ast_cli(a->fd, "\n%d FAX sessions\n\n", session_count);
2116
2117         return CLI_SUCCESS;
2118 }
2119
2120 static struct ast_cli_entry fax_cli[] = {
2121         AST_CLI_DEFINE(cli_fax_show_version, "Show versions of FAX For Asterisk components"),
2122         AST_CLI_DEFINE(cli_fax_set_debug, "Enable/Disable FAX debugging on new FAX sessions"),
2123         AST_CLI_DEFINE(cli_fax_show_capabilities, "Show the capabilities of the registered FAX technology modules"),
2124         AST_CLI_DEFINE(cli_fax_show_settings, "Show the global settings and defaults of both the FAX core and technology modules"),
2125         AST_CLI_DEFINE(cli_fax_show_session, "Show the status of the named FAX sessions"),
2126         AST_CLI_DEFINE(cli_fax_show_sessions, "Show the current FAX sessions"),
2127         AST_CLI_DEFINE(cli_fax_show_stats, "Summarize FAX session history"),
2128 };
2129
2130 /*! \brief configure res_fax */
2131 static int set_config(const char *config_file)
2132 {
2133         struct ast_config *cfg;
2134         struct ast_variable *v;
2135         struct ast_flags config_flags = { 0 };
2136
2137         /* set defaults */      
2138         general_options.minrate = RES_FAX_MINRATE;
2139         general_options.maxrate = RES_FAX_MAXRATE;      
2140         general_options.statusevents = RES_FAX_STATUSEVENTS;
2141         general_options.modems = RES_FAX_MODEM;
2142         general_options.ecm = AST_FAX_OPTFLAG_TRUE;
2143
2144         /* read configuration */
2145         if (!(cfg = ast_config_load2(config_file, "res_fax", config_flags))) {
2146                 ast_log(LOG_NOTICE, "Configuration file '%s' not found, using default options.\n", config_file);
2147                 return 0;
2148         }
2149         if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
2150                 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
2151                 cfg = ast_config_load2(config_file, "res_fax", config_flags);
2152         }
2153
2154         /* create configuration */
2155         for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
2156                 int rate;
2157
2158                 if (!strcasecmp(v->name, "minrate")) {
2159                         ast_debug(3, "reading minrate '%s' from configuration file\n", v->value);
2160                         if ((rate = fax_rate_str_to_int(v->value)) == 0) {
2161                                 ast_config_destroy(cfg);
2162                                 return -1;
2163                         }
2164                         general_options.minrate = rate;
2165                 } else if (!strcasecmp(v->name, "maxrate")) {
2166                         ast_debug(3, "reading maxrate '%s' from configuration file\n", v->value);
2167                         if ((rate = fax_rate_str_to_int(v->value)) == 0) {
2168                                 ast_config_destroy(cfg);
2169                                 return -1;
2170                         }
2171                         general_options.maxrate = rate;
2172                 } else if (!strcasecmp(v->name, "statusevents")) {
2173                         ast_debug(3, "reading statusevents '%s' from configuration file\n", v->value);
2174                         general_options.statusevents = ast_true(v->value);
2175                 } else if (!strcasecmp(v->name, "ecm")) {
2176                         ast_debug(3, "reading ecm '%s' from configuration file\n", v->value);
2177                         general_options.ecm = ast_true(v->value);
2178                 } else if ((!strcasecmp(v->name, "modem")) || (!strcasecmp(v->name, "modems"))) {
2179                         general_options.modems = 0;
2180                         update_modem_bits(&general_options.modems, v->value);
2181                 }
2182         }
2183
2184         ast_config_destroy(cfg);
2185
2186         return 0;
2187 }
2188
2189 /*! \brief FAXOPT read function returns the contents of a FAX option */
2190 static int acf_faxopt_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
2191 {
2192         struct ast_fax_session_details *details = find_details(chan);
2193         int res = 0;
2194         char *filenames;
2195
2196         if (!details) {
2197                 ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", chan->name, data);
2198                 return -1;
2199         }
2200         if (!strcasecmp(data, "ecm")) {
2201                 ast_copy_string(buf, details->option.ecm ? "yes" : "no", len);
2202         } else if (!strcasecmp(data, "error")) {
2203                 ast_copy_string(buf, details->error, len);
2204         } else if (!strcasecmp(data, "filename")) {
2205                 if (AST_LIST_EMPTY(&details->documents)) {
2206                         ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", chan->name, data);
2207                         res = -1;
2208                 } else {
2209                         ast_copy_string(buf, AST_LIST_FIRST(&details->documents)->filename, len);
2210                 }
2211         } else if (!strcasecmp(data, "filenames")) {
2212                 if (AST_LIST_EMPTY(&details->documents)) {
2213                         ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s) because it has never been written.\n", chan->name, data);
2214                         res = -1;
2215                 } else if ((filenames = generate_filenames_string(details, "", ","))) {
2216                         ast_copy_string(buf, filenames, len);
2217                         ast_free(filenames);
2218                 } else {
2219                         ast_log(LOG_ERROR, "channel '%s' can't read FAXOPT(%s), there was an error generating the filenames list.\n", chan->name, data);
2220                         res = -1;
2221                 }
2222         } else if (!strcasecmp(data, "headerinfo")) {
2223                 ast_copy_string(buf, details->headerinfo, len);
2224         } else if (!strcasecmp(data, "localstationid")) {
2225                 ast_copy_string(buf, details->localstationid, len);
2226         } else if (!strcasecmp(data, "maxrate")) {
2227                 snprintf(buf, len, "%d", details->maxrate);
2228         } else if (!strcasecmp(data, "minrate")) {
2229                 snprintf(buf, len, "%d", details->minrate);
2230         } else if (!strcasecmp(data, "pages")) {
2231                 snprintf(buf, len, "%d", details->pages_transferred);
2232         } else if (!strcasecmp(data, "rate")) {
2233                 ast_copy_string(buf, details->transfer_rate, len);
2234         } else if (!strcasecmp(data, "remotestationid")) {
2235                 ast_copy_string(buf, details->remotestationid, len);
2236         } else if (!strcasecmp(data, "resolution")) {
2237                 ast_copy_string(buf, details->resolution, len);
2238         } else if (!strcasecmp(data, "sessionid")) {
2239                 snprintf(buf, len, "%d", details->id);
2240         } else if (!strcasecmp(data, "status")) {
2241                 ast_copy_string(buf, details->result, len);
2242         } else if (!strcasecmp(data, "statusstr")) {
2243                 ast_copy_string(buf, details->resultstr, len);
2244         } else if ((!strcasecmp(data, "modem")) || (!strcasecmp(data, "modems"))) {
2245                 ast_fax_modem_to_str(details->modems, buf, len);
2246         } else {
2247                 ast_log(LOG_WARNING, "channel '%s' can't read FAXOPT(%s) because it is unhandled!\n", chan->name, data);
2248                 res = -1;
2249         }
2250         ao2_ref(details, -1);
2251
2252         return res;
2253 }
2254
2255 /*! \brief FAXOPT write function modifies the contents of a FAX option */
2256 static int acf_faxopt_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
2257 {
2258         int res = 0;
2259         struct ast_fax_session_details *details;
2260
2261         if (!(details = find_or_create_details(chan))) {
2262                 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);
2263                 return -1;
2264         }
2265         ast_debug(3, "channel '%s' setting FAXOPT(%s) to '%s'\n", chan->name, data, value);
2266
2267         if (!strcasecmp(data, "ecm")) {
2268                 const char *val = ast_skip_blanks(value);
2269                 if (ast_true(val)) {
2270                         details->option.ecm = AST_FAX_OPTFLAG_TRUE;
2271                 } else if (ast_false(val)) {
2272                         details->option.ecm = AST_FAX_OPTFLAG_FALSE;
2273                 } else {
2274                         ast_log(LOG_WARNING, "Unsupported value '%s' passed to FAXOPT(ecm).\n", value);
2275                 }
2276         } else if (!strcasecmp(data, "headerinfo")) {
2277                 ast_string_field_set(details, headerinfo, value);
2278         } else if (!strcasecmp(data, "localstationid")) {
2279                 ast_string_field_set(details, localstationid, value);
2280         } else if (!strcasecmp(data, "maxrate")) {
2281                 details->maxrate = fax_rate_str_to_int(value);
2282                 if (!details->maxrate) {
2283                         details->maxrate = ast_fax_maxrate();
2284                 }
2285         } else if (!strcasecmp(data, "minrate")) {
2286                 details->minrate = fax_rate_str_to_int(value);
2287                 if (!details->minrate) {
2288                         details->minrate = ast_fax_minrate();
2289                 }
2290         } else if ((!strcasecmp(data, "modem")) || (!strcasecmp(data, "modems"))) {
2291                 update_modem_bits(&details->modems, value);
2292         } else {
2293                 ast_log(LOG_WARNING, "channel '%s' set FAXOPT(%s) to '%s' is unhandled!\n", chan->name, data, value);
2294                 res = -1;
2295         }
2296
2297         ao2_ref(details, -1);
2298
2299         return res;
2300 }
2301
2302 /*! \brief FAXOPT dialplan function */
2303 struct ast_custom_function acf_faxopt = {
2304         .name = "FAXOPT",
2305         .synopsis = "Set options for use with the SendFAX and ReceiveFAX functions, or read options after a FAX transmission completes",
2306         .syntax = 
2307 "FAXOPT(<option>)\n"
2308 "  To write an option:\n"
2309 "     exten => blah,n,Set(FAXOPT(minrate)=4800)\n"
2310 "  To read an option:\n"
2311 "     exten => blah,n,NoOp(result: ${FAXOPT(status)})",
2312         .desc =
2313 "The following table outlines the <options> that can be used with FAXOPT\n\n"
2314 "  OPTION             TYPE     DESCRIPTION\n"
2315 "  ------             ----     -----------\n"
2316 "  ecm                 RW      Specify Error Correction Mode (ECM) with 'yes', disable with 'no'.\n"
2317 "  error               RO      Read the FAX transmission error upon failure.\n"
2318 "  filename            RO      Read the filename of the first file of the FAX transmission.\n"
2319 "  filenames           RO      Read the filenames of all of the files in the FAX transmission (comma separated).\n"
2320 "  headerinfo          RW      Specify or read the FAX header.\n"
2321 "  localstationid      RW      Specify or read the local station identification\n"
2322 "  maxrate             RW      Specify or read the maximum transfer rate before transmission\n"
2323 "  minrate             RW      Specify or read the minimum transfer rate before transmission\n"
2324 "  modem               RW      Specify or read the FAX modem\n"
2325 "  pages               RO      Read the number of pages transferred\n"
2326 "  rate                RO      Read the negotiated transmission rate\n"
2327 "  remotestationid     RO      Read the remote station identification after the transmission\n"
2328 "  resolution          RO      Read the negotiated image resolution after the transmission\n"
2329 "  sessionid           RO      Read the session ID of the FAX transmission\n"
2330 "  status              RO      Read the result status of the FAX transmission\n"
2331 "  statusstr           RO      Read a verbose result status of the FAX transmission\n"
2332 "\n  RO : Read Only\n  RW : Read/Write\n  WO : Write Only\n"
2333 "",
2334         .read = acf_faxopt_read,
2335         .write = acf_faxopt_write,
2336 };
2337
2338 /*! \brief unload res_fax */
2339 static int unload_module(void)
2340 {
2341         ast_cli_unregister_multiple(fax_cli, ARRAY_LEN(fax_cli));
2342         
2343         if (ast_custom_function_unregister(&acf_faxopt) < 0) {
2344                 ast_log(LOG_WARNING, "failed to unregister function '%s'\n", acf_faxopt.name);
2345         }
2346
2347         if (ast_unregister_application(app_sendfax) < 0) {
2348                 ast_log(LOG_WARNING, "failed to unregister '%s'\n", app_sendfax);
2349         }
2350
2351         if (ast_unregister_application(app_receivefax) < 0) {
2352                 ast_log(LOG_WARNING, "failed to unregister '%s'\n", app_receivefax);
2353         }
2354
2355         if (fax_logger_level != -1) {
2356                 ast_logger_unregister_level("FAX");
2357         }
2358
2359         ao2_ref(faxregistry.container, -1);
2360
2361         return 0;
2362 }
2363
2364 /*! \brief load res_fax */
2365 static int load_module(void)
2366 {
2367         int res;
2368
2369         /* initialize the registry */
2370         faxregistry.active_sessions = 0;
2371         if (!(faxregistry.container = ao2_container_alloc(FAX_MAXBUCKETS, session_hash_cb, session_cmp_cb))) {
2372                 return AST_MODULE_LOAD_DECLINE;
2373         }
2374         
2375         if (set_config(config) < 0) {
2376                 ast_log(LOG_ERROR, "failed to load configuration file '%s'\n", config);
2377                 ao2_ref(faxregistry.container, -1);
2378                 return AST_MODULE_LOAD_DECLINE;
2379         }
2380
2381         /* register CLI operations and applications */
2382         if (ast_register_application(app_sendfax, sendfax_exec, synopsis_sendfax, descrip_sendfax) < 0) {
2383                 ast_log(LOG_WARNING, "failed to register '%s'.\n", app_sendfax);
2384                 ao2_ref(faxregistry.container, -1);
2385                 return AST_MODULE_LOAD_DECLINE;
2386         }
2387         if (ast_register_application(app_receivefax, receivefax_exec, synopsis_receivefax, descrip_receivefax) < 0) {
2388                 ast_log(LOG_WARNING, "failed to register '%s'.\n", app_receivefax);
2389                 ast_unregister_application(app_sendfax);
2390                 ao2_ref(faxregistry.container, -1);
2391                 return AST_MODULE_LOAD_DECLINE;
2392         }
2393         ast_cli_register_multiple(fax_cli, ARRAY_LEN(fax_cli));
2394         res = ast_custom_function_register(&acf_faxopt);        
2395         fax_logger_level = ast_logger_register_level("FAX");
2396
2397         return res;
2398 }
2399
2400
2401 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Generic FAX Applications",
2402                 .load = load_module,
2403                 .unload = unload_module,
2404                );