Example #1
0
void CProjExt::DoDataExchange(CDataExchange* pDX)
{
  proj_extension tmp;
  CComboBox *cb2;
  CButton *cb;
  CWnd *cw;
  CString tmpstr;
  int i,j,k;
  int flg;

  memcpy(&tmp,&the_projectile.extension,sizeof(proj_extension));
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CProjExt)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP

  tmpstr.Format("0x%02x",the_projectile.extension.aoe);
  DDX_Text(pDX, IDC_ATTR, tmpstr);
  the_projectile.extension.aoe=(short) strtonum(tmpstr);

  DDX_Text(pDX, IDC_UNKNOWN2, the_projectile.extension.flags);

  tmpstr=convert_radius(the_projectile.extension.tradius);
  DDX_Text(pDX, IDC_TRIGGER, tmpstr);
  the_projectile.extension.tradius=(short) strtonum(tmpstr);

  tmpstr=convert_radius(the_projectile.extension.radius);
  DDX_Text(pDX, IDC_AREA, tmpstr);
  the_projectile.extension.radius=(short) strtonum(tmpstr);

  RetrieveResref(tmpstr, the_projectile.extension.wavc1);
  DDX_Text(pDX, IDC_SOUND, tmpstr);
  DDV_MaxChars(pDX, tmpstr, 8);
  StoreResref(tmpstr, the_projectile.extension.wavc1);

  DDX_Text(pDX, IDC_DELAY, the_projectile.extension.delay);

  tmpstr.Format("0x%04x %s",the_projectile.extension.fragmentanim,IDSToken("ANIMATE",the_projectile.extension.fragmentanim, false) );
  DDX_Text(pDX, IDC_FRAGMENT, tmpstr);
  k=IDSKey2("ANIMATE", tmpstr);
  the_projectile.extension.fragmentanim=(unsigned short) k;

  DDX_Text(pDX, IDC_DURATION, the_projectile.extension.duration);

  if(pDX->m_bSaveAndValidate==UD_DISPLAY)
  {
    cb2=(CComboBox *) GetDlgItem(IDC_EXPLOSION);
    tmpstr.Format("0x%02x",the_projectile.extension.expgr2);
    k=cb2->SelectString(0,tmpstr);
    if(k==-1)
    {
      tmpstr.Format("0x%02x unknown",the_projectile.extension.expgr2);
    }
    else
    {
      cb2->GetLBText(k,tmpstr);
    }
  }
  DDX_Text(pDX, IDC_EXPLOSION, tmpstr); //first projectile
  the_projectile.extension.expgr2=(unsigned char) strtonum(tmpstr);

  tmpstr=colortitle(the_projectile.extension.expclr);
  DDX_Text(pDX, IDC_COLOR, tmpstr);
  the_projectile.extension.expclr=(short) strtonum(tmpstr);

  tmpstr=get_projectile_id(the_projectile.extension.proref+1,1);
  DDX_Text(pDX, IDC_UNKNOWN14, tmpstr);
  the_projectile.extension.proref=(short) strtonum(tmpstr);

  tmpstr=get_projectile_id(the_projectile.extension.projectile,0);
  DDX_Text(pDX, IDC_PROJECTILE, tmpstr);
  the_projectile.extension.projectile=(short) strtonum(tmpstr);

  RetrieveResref(tmpstr, the_projectile.extension.vvc);
  DDX_Text(pDX, IDC_VVC, tmpstr);
  DDV_MaxChars(pDX, tmpstr, 8);
  StoreResref(tmpstr, the_projectile.extension.vvc);

  tmpstr=convert_degree(the_projectile.extension.conewidth);
  DDX_Text(pDX, IDC_CONESIZE, tmpstr);
  the_projectile.extension.conewidth=(short) strtonum(tmpstr);

  j=1;
  for(i=0;i<16;i++)
  {
    cb=(CButton *) GetDlgItem(IDC_ATTR1+i);
    flg=!!(the_projectile.extension.aoe&j);
    cb->SetCheck(flg);
    j<<=1;
    if(extensioncontrols[i])
    {
      for(k=0;extensioncontrols[i][k];k++)
      {
        cw=GetDlgItem(extensioncontrols[i][k]);
        cw->EnableWindow(flg);
      }
    }
  }
  if(memcmp(&tmp,&the_projectile.extension,sizeof(proj_extension)))
  {
    the_projectile.m_changed=true;
  }
}
Example #2
0
int
main(int argc, char *argv[])
{
	struct rlimit rlp;
	struct addrinfo hints, *res;
	struct event ev_sighup, ev_sigint, ev_sigterm;
	int ch, error, listenfd, on;
	const char *errstr;

	/* Defaults. */
	anonymous_only	= 0;
	daemonize	= 1;
	fixed_proxy	= NULL;
	fixed_server	= NULL;
	fixed_server_port = "21";
	ipv6_mode	= 0;
	listen_ip	= NULL;
	listen_port	= "8021";
	loglevel	= LOG_NOTICE;
	max_sessions	= 100;
	qname		= NULL;
	rfc_mode	= 0;
	tagname		= NULL;
	timeout		= 24 * 3600;
	verbose		= 0;

	/* Other initialization. */
	id_count	= 1;
	session_count	= 0;

	while ((ch = getopt(argc, argv, "6Aa:b:D:dm:P:p:q:R:rT:t:v")) != -1) {
		switch (ch) {
		case '6':
			ipv6_mode = 1;
			break;
		case 'A':
			anonymous_only = 1;
			break;
		case 'a':
			fixed_proxy = optarg;
			break;
		case 'b':
			listen_ip = optarg;
			break;
		case 'D':
			loglevel = strtonum(optarg, LOG_EMERG, LOG_DEBUG,
			    &errstr);
			if (errstr)
				errx(1, "loglevel %s", errstr);
			break;
		case 'd':
			daemonize = 0;
			break;
		case 'm':
			max_sessions = strtonum(optarg, 1, 500, &errstr);
			if (errstr)
				errx(1, "max sessions %s", errstr);
			break;
		case 'P':
			fixed_server_port = optarg;
			break;
		case 'p':
			listen_port = optarg;
			break;
		case 'q':
			if (strlen(optarg) >= PF_QNAME_SIZE)
				errx(1, "queuename too long");
			qname = optarg;
			break;
		case 'R':
			fixed_server = optarg;
			break;
		case 'r':
			rfc_mode = 1;
			break;
		case 'T':
			if (strlen(optarg) >= PF_TAG_NAME_SIZE)
				errx(1, "tagname too long");
			tagname = optarg;
			break;
		case 't':
			timeout = strtonum(optarg, 0, 86400, &errstr);
			if (errstr)
				errx(1, "timeout %s", errstr);
			break;
		case 'v':
			verbose++;
			if (verbose > 2)
				usage();
			break;
		default:
			usage();
		}
	}

	if (listen_ip == NULL)
		listen_ip = ipv6_mode ? "::1" : "127.0.0.1";

	/* Check for root to save the user from cryptic failure messages. */
	if (getuid() != 0)
		errx(1, "needs to start as root");

	/* Raise max. open files limit to satisfy max. sessions. */
	rlp.rlim_cur = rlp.rlim_max = (2 * max_sessions) + 10;
	if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
		err(1, "setrlimit");

	if (fixed_proxy) {
		memset(&hints, 0, sizeof hints);
		hints.ai_flags = AI_NUMERICHOST;
		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
		hints.ai_socktype = SOCK_STREAM;
		error = getaddrinfo(fixed_proxy, NULL, &hints, &res);
		if (error)
			errx(1, "getaddrinfo fixed proxy address failed: %s",
			    gai_strerror(error));
		memcpy(&fixed_proxy_ss, res->ai_addr, res->ai_addrlen);
		logmsg(LOG_INFO, "using %s to connect to servers",
		    sock_ntop(sstosa(&fixed_proxy_ss)));
		freeaddrinfo(res);
	}

	if (fixed_server) {
		memset(&hints, 0, sizeof hints);
		hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
		hints.ai_socktype = SOCK_STREAM;
		error = getaddrinfo(fixed_server, fixed_server_port, &hints,
		    &res);
		if (error)
			errx(1, "getaddrinfo fixed server address failed: %s",
			    gai_strerror(error));
		memcpy(&fixed_server_ss, res->ai_addr, res->ai_addrlen);
		logmsg(LOG_INFO, "using fixed server %s",
		    sock_ntop(sstosa(&fixed_server_ss)));
		freeaddrinfo(res);
	}

	/* Setup listener. */
	memset(&hints, 0, sizeof hints);
	hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
	hints.ai_family = ipv6_mode ? AF_INET6 : AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	error = getaddrinfo(listen_ip, listen_port, &hints, &res);
	if (error)
		errx(1, "getaddrinfo listen address failed: %s",
		    gai_strerror(error));
	if ((listenfd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
		errx(1, "socket failed");
	on = 1;
	if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
	    sizeof on) != 0)
		err(1, "setsockopt failed");
	if (bind(listenfd, (struct sockaddr *)res->ai_addr,
	    (socklen_t)res->ai_addrlen) != 0)
	    	err(1, "bind failed");
	if (listen(listenfd, TCP_BACKLOG) != 0)
		err(1, "listen failed");
	freeaddrinfo(res);

	/* Initialize pf. */
	init_filter(qname, tagname, verbose);

	if (daemonize) {
		if (daemon(0, 0) == -1)
			err(1, "cannot daemonize");
		openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
	}

	/* Use logmsg for output from here on. */

	if (!drop_privs()) {
		logmsg(LOG_ERR, "cannot drop privileges: %s", strerror(errno));
		exit(1);
	}
	
	event_init();

	/* Setup signal handler. */
	signal(SIGPIPE, SIG_IGN);
	signal_set(&ev_sighup, SIGHUP, handle_signal, NULL);
	signal_set(&ev_sigint, SIGINT, handle_signal, NULL);
	signal_set(&ev_sigterm, SIGTERM, handle_signal, NULL);
	signal_add(&ev_sighup, NULL);
	signal_add(&ev_sigint, NULL);
	signal_add(&ev_sigterm, NULL);

	event_set(&listen_ev, listenfd, EV_READ, handle_connection, NULL);
	event_add(&listen_ev, NULL);
	evtimer_set(&pause_accept_ev, handle_connection, NULL);

	logmsg(LOG_NOTICE, "listening on %s port %s", listen_ip, listen_port);

	/*  Vroom, vroom.  */
	event_dispatch();

	logmsg(LOG_ERR, "event_dispatch error: %s", strerror(errno));
	exit_daemon();

	/* NOTREACHED */
	return (1);
}
Example #3
0
int
ocsp_main(int argc, char **argv)
{
	char **args;
	char *host = NULL, *port = NULL, *path = "/";
	char *reqin = NULL, *respin = NULL;
	char *reqout = NULL, *respout = NULL;
	char *signfile = NULL, *keyfile = NULL;
	char *rsignfile = NULL, *rkeyfile = NULL;
	char *outfile = NULL;
	int add_nonce = 1, noverify = 0, use_ssl = -1;
	STACK_OF(CONF_VALUE) * headers = NULL;
	OCSP_REQUEST *req = NULL;
	OCSP_RESPONSE *resp = NULL;
	OCSP_BASICRESP *bs = NULL;
	X509 *issuer = NULL, *cert = NULL;
	X509 *signer = NULL, *rsigner = NULL;
	EVP_PKEY *key = NULL, *rkey = NULL;
	BIO *acbio = NULL, *cbio = NULL;
	BIO *derbio = NULL;
	BIO *out = NULL;
	int req_timeout = -1;
	int req_text = 0, resp_text = 0;
	long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
	char *CAfile = NULL, *CApath = NULL;
	X509_STORE *store = NULL;
	STACK_OF(X509) * sign_other = NULL, *verify_other = NULL, *rother = NULL;
	char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
	unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
	int ret = 1;
	int accept_count = -1;
	int badarg = 0;
	int i;
	int ignore_err = 0;
	STACK_OF(OPENSSL_STRING) * reqnames = NULL;
	STACK_OF(OCSP_CERTID) * ids = NULL;
	X509 *rca_cert = NULL;
	char *ridx_filename = NULL;
	char *rca_filename = NULL;
	CA_DB *rdb = NULL;
	int nmin = 0, ndays = -1;
	const EVP_MD *cert_id_md = NULL;
	const char *errstr = NULL;

	if (single_execution) {
		if (pledge("stdio inet rpath wpath cpath", NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

	args = argv + 1;
	reqnames = sk_OPENSSL_STRING_new_null();
	ids = sk_OCSP_CERTID_new_null();
	while (!badarg && *args && *args[0] == '-') {
		if (!strcmp(*args, "-out")) {
			if (args[1]) {
				args++;
				outfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-timeout")) {
			if (args[1]) {
				args++;
				req_timeout = strtonum(*args, 0,
				    INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal timeout value %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-url")) {
			if (args[1]) {
				args++;
				if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl)) {
					BIO_printf(bio_err, "Error parsing URL\n");
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-host")) {
			if (args[1]) {
				args++;
				host = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-port")) {
			if (args[1]) {
				args++;
				port = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-header")) {
			if (args[1] && args[2]) {
				if (!X509V3_add_value(args[1], args[2], &headers))
					goto end;
				args += 2;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-ignore_err"))
			ignore_err = 1;
		else if (!strcmp(*args, "-noverify"))
			noverify = 1;
		else if (!strcmp(*args, "-nonce"))
			add_nonce = 2;
		else if (!strcmp(*args, "-no_nonce"))
			add_nonce = 0;
		else if (!strcmp(*args, "-resp_no_certs"))
			rflags |= OCSP_NOCERTS;
		else if (!strcmp(*args, "-resp_key_id"))
			rflags |= OCSP_RESPID_KEY;
		else if (!strcmp(*args, "-no_certs"))
			sign_flags |= OCSP_NOCERTS;
		else if (!strcmp(*args, "-no_signature_verify"))
			verify_flags |= OCSP_NOSIGS;
		else if (!strcmp(*args, "-no_cert_verify"))
			verify_flags |= OCSP_NOVERIFY;
		else if (!strcmp(*args, "-no_chain"))
			verify_flags |= OCSP_NOCHAIN;
		else if (!strcmp(*args, "-no_cert_checks"))
			verify_flags |= OCSP_NOCHECKS;
		else if (!strcmp(*args, "-no_explicit"))
			verify_flags |= OCSP_NOEXPLICIT;
		else if (!strcmp(*args, "-trust_other"))
			verify_flags |= OCSP_TRUSTOTHER;
		else if (!strcmp(*args, "-no_intern"))
			verify_flags |= OCSP_NOINTERN;
		else if (!strcmp(*args, "-text")) {
			req_text = 1;
			resp_text = 1;
		} else if (!strcmp(*args, "-req_text"))
			req_text = 1;
		else if (!strcmp(*args, "-resp_text"))
			resp_text = 1;
		else if (!strcmp(*args, "-reqin")) {
			if (args[1]) {
				args++;
				reqin = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-respin")) {
			if (args[1]) {
				args++;
				respin = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-signer")) {
			if (args[1]) {
				args++;
				signfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-VAfile")) {
			if (args[1]) {
				args++;
				verify_certfile = *args;
				verify_flags |= OCSP_TRUSTOTHER;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-sign_other")) {
			if (args[1]) {
				args++;
				sign_certfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-verify_other")) {
			if (args[1]) {
				args++;
				verify_certfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CAfile")) {
			if (args[1]) {
				args++;
				CAfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CApath")) {
			if (args[1]) {
				args++;
				CApath = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-validity_period")) {
			if (args[1]) {
				args++;
				nsec = strtonum(*args, 0, LONG_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal validity period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-status_age")) {
			if (args[1]) {
				args++;
				maxage = strtonum(*args, 0, LONG_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal validity age %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-signkey")) {
			if (args[1]) {
				args++;
				keyfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-reqout")) {
			if (args[1]) {
				args++;
				reqout = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-respout")) {
			if (args[1]) {
				args++;
				respout = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-path")) {
			if (args[1]) {
				args++;
				path = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-issuer")) {
			if (args[1]) {
				args++;
				X509_free(issuer);
				issuer = load_cert(bio_err, *args, FORMAT_PEM,
				    NULL, "issuer certificate");
				if (!issuer)
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-cert")) {
			if (args[1]) {
				args++;
				X509_free(cert);
				cert = load_cert(bio_err, *args, FORMAT_PEM,
				    NULL, "certificate");
				if (!cert)
					goto end;
				if (!cert_id_md)
					cert_id_md = EVP_sha1();
				if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
					goto end;
				if (!sk_OPENSSL_STRING_push(reqnames, *args))
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-serial")) {
			if (args[1]) {
				args++;
				if (!cert_id_md)
					cert_id_md = EVP_sha1();
				if (!add_ocsp_serial(&req, *args, cert_id_md, issuer, ids))
					goto end;
				if (!sk_OPENSSL_STRING_push(reqnames, *args))
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-index")) {
			if (args[1]) {
				args++;
				ridx_filename = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CA")) {
			if (args[1]) {
				args++;
				rca_filename = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-nmin")) {
			if (args[1]) {
				args++;
				nmin = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal update period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			}
			if (ndays == -1)
				ndays = 0;
			else
				badarg = 1;
		} else if (!strcmp(*args, "-nrequest")) {
			if (args[1]) {
				args++;
				accept_count = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal accept count %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-ndays")) {
			if (args[1]) {
				args++;
				ndays = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal update period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rsigner")) {
			if (args[1]) {
				args++;
				rsignfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rkey")) {
			if (args[1]) {
				args++;
				rkeyfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rother")) {
			if (args[1]) {
				args++;
				rcertfile = *args;
			} else
				badarg = 1;
		} else if ((cert_id_md = EVP_get_digestbyname((*args) + 1)) == NULL) {
			badarg = 1;
		}
		args++;
	}

	/* Have we anything to do? */
	if (!req && !reqin && !respin && !(port && ridx_filename))
		badarg = 1;

	if (badarg) {
		BIO_printf(bio_err, "OCSP utility\n");
		BIO_printf(bio_err, "Usage ocsp [options]\n");
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, "-out file          output filename\n");
		BIO_printf(bio_err, "-issuer file       issuer certificate\n");
		BIO_printf(bio_err, "-cert file         certificate to check\n");
		BIO_printf(bio_err, "-serial n          serial number to check\n");
		BIO_printf(bio_err, "-signer file       certificate to sign OCSP request with\n");
		BIO_printf(bio_err, "-signkey file      private key to sign OCSP request with\n");
		BIO_printf(bio_err, "-sign_other file   additional certificates to include in signed request\n");
		BIO_printf(bio_err, "-no_certs          don't include any certificates in signed request\n");
		BIO_printf(bio_err, "-req_text          print text form of request\n");
		BIO_printf(bio_err, "-resp_text         print text form of response\n");
		BIO_printf(bio_err, "-text              print text form of request and response\n");
		BIO_printf(bio_err, "-reqout file       write DER encoded OCSP request to \"file\"\n");
		BIO_printf(bio_err, "-respout file      write DER encoded OCSP reponse to \"file\"\n");
		BIO_printf(bio_err, "-reqin file        read DER encoded OCSP request from \"file\"\n");
		BIO_printf(bio_err, "-respin file       read DER encoded OCSP reponse from \"file\"\n");
		BIO_printf(bio_err, "-nonce             add OCSP nonce to request\n");
		BIO_printf(bio_err, "-no_nonce          don't add OCSP nonce to request\n");
		BIO_printf(bio_err, "-url URL           OCSP responder URL\n");
		BIO_printf(bio_err, "-host host:n       send OCSP request to host on port n\n");
		BIO_printf(bio_err, "-path              path to use in OCSP request\n");
		BIO_printf(bio_err, "-CApath dir        trusted certificates directory\n");
		BIO_printf(bio_err, "-CAfile file       trusted certificates file\n");
		BIO_printf(bio_err, "-VAfile file       validator certificates file\n");
		BIO_printf(bio_err, "-validity_period n maximum validity discrepancy in seconds\n");
		BIO_printf(bio_err, "-status_age n      maximum status age in seconds\n");
		BIO_printf(bio_err, "-noverify          don't verify response at all\n");
		BIO_printf(bio_err, "-verify_other file additional certificates to search for signer\n");
		BIO_printf(bio_err, "-trust_other       don't verify additional certificates\n");
		BIO_printf(bio_err, "-no_intern         don't search certificates contained in response for signer\n");
		BIO_printf(bio_err, "-no_signature_verify don't check signature on response\n");
		BIO_printf(bio_err, "-no_cert_verify    don't check signing certificate\n");
		BIO_printf(bio_err, "-no_chain          don't chain verify response\n");
		BIO_printf(bio_err, "-no_cert_checks    don't do additional checks on signing certificate\n");
		BIO_printf(bio_err, "-port num		 port to run responder on\n");
		BIO_printf(bio_err, "-index file	 certificate status index file\n");
		BIO_printf(bio_err, "-CA file		 CA certificate\n");
		BIO_printf(bio_err, "-rsigner file	 responder certificate to sign responses with\n");
		BIO_printf(bio_err, "-rkey file	 responder key to sign responses with\n");
		BIO_printf(bio_err, "-rother file	 other certificates to include in response\n");
		BIO_printf(bio_err, "-resp_no_certs     don't include any certificates in response\n");
		BIO_printf(bio_err, "-nmin n	 	 number of minutes before next update\n");
		BIO_printf(bio_err, "-ndays n	 	 number of days before next update\n");
		BIO_printf(bio_err, "-resp_key_id       identify reponse by signing certificate key ID\n");
		BIO_printf(bio_err, "-nrequest n        number of requests to accept (default unlimited)\n");
		BIO_printf(bio_err, "-<dgst alg>     use specified digest in the request\n");
		goto end;
	}
	if (outfile)
		out = BIO_new_file(outfile, "w");
	else
		out = BIO_new_fp(stdout, BIO_NOCLOSE);

	if (!out) {
		BIO_printf(bio_err, "Error opening output file\n");
		goto end;
	}
	if (!req && (add_nonce != 2))
		add_nonce = 0;

	if (!req && reqin) {
		derbio = BIO_new_file(reqin, "rb");
		if (!derbio) {
			BIO_printf(bio_err, "Error Opening OCSP request file\n");
			goto end;
		}
		req = d2i_OCSP_REQUEST_bio(derbio, NULL);
		BIO_free(derbio);
		if (!req) {
			BIO_printf(bio_err, "Error reading OCSP request\n");
			goto end;
		}
	}
	if (!req && port) {
		acbio = init_responder(port);
		if (!acbio)
			goto end;
	}
	if (rsignfile && !rdb) {
		if (!rkeyfile)
			rkeyfile = rsignfile;
		rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
		    NULL, "responder certificate");
		if (!rsigner) {
			BIO_printf(bio_err, "Error loading responder certificate\n");
			goto end;
		}
		rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
		    NULL, "CA certificate");
		if (rcertfile) {
			rother = load_certs(bio_err, rcertfile, FORMAT_PEM,
			    NULL, "responder other certificates");
			if (!rother)
				goto end;
		}
		rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL,
		    "responder private key");
		if (!rkey)
			goto end;
	}
	if (acbio)
		BIO_printf(bio_err, "Waiting for OCSP client connections...\n");

redo_accept:

	if (acbio) {
		if (!do_responder(&req, &cbio, acbio, port))
			goto end;
		if (!req) {
			resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
			send_ocsp_response(cbio, resp);
			goto done_resp;
		}
	}
	if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) {
		BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
		goto end;
	}
	if (req && add_nonce)
		OCSP_request_add1_nonce(req, NULL, -1);

	if (signfile) {
		if (!keyfile)
			keyfile = signfile;
		signer = load_cert(bio_err, signfile, FORMAT_PEM,
		    NULL, "signer certificate");
		if (!signer) {
			BIO_printf(bio_err, "Error loading signer certificate\n");
			goto end;
		}
		if (sign_certfile) {
			sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
			    NULL, "signer certificates");
			if (!sign_other)
				goto end;
		}
		key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL,
		    "signer private key");
		if (!key)
			goto end;

		if (!OCSP_request_sign(req, signer, key, NULL, sign_other, sign_flags)) {
			BIO_printf(bio_err, "Error signing OCSP request\n");
			goto end;
		}
	}
	if (req_text && req)
		OCSP_REQUEST_print(out, req, 0);

	if (reqout) {
		derbio = BIO_new_file(reqout, "wb");
		if (!derbio) {
			BIO_printf(bio_err, "Error opening file %s\n", reqout);
			goto end;
		}
		i2d_OCSP_REQUEST_bio(derbio, req);
		BIO_free(derbio);
	}
	if (ridx_filename && (!rkey || !rsigner || !rca_cert)) {
		BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n");
		goto end;
	}
	if (ridx_filename && !rdb) {
		rdb = load_index(ridx_filename, NULL);
		if (!rdb)
			goto end;
		if (!index_index(rdb))
			goto end;
	}
	if (rdb) {
		i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays);
		if (cbio)
			send_ocsp_response(cbio, resp);
	} else if (host) {
		resp = process_responder(bio_err, req, host, path,
		    port, use_ssl, headers, req_timeout);
		if (!resp)
			goto end;
	} else if (respin) {
		derbio = BIO_new_file(respin, "rb");
		if (!derbio) {
			BIO_printf(bio_err, "Error Opening OCSP response file\n");
			goto end;
		}
		resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
		BIO_free(derbio);
		if (!resp) {
			BIO_printf(bio_err, "Error reading OCSP response\n");
			goto end;
		}
	} else {
		ret = 0;
		goto end;
	}

done_resp:

	if (respout) {
		derbio = BIO_new_file(respout, "wb");
		if (!derbio) {
			BIO_printf(bio_err, "Error opening file %s\n", respout);
			goto end;
		}
		i2d_OCSP_RESPONSE_bio(derbio, resp);
		BIO_free(derbio);
	}
	i = OCSP_response_status(resp);

	if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
		BIO_printf(out, "Responder Error: %s (%d)\n",
		    OCSP_response_status_str(i), i);
		if (ignore_err)
			goto redo_accept;
		ret = 0;
		goto end;
	}
	if (resp_text)
		OCSP_RESPONSE_print(out, resp, 0);

	/* If running as responder don't verify our own response */
	if (cbio) {
		if (accept_count > 0)
			accept_count--;
		/* Redo if more connections needed */
		if (accept_count) {
			BIO_free_all(cbio);
			cbio = NULL;
			OCSP_REQUEST_free(req);
			req = NULL;
			OCSP_RESPONSE_free(resp);
			resp = NULL;
			goto redo_accept;
		}
		goto end;
	}
	if (!store)
		store = setup_verify(bio_err, CAfile, CApath);
	if (!store)
		goto end;
	if (verify_certfile) {
		verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
		    NULL, "validator certificate");
		if (!verify_other)
			goto end;
	}
	bs = OCSP_response_get1_basic(resp);

	if (!bs) {
		BIO_printf(bio_err, "Error parsing response\n");
		goto end;
	}
	if (!noverify) {
		if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
			if (i == -1)
				BIO_printf(bio_err, "WARNING: no nonce in response\n");
			else {
				BIO_printf(bio_err, "Nonce Verify error\n");
				goto end;
			}
		}
		i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
		if (i < 0)
			i = OCSP_basic_verify(bs, NULL, store, 0);

		if (i <= 0) {
			BIO_printf(bio_err, "Response Verify Failure\n");
			ERR_print_errors(bio_err);
		} else
			BIO_printf(bio_err, "Response verify OK\n");

	}
	if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
		goto end;

	ret = 0;

end:
	ERR_print_errors(bio_err);
	X509_free(signer);
	X509_STORE_free(store);
	EVP_PKEY_free(key);
	EVP_PKEY_free(rkey);
	X509_free(issuer);
	X509_free(cert);
	X509_free(rsigner);
	X509_free(rca_cert);
	free_index(rdb);
	BIO_free_all(cbio);
	BIO_free_all(acbio);
	BIO_free(out);
	OCSP_REQUEST_free(req);
	OCSP_RESPONSE_free(resp);
	OCSP_BASICRESP_free(bs);
	sk_OPENSSL_STRING_free(reqnames);
	sk_OCSP_CERTID_free(ids);
	sk_X509_pop_free(sign_other, X509_free);
	sk_X509_pop_free(verify_other, X509_free);
	sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);

	if (use_ssl != -1) {
		free(host);
		free(port);
		free(path);
	}
	return (ret);
}
Example #4
0
static int
parse_prime(int linenum, char *line, struct dhgroup *dhg)
{
	char *cp, *arg;
	char *strsize, *gen, *prime;
	const char *errstr = NULL;
	long long n;

	dhg->p = dhg->g = NULL;
	cp = line;
	if ((arg = strdelim(&cp)) == NULL)
		return 0;
	/* Ignore leading whitespace */
	if (*arg == '\0')
		arg = strdelim(&cp);
	if (!arg || !*arg || *arg == '#')
		return 0;

	/* time */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	arg = strsep(&cp, " "); /* type */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	/* Ensure this is a safe prime */
	n = strtonum(arg, 0, 5, &errstr);
	if (errstr != NULL || n != MODULI_TYPE_SAFE) {
		error("moduli:%d: type is not %d", linenum, MODULI_TYPE_SAFE);
		goto fail;
	}
	arg = strsep(&cp, " "); /* tests */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	/* Ensure prime has been tested and is not composite */
	n = strtonum(arg, 0, 0x1f, &errstr);
	if (errstr != NULL ||
	    (n & MODULI_TESTS_COMPOSITE) || !(n & ~MODULI_TESTS_COMPOSITE)) {
		error("moduli:%d: invalid moduli tests flag", linenum);
		goto fail;
	}
	arg = strsep(&cp, " "); /* tries */
	if (cp == NULL || *arg == '\0')
		goto truncated;
	n = strtonum(arg, 0, 1<<30, &errstr);
	if (errstr != NULL || n == 0) {
		error("moduli:%d: invalid primality trial count", linenum);
		goto fail;
	}
	strsize = strsep(&cp, " "); /* size */
	if (cp == NULL || *strsize == '\0' ||
	    (dhg->size = (int)strtonum(strsize, 0, 64*1024, &errstr)) == 0 ||
	    errstr) {
		error("moduli:%d: invalid prime length", linenum);
		goto fail;
	}
	/* The whole group is one bit larger */
	dhg->size++;
	gen = strsep(&cp, " "); /* gen */
	if (cp == NULL || *gen == '\0')
		goto truncated;
	prime = strsep(&cp, " "); /* prime */
	if (cp != NULL || *prime == '\0') {
 truncated:
		error("moduli:%d: truncated", linenum);
		goto fail;
	}

	if ((dhg->g = BN_new()) == NULL)
		fatal("parse_prime: BN_new failed");
	if ((dhg->p = BN_new()) == NULL)
		fatal("parse_prime: BN_new failed");
	if (BN_hex2bn(&dhg->g, gen) == 0) {
		error("moduli:%d: could not parse generator value", linenum);
		goto fail;
	}
	if (BN_hex2bn(&dhg->p, prime) == 0) {
		error("moduli:%d: could not parse prime value", linenum);
		goto fail;
	}
	if (BN_num_bits(dhg->p) != dhg->size) {
		error("moduli:%d: prime has wrong size: actual %d listed %d",
		    linenum, BN_num_bits(dhg->p), dhg->size - 1);
		goto fail;
	}
	if (BN_cmp(dhg->g, BN_value_one()) <= 0) {
		error("moduli:%d: generator is invalid", linenum);
		goto fail;
	}

	return 1;

 fail:
	if (dhg->g != NULL)
		BN_clear_free(dhg->g);
	if (dhg->p != NULL)
		BN_clear_free(dhg->p);
	dhg->g = dhg->p = NULL;
	error("Bad prime description in line %d", linenum);
	return 0;
}
Example #5
0
int
main(int argc, char *argv[])
{
	struct timezone tz;
	const char *errstr;
	struct tm *tp;
	int ch, rflag;
	char *format, buf[1024], *outzone = NULL;

	setlocale(LC_ALL, "");

	tz.tz_dsttime = tz.tz_minuteswest = 0;
	rflag = 0;
	while ((ch = getopt(argc, argv, "ad:jr:ut:z:")) != -1)
		switch(ch) {
		case 'd':		/* daylight saving time */
			tz.tz_dsttime = atoi(optarg) ? 1 : 0;
			break;
		case 'a':
			slidetime = 1;
			break;
		case 'j':		/* don't set */
			jflag = 1;
			break;
		case 'r':		/* user specified seconds */
			rflag = 1;
			tval = atoll(optarg);
			break;
		case 'u':		/* do everything in UTC */
			if (setenv("TZ", "UTC", 1) == -1)
				err(1, "cannot unsetenv TZ");
			break;
		case 't':		/* minutes west of GMT */
			tz.tz_minuteswest = strtonum(optarg, 0, 24*60-1, &errstr);
			if (errstr)
				errx(1, "-t %s: %s", optarg, errstr);
			break;
		case 'z':
			outzone = optarg;
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

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

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

	format = "%a %b %e %H:%M:%S %Z %Y";

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

	if (*argv) {
		setthetime(*argv);
		argv++;
		argc--;
	}

	if (pledge("stdio rpath wpath", NULL) == -1)
		err(1, "pledge");

	if (*argv && **argv == '+') {
		format = *argv + 1;
		argc--;
	}

	if (argc > 0)
		errx(1, "too many arguments");

	if (outzone)
		setenv("TZ", outzone, 1);

	tp = localtime(&tval);
	if (tp == NULL)
		errx(1, "conversion error");
	(void)strftime(buf, sizeof(buf), format, tp);
	(void)printf("%s\n", buf);
	exit(0);
}
Example #6
0
/*
 * Nfs server daemon mostly just a user context for nfssvc()
 *
 * 1 - do file descriptor and signal cleanup
 * 2 - fork the nfsd(s)
 * 3 - create server socket(s)
 * 4 - register socket with portmap
 *
 * For connectionless protocols, just pass the socket into the kernel via.
 * nfssvc().
 * For connection based sockets, loop doing accepts. When you get a new
 * socket from accept, pass the msgsock into the kernel via. nfssvc().
 * The arguments are:
 *	-r - reregister with portmapper
 *	-t - support tcp nfs clients
 *	-u - support udp nfs clients
 * followed by "n" which is the number of nfsds' to fork off
 */
int
main(int argc, char *argv[])
{
	struct nfsd_args nfsdargs;
	struct sockaddr_in inetaddr, inetpeer;
	fd_set *ready, *sockbits;
	size_t fd_size;
	int ch, connect_type_cnt, i, maxsock = 0, msgsock;
	int nfsdcnt = DEFNFSDCNT, on, reregister = 0, sock;
	int udpflag = 0, tcpflag = 0, tcpsock;
	const char *errstr = NULL;
	socklen_t len;

	/* Start by writing to both console and log. */
	openlog("nfsd", LOG_PID | LOG_PERROR, LOG_DAEMON);

	if (argc == 1)
		udpflag = 1;
	while ((ch = getopt(argc, argv, "n:rtu")) != -1)
		switch (ch) {
		case 'n':
			nfsdcnt = strtonum(optarg, 1, MAXNFSDCNT, &errstr);
			if (errstr) {
				syslog(LOG_ERR, "nfsd count is %s: %s", errstr, optarg);
				return(1);
			}
			break;
		case 'r':
			reregister = 1;
			break;
		case 't':
			tcpflag = 1;
			break;
		case 'u':
			udpflag = 1;
			break;
		default:
			usage();
		};
	argv += optind;
	argc -= optind;

	/*
	 * XXX
	 * Backward compatibility, trailing number is the count of daemons.
	 */
	if (argc > 1)
		usage();
	if (argc == 1) {
		nfsdcnt = strtonum(argv[0], 1, MAXNFSDCNT, &errstr);
		if (errstr) {
			syslog(LOG_ERR, "nfsd count is %s: %s", errstr, optarg);
			return(1);
		}
	}

	if (debug == 0) {
		daemon(0, 0);
		(void)signal(SIGHUP, SIG_IGN);
		(void)signal(SIGINT, SIG_IGN);
		(void)signal(SIGQUIT, SIG_IGN);
		(void)signal(SIGSYS, nonfs);
	}
	(void)signal(SIGCHLD, reapchild);

	if (reregister) {
		if (udpflag &&
		    (!pmap_set(RPCPROG_NFS, 2, IPPROTO_UDP, NFS_PORT) ||
		     !pmap_set(RPCPROG_NFS, 3, IPPROTO_UDP, NFS_PORT))) {
			syslog(LOG_ERR, "can't register with portmap for UDP (%m).");
			return (1);
		}
		if (tcpflag &&
		    (!pmap_set(RPCPROG_NFS, 2, IPPROTO_TCP, NFS_PORT) ||
		     !pmap_set(RPCPROG_NFS, 3, IPPROTO_TCP, NFS_PORT))) {
			syslog(LOG_ERR, "can't register with portmap for TCP (%m).");
			return (1);
		}
		return (0);
	}

	/* Cut back to writing to log only. */
	closelog();
	openlog("nfsd", LOG_PID, LOG_DAEMON);

	for (i = 0; i < nfsdcnt; i++) {
		switch (fork()) {
		case -1:
			syslog(LOG_ERR, "fork: %m");
			return (1);
		case 0:
			break;
		default:
			continue;
		}

		setproctitle("server");
		nsd.nsd_nfsd = NULL;
		if (nfssvc(NFSSVC_NFSD, &nsd) < 0) {
			syslog(LOG_ERR, "nfssvc: %m");
			return (1);
		}
		return (0);
	}

	/* If we are serving udp, set up the socket. */
	if (udpflag) {
		if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
			syslog(LOG_ERR, "can't create udp socket");
			return (1);
		}
		memset(&inetaddr, 0, sizeof inetaddr);
		inetaddr.sin_family = AF_INET;
		inetaddr.sin_addr.s_addr = INADDR_ANY;
		inetaddr.sin_port = htons(NFS_PORT);
		inetaddr.sin_len = sizeof(inetaddr);
		if (bind(sock, (struct sockaddr *)&inetaddr,
		    sizeof(inetaddr)) < 0) {
			syslog(LOG_ERR, "can't bind udp addr");
			return (1);
		}
		if (!pmap_set(RPCPROG_NFS, 2, IPPROTO_UDP, NFS_PORT) ||
		    !pmap_set(RPCPROG_NFS, 3, IPPROTO_UDP, NFS_PORT)) {
			syslog(LOG_ERR, "can't register with udp portmap");
			return (1);
		}
		nfsdargs.sock = sock;
		nfsdargs.name = NULL;
		nfsdargs.namelen = 0;
		if (nfssvc(NFSSVC_ADDSOCK, &nfsdargs) < 0) {
			syslog(LOG_ERR, "can't Add UDP socket");
			return (1);
		}
		(void)close(sock);
	}

	/* Now set up the master server socket waiting for tcp connections. */
	on = 1;
	connect_type_cnt = 0;
	if (tcpflag) {
		if ((tcpsock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
			syslog(LOG_ERR, "can't create tcp socket");
			return (1);
		}
		if (setsockopt(tcpsock,
		    SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
			syslog(LOG_ERR, "setsockopt SO_REUSEADDR: %m");
		memset(&inetaddr, 0, sizeof inetaddr);
		inetaddr.sin_family = AF_INET;
		inetaddr.sin_addr.s_addr = INADDR_ANY;
		inetaddr.sin_port = htons(NFS_PORT);
		inetaddr.sin_len = sizeof(inetaddr);
		if (bind(tcpsock, (struct sockaddr *)&inetaddr,
		    sizeof (inetaddr)) < 0) {
			syslog(LOG_ERR, "can't bind tcp addr");
			return (1);
		}
		if (listen(tcpsock, 5) < 0) {
			syslog(LOG_ERR, "listen failed");
			return (1);
		}
		if (!pmap_set(RPCPROG_NFS, 2, IPPROTO_TCP, NFS_PORT) ||
		    !pmap_set(RPCPROG_NFS, 3, IPPROTO_TCP, NFS_PORT)) {
			syslog(LOG_ERR, "can't register tcp with portmap");
			return (1);
		}
		maxsock = tcpsock;
		connect_type_cnt++;
	}

	if (connect_type_cnt == 0)
		return (0);

	setproctitle("master");

	/*
	 * Allocate space for the fd_set pointers and fill in sockbits
	 */
	fd_size = howmany(maxsock + 1, NFDBITS) * sizeof(fd_mask);
	sockbits = malloc(fd_size);
	ready = malloc(fd_size);
	if (sockbits == NULL || ready == NULL) {
		syslog(LOG_ERR, "cannot allocate memory");
		return (1);
	}
	memset(sockbits, 0, fd_size);
	if (tcpflag)
		FD_SET(tcpsock, sockbits);

	/*
	 * Loop forever accepting connections and passing the sockets
	 * into the kernel for the mounts.
	 */
	for (;;) {
		memcpy(ready, sockbits, fd_size);
		if (connect_type_cnt > 1) {
			if (select(maxsock + 1,
			    ready, NULL, NULL, NULL) < 1) {
				syslog(LOG_ERR, "select failed: %m");
				return (1);
			}
		}
		if (tcpflag && FD_ISSET(tcpsock, ready)) {
			len = sizeof(inetpeer);
			if ((msgsock = accept(tcpsock,
			    (struct sockaddr *)&inetpeer, &len)) < 0) {
				if (errno == EWOULDBLOCK || errno == EINTR ||
				    errno == ECONNABORTED)
					continue;
				syslog(LOG_ERR, "accept failed: %m");
				return (1);
			}
			memset(inetpeer.sin_zero, 0, sizeof(inetpeer.sin_zero));
			if (setsockopt(msgsock, SOL_SOCKET,
			    SO_KEEPALIVE, &on, sizeof(on)) < 0)
				syslog(LOG_ERR,
				    "setsockopt SO_KEEPALIVE: %m");
			nfsdargs.sock = msgsock;
			nfsdargs.name = (caddr_t)&inetpeer;
			nfsdargs.namelen = sizeof(inetpeer);
			if (nfssvc(NFSSVC_ADDSOCK, &nfsdargs) < 0) {
				syslog(LOG_ERR, "can't Add TCP socket");
				return (1);
			}
			(void)close(msgsock);
		}
	}
}
/***********************************************************************
 * parseArgs - Parse command line arguments and initialize data
 *
 * Returns 0 if ok, -1 on bad args
 */
static int 
parseArgs(int argc, char **argv)
{
	int badop = 0;
	const char *errstr;

	verify_depth = 0;
	verify_error = X509_V_OK;

	argc--;
	argv++;

	while (argc >= 1) {
		if (strcmp(*argv, "-connect") == 0) {
			if (--argc < 1)
				goto bad;
			host = *(++argv);
		}
#if 0
		else if (strcmp(*argv, "-host") == 0) {
			if (--argc < 1)
				goto bad;
			host = *(++argv);
		} else if (strcmp(*argv, "-port") == 0) {
			if (--argc < 1)
				goto bad;
			port = *(++argv);
		}
#endif
		else if (strcmp(*argv, "-reuse") == 0)
			perform = 2;
		else if (strcmp(*argv, "-new") == 0)
			perform = 1;
		else if (strcmp(*argv, "-verify") == 0) {
			const char *errstr;

			tm_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
			if (--argc < 1)
				goto bad;
			verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
			if (errstr)
				goto bad;
			BIO_printf(bio_err, "verify depth is %d\n", verify_depth);

		} else if (strcmp(*argv, "-cert") == 0) {

			if (--argc < 1)
				goto bad;
			t_cert_file = *(++argv);

		} else if (strcmp(*argv, "-key") == 0) {

			if (--argc < 1)
				goto bad;
			t_key_file = *(++argv);

		} else if (strcmp(*argv, "-CApath") == 0) {

			if (--argc < 1)
				goto bad;
			CApath = *(++argv);

		} else if (strcmp(*argv, "-CAfile") == 0) {

			if (--argc < 1)
				goto bad;
			CAfile = *(++argv);

		} else if (strcmp(*argv, "-cipher") == 0) {

			if (--argc < 1)
				goto bad;
			tm_cipher = *(++argv);
		}
		else if (strcmp(*argv, "-nbio") == 0) {
			t_nbio = 1;
		}
		else if (strcmp(*argv, "-www") == 0) {
			if (--argc < 1)
				goto bad;
			s_www_path = *(++argv);
			if (strlen(s_www_path) > MYBUFSIZ - 100) {
				BIO_printf(bio_err, "-www option too long\n");
				badop = 1;
			}
		} else if (strcmp(*argv, "-bugs") == 0)
			st_bugs = 1;
		else if (strcmp(*argv, "-ssl3") == 0)
			s_time_meth = SSLv3_client_method();
		else if (strcmp(*argv, "-time") == 0) {

			if (--argc < 1)
				goto bad;
			maxTime = strtonum(*(++argv), 0, INT_MAX, &errstr);
			if (errstr)
				goto bad;
		} else {
			BIO_printf(bio_err, "unknown option %s\n", *argv);
			badop = 1;
			break;
		}

		argc--;
		argv++;
	}

	if (perform == 0)
		perform = 3;

	if (badop) {
bad:
		s_time_usage();
		return -1;
	}
	return 0;		/* Valid args */
}
Example #8
0
File: if.c Project: yellowman/nsh
int
intmetric(char *ifname, int ifs, int argc, char **argv)
{
	struct ifreq ifr;
	int set, max;
	unsigned long theioctl;
	char *type;
	const char *errmsg = NULL;

	if (NO_ARG(argv[0])) {
		set = 0;
		argc--;
		argv++;
	} else
		set = 1;

	if (isprefix(argv[0], "metric")) {
		type = "metric";
		max = INT_MAX;
		theioctl = SIOCSIFMETRIC;
	} else if (isprefix(argv[0], "priority")) {
		type = "priority";
		max = 15;
		theioctl = SIOCSIFPRIORITY;
	} else {
		printf("%% intmetric internal failure\n");
		return(0);
	}

	argc--;
	argv++;

	if ((!set && argc > 1) || (set && argc != 1)) {
		printf("%% %s <%s>\n", type, type);
		printf("%% no %s [%s]\n", type, type);
		return(0);
	}

	if (set) {
		int num;

		num = strtonum(argv[0], 0, max, &errmsg);
		if (errmsg) {
			printf("%% Invalid %s %s: %s\n", type, argv[0],
			    errmsg);
			return(0);
		}
		ifr.ifr_metric = num;
	} else {
		ifr.ifr_metric = 0;
	}

	if (errmsg) {
		printf("%% Invalid %s %s: %s\n", type, argv[0], errmsg);
		return(0);
	}

	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
	if (ioctl(ifs, theioctl, (caddr_t)&ifr) < 0)
		printf("%% intmetric: SIOCSIF%s: %s\n", type,
		    strerror(errno));

	return(0);
}
Example #9
0
File: if.c Project: yellowman/nsh
int
intvlan(char *ifname, int ifs, int argc, char **argv)
{
#ifndef SIOCSIFPARENT /* 5.9- */
	const char *errmsg = NULL;
	struct ifreq ifr;
	struct vlanreq vreq;
#endif
	int set;

	if (NO_ARG(argv[0])) {
		set = 0;
		argc--;
		argv++;
	} else
		set = 1;

	argc--;
	argv++;

	if ((set && argc != 3) || (!set && argc > 3) ||
	    (argc == 3 && !isprefix(argv[1], "parent"))) {
		printf("%% vlan <tag> parent <parent interface>\n");
		printf("%% no vlan [tag] [parent <parent interface>]\n");
		return 0;
	}

#ifndef SIOCSIFPARENT /* 5.9- */
	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));

	bzero(&vreq, sizeof(vreq));

	ifr.ifr_data = (caddr_t)&vreq;

	if (ioctl(ifs, SIOCGETVLAN, (caddr_t)&ifr) == -1) {
		switch(errno) {
		case ENOTTY:
			printf("%% This interface does not support vlan"
			    " tagging\n");
			break;
		default:
			printf("%% intvlan: SIOCGETVLAN: %s\n",
			    strerror(errno));
		}
		return(0);
	}
#endif
	if (set) {
		if (!is_valid_ifname(argv[2]) || is_bridge(ifs, argv[2])) {
			printf("%% Invalid vlan parent %s\n", argv[2]);
			return 0;
		}
#ifndef SIOCSIFPARENT	/* 5.9- */
		strlcpy(vreq.vlr_parent, argv[2], sizeof(vreq.vlr_parent));
		vreq.vlr_tag = strtonum(argv[0], 0, 4095, &errmsg);
		if (errmsg) {
			printf("%% Invalid vlan tag %s: %s", argv[0], errmsg);
			return 0;
		}
		if (vreq.vlr_tag != EVL_VLANOFTAG(vreq.vlr_tag)) {
			printf("%% Invalid vlan tag %s\n", argv[0]);
			return 0;
		}
	} else {
		bzero(&vreq.vlr_parent, sizeof(vreq.vlr_parent));
		vreq.vlr_tag = 0;
#endif
	}

#ifdef SIOCSIFPARENT	/* 6.0+ */
	if (set) {
		char *vnet_argv[] = { "vnetid", argv[0], '\0' };
		char *par_argv[] = { "parent", argv[2], '\0' };

		intparent(ifname, ifs, 2, par_argv);
		intvnetid(ifname, ifs, 2, vnet_argv);
	} else {
		char *vnet_argv[] = { "no", "vnetid" };
		char *par_argv[] = { "no", "parent" };

		intparent(ifname, ifs, 2, par_argv);
		intvnetid(ifname, ifs, 2, vnet_argv);
	}

#else
	if (ioctl(ifs, SIOCSETVLAN, (caddr_t)&ifr) == -1) {
		switch(errno) {
		case EBUSY:
			printf("%% Please disconnect the current vlan parent"
			    " before setting a new one\n");
			return 0;
			break;
		default:
			printf("%% intvlan: SIOCSETVLAN: %s\n",
			    strerror(errno));
			return 0;
		}
	}
#endif

	return 0;
}
enum cmd_retval
cmd_resize_pane_exec(struct cmd *self, struct cmd_q *cmdq)
{
	struct args		*args = self->args;
	struct winlink		*wl;
	struct window		*w;
	const char	       	*errstr;
	char			*cause;
	struct window_pane	*wp;
	u_int			 adjust;
	int			 x, y;

	if ((wl = cmd_find_pane(cmdq, args_get(args, 't'), NULL, &wp)) == NULL)
		return (CMD_RETURN_ERROR);
	w = wl->window;

	if (args_has(args, 'Z')) {
		if (w->flags & WINDOW_ZOOMED)
			window_unzoom(w);
		else
			window_zoom(wp);
		server_redraw_window(w);
		server_status_window(w);
		return (CMD_RETURN_NORMAL);
	}
	server_unzoom_window(w);

	if (args->argc == 0)
		adjust = 1;
	else {
		adjust = strtonum(args->argv[0], 1, INT_MAX, &errstr);
		if (errstr != NULL) {
			cmdq_error(cmdq, "adjustment %s", errstr);
			return (CMD_RETURN_ERROR);
		}
	}

	if (args_has(self->args, 'x')) {
		x = args_strtonum(self->args, 'x', PANE_MINIMUM, INT_MAX,
		    &cause);
		if (cause != NULL) {
			cmdq_error(cmdq, "width %s", cause);
			free(cause);
			return (CMD_RETURN_ERROR);
		}
		layout_resize_pane_to(wp, LAYOUT_LEFTRIGHT, x);
	}
	if (args_has(self->args, 'y')) {
		y = args_strtonum(self->args, 'y', PANE_MINIMUM, INT_MAX,
		    &cause);
		if (cause != NULL) {
			cmdq_error(cmdq, "height %s", cause);
			free(cause);
			return (CMD_RETURN_ERROR);
		}
		layout_resize_pane_to(wp, LAYOUT_TOPBOTTOM, y);
	}

	if (args_has(self->args, 'L'))
		layout_resize_pane(wp, LAYOUT_LEFTRIGHT, -adjust);
	else if (args_has(self->args, 'R'))
		layout_resize_pane(wp, LAYOUT_LEFTRIGHT, adjust);
	else if (args_has(self->args, 'U'))
		layout_resize_pane(wp, LAYOUT_TOPBOTTOM, -adjust);
	else if (args_has(self->args, 'D'))
		layout_resize_pane(wp, LAYOUT_TOPBOTTOM, adjust);
	server_redraw_window(wl->window);

	return (CMD_RETURN_NORMAL);
}
Example #11
0
File: if.c Project: yellowman/nsh
/* from ifconfig.c */
int
intmpw(char *ifname, int ifs, int argc, char **argv)
{
	int set;
	struct sockaddr_in *sin, *sinn;
	struct ifmpwreq imr;
	struct ifreq ifr;
	struct mpwc *x;
	const char *errstr;

	bzero(&imr, sizeof(imr));
	bzero(&ifr, sizeof(ifr));

	strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);

	if (NO_ARG(argv[0])) {
		set = 0;
		argc--;
		argv++;
	} else
		set = 1;

	x=(struct mpwc *) genget(argv[0], (char **)mpwcs, sizeof(struct mpwc));
	if (x == 0) {
		printf("%% Internal error - Invalid argument %s\n", argv[0]);
		return 0;
	} else if (Ambiguous(x)) {
		printf("%% Internal error - Ambiguous argument %s\n", argv[0]);
		return 0;
	}

	argc--;
	argv++;

	if (x->args == 2 && ((!set && argc > 2) || (set && argc != 2))) {
		printf("%% %s <%s> <%s>\n", x->name, x->descr, x->descr2);
		printf("%% no %s [%s] [%s]\n", x->name, x->descr, x->descr2);
		return(0);
	}
	if (x->args == 1 && ((!set && argc > 1) || (set && argc != 1))) {
		printf("%% %s <%s>\n", x->name, x->descr);
		printf("%% no %s [%s]\n", x->name, x->descr);
		return(0);
	}
	if (!x->args && argc) {
		printf("%% %s\n", x->name);
		printf("%% no %s\n", x->name);
		return(0);
	}

	switch(x->type) {
	case MPWLABEL:
		if (!set) {
			imrsave.imr_lshim.shim_label = 0;
			imrsave.imr_rshim.shim_label = 0;
			break;
		}
		imrsave.imr_lshim.shim_label = strtonum(argv[0],
		    (MPLS_LABEL_RESERVED_MAX + 1), MPLS_LABEL_MAX, &errstr);
		if (errstr != NULL) {
			printf("%% invalid local label: %s\n", errstr);
			return 0;
		}

		imrsave.imr_rshim.shim_label = strtonum(argv[1],
		    (MPLS_LABEL_RESERVED_MAX + 1), MPLS_LABEL_MAX, &errstr);
		if (errstr != NULL) {
			printf("%% invalid remote label: %s\n", errstr);
			return 0;
		}
	break;
	case MPWNEIGHBOR:
		sin = (struct sockaddr_in *) &imrsave.imr_nexthop;
		if (set && inet_aton(argv[0], &sin->sin_addr) == 0) {
			printf("%% invalid neighbor addresses\n");
			return 0;
		}
		if (!set) {
			sin->sin_addr.s_addr = 0;
		}
		sin->sin_family = AF_INET;
	break;
	case MPWCONTROLWORD:
		if (set)
			imrsave.imr_flags |= IMR_FLAG_CONTROLWORD;
		else
			imrsave.imr_flags &= ~IMR_FLAG_CONTROLWORD;
	break;
	case MPWENCAP:
		if (!set) {
			imrsave.imr_type = UINT32_MAX;
			break;
		}
		if (isprefix(argv[0], "ethernet")) {
			imrsave.imr_type = IMR_TYPE_ETHERNET;
		} else if (isprefix(argv[0], "ethernet-tagged")) {
			imrsave.imr_type = IMR_TYPE_ETHERNET_TAGGED;
		} else {
			printf("%% invalid mpw encapsulation type\n");
			return 0;
		}
		break;
	}

	ifr.ifr_data = (caddr_t) &imr;
	if (ioctl(ifs, SIOCGETMPWCFG, (caddr_t) &ifr) == -1) {
		printf("%% SIOCGETMPWCFG: %s\n", strerror(errno));
		return 0;
	}

	if (imrsave.imr_type == 0)
		imrsave.imr_type = imr.imr_type;
	if (imrsave.imr_type == UINT32_MAX)
		imrsave.imr_type = 0;

	if (x->type != MPWCONTROLWORD)
		imrsave.imr_flags |= imr.imr_flags;

	if (imrsave.imr_lshim.shim_label == 0 ||
	    imrsave.imr_rshim.shim_label == 0) {
		if (imr.imr_lshim.shim_label == 0 ||
		    imr.imr_rshim.shim_label == 0) {
			/* mpw local / remote label not specified */
			return 0;
		}
		imrsave.imr_lshim.shim_label = imr.imr_lshim.shim_label;
		imrsave.imr_rshim.shim_label = imr.imr_rshim.shim_label;
	}

	sin = (struct sockaddr_in *) &imrsave.imr_nexthop;
	sinn = (struct sockaddr_in *) &imr.imr_nexthop;
	if (sin->sin_addr.s_addr == 0) {
		if (sinn->sin_addr.s_addr == 0) {
			/* mpw neighbor address not specified */
			return 0;
		}

		sin->sin_family = sinn->sin_family;
		sin->sin_addr.s_addr = sinn->sin_addr.s_addr;
	}

	ifr.ifr_data = (caddr_t) &imrsave;
	if (ioctl(ifs, SIOCSETMPWCFG, (caddr_t) &ifr) == -1)
		printf("%% intmpw: SIOCSETMPWCFG: %s\n", strerror(errno));

	return 0;
}
Example #12
0
int
main(int argc, char *argv[])
{
	int ch, fd, error;
	int i_flag = 0, m_flag = 0, u_flag = 0;
	int c_arg = 0, h_arg = 0, s_arg = 0;
	struct disk disk;
	u_int32_t l_arg = 0;
#ifdef HAS_MBR
	char *mbrfile = _PATH_MBR;
#else
	char *mbrfile = NULL;
#endif
	struct mbr mbr;
	struct dos_mbr dos_mbr;

	while ((ch = getopt(argc, argv, "ieguf:c:h:s:l:y")) != -1) {
		const char *errstr;

		switch(ch) {
		case 'i':
			i_flag = 1;
			break;
		case 'u':
			u_flag = 1;
			break;
		case 'e':
			m_flag = 1;
			break;
		case 'f':
			mbrfile = optarg;
			break;
		case 'c':
			c_arg = strtonum(optarg, 1, 262144, &errstr);
			if (errstr)
				errx(1, "Cylinder argument %s [1..262144].",
				    errstr);
			break;
		case 'h':
			h_arg = strtonum(optarg, 1, 256, &errstr);
			if (errstr)
				errx(1, "Head argument %s [1..256].", errstr);
			break;
		case 's':
			s_arg = strtonum(optarg, 1, 63, &errstr);
			if (errstr)
				errx(1, "Sector argument %s [1..63].", errstr);
			break;
		case 'g':
			g_flag = 1;
			break;
		case 'l':
			l_arg = strtonum(optarg, 64, UINT32_MAX, &errstr);
			if (errstr)
				errx(1, "Block argument %s [64..%u].", errstr,
				    UINT32_MAX);
			break;
		case 'y':
			y_flag = 1;
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	memset(&disk, 0, sizeof(disk));

	/* Argument checking */
	if (argc != 1)
		usage();
	else
		disk.name = argv[0];

	if (g_flag != 0 && i_flag == 0) {
		warnx("-g specified without -i");
		usage();
	}

	/* Start with the disklabel geometry and get the sector size. */
	DISK_getlabelgeometry(&disk);

	if (c_arg | h_arg | s_arg) {
		/* Use supplied geometry if it is completely specified. */
		if (c_arg && h_arg && s_arg) {
			disk.cylinders = c_arg;
			disk.heads = h_arg;
			disk.sectors = s_arg;
			disk.size = c_arg * h_arg * s_arg;
		} else
			errx(1, "Please specify a full geometry with [-chs].");
	} else if (l_arg) {
		/* Use supplied size to calculate a geometry. */
		disk.cylinders = l_arg / 64;
		disk.heads = 1;
		disk.sectors = 64;
		disk.size = l_arg;
	}

	if (disk.size == 0 || disk.cylinders == 0 || disk.heads == 0 ||
	    disk.sectors == 0 || unit_types[SECTORS].conversion == 0)
		errx(1, "Can't get disk geometry, please use [-chs] "
		    "to specify.");

	/* Print out current MBRs on disk */
	if ((i_flag + u_flag + m_flag) == 0)
		exit(USER_print_disk(&disk));

	/* Parse mbr template, to pass on later */
	if (mbrfile != NULL && (fd = open(mbrfile, O_RDONLY)) == -1) {
		warn("%s", mbrfile);
		warnx("using builtin MBR");
		mbrfile = NULL;
	}
	if (mbrfile == NULL) {
		memcpy(&dos_mbr, builtin_mbr, sizeof(dos_mbr));
	} else {
		error = MBR_read(fd, 0, &dos_mbr);
		if (error == -1)
			err(1, "Unable to read MBR");
		close(fd);
	}
	MBR_parse(&disk, &dos_mbr, 0, 0, &mbr);

	/* Now do what we are supposed to */
	if (i_flag || u_flag)
		if (USER_init(&disk, &mbr, u_flag) == -1)
			err(1, "error initializing MBR");

	if (m_flag)
		USER_modify(&disk, &mbr, 0, 0);

	return (0);
}
Example #13
0
/*
 * Get an entry in the One-time Password database and lock it.
 *
 * Return codes:
 * -1: error in opening database or unable to lock entry
 *  0: entry found, file R/W pointer positioned at beginning of record
 *  1: entry not found
 */
static int
skeygetent(int fd, struct skey *mp, const char *name)
{
	char *cp, filename[PATH_MAX], *last;
	struct stat statbuf;
	const char *errstr;
	size_t nread;
	FILE *keyfile;

	/* Check to see that /etc/skey has not been disabled. */
	if (stat(_PATH_SKEYDIR, &statbuf) != 0)
		return (-1);
	if ((statbuf.st_mode & ALLPERMS) == 0) {
		errno = EPERM;
		return (-1);
	}

	if (fd == -1) {
		/* Open the user's databse entry, creating it as needed. */
		if (snprintf(filename, sizeof(filename), "%s/%s", _PATH_SKEYDIR,
		    name) >= sizeof(filename)) {
			errno = ENAMETOOLONG;
			return (-1);
		}
		if ((fd = open(filename, O_RDWR | O_NOFOLLOW | O_NONBLOCK,
		    S_IRUSR | S_IWUSR)) == -1) {
			if (errno == ENOENT)
				goto not_found;
			return (-1);
		}
	}

	/* Lock and stat the user's skey file. */
	if (flock(fd, LOCK_EX) != 0 || fstat(fd, &statbuf) != 0) {
		close(fd);
		return (-1);
	}
	if (statbuf.st_size == 0)
		goto not_found;

	/* Sanity checks. */
	if ((statbuf.st_mode & ALLPERMS) != (S_IRUSR | S_IWUSR) ||
	    !S_ISREG(statbuf.st_mode) || statbuf.st_nlink != 1 ||
	    (keyfile = fdopen(fd, "r+")) == NULL) {
		close(fd);
		return (-1);
	}

	/* At this point, we are committed. */
	mp->keyfile = keyfile;

	if ((nread = fread(mp->buf, 1, sizeof(mp->buf), keyfile)) == 0 ||
	    !isspace((unsigned char)mp->buf[nread - 1]))
		goto bad_keyfile;
	mp->buf[nread - 1] = '\0';

	if ((mp->logname = strtok_r(mp->buf, " \t\n\r", &last)) == NULL ||
	    strcmp(mp->logname, name) != 0)
		goto bad_keyfile;
	if ((cp = strtok_r(NULL, " \t\n\r", &last)) == NULL)
		goto bad_keyfile;
	if (skey_set_algorithm(cp) == NULL)
		goto bad_keyfile;
	if ((cp = strtok_r(NULL, " \t\n\r", &last)) == NULL)
		goto bad_keyfile;
	mp->n = strtonum(cp, 0, UINT_MAX, &errstr);
	if (errstr)
		goto bad_keyfile;
	if ((mp->seed = strtok_r(NULL, " \t\n\r", &last)) == NULL)
		goto bad_keyfile;
	if ((mp->val = strtok_r(NULL, " \t\n\r", &last)) == NULL)
		goto bad_keyfile;

	(void)fseek(keyfile, 0L, SEEK_SET);
	return (0);

    bad_keyfile:
	fclose(keyfile);
	return (-1);

    not_found:
	/* No existing entry, fill in what we can and return */
	memset(mp, 0, sizeof(*mp));
	strlcpy(mp->buf, name, sizeof(mp->buf));
	mp->logname = mp->buf;
	if (fd != -1)
		close(fd);
	return (1);
}
Example #14
0
void CProjEdit::DoDataExchange(CDataExchange* pDX)
{
  proj_header tmp;
  CButton *cb;
  CWnd *cw;
  CString tmpstr;
  int i,j,k;
  int flg;

  memcpy(&tmp,&the_projectile.header,sizeof(proj_header));
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CProjEdit)
	DDX_Control(pDX, IDC_MPSMOKE, m_mpsmoke);
	DDX_Control(pDX, IDC_MPTRAVEL, m_mptravel);
	//}}AFX_DATA_MAP
  switch(the_projectile.header.type)
  {
  case 2: tmpstr="0x2 One target"; break;
  case 3: tmpstr="0x3 Area effect"; break;
  default: tmpstr.Format("0x%x Unknown",the_projectile.header.type); break;
  }
  DDX_Text(pDX, IDC_TYPE, tmpstr);
  the_projectile.header.type=(short) strtonum(tmpstr);

  DDX_Text(pDX, IDC_SPEED, the_projectile.header.speed);
  DDX_Text(pDX, IDC_FLAGS, the_projectile.header.sparks);

  DDX_Text(pDX, IDC_UNKNOWN0E, the_projectile.header.unknown0e);

  RetrieveResref(tmpstr,the_projectile.header.wavc1);
  DDX_Text(pDX, IDC_SOUND1, tmpstr);
  DDV_MaxChars(pDX, tmpstr,8);
  StoreResref(tmpstr,the_projectile.header.wavc1);

  RetrieveResref(tmpstr,the_projectile.header.wavc2);
  DDX_Text(pDX, IDC_SOUND2, tmpstr);
  DDV_MaxChars(pDX, tmpstr,8);
  StoreResref(tmpstr,the_projectile.header.wavc2);

  RetrieveResref(tmpstr,the_projectile.header.vvc);
  DDX_Text(pDX, IDC_VVC, tmpstr);
  DDV_MaxChars(pDX, tmpstr,8);
  StoreResref(tmpstr,the_projectile.header.vvc);

  tmpstr=get_spark_colour(the_projectile.header.spkcolour);
  DDX_Text(pDX, IDC_SPARKCOLOUR, tmpstr);
  the_projectile.header.spkcolour=(short) strtonum(tmpstr);

  tmpstr.Format("%d", the_projectile.header.attr);
  DDX_Text(pDX, IDC_ATTR, tmpstr);
  the_projectile.header.attr=strtonum(tmpstr);

  RetrieveResref(tmpstr,the_projectile.header.bam1);
  DDX_Text(pDX, IDC_BAM1, tmpstr);
  DDV_MaxChars(pDX, tmpstr,8);
  StoreResref(tmpstr,the_projectile.header.bam1);

  RetrieveResref(tmpstr,the_projectile.header.bam2);
  DDX_Text(pDX, IDC_BAM2, tmpstr);
  DDV_MaxChars(pDX, tmpstr,8);
  StoreResref(tmpstr,the_projectile.header.bam2);

  DDX_Text(pDX, IDC_SEQ1, the_projectile.header.seq1);
  DDX_Text(pDX, IDC_SEQ2, the_projectile.header.seq2);

  DDX_Text(pDX, IDC_Z, the_projectile.header.lightz);
  DDX_Text(pDX, IDC_X, the_projectile.header.lightx);
  DDX_Text(pDX, IDC_Y, the_projectile.header.lighty);

  RetrieveResref(tmpstr,the_projectile.header.bmp);
  DDX_Text(pDX, IDC_PALETTE, tmpstr);
  DDV_MaxChars(pDX, tmpstr,8);
  StoreResref(tmpstr,the_projectile.header.bmp);

  for(i=0;i<7;i++)
  {
    DDX_Text(pDX, IDC_U1+i, (unsigned char &) the_projectile.header.colours[i]);
  }
  DDX_Text(pDX, IDC_DELAY, the_projectile.header.smokepuff);
  for(i=0;i<7;i++)
  {
    DDX_Text(pDX, IDC_U11+i, (unsigned char &) the_projectile.header.smokecols[i]);
  }

  tmpstr=get_face_value(the_projectile.header.aim);
  DDX_Text(pDX, IDC_AIM, tmpstr);
  the_projectile.header.aim=(unsigned char) strtonum(tmpstr);

  tmpstr.Format("0x%04x %s",the_projectile.header.smokeanim,IDSToken("ANIMATE",the_projectile.header.smokeanim, false) );
  DDX_Text(pDX, IDC_SMOKETYPE, tmpstr);
  k=IDSKey2("ANIMATE", tmpstr);
  the_projectile.header.smokeanim=(unsigned short) k;

  for(i=0;i<3;i++)
  {
    RetrieveResref(tmpstr,the_projectile.header.trailbam[i]);
    DDX_Text(pDX, IDC_BAM3+i, tmpstr);
    DDV_MaxChars(pDX, tmpstr,8);
    StoreResref(tmpstr,the_projectile.header.trailbam[i]);

    DDX_Text(pDX, IDC_FREQ1+i, the_projectile.header.trailtype[i]);
  }

  flg=(the_projectile.header.type==3);
  cw=GetDlgItem(IDC_EXTENSION);
  cw->EnableWindow(flg);

  flg=!!(the_projectile.header.sparks&1);
  for(k=0;sparkboxids[k];k++)
  {
    cw=GetDlgItem(sparkboxids[k]);
    cw->EnableWindow(flg);
  }

  j=1;
  for(i=0;i<8;i++)
  {
    cb=(CButton *) GetDlgItem(IDC_FLAG1+i);
    if(cb)
    {
      cb->SetCheck(!!(the_projectile.header.sparks&j));
    }
    j<<=1;
  }

  j=1;
  for(i=0;i<16;i++)
  {
    cb=(CButton *) GetDlgItem(IDC_ATTR1+i);
    flg=!!(the_projectile.header.attr&j);
    cb->SetCheck(flg);
    if(headercontrols[i])
    {
      for(k=0;headercontrols[i][k];k++)
      {
        cw=GetDlgItem(headercontrols[i][k]);
        cw->EnableWindow(flg);
      }
    }
    j<<=1;
  }
  if(memcmp(&tmp,&the_projectile.header,sizeof(proj_header)))
  {
    the_projectile.m_changed=true;
  }
}
Example #15
0
int
main(int argc, char **argv)
{
	const char	*errstr;
	char		*tmp, *s, *host;
	int		 opt, i;

	if (isatty(STDIN_FILENO) && tcgetattr(STDIN_FILENO, &saved_tio) != 0)
		err(1, "tcgetattr");

	/*
	 * Convert obsolescent -### speed to modern -s### syntax which getopt()
	 * can handle.
	 */
	for (i = 1; i < argc; i++) {
		if (strcmp("--", argv[i]) == 0)
			break;
		if (argv[i][0] != '-' || !isdigit((unsigned char)argv[i][1]))
			continue;

		if (asprintf(&argv[i], "-s%s", &argv[i][1]) == -1)
			errx(1, "speed asprintf");
	}

	while ((opt = getopt(argc, argv, "l:s:")) != -1) {
		switch (opt) {
		case 'l':
			line_path = optarg;
			break;
		case 's':
			line_speed = strtonum(optarg, 0, INT_MAX, &errstr);
			if (errstr != NULL)
				errx(1, "speed is %s: %s", errstr, optarg);
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 0 && argc != 1)
		usage();

	if (argc == 1)
		host = argv[0];
	else
		host = getenv("HOST");
	if (host != NULL && *host != '\0') {
		if (*host == '/')
			line_path = host;
		else {
			s = getenv("REMOTE");
			if (s != NULL && *s == '/')
				try_remote(host, s, NULL);
			else
				try_remote(host, NULL, s);
		}
	}

	if (line_path == NULL)
		line_path = "/dev/cua00";
	if (line_speed == -1)
		line_speed = 9600;

	if (strchr(line_path, '/') == NULL) {
		if (asprintf(&tmp, "%s%s", _PATH_DEV, line_path) == -1)
			err(1, "asprintf");
		line_path = tmp;
	}

	line_fd = open(line_path, O_RDWR);
	if (line_fd < 0)
		err(1, "open(\"%s\")", line_path);
	if (ioctl(line_fd, TIOCEXCL) != 0)
		err(1, "ioctl(TIOCEXCL)");
	if (tcgetattr(line_fd, &line_tio) != 0)
		err(1, "tcgetattr");
	if (set_line(line_speed) != 0)
		err(1, "tcsetattr");

	event_init();

	signal_set(&sigterm_ev, SIGTERM, signal_event, NULL);
	signal_add(&sigterm_ev, NULL);
	signal_set(&sighup_ev, SIGHUP, signal_event, NULL);
	signal_add(&sighup_ev, NULL);
	if (signal(SIGINT, SIG_IGN) == SIG_ERR)
		err(1, "signal");
	if (signal(SIGQUIT, SIG_IGN) == SIG_ERR)
		err(1, "signal");

	set_termios(); /* after this use cu_err and friends */

	/* stdin and stdout get separate events */
	input_ev = bufferevent_new(STDIN_FILENO, stream_read, NULL,
	    stream_error, NULL);
	bufferevent_enable(input_ev, EV_READ);
	output_ev = bufferevent_new(STDOUT_FILENO, NULL, NULL, stream_error,
	    NULL);
	bufferevent_enable(output_ev, EV_WRITE);

	line_ev = bufferevent_new(line_fd, line_read, NULL, line_error,
	    NULL);
	bufferevent_enable(line_ev, EV_READ|EV_WRITE);

	printf("Connected to %s (speed %d)\r\n", line_path, line_speed);
	event_dispatch();

	restore_termios();
	printf("\r\n[EOT]\n");

	exit(0);
}
Example #16
0
File: if.c Project: yellowman/nsh
int
intlink(char *ifname, int ifs, int argc, char **argv)
{
	const char *errmsg = NULL;
	int set, i, flags, value = 0;

	if (NO_ARG(argv[0])) {
		set = 0;
		argv++;
		argc--;
	} else
		set = 1;

	argv++;
	argc--;

	if ((set && argc < 1) || argc > 3) {
		printf("%% link <012>\n");
		printf("%% no link [012]\n");
		return(0);
	}

	flags = get_ifflags(ifname, ifs);

	if (!set && argc == 0) {
		/*
		 * just 'no link' was specified.  so we remove all flags
		 */
		flags &= ~IFF_LINK0 & ~IFF_LINK1 & ~IFF_LINK2;
	} else 
	for (i = 0; i < argc; i++) {
		int a;

		a = strtonum(argv[i], 0, 2, &errmsg);
		if (errmsg) {
			printf("%% Invalid link flag %s: %s\n", argv[i],
			    errmsg);
			return(0);
		}
		switch(a) {
		case 0:
			value = IFF_LINK0;
			break;
		case 1:
			value = IFF_LINK1;
			break;
		case 2:
			value = IFF_LINK2;
			break;
		}

		if (set)
			flags |= value;
		else
			flags &= ~value;
	}

	set_ifflags(ifname, ifs, flags);

	return(0);
}
Example #17
0
int
intmedia(char *ifname, int ifs, int argc, char **argv)
{
	const char *errmsg = NULL;
	uint64_t set, media_current, type, subtype, inst;

	if (NO_ARG(argv[0])) {
		set = 0;
		argc--;
		argv++;
	} else
		set = 1;

	argv++;
	argc--;

	if ((set && (argc < 1 || argc > 2)) || (!set && argc > 2)) {
		printf("%% media <type> [instance]\n");
		printf("%% no media [type] [instance]\n");
		media_supported(ifs, ifname, "% ", "%   ");
		return(0);
	}

	media_current = init_current_media(ifs, ifname);

	if (media_current == -1) {
		if (errno == EINVAL)
			printf("%% This device does not support "
			    "media commands.\n");
		else
			printf("%% Failed to initialize media: %s\n",
			    strerror(errno));
		return(0);
	}

	if (argc == 2) {
		inst = strtonum(argv[1], 0, IFM_INST_MAX, &errmsg);
		if (errmsg) {
			printf("%% Invalid media instance: %s: %s\n", argv[1],
			    errmsg);
			return(0);
		}
	} else {
		inst = IFM_INST(media_current);
	}

	type = IFM_TYPE(media_current);
	/* Look up the subtype */
	if (set)
		subtype = get_media_subtype(type, argv[0]);
	else
		subtype = get_media_subtype(type, DEFAULT_MEDIA_TYPE);

	if (subtype == -1)
		return(0);

	/* Build the new media_current word */
	media_current = IFM_MAKEWORD(type, subtype, 0, inst);

	process_media_commands(ifs, ifname, media_current);

	return(0);
}
Example #18
0
File: if.c Project: yellowman/nsh
/*
 * addr/port parsing lifted from sbin/ifconfig/ifconfig.c
 */
int
intpflow(char *ifname, int ifs, int argc, char **argv)
{
	struct ifreq ifr;
	struct pflowreq preq;
	int set;
	const char *errmsg = NULL;

	if (NO_ARG(argv[0])) {
		set = 0;
		argc--;
		argv++;
	} else
		set = 1;

	argc--;
	argv++;

	/* XXX f*****g makes my eyes bleed. learn how to use yacc ? */
	if ((set && argc < 4) || (set && argc == 5) || (set &&
	    (argc == 4 || argc == 6) && (!isprefix(argv[0], "sender") ||
	    !isprefix(argv[2], "receiver") ||
	    (argc == 6 && !isprefix(argv[4], "version"))))) {
		printf("%% pflow sender <x.x.x.x> receiver <x.x.x.x:port> "
		    "[version 5|9|10]\n"
		    "%% no pflow [sender x.x.x.x receiver x.x.x.x:port "
		    "version 5|9|10]\n");
		return(0);
	}

	if (set) {
	        if (strchr(argv[3], ':') == NULL) {
			printf("%% Receiver has no port specified\n");
			return(0);
		}
	}

	bzero(&ifr, sizeof(ifr));     
	strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);

	bzero(&preq, sizeof(struct pflowreq));
	ifr.ifr_data = (caddr_t)&preq;

	preq.addrmask = PFLOW_MASK_SRCIP | PFLOW_MASK_DSTIP;
	if (set) {
		pflow_addr(argv[1], &preq.flowsrc);
		pflow_addr(argv[3], &preq.flowdst);
		if (argc == 6) {
			preq.version = strtonum(argv[5], 5, PFLOW_PROTO_MAX,
			    &errmsg);
			preq.addrmask |= PFLOW_MASK_VERSION;
	                if (errmsg) {
				printf("%% Invalid pflow version %s: %s\n",
				    argv[0], errmsg);
				return(0);
			}
                }
	}

	if (ioctl(ifs, SIOCSETPFLOW, (caddr_t)&ifr) == -1)
		printf("%% Unable to set pflow parameters: %s\n",
		    strerror(errno));

	return(0);
}
int
cmd_resize_pane_down_exec(struct cmd *self, struct cmd_ctx *ctx)
{
	struct cmd_pane_data	*data = self->data;
	struct winlink		*wl;
	const char	       	*errstr;
	struct window_pane	*wp, *wq;
	u_int			 adjust;
	
	if ((wl = cmd_find_window(ctx, data->target, NULL)) == NULL)
		return (-1);
	if (wl->window->layout != 0) {
		ctx->error(ctx, "window not in manual layout");
		return (-1);
	}
	if (data->pane == -1)
		wp = wl->window->active;
	else {
		wp = window_pane_at_index(wl->window, data->pane);
		if (wp == NULL) {
			ctx->error(ctx, "no pane: %d", data->pane);
			return (-1);
		}
	}

	if (data->arg == NULL)
		adjust = 1;
	else {
		adjust = strtonum(data->arg, 1, INT_MAX, &errstr);
		if (errstr != NULL) {
			ctx->error(ctx, "adjustment %s: %s", errstr, data->arg);
			return (-1);
		}
	}

	/*
	 * If this is not the last window, keep trying to increase size and
	 * remove it from the next windows. If it is the last, do so on the
	 * previous window.
	 */
	if (TAILQ_NEXT(wp, entry) == NULL) {
		if (wp == TAILQ_FIRST(&wl->window->panes)) {
			/* Only one pane. */
			return (0);
		}
		wp = TAILQ_PREV(wp, window_panes, entry);
	}
	while (adjust-- > 0) {
		wq = wp;
		while ((wq = TAILQ_NEXT(wq, entry)) != NULL) {
			if (wq->sy > PANE_MINIMUM) {
				window_pane_resize(wq, wq->sx, wq->sy - 1);
				break;
			}
		}
		if (wq == NULL)
			break;
		window_pane_resize(wp, wp->sx, wp->sy + 1);

	}
	window_update_panes(wl->window);

	server_redraw_window(wl->window);

	return (0);
}
Example #20
0
void CAreaSong::DoDataExchange(CDataExchange* pDX)
{
  CString tmpstr;

	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAreaSong)
	DDX_Control(pDX, IDC_ALT5, m_alt5control);
	DDX_Control(pDX, IDC_ALT4, m_alt4control);
	DDX_Control(pDX, IDC_ALT3, m_alt3control);
	DDX_Control(pDX, IDC_ALT2, m_alt2control);
	DDX_Control(pDX, IDC_ALT1, m_alt1control);
	DDX_Control(pDX, IDC_BATTLE, m_battlecontrol);
	DDX_Control(pDX, IDC_UNKNOWN2, m_u2control);
	DDX_Control(pDX, IDC_UNKNOWN1, m_u1control);
	DDX_Control(pDX, IDC_NIGHT, m_nightcontrol);
	DDX_Control(pDX, IDC_DAY, m_daycontrol);
	//}}AFX_DATA_MAP
  tmpstr=get_songname(the_area.songheader.songs[0]);
  DDX_Text(pDX, IDC_DAY, tmpstr);
  the_area.songheader.songs[0]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[1]);
  DDX_Text(pDX, IDC_NIGHT, tmpstr);
  the_area.songheader.songs[1]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[2]);
  DDX_Text(pDX, IDC_UNKNOWN1, tmpstr);
  the_area.songheader.songs[2]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[3]);
  DDX_Text(pDX, IDC_BATTLE, tmpstr);
  the_area.songheader.songs[3]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[4]);
  DDX_Text(pDX, IDC_UNKNOWN2,tmpstr);
  the_area.songheader.songs[4]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[5]);
  DDX_Text(pDX, IDC_ALT1,tmpstr);
  the_area.songheader.songs[5]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[6]);
  DDX_Text(pDX, IDC_ALT2,tmpstr);
  the_area.songheader.songs[6]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[7]);
  DDX_Text(pDX, IDC_ALT3,tmpstr);
  the_area.songheader.songs[7]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[8]);
  DDX_Text(pDX, IDC_ALT4,tmpstr);
  the_area.songheader.songs[8]=strtonum(tmpstr);

  tmpstr=get_songname(the_area.songheader.songs[9]);
  DDX_Text(pDX, IDC_ALT5,tmpstr);
  the_area.songheader.songs[9]=strtonum(tmpstr);
  /*
  DDX_Text(pDX, IDC_UNKNOWN3, the_area.songheader.songs[5]);
  DDX_Text(pDX, IDC_UNKNOWN4, the_area.songheader.songs[6]);
  DDX_Text(pDX, IDC_UNKNOWN5, the_area.songheader.songs[7]);
  DDX_Text(pDX, IDC_UNKNOWN6, the_area.songheader.songs[8]);
  DDX_Text(pDX, IDC_UNKNOWN7, the_area.songheader.songs[9]);
*/
  RetrieveResref(tmpstr,the_area.songheader.dayambi1);
  DDX_Text(pDX, IDC_AMBI1D, tmpstr);
  DDV_MaxChars(pDX, tmpstr, 8);
  StoreResref(tmpstr,the_area.songheader.dayambi1);

  RetrieveResref(tmpstr,the_area.songheader.dayambi2);
  DDX_Text(pDX, IDC_AMBI2D, tmpstr);
  DDV_MaxChars(pDX, tmpstr, 8);
  StoreResref(tmpstr,the_area.songheader.dayambi2);

  RetrieveResref(tmpstr,the_area.songheader.nightambi1);
  DDX_Text(pDX, IDC_AMBI1N, tmpstr);
  DDV_MaxChars(pDX, tmpstr, 8);
  StoreResref(tmpstr,the_area.songheader.nightambi1);

  RetrieveResref(tmpstr,the_area.songheader.nightambi2);
  DDX_Text(pDX, IDC_AMBI2N, tmpstr);
  DDV_MaxChars(pDX, tmpstr, 8);
  StoreResref(tmpstr,the_area.songheader.nightambi2);

  DDX_Text(pDX, IDC_VOLUMED, the_area.songheader.volumed);
  DDX_Text(pDX, IDC_VOLUMEN, the_area.songheader.volumen);
  DDX_Text(pDX, IDC_FLAGS, the_area.songheader.songflag);
}
Example #21
0
enum cmd_retval
cmd_new_session_exec(struct cmd *self, struct cmd_q *cmdq)
{
	struct args		*args = self->args;
	struct client		*c = cmdq->client;
	struct session		*s, *attach_sess;
	struct session		*groupwith = cmdq->state.tflag.s;
	struct window		*w;
	struct environ		*env;
	struct termios		 tio, *tiop;
	const char		*newname, *target, *update, *errstr, *template;
	const char		*path, *cwd, *to_free;
	char		       **argv, *cmd, *cause, *cp;
	int			 detached, already_attached, idx, argc;
	u_int			 sx, sy;
	struct format_tree	*ft;
	struct environ_entry	*envent;

	if (self->entry == &cmd_has_session_entry) {
		/*
		 * cmd_prepare() will fail if the session cannot be found,
		 * hence always return success here.
		 */
		return (CMD_RETURN_NORMAL);
	}

	if (args_has(args, 't') && (args->argc != 0 || args_has(args, 'n'))) {
		cmdq_error(cmdq, "command or window name given with target");
		return (CMD_RETURN_ERROR);
	}

	newname = args_get(args, 's');
	if (newname != NULL) {
		if (!session_check_name(newname)) {
			cmdq_error(cmdq, "bad session name: %s", newname);
			return (CMD_RETURN_ERROR);
		}
		if ((attach_sess = session_find(newname)) != NULL) {
			if (args_has(args, 'A')) {
				/*
				 * This cmdq is now destined for
				 * attach-session.  Because attach-session
				 * will have already been prepared, copy this
				 * session into its tflag so it can be used.
				 */
				cmdq->state.tflag.s = attach_sess;
				return (cmd_attach_session(cmdq,
				    args_has(args, 'D'), 0, NULL,
				    args_has(args, 'E')));
			}
			cmdq_error(cmdq, "duplicate session: %s", newname);
			return (CMD_RETURN_ERROR);
		}
	}

	if ((target = args_get(args, 't')) == NULL)
		groupwith = NULL;

	/* Set -d if no client. */
	detached = args_has(args, 'd');
	if (c == NULL)
		detached = 1;

	/* Is this client already attached? */
	already_attached = 0;
	if (c != NULL && c->session != NULL)
		already_attached = 1;

	/* Get the new session working directory. */
	to_free = NULL;
	if (args_has(args, 'c')) {
		ft = format_create(cmdq, 0);
		format_defaults(ft, c, NULL, NULL, NULL);
		to_free = cwd = format_expand(ft, args_get(args, 'c'));
		format_free(ft);
	} else if (c != NULL && c->session == NULL)
		cwd = c->cwd;
	else
		cwd = ".";

	/*
	 * If this is a new client, check for nesting and save the termios
	 * settings (part of which is used for new windows in this session).
	 *
	 * tcgetattr() is used rather than using tty.tio since if the client is
	 * detached, tty_open won't be called. It must be done before opening
	 * the terminal as that calls tcsetattr() to prepare for tmux taking
	 * over.
	 */
	if (!detached && !already_attached && c->tty.fd != -1) {
		if (server_client_check_nested(cmdq->client)) {
			cmdq_error(cmdq, "sessions should be nested with care, "
			    "unset $TMUX to force");
			return (CMD_RETURN_ERROR);
		}
		if (tcgetattr(c->tty.fd, &tio) != 0)
			fatal("tcgetattr failed");
		tiop = &tio;
	} else
		tiop = NULL;

	/* Open the terminal if necessary. */
	if (!detached && !already_attached) {
		if (server_client_open(c, &cause) != 0) {
			cmdq_error(cmdq, "open terminal failed: %s", cause);
			free(cause);
			goto error;
		}
	}

	/* Find new session size. */
	if (c != NULL) {
		sx = c->tty.sx;
		sy = c->tty.sy;
	} else {
		sx = 80;
		sy = 24;
	}
	if (detached && args_has(args, 'x')) {
		sx = strtonum(args_get(args, 'x'), 1, USHRT_MAX, &errstr);
		if (errstr != NULL) {
			cmdq_error(cmdq, "width %s", errstr);
			goto error;
		}
	}
	if (detached && args_has(args, 'y')) {
		sy = strtonum(args_get(args, 'y'), 1, USHRT_MAX, &errstr);
		if (errstr != NULL) {
			cmdq_error(cmdq, "height %s", errstr);
			goto error;
		}
	}
	if (sy > 0 && options_get_number(global_s_options, "status"))
		sy--;
	if (sx == 0)
		sx = 1;
	if (sy == 0)
		sy = 1;

	/* Figure out the command for the new window. */
	argc = -1;
	argv = NULL;
	if (!args_has(args, 't') && args->argc != 0) {
		argc = args->argc;
		argv = args->argv;
	} else if (target == NULL) {
		cmd = options_get_string(global_s_options, "default-command");
		if (cmd != NULL && *cmd != '\0') {
			argc = 1;
			argv = &cmd;
		} else {
			argc = 0;
			argv = NULL;
		}
	}

	path = NULL;
	if (c != NULL && c->session == NULL)
		envent = environ_find(c->environ, "PATH");
	else
		envent = environ_find(global_environ, "PATH");
	if (envent != NULL)
		path = envent->value;

	/* Construct the environment. */
	env = environ_create();
	if (c != NULL && !args_has(args, 'E')) {
		update = options_get_string(global_s_options,
		    "update-environment");
		environ_update(update, c->environ, env);
	}

	/* Create the new session. */
	idx = -1 - options_get_number(global_s_options, "base-index");
	s = session_create(newname, argc, argv, path, cwd, env, tiop, idx, sx,
	    sy, &cause);
	environ_free(env);
	if (s == NULL) {
		cmdq_error(cmdq, "create session failed: %s", cause);
		free(cause);
		goto error;
	}

	/* Set the initial window name if one given. */
	if (argc >= 0 && args_has(args, 'n')) {
		w = s->curw->window;
		window_set_name(w, args_get(args, 'n'));
		options_set_number(w->options, "automatic-rename", 0);
	}

	/*
	 * If a target session is given, this is to be part of a session group,
	 * so add it to the group and synchronize.
	 */
	if (args_has(args, 't')) {
		session_group_add(groupwith, s);
		session_group_synchronize_to(s);
		session_select(s, RB_MIN(winlinks, &s->windows)->idx);
	}

	/*
	 * Set the client to the new session. If a command client exists, it is
	 * taking this session and needs to get MSG_READY and stay around.
	 */
	if (!detached) {
		if (!already_attached) {
			if (~c->flags & CLIENT_CONTROL)
				proc_send(c->peer, MSG_READY, -1, NULL, 0);
		} else if (c->session != NULL)
			c->last_session = c->session;
		c->session = s;
		server_client_set_key_table(c, NULL);
		status_timer_start(c);
		notify_attached_session_changed(c);
		session_update_activity(s, NULL);
		gettimeofday(&s->last_attached_time, NULL);
		server_redraw_client(c);
	}
	recalculate_sizes();
	server_update_socket();

	/*
	 * If there are still configuration file errors to display, put the new
	 * session's current window into more mode and display them now.
	 */
	if (cfg_finished)
		cfg_show_causes(s);

	/* Print if requested. */
	if (args_has(args, 'P')) {
		if ((template = args_get(args, 'F')) == NULL)
Example #22
0
int
pkg_sshserve(int fd)
{
	struct stat st;
	char *line = NULL;
	char *file, *age;
	size_t linecap = 0, r;
	ssize_t linelen;
	time_t mtime = 0;
	const char *errstr;
	int ffd;
	char buf[BUFSIZ];
	char fpath[MAXPATHLEN];
	const char *restricted = NULL;

	restricted = pkg_object_string(pkg_config_get("SSH_RESTRICT_DIR"));

	printf("ok: pkg "PKGVERSION"\n");
	for (;;) {
		if ((linelen = getline(&line, &linecap, stdin)) <= 0)
			continue;

		/* trim cr */
		if (line[linelen - 1] == '\n')
			line[linelen - 1] = '\0';

		if (strcmp(line, "quit") == 0)
			return (EPKG_OK);

		if (strncmp(line, "get ", 4) != 0) {
			printf("ko: unknown command '%s'\n", line);
			continue;
		}

		file = line + 4;

		if (*file == '/')
			file++;

		age = file;
		while (!isspace(*age)) {
			if (*age == '\0') {
				age = NULL;
				break;
			}
			age++;
		}

		if (age == NULL) {
			printf("ko: bad command get, expecting 'get file age'\n");
			continue;
		}

		*age = '\0';
		age++;

		while (isspace(*age)) {
			if (*age == '\0') {
				age = NULL;
				break;
			}
			age++;
		}

		if (age == NULL) {
			printf("ko: bad command get, expecting 'get file age'\n");
			continue;
		}

		mtime = strtonum(age, 0, LONG_MAX, &errstr);
		if (errstr) {
			printf("ko: bad number %s: %s\n", age, errstr);
			continue;
		}

#ifdef HAVE_CAPSICUM
		if (!cap_sandboxed() && restricted != NULL) {
#else
		if (restricted != NULL) {
#endif
			chdir(restricted);
			file = realpath(file, fpath);
			if (strncmp(file, restricted, strlen(restricted)) != 0) {
				printf("ko: file not found\n");
				continue;
			}
		}

		if (fstatat(fd, file, &st, AT_SYMLINK_NOFOLLOW) == -1) {
			printf("ko: file not found\n");
			continue;
		}

		if (!S_ISREG(st.st_mode)) {
			printf("ko: not a file\n");
			continue;
		}

		if (st.st_mtime <= mtime) {
			printf("ok: 0\n");
			continue;
		}

		if ((ffd = openat(fd, file, O_RDONLY)) == -1) {
			printf("ko: file not found\n");
			continue;
		}

		printf("ok: %" PRIdMAX "\n", (intmax_t)st.st_size);

		while ((r = read(ffd, buf, sizeof(buf))) > 0)
			fwrite(buf, 1, r, stdout);

		close(ffd);
	}

	free(line);

	return (EPKG_OK);
}
int
cmd_split_window_parse(struct cmd *self, int argc, char **argv, char **cause)
{
	struct cmd_split_window_data	*data;
	int				 opt;
	const char			*errstr;

	self->entry->init(self, 0);
	data = self->data;

	while ((opt = getopt(argc, argv, "dhl:p:t:v")) != -1) {
		switch (opt) {
		case 'd':
			data->flag_detached = 1;
			break;
		case 'h':
			data->flag_horizontal = 1;
			break;
		case 't':
			if (data->target == NULL)
				data->target = xstrdup(optarg);
			break;
		case 'l':
			if (data->percentage != -1 || data->size != -1)
				break;
			data->size = strtonum(optarg, 1, INT_MAX, &errstr);
			if (errstr != NULL) {
				xasprintf(cause, "size %s", errstr);
				goto error;
			}
			break;
		case 'p':
			if (data->size != -1 || data->percentage != -1)
				break;
			data->percentage = strtonum(optarg, 1, 100, &errstr);
			if (errstr != NULL) {
				xasprintf(cause, "percentage %s", errstr);
				goto error;
			}
			break;
		case 'v':
			data->flag_horizontal = 0;
			break;
		default:
			goto usage;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 0 && argc != 1)
		goto usage;

	if (argc == 1)
		data->cmd = xstrdup(argv[0]);

	return (0);

usage:
	xasprintf(cause, "usage: %s %s", self->entry->name, self->entry->usage);

error:
	self->entry->free(self);
	return (-1);
}
Example #24
0
/* Convert % sequence to job
 *
 * If jobs are compiled in then this routine expects sigchld to be blocked.
 */
static Job *
j_lookup(const char *cp, int *ecodep)
{
	Job		*j, *last_match;
	const char	*errstr;
	Proc		*p;
	int		len, job = 0;

	if (digit(*cp)) {
		job = strtonum(cp, 1, INT_MAX, &errstr);
		if (errstr) {
			if (ecodep)
				*ecodep = JL_NOSUCH;
			return NULL;
		}
		/* Look for last_proc->pid (what $! returns) first... */
		for (j = job_list; j != NULL; j = j->next)
			if (j->last_proc && j->last_proc->pid == job)
				return j;
		/* ...then look for process group (this is non-POSIX),
		 * but should not break anything (so FPOSIX isn't used).
		 */
		for (j = job_list; j != NULL; j = j->next)
			if (j->pgrp && j->pgrp == job)
				return j;
		if (ecodep)
			*ecodep = JL_NOSUCH;
		return NULL;
	}
	if (*cp != '%') {
		if (ecodep)
			*ecodep = JL_INVALID;
		return NULL;
	}
	switch (*++cp) {
	case '\0': /* non-standard */
	case '+':
	case '%':
		if (job_list != NULL)
			return job_list;
		break;

	case '-':
		if (job_list != NULL && job_list->next)
			return job_list->next;
		break;

	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
		job = strtonum(cp, 1, INT_MAX, &errstr);
		if (errstr)
			break;
		for (j = job_list; j != NULL; j = j->next)
			if (j->job == job)
				return j;
		break;

	case '?':		/* %?string */
		last_match = NULL;
		for (j = job_list; j != NULL; j = j->next)
			for (p = j->proc_list; p != NULL; p = p->next)
				if (strstr(p->command, cp+1) != NULL) {
					if (last_match) {
						if (ecodep)
							*ecodep = JL_AMBIG;
						return NULL;
					}
					last_match = j;
				}
		if (last_match)
			return last_match;
		break;

	default:		/* %string */
		len = strlen(cp);
		last_match = NULL;
		for (j = job_list; j != NULL; j = j->next)
			if (strncmp(cp, j->proc_list->command, len) == 0) {
				if (last_match) {
					if (ecodep)
						*ecodep = JL_AMBIG;
					return NULL;
				}
				last_match = j;
			}
		if (last_match)
			return last_match;
		break;
	}
	if (ecodep)
		*ecodep = JL_NOSUCH;
	return NULL;
}
Example #25
0
int
manconf_output(struct manoutput *conf, const char *cp, int fromfile)
{
	const char *const toks[] = {
	    "includes", "man", "paper", "style",
	    "indent", "width", "fragment", "mdoc", "noval"
	};

	const char	*errstr;
	char		*oldval;
	size_t		 len, tok;

	for (tok = 0; tok < sizeof(toks)/sizeof(toks[0]); tok++) {
		len = strlen(toks[tok]);
		if ( ! strncmp(cp, toks[tok], len) &&
		    strchr(" =	", cp[len]) != NULL) {
			cp += len;
			if (*cp == '=')
				cp++;
			while (isspace((unsigned char)*cp))
				cp++;
			break;
		}
	}

	if (tok < 6 && *cp == '\0') {
		warnx("-O %s=?: Missing argument value", toks[tok]);
		return -1;
	}
	if ((tok == 6 || tok == 7) && *cp != '\0') {
		warnx("-O %s: Does not take a value: %s", toks[tok], cp);
		return -1;
	}

	switch (tok) {
	case 0:
		if (conf->includes != NULL) {
			oldval = mandoc_strdup(conf->includes);
			break;
		}
		conf->includes = mandoc_strdup(cp);
		return 0;
	case 1:
		if (conf->man != NULL) {
			oldval = mandoc_strdup(conf->man);
			break;
		}
		conf->man = mandoc_strdup(cp);
		return 0;
	case 2:
		if (conf->paper != NULL) {
			oldval = mandoc_strdup(conf->paper);
			break;
		}
		conf->paper = mandoc_strdup(cp);
		return 0;
	case 3:
		if (conf->style != NULL) {
			oldval = mandoc_strdup(conf->style);
			break;
		}
		conf->style = mandoc_strdup(cp);
		return 0;
	case 4:
		if (conf->indent) {
			mandoc_asprintf(&oldval, "%zu", conf->indent);
			break;
		}
		conf->indent = strtonum(cp, 0, 1000, &errstr);
		if (errstr == NULL)
			return 0;
		warnx("-O indent=%s is %s", cp, errstr);
		return -1;
	case 5:
		if (conf->width) {
			mandoc_asprintf(&oldval, "%zu", conf->width);
			break;
		}
		conf->width = strtonum(cp, 58, 1000, &errstr);
		if (errstr == NULL)
			return 0;
		warnx("-O width=%s is %s", cp, errstr);
		return -1;
	case 6:
		conf->fragment = 1;
		return 0;
	case 7:
		conf->mdoc = 1;
		return 0;
	case 8:
		conf->noval = 1;
		return 0;
	default:
		if (fromfile)
			warnx("-O %s: Bad argument", cp);
		return -1;
	}
	if (fromfile == 0)
		warnx("-O %s=%s: Option already set to %s",
		    toks[tok], cp, oldval);
	free(oldval);
	return -1;
}
Example #26
0
int
main(int argc, const char *argv[])
{
	int		 fflag;
	int		 wflag;
	int		 ch;
	char		*fname;
	const char	*errstr;
	char		*word1;
	char		*word2;

	setlocale(LC_ALL, "");

	dflag = fflag = iflag = wflag = ch = 0;
	fname = word1 = word2 = NULL;

	if (argc < 3)
		usage();

	while ((ch = getopt(argc, (char *const *)argv, "d:f:iw:")) != -1) {
		switch ((char)ch) {
		case 'd': /* difference can be wdist <= distance */
			dflag = 1;
			wdist = strtonum(optarg, 0, 128, &errstr);
			if (errstr)
				errx(1, "Error: %s\nOut of range: %s", errstr, optarg);
			break;
		case 'f':
			fflag = 1;
			fname = optarg;
			/* TODO add support to stdin */
			break;
		case 'i':
			iflag = 1;
			break;
		case 'w':
			wflag = 1;
			word1 = optarg;
			break;
		case '?':
			if (optopt == 'f')
				(void)fprintf(stderr, "Missing file argument\n");
			else if (optopt == 'w')
				(void)fprintf(stderr, "Missing word argument\n");
			exit(1);
		default:
			usage();
		}
	}

	word2 = (char *const)argv[argc-1];

	if (iflag) {
		if (!fflag)
			convertlowercase(word1, sizeof(word1));
		convertlowercase(word2, sizeof(word2));
	}

	if (fflag)
		comparefile(fname, word2, strlen(word2));
	else if (wflag) {
		int diff;

		diff = levensteinDistance(word1, strlen(word1), word2, strlen(word2));

		if (!dflag)
			(void)fprintf(stdout, "%-10s %5s %2d\n", word1, word2, diff);
		else if (diff <= wdist)
			(void)fprintf(stdout, "%-10s %5s %2d\n", word1, word2, diff);
	}
	else
		usage();

	return (0);
}
Example #27
0
int
s_client_main(int argc, char **argv)
{
	unsigned int off = 0, clr = 0;
	SSL *con = NULL;
	int s, k, width, state = 0, af = AF_UNSPEC;
	char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
	int cbuf_len, cbuf_off;
	int sbuf_len, sbuf_off;
	fd_set readfds, writefds;
	char *port = PORT_STR;
	int full_log = 1;
	char *host = SSL_HOST_NAME;
	char *cert_file = NULL, *key_file = NULL;
	int cert_format = FORMAT_PEM, key_format = FORMAT_PEM;
	char *passarg = NULL, *pass = NULL;
	X509 *cert = NULL;
	EVP_PKEY *key = NULL;
	char *CApath = NULL, *CAfile = NULL, *cipher = NULL;
	int reconnect = 0, badop = 0, verify = SSL_VERIFY_NONE, bugs = 0;
	int crlf = 0;
	int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
	SSL_CTX *ctx = NULL;
	int ret = 1, in_init = 1, i, nbio_test = 0;
	int starttls_proto = PROTO_OFF;
	int prexit = 0;
	X509_VERIFY_PARAM *vpm = NULL;
	int badarg = 0;
	const SSL_METHOD *meth = NULL;
	int socket_type = SOCK_STREAM;
	BIO *sbio;
	int mbuf_len = 0;
	struct timeval timeout, *timeoutp;
	const char *errstr = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine_id = NULL;
	char *ssl_client_engine_id = NULL;
	ENGINE *ssl_client_engine = NULL;
#endif
	ENGINE *e = NULL;
	char *servername = NULL;
	tlsextctx tlsextcbp =
	{NULL, 0};
#ifndef OPENSSL_NO_NEXTPROTONEG
	const char *next_proto_neg_in = NULL;
#endif
	char *sess_in = NULL;
	char *sess_out = NULL;
	struct sockaddr peer;
	int peerlen = sizeof(peer);
	int enable_timeouts = 0;
	long socket_mtu = 0;

	meth = SSLv23_client_method();

	c_Pause = 0;
	c_quiet = 0;
	c_ign_eof = 0;
	c_debug = 0;
	c_msg = 0;
	c_showcerts = 0;

	if (((cbuf = malloc(BUFSIZZ)) == NULL) ||
	    ((sbuf = malloc(BUFSIZZ)) == NULL) ||
	    ((mbuf = malloc(BUFSIZZ + 1)) == NULL)) {	/* NUL byte */
		BIO_printf(bio_err, "out of memory\n");
		goto end;
	}
	verify_depth = 0;
	verify_error = X509_V_OK;
	c_nbio = 0;

	argc--;
	argv++;
	while (argc >= 1) {
		if (strcmp(*argv, "-host") == 0) {
			if (--argc < 1)
				goto bad;
			host = *(++argv);
		} else if (strcmp(*argv, "-port") == 0) {
			if (--argc < 1)
				goto bad;
			port = *(++argv);
			if (port == NULL || *port == '\0')
				goto bad;
		} else if (strcmp(*argv, "-connect") == 0) {
			if (--argc < 1)
				goto bad;
			if (!extract_host_port(*(++argv), &host, NULL, &port))
				goto bad;
		} else if (strcmp(*argv, "-verify") == 0) {
			verify = SSL_VERIFY_PEER;
			if (--argc < 1)
				goto bad;
			verify_depth = strtonum(*(++argv), 0, INT_MAX, &errstr);
			if (errstr)
				goto bad;
			BIO_printf(bio_err, "verify depth is %d\n", verify_depth);
		} else if (strcmp(*argv, "-cert") == 0) {
			if (--argc < 1)
				goto bad;
			cert_file = *(++argv);
		} else if (strcmp(*argv, "-sess_out") == 0) {
			if (--argc < 1)
				goto bad;
			sess_out = *(++argv);
		} else if (strcmp(*argv, "-sess_in") == 0) {
			if (--argc < 1)
				goto bad;
			sess_in = *(++argv);
		} else if (strcmp(*argv, "-certform") == 0) {
			if (--argc < 1)
				goto bad;
			cert_format = str2fmt(*(++argv));
		} else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) {
			if (badarg)
				goto bad;
			continue;
		} else if (strcmp(*argv, "-verify_return_error") == 0)
			verify_return_error = 1;
		else if (strcmp(*argv, "-prexit") == 0)
			prexit = 1;
		else if (strcmp(*argv, "-crlf") == 0)
			crlf = 1;
		else if (strcmp(*argv, "-quiet") == 0) {
			c_quiet = 1;
			c_ign_eof = 1;
		} else if (strcmp(*argv, "-ign_eof") == 0)
			c_ign_eof = 1;
		else if (strcmp(*argv, "-no_ign_eof") == 0)
			c_ign_eof = 0;
		else if (strcmp(*argv, "-pause") == 0)
			c_Pause = 1;
		else if (strcmp(*argv, "-debug") == 0)
			c_debug = 1;
		else if (strcmp(*argv, "-tlsextdebug") == 0)
			c_tlsextdebug = 1;
		else if (strcmp(*argv, "-status") == 0)
			c_status_req = 1;
		else if (strcmp(*argv, "-msg") == 0)
			c_msg = 1;
		else if (strcmp(*argv, "-showcerts") == 0)
			c_showcerts = 1;
		else if (strcmp(*argv, "-nbio_test") == 0)
			nbio_test = 1;
		else if (strcmp(*argv, "-state") == 0)
			state = 1;
		else if (strcmp(*argv, "-ssl3") == 0)
			meth = SSLv3_client_method();
		else if (strcmp(*argv, "-tls1_2") == 0)
			meth = TLSv1_2_client_method();
		else if (strcmp(*argv, "-tls1_1") == 0)
			meth = TLSv1_1_client_method();
		else if (strcmp(*argv, "-tls1") == 0)
			meth = TLSv1_client_method();
#ifndef OPENSSL_NO_DTLS1
		else if (strcmp(*argv, "-dtls1") == 0) {
			meth = DTLSv1_client_method();
			socket_type = SOCK_DGRAM;
		} else if (strcmp(*argv, "-timeout") == 0)
			enable_timeouts = 1;
		else if (strcmp(*argv, "-mtu") == 0) {
			if (--argc < 1)
				goto bad;
			socket_mtu = strtonum(*(++argv), 0, LONG_MAX, &errstr);
			if (errstr)
				goto bad;
		}
#endif
		else if (strcmp(*argv, "-bugs") == 0)
			bugs = 1;
		else if (strcmp(*argv, "-keyform") == 0) {
			if (--argc < 1)
				goto bad;
			key_format = str2fmt(*(++argv));
		} else if (strcmp(*argv, "-pass") == 0) {
			if (--argc < 1)
				goto bad;
			passarg = *(++argv);
		} else if (strcmp(*argv, "-key") == 0) {
			if (--argc < 1)
				goto bad;
			key_file = *(++argv);
		} else if (strcmp(*argv, "-reconnect") == 0) {
			reconnect = 5;
		} else if (strcmp(*argv, "-CApath") == 0) {
			if (--argc < 1)
				goto bad;
			CApath = *(++argv);
		} else if (strcmp(*argv, "-CAfile") == 0) {
			if (--argc < 1)
				goto bad;
			CAfile = *(++argv);
		} else if (strcmp(*argv, "-no_tls1_2") == 0)
			off |= SSL_OP_NO_TLSv1_2;
		else if (strcmp(*argv, "-no_tls1_1") == 0)
			off |= SSL_OP_NO_TLSv1_1;
		else if (strcmp(*argv, "-no_tls1") == 0)
			off |= SSL_OP_NO_TLSv1;
		else if (strcmp(*argv, "-no_ssl3") == 0)
			off |= SSL_OP_NO_SSLv3;
		else if (strcmp(*argv, "-no_ssl2") == 0)
			off |= SSL_OP_NO_SSLv2;
		else if (strcmp(*argv, "-no_comp") == 0) {
			off |= SSL_OP_NO_COMPRESSION;
		}
		else if (strcmp(*argv, "-no_ticket") == 0) {
			off |= SSL_OP_NO_TICKET;
		}
#ifndef OPENSSL_NO_NEXTPROTONEG
		else if (strcmp(*argv, "-nextprotoneg") == 0) {
			if (--argc < 1)
				goto bad;
			next_proto_neg_in = *(++argv);
		}
#endif
		else if (strcmp(*argv, "-serverpref") == 0)
			off |= SSL_OP_CIPHER_SERVER_PREFERENCE;
		else if (strcmp(*argv, "-legacy_renegotiation") == 0)
			; /* no-op */
		else if (strcmp(*argv, "-legacy_server_connect") == 0) {
			off |= SSL_OP_LEGACY_SERVER_CONNECT;
		} else if (strcmp(*argv, "-no_legacy_server_connect") == 0) {
			clr |= SSL_OP_LEGACY_SERVER_CONNECT;
		} else if (strcmp(*argv, "-cipher") == 0) {
			if (--argc < 1)
				goto bad;
			cipher = *(++argv);
		}
		else if (strcmp(*argv, "-nbio") == 0) {
			c_nbio = 1;
		}
		else if (strcmp(*argv, "-starttls") == 0) {
			if (--argc < 1)
				goto bad;
			++argv;
			if (strcmp(*argv, "smtp") == 0)
				starttls_proto = PROTO_SMTP;
			else if (strcmp(*argv, "lmtp") == 0)
				starttls_proto = PROTO_LMTP;
			else if (strcmp(*argv, "pop3") == 0)
				starttls_proto = PROTO_POP3;
			else if (strcmp(*argv, "imap") == 0)
				starttls_proto = PROTO_IMAP;
			else if (strcmp(*argv, "ftp") == 0)
				starttls_proto = PROTO_FTP;
			else if (strcmp(*argv, "xmpp") == 0)
				starttls_proto = PROTO_XMPP;
			else
				goto bad;
		}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv, "-engine") == 0) {
			if (--argc < 1)
				goto bad;
			engine_id = *(++argv);
		} else if (strcmp(*argv, "-ssl_client_engine") == 0) {
			if (--argc < 1)
				goto bad;
			ssl_client_engine_id = *(++argv);
		}
#endif
		else if (strcmp(*argv, "-4") == 0) {
			af = AF_INET;
		} else if (strcmp(*argv, "-6") == 0) {
			af = AF_INET6;
		}
		else if (strcmp(*argv, "-servername") == 0) {
			if (--argc < 1)
				goto bad;
			servername = *(++argv);
			/* meth=TLSv1_client_method(); */
		}
#ifndef OPENSSL_NO_SRTP
		else if (strcmp(*argv, "-use_srtp") == 0) {
			if (--argc < 1)
				goto bad;
			srtp_profiles = *(++argv);
		}
#endif
		else if (strcmp(*argv, "-keymatexport") == 0) {
			if (--argc < 1)
				goto bad;
			keymatexportlabel = *(++argv);
		} else if (strcmp(*argv, "-keymatexportlen") == 0) {
			if (--argc < 1)
				goto bad;
			keymatexportlen = strtonum(*(++argv), 1, INT_MAX, &errstr);
			if (errstr)
				goto bad;
		} else {
			BIO_printf(bio_err, "unknown option %s\n", *argv);
			badop = 1;
			break;
		}
		argc--;
		argv++;
	}
	if (badop) {
bad:
		if (errstr)
			BIO_printf(bio_err, "invalid argument %s: %s\n",
			    *argv, errstr);
		else
			sc_usage();
		goto end;
	}

#if !defined(OPENSSL_NO_NEXTPROTONEG)
	next_proto.status = -1;
	if (next_proto_neg_in) {
		next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
		if (next_proto.data == NULL) {
			BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
			goto end;
		}
	} else
		next_proto.data = NULL;
#endif

#ifndef OPENSSL_NO_ENGINE
	e = setup_engine(bio_err, engine_id, 1);
	if (ssl_client_engine_id) {
		ssl_client_engine = ENGINE_by_id(ssl_client_engine_id);
		if (!ssl_client_engine) {
			BIO_printf(bio_err,
			    "Error getting client auth engine\n");
			goto end;
		}
	}
#endif
	if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
		BIO_printf(bio_err, "Error getting password\n");
		goto end;
	}
	if (key_file == NULL)
		key_file = cert_file;


	if (key_file) {

		key = load_key(bio_err, key_file, key_format, 0, pass, e,
		    "client certificate private key file");
		if (!key) {
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (cert_file) {
		cert = load_cert(bio_err, cert_file, cert_format,
		    NULL, e, "client certificate file");

		if (!cert) {
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (bio_c_out == NULL) {
		if (c_quiet && !c_debug && !c_msg) {
			bio_c_out = BIO_new(BIO_s_null());
		} else {
			if (bio_c_out == NULL)
				bio_c_out = BIO_new_fp(stdout, BIO_NOCLOSE);
		}
	}

	ctx = SSL_CTX_new(meth);
	if (ctx == NULL) {
		ERR_print_errors(bio_err);
		goto end;
	}
	if (vpm)
		SSL_CTX_set1_param(ctx, vpm);

#ifndef OPENSSL_NO_ENGINE
	if (ssl_client_engine) {
		if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
			BIO_puts(bio_err, "Error setting client auth engine\n");
			ERR_print_errors(bio_err);
			ENGINE_free(ssl_client_engine);
			goto end;
		}
		ENGINE_free(ssl_client_engine);
	}
#endif

#ifndef OPENSSL_NO_SRTP
	if (srtp_profiles != NULL)
		SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles);
#endif
	if (bugs)
		SSL_CTX_set_options(ctx, SSL_OP_ALL | off);
	else
		SSL_CTX_set_options(ctx, off);

	if (clr)
		SSL_CTX_clear_options(ctx, clr);
	/*
	 * DTLS: partial reads end up discarding unread UDP bytes :-( Setting
	 * read ahead solves this problem.
	 */
	if (socket_type == SOCK_DGRAM)
		SSL_CTX_set_read_ahead(ctx, 1);

#if !defined(OPENSSL_NO_NEXTPROTONEG)
	if (next_proto.data)
		SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
#endif

	if (state)
		SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
	if (cipher != NULL)
		if (!SSL_CTX_set_cipher_list(ctx, cipher)) {
			BIO_printf(bio_err, "error setting cipher list\n");
			ERR_print_errors(bio_err);
			goto end;
		}

	SSL_CTX_set_verify(ctx, verify, verify_callback);
	if (!set_cert_key_stuff(ctx, cert, key))
		goto end;

	if ((!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) ||
	    (!SSL_CTX_set_default_verify_paths(ctx))) {
		/*
		 * BIO_printf(bio_err,"error setting default verify
		 * locations\n");
		 */
		ERR_print_errors(bio_err);
		/* goto end; */
	}
	if (servername != NULL) {
		tlsextcbp.biodebug = bio_err;
		SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
		SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
	}

	con = SSL_new(ctx);
	if (sess_in) {
		SSL_SESSION *sess;
		BIO *stmp = BIO_new_file(sess_in, "r");
		if (!stmp) {
			BIO_printf(bio_err, "Can't open session file %s\n",
			    sess_in);
			ERR_print_errors(bio_err);
			goto end;
		}
		sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
		BIO_free(stmp);
		if (!sess) {
			BIO_printf(bio_err, "Can't open session file %s\n",
			    sess_in);
			ERR_print_errors(bio_err);
			goto end;
		}
		SSL_set_session(con, sess);
		SSL_SESSION_free(sess);
	}
	if (servername != NULL) {
		if (!SSL_set_tlsext_host_name(con, servername)) {
			BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
			ERR_print_errors(bio_err);
			goto end;
		}
	}
/*	SSL_set_cipher_list(con,"RC4-MD5"); */

re_start:

	if (init_client(&s, host, port, socket_type, af) == 0) {
		BIO_printf(bio_err, "connect:errno=%d\n", errno);
		goto end;
	}
	BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);

	if (c_nbio) {
		if (!c_quiet)
			BIO_printf(bio_c_out, "turning on non blocking io\n");
		if (!BIO_socket_nbio(s, 1)) {
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (c_Pause & 0x01)
		SSL_set_debug(con, 1);

	if (SSL_version(con) == DTLS1_VERSION) {

		sbio = BIO_new_dgram(s, BIO_NOCLOSE);
		if (getsockname(s, &peer, (void *) &peerlen) < 0) {
			BIO_printf(bio_err, "getsockname:errno=%d\n",
			    errno);
			shutdown(s, SHUT_RD);
			close(s);
			goto end;
		}
		(void) BIO_ctrl_set_connected(sbio, 1, &peer);

		if (enable_timeouts) {
			timeout.tv_sec = 0;
			timeout.tv_usec = DGRAM_RCV_TIMEOUT;
			BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);

			timeout.tv_sec = 0;
			timeout.tv_usec = DGRAM_SND_TIMEOUT;
			BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
		}
		if (socket_mtu > 28) {
			SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
			SSL_set_mtu(con, socket_mtu - 28);
		} else
			/* want to do MTU discovery */
			BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
	} else
		sbio = BIO_new_socket(s, BIO_NOCLOSE);

	if (nbio_test) {
		BIO *test;

		test = BIO_new(BIO_f_nbio_test());
		sbio = BIO_push(test, sbio);
	}
	if (c_debug) {
		SSL_set_debug(con, 1);
		BIO_set_callback(sbio, bio_dump_callback);
		BIO_set_callback_arg(sbio, (char *) bio_c_out);
	}
	if (c_msg) {
		SSL_set_msg_callback(con, msg_cb);
		SSL_set_msg_callback_arg(con, bio_c_out);
	}
	if (c_tlsextdebug) {
		SSL_set_tlsext_debug_callback(con, tlsext_cb);
		SSL_set_tlsext_debug_arg(con, bio_c_out);
	}
	if (c_status_req) {
		SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
		SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
		SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
	}

	SSL_set_bio(con, sbio, sbio);
	SSL_set_connect_state(con);

	/* ok, lets connect */
	width = SSL_get_fd(con) + 1;

	read_tty = 1;
	write_tty = 0;
	tty_on = 0;
	read_ssl = 1;
	write_ssl = 1;

	cbuf_len = 0;
	cbuf_off = 0;
	sbuf_len = 0;
	sbuf_off = 0;

	/* This is an ugly hack that does a lot of assumptions */
	/*
	 * We do have to handle multi-line responses which may come in a
	 * single packet or not. We therefore have to use BIO_gets() which
	 * does need a buffering BIO. So during the initial chitchat we do
	 * push a buffering BIO into the chain that is removed again later on
	 * to not disturb the rest of the s_client operation.
	 */
	if (starttls_proto == PROTO_SMTP || starttls_proto == PROTO_LMTP) {
		int foundit = 0;
		BIO *fbio = BIO_new(BIO_f_buffer());
		BIO_push(fbio, sbio);
		/* wait for multi-line response to end from SMTP */
		do {
			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
		}
		while (mbuf_len > 3 && mbuf[3] == '-');
		/* STARTTLS command requires EHLO... */
		BIO_printf(fbio, "%cHLO openssl.client.net\r\n",
			   starttls_proto == PROTO_SMTP ? 'E' : 'L');
		(void) BIO_flush(fbio);
		/* wait for multi-line response to end EHLO SMTP response */
		do {
			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
			if (strstr(mbuf, "STARTTLS"))
				foundit = 1;
		}
		while (mbuf_len > 3 && mbuf[3] == '-');
		(void) BIO_flush(fbio);
		BIO_pop(fbio);
		BIO_free(fbio);
		if (!foundit)
			BIO_printf(bio_err,
			    "didn't found starttls in server response,"
			    " try anyway...\n");
		BIO_printf(sbio, "STARTTLS\r\n");
		BIO_read(sbio, sbuf, BUFSIZZ);
	} else if (starttls_proto == PROTO_POP3) {
		mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
		if (mbuf_len == -1) {
			BIO_printf(bio_err, "BIO_read failed\n");
			goto end;
		}
		BIO_printf(sbio, "STLS\r\n");
		BIO_read(sbio, sbuf, BUFSIZZ);
	} else if (starttls_proto == PROTO_IMAP) {
		int foundit = 0;
		BIO *fbio = BIO_new(BIO_f_buffer());
		BIO_push(fbio, sbio);
		BIO_gets(fbio, mbuf, BUFSIZZ);
		/* STARTTLS command requires CAPABILITY... */
		BIO_printf(fbio, ". CAPABILITY\r\n");
		(void) BIO_flush(fbio);
		/* wait for multi-line CAPABILITY response */
		do {
			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
			if (strstr(mbuf, "STARTTLS"))
				foundit = 1;
		}
		while (mbuf_len > 3 && mbuf[0] != '.');
		(void) BIO_flush(fbio);
		BIO_pop(fbio);
		BIO_free(fbio);
		if (!foundit)
			BIO_printf(bio_err,
			    "didn't found STARTTLS in server response,"
			    " try anyway...\n");
		BIO_printf(sbio, ". STARTTLS\r\n");
		BIO_read(sbio, sbuf, BUFSIZZ);
	} else if (starttls_proto == PROTO_FTP) {
		BIO *fbio = BIO_new(BIO_f_buffer());
		BIO_push(fbio, sbio);
		/* wait for multi-line response to end from FTP */
		do {
			mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
		}
		while (mbuf_len > 3 && mbuf[3] == '-');
		(void) BIO_flush(fbio);
		BIO_pop(fbio);
		BIO_free(fbio);
		BIO_printf(sbio, "AUTH TLS\r\n");
		BIO_read(sbio, sbuf, BUFSIZZ);
	}
	if (starttls_proto == PROTO_XMPP) {
		int seen = 0;
		BIO_printf(sbio, "<stream:stream "
		    "xmlns:stream='http://etherx.jabber.org/streams' "
		    "xmlns='jabber:client' to='%s' version='1.0'>", host);
		seen = BIO_read(sbio, mbuf, BUFSIZZ);
		mbuf[seen] = 0;
		while (!strstr(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")) {
			if (strstr(mbuf, "/stream:features>"))
				goto shut;
			seen = BIO_read(sbio, mbuf, BUFSIZZ);
			mbuf[seen] = 0;
		}
		BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
		seen = BIO_read(sbio, sbuf, BUFSIZZ);
		sbuf[seen] = 0;
		if (!strstr(sbuf, "<proceed"))
			goto shut;
		mbuf[0] = 0;
	}
	for (;;) {
		FD_ZERO(&readfds);
		FD_ZERO(&writefds);

		if ((SSL_version(con) == DTLS1_VERSION) &&
		    DTLSv1_get_timeout(con, &timeout))
			timeoutp = &timeout;
		else
			timeoutp = NULL;

		if (SSL_in_init(con) && !SSL_total_renegotiations(con)) {
			in_init = 1;
			tty_on = 0;
		} else {
			tty_on = 1;
			if (in_init) {
				in_init = 0;
				if (sess_out) {
					BIO *stmp = BIO_new_file(sess_out, "w");
					if (stmp) {
						PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
						BIO_free(stmp);
					} else
						BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
				}
				print_stuff(bio_c_out, con, full_log);
				if (full_log > 0)
					full_log--;

				if (starttls_proto) {
					BIO_write(bio_err, mbuf, mbuf_len);
					/* We don't need to know any more */
					starttls_proto = PROTO_OFF;
				}
				if (reconnect) {
					reconnect--;
					BIO_printf(bio_c_out, "drop connection and then reconnect\n");
					SSL_shutdown(con);
					SSL_set_connect_state(con);
					shutdown(SSL_get_fd(con), SHUT_RD);
					close(SSL_get_fd(con));
					goto re_start;
				}
			}
		}

		ssl_pending = read_ssl && SSL_pending(con);

		/* XXX should add tests for fd_set overflow */

		if (!ssl_pending) {
			if (tty_on) {
				if (read_tty)
					FD_SET(fileno(stdin), &readfds);
				if (write_tty)
					FD_SET(fileno(stdout), &writefds);
			}
			if (read_ssl)
				FD_SET(SSL_get_fd(con), &readfds);
			if (write_ssl)
				FD_SET(SSL_get_fd(con), &writefds);
/*			printf("mode tty(%d %d%d) ssl(%d%d)\n",
				tty_on,read_tty,write_tty,read_ssl,write_ssl);*/

			i = select(width, &readfds, &writefds,
			    NULL, timeoutp);
			if (i < 0) {
				BIO_printf(bio_err, "bad select %d\n",
				    errno);
				goto shut;
				/* goto end; */
			}
		}
		if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0) {
			BIO_printf(bio_err, "TIMEOUT occured\n");
		}
		if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
			k = SSL_write(con, &(cbuf[cbuf_off]),
			    (unsigned int) cbuf_len);
			switch (SSL_get_error(con, k)) {
			case SSL_ERROR_NONE:
				cbuf_off += k;
				cbuf_len -= k;
				if (k <= 0)
					goto end;
				/* we have done a  write(con,NULL,0); */
				if (cbuf_len <= 0) {
					read_tty = 1;
					write_ssl = 0;
				} else {	/* if (cbuf_len > 0) */
					read_tty = 0;
					write_ssl = 1;
				}
				break;
			case SSL_ERROR_WANT_WRITE:
				BIO_printf(bio_c_out, "write W BLOCK\n");
				write_ssl = 1;
				read_tty = 0;
				break;
			case SSL_ERROR_WANT_READ:
				BIO_printf(bio_c_out, "write R BLOCK\n");
				write_tty = 0;
				read_ssl = 1;
				write_ssl = 0;
				break;
			case SSL_ERROR_WANT_X509_LOOKUP:
				BIO_printf(bio_c_out, "write X BLOCK\n");
				break;
			case SSL_ERROR_ZERO_RETURN:
				if (cbuf_len != 0) {
					BIO_printf(bio_c_out, "shutdown\n");
					ret = 0;
					goto shut;
				} else {
					read_tty = 1;
					write_ssl = 0;
					break;
				}

			case SSL_ERROR_SYSCALL:
				if ((k != 0) || (cbuf_len != 0)) {
					BIO_printf(bio_err, "write:errno=%d\n",
					    errno);
					goto shut;
				} else {
					read_tty = 1;
					write_ssl = 0;
				}
				break;
			case SSL_ERROR_SSL:
				ERR_print_errors(bio_err);
				goto shut;
			}
		} else if (!ssl_pending && FD_ISSET(fileno(stdout), &writefds)) {
			i = write(fileno(stdout), &(sbuf[sbuf_off]), sbuf_len);

			if (i <= 0) {
				BIO_printf(bio_c_out, "DONE\n");
				ret = 0;
				goto shut;
				/* goto end; */
			}
			sbuf_len -= i;
			sbuf_off += i;
			if (sbuf_len <= 0) {
				read_ssl = 1;
				write_tty = 0;
			}
		} else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
#ifdef RENEG
			{
				static int iiii;
				if (++iiii == 52) {
					SSL_renegotiate(con);
					iiii = 0;
				}
			}
#endif
			k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );

			switch (SSL_get_error(con, k)) {
			case SSL_ERROR_NONE:
				if (k <= 0)
					goto end;
				sbuf_off = 0;
				sbuf_len = k;

				read_ssl = 0;
				write_tty = 1;
				break;
			case SSL_ERROR_WANT_WRITE:
				BIO_printf(bio_c_out, "read W BLOCK\n");
				write_ssl = 1;
				read_tty = 0;
				break;
			case SSL_ERROR_WANT_READ:
				BIO_printf(bio_c_out, "read R BLOCK\n");
				write_tty = 0;
				read_ssl = 1;
				if ((read_tty == 0) && (write_ssl == 0))
					write_ssl = 1;
				break;
			case SSL_ERROR_WANT_X509_LOOKUP:
				BIO_printf(bio_c_out, "read X BLOCK\n");
				break;
			case SSL_ERROR_SYSCALL:
				ret = errno;
				BIO_printf(bio_err, "read:errno=%d\n", ret);
				goto shut;
			case SSL_ERROR_ZERO_RETURN:
				BIO_printf(bio_c_out, "closed\n");
				ret = 0;
				goto shut;
			case SSL_ERROR_SSL:
				ERR_print_errors(bio_err);
				goto shut;
				/* break; */
			}
		} else if (FD_ISSET(fileno(stdin), &readfds)) {
			if (crlf) {
				int j, lf_num;

				i = read(fileno(stdin), cbuf, BUFSIZZ / 2);
				lf_num = 0;
				/* both loops are skipped when i <= 0 */
				for (j = 0; j < i; j++)
					if (cbuf[j] == '\n')
						lf_num++;
				for (j = i - 1; j >= 0; j--) {
					cbuf[j + lf_num] = cbuf[j];
					if (cbuf[j] == '\n') {
						lf_num--;
						i++;
						cbuf[j + lf_num] = '\r';
					}
				}
				assert(lf_num == 0);
			} else
				i = read(fileno(stdin), cbuf, BUFSIZZ);

			if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q'))) {
				BIO_printf(bio_err, "DONE\n");
				ret = 0;
				goto shut;
			}
			if ((!c_ign_eof) && (cbuf[0] == 'R')) {
				BIO_printf(bio_err, "RENEGOTIATING\n");
				SSL_renegotiate(con);
				cbuf_len = 0;
			} else {
				cbuf_len = i;
				cbuf_off = 0;
			}

			write_ssl = 1;
			read_tty = 0;
		}
	}

	ret = 0;
shut:
	if (in_init)
		print_stuff(bio_c_out, con, full_log);
	SSL_shutdown(con);
	shutdown(SSL_get_fd(con), SHUT_RD);
	close(SSL_get_fd(con));
end:
	if (con != NULL) {
		if (prexit != 0)
			print_stuff(bio_c_out, con, 1);
		SSL_free(con);
	}
#if !defined(OPENSSL_NO_NEXTPROTONEG)
	free(next_proto.data);
#endif
	if (ctx != NULL)
		SSL_CTX_free(ctx);
	if (cert)
		X509_free(cert);
	if (key)
		EVP_PKEY_free(key);
	free(pass);
	if (vpm)
		X509_VERIFY_PARAM_free(vpm);
	if (cbuf != NULL) {
		OPENSSL_cleanse(cbuf, BUFSIZZ);
		free(cbuf);
	}
	if (sbuf != NULL) {
		OPENSSL_cleanse(sbuf, BUFSIZZ);
		free(sbuf);
	}
	if (mbuf != NULL) {
		OPENSSL_cleanse(mbuf, BUFSIZZ);
		free(mbuf);
	}
	if (bio_c_out != NULL) {
		BIO_free(bio_c_out);
		bio_c_out = NULL;
	}

	return (ret);
}
Example #28
0
/*
 * expand_builtin - evaluate built-in macros.
 */
void
expand_builtin(const char *argv[], int argc, int td)
{
	int c, n;
	int ac;
	static int sysval = 0;

#ifdef DEBUG
	printf("argc = %d\n", argc);
	for (n = 0; n < argc; n++)
		printf("argv[%d] = %s\n", n, argv[n]);
	fflush(stdout);
#endif

 /*
  * if argc == 3 and argv[2] is null, then we
  * have macro-or-builtin() type call. We adjust
  * argc to avoid further checking..
  */
 /* we keep the initial value for those built-ins that differentiate
  * between builtin() and builtin.
  */
	ac = argc;

	if (argc == 3 && !*(argv[2]) && !mimic_gnu)
		argc--;

	switch (td & TYPEMASK) {

	case DEFITYPE:
		if (argc > 2)
			dodefine(argv[2], (argc > 3) ? argv[3] : null);
		break;

	case PUSDTYPE:
		if (argc > 2)
			dopushdef(argv[2], (argc > 3) ? argv[3] : null);
		break;

	case DUMPTYPE:
		dodump(argv, argc);
		break;

	case TRACEONTYPE:
		dotrace(argv, argc, 1);
		break;

	case TRACEOFFTYPE:
		dotrace(argv, argc, 0);
		break;

	case EXPRTYPE:
	/*
	 * doexpr - evaluate arithmetic
	 * expression
	 */
	{
		int base = 10;
		int maxdigits = 0;
		const char *errstr;

		if (argc > 3) {
			base = strtonum(argv[3], 2, 36, &errstr);
			if (errstr) {
				m4errx(1, "expr: base %s invalid.", argv[3]);
			}
		}
		if (argc > 4) {
			maxdigits = strtonum(argv[4], 0, INT_MAX, &errstr);
			if (errstr) {
				m4errx(1, "expr: maxdigits %s invalid.", argv[4]);
			}
		}
		if (argc > 2)
			pbnumbase(expr(argv[2]), base, maxdigits);
		break;
	}

	case IFELTYPE:
		if (argc > 4)
			doifelse(argv, argc);
		break;

	case IFDFTYPE:
	/*
	 * doifdef - select one of two
	 * alternatives based on the existence of
	 * another definition
	 */
		if (argc > 3) {
			if (lookup_macro_definition(argv[2]) != NULL)
				pbstr(argv[3]);
			else if (argc > 4)
				pbstr(argv[4]);
		}
		break;

	case LENGTYPE:
	/*
	 * dolen - find the length of the
	 * argument
	 */
		pbnum((argc > 2) ? strlen(argv[2]) : 0);
		break;

	case INCRTYPE:
	/*
	 * doincr - increment the value of the
	 * argument
	 */
		if (argc > 2)
			pbnum(atoi(argv[2]) + 1);
		break;

	case DECRTYPE:
	/*
	 * dodecr - decrement the value of the
	 * argument
	 */
		if (argc > 2)
			pbnum(atoi(argv[2]) - 1);
		break;

	case SYSCTYPE:
	/*
	 * dosys - execute system command
	 */
		if (argc > 2) {
			fflush(stdout);
			sysval = system(argv[2]);
		}
		break;

	case SYSVTYPE:
	/*
	 * dosysval - return value of the last
	 * system call.
	 *
	 */
		pbnum(sysval);
		break;

	case ESYSCMDTYPE:
		if (argc > 2)
			doesyscmd(argv[2]);
		break;
	case INCLTYPE:
		if (argc > 2)
			if (!doincl(argv[2])) {
				if (mimic_gnu) {
					warn("%s at line %lu: include(%s)",
					    CURRENT_NAME, CURRENT_LINE, argv[2]);
					exit_code = 1;
				} else
					err(1, "%s at line %lu: include(%s)",
					    CURRENT_NAME, CURRENT_LINE, argv[2]);
			}
		break;

	case SINCTYPE:
		if (argc > 2)
			(void) doincl(argv[2]);
		break;
#ifdef EXTENDED
	case PASTTYPE:
		if (argc > 2)
			if (!dopaste(argv[2]))
				err(1, "%s at line %lu: paste(%s)", 
				    CURRENT_NAME, CURRENT_LINE, argv[2]);
		break;

	case SPASTYPE:
		if (argc > 2)
			(void) dopaste(argv[2]);
		break;
	case FORMATTYPE:
		doformat(argv, argc);
		break;
#endif
	case CHNQTYPE:
		dochq(argv, ac);
		break;

	case CHNCTYPE:
		dochc(argv, argc);
		break;

	case SUBSTYPE:
	/*
	 * dosub - select substring
	 *
	 */
		if (argc > 3)
			dosub(argv, argc);
		break;

	case SHIFTYPE:
	/*
	 * doshift - push back all arguments
	 * except the first one (i.e. skip
	 * argv[2])
	 */
		if (argc > 3) {
			for (n = argc - 1; n > 3; n--) {
				pbstr(rquote);
				pbstr(argv[n]);
				pbstr(lquote);
				pushback(COMMA);
			}
			pbstr(rquote);
			pbstr(argv[3]);
			pbstr(lquote);
		}
		break;

	case DIVRTYPE:
		if (argc > 2 && (n = atoi(argv[2])) != 0)
			dodiv(n);
		else {
			active = stdout;
			oindex = 0;
		}
		break;

	case UNDVTYPE:
		doundiv(argv, argc);
		break;

	case DIVNTYPE:
	/*
	 * dodivnum - return the number of
	 * current output diversion
	 */
		pbnum(oindex);
		break;

	case UNDFTYPE:
	/*
	 * doundefine - undefine a previously
	 * defined macro(s) or m4 keyword(s).
	 */
		if (argc > 2)
			for (n = 2; n < argc; n++)
				macro_undefine(argv[n]);
		break;

	case POPDTYPE:
	/*
	 * dopopdef - remove the topmost
	 * definitions of macro(s) or m4
	 * keyword(s).
	 */
		if (argc > 2)
			for (n = 2; n < argc; n++)
				macro_popdef(argv[n]);
		break;

	case MKTMTYPE:
	/*
	 * dotemp - create a temporary file
	 */
		if (argc > 2) {
			int fd;
			char *temp;

			temp = xstrdup(argv[2]);

			fd = mkstemp(temp);
			if (fd == -1)
				err(1,
	    "%s at line %lu: couldn't make temp file %s",
	    CURRENT_NAME, CURRENT_LINE, argv[2]);
			close(fd);
			pbstr(temp);
			free(temp);
		}
		break;

	case TRNLTYPE:
	/*
	 * dotranslit - replace all characters in
	 * the source string that appears in the
	 * "from" string with the corresponding
	 * characters in the "to" string.
	 */
		if (argc > 3) {
			char *temp;

			temp = xalloc(strlen(argv[2])+1, NULL);
			if (argc > 4)
				map(temp, argv[2], argv[3], argv[4]);
			else
				map(temp, argv[2], argv[3], null);
			pbstr(temp);
			free(temp);
		} else if (argc > 2)
			pbstr(argv[2]);
		break;

	case INDXTYPE:
	/*
	 * doindex - find the index of the second
	 * argument string in the first argument
	 * string. -1 if not present.
	 */
		pbnum((argc > 3) ? indx(argv[2], argv[3]) : -1);
		break;

	case ERRPTYPE:
	/*
	 * doerrp - print the arguments to stderr
	 * file
	 */
		if (argc > 2) {
			for (n = 2; n < argc; n++)
				fprintf(stderr, "%s ", argv[n]);
			fprintf(stderr, "\n");
		}
		break;

	case DNLNTYPE:
	/*
	 * dodnl - eat-up-to and including
	 * newline
	 */
		while ((c = gpbc()) != '\n' && c != EOF)
			;
		break;

	case M4WRTYPE:
	/*
	 * dom4wrap - set up for
	 * wrap-up/wind-down activity
	 */
		if (argc > 2)
			dom4wrap(argv[2]);
		break;

	case EXITTYPE:
	/*
	 * doexit - immediate exit from m4.
	 */
		killdiv();
		exit((argc > 2) ? atoi(argv[2]) : 0);
		break;

	case DEFNTYPE:
		if (argc > 2)
			for (n = 2; n < argc; n++)
				dodefn(argv[n]);
		break;

	case INDIRTYPE:	/* Indirect call */
		if (argc > 2)
			doindir(argv, argc);
		break;

	case BUILTINTYPE: /* Builtins only */
		if (argc > 2)
			dobuiltin(argv, argc);
		break;

	case PATSTYPE:
		if (argc > 2)
			dopatsubst(argv, argc);
		break;
	case REGEXPTYPE:
		if (argc > 2)
			doregexp(argv, argc);
		break;
	case LINETYPE:
		doprintlineno(infile+ilevel);
		break;
	case FILENAMETYPE:
		doprintfilename(infile+ilevel);
		break;
	case SELFTYPE:
		pbstr(rquote);
		pbstr(argv[1]);
		pbstr(lquote);
		break;
	default:
		m4errx(1, "eval: major botch.");
		break;
	}
}
Example #29
0
int
main(int argc, char *argv[])
{
	static char dot[] = ".", *dotav[] = {dot, NULL};
	struct winsize win;
	int ch, fts_options, notused;
	char *p;
	const char *errstr = NULL;
#ifdef COLORLS
	char termcapbuf[1024];	/* termcap definition buffer */
	char tcapbuf[512];	/* capability buffer */
	char *bp = tcapbuf;
#endif

	(void)setlocale(LC_ALL, "");

	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
	if (isatty(STDOUT_FILENO)) {
		termwidth = 80;
		if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
			termwidth = strtonum(p, 0, INT_MAX, &errstr);
		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
		    win.ws_col > 0)
			termwidth = win.ws_col;
		f_nonprint = 1;
	} else {
		f_singlecol = 1;
		/* retrieve environment variable, in case of explicit -C */
		p = getenv("COLUMNS");
		if (p)
			termwidth = strtonum(p, 0, INT_MAX, &errstr);
	}

	if (errstr)
		termwidth = 80;

	fts_options = FTS_PHYSICAL;
	if (getenv("LS_SAMESORT"))
		f_samesort = 1;

	argc = xo_parse_args(argc, argv);
	if (argc < 0)
		return (1);
	xo_set_flags(NULL, XOF_COLUMNS);

	while ((ch = getopt(argc, argv,
	    "1ABCD:FGHILPRSTUWXZabcdfghiklmnopqrstuwxy,")) != -1) {
		switch (ch) {
		/*
		 * The -1, -C, -x and -l options all override each other so
		 * shell aliasing works right.
		 */
		case '1':
			f_singlecol = 1;
			f_longform = 0;
			f_stream = 0;
			break;
		case 'C':
			f_sortacross = f_longform = f_singlecol = 0;
			break;
		case 'l':
			f_longform = 1;
			f_singlecol = 0;
			f_stream = 0;
			break;
		case 'x':
			f_sortacross = 1;
			f_longform = 0;
			f_singlecol = 0;
			break;
		/* The -c, -u, and -U options override each other. */
		case 'c':
			f_statustime = 1;
			f_accesstime = 0;
			f_birthtime = 0;
			break;
		case 'u':
			f_accesstime = 1;
			f_statustime = 0;
			f_birthtime = 0;
			break;
		case 'U':
			f_birthtime = 1;
			f_accesstime = 0;
			f_statustime = 0;
			break;
		case 'f':
			f_nosort = 1;
		       /* FALLTHROUGH */
		case 'a':
			fts_options |= FTS_SEEDOT;
			/* FALLTHROUGH */
		case 'A':
			f_listdot = 1;
			break;
		/* The -t and -S options override each other. */
		case 'S':
			f_sizesort = 1;
			f_timesort = 0;
			break;
		case 't':
			f_timesort = 1;
			f_sizesort = 0;
			break;
		/* Other flags.  Please keep alphabetic. */
		case ',':
			f_thousands = 1;
			break;
		case 'B':
			f_nonprint = 0;
			f_octal = 1;
			f_octal_escape = 0;
			break;
		case 'D':
			f_timeformat = optarg;
			break;
		case 'F':
			f_type = 1;
			f_slash = 0;
			break;
		case 'G':
			setenv("CLICOLOR", "", 1);
			break;
		case 'H':
			fts_options |= FTS_COMFOLLOW;
			f_nofollow = 0;
			break;
		case 'I':
			f_noautodot = 1;
			break;
		case 'L':
			fts_options &= ~FTS_PHYSICAL;
			fts_options |= FTS_LOGICAL;
			f_nofollow = 0;
			break;
		case 'P':
			fts_options &= ~FTS_COMFOLLOW;
			fts_options &= ~FTS_LOGICAL;
			fts_options |= FTS_PHYSICAL;
			f_nofollow = 1;
			break;
		case 'R':
			f_recursive = 1;
			break;
		case 'T':
			f_sectime = 1;
			break;
		case 'W':
			f_whiteout = 1;
			break;
		case 'Z':
			f_label = 1;
			break;
		case 'b':
			f_nonprint = 0;
			f_octal = 0;
			f_octal_escape = 1;
			break;
		/* The -d option turns off the -R option. */
		case 'd':
			f_listdir = 1;
			f_recursive = 0;
			break;
		case 'g':	/* Compatibility with 4.3BSD. */
			break;
		case 'h':
			f_humanval = 1;
			break;
		case 'i':
			f_inode = 1;
			break;
		case 'k':
			f_humanval = 0;
			f_kblocks = 1;
			break;
		case 'm':
			f_stream = 1;
			f_singlecol = 0;
			f_longform = 0;
			break;
		case 'n':
			f_numericonly = 1;
			break;
		case 'o':
			f_flags = 1;
			break;
		case 'p':
			f_slash = 1;
			f_type = 1;
			break;
		case 'q':
			f_nonprint = 1;
			f_octal = 0;
			f_octal_escape = 0;
			break;
		case 'r':
			f_reversesort = 1;
			break;
		case 's':
			f_size = 1;
			break;
		case 'w':
			f_nonprint = 0;
			f_octal = 0;
			f_octal_escape = 0;
			break;
		case 'y':
			f_samesort = 1;
			break;
		default:
		case '?':
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	/* Root is -A automatically unless -I. */
	if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
		f_listdot = 1;

	/* Enabling of colours is conditional on the environment. */
	if (getenv("CLICOLOR") &&
	    (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
#ifdef COLORLS
		if (tgetent(termcapbuf, getenv("TERM")) == 1) {
			ansi_fgcol = tgetstr("AF", &bp);
			ansi_bgcol = tgetstr("AB", &bp);
			attrs_off = tgetstr("me", &bp);
			enter_bold = tgetstr("md", &bp);

			/* To switch colours off use 'op' if
			 * available, otherwise use 'oc', or
			 * don't do colours at all. */
			ansi_coloff = tgetstr("op", &bp);
			if (!ansi_coloff)
				ansi_coloff = tgetstr("oc", &bp);
			if (ansi_fgcol && ansi_bgcol && ansi_coloff)
				f_color = 1;
		}
#else
		xo_warnx("color support not compiled in");
#endif /*COLORLS*/

#ifdef COLORLS
	if (f_color) {
		/*
		 * We can't put tabs and color sequences together:
		 * column number will be incremented incorrectly
		 * for "stty oxtabs" mode.
		 */
		f_notabs = 1;
		(void)signal(SIGINT, colorquit);
		(void)signal(SIGQUIT, colorquit);
		parsecolors(getenv("LSCOLORS"));
	}
#endif

	/*
	 * If not -F, -i, -l, -s, -S or -t options, don't require stat
	 * information, unless in color mode in which case we do
	 * need this to determine which colors to display.
	 */
	if (!f_inode && !f_longform && !f_size && !f_timesort &&
	    !f_sizesort && !f_type
#ifdef COLORLS
	    && !f_color
#endif
	    )
		fts_options |= FTS_NOSTAT;

	/*
	 * If not -F, -P, -d or -l options, follow any symbolic links listed on
	 * the command line, unless in color mode in which case we need to
	 * distinguish file type for a symbolic link itself and its target.
	 */
	if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash)
#ifdef COLORLS
	    && !f_color
#endif
	    )
		fts_options |= FTS_COMFOLLOW;

	/*
	 * If -W, show whiteout entries
	 */
#ifdef FTS_WHITEOUT
	if (f_whiteout)
		fts_options |= FTS_WHITEOUT;
#endif

	/* If -i, -l or -s, figure out block size. */
	if (f_inode || f_longform || f_size) {
		if (f_kblocks)
			blocksize = 2;
		else {
			(void)getbsize(&notused, &blocksize);
			blocksize /= 512;
		}
	}
	/* Select a sort function. */
	if (f_reversesort) {
		if (!f_timesort && !f_sizesort)
			sortfcn = revnamecmp;
		else if (f_sizesort)
			sortfcn = revsizecmp;
		else if (f_accesstime)
			sortfcn = revacccmp;
		else if (f_birthtime)
			sortfcn = revbirthcmp;
		else if (f_statustime)
			sortfcn = revstatcmp;
		else		/* Use modification time. */
			sortfcn = revmodcmp;
	} else {
		if (!f_timesort && !f_sizesort)
			sortfcn = namecmp;
		else if (f_sizesort)
			sortfcn = sizecmp;
		else if (f_accesstime)
			sortfcn = acccmp;
		else if (f_birthtime)
			sortfcn = birthcmp;
		else if (f_statustime)
			sortfcn = statcmp;
		else		/* Use modification time. */
			sortfcn = modcmp;
	}

	/* Select a print function. */
	if (f_singlecol)
		printfcn = printscol;
	else if (f_longform)
		printfcn = printlong;
	else if (f_stream)
		printfcn = printstream;
	else
		printfcn = printcol;

	xo_open_container("file-information");
	if (argc)
		traverse(argc, argv, fts_options);
	else
		traverse(1, dotav, fts_options);
	xo_close_container("file-information");
	xo_finish();
	exit(rval);
}
Example #30
0
int
main(int argc, char *argv[])
{
	double		x;
	double		y;
	long		i;
	unsigned int	mask = 0;
	int		n = 0;
	int		ch;
	const	char	*errstr;

	while ((ch = getopt(argc, argv, "rb:w:cs:np:")) != -1)
		switch (ch) {
		case 'r':
			randomize = true;
			break;
		case 'c':
			chardata = true;
			break;
		case 'n':
			finalnl = false;
			break;
		case 'b':
			boring = true;
			if (strlcpy(format, optarg, sizeof(format)) >=
			    sizeof(format))
				errx(1, "-b word too long");
			break;
		case 'w':
			if (strlcpy(format, optarg, sizeof(format)) >=
			    sizeof(format))
				errx(1, "-w word too long");
			break;
		case 's':
			if (strlcpy(sepstring, optarg, sizeof(sepstring)) >=
			    sizeof(sepstring))
				errx(1, "-s word too long");
			break;
		case 'p':
			prec = strtonum(optarg, 0, INT_MAX, &errstr);
			if (errstr != NULL)
				errx(1, "bad precision value, %s: %s", errstr, 
					optarg);
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	switch (argc) {	/* examine args right to left, falling thru cases */
	case 4:
		if (!is_default(argv[3])) {
			if (!sscanf(argv[3], "%lf", &s))
				errx(1, "Bad s value:  %s", argv[3]);
			mask |= 01;
			if (randomize)
				warnx("random seeding not supported");
		}
	case 3:
		if (!is_default(argv[2])) {
			if (!sscanf(argv[2], "%lf", &ender))
				ender = argv[2][strlen(argv[2])-1];
			mask |= 02;
			if (prec == -1)
				n = getprec(argv[2]);
		}
	case 2:
		if (!is_default(argv[1])) {
			if (!sscanf(argv[1], "%lf", &begin))
				begin = argv[1][strlen(argv[1])-1];
			mask |= 04;
			if (prec == -1)
				prec = getprec(argv[1]);
			if (n > prec)		/* maximum precision */
				prec = n;
		}
	case 1:
		if (!is_default(argv[0])) {
			if (!sscanf(argv[0], "%ld", &reps))
				errx(1, "Bad reps value:  %s", argv[0]);
			mask |= 010;
			if (prec == -1)
				prec = 0;
		}
		break;
	case 0:
		usage();
		break;
	default:
		errx(1, "Too many arguments.  What do you mean by %s?",
		    argv[4]);
	}
	getformat();
	while (mask)	/* 4 bit mask has 1's where last 4 args were given */
		switch (mask) {	/* fill in the 0's by default or computation */
		case 001:
			reps = REPS_DEF;
			mask = 011;
			break;
		case 002:
			reps = REPS_DEF;
			mask = 012;
			break;
		case 003:
			reps = REPS_DEF;
			mask = 013;
			break;
		case 004:
			reps = REPS_DEF;
			mask = 014;
			break;
		case 005:
			reps = REPS_DEF;
			mask = 015;
			break;
		case 006:
			reps = REPS_DEF;
			mask = 016;
			break;
		case 007:
			if (randomize) {
				reps = REPS_DEF;
				mask = 0;
				break;
			}
			if (s == 0.0) {
				reps = 0;
				mask = 0;
				break;
			}
			reps = (ender - begin + s) / s;
			if (reps <= 0)
				errx(1, "Impossible stepsize");
			mask = 0;
			break;
		case 010:
			begin = BEGIN_DEF;
			mask = 014;
			break;
		case 011:
			begin = BEGIN_DEF;
			mask = 015;
			break;
		case 012:
			s = STEP_DEF;
			mask = 013;
			break;
		case 013:
			if (randomize)
				begin = BEGIN_DEF;
			else if (reps == 0)
				errx(1, "Must specify begin if reps == 0");
			begin = ender - reps * s + s;
			mask = 0;
			break;
		case 014:
			s = STEP_DEF;
			mask = 015;
			break;
		case 015:
			if (randomize)
				ender = ENDER_DEF;
			else
				ender = begin + reps * s - s;
			mask = 0;
			break;
		case 016:
			if (reps == 0)
				errx(1, "Infinite sequences cannot be bounded");
			else if (reps == 1)
				s = 0.0;
			else
				s = (ender - begin) / (reps - 1);
			mask = 0;
			break;
		case 017:		/* if reps given and implied, */
			if (!randomize && s != 0.0) {
				long t = (ender - begin + s) / s;
				if (t <= 0)
					errx(1, "Impossible stepsize");
				if (t < reps)		/* take lesser */
					reps = t;
			}
			mask = 0;
			break;
		default:
			errx(1, "bad mask");
		}
	if (reps == 0)
		infinity = true;
	if (randomize) {
		x = (ender - begin) * (ender > begin ? 1 : -1);
		for (i = 1; i <= reps || infinity; i++) {
			double v;
			y = arc4random() / ((double)0xffffffff + 1);
			v = y * x + begin;
			if (putdata(v, reps == i && !infinity))
				errx(1, "range error in conversion: %f", v);
		}
	}
	else
		for (i = 1, x = begin; i <= reps || infinity; i++, x += s)
			if (putdata(x, reps == i && !infinity))
				errx(1, "range error in conversion: %f", x);
	if (finalnl)
		putchar('\n');
	exit(0);
}