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