/* mounts, creating the device if needed+possible */ int my_mount(const char *dev, const char *location, const char *fs, int force_rw) { unsigned long flags = MS_MGC_VAL | (force_rw ? 0 : MS_RDONLY); char * opts = NULL; struct stat buf; int rc; if (strcmp(fs, "nfs")) { rc = ensure_dev_exists(dev); if (rc != 0) { log_message("could not create required device file"); return -1; } } log_message("mounting %s on %s as type %s", dev, location, fs); if (stat(location, &buf)) { if (mkdir(location, 0755)) { log_perror("could not create location dir"); return -1; } } else if (!S_ISDIR(buf.st_mode)) { log_message("not a dir %s, will unlink and mkdir", location); if (unlink(location)) { log_perror("could not unlink"); return -1; } if (mkdir(location, 0755)) { log_perror("could not create location dir"); return -1; } } #ifndef DISABLE_MEDIAS if (!strcmp(fs, "vfat")) { my_modprobe("nls_cp437", ANY_DRIVER_TYPE, NULL); my_modprobe("nls_iso8859_1", ANY_DRIVER_TYPE, NULL); my_modprobe("vfat", ANY_DRIVER_TYPE, NULL); opts = (char*)"check=relaxed"; } if (!strcmp(fs, "ntfs")) { my_modprobe("ntfs", ANY_DRIVER_TYPE, NULL); } if (!strcmp(fs, "reiserfs")) my_modprobe("reiserfs", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "reiser4")) my_modprobe("reiser4", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "jfs")) my_modprobe("jfs", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "xfs")) my_modprobe("xfs", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "ext4")) my_modprobe("ext4", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "btrfs")) my_modprobe("btrfs", ANY_DRIVER_TYPE, NULL); #endif if (!strcmp(fs, "iso9660")) my_modprobe("isofs", ANY_DRIVER_TYPE, NULL); #ifndef DISABLE_NETWORK if (!strcmp(fs, "nfs")) { my_modprobe("nfs", ANY_DRIVER_TYPE, NULL); log_message("preparing nfsmount for %s", dev); rc = nfsmount_prepare(dev, &opts); if (rc != 0) return rc; } #endif rc = mount(dev, location, fs, flags, opts); if (rc != 0) { log_perror("mount failed"); rmdir(location); } return rc; }
int rm_r(const char *path) { int ret = 0; DIR *dir; struct dirent *dent; if (path == NULL) { opkg_perror(ERROR, "Missing directory parameter"); return -1; } dir = opendir(path); if (dir == NULL) { opkg_perror(ERROR, "Failed to open dir %s", path); return -1; } if (fchdir(dirfd(dir)) == -1) { opkg_perror(ERROR, "Failed to change to dir %s", path); closedir(dir); return -1; } while (1) { errno = 0; if ((dent = readdir(dir)) == NULL) { if (errno) { opkg_perror(ERROR, "Failed to read dir %s", path); ret = -1; } break; } if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; #ifdef _BSD_SOURCE if (dent->d_type == DT_DIR) { if ((ret = rm_r(dent->d_name)) == -1) break; continue; } else if (dent->d_type == DT_UNKNOWN) #endif { struct stat st; if ((ret = lstat(dent->d_name, &st)) == -1) { opkg_perror(ERROR, "Failed to lstat %s", dent->d_name); break; } if (S_ISDIR(st.st_mode)) { if ((ret = rm_r(dent->d_name)) == -1) break; continue; } } if ((ret = unlink(dent->d_name)) == -1) { opkg_perror(ERROR, "Failed to unlink %s", dent->d_name); break; } } if (chdir("..") == -1) { ret = -1; opkg_perror(ERROR, "Failed to change to dir %s/..", path); } if (rmdir(path) == -1 ) { ret = -1; opkg_perror(ERROR, "Failed to remove dir %s", path); } if (closedir(dir) == -1) { ret = -1; opkg_perror(ERROR, "Failed to close dir %s", path); } return ret; }
/* * remove_tablespace_directories: attempt to remove filesystem infrastructure * * Returns TRUE if successful, FALSE if some subdirectory is not empty * * redo indicates we are redoing a drop from XLOG; okay if nothing there */ static bool remove_tablespace_directories(Oid tablespaceoid, bool redo) { char *location; DIR *dirdesc; struct dirent *de; char *subfile; struct stat st; location = (char *) palloc(10 + 10 + 1); sprintf(location, "pg_tblspc/%u", tablespaceoid); /* * Check if the tablespace still contains any files. We try to rmdir each * per-database directory we find in it. rmdir failure implies there are * still files in that subdirectory, so give up. (We do not have to worry * about undoing any already completed rmdirs, since the next attempt to * use the tablespace from that database will simply recreate the * subdirectory via TablespaceCreateDbspace.) * * Since we hold TablespaceCreateLock, no one else should be creating any * fresh subdirectories in parallel. It is possible that new files are * being created within subdirectories, though, so the rmdir call could * fail. Worst consequence is a less friendly error message. */ dirdesc = AllocateDir(location); if (dirdesc == NULL) { if (redo && errno == ENOENT) { pfree(location); return true; } /* else let ReadDir report the error */ } while ((de = ReadDir(dirdesc, location)) != NULL) { /* Note we ignore PG_VERSION for the nonce */ if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0 || strcmp(de->d_name, "PG_VERSION") == 0) continue; subfile = palloc(strlen(location) + 1 + strlen(de->d_name) + 1); sprintf(subfile, "%s/%s", location, de->d_name); /* This check is just to deliver a friendlier error message */ if (!directory_is_empty(subfile)) { FreeDir(dirdesc); return false; } /* Do the real deed */ if (rmdir(subfile) < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not delete directory \"%s\": %m", subfile))); pfree(subfile); } FreeDir(dirdesc); /* * Okay, try to unlink PG_VERSION (we allow it to not be there, even in * non-REDO case, for robustness). */ subfile = palloc(strlen(location) + 11 + 1); sprintf(subfile, "%s/PG_VERSION", location); if (unlink(subfile) < 0) { if (errno != ENOENT) ereport(ERROR, (errcode_for_file_access(), errmsg("could not remove file \"%s\": %m", subfile))); } pfree(subfile); /* * Okay, try to remove the symlink. We must however deal with the * possibility that it's a directory instead of a symlink --- this could * happen during WAL replay (see TablespaceCreateDbspace), and it is also * the normal case on Windows. */ if (lstat(location, &st) == 0 && S_ISDIR(st.st_mode)) { if (rmdir(location) < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not remove directory \"%s\": %m", location))); } else { if (unlink(location) < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not remove symbolic link \"%s\": %m", location))); } pfree(location); return true; }
int _alpm_runscriptlet(alpm_handle_t *handle, const char *filepath, const char *script, const char *ver, const char *oldver, int is_archive) { char arg0[64], arg1[3], cmdline[PATH_MAX]; char *argv[] = { arg0, arg1, cmdline, NULL }; char *tmpdir, *scriptfn = NULL, *scriptpath; int retval = 0; size_t len; if(_alpm_access(handle, NULL, filepath, R_OK) != 0) { _alpm_log(handle, ALPM_LOG_DEBUG, "scriptlet '%s' not found\n", filepath); return 0; } if(!is_archive && !grep(filepath, script)) { /* script not found in scriptlet file; we can only short-circuit this early * if it is an actual scriptlet file and not an archive. */ return 0; } strcpy(arg0, SCRIPTLET_SHELL); strcpy(arg1, "-c"); /* create a directory in $root/tmp/ for copying/extracting the scriptlet */ len = strlen(handle->root) + strlen("tmp/alpm_XXXXXX") + 1; MALLOC(tmpdir, len, RET_ERR(handle, ALPM_ERR_MEMORY, -1)); snprintf(tmpdir, len, "%stmp/", handle->root); if(access(tmpdir, F_OK) != 0) { _alpm_makepath_mode(tmpdir, 01777); } snprintf(tmpdir, len, "%stmp/alpm_XXXXXX", handle->root); if(mkdtemp(tmpdir) == NULL) { _alpm_log(handle, ALPM_LOG_ERROR, _("could not create temp directory\n")); free(tmpdir); return 1; } /* either extract or copy the scriptlet */ len += strlen("/.INSTALL"); MALLOC(scriptfn, len, free(tmpdir); RET_ERR(handle, ALPM_ERR_MEMORY, -1)); snprintf(scriptfn, len, "%s/.INSTALL", tmpdir); if(is_archive) { if(_alpm_unpack_single(handle, filepath, tmpdir, ".INSTALL")) { retval = 1; } } else { if(_alpm_copyfile(filepath, scriptfn)) { _alpm_log(handle, ALPM_LOG_ERROR, _("could not copy tempfile to %s (%s)\n"), scriptfn, strerror(errno)); retval = 1; } } if(retval == 1) { goto cleanup; } if(is_archive && !grep(scriptfn, script)) { /* script not found in extracted scriptlet file */ goto cleanup; } /* chop off the root so we can find the tmpdir in the chroot */ scriptpath = scriptfn + strlen(handle->root) - 1; if(oldver) { snprintf(cmdline, PATH_MAX, ". %s; %s %s %s", scriptpath, script, ver, oldver); } else { snprintf(cmdline, PATH_MAX, ". %s; %s %s", scriptpath, script, ver); } _alpm_log(handle, ALPM_LOG_DEBUG, "executing \"%s\"\n", cmdline); retval = _alpm_run_chroot(handle, SCRIPTLET_SHELL, argv); cleanup: if(scriptfn && unlink(scriptfn)) { _alpm_log(handle, ALPM_LOG_WARNING, _("could not remove %s\n"), scriptfn); } if(rmdir(tmpdir)) { _alpm_log(handle, ALPM_LOG_WARNING, _("could not remove tmpdir %s\n"), tmpdir); } free(scriptfn); free(tmpdir); return retval; }
static void rm_tree(char **argv) { FTS *fts; FTSENT *p; int needstat; int flags; int rval; /* * Remove a file hierarchy. If forcing removal (-f), or interactive * (-i) or can't ask anyway (stdin_ok), don't stat the file. */ needstat = !uid || (!fflag && !iflag && stdin_ok); /* * If the -i option is specified, the user can skip on the pre-order * visit. The fts_number field flags skipped directories. */ #define SKIPPED 1 flags = FTS_PHYSICAL; if (!needstat) flags |= FTS_NOSTAT; if (Wflag) flags |= FTS_WHITEOUT; if (xflag) flags |= FTS_XDEV; if (!(fts = fts_open(argv, flags, NULL))) { if (fflag && errno == ENOENT) return; err(1, "fts_open"); } while ((p = fts_read(fts)) != NULL) { switch (p->fts_info) { case FTS_DNR: if (!fflag || p->fts_errno != ENOENT) { warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); eval = 1; } continue; case FTS_ERR: errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno)); case FTS_NS: /* * Assume that since fts_read() couldn't stat the * file, it can't be unlinked. */ if (!needstat) break; if (!fflag || p->fts_errno != ENOENT) { warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); eval = 1; } continue; case FTS_D: /* Pre-order: give user chance to skip. */ if (!fflag && !check(p->fts_path, p->fts_accpath, p->fts_statp)) { (void)fts_set(fts, p, FTS_SKIP); p->fts_number = SKIPPED; } else if (!uid && (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) && !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) && lchflags(p->fts_accpath, p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0) goto err; continue; case FTS_DP: /* Post-order: see if user skipped. */ if (p->fts_number == SKIPPED) continue; break; default: if (!fflag && !check(p->fts_path, p->fts_accpath, p->fts_statp)) continue; } rval = 0; if (!uid && (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) && !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE))) rval = lchflags(p->fts_accpath, p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)); if (rval == 0) { /* * If we can't read or search the directory, may still be * able to remove it. Don't print out the un{read,search}able * message unless the remove fails. */ switch (p->fts_info) { case FTS_DP: case FTS_DNR: rval = rmdir(p->fts_accpath); if (rval == 0 || (fflag && errno == ENOENT)) { if (rval == 0 && vflag) (void)printf("%s\n", p->fts_path); if (rval == 0 && info) { info = 0; (void)printf("%s\n", p->fts_path); } continue; } break; case FTS_W: rval = undelete(p->fts_accpath); if (rval == 0 && (fflag && errno == ENOENT)) { if (vflag) (void)printf("%s\n", p->fts_path); if (info) { info = 0; (void)printf("%s\n", p->fts_path); } continue; } break; case FTS_NS: /* * Assume that since fts_read() couldn't stat * the file, it can't be unlinked. */ if (fflag) continue; /* FALLTHROUGH */ case FTS_F: case FTS_NSOK: if (Pflag) if (!rm_overwrite(p->fts_accpath, p->fts_info == FTS_NSOK ? NULL : p->fts_statp)) continue; /* FALLTHROUGH */ default: rval = unlink(p->fts_accpath); if (rval == 0 || (fflag && errno == ENOENT)) { if (rval == 0 && vflag) (void)printf("%s\n", p->fts_path); if (rval == 0 && info) { info = 0; (void)printf("%s\n", p->fts_path); } continue; } } } err: warn("%s", p->fts_path); eval = 1; } if (!fflag && errno) err(1, "fts_read"); fts_close(fts); }
int main(int argc, char **argv) { FILE *cgf; bool found_zdtmtstroot = false, found_newroot = false; char paux[1024]; int ret = -1; int fd; test_init(argc, argv); if (mount_and_add(cgname, "prefix", subname)) goto out; if (mount_and_add(cgname2, "prefix", subname)) { sprintf(paux, "%s/%s", dirname, cgname); umount(paux); rmdir(paux); goto out; } sprintf(paux, "%s/%s/prefix", dirname, cgname); fd = open(paux, O_DIRECTORY); if (fd < 0) goto out_umount; if (fchmod(fd, 0777) < 0) { fail("fchmod"); goto out_umount; } test_daemon(); test_waitsig(); if (close(fd) < 0) { fail("fd didn't survive"); goto out_umount; } cgf = fopen("/proc/self/mountinfo", "r"); if (cgf == NULL) { fail("No mountinfo file"); goto out_umount; } while (fgets(paux, sizeof(paux), cgf)) { char *s; s = strstr(paux, cgname); if (s && test_exists(paux, "prefix")) { found_zdtmtstroot = true; } s = strstr(paux, cgname2); if (s && test_exists(paux, "newroot")) { found_newroot = true; } } if (!found_zdtmtstroot) { fail("oldroot not rewritten to zdtmtstroot!\n"); goto out_close; } if (!found_newroot) { fail("oldroot not rewritten to newroot!\n"); goto out_close; } pass(); ret = 0; out_close: fclose(cgf); out_umount: sprintf(paux, "%s/%s", dirname, cgname); umount(paux); rmdir(paux); sprintf(paux, "%s/%s", dirname, cgname2); umount(paux); rmdir(paux); out: return ret; }
int comando_apagadir(char * nome_dir) { return rmdir(nome_dir); }
VOID UpdateFilebase (USHORT KeepDate) { FILE *fp; DIR *dir; ULONG Total, Added; CHAR *p, Path[128], Temp[128]; time_t today; struct stat statbuf; struct tm *ltm; struct dirent *ent; class TFileData *Data; class TFileBase *File; class TPacker *Packer; printf (" * Updating filebase\r\n"); unlink ("file_id.diz"); Packer = new TPacker (Cfg->SystemPath); if ((Data = new TFileData (Cfg->SystemPath)) != NULL) { if (Data->First () == TRUE) do { Total = 0L; Added = 0L; cprintf (" +-- %-15.15s %-32.32s ", Data->Key, Data->Display); if ((File = new TFileBase (Cfg->SystemPath, Data->Key)) != NULL) { strcpy (Temp, Data->Download); if (Temp[strlen (Temp) - 1] == '\\' || Temp[strlen (Temp) - 1] == '/') Temp[strlen (Temp) - 1] = '\0'; if (File->First () == TRUE) do { sprintf (Path, "%s%s", Data->Download, File->Name); if (stat (AdjustPath (Path), &statbuf)) File->Delete (); } while (File->Next () == TRUE); File->SortByName (); if ((dir = opendir (AdjustPath (Temp))) != NULL) { while ((ent = readdir (dir)) != NULL) { if (!strcmp (ent->d_name, ".") || !strcmp (ent->d_name, "..")) continue; if (!stricmp (ent->d_name, "files.bbs") || !stricmp (ent->d_name, "descript.ion")) continue; if (File->Read (ent->d_name) == FALSE) { sprintf (Path, "%s%s", Data->Download, ent->d_name); if (!stat (AdjustPath (Path), &statbuf)) { File->Clear (); strcpy (File->Area, Data->Key); strcpy (File->Name, ent->d_name); strcpy (File->Complete, Path); File->Size = statbuf.st_size; ltm = localtime ((time_t *)&statbuf.st_mtime); File->Date.Day = (UCHAR)ltm->tm_mday; File->Date.Month = (UCHAR)(ltm->tm_mon + 1); File->Date.Year = (USHORT)(ltm->tm_year + 1900); File->Date.Hour = (UCHAR)ltm->tm_hour; File->Date.Minute = (UCHAR)ltm->tm_min; if (KeepDate == FALSE) { today = time (NULL); ltm = localtime (&today); File->UplDate.Day = (UCHAR)ltm->tm_mday; File->UplDate.Month = (UCHAR)(ltm->tm_mon + 1); File->UplDate.Year = (USHORT)(ltm->tm_year + 1900); File->UplDate.Hour = (UCHAR)ltm->tm_hour; File->UplDate.Minute = (UCHAR)ltm->tm_min; } else { File->UplDate.Day = File->Date.Day; File->UplDate.Month = File->Date.Month; File->UplDate.Year = File->Date.Year; File->UplDate.Hour = File->Date.Hour; File->UplDate.Minute = File->Date.Minute; } File->Uploader = "Sysop"; File->CdRom = Data->CdRom; File->Description->Add ("Description missing"); if (Packer != NULL) { if (Packer->CheckArc (Path) == TRUE) { #if defined(__LINUX__) mkdir ("lfiletmp", 0666); #else mkdir ("lfiletmp"); #endif if (strstr (Packer->UnpackCmd, "%3") == NULL && strstr (Packer->UnpackCmd, "%f") == NULL) strcat (Packer->UnpackCmd, " %3"); Packer->DoUnpack (Path, "lfiletmp", "file_id.diz"); strcpy (Temp, "lfiletmp\\file_id.diz"); if (!stat (AdjustPath (Temp), &statbuf)) { if ((fp = fopen (Temp, "rt")) != NULL) { File->Description->Clear (); while (fgets (Temp, sizeof (Temp) - 1, fp) != NULL) { if ((p = strchr (Temp, '\n')) != NULL) *p = '\0'; if ((p = strchr (Temp, '\r')) != NULL) *p = '\0'; File->Description->Add (Temp); } fclose (fp); } strcpy (Temp, "lfiletmp\\file_id.diz"); unlink (AdjustPath (Temp)); } rmdir ("lfiletmp"); } } File->Add (); Added++; } } Total++; } closedir (dir); } delete File; } cprintf ("Total: %5lu Added: %5lu\r\n", Total, Added); } while (Data->Next () == TRUE); delete Data; } if (Packer != NULL) delete Packer; }
void remove_directory(char *dir) { rmdir(dir); free(dir); }
int main(int ac, char **av) { int lc; /* loop counter */ char *msg; /* message returned from parse_opts */ /*************************************************************** * parse standard options ***************************************************************/ if ((msg = parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *)NULL) tst_brkm(TBROK, cleanup, "OPTION PARSING ERROR - %s", msg); /*************************************************************** * perform global setup for test ***************************************************************/ setup(); /* set the expected errnos... */ TEST_EXP_ENOS(exp_enos); /*************************************************************** * check looping state if -c option given ***************************************************************/ for (lc = 0; TEST_LOOPING(lc); lc++) { /* reset Tst_count in case we are looping. */ Tst_count = 0; if (mkdir(fname, 0777) == -1) { tst_brkm(TBROK, cleanup, "mkdir(%s) Failure. errno=%d : %s", fname, errno, strerror(errno)); } /* * Call rmdir(2) */ TEST(rmdir(fname)); /* check return code */ if (TEST_RETURN == -1) { TEST_ERROR_LOG(TEST_ERRNO); tst_resm(TFAIL, "rmdir(%s) Failed, errno=%d : %s", fname, TEST_ERRNO, strerror(TEST_ERRNO)); } else { /*************************************************************** * only perform functional verification if flag set (-f not given) ***************************************************************/ if (STD_FUNCTIONAL_TEST) { /* No Verification test, yet... */ tst_resm(TPASS, "rmdir(%s) returned %ld", fname, TEST_RETURN); } } } /* End for TEST_LOOPING */ /*************************************************************** * cleanup and exit ***************************************************************/ cleanup(); return 0; } /* End main */
int main(void) { #ifndef TEST_BZIP2 return 77; #else const char *filedir = "dirfile"; const char *format = "dirfile/format"; const char *format1 = "dirfile/format1"; const char *data = "dirfile/data"; const char *bz2data = "dirfile/data.bz2"; const char *format_data = "/INCLUDE format1\ndata RAW UINT16 11\nENCODING bzip2\n"; const char *format1_data = "ENCODING none\n"; uint16_t data_data[128]; int fd, ret, error, ge_ret, unlink_data, unlink_bz2data, r = 0, i = 0; char command[4096]; gd_entry_t E; DIRFILE *D; uint16_t d; rmdirfile(); mkdir(filedir, 0777); for (fd = 0; fd < 128; ++fd) data_data[fd] = fd * 0x201; fd = open(format, O_CREAT | O_EXCL | O_WRONLY, 0666); write(fd, format_data, strlen(format_data)); close(fd); fd = open(format1, O_CREAT | O_EXCL | O_WRONLY, 0666); write(fd, format1_data, strlen(format1_data)); close(fd); fd = open(data, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, 0666); write(fd, data_data, 128 * sizeof(uint16_t)); close(fd); /* compress */ snprintf(command, 4096, "%s -f %s > /dev/null", BZIP2, data); if (gd_system(command)) return 1; #ifdef USE_BZIP2 D = gd_open(filedir, GD_RDWR | GD_VERBOSE | GD_UNENCODED); #else D = gd_open(filedir, GD_RDWR | GD_UNENCODED); #endif ret = gd_move(D, "data", 1, 1); error = gd_error(D); ge_ret = gd_entry(D, "data", &E); gd_close(D); #ifdef USE_BZIP2 fd = open(data, O_RDONLY | O_BINARY); if (fd >= 0) { while (read(fd, &d, sizeof(uint16_t))) { CHECKI(d, i * 0x201); i++; } close(fd); } else { perror("open"); r = 1; } #endif unlink(format1); unlink(format); unlink_data = unlink(data); unlink_bz2data = unlink(bz2data); rmdir(filedir); #ifdef USE_BZIP2 CHECKI(ret, 0); CHECKI(error, GD_E_OK); CHECKI(ge_ret, 0); CHECKI(E.fragment_index, 1); CHECKI(unlink_data, 0); CHECKI(unlink_bz2data, -1); #else CHECKI(ret, -1); CHECKI(error, GD_E_UNSUPPORTED); CHECKI(ge_ret, 0); CHECKI(E.fragment_index, 0); CHECKI(unlink_data, -1); CHECKI(unlink_bz2data, 0); #endif gd_free_entry_strings(&E); return r; #endif }
void setup_data_media() { rmdir("/sdcard"); mkdir("/data/media", 0755); symlink("/data/media", "/sdcard"); }
/* main: * Guess what this function does. */ int main(int argc, char *argv[]) { PACKFILE *f; CFURLRef cf_url_ref; FSRef fs_ref; FSSpec fs_spec; IconFamilyHandle icon_family; Handle raw_data; char datafile[MAX_STRING_SIZE]; char bundle[MAX_STRING_SIZE]; char bundle_dir[MAX_STRING_SIZE]; char bundle_contents_dir[MAX_STRING_SIZE]; char bundle_contents_resources_dir[MAX_STRING_SIZE]; char bundle_contents_macos_dir[MAX_STRING_SIZE]; char bundle_contents_frameworks_dir[MAX_STRING_SIZE]; char *bundle_exe = NULL; char bundle_plist[MAX_STRING_SIZE]; char bundle_pkginfo[MAX_STRING_SIZE]; char bundle_icns[MAX_STRING_SIZE]; char bundle_version[MAX_STRING_SIZE]; char bundle_long_version[MAX_STRING_SIZE]; char *buffer = NULL; int arg, type = 0, result = 0; int i, size, x, y, mask_bit, mask_byte; unsigned char *data; install_allegro(SYSTEM_NONE, &errno, &atexit); set_color_depth(32); set_color_conversion(COLORCONV_TOTAL | COLORCONV_KEEP_TRANS); if (argc < 2) usage(); datafile[0] = '\0'; bundle[0] = '\0'; select_palette(black_palette); /* Parse command line and load any given resource */ for (arg = 2; arg < argc; arg++) { if (!strcmp(argv[arg], "-m")) flags |= F_MOVE; else if (!strcmp(argv[arg], "-e")) flags |= F_EMBED_FRAMEWORK; else if (!strcmp(argv[arg], "-o")) { if ((argc < arg + 2) || (bundle[0] != '\0')) usage(); strcpy(bundle, argv[++arg]); } else if (!strcmp(argv[arg], "-v")) { if (argc < arg + 2) usage(); flags |= F_GOT_VERSION; strcpy(bundle_version, argv[++arg]); } else if (!strcmp(argv[arg], "-V")) { if (argc < arg + 2) usage(); flags |= F_GOT_LONG_VERSION; strcpy(bundle_long_version, argv[++arg]); } else if (!strcmp(argv[arg], "-d")) { if (argc < arg + 2) usage(); strcpy(datafile, argv[++arg]); } else if ((!strcmp(argv[arg], "-16")) || (!strcmp(argv[arg], "-32")) || (!strcmp(argv[arg], "-48")) || (!strcmp(argv[arg], "-128"))) { if (argc < arg + 2) usage(); switch (atoi(&argv[arg][1])) { case 16: type = 0; break; case 32: type = 1; break; case 48: type = 2; break; case 128: type = 3; break; } if (load_resource(datafile, argv[++arg], &icon_data[type])) { result = -1; goto exit_error; } } else { if (load_resource(datafile, argv[arg], NULL)) { result = -1; goto exit_error; } } } buffer = malloc(4096); if (!buffer) { result = -1; goto exit_error_bundle; } bundle_exe = argv[1]; if (!exists(bundle_exe)) { fprintf(stderr, "Cannot locate executable file '%s'\n", bundle_exe); result = -1; goto exit_error; } if (bundle[0] == '\0') strcpy(bundle, bundle_exe); replace_extension(bundle_dir, bundle, "app", MAX_STRING_SIZE); strcpy(bundle_contents_dir, bundle_dir); strcat(bundle_contents_dir, "/Contents"); strcpy(bundle_contents_resources_dir, bundle_contents_dir); strcat(bundle_contents_resources_dir, "/Resources"); strcpy(bundle_contents_macos_dir, bundle_contents_dir); strcat(bundle_contents_macos_dir, "/MacOS"); strcpy(bundle_contents_frameworks_dir, bundle_contents_dir); strcat(bundle_contents_frameworks_dir, "/Frameworks"); bundle_icns[0] = '\0'; bundle_plist[0] = '\0'; bundle_pkginfo[0] = '\0'; /* Create bundle structure */ if ((mkdir(bundle_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_resources_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_macos_dir, 0777) && (errno != EEXIST))) { fprintf(stderr, "Cannot create %s\n", bundle_dir); result = -1; goto exit_error_bundle; } /* Copy/move executable into the bundle */ if (copy_file(bundle_exe, bundle_contents_macos_dir)) { fprintf(stderr, "Cannot create %s\n", bundle_contents_macos_dir); result = -1; goto exit_error_bundle; } strcat(bundle_contents_macos_dir, "/"); strcat(bundle_contents_macos_dir, get_filename(bundle_exe)); chmod(bundle_contents_macos_dir, 0755); if (flags & F_MOVE) unlink(bundle_exe); /* Embed Allegro framework if requested */ if (flags & F_EMBED_FRAMEWORK) { if (!file_exists("/Library/Frameworks/Allegro.framework", FA_RDONLY | FA_DIREC, NULL)) { fprintf(stderr, "Cannot find Allegro framework\n"); result = -1; goto exit_error_bundle; } if (!exists("/Library/Frameworks/Allegro.framework/Resources/Embeddable")) { fprintf(stderr, "Cannot embed system wide Allegro framework; install embeddable version first!\n"); result = -1; goto exit_error_bundle; } sprintf(buffer, "/Developer/Tools/pbxcp -exclude .DS_Store -exclude CVS -resolve-src-symlinks /Library/Frameworks/Allegro.framework %s", bundle_contents_frameworks_dir); if ((mkdir(bundle_contents_frameworks_dir, 0777) && (errno != EEXIST)) || (system(buffer))) { fprintf(stderr, "Cannot create %s\n", bundle_contents_frameworks_dir); result = -1; goto exit_error_bundle; } } /* Setup the .icns resource */ if (flags & F_ICONS_DEFINED) { strcat(bundle_contents_resources_dir, "/"); strcat(bundle_contents_resources_dir, get_filename(bundle)); replace_extension(bundle_icns, bundle_contents_resources_dir, "icns", MAX_STRING_SIZE); icon_family = (IconFamilyHandle)NewHandle(0); for (i = 0; i < 4; i++) { if (flags & icon_data[i].defined) { /* Set 32bit RGBA data */ raw_data = NewHandle(icon_data[i].size * icon_data[i].size * 4); data = *(unsigned char **)raw_data; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { *data++ = geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getr32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getg32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getb32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); } } if (SetIconFamilyData(icon_family, icon_data[i].data, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource RGBA data\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); /* Set 8bit mask */ raw_data = NewHandle(icon_data[i].size * icon_data[i].size); data = *(unsigned char **)raw_data; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { *data++ = geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); } } if (SetIconFamilyData(icon_family, icon_data[i].mask8, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource 8bit mask\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); /* Set 1bit mask */ if (icon_data[i].mask1) { size = ((icon_data[i].size * icon_data[i].size) + 7) / 8; raw_data = NewHandle(size * 2); data = *(unsigned char **)raw_data; mask_byte = 0; mask_bit = 7; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { if (geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]) >= 0xfd) mask_byte |= (1 << mask_bit); mask_bit--; if (mask_bit < 0) { *data++ = mask_byte; mask_byte = 0; mask_bit = 7; } } } memcpy(*raw_data + size, *raw_data, size); if (SetIconFamilyData(icon_family, icon_data[i].mask1, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource 1bit mask\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); } } } f = pack_fopen(bundle_icns, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } pack_fclose(f); cf_url_ref = CFURLCreateWithBytes(kCFAllocatorDefault, (unsigned char *)bundle_icns, strlen(bundle_icns), 0, NULL); if (!cf_url_ref) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } CFURLGetFSRef(cf_url_ref, &fs_ref); CFRelease(cf_url_ref); if ((FSGetCatalogInfo(&fs_ref, kFSCatInfoNone, NULL, NULL, &fs_spec, NULL)) || (WriteIconFile(icon_family, &fs_spec) != noErr)) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } DisposeHandle((Handle)icon_family); } /* Setup Info.plist */ sprintf(bundle_plist, "%s/Info.plist", bundle_contents_dir); f = pack_fopen(bundle_plist, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_plist); result = -1; goto exit_error_bundle; } sprintf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" "<plist version=\"1.0\">\n" "<dict>\n" "\t<key>CFBundleExecutable</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleInfoDictionaryVersion</key>\n" "\t<string>6.0</string>\n" "\t<key>CFBundlePackageType</key>\n" "\t<string>APPL</string>\n" "\t<key>CFBundleSignature</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleVersion</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleDocumentTypes</key>\n" "\t<array>\n" "\t\t<dict>\n" "\t\t\t<key>CFBundleTypeExtensions</key>\n" "\t\t\t<array>\n" "\t\t\t\t<string>*</string>\n" "\t\t\t</array>\n" "\t\t\t<key>CFBundleTypeName</key>\n" "\t\t\t<string>NSStringPboardType</string>\n" "\t\t\t<key>CFBundleTypeOSTypes</key>\n" "\t\t\t<array>\n" "\t\t\t\t<string>****</string>\n" "\t\t\t</array>\n" "\t\t\t<key>CFBundleTypeRole</key>\n" "\t\t\t<string>Viewer</string>\n" "\t\t</dict>\n" "\t</array>\n", get_filename(bundle_exe), "????", (flags & F_GOT_VERSION) ? bundle_version : "1.0"); pack_fputs(buffer, f); if (flags & F_GOT_LONG_VERSION) { sprintf(buffer, "\t<key>CFBundleGetInfoString</key>\n" "\t<string>%s</string>\n", bundle_long_version); pack_fputs(buffer, f); } if (flags & F_ICONS_DEFINED) { sprintf(buffer, "\t<key>CFBundleIconFile</key>\n" "\t<string>%s</string>\n", get_filename(bundle_icns)); pack_fputs(buffer, f); } pack_fputs("</dict>\n</plist>\n", f); pack_fclose(f); /* Setup PkgInfo */ sprintf(bundle_pkginfo, "%s/PkgInfo", bundle_contents_dir); f = pack_fopen(bundle_pkginfo, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_pkginfo); result = -1; goto exit_error_bundle; } pack_fputs("APPL????", f); pack_fclose(f); exit_error: if (buffer) free(buffer); for (i = 0; i < 4; i++) { if (icon_data[i].original) destroy_bitmap(icon_data[i].original); if (icon_data[i].workspace) destroy_bitmap(icon_data[i].workspace); if (icon_data[i].scaled) destroy_bitmap(icon_data[i].scaled); } return result; exit_error_bundle: sprintf(buffer, "%s/%s", bundle_contents_macos_dir, get_filename(bundle_exe)); unlink(buffer); unlink(bundle_plist); unlink(bundle_pkginfo); unlink(bundle_icns); rmdir(bundle_dir); rmdir(bundle_contents_dir); rmdir(bundle_contents_resources_dir); rmdir(bundle_contents_macos_dir); goto exit_error; }
/* We expect four arguments: - source directory name - object directory - common object directory - the program name with path */ int main (int argc, char *argv[]) { const char *srcdir; const char *objdir; const char *common_objdir; const char *progpath; struct stat64 st1; struct stat64 st2; struct stat64 st3; DIR *dir1; DIR *dir2; int result = 0; struct dirent64 *d; struct dirent64 direntbuf; char *objdir_copy1; char *objdir_copy2; char *buf; int fd; mtrace (); if (argc < 5) { puts ("not enough parameters"); exit (1); } /* Make parameters available with nicer names. */ srcdir = argv[1]; objdir = argv[2]; common_objdir = argv[3]; progpath = argv[4]; /* First test the current source dir. We cannot really compare the result of `getpwd' with the srcdir string but we have other means. */ if (stat64 (".", &st1) < 0) { printf ("cannot stat starting directory: %m\n"); exit (1); } if (chdir (srcdir) < 0) { printf ("cannot change to source directory: %m\n"); exit (1); } if (stat64 (".", &st2) < 0) { printf ("cannot stat source directory: %m\n"); exit (1); } /* The two last stat64 calls better were for the same directory. */ if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { printf ("stat of source directory failed: (%lld,%lld) vs (%lld,%lld)\n", (long long int) st1.st_dev, (long long int) st1.st_ino, (long long int) st2.st_dev, (long long int) st2.st_ino); exit (1); } /* Change to the object directory. */ if (chdir (objdir) < 0) { printf ("cannot change to object directory: %m\n"); exit (1); } if (stat64 (".", &st1) < 0) { printf ("cannot stat object directory: %m\n"); exit (1); } /* Is this the same we get as with the full path? */ if (stat64 (objdir, &st2) < 0) { printf ("cannot stat object directory with full path: %m\n"); exit (1); } if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { printf ("stat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n", (long long int) st1.st_dev, (long long int) st1.st_ino, (long long int) st2.st_dev, (long long int) st2.st_ino); exit (1); } objdir_copy1 = getcwd (NULL, 0); if (objdir_copy1 == NULL) { printf ("cannot get current directory name for object directory: %m\n"); result = 1; } /* First test: this directory must include our program. */ if (stat64 (progpath, &st2) < 0) { printf ("cannot stat program: %m\n"); exit (1); } dir1 = opendir ("."); if (dir1 == NULL) { printf ("cannot open object directory: %m\n"); exit (1); } while ((d = readdir64 (dir1)) != NULL) { #ifdef _DIRENT_HAVE_D_TYPE if (d->d_type != DT_UNKNOWN && d->d_type != DT_REG) continue; #endif if (d->d_ino == st2.st_ino) { /* Might be it. Test the device. We could use the st_dev element from st1 but what the heck, do more testing. */ if (stat64 (d->d_name, &st3) < 0) { printf ("cannot stat entry from readdir: %m\n"); result = 1; d = NULL; break; } if (st3.st_dev == st2.st_dev) break; } } if (d == NULL) { puts ("haven't found program in object directory"); result = 1; } /* We leave dir1 open. */ /* Stat using file descriptor. */ if (fstat64 (dirfd (dir1), &st2) < 0) { printf ("cannot fstat object directory: %m\n"); result = 1; } if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { printf ("fstat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n", (long long int) st1.st_dev, (long long int) st1.st_ino, (long long int) st2.st_dev, (long long int) st2.st_ino); exit (1); } if (chdir ("..") < 0) { printf ("cannot go to common object directory with \"..\": %m\n"); exit (1); } if (stat64 (".", &st1) < 0) { printf ("cannot stat common object directory: %m\n"); exit (1); } /* Is this the same we get as with the full path? */ if (stat64 (common_objdir, &st2) < 0) { printf ("cannot stat common object directory with full path: %m\n"); exit (1); } if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { printf ("stat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n", (long long int) st1.st_dev, (long long int) st1.st_ino, (long long int) st2.st_dev, (long long int) st2.st_ino); exit (1); } /* Stat using file descriptor. */ if (fstat64 (dirfd (dir1), &st2) < 0) { printf ("cannot fstat object directory: %m\n"); result = 1; } dir2 = opendir (common_objdir); if (dir2 == NULL) { printf ("cannot open common object directory: %m\n"); exit (1); } while ((d = readdir64 (dir2)) != NULL) { #ifdef _DIRENT_HAVE_D_TYPE if (d->d_type != DT_UNKNOWN && d->d_type != DT_DIR) continue; #endif if (d->d_ino == st2.st_ino) { /* Might be it. Test the device. We could use the st_dev element from st1 but what the heck, do more testing. */ if (stat64 (d->d_name, &st3) < 0) { printf ("cannot stat entry from readdir: %m\n"); result = 1; d = NULL; break; } if (st3.st_dev == st2.st_dev) break; } } /* This better should be the object directory again. */ if (fchdir (dirfd (dir1)) < 0) { printf ("cannot fchdir to object directory: %m\n"); exit (1); } objdir_copy2 = getcwd (NULL, 0); if (objdir_copy2 == NULL) { printf ("cannot get current directory name for object directory: %m\n"); result = 1; } if (strcmp (objdir_copy1, objdir_copy2) != 0) { puts ("getcwd returned a different string the second time"); result = 1; } /* This better should be the common object directory again. */ if (fchdir (dirfd (dir2)) < 0) { printf ("cannot fchdir to common object directory: %m\n"); exit (1); } if (stat64 (".", &st2) < 0) { printf ("cannot stat common object directory: %m\n"); exit (1); } if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { printf ("stat of object directory failed: (%lld,%lld) vs (%lld,%lld)\n", (long long int) st1.st_dev, (long long int) st1.st_ino, (long long int) st2.st_dev, (long long int) st2.st_ino); exit (1); } buf = (char *) malloc (strlen (objdir_copy1) + 1 + sizeof "tst-dir.XXXXXX"); if (buf == NULL) { printf ("cannot allocate buffer: %m"); exit (1); } stpcpy (stpcpy (stpcpy (buf, objdir_copy1), "/"), "tst-dir.XXXXXX"); if (mkdtemp (buf) == NULL) { printf ("cannot create test directory in object directory: %m\n"); exit (1); } if (stat64 (buf, &st1) < 0) { printf ("cannot stat new directory \"%s\": %m\n", buf); exit (1); } if (chmod (buf, 0700) < 0) { printf ("cannot change mode of new directory: %m\n"); exit (1); } /* Try to find the new directory. */ rewinddir (dir1); while (readdir64_r (dir1, &direntbuf, &d) == 0 && d != NULL) { #ifdef _DIRENT_HAVE_D_TYPE if (d->d_type != DT_UNKNOWN && d->d_type != DT_DIR) continue; #endif if (d->d_ino == st1.st_ino) { /* Might be it. Test the device. We could use the st_dev element from st1 but what the heck, do more testing. */ size_t len = strlen (objdir) + 1 + _D_EXACT_NAMLEN (d) + 1; char tmpbuf[len]; stpcpy (stpcpy (stpcpy (tmpbuf, objdir), "/"), d->d_name); if (stat64 (tmpbuf, &st3) < 0) { printf ("cannot stat entry from readdir: %m\n"); result = 1; d = NULL; break; } if (st3.st_dev == st2.st_dev && strcmp (d->d_name, buf + strlen (buf) - 14) == 0) break; } } if (d == NULL) { printf ("haven't found new directory \"%s\"\n", buf); exit (1); } if (closedir (dir2) < 0) { printf ("closing dir2 failed: %m\n"); result = 1; } if (chdir (buf) < 0) { printf ("cannot change to new directory: %m\n"); exit (1); } dir2 = opendir (buf); if (dir2 == NULL) { printf ("cannot open new directory: %m\n"); exit (1); } if (fstat64 (dirfd (dir2), &st2) < 0) { printf ("cannot fstat new directory \"%s\": %m\n", buf); exit (1); } if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { printf ("stat of new directory failed: (%lld,%lld) vs (%lld,%lld)\n", (long long int) st1.st_dev, (long long int) st1.st_ino, (long long int) st2.st_dev, (long long int) st2.st_ino); exit (1); } if (mkdir ("another-dir", 0777) < 0) { printf ("cannot create \"another-dir\": %m\n"); exit (1); } fd = open ("and-a-file", O_RDWR | O_CREAT | O_EXCL, 0666); if (fd == -1) { printf ("cannot create \"and-a-file\": %m\n"); exit (1); } close (fd); /* Some tests about error reporting. */ errno = 0; if (chdir ("and-a-file") >= 0) { printf ("chdir to \"and-a-file\" succeeded\n"); exit (1); } if (errno != ENOTDIR) { printf ("chdir to \"and-a-file\" didn't set correct error\n"); result = 1; } errno = 0; if (chdir ("and-a-file/..") >= 0) { printf ("chdir to \"and-a-file/..\" succeeded\n"); exit (1); } if (errno != ENOTDIR) { printf ("chdir to \"and-a-file/..\" didn't set correct error\n"); result = 1; } errno = 0; if (chdir ("another-dir/../and-a-file") >= 0) { printf ("chdir to \"another-dir/../and-a-file\" succeeded\n"); exit (1); } if (errno != ENOTDIR) { printf ("chdir to \"another-dir/../and-a-file\" didn't set correct error\n"); result = 1; } /* We now should have a directory and a file in the new directory. */ rewinddir (dir2); while (readdir64_r (dir2, &direntbuf, &d) == 0 && d != NULL) { if (strcmp (d->d_name, ".") == 0 || strcmp (d->d_name, "..") == 0 || strcmp (d->d_name, "another-dir") == 0) { #ifdef _DIRENT_HAVE_D_TYPE if (d->d_type != DT_UNKNOWN && d->d_type != DT_DIR) { printf ("d_type for \"%s\" is wrong\n", d->d_name); result = 1; } #endif if (stat64 (d->d_name, &st3) < 0) { printf ("cannot stat \"%s\" is wrong\n", d->d_name); result = 1; } else if (! S_ISDIR (st3.st_mode)) { printf ("\"%s\" is no directory\n", d->d_name); result = 1; } } else if (strcmp (d->d_name, "and-a-file") == 0) { #ifdef _DIRENT_HAVE_D_TYPE if (d->d_type != DT_UNKNOWN && d->d_type != DT_REG) { printf ("d_type for \"%s\" is wrong\n", d->d_name); result = 1; } #endif if (stat64 (d->d_name, &st3) < 0) { printf ("cannot stat \"%s\" is wrong\n", d->d_name); result = 1; } else if (! S_ISREG (st3.st_mode)) { printf ("\"%s\" is no regular file\n", d->d_name); result = 1; } } else { printf ("unexpected directory entry \"%s\"\n", d->d_name); result = 1; } } if (stat64 ("does-not-exist", &st1) >= 0) { puts ("stat for unexisting file did not fail"); result = 1; } /* Free all resources. */ if (closedir (dir1) < 0) { printf ("closing dir1 failed: %m\n"); result = 1; } if (closedir (dir2) < 0) { printf ("second closing dir2 failed: %m\n"); result = 1; } if (rmdir ("another-dir") < 0) { printf ("cannot remove \"another-dir\": %m\n"); result = 1; } if (unlink ("and-a-file") < 0) { printf ("cannot remove \"and-a-file\": %m\n"); result = 1; } /* One more test before we leave: mkdir() is supposed to fail with EEXIST if the named file is a symlink. */ if (symlink ("a-symlink", "a-symlink") != 0) { printf ("cannot create symlink \"a-symlink\": %m\n"); result = 1; } else { if (mkdir ("a-symlink", 0666) == 0) { puts ("can make directory \"a-symlink\""); result = 1; } else if (errno != EEXIST) { puts ("mkdir(\"a-symlink\") does not fail with EEXIST\n"); result = 1; } if (unlink ("a-symlink") < 0) { printf ("cannot unlink \"a-symlink\": %m\n"); result = 1; } } if (chdir (srcdir) < 0) { printf ("cannot change back to source directory: %m\n"); exit (1); } if (rmdir (buf) < 0) { printf ("cannot remove \"%s\": %m\n", buf); result = 1; } free (objdir_copy1); free (objdir_copy2); if (result == 0) puts ("all OK"); return result; }
void *rszshm_mk(struct rszshm *r, size_t flen, const char *fname, struct rszshm_scan scan) { long pgsz = sysconf(_SC_PAGE_SIZE); int i, errno_; char *m, *tgt, *p = NULL; if (!r || flen == 0 || scan.len < flen + sizeof(*r->hdr) || !scan.start || scan.len == 0 || scan.hop == 0 || scan.iter == 0 || (fname && strnlen(fname, RSZSHM_PATH_MAX) == RSZSHM_PATH_MAX)) { errno = EINVAL; return NULL; } *r = (typeof(*r)) { -1, 0, "", NULL, NULL }; strcpy(r->fname, fname ? fname : RSZSHM_DFLT_FNAME); flen = pgup(flen + sizeof(*r->hdr), pgsz); scan.len = pgup(scan.len, pgsz); for (i = 1, tgt = scan.start; i <= scan.iter; i++) { m = mmap(tgt, scan.len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON|MAP_NORESERVE, -1, 0); if (m == MAP_FAILED) return NULL; if (m == tgt) break; munmap(m, scan.len); m = NULL; tgt += (i % 2 == 0 ? 1 : -1) * i * scan.hop; } if (!m) { errno = ENOSPC; return NULL; } if ((p = strstr(r->fname, "XXXXXX/")) != NULL) { p += 6; *p = '\0'; if (!mkdtemp(r->fname)) goto err; *p = '/'; } if ((r->fd = open(r->fname, O_CREAT|O_EXCL|O_RDWR, p ? 0600 : 0666)) == -1) goto err; if (ftruncate(r->fd, flen) == -1) goto err; if (mmap(m, flen, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED, r->fd, 0) == MAP_FAILED) goto err; *(r->hdr = (typeof(r->hdr)) m) = (typeof(*r->hdr)) { flen, scan.len, m }; if (msync(m, sizeof(*r->hdr), MS_SYNC) == -1) goto err; r->flen = flen; r->cap = flen - sizeof(*r->hdr); r->dat = m + sizeof(*r->hdr); return r->dat; err: errno_ = errno; if (m && m != MAP_FAILED) munmap(m, scan.len); if (r->fd != -1) { close(r->fd); unlink(r->fname); } if (p) { *p = '\0'; rmdir(r->fname); *p = '/'; } errno = errno_; return NULL; }
void RemoveFile(char *File) { struct stat FileStats; int Status; /* Get the file's information */ if(lstat(File, &FileStats) == -1) { perror("Error:\n\t"); return; } /* If the file is a regular file, then delete it */ if(S_ISREG(FileStats.st_mode)) { /* Attempt to delete the file, and print a message * telling whether deletion was successful */ if(unlink(File) == -1) { perror("Error:\n\t"); return; } else { fprintf(stdout, "File %s removed\n", File); } } /* If the file is a directory, loop over its contents and * pass each one to the FileRemove function */ else if(S_ISDIR(FileStats.st_mode)) { DIR *Directory; struct dirent *Entry; /* Attempt to open the directory */ if((Directory = opendir(File)) == NULL) { perror("Error:\n\t"); return; } else { char FullDirPath[PATH_MAX]; char FullFilePath[PATH_MAX]; /* Get the full path of the directory */ if(realpath(File, FullDirPath) == NULL) { perror("Error:\n\t"); return; } /* Loop over the directory contents */ while((Entry = readdir(Directory)) != NULL) { /* Don't try to remove . or .. from the directory */ if(strcmp(Entry->d_name, ".") != 0 && \ strcmp(Entry->d_name, "..") != 0) { /* Get the full file path of the entry and remove * it */ memset(FullFilePath, 0, PATH_MAX); strcat(FullFilePath, FullDirPath); strcat(FullFilePath, "/"); strcat(FullFilePath, Entry->d_name); RemoveFile(FullFilePath); } } /* Close the directory */ if(closedir(Directory) == -1) { perror("Error:\n\t"); return; } /* Remove the directory itself */ if(rmdir(File) == -1) { perror("Error\n\t"); return; } fprintf(stdout, "Directory %s removed\n", File); } } /* If the file is a symbolic link, then delete it */ else if(S_ISLNK(FileStats.st_mode)) { /* Attempt to delete the symbolic link, and print a message * telling whether deletion was successful */ if(unlink(File) == -1) { perror("Error:\n\t"); return; } else { fprintf(stdout, "Symbolic link %s removed\n", File); } } /* If the file is not a directory, regular file, or symbolic * link, print an error message */ else { fprintf(stderr, "Error: %s is not a directory or regular" " file\n", File); } return; }
static boolean disk_file_remove_dir(const char* path) { DIR* dir; struct dirent* pdirent; struct STAT st; char* p; boolean ret = true; dir = opendir(path); if (dir == NULL) return false; pdirent = readdir(dir); while (pdirent) { if (strcmp(pdirent->d_name, ".") == 0 || strcmp(pdirent->d_name, "..") == 0) { pdirent = readdir(dir); continue; } p = xmalloc(strlen(path) + strlen(pdirent->d_name) + 2); sprintf(p, "%s/%s", path, pdirent->d_name); if (STAT(p, &st) != 0) { DEBUG_WARN("stat %s failed.", p); ret = false; } else if (S_ISDIR(st.st_mode)) { ret = disk_file_remove_dir(p); } else if (unlink(p) < 0) { DEBUG_WARN("unlink %s failed.", p); ret = false; } else ret = true; xfree(p); if (!ret) break; pdirent = readdir(dir); } closedir(dir); if (ret) { if (rmdir(path) < 0) { DEBUG_WARN("rmdir %s failed.", path); ret = false; } } return ret; }
int Q_rmdir (const char *path) { return rmdir(path); }
// blow away all local filesystem state for a monitor int udev_monitor_fs_destroy( struct udev_monitor* monitor ) { char pathbuf[ PATH_MAX+1 ]; int dirfd = 0; int rc = 0; DIR* dirh = NULL; struct dirent entry; struct dirent* result = NULL; bool can_rmdir = true; // stop listening udev_monitor_fs_shutdown( monitor ); // remove events dir contents dirfd = open( monitor->events_dir, O_DIRECTORY | O_CLOEXEC ); if( dirfd < 0 ) { rc = -errno; log_error("open('%s') rc = %d", monitor->events_dir, rc ); return rc; } dirh = fdopendir( dirfd ); if( dirh == NULL ) { // OOM rc = -errno; close( dirfd ); return rc; } do { // next entry rc = readdir_r( dirh, &entry, &result ); if( rc != 0 ) { // I/O error log_error("readdir_r('%s') rc = %d", monitor->events_dir, rc ); break; } // skip . and .. if( strcmp( entry.d_name, "." ) == 0 || strcmp( entry.d_name, ".." ) == 0 ) { continue; } // generate full path memset( pathbuf, 0, PATH_MAX+1 ); snprintf( pathbuf, PATH_MAX, "%s/%s", monitor->events_dir, entry.d_name ); // optimistically remove if( entry.d_type == DT_DIR ) { rc = rmdir( pathbuf ); } else { rc = unlink( pathbuf ); } if( rc != 0 ) { rc = -errno; log_error("remove '%s' rc = %d", pathbuf, rc ); can_rmdir = false; rc = 0; } } while( result != NULL ); // NOTE: closes dirfd closedir( dirh ); if( can_rmdir ) { rc = rmdir( monitor->events_dir ); if( rc != 0 ) { rc = -errno; log_error("rmdir('%s') rc = %d\n", monitor->events_dir, rc); } } else { // let the caller know... rc = -ENOTEMPTY; } return rc; }
BOOL RemoveDirectoryA(LPCSTR lpPathName) { return (rmdir(lpPathName) == 0); }
static unsigned int call_syscall(struct syscall_desc *scall, char *argv[]) { struct stat64 sb; long long flags; unsigned int i; char *endp; int name, rval; union { char *str; long long num; } args[MAX_ARGS]; #ifdef HAS_FREEBSD_ACL int entry_id = ACL_FIRST_ENTRY; acl_t acl, newacl; acl_entry_t entry, newentry; #endif /* * Verify correctness of the arguments. */ for (i = 0; i < sizeof(args)/sizeof(args[0]); i++) { if (scall->sd_args[i] == TYPE_NONE) { if (argv[i] == NULL || strcmp(argv[i], ":") == 0) break; fprintf(stderr, "too many arguments [%s]\n", argv[i]); exit(1); } else { if (argv[i] == NULL || strcmp(argv[i], ":") == 0) { if (scall->sd_args[i] & TYPE_OPTIONAL) break; fprintf(stderr, "too few arguments\n"); exit(1); } if ((scall->sd_args[i] & TYPE_MASK) == TYPE_STRING) { if (strcmp(argv[i], "NULL") == 0) args[i].str = NULL; else if (strcmp(argv[i], "DEADCODE") == 0) args[i].str = (void *)0xdeadc0de; else args[i].str = argv[i]; } else if ((scall->sd_args[i] & TYPE_MASK) == TYPE_NUMBER) { args[i].num = strtoll(argv[i], &endp, 0); if (*endp != '\0' && !isspace((unsigned char)*endp)) { fprintf(stderr, "invalid argument %u, number expected [%s]\n", i, endp); exit(1); } } else if ((scall->sd_args[i] & TYPE_MASK) == TYPE_DESCRIPTOR) { if (strcmp(argv[i], "AT_FDCWD") == 0) { args[i].num = AT_FDCWD; } else if (strcmp(argv[i], "BADFD") == 0) { /* In case AT_FDCWD is -1 on some systems... */ if (AT_FDCWD == -1) args[i].num = -2; else args[i].num = -1; } else { int pos; pos = strtoll(argv[i], &endp, 0); if (*endp != '\0' && !isspace((unsigned char)*endp)) { fprintf(stderr, "invalid argument %u, number expected [%s]\n", i, endp); exit(1); } args[i].num = descriptor_get(pos); } } } } /* * Call the given syscall. */ #define NUM(n) (args[(n)].num) #define STR(n) (args[(n)].str) switch (scall->sd_action) { case ACTION_OPEN: flags = str2flags(open_flags, STR(1)); if (flags & O_CREAT) { if (i == 2) { fprintf(stderr, "too few arguments\n"); exit(1); } rval = open(STR(0), (int)flags, (mode_t)NUM(2)); } else { if (i == 3) { fprintf(stderr, "too many arguments\n"); exit(1); } rval = open(STR(0), (int)flags); } if (rval >= 0) descriptor_add(rval); break; case ACTION_OPENAT: flags = str2flags(open_flags, STR(2)); if (flags & O_CREAT) { if (i == 3) { fprintf(stderr, "too few arguments\n"); exit(1); } rval = openat(NUM(0), STR(1), (int)flags, (mode_t)NUM(3)); } else { if (i == 4) { fprintf(stderr, "too many arguments\n"); exit(1); } rval = openat(NUM(0), STR(1), (int)flags); } if (rval >= 0) descriptor_add(rval); break; case ACTION_CREATE: rval = open(STR(0), O_CREAT | O_EXCL, (mode_t)NUM(1)); if (rval >= 0) close(rval); break; case ACTION_UNLINK: rval = unlink(STR(0)); break; case ACTION_UNLINKAT: rval = unlinkat(NUM(0), STR(1), (int)str2flags(unlinkat_flags, STR(2))); break; case ACTION_MKDIR: rval = mkdir(STR(0), (mode_t)NUM(1)); break; case ACTION_MKDIRAT: rval = mkdirat(NUM(0), STR(1), (mode_t)NUM(2)); break; case ACTION_RMDIR: rval = rmdir(STR(0)); break; case ACTION_LINK: rval = link(STR(0), STR(1)); break; case ACTION_LINKAT: rval = linkat(NUM(0), STR(1), NUM(2), STR(3), (int)str2flags(linkat_flags, STR(4))); break; case ACTION_SYMLINK: rval = symlink(STR(0), STR(1)); break; case ACTION_SYMLINKAT: rval = symlinkat(STR(0), NUM(1), STR(2)); break; case ACTION_RENAME: rval = rename(STR(0), STR(1)); break; case ACTION_RENAMEAT: rval = renameat(NUM(0), STR(1), NUM(2), STR(3)); break; case ACTION_MKFIFO: rval = mkfifo(STR(0), (mode_t)NUM(1)); break; case ACTION_MKFIFOAT: rval = mkfifoat(NUM(0), STR(1), (mode_t)NUM(2)); break; case ACTION_MKNOD: case ACTION_MKNODAT: { mode_t ntype; dev_t dev; int fa; switch (scall->sd_action) { case ACTION_MKNOD: fa = 0; break; case ACTION_MKNODAT: fa = 1; break; default: abort(); } dev = makedev(NUM(fa + 3), NUM(fa + 4)); if (strcmp(STR(fa + 1), "c") == 0) /* character device */ ntype = S_IFCHR; else if (strcmp(STR(fa + 1), "b") == 0) /* block device */ ntype = S_IFBLK; else if (strcmp(STR(fa + 1), "f") == 0) /* fifo special */ ntype = S_IFIFO; else if (strcmp(STR(fa + 1), "d") == 0) /* directory */ ntype = S_IFDIR; else if (strcmp(STR(fa + 1), "o") == 0) /* regular file */ ntype = S_IFREG; else { fprintf(stderr, "wrong argument 1\n"); exit(1); } switch (scall->sd_action) { case ACTION_MKNOD: rval = mknod(STR(0), ntype | NUM(2), dev); break; case ACTION_MKNODAT: rval = mknodat(NUM(0), STR(1), ntype | NUM(3), dev); break; default: abort(); } break; } case ACTION_BIND: { struct sockaddr_un sunx; sunx.sun_family = AF_UNIX; strncpy(sunx.sun_path, STR(0), sizeof(sunx.sun_path) - 1); sunx.sun_path[sizeof(sunx.sun_path) - 1] = '\0'; rval = socket(AF_UNIX, SOCK_STREAM, 0); if (rval < 0) break; rval = bind(rval, (struct sockaddr *)&sunx, sizeof(sunx)); break; } #ifdef HAS_BINDAT case ACTION_BINDAT: { struct sockaddr_un sunx; sunx.sun_family = AF_UNIX; strncpy(sunx.sun_path, STR(1), sizeof(sunx.sun_path) - 1); sunx.sun_path[sizeof(sunx.sun_path) - 1] = '\0'; rval = socket(AF_UNIX, SOCK_STREAM, 0); if (rval < 0) break; rval = bindat(NUM(0), rval, (struct sockaddr *)&sunx, sizeof(sunx)); break; } #endif case ACTION_CONNECT: { struct sockaddr_un sunx; sunx.sun_family = AF_UNIX; strncpy(sunx.sun_path, STR(0), sizeof(sunx.sun_path) - 1); sunx.sun_path[sizeof(sunx.sun_path) - 1] = '\0'; rval = socket(AF_UNIX, SOCK_STREAM, 0); if (rval < 0) break; rval = connect(rval, (struct sockaddr *)&sunx, sizeof(sunx)); break; } #ifdef HAS_CONNECTAT case ACTION_CONNECTAT: { struct sockaddr_un sunx; sunx.sun_family = AF_UNIX; strncpy(sunx.sun_path, STR(1), sizeof(sunx.sun_path) - 1); sunx.sun_path[sizeof(sunx.sun_path) - 1] = '\0'; rval = socket(AF_UNIX, SOCK_STREAM, 0); if (rval < 0) break; rval = connectat(NUM(0), rval, (struct sockaddr *)&sunx, sizeof(sunx)); break; } #endif case ACTION_CHMOD: rval = chmod(STR(0), (mode_t)NUM(1)); break; case ACTION_FCHMOD: rval = fchmod(NUM(0), (mode_t)NUM(1)); break; #ifdef HAS_LCHMOD case ACTION_LCHMOD: rval = lchmod(STR(0), (mode_t)NUM(1)); break; #endif case ACTION_FCHMODAT: rval = fchmodat(NUM(0), STR(1), (mode_t)NUM(2), str2flags(fchmodat_flags, STR(3))); break; case ACTION_CHOWN: rval = chown(STR(0), (uid_t)NUM(1), (gid_t)NUM(2)); break; case ACTION_FCHOWN: rval = fchown(NUM(0), (uid_t)NUM(1), (gid_t)NUM(2)); break; case ACTION_LCHOWN: rval = lchown(STR(0), (uid_t)NUM(1), (gid_t)NUM(2)); break; case ACTION_FCHOWNAT: rval = fchownat(NUM(0), STR(1), (uid_t)NUM(2), (gid_t)NUM(3), (int)str2flags(fchownat_flags, STR(4))); break; #ifdef HAS_CHFLAGS case ACTION_CHFLAGS: rval = chflags(STR(0), (unsigned long)str2flags(chflags_flags, STR(1))); break; #endif #ifdef HAS_FCHFLAGS case ACTION_FCHFLAGS: rval = fchflags(NUM(0), (unsigned long)str2flags(chflags_flags, STR(1))); break; #endif #ifdef HAS_CHFLAGSAT case ACTION_CHFLAGSAT: rval = chflagsat(NUM(0), STR(1), (unsigned long)str2flags(chflags_flags, STR(2)), (int)str2flags(chflagsat_flags, STR(3))); break; #endif #ifdef HAS_LCHFLAGS case ACTION_LCHFLAGS: rval = lchflags(STR(0), (unsigned long)str2flags(chflags_flags, STR(1))); break; #endif case ACTION_TRUNCATE: rval = truncate64(STR(0), NUM(1)); break; case ACTION_FTRUNCATE: rval = ftruncate64(NUM(0), NUM(1)); break; case ACTION_STAT: rval = stat64(STR(0), &sb); if (rval == 0) { show_stats(&sb, STR(1)); return (i); } break; case ACTION_FSTAT: rval = fstat64(NUM(0), &sb); if (rval == 0) { show_stats(&sb, STR(1)); return (i); } break; case ACTION_LSTAT: rval = lstat64(STR(0), &sb); if (rval == 0) { show_stats(&sb, STR(1)); return (i); } break; case ACTION_FSTATAT: rval = fstatat(NUM(0), STR(1), &sb, (int)str2flags(fstatat_flags, STR(2))); if (rval == 0) { show_stats(&sb, STR(3)); return (i); } break; case ACTION_PATHCONF: case ACTION_FPATHCONF: case ACTION_LPATHCONF: { long lrval; name = str2name(pathconf_names, STR(1)); if (name == -1) { fprintf(stderr, "unknown name %s", STR(1)); exit(1); } errno = 0; switch (scall->sd_action) { case ACTION_PATHCONF: lrval = pathconf(STR(0), name); break; case ACTION_FPATHCONF: lrval = fpathconf(NUM(0), name); break; case ACTION_LPATHCONF: lrval = lpathconf(STR(0), name); break; default: abort(); } if (lrval == -1 && errno == 0) { printf("unlimited\n"); return (i); } else if (lrval >= 0) { printf("%ld\n", lrval); return (i); } rval = -1; break; } #ifdef HAS_FREEBSD_ACL case ACTION_PREPENDACL: rval = -1; acl = acl_get_file(STR(0), ACL_TYPE_NFS4); if (acl == NULL) break; newacl = acl_from_text(STR(1)); if (acl == NULL) break; while (acl_get_entry(newacl, entry_id, &newentry) == 1) { entry_id = ACL_NEXT_ENTRY; if (acl_create_entry_np(&acl, &entry, 0)) break; if (acl_copy_entry(entry, newentry)) break; } rval = acl_set_file(STR(0), ACL_TYPE_NFS4, acl); break; case ACTION_READACL: acl = acl_get_file(STR(0), ACL_TYPE_NFS4); if (acl == NULL) rval = -1; else rval = 0; break; #endif case ACTION_WRITE: rval = write(NUM(0), STR(1), strlen(STR(1))); break; default: fprintf(stderr, "unsupported syscall\n"); exit(1); } #undef STR #undef NUM if (rval < 0) { const char *serrno; serrno = err2str(errno); fprintf(stderr, "%s returned %d\n", scall->sd_name, rval); printf("%s\n", serrno); exit(1); } printf("0\n"); return (i); }
int main(int ac, char *av[]) { int pid, child, status, count, k, j; char name[3]; int lc; const char *msg; /* * parse standard options */ if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); /* * Default values for run conditions. */ iterations = 50; nchild = 5; if (signal(SIGTERM, term) == SIG_ERR) { tst_resm(TBROK, "first signal failed"); } /* use the default values for run conditions */ for (lc = 0; TEST_LOOPING(lc); lc++) { local_flag = PASSED; /* * Make a directory to do this in; ignore error if already exists. */ parent_pid = getpid(); tst_tmpdir(); if (!startdir[0]) { if (getcwd(startdir, MAXPATHLEN) == NULL) { tst_brkm(TFAIL | TERRNO, NULL, "getcwd failed"); } } cwd = startdir; snprintf(dirname, ARRAY_SIZE(dirname), "%s/ftest06.%d", cwd, getpid()); snprintf(homedir, ARRAY_SIZE(homedir), "%s/ftest06h.%d", cwd, getpid()); mkdir(dirname, 0755); mkdir(homedir, 0755); if (chdir(dirname) < 0) tst_brkm(TFAIL | TERRNO, cleanup, "\tCan't chdir(%s)", dirname); dirlen = strlen(dirname); if (chdir(homedir) < 0) tst_brkm(TFAIL | TERRNO, cleanup, "\tCan't chdir(%s)", homedir); /* enter block */ for (k = 0; k < nchild; k++) { if ((child = fork()) == 0) { dotest(k, iterations); tst_exit(); } if (child < 0) { tst_brkm(TBROK | TERRNO, cleanup, "fork failed"); } pidlist[k] = child; } /* * Wait for children to finish. */ count = 0; while ((child = wait(&status)) > 0) { //tst_resm(TINFO,"Test{%d} exited status = 0x%x", child, status); //fprintf(stdout, "status is %d",status); if (status) { tst_resm(TFAIL, "Test{%d} failed, expected 0 exit.", child); local_flag = FAILED; } ++count; } /* * Should have collected all children. */ if (count != nchild) { tst_resm(TFAIL, "Wrong # children waited on, count = %d", count); local_flag = FAILED; } if (local_flag == PASSED) tst_resm(TPASS, "Test passed."); else tst_resm(TFAIL, "Test failed."); if (iterations > 26) iterations = 26; for (k = 0; k < nchild; k++) for (j = 0; j < iterations + 1; j++) { ft_mkname(name, dirname, k, j); rmdir(name); unlink(name); } if (chdir(startdir) < 0) tst_brkm(TFAIL | TERRNO, cleanup, "Can't chdir(%s)", startdir); pid = fork(); if (pid < 0) { tst_brkm(TBROK | TERRNO, NULL, "fork failed"); } if (pid == 0) { execl("/bin/rm", "rm", "-rf", homedir, NULL); } else wait(&status); if (status) tst_resm(TINFO, "CAUTION - ftest06, '%s' may not have been removed.", homedir); pid = fork(); if (pid < 0) { tst_brkm(TBROK | TERRNO, NULL, "fork failed"); } if (pid == 0) { execl("/bin/rm", "rm", "-rf", dirname, NULL); exit(1); } else wait(&status); if (status) { tst_resm(TWARN, "CAUTION - ftest06, '%s' may not have been removed.", dirname); } sync(); } if (local_flag == FAILED) tst_resm(TFAIL, "Test failed."); else tst_resm(TPASS, "Test passed."); cleanup(); tst_exit(); }
int main(int ac, char **av) { int lc; /* loop counter */ char *msg; /* message returned from parse_opts */ struct stat buf; /* * parse standard options */ if ((msg=parse_opts(ac, av, (option_t *)NULL, NULL)) != (char *)NULL) { tst_brkm(TBROK, tst_exit, "OPTION PARSING ERROR - %s", msg); } /* * perform global setup for test */ setup(); /* * check looping state if -i option given */ for (lc=0; TEST_LOOPING(lc); lc++) { /* reset Tst_count in case we are looping. */ Tst_count=0; /* * TEST rmdir() base functionality */ /* Initialize the test directory name */ /* create a directory */ if ( mkdir(tstdir, PERMS) == -1 ) { tst_brkm(TBROK, cleanup, "mkdir(%s, %#o) Failed", tstdir, PERMS); /*NOTREACHED*/ } /* call rmdir using TEST macro */ TEST(rmdir(tstdir)); if (TEST_RETURN == -1 ) { tst_resm(TFAIL, "rmdir(%s) Failed", tstdir); continue; } if (STD_FUNCTIONAL_TEST) { /* check whether tstdir been removed */ if (stat(tstdir, &buf) != -1) { tst_resm(TFAIL, "directory %s still exists", tstdir); continue; } else { tst_resm(TPASS, "directory has been removed"); } } else { tst_resm(TPASS, "call succeeded"); } } /* End for TEST_LOOPING */ /* * cleanup and exit */ cleanup(); /*NOTREACHED*/ return(0); }
static int tcl_rmdir(ClientData cd, Tcl_Interp *irp, int argc, char *argv[]) { FILE *fdb; filedb_entry *fdbe; char *s = NULL, *t, *d, *p; BADARGS(2, 2, " dir"); malloc_strcpy(s, argv[1]); if (s[strlen(s) - 1] == '/') s[strlen(s) - 1] = 0; p = strrchr(s, '/'); if (p == NULL) { p = s; d = ""; } else { *p = 0; p++; d = s; } fdb = filedb_open(d, 0); if (!fdb) { Tcl_AppendResult(irp, "1", NULL); my_free(s); return TCL_OK; } filedb_readtop(fdb, NULL); fdbe = filedb_matchfile(fdb, ftell(fdb), p); if (!fdbe) { Tcl_AppendResult(irp, "1", NULL); filedb_close(fdb); my_free(s); return TCL_OK; } if (!(fdbe->stat & FILE_DIR)) { Tcl_AppendResult(irp, "1", NULL); filedb_close(fdb); free_fdbe(&fdbe); my_free(s); return TCL_OK; } /* Erase '.filedb' and '.files' if they exist */ t = nmalloc(strlen(dccdir) + strlen(d) + strlen(p) + 11); sprintf(t, "%s%s/%s/.filedb", dccdir, d, p); unlink(t); sprintf(t, "%s%s/%s/.files", dccdir, d, p); unlink(t); sprintf(t, "%s%s/%s", dccdir, d, p); my_free(s); if (rmdir(t) == 0) { filedb_delfile(fdb, fdbe->pos); filedb_close(fdb); free_fdbe(&fdbe); my_free(t); Tcl_AppendResult(irp, "0", NULL); return TCL_OK; } my_free(t); free_fdbe(&fdbe); filedb_close(fdb); Tcl_AppendResult(irp, "1", NULL); return TCL_OK; }
static void rm_file(char **argv) { struct stat sb; int rval; char *f; /* * Remove a file. POSIX 1003.2 states that, by default, attempting * to remove a directory is an error, so must always stat the file. */ while ((f = *argv++) != NULL) { /* Assume if can't stat the file, can't unlink it. */ if (lstat(f, &sb)) { if (Wflag) { sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR; } else { if (!fflag || errno != ENOENT) { warn("%s", f); eval = 1; } continue; } } else if (Wflag) { warnx("%s: %s", f, strerror(EEXIST)); eval = 1; continue; } if (S_ISDIR(sb.st_mode) && !dflag) { warnx("%s: is a directory", f); eval = 1; continue; } if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb)) continue; rval = 0; if (!uid && !S_ISWHT(sb.st_mode) && (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) && !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE))) rval = lchflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE)); if (rval == 0) { if (S_ISWHT(sb.st_mode)) rval = undelete(f); else if (S_ISDIR(sb.st_mode)) rval = rmdir(f); else { if (Pflag) if (!rm_overwrite(f, &sb)) continue; rval = unlink(f); } } if (rval && (!fflag || errno != ENOENT)) { warn("%s", f); eval = 1; } if (vflag && rval == 0) (void)printf("%s\n", f); if (info && rval == 0) { info = 0; (void)printf("%s\n", f); } } }
int setup_machine_directory(uint64_t size, sd_bus_error *error) { _cleanup_release_lock_file_ LockFile lock_file = LOCK_FILE_INIT; struct loop_info64 info = { .lo_flags = LO_FLAGS_AUTOCLEAR, }; _cleanup_close_ int fd = -1, control = -1, loop = -1; _cleanup_free_ char* loopdev = NULL; char tmpdir[] = "/tmp/import-mount.XXXXXX", *mntdir = NULL; bool tmpdir_made = false, mntdir_made = false, mntdir_mounted = false; char buf[FORMAT_BYTES_MAX]; int r, nr = -1; /* btrfs cannot handle file systems < 16M, hence use this as minimum */ if (size == (uint64_t) -1) size = VAR_LIB_MACHINES_SIZE_START; else if (size < 16*1024*1024) size = 16*1024*1024; /* Make sure we only set the directory up once at a time */ r = make_lock_file("/run/systemd/machines.lock", LOCK_EX, &lock_file); if (r < 0) return r; r = check_btrfs(); if (r < 0) return sd_bus_error_set_errnof(error, r, "Failed to determine whether /var/lib/machines is located on btrfs: %m"); if (r > 0) { (void) btrfs_subvol_make_label("/var/lib/machines"); r = btrfs_quota_enable("/var/lib/machines", true); if (r < 0) log_warning_errno(r, "Failed to enable quota, ignoring: %m"); return 0; } if (path_is_mount_point("/var/lib/machines", true) > 0 || dir_is_empty("/var/lib/machines") == 0) return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "/var/lib/machines is not a btrfs file system. Operation is not supported on legacy file systems."); fd = setup_machine_raw(size, error); if (fd < 0) return fd; control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK); if (control < 0) return sd_bus_error_set_errnof(error, errno, "Failed to open /dev/loop-control: %m"); nr = ioctl(control, LOOP_CTL_GET_FREE); if (nr < 0) return sd_bus_error_set_errnof(error, errno, "Failed to allocate loop device: %m"); if (asprintf(&loopdev, "/dev/loop%i", nr) < 0) { r = -ENOMEM; goto fail; } loop = open(loopdev, O_CLOEXEC|O_RDWR|O_NOCTTY|O_NONBLOCK); if (loop < 0) { r = sd_bus_error_set_errnof(error, errno, "Failed to open loopback device: %m"); goto fail; } if (ioctl(loop, LOOP_SET_FD, fd) < 0) { r = sd_bus_error_set_errnof(error, errno, "Failed to bind loopback device: %m"); goto fail; } if (ioctl(loop, LOOP_SET_STATUS64, &info) < 0) { r = sd_bus_error_set_errnof(error, errno, "Failed to enable auto-clear for loopback device: %m"); goto fail; } /* We need to make sure the new /var/lib/machines directory * has an access mode of 0700 at the time it is first made * available. mkfs will create it with 0755 however. Hence, * let's mount the directory into an inaccessible directory * below /tmp first, fix the access mode, and move it to the * public place then. */ if (!mkdtemp(tmpdir)) { r = sd_bus_error_set_errnof(error, errno, "Failed to create temporary mount parent directory: %m"); goto fail; } tmpdir_made = true; mntdir = strjoina(tmpdir, "/mnt"); if (mkdir(mntdir, 0700) < 0) { r = sd_bus_error_set_errnof(error, errno, "Failed to create temporary mount directory: %m"); goto fail; } mntdir_made = true; if (mount(loopdev, mntdir, "btrfs", 0, NULL) < 0) { r = sd_bus_error_set_errnof(error, errno, "Failed to mount loopback device: %m"); goto fail; } mntdir_mounted = true; r = btrfs_quota_enable(mntdir, true); if (r < 0) log_warning_errno(r, "Failed to enable quota, ignoring: %m"); if (chmod(mntdir, 0700) < 0) { r = sd_bus_error_set_errnof(error, errno, "Failed to fix owner: %m"); goto fail; } (void) mkdir_p_label("/var/lib/machines", 0700); if (mount(mntdir, "/var/lib/machines", NULL, MS_BIND, NULL) < 0) { r = sd_bus_error_set_errnof(error, errno, "Failed to mount directory into right place: %m"); goto fail; } (void) syncfs(fd); log_info("Set up /var/lib/machines as btrfs loopback file system of size %s mounted on /var/lib/machines.raw.", format_bytes(buf, sizeof(buf), size)); (void) umount2(mntdir, MNT_DETACH); (void) rmdir(mntdir); (void) rmdir(tmpdir); return 0; fail: if (mntdir_mounted) (void) umount2(mntdir, MNT_DETACH); if (mntdir_made) (void) rmdir(mntdir); if (tmpdir_made) (void) rmdir(tmpdir); if (loop >= 0) { (void) ioctl(loop, LOOP_CLR_FD); loop = safe_close(loop); } if (control >= 0 && nr >= 0) (void) ioctl(control, LOOP_CTL_REMOVE, nr); return r; }
void do_test(void) { int r, fd; int s[2]; char buf[1], testroot[PATH_MAX+1], renamebuf[PATH_MAX+1]; subtest = 1; if (socketpair(PF_UNIX, SOCK_STREAM, 0, s) == -1) e(1); if (system("mkdir -p " TEST_PATH) == -1) e(2); if (realpath(".", testroot) == NULL) e(3); r = fork(); if (r == -1) e(4); else if (r == 0) { /* Child */ /* Change child's cwd to TEST_PATH */ if (chdir(TEST_PATH) == -1) e(5); /* Signal parent we're ready for the test */ buf[0] = 'a'; if (write(s[0], buf, sizeof(buf)) != sizeof(buf)) e(6); /* Wait for parent to remove my cwd */ if (read(s[0], buf, sizeof(buf)) != sizeof(buf)) e(7); /* Try to create a file */ if ((fd = open("testfile", O_RDWR | O_CREAT)) != -1) { e(8); /* Uh oh. We created a file?! Try to remove it. */ (void) close(fd); if (unlink("testfile") != 0) { /* This is not good. We created a file, but we can * never access it; we have a spurious inode. */ e(9); printf(INTEGR_MSG); exit(errct); } } if (errno != ENOENT) e(10); /* Try to create a dir */ errno = 0; if (mkdir("testdir", 0777) == 0) { e(11); /* Uh oh. This shouldn't have been possible. Try to undo. */ if (rmdir("testdir") != 0) { /* Not good. */ e(12); printf(INTEGR_MSG); exit(errct); } } if (errno != ENOENT) e(13); /* Try to create a special file */ errno = 0; if (mknod("testnode", 0777 | S_IFIFO, 0) == 0) { e(14); /* Impossible. Try to make it unhappen. */ if (unlink("testnode") != 0) { /* Not good. */ e(15); printf(INTEGR_MSG); exit(errct); } } if (errno != ENOENT) e(16); /* Try to rename a file */ errno = 0; /* First create a file in the test dir */ snprintf(renamebuf, PATH_MAX, "%s/oldname", testroot); if ((fd = open(renamebuf, O_RDWR | O_CREAT)) == -1) e(17); if (close(fd) != 0) e(18); /* Now try to rename that file to an entry in the current, non-existing * working directory. */ if (rename(renamebuf, "testrename") == 0) { e(19); /* This shouldn't have been possible. Revert the name change. */ if (rename("testrename", renamebuf) != 0) { /* Failed */ e(20); printf(INTEGR_MSG); exit(errct); } } /* Try to create a hard link to that file */ errno = 0; if (link(renamebuf, "testhlink") == 0) { e(21); /* Try to undo the hard link to prevent fs corruption. */ if (unlink("testhlink") != 0) { /* Failed. */ e(22); printf(INTEGR_MSG); exit(errct); } } if (errno != ENOENT) e(23); /* Try to create a symlink */ errno = 0; if (symlink(testroot, "testslink") == 0) { e(24); /* Try to remove the symlink to prevent fs corruption. */ if (unlink("testslink") != 0) { /* Failed. */ e(25); printf(INTEGR_MSG); exit(errct); } } if (errno != ENOENT) e(26); exit(errct); } else { /* Parent */ int status; /* Wait for the child to enter the TEST_PATH dir */ if (read(s[1], buf, sizeof(buf)) != sizeof(buf)) e(27); /* Delete TEST_PATH */ if (rmdir(TEST_PATH) != 0) e(28); /* Tell child we removed its cwd */ buf[0] = 'b'; if (write(s[1], buf, sizeof(buf)) != sizeof(buf)) e(29); wait(&status); errct += WEXITSTATUS(status); /* Count errors */ } }
int VSIRmdir( const char * pszFilename ) { return rmdir( pszFilename ); }