forked from ElektraInitiative/libelektra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyname.c
2018 lines (1800 loc) · 53.7 KB
/
keyname.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 Methods for Key name manipulation.
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
/** @class doxygenNamespaces
*
* @brief .
*
* .
*
* - @p spec:/something for specification of other keys.
* - @p proc:/something for in-memory keys, e.g. commandline.
* - @p dir:/something for dir keys in current working directory
* - @p system:/something for system keys in /etc or /
* - @p user:/something for user keys in home directory
* - @p user:username/something for other users (deprecated: kdbGet() + kdbSet() currently unsupported)
* - @p /something for cascading keys (actually refers to one of the above, see also ksLookup())
*
*/
/**
* @defgroup keyname Name Manipulation Methods
* @ingroup key
* @brief Methods to do various operations on Key names.
*
* To use them:
* @code
#include <kdb.h>
* @endcode
*
* These functions make it easier for C programmers to work with key names.
*
*
* @par Terminology of Key Names
* - A *key name* (see keySetName() and keyName()) defines the
* place of a key within the key database.
* To be unique, it is always absolute and canonical.
* - Key names are composed out of many *key name parts* split by a
* separator. These *key name parts* do not contain an unescaped
* separator.
* - A *key base name* (see keySetBaseName() and keyAddBaseName()) is
* the last part of the key name.
* - A *C-String* is a null terminated sequence of characters.
* So \\0 (null-character) must not occur within a C-String.
*
* @par Namespaces
* A namespace denotes the place the key comes from:
*
* @copydetails doxygenNamespaces
*
*
* @note The rules are currently not formally specified and are subject
* of change in the next major release.
* So, always prefer:
* - To use keySetName() and keyAddName() to get the canonified version of the keyname
* - To use keySetBaseName() and keyAddBaseName() to get an escaped key
* name part.
* - Not to escape or canonify with your own algorithms!
* - To use keyUnescapedName() and keyBaseName() to have access to the
* key name without escape sequences (key name parts are null
* terminated)
* - Not to unescape the strings yourself!
*
*
* @par Syntax for Key Names
* Key names and key name parts have following goals:
* - The C-String passed to keySetName() and keyAddName() may be any
* C-String.
* - The *key name parts* (e.g. keySetBaseName(), keyBaseName()) may
* be any C-String.
* Escaping is needed to achieve both goals.
*
*
* @par Semantics for Key Name Parts
* - \% denotes an empty key name part.
*
*
* @par Canonicalization for Key Names
* - / (slash) is the separator between key name parts.
* - // is shortened to /
* - trailing / (slashes) are removed
* - . (dot) and .. (dot-dot) is removed in an canonical key name, with
* following rules:
* - /./ is shortened to /
* - _/../ is shortened to _
*
*
* @par Conventions for key names
* - Key name parts starting with \# are array elements.
* Then only _ (underscore) followed by 0-9 is allowed.
* So we have the regular expression #[_]*[0-9]+ with the further
* limitation that the number of _ is defined by the number of
* digits-1.
* - Key name parts starting with _ are reserved for special purposes
* (if you use this within a plugin you still have to make sure _ is
* escaped properly)
* - Key name parts starting with @ are reserved for special purposes
* (if you use this within a plugin you still have to make sure @ is
* escaped properly)
*
*
* @par Escaping rules
* - \\ (backslash) is the escape character for the situations as
* described here (and only these).
* The \\ character must only be escaped, when one of the following
* rules apply.
* - Stray escape characters are only possible in the end of the string.
* - \\/ allows one to escape / (any uneven number of \\).
* Does not introduce a new part.
* - Any uneven number N of \\ before / allows you to escape / with the
* N/2 of \\ prefixed.
* Does not introduce a new part.
* - \\\\/ allows one to use \\ as character before / and introduces a new
* part.
* - Any even number N of \\ before / allows you to have N/2 of \\
* prefixed before a / which introduces a new part.
* - Use \\. and \\.. if you want your key name part to represent . and ..
* - \\\\. and \\\\.. allows us to use \\ as character before . and .. (and so on)
* - Use \\% if you want your key name part to start with \% (and does
* not represent an empty name)
* - Using \\\\% allows one to use \\ as character before \% (and so on)
*
*
* @par Semantics for Key Name Specifications
* - _ denotes that the key name part is
* arbitrary (syntax as described above).
* - \# denotes that the key name part
* has array syntax.
* - names surrounded by \% (e.g. \%profile\%)
* denotes a placeholder.
*
*
* @{
*/
#include "kdbprivate.h"
#ifdef HAVE_KDBCONFIG_H
#include "kdbconfig.h"
#endif
#include <kdbassert.h>
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <ctype.h>
#include "kdb.h"
#include "kdbhelper.h"
#include "kdbinternal.h"
/**
* @internal
*
* @brief Helper method: creates a deep copy of a keyname. Does not copy the reference counter.
* The escaped and unescaped name have the provided sizes.
* If the size is less then the sizes of @p source, not everything will be copied!
* @param source the keyname to copy
* @param escapedSize size of the escaped name
* @param unescapedSize size of the unescaped name
* @return
*/
static struct _KeyName * keyNameCopyWithSize (struct _KeyName * source, size_t escapedSize, size_t unescapedSize)
{
struct _KeyName * dest = keyNameNew ();
dest->key = elektraMalloc (escapedSize);
dest->keySize = escapedSize;
size_t copySize = source->keySize;
if (copySize > escapedSize)
{
copySize = escapedSize;
}
memcpy (dest->key, source->key, copySize);
dest->key[copySize - 1] = 0;
dest->ukey = elektraMalloc (unescapedSize);
dest->keyUSize = unescapedSize;
copySize = source->keyUSize;
if (copySize > unescapedSize)
{
copySize = unescapedSize;
}
memcpy (dest->ukey, source->ukey, copySize);
return dest;
}
/**
* @internal
*
* @brief Helper method: creates a deep copy of a keyname. Does not copy the reference counter.
*
* @param source the keyname to copy
*
* @return copied keyname
*/
struct _KeyName * keyNameCopy (struct _KeyName * source)
{
return keyNameCopyWithSize (source, source->keySize, source->keyUSize);
}
/**
* @internal
*
* @brief Helper method: Ensures, that the supplied key has its own KeyName instance
*
* @post @p key's keyName field != NULL
*
* @param key the key to ensure it has its own KeyName instance
*/
void keyDetachKeyName (Key * key)
{
if (!key)
{
return;
}
if (key->keyName == NULL)
{
key->keyName = keyNameNew ();
keyNameRefInc (key->keyName);
}
else if (key->keyName->refs > 1 || isKeyNameInMmap (key->keyName))
{
struct _KeyName * copiedKeyName = keyNameCopy (key->keyName);
keyNameRefDecAndDel (key->keyName);
key->keyName = copiedKeyName;
keyNameRefInc (key->keyName);
}
}
/**
* @internal
*
* @brief Helper method: Ensures, that the supplied key has its own KeyName instance.
* Also ensures, that the key and unescaped key have the specified size.
*
* @post @p key's keyName field != NULL
* @post @p key's escaped name has @p escapeSize size
* @post @p key's unescaped name has @p unescapedSize size
*
* @param key the key to ensure it has its own KeyName instance
* @param escapedSize the new size of the escaped name
* @param unescapedSize the new size of the unescaped name
*/
static void keyDetachKeyNameAndRealloc (Key * key, size_t escapedSize, size_t unescapedSize)
{
if (!key)
{
return;
}
if (key->keyName == NULL)
{
key->keyName = keyNameNew ();
keyNameRefInc (key->keyName);
}
else if (key->keyName->refs > 1 || isKeyNameInMmap (key->keyName))
{
struct _KeyName * copiedKeyName = keyNameCopyWithSize (key->keyName, escapedSize, unescapedSize);
keyNameRefDecAndDel (key->keyName);
key->keyName = copiedKeyName;
keyNameRefInc (key->keyName);
return;
}
if (key->keyName->keySize != escapedSize)
{
elektraRealloc ((void **) &key->keyName->key, escapedSize * sizeof (char));
if (key->keyName->keySize > escapedSize)
{
key->keyName->key[escapedSize - 1] = 0;
}
key->keyName->keySize = escapedSize;
}
if (key->keyName->keyUSize != unescapedSize)
{
elektraRealloc ((void **) &key->keyName->ukey, unescapedSize * sizeof (char));
if (key->keyName->keyUSize > unescapedSize)
{
key->keyName->ukey[unescapedSize - 1] = 0;
}
key->keyName->keyUSize = unescapedSize;
}
}
/**
* @internal
*
* @brief Helper method: Ensures, that the supplied key has its own KeyName instance.
* If the name is shared with other keys, the key gets an empty KeyName instance.
*
* @post @p key's keyName field != NULL
*
* @param key the key to ensure it has its own KeyName instance
*/
static inline void keyDetachKeyNameWithoutCopy (Key * key)
{
if (!key)
{
return;
}
if (key->keyName == NULL)
{
key->keyName = keyNameNew ();
keyNameRefInc (key->keyName);
}
else if (key->keyName->refs > 1 || isKeyNameInMmap (key->keyName))
{
keyNameRefDecAndDel (key->keyName);
key->keyName = keyNameNew ();
keyNameRefInc (key->keyName);
}
}
/**
* Helper method: returns a pointer to the start of the last part of the given key name
*
* @param name a canonical key name
* @param len the length of the key name
*
* @returns pointer to the start of the last part within @p name
*/
static char * findStartOfLastPart (char * name, size_t len)
{
// compare to elektraKeyNameValidate we can just look for the :,
// because we know the name must be valid
char * colon = strchr (name, ':');
char * start = colon == NULL ? name : colon + 1;
++start; // start after first slash
char * cur = start + len - (start - name) - 1;
if (cur == start) return NULL; // no base name
while (cur >= start)
{
--cur;
while (cur >= start && *cur != '/')
{
--cur;
}
size_t backslashes = 0;
while (cur - backslashes > start && *(cur - backslashes - 1) == '\\')
{
++backslashes;
}
if (backslashes % 2 == 0)
{
break;
}
}
return cur < start - 1 ? NULL : cur;
}
/*******************************************
* General name manipulation methods *
*******************************************/
/**
* Returns a pointer to the abbreviated real internal @p key name.
*
* This is a much more efficient version of keyGetName() and can use
* it if you are responsible enough to not mess up things. You are not allowed
* to change anything in the returned array. The content of that string
* may change after keySetName() and similar functions. If you need a copy of the name,
* consider using keyGetName().
*
*
* @retval "" when there is no keyName. The reason is
* @code
key=keyNew(0);
keySetName(key,"");
keyName(key); // you would expect "" here
keyDel(key);
* @endcode
*
* Valid key names are:
*
* @copydetails doxygenNamespaces
*
* @note Note that the Key structure keeps its own size field that is calculated
* by library internal calls, so to avoid inconsistencies, you
* must never use the pointer returned by keyName() method to set a new
* value. Use keySetName() instead.
*
* @param key the Key you want to get the name from
*
* @return a pointer to the Key's name which must not be changed.
* @retval "" when Key's name is empty
* @retval 0 on NULL pointer
*
* @since 1.0.0
* @ingroup keyname
* @see keyGetNameSize() for the string length
* @see keyGetName() as alternative to get a copy
* @see keyUnescapedName to get an unescaped key name
*/
const char * keyName (const Key * key)
{
if (!key) return 0;
if (!key->keyName) return "";
ELEKTRA_ASSERT (key->keyName->key != NULL, "invalid name");
return key->keyName->key;
}
/**
* Bytes needed to store the Key's name (excluding owner).
*
* For an empty Key name you need one byte to store the ending NULL.
* For that reason, 1 is returned when the name is empty.
*
* @param key the Key to get the name size from
*
* @return number of bytes needed, including NULL terminator, to store Key's name
* (excluding owner)
* @retval 1 if Key has no name
* @retval -1 on NULL pointer
*
* @since 1.0.0
* @ingroup keyname
* @see keyGetName() for getting the Key's name
* @see keyGetUnescapedNameSize() for getting the size of the unescaped name
*/
ssize_t keyGetNameSize (const Key * key)
{
if (!key) return -1;
if (!key->keyName || !key->keyName->key) return 1;
return key->keyName->keySize;
}
/**
* Returns a Key's name, separated by NULL bytes and without backslashes for
* escaping
*
* Slashes are replaced with NULL bytes.
* Therefore unescaped names of cascading Keys start with a NULL byte.
* Otherwise escaped characters, e.g. non-hierarchy slashes, will be unescaped.
*
* This name is essential if you want to iterate over parts of the Key's
* name, compare Key names or check relations of Keys in the hierarchy.
*
* @param key the Key whose unescaped name to get
*
* @return the name in its unescaped form
* @retval 0 on NULL pointers
* @retval "" if Key's name is empty
*
* @since 1.0.0
* @ingroup keyname
* @see keyGetUnescapedName() for getting a copy of the unescaped name
* @see keyGetUnescapedNameSize() for getting the size of the unescaped name
* @see keyName() for getting the escaped name of the Key
*/
const void * keyUnescapedName (const Key * key)
{
if (!key) return 0;
if (!key->keyName) return "";
ELEKTRA_ASSERT (key->keyName->ukey != NULL, "invalid name");
return key->keyName->ukey;
}
/**
* @brief Returns the size of the Key's unescaped name including embedded and
* terminating NULL characters
*
* @param key the Key where to get the size of the unescaped name from
*
* @return The size of the Key's unescaped name
* @retval -1 on NULL pointer
* @retval 0 if Key has no name
*
* @since 1.0.0
* @ingroup keyname
* @see keyUnescapedName() for getting a pointer to the unescaped name
* @see keyGetUnescapedName() for getting a copy of the unescaped name
* @see keyGetNameSize() for getting the size of the escaped name
*/
ssize_t keyGetUnescapedNameSize (const Key * key)
{
if (!key) return -1;
if (!key->keyName) return 0;
return key->keyName->keyUSize;
}
/**
* Get abbreviated Key name (excluding owner).
*
* When there is not enough space to write the name,
* nothing will be written and -1 will be returned.
*
* @p maxSize is limited to SSIZE_MAX. When this value
* is exceeded, -1 will be returned. The reason for that
* is, that any value higher is just a negative return
* value passed by accident. elektraMalloc() is not
* as failure tolerant and would try to allocate memory
* accordingly.
*
* @code
char *getBack = elektraMalloc (keyGetNameSize(key));
keyGetName(key, getBack, keyGetNameSize(key));
* @endcode
*
* @param key the Key to get the name from
* @param returnedName pre-allocated buffer to write the Key's name
* @param maxSize maximum number of bytes that will fit in returnedName,
* including the NULL terminator
*
* @return number of bytes written to @p returnedName
* @retval 1 when only NULL terminator was written
* @retval -1 when Key's name is longer than maxSize or maxSize is 0 or maxSize
* is greater than SSIZE_MAX
* @retval -1 @p key or @p returnedName is NULL pointer
*
* @since 1.0.0
* @ingroup keyname
* @see keyGetNameSize() for getting the size of a Key's name
* @see keyName() for getting a pointer to a Key's name
* @see keyGetBaseName() for getting a Key's base name
* @see keyGetNamespace() for getting the namespace of a Key's name
*/
ssize_t keyGetName (const Key * key, char * returnedName, size_t maxSize)
{
if (!key) return -1;
if (!returnedName) return -1;
if (!maxSize) return -1;
if (maxSize > SSIZE_MAX) return -1;
if (!key->keyName || !key->keyName->key)
{
returnedName[0] = 0;
return 1;
}
if (key->keyName->keySize > maxSize)
{
return -1;
}
memcpy (returnedName, key->keyName->key, key->keyName->keySize);
return key->keyName->keySize;
}
/**
* Copies the unescaped name of a Key into @p returnedName.
*
* It will only copy the whole name. If the buffer is too small,
* an error code will be returned.
*
* To ensure the buffer is big enough, you can use keyGetUnescapedNameSize()
* to get the correct size.
*
* @param key the Key to extract the unescaped name from
* @param returnedName the buffer to write the unescaped name into
* @param maxSize maximum number of bytes that can be copied
* into @p returnedName
*
* @pre @p key MUST be a valid #Key and `key != NULL`
* @pre @p returnedName MUST be allocated to be at least @p maxSize bytes big
* @pre @p returnedName must not be NULL
*
* @returns the actual size of the Key's unescaped name, i.e. the number of
* bytes copied into @p returnedName
* @retval -1 Precondition error
* @retval -2 the size of the unescaped name is greater than @p maxSize
*
* @since 1.0.0
* @ingroup keyname
* @see keyGetUnescapedNameSize() for getting the size of the unescaped name
* @see keyGetName() for getting the Key's escaped name
*/
ssize_t keyGetUnescapedName (const Key * key, char * returnedName, size_t maxSize)
{
if (!key) return -1;
if (!returnedName) return -1;
if (!key->keyName || !key->keyName->ukey)
{
returnedName[0] = 0;
return 1;
}
if (key->keyName->keyUSize > maxSize)
{
return -2;
}
memcpy (returnedName, key->keyName->ukey, maxSize);
return key->keyName->keyUSize;
}
/**
* Set a new name to a Key.
*
* A valid name is one of the forms:
* @copydetails doxygenNamespaces
*
* An invalid name either has an invalid namespace or
* a wrongly escaped \\ at the end of the name.
*
* See @link keyname key names @endlink for the exact rules.
*
* The last form has explicitly set the owner, to let the library
* know in which user folder to save the Key. A owner is a user name.
* If it is not defined (the second form), current user is used.
*
* You should always follow the guidelines for Key tree structure creation.
*
* A private copy of the Key name will be stored, and the @p newName
* parameter can be freed after this call.
*
* .., . and / will be handled as in filesystem paths. A valid name will be build
* out of the (valid) name what you pass, e.g. user:///sw/../sw//././MyApp -> user:/sw/MyApp
*
* Trailing slashes will be stripped.
*
* On invalid names, the name stays unchanged.
*
* @return size of the new Key name in bytes, including NULL terminator
* @retval -1 if @p key or @p keyName is NULL or @p keyName is empty or invalid
* @retval -1 if Key was inserted to a KeySet before
* @retval -1 if Key name is read-only
*
* @param key the Key whose name to set
* @param newName the new name for the Key
*
* @since 1.0.0
* @ingroup keyname
* @see keyGetName() for getting a copy of the Key's name
* @see keyName() for getting a pointer to the Key's name
* @see keySetBaseName(), keyAddBaseName() for manipulating the base name
*/
ssize_t keySetName (Key * key, const char * newName)
{
if (!key) return -1;
if (key->hasReadOnlyName) return -1;
if (newName == NULL || strlen (newName) == 0) return -1;
if (!elektraKeyNameValidate (newName, true))
{
// error invalid name
return -1;
}
// from now on this function CANNOT fail -> we may modify the key
keyDetachKeyNameWithoutCopy (key);
elektraKeyNameCanonicalize (newName, &key->keyName->key, &key->keyName->keySize, 0, &key->keyName->keyUSize);
elektraRealloc ((void **) &key->keyName->ukey, key->keyName->keyUSize);
elektraKeyNameUnescape (key->keyName->key, key->keyName->ukey);
return key->keyName->keySize;
}
/**
* Add an already escaped name part to the Key's name.
*
* The same way as in keySetName() this method finds the canonical pathname:
* - it will ignore /./
* - it will remove a level when /../ is used
* - it will remove multiple slashes ////
*
* For example:
* @snippet keyName.c add name
*
* Unlike keySetName() it adds relative to the previous name and
* cannot change the namespace of a Key.
* For example:
* @snippet keyName.c namespace
*
* The passed name needs to be valid according the @link keyname key name rules @endlink.
* It is not allowed to:
* - be empty
* - end with unequal number of \\
*
* @pre @p key MUST be a valid #Key
*
* @param key the Key where a name should be added
* @param newName the new name to add to the name of @p key
*
* @returns new size of the escaped name of @p key
* @retval -1 if `key == NULL` or `newName == NULL`
* @retval -1 @p newName is not a valid escaped name
* @retval -1 @p key is read-only
*
* @since 1.0.0
* @ingroup keyname
* @see keySetName() for setting a Key's name
* @see keyAddBaseName() for adding a basename to a Key
*/
ssize_t keyAddName (Key * key, const char * newName)
{
if (!key) return -1;
if (key->hasReadOnlyName) return -1;
if (!newName) return -1;
while (*newName == '/')
{
// skip leading slashes
++newName;
if (*newName == '.' && *(newName + 1) == '/')
{
// also skip /./ parts
newName += 2;
}
}
if (strlen (newName) == 0) return key->keyName->keySize;
if (!elektraKeyNameValidate (newName, false))
{
// error invalid name suffix
return -1;
}
// from now on this function CANNOT fail -> we may modify the key
keyDetachKeyName (key);
elektraKeyNameCanonicalize (newName, &key->keyName->key, &key->keyName->keySize, key->keyName->keySize, &key->keyName->keyUSize);
elektraRealloc ((void **) &key->keyName->ukey, key->keyName->keyUSize);
elektraKeyNameUnescape (key->keyName->key, key->keyName->ukey);
return key->keyName->keySize;
}
static size_t replacePrefix (char ** buffer, size_t size, size_t oldPrefixSize, const char * newPrefix, size_t newPrefixSize)
{
size_t newSize;
if (size == oldPrefixSize)
{
// overwrite everything
newSize = newPrefixSize;
elektraRealloc ((void **) buffer, newSize);
memcpy (*buffer, newPrefix, newPrefixSize);
}
else if (oldPrefixSize < newPrefixSize)
{
// grow, move, overwrite
newSize = size + (newPrefixSize - oldPrefixSize);
elektraRealloc ((void **) buffer, newSize);
memmove (*buffer + newPrefixSize, *buffer + oldPrefixSize, size - oldPrefixSize);
memcpy (*buffer, newPrefix, newPrefixSize);
}
else
{
// move, overwrite, shrink
newSize = size - (oldPrefixSize - newPrefixSize);
memmove (*buffer + newPrefixSize, *buffer + oldPrefixSize, size - oldPrefixSize);
memcpy (*buffer, newPrefix, newPrefixSize);
elektraRealloc ((void **) buffer, newSize);
}
return newSize;
}
/**
* Replaces a prefix of the key name of @p key.
*
* The function only modifies @p key, if is is below (or same as)
* @p oldPrefix (see keyIsBelowOrSame()) and they both have the
* same namespace (this is not always the case with keyIsBelowOrSame()).
*
* In simple terms this function operates as follows:
* 1. If before calling this function @p key and @p oldPrefix had the
* same name, then afterwards @p key will have the same name as
* @p newPrefix.
* 2. If @p key was in the same namespace as and below @p oldPrefix, then
* after calling this function @p key will be in the same namespace as
* and below @p newPrefix.
* 3. Otherwise @p key will not be modified.
*
* Note: We use `const Key *` arguments for the prefixes instead of
* `const char *` to ensure only valid key names can be passed as arguments.
*
* @param key The key that will be manipulated.
* @param oldPrefix The name of this key will be removed from the front
* of the name of @p key.
* @param newPrefix The name of this key will be added to the front of
* @p key, after the name of @p oldPrefix is removed.
*
* @retval -1 if @p key, @p oldPrefix or @p newPrefix are NULL
* or the name of @p key is marked as read-only
* @retval 0 if @p key is not below (or same as) @p oldPrefix,
* i.e. there is no prefix to replace
* @retval 1 if the prefix was sucessfully replaced
*/
int keyReplacePrefix (Key * key, const Key * oldPrefix, const Key * newPrefix)
{
if (key == NULL || oldPrefix == NULL || newPrefix == NULL) return -1;
if (key->hasReadOnlyName) return -1;
// check namespace manually, because keyIsBelowOrSame has special handling for cascading keys
if (keyGetNamespace (key) != keyGetNamespace (oldPrefix)) return 0;
if (keyIsBelowOrSame (oldPrefix, key) != 1) return 0;
// same prefix -> nothing to do
if (keyCmp (oldPrefix, newPrefix) == 0) return 1;
if (key->keyName->keyUSize == oldPrefix->keyName->keyUSize)
{
// key is same as oldPrefix -> just copy name
keyCopy (key, newPrefix, KEY_CP_NAME);
return 1;
}
keyDetachKeyName (key);
size_t oldSize, oldUSize;
if (oldPrefix->keyName->keyUSize == 3)
{
// oldPrefix is root key -> needs special handling
oldSize = oldPrefix->keyName->keySize - 2;
oldUSize = 2;
}
else
{
oldSize = oldPrefix->keyName->keySize - 1;
oldUSize = oldPrefix->keyName->keyUSize;
}
size_t newSize, newUSize;
if (newPrefix->keyName->keyUSize == 3)
{
// newPrefix is root key -> needs special handling
newSize = newPrefix->keyName->keySize - 2;
newUSize = 2;
}
else
{
newSize = newPrefix->keyName->keySize - 1;
newUSize = newPrefix->keyName->keyUSize;
}
key->keyName->keySize = replacePrefix (&key->keyName->key, key->keyName->keySize, oldSize, newPrefix->keyName->key, newSize);
key->keyName->keyUSize = replacePrefix (&key->keyName->ukey, key->keyName->keyUSize, oldUSize, newPrefix->keyName->ukey, newUSize);
return 1;
}
/**
* Takes an escaped key name and validates it.
* Complete key names must inlcude a namespace or a leading slash.
*
* @param name The escaped key name to check
* @param isComplete Whether or not @p name is supposed to be a complete key name
*
* @retval #true If @p name is a valid key name.
* @retval #false Otherwise
*
* @ingroup keyname
*/
bool elektraKeyNameValidate (const char * name, bool isComplete)
{
if (name == NULL || (strlen (name) == 0 && isComplete)) return 0;
if (isComplete)
{
const char * colonOrSlash = strpbrk (name, ":/");
if (colonOrSlash == NULL || *colonOrSlash == '/')
{
// if colonOrSlash == NULL the following is always true
if (colonOrSlash != name)
{
ELEKTRA_LOG_DEBUG ("No namespace (and not cascading) or missing colon (:) after namespace: %s", name);
return false;
}
}
else
{
const char * colon = colonOrSlash;
if (elektraReadNamespace (name, colon - name) == KEY_NS_NONE)
{
ELEKTRA_LOG_DEBUG ("Illegal namespace '%.*s': %s", (int) (colon - name - 1), name, name);
return false;
}
if (*(colon + 1) != '/')
{
ELEKTRA_LOG_DEBUG ("Missing slash after namespace: %s", name);
return false;
}
name = colon + 1;
}
}
const char * cur = name;
while ((cur = strchr (cur, '\\')) != NULL)
{
++cur;
switch (*cur)
{
case '\0':
ELEKTRA_LOG_DEBUG ("Dangling escape: %s", name);
return false;
case '\\':
case '/':
++cur;
// allowed anywhere
continue;
case '%':
if (*(cur - 2) == '/' && (*(cur + 1) == '/' || *(cur + 1) == '\0')) continue;
break;
case '.':
if (*(cur - 2) == '/' && (*(cur + 1) == '/' || *(cur + 1) == '\0')) continue;
if (*(cur - 2) == '/' && *(cur + 1) == '.' && (*(cur + 2) == '/' || *(cur + 2) == '\0')) continue;
break;
case '#': {
const char * end = cur + 1;
while (isdigit (*end))
{
++end;
}
size_t len = end - cur;
bool check1 = *end == '/' || *end == '\0';
bool check2 = len < 20 || strncmp (cur + 1, "9223372036854775807", 19) <= 0;
bool check3 = *(cur + 1) != '0';
if (check1 && check2 && check3) continue;
break;
}
}
ELEKTRA_LOG_DEBUG ("Illegal escape '\\%c': %s", *cur, name);
return false;
}
return true;
}
/**
* Takes a valid (non-)canonical key name and produces its canonical form.
* As a side-effect it can also calculate the size of the corresponding unescaped key name.
*
* @param name The key name that is processed
* @param canonicalName Output buffer for the canonical name
* @param canonicalSizePtr Pointer to size of @p canonicalName
* @param offset Offset into @p canonicalName
* @param usizePtr Output variable for the size of the unescaped name
*
* @pre @p name MUST be a valid (non-)canonical key name. If it is not, the result is undefined
* @pre @p canonicalName MUST be a valid first argument for elektraRealloc() when cast to void**