Beispiel #1
0
static
void
dumpdata(void)
{
	struct indexentry x;
	off_t indexsize, pos, done;
	size_t amount, len;

	indexsize = dolseek(indexfd, indexname, 0, SEEK_CUR);
	pos = indexsize;
	assert(pos % sizeof(x) == 0);
	while (pos != 0) {
		pos -= sizeof(x);
		dolseek(indexfd, indexname, pos, SEEK_SET);

		len = doread(indexfd, indexname, &x, sizeof(x));
		if (len != sizeof(x)) {
			errx(1, "%s: read: Unexpected EOF", indexname);
		}
		dolseek(datafd, dataname, x.pos, SEEK_SET);

		for (done = 0; done < x.len; done += amount) {
			amount = sizeof(buf);
			if ((off_t)amount > x.len - done) {
				amount = x.len - done;
			}
			len = doread(datafd, dataname, buf, amount);
			if (len != amount) {
				errx(1, "%s: read: Unexpected short count"
				     " %zu of %zu", dataname, len, amount);
			}
			dowrite(STDOUT_FILENO, "stdout", buf, len);
		}
	}
}
Beispiel #2
0
/*
 * @offset, @count: random values from [0, max_file_size - 1]
 */
static int frag_read(struct frag_ctx *ctx, off_t offset, size_t count)
{
	ssize_t test_ret;
	ssize_t good_ret;

	test_ret = doread(ctx->test_fd,
			  offset, count, ctx->test_buf, ctx->max_file_size);
	if (test_ret < 0) {
		fprintf(stderr, "READ: failed to read test file\n");
		return -1;
	}
	good_ret = doread(ctx->good_fd,
			  offset, count, ctx->good_buf, ctx->max_file_size);
	if (good_ret < 0) {
		fprintf(stderr, "READ: failed to read good file\n");
		return -1;
	}
	if (test_ret != good_ret) {
		fprintf(stderr,
			"READ: Bad return value %d (expected %d\n)",
			test_ret, good_ret);
		return -1;
	}
	if (memcmp(ctx->test_buf + offset, ctx->good_buf + offset, good_ret)) {
		fprintf(stderr, "READ: bad data\n");
		return -1;
	}
	return 0;
}
Beispiel #3
0
void dotest()
{
  dowrite(0x0, 0xf00f00);

  dowrite(0x11110000, 0x00000000);
  dowrite(0x22220000, 0x00000000);
  dowrite(0x33330000, 0x00000000);
  dowrite(0x44440000, 0x00000000);

  doread(0x11110000, 0x00000000);
  doread(0x22220000, 0x00000000);
  doread(0x33330000, 0x00000000);
  doread(0x44440000, 0x00000000);


  dowrite(0x11110000, 0x11111111);
  dowrite(0x22220000, 0x22222222);
  dowrite(0x33330000, 0x33333333);
  dowrite(0x44440000, 0x44444444);

  doread(0x11110000, 0x11111111);
  doread(0x22220000, 0x00222222);
  doread(0x33330000, 0x00003333);
  doread(0x44440000, 0x00000044);


  dowrite(0x0, 0xdeadbeef);
  doread(0x0, 0xfeedface);
}
Beispiel #4
0
int main(int argc, char **argv) {
  unsigned char pw[64];

  unsigned char flagdata[MAX_STRLEN];

  unsigned char rbuf[MAX_STRLEN + PREAMBLE_SIZE];

  unsigned char nonce[33];
  unsigned char md5[33];

  int fd, err;

  struct sockaddr_in addr_s;

  if (argc < 4) {
    fprintf(stderr, "usage: client pw ip port\n");
    return -1;
  }

  memset(pw, 0, sizeof(pw));
  strncpy(pw, argv[1], sizeof(pw) - 1);

  fd = socket(AF_INET, SOCK_STREAM, 0);

  bzero(&addr_s, sizeof(addr_s));
  addr_s.sin_family = AF_INET;
  inet_pton(addr_s.sin_family, argv[2], &(addr_s.sin_addr));
  addr_s.sin_port = htons(atoi(argv[3]));

  connect(fd, (struct sockaddr *)&addr_s, sizeof(addr_s));

  doread(fd, nonce, 32, 32);
  nonce[32] = 0;
  //fprintf(stderr, "iv:  %s\n", iv);
  doread(fd, rbuf, 1, 1);

  doread(fd, md5, 32, 32);
  md5[32] = 0;
  //fprintf(stderr, "md5: %s\n", md5);
  doread(fd, rbuf, 1, 1);

  memset(rbuf, 0, sizeof(rbuf));
  doread(fd, rbuf, MAX_STRLEN + PREAMBLE_SIZE - 1, 1);
  //fprintf(stderr, "%s", rbuf);

  if ((err = str_decrypt(flagdata, rbuf, pw, nonce, md5)) >= 0) {
    printf("Correct password! Decrypted payload:\n%s", flagdata);
  } else {
    printf("MD5 mismatch, perhaps you have the wrong password? Encrypted payload:\n%s", rbuf);
  }

  close(fd);

  return 0;
}
void dump_article(uint32_t offset) {
	printf("match\n");
	doseek(offset);
	uint8_t article_len[4];
	doread(&article_len, sizeof(article_len));
	int len = article_len[0] + 256*article_len[1] + 256*256*article_len[2] + 256*256*256*article_len[3];
	uint8_t* buf = (uint8_t*) malloc(len + 1);
	doread(buf, len);
	buf[len] = 0;
	printf((char*) buf);
	free(buf);
}
Beispiel #6
0
long
syspread(uint32 *arg)
{
	vlong v;

	// Plan 9 VX replaced dodgy varargs code
	v = *(vlong*)&arg[3];

	if(v == ~0ULL)
		return doread(arg, nil);

	return doread(arg, &v);
}
Beispiel #7
0
/* parse arguments of read command */
int runread(int argc, char **argv){
  char *name, *rstr;
  int i, rnd, rnum, rv;
  name = NULL;
  rstr = NULL;
  rnd = FALSE;
  rnum = 0;
  for(i = 2; i < argc; i++){
    if(!name && argv[i][0] == '-'){
      if(!name && !strcmp(argv[i], "-rnd"))
        rnd = TRUE;
      else
        usage();
    } else if(!name){
      name = argv[i];
    } else if(!rstr){
      rstr = argv[i];
    } else {
      usage();
    }
  }
  if(!name || !rstr)
    usage();
  rnum = atoi(rstr);
  if(rnum < 1)
    usage();
  rv = doread(name, rnum, rnd);
  return rv;
}
Beispiel #8
0
void read_string(char **ptr, unsigned long *left, unsigned long cnt)
{
	if (imap_readptrleft == 0)
	{
		/* Keep reading until we fill the buffer or until we've
		** read the entire string.
		*/

		read_timeout(SOCKET_TIMEOUT);
		imap_readptr=readbuf;
		while (imap_readptrleft < sizeof(readbuf) && imap_readptrleft < cnt)
			imap_readptrleft += doread(readbuf+imap_readptrleft,
						sizeof(readbuf)-imap_readptrleft);
	}

	if (cnt < imap_readptrleft)	/* Can satisfy fully from buffer */
	{
		*ptr=imap_readptr;
		*left=cnt;
		imap_readptr += cnt;
		imap_readptrleft -= cnt;
		return;
	}

	*ptr=imap_readptr;
	*left=imap_readptrleft;
	imap_readptrleft=0;
	return;
}
Beispiel #9
0
void
popdir(Ram *r)
{
	int i, ino;
	char *cp;
	struct v10dir *dp;
	Fileinf f;
	char name[VNAMELEN+1];

	cp = 0;
	for (i=0; i<r->ndata; i+=sizeof(struct v10dir)) {
		if (i%BLSIZE==0)
			cp = doread(r, i, BLSIZE);
		dp = (struct v10dir *)(cp+i%BLSIZE);
		ino = g2byte(dp->ino);
		if (strcmp(dp->name, ".")==0 || strcmp(dp->name, "..")==0)
			continue;
		if (ino==0)
			continue;
		f = iget(ino);
		strncpy(name, dp->name, VNAMELEN);
		name[VNAMELEN] = '\0';
		f.name = name;
		popfile(r, f);
	}
	r->replete = 1;
}
Beispiel #10
0
/*
 *  this just proxies what the factotum tells it to.
 */
