aboutsummaryrefslogtreecommitdiffstats
path: root/pbx/pbx_lua.c
blob: 34babe39af3cf76762927780d6f17116d46b54bb (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 1999 - 2007, Digium, Inc.
 *
 * Matthew Nicholson <mnicholson@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
 *
 * \author Matthew Nicholson <mnicholson@digium.com>
 * \brief Lua PBX Switch
 *
 */

/*** MODULEINFO
	<depend>lua</depend>
 ***/

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#include "asterisk/logger.h"
#include "asterisk/channel.h"
#include "asterisk/pbx.h"
#include "asterisk/module.h"
#include "asterisk/cli.h"
#include "asterisk/utils.h"
#include "asterisk/term.h"
#include "asterisk/paths.h"
#include "asterisk/hashtab.h"

#ifdef LUA51_PREFIX
#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>
#else
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#endif

static char *config = "extensions.lua";
static char *registrar = "pbx_lua";

#define LUA_EXT_DATA_SIZE 256
#define LUA_BUF_SIZE 4096

static char *lua_read_extensions_file(lua_State *L, long *size);
static int lua_load_extensions(lua_State *L, struct ast_channel *chan);
static int lua_reload_extensions(lua_State *L);
static void lua_free_extensions(void);
static int lua_sort_extensions(lua_State *L);
static int lua_register_switches(lua_State *L);
static int lua_extension_cmp(lua_State *L);
static int lua_find_extension(lua_State *L, const char *context, const char *exten, int priority, ast_switch_f *func, int push_func);
static int lua_pbx_findapp(lua_State *L);
static int lua_pbx_exec(lua_State *L);

static int lua_get_variable_value(lua_State *L);
static int lua_set_variable_value(lua_State *L);
static int lua_get_variable(lua_State *L);
static int lua_set_variable(lua_State *L);
static int lua_func_read(lua_State *L);

static int lua_autoservice_start(lua_State *L);
static int lua_autoservice_stop(lua_State *L);
static int lua_autoservice_status(lua_State *L);
static int lua_check_hangup(lua_State *L);
static int lua_error_function(lua_State *L);

static void lua_update_registry(lua_State *L, const char *context, const char *exten, int priority);
static void lua_push_variable_table(lua_State *L, const char *name);
static void lua_create_app_table(lua_State *L);
static void lua_create_channel_table(lua_State *L);
static void lua_create_variable_metatable(lua_State *L);
static void lua_create_application_metatable(lua_State *L);
static void lua_create_autoservice_functions(lua_State *L);
static void lua_create_hangup_function(lua_State *L);

void lua_state_destroy(void *data);
static lua_State *lua_get_state(struct ast_channel *chan);

static int exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data);
static int canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data);
static int matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data);
static int exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data);

AST_MUTEX_DEFINE_STATIC(config_file_lock);
char *config_file_data = NULL;
long config_file_size = 0;

static struct ast_context *local_contexts = NULL;
static struct ast_hashtab *local_table = NULL;

static const struct ast_datastore_info lua_datastore = {
	.type = "lua",
	.destroy = lua_state_destroy,
};


/*!
 * \brief The destructor for lua_datastore
 */
void lua_state_destroy(void *data)
{
	if (data)
		lua_close(data);
}

/*!
 * \brief [lua_CFunction] Find an app and return it in a lua table (for access from lua, don't
 * call directly)
 *
 * This function would be called in the following example as it would be found
 * in extensions.lua.
 *
 * \code
 * app.dial
 * \endcode
 */
static int lua_pbx_findapp(lua_State *L)
{
	const char *app_name = luaL_checkstring(L, 2);
	
	lua_newtable(L);

	lua_pushstring(L, "name");
	lua_pushstring(L, app_name);
	lua_settable(L, -3);

	luaL_getmetatable(L, "application");
	lua_setmetatable(L, -2);

	return 1;
}

/*!
 * \brief [lua_CFunction] This function is part of the 'application' metatable
 * and is used to execute applications similar to pbx_exec() (for access from
 * lua, don't call directly)
 *
 * \param L the lua_State to use
 * \return nothing
 *
 * This funciton is executed as the '()' operator for apps accessed through the
 * 'app' table.
 *
 * \code
 * app.playback('demo-congrats')
 * \endcode
 */
