Exemple #1
0
static int ibmca_finish(ENGINE *e)

        {

        if(ibmca_dso == NULL)

                {

                IBMCAerr(IBMCA_F_IBMCA_FINISH,IBMCA_R_NOT_LOADED);

                return 0;

                }

        release_context(handle);

        if(!DSO_free(ibmca_dso))

                {

                IBMCAerr(IBMCA_F_IBMCA_FINISH,IBMCA_R_DSO_FAILURE);

                return 0;

                }

        ibmca_dso = NULL;



        return 1;

        }
static int hwcrhk_finish(ENGINE *e)
	{
	int to_return = 1;
	free_HWCRHK_LIBNAME();
	if(hwcrhk_dso == NULL)
		{
		HWCRHKerr(HWCRHK_F_HWCRHK_FINISH,HWCRHK_R_NOT_LOADED);
		to_return = 0;
		goto err;
		}
	release_context(hwcrhk_context);
	if(!DSO_free(hwcrhk_dso))
		{
		HWCRHKerr(HWCRHK_F_HWCRHK_FINISH,HWCRHK_R_DSO_FAILURE);
		to_return = 0;
		goto err;
		}
 err:
	if (logstream)
		BIO_free(logstream);
	hwcrhk_dso = NULL;
	p_hwcrhk_Init = NULL;
	p_hwcrhk_Finish = NULL;
	p_hwcrhk_ModExp = NULL;
#ifndef OPENSSL_NO_RSA
	p_hwcrhk_RSA = NULL;
	p_hwcrhk_RSALoadKey = NULL;
	p_hwcrhk_RSAGetPublicKey = NULL;
	p_hwcrhk_RSAUnloadKey = NULL;
#endif
	p_hwcrhk_ModExpCRT = NULL;
	p_hwcrhk_RandomBytes = NULL;
	return to_return;
	}
int
main(void)
{
  context_t *context = alloc_context();
  if (!context)
    {
      printf("T:  Failed to create new context.\n");
      return 1;
    }
  for (int i = 0; i < 5; i++)
    {
      measurement_t measurement;
      if (measure(context, &measurement) == 0)
        {
          printf("T:  Time = %.1u, Value = %.3f\n",
                 measurement.time, measurement.value);
        }
      else
        {
          printf("T:  Failed to obtain measurement.\n");
        }
    }
  if (release_context(context) != 0)
    {
      printf("T:  Failed to release context.\n");
      return 1;
    }
  return 0;
}
Exemple #4
0
HOT_INLINE
static void cb_Exit(
    hot_contextID_t id, 
    unsigned *cs
) {
    hot_context_t s;
    hot_ens_Exit_cback exit_cb;
    void *env;
    
    begin_critical(); {
	s = lookup_context(id);
	if (!s->leaving)
	    hot_sys_Panic("hot_ens_Exit_cbd: mbr state is not leaving");
	env = s->env;
	exit_cb = s->conf.exit;
    }  end_critical();

    if (exit_cb != NULL) {
	(*exit_cb)(s, env);
    }  

    begin_critical(); {
	release_context(s);
    } end_critical();  
}
int main( int argc, char **argv )
{
    if(argc == 1)
    {
        printf("usage: %s shader.glsl [mesh.obj] [texture0.png [texture1.png]]\n", argv[0]);
        return 0;
    }
    
    Window window= create_window(1024, 640);
    if(window == NULL) 
        return 1;
    
    Context context= create_context(window);
    if(context == NULL) 
        return 1;
    
    // creation des objets opengl
    std::vector<const char *> options(argv + 1, argv + argc);
    if(init(options) < 0)
    {
        printf("[error] init failed.\n");
        return 1;
    }
    
    // affichage de l'application
    run(window, draw);

    // nettoyage
    quit();
    release_context(context);
    release_window(window);
    return 0;
}
Exemple #6
0
int main( int argc, char **argv )
{
    // etape 1 : creer la fenetre
    Window window= create_window(1024, 640);
    if(window == NULL) 
        return 1;       // erreur lors de la creation de la fenetre ou de l'init de sdl2
    
    // etape 2 : creer un contexte opengl pour pouvoir dessiner
    Context context= create_context(window);
    if(context == NULL) 
        return 1;       // erreur lors de la creation du contexte opengl
    
    // etape 3 : creation des objets 
    if(init() < 0)
    {
        printf("[error] init failed.\n");
        return 1;
    }
    
    // etape 4 : affichage de l'application, tant que la fenetre n'est pas fermee. ou que draw() ne renvoie pas 0
    run(window, draw);

    // etape 5 : nettoyage
    quit();
    release_context(context);
    release_window(window);
    return 0;
}
/* (de)initialisation functions. */
static int cswift_init(ENGINE *e)
	{
        SW_CONTEXT_HANDLE hac;
        t_swAcquireAccContext *p1;
        t_swAttachKeyParam *p2;
        t_swSimpleRequest *p3;
        t_swReleaseAccContext *p4;

	if(cswift_dso != NULL)
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_ALREADY_LOADED);
		goto err;
		}
	/* Attempt to load libswift.so/swift.dll/whatever. */
	cswift_dso = DSO_load(NULL, get_CSWIFT_LIBNAME(), NULL, 0);
	if(cswift_dso == NULL)
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED);
		goto err;
		}
	if(!(p1 = (t_swAcquireAccContext *)
				DSO_bind_func(cswift_dso, CSWIFT_F1)) ||
			!(p2 = (t_swAttachKeyParam *)
				DSO_bind_func(cswift_dso, CSWIFT_F2)) ||
			!(p3 = (t_swSimpleRequest *)
				DSO_bind_func(cswift_dso, CSWIFT_F3)) ||
			!(p4 = (t_swReleaseAccContext *)
				DSO_bind_func(cswift_dso, CSWIFT_F4)))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_NOT_LOADED);
		goto err;
		}
	/* Copy the pointers */
	p_CSwift_AcquireAccContext = p1;
	p_CSwift_AttachKeyParam = p2;
	p_CSwift_SimpleRequest = p3;
	p_CSwift_ReleaseAccContext = p4;
	/* Try and get a context - if not, we may have a DSO but no
	 * accelerator! */
	if(!get_context(&hac))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_INIT,CSWIFT_R_UNIT_FAILURE);
		goto err;
		}
	release_context(hac);
	/* Everything's fine. */
	return 1;
err:
	if(cswift_dso)
	{
		DSO_free(cswift_dso);
		cswift_dso = NULL;
	}
	p_CSwift_AcquireAccContext = NULL;
	p_CSwift_AttachKeyParam = NULL;
	p_CSwift_SimpleRequest = NULL;
	p_CSwift_ReleaseAccContext = NULL;
	return 0;
	}
Exemple #8
0
	booster::shared_ptr<json_call> json_rpc_server::release_call()
	{
		check_call();
		current_call_->attach_context(release_context());
		booster::shared_ptr<json_call> call = current_call_;
		current_call_.reset();
		return call;
	}
Exemple #9
0
	void single()
	{
		calls ++;
		std::ostream &out = response().out();
		for(unsigned i=0;i<10000000;i++) {
			out << i << '\n';
		}
		release_context()->async_complete_response();
	}
Exemple #10
0
	void multiple()
	{
		calls ++;
		binder call;
		call.context = release_context();
		call.counter = 10000;
		call(cppcms::http::context::operation_completed);

	}
