Example #1
0
static long
consread(Chan *c, void *va, long n, vlong offset)
{
	ulong l;
	int i, send;
	char *p, buf[64], ch;

	if(c->qid.type & QTDIR)
		return devdirread(c, va, n, contab, nelem(contab), devgen);

	switch((ulong)c->qid.path) {
	default:
		error(Egreg);

	case Qsysctl:
		return readstr(offset, va, n, VERSION);

	case Qsysname:
		if(ossysname == nil)
			return 0;
		return readstr(offset, va, n, ossysname);

	case Qrandom:
		return randomread(va, n);

	case Qnotquiterandom:
		genrandom(va, n);
		return n;

	case Qpin:
		p = "pin set";
		if(up->env->pgrp->pin == Nopin)
			p = "no pin";
		return readstr(offset, va, n, p);

	case Qhostowner:
		return readstr(offset, va, n, eve);

	case Qhoststdin:
		return read(0, va, n);	/* should be pread */

	case Quser:
		return readstr(offset, va, n, up->env->user);

	case Qjit:
		snprint(buf, sizeof(buf), "%d", cflag);
		return readstr(offset, va, n, buf);

	case Qtime:
		snprint(buf, sizeof(buf), "%.lld", timeoffset + osusectime());
		return readstr(offset, va, n, buf);

	case Qdrivers:
		p = malloc(READSTR);
		if(p == nil)
			error(Enomem);
		l = 0;
		for(i = 0; devtab[i] != nil; i++)
			l += snprint(p+l, READSTR-l, "#%C %s\n", devtab[i]->dc,  devtab[i]->name);
		if(waserror()){
			free(p);
			nexterror();
		}
		n = readstr(offset, va, n, p);
		poperror();
		free(p);
		return n;

	case Qmemory:
		return poolread(va, n, offset);

	case Qnull:
		return 0;

	case Qmsec:
		return readnum(offset, va, n, osmillisec(), NUMSIZE);

	case Qcons:
		qlock(&kbd.q);
		if(waserror()){
			qunlock(&kbd.q);
			nexterror();
		}

		if(dflag)
			error(Enonexist);

		while(!qcanread(lineq)) {
			if(qread(kbdq, &ch, 1) == 0)
				continue;
			send = 0;
			if(ch == 0){
				/* flush output on rawoff -> rawon */
				if(kbd.x > 0)
					send = !qcanread(kbdq);
			}else if(kbd.raw){
				kbd.line[kbd.x++] = ch;
				send = !qcanread(kbdq);
			}else{
				switch(ch){
				case '\b':
					if(kbd.x)
						kbd.x--;
					break;
				case 0x15:
					kbd.x = 0;
					break;
				case 0x04:
					send = 1;
					break;
				case '\n':
					send = 1;
				default:
					kbd.line[kbd.x++] = ch;
					break;
				}
			}
			if(send || kbd.x == sizeof kbd.line){
				qwrite(lineq, kbd.line, kbd.x);
				kbd.x = 0;
			}
		}
		n = qread(lineq, va, n);
		qunlock(&kbd.q);
		poperror();
		return n;

	case Qscancode:
		if(offset == 0)
			return readstr(0, va, n, gkscanid);
		return qread(gkscanq, va, n);

	case Qkeyboard:
		return qread(gkbdq, va, n);

	case Qkprint:
		rlock(&kprintq.l);
		if(waserror()){
			runlock(&kprintq.l);
			nexterror();
		}
		n = qread(kprintq.q, va, n);
		poperror();
		runlock(&kprintq.l);
		return n;
	}
}
Example #2
0
static long
ipread(Chan *ch, void *a, long n, vlong off)
{
	Conv *c;
	Proto *x;
	char *buf, *p;
	long rv;
	Fs *f;
	ulong offset = off;

	f = ipfs[ch->dev];

	p = a;
	switch(TYPE(ch->qid)) {
	default:
		error(Eperm);
	case Qtopdir:
	case Qprotodir:
	case Qconvdir:
		return devdirread(ch, a, n, 0, 0, ipgen);
	case Qarp:
		return arpread(f->arp, a, offset, n);
 	case Qbootp:
 		return bootpread(a, offset, n);
 	case Qndb:
		return readstr(offset, a, n, f->ndb);
	case Qiproute:
		return routeread(f, a, offset, n);
	case Qipselftab:
		return ipselftabread(f, a, offset, n);
	case Qlog:
		return netlogread(f, a, offset, n);
	case Qctl:
		buf = smalloc(16);
		snprint(buf, 16, "%lud", CONV(ch->qid));
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qremote:
		buf = smalloc(Statelen);
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		if(x->remote == nil) {
			snprint(buf, Statelen, "%I!%d\n", c->raddr, c->rport);
		} else {
			(*x->remote)(c, buf, Statelen-2);
		}
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qlocal:
		buf = smalloc(Statelen);
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		if(x->local == nil) {
			snprint(buf, Statelen, "%I!%d\n", c->laddr, c->lport);
		} else {
			(*x->local)(c, buf, Statelen-2);
		}
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qstatus:
		buf = smalloc(Statelen);
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		(*x->state)(c, buf, Statelen-2);
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	case Qdata:
		c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
		return qread(c->rq, a, n);
	case Qerr:
		c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
		return qread(c->eq, a, n);
	case Qsnoop:
		c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
		return qread(c->sq, a, n);
	case Qstats:
		x = f->p[PROTO(ch->qid)];
		if(x->stats == nil)
			error("stats not implemented");
		buf = smalloc(Statelen);
		(*x->stats)(x, buf, Statelen);
		rv = readstr(offset, p, n, buf);
		free(buf);
		return rv;
	}
}
Example #3
0
static long
consread(Chan *c, void *va, long n, vlong offset)
{
	int send;
	char *p, buf[64], ch;

	if(c->qid.type & QTDIR)
		return devdirread(c, va, n, contab, nelem(contab), devgen);

	switch((ulong)c->qid.path) {
	default:
		error(Egreg);

	case Qsysctl:
		return readstr(offset, va, n, VERSION);

	case Qsysname:
		if(ossysname == nil)
			return 0;
		return readstr(offset, va, n, ossysname);

	case Qrandom:
		return randomread(va, n);

	case Qnotquiterandom:
		genrandom(va, n);
		return n;

	case Qhostowner:
		return readstr(offset, va, n, eve);

	case Qhoststdin:
		return read(0, va, n);	/* should be pread */

	case Quser:
		return readstr(offset, va, n, up->env->user);

	case Qjit:
		snprint(buf, sizeof(buf), "%d", cflag);
		return readstr(offset, va, n, buf);

	case Qtime:
		snprint(buf, sizeof(buf), "%.lld", timeoffset + osusectime());
		return readstr(offset, va, n, buf);

	case Qdrivers:
		return devtabread(c, va, n, offset);

	case Qmemory:
		return poolread(va, n, offset);

	case Qnull:
		return 0;

	case Qmsec:
		return readnum(offset, va, n, osmillisec(), NUMSIZE);

	case Qcons:
		qlock(&kbd.q);
		if(waserror()){
			qunlock(&kbd.q);
			nexterror();
		}

		if(dflag)
			error(Enonexist);

        /* register this proc's read interest in the channel */
        /* this probably won't be done here.  the read/readn requests 
         * are going to be different watcher callbacks
         */
        
        /* the following waits for a signal from the keyboard handler */
        uv_mutex_lock(&line_lock);
		uv_cond_wait(&line_ready, &line_lock);
		n = qread(lineq, va, n);
        uv_mutex_unlock(&line_lock);
		qunlock(&kbd.q);
		poperror();
		return n;

	case Qscancode:
		if(offset == 0)
			return readstr(0, va, n, gkscanid);
		return qread(gkscanq, va, n);

	case Qkeyboard:
		return qread(gkbdq, va, n);

	case Qkprint:
		rlock(&kprintq.l);
		if(waserror()){
			runlock(&kprintq.l);
			nexterror();
		}
		n = qread(kprintq.q, va, n);
		poperror();
		runlock(&kprintq.l);
		return n;
	}
}
Example #4
0
/*
 * Obtain status information on the com port.
 */
