Example #1
0
void parseline(char *line, const ssize_t linenum)
{
    char *past_date_p;
    size_t ret;
    static char *outbuf;
    static size_t outbuf_len = OUTBUF_LEN_MIN;

    if (!outbuf)
        if ((outbuf = malloc(outbuf_len)) == NULL)
            err(EX_OSERR, "malloc() failed to create output buffer");

    while (*line != '\0') {
        if (*line == '\n') {
            putchar('\n');
            break;
        }

        if ((past_date_p = strptime(line, Flag_Input_Format, &When)) != NULL) {
            /* Uhh so yeah about that %s thing on Mac OS X. Guard for it.
             * This was reported in Apple Bug 15753871 maaaaaany months ago but
             * hey I guess there's more important things to deal with? */
            if (past_date_p - line < 1)
                errx(EX_SOFTWARE, "error: zero-width timestamp parse");

            if (!Flag_Output_Format) {
                printf("%ld", (long) mktime(&When));
            } else {
                while ((ret =
                        strftime(outbuf, outbuf_len, Flag_Output_Format, &When))
                       == 0) {
                    outbuf_len <<= 1;
                    if (outbuf_len > OUTBUF_LEN_MAX)
                        errx(EX_SOFTWARE,
                             "strftime() output too large for buffer %d at %s:%ld",
                             OUTBUF_LEN_MAX, File_Name, linenum);
                    if ((outbuf = realloc(outbuf, outbuf_len)) == NULL)
                        err(EX_OSERR,
                            "realloc() could not resize output buffer to %ld",
                            outbuf_len);
                }
                fwrite(outbuf, ret, (size_t) 1, stdout);
            }

            if (!Flag_Global) {
                if (Flag_Suppress) {
                    putchar('\n');
                } else {
                    printf("%s", past_date_p);
                }

                /* no global search means we're done with the line */
                break;

            } else {
                /* spacer necessary between just the strftimes */
                if (Flag_Suppress)
                    putchar(' ');
            }

            line = past_date_p;
        } else {
            /* charwise until strptime finds something, or not */
            if (!Flag_Suppress) {
                putchar(*line);
            }
            line++;
        }
    }
}
Example #2
0
int
main(int argc, char **argv)
{
	struct command *cmds;
	char objformat[32];
	char *path, *chunk;
	char *cmd, *newcmd = NULL;
	const char *objformat_path;
	const char *ccver;
	const char *buver;
	const char *env_value = NULL;
	const char *base_path = NULL;
	int use_objformat = 0;

	if (getobjformat(objformat, sizeof objformat, &argc, argv) == -1)
		errx(1, "Invalid object format");

	/*
	 * Get the last path element of the program name being executed
	 */
	cmd = strrchr(argv[0], '/');
	if (cmd != NULL)
		cmd++;
	else
		cmd = argv[0];

	for (cmds = commands; cmds < &commands[NELEM(commands) - 1]; ++cmds) {
		if (strcmp(cmd, cmds->cmd) == 0)
			break;
	}

	if ((ccver = getenv("CCVER")) == NULL || ccver[0] == 0)
		ccver = CCVER_DEFAULT;
	if ((buver = getenv("BINUTILSVER")) == NULL) {
		buver = BINUTILSVER_DEFAULT;
	}

	if (cmds) {
		switch (cmds->type) {
		case COMPILER:
			base_path = "/usr/libexec";
			use_objformat = 0;
			env_value = ccver;
			break;
		case BINUTILS:
			base_path = "/usr/libexec";
			use_objformat = 1;
			env_value = buver;
			break;
		case OBJFORMAT:
			break;
		default:
			errx(1, "unknown command type");
			break;
		}
	}

	/*
	 * The objformat command itself doesn't need another exec
	 */
	if (cmds->type == OBJFORMAT) {
		if (argc != 1) {
			fprintf(stderr, "Usage: objformat\n");
			exit(1);
		}

		printf("%s\n", objformat);
		exit(0);
	}

	/*
	 * make buildworld glue and CCVER overrides.
	 */
	objformat_path = getenv("OBJFORMAT_PATH");
	if (objformat_path == NULL)
		objformat_path = OBJFORMAT_PATH_DEFAULT;

again:
	path = strdup(objformat_path);

	if (setenv("OBJFORMAT", objformat, 1) == -1)
		err(1, "setenv: cannot set OBJFORMAT=%s", objformat);

	/*
	 * objformat_path could be sequence of colon-separated paths.
	 */
	while ((chunk = strsep(&path, ":")) != NULL) {
		if (newcmd != NULL) {
			free(newcmd);
			newcmd = NULL;
		}
		if (use_objformat) {
			asprintf(&newcmd, "%s%s/%s/%s/%s",
				chunk, base_path, env_value, objformat, cmd);
		} else {
			asprintf(&newcmd, "%s%s/%s/%s",
				chunk, base_path, env_value, cmd);
		}
		if (newcmd == NULL)
			err(1, "cannot allocate memory");

		argv[0] = newcmd;
		execv(newcmd, argv);
	}

	/*
	 * Fallback:  if we're searching for a compiler, but didn't
	 * find any, try again using the custom compiler driver.
	 */
	if (cmds && cmds->type == COMPILER &&
	    strcmp(env_value, "custom") != 0) {
		env_value = "custom";
		goto again;
	}

	if (use_objformat) {
		err(1, "in path [%s]%s/%s/%s/%s",
			objformat_path, base_path, env_value, objformat, cmd);
	} else {
		err(1, "in path [%s]%s/%s/%s",
			objformat_path, base_path, env_value, cmd);
	}
}
Example #3
0
// Turns LLL tree into tree of code fragments
programData opcodeify(Node node,
                      programAux aux=Aux(),
                      programVerticalAux vaux=verticalAux()) {
    std::string symb = "_"+mkUniqueToken();
    Metadata m = node.metadata;
    // Numbers
    if (node.type == TOKEN) {
        return pd(aux, nodeToNumeric(node), 1);
    }
    else if (node.val == "ref" || node.val == "get" || node.val == "set") {
        std::string varname = node.args[0].val;
        // Determine reference to variable
        if (!aux.vars.count(node.args[0].val)) {
            aux.vars[node.args[0].val] = utd(aux.nextVarMem);
            aux.nextVarMem += 32;
        }
        Node varNode = tkn(aux.vars[varname], m);
        //std::cerr << varname << " " << printSimple(varNode) << "\n";
        // Set variable
        if (node.val == "set") {
            programData sub = opcodeify(node.args[1], aux, vaux);
            if (!sub.outs)
                err("Value to set variable must have nonzero arity!", m);
            // What if we are setting a stack variable?
            if (vaux.dupvars.count(node.args[0].val)) {
                int h = vaux.height - vaux.dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                Node nodelist[] = {
                    sub.code,
                    token("SWAP"+unsignedToDecimal(h), m),
                    token("POP", m)
                };
                return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
            }
            // Setting a memory variable
            else {
                Node nodelist[] = {
                    sub.code,
                    varNode,
                    token("MSTORE", m),
                };
                return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
            }
        }
        // Get variable
        else if (node.val == "get") {
            // Getting a stack variable
            if (vaux.dupvars.count(node.args[0].val)) {
                 int h = vaux.height - vaux.dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                return pd(aux, token("DUP"+unsignedToDecimal(h)), 1);                   
            }
            // Getting a memory variable
            else {
                Node nodelist[] = 
                     { varNode, token("MLOAD", m) };
                return pd(aux, multiToken(nodelist, 2, m), 1);
            }
        }
        // Refer variable
        else if (node.val == "ref") {
            if (vaux.dupvars.count(node.args[0].val))
                err("Cannot ref stack variable!", m);
            return pd(aux, varNode, 1);
        }
    }
    // Comments do nothing
    else if (node.val == "comment") {
        return pd(aux, astnode("_", m), 0);
    }
    // Custom operation sequence
    // eg. (ops bytez id msize swap1 msize add 0 swap1 mstore) == alloc
    if (node.val == "ops") {
        std::vector<Node>  subs2;
        int depth = 0;
        for (unsigned i = 0; i < node.args.size(); i++) {
            std::string op = upperCase(node.args[i].val);
            if (node.args[i].type == ASTNODE || opinputs(op) == -1) {
                programVerticalAux vaux2 = vaux;
                vaux2.height = vaux.height - i - 1 + node.args.size();
                programData sub = opcodeify(node.args[i], aux, vaux2);
                aux = sub.aux;
                depth += sub.outs;
                subs2.push_back(sub.code);
            }
            else {
                subs2.push_back(token(op, m));
                depth += opoutputs(op) - opinputs(op);
            }
        }
        if (depth < 0 || depth > 1) err("Stack depth mismatch", m);
        return pd(aux, astnode("_", subs2, m), 0);
    }
    // Code blocks
    if (node.val == "lll" && node.args.size() == 2) {
        if (node.args[1].val != "0") aux.allocUsed = true;
        std::vector<Node> o;
        o.push_back(finalize(opcodeify(node.args[0])));
        programData sub = opcodeify(node.args[1], aux, vaux);
        Node code = astnode("____CODE", o, m);
        Node nodelist[] = {
            token("$begincode"+symb+".endcode"+symb, m), token("DUP1", m),
            token("$begincode"+symb, m), sub.code, token("CODECOPY", m),
            token("$endcode"+symb, m), token("JUMP", m),
            token("~begincode"+symb, m), code, 
            token("~endcode"+symb, m), token("JUMPDEST", m)
        };
        return pd(sub.aux, multiToken(nodelist, 11, m), 1);
    }
    // Stack variables
    if (node.val == "with") {
        programData initial = opcodeify(node.args[1], aux, vaux);
        programVerticalAux vaux2 = vaux;
        vaux2.dupvars[node.args[0].val] = vaux.height;
        vaux2.height += 1;
        if (!initial.outs)
            err("Initial variable value must have nonzero arity!", m);
        programData sub = opcodeify(node.args[2], initial.aux, vaux2);
        Node nodelist[] = {
            initial.code,
            sub.code
        };
        programData o = pd(sub.aux, multiToken(nodelist, 2, m), sub.outs);
        if (sub.outs)
            o.code.args.push_back(token("SWAP1", m));
        o.code.args.push_back(token("POP", m));
        return o;
    }
    // Seq of multiple statements
    if (node.val == "seq") {
        std::vector<Node> children;
        int lastOut = 0;
        for (unsigned i = 0; i < node.args.size(); i++) {
            programData sub = opcodeify(node.args[i], aux, vaux);
            aux = sub.aux;
            if (sub.outs == 1) {
                if (i < node.args.size() - 1) sub.code = popwrap(sub.code);
                else lastOut = 1;
            }
            children.push_back(sub.code);
        }
        return pd(aux, astnode("_", children, m), lastOut);
    }
    // 2-part conditional (if gets rewritten to unless in rewrites)
    else if (node.val == "unless" && node.args.size() == 2) {
        programData cond = opcodeify(node.args[0], aux, vaux);
        programData action = opcodeify(node.args[1], cond.aux, vaux);
        aux = action.aux;
        if (!cond.outs) err("Condition of if/unless statement has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            cond.code,
            token("$endif"+symb, m), token("JUMPI", m),
            action.code,
            token("~endif"+symb, m), token("JUMPDEST", m)
        };
        return pd(aux, multiToken(nodelist, 6, m), 0);
    }
    // 3-part conditional
    else if (node.val == "if" && node.args.size() == 3) {
        programData ifd = opcodeify(node.args[0], aux, vaux);
        programData thend = opcodeify(node.args[1], ifd.aux, vaux);
        programData elsed = opcodeify(node.args[2], thend.aux, vaux);
        aux = elsed.aux;
        if (!ifd.outs)
            err("Condition of if/unless statement has arity 0", m);
        // Handle cases where one conditional outputs something
        // and the other does not
        int outs = (thend.outs && elsed.outs) ? 1 : 0;
        if (thend.outs > outs) thend.code = popwrap(thend.code);
        if (elsed.outs > outs) elsed.code = popwrap(elsed.code);
        Node nodelist[] = {
            ifd.code,
            token("ISZERO", m),
            token("$else"+symb, m), token("JUMPI", m),
            thend.code,
            token("$endif"+symb, m), token("JUMP", m),
            token("~else"+symb, m), token("JUMPDEST", m),
            elsed.code,
            token("~endif"+symb, m), token("JUMPDEST", m)
        };
        return pd(aux, multiToken(nodelist, 12, m), outs);
    }
    // While (rewritten to this in rewrites)
    else if (node.val == "until") {
        programData cond = opcodeify(node.args[0], aux, vaux);
        programData action = opcodeify(node.args[1], cond.aux, vaux);
        aux = action.aux;
        if (!cond.outs)
            err("Condition of while/until loop has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            token("~beg"+symb, m), token("JUMPDEST", m),
            cond.code,
            token("$end"+symb, m), token("JUMPI", m),
            action.code,
            token("$beg"+symb, m), token("JUMP", m),
            token("~end"+symb, m), token("JUMPDEST", m),
        };
        return pd(aux, multiToken(nodelist, 10, m));
    }
    // Memory allocations
    else if (node.val == "alloc") {
        programData bytez = opcodeify(node.args[0], aux, vaux);
        aux = bytez.aux;
        if (!bytez.outs)
            err("Alloc input has arity 0", m);
        aux.allocUsed = true;
        Node nodelist[] = {
            bytez.code,
            token("MSIZE", m), token("SWAP1", m), token("MSIZE", m),
            token("ADD", m), 
            token("0", m), token("SWAP1", m), token("MSTORE", m)
        };
        return pd(aux, multiToken(nodelist, 8, m), 1);
    }
    // All other functions/operators
    else {
        std::vector<Node>  subs2;
        int depth = opinputs(upperCase(node.val));
        if (depth == -1)
            err("Not a function or opcode: "+node.val, m);
        if ((int)node.args.size() != depth)
            err("Invalid arity for "+node.val, m);
        for (int i = node.args.size() - 1; i >= 0; i--) {
            programVerticalAux vaux2 = vaux;
            vaux2.height = vaux.height - i - 1 + node.args.size();
            programData sub = opcodeify(node.args[i], aux, vaux2);
            aux = sub.aux;
            if (!sub.outs)
                err("Input "+unsignedToDecimal(i)+" has arity 0", sub.code.metadata);
            subs2.push_back(sub.code);
        }
        subs2.push_back(token(upperCase(node.val), m));
        int outdepth = opoutputs(upperCase(node.val));
        return pd(aux, astnode("_", subs2, m), outdepth);
    }
}
Example #4
0
int
socks_connect(const char *host, const char *port,
    struct addrinfo hints __attribute__ ((__unused__)),
    const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
    int socksv, const char *proxyuser)
{
	int proxyfd, r, authretry = 0;
	size_t hlen, wlen;
	unsigned char buf[1024];
	size_t cnt;
	struct sockaddr_storage addr;
	struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
	struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
	in_port_t serverport;
	const char *proxypass = NULL;

	if (proxyport == NULL)
		proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;

	/* Abuse API to lookup port */
	if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
	    sizeof(addr), 1, 1) == -1)
		errx(1, "unknown port \"%.64s\"", port);
	serverport = in4->sin_port;

 again:
	if (authretry++ > 3)
		errx(1, "Too many authentication failures");

	proxyfd = remote_connect(proxyhost, proxyport, proxyhints);

	if (proxyfd < 0)
		return (-1);

	if (socksv == 5) {
		if (decode_addrport(host, port, (struct sockaddr *)&addr,
		    sizeof(addr), 0, 1) == -1)
			addr.ss_family = 0; /* used in switch below */

		/* Version 5, one method: no authentication */
		buf[0] = SOCKS_V5;
		buf[1] = 1;
		buf[2] = SOCKS_NOAUTH;
		cnt = atomicio(vwrite, proxyfd, buf, 3);
		if (cnt != 3)
			err(1, "write failed (%zu/3)", cnt);

		cnt = atomicio(read, proxyfd, buf, 2);
		if (cnt != 2)
			err(1, "read failed (%zu/3)", cnt);

		if (buf[1] == SOCKS_NOMETHOD)
			errx(1, "authentication method negotiation failed");

		switch (addr.ss_family) {
		case 0:
			/* Version 5, connect: domain name */

			/* Max domain name length is 255 bytes */
			hlen = strlen(host);
			if (hlen > 255)
				errx(1, "host name too long for SOCKS5");
			buf[0] = SOCKS_V5;
			buf[1] = SOCKS_CONNECT;
			buf[2] = 0;
			buf[3] = SOCKS_DOMAIN;
			buf[4] = hlen;
			memcpy(buf + 5, host, hlen);			
			memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
			wlen = 7 + hlen;
			break;
		case AF_INET:
			/* Version 5, connect: IPv4 address */
			buf[0] = SOCKS_V5;
			buf[1] = SOCKS_CONNECT;
			buf[2] = 0;
			buf[3] = SOCKS_IPV4;
			memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
			memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
			wlen = 10;
			break;
		case AF_INET6:
			/* Version 5, connect: IPv6 address */
			buf[0] = SOCKS_V5;
			buf[1] = SOCKS_CONNECT;
			buf[2] = 0;
			buf[3] = SOCKS_IPV6;
			memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
			memcpy(buf + 20, &in6->sin6_port,
			    sizeof in6->sin6_port);
			wlen = 22;
			break;
		default:
			errx(1, "internal error: silly AF");
		}

		cnt = atomicio(vwrite, proxyfd, buf, wlen);
		if (cnt != wlen)
			err(1, "write failed (%zu/%zu)", cnt, wlen);

		cnt = atomicio(read, proxyfd, buf, 4);
		if (cnt != 4)
			err(1, "read failed (%zu/4)", cnt);
		if (buf[1] != 0) {
			errx(1, "connection failed, SOCKSv5 error: %s",
			    socks5_strerror(buf[1]));
		}
		switch (buf[3]) {
		case SOCKS_IPV4:
			cnt = atomicio(read, proxyfd, buf + 4, 6);
			if (cnt != 6)
				err(1, "read failed (%zu/6)", cnt);
			break;
		case SOCKS_IPV6:
			cnt = atomicio(read, proxyfd, buf + 4, 18);
			if (cnt != 18)
				err(1, "read failed (%zu/18)", cnt);
			break;
		default:
			errx(1, "connection failed, unsupported address type");
		}
	} else if (socksv == 4) {
		/* This will exit on lookup failure */
		decode_addrport(host, port, (struct sockaddr *)&addr,
		    sizeof(addr), 1, 0);

		/* Version 4 */
		buf[0] = SOCKS_V4;
		buf[1] = SOCKS_CONNECT;	/* connect */
		memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
		memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
		buf[8] = 0;	/* empty username */
		wlen = 9;

		cnt = atomicio(vwrite, proxyfd, buf, wlen);
		if (cnt != wlen)
			err(1, "write failed (%zu/%zu)", cnt, wlen);

		cnt = atomicio(read, proxyfd, buf, 8);
		if (cnt != 8)
			err(1, "read failed (%zu/8)", cnt);
		if (buf[1] != 90) {
			errx(1, "connection failed, SOCKSv4 error: %s",
			    socks4_strerror(buf[1]));
		}
	} else if (socksv == -1) {
		/* HTTP proxy CONNECT */

		/* Disallow bad chars in hostname */
		if (strcspn(host, "\r\n\t []:") != strlen(host))
			errx(1, "Invalid hostname");

		/* Try to be sane about numeric IPv6 addresses */
		if (strchr(host, ':') != NULL) {
			r = snprintf(buf, sizeof(buf),
			    "CONNECT [%s]:%d HTTP/1.0\r\n",
			    host, ntohs(serverport));
		} else {
			r = snprintf(buf, sizeof(buf),
			    "CONNECT %s:%d HTTP/1.0\r\n",
			    host, ntohs(serverport));
		}
		if (r == -1 || (size_t)r >= sizeof(buf))
			errx(1, "hostname too long");
		r = strlen(buf);

		cnt = atomicio(vwrite, proxyfd, buf, r);
		if (cnt != r)
			err(1, "write failed (%zu/%d)", cnt, r);

		if (authretry > 1) {
			char resp[1024];

			proxypass = getproxypass(proxyuser, proxyhost);
			r = snprintf(buf, sizeof(buf), "%s:%s",
			    proxyuser, proxypass);
			if (r == -1 || (size_t)r >= sizeof(buf) ||
			    b64_ntop(buf, strlen(buf), resp,
			    sizeof(resp)) == -1)
				errx(1, "Proxy username/password too long");
			r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
			    "Basic %s\r\n", resp);
			if (r == -1 || (size_t)r >= sizeof(buf))
				errx(1, "Proxy auth response too long");
			r = strlen(buf);
			if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != r)
				err(1, "write failed (%zu/%d)", cnt, r);
		}

		/* Terminate headers */
		if ((cnt = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
			err(1, "write failed (%zu/2)", cnt);

		/* Read status reply */
		proxy_read_line(proxyfd, buf, sizeof(buf));
		if (proxyuser != NULL &&
		    strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
			if (authretry > 1) {
				fprintf(stderr, "Proxy authentication "
				    "failed\n");
			}
			close(proxyfd);
			goto again;
		} else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
		    strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
			errx(1, "Proxy error: \"%s\"", buf);

		/* Headers continue until we hit an empty line */
		for (r = 0; r < HTTP_MAXHDRS; r++) {
			proxy_read_line(proxyfd, buf, sizeof(buf));
			if (*buf == '\0')
				break;
		}
		if (*buf != '\0')
			errx(1, "Too many proxy headers received");
	} else
		errx(1, "Unknown proxy protocol %d", socksv);

	return (proxyfd);
}
Example #5
0
int
main(int argc, char **argv)
{
	struct iovec *iov;
	int iovlen;
	int ch, mntflags;
	char *dev, *dir, *p, *val, mntpath[MAXPATHLEN];
	int verbose;
	int ssector;		/* starting sector, 0 for 1st session */
	char fstype[] = "cd9660";

	iov = NULL;
	iovlen = 0;
	mntflags = verbose = 0;
	ssector = -1;

	while ((ch = getopt(argc, argv, "begjo:rs:vC:")) != -1)
		switch (ch) {
		case 'b':
			build_iovec(&iov, &iovlen, "brokenjoliet", NULL, (size_t)-1);
			break;
		case 'e':
			build_iovec(&iov, &iovlen, "extatt", NULL, (size_t)-1);
			break;
		case 'g':
			build_iovec(&iov, &iovlen, "gens", NULL, (size_t)-1);
			break;
		case 'j':
			build_iovec(&iov, &iovlen, "nojoliet", NULL, (size_t)-1);
			break;
		case 'o':
			getmntopts(optarg, mopts, &mntflags, NULL);
			p = strchr(optarg, '=');
			val = NULL;
			if (p != NULL) {
				*p = '\0';
				val = p + 1;
			}
			build_iovec(&iov, &iovlen, optarg, val, (size_t)-1);
			break;
		case 'r':
			build_iovec(&iov, &iovlen, "norrip", NULL, (size_t)-1);
			break;
		case 's':
			ssector = atoi(optarg);
			break;
		case 'v':
			verbose++;
			break;
		case 'C':
			if (set_charset(&iov, &iovlen, optarg) == -1)
				err(EX_OSERR, "cd9660_iconv");
			build_iovec(&iov, &iovlen, "kiconv", NULL, (size_t)-1);
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc != 2)
		usage();

	dev = argv[0];
	dir = argv[1];

	/*
	 * Resolve the mountpoint with realpath(3) and remove unnecessary
	 * slashes from the devicename if there are any.
	 */
	if (checkpath(dir, mntpath) != 0)
		err(1, "%s", mntpath);
	(void)rmslashes(dev, dev);

	if (ssector == -1) {
		/*
		 * The start of the session has not been specified on
		 * the command line.  If we can successfully read the
		 * TOC of a CD-ROM, use the last data track we find.
		 * Otherwise, just use 0, in order to mount the very
		 * first session.  This is compatible with the
		 * historic behaviour of mount_cd9660(8).  If the user
		 * has specified -s <ssector> above, we don't get here
		 * and leave the user's will.
		 */
		if ((ssector = get_ssector(dev)) == -1) {
			if (verbose)
				printf("could not determine starting sector, "
				       "using very first session\n");
			ssector = 0;
		} else if (verbose)
			printf("using starting sector %d\n", ssector);
	}
	mntflags |= MNT_RDONLY;
	build_iovec(&iov, &iovlen, "fstype", fstype, (size_t)-1);
	build_iovec(&iov, &iovlen, "fspath", mntpath, (size_t)-1);
	build_iovec(&iov, &iovlen, "from", dev, (size_t)-1);
	build_iovec_argf(&iov, &iovlen, "ssector", "%d", ssector);

	if (nmount(iov, iovlen, mntflags) < 0)
		err(1, "%s", dev);
	exit(0);
}
Example #6
0
int
main(int argc, char **argv)
{
    int i, len;
    double eval, clk;
    long long ncycles_ref, counter;
    double eptime;
    double add_delay;
    struct cfg cf;
    char buf[256];
    struct recfilter loop_error;
    struct PFD phase_detector;
    useconds_t usleep_time;
    struct sched_param sparam;
#if RTPP_DEBUG
    double sleep_time, filter_lastval;
#endif
    memset(&cf, 0, sizeof(cf));

    cf.stable = malloc(sizeof(struct rtpp_cfg_stable));
    if (cf.stable == NULL) {
         err(1, "can't allocate memory for the struct rtpp_cfg_stable");
         /* NOTREACHED */
    }
    memset(cf.stable, '\0', sizeof(struct rtpp_cfg_stable));
    cf.stable->ctrl_socks = malloc(sizeof(struct rtpp_list));
    if (cf.stable->ctrl_socks == NULL) {
         err(1, "can't allocate memory for the struct rtpp_cfg_stable");
         /* NOTREACHED */
    }
    memset(cf.stable->ctrl_socks, '\0', sizeof(struct rtpp_list));
    RTPP_LIST_RESET(cf.stable->ctrl_socks);    

    init_config(&cf, argc, argv);

    seedrandom();

    cf.stable->sessions_ht = rtpp_hash_table_ctor();
    if (cf.stable->sessions_ht == NULL) {
        err(1, "can't allocate memory for the hash table");
         /* NOTREACHED */
    }
    cf.stable->rtpp_stats = rtpp_stats_ctor();
    if (cf.stable->rtpp_stats == NULL) {
        err(1, "can't allocate memory for the stats data");
         /* NOTREACHED */
    }
    init_port_table(&cf);

    if (rtpp_controlfd_init(&cf) != 0) {
        err(1, "can't inilialize control socket%s",
          cf.stable->ctrl_socks->len > 1 ? "s" : "");
    }

    if (cf.stable->nodaemon == 0) {
	if (rtpp_daemon(0, 0) == -1)
	    err(1, "can't switch into daemon mode");
	    /* NOTREACHED */
    }

    if (rtpp_notify_init() != 0)
        errx(1, "can't start notification thread");

    cf.stable->glog = rtpp_log_open(cf.stable, "rtpproxy", NULL, LF_REOPEN);
    rtpp_log_setlevel(cf.stable->glog, cf.stable->log_level);
    _sig_cf = &cf;
    atexit(ehandler);
    rtpp_log_write(RTPP_LOG_INFO, cf.stable->glog, "rtpproxy started, pid %d", getpid());

    i = open(cf.stable->pid_file, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE);
    if (i >= 0) {
	len = sprintf(buf, "%u\n", (unsigned int)getpid());
	write(i, buf, len);
	close(i);
    } else {
	rtpp_log_ewrite(RTPP_LOG_ERR, cf.stable->glog, "can't open pidfile for writing");
    }

    signal(SIGHUP, sighup);
    signal(SIGINT, fatsignal);
    signal(SIGKILL, fatsignal);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGTERM, fatsignal);
    signal(SIGXCPU, fatsignal);
    signal(SIGXFSZ, fatsignal);
    signal(SIGVTALRM, fatsignal);
    signal(SIGPROF, fatsignal);
    signal(SIGUSR1, fatsignal);
    signal(SIGUSR2, fatsignal);

    if (cf.stable->sched_policy != SCHED_OTHER) {
        sparam.sched_priority = sched_get_priority_max(cf.stable->sched_policy);
        if (sched_setscheduler(0, cf.stable->sched_policy, &sparam) == -1) {
            rtpp_log_ewrite(RTPP_LOG_ERR, cf.stable->glog, "sched_setscheduler(SCHED_%s, %d)",
              (cf.stable->sched_policy == SCHED_FIFO) ? "FIFO" : "RR", sparam.sched_priority);
        }
    }

    if (cf.stable->run_uname != NULL || cf.stable->run_gname != NULL) {
	if (drop_privileges(&cf) != 0) {
	    rtpp_log_ewrite(RTPP_LOG_ERR, cf.stable->glog,
	      "can't switch to requested user/group");
	    exit(1);
	}
    }
    set_rlimits(&cf);

    cf.sessinfo.sessions[0] = NULL;
    cf.sessinfo.nsessions = 0;
    cf.rtp_nsessions = 0;

    rtpp_command_async_init(&cf);
    rtpp_proc_async_init(&cf);

    counter = 0;
    recfilter_init(&loop_error, 0.96, 0.0, 0);
    PFD_init(&phase_detector, 2.0);
