forked from ElektraInitiative/libelektra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.c
1235 lines (1080 loc) · 30.7 KB
/
resolver.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
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "resolver.h"
#include <kdbassert.h>
#include <kdbconfig.h>
#include <kdbhelper.h> // elektraStrDup
#include <kdbprivate.h> // KDB_CACHE_PREFIX
#include "kdbos.h"
#include <stdlib.h>
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif
/* Needs posix */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <dirent.h>
#include <kdberrors.h>
#include <kdblogger.h>
#include <kdbmacros.h>
#ifdef ELEKTRA_LOCK_MUTEX
#include <pthread.h>
#endif
#ifdef ELEKTRA_LOCK_MUTEX
#if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
static pthread_mutex_t elektraResolverMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
#elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
static pthread_mutex_t elektraResolverMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
#else
static pthread_mutex_t elektraResolverMutex;
static pthread_mutex_t elektraResolverInitMutex = PTHREAD_MUTEX_INITIALIZER;
static unsigned char elektraResolverMutexInitialized = 0;
#define ELEKTRA_RESOLVER_RECURSIVE_MUTEX_INITIALIZATION
#endif
#endif
static void resolverInit (resolverHandle * p, const char * path)
{
p->fd = -1;
p->mtime.tv_sec = 0;
p->mtime.tv_nsec = 0;
p->filemode = KDB_FILE_MODE;
p->dirmode = KDB_FILE_MODE | KDB_DIR_MODE;
p->removalNeeded = 0;
p->isMissing = 0;
p->timeFix = 1;
p->filename = 0;
p->dirname = 0;
p->tempfile = 0;
p->path = path;
p->uid = 0;
p->gid = 0;
}
static resolverHandle * elektraGetResolverHandle (Plugin * handle, Key * parentKey)
{
resolverHandles * pks = elektraPluginGetData (handle);
ELEKTRA_ASSERT (pks != NULL, "Unable to retrieve plugin data for handle %p with parentKey %s", (void *) handle,
keyName (parentKey));
switch (keyGetNamespace (parentKey))
{
case KEY_NS_SPEC:
return &pks->spec;
case KEY_NS_DIR:
return &pks->dir;
case KEY_NS_USER:
return &pks->user;
case KEY_NS_SYSTEM:
return &pks->system;
case KEY_NS_PROC:
case KEY_NS_NONE:
case KEY_NS_META:
case KEY_NS_CASCADING:
case KEY_NS_DEFAULT:
return 0;
}
return 0;
}
static void resolverCloseOne (resolverHandle * p)
{
elektraFree (p->filename);
p->filename = 0;
elektraFree (p->dirname);
p->dirname = 0;
elektraFree (p->tempfile);
p->tempfile = 0;
}
static void resolverClose (resolverHandles * p)
{
// shared by all, freed at the end
char * path = (char *) p->system.path;
resolverCloseOne (&p->spec);
resolverCloseOne (&p->dir);
resolverCloseOne (&p->user);
resolverCloseOne (&p->system);
elektraFree (path);
elektraFree (p);
}
/**
* Locks file for exclusive read/write mode.
*
* This function will not block until all reader
* and writer have left the file.
* -> conflict with other cooperative process detected,
* but we were later (and lost)
*
* @exception 27 set if locking failed, most likely a conflict
*
* @param fd is a valid filedescriptor
* @retval 0 on success
* @retval -1 on failure
* @ingroup backendhelper
*/
static int elektraLockFile (int fd ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
#ifdef ELEKTRA_LOCK_FILE
struct flock l;
l.l_type = F_WRLCK; /*Do exclusive Lock*/
l.l_start = 0; /*Start at begin*/
l.l_whence = SEEK_SET;
l.l_len = 0; /*Do it with whole file*/
int ret = fcntl (fd, F_SETLK, &l);
if (ret == -1)
{
if (errno == EAGAIN || errno == EACCES)
{
ELEKTRA_SET_RESOURCE_ERROR (parentKey,
"Conflict because other process writes to configuration indicated by file lock");
}
else
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Assuming conflict because of failed file lock. Reason: %s",
strerror (errno));
}
return -1;
}
return ret;
#else
return 0;
#endif
}
/**
* Unlocks file.
*
* @param fd is a valid filedescriptor
* @retval 0 on success
* @retval -1 on failure
* @ingroup backendhelper
*/
static int elektraUnlockFile (int fd ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
#ifdef ELEKTRA_LOCK_FILE
struct flock l;
l.l_type = F_UNLCK; /*Give Lock away*/
l.l_start = 0; /*Start at begin*/
l.l_whence = SEEK_SET;
l.l_len = 0; /*Do it with whole file*/
int ret = fcntl (fd, F_SETLK, &l);
if (ret == -1)
{
ELEKTRA_ADD_RESOURCE_WARNINGF (parentKey, "Method 'fcntl' unlocking failed (SETLK). Reason: %s", strerror (errno));
}
return ret;
#else
return 0;
#endif
}
/**
* @brief mutex lock for multithread-safety
*
* @retval 0 on success
* @retval -1 on error
*/
static int elektraLockMutex (Key * parentKey ELEKTRA_UNUSED)
{
#ifdef ELEKTRA_LOCK_MUTEX
int ret = pthread_mutex_trylock (&elektraResolverMutex);
if (ret != 0)
{
if (errno == EBUSY // for trylock
|| errno == EDEADLK) // for error checking mutex, if enabled
{
ELEKTRA_SET_CONFLICTING_STATE_ERROR (
parentKey, "Conflict because other thread writes to configuration indicated by mutex lock");
}
else
{
ELEKTRA_SET_CONFLICTING_STATE_ERRORF (parentKey, "Assuming conflict because of failed mutex lock. Reason: %s",
strerror (errno));
}
return -1;
}
return 0;
#else
return 0;
#endif
}
/**
* @brief mutex unlock for multithread-safety
*
* @retval 0 on success
* @retval -1 on error
*/
static int elektraUnlockMutex (Key * parentKey ELEKTRA_UNUSED)
{
#ifdef ELEKTRA_LOCK_MUTEX
int ret = pthread_mutex_unlock (&elektraResolverMutex);
if (ret != 0)
{
ELEKTRA_ADD_RESOURCE_WARNINGF (parentKey, "Mutex unlock failed. Reason: %s", strerror (errno));
return -1;
}
return 0;
#else
return 0;
#endif
}
/**
* @brief Close a file
*
* @param fd the filedescriptor to close
* @param parentKey the key to write warnings to
*/
static void elektraCloseFile (int fd, Key * parentKey)
{
if (close (fd) == -1)
{
ELEKTRA_ADD_RESOURCE_WARNINGF (parentKey, "Close file failed. Reason: %s", strerror (errno));
}
}
/**
* @brief Add error text received from strerror
*
* @param errorText should have at least ERROR_SIZE bytes in reserve
*/
static char * elektraAddErrnoText (void)
{
if (errno == E2BIG)
{
return "could not find a / in the pathname";
}
else if (errno == EINVAL)
{
return "went up to root for creating directory";
}
else
{
return strerror (errno);
}
#if defined(__GNUC__) && __GNUC__ >= 8 && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
#endif
#if defined(__GNUC__) && __GNUC__ >= 8 && !defined(__clang__)
#pragma GCC diagnostic pop
#endif
}
static int needsMapping (Key * testKey, Key * errorKey)
{
elektraNamespace ns = keyGetNamespace (errorKey);
if (ns == KEY_NS_NONE) return 1; // for unit tests
if (ns == KEY_NS_CASCADING) return 1; // init all namespaces for cascading
return ns == keyGetNamespace (testKey); // otherwise only init if same ns
}
static int mapFilesForNamespaces (resolverHandles * p, Key * errorKey)
{
Key * testKey = keyNew ("/", KEY_END);
// switch is only present to forget no namespace and to get
// a warning whenever a new namespace is present.
// In fact its linear code executed:
ElektraResolved * resolved = NULL;
switch (KEY_NS_SPEC)
{
case KEY_NS_SPEC:
keySetName (testKey, "spec:/");
if (needsMapping (testKey, errorKey))
{
if ((resolved = ELEKTRA_PLUGIN_FUNCTION (filename) (KEY_NS_SPEC, (p->spec).path, ELEKTRA_RESOLVER_TEMPFILE_SAMEDIR,
errorKey)) == NULL)
{
resolverClose (p);
keyDel (testKey);
ELEKTRA_SET_RESOURCE_ERROR (errorKey, "Could not resolve filename. Could not resolve spec key");
return -1;
}
else
{
p->spec.tempfile = elektraStrDup (resolved->tmpFile);
p->spec.filename = elektraStrDup (resolved->fullPath);
p->spec.dirname = elektraStrDup (resolved->dirname);
ELEKTRA_PLUGIN_FUNCTION (freeHandle) (resolved);
}
}
// FALLTHROUGH
case KEY_NS_DIR:
keySetName (testKey, "dir:/");
if (needsMapping (testKey, errorKey))
{
if ((resolved = ELEKTRA_PLUGIN_FUNCTION (filename) (KEY_NS_DIR, (p->dir).path, ELEKTRA_RESOLVER_TEMPFILE_SAMEDIR,
errorKey)) == NULL)
{
resolverClose (p);
keyDel (testKey);
ELEKTRA_SET_RESOURCE_ERROR (errorKey, "Could not resolve filename. Could not resolve dir key");
return -1;
}
else
{
p->dir.tempfile = elektraStrDup (resolved->tmpFile);
p->dir.filename = elektraStrDup (resolved->fullPath);
p->dir.dirname = elektraStrDup (resolved->dirname);
ELEKTRA_PLUGIN_FUNCTION (freeHandle) (resolved);
}
}
// FALLTHROUGH
case KEY_NS_USER:
keySetName (testKey, "user:/");
if (needsMapping (testKey, errorKey))
{
if ((resolved = ELEKTRA_PLUGIN_FUNCTION (filename) (KEY_NS_USER, (p->user).path, ELEKTRA_RESOLVER_TEMPFILE_SAMEDIR,
errorKey)) == NULL)
{
resolverClose (p);
keyDel (testKey);
ELEKTRA_SET_RESOURCE_ERRORF (errorKey, "Could not resolve user key with configuration %s",
ELEKTRA_VARIANT_USER);
return -1;
}
else
{
p->user.tempfile = elektraStrDup (resolved->tmpFile);
p->user.filename = elektraStrDup (resolved->fullPath);
p->user.dirname = elektraStrDup (resolved->dirname);
ELEKTRA_PLUGIN_FUNCTION (freeHandle) (resolved);
}
}
// FALLTHROUGH
case KEY_NS_SYSTEM:
keySetName (testKey, "system:/");
if (needsMapping (testKey, errorKey))
{
if ((resolved = ELEKTRA_PLUGIN_FUNCTION (filename) (KEY_NS_SYSTEM, (p->system).path,
ELEKTRA_RESOLVER_TEMPFILE_SAMEDIR, errorKey)) == NULL)
{
resolverClose (p);
keyDel (testKey);
ELEKTRA_SET_RESOURCE_ERRORF (errorKey, "Could not resolve system key with configuration %s",
ELEKTRA_VARIANT_SYSTEM);
return -1;
}
else
{
p->system.tempfile = elektraStrDup (resolved->tmpFile);
p->system.filename = elektraStrDup (resolved->fullPath);
p->system.dirname = elektraStrDup (resolved->dirname);
ELEKTRA_PLUGIN_FUNCTION (freeHandle) (resolved);
}
}
// FALLTHROUGH
case KEY_NS_PROC:
case KEY_NS_NONE:
case KEY_NS_META:
case KEY_NS_CASCADING:
case KEY_NS_DEFAULT:
break;
}
keyDel (testKey);
return 0;
}
/**
* @brief Generate key name for the cache
*
* @param filename the name of the config file
* @ret pointer to the generated key name
*/
static char * elektraCacheKeyName (char * filename)
{
char * name = 0;
size_t len = strlen (KDB_CACHE_PREFIX) + strlen ("/") + strlen (ELEKTRA_PLUGIN_NAME) + strlen (filename) + 1;
name = elektraMalloc (len);
name = strcpy (name, KDB_CACHE_PREFIX);
name = strcat (name, "/");
name = strcat (name, ELEKTRA_PLUGIN_NAME);
name = strcat (name, filename);
ELEKTRA_LOG_DEBUG ("persistent chid key: %s", name);
return name;
}
static int initHandles (Plugin * handle, Key * parentKey)
{
const char * path = elektraStrDup (keyString (parentKey));
resolverHandles * p = elektraMalloc (sizeof (resolverHandles));
resolverInit (&p->spec, path);
resolverInit (&p->dir, path);
resolverInit (&p->user, path);
resolverInit (&p->system, path);
#if defined(ELEKTRA_RESOLVER_RECURSIVE_MUTEX_INITIALIZATION)
// PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP is available in glibc only
// so we use another mutex for the initialization of the recursive mutex,
// since this section must be thread safe.
pthread_mutex_lock (&elektraResolverInitMutex);
if (!elektraResolverMutexInitialized)
{
pthread_mutexattr_t mutexAttr;
int mutexError;
if ((mutexError = pthread_mutexattr_init (&mutexAttr)) != 0)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Could not initialize recursive mutex: pthread_mutexattr_init returned %d",
mutexError);
pthread_mutex_unlock (&elektraResolverInitMutex);
return -1;
}
if ((mutexError = pthread_mutexattr_settype (&mutexAttr, PTHREAD_MUTEX_RECURSIVE)) != 0)
{
ELEKTRA_SET_RESOURCE_ERRORF (
parentKey, "Could not initialize recursive mutex: pthread_mutexattr_settype returned %d", mutexError);
pthread_mutex_unlock (&elektraResolverInitMutex);
return -1;
}
if ((mutexError = pthread_mutex_init (&elektraResolverMutex, &mutexAttr)) != 0)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Could not initialize recursive mutex: pthread_mutex_init returned %d",
mutexError);
pthread_mutex_unlock (&elektraResolverInitMutex);
return -1;
}
elektraResolverMutexInitialized = 1;
}
pthread_mutex_unlock (&elektraResolverInitMutex);
#endif
// system and spec files need to be world-readable, otherwise they are
// useless
p->system.filemode = 0644;
p->system.dirmode = 0755;
p->spec.filemode = 0644;
p->spec.dirmode = 0755;
int ret = mapFilesForNamespaces (p, parentKey);
if (ret != -1)
{
elektraPluginSetData (handle, p);
}
return ret;
}
int ELEKTRA_PLUGIN_FUNCTION (open) (Plugin * handle, Key * errorKey ELEKTRA_UNUSED)
{
elektraPluginSetData (handle, NULL);
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
int ELEKTRA_PLUGIN_FUNCTION (close) (Plugin * handle, Key * errorKey ELEKTRA_UNUSED)
{
resolverHandles * ps = elektraPluginGetData (handle);
if (ps)
{
resolverClose (ps);
elektraPluginSetData (handle, 0);
}
return 0; /* success */
}
int ELEKTRA_PLUGIN_FUNCTION (get) (Plugin * handle, KeySet * returned, Key * parentKey)
{
Key * root = keyNew ("system:/elektra/modules/" ELEKTRA_PLUGIN_NAME, KEY_END);
if (keyCmp (root, parentKey) == 0 || keyIsBelow (root, parentKey) == 1)
{
keyDel (root);
KeySet * info =
#include "contract.h"
ksAppend (returned, info);
ksDel (info);
return 1;
}
keyDel (root);
if (elektraPluginGetData (handle) == NULL)
{
if (initHandles (handle, parentKey) == ELEKTRA_PLUGIN_STATUS_ERROR)
{
return ELEKTRA_PLUGIN_STATUS_ERROR;
}
}
resolverHandle * pk = elektraGetResolverHandle (handle, parentKey);
keySetString (parentKey, pk->filename);
int errnoSave = errno;
struct stat buf;
ELEKTRA_LOG ("stat file %s", pk->filename);
/* Start file IO with stat() */
if (stat (pk->filename, &buf) == -1)
{
// no file, so storage has no job
errno = errnoSave;
pk->isMissing = 1;
// no file, so no metadata:
pk->mtime.tv_sec = 0;
pk->mtime.tv_nsec = 0;
return 0;
}
else
{
// successful, remember mode, uid and gid
pk->filemode = buf.st_mode;
pk->gid = buf.st_gid;
pk->uid = buf.st_uid;
pk->isMissing = 0;
}
/* Check if update needed */
if (pk->mtime.tv_sec == ELEKTRA_STAT_SECONDS (buf) && pk->mtime.tv_nsec == ELEKTRA_STAT_NANO_SECONDS (buf))
{
// no update, so storage has no job
errno = errnoSave;
return 0;
}
/* Check if cache update needed */
KeySet * global;
char * name = elektraCacheKeyName (pk->filename);
if ((global = elektraPluginGetGlobalKeySet (handle)) != NULL && ELEKTRA_STAT_NANO_SECONDS (buf) != 0)
{
// TODO [new_backend]: implement cache
/*
ELEKTRA_LOG_DEBUG ("global-cache: check cache update needed?");
Key * time = ksLookupByName (global, name, KDB_O_NONE);
if (time && keyGetValueSize (time) == sizeof (struct timespec))
{
struct timespec cached;
keyGetBinary (time, &cached, sizeof (struct timespec));
if (cached.tv_sec == ELEKTRA_STAT_SECONDS (buf) && cached.tv_nsec == ELEKTRA_STAT_NANO_SECONDS (buf))
{
ELEKTRA_LOG_DEBUG ("global-cache: no update needed, everything is fine");
ELEKTRA_LOG_DEBUG ("cached.tv_sec:\t%ld", cached.tv_sec);
ELEKTRA_LOG_DEBUG ("cached.tv_nsec:\t%ld", cached.tv_nsec);
ELEKTRA_LOG_DEBUG ("buf.tv_sec:\t%ld", ELEKTRA_STAT_SECONDS (buf));
ELEKTRA_LOG_DEBUG ("buf.tv_nsec:\t%ld", ELEKTRA_STAT_NANO_SECONDS (buf));
// update timestamp inside resolver
pk->mtime.tv_sec = ELEKTRA_STAT_SECONDS (buf);
pk->mtime.tv_nsec = ELEKTRA_STAT_NANO_SECONDS (buf);
if (name) elektraFree (name);
errno = errnoSave;
return ELEKTRA_PLUGIN_STATUS_CACHE_HIT;
}
}
*/
}
pk->mtime.tv_sec = ELEKTRA_STAT_SECONDS (buf);
pk->mtime.tv_nsec = ELEKTRA_STAT_NANO_SECONDS (buf);
/* Persist modification times for cache */
if (global != NULL && ELEKTRA_STAT_NANO_SECONDS (buf) != 0)
{
ELEKTRA_LOG_DEBUG ("global-cache: adding file modification times");
Key * time = keyNew (name, KEY_BINARY, KEY_SIZE, sizeof (struct timespec), KEY_VALUE, &(pk->mtime), KEY_END);
ksAppendKey (global, time);
}
if (name) elektraFree (name);
errno = errnoSave;
return 1;
}
/**
* @brief Open a file and yield an error on conflicts
*
* @param pk->filename will be used
* @param parentKey to yield the error to
*
* @retval 0 on success (might be an error for creating a missing file)
* @retval -1 on conflict
*/
static int elektraOpenFile (resolverHandle * pk, Key * parentKey)
{
int flags = 0;
if (pk->isMissing)
{
ELEKTRA_LOG_DEBUG ("creating %s", pk->filename);
// it must be created newly, otherwise we have an conflict
flags = O_RDWR | O_CREAT | O_EXCL;
// only works when using NFSv3 or later on kernel 2.6 or later
// TODO: add variant with linkat?
}
else
{
ELEKTRA_LOG_DEBUG ("opening %s", pk->filename);
// file was there before, so opening should work!
flags = O_RDWR;
}
errno = 0;
pk->fd = open (pk->filename, flags, pk->filemode);
if (!pk->isMissing)
{
if (errno == ENOENT)
{
ELEKTRA_SET_INTERNAL_ERRORF (parentKey,
"The configuration file '%s' was there earlier, "
"now it is missing",
pk->filename);
return -1;
}
else if (pk->fd == -1)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Could not reopen configuration file '%s' for writing. Reason: %s",
pk->filename, strerror (errno));
return -1;
}
// successfully reopened
}
else
{
if (pk->fd != -1)
{
// successfully created a file
pk->removalNeeded = 1;
return 0;
}
else if (errno == EEXIST)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey,
"No configuration file was there earlier. "
"Now configuration file '%s' exists",
pk->filename);
return -1;
}
// ignore errors for attempts to create a new file, we will try it again later
}
errno = 0;
return 0;
}
/**
* @brief Create a file and yield an error if it did not work
*
* @param pk->filename will be used
* @param parentKey to yield the error to
*
* @retval 0 on success
* @retval -1 on error
*/
static int elektraCreateFile (resolverHandle * pk, Key * parentKey)
{
ELEKTRA_LOG_DEBUG ("creating %s", pk->filename);
pk->fd = open (pk->filename, O_RDWR | O_CREAT, pk->filemode);
if (pk->fd == -1)
{
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Could not create configuration file '%s'. Reason: %s", pk->filename,
strerror (errno));
return -1;
}
return 0;
}
/**
* @brief Create pathname recursively.
*
* Try unless the whole path was
* created or it is sure that it cannot be done.
*
* @param pathname The path to create.
*
* @retval 0 on success
* @retval -1 on error + elektra error will be set
*/
static int elektraMkdirParents (resolverHandle * pk, const char * pathname, Key * parentKey)
{
if (mkdir (pathname, pk->dirmode) == -1)
{
if (errno == EEXIST)
{
// already exists
return 0;
}
if (errno != ENOENT)
{
// hopeless, give it up
goto error;
}
// last part of filename component (basename)
char * p = strrchr (pathname, '/');
/* nothing found */
if (p == NULL)
{
// set any errno, corrected in
// elektraAddErrnoText
errno = E2BIG;
goto error;
}
/* absolute path */
if (p == pathname)
{
// set any errno, corrected in
// elektraAddErrnoText
errno = EINVAL;
goto error;
}
/* Cut path at last /. */
*p = 0;
/* Now call ourselves recursively */
if (elektraMkdirParents (pk, pathname, parentKey) == -1)
{
// do not yield an error, was already done
// before
*p = '/';
return -1;
}
/* Restore path. */
*p = '/';
if (mkdir (pathname, pk->dirmode) == -1)
{
goto error;
}
}
return 0;
error : {
ELEKTRA_SET_RESOURCE_ERRORF (parentKey,
"Could not create directory '%s'. Reason: %s. Identity: uid: %u, euid: %u, gid: %u, egid: %u",
pathname, elektraAddErrnoText (), getuid (), geteuid (), getgid (), getegid ());
return -1;
}
}
/**
* @brief Check conflict for the current open file
*
* Does an fstat and checks if mtime are equal as they were
*
* @param pk to get mtime and fd from
* @param parentKey to write errors&warnings to
*
* @retval 0 success
* @retval -1 error
*/
static int elektraCheckConflict (resolverHandle * pk, Key * parentKey)
{
if (pk->isMissing)
{
// conflict already handled at file creation time, so just return successfully
return 0;
}
struct stat buf;
if (fstat (pk->fd, &buf) == -1)
{
ELEKTRA_ADD_RESOURCE_WARNINGF (
parentKey,
"Could not 'fstat' to check for conflict '%s'. Reason: %s. Identity: uid: %u, euid: %u, gid: %u, egid: %u",
pk->filename, elektraAddErrnoText (), getuid (), geteuid (), getgid (), getegid ());
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "Assuming conflict because of failed stat (warning %s for details)",
ELEKTRA_ERROR_RESOURCE);
return -1;
}
if (ELEKTRA_STAT_SECONDS (buf) != pk->mtime.tv_sec || ELEKTRA_STAT_NANO_SECONDS (buf) != pk->mtime.tv_nsec)
{
ELEKTRA_SET_CONFLICTING_STATE_ERRORF (
parentKey,
"Conflict, file modification time stamp '%ld.%ld' is different than our time stamp '%ld.%ld', config file "
"name is '%s'. "
"Our identity is uid: %u, euid: %u, gid: %u, egid: %u",
ELEKTRA_STAT_SECONDS (buf), ELEKTRA_STAT_NANO_SECONDS (buf), pk->mtime.tv_sec, pk->mtime.tv_nsec, pk->filename,
getuid (), geteuid (), getgid (), getegid ());
return -1;
}
return 0;
}
/**
* @brief Does everything needed before the storage plugin will be
* invoked.
*
* @param pk resolver information
* @param parentKey parent
*
* @retval 0 on success
* @retval -1 on error
*/
static int elektraSetPrepare (resolverHandle * pk, Key * parentKey)
{
pk->removalNeeded = 0;
if (elektraOpenFile (pk, parentKey) == -1)
{
// file/none-file conflict OR error on previously existing file
return -1;
}
if (pk->fd == -1)
{
// try creation of underlying directory
elektraMkdirParents (pk, pk->dirname, parentKey);
// now try to create file
if (elektraCreateFile (pk, parentKey) == -1)
{
// no way to be successful
return -1;
}
// the file was created by us, so we need to remove it
// on error:
pk->removalNeeded = 1;
}
if (elektraLockMutex (parentKey) != 0)
{
elektraCloseFile (pk->fd, parentKey);
pk->fd = -1;
return -1;
}
// now we have a file, so lock immediately
if (elektraLockFile (pk->fd, parentKey) == -1)
{
elektraCloseFile (pk->fd, parentKey);
elektraUnlockMutex (parentKey);
pk->fd = -1;
return -1;
}
if (elektraCheckConflict (pk, parentKey) == -1)
{
elektraUnlockFile (pk->fd, parentKey);
elektraCloseFile (pk->fd, parentKey);
elektraUnlockMutex (parentKey);
pk->fd = -1;
return -1;
}
return 0;
}
static void elektraModifyFileTime (resolverHandle * pk)
{
#ifdef HAVE_CLOCK_GETTIME
// for linux let us calculate a new ns timestamp to use
struct timespec ts;
clock_gettime (CLOCK_MONOTONIC, &ts);
if (ts.tv_sec == pk->mtime.tv_sec)
{
// for filesystems not supporting subseconds, make sure the second is changed, too
pk->mtime.tv_sec += pk->timeFix;
pk->timeFix *= -1; // toggle timefix
}
else
{
pk->mtime.tv_sec = ts.tv_sec;
}
if (ts.tv_nsec == pk->mtime.tv_nsec)
{
// also slightly change nsec (same direction as seconds):
pk->mtime.tv_nsec += pk->timeFix;
}
else
{
pk->mtime.tv_nsec = ts.tv_nsec;
}
#else
// otherwise use simple time toggling schema of seconds
pk->mtime.tv_sec += pk->timeFix;
pk->timeFix *= -1; // toggle timefix
#endif
}
/* Update timestamp of old file to provoke conflicts in
* stalling processes that might still wait with the old
* filedescriptor */
static void elektraUpdateFileTime (resolverHandle * pk, int fd, Key * parentKey)
{
#ifdef HAVE_FUTIMENS
const struct timespec times[2] = { pk->mtime, // atime
pk->mtime }; // mtime
if (futimens (fd, times) == -1)
{
ELEKTRA_ADD_RESOURCE_WARNINGF (parentKey, "Could not update time stamp of '%s'. Reason: %s",
fd == pk->fd ? pk->filename : pk->tempfile, strerror (errno));
}
#elif defined(HAVE_FUTIMES)
const struct timeval times[2] = { { pk->mtime.tv_sec, pk->mtime.tv_nsec / 1000 }, // atime
{ pk->mtime.tv_sec, pk->mtime.tv_nsec / 1000 } }; // mtime
if (futimes (fd, times) == -1)
{
ELEKTRA_ADD_RESOURCE_WARNINGF (parentKey, "Could not update time stamp of \"%s\", because %s",
fd == pk->fd ? pk->filename : pk->tempfile, strerror (errno));
}
#else
#warning futimens/futimes not defined
#endif
}
/**
* @brief Now commit the temporary file to be final
*
* @param pk
* @param parentKey
*
* It will also reset pk->fd
*
* @retval 0 on success
* @retval -1 on error
*/
static int elektraSetCommit (resolverHandle * pk, Key * parentKey)
{
int ret = 0;
ELEKTRA_LOG_DEBUG ("committing %s to %s", pk->tempfile, pk->filename);