Example #1
0
int main(int argc, char *argv[])
{
  init_ctx(&ctx_ping, 16384, f_ping, NULL);
  init_ctx(&ctx_pong, 16384, f_pong, NULL);
  switch_to_ctx(&ctx_ping);

  exit(EXIT_SUCCESS);
}
Example #2
0
//------------------------------------------------------------------------
int
notmain ( void )
{
  init_ctx(&ctx_A, ping, STACK_SIZE);
  init_ctx(&ctx_B, pong, STACK_SIZE);

  current_ctx = &ctx_init;

  switch_to(&ctx_A);
}
Example #3
0
int main(int argc, char *argv[])
{
  init_ctx(&ctx1, 16384, f1, NULL);
  printf("initialisation ctx1\n");
  init_ctx(&ctx2, 16384, f2, NULL);
  printf("initialisation ctx2\n");
  init_ctx(&ctx3, 16384, f3, NULL);
  printf("initialisation ctx3\n");
  
  printf("switch to ctx1\n");
  switch_to_ctx(&ctx1);
  printf("retour au main\n");
  exit(EXIT_SUCCESS);
}
Example #4
0
    static void get(backend::source_generator &src,
            const tagged_terminal<Tag, Term> &term,
            const backend::command_queue &queue,
            const std::string&/*prm_name*/,
            detail::kernel_generator_state_ptr state)
    {
        auto s = state->find("tag_locinit");

        if (s == state->end()) {
            s = state->insert(std::make_pair(
                        std::string("tag_locinit"),
                        boost::any(std::set<size_t>())
                        )).first;
        }

        auto &pos = boost::any_cast< std::set<size_t>& >(s->second);
        auto p = pos.find(Tag);

        if (p == pos.end()) {
            pos.insert(Tag);

            std::ostringstream prm_name;
            prm_name << "prm_tag_" << Tag;

            detail::output_local_preamble init_ctx(src, queue, prm_name.str(), state);
            boost::proto::eval(boost::proto::as_child(term.term), init_ctx);
        }
    }
int create_ctx(int stack_size, func_t f, void* args) {

	irq_disable();

	//Allocation de mémoire pour stocker un nouveau contexte -> MALLOC RÉSERVERA UN ESPACE MÉMOIRE DE TAILLE sizeof(struct ctx_s)
	struct ctx_s* ctx_new = malloc(sizeof(struct ctx_s));

	assert(ctx_new);

	//Initialisation du nouveau contexte
	init_ctx(ctx_new, stack_size, f, args);

	//Ajout dans la liste de contextes

	//Si la liste de contextes existe, on ajoute alors ce nouveau contexte (ctx_new) dans le contexte suivant la liste de contextes
	if (ctxs) {
		ctx_new -> ctx_next = ctxs -> ctx_next;
		ctxs -> ctx_next = ctx_new;
	}
	//Si la liste de contextes n'existe pas, ce contexte est alors le premier dans la liste de contexte -> on pointe sur lui!!
	else {
		ctxs = ctx_new;
		ctxs -> ctx_next = ctx_new;
	}

	irq_enable();

	return 0;

}
Example #6
0
/* ***************************************************
 * Function: transport_init
 * ***************************************************
 * initialise the transport layer, and start the main loop, handling
 * any data from the peer or the application.  this function should not
 * return until the connection is closed.
 */
void transport_init(mysocket_t sd, bool_t is_active)
{
    context_t *ctx = init_ctx(is_active);
	bool success = false;
    if (is_active) {
		success = active_init(sd, ctx);		
    }
    else {
    	success = passive_init(sd, ctx);    	
    }
	if (success){  	
  	    ctx->connection_state = CSTATE_ESTABLISHED;
	    stcp_unblock_application(sd);
	    control_loop(sd, ctx);
	}
	else {
		errno = ETIMEDOUT;
		stcp_unblock_application(sd);
	}
	teardown_resources(ctx);
	/* Wait for potential pending processes in 
	 * other side (this is to fix a bug in the starter code) */
	sleep(1);		
	our_dprintf("Exiting Loop!\n");
}
Example #7
0
    static void get(backend::source_generator &src,
            const temporary<T, Tag, Expr> &term,
            const backend::command_queue &queue, const std::string &prm_name,
            detail::kernel_generator_state_ptr state)
    {
        auto s = state->find("tmp_locinit");

        if (s == state->end()) {
            s = state->insert(std::make_pair(
                        std::string("tmp_locinit"),
                        boost::any(std::set<size_t>())
                        )).first;
        }

        auto &pos = boost::any_cast< std::set<size_t>& >(s->second);
        auto p = pos.find(Tag);

        if (p == pos.end()) {
            pos.insert(Tag);

            detail::output_local_preamble init_ctx(src, queue, prm_name, state);
            boost::proto::eval(boost::proto::as_child(term.expr), init_ctx);

            src.new_line() << type_name<T>() << " temp_" << Tag << " = ";

            detail::vector_expr_context expr_ctx(src, queue, prm_name, state);
            boost::proto::eval(boost::proto::as_child(term.expr), expr_ctx);

            src << ";";
        }
    }