static int lua_pbx_exec(lua_State *L)
{
	int res, nargs = lua_gettop(L);
	char data[LUA_EXT_DATA_SIZE] = "";
	char *data_next = data, *app_name;
	char *context, *exten;
	char tmp[80], tmp2[80], tmp3[LUA_EXT_DATA_SIZE];
	int priority, autoservice;
	size_t data_left = sizeof(data);
	struct ast_app *app;
	struct ast_channel *chan;
	
	lua_getfield(L, 1, "name");
	app_name = ast_strdupa(lua_tostring(L, -1));
	lua_pop(L, 1);
	
	if (!(app = pbx_findapp(app_name))) {
		lua_pushstring(L, "application '");
		lua_pushstring(L, app_name);
		lua_pushstring(L, "' not found");
		lua_concat(L, 3);
		return lua_error(L);
	}
	

	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);
	
	
	lua_getfield(L, LUA_REGISTRYINDEX, "context");
	context = ast_strdupa(lua_tostring(L, -1));
	lua_pop(L, 1);
	
	lua_getfield(L, LUA_REGISTRYINDEX, "exten");
	exten = ast_strdupa(lua_tostring(L, -1));
	lua_pop(L, 1);
	
	lua_getfield(L, LUA_REGISTRYINDEX, "priority");
	priority = lua_tointeger(L, -1);
	lua_pop(L, 1);


	if (nargs > 1) {
		int i;

		if (!lua_isnil(L, 2))
			ast_build_string(&data_next, &data_left, "%s", luaL_checkstring(L, 2));

		for (i = 3; i <= nargs; i++) {
			if (lua_isnil(L, i))
				ast_build_string(&data_next, &data_left, ",");
			else
				ast_build_string(&data_next, &data_left, ",%s", luaL_checkstring(L, i));
		}
	}
	
	ast_verb(3, "Executing [%s@%s:%d] %s(\"%s\", \"%s\")\n",
			exten, context, priority,
			term_color(tmp, app_name, COLOR_BRCYAN, 0, sizeof(tmp)),
			term_color(tmp2, chan->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)),
			term_color(tmp3, data, COLOR_BRMAGENTA, 0, sizeof(tmp3)));

	lua_getfield(L, LUA_REGISTRYINDEX, "autoservice");
	autoservice = lua_toboolean(L, -1);
	lua_pop(L, 1);

	if (autoservice)
		ast_autoservice_stop(chan);

	res = pbx_exec(chan, app, data);
	
	if (autoservice)
		ast_autoservice_start(chan);

	/* error executing an application, report it */
	if (res) {
		lua_pushinteger(L, res);
		return lua_error(L);
	}
	return 0;
}

/*!
 * \brief [lua_CFunction] Used to get the value of a variable or dialplan
 * function (for access from lua, don't call directly)
 * 
 * The value of the variable or function is returned.  This function is the
 * 'get()' function in the following example as would be seen in
 * extensions.lua.
 *
 * \code
 * channel.variable:get()
 * \endcode
 */
static int lua_get_variable_value(lua_State *L)
{
	struct ast_channel *chan;
	char *value = NULL, *name;
	char *workspace = alloca(LUA_BUF_SIZE);
	int autoservice;

	workspace[0] = '\0';

	if (!lua_istable(L, 1)) {
		lua_pushstring(L, "User probably used '.' instead of ':' for retrieving a channel variable value");
		return lua_error(L);
	}
	
	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "name");
	name = ast_strdupa(lua_tostring(L, -1));
	lua_pop(L, 1);
	
	lua_getfield(L, LUA_REGISTRYINDEX, "autoservice");
	autoservice = lua_toboolean(L, -1);
	lua_pop(L, 1);

	if (autoservice)
		ast_autoservice_stop(chan);
	
	/* if this is a dialplan function then use ast_func_read(), otherwise
	 * use pbx_retrieve_variable() */
	if (!ast_strlen_zero(name) && name[strlen(name) - 1] == ')') {
		value = ast_func_read(chan, name, workspace, LUA_BUF_SIZE) ? NULL : workspace;
	} else {
		pbx_retrieve_variable(chan, name, &value, workspace, LUA_BUF_SIZE, &chan->varshead);
	}
	
	if (autoservice)
		ast_autoservice_start(chan);

	if (value) {
		lua_pushstring(L, value);
	} else {
		lua_pushnil(L);
	}

	return 1;
}

/*!
 * \brief [lua_CFunction] Used to set the value of a variable or dialplan
 * function (for access from lua, don't call directly)
 * 
 * This function is the 'set()' function in the following example as would be
 * seen in extensions.lua.
 *
 * \code
 * channel.variable:set("value")
 * \endcode
 */
static int lua_set_variable_value(lua_State *L)
{
	const char *name, *value;
	struct ast_channel *chan;
	int autoservice;

	if (!lua_istable(L, 1)) {
		lua_pushstring(L, "User probably used '.' instead of ':' for setting a channel variable");
		return lua_error(L);
	}

	lua_getfield(L, 1, "name");
	name = ast_strdupa(lua_tostring(L, -1));
	lua_pop(L, 1);

	value = luaL_checkstring(L, 2);
	
	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, LUA_REGISTRYINDEX, "autoservice");
	autoservice = lua_toboolean(L, -1);
	lua_pop(L, 1);

	if (autoservice)
		ast_autoservice_stop(chan);

	pbx_builtin_setvar_helper(chan, name, value);
	
	if (autoservice)
		ast_autoservice_start(chan);

	return 0;
}

/*!
 * \brief Update the lua registry with the given context, exten, and priority.
 *
 * \param L the lua_State to use
 * \param context the new context
 * \param exten the new exten
 * \param priority the new priority
 */
static void lua_update_registry(lua_State *L, const char *context, const char *exten, int priority)
{
	lua_pushstring(L, context);
	lua_setfield(L, LUA_REGISTRYINDEX, "context");

	lua_pushstring(L, exten);
	lua_setfield(L, LUA_REGISTRYINDEX, "exten");

	lua_pushinteger(L, priority);
	lua_setfield(L, LUA_REGISTRYINDEX, "priority");
}

