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