Example #8
0
int main(int argc, char **argv)
{
	struct ctx ctx = { };
	int key;
	char *imageFile = argv[1];
	ctx.image = cvLoadImage(imageFile, 1);
	//init_capture(&ctx);
	//init_recording(&ctx);
	init_windows();
	init_ctx(&ctx);

	//do {
		// ctx.image = cvQueryFrame(ctx.capture); 
		//ctx.image = cvLoadImage("/home/csrobot/Downloads/grab_box/images/OtivvoH.jpg", 1);
		//fprintf(stdout, "image loaded\n");
		filter_and_threshold(&ctx);
		find_contour(&ctx);
		find_convex_hull(&ctx);
		find_fingers(&ctx);

		display(&ctx);
		cvWriteFrame(ctx.writer, ctx.image);

		key = cvWaitKey(0);
	//} while (key != 'q');

	return 0;
}
Example #9
0
void init_pcb( struct pcb_s* pcb, ctx_s* ctx, func_t fct, void* args)
{
	init_ctx(ctx, fct, STACK_SIZE);
	pcb->ctx  = ctx;
	pcb->entry_point  = fct;
	pcb->args = args;
	pcb->state = NEW;
}
Example #10
0
SSL_CTX * KSSLSocket::init_server(const char *cert_file, const char *key_file,
		const char *verified_file) {
	SSL_CTX * ctx = init_ctx(true);
	if (ctx == NULL) {
		fprintf(stderr, "cann't init_ctx\n");
		return NULL;
	}
	if (cert_file == NULL) {
		cert_file = key_file;
	}
	if (SSL_CTX_use_certificate_chain_file(ctx, cert_file) <= 0) {
		fprintf(stderr,
				"SSL use certificate file : Error allocating handle: %s\n",
				ERR_error_string(ERR_get_error(), NULL));
		clean_ctx(ctx);
		return NULL;
	}
	if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
		fprintf(stderr,
				"SSL use privatekey file: Error allocating handle: %s\n",
				ERR_error_string(ERR_get_error(), NULL));
		clean_ctx(ctx);
		return NULL;
	}

	if (!SSL_CTX_check_private_key(ctx)) {
		fprintf(stderr, "SSL: Error allocating handle: %s\n", ERR_error_string(
				ERR_get_error(), NULL));
		clean_ctx(ctx);
		return NULL;
	}
	if (verified_file) {
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER
				| SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
		SSL_CTX_set_verify_depth(ctx, 1);
		if (SSL_CTX_load_verify_locations(ctx, verified_file, NULL) <= 0) {
			fprintf(stderr, "SSL error %s:%d: Error allocating handle: %s\n",
					__FILE__, __LINE__, ERR_error_string(ERR_get_error(), NULL));
			clean_ctx(ctx);
			return NULL;
		}
	}
	int session_context_len = strlen(cert_file);
	const char *session_context = cert_file;
	int pos = session_context_len - SSL_MAX_SSL_SESSION_ID_LENGTH;
	if (pos>0) {
		session_context_len -= pos;
		session_context += pos;
	}
	SSL_CTX_set_session_id_context(ctx,(const unsigned char *)session_context,session_context_len);
	SSL_CTX_set_session_cache_mode(ctx,SSL_SESS_CACHE_SERVER);
	//SSL_CTX_sess_set_cache_size(ctx,1000);
	return ctx;
}
Example #11
0
int main(int argc, char **argv) {
    char *input, *output;
    unsigned char *input_data;
    struct stat in_st;
    int input_fd, output_fd;
    int i;
    unsigned char tmp[64];
    ECRYPT_ctx ctx;

    if (argc != 3) {
    	fprintf(stderr, "usage: %s input output\n", argv[0]);
    	exit(EXIT_FAILURE);
    }

    input = argv[1]; output = argv[2];

    init_ctx(&ctx);

    if (stat(input, &in_st) == -1) {
    	perror("stat");
    	exit(EXIT_FAILURE);
    }

    input_fd = open(input, O_RDONLY);
    if (input_fd == -1) {
    	perror("open");
    	exit(EXIT_FAILURE);
    }

    output_fd = creat(output, S_IRWXU);
    if (output_fd == -1) {
    	perror("open");
    	exit(EXIT_FAILURE);
    }

    input_data = mmap(NULL, in_st.st_size, PROT_READ, MAP_SHARED, input_fd, 0);
    if (input_data == (void *) -1) {
    	perror("mmap");
    	exit(EXIT_FAILURE);
    }

    ECRYPT_init();
    for (i = 0; i < (in_st.st_size / 64); i++) {
    	ECRYPT_decrypt_bytes(&ctx, input_data + 64 * i, tmp, 64);
    	write(output_fd, tmp, 64); 
    }

    close(output_fd);
    munmap(input_data, in_st.st_size);
    close(input_fd);

    exit(EXIT_SUCCESS);
}
Example #12
0
int create_ctx(int stack_size, func_t f, void* args){
	struct ctx_s *ctx ;
	ctx = malloc(sizeof(struct ctx_s));
	init_ctx(ctx,stack_size,f,args);
	if(anneau==NULL){
		ctx->suivant = ctx;
		anneau = ctx ;
	} else {
		ctx->suivant = anneau -> suivant ;
		anneau->suivant = ctx;
	}
	return 0;
}
Example #13
0
bool tls_socket::set_hostname(const char* sAddr)
{
	sock_closed = false;
	if(ctx == nullptr)
	{
		init_ctx();
		if(ctx == nullptr)
		{
			print_error();
			return false;
		}
	}

	if((bio = BIO_new_ssl_connect(ctx)) == nullptr)
	{
		print_error();
		return false;
	}

	int flag = 1;
	/* If it fails, it fails, we won't loose too much sleep over it */
	setsockopt(BIO_get_fd(bio, nullptr), IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));

	if(BIO_set_conn_hostname(bio, sAddr) != 1)
	{
		print_error();
		return false;
	}

	BIO_get_ssl(bio, &ssl);
	if(ssl == nullptr)
	{
		print_error();
		return false;
	}

	if(jconf::inst()->TlsSecureAlgos())
	{
		if(SSL_set_cipher_list(ssl, "HIGH:!aNULL:!PSK:!SRP:!MD5:!RC4:!SHA1") != 1)
		{
			print_error();
			return false;
		}
	}

	return true;
}
Example #14
0
SSL_CTX * KSSLSocket::init_client(const char *path, const char *file) {
	SSL_CTX *ctx = init_ctx(false);
	if (ctx) {
		if (file != NULL) {
			SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
			SSL_CTX_set_verify_depth(ctx, 1);

			if (SSL_CTX_load_verify_locations(ctx, file, path) <= 0) {
				fprintf(stderr, "SSL error %s:%d: Error allocating handle: %s\n",
						__FILE__, __LINE__, ERR_error_string(ERR_get_error(), NULL));
				clean_ctx(ctx);
				return NULL;
			}
		}
		SSL_CTX_set_session_id_context(ctx,(const unsigned char *)PROGRAM_NAME,sizeof(PROGRAM_NAME)-1);
		SSL_CTX_set_session_cache_mode(ctx,SSL_SESS_CACHE_BOTH);
	}
	return ctx;
}
Example #15
0
ERL_NIF_TERM
snappy_create_ctx(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
    ERL_NIF_TERM  rv;
    ctx_t        *ctx;

    ctx = init_ctx();

    if (ctx == NULL) {
        return enif_make_tuple2(env, atom_error,
            enif_make_string(env, "Failed to create context",
                ERL_NIF_LATIN1));
    }

    rv = enif_make_resource(env, ctx);
    enif_release_resource(ctx);

    return enif_make_tuple2(env, atom_ok, rv);
}
Example #16
0
bool tls_socket::set_hostname(const char* sAddr)
{
	if(ctx == nullptr)
	{
		init_ctx();
		if(ctx == nullptr)
		{
			print_error();
			return false;
		}
	}

	if((bio = BIO_new_ssl_connect(ctx)) == nullptr)
	{
		print_error();
		return false;
	}

	if(BIO_set_conn_hostname(bio, sAddr) != 1)
	{
		print_error();
		return false;
	}

	BIO_get_ssl(bio, &ssl);
	if(ssl == nullptr)
	{
		print_error();
		return false;
	}

	if(jconf::inst()->TlsSecureAlgos())
	{
		if(SSL_set_cipher_list(ssl, "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4:!SHA1") != 1)
		{
			print_error();
			return false;
		}
	}

	return true;
}
Example #17
0
int create_ctx(int stack_size, char *name, func_t *f, void *args)
{
  ctx_t	*ptr;

  irq_disable();
  if ((ptr = malloc(sizeof(ctx_t))) == NULL)
    {
      fprintf(stderr, "Unable to create a new context\n");
      return (-1);
    }
  if (ctx == NULL)
    ctx = ptr;
  else
    {
      ptr->next = ctx->next;
      ctx->next = ptr;
    }
  ctx->next = ptr;
  ptr->next->prev = ptr;
  ptr->prev = ctx;
  strcpy(ptr->name, name);
  return (init_ctx(ptr, stack_size, f, args));
}
Example #18
0
int
pkeyutl_main(int argc, char **argv)
{
	BIO *in = NULL, *out = NULL;
	char *infile = NULL, *outfile = NULL, *sigfile = NULL;
	int pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
	int keyform = FORMAT_PEM, peerform = FORMAT_PEM;
	char badarg = 0, rev = 0;
	char hexdump = 0, asn1parse = 0;
	EVP_PKEY_CTX *ctx = NULL;
	char *passargin = NULL;
	int keysize = -1;

	unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
	size_t buf_outlen = 0;
	int buf_inlen = 0, siglen = -1;

	int ret = 1, rv = -1;

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

	argc--;
	argv++;

	while (argc >= 1) {
		if (!strcmp(*argv, "-in")) {
			if (--argc < 1)
				badarg = 1;
			else
				infile = *(++argv);
		} else if (!strcmp(*argv, "-out")) {
			if (--argc < 1)
				badarg = 1;
			else
				outfile = *(++argv);
		} else if (!strcmp(*argv, "-sigfile")) {
			if (--argc < 1)
				badarg = 1;
			else
				sigfile = *(++argv);
		} else if (!strcmp(*argv, "-inkey")) {
			if (--argc < 1)
				badarg = 1;
			else {
				ctx = init_ctx(&keysize,
				    *(++argv), keyform, key_type,
				    passargin, pkey_op);
				if (!ctx) {
					BIO_puts(bio_err,
					    "Error initializing context\n");
					ERR_print_errors(bio_err);
					badarg = 1;
				}
			}
		} else if (!strcmp(*argv, "-peerkey")) {
			if (--argc < 1)
				badarg = 1;
			else if (!setup_peer(bio_err, ctx, peerform, *(++argv)))
				badarg = 1;
		} else if (!strcmp(*argv, "-passin")) {
			if (--argc < 1)
				badarg = 1;
			else
				passargin = *(++argv);
		} else if (strcmp(*argv, "-peerform") == 0) {
			if (--argc < 1)
				badarg = 1;
			else
				peerform = str2fmt(*(++argv));
		} else if (strcmp(*argv, "-keyform") == 0) {
			if (--argc < 1)
				badarg = 1;
			else
				keyform = str2fmt(*(++argv));
		}
		else if (!strcmp(*argv, "-pubin"))
			key_type = KEY_PUBKEY;
		else if (!strcmp(*argv, "-certin"))
			key_type = KEY_CERT;
		else if (!strcmp(*argv, "-asn1parse"))
			asn1parse = 1;
		else if (!strcmp(*argv, "-hexdump"))
			hexdump = 1;
		else if (!strcmp(*argv, "-sign"))
			pkey_op = EVP_PKEY_OP_SIGN;
		else if (!strcmp(*argv, "-verify"))
			pkey_op = EVP_PKEY_OP_VERIFY;
		else if (!strcmp(*argv, "-verifyrecover"))
			pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
		else if (!strcmp(*argv, "-rev"))
			rev = 1;
		else if (!strcmp(*argv, "-encrypt"))
			pkey_op = EVP_PKEY_OP_ENCRYPT;
		else if (!strcmp(*argv, "-decrypt"))
			pkey_op = EVP_PKEY_OP_DECRYPT;
		else if (!strcmp(*argv, "-derive"))
			pkey_op = EVP_PKEY_OP_DERIVE;
		else if (strcmp(*argv, "-pkeyopt") == 0) {
			if (--argc < 1)
				badarg = 1;
			else if (!ctx) {
				BIO_puts(bio_err,
				    "-pkeyopt command before -inkey\n");
				badarg = 1;
			} else if (pkey_ctrl_string(ctx, *(++argv)) <= 0) {
				BIO_puts(bio_err, "parameter setting error\n");
				ERR_print_errors(bio_err);
				goto end;
			}
		} else
			badarg = 1;
		if (badarg) {
			usage();
			goto end;
		}
		argc--;
		argv++;
	}

	if (!ctx) {
		usage();
		goto end;
	}
	if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) {
		BIO_puts(bio_err, "Signature file specified for non verify\n");
		goto end;
	}
	if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) {
		BIO_puts(bio_err, "No signature file specified for verify\n");
		goto end;
	}

	if (pkey_op != EVP_PKEY_OP_DERIVE) {
		if (infile) {
			if (!(in = BIO_new_file(infile, "rb"))) {
				BIO_puts(bio_err,
				    "Error Opening Input File\n");
				ERR_print_errors(bio_err);
				goto end;
			}
		} else
			in = BIO_new_fp(stdin, BIO_NOCLOSE);
	}
	if (outfile) {
		if (!(out = BIO_new_file(outfile, "wb"))) {
			BIO_printf(bio_err, "Error Creating Output File\n");
			ERR_print_errors(bio_err);
			goto end;
		}
	} else {
		out = BIO_new_fp(stdout, BIO_NOCLOSE);
	}

	if (sigfile) {
		BIO *sigbio = BIO_new_file(sigfile, "rb");
		if (!sigbio) {
			BIO_printf(bio_err, "Can't open signature file %s\n",
			    sigfile);
			goto end;
		}
		siglen = bio_to_mem(&sig, keysize * 10, sigbio);
		BIO_free(sigbio);
		if (siglen <= 0) {
			BIO_printf(bio_err, "Error reading signature data\n");
			goto end;
		}
	}
	if (in) {
		/* Read the input data */
		buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
		if (buf_inlen <= 0) {
			BIO_printf(bio_err, "Error reading input Data\n");
			exit(1);
		}
		if (rev) {
			size_t i;
			unsigned char ctmp;
			size_t l = (size_t) buf_inlen;
			for (i = 0; i < l / 2; i++) {
				ctmp = buf_in[i];
				buf_in[i] = buf_in[l - 1 - i];
				buf_in[l - 1 - i] = ctmp;
			}
		}
	}
	if (pkey_op == EVP_PKEY_OP_VERIFY) {
		rv = EVP_PKEY_verify(ctx, sig, (size_t) siglen,
		    buf_in, (size_t) buf_inlen);
		if (rv == 1) {
			BIO_puts(out, "Signature Verified Successfully\n");
			ret = 0;
		} else
			BIO_puts(out, "Signature Verification Failure\n");
		if (rv >= 0)
			goto end;
	} else {
		rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
		    buf_in, (size_t) buf_inlen);
		if (rv > 0) {
			buf_out = malloc(buf_outlen);
			if (!buf_out)
				rv = -1;
			else
				rv = do_keyop(ctx, pkey_op,
				    buf_out, (size_t *) & buf_outlen,
				    buf_in, (size_t) buf_inlen);
		}
	}

	if (rv <= 0) {
		BIO_printf(bio_err, "Public Key operation error\n");
		ERR_print_errors(bio_err);
		goto end;
	}
	ret = 0;
	if (asn1parse) {
		if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
			ERR_print_errors(bio_err);
	} else if (hexdump)
		BIO_dump(out, (char *) buf_out, buf_outlen);
	else
		BIO_write(out, buf_out, buf_outlen);

 end:
	EVP_PKEY_CTX_free(ctx);
	BIO_free(in);
	BIO_free_all(out);
	free(buf_in);
	free(buf_out);
	free(sig);

	return ret;
}
Example #19
0
int pkeyutl_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    ENGINE *e = NULL;
    EVP_PKEY_CTX *ctx = NULL;
    char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
    char hexdump = 0, asn1parse = 0, rev = 0, *prog;
    unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
    OPTION_CHOICE o;
    int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform =
        FORMAT_PEM;
    int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
    int engine_impl = 0;
    int ret = 1, rv = -1;
    size_t buf_outlen;
    const char *inkey = NULL;
    const char *peerkey = NULL;
    STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;

    prog = opt_init(argc, argv, pkeyutl_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(pkeyutl_options);
            ret = 0;
            goto end;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_SIGFILE:
            sigfile = opt_arg();
            break;
        case OPT_ENGINE_IMPL:
            engine_impl = 1;
            break;
        case OPT_INKEY:
            inkey = opt_arg();
            break;
        case OPT_PEERKEY:
            peerkey = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PEERFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDE, &peerform))
                goto opthelp;
            break;
        case OPT_KEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform))
                goto opthelp;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_PUBIN:
            key_type = KEY_PUBKEY;
            break;
        case OPT_CERTIN:
            key_type = KEY_CERT;
            break;
        case OPT_ASN1PARSE:
            asn1parse = 1;
            break;
        case OPT_HEXDUMP:
            hexdump = 1;
            break;
        case OPT_SIGN:
            pkey_op = EVP_PKEY_OP_SIGN;
            break;
        case OPT_VERIFY:
            pkey_op = EVP_PKEY_OP_VERIFY;
            break;
        case OPT_VERIFYRECOVER:
            pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
            break;
        case OPT_ENCRYPT:
            pkey_op = EVP_PKEY_OP_ENCRYPT;
            break;
        case OPT_DECRYPT:
            pkey_op = EVP_PKEY_OP_DECRYPT;
            break;
        case OPT_DERIVE:
            pkey_op = EVP_PKEY_OP_DERIVE;
            break;
        case OPT_REV:
            rev = 1;
            break;
        case OPT_PKEYOPT:
            if ((pkeyopts == NULL &&
                 (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
                sk_OPENSSL_STRING_push(pkeyopts, *++argv) == 0) {
                BIO_puts(bio_err, "out of memory\n");
                goto end;
            }
            break;
        }
    }
    argc = opt_num_rest();
    if (argc != 0)
        goto opthelp;

    if (inkey == NULL ||
        (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE))
        goto opthelp;

    ctx = init_ctx(&keysize, inkey, keyform, key_type,
                   passinarg, pkey_op, e, engine_impl);
    if (ctx == NULL) {
        BIO_printf(bio_err, "%s: Error initializing context\n", prog);
        ERR_print_errors(bio_err);
        goto end;
    }
    if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
        BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
        ERR_print_errors(bio_err);
        goto end;
    }
    if (pkeyopts != NULL) {
        int num = sk_OPENSSL_STRING_num(pkeyopts);
        int i;

        for (i = 0; i < num; ++i) {
            const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);

            if (pkey_ctrl_string(ctx, opt) <= 0) {
                BIO_printf(bio_err, "%s: Can't set parameter:\n", prog);
                ERR_print_errors(bio_err);
                goto end;
            }
        }
    }

    if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) {
        BIO_printf(bio_err,
                   "%s: Signature file specified for non verify\n", prog);
        goto end;
    }

    if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) {
        BIO_printf(bio_err,
                   "%s: No signature file specified for verify\n", prog);
        goto end;
    }

