Example #1
0
//TODO: error checking
message_handler * new_message_handler(){
    message_handler * ret = malloc(sizeof(message_handler));
    list_init(&(ret->handlers));
    list_attributes_seeker(&(ret->handlers), &msgtypeseek)
    ret->default_handler = NULL; //TODOL perhaps we want to make a default handler?
    return ret;
}
Example #2
0
CK_RV create_slot(sc_reader_t *reader)
{
	struct sc_pkcs11_slot *slot;

	if (list_size(&virtual_slots) >= sc_pkcs11_conf.max_virtual_slots)
		return CKR_FUNCTION_FAILED;

	slot = (struct sc_pkcs11_slot *)calloc(1, sizeof(struct sc_pkcs11_slot));
	if (!slot)
		return CKR_HOST_MEMORY;

	list_append(&virtual_slots, slot);
	slot->login_user = -1;
	slot->id = (CK_SLOT_ID) list_locate(&virtual_slots, slot);
	sc_debug(context, SC_LOG_DEBUG_NORMAL, "Creating slot with id 0x%lx", slot->id);
	
	list_init(&slot->objects);
	list_attributes_seeker(&slot->objects, object_list_seeker);

	init_slot_info(&slot->slot_info);
	if (reader != NULL) {
		slot->reader = reader;
		strcpy_bp(slot->slot_info.slotDescription, reader->name, 64);
	}
	return CKR_OK;
}
Example #3
0
LONG ContextsInitialize(int customMaxThreadCounter,
	int customMaxThreadCardHandles)
{
	int lrv = 0;

	if (customMaxThreadCounter != 0)
		contextMaxThreadCounter = customMaxThreadCounter;

	if (customMaxThreadCardHandles != 0)
		contextMaxCardHandles = customMaxThreadCardHandles;

	lrv = list_init(&contextsList);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL, "list_init failed with return value: %d", lrv);
		return -1;
	}
	lrv = list_attributes_seeker(& contextsList, contextsListhContext_seeker);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL,
			"list_attributes_seeker failed with return value: %d", lrv);
		return -1;
	}

	(void)pthread_mutex_init(&contextsList_lock, NULL);

	return 1;
}
Example #4
0
list_t* list_create()
{
	list_t* list = malloc(sizeof(list_t));
	list_init(list);
	list_attributes_copy(list, &lconv_entry_meter, 1);
	list_attributes_comparator(list, &lconv_entry_comparator);
	list_attributes_seeker(list, &lconv_entry_seeker);
	return list;
}
Example #5
0
void *service_single_client(void *args) {
	
	workerArgs *wa;
	int socket;
	chirc_server *ourserver;
    char *clientname;
    list_t userchans;
    person client;
    client.nick[0] = '\0';
    client.user[0] = '\0';
    client.fullname[0] = '\0';
    client.mode[0] = '\0';
    pthread_mutex_init(&(client.c_lock), NULL);
    
    //unpack arguments
	wa = (workerArgs*) args;
	socket = wa->socket;
	ourserver = wa->server;
    
    //set up client struct
    list_init(&userchans);
    if(list_attributes_seeker(&userchans, fun_seek) == -1){
        perror("list fail");
        exit(-1);
    }
    if(list_attributes_comparator(&userchans, fun_compare) == -1){
        perror("list fail");
        exit(-1);
    }
    clientname = wa->clientname;
    client.clientSocket = socket;
    client.address = clientname;
    client.my_chans = &userchans;
    client.tid = pthread_self();
    
    free(wa);

    //add client to list
    pthread_mutex_lock(&lock);
    list_append(ourserver->userlist, &client);
    pthread_mutex_unlock(&lock);

	pthread_detach(pthread_self());

    //actually get messages
	parse_message(socket, ourserver);
	
	pthread_mutex_destroy(&(client.c_lock));

	close(socket);
	pthread_exit(NULL);
}
Example #6
0
list_t* list_clone(list_t* original)
{
	list_t* list = malloc(sizeof(list_t));
	list_init(list);
	list_attributes_copy(list, &lconv_entry_meter, 1);
	list_attributes_comparator(list, &lconv_entry_comparator);
	list_attributes_seeker(list, &lconv_entry_seeker);
	list_iterator_start(original);
	while (list_iterator_hasnext(original))
		list_append(list, list_iterator_next(original));
	list_iterator_stop(original);
	return list;
}
Example #7
0
File: slot.c Project: llogar/OpenSC
CK_RV create_slot(sc_reader_t *reader)
{
	/* find unused virtual hotplug slots */
	struct sc_pkcs11_slot *slot = reader_get_slot(NULL);

	/* create a new slot if no empty slot is available */
	if (!slot) {
		if (list_size(&virtual_slots) >= sc_pkcs11_conf.max_virtual_slots)
			return CKR_FUNCTION_FAILED;

		slot = (struct sc_pkcs11_slot *)calloc(1, sizeof(struct sc_pkcs11_slot));
		if (!slot)
			return CKR_HOST_MEMORY;

		list_append(&virtual_slots, slot);
		if (0 != list_init(&slot->objects)) {
			return CKR_HOST_MEMORY;
		}
		list_attributes_seeker(&slot->objects, object_list_seeker);

		if (0 != list_init(&slot->logins)) {
			return CKR_HOST_MEMORY;
		}
	} else {
		/* reuse the old list of logins/objects since they should be empty */
		list_t logins = slot->logins;
		list_t objects = slot->objects;

		memset(slot, 0, sizeof *slot);

		slot->logins = logins;
		slot->objects = objects;
	}

	slot->login_user = -1;
	slot->id = (CK_SLOT_ID) list_locate(&virtual_slots, slot);
	init_slot_info(&slot->slot_info, reader);
	sc_log(context, "Initializing slot with id 0x%lx", slot->id);

	if (reader != NULL) {
		slot->reader = reader;
		strcpy_bp(slot->slot_info.manufacturerID, reader->vendor, 32);
		strcpy_bp(slot->slot_info.slotDescription, reader->name, 64);
		slot->slot_info.hardwareVersion.major = reader->version_major;
		slot->slot_info.hardwareVersion.minor = reader->version_minor;
	}

	return CKR_OK;
}
Example #8
0
list_t* list_convert(struct lprov_entry* first)
{
	struct lconv_entry* entry;
	list_t* list = malloc(sizeof(list_t));
	list_init(list);
	list_attributes_copy(list, &lconv_entry_meter, 1);
	list_attributes_comparator(list, &lconv_entry_comparator);
	list_attributes_seeker(list, &lconv_entry_seeker);
	while (first != NULL)
	{
		entry = malloc(sizeof(struct lconv_entry));
		entry->address = first->address;
		entry->bin = NULL;
		entry->label = bfromcstr(first->label);
		list_append(list, entry);
		free(entry);
		first = first->next;
	}
	return list;
}
Example #9
0
int logsuck_init() {
    list_init(& sources_list);
    list_attributes_copy(& sources_list, list_meter_sourceentry, 1);

#if defined(HAVE_KQUEUE)
    /* will need file descriptor seeker to look up source items from fds */
    list_attributes_seeker(& sources_list, list_seeker_filedescriptor);
#endif

#if defined(HAVE_KQUEUE)
    /* initialize kqueue */
    if ((kq = kqueue()) == -1) {
        sshguard_log(LOG_CRIT, "Unable to create kqueue! %s.", strerror(errno));
        return -1;
    }
    /* re-test sources every this interval */
    kev_timeout.tv_sec = 1;
    kev_timeout.tv_nsec = 500 * 1000 * 1000;
#endif

    return 0;
}
Example #10
0
int sc_context_create(sc_context_t **ctx_out, const sc_context_param_t *parm)
{
	sc_context_t		*ctx;
	struct _sc_ctx_options	opts;
	int			r;

	if (ctx_out == NULL || parm == NULL)
		return SC_ERROR_INVALID_ARGUMENTS;

	ctx = calloc(1, sizeof(sc_context_t));
	if (ctx == NULL)
		return SC_ERROR_OUT_OF_MEMORY;
	memset(&opts, 0, sizeof(opts));

	/* set the application name if set in the parameter options */
	if (parm->app_name != NULL)
		ctx->app_name = strdup(parm->app_name);
	else
		ctx->app_name = strdup("default");
	if (ctx->app_name == NULL) {
		sc_release_context(ctx);
		return SC_ERROR_OUT_OF_MEMORY;
	}
	
	set_defaults(ctx, &opts);
	list_init(&ctx->readers);
	list_attributes_seeker(&ctx->readers, reader_list_seeker);
	/* set thread context and create mutex object (if specified) */
	if (parm->thread_ctx != NULL)
		ctx->thread_ctx = parm->thread_ctx;
	r = sc_mutex_create(ctx, &ctx->mutex);
	if (r != SC_SUCCESS) {
		sc_release_context(ctx);
		return r;
	}

	process_config_file(ctx, &opts);
	sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "==================================="); /* first thing in the log */
	sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "opensc version: %s", sc_get_version());