/*!
 * \brief Push a 'variable' table on the stack for access the channel variable
 * with the given name.
 *
 * \param L the lua_State to use
 * \param name the name of the variable
 */
static void lua_push_variable_table(lua_State *L, const char *name)
{
	lua_newtable(L);
	luaL_getmetatable(L, "variable");
	lua_setmetatable(L, -2);

	lua_pushstring(L, name);
	lua_setfield(L, -2, "name");
	
	lua_pushcfunction(L, &lua_get_variable_value);
	lua_setfield(L, -2, "get");
	
	lua_pushcfunction(L, &lua_set_variable_value);
	lua_setfield(L, -2, "set");
}

/*!
 * \brief Create the global 'app' table for executing applications
 *
 * \param L the lua_State to use
 */
static void lua_create_app_table(lua_State *L)
{
	lua_newtable(L);
	luaL_newmetatable(L, "app");

	lua_pushstring(L, "__index");
	lua_pushcfunction(L, &lua_pbx_findapp);
	lua_settable(L, -3);

	lua_setmetatable(L, -2);
	lua_setglobal(L, "app");
}

/*!
 * \brief Create the global 'channel' table for accesing channel variables
 *
 * \param L the lua_State to use
 */
static void lua_create_channel_table(lua_State *L)
{
	lua_newtable(L);
	luaL_newmetatable(L, "channel_data");

	lua_pushstring(L, "__index");
	lua_pushcfunction(L, &lua_get_variable);
	lua_settable(L, -3);

	lua_pushstring(L, "__newindex");
	lua_pushcfunction(L, &lua_set_variable);
	lua_settable(L, -3);

	lua_setmetatable(L, -2);
	lua_setglobal(L, "channel");
}

/*!
 * \brief Create the 'variable' metatable, used to retrieve channel variables
 *
 * \param L the lua_State to use
 */
static void lua_create_variable_metatable(lua_State *L)
{
	luaL_newmetatable(L, "variable");

	lua_pushstring(L, "__call");
	lua_pushcfunction(L, &lua_func_read);
	lua_settable(L, -3);

	lua_pop(L, 1);
}

/*!
 * \brief Create the 'application' metatable, used to execute asterisk
 * applications from lua 
 *
 * \param L the lua_State to use
 */
static void lua_create_application_metatable(lua_State *L)
{
	luaL_newmetatable(L, "application");

	lua_pushstring(L, "__call");
	lua_pushcfunction(L, &lua_pbx_exec);
	lua_settable(L, -3);

	lua_pop(L, 1);
}

/*!
 * \brief Create the autoservice functions
 *
 * \param L the lua_State to use
 */
static void lua_create_autoservice_functions(lua_State *L)
{
	lua_pushcfunction(L, &lua_autoservice_start);
	lua_setglobal(L, "autoservice_start");
	
	lua_pushcfunction(L, &lua_autoservice_stop);
	lua_setglobal(L, "autoservice_stop");

	lua_pushcfunction(L, &lua_autoservice_status);
	lua_setglobal(L, "autoservice_status");

	lua_pushboolean(L, 0);
	lua_setfield(L, LUA_REGISTRYINDEX, "autoservice");
}

/*!
 * \brief Create the hangup check function
 *
 * \param L the lua_State to use
 */
static void lua_create_hangup_function(lua_State *L)
{
	lua_pushcfunction(L, &lua_check_hangup);
	lua_setglobal(L, "check_hangup");
}

/*!
 * \brief [lua_CFunction] Return a lua 'variable' object (for access from lua, don't call
 * directly)
 * 
 * This function is called to lookup a variable construct a 'variable' object.
 * It would be called in the following example as would be seen in
 * extensions.lua.
 *
 * \code
 * channel.variable
 * \endcode
 */
static int lua_get_variable(lua_State *L)
{
	struct ast_channel *chan;
	char *name = ast_strdupa(luaL_checkstring(L, 2));
	char *value = NULL;
	char *workspace = alloca(LUA_BUF_SIZE);
	workspace[0] = '\0';
	
	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);

	lua_push_variable_table(L, name);
	
	/* if this is not a request for a dialplan funciton attempt to retrieve
	 * the value of the variable */
	if (!ast_strlen_zero(name) && name[strlen(name) - 1] != ')') {
		pbx_retrieve_variable(chan, name, &value, workspace, LUA_BUF_SIZE, &chan->varshead);
	}

	if (value) {
		lua_pushstring(L, value);
		lua_setfield(L, -2, "value");
	}

	return 1;	
}

/*!
 * \brief [lua_CFunction] Set the value of a channel variable or dialplan
 * function (for access from lua, don't call directly)
 * 
 * This function is called to set a variable or dialplan function.  It would be
 * called in the following example as would be seen in extensions.lua.
 *
 * \code
 * channel.variable = "value"
 * \endcode
 */
