aboutsummaryrefslogtreecommitdiff
path: root/daemon/ip/cfg.c
blob: 26a7dd562e27f8360ed2d6dffc775c2e6cb81cc7 (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
/* ****************************************************************************
 * ip/cfg.c -- gestion de la configuration par FTP des serveurs WES.
 * Copyright (C) 2018 Thomas Touhey <thomas@touhey.fr>
 *
 * This project is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software. You can use,
 * modify and/or redistribute the software under the terms of the
 * CeCILL license as circulated by CEA, CNRS and INRIA at the
 * following URL: "http://www.cecill.info".
 *
 * As a counterpart to the access to the source code and rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty and the project's author, the holder of the
 * economic rights, and the successive licensors have only limited liability.
 *
 * In this respect, the user's attention is drawn to the risks associated
 * with loading, using, modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean that it is complicated to manipulate, and that also therefore
 * means that it is reserved for developers and experienced professionals
 * having in-depth computer knowledge. Users are therefore encouraged to load
 * and test the software's suitability as regards their requirements in
 * conditions enabling the security of their systems and/or data to be
 * ensured and, more generally, to use and operate it in the same conditions
 * as regards security.
 *
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
 * ************************************************************************* */
#include "internals.h"
#define SECSIZE 10
#define KEYSIZE 50
#define VALSIZE 100

#define DEFAULTSECTION "RESEAU"

#define validkeycar(CAR) (isalnum(CAR))
#define validvalcar(CAR) (isalnum(CAR) || strchr(".- ", (CAR)))

/* ---
 * Utilitaires.
 * --- */

/* `get_request()`: Préparation d'une requête, avec URL et identifiants. */

static int get_request(wes_t *wes, CURL **handlep, const char *section)
{
	char path[10 + SECSIZE];

	sprintf(path, "/CFG/%s.CFG", section);
	return (open_ftp_handle(wes, handlep, path));
}

/* `normalize_section()`: Normalisation du nom de section. */

static int normalize_section(char *buf, const char *src)
{
	int left, car;

	for (left = SECSIZE; left && *src; src++) {
		car = *src;
		if (car == '.')
			break;
		if (!isalnum(car))
			continue;

		left--;
		*buf++ = (char)car;
		if (!left)
			break;
	}
	*buf = 0;

	/* Si la forme normalisée est vide, on utilise la section par
	 * défaut, ici « RESEAU ». */

	if (left == SECSIZE)
		memcpy(buf, DEFAULTSECTION, sizeof(DEFAULTSECTION));

	return (WROK);
}

/* `normalize_key()`: Normalisation du nom de clé. */

static int normalize_key(char *buf, const char *src)
{
	int left, car;

	for (left = KEYSIZE; left && *src; src++) {
		car = *src;
		if (!validkeycar(car))
			continue;

		left--;
		*buf++ = (char)car;
		if (!left)
			break;
	}
	*buf = 0;

	if (left == KEYSIZE)
		return (WROP);
	return (WROK);
}

/* `normalize_value()`: Normalisation de la valeur. */

static int normalize_value(char *buf, const char *src)
{
	int left, car;

	for (left = VALSIZE; left && *src; src++) {
		car = *src;
		if (!validvalcar(car))
			continue;

		left--;
		*buf++ = (char)car;
		if (!left)
			break;
	}
	*buf = 0;

	return (WROK);
}

/* `emptysection()`: Vider une section de configuration. */

static int emptysection(wescfgsec_t *sec)
{
	wescfg_t *cfg;

	while ((cfg = sec->child)) {
		sec->child = cfg->next;
		free(cfg);
	}

	return (WROK);
}

/* `setsectionkeyval()`: Définition de la valeur pour une clé de la
 * section. */

static int setsectionkeyval(wescfgsec_t *sec, const char *key, const char *val)
{
	wescfg_t **cfgp, *cfg;
	const char *temp;
	size_t keysz, valsz;

	temp = memchr(key, 0, KEYSIZE);
	keysz = temp ? (size_t)(temp - key) : KEYSIZE;
	temp = memchr(val, 0, VALSIZE);
	valsz = temp ? (size_t)(temp - val) : VALSIZE;

	cfgp = &sec->child;
	for (cfgp = &sec->child; (cfg = *cfgp); cfgp = &cfg->next) {
		if (cfg->keysz == keysz && !memcmp(cfg->data, key, keysz)) {
			if (cfg->valsz == valsz && !memcmp(&cfg->data[keysz], val, valsz))
				return (WROK);

			*cfgp = cfg->next;
			free(cfg);
			break;
		}
	}

	cfg = malloc(sizeof(wescfg_t) + keysz + valsz);
	if (!cfg)
		return (WRALLOC);
	cfg->next = *cfgp;
	*cfgp = cfg;
	cfg->keysz = keysz;
	cfg->valsz = valsz;
	memcpy(cfg->data, key, keysz);
	memcpy(&cfg->data[keysz], val, valsz);

	return (WROK);
}

/* ---
 * Lecture de section (récupération d'un fichier via FTP).
 * --- */

#define SG_KEY  0 /* clé */
#define SG_VAL  1 /* valeur */

struct getcookie {
	wescfgsec_t *sec;
	int err;
	int step, off, hadval;
	char keybuf[KEYSIZE + 1];
	char valbuf[VALSIZE + 1];
};

/* `getsection_callback()`: Callback de la fonction de récupération de
 * section. */

static size_t getsection_callback(char *buffer, size_t size, size_t nmemb,
	struct getcookie *cookie)
{
	int car, save, err;
	size_t memb_size = size, orig_size;

	if (cookie->err != WROK)
		return (0);

	size = size * nmemb;
	orig_size = size;
	for (; size; size--) {
		car = *buffer++;

		save = 0;
		switch (cookie->step) {
		case SG_KEY:
			switch (car) {
			case '=':
				cookie->keybuf[cookie->off] = 0;
				cookie->off = 0;
				cookie->step = SG_VAL;
				cookie->hadval = 1;
				break;
			case '\n':
				cookie->keybuf[cookie->off] = '\0';
				cookie->valbuf[0] = '\0';
				save = 1;
				break;
			default:
				if (isalnum(car) && cookie->off < KEYSIZE)
					cookie->keybuf[cookie->off++] = (char)car;
				break;
			}
			break;
		case SG_VAL:
			switch (car) {
			case '\n':
				cookie->valbuf[cookie->off] = '\0';
				save = 1;
				break;
			default:
				if (validvalcar(car) && cookie->off < VALSIZE)
					cookie->valbuf[cookie->off++] = (char)car;
				break;
			}
			break;
		}

		if (save) {
			/* On vérifie si :
			 * - il y a eu un '=' (`hadval == 1`) ;
			 * - la clé et la valeur sont non vides. */

			if (cookie->hadval && cookie->keybuf[0] && cookie->valbuf[0]) {
				if ((err = setsectionkeyval(cookie->sec, cookie->keybuf,
					cookie->valbuf))) {
					cookie->err = err;
					return ((orig_size - size) / memb_size);
				}
			}

			/* Dans tous les cas, on passe au prochain élément de
			 * configuration. */

			cookie->step = SG_KEY;
			cookie->off = 0;
			cookie->hadval = 0;
		}
	}

	return (nmemb);
}

/* `gathersection()`: Récupération d'une section de configuration. */

static int gathersection(wes_t *wes, wescfgsec_t *sec)
{
	struct getcookie cookie;
	CURL *curl; CURLcode cres;
	const char *section;
	int err;

	section = sec->data;

	/* On vide la section actuelle. */

	emptysection(sec);

	/* On initialise la requête. */

	if ((err = get_request(wes, &curl, section)))
		return (err);

	cookie.sec = sec;
	cookie.step = SG_KEY;
	cookie.off = 0;
	cookie.hadval = 0;
	cookie.err = WROK;

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getsection_callback);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &cookie);

	cres = curl_easy_perform(curl);

	if (cres != CURLE_OK) {
		emptysection(sec);

		switch (cres) {
		case CURLE_OK:
			/* Tout s'est bien passé. */
			break;

		case CURLE_READ_ERROR:
		case CURLE_WRITE_ERROR:
			/* Le callback d'écriture a fait s'arrêter le transfert. */

			return (cookie.err);

		case CURLE_OUT_OF_MEMORY:
			/* Une allocation a échoué. */

			return (WRALLOC);

		case CURLE_COULDNT_RESOLVE_HOST: /* FALLTHRU */
		case CURLE_COULDNT_CONNECT: /* FALLTHRU */
		case CURLE_FTP_CANT_GET_HOST: /* FALLTHRU */
		case CURLE_SEND_ERROR: /* FALLTHRU */
		case CURLE_RECV_ERROR:
			/* Quelque chose s'est mal passé sur la transmission. */

			return (WRNOHOST);

		case CURLE_REMOTE_FILE_NOT_FOUND:
			/* Le fichier n'existe pas.
			 * FIXME: Crée-t-on la configuration par défaut ? */

			return (WRUNKNOWN);

		default:
			return (WRUNKNOWN);
		}
	}

	return (WROK);
}

