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