/* FIXME: seed PRNG only if needed */
    app_RAND_load_file(NULL, 0);

    if (pkey_op != EVP_PKEY_OP_DERIVE) {
        in = bio_open_default(infile, 'r', FORMAT_BINARY);
        if (in == NULL)
            goto end;
    }
    out = bio_open_default(outfile, 'w', FORMAT_BINARY);
    if (out == NULL)
        goto end;

    if (sigfile) {
        BIO *sigbio = BIO_new_file(sigfile, "rb");
        if (!sigbio) {
            BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
            goto end;
        }
        siglen = bio_to_mem(&sig, keysize * 10, sigbio);
        BIO_free(sigbio);
        if (siglen < 0) {
            BIO_printf(bio_err, "Error reading signature data\n");
            goto end;
        }
    }

    if (in) {
        /* Read the input data */
        buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
        if (buf_inlen < 0) {
            BIO_printf(bio_err, "Error reading input Data\n");
            exit(1);
        }
        if (rev) {
            size_t i;
            unsigned char ctmp;
            size_t l = (size_t)buf_inlen;
            for (i = 0; i < l / 2; i++) {
                ctmp = buf_in[i];
                buf_in[i] = buf_in[l - 1 - i];
                buf_in[l - 1 - i] = ctmp;
            }
        }
    }

    if (pkey_op == EVP_PKEY_OP_VERIFY) {
        rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
                             buf_in, (size_t)buf_inlen);
        if (rv == 1) {
            BIO_puts(out, "Signature Verified Successfully\n");
            ret = 0;
        } else
            BIO_puts(out, "Signature Verification Failure\n");
        goto end;
    }
    rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
                  buf_in, (size_t)buf_inlen);
    if (rv > 0 && buf_outlen != 0) {
        buf_out = app_malloc(buf_outlen, "buffer output");
        rv = do_keyop(ctx, pkey_op,
                      buf_out, (size_t *)&buf_outlen,
                      buf_in, (size_t)buf_inlen);
    }
    if (rv < 0) {
        ERR_print_errors(bio_err);
        goto end;
    }
    ret = 0;

    if (asn1parse) {
        if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
            ERR_print_errors(bio_err);
    } else if (hexdump)
        BIO_dump(out, (char *)buf_out, buf_outlen);
    else
        BIO_write(out, buf_out, buf_outlen);

 end:
    EVP_PKEY_CTX_free(ctx);
    BIO_free(in);
    BIO_free_all(out);
    OPENSSL_free(buf_in);
    OPENSSL_free(buf_out);
    OPENSSL_free(sig);
    sk_OPENSSL_STRING_free(pkeyopts);
    return ret;
}
Example #20
0
int main(int argc, char** argv)
{
	openni::Status rc = openni::STATUS_OK;

	openni::Device device;
	openni::VideoStream depth, color;
	const char* deviceURI = openni::ANY_DEVICE;
	if (argc > 1)
	{
		deviceURI = argv[1];
	}

	rc = openni::OpenNI::initialize();

	printf("After initialization:\n%s\n", openni::OpenNI::getExtendedError());

	rc = device.open(deviceURI);
	if (rc != openni::STATUS_OK)
	{
		printf("SimpleViewer: Device open failed:\n%s\n", openni::OpenNI::getExtendedError());
		openni::OpenNI::shutdown();
		return 1;
	}

	rc = depth.create(device, openni::SENSOR_DEPTH);
	if (rc == openni::STATUS_OK)
	{
		rc = depth.start();
		if (rc != openni::STATUS_OK)
		{
			printf("SimpleViewer: Couldn't start depth stream:\n%s\n", openni::OpenNI::getExtendedError());
			depth.destroy();
		}
	}
	else
	{
		printf("SimpleViewer: Couldn't find depth stream:\n%s\n", openni::OpenNI::getExtendedError());
	}

	rc = color.create(device, openni::SENSOR_COLOR);
	if (rc == openni::STATUS_OK)
	{
		rc = color.start();
		if (rc != openni::STATUS_OK)
		{
			printf("SimpleViewer: Couldn't start color stream:\n%s\n", openni::OpenNI::getExtendedError());
			color.destroy();
		}
	}
	else
	{
		printf("SimpleViewer: Couldn't find color stream:\n%s\n", openni::OpenNI::getExtendedError());
	}

	if (!depth.isValid() || !color.isValid())
	{
		printf("SimpleViewer: No valid streams. Exiting\n");
		openni::OpenNI::shutdown();
		return 2;
	}

	/*Viewer class initialization. */
	Viewer Viewer("Simple Viewer", device, depth, color);

	rc = Viewer.init();
	if (rc != openni::STATUS_OK)
	{
		openni::OpenNI::shutdown();
		return 3;
	}

	rc = Viewer.initOpenCv();
	if (rc != openni::STATUS_OK)
	{
		openni::OpenNI::shutdown();
		return 4;
	}

	/*Hand processing initialization. */
	init_recording(&cvctx);
	//init_windows();
	init_ctx(&cvctx);

	/*loop program */
	while(1)
	{
		Viewer.run();
	}
}
Example #21
0
void initCtx(void) {
  cntx = init_ctx();
}
Example #22
0
int main(int argc, char **argv)
{
	char *ptr;
	int c, i, j, cpu_tmp, opt_index, ops_touched = 0, vals[4] = {0};
	bool prio_high = false, setsockmem = true;
	void (*main_loop)(struct ctx *ctx) = NULL;
	struct ctx ctx;

	init_ctx(&ctx);
	srand(time(NULL));

	while ((c = getopt_long(argc, argv, short_options, long_options,
				&opt_index)) != EOF) {
		switch (c) {
		case 'd':
		case 'i':
			ctx.device_in = xstrdup(optarg);
			break;
		case 'o':
			ctx.device_out = xstrdup(optarg);
			break;
		case 'P':
			ctx.prefix = xstrdup(optarg);
			break;
		case 'R':
			ctx.link_type = LINKTYPE_IEEE802_11;
			ctx.rfraw = 1;
			break;
		case 'r':
			ctx.randomize = true;
			break;
		case 'J':
			ctx.jumbo = true;
			break;
		case 'T':
			ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
			pcap_check_magic(ctx.magic);
			break;
		case 'f':
			ctx.filter = xstrdup(optarg);
			break;
		case 'M':
			ctx.promiscuous = false;
			break;
		case 'A':
			setsockmem = false;
			break;
		case 'u':
			ctx.uid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'g':
			ctx.gid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 't':
			if (!strncmp(optarg, "host", strlen("host")))
				ctx.packet_type = PACKET_HOST;
			else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
				ctx.packet_type = PACKET_BROADCAST;
			else if (!strncmp(optarg, "multicast", strlen("multicast")))
				ctx.packet_type = PACKET_MULTICAST;
			else if (!strncmp(optarg, "others", strlen("others")))
				ctx.packet_type = PACKET_OTHERHOST;
			else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
				ctx.packet_type = PACKET_OUTGOING;
			else
				ctx.packet_type = -1;
			break;
		case 'S':
			ptr = optarg;
			ctx.reserve_size = 0;

			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB")))
				ctx.reserve_size = 1 << 10;
			else if (!strncmp(ptr, "MiB", strlen("MiB")))
				ctx.reserve_size = 1 << 20;
			else if (!strncmp(ptr, "GiB", strlen("GiB")))
				ctx.reserve_size = 1 << 30;
			else
				panic("Syntax error in ring size param!\n");
			*ptr = 0;

			ctx.reserve_size *= strtol(optarg, NULL, 0);
			break;
		case 'b':
			cpu_tmp = strtol(optarg, NULL, 0);

			cpu_affinity(cpu_tmp);
			if (ctx.cpu != -2)
				ctx.cpu = cpu_tmp;
			break;
		case 'H':
			prio_high = true;
			break;
		case 'c':
			ctx.pcap = PCAP_OPS_RW;
			ops_touched = 1;
			break;
		case 'm':
			ctx.pcap = PCAP_OPS_MM;
			ops_touched = 1;
			break;
		case 'G':
			ctx.pcap = PCAP_OPS_SG;
			ops_touched = 1;
			break;
		case 'Q':
			ctx.cpu = -2;
			break;
		case 's':
			ctx.print_mode = PRINT_NONE;
			break;
		case 'q':
			ctx.print_mode = PRINT_LESS;
			break;
		case 'X':
			ctx.print_mode =
				(ctx.print_mode == PRINT_ASCII) ?
				 PRINT_HEX_ASCII : PRINT_HEX;
			break;
		case 'l':
			ctx.print_mode =
				(ctx.print_mode == PRINT_HEX) ?
				 PRINT_HEX_ASCII : PRINT_ASCII;
			break;
		case 'k':
			ctx.kpull = strtol(optarg, NULL, 0);
			break;
		case 'n':
			frame_count_max = strtol(optarg, NULL, 0);
			break;
		case 'F':
			ptr = optarg;
			ctx.dump_interval = 0;

			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB"))) {
				ctx.dump_interval = 1 << 10;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
				ctx.dump_interval = 1 << 20;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
				ctx.dump_interval = 1 << 30;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "sec", strlen("sec"))) {
				ctx.dump_interval = 1;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "min", strlen("min"))) {
				ctx.dump_interval = 60;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
				ctx.dump_interval = 60 * 60;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "s", strlen("s"))) {
				ctx.dump_interval = 1;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else {
				panic("Syntax error in time/size param!\n");
			}

			*ptr = 0;
			ctx.dump_interval *= strtol(optarg, NULL, 0);
			break;
		case 'V':
			ctx.verbose = 1;
			break;
		case 'B':
			ctx.dump_bpf = true;
			break;
		case 'D':
			pcap_dump_type_features();
			die();
			break;
		case 'U':
			update_geoip();
			die();
			break;
		case 'v':
			version();
			break;
		case 'h':
			help();
			break;
		case '?':
			switch (optopt) {
			case 'd':
			case 'i':
			case 'o':
			case 'f':
			case 't':
			case 'P':
			case 'F':
			case 'n':
			case 'S':
			case 'b':
			case 'k':
			case 'T':
			case 'u':
			case 'g':
			case 'e':
				panic("Option -%c requires an argument!\n",
				      optopt);
			default:
				if (isprint(optopt))
					printf("Unknown option character `0x%X\'!\n", optopt);
				die();
			}
		default:
			break;
		}
	}

	if (!ctx.filter && optind != argc) {
		int ret;
		off_t offset = 0;

		for (i = optind; i < argc; ++i) {
			size_t alen = strlen(argv[i]) + 2;
			size_t flen = ctx.filter ? strlen(ctx.filter) : 0;

			ctx.filter = xrealloc(ctx.filter, 1, flen + alen);
			ret = slprintf(ctx.filter + offset, strlen(argv[i]) + 2, "%s ", argv[i]);
			if (ret < 0)
				panic("Cannot concatenate filter string!\n");
			else
				offset += ret;
		}
	}

	if (!ctx.device_in)
		ctx.device_in = xstrdup("any");

	register_signal(SIGINT, signal_handler);
	register_signal(SIGHUP, signal_handler);

	tprintf_init();

	if (prio_high) {
		set_proc_prio(-20);
		set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
	}

	if (ctx.device_in && (device_mtu(ctx.device_in) ||
	    !strncmp("any", ctx.device_in, strlen(ctx.device_in)))) {
		if (!ctx.rfraw)
			ctx.link_type = pcap_devtype_to_linktype(ctx.device_in);
		if (!ctx.device_out) {
			ctx.dump = 0;
			main_loop = recv_only_or_dump;
		} else if (device_mtu(ctx.device_out)) {
			register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
			main_loop = receive_to_xmit;
		} else {
			ctx.dump = 1;
			register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
			main_loop = recv_only_or_dump;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_SG;
		}
	} else {
		if (ctx.device_out && device_mtu(ctx.device_out)) {
			register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
			main_loop = pcap_to_xmit;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_MM;
		} else {
			main_loop = read_pcap;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_SG;
		}
	}

	bug_on(!main_loop);

	init_geoip(0);
	if (setsockmem)
		set_system_socket_memory(vals, array_size(vals));
	if (!ctx.enforce)
		xlockme();

	main_loop(&ctx);

	if (!ctx.enforce)
		xunlockme();
	if (setsockmem)
		reset_system_socket_memory(vals, array_size(vals));
	destroy_geoip();

	device_restore_irq_affinity_list();
	tprintf_cleanup();

	destroy_ctx(&ctx);
	return 0;
}
Example #23
0
int main(int argc, char **argv)
{
    struct ctx ctx = { };
    int key;
    CvPoint last_center;
    last_center.x = 0;
    last_center.y = 0;
    int threshold_x = 50;
    int threshold_y = 50;

    init_capture(&ctx);
    init_windows();
    init_ctx(&ctx);

    do
    {
        ctx.image = cvQueryFrame(ctx.capture);

        filter_and_threshold(&ctx);
        find_contour(&ctx);
        find_convex_hull(&ctx);
        find_fingers(&ctx);

        display(&ctx);
//cvWriteFrame(ctx.writer, ctx.image);

//printf("num: %d rad: %d def: %d x: %d y: %d\n", ctx.num_fingers, ctx.hand_radius, ctx.num_defects, ctx.hand_center.x, ctx.hand_center.y);

        if(ctx.num_fingers && ctx.hand_radius)
        {
            if(!last_center.x)
            {
                last_center = ctx.hand_center;

            }
            else
            {
                //Check If Position changed

                if( abs(ctx.hand_center.x - last_center.x)  > threshold_x )
                {
                    if( ctx.hand_center.x - last_center.x > 0 )
                    {
                        printf("move left\n");
                    }
                    else
                    {
                        printf("move right\n");
                    }
                }

                if( abs(ctx.hand_center.y - last_center.y)  > threshold_y )
                {
                    if( ctx.hand_center.y - last_center.y > 0 )
                    {
                        printf("move down\n");
                    }
                    else
                    {
                        printf("move up\n");
                    }
                }


                last_center = ctx.hand_center;

            }



        }




        key = cvWaitKey(1);
    }
    while (key != 'q');

    return 0;
}
Example #24
0
int main(int argc, char **argv)
{
	char *ptr;
	int c, i, j, cpu_tmp, opt_index, ops_touched = 0, vals[4] = {0};
	bool prio_high = false, setsockmem = true;
	void (*main_loop)(struct ctx *ctx) = NULL;
	struct ctx ctx;

	init_ctx(&ctx);
	srand(time(NULL));

	while ((c = getopt_long(argc, argv, short_options, long_options,
				&opt_index)) != EOF) {
		switch (c) {
		case 'd':
		case 'i':
			ctx.device_in = xstrdup(optarg);
			break;
		case 'o':
			ctx.device_out = xstrdup(optarg);
			break;
		case 'P':
			ctx.prefix = xstrdup(optarg);
			break;
		case 'R':
			ctx.rfraw = 1;
			break;
		case 'r':
			ctx.randomize = true;
			break;
		case 'J':
			ctx.jumbo = true;
			break;
		case 'T':
			ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
			pcap_check_magic(ctx.magic);
			break;
		case 'f':
			ctx.filter = xstrdup(optarg);
			break;
		case 'M':
			ctx.promiscuous = false;
			break;
		case 'N':
			ctx.hwtimestamp = false;
			break;
		case 'A':
			setsockmem = false;
			break;
		case 'u':
			ctx.uid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'g':
			ctx.gid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'C':
			ctx.fanout_group = strtoul(optarg, NULL, 0);
			if (ctx.fanout_group == 0)
				panic("Non-zero fanout group id required!\n");
			break;
		case 'K':
			if (!strncmp(optarg, "hash", strlen("hash")))
				ctx.fanout_type = PACKET_FANOUT_HASH;
			else if (!strncmp(optarg, "lb", strlen("lb")) ||
				 !strncmp(optarg, "rr", strlen("rr")))
				ctx.fanout_type = PACKET_FANOUT_LB;
			else if (!strncmp(optarg, "cpu", strlen("cpu")))
				ctx.fanout_type = PACKET_FANOUT_CPU;
			else if (!strncmp(optarg, "rnd", strlen("rnd")))
				ctx.fanout_type = PACKET_FANOUT_RND;
			else if (!strncmp(optarg, "roll", strlen("roll")))
				ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
			else if (!strncmp(optarg, "qm", strlen("qm")))
				ctx.fanout_type = PACKET_FANOUT_QM;
			else
				panic("Unknown fanout type!\n");
			break;
		case 'L':
			if (!strncmp(optarg, "defrag", strlen("defrag")))
				ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
			else if (!strncmp(optarg, "roll", strlen("roll")))
				ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
			else
				panic("Unknown fanout option!\n");
			break;
		case 't':
			if (!strncmp(optarg, "host", strlen("host")))
				ctx.packet_type = PACKET_HOST;
			else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
				ctx.packet_type = PACKET_BROADCAST;
			else if (!strncmp(optarg, "multicast", strlen("multicast")))
				ctx.packet_type = PACKET_MULTICAST;
			else if (!strncmp(optarg, "others", strlen("others")))
				ctx.packet_type = PACKET_OTHERHOST;
			else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
				ctx.packet_type = PACKET_OUTGOING;
			else
				ctx.packet_type = -1;
			break;
		case 'S':
			ptr = optarg;
			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB")))
				ctx.reserve_size = 1 << 10;
			else if (!strncmp(ptr, "MiB", strlen("MiB")))
				ctx.reserve_size = 1 << 20;
			else if (!strncmp(ptr, "GiB", strlen("GiB")))
				ctx.reserve_size = 1 << 30;
			else
				panic("Syntax error in ring size param!\n");

			ctx.reserve_size *= strtoul(optarg, NULL, 0);
			break;
		case 'b':
			cpu_tmp = strtol(optarg, NULL, 0);

			cpu_affinity(cpu_tmp);
			if (ctx.cpu != -2)
				ctx.cpu = cpu_tmp;
			break;
		case 'H':
			prio_high = true;
			break;
		case 'c':
			ctx.pcap = PCAP_OPS_RW;
			ops_touched = 1;
			break;
		case 'm':
			ctx.pcap = PCAP_OPS_MM;
			ops_touched = 1;
			break;
		case 'G':
			ctx.pcap = PCAP_OPS_SG;
			ops_touched = 1;
			break;
		case 'Q':
			ctx.cpu = -2;
			break;
		case 's':
			ctx.print_mode = PRINT_NONE;
			break;
		case 'q':
			ctx.print_mode = PRINT_LESS;
			break;
		case 'X':
			ctx.print_mode =
				(ctx.print_mode == PRINT_ASCII) ?
				 PRINT_HEX_ASCII : PRINT_HEX;
			break;
		case 'l':
			ctx.print_mode =
				(ctx.print_mode == PRINT_HEX) ?
				 PRINT_HEX_ASCII : PRINT_ASCII;
			break;
		case 'k':
			ctx.kpull = strtoul(optarg, NULL, 0);
			break;
		case 'n':
			frame_count_max = strtoul(optarg, NULL, 0);
			break;
		case 'F':
			ptr = optarg;
			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB"))) {
				ctx.dump_interval = 1 << 10;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
				ctx.dump_interval = 1 << 20;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
				ctx.dump_interval = 1 << 30;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "sec", strlen("sec"))) {
				ctx.dump_interval = 1;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "min", strlen("min"))) {
				ctx.dump_interval = 60;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
				ctx.dump_interval = 60 * 60;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "s", strlen("s"))) {
				ctx.dump_interval = 1;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else {
				panic("Syntax error in time/size param!\n");
			}

			ctx.dump_interval *= strtoul(optarg, NULL, 0);
			break;
		case 'V':
			ctx.verbose = true;
			break;
		case 'B':
			ctx.dump_bpf = true;
			break;
		case 'D':
			pcap_dump_type_features();
			die();
			break;
		case 'U':
			update_geoip();
			die();
			break;
		case 'w':
			ctx.link_type = LINKTYPE_LINUX_SLL;
			break;
		case 'v':
			version();
			break;
		case 'h':
			help();
			break;
		case '?':
			switch (optopt) {
			case 'd':
			case 'i':
			case 'o':
			case 'f':
			case 't':
			case 'P':
			case 'F':
			case 'n':
			case 'S':
			case 'b':
			case 'k':
			case 'T':
			case 'u':
			case 'g':
			case 'e':
				panic("Option -%c requires an argument!\n",
				      optopt);
			default:
				if (isprint(optopt))
					printf("Unknown option character `0x%X\'!\n", optopt);
				die();
			}
		default:
			break;
		}
	}

	if (!ctx.filter && optind != argc)
		ctx.filter = argv2str(optind, argc, argv);

	if (!ctx.device_in)
		ctx.device_in = xstrdup("any");

	register_signal(SIGINT, signal_handler);
	register_signal(SIGQUIT, signal_handler);
	register_signal(SIGTERM, signal_handler);
	register_signal(SIGHUP, signal_handler);

	tprintf_init();

	if (prio_high) {
		set_proc_prio(-20);
		set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
	}

	if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
		if (ctx.rfraw)
			setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);

		if (!ctx.link_type)
			ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
		if (link_has_sll_hdr(ctx.link_type)) {
			switch (ctx.magic) {
			case ORIGINAL_TCPDUMP_MAGIC:
				ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
				break;
			case NSEC_TCPDUMP_MAGIC:
				ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
				break;
			case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
				ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
				break;
			case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
				ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
				break;
			}
		}


		if (!ctx.device_out) {
			ctx.dump = 0;
			main_loop = recv_only_or_dump;
		} else if (device_mtu(ctx.device_out)) {
			register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
			main_loop = receive_to_xmit;
		} else {
			ctx.dump = 1;
			register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
			main_loop = recv_only_or_dump;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_SG;
		}
	} else {
		if (ctx.device_out && device_mtu(ctx.device_out)) {
			register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
			main_loop = pcap_to_xmit;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_MM;
		} else {
			setsockmem = false;
			main_loop = read_pcap;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_SG;
		}
	}

	bug_on(!main_loop);

	init_geoip(0);
	if (setsockmem)
		set_system_socket_memory(vals, array_size(vals));
	if (!ctx.enforce)
		xlockme();

	if (ctx.verbose)
		printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);

	main_loop(&ctx);

	if (!ctx.enforce)
		xunlockme();
	if (setsockmem)
		reset_system_socket_memory(vals, array_size(vals));
	destroy_geoip();

	device_restore_irq_affinity_list();
	tprintf_cleanup();

	destroy_ctx(&ctx);
	return 0;
}
int MAIN(int argc, char **argv)
{
	BIO *in = NULL, *out = NULL;
	char *infile = NULL, *outfile = NULL, *sigfile = NULL;
	ENGINE *e = NULL;
	int pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
	int keyform = FORMAT_PEM, peerform = FORMAT_PEM;
	char badarg = 0, rev = 0;
	char hexdump = 0, asn1parse = 0;
	EVP_PKEY_CTX *ctx = NULL;
	char *passargin = NULL;
	int keysize = -1;

	unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
	size_t buf_outlen;
	int buf_inlen = 0, siglen = -1;

	int ret = 1, rv = -1;

	argc--;
	argv++;

	if(!bio_err) bio_err = BIO_new_fp(OPENSSL_TYPE__FILE_STDERR, BIO_NOCLOSE);

	if (!load_config(bio_err, NULL))
		goto end;
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	
	while(argc >= 1)
		{
		if (!TINYCLR_SSL_STRCMP(*argv,"-in"))
			{
			if (--argc < 1) badarg = 1;
                        else infile= *(++argv);
			}
		else if (!TINYCLR_SSL_STRCMP(*argv,"-out"))
			{
			if (--argc < 1) badarg = 1;
			else outfile= *(++argv);
			}
		else if (!TINYCLR_SSL_STRCMP(*argv,"-sigfile"))
			{
			if (--argc < 1) badarg = 1;
			else sigfile= *(++argv);
			}
		else if(!TINYCLR_SSL_STRCMP(*argv, "-inkey"))
			{
			if (--argc < 1)
				badarg = 1;
			else
				{
				ctx = init_ctx(&keysize,
						*(++argv), keyform, key_type,
						passargin, pkey_op, e);
				if (!ctx)
					{
					BIO_puts(bio_err,
						"Error initializing context\n");
					ERR_print_errors(bio_err);
					badarg = 1;
					}
				}
			}
		else if (!TINYCLR_SSL_STRCMP(*argv,"-peerkey"))
			{
			if (--argc < 1)
				badarg = 1;
			else if (!setup_peer(bio_err, ctx, peerform, *(++argv)))
				badarg = 1;
			}
		else if (!TINYCLR_SSL_STRCMP(*argv,"-passin"))
			{
			if (--argc < 1) badarg = 1;
			else passargin= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-peerform") == 0)
			{
			if (--argc < 1) badarg = 1;
			else peerform=str2fmt(*(++argv));
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-keyform") == 0)
			{
			if (--argc < 1) badarg = 1;
			else keyform=str2fmt(*(++argv));
			}
#ifndef OPENSSL_NO_ENGINE
		else if(!TINYCLR_SSL_STRCMP(*argv, "-engine"))
			{
			if (--argc < 1)
				badarg = 1;
			else
				e = setup_engine(bio_err, *(++argv), 0);
			}
#endif
		else if(!TINYCLR_SSL_STRCMP(*argv, "-pubin"))
			key_type = KEY_PUBKEY;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-certin"))
			key_type = KEY_CERT;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-asn1parse"))
			asn1parse = 1;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-hexdump"))
			hexdump = 1;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-sign"))
			pkey_op = EVP_PKEY_OP_SIGN;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-verify"))
			pkey_op = EVP_PKEY_OP_VERIFY;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-verifyrecover"))
			pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-rev"))
			rev = 1;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-encrypt"))
			pkey_op = EVP_PKEY_OP_ENCRYPT;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-decrypt"))
			pkey_op = EVP_PKEY_OP_DECRYPT;
		else if(!TINYCLR_SSL_STRCMP(*argv, "-derive"))
			pkey_op = EVP_PKEY_OP_DERIVE;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pkeyopt") == 0)
			{
			if (--argc < 1)
				badarg = 1;
			else if (!ctx)
				{
				BIO_puts(bio_err,
					"-pkeyopt command before -inkey\n");
				badarg = 1;
				}
			else if (pkey_ctrl_string(ctx, *(++argv)) <= 0)
				{
				BIO_puts(bio_err, "parameter setting error\n");
				ERR_print_errors(bio_err);
				goto end;
				}
			}
		else badarg = 1;
		if(badarg)
			{
			usage();
			goto end;
			}
		argc--;
		argv++;
		}

	if (!ctx)
		{
		usage();
		goto end;
		}

	if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY))
		{
		BIO_puts(bio_err, "Signature file specified for non verify\n");
		goto end;
		}

	if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY))
		{
		BIO_puts(bio_err, "No signature file specified for verify\n");
		goto end;
		}