static long
rdstat(int port, void *buf, long n, ulong offset)
{
	HANDLE comfh = eia[port].comfh;
	char str[Maxctl];
	char *s;
	DCB dcb;
	DWORD modemstatus;
	DWORD porterr;
	COMSTAT  portstat;
	int frame, overrun, i;

	// valid line control ids
	static enum {
		L_CTS, L_DSR, L_RING, L_DCD, L_DTR, L_RTS, L_MAX
	};
	int status[L_MAX];

	// line control strings (should match above id's)
	static char* lines[] = {
		"cts", "dsr", "ring", "dcd", "dtr",	"rts", NULL
	};


	// get any error conditions; also clears error flag
	// and enables io
	if(!ClearCommError(comfh, &porterr, &portstat))
		oserror();

	// get comm port state
	if(!GetCommState(comfh, &dcb))
		oserror();

	// get modem line information
	if(!GetCommModemStatus(comfh, &modemstatus))
		oserror();

	// now set our local flags
	status[L_CTS] = MS_CTS_ON & modemstatus;
	status[L_DSR] = MS_DSR_ON & modemstatus;
	status[L_RING] = MS_RING_ON & modemstatus;
	status[L_DCD] = MS_RLSD_ON & modemstatus;
	status[L_DTR] = FALSE;  //?? cand this work: dcb.fDtrControl;
	status[L_RTS] = FALSE;  //??   dcb.fRtsControl;
	frame = porterr & CE_FRAME;
	overrun = porterr & CE_OVERRUN;

	/* TO DO: mimic native eia driver's first line */

	s = seprint(str, str+sizeof(str), "opens %d ferr %d oerr %d baud %d", 
		    eia[port].r.ref-1, 
			frame, 
			overrun,
		    dcb.BaudRate);

	// add line settings
	for(i=0; i < L_MAX; i++) 
		if(status[i])
			s = seprint(s, str+sizeof(str), " %s", lines[i]);
	seprint(s, str+sizeof(str), "\n");
	return readstr(offset, buf, n, str);
}
Example #5
0
static int32_t
irqmapread(Chan* c, void *vbuf, int32_t n, int64_t offset)
{
	char *readtodo(void);
	return readstr(offset, vbuf, n, readtodo());
}
Example #6
0
static long archread(struct chan *c, void *a, long n, int64_t offset)
{
	char *buf, *p;
	int port;
	uint16_t *sp;
	uint32_t *lp;
	IOMap *map;
	Rdwrfn *fn;

	switch ((uint32_t) c->qid.path) {

		case Qdir:
			return devdirread(c, a, n, archdir, narchdir, devgen);

		case Qgdb:
			p = gdbactive ? "1" : "0";
			return readstr(offset, a, n, p);
		case Qiob:
			port = offset;
			checkport(offset, offset + n);
			for (p = a; port < offset + n; port++)
				*p++ = inb(port);
			return n;

		case Qiow:
			if (n & 1)
				error(EINVAL, NULL);
			checkport(offset, offset + n);
			sp = a;
			for (port = offset; port < offset + n; port += 2)
				*sp++ = inw(port);
			return n;

		case Qiol:
			if (n & 3)
				error(EINVAL, NULL);
			checkport(offset, offset + n);
			lp = a;
			for (port = offset; port < offset + n; port += 4)
				*lp++ = inl(port);
			return n;

		case Qioalloc:
			break;

		default:
			if (c->qid.path < narchdir && (fn = readfn[c->qid.path]))
				return fn(c, a, n, offset);
			error(EPERM, NULL);
			break;
	}

	if ((buf = kzmalloc(n, 0)) == NULL)
		error(ENOMEM, NULL);
	p = buf;
	n = n / Linelen;
	offset = offset / Linelen;

	switch ((uint32_t) c->qid.path) {
		case Qioalloc:
			spin_lock(&(&iomap)->lock);
			for (map = iomap.map; n > 0 && map != NULL; map = map->next) {
				if (offset-- > 0)
					continue;
				snprintf(p, n * Linelen, "%#8p %#8p %-12.12s\n", map->start,
						 map->end - 1, map->tag);
				p += Linelen;
				n--;
			}
			spin_unlock(&(&iomap)->lock);
			break;
		case Qmapram:
			error(ENOSYS, NULL);
			break;
	}

	n = p - buf;
	memmove(a, buf, n);
	kfree(buf);

	return n;
}
Example #7
0
void netspool_start(s_netspool_state *state, const char *host, const char *port, const char *addresses, const char *password)
{
    int s, r;
    struct addrinfo hint;
    struct addrinfo *addrs, *a;
    char strbuf[STRBUF];

    s = socket(AF_INET6, SOCK_STREAM, 0);
    state->socket = s;
    if( s==-1 )
    {
        state->state = NS_ERROR;
        state->error = "socket error";
        return;
    }

    memset(&hint, 0, sizeof(struct addrinfo));
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_family = PF_INET6;
    hint.ai_flags = AI_V4MAPPED;

    r = getaddrinfo(host, port!=NULL? port: "24555", &hint, &addrs);

    if( r ) {
        state->state = NS_ERROR;
        state->error = gai_strerror(r);
        return;
    }

    a=addrs;
    r=-1;
    while(a) {
        r = connect(s, a->ai_addr, a->ai_addrlen);
        if(r==-1) {
            //printf("%d %s\n", errno, strerror(errno));
            ;
        } else {
            break;
        }
        a=a->ai_next;
    }
    freeaddrinfo(addrs);

    if(r==-1) {
        state->state = NS_ERROR;
        state->error = "could not connect";
        return;
    }

    r = readstr(s, strbuf, STRBUF);
    if( r ) {
        state->state = NS_ERROR;
        state->error = "IO error";
        return;
    }
    //puts(strbuf); -- hello from remote

    while (*addresses) { // stop when zero length string under pointer
        snprintf(strbuf, STRBUF, "ADDRESS %s", addresses);
        r = sendstr(s, strbuf);
        if( r ) {
            state->state = NS_ERROR;
            state->error = "IO error";
            return;
        }
        addresses += strlen(addresses)+1; // go to next string
    }

    snprintf(strbuf, STRBUF, "PASSWORD %s", password);
    r = sendstr(s, strbuf);
    if( r ) {
        state->state = NS_ERROR;
        state->error = "IO error";
        return;
    }

    state->state = NS_READY;
}
Example #8
0
File: cpu.c Project: npe9/harvey
void
main(int argc, char **argv)
{
	char dat[MaxStr], buf[MaxStr], cmd[MaxStr], *p, *err;
	int ac, fd, ms, data;
	char *av[10];

	quotefmtinstall();
	origargs = procgetname();
	/* see if we should use a larger message size */
	fd = open("/dev/draw", OREAD);
	if(fd > 0){
		ms = iounit(fd);
		if(msgsize < ms+IOHDRSZ)
			msgsize = ms+IOHDRSZ;
		close(fd);
	}

	user = getuser();
	if(user == nil)
		fatal(1, "can't read user name");
	ARGBEGIN{
	case 'a':
		p = EARGF(usage());
		if(setam(p) < 0)
			fatal(0, "unknown auth method %s", p);
		break;
	case 'e':
		ealgs = EARGF(usage());
		if(*ealgs == 0 || strcmp(ealgs, "clear") == 0)
			ealgs = nil;
		break;
	case 'd':
		dbg++;
		break;
	case 'f':
		/* ignored but accepted for compatibility */
		break;
	case 'O':
		p9authproto = "p9sk2";
		remoteside(1);				/* From listen */
		break;
	case 'R':				/* From listen */
		remoteside(0);
		break;
	case 'h':
		system = EARGF(usage());
		break;
	case 'c':
		cflag++;
		cmd[0] = '!';
		cmd[1] = '\0';
		while(p = ARGF()) {
			strcat(cmd, " ");
			strcat(cmd, p);
		}
		break;
	case 'k':
		keyspec = smprint("%s %s", keyspec, EARGF(usage()));
		break;
	case 'P':
		patternfile = EARGF(usage());
		break;
	case 'u':
		user = EARGF(usage());
		keyspec = smprint("%s user=%s", keyspec, user);
		break;
	default:
		usage();
	}ARGEND;


	if(argc != 0)
		usage();

	if(system == nil) {
		p = getenv("cpu");
		if(p == 0)
			fatal(0, "set $cpu");
		system = p;
	}

	if(err = rexcall(&data, system, srvname))
		fatal(1, "%s: %s", err, system);

	procsetname("%s", origargs);
	/* Tell the remote side the command to execute and where our working directory is */
	if(cflag)
		writestr(data, cmd, "command", 0);
	if(getwd(dat, sizeof(dat)) == 0)
		writestr(data, "NO", "dir", 0);
	else
		writestr(data, dat, "dir", 0);

	/* start up a process to pass aint32_t notes */
	lclnoteproc(data);

	/* 
	 *  Wait for the other end to execute and start our file service
	 *  of /mnt/term
	 */
	if(readstr(data, buf, sizeof(buf)) < 0)
		fatal(1, "waiting for FS: %r");
	if(strncmp("FS", buf, 2) != 0) {
		print("remote cpu: %s", buf);
		exits(buf);
	}

	/* Begin serving the gnot namespace */
	close(0);
	dup(data, 0);
	close(data);

	sprint(buf, "%d", msgsize);
	ac = 0;
	av[ac++] = exportfs;
	av[ac++] = "-m";
	av[ac++] = buf;
	if(dbg)
		av[ac++] = "-d";
	if(patternfile != nil){
		av[ac++] = "-P";
		av[ac++] = patternfile;
	}
	av[ac] = nil;
	exec(exportfs, av);
	fatal(1, "starting exportfs");
}
Example #9
0
/*
 * Here we communicate with the letsencrypt server.
 * For this, we'll need the certificate we want to upload and our
 * account key information.
 */
int
netproc(int kfd, int afd, int Cfd, int cfd, int dfd, int rfd,
	int newacct, int revoke, int staging,
	const char *const *alts, size_t altsz)
{
	int		 rc;
	size_t		 i;
	char		*cert, *thumb, *url;
	struct conn	 c;
	struct capaths	 paths;
	struct chng 	*chngs;
	long		 lval;

	rc = 0;
	memset(&paths, 0, sizeof(struct capaths));
	memset(&c, 0, sizeof(struct conn));
	url = cert = thumb = NULL;
	chngs = NULL;

	/* File-system, user, and sandbox jail. */

	if ( ! sandbox_before())
		goto out;
	else if ( ! dropfs(PATH_VAR_EMPTY))
		goto out;
	else if ( ! dropprivs())
		goto out;
	else if ( ! sandbox_after())
		goto out;

	/*
	 * Wait until the acctproc, keyproc, and revokeproc have started
	 * up and are ready to serve us data.
	 * There's no point in running if these don't work.
	 * Then check whether revokeproc indicates that the certificate
	 * on file (if any) can be updated.
	 */

	if (0 == (lval = readop(afd, COMM_ACCT_STAT))) {
		rc = 1;
		goto out;
	} else if (ACCT_READY != lval) {
		warnx("unknown operation from acctproc");
		goto out;
	}

	if (0 == (lval = readop(kfd, COMM_KEY_STAT))) {
		rc = 1;
		goto out;
	} else if (KEY_READY != lval) {
		warnx("unknown operation from keyproc");
		goto out;
	}

	if (0 == (lval = readop(rfd, COMM_REVOKE_RESP))) {
		rc = 1;
		goto out;
	} else if (REVOKE_EXP != lval && REVOKE_OK != lval) {
		warnx("unknown operation from revokeproc");
		goto out;
	}

	/* If our certificate is up-to-date, return now. */

	if (REVOKE_OK == lval) {
		rc = 1;
		goto out;
	}

	/* Allocate main state. */

	chngs = calloc(altsz, sizeof(struct chng));
	if (NULL == chngs) {
		warn("calloc");
		goto out;
	}

	c.dfd = dfd;
	c.fd = afd;
	c.na = staging ? URL_STAGE_CA : URL_REAL_CA;

	/*
	 * Look up the domain of the ACME server.
	 * We'll use this ourselves instead of having libcurl do the DNS
	 * resolution itself.
	 */
	if ( ! dodirs(&c, c.na, &paths))
		goto out;

	/*
	 * If we're meant to revoke, then wait for revokeproc to send us
	 * the certificate (if it's found at all).
	 * Following that, submit the request to the CA then notify the
	 * certproc, which will in turn notify the fileproc.
	 */

	if (revoke) {
		if (NULL == (cert = readstr(rfd, COMM_CSR)))
			goto out;
		if ( ! dorevoke(&c, paths.revokecert, cert))
			goto out;
		else if (writeop(cfd, COMM_CSR_OP, CERT_REVOKE) > 0)
			rc = 1;
		goto out;
	}

	/* If new, register with the CA server. */

	if (newacct && ! donewreg(&c, &paths))
		goto out;

	/* Pre-authorise all domains with CA server. */

	for (i = 0; i < altsz; i++)
		if ( ! dochngreq(&c, alts[i], &chngs[i], &paths))
			goto out;

	/*
	 * We now have our challenges.
	 * We need to ask the acctproc for the thumbprint.
	 * We'll combine this to the challenge to create our response,
	 * which will be orchestrated by the chngproc.
	 */

	if (writeop(afd, COMM_ACCT, ACCT_THUMBPRINT) <= 0)
		goto out;
	else if (NULL == (thumb = readstr(afd, COMM_THUMB)))
		goto out;

	/* We'll now ask chngproc to build the challenge. */

	for (i = 0; i < altsz; i++) {
		if (writeop(Cfd, COMM_CHNG_OP, CHNG_SYN) <= 0)
			goto out;
		else if (writestr(Cfd, COMM_THUMB, thumb) <= 0)
			goto out;
		else if (writestr(Cfd, COMM_TOK, chngs[i].token) <= 0)
			goto out;

		/* Read that the challenge has been made. */

		if (CHNG_ACK != readop(Cfd, COMM_CHNG_ACK))
			goto out;

		/* Write to the CA that it's ready. */

		if ( ! dochngresp(&c, &chngs[i], thumb))
			goto out;
	}

	/*
	 * We now wait on the ACME server for each domain.
	 * Connect to the server (assume it's the same server) once
	 * every five seconds.
	 */

	for (i = 0; i < altsz; i++) {
		if (1 == chngs[i].status)
			continue;

		if (chngs[i].retry++ >= RETRY_MAX) {
			warnx("%s: too many tries", chngs[i].uri);
			goto out;
		}

		/* Sleep before every attempt. */
		sleep(RETRY_DELAY);
		if ( ! dochngcheck(&c, &chngs[i]))
			goto out;
	}

	/*
	 * Write our acknowledgement that the challenges are over.
	 * The challenge process will remove all of the files.
	 */

	if (writeop(Cfd, COMM_CHNG_OP, CHNG_STOP) <= 0)
		goto out;

	/* Wait to receive the certificate itself. */

	if (NULL == (cert = readstr(kfd, COMM_CERT)))
		goto out;

	/*
	 * Otherwise, submit the CA for signing, download the signed
	 * copy, and ship that into the certificate process for copying.
	 */

	if ( ! docert(&c, paths.newcert, cert))
		goto out;
	else if (writeop(cfd, COMM_CSR_OP, CERT_UPDATE) <= 0)
		goto out;
	else if (writebuf(cfd, COMM_CSR, c.buf.buf, c.buf.sz) <= 0)
		goto out;

	/*
	 * Read back the issuer from the certproc.
	 * Then contact the issuer to get the certificate chain.
	 * Write this chain directly back to the certproc.
	 */

	if (NULL == (url = readstr(cfd, COMM_ISSUER)))
		goto out;
	else if ( ! dofullchain(&c, url))
		goto out;
	else if (writebuf(cfd, COMM_CHAIN, c.buf.buf, c.buf.sz) <= 0)
		goto out;

	rc = 1;
out:
	close(cfd);
	close(kfd);
	close(afd);
	close(Cfd);
	close(dfd);
	close(rfd);
	free(cert);
	free(url);
	free(thumb);
	free(c.buf.buf);
	if (NULL != chngs)
		for (i = 0; i < altsz; i++)
			json_free_challenge(&chngs[i]);
	free(chngs);
	json_free_capaths(&paths);
	return(rc);
}
//
//  Load OBJ file
//
int LoadOBJ(const char* file)
{
   int k;
   int  Nv,Nn,Nt;  //  Number of vertex, normal and textures
   int  Mv,Mn,Mt;  //  Maximum vertex, normal and textures
   float* V;       //  Array of vertexes
   float* N;       //  Array of normals
   float* T;       //  Array if textures coordinates
   char*  line;    //  Line pointer
   char*  str;     //  String pointer

   //  Open file
   FILE* f = fopen(file,"r");
   if (!f) Fatal("Cannot open file %s\n",file);

   // Reset materials
   mtl = NULL;
   Nmtl = 0;

   //  Start new displaylist
   int list = glGenLists(1);
   glNewList(list,GL_COMPILE);
   //  Push attributes for textures
   glPushAttrib(GL_TEXTURE_BIT);

   //  Read vertexes and facets
   V  = N  = T  = NULL;
   Nv = Nn = Nt = 0;
   Mv = Mn = Mt = 0;
   while ((line = readline(f)))
   {
      //  Vertex coordinates (always 3)
      if (line[0]=='v' && line[1]==' ')
         readcoord(line+2,3,&V,&Nv,&Mv);
      //  Normal coordinates (always 3)
      else if (line[0]=='v' && line[1] == 'n')
         readcoord(line+2,3,&N,&Nn,&Mn);
      //  Texture coordinates (always 2)
      else if (line[0]=='v' && line[1] == 't')
         readcoord(line+2,2,&T,&Nt,&Mt);
      //  Read and draw facets
      else if (line[0]=='f')
      {
         line++;
         //  Read Vertex/Texture/Normal triplets
         glBegin(GL_POLYGON);
         while ((str = getword(&line)))
         {
            int Kv,Kt,Kn;
            //  Try Vertex/Texture/Normal triplet
            if (sscanf(str,"%d/%d/%d",&Kv,&Kt,&Kn)==3)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               if (Kn<0 || Kn>Nn/3) Fatal("Normal %d out of range 1-%d\n",Kn,Nn/3);
               if (Kt<0 || Kt>Nt/2) Fatal("Texture %d out of range 1-%d\n",Kt,Nt/2);
            }
            //  Try Vertex//Normal pairs
            else if (sscanf(str,"%d//%d",&Kv,&Kn)==2)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               if (Kn<0 || Kn>Nn/3) Fatal("Normal %d out of range 1-%d\n",Kn,Nn/3);
               Kt = 0;
            }
            //  Try Vertex index
            else if (sscanf(str,"%d",&Kv)==1)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               Kn = 0;
               Kt = 0;
            }
            //  This is an error
            else
               Fatal("Invalid facet %s\n",str);
            //  Draw vectors
            if (Kt) glTexCoord2fv(T+2*(Kt-1));
            if (Kn) glNormal3fv(N+3*(Kn-1));
            if (Kv) glVertex3fv(V+3*(Kv-1));
         }
         glEnd();
      }
      //  Use material
      else if ((str = readstr(line,"usemtl")))
         SetMaterial(str);
      //  Load materials
      else if ((str = readstr(line,"mtllib")))
         LoadMaterial(str);
      //  Skip this line
   }
   fclose(f);
   //  Pop attributes (textures)
   glPopAttrib();
   glEndList();

   //  Free materials
   for (k=0;k<Nmtl;k++)
      free(mtl[k].name);
   free(mtl);

   //  Free arrays
   free(V);
   free(T);
   free(N);

   return list;
}
Example #11
0
/*
 * Create and send a signed communication to the ACME server.
 * Stuff the response into the communication buffer.
 * Return <0 on failure on the HTTP error code otherwise.
 */