static int lua_set_variable(lua_State *L)
{
	struct ast_channel *chan;
	int autoservice;
	const char *name = luaL_checkstring(L, 2);
	const char *value = luaL_checkstring(L, 3);

	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, LUA_REGISTRYINDEX, "autoservice");
	autoservice = lua_toboolean(L, -1);
	lua_pop(L, 1);

	if (autoservice)
		ast_autoservice_stop(chan);

	pbx_builtin_setvar_helper(chan, name, value);
	
	if (autoservice)
		ast_autoservice_start(chan);

	return 0;
}

/*!
 * \brief [lua_CFunction] Create a 'variable' object for accessing a dialplan
 * function (for access from lua, don't call directly)
 * 
 * This function is called to create a 'variable' object to access a dialplan
 * function.  It would be called in the following example as would be seen in
 * extensions.lua.
 *
 * \code
 * channel.func("arg1", "arg2", "arg3")
 * \endcode
 *
 * To actually do anything with the resulting value you must use the 'get()'
 * and 'set()' methods (the reason is the resulting value is not a value, but
 * an object in the form of a lua table).
 */
static int lua_func_read(lua_State *L)
{
	int nargs = lua_gettop(L);
	char fullname[LUA_EXT_DATA_SIZE] = "";
	char *fullname_next = fullname, *name;
	size_t fullname_left = sizeof(fullname);
	
	lua_getfield(L, 1, "name");
	name = ast_strdupa(lua_tostring(L, -1));
	lua_pop(L, 1);

	ast_build_string(&fullname_next, &fullname_left, "%s(", name);
	
	if (nargs > 1) {
		int i;

		if (!lua_isnil(L, 2))
			ast_build_string(&fullname_next, &fullname_left, "%s", luaL_checkstring(L, 2));

		for (i = 3; i <= nargs; i++) {
			if (lua_isnil(L, i))
				ast_build_string(&fullname_next, &fullname_left, ",");
			else
				ast_build_string(&fullname_next, &fullname_left, ",%s", luaL_checkstring(L, i));
		}
	}

	ast_build_string(&fullname_next, &fullname_left, ")");
	
	lua_push_variable_table(L, fullname);
	
	return 1;
}

/*!
 * \brief [lua_CFunction] Tell pbx_lua to maintain an autoservice on this
 * channel (for access from lua, don't call directly)
 *
 * \param L the lua_State to use
 *
 * This function will set a flag that will cause pbx_lua to maintain an
 * autoservice on this channel.  The autoservice will automatically be stopped
 * and restarted before calling applications and functions.
 *
 * \return This function returns the result of the ast_autoservice_start()
 * function as a boolean to its lua caller.
 */
static int lua_autoservice_start(lua_State *L)
{
	struct ast_channel *chan;
	int res;

	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);

	res = ast_autoservice_start(chan);

	lua_pushboolean(L, !res);
	lua_setfield(L, LUA_REGISTRYINDEX, "autoservice");

	lua_pushboolean(L, !res);
	return 1;
}

/*!
 * \brief [lua_CFunction] Tell pbx_lua to stop maintaning an autoservice on
 * this channel (for access from lua, don't call directly)
 *
 * \param L the lua_State to use
 *
 * This function will stop any autoservice running and turn off the autoservice
 * flag.  If this function returns false, it's probably because no autoservice
 * was running to begin with.
 *
 * \return This function returns the result of the ast_autoservice_stop()
 * function as a boolean to its lua caller.
 */
static int lua_autoservice_stop(lua_State *L)
{
	struct ast_channel *chan;
	int res;

	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);

	res = ast_autoservice_stop(chan);

	lua_pushboolean(L, 0);
	lua_setfield(L, LUA_REGISTRYINDEX, "autoservice");

	lua_pushboolean(L, !res);
	return 1;
}

/*!
 * \brief [lua_CFunction] Get the status of the autoservice flag (for access
 * from lua, don't call directly)
 *
 * \param L the lua_State to use
 *
 * \return This function returns the status of the autoservice flag as a
 * boolean to its lua caller.
 */
static int lua_autoservice_status(lua_State *L)
{
	lua_getfield(L, LUA_REGISTRYINDEX, "autoservice");
	return 1;
}

/*!
 * \brief [lua_CFunction] Check if this channel has been hungup or not (for
 * access from lua, don't call directly)
 *
 * \param L the lua_State to use
 *
 * \return This function returns true if the channel was hungup
 */
static int lua_check_hangup(lua_State *L)
{
	struct ast_channel *chan;
	lua_getfield(L, LUA_REGISTRYINDEX, "channel");
	chan = lua_touserdata(L, -1);
	lua_pop(L, 1);

	lua_pushboolean(L, ast_check_hangup(chan));
	return 1;
}

/*!
 * \brief [lua_CFunction] Handle lua errors (for access from lua, don't call
 * directly)
 *
 * \param L the lua_State to use
 */
static int lua_error_function(lua_State *L)
{
	int message_index;

	/* pass number arguments right through back to asterisk*/
	if (lua_isnumber(L, -1)) {
		return 1;
	}

	/* if we are here then we have a string error message, let's attach a
	 * backtrace to it */
	message_index = lua_gettop(L);

	lua_getglobal(L, "debug");
	lua_getfield(L, -1, "traceback");
	lua_remove(L, -2); /* remove the 'debug' table */

	lua_pushvalue(L, message_index);
	lua_remove(L, message_index);

	lua_pushnumber(L, 2);

	lua_call(L, 2, 1);

	return 1;
}

