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