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