2 * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3 * Copyright (c) 1997-1998 University of Maryland at College Park
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.
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.
23 * Author: AMANDA core development group.
26 * $Id: file.c,v 1.40 2006/07/19 17:41:15 martinea Exp $
28 * file and directory bashing routines
34 void amanda_setup(int argc, char **argv, int setup_flags);
35 static int mk1dir(const char *, mode_t, uid_t, gid_t);
36 static void areads_getbuf(const char *s, int l, int fd);
38 uid_t client_uid = (uid_t) -1;
39 gid_t client_gid = (gid_t) -1;
41 /* Make a directory (internal function).
42 ** If the directory already exists then we pretend we created it.
43 ** XXX - I'm not sure about the use of the chown() stuff. On most systems
44 ** it will do nothing - only root is permitted to change the owner
49 const char *dir, /* directory to create */
50 mode_t mode, /* mode for new directory */
51 uid_t uid, /* uid for new directory */
52 gid_t gid) /* gid for new directory */
54 int rc; /* return code */
56 if((rc = mkdir(dir, mode)) == 0) {
57 if ((rc = chmod(dir, mode)) == 0) { /* mkdir() affected by the umask */
58 rc = chown(dir, uid, gid);
60 } else { /* maybe someone beat us to it */
64 if(access(dir, F_OK) != 0)
66 errno = serrno; /* pass back the real error */
74 * Make a directory hierarchy given an entry to be created (by the caller)
75 * in the new target. In other words, create all the directories down to
76 * the last element, but not the last element. So a (potential) file name
77 * may be passed to mkpdir and all the parents of that file will be created.
81 char * file, /* file to create parent directories for */
82 mode_t mode, /* mode for new directories */
83 uid_t uid, /* uid for new directories */
84 gid_t gid) /* gid for new directories */
88 int rc; /* return code */
92 dir = stralloc(file); /* make a copy we can play with */
93 p = strrchr(dir, '/');
94 if(p != dir && p != NULL) { /* got a '/' or a simple name */
97 if(access(dir, F_OK) != 0) { /* doesn't exist */
98 if(mkpdir(dir, mode, uid, gid) != 0 ||
99 mk1dir(dir, mode, uid, gid) != 0) rc = -1; /* create failed */
108 /* Remove as much of a directory hierarchy as possible.
110 ** - assumes that rmdir() on a non-empty directory will fail!
111 ** - stops deleting before topdir, ie: topdir will not be removed
112 ** - if file is not under topdir this routine will not notice
116 char * file, /* directory hierarchy to remove */
117 char * topdir) /* where to stop removing */
122 if(strcmp(file, topdir) == 0) return 0; /* all done */
125 if (rc != 0) switch(errno) {
127 #if ENOTEMPTY != EEXIST /* AIX makes these the same */
131 case EEXIST: /* directory not empty */
132 return 0; /* cant do much more */
133 case ENOENT: /* it has already gone */
136 case ENOTDIR: /* it was a file */
141 if(rc != 0) return -1; /* unexpected error */
143 dir = stralloc(file);
145 p = strrchr(dir, '/');
146 if (p == NULL || p == dir) {
150 rc = rmpdir(dir, topdir);
160 *=====================================================================
161 * Do Amanda setup for all programs.
163 * void amanda_setup (int argc, char **argv, int setup_flags)
165 * entry: setup_flags (see AMANDA_SETUP_FLAG_xxx)
167 *=====================================================================
176 (void)argc; /* Quiet unused parameter warning */
177 (void)argv; /* Quiet unused parameter warning */
178 (void)setup_flags; /* Quiet unused parameter warning */
182 *=====================================================================
183 * Change directory to a "safe" location and set some base environment.
185 * void safe_cd (void)
187 * entry: client_uid and client_gid set to CLIENT_LOGIN information
190 * Set a default umask of 0077.
192 * Create the Amada debug directory (if defined) and the Amanda temp
195 * Try to chdir to the Amanda debug directory first, but it must be owned
196 * by the Amanda user and not allow rwx to group or other. Otherwise,
197 * try the same thing to the Amanda temp directory.
199 * If that is all OK, call save_core().
201 * Otherwise, cd to "/" so if we take a signal we cannot drop core
202 * unless the system administrator has made special arrangements (e.g.
203 * pre-created a core file with the right ownership and permissions).
204 *=====================================================================
212 struct passwd *pwent;
215 if(client_uid == (uid_t) -1 && (pwent = getpwnam(CLIENT_LOGIN)) != NULL) {
216 client_uid = pwent->pw_uid;
217 client_gid = pwent->pw_gid;
223 if (client_uid != (uid_t) -1) {
224 #if defined(AMANDA_DBGDIR)
225 d = stralloc2(AMANDA_DBGDIR, "/.");
226 (void) mkpdir(d, (mode_t)02700, client_uid, client_gid);
229 d = stralloc2(AMANDA_TMPDIR, "/.");
230 (void) mkpdir(d, (mode_t)02700, client_uid, client_gid);
234 #if defined(AMANDA_DBGDIR)
235 if (chdir(AMANDA_DBGDIR) != -1
236 && stat(".", &sbuf) != -1
237 && (sbuf.st_mode & 0777) == 0700 /* drwx------ */
238 && sbuf.st_uid == client_uid) { /* owned by Amanda user */
239 cd_ok = 1; /* this is a good place to be */
243 && chdir(AMANDA_TMPDIR) != -1
244 && stat(".", &sbuf) != -1
245 && (sbuf.st_mode & 0777) == 0700 /* drwx------ */
246 && sbuf.st_uid == client_uid) { /* owned by Amanda user */
247 cd_ok = 1; /* this is a good place to be */
250 save_core(); /* save any old core file */
252 if ((cd_ok = chdir("/")) == -1) {
253 (void)cd_ok; /* Quiet compiler warning if DEBUG disabled */
259 *=====================================================================
260 * Close all file descriptors except stdin, stdout and stderr. Make
261 * sure they are open.
263 * void safe_fd (fd_start, fd_count)
265 * entry: fd_start - start of fd-s to leave alone (or -1)
266 * fd_count - count of fd-s to leave alone
269 * On exit, all three standard file descriptors will be open and pointing
270 * someplace (either what we were handed or /dev/null) and all other
271 * file descriptors (up to FD_SETSIZE) will be closed.
272 *=====================================================================
282 for(fd = 0; fd < FD_SETSIZE; fd++) {
285 * Open three file descriptors. If one of the standard
286 * descriptors is not open it will be pointed to /dev/null...
288 * This avoids, for instance, someone running us with stderr
289 * closed so that when we open some other file, messages
290 * sent to stderr do not accidentally get written to the
293 if (fcntl(fd, F_GETFD) == -1) {
294 if (open("/dev/null", O_RDWR) == -1) {
295 fprintf(stderr, "/dev/null is inaccessable: %s\n",
302 * Make sure nobody spoofs us with a lot of extra open files
303 * that would cause an open we do to get a very high file
304 * descriptor, which in turn might be used as an index into
305 * an array (e.g. an fd_set).
307 if (fd < fd_start || fd >= fd_start + fd_count) {
315 *=====================================================================
316 * Save an existing core file.
318 * void save_core (void)
325 * "core" to "coreYYYYMMDD",
326 * "coreYYYYMMDD" to "coreYYYYMMDDa",
327 * "coreYYYYMMDDa" to "coreYYYYMMDDb",
330 * ... where YYYYMMDD is the modification time of the original file.
331 * If it gets that far, an old "coreYYYYMMDDz" is thrown away.
332 *=====================================================================
340 if(stat("core", &sbuf) != -1) {
345 ts = construct_datestamp((time_t *)&sbuf.st_mtime);
348 old = vstralloc("core", ts, suffix, NULL);
350 while(ts[0] != '\0') {
353 if(suffix[0] == 'a') {
355 } else if(suffix[0] == '\0') {
360 old = vstralloc("core", ts, suffix, NULL);
361 (void)rename(old, new); /* it either works ... */
370 ** Sanitise a file name.
372 ** Convert all '/' characters to '_' so that we can use,
373 ** for example, disk names as part of file names.
375 ** - there is a many-to-one mapping between input and output
376 ** - Only / and '\0' are disallowed in filenames by POSIX...
387 buf_size = strlen(inp) + 1; /* worst case */
388 buf = alloc(buf_size);
391 while((ch = *s++) != '\0') {
393 ch = '_'; /* convert "bad" to "_" */
397 assert(d < buf + buf_size);
404 *=====================================================================
405 * Get the next line of input from a stdio file.
407 * char *agets (FILE *stream)
409 * entry: stream - stream to read
410 * exit: returns a pointer to an alloc'd string or NULL
411 * at EOF or error. The functions ferror(stream) and
412 * feof(stream) should be checked by caller to determine
415 * Notes: the newline at the end of a line, if read, is removed from
416 * the string. Quoted newlines are left intact.
417 * the caller is responsible for free'ing the string
419 *=====================================================================
422 #define AGETS_LINE_INCR 128
426 const char *sourcefile,
431 char *line = alloc(AGETS_LINE_INCR);
432 size_t line_size = 0;
437 (void)sourcefile; /* Quiet unused parameter warning if not debugging */
438 (void)lineno; /* Quiet unused parameter warning if not debugging */
440 while ((ch = fgetc(stream)) != EOF) {
445 loffset--; /* Consume escape in buffer */
448 /* Reached end of line so exit without passing on LF */
463 if ((loffset + 1) >= line_size) {
467 * Reallocate input line.
468 * alloc() never return NULL pointer.
470 tmpline = alloc(line_size + AGETS_LINE_INCR);
471 memcpy(tmpline, line, line_size);
474 line_size = line_size + AGETS_LINE_INCR;
476 line[loffset++] = (char)ch;
479 if ((ch == EOF) && (loffset == 0)) {
480 amfree(line); /* amfree zeros line... */
482 line[loffset] = '\0';
486 * Return what we got even if there was not a newline.
487 * Only report done (NULL) when no data was processed.
494 *=====================================================================
495 * Find/create a buffer for a particular file descriptor for use with
498 * void areads_getbuf (const char *file, size_t line, int fd)
500 * entry: file, line = caller source location
501 * fd = file descriptor to look up
502 * exit: returns a pointer to the buffer, possibly new
503 *=====================================================================
506 static struct areads_buffer {
510 } *areads_buffer = NULL;
511 static int areads_bufcount = 0;
512 static size_t areads_bufsize = BUFSIZ; /* for the test program */
520 struct areads_buffer *new;
524 if(fd >= areads_bufcount) {
525 size = (size_t)(fd + 1) * SIZEOF(*areads_buffer);
526 new = (struct areads_buffer *) debug_alloc(s, l, size);
527 memset((char *)new, 0, size);
529 size = areads_bufcount * SIZEOF(*areads_buffer);
530 memcpy(new, areads_buffer, size);
532 amfree(areads_buffer);
534 areads_bufcount = fd + 1;
536 if(areads_buffer[fd].buffer == NULL) {
537 areads_buffer[fd].bufsize = areads_bufsize;
538 areads_buffer[fd].buffer = debug_alloc(s, l,
539 areads_buffer[fd].bufsize + 1);
540 areads_buffer[fd].buffer[0] = '\0';
541 areads_buffer[fd].endptr = areads_buffer[fd].buffer;
546 *=====================================================================
547 * Return the amount of data still in an areads buffer.
549 * ssize_t areads_dataready (int fd)
551 * entry: fd = file descriptor to release buffer for
552 * exit: returns number of bytes of data ready to process
553 *=====================================================================
562 if(fd >= 0 && fd < areads_bufcount && areads_buffer[fd].buffer != NULL) {
563 r = (ssize_t) (areads_buffer[fd].endptr - areads_buffer[fd].buffer);
569 *=====================================================================
570 * Release a buffer for a particular file descriptor used by areads().
572 * void areads_relbuf (int fd)
574 * entry: fd = file descriptor to release buffer for
576 *=====================================================================
583 if(fd >= 0 && fd < areads_bufcount) {
584 amfree(areads_buffer[fd].buffer);
585 areads_buffer[fd].endptr = NULL;
586 areads_buffer[fd].bufsize = 0;
591 *=====================================================================
592 * Get the next line of input from a file descriptor.
594 * char *areads (int fd)
596 * entry: fd = file descriptor to read
597 * exit: returns a pointer to an alloc'd string or NULL at EOF
598 * or error (errno will be zero on EOF).
600 * Notes: the newline, if read, is removed from the string
601 * the caller is responsible for free'ing the string
602 *=====================================================================
620 malloc_enter(dbmalloc_caller_loc(s, l));
626 areads_getbuf(s, l, fd);
627 buffer = areads_buffer[fd].buffer;
628 endptr = areads_buffer[fd].endptr;
629 buflen = areads_buffer[fd].bufsize - (size_t)(endptr - buffer);
630 while((nl = strchr(buffer, '\n')) == NULL) {
632 * No newline yet, so get more data.
635 if ((size = areads_buffer[fd].bufsize) < 256 * areads_bufsize) {
638 size += 256 * areads_bufsize;
640 newbuf = debug_alloc(s, l, size + 1);
641 memcpy (newbuf, buffer, areads_buffer[fd].bufsize + 1);
642 amfree(areads_buffer[fd].buffer);
643 areads_buffer[fd].buffer = newbuf;
644 areads_buffer[fd].endptr = newbuf + areads_buffer[fd].bufsize;
645 areads_buffer[fd].bufsize = size;
646 buffer = areads_buffer[fd].buffer;
647 endptr = areads_buffer[fd].endptr;
648 buflen = areads_buffer[fd].bufsize - (size_t)(endptr - buffer);
650 if ((r = read(fd, endptr, buflen)) <= 0) {
652 errno = 0; /* flag EOF instead of error */
654 malloc_leave(dbmalloc_caller_loc(s, l));
657 endptr[r] = '\0'; /* we always leave room for this */
662 line = stralloc(buffer);
663 size = (size_t)(endptr - nl); /* data still left in buffer */
664 memmove(buffer, nl, size);
665 areads_buffer[fd].endptr = buffer + size;
666 areads_buffer[fd].endptr[0] = '\0';
667 malloc_leave(dbmalloc_caller_loc(s, l));
687 set_pname("file test");
691 /* Don't die when child closes pipe */
692 signal(SIGPIPE, SIG_IGN);
694 name = "/tmp/a/b/c/d/e";
695 if (argc > 2 && argv[1][0] != '\0') {
699 if (argc > 3 && argv[2][0] != '\0') {
703 if (argc > 4 && argv[3][0] != '\0') {
707 fprintf(stderr, "Create parent directories of %s ...", name);
708 rc = mkpdir(name, (mode_t)02777, (uid_t)-1, (gid_t)-1);
710 fprintf(stderr, " done\n");
716 fprintf(stderr, "Delete %s back to %s ...", name, top);
717 rc = rmpdir(name, top);
719 fprintf(stderr, " done\n");
725 fprintf(stderr, "areads dump of %s ...", file);
726 if ((fd = open (file, 0)) < 0) {
730 areads_bufsize = 1; /* force buffer overflow */
731 while ((line = areads(fd)) != NULL) {
736 fprintf(stderr, " done.\n");
738 fprintf(stderr, "Finished.\n");