#ifdef HAVE_SYSTEMD_SD_DAEMON_H
    sd_notify(0, "READY=1");
#endif
#ifdef RTPP_CHECK_LEAKS
    rtpp_memdeb_setbaseln();
#endif
    for (;;) {
	eptime = getdtime();

        clk = (eptime + cf.stable->sched_offset) * cf.stable->target_pfreq;

        ncycles_ref = llrint(clk);

        eval = PFD_get_error(&phase_detector, clk);

#if RTPP_DEBUG
        filter_lastval = loop_error.lastval;
#endif

        if (eval != 0.0) {
            recfilter_apply(&loop_error, sigmoid(eval));
        }

#if RTPP_DEBUG
        if (counter % (unsigned int)cf.stable->target_pfreq == 0 || counter < 1000) {
          rtpp_log_write(RTPP_LOG_DBUG, cf.stable->glog, "run %lld ncycles %f raw error1 %f, filter lastval %f, filter nextval %f",
            counter, clk, eval, filter_lastval, loop_error.lastval);
        }
#endif
        add_delay = freqoff_to_period(cf.stable->target_pfreq, 1.0, loop_error.lastval);
        usleep_time = add_delay * 1000000.0;
#if RTPP_DEBUG
        if (counter % (unsigned int)cf.stable->target_pfreq == 0 || counter < 1000) {
            rtpp_log_write(RTPP_LOG_DBUG, cf.stable->glog, "run %lld filter lastval %f, filter nextval %f, error %f",
              counter, filter_lastval, loop_error.lastval, sigmoid(eval));
            rtpp_log_write(RTPP_LOG_DBUG, cf.stable->glog, "run %lld extra sleeping time %llu", counter, usleep_time);
        }
        sleep_time = getdtime();
#endif
        rtpp_proc_async_wakeup(cf.stable->rtpp_proc_cf, counter, ncycles_ref);
        usleep(usleep_time);
#if RTPP_DEBUG
        sleep_time = getdtime() - sleep_time;
        if (counter % (unsigned int)cf.stable->target_pfreq == 0 || counter < 1000 || sleep_time > add_delay * 2.0) {
            rtpp_log_write(RTPP_LOG_DBUG, cf.stable->glog, "run %lld sleeping time required %llu sleeping time actual %f, CSV: %f,%f,%f", \
              counter, usleep_time, sleep_time, (double)counter / cf.stable->target_pfreq, ((double)usleep_time) / 1000.0, sleep_time * 1000.0);
        }
#endif
        counter += 1;
        if (cf.stable->slowshutdown != 0) {
            pthread_mutex_lock(&cf.sessinfo.lock);
            if (cf.sessinfo.nsessions == 0) {
                /* The below unlock is not necessary, but does not hurt either */
                pthread_mutex_unlock(&cf.sessinfo.lock);
                rtpp_log_write(RTPP_LOG_INFO, cf.stable->glog,
                  "deorbiting-burn sequence completed, exiting");
                break;
            }
            pthread_mutex_unlock(&cf.sessinfo.lock);
        }
    }