/* ---
 * Écriture de section (envoi d'un fichier via FTP).
 * --- */

#define SC_KEY  0 /* key */
#define SC_EQU  1 /* '=' */
#define SC_VAL  2 /* val */
#define SC_EOL  3 /* <CR><LF> */
#define SC_NEXT 4

struct sendcookie {
	wescfg_t *cfg;
	int step, err;
	size_t off;
};

/* `sendsection_callback()`: Callback de la fonction d'envoi de section. */

static size_t sendsection_callback(char *buffer, size_t blocksize, size_t size,
	struct sendcookie *cookie)
{
	wescfg_t *cfg;
	const char *tocopy;
	size_t off, csize, copysize;
	size_t wr = 0;

	if (cookie->err != WROK)
		return (0);

	size *= blocksize;
	while (size) {
		cfg = cookie->cfg;
		if (!cfg)
			break;

		/* Sélection de ce qu'il faut copier. */

		switch (cookie->step) {
		case SC_KEY:
			tocopy = cfg->data;
			csize = cfg->keysz;
			break;
		case SC_EQU:
			tocopy = "=";
			csize = 1;
			break;
		case SC_VAL:
			tocopy = &cfg->data[cfg->keysz];
			csize = cfg->valsz;
			break;
		case SC_EOL:
			tocopy = "\r\n";
			csize = 2;
			break;
		default:
			cookie->err = WRUNKNOWN;
			return (wr / blocksize);
		}

		/* Calcul de ce qu'il faut copier, préparation de la prochaine
		 * lecture. */

		copysize = size;
		off = cookie->off;
		cookie->off += off;
		if (cookie->off + copysize >= csize) {
			copysize = csize - off;
			cookie->off = 0;
			cookie->step++;
			if (cookie->step == SC_NEXT) {
				cookie->step = SC_KEY;
				cookie->cfg = cfg->next;
			}
		}

		memcpy(buffer, &tocopy[off], copysize);
		buffer += copysize;
		size -= copysize;
		wr += copysize;
	}

