-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpcache.c
1710 lines (1655 loc) · 53.1 KB
/
pcache.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
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2012 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "libtecla.h"
#include "pathutil.h"
#include "homedir.h"
#include "freelist.h"
#include "direader.h"
#include "stringrp.h"
#include "errmsg.h"
/*
* The new_PcaPathConf() constructor sets the integer first member of
* the returned object to the following magic number. This is then
* checked for by pca_path_completions() as a sanity check.
*/
#define PPC_ID_CODE 4567
/*
* A pointer to a structure of the following type can be passed to
* the builtin path-completion callback function to modify its behavior.
*/
struct PcaPathConf {
int id; /* This is set to PPC_ID_CODE by new_PcaPathConf() */
PathCache *pc; /* The path-list cache in which to look up the executables */
int escaped; /* If non-zero, backslashes in the input line are */
/* interpreted as escaping special characters and */
/* spaces, and any special characters and spaces in */
/* the listed completions will also be escaped with */
/* added backslashes. This is the default behaviour. */
/* If zero, backslashes are interpreted as being */
/* literal parts of the file name, and none are added */
/* to the completion suffixes. */
int file_start; /* The index in the input line of the first character */
/* of the file name. If you specify -1 here, */
/* pca_path_completions() identifies the */
/* the start of the file by looking backwards for */
/* an unescaped space, or the beginning of the line. */
};
/*
* Prepended to each chached filename is a character which contains
* one of the following status codes. When a given filename (minus
* this byte) is passed to the application's check_fn(), the result
* is recorded in this byte, such that the next time it is looked
* up, we don't have to call check_fn() again. These codes are cleared
* whenever the path is scanned and whenever the check_fn() callback
* is changed.
*/
typedef enum {
PCA_F_ENIGMA='?', /* The file remains to be checked */
PCA_F_WANTED='+', /* The file has been selected by the caller's callback */
PCA_F_IGNORE='-' /* The file has been rejected by the caller's callback */
} PcaFileStatus;
/*
* Encapsulate the memory management objects which supply memoy for
* the arrays of filenames.
*/
typedef struct {
StringGroup *sg; /* The memory used to record the names of files */
size_t files_dim; /* The allocated size of files[] */
char **files; /* Memory for 'files_dim' pointers to files */
size_t nfiles; /* The number of filenames currently in files[] */
} CacheMem;
static CacheMem *new_CacheMem(void);
static CacheMem *del_CacheMem(CacheMem *cm);
static void rst_CacheMem(CacheMem *cm);
/*
* Lists of nodes of the following type are used to record the
* names and contents of individual directories.
*/
typedef struct PathNode PathNode;
struct PathNode {
PathNode *next; /* The next directory in the path */
int relative; /* True if the directory is a relative pathname */
CacheMem *mem; /* The memory used to store dir[] and files[] */
char *dir; /* The directory pathname (stored in pc->sg) */
int nfile; /* The number of filenames stored in 'files' */
char **files; /* Files of interest in the current directory, */
/* or NULL if dir[] is a relative pathname */
/* who's contents can't be cached. This array */
/* and its contents are taken from pc->abs_mem */
/* or pc->rel_mem */
};
/*
* Append a new node to the list of directories in the path.
*/
static int add_PathNode(PathCache *pc, const char *dirname);
/*
* Set the maximum length allowed for usernames.
* names.
*/
#define USR_LEN 100
/*
* PathCache objects encapsulate the resources needed to record
* files of interest from comma-separated lists of directories.
*/
struct PathCache {
ErrMsg *err; /* The error reporting buffer */
FreeList *node_mem; /* A free-list of PathNode objects */
CacheMem *abs_mem; /* Memory for the filenames of absolute paths */
CacheMem *rel_mem; /* Memory for the filenames of relative paths */
PathNode *head; /* The head of the list of directories in the */
/* path, or NULL if no path has been scanned yet. */
PathNode *tail; /* The tail of the list of directories in the */
/* path, or NULL if no path has been scanned yet. */
PathName *path; /* The fully qualified name of a file */
HomeDir *home; /* Home-directory lookup object */
DirReader *dr; /* A portable directory reader */
CplFileConf *cfc; /* Configuration parameters to pass to */
/* cpl_file_completions() */
CplCheckFn *check_fn; /* The callback used to determine if a given */
/* filename should be recorded in the cache. */
void *data; /* Annonymous data to be passed to pc->check_fn() */
char usrnam[USR_LEN+1];/* The buffer used when reading the names of */
/* users. */
};
/*
* Empty the cache.
*/
static void pca_clear_cache(PathCache *pc);
/*
* Read a username from string[] and record it in pc->usrnam[].
*/
static int pca_read_username(PathCache *pc, const char *string, int slen,
int literal, const char **nextp);
/*
* Extract the next component of a colon separated list of directory
* paths.
*/
static int pca_extract_dir(PathCache *pc, const char *path,
const char **nextp);
/*
* Scan absolute directories for files of interest, recording their names
* in mem->sg and recording pointers to these names in mem->files[].
*/
static int pca_scan_dir(PathCache *pc, const char *dirname, CacheMem *mem);
/*
* A qsort() comparison function for comparing the cached filename
* strings pointed to by two (char **) array elements. Note that
* this ignores the initial cache-status byte of each filename.
*/
static int pca_cmp_matches(const void *v1, const void *v2);
/*
* A qsort() comparison function for comparing a filename
* against an element of an array of pointers to filename cache
* entries.
*/
static int pca_cmp_file(const void *v1, const void *v2);
/*
* Initialize a PcaPathConf configuration objects with the default
* options.
*/
static int pca_init_PcaPathConf(PcaPathConf *ppc, PathCache *pc);
/*
* Make a copy of a completion suffix, suitable for passing to
* cpl_add_completion().
*/
static int pca_prepare_suffix(PathCache *pc, const char *suffix,
int add_escapes);
/*
* Return non-zero if the specified string appears to start with a pathname.
*/
static int cpa_cmd_contains_path(const char *prefix, int prefix_len);
/*
* Return a given prefix with escapes optionally removed.
*/
static const char *pca_prepare_prefix(PathCache *pc, const char *prefix,
size_t prefix_len, int escaped);
/*
* If there is a tilde expression at the beginning of the specified path,
* place the corresponding home directory into pc->path. Otherwise
* just clear pc->path.
*/
static int pca_expand_tilde(PathCache *pc, const char *path, int pathlen,
int literal, const char **endp);
/*
* Clear the filename status codes that are recorded before each filename
* in the cache.
*/
static void pca_remove_marks(PathCache *pc);
/*
* Specify how many PathNode's to allocate at a time.
*/
#define PATH_NODE_BLK 30
/*
* Specify the amount by which the files[] arrays are to be extended
* whenever they are found to be too small.
*/
#define FILES_BLK_FACT 256
/*.......................................................................
* Create a new object who's function is to maintain a cache of
* filenames found within a list of directories, and provide quick
* lookup and completion of selected files in this cache.
*
* Output:
* return PathCache * The new, initially empty cache, or NULL
* on error.
*/
PathCache *new_PathCache(void)
{
PathCache *pc; /* The object to be returned */
/*
* Allocate the container.
*/
pc = (PathCache *)malloc(sizeof(PathCache));
if(!pc) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_PathCache().
*/
pc->err = NULL;
pc->node_mem = NULL;
pc->abs_mem = NULL;
pc->rel_mem = NULL;
pc->head = NULL;
pc->tail = NULL;
pc->path = NULL;
pc->home = NULL;
pc->dr = NULL;
pc->cfc = NULL;
pc->check_fn = 0;
pc->data = NULL;
pc->usrnam[0] = '\0';
/*
* Allocate a place to record error messages.
*/
pc->err = _new_ErrMsg();
if(!pc->err)
return del_PathCache(pc);
/*
* Allocate the freelist of directory list nodes.
*/
pc->node_mem = _new_FreeList(sizeof(PathNode), PATH_NODE_BLK);
if(!pc->node_mem)
return del_PathCache(pc);
/*
* Allocate memory for recording names of files in absolute paths.
*/
pc->abs_mem = new_CacheMem();
if(!pc->abs_mem)
return del_PathCache(pc);
/*
* Allocate memory for recording names of files in relative paths.
*/
pc->rel_mem = new_CacheMem();
if(!pc->rel_mem)
return del_PathCache(pc);
/*
* Allocate a pathname buffer.
*/
pc->path = _new_PathName();
if(!pc->path)
return del_PathCache(pc);
/*
* Allocate an object for looking up home-directories.
*/
pc->home = _new_HomeDir();
if(!pc->home)
return del_PathCache(pc);
/*
* Allocate an object for reading directories.
*/
pc->dr = _new_DirReader();
if(!pc->dr)
return del_PathCache(pc);
/*
* Allocate a cpl_file_completions() configuration object.
*/
pc->cfc = new_CplFileConf();
if(!pc->cfc)
return del_PathCache(pc);
/*
* Configure cpl_file_completions() to use check_fn() to select
* files of interest.
*/
cfc_set_check_fn(pc->cfc, pc->check_fn, pc->data);
/*
* Return the cache, ready for use.
*/
return pc;
}
/*.......................................................................
* Delete a given cache of files, returning the resources that it
* was using to the system.
*
* Input:
* pc PathCache * The cache to be deleted (can be NULL).
* Output:
* return PathCache * The deleted object (ie. allways NULL).
*/
PathCache *del_PathCache(PathCache *pc)
{
if(pc) {
/*
* Delete the error message buffer.
*/
pc->err = _del_ErrMsg(pc->err);
/*
* Delete the memory of the list of path nodes.
*/
pc->node_mem = _del_FreeList(pc->node_mem, 1);
/*
* Delete the memory used to record filenames.
*/
pc->abs_mem = del_CacheMem(pc->abs_mem);
pc->rel_mem = del_CacheMem(pc->rel_mem);
/*
* The list of PathNode's was already deleted when node_mem was
* deleted.
*/
pc->head = NULL;
pc->tail = NULL;
/*
* Delete the pathname buffer.
*/
pc->path = _del_PathName(pc->path);
/*
* Delete the home-directory lookup object.
*/
pc->home = _del_HomeDir(pc->home);
/*
* Delete the directory reader.
*/
pc->dr = _del_DirReader(pc->dr);
/*
* Delete the cpl_file_completions() config object.
*/
pc->cfc = del_CplFileConf(pc->cfc);
/*
* Delete the container.
*/
free(pc);
};
return NULL;
}
/*.......................................................................
* If you want subsequent calls to pca_lookup_file() and
* pca_path_completions() to only return the filenames of certain
* types of files, for example executables, or filenames ending in
* ".ps", call this function to register a file-selection callback
* function. This callback function takes the full pathname of a file,
* plus application-specific data, and returns 1 if the file is of
* interest, and zero otherwise.
*
* Input:
* pc PathCache * The filename cache.
* check_fn CplCheckFn * The function to call to see if the name of
* a given file should be included in the
* cache. This determines what type of files
* will reside in the cache. To revert to
* selecting all files, regardless of type,
* pass 0 here.
* data void * You can pass a pointer to anything you
* like here, including NULL. It will be
* passed to your check_fn() callback
* function, for its private use.
*/
void pca_set_check_fn(PathCache *pc, CplCheckFn *check_fn, void *data)
{
if(pc) {
/*
* If the callback or its data pointer have changed, clear the cached
* statuses of files that were accepted or rejected by the previous
* calback.
*/
if(check_fn != pc->check_fn || data != pc->data)
pca_remove_marks(pc);
/*
* Record the new callback locally.
*/
pc->check_fn = check_fn;
pc->data = data;
/*
* Configure cpl_file_completions() to use the same callback to
* select files of interest.
*/
cfc_set_check_fn(pc->cfc, check_fn, data);
};
return;
}
/*.......................................................................
* Return a description of the last path-caching error that occurred.
*
* Input:
* pc PathCache * The filename cache that suffered the error.
* Output:
* return char * The description of the last error.
*/
const char *pca_last_error(PathCache *pc)
{
return pc ? _err_get_msg(pc->err) : "NULL PathCache argument";
}
/*.......................................................................
* Discard all cached filenames.
*
* Input:
* pc PathCache * The cache to be cleared.
*/
static void pca_clear_cache(PathCache *pc)
{
if(pc) {
/*
* Return all path-nodes to the freelist.
*/
_rst_FreeList(pc->node_mem);
pc->head = pc->tail = NULL;
/*
* Delete all filename strings.
*/
rst_CacheMem(pc->abs_mem);
rst_CacheMem(pc->rel_mem);
};
return;
}
/*.......................................................................
* Build the list of files of interest contained in a given
* colon-separated list of directories.
*
* Input:
* pc PathCache * The cache in which to store the names of
* the files that are found in the list of
* directories.
* path const char * A colon-separated list of directory
* paths. Under UNIX, when searching for
* executables, this should be the return
* value of getenv("PATH").
* Output:
* return int 0 - OK.
* 1 - An error occurred. A description of
* the error can be acquired by calling
* pca_last_error(pc).
*/
int pca_scan_path(PathCache *pc, const char *path)
{
const char *pptr; /* A pointer to the next unprocessed character in path[] */
PathNode *node; /* A node in the list of directory paths */
char **fptr; /* A pointer into pc->abs_mem->files[] */
/*
* Check the arguments.
*/
if(!pc)
return 1;
/*
* Clear the outdated contents of the cache.
*/
pca_clear_cache(pc);
/*
* If no path list was provided, there is nothing to be added to the
* cache.
*/
if(!path)
return 0;
/*
* Extract directories from the path list, expanding tilde expressions
* on the fly into pc->pathname, then add them to the list of path
* nodes, along with a sorted list of the filenames of interest that
* the directories hold.
*/
pptr = path;
while(*pptr) {
/*
* Extract the next pathname component into pc->path->name.
*/
if(pca_extract_dir(pc, pptr, &pptr))
return 1;
/*
* Add a new node to the list of paths, containing both the
* directory name and, if not a relative pathname, the list of
* files of interest in the directory.
*/
if(add_PathNode(pc, pc->path->name))
return 1;
};
/*
* The file arrays in each absolute directory node are sections of
* pc->abs_mem->files[]. Record pointers to the starts of each
* of these sections in each directory node. Note that this couldn't
* be done in add_PathNode(), because pc->abs_mem->files[] may
* get reallocated in subsequent calls to add_PathNode(), thus
* invalidating any pointers to it.
*/
fptr = pc->abs_mem->files;
for(node=pc->head; node; node=node->next) {
node->files = fptr;
fptr += node->nfile;
};
return 0;
}
/*.......................................................................
* Extract the next directory path from a colon-separated list of
* directories, expanding tilde home-directory expressions where needed.
*
* Input:
* pc PathCache * The cache of filenames.
* path const char * A pointer to the start of the next component
* in the path list.
* Input/Output:
* nextp const char ** A pointer to the next unprocessed character
* in path[] will be assigned to *nextp.
* Output:
* return int 0 - OK. The extracted path is in pc->path->name.
* 1 - Error. A description of the error will
* have been left in pc->err.
*/
static int pca_extract_dir(PathCache *pc, const char *path, const char **nextp)
{
const char *pptr; /* A pointer into path[] */
const char *sptr; /* The path following tilde expansion */
int escaped = 0; /* True if the last character was a backslash */
/*
* If there is a tilde expression at the beginning of the specified path,
* place the corresponding home directory into pc->path. Otherwise
* just clear pc->path.
*/
if(pca_expand_tilde(pc, path, strlen(path), 0, &pptr))
return 1;
/*
* Keep a record of the current location in the path.
*/
sptr = pptr;
/*
* Locate the end of the directory name in the pathname string, stopping
* when either the end of the string is reached, or an un-escaped colon
* separator is seen.
*/
while(*pptr && (escaped || *pptr != ':'))
escaped = !escaped && *pptr++ == '\\';
/*
* Append the rest of the directory path to the pathname buffer.
*/
if(_pn_append_to_path(pc->path, sptr, pptr - sptr, 1) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to record directory name",
END_ERR_MSG);
return 1;
};
/*
* To facilitate subsequently appending filenames to the directory
* path name, make sure that the recorded directory name ends in a
* directory separator.
*/
{
int dirlen = strlen(pc->path->name);
if(dirlen < FS_DIR_SEP_LEN ||
strncmp(pc->path->name + dirlen - FS_DIR_SEP_LEN, FS_DIR_SEP,
FS_DIR_SEP_LEN) != 0) {
if(_pn_append_to_path(pc->path, FS_DIR_SEP, FS_DIR_SEP_LEN, 0) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to record directory name",
END_ERR_MSG);
return 1;
};
};
};
/*
* Skip the separator unless we have reached the end of the path.
*/
if(*pptr==':')
pptr++;
/*
* Return the unprocessed tail of the path-list string.
*/
*nextp = pptr;
return 0;
}
/*.......................................................................
* Read a username, stopping when a directory separator is seen, a colon
* separator is seen, the end of the string is reached, or the username
* buffer overflows.
*
* Input:
* pc PathCache * The cache of filenames.
* string char * The string who's prefix contains the name.
* slen int The max number of characters to read from string[].
* literal int If true, treat backslashes as literal characters
* instead of escapes.
* Input/Output:
* nextp char ** A pointer to the next unprocessed character
* in string[] will be assigned to *nextp.
* Output:
* return int 0 - OK. The username can be found in pc->usrnam.
* 1 - Error. A description of the error message
* can be found in pc->err.
*/
static int pca_read_username(PathCache *pc, const char *string, int slen,
int literal, const char **nextp)
{
int usrlen; /* The number of characters in pc->usrnam[] */
const char *sptr; /* A pointer into string[] */
int escaped = 0; /* True if the last character was a backslash */
/*
* Extract the username.
*/
for(sptr=string,usrlen=0; usrlen < USR_LEN && (sptr-string) < slen; sptr++) {
/*
* Stop if the end of the string is reached, or a directory separator
* or un-escaped colon separator is seen.
*/
if(!*sptr || strncmp(sptr, FS_DIR_SEP, FS_DIR_SEP_LEN)==0 ||
(!escaped && *sptr == ':'))
break;
/*
* Escape the next character?
*/
if(!literal && !escaped && *sptr == '\\') {
escaped = 1;
} else {
escaped = 0;
pc->usrnam[usrlen++] = *sptr;
};
};
/*
* Did the username overflow the buffer?
*/
if(usrlen >= USR_LEN) {
_err_record_msg(pc->err, "Username too long", END_ERR_MSG);
return 1;
};
/*
* Terminate the string.
*/
pc->usrnam[usrlen] = '\0';
/*
* Indicate where processing of the input string should continue.
*/
*nextp = sptr;
return 0;
}
/*.......................................................................
* Create a new CacheMem object.
*
* Output:
* return CacheMem * The new object, or NULL on error.
*/
static CacheMem *new_CacheMem(void)
{
CacheMem *cm; /* The object to be returned */
/*
* Allocate the container.
*/
cm = (CacheMem *)malloc(sizeof(CacheMem));
if(!cm) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to del_CacheMem().
*/
cm->sg = NULL;
cm->files_dim = 0;
cm->files = NULL;
cm->nfiles = 0;
/*
* Allocate a list of string segments for storing filenames.
*/
cm->sg = _new_StringGroup(_pu_pathname_dim());
if(!cm->sg)
return del_CacheMem(cm);
/*
* Allocate an array of pointers to filenames.
* This will be extended later if needed.
*/
cm->files_dim = FILES_BLK_FACT;
cm->files = (char **) malloc(sizeof(*cm->files) * cm->files_dim);
if(!cm->files) {
errno = ENOMEM;
return del_CacheMem(cm);
};
return cm;
}
/*.......................................................................
* Delete a CacheMem object.
*
* Input:
* cm CacheMem * The object to be deleted.
* Output:
* return CacheMem * The deleted object (always NULL).
*/
static CacheMem *del_CacheMem(CacheMem *cm)
{
if(cm) {
/*
* Delete the memory that was used to record filename strings.
*/
cm->sg = _del_StringGroup(cm->sg);
/*
* Delete the array of pointers to filenames.
*/
cm->files_dim = 0;
if(cm->files) {
free(cm->files);
cm->files = NULL;
};
/*
* Delete the container.
*/
free(cm);
};
return NULL;
}
/*.......................................................................
* Re-initialize the memory used to allocate filename strings.
*
* Input:
* cm CacheMem * The memory cache to be cleared.
*/
static void rst_CacheMem(CacheMem *cm)
{
_clr_StringGroup(cm->sg);
cm->nfiles = 0;
return;
}
/*.......................................................................
* Append a new directory node to the list of directories read from the
* path.
*
* Input:
* pc PathCache * The filename cache.
* dirname const char * The name of the new directory.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int add_PathNode(PathCache *pc, const char *dirname)
{
PathNode *node; /* The new directory list node */
int relative; /* True if dirname[] is a relative pathname */
/*
* Have we been passed a relative pathname or an absolute pathname?
*/
relative = strncmp(dirname, FS_ROOT_DIR, FS_ROOT_DIR_LEN) != 0;
/*
* If it's an absolute pathname, ignore it if the corresponding
* directory doesn't exist.
*/
if(!relative && !_pu_path_is_dir(dirname))
return 0;
/*
* Allocate a new list node to record the specifics of the new directory.
*/
node = (PathNode *) _new_FreeListNode(pc->node_mem);
if(!node) {
_err_record_msg(pc->err, "Insufficient memory to cache new directory.",
END_ERR_MSG);
return 1;
};
/*
* Initialize the node.
*/
node->next = NULL;
node->relative = relative;
node->mem = relative ? pc->rel_mem : pc->abs_mem;
node->dir = NULL;
node->nfile = 0;
node->files = NULL;
/*
* Make a copy of the directory pathname.
*/
node->dir = _sg_store_string(pc->abs_mem->sg, dirname, 0);
if(!node->dir) {
_err_record_msg(pc->err, "Insufficient memory to store directory name.",
END_ERR_MSG);
return 1;
};
/*
* Scan absolute directories for files of interest, recording their names
* in node->mem->sg and appending pointers to these names to the
* node->mem->files[] array.
*/
if(!node->relative) {
int nfile = node->nfile = pca_scan_dir(pc, node->dir, node->mem);
if(nfile < 1) { /* No files matched or an error occurred */
node = (PathNode *) _del_FreeListNode(pc->node_mem, node);
return nfile < 0;
};
};
/*
* Append the new node to the list.
*/
if(pc->head) {
pc->tail->next = node;
pc->tail = node;
} else {
pc->head = pc->tail = node;
};
return 0;
}
/*.......................................................................
* Scan a given directory for files of interest, record their names
* in mem->sg and append pointers to them to the mem->files[] array.
*
* Input:
* pc PathCache * The filename cache.
* dirname const char * The pathname of the directory to be scanned.
* mem CacheMem * The memory in which to store filenames of
* interest.
* Output:
* return int The number of files recorded, or -1 if a
* memory error occurs. Note that the
* inability to read the contents of the
* directory is not counted as an error.
*/
static int pca_scan_dir(PathCache *pc, const char *dirname, CacheMem *mem)
{
int nfile = 0; /* The number of filenames recorded */
const char *filename; /* The name of the file being looked at */
/*
* Attempt to open the directory. If the directory can't be read then
* there are no accessible files of interest in the directory.
*/
if(_dr_open_dir(pc->dr, dirname, NULL))
return 0;
/*
* Record the names of all files in the directory in the cache.
*/
while((filename = _dr_next_file(pc->dr))) {
char *copy; /* A copy of the filename */
/*
* Make a temporary copy of the filename with an extra byte prepended.
*/
_pn_clear_path(pc->path);
if(_pn_append_to_path(pc->path, " ", 1, 0) == NULL ||
_pn_append_to_path(pc->path, filename, -1, 1) == NULL) {
_err_record_msg(pc->err, "Insufficient memory to record filename",
END_ERR_MSG);
return -1;
};
/*
* Store the filename.
*/
copy = _sg_store_string(mem->sg, pc->path->name, 0);
if(!copy) {
_err_record_msg(pc->err, "Insufficient memory to cache file name.",
END_ERR_MSG);
return -1;
};
/*
* Mark the filename as unchecked.
*/
copy[0] = PCA_F_ENIGMA;
/*
* Make room to store a pointer to the copy in mem->files[].
*/
if(mem->nfiles + 1 > mem->files_dim) {
int needed = mem->files_dim + FILES_BLK_FACT;
char **files = (char **) realloc(mem->files, sizeof(*mem->files)*needed);
if(!files) {
_err_record_msg(pc->err,
"Insufficient memory to extend filename cache.",
END_ERR_MSG);
return 1;
};
mem->files = files;
mem->files_dim = needed;
};
/*
* Record a pointer to the copy of the filename at the end of the files[]
* array.
*/
mem->files[mem->nfiles++] = copy;
/*
* Keep a record of the number of files matched so far.
*/
nfile++;
};
/*
* Sort the list of files into lexical order.
*/
qsort(mem->files + mem->nfiles - nfile, nfile, sizeof(*mem->files),
pca_cmp_matches);
/*
* Return the number of files recorded in mem->files[].
*/
return nfile;
}
/*.......................................................................
* A qsort() comparison function for comparing the cached filename
* strings pointed to by two (char **) array elements. Note that
* this ignores the initial cache-status byte of each filename.
*
* Input:
* v1, v2 void * Pointers to the pointers of two strings to be compared.
* Output:
* return int -1 -> v1 < v2.
* 0 -> v1 == v2
* 1 -> v1 > v2
*/
static int pca_cmp_matches(const void *v1, const void *v2)
{
const char **s1 = (const char **) v1;
const char **s2 = (const char **) v2;
return strcmp(*s1+1, *s2+1);
}
/*.......................................................................
* Given the simple name of a file, search the cached list of files
* in the order in which they where found in the list of directories
* previously presented to pca_scan_path(), and return the pathname
* of the first file which has this name. If a pathname to a file is
* given instead of a simple filename, this is returned without being
* looked up in the cache, but with any initial ~username expression
* expanded, and optionally, unescaped backslashes removed.
*
* Input:
* pc PathCache * The cached list of files.
* name const char * The name of the file to lookup.
* name_len int The length of the filename string at the
* beginning of name[], or -1 to indicate that
* the filename occupies the whole of the
* string.
* literal int If this argument is zero, lone backslashes
* in name[] are ignored during comparison
* with filenames in the cache, under the
* assumption that they were in the input line
* soley to escape the special significance of
* characters like spaces. To have them treated
* as normal characters, give this argument a
* non-zero value, such as 1.
* Output:
* return char * The pathname of the first matching file,
* or NULL if not found. Note that the returned