Exemple #11
0
/* Should NOT be called with cs_error held */
KHMEXP void KHMAPI
kherr_release_context(kherr_context * c)
{
    if (!IS_KHERR_CTX(c))
        return;

    EnterCriticalSection(&cs_error);
    release_context(c);
    LeaveCriticalSection(&cs_error);
}
Exemple #12
0
	void json_rpc_server::main(std::string /*unused*/)
	{
		if(!smd_.empty() && request().request_method()=="GET") {

			response().set_content_header("application/json");
			response().out() << smd_;

			if(is_asynchronous())
				release_context()->async_complete_response();
			return;
		}

		try {
			current_call_.reset(new json_call(context()));
			methods_map_type::iterator p=methods_.find(method());
			if(p==methods_.end()) {
				if(!notification())
					return_error("Method not found");
				return;
			}
			if(p->second.role == notification_role && !notification()) {
				return_error("The request should be notification");
				return;
			}
			if(p->second.role == method_role && notification()) {
				// No way to respond according to protocol
				return;
			}
			try {
				p->second.method(params());
			}
			catch(json::bad_value_cast const &e) {
				if(current_call_.get() && !notification())
					return_error("Invalid parameters");
				return;
			}
			catch(call_error const &e) {
				if(current_call_.get() && !notification())
					return_error(e.what());
				return;
			}
			catch(std::exception const &e) {
				if(current_call_.get() && !notification())
					return_error("Internal Service Error");
				return;
			}
		}
		catch(call_error const &e)
		{
			response().set_content_header("text/plain");
			response().out()<< e.what() << std::endl;
		}
	}
Exemple #13
0
/* Should NOT be called with cs_error held */
KHMEXP void KHMAPI
kherr_pop_context(void)
{
    kherr_context * c;

    EnterCriticalSection(&cs_error);
    c = pop_context();
    if(IS_KHERR_CTX(c)) {
        release_context(c);
    }
    LeaveCriticalSection(&cs_error);
}
Exemple #14
0
static void delete_context_map(void)
{
	struct gccontextmap *curr;

	while (g_map != NULL)
		release_context(g_map);

	while (g_mapvacant != NULL) {
		curr = g_mapvacant;
		g_mapvacant = g_mapvacant->next;
		kfree(curr);
	}
}
Exemple #15
0
/* MUST be called with cs_error held */
static void
release_context(kherr_context * c)
{
    if (IS_KHERR_CTX(c)) {
        c->refcount--;

        {
            kherr_event * e;

            e = QBOTTOM(c);
            if (IS_KHERR_EVENT(e) && !(e->flags & KHERR_RF_COMMIT)) {
                commit_event(c, e);
            }
        }

        if (c->refcount == 0) {
            kherr_context * p;

            if (CTX_USES_OWN_PROGRESS(c)) {
                set_and_notify_progress_change(c, 256, 256);
            }

            p = TPARENT(c);

#ifdef DEBUG
	    kherr_debug_printf(L"Posting KHERR_CTX_END for %p\n", (void *) c);
#endif
            notify_ctx_event(KHERR_CTX_END, c, NULL, NULL, 0);

            if (IS_KHERR_CTX(p)) {
                kherr_event * e;

                e = fold_context(c);
                TDELCHILD(p, c);
                
		if (e) {
                    add_event(p, e);
		    notify_ctx_event(KHERR_CTX_FOLDCHILD, p, NULL, e, 0);
		}

                release_context(p);
            } else {
                LDELETE(&ctx_root_list, c);
            }
            free_context(c);
        }
    }
}
void test_query_string() {
  void* ctx;
  parse_query_string(&ctx, "width=640&height=360&video=bigbunny.ogg");
  const char* width = get_parameter(ctx, "width");
  const char* height = get_parameter(ctx, "height");
  const char* video = get_parameter(ctx, "video");
  if(!strcmp(width,"640")) {
      printf("Querystring width esperado:%s - recebido:%s\n", "640", width);
  }
  if(!strcmp(height,"360")) {
      printf("Querystring height esperado:%s - recebido:%s\n", "360", height);
  }
  if(!strcmp(video,"bigbunny.ogg")) {
      printf("Querystring video esperado:%s - recebido:%s\n", "bigbunny.ogg", video);
  }
  release_context(ctx);
}
Exemple #17
0
static int loadfile(struct sr_input *in, const char *filename)
{
	struct sr_datafeed_packet packet;
	struct sr_datafeed_meta meta;
	struct sr_config *src;
	FILE *file;
	struct context *ctx;
	uint64_t samplerate;

	ctx = in->internal;

	if ((file = fopen(filename, "r")) == NULL)
		return SR_ERR;

	if (!parse_header(file, ctx))
	{
		sr_err("VCD parsing failed");
		fclose(file);
		return SR_ERR;
	}

	/* Send header packet to the session bus. */
	std_session_send_df_header(in->sdi, LOG_PREFIX);

	/* Send metadata about the SR_DF_LOGIC packets to come. */
	packet.type = SR_DF_META;
	packet.payload = &meta;
	samplerate = ctx->samplerate / ctx->downsample;
	src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
	meta.config = g_slist_append(NULL, src);
	sr_session_send(in->sdi, &packet);
	sr_config_free(src);

	/* Parse the contents of the VCD file */
	parse_contents(file, in->sdi, ctx);
	
	/* Send end packet to the session bus. */
	packet.type = SR_DF_END;
	sr_session_send(in->sdi, &packet);

	fclose(file);
	release_context(ctx);
	in->internal = NULL;

	return SR_OK;
}
Exemple #18
0
	void test_gzip()
	{
		std::cout << "- Page Gzip" << std::endl;
		set_context(true);
		cache().clear();
		TEST(request().getenv("HTTP_ACCEPT_ENCODING") == "gzip, deflate");
		cache().fetch_page("test");
		response().out() << "gzip";
		cache().store_page("test");
		TEST(str().substr(0,2)=="\x1f\x8b");
		TEST(gzip_);
		
		set_context(false);
	
		TEST(request().getenv("HTTP_ACCEPT_ENCODING") == "");
		TEST(cache_size() == 1);

		TEST(cache().fetch_page("test") ==false);
		response().out() << "gzip";
		cache().store_page("test");
		TEST(str() == "gzip");
		TEST(!gzip_);

		set_context(false);
		TEST(cache().fetch_page("test"));
		TEST(str()=="gzip");
		TEST(!gzip_);

		set_context(true);
		TEST(cache().fetch_page("test"));
		TEST(str().substr(0,2)=="\x1f\x8b");
		TEST(gzip_);

		set_context(false);
		TEST(cache_size()==2);
		cache().clear();
		TEST(cache_size()==0);
		release_context();
	}
Exemple #19
0
	void test_basic()
	{
		std::cout << "- Page Basic" << std::endl;
		
		set_context(false);
		TEST(cache().has_cache());
		TEST(!cache().fetch_page("test"));
		response().out() << "test";
		cache().add_trigger("x");
		cache().store_page("test");
		TEST(str()=="test");
		
		set_context(false);
		TEST(cache_size()==1);
		TEST(cache().fetch_page("test"));
		TEST(str()=="test");
		
		set_context(false);
		cache().rise("x");
		TEST(cache_size() == 0);
		TEST(!cache().fetch_page("test"));
		cache().add_trigger("x");
		response().out() << "test2";
		cache().reset(); // reset works
		cache().store_page("test",2);
		TEST(str()=="test2");
		set_context(false);
		cache().rise("x");
		TEST(cache_size() == 1);
		TEST(cache().fetch_page("test"));
		TEST(str() == "test2");
		booster::ptime::millisleep(3000);
		set_context(false);
		TEST(cache().fetch_page("test")==false);
		cache().clear();
		release_context();
	}