	return (wr / blocksize);
}

/* `sendsection()`: Envoi d'une section de configuration. */

static int sendsection(wes_t *wes, wescfgsec_t *sec)
{
	CURL *curl; CURLcode cres;
	struct sendcookie cookie;
	curl_off_t fsize;
	wescfg_t *cfg;
	int err;

	/* On calcule le nombre total de bytes que cela va prendre. */

	fsize = 0;
	for (cfg = sec->child; cfg; cfg = cfg->next)
		fsize += cfg->keysz + cfg->valsz + 3; /* '=', <CR>, <LF> */

	/* On initialise la requête. */

	curl = curl_easy_init();
	if (!curl)
		return (WRUNKNOWN);

	if ((err = get_request(wes, &curl, &sec->data[sec->keysz])))
		return (err);

	curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
	curl_easy_setopt(curl, CURLOPT_READDATA, &cookie);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, sendsection_callback);
	curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fsize);

	cres = curl_easy_perform(curl);

	switch (cres) {
	case CURLE_OK:
		/* Tout s'est bien passé. */
		break;

	case CURLE_READ_ERROR:
	case CURLE_WRITE_ERROR:
		/* Le callback de lecture a fait s'arrêter le transfert. */

		return (cookie.err);

	case CURLE_OUT_OF_MEMORY:
		/* Une allocation a échoué. */

		return (WRALLOC);

	case CURLE_COULDNT_RESOLVE_HOST: /* FALLTHRU */
	case CURLE_COULDNT_CONNECT: /* FALLTHRU */
	case CURLE_FTP_CANT_GET_HOST: /* FALLTHRU */
	case CURLE_SEND_ERROR: /* FALLTHRU */
	case CURLE_RECV_ERROR:
		/* Quelque chose s'est mal passé sur la transmission. */

		return (WRNOHOST);

	default:
		return (WRUNKNOWN);
	}

	return (WROK);
}

/* ---
 * Gestion plus haut niveau de la configuration.
 * --- */

static int getsection(wes_t *wes, wescfgsec_t **secresp, const char *section)
{
	wescfgsec_t *sec, **secp;
	size_t sz; int err;

	/* Recherche de la section. */

	sz = strlen(section);
	for (secp = &wes->sections; (sec = *secp); secp = &sec->next) {
		if (sz == sec->keysz && !memcmp(sec->data, section, sz))
			break;
	}

	/* Si la section n'a pas été trouvée, on la récupère. */

	if (!sec) {
		*secp = malloc(sizeof(wescfgsec_t) + sz + 1);
		sec = *secp;
		if (!sec)
			return (WRALLOC);

		sec->next = NULL;
		sec->child = NULL;
		sec->keysz = sz;
		memcpy(sec->data, section, sz);
		sec->data[sz] = 0;

		err = gathersection(wes, sec);
		if (err) {
			free(sec);
			*secp = NULL;
			return (err);
		}

		sec = *secp;
	}

	*secresp = sec;
	return (WROK);
}

