static int validate_file(const char *filename, char **root, char **repository, const char **file, const char **returned_dir, int must_exist) { char *dir = (char*)xmalloc(strlen(filename)+sizeof(CVSADM_REP)+sizeof(CVSADM_ROOT)+1),*p; size_t repos_len; FILE *fp; strcpy(dir,filename); p=(char*)last_component(dir); *file=last_component((char*)filename); *p='\0'; strcat(dir,CVSADM); if(!isdir(dir)) error(1,0,"%s is not part of a checked out repository",filename); *p='\0'; strcat(dir,CVSADM_REP); if(!isfile(dir) || isdir(dir)) error(1,0,"%s is not part of a checked out repository",filename); fp = fopen(dir,"r"); if(!fp) error(1,errno,"Couldn't open %s", dir); *repository=NULL; if((repos_len=getline(repository,&repos_len,fp))<0) error(1,errno,"Couldn't read %s", dir); fclose(fp); (*repository)[repos_len-1]='\0'; *p='\0'; strcat(dir,CVSADM_ROOT); if(!isfile(dir) || isdir(dir)) error(1,0,"%s is not part of a checked out repository",filename); fp = fopen(dir,"r"); if(!fp) error(1,errno,"Couldn't open %s", dir); *root=NULL; if((repos_len=getline(root,&repos_len,fp))<0) error(1,errno,"Couldn't read %s", dir); fclose(fp); (*root)[repos_len-1]='\0'; *p='\0'; if(!strlen(dir)) strcpy(dir,"./"); *returned_dir = dir; TRACE(3,"%s is in %s/%s",PATCH_NULL(filename),PATCH_NULL(*root),PATCH_NULL(*repository)); return 0; }
static void proc_etccertsdir(const char* fullpath, struct hash* h, int tmpfile_fd) { char linktarget[SYMLINK_MAX]; ssize_t linklen; linklen = readlink(fullpath, linktarget, sizeof(linktarget)-1); if (linklen < 0) return; linktarget[linklen] = 0; struct hash_item *item = hash_get(h, last_component(fullpath)); if (!item) { /* Symlink exists but is not wanted * Delete it if it points to 'our' directory */ if (str_begins(linktarget, CERTSDIR) || str_begins(linktarget, LOCALCERTSDIR)) unlink(fullpath); } else if (strcmp(linktarget, item->value) != 0) { /* Symlink exists but points wrong */ unlink(fullpath); if (symlink(item->value, fullpath) < 0) fprintf(stderr, "Warning! Cannot update symlink %s -> %s\n", item->value, fullpath); item->value = 0; } else { /* Symlink exists and is ok */ item->value = 0; } }
char * mfile_name_concat (char const *dir, char const *abase, char **base_in_result) { char const *dirbase = last_component (dir); size_t dirbaselen = base_len (dirbase); size_t dirlen = dirbase - dir + dirbaselen; size_t needs_separator = (dirbaselen && ! ISSLASH (dirbase[dirbaselen - 1])); char const *base = longest_relative_suffix (abase); size_t baselen = strlen (base); char *p_concat = malloc (dirlen + needs_separator + baselen + 1); char *p; if (p_concat == NULL) return NULL; p = mempcpy (p_concat, dir, dirlen); *p = DIRECTORY_SEPARATOR; p += needs_separator; if (base_in_result) *base_in_result = p - IS_ABSOLUTE_FILE_NAME (abase); p = mempcpy (p, base, baselen); *p = '\0'; return p_concat; }
char * base_name (char const *name) { char const *base = last_component (name); size_t length; /* If there is no last component, then name is a file system root or the empty string. */ if (! *base) return xstrndup (name, base_len (name)); /* Collapse a sequence of trailing slashes into one. */ length = base_len (base); if (ISSLASH (base[length])) length++; /* On systems with drive letters, `a/b:c' must return `./b:c' rather than `b:c' to avoid confusion with a drive letter. On systems with pure POSIX semantics, this is not an issue. */ if (FILE_SYSTEM_PREFIX_LEN (base)) { char *p = xmalloc (length + 3); p[0] = '.'; p[1] = '/'; memcpy (p + 2, base, length); p[length + 2] = '\0'; return p; } /* Finally, copy the basename. */ return xstrndup (base, length); }
static int parallelsGetBridgedNetInfo(virNetworkDefPtr def, virJSONValuePtr jobj) { const char *ifname; char *bridgeLink = NULL; char *bridgePath = NULL; char *bridgeAddressPath = NULL; char *bridgeAddress = NULL; int len = 0; int ret = -1; if (!(ifname = virJSONValueObjectGetString(jobj, "Bound To"))) { parallelsParseError(); goto cleanup; } if (virAsprintf(&bridgeLink, SYSFS_NET_DIR "%s/brport/bridge", ifname) < 0) goto cleanup; if (virFileResolveLink(bridgeLink, &bridgePath) < 0) { virReportSystemError(errno, _("cannot read link '%s'"), bridgeLink); goto cleanup; } if (VIR_STRDUP(def->bridge, last_component(bridgePath)) < 0) goto cleanup; if (virAsprintf(&bridgeAddressPath, SYSFS_NET_DIR "%s/brport/bridge/address", ifname) < 0) goto cleanup; if ((len = virFileReadAll(bridgeAddressPath, 18, &bridgeAddress)) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Error reading file '%s'"), bridgeAddressPath); goto cleanup; } if (len < VIR_MAC_STRING_BUFLEN) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Error reading MAC from '%s'"), bridgeAddressPath); } bridgeAddress[VIR_MAC_STRING_BUFLEN - 1] = '\0'; if (virMacAddrParse(bridgeAddress, &def->mac) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Can't parse MAC '%s'"), bridgeAddress); goto cleanup; } def->mac_specified = 1; ret = 0; cleanup: VIR_FREE(bridgeLink); VIR_FREE(bridgePath); VIR_FREE(bridgeAddress); VIR_FREE(bridgeAddressPath); return ret; }
__inline static void emit_ancillary_info(void) { char *tmp ; char *tmp___0 ; char *tmp___1 ; char *tmp___2 ; char const *lc_messages ; char *tmp___3 ; char *tmp___4 ; char *tmp___5 ; int tmp___6 ; char *tmp___7 ; char *tmp___8 ; { tmp = last_component(program_name); tmp___0 = gettext("\nReport %s bugs to %s\n"); printf((char const */* __restrict */)tmp___0, tmp, "*****@*****.**"); tmp___1 = gettext("%s home page: <http://www.gnu.org/software/%s/>\n"); printf((char const */* __restrict */)tmp___1, "GNU coreutils", "coreutils"); tmp___2 = gettext("General help using GNU software: <http://www.gnu.org/gethelp/>\n"); fputs_unlocked((char const */* __restrict */)tmp___2, (FILE */* __restrict */)stdout); tmp___3 = setlocale(5, (char const *)((void *)0)); lc_messages = (char const *)tmp___3; if (lc_messages) { tmp___6 = strncmp(lc_messages, "en_", 3UL); if (tmp___6) { tmp___4 = last_component(program_name); tmp___5 = gettext("Report %s translation bugs to <http://translationproject.org/team/>\n"); printf((char const */* __restrict */)tmp___5, tmp___4); } else { } } else { } tmp___7 = last_component(program_name); tmp___8 = gettext("For complete documentation, run: info coreutils \'%s invocation\'\n"); printf((char const */* __restrict */)tmp___8, tmp___7); return; } }
static char const * expand_name (char *name, bool is_dir, char const *other_name) { if (STREQ (name, "-")) fatal ("cannot interactively merge standard input"); if (! is_dir) return name; else { /* Yield NAME/BASE, where BASE is OTHER_NAME's basename. */ char const *base = last_component (other_name); size_t namelen = strlen (name), baselen = base_len (base); bool insert_slash = *last_component (name) && name[namelen - 1] != '/'; char *r = xmalloc (namelen + insert_slash + baselen + 1); memcpy (r, name, namelen); r[namelen] = '/'; memcpy (r + namelen + insert_slash, base, baselen); r[namelen + insert_slash + baselen] = '\0'; return r; } }
static void check_extension (char *file, size_t filelen, char e) { char *base = last_component (file); size_t baselen = base_len (base); size_t baselen_max = HAVE_LONG_FILE_NAMES ? 255 : NAME_MAX_MINIMUM; if (HAVE_DOS_FILE_NAMES || NAME_MAX_MINIMUM < baselen) { /* The new base name is long enough to require a pathconf check. */ long name_max; /* Temporarily modify the buffer into its parent directory name, invoke pathconf on the directory, and then restore the buffer. */ char tmp[sizeof "."]; memcpy (tmp, base, sizeof "."); strcpy (base, "."); errno = 0; name_max = pathconf (file, _PC_NAME_MAX); if (0 <= name_max || errno == 0) { long size = baselen_max = name_max; if (name_max != size) baselen_max = SIZE_MAX; } memcpy (base, tmp, sizeof "."); } if (HAVE_DOS_FILE_NAMES && baselen_max <= 12) { /* Live within DOS's 8.3 limit. */ char *dot = strchr (base, '.'); if (!dot) baselen_max = 8; else { char const *second_dot = strchr (dot + 1, '.'); baselen_max = (second_dot ? second_dot - base : dot + 1 - base + 3); } } if (baselen_max < baselen) { baselen = file + filelen - base; if (baselen_max <= baselen) baselen = baselen_max - 1; base[baselen] = e; base[baselen + 1] = '\0'; } }
bool strip_trailing_slashes (char *file) { char *base = last_component (file); char *base_lim; bool had_slash; /* last_component returns "" for file system roots, but we need to turn `///' into `/'. */ if (! *base) base = file; base_lim = base + base_len (base); had_slash = (*base_lim != '\0'); *base_lim = '\0'; return had_slash; }
static bool target_directory_operand (char const *file) { char const *b = last_component (file); size_t blen = strlen (b); bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1])); struct stat st; int stat_result = (dereference_dest_dir_symlinks ? stat (file, &st) : lstat (file, &st)); int err = (stat_result == 0 ? 0 : errno); bool is_a_dir = !err && S_ISDIR (st.st_mode); if (err && err != ENOENT) error (EXIT_FAILURE, err, _("accessing %s"), quote (file)); if (is_a_dir < looks_like_a_dir) error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file)); return is_a_dir; }
int rpl_mkdir (char const *dir, mode_t mode maybe_unused) { int ret_val; char *tmp_dir; size_t len = strlen (dir); if (len && dir[len - 1] == '/') { tmp_dir = strdup (dir); if (!tmp_dir) { /* Rather than rely on strdup-posix, we set errno ourselves. */ errno = ENOMEM; return -1; } strip_trailing_slashes (tmp_dir); } else { tmp_dir = (char *) dir; } #if FUNC_MKDIR_DOT_BUG /* Additionally, cygwin 1.5 mistakenly creates a directory "d/./". */ { char *last = last_component (tmp_dir); if (*last == '.' && (last[1] == '\0' || (last[1] == '.' && last[2] == '\0'))) { struct stat st; if (stat (tmp_dir, &st) == 0) errno = EEXIST; return -1; } } #endif /* FUNC_MKDIR_DOT_BUG */ ret_val = mkdir (tmp_dir, mode); if (tmp_dir != dir) free (tmp_dir); return ret_val; }
/* Returns a pointer to a dynamically allocated structure whose value can be used to tell whether two files are actually the same file. Returns a null pointer if no information about the file is available, perhaps because it does not exist. The caller is responsible for freeing the structure with fn_free_identity() when finished. */ struct file_identity * fn_get_identity (const char *file_name) { struct file_identity *identity = xmalloc (sizeof *identity); #if !(defined _WIN32 || defined __WIN32__) struct stat s; if (lstat (file_name, &s) == 0) { identity->device = s.st_dev; identity->inode = s.st_ino; identity->name = NULL; } else { char *dir = dir_name (file_name); if (last_component (file_name) != NULL && stat (dir, &s) == 0) { identity->device = s.st_dev; identity->inode = s.st_ino; identity->name = base_name (file_name); } else { identity->device = 0; identity->inode = 0; identity->name = xstrdup (file_name); } free (dir); } #else /* Windows */ char cname[PATH_MAX]; int ok = GetFullPathName (file_name, sizeof cname, cname, NULL); identity->device = 0; identity->inode = 0; identity->name = xstrdup (ok ? cname : file_name); str_lowercase (identity->name); #endif /* Windows */ return identity; }
static void file_name_split (const char *file_name, const char **base, const char **tab, const char **ext) { *base = last_component (file_name); /* Look for the extension, i.e., look for the last dot. */ *ext = (const char*)_mbsrchr ((const unsigned char*)*base, '.'); *tab = NULL; /* If there is an extension, check if there is a '.tab' part right before. */ if (*ext) { size_t baselen = *ext - *base; size_t dottablen = sizeof (TAB_EXT) - 1; if (dottablen < baselen && STRPREFIX_LIT (TAB_EXT, *ext - dottablen)) *tab = *ext - dottablen; } }
static void proc_localglobaldir(const char *fullpath, struct hash *h, int tmpfile_fd) { const char *fname = last_component(fullpath); size_t flen = strlen(fname); char *s, *actual_file = NULL; /* Snip off the .crt suffix */ if (flen > 4 && strcmp(&fname[flen-4], ".crt") == 0) flen -= 4; if (asprintf(&actual_file, "%s%.*s%s", "ca-cert-", flen, fname, ".pem") == -1) { fprintf(stderr, "Cannot open path: %s\n", fullpath); return; } for (s = actual_file; *s; s++) { switch(*s) { case ',': case ' ': *s = '_'; break; case ')': case '(': *s = '='; break; default: break; } } if (!hash_add(h, actual_file, fullpath)) fprintf(stderr, "Warning! Cannot hash: %s\n", fullpath); if (!copyfile(fullpath, tmpfile_fd)) fprintf(stderr, "Warning! Cannot copy to bundle: %s\n", fullpath); free(actual_file); }
char *mfile_name_concat( char *dir, char *abase, char **base_in_result ) { char *dirbase = last_component( dir ); size_t dirbaselen = base_len( dirbase ); size_t dirlen = dirbaselen + ( dirbase - dir ); size_t needs_separator = dirbaselen == 0 || dirbase[ dirbaselen - 1 ] == '/' ? 0 : 1; char *base = longest_relative_suffix( abase ); size_t baselen = strlen( base ); char *p_concat = malloc( ( baselen + needs_separator + dirlen + 1 ) * sizeof( char ) ); char *p; if ( p_concat == 0 ) { return 0; } p = mempcpy( p_concat, dir, dirlen ); p[0] = '/'; p = &p[ needs_separator ]; if ( base_in_result != 0 ) base_in_result[0] = &p[ ( abase[0] == '/' ) * -1 ]; p = mempcpy( p, base, baselen ); p[0] = 0; return p_concat; }
size_t dir_len (char const *file) { size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file); size_t length; /* Advance prefix_length beyond important leading slashes. */ prefix_length += (prefix_length != 0 ? (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && ISSLASH (file[prefix_length])) : (ISSLASH (file[0]) ? ((DOUBLE_SLASH_IS_DISTINCT_ROOT && ISSLASH (file[1]) && ! ISSLASH (file[2]) ? 2 : 1)) : 0)); /* Strip the basename and any redundant slashes before it. */ for (length = last_component (file) - file; prefix_length < length; length--) if (! ISSLASH (file[length - 1])) break; return length; }
static enum numbered_backup_result numbered_backup (char **buffer, size_t buffer_size, size_t filelen) { enum numbered_backup_result result = BACKUP_IS_NEW; DIR *dirp; struct dirent *dp; char *buf = *buffer; size_t versionlenmax = 1; char *base = last_component (buf); size_t base_offset = base - buf; size_t baselen = base_len (base); /* Temporarily modify the buffer into its parent directory name, open the directory, and then restore the buffer. */ char tmp[sizeof "."]; memcpy (tmp, base, sizeof "."); strcpy (base, "."); dirp = opendir (buf); memcpy (base, tmp, sizeof "."); strcpy (base + baselen, ".~1~"); if (!dirp) return result; while ((dp = readdir (dirp)) != NULL) { char const *p; char *q; bool all_9s; size_t versionlen; size_t new_buflen; if (! REAL_DIR_ENTRY (dp) || _D_EXACT_NAMLEN (dp) < baselen + 4) continue; if (memcmp (buf + base_offset, dp->d_name, baselen + 2) != 0) continue; p = dp->d_name + baselen + 2; /* Check whether this file has a version number and if so, whether it is larger. Use string operations rather than integer arithmetic, to avoid problems with integer overflow. */ if (! ('1' <= *p && *p <= '9')) continue; all_9s = (*p == '9'); for (versionlen = 1; ISDIGIT (p[versionlen]); versionlen++) all_9s &= (p[versionlen] == '9'); if (! (p[versionlen] == '~' && !p[versionlen + 1] && (versionlenmax < versionlen || (versionlenmax == versionlen && memcmp (buf + filelen + 2, p, versionlen) <= 0)))) continue; /* This directory has the largest version number seen so far. Append this highest numbered extension to the file name, prepending '0' to the number if it is all 9s. */ versionlenmax = all_9s + versionlen; result = (all_9s ? BACKUP_IS_LONGER : BACKUP_IS_SAME_LENGTH); new_buflen = filelen + 2 + versionlenmax + 1; if (buffer_size <= new_buflen) { buf = xnrealloc (buf, 2, new_buflen); buffer_size = new_buflen * 2; } q = buf + filelen; *q++ = '.'; *q++ = '~'; *q = '0'; q += all_9s; memcpy (q, p, versionlen + 2); /* Add 1 to the version number. */ q += versionlen; while (*--q == '9') *q = '0'; ++*q; } closedir (dirp); *buffer = buf; return result; }
static void compute_file_name_parts (void) { const char *base, *tab, *ext; /* Compute ALL_BUT_EXT and ALL_BUT_TAB_EXT from SPEC_OUTFILE or GRAMMAR_FILE. The precise -o name will be used for FTABLE. For other output files, remove the ".c" or ".tab.c" suffix. */ if (spec_outfile) { file_name_split (spec_outfile, &base, &tab, &ext); dir_prefix = xstrndup (spec_outfile, base - spec_outfile); /* ALL_BUT_EXT goes up the EXT, excluding it. */ all_but_ext = xstrndup (spec_outfile, (strlen (spec_outfile) - (ext ? strlen (ext) : 0))); /* ALL_BUT_TAB_EXT goes up to TAB, excluding it. */ all_but_tab_ext = xstrndup (spec_outfile, (strlen (spec_outfile) - (tab ? strlen (tab) : (ext ? strlen (ext) : 0)))); if (ext) compute_exts_from_src (ext); } else { file_name_split (grammar_file, &base, &tab, &ext); if (spec_file_prefix) { /* If --file-prefix=foo was specified, ALL_BUT_TAB_EXT = 'foo'. */ dir_prefix = xstrndup (spec_file_prefix, last_component (spec_file_prefix) - spec_file_prefix); all_but_tab_ext = xstrdup (spec_file_prefix); } else if (yacc_flag) { /* If --yacc, then the output is 'y.tab.c'. */ dir_prefix = xstrdup (""); all_but_tab_ext = xstrdup ("y"); } else { /* Otherwise, ALL_BUT_TAB_EXT is computed from the input grammar: 'foo/bar.yy' => 'bar'. */ dir_prefix = xstrdup (""); all_but_tab_ext = xstrndup (base, (strlen (base) - (ext ? strlen (ext) : 0))); } if (language->add_tab) all_but_ext = concat2 (all_but_tab_ext, TAB_EXT); else all_but_ext = xstrdup (all_but_tab_ext); /* Compute the extensions from the grammar file name. */ if (ext && !yacc_flag) compute_exts_from_gf (ext); } }
/* * Decode a "percent" prototype character. * A prototype string may include various "percent" escapes; * that is, a percent sign followed by a single letter. * Here we decode that letter and take the appropriate action, * usually by appending something to the message being built. */ static void protochar(int c, int where) { off_t pos; off_t len; int n; off_t linenum; off_t last_linenum; IFILE h; #undef PAGE_NUM #define PAGE_NUM(linenum) ((((linenum) - 1) / (sc_height - 1)) + 1) switch (c) { case 'b': /* Current byte offset */ pos = curr_byte(where); if (pos != -1) ap_pos(pos); else ap_quest(); break; case 'c': ap_int(hshift); break; case 'd': /* Current page number */ linenum = currline(where); if (linenum > 0 && sc_height > 1) ap_pos(PAGE_NUM(linenum)); else ap_quest(); break; case 'D': /* Final page number */ /* Find the page number of the last byte in the file (len-1). */ len = ch_length(); if (len == -1) { ap_quest(); } else if (len == 0) { /* An empty file has no pages. */ ap_pos(0); } else { linenum = find_linenum(len - 1); if (linenum <= 0) ap_quest(); else ap_pos(PAGE_NUM(linenum)); } break; case 'E': /* Editor name */ ap_str(editor); break; case 'f': /* File name */ ap_str(get_filename(curr_ifile)); break; case 'F': /* Last component of file name */ ap_str(last_component(get_filename(curr_ifile))); break; case 'i': /* Index into list of files */ if (ntags()) ap_int(curr_tag()); else ap_int(get_index(curr_ifile)); break; case 'l': /* Current line number */ linenum = currline(where); if (linenum != 0) ap_pos(linenum); else ap_quest(); break; case 'L': /* Final line number */ len = ch_length(); if (len == -1 || len == ch_zero() || (linenum = find_linenum(len)) <= 0) ap_quest(); else ap_pos(linenum-1); break; case 'm': /* Number of files */ n = ntags(); if (n) ap_int(n); else ap_int(nifile()); break; case 'p': /* Percent into file (bytes) */ pos = curr_byte(where); len = ch_length(); if (pos != -1 && len > 0) ap_int(percentage(pos, len)); else ap_quest(); break; case 'P': /* Percent into file (lines) */ linenum = currline(where); if (linenum == 0 || (len = ch_length()) == -1 || len == ch_zero() || (last_linenum = find_linenum(len)) <= 0) ap_quest(); else ap_int(percentage(linenum, last_linenum)); break; case 's': /* Size of file */ case 'B': len = ch_length(); if (len != -1) ap_pos(len); else ap_quest(); break; case 't': /* Truncate trailing spaces in the message */ while (mp > message && mp[-1] == ' ') mp--; *mp = '\0'; break; case 'T': /* Type of list */ if (ntags()) ap_str("tag"); else ap_str("file"); break; case 'x': /* Name of next file */ h = next_ifile(curr_ifile); if (h != NULL) ap_str(get_filename(h)); else ap_quest(); break; } }
int main (void) { struct test *t; bool ok = true; for (t = tests; t->name; t++) { char *dir = dir_name (t->name); int dirlen = dir_len (t->name); char *last = last_component (t->name); char *base = base_name (t->name); int baselen = base_len (base); char *stripped = strdup (t->name); bool modified = strip_trailing_slashes (stripped); bool absolute = IS_ABSOLUTE_FILE_NAME (t->name); if (! (strcmp (dir, t->dir) == 0 && (dirlen == strlen (dir) || (dirlen + 1 == strlen (dir) && dir[dirlen] == '.')))) { ok = false; printf ("dir_name '%s': got '%s' len %d," " expected '%s' len %ld\n", t->name, dir, dirlen, t->dir, (unsigned long) strlen (t->dir)); } if (strcmp (last, t->last)) { ok = false; printf ("last_component '%s': got '%s', expected '%s'\n", t->name, last, t->last); } if (! (strcmp (base, t->base) == 0 && (baselen == strlen (base) || (baselen + 1 == strlen (base) && ISSLASH (base[baselen]))))) { ok = false; printf ("base_name '%s': got '%s' len %d," " expected '%s' len %ld\n", t->name, base, baselen, t->base, (unsigned long) strlen (t->base)); } if (strcmp (stripped, t->stripped) || modified != t->modified) { ok = false; printf ("strip_trailing_slashes '%s': got %s %s, expected %s %s\n", t->name, stripped, modified ? "changed" : "unchanged", t->stripped, t->modified ? "changed" : "unchanged"); } if (t->absolute != absolute) { ok = false; printf ("'%s': got %s, expected %s\n", t->name, absolute ? "absolute" : "relative", t->absolute ? "absolute" : "relative"); } free (dir); free (base); free (stripped); } return ok ? 0 : 1; }
bool same_name(const char *source, const char *dest) { /* Compare the basenames. */ char const *source_basename = last_component(source); char const *dest_basename = last_component(dest); size_t source_baselen = base_len(source_basename); size_t dest_baselen = base_len(dest_basename); bool identical_basenames = ((source_baselen == dest_baselen) && (memcmp(source_basename, dest_basename, dest_baselen) == 0)); bool compare_dirs = identical_basenames; bool same = false; #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && (defined(_PC_NAME_MAX) || defined(_POSIX_NAME_MAX)) /* This implementation silently truncates components of file names. If * the base names might be truncated, check whether the truncated * base names are the same, while checking the directories. */ size_t slen_max = (HAVE_LONG_FILE_NAMES ? 255 : _POSIX_NAME_MAX); size_t min_baselen = MIN(source_baselen, dest_baselen); if ((slen_max <= min_baselen) && (memcmp(source_basename, dest_basename, slen_max) == 0)) { compare_dirs = true; } #else /* use 'MIN' macro: */ size_t min_baselen = MIN(source_baselen, dest_baselen); /* dummy condition to use value stored to it: */ if ((min_baselen == source_baselen) || (min_baselen == dest_baselen)) { ; } #endif /* !_POSIX_NO_TRUNC && HAVE_PATHCONF && (_PC_NAME_MAX || _POSIX_NAME_MAX) */ if (compare_dirs) { struct stat source_dir_stats; struct stat dest_dir_stats; char *source_dirname, *dest_dirname; /* Compare the parent directories (via the device and inode numbers). */ source_dirname = dir_name(source); dest_dirname = dir_name(dest); if (stat(source_dirname, &source_dir_stats)) { /* Should NOT happen. */ error (1, errno, "%s", source_dirname); } if (stat(dest_dirname, &dest_dir_stats)) { /* Should NOT happen. */ error (1, errno, "%s", dest_dirname); } same = SAME_INODE(source_dir_stats, dest_dir_stats); #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX if (same && ! identical_basenames) { long name_max = (errno = 0, pathconf(dest_dirname, _PC_NAME_MAX)); if (name_max < 0) { if (errno) { /* Should NOT happen. */ error(1, errno, "%s", dest_dirname); } same = false; } else same = ((name_max <= min_baselen) && (memcmp(source_basename, dest_basename, name_max) == 0)); } #endif /* !_POSIX_NO_TRUNC && HAVE_PATHCONF && _PC_NAME_MAX */ free(source_dirname); free(dest_dirname); } return same; }
/* Specification. */ #include "getprogname.h" #include <errno.h> /* get program_invocation_name declaration */ #include <stdlib.h> /* get __argv declaration */ #ifdef _AIX # include <unistd.h> # include <procinfo.h> # include <string.h> #endif #ifdef __MVS__ # ifndef _OPEN_SYS # define _OPEN_SYS # endif # include <string.h> # include <sys/ps.h> #endif #ifdef __hpux # include <unistd.h> # include <sys/param.h> # include <sys/pstat.h> # include <string.h> #endif #include "dirname.h" #ifndef HAVE_GETPROGNAME /* not Mac OS X, FreeBSD, NetBSD, OpenBSD >= 5.4, Cygwin */ char const * getprogname (void) { # if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME /* glibc, BeOS */ /* https://www.gnu.org/software/libc/manual/html_node/Error-Messages.html */ return program_invocation_short_name; # elif HAVE_DECL_PROGRAM_INVOCATION_NAME /* glibc, BeOS */ /* https://www.gnu.org/software/libc/manual/html_node/Error-Messages.html */ return last_component (program_invocation_name); # elif HAVE_GETEXECNAME /* Solaris */ /* http://docs.oracle.com/cd/E19253-01/816-5168/6mbb3hrb1/index.html */ const char *p = getexecname (); if (!p) p = "?"; return last_component (p); # elif HAVE_DECL___ARGV /* mingw, MSVC */ /* https://msdn.microsoft.com/en-us/library/dn727674.aspx */ const char *p = __argv && __argv[0] ? __argv[0] : "?"; return last_component (p); # elif HAVE_VAR___PROGNAME /* OpenBSD, QNX */ /* http://man.openbsd.org/style.9 */ /* http://www.qnx.de/developers/docs/6.5.0/index.jsp?topic=%2Fcom.qnx.doc.neutrino_lib_ref%2Fp%2F__progname.html */ /* Be careful to declare this only when we absolutely need it (OpenBSD 5.1), rather than when it's available. Otherwise, its mere declaration makes program_invocation_short_name malfunction (have zero length) with Fedora 25's glibc. */ extern char *__progname; const char *p = __progname; return p && p[0] ? p : "?"; # elif _AIX /* AIX */ /* Idea by Bastien ROUCARIÈS, http://lists.gnu.org/archive/html/bug-gnulib/2010-12/msg00095.html Reference: http:// ibm.biz/knowctr#ssw_aix_53/com.ibm.aix.basetechref/doc/basetrf1/getprocs.htm */ static char *p; static int first = 1; if (first) { first = 0; pid_t pid = getpid (); struct procentry64 procs; p = (0 < getprocs64 (&procs, sizeof procs, NULL, 0, &pid, 1) ? strdup (procs.pi_comm) : NULL); if (!p) p = "?"; } return p; # elif defined __hpux static char *p; static int first = 1; if (first) { first = 0; pid_t pid = getpid (); struct pst_status status; p = (0 < pstat_getproc (&status, sizeof status, 0, pid) ? strdup (status.pst_ucomm) : NULL); if (!p) p = "?"; } return p; # elif __MVS__ /* z/OS */ /* https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.bpxbd00/rtwgetp.htm */ static char *p = "?"; static int first = 1; if (first) { pid_t pid = getpid (); int token; W_PSPROC buf; first = 0; memset (&buf, 0, sizeof(buf)); buf.ps_cmdptr = (char *) malloc (buf.ps_cmdlen = PS_CMDBLEN_LONG); buf.ps_conttyptr = (char *) malloc (buf.ps_conttylen = PS_CONTTYBLEN); buf.ps_pathptr = (char *) malloc (buf.ps_pathlen = PS_PATHBLEN); if (buf.ps_cmdptr && buf.ps_conttyptr && buf.ps_pathptr) { for (token = 0; token >= 0; token = w_getpsent (token, &buf, sizeof(buf))) { if (token > 0 && buf.ps_pid == pid) { char *s = strdup (last_component (buf.ps_pathptr)); if (s) p = s; break; } } } free (buf.ps_cmdptr); free (buf.ps_conttyptr); free (buf.ps_pathptr); } return p; # else # error "getprogname module not ported to this OS" # endif }
int rpl_rename (char const *src, char const *dst) { size_t src_len = strlen (src); size_t dst_len = strlen (dst); char *src_temp = (char *) src; char *dst_temp = (char *) dst; bool src_slash; bool dst_slash; bool dst_exists; int ret_val = -1; int rename_errno = ENOTDIR; struct stat src_st; struct stat dst_st; if (!src_len || !dst_len) return rename (src, dst); /* Let strace see the ENOENT failure. */ # if RENAME_DEST_EXISTS_BUG { char *src_base = last_component (src); char *dst_base = last_component (dst); if (*src_base == '.') { size_t len = base_len (src_base); if (len == 1 || (len == 2 && src_base[1] == '.')) { errno = EINVAL; return -1; } } if (*dst_base == '.') { size_t len = base_len (dst_base); if (len == 1 || (len == 2 && dst_base[1] == '.')) { errno = EINVAL; return -1; } } } # endif /* RENAME_DEST_EXISTS_BUG */ src_slash = src[src_len - 1] == '/'; dst_slash = dst[dst_len - 1] == '/'; # if !RENAME_HARD_LINK_BUG && !RENAME_DEST_EXISTS_BUG /* If there are no trailing slashes, then trust the native implementation unless we also suspect issues with hard link detection or file/directory conflicts. */ if (!src_slash && !dst_slash) return rename (src, dst); # endif /* !RENAME_HARD_LINK_BUG && !RENAME_DEST_EXISTS_BUG */ /* Presence of a trailing slash requires directory semantics. If the source does not exist, or if the destination cannot be turned into a directory, give up now. Otherwise, strip trailing slashes before calling rename. */ if (lstat (src, &src_st)) return -1; if (lstat (dst, &dst_st)) { if (errno != ENOENT || (!S_ISDIR (src_st.st_mode) && dst_slash)) return -1; dst_exists = false; } else { if (S_ISDIR (dst_st.st_mode) != S_ISDIR (src_st.st_mode)) { errno = S_ISDIR (dst_st.st_mode) ? EISDIR : ENOTDIR; return -1; } # if RENAME_HARD_LINK_BUG if (SAME_INODE (src_st, dst_st)) return 0; # endif /* RENAME_HARD_LINK_BUG */ dst_exists = true; } # if (RENAME_TRAILING_SLASH_SOURCE_BUG || RENAME_DEST_EXISTS_BUG \ || RENAME_HARD_LINK_BUG) /* If the only bug was that a trailing slash was allowed on a non-existing file destination, as in Solaris 10, then we've already covered that situation. But if there is any problem with a trailing slash on an existing source or destination, as in Solaris 9, or if a directory can overwrite a symlink, as on Cygwin 1.5, or if directories cannot be created with trailing slash, as on NetBSD 1.6, then we must strip the offending slash and check that we have not encountered a symlink instead of a directory. Stripping a trailing slash interferes with POSIX semantics, where rename behavior on a symlink with a trailing slash operates on the corresponding target directory. We prefer the GNU semantics of rejecting any use of a symlink with trailing slash, but do not enforce them, since Solaris 10 is able to obey POSIX semantics and there might be clients expecting it, as counter-intuitive as those semantics are. Technically, we could also follow the POSIX behavior by chasing a readlink trail, but that is harder to implement. */ if (src_slash) { src_temp = strdup (src); if (!src_temp) { /* Rather than rely on strdup-posix, we set errno ourselves. */ rename_errno = ENOMEM; goto out; } strip_trailing_slashes (src_temp); if (lstat (src_temp, &src_st)) { rename_errno = errno; goto out; } if (S_ISLNK (src_st.st_mode)) goto out; } if (dst_slash) { dst_temp = strdup (dst); if (!dst_temp) { rename_errno = ENOMEM; goto out; } strip_trailing_slashes (dst_temp); if (lstat (dst_temp, &dst_st)) { if (errno != ENOENT) { rename_errno = errno; goto out; } } else if (S_ISLNK (dst_st.st_mode)) goto out; } # endif /* RENAME_TRAILING_SLASH_SOURCE_BUG || RENAME_DEST_EXISTS_BUG || RENAME_HARD_LINK_BUG */
extern char strip_trailing_slashes(char *__T34544056); static void __zvm_this_file_init(void); static __attribute__((__constructor__)) void __zvm_file_constructor(void); char strip_trailing_slashes( char *file) { auto char __T34690784; auto int __zvm_memchk_nesting_nr; auto void *__zvm_prev_stack_end; auto char __T33175560; auto char *base; auto char *base_lim = 0xaaaaaaaaaaaaaaaa; auto char had_slash; # 32 __zvm_memchk_nesting_nr = (__zvm_memchk_push_function("strip_trailing_slashes", 0, "/home/release/apps/grep2.5.3/grep-2.9/lib/stripslash.c", 31)); __zvm_memchk_add_stack_object("/home/release/apps/grep2.5.3/grep-2.9/lib/stripslash.c", ((int)31), ((void *)((unsigned long)(&base))), ((unsigned long)8), ((unsigned long)1), ((const char *)((unsigned long)"base")), ((int)__zvm_memchk_nesting_nr)); __ZVM_DECL_LOCAL_MLS(); __zvm_mls_scope_in(__zvm_cc_var, 1, file, (__zvm_varinfo + 1U)); __ZVM_PUSH_FUNC_INIT((__zvm_funcinfo + 2U)); __zcov_update_counter(0); __ZVM_PUSH_FUNC((__zvm_funcinfo + 0U)); base = (((void *)(__zvm_mls_set_instrumented(__zvm_cc_var))) , ((char *)(__zvm_mls_ptr_init((last_component(((const char *)file))))))); { # 39 if ((!((int)((*((char *)(__zvm_component_reference_inline((__zvm_varinfo + 2U), ((void *)((unsigned long)base)), ((long)0L), ((int)1), ((void *)((unsigned long)__zvm_cc_var)))))))))) { __zcov_update_counter(1); ((void *)(__zvm_mls_set_instrumented(__zvm_cc_var))) , ((char *)(__zvm_mls_ptr_assignment((__zvm_varinfo + 3U), __zvm_cc_var, (&base), file, 0))); } else { __zcov_update_counter(2); } } __zcov_update_counter(3); __ZVM_PUSH_FUNC((__zvm_funcinfo + 1U)); ((void *)(__zvm_mls_set_instrumented(__zvm_cc_var))) , ((char *)(__zvm_mls_ptr_assignment((__zvm_varinfo + 4U), __zvm_cc_var, (&base_lim), (base + (base_len(((const char *)base)))), 0))); had_slash = ((char)((((int)((*((char *)(__zvm_component_reference_inline((__zvm_varinfo + 5U), ((void *)((unsigned long)base_lim)), ((long)0L), ((int)1), ((void *)((unsigned long)__zvm_cc_var)))))))) != 0) != 0)); (*((char *)(__zvm_component_reference_inline((__zvm_varinfo + 6U), ((void *)((unsigned long)base_lim)), ((long)0L), ((int)1), ((void *)((unsigned long)__zvm_cc_var)))))) = ((char)0); { __T33175560 = had_slash; __zvm_mls_scope_out("/home/release/apps/grep2.5.3/grep-2.9/lib/stripslash.c", 43, __zvm_cc_var, __zvm_mls_return_unused, 0, 3, 0, base, "base", base_lim, "base_lim", file, "file"); __ZVM_POP_FUNC_END(); { __T34690784 = __T33175560; __zvm_memchk_pop_function("strip_trailing_slashes", __zvm_memchk_nesting_nr); return __T34690784; } } } static void __zvm_this_file_init(void) { } static __attribute__((__constructor__)) void __zvm_file_constructor(void) { __zvm_file_ctr(((void *)__zvm_dirnames)); __zvm_this_file_init(); __zvm_local_init_inline(); __zvm_dr_varinfo_init(((void *)__zvm_varinfo), zvm_file_option); __zvm_update_align(4U); }
/* Move to the parent of a given directory and then call a function, * restoring the cwd. Don't bother changing directory if the * specified directory is a child of "." or is the root directory. */ static void at_top (char *pathname, mode_t mode, ino_t inum, struct stat *pstat, void (*action)(char *pathname, char *basename, int mode, ino_t inum, struct stat *pstat)) { int dirchange; char *parent_dir = dir_name (pathname); char *base = last_component (pathname); state.curdepth = 0; state.starting_path_length = strlen (pathname); if (0 == *base || 0 == strcmp (parent_dir, ".")) { dirchange = 0; base = pathname; } else { enum TraversalDirection direction; enum SafeChdirStatus chdir_status; struct stat st; bool did_stat = false; dirchange = 1; if (0 == strcmp (base, "..")) direction = TraversingUp; else direction = TraversingDown; /* We pass SymlinkFollowOk to safely_chdir(), which allows it to * chdir() into a symbolic link. This is only useful for the * case where the directory we're chdir()ing into is the * basename of a command line argument, for example where * "foo/bar/baz" is specified on the command line. When -P is * in effect (the default), baz will not be followed if it is a * symlink, but if bar is a symlink, it _should_ be followed. * Hence we need the ability to override the policy set by * following_links(). */ chdir_status = safely_chdir (parent_dir, direction, &st, SymlinkFollowOk, &did_stat); if (SafeChdirOK != chdir_status) { const char *what = (SafeChdirFailWouldBeUnableToReturn == chdir_status) ? "." : parent_dir; if (errno) error (0, errno, "%s", safely_quote_err_filename (0, what)); else error (0, 0, _("Failed to safely change directory into %s"), safely_quote_err_filename (0, parent_dir)); /* We can't process this command-line argument. */ state.exit_status = 1; return; } } free (parent_dir); parent_dir = NULL; action (pathname, base, mode, inum, pstat); if (dirchange) { chdir_back (); } }
/* Open a file (a magnetic tape device?) on the system specified in FILE_NAME, as the given user. FILE_NAME has the form `[USER@]HOST:FILE'. OPEN_MODE is O_RDONLY, O_WRONLY, etc. If successful, return the remote pipe number plus BIAS. REMOTE_SHELL may be overridden. On error, return -1. */ int rmt_open__ (const char *file_name, int open_mode, int bias, const char *remote_shell) { int remote_pipe_number; /* pseudo, biased file descriptor */ char *file_name_copy; /* copy of file_name string */ char *remote_host; /* remote host name */ char *remote_file; /* remote file name (often a device) */ char *remote_user; /* remote user name */ /* Find an unused pair of file descriptors. */ for (remote_pipe_number = 0; remote_pipe_number < MAXUNIT; remote_pipe_number++) if (READ_SIDE (remote_pipe_number) == -1 && WRITE_SIDE (remote_pipe_number) == -1) break; if (remote_pipe_number == MAXUNIT) { errno = EMFILE; return -1; } /* Pull apart the system and device, and optional user. */ { char *cursor; file_name_copy = xstrdup (file_name); remote_host = file_name_copy; remote_user = 0; remote_file = 0; for (cursor = file_name_copy; *cursor; cursor++) switch (*cursor) { default: break; case '\n': /* Do not allow newlines in the file_name, since the protocol uses newline delimiters. */ free (file_name_copy); errno = ENOENT; return -1; case '@': if (!remote_user) { remote_user = remote_host; *cursor = '\0'; remote_host = cursor + 1; } break; case ':': if (!remote_file) { *cursor = '\0'; remote_file = cursor + 1; } break; } } /* FIXME: Should somewhat validate the decoding, here. */ if (gethostbyname (remote_host) == NULL) error (EXIT_ON_EXEC_ERROR, 0, _("Cannot connect to %s: resolve failed"), remote_host); if (remote_user && *remote_user == '\0') remote_user = 0; #if WITH_REXEC /* Execute the remote command using rexec. */ READ_SIDE (remote_pipe_number) = _rmt_rexec (remote_host, remote_user); if (READ_SIDE (remote_pipe_number) < 0) { int e = errno; free (file_name_copy); errno = e; return -1; } WRITE_SIDE (remote_pipe_number) = READ_SIDE (remote_pipe_number); #else /* not WITH_REXEC */ { const char *remote_shell_basename; pid_t status; /* Identify the remote command to be executed. */ if (!remote_shell) { #ifdef REMOTE_SHELL remote_shell = REMOTE_SHELL; #else free (file_name_copy); errno = EIO; return -1; #endif } remote_shell_basename = last_component (remote_shell); /* Set up the pipes for the `rsh' command, and fork. */ if (pipe (to_remote[remote_pipe_number]) == -1 || pipe (from_remote[remote_pipe_number]) == -1) { int e = errno; free (file_name_copy); errno = e; return -1; } status = fork (); if (status == -1) { int e = errno; free (file_name_copy); errno = e; return -1; } if (status == 0) { /* Child. */ if (dup2 (to_remote[remote_pipe_number][PREAD], STDIN_FILENO) < 0 || (to_remote[remote_pipe_number][PREAD] != STDIN_FILENO && close (to_remote[remote_pipe_number][PREAD]) != 0) || (to_remote[remote_pipe_number][PWRITE] != STDIN_FILENO && close (to_remote[remote_pipe_number][PWRITE]) != 0) || dup2 (from_remote[remote_pipe_number][PWRITE], STDOUT_FILENO) < 0 || close (from_remote[remote_pipe_number][PREAD]) != 0 || close (from_remote[remote_pipe_number][PWRITE]) != 0) error (EXIT_ON_EXEC_ERROR, errno, _("Cannot redirect files for remote shell")); sys_reset_uid_gid (); if (remote_user) execl (remote_shell, remote_shell_basename, remote_host, "-l", remote_user, rmt_command, (char *) 0); else execl (remote_shell, remote_shell_basename, remote_host, rmt_command, (char *) 0); /* Bad problems if we get here. */ /* In a previous version, _exit was used here instead of exit. */ error (EXIT_ON_EXEC_ERROR, errno, _("Cannot execute remote shell")); } /* Parent. */ close (from_remote[remote_pipe_number][PWRITE]); close (to_remote[remote_pipe_number][PREAD]); } #endif /* not WITH_REXEC */ /* Attempt to open the tape device. */ { size_t remote_file_len = strlen (remote_file); char *command_buffer = xmalloc (remote_file_len + 1000); sprintf (command_buffer, "O%s\n", remote_file); encode_oflag (command_buffer + remote_file_len + 2, open_mode); strcat (command_buffer, "\n"); if (do_command (remote_pipe_number, command_buffer) == -1 || get_status (remote_pipe_number) == -1) { int e = errno; free (command_buffer); free (file_name_copy); _rmt_shutdown (remote_pipe_number, e); return -1; } free (command_buffer); } free (file_name_copy); return remote_pipe_number + bias; }
/* This function is called once for every file system object that fts encounters. fts performs a depth-first traversal. A directory is usually processed twice, first with fts_info == FTS_D, and later, after all of its entries have been processed, with FTS_DP. Return RM_ERROR upon error, RM_USER_DECLINED for a negative response to an interactive prompt, and otherwise, RM_OK. */ static enum RM_status rm_fts (FTS *fts, FTSENT *ent, struct rm_options const *x) { switch (ent->fts_info) { case FTS_D: /* preorder directory */ if (! x->recursive && !(x->remove_empty_directories && is_empty_dir (fts->fts_cwd_fd, ent->fts_accpath))) { /* This is the first (pre-order) encounter with a directory that we cannot delete. Not recursive, and it's not an empty directory (if we're removing them) so arrange to skip contents. */ int err = x->remove_empty_directories ? ENOTEMPTY : EISDIR; error (0, err, _("cannot remove %s"), quote (ent->fts_path)); mark_ancestor_dirs (ent); fts_skip_tree (fts, ent); return RM_ERROR; } /* Perform checks that can apply only for command-line arguments. */ if (ent->fts_level == FTS_ROOTLEVEL) { if (strip_trailing_slashes (ent->fts_path)) ent->fts_pathlen = strlen (ent->fts_path); /* If the basename of a command line argument is "." or "..", diagnose it and do nothing more with that argument. */ if (dot_or_dotdot (last_component (ent->fts_accpath))) { error (0, 0, _("cannot remove directory: %s"), quote (ent->fts_path)); fts_skip_tree (fts, ent); return RM_ERROR; } /* If a command line argument resolves to "/" (and --preserve-root is in effect -- default) diagnose and skip it. */ if (ROOT_DEV_INO_CHECK (x->root_dev_ino, ent->fts_statp)) { ROOT_DEV_INO_WARN (ent->fts_path); fts_skip_tree (fts, ent); return RM_ERROR; } } { Ternary is_empty_directory; enum RM_status s = prompt (fts, ent, true /*is_dir*/, x, PA_DESCEND_INTO_DIR, &is_empty_directory); if (s == RM_OK && is_empty_directory == T_YES) { /* When we know (from prompt when in interactive mode) that this is an empty directory, don't prompt twice. */ s = excise (fts, ent, x, true); fts_skip_tree (fts, ent); } if (s != RM_OK) { mark_ancestor_dirs (ent); fts_skip_tree (fts, ent); } return s; } case FTS_F: /* regular file */ case FTS_NS: /* stat(2) failed */ case FTS_SL: /* symbolic link */ case FTS_SLNONE: /* symbolic link without target */ case FTS_DP: /* postorder directory */ case FTS_DNR: /* unreadable directory */ case FTS_NSOK: /* e.g., dangling symlink */ case FTS_DEFAULT: /* none of the above */ { /* With --one-file-system, do not attempt to remove a mount point. fts' FTS_XDEV ensures that we don't process any entries under the mount point. */ if (ent->fts_info == FTS_DP && x->one_file_system && FTS_ROOTLEVEL < ent->fts_level && ent->fts_statp->st_dev != fts->fts_dev) { mark_ancestor_dirs (ent); error (0, 0, _("skipping %s, since it's on a different device"), quote (ent->fts_path)); return RM_ERROR; } bool is_dir = ent->fts_info == FTS_DP || ent->fts_info == FTS_DNR; enum RM_status s = prompt (fts, ent, is_dir, x, PA_REMOVE_DIR, NULL); if (s != RM_OK) return s; return excise (fts, ent, x, is_dir); } case FTS_DC: /* directory that causes cycles */ emit_cycle_warning (ent->fts_path); fts_skip_tree (fts, ent); return RM_ERROR; case FTS_ERR: /* Various failures, from opendir to ENOMEM, to failure to "return" to preceding directory, can provoke this. */ error (0, ent->fts_errno, _("traversal failed: %s"), quote (ent->fts_path)); fts_skip_tree (fts, ent); return RM_ERROR; default: error (0, 0, _("unexpected failure: fts_info=%d: %s\n" "please report to %s"), ent->fts_info, quote (ent->fts_path), PACKAGE_BUGREPORT); abort (); } }
char * xheader_format_name (struct tar_stat_info *st, const char *fmt, size_t n) { char *buf; size_t len = strlen (fmt); char *q; const char *p; char *dirp = NULL; char *dir = NULL; char *base = NULL; char pidbuf[UINTMAX_STRSIZE_BOUND]; char const *pptr = NULL; char nbuf[UINTMAX_STRSIZE_BOUND]; char const *nptr = NULL; for (p = fmt; *p && (p = strchr (p, '%')); ) { switch (p[1]) { case '%': len--; break; case 'd': if (st) { if (!dirp) dirp = dir_name (st->orig_file_name); dir = safer_name_suffix (dirp, false, absolute_names_option); len += strlen (dir) - 2; } break; case 'f': if (st) { base = last_component (st->orig_file_name); len += strlen (base) - 2; } break; case 'p': pptr = umaxtostr (getpid (), pidbuf); len += pidbuf + sizeof pidbuf - 1 - pptr - 2; break; case 'n': nptr = umaxtostr (n, nbuf); len += nbuf + sizeof nbuf - 1 - nptr - 2; break; } p++; } buf = xmalloc (len + 1); for (q = buf, p = fmt; *p; ) { if (*p == '%') { switch (p[1]) { case '%': *q++ = *p++; p++; break; case 'd': if (dir) q = stpcpy (q, dir); p += 2; break; case 'f': if (base) q = stpcpy (q, base); p += 2; break; case 'p': q = stpcpy (q, pptr); p += 2; break; case 'n': q = stpcpy (q, nptr); p += 2; break; default: *q++ = *p++; if (*p) *q++ = *p++; } } else *q++ = *p++; } free (dirp); /* Do not allow it to end in a slash */ while (q > buf && ISSLASH (q[-1])) q--; *q = 0; return buf; }
/* Rename the file SRC to DST. This replacement is necessary on Windows, on which the system rename function will not replace an existing DST. */ int rpl_rename (char const *src, char const *dst) { int error; size_t src_len = strlen (src); size_t dst_len = strlen (dst); char *src_base = last_component (src); char *dst_base = last_component (dst); bool src_slash; bool dst_slash; bool dst_exists; struct stat src_st; struct stat dst_st; /* Filter out dot as last component. */ if (!src_len || !dst_len) { errno = ENOENT; return -1; } if (*src_base == '.') { size_t len = base_len (src_base); if (len == 1 || (len == 2 && src_base[1] == '.')) { errno = EINVAL; return -1; } } if (*dst_base == '.') { size_t len = base_len (dst_base); if (len == 1 || (len == 2 && dst_base[1] == '.')) { errno = EINVAL; return -1; } } /* Presence of a trailing slash requires directory semantics. If the source does not exist, or if the destination cannot be turned into a directory, give up now. Otherwise, strip trailing slashes before calling rename. There are no symlinks on mingw, so stat works instead of lstat. */ src_slash = ISSLASH (src[src_len - 1]); dst_slash = ISSLASH (dst[dst_len - 1]); if (stat (src, &src_st)) return -1; if (stat (dst, &dst_st)) { if (errno != ENOENT || (!S_ISDIR (src_st.st_mode) && dst_slash)) return -1; dst_exists = false; } else { if (S_ISDIR (dst_st.st_mode) != S_ISDIR (src_st.st_mode)) { errno = S_ISDIR (dst_st.st_mode) ? EISDIR : ENOTDIR; return -1; } dst_exists = true; } /* There are no symlinks, so if a file existed with a trailing slash, it must be a directory, and we don't have to worry about stripping strip trailing slash. However, mingw refuses to replace an existing empty directory, so we have to help it out. And canonicalize_file_name is not yet ported to mingw; however, for directories, getcwd works as a viable alternative. Ensure that we can get back to where we started before using it; later attempts to return are fatal. Note that we can end up losing a directory if rename then fails, but it was empty, so not much damage was done. */ if (dst_exists && S_ISDIR (dst_st.st_mode)) { char *cwd = getcwd (NULL, 0); char *src_temp; char *dst_temp; if (!cwd || chdir (cwd)) return -1; if (IS_ABSOLUTE_FILE_NAME (src)) { dst_temp = chdir (dst) ? NULL : getcwd (NULL, 0); src_temp = chdir (src) ? NULL : getcwd (NULL, 0); } else { src_temp = chdir (src) ? NULL : getcwd (NULL, 0); if (!IS_ABSOLUTE_FILE_NAME (dst) && chdir (cwd)) abort (); dst_temp = chdir (dst) ? NULL : getcwd (NULL, 0); } if (chdir (cwd)) abort (); free (cwd); if (!src_temp || !dst_temp) { free (src_temp); free (dst_temp); errno = ENOMEM; return -1; } src_len = strlen (src_temp); if (strncmp (src_temp, dst_temp, src_len) == 0 && (ISSLASH (dst_temp[src_len]) || dst_temp[src_len] == '\0')) { error = dst_temp[src_len]; free (src_temp); free (dst_temp); if (error) { errno = EINVAL; return -1; } return 0; } if (rmdir (dst)) { error = errno; free (src_temp); free (dst_temp); errno = error; return -1; } free (src_temp); free (dst_temp); } /* MoveFileEx works if SRC is a directory without any flags, but fails with MOVEFILE_REPLACE_EXISTING, so try without flags first. Thankfully, MoveFileEx handles hard links correctly, even though rename() does not. */ if (MoveFileEx (src, dst, 0)) return 0; /* Retry with MOVEFILE_REPLACE_EXISTING if the move failed due to the destination already existing. */ error = GetLastError (); if (error == ERROR_FILE_EXISTS || error == ERROR_ALREADY_EXISTS) { if (MoveFileEx (src, dst, MOVEFILE_REPLACE_EXISTING)) return 0; error = GetLastError (); } switch (error) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_BAD_PATHNAME: case ERROR_DIRECTORY: errno = ENOENT; break; case ERROR_ACCESS_DENIED: case ERROR_SHARING_VIOLATION: errno = EACCES; break; case ERROR_OUTOFMEMORY: errno = ENOMEM; break; case ERROR_CURRENT_DIRECTORY: errno = EBUSY; break; case ERROR_NOT_SAME_DEVICE: errno = EXDEV; break; case ERROR_WRITE_PROTECT: errno = EROFS; break; case ERROR_WRITE_FAULT: case ERROR_READ_FAULT: case ERROR_GEN_FAILURE: errno = EIO; break; case ERROR_HANDLE_DISK_FULL: case ERROR_DISK_FULL: case ERROR_DISK_TOO_FRAGMENTED: errno = ENOSPC; break; case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: errno = EEXIST; break; case ERROR_BUFFER_OVERFLOW: case ERROR_FILENAME_EXCED_RANGE: errno = ENAMETOOLONG; break; case ERROR_INVALID_NAME: case ERROR_DELETE_PENDING: errno = EPERM; /* ? */ break; # ifndef ERROR_FILE_TOO_LARGE /* This value is documented but not defined in all versions of windows.h. */ # define ERROR_FILE_TOO_LARGE 223 # endif case ERROR_FILE_TOO_LARGE: errno = EFBIG; break; default: errno = EINVAL; break; } return -1; }
/* Start a recursive command. Command line arguments (ARGC, ARGV) dictate the directories and files on which we operate. In the special case of no arguments, we default to ".". */ int start_recursion (FILEPROC fileproc, FILESDONEPROC filesdoneproc, PREDIRENTPROC predirentproc, DIRENTPROC direntproc, DIRLEAVEPROC dirleaveproc, void *callerdat, int argc, char **argv, int local, /* This specifies the kind of recursion. There are several cases: 1. W_LOCAL is not set but W_REPOS is. The current directory when we are called must be the repository and recursion proceeds according to what exists in the repository. 2a. W_LOCAL is set but W_REPOS is not. The current directory when we are called must be the working directory. Recursion proceeds according to what exists in the working directory, never (I think) consulting any part of the repository which does not correspond to the working directory ("correspond" == Name_Repository). 2b. W_LOCAL is set and so is W_REPOS. This is the weird one. The current directory when we are called must be the working directory. We recurse through working directories, but we recurse into a directory if it is exists in the working directory *or* it exists in the repository. If a directory does not exist in the working directory, the direntproc must either tell us to skip it (R_SKIP_ALL), or must create it (I think those are the only two cases). */ int which, int aflag, int readlock, const char *update_preload, const char *repos_preload, int dosrcs, PERMPROC permproc, const char *tag) { int i, err = 0; List *args_to_send_when_finished = NULL; List *files_by_dir = NULL; struct recursion_frame frame; TRACE(3,"start_recursion()"); frame.fileproc = fileproc; frame.filesdoneproc = filesdoneproc; frame.predirentproc = predirentproc; frame.direntproc = direntproc; frame.dirleaveproc = dirleaveproc; frame.callerdat = callerdat; frame.flags = local ? R_SKIP_DIRS : R_PROCESS; frame.which = which; frame.aflag = aflag; frame.readlock = readlock; frame.dosrcs = dosrcs; frame.permproc = permproc; frame.tag = tag; expand_wild (argc, argv, &argc, &argv); if (update_preload == NULL) update_dir = xstrdup (""); else update_dir = xstrdup (update_preload); /* clean up from any previous calls to start_recursion */ xfree (repository); if (filelist) dellist (&filelist); /* FIXME-krp: no longer correct. */ if (dirlist) dellist (&dirlist); update_repos = xstrdup(repos_preload); for (i = 0; i < argc; ++i) { #ifdef SERVER_SUPPORT if (server_active) server_pathname_check (argv[i]); else #endif if(isabsolute(argv[i])) error(1,0,"Absolute filenames not allowed"); } if (argc == 0) { int just_subdirs = (which & W_LOCAL) && !noexec && !isdir (CVSADM); if (!just_subdirs && CVSroot_cmdline == NULL && current_parsed_root->isremote) { char *root = Name_Root (NULL, update_dir); if (root && strcmp (root, current_parsed_root->original) != 0) /* We're skipping this directory because it is for a different root. Therefore, we just want to do the subdirectories only. Processing files would cause a working directory from one repository to be processed against a different repository, which could cause all kinds of spurious conflicts and such. Question: what about the case of "cvs update foo" where we process foo/bar and not foo itself? That seems to be handled somewhere (else) but why should it be a separate case? Needs investigation... */ just_subdirs = 1; xfree (root); } /* * There were no arguments, so we'll probably just recurse. The * exception to the rule is when we are called from a directory * without any CVS administration files. That has always meant to * process each of the sub-directories, so we pretend like we were * called with the list of sub-dirs of the current dir as args */ if (just_subdirs) { dirlist = Find_Directories ((char *) NULL, W_LOCAL, (List *) NULL, NULL); /* If there are no sub-directories, there is a certain logic in favor of doing nothing, but in fact probably the user is just confused about what directory they are in, or whether they cvs add'd a new directory. In the case of at least one sub-directory, at least when we recurse into them we notice (hopefully) whether they are under CVS control. */ if (list_isempty (dirlist) && !noexec) { if (update_dir[0] == '\0') error (0, 0, "in directory .:"); else error (0, 0, "in directory %s:", update_dir); error (1, 0, "there is no version here; run '%s checkout' first", program_name); } else if (current_parsed_root->isremote && server_started) { /* In the the case "cvs update foo bar baz", a call to send_file_names in update.c will have sent the appropriate "Argument" commands to the server. In this case, that won't have happened, so we need to do it here. While this example uses "update", this generalizes to other commands. */ /* This is the same call to Find_Directories as above. FIXME: perhaps it would be better to write a function that duplicates a list. */ args_to_send_when_finished = Find_Directories ((char *) NULL, W_LOCAL, (List *) NULL, NULL); } } else { addlist (&dirlist, "."); } goto do_the_work; } /* * There were arguments, so we have to handle them by hand. To do * that, we set up the filelist and dirlist with the arguments and * call do_recursion. do_recursion recognizes the fact that the * lists are non-null when it starts and doesn't update them. * * explicitly named directories are stored in dirlist. * explicitly named files are stored in filelist. * other possibility is named entities whicha are not currently in * the working directory. */ for (i = 0; i < argc; i++) { /* if this argument is a directory, then add it to the list of directories. */ if (isdir (argv[i])) { strip_trailing_slashes (argv[i]); addlist (&dirlist, argv[i]); } else { /* otherwise, split argument into directory and component names. */ char *dir; char *comp; char *file_to_try; /* Now break out argv[i] into directory part (DIR) and file part (COMP). DIR and COMP will each point to a newly malloc'd string. */ dir = xstrdup (argv[i]); comp = (char*)last_component (dir); if (comp == dir) { /* no dir component. What we have is an implied "./" */ dir = xstrdup("."); } else { char *p = comp; p[-1] = '\0'; comp = xstrdup (p); } /* if this argument exists as a file in the current working directory tree, then add it to the files list. */ if (!(which & W_LOCAL)) { /* If doing rtag, we've done a chdir to the repository. */ file_to_try = (char*)xmalloc (strlen (argv[i]) + sizeof (RCSEXT) + 5); sprintf (file_to_try, "%s%s", argv[i], RCSEXT); } else file_to_try = xstrdup (argv[i]); if (isfile (file_to_try)) { const char *tag; const char *date; int nonbranch; const char *message; const char *v_type; /* before we do anything else, see if we have any per-directory tags */ ParseTag_Dir (dir, &tag, &date, &nonbranch, NULL); if (! verify_access (frame.permproc, dir, file_to_try, update_dir,tag,&message,&v_type)) { if(tag && !quiet && !(which&W_QUIET)) error (0, 0, "User %s is unable to %s %s/%s on branch/tag %s - ignoring",CVS_Username,v_type,dir,file_to_try?file_to_try:"",tag); else if(!quiet && !(which&W_QUIET)) error (0, 0, "User %s is unable to %s %s/%s - ignoring",CVS_Username,v_type,dir,file_to_try?file_to_try:""); if(message && !quiet && !(which&W_QUIET)) error (0, 0, "%s", message); } else { addfile (&files_by_dir, dir, comp); } } else if (isdir (dir)) { if ((which & W_LOCAL) && isdir (CVSADM) && !current_parsed_root->isremote ) { /* otherwise, look for it in the repository. */ char *tmp_update_dir; char *repos; char *reposfile; tmp_update_dir = (char*)xmalloc (strlen (update_dir) + strlen (dir) + 5); strcpy (tmp_update_dir, update_dir); if (*tmp_update_dir != '\0') (void) strcat (tmp_update_dir, "/"); (void) strcat (tmp_update_dir, dir); /* look for it in the repository. */ repos = Name_Repository (dir, tmp_update_dir); reposfile = (char*)xmalloc (strlen (repos) + strlen (comp) + 5); (void) sprintf (reposfile, "%s/%s", repos, comp); xfree (repos); if (isdir (reposfile)) { addlist (&dirlist, argv[i]); } else addfile (&files_by_dir, dir, comp); xfree (tmp_update_dir); xfree (reposfile); } else addfile (&files_by_dir, dir, comp); } else { error (1, 0, "no such directory `%s'", dir); } xfree (file_to_try); xfree (dir); xfree (comp); } } /* At this point we have looped over all named arguments and built a coupla lists. Now we unroll the lists, setting up and calling do_recursion. */ err += walklist (files_by_dir, unroll_files_proc, (void *) &frame); if (files_by_dir) dellist(&files_by_dir); /* then do_recursion on the dirlist. */ if (dirlist != NULL) { do_the_work: err += do_recursion (&frame, 1); } /* Free the data which expand_wild allocated. */ free_names (&argc, argv); xfree (update_dir); xfree (update_repos); if (args_to_send_when_finished != NULL) { /* FIXME (njc): in the multiroot case, we don't want to send argument commands for those top-level directories which do not contain any subdirectories which have files checked out from current_parsed_root->original. If we do, and two repositories have a module with the same name, nasty things could happen. This is hard. Perhaps we should send the Argument commands later in this procedure, after we've had a chance to notice which directores we're using (after do_recursion has been called once). This means a _lot_ of rewriting, however. What we need to do for that to happen is descend the tree and construct a list of directories which are checked out from current_cvsroot. Now, we eliminate from the list all of those directories which are immediate subdirectories of another directory in the list. To say that the opposite way, we keep the directories which are not immediate subdirectories of any other in the list. Here's a picture: a / \ B C / \ D e / \ F G / \ H I The node in capitals are those directories which are checked out from current_cvsroot. We want the list to contain B, C, F, and G. D, H, and I are not included, because their parents are also checked out from current_cvsroot. The algorithm should be: 1) construct a tree of all directory names where each element contains a directory name and a flag which notes if that directory is checked out from current_cvsroot a0 / \ B1 C1 / \ D1 e0 / \ F1 G1 / \ H1 I1 2) Recursively descend the tree. For each node, recurse before processing the node. If the flag is zero, do nothing. If the flag is 1, check the node's parent. If the parent's flag is one, change the current entry's flag to zero. a0 / \ B1 C1 / \ D0 e0 / \ F1 G1 / \ H0 I0 3) Walk the tree and spit out "Argument" commands to tell the server which directories to munge. Yuck. It's not clear this is worth spending time on, since we might want to disable cvs commands entirely from directories that do not have CVSADM files... Anyways, the solution as it stands has modified server.c (dirswitch) to create admin files [via server.c (create_adm_p)] in all path elements for a client's "Directory xxx" command, which forces the server to descend and serve the files there. client.c (send_file_names) has also been modified to send only those arguments which are appropriate to current_parsed_root->original. */ /* Construct a fake argc/argv pair. */ int our_argc = 0, i; char **our_argv = NULL; if (! list_isempty (args_to_send_when_finished)) { Node *head, *p; head = args_to_send_when_finished->list; /* count the number of nodes */ i = 0; for (p = head->next; p != head; p = p->next) i++; our_argc = i; /* create the argument vector */ our_argv = (char **) xmalloc (sizeof (char *) * our_argc); /* populate it */ i = 0; for (p = head->next; p != head; p = p->next) our_argv[i++] = xstrdup (p->key); } /* We don't want to expand widcards, since we've just created a list of directories directly from the filesystem. */ send_file_names (our_argc, our_argv, 0); /* Free our argc/argv. */ if (our_argv != NULL) { for (i = 0; i < our_argc; i++) xfree (our_argv[i]); xfree (our_argv); } if (args_to_send_when_finished) dellist (&args_to_send_when_finished); } return (err); }