/* FIXME: seed PRNG only if needed */
	app_RAND_load_file(NULL, bio_err, 0);

	if (pkey_op != EVP_PKEY_OP_DERIVE)
		{
		if(infile)
			{
			if(!(in = BIO_new_file(infile, "rb")))
				{
				BIO_puts(bio_err,
					"Error Opening Input File\n");
				ERR_print_errors(bio_err);	
				goto end;
				}
			}
		else
			in = BIO_new_fp(OPENSSL_TYPE__FILE_STDIN, BIO_NOCLOSE);
		}

	if(outfile)
		{
		if(!(out = BIO_new_file(outfile, "wb")))
			{
			BIO_printf(bio_err, "Error Creating Output File\n");
			ERR_print_errors(bio_err);	
			goto end;
			}
		}
	else
		{
		out = BIO_new_fp(OPENSSL_TYPE__FILE_STDOUT, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		    BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		    out = BIO_push(tmpbio, out);
		}
#endif
	}

	if (sigfile)
		{
		BIO *sigbio = BIO_new_file(sigfile, "rb");
		if (!sigbio)
			{
			BIO_printf(bio_err, "Can't open signature file %s\n",
								sigfile);
			goto end;
			}
		siglen = bio_to_mem(&sig, keysize * 10, sigbio);
		BIO_free(sigbio);
		if (siglen <= 0)
			{
			BIO_printf(bio_err, "Error reading signature data\n");
			goto end;
			}
		}
	
	if (in)
		{
		/* Read the input data */
		buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
		if(buf_inlen <= 0)
			{
			BIO_printf(bio_err, "Error reading input Data\n");
			TINYCLR_SSL_EXIT(1);
			}
		if(rev)
			{
			size_t i;
			unsigned char ctmp;
			size_t l = (size_t)buf_inlen;
			for(i = 0; i < l/2; i++)
				{
				ctmp = buf_in[i];
				buf_in[i] = buf_in[l - 1 - i];
				buf_in[l - 1 - i] = ctmp;
				}
			}
		}

	if(pkey_op == EVP_PKEY_OP_VERIFY)
		{
		rv  = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
				      buf_in, (size_t)buf_inlen);
		if (rv == 0)
			BIO_puts(out, "Signature Verification Failure\n");
		else if (rv == 1)
			BIO_puts(out, "Signature Verified Successfully\n");
		if (rv >= 0)
			goto end;
		}
	else
		{	
		rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
			      buf_in, (size_t)buf_inlen);
		if (rv > 0)
			{
			buf_out = (unsigned char*)OPENSSL_malloc(buf_outlen);
			if (!buf_out)
				rv = -1;
			else
				rv = do_keyop(ctx, pkey_op,
						buf_out, (size_t *)&buf_outlen,
						buf_in, (size_t)buf_inlen);
			}
		}

	if(rv <= 0)
		{
		BIO_printf(bio_err, "Public Key operation error\n");
		ERR_print_errors(bio_err);
		goto end;
		}
	ret = 0;
	if(asn1parse)
		{
		if(!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
			ERR_print_errors(bio_err);
		}
	else if(hexdump)
		BIO_dump(out, (char *)buf_out, buf_outlen);
	else
		BIO_write(out, buf_out, buf_outlen);

	end:
	if (ctx)
		EVP_PKEY_CTX_free(ctx);
	BIO_free(in);
	BIO_free_all(out);
	if (buf_in)
		OPENSSL_free(buf_in);
	if (buf_out)
		OPENSSL_free(buf_out);
	if (sig)
		OPENSSL_free(sig);
	return ret;
}
Example #26
0
File: test.c Project: Rad0x6f/kpro9
struct xcon *init_xcon()
{
   unsigned int i;
   const unsigned int NUM_CTX = 2;
   const unsigned int NUM_NLP = 3;
   const char *asn1_data = "\x30\x08\x81\x02\x08\x9e\x82\x02\x03\x04";
   /* Note: ASN.1 may contain \0, so this won't always work.. */
   const unsigned int ASN1_DATA_LEN = strlen(asn1_data);