#ifdef HAVE_LTDL_H
	/* initialize ltdl, if available. See scdl.c for more information */
	if (lt_dlinit() != 0) {
		sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "lt_dlinit() failed");
		sc_release_context(ctx);
		return SC_ERROR_INTERNAL;
	}
#endif

#ifdef ENABLE_PCSC
	ctx->reader_driver = sc_get_pcsc_driver();
/* XXX: remove cardmod pseudoreader driver */
#ifdef ENABLE_MINIDRIVER
	if(strcmp(ctx->app_name, "cardmod") == 0) {
		ctx->reader_driver = sc_get_cardmod_driver();
	}
#endif
#elif ENABLE_CTAPI
	ctx->reader_driver = sc_get_ctapi_driver();
#elif ENABLE_OPENCT
	ctx->reader_driver = sc_get_openct_driver();
#endif

	load_reader_driver_options(ctx);
	ctx->reader_driver->ops->init(ctx);
	
	load_card_drivers(ctx, &opts);
	load_card_atrs(ctx);
	if (opts.forced_card_driver) {
		/* FIXME: check return value? */
		sc_set_card_driver(ctx, opts.forced_card_driver);
		free(opts.forced_card_driver);
	}
	del_drvs(&opts);
	sc_ctx_detect_readers(ctx);
	*ctx_out = ctx;
	return SC_SUCCESS;
}
Example #11
0
int main(int argc, char *argv[])
{
  time_t current_time;
  char * createdDate;
  int opt;
  char *port = "6667", *passwd = NULL;


  while ((opt = getopt(argc, argv, "p:o:h")) != -1)
    switch (opt)
    {
      case 'p':
        port = strdup(optarg);
        break;
      case 'o':
        passwd = strdup(optarg);
        break;
      default:
        printf("ERROR: Unknown option -%c\n", opt);
        exit(-1);
    }

  if (!passwd)
  {
    fprintf(stderr, "ERROR: You must specify an operator password\n");
    exit(-1);
  }
  num_pthreads = 0;
  int serverSocket;
  int clientSocket;
  pthread_t worker_thread;
  struct sockaddr_in serverAddr, clientAddr;
  int yes = 1; 
  socklen_t sinSize = sizeof(struct sockaddr_in);

  memset(&serverAddr, 0, sizeof(serverAddr));
  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(atoi(port));
  serverAddr.sin_addr.s_addr = INADDR_ANY;

  // store server data
  serverInfo * servData;
  servData = (serverInfo *) malloc(sizeof(serverInfo));
  memset(servData, 0, sizeof(servData));
  struct hostent *heServ;
  char hostname[1024];
  hostname[1023] = '\0';
  gethostname(hostname, 1023);
  heServ = gethostbyname(hostname);
  memcpy(servData->passwd, passwd, strlen(passwd));
  memcpy(servData->serverHost, heServ->h_name, strlen(heServ->h_name));
  char serverVersion[] = "version2";
  memcpy(servData->serverVersion, serverVersion, strlen(serverVersion));
  current_time = time(NULL);
  createdDate = ctime(&current_time);
  memcpy(servData->createdDate, createdDate, strlen(createdDate));
  char userModes[] = "ao";
  memcpy(servData->userModes, userModes, strlen(userModes));
  char chanModes[] = "mtov";
  memcpy(servData->chanModes, chanModes, strlen(chanModes));

  serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
  bind(serverSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
  listen(serverSocket, 5);

  // initialize global list of users
  list_t * userList = (list_t *) malloc(sizeof(list_t));
  list_init(userList);
  list_attributes_copy(userList, user_info_size, 1);
  list_attributes_comparator(userList, nick_comparator);
  list_attributes_seeker(userList, (element_seeker) seeker);

  // initialize global list of channels
  list_t * chanList = (list_t *) malloc(sizeof(list_t));
  list_init(chanList);
  list_attributes_copy(chanList, chan_info_size, 1);
  list_attributes_comparator(chanList, chan_comparator);
  list_attributes_seeker(chanList, (element_seeker) chan_seeker);

  // initialize list of users not in a channel
/*  channelData * newChannel;
  newChannel = (channelData *) malloc(sizeof(channelData));
  memcpy(newChannel->name, "*\0", strlen("*\0"));
  pthread_mutex_init(&newChannel->chanUserLock, NULL);
  // remember to delete mutex upon channel deletion
  newChannel->userList = (list_t *) malloc(sizeof(list_t));
  list_init(newChannel->userList);
  list_attributes_copy(newChannel->userList, user_info_size, 1);
  list_attributes_comparator(newChannel->userList, nick_comparator);
  list_attributes_seeker(newChannel->userList, (element_seeker) seeker);
  list_append(chanList, newChannel);
  list_sort(chanList, 1);
*/
  struct workerArgs *wa;

  pthread_mutex_init(&lock, NULL);
  pthread_mutex_init(&chanLock, NULL);

  while(1)
  {
    clientSocket = accept(serverSocket, (struct sockaddr *) &clientAddr, &sinSize);
    setsockopt(clientSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
    // retrieve client hostname
    struct hostent *he;
    struct in_addr ipv4addr;
    char *IP = inet_ntoa(clientAddr.sin_addr);
    inet_pton(AF_INET, IP, &ipv4addr);
    he = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);
    char *clientHost = he->h_name;
    // pass on arguments to worker thread
    wa = malloc(sizeof(struct workerArgs));
    wa->socket = clientSocket;
    wa->clientHost = clientHost;
    wa->userList = userList;
    wa->chanList = chanList;
    wa->servData = servData;
    if(pthread_create(&worker_thread, NULL, run_client, wa) != 0)
    {
      perror("Could not create a worker thread");
      free(wa);
      close(clientSocket);
      pthread_exit(NULL);
    }
  }
  close(serverSocket);
  pthread_mutex_destroy(&lock);
  pthread_mutex_destroy(&chanLock);
  return 0;
}
Example #12
0
File: ctx.c Project: AktivCo/OpenSC
int sc_context_create(sc_context_t **ctx_out, const sc_context_param_t *parm)
{
	sc_context_t		*ctx;
	struct _sc_ctx_options	opts;
	int			r;
	char			*driver;

	if (ctx_out == NULL || parm == NULL)
		return SC_ERROR_INVALID_ARGUMENTS;

	ctx = calloc(1, sizeof(sc_context_t));
	if (ctx == NULL)
		return SC_ERROR_OUT_OF_MEMORY;
	memset(&opts, 0, sizeof(opts));

	/* set the application name if set in the parameter options */
	if (parm->app_name != NULL)
		ctx->app_name = strdup(parm->app_name);
	else
		ctx->app_name = strdup("default");
	if (ctx->app_name == NULL) {
		sc_release_context(ctx);
		return SC_ERROR_OUT_OF_MEMORY;
	}

	ctx->flags = parm->flags;
	set_defaults(ctx, &opts);

	if (0 != list_init(&ctx->readers)) {
		sc_release_context(ctx);
		return SC_ERROR_OUT_OF_MEMORY;
	}
	list_attributes_seeker(&ctx->readers, reader_list_seeker);
	/* set thread context and create mutex object (if specified) */
	if (parm->thread_ctx != NULL)
		ctx->thread_ctx = parm->thread_ctx;
	r = sc_mutex_create(ctx, &ctx->mutex);
	if (r != SC_SUCCESS) {
		sc_release_context(ctx);
		return r;
	}

#if defined(ENABLE_OPENSSL) && defined(OPENSSL_SECURE_MALLOC_SIZE)
	if (!CRYPTO_secure_malloc_initialized()) {
		CRYPTO_secure_malloc_init(OPENSSL_SECURE_MALLOC_SIZE, OPENSSL_SECURE_MALLOC_SIZE/8);
	}
#endif

	process_config_file(ctx, &opts);
	sc_log(ctx, "==================================="); /* first thing in the log */
	sc_log(ctx, "opensc version: %s", sc_get_version());

#ifdef ENABLE_PCSC
	ctx->reader_driver = sc_get_pcsc_driver();
#elif defined(ENABLE_CRYPTOTOKENKIT)
	ctx->reader_driver = sc_get_cryptotokenkit_driver();
#elif defined(ENABLE_CTAPI)
	ctx->reader_driver = sc_get_ctapi_driver();
#elif defined(ENABLE_OPENCT)
	ctx->reader_driver = sc_get_openct_driver();
#endif

	r = ctx->reader_driver->ops->init(ctx);
	if (r != SC_SUCCESS)   {
		sc_release_context(ctx);
		return r;
	}

	driver = getenv("OPENSC_DRIVER");
	if (driver) {
		scconf_list *list = NULL;
		scconf_list_add(&list, driver);
		set_drivers(&opts, list);
		scconf_list_destroy(list);
	}

	load_card_drivers(ctx, &opts);
	load_card_atrs(ctx);

	del_drvs(&opts);
	sc_ctx_detect_readers(ctx);
	*ctx_out = ctx;

	return SC_SUCCESS;
}
Example #13
0
///
/// Splits the currently loaded bins into sectioned bins.
///
void bins_sectionize()
{
	struct lconv_entry* entry;
	struct ldbin* bin;
	struct ldbin* target;
	list_t create;
	size_t i;
	int steal, stolen, index, base;
	bstring name;

	list_init(&create);
	list_attributes_seeker(&create, &bin_seeker);

	// Print result information.
	for (i = 0; i < list_size(&ldbins.bins); i++)
	{
		bin = list_get_at(&ldbins.bins, i);
		printd(LEVEL_VERBOSE, "start bin: %s\n", bin->name->data);
		bin->provided != NULL ? printd(LEVEL_VERBOSE, "	 total provided: %u\n", list_size(bin->provided)) : false;
		bin->required != NULL ? printd(LEVEL_VERBOSE, "	 total required: %u\n", list_size(bin->required)) : false;
		bin->adjustment != NULL ? printd(LEVEL_VERBOSE, "  total adjustment: %u\n", list_size(bin->adjustment)) : false;
		bin->section != NULL ? printd(LEVEL_VERBOSE, "	total sections: %u\n", list_size(bin->section)) : false;
		bin->output != NULL ? printd(LEVEL_VERBOSE, "  total outputs: %u\n", list_size(bin->output)) : false;
		printd(LEVEL_VERBOSE, "	 total words: 0x%04X\n", list_size(&bin->words));
		list_iterator_start(&bin->words);
		while (list_iterator_hasnext(&bin->words))
			printd(LEVEL_VERBOSE, "	   0x%04X\n", *(uint16_t*)list_iterator_next(&bin->words));
		list_iterator_stop(&bin->words);
		printd(LEVEL_VERBOSE, "	 \n");
	}

	// Copy words into appropriate bins.
	list_iterator_start(&ldbins.bins);
	while (list_iterator_hasnext(&ldbins.bins))
	{
		bin = list_iterator_next(&ldbins.bins);

		// Search all of the sections in this bin.
		assert(bin->section != NULL);
		list_iterator_start(bin->section);
		while (list_iterator_hasnext(bin->section))
		{
			entry = list_iterator_next(bin->section);

			// Create target section bin if it doesn't
			// already exist.
			name = bfromcstr("SECTION ");
			bconcat(name, entry->label);
			if (list_seek(&create, name) == NULL)
			{
				target = bin_create(bautofree(name), false);
				target->provided = list_create();
				target->required = list_create();
				target->adjustment = list_create();
				target->output = list_create();
				list_append(&create, target);
			}
			else
				bdestroy(name);
		}
		list_iterator_stop(bin->section);
	}
	list_iterator_stop(&ldbins.bins);

	// For each of the file bins, move the code that they
	// have in sections into the section bins.
	list_iterator_start(&ldbins.bins);
	while (list_iterator_hasnext(&ldbins.bins))
	{
		bin = list_iterator_next(&ldbins.bins);

		// Search all of the sections in this bin.
		stolen = 0;
		assert(bin->section != NULL);
		list_sort(bin->section, 1);
		for (i = 0; i < list_size(bin->section); i++)
		{
			// Work out the target bin.
			name = bfromcstr("SECTION ");
			bconcat(name, ((struct lconv_entry*)list_get_at(bin->section, i))->label);
			target = list_seek(&create, name);
			assert(target != NULL);
			bdestroy(name);

			// Calculate how many bytes to steal from this section.
			if (i == list_size(bin->section) - 1)
			{
				// Steal until end-of-bin.
				steal = list_size(&bin->words) -
					(((struct lconv_entry*)list_get_at(bin->section, i))->address - stolen);
			}
			else
			{
				// Steal up to the next section.
				steal = (((struct lconv_entry*)list_get_at(bin->section, i + 1))->address - stolen) -
					(((struct lconv_entry*)list_get_at(bin->section, i))->address - stolen);
			}

			// Get the index from which to extract.
			index = ((struct lconv_entry*)list_get_at(bin->section, i))->address - stolen;
			base = list_size(&target->words);

			bin_move(target, bin, base, index, steal);
			stolen += steal;
		}
	}
	list_iterator_stop(&ldbins.bins);

	// Append new bins to the bin list and free
	// memory of old list.
	list_iterator_start(&create);
	while (list_iterator_hasnext(&create))
		list_append(&ldbins.bins, list_iterator_next(&create));
	list_iterator_stop(&create);
	list_destroy(&create);

	// Print result information.
	for (i = 0; i < list_size(&ldbins.bins); i++)
	{
		bin = list_get_at(&ldbins.bins, i);
		printd(LEVEL_VERBOSE, "end bin: %s\n", bin->name->data);
		bin->provided != NULL ? printd(LEVEL_VERBOSE, "	 total provided: %u\n", list_size(bin->provided)) : false;
		bin->required != NULL ? printd(LEVEL_VERBOSE, "	 total required: %u\n", list_size(bin->required)) : false;
		bin->adjustment != NULL ? printd(LEVEL_VERBOSE, "  total adjustment: %u\n", list_size(bin->adjustment)) : false;
		bin->section != NULL ? printd(LEVEL_VERBOSE, "	total sections: %u\n", list_size(bin->section)) : false;
		bin->output != NULL ? printd(LEVEL_VERBOSE, "  total outputs: %u\n", list_size(bin->output)) : false;
		printd(LEVEL_VERBOSE, "	 total words: 0x%04X\n", list_size(&bin->words));
		list_iterator_start(&bin->words);
		while (list_iterator_hasnext(&bin->words))
			printd(LEVEL_VERBOSE, "	   0x%04X\n", *(uint16_t*)list_iterator_next(&bin->words));
		list_iterator_stop(&bin->words);
		printd(LEVEL_VERBOSE, "	 \n");
	}
}
CK_RV C_Initialize(CK_VOID_PTR pInitArgs)
{
	CK_RV rv;
#if !defined(_WIN32)
	pid_t current_pid = getpid();
#endif
	int rc;
	unsigned int i;
	sc_context_param_t ctx_opts;

	/* Handle fork() exception */
#if !defined(_WIN32)
	if (current_pid != initialized_pid) {
		C_Finalize(NULL_PTR);
	}
	initialized_pid = current_pid;
	in_finalize = 0;
#endif

	if (context != NULL) {
		sc_debug(context, SC_LOG_DEBUG_NORMAL, "C_Initialize(): Cryptoki already initialized\n");
		return CKR_CRYPTOKI_ALREADY_INITIALIZED;
	}

	rv = sc_pkcs11_init_lock((CK_C_INITIALIZE_ARGS_PTR) pInitArgs);
	if (rv != CKR_OK)
		goto out;

	/* set context options */
	memset(&ctx_opts, 0, sizeof(sc_context_param_t));
	ctx_opts.ver        = 0;
	ctx_opts.app_name   = "opensc-pkcs11";
	ctx_opts.thread_ctx = &sc_thread_ctx;
	
	rc = sc_context_create(&context, &ctx_opts);
	if (rc != SC_SUCCESS) {
		rv = CKR_GENERAL_ERROR;
		goto out;
	}

	/* Load configuration */
	load_pkcs11_parameters(&sc_pkcs11_conf, context);

	/* List of sessions */
	list_init(&sessions);
	list_attributes_seeker(&sessions, session_list_seeker);
	
	/* List of slots */
	list_init(&virtual_slots);
	list_attributes_seeker(&virtual_slots, slot_list_seeker);
	
	/* Create a slot for a future "PnP" stuff. */
	if (sc_pkcs11_conf.plug_and_play) {
		create_slot(NULL);
	}
	/* Create slots for readers found on initialization */
	for (i=0; i<sc_ctx_get_reader_count(context); i++) {
		initialize_reader(sc_ctx_get_reader(context, i));
	}

	/* Set initial event state on slots */
	for (i=0; i<list_size(&virtual_slots); i++) {
		sc_pkcs11_slot_t *slot = (sc_pkcs11_slot_t *) list_get_at(&virtual_slots, i);
		slot->events = 0; /* Initially there are no events */
	}

out:	
	if (context != NULL)
		sc_debug(context, SC_LOG_DEBUG_NORMAL, "C_Initialize() = %s", lookup_enum ( RV_T, rv ));

	if (rv != CKR_OK) {
		if (context != NULL) {
			sc_release_context(context);
			context = NULL;
		}
		/* Release and destroy the mutex */
		sc_pkcs11_free_lock();
	}

	return rv;
}
Example #15
0
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *   Update the csv context with the latest contents from the
 *   Falcon. For each buffer that has at least on hour worth of
 *   data, compress and write the data to the diskloop.
 */
void csv_poll( csv_context_t* csv_buffer_list, buffer_t* url_str,
               st_info_t* st_info, time_t initial_time )
{
    list_t* file_list = NULL;
    buffer_t* buf = NULL;
    buffer_t* url = NULL;
    char* file_name = NULL;
    const char* path = "/data/minute";
    csv_buffer_t csv_tmp;
    csv_buffer_t* csv_buffer;
    int location = 0;
    uint64_t file_hash = 0LL;

    uint8_t buffer_found = 0;

    int tally = 0;

    // Build the CSV directory URL
    url = buffer_init();
    buffer_write(url, url_str->content, url_str->length);
    buffer_write(url, (uint8_t*)path, strlen(path));
    buffer_terminate(url);

    // Initialize the CSV file list
    file_list = (list_t*)malloc(sizeof(list_t));
    if (!file_list)
        goto clean;
    list_init(file_list);
    list_attributes_seeker( file_list,  _file_list_seeker );
    list_attributes_comparator( file_list,  _file_list_comparator );

    // Get the html page listing the available CSV files
    buf = buffer_init();
    get_page((char*)url->content, buf);

    // Generate a list of files from the page
    if (!csv_get_file_list(file_list, buf))
        goto clean;
    buffer_reset(buf);
    buffer_reset(url);

    // Step through each CSV file and update its csv_buffer
    // in the csv_buffer_list
    while (!list_empty(file_list)) 
    {
        tally++;
        file_name = (char*)list_fetch(file_list);
        memset(&csv_tmp, 0, sizeof(csv_tmp));
        csv_tmp.file_name = file_name;

        // If there is not a csv buffer for this csv file, create a
        // new buffer and add it to the list
        if ((location = list_locate(csv_buffer_list, &csv_tmp)) < 0)
        {
            csv_buffer = csv_buffer_init();
            csv_buffer->file_name = file_name;
            list_append(csv_buffer_list, csv_buffer);
            buffer_found = 0;
        // Otherwise re-use the old csv buffer
        } else { 
            csv_buffer = (csv_buffer_t*)list_get_at(csv_buffer_list, location);
            buffer_found = 1;
        }

     // Process the contents of this CSV file
        // Generate the URL for retrieving the file
        buffer_write(url, url_str->content, url_str->length);
        buffer_write(url, (uint8_t*)csv_buffer->file_name,
                     strlen(csv_buffer->file_name));
        buffer_terminate(url);
        if (gDebug) {
            printf("getting page %s\n", url->content);
        }
        // Download the file
        get_page((char*)url->content, buf);
        file_hash = murmur_64_b( buf->content, buf->length, HASH_SEED_64 );
        if (gDebug) {
            fprintf(stderr, "file '%s' [0x%016llx] uncompressed size is %lu bytes\n",
                   csv_buffer->file_name, (unsigned long long)file_hash,
                   (unsigned long)buf->length);
            if (strcmp("/data/minute/logm1.csv", csv_buffer->file_name) == 0)
              fprintf(stderr, "'%s'\n", buf->content);
        }
        // Populate a csv_buffer with the contents of the file
        csv_parse_file(csv_buffer, buf, initial_time);
        if (gDebug) {
            fprintf(stderr, "The CSV buffer contains %u rows\n", csv_buffer->list->numels);
        }
        // Empty our temporary buffers
        buffer_reset(buf);
        buffer_reset(url);
        if (buffer_found) {
            free(file_name);
        }
        file_name = NULL;
        csv_buffer = NULL;
    }

// Clean up all temporary resources
clean:
    buf = buffer_destroy(buf);
    url = buffer_destroy(url);
    if (file_list) 
    {
        while(!list_empty(file_list))
        {
            file_name = list_fetch(file_list);
            if (file_name)
            {
                free(file_name);
            }
        }
        list_destroy(file_list);
        free(file_list);
    }
} // csv_poll()
Example #16
0
///
/// Initializes the linker bin system.
///
void bins_init()
{
	list_init(&ldbins.bins);
	list_attributes_seeker(&ldbins.bins, &bin_seeker);
}
Example #17
0
CK_RV C_Initialize(CK_VOID_PTR pInitArgs)
{
	CK_RV rv;
#if !defined(_WIN32)
	pid_t current_pid = getpid();
#endif
	int rc;
	unsigned int i;
	sc_context_param_t ctx_opts;

#if !defined(_WIN32)
	/* Handle fork() exception */
	if (current_pid != initialized_pid) {
		if (context)
			context->flags |= SC_CTX_FLAG_TERMINATE;
		C_Finalize(NULL_PTR);
	}
	initialized_pid = current_pid;
	in_finalize = 0;
#endif

	if (context != NULL) {
		sc_log(context, "C_Initialize(): Cryptoki already initialized\n");
		return CKR_CRYPTOKI_ALREADY_INITIALIZED;
	}

	rv = sc_pkcs11_init_lock((CK_C_INITIALIZE_ARGS_PTR) pInitArgs);
	if (rv != CKR_OK)
		goto out;

	/* set context options */
	memset(&ctx_opts, 0, sizeof(sc_context_param_t));
	ctx_opts.ver        = 0;
	ctx_opts.app_name   = MODULE_APP_NAME;
	ctx_opts.thread_ctx = &sc_thread_ctx;

	rc = sc_context_create(&context, &ctx_opts);
	if (rc != SC_SUCCESS) {
		rv = CKR_GENERAL_ERROR;
		goto out;
	}

	/* Load configuration */
	load_pkcs11_parameters(&sc_pkcs11_conf, context);

	/* List of sessions */
	list_init(&sessions);
	list_attributes_seeker(&sessions, session_list_seeker);

	/* List of slots */
	list_init(&virtual_slots);
	list_attributes_seeker(&virtual_slots, slot_list_seeker);

	/* Create a slot for a future "PnP" stuff. */
	if (sc_pkcs11_conf.plug_and_play) {
		create_slot(NULL);
	}

	/* Create slots for readers found on initialization, only if in 2.11 mode */
	if (!sc_pkcs11_conf.plug_and_play) {
		for (i=0; i<sc_ctx_get_reader_count(context); i++) {
			initialize_reader(sc_ctx_get_reader(context, i));
		}
	}

out:
	if (context != NULL)
		sc_log(context, "C_Initialize() = %s", lookup_enum ( RV_T, rv ));

	if (rv != CKR_OK) {
		if (context != NULL) {
			sc_release_context(context);
			context = NULL;
		}
		/* Release and destroy the mutex */
		sc_pkcs11_free_lock();
	}

	return rv;
}
LONG RFAddReader(const char *readerNameLong, int port, const char *library,
	const char *device)
{
	DWORD dwContext = 0, dwGetSize;
	UCHAR ucGetData[1], ucThread[1];
	LONG rv, parentNode;
	int i, j;
	int lrv = 0;
	char *readerName = NULL;

	if ((readerNameLong == NULL) || (library == NULL) || (device == NULL))
		return SCARD_E_INVALID_VALUE;

#ifdef FILTER_NAMES
	const char *ro_filter = getenv("PCSCLITE_FILTER_IGNORE_READER_NAMES");
	if (ro_filter)
	{
		char *filter, *next;

		/* get a RW copy of the env string */
		filter = alloca(strlen(ro_filter)+1);
		strcpy(filter, ro_filter);

		while (filter)
		{
			/* ':' is the separator */
			next = strchr(filter, ':');
			if (next)
			{
				/* NUL terminate the current pattern */
				*next = '\0';
			}

			/* if filter is non empty and found in the reader name */
			if (*filter && strstr(readerNameLong, filter))
			{
				Log3(PCSC_LOG_ERROR,
					"Reader name \"%s\" contains \"%s\": ignored",
					readerNameLong, filter);
				return SCARD_E_READER_UNAVAILABLE;
			}

			if (next)
				/* next pattern */
				filter = next+1;
			else
				/* end */
				filter = NULL;
		}
	}
#endif

	/* allocate memory that is automatically freed */
	readerName = alloca(strlen(readerNameLong)+1);
	strcpy(readerName, readerNameLong);

	/* Reader name too long? also count " 00 00"*/
	if (strlen(readerName) > MAX_READERNAME - sizeof(" 00 00"))
	{
		Log3(PCSC_LOG_ERROR,
			"Reader name too long: %zd chars instead of max %zd. Truncating!",
			strlen(readerName), MAX_READERNAME - sizeof(" 00 00"));
		readerName[MAX_READERNAME - sizeof(" 00 00")] = '\0';
	}

	/* Same name, same port, same device - duplicate reader cannot be used */
	if (dwNumReadersContexts != 0)
	{
		for (i = 0; i < PCSCLITE_MAX_READERS_CONTEXTS; i++)
		{
			if (sReadersContexts[i]->vHandle != 0)
			{
				char lpcStripReader[MAX_READERNAME];
				int tmplen;

				/* get the reader name without the reader and slot numbers */
				strncpy(lpcStripReader,
					sReadersContexts[i]->readerState->readerName,
					sizeof(lpcStripReader));
				tmplen = strlen(lpcStripReader);
				lpcStripReader[tmplen - 6] = 0;

				if ((strcmp(readerName, lpcStripReader) == 0)
					&& (port == sReadersContexts[i]->port)
					&& (strcmp(device, sReadersContexts[i]->device) == 0))
				{
					Log1(PCSC_LOG_ERROR, "Duplicate reader found.");
					return SCARD_E_DUPLICATE_READER;
				}
			}
		}
	}

	/* We must find an empty slot to put the reader structure */
	for (i = 0; i < PCSCLITE_MAX_READERS_CONTEXTS; i++)
	{
		if (sReadersContexts[i]->vHandle == 0)
		{
			dwContext = i;
			break;
		}
	}

	if (i == PCSCLITE_MAX_READERS_CONTEXTS)
	{
		/* No more spots left return */
		return SCARD_E_NO_MEMORY;
	}

	/* Check and set the readername to see if it must be enumerated */
	parentNode = RFSetReaderName(sReadersContexts[dwContext], readerName,
		library, port);
	if (parentNode < -1)
		return SCARD_E_NO_MEMORY;

	sReadersContexts[dwContext]->library = strdup(library);
	sReadersContexts[dwContext]->device = strdup(device);
	sReadersContexts[dwContext]->version = 0;
	sReadersContexts[dwContext]->port = port;
	sReadersContexts[dwContext]->mMutex = NULL;
	sReadersContexts[dwContext]->contexts = 0;
	sReadersContexts[dwContext]->pthThread = 0;
	sReadersContexts[dwContext]->hLockId = 0;
	sReadersContexts[dwContext]->LockCount = 0;
	sReadersContexts[dwContext]->vHandle = NULL;
	sReadersContexts[dwContext]->pFeeds = NULL;
	sReadersContexts[dwContext]->pMutex = NULL;
	sReadersContexts[dwContext]->pthCardEvent = NULL;

	lrv = list_init(&sReadersContexts[dwContext]->handlesList);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL, "list_init failed with return value: %d", lrv);
		return SCARD_E_NO_MEMORY;
	}

	lrv = list_attributes_seeker(&sReadersContexts[dwContext]->handlesList,
		RDR_CLIHANDLES_seeker);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL,
			"list_attributes_seeker failed with return value: %d", lrv);
		return SCARD_E_NO_MEMORY;
	}

	(void)pthread_mutex_init(&sReadersContexts[dwContext]->handlesList_lock,
		NULL);

	(void)pthread_mutex_init(&sReadersContexts[dwContext]->powerState_lock,
		NULL);
	sReadersContexts[dwContext]->powerState = POWER_STATE_UNPOWERED;

	/* reference count */
	(void)pthread_mutex_init(&sReadersContexts[dwContext]->reference_lock,
		NULL);
	sReadersContexts[dwContext]->reference = 1;

	/* If a clone to this reader exists take some values from that clone */
	if (parentNode >= 0 && parentNode < PCSCLITE_MAX_READERS_CONTEXTS)
	{
		sReadersContexts[dwContext]->pFeeds =
		  sReadersContexts[parentNode]->pFeeds;
		*(sReadersContexts[dwContext])->pFeeds += 1;
		sReadersContexts[dwContext]->vHandle =
		  sReadersContexts[parentNode]->vHandle;
		sReadersContexts[dwContext]->mMutex =
		  sReadersContexts[parentNode]->mMutex;
		sReadersContexts[dwContext]->pMutex =
		  sReadersContexts[parentNode]->pMutex;

		/* Call on the parent driver to see if it is thread safe */
		dwGetSize = sizeof(ucThread);
		rv = IFDGetCapabilities(sReadersContexts[parentNode],
			TAG_IFD_THREAD_SAFE, &dwGetSize, ucThread);

		if (rv == IFD_SUCCESS && dwGetSize == 1 && ucThread[0] == 1)
		{
			Log1(PCSC_LOG_INFO, "Driver is thread safe");
			sReadersContexts[dwContext]->mMutex = NULL;
			sReadersContexts[dwContext]->pMutex = NULL;
		}
		else
			*(sReadersContexts[dwContext])->pMutex += 1;
	}

	if (sReadersContexts[dwContext]->pFeeds == NULL)
	{
		sReadersContexts[dwContext]->pFeeds = malloc(sizeof(int));

		/* Initialize pFeeds to 1, otherwise multiple
		   cloned readers will cause pcscd to crash when
		   RFUnloadReader unloads the driver library
		   and there are still devices attached using it --mikeg*/
		*(sReadersContexts[dwContext])->pFeeds = 1;
	}

	if (sReadersContexts[dwContext]->mMutex == 0)
	{
		sReadersContexts[dwContext]->mMutex =
			malloc(sizeof(pthread_mutex_t));
		(void)pthread_mutex_init(sReadersContexts[dwContext]->mMutex, NULL);
	}

	if (sReadersContexts[dwContext]->pMutex == NULL)
	{
		sReadersContexts[dwContext]->pMutex = malloc(sizeof(int));
		*(sReadersContexts[dwContext])->pMutex = 1;
	}

	dwNumReadersContexts += 1;

	rv = RFInitializeReader(sReadersContexts[dwContext]);
	if (rv != SCARD_S_SUCCESS)
	{
		/* Cannot connect to reader. Exit gracefully */
		Log2(PCSC_LOG_ERROR, "%s init failed.", readerName);
		(void)RFRemoveReader(readerName, port);
		return rv;
	}

	/* asynchronous card movement?  */
	{
		RESPONSECODE (*fct)(DWORD, int) = NULL;

		dwGetSize = sizeof(fct);

		rv = IFDGetCapabilities(sReadersContexts[dwContext],
			TAG_IFD_POLLING_THREAD_WITH_TIMEOUT, &dwGetSize, (PUCHAR)&fct);
		if ((rv != SCARD_S_SUCCESS) || (dwGetSize != sizeof(fct)))
		{
			Log1(PCSC_LOG_INFO, "Using the pcscd polling thread");
		}
		else
		{
			sReadersContexts[dwContext]->pthCardEvent = fct;
			Log1(PCSC_LOG_INFO, "Using the reader polling thread");
		}

		rv = EHSpawnEventHandler(sReadersContexts[dwContext]);
		if (rv != SCARD_S_SUCCESS)
		{
			Log2(PCSC_LOG_ERROR, "%s init failed.", readerName);
			(void)RFRemoveReader(readerName, port);
			return rv;
		}
	}

	/* Call on the driver to see if there are multiple slots */
	dwGetSize = sizeof(ucGetData);
	rv = IFDGetCapabilities((sReadersContexts[dwContext]),
		TAG_IFD_SLOTS_NUMBER, &dwGetSize, ucGetData);

	int nbSlots = ucGetData[0];
	if (rv != IFD_SUCCESS || dwGetSize != 1 || nbSlots == 0)
		/* Reader does not have this defined.  Must be a single slot
		 * reader so we can just return SCARD_S_SUCCESS. */
		return SCARD_S_SUCCESS;

	if (1 == nbSlots)
		/* Reader has only one slot */
		return SCARD_S_SUCCESS;

	/*
	 * Check the number of slots and create a different
	 * structure for each one accordingly
	 */

	/* Initialize the rest of the slots */
	for (j = 1; j < nbSlots; j++)
	{
		char *tmpReader = NULL;
		DWORD dwContextB = 0;
		RESPONSECODE (*fct)(DWORD, int) = NULL;

		/* We must find an empty spot to put the reader structure */
		for (i = 0; i < PCSCLITE_MAX_READERS_CONTEXTS; i++)
		{
			if (sReadersContexts[i]->vHandle == 0)
			{
				dwContextB = i;
				break;
			}
		}

		if (i == PCSCLITE_MAX_READERS_CONTEXTS)
		{
			/* No more slot left return */
			RFRemoveReader(readerName, port);
			return SCARD_E_NO_MEMORY;
		}

		/* Copy the previous reader name and increment the slot number */
		tmpReader = sReadersContexts[dwContextB]->readerState->readerName;
		memcpy(tmpReader,
			sReadersContexts[dwContext]->readerState->readerName,
			sizeof(sReadersContexts[dwContextB]->readerState->readerName));
		snprintf(tmpReader + strlen(tmpReader) - 2, 3, "%02X", j);

		sReadersContexts[dwContextB]->library =
			sReadersContexts[dwContext]->library;
		sReadersContexts[dwContextB]->device =
			sReadersContexts[dwContext]->device;
		sReadersContexts[dwContextB]->version =
		  sReadersContexts[dwContext]->version;
		sReadersContexts[dwContextB]->port =
		  sReadersContexts[dwContext]->port;
		sReadersContexts[dwContextB]->vHandle =
		  sReadersContexts[dwContext]->vHandle;
		sReadersContexts[dwContextB]->mMutex =
		  sReadersContexts[dwContext]->mMutex;
		sReadersContexts[dwContextB]->pMutex =
		  sReadersContexts[dwContext]->pMutex;
		sReadersContexts[dwContextB]->slot =
			sReadersContexts[dwContext]->slot + j;
		sReadersContexts[dwContextB]->pthCardEvent = NULL;

		/*
		 * Added by Dave - slots did not have a pFeeds
		 * parameter so it was by luck they were working
		 */
		sReadersContexts[dwContextB]->pFeeds =
		  sReadersContexts[dwContext]->pFeeds;

		/* Added by Dave for multiple slots */
		*(sReadersContexts[dwContextB])->pFeeds += 1;

		sReadersContexts[dwContextB]->contexts = 0;
		sReadersContexts[dwContextB]->hLockId = 0;
		sReadersContexts[dwContextB]->LockCount = 0;

		lrv = list_init(&sReadersContexts[dwContextB]->handlesList);
		if (lrv < 0)
		{
			Log2(PCSC_LOG_CRITICAL, "list_init failed with return value: %d", lrv);
			return SCARD_E_NO_MEMORY;
		}

		lrv = list_attributes_seeker(&sReadersContexts[dwContextB]->handlesList,
			RDR_CLIHANDLES_seeker);
		if (lrv < 0)
		{
			Log2(PCSC_LOG_CRITICAL,
					"list_attributes_seeker failed with return value: %d", lrv);
			return SCARD_E_NO_MEMORY;
		}

		(void)pthread_mutex_init(&sReadersContexts[dwContextB]->handlesList_lock, NULL);
		(void)pthread_mutex_init(&sReadersContexts[dwContextB]->powerState_lock,
			NULL);
		sReadersContexts[dwContextB]->powerState = POWER_STATE_UNPOWERED;

		/* reference count */
		(void)pthread_mutex_init(&sReadersContexts[dwContextB]->reference_lock,
			NULL);
		sReadersContexts[dwContextB]->reference = 1;

		/* Call on the parent driver to see if the slots are thread safe */
		dwGetSize = sizeof(ucThread);
		rv = IFDGetCapabilities((sReadersContexts[dwContext]),
			TAG_IFD_SLOT_THREAD_SAFE, &dwGetSize, ucThread);

		if (rv == IFD_SUCCESS && dwGetSize == 1 && ucThread[0] == 1)
		{
			Log1(PCSC_LOG_INFO, "Driver is slot thread safe");

			sReadersContexts[dwContextB]->library =
				strdup(sReadersContexts[dwContext]->library);
			sReadersContexts[dwContextB]->device =
				strdup(sReadersContexts[dwContext]->device);
			sReadersContexts[dwContextB]->mMutex =
				malloc(sizeof(pthread_mutex_t));
			(void)pthread_mutex_init(sReadersContexts[dwContextB]->mMutex,
				NULL);

			sReadersContexts[dwContextB]->pMutex = malloc(sizeof(int));
			*(sReadersContexts[dwContextB])->pMutex = 1;
		}
		else
			*(sReadersContexts[dwContextB])->pMutex += 1;

		dwNumReadersContexts += 1;

		rv = RFInitializeReader(sReadersContexts[dwContextB]);
		if (rv != SCARD_S_SUCCESS)
		{
			/* Cannot connect to slot. Exit gracefully */
			(void)RFRemoveReader(readerName, port);
			return rv;
		}

		/* asynchronous card movement? */
		dwGetSize = sizeof(fct);

		rv = IFDGetCapabilities((sReadersContexts[dwContextB]),
			TAG_IFD_POLLING_THREAD_WITH_TIMEOUT, &dwGetSize, (PUCHAR)&fct);
		if ((rv != SCARD_S_SUCCESS) || (dwGetSize != sizeof(fct)))
		{
			Log1(PCSC_LOG_INFO, "Using the pcscd polling thread");
		}
		else
		{
			sReadersContexts[dwContextB]->pthCardEvent = fct;
			Log1(PCSC_LOG_INFO, "Using the reader polling thread");
		}

		rv = EHSpawnEventHandler(sReadersContexts[dwContextB]);
		if (rv != SCARD_S_SUCCESS)
		{
			Log2(PCSC_LOG_ERROR, "%s init failed.", readerName);
			(void)RFRemoveReader(readerName, port);
			return rv;
		}
	}

	return SCARD_S_SUCCESS;
}