AuthInfo*
authproto(Session *s, Fid *f, AuthRpc *rpc, AuthGetkey *getkey, char *params)
{
	char *buf;
	int m, n, ret;
	AuthInfo *a;
	char oerr[ERRMAX];

	rerrstr(oerr, sizeof oerr);
	werrstr("UNKNOWN AUTH ERROR");

	if(dorpc(rpc, "start", params, strlen(params), getkey) != ARok){
		werrstr("fauth_proxy start: %r");
		return nil;
	}

	buf = malloc(AuthRpcMax);
	if(buf == nil)
		return nil;
	for(;;){
		switch(dorpc(rpc, "read", nil, 0, getkey)){
		case ARdone:
			free(buf);
			a = auth_getinfo(rpc);
			errstr(oerr, sizeof oerr);	/* no error, restore whatever was there */
			return a;
		case ARok:
			if(dowrite(s, f, rpc->arg, rpc->narg) != rpc->narg){
				werrstr("auth_proxy write fd: %r");
				goto Error;
			}
			break;
		case ARphase:
			n = 0;
			memset(buf, 0, AuthRpcMax);
			while((ret = dorpc(rpc, "write", buf, n, getkey)) == ARtoosmall){
				if(atoi(rpc->arg) > AuthRpcMax)
					break;
				m = doread(s, f, buf+n, atoi(rpc->arg)-n);
				if(m <= 0){
					if(m == 0)
						werrstr("auth_proxy short read: %s", buf);
					goto Error;
				}
				n += m;
			}
			if(ret != ARok){
				werrstr("auth_proxy rpc write: %s: %r", buf);
				goto Error;
			}
			break;
		default:
			werrstr("auth_proxy rpc: %r");
			goto Error;
		}
	}
Error:
	free(buf);
	return nil;
}
Beispiel #11
0
static
void
readfile(const char *name)
{
	int fd, closefd;
	struct indexentry x;
	size_t len, remaining, here;
	const char *s, *t;

	if (name == NULL || !strcmp(name, "-")) {
		fd = STDIN_FILENO;
		closefd = -1;
	}
	else {
		fd = open(name, O_RDONLY);
		if (fd < 0) {
			err(1, "%s", name);
		}
		closefd = fd;
	}

	x.pos = 0;
	x.len = 0;
	while (1) {
		len = doread(fd, name, buf, sizeof(buf));
		if (len == 0) {
			break;
		}

		remaining = len;
		for (s = buf; s != NULL; s = t) {
			t = memchr(s, '\n', remaining);
			if (t != NULL) {
				t++;
				here = (t - s);
				x.len += here;
				remaining -= here;
				dowrite(indexfd, indexname, &x, sizeof(x));
				x.pos += x.len;
				x.len = 0;
			}
			else {
				x.len += remaining;
			}
		}
		dowrite(datafd, dataname, buf, len);
	}
	if (x.len > 0) {
		dowrite(indexfd, indexname, &x, sizeof(x));
	}

	if (closefd != -1) {
		close(closefd);
	}
}
Beispiel #12
0
static
int
disk_readsector(struct disk_data *dd)
{
    off_t offset = dd->dd_sect;
    offset *= SECTSIZE;
    offset += HEADERSIZE;

    g_stats.s_rsects++;

    return doread(dd->dd_fd, offset, dd->dd_buf, SECTSIZE);
}
Beispiel #13
0
Datei: psort.c Projekt: BWK/os161
static
void
doexactread(const char *path, int fd, void *buf, size_t len)
{
	size_t result;

	result = doread(path, fd, buf, len);
	if (result != len) {
		complainx("%s: read: short count", path);
		exit(1);
	}
}
Beispiel #14
0
unsigned QRead( f_handle file, void *buffer, unsigned len, char *name )
/*********************************************************************/
/* read into far memory */
{
    int     h;

    CheckBreak();
    h = doread( file, buffer, len );
    if( h == -1 ) {
        LnkMsg( ERR+MSG_IO_PROBLEM, "12", name, strerror( errno ) );
    }
    return( h );
}
Beispiel #15
0
int main() {

  try {
    initialize();
    dowrite();
    doread();
    terminateit();
  }
  catch (SQLException &e) {
    cout << "SQL exception :" << e.getMessage() << endl;
  }

  return 0;
}
Beispiel #16
0
/**
* Reads <Node> from from <f> (global FILE variable)
*/
void read_node(Node& node) {
	doread(&node, size_of_node);
	int pchildren_len = sizeof(uint32_t*)* node.nchildren;
	int children_names_len = node.len - size_of_node - pchildren_len;

	// ensure pchildren is big enough
	if (node.pchildren_len < pchildren_len) {
		if (node.pchildren_len > 0) {
			free(node.pchildren);
		}
		node.pchildren = (uint32_t*) malloc(pchildren_len);
	}

	// ensure children_names is big enough
	if (node.children_names_len < children_names_len) {
		if (node.children_names_len > 0) {
			free(node.children_names);
		}
		node.children_names = (uint16_t*) malloc(children_names_len);
	}

	doread(node.pchildren, pchildren_len);
	doread(node.children_names, children_names_len);
}
Beispiel #17
0
static
void
checkheader(const char *file, int fd)
{
    char buf[SECTORSIZE];

    doread(file, fd, buf, sizeof(buf));
    buf[sizeof(buf) - 1] = 0;

    if (!strcmp(buf, HEADERSTRING)) {
        /* ok */
        return;
    }
    fprintf(stderr, "disk161: %s: Not a System/161 disk image\n", file);
    exit(1);
}
Beispiel #18
0
void justice_reader(int num, int duration) {
    pthread_mutex_lock(&new_op_mutex);
    pthread_mutex_lock(&reader_mutex);
    ++reader_count;
    if (reader_count == 1)
        pthread_mutex_lock(&writer_mutex);
    pthread_mutex_unlock(&reader_mutex);
    pthread_mutex_unlock(&new_op_mutex);
    
    doread(num, duration);

    pthread_mutex_lock(&reader_mutex);
    --reader_count;
    if (reader_count == 0)
        pthread_mutex_unlock(&writer_mutex);
    pthread_mutex_unlock(&reader_mutex);
}
Beispiel #19
0
char*
rread(Fid *f)
{
	int i, len;
	Ram *r;
	char *buf;
	uvlong off, end;
	int n, cnt;

	if(f->ram->busy == 0)
		return Enotexist;
	n = 0;
	thdr.count = 0;
	off = rhdr.offset;
	end = rhdr.offset + rhdr.count;
	cnt = rhdr.count;
	if(cnt > messagesize-IOHDRSZ)
		cnt = messagesize-IOHDRSZ;
	buf = thdr.data;
	if(f->ram->qid.type & QTDIR){
		if(!f->ram->replete)
			popdir(f->ram);
		for(i=0,r=f->ram->child; r!=nil && i<end; r=r->next){
			if(!r->busy)
				continue;
			len = ramstat(r, (uchar*)buf+n, cnt-n);
			if(len <= BIT16SZ)
				break;
			if(i >= off)
				n += len;
			i += len;
		}
		thdr.count = n;
		return 0;
	}
	r = f->ram;
	if(off >= r->ndata)
		return 0;
	r->atime = time(0);
	n = cnt;
	if(off+n > r->ndata)
		n = r->ndata - off;
	thdr.data = doread(r, off, n);
	thdr.count = n;
	return 0;
}
Beispiel #20
0
static
void
readheader(struct disk_data *dd, const char *filename)
{
    char buf[HEADERSIZE];
    if (doread(dd->dd_fd, 0, buf, HEADERSIZE)) {
        msg("disk: slot %d: %s: Reading header: %s",
            dd->dd_slot, filename, strerror(errno));
        die();
    }

    /* just in case */
    buf[HEADERSIZE-1] = 0;

    if (strcmp(buf, HEADER_MESSAGE)) {
        msg("disk: slot %d: %s is not a disk image",
            dd->dd_slot, filename);
        die();
    }
}
Beispiel #21
0
Datei: psort.c Projekt: BWK/os161
static
unsigned long
checksum_file(const char *path)
{
	int fd;
	char buf[512];
	size_t count, i;
	unsigned long sum = 0;

	fd = doopen(path, O_RDONLY, 0);

	while ((count = doread(path, fd, buf, sizeof(buf))) > 0) {
		for (i=0; i<count; i++) {
			sum += (unsigned char) buf[i];
		}
	}

	doclose(path, fd);

	return sum;
}
Beispiel #22
0
void
test(void)
{
	unsigned long	offset;
	unsigned long	size = maxoplen;
	unsigned long	rv = random();
	unsigned long	op;

	if (simulatedopcount > 0 && testcalls == simulatedopcount)
		writefileimage();

	testcalls++;

	if (closeprob)
		closeopen = (rv >> 3) < (1u << 28) / (unsigned)closeprob;

	if (debugstart > 0 && testcalls >= debugstart)
		debug = 1;

	if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
		prt("%lu...\n", testcalls);

	offset = random();
	if (randomoplen)
		size = random() % (maxoplen + 1);

	/* calculate appropriate op to run */
	if (lite)
		op = rv % OP_MAX_LITE;
	else
		op = rv % OP_MAX_FULL;

	switch (op) {
	case OP_MAPREAD:
		if (!mapped_reads)
			op = OP_READ;
		break;
	case OP_MAPWRITE:
		if (!mapped_writes)
			op = OP_WRITE;
		break;
	case OP_FALLOCATE:
		if (!fallocate_calls) {
			log4(OP_SKIPPED, OP_FALLOCATE, offset, size);
			goto out;
		}
		break;
	case OP_PUNCH_HOLE:
		if (!punch_hole_calls) {
			log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, size);
			goto out;
		}
		break;
	}

	switch (op) {
	case OP_READ:
		TRIM_OFF_LEN(offset, size, file_size);
		doread(offset, size);
		break;

	case OP_WRITE:
		TRIM_OFF_LEN(offset, size, maxfilelen);
		dowrite(offset, size);
		break;

	case OP_MAPREAD:
		TRIM_OFF_LEN(offset, size, file_size);
		exit(183);
		break;

	case OP_MAPWRITE:
		TRIM_OFF_LEN(offset, size, maxfilelen);
		exit(182);
		break;

	case OP_TRUNCATE:
		if (!style)
			size = random() % maxfilelen;
		dotruncate(size);
		break;

	case OP_PUNCH_HOLE:
		TRIM_OFF_LEN(offset, size, file_size);
		do_punch_hole(offset, size);
		break;
	default:
		prterr("test: unknown operation");
		report_failure(42);
		break;
	}

