Ejemplo n.º 1
0
struct ipmipower_connection *
ipmipower_connection_array_create(const char *hostname, unsigned int *len) 
{
  char *str = NULL;
  int index = 0;
  hostlist_t hl = NULL;
  hostlist_iterator_t itr = NULL;
  struct ipmipower_connection *ics;
  int size = sizeof(struct ipmipower_connection);
  int hl_count;
  int errcount = 0;
  int emfilecount = 0;

  assert(hostname && len); 

  *len = 0;
  
  if (!(hl = hostlist_create(hostname)))
    {
      ipmipower_output(MSG_TYPE_HOSTNAME_INVALID, hostname);
      return NULL;
    }
  
  if (!(itr = hostlist_iterator_create(hl)))
    ierr_exit("hostlist_iterator_create() error"); 
  
  hostlist_uniq(hl);

  hl_count = hostlist_count(hl);

  ics = (struct ipmipower_connection *)Malloc(size * hl_count);
  
  memset(ics, '\0', (size * hl_count));
  
  while ((str = hostlist_next(itr))) 
    {
      ics[index].ipmi_fd = -1;
      ics[index].ping_fd = -1;
      
      /* cleanup only at the end, gather all error outputs for
       * later 
       */
      if (_connection_setup(&ics[index], str) < 0) 
        {
          if (errno == EMFILE && !emfilecount)
            {
              cbuf_printf(ttyout, "file descriptor limit reached\n");
              emfilecount++;
            }
          errcount++;
        }
       
      free(str);
      index++;
    }

  hostlist_iterator_destroy(itr);
  hostlist_destroy(hl);

  if (errcount)
    {
      int i;
      for (i = 0; i < hl_count; i++) 
        {
          close(ics[i].ipmi_fd);
          close(ics[i].ping_fd);
          if (ics[i].ipmi_in)
            cbuf_destroy(ics[i].ipmi_in);
          if (ics[i].ipmi_out)
            cbuf_destroy(ics[i].ipmi_out);
          if (ics[i].ping_in)
            cbuf_destroy(ics[i].ping_in);
          if (ics[i].ping_out)
            cbuf_destroy(ics[i].ping_out);
        }
      Free(ics);
      return NULL;
    }

  *len = hl_count;
  return ics;
}
Ejemplo n.º 2
0
/* 
 * forward_response - send request to server, then store resposne content
 * in cache if necessary 
 */