/*!
 * \brief Store the sort order of each context
 
 * In the event of an error, an error string will be pushed onto the lua stack.
 *
 * \retval 0 success
 * \retval 1 failure
 */
static int lua_sort_extensions(lua_State *L)
{
	int extensions, extensions_order;

	/* create the extensions_order table */
	lua_newtable(L);
	lua_setfield(L, LUA_REGISTRYINDEX, "extensions_order");
	lua_getfield(L, LUA_REGISTRYINDEX, "extensions_order");
	extensions_order = lua_gettop(L);

	/* sort each context in the extensions table */
	/* load the 'extensions' table */
	lua_getglobal(L, "extensions");
	extensions = lua_gettop(L);
	if (lua_isnil(L, -1)) {
		lua_pop(L, 1);
		lua_pushstring(L, "Unable to find 'extensions' table in extensions.lua\n");
		return 1;
	}

	/* iterate through the extensions table and create a
	 * matching table (holding the sort order) in the
	 * extensions_order table for each context that is found
	 */
	for (lua_pushnil(L); lua_next(L, extensions); lua_pop(L, 1)) {
		int context = lua_gettop(L);
		int context_name = context - 1;
		int context_order;

		lua_pushvalue(L, context_name);
		lua_newtable(L);
		context_order = lua_gettop(L);

		/* iterate through this context an popluate the corrisponding
		 * table in the extensions_order table */
		for (lua_pushnil(L); lua_next(L, context); lua_pop(L, 1)) {
			int exten = lua_gettop(L) - 1;

			lua_pushinteger(L, lua_objlen(L, context_order) + 1);
			lua_pushvalue(L, exten);
			lua_settable(L, context_order);
		}
		lua_settable(L, extensions_order); /* put the context_order table in the extensions_order table */

		/* now sort the new table */

		/* push the table.sort function */
		lua_getglobal(L, "table");
		lua_getfield(L, -1, "sort");
		lua_remove(L, -2); /* remove the 'table' table */

		/* push the context_order table */
		lua_pushvalue(L, context_name);
		lua_gettable(L, extensions_order);

		/* push the comp function */
		lua_pushcfunction(L, &lua_extension_cmp);

		if (lua_pcall(L, 2, 0, 0)) {
			lua_insert(L, -5);
			lua_pop(L, 4);
			return 1;
		}
	}
	
	/* remove the extensions table and the extensions_order table */
	lua_pop(L, 2);
	return 0;
}

/*!
 * \brief Register dialplan switches for our pbx_lua contexs.
 *
 * In the event of an error, an error string will be pushed onto the lua stack.
 *
 * \retval 0 success
 * \retval 1 failure
 */
static int lua_register_switches(lua_State *L)
{
	int extensions;
	struct ast_context *con = NULL;

	/* create the hash table for our contexts */
	/* XXX do we ever need to destroy this? pbx_config does not */
	if (!local_table)
		local_table = ast_hashtab_create(17, ast_hashtab_compare_contexts, ast_hashtab_resize_java, ast_hashtab_newsize_java, ast_hashtab_hash_contexts, 0);

	/* load the 'extensions' table */
	lua_getglobal(L, "extensions");
	extensions = lua_gettop(L);
	if (lua_isnil(L, -1)) {
		lua_pop(L, 1);
		lua_pushstring(L, "Unable to find 'extensions' table in extensions.lua\n");
		return 1;
	}

	/* iterate through the extensions table and register a context and
	 * dialplan switch for each lua context
	 */
	for (lua_pushnil(L); lua_next(L, extensions); lua_pop(L, 1)) {
		int context = lua_gettop(L);
		int context_name = context - 1;
		const char *context_str = lua_tostring(L, context_name);

		/* find or create this context */
		con = ast_context_find_or_create(&local_contexts, local_table, context_str, registrar);
		if (!con) {
			/* remove extensions table and context key and value */
			lua_pop(L, 3);
			lua_pushstring(L, "Failed to find or create context\n");
			return 1;
		}

		/* register the switch */
		if (ast_context_add_switch2(con, "Lua", "", 0, registrar)) {
			/* remove extensions table and context key and value */
			lua_pop(L, 3);
			lua_pushstring(L, "Unable to create switch for context\n");
			return 1;
		}
	}
	
	/* remove the extensions table */
	lua_pop(L, 1);
	return 0;
}


/*!
 * \brief [lua_CFunction] Compare two extensions (for access from lua, don't
 * call directly)
 *
 * This function returns true if the first extension passed should match after
 * the second.  It behaves like the '<' operator.
 */
static int lua_extension_cmp(lua_State *L)
{
	const char *a = luaL_checkstring(L, -2);
	const char *b = luaL_checkstring(L, -1);

	if (ast_extension_cmp(a, b) == -1)
		lua_pushboolean(L, 1);
	else
		lua_pushboolean(L, 0);

	return 1;
}

/*!
 * \brief Load the extensions.lua file in to a buffer and execute the file
 *
 * \param L the lua_State to use
 * \param size a pointer to store the size of the buffer
 *
 * \note The caller is expected to free the buffer at some point.
 *
 * \return a pointer to the buffer
 */
