Merge "astobj2: Create function to copy weak proxied objects from container."
[asterisk/asterisk.git] / apps / app_fax.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Simple fax applications
5  *
6  * 2007-2008, Dmitry Andrianov <asterisk@dima.spb.ru>
7  *
8  * Code based on original implementation by Steve Underwood <steveu@coppice.org>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  *
13  */
14
15 /*** MODULEINFO
16         <defaultenabled>no</defaultenabled>
17         <depend>spandsp</depend>
18         <conflict>res_fax</conflict>
19         <support_level>deprecated</support_level>
20         <replacement>res_fax</replacement>
21 ***/
22
23 #include "asterisk.h"
24
25 #include <string.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <inttypes.h>
29 #include <pthread.h>
30 #include <errno.h>
31 #include <tiffio.h>
32
33 #define SPANDSP_EXPOSE_INTERNAL_STRUCTURES
34 #include <spandsp.h>
35 #include <spandsp/version.h>
36
37 #include "asterisk/lock.h"
38 #include "asterisk/file.h"
39 #include "asterisk/logger.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/app.h"
43 #include "asterisk/dsp.h"
44 #include "asterisk/module.h"
45 #include "asterisk/stasis.h"
46 #include "asterisk/stasis_channels.h"
47 #include "asterisk/format_cache.h"
48
49 /*** DOCUMENTATION
50         <application name="SendFAX" language="en_US" module="app_fax">
51                 <synopsis>
52                         Send a Fax
53                 </synopsis>
54                 <syntax>
55                         <parameter name="filename" required="true">
56                                 <para>Filename of TIFF file to fax</para>
57                         </parameter>
58                         <parameter name="a" required="false">
59                                 <para>Makes the application behave as the answering machine</para>
60                                 <para>(Default behavior is as calling machine)</para>
61                         </parameter>
62                 </syntax>
63                 <description>
64                         <para>Send a given TIFF file to the channel as a FAX.</para>
65                         <para>This application sets the following channel variables:</para>
66                         <variablelist>
67                                 <variable name="LOCALSTATIONID">
68                                         <para>To identify itself to the remote end</para>
69                                 </variable>
70                                 <variable name="LOCALHEADERINFO">
71                                         <para>To generate a header line on each page</para>
72                                 </variable>
73                                 <variable name="FAXSTATUS">
74                                         <value name="SUCCESS"/>
75                                         <value name="FAILED"/>
76                                 </variable>
77                                 <variable name="FAXERROR">
78                                         <para>Cause of failure</para>
79                                 </variable>
80                                 <variable name="REMOTESTATIONID">
81                                         <para>The CSID of the remote side</para>
82                                 </variable>
83                                 <variable name="FAXPAGES">
84                                         <para>Number of pages sent</para>
85                                 </variable>
86                                 <variable name="FAXBITRATE">
87                                         <para>Transmission rate</para>
88                                 </variable>
89                                 <variable name="FAXRESOLUTION">
90                                         <para>Resolution of sent fax</para>
91                                 </variable>
92                         </variablelist>
93                 </description>
94         </application>
95         <application name="ReceiveFAX" language="en_US" module="app_fax">
96                 <synopsis>
97                         Receive a Fax
98                 </synopsis>
99                 <syntax>
100                         <parameter name="filename" required="true">
101                                 <para>Filename of TIFF file save incoming fax</para>
102                         </parameter>
103                         <parameter name="c" required="false">
104                                 <para>Makes the application behave as the calling machine</para>
105                                 <para>(Default behavior is as answering machine)</para>
106                         </parameter>
107                 </syntax>
108                 <description>
109                         <para>Receives a FAX from the channel into the given filename
110                         overwriting the file if it already exists.</para>
111                         <para>File created will be in TIFF format.</para>
112
113                         <para>This application sets the following channel variables:</para>
114                         <variablelist>
115                                 <variable name="LOCALSTATIONID">
116                                         <para>To identify itself to the remote end</para>
117                                 </variable>
118                                 <variable name="LOCALHEADERINFO">
119                                         <para>To generate a header line on each page</para>
120                                 </variable>
121                                 <variable name="FAXSTATUS">
122                                         <value name="SUCCESS"/>
123                                         <value name="FAILED"/>
124                                 </variable>
125                                 <variable name="FAXERROR">
126                                         <para>Cause of failure</para>
127                                 </variable>
128                                 <variable name="REMOTESTATIONID">
129                                         <para>The CSID of the remote side</para>
130                                 </variable>
131                                 <variable name="FAXPAGES">
132                                         <para>Number of pages sent</para>
133                                 </variable>
134                                 <variable name="FAXBITRATE">
135                                         <para>Transmission rate</para>
136                                 </variable>
137                                 <variable name="FAXRESOLUTION">
138                                         <para>Resolution of sent fax</para>
139                                 </variable>
140                         </variablelist>
141                 </description>
142         </application>
143
144  ***/
145
146 static const char app_sndfax_name[] = "SendFAX";
147 static const char app_rcvfax_name[] = "ReceiveFAX";
148
149 #define MAX_SAMPLES 240
150
151 /* Watchdog. I have seen situations when remote fax disconnects (because of poor line
152    quality) while SpanDSP continues staying in T30_STATE_IV_CTC state forever.
153    To avoid this, we terminate when we see that T30 state does not change for 5 minutes.
154    We also terminate application when more than 30 minutes passed regardless of
155    state changes. This is just a precaution measure - no fax should take that long */
156
157 #define WATCHDOG_TOTAL_TIMEOUT  30 * 60
158 #define WATCHDOG_STATE_TIMEOUT  5 * 60
159
160 typedef struct {
161         struct ast_channel *chan;
162         enum ast_t38_state t38state;    /* T38 state of the channel */
163         int direction;                  /* Fax direction: 0 - receiving, 1 - sending */
164         int caller_mode;
165         char *file_name;
166         struct ast_control_t38_parameters t38parameters;
167         volatile int finished;
168 } fax_session;
169
170 static void span_message(int level, const char *msg)
171 {
172         if (level == SPAN_LOG_ERROR) {
173                 ast_log(LOG_ERROR, "%s", msg);
174         } else if (level == SPAN_LOG_WARNING) {
175                 ast_log(LOG_WARNING, "%s", msg);
176         } else {
177                 ast_debug(1, "%s", msg);
178         }
179 }
180
181 static int t38_tx_packet_handler(t38_core_state_t *s, void *user_data, const uint8_t *buf, int len, int count)
182 {
183         struct ast_channel *chan = (struct ast_channel *) user_data;
184
185         struct ast_frame outf = {
186                 .frametype = AST_FRAME_MODEM,
187                 .subclass.integer = AST_MODEM_T38,
188                 .src = __FUNCTION__,
189         };
190
191         /* TODO: Asterisk does not provide means of resending the same packet multiple
192           times so count is ignored at the moment */
193
194         AST_FRAME_SET_BUFFER(&outf, buf, 0, len);
195
196         if (ast_write(chan, &outf) < 0) {
197                 ast_log(LOG_WARNING, "Unable to write frame to channel; %s\n", strerror(errno));
198                 return -1;
199         }
200
201         return 0;
202 }
203
204 static void phase_e_handler(t30_state_t *f, void *user_data, int result)
205 {
206         RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
207         RAII_VAR(struct ast_json *, json_filenames, NULL, ast_json_unref);
208         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
209         const char *local_ident;
210         const char *far_ident;
211         char buf[20];
212         fax_session *s = (fax_session *) user_data;
213         t30_stats_t stat;
214         int pages_transferred;
215
216         ast_debug(1, "Fax phase E handler. result=%d\n", result);
217
218         t30_get_transfer_statistics(f, &stat);
219
220         s = (fax_session *) user_data;
221
222         if (result != T30_ERR_OK) {
223                 s->finished = -1;
224
225                 /* FAXSTATUS is already set to FAILED */
226                 pbx_builtin_setvar_helper(s->chan, "FAXERROR", t30_completion_code_to_str(result));
227
228                 ast_log(LOG_WARNING, "Error transmitting fax. result=%d: %s.\n", result, t30_completion_code_to_str(result));
229
230                 return;
231         }
232
233         s->finished = 1;
234
235         local_ident = S_OR(t30_get_tx_ident(f), "");
236         far_ident = S_OR(t30_get_rx_ident(f), "");
237         pbx_builtin_setvar_helper(s->chan, "FAXSTATUS", "SUCCESS");
238         pbx_builtin_setvar_helper(s->chan, "FAXERROR", NULL);
239         pbx_builtin_setvar_helper(s->chan, "REMOTESTATIONID", far_ident);
240 #if SPANDSP_RELEASE_DATE >= 20090220
241         pages_transferred = (s->direction) ? stat.pages_tx : stat.pages_rx;
242 #else
243         pages_transferred = stat.pages_transferred;
244 #endif
245         snprintf(buf, sizeof(buf), "%d", pages_transferred);
246         pbx_builtin_setvar_helper(s->chan, "FAXPAGES", buf);
247         snprintf(buf, sizeof(buf), "%d", stat.y_resolution);
248         pbx_builtin_setvar_helper(s->chan, "FAXRESOLUTION", buf);
249         snprintf(buf, sizeof(buf), "%d", stat.bit_rate);
250         pbx_builtin_setvar_helper(s->chan, "FAXBITRATE", buf);
251
252         ast_debug(1, "Fax transmitted successfully.\n");
253         ast_debug(1, "  Remote station ID: %s\n", far_ident);
254         ast_debug(1, "  Pages transferred: %d\n", pages_transferred);
255         ast_debug(1, "  Image resolution:  %d x %d\n", stat.x_resolution, stat.y_resolution);
256         ast_debug(1, "  Transfer Rate:     %d\n", stat.bit_rate);
257
258         json_filenames = ast_json_pack("[s]", s->file_name);
259         if (!json_filenames) {
260                 return;
261         }
262         ast_json_ref(json_filenames);
263         json_object = ast_json_pack("{s: s, s: s, s: s, s: i, s: i, s: i, s: o}",
264                 "type", s->direction ? "send" : "receive",
265                 "remote_station_id", AST_JSON_UTF8_VALIDATE(far_ident),
266                 "local_station_id", AST_JSON_UTF8_VALIDATE(local_ident),
267                 "fax_pages", pages_transferred,
268                 "fax_resolution", stat.y_resolution,
269                 "fax_bitrate", stat.bit_rate,
270                 "filenames", json_filenames);
271         message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(s->chan), ast_channel_fax_type(), json_object);
272         if (!message) {
273                 return;
274         }
275         stasis_publish(ast_channel_topic(s->chan), message);
276 }
277
278 /* === Helper functions to configure fax === */
279
280 /* Setup SPAN logging according to Asterisk debug level */
281 static int set_logging(logging_state_t *state)
282 {
283         int level = SPAN_LOG_WARNING + option_debug;
284
285         span_log_set_message_handler(state, span_message);
286         span_log_set_level(state, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | level);
287
288         return 0;
289 }
290
291 static void set_local_info(t30_state_t *state, fax_session *s)
292 {
293         const char *x;
294
295         x = pbx_builtin_getvar_helper(s->chan, "LOCALSTATIONID");
296         if (!ast_strlen_zero(x))
297                 t30_set_tx_ident(state, x);
298
299         x = pbx_builtin_getvar_helper(s->chan, "LOCALHEADERINFO");
300         if (!ast_strlen_zero(x))
301                 t30_set_tx_page_header_info(state, x);
302 }
303
304 static void set_file(t30_state_t *state, fax_session *s)
305 {
306         if (s->direction)
307                 t30_set_tx_file(state, s->file_name, -1, -1);
308         else
309                 t30_set_rx_file(state, s->file_name, -1);
310 }
311
312 static void set_ecm(t30_state_t *state, int ecm)
313 {
314         t30_set_ecm_capability(state, ecm);
315         t30_set_supported_compressions(state, T30_SUPPORT_T4_1D_COMPRESSION | T30_SUPPORT_T4_2D_COMPRESSION | T30_SUPPORT_T6_COMPRESSION);
316 }
317
318 /* === Generator === */
319
320 /* This function is only needed to return passed params so
321    generator_activate will save it to channel's generatordata */
322 static void *fax_generator_alloc(struct ast_channel *chan, void *params)
323 {
324         return params;
325 }
326
327 static int fax_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
328 {
329         fax_state_t *fax = (fax_state_t*) data;
330         uint8_t buffer[AST_FRIENDLY_OFFSET + MAX_SAMPLES * sizeof(uint16_t)];
331         int16_t *buf = (int16_t *) (buffer + AST_FRIENDLY_OFFSET);
332
333         struct ast_frame outf = {
334                 .frametype = AST_FRAME_VOICE,
335                 .subclass.format = ast_format_slin,
336                 .src = __FUNCTION__,
337         };
338
339         if (samples > MAX_SAMPLES) {
340                 ast_log(LOG_WARNING, "Only generating %d samples, where %d requested\n", MAX_SAMPLES, samples);
341                 samples = MAX_SAMPLES;
342         }
343
344         if ((len = fax_tx(fax, buf, samples)) > 0) {
345                 outf.samples = len;
346                 AST_FRAME_SET_BUFFER(&outf, buffer, AST_FRIENDLY_OFFSET, len * sizeof(int16_t));
347
348                 if (ast_write(chan, &outf) < 0) {
349                         ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
350                         return -1;
351                 }
352         }
353
354         return 0;
355 }
356
357 static struct ast_generator generator = {
358         .alloc = fax_generator_alloc,
359         .generate = fax_generator_generate,
360 };
361
362
363 /* === Transmission === */
364
365 static int transmit_audio(fax_session *s)
366 {
367         int res = -1;
368         struct ast_format *original_read_fmt;
369         struct ast_format *original_write_fmt = NULL;
370         fax_state_t fax;
371         t30_state_t *t30state;
372         struct ast_frame *inf = NULL;
373         int last_state = 0;
374         struct timeval now, start, state_change;
375         enum ast_t38_state t38_state;
376         struct ast_control_t38_parameters t38_parameters = { .version = 0,
377                                                              .max_ifp = 800,
378                                                              .rate = AST_T38_RATE_14400,
379                                                              .rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF,
380                                                              .fill_bit_removal = 1,
381 /*
382  * spandsp has API calls to support MMR and JBIG transcoding, but they aren't
383  * implemented quite yet... so don't offer them to the remote endpoint
384  *                                                           .transcoding_mmr = 1,
385  *                                                           .transcoding_jbig = 1,
386 */
387         };
388
389         /* if in called party mode, try to use T.38 */
390         if (s->caller_mode == FALSE) {
391                 /* check if we are already in T.38 mode (unlikely), or if we can request
392                  * a switch... if so, request it now and wait for the result, rather
393                  * than starting an audio FAX session that will have to be cancelled
394                  */
395                 if ((t38_state = ast_channel_get_t38_state(s->chan)) == T38_STATE_NEGOTIATED) {
396                         return 1;
397                 } else if ((t38_state != T38_STATE_UNAVAILABLE) &&
398                            (t38_parameters.request_response = AST_T38_REQUEST_NEGOTIATE,
399                             (ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) == 0))) {
400                         /* wait up to five seconds for negotiation to complete */
401                         unsigned int timeout = 5000;
402                         int ms;
403
404                         ast_debug(1, "Negotiating T.38 for receive on %s\n", ast_channel_name(s->chan));
405                         while (timeout > 0) {
406                                 ms = ast_waitfor(s->chan, 1000);
407                                 if (ms < 0) {
408                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(s->chan));
409                                         return -1;
410                                 }
411                                 if (!ms) {
412                                         /* nothing happened */
413                                         if (timeout > 0) {
414                                                 timeout -= 1000;
415                                                 continue;
416                                         } else {
417                                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 negotiation.\n", ast_channel_name(s->chan));
418                                                 break;
419                                         }
420                                 }
421                                 if (!(inf = ast_read(s->chan))) {
422                                         return -1;
423                                 }
424                                 if ((inf->frametype == AST_FRAME_CONTROL) &&
425                                     (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
426                                     (inf->datalen == sizeof(t38_parameters))) {
427                                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
428
429                                         switch (parameters->request_response) {
430                                         case AST_T38_NEGOTIATED:
431                                                 ast_debug(1, "Negotiated T.38 for receive on %s\n", ast_channel_name(s->chan));
432                                                 res = 1;
433                                                 break;
434                                         case AST_T38_REFUSED:
435                                                 ast_log(LOG_WARNING, "channel '%s' refused to negotiate T.38\n", ast_channel_name(s->chan));
436                                                 break;
437                                         default:
438                                                 ast_log(LOG_ERROR, "channel '%s' failed to negotiate T.38\n", ast_channel_name(s->chan));
439                                                 break;
440                                         }
441                                         ast_frfree(inf);
442                                         if (res == 1) {
443                                                 return 1;
444                                         } else {
445                                                 break;
446                                         }
447                                 }
448                                 ast_frfree(inf);
449                         }
450                 }
451         }
452
453 #if SPANDSP_RELEASE_DATE >= 20080725
454         /* for spandsp shaphots 0.0.6 and higher */
455         t30state = &fax.t30;
456 #else
457         /* for spandsp release 0.0.5 */
458         t30state = &fax.t30_state;
459 #endif
460
461     original_read_fmt = ao2_bump(ast_channel_readformat(s->chan));
462         res = ast_set_read_format(s->chan, ast_format_slin);
463         if (res < 0) {
464                 ast_log(LOG_WARNING, "Unable to set to linear read mode, giving up\n");
465                 goto done;
466         }
467
468         original_write_fmt = ao2_bump(ast_channel_writeformat(s->chan));
469         res = ast_set_write_format(s->chan, ast_format_slin);
470         if (res < 0) {
471                 ast_log(LOG_WARNING, "Unable to set to linear write mode, giving up\n");
472                 goto done;
473         }
474
475         /* Initialize T30 terminal */
476         fax_init(&fax, s->caller_mode);
477
478         /* Setup logging */
479         set_logging(&fax.logging);
480         set_logging(&t30state->logging);
481
482         /* Configure terminal */
483         set_local_info(t30state, s);
484         set_file(t30state, s);
485         set_ecm(t30state, TRUE);
486
487         fax_set_transmit_on_idle(&fax, TRUE);
488
489         t30_set_phase_e_handler(t30state, phase_e_handler, s);
490
491         start = state_change = ast_tvnow();
492
493         ast_activate_generator(s->chan, &generator, &fax);
494
495         while (!s->finished) {
496                 inf = NULL;
497
498                 if ((res = ast_waitfor(s->chan, 25)) < 0) {
499                         ast_debug(1, "Error waiting for a frame\n");
500                         break;
501                 }
502
503                 /* Watchdog */
504                 now = ast_tvnow();
505                 if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
506                         ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
507                         res = -1;
508                         break;
509                 }
510
511                 if (!res) {
512                         /* There was timeout waiting for a frame. Loop around and wait again */
513                         continue;
514                 }
515
516                 /* There is a frame available. Get it */
517                 res = 0;
518
519                 if (!(inf = ast_read(s->chan))) {
520                         ast_debug(1, "Channel hangup\n");
521                         res = -1;
522                         break;
523                 }
524
525                 ast_debug(10, "frame %d/%s, len=%d\n", inf->frametype, ast_format_get_name(inf->subclass.format), inf->datalen);
526
527                 /* Check the frame type. Format also must be checked because there is a chance
528                    that a frame in old format was already queued before we set channel format
529                    to slinear so it will still be received by ast_read */
530                 if (inf->frametype == AST_FRAME_VOICE &&
531                         (ast_format_cmp(inf->subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL)) {
532                         if (fax_rx(&fax, inf->data.ptr, inf->samples) < 0) {
533                                 /* I know fax_rx never returns errors. The check here is for good style only */
534                                 ast_log(LOG_WARNING, "fax_rx returned error\n");
535                                 res = -1;
536                                 break;
537                         }
538                         if (last_state != t30state->state) {
539                                 state_change = ast_tvnow();
540                                 last_state = t30state->state;
541                         }
542                 } else if ((inf->frametype == AST_FRAME_CONTROL) &&
543                            (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS)) {
544                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
545
546                         if (parameters->request_response == AST_T38_NEGOTIATED) {
547                                 /* T38 switchover completed */
548                                 s->t38parameters = *parameters;
549                                 ast_debug(1, "T38 negotiated, finishing audio loop\n");
550                                 res = 1;
551                                 break;
552                         } else if (parameters->request_response == AST_T38_REQUEST_NEGOTIATE) {
553                                 t38_parameters.request_response = AST_T38_NEGOTIATED;
554                                 ast_debug(1, "T38 request received, accepting\n");
555                                 /* Complete T38 switchover */
556                                 ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters));
557                                 /* Do not break audio loop, wait until channel driver finally acks switchover
558                                  * with AST_T38_NEGOTIATED
559                                  */
560                         }
561                 }
562
563                 ast_frfree(inf);
564                 inf = NULL;
565         }
566
567         ast_debug(1, "Loop finished, res=%d\n", res);
568
569         if (inf)
570                 ast_frfree(inf);
571
572         ast_deactivate_generator(s->chan);
573
574         /* If we are switching to T38, remove phase E handler. Otherwise it will be executed
575            by t30_terminate, display diagnostics and set status variables although no transmittion
576            has taken place yet. */
577         if (res > 0) {
578                 t30_set_phase_e_handler(t30state, NULL, NULL);
579         }
580
581         t30_terminate(t30state);
582         fax_release(&fax);
583
584 done:
585         if (original_write_fmt) {
586                 if (ast_set_write_format(s->chan, original_write_fmt) < 0)
587                         ast_log(LOG_WARNING, "Unable to restore write format on '%s'\n", ast_channel_name(s->chan));
588                 ao2_ref(original_write_fmt, -1);
589         }
590
591         if (original_read_fmt) {
592                 if (ast_set_read_format(s->chan, original_read_fmt) < 0)
593                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(s->chan));
594                 ao2_ref(original_read_fmt, -1);
595         }
596
597         return res;
598
599 }
600
601 static int transmit_t38(fax_session *s)
602 {
603         int res = 0;
604         t38_terminal_state_t t38;
605         struct ast_frame *inf = NULL;
606         int last_state = 0;
607         struct timeval now, start, state_change, last_frame;
608         t30_state_t *t30state;
609         t38_core_state_t *t38state;
610
611 #if SPANDSP_RELEASE_DATE >= 20080725
612         /* for spandsp shaphots 0.0.6 and higher */
613         t30state = &t38.t30;
614         t38state = &t38.t38_fe.t38;
615 #else
616         /* for spandsp releases 0.0.5 */
617         t30state = &t38.t30_state;
618         t38state = &t38.t38;
619 #endif
620
621         /* Initialize terminal */
622         memset(&t38, 0, sizeof(t38));
623         if (t38_terminal_init(&t38, s->caller_mode, t38_tx_packet_handler, s->chan) == NULL) {
624                 ast_log(LOG_WARNING, "Unable to start T.38 termination.\n");
625                 res = -1;
626                 goto disable_t38;
627         }
628
629         t38_set_max_datagram_size(t38state, s->t38parameters.max_ifp);
630
631         if (s->t38parameters.fill_bit_removal) {
632                 t38_set_fill_bit_removal(t38state, TRUE);
633         }
634         if (s->t38parameters.transcoding_mmr) {
635                 t38_set_mmr_transcoding(t38state, TRUE);
636         }
637         if (s->t38parameters.transcoding_jbig) {
638                 t38_set_jbig_transcoding(t38state, TRUE);
639         }
640
641         /* Setup logging */
642         set_logging(&t38.logging);
643         set_logging(&t30state->logging);
644         set_logging(&t38state->logging);
645
646         /* Configure terminal */
647         set_local_info(t30state, s);
648         set_file(t30state, s);
649         set_ecm(t30state, TRUE);
650
651         t30_set_phase_e_handler(t30state, phase_e_handler, s);
652
653         now = start = state_change = ast_tvnow();
654
655         while (!s->finished) {
656                 inf = NULL;
657
658                 if ((res = ast_waitfor(s->chan, 25)) < 0) {
659                         ast_debug(1, "Error waiting for a frame\n");
660                         break;
661                 }
662
663                 last_frame = now;
664
665                 /* Watchdog */
666                 now = ast_tvnow();
667                 if (ast_tvdiff_sec(now, start) > WATCHDOG_TOTAL_TIMEOUT || ast_tvdiff_sec(now, state_change) > WATCHDOG_STATE_TIMEOUT) {
668                         ast_log(LOG_WARNING, "It looks like we hung. Aborting.\n");
669                         res = -1;
670                         break;
671                 }
672
673                 t38_terminal_send_timeout(&t38, ast_tvdiff_us(now, last_frame) / (1000000 / 8000));
674
675                 if (!res) {
676                         /* There was timeout waiting for a frame. Loop around and wait again */
677                         continue;
678                 }
679
680                 /* There is a frame available. Get it */
681                 res = 0;
682
683                 if (!(inf = ast_read(s->chan))) {
684                         ast_debug(1, "Channel hangup\n");
685                         res = -1;
686                         break;
687                 }
688
689                 ast_debug(10, "frame %d/%d, len=%d\n", inf->frametype, inf->subclass.integer, inf->datalen);
690
691                 if (inf->frametype == AST_FRAME_MODEM && inf->subclass.integer == AST_MODEM_T38) {
692                         t38_core_rx_ifp_packet(t38state, inf->data.ptr, inf->datalen, inf->seqno);
693                         if (last_state != t30state->state) {
694                                 state_change = ast_tvnow();
695                                 last_state = t30state->state;
696                         }
697                 } else if (inf->frametype == AST_FRAME_CONTROL && inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) {
698                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
699                         if (parameters->request_response == AST_T38_TERMINATED) {
700                                 ast_debug(1, "T38 down, finishing\n");
701                                 break;
702                         }
703                 }
704
705                 ast_frfree(inf);
706                 inf = NULL;
707         }
708
709         ast_debug(1, "Loop finished, res=%d\n", res);
710
711         if (inf)
712                 ast_frfree(inf);
713
714         t30_terminate(t30state);
715         t38_terminal_release(&t38);
716
717 disable_t38:
718         /* if we are not the caller, it's our job to shut down the T.38
719          * session when the FAX transmisson is complete.
720          */
721         if ((s->caller_mode == FALSE) &&
722             (ast_channel_get_t38_state(s->chan) == T38_STATE_NEGOTIATED)) {
723                 struct ast_control_t38_parameters t38_parameters = { .request_response = AST_T38_REQUEST_TERMINATE, };
724
725                 if (ast_indicate_data(s->chan, AST_CONTROL_T38_PARAMETERS, &t38_parameters, sizeof(t38_parameters)) == 0) {
726                         /* wait up to five seconds for negotiation to complete */
727                         unsigned int timeout = 5000;
728                         int ms;
729
730                         ast_debug(1, "Shutting down T.38 on %s\n", ast_channel_name(s->chan));
731                         while (timeout > 0) {
732                                 ms = ast_waitfor(s->chan, 1000);
733                                 if (ms < 0) {
734                                         ast_log(LOG_WARNING, "something bad happened while channel '%s' was polling.\n", ast_channel_name(s->chan));
735                                         return -1;
736                                 }
737                                 if (!ms) {
738                                         /* nothing happened */
739                                         if (timeout > 0) {
740                                                 timeout -= 1000;
741                                                 continue;
742                                         } else {
743                                                 ast_log(LOG_WARNING, "channel '%s' timed-out during the T.38 shutdown.\n", ast_channel_name(s->chan));
744                                                 break;
745                                         }
746                                 }
747                                 if (!(inf = ast_read(s->chan))) {
748                                         return -1;
749                                 }
750                                 if ((inf->frametype == AST_FRAME_CONTROL) &&
751                                     (inf->subclass.integer == AST_CONTROL_T38_PARAMETERS) &&
752                                     (inf->datalen == sizeof(t38_parameters))) {
753                                         struct ast_control_t38_parameters *parameters = inf->data.ptr;
754
755                                         switch (parameters->request_response) {
756                                         case AST_T38_TERMINATED:
757                                                 ast_debug(1, "Shut down T.38 on %s\n", ast_channel_name(s->chan));
758                                                 break;
759                                         case AST_T38_REFUSED:
760                                                 ast_log(LOG_WARNING, "channel '%s' refused to disable T.38\n", ast_channel_name(s->chan));
761                                                 break;
762                                         default:
763                                                 ast_log(LOG_ERROR, "channel '%s' failed to disable T.38\n", ast_channel_name(s->chan));
764                                                 break;
765                                         }
766                                         ast_frfree(inf);
767                                         break;
768                                 }
769                                 ast_frfree(inf);
770                         }
771                 }
772         }
773
774         return res;
775 }
776
777 static int transmit(fax_session *s)
778 {
779         int res = 0;
780
781         /* Clear all channel variables which to be set by the application.
782            Pre-set status to error so in case of any problems we can just leave */
783         pbx_builtin_setvar_helper(s->chan, "FAXSTATUS", "FAILED");
784         pbx_builtin_setvar_helper(s->chan, "FAXERROR", "Channel problems");
785
786         pbx_builtin_setvar_helper(s->chan, "FAXMODE", NULL);
787         pbx_builtin_setvar_helper(s->chan, "REMOTESTATIONID", NULL);
788         pbx_builtin_setvar_helper(s->chan, "FAXPAGES", "0");
789         pbx_builtin_setvar_helper(s->chan, "FAXRESOLUTION", NULL);
790         pbx_builtin_setvar_helper(s->chan, "FAXBITRATE", NULL);
791
792         if (ast_channel_state(s->chan) != AST_STATE_UP) {
793                 /* Shouldn't need this, but checking to see if channel is already answered
794                  * Theoretically asterisk should already have answered before running the app */
795                 res = ast_answer(s->chan);
796                 if (res) {
797                         ast_log(LOG_WARNING, "Could not answer channel '%s'\n", ast_channel_name(s->chan));
798                         return res;
799                 }
800         }
801
802         s->t38state = ast_channel_get_t38_state(s->chan);
803         if (s->t38state != T38_STATE_NEGOTIATED) {
804                 /* T38 is not negotiated on the channel yet. First start regular transmission. If it switches to T38, follow */
805                 pbx_builtin_setvar_helper(s->chan, "FAXMODE", "audio");
806                 res = transmit_audio(s);
807                 if (res > 0) {
808                         /* transmit_audio reports switchover to T38. Update t38state */
809                         s->t38state = ast_channel_get_t38_state(s->chan);
810                         if (s->t38state != T38_STATE_NEGOTIATED) {
811                                 ast_log(LOG_ERROR, "Audio loop reports T38 switchover but t38state != T38_STATE_NEGOTIATED\n");
812                         }
813                 }
814         }
815
816         if (s->t38state == T38_STATE_NEGOTIATED) {
817                 pbx_builtin_setvar_helper(s->chan, "FAXMODE", "T38");
818                 res = transmit_t38(s);
819         }
820
821         if (res) {
822                 ast_log(LOG_WARNING, "Transmission error\n");
823                 res = -1;
824         } else if (s->finished < 0) {
825                 ast_log(LOG_WARNING, "Transmission failed\n");
826         } else if (s->finished > 0) {
827                 ast_debug(1, "Transmission finished Ok\n");
828         }
829
830         return res;
831 }
832
833 /* === Application functions === */
834
835 static int sndfax_exec(struct ast_channel *chan, const char *data)
836 {
837         int res = 0;
838         char *parse;
839         fax_session session = { 0, };
840         char restore_digit_detect = 0;
841
842         AST_DECLARE_APP_ARGS(args,
843                 AST_APP_ARG(file_name);
844                 AST_APP_ARG(options);
845         );
846
847         if (chan == NULL) {
848                 ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
849                 return -1;
850         }
851
852         /* The next few lines of code parse out the filename and header from the input string */
853         if (ast_strlen_zero(data)) {
854                 /* No data implies no filename or anything is present */
855                 ast_log(LOG_ERROR, "SendFAX requires an argument (filename)\n");
856                 return -1;
857         }
858
859         parse = ast_strdupa(data);
860         AST_STANDARD_APP_ARGS(args, parse);
861
862         session.caller_mode = TRUE;
863
864         if (args.options) {
865                 if (strchr(args.options, 'a'))
866                         session.caller_mode = FALSE;
867         }
868
869         /* Done parsing */
870         session.direction = 1;
871         session.file_name = args.file_name;
872         session.chan = chan;
873         session.finished = 0;
874
875         /* get current digit detection mode, then disable digit detection if enabled */
876         {
877                 int dummy = sizeof(restore_digit_detect);
878
879                 ast_channel_queryoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, &dummy, 0);
880         }
881
882         if (restore_digit_detect) {
883                 char new_digit_detect = 0;
884
885                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &new_digit_detect, sizeof(new_digit_detect), 0);
886         }
887
888         /* disable FAX tone detection if enabled */
889         {
890                 char new_fax_detect = 0;
891
892                 ast_channel_setoption(chan, AST_OPTION_FAX_DETECT, &new_fax_detect, sizeof(new_fax_detect), 0);
893         }
894
895         res = transmit(&session);
896
897         if (restore_digit_detect) {
898                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, sizeof(restore_digit_detect), 0);
899         }
900
901         return res;
902 }
903
904 static int rcvfax_exec(struct ast_channel *chan, const char *data)
905 {
906         int res = 0;
907         char *parse;
908         fax_session session;
909         char restore_digit_detect = 0;
910
911         AST_DECLARE_APP_ARGS(args,
912                 AST_APP_ARG(file_name);
913                 AST_APP_ARG(options);
914         );
915
916         if (chan == NULL) {
917                 ast_log(LOG_ERROR, "Fax channel is NULL. Giving up.\n");
918                 return -1;
919         }
920
921         /* The next few lines of code parse out the filename and header from the input string */
922         if (ast_strlen_zero(data)) {
923                 /* No data implies no filename or anything is present */
924                 ast_log(LOG_ERROR, "ReceiveFAX requires an argument (filename)\n");
925                 return -1;
926         }
927
928         parse = ast_strdupa(data);
929         AST_STANDARD_APP_ARGS(args, parse);
930
931         session.caller_mode = FALSE;
932
933         if (args.options) {
934                 if (strchr(args.options, 'c'))
935                         session.caller_mode = TRUE;
936         }
937
938         /* Done parsing */
939         session.direction = 0;
940         session.file_name = args.file_name;
941         session.chan = chan;
942         session.finished = 0;
943
944         /* get current digit detection mode, then disable digit detection if enabled */
945         {
946                 int dummy = sizeof(restore_digit_detect);
947
948                 ast_channel_queryoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, &dummy, 0);
949         }
950
951         if (restore_digit_detect) {
952                 char new_digit_detect = 0;
953
954                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &new_digit_detect, sizeof(new_digit_detect), 0);
955         }
956
957         /* disable FAX tone detection if enabled */
958         {
959                 char new_fax_detect = 0;
960
961                 ast_channel_setoption(chan, AST_OPTION_FAX_DETECT, &new_fax_detect, sizeof(new_fax_detect), 0);
962         }
963
964         res = transmit(&session);
965
966         if (restore_digit_detect) {
967                 ast_channel_setoption(chan, AST_OPTION_DIGIT_DETECT, &restore_digit_detect, sizeof(restore_digit_detect), 0);
968         }
969
970         return res;
971 }
972
973 static int unload_module(void)
974 {
975         int res;
976
977         res = ast_unregister_application(app_sndfax_name);
978         res |= ast_unregister_application(app_rcvfax_name);
979
980         return res;
981 }
982
983 static int load_module(void)
984 {
985         int res ;
986
987         res = ast_register_application_xml(app_sndfax_name, sndfax_exec);
988         res |= ast_register_application_xml(app_rcvfax_name, rcvfax_exec);
989
990         /* The default SPAN message handler prints to stderr. It is something we do not want */
991         span_set_message_handler(NULL);
992
993         return res;
994 }
995
996
997 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Simple FAX Application",
998         .support_level = AST_MODULE_SUPPORT_DEPRECATED,
999         .load = load_module,
1000         .unload = unload_module,
1001 );