static DSA_SIG *cswift_dsa_sign(const unsigned char *dgst, int dlen, DSA *dsa)
	{
	SW_CONTEXT_HANDLE hac;
	SW_PARAM sw_param;
	SW_STATUS sw_status;
	SW_LARGENUMBER arg, res;
	unsigned char *ptr;
	BN_CTX *ctx;
	BIGNUM *dsa_p = NULL;
	BIGNUM *dsa_q = NULL;
	BIGNUM *dsa_g = NULL;
	BIGNUM *dsa_key = NULL;
	BIGNUM *result = NULL;
	DSA_SIG *to_return = NULL;
	int acquired = 0;

	if((ctx = BN_CTX_new()) == NULL)
		goto err;
	if(!get_context(&hac))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_UNIT_FAILURE);
		goto err;
		}
	acquired = 1;
	/* Prepare the params */
	BN_CTX_start(ctx);
	dsa_p = BN_CTX_get(ctx);
	dsa_q = BN_CTX_get(ctx);
	dsa_g = BN_CTX_get(ctx);
	dsa_key = BN_CTX_get(ctx);
	result = BN_CTX_get(ctx);
	if(!result)
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_CTX_FULL);
		goto err;
		}
	if(!bn_wexpand(dsa_p, dsa->p->top) ||
			!bn_wexpand(dsa_q, dsa->q->top) ||
			!bn_wexpand(dsa_g, dsa->g->top) ||
			!bn_wexpand(dsa_key, dsa->priv_key->top) ||
			!bn_wexpand(result, dsa->p->top))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
		}
	sw_param.type = SW_ALG_DSA;
	sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p,
				(unsigned char *)dsa_p->d);
	sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d;
	sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q,
				(unsigned char *)dsa_q->d);
	sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d;
	sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g,
				(unsigned char *)dsa_g->d);
	sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d;
	sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->priv_key,
				(unsigned char *)dsa_key->d);
	sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d;
	/* Attach the key params */
	sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
	switch(sw_status)
		{
	case SW_OK:
		break;
	case SW_ERR_INPUT_SIZE:
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_BAD_KEY_SIZE);
		goto err;
	default:
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		}
		goto err;
		}
	/* Prepare the argument and response */
	arg.nbytes = dlen;
	arg.value = (unsigned char *)dgst;
	res.nbytes = BN_num_bytes(dsa->p);
	memset(result->d, 0, res.nbytes);
	res.value = (unsigned char *)result->d;
	/* Perform the operation */
	sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_SIGN, &arg, 1,
		&res, 1);
	if(sw_status != SW_OK)
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_SIGN,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		goto err;
		}
	/* Convert the response */
	ptr = (unsigned char *)result->d;
	if((to_return = DSA_SIG_new()) == NULL)
		goto err;
	to_return->r = BN_bin2bn((unsigned char *)result->d, 20, NULL);
	to_return->s = BN_bin2bn((unsigned char *)result->d + 20, 20, NULL);

err:
	if(acquired)
		release_context(hac);
	if(ctx)
		{
		BN_CTX_end(ctx);
		BN_CTX_free(ctx);
		}
	return to_return;
	}
Exemple #21
0
ns_usb_context::~ns_usb_context(){
  release_context();
}
Exemple #22
0
	~test_app()
	{
		release_context();
	}