static char *lua_read_extensions_file(lua_State *L, long *size)
{
	FILE *f;
	char *data;
	char *path = alloca(strlen(config) + strlen(ast_config_AST_CONFIG_DIR) + 2);
	sprintf(path, "%s/%s", ast_config_AST_CONFIG_DIR, config);

	if (!(f = fopen(path, "r"))) {
		lua_pushstring(L, "cannot open '");
		lua_pushstring(L, path);
		lua_pushstring(L, "' for reading: ");
		lua_pushstring(L, strerror(errno));
		lua_concat(L, 4);

		return NULL;
	}

	fseek(f, 0l, SEEK_END);
	*size = ftell(f);

	fseek(f, 0l, SEEK_SET);

	if (!(data = ast_malloc(*size))) {
		*size = 0;
		fclose(f);
		lua_pushstring(L, "not enough memory");
		return NULL;
	}

	if (fread(data, sizeof(char), *size, f) != *size) {
		ast_log(LOG_WARNING, "fread() failed: %s\n", strerror(errno));
	}
	fclose(f);

	if (luaL_loadbuffer(L, data, *size, "extensions.lua")
			|| lua_pcall(L, 0, LUA_MULTRET, 0)
			|| lua_sort_extensions(L)
			|| lua_register_switches(L)) {
		ast_free(data);
		data = NULL;
		*size = 0;
	}
	return data;
}

/*!
 * \brief Load the extensions.lua file from the internal buffer
 *
 * \param L the lua_State to use
 * \param chan channel to work on
 *
 * This function also sets up some constructs used by the extensions.lua file.
 * In the event of an error, an error string will be pushed onto the lua stack.
 *
 * \retval 0 success
 * \retval 1 failure
 */
static int lua_load_extensions(lua_State *L, struct ast_channel *chan)
{
	
	/* store a pointer to this channel */
	lua_pushlightuserdata(L, chan);
	lua_setfield(L, LUA_REGISTRYINDEX, "channel");
	
	luaL_openlibs(L);

	/* load and sort extensions */
	ast_mutex_lock(&config_file_lock);
	if (luaL_loadbuffer(L, config_file_data, config_file_size, "extensions.lua")
			|| lua_pcall(L, 0, LUA_MULTRET, 0)
			|| lua_sort_extensions(L)) {
		ast_mutex_unlock(&config_file_lock);
		return 1;
	}
	ast_mutex_unlock(&config_file_lock);

	/* now we setup special tables and functions */

	lua_create_app_table(L);
	lua_create_channel_table(L);

	lua_create_variable_metatable(L);
	lua_create_application_metatable(L);

	lua_create_autoservice_functions(L);
	lua_create_hangup_function(L);

	return 0;
}

/*!
 * \brief Reload the extensions file and update the internal buffers if it
 * loads correctly.
 *
 * \warning This function should not be called on a lua_State returned from
 * lua_get_state().
 *
 * \param L the lua_State to use (must be freshly allocated with
 * luaL_newstate(), don't use lua_get_state())
 */
static int lua_reload_extensions(lua_State *L)
{
	long size = 0;
	char *data = NULL;

	luaL_openlibs(L);

	if (!(data = lua_read_extensions_file(L, &size))) {
		return 1;
	}

	ast_mutex_lock(&config_file_lock);

	if (config_file_data)
		ast_free(config_file_data);

	config_file_data = data;
	config_file_size = size;
	
	/* merge our new contexts */
	ast_merge_contexts_and_delete(&local_contexts, local_table, registrar);
	/* merge_contexts_and_delete will actually, at the correct moment, 
	   set the global dialplan pointers to your local_contexts and local_table.
	   It then will free up the old tables itself. Just be sure not to
	   hang onto the pointers. */
	local_table = NULL;
	local_contexts = NULL;

	ast_mutex_unlock(&config_file_lock);
	return 0;
}

/*!
 * \brief Free the internal extensions buffer.
 */
static void lua_free_extensions()
{
	ast_mutex_lock(&config_file_lock);
	config_file_size = 0;
	ast_free(config_file_data);
	ast_mutex_unlock(&config_file_lock);
}

/*!
 * \brief Get the lua_State for this channel
 *
 * If no channel is passed then a new state is allocated.  States with no
 * channel assocatied with them should only be used for matching extensions.
 * If the channel does not yet have a lua state associated with it, one will be
 * created.
 *
 * \note If no channel was passed then the caller is expected to free the state
 * using lua_close().
 *
 * \return a lua_State
 */