static int getsectionkey(wes_t *wes, const char *section, const char *key,
	wescfg_t **cfgp)
{
	wescfgsec_t *sec;
	wescfg_t *cfg;
	size_t keysz;
	int err;

	/* Récupération de la section. */

	if ((err = getsection(wes, &sec, section)))
		return (err);

	/* On recherche l'élément de configuration en utilisant la clé. */

	keysz = strlen(key);
	for (cfg = sec->child; cfg; cfg = cfg->next)
		if (keysz == cfg->keysz && !memcmp(cfg->data, key, keysz))
			break;
	if (!cfg)
		return (WRNOTFOUND);

	/* L'élément a été trouvé, on a juste à le retourner :) */

	*cfgp = cfg;
	return (WROK);
}

static int setsectionkey(wes_t *wes, const char *section, const char *key,
	const char *value)
{
	wescfgsec_t *sec;
	int err;

	/* Récupération de la section. */

	if ((err = getsection(wes, &sec, section)))
		return (err);

	/* On inscrit la donnée en utilisant la fonction déjà utilisée
	 * dans `gathersection()`. */

	err = setsectionkeyval(sec, key, value);
	if (err)
		return (err);

	/* Si on est là, c'est que la donnée de configuration a été écrite avec
	 * succès ! Bien joué ! */

	return (WROK);
}

static int delsectionkey(wes_t *wes, const char *section, const char *key)
{
	wescfgsec_t *sec;
	wescfg_t **cfgp, *cfg, *next;
	size_t keysz; int err;

	/* Récupération de la section. */

	if ((err = getsection(wes, &sec, section)))
		return (err);

	/* On cherche la donnée. */

	keysz = strlen(key);
	for (cfgp = &sec->child; (cfg = *cfgp); cfgp = &cfg->next) {
		if (keysz == cfg->keysz && !memcmp(cfg->data, key, keysz))
			break;
	}
	if (!cfg)
		return (WRNOTFOUND);

	/* On la supprime. */

	next = cfg->next;
	free(cfg);
	*cfgp = next;

	/* On a bien supprimé la donnée ! */

	return (WROK);
}

/* ---
 * Fonctions pour l'utilisateur concernant la configuration.
 * --- */

/* `get_config()`: Récupération d'un élément de configuration. */

int get_config(wes_t *wes, const char *section_src, const char *key_src,
	char *buf, size_t len)
{
	int err; wescfg_t *cfg;
	char section[SECSIZE + 1];
	char key[KEYSIZE + 1];

	if ((err = normalize_section(section, section_src))
	 || (err = normalize_key(key, key_src)))
		return (err);

	if ((err = getsectionkey(wes, section, key, &cfg)))
		return (err);

	if (len > cfg->valsz + 1)
		len = cfg->valsz + 1;
	len--;
	memcpy(buf, &cfg->data[cfg->keysz], len);
	buf[len] = 0;

	return (WROK);
}

/* `set_config()`: Définition d'un élément de configuration. */

int set_config(wes_t *wes, const char *section_src, const char *key_src,
	const char *value_src)
{
	int err;
	char section[SECSIZE + 1];
	char key[KEYSIZE + 1];
	char value[VALSIZE + 1];

	if ((err = normalize_section(section, section_src))
	 || (err = normalize_key(key, key_src))
	 || (err = normalize_value(key, value_src)))
		return (err);

	err = *value ? setsectionkey(wes, section, key, value)
		: delsectionkey(wes, section, key);
	if (err)
		return (err);

	return (WROK);
}

/* `apply_config()`: Application de la configuration. */

int apply_config(wes_t *wes)
{
	wescfgsec_t *sec;
	int err;

	for (sec = wes->sections; sec; sec++) {
		if ((err = sendsection(wes, sec)))
			return (err);
	}

	return (WROK);
}

/* `clear_config()`: Vidage de la configuration. */

int clear_config(wes_t *wes)
{
	wescfgsec_t *sec;

	while ((sec = wes->sections)) {
		wes->sections = sec->next;
		emptysection(sec);
		free(sec);
	}

	return (WROK);
}