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