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