   struct xcon *xc = malloc(sizeof(struct xcon)
		            + sizeof(struct ctx) * NUM_CTX
			    + sizeof(struct nl_p) * NUM_NLP
             + ASN1_DATA_LEN);
   struct ctx *ctxp = (struct ctx*)   (xc   + 1);
   struct nl_p *nlpp = (struct nl_p*) (ctxp + NUM_CTX);
   char* asn1p =              (char*) (nlpp + NUM_NLP);

   /* Could do this in one big memset, but wanted to show each section.. */
   memset(xc, 0, sizeof(struct xcon));
   memset(ctxp, 0, sizeof(struct ctx)*NUM_CTX);
   memset(nlpp, 0, sizeof(struct nl_p)*NUM_NLP);
   memset(asn1p, 0, ASN1_DATA_LEN);

   xc->agent_type = AGENT_D;
   xc->agent_id = 11233342;
   xc->features = 0x01 | 0x02 | 0x08 | 0x10;
   xc->pres_ctx[0] = 70000000;
   xc->pres_ctx[1] = 6000000;
   xc->pres_ctx[2] = 500000;
   xc->pres_ctx[4] = 3000;
   xc->pres_ctx[5] = 200;
   xc->pres_ctx[6] = 10;
   xc->pres_ctx[7] = 0;
   xc->common_ref[0] = 12;
   xc->common_ref[4] = 106;
   strcpy (xc->name, "CSjark uttales sæschjaschjjjk");
   xc->a_xsap = init_sap(1);
   xc->b_xsap = init_sap(2);
   xc->result_source = 22;
   xc->diagnostic = -23;
   xc->trak = 554;
   xc->link = init_tsk_address();
   xc->context = init_ctx(0);
   xc->abc = init_abc_p();
   xc->rst = init_rst_p();
   xc->pl  = init_pl_p();
   xc->sl  = init_sl_p();
   xc->nl  = init_nl_p();
   xc->gir = 64646464;
   xc->colour = GREEN;
   xc->fatso = init_huge_t();
   strcpy (xc->filename, "/path/to/file/buried/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/far/down");
   xc->created = init_nstime_t();
   xc->timeout = init_time_t();
   xc->ctx_no = NUM_CTX;
   xc->nlp_no = NUM_NLP;