static lua_State *lua_get_state(struct ast_channel *chan)
{
	struct ast_datastore *datastore = NULL;
	lua_State *L;

	if (!chan) {
		lua_State *L = luaL_newstate();
		if (!L) {
			ast_log(LOG_ERROR, "Error allocating lua_State, no memory\n");
			return NULL;
		}

		if (lua_load_extensions(L, NULL)) {
			const char *error = lua_tostring(L, -1);
			ast_log(LOG_ERROR, "Error loading extensions.lua: %s\n", error);
			lua_close(L);
			return NULL;
		}
		return L;
	} else {
		ast_channel_lock(chan);
		datastore = ast_channel_datastore_find(chan, &lua_datastore, NULL);
		ast_channel_unlock(chan);

		if (!datastore) {
			/* nothing found, allocate a new lua state */
			datastore = ast_channel_datastore_alloc(&lua_datastore, NULL);
			if (!datastore) {
				ast_log(LOG_ERROR, "Error allocation channel datastore for lua_State\n");
				return NULL;
			}

			datastore->data = luaL_newstate();
			if (!datastore->data) {
				ast_channel_datastore_free(datastore);
				ast_log(LOG_ERROR, "Error allocating lua_State, no memory\n");
				return NULL;
			}

			ast_channel_lock(chan);
			ast_channel_datastore_add(chan, datastore);
			ast_channel_unlock(chan);

			L = datastore->data;

			if (lua_load_extensions(L, chan)) {
				const char *error = lua_tostring(L, -1);
				ast_log(LOG_ERROR, "Error loading extensions.lua for %s: %s\n", chan->name, error);

				ast_channel_lock(chan);
				ast_channel_datastore_remove(chan, datastore);
				ast_channel_unlock(chan);

				ast_channel_datastore_free(datastore);
				return NULL;
			}
		}

		return datastore->data;
	}
}

static int exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
{
	int res;
	lua_State *L;
	struct ast_module_user *u = ast_module_user_add(chan);
	if (!u) {
		ast_log(LOG_ERROR, "Error adjusting use count, probably could not allocate memory\n");
		return 0;
	}

	L = lua_get_state(chan);
	if (!L) {
		ast_module_user_remove(u);
		return 0;
	}

	res = lua_find_extension(L, context, exten, priority, &exists, 0);

	if (!chan) lua_close(L);
	ast_module_user_remove(u);
	return res;
}

static int canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
{
	int res;
	lua_State *L;
	struct ast_module_user *u = ast_module_user_add(chan);
	if (!u) {
		ast_log(LOG_ERROR, "Error adjusting use count, probably could not allocate memory\n");
		return 0;
	}

	L = lua_get_state(chan);
	if (!L) {
		ast_module_user_remove(u);
		return 0;
	}

	res = lua_find_extension(L, context, exten, priority, &canmatch, 0);

	if (!chan) lua_close(L);
	ast_module_user_remove(u);
	return res;
}

static int matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
{
	int res;
	lua_State *L;
	struct ast_module_user *u = ast_module_user_add(chan);
	if (!u) {
		ast_log(LOG_ERROR, "Error adjusting use count, probably could not allocate memory\n");
		return 0;
	}

	L = lua_get_state(chan);
	if (!L) {
		ast_module_user_remove(u);
		return 0;
	}
	
	res = lua_find_extension(L, context, exten, priority, &matchmore, 0);

	if (!chan) lua_close(L);
	ast_module_user_remove(u);
	return res;
}


static int exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
{
	int res, error_func;
	lua_State *L;
	struct ast_module_user *u = ast_module_user_add(chan);
	if (!u) {
		ast_log(LOG_ERROR, "Error adjusting use count, probably could not allocate memory\n");
		return -1;
	}
	
	L = lua_get_state(chan);
	if (!L) {
		ast_module_user_remove(u);
		return -1;
	}

	lua_pushcfunction(L, &lua_error_function);
	error_func = lua_gettop(L);

	/* push the extension function onto the stack */
	if (!lua_find_extension(L, context, exten, priority, &exists, 1)) {
		lua_pop(L, 1); /* pop the debug function */
		ast_log(LOG_ERROR, "Could not find extension %s in context %s\n", exten, context);
		if (!chan) lua_close(L);
		ast_module_user_remove(u);
		return -1;
	}
		
	lua_update_registry(L, context, exten, priority);
	
	lua_pushstring(L, context);
	lua_pushstring(L, exten);
	
	res = lua_pcall(L, 2, 0, error_func);
	if (res) {
		if (res == LUA_ERRRUN) {
			res = -1;
			if (lua_isnumber(L, -1)) {
				res = lua_tointeger(L, -1);
			} else if (lua_isstring(L, -1)) {
				const char *error = lua_tostring(L, -1);
				ast_log(LOG_ERROR, "Error executing lua extension: %s\n", error);
			}
		} else if (res == LUA_ERRERR) {
			res = -1;
			ast_log(LOG_ERROR, "Error in the lua error handler (this is probably a bug in pbx_lua)\n");
		} else if (res == LUA_ERRMEM) {
			res = -1;
			ast_log(LOG_ERROR, "Memory allocation error\n");
		}
		lua_pop(L, 1);
	}
	lua_remove(L, error_func);
	if (!chan) lua_close(L);
	ast_module_user_remove(u);
	return res;
}

/*!
 * \brief Locate an extensions and optionally push the matching function on the
 * stack
 *
 * \param L the lua_State to use
 * \param context the context to look in
 * \param exten the extension to look up
 * \param priority the priority to check, '1' is the only valid priority
 * \param func the calling func, used to adjust matching behavior between,
 * match, canmatch, and matchmore
 * \param push_func whether or not to push the lua function for the given
 * extension onto the stack
 */