#ifdef HAVE_SYSTEMD_SD_DAEMON_H
    sd_notify(0, "STATUS=Exited");
#endif

#ifdef RTPP_CHECK_LEAKS
    exit(rtpp_memdeb_dumpstats(&cf) == 0 ? 0 : 1);
#else
    exit(0);
#endif
}
Example #7
0
xamdeflst()
{
    long mul;
    int	 botptr, bret, value;
    int  xoff, yoff, mx, my;
    int  i, ret, cont;
    int  np, xam;
    int  k1, k2;

    /* Allocate memory to hold defects */
    if ((xampaddr = mymalloc(npndefs*(sizeof(PADDR)))) <= 0) {
        return err(nomemory);
    }
    
    for (np = 0; np < npndefs; np++) {
    	xampaddr[np].exist = nppaddr[np].exist;
    	xampaddr[np].head = nppaddr[np].head;
    	xampaddr[np].cylndr = nppaddr[np].cylndr;
    	xampaddr[np].btoffst = nppaddr[np].btoffst;
    }
    
    r_items();		/* read items */
    
    totcnt = npndefs;
    if (npndefs > NM_ITEMS)		/* bigger than one window */
	botptr = npndefs - NM_ITEMS;
    else
	botptr = 0;

    cont = TRUE;			/* control flag	*/
    while(cont) {
	bret = form_do(xamform, -1);
	graf_mkstate(&mx, &my, &k1, &k2);	/* graf mkstate	*/
	ret = bret & 0x7FFF;			/* mask off double click */
	LWSET(OB_STATE(xamform, ret), 0);
	value = 1;			/* scroll factor */

	switch (ret) {		/* Big Switch */
	    case FSVSLID:		
		objc_offset(xamform, FSVELEV, &xoff, &yoff);
		value = NM_ITEMS;		/* one full window size	*/
		if (my <= yoff)
		    goto up;		
		goto down;

	    case FSVELEV:
		value = graf_slidebox(xamform, FSVSLID, FSVELEV, TRUE);
		mul = (npndefs - NM_ITEMS) * value;
		mul /= 1000;
		value = (int)mul; 
		value = (topptr - value);
		if (value >= 0)
		    goto up;			/* go up */
		else
		    value = -value;		/* go down */

down:	    case FDNAROW:			/* scroll down */
		if (topptr == botptr)
		    break;

		if ((topptr + value) <= botptr)
		    topptr += value;
		else
		    topptr = botptr;

		goto sfiles;			

up:	    case FUPAROW:			/* scroll up */
		if (!topptr)
		    break;

		if ((topptr - value) >= 0)
		    topptr -= value;
		else
		    topptr = 0;

sfiles:	    r_show(topptr);		/* redisplay the file */
	    break;

	    case FCLSBOX:
	      cont = FALSE;
	      break;

	    default:
	      if (ret >= ENTRY0 && ret <= ENTRY7) {
	      	  erasemsg();		/* erase EXAMINING box */
	      	  want2edt(ret);	/* let user edit entry */
	      	  dsplymsg(xamform);	/* redraw EXAMINING box */
	      }
	      break;  
	}				/* end of switch */
    }			    	/* while */
    erasemsg();
    
    /* New inputted list = Examined list */
    for (xam = 0, np = 0; xam < npndefs; xam++) {
    	if (xampaddr[xam].exist) {
    	    nppaddr[np].head = xampaddr[xam].head;
    	    nppaddr[np].cylndr = xampaddr[xam].cylndr;
    	    nppaddr[np].btoffst = xampaddr[xam].btoffst;
    	    np++;
    	}
    }
    npndefs = np;	/* current number of input entries */
    free(xampaddr);
    return (TRUE);
}
Example #8
0
int main(int argc, char **argv)
{
	if (argc < 2) {
		usage();
		exit(1);
	}

	FILE *fin, *fh, *fc;
	fname = argv[1];
	create_names();

	fin = fopen(fname, "rt");
	if (fin == NULL)
		err(1, "cannot open input file: %s", fname);

	fc = fopen(c_fname, "wt");
	if (fc == NULL)
		err(1, "cannot open output C file %s", c_fname);

	fh = fopen(h_fname, "wt");
	if (fh == NULL)
		err(1, "cannot open output H file %s", h_fname);

	fprintf(fh,
		"extern const char %s[];\n"
		"extern const size_t %s_size;\n",
		name, name);

	fprintf(fc,
		"#include <unistd.h>\n"
		"\n"
		"const char %s[] = \"\"\n\"",
		name);

	int c = 0;
	size_t size = 0;

	while ((c = fgetc(fin)) != EOF) {
		size++;
		switch (c) {
			case '\\':
				fputs("\\\\", fc);
				break;
			case '\"':
				fputs("\\\"", fc);
				break;
			case '\n':
				fputs("\\n\"\n\"", fc);
				break;
			default:
				fputc(c, fc);
		}
	}

	fprintf(fc,
		"\";\n"
		"\n"
		"const size_t %s_size = %zu;\n",
		name,
		size);

	fclose(fc);
	fclose(fh);
	fclose(fin);

	return 0;
}
Example #9
0
int
main(int argc, char *argv[])
{
	struct passwd *pwd;
	int ch, newline;
	char *file, *sender, *p;
#if MAXPATHLEN > BUFSIZ
	char buf[MAXPATHLEN];
#else
	char buf[BUFSIZ];
#endif

	file = sender = NULL;
	while ((ch = getopt(argc, argv, "f:s:")) != -1)
		switch((char)ch) {
		case 'f':
			file = optarg;
			break;
		case 's':
			sender = optarg;
			for (p = sender; *p; ++p)
				if (isupper(*p))
					*p = tolower(*p);
			break;
		case '?':
		default:
			fprintf(stderr,
			    "usage: from [-f file] [-s sender] [user]\n");
			exit(1);
		}
	argv += optind;

	/*
	 * We find the mailbox by:
	 *	1 -f flag
	 *	2 user
	 *	2 MAIL environment variable
	 *	3 _PATH_MAILDIR/file
	 */
	if (!file) {
		if (!(file = *argv)) {
			if (!(file = getenv("MAIL"))) {
				if (!(pwd = getpwuid(getuid())))
					errx(1, "no password file entry for you");
				if ((file = getenv("USER"))) {
					(void)snprintf(buf, sizeof(buf),
					    "%s/%s", _PATH_MAILDIR, file);
					file = buf;
				} else
					(void)snprintf(file = buf, sizeof(buf),
					    "%s/%s", _PATH_MAILDIR,
					    pwd->pw_name);
			}
		} else {
			(void)snprintf(buf, sizeof(buf), "%s/%s",
			    _PATH_MAILDIR, file);
			file = buf;
		}
	}
	if (!freopen(file, "r", stdin))
		err(1, "%s", file);
	for (newline = 1; fgets(buf, sizeof(buf), stdin);) {
		if (*buf == '\n') {
			newline = 1;
			continue;
		}
		if (newline && !strncmp(buf, "From ", 5) &&
		    (!sender || match(buf + 5, sender)))
			printf("%s", buf);
		newline = 0;
	}
	exit(0);
}
Example #10
0
/*
 * Periodically pat the watchdog, preventing it from firing.
 */