   for (i = 0; i < NUM_CTX; i++) {
      ctxp[i] = init_ctx(i+1);
   }

   for (i = 0; i < NUM_NLP; i++) {
      nlpp[i] = init_nl_p(i);
   }

   memcpy(asn1p, asn1_data, ASN1_DATA_LEN);

   return xc;

}
Example #27
0
/*
// Name: main
// In: argv, the arguments sent to the program.
//	   argc, the number of arguments sent to the program.
*/
int main (int argc, char **argv) {
	char port[6];
	char ssl_port[6];
	if(!arguments(argv, argc, port, ssl_port)) {
		printf("Usage: chat_server [port] [ssl port]\n");
		return 0;
	}
	char topic[MAXTOKENSIZE];
	memset(topic, '\0', MAXTOKENSIZE);
	// Set the signal handler.
	signal(SIGINT, signal_handler);
	server_socket = -1;
	ssl_socket = -1;
	server_socket_fd;
	int epoll_fd;
	struct epoll_event event, ssl_event;
	BIO *sbio;
	SSL *ssl;
	// Initialize ssl context.
	ctx=init_ctx();
	memset(&event, 0, sizeof event);
	memset(&ssl_event, 0, sizeof event);
	printf("Trying to create socket.\n");
	server_socket_fd = create_socket("telnet", port);
	ssl_socket_fd = create_socket("telnet", ssl_port);
	printf("Created socket.\n");
	// Check if sockets couldn't be created.
	if(server_socket_fd<0 || ssl_socket_fd<0) {
		fprintf(stderr, "Socket could not be created!\n");
		return -1;
	}
	// Set the socket to be non-blocking.
	server_socket = unblock_socket(server_socket_fd);
	ssl_socket = unblock_socket(ssl_socket_fd);
	if(server_socket<0 || ssl_socket<0) {
		fprintf(stderr, "Could not make socket non blocking.\n");
		return -1;
	}
	printf("Listening...\n");
	// Listen for incoming connections.
	server_socket = listen(server_socket_fd, NUMBER_PENDING_CONNECTIONS);
	ssl_socket = listen(ssl_socket_fd, NUMBER_PENDING_CONNECTIONS);
	if(server_socket < 0 || ssl_socket<0) {
		fprintf(stderr, "Could not listen to incoming connections.\n");
		return -1;
	}
	epoll_fd = epoll_create1(0);
	event.data.fd = server_socket_fd;
	// Run as edge-triggered, meaning that epoll_wait will return only on
	// new events.
	event.events = EPOLLIN | EPOLLET;
	// Create epoll control interface for the unsecure socket.
	server_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 
								server_socket_fd, &event);
	ssl_event.data.fd=ssl_socket_fd;
	ssl_event.events = EPOLLIN | EPOLLET;
	// Create epoll control interface for the secure socket.
	ssl_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, ssl_socket_fd, &ssl_event);
	if(server_socket<0 || ssl_socket<0) {
		fprintf(stderr, "Could not create control interface for polling.\n");
		return -1;
	}
	events = calloc(MAXEVENTS, sizeof event);
	// Create hash map for storing connected clients.
	clients = hash_empty(MAXCLIENTS);
	struct sockaddr client_addr;
	socklen_t client_len;
	int insocket_fd;
	int client_socket;
	char host[MAXHOST_LEN], serv[MAXSERV_LEN];
	client_len = sizeof client_addr;
	// Main loop listening from events generated by epoll.
	while(1) {
		int n,i;
		// Wait for new events.
		n = epoll_wait(epoll_fd, events, MAXEVENTS, -1);
		for(i=0;i<n;i++) {
			if((events[i].events & EPOLLERR) || 
				events[i].events & EPOLLHUP || 
				(!(events[i].events & EPOLLIN))) {
				fprintf(stderr, "An error occured at an event.\n");
				clientconn_t *c;
				// If the an error-event occured at a connected client.
				if((c = hash_get(events[i].data.fd, clients))!=NULL) {
					client_close(c);
					hash_remove(c, clients);
				}
				close(events[i].data.fd);
				continue;
			}
			// If an a connection is made on the unsecure socket.
			else if(server_socket_fd == events[i].data.fd) {
				while(1) {
					// Accept connection.
					insocket_fd = accept(server_socket_fd, 
									&client_addr, &client_len);
					if(insocket_fd<0) {
						if(!(errno == EAGAIN || errno == EWOULDBLOCK)) {
							fprintf(stderr, "Could not accept "
											"input connection");
							break;
						} else {
							// If the whole handshake could not be made, 
							// keep trying to accept.
							break;
						}
					}
					// The address information.
					server_socket = getnameinfo(&client_addr, client_len, host,
							sizeof host, serv, sizeof serv, 
							NI_NUMERICHOST|NI_NUMERICSERV);
					if(server_socket==0) {
						printf("Connection accepted!\n");
					}
					// Make client socket non-blocking.
					server_socket = unblock_socket(insocket_fd);
					if(server_socket <0) {
						fprintf(stderr, "Could not make client socket "
								"non-blocking\n");
						return -1;
					}
					// Create an epoll interface for the client socket.
					event.data.fd = insocket_fd;
					event.events = EPOLLIN|EPOLLET;
					server_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 
									insocket_fd, &event);
					if(server_socket<0) {
						fprintf(stderr, "Could not create epoll "
										"interface for client\n");
						return -1;
					}
					printf("Added client(%d)!\n", insocket_fd);
					// Store client in the hash map.
					c = create_client(insocket_fd, &client_addr);
					hash_insert(c, clients);
				}
				continue;
			}
			// If a connection is made on the secure socket.
			else if(ssl_socket_fd == events[i].data.fd) {
				printf("Someone connected through ssl!\n");
				while(1) {
					// Accept in the same way as the unsecure socket.
					insocket_fd = accept(ssl_socket_fd, 
										&client_addr, &client_len);
					if(insocket_fd<0) {
						if(!(errno == EAGAIN || errno == EWOULDBLOCK)) {
							fprintf(stderr, "Could not accept input "
											"connection\n");
							break;
						} else {
							break;
						}
					}
					ssl_socket = getnameinfo(&client_addr, client_len, host, 
							sizeof host, serv, sizeof serv, 
							NI_NUMERICHOST|NI_NUMERICSERV);
					if(ssl_socket==0) {
						printf("Connection accepted!\n");
					}
					// Make socket non-blocking
					ssl_socket = unblock_socket(insocket_fd);
					if(ssl_socket<0){
						fprintf(stderr, "Could not make secure client "
										"socket non-blocking.\n");
						return -1;
					}
					// Create epoll interface for the secure client connection
					ssl_event.data.fd = insocket_fd;
					ssl_event.events = EPOLLIN;
					ssl_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD,
											insocket_fd, &ssl_event);
					if(ssl_socket<0) {
						fprintf(stderr, "Could not create "
										"epoll interface for client.\n");
						return -1;
					}
					printf("Added client!(%d)\n", insocket_fd);
					c = create_client(insocket_fd, &client_addr);
					// Set up ssl.
					c->ssl_status=STATUS_HANDSHAKE;
					c->ssl = SSL_new(ctx);
					SSL_set_fd(c->ssl, insocket_fd);
					SSL_set_mode(c->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
					hash_insert(c, clients);
				}
				continue;
			}
			// If an incoming message has caused an event.
			else {
				int done = 0;
				while (1) {
					ssize_t count;
					char buf[MAXBUFSIZE];
					memset(buf, '\0', MAXBUFSIZE);
					clientconn_t *c = hash_get(events[i].data.fd, clients);
					// If the client is trying to make an ssl handshake.
					if(c->ssl_status==STATUS_HANDSHAKE) {
						int r=1;
						r=SSL_accept(c->ssl);
						if (r<0) {
							if(SSL_get_error(c->ssl, r)!=SSL_ERROR_WANT_READ &&
							  SSL_get_error(c->ssl, r)!=SSL_ERROR_WANT_WRITE ){
									done=1;
									printf("Could not accept ssl "
											"connection\n");
								break;
							}
						} else {
							// Handshake is done.
							c->ssl_status=STATUS_ACCEPTED;
						}
					}
					else {
						// Read data from client.
						int count = client_read(c, buf, sizeof buf);
						if(count<0) {
							if(errno!=EAGAIN) {
								fprintf(stderr, "Could not read"
											" from socket!\n");
								done=1;
							}
							break;
						}
						if(buf[MAXBUFSIZE-1] != '\0') {
							write(events[i].data.fd, "* BAD Buffer will "
													"overflow\r\n", 28);
							break;
						}
						else if (count==0) {
							done=1;
							break;
						}
						if (handle_input(events[i].data.fd, 
								buf, count, clients, topic)==CLIENTCLOSED) {
							done=1;
							break;
						}
						if(server_socket<0) {
							fprintf(stderr, "Could get input.\n");
							return -1;
						}
					}
				}
				// Client connection is done, wants to disconnect.
				if(done) {
					printf("Closed connection!\n");
					clientconn_t *closeclient = hash_get(events[i].data.fd, 
															clients);
					if(closeclient != NULL) {
						hash_remove(closeclient, clients);
						client_close(closeclient);
					}
					close(events[i].data.fd);
				}
			}
		}
	}
	free(events);
	close(server_socket_fd);
	return 0;
}
Example #28
0
/* type is one of the following: 1, 224, 256, 384, 512 (for SHA) or 5 (for MD5) */
static void *
hmac_sha_md5 (const char *buffer, size_t len, char *key, size_t key_len, char *resbuf, int type) {
  /* SHA512_BLOCKSIZE and SHA512_DIGESTSIZE are the biggest, so we can use it with other algorithms */
  char Ki[SHA512_BLOCKSIZE];
  char Ko[SHA512_BLOCKSIZE];
  char tmpbuf[SHA512_DIGESTSIZE];
  int i;
  int blocksize;
  int digestsize;
  void *ctx;
  void (*init_ctx)(void *);
  void (*process_bytes)(void *, size_t, void *);
  void *(*finish_ctx)(void *, void *);
  void *result;

  switch (type) {
          case 5: /* Oh, it's MD5! */
                  ctx = malloc(sizeof(struct md5_ctx));
                  init_ctx      = (void(*)(void *))                 &md5_init_ctx;
                  process_bytes = (void(*)(void *, size_t, void *)) &md5_process_bytes;
                  finish_ctx    = (void* (*)(void *, void *))       &md5_finish_ctx;
                  blocksize = MD5_BLOCKSIZE;
                  digestsize = MD5_DIGESTSIZE;
                  break;
               /*   .--------< SHA variant   
                    |                        
                    v                   */
          SHA_CASE(  1,   1)
          SHA_CASE(224, 256)
          SHA_CASE(256, 256)
          SHA_CASE(384, 512)
          SHA_CASE(512, 512)
          default:
                  return NULL;
  }

  /* if given key is longer that algorithm's block, we must change it to
     hash of the original key (of size of algorithm's digest) */
  if (key_len > blocksize) {
          init_ctx (&ctx);
          process_bytes (key, key_len, &ctx);
          finish_ctx (&ctx, Ki);
          key_len = digestsize;
          memcpy(Ko, Ki, key_len);
  } else {
          memcpy(Ki, key, key_len);
          memcpy(Ko, key, key_len);
  }

  /* prepare input and output key */
  for (i = 0; i < key_len; i++) {
          Ki[i] ^= 0x36;
          Ko[i] ^= 0x5c;
  }
  for (; i < blocksize; i++) {
          Ki[i] = 0x36;
          Ko[i] = 0x5c;
  }

  init_ctx (ctx);
  process_bytes (Ki, blocksize, ctx);
  process_bytes ((void *)buffer, len, ctx);
  finish_ctx (ctx, tmpbuf);

  init_ctx (ctx);
  process_bytes (Ko, blocksize, ctx);
  process_bytes (tmpbuf, digestsize, ctx);

  result = finish_ctx (ctx, resbuf);
  free(ctx);

  return result;
}
Example #29
0
int main(void) {
  open_log(NULL);
  
  ctx *context = init_ctx();
  
  strcpy(context->dev_name, "/dev/video1");
  
  open_device(context);
  
  //printf("%d %d\n", context->d_framerate.num, context->d_framerate.den);
  
  //context->c_top = 0;
  //context->c_left = 0;
  //context->c_width = 960;
  //context->c_height = 540;
  //
  //context->f_width = 960;
  //context->f_height = 540;
  
  //context->framerate.num = 1;
  //context->framerate.den = 7;
  
  init_device(context);
  
  //printf("%d %d\n", context->framerate.num, context->framerate.den);
  
  context->stop = 60;
  bool infinite;
  if (context->stop == 0) {
    infinite = true;
  }
  
  conv_ctx *conv_context = conv_ctx_init(context);
  
  //strcpy(conv_context->filename, "test.ts");
  strcpy(conv_context->format, "avi");
  
  start_capture(context);

  //rgb24_init(context, conv_context);
  
  scaler_init(context, conv_context);
  mux_encoder_init(context, conv_context);

  while (context->stop-- | infinite) {
    for (;;) {
      capture_timeout(context);
      
      /* read frame and go on */
      if (read_frame(context)) {
        //rgb24(context, conv_context);
        scale(context, conv_context);
        mux_encode(context, conv_context);
        break;
      }
    }
  }

  write_cached(context, conv_context);

  //rgb24_uninit(context, conv_context);

  scaler_uninit(context, conv_context);
  mux_encoder_uninit(context, conv_context);

  conv_ctx_uninit(conv_context);

  stop_capture(context);
  uninit_device(context);
  
  close_device(context);
  
  close_log();

  return EXIT_SUCCESS;
}
Example #30
0
int pkeyutl_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    ENGINE *e = NULL;
    EVP_PKEY_CTX *ctx = NULL;
    EVP_PKEY *pkey = NULL;
    char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
    char hexdump = 0, asn1parse = 0, rev = 0, *prog;
    unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
    OPTION_CHOICE o;
    int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform = FORMAT_PEM;
    int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
    int engine_impl = 0;
    int ret = 1, rv = -1;
    size_t buf_outlen;
    const char *inkey = NULL;
    const char *peerkey = NULL;
    const char *kdfalg = NULL;
    int kdflen = 0;
    STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
    STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL;
    int rawin = 0;
    const EVP_MD *md = NULL;

    prog = opt_init(argc, argv, pkeyutl_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(pkeyutl_options);
            ret = 0;
            goto end;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_SIGFILE:
            sigfile = opt_arg();
            break;
        case OPT_ENGINE_IMPL:
            engine_impl = 1;
            break;
        case OPT_INKEY:
            inkey = opt_arg();
            break;
        case OPT_PEERKEY:
            peerkey = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PEERFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDE, &peerform))
                goto opthelp;
            break;
        case OPT_KEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform))
                goto opthelp;
            break;
        case OPT_R_CASES:
            if (!opt_rand(o))
                goto end;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_PUBIN:
            key_type = KEY_PUBKEY;
            break;
        case OPT_CERTIN:
            key_type = KEY_CERT;
            break;
        case OPT_ASN1PARSE:
            asn1parse = 1;
            break;
        case OPT_HEXDUMP:
            hexdump = 1;
            break;
        case OPT_SIGN:
            pkey_op = EVP_PKEY_OP_SIGN;
            break;
        case OPT_VERIFY:
            pkey_op = EVP_PKEY_OP_VERIFY;
            break;
        case OPT_VERIFYRECOVER:
            pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
            break;
        case OPT_ENCRYPT:
            pkey_op = EVP_PKEY_OP_ENCRYPT;
            break;
        case OPT_DECRYPT:
            pkey_op = EVP_PKEY_OP_DECRYPT;
            break;
        case OPT_DERIVE:
            pkey_op = EVP_PKEY_OP_DERIVE;
            break;
        case OPT_KDF:
            pkey_op = EVP_PKEY_OP_DERIVE;
            key_type = KEY_NONE;
            kdfalg = opt_arg();
            break;
        case OPT_KDFLEN:
            kdflen = atoi(opt_arg());
            break;
        case OPT_REV:
            rev = 1;
            break;
        case OPT_PKEYOPT:
            if ((pkeyopts == NULL &&
                 (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
                sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
                BIO_puts(bio_err, "out of memory\n");
                goto end;
            }
            break;
        case OPT_PKEYOPT_PASSIN:
            if ((pkeyopts_passin == NULL &&
                 (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) ||
                sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) {
                BIO_puts(bio_err, "out of memory\n");
                goto end;
            }
            break;
        case OPT_RAWIN:
            rawin = 1;
            break;
        case OPT_DIGEST:
            if (!opt_md(opt_arg(), &md))
                goto end;
            break;
        }
    }
    argc = opt_num_rest();
    if (argc != 0)
        goto opthelp;

    if (rawin && pkey_op != EVP_PKEY_OP_SIGN && pkey_op != EVP_PKEY_OP_VERIFY) {
        BIO_printf(bio_err,
                   "%s: -rawin can only be used with -sign or -verify\n",
                   prog);
        goto opthelp;
    }

    if (md != NULL && !rawin) {
        BIO_printf(bio_err,
                   "%s: -digest can only be used with -rawin\n",
                   prog);
        goto opthelp;
    }

    if (rawin && rev) {
        BIO_printf(bio_err, "%s: -rev cannot be used with raw input\n",
                   prog);
        goto opthelp;
    }

    if (kdfalg != NULL) {
        if (kdflen == 0) {
            BIO_printf(bio_err,
                       "%s: no KDF length given (-kdflen parameter).\n", prog);
            goto opthelp;
        }
    } else if (inkey == NULL) {
        BIO_printf(bio_err,
                   "%s: no private key given (-inkey parameter).\n", prog);
        goto opthelp;
    } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) {
        BIO_printf(bio_err,
                   "%s: no peer key given (-peerkey parameter).\n", prog);
        goto opthelp;
    }
    ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
                   passinarg, pkey_op, e, engine_impl, &pkey);
    if (ctx == NULL) {
        BIO_printf(bio_err, "%s: Error initializing context\n", prog);
        ERR_print_errors(bio_err);
        goto end;
    }
    if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
        BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
        ERR_print_errors(bio_err);
        goto end;
    }
    if (pkeyopts != NULL) {
        int num = sk_OPENSSL_STRING_num(pkeyopts);
        int i;

        for (i = 0; i < num; ++i) {
            const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);

            if (pkey_ctrl_string(ctx, opt) <= 0) {
                BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
                           prog, opt);
                ERR_print_errors(bio_err);
                goto end;
            }
        }
    }
    if (pkeyopts_passin != NULL) {
        int num = sk_OPENSSL_STRING_num(pkeyopts_passin);
        int i;

        for (i = 0; i < num; i++) {
            char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i);
            char *passin = strchr(opt, ':');
            char *passwd;

            if (passin == NULL) {
                /* Get password interactively */
                char passwd_buf[4096];
                BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt);
                EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1,
                                   passwd_buf, 0);
                passwd = OPENSSL_strdup(passwd_buf);
                if (passwd == NULL) {
                    BIO_puts(bio_err, "out of memory\n");
                    goto end;
                }
            } else {
                /* Get password as a passin argument: First split option name
                 * and passphrase argument into two strings */
                *passin = 0;
                passin++;
                if (app_passwd(passin, NULL, &passwd, NULL) == 0) {
                    BIO_printf(bio_err, "failed to get '%s'\n", opt);
                    goto end;
                }
            }

            if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) {
                BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
                           prog, opt);
                goto end;
            }
            OPENSSL_free(passwd);
        }
    }

    if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) {
        BIO_printf(bio_err,
                   "%s: Signature file specified for non verify\n", prog);
        goto end;
    }

    if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) {
        BIO_printf(bio_err,
                   "%s: No signature file specified for verify\n", prog);
        goto end;
    }

    if (pkey_op != EVP_PKEY_OP_DERIVE) {
        in = bio_open_default(infile, 'r', FORMAT_BINARY);
        if (in == NULL)
            goto end;
    }
    out = bio_open_default(outfile, 'w', FORMAT_BINARY);
    if (out == NULL)
        goto end;

    if (sigfile != NULL) {
        BIO *sigbio = BIO_new_file(sigfile, "rb");

        if (sigbio == NULL) {
            BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
            goto end;
        }
        siglen = bio_to_mem(&sig, keysize * 10, sigbio);
        BIO_free(sigbio);
        if (siglen < 0) {
            BIO_printf(bio_err, "Error reading signature data\n");
            goto end;
        }
    }

    /* Raw input data is handled elsewhere */
    if (in != NULL && !rawin) {
        /* Read the input data */
        buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
        if (buf_inlen < 0) {
            BIO_printf(bio_err, "Error reading input Data\n");
            goto end;
        }
        if (rev) {
            size_t i;
            unsigned char ctmp;
            size_t l = (size_t)buf_inlen;
            for (i = 0; i < l / 2; i++) {
                ctmp = buf_in[i];
                buf_in[i] = buf_in[l - 1 - i];
                buf_in[l - 1 - i] = ctmp;
            }
        }
    }

    /* Sanity check the input if the input is not raw */
    if (!rawin
            && buf_inlen > EVP_MAX_MD_SIZE
            && (pkey_op == EVP_PKEY_OP_SIGN
                || pkey_op == EVP_PKEY_OP_VERIFY
                || pkey_op == EVP_PKEY_OP_VERIFYRECOVER)) {
        BIO_printf(bio_err,
                   "Error: The input data looks too long to be a hash\n");
        goto end;
    }

    if (pkey_op == EVP_PKEY_OP_VERIFY) {
        if (rawin) {
            rv = do_raw_keyop(pkey_op, ctx, md, pkey, in, sig, siglen,
                              NULL, 0);
        } else {
            rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
                                 buf_in, (size_t)buf_inlen);
        }
        if (rv == 1) {
            BIO_puts(out, "Signature Verified Successfully\n");
            ret = 0;
        } else {
            BIO_puts(out, "Signature Verification Failure\n");
        }
        goto end;
    }
    if (kdflen != 0) {
        buf_outlen = kdflen;
        rv = 1;
    } else {
        if (rawin) {
            /* rawin allocates the buffer in do_raw_keyop() */
            rv = do_raw_keyop(pkey_op, ctx, md, pkey, in, NULL, 0,
                              &buf_out, (size_t *)&buf_outlen);
        } else {
            rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
                          buf_in, (size_t)buf_inlen);
            if (rv > 0 && buf_outlen != 0) {
                buf_out = app_malloc(buf_outlen, "buffer output");
                rv = do_keyop(ctx, pkey_op,
                              buf_out, (size_t *)&buf_outlen,
                              buf_in, (size_t)buf_inlen);
            }
        }
    }
    if (rv <= 0) {
        if (pkey_op != EVP_PKEY_OP_DERIVE) {
            BIO_puts(bio_err, "Public Key operation error\n");
        } else {
            BIO_puts(bio_err, "Key derivation failed\n");
        }
        ERR_print_errors(bio_err);
        goto end;
    }
    ret = 0;

    if (asn1parse) {
        if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
            ERR_print_errors(bio_err);
    } else if (hexdump) {
        BIO_dump(out, (char *)buf_out, buf_outlen);
    } else {
        BIO_write(out, buf_out, buf_outlen);
    }

 end:
    EVP_PKEY_CTX_free(ctx);
    release_engine(e);
    BIO_free(in);
    BIO_free_all(out);
    OPENSSL_free(buf_in);
    OPENSSL_free(buf_out);
    OPENSSL_free(sig);
    sk_OPENSSL_STRING_free(pkeyopts);
    sk_OPENSSL_STRING_free(pkeyopts_passin);
    return ret;
}