a7a418d189b1d5fdd517299e44edd85414458d2e
[debian/amanda] / common-src / file.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1997-1998 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Author: AMANDA core development group.
24  */
25 /*
26  * $Id: file.c,v 1.14.4.6.4.2.2.5 2003/01/01 23:28:52 martinea Exp $
27  *
28  * file and directory bashing routines
29  */
30
31 #include "amanda.h"
32 #include "util.h"
33
34 uid_t client_uid = (uid_t) -1;
35 gid_t client_gid = (gid_t) -1;
36
37 /* Make a directory (internal function).
38 ** If the directory already exists then we pretend we created it.
39 ** XXX - I'm not sure about the use of the chown() stuff.  On most systems
40 **       it will do nothing - only root is permitted to change the owner
41 **       of a file.
42 */
43 int mk1dir(dir, mode, uid, gid)
44 char *dir;      /* directory to create */
45 int mode;       /* mode for new directory */
46 uid_t uid;      /* uid for new directory */
47 gid_t gid;      /* gid for new directory */
48 {
49     int rc;     /* return code */
50
51     rc = 0;     /* assume the best */
52
53     if(mkdir(dir, mode) == 0) {
54         chmod(dir, mode);       /* mkdir() is affected by the umask */
55         chown(dir, uid, gid);   /* XXX - no-op on most systems? */
56     } else {                    /* maybe someone beat us to it */
57         int serrno;
58
59         serrno = errno;
60         if(access(dir, F_OK) != 0) rc = -1;
61         errno = serrno; /* pass back the real error */
62     }
63
64     return rc;
65 }
66
67
68 /*
69  * Make a directory hierarchy given an entry to be created (by the caller)
70  * in the new target.  In other words, create all the directories down to
71  * the last element, but not the last element.  So a (potential) file name
72  * may be passed to mkpdir and all the parents of that file will be created.
73  */
74 int mkpdir(file, mode, uid, gid)
75 char *file;     /* file to create parent directories for */
76 int mode;       /* mode for new directories */
77 uid_t uid;      /* uid for new directories */
78 gid_t gid;      /* gid for new directories */
79 {
80     char *dir = NULL, *p;
81     int rc;     /* return code */
82
83     rc = 0;
84
85     dir = stralloc(file);       /* make a copy we can play with */
86
87     p = strrchr(dir, '/');
88     if(p != dir && p != NULL) { /* got a '/' or a simple name */
89         *p = '\0';
90
91         if(access(dir, F_OK) != 0) {    /* doesn't exist */
92             if(mkpdir(dir, mode, uid, gid) != 0 ||
93                mk1dir(dir, mode, uid, gid) != 0) rc = -1; /* create failed */
94         }
95     }
96
97     amfree(dir);
98     return rc;
99 }
100
101
102 /* Remove as much of a directory hierarchy as possible.
103 ** Notes:
104 **  - assumes that rmdir() on a non-empty directory will fail!
105 **  - stops deleting before topdir, ie: topdir will not be removed
106 **  - if file is not under topdir this routine will not notice
107 */
108 int rmpdir(file, topdir)
109 char *file;     /* directory hierarchy to remove */
110 char *topdir;   /* where to stop removing */
111 {
112     int rc;
113     char *p, *dir = NULL;
114
115     if(strcmp(file, topdir) == 0) return 0; /* all done */
116
117     rc = rmdir(file);
118     if (rc != 0) switch(errno) {
119 #ifdef ENOTEMPTY
120 #if ENOTEMPTY != EEXIST                 /* AIX makes these the same */
121         case ENOTEMPTY:
122 #endif
123 #endif
124         case EEXIST:    /* directory not empty */
125             return 0; /* cant do much more */
126         case ENOENT:    /* it has already gone */
127             rc = 0; /* ignore */
128             break;
129         case ENOTDIR:   /* it was a file */
130             rc = unlink(file);
131             break;
132         }
133
134     if(rc != 0) return -1; /* unexpected error */
135
136     dir = stralloc(file);
137
138     p = strrchr(dir, '/');
139     if(p == dir) rc = 0; /* no /'s */
140     else {
141         *p = '\0';
142
143         rc = rmpdir(dir, topdir);
144     }
145
146     amfree(dir);
147
148     return rc;
149 }
150
151
152 /*
153  *=====================================================================
154  * Do Amanda setup for all programs.
155  *
156  * void amanda_setup (int argc, char **argv, int setup_flags)
157  *
158  * entry:       setup_flags (see AMANDA_SETUP_FLAG_xxx)
159  * exit:        none
160  *=====================================================================
161  */
162
163 void
164 amanda_setup (argc, argv, setup_flags)
165     int                 argc;
166     char                **argv;
167     int                 setup_flags;
168 {
169 }
170
171 /*
172  *=====================================================================
173  * Change directory to a "safe" location and set some base environment.
174  *
175  * void safe_cd (void)
176  *
177  * entry:       client_uid and client_gid set to CLIENT_LOGIN information
178  * exit:        none
179  *
180  * Set a default umask of 0077.
181  *
182  * Create the Amada debug directory (if defined) and the Amanda temp
183  * directory.
184  *
185  * Try to chdir to the Amanda debug directory first, but it must be owned
186  * by the Amanda user and not allow rwx to group or other.  Otherwise,
187  * try the same thing to the Amanda temp directory.
188  *
189  * If that is all OK, call save_core().
190  *
191  * Otherwise, cd to "/" so if we take a signal we cannot drop core
192  * unless the system administrator has made special arrangements (e.g.
193  * pre-created a core file with the right ownership and permissions).
194  *=====================================================================
195  */
196
197 void
198 safe_cd()
199 {
200     int                 cd_ok = 0;
201     struct stat         sbuf;
202     struct passwd       *pwent;
203     char                *d;
204
205     if(client_uid == (uid_t) -1 && (pwent = getpwnam(CLIENT_LOGIN)) != NULL) {
206         client_uid = pwent->pw_uid;
207         client_gid = pwent->pw_gid;
208         endpwent();
209     }
210
211     (void) umask(0077);
212
213     if (client_uid != (uid_t) -1) {
214 #if defined(AMANDA_DBGDIR)
215         d = stralloc2(AMANDA_DBGDIR, "/.");
216         (void) mkpdir(d, 02700, client_uid, client_gid);
217         amfree(d);
218 #endif
219         d = stralloc2(AMANDA_TMPDIR, "/.");
220         (void) mkpdir(d, 02700, client_uid, client_gid);
221         amfree(d);
222     }
223
224 #if defined(AMANDA_DBGDIR)
225     if (chdir(AMANDA_DBGDIR) != -1
226         && stat(".", &sbuf) != -1
227         && (sbuf.st_mode & 0777) == 0700        /* drwx------ */
228         && sbuf.st_uid == client_uid) {         /* owned by Amanda user */
229         cd_ok = 1;                              /* this is a good place to be */
230     }
231 #endif
232     if (! cd_ok
233         && chdir(AMANDA_TMPDIR) != -1
234         && stat(".", &sbuf) != -1
235         && (sbuf.st_mode & 0777) == 0700        /* drwx------ */
236         && sbuf.st_uid == client_uid) {         /* owned by Amanda user */
237         cd_ok = 1;                              /* this is a good place to be */
238     }
239     if(cd_ok) {
240         save_core();                            /* save any old core file */
241     } else {
242         (void) chdir("/");                      /* assume this works */
243     }
244 }
245
246 /*
247  *=====================================================================
248  * Save an existing core file.
249  *
250  * void save_core (void)
251  *
252  * entry:       none
253  * exit:        none
254  *
255  * Renames:
256  *
257  *      "core"          to "coreYYYYMMDD",
258  *      "coreYYYYMMDD"  to "coreYYYYMMDDa",
259  *      "coreYYYYMMDDa" to "coreYYYYMMDDb",
260  *      ...
261  *
262  * ... where YYYYMMDD is the modification time of the original file.
263  * If it gets that far, an old "coreYYYYMMDDz" is thrown away.
264  *=====================================================================
265  */
266
267 void
268 save_core()
269 {
270     struct stat sbuf;
271
272     if(stat("core", &sbuf) != -1) {
273         char *ts;
274         char suffix[2];
275         char *old, *new;
276
277         ts = construct_datestamp((time_t *)&sbuf.st_mtime);
278         suffix[0] = 'z';
279         suffix[1] = '\0';
280         old = vstralloc("core", ts, suffix, NULL);
281         new = NULL;
282         while(ts[0] != '\0') {
283             amfree(new);
284             new = old;
285             if(suffix[0] == 'a') {
286                 suffix[0] = '\0';
287             } else if(suffix[0] == '\0') {
288                 ts[0] = '\0';
289             } else {
290                 suffix[0]--;
291             }
292             old = vstralloc("core", ts, suffix, NULL);
293             (void)rename(old, new);         /* it either works ... */
294         }
295         amfree(ts);
296         amfree(old);
297         amfree(new);
298     }
299 }
300
301 /*
302 ** Sanitise a file name.
303 ** 
304 ** Convert all funny characters to '_' so that we can use,
305 ** for example, disk names as part of file names.
306 ** Notes: 
307 **  - there is a many-to-one mapping between input and output
308 ** XXX - We only look for '/' and ' ' at the moment.  May
309 ** XXX - be we should also do all unprintables.
310 */
311 char *sanitise_filename(inp)
312 char *inp;
313 {
314     char *buf;
315     int buf_size;
316     char *s, *d;
317     int ch;
318
319     buf_size = 2 * strlen(inp) + 1;             /* worst case */
320     buf = alloc(buf_size);
321     d = buf;
322     s = inp;
323     while((ch = *s++) != '\0') {
324         if(ch == '_') {
325             if(d >= buf + buf_size) {
326                 return NULL;                    /* cannot happen */
327             }
328             *d++ = '_';                         /* convert _ to __ to try */
329                                                 /* and ensure unique output */
330         } else if(ch == '/' || isspace(ch)) {
331             ch = '_';   /* convert "bad" to "_" */
332         }
333         if(d >= buf + buf_size) {
334             return NULL;                        /* cannot happen */
335         }
336         *d++ = ch;
337     }
338     if(d >= buf + buf_size) {
339         return NULL;                            /* cannot happen */
340     }
341     *d = '\0';
342
343     return buf;
344 }
345
346 /*
347  *=====================================================================
348  * Get the next line of input from a stdio file.
349  *
350  * char *agets (FILE *f)
351  *
352  * entry:       f = stdio stream to read
353  * exit:        returns a pointer to an alloc'd string or NULL at EOF
354  *              or error (errno will be zero on EOF).
355  *
356  * Notes:       the newline, if read, is removed from the string
357  *              the caller is responsible for free'ing the string
358  *=====================================================================
359  */
360
361 char *
362 debug_agets(s, l, file)
363     char *s;
364     int l;
365     FILE *file;
366 {
367     char *line = NULL, *line_ptr;
368     size_t line_size, size_save;
369     int line_free, line_len;
370     char *cp;
371     char *f;
372
373     malloc_enter(dbmalloc_caller_loc(s, l));
374
375 #define AGETS_LINE_INCR 128
376
377     line_size = AGETS_LINE_INCR;
378     line = debug_alloc (s, l, line_size);
379     line_free = line_size;
380     line_ptr = line;
381     line_len = 0;
382
383     while ((f = fgets(line_ptr, line_free, file)) != NULL) {
384         /*
385          * Note that we only have to search what we just read, not
386          * the whole buffer.
387          */
388         if ((cp = strchr (line_ptr, '\n')) != NULL) {
389             line_len += cp - line_ptr;
390             *cp = '\0';                         /* zap the newline */
391             break;                              /* got to end of line */
392         }
393         line_len += line_free - 1;              /* bytes read minus '\0' */
394         size_save = line_size;
395         if (line_size < 256 * AGETS_LINE_INCR) {
396             line_size *= 2;
397         } else {
398             line_size += 256 * AGETS_LINE_INCR;
399         }
400         cp = debug_alloc (s, l, line_size);     /* get more space */
401         memcpy (cp, line, size_save);           /* copy old to new */
402         free (line);                            /* and release the old */
403         line = cp;
404         line_ptr = line + size_save - 1;        /* start at the null byte */
405         line_free = line_size - line_len;       /* and we get to use it */
406     }
407     /*
408      * Return what we got even if there was not a newline.  Only
409      * report done (NULL) when no data was processed.
410      */
411     if (f == NULL && line_len == 0) {
412         amfree (line);
413         line = NULL;                            /* redundant, but clear */
414         if(!ferror(file)) {
415             errno = 0;                          /* flag EOF vs error */
416         }
417     }
418     malloc_leave(dbmalloc_caller_loc(s, l));
419     return line;
420 }
421
422 /*
423  *=====================================================================
424  * Find/create a buffer for a particular file descriptor for use with
425  * areads().
426  *
427  * void areads_getbuf (char *file, int line, int fd)
428  *
429  * entry:       file, line = caller source location
430  *              fd = file descriptor to look up
431  * exit:        returns a pointer to the buffer, possibly new
432  *=====================================================================
433  */
434
435 static struct areads_buffer {
436     char *buffer;
437     char *endptr;
438     ssize_t bufsize;
439 } *areads_buffer = NULL;
440 static int areads_bufcount = 0;
441 static ssize_t areads_bufsize = BUFSIZ;         /* for the test program */
442
443 static void
444 areads_getbuf(s, l, fd)
445     char *s;
446     int l;
447     int fd;
448 {
449     struct areads_buffer *new;
450     ssize_t size;
451
452     assert(fd >= 0);
453     if(fd >= areads_bufcount) {
454         size = (fd + 1) * sizeof(*areads_buffer);
455         new = (struct areads_buffer *) debug_alloc(s, l, size);
456         memset((char *)new, 0, size);
457         if(areads_buffer) {
458             size = areads_bufcount * sizeof(*areads_buffer);
459             memcpy(new, areads_buffer, size);
460         }
461         amfree(areads_buffer);
462         areads_buffer = new;
463         areads_bufcount = fd + 1;
464     }
465     if(areads_buffer[fd].buffer == NULL) {
466         areads_buffer[fd].bufsize = areads_bufsize;
467         areads_buffer[fd].buffer = debug_alloc(s, l,
468                                                areads_buffer[fd].bufsize + 1);
469         areads_buffer[fd].buffer[0] = '\0';
470         areads_buffer[fd].endptr = areads_buffer[fd].buffer;
471     }
472 }
473
474 /*
475  *=====================================================================
476  * Return the amount of data still in an areads buffer.
477  *
478  * ssize_t areads_dataready (int fd)
479  *
480  * entry:       fd = file descriptor to release buffer for
481  * exit:        returns number of bytes of data ready to process
482  *=====================================================================
483  */
484
485 ssize_t
486 areads_dataready(fd)
487     int fd;
488 {
489     ssize_t r = 0;
490
491     if(fd >= 0 && fd < areads_bufcount && areads_buffer[fd].buffer != NULL) {
492         r = (ssize_t) (areads_buffer[fd].endptr - areads_buffer[fd].buffer);
493     }
494     return r;
495 }
496
497 /*
498  *=====================================================================
499  * Release a buffer for a particular file descriptor used by areads().
500  *
501  * void areads_relbuf (int fd)
502  *
503  * entry:       fd = file descriptor to release buffer for
504  * exit:        none
505  *=====================================================================
506  */
507
508 void
509 areads_relbuf(fd)
510     int fd;
511 {
512     if(fd >= 0 && fd < areads_bufcount) {
513         amfree(areads_buffer[fd].buffer);
514         areads_buffer[fd].endptr = NULL;
515         areads_buffer[fd].bufsize = 0;
516     }
517 }
518
519 /*
520  *=====================================================================
521  * Get the next line of input from a file descriptor.
522  *
523  * char *areads (int fd)
524  *
525  * entry:       fd = file descriptor to read
526  * exit:        returns a pointer to an alloc'd string or NULL at EOF
527  *              or error (errno will be zero on EOF).
528  *
529  * Notes:       the newline, if read, is removed from the string
530  *              the caller is responsible for free'ing the string
531  *=====================================================================
532  */
533
534 char *
535 debug_areads (s, l, fd)
536     char *s;
537     int l;
538     int fd;
539 {
540     char *nl;
541     char *line;
542     char *buffer;
543     char *endptr;
544     char *newbuf;
545     ssize_t buflen;
546     ssize_t size;
547     ssize_t r;
548
549     malloc_enter(dbmalloc_caller_loc(s, l));
550
551     if(fd < 0) {
552         errno = EBADF;
553         return NULL;
554     }
555     areads_getbuf(s, l, fd);
556     buffer = areads_buffer[fd].buffer;
557     endptr = areads_buffer[fd].endptr;
558     buflen = areads_buffer[fd].bufsize - (endptr - buffer);
559     while((nl = strchr(buffer, '\n')) == NULL) {
560         /*
561          * No newline yet, so get more data.
562          */
563         if (buflen == 0) {
564             if ((size = areads_buffer[fd].bufsize) < 256 * areads_bufsize) {
565                 size *= 2;
566             } else {
567                 size += 256 * areads_bufsize;
568             }
569             newbuf = debug_alloc(s, l, size + 1);
570             memcpy (newbuf, buffer, areads_buffer[fd].bufsize + 1);
571             amfree(areads_buffer[fd].buffer);
572             buffer = NULL;
573             areads_buffer[fd].buffer = newbuf;
574             areads_buffer[fd].endptr = newbuf + areads_buffer[fd].bufsize;
575             areads_buffer[fd].bufsize = size;
576             buffer = areads_buffer[fd].buffer;
577             endptr = areads_buffer[fd].endptr;
578             buflen = areads_buffer[fd].bufsize - (endptr - buffer);
579         }
580         if ((r = read(fd, endptr, buflen)) <= 0) {
581             if(r == 0) {
582                 errno = 0;              /* flag EOF instead of error */
583             }
584             malloc_leave(dbmalloc_caller_loc(s, l));
585             return NULL;
586         }
587         endptr[r] = '\0';               /* we always leave room for this */
588         endptr += r;
589         buflen -= r;
590     }
591     *nl++ = '\0';
592     line = stralloc(buffer);
593     size = endptr - nl;                 /* data still left in buffer */
594     memmove(buffer, nl, size);
595     areads_buffer[fd].endptr = buffer + size;
596     areads_buffer[fd].endptr[0] = '\0';
597     malloc_leave(dbmalloc_caller_loc(s, l));
598     return line;
599 }
600
601 #ifdef TEST
602
603 int main(argc, argv)
604         int argc;
605         char **argv;
606 {
607         int rc;
608         int fd;
609         char *name;
610         char *top;
611         char *file;
612         char *line;
613
614         for(fd = 3; fd < FD_SETSIZE; fd++) {
615                 /*
616                  * Make sure nobody spoofs us with a lot of extra open files
617                  * that would cause an open we do to get a very high file
618                  * descriptor, which in turn might be used as an index into
619                  * an array (e.g. an fd_set).
620                  */
621                 close(fd);
622         }
623
624         set_pname("file test");
625
626         name = "/tmp/a/b/c/d/e";
627         if (argc > 2 && argv[1][0] != '\0') {
628                 name = argv[1];
629         }
630         top = "/tmp";
631         if (argc > 3 && argv[2][0] != '\0') {
632                 name = argv[2];
633         }
634         file = "/etc/hosts";
635         if (argc > 4 && argv[3][0] != '\0') {
636                 name = argv[3];
637         }
638
639         fprintf(stderr, "Create parent directories of %s ...", name);
640         rc = mkpdir(name, 02777, (uid_t)-1, (gid_t)-1);
641         if (rc == 0)
642                 fprintf(stderr, " done\n");
643         else {
644                 perror("failed");
645                 return rc;
646         }
647
648         fprintf(stderr, "Delete %s back to %s ...", name, top);
649         rc = rmpdir(name, top);
650         if (rc == 0)
651                 fprintf(stderr, " done\n");
652         else {
653                 perror("failed");
654                 return rc;
655         }
656
657         fprintf(stderr, "areads dump of %s ...", file);
658         if ((fd = open (file, 0)) < 0) {
659                 perror(file);
660                 return 1;
661         }
662         areads_bufsize = 1;                     /* force buffer overflow */
663         while ((line = areads(fd)) != NULL) {
664                 puts(line);
665                 amfree(line);
666         }
667         aclose(fd);
668         fprintf(stderr, " done.\n");
669
670         fprintf(stderr, "Finished.\n");
671         return 0;
672 }
673
674 #endif