static int lua_find_extension(lua_State *L, const char *context, const char *exten, int priority, ast_switch_f *func, int push_func)
{
	int context_table, context_order_table, i;

	ast_debug(2, "Looking up %s@%s:%i\n", exten, context, priority);
	if (priority != 1)
		return 0;

	/* load the 'extensions' table */
	lua_getglobal(L, "extensions");
	if (lua_isnil(L, -1)) {
		ast_log(LOG_ERROR, "Unable to find 'extensions' table in extensions.lua\n");
		lua_pop(L, 1);
		return 0;
	}

	/* load the given context */
	lua_getfield(L, -1, context);
	if (lua_isnil(L, -1)) {
		lua_pop(L, 2);
		return 0;
	}

	/* remove the extensions table */
	lua_remove(L, -2);

	context_table = lua_gettop(L);

	/* load the extensions order table for this context */
	lua_getfield(L, LUA_REGISTRYINDEX, "extensions_order");
	lua_getfield(L, -1, context);

	lua_remove(L, -2);  /* remove the extensions order table */

	context_order_table = lua_gettop(L);
	
	/* step through the extensions looking for a match */
	for (i = 1; i < lua_objlen(L, context_order_table) + 1; i++) {
		int e_index, e_index_copy, match = 0;
		const char *e;

		lua_pushinteger(L, i);
		lua_gettable(L, context_order_table);
		e_index = lua_gettop(L);

		/* copy the key at the top of the stack for use later */
		lua_pushvalue(L, -1);
		e_index_copy = lua_gettop(L);

		if (!(e = lua_tostring(L, e_index_copy))) {
			lua_pop(L, 2);
			continue;
		}

		/* make sure this is not the 'include' extension */
		if (!strcasecmp(e, "include")) {
			lua_pop(L, 2);
			continue;
		}

		if (func == &matchmore)
			match = ast_extension_close(e, exten, E_MATCHMORE);
		else if (func == &canmatch)
			match = ast_extension_close(e, exten, E_CANMATCH);
		else
			match = ast_extension_match(e, exten);

		/* the extension matching functions return 0 on fail, 1 on
		 * match, 2 on earlymatch */

		if (!match) {
			/* pop the copy and the extension */
			lua_pop(L, 2);
			continue;	/* keep trying */
		}

		if (func == &matchmore && match == 2) {
			/* We match an extension ending in '!'. The decision in
			 * this case is final and counts as no match. */
			lua_pop(L, 4);
			return 0;
		}

		/* remove the context table, the context order table, the
		 * extension, and the extension copy (or replace the extension
		 * with the corresponding function) */
		if (push_func) {
			lua_pop(L, 1);  /* pop the copy */
			lua_gettable(L, context_table);
			lua_insert(L, -3);
			lua_pop(L, 2);
		} else {
			lua_pop(L, 4);
		}

		return 1;
	}

	/* load the includes for this context */
	lua_getfield(L, context_table, "include");
	if (lua_isnil(L, -1)) {
		lua_pop(L, 3);
		return 0;
	}

	/* remove the context and the order table*/
	lua_remove(L, context_order_table);
	lua_remove(L, context_table);

	/* Now try any includes we have in this context */
	for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
		const char *c = lua_tostring(L, -1);
		if (!c)
			continue;

		if (lua_find_extension(L, c, exten, priority, func, push_func)) {
			/* remove the value, the key, and the includes table
			 * from the stack.  Leave the function behind if
			 * necessary */

			if (push_func)
				lua_insert(L, -4);

			lua_pop(L, 3);
			return 1;
		}
	}

	/* pop the includes table */
	lua_pop(L, 1);
	return 0;
}

static struct ast_switch lua_switch = {
        .name		= "Lua",
        .description	= "Lua PBX Switch",
        .exists		= exists,
        .canmatch	= canmatch,
        .exec		= exec,
        .matchmore	= matchmore,
};


static int load_or_reload_lua_stuff(void)
{
	int res = AST_MODULE_LOAD_SUCCESS;

	lua_State *L = luaL_newstate();
	if (!L) {
		ast_log(LOG_ERROR, "Error allocating lua_State, no memory\n");
		return AST_MODULE_LOAD_DECLINE;
	}

	if (lua_reload_extensions(L)) {
		const char *error = lua_tostring(L, -1);
		ast_log(LOG_ERROR, "Error loading extensions.lua: %s\n", error);
		res = AST_MODULE_LOAD_DECLINE;
	}

	lua_close(L);
	return res;
}

static int unload_module(void)
{
	ast_context_destroy(NULL, registrar);
	ast_unregister_switch(&lua_switch);
	lua_free_extensions();
	return 0;
}

static int reload(void)
{
	return load_or_reload_lua_stuff();
}

static int load_module(void)
{
	int res;

	if ((res = load_or_reload_lua_stuff()))
		return res;

	if (ast_register_switch(&lua_switch)) {
		ast_log(LOG_ERROR, "Unable to register LUA PBX switch\n");
		return AST_MODULE_LOAD_DECLINE;
	}

	return AST_MODULE_LOAD_SUCCESS;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Lua PBX Switch",
		.load = load_module,
		.unload = unload_module,
		.reload = reload,
	       );