int forward_response(int client_fd, int server_fd, Response *response) {
    #ifdef DEBUG
    printf("enter forward_response\n");
    #endif
    size_t  n;
    int     length = -1;
    int     read_size;
    rio_t   server_rio;
    char header_buffer[MAXLINE];
    char temp_buffer[MAX_OBJECT_SIZE];
    char  buffer[10 * MAX_OBJECT_SIZE];
    char content_buffer[10 * MAX_OBJECT_SIZE];

    rio_readinitb(&server_rio, server_fd);
    int buffer_pos = 0;
    while ((n = rio_readlineb(&server_rio, header_buffer, MAXLINE)) != 0) { 
        memcpy(response->header + buffer_pos, 
                header_buffer, sizeof(char) * n);      
        buffer_pos += n;
        
        /*specify content-length info if header has this info */
        if (strstr(header_buffer, "Content-Length: ")) {
            sscanf(header_buffer + 16, "%d", &length);
        }
        if (!strcmp(header_buffer, "\r\n")) {
            break;
        }
    }

    if (length == -1)
        read_size = MAX_OBJECT_SIZE;
    else 
        read_size = min(length, MAX_OBJECT_SIZE);
    
    #ifdef DEBUG
    printf("finish response header\n");
    #endif

    int sum = 0;
    while ((n = rio_readnb(&server_rio, temp_buffer, read_size)) != 0) { 
        memcpy(content_buffer + sum, temp_buffer, sizeof(char) * n);      
        sum += n;
    }

    memcpy(buffer, response->header, sizeof(char) * buffer_pos);
    memcpy(buffer + buffer_pos, content_buffer,  sizeof(char) * sum);
    if (rio_writen(client_fd, buffer, buffer_pos + sum) < 0) {
            sleep(1);
            if (rio_writen(client_fd, buffer, buffer_pos + sum) < 0) {
                sleep(2);
                if (rio_writen(client_fd, buffer, buffer_pos + sum) < 0)
                    proxy_error("rio_writen in forward_response" 
                            " header content error");
                    return -1;
            }
    }

    #ifdef DEBUG 
    printf("read byte size:%u\n", sum);
    #endif
    
    if (sum <= MAX_OBJECT_SIZE) {
        response->content = Malloc(sizeof(char) * sum);
        memcpy(response->content, content_buffer, sum * sizeof(char)); 
        response->content_size = sum;
    } else {
        response->content_size = sum;
    }

    #ifdef DEBUG
    printf("leave forward_response\n");
    #endif
    return 1;
}
Ejemplo n.º 3
0
//
// Interface functions
//
model* train(const problem *prob, const parameter *param)
{
	problem newprob;
	remove_zero_weight(&newprob, prob);
	prob = &newprob;

	int i,j;
	int l = prob->l;
	int n = prob->n;
	int w_size = prob->n;
	model *model_ = Malloc(model,1);

	if(prob->bias>=0)
		model_->nr_feature=n-1;
	else
		model_->nr_feature=n;
	model_->param = *param;
	model_->bias = prob->bias;

	int nr_class;
	int *label = NULL;
	int *start = NULL;
	int *count = NULL;
	int *perm = Malloc(int,l);

	// group training data of the same class
	group_classes(prob,&nr_class,&label,&start,&count,perm);

	model_->nr_class=nr_class;
	model_->label = Malloc(int,nr_class);
	for(i=0;i<nr_class;i++)
		model_->label[i] = label[i];

	// calculate weighted C
	double *weighted_C = Malloc(double, nr_class);
	for(i=0;i<nr_class;i++)
		weighted_C[i] = param->C;
	for(i=0;i<param->nr_weight;i++)
	{
		for(j=0;j<nr_class;j++)
			if(param->weight_label[i] == label[j])
				break;
		if(j == nr_class)
			fprintf(stderr,"warning: class label %d specified in weight is not found\n", param->weight_label[i]);
		else
			weighted_C[j] *= param->weight[i];
	}

	// constructing the subproblem
	feature_node **x = Malloc(feature_node *,l);
	double *W = Malloc(double,l);
	for(i=0;i<l;i++)
	{
		x[i] = prob->x[perm[i]];
		W[i] = prob->W[perm[i]];
	}

	int k;
	problem sub_prob;
	sub_prob.l = l;
	sub_prob.n = n;
	sub_prob.x = Malloc(feature_node *,sub_prob.l);
	sub_prob.y = Malloc(int,sub_prob.l);
	sub_prob.W = Malloc(double,sub_prob.l);

	for(k=0; k<sub_prob.l; k++)
	{
		sub_prob.x[k] = x[k];
		sub_prob.W[k] = W[k];
	}

	// multi-class svm by Crammer and Singer
	if(param->solver_type == MCSVM_CS)
	{
		model_->w=Malloc(double, n*nr_class);
		for(i=0;i<nr_class;i++)
			for(j=start[i];j<start[i]+count[i];j++)
				sub_prob.y[j] = i;
		Solver_MCSVM_CS Solver(&sub_prob, nr_class, weighted_C, param->eps);
		Solver.Solve(model_->w);
	}
Ejemplo n.º 4
0
static void *OpenSslMallocFun(size_t size) {
	return Malloc(size);
}
Ejemplo n.º 5
0
/* 
 * _event_dump
 *
 * Output event debugging info
 */
static void
_event_dump(struct cerebro_event *event)
{
#if CEREBRO_DEBUG
  if (conf.event_server_debug)
    {
      char *buf;

      Pthread_mutex_lock(&debug_output_mutex);
      fprintf(stderr, "**************************************\n");
      fprintf(stderr, "* Cerebrod Event:\n");
      fprintf(stderr, "* ---------------\n");
      fprintf(stderr, "* Version: %d\n", event->version);
      fprintf(stderr, "* Nodename: %s\n", event->nodename);
      fprintf(stderr, "* Event_Name: %s\n", event->event_name);
      fprintf(stderr, "* Value Type: %d\n", event->event_value_type);
      fprintf(stderr, "* Value Len: %d\n", event->event_value_len);

      switch(event->event_value_type)
        {
        case CEREBRO_DATA_VALUE_TYPE_NONE:
          break;
        case CEREBRO_DATA_VALUE_TYPE_INT32:
          fprintf(stderr, "* Value = %d",
                  *((int32_t *)event->event_value));
          break;
        case CEREBRO_DATA_VALUE_TYPE_U_INT32:
          fprintf(stderr, "* Value = %u",
                  *((u_int32_t *)event->event_value));
          break;
        case CEREBRO_DATA_VALUE_TYPE_FLOAT:
          fprintf(stderr, "* Value = %f",
                  *((float *)event->event_value));
          break;
        case CEREBRO_DATA_VALUE_TYPE_DOUBLE:
          fprintf(stderr, "* Value = %f",
                  *((double *)event->event_value));
          break;
        case CEREBRO_DATA_VALUE_TYPE_STRING:
          /* Watch for NUL termination */
          buf = Malloc(event->event_value_len + 1);
          memset(buf, '\0', event->event_value_len + 1);
          memcpy(buf,
                 event->event_value,
                 event->event_value_len);
          fprintf(stderr, "* Value = %s", buf);
          Free(buf);
          break;
#if SIZEOF_LONG == 4
        case CEREBRO_DATA_VALUE_TYPE_INT64:
          fprintf(stderr, "* Value = %lld",
                  *((int64_t *)event->event_value));
          break;
        case CEREBRO_DATA_VALUE_TYPE_U_INT64:
          fprintf(stderr, "* Value = %llu",
                  *((u_int64_t *)event->event_value));
          break;
#else  /* SIZEOF_LONG == 8 */
        case CEREBRO_DATA_VALUE_TYPE_INT64:
          fprintf(stderr, "* Value = %ld",
                  *((int64_t *)event->event_value));
          break;
        case CEREBRO_DATA_VALUE_TYPE_U_INT64:
          fprintf(stderr, "* Value = %lu",
                  *((u_int64_t *)event->event_value));
          break;
#endif /* SIZEOF_LONG == 8 */
        default:
          break;
        }
      fprintf(stderr, "\n");
      fprintf(stderr, "**************************************\n");
      Pthread_mutex_unlock(&debug_output_mutex);
    }
#endif /* CEREBRO_DEBUG */
}
Ejemplo n.º 6
0
//#ifdef WIN32
int main(int c, char **v)
//#else
//int anago_cui(int c, char **v)
//#endif
{
	mm_init();
	if(c >= 2){
		const struct reader_driver *r = &DRIVER_KAZZO;
#ifdef _UNICODE
		int i;
		wchar_t **v;
		v = Malloc(sizeof(wchar_t *) * c);
		for(i = 0; i < c; i++){
			size_t len = strlen(vv[i]) + 1;
			v[i] = Malloc(sizeof(wchar_t) * len);
			mbstowcs(v[i], vv[i], len);
		}
#endif
		switch(v[1][0]){
		case wgT('x'): case wgT('X'):
			r = &DRIVER_DUMMY; //though down
		case wgT('f'): case wgT('F'):
			program(c, v, r);
			break;
		case wgT('z'): case wgT('R'): case wgT('W'): 
			r = &DRIVER_DUMMY; //though down
		case wgT('d'): case wgT('D'):
		case wgT('r'): case wgT('w'):
			dump(c, v, r);
			break;
		case wgT('V'):
			r = &DRIVER_DUMMY;
		case wgT('v'):
			vram_scan(c, v, r);
			break;
		case wgT('b'):
			crc32_display(c, v);
			break;
		default:
			usage(v[0]);
			PUTS(wgT("mode are d, D, f, g"));
			break;
		}
#ifdef _UNICODE
		for(i = 0; i < c; i++){
			Free(v[i]);
		}
		Free(v);
#endif
	}else{ //usage
#ifdef _UNICODE
		size_t len = strlen(vv[0]) + 1;
		wchar_t *t = Malloc(sizeof(wchar_t) * len);
		mbstowcs(t, vv[0], len);
		usage(t);
		Free(t);
#else
		usage(v[0]);
#endif
	}
	mm_end();
	return 0;
}
Ejemplo n.º 7
0
/* load_config - load configuration from config and rules file */
void load_config (void)
{
    FILE *config, *rules;
    char buf[CONF_MAXLEN], *tok, *beg;
    size_t len, line_cnt, erule_cnt, drule_cnt, srule_cnt, vrule_cnt;
    int state;
    int port;

    /*** load program configuration ***/

    if (NULL == (config = fopen(conf.config_file, "r"))) {
        fprintf(stderr, "Can't read '%s' configuration file.\n",
                conf.config_file);
        usage();
        exit(1);
    }

    line_cnt = 0;

    while (fgets(buf, CONF_MAXLEN, config) != NULL) {
        ++line_cnt;

        if ('#' == buf[0] || '\n' == buf[0])  /* comment or empty line */
            continue;
        /* SMTP Port */
        else if (0 == strncmp("smtp_port = ", buf, 12)) {
            if ((port = atoi(buf+12)) > 0)
                conf.smtp_port = htons(port);
            else
                fprintf(stderr, "Syntax error in config file on line %d"
                       "-- bad SMTP port (smtp_port).\n", line_cnt);
        }
        /* rules file location */
        else if (0 == strncmp("rules = ", buf, 8)) {
            if (NULL != conf.rules_file)
                continue;

            len = strlen(buf+8)+1;
            conf.rules_file = Malloc(len);
            strncpy(conf.rules_file, buf+8, len);
            conf.rules_file[len-2] = '\0';
        }
        /* mail server address */
        else if (0 == strncmp("mail_srv_addr = ", buf, 16)) {
            (buf+16)[strlen(buf+16)-1] = '\0';
            if (1 != inet_pton(AF_INET, buf+16, &(conf.mail_srv.sin_addr))) {
                fprintf(stderr, "Syntax error in config file on line %d"
                       " - not valid mail server address (mail_srv).\n",
                       line_cnt);
                break;
            }
            else
                conf.mail_srv.sin_family = AF_INET;
        }
        /* mail server port */
        else if (0 == strncmp("mail_srv_port = ", buf, 16)) {
            if ((port = atoi(buf+16)) > 0)
                conf.mail_srv.sin_port = htons(port);
            else
                fprintf(stderr, "Syntax error in config file on line %d"
                       "-- bad mail server port (mail_srv_port).\n", line_cnt);
        }

        else
            fprintf(stderr, "Syntax error in config file on line %d.\n",
                    line_cnt);
    }

    fclose(config);

    /* check whether configuration is complete */
    if (0 == conf.mail_srv.sin_port || 0 == conf.mail_srv.sin_family) {
        fprintf(stderr, "Configuration error, mail server address or port "
               "was not set\n");
        exit(1);
    }
    if (0 == conf.smtp_port) {
        conf.smtp_port = htons(DEFAULT_SMTP_PORT);
        fprintf(stderr, "Loaded default SMTP port as none was set.\n");
    }
    /* load default rules file, if none was set */
    if (NULL == conf.rules_file) {
        len = strlen(DEFAULT_RULES_FILE)+1;
        conf.rules_file = Malloc(len);
        strncpy(conf.rules_file, DEFAULT_RULES_FILE, len);
        fprintf(stderr, "Loaded default SMTP port as none was set.\n");
    }


    /*** load encryption/signing rules ***/

    if (NULL == (rules = fopen(conf.rules_file, "r"))) {
        fprintf(stderr, "Can't read '%s' rules file.\n", conf.rules_file);
        exit(1);
    }

    line_cnt = 0;
    conf.encr_rules_size = 0;
    conf.sign_rules_size = 0;
    conf.decr_rules_size = 0;
    conf.vrfy_rules_size = 0;

    /* count encryption/decryption/signing/verification rules */
    while (fgets(buf, CONF_MAXLEN, rules) != NULL) {
        ++line_cnt;

        if ('#' == buf[0] || '\n' == buf[0])  /* comment or empty line */
            continue;
        else if  (0 == strncmp("ENCR ", buf, 5)) /* encryption rule */
            conf.encr_rules_size += 1;
        else if  (0 == strncmp("SIGN ", buf, 5)) /* signing rule */
            conf.sign_rules_size += 1;
        else if  (0 == strncmp("DECR ", buf, 5)) /* decryption rule */
            conf.decr_rules_size += 1;
        else if  (0 == strncmp("VRFY ", buf, 5)) /* verify rule */
            conf.vrfy_rules_size += 1;
        else
            fprintf(stderr, "Syntax error in rules file on line %d.\n",
                    line_cnt);
    }

    /* allocate rule arrays */
    conf.encr_rules = Calloc(conf.encr_rules_size, sizeof(struct encr_rule));
    conf.sign_rules = Calloc(conf.sign_rules_size, sizeof(struct sign_rule));
    conf.decr_rules = Calloc(conf.decr_rules_size, sizeof(struct decr_rule));
    conf.vrfy_rules = Calloc(conf.vrfy_rules_size, sizeof(struct vrfy_rule));

    rewind(rules);
    line_cnt = 0;
    erule_cnt = 0;
    srule_cnt = 0;
    drule_cnt = 0;
    vrule_cnt = 0;

    /* load rules */
    while (fgets(buf, CONF_MAXLEN, rules) != NULL) {
        ++line_cnt;

        if ('#' == buf[0] || '\n' == buf[0])  /* comment or empty line */
            continue;

        /** encryption rule **/
        else if (0 == strncmp("ENCR ", buf, 5)) {
            size_t i;

            beg = buf+5;
            tok = beg;
            len = strlen(tok);

            for (i = 0, state = R_ADDR; i < len; ++i, ++tok) {

                /* space is a separator */
                if (state == R_ADDR && ' ' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    /* fetching recipient address */
                    conf.encr_rules[erule_cnt].rcpt = Malloc(strlen(beg)+1);
                    strcpy(conf.encr_rules[erule_cnt].rcpt, beg);
                    state = R_CERT;     /* now look for certificate key */
                    beg = tok+1;
                    continue;
                }
                /* fetching certificate */
                else if (R_CERT == state && '\n' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    conf.encr_rules[erule_cnt].cert_path =
                        Malloc(strlen(beg)+1);
                    strcpy(conf.encr_rules[erule_cnt].cert_path, beg);

                    /* all needed info fetched, we're done */
                    state = R_DONE;
                    break;
                }
                /* reached end of line before fetching information */
                else if ('\0' == *tok) {
                    state = R_FAIL;
                    break;
                }
            }

            if (R_DONE == state)
                ++erule_cnt;
            else {
                fprintf(stderr, "Syntax error in rules file on line %d.\n",
                        line_cnt);

                if (NULL != conf.encr_rules[erule_cnt].rcpt)
                    free(conf.encr_rules[erule_cnt].rcpt);
                if (NULL != conf.encr_rules[erule_cnt].cert_path)
                    free(conf.encr_rules[erule_cnt].cert_path);
                bzero(conf.encr_rules+erule_cnt, sizeof(struct encr_rule));
            }
        }
        /** signing rule **/
        else if (0 == strncmp("SIGN ", buf, 5)) {
            size_t i;

            beg = buf+5;
            tok = beg;
            len = strlen(tok);

            for (i = 0, state = R_ADDR; i < len; ++i, ++tok) {

                /* space is a separator */
                if (state != R_PASS && ' ' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    /* fetching sender address */
                    if (R_ADDR == state) {
                        conf.sign_rules[srule_cnt].sndr =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.sign_rules[srule_cnt].sndr, beg);

                        state = R_CERT;     /* now look for certificate */
                        beg = tok+1;
                        continue;
                    }
                    /* fetching sender's certificate */
                    else if (R_CERT == state) {
                        conf.sign_rules[srule_cnt].cert_path =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.sign_rules[srule_cnt].cert_path, beg);

                        state = R_PKEY;     /* now look for private key */
                        beg = tok+1;
                        continue;
                    }
                    /* fetching private key */
                    else if (R_PKEY == state) {
                        conf.sign_rules[srule_cnt].key_path =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.sign_rules[srule_cnt].key_path, beg);

                        state = R_PASS; /* now look for private key password */
                        beg = tok+1;
                        continue;
                    }
                }
                /* fetching private key password */
                else if (R_PASS == state && '\n' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    conf.sign_rules[srule_cnt].key_pass =
                        Malloc(strlen(beg)+1);
                    strcpy(conf.sign_rules[srule_cnt].key_pass, beg);

                    /* all needed info fetched, we're done */
                    state = R_DONE;
                    break;
                }
                /* reached end of line before fetching information */
                else if ('\0' == *tok) {
                    state = R_FAIL;
                    break;
                }
            }

            if (R_DONE == state)
                ++srule_cnt;
            else {
                fprintf(stderr, "Syntax error in rules file on line %d.\n",
                        line_cnt);

                if (NULL != conf.sign_rules[srule_cnt].sndr)
                    free(conf.sign_rules[srule_cnt].sndr);
                if (NULL != conf.sign_rules[srule_cnt].cert_path)
                    free(conf.sign_rules[srule_cnt].cert_path);
                if (NULL != conf.sign_rules[srule_cnt].key_path)
                    free(conf.sign_rules[srule_cnt].key_path);
                if (NULL != conf.sign_rules[srule_cnt].key_pass)
                    free(conf.sign_rules[srule_cnt].key_pass);
                bzero(conf.sign_rules+srule_cnt, sizeof(struct sign_rule));
            }
        }
        /** decryption rule **/
        else if (0 == strncmp("DECR ", buf, 5)) {
            size_t i;

            beg = buf+5;
            tok = beg;
            len = strlen(tok);

            for (i = 0, state = R_ADDR; i < len; ++i, ++tok) {

                /* space is a separator */
                if (state != R_PASS && ' ' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    /* fetching recipient address */
                    if (R_ADDR == state) {
                        conf.decr_rules[drule_cnt].rcpt =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.decr_rules[drule_cnt].rcpt, beg);

                        state = R_CERT;     /* now look for certificate */
                        beg = tok+1;
                        continue;
                    }
                    /* fetching sender's certificate */
                    else if (R_CERT == state) {
                        conf.decr_rules[drule_cnt].cert_path =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.decr_rules[drule_cnt].cert_path, beg);

                        state = R_PKEY;     /* now look for private key */
                        beg = tok+1;
                        continue;
                    }
                    /* fetching private key */
                    else if (R_PKEY == state) {
                        conf.decr_rules[drule_cnt].key_path =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.decr_rules[drule_cnt].key_path, beg);

                        state = R_PASS; /* now look for private key password */
                        beg = tok+1;
                        continue;
                    }
                }
                /* fetching private key password */
                else if (R_PASS == state && '\n' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    conf.decr_rules[drule_cnt].key_pass =
                        Malloc(strlen(beg)+1);
                    strcpy(conf.decr_rules[drule_cnt].key_pass, beg);

                    /* all needed info fetched, we're done */
                    state = R_DONE;
                    break;
                }
                /* reached end of line before fetching information */
                else if ('\0' == *tok) {
                    state = R_FAIL;
                    break;
                }
            }

            if (R_DONE == state)
                ++drule_cnt;
            else {
                fprintf(stderr, "Syntax error in rules file on line %d.\n",
                        line_cnt);

                if (NULL != conf.decr_rules[drule_cnt].rcpt)
                    free(conf.decr_rules[drule_cnt].rcpt);
                if (NULL != conf.decr_rules[drule_cnt].cert_path)
                    free(conf.decr_rules[drule_cnt].cert_path);
                if (NULL != conf.decr_rules[drule_cnt].key_path)
                    free(conf.decr_rules[drule_cnt].key_path);
                if (NULL != conf.decr_rules[drule_cnt].key_pass)
                    free(conf.decr_rules[drule_cnt].key_pass);
                bzero(conf.decr_rules+drule_cnt, sizeof(struct decr_rule));
            }
        }
        /** verification rule **/
        else if (0 == strncmp("VRFY ", buf, 5)) {
            size_t i;

            beg = buf+5;
            tok = beg;
            len = strlen(tok);

            for (i = 0, state = R_ADDR; i < len; ++i, ++tok) {

                /* space is a separator */
                if (state != R_CACR && ' ' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    /* fetching sender address */
                    if (R_ADDR == state) {
                        conf.vrfy_rules[vrule_cnt].sndr =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.vrfy_rules[vrule_cnt].sndr, beg);

                        state = R_CERT;     /* now look for certificate */
                        beg = tok+1;
                        continue;
                    }
                    /* fetching sender's certificate */
                    else if (R_CERT == state) {
                        conf.vrfy_rules[vrule_cnt].cert_path =
                            Malloc(strlen(beg)+1);
                        strcpy(conf.vrfy_rules[vrule_cnt].cert_path, beg);

                        state = R_CACR;     /* now look for CA certificate */
                        beg = tok+1;
                        continue;
                    }
                }
                /* fetching CA certificate */
                else if (R_CACR == state && '\n' == *tok) {
                    *tok = '\0';

                    /* field should contain some data... */
                    if (0 == strlen(beg)) {
                        state = R_FAIL;
                        break;
                    }

                    conf.vrfy_rules[vrule_cnt].cacert_path =
                        Malloc(strlen(beg)+1);
                    strcpy(conf.vrfy_rules[vrule_cnt].cacert_path, beg);

                    /* all needed info fetched, we're done */
                    state = R_DONE;
                    break;
                }
                /* reached end of line before fetching information */
                else if ('\0' == *tok) {
                    state = R_FAIL;
                    break;
                }
            }

            if (R_DONE == state)
                ++vrule_cnt;
            else {
                fprintf(stderr, "Syntax error in rules file on line %d.\n",
                        line_cnt);

                if (NULL != conf.vrfy_rules[vrule_cnt].sndr)
                    free(conf.vrfy_rules[vrule_cnt].sndr);
                if (NULL != conf.vrfy_rules[vrule_cnt].cert_path)
                    free(conf.vrfy_rules[vrule_cnt].cert_path);
                if (NULL != conf.vrfy_rules[vrule_cnt].cacert_path)
                    free(conf.vrfy_rules[vrule_cnt].cacert_path);
                bzero(conf.vrfy_rules+vrule_cnt, sizeof(struct vrfy_rule));
            }
        }
        else
            fprintf(stderr, "Syntax error in rules file on line %d.\n",
                    line_cnt);
    }

    fclose(rules);
}
Ejemplo n.º 8
0
int main(int argc, char **argv) {
	char sp1[] = "9878";
	char sp2[] = "9879";

	int maxfd;
	int nready, clientEcho[FD_SETSIZE], clientTime[FD_SETSIZE];
	ssize_t nEcho, nTime;
	fd_set rset, allset;

	int listenfdEcho, *iptrEcho;
	pthread_t tid;
	socklen_t addrlenEcho, lenEcho;
	struct sockaddr *cliaddrEcho;

	int listenfdTime, *iptrTime;
	//	pthread_t tid;
	socklen_t addrlenTime, lenTime;
	struct sockaddr *cliaddrTime;

	if (argc == 1) {
		listenfdEcho = Tcp_listen(NULL, sp1, &addrlenEcho);
		listenfdTime = Tcp_listen(NULL, sp2, &addrlenTime);
	} else
	err_quit("usage: tcpserv01 [ <host> ] <service or port>");

	int oneEcho = 1;
	setsockopt(listenfdEcho, SOL_SOCKET, SO_REUSEADDR, &oneEcho,
		sizeof(oneEcho));

		int oneTime = 1;
		setsockopt(listenfdEcho, SOL_SOCKET, SO_REUSEADDR, &oneTime,
			sizeof(oneTime));

			cliaddrTime = Malloc(addrlenTime);
			cliaddrEcho = Malloc(addrlenEcho);

			FD_ZERO(&allset);
			FD_SET(listenfdEcho, &allset);
			FD_SET(listenfdTime, &allset);

			if (listenfdEcho > listenfdTime)
			maxfd = listenfdEcho;
			else
			maxfd = listenfdTime;

			printf("%s\n\n","waiting for connection" );

			for (;;) {

				rset = allset; /* structure assignment */
				nready = Select(maxfd + 1, &rset, NULL, NULL, NULL);

				if (FD_ISSET(listenfdEcho, &rset)) { /* new client connection */

					lenEcho = addrlenEcho;
					iptrEcho = Malloc(sizeof(int));
					*iptrEcho = Accept(listenfdEcho, cliaddrEcho, &lenEcho);
					Pthread_create(&tid, NULL, &echoFunction, iptrEcho);
					// printf("echo server thread started, thread id: %d \n\n",tid);

				}

				if (FD_ISSET(listenfdTime, &rset)) { /* new client connection */

					lenTime = addrlenTime;
					iptrTime = Malloc(sizeof(int));
					*iptrTime = Accept(listenfdTime, cliaddrTime, &lenTime);
					Pthread_create(&tid, NULL, &timeFunction, iptrTime);
					// printf("time server thread started, thread id: %d \n\n",tid);
				}
			}
		}