Exemple #23
0
static int handleCommands(FILE *fd)
{
    char buf[BUFLEN + 1], commandLine[BUFLEN + 1];
    int rv = EXIT_SUCCESS, i;
    char *token;
    OptionStr optionStr;

    while (fgets (buf, BUFLEN, fd) != NULL) {

	// copy command line for printing it out later
	strncpy (commandLine, buf, BUFLEN);

	token = strtokCheckComment(buf);
	while (token != NULL) {
	    if (token[0] == '#' || strncmp (token, "//", 2) == 0)
		break;

	    // print command line
	    printf ("%s", commandLine);

	    if (strcmp(token, "establish_context") == 0) {
		// Establish context
		rv = establish_context(&cardContext);
		if (rv != OPGP_ERROR_SUCCESS) {
		    printf ("establish_context failed with error 0x%08X\n", rv);
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "release_context") == 0) {
		// Release context
		rv = release_context(cardContext);
		if (rv != OPGP_ERROR_SUCCESS) {
		    printf ("release_context failed with error 0x%08X\n", rv);
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    } else if (strcmp(token, "card_connect") == 0) {
		TCHAR buf[BUFLEN + 1];
		DWORD readerStrLen = BUFLEN;
		// open reader
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (_tcslen(optionStr.reader) == 0) {
			int j=0;
			int k=0;

			// get all readers
		    rv = list_readers (cardContext, buf, &readerStrLen);

			for (j=0; j<(int)readerStrLen;) {
				/* Check for end of readers */
				if (buf[j] == _T('\0'))
					break;
				_tcsncpy(optionStr.reader, buf+j, READERNAMELEN+1);
				if (k == optionStr.readerNumber)
					break;
				k++;
				j+=(int)_tcslen(buf+j)+1;
			}
			optionStr.reader[READERNAMELEN] = _T('\0');

#ifdef DEBUG
		    _tprintf ( _T("* reader name %s\n"), optionStr.reader);
#endif
		}

		rv = card_connect (cardContext, optionStr.reader,
				   &cardInfo, optionStr.protocol);

		if (rv != 0) {
		    _tprintf (_T("card_connect() returns 0x%08X (%s)\n"), rv,
			      stringify_error(rv));
		}

		break;
	    } if (strcmp(token, "open_sc") == 0) {
		// open secure channel
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
			if (gemXpressoPro) {
				rv = GemXpressoPro_create_daughter_keys(cardInfo, optionStr.key,  
								 optionStr.enc_key, optionStr.mac_key, optionStr.kek_key);
				if (rv != 0) {
					_tprintf (_T("GemXpressoPro_create_daughter_keys() returns 0x%08X (%s)\n"),
						rv, stringify_error(rv));
					rv = EXIT_FAILURE;
					goto end;
				}
			}
		    rv = OP201_mutual_authentication(cardInfo,
						     optionStr.enc_key,
						     optionStr.mac_key,
							 optionStr.kek_key,
						     optionStr.keySetVersion,
						     optionStr.keyIndex,
						     optionStr.securityLevel,
						     &securityInfo201);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
			if (optionStr.scp == 0 || optionStr.scpImpl == 0) {
				rv = GP211_get_secure_channel_protocol_details(cardInfo,
					&optionStr.scp,
					&optionStr.scpImpl);
				if (rv != 0) {
					_tprintf (_T("GP211_get_secure_channel_protocol_details() returns 0x%08X (%s)\n"),
						rv, stringify_error(rv));
					rv = EXIT_FAILURE;
					goto end;
				}
			}

		    rv = GP211_mutual_authentication(cardInfo,
						     optionStr.key,
						     optionStr.enc_key,
						     optionStr.mac_key,
						     optionStr.kek_key,
						     optionStr.keySetVersion,
						     optionStr.keyIndex,
						     optionStr.scp,
						     optionStr.scpImpl,
						     optionStr.securityLevel,
						     &securityInfo211);

		}

		if (rv != 0) {
		    _tprintf (_T("mutual_authentication() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    } else if (strcmp(token, "select") == 0) {
		// select instance
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		rv = select_application (cardInfo,
                                         (PBYTE)optionStr.AID, optionStr.AIDLen);
		if (rv != 0) {
		    _tprintf (_T("select_application() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "getdata") == 0) {
		// Get Data
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		// TODO: get data
		break;
	    } else if (strcmp(token, "load") == 0) {
		// Load Applet
		DWORD receiptDataLen = 0;
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    rv = OP201_load(cardInfo, &securityInfo201,
				    NULL, 0,
				    optionStr.file,
				    NULL, &receiptDataLen);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    rv = GP211_load(cardInfo, &securityInfo211,
				    NULL, 0,
				    optionStr.file,
				    NULL, &receiptDataLen);
		}

		if (rv != 0) {
		    _tprintf (_T("load_applet() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    }  else if (strcmp(token, "delete") == 0) {
		// Delete Applet
		OPGP_AID AIDs[1];

		DWORD receiptLen = 10;

		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		memcpy (AIDs[0].AID, optionStr.AID, optionStr.AIDLen);
		AIDs[0].AIDLength = optionStr.AIDLen;

		if (platform_mode == PLATFORM_MODE_OP_201) {
		    OP201_RECEIPT_DATA receipt[10];
		    rv = OP201_delete_application(cardInfo, &securityInfo201,
					      AIDs, 1,
					      (OP201_RECEIPT_DATA *)receipt,
					      &receiptLen);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    GP211_RECEIPT_DATA receipt[10];
		    rv = GP211_delete_application(cardInfo, &securityInfo211,
						  AIDs, 1,
						  (GP211_RECEIPT_DATA *)receipt,
						  &receiptLen);

		}

		if (rv != 0) {
		    _tprintf (_T("delete_applet() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
		}
		break;
	    }

	    else if (strcmp(token, "install") == 0) {
			// One step install
			OPGP_LOAD_FILE_PARAMETERS loadFileParams;
			DWORD receiptDataAvailable = 0;
			DWORD receiptDataLen = 0;
			char installParam[1];
			installParam[0] = 0;

			rv = handleOptions(&optionStr);
			if (rv != EXIT_SUCCESS) {
				goto end;
			}
			rv = read_executable_load_file_parameters(optionStr.file, &loadFileParams);
			if (rv != EXIT_SUCCESS) {
				_tprintf (_T("read_executable_load_file_parameters() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}
			if (optionStr.pkgAIDLen == 0) {
				optionStr.pkgAIDLen = loadFileParams.loadFileAID.AIDLength;
				memcpy(optionStr.pkgAID, loadFileParams.loadFileAID.AID, optionStr.pkgAIDLen);
			}
			if (optionStr.AIDLen == 0) {
				optionStr.AIDLen = loadFileParams.appletAIDs[0].AIDLength;
				memcpy(optionStr.AID, loadFileParams.appletAIDs[0].AID, optionStr.AIDLen);
			}
			if (optionStr.instAIDLen == 0) {
				optionStr.instAIDLen = loadFileParams.appletAIDs[0].AIDLength;
				memcpy(optionStr.instAID, loadFileParams.appletAIDs[0].AID, optionStr.instAIDLen);
			}
			if (optionStr.nvCodeLimit == 0) {
				optionStr.nvCodeLimit = loadFileParams.loadFileSize;
			}
			if (platform_mode == PLATFORM_MODE_OP_201) {
				if (optionStr.sdAIDLen == 0) {
					optionStr.sdAIDLen = sizeof(OP201_CARD_MANAGER_AID);
					memcpy(optionStr.sdAID, OP201_CARD_MANAGER_AID, optionStr.sdAIDLen);
				}
				rv = OP201_install_for_load(cardInfo, &securityInfo201,
							(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
							(PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
						NULL, NULL,
						optionStr.nvCodeLimit,
						0,
						0);
			} else if (platform_mode == PLATFORM_MODE_GP_211) {
				if (optionStr.sdAIDLen == 0) {
					optionStr.sdAIDLen = sizeof(GP211_CARD_MANAGER_AID);
					memcpy(optionStr.sdAID, GP211_CARD_MANAGER_AID, optionStr.sdAIDLen);
				}
				rv = GP211_install_for_load(cardInfo, &securityInfo211,
							(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
							(PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
							NULL, NULL,
							optionStr.nvCodeLimit,
							optionStr.nvDataLimit,
							optionStr.vDataLimit);
			}

			if (rv != 0) {
				_tprintf (_T("install_for_load() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}
			if (platform_mode == PLATFORM_MODE_OP_201) {
				rv = OP201_load(cardInfo, &securityInfo201,
						NULL, 0,
						optionStr.file,
						NULL, &receiptDataLen);
			} else if (platform_mode == PLATFORM_MODE_GP_211) {
				rv = GP211_load(cardInfo, &securityInfo211,
						NULL, 0,
						optionStr.file,
						NULL, &receiptDataLen);
			}

			if (rv != 0) {
				_tprintf (_T("load_applet() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}

			if (platform_mode == PLATFORM_MODE_OP_201) {
				OP201_RECEIPT_DATA receipt;
				rv = OP201_install_for_install_and_make_selectable(
							cardInfo, &securityInfo201,
						(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
						(PBYTE)optionStr.AID, optionStr.AIDLen,
						(PBYTE)optionStr.instAID, optionStr.instAIDLen,
						optionStr.privilege,
						optionStr.vDataLimit,
						optionStr.nvDataLimit,
											(PBYTE)optionStr.instParam,
						optionStr.instParamLen,
						NULL, // No install token
						&receipt,
						&receiptDataAvailable);
			} else if (platform_mode == PLATFORM_MODE_GP_211) {
				GP211_RECEIPT_DATA receipt;

				rv = GP211_install_for_install_and_make_selectable(
						cardInfo, &securityInfo211,
						(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
						(PBYTE)optionStr.AID, optionStr.AIDLen,
						(PBYTE)optionStr.instAID, optionStr.instAIDLen,
						optionStr.privilege,
						optionStr.vDataLimit,
						optionStr.nvDataLimit,
											(PBYTE)optionStr.instParam,
						optionStr.instParamLen,
						NULL, // No install token
						&receipt,
						&receiptDataAvailable);
			}

			if (rv != 0) {
				_tprintf (_T("install_for_install_and_make_selectable() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}
			break;
		}
	    else if (strcmp(token, "install_for_load") == 0) {
		// Install for Load
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
			if (optionStr.sdAIDLen == 0) {
				optionStr.sdAIDLen = sizeof(OP201_CARD_MANAGER_AID);
				memcpy(optionStr.sdAID, OP201_CARD_MANAGER_AID, optionStr.sdAIDLen);
			}
			rv = OP201_install_for_load(cardInfo, &securityInfo201,
                        (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                        (PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
				      NULL, NULL,
				      optionStr.nvCodeLimit,
				      optionStr.nvDataLimit,
				      optionStr.vDataLimit);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
			if (optionStr.sdAIDLen == 0) {
				optionStr.sdAIDLen = sizeof(GP211_CARD_MANAGER_AID);
				memcpy(optionStr.sdAID, GP211_CARD_MANAGER_AID, optionStr.sdAIDLen);
			}
			rv = GP211_install_for_load(cardInfo, &securityInfo211,
                        (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                        (PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
					    NULL, NULL,
					    optionStr.nvCodeLimit,
					    optionStr.nvDataLimit,
					    optionStr.vDataLimit);
		}

		if (rv != 0) {
		    _tprintf (_T("install_for_load() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "install_for_install") == 0) {


		DWORD receiptDataAvailable = 0;
		char installParam[1];
		installParam[0] = 0;

		// Install for Install
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    OP201_RECEIPT_DATA receipt;
		    rv = OP201_install_for_install_and_make_selectable(
				         cardInfo, &securityInfo201,
                    (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                    (PBYTE)optionStr.AID, optionStr.AIDLen,
                    (PBYTE)optionStr.instAID, optionStr.instAIDLen,
					 optionStr.privilege,
					 optionStr.vDataLimit,
					 optionStr.nvDataLimit,
                                         (PBYTE)optionStr.instParam,
					 optionStr.instParamLen,
					 NULL, // No install token
					 &receipt,
					 &receiptDataAvailable);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    GP211_RECEIPT_DATA receipt;

		    rv = GP211_install_for_install_and_make_selectable(
					cardInfo, &securityInfo211,
                    (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                    (PBYTE)optionStr.AID, optionStr.AIDLen,
                    (PBYTE)optionStr.instAID, optionStr.instAIDLen,
					optionStr.privilege,
					optionStr.vDataLimit,
					optionStr.nvDataLimit,
                                        (PBYTE)optionStr.instParam,
					optionStr.instParamLen,
					NULL, // No install token
					&receipt,
					&receiptDataAvailable);
		}

		if (rv != 0) {
		    _tprintf (_T("install_for_install_and_make_selectable() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    } else if (strcmp(token, "card_disconnect") == 0) {
		// disconnect card
		card_disconnect(cardInfo);

		break;
	    } else if (strcmp(token, "put_sc_key") == 0) {
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    rv = OP201_put_secure_channel_keys(cardInfo, &securityInfo201,
						       optionStr.keySetVersion,
						       optionStr.newKeySetVersion,
						       optionStr.enc_key,
						       optionStr.mac_key,
						       optionStr.kek_key,
						       optionStr.current_kek);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    rv = GP211_put_secure_channel_keys(cardInfo,
						       &securityInfo211,
						       optionStr.keySetVersion,
						       optionStr.newKeySetVersion,
						       NULL,
						       optionStr.enc_key,
						       optionStr.mac_key,
						       optionStr.kek_key);
		}

		if (rv != 0) {
		    _tprintf (_T("put_secure_channel_keys() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "get_status") == 0) {
#define NUM_APPLICATIONS 64
		DWORD numData = NUM_APPLICATIONS;

		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    OP201_APPLICATION_DATA data[NUM_APPLICATIONS];
		    rv = OP201_get_status(cardInfo, &securityInfo201,
				      optionStr.element,
				      data,
				      &numData);

		    if (rv != 0) {
			_tprintf (_T("OP201_get_status() returns 0x%08X (%s)\n"),
				  rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
		    }
#ifdef DEBUG
		    printf ("OP201_get_status() returned %d items\n", numData);
#endif
		    printf ("\nList of applets (AID state privileges)\n");
		    for (i=0; i<(int)numData; i++) {
			int j;

			for (j=0; j<data[i].AIDLength; j++) {
			    printf ("%02x", data[i].AID[j]);
			}

			printf ("\t%x", data[i].lifeCycleState);
			printf ("\t%x\n", data[i].privileges);
		    }
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
                  GP211_APPLICATION_DATA appData[NUM_APPLICATIONS];
                  GP211_EXECUTABLE_MODULES_DATA execData[NUM_APPLICATIONS];
		    rv = GP211_get_status(cardInfo, &securityInfo211,
                                          optionStr.element,
					  appData,
					  execData,
					  &numData);

		    if (rv != 0) {
				_tprintf (_T("GP211_get_status() returns 0x%08X (%s)\n"),
				  rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
		    }
#ifdef DEBUG
		    printf ("GP211_get_status() returned %d items\n", numData);
#endif
		    printf ("\nList of applets (AID state privileges)\n");
		    for (i=0; i<(int)numData; i++) {
			int j;

			for (j=0; j<appData[i].AIDLength; j++) {
			    printf ("%02x", appData[i].AID[j]);
			}

			printf ("\t%x", appData[i].lifeCycleState);
			printf ("\t%x\n", appData[i].privileges);
		    }
		}
		if (rv != 0) {
		    _tprintf (_T("get_status() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}


		break;
	    } else if (strcmp(token, "send_apdu") == 0) {
		unsigned char recvAPDU[257];
                DWORD recvAPDULen = 257;
                int i;
		// Install for Load
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		printf ("Send APDU: ");
		for (i=0; i<optionStr.APDULen; i++)
		    printf ("%02X ", optionStr.APDU[i] & 0xFF);
		printf ("\n");

		if (platform_mode == PLATFORM_MODE_OP_201) {
		    rv = OP201_send_APDU(cardInfo,
				     (optionStr.secureChannel == 0 ? NULL : &securityInfo201),
				     (PBYTE)(optionStr.APDU), optionStr.APDULen,
				     recvAPDU, &recvAPDULen);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    rv = GP211_send_APDU(cardInfo,
				     (optionStr.secureChannel == 0 ? NULL : &securityInfo211),
					 (PBYTE)(optionStr.APDU), optionStr.APDULen,
				     recvAPDU, &recvAPDULen);
		}
		if (rv != 0) {
		    _tprintf (_T("send_APDU() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		printf ("Recv APDU: ");
		for (i=0; i<(int)recvAPDULen; i++)
		    printf ("%02x ", recvAPDU[i]);
		printf ("\n");

		break;
	    } else if (strcmp(token, "mode_201") == 0) {
			platform_mode = PLATFORM_MODE_OP_201;
	    } else if (strcmp(token, "mode_211") == 0) {
			platform_mode = PLATFORM_MODE_GP_211;
	    } else if (strcmp(token, "enable_trace") == 0) {
			enableTraceMode(OPGP_TRACE_MODE_ENABLE, NULL);
	    } else if (strcmp(token, "gemXpressoPro") == 0) {
			gemXpressoPro = 1;
	    }

	    else {
			printf ("Unknown command %s\n", token);
			rv = EXIT_FAILURE;
			goto end;
	    }

	    token = strtokCheckComment(NULL);
	}
    }
end:
    return rv;
}
Exemple #24
0
 void stop_holding_blocks()
 { release_context(); }
Exemple #25
0
static int init(struct sr_input *in, const char *filename)
{
	struct sr_probe *probe;
	int num_probes, i;
	char name[SR_MAX_PROBENAME_LEN + 1];
	char *param;
	struct context *ctx;

	(void)filename;

	if (!(ctx = g_try_malloc0(sizeof(*ctx)))) {
		sr_err("Input format context malloc failed.");
		return SR_ERR_MALLOC;
	}

	num_probes = DEFAULT_NUM_PROBES;
	ctx->samplerate = 0;
	ctx->downsample = 1;
	ctx->skip = -1;

	if (in->param) {
		param = g_hash_table_lookup(in->param, "numprobes");
		if (param) {
			num_probes = strtoul(param, NULL, 10);
			if (num_probes < 1)
			{
				release_context(ctx);
				return SR_ERR;
			}
		}
		
		param = g_hash_table_lookup(in->param, "downsample");
		if (param) {
			ctx->downsample = strtoul(param, NULL, 10);
			if (ctx->downsample < 1)
			{
				ctx->downsample = 1;
			}
		}
		
		param = g_hash_table_lookup(in->param, "compress");
		if (param) {
			ctx->compress = strtoul(param, NULL, 10);
		}
		
		param = g_hash_table_lookup(in->param, "skip");
		if (param) {
			ctx->skip = strtoul(param, NULL, 10) / ctx->downsample;
		}
	}
	
	/* Maximum number of probes to parse from the VCD */
	ctx->maxprobes = num_probes;

	/* Create a virtual device. */
	in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
	in->internal = ctx;

	for (i = 0; i < num_probes; i++) {
		snprintf(name, SR_MAX_PROBENAME_LEN, "%d", i);
		
		if (!(probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, name)))
		{
			release_context(ctx);
			return SR_ERR;
		}
			
		in->sdi->probes = g_slist_append(in->sdi->probes, probe);
	}

	return SR_OK;
}
Exemple #26
0
int handleCommands(FILE *fd)
{
    BYTE buf[BUFLEN + 1];
    int rv = 0, i;
    char *token;
    OptionStr optionStr;

    while (fgets (buf, BUFLEN, fd) != NULL) {	
	token = strtokCheckComment(buf);
	while (token != NULL) {
	    if (token[0] == '#' || strncmp (token, "//", 2) == 0)
		break;
	    if (strcmp(token, "establish_context") == 0) {
		// Establish context
		rv = establish_context(&cardContext);
		if (rv != OPSP_ERROR_SUCCESS) {
		    printf ("establish_context failed with error %d\n", rv);
		    exit (1);
		}
		break;
	    } else if (strcmp(token, "release_context") == 0) {
		// Release context
		rv = release_context(cardContext);
		if (rv != OPSP_ERROR_SUCCESS) {
		    printf ("release_context failed with error %d\n", rv);
		    exit (1);
		}

		break;
	    } else if (strcmp(token, "card_connect") == 0) {
		TCHAR buf[BUFLEN + 1];
		DWORD readerStrLen = BUFLEN;
		// open reader
		handleOptions(&optionStr);
#ifdef DEBUG
		printf ("optionStr.reader %d\n", optionStr.reader);
#endif
		if (optionStr.reader == NULL) {	
		    // get the first reader
		    rv = list_readers (cardContext, buf, &readerStrLen);

		    optionStr.reader = buf;
#ifdef DEBUG
		    _tprintf ( _T("reader name %s\n"), optionStr.reader);
#endif
		}
		
		rv = card_connect (cardContext, optionStr.reader,
				   &cardHandle, optionStr.protocol);

		if (rv != 0) {
		    _tprintf (_T("card_connect() returns %d (%s)\n"), rv,
			      stringify_error(rv));
		}

		rv = get_card_status (cardHandle, &cardInfo);
		if (rv != 0) {
		    _tprintf (_T("get_card_status() returns %d (%s)\n"), rv,
			      stringify_error(rv));
		    exit (1);
		}
		
		break;
	    } if (strcmp(token, "open_sc") == 0) {
		// open secure channel
		handleOptions(&optionStr);
		/*for (i=0; i<TDES_KEY_LEN; i++) {
		  printf ("%02x ", optionStr.key[i]);
		  }*/
		rv = mutual_authentication(cardHandle,
					   optionStr.enc_key,
					   optionStr.mac_key,
					   optionStr.keySetVersion,
					   optionStr.keyIndex,
					   cardInfo,
					   optionStr.securityLevel,
					   &securityInfo);
		if (rv != 0) {
		    _tprintf (_T("mutual_authentication() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}
					       
		break;
	    } else if (strcmp(token, "select") == 0) {
		// select instance
		handleOptions(&optionStr);
		rv = select_application (cardHandle, cardInfo,
					 optionStr.AID, optionStr.AIDLen);
		if (rv != 0) {
		    _tprintf (_T("select_application() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}
		break;
	    } else if (strcmp(token, "getdata") == 0) {
		// Get Data
		handleOptions(&optionStr);
		// TODO: get data
		break;
	    } else if (strcmp(token, "load") == 0) {
		// Load Applet
		DWORD receiptDataLen = 0;
		handleOptions(&optionStr);

		rv = load_applet(cardHandle, &securityInfo, cardInfo,
				 NULL, 0, optionStr.file,
				 NULL, &receiptDataLen);
		if (rv != 0) {
		    _tprintf (_T("load_applet() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}

		break;
	    }  else if (strcmp(token, "delete") == 0) {
		// Delete Applet
		OPSP_AID AIDs[1];
		OPSP_RECEIPT_DATA receipt[10];
		DWORD receiptLen = 10;
		    
		handleOptions(&optionStr);
		memcpy (AIDs[0].AID, optionStr.AID, optionStr.AIDLen);
		AIDs[0].AIDLength = optionStr.AIDLen;

		rv = delete_applet(cardHandle, &securityInfo,
				   cardInfo,
				   AIDs, 1,
                                   (OPSP_RECEIPT_DATA **)&receipt, &receiptLen);

		if (rv != 0) {
		    _tprintf (_T("delete_applet() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		}
		break;
	    }
    
	    else if (strcmp(token, "install_for_load") == 0) {
		// Install for Load
		handleOptions(&optionStr);

		rv = install_for_load(cardHandle, &securityInfo,
				      cardInfo,
				      optionStr.AID, optionStr.AIDLen,
				      optionStr.sdAID, optionStr.sdAIDLen,
				      NULL, NULL,
				      optionStr.nvCodeLimit,
				      optionStr.nvDataLimit,
				      optionStr.vDataLimit);
				      
		if (rv != 0) {
		    _tprintf (_T("install_for_load() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}
		break;
	    } else if (strcmp(token, "install_for_install") == 0) {
		OPSP_RECEIPT_DATA receipt;
		DWORD receiptDataAvailable = 0;
		char installParam[1];
		installParam[0] = 0;

		// Install for Install
		handleOptions(&optionStr);
		
		rv = install_for_install_and_make_selectable(
					 cardHandle, &securityInfo,
					 cardInfo,
					 optionStr.pkgAID, optionStr.pkgAIDLen,
					 optionStr.AID, optionStr.AIDLen,
					 optionStr.instAID, optionStr.instAIDLen,
					 OPSP_APPLICATION_PRIVILEGE_PIN_CHANGE_PRIVILEGE, // 
					 optionStr.vDataLimit,
					 optionStr.nvDataLimit,
					 optionStr.instParam,
					 optionStr.instParamLen, 
					 NULL, // No install token
					 &receipt,
					 &receiptDataAvailable);

		if (rv != 0) {
		    _tprintf (_T("install_for_install_and_make_selectable() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}
		break;
	    } else if (strcmp(token, "card_disconnect") == 0) {
		// disconnect card
		card_disconnect(cardHandle);

		break;
	    } else if (strcmp(token, "put_sc_key") == 0) {
		handleOptions(&optionStr);

		rv = put_secure_channel_keys(cardHandle, &securityInfo,
					     cardInfo,
					     optionStr.keySetVersion,
					     optionStr.newKeySetVersion,
					     optionStr.enc_key,
					     optionStr.mac_key,
					     optionStr.kek_key,
					     optionStr.current_kek);
		
		if (rv != 0) {
		    _tprintf (_T("put_secure_channel_keys() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}
		break;
	    } else if (strcmp(token, "get_status") == 0) {
#define NUM_APPLICATIONS 64
		OPSP_APPLICATION_DATA data[NUM_APPLICATIONS];
		DWORD numData = NUM_APPLICATIONS;

		handleOptions(&optionStr);
		
		rv = get_status(cardHandle, &securityInfo, cardInfo,
				optionStr.element,
				data,
				&numData);
		if (rv != 0) {
		    _tprintf (_T("get_status() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}
#ifdef DEBUG
		printf ("get_status() returned %d items\n", numData);
#endif
		printf ("\nList of applets (AID state privileges)\n");
		for (i=0; i<numData; i++) {
		    int j;
		    
		    for (j=0; j<data[i].AIDLength; j++) {
			printf ("%02x", data[i].AID[j]);
		    }

		    printf ("\t%x", data[i].lifeCycleState);
		    printf ("\t%x\n", data[i].privileges);
		}
		
		break;
	    } else if (strcmp(token, "send_apdu") == 0) {
		unsigned char recvAPDU[257];
		int recvAPDULen = 257, i;
		// Install for Load
		handleOptions(&optionStr);

		printf ("Send APDU: ");
		for (i=0; i<optionStr.APDULen; i++)
		    printf ("%02x ", optionStr.APDU[i]);
		printf ("\n");
		
		rv = send_APDU(cardHandle, 
			       optionStr.APDU, optionStr.APDULen, 
			       recvAPDU, &recvAPDULen,
			       cardInfo,
			       (optionStr.secureChannel == 0 ? NULL : &securityInfo));
		if (rv != 0) {
		    _tprintf (_T("send_APDU() returns %d (%s)\n"),
			      rv, stringify_error(rv));
		    exit (1);
		}

		printf ("Recv APDU: ");
		for (i=0; i<recvAPDULen; i++)
		    printf ("%02x ", recvAPDU[i]);
		printf ("\n");
		
		break;
	    } else {
		printf ("Unknown command %s\n", token);
		exit (1);
	    }

	    token = strtokCheckComment(NULL);
	}
    }

    return rv;
}
static int cswift_dsa_verify(const unsigned char *dgst, int dgst_len,
				DSA_SIG *sig, DSA *dsa)
	{
	SW_CONTEXT_HANDLE hac;
	SW_PARAM sw_param;
	SW_STATUS sw_status;
	SW_LARGENUMBER arg[2], res;
	unsigned long sig_result;
	BN_CTX *ctx;
	BIGNUM *dsa_p = NULL;
	BIGNUM *dsa_q = NULL;
	BIGNUM *dsa_g = NULL;
	BIGNUM *dsa_key = NULL;
	BIGNUM *argument = NULL;
	int to_return = -1;
	int acquired = 0;

	if((ctx = BN_CTX_new()) == NULL)
		goto err;
	if(!get_context(&hac))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_UNIT_FAILURE);
		goto err;
		}
	acquired = 1;
	/* Prepare the params */
	BN_CTX_start(ctx);
	dsa_p = BN_CTX_get(ctx);
	dsa_q = BN_CTX_get(ctx);
	dsa_g = BN_CTX_get(ctx);
	dsa_key = BN_CTX_get(ctx);
	argument = BN_CTX_get(ctx);
	if(!argument)
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_CTX_FULL);
		goto err;
		}
	if(!bn_wexpand(dsa_p, dsa->p->top) ||
			!bn_wexpand(dsa_q, dsa->q->top) ||
			!bn_wexpand(dsa_g, dsa->g->top) ||
			!bn_wexpand(dsa_key, dsa->pub_key->top) ||
			!bn_wexpand(argument, 40))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
		}
	sw_param.type = SW_ALG_DSA;
	sw_param.up.dsa.p.nbytes = BN_bn2bin(dsa->p,
				(unsigned char *)dsa_p->d);
	sw_param.up.dsa.p.value = (unsigned char *)dsa_p->d;
	sw_param.up.dsa.q.nbytes = BN_bn2bin(dsa->q,
				(unsigned char *)dsa_q->d);
	sw_param.up.dsa.q.value = (unsigned char *)dsa_q->d;
	sw_param.up.dsa.g.nbytes = BN_bn2bin(dsa->g,
				(unsigned char *)dsa_g->d);
	sw_param.up.dsa.g.value = (unsigned char *)dsa_g->d;
	sw_param.up.dsa.key.nbytes = BN_bn2bin(dsa->pub_key,
				(unsigned char *)dsa_key->d);
	sw_param.up.dsa.key.value = (unsigned char *)dsa_key->d;
	/* Attach the key params */
	sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
	switch(sw_status)
		{
	case SW_OK:
		break;
	case SW_ERR_INPUT_SIZE:
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_BAD_KEY_SIZE);
		goto err;
	default:
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		}
		goto err;
		}
	/* Prepare the argument and response */
	arg[0].nbytes = dgst_len;
	arg[0].value = (unsigned char *)dgst;
	arg[1].nbytes = 40;
	arg[1].value = (unsigned char *)argument->d;
	memset(arg[1].value, 0, 40);
	BN_bn2bin(sig->r, arg[1].value + 20 - BN_num_bytes(sig->r));
	BN_bn2bin(sig->s, arg[1].value + 40 - BN_num_bytes(sig->s));
	res.nbytes = 4; /* unsigned long */
	res.value = (unsigned char *)(&sig_result);
	/* Perform the operation */
	sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_DSS_VERIFY, arg, 2,
		&res, 1);
	if(sw_status != SW_OK)
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_DSA_VERIFY,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		goto err;
		}
	/* Convert the response */
	to_return = ((sig_result == 0) ? 0 : 1);

err:
	if(acquired)
		release_context(hac);
	if(ctx)
		{
		BN_CTX_end(ctx);
		BN_CTX_free(ctx);
		}
	return to_return;
	}
/* Un petit mod_exp chinois */
static int cswift_mod_exp_crt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
			const BIGNUM *q, const BIGNUM *dmp1,
			const BIGNUM *dmq1, const BIGNUM *iqmp, BN_CTX *ctx)
	{
	SW_STATUS sw_status;
	SW_LARGENUMBER arg, res;
	SW_PARAM sw_param;
	SW_CONTEXT_HANDLE hac;
	BIGNUM *result = NULL;
	BIGNUM *argument = NULL;
	int to_return = 0; /* expect failure */
	int acquired = 0;

	sw_param.up.crt.p.value = NULL;
	sw_param.up.crt.q.value = NULL;
	sw_param.up.crt.dmp1.value = NULL;
	sw_param.up.crt.dmq1.value = NULL;
	sw_param.up.crt.iqmp.value = NULL;
 
	if(!get_context(&hac))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_UNIT_FAILURE);
		goto err;
		}
	acquired = 1;

	/* Prepare the params */
	argument = BN_new();
	result = BN_new();
	if(!result || !argument)
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_CTX_FULL);
		goto err;
		}


	sw_param.type = SW_ALG_CRT;
	/************************************************************************/
	/* 04/02/2003                                                           */
	/* Modified by Frederic Giudicelli (deny-all.com) to overcome the       */
	/* limitation of cswift with values not a multiple of 32                */
	/************************************************************************/
	if(!cswift_bn_32copy(&sw_param.up.crt.p, p))
	{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
	}
	if(!cswift_bn_32copy(&sw_param.up.crt.q, q))
	{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
	}
	if(!cswift_bn_32copy(&sw_param.up.crt.dmp1, dmp1))
	{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
	}
	if(!cswift_bn_32copy(&sw_param.up.crt.dmq1, dmq1))
	{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
	}
	if(!cswift_bn_32copy(&sw_param.up.crt.iqmp, iqmp))
	{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
	}
	if(	!bn_wexpand(argument, a->top) ||
			!bn_wexpand(result, p->top + q->top))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
		}

	/* Attach the key params */
	sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
	switch(sw_status)
		{
	case SW_OK:
		break;
	case SW_ERR_INPUT_SIZE:
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_BAD_KEY_SIZE);
		goto err;
	default:
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		}
		goto err;
		}
	/* Prepare the argument and response */
	arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d);
	arg.value = (unsigned char *)argument->d;
	res.nbytes = 2 * BN_num_bytes(p);
	memset(result->d, 0, res.nbytes);
	res.value = (unsigned char *)result->d;
	/* Perform the operation */
	if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP_CRT, &arg, 1,
		&res, 1)) != SW_OK)
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP_CRT,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		goto err;
		}
	/* Convert the response */
	BN_bin2bn((unsigned char *)result->d, res.nbytes, r);
	to_return = 1;
err:
	if(sw_param.up.crt.p.value)
		OPENSSL_free(sw_param.up.crt.p.value);
	if(sw_param.up.crt.q.value)
		OPENSSL_free(sw_param.up.crt.q.value);
	if(sw_param.up.crt.dmp1.value)
		OPENSSL_free(sw_param.up.crt.dmp1.value);
	if(sw_param.up.crt.dmq1.value)
		OPENSSL_free(sw_param.up.crt.dmq1.value);
	if(sw_param.up.crt.iqmp.value)
		OPENSSL_free(sw_param.up.crt.iqmp.value);
	if(result)
		BN_free(result);
	if(argument)
		BN_free(argument);
	if(acquired)
		release_context(hac);
	return to_return;
	}
/* Un petit mod_exp */
static int cswift_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
			const BIGNUM *m, BN_CTX *ctx)
	{
	/* I need somewhere to store temporary serialised values for
	 * use with the CryptoSwift API calls. A neat cheat - I'll use
	 * BIGNUMs from the BN_CTX but access their arrays directly as
	 * byte arrays <grin>. This way I don't have to clean anything
	 * up. */
	BIGNUM *modulus;
	BIGNUM *exponent;
	BIGNUM *argument;
	BIGNUM *result;
	SW_STATUS sw_status;
	SW_LARGENUMBER arg, res;
	SW_PARAM sw_param;
	SW_CONTEXT_HANDLE hac;
	int to_return, acquired;
 
	modulus = exponent = argument = result = NULL;
	to_return = 0; /* expect failure */
	acquired = 0;
 
	if(!get_context(&hac))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_UNIT_FAILURE);
		goto err;
		}
	acquired = 1;
	/* Prepare the params */
	BN_CTX_start(ctx);
	modulus = BN_CTX_get(ctx);
	exponent = BN_CTX_get(ctx);
	argument = BN_CTX_get(ctx);
	result = BN_CTX_get(ctx);
	if(!result)
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_CTX_FULL);
		goto err;
		}
	if(!bn_wexpand(modulus, m->top) || !bn_wexpand(exponent, p->top) ||
		!bn_wexpand(argument, a->top) || !bn_wexpand(result, m->top))
		{
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BN_EXPAND_FAIL);
		goto err;
		}
	sw_param.type = SW_ALG_EXP;
	sw_param.up.exp.modulus.nbytes = BN_bn2bin(m,
		(unsigned char *)modulus->d);
	sw_param.up.exp.modulus.value = (unsigned char *)modulus->d;
	sw_param.up.exp.exponent.nbytes = BN_bn2bin(p,
		(unsigned char *)exponent->d);
	sw_param.up.exp.exponent.value = (unsigned char *)exponent->d;
	/* Attach the key params */
	sw_status = p_CSwift_AttachKeyParam(hac, &sw_param);
	switch(sw_status)
		{
	case SW_OK:
		break;
	case SW_ERR_INPUT_SIZE:
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_BAD_KEY_SIZE);
		goto err;
	default:
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		}
		goto err;
		}
	/* Prepare the argument and response */
	arg.nbytes = BN_bn2bin(a, (unsigned char *)argument->d);
	arg.value = (unsigned char *)argument->d;
	res.nbytes = BN_num_bytes(m);
	memset(result->d, 0, res.nbytes);
	res.value = (unsigned char *)result->d;
	/* Perform the operation */
	if((sw_status = p_CSwift_SimpleRequest(hac, SW_CMD_MODEXP, &arg, 1,
		&res, 1)) != SW_OK)
		{
		char tmpbuf[DECIMAL_SIZE(sw_status)+1];
		CSWIFTerr(CSWIFT_F_CSWIFT_MOD_EXP,CSWIFT_R_REQUEST_FAILED);
		sprintf(tmpbuf, "%ld", sw_status);
		ERR_add_error_data(2, "CryptoSwift error number is ",tmpbuf);
		goto err;
		}
	/* Convert the response */
	BN_bin2bn((unsigned char *)result->d, res.nbytes, r);
	to_return = 1;
err:
	if(acquired)
		release_context(hac);
	BN_CTX_end(ctx);
	return to_return;
	}
/* Random bytes are good */
static int cswift_rand_bytes(unsigned char *buf, int num)
{
	SW_CONTEXT_HANDLE hac;
	SW_STATUS swrc;
	SW_LARGENUMBER largenum;
	int acquired = 0;
	int to_return = 0; /* assume failure */
	unsigned char buf32[1024];


	if (!get_context(&hac))
	{
		CSWIFTerr(CSWIFT_F_CSWIFT_RAND_BYTES, CSWIFT_R_UNIT_FAILURE);
		goto err;
	}
	acquired = 1;

	/************************************************************************/
	/* 04/02/2003                                                           */
	/* Modified by Frederic Giudicelli (deny-all.com) to overcome the       */
	/* limitation of cswift with values not a multiple of 32                */
	/************************************************************************/

	while(num >= (int)sizeof(buf32))
	{
		largenum.value = buf;
		largenum.nbytes = sizeof(buf32);
		/* tell CryptoSwift how many bytes we want and where we want it.
		 * Note: - CryptoSwift cannot do more than 4096 bytes at a time.
		 *       - CryptoSwift can only do multiple of 32-bits. */
		swrc = p_CSwift_SimpleRequest(hac, SW_CMD_RAND, NULL, 0, &largenum, 1);
		if (swrc != SW_OK)
		{
			char tmpbuf[20];
			CSWIFTerr(CSWIFT_F_CSWIFT_RAND_BYTES, CSWIFT_R_REQUEST_FAILED);
			sprintf(tmpbuf, "%ld", swrc);
			ERR_add_error_data(2, "CryptoSwift error number is ", tmpbuf);
			goto err;
		}
		buf += sizeof(buf32);
		num -= sizeof(buf32);
	}
	if(num)
	{
		largenum.nbytes = sizeof(buf32);
		largenum.value = buf32;
		swrc = p_CSwift_SimpleRequest(hac, SW_CMD_RAND, NULL, 0, &largenum, 1);
		if (swrc != SW_OK)
		{
			char tmpbuf[20];
			CSWIFTerr(CSWIFT_F_CSWIFT_CTRL, CSWIFT_R_REQUEST_FAILED);
			sprintf(tmpbuf, "%ld", swrc);
			ERR_add_error_data(2, "CryptoSwift error number is ", tmpbuf);
			goto err;
		}
		memcpy(buf, largenum.value, num);
	}

	to_return = 1;  /* success */
err:
	if (acquired)
		release_context(hac);

	return to_return;
}