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 void areads_getbuf(const char *s, int l, int fd);
38 static char *original_cwd = NULL;
41 * Make a directory hierarchy given an entry to be created (by the caller)
42 * in the new target. In other words, create all the directories down to
43 * the last element, but not the last element. So a (potential) file name
44 * may be passed to mkpdir and all the parents of that file will be created.
48 char * file, /* file to create parent directories for */
49 mode_t mode, /* mode for new directories */
50 uid_t uid, /* uid for new directories */
51 gid_t gid) /* gid for new directories */
55 int rc; /* return code */
59 /* Remove last member of file, put the result in dir */
60 dir = stralloc(file); /* make a copy we can play with */
61 p = strrchr(dir, '/');
64 rc = mkdir(dir, mode);
66 if (errno == ENOENT) { /* create parent directory */
67 rc = mkpdir(dir, mode, uid, gid);
70 rc = mkdir(dir, mode);
72 if (rc != 0 && errno == EEXIST) {
78 /* mkdir succeded, set permission and ownership */
80 /* mkdir is affected by umask, so set the mode bits manually */
81 rc = chmod(dir, mode);
83 if (rc == 0 && geteuid() == 0) {
84 rc = chown(dir, uid, gid);
93 /* Remove as much of a directory hierarchy as possible.
95 ** - assumes that rmdir() on a non-empty directory will fail!
96 ** - stops deleting before topdir, ie: topdir will not be removed
97 ** - if file is not under topdir this routine will not notice
101 char * file, /* directory hierarchy to remove */
102 char * topdir) /* where to stop removing */
107 if(strcmp(file, topdir) == 0) return 0; /* all done */
110 if (rc != 0) switch(errno) {
112 #if ENOTEMPTY != EEXIST /* AIX makes these the same */
116 case EEXIST: /* directory not empty */
117 return 0; /* cant do much more */
118 case ENOENT: /* it has already gone */
121 case ENOTDIR: /* it was a file */
126 if(rc != 0) return -1; /* unexpected error */
128 dir = stralloc(file);
130 p = strrchr(dir, '/');
131 if (p == NULL || p == dir) {
135 rc = rmpdir(dir, topdir);
145 *=====================================================================
146 * Change directory to a "safe" location and set some base environment.
148 * void safe_cd (void)
150 * Set a default umask of 0077.
152 * Create the Amada debug directory (if defined) and the Amanda temp
155 * Try to chdir to the Amanda debug directory first, but it must be owned
156 * by the Amanda user and not allow rwx to group or other. Otherwise,
157 * try the same thing to the Amanda temp directory.
159 * If that is all OK, call save_core().
161 * Otherwise, cd to "/" so if we take a signal we cannot drop core
162 * unless the system administrator has made special arrangements (e.g.
163 * pre-created a core file with the right ownership and permissions).
164 *=====================================================================
173 uid_t client_uid = get_client_uid();
174 gid_t client_gid = get_client_gid();
178 /* stash away the current directory for later reference */
179 if (original_cwd == NULL) {
180 original_cwd = g_get_current_dir();
183 if (client_uid != (uid_t) -1) {
184 #if defined(AMANDA_DBGDIR)
185 d = stralloc2(AMANDA_DBGDIR, "/.");
186 (void) mkpdir(d, (mode_t)0700, client_uid, client_gid);
189 d = stralloc2(AMANDA_TMPDIR, "/.");
190 (void) mkpdir(d, (mode_t)0700, client_uid, client_gid);
194 #if defined(AMANDA_DBGDIR)
195 if (chdir(AMANDA_DBGDIR) != -1
196 && stat(".", &sbuf) != -1
197 && (sbuf.st_mode & 0777) == 0700 /* drwx------ */
198 && sbuf.st_uid == client_uid) { /* owned by Amanda user */
199 cd_ok = 1; /* this is a good place to be */
203 && chdir(AMANDA_TMPDIR) != -1
204 && stat(".", &sbuf) != -1
205 && (sbuf.st_mode & 0777) == 0700 /* drwx------ */
206 && sbuf.st_uid == client_uid) { /* owned by Amanda user */
207 cd_ok = 1; /* this is a good place to be */
210 save_core(); /* save any old core file */
212 if ((cd_ok = chdir("/")) == -1) {
213 (void)cd_ok; /* Quiet compiler warning if DEBUG disabled */
219 *=====================================================================
220 * Close all file descriptors except stdin, stdout and stderr. Make
221 * sure they are open.
223 * void safe_fd (fd_start, fd_count)
225 * entry: fd_start - start of fd-s to leave alone (or -1)
226 * fd_count - count of fd-s to leave alone
229 * On exit, all three standard file descriptors will be open and pointing
230 * someplace (either what we were handed or /dev/null) and all other
231 * file descriptors (up to FD_SETSIZE) will be closed.
232 *=====================================================================
242 for(fd = 0; fd < (int)FD_SETSIZE; fd++) {
245 * Open three file descriptors. If one of the standard
246 * descriptors is not open it will be pointed to /dev/null...
248 * This avoids, for instance, someone running us with stderr
249 * closed so that when we open some other file, messages
250 * sent to stderr do not accidentally get written to the
253 if (fcntl(fd, F_GETFD) == -1) {
254 if (open("/dev/null", O_RDWR) == -1) {
255 g_fprintf(stderr, _("/dev/null is inaccessable: %s\n"),
262 * Make sure nobody spoofs us with a lot of extra open files
263 * that would cause an open we do to get a very high file
264 * descriptor, which in turn might be used as an index into
265 * an array (e.g. an fd_set).
267 if (fd < fd_start || fd >= fd_start + fd_count) {
275 *=====================================================================
276 * Save an existing core file.
278 * void save_core (void)
285 * "core" to "coreYYYYMMDD",
286 * "coreYYYYMMDD" to "coreYYYYMMDDa",
287 * "coreYYYYMMDDa" to "coreYYYYMMDDb",
290 * ... where YYYYMMDD is the modification time of the original file.
291 * If it gets that far, an old "coreYYYYMMDDz" is thrown away.
292 *=====================================================================
300 if(stat("core", &sbuf) != -1) {
305 ts = get_datestamp_from_time(sbuf.st_mtime);
308 old = vstralloc("core", ts, suffix, NULL);
310 while(ts[0] != '\0') {
313 if(suffix[0] == 'a') {
315 } else if(suffix[0] == '\0') {
320 old = vstralloc("core", ts, suffix, NULL);
321 (void)rename(old, new); /* it either works ... */
330 ** Sanitise a file name.
332 ** Convert all '/', ':', and '\' characters to '_' so that we can use,
333 ** for example, disk names as part of file names.
335 ** - there is a many-to-one mapping between input and output
336 ** - Only / and '\0' are disallowed in filenames by POSIX, but Windows
337 ** disallows ':' and '\' as well. Furthermore, we use ':' as a
338 ** delimiter at other points in Amanda.
349 buf_size = strlen(inp) + 1; /* worst case */
350 buf = alloc(buf_size);
353 while((ch = *s++) != '\0') {
354 if((ch == '/') || (ch == ':') || (ch == '\\')) {
355 ch = '_'; /* convert "bad" to "_" */
359 assert(d < buf + buf_size);
367 old_sanitise_filename(
375 buf_size = 2*strlen(inp) + 1; /* worst case */
376 buf = alloc(buf_size);
379 while((ch = *s++) != '\0') {
384 ch = '_'; /* convert "bad" to "_" */
388 assert(d < buf + buf_size);
395 canonicalize_pathname(char *pathname, char *result_buf)
398 cygwin_conv_to_full_posix_path(pathname, result_buf);
400 strncpy(result_buf, pathname, PATH_MAX-1);
401 result_buf[PATH_MAX-1] = '\0';
406 *=====================================================================
407 * Get the next line of input from a stdio file.
409 * char *agets (FILE *stream)
411 * entry: stream - stream to read
412 * exit: returns a pointer to an alloc'd string or NULL
413 * at EOF or error. The functions ferror(stream) and
414 * feof(stream) should be checked by caller to determine
417 * Notes: the newline at the end of a line, if read, is removed from
418 * the string. Quoted newlines are left intact.
419 * the caller is responsible for free'ing the string
421 *=====================================================================
424 #define AGETS_LINE_INCR 128
428 const char *sourcefile,
433 char *line = alloc(AGETS_LINE_INCR);
434 size_t line_size = 0;
439 (void)sourcefile; /* Quiet unused parameter warning if not debugging */
440 (void)lineno; /* Quiet unused parameter warning if not debugging */
442 while ((ch = fgetc(stream)) != EOF) {
447 loffset--; /* Consume escape in buffer */
450 /* Reached end of line so exit without passing on LF */
465 if ((loffset + 1) >= line_size) {
469 * Reallocate input line.
470 * alloc() never return NULL pointer.
472 tmpline = alloc(line_size + AGETS_LINE_INCR);
473 memcpy(tmpline, line, line_size);
476 line_size = line_size + AGETS_LINE_INCR;
478 line[loffset++] = (char)ch;
481 if ((ch == EOF) && (loffset == 0)) {
482 amfree(line); /* amfree zeros line... */
484 line[loffset] = '\0';
488 * Return what we got even if there was not a newline.
489 * Only report done (NULL) when no data was processed.
496 *=====================================================================
497 * Find/create a buffer for a particular file descriptor for use with
500 * void areads_getbuf (const char *file, size_t line, int fd)
502 * entry: file, line = caller source location
503 * fd = file descriptor to look up
504 * exit: returns a pointer to the buffer, possibly new
505 *=====================================================================
508 static struct areads_buffer {
512 } *areads_buffer = NULL;
513 static int areads_bufcount = 0;
514 static size_t areads_bufsize = BUFSIZ; /* for the test program */
522 struct areads_buffer *new;
526 if(fd >= areads_bufcount) {
527 size = (size_t)(fd + 1) * SIZEOF(*areads_buffer);
528 new = (struct areads_buffer *) debug_alloc(s, l, size);
529 memset((char *)new, 0, size);
531 size = areads_bufcount * SIZEOF(*areads_buffer);
532 memcpy(new, areads_buffer, size);
534 amfree(areads_buffer);
536 areads_bufcount = fd + 1;
538 if(areads_buffer[fd].buffer == NULL) {
539 areads_buffer[fd].bufsize = areads_bufsize;
540 areads_buffer[fd].buffer = debug_alloc(s, l,
541 areads_buffer[fd].bufsize + 1);
542 areads_buffer[fd].buffer[0] = '\0';
543 areads_buffer[fd].endptr = areads_buffer[fd].buffer;
548 *=====================================================================
549 * Return the amount of data still in an areads buffer.
551 * ssize_t areads_dataready (int fd)
553 * entry: fd = file descriptor to release buffer for
554 * exit: returns number of bytes of data ready to process
555 *=====================================================================
564 if(fd >= 0 && fd < areads_bufcount && areads_buffer[fd].buffer != NULL) {
565 r = (ssize_t) (areads_buffer[fd].endptr - areads_buffer[fd].buffer);
571 *=====================================================================
572 * Release a buffer for a particular file descriptor used by areads().
574 * void areads_relbuf (int fd)
576 * entry: fd = file descriptor to release buffer for
578 *=====================================================================
585 if(fd >= 0 && fd < areads_bufcount) {
586 amfree(areads_buffer[fd].buffer);
587 areads_buffer[fd].endptr = NULL;
588 areads_buffer[fd].bufsize = 0;
593 *=====================================================================
594 * Get the next line of input from a file descriptor.
596 * char *areads (int fd)
598 * entry: fd = file descriptor to read
599 * exit: returns a pointer to an alloc'd string or NULL at EOF
600 * or error (errno will be zero on EOF).
602 * Notes: the newline, if read, is removed from the string
603 * the caller is responsible for free'ing the string
604 *=====================================================================
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 */
656 endptr[r] = '\0'; /* we always leave room for this */
661 line = stralloc(buffer);
662 size = (size_t)(endptr - nl); /* data still left in buffer */
663 memmove(buffer, nl, size);
664 areads_buffer[fd].endptr = buffer + size;
665 areads_buffer[fd].endptr[0] = '\0';
669 int robust_open(const char * pathname, int flags, mode_t mode) {
671 int e_busy_count = 0;
674 if (flags & O_CREAT) {
675 result = open(pathname, flags, mode);
677 result = open(pathname, flags);
682 /* EBUSY is a tricky one; sometimes it is synonymous with
683 EINTR, but sometimes it means the device is open
684 elsewhere (e.g., with a tape drive on Linux). We take
685 the middle path and retry, but with limited
687 if (errno == EBUSY && e_busy_count < 10) {
693 /* Always retry on EINTR; if the caller did
694 not specify non-blocking mode, then also retry on
695 EAGAIN or EWOULDBLOCK. */
701 && !(flags & O_NONBLOCK)
708 || errno == EWOULDBLOCK
724 fcntl(result, F_SETFD, 1); /* Throw away result. */
731 int robust_close(int fd) {
736 if (result != 0 && (0
747 || errno == EWOULDBLOCK
760 static uid_t client_uid = (uid_t) -1;
761 struct passwd *pwent;
763 if(client_uid == (uid_t) -1 && (pwent = getpwnam(CLIENT_LOGIN)) != NULL) {
764 client_uid = pwent->pw_uid;
774 static gid_t client_gid = (gid_t) -1;
775 struct passwd *pwent;
777 if(client_gid == (gid_t) -1 && (pwent = getpwnam(CLIENT_LOGIN)) != NULL) {
778 client_gid = pwent->pw_gid;
786 get_original_cwd(void)
788 if (original_cwd == NULL) {
789 original_cwd = g_get_current_dir();
810 * Configure program for internationalization:
811 * 1) Only set the message locale for now.
812 * 2) Set textdomain for all amanda related programs to "amanda"
813 * We don't want to be forced to support dozens of message catalogs
815 setlocale(LC_MESSAGES, "C");
816 textdomain("amanda");
820 set_pname("file test");
824 /* Don't die when child closes pipe */
825 signal(SIGPIPE, SIG_IGN);
827 name = "/tmp/a/b/c/d/e";
828 if (argc > 2 && argv[1][0] != '\0') {
832 if (argc > 3 && argv[2][0] != '\0') {
836 if (argc > 4 && argv[3][0] != '\0') {
840 g_fprintf(stderr, _("Create parent directories of %s ..."), name);
841 rc = mkpdir(name, (mode_t)02777, (uid_t)-1, (gid_t)-1);
843 g_fprintf(stderr, " done\n");
849 g_fprintf(stderr, _("Delete %s back to %s ..."), name, top);
850 rc = rmpdir(name, top);
852 g_fprintf(stderr, _(" done\n"));
858 g_fprintf(stderr, _("areads dump of %s ..."), file);
859 if ((fd = open (file, 0)) < 0) {
863 areads_bufsize = 1; /* force buffer overflow */
864 while ((line = areads(fd)) != NULL) {
869 g_fprintf(stderr, _(" done.\n"));
871 g_fprintf(stderr, _("Finished.\n"));