Ejemplo n.º 9
0
unsigned int HMQHash(register const char *str)
{
  static unsigned char hmqHashArray[] =
  {
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262,   0, 262, 262, 262, 262,  40, 262, 262, 262,
    262,   0, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262,   0,  20, 115,
     12,  40,   0,  35,  10,  30, 262,  10,   0,  85,
      5,  25,   0, 105,  15,  90,   5,  45, 262,  55,
      0,  15, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262, 262, 262, 262, 262,
    262, 262, 262, 262, 262, 262
  };
  register unsigned int len = strlen(str);

  switch (len)
  {
  default:
    len += hmqHashArray[(unsigned char)(str[15]>64 && str[15]<91?(str[15]|0x20):str[15])];
  case 15:
  case 14:
    len += hmqHashArray[(unsigned char)(str[13]>64 && str[13]<91?(str[13]|0x20):str[13])];
  case 13:
  case 12:
  case 11:
    len += hmqHashArray[(unsigned char)(str[10]>64 && str[10]<91?(str[10]|0x20):str[10])];
  case 10:
    len += hmqHashArray[(unsigned char)(str[9]>64 && str[9]<91?(str[9]|0x20):str[9])];
  case 9:
    break;
  case 8:
  case 7:
  case 6:
  case 5:
  case 4:
  case 3:
  case 2:
  case 1:
    ;
  }
  register unsigned int i = len & hmqHashFactor;
  for(;;)
  {
    if (hmqHashString[i] == NULL)
    {
      hmqHashString[i]=(char*)Malloc(len+1);
      for(int x=0;;x++)
      {
        if ((hmqHashString[i][x]=str[x])==NULL)
          return i;
      }			
    }
    else
      for(int x=0;(str[x]|0x20)==(hmqHashString[i][x]|0x20);x++)
      {
        if (str[x]==NULL)
          return i;
      }		
      i++;
  }
}
Ejemplo n.º 10
0
int _xioopen_proxy_connect(struct single *xfd,
			   struct proxyvars *proxyvars,
			   int level) {
   size_t offset;
   char request[CONNLEN];
   char buff[BUFLEN+1];
#if CONNLEN > BUFLEN
#error not enough buffer space 
#endif
   char textbuff[2*BUFLEN+1];	/* just for sanitizing print data */
   char *eol = buff;
   int state;
   ssize_t sresult;

   /* generate proxy request header - points to final target */
   sprintf(request, "CONNECT %s:%u HTTP/1.0\r\n",
	   proxyvars->targetaddr, proxyvars->targetport);

   /* send proxy CONNECT request (target addr+port) */
   * xiosanitize(request, strlen(request), textbuff) = '\0';
   Info1("sending \"%s\"", textbuff);
   /* write errors are assumed to always be hard errors, no retry */
   do {
      sresult = Write(xfd->wfd, request, strlen(request));
   } while (sresult < 0 && errno == EINTR);
   if (sresult < 0) {
      Msg4(level, "write(%d, %p, "F_Zu"): %s",
	   xfd->wfd, request, strlen(request), strerror(errno));
      if (Close(xfd->wfd) < 0) {
	 Info2("close(%d): %s", xfd->wfd, strerror(errno));
      }
      return STAT_RETRYLATER;
   }

   if (proxyvars->authstring) {
      /* send proxy authentication header */
#     define XIOAUTHHEAD "Proxy-authorization: Basic "
#     define XIOAUTHLEN  27
      static const char *authhead = XIOAUTHHEAD;
#     define HEADLEN 256
      char *header, *next;

      /* ...\r\n\0 */
      if ((header =
	   Malloc(XIOAUTHLEN+((strlen(proxyvars->authstring)+2)/3)*4+3))
	  == NULL) {
	 return -1;
      }
      strcpy(header, authhead);
      next = xiob64encodeline(proxyvars->authstring,
			      strlen(proxyvars->authstring),
			      strchr(header, '\0'));
      *next = '\0';
      Info1("sending \"%s\\r\\n\"", header);
      *next++ = '\r';  *next++ = '\n'; *next++ = '\0';
      do {
	 sresult = Write(xfd->wfd, header, strlen(header));
      } while (sresult < 0 && errno == EINTR);
      if (sresult < 0) {
	 Msg4(level, "write(%d, %p, "F_Zu"): %s",
	      xfd->wfd, header, strlen(header), strerror(errno));
	 if (Close(xfd->wfd/*!*/) < 0) {
	    Info2("close(%d): %s", xfd->wfd, strerror(errno));
	 }
	 return STAT_RETRYLATER;
      }

      free(header);
   }

   Info("sending \"\\r\\n\"");
   do {
      sresult = Write(xfd->wfd, "\r\n", 2);
   } while (sresult < 0 && errno == EINTR);
   /*! */

   /* request is kept for later error messages */
   *strstr(request, " HTTP") = '\0';

   /* receive proxy answer; looks like "HTTP/1.0 200 .*\r\nHeaders..\r\n\r\n" */
   /* socat version 1 depends on a valid fd for data transfer; address
      therefore cannot buffer data. So, to prevent reading beyond the end of
      the answer headers, only single bytes are read. puh. */
   state = XIOSTATE_HTTP1;
   offset = 0;	/* up to where the buffer is filled (relative) */
   /*eol;*/	/* points to the first lineterm of the current line */
   do {
      sresult = xioproxy_recvbytes(xfd, buff+offset, 1, level);
      if (sresult <= 0) {
	 state = XIOSTATE_ERROR;
	 break;	/* leave read cycles */
      }
      
      switch (state) {

      case XIOSTATE_HTTP1:
	 /* 0 or more bytes of first line received, no '\r' yet */
	 if (*(buff+offset) == '\r') {
	    eol = buff+offset;
	    state = XIOSTATE_HTTP2;
	    break;
	 }
	 if (proxyvars->ignorecr && *(buff+offset) == '\n') {
	    eol = buff+offset;
	    state = XIOSTATE_HTTP3;
	    break;
	 }
	 break;

      case XIOSTATE_HTTP2:
	 /* first line received including '\r' */
	 if (*(buff+offset) != '\n') {
	    state = XIOSTATE_HTTP1;
	    break;
	 }
	 state = XIOSTATE_HTTP3;
	 break;

      case XIOSTATE_HTTP3:
	 /* received status (first line) and "\r\n" */
	 if (*(buff+offset) == '\r') {
	    state = XIOSTATE_HTTP7;
	    break;
	 }
	 if (proxyvars->ignorecr && *(buff+offset) == '\n') {
	    state = XIOSTATE_HTTP8;
	    break;
	 }
	 state = XIOSTATE_HTTP4;
	 break;
	 
      case XIOSTATE_HTTP4:
	 /* within header */
	 if (*(buff+offset) == '\r') {
	    eol = buff+offset;
	    state = XIOSTATE_HTTP5;
	    break;
	 }
	 if (proxyvars->ignorecr && *(buff+offset) == '\n') {
	    eol = buff+offset;
	    state = XIOSTATE_HTTP6;
	    break;
	 }
	 break;

      case XIOSTATE_HTTP5:
	 /* within header, '\r' received */
	 if (*(buff+offset) != '\n') {
	    state = XIOSTATE_HTTP4;
	    break;
	 }
	 state = XIOSTATE_HTTP6;
	 break;

      case XIOSTATE_HTTP6:
	 /* received status (first line) and 1 or more headers, "\r\n" */
	 if (*(buff+offset) == '\r') {
	    state = XIOSTATE_HTTP7;
	    break;
	 }
	 if (proxyvars->ignorecr && *(buff+offset) == '\n') {
	    state = XIOSTATE_HTTP8;
	    break;
	 }
	 state = XIOSTATE_HTTP4;
	 break;

      case XIOSTATE_HTTP7:
	 /* received status (first line), 0 or more headers, "\r\n\r" */
	 if (*(buff+offset) == '\n') {
	    state = XIOSTATE_HTTP8;
	    break;
	 }
	 if (*(buff+offset) == '\r') {
	    if (proxyvars->ignorecr) {
	       break;	/* ignore it, keep waiting for '\n' */
	    } else {
	       state = XIOSTATE_HTTP5;
	    }
	    break;
	 }
	 state = XIOSTATE_HTTP4;
	 break;

      }
      ++offset;

      /* end of status line reached */
      if (state == XIOSTATE_HTTP3) {
	 char *ptr;
	 /* set a terminating null - on or after CRLF? */
	 *(buff+offset) = '\0';

	 * xiosanitize(buff, Min(offset, (sizeof(textbuff)-1)>>1), textbuff)
	    = '\0';
	 Info1("proxy_connect: received answer \"%s\"", textbuff);
	 *eol = '\0';
	 * xiosanitize(buff, Min(strlen(buff), (sizeof(textbuff)-1)>>1),
		       textbuff) = '\0';
	 if (strncmp(buff, "HTTP/1.0 ", 9) &&
	     strncmp(buff, "HTTP/1.1 ", 9)) {
	    /* invalid answer */
	    Msg1(level, "proxy: invalid answer \"%s\"", textbuff);
	    return STAT_RETRYLATER;
	 }
	 ptr = buff+9;

	 /* skip multiple spaces */
	 while (*ptr == ' ')  ++ptr;

	 /* HTTP answer */
	 if (strncmp(ptr, "200", 3)) {
	    /* not ok */
	    /* CERN:
	       "HTTP/1.0 200 Connection established"
	       "HTTP/1.0 400 Invalid request "CONNECT 10.244.9.3:8080 HTTP/1.0" (unknown method)"
	       "HTTP/1.0 403 Forbidden - by rule"
	       "HTTP/1.0 407 Proxy Authentication Required"
	       Proxy-Authenticate: Basic realm="Squid proxy-caching web server"
>  50 72 6f 78 79 2d 61 75 74 68 6f 72 69 7a 61 74  Proxy-authorizat
>  69 6f 6e 3a 20 42 61 73 69 63 20 61 57 4e 6f 63  ion: Basic aWNoc
>  32 56 73 59 6e 4e 30 4f 6e 4e 30 63 6d 56 75 5a  2VsYnN0OnN0cmVuZ
>  32 64 6c 61 47 56 70 62 51 3d 3d 0d 0a           2dlaGVpbQ==..
                b64encode("username:password")
	       "HTTP/1.0 500 Can't connect to host"
	    */
	    /* Squid:
	       "HTTP/1.0 400 Bad Request"
	       "HTTP/1.0 403 Forbidden"
	       "HTTP/1.0 503 Service Unavailable"
	       interesting header: "X-Squid-Error: ERR_CONNECT_FAIL 111" */
	    /* Apache:
	       "HTTP/1.0 400 Bad Request"
	       "HTTP/1.1 405 Method Not Allowed"
	    */
	    /* WTE:
	       "HTTP/1.1 200 Connection established"
	       "HTTP/1.1 404 Host not found or not responding, errno:  79"
	       "HTTP/1.1 404 Host not found or not responding, errno:  32"
	       "HTTP/1.1 404 Host not found or not responding, errno:  13"
	    */
	    /* IIS:
	       "HTTP/1.1 404 Object Not Found"
	    */
	    ptr += 3;
	    while (*ptr == ' ')  ++ptr;
	    
	    Msg2(level, "%s: %s", request, ptr);
	    return STAT_RETRYLATER;
	 }

	 /* ok!! */
	 /* "HTTP/1.0 200 Connection established" */
	 /*Info1("proxy: \"%s\"", textbuff+13);*/
	 offset = 0;

      } else if (state == XIOSTATE_HTTP6) {
      /* end of a header line reached */
	 char *endp;

	 /* set a terminating null */
	 *(buff+offset) = '\0';

	 endp =
	    xiosanitize(buff, Min(offset, (sizeof(textbuff)-1)>>1),
			textbuff);
	 *endp = '\0';
	 Info1("proxy_connect: received header \"%s\"", textbuff);
	 offset = 0;
      }
Ejemplo n.º 11
0
/* Code Principal */

int main(void)
{
	int ability,i,fhandle;
	char buffer[2000];
	DTA *mydta;
    char *pmodule;	   
	
	if ((mydta = (long)(Malloc(44))) == NULL)
	  {
	    printf("Erreur Reservation memoire !!!");
	    return -4;
	  }
	  
	Fsetdta(mydta);
	
	printf("\033E");

    /* Initialisation du DSP */

	ability=xbios(113);
	
	if ((Dsp_LoadProg(DSP_CODE,ability,buffer))==0)
	  printf("Chargement du code DSP = OK !!!\n");
	else
	  {
	     printf("Erreur de chargement du programme DSP !!!\n");
	     i=getchar();
	     return -1;
	  }
	  
	/* Chargement du module */
	  
	if (Fsfirst(MODULE,0) == 0)
      if ((pmodule=Malloc(TAILLE_BUFF+(mydta->d_length))) != NULL)
		{
          fhandle=Fopen(MODULE,0 );
		  Fread(fhandle,mydta->d_length,pmodule);
		  Fclose(fhandle);
		}
	  else
	    {
	      printf("Pas assez de memoire !!!\n");
	      i=getchar();
	      return -2;
	    }
	else
	  {
	    printf("Module introuvable\n");
	    i=getchar();
	    return -3;
	  }
	  
	/* Initialisation du player */

	printf("Un petit moment SVP...\n");
	
	if (Player_dtm(0,pmodule,pmodule+mydta->d_length)==-1)
	  {
	     printf("Erreur initialisation du module !!!");
	     i=getchar();
	     return -2;
	  }
	
	printf("Appuyez sur une RETURN...\n");
		
Ejemplo n.º 12
0

/*
 * Allocates and initializes a type and it's basicType info
 * used extensively by asn1.yacc
 * (was a macro)
 */
void
SetupType PARAMS ((t, typeId, lineNum),
    Type **t _AND_
    enum BasicTypeChoiceId typeId _AND_
    unsigned long lineNum)
{
    Tag **tmpPtr;

    (*t) = (Type*)Malloc (sizeof (Type));
    (*t)->lineNo = lineNum;
    (*t)->basicType = (BasicType*)Malloc (sizeof (BasicType));
    (*t)->basicType->choiceId = typeId;
    (*t)->tags = (TagList*)AsnListNew (sizeof (void*));
    if (LIBTYPE_GET_UNIV_TAG_CODE ((typeId)) != NO_TAG_CODE)
    {
         tmpPtr = (Tag**)AsnListAppend ((AsnList*)(*t)->tags);
         *tmpPtr = (Tag*)Malloc (sizeof (Tag));
         (*tmpPtr)->tclass = UNIV;
         (*tmpPtr)->code = LIBTYPE_GET_UNIV_TAG_CODE ((typeId));
    }
} /* SetupType */


/*
Ejemplo n.º 13
0
static void *OpenSslMallocFun(size_t size, const char *file, int line) {
	return Malloc(size);
}
Ejemplo n.º 14
0
/*
 * pmemlog_map_common -- (internal) map a log memory pool
 *
 * This routine does all the work, but takes a rdonly flag so internal
 * calls can map a read-only pool if required.
 */
static PMEMlog *
pmemlog_map_common(int fd, int rdonly)
{
	LOG(3, "fd %d rdonly %d", fd, rdonly);

	struct stat stbuf;
	if (fstat(fd, &stbuf) < 0) {
		LOG(1, "!fstat");
		return NULL;
	}

	if (stbuf.st_size < PMEMLOG_MIN_POOL) {
		LOG(1, "size %lld smaller than %zu",
				(long long)stbuf.st_size, PMEMLOG_MIN_POOL);
		errno = EINVAL;
		return NULL;
	}

	void *addr;
	if ((addr = util_map(fd, stbuf.st_size, rdonly)) == NULL)
		return NULL;	/* util_map() set errno, called LOG */

	/* check if the mapped region is located in persistent memory */
	int is_pmem = pmem_is_pmem(addr, stbuf.st_size);

	/* opaque info lives at the beginning of mapped memory pool */
	struct pmemlog *plp = addr;
	struct pool_hdr hdr;

	memcpy(&hdr, &plp->hdr, sizeof (hdr));

	if (util_convert_hdr(&hdr)) {
		/*
		 * valid header found
		 */
		if (strncmp(hdr.signature, LOG_HDR_SIG, POOL_HDR_SIG_LEN)) {
			LOG(1, "wrong pool type: \"%s\"", hdr.signature);
			errno = EINVAL;
			goto err;
		}

		if (hdr.major != LOG_FORMAT_MAJOR) {
			LOG(1, "log pool version %d (library expects %d)",
				hdr.major, LOG_FORMAT_MAJOR);
			errno = EINVAL;
			goto err;
		}

		uint64_t hdr_start = le64toh(plp->start_offset);
		uint64_t hdr_end = le64toh(plp->end_offset);
		uint64_t hdr_write = le64toh(plp->write_offset);

		if ((hdr_start != roundup(sizeof (*plp),
					LOG_FORMAT_DATA_ALIGN)) ||
			(hdr_end != stbuf.st_size) || (hdr_start > hdr_end)) {
			LOG(1, "wrong start/end offsets (start: %ju end: %ju), "
				"pool size %lld",
				hdr_start, hdr_end, (long long)stbuf.st_size);
			errno = EINVAL;
			goto err;
		}

		if ((hdr_write > hdr_end) || (hdr_write < hdr_start)) {
			LOG(1, "wrong write offset "
				"(start: %ju end: %ju write: %ju)",
				hdr_start, hdr_end, hdr_write);
			errno = EINVAL;
			goto err;
		}

		LOG(3, "start: %ju, end: %ju, write: %ju",
			hdr_start, hdr_end, hdr_write);

		int retval = util_feature_check(&hdr, LOG_FORMAT_INCOMPAT,
							LOG_FORMAT_RO_COMPAT,
							LOG_FORMAT_COMPAT);
		if (retval < 0)
		    goto err;
		else if (retval == 0)
		    rdonly = 1;
	} else {
		/*
		 * no valid header was found
		 */
		if (rdonly) {
			LOG(1, "read-only and no header found");
			errno = EROFS;
			goto err;
		}
		LOG(3, "creating new log memory pool");

		struct pool_hdr *hdrp = &plp->hdr;

		memset(hdrp, '\0', sizeof (*hdrp));
		strncpy(hdrp->signature, LOG_HDR_SIG, POOL_HDR_SIG_LEN);
		hdrp->major = htole32(LOG_FORMAT_MAJOR);
		hdrp->compat_features = htole32(LOG_FORMAT_COMPAT);
		hdrp->incompat_features = htole32(LOG_FORMAT_INCOMPAT);
		hdrp->ro_compat_features = htole32(LOG_FORMAT_RO_COMPAT);
		uuid_generate(hdrp->uuid);
		hdrp->crtime = htole64((uint64_t)time(NULL));
		util_checksum(hdrp, sizeof (*hdrp), &hdrp->checksum, 1);
		hdrp->checksum = htole64(hdrp->checksum);

		/* store pool's header */
		libpmem_persist(is_pmem, hdrp, sizeof (*hdrp));

		/* create rest of required metadata */
		plp->start_offset = htole64(roundup(sizeof (*plp),
						LOG_FORMAT_DATA_ALIGN));
		plp->end_offset = htole64(stbuf.st_size);
		plp->write_offset = plp->start_offset;

		/* store non-volatile part of pool's descriptor */
		libpmem_persist(is_pmem, &plp->start_offset,
							3 * sizeof (uint64_t));
	}

	/*
	 * Use some of the memory pool area for run-time info.  This
	 * run-time state is never loaded from the file, it is always
	 * created here, so no need to worry about byte-order.
	 */
	plp->addr = addr;
	plp->size = stbuf.st_size;
	plp->rdonly = rdonly;
	plp->is_pmem = is_pmem;

	if ((plp->rwlockp = Malloc(sizeof (*plp->rwlockp))) == NULL) {
		LOG(1, "!Malloc for a RW lock");
		goto err;
	}

	if (pthread_rwlock_init(plp->rwlockp, NULL)) {
		LOG(1, "!pthread_rwlock_init");
		goto err_free;
	}

	/*
	 * If possible, turn off all permissions on the pool header page.
	 *
	 * The prototype PMFS doesn't allow this when large pages are in
	 * use. It is not considered an error if this fails.
	 */
	util_range_none(addr, sizeof (struct pool_hdr));

	/* the rest should be kept read-only (debug version only) */
	RANGE_RO(addr + sizeof (struct pool_hdr),
			stbuf.st_size - sizeof (struct pool_hdr));

	LOG(3, "plp %p", plp);
	return plp;

err_free:
	Free((void *)plp->rwlockp);
err:
	LOG(4, "error clean up");
	int oerrno = errno;
	util_unmap(addr, stbuf.st_size);
	errno = oerrno;
	return NULL;
}
Ejemplo n.º 15
0
BUF *HttpRequestEx3(URL_DATA *data, INTERNET_SETTING *setting,
					UINT timeout_connect, UINT timeout_comm,
					UINT *error_code, bool check_ssl_trust, char *post_data,
					WPC_RECV_CALLBACK *recv_callback, void *recv_callback_param, void *sha1_cert_hash, UINT num_hashes,
					bool *cancel, UINT max_recv_size, char *header_name, char *header_value)
{
	WPC_CONNECT con;
	SOCK *s;
	HTTP_HEADER *h;
	bool use_http_proxy = false;
	char target[MAX_SIZE * 4];
	char *send_str;
	BUF *send_buf;
	BUF *recv_buf;
	UINT http_error_code;
	char len_str[100];
	UINT content_len;
	void *socket_buffer;
	UINT socket_buffer_size = WPC_RECV_BUF_SIZE;
	UINT num_continue = 0;
	INTERNET_SETTING wt_setting;
	// Validate arguments
	if (data == NULL)
	{
		return NULL;
	}
	if (setting == NULL)
	{
		Zero(&wt_setting, sizeof(wt_setting));
		setting = &wt_setting;
	}
	if (error_code == NULL)
	{
		static UINT ret = 0;
		error_code = &ret;
	}
	if (timeout_comm == 0)
	{
		timeout_comm = WPC_TIMEOUT;
	}
	if (sha1_cert_hash == NULL)
	{
		num_hashes = 0;
	}
	if (num_hashes == 0)
	{
		sha1_cert_hash = NULL;
	}

	// Connection
	Zero(&con, sizeof(con));
	StrCpy(con.HostName, sizeof(con.HostName), data->HostName);
	con.Port = data->Port;
	con.ProxyType = setting->ProxyType;
	StrCpy(con.ProxyHostName, sizeof(con.ProxyHostName), setting->ProxyHostName);
	con.ProxyPort = setting->ProxyPort;
	StrCpy(con.ProxyUsername, sizeof(con.ProxyUsername), setting->ProxyUsername);
	StrCpy(con.ProxyPassword, sizeof(con.ProxyPassword), setting->ProxyPassword);

	if (setting->ProxyType != PROXY_HTTP || data->Secure)
	{
		use_http_proxy = false;
		StrCpy(target, sizeof(target), data->Target);
	}
	else
	{
		use_http_proxy = true;
		CreateUrl(target, sizeof(target), data);
	}

	if (use_http_proxy == false)
	{
		// If the connection is not via HTTP Proxy, or is a SSL connection even via HTTP Proxy
		s = WpcSockConnectEx(&con, error_code, timeout_connect, cancel);
	}
	else
	{
		// If the connection is not SSL via HTTP Proxy
		s = TcpConnectEx3(con.ProxyHostName, con.ProxyPort, timeout_connect, cancel, NULL, true, NULL, false, false, NULL);
		if (s == NULL)
		{
			*error_code = ERR_PROXY_CONNECT_FAILED;
		}
	}

	if (s == NULL)
	{
		return NULL;
	}

	if (data->Secure)
	{
		// Start the SSL communication
		if (StartSSLEx(s, NULL, NULL, true, 0, (IsEmptyStr(data->SniString) ? NULL : data->SniString)) == false)
		{
			// SSL connection failed
			*error_code = ERR_PROTOCOL_ERROR;
			Disconnect(s);
			ReleaseSock(s);
			return NULL;
		}

		if (sha1_cert_hash != NULL && num_hashes >= 1)
		{
			UCHAR hash[SHA1_SIZE];
			UINT i;
			bool ok = false;

			Zero(hash, sizeof(hash));
			GetXDigest(s->RemoteX, hash, true);

			for (i = 0;i < num_hashes;i++)
			{
				UCHAR *a = (UCHAR *)sha1_cert_hash;
				a += (SHA1_SIZE * i);

				if (Cmp(hash, a, SHA1_SIZE) == 0)
				{
					ok = true;
					break;
				}
			}

			if (ok == false)
			{
				// Destination certificate hash mismatch
				*error_code = ERR_CERT_NOT_TRUSTED;
				Disconnect(s);
				ReleaseSock(s);
				return NULL;
			}
		}
	}

	// Timeout setting
	SetTimeout(s, timeout_comm);

	// Generate a request
	h = NewHttpHeader(data->Method, target, use_http_proxy ? "HTTP/1.0" : "HTTP/1.1");
	AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
	AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
	AddHttpValue(h, NewHttpValue("Accept-Language", "ja"));
	AddHttpValue(h, NewHttpValue("User-Agent", WPC_USER_AGENT));
	AddHttpValue(h, NewHttpValue("Pragma", "no-cache"));
	AddHttpValue(h, NewHttpValue("Cache-Control", "no-cache"));
	AddHttpValue(h, NewHttpValue("Host", data->HeaderHostName));

	if (IsEmptyStr(header_name) == false && IsEmptyStr(header_value) == false)
	{
		AddHttpValue(h, NewHttpValue(header_name, header_value));
	}

	if (IsEmptyStr(data->Referer) == false)
	{
		AddHttpValue(h, NewHttpValue("Referer", data->Referer));
	}

	if (StrCmpi(data->Method, WPC_HTTP_POST_NAME) == 0)
	{
		ToStr(len_str, StrLen(post_data));
		AddHttpValue(h, NewHttpValue("Content-Type", "application/x-www-form-urlencoded"));
		AddHttpValue(h, NewHttpValue("Content-Length", len_str));
	}

	if (IsEmptyStr(data->AdditionalHeaderName) == false && IsEmptyStr(data->AdditionalHeaderValue) == false)
	{
		AddHttpValue(h, NewHttpValue(data->AdditionalHeaderName, data->AdditionalHeaderValue));
	}

	if (use_http_proxy)
	{
		AddHttpValue(h, NewHttpValue("Proxy-Connection", "Keep-Alive"));

		if (IsEmptyStr(setting->ProxyUsername) == false || IsEmptyStr(setting->ProxyPassword) == false)
		{
			char auth_tmp_str[MAX_SIZE], auth_b64_str[MAX_SIZE * 2];
			char basic_str[MAX_SIZE * 2];

			// Generate the authentication string
			Format(auth_tmp_str, sizeof(auth_tmp_str), "%s:%s",
				setting->ProxyUsername, setting->ProxyPassword);

			// Base64 encode
			Zero(auth_b64_str, sizeof(auth_b64_str));
			Encode64(auth_b64_str, auth_tmp_str);
			Format(basic_str, sizeof(basic_str), "Basic %s", auth_b64_str);

			AddHttpValue(h, NewHttpValue("Proxy-Authorization", basic_str));
		}
	}

	send_str = HttpHeaderToStr(h);
	FreeHttpHeader(h);

	send_buf = NewBuf();
	WriteBuf(send_buf, send_str, StrLen(send_str));
	Free(send_str);

	// Append to the sending data in the case of POST
	if (StrCmpi(data->Method, WPC_HTTP_POST_NAME) == 0)
	{
		WriteBuf(send_buf, post_data, StrLen(post_data));
	}

	// Send
	if (SendAll(s, send_buf->Buf, send_buf->Size, s->SecureMode) == false)
	{
		Disconnect(s);
		ReleaseSock(s);
		FreeBuf(send_buf);

		*error_code = ERR_DISCONNECTED;

		return NULL;
	}

	FreeBuf(send_buf);

CONT:
	// Receive
	h = RecvHttpHeader(s);
	if (h == NULL)
	{
		Disconnect(s);
		ReleaseSock(s);

		*error_code = ERR_DISCONNECTED;

		return NULL;
	}

	http_error_code = 0;
	if (StrLen(h->Method) == 8)
	{
		if (Cmp(h->Method, "HTTP/1.", 7) == 0)
		{
			http_error_code = ToInt(h->Target);
		}
	}

	*error_code = ERR_NO_ERROR;

	switch (http_error_code)
	{
	case 401:
	case 407:
		// Proxy authentication error
		*error_code = ERR_PROXY_AUTH_FAILED;
		break;

	case 404:
		// 404 File Not Found
		*error_code = ERR_OBJECT_NOT_FOUND;
		break;

	case 100:
		// Continue
		num_continue++;
		if (num_continue >= 10)
		{
			goto DEF;
		}
		FreeHttpHeader(h);
		goto CONT;

	case 200:
		// Success
		break;

	default:
		// Protocol error
DEF:
		*error_code = ERR_PROTOCOL_ERROR;
		break;
	}

	if (*error_code != ERR_NO_ERROR)
	{
		// An error has occured
		Disconnect(s);
		ReleaseSock(s);
		FreeHttpHeader(h);
		return NULL;
	}

	// Get the length of the content
	content_len = GetContentLength(h);
	if (max_recv_size != 0)
	{
		content_len = MIN(content_len, max_recv_size);
	}

	FreeHttpHeader(h);

	socket_buffer = Malloc(socket_buffer_size);

	// Receive the content
	recv_buf = NewBuf();

	while (true)
	{
		UINT recvsize = MIN(socket_buffer_size, content_len - recv_buf->Size);
		UINT size;

		if (recv_callback != NULL)
		{
			if (recv_callback(recv_callback_param,
				content_len, recv_buf->Size, recv_buf) == false)
			{
				// Cancel the reception
				*error_code = ERR_USER_CANCEL;
				goto RECV_CANCEL;
			}
		}

		if (recvsize == 0)
		{
			break;
		}

		size = Recv(s, socket_buffer, recvsize, s->SecureMode);
		if (size == 0)
		{
			// Disconnected
			*error_code = ERR_DISCONNECTED;

RECV_CANCEL:
			FreeBuf(recv_buf);
			Free(socket_buffer);
			Disconnect(s);
			ReleaseSock(s);

			return NULL;
		}

		WriteBuf(recv_buf, socket_buffer, size);
	}

	SeekBuf(recv_buf, 0, 0);
	Free(socket_buffer);

	Disconnect(s);
	ReleaseSock(s);

	// Transmission
	return recv_buf;
}
Ejemplo n.º 16
0
void init_object()
{
  /* local variables */
  NeighObjectType* NeighObject;
  int status;
  int u_f;
  int u_s;
  int i;

  /* Allocate memory for KIM objects */
  g_kim.pkimObj = (void**) Malloc(g_config.nconf * sizeof(void *));

  for (i = 0; i < g_config.nconf; i++) {

    /* write descriptor file */
    u_f = g_config.useforce[i];
    u_s = 0;
#if defined(STRESS)
    u_s = g_config.usestress[i];
#endif
    status = write_final_descriptor_file(u_f, u_s);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "write_final_descriptor file", status);
      exit(1);
    }

    /* QUESTION: does each config has the same number of species? e.g. there are
     * two types of species, but a specific config may one have one species). If
     * not, then ntypes below need to be modified from config to config */
    /* Answer: actually this does not need any worry. If there is only one species in
     * the whole configuration, but we let ntypes = 2 in the following function call,
     * we just allocate more memory. But the species code for each atom would be
     * correct(see function init_KIM_API_argument). Then KIM Model would know how to
     * do the force calculation. */

    /* init KIM API object and allocate memory for data argument */
    status = setup_KIM_API_object(&g_kim.pkimObj[i], g_config.inconf[i], g_param.ntypes, g_kim.kim_model_name);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "setup_KIM_API_object", status);
      exit(1);
    }

    /* init KIM API argument values */
    init_KIM_API_argument(g_kim.pkimObj[i], g_config.inconf[i], g_param.ntypes, g_config.cnfstart[i]);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "init_KIM_API_argument", status);
      exit(1);
    }

    /* allocate memory for NeighObject */
    NeighObject = (NeighObjectType*) Malloc(sizeof(NeighObjectType));

		/* register access of neighborlist in KIM API */
    setup_neighborlist_KIM_access(g_kim.pkimObj[i], NeighObject);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "setup_neighborlist_KIM_access", status);
      exit(1);
    }

    /* initialize neighbor list */
    status = init_neighborlist(NeighObject, g_config.inconf[i], g_config.cnfstart[i]);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__,"init_nieghborlist",status);
      exit(1);
    }
  }
}
Ejemplo n.º 17
0
/*
 *	make_trans -- Construct a single transform payload
 *
 *	Inputs:
 *
 *	length	(output) length of entire transform payload.
 *	next    Next Payload Type (3 = More transforms; 0=No more transforms)
 *	number	Transform number
 *	cipher	The encryption algorithm
 *	keylen	Key length for variable length keys (0=fixed key length)
 *	hash	Hash algorithm
 *	auth	Authentication method
 *	group	DH Group number
 *	lifetime	Lifetime in seconds (0=no lifetime)
 *	lifesize	Life in kilobytes (0=no life)
 *
 *	Returns:
 *
 *	Pointer to transform payload.
 *
 *	This constructs a single transform payload.
 *	Most of the values are defined in RFC 2409 Appendix A.
 */
