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