aboutsummaryrefslogtreecommitdiffstats
path: root/apps/app_agi.c
blob: a4e0f17d57836191de4946ee7c302888d1490c90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
/*
 * Asterisk -- A telephony toolkit for Linux.
 *
 * Asterisk Gateway Interface
 * 
 * Copyright (C) 1999, Mark Spencer
 *
 * Mark Spencer <markster@linux-support.net>
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License
 */

#include <asterisk/file.h>
#include <asterisk/logger.h>
#include <asterisk/channel.h>
#include <asterisk/pbx.h>
#include <asterisk/module.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/signal.h>
#include <sys/time.h>
#include <asterisk/cli.h>
#include <asterisk/logger.h>
#include <asterisk/options.h>
#include <asterisk/image.h>
#include <asterisk/say.h>
#include "../asterisk.h"

#include <pthread.h>

#define MAX_ARGS 128

/* Recycle some stuff from the CLI interface */
#define fdprintf ast_cli

typedef struct agi_command {
	/* Null terminated list of the words of the command */
	char *cmda[AST_MAX_CMD_LEN];
	/* Handler for the command (fd for output, # of arguments, argument list). 
	    Returns RESULT_SHOWUSAGE for improper arguments */
	int (*handler)(struct ast_channel *chan, int fd, int argc, char *argv[]);
	/* Summary of the command (< 60 characters) */
	char *summary;
	/* Detailed usage information */
	char *usage;
} agi_command;

static char *tdesc = "Asterisk Gateway Interface (AGI)";

static char *app = "AGI";

static char *synopsis = "Executes an AGI compliant application";

static char *descrip =
"  AGI(command|args): Executes an Asterisk Gateway Interface compliant\n"
"program on a channel.   AGI allows Asterisk to launch external programs\n"
"written in any language to control a telephony channel, play audio,\n"
"read DTMF digits, etc. by communicating with the AGI protocol on stdin\n"
"and stdout.  Returns -1 on hangup or if application requested hangup, or\n"
"0 on non-hangup exit.\n";

STANDARD_LOCAL_USER;

LOCAL_USER_DECL;

#define TONE_BLOCK_SIZE 200

static float loudness = 8192.0;

unsigned char linear2ulaw(short sample);
static void make_tone_block(unsigned char *data, float f1, int *x);

static void make_tone_block(unsigned char *data, float f1, int *x)
{
int	i;
float	val;

	for(i = 0; i < TONE_BLOCK_SIZE; i++)
	{
		val = loudness * sin((f1 * 2.0 * M_PI * (*x)++)/8000.0);
		data[i] = linear2ulaw((int)val);
	 }		
	  /* wrap back around from 8000 */
	if (*x >= 8000) *x = 0;
	return;
}

static int launch_script(char *script, char *args, int *fds, int *opid)
{
	char tmp[256];
	int pid;
	int toast[2];
	int fromast[2];
	int x;
	if (script[0] != '/') {
		snprintf(tmp, sizeof(tmp), "%s/%s", AST_AGI_DIR, script);
		script = tmp;
	}
	if (pipe(toast)) {
		ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
		return -1;
	}
	if (pipe(fromast)) {
		ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
		close(toast[0]);
		close(toast[1]);
		return -1;
	}
	pid = fork();
	if (pid < 0) {
		ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
		return -1;
	}
	if (!pid) {
		/* Redirect stdin and out */
		dup2(fromast[0], STDIN_FILENO);
		dup2(toast[1], STDOUT_FILENO);
		/* Close everything but stdin/out/error */
		for (x=STDERR_FILENO + 1;x<1024;x++) 
			close(x);
		/* Execute script */
		execl(script, script, args, NULL);
		ast_log(LOG_WARNING, "Failed to execute '%s': %s\n", script, strerror(errno));
		exit(1);
	}
	if (option_verbose > 2) 
		ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
	fds[0] = toast[0];
	fds[1] = fromast[1];
	/* close what we're not using in the parent */
	close(toast[1]);
	close(fromast[0]);
	*opid = pid;
	return 0;
		
}

