-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathalfred.c
2619 lines (2352 loc) · 78.6 KB
/
alfred.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
/**
* @file alfred.c
*
* Copyright 2015, Allied Telesis Labs New Zealand, Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>
*/
#include <assert.h>
#include <dirent.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlschemas.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <pthread.h>
#include <time.h>
#include <glib.h>
#include <glib-unix.h>
#include <lua.h>
#include <apteryx.h>
#include "common.h"
/* Change the following to alfred*/
#define ALFRED_PID "/var/run/apteryx-alfred.pid"
#define ALFRED_CONFIG_DIR "/etc/apteryx/schema/"
#define ALFRED_SCRIPT_DIR "/usr/share/alfred/"
#define SECONDS_TO_MILLI 1000
/* Debug */
bool apteryx_debug = false;
/* An Alfred instance. */
struct alfred_instance_t
{
/* Lua state */
/* List of watches based on path */
GList *watches;
/* List of refreshers based on path */
GList *refreshers;
/* List of provides based on path */
GList *provides;
/* List of indexes based on path */
GList *indexes;
/* Mapping table */
GHashTable *map_hash_table;
} alfred_instance_t;
typedef struct alfred_instance_t *alfred_instance;
/* The one and only instance */
alfred_instance alfred_inst = NULL;
GHashTable *lua_instances = NULL;
int luaopen_apteryx (lua_State *L);
int lua_apteryx_close (lua_State *L);
bool lua_apteryx_instance_lock (lua_State *L);
void lua_apteryx_instance_unlock (lua_State *L);
static lua_State *alfred_new_instance(const char *key, bool api_required);
static void
alfred_error (lua_State *ls, int res)
{
switch (res)
{
case LUA_ERRRUN:
CRITICAL ("LUA: %s\n", lua_tostring (ls, -1));
break;
case LUA_ERRSYNTAX:
CRITICAL ("LUA: %s\n", lua_tostring (ls, -1));
break;
case LUA_ERRMEM:
CRITICAL ("LUA: Memory allocation error\n");
break;
case LUA_ERRERR:
CRITICAL ("LUA: Error handler error\n");
break;
case LUA_ERRFILE:
CRITICAL ("LUA: Couldn't open file\n");
break;
default:
CRITICAL ("LUA: Unknown error\n");
break;
}
}
static bool
alfred_call (lua_State *ls, int nresults)
{
int res, s_0 = lua_gettop (ls);
size_t fargs = lua_rawlen(ls, -1) - 1;
/* Load stack with function and its arguments from table */
for (size_t i = 1; i <= fargs + 1; i++)
{
lua_rawgeti(ls, s_0, i);
}
res = lua_pcall (ls, (int)(fargs), nresults, 0);
if (res != 0)
alfred_error (ls, res);
if (lua_gettop (ls) != (s_0 + nresults))
{
lua_Debug ar;
/* Push function back on the stack to get some details */
lua_rawgeti(ls, s_0, 1);
lua_getinfo(ls, ">nS", &ar);
printf ("Lua: Stack not zero(%d) after function: %s:%d:%s\n",
lua_gettop (ls),
ar.source && ar.source[0] != '\0' ? ar.source : "(unknown)",
ar.linedefined,
ar.name && ar.name[0] != '\0' ? ar.name : "(unknown)");
lua_pop(ls, 1);
}
return (res == 0);
}
static bool
alfred_exec (lua_State *ls, const char *script, int nresults)
{
int res = 0;
int s_0 = lua_gettop (ls);
res = luaL_loadstring (ls, script);
if (res == 0)
res = lua_pcall (ls, 0, nresults, 0);
if (res != 0)
alfred_error (ls, res);
if (lua_gettop (ls) != (s_0 + nresults))
{
ERROR ("Lua: Stack not zero(%d) after script: %s\n",
lua_gettop (ls), script);
}
return (res == 0);
}
static bool
watch_node_changed (const char *path, const char *value)
{
GList *matches = NULL;
GList *node = NULL;
GList *script = NULL;
GList *scripts = NULL;
bool ret = false;
cb_info_t *cb = NULL;
assert (path);
assert (alfred_inst);
matches = cb_match (&alfred_inst->watches, path, CB_MATCH_EXACT |
CB_PATH_MATCH_PART | CB_MATCH_WILD_PATH);
if (matches == NULL)
{
ERROR ("ALFRED: No Alfred watch for %s\n", path);
return false;
}
for (node = g_list_first (matches); node != NULL; node = g_list_next (node))
{
cb = node->data;
scripts = (GList *) (long) cb->cb;
for (script = g_list_first (scripts); script != NULL; script = g_list_next (script))
{
if (lua_apteryx_instance_lock (cb->instance))
{
lua_pushstring (cb->instance, path);
lua_setglobal (cb->instance, "_path");
lua_pushstring (cb->instance, value);
lua_setglobal (cb->instance, "_value");
ret = alfred_exec (cb->instance, script->data, 0);
lua_gc (cb->instance, LUA_GCCOUNT, 0);
DEBUG ("LUA: Stack:%d Memory:%dkb\n", lua_gettop (cb->instance),
lua_gc (cb->instance, LUA_GCCOUNT, 0));
lua_apteryx_instance_unlock (cb->instance);
}
}
}
g_list_free_full (matches, (GDestroyNotify) cb_release);
DEBUG ("ALFRED WATCH: %s = %s\n", path, value);
return ret;
}
uint64_t
refresh_node_changed (const char *path)
{
uint64_t timeout = 0;
GList *matches = NULL;
char *script = NULL;
cb_info_t *cb = NULL;
int s_0;
matches = cb_match (&alfred_inst->refreshers, path, CB_MATCH_EXACT | CB_MATCH_WILD_PATH);
if (matches == NULL)
{
ERROR ("ALFRED: No Alfred refresh for %s\n", path);
return 0;
}
cb = g_list_first (matches)->data;
script = (char *) (long) cb->cb;
if(lua_apteryx_instance_lock (cb->instance))
{
lua_pushstring (cb->instance, path);
lua_setglobal (cb->instance, "_path");
s_0 = lua_gettop (cb->instance);
if (!alfred_exec (cb->instance, script, 1))
{
ERROR ("Lua: Failed to execute refresh script for path: %s\n", path);
}
g_list_free_full (matches, (GDestroyNotify) cb_release);
/* The return value of luaL_dostring is the top value of the stack */
timeout = lua_tonumber (cb->instance, -1);
lua_pop (cb->instance, 1);
DEBUG ("LUA: Stack:%d Memory:%dkb\n", lua_gettop (cb->instance),
lua_gc (cb->instance, LUA_GCCOUNT, 0));
if (lua_gettop (cb->instance) != s_0)
{
ERROR ("Lua: Stack not zero(%d) after provide: %s\n",
lua_gettop (cb->instance), path);
}
lua_apteryx_instance_unlock (cb->instance);
}
return timeout;
}
char *
provide_node_changed (const char *path)
{
const char *const_value = NULL;
char *ret = NULL;
GList *matches = NULL;
char *script = NULL;
cb_info_t *cb = NULL;
int s_0;
matches = cb_match (&alfred_inst->provides, path, CB_MATCH_EXACT | CB_MATCH_WILD_PATH);
if (matches == NULL)
{
ERROR ("ALFRED: No Alfred provide for %s\n", path);
return NULL;
}
cb = g_list_first (matches)->data;
script = (char *) (long) cb->cb;
if (lua_apteryx_instance_lock (cb->instance))
{
lua_pushstring (cb->instance, path);
lua_setglobal (cb->instance, "_path");
s_0 = lua_gettop (cb->instance);
if (!alfred_exec (cb->instance, script, 1))
{
ERROR ("Lua: Failed to execute provide script for path: %s\n", path);
}
g_list_free_full (matches, (GDestroyNotify) cb_release);
/* The return value of luaL_dostring is the top value of the stack */
const_value = lua_tostring (cb->instance, -1);
lua_pop (cb->instance, 1);
ret = g_strdup (const_value);
DEBUG("LUA: Stack:%d Memory:%dkb\n", lua_gettop (cb->instance),
lua_gc (cb->instance, LUA_GCCOUNT, 0));
if (lua_gettop (cb->instance) != s_0)
{
ERROR ("Lua: Stack not zero(%d) after provide: %s\n",
lua_gettop (cb->instance), path);
}
lua_apteryx_instance_unlock(cb->instance);
}
return ret;
}
static GList *
index_node_changed (const char *path)
{
char *script = NULL;
const char *tmp_path = NULL;
char *tmp_path2 = NULL;
GList *ret = NULL;
GList *matches = NULL;
cb_info_t *cb = NULL;
int s_0;
matches = cb_match (&alfred_inst->indexes, path, CB_MATCH_EXACT | CB_MATCH_WILD_PATH);
if (matches == NULL)
{
ERROR ("ALFRED: No Alfred index for %s\n", path);
return NULL;
}
cb = g_list_first (matches)->data;
script = (char *) (long) cb->cb;
if (lua_apteryx_instance_lock (cb->instance))
{
lua_pushstring (cb->instance, path);
lua_setglobal (cb->instance, "_path");
s_0 = lua_gettop (cb->instance);
if (!alfred_exec (cb->instance, script, 1))
{
ERROR ("Lua: Failed to execute index script for path: %s\n", path);
}
g_list_free_full (matches, (GDestroyNotify) cb_release);
if (lua_gettop (cb->instance))
{
if (lua_istable (cb->instance, -1))
{
lua_pushnil (cb->instance);
while (lua_next(cb->instance, -2) != 0)
{
tmp_path = lua_tostring (cb->instance, -1);
tmp_path2 = strdup (tmp_path);
ret = g_list_append (ret, tmp_path2);
/* Removes 'value'; keeps 'key' for next iteration */
lua_pop (cb->instance, 1);
}
lua_pop (cb->instance, 1);
}
}
DEBUG("LUA: Stack:%d Memory:%dkb\n", lua_gettop(cb->instance),
lua_gc (cb->instance, LUA_GCCOUNT, 0));
if (lua_gettop (cb->instance) != s_0)
{
ERROR ("Lua: Stack not zero(%d) after index: %s\n",
lua_gettop (cb->instance), path);
}
lua_apteryx_instance_unlock (cb->instance);
}
return ret;
}
static void
alfred_register_watches (gpointer value, gpointer user_data)
{
cb_info_t *cb = (cb_info_t *) value;
int install = GPOINTER_TO_INT (user_data);
if ((install && !apteryx_watch (cb->path, watch_node_changed)) ||
(!install && !apteryx_unwatch (cb->path, watch_node_changed)))
{
ERROR ("Failed to (un)register watch for path %s\n", cb->path);
}
}
static void
alfred_register_refresh (gpointer value, gpointer user_data)
{
cb_info_t *cb = (cb_info_t *) value;
int install = GPOINTER_TO_INT (user_data);
if ((install && !apteryx_refresh (cb->path, refresh_node_changed)) ||
(!install && !apteryx_unrefresh (cb->path, refresh_node_changed)))
{
ERROR ("Failed to (un)register refresh for path %s\n", cb->path);
}
}
static void
alfred_register_provide (gpointer value, gpointer user_data)
{
cb_info_t *cb = (cb_info_t *) value;
int install = GPOINTER_TO_INT (user_data);
if ((install && !apteryx_provide (cb->path, provide_node_changed)) ||
(!install && !apteryx_unprovide (cb->path, provide_node_changed)))
{
ERROR ("Failed to (un)register provide for path %s\n", cb->path);
}
}
static void
alfred_register_index (gpointer value, gpointer user_data)
{
cb_info_t *cb = (cb_info_t *) value;
int install = GPOINTER_TO_INT (user_data);
if ((install && !apteryx_index (cb->path, index_node_changed)) ||
(!install && !apteryx_unindex (cb->path, index_node_changed)))
{
ERROR ("Failed to (un)register provide for path %s\n", cb->path);
}
}
static bool
destroy_watches (gpointer value, gpointer rpc)
{
cb_info_t *cb = (cb_info_t *) value;
GList *scripts = (GList *) (long) cb->cb;
DEBUG ("XML: Destroy watches for path %s\n", cb->path);
g_list_free_full (scripts, g_free);
cb_destroy (cb);
cb_release (cb);
return true;
}
static bool
destroy_refresher (gpointer value, gpointer rpc)
{
cb_info_t *cb = (cb_info_t *) value;
char *script = (char *) (long) cb->cb;
DEBUG ("XML: Destroy refresher for path %s\n", cb->path);
g_free (script);
cb_destroy (cb);
cb_release (cb);
return true;
}
static bool
destroy_provides (gpointer value, gpointer rpc)
{
cb_info_t *cb = (cb_info_t *) value;
char *script = (char *) (long) cb->cb;
DEBUG ("XML: Destroy provides for path %s\n", cb->path);
g_free (script);
cb_destroy (cb);
cb_release (cb);
return true;
}
static bool
destroy_indexes (gpointer value, gpointer rpc)
{
cb_info_t *cb = (cb_info_t *) value;
char *script = (char *) (long) cb->cb;
DEBUG ("XML: Destroy indexes for path %s\n", cb->path);
g_free (script);
cb_destroy (cb);
cb_release (cb);
return true;
}
static bool
node_is_leaf (xmlNode *node)
{
for (xmlNode *n = node->children; n; n = n->next)
{
if (n->type == XML_ELEMENT_NODE && strcmp ((const char *) n->name, "NODE") == 0)
return false;
}
return true;
}
static bool
process_node (alfred_instance alfred, lua_State *instance, xmlNode *node, char *parent)
{
xmlChar *name = NULL;
const char *mapping = NULL;
xmlChar *content = NULL;
char *path = NULL;
char *tmp_content = NULL;
GList *matches = NULL;
GList *scripts = NULL;
cb_info_t *cb;
bool res = true;
assert (alfred);
/* Ignore fluff */
if (!node || node->type != XML_ELEMENT_NODE)
return true;
/* Check for a root node mapping */
if (!parent && node->ns && alfred->map_hash_table)
mapping = (const char *) g_hash_table_lookup (alfred->map_hash_table,
(const char *) node->ns->href);
/* Process this node */
if (strcmp ((const char *) node->name, "NODE") == 0)
{
/* Find node name and path */
name = xmlGetProp (node, (xmlChar *) "name");
if (mapping)
path = g_strdup (mapping);
else if (parent)
path = g_strdup_printf ("%s/%s", parent, name);
else
path = g_strdup_printf ("/%s", name);
DEBUG ("XML: %s: %s (%s)\n", node->name, name, path);
}
else if (strcmp ((const char *) node->name, "WATCH") == 0)
{
content = xmlNodeGetContent (node);
tmp_content = g_strdup ((char *) content);
/* If the node is a leaf or ends in a '*' don't add another '*' */
if (node_is_leaf (node->parent) || parent[strlen (parent) - 1] == '*')
{
path = g_strdup (parent);
}
else
{
path = g_strdup_printf ("%s/*", parent);
}
if (alfred->watches)
{
matches = cb_match (&alfred->watches, path, CB_MATCH_EXACT);
}
if (matches == NULL)
{
scripts = g_list_append (scripts, tmp_content);
cb = cb_create (&alfred->watches, instance, "", (const char *) path, 0,
(uint64_t) (long) scripts);
}
else
{
/* A watch already exists on that exact path */
cb = matches->data;
/* Watch callbacks on the same path from a different XML instance
* need to do something different here...*/
assert (cb->instance == instance);
scripts = (GList *) (long) cb->cb;
scripts = g_list_append (scripts, tmp_content);
g_list_free_full (matches, (GDestroyNotify) cb_release);
}
DEBUG ("XML: %s: (%s)\n", node->name, cb->path);
}
else if (strcmp ((const char *) node->name, "SCRIPT") == 0)
{
bool ret = false;
content = xmlNodeGetContent (node);
DEBUG ("XML: %s: %s\n", node->name, content);
ret = alfred_exec (instance, (char *) content, 0);
if (!ret)
{
res = false;
goto exit;
}
}
else if (strcmp ((const char *) node->name, "REFRESH") == 0)
{
content = xmlNodeGetContent (node);
tmp_content = g_strdup ((char *) content);
DEBUG ("REFRESH: %s, XML STR: %s\n", parent, content);
/* If the node is a leaf or ends in a '*' don't add another '*' */
if (node_is_leaf (node->parent) || parent[strlen (parent) - 1] == '*')
{
path = g_strdup (parent);
}
else
{
path = g_strdup_printf ("%s/*", parent);
}
if (path)
{
cb = cb_create (&alfred->refreshers, instance, "", (const char *) path, 0,
(uint64_t) (long) tmp_content);
}
}
else if (strcmp ((const char *) node->name, "PROVIDE") == 0)
{
content = xmlNodeGetContent (node);
tmp_content = g_strdup ((char *) content);
DEBUG ("PROVIDE: %s, XML STR: %s\n", parent, content);
/* If the node is a leaf or ends in a '*' don't add another '*' */
if (node_is_leaf (node->parent) || parent[strlen (parent) - 1] == '*')
{
path = g_strdup (parent);
}
else
{
path = g_strdup_printf ("%s/*", parent);
}
if (path)
{
cb = cb_create (&alfred->provides, instance, "", (const char *) path, 0,
(uint64_t) (long) tmp_content);
}
}
else if (strcmp ((const char *) node->name, "INDEX") == 0)
{
content = xmlNodeGetContent (node);
tmp_content = g_strdup ((char *) content);
DEBUG ("INDEX: XML STR: %s\n", content);
/* If the node is a leaf or ends in a '*' don't add another '*' */
if (node_is_leaf (node->parent) || parent[strlen (parent) - 1] == '*')
{
path = g_strdup (parent);
}
else
{
path = g_strdup_printf ("%s/*", parent);
}
if (path)
{
cb = cb_create (&alfred->indexes, instance, "", (const char *) path, 0,
(uint64_t) (long) tmp_content);
}
}
/* Process children */
for (xmlNode *n = node->children; n; n = n->next)
{
if (!process_node (alfred, instance, n, path))
{
res = false;
goto exit;
}
}
exit:
if (path)
g_free (path);
if (name)
xmlFree (name);
if (content)
xmlFree (content);
return res;
}
static void
sch_load_namespace_mappings (alfred_instance instance, const char *filename)
{
FILE *fp = NULL;
gchar **ns_names;
char buf[256];
if (!instance)
return;
fp = fopen (filename, "r");
if (fp)
{
if (!instance->map_hash_table)
instance->map_hash_table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
while (fgets (buf, sizeof (buf), fp) != NULL)
{
/* Skip comment lines */
if (buf[0] == '#')
continue;
/* Remove any trailing LF */
buf[strcspn(buf, "\n")] = '\0';
ns_names = g_strsplit (buf, " ", 2);
if (ns_names[0] && ns_names[1])
{
/* Insert will take care of duplicates automatically. */
g_hash_table_insert (instance->map_hash_table, g_strdup (ns_names[0]),
g_strdup (ns_names[1]));
}
g_strfreev (ns_names);
}
fclose (fp);
}
}
static bool
load_config_files (alfred_instance alfred, const char *path)
{
struct dirent *entry;
DIR *dir;
bool res = true;
/* Find all the XML files in this folder */
dir = opendir (path);
if (dir == NULL)
{
/* Not a critical error - but let someone know */
NOTICE ("ALFRED: No config files in \"%s\"", path);
return true;
}
/* Load all the mapping files */
for (entry = readdir (dir); entry; entry = readdir (dir))
{
const char *ext = strchr (entry->d_name, '.');
if (ext && strcmp (".map", ext) == 0)
{
/* Full path */
char *filename = g_strdup_printf ("%s%s%s", path,
path[strlen (path) - 1] == '/' ? "" : "/", entry->d_name);
DEBUG ("ALFRED: Parse MAP file \"%s\"\n", filename);
sch_load_namespace_mappings (alfred, filename);
g_free (filename);
}
}
rewinddir (dir);
lua_State *instance = alfred_new_instance ("xml-default", true);
/* Load all XML files */
for (entry = readdir (dir); entry; entry = readdir (dir))
{
const char *ext = strchr (entry->d_name, '.');
if (ext && ((strcmp (".xml", ext) == 0) || (strcmp (".xml.gz", ext) == 0)))
{
/* Full path */
char *filename = g_strdup_printf ("%s%s%s", path,
path[strlen (path) - 1] == '/' ? "" : "/", entry->d_name);
DEBUG ("ALFRED: Parse XML file \"%s\" into instance \"xml-default\"\n", filename);
/* Parse the file */
xmlDoc *doc = xmlParseFile (filename);
if (doc == NULL)
{
CRITICAL ("ALFRED: Invalid file \"%s\"\n", filename);
g_free (filename);
res = false;
goto exit;
}
res = process_node (alfred, instance, xmlDocGetRootElement (doc), NULL);
xmlFreeDoc (doc);
/* Stop processing files if there has been an error */
if (!res)
{
CRITICAL ("ALFRED: Failed to process \"%s\"\n", filename);
g_free (filename);
goto exit;
}
g_free (filename);
}
}
exit:
/* Set the LUA instance running... */
lua_apteryx_instance_unlock (instance);
closedir (dir);
return res;
}
static bool
load_script_files (alfred_instance alfred, const char *path)
{
struct dirent *entry;
DIR *dir;
bool res = true;
/* Mostly squashing a compiler warning - this is the default. */
if (path == NULL)
{
path = "/usr/share/alfred";
}
/* Find all the LUA files in this folder */
dir = opendir (path);
if (dir == NULL)
{
/* Not a critical error - but let someone know */
NOTICE ("ALFRED: No script files in \"%s\"", path);
return true;
}
/* Load and execute all LUA files */
for (entry = readdir (dir); entry; entry = readdir (dir))
{
const char *ext = strrchr (entry->d_name, '.');
if (ext && strcmp (".lua", ext) == 0)
{
char *filename = g_strdup_printf ("%s%s", path, entry->d_name);
int error;
lua_State *instance = alfred_new_instance (filename, false);
DEBUG ("ALFRED: Load Lua file \"%s\"\n", filename);
/* Execute the script */
lua_getglobal (instance, "debug");
lua_getfield (instance, -1, "traceback");
error = luaL_loadfile (instance, filename);
if (error == 0)
error = lua_pcall (instance, 0, 0, 0);
if (error != 0)
alfred_error (instance, error);
while (lua_gettop (instance))
lua_pop (instance, 1);
/* Set the LUA instance running... */
lua_apteryx_instance_unlock (instance);
/* Stop processing files if there has been an error */
if (error != 0)
{
CRITICAL ("ALFRED: Invalid file \"%s\"\n", filename);
res = false;
}
g_free (filename);
}
}
closedir (dir);
return res;
}
static pthread_mutex_t delayed_work_lock = PTHREAD_MUTEX_INITIALIZER;
GList *delayed_work = NULL;
struct delayed_work_s {
guint id;
int call;
char *script;
lua_State *instance;
};
static void
dw_destroy (gpointer arg1)
{
struct delayed_work_s *dw = (struct delayed_work_s *) arg1;
lua_apteryx_instance_lock (dw->instance);
luaL_unref (dw->instance, LUA_REGISTRYINDEX, dw->call);
lua_apteryx_instance_unlock (dw->instance);
dw->call = LUA_NOREF;
g_free (dw->script);
g_free (dw);
}
static gboolean
delayed_work_process (gpointer arg1)
{
struct delayed_work_s *dw = (struct delayed_work_s *) arg1;
/* Remove the script to be run */
pthread_mutex_lock (&delayed_work_lock);
delayed_work = g_list_remove (delayed_work, dw);
pthread_mutex_unlock (&delayed_work_lock);
if (lua_apteryx_instance_lock (dw->instance))
{
if (dw->script)
{
/* Execute the script */
alfred_exec (dw->instance, dw->script, 0);
}
else
{
lua_rawgeti (dw->instance, LUA_REGISTRYINDEX, dw->call);
alfred_call (dw->instance, 0);
lua_pop (dw->instance, 0);
}
lua_apteryx_instance_unlock (dw->instance);
}
else
{
DEBUG ("Delayed work executed after instance shutdown");
}
return false;
}
static void
delayed_work_add (lua_State *ls, bool reset_timer)
{
int call_args = 0;
bool found = false;
const char *script = NULL;
struct delayed_work_s *dw = NULL;
if (lua_isstring (ls, 2))
{
script = lua_tostring(ls, 2);
}
else /* lua_isfunction(ls, 2) */
{
call_args = lua_gettop (ls) - 1;
}
for (GList * iter = delayed_work; iter && !found; iter = g_list_next (iter))
{
dw = (struct delayed_work_s *) iter->data;
if (script)
{
found = dw->instance == ls && dw->script && strcmp (script, dw->script) == 0;
}
else if (lua_isfunction (ls, 2)
&& dw->instance == ls
&& dw->call != LUA_NOREF && dw->call != LUA_REFNIL)
{
size_t len;
bool call_same = true;
lua_rawgeti(ls, LUA_REGISTRYINDEX, dw->call);
/* Try to avoid comparing calls */
len = lua_rawlen(ls, -1);
if (((size_t)call_args) != len)
{
lua_pop(ls, 1);
continue;
}
for (size_t i = 0; call_same && i < call_args; i++)
{
lua_rawgeti(ls, -1, i + 1);
/* lua_compare has the usual meaning in lua, tables with
* the same keys and values will not be counted as the same,
* unless metamethods are changed.
*/
call_same = lua_compare(ls, i + 2, -1, LUA_OPEQ);
lua_pop(ls, 1);
}
found = call_same;
lua_pop(ls, 1);
}
if (found && reset_timer)
{
delayed_work = g_list_remove (delayed_work, dw);
/* When destroying the old delayed work object we access the
* lua_State under the lock, so it must be released here.
*/
lua_State *instance = dw->instance;
lua_apteryx_instance_unlock (instance);
g_source_remove (dw->id);
lua_apteryx_instance_lock (instance);
}
}
if (!found || reset_timer)
{
struct delayed_work_s *dw = (struct delayed_work_s *) g_malloc0 (sizeof (struct delayed_work_s));
dw->instance = ls;
if (script)
{
dw->script = g_strdup (script);
}
else
{
/* Transfer stack (past delay) into the argument table */
lua_newtable(ls);
lua_pushvalue(ls, 2);
lua_rawseti(ls, -2, 1);
lua_replace(ls, 2);
for (int i = lua_gettop (ls); i > 2; i--)
{
lua_rawseti(ls, 2, i - 1);
}
dw->call = luaL_ref(ls, LUA_REGISTRYINDEX);
}
delayed_work = g_list_append (delayed_work, dw);
dw->id = g_timeout_add_full (G_PRIORITY_DEFAULT,
lua_tonumber (ls, 1) * SECONDS_TO_MILLI,
delayed_work_process, (gpointer) dw, dw_destroy);
}
}
static int
validate_script_or_function_args (lua_State *ls, const char *funct)
{
bool success = true;
if (!lua_isnumber (ls, 1))
{
ERROR ("First argument to %s must be a number\n", funct);
success = false;
}
if (lua_isstring (ls, 2))
{
if (lua_gettop (ls) != 2)
{
ERROR ("%s takes 2 arguements\n", funct);
success = false;
}
}
else if (!lua_isfunction (ls, 2))
{
ERROR ("Second argument to %s must be a string or Lua function\n", funct);
success = false;
}
return success;
}
static int
rate_limit (lua_State *ls)
{
if (validate_script_or_function_args (ls, "Alfred.rate_limit()"))
{
pthread_mutex_lock (&delayed_work_lock);
delayed_work_add (ls, false);
pthread_mutex_unlock (&delayed_work_lock);
}
return 0;
}
static int
after_quiet (lua_State *ls)
{
if (validate_script_or_function_args (ls, "Alfred.after_quiet()"))
{