out:
	if (sizechecks && testcalls > simulatedopcount)
		check_size();
	if (closeopen)
		docloseopen();
}
Beispiel #23
0
void readfill()
{
	imap_readptrleft=doread(readbuf, sizeof(readbuf));
	imap_readptr=readbuf;
}
Beispiel #24
0
extern unsigned BigRead( int fh, void * buff, unsigned size )
/***********************************************************/
{
    return( doread( fh, buff, size ) );
}
Beispiel #25
0
//
// Supported commands are:
//	<dict.file> e <word> - find exact match, if nothing found, dump list
//	<dict.file> l <word> - dump list
//  <dict.file> n <offset> - dump next word list starting from <offset>
//  <dict.file> p <offset> - dump previous word list, ending at offset <offset>
//  <dict.file> x <offset> - dump article at address x
//
// Output format:
//	list result
//		"list"
//		<word>\t<short translation>\n
//		<word>\t<short translation>\n
//		...
//		<starting_offset>\t<ending_offset>\n
//
//	exact result
//		"match"\n
//		<translation>
//			
int main(int argc, char* argv[])
{
	// Set console codepage to UTF8 on windows
	#ifdef _MSC_VER
		SetConsoleOutputCP(CP_UTF8);
	#endif


	// Expecting <exec name> <dictionary file> <word>
	if (argc < 4) {
		print_usage();
		return ERR_INVALID_ARGUMENT;
	}

	char* command = (char*) argv[2];

	// dictionary file name, fancy names aren't supported
	char* filename = (char*) argv[1];

	// UTF 16 version of the search string (assuming input is UTF8)
	int search_len;
	uint16_t* searchUTF16 = utf8to16((uint8_t*) argv[3], search_len);
	
	// Open dictionary file
	f = fopen(filename, "rb");
	if (!f) {
		printf("Failed to open file: %s", filename);
		return ERR_FILE_NOT_FOUND;
	}

	// Read header
	doread(&header, sizeof(header));

	// check magic (PRSPDICT ascii)
	int MAGIC[8] = {0x50, 0x52, 0x53, 0x50, 0x44, 0x49, 0x43, 0x54};
	for (int i = 0; i < 8; i++) {
		if (header.magic[i] != MAGIC[i]) {
			printf("Invalid file magic");
			return ERR_INVALID_MAGIC;
		}
	}

	// Check dicitonary version
	if (header.version_lo != 0 || header.version_hi != 1) {
		printf("Unsupported dictionary version: %d.%d", header.version_hi, header.version_lo);
		return ERR_UNSUPPORTED_VERSION;
	}

	switch (command[0]) {
		case 'e':
			//	e <word> - find exact match, if nothing found, dump list
			if (!find_exact_match(header.offset_radix, searchUTF16, search_len)) {
				find_best_match(searchUTF16, search_len);
			}
			break;
		//	l <word> - dump list
		case 'l':
			find_best_match(searchUTF16, search_len);
			break;
		//  n <offset> - dump next word list starting from <offset>
		case 'n':
			dump_word_list(atoi(argv[3]), NEXT);
			break;
		//  p <offset> - dump previous word list, ending at offset <offset>
		case 'p':
			dump_word_list(atoi(argv[3]), PREV);
			break;
		//  x <offset> - dump article at address x
		case 'x':
			dump_article(atoi(argv[3]));
			break;
		default:
			print_usage();
	}

	
	fclose(f);
	return 0;
}
Beispiel #26
0
void
test(void)
{
	unsigned long	offset;
	unsigned long	size = maxoplen;
	unsigned long	rv = random();
	unsigned long	op = rv % (3 + !lite + mapped_writes);

        /* turn off the map read if necessary */

        if (op == 2 && !mapped_reads)
            op = 0;

	if (simulatedopcount > 0 && testcalls == simulatedopcount)
		writefileimage();

	testcalls++;

	if (closeprob)
		closeopen = (rv >> 3) < (1 << 28) / closeprob;

	if (debugstart > 0 && testcalls >= debugstart)
		debug = 1;

	if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
		prt("%lu...\n", testcalls);

	/*
	 * READ:	op = 0
	 * WRITE:	op = 1
	 * MAPREAD:     op = 2
	 * TRUNCATE:	op = 3
	 * MAPWRITE:    op = 3 or 4
	 */
	if (lite ? 0 : op == 3 && (style & 1) == 0) /* vanilla truncate? */
		dotruncate(random() % maxfilelen);
	else {
		if (randomoplen)
			size = random() % (maxoplen+1);
		if (lite ? 0 : op == 3)
			dotruncate(size);
		else {
			offset = random();
			if (op == 1 || op == (lite ? 3 : 4)) {
				offset %= maxfilelen;
				if (offset + size > maxfilelen)
					size = maxfilelen - offset;
				if (op != 1)
					domapwrite(offset, size);
				else
					dowrite(offset, size);
			} else {
				if (file_size)
					offset %= file_size;
				else
					offset = 0;
				if (offset + size > file_size)
					size = file_size - offset;
				if (op != 0)
					domapread(offset, size);
				else
					doread(offset, size);
			}
		}
	}
	if (sizechecks && testcalls > simulatedopcount)
		check_size();
	if (closeopen)
		docloseopen();
}
Beispiel #27
0
long
sys_read(uint32 *arg)
{
	return doread(arg, nil);
}
Beispiel #28
0
Datei: psort.c Projekt: BWK/os161
static
void
mergebins(void)
{
	int infds[numprocs], outfd;
	int values[numprocs], ready[numprocs];
	const char *name, *outname;
	int i, result;
	int numready, place, val, worknum;

	outname = mergedname(me);
	outfd = doopen(outname, O_WRONLY|O_CREAT|O_TRUNC, 0664);

	for (i=0; i<numprocs; i++) {
		name = binname(i, me);
		infds[i] = doopen(name, O_RDONLY, 0);
		values[i] = 0;
		ready[i] = 0;
	}

	worknum = 0;

	while (1) {
		numready = 0;
		for (i=0; i<numprocs; i++) {
			if (infds[i] < 0) {
				continue;
			}

			if (!ready[i]) {
				result = doread("bin", infds[i], 
						&val, sizeof(int));
				if (result == 0) {
					doclose("bin", infds[i]);
					infds[i] = -1;
					continue;
				}
				if ((size_t) result != sizeof(int)) {
					complainx("%s: read: short count",
						  binname(i, me));
					exit(1);
				}
				values[i] = val;
				ready[i] = 1;
			}
			numready++;
		}
		if (numready == 0) {
			break;
		}

		/* find the smallest */
		place = -1;
		for (i=0; i<numprocs; i++) {
			if (!ready[i]) {
				continue;
			}
			if (place < 0 || values[i] < val) {
				val = values[i];
				place = i;
			}
		}
		assert(place >= 0);

		workspace[worknum++] = val;
		if (worknum >= WORKNUM) {
			assert(worknum == WORKNUM);
			dowrite(outname, outfd, workspace,
				worknum * sizeof(int));
			worknum = 0;
		}
		ready[place] = 0;
	}

	dowrite(outname, outfd, workspace, worknum * sizeof(int));
	doclose(outname, outfd);

	for (i=0; i<numprocs; i++) {
		assert(infds[i] < 0);
	}
}
Beispiel #29
0
int main(int argc, char **argv)
{
	char *value, *subs;
	int i;
	char *subopts[] = {
#define SUB_VAL				0
		"val",
#define SUB_YUV_MODE			1
		"mode",
#define SUB_DIR				2
		"dir",

		NULL
	};

	int fd = -1;

	/* bitfield for OptSetCodec */

	/* command args */
	const char *device = "/dev/video0";	/* -d device */
	int ch;
	int yuv_mode = 0;
	unsigned short gpio_out = 0x0;	/* GPIO output data */
	unsigned short gpio_dir = 0x0;	/* GPIO direction bits */
	int gpio_set_dir = 0;
	int passthrough = 0;
	long audio_mute = 0;
	long stereo_mode = 0;
	long bilingual_mode = 0;
	int debug_level = 0;
	__u32 reset = 0;
	int new_debug_level, gdebug_level;
	double timestamp;
	char *ptsstr;
	char short_options[26 * 2 * 2 + 1];

	if (argc == 1) {
		usage();
		return 0;
	}
	while (1) {
		int option_index = 0;
		int idx = 0;

		for (i = 0; long_options[i].name; i++) {
			if (!isalpha(long_options[i].val))
				continue;
			short_options[idx++] = long_options[i].val;
			if (long_options[i].has_arg == required_argument)
				short_options[idx++] = ':';
		}
		short_options[idx] = 0;
		ch = getopt_long(argc, argv, short_options,
				 long_options, &option_index);
		if (ch == -1)
			break;

		options[(int)ch] = 1;
		switch (ch) {
		case OptSetYuvMode:
		    {
			subs = optarg;
			while (*subs != '\0') {
				switch (getsubopt(&subs, subopts, &value)) {
				case SUB_YUV_MODE:
					if (value == NULL) {
						fprintf(stderr,
							"No value given to suboption <mode>\n");
						usage();
						return 1;

					}
					yuv_mode = strtol(value, 0L, 0);
					if (yuv_mode < 0 || yuv_mode > 3) {
						fprintf(stderr, "invalid yuv mode\n");
						return 1;
					}
					break;
				}
			}
		    }
		    break;
		case OptHelp:
			usage();
			return 0;
		case OptSetDebugLevel:{
			debug_level = strtol(optarg, 0L, 0);
			break;
		}
		case OptSetDevice:
			device = optarg;
			if (device[0] >= '0' && device[0] <= '9' && strlen(device) <= 3) {
				static char newdev[20];

				sprintf(newdev, "/dev/video%s", device);
				device = newdev;
			}
			break;
		case OptReset:
			reset = strtol(optarg, 0L, 0);
			break;
		case OptPassThrough:
			passthrough = strtol(optarg, 0L, 0);
			break;
		case OptSetAudioMute:
			audio_mute = strtol(optarg, 0L, 0);
			break;
		case OptSetStereoMode:
			stereo_mode = strtol(optarg, 0L, 0);
			break;
		case OptSetBilingualMode:
			bilingual_mode = strtol(optarg, 0L, 0);
			break;
		case OptSetGPIO:
			subs = optarg;
			while (*subs != '\0') {
				switch (getsubopt(&subs, subopts, &value)) {
				case SUB_DIR:
					if (value == NULL) {
						fprintf(stderr,
							"No value given to suboption <dir>\n");
						usage();
						exit(1);
					}
					gpio_dir = strtol(value, 0L, 0);
					gpio_set_dir = 1;
					break;
				case SUB_VAL:
					if (value == NULL) {
						fprintf(stderr,
							"No value given to suboption <val>\n");
						usage();
						exit(1);
					}
					gpio_out = (unsigned short)strtol(value, 0L, 0);
					break;
				default:
					fprintf(stderr,
						"Invalid suboptions specified\n");
					usage();
					exit(1);
					break;
				}
			}
			break;
		case ':':
			fprintf(stderr, "Option `%s' requires a value\n",
				argv[optind]);
			usage();
			return 1;
		case '?':
			fprintf(stderr, "Unknown argument `%s'\n",
				argv[optind]);
			usage();
			return 1;
		}
	}
	if (optind < argc) {
		printf("unknown arguments: ");
		while (optind < argc)
			printf("%s ", argv[optind++]);
		printf("\n");
		usage();
		return 1;
	}

	fd = open(device, O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "Failed to open %s: %s\n", device,
			strerror(errno));
		exit(1);
	}

	/* Setting Opts */

	if (options[OptFrameSync]) {
		printf("ioctl: VIDEO_GET_EVENT\n");

		for (;;) {
			struct video_event ev;
			int fps = 30;
			v4l2_std_id std;

			if (ioctl(fd, VIDIOC_G_STD, &std) == 0)
				fps = (std & V4L2_STD_525_60) ? 30 : 25;
			if (ioctl(fd, VIDEO_GET_EVENT, &ev) < 0) {
				fprintf(stderr, "ioctl: VIDEO_GET_EVENT failed\n");
				break;
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
			} else if (ev.timestamp.tv_sec == 0 && ev.timestamp.tv_nsec == 0) {
#else
			} else if (ev.timestamp == 0) {
#endif
				unsigned long long pts = 0, frame = 0;
				struct timeval tv;
				gettimeofday(&tv, NULL);
				timestamp =
				    (double)tv.tv_sec +
				    ((double)tv.tv_usec / 1000000.0);

				ioctl(fd, VIDEO_GET_PTS, &pts);
				ioctl(fd, VIDEO_GET_FRAME_COUNT, &frame);
				ptsstr = pts_to_string(pts, fps);
				printf("%10.6f: pts %-20s, %lld frames\n",
				     timestamp, ptsstr, frame);
			}
		}
	}

	if (options[OptSetGPIO]) {
		struct v4l2_dbg_register reg;

		reg.match.type = V4L2_CHIP_MATCH_HOST;
		reg.match.addr = 0;
		reg.reg = IVTV_REG_GPIO_DIR_OFFSET;
		reg.val = gpio_dir;
		if (gpio_set_dir && doioctl(fd, VIDIOC_DBG_S_REGISTER, &reg,
			"VIDIOC_DBG_S_REGISTER") == 0)
			printf("GPIO dir set to 0x%04llx\n", reg.val);
		reg.reg = IVTV_REG_GPIO_OUT_OFFSET;
		reg.val = gpio_out;
		if (doioctl(fd, VIDIOC_DBG_S_REGISTER, &reg,
			"VIDIOC_DBG_S_REGISTER") == 0)
			printf("GPIO out set to 0x%04llx\n", reg.val);
	}

	if (options[OptListGPIO]) {
		struct v4l2_dbg_register reg;

		reg.match.type = V4L2_CHIP_MATCH_HOST;
		reg.match.addr = 0;
		reg.reg = IVTV_REG_GPIO_IN_OFFSET;
		if (ioctl(fd, VIDIOC_DBG_G_REGISTER, &reg) == 0)
			printf("GPIO in:  0x%04llx\n", reg.val);
		reg.reg = IVTV_REG_GPIO_DIR_OFFSET;
		if (ioctl(fd, VIDIOC_DBG_G_REGISTER, &reg) == 0)
			printf("GPIO dir: 0x%04llx\n", reg.val);
		reg.reg = IVTV_REG_GPIO_OUT_OFFSET;
		if (ioctl(fd, VIDIOC_DBG_G_REGISTER, &reg) == 0)
			printf("GPIO out: 0x%04llx\n", reg.val);
	}

	if (options[OptSetDebugLevel]) {
		char buf[20];
		new_debug_level = debug_level;

		sprintf(buf, "%d", debug_level);
		if (dowrite(buf, "/sys/module/ivtv/parameters/debug") == 0) {
			printf(" set debug level: ");
			print_debug_mask(new_debug_level);
			printf("\n");
		}
	}

	if (options[OptGetDebugLevel]) {
		char *buf = doread("/sys/module/ivtv/parameters/debug");

		gdebug_level = 0;
		if (buf) {
			gdebug_level = atol(buf);
			printf(" debug level: ");
			print_debug_mask(gdebug_level);
			printf("\n");
		}
	}

	if (options[OptPassThrough]) {
		long source = passthrough ? VIDEO_SOURCE_DEMUX : VIDEO_SOURCE_MEMORY;

		doioctl(fd, VIDEO_SELECT_SOURCE, (void *)source,
				"IVTV_IOC_PASSTHROUGH");
	}

	if (options[OptSetAudioMute]) {
		doioctl(fd, AUDIO_SET_MUTE, (void *)audio_mute, "AUDIO_SET_MUTE");
	}

	if (options[OptSetStereoMode]) {
		doioctl(fd, AUDIO_CHANNEL_SELECT,
			(void *)stereo_mode, "AUDIO_CHANNEL_SELECT");
	}

	if (options[OptSetBilingualMode]) {
		doioctl(fd, AUDIO_BILINGUAL_CHANNEL_SELECT,
			(void *)bilingual_mode, "AUDIO_BILINGUAL_CHANNEL_SELECT");
	}

	if (options[OptReset])
		doioctl(fd, VIDIOC_INT_RESET, &reset, "VIDIOC_INT_RESET");

	if (options[OptSetYuvMode]) {
		struct ivtv_dma_frame frame;
		struct v4l2_format fmt;
		const enum v4l2_field map[4] = {
			V4L2_FIELD_INTERLACED_TB,
			V4L2_FIELD_INTERLACED_BT,
			V4L2_FIELD_NONE,
			V4L2_FIELD_ANY,
		};

		printf("set yuv mode\n");
		memset(&frame, 0, sizeof(frame));
		frame.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		if (ioctl(fd, IVTV_IOC_DMA_FRAME, &frame) < 0) {
			fprintf(stderr, "Unable to switch to user DMA YUV mode\n");
			exit(1);
		}
		fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		ioctl(fd, VIDIOC_G_FMT, &fmt);
		fmt.fmt.pix.field = map[yuv_mode];
		doioctl(fd, VIDIOC_S_FMT, &fmt, "VIDIOC_S_FMT");
	}

	if (options[OptGetYuvMode]) {
		struct ivtv_dma_frame frame;
		struct v4l2_format fmt;

		memset(&frame, 0, sizeof(frame));
		frame.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		if (ioctl(fd, IVTV_IOC_DMA_FRAME, &frame) < 0) {
			fprintf(stderr, "Unable to switch to user DMA YUV mode\n");
			exit(1);
		}
		fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
		doioctl(fd, VIDIOC_G_FMT, &fmt, "VIDIOC_G_FMT");
		printf("Current yuv_mode %d %s\n", fmt.fmt.pix.field,
				field2s(fmt.fmt.pix.field));
	}

	close(fd);
	exit(app_result);
}
Beispiel #30
0
char *rfc1035_recv_tcp(struct rfc1035_res *res, int fd, int *buflen, unsigned w)
{
int	len;
unsigned response_len;
char lenbuf[2];
char	*mallocedbuf=0;
time_t	current_time, finish_time;

	time(&current_time);
	finish_time=current_time+w;

	if (rfc1035_wait_reply(fd, w))
		return (0);

	len=doread(fd, lenbuf, 2);
	if (len <= 0)
	{
		errno=EIO;
		return (0);
	}
	if (len == 1)
	{
		time(&current_time);
		if (current_time >= finish_time)	return (0);
		if (rfc1035_wait_reply(fd, finish_time - current_time))
			return (0);

		len=doread(fd, lenbuf+1, 1);
		if (len <= 0)
		{
			errno=EIO;
			return (0);
		}
		++len;
	}

	response_len= ((unsigned)(unsigned char)lenbuf[0] << 8)
			| (unsigned char)lenbuf[1];

	if ((mallocedbuf=malloc(response_len)) == 0)
		return (0);

	*buflen=0;

	while ((unsigned)*buflen < response_len)
	{
		time(&current_time);
		if (current_time >= finish_time ||
			rfc1035_wait_reply(fd, finish_time - current_time))
		{
			len=0;
			errno=ETIMEDOUT;
		}
		else
			len=doread(fd, mallocedbuf + *buflen,
						response_len - *buflen);
		if (len <= 0)
		{
			free(mallocedbuf);
			return (0);
		}
		*buflen += len;
	}
	return (mallocedbuf);
}