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
33 #include "timestamp.h"
37 static int mk1dir(const char *, mode_t, uid_t, gid_t);
38 static void areads_getbuf(const char *s, int l, int fd);
39 static char *original_cwd = NULL;
41 /* Make a directory (internal function).
42 * If the directory already exists then we pretend we created it.
44 * The uid and gid are used only if we are running as root.
48 const char *dir, /* directory to create */
49 mode_t mode, /* mode for new directory */
50 uid_t uid, /* uid for new directory */
51 gid_t gid) /* gid for new directory */
53 int rc; /* return code */
55 rc = mkdir(dir, mode);
60 if(access(dir, F_OK) == 0)
61 rc = 0; /* someone just beat us to it, so it's OK */
65 /* mkdir is affected by umask, so set the mode bits manually */
67 rc = chmod(dir, mode);
70 if (rc == 0 && geteuid() == 0) {
71 rc = chown(dir, uid, gid);
79 * Make a directory hierarchy given an entry to be created (by the caller)
80 * in the new target. In other words, create all the directories down to
81 * the last element, but not the last element. So a (potential) file name
82 * may be passed to mkpdir and all the parents of that file will be created.
86 char * file, /* file to create parent directories for */
87 mode_t mode, /* mode for new directories */
88 uid_t uid, /* uid for new directories */
89 gid_t gid) /* gid for new directories */
93 int rc; /* return code */
97 dir = stralloc(file); /* make a copy we can play with */
98 p = strrchr(dir, '/');
99 if(p != dir && p != NULL) { /* got a '/' or a simple name */
102 if(access(dir, F_OK) != 0) { /* doesn't exist */
103 if(mkpdir(dir, mode, uid, gid) != 0 ||
104 mk1dir(dir, mode, uid, gid) != 0) rc = -1; /* create failed */
113 /* Remove as much of a directory hierarchy as possible.
115 ** - assumes that rmdir() on a non-empty directory will fail!
116 ** - stops deleting before topdir, ie: topdir will not be removed
117 ** - if file is not under topdir this routine will not notice
121 char * file, /* directory hierarchy to remove */
122 char * topdir) /* where to stop removing */
127 if(strcmp(file, topdir) == 0) return 0; /* all done */
130 if (rc != 0) switch(errno) {
132 #if ENOTEMPTY != EEXIST /* AIX makes these the same */
136 case EEXIST: /* directory not empty */
137 return 0; /* cant do much more */
138 case ENOENT: /* it has already gone */
141 case ENOTDIR: /* it was a file */
146 if(rc != 0) return -1; /* unexpected error */
148 dir = stralloc(file);
150 p = strrchr(dir, '/');
151 if (p == NULL || p == dir) {
155 rc = rmpdir(dir, topdir);
165 *=====================================================================
166 * Change directory to a "safe" location and set some base environment.
168 * void safe_cd (void)
170 * Set a default umask of 0077.
172 * Create the Amada debug directory (if defined) and the Amanda temp
175 * Try to chdir to the Amanda debug directory first, but it must be owned
176 * by the Amanda user and not allow rwx to group or other. Otherwise,
177 * try the same thing to the Amanda temp directory.
179 * If that is all OK, call save_core().
181 * Otherwise, cd to "/" so if we take a signal we cannot drop core
182 * unless the system administrator has made special arrangements (e.g.
183 * pre-created a core file with the right ownership and permissions).
184 *=====================================================================
193 uid_t client_uid = get_client_uid();
194 gid_t client_gid = get_client_gid();
198 /* stash away the current directory for later reference */
199 if (original_cwd == NULL) {
200 original_cwd = g_get_current_dir();
203 if (client_uid != (uid_t) -1) {
204 #if defined(AMANDA_DBGDIR)
205 d = stralloc2(AMANDA_DBGDIR, "/.");
206 (void) mkpdir(d, (mode_t)0700, client_uid, client_gid);
209 d = stralloc2(AMANDA_TMPDIR, "/.");
210 (void) mkpdir(d, (mode_t)0700, client_uid, client_gid);
214 #if defined(AMANDA_DBGDIR)
215 if (chdir(AMANDA_DBGDIR) != -1
216 && stat(".", &sbuf) != -1
217 && (sbuf.st_mode & 0777) == 0700 /* drwx------ */
218 && sbuf.st_uid == client_uid) { /* owned by Amanda user */
219 cd_ok = 1; /* this is a good place to be */
223 && chdir(AMANDA_TMPDIR) != -1
224 && stat(".", &sbuf) != -1
225 && (sbuf.st_mode & 0777) == 0700 /* drwx------ */
226 && sbuf.st_uid == client_uid) { /* owned by Amanda user */
227 cd_ok = 1; /* this is a good place to be */
230 save_core(); /* save any old core file */
232 if ((cd_ok = chdir("/")) == -1) {
233 (void)cd_ok; /* Quiet compiler warning if DEBUG disabled */
239 *=====================================================================
240 * Close all file descriptors except stdin, stdout and stderr. Make
241 * sure they are open.
243 * void safe_fd (fd_start, fd_count)
245 * entry: fd_start - start of fd-s to leave alone (or -1)
246 * fd_count - count of fd-s to leave alone
249 * On exit, all three standard file descriptors will be open and pointing
250 * someplace (either what we were handed or /dev/null) and all other
251 * file descriptors (up to FD_SETSIZE) will be closed.
252 *=====================================================================
262 for(fd = 0; fd < (int)FD_SETSIZE; fd++) {
265 * Open three file descriptors. If one of the standard
266 * descriptors is not open it will be pointed to /dev/null...
268 * This avoids, for instance, someone running us with stderr
269 * closed so that when we open some other file, messages
270 * sent to stderr do not accidentally get written to the
273 if (fcntl(fd, F_GETFD) == -1) {
274 if (open("/dev/null", O_RDWR) == -1) {
275 g_fprintf(stderr, _("/dev/null is inaccessable: %s\n"),
282 * Make sure nobody spoofs us with a lot of extra open files
283 * that would cause an open we do to get a very high file
284 * descriptor, which in turn might be used as an index into
285 * an array (e.g. an fd_set).
287 if (fd < fd_start || fd >= fd_start + fd_count) {
295 *=====================================================================
296 * Save an existing core file.
298 * void save_core (void)
305 * "core" to "coreYYYYMMDD",
306 * "coreYYYYMMDD" to "coreYYYYMMDDa",
307 * "coreYYYYMMDDa" to "coreYYYYMMDDb",
310 * ... where YYYYMMDD is the modification time of the original file.
311 * If it gets that far, an old "coreYYYYMMDDz" is thrown away.
312 *=====================================================================
320 if(stat("core", &sbuf) != -1) {
325 ts = get_datestamp_from_time(sbuf.st_mtime);
328 old = vstralloc("core", ts, suffix, NULL);
330 while(ts[0] != '\0') {
333 if(suffix[0] == 'a') {
335 } else if(suffix[0] == '\0') {
340 old = vstralloc("core", ts, suffix, NULL);
341 (void)rename(old, new); /* it either works ... */
350 ** Sanitise a file name.
352 ** Convert all '/', ':', and '\' characters to '_' so that we can use,
353 ** for example, disk names as part of file names.
355 ** - there is a many-to-one mapping between input and output
356 ** - Only / and '\0' are disallowed in filenames by POSIX, but Windows
357 ** disallows ':' and '\' as well. Furthermore, we use ':' as a
358 ** delimiter at other points in Amanda.
369 buf_size = strlen(inp) + 1; /* worst case */
370 buf = alloc(buf_size);
373 while((ch = *s++) != '\0') {
374 if((ch == '/') || (ch == ':') || (ch == '\\')) {
375 ch = '_'; /* convert "bad" to "_" */
379 assert(d < buf + buf_size);
387 old_sanitise_filename(
395 buf_size = 2*strlen(inp) + 1; /* worst case */
396 buf = alloc(buf_size);
399 while((ch = *s++) != '\0') {
404 ch = '_'; /* convert "bad" to "_" */
408 assert(d < buf + buf_size);
415 canonicalize_pathname(char *pathname, char *result_buf)
418 cygwin_conv_to_full_posix_path(pathname, result_buf);
420 strncpy(result_buf, pathname, PATH_MAX-1);
421 result_buf[PATH_MAX-1] = '\0';
426 *=====================================================================
427 * Get the next line of input from a stdio file.
429 * char *agets (FILE *stream)
431 * entry: stream - stream to read
432 * exit: returns a pointer to an alloc'd string or NULL
433 * at EOF or error. The functions ferror(stream) and
434 * feof(stream) should be checked by caller to determine
437 * Notes: the newline at the end of a line, if read, is removed from
438 * the string. Quoted newlines are left intact.
439 * the caller is responsible for free'ing the string
441 *=====================================================================
444 #define AGETS_LINE_INCR 128
448 const char *sourcefile,
453 char *line = alloc(AGETS_LINE_INCR);
454 size_t line_size = 0;
459 (void)sourcefile; /* Quiet unused parameter warning if not debugging */
460 (void)lineno; /* Quiet unused parameter warning if not debugging */
462 while ((ch = fgetc(stream)) != EOF) {
467 loffset--; /* Consume escape in buffer */
470 /* Reached end of line so exit without passing on LF */
485 if ((loffset + 1) >= line_size) {
489 * Reallocate input line.
490 * alloc() never return NULL pointer.
492 tmpline = alloc(line_size + AGETS_LINE_INCR);
493 memcpy(tmpline, line, line_size);
496 line_size = line_size + AGETS_LINE_INCR;
498 line[loffset++] = (char)ch;
501 if ((ch == EOF) && (loffset == 0)) {
502 amfree(line); /* amfree zeros line... */
504 line[loffset] = '\0';
508 * Return what we got even if there was not a newline.
509 * Only report done (NULL) when no data was processed.
516 *=====================================================================
517 * Find/create a buffer for a particular file descriptor for use with
520 * void areads_getbuf (const char *file, size_t line, int fd)
522 * entry: file, line = caller source location
523 * fd = file descriptor to look up
524 * exit: returns a pointer to the buffer, possibly new
525 *=====================================================================
528 static struct areads_buffer {
532 } *areads_buffer = NULL;
533 static int areads_bufcount = 0;
534 static size_t areads_bufsize = BUFSIZ; /* for the test program */
542 struct areads_buffer *new;
546 if(fd >= areads_bufcount) {
547 size = (size_t)(fd + 1) * SIZEOF(*areads_buffer);
548 new = (struct areads_buffer *) debug_alloc(s, l, size);
549 memset((char *)new, 0, size);
551 size = areads_bufcount * SIZEOF(*areads_buffer);
552 memcpy(new, areads_buffer, size);
554 amfree(areads_buffer);
556 areads_bufcount = fd + 1;
558 if(areads_buffer[fd].buffer == NULL) {
559 areads_buffer[fd].bufsize = areads_bufsize;
560 areads_buffer[fd].buffer = debug_alloc(s, l,
561 areads_buffer[fd].bufsize + 1);
562 areads_buffer[fd].buffer[0] = '\0';
563 areads_buffer[fd].endptr = areads_buffer[fd].buffer;
568 *=====================================================================
569 * Return the amount of data still in an areads buffer.
571 * ssize_t areads_dataready (int fd)
573 * entry: fd = file descriptor to release buffer for
574 * exit: returns number of bytes of data ready to process
575 *=====================================================================
584 if(fd >= 0 && fd < areads_bufcount && areads_buffer[fd].buffer != NULL) {
585 r = (ssize_t) (areads_buffer[fd].endptr - areads_buffer[fd].buffer);
591 *=====================================================================
592 * Release a buffer for a particular file descriptor used by areads().
594 * void areads_relbuf (int fd)
596 * entry: fd = file descriptor to release buffer for
598 *=====================================================================
605 if(fd >= 0 && fd < areads_bufcount) {
606 amfree(areads_buffer[fd].buffer);
607 areads_buffer[fd].endptr = NULL;
608 areads_buffer[fd].bufsize = 0;
613 *=====================================================================
614 * Get the next line of input from a file descriptor.
616 * char *areads (int fd)
618 * entry: fd = file descriptor to read
619 * exit: returns a pointer to an alloc'd string or NULL at EOF
620 * or error (errno will be zero on EOF).
622 * Notes: the newline, if read, is removed from the string
623 * the caller is responsible for free'ing the string
624 *=====================================================================
646 areads_getbuf(s, l, fd);
647 buffer = areads_buffer[fd].buffer;
648 endptr = areads_buffer[fd].endptr;
649 buflen = areads_buffer[fd].bufsize - (size_t)(endptr - buffer);
650 while((nl = strchr(buffer, '\n')) == NULL) {
652 * No newline yet, so get more data.
655 if ((size = areads_buffer[fd].bufsize) < 256 * areads_bufsize) {
658 size += 256 * areads_bufsize;
660 newbuf = debug_alloc(s, l, size + 1);
661 memcpy (newbuf, buffer, areads_buffer[fd].bufsize + 1);
662 amfree(areads_buffer[fd].buffer);
663 areads_buffer[fd].buffer = newbuf;
664 areads_buffer[fd].endptr = newbuf + areads_buffer[fd].bufsize;
665 areads_buffer[fd].bufsize = size;
666 buffer = areads_buffer[fd].buffer;
667 endptr = areads_buffer[fd].endptr;
668 buflen = areads_buffer[fd].bufsize - (size_t)(endptr - buffer);
670 if ((r = read(fd, endptr, buflen)) <= 0) {
672 errno = 0; /* flag EOF instead of error */
676 endptr[r] = '\0'; /* we always leave room for this */
681 line = stralloc(buffer);
682 size = (size_t)(endptr - nl); /* data still left in buffer */
683 memmove(buffer, nl, size);
684 areads_buffer[fd].endptr = buffer + size;
685 areads_buffer[fd].endptr[0] = '\0';
689 int robust_open(const char * pathname, int flags, mode_t mode) {
691 int e_busy_count = 0;
694 if (flags & O_CREAT) {
695 result = open(pathname, flags, mode);
697 result = open(pathname, flags);
702 /* EBUSY is a tricky one; sometimes it is synonymous with
703 EINTR, but sometimes it means the device is open
704 elsewhere (e.g., with a tape drive on Linux). We take
705 the middle path and retry, but with limited
707 if (errno == EBUSY && e_busy_count < 10) {
713 /* Always retry on EINTR; if the caller did
714 not specify non-blocking mode, then also retry on
715 EAGAIN or EWOULDBLOCK. */
721 && !(flags & O_NONBLOCK)
728 || errno == EWOULDBLOCK
744 fcntl(result, F_SETFD, 1); /* Throw away result. */
751 int robust_close(int fd) {
756 if (result != 0 && (0
767 || errno == EWOULDBLOCK
780 static uid_t client_uid = (uid_t) -1;
781 struct passwd *pwent;
783 if(client_uid == (uid_t) -1 && (pwent = getpwnam(CLIENT_LOGIN)) != NULL) {
784 client_uid = pwent->pw_uid;
794 static gid_t client_gid = (gid_t) -1;
795 struct passwd *pwent;
797 if(client_gid == (gid_t) -1 && (pwent = getpwnam(CLIENT_LOGIN)) != NULL) {
798 client_gid = pwent->pw_gid;
806 get_original_cwd(void)
808 if (original_cwd == NULL) {
809 original_cwd = g_get_current_dir();
830 * Configure program for internationalization:
831 * 1) Only set the message locale for now.
832 * 2) Set textdomain for all amanda related programs to "amanda"
833 * We don't want to be forced to support dozens of message catalogs
835 setlocale(LC_MESSAGES, "C");
836 textdomain("amanda");
840 set_pname("file test");
844 /* Don't die when child closes pipe */
845 signal(SIGPIPE, SIG_IGN);
847 name = "/tmp/a/b/c/d/e";
848 if (argc > 2 && argv[1][0] != '\0') {
852 if (argc > 3 && argv[2][0] != '\0') {
856 if (argc > 4 && argv[3][0] != '\0') {
860 g_fprintf(stderr, _("Create parent directories of %s ..."), name);
861 rc = mkpdir(name, (mode_t)02777, (uid_t)-1, (gid_t)-1);
863 g_fprintf(stderr, " done\n");
869 g_fprintf(stderr, _("Delete %s back to %s ..."), name, top);
870 rc = rmpdir(name, top);
872 g_fprintf(stderr, _(" done\n"));
878 g_fprintf(stderr, _("areads dump of %s ..."), file);
879 if ((fd = open (file, 0)) < 0) {
883 areads_bufsize = 1; /* force buffer overflow */
884 while ((line = areads(fd)) != NULL) {
889 g_fprintf(stderr, _(" done.\n"));
891 g_fprintf(stderr, _("Finished.\n"));