void diff_in_file( char* file, int verbosity ) {
    bool finished = false;
    bool print_diff_info = verbosity > 0 ? true : false;
    bool print_file_info = verbosity > 1 ? true : false;

    list_t list_global;
    list_t list_fixed;
    list_t list_log;
    list_t list_token_context;

    seed_file_info file_info;

    printf( "Initializing lists\n" );
    if ( list_init( &list_global ) ||
         list_init( &list_fixed  ) ||
         list_init( &list_log    ) ||
         list_init( &list_token_context ) ) {
        goto cleanup;
    }

    get_seed_file_info( file, &file_info, print_file_info );

    list_attributes_comparator( &list_global, metadata_compare );
    list_attributes_comparator( &list_fixed, metadata_compare );
    list_attributes_comparator( &list_log, metadata_compare );
    list_attributes_comparator( &list_token_context, metadata_compare );

    printf( "Populating records\n" );
    populate_records( file, &list_global, &list_fixed, 
                      &list_log, &list_token_context, print_file_info );

    printf( "Sorting lists\n" );
    list_sort( &list_global, LIST_ORDER_S2L );
    list_sort( &list_fixed, LIST_ORDER_S2L );
    list_sort( &list_log, LIST_ORDER_S2L );
    list_sort( &list_token_context, LIST_ORDER_S2L );

    printf( "Comparing lists\n" );
    diff_list_global( &list_global, print_diff_info );
    diff_list_fixed( &list_fixed, print_diff_info );
    diff_list_log( &list_log, print_diff_info );
    diff_list_tokens( &list_token_context, print_diff_info );

goto finish;
cleanup:
    fprintf( stderr, "A list initialization failed.\n" );
    list_init(&list_global);
    list_init(&list_fixed);
    list_init(&list_log);
    list_init(&list_token_context);
finish:
    return;
}
示例#2
0
/*
 * Class:     net_towerdefender_image_ARToolkit
 * Method:    artoolkit_init
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_net_towerdefender_image_ARToolkit_artoolkit_1init__(
		JNIEnv * env, jobject object) {
#ifdef DEBUG_LOGGING
	__android_log_write(ANDROID_LOG_INFO,"AR native","initializing artoolkit");
#endif
	//initialize the list of objects
	list_init(&objects);
	//set the comperator function:
	list_attributes_comparator(&objects, objectcomparator);
	//Intialize the list of pattern IDs
	//It might already be initialized, as the native library doesn't get unloaded after the java application finished
	//The pattern IDs will be cached during multiple invocation of the Java application(AndAR)
	if (patternIDs == NULL) {
		patternIDs = (list_t*) malloc(sizeof(list_t));
		if (patternIDs == NULL) {
#ifdef DEBUG_LOGGING
			__android_log_write(ANDROID_LOG_INFO,"AR native","list of patterns is null after init!!");
#endif	
		} else {
			list_init(patternIDs);
		}
	}
#ifdef DEBUG_LOGGING
	__android_log_write(ANDROID_LOG_INFO,"AR native","finished initializing ARToolkit");
#endif
}
示例#3
0
文件: ddata.c 项目: Ape/DCPUToolchain
list_t* dbgfmt_create_list()
{
    list_t* result = malloc(sizeof(list_t));
    list_init(result);
    list_attributes_copy(result, &dbgsym_meter, 1);
    list_attributes_comparator(result, &dbgsym_comparator);
    return result;
}
示例#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;
}
示例#5
0
///
/// Performs preprocessing.
///
void ppimpl(freed_bstring filename, int line, freed_bstring lang, has_t has_input, pop_t input, push_t output)
{
    state_t state;
    list_init(&state.cached_input);
    list_init(&state.cached_output);
    list_init(&state.handlers);
    list_init(&state.scopes);
    list_attributes_comparator(&state.cached_input, list_comparator_char_t);
    list_attributes_comparator(&state.cached_output, list_comparator_char_t);
    list_attributes_copy(&state.cached_input, list_meter_char_t, false);
    list_attributes_copy(&state.cached_output, list_meter_char_t, false);
    list_attributes_hash_computer(&state.cached_input, list_hashcomputer_char_t);
    list_attributes_hash_computer(&state.cached_output, list_hashcomputer_char_t);
    state.has_input = has_input;
    state.input = input;
    state.output = output;
    state.current_line = line;
    state.current_filename = bstrcpy(filename.ref);
    state.default_filename = bfromcstr("<unknown>");
    state.in_single_string = false;
    state.in_double_string = false;
    if (biseqcstrcaseless(lang.ref, "asm"))
    {
        ppimpl_asm_line_register(&state);
        ppimpl_asm_expr_register(&state);
        ppimpl_asm_define_register(&state);
        ppimpl_asm_include_register(&state);
        ppimpl_asm_lua_register(&state);
        ppimpl_asm_init(&state);
    }
    else if (biseqcstrcaseless(lang.ref, "c"))
    {
        ppimpl_c_line_register(&state);
        ppimpl_c_expr_register(&state);
        ppimpl_c_define_register(&state);
        ppimpl_c_include_register(&state);
        ppimpl_c_init(&state);
    }
    ppimpl_process(&state);
    bautodestroy(lang);
    bautodestroy(filename);
}
示例#6
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);
}
示例#7
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;
}
示例#8
0
LONG EHInitializeEventStructures(void)
{
	(void)list_init(&ClientsWaitingForEvent);

	/* request to store copies, and provide the metric function */
    (void)list_attributes_copy(&ClientsWaitingForEvent, list_meter_int32_t, 1);

	/* setting the comparator, so the list can sort, find the min, max etc */
    (void)list_attributes_comparator(&ClientsWaitingForEvent, list_comparator_int32_t);

	(void)pthread_mutex_init(&ClientsWaitingForEvent_lock, NULL);

	return SCARD_S_SUCCESS;
}
示例#9
0
int fw_init() {
    char buf[HOSTS_MAXCMDLEN];
    FILE *tmp, *deny;

    /* set the filename of the temporary configuration file */
    if (snprintf(tempflname, MAX_TEMPFILE_NAMELEN, "%s-sshguard.%u", HOSTSFILE_PATH, getpid()) >= MAX_TEMPFILE_NAMELEN) {
        sshguard_log(LOG_ERR, "'tempflname' buffer too small to hold '%s-sshguard.%u!'", HOSTSFILE_PATH, getpid());
        return FWALL_ERR;
    }

    hosts_clearsshguardblocks();

    /* place sshguard block delimiters (header/footer) into HOSTSFILE_PATH */
    deny = fopen(HOSTSFILE_PATH, "r+");
    if (deny == NULL) {
        sshguard_log(LOG_ERR, "Could not initialize " HOSTSFILE_PATH " for use by sshguard: %s", strerror(errno));
        return FWALL_ERR;
    }

    tmp = make_temporary_conffile();
    if (tmp == NULL) {
        sshguard_log(LOG_ERR, "Could not create temporary file %s!", tempflname);
        fclose(deny);
        return FWALL_ERR;
    }
    fprintf(tmp, "%s%s", HOSTS_SSHGUARD_PREFIX, HOSTS_SSHGUARD_SUFFIX);

    /* copy the original content of HOSTSFILE_PATH into tmp */
    while (fgets(buf, HOSTS_MAXCMDLEN, deny) != NULL) {
        fprintf(tmp, "%s", buf);
    }
    
    fclose(tmp);
    fclose(deny);

    /* install temporary conf file into main file */
    if (install_temporary_conffile() != FWALL_OK)
        return FWALL_ERR;

    list_init(&hosts_blockedaddrs);
    list_attributes_copy(&hosts_blockedaddrs, addr_service_meter, 1);
    list_attributes_comparator(&hosts_blockedaddrs, addr_service_comparator);

    return FWALL_OK;
}
示例#10
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;
}
示例#11
0
void diff_files( char* file_name_a, char* file_name_b, int verbosity ) {
    bool finished = false;
    bool print_diff_info = verbosity > 0 ? true : false;
    bool print_file_info = verbosity > 1 ? true : false;

    seed_file_info file_info_a;
    seed_file_info file_info_b;

    char* file_name_original;
    char* file_name_updated;

    list_t list_global_original;
    list_t list_global_updated;
    list_t list_fixed_original;
    list_t list_fixed_updated;
    list_t list_log_original;
    list_t list_log_updated;
    list_t list_token_context_original;
    list_t list_token_context_updated;

    list_t list_global;
    list_t list_fixed;
    list_t list_log;
    list_t list_token_context;

    printf( "Retrieving file info\n" );
    get_seed_file_info( file_name_a, &file_info_a, print_file_info );
    get_seed_file_info( file_name_b, &file_info_b, print_file_info );
    if ( print_file_info ) {
        print_seed_time( "File A Start Time ", &file_info_a.start_time, "\n" );
        print_seed_time( "File A End Time   ", &file_info_a.end_time,   "\n" );
        print_seed_time( "File B Start Time ", &file_info_b.start_time, "\n" );
        print_seed_time( "File B End Time   ", &file_info_b.end_time,   "\n" );
    }

    printf( "Comparing file times\n" );
    if ( cmp_times( &file_info_a.start_time, &file_info_a.end_time   )  > 0 ||
         cmp_times( &file_info_b.start_time, &file_info_b.end_time   )  > 0 ||
         cmp_times( &file_info_a.start_time, &file_info_b.start_time ) == 0 ||
         cmp_times( &file_info_a.start_time, &file_info_b.end_time   ) == 0 ||
         cmp_times( &file_info_a.end_time, &file_info_b.start_time   ) == 0 ||
         cmp_times( &file_info_a.end_time, &file_info_b.end_time     ) == 0 ) {
        printf( "File times too close\n" );
        goto cleanup;
    } 
    else if ( cmp_times( &file_info_a.end_time, &file_info_b.start_time ) < 0 ) {
        file_name_original = file_name_a;
        file_name_updated  = file_name_b;
    }
    else if ( cmp_times( &file_info_b.end_time, &file_info_a.start_time ) < 0 ) {
        file_name_original = file_name_b;
        file_name_updated  = file_name_a;
    }
    else {
        printf( "File times not as expected\n" );
        goto cleanup;
    }

    printf( "Initializing lists\n" );
    if ( list_init( &list_global_original ) ||
         list_init( &list_fixed_original  ) ||
         list_init( &list_log_original    ) ||
         list_init( &list_token_context_original ) ||

         list_init( &list_global_updated  ) ||
         list_init( &list_fixed_updated   ) ||
         list_init( &list_log_updated     ) ||
         list_init( &list_token_context_updated ) ||

         list_init( &list_global          ) ||
         list_init( &list_fixed           ) ||
         list_init( &list_log             ) ||
         list_init( &list_token_context   ) ) {
        goto cleanup;
    }

    list_attributes_comparator( &list_global_original, metadata_compare );
    list_attributes_comparator( &list_fixed_original, metadata_compare );
    list_attributes_comparator( &list_log_original, metadata_compare );
    list_attributes_comparator( &list_token_context_original, metadata_compare );

    list_attributes_comparator( &list_global_updated, metadata_compare );
    list_attributes_comparator( &list_fixed_updated, metadata_compare );
    list_attributes_comparator( &list_log_updated, metadata_compare );
    list_attributes_comparator( &list_token_context_updated, metadata_compare );

    list_attributes_comparator( &list_global, metadata_compare );
    list_attributes_comparator( &list_fixed, metadata_compare );
    list_attributes_comparator( &list_log, metadata_compare );
    list_attributes_comparator( &list_token_context, metadata_compare );

    printf( "Populating lists\n" );
    /* Loop through file, comparing records as we go  */
    populate_records( file_name_original, 
                      &list_global_original, 
                      &list_fixed_original, 
                      &list_log_original, 
                      &list_token_context_original,
                      print_file_info );
    populate_records( file_name_updated, 
                      &list_global_updated, 
                      &list_fixed_updated, 
                      &list_log_updated, 
                      &list_token_context_updated,
                      print_file_info );

    printf( "Sorting lists\n" );
    list_sort( &list_global_original,        LIST_ORDER_S2L );
    list_sort( &list_fixed_original,         LIST_ORDER_S2L );
    list_sort( &list_log_original,           LIST_ORDER_S2L );
    list_sort( &list_token_context_original, LIST_ORDER_S2L );

    list_sort( &list_global_updated,         LIST_ORDER_S2L );
    list_sort( &list_fixed_updated,          LIST_ORDER_S2L );
    list_sort( &list_log_updated,            LIST_ORDER_S2L );
    list_sort( &list_token_context_updated,  LIST_ORDER_S2L );

    printf( "Populating test lists\n" );
    list_prepend( &list_global, list_get_max(&list_global_original) );
    list_append(  &list_global, list_get_min(&list_global_updated)  );

    list_prepend( &list_fixed, list_get_max(&list_fixed_original) );
    list_append(  &list_fixed, list_get_min(&list_fixed_updated)  );

    list_prepend( &list_log, list_get_max(&list_log_original) );
    list_append(  &list_log, list_get_min(&list_log_updated)  );

    list_prepend( &list_token_context, list_get_max(&list_token_context_original) );
    list_append(  &list_token_context, list_get_min(&list_token_context_updated)  );

    list_sort( &list_global,         LIST_ORDER_S2L );
    list_sort( &list_fixed,          LIST_ORDER_S2L );
    list_sort( &list_log,            LIST_ORDER_S2L );
    list_sort( &list_token_context,  LIST_ORDER_S2L );

    printf( "Comparing lists\n" );
    diff_list_global( &list_global, print_diff_info );
    diff_list_fixed( &list_fixed, print_diff_info );
    diff_list_log( &list_log, print_diff_info );
    diff_list_tokens( &list_token_context, print_diff_info );

goto finish;
cleanup:
    fprintf( stderr, "Either a list initialization failed, "
                     "or the files were incompatable.\n" );
    list_destroy(&list_global_original);
    list_destroy(&list_fixed_original);
    list_destroy(&list_log_original);
    list_destroy(&list_token_context_original);

    list_destroy(&list_global_updated);
    list_destroy(&list_fixed_updated);
    list_destroy(&list_log_updated);
    list_destroy(&list_token_context_updated);

    list_destroy(&list_global);
    list_destroy(&list_fixed);
    list_destroy(&list_log);
    list_destroy(&list_token_context);
finish:
    return;
}
示例#12
0
int main(int argc, char *argv[])
{
  int verbose = 0;
  int iterations = 1;
  int iterating = 0;
  int self_terminate = 0;
  double total_prob = 0.00000001;
  double total_prob_prev = 0.0;
	char c;
  if (argc > 1){
    if (!strcmp(argv[1], "-v")){
      verbose = 1;
      printf("VERBOSE OUTPUT\n");
    } else if (!strcmp(argv[1], "-i")){
    		if (argc == 2){
    			fprintf(stderr, "enter number of iterations\n");
    			exit(1);
    		} else if (argc == 3){
    			iterations = atoi(argv[2]);
    			iterating = 1;
    			printf ("Running %d iterations\n", iterations);
			}
    	} else if (!strcmp(argv[1], "-st")){
    		self_terminate = 1;
    } else {
    		fprintf(stderr, "Invalid arguments\n");
    		exit(1);
    }
	}
  
  puts("Enter input file name:");
  char file_name[64];
  scanf("%s", file_name);
  FILE *file;
  file = fopen(file_name, "r");
  list_t alphabet;
  list_init(& alphabet);
  if (file == NULL){
    fprintf(stderr, "%s: No such file\n", file_name);
    exit(1);
  }
  // Get the list of letters from the file.
  alphabet = parse_file(file);
  
  // Randomly generate initial probabilities.
  srand((unsigned)time(NULL));
  
  int num_letters;
  num_letters = list_size(&alphabet);
  state *state_0 = (state*)malloc(sizeof(state));
  state *state_1 = (state*)malloc(sizeof(state));
  
  state_0 = initialize_state(0, alphabet, 1);
  state_1 = initialize_state(1, alphabet, 0);
  
    printf("---------------------------------\n- Initialization -\n---------------------------------\n");
  
    print_state(state_0, alphabet);
    print_state(state_1, alphabet);
  
    printf("\n---------------------------------\n");
  
  
  double *Pi = (double*)malloc(2*sizeof(double));
  // Pi[0] = ((double)rand()/(double)RAND_MAX);
  Pi[0] = 0.5;
  Pi[1] = 1 - Pi[0];
  printf("Pi:\n\tState\t0\t%lf\n\tState\t1\t%lf\n", Pi[0], Pi[1]);
  
  // Max word size 32
  int i=0;
  char *buffer = (char*)malloc(32);
  list_t words;
  list_init(&words);
  fclose(file);
  file = fopen(file_name, "r");
  while (fscanf(file, "%s ", buffer) != EOF){
  strcat(buffer, "#");
    list_prepend(& words, strdup(buffer));
  }
	//shuffle_list(words, list_size(&words));
  
// Display word list
//  char *temp;
//  for (i=0; i<list_size(&words); i++){
//    temp = (char*)list_get_at(&words, i);
//			printf("%s\n", temp);
//  }
  int iteration = 0;
  if (!self_terminate){
  		while(iteration < iterations){
  			printf("Running iteration number %d\n", iteration);
  			if (!iterating){
   			iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
 		   	printf("\n\n\n\n");
  	  		} else if (iteration == iterations - 1){
   		 	iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
 	 	  } else {
    			iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
    		}
    		iteration++;
    }
  } else {
  		while((iteration < 10) || total_prob_prev < total_prob){
			printf("%lf %lf\n", total_prob_prev, total_prob);
  			printf("Running iteration number %d\n", iteration);
  			total_prob_prev = total_prob;
  			total_prob = iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
  			iteration++;
  			/* If total probability is not increasing much, return that iteration's information.
  			It doesn't make a big difference if we run one more information after the maximum,
  			so I don't output the previous iteration */
 	 	}
		printf("%lf %lf\n", total_prob_prev, total_prob);
		iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
  }
//	for (i=0; i<list_size(&alphabet); i++){
//		c = ((letter_count*)list_get_at(&alphabet, i))->letter;
//		printf("Log probability of %c: %lf\n", c, log(ep(state_0, c)/ep(state_1, c)));
//	}
	list_t freq0;
	list_t freq1;
	list_init(&freq0);
	list_init(&freq1);
	letter_double* ld;
	for (i=0; i<list_size(&alphabet); i++){
		c = ((letter_count*)list_get_at(&alphabet, i))->letter;
		ld = (letter_double*)malloc(sizeof(letter_double));
		ld->letter = c;
		ld->d = log(ep(state_0, c)/ep(state_1, c));
		if (log(ep(state_0, c)/ep(state_1, c)) > 0){
			list_append(&freq0, ld);
		}
	}
	list_attributes_comparator(&freq0, compare_log_prob);
	list_sort(&freq0, 1);
	printf("Letters most preferred by State 0:\n");
	for (i=0; i<list_size(&freq0); i++){
		ld = ((letter_double*)list_get_at(&freq0, i));
			printf("%c: %lf\n", ld->letter, ld->d);
	}
	for (i=0; i<list_size(&alphabet); i++){
		c = ((letter_count*)list_get_at(&alphabet, i))->letter;
		ld = (letter_double*)malloc(sizeof(letter_double));
		ld->letter = c;
		ld->d = log(ep(state_0, c)/ep(state_1, c));
		if (log(ep(state_0, c)/ep(state_1, c)) < 0){
			list_append(&freq1, ld);
		}
	}
	list_attributes_comparator(&freq1, compare_log_prob);
	list_sort(&freq1, 1);
	printf("\nLetters most preferred by State 1:\n");
	for (i=0; i<list_size(&freq1); i++){
		ld = ((letter_double*)list_get_at(&freq1, i));
			printf("%c: %lf\n", ld->letter, ld->d);
	}
	printf("\n");
  
  fclose(file);
  return 0;
}
示例#13
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;
}
示例#14
0
bool do_search(CURL* curl, bstring name, bool all)
{
    DIR* dir;
    bool printed;
    CURLcode res;
    FILE* fp;
    list_t installed;
    struct bStream* stream;
    long httpcode = 0;
    bstring buffer, fname, sstr;
    bstring ext = bfromcstr(".lua");
    bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/search?q=");
    bstring modpath = osutil_getmodulepath();
    struct dirent* entry;
    list_init(&installed);
    list_attributes_copy(&installed, list_meter_string, 1);
    list_attributes_comparator(&installed, list_comparator_string);

    // Attempt to open the modules directory.
    dir = opendir(modpath->data);
    if (dir == NULL)
    {
        printd(LEVEL_ERROR, "unable to query local repository.\n");
        return 1;
    }

    // Append the temporary search file name.
    bcatcstr(modpath, "/.search");
    bconcat(url, name);

    // Open the file and do the cURL transfer.
    printd(LEVEL_DEFAULT, "querying module repository...\n");
    fp = fopen(modpath->data, "wb");
    curl_easy_setopt(curl, CURLOPT_URL, url->data);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode);
    if (res != 0 || httpcode != 200)
    {
        bdestroy(url);
        bdestroy(name);
        bdestroy(modpath);
        printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode);
        return 1;
    }
    fclose(fp);

    // Print the local results.
    if (all)
        printd(LEVEL_DEFAULT, "all modules:\n");
    else
        printd(LEVEL_DEFAULT, "search results for %s:\n", name->data);
    while ((entry = readdir(dir)) != NULL)
    {
        fname = bfromcstr(&entry->d_name[0]);
        if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (binstr(fname, 0, name) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (entry->d_type != DT_REG)
        {
            bdestroy(fname);
            continue;
        }
        sstr = bmidstr(fname, 0, blength(fname) - 4);
        printd(LEVEL_DEFAULT, "   %s (installed)\n", sstr->data);
        list_append(&installed, sstr->data);
        bdestroy(sstr);
        bdestroy(fname);
    }

    // Print the online results.
    fp = fopen(modpath->data, "r");
    stream = bsopen(&read_data, fp);
    buffer = bfromcstr("");
    printed = false;
    while (bsreadln(buffer, stream, '\n') != BSTR_ERR)
    {
        btrimws(buffer);
        sstr = bmidstr(buffer, 0, blength(buffer) - 4);
        if (!list_contains(&installed, sstr->data))
            printd(LEVEL_DEFAULT, "  %s\n", sstr->data);
        printed = true;
        bdestroy(sstr);
    }
    if (!printed)
        printd(LEVEL_DEFAULT, "   <no online results>\n");
    bsclose(stream);
    fclose(fp);

    // Clean up.
    curl_easy_cleanup(curl);
    return 0;
}
示例#15
0
bool do_install_all(CURL* curl)
{
    // define used variables
    DIR* dir;
    FILE* fp;
    CURLcode res;
    bool printed;
    bool install_status;
    bool something_errored;
    bool if_something_was_installed;
    list_t installed;
    long httpcode = 0;
    struct dirent* entry;
    struct bStream* stream;
    bstring buffer, fname, sstr;
    bstring modpath = osutil_getmodulepath();
    bstring ext = bfromcstr(".lua");
    bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/list");
    list_init(&installed);
    list_attributes_copy(&installed, list_meter_string, 1);
    list_attributes_comparator(&installed, list_comparator_string);

    // Attempt to open the modules directory.
    dir = opendir(modpath->data);
    if (dir == NULL)
    {
        printd(LEVEL_ERROR, "unable to query local repository.\n");
        return 1;
    }

    // add the filename we wish to query to the modules folder path
    bcatcstr(modpath, "/.all_avail");

    // Open the file and do the cURL transfer.
    printd(LEVEL_DEFAULT, "loading a list of all the modules...\n");
    fp = fopen(modpath->data, "wb");
    curl_easy_setopt(curl, CURLOPT_URL, url->data);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode);
    if (res != 0 || httpcode != 200)
    {
        bdestroy(url);
        bdestroy(modpath);
        printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode);
        return 1;
    }
    fclose(fp);


    // create a list of already installed modules
    while ((entry = readdir(dir)) != NULL)
    {
        fname = bfromcstr(&entry->d_name[0]);
        if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (entry->d_type != DT_REG)
        {
            bdestroy(fname);
            continue;
        }
        sstr = bmidstr(fname, 0, blength(fname) - 4);
        list_append(&installed, sstr->data);
        bdestroy(sstr);
        bdestroy(fname);
    }

    printd(LEVEL_DEFAULT, "\n");

    // Print the names of the modules, and install them through the do_install function
    fp = fopen(modpath->data, "r");
    stream = bsopen(&read_data, fp);
    buffer = bfromcstr("");
    printed = false;
    if_something_was_installed = false;
    something_errored = false;
    while (bsreadln(buffer, stream, '\n') != BSTR_ERR)
    {
        btrimws(buffer);
        sstr = bmidstr(buffer, 0, blength(buffer) - 4);

        // if the module is not already installed
        if (!list_contains(&installed, sstr->data))
        {
            install_status = do_install(curl, bfromcstr(sstr->data));
            if_something_was_installed = true;
            // check whether the installation was successful
            if (install_status != 0)
            {
                printd(LEVEL_DEFAULT, "  %s failed to install.\n", sstr->data);
                something_errored = true;
            }
            printd(LEVEL_DEFAULT, "\n");
        }

        printed = true;
        bdestroy(sstr);
    }
    if (!printed)
        printd(LEVEL_DEFAULT, "  <no modules available>\n");
    if (something_errored)
        printd(LEVEL_DEFAULT, "errors occured\n");
    if (!if_something_was_installed)
        printd(LEVEL_DEFAULT, "no changes were made\n");
    bsclose(stream);
    fclose(fp);

    // Clean up.
    curl_easy_cleanup(curl);

    return 0;
}
示例#16
0
/**
 * @brief Creates threads to handle messages received from Clients.
 *
 * @param[in] pdwClientID Connection ID used to reference the Client.
 *
 * @return Error code.
 * @retval SCARD_S_SUCCESS Success.
 * @retval SCARD_F_INTERNAL_ERROR Exceded the maximum number of simultaneous Application Contexts.
 * @retval SCARD_E_NO_MEMORY Error creating the Context Thread.
 */
