-
Notifications
You must be signed in to change notification settings - Fork 0
/
pbx.c
8399 lines (7392 loc) · 251 KB
/
pbx.c
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2008, Digium, Inc.
*
* Mark Spencer <markster@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief Core PBX routines.
*
* \author Mark Spencer <markster@digium.com>
*/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
#include "asterisk/_private.h"
#include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
#include <ctype.h>
#include <time.h>
#include <sys/time.h>
#if defined(HAVE_SYSINFO)
#include <sys/sysinfo.h>
#endif
#if defined(SOLARIS)
#include <sys/loadavg.h>
#endif
#include "asterisk/lock.h"
#include "asterisk/cli.h"
#include "asterisk/pbx.h"
#include "asterisk/channel.h"
#include "asterisk/file.h"
#include "asterisk/callerid.h"
#include "asterisk/cdr.h"
#include "asterisk/config.h"
#include "asterisk/term.h"
#include "asterisk/time.h"
#include "asterisk/manager.h"
#include "asterisk/ast_expr.h"
#include "asterisk/linkedlists.h"
#define SAY_STUBS /* generate declarations and stubs for say methods */
#include "asterisk/say.h"
#include "asterisk/utils.h"
#include "asterisk/causes.h"
#include "asterisk/musiconhold.h"
#include "asterisk/app.h"
#include "asterisk/devicestate.h"
#include "asterisk/stringfields.h"
#include "asterisk/event.h"
#include "asterisk/hashtab.h"
#include "asterisk/module.h"
#include "asterisk/indications.h"
/*!
* \note I M P O R T A N T :
*
* The speed of extension handling will likely be among the most important
* aspects of this PBX. The switching scheme as it exists right now isn't
* terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
* of priorities, but a constant search time here would be great ;-)
*
* A new algorithm to do searching based on a 'compiled' pattern tree is introduced
* here, and shows a fairly flat (constant) search time, even for over
* 10000 patterns.
*
* Also, using a hash table for context/priority name lookup can help prevent
* the find_extension routines from absorbing exponential cpu cycles as the number
* of contexts/priorities grow. I've previously tested find_extension with red-black trees,
* which have O(log2(n)) speed. Right now, I'm using hash tables, which do
* searches (ideally) in O(1) time. While these techniques do not yield much
* speed in small dialplans, they are worth the trouble in large dialplans.
*
*/
#ifdef LOW_MEMORY
#define EXT_DATA_SIZE 256
#else
#define EXT_DATA_SIZE 8192
#endif
#define SWITCH_DATA_LENGTH 256
#define VAR_BUF_SIZE 4096
#define VAR_NORMAL 1
#define VAR_SOFTTRAN 2
#define VAR_HARDTRAN 3
#define BACKGROUND_SKIP (1 << 0)
#define BACKGROUND_NOANSWER (1 << 1)
#define BACKGROUND_MATCHEXTEN (1 << 2)
#define BACKGROUND_PLAYBACK (1 << 3)
AST_APP_OPTIONS(background_opts, {
AST_APP_OPTION('s', BACKGROUND_SKIP),
AST_APP_OPTION('n', BACKGROUND_NOANSWER),
AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
});
#define WAITEXTEN_MOH (1 << 0)
#define WAITEXTEN_DIALTONE (1 << 1)
AST_APP_OPTIONS(waitexten_opts, {
AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0),
});
struct ast_context;
struct ast_app;
AST_THREADSTORAGE(switch_data);
/*!
\brief ast_exten: An extension
The dialplan is saved as a linked list with each context
having it's own linked list of extensions - one item per
priority.
*/
struct ast_exten {
char *exten; /*!< Extension name */
int matchcid; /*!< Match caller id ? */
const char *cidmatch; /*!< Caller id to match for this extension */
int priority; /*!< Priority */
const char *label; /*!< Label */
struct ast_context *parent; /*!< The context this extension belongs to */
const char *app; /*!< Application to execute */
struct ast_app *cached_app; /*!< Cached location of application */
void *data; /*!< Data to use (arguments) */
void (*datad)(void *); /*!< Data destructor */
struct ast_exten *peer; /*!< Next higher priority with our extension */
struct ast_hashtab *peer_table; /*!< Priorities list in hashtab form -- only on the head of the peer list */
struct ast_hashtab *peer_label_table; /*!< labeled priorities in the peers -- only on the head of the peer list */
const char *registrar; /*!< Registrar */
struct ast_exten *next; /*!< Extension with a greater ID */
char stuff[0];
};
/*! \brief ast_include: include= support in extensions.conf */
struct ast_include {
const char *name;
const char *rname; /*!< Context to include */
const char *registrar; /*!< Registrar */
int hastime; /*!< If time construct exists */
struct ast_timing timing; /*!< time construct */
struct ast_include *next; /*!< Link them together */
char stuff[0];
};
/*! \brief ast_sw: Switch statement in extensions.conf */
struct ast_sw {
char *name;
const char *registrar; /*!< Registrar */
char *data; /*!< Data load */
int eval;
AST_LIST_ENTRY(ast_sw) list;
char stuff[0];
};
/*! \brief ast_ignorepat: Ignore patterns in dial plan */
struct ast_ignorepat {
const char *registrar;
struct ast_ignorepat *next;
const char pattern[0];
};
/*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
struct match_char
{
int is_pattern; /* the pattern started with '_' */
int deleted; /* if this is set, then... don't return it */
char *x; /* the pattern itself-- matches a single char */
int specificity; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */
struct match_char *alt_char;
struct match_char *next_char;
struct ast_exten *exten; /* attached to last char of a pattern for exten */
};
struct scoreboard /* make sure all fields are 0 before calling new_find_extension */
{
int total_specificity;
int total_length;
char last_char; /* set to ! or . if they are the end of the pattern */
int canmatch; /* if the string to match was just too short */
struct match_char *node;
struct ast_exten *canmatch_exten;
struct ast_exten *exten;
};
/*! \brief ast_context: An extension context */
struct ast_context {
ast_rwlock_t lock; /*!< A lock to prevent multiple threads from clobbering the context */
struct ast_exten *root; /*!< The root of the list of extensions */
struct ast_hashtab *root_table; /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree */
struct match_char *pattern_tree; /*!< A tree to speed up extension pattern matching */
struct ast_context *next; /*!< Link them together */
struct ast_include *includes; /*!< Include other contexts */
struct ast_ignorepat *ignorepats; /*!< Patterns for which to continue playing dialtone */
const char *registrar; /*!< Registrar */
int refcount; /*!< each module that would have created this context should inc/dec this as appropriate */
AST_LIST_HEAD_NOLOCK(, ast_sw) alts; /*!< Alternative switches */
ast_mutex_t macrolock; /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
char name[0]; /*!< Name of the context */
};
/*! \brief ast_app: A registered application */
struct ast_app {
int (*execute)(struct ast_channel *chan, void *data);
const char *synopsis; /*!< Synopsis text for 'show applications' */
const char *description; /*!< Description (help text) for 'show application <name>' */
AST_RWLIST_ENTRY(ast_app) list; /*!< Next app in list */
struct ast_module *module; /*!< Module this app belongs to */
char name[0]; /*!< Name of the application */
};
/*! \brief ast_state_cb: An extension state notify register item */
struct ast_state_cb {
int id;
void *data;
ast_state_cb_type callback;
AST_LIST_ENTRY(ast_state_cb) entry;
};
/*! \brief Structure for dial plan hints
\note Hints are pointers from an extension in the dialplan to one or
more devices (tech/name)
- See \ref AstExtState
*/
struct ast_hint {
struct ast_exten *exten; /*!< Extension */
int laststate; /*!< Last known state */
AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks; /*!< Callback list for this extension */
AST_RWLIST_ENTRY(ast_hint) list;/*!< Pointer to next hint in list */
};
static const struct cfextension_states {
int extension_state;
const char * const text;
} extension_states[] = {
{ AST_EXTENSION_NOT_INUSE, "Idle" },
{ AST_EXTENSION_INUSE, "InUse" },
{ AST_EXTENSION_BUSY, "Busy" },
{ AST_EXTENSION_UNAVAILABLE, "Unavailable" },
{ AST_EXTENSION_RINGING, "Ringing" },
{ AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
{ AST_EXTENSION_ONHOLD, "Hold" },
{ AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD, "InUse&Hold" }
};
struct statechange {
AST_LIST_ENTRY(statechange) entry;
char dev[0];
};
/*!
* \brief Data used by the device state thread
*/
static struct {
/*! Set to 1 to stop the thread */
unsigned int stop:1;
/*! The device state monitoring thread */
pthread_t thread;
/*! Lock for the state change queue */
ast_mutex_t lock;
/*! Condition for the state change queue */
ast_cond_t cond;
/*! Queue of state changes */
AST_LIST_HEAD_NOLOCK(, statechange) state_change_q;
} device_state = {
.thread = AST_PTHREADT_NULL,
};
struct pbx_exception {
AST_DECLARE_STRING_FIELDS(
AST_STRING_FIELD(context); /*!< Context associated with this exception */
AST_STRING_FIELD(exten); /*!< Exten associated with this exception */
AST_STRING_FIELD(reason); /*!< The exception reason */
);
int priority; /*!< Priority associated with this exception */
};
static int pbx_builtin_answer(struct ast_channel *, void *);
static int pbx_builtin_goto(struct ast_channel *, void *);
static int pbx_builtin_hangup(struct ast_channel *, void *);
static int pbx_builtin_background(struct ast_channel *, void *);
static int pbx_builtin_wait(struct ast_channel *, void *);
static int pbx_builtin_waitexten(struct ast_channel *, void *);
static int pbx_builtin_keepalive(struct ast_channel *, void *);
static int pbx_builtin_resetcdr(struct ast_channel *, void *);
static int pbx_builtin_setamaflags(struct ast_channel *, void *);
static int pbx_builtin_ringing(struct ast_channel *, void *);
static int pbx_builtin_progress(struct ast_channel *, void *);
static int pbx_builtin_congestion(struct ast_channel *, void *);
static int pbx_builtin_busy(struct ast_channel *, void *);
static int pbx_builtin_noop(struct ast_channel *, void *);
static int pbx_builtin_gotoif(struct ast_channel *, void *);
static int pbx_builtin_gotoiftime(struct ast_channel *, void *);
static int pbx_builtin_execiftime(struct ast_channel *, void *);
static int pbx_builtin_saynumber(struct ast_channel *, void *);
static int pbx_builtin_saydigits(struct ast_channel *, void *);
static int pbx_builtin_saycharacters(struct ast_channel *, void *);
static int pbx_builtin_sayphonetic(struct ast_channel *, void *);
static int matchcid(const char *cidpattern, const char *callerid);
int pbx_builtin_setvar(struct ast_channel *, void *);
void log_match_char_tree(struct match_char *node, char *prefix); /* for use anywhere */
int pbx_builtin_setvar_multiple(struct ast_channel *, void *);
static int pbx_builtin_importvar(struct ast_channel *, void *);
static void set_ext_pri(struct ast_channel *c, const char *exten, int pri);
static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *callerid, enum ext_match_t action);
static struct match_char *already_in_tree(struct match_char *current, char *pat);
static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly);
static struct match_char *add_pattern_node(struct ast_context *con, struct match_char *current, char *pattern, int is_pattern, int already, int specificity, struct match_char **parent);
static void create_match_char_tree(struct ast_context *con);
static struct ast_exten *get_canmatch_exten(struct match_char *node);
static void destroy_pattern_tree(struct match_char *pattern_tree);
int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b);
static int hashtab_compare_extens(const void *ha_a, const void *ah_b);
static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b);
static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b);
unsigned int ast_hashtab_hash_contexts(const void *obj);
static unsigned int hashtab_hash_extens(const void *obj);
static unsigned int hashtab_hash_priority(const void *obj);
static unsigned int hashtab_hash_labels(const void *obj);
static void __ast_internal_context_destroy( struct ast_context *con);
/* a func for qsort to use to sort a char array */
static int compare_char(const void *a, const void *b)
{
const char *ac = a;
const char *bc = b;
if ((*ac) < (*bc))
return -1;
else if ((*ac) == (*bc))
return 0;
else
return 1;
}
/* labels, contexts are case sensitive priority numbers are ints */
int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b)
{
const struct ast_context *ac = ah_a;
const struct ast_context *bc = ah_b;
/* assume context names are registered in a string table! */
return strcmp(ac->name, bc->name);
}
static int hashtab_compare_extens(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
int x = strcmp(ac->exten, bc->exten);
if (x) /* if exten names are diff, then return */
return x;
/* but if they are the same, do the cidmatch values match? */
if (ac->matchcid && bc->matchcid) {
return strcmp(ac->cidmatch,bc->cidmatch);
} else if (!ac->matchcid && !bc->matchcid) {
return 0; /* if there's no matchcid on either side, then this is a match */
} else {
return 1; /* if there's matchcid on one but not the other, they are different */
}
}
static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
return ac->priority != bc->priority;
}
static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
return strcmp(ac->label, bc->label);
}
unsigned int ast_hashtab_hash_contexts(const void *obj)
{
const struct ast_context *ac = obj;
return ast_hashtab_hash_string(ac->name);
}
static unsigned int hashtab_hash_extens(const void *obj)
{
const struct ast_exten *ac = obj;
unsigned int x = ast_hashtab_hash_string(ac->exten);
unsigned int y = 0;
if (ac->matchcid)
y = ast_hashtab_hash_string(ac->cidmatch);
return x+y;
}
static unsigned int hashtab_hash_priority(const void *obj)
{
const struct ast_exten *ac = obj;
return ast_hashtab_hash_int(ac->priority);
}
static unsigned int hashtab_hash_labels(const void *obj)
{
const struct ast_exten *ac = obj;
return ast_hashtab_hash_string(ac->label);
}
AST_RWLOCK_DEFINE_STATIC(globalslock);
static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
static int autofallthrough = 1;
static int extenpatternmatchnew = 0;
static char *overrideswitch = NULL;
/*! \brief Subscription for device state change events */
static struct ast_event_sub *device_state_sub;
AST_MUTEX_DEFINE_STATIC(maxcalllock);
static int countcalls;
static int totalcalls;
static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
/*! \brief Declaration of builtin applications */
static struct pbx_builtin {
char name[AST_MAX_APP];
int (*execute)(struct ast_channel *chan, void *data);
char *synopsis;
char *description;
} builtins[] =
{
/* These applications are built into the PBX core and do not
need separate modules */
{ "Answer", pbx_builtin_answer,
"Answer a channel if ringing",
" Answer([delay]): If the call has not been answered, this application will\n"
"answer it. Otherwise, it has no effect on the call. If a delay is specified,\n"
"Asterisk will wait this number of milliseconds before returning to\n"
"the dialplan after answering the call.\n"
},
{ "BackGround", pbx_builtin_background,
"Play an audio file while waiting for digits of an extension to go to.",
" Background(filename1[&filename2...][,options[,langoverride][,context]]):\n"
"This application will play the given list of files (do not put extension)\n"
"while waiting for an extension to be dialed by the calling channel. To\n"
"continue waiting for digits after this application has finished playing\n"
"files, the WaitExten application should be used. The 'langoverride' option\n"
"explicitly specifies which language to attempt to use for the requested sound\n"
"files. If a 'context' is specified, this is the dialplan context that this\n"
"application will use when exiting to a dialed extension."
" If one of the requested sound files does not exist, call processing will be\n"
"terminated.\n"
" Options:\n"
" s - Causes the playback of the message to be skipped\n"
" if the channel is not in the 'up' state (i.e. it\n"
" hasn't been answered yet). If this happens, the\n"
" application will return immediately.\n"
" n - Don't answer the channel before playing the files.\n"
" m - Only break if a digit hit matches a one digit\n"
" extension in the destination context.\n"
"This application sets the following channel variable upon completion:\n"
" BACKGROUNDSTATUS The status of the background attempt as a text string, one of\n"
" SUCCESS | FAILED\n"
"See Also: Playback (application) -- Play sound file(s) to the channel,\n"
" that cannot be interrupted\n"
},
{ "Busy", pbx_builtin_busy,
"Indicate the Busy condition",
" Busy([timeout]): This application will indicate the busy condition to\n"
"the calling channel. If the optional timeout is specified, the calling channel\n"
"will be hung up after the specified number of seconds. Otherwise, this\n"
"application will wait until the calling channel hangs up.\n"
},
{ "Congestion", pbx_builtin_congestion,
"Indicate the Congestion condition",
" Congestion([timeout]): This application will indicate the congestion\n"
"condition to the calling channel. If the optional timeout is specified, the\n"
"calling channel will be hung up after the specified number of seconds.\n"
"Otherwise, this application will wait until the calling channel hangs up.\n"
},
{ "ExecIfTime", pbx_builtin_execiftime,
"Conditional application execution based on the current time",
" ExecIfTime(<times>,<weekdays>,<mdays>,<months>?appname[(appargs)]):\n"
"This application will execute the specified dialplan application, with optional\n"
"arguments, if the current time matches the given time specification.\n"
},
{ "Goto", pbx_builtin_goto,
"Jump to a particular priority, extension, or context",
" Goto([[context,]extension,]priority): This application will set the current\n"
"context, extension, and priority in the channel structure. After it completes, the\n"
"pbx engine will continue dialplan execution at the specified location.\n"
"If no specific extension, or extension and context, are specified, then this\n"
"application will just set the specified priority of the current extension.\n"
" At least a priority is required as an argument, or the goto will return a -1,\n"
"and the channel and call will be terminated.\n"
" If the location that is put into the channel information is bogus, and asterisk cannot\n"
"find that location in the dialplan,\n"
"then the execution engine will try to find and execute the code in the 'i' (invalid)\n"
"extension in the current context. If that does not exist, it will try to execute the\n"
"'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
"channel is hung up, and the execution of instructions on the channel is terminated.\n"
"What this means is that, for example, you specify a context that does not exist, then\n"
"it will not be possible to find the 'h' or 'i' extensions, and the call will terminate!\n"
},
{ "GotoIf", pbx_builtin_gotoif,
"Conditional goto",
" GotoIf(condition?[labeliftrue]:[labeliffalse]): This application will set the current\n"
"context, extension, and priority in the channel structure based on the evaluation of\n"
"the given condition. After this application completes, the\n"
"pbx engine will continue dialplan execution at the specified location in the dialplan.\n"
"The channel will continue at\n"
"'labeliftrue' if the condition is true, or 'labeliffalse' if the condition is\n"
"false. The labels are specified with the same syntax as used within the Goto\n"
"application. If the label chosen by the condition is omitted, no jump is\n"
"performed, and the execution passes to the next instruction.\n"
"If the target location is bogus, and does not exist, the execution engine will try \n"
"to find and execute the code in the 'i' (invalid)\n"
"extension in the current context. If that does not exist, it will try to execute the\n"
"'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
"channel is hung up, and the execution of instructions on the channel is terminated.\n"
"Remember that this command can set the current context, and if the context specified\n"
"does not exist, then it will not be able to find any 'h' or 'i' extensions there, and\n"
"the channel and call will both be terminated!\n"
},
{ "GotoIfTime", pbx_builtin_gotoiftime,
"Conditional Goto based on the current time",
" GotoIfTime(<times>,<weekdays>,<mdays>,<months>?[labeliftrue]:[labeliffalse]):\n"
"This application will set the context, extension, and priority in the channel structure\n"
"based on the evaluation of the given time specification. After this application completes,\n"
"the pbx engine will continue dialplan execution at the specified location in the dialplan.\n"
"If the current time is within the given time specification, the channel will continue at\n"
"'labeliftrue'. Otherwise the channel will continue at 'labeliffalse'. If the label chosen\n"
"by the condition is omitted, no jump is performed, and execution passes to the next\n"
"instruction. If the target jump location is bogus, the same actions would be taken as for\n"
"Goto.\n"
"Further information on the time specification can be found in examples\n"
"illustrating how to do time-based context includes in the dialplan.\n"
},
{ "ImportVar", pbx_builtin_importvar,
"Import a variable from a channel into a new variable",
" ImportVar(newvar=channelname,variable): This application imports a variable\n"
"from the specified channel (as opposed to the current one) and stores it as\n"
"a variable in the current channel (the channel that is calling this\n"
"application). Variables created by this application have the same inheritance\n"
"properties as those created with the Set application. See the documentation for\n"
"Set for more information.\n"
},
{ "Hangup", pbx_builtin_hangup,
"Hang up the calling channel",
" Hangup([causecode]): This application will hang up the calling channel.\n"
"If a causecode is given the channel's hangup cause will be set to the given\n"
"value.\n"
},
{ "NoOp", pbx_builtin_noop,
"Do Nothing (No Operation)",
" NoOp(): This application does nothing. However, it is useful for debugging\n"
"purposes. Any text that is provided as arguments to this application can be\n"
"viewed at the Asterisk CLI. This method can be used to see the evaluations of\n"
"variables or functions without having any effect. Alternatively, see the\n"
"Verbose() application for finer grain control of output at custom verbose levels.\n"
},
{ "Progress", pbx_builtin_progress,
"Indicate progress",
" Progress(): This application will request that in-band progress information\n"
"be provided to the calling channel.\n"
},
{ "RaiseException", pbx_builtin_raise_exception,
"Handle an exceptional condition",
" RaiseException(<reason>): This application will jump to the \"e\" extension\n"
"in the current context, setting the dialplan function EXCEPTION(). If the \"e\"\n"
"extension does not exist, the call will hangup.\n"
},
{ "ResetCDR", pbx_builtin_resetcdr,
"Resets the Call Data Record",
" ResetCDR([options]): This application causes the Call Data Record to be\n"
"reset.\n"
" Options:\n"
" w -- Store the current CDR record before resetting it.\n"
" a -- Store any stacked records.\n"
" v -- Save CDR variables.\n"
" e -- Enable CDR only (negate effects of NoCDR).\n"
},
{ "Ringing", pbx_builtin_ringing,
"Indicate ringing tone",
" Ringing(): This application will request that the channel indicate a ringing\n"
"tone to the user.\n"
},
{ "SayAlpha", pbx_builtin_saycharacters,
"Say Alpha",
" SayAlpha(string): This application will play the sounds that correspond to\n"
"the letters of the given string.\n"
},
{ "SayDigits", pbx_builtin_saydigits,
"Say Digits",
" SayDigits(digits): This application will play the sounds that correspond\n"
"to the digits of the given number. This will use the language that is currently\n"
"set for the channel. See the LANGUAGE function for more information on setting\n"
"the language for the channel.\n"
},
{ "SayNumber", pbx_builtin_saynumber,
"Say Number",
" SayNumber(digits[,gender]): This application will play the sounds that\n"
"correspond to the given number. Optionally, a gender may be specified.\n"
"This will use the language that is currently set for the channel. See the\n"
"LANGUAGE function for more information on setting the language for the channel.\n"
},
{ "SayPhonetic", pbx_builtin_sayphonetic,
"Say Phonetic",
" SayPhonetic(string): This application will play the sounds from the phonetic\n"
"alphabet that correspond to the letters in the given string.\n"
},
{ "Set", pbx_builtin_setvar,
"Set channel variable or function value",
" Set(name=value)\n"
"This function can be used to set the value of channel variables or dialplan\n"
"functions. When setting variables, if the variable name is prefixed with _,\n"
"the variable will be inherited into channels created from the current\n"
"channel. If the variable name is prefixed with __, the variable will be\n"
"inherited into channels created from the current channel and all children\n"
"channels.\n"
},
{ "MSet", pbx_builtin_setvar_multiple,
"Set channel variable(s) or function value(s)",
" MSet(name1=value1,name2=value2,...)\n"
"This function can be used to set the value of channel variables or dialplan\n"
"functions. When setting variables, if the variable name is prefixed with _,\n"
"the variable will be inherited into channels created from the current\n"
"channel. If the variable name is prefixed with __, the variable will be\n"
"inherited into channels created from the current channel and all children\n"
"channels.\n\n"
"MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus\n"
"prone to doing things that you may not expect. Avoid its use if possible.\n"
},
{ "SetAMAFlags", pbx_builtin_setamaflags,
"Set the AMA Flags",
" SetAMAFlags([flag]): This application will set the channel's AMA Flags for\n"
" billing purposes.\n"
},
{ "Wait", pbx_builtin_wait,
"Waits for some time",
" Wait(seconds): This application waits for a specified number of seconds.\n"
"Then, dialplan execution will continue at the next priority.\n"
" Note that the seconds can be passed with fractions of a second. For example,\n"
"'1.5' will ask the application to wait for 1.5 seconds.\n"
},
{ "WaitExten", pbx_builtin_waitexten,
"Waits for an extension to be entered",
" WaitExten([seconds][,options]): This application waits for the user to enter\n"
"a new extension for a specified number of seconds.\n"
" Note that the seconds can be passed with fractions of a second. For example,\n"
"'1.5' will ask the application to wait for 1.5 seconds.\n"
" Options:\n"
" m[(x)] - Provide music on hold to the caller while waiting for an extension.\n"
" Optionally, specify the class for music on hold within parenthesis.\n"
"See Also: Playback(application), Background(application).\n"
},
{ "KeepAlive", pbx_builtin_keepalive,
"returns AST_PBX_KEEPALIVE value",
" KeepAlive(): This application is chiefly meant for internal use with Gosubs.\n"
"Please do not run it alone from the dialplan!\n"
},
};
static struct ast_context *contexts;
static struct ast_hashtab *contexts_table = NULL;
AST_RWLOCK_DEFINE_STATIC(conlock); /*!< Lock for the ast_context list */
static AST_RWLIST_HEAD_STATIC(apps, ast_app);
static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
static int stateid = 1;
/* WARNING:
When holding this list's lock, do _not_ do anything that will cause conlock
to be taken, unless you _already_ hold it. The ast_merge_contexts_and_delete
function will take the locks in conlock/hints order, so any other
paths that require both locks must also take them in that order.
*/
static AST_RWLIST_HEAD_STATIC(hints, ast_hint);
static AST_LIST_HEAD_NOLOCK_STATIC(statecbs, ast_state_cb);
/*
\note This function is special. It saves the stack so that no matter
how many times it is called, it returns to the same place */
int pbx_exec(struct ast_channel *c, /*!< Channel */
struct ast_app *app, /*!< Application */
void *data) /*!< Data for execution */
{
int res;
struct ast_module_user *u = NULL;
const char *saved_c_appl;
const char *saved_c_data;
if (c->cdr && !ast_check_hangup(c))
ast_cdr_setapp(c->cdr, app->name, data);
/* save channel values */
saved_c_appl= c->appl;
saved_c_data= c->data;
c->appl = app->name;
c->data = data;
if (app->module)
u = __ast_module_user_add(app->module, c);
res = app->execute(c, S_OR(data, ""));
if (app->module && u)
__ast_module_user_remove(app->module, u);
/* restore channel values */
c->appl = saved_c_appl;
c->data = saved_c_data;
return res;
}
/*! Go no deeper than this through includes (not counting loops) */
#define AST_PBX_MAX_STACK 128
/*! \brief Find application handle in linked list
*/
struct ast_app *pbx_findapp(const char *app)
{
struct ast_app *tmp;
AST_RWLIST_RDLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, tmp, list) {
if (!strcasecmp(tmp->name, app))
break;
}
AST_RWLIST_UNLOCK(&apps);
return tmp;
}
static struct ast_switch *pbx_findswitch(const char *sw)
{
struct ast_switch *asw;
AST_RWLIST_RDLOCK(&switches);
AST_RWLIST_TRAVERSE(&switches, asw, list) {
if (!strcasecmp(asw->name, sw))
break;
}
AST_RWLIST_UNLOCK(&switches);
return asw;
}
static inline int include_valid(struct ast_include *i)
{
if (!i->hastime)
return 1;
return ast_check_timing(&(i->timing));
}
static void pbx_destroy(struct ast_pbx *p)
{
ast_free(p);
}
/* form a tree that fully describes all the patterns in a context's extensions
* in this tree, a "node" represents an individual character or character set
* meant to match the corresponding character in a dial string. The tree
* consists of a series of match_char structs linked in a chain
* via the alt_char pointers. More than one pattern can share the same parts of the
* tree as other extensions with the same pattern to that point.
* My first attempt to duplicate the finding of the 'best' pattern was flawed in that
* I misunderstood the general algorithm. I thought that the 'best' pattern
* was the one with lowest total score. This was not true. Thus, if you have
* patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is
* the "best" match because it has fewer X's, and is therefore more specific,
* but this is not how the old algorithm works. It sorts matching patterns
* in a similar collating sequence as sorting alphabetic strings, from left to
* right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match,
* because "1" is more specific than "X".
* So, to accomodate this philosophy, I sort the tree branches along the alt_char
* line so they are lowest to highest in specificity numbers. This way, as soon
* as we encounter our first complete match, we automatically have the "best"
* match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE.
* If anyone would like to resurrect the "wrong" pattern trie searching algorithm,
* they are welcome to revert pbx to before 1 Apr 2008.
* As an example, consider these 4 extensions:
* (a) NXXNXXXXXX
* (b) 307754XXXX
* (c) fax
* (d) NXXXXXXXXX
*
* In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over
* most numbers. For all numbers beginning with 307754, (b) should always win.
*
* These pattern should form a (sorted) tree that looks like this:
* { "3" } --next--> { "0" } --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) }
* |
* |alt
* |
* { "f" } --next--> { "a" } --next--> { "x" exten_match: (c) }
* { "N" } --next--> { "X" } --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
* | |
* | |alt
* |alt |
* | { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
* |
* NULL
*
* In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take
* fewer CPU cycles than a call to index("23456789",*z), where *z is the char to match...
*
* traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern, it calls itself
* on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length.
* We pass a pointer to a scoreboard down through, also.
* The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension.
* The first complete match ends the traversal, which should make this version of the pattern matcher faster
* the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both
* these cases, the reason we can stop immediately, is because the first pattern match found will be the "best"
* according to the sort criteria.
* Hope the limit on stack depth won't be a problem... this routine should
* be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch.
*
* In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d. All are
* of length 10; they have total specificities of 24580, 10246, and 25090, respectively, not that this matters
* at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have
* left the specificity totals in the code as an artifact; at some point, I will strip it out.
*
* Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown,
* because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup
* can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or
* more times faster in extreme cases.
*
* MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you
* can have patterns in your CID field as well.
*
* */
static void update_scoreboard(struct scoreboard *board, int length, int spec, struct ast_exten *exten, char last, const char *callerid, int deleted, struct match_char *node)
{
/* if this extension is marked as deleted, then skip this -- if it never shows
on the scoreboard, it will never be found, nor will halt the traversal. */
if (deleted)
return;
board->total_specificity = spec;
board->total_length = length;
board->exten = exten;
board->last_char = last;
board->node = node;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec);
#endif
}
void log_match_char_tree(struct match_char *node, char *prefix)
{
char extenstr[40];
struct ast_str *my_prefix = ast_str_alloca(1024);
extenstr[0] = '\0';
if (node && node->exten && node->exten)
snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
if (strlen(node->x) > 1) {
ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
node->exten ? node->exten->exten : "", extenstr);
} else {
ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
node->exten ? node->exten->exten : "", extenstr);
}
ast_str_set(&my_prefix, 0, "%s+ ", prefix);
if (node->next_char)
log_match_char_tree(node->next_char, my_prefix->str);
if (node->alt_char)
log_match_char_tree(node->alt_char, prefix);
}
static void cli_match_char_tree(struct match_char *node, char *prefix, int fd)
{
char extenstr[40];
struct ast_str *my_prefix = ast_str_alloca(1024);
extenstr[0] = '\0';
if (node && node->exten && node->exten)
snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
if (strlen(node->x) > 1) {
ast_cli(fd, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
node->exten ? node->exten->exten : "", extenstr);
} else {
ast_cli(fd, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
node->exten ? node->exten->exten : "", extenstr);
}
ast_str_set(&my_prefix, 0, "%s+ ", prefix);
if (node->next_char)
cli_match_char_tree(node->next_char, my_prefix->str, fd);
if (node->alt_char)
cli_match_char_tree(node->alt_char, prefix, fd);
}
static struct ast_exten *get_canmatch_exten(struct match_char *node)
{
/* find the exten at the end of the rope */
struct match_char *node2 = node;
for (node2 = node; node2; node2 = node2->next_char) {
if (node2->exten) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten);
#endif
return node2->exten;
}
}
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x);
#endif
return 0;
}
static struct ast_exten *trie_find_next_match(struct match_char *node)
{
struct match_char *m3;
struct match_char *m4;
struct ast_exten *e3;
if (node && node->x[0] == '.' && !node->x[1]) /* dot and ! will ALWAYS be next match in a matchmore */
return node->exten;
if (node && node->x[0] == '!' && !node->x[1])
return node->exten;
if (!node || !node->next_char)
return NULL;
m3 = node->next_char;
if (m3->exten)
return m3->exten;
for(m4=m3->alt_char; m4; m4 = m4->alt_char) {
if (m4->exten)
return m4->exten;
}
for(m4=m3; m4; m4 = m4->alt_char) {
e3 = trie_find_next_match(m3);
if (e3)
return e3;
}