aboutsummaryrefslogtreecommitdiffstats
path: root/src/afb-apiset.c
blob: b4a57ee64c8278025d832b88cc7d070ec9ad5ca0 (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
/*
 * Copyright (C) 2015-2020 "IoT.bzh"
 * Author José Bollo <jose.bollo@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _GNU_SOURCE

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>

#include "verbose.h"
#include "afb-api.h"
#include "afb-apiset.h"
#include "afb-context.h"
#include "afb-xreq.h"
#include "jobs.h"

#define INCR		8	/* CAUTION: must be a power of 2 */
#define NOT_STARTED	-1

struct afb_apiset;
struct api_desc;
struct api_class;
struct api_alias;
struct api_depend;

/**
 * array of items
 */
struct api_array {
	int count;			/* count of items */
	union {
		void **anys;
		struct api_desc **apis;
		struct api_class **classes;
		struct api_alias **aliases;
		struct api_depend **depends;
	};
};

/**
 * Internal description of an api
 */
struct api_desc
{
	struct api_desc *next;
	const char *name;		/**< name of the api */
	int status;			/**< initialisation status:
						- NOT_STARTED not started,
						- 0 started without error,
						- greater than 0, error number of start */
	struct afb_api_item api;	/**< handler of the api */
	struct {
		struct api_array classes;
		struct api_array apis;
	} require;
};

/**
 * internal description of aliases
 */
struct api_alias
{
	struct api_alias *next;
	struct api_desc *api;
	char name[];
};

/**
 *
 */
struct api_class
{
	struct api_class *next;
	struct api_array providers;
	char name[];
};

/**
 *
 */
struct api_depend
{
	struct afb_apiset *set;
	char name[];
};

/**
 * Data structure for apiset
 */
struct afb_apiset
{
	struct api_array apis;		/**< the apis */
	struct api_alias *aliases;	/**< the aliases */
	struct afb_apiset *subset;	/**< subset if any */
	struct {
		int (*callback)(void*, struct afb_apiset*, const char*); /* not found handler */
		void *closure;
		void (*cleanup)(void*);
	} onlack;			/** not found handler */
	int timeout;			/**< the timeout in second for the apiset */
	int refcount;			/**< reference count for freeing resources */
	char name[];			/**< name of the apiset */
};

/**
 * global apis
 */
static struct api_desc *all_apis;

/**
 * global classes
 */
static struct api_class *all_classes;

/**
 * Ensure enough room in 'array' for 'count' items
 */
static int api_array_ensure_count(struct api_array *array, int count)
{
	int c;
	void **anys;

	c = (count + INCR - 1) & ~(INCR - 1);
	anys = realloc(array->anys, c * sizeof *anys);
	if (!anys) {
		errno = ENOMEM;
		return -1;
	}

	array->count = count;
	array->anys = anys;
	return 0;
}

/**
 * Insert in 'array' the item 'any' at the 'index'
 */
static int api_array_insert(struct api_array *array, void *any, int index)
{
	int n = array->count;

	if (api_array_ensure_count(array, n + 1) < 0)
		return -1;

	while (index < n) {
		array->anys[n] = array->anys[n - 1];
		n--;
	}

	array->anys[index] = any;
	return 0;
}

/**
 * Add the item 'any' to the 'array'
 */
static int api_array_add(struct api_array *array, void *any)
{
	int i, n = array->count;

	for (i = 0 ; i < n ; i++) {
		if (array->anys[i] == any)
			return 0;
	}

	if (api_array_ensure_count(array, n + 1) < 0)
		return -1;

	array->anys[n] = any;
	return 0;
}

/**
 * Delete the 'api' from the 'array'
 * Returns 1 if delete or 0 if not found
 */
static int api_array_del(struct api_array *array, void *any)
{
	int i = array->count;
	while (i) {
		if (array->anys[--i] == any) {
			array->anys[i] = array->anys[--array->count];
			return 1;
		}
	}
	return 0;
}

/**
 * Search the class of 'name' and return it.
 * In case where the class of 'namle' isn't found, it returns
 * NULL when 'create' is null or a fresh created instance if 'create' isn't
 * zero (but NULL on allocation failure).
 */
static struct api_class *class_search(const char *name, int create)
{
	struct api_class *c;

	for (c= all_classes ; c ; c = c->next) {
		if (!strcasecmp(name, c->name))
			return c;
	}

	if (!create)
		return NULL;

	c = calloc(1, strlen(name) + 1 + sizeof *c);
	if (!c)
		errno = ENOMEM;
	else {
		strcpy(c->name, name);
		c->next = all_classes;
		all_classes = c;
	}
	return c;
}

/**
 * Search the api of 'name'.
 * @param set the api set
 * @param name the api name to search
 * @return the descriptor if found or NULL otherwise
 */
static struct api_desc *search(struct afb_apiset *set, const char *name)
{
	int i, c, up, lo;
	struct api_desc *a;
	struct api_alias *aliases;

	/* dichotomic search of the api */
	/* initial slice */
	lo = 0;
	up = set->apis.count;
	while (lo < up) {
		/* check the mid of the slice */
		i = (lo + up) >> 1;
		a = set->apis.apis[i];
		c = strcasecmp(a->name, name);
		if (c == 0) {
			/* found */
			return a;
		}
		/* update the slice */
		if (c < 0)
			lo = i + 1;
		else
			up = i;
	}

	/* linear search of aliases */
	aliases = set->aliases;
	for(;;) {
		if (!aliases)
			break;
		c = strcasecmp(aliases->name, name);
		if (!c)
			return aliases->api;
		if (c > 0)
			break;
		aliases = aliases->next;
	}
	return NULL;
}

/**
 * Search the api of 'name' in the apiset and in its subsets.
 * @param set the api set
 * @param name the api name to search
 * @return the descriptor if found or NULL otherwise
 */
static struct api_desc *searchrec(struct afb_apiset *set, const char *name)
{
	struct api_desc *result;

	do {
		result = search(set, name);
	} while (result == NULL && (set = set->subset) != NULL);

	return result;
}

/**
 * Increases the count of references to the apiset and return its address
 * @param set the set whose reference count is to be increased
 * @return the given apiset
 */
struct afb_apiset *afb_apiset_addref(struct afb_apiset *set)
{
	if (set)
		__atomic_add_fetch(&set->refcount, 1, __ATOMIC_RELAXED);
	return set;
}

/**
 * Decreases the count of references to the apiset and frees its
 * resources when no more references exists.
 * @param set the set to unrefrence
 */
void afb_apiset_unref(struct afb_apiset *set)
{
	struct api_alias *a;
	struct api_desc *d;

	if (set && !__atomic_sub_fetch(&set->refcount, 1, __ATOMIC_RELAXED)) {
		afb_apiset_unref(set->subset);
		if (set->onlack.cleanup)
			set->onlack.cleanup(set->onlack.closure);
		while((a = set->aliases)) {
			set->aliases = a->next;
			free(a);
		}
		while (set->apis.count) {
			d = set->apis.apis[--set->apis.count];
			if (d->api.itf->unref)
				d->api.itf->unref(d->api.closure);
			free(d);
		}
		free(set->apis.apis);
		free(set);
	}
}

/**
 * Create an apiset
 * @param name the name of the apiset
 * @param timeout the default timeout in seconds for the apiset
 * @return the created apiset or NULL in case of error
 */
struct afb_apiset *afb_apiset_create(const char *name, int timeout)
{
	struct afb_apiset *set;

	set = calloc(1, (name ? strlen(name) : 0) + 1 + sizeof *set);
	if (set) {
		set->timeout = timeout;
		set->refcount = 1;
		if (name)
			strcpy(set->name, name);
	}
	return set;
}

/**
 * Create an apiset being the last subset of 'set'
 * @param set     the set to extend with the created subset (can be NULL)
 * @param name    the name of the created apiset (can be NULL)
 * @param timeout the default timeout in seconds for the created apiset
 * @return the created apiset or NULL in case of error
 */
struct afb_apiset *afb_apiset_create_subset_last(struct afb_apiset *set, const char *name, int timeout)
{
	if (set)
		while (set->subset)
			set = set->subset;
	return afb_apiset_create_subset_first(set, name, timeout);
}

/**
 * Create an apiset being the first subset of 'set'
 * @param set     the set to extend with the created subset (can be NULL)
 * @param name    the name of the created apiset (can be NULL)
 * @param timeout the default timeout in seconds for the created apiset
 * @return the created apiset or NULL in case of error
 */
struct afb_apiset *afb_apiset_create_subset_first(struct afb_apiset *set, const char *name, int timeout)
{
	struct afb_apiset *result = afb_apiset_create(name, timeout);
	if (result && set) {
		result->subset = set->subset;
		set->subset = result;
	}
	return result;
}

/**
 * the name of the apiset
 * @param set the api set
 * @return the name of the set
 */
const char *afb_apiset_name(struct afb_apiset *set)
{
	return set->name;
}

/**
 * Get the API timeout of the set
 * @param set the api set
 * @return the timeout in seconds
 */
int afb_apiset_timeout_get(struct afb_apiset *set)
{
	return set->timeout;
}

/**
 * Set the API timeout of the set
 * @param set the api set
 * @param to the timeout in seconds
 */
void afb_apiset_timeout_set(struct afb_apiset *set, int to)
{
	set->timeout = to;
}

/**
 * Get the subset of the set
 * @param set the api set
 * @return the subset of set
 */
struct afb_apiset *afb_apiset_subset_get(struct afb_apiset *set)
{
	return set->subset;
}

/**
 * Set the subset of the set
 * @param set the api set
 * @param subset the subset to set
 *
 * @return 0 in case of success or -1 if it had created a loop
 */
int afb_apiset_subset_set(struct afb_apiset *set, struct afb_apiset *subset)
{
	struct afb_apiset *tmp;

	/* avoid infinite loop */
	for (tmp = subset ; tmp ; tmp = tmp->subset)
		if (tmp == set)
			return -1;

	tmp = set->subset;
	set->subset = afb_apiset_addref(subset);
	afb_apiset_unref(tmp);

	return 0;
}

void afb_apiset_onlack_set(struct afb_apiset *set, int (*callback)(void*, struct afb_apiset*, const char*), void *closure, void (*cleanup)(void*))
{
	if (set->onlack.cleanup)
		set->onlack.cleanup(set->onlack.closure);
	set->onlack.callback = callback;
	set->onlack.closure = closure;
	set->onlack.cleanup = cleanup;
}

/**
 * Adds the api of 'name' described by 'api'.
 * @param set the api set
 * @param name the name of the api to add (have to survive, not copied!)
 * @param api the api
 * @returns 0 in case of success or -1 in case
 * of error with errno set:
 *   - EEXIST if name already registered
 *   - ENOMEM when out of memory
 */
int afb_apiset_add(struct afb_apiset *set, const char *name, struct afb_api_item api)
{
	struct api_desc *desc;
	int i, c;

	/* check whether it exists already */
	if (search(set, name)) {
		ERROR("api of name %s already exists", name);
		errno = EEXIST;
		goto error;
	}

	/* search insertion place */
	for (i = 0 ; i < set->apis.count ; i++) {
		c = strcasecmp(set->apis.apis[i]->name, name);
		if (c > 0)
			break;
	}

	/* allocates memory */
	desc = calloc(1, sizeof *desc);
	if (!desc)
		goto oom;

	desc->status = NOT_STARTED;
	desc->api = api;
	desc->name = name;

	if (api_array_insert(&set->apis, desc, i) < 0) {
		free(desc);
		goto error;
	}

	desc->next = all_apis;
	all_apis = desc;

	if (afb_api_is_public(name))
		INFO("API %s added", name);

	return 0;

oom:
	ERROR("out of memory");
	errno = ENOMEM;
error:
	return -1;
}

/**
 * Adds a the 'alias' name to the api of 'name'.
 * @params set the api set
 * @param name the name of the api to alias
 * @param alias the aliased name to add to the api of name
 * @returns 0 in case of success or -1 in case
 * of error with errno set:
 *   - ENOENT if the api doesn't exist
 *   - EEXIST if name (of alias) already registered
 *   - ENOMEM when out of memory
 */
int afb_apiset_add_alias(struct afb_apiset *set, const char *name, const char *alias)
{
	struct api_desc *api;
	struct api_alias *ali, **pali;

	/* check alias doesn't already exist */
	if (search(set, alias)) {
		ERROR("api of name %s already exists", alias);
		errno = EEXIST;
		goto error;
	}

	/* check aliased api exists */
	api = search(set, name);
	if (api == NULL) {
		ERROR("api of name %s doesn't exists", name);
		errno = ENOENT;
		goto error;
	}

	/* allocates and init the struct */
	ali = malloc(sizeof *ali + strlen(alias) + 1);
	if (ali == NULL) {
		ERROR("out of memory");
		errno = ENOMEM;
		goto error;
	}
	ali->api = api;
	strcpy(ali->name, alias);

	/* insert the alias in the sorted order */
	pali = &set->aliases;
	while(*pali && strcmp((*pali)->name, alias) < 0)
		pali = &(*pali)->next;
	ali->next = *pali;
	*pali = ali;
	return 0;
error:
	return -1;
}

int afb_apiset_is_alias(struct afb_apiset *set, const char *name)
{
	struct api_desc *api = searchrec(set, name);
	return api && strcasecmp(api->name, name);
}

const char *afb_apiset_unalias(struct afb_apiset *set, const char *name)
{
	struct api_desc *api = searchrec(set, name);
	return api ? api->name : NULL;
}

/**
 * Delete from the 'set' the api of 'name'.
 * @param set the set to be changed
 * @param name the name of the API to remove
 * @return 0 in case of success or -1 in case where the API doesn't exist.
 */
int afb_apiset_del(struct afb_apiset *set, const char *name)
{
	struct api_class *cla;
	struct api_alias *ali, **pali;
	struct api_desc *desc, **pdesc, *odesc;
	int i, c;

	/* search the alias */
	pali = &set->aliases;
	while ((ali = *pali)) {
		c = strcasecmp(ali->name, name);
		if (!c) {
			*pali = ali->next;
			free(ali);
			return 0;
		}
		if (c > 0)
			break;
		pali = &ali->next;
	}

	/* search the api */
	for (i = 0 ; i < set->apis.count ; i++) {
		desc = set->apis.apis[i];
		c = strcasecmp(desc->name, name);
		if (c == 0) {
			/* remove from classes */
			for (cla = all_classes ; cla ; cla = cla->next)
				api_array_del(&cla->providers, desc);

			/* unlink from the whole set and their requires */
			pdesc = &all_apis;
			while ((odesc = *pdesc) != desc) {
				pdesc = &odesc->next;
			}
			*pdesc = odesc = desc->next;
			while (odesc) {
				odesc = odesc->next;
			}

			/* remove references from classes */
			free(desc->require.classes.classes);

			/* drop the aliases */
			pali = &set->aliases;
			while ((ali = *pali)) {
				if (ali->api != desc)
					pali = &ali->next;
				else {
					*pali = ali->next;
					free(ali);
				}
			}

			/* unref the api */
			if (desc->api.itf->unref)
				desc->api.itf->unref(desc->api.closure);

			set->apis.count--;
			while(i < set->apis.count) {
				set->apis.apis[i] = set->apis.apis[i + 1];
				i++;
			}
			free(desc);
			return 0;
		}
		if (c > 0)
			break;
	}
	errno = ENOENT;
	return -1;
}

/**
 * Get from the 'set' the API of 'name' in 'api' with fallback to subset or default api
 * @param set the set of API
 * @param name the name of the API to get
 * @param rec if not zero look also recursively in subsets
 * @return the api pointer in case of success or NULL in case of error
 */
static struct api_desc *lookup(struct afb_apiset *set, const char *name, int rec)
{
	struct api_desc *result;

	result = search(set, name);
	while (!result) {
		/* lacking the api, try onlack behaviour */
		if (set->onlack.callback && set->onlack.callback(set->onlack.closure, set, name) > 0) {
			result = search(set, name);
			if (result)
				break;
		}
		if (!rec || !(set = set->subset))
			break;
		result = search(set, name);
	}
	return result;
}

/**
 * Get from the 'set' the API of 'name' in 'api'
 * @param set the set of API
 * @param name the name of the API to get
 * @param rec if not zero look also recursively in subsets
 * @return the api pointer in case of success or NULL in case of error
 */
const struct afb_api_item *afb_apiset_lookup(struct afb_apiset *set, const char *name, int rec)
{
	struct api_desc *i;

	i = lookup(set, name, rec);
	if (i)
		return &i->api;
	errno = ENOENT;
	return NULL;
}

static int start_api(struct api_desc *api);

/**
 * Start the apis of the 'array'
 */
static int start_array_apis(struct api_array *array)
{
	int i, rc = 0, rc2;

	i = 0;
	while (i < array->count) {
		rc2 = array->apis[i]->status;
		if (rc2 == NOT_STARTED) {
			rc2 = start_api(array->apis[i]);
			if (rc2 < 0)
				rc = rc2;
			i = 0;
		} else {
			if (rc2)
				rc = -1;
			i++;
		}
	}
	return rc;
}

/**
 * Start the class 'cla' (start the apis that provide it).
 */
static int start_class(struct api_class *cla)
{
	return start_array_apis(&cla->providers);
}

/**
 * Start the classes of the 'array'
 */
static int start_array_classes(struct api_array *array)
{
	int i, rc = 0, rc2;

	i = array->count;
	while (i) {
		rc2 = start_class(array->classes[--i]);
		if (rc2 < 0) {
			rc = rc2;
		}
	}
	return rc;
}

/**
 * Start the depends of the 'array'
 */
static int start_array_depends(struct api_array *array)
{
	struct api_desc *api;
	int i, rc = 0, rc2;

	i = 0;
	while (i < array->count) {
		api = searchrec(array->depends[i]->set, array->depends[i]->name);
		if (!api) {
			rc = -1;
			i++;
		} else {
			rc2 = api->status;
			if (rc2 == NOT_STARTED) {
				rc2 = start_api(api);
				if (rc2 < 0)
					rc = rc2;
				i = 0;
			} else {
				if (rc2)
					rc = -1;
				i++;
			}
		}
	}

	return rc;
}

/**
 * Starts the service 'api'.
 * @param api the api
 * @return zero on success, -1 on error
 */
static int start_api(struct api_desc *api)
{
	int rc;

	if (api->status != NOT_STARTED) {
		if (api->status > 0) {
			errno = api->status;
			return -1;
		}
		return 0;
	}

	NOTICE("API %s starting...", api->name);
	api->status = EBUSY;
	rc = start_array_classes(&api->require.classes);
	if (rc < 0)
		ERROR("Cannot start classes needed by api %s", api->name);
	else {
		rc = start_array_depends(&api->require.apis);
		if (rc < 0)
			ERROR("Cannot start apis needed by api %s", api->name);
		else if (api->api.itf->service_start) {
			rc = api->api.itf->service_start(api->api.closure);
			if (rc < 0)
				ERROR("The api %s failed to start", api->name);
		}
	}
	if (rc < 0) {
		api->status = errno ?: ECANCELED;
		return -1;
	}
	INFO("API %s started", api->name);
	api->status = 0;
	return 0;
}

/**
 * Get from the 'set' the API of 'name' in 'api'
 * @param set the set of API
 * @param name the name of the API to get
 * @param rec if not zero look also recursively in subsets
 * @return a pointer to the API item in case of success or NULL in case of error
 */
const struct afb_api_item *afb_apiset_lookup_started(struct afb_apiset *set, const char *name, int rec)
{
	struct api_desc *desc;

	desc = lookup(set, name, rec);
	if (!desc) {
		errno = ENOENT;
		return NULL;
	}
	if (start_api(desc)) {
		errno = desc->status;
		return NULL;
	}
	return &desc->api;
}

/**
 * Starts a service by its 'api' name.
 * @param set the api set
 * @param name name of the service to start
 * @return zero on success, -1 on error
 */
int afb_apiset_start_service(struct afb_apiset *set, const char *name)
{
	struct api_desc *a;

	a = searchrec(set, name);
	if (!a) {
		ERROR("can't find service %s", name);
		errno = ENOENT;
		return -1;
	}

	return start_api(a);
}

/**
 * Starts all possible services but stops at first error.
 * @param set the api set
 * @return 0 on success or a negative number when an error is found
 */
int afb_apiset_start_all_services(struct afb_apiset *set)
{
	struct afb_apiset *rootset;
	int rc, ret;
	int i;

	rootset = set;
	ret = 0;
	while (set) {
		i = 0;
		while (i < set->apis.count) {
			rc = set->apis.apis[i]->status;
			if (rc == NOT_STARTED) {
				rc = start_api(set->apis.apis[i]);
				if (rc < 0)
					ret = rc;
				set = rootset;
				i = 0;
			} else {
				if (rc)
					ret = -1;
				i++;
			}
		}
		set = set->subset;
	}
	return ret;
}

#if WITH_AFB_HOOK
/**
 * Ask to update the hook flags of the 'api'
 * @param set the api set
 * @param name the api to update (NULL updates all)
 */
void afb_apiset_update_hooks(struct afb_apiset *set, const char *name)
{
	struct api_desc **i, **e, *d;

	if (!name) {
		i = set->apis.apis;
		e = &set->apis.apis[set->apis.count];
		while (i != e) {
			d = *i++;
			if (d->api.itf->update_hooks)
				d->api.itf->update_hooks(d->api.closure);
		}
	} else {
		d = searchrec(set, name);
		if (d && d->api.itf->update_hooks)
			d->api.itf->update_hooks(d->api.closure);
	}
}
#endif

/**
 * Set the logmask of the 'api' to 'mask'
 * @param set the api set
 * @param name the api to set (NULL set all)
 */
void afb_apiset_set_logmask(struct afb_apiset *set, const char *name, int mask)
{
	int i;
	struct api_desc *d;

	if (!name) {
		for (i = 0 ; i < set->apis.count ; i++) {
			d = set->apis.apis[i];;
			if (d->api.itf->set_logmask)
				d->api.itf->set_logmask(d->api.closure, mask);
		}
	} else {
		d = searchrec(set, name);
		if (d && d->api.itf->set_logmask)
			d->api.itf->set_logmask(d->api.closure, mask);
	}
}

/**
 * Get the logmask level of the 'api'
 * @param set the api set
 * @param name the api to get
 * @return the logmask level or -1 in case of error
 */
int afb_apiset_get_logmask(struct afb_apiset *set, const char *name)
{
	const struct api_desc *i;

	i = name ? searchrec(set, name) : NULL;
	if (!i) {
		errno = ENOENT;
		return -1;
	}

	if (!i->api.itf->get_logmask)
		return logmask;

	return i->api.itf->get_logmask(i->api.closure);
}

void afb_apiset_describe(struct afb_apiset *set, const char *name, void (*describecb)(void *, struct json_object *), void *closure)
{
	const struct api_desc *i;
	struct json_object *r;

	r = NULL;
	if (name) {
		i = searchrec(set, name);
		if (i) {
			if (i->api.itf->describe) {
				i->api.itf->describe(i->api.closure, describecb, closure);
				return;
			}
		}
	}
	describecb(closure, r);
}


struct get_names {
	union  {
		struct {
			size_t count;
			size_t size;
		};
		struct {
			const char **ptr;
			char *data;
		};
	};
	int type;
};

static void get_names_count(void *closure, struct afb_apiset *set, const char *name, int isalias)
{
	struct get_names *gc = closure;
	if ((1 + isalias) & gc->type) {
		gc->size += strlen(name);
		gc->count++;
	}
}

static void get_names_value(void *closure, struct afb_apiset *set, const char *name, int isalias)
{
	struct get_names *gc = closure;
	if ((1 + isalias) & gc->type) {
		*gc->ptr++ = gc->data;
		gc->data = stpcpy(gc->data, name) + 1;
	}
}

#if !defined(APISET_NO_SORT)
static int get_names_sortcb(const void *a, const void *b)
{
	return strcasecmp(*(const char **)a, *(const char **)b);
}
#endif

/**
 * Get the list of api names
 * @param set the api set
 * @param rec recursive
 * @param type expected type: 1 names, 3 names+aliases, 2 aliases
 * @return a NULL terminated array of api names. Must be freed.
 */
const char **afb_apiset_get_names(struct afb_apiset *set, int rec, int type)
{
	struct get_names gc;
	size_t size;
	const char **names;

	gc.count = gc.size = 0;
	gc.type = type >= 1 && type <= 3 ? type : 1;
	afb_apiset_enum(set, rec, get_names_count, &gc);

	size = gc.size + gc.count * (1 + sizeof *names) + sizeof(*names);
	names = malloc(size);

	if (!names)
		errno = ENOMEM;
	else {
		gc.data = (char*)&names[gc.count + 1];
		gc.ptr = names;
		afb_apiset_enum(set, rec, get_names_value, &gc);
#if !defined(APISET_NO_SORT)
		qsort(names, gc.ptr - names, sizeof *names, get_names_sortcb);
#endif
		*gc.ptr = NULL;
	}
	return names;
}

/**
 * Enumerate the api names to a callback.
 * @param set the api set
 * @param rec should the enumeration be recursive
 * @param callback the function to call for each name
 * @param closure the closure for the callback
 */
void afb_apiset_enum(
	struct afb_apiset *set,
	int rec,
	void (*callback)(void *closure, struct afb_apiset *set, const char *name, int isalias),
	void *closure)
{
	int i;
	struct afb_apiset *iset;
	struct api_desc *d;
	struct api_alias *a;

	iset = set;
	while (iset) {
		for (i = 0 ; i < set->apis.count ; i++) {
			d = set->apis.apis[i];;
			if (searchrec(set, d->name) == d)
				callback(closure, iset, d->name, 0);
		}
		a = iset->aliases;
		while (a) {
			if (searchrec(set, a->name) == a->api)
				callback(closure, iset, a->name, 1);
			a = a->next;
		}
		iset = rec ? iset->subset : NULL;
	}
}

/**
 * Declare that the api of 'name' requires the api of name 'required'.
 * The api is searched in the apiset 'set' and if 'rec' isn't null also in its subset.
 * Returns 0 if the declaration successed or -1 in case of failure
 * (ENOMEM: allocation failure, ENOENT: api name not found)
 */
int afb_apiset_require(struct afb_apiset *set, const char *name, const char *required)
{
	struct api_desc *a;
	struct api_depend *d;
	int rc = -1;

	a = searchrec(set, name);
	if (!a)
		errno = ENOENT;
	else {
		d = malloc(strlen(required) + 1 + sizeof *d);
		if (!d)
			errno = ENOMEM;
		else {
			d->set = set;
			strcpy(d->name, required);
			rc = api_array_add(&a->require.apis, d);
		}
	}
	return rc;
}

/**
 * Declare that the api of name 'apiname' requires the class of name 'classname'.
 * Returns 0 if the declaration successed or -1 in case of failure
 * (ENOMEM: allocation failure, ENOENT: api name not found)
 */
int afb_apiset_require_class(struct afb_apiset *set, const char *apiname, const char *classname)
{
	struct api_desc *a = searchrec(set, apiname);
	struct api_class *c = class_search(classname, 1);
	return a && c ? api_array_add(&a->require.classes, c) : (errno = ENOENT, -1);
}

/**
 * Declare that the api of name 'apiname' provides the class of name 'classname'
 * Returns 0 if the declaration successed or -1 in case of failure
 * (ENOMEM: allocation failure, ENOENT: api name not found)
 */
int afb_apiset_provide_class(struct afb_apiset *set, const char *apiname, const char *classname)
{
	struct api_desc *a = searchrec(set, apiname);
	struct api_class *c = class_search(classname, 1);
	return a && c ? api_array_add(&c->providers, a) : (errno = ENOENT, -1);
}

/**
 * Start any API that provides the class of name 'classname'
 */
int afb_apiset_class_start(const char *classname)
{
	struct api_class *cla = class_search(classname, 0);
	return cla ? start_class(cla) : (errno = ENOENT, -1);
}