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