LONG CreateContextThread(uint32_t *pdwClientID)
{
	int rv;
	int lrv;
	int listSize;
	SCONTEXT * newContext = NULL;
	LONG retval = SCARD_E_NO_MEMORY;

	(void)pthread_mutex_lock(&contextsList_lock);

	listSize = list_size(&contextsList);
	if (listSize >= contextMaxThreadCounter)
	{
		Log2(PCSC_LOG_CRITICAL, "Too many context running: %d", listSize);
		goto out;
	}

	/* Create the context for this thread. */
	newContext = malloc(sizeof(*newContext));
	if (NULL == newContext)
	{
		Log1(PCSC_LOG_CRITICAL, "Could not allocate new context");
		goto out;
	}
	memset(newContext, 0, sizeof(*newContext));

	newContext->dwClientID = *pdwClientID;

	/* Initialise the list of card contexts */
	lrv = list_init(&newContext->cardsList);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL, "list_init failed with return value: %d", lrv);
		goto out;
	}

	/* request to store copies, and provide the metric function */
	list_attributes_copy(&newContext->cardsList, list_meter_int32_t, 1);

	/* Adding a comparator
	 * The stored type is SCARDHANDLE (long) but has only 32 bits
	 * usefull even on a 64-bit CPU since the API between pcscd and
	 * libpcscliter uses "int32_t hCard;"
	 */
	lrv = list_attributes_comparator(&newContext->cardsList,
		list_comparator_int32_t);
	if (lrv != 0)
	{
		Log2(PCSC_LOG_CRITICAL,
			"list_attributes_comparator failed with return value: %d", lrv);
		list_destroy(&newContext->cardsList);
		goto out;
	}

	(void)pthread_mutex_init(&newContext->cardsList_lock, NULL);

	lrv = list_append(&contextsList, newContext);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL, "list_append failed with return value: %d",
			lrv);
		list_destroy(&newContext->cardsList);
		goto out;
	}

	rv = ThreadCreate(&newContext->pthThread, THREAD_ATTR_DETACHED,
		(PCSCLITE_THREAD_FUNCTION( )) ContextThread, (LPVOID) newContext);
	if (rv)
	{
		int lrv2;

		Log2(PCSC_LOG_CRITICAL, "ThreadCreate failed: %s", strerror(rv));
		lrv2 = list_delete(&contextsList, newContext);
		if (lrv2 < 0)
			Log2(PCSC_LOG_CRITICAL, "list_delete failed with error %d", lrv2);
		list_destroy(&newContext->cardsList);
		goto out;
	}

	/* disable any suicide alarm */
	if (AutoExit)
		alarm(0);

	retval = SCARD_S_SUCCESS;

out:
	(void)pthread_mutex_unlock(&contextsList_lock);

	if (retval != SCARD_S_SUCCESS)
	{
		if (newContext)
			free(newContext);
		(void)close(*pdwClientID);
	}

	return retval;
}
示例#17
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()