static long
sreq(struct conn *c, const char *addr, const char *req)
{
	struct httpget	*g;
	struct source	 src[MAX_SERVERS_DNS];
	char		*host, *path, *nonce, *reqsn;
	short		 port;
	struct httphead	*h;
	ssize_t		 ssz;
	long		 code;

	if (NULL == (host = url2host(c->na, &port, &path)))
		return(-1);

	if ((ssz = urlresolve(c->dfd, host, src)) < 0) {
		free(host);
		free(path);
		return(-1);
	}

	g = http_get(src, (size_t)ssz, host, port, path, NULL, 0);
	free(host);
	free(path);
	if (NULL == g)
		return(-1);

	h = http_head_get("Replay-Nonce", g->head, g->headsz);
	if (NULL == h) {
		warnx("%s: no replay nonce", c->na);
		http_get_free(g);
		return(-1);
	} else if (NULL == (nonce = strdup(h->val))) {
		warn("strdup");
		http_get_free(g);
		return(-1);
	}
	http_get_free(g);

	/*
	 * Send the nonce and request payload to the acctproc.
	 * This will create the proper JSON object we need.
	 */

	if (writeop(c->fd, COMM_ACCT, ACCT_SIGN) <= 0) {
		free(nonce);
		return(-1);
	} else if (writestr(c->fd, COMM_PAY, req) <= 0) {
		free(nonce);
		return(-1);
	} else if (writestr(c->fd, COMM_NONCE, nonce) <= 0) {
		free(nonce);
		return(-1);
	}
	free(nonce);

	/* Now read back the signed payload. */

	if (NULL == (reqsn = readstr(c->fd, COMM_REQ)))
		return(-1);

	/* Now send the signed payload to the CA. */

	if (NULL == (host = url2host(addr, &port, &path))) {
		free(reqsn);
		return(-1);
	} else if ((ssz = urlresolve(c->dfd, host, src)) < 0) {
		free(host);
		free(path);
		free(reqsn);
		return(-1);
	}

	g = http_get(src, (size_t)ssz, host,
		port, path, reqsn, strlen(reqsn));

	free(host);
	free(path);
	free(reqsn);
	if (NULL == g)
		return(-1);

	/* Stuff response into parse buffer. */

	code = g->code;

	free(c->buf.buf);
	c->buf.sz = g->bodypartsz;
	c->buf.buf = malloc(c->buf.sz);
	memcpy(c->buf.buf, g->bodypart, c->buf.sz);
	http_get_free(g);
	if (NULL == c->buf.buf) {
		warn("malloc");
		return(-1);
	}
	return(code);
}
Example #12
0
static int32_t
cmdread(Chan *ch, void *a, int32_t n, int64_t offset)
{
	Proc *up = externup();
	Conv *c;
	Proc *p;
	char *s, *cmds;
	int fd;
	char buf[256];

	USED(offset);

	s = a;
	switch(TYPE(ch->qid)) {
	default:
		error(Eperm);
	case Qcmd:
	case Qtopdir:
	case Qconvdir:
		return devdirread(ch, a, n, 0, 0, cmdgen);
	case Qctl:
		sprint(up->genbuf, "%ld", CONV(ch->qid));
		return readstr(offset, s, n, up->genbuf);
	case Qalloc:
		c = cmd.conv[CONV(ch->qid)];
		p = c->p;
		snprint(buf, sizeof(buf), "%#p %#p %#p %#p %#p %#p %#p %#p",
			p->seg[TSEG]->base, p->seg[TSEG]->top,
			p->seg[DSEG]->base, p->seg[DSEG]->top,
			p->seg[BSEG]->base, p->seg[BSEG]->top,
			p->seg[SSEG]->base, p->seg[SSEG]->top);
		return readstr(offset, s, n, buf);
	case Qexec:
		c = cmd.conv[CONV(ch->qid)];
		snprint(up->genbuf, sizeof(up->genbuf), "%ld", c->esz);
		return readstr(offset, s, n, up->genbuf);
	case Qstatus:
		c = cmd.conv[CONV(ch->qid)];
		cmds = "";
		if(c->cmd != nil)
			cmds = c->cmd->f[1];
		snprint(up->genbuf, sizeof(up->genbuf), "cmd/%d %d %s %q %q\n",
			c->x, c->inuse, c->state, c->dir, cmds);
		return readstr(offset, s, n, up->genbuf);
	case Qdata:
	case Qstderr:
		fd = 1;
		if(TYPE(ch->qid) == Qstderr)
			fd = 2;
		c = cmd.conv[CONV(ch->qid)];
		qlock(&c->l);
		if(c->fd[fd] == -1){
			qunlock(&c->l);
			return 0;
		}
		qunlock(&c->l);
	//	osenter();
//		n = read(c->fd[fd], a, n);
//		osleave();
//		if(n < 0)
//			oserror();
		return n;
	case Qwait:
		c = cmd.conv[CONV(ch->qid)];
		return qread(c->waitq, a, n);
	}
}
Example #13
0
int main(int argc, char **argv)
{
    if(argc < 3)
    {
        printf("Usage: %s [source] [output]\n", argv[0]);
        return EXIT_FAILURE;
    }

    FILE *src = fopen(argv[1], "rt");
    if(src == NULL)
    {
        printf("Error.\n");
        return EXIT_FAILURE;
    }

    FILE *dest = fopen(argv[2], "wb");
    if(dest == NULL)
    {
        printf("Error.\n");
        return EXIT_FAILURE;
    }

    int i,j;

    mat_t material;
    int have_material = 0;
    int num_vertices = 0;
    int num_faces = 0;
    int num_texcoords = 0;
    int num_normals = 0;
    char line[256];

    fseek(src, SEEK_SET, 0);

    readstr(src, line);
    char mtllib[256];
    char mat_name[256];
    if(sscanf(line, "mtllib %s\n", mtllib) != NULL)
    {
        printf("Material: %s\n", mtllib);
        FILE *mtl = fopen(mtllib, "rt");
        if(mtl == NULL)
        {
            printf("Error.\n");
            return EXIT_FAILURE;
        }
        else
        {
            readstr(mtl, line);
            sscanf(line, "newmtl %s\n", mat_name);
            readstr(mtl, line);
            sscanf(line, "Ka %f %f %f\n", &material.a[0], &material.a[1], &material.a[2]);
            readstr(mtl, line);
            sscanf(line, "Kd %f %f %f\n", &material.d[0], &material.d[1], &material.d[2]);
            readstr(mtl, line);
            sscanf(line, "Ks %f %f %f\n", &material.s[0], &material.s[1], &material.s[2]);
            readstr(mtl, line);
            readstr(mtl, line);
            sscanf(line, "Ns %f\n", &material.sh);
            readstr(mtl, line);
            sscanf(line, "map_Kd %s\n", &material.texD);
            readstr(mtl, line);
            sscanf(line, "map_Ka %s\n", &material.texA);
            readstr(mtl, line);
            sscanf(line, "map_Ks %s\n", &material.texS);
            have_material = 1;
        }
    }

    while(readstr(src, line) == 0)
    {
        switch(line[0])
        {
            case 'v':
                switch(line[1])
                {
                    case 't': // texture choord
                        num_texcoords++;
                        break;
                    case 'n': // normal
                        num_normals++;
                        break;
                    default: // vertex
                        num_vertices++;
                        break;
                }
                break;
            case 'f':
                num_faces++;
                break;
        }
    }

    printf("%d vertices\n", num_vertices);
    printf("%d texture coords\n", num_texcoords);
    printf("%d normals\n", num_normals);
    printf("%d faces\n", num_faces);

    vertex3d_t *vertices = (vertex3d_t*) calloc(num_vertices, sizeof(vertex3d_t));
    uv_t *texcoords = (uv_t*) calloc(num_texcoords, sizeof(uv_t));
    int **uv_maps = (int**) calloc(num_faces, sizeof(int*));
    int *size = (int*) calloc(num_faces, sizeof(int));
    int **faces = (int**) calloc(num_faces, sizeof(int*));

    fseek(src, SEEK_SET, 0);
    int v = 0, t = 0, n = 0, f = 0, pos;
    int c,d,e;
    char buf[256];

    while(readstr(src, line) == 0)
    {
        int len = strlen(line);
        switch(line[0])
        {
            case 'v':
                switch(line[1])
                {
                    case 't':
                        sscanf(line, "vt %f %f\n", &texcoords[t].u, &texcoords[t].v);
                        t++;
                        break;
                    case 'n':
                        // ignore normals
                        n++;
                        break;
                    default:
                        sscanf(line, "v %f %f %f\n", &vertices[v].x, &vertices[v].y, &vertices[v].z);
                        v++;
                        break;
                }
                break;
            case 'f':
                size[f] = 0;
                pos = 1;
                while(pos < len)
                {
                    if(num_texcoords == 0 && num_normals == 0)
                    {
                        if(sscanf(line+pos, " %d", &c) == EOF) break;
                        sprintf(buf, " %d", c);
                        pos += strlen(buf);
                    }
                    else if(num_texcoords != 0 && num_normals == 0)
                    {
                        if(sscanf(line+pos, " %d/%d", &c, &d) == EOF) break;
                        sprintf(buf, " %d/%d", c, d);
                        pos += strlen(buf);
                    }
                    else if(num_texcoords != 0 && num_normals != 0)
                    {
                        if(sscanf(line+pos, " %d/%d/%d", &c, &d, &e) == EOF) break;
                        sprintf(buf, " %d/%d/%d", c, d, e);
                        pos += strlen(buf);
                    }
                    size[f]++;
                }
                faces[f] = (int*) calloc(size[f], sizeof(int));
                if(num_texcoords != 0)
                {
                    uv_maps[f] = (int*) calloc(size[f], sizeof(int));
                }

                pos = 1;
                for(i = 0; i < size[f]; i++)
                {
                    if(num_texcoords == 0 && num_normals == 0)
                    {
                        sscanf(line+pos, " %d", &faces[f][i]);
                        sprintf(buf, " %d", faces[f][i]);
                        pos += strlen(buf);
                    }
                    else if(num_texcoords != 0 && num_normals == 0)
                    {
                        sscanf(line+pos, " %d/%d", &faces[f][i], &uv_maps[f][i]);
                        sprintf(buf, " %d/%d", faces[f][i], uv_maps[f][i]);
                        pos += strlen(buf);
                    }
                    else if(num_texcoords != 0 && num_normals != 0)
                    {
                        sscanf(line+pos, " %d/%d/%d", &faces[f][i], &uv_maps[f][i], &e);
                        sprintf(buf, " %d/%d/%d", faces[f][i], uv_maps[f][i], e);
                        pos += strlen(buf);
                    }
                }
                f++;
                break;
            default:
                break;
        }
    }

    if(! have_material)
    {
        fprintf(dest,
                "MATERIAL\n"
                "texture.png\n"
                "AMBIENT   0.2 0.2 0.2 0.0\n"
                "DIFFUSE   1.0 1.0 1.0 0.0\n"
                "SPECULAR  0.2 0.2 0.2 0.0\n"
                "SHININESS 1.0\n\n"
               );
    }
    else
    {
        fprintf(dest, "MATERIAL\n");
        fprintf(dest, "%s\n", material.texD);
        fprintf(dest, "AMBIENT   %f %f %f %f\n", material.a[0], material.a[1], material.a[2]);
        fprintf(dest, "DIFFUSE   %f %f %f %f\n", material.d[0], material.d[1], material.d[2]);
        fprintf(dest, "SPECULAR  %f %f %f %f\n", material.s[0], material.s[1], material.s[2]);
        fprintf(dest, "SHININESS %f\n\n", material.sh);
    }

    fprintf(dest, "VERTICES %d\n", num_vertices);
    for(i = 0; i < num_vertices; i++)
    {
        fprintf(dest, "%d: %f %f %f\n", i, vertices[i].x, vertices[i].y, vertices[i].z);
    }

    fprintf(dest, "\n");

    if(num_texcoords != 0)
    {
        fprintf(dest, "UVMAPS %d\n", num_faces);
        for(i = 0; i < num_faces; i++)
        {
            fprintf(dest, "%d: SIZE %d\n", i, size[i]);
            for(j = 0; j < size[i]; j++)
            {
                fprintf(dest, "%f %f\n", texcoords[uv_maps[i][j]-1].u, texcoords[uv_maps[i][j]-1].v);
            }
        }
    }
    else
    {
        fprintf(dest,
                "UVMAPS 1\n"
                "0: SIZE 4\n"
                "0 1\n"
                "0 0\n"
                "1 0\n"
                "1 1\n\n"
               );
    }

    fprintf(dest, "\n");

    fprintf(dest, "FACES %d\n", num_faces);
    for(i = 0; i < num_faces; i++)
    {
        int uvmap = 0;
        if(num_texcoords != 0) uvmap = i;
        fprintf(dest, "%d : SIZE %d\n%d", i, size[i], uvmap);
        for(j = 0; j < size[i]; j++)
        {
            fprintf(dest, " %d", faces[i][j]-1);
        }
        fprintf(dest, "\n");
    }

    fclose(src);
    fclose(dest);

    return EXIT_SUCCESS;
}
Example #14
0
static int cb(RDiff *d, void *user, RDiffOp *op) {
	int i; //, diffmode = (int)(size_t)user;
	char s[256];
	if (showcount) {
		count++;
		return 1;
	}
	switch (diffmode) {
	case 'U': // 'U' in theory never handled here
	case 'u':
		if (op->a_len > 0) {
			readstr (s, sizeof (s), op->a_buf, op->a_len);
			if (*s) {
				if (!quiet) printf (Color_RED);
				if (r_mem_is_printable ((const ut8*)s, R_MIN (strlen (s), 5))) {
					printf ("- %s\n", s);
				} else {
					printf ("-:");
					int len = op->a_len; //R_MIN (op->a_len, strlen (op->a_buf));
					for (i = 0; i < len; i++) {
						printf ("%02x", op->a_buf[i]);
					}
					printf (" \"%s\"\n", op->a_buf);
				}
				if (!quiet) printf (Color_RESET);
			}
		}
		if (op->b_len > 0) {
			readstr (s, sizeof (s), op->b_buf, op->b_len);
			if (*s) {
				if (!quiet) printf (Color_GREEN);
				if (r_mem_is_printable ((const ut8*)s, R_MIN (strlen (s), 5))) {
					printf ("+ %s\n", s);
				} else {
					printf ("+:");
					for (i = 0; i < op->b_len; i++) {
						printf ("%02x", op->b_buf[i]);
					}
					printf (" \"%s\"\n", op->b_buf);
				}
				if (!quiet) printf (Color_RESET);
			}
		}
		break;
	case 'r':
		if (disasm) {
			eprintf ("r2cmds (-r) + disasm (-D) not yet implemented\n");
		}
		if (op->a_len == op->b_len) {
			printf ("wx ");
			for (i = 0; i < op->b_len; i++) {
				printf ("%02x", op->b_buf[i]);
			}
			printf (" @ 0x%08"PFMT64x"\n", op->b_off);
		} else {
			if (op->a_len > 0) {
				printf ("r-%d @ 0x%08"PFMT64x"\n",
					op->a_len, op->a_off + delta);
			}
			if (op->b_len > 0) {
				printf ("r+%d @ 0x%08"PFMT64x"\n",
					op->b_len, op->b_off + delta);
				printf ("wx ");
				for (i = 0; i < op->b_len; i++) {
					printf ("%02x", op->b_buf[i]);
				}
				printf (" @ 0x%08"PFMT64x"\n", op->b_off+delta);
			}
			delta += (op->b_off - op->a_off);
		}
		return 1;
	case 'j':
		if (disasm) {
			eprintf ("JSON (-j) + disasm (-D) not yet implemented\n");
		}
		if (json_started) {
			printf (",\n");
		}
		json_started = 1;
		printf ("{\"offset\":%"PFMT64d",", op->a_off);
		printf("\"from\":\"");
		for (i = 0; i < op->a_len; i++) {
			printf ("%02x", op->a_buf[i]);
		}
		printf ("\", \"to\":\"");
		for (i = 0; i < op->b_len; i++) {
			printf ("%02x", op->b_buf[i]);
		}
		printf ("\"}"); //,\n");
		return 1;
	case 0:
	default:
		if (disasm) {
			printf ("--- 0x%08"PFMT64x"\n", op->a_off);
			if (!core) {
				core = opencore (file);
				if (arch) {
					r_config_set (core->config, "asm.arch", arch);
				}
				if (bits) {
					r_config_set_i (core->config, "asm.bits", bits);
				}
			}
			if (core) {
				RAsmCode *ac = r_asm_mdisassemble (core->assembler, op->a_buf, op->a_len);
				printf ("%s\n", ac->buf_asm);
				//r_asm_code_free (ac);
			}
		} else {
			printf ("0x%08"PFMT64x" ", op->a_off);
			for (i = 0; i < op->a_len; i++) {
				printf ("%02x", op->a_buf[i]);
			}
		}
		if (disasm) {
			printf ("+++ 0x%08"PFMT64x"\n", op->b_off);
			if (!core) {
				core = opencore (NULL);
			}
			if (core) {
				RAsmCode *ac = r_asm_mdisassemble (core->assembler, op->b_buf, op->b_len);
				printf ("%s\n", ac->buf_asm);
				//r_asm_code_free (ac);
			}
		} else {
			printf (" => ");
			for (i = 0; i < op->b_len; i++) {
				printf ("%02x", op->b_buf[i]);
			}
			printf (" 0x%08"PFMT64x"\n", op->b_off);
		}
		return 1;
	}
	return 0;
}
Example #15
0
int
chngproc(int netsock, const char *root, int remote)
{
	int		  rc;
	long		  lval;
	enum chngop	  op;
	char		 *tok, *th, *fmt;
	char		**fs;
	size_t		  i, fsz;
	void		 *pp;
	int		  fd, cc;

	rc = 0;
	th = tok = fmt = NULL;
	fd = -1;
	fs = NULL;
	fsz = 0;

	/* File-system and sandbox jailing. */

	if ( ! sandbox_before())
		goto out;
	else if ( ! dropfs(root))
		goto out;
	else if ( ! sandbox_after())
		goto out;

	/* 
	 * Loop while we wait to get a thumbprint and token.
	 * We'll get this for each SAN request.
	 */

	for (;;) {
		op = CHNG__MAX;
		if (0 == (lval = readop(netsock, COMM_CHNG_OP))) 
			op = CHNG_STOP;
		else if (CHNG_SYN == lval)
			op = lval;

		if (CHNG__MAX == op) {
			warnx("unknown operation from netproc");
			goto out;
		} else if (CHNG_STOP == op)
			break;

		assert(CHNG_SYN == op);

		/* 
		 * Read the thumbprint and token.
		 * The token is the filename, so store that in a vector
		 * of tokens that we'll later clean up.
		 */

		if (NULL == (th = readstr(netsock, COMM_THUMB)))
			goto out;
		else if (NULL == (tok = readstr(netsock, COMM_TOK)))
			goto out;

		/* Vector appending... */

		pp = realloc(fs, (fsz + 1) * sizeof(char *));
		if (NULL == pp) {
			warn("realloc");
			goto out;
		}
		fs = pp;
		fs[fsz] = tok;
		tok = NULL;
		fsz++;

		if (-1 == asprintf(&fmt, "%s.%s", fs[fsz - 1], th)) {
			warn("asprintf");
			goto out;
		}

		/*
		 * I use this for testing when letskencrypt is being run
		 * on machines apart from where I'm hosting the
		 * challenge directory.
		 * DON'T DEPEND ON THIS FEATURE.
		 */
		if (remote) {
			puts("RUN THIS IN THE CHALLENGE DIRECTORY");
			puts("YOU HAVE 20 SECONDS...");
			printf("doas sh -c \"echo %s > %s\"\n", 
				fmt, fs[fsz - 1]);
			sleep(20);
			puts("TIME'S UP.");
		} else { 
			/* 
			 * Create and write to our challenge file.
			 * Note: we use file descriptors instead of FILE
			 * because we want to minimise our pledges.
			 */
			fd = open(fs[fsz - 1], 
				O_WRONLY|O_EXCL|O_CREAT, 0444);
			if (-1 == fd) {
				warn("%s", fs[fsz - 1]);
				goto out;
			} if (-1 == write(fd, fmt, strlen(fmt))) {
				warn("%s", fs[fsz - 1]);
				goto out;
			} else if (-1 == close(fd)) {
				warn("%s", fs[fsz - 1]);
				goto out;
			}
			fd = -1;
		}

		free(th);
		free(fmt);
		th = fmt = NULL;

		dodbg("%s/%s: created", root, fs[fsz - 1]);

		/* 
		 * Write our acknowledgement. 
		 * Ignore reader failure.
		 */

		cc = writeop(netsock, COMM_CHNG_ACK, CHNG_ACK);
		if (0 == cc)
			break;
		if (cc < 0)
			goto out;
	}

	rc = 1;
out:
	close(netsock);
	if (-1 != fd)
		close(fd);
	for (i = 0; i < fsz; i++) {
		if (-1 == unlink(fs[i]) && ENOENT != errno)
			warn("%s", fs[i]);
		free(fs[i]);
	}
	free(fs);
	free(fmt);
	free(th);
	free(tok);
	return(rc);
}
Example #16
0
static long
ifstat(Ether* ether, void* a, long n, ulong offset)
{
	Ctlr *ctlr;
	char *buf, *p;
	int i, l, len;

	ctlr = ether->ctlr;

	ether->crcs = ctlr->ce;
	ether->frames = ctlr->rf+ctlr->cs;
	ether->buffs = ctlr->de+ctlr->tl;
	ether->overflows = ctlr->of;

	if(n == 0)
		return 0;

	p = smalloc(READSTR);
	l = snprint(p, READSTR, "Overflow: %lud\n", ctlr->of);
	l += snprint(p+l, READSTR-l, "Ru: %lud\n", ctlr->ru);
	l += snprint(p+l, READSTR-l, "Rps: %lud\n", ctlr->rps);
	l += snprint(p+l, READSTR-l, "Rwt: %lud\n", ctlr->rwt);
	l += snprint(p+l, READSTR-l, "Tps: %lud\n", ctlr->tps);
	l += snprint(p+l, READSTR-l, "Tu: %lud\n", ctlr->tu);
	l += snprint(p+l, READSTR-l, "Tjt: %lud\n", ctlr->tjt);
	l += snprint(p+l, READSTR-l, "Unf: %lud\n", ctlr->unf);
	l += snprint(p+l, READSTR-l, "CRC Error: %lud\n", ctlr->ce);
	l += snprint(p+l, READSTR-l, "Collision Seen: %lud\n", ctlr->cs);
	l += snprint(p+l, READSTR-l, "Frame Too Long: %lud\n", ctlr->tl);
	l += snprint(p+l, READSTR-l, "Runt Frame: %lud\n", ctlr->rf);
	l += snprint(p+l, READSTR-l, "Descriptor Error: %lud\n", ctlr->de);
	l += snprint(p+l, READSTR-l, "Underflow Error: %lud\n", ctlr->uf);
	l += snprint(p+l, READSTR-l, "Excessive Collisions: %lud\n", ctlr->ec);
	l += snprint(p+l, READSTR-l, "Late Collision: %lud\n", ctlr->lc);
	l += snprint(p+l, READSTR-l, "No Carrier: %lud\n", ctlr->nc);
	l += snprint(p+l, READSTR-l, "Loss of Carrier: %lud\n", ctlr->lo);
	l += snprint(p+l, READSTR-l, "Transmit Jabber Timeout: %lud\n",
		ctlr->to);
	l += snprint(p+l, READSTR-l, "csr6: %luX %uX\n", csr32r(ctlr, 6),
		ctlr->csr6);
	snprint(p+l, READSTR-l, "ntqmax: %d\n", ctlr->ntqmax);
	ctlr->ntqmax = 0;
	buf = a;
	len = readstr(offset, buf, n, p);
	if(offset > l)
		offset -= l;
	else
		offset = 0;
	buf += len;
	n -= len;

	l = snprint(p, READSTR, "srom:");
	for(i = 0; i < (1<<(ctlr->sromsz)*sizeof(ushort)); i++){
		if(i && ((i & 0x0F) == 0))
			l += snprint(p+l, READSTR-l, "\n     ");
		l += snprint(p+l, READSTR-l, " %2.2uX", ctlr->srom[i]);
	}

	snprint(p+l, READSTR-l, "\n");
	len += readstr(offset, buf, n, p);
	free(p);

	return len;
}
Example #17
0
long
w_ifstat(Ether* ether, void* a, long n, ulong offset)
{
	Ctlr *ctlr = (Ctlr*) ether->ctlr;
	char *k, *p;
	int i, l, txid;

	ether->oerrs = ctlr->ntxerr;
	ether->crcs = ctlr->nrxfcserr;
	ether->frames = 0;
	ether->buffs = ctlr->nrxdropnobuf;
	ether->overflows = 0;

	//
	// Offset must be zero or there's a possibility the
	// new data won't match the previous read.
	//
	if(n == 0 || offset != 0)
		return 0;

	p = malloc(READSTR);
	l = 0;

	PRINTSTAT("Signal: %d\n", ctlr->signal-149);
	PRINTSTAT("Noise: %d\n", ctlr->noise-149);
	PRINTSTAT("SNR: %ud\n", ctlr->signal-ctlr->noise);
	PRINTSTAT("Interrupts: %lud\n", ctlr->nints);
	PRINTSTAT("Double Interrupts: %lud\n", ctlr->ndoubleint);
	PRINTSTAT("TxPackets: %lud\n", ctlr->ntx);
	PRINTSTAT("RxPackets: %lud\n", ctlr->nrx);
	PRINTSTAT("TxErrors: %lud\n", ctlr->ntxerr);
	PRINTSTAT("RxErrors: %lud\n", ctlr->nrxerr);
	PRINTSTAT("TxRequests: %lud\n", ctlr->ntxrq);
	PRINTSTAT("AllocEvs: %lud\n", ctlr->nalloc);
	PRINTSTAT("InfoEvs: %lud\n", ctlr->ninfo);
	PRINTSTAT("InfoDrop: %lud\n", ctlr->nidrop);
	PRINTSTAT("WatchDogs: %lud\n", ctlr->nwatchdogs);
	PRINTSTAT("Ticks: %ud\n", ctlr->ticks);
	PRINTSTAT("TickIntr: %ud\n", ctlr->tickintr);
	k = ((ctlr->state & Attached) ? "attached" : "not attached");
	PRINTSTAT("Card %s", k);
	k = ((ctlr->state & Power) ? "on" : "off");
	PRINTSTAT(", power %s", k);
	k = ((ctlr->txbusy)? ", txbusy" : "");
	PRINTSTAT("%s\n", k);

	if(ctlr->hascrypt){
		PRINTSTR("Keys: ");
		for (i = 0; i < WNKeys; i++){
			if(ctlr->keys.keys[i].len == 0)
				PRINTSTR("none ");
			else if(SEEKEYS == 0)
				PRINTSTR("set ");
			else
				PRINTSTAT("%s ", ctlr->keys.keys[i].dat);
		}
		PRINTSTR("\n");
	}

	// real card stats
	ilock(ctlr);
	PRINTSTR("\nCard stats: \n");
	PRINTSTAT("Status: %ux\n", csr_ins(ctlr, WR_Sts));
	PRINTSTAT("Event status: %ux\n", csr_ins(ctlr, WR_EvSts));
	i = ltv_ins(ctlr, WTyp_Ptype);
	PRINTSTAT("Port type: %d\n", i);
	PRINTSTAT("Transmit rate: %d\n", ltv_ins(ctlr, WTyp_TxRate));
	PRINTSTAT("Current Transmit rate: %d\n",
		ltv_ins(ctlr, WTyp_CurTxRate));
	PRINTSTAT("Channel: %d\n", ltv_ins(ctlr, WTyp_Chan));
	PRINTSTAT("AP density: %d\n", ltv_ins(ctlr, WTyp_ApDens));
	PRINTSTAT("Promiscuous mode: %d\n", ltv_ins(ctlr, WTyp_Prom));
	if(i == WPTypeAdHoc)
		PRINTSTAT("SSID name: %s\n", ltv_inname(ctlr, WTyp_NetName));
	else {
		Wltv ltv;
		PRINTSTAT("Current name: %s\n", ltv_inname(ctlr, WTyp_CurName));
		ltv.type = WTyp_BaseID;
		ltv.len = 4;
		if(w_inltv(ctlr, &ltv))
			print("#l%d: unable to read base station mac addr\n", ether->ctlrno);
		l += snprint(p+l, READSTR-l, "Base station: %2.2x%2.2x%2.2x%2.2x%2.2x%2.2x\n",
			ltv.addr[0], ltv.addr[1], ltv.addr[2], ltv.addr[3], ltv.addr[4], ltv.addr[5]);
	}
	PRINTSTAT("Net name: %s\n", ltv_inname(ctlr, WTyp_WantName));
	PRINTSTAT("Node name: %s\n", ltv_inname(ctlr, WTyp_NodeName));
	if(ltv_ins(ctlr, WTyp_HasCrypt) == 0)
		PRINTSTR("WEP: not supported\n");
	else {
		if(ltv_ins(ctlr, WTyp_Crypt) == 0)
			PRINTSTR("WEP: disabled\n");
		else{
			PRINTSTR("WEP: enabled\n");
			k = ((ctlr->xclear)? "excluded": "included");
			PRINTSTAT("Clear packets: %s\n", k);
			txid = ltv_ins(ctlr, WTyp_TxKey);
			PRINTSTAT("Transmit key id: %d\n", txid);
		}
	}
	iunlock(ctlr);

	PRINTSTAT("ntxuframes: %lud\n", ctlr->ntxuframes);
	PRINTSTAT("ntxmframes: %lud\n", ctlr->ntxmframes);
	PRINTSTAT("ntxfrags: %lud\n", ctlr->ntxfrags);
	PRINTSTAT("ntxubytes: %lud\n", ctlr->ntxubytes);
	PRINTSTAT("ntxmbytes: %lud\n", ctlr->ntxmbytes);
	PRINTSTAT("ntxdeferred: %lud\n", ctlr->ntxdeferred);
	PRINTSTAT("ntxsretries: %lud\n", ctlr->ntxsretries);
	PRINTSTAT("ntxmultiretries: %lud\n", ctlr->ntxmultiretries);
	PRINTSTAT("ntxretrylimit: %lud\n", ctlr->ntxretrylimit);
	PRINTSTAT("ntxdiscards: %lud\n", ctlr->ntxdiscards);
	PRINTSTAT("nrxuframes: %lud\n", ctlr->nrxuframes);
	PRINTSTAT("nrxmframes: %lud\n", ctlr->nrxmframes);
	PRINTSTAT("nrxfrags: %lud\n", ctlr->nrxfrags);
	PRINTSTAT("nrxubytes: %lud\n", ctlr->nrxubytes);
	PRINTSTAT("nrxmbytes: %lud\n", ctlr->nrxmbytes);
	PRINTSTAT("nrxfcserr: %lud\n", ctlr->nrxfcserr);
	PRINTSTAT("nrxdropnobuf: %lud\n", ctlr->nrxdropnobuf);
	PRINTSTAT("nrxdropnosa: %lud\n", ctlr->nrxdropnosa);
	PRINTSTAT("nrxcantdecrypt: %lud\n", ctlr->nrxcantdecrypt);
	PRINTSTAT("nrxmsgfrag: %lud\n", ctlr->nrxmsgfrag);
	PRINTSTAT("nrxmsgbadfrag: %lud\n", ctlr->nrxmsgbadfrag);
	USED(l);
	n = readstr(offset, a, n, p);
	free(p);
	return n;
}
Example #18
0
File: cpu.c Project: npe9/harvey
/* Invoked with stdin, stdout and stderr connected to the network connection */
void
remoteside(int old)
{
	char user[MaxStr], home[MaxStr], buf[MaxStr], xdir[MaxStr], cmd[MaxStr];
	int i, n, fd, badchdir, gotcmd;

	rfork(RFENVG);
	putenv("service", "cpu");
	fd = 0;

	/* negotiate authentication mechanism */
	n = readstr(fd, cmd, sizeof(cmd));
	if(n < 0)
		fatal(1, "authenticating");
	if(setamalg(cmd) < 0){
		writestr(fd, "unsupported auth method", nil, 0);
		fatal(1, "bad auth method %s", cmd);
	} else
		writestr(fd, "", "", 1);

	fd = (*am->sf)(fd, user);
	if(fd < 0)
		fatal(1, "srvauth");

	/* Set environment values for the user */
	putenv("user", user);
	sprint(home, "/usr/%s", user);
	putenv("home", home);

	/* Now collect invoking cpu's current directory or possibly a command */
	gotcmd = 0;
	if(readstr(fd, xdir, sizeof(xdir)) < 0)
		fatal(1, "dir/cmd");
	if(xdir[0] == '!') {
		strcpy(cmd, &xdir[1]);
		gotcmd = 1;
		if(readstr(fd, xdir, sizeof(xdir)) < 0)
			fatal(1, "dir");
	}

	/* Establish the new process at the current working directory of the
	 * gnot */
	badchdir = 0;
	if(strcmp(xdir, "NO") == 0)
		chdir(home);
	else if(chdir(xdir) < 0) {
		badchdir = 1;
		chdir(home);
	}

	/* Start the gnot serving its namespace */
	writestr(fd, "FS", "FS", 0);
	writestr(fd, "/", "exportfs dir", 0);

	n = read(fd, buf, sizeof(buf));
	if(n != 2 || buf[0] != 'O' || buf[1] != 'K')
		exits("remote tree");

	if(old)
		fd = old9p(fd);

	/* make sure buffers are big by doing fversion explicitly; pick a huge number; other side will trim */
	strcpy(buf, VERSION9P);
	if(fversion(fd, 64*1024, buf, sizeof buf) < 0)
		exits("fversion failed");
	if(mount(fd, -1, "/mnt/term", MCREATE|MREPL, "") < 0)
		exits("mount failed");

	close(fd);

	/* the remote noteproc uses the mount so it must follow it */
	rmtnoteproc();

	for(i = 0; i < 3; i++)
		close(i);

	if(open("/mnt/term/dev/cons", OREAD) != 0)
		exits("open stdin");
	if(open("/mnt/term/dev/cons", OWRITE) != 1)
		exits("open stdout");
	dup(1, 2);

	if(badchdir)
		print("cpu: failed to chdir to '%s'\n", xdir);

	if(gotcmd)
		execl("/bin/rc", "rc", "-lc", cmd, nil);
	else
		execl("/bin/rc", "rc", "-li", nil);
	fatal(1, "exec shell");
}
Example #19
0
static long
consread(Chan *c, void *buf, long n, vlong off)
{
	ulong l;
	Mach *mp;
	char *b, *bp, ch;
	char tmp[256];		/* must be >= 18*NUMSIZE (Qswap) */
	int i, k, id, send;
	vlong offset = off;

	if(n <= 0)
		return n;

	switch((ulong)c->qid.path){
	case Qdir:
		return devdirread(c, buf, n, consdir, nelem(consdir), devgen);

	case Qcons:
		qlock(&kbd.lk);
		if(waserror()) {
			qunlock(&kbd.lk);
			nexterror();
		}
		while(!qcanread(lineq)){
			if(qread(kbdq, &ch, 1) == 0)
				continue;
			send = 0;
			if(ch == 0){
				/* flush output on rawoff -> rawon */
				if(kbd.x > 0)
					send = !qcanread(kbdq);
			}else if(kbd.raw){
				kbd.line[kbd.x++] = ch;
				send = !qcanread(kbdq);
			}else{
				switch(ch){
				case '\b':
					if(kbd.x > 0)
						kbd.x--;
					break;
				case 0x15:	/* ^U */
					kbd.x = 0;
					break;
				case '\n':
				case 0x04:	/* ^D */
					send = 1;
				default:
					if(ch != 0x04)
						kbd.line[kbd.x++] = ch;
					break;
				}
			}
			if(send || kbd.x == sizeof kbd.line){
				qwrite(lineq, kbd.line, kbd.x);
				kbd.x = 0;
			}
		}
		n = qread(lineq, buf, n);
		qunlock(&kbd.lk);
		poperror();
		return n;

	case Qcputime:
		k = offset;
		if(k >= 6*NUMSIZE)
			return 0;
		if(k+n > 6*NUMSIZE)
			n = 6*NUMSIZE - k;
		/* easiest to format in a separate buffer and copy out */
		for(i=0; i<6 && NUMSIZE*i<k+n; i++){
			l = up->time[i];
			if(i == TReal)
				l = msec() - l;
			l = TK2MS(l);
			readnum(0, tmp+NUMSIZE*i, NUMSIZE, l, NUMSIZE);
		}
		memmove(buf, tmp+k, n);
		return n;

	case Qkmesg:
		/*
		 * This is unlocked to avoid tying up a process
		 * that's writing to the buffer.  kmesg.n never 
		 * gets smaller, so worst case the reader will
		 * see a slurred buffer.
		 */
		if(off >= kmesg.n)
			n = 0;
		else{
			if(off+n > kmesg.n)
				n = kmesg.n - off;
			memmove(buf, kmesg.buf+off, n);
		}
		return n;
		
	case Qkprint:
		return qread(kprintoq, buf, n);

	case Qpgrpid:
		return readnum((ulong)offset, buf, n, up->pgrp->pgrpid, NUMSIZE);

	case Qpid:
		return readnum((ulong)offset, buf, n, up->pid, NUMSIZE);

	case Qppid:
		return readnum((ulong)offset, buf, n, up->parentpid, NUMSIZE);

	case Qtime:
		return readtime((ulong)offset, buf, n);

	case Qbintime:
		return readbintime(buf, n);

	case Qhostowner:
		return readstr((ulong)offset, buf, n, eve);

	case Qhostdomain:
		return readstr((ulong)offset, buf, n, hostdomain);

	case Quser:
		return readstr((ulong)offset, buf, n, up->user);

	case Qnull:
		return 0;

	case Qsysstat:
		b = smalloc(conf.nmach*(NUMSIZE*11+1) + 1);	/* +1 for NUL */
		bp = b;
		for(id = 0; id < 32; id++) {
			if(active.machs & (1<<id)) {
				mp = MACHP(id);
				readnum(0, bp, NUMSIZE, id, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE, mp->cs, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE, mp->intr, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE, mp->syscall, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE, mp->pfault, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE, mp->tlbfault, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE, mp->tlbpurge, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE, mp->load, NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE,
					(mp->perf.avg_inidle*100)/mp->perf.period,
					NUMSIZE);
				bp += NUMSIZE;
				readnum(0, bp, NUMSIZE,
					(mp->perf.avg_inintr*100)/mp->perf.period,
					NUMSIZE);
				bp += NUMSIZE;
				*bp++ = '\n';
			}
		}
		if(waserror()){
			free(b);
			nexterror();
		}
		n = readstr((ulong)offset, buf, n, b);
		free(b);
		poperror();
		return n;

	case Qswap:
		tmp[0] = 0;

		return readstr((ulong)offset, buf, n, tmp);

	case Qsysname:
		if(sysname == nil)
			return 0;
		return readstr((ulong)offset, buf, n, sysname);

	case Qrandom:
		return randomread(buf, n);

	case Qdrivers:
		b = malloc(READSTR);
		if(b == nil)
			error(Enomem);
		n = 0;
		for(i = 0; devtab[i] != nil; i++)
			n += snprint(b+n, READSTR-n, "#%C %s\n", devtab[i]->dc,  devtab[i]->name);
		if(waserror()){
			free(b);
			nexterror();
		}
		n = readstr((ulong)offset, buf, n, b);
		free(b);
		poperror();
		return n;

	case Qzero:
		memset(buf, 0, n);
		return n;

	case Qosversion:
		snprint(tmp, sizeof tmp, "2000");
		n = readstr((ulong)offset, buf, n, tmp);
		return n;

	default:
		print("consread 0x%llux\n", c->qid.path);
		error(Egreg);
	}
	return -1;		/* never reached */
}
Example #20
0
int
dnsproc(int nfd)
{
	int		 rc, cc;
	char		*look, *last;
	struct addr	 v[MAX_SERVERS_DNS];
	long		 lval;
	size_t		 i;
	ssize_t		 vsz;
	enum dnsop	 op;

	rc = 0;
	look = last = NULL;
	vsz = 0;

	/*
	 * Why don't we chroot() here?
	 * On OpenBSD, the pledge(2) takes care of our constraining the
	 * environment to DNS resolution only, so the chroot(2) is
	 * unnecessary.
	 * On Mac OS X, we can't chroot(2): we'd need to have an mdns
	 * responder thing in each jail.
	 * On Linux, forget it.  getaddrinfo(2) pulls on all sorts of
	 * mystery meat.
	 */

	if ( ! sandbox_before())
		goto out;
	else if ( ! dropprivs())
		goto out;
	else if ( ! sandbox_after()) 
		goto out;

	/*
	 * This is simple: just loop on a request operation, and each
	 * time we write back zero or more entries.
	 * Also do a simple trick and cache the last lookup.
	 */

	for (;;) {
		op = DNS__MAX;
		if (0 == (lval = readop(nfd, COMM_DNS)))
			op = DNS_STOP;
		else if (DNS_LOOKUP == lval)
			op = lval;

		if (DNS__MAX == op) {
			warnx("unknown operation from netproc");
			goto out;
		} else if (DNS_STOP == op)
			break;

		if (NULL == (look = readstr(nfd, COMM_DNSQ)))
			goto out;

		/* 
		 * Check if we're asked to repeat the lookup.
		 * If not, request it from host_dns().
		 */

		if (NULL == last || strcmp(look, last)) {
			if ((vsz = host_dns(look, v)) < 0)
				goto out;

			free(last);
			last = look;
			look = NULL;
		} else {
			doddbg("%s: cached", look);
			free(look);
			look = NULL;
		}

		if (0 == (cc = writeop(nfd, COMM_DNSLEN, vsz)))
			break;
		else if (cc < 0)
			goto out;
		for (i = 0; i < (size_t)vsz; i++) { 
			if (writeop(nfd, COMM_DNSF, v[i].family) <= 0)
				goto out;
			if (writestr(nfd, COMM_DNSA, v[i].ip) <= 0)
				goto out;
		}
	}

	rc = 1;
out:
	close(nfd);
	free(look);
	free(last);
	return(rc);
}
Example #21
0
File: devprog.c Project: 8l/inferno
static long
progread(Chan *c, void *va, long n, vlong offset)
{
	int i;
	Prog *p;
	Osenv *o;
	Mntwalk *mw;
	ulong grpid;
	char *a = va;
	Progctl *ctl;
	char mbuf[64], timebuf[12];
	char flag[10];

	if(c->qid.type & QTDIR)
		return devdirread(c, a, n, 0, 0, proggen);

	switch(QID(c->qid)){
	case Qdbgctl:
		ctl = c->aux;
		return qread(ctl->q, va, n);
	case Qstatus:
		acquire();
		p = progpid(PID(c->qid));
		if(p == nil || p->state == Pexiting || p->R.M == H) {
			release();
			snprint(up->genbuf, sizeof(up->genbuf), "%8lud %8d %10s %s %10s %5dK %s",
				PID(c->qid),
				0,
				eve,
				progtime(0, timebuf, timebuf+sizeof(timebuf)),
				progstate[Pexiting],
				0,
				"[$Sys]");
			return readstr(offset, va, n, up->genbuf);
		}
		modstatus(&p->R, mbuf, sizeof(mbuf));
		o = p->osenv;
		snprint(up->genbuf, sizeof(up->genbuf), "%8d %8d %10s %s %10s %5dK %s",
			p->pid,
			p->group!=nil? p->group->id: 0,
			o->user,
			progtime(p->ticks, timebuf, timebuf+sizeof(timebuf)),
			progstate[p->state],
			progsize(p),
			mbuf);
		release();
		return readstr(offset, va, n, up->genbuf);
	case Qwait:
		return qread(c->aux, va, n);
	case Qns:
		acquire();
		if(waserror()){
			release();
			nexterror();
		}
		p = progpid(PID(c->qid));
		if(p == nil)
			error(Ethread);
		mw = c->aux;
		if(mw->cddone){
			poperror();
			release();
			return 0;
		}
		o = p->osenv;
		mntscan(mw, o->pgrp);
		if(mw->mh == 0) {
			mw->cddone = 1;
			i = snprint(a, n, "cd %s\n", o->pgrp->dot->name->s);
			poperror();
			release();
			return i;
		}
		int2flag(mw->cm->mflag, flag);
		if(strcmp(mw->cm->to->name->s, "#M") == 0){
			i = snprint(a, n, "mount %s %s %s %s\n", flag,
				mw->cm->to->mchan->name->s,
				mw->mh->from->name->s, mw->cm->spec? mw->cm->spec : "");
		}else
			i = snprint(a, n, "bind %s %s %s\n", flag,
				mw->cm->to->name->s, mw->mh->from->name->s);
		poperror();
		release();
		return i;
	case Qnsgrp:
		acquire();
		p = progpid(PID(c->qid));
		if(p == nil) {
			release();
			error(Ethread);
		}
		grpid = ((Osenv *)p->osenv)->pgrp->pgrpid;
		release();
		return readnum(offset, va, n, grpid, NUMSIZE);
	case Qpgrp:
		acquire();
		p = progpid(PID(c->qid));
		if(p == nil) {
			release();
			error(Ethread);
		}
		grpid = p->group!=nil? p->group->id: 0;
		release();
		return readnum(offset, va, n, grpid, NUMSIZE);
	case Qstack:
		acquire();
		p = progpid(PID(c->qid));
		if(p == nil || p->state == Pexiting) {
			release();
			error(Ethread);
		}
		if(p->state == Pready) {
			release();
			error(Estopped);
		}
		n = progstack(&p->R, p->state, va, n, offset);
		release();
		return n;
	case Qheap:
		acquire();
		if(waserror()){
			release();
			nexterror();
		}
		n = progheap(c->aux, va, n, offset);
		if(n == -1)
			error(Emisalign);
		poperror();
		release();
		return n;
	case Qfd:
		acquire();
		if(waserror()) {
			release();
			nexterror();
		}
		p = progpid(PID(c->qid));
		if(p == nil)
			error(Ethread);
		o = p->osenv;
		n = progfds(o, va, n, offset);
		poperror();
		release();
		return n;
	case Qexception:
		acquire();
		p = progpid(PID(c->qid));
		if(p == nil) {
			release();
			error(Ethread);
		}
		if(p->exstr == nil)
			up->genbuf[0] = 0;
		else
			snprint(up->genbuf, sizeof(up->genbuf), p->exstr);
		release();
		return readstr(offset, va, n, up->genbuf);
	}
	error(Egreg);
	return 0;
}
Example #22
0
// loads the world from a text file.
void SetupWorld() 
{
#define TRI 4
	float square[TRI][3][5] = {
	// A1
		{
			{ -2.0, 1.0, -2.0,0.0,1.0 },
			{ -2.0, 0.0, -2.0,0.0,0.0 },
			{ -0.5, 0.0, -2.0,1.5,0.0 },
		},
		{
			{ -2.0, 1.0, -2.0,0.0,1.0 },
			{ -0.5, 1.0, -2.0,1.5,1.0 },
			{ -0.5, 0.0, -2.0,1.5,0.0 },
		},
	// A2
		{
			{  2.0, 1.0, -2.0,2.0,1.0 },
			{  2.0, 0.0, -2.0,2.0,0.0 },
			{  0.5, 0.0, -2.0,0.5,0.0 },
		},
		{
			{  2.0, 1.0, -2.0,2.0,1.0 },
			{  0.5, 1.0, -2.0,0.5,1.0 },
			{  0.5, 0.0, -2.0,0.5,0.0 },
		},

	};
	sector1.numtriangles = TRI;
	sector1.triangle = (TRIANGLE *) malloc(sizeof(TRIANGLE)*sector1.numtriangles);

	int i, t;
	for (t = 0; t < TRI; t++) {
		for (i = 0; i < 3; i++) {
			sector1.triangle[t].vertex[i].x = square[t][i][0];
			sector1.triangle[t].vertex[i].y = square[t][i][1];
			sector1.triangle[t].vertex[i].z = square[t][i][2];
			sector1.triangle[t].vertex[i].u = square[t][i][3];
			sector1.triangle[t].vertex[i].v = square[t][i][4];
		}
	}

	//return;
	float x, y, z, u, v;
	int vert;
	int numtriangles;
	FILE *filein;        // file to load the world from
	char oneline[255];

	filein = fopen("Data/world.txt", "rt");

	readstr(filein, oneline);
	sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles);

	sector1.numtriangles = numtriangles;
	sector1.triangle = (TRIANGLE *) malloc(sizeof(TRIANGLE)*numtriangles);

	for (loop = 0; loop < numtriangles; loop++) {
		for (vert = 0; vert < 3; vert++) {
			readstr(filein,oneline);
			sscanf(oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v);
			sector1.triangle[loop].vertex[vert].x = x;
			sector1.triangle[loop].vertex[vert].y = y;
			sector1.triangle[loop].vertex[vert].z = z;
			sector1.triangle[loop].vertex[vert].u = u;
			sector1.triangle[loop].vertex[vert].v = v;
		}
	}

	fclose(filein);
	return;
}
Example #23
0
static long
mouseread(Chan *c, void *va, long n, vlong off)
{
	char buf[1+4*12+1], *s;
	uchar *p;
	ulong offset = off;
	Mousestate m;
	int b;

	p = va;
	switch((ulong)c->qid.path){
	case Qdir:
		return devdirread(c, va, n, mousedir, nelem(mousedir), mousedevgen);

	case Qcursor:
		if(offset != 0)
			return 0;
		if(n < 2*4+2*2*16)
			error(Eshort);
		n = 2*4+2*2*16;
		lock(&cursor.lk);
		BPLONG(p+0, curs.offset.x);
		BPLONG(p+4, curs.offset.y);
		memmove(p+8, curs.clr, 2*16);
		memmove(p+40, curs.set, 2*16);
		unlock(&cursor.lk);
		return n;

	case Qmouse:
		while(mousechanged(0) == 0)
			sleep(&mouse.r, mousechanged, 0);

		mouse.qfull = 0;
		mousetime = seconds();

		/*
		 * No lock of the indices is necessary here, because ri is only
		 * updated by us, and there is only one mouse reader
		 * at a time.  I suppose that more than one process
		 * could try to read the fd at one time, but such behavior
		 * is degenerate and already violates the calling
		 * conventions for sleep above.
		 */
		if(mouse.ri != mouse.wi) {
			m = mouse.queue[mouse.ri];
			if(++mouse.ri == nelem(mouse.queue))
				mouse.ri = 0;
		} else {
			while(!canlock(&cursor.lk))
				tsleep(&up->sleep, return0, 0, TK2MS(1));

			m = mouse.mstate;
			unlock(&cursor.lk);
		}

		b = buttonmap[m.buttons&7];
		/* put buttons 4 and 5 back in */
		b |= m.buttons & (3<<3);
		if (scrollswap){
			if (b == 8)
				b = 16;
			else if (b == 16)
				b = 8;
		}
		sprint(buf, "m%11d %11d %11d %11lud ",
			m.xy.x, m.xy.y,
			b,
			m.msec);
		mouse.lastcounter = m.counter;
		if(n > 1+4*12)
			n = 1+4*12;
		if(mouse.lastresize != mouse.resize){
			mouse.lastresize = mouse.resize;
			buf[0] = 'r';
		}
		memmove(va, buf, n);
		return n;
	
	case Qsnarf:
		if(offset == 0){
			s = getsnarf();
			if(c->aux)
				free(c->aux);
			c->aux = s;
		}
		if(c->aux == nil)
			return 0;
		return readstr(offset, va, n, c->aux);
	}
	return 0;
}
Example #24
0
static void
xread(Req *r)
{
	int i, size, height, ascent;
	vlong path;
	Fmt fmt;
	XFont *f;
	char *data;
	Memsubfont *sf;
	Memimage *m;
	
	path = r->fid->qid.path;
	switch(QTYPE(path)) {
	case Qroot:
		dirread9p(r, rootgen, nil);
		break;
	case Qfontdir:
		dirread9p(r, fontgen, r->fid);
		break;
	case Qsizedir:
		dirread9p(r, sizegen, r->fid);
		break;
	case Qfontfile:
		fmtstrinit(&fmt);
		f = &xfont[QFONT(path)];
		load(f);
		if(f->unit == 0 && f->loadheight == nil) {
			readstr(r, "font missing\n");
			break;
		}
		height = 0;
		ascent = 0;
		if(f->unit > 0) {
			height = f->height * (int)QSIZE(path)/f->unit + 0.99999999;
			ascent = height - (int)(-f->originy * (int)QSIZE(path)/f->unit + 0.99999999);
		}
		if(f->loadheight != nil)
			f->loadheight(f, QSIZE(path), &height, &ascent);
		fmtprint(&fmt, "%11d %11d\n", height, ascent);
		for(i=0; i<nelem(f->range); i++) {
			if(f->range[i] == 0)
				continue;
			fmtprint(&fmt, "0x%04x 0x%04x x%04x.bit\n", i*SubfontSize, ((i+1)*SubfontSize) - 1, i*SubfontSize);
		}
		data = fmtstrflush(&fmt);
		readstr(r, data);
		free(data);
		break;
	case Qsubfontfile:
		f = &xfont[QFONT(path)];
		load(f);
		if(r->fid->aux == nil) {
			r->fid->aux = mksubfont(f, f->name, QRANGE(path)*SubfontSize, ((QRANGE(path)+1)*SubfontSize)-1, QSIZE(path), QANTIALIAS(path));
			if(r->fid->aux == nil) {
				responderrstr(r);
				return;
			}
		}
		sf = r->fid->aux;
		m = sf->bits;
		if(r->ifcall.offset < 5*12) {
			char *chan;
			if(QANTIALIAS(path))
				chan = "k8";
			else
				chan = "k1";
			data = smprint("%11s %11d %11d %11d %11d ", chan, m->r.min.x, m->r.min.y, m->r.max.x, m->r.max.y);
			readstr(r, data);
			free(data);
			break;
		}
		r->ifcall.offset -= 5*12;
		size = bytesperline(m->r, chantodepth(m->chan)) * Dy(m->r);
		if(r->ifcall.offset < size) {
			readbuf(r, byteaddr(m, m->r.min), size);
			break;
		}
		r->ifcall.offset -= size;
		data = emalloc9p(3*12+6*(sf->n+1));
		sprint(data, "%11d %11d %11d ", sf->n, sf->height, sf->ascent);
		packinfo(sf->info, (uchar*)data+3*12, sf->n);
		readbuf(r, data, 3*12+6*(sf->n+1));
		free(data);
		break;
	}
	respond(r, nil);
}
Example #25
0
static long
sdread(Chan *c, void *a, long n, vlong off)
{
	char *p, *e, *buf;
	SDev *sdev;
	SDpart *pp;
	SDreq *r;
	SDunit *unit;
	ulong offset;
	int i, l, m, status;

	offset = off;
	switch(TYPE(c->qid)){
	default:
		error(Eperm);
	case Qtopctl:
		m = 64*1024;	/* room for register dumps */
		p = buf = smalloc(m);
		e = p + m;
		qlock(&devslock);
		for(i = 0; i < nelem(devs); i++){
			sdev = devs[i];
			if(sdev && sdev->ifc->rtopctl)
				p = sdev->ifc->rtopctl(sdev, p, e);
			else if(sdev)
				p = deftopctl(sdev, p, e);
		}
		qunlock(&devslock);
		n = readstr(off, a, n, buf);
		free(buf);
		return n;

	case Qtopdir:
	case Qunitdir:
		return devdirread(c, a, n, 0, 0, sdgen);

	case Qctl:
		sdev = sdgetdev(DEV(c->qid));
		if(sdev == nil)
			error(Enonexist);

		unit = sdev->unit[UNIT(c->qid)];
		m = 16*1024;	/* room for register dumps */
		p = smalloc(m);
		l = snprint(p, m, "inquiry %.48s\n",
			(char*)unit->inquiry+8);
		qlock(&unit->ctl);
		/*
		 * If there's a device specific routine it must
		 * provide all information pertaining to night geometry
		 * and the garscadden trains.
		 */
		if(unit->dev->ifc->rctl)
			l += unit->dev->ifc->rctl(unit, p+l, m-l);
		if(unit->sectors == 0)
			sdinitpart(unit);
		if(unit->sectors){
			if(unit->dev->ifc->rctl == nil)
				l += snprint(p+l, m-l,
					"geometry %llud %lud\n",
					unit->sectors, unit->secsize);
			pp = unit->part;
			for(i = 0; i < unit->npart; i++){
				if(pp->valid)
					l += snprint(p+l, m-l,
						"part %s %llud %llud\n",
						pp->name, pp->start, pp->end);
				pp++;
			}
		}
		qunlock(&unit->ctl);
		decref(&sdev->r);
		l = readstr(offset, a, n, p);
		free(p);
		return l;

	case Qraw:
		sdev = sdgetdev(DEV(c->qid));
		if(sdev == nil)
			error(Enonexist);

		unit = sdev->unit[UNIT(c->qid)];
		qlock(&unit->raw);
		if(waserror()){
			qunlock(&unit->raw);
			decref(&sdev->r);
			nexterror();
		}
		if(unit->state == Rawdata){
			unit->state = Rawstatus;
			r = unit->req;
			i = sdrio(r, a, n);
		}
		else if(unit->state == Rawstatus){
			r = unit->req;
			unit->req = nil;
			unit->state = Rawcmd;
			status = r->status;
			if(r->proto == SData){
				p = a;
				i = 16 + Ahdrsz;
				if(n < i)
					i = n;
				if(i > 0)
					p[0] = status;
				if(i > Ahdrsz)
					memmove(p + Ahdrsz, r->cmd, i - Ahdrsz);
			}else
				i = readnum(0, a, n, status, NUMSIZE);
			free(r);
		} else
			i = 0;
		poperror();
		qunlock(&unit->raw);
		decref(&sdev->r);
		return i;

	case Qpart:
		return sdbio(c, 0, a, n, off);
	case Qextra:
		return extrarw(0, c, a, n, off);
	}
}
Example #26
0
static long	 
flashread(Chan *c, void *buf, long n, vlong offset)
{
	Flash *f;
	Flashpart *fp;
	Flashregion *r;
	int i;
	ulong start, end;
	char *s, *o;

	if(c->qid.type & QTDIR)
		return devdirread(c, buf, n, nil, 0, flashgen);

	f = flash.card[c->dev];
	fp = &f->part[PART(c->qid.path)];
	if(fp->name == nil)
		error(Egreg);
	switch(TYPE(c->qid.path)){
	case Qdata:
		offset += fp->start;
		if(offset >= fp->end)
			return 0;
		if(offset+n > fp->end)
			n = fp->end - offset;
		n = readflash(f, buf, offset, n);
		if(n < 0)
			error(Eio);
		return n;
	case Qctl:
		s = malloc(READSTR);
		if(s == nil)
			error(Enomem);
		if(waserror()){
			free(s);
			nexterror();
		}
		o = seprint(s, s+READSTR, "%#2.2ux %#4.4ux %d %q\n",
			f->id, f->devid, f->width, f->sort!=nil? f->sort: "nor");
		for(i=0; i<f->nr; i++){
			r = &f->regions[i];
			if(r->start < fp->end && fp->start < r->end){
				start = r->start;
				if(fp->start > start)
					start = fp->start;
				end = r->end;
				if(fp->end < end)
					end = fp->end;
				o = seprint(o, s+READSTR, "%#8.8lux %#8.8lux %#8.8lux",
					start, end, r->erasesize);
				if(r->pagesize)
					o = seprint(o, s+READSTR, " %#8.8lux",
						r->pagesize);
				o = seprint(o, s+READSTR, "\n");
			}
		}
		n = readstr(offset, buf, n, s);
		poperror();
		free(s);
		return n;
	}
	error(Egreg);
	return 0;		/* not reached */
}
Example #27
0
File: devcons.c Project: 8l/inferno
static long
consread(Chan *c, void *va, long n, vlong offset)
{
	int send;
	char *p, buf[64], ch;
	FILE * battery;
	FILE * brightness;
	int size;

	if(c->qid.type & QTDIR)
		return devdirread(c, va, n, contab, nelem(contab), devgen);

	switch((ulong)c->qid.path) {
	default:
		error(Egreg);

	case Qsysctl:
		return readstr(offset, va, n, VERSION);

	case Qsysname:
		if(ossysname == nil)
			return 0;
		return readstr(offset, va, n, ossysname);

	case Qrandom:
		return randomread(va, n);

	case Qnotquiterandom:
		genrandom(va, n);
		return n;

	case Qhostowner:
		return readstr(offset, va, n, eve);

	case Qhoststdin:
		return read(0, va, n);	/* should be pread */

	case Quser:
		return readstr(offset, va, n, up->env->user);

	case Qjit:
		snprint(buf, sizeof(buf), "%d", cflag);
		return readstr(offset, va, n, buf);

	case Qtime:
		snprint(buf, sizeof(buf), "%.lld", timeoffset + osusectime());
		return readstr(offset, va, n, buf);

	case Qdrivers:
		return devtabread(c, va, n, offset);

	case Qmemory:
		return poolread(va, n, offset);

	case Qnull:
		return 0;

	case Qmsec:
		return readnum(offset, va, n, osmillisec(), NUMSIZE);

	case Qcons:
		qlock(&kbd.q);
		if(waserror()){
			qunlock(&kbd.q);
			nexterror();
		}

		if(dflag)
			error(Enonexist);

		while(!qcanread(lineq)) {
			if(qread(kbdq, &ch, 1) == 0)
				continue;
			send = 0;
			if(ch == 0){
				/* flush output on rawoff -> rawon */
				if(kbd.x > 0)
					send = !qcanread(kbdq);
			}else if(kbd.raw){
				kbd.line[kbd.x++] = ch;
				send = !qcanread(kbdq);
			}else{
				switch(ch){
				case '\b':
					if(kbd.x)
						kbd.x--;
					break;
				case 0x15:
					kbd.x = 0;
					break;
				case 0x04:
					send = 1;
					break;
				case '\n':
					send = 1;
				default:
					kbd.line[kbd.x++] = ch;
					break;
				}
			}
			if(send || kbd.x == sizeof kbd.line){
				qwrite(lineq, kbd.line, kbd.x);
				kbd.x = 0;
			}
		}
		n = qread(lineq, va, n);
		qunlock(&kbd.q);
		poperror();
		return n;

	case Qscancode:
		if(offset == 0)
			return readstr(0, va, n, gkscanid);
		return qread(gkscanq, va, n);

	case Qkeyboard:
		return qread(gkbdq, va, n);

	case Qevents:
		return qread(c->aux, va, n);

	case Qkprint:
		rlock(&kprintq.l);
		if(waserror()){
			runlock(&kprintq.l);
			nexterror();
		}
		n = qread(kprintq.q, va, n);
		poperror();
		runlock(&kprintq.l);
		return n;
	case Qbattery:
		if(type == 's')
			battery = fopen("/sys/class/power_supply/battery/capacity", "r");
		else if(type == 'c')
			battery = fopen("/sys/class/power_supply/max17042-0/capacity", "r");
		else
			battery = fopen("/sys/class/power_supply/battery/capacity", "r");
		size = fread(buf, 1, sizeof(buf), battery);
		fclose(battery);
		buf[size - 1] = '\0';
		return readstr(offset, va, n, buf);
	case Qtype:
		if(type == 's')
			strncpy(buf, "nexus s", sizeof(buf));
		else if(type == 'c')
			strncpy(buf, "nook color", sizeof(buf));
		else if(type == 'e')
			strncpy(buf, "emulator", sizeof(buf));
		else
			strncpy(buf, "nexus s", sizeof(buf));
		return readstr(offset, va, n, buf);
	case Qbrightness:
		if(type == 'c')
			brightness = fopen("/sys/devices/platform/omap_pwm_led/leds/lcd-backlight/brightness", "r");
		else if(type == 'e')
			return;
		else
			brightness = fopen("/sys/class/backlight/s5p_bl/brightness", "r");
		size = fread(buf, 1, sizeof(buf), brightness);
		fclose(brightness);
		buf[size - 1] = '\0';
		return readstr(offset, va, n, buf);
	}
}