int
main(int argc, char *argv[])
{
	struct rtprio rtp;
	struct pidfh *pfh;
	pid_t otherpid;

	if (getuid() != 0)
		errx(EX_SOFTWARE, "not super user");
		
	parseargs(argc, argv);

	if (do_syslog)
		openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
		    LOG_DAEMON);

	rtp.type = RTP_PRIO_REALTIME;
	rtp.prio = 0;
	if (rtprio(RTP_SET, 0, &rtp) == -1)
		err(EX_OSERR, "rtprio");

	if (!is_dry_run && watchdog_init() == -1)
		errx(EX_SOFTWARE, "unable to initialize watchdog");

	if (is_daemon) {
		if (watchdog_onoff(1) == -1)
			err(EX_OSERR, "patting the dog");

		pfh = pidfile_open(pidfile, 0600, &otherpid);
		if (pfh == NULL) {
			if (errno == EEXIST) {
				watchdog_onoff(0);
				errx(EX_SOFTWARE, "%s already running, pid: %d",
				    getprogname(), otherpid);
			}
			warn("Cannot open or create pidfile");
		}

		if (debugging == 0 && daemon(0, 0) == -1) {
			watchdog_onoff(0);
			pidfile_remove(pfh);
			err(EX_OSERR, "daemon");
		}

		signal(SIGHUP, SIG_IGN);
		signal(SIGINT, sighandler);
		signal(SIGTERM, sighandler);

		pidfile_write(pfh);
		if (madvise(0, 0, MADV_PROTECT) != 0)
			warn("madvise failed");
		if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
			warn("mlockall failed");

		watchdog_loop();

		/* exiting */
		pidfile_remove(pfh);
		return (EX_OK);
	} else {
		if (passive)
			timeout |= WD_PASSIVE;
		else
			timeout |= WD_ACTIVE;
		if (watchdog_patpat(timeout) < 0)
			err(EX_OSERR, "patting the dog");
		return (EX_OK);
	}
}
Example #11
0
/*
 * Convert a timeval to a number of ticks.
 * Mostly copied from the kernel.
 */
int
tvtohz(struct timeval *tv)
{
	register unsigned long ticks;
	register long sec, usec;
	int hz;
	size_t hzsize;
	int error;
	int tick;

	hzsize = sizeof(hz);

	error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
	if (error)
		err(1, "sysctlbyname kern.hz");

	tick = 1000000 / hz;

	/*
	 * If the number of usecs in the whole seconds part of the time
	 * difference fits in a long, then the total number of usecs will
	 * fit in an unsigned long.  Compute the total and convert it to
	 * ticks, rounding up and adding 1 to allow for the current tick
	 * to expire.  Rounding also depends on unsigned long arithmetic
	 * to avoid overflow.
	 *
	 * Otherwise, if the number of ticks in the whole seconds part of
	 * the time difference fits in a long, then convert the parts to
	 * ticks separately and add, using similar rounding methods and
	 * overflow avoidance.  This method would work in the previous
	 * case but it is slightly slower and assumes that hz is integral.
	 *
	 * Otherwise, round the time difference down to the maximum
	 * representable value.
	 *
	 * If ints have 32 bits, then the maximum value for any timeout in
	 * 10ms ticks is 248 days.
	 */
	sec = tv->tv_sec;
	usec = tv->tv_usec;
	if (usec < 0) {
		sec--;
		usec += 1000000;
	}
	if (sec < 0) {
#ifdef DIAGNOSTIC
		if (usec > 0) {
			sec++;
			usec -= 1000000;
		}
		printf("tvotohz: negative time difference %ld sec %ld usec\n",
		    sec, usec);
#endif
		ticks = 1;
	} else if (sec <= LONG_MAX / 1000000)
		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
		    / tick + 1;
	else if (sec <= LONG_MAX / hz)
		ticks = sec * hz
		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
	else
		ticks = LONG_MAX;
	if (ticks > INT_MAX)
		ticks = INT_MAX;
	return ((int)ticks);
}
int runServer(void) {
	int listenfd;
	struct sockaddr_in listen_addr;
	struct event ev_accept;
	int reuseaddr_on;

	event_init();

	sigset_t sigset;
	sigemptyset(&sigset);
	struct sigaction siginfo = {
		.sa_handler = sighandler,
		.sa_mask = sigset,
		.sa_flags = SA_RESTART,
	};
	sigaction(SIGINT, &siginfo, NULL);
	sigaction(SIGTERM, &siginfo, NULL);

	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	if (listenfd < 0) {
		err(1, "listen failed");
	}
	memset(&listen_addr, 0, sizeof(listen_addr));
	listen_addr.sin_family = AF_INET;
	listen_addr.sin_addr.s_addr = INADDR_ANY;
	listen_addr.sin_port = htons(SERVER_PORT);
	if (bind(listenfd, (struct sockaddr *)&listen_addr, sizeof(listen_addr)) < 0) {
		err(1, "bind failed");
	}
	if (listen(listenfd, CONNECTION_BACKLOG) < 0) {
		err(1, "listen failed");
	}
	reuseaddr_on = 1;
	setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on, sizeof(reuseaddr_on));

	if (setnonblock(listenfd) < 0) {
		err(1, "failed to set server socket to non-blocking");
	}

	if ((evbase_accept = event_base_new()) == NULL) {
		perror("Unable to create socket accept event base");
		close(listenfd);
		return 1;
	}

	if (workqueue_init(&workqueue, NUM_THREADS)) {
		perror("Failed to create work queue");
		close(listenfd);
		workqueue_shutdown(&workqueue);
		return 1;
	}

	event_set(&ev_accept, listenfd, EV_READ|EV_PERSIST, on_accept, (void *)&workqueue);
	event_base_set(evbase_accept, &ev_accept);
	event_add(&ev_accept, NULL);

	printf("Server running.\n");

	event_base_dispatch(evbase_accept);

	event_base_free(evbase_accept);
	evbase_accept = NULL;

	close(listenfd);

	printf("Server shutdown.\n");

	return 0;
}
Example #13
0
static void
runtest(struct alg *alg, int count, int size, u_long cmd, struct timeval *tv)
{
	int i, fd = crget();
	struct timeval start, stop, dt;
	char *cleartext, *ciphertext, *originaltext;
	struct session2_op sop;
	struct crypt_op cop;
	char iv[EALG_MAX_BLOCK_LEN];

	bzero(&sop, sizeof(sop));
	if (!alg->ishash) {
		sop.keylen = (alg->minkeylen + alg->maxkeylen)/2;
		sop.key = (char *) malloc(sop.keylen);
		if (sop.key == NULL)
			err(1, "malloc (key)");
		for (i = 0; i < sop.keylen; i++)
			sop.key[i] = rdigit();
		sop.cipher = alg->code;
	} else {
		sop.mackeylen = (alg->minkeylen + alg->maxkeylen)/2;
		sop.mackey = (char *) malloc(sop.mackeylen);
		if (sop.mackey == NULL)
			err(1, "malloc (mac)");
		for (i = 0; i < sop.mackeylen; i++)
			sop.mackey[i] = rdigit();
		sop.mac = alg->code;
	}
	sop.crid = crid;
	if (ioctl(fd, cmd, &sop) < 0) {
		if (cmd == CIOCGSESSION || cmd == CIOCGSESSION2) {
			close(fd);
			if (verbose) {
				printf("cipher %s", alg->name);
				if (alg->ishash)
					printf(" mackeylen %u\n", sop.mackeylen);
				else
					printf(" keylen %u\n", sop.keylen);
				perror("CIOCGSESSION");
			}
			/* hardware doesn't support algorithm; skip it */
			return;
		}
		printf("cipher %s keylen %u mackeylen %u\n",
			alg->name, sop.keylen, sop.mackeylen);
		err(1, "CIOCGSESSION");
	}

	originaltext = malloc(3*size);
	if (originaltext == NULL)
		err(1, "malloc (text)");
	cleartext = originaltext+size;
	ciphertext = cleartext+size;
	for (i = 0; i < size; i++)
		cleartext[i] = rdigit();
	memcpy(originaltext, cleartext, size);
	for (i = 0; i < N(iv); i++)
		iv[i] = rdigit();

	if (verbose) {
		printf("session = 0x%x\n", sop.ses);
		printf("device = %s\n", crfind(sop.crid));
		printf("count = %d, size = %d\n", count, size);
		if (!alg->ishash) {
			printf("iv:");
			hexdump(iv, sizeof iv);
		}
		printf("cleartext:");
		hexdump(cleartext, MIN(size, CHUNK));
	}

	gettimeofday(&start, NULL);
	if (!alg->ishash) {
		for (i = 0; i < count; i++) {
			cop.ses = sop.ses;
			cop.op = COP_ENCRYPT;
			cop.flags = opflags;
			cop.len = size;
			cop.src = cleartext;
			cop.dst = ciphertext;
			cop.mac = 0;
			cop.iv = iv;

			if (ioctl(fd, CIOCCRYPT, &cop) < 0)
				err(1, "ioctl(CIOCCRYPT)");

			if (verify && bcmp(ciphertext, cleartext, size) == 0) {
				printf("cipher text unchanged:");
				hexdump(ciphertext, size);
			}

			memset(cleartext, 'x', MIN(size, CHUNK));
			cop.ses = sop.ses;
			cop.op = COP_DECRYPT;
			cop.flags = opflags;
			cop.len = size;
			cop.src = ciphertext;
			cop.dst = cleartext;
			cop.mac = 0;
			cop.iv = iv;

			if (ioctl(fd, CIOCCRYPT, &cop) < 0)
				err(1, "ioctl(CIOCCRYPT)");

			if (verify && bcmp(cleartext, originaltext, size) != 0) {
				printf("decrypt mismatch:\n");
				printf("original:");
				hexdump(originaltext, size);
				printf("cleartext:");
				hexdump(cleartext, size);
			}
		}
	} else {
		for (i = 0; i < count; i++) {
			cop.ses = sop.ses;
			cop.op = 0;
			cop.flags = opflags;
			cop.len = size;
			cop.src = cleartext;
			cop.dst = 0;
			cop.mac = ciphertext;
			cop.iv = 0;

			if (ioctl(fd, CIOCCRYPT, &cop) < 0)
				err(1, "ioctl(CIOCCRYPT)");
		}
	}
	gettimeofday(&stop, NULL);
 
	if (ioctl(fd, CIOCFSESSION, &sop.ses) < 0)
		perror("ioctl(CIOCFSESSION)");

	if (verbose) {
		printf("cleartext:");
		hexdump(cleartext, MIN(size, CHUNK));
	}
	timersub(&stop, &start, tv);

	free(originaltext);

	close(fd);
}
Example #14
0
int main(int argc, char *argv[])
{
    FILE *fh;
    char *line = NULL;
    int ch;
    size_t linesize = 0;
    ssize_t linelen;
    ssize_t linenum = 1;
    time_t now;

    if (!setlocale(LC_ALL, ""))
        errx(EX_USAGE, "setlocale(3) failed: check the locale settings");

    /* As otherwise the default of 0 could cause time formats that do not
     * include the date to skip back to a date in the previous month. */
    When.tm_mday = 1;

    while ((ch = getopt(argc, argv, "f:gh?o:syY:")) != -1) {
        switch (ch) {
        case 'f':
            Flag_Input_Format = optarg;
            break;
        case 'g':
            Flag_Global = true;
            break;
        case 'o':
            Flag_Output_Format = optarg;
            break;
        case 's':
            Flag_Suppress = true;
            break;
        case 'y':
            if (time(&now) == (time_t) - 1)
                errx(EX_OSERR, "time(3) could not obtain current time??");
            if (localtime_r(&now, &When) == NULL)
                errx(EX_OSERR, "localtime_r(3) failed??");
            Flag_Custom_Year = true;
            break;
        case 'Y':
            if (!strptime(optarg, "%Y", &When))
                errx(EX_USAGE, "strptime(3) could not parse year from -Y flag");
            Flag_Custom_Year = true;
            break;
        case 'h':
        case '?':
        default:
            emit_help();
            /* NOTREACHED */
        }
    }
    argc -= optind;
    argv += optind;

    if (!Flag_Input_Format)
        emit_help();

    /* Due to crazy behavior on Mac OS X (see also guard for it, below), and
     * otherwise there are less expensive syscalls that can better deal with
     * epoch values. */
    if (strncmp(Flag_Input_Format, "%s", (size_t) 2) == 0)
        errx(EX_DATAERR, "%%s is not supported as input format");

    if (argc == 0 || strncmp(*argv, "-", (size_t) 2) == 0) {
        fh = stdin;
    } else {
        if ((fh = fopen(*argv, "r")) == NULL)
            err(EX_IOERR, "could not open '%s'", *argv);
        File_Name = *argv;
    }

    while ((linelen = getline(&line, &linesize, fh)) != -1) {
        parseline(line, linenum);
        linenum++;
    }
    if (ferror(fh))
        err(EX_IOERR, "error reading file");

    exit(EXIT_SUCCESS);
}
Example #15
0
void RTFDocVisitor::visit(DocVerbatim *s)
{
  if (m_hide) return;
  DBG_RTF("{\\comment RTFDocVisitor::visit(DocVerbatim)}\n");
  QCString lang = m_langExt;
  if (!s->language().isEmpty()) // explicit language setting
  {
    lang = s->language();
  }
  SrcLangExt langExt = getLanguageFromFileName(lang);
  switch(s->type())
  {
    case DocVerbatim::Code: // fall though
      m_t << "{" << endl;
      m_t << "\\par" << endl;
      m_t << rtf_Style_Reset << getStyle("CodeExample");
      Doxygen::parserManager->getParser(lang)
                            ->parseCode(m_ci,s->context(),s->text(),langExt,
                                        s->isExample(),s->exampleFile());
      //m_t << "\\par" << endl; 
      m_t << "}" << endl;
      break;
    case DocVerbatim::Verbatim: 
      m_t << "{" << endl;
      m_t << "\\par" << endl;
      m_t << rtf_Style_Reset << getStyle("CodeExample");
      filter(s->text(),TRUE);
      //m_t << "\\par" << endl; 
      m_t << "}" << endl;
      break;
    case DocVerbatim::RtfOnly: 
      m_t << s->text(); 
      break;
    case DocVerbatim::HtmlOnly: 
    case DocVerbatim::LatexOnly: 
    case DocVerbatim::XmlOnly: 
    case DocVerbatim::ManOnly:
    case DocVerbatim::DocbookOnly:
      /* nothing */
      break;
    case DocVerbatim::Dot: 
      {
        static int dotindex = 1;
        QCString fileName(4096);

        fileName.sprintf("%s%d%s", 
            (Config_getString(RTF_OUTPUT)+"/inline_dotgraph_").data(), 
            dotindex++,
            ".dot"
           );
        QFile file(fileName);
        if (!file.open(IO_WriteOnly))
        {
          err("Could not open file %s for writing\n",fileName.data());
        }
        file.writeBlock( s->text(), s->text().length() );
        file.close();

        writeDotFile(fileName, s->hasCaption());
        visitCaption(this, s->children());
        includePicturePostRTF(true, s->hasCaption());

        if (Config_getBool(DOT_CLEANUP)) file.remove();
      }
      break;
    case DocVerbatim::Msc: 
      {
        static int mscindex = 1;
        QCString baseName(4096);

        baseName.sprintf("%s%d%s",
            (Config_getString(RTF_OUTPUT)+"/inline_mscgraph_").data(), 
            mscindex++,
            ".msc"
           );
        QFile file(baseName);
        if (!file.open(IO_WriteOnly))
        {
          err("Could not open file %s for writing\n",baseName.data());
        }
        QCString text = "msc {";
        text+=s->text();
        text+="}";
        file.writeBlock( text, text.length() );
        file.close();

        writeMscFile(baseName, s->hasCaption());
        visitCaption(this, s->children());
        includePicturePostRTF(true, s->hasCaption());

        if (Config_getBool(DOT_CLEANUP)) file.remove();
      }
      break;
    case DocVerbatim::PlantUML:
      {
        static QCString rtfOutput = Config_getString(RTF_OUTPUT);
        QCString baseName = writePlantUMLSource(rtfOutput,s->exampleFile(),s->text());

        writePlantUMLFile(baseName, s->hasCaption());
        visitCaption(this, s->children());
        includePicturePostRTF(true, s->hasCaption());
      }
      break;
  }
  m_lastIsPara=FALSE;
}
Example #16
0
/*
 * main()
 */