unsigned char*make_trans(size_t *length, unsigned next, unsigned number,
			 unsigned cipher,
			 unsigned keylen, unsigned hash, unsigned auth,
			 unsigned group,
			 unsigned lifetime, unsigned lifesize, int gss_id_flag,
			 unsigned char *gss_data, size_t gss_data_len)
{

	struct isakmp_transform* hdr;   /* Transform header */
	unsigned char *payload;
	unsigned char *attr;
	unsigned char *cp;
	size_t attr_len;                /* Attribute Length */
	size_t len;                     /* Payload Length */

/* Allocate and initialise the transform header */

	hdr = Malloc(sizeof(struct isakmp_transform));
	memset(hdr, '\0', sizeof(struct isakmp_transform));

	hdr->isat_np = next;            /* Next payload type */
	hdr->isat_transnum = number;    /* Transform Number */
	hdr->isat_transid = KEY_IKE;

/* Allocate and initialise the mandatory attributes */

	add_attr(0, NULL, 'B', OAKLEY_ENCRYPTION_ALGORITHM, 0, cipher, NULL);
	add_attr(0, NULL, 'B', OAKLEY_HASH_ALGORITHM, 0, hash, NULL);
	add_attr(0, NULL, 'B', OAKLEY_AUTHENTICATION_METHOD, 0, auth, NULL);
	add_attr(0, NULL, 'B', OAKLEY_GROUP_DESCRIPTION, 0, group, NULL);

/* Allocate and initialise the optional attributes */

	if (keylen)
		add_attr(0, NULL, 'B', OAKLEY_KEY_LENGTH, 0, keylen, NULL);

	if (lifetime) {
		uint32_t lifetime_n = htonl(lifetime);

		add_attr(0, NULL, 'B', OAKLEY_LIFE_TYPE, 0,
			 SA_LIFE_TYPE_SECONDS, NULL);
		add_attr(0, NULL, 'V', OAKLEY_LIFE_DURATION, 4, 0,
			 &lifetime_n);
	}

	if (lifesize) {
		uint32_t lifesize_n = htonl(lifesize);

		add_attr(0, NULL, 'B', OAKLEY_LIFE_TYPE, 0,
			 SA_LIFE_TYPE_KBYTES, NULL);
		add_attr(0, NULL, 'V', OAKLEY_LIFE_DURATION, 4, 0,
			 &lifesize_n);
	}

	if (gss_id_flag)
		add_attr(0, NULL, 'V', OAKLEY_GSS_ID, gss_data_len, 0,
			 gss_data);

/* Finalise attributes and fill in length value */

	attr = add_attr(1, &attr_len, '\0', 0, 0, 0, NULL);
	len = attr_len + sizeof(struct isakmp_transform);
	hdr->isat_length = htons(len);  /* Transform length */
	*length = len;

/* Allocate memory for payload and copy structures to payload */

	payload = Malloc(len);

	cp = payload;
	memcpy(cp, hdr, sizeof(struct isakmp_transform));
	free(hdr);
	cp += sizeof(struct isakmp_transform);
	memcpy(cp, attr, attr_len);
	free(attr);

	return payload;
}
Ejemplo n.º 18
0
int get_free_param_double(void* pkim, FreeParamType* FreeParam)
{
  /*local vars*/
  int status;
  int NumFreeParam;
  int maxStringLength;
  char* pstr;
  char buffer[128];
  char name[64];
  char type[16];
  int NumFreeParamDouble;
  int i;

  /* get the maxStringLength of free parameters */
  status = KIM_API_get_num_free_params(pkim, &NumFreeParam, &maxStringLength);
  if (KIM_STATUS_OK > status) {
    KIM_API_report_error(__LINE__, __FILE__, "KIM_API_get_num_free_params", status);
    return(status);
  }

  /* get the descriptor file, pointed by pstr. the type of data will be phrased from pstr*/
  status = KIM_API_get_model_kim_str(g_kim.kim_model_name, &pstr);
  if (KIM_STATUS_OK > status) {
    KIM_API_report_error(__LINE__, __FILE__, "KIM_API_get_model_kim_str", status);
    return(status);
  }

  /* infinite loop to find PARAM_FREE_* of type `double' */
  /* It's safe to do pstr = strstr(pstr+1,"PARAM_FREE") because the ``PARAM_FREE''
    will never ever occur at the beginning of the ``descriptor.kim'' file */
  FreeParam->name = NULL;
  NumFreeParamDouble = 0;
  while (1) {
    pstr = strstr(pstr+1,"PARAM_FREE");
    if (pstr == NULL) {
      break;
    } else {
      snprintf(buffer, sizeof(buffer), "%s", pstr);
      sscanf(buffer, "%s%s", name, type);
      if (strcmp(type, "double") == 0) {
        NumFreeParamDouble++;
        FreeParam->name = (char**) Realloc(FreeParam->name, (NumFreeParamDouble)*sizeof(char*));

        /*maxStringLength+1 to hold the `\0' at end*/
        FreeParam->name[NumFreeParamDouble - 1] = (char*) Malloc((maxStringLength+1)*sizeof(char));
        strcpy(FreeParam->name[NumFreeParamDouble - 1], name);
      }
    }
  }


  FreeParam->Nparam = NumFreeParamDouble;

  /* allocate memory for value */
  FreeParam->value = (double**) Malloc(FreeParam->Nparam * sizeof(double*));

  /* get the pointer to parameter */
  for(i = 0; i < FreeParam->Nparam; i++ ) {
    FreeParam->value[i] = KIM_API_get_data(pkim, FreeParam->name[i], &status);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "KIM_API_get_data", status);
      return(status);
    }
  }

  /* allocate memory for rank */
  FreeParam->rank = (int*) Malloc(FreeParam->Nparam * sizeof(int));

	/* get rank */
  for(i = 0; i < FreeParam->Nparam; i++) {
    FreeParam->rank[i] = KIM_API_get_rank(pkim, FreeParam->name[i], &status);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "KIM_API_get_rank", status);
      return(status);
    }
  }

  /* allocate memory for shape */
  FreeParam->shape = (int**) Malloc(FreeParam->Nparam * sizeof(int*));

	for (i = 0; i < FreeParam->Nparam; i++) {
    if (FreeParam->rank[i] != 0) {
      FreeParam->shape[i] = (int*) Malloc(FreeParam->rank[i] * sizeof(int));
    }
  }
  /* get shape */
  for(i = 0; i < FreeParam->Nparam; i++) {
    KIM_API_get_shape(pkim, FreeParam->name[i], FreeParam->shape[i], &status);
    if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "KIM_API_get_shape", status);
      return(status);
    }
  }

  /* nestedvalue is not allocated here, give NULL pointer to it */
  FreeParam->nestedvalue = NULL;

  /* free the memory of model kim str */
  free(pstr);

  return KIM_STATUS_OK;
}
Ejemplo n.º 19
0
/*
 * heap_buckets_init -- (internal) initializes bucket instances
 */