static void setup_env(struct ast_channel *chan, char *request, int fd)
{
	/* Print initial environment, with agi_request always being the first
	   thing */
	fdprintf(fd, "agi_request: %s\n", request);
	fdprintf(fd, "agi_channel: %s\n", chan->name);
	fdprintf(fd, "agi_language: %s\n", chan->language);
	fdprintf(fd, "agi_type: %s\n", chan->type);

	/* ANI/DNIS */
	fdprintf(fd, "agi_callerid: %s\n", chan->callerid ? chan->callerid : "");
	fdprintf(fd, "agi_dnid: %s\n", chan->dnid ? chan->dnid : "");

	/* Context information */
	fdprintf(fd, "agi_context: %s\n", chan->context);
	fdprintf(fd, "agi_extension: %s\n", chan->exten);
	fdprintf(fd, "agi_priority: %d\n", chan->priority);

	/* End with empty return */
	fdprintf(fd, "\n");
}

static int handle_answer(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	res = 0;
	if (chan->_state != AST_STATE_UP) {
		/* Answer the chan */
		res = ast_answer(chan);
	}
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_waitfordigit(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	int to;
	if (argc != 4)
		return RESULT_SHOWUSAGE;
	if (sscanf(argv[3], "%i", &to) != 1)
		return RESULT_SHOWUSAGE;
	res = ast_waitfordigit(chan, to);
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_sendtext(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	if (argc != 3)
		return RESULT_SHOWUSAGE;
	/* At the moment, the parser (perhaps broken) returns with
	   the last argument PLUS the newline at the end of the input
	   buffer. This probably needs to be fixed, but I wont do that
	   because other stuff may break as a result. The right way
	   would probably be to strip off the trailing newline before
	   parsing, then here, add a newline at the end of the string
	   before sending it to ast_sendtext --DUDE */
	res = ast_sendtext(chan, argv[2]);
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_recvchar(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	if (argc != 3)
		return RESULT_SHOWUSAGE;
	res = ast_recvchar(chan,atoi(argv[2]));
	if (res == 0) {
		fdprintf(fd, "200 result=%d (timeout)\n", res);
		return RESULT_SUCCESS;
	}
	if (res > 0) {
		fdprintf(fd, "200 result=%d\n", res);
		return RESULT_SUCCESS;
	}
	else {
		fdprintf(fd, "200 result=%d (hangup)\n", res);
		return RESULT_FAILURE;
	}
}

static int handle_tddmode(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res,x;
	if (argc != 3)
		return RESULT_SHOWUSAGE;
	if (!strncasecmp(argv[2],"on",2)) x = 1; else x = 0;
	if (!strncasecmp(argv[2],"mate",4)) x = 2;
	if (!strncasecmp(argv[2],"tdd",3)) x = 1;
	res = ast_channel_setoption(chan,AST_OPTION_TDD,&x,sizeof(char),0);
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0) 
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_sendimage(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	if (argc != 3)
		return RESULT_SHOWUSAGE;
	res = ast_send_image(chan, argv[2]);
	if (!ast_check_hangup(chan))
		res = 0;
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_streamfile(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	if (argc != 4)
		return RESULT_SHOWUSAGE;
	res = ast_streamfile(chan, argv[2],chan->language);
	if (res) {
		fdprintf(fd, "200 result=%d\n", res);
		if (res >= 0)
			return RESULT_SHOWUSAGE;
		else
			return RESULT_FAILURE;
	}
	res = ast_waitstream(chan, argv[3]);
	ast_stopstream(chan);
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_saynumber(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	int num;
	if (argc != 4)
		return RESULT_SHOWUSAGE;
	if (sscanf(argv[2], "%i", &num) != 1)
		return RESULT_SHOWUSAGE;
	res = ast_say_number(chan, num, argv[3], chan->language);
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_saydigits(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	int num;
	if (argc != 4)
		return RESULT_SHOWUSAGE;
	if (sscanf(argv[2], "%i", &num) != 1)
		return RESULT_SHOWUSAGE;
	res = ast_say_digit_str(chan, argv[2], argv[3], chan->language);
	fdprintf(fd, "200 result=%d\n", res);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout);

static int handle_getdata(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int res;
	char data[50];
	int max;
	int timeout;

	if (argc < 3)
		return RESULT_SHOWUSAGE;
	if (argc >= 4) timeout = atoi(argv[3]); else timeout = 0;
	if (argc >= 5) max = atoi(argv[4]); else max = 50;
	res = ast_app_getdata(chan, argv[2], data, max, timeout);
	if (res == 1)
		fdprintf(fd, "200 result=%s (timeout)\n", data);
	else
		fdprintf(fd, "200 result=%s\n", data);
	if (res >= 0)
		return RESULT_SUCCESS;
	else
		return RESULT_FAILURE;
}

static int handle_setcontext(struct ast_channel *chan, int fd, int argc, char *argv[])
{

	if (argc != 3)
		return RESULT_SHOWUSAGE;
	strncpy(chan->context, argv[2], sizeof(chan->context)-1);
	fdprintf(fd, "200 result=0\n");
	return RESULT_SUCCESS;
}
	
static int handle_setextension(struct ast_channel *chan, int fd, int argc, char **argv)
{
	if (argc != 3)
		return RESULT_SHOWUSAGE;
	strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
	fdprintf(fd, "200 result=0\n");
	return RESULT_SUCCESS;
}

static int handle_setpriority(struct ast_channel *chan, int fd, int argc, char **argv)
{
	int pri;
	if (argc != 3)
		return RESULT_SHOWUSAGE;	
	if (sscanf(argv[2], "%i", &pri) != 1)
		return RESULT_SHOWUSAGE;
	chan->priority = pri - 1;
	fdprintf(fd, "200 result=0\n");
	return RESULT_SUCCESS;
}
		
static int ms_diff(struct timeval *tv1, struct timeval *tv2)
{
int	ms;
	
	ms = (tv1->tv_sec - tv2->tv_sec) * 1000;
	ms += (tv1->tv_usec - tv2->tv_usec) / 1000;
	return(ms);
}

static int handle_recordfile(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	struct ast_filestream *fs;
	struct ast_frame *f;
	struct timeval tv, start;
	int res = 0;
	int ms;

	if (argc < 6)
		return RESULT_SHOWUSAGE;
	if (sscanf(argv[5], "%i", &ms) != 1)
		return RESULT_SHOWUSAGE;

	if (argc > 6)
		res = ast_streamfile(chan, "beep", chan->language);
	if (!res)
		res = ast_waitstream(chan, argv[4]);
	if (!res) {
		fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_TRUNC | O_WRONLY, 0, 0644);
		if (!fs) {
			res = -1;
			fdprintf(fd, "200 result=%d (writefile)\n", res);
			return RESULT_FAILURE;
		}
		gettimeofday(&start, NULL);
		gettimeofday(&tv, NULL);
		while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
			res = ast_waitfor(chan, -1);
			if (res < 0) {
				ast_closestream(fs);
				fdprintf(fd, "200 result=%d (waitfor)\n", res);
				return RESULT_FAILURE;
			}
			f = ast_read(chan);
			if (!f) {
				fdprintf(fd, "200 result=%d (hangup)\n", 0);
				ast_closestream(fs);
				return RESULT_FAILURE;
			}
			switch(f->frametype) {
			case AST_FRAME_DTMF:
				if (strchr(argv[4], f->subclass)) {
					/* This is an interrupting chracter */
					fdprintf(fd, "200 result=%d (dtmf)\n", f->subclass);
					ast_closestream(fs);
					ast_frfree(f);
					return RESULT_SUCCESS;
				}
				break;
			case AST_FRAME_VOICE:
				ast_writestream(fs, f);
				break;
			}
			ast_frfree(f);
		}
		gettimeofday(&tv, NULL);
		fdprintf(fd, "200 result=%d (timeout)\n", res);
		ast_closestream(fs);
	} else
		fdprintf(fd, "200 result=%d (randomerror)\n", res);
	return RESULT_SUCCESS;
}

static int handle_autohangup(struct ast_channel *chan, int fd, int argc, char *argv[])
{
	int timeout;

	if (argc != 3)
		return RESULT_SHOWUSAGE;
	if (sscanf(argv[2], "%d", &timeout) != 1)
		return RESULT_SHOWUSAGE;
	if (timeout < 0)
		timeout = 0;
	if (timeout)
		chan->whentohangup = time(NULL) + timeout;
	else
		chan->whentohangup = 0;
	fdprintf(fd, "200 result=0\n");
	return RESULT_SUCCESS;
}

static int handle_hangup(struct ast_channel *chan, int fd, int argc, char **argv)
{
	ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
	fdprintf(fd, "200 result=1\n");
	return RESULT_SUCCESS;
}

static int handle_exec(struct ast_channel *chan, int fd, int argc, char **argv)
{
	int res;
	struct ast_app *app;

	if (argc < 2)
		return RESULT_SHOWUSAGE;

	if (option_verbose > 2)
		ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);

	app = pbx_findapp(argv[1]);

	if (app) {
		res = pbx_exec(chan, app, argv[2], 1);
	} else {
		ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
		res = -2;
	}
	fdprintf(fd, "200 result=%d\n", res);

	return res;
}

static int handle_setcallerid(struct ast_channel *chan, int fd, int argc, char **argv)
{
	if (argv[2])
		ast_set_callerid(chan, argv[2]);

/*	strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
*/	fdprintf(fd, "200 result=1\n");
	return RESULT_SUCCESS;
}

static int handle_channelstatus(struct ast_channel *chan, int fd, int argc, char **argv)
{
	fdprintf(fd, "200 result=%d\n", chan->_state);
	return RESULT_SUCCESS;
}

static char usage_channelstatus[] =
" Usage: CHANNEL STATUS\n"
"	Returns the status of the connected channel. Return values:\n"
" 0 Channel is down and available\n"
" 1 Channel is down, but reserved\n"
" 2 Channel is off hook\n"
" 3 Digits (or equivalent) have been dialed\n"
" 4 Line is ringing\n"
" 5 Remote end is ringing\n"
" 6 Line is up\n"
" 7 Line is busy\n";

static char usage_setcallerid[] =
" Usage: SET CALLERID <number>\n"
"	Changes the callerid of the current channel.\n";

static char usage_exec[] =
" Usage: EXEC <application> <options>\n"
"	Executes <application> with given <options>.\n"
"	Returns whatever the application returns, or -2 on failure to find application\n";

static char usage_hangup[] =
" Usage: HANGUP\n"
"	Hangs up the current channel.\n";


static char usage_answer[] = 
" Usage: ANSWER\n"
"        Answers channel if not already in answer state. Returns -1 on\n"
" channel failure, or 0 if successful.\n";

static char usage_waitfordigit[] = 
" Usage: WAIT FOR DIGIT <timeout>\n"
"        Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
" Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
" the numerical value of the ascii of the digit if one is received.  Use -1\n"
" for the timeout value if you desire the call to block indefinitely.\n";

static char usage_sendtext[] =
" Usage: SEND TEXT \"<text to send>\"\n"
"        Sends the given text on a channel.  Most channels do not support the\n"
" transmission of text.  Returns 0 if text is sent, or if the channel does not\n"
" support text transmission.  Returns -1 only on error/hangup.  Text\n"
" consisting of greater than one word should be placed in quotes since the\n"
" command only accepts a single argument.\n";

static char usage_recvchar[] =
" Usage: RECEIVE CHAR <timeout>\n"
"        Receives a character of text on a channel.  Specify timeout to be the\n"
" maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
" do not support the reception of text.  Returns the decimal value of the character\n"
" if one is received, or 0 if the channel does not support text reception.  Returns\n"
" -1 only on error/hangup.\n";

static char usage_tddmode[] =
" Usage: TDD MODE <on|off>\n"
"        Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
" successful, or 0 if channel is not TDD-capable.\n";

static char usage_sendimage[] =
" Usage: SEND IMAGE <image>\n"
"        Sends the given image on a channel.  Most channels do not support the\n"
" transmission of images.  Returns 0 if image is sent, or if the channel does not\n"
" support image transmission.  Returns -1 only on error/hangup.  Image names\n"
" should not include extensions.\n";

static char usage_streamfile[] =
" Usage: STREAM FILE <filename> <escape digits>\n"
"        Send the given file, allowing playback to be interrupted by the given\n"
" digits, if any.  Use double quotes for the digits if you wish none to be\n"
" permitted.  Returns 0 if playback completes without a digit being pressed, or\n"
" the ASCII numerical value of the digit if one was pressed, or -1 on error or\n"
" if the channel was disconnected.  Remember, the file extension must not be\n"
" included in the filename.\n";

static char usage_saynumber[] =
" Usage: SAY NUMBER <number> <escape digits>\n"
"        Say a given number, returning early if any of the given DTMF digits\n"
" are received on the channel.  Returns 0 if playback completes without a digit\n"
" being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
" -1 on error/hangup.\n";

static char usage_saydigits[] =
" Usage: SAY DIGITS <number> <escape digits>\n"
"        Say a given digit string, returning early if any of the given DTMF digits\n"
" are received on the channel.  Returns 0 if playback completes without a digit\n"
" being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
" -1 on error/hangup.\n";

static char usage_getdata[] =
" Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
"	 Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
"from the channel at the other end.\n";

static char usage_setcontext[] =
" Usage: SET CONTEXT <desired context>\n"
"	 Sets the context for continuation upon exiting the application.\n";

static char usage_setextension[] =
" Usage: SET EXTENSION <new extension>\n"
"	 Changes the extension for continuation upon exiting the application.\n";

static char usage_setpriority[] =
" Usage: SET PRIORITY <num>\n"
"	 Changes the priority for continuation upon exiting the application.\n";

static char usage_recordfile[] =
" Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [BEEP]\n"
"        Record to a file until a given dtmf digit in the sequence is received\n"
" Returns -1 on hangup or error.  The format will specify what kind of file\n"
" will be recorded.  The timeout is the maximum record time in milliseconds, or\n"
" -1 for no timeout\n";

static char usage_autohangup[] =
" Usage: SET AUTOHANGUP <time>\n"
"    Cause the channel to automatically hangup at <time> seconds in the\n"
"future.  Of course it can be hungup before then as well.   Setting to\n"
"0 will cause the autohangup feature to be disabled on this channel.\n";

agi_command commands[] = {
	{ { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
	{ { "answer\n", NULL }, handle_answer, "Asserts answer", usage_answer },
	{ { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
	{ { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
	{ { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
	{ { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
	{ { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
	{ { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
	{ { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
	{ { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
	{ { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
	{ { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
	{ { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
	{ { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
	{ { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
	{ { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
	{ { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
	{ { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
	{ { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
	{ { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus }
};

static agi_command *find_command(char *cmds[])
{
	int x;
	int y;
	int match;
	for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
		/* start optimistic */
		match = 1;
		for (y=0;match && cmds[y]; y++) {
			/* If there are no more words in the command (and we're looking for
			   an exact match) or there is a difference between the two words,
			   then this is not a match */
			if (!commands[x].cmda[y])
				break;
			if (strcasecmp(commands[x].cmda[y], cmds[y]))
				match = 0;
		}
		/* If more words are needed to complete the command then this is not
		   a candidate (unless we're looking for a really inexact answer  */
		if (commands[x].cmda[y])
			match = 0;
		if (match)
			return &commands[x];
	}
	return NULL;
}


static int parse_args(char *s, int *max, char *argv[])
{
	int x=0;
	int quoted=0;
	int escaped=0;
	int whitespace=1;
	char *cur;

	cur = s;
	while(*s) {
		switch(*s) {
		case '"':
			/* If it's escaped, put a literal quote */
			if (escaped) 
				goto normal;
			else 
				quoted = !quoted;
			if (quoted && whitespace) {
				/* If we're starting a quote, coming off white space start a new word, too */
				argv[x++] = cur;
				whitespace=0;
			}
			escaped = 0;
		break;
		case ' ':
		case '\t':
			if (!quoted && !escaped) {
				/* If we're not quoted, mark this as whitespace, and
				   end the previous argument */
				whitespace = 1;
				*(cur++) = '\0';
			} else
				/* Otherwise, just treat it as anything else */ 
				goto normal;
			break;
		case '\\':
			/* If we're escaped, print a literal, otherwise enable escaping */
			if (escaped) {
				goto normal;
			} else {
				escaped=1;
			}
			break;
		default:
normal:
			if (whitespace) {
				if (x >= MAX_ARGS -1) {
					ast_log(LOG_WARNING, "Too many arguments, truncating\n");
					break;
				}
				/* Coming off of whitespace, start the next argument */
				argv[x++] = cur;
				whitespace=0;
			}
			*(cur++) = *s;
			escaped=0;
		}
		s++;
	}
	/* Null terminate */
	*(cur++) = '\0';
	argv[x] = NULL;
	*max = x;
	return 0;
}

static int agi_handle_command(struct ast_channel *chan, int fd, char *buf)
{
	char *argv[MAX_ARGS];
	int argc = 0;
	int res;
	agi_command *c;
	argc = MAX_ARGS;
	parse_args(buf, &argc, argv);
#if	0
	{ int x;
	for (x=0;x<argc;x++) 
		fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
#endif
	c = find_command(argv);
	if (c) {
		res = c->handler(chan, fd, argc, argv);
		switch(res) {
		case RESULT_SHOWUSAGE:
			fdprintf(fd, "520-Invalid command syntax.  Proper usage follows:\n");
			fdprintf(fd, c->usage);
			fdprintf(fd, "520 End of proper usage.\n");
			break;
		case RESULT_FAILURE:
			/* They've already given the failure.  We've been hung up on so handle this
			   appropriately */
			return -1;
		}
	} else {
		fdprintf(fd, "510 Invalid or unknown command\n");
	}
	return 0;
}

static int run_agi(struct ast_channel *chan, char *request, int *fds, int pid)
{
	struct ast_channel *c;
	int outfd;
	int ms;
	int returnstatus = 0;
	struct ast_frame *f;
	char buf[2048];
	FILE *readf;
	if (!(readf = fdopen(fds[0], "r"))) {
		ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
		kill(pid, SIGHUP);
		return -1;
	}
	setlinebuf(readf);
	setup_env(chan, request, fds[1]);
	for (;;) {
		ms = -1;
		c = ast_waitfor_nandfds(&chan, 1, &fds[0], 1, NULL, &outfd, &ms);
		if (c) {
			/* Idle the channel until we get a command */
			f = ast_read(c);
			if (!f) {
				ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
				returnstatus = -1;
				break;
			} else {
				ast_frfree(f);
			}
		} else if (outfd > -1) {
			if (!fgets(buf, sizeof(buf), readf)) {
				/* Program terminated */
				if (returnstatus)
					returnstatus = -1;
				if (option_verbose > 2) 
					ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
				/* No need to kill the pid anymore, since they closed us */
				pid = -1;
				break;
			}
			  /* get rid of trailing newline, if any */
			if (*buf && buf[strlen(buf) - 1] == '\n')
				buf[strlen(buf) - 1] = 0;

			returnstatus |= agi_handle_command(chan, fds[1], buf);
			/* If the handle_command returns -1, we need to stop */
			if (returnstatus < 0) {
				break;
			}
		} else {
			ast_log(LOG_WARNING, "No channel, no fd?\n");
			returnstatus = -1;
			break;
		}
	}
	/* Notify process */
	if (pid > -1)
		kill(pid, SIGHUP);
	fclose(readf);
	return returnstatus;
}

static int agi_exec(struct ast_channel *chan, void *data)
{
	int res=0;
	struct localuser *u;
	char *args,*ringy;
	char tmp[256];
	int fds[2];
	int pid;
	if (!data || !strlen(data)) {
		ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
		return -1;
	}


	strncpy(tmp, data, sizeof(tmp)-1);
	strtok(tmp, "|");
	args = strtok(NULL, "|");
	ringy = strtok(NULL,"|");
	if (!args)
		args = "";
	LOCAL_USER_ADD(u);
#if 0
	 /* Answer if need be */
        if (chan->_state != AST_STATE_UP) {
		if (ringy) { /* if for ringing first */
			/* a little ringy-dingy first */
		        ast_indicate(chan, AST_CONTROL_RINGING);  
			sleep(3); 
		}
		if (ast_answer(chan)) {
			LOCAL_USER_REMOVE(u);
			return -1;
		}
	}
#endif
	res = launch_script(tmp, args, fds, &pid);
	if (!res) {
		res = run_agi(chan, tmp, fds, pid);
		close(fds[0]);
		close(fds[1]);
	}
	LOCAL_USER_REMOVE(u);
	return res;
}

int unload_module(void)
{
	STANDARD_HANGUP_LOCALUSERS;
	return ast_unregister_application(app);
}

int load_module(void)
{
	return ast_register_application(app, agi_exec, synopsis, descrip);
}

char *description(void)
{
	return tdesc;
}

int usecount(void)
{
	int res;
	STANDARD_USECOUNT(res);
	return res;
}

char *key()
{
	return ASTERISK_GPL_KEY;
}

#define CLIP 32635
#define BIAS 0x84

unsigned char
linear2ulaw(sample)
short sample; {
  static int exp_lut[256] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
                             4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
                             5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
                             5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
                             7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7};
  int sign, exponent, mantissa;
  unsigned char ulawbyte;
 
  /* Get the sample into sign-magnitude. */
  sign = (sample >> 8) & 0x80;          /* set aside the sign */
  if (sign != 0) sample = -sample;              /* get magnitude */
  if (sample > CLIP) sample = CLIP;             /* clip the magnitude */
 
  /* Convert from 16 bit linear to ulaw. */
  sample = sample + BIAS;
  exponent = exp_lut[(sample >> 7) & 0xFF];
  mantissa = (sample >> (exponent + 3)) & 0x0F;
  ulawbyte = ~(sign | (exponent << 4) | mantissa);
#ifdef ZEROTRAP
  if (ulawbyte == 0) ulawbyte = 0x02;   /* optional CCITT trap */
#endif
 
  return(ulawbyte);
}