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