static int
heap_buckets_init(PMEMobjpool *pop)
{
    struct pmalloc_heap *h = pop->heap;
    int i;

    bucket_proto[0].unit_max = RUN_UNIT_MAX;

    /*
     * To take use of every single bit available in the run the unit size
     * would have to be calculated using following expression:
     * (RUNSIZE / (MAX_BITMAP_VALUES * BITS_PER_VALUE)), but to preserve
     * cacheline alignment a little bit of memory at the end of the run
     * is left unused.
     */
    bucket_proto[0].unit_size = MIN_RUN_SIZE;

    for (i = 1; i < MAX_BUCKETS - 1; ++i) {
        bucket_proto[i].unit_max = RUN_UNIT_MAX;
        bucket_proto[i].unit_size =
            bucket_proto[i - 1].unit_size *
            bucket_proto[i - 1].unit_max;
    }

    bucket_proto[i].unit_max = -1;
    bucket_proto[i].unit_size = CHUNKSIZE;

    h->last_run_max_size = bucket_proto[i - 1].unit_size *
                           (bucket_proto[i - 1].unit_max - 1);

    h->bucket_map = Malloc(sizeof (*h->bucket_map) * h->last_run_max_size);
    if (h->bucket_map == NULL)
        goto error_bucket_map_malloc;

    for (i = 0; i < MAX_BUCKETS; ++i) {
        h->buckets[i] = bucket_new(bucket_proto[i].unit_size,
                                   bucket_proto[i].unit_max);
        if (h->buckets[i] == NULL)
            goto error_bucket_new;
    }

    /* XXX better way to fill the bucket map */
    for (i = 0; i < h->last_run_max_size; ++i) {
        for (int j = 0; j < MAX_BUCKETS - 1; ++j) {
            /*
             * Skip the last unit, so that the distribution
             * of buckets in the map is better.
             */
            if ((bucket_proto[j].unit_size *
                    ((bucket_proto[j].unit_max - 1))) >= i) {
                h->bucket_map[i] = h->buckets[j];
                break;
            }
        }
    }

    heap_populate_buckets(pop);

    return 0;

error_bucket_new:
    Free(h->bucket_map);

    for (i = i - 1; i >= 0; --i)
        bucket_delete(h->buckets[i]);
error_bucket_map_malloc:

    return ENOMEM;
}
Ejemplo n.º 20
0
int read_potential_keyword(pot_table_t* pt, char const* filename, FILE* infile)
{
	/* local variables */
  int   i, j, k, ret_val;
  char  buffer[255], name[255];
  fpos_t startpos;
  FreeParamType FreeParam;
	void* pkim;
  int status;

  /* save starting position */
  fgetpos(infile, &startpos);

  /* scan for "type" keyword */
  buffer[0] = '\0';
  name[0] = '\0';
  do {
    if (NULL == fgets(buffer, 255, infile))
      error(1, "Error while reading KIM potential keyword\n");
    sscanf(buffer, "%s", name);
  } while (strncmp(name, "type", 4) != 0 && !feof(infile));
  if (strncmp(name, "type", 4) != 0) {
    error(1, "Keyword 'type' is missing in file: %s.", filename);
  }
  if (1 > sscanf(buffer, "%*s %s", name))
    error(1, "KIM Model name missing in file: %s.", filename);

  /* copy name*/
  strcpy(g_kim.kim_model_name, name);
  printf("\nKIM Model: %s.\n", g_kim.kim_model_name);

  /* find `check_kim_opt_param' or `num_opt_param'. The two keywords are mutually
	 * exculsive, which comes first will be read, and the other one will be ignored. */
  fsetpos(infile, &startpos);

  do {
    if (NULL == fgets(buffer, 255, infile))
      error(1, "Error while reading KIM potentials\n");
    sscanf(buffer, "%s", name);
  } while (strcmp(name, "check_kim_opt_param") != 0
					 && strcmp(name, "num_opt_param") != 0
           && !feof(infile));

	/* read `check_kim_opt_param' or `num_opt_param' */
	if (strncmp(buffer,"check_kim_opt_param", 19) == 0) {

  	/* create a temporary KIM objects to query the info */
		/* write temporary descriptor file */
		write_temporary_descriptor_file(g_kim.kim_model_name);
		/* create KIM object with 1 atom and 1 species */
		status = setup_KIM_API_object(&pkim, 1, 1, g_kim.kim_model_name);
		if (KIM_STATUS_OK > status) {
      KIM_API_report_error(__LINE__, __FILE__, "setup_KIM_API_object", status);
      exit(1);
    }
		/* initialze the data struct for the free parameters with type double */
		get_free_param_double(pkim, &FreeParam);

		printf(" - The following potential parameters are available to fit. Include the\n"
           "name(s) (and the initial value(s) and the corresponding lower and upper\n"
           "boundaries) that you want to optimize in file: %s.\n",filename);
    printf("         param name                 param extent\n");
    printf("        ############               ##############\n");
    for(k = 0; k < FreeParam.Nparam; k++ ) {
      if (strncmp(FreeParam.name[k], "PARAM_FREE_cutoff", 17) == 0){
        continue;
      }
      printf("     %-35s[ ", FreeParam.name[k]);
      for(j = 0; j < FreeParam.rank[k]; j++) {
        printf("%d ", FreeParam.shape[k][j]);
      }
      printf("]\n");
   }
    printf("\n - Note that empty parameter extent (i.e. '[ ]') indicates that the\n"
           "parameter is a scalar.\n");
    printf(" - Also KIM array parameter is row based. While listing the initial\n"
           "values for such parameter, you should ensure that the sequence is\n"
           "correct. For example, if the extent of a parameter `PARAM_FREE_A' is\n"
           "[ 2 2 ], then you should list the initial values as: A[0 0], A[0 1],\n"
           "A[1 0], A[1 1].\n");

	 /* free the temporary kim model */
	  free_model_object(&pkim);
	  exit(1);

  } else if (strncmp(buffer,"num_opt_param", 13) == 0) {
    if(1 != sscanf(buffer, "%*s%d", &g_kim.num_opt_param)) {
      error(1, "Cannot read 'num_opt_param' in file: %s.", filename);
    }
  } else {
    error(1, "Keyword 'num_opt_param' is missing in file: %s.", filename);
  }

  /* allocate memory */
  g_kim.name_opt_param = (char**)Malloc(g_kim.num_opt_param*sizeof(char*));
  g_kim.size_opt_param = (int*)Malloc(g_kim.num_opt_param*sizeof(int));
  for (i = 0; i < g_kim.num_opt_param; i++) {
    g_kim.name_opt_param[i] = (char *)Malloc(255 * sizeof(char));
  }

	/* find parameter names beginning with `PARAM_FREE_*' */
	fsetpos(infile, &startpos);
	for (j = 0; j < g_kim.num_opt_param; j++) {
		buffer[0] = '\0';
		name[0] = '\0';
		do {
			if (NULL == fgets(buffer, 255, infile))
              error(1, "Error while reading KIM potentials\n");
			ret_val = sscanf(buffer, "%s", name);
		} while (strncmp(name, "PARAM_FREE", 10) != 0 && !feof(infile));
		if (feof(infile) ) {
			error(0, "Not enough parameter(s) 'PARAM_FREE_*' in file: %s.\n", filename);
			error(1, "You listed %d parameter(s), but required are %d.\n", j, g_kim.num_opt_param);
		}
		if (ret_val == 1) {
			strcpy(g_kim.name_opt_param[j], name);
		} else {
			error(0, "parameter '%d' in file '%s' corrupted\n.", j + 1, filename);
			error(1, "Each parameter name should be in a single line.\n");
		}
	}

	return 0;
}
Ejemplo n.º 21
0
/* parse_args - parse command-line arguments, exits on failure */
void parse_args (int argc, char **argv)
{
    size_t len;     /* argument length */
    char *arg;      /* current argument */

    bzero(&conf, sizeof(conf));

    /* get program name */
    arg = basename(argv[0]);
    len = strlen(arg)+1;
    conf.prog_name = Malloc(len);
    strncpy(conf.prog_name, arg, len);

    /* get release version */
    len = strlen(VERSION)+1;
    conf.version = Malloc(len);
    strncpy(conf.version, VERSION, len);

    /* parse command-line arguments */
    while (--argc > 0 && (*++argv)[0] == '-') {
        arg = argv[0];

        /* long options */
        if ('-' == arg[1]) {
            /* --version */
            if (0 == strncmp(arg+2, "version", 7) && '\0' == arg[9]) {
                version();
                exit(0);
            }
            /* --help */
            else if (0 == strncmp(arg+2, "help", 4) && '\0' == arg[6]) {
                help();
                exit(0);
            }
            /* --daemon */
            else if (0 == strncmp(arg+2, "daemon", 6) && '\0' == arg[8]) {
                conf.daemon = 1;
            }
            /* --config=FILE */
            else if (0 == strncmp(arg+2, "config", 6)) {
                if ('=' != arg[8] || '\0' == arg[9]) {
                    fprintf(stderr, "No FILE given in 'config' option.\n");
                    usage();
                    exit(1);
                }

                len = strlen(arg+9)+1;
                conf.config_file = Malloc(len);
                strncpy(conf.config_file, arg+9, len);
            }
            /* --rules=FILE */
            else if (0 == strncmp(arg+2, "rules", 5)) {
                if ('=' != arg[7] || '\0' == arg[8]) {
                    fprintf(stderr, "No FILE given in 'rules' option.\n");
                    usage();
                    exit(1);
                }

                len = strlen(arg+8)+1;
                conf.rules_file = Malloc(len);
                strncpy(conf.rules_file, arg+8, len);
            }
            else {
                fprintf(stderr, "Unknown option.\n");
                usage();
                exit(1);
            }
        }
        /* short options */
        else if ('\0' != arg[1] && '\0' == arg[2]) {
            switch (arg[1]) {
                case 'V':       /* -V */
                    version();
                    exit(0);

                case 'h':       /* -h*/
                    help();
                    exit(0);

                case 'd':       /* -d */
                    conf.daemon = 1;
                    break;

                case 'c':       /* -c FILE */
                    /* FILE should be in the next argument */
                    if (--argc <= 0) {
                        fprintf(stderr, "No FILE given in 'config' option.\n");
                        usage();
                        exit(1);
                    }

                    arg = *++argv;
                    len = strlen(arg)+1;
                    if (NULL != conf.config_file)
                        free(conf.config_file);
                    conf.config_file = Malloc(len);
                    strncpy(conf.config_file, arg, len);
                    break;

                case 'r':       /* -r FILE */
                    /* FILE should be in the next argument */
                    if (--argc <= 0) {
                        fprintf(stderr, "No FILE given in 'rules' option.\n");
                        usage();
                        exit(1);
                    }

                    arg = *++argv;
                    len = strlen(arg)+1;
                    if (NULL != conf.rules_file)
                        free(conf.rules_file);
                    conf.rules_file = Malloc(len);
                    strncpy(conf.rules_file, arg, len);
                    break;

                default:        /* unknown argument */
                    fprintf(stderr, "Unknown option.\n");
                    usage();
                    exit(1);
            }
        }
        /* bad argument format */
        else {
            fprintf(stderr, "Bad argument(s).\n");
            usage();
            exit(1);
        }
    }

    if (0 != argc) {
        fprintf(stderr, "Bad arguments.\n");
        usage();
        exit(1);
    }

    /* load default config file, if none was set */
    if (NULL == conf.config_file) {
        len = strlen(DEFAULT_CONFIG_FILE)+1;
        conf.config_file = Malloc(len);
        strncpy(conf.config_file, DEFAULT_CONFIG_FILE, len);
    }
    /* check if set config file is readable */
    if (0 != access(conf.config_file, R_OK)) {
        fprintf(stderr, "Can't read '%s' configuration file.\n",
                conf.config_file);
        usage();
        exit(1);
    }

    /* check if set rules file is readable (i it was set) */
    else if (NULL != conf.rules_file && 0 != access(conf.rules_file, R_OK)) {
        fprintf(stderr, "Can't read %s file (given in 'rules' option).\n",
                conf.rules_file);
        usage();
        exit(1);
    }

    /* create working directory */
    if (0 != mkdir(DEFAULT_WORKING_DIR, 0755) && EEXIST != errno) {
        fprintf(stderr, "Can't create working directory '%s'.\n",
                DEFAULT_WORKING_DIR);
        exit(1);
    }
}
Ejemplo n.º 22
0
/*
 * parse_url - parse url into uri and CGI args
 *             only care about static request
 */
