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