int
main(int ac, char *av[])
{
	char	name[NG_NODESIZ];
	int	interactive = isatty(0) && isatty(1);
	FILE	*fp = NULL;
	int	ch, rtn = 0;

	/* Set default node name */
	snprintf(name, sizeof(name), "ngctl%d", getpid());

	/* Parse command line */
	while ((ch = getopt(ac, av, "df:n:")) != -1) {
		switch (ch) {
		case 'd':
			NgSetDebug(NgSetDebug(-1) + 1);
			break;
		case 'f':
			if (strcmp(optarg, "-") == 0)
				fp = stdin;
			else if ((fp = fopen(optarg, "r")) == NULL)
				err(EX_NOINPUT, "%s", optarg);
			break;
		case 'n':
			snprintf(name, sizeof(name), "%s", optarg);
			break;
		case '?':
		default:
			Usage((char *)NULL);
			break;
		}
	}
	ac -= optind;
	av += optind;

	/* Create a new socket node */
	if (NgMkSockNode(name, &csock, &dsock) < 0)
		err(EX_OSERR, "can't create node");

	/* Do commands as requested */
	if (ac == 0) {
		if (fp != NULL) {
			rtn = ReadFile(fp);
		} else if (interactive) {
			rtn = DoInteractive();
		} else
			Usage("no command specified");
	} else {
		rtn = DoCommand(ac, av);
	}

	/* Convert command return code into system exit code */
	switch (rtn) {
	case CMDRTN_OK:
	case CMDRTN_QUIT:
		rtn = 0;
		break;
	case CMDRTN_USAGE:
		rtn = EX_USAGE;
		break;
	case CMDRTN_ERROR:
		rtn = EX_OSERR;
		break;
	}
	return (rtn);
}
Example #17
0
static void
init_config(struct cfg *cf, int argc, char **argv)
{
    int ch, i, umode, stdio_mode;
    char *bh[2], *bh6[2], *cp, *tp[2];
    const char *errmsg;
    struct passwd *pp;
    struct group *gp;
    double x, y;
    struct rtpp_ctrl_sock *ctrl_sock;

    bh[0] = bh[1] = bh6[0] = bh6[1] = NULL;

    umode = stdio_mode = 0;

    cf->stable->pid_file = PID_FILE;

    cf->stable->port_min = PORT_MIN;
    cf->stable->port_max = PORT_MAX;
    cf->stable->port_ctl = 0;

    cf->stable->advaddr[0] = NULL;
    cf->stable->advaddr[1] = NULL;

    cf->stable->max_ttl = SESSION_TIMEOUT;
    cf->stable->tos = TOS;
    cf->stable->rrtcp = 1;
    cf->stable->ttl_mode = TTL_UNIFIED;
    cf->stable->log_level = -1;
    cf->stable->log_facility = -1;
    cf->stable->sched_offset = 0.0;
    cf->stable->sched_hz = rtpp_get_sched_hz();
    cf->stable->sched_policy = SCHED_OTHER;
    cf->stable->target_pfreq = MIN(POLL_RATE, cf->stable->sched_hz);
#if RTPP_DEBUG
    printf("target_pfreq = %f\n", cf->stable->target_pfreq);
#endif
    cf->stable->slowshutdown = 0;

    cf->timeout_handler = rtpp_th_init();
    if (cf->timeout_handler == NULL)
        err(1, "rtpp_th_init");

    pthread_mutex_init(&cf->glock, NULL);
    pthread_mutex_init(&cf->sessinfo.lock, NULL);
    pthread_mutex_init(&cf->bindaddr_lock, NULL);

    cf->stable->nofile_limit = malloc(sizeof(*cf->stable->nofile_limit));
    if (cf->stable->nofile_limit == NULL)
        err(1, "malloc");
    if (getrlimit(RLIMIT_NOFILE, cf->stable->nofile_limit) != 0)
	err(1, "getrlimit");

    while ((ch = getopt(argc, argv, "vf2Rl:6:s:S:t:r:p:T:L:m:M:u:Fin:Pad:VN:c:A:")) != -1) {
	switch (ch) {
        case 'c':
            if (strcmp(optarg, "fifo") == 0) {
                 cf->stable->sched_policy = SCHED_FIFO;
                 break;
            }
            if (strcmp(optarg, "rr") == 0) {
                 cf->stable->sched_policy = SCHED_RR;
                 break;
            }
            errx(1, "%s: unknown scheduling policy", optarg);
            break;

        case 'N':
	    if (strcmp(optarg, "random") == 0) {
                x = getdtime() * 1000000.0;
                srand48((long)x);
                cf->stable->sched_offset = drand48();
            } else {
                tp[0] = optarg;
                tp[1] = strchr(tp[0], '/');
       	        if (tp[1] == NULL) {
                    errx(1, "%s: -N should be in the format X/Y", optarg);
                }
                *tp[1] = '\0';
                tp[1]++;
                x = (double)strtol(tp[0], &tp[0], 10);
                y = (double)strtol(tp[1], &tp[1], 10);
                cf->stable->sched_offset = x / y;
            }
            x = (double)cf->stable->sched_hz / cf->stable->target_pfreq;
            cf->stable->sched_offset = trunc(x * cf->stable->sched_offset) / x;
            cf->stable->sched_offset /= cf->stable->target_pfreq;
            warnx("sched_offset = %f",  cf->stable->sched_offset);
            break;

	case 'f':
	    cf->stable->nodaemon = 1;
	    break;

	case 'l':
	    bh[0] = optarg;
	    bh[1] = strchr(bh[0], '/');
	    if (bh[1] != NULL) {
		*bh[1] = '\0';
		bh[1]++;
		cf->stable->bmode = 1;
	    }
	    break;

	case '6':
	    bh6[0] = optarg;
	    bh6[1] = strchr(bh6[0], '/');
	    if (bh6[1] != NULL) {
		*bh6[1] = '\0';
		bh6[1]++;
		cf->stable->bmode = 1;
	    }
	    break;

    case 'A':
        if (*optarg == '\0') {
            errx(1, "first advertised address is invalid");
        }
        cf->stable->advaddr[0] = optarg;
        cp = strchr(optarg, '/');
        if (cp != NULL) {
            *cp = '\0';
            cp++;
            if (*cp == '\0') {
                errx(1, "second advertised address is invalid");
            }
        }
        cf->stable->advaddr[1] = cp;
        break;

	case 's':
            ctrl_sock = rtpp_ctrl_sock_parse(optarg);
            if (ctrl_sock == NULL) {
                errx(1, "can't parse control socket argument");
            }
            rtpp_list_append(cf->stable->ctrl_socks, ctrl_sock);
            if (RTPP_CTRL_ISDG(ctrl_sock)) {
                umode = 1;
            } else if (ctrl_sock->type == RTPC_STDIO) {
                stdio_mode = 1;
            }
	    break;

	case 't':
	    cf->stable->tos = atoi(optarg);
	    if (cf->stable->tos > 255)
		errx(1, "%d: TOS is too large", cf->stable->tos);
	    break;

	case '2':
	    cf->stable->dmode = 1;
	    break;

	case 'v':
	    printf("Basic version: %d\n", CPROTOVER);
	    for (i = 1; proto_caps[i].pc_id != NULL; ++i) {
		printf("Extension %s: %s\n", proto_caps[i].pc_id,
		    proto_caps[i].pc_description);
	    }
	    exit(0);
	    break;

	case 'r':
	    cf->stable->rdir = optarg;
	    break;

	case 'S':
	    cf->stable->sdir = optarg;
	    break;

	case 'R':
	    cf->stable->rrtcp = 0;
	    break;

	case 'p':
	    cf->stable->pid_file = optarg;
	    break;

	case 'T':
	    cf->stable->max_ttl = atoi(optarg);
	    break;

	case 'L':
	    cf->stable->nofile_limit->rlim_cur = cf->stable->nofile_limit->rlim_max = atoi(optarg);
	    if (setrlimit(RLIMIT_NOFILE, cf->stable->nofile_limit) != 0)
		err(1, "setrlimit");
	    if (getrlimit(RLIMIT_NOFILE, cf->stable->nofile_limit) != 0)
		err(1, "getrlimit");
	    if (cf->stable->nofile_limit->rlim_max < atoi(optarg))
		warnx("limit allocated by setrlimit (%d) is less than "
		  "requested (%d)", (int) cf->stable->nofile_limit->rlim_max,
		  atoi(optarg));
	    break;

	case 'm':
	    cf->stable->port_min = atoi(optarg);
	    break;

	case 'M':
	    cf->stable->port_max = atoi(optarg);
	    break;

	case 'u':
	    cf->stable->run_uname = optarg;
	    cp = strchr(optarg, ':');
	    if (cp != NULL) {
		if (cp == optarg)
		    cf->stable->run_uname = NULL;
		cp[0] = '\0';
		cp++;
	    }
	    cf->stable->run_gname = cp;
	    cf->stable->run_uid = -1;
	    cf->stable->run_gid = -1;
	    if (cf->stable->run_uname != NULL) {
		pp = getpwnam(cf->stable->run_uname);
		if (pp == NULL)
		    err(1, "can't find ID for the user: %s", cf->stable->run_uname);
		cf->stable->run_uid = pp->pw_uid;
		if (cf->stable->run_gname == NULL)
		    cf->stable->run_gid = pp->pw_gid;
	    }
	    if (cf->stable->run_gname != NULL) {
		gp = getgrnam(cf->stable->run_gname);
		if (gp == NULL)
		    err(1, "can't find ID for the group: %s", cf->stable->run_gname);
		cf->stable->run_gid = gp->gr_gid;
	    }
	    break;

	case 'F':
	    cf->stable->no_check = 1;
	    break;

	case 'i':
	    cf->stable->ttl_mode = TTL_INDEPENDENT;
	    break;

	case 'n':
	    if(strncmp("unix:", optarg, 5) == 0)
		optarg += 5;
	    if(strlen(optarg) == 0)
		errx(1, "timeout notification socket name too short");
            if (rtpp_th_set_sn(cf->timeout_handler, optarg, NULL) == NULL) {
		err(1, "can't allocate memory");
            }
	    break;

	case 'P':
	    cf->stable->record_pcap = 1;
	    break;

	case 'a':
	    cf->stable->record_all = 1;
	    break;

	case 'd':
	    cp = strchr(optarg, ':');
	    if (cp != NULL) {
		cf->stable->log_facility = rtpp_log_str2fac(cp + 1);
		if (cf->stable->log_facility == -1)
		    errx(1, "%s: invalid log facility", cp + 1);
		*cp = '\0';
	    }
	    cf->stable->log_level = rtpp_log_str2lvl(optarg);
	    if (cf->stable->log_level == -1)
		errx(1, "%s: invalid log level", optarg);
	    break;

	case 'V':
	    printf("%s\n", RTPP_SW_VERSION);
	    exit(0);
	    break;

	case '?':
	default:
	    usage();
	}
    }

    /* No control socket has been specified, add a default one */
    if (RTPP_LIST_IS_EMPTY(cf->stable->ctrl_socks)) {
        ctrl_sock = rtpp_ctrl_sock_parse(CMD_SOCK);
        if (ctrl_sock == NULL) {
            errx(1, "can't parse control socket: \"%s\"", CMD_SOCK);
        }
        rtpp_list_append(cf->stable->ctrl_socks, ctrl_sock);
    }

    if (cf->stable->rdir == NULL && cf->stable->sdir != NULL)
	errx(1, "-S switch requires -r switch");

    if (cf->stable->nodaemon == 0 && stdio_mode != 0)
        errx(1, "stdio command mode requires -f switch");

    if (cf->stable->no_check == 0 && getuid() == 0 && cf->stable->run_uname == NULL) {
	if (umode != 0) {
	    errx(1, "running this program as superuser in a remote control "
	      "mode is strongly not recommended, as it poses serious security "
	      "threat to your system. Use -u option to run as an unprivileged "
	      "user or -F is you want to run as a superuser anyway.");
	} else {
	    warnx("WARNING!!! Running this program as superuser is strongly "
	      "not recommended, as it may pose serious security threat to "
	      "your system. Use -u option to run as an unprivileged user "
	      "or -F to surpress this warning.");
	}
    }

    /* make sure that port_min and port_max are even */
    if ((cf->stable->port_min % 2) != 0)
	cf->stable->port_min++;
    if ((cf->stable->port_max % 2) != 0) {
	cf->stable->port_max--;
    } else {
	/*
	 * If port_max is already even then there is no
	 * "room" for the RTCP port, go back by two ports.
	 */
	cf->stable->port_max -= 2;
    }

    if (!IS_VALID_PORT(cf->stable->port_min))
	errx(1, "invalid value of the port_min argument, "
	  "not in the range 1-65535");
    if (!IS_VALID_PORT(cf->stable->port_max))
	errx(1, "invalid value of the port_max argument, "
	  "not in the range 1-65535");
    if (cf->stable->port_min > cf->stable->port_max)
	errx(1, "port_min should be less than port_max");

    cf->sessinfo.sessions = malloc((sizeof cf->sessinfo.sessions[0]) *
      (((cf->stable->port_max - cf->stable->port_min + 1)) + 1));
    cf->rtp_servers =  malloc((sizeof cf->rtp_servers[0]) *
      (((cf->stable->port_max - cf->stable->port_min + 1) * 2) + 1));
    cf->sessinfo.pfds_rtp = malloc((sizeof cf->sessinfo.pfds_rtp[0]) *
      (((cf->stable->port_max - cf->stable->port_min + 1)) + 1));
    cf->sessinfo.pfds_rtcp = malloc((sizeof cf->sessinfo.pfds_rtcp[0]) *
      (((cf->stable->port_max - cf->stable->port_min + 1)) + 1));

    if (bh[0] == NULL && bh[1] == NULL && bh6[0] == NULL && bh6[1] == NULL) {
	bh[0] = "*";
    }

    for (i = 0; i < 2; i++) {
	if (bh[i] != NULL && *bh[i] == '\0')
	    bh[i] = NULL;
	if (bh6[i] != NULL && *bh6[i] == '\0')
	    bh6[i] = NULL;
    }

    i = ((bh[0] == NULL) ? 0 : 1) + ((bh[1] == NULL) ? 0 : 1) +
      ((bh6[0] == NULL) ? 0 : 1) + ((bh6[1] == NULL) ? 0 : 1);
    if (cf->stable->bmode != 0) {
	if (bh[0] != NULL && bh6[0] != NULL)
	    errx(1, "either IPv4 or IPv6 should be configured for external "
	      "interface in bridging mode, not both");
	if (bh[1] != NULL && bh6[1] != NULL)
	    errx(1, "either IPv4 or IPv6 should be configured for internal "
	      "interface in bridging mode, not both");
    if (cf->stable->advaddr[0] != NULL && cf->stable->advaddr[1] == NULL)
        errx(1, "two advertised addresses are required for internal "
          "and external interfaces in bridging mode");
	if (i != 2)
	    errx(1, "incomplete configuration of the bridging mode - exactly "
	      "2 listen addresses required, %d provided", i);
    } else if (i != 1) {
	errx(1, "exactly 1 listen addresses required, %d provided", i);
    }

    for (i = 0; i < 2; i++) {
	cf->stable->bindaddr[i] = NULL;
	if (bh[i] != NULL) {
	    cf->stable->bindaddr[i] = host2bindaddr(cf, bh[i], AF_INET, &errmsg);
	    if (cf->stable->bindaddr[i] == NULL)
		errx(1, "host2bindaddr: %s", errmsg);
	    continue;
	}
	if (bh6[i] != NULL) {
	    cf->stable->bindaddr[i] = host2bindaddr(cf, bh6[i], AF_INET6, &errmsg);
	    if (cf->stable->bindaddr[i] == NULL)
		errx(1, "host2bindaddr: %s", errmsg);
	    continue;
	}
    }
    if (cf->stable->bindaddr[0] == NULL) {
	cf->stable->bindaddr[0] = cf->stable->bindaddr[1];
	cf->stable->bindaddr[1] = NULL;
    }
}
Example #18
0
/*---------------------------------------------------------------------------*/
int
slip_config_handle_arguments(int argc, char **argv)
{
  const char *prog;
  signed char c;
  int baudrate = 115200;

  prog = argv[0];
  while((c = getopt(argc, argv, "c:B:H:D:L:S:hs:t:v::d::a:p:rRfU:D:w:")) != -1) {
    switch (c) {
    case 'c':
      nvm_file = optarg;
      break;

    case 'B':
      baudrate = atoi(optarg);
      break;

    case 'H':
      slip_config_flowcontrol = 1;
      break;

    case 'L':
      if (optarg) {
        Log6lbr_level = atoi(optarg) * 10;
      } else {
        Log6lbr_level = Log6lbr_Level_DEFAULT;
      }
      break;

    case 'S':
      if (optarg) {
        Log6lbr_services = strtol(optarg, NULL, 16);
      } else {
        Log6lbr_services = Log6lbr_Service_DEFAULT;
      }
      break;

    case 's':
      if(strncmp("/dev/", optarg, 5) == 0) {
        slip_config_siodev = optarg + 5;
      } else {
        slip_config_siodev = optarg;
      }
      break;

    case 't':
      if(strncmp("/dev/", optarg, 5) == 0) {
        strncpy(slip_config_tundev, optarg + 5, sizeof(slip_config_tundev));
      } else {
        strncpy(slip_config_tundev, optarg, sizeof(slip_config_tundev));
      }
      break;

    case 'a':
      slip_config_host = optarg;
      break;

    case 'p':
      slip_config_port = optarg;
      break;

    case 'd':
      slip_config_basedelay = 10;
      if(optarg)
        slip_config_basedelay = atoi(optarg);
      break;

    case 'r':
      use_raw_ethernet = 1;
      break;

    case 'R':
      use_raw_ethernet = 0;
      break;

    case 'f':
      ethernet_has_fcs = 1;
      break;

    case 'U':
      slip_config_ifup_script = optarg;
      break;

    case 'D':
      slip_config_ifdown_script = optarg;
      break;

    case 'w':
      slip_config_www_root = optarg;
      break;

    case 'v':
      printf("Warning: -v option is deprecated, use -L and -S instead\n");
      break;

    case '?':
    case 'h':
    default:
      fprintf(stderr, "usage:  %s [options] ipaddress\n", prog);
      fprintf(stderr, "example: %s -L -v2 -s ttyUSB1\n", prog);
      fprintf(stderr, "Options are:\n");
#ifdef linux
      fprintf(stderr,
              " -B baudrate    9600,19200,38400,57600,115200,921600 (default 115200)\n");
#else
      fprintf(stderr,
              " -B baudrate    9600,19200,38400,57600,115200 (default 115200)\n");
#endif
      fprintf(stderr,
              " -H             Hardware CTS/RTS flow control (default disabled)\n");
      fprintf(stderr,
              " -s siodev      Serial device (default /dev/ttyUSB0)\n");
      fprintf(stderr,
              " -a host        Connect via TCP to server at <host>\n");
      fprintf(stderr,
              " -p port        Connect via TCP to server at <host>:<port>\n");
      fprintf(stderr, " -t dev         Name of interface (default eth0)\n");
      fprintf(stderr, " -r	        Use Raw Ethernet interface\n");
      fprintf(stderr, " -R             Use Tap Ethernet interface\n");
      fprintf(stderr, " -f             Raw Ethernet frames contains FCS\n");
      fprintf(stderr,
              " -d[basedelay]  Minimum delay between outgoing SLIP packets.\n");
      fprintf(stderr,
              "                Actual delay is basedelay*(#6LowPAN fragments) milliseconds.\n");
      fprintf(stderr, "                -d is equivalent to -d10.\n");
      fprintf(stderr, " -L[level]      Log level\n");
      fprintf(stderr, " -S[services]   Log services\n");
      fprintf(stderr, " -c conf        Configuration file (nvm file)\n");
      fprintf(stderr, " -U script      Interface up configuration script\n");
      fprintf(stderr,
              " -D script      Interface down configuration script\n");
      exit(1);
      break;
    }
  }
  argc -= optind - 1;
  argv += optind - 1;

  if(argc > 1) {
    err(1,
        "usage: %s [-B baudrate] [-H] [-L log] [-S services] [-s siodev] [-t dev] [-d delay] [-a serveraddress] [-p serverport] [-c conf] [-U ifup] [-D ifdown]",
        prog);
  }

  switch (baudrate) {
  case -2:
    break;                      /* Use default. */
  case 9600:
    slip_config_b_rate = B9600;
    break;
  case 19200:
    slip_config_b_rate = B19200;
    break;
  case 38400:
    slip_config_b_rate = B38400;
    break;
  case 57600:
    slip_config_b_rate = B57600;
    break;
  case 115200:
    slip_config_b_rate = B115200;
    break;
#ifdef linux
  case 921600:
    slip_config_b_rate = B921600;
    break;
#endif
  default:
    err(1, "unknown baudrate %d", baudrate);
    break;
  }

  if(*slip_config_tundev == '\0') {
    /* Use default. */
    strcpy(slip_config_tundev, "eth0");
  }
  if(nvm_file == NULL) {
    nvm_file = default_nvm_file;
  }

  printf("Log level : %d\n", Log6lbr_level);
  printf("Log services : %x\n", Log6lbr_services);
  return 1;
}
int main(int argc, char **argv)
{
	char *p;
	int c;
	int len = HPS;
	int inject = 0;
	int collapse = 0;
	int mremap_flag = 0;
	int pfn_get = 0;
	int split = 0;
	int verbose = 0;
	char buf[256];
	uint64_t pfn_buf[10];

	while ((c = getopt(argc, argv, "m:w:crpsiv")) != -1) {
		switch (c) {
		case 'm':
			len = strtol(optarg, NULL, 10) * HPS;
			break;
		case 'c':
			collapse = 1;
			break;
		case 'r':
			mremap_flag = 1;
			break;
		case 'p':
			pfn_get = 1;
			break;
		case 's':
			split = 1;
			break;
		case 'i':
			inject = 1;
			break;
		case 'v':
			verbose = 1;
			break;
		default:
			usage(argv[0]);
		}
	}

	signal(SIGUSR1, sighandler);

	p = mmap_check((void *)0x7f0000000000, len, PROTECTION,
		       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	Dprintf(verbose, "p = %p\n", p);
	madvise(p, len, MADV_HUGEPAGE);

	/* directly allocate thp in page fault. */
	write_bytes(p, len);
	pause();

	if (inject)
		madvise(p, 1, MADV_SOFT_OFFLINE);

	if (split) {
		mlock(p, 4096);
		munlock(p, 4096);
	}

	if (mremap_flag) {
		Dprintf(verbose, "mremap old p is %p!\n", p);
		p = mremap(p, len, len + HPS, 0, MREMAP_FIXED);
		/* p = mremap(p, len, len + HPS, 0, NULL); */
		if (p == (void *)-1)
			err("mremap");
		Dprintf(verbose, "mremap new p is %p!\n", p);
	}

	/* splitted thp will be collapsed again in the next khugepaged scan */
	if (split && collapse) {
		/* split thp */
		write_bytes(p, len);
	}
	pause();

	munmap(p, len);
	return 0;
}
Example #20
0
File: much.c Project: gabc/much
int
main(int argc, char **argv)
{
        FILE *fp;
        FILE *in;

        if(argc == 2){
                fp = fopen(argv[1], "r");
                in = stdin;
        } else {
                fp = stdin;
                in = fopen("/dev/tty", "r");
        }
        if(!fp || !in)
                err(1, "Cannot open files");


        signal(SIGINT, finish);

        (void) initscr();
        (void) keypad(stdscr, TRUE);
        (void) nonl();
        (void) cbreak();
        (void) noecho();

        (void) read_file(fp);

        v_end = LINES;
        (void) repaint();

	lastreg = malloc(80 * sizeof(char*));
	if(!lastreg)
		err(1, "can't lastreg");

        for(;;){
                int c = getch();
                switch(c){
                case 'j':
                        godown();
                        break;
                case 'k':
                        goup();
                        break;
                case '<':
                        gostart();
                        break;
                case '>':
                        goend();
                        break;
                case 'q':
                        finish(0);
                        break;
		case KEY_NPAGE:
		case ' ':
			downpage();
			break;
		case KEY_PPAGE:
		case KEY_BACKSPACE:
			uppage();
			break;
		case '/':
			dosearch();
			break;
		case '?':
			dobacksearch();
			break;
		case 12: /* ^L */
			repaint();
			break;
                }
        }
}
Example #21
0
int main(int argc, char **argv)
{
	int permission = 0644;
	int opt;
	size_t size = 0;
	int nsems = 0;
	int ask_shm = 0, ask_msg = 0, ask_sem = 0;
	static const struct option longopts[] = {
		{"shmem", required_argument, NULL, 'M'},
		{"semaphore", required_argument, NULL, 'S'},
		{"queue", no_argument, NULL, 'Q'},
		{"mode", required_argument, NULL, 'p'},
		{"version", no_argument, NULL, 'V'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while((opt = getopt_long(argc, argv, "hM:QS:p:Vh", longopts, NULL)) != -1) {
		switch(opt) {
		case 'M':
			size = strtou64_or_err(optarg, _("failed to parse size"));
			ask_shm = 1;
			break;
		case 'Q':
			ask_msg = 1;
			break;
		case 'S':
			nsems = strtos32_or_err(optarg, _("failed to parse elements"));
			ask_sem = 1;
			break;
		case 'p':
			permission = strtoul(optarg, NULL, 8);
			break;
		case 'h':
			usage(stdout);
			break;
		case 'V':
			printf(UTIL_LINUX_VERSION);
			return EXIT_SUCCESS;
		default:
			ask_shm = ask_msg = ask_sem = 0;
			break;
		}
	}

	if(!ask_shm && !ask_msg && !ask_sem)
		usage(stderr);

	if (ask_shm) {
		int shmid;
		if (-1 == (shmid = create_shm(size, permission)))
			err(EXIT_FAILURE, _("create share memory failed"));
		else
			printf(_("Shared memory id: %d\n"), shmid);
	}

	if (ask_msg) {
		int msgid;
		if (-1 == (msgid = create_msg(permission)))
			err(EXIT_FAILURE, _("create message queue failed"));
		else
			printf(_("Message queue id: %d\n"), msgid);
	}

	if (ask_sem) {
		int semid;
		if (-1 == (semid = create_sem(nsems, permission)))
			err(EXIT_FAILURE, _("create semaphore failed"));
		else
			printf(_("Semaphore id: %d\n"), semid);
	}

	return EXIT_SUCCESS;
}
Example #22
0
/* readelfheader() reads the ELF header into our global variable, and
 * checks to make sure that this is in fact a file that we should be
 * munging.
 */
static int readelfheader(int fd, Elf_Ehdr *ehdr) {
    errno = 0;
    if (read(fd, ehdr, sizeof *ehdr) != sizeof *ehdr) {
	return ferr("missing or incomplete ELF header.");
    }

    /* Check the ELF signature.
     */
    if (!(ehdr->e_ident[EI_MAG0] == ELFMAG0 &&
	  ehdr->e_ident[EI_MAG1] == ELFMAG1 &&
	  ehdr->e_ident[EI_MAG2] == ELFMAG2 &&
	  ehdr->e_ident[EI_MAG3] == ELFMAG3)) {
	printf("missing ELF signature.");
        exit(0);
    }

    if (ehdr->e_ident[EI_CLASS] != ELF_CLASS) {
       err("ELF file has different word size.");
    }

    /* Compare the file's class and endianness with the program's.
     */

   if (ELF_DATA == ELFDATA2LSB) {         /* 2's complement, little endian */
      if (!little_endian) {
         fprintf(stderr,"Warning!  Host and target endianess don't match!\n");
	 swap_bytes=1;
      }
   }
   else if (ELF_DATA == ELFDATA2MSB) {    /* 2's complement, big endian */
      if (little_endian) {
         fprintf(stderr,"Warning!  Host and target endianess don't match!\n");
	 swap_bytes=1;
      }
   }
   else {
      err("Unknown endianess type.");
   }

   if (ELF_CLASS == ELFCLASS64) {
      if (sizeof(void *)!=8) err("host!=elf word size not supported");
   }
   else if (ELF_CLASS == ELFCLASS32) {
      if (sizeof(void *)!=4) err("host!=elf word size not supported");
   }
   else {
      err("Unknown word size");
   }

    if (ehdr->e_ident[EI_DATA] != ELF_DATA) {
       err("ELF file has different endianness.");
    }

    /* Check the target architecture.
     */
     { unsigned short machine;
       machine=ehdr->e_machine;
       if (swap_bytes) machine=bswap_16(machine);

       if (machine != ELF_ARCH) {
          fprintf(stderr, "Warning!  "
	       "ELF file created for different architecture: %d\n",
	       ehdr->e_machine);
       }
     }

    /* Verify the sizes of the ELF header and the program segment
     * header table entries.
     */
     { short ehsize;
	ehsize=ehdr->e_ehsize;
	if (swap_bytes) ehsize=bswap_16(ehsize);

	if (ehsize != sizeof(Elf_Ehdr)) {
           fprintf(stderr,"Warning! "
	       "unrecognized ELF header size: %d != %ld\n",
	       ehdr->e_ehsize,(long)sizeof(Elf_Ehdr));
	}
     }

     {
	short phentsize;
	phentsize=ehdr->e_phentsize;
	if (swap_bytes) phentsize=bswap_16(phentsize);

        if (phentsize != sizeof(Elf_Phdr)) {
           fprintf(stderr,"Warning! "
	      "unrecognized program segment header size: %d != %ld\n",
	      ehdr->e_phentsize,(long)sizeof(Elf_Phdr));
	}
     }

    /* Finally, check the file type.
     */
     {short e_type;
      e_type=ehdr->e_type;
      if (swap_bytes) e_type=bswap_16(e_type);
	
      if (e_type != ET_EXEC && e_type != ET_DYN) {
	return err("not an executable or shared-object library.");
      }
     }
   
    return 1;
}
Example #23
0
/*
 * Convert an expression of the following forms to an off_t.  This is the
 * same as get_num(), but it uses signed numbers.
 *
 * The major problem here is that an off_t may not necessarily be a intmax_t.
 */
static off_t
get_off_t(const char *val)
{
	intmax_t num, mult, prevnum;
	char *expr;

	errno = 0;
	num = strtoq(val, &expr, 0);
	if (errno != 0)				/* Overflow or underflow. */
		err(1, "%s", oper);
	
	if (expr == val)			/* No valid digits. */
		errx(1, "%s: illegal numeric value", oper);

	mult = 0;
	switch (*expr) {
	case 'B':
	case 'b':
		mult = 512;
		break;
	case 'K':
	case 'k':
		mult = 1 << 10;
		break;
	case 'M':
	case 'm':
		mult = 1 << 20;
		break;
	case 'G':
	case 'g':
		mult = 1 << 30;
		break;
	case 'W':
	case 'w':
		mult = sizeof(int);
		break;
	}

	if (mult != 0) {
		prevnum = num;
		num *= mult;
		/* Check for overflow. */
		if ((prevnum > 0) != (num > 0) || num / mult != prevnum)
			goto erange;
		expr++;
	}

	switch (*expr) {
		case '\0':
			break;
		case '*':			/* Backward compatible. */
		case 'X':
		case 'x':
			mult = (intmax_t)get_off_t(expr + 1);
			prevnum = num;
			num *= mult;
			if ((prevnum > 0) == (num > 0) && num / mult == prevnum)
				break;
erange:
			errx(1, "%s: %s", oper, strerror(ERANGE));
		default:
			errx(1, "%s: illegal numeric value", oper);
	}
	return (num);
}
Example #24
0
static void
setthetime(const char *fmt, const char *p, int jflag, int nflag)
{
	struct tm *lt;
	struct timeval tv;
	const char *dot, *t;
	int century;

	if (fmt != NULL) {
		lt = localtime(&tval);
		t = strptime(p, fmt, lt);
		if (t == NULL) {
			fprintf(stderr, "Failed conversion of ``%s''"
				" using format ``%s''\n", p, fmt);
			badformat();
		} else if (*t != '\0')
			fprintf(stderr, "Warning: Ignoring %ld extraneous"
				" characters in date string (%s)\n",
				(long) strlen(t), t);
	} else {
		for (t = p, dot = NULL; *t; ++t) {
			if (isdigit(*t))
				continue;
			if (*t == '.' && dot == NULL) {
				dot = t;
				continue;
			}
			badformat();
		}

		lt = localtime(&tval);

		if (dot != NULL) {			/* .ss */
			dot++; /* *dot++ = '\0'; */
			if (strlen(dot) != 2)
				badformat();
			lt->tm_sec = ATOI2(dot);
			if (lt->tm_sec > 61)
				badformat();
		} else
			lt->tm_sec = 0;

		century = 0;
		/* if p has a ".ss" field then let's pretend it's not there */
		switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
		case 12:				/* cc */
			lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
			century = 1;
			/* FALLTHROUGH */
		case 10:				/* yy */
			if (century)
				lt->tm_year += ATOI2(p);
			else {				/* hack for 2000 ;-} */
				lt->tm_year = ATOI2(p);
				if (lt->tm_year < 69)
					lt->tm_year += 2000 - TM_YEAR_BASE;
				else
					lt->tm_year += 1900 - TM_YEAR_BASE;
			}
			/* FALLTHROUGH */
		case 8:					/* mm */
			lt->tm_mon = ATOI2(p);
			if (lt->tm_mon > 12)
				badformat();
			--lt->tm_mon;		/* time struct is 0 - 11 */
			/* FALLTHROUGH */
		case 6:					/* dd */
			lt->tm_mday = ATOI2(p);
			if (lt->tm_mday > 31)
				badformat();
			/* FALLTHROUGH */
		case 4:					/* HH */
			lt->tm_hour = ATOI2(p);
			if (lt->tm_hour > 23)
				badformat();
			/* FALLTHROUGH */
		case 2:					/* MM */
			lt->tm_min = ATOI2(p);
			if (lt->tm_min > 59)
				badformat();
			break;
		default:
			badformat();
		}
	}

	/* Let mktime() decide whether summer time is in effect. */
	lt->tm_isdst = -1;

	/* convert broken-down time to GMT clock time */
	if ((tval = mktime(lt)) == -1)
		errx(1, "nonexistent time");

	if (!jflag) {
		/* set the time */
		if (nflag || netsettime(tval)) {
			logwtmp("|", "date", "");
			tv.tv_sec = tval;
			tv.tv_usec = 0;
			if (settimeofday(&tv, NULL))
				err(1, "settimeofday (timeval)");
			logwtmp("{", "date", "");
		}

		if ((p = getlogin()) == NULL)
			p = "???";
		syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
	}
}
Example #25
0
int
main(int argc, char **argv)
{
    struct sockaddr_un servaddr;
    int listenfd, connfd, pid;
    u_int counter, ncpus;
    size_t len;

    len = sizeof(ncpus);
    if (sysctlbyname("kern.smp.cpus", &ncpus, &len, NULL, 0) < 0)
        err(1, "kern.smp.cpus");
    if (len != sizeof(ncpus))
        errx(1, "kern.smp.cpus: invalid length");
    if (ncpus < 2)
        warnx("SMP not present, test may be unable to trigger race");

    /*
     * Create a UNIX domain socket that the child will repeatedly
     * accept() from, and that the parent will repeatedly connect() to.
     */
    if ((listenfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0)
        err(1, "parent: socket error");
    (void)unlink(UNIXSTR_PATH);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sun_family = AF_LOCAL;
    strcpy(servaddr.sun_path, UNIXSTR_PATH);
    if (bind(listenfd, (struct sockaddr *) &servaddr,
             sizeof(servaddr)) < 0)
        err(1, "parent: bind error");
    if (listen(listenfd, 1024) < 0)
        err(1, "parent: listen error");

    pid = fork();
    if (pid == -1)
        err(1, "fork()");
    if (pid != 0) {
        /*
         * In the parent, repeatedly connect and disconnect from the
         * socket, attempting to induce the race.
         */
        close(listenfd);
        sleep(1);
        bzero(&servaddr, sizeof(servaddr));
        servaddr.sun_family = AF_LOCAL;
        strcpy(servaddr.sun_path, UNIXSTR_PATH);
        for (counter = 0; counter < LOOPS; counter++) {
            if ((connfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
                (void)kill(pid, SIGTERM);
                err(1, "parent: socket error");
            }
            if (connect(connfd, (struct sockaddr *)&servaddr,
                        sizeof(servaddr)) < 0) {
                (void)kill(pid, SIGTERM);
                err(1, "parent: connect error");
            }
            if (close(connfd) < 0) {
                (void)kill(pid, SIGTERM);
                err(1, "parent: close error");
            }
            usleep(USLEEP);
        }
        (void)kill(pid, SIGTERM);
    } else {
        /*
         * In the child, loop accepting and closing.  We may pick up
         * the race here so report errors from close().
         */
        for ( ; ; ) {
            if ((connfd = accept(listenfd,
                                 (struct sockaddr *)NULL, NULL)) < 0)
                err(1, "child: accept error");
            if (close(connfd) < 0)
                err(1, "child: close error");
        }
    }
    printf("OK\n");
    exit(0);
}
Example #26
0
int
main(int argc, char **argv)
{
	struct timezone tz;
	int ch, rflag;
	int jflag, nflag;
	const char *format;
	char buf[1024];
	char *endptr, *fmt;
	char *tmp;
	int set_timezone;
	struct vary *v;
	const struct vary *badv;
	struct tm lt;

	v = NULL;
	fmt = NULL;
	setlocale(LC_TIME, "");
	tz.tz_dsttime = tz.tz_minuteswest = 0;
	rflag = 0;
	jflag = nflag = 0;
	set_timezone = 0;
	while ((ch = getopt(argc, argv, "d:f:jnr:t:uv:")) != -1)
		switch(ch) {
		case 'd':		/* daylight savings time */
			tz.tz_dsttime = strtol(optarg, &endptr, 10) ? 1 : 0;
			if (endptr == optarg || *endptr != '\0')
				usage();
			set_timezone = 1;
			break;
		case 'f':
			fmt = optarg;
			break;
		case 'j':
			jflag = 1;	/* don't set time */
			break;
		case 'n':		/* don't set network */
			nflag = 1;
			break;
		case 'r':		/* user specified seconds */
			rflag = 1;
			tval = strtoll(optarg, &tmp, 0);
			if (*tmp != 0)
				usage();
			break;
		case 't':		/* minutes west of UTC */
					/* error check; don't allow "PST" */
			tz.tz_minuteswest = strtol(optarg, &endptr, 10);
			if (endptr == optarg || *endptr != '\0')
				usage();
			set_timezone = 1;
			break;
		case 'u':		/* do everything in UTC */
			if (setenv("TZ", "UTC0", 1) != 0)
				err(1, "setenv: cannot set TZ=UTC0");
			break;
		case 'v':
			v = vary_append(v, optarg);
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	/*
	 * If -d or -t, set the timezone or daylight savings time; this
	 * doesn't belong here; the kernel should not know about either.
	 */
	if (set_timezone && settimeofday(NULL, &tz))
		err(1, "settimeofday (timezone)");

	if (!rflag && time(&tval) == -1)
		err(1, "time");

	format = "%+";

	/* allow the operands in any order */
	if (*argv && **argv == '+') {
		format = *argv + 1;
		++argv;
	}

	if (*argv) {
		setthetime(fmt, *argv, jflag, nflag);
		++argv;
	} else if (fmt != NULL)
		usage();

	if (*argv && **argv == '+')
		format = *argv + 1;

	lt = *localtime(&tval);
	badv = vary_apply(v, &lt);
	if (badv) {
		fprintf(stderr, "%s: Cannot apply date adjustment\n",
			badv->arg);
		vary_destroy(v);
		usage();
	}
	vary_destroy(v);
	strftime(buf, sizeof(buf), format, &lt);
	printf("%s\n", buf);
	if (fflush(stdout) != 0)
		err(1, "stdout");
	exit(retval);
}
Example #27
0
    int
main(int argc, char *argv[])
{
    EPCAP_STATE *ep = NULL;
    pid_t pid = 0;
    int ch = 0;
    int fd = 0;


    IS_NULL(ep = calloc(1, sizeof(EPCAP_STATE)));

    ep->snaplen = SNAPLEN;
    ep->timeout = TIMEOUT;

    while ( (ch = getopt(argc, argv, "d:f:g:hi:MPs:t:u:v")) != -1) {
        switch (ch) {
            case 'd':   /* chroot directory */
                IS_NULL(ep->chroot = strdup(optarg));
                break;
            case 'f':
                IS_NULL(ep->file = strdup(optarg));
                ep->runasuser = 1;
                break;
            case 'g':
                IS_NULL(ep->group = strdup(optarg));
                break;
            case 'i':
                IS_NULL(ep->dev = strdup(optarg));
                break;
            case 'M':
                ep->rfmon = 1;
                break;
            case 'P':
                ep->promisc = 1;
                break;
            case 's':
                ep->snaplen = (size_t)atoi(optarg);
                break;
            case 't':
                ep->timeout = (u_int32_t)atoi(optarg);
                break;
            case 'u':
                IS_NULL(ep->user = strdup(optarg));
                break;
            case 'v':
                ep->verbose++;
                break;
            case 'h':
            default:
                usage(ep);
        }
    }

    argc -= optind;
    argv += optind;

    IS_NULL(ep->filt = strdup( (argc == 1) ? argv[0] : EPCAP_FILTER));

    IS_LTZERO(fd = open("/dev/null", O_RDWR));

    epcap_priv_issetuid(ep);
    IS_LTZERO(epcap_open(ep));
    if (epcap_priv_drop(ep) < 0)
        exit (1);

    signal(SIGCHLD, gotsig);

    switch (pid = fork()) {
        case -1:
            err(EXIT_FAILURE, "fork");
        case 0:
            IS_LTZERO(dup2(fd, STDIN_FILENO));
            IS_LTZERO(close(fd));
            IS_LTZERO(epcap_init(ep));
            IS_LTZERO(epcap_priv_rlimits(EPCAP_RLIMIT_NOFILES));
            epcap_loop(ep);
            break;
        default:
            if ( (dup2(fd, STDOUT_FILENO) < 0) ||
                (close(fd) < 0))
                goto CLEANUP;

            pcap_close(ep->p);

            if (epcap_priv_rlimits(0) < 0)
                goto CLEANUP;

            epcap_watch();

CLEANUP:
            (void)kill(pid, SIGTERM);
            break;
    }

    exit (0);
}
Example #28
0
/**
 * Perform some basic functional tests on the driver;
 * make sure we can collect data from the sensor in polled
 * and automatic modes.
 */
void
test()
{
	struct distance_sensor_s report;
	ssize_t sz;

	int fd = open(RANGE_FINDER0_DEVICE_PATH, O_RDONLY);

	if (fd < 0) {
		err(1, "%s open failed (try 'sf0x start' if the driver is not running", RANGE_FINDER0_DEVICE_PATH);
	}

	/* do a simple demand read */
	sz = read(fd, &report, sizeof(report));

	if (sz != sizeof(report)) {
		err(1, "immediate read failed");
	}

	warnx("single read");
	warnx("measurement:  %0.2f m", (double)report.current_distance);
	warnx("time: %llu", report.timestamp);

	/* start the sensor polling at 2 Hz rate */
	if (OK != ioctl(fd, SENSORIOCSPOLLRATE, 2)) {
		errx(1, "failed to set 2Hz poll rate");
	}

	/* read the sensor 5x and report each value */
	for (unsigned i = 0; i < 5; i++) {
		struct pollfd fds;

		/* wait for data to be ready */
		fds.fd = fd;
		fds.events = POLLIN;
		int ret = poll(&fds, 1, 2000);

		if (ret != 1) {
			warnx("timed out");
			break;
		}

		/* now go get it */
		sz = read(fd, &report, sizeof(report));

		if (sz != sizeof(report)) {
			warnx("read failed: got %d vs exp. %d", sz, sizeof(report));
			break;
		}

		warnx("read #%u", i);
		warnx("valid %u", (float)report.current_distance > report.min_distance
			&& (float)report.current_distance < report.max_distance ? 1 : 0);
		warnx("measurement:  %0.3f m", (double)report.current_distance);
		warnx("time: %llu", report.timestamp);
	}

	/* reset the sensor polling to the default rate */
	if (OK != ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT)) {
		errx(1, "ERR: DEF RATE");
	}

	errx(0, "PASS");
}
Example #29
0
int
main(int argc, char **argv)
{
    struct iperf_test *test;

    // XXX: Setting the process affinity requires root on most systems.
    //      Is this a feature we really need?
#ifdef TEST_PROC_AFFINITY
    /* didnt seem to work.... */
    /*
     * increasing the priority of the process to minimise packet generation
     * delay
     */
    int rc = setpriority(PRIO_PROCESS, 0, -15);

    if (rc < 0) {
        perror("setpriority:");
        fprintf(stderr, "setting priority to valid level\n");
        rc = setpriority(PRIO_PROCESS, 0, 0);
    }
    
    /* setting the affinity of the process  */
    cpu_set_t cpu_set;
    int affinity = -1;
    int ncores = 1;

    sched_getaffinity(0, sizeof(cpu_set_t), &cpu_set);
    if (errno)
        perror("couldn't get affinity:");

    if ((ncores = sysconf(_SC_NPROCESSORS_CONF)) <= 0)
        err("sysconf: couldn't get _SC_NPROCESSORS_CONF");

    CPU_ZERO(&cpu_set);
    CPU_SET(affinity, &cpu_set);
    if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0)
        err("couldn't change CPU affinity");
#endif

    test = iperf_new_test();
    if (!test)
        iperf_errexit(NULL, "create new test error - %s", iperf_strerror(i_errno));
    iperf_defaults(test);	/* sets defaults */

    /* This main program doesn't use SIGALRM, so the iperf API may use it. */
    iperf_set_test_may_use_sigalrm(test, 1);

    if (iperf_parse_arguments(test, argc, argv) < 0) {
        iperf_err(test, "parameter error - %s", iperf_strerror(i_errno));
        fprintf(stderr, "\n");
        usage_long();
        exit(1);
    }

    if (run(test) < 0)
        iperf_errexit(test, "error - %s", iperf_strerror(i_errno));

    iperf_free_test(test);

    return 0;
}
Example #30
0
static void
dofsizes(int fd, struct fs *super, char *name)
{
	ino_t inode, maxino;
	union dinode *dp;
	daddr_t sz, ksz;
	struct fsizes *fp, **fsp;
	int i;

	maxino = super->fs_ncg * super->fs_ipg - 1;
#ifdef	COMPAT
	if (!(fsizes = (struct fsizes *)malloc(sizeof(struct fsizes))))
		errx(1, "allocate fsize structure");
#endif	/* COMPAT */
	for (inode = 0; inode < maxino; inode++) {
		errno = 0;
		if ((dp = get_inode(fd,super,inode))
#ifdef	COMPAT
		    && ((DIP(super, dp, di_mode) & IFMT) == IFREG
			|| (DIP(super, dp, di_mode) & IFMT) == IFDIR)
#else	/* COMPAT */
		    && !isfree(super, dp)
#endif	/* COMPAT */
		    ) {
			sz = estimate ? virtualblocks(super, dp) :
			    actualblocks(super, dp);
#ifdef	COMPAT
			if (sz >= FSZCNT) {
				fsizes->fsz_count[FSZCNT-1]++;
				fsizes->fsz_sz[FSZCNT-1] += sz;
			} else {
				fsizes->fsz_count[sz]++;
				fsizes->fsz_sz[sz] += sz;
			}
#else	/* COMPAT */
			ksz = SIZE(sz);
			for (fsp = &fsizes; (fp = *fsp); fsp = &fp->fsz_next) {
				if (ksz < fp->fsz_last)
					break;
			}
			if (!fp || ksz < fp->fsz_first) {
				if (!(fp = (struct fsizes *)
				    malloc(sizeof(struct fsizes))))
					errx(1, "allocate fsize structure");
				fp->fsz_next = *fsp;
				*fsp = fp;
				fp->fsz_first = (ksz / FSZCNT) * FSZCNT;
				fp->fsz_last = fp->fsz_first + FSZCNT;
				for (i = FSZCNT; --i >= 0;) {
					fp->fsz_count[i] = 0;
					fp->fsz_sz[i] = 0;
				}
			}
			fp->fsz_count[ksz % FSZCNT]++;
			fp->fsz_sz[ksz % FSZCNT] += sz;
#endif	/* COMPAT */
		} else if (errno) {
			err(1, "%s", name);
		}
	}
	sz = 0;
	for (fp = fsizes; fp; fp = fp->fsz_next) {
		for (i = 0; i < FSZCNT; i++) {
			if (fp->fsz_count[i])
				printf("%jd\t%jd\t%d\n",
				    (intmax_t)(fp->fsz_first + i),
				    (intmax_t)fp->fsz_count[i],
				    SIZE(sz += fp->fsz_sz[i]));
		}
	}
}