void parse_url(char *url, char *hostname, char *port) {

    dbg_printf("--------In parse_uri function --------\n");
    dbg_printf("request url is: %s\n", url);

    /* 
     * should handle following urls:
     * eg:  http://localhost:15213/home.html
     *      http://www.cmu.edu:8080/hub/index.html
     *      http://www.cmu.edu/hub/index.html
     *      http://www.cmu.edu
     */ 

    char *url_prt;  // url pointer 
    char *url_end;  // the end of url
    char port_tmp[MAXLINE]; // temp port 

    /* initialization */
    url_prt = Malloc(sizeof(char) * MAXLINE);
    strncpy(url_prt, url, MAXLINE);
    url_end = url_prt + strlen(url_prt);

    /* start parsing url */
    for (url_prt += 7; /* since "http://" has 7 characters */
            url_prt < url_end; url_prt++) {

        /* parse port if exist */
        if (*url_prt == ':') {  
            url_prt++; 
            
            while (url_prt < url_end && *url_prt != '/') {
                sprintf(port_tmp, "%s%c", port_tmp, *url_prt);
                dbg_printf("port_tmp is '%s' \n", port_tmp);
                url_prt++; 
            }

            strcpy(port, port_tmp);
            dbg_printf("request port is '%s' \n", port);
        }

        /* parse hostname */
        if (*url_prt == '/') {
        	strcat(hostname, "\0");
        	dbg_printf("request hostname is '%s' \n", hostname);
        	strcpy(url, url_prt);
        	dbg_printf("request uri is '%s'\n", url);
        	break;
        }
        /* continue loop */
        else { 
            sprintf(hostname, "%s%c", hostname, *url_prt);
        }
    }

    /* handle hostname or url not been updated */
    strcat(hostname, "");
    strcat(url, "");

    dbg_printf("request hostname is '%s' \n", hostname);
    dbg_printf("request uri is '%s'\n", url);
    dbg_printf("request port is '%s' \n", port);

    dbg_printf("--------In parse_uri function END--------\n");
}
Ejemplo n.º 23
0
void *
cerebrod_event_server(void *arg)
{
  int server_fd;

  _event_server_initialize();

  if ((server_fd = _event_server_setup_socket(0)) < 0)
    CEREBRO_EXIT(("event server fd setup failed"));

  for (;;)
    {
      ListIterator eitr;
      struct cerebrod_event_connection_data *ecd;
      struct pollfd *pfds;
      int pfdslen = 0;
      int i;

      /* Note that the list_count won't grow larger after the first
       * mutex block, b/c the cerebrod_event_queue_monitor thread can
       * never add to the event_connections.  It can only shrink it.
       */
      Pthread_mutex_lock(&event_connections_lock);
      if (event_connections)
        pfdslen = List_count(event_connections);
      Pthread_mutex_unlock(&event_connections_lock);

      /* The + 1 is b/c of the server_fd. */
      pfdslen++;

      pfds = Malloc(sizeof(struct pollfd) * pfdslen);
      memset(pfds, '\0', sizeof(struct pollfd) * pfdslen);

      pfds[0].fd = server_fd;
      pfds[0].events = POLLIN;
      pfds[0].revents = 0;

      /* No 'event_connections' if there are no events */
      if (event_connections)
        {
          i = 1;
          Pthread_mutex_lock(&event_connections_lock);
          eitr = List_iterator_create(event_connections);
          while ((ecd = list_next(eitr)))
            {
              pfds[i].fd = ecd->fd;
              pfds[i].events = POLLIN;
              pfds[i].revents = 0;
              i++;
            }
          List_iterator_destroy(eitr);
          Pthread_mutex_unlock(&event_connections_lock);
        }
      
      Poll(pfds, pfdslen, -1);

      /* Deal with the server fd first */
      if (pfds[0].revents & POLLERR)
        CEREBRO_DBG(("server_fd POLLERR"));
      else if (pfds[0].revents & POLLIN)
        {
          unsigned int client_addr_len;
          int fd;
          struct sockaddr_in client_addr;

          client_addr_len = sizeof(struct sockaddr_in);
          if ((fd = accept(server_fd,
                           (struct sockaddr *)&client_addr,
                           &client_addr_len)) < 0)
            server_fd = cerebrod_reinit_socket(server_fd,
                                               0,
                                               _event_server_setup_socket,
                                               "event_server: accept");
          if (fd >= 0)
            _event_server_service_connection(fd);
        }

      /* Deal with the connecting fds */
      for (i = 1; i < pfdslen; i++)
        {
          if (pfds[i].revents & POLLERR)
            {
              CEREBRO_DBG(("fd = %d POLLERR", pfds[i].fd));
              Pthread_mutex_lock(&event_connections_lock);
              _delete_event_connection_fd(pfds[i].fd);
              Pthread_mutex_unlock(&event_connections_lock);
              continue;
            }

          if (pfds[i].revents & POLLIN)
            {
              char buf[CEREBRO_MAX_PACKET_LEN];
              int n;

              /* We should not expect any actual data.  If
               * we get some, just eat it and move on.
               *
               * The common situation is that the client
               * closes the connection.  So we need to delete
               * our fd.
               */

              n = fd_read_n(pfds[i].fd, 
                            buf,
                            CEREBRO_MAX_PACKET_LEN);
              if (n < 0)
                CEREBRO_DBG(("fd_read_n = %s", strerror(errno)));

              if (n <= 0)
                {
#if CEREBRO_DEBUG
                  if (conf.debug && conf.event_server_debug)
                    {
                      Pthread_mutex_lock(&debug_output_mutex);
                      fprintf(stderr, "**************************************\n");
                      fprintf(stderr, "* Event Server Close Fd: %d\n", pfds[i].fd);
                      fprintf(stderr, "**************************************\n");
                      Pthread_mutex_unlock(&debug_output_mutex);
                    }
#endif /* CEREBRO_DEBUG */
                  Pthread_mutex_lock(&event_connections_lock);
                  _delete_event_connection_fd(pfds[i].fd);
                  Pthread_mutex_unlock(&event_connections_lock);
                }
            }
        }
      
      Free(pfds);
    }

  return NULL;			/* NOT REACHED */
}
Ejemplo n.º 24
0
int osd_submit_command(int fd, struct osd_command *command)
{
	int ret;
	struct sg_io_v4 sg;

	memset(&sg, 0, sizeof(sg));
	sg.guard = 'Q';
	sg.request_len = command->cdb_len;
	sg.request = (uint64_t) (uintptr_t) command->cdb;
	sg.max_response_len = sizeof(command->sense);
	sg.response = (uint64_t) (uintptr_t) command->sense;

	if (command->outlen) {
#ifdef KERNEL_SUPPORTS_BSG_IOVEC
		sg.dout_xfer_len = command->outlen;
		sg.dout_xferp = (uint64_t) (uintptr_t) command->outdata;
		sg.dout_iovec_count = command->iov_outlen;
#else
		// The kernel doesn't support BSG iovecs mainly because
		// of a problem going from 32-bit user iovecs to a 64-bit kernel
		// So, just copy the iovecs into a new buffer and use that
		sg_iovec_t *iov = (sg_iovec_t *)(uintptr_t)command->outdata;
		if (command->iov_outlen == 0) {
			sg.dout_xfer_len = command->outlen;
			sg.dout_xferp = (uint64_t) (uintptr_t) command->outdata;
		} else if (command->iov_outlen == 1) {
			sg.dout_xfer_len = iov->iov_len;
			sg.dout_xferp = (uint64_t) (uintptr_t) iov->iov_base;
		} else {
			int i;
			uint8_t *buff = Malloc(command->outlen);
			sg.dout_xferp = (uint64_t) (uintptr_t) buff;
			for (i=0; i<command->iov_outlen; i++) {
				memcpy(buff, iov[i].iov_base, iov[i].iov_len);
				buff += iov[i].iov_len;
			}
			sg.dout_xfer_len = command->outlen;
		}
		sg.dout_iovec_count = 0;
#endif
	}
	if (command->inlen_alloc) {
#ifdef KERNEL_SUPPORTS_BSG_IOVEC
		sg.din_xfer_len = command->inlen_alloc;
		sg.din_xferp = (uint64_t) (uintptr_t) command->indata;
		sg.din_iovec_count = command->iov_inlen;
#else
		if (command->iov_inlen == 0) {
			sg.din_xfer_len = command->inlen_alloc;
			sg.din_xferp = (uint64_t) (uintptr_t) command->indata;
			sg.din_iovec_count = command->iov_inlen;
		} else if (command->iov_inlen == 1) {
			sg_iovec_t *iov = (sg_iovec_t *)command->indata;
			sg.din_xfer_len = iov->iov_len;
			sg.din_xferp = (uint64_t) (uintptr_t) iov->iov_base;
		} else {
			sg.din_xfer_len = command->inlen_alloc;
			sg.din_xferp = (uint64_t) (uintptr_t) (uint8_t*) Malloc(command->inlen_alloc);
		}
		sg.din_iovec_count = 0;
#endif
	}

	/*
	 * Allow 30 sec for entire command.  Some can be
	 * slow, especially with debugging messages on.
	 */
	sg.timeout = 30000;
	sg.usr_ptr = (uint64_t) (uintptr_t) command;
	ret = write(fd, &sg, sizeof(sg));
#ifndef KERNEL_SUPPORTS_BSG_IOVEC
	if (command->outlen && command->iov_outlen > 1) {
		free((void *) (uintptr_t) sg.dout_xferp);
	}
#endif
	if (ret < 0) {
		osd_error_errno("%s: write", __func__);
		return -errno;
	}
	if (ret != sizeof(sg)) {
		osd_error("%s: short write, %d not %zu", __func__, ret,
			  sizeof(sg));
		return -EIO;
	}
	return 0;
}
Ejemplo n.º 25
0
/*
 * _event_server_service_connection
 *
 * Service a connection from a client to receive event packets.  Use
 * wrapper functions minimally, b/c we want to return errors to the
 * user instead of exitting with errors.
 *
 */
static void
_event_server_service_connection(int fd)
{
  int recv_len;
  struct cerebro_event_server_request req;
  struct cerebrod_event_connection_data *ecd = NULL;
  char buf[CEREBRO_MAX_PACKET_LEN];
  char event_name_buf[CEREBRO_MAX_EVENT_NAME_LEN+1];
  char *event_name_ptr = NULL;
  int32_t version;
  int *fdptr = NULL;
  List connections = NULL;

  assert(fd >= 0);

  memset(&req, '\0', sizeof(struct cerebro_event_server_request));
  if ((recv_len = receive_data(fd,
                               CEREBRO_EVENT_SERVER_REQUEST_PACKET_LEN,
                               buf,
                               CEREBRO_MAX_PACKET_LEN,
                               CEREBRO_EVENT_SERVER_PROTOCOL_CLIENT_TIMEOUT_LEN,
                               NULL)) < 0)
    goto cleanup;

  if (recv_len < sizeof(version))
    goto cleanup;

  if (_event_server_request_check_version(buf, recv_len, &version) < 0)
    {
      _event_server_err_only_response(fd,
                                      version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_VERSION_INVALID);
      goto cleanup;
    }

  if (recv_len != CEREBRO_EVENT_SERVER_REQUEST_PACKET_LEN)
    {
      _event_server_err_only_response(fd,
                                      version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_PACKET_INVALID);
      goto cleanup;
    }

  if (_event_server_request_unmarshall(&req, buf, recv_len) < 0)
    {
      _event_server_err_only_response(fd,
                                      version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_PACKET_INVALID);
      goto cleanup;
    }

  _event_server_request_dump(&req);

  /* Guarantee ending '\0' character */
  memset(event_name_buf, '\0', CEREBRO_MAX_EVENT_NAME_LEN+1);
  memcpy(event_name_buf, req.event_name, CEREBRO_MAX_EVENT_NAME_LEN);

  if (!strlen(event_name_buf))
    {
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_EVENT_INVALID);
      goto cleanup;
    }

  /* Is it the special event-names request */
  if (!strcmp(event_name_buf, CEREBRO_EVENT_NAMES))
    {
      pthread_t thread;
      pthread_attr_t attr;
      int *arg;

      Pthread_attr_init(&attr);
      Pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
      Pthread_attr_setstacksize(&attr, CEREBROD_THREAD_STACKSIZE);
      arg = Malloc(sizeof(int));
      *arg = fd;
      Pthread_create(&thread,
                     &attr,
                     _respond_with_event_names,
                     (void *)arg);
      Pthread_attr_destroy(&attr);
      return;
    }

  if (!event_names)
    {
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_EVENT_INVALID);
      goto cleanup;
    }

  /* Event names is not changeable - so no need for a lock */
  if (!(event_name_ptr = list_find_first(event_names, 
                                         _event_names_compare,
                                         event_name_buf)))
    {
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_EVENT_INVALID);
      goto cleanup;
    }
  
  if (!(ecd = (struct cerebrod_event_connection_data *)malloc(sizeof(struct cerebrod_event_connection_data))))
    {
      CEREBRO_ERR(("malloc: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }
  
  ecd->event_name = event_name_ptr;
  ecd->fd = fd;
  
  if (!(fdptr = (int *)malloc(sizeof(int))))
    {
      CEREBRO_ERR(("malloc: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }
  *fdptr = fd;

  Pthread_mutex_lock(&event_connections_lock);
  if (!list_append(event_connections, ecd))
    {
      CEREBRO_ERR(("list_append: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }

  if (!(connections = Hash_find(event_connections_index, 
                                ecd->event_name)))
    {
      if (!(connections = list_create((ListDelF)free)))
        {
          CEREBRO_ERR(("list_create: %s", strerror(errno)));
          _event_server_err_only_response(fd,
                                          req.version,
                                          CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
          goto cleanup;
        }

      if (!Hash_insert(event_connections_index, ecd->event_name, connections))
        {
          CEREBRO_ERR(("Hash_insert: %s", strerror(errno)));
          _event_server_err_only_response(fd,
                                          req.version,
                                          CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
          list_destroy(connections);
          goto cleanup;
        }
    }

  if (!list_append(connections, fdptr))
    {
      CEREBRO_ERR(("list_append: %s", strerror(errno)));
      _event_server_err_only_response(fd,
                                      req.version,
                                      CEREBRO_EVENT_SERVER_PROTOCOL_ERR_INTERNAL_ERROR);
      goto cleanup;
    }

  Pthread_mutex_unlock(&event_connections_lock);
  /* Clear this pointer so we know it's stored away in a list */
  fdptr = NULL;

  _event_server_err_only_response(fd,
                                  req.version,
                                  CEREBRO_EVENT_SERVER_PROTOCOL_ERR_SUCCESS);

  return;
  
 cleanup:
  if (ecd)
    free(ecd);
  if (fdptr)
    free(fdptr);
  /* ignore potential error, we're in the error path already */
  close(fd);
  return;
}
Ejemplo n.º 26
0
// UDP listener main loop
void ListenerUDPMainLoop(LISTENER *r)
{
	UCHAR *data;
	// Validate arguments
	if (r == NULL)
	{
		return;
	}

	Debug("ListenerUDPMainLoop Starts.\n");
	r->Status = LISTENER_STATUS_TRYING;

	while (true)
	{
		// Try to listen on the UDP port
		while (true)
		{
			// Stop flag inspection
			if (r->Halt)
			{
				// Stop
				return;
			}

			Debug("NewUDP()\n");
			r->Sock = NewUDP(r->Port);
			if (r->Sock != NULL)
			{
				// Wait success
				break;
			}

			// Wait failure
			Debug("Failed to NewUDP.\n");
			Wait(r->Event, LISTEN_RETRY_TIME);

			// Stop flag inspection
			if (r->Halt)
			{
				Debug("UDP Halt.\n");
				return;
			}
		}

		r->Status = LISTENER_STATUS_LISTENING;
		Debug("Start Listening at UDP Port %u.\n", r->Sock->LocalPort);

		// Stop flag inspection
		if (r->Halt)
		{
			// Stop
			goto STOP;
		}

		// Allocate the buffer area
		data = Malloc(UDP_PACKET_SIZE);

		// Read the next packet
		while (true)
		{
			IP src_ip;
			UINT src_port;
			UINT size;
			SOCKSET set;

			InitSockSet(&set);
			AddSockSet(&set, r->Sock);
			Select(&set, SELECT_TIME, NULL, NULL);

			size = RecvFrom(r->Sock, &src_ip, &src_port, data, UDP_PACKET_SIZE);
			if (((size == 0) && (r->Sock->IgnoreRecvErr == false)) || r->Halt)
			{
				// Error has occurred
STOP:
				Disconnect(r->Sock);
				ReleaseSock(r->Sock);
				r->Sock = NULL;
				Debug("UDP Listen Stopped.\n");
				Free(data);
				break;
			}

			// Received an UDP packet
			if (size != SOCK_LATER)
			{
				UDPReceivedPacket(r->Cedar, r->Sock, &src_ip, src_port, data, size);
			}
		}
	}
}
Ejemplo n.º 27
0
/*
 * Install hard disk driver.
 *
 */
install()
{
    int i, pdev, ldev;
    int maxsiz;
    char *s, *d, sdev, dvr[15];
    char *lbuf;
    extern char rootstart, rootend;
    extern char bootstart, bootend;

    if ((ldev = glogdev()) < 0) 
	return BAILOUT;
  
    /* final warning */
    sdev = ldev + 'C';
    (instfnl[INSTDRV].ob_spec)->te_ptext = &sdev;
    instfnl[INSTOK].ob_state = NORMAL;
    instfnl[INSTCN].ob_state = NORMAL;
    if (execform(instfnl) != INSTOK) return BAILOUT;

    /* find maximum sector size on system */
    if (!vernum)	    /* new version of AHDI? */
	maxsiz = 512;	    /* if not, sector size is always 512 bytes */
    else
	maxsiz = *(vernum + 1);	/* max sector size kept after version # */

    if (!(lbuf = Malloc((long)maxsiz))) {
	err(nomemory);
	return ERROR;
    }

    /* find which physical unit the chosen logical drive belongs to */
    pdev = physdev[ldev];
    pdev &= 0x1f;		/* mask off extra bits */
      
    /* Remove old driver if there is one */
    dvr[0] = sdev;
    strcpy(&dvr[1], OLDDVR);
    if (!(Fsfirst(dvr, 0x04)))	/* 0x04 = system files */
	Fdelete(dvr);
          
  
    /* copy driver to specified unit */
    if (copydvr(sdev) != OK)
	return ERROR;

    /* read in the root sector */
    if (getroot(pdev, lbuf) != 0) {
	err(rootread);
	goto argh;
    }
  
    /* copy boot code into root sector */
    for (d = lbuf, s = &rootstart, i = &rootend - &rootstart; i--;)
	*d++ = *s++;

    /* if gemroot() is not successful, return with error */
    if (gemroot(lbuf, 1) != 0) {
	err(cantinst);
	goto argh;
    }

    /* write installed root sector back to disk */  
    if (putroot(pdev, lbuf) != 0) {
	err(rootwrit);
	goto argh;
    }

    /* read boot sector from partition */
    if (getboot(ldev, lbuf) != 0) {
	err(bootread);
	goto argh;
    }

    /* 
     * copy boot code to boot sector, avoiding the BPB information 
     * copy bytes 0..1 for BRA.S to code;
     * leave bytes 2..$1d unaltered (information for BPB);
     * copy bytes $1e..$1fe for code.
     */
    s = &bootstart;
    d = lbuf;
    *d++ = *s++;
    *d++ = *s++;
    d += 0x1c;
    s += 0x1c;
    for (i = &bootend-&bootstart-0x1e; i--;)
	*d++ = *s++;

    /* make the image executable */
    Protobt(lbuf, -1L, -1, 1);

    /* write the installed boot sector back to disk */
    if (putboot(ldev, lbuf) != 0) {
	err(bootwrit);
	goto argh;
    }

    return;

argh:
    dvr[0] = sdev;
    strcpy(&dvr[1], DVRNAME);
    Fdelete(dvr);
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{ DAZZ_DB    _db, *db = &_db;
  FILE       *hdrs = NULL;
  char       *hdrs_name = NULL;

  int         nfiles;
  char      **flist = NULL;
  int        *findx = NULL;

  int            reps, *pts;
  int            input_pts;
  File_Iterator *iter = NULL;
  FILE          *input;

  int         TRIM, UPPER;
  int         DOSEQ, DOQVS, DOARR, QUIVA, ARROW, DAM;
  int         WIDTH;

  int         MMAX, MTOP;
  char      **MASK;

  //  Process arguments

  { int  i, j, k;
    int  flags[128];
    char *eptr;

    ARG_INIT("DBshow")

    WIDTH = 80;
    MTOP  = 0;
    MMAX  = 10;
    MASK  = (char **) Malloc(MMAX*sizeof(char *),"Allocating mask track array");
    if (MASK == NULL)
      exit (1);

    j = 1;
    for (i = 1; i < argc; i++)
      if (argv[i][0] == '-')
        switch (argv[i][1])
        { default:
            ARG_FLAGS("unqaUQA")
            break;
          case 'w':
            ARG_NON_NEGATIVE(WIDTH,"Line width")
            break;
          case 'm':
            if (MTOP >= MMAX)
              { MMAX = 1.2*MTOP + 10;
                MASK = (char **) Realloc(MASK,MMAX*sizeof(char *),"Reallocating mask track array");
                if (MASK == NULL)
                  exit (1);
              }
            MASK[MTOP++] = argv[i]+2;
            break;
        }
      else
        argv[j++] = argv[i];
    argc = j;

    DAM   = 0;
    TRIM  = 1-flags['u'];
    UPPER = 1+flags['U'];
    DOQVS = flags['q'];
    DOARR = flags['a'];
    DOSEQ = 1-flags['n'];
    QUIVA = flags['Q'];
    ARROW = flags['A'];
    if ((QUIVA || DOQVS) && (ARROW || DOARR))
      { fprintf(stderr,"%s: Cannot request both Quiver (-Q,-q) and Arrow (-A,a) information\n",
                       Prog_Name);
        exit (1);
      }

    if (QUIVA)
      { DOQVS = 1;
        DOSEQ = 0;
        MTOP  = 0;
      }
    if (ARROW)
      { DOARR = 1;
        DOSEQ = 0;
        MTOP  = 0;
      }

    if (argc <= 1)
      { fprintf(stderr,"Usage: %s %s\n",Prog_Name,Usage[0]);
        fprintf(stderr,"       %*s %s\n",(int) strlen(Prog_Name),"",Usage[1]);
        fprintf(stderr,"\n");
        fprintf(stderr,"      -u: Show the untrimmed database.\n");
        fprintf(stderr,"\n");
        fprintf(stderr,"      -q: Show also the .quiva streams.\n");
        fprintf(stderr,"      -a: Show also the .arrow pulse sequences.\n");
        fprintf(stderr,"      -n: Do not show the default read DNA sequences.\n");
        fprintf(stderr,"      -m: Show mask intervals and highlight in sequence.\n");
        fprintf(stderr,"\n");
        fprintf(stderr,"      -Q: Produce a .quiva file (ignore all other options but -uU).\n");
        fprintf(stderr,"      -A: Produce a .arrow file (ignore all other options but -uw).\n");
        fprintf(stderr,"\n");
        fprintf(stderr,"      -U: Use upper case for DNA (default is lower case).\n");
        fprintf(stderr,"      -w: Print -w bp per line (default is 80).\n");
        exit (1);
      }
  }
Ejemplo n.º 29
0
Archivo: QV.c Proyecto: ebioman/DAZZ_DB
static HScheme *Huffman(uint64 *hist, HScheme *inscheme)
{ HScheme *scheme;
  HTree   *heap[257];
  HTree    node[512];
  int      hsize;
  HTree   *lft, *rgt;
  int      value, range;
  int     i;

  scheme = (HScheme *) Malloc(sizeof(HScheme),"Allocating Huffman scheme record");
  if (scheme == NULL)
    exit (1);

  hsize = 0;                        //  Load heap
  value = 0;
  if (inscheme != NULL)
    { node[0].count = 0;
      node[0].lft   = (HTree *) (uint64) 255;
      node[0].rgt   = NULL;
      heap[++hsize] = node+(value++);
    }
  for (i = 0; i < 256; i++)
    if (hist[i] > 0)
      { if (inscheme != NULL && (inscheme->codelens[i] > HUFF_CUTOFF || i == 255))
          node[0].count += hist[i];
        else
          { node[value].count = hist[i];
            node[value].lft   = (HTree *) (uint64) i;
            node[value].rgt   = NULL;
            heap[++hsize] = node+(value++);
          }
      }

  for (i = hsize/2; i >= 1; i--)    //  Establish heap property
    Reheap(i,heap,hsize);

  range = value;                    //   Merge pairs with smallest count until have a tree
  for (i = 1; i < value; i++)
    { lft = heap[1];
      heap[1] = heap[hsize--];
      Reheap(1,heap,hsize);
      rgt = heap[1];
      node[range].lft = lft;
      node[range].rgt = rgt;
      node[range].count = lft->count + rgt->count;
      heap[1] = node+(range++);
      Reheap(1,heap,hsize);
    }

  for (i = 0; i < 256; i++)        //  Build the code table
    { scheme->codebits[i] = 0;
      scheme->codelens[i] = 0;
    }

  Build_Table(node+(range-1),0,0,scheme->codebits,scheme->codelens);

  if (inscheme != NULL)            //  Set scheme type and if truncated (2), map truncated codes
    { scheme->type = 2;            //    to code and length for 255
      for (i = 0; i < 255; i++)
        if (inscheme->codelens[i] > HUFF_CUTOFF || scheme->codelens[i] > HUFF_CUTOFF)
          { scheme->codelens[i] = scheme->codelens[255];
            scheme->codebits[i] = scheme->codebits[255];
          }
    }
  else
    { scheme->type = 0;
      for (i = 0; i < 256; i++)
        { if (scheme->codelens[i] > HUFF_CUTOFF)
            scheme->type = 1;
        }
    }

  return (scheme);
}
Ejemplo n.º 30
0
void Bitmap_RLE8::BlitRLE(int x1, int y1, int x2, int y2, Bitmap_16bitAlpha* target, int x, int y, unsigned short modulate) const
	{
	// Check for empty bitmap
	if (!opaqueData_ && !alphaData_)
		{
		return;
		}

	x-=x1;
	y-=y1;


	int clipX1=x+xOffset_;
	int clipY1=y+yOffset_;
	int clipX2=x+xOffset_+(x2-x1);
	int clipY2=y+yOffset_+(y2-y1);


	if (clipX1<0)
		clipX1=0;
	if (clipY1<0)
		clipY1=0;
	if (clipX2>=target->GetWidth())
		clipX2=target->GetWidth()-1;
	if (clipY2>=target->GetHeight())
		clipY2=target->GetHeight()-1;

	// Set up palette
	currentPalette_=palette_;
	if (modulate!=0xffff)
		{
		if (!modulatedPalette_)
			{
			modulatedPalette_=static_cast<unsigned short*>(Malloc(sizeof(unsigned short)*colorCount_));
			}
		for (int i=0; i<colorCount_; i++)
			{
			int c=palette_[i];
			unsigned int r=(c & 0xf800)>>11;
			unsigned int g=(c & 0x7e0)>>5;
			unsigned int b=(c & 0x1f);
			unsigned int mr=(modulate & 0xf800)>>11;
			unsigned int mg=(modulate & 0x7e0)>>5;
			unsigned int mb=(modulate & 0x1f);
			r*=mr;
			g*=mg;
			b*=mb;
			r>>=5;
			g>>=6;
			b>>=5;
			modulatedPalette_[i]=(unsigned short)((r<<11)|(g<<5)|(b));
			}
		currentPalette_=modulatedPalette_;
		}

	int targetDelta=target->GetWidth()-activeWidth_;
	int tx1=x+xOffset_;
	int ty1=y+yOffset_;
	int tx2=tx1+activeWidth_-1;
	int ty2=ty1+activeHeight_-1;
	unsigned short* colorData=&(target->GetColorData())[tx1+ty1*target->GetWidth()];
	unsigned char* alphaData=&(target->GetAlphaData())[tx1+ty1*target->GetWidth()];

	// Do we need to clip?
	if (tx1>=clipX1 && ty1>=clipY1 && tx2<=clipX2 && ty2<=clipY2)
		{
		// Render alpha part
		if (alphaData_)
			{
			CopperRLE8::Alpha_Unclipped(alphaData_,activeWidth_,activeHeight_,currentPalette_,colorData, alphaData, targetDelta, tx1, ty1);
			}

		// Render opaque part
		if (opaqueData_)
			{
			if (usesMask_)
				{
				CopperRLE8::Opaque_Unclipped_Masked(opaqueData_,activeWidth_,activeHeight_,currentPalette_,colorData, alphaData, targetDelta, tx1, ty1);
				}
			else
				{
				CopperRLE8::Opaque_Unclipped_Unmasked(opaqueData_,activeWidth_,activeHeight_,currentPalette_,colorData, alphaData, targetDelta, tx1, ty1);
				}
			}

		}
	else	// Yes, clipping required
		{
		// Trivial rejection test
		if (tx2<clipX1 || ty2<clipY1 || tx1>clipX2 || ty1>clipY2)
			return;

		// Calculate visible part
		int xStart=0;
		int yStart=0;
		int xEnd=0;
		int yEnd=0;

		if (tx1<clipX1)
			{
			xStart=clipX1-tx1;
			}
		if (ty1<clipY1)
			{
			yStart=clipY1-ty1;
			}
		if (tx2>clipX2)
			{
			xEnd=tx2-clipX2+1;
			}
		if (ty2>clipY2)
			{
			yEnd=ty2-clipY2+1;
			}

		// Render opaque part
		if (opaqueData_)
			{
			if (usesMask_)
				{
				CopperRLE8::Opaque_Clipped_Masked(opaqueData_,activeWidth_,activeHeight_,currentPalette_,colorData, alphaData, targetDelta, tx1, ty1, xStart, yStart, xEnd, yEnd);
				}
			else
				{
				CopperRLE8::Opaque_Clipped_Unmasked(opaqueData_,activeWidth_,activeHeight_,currentPalette_,colorData, alphaData, targetDelta, tx1, ty1, xStart, yStart, xEnd, yEnd);
				}
			}

		// Render alpha part
		if (alphaData_)
			{
			CopperRLE8::Alpha_Clipped(alphaData_,activeWidth_,activeHeight_,currentPalette_,colorData, alphaData, targetDelta, tx1, ty1, xStart, yStart, xEnd, yEnd);
			}
		}
	}