Exemple #1
0
static int lirc_readconfig_only_internal(const struct lirc_state *state,
                                         const char *file,
                                         struct lirc_config **config,
                                         int (check)(char *s),
                                         char **full_name,
                                         char **sha_bang)
{
	char *string,*eq,*token,*token2,*token3,*strtok_state = NULL;
	struct filestack_t *filestack, *stack_tmp;
	int open_files;
	struct lirc_config_entry *new_entry,*first,*last;
	char *mode,*remote;
	int ret=0;
	int firstline=1;
	char *save_full_name = NULL;
	
	filestack = stack_push(state, NULL);
	if (filestack == NULL)
	{
		return -1;
	}
	filestack->file = lirc_open(state, file, NULL, &(filestack->name));
	if (filestack->file == NULL)
	{
		stack_free(filestack);
		return -1;
	}
	filestack->line = 0;
	open_files = 1;

	first=new_entry=last=NULL;
	mode=NULL;
	remote=LIRC_ALL;
	while (filestack)
	{
		if((ret=lirc_readline(state,&string,filestack->file))==-1 ||
		   string==NULL)
		{
			fclose(filestack->file);
			if(open_files == 1 && full_name != NULL)
			{
				save_full_name = filestack->name;
				filestack->name = NULL;
			}
			filestack = stack_pop(filestack);
			open_files--;
			continue;
		}
		/* check for sha-bang */
		if(firstline && sha_bang)
		{
			firstline = 0;
			if(strncmp(string, "#!", 2)==0)
			{
				*sha_bang=strdup(string+2);
				if(*sha_bang==NULL)
				{
					lirc_printf(state, "%s: out of memory\n",
						    state->lirc_prog);
					ret=-1;
					free(string);
					break;
				}
			}
		}
		filestack->line++;
		eq=strchr(string,'=');
		if(eq==NULL)
		{
			token=strtok_r(string," \t",&strtok_state);
			if(token==NULL)
			{
				/* ignore empty line */
			}
			else if(token[0]=='#')
			{
				/* ignore comment */
			}
			else if(strcasecmp(token, "include") == 0)
			{
				if (open_files >= MAX_INCLUDES)
				{
					lirc_printf(state, "%s: too many files "
						    "included at %s:%d\n",
						    state->lirc_prog,
						    filestack->name,
						    filestack->line);
					ret=-1;
				}
				else
				{
					token2 = strtok_r(NULL, "", &strtok_state);
					token2 = lirc_trim(token2);
					lirc_parse_include
						(token2, filestack->name,
						 filestack->line);
					stack_tmp = stack_push(state, filestack);
					if (stack_tmp == NULL)
					{
						ret=-1;
					}
					else
					{
						stack_tmp->file = lirc_open(state, token2, filestack->name, &(stack_tmp->name));
						stack_tmp->line = 0;
						if (stack_tmp->file)
						{
							open_files++;
							filestack = stack_tmp;
						}
						else
						{
							stack_pop(stack_tmp);
							ret=-1;
						}
					}
				}
			}
			else
			{
				token2=strtok_r(NULL," \t",&strtok_state);
				if(token2!=NULL && 
				   (token3=strtok_r(NULL," \t",&strtok_state))!=NULL)
				{
					lirc_printf(state, "%s: unexpected token in line %s:%d\n",
						    state->lirc_prog,filestack->name,filestack->line);
				}
				else
				{
					ret=lirc_mode(state, token,token2,&mode,
						      &new_entry,&first,&last,
						      check,
						      filestack->name,
						      filestack->line);
					if(ret==0)
					{
						if(remote!=LIRC_ALL)
							free(remote);
						remote=LIRC_ALL;
					}
					else
					{
						if(mode!=NULL)
						{
							free(mode);
							mode=NULL;
						}
						if(new_entry!=NULL)
						{
							lirc_freeconfigentries
								(new_entry);
							new_entry=NULL;
						}
					}
				}
			}
		}
		else
		{
			eq[0]=0;
			token=lirc_trim(string);
			token2=lirc_trim(eq+1);
			if(token[0]=='#')
			{
				/* ignore comment */
			}
			else if(new_entry==NULL)
			{
				lirc_printf(state, "%s: bad file format, %s:%d\n",
					state->lirc_prog,filestack->name,filestack->line);
				ret=-1;
			}
			else
			{
				token2=strdup(token2);
				if(token2==NULL)
				{
					lirc_printf(state, "%s: out of memory\n",
						    state->lirc_prog);
					ret=-1;
				}
				else if(strcasecmp(token,"prog")==0)
				{
					if(new_entry->prog!=NULL) free(new_entry->prog);
					new_entry->prog=token2;
				}
				else if(strcasecmp(token,"remote")==0)
				{
					if(remote!=LIRC_ALL)
						free(remote);
					
					if(strcasecmp("*",token2)==0)
					{
						remote=LIRC_ALL;
						free(token2);
					}
					else
					{
						remote=token2;
					}
				}
				else if(strcasecmp(token,"button")==0)
				{
					struct lirc_code *code;
					
					code=(struct lirc_code *)
					malloc(sizeof(struct lirc_code));
					if(code==NULL)
					{
						free(token2);
						lirc_printf(state, "%s: out of "
							    "memory\n",
							    state->lirc_prog);
						ret=-1;
					}
					else
					{
						code->remote=remote;
						if(strcasecmp("*",token2)==0)
						{
							code->button=LIRC_ALL;
							free(token2);
						}
						else
						{
							code->button=token2;
						}
						code->next=NULL;

						if(new_entry->code==NULL)
						{
							new_entry->code=code;
						}
						else
						{
							new_entry->next_code->next
							=code;
						}
						new_entry->next_code=code;
						if(remote!=LIRC_ALL)
						{
							remote=strdup(remote);
							if(remote==NULL)
							{
								lirc_printf(state, "%s: out of memory\n",state->lirc_prog);
								ret=-1;
							}
						}
					}
				}
				else if(strcasecmp(token,"delay")==0)
				{
					char *end;

					errno=ERANGE+1;
					new_entry->rep_delay=strtoul(token2,&end,0);
					if((new_entry->rep_delay==UINT_MAX 
					    && errno==ERANGE)
					   || end[0]!=0
					   || strlen(token2)==0)
					{
						lirc_printf(state, "%s: \"%s\" not"
							    " a  valid number for "
							    "delay\n",state->lirc_prog,
							    token2);
					}
					free(token2);
				}
				else if(strcasecmp(token,"repeat")==0)
				{
					char *end;

					errno=ERANGE+1;
					new_entry->rep=strtoul(token2,&end,0);
					if((new_entry->rep==UINT_MAX
					    && errno==ERANGE)
					   || end[0]!=0
					   || strlen(token2)==0)
					{
						lirc_printf(state, "%s: \"%s\" not"
							    " a  valid number for "
							    "repeat\n",state->lirc_prog,
							    token2);
					}
					free(token2);
				}
				else if(strcasecmp(token,"config")==0)
				{
					struct lirc_list *new_list;

					new_list=(struct lirc_list *) 
					malloc(sizeof(struct lirc_list));
					if(new_list==NULL)
					{
						free(token2);
						lirc_printf(state, "%s: out of "
							    "memory\n",
							    state->lirc_prog);
						ret=-1;
					}
					else
					{
						lirc_parse_string(state,token2,filestack->name,filestack->line);
						new_list->string=token2;
						new_list->next=NULL;
						if(new_entry->config==NULL)
						{
							new_entry->config=new_list;
						}
						else
						{
							new_entry->next_config->next
							=new_list;
						}
						new_entry->next_config=new_list;
					}
				}
				else if(strcasecmp(token,"mode")==0)
				{
					if(new_entry->change_mode!=NULL) free(new_entry->change_mode);
					new_entry->change_mode=token2;
				}
				else if(strcasecmp(token,"flags")==0)
				{
					new_entry->flags=lirc_flags(state, token2);
					free(token2);
				}
				else
				{
					free(token2);
					lirc_printf(state, "%s: unknown token \"%s\" in %s:%d ignored\n",
						    state->lirc_prog,token,filestack->name,filestack->line);
				}
			}
		}
		free(string);
		if(ret==-1) break;
	}
	if(remote!=LIRC_ALL)
		free(remote);
	if(new_entry!=NULL)
	{
		if(ret==0)
		{
			ret=lirc_mode(state, "end",NULL,&mode,&new_entry,
				      &first,&last,check,"",0);
			lirc_printf(state, "%s: warning: end token missing at end "
				    "of file\n",state->lirc_prog);
		}
		else
		{
			lirc_freeconfigentries(new_entry);
			new_entry=NULL;
		}
	}
	if(mode!=NULL)
	{
		if(ret==0)
		{
			lirc_printf(state, "%s: warning: no end token found for mode "
				    "\"%s\"\n",state->lirc_prog,mode);
		}
		free(mode);
	}
	if(ret==0)
	{
		char *startupmode;
		
		*config=(struct lirc_config *)
			malloc(sizeof(struct lirc_config));
		if(*config==NULL)
		{
			lirc_printf(state, "%s: out of memory\n",state->lirc_prog);
			lirc_freeconfigentries(first);
			return(-1);
		}
		(*config)->first=first;
		(*config)->next=first;
		startupmode = lirc_startupmode(state, (*config)->first);
		(*config)->current_mode=startupmode ? strdup(startupmode):NULL;
		(*config)->sockfd=-1;
		if(full_name != NULL)
		{
			*full_name = save_full_name;
			save_full_name = NULL;
		}
	}
	else
	{
		*config=NULL;
		lirc_freeconfigentries(first);
		if(sha_bang && *sha_bang!=NULL)
		{
			free(*sha_bang);
			*sha_bang=NULL;
		}
	}
	if(filestack)
	{
		stack_free(filestack);
	}
	if(save_full_name)
	{
		free(save_full_name);
	}
	return(ret);
}
Exemple #2
0
/**
 * Parse and store the command line arguments
 *
 * @param argc       argument count
 * @param argv[]     argument vector
 * @param appl_args  Store application arguments here
 */
static void parse_args(int argc, char *argv[], appl_args_t *appl_args)
{
	int opt;
	int long_index;
	char *names, *str, *token, *save;
	size_t len;
	int i;
	static struct option longopts[] = {
		{"count", required_argument, NULL, 'c'},
		{"interface", required_argument, NULL, 'i'},	/* return 'i' */
		{"help", no_argument, NULL, 'h'},		/* return 'h' */
		{"configuration file", required_argument,
			NULL, 'f'},/* return 'f' */
		{NULL, 0, NULL, 0}
	};

	memset(appl_args, 0, sizeof(*appl_args));

	while (1) {
		opt = getopt_long(argc, argv, "+c:i:hf:",
				  longopts, &long_index);

		if (opt == -1)
			break;	/* No more options */

		switch (opt) {
		case 'c':
			appl_args->core_count = atoi(optarg);
			break;
			/* parse packet-io interface names */
		case 'i':
			len = strlen(optarg);
			if (len == 0) {
				usage(argv[0]);
				exit(EXIT_FAILURE);
			}
			len += 1;	/* add room for '\0' */

			names = malloc(len);
			if (names == NULL) {
				usage(argv[0]);
				exit(EXIT_FAILURE);
			}

			/* count the number of tokens separated by ',' */
			strcpy(names, optarg);
			for (str = names, i = 0;; str = NULL, i++) {
				token = strtok_r(str, ",", &save);
				if (token == NULL)
					break;
			}
			appl_args->if_count = i;

			if (appl_args->if_count == 0) {
				usage(argv[0]);
				exit(EXIT_FAILURE);
			}

			/* allocate storage for the if names */
			appl_args->if_names =
				calloc(appl_args->if_count, sizeof(char *));

			/* store the if names (reset names string) */
			strcpy(names, optarg);
			for (str = names, i = 0;; str = NULL, i++) {
				token = strtok_r(str, ",", &save);
				if (token == NULL)
					break;
				appl_args->if_names[i] = token;
			}
			break;

		case 'h':
			usage(argv[0]);
			exit(EXIT_SUCCESS);
			break;

		case 'f':
			len = strlen(optarg);
			if (len == 0) {
				usage(argv[0]);
				exit(EXIT_FAILURE);
			}
			len += 1;	/* add room for '\0' */

			appl_args->conf_file = malloc(len);
			if (appl_args->conf_file == NULL) {
				usage(argv[0]);
				exit(EXIT_FAILURE);
			}

			strcpy(appl_args->conf_file, optarg);
			break;

		default:
			break;
		}
	}

	if (appl_args->if_count == 0) {
		usage(argv[0]);
		exit(EXIT_FAILURE);
	}

	optind = 1;		/* reset 'extern optind' from the getopt lib */
}
Exemple #3
0
/*
    Receive data in multiple chunks by checking a non-blocking socket
    Timeout in seconds
*/
int recv_timeout(int s ,int fileFd, int timeout)
{
  int size_recv , total_size= 0;
  struct timeval begin , now;
  char chunk[CHUNK_SIZE], *data;
  double timediff;
  char *token;
  char *saveptr,*saveptr2;
  char header[200];
  int loop =0;
  int http_status,contentLength;

  //make socket non blocking
  fcntl(s, F_SETFL, O_NONBLOCK);

  //beginning time
  gettimeofday(&begin , NULL);
  while(1)
  {
    gettimeofday(&now , NULL);

    //time elapsed in seconds
    timediff = (now.tv_sec - begin.tv_sec) + 1e-6 * (now.tv_usec - begin.tv_usec);

    //if you got some data, then break after timeout
    if( total_size > 0 && timediff > timeout ) {
      break;
    }
    //if you got no data at all, wait a little longer, twice the timeout
    else if( timediff > timeout*2) {
      break;
    }

    memset(chunk ,0 , CHUNK_SIZE);  //clear the variable
    if((size_recv =  recv(s , chunk , CHUNK_SIZE , 0) ) < 0) {
      //if nothing was received then we want to wait a little before trying again, 0.1 seconds
      usleep(100000);
    }
    else
    {
      //PRINTF_FL("Received Size:%d",size_recv);
      data = chunk;
      //PRINTF_FL("data:%s",chunk);
      total_size += size_recv;
      //PRINTF_FL("%s" , chunk);
      if(loop == 0)
      {
        while((token = strtok_r(data,"\r",&saveptr)))
        {
          /* code to retieve the http response status
           * example : HTTP/1.1 200 OK
          */
          if(token == NULL || strcmp(&token[0],"\n") == 0)
          {
            data = saveptr+1;
            break;
          }

          strncpy(header,&token[0],199);
          //PRINTF_FL("Header msg: %s",header);
          if(loop == 0)
          {
            token = strtok_r(header," ",&saveptr2);
            if(token == NULL)
            {
              PRINTF_FL("Wrong Response Header .. Returning1");
              return;
            }
            else if(strcmp("HTTP/1.1",token) != 0)
            {
              PRINTF_FL("Wrong Response Header .. Returning ");
              return;
            }

            token = strtok_r(NULL," ",&saveptr2);
            if(token == NULL)
            {
              PRINTF_FL("Wrong Response Header .. Returning ");
              return;
            }
            http_status = atoi(&token[0]);
            PRINTF_FL("HTTP response status : %d",http_status);
            loop = 1;
            if(http_status != 200)
              return;

          }
          else
          {
            if((token = strstr(header,"Content-Length:")))
            {
              contentLength = atoi(token+16);
              PRINTF_FL("Content Length:%d",contentLength);
            }
          }
          data = NULL;
        }
        size_recv = (chunk + size_recv) - data;
      }
      //PRINTF_FL("Content Starts Here:");
      //PRINTF_FL("%s",data);
      if((size_recv = ccsFileWrite(fileFd,data,size_recv))<0)
        return -1;
      //PRINTF_FL("Bytes Written:%d",size_recv);
      //reset beginning time
      gettimeofday(&begin , NULL);
    }
  }

  //PRINTF_FL("TotalSize: %d",total_size);
  return contentLength;
}
/* #define DEBUG */
int rrd_create_r(
    const char *filename,
    unsigned long pdp_step,
    time_t last_up,
    int argc,
    const char **argv)
{
    rrd_t     rrd;
    long      i;
    int       offset;
    char     *token;
    char      dummychar1[2], dummychar2[2];
    unsigned short token_idx, error_flag, period = 0;
    unsigned long hashed_name;

    /* init rrd clean */
    rrd_init(&rrd);
    /* static header */
    if ((rrd.stat_head = (stat_head_t*)calloc(1, sizeof(stat_head_t))) == NULL) {
        rrd_set_error("allocating rrd.stat_head");
        rrd_free2(&rrd);
        return (-1);
    }

    /* live header */
    if ((rrd.live_head = (live_head_t*)calloc(1, sizeof(live_head_t))) == NULL) {
        rrd_set_error("allocating rrd.live_head");
        rrd_free2(&rrd);
        return (-1);
    }

    /* set some defaults */
    strcpy(rrd.stat_head->cookie, RRD_COOKIE);
    strcpy(rrd.stat_head->version, RRD_VERSION3);   /* by default we are still version 3 */
    rrd.stat_head->float_cookie = FLOAT_COOKIE;
    rrd.stat_head->ds_cnt = 0;  /* this will be adjusted later */
    rrd.stat_head->rra_cnt = 0; /* ditto */
    rrd.stat_head->pdp_step = pdp_step; /* 5 minute default */

    /* a default value */
    rrd.ds_def = NULL;
    rrd.rra_def = NULL;

    rrd.live_head->last_up = last_up;

    /* optind points to the first non-option command line arg,
     * in this case, the file name. */
    /* Compute the FNV hash value (used by SEASONAL and DEVSEASONAL
     * arrays. */
    hashed_name = FnvHash(filename);
    for (i = 0; i < argc; i++) {
        unsigned int ii;

        if (strncmp(argv[i], "DS:", 3) == 0) {
            size_t    old_size = sizeof(ds_def_t) * (rrd.stat_head->ds_cnt);

            if ((rrd.ds_def = (ds_def_t*)rrd_realloc(rrd.ds_def,
                                          old_size + sizeof(ds_def_t))) ==
                NULL) {
                rrd_set_error("allocating rrd.ds_def");
                rrd_free2(&rrd);
                return (-1);
            }
            memset(&rrd.ds_def[rrd.stat_head->ds_cnt], 0, sizeof(ds_def_t));
            /* extract the name and type */
            switch (sscanf(&argv[i][3],
                           DS_NAM_FMT "%1[:]" DST_FMT "%1[:]%n",
                           rrd.ds_def[rrd.stat_head->ds_cnt].ds_nam,
                           dummychar1,
                           rrd.ds_def[rrd.stat_head->ds_cnt].dst,
                           dummychar2, &offset)) {
            case 0:
            case 1:
                rrd_set_error("Invalid DS name");
                break;
            case 2:
            case 3:
                rrd_set_error("Invalid DS type");
                break;
            case 4:    /* (%n may or may not be counted) */
            case 5:    /* check for duplicate datasource names */
                for (ii = 0; ii < rrd.stat_head->ds_cnt; ii++)
                    if (strcmp(rrd.ds_def[rrd.stat_head->ds_cnt].ds_nam,
                               rrd.ds_def[ii].ds_nam) == 0)
                        rrd_set_error("Duplicate DS name: %s",
                                      rrd.ds_def[ii].ds_nam);
                /* DS_type may be valid or not. Checked later */
                break;
            default:
                rrd_set_error("invalid DS format");
            }
            if (rrd_test_error()) {
                rrd_free2(&rrd);
                return -1;
            }

            /* parse the remainder of the arguments */
            switch (dst_conv(rrd.ds_def[rrd.stat_head->ds_cnt].dst)) {
            case DST_COUNTER:
            case DST_ABSOLUTE:
            case DST_GAUGE:
            case DST_DERIVE:
                parseGENERIC_DS(&argv[i][offset + 3], &rrd,
                                rrd.stat_head->ds_cnt);
                break;
            case DST_CDEF:
                parseCDEF_DS(&argv[i][offset + 3], &rrd,
                             rrd.stat_head->ds_cnt);
                break;
            default:
                rrd_set_error("invalid DS type specified");
                break;
            }

            if (rrd_test_error()) {
                rrd_free2(&rrd);
                return -1;
            }
            rrd.stat_head->ds_cnt++;
        } else if (strncmp(argv[i], "RRA:", 4) == 0) {
            char     *argvcopy;
            char     *tokptr = "";
            int       cf_id = -1;
            size_t    old_size = sizeof(rra_def_t) * (rrd.stat_head->rra_cnt);
            int       row_cnt;
            int       token_min = 4;
            if ((rrd.rra_def = (rra_def_t*)rrd_realloc(rrd.rra_def,
                                           old_size + sizeof(rra_def_t))) ==
                NULL) {
                rrd_set_error("allocating rrd.rra_def");
                rrd_free2(&rrd);
                return (-1);
            }
            memset(&rrd.rra_def[rrd.stat_head->rra_cnt], 0,
                   sizeof(rra_def_t));

            argvcopy = strdup(argv[i]);
            token = strtok_r(&argvcopy[4], ":", &tokptr);
            token_idx = error_flag = 0;
            
            while (token != NULL) {
                switch (token_idx) {
                case 0:
                    if (sscanf(token, CF_NAM_FMT,
                               rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam) !=
                        1)
                        rrd_set_error("Failed to parse CF name");
                    cf_id = cf_conv(rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam);
                    switch (cf_id) {
                    case CF_MHWPREDICT:
                        strcpy(rrd.stat_head->version, RRD_VERSION);    /* MHWPREDICT causes Version 4 */
                    case CF_HWPREDICT:
                        token_min = 5;
                        /* initialize some parameters */
                        rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_alpha].
                            u_val = 0.1;
                        rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_beta].
                            u_val = 1.0 / 288;
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_dependent_rra_idx].u_cnt =
                            rrd.stat_head->rra_cnt;
                        break;
                    case CF_DEVSEASONAL:
                        token_min = 3;
                    case CF_SEASONAL:
                        if (cf_id == CF_SEASONAL){
                           token_min = 4;
                        }
                        /* initialize some parameters */
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_seasonal_gamma].u_val = 0.1;
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_seasonal_smoothing_window].u_val = 0.05;
                        /* fall through */
                    case CF_DEVPREDICT:
                        if (cf_id == CF_DEVPREDICT){
                           token_min = 3;
                        }
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_dependent_rra_idx].u_cnt = -1;
                        break;
                    case CF_FAILURES:
                        token_min = 5;
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_delta_pos].u_val = 2.0;
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_delta_neg].u_val = 2.0;
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_window_len].u_cnt = 3;
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_failure_threshold].u_cnt = 2;
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_dependent_rra_idx].u_cnt = -1;
                        break;
                        /* invalid consolidation function */
                    case -1:
                        rrd_set_error
                            ("Unrecognized consolidation function %s",
                             rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam);
                    default:
                        break;
                    }
                    /* default: 1 pdp per cdp */
                    rrd.rra_def[rrd.stat_head->rra_cnt].pdp_cnt = 1;
                    break;
                case 1:
                    switch (cf_conv
                            (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
                    case CF_HWPREDICT:
                    case CF_MHWPREDICT:
                    case CF_DEVSEASONAL:
                    case CF_SEASONAL:
                    case CF_DEVPREDICT:
                    case CF_FAILURES:
                        row_cnt = atoi(token);
                        if (row_cnt <= 0)
                            rrd_set_error("Invalid row count: %i", row_cnt);
                        rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt = row_cnt;
                        break;
                    default:
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_cdp_xff_val].u_val = atof(token);
                        if (rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_cdp_xff_val].u_val < 0.0
                            || rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_cdp_xff_val].u_val >= 1.0)
                            rrd_set_error
                                ("Invalid xff: must be between 0 and 1");
                        break;
                    }
                    break;
                case 2:
                    switch (cf_conv
                            (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
                    case CF_HWPREDICT:
                    case CF_MHWPREDICT:
                        rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_alpha].
                            u_val = atof(token);
                        if (atof(token) <= 0.0 || atof(token) >= 1.0)
                            rrd_set_error
                                ("Invalid alpha: must be between 0 and 1");
                        break;
                    case CF_DEVSEASONAL:
                    case CF_SEASONAL:
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_seasonal_gamma].u_val = atof(token);
                        if (atof(token) <= 0.0 || atof(token) >= 1.0)
                            rrd_set_error
                                ("Invalid gamma: must be between 0 and 1");
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_seasonal_smooth_idx].u_cnt =
                            hashed_name %
                            rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt;
                        break;
                    case CF_FAILURES:
                        /* specifies the # of violations that constitutes the failure threshold */
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_failure_threshold].u_cnt = atoi(token);
                        if (atoi(token) < 1
                            || atoi(token) > MAX_FAILURES_WINDOW_LEN)
                            rrd_set_error
                                ("Failure threshold is out of range %d, %d",
                                 1, MAX_FAILURES_WINDOW_LEN);
                        break;
                    case CF_DEVPREDICT:
                        /* specifies the index (1-based) of CF_DEVSEASONAL array
                         * associated with this CF_DEVPREDICT array. */
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_dependent_rra_idx].u_cnt =
                            atoi(token) - 1;
                        break;
                    default:
                        rrd.rra_def[rrd.stat_head->rra_cnt].pdp_cnt =
                            atoi(token);
                        if (atoi(token) < 1)
                            rrd_set_error("Invalid step: must be >= 1");
                        break;
                    }
                    break;
                case 3:
                    switch (cf_conv
                            (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
                    case CF_HWPREDICT:
                    case CF_MHWPREDICT:
                        rrd.rra_def[rrd.stat_head->rra_cnt].par[RRA_hw_beta].
                            u_val = atof(token);
                        if (atof(token) < 0.0 || atof(token) > 1.0)
                            rrd_set_error
                                ("Invalid beta: must be between 0 and 1");
                        break;
                    case CF_DEVSEASONAL:
                    case CF_SEASONAL:
                        /* specifies the index (1-based) of CF_HWPREDICT array
                         * associated with this CF_DEVSEASONAL or CF_SEASONAL array. 
                         * */
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_dependent_rra_idx].u_cnt =
                            atoi(token) - 1;
                        break;
                    case CF_FAILURES:
                        /* specifies the window length */
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_window_len].u_cnt = atoi(token);
                        if (atoi(token) < 1
                            || atoi(token) > MAX_FAILURES_WINDOW_LEN)
                            rrd_set_error
                                ("Window length is out of range %d, %d", 1,
                                 MAX_FAILURES_WINDOW_LEN);
                        /* verify that window length exceeds the failure threshold */
                        if (rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_window_len].u_cnt <
                            rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_failure_threshold].u_cnt)
                            rrd_set_error
                                ("Window length is shorter than the failure threshold");
                        break;
                    case CF_DEVPREDICT:
                        /* shouldn't be any more arguments */
                        rrd_set_error
                            ("Unexpected extra argument for consolidation function DEVPREDICT");
                        break;
                    default:
                        row_cnt = atoi(token);
                        if (row_cnt <= 0)
                            rrd_set_error("Invalid row count: %i", row_cnt);
                        rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt = row_cnt;
                        break;
                    }
                    break;
                case 4:
                    switch (cf_conv
                            (rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam)) {
                    case CF_FAILURES:
                        /* specifies the index (1-based) of CF_DEVSEASONAL array
                         * associated with this CF_DEVFAILURES array. */
                        rrd.rra_def[rrd.stat_head->rra_cnt].
                            par[RRA_dependent_rra_idx].u_cnt =
                            atoi(token) - 1;
                        break;
                    case CF_DEVSEASONAL:
                    case CF_SEASONAL:
                        /* optional smoothing window */
                        if (sscanf(token, "smoothing-window=%lf",
                                   &(rrd.rra_def[rrd.stat_head->rra_cnt].
                                     par[RRA_seasonal_smoothing_window].
                                     u_val))) {
                            strcpy(rrd.stat_head->version, RRD_VERSION);    /* smoothing-window causes Version 4 */
                            if (rrd.rra_def[rrd.stat_head->rra_cnt].
                                par[RRA_seasonal_smoothing_window].u_val < 0.0
                                || rrd.rra_def[rrd.stat_head->rra_cnt].
                                par[RRA_seasonal_smoothing_window].u_val >
                                1.0) {
                                rrd_set_error
                                    ("Invalid smoothing-window %f: must be between 0 and 1",
                                     rrd.rra_def[rrd.stat_head->rra_cnt].
                                     par[RRA_seasonal_smoothing_window].
                                     u_val);
                            }
                        } else {
                            rrd_set_error("Invalid option %s", token);
                        }
                        break;
                    case CF_HWPREDICT:
                    case CF_MHWPREDICT:
                        /* length of the associated CF_SEASONAL and CF_DEVSEASONAL arrays. */
                        period = atoi(token);
                        if (period >
                            rrd.rra_def[rrd.stat_head->rra_cnt].row_cnt)
                            rrd_set_error
                                ("Length of seasonal cycle exceeds length of HW prediction array");
                        break;
                    default:
                        /* shouldn't be any more arguments */
                        rrd_set_error
                            ("Unexpected extra argument for consolidation function %s",
                             rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam);
                        break;
                    }
                    break;
                case 5:
                    /* If we are here, this must be a CF_HWPREDICT RRA.
                     * Specifies the index (1-based) of CF_SEASONAL array
                     * associated with this CF_HWPREDICT array. If this argument 
                     * is missing, then the CF_SEASONAL, CF_DEVSEASONAL, CF_DEVPREDICT,
                     * CF_FAILURES.
                     * arrays are created automatically. */
                    rrd.rra_def[rrd.stat_head->rra_cnt].
                        par[RRA_dependent_rra_idx].u_cnt = atoi(token) - 1;
                    break;
                default:
                    /* should never get here */
                    rrd_set_error("Unknown error");
                    break;
                }       /* end switch */
                if (rrd_test_error()) {
                    /* all errors are unrecoverable */
                    free(argvcopy);
                    rrd_free2(&rrd);
                    return (-1);
                }
                token = strtok_r(NULL, ":", &tokptr);
                token_idx++;
            }           /* end while */
            free(argvcopy);
            if (token_idx < token_min){
                rrd_set_error("Expected at least %i arguments for RRA but got %i",token_min,token_idx);
                rrd_free2(&rrd);
                return(-1);
            }
#ifdef DEBUG
            fprintf(stderr,
                    "Creating RRA CF: %s, dep idx %lu, current idx %lu\n",
                    rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam,
                    rrd.rra_def[rrd.stat_head->rra_cnt].
                    par[RRA_dependent_rra_idx].u_cnt, rrd.stat_head->rra_cnt);
#endif
            /* should we create CF_SEASONAL, CF_DEVSEASONAL, and CF_DEVPREDICT? */
            if ((cf_conv(rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam) ==
                 CF_HWPREDICT
                 || cf_conv(rrd.rra_def[rrd.stat_head->rra_cnt].cf_nam) ==
                 CF_MHWPREDICT)
                && rrd.rra_def[rrd.stat_head->rra_cnt].
                par[RRA_dependent_rra_idx].u_cnt == rrd.stat_head->rra_cnt) {
#ifdef DEBUG
                fprintf(stderr, "Creating HW contingent RRAs\n");
#endif
                if (create_hw_contingent_rras(&rrd, period, hashed_name) ==
                    -1) {
                    rrd_set_error("creating contingent RRA");
                    rrd_free2(&rrd);
                    return -1;
                }
            }
            rrd.stat_head->rra_cnt++;
        } else {
            rrd_set_error("can't parse argument '%s'", argv[i]);
            rrd_free2(&rrd);
            return -1;
        }
    }


    if (rrd.stat_head->rra_cnt < 1) {
        rrd_set_error("you must define at least one Round Robin Archive");
        rrd_free2(&rrd);
        return (-1);
    }

    if (rrd.stat_head->ds_cnt < 1) {
        rrd_set_error("you must define at least one Data Source");
        rrd_free2(&rrd);
        return (-1);
    }
    return rrd_create_fn(filename, &rrd);
}
Exemple #5
0
char
*transcode_query(const char *query, const char *username, char *transcoded_query)
{	
	
	char *saveptr = NULL, *token;
	int i, j, len, replacements;
	int namelen = strlen(username);
	int querylen = strlen(query);
	char *str = malloc (querylen);

	/* count aprox. the number of replacements.
	 * %% escaping is also accounted and shouldn't
	 * in the TODO */
	for (replacements = 0, str=strdup(query); ; str = NULL) {
		token = strtok_r(str, "%", &saveptr);
		if (token == NULL)
			break;
		if (token[0] == 'u') {
			replacements++;
		}
	}

	free(str);
	
	len = querylen + namelen * replacements - 2 * replacements + 1;

	transcoded_query = malloc (len);
	memset(transcoded_query, 0, len);

    for (i=j=0;j<len && query[i]; ){
		if (query[i] == '%') {
		    switch (query[i+1]) {
				case '%': /* escaped '%' character */
				    transcoded_query[j++] = '%';
				    break;
				case 'u': /* paste in the username */
				    if (j+namelen>=len) {
						LOG(LOG_ERR, "%s: check ExtLookupQuery", ERR_EXT_LOOKUP_MISCONFIGURED);
						return NULL;
				    }
				    memcpy (transcoded_query+j, username, namelen);
				    j += namelen;
				    break;
				default: /* unrecognised formatting, abort!  */
					LOG(LOG_ERR, "%s: check ExtLookupQuery", ERR_EXT_LOOKUP_MISCONFIGURED);
			    	return NULL;
		    }
		    i += 2;
		} else {
		    transcoded_query[j++] = query[i++];
		}
	}

    if (j>=len) {
		LOG(LOG_ERR, "%s: check ExtLookupQuery", ERR_EXT_LOOKUP_MISCONFIGURED);
		return NULL;
    }
    /* and finally zero terminate string */
    transcoded_query[j] = 0;
	
	return transcoded_query;
}
Exemple #6
0
/*
 * Processes the incoming request
 */
void process_request(gnutls_session_t session) 
{
   char buffer[MAX_BUF + 1];
   char header[MAX_BUF];

   /*
    * Reset mem, read the client header into
    * the buffer.
    */
   memset (buffer, 0, MAX_BUF + 1);
   char *buf = read_line(session, buffer, MAX_BUF);

   printf("\t%s\n", buf);

   /*
    * Sepearate our first line request header
    * into separate parts, specifically we need
    * the file path its requesting
    */
   char *token;
   char *tokenizer;

   token = strtok_r(buf, " ", &tokenizer);
   token = strtok_r(NULL, " ", &tokenizer);

   char *file_name = strdup(token); 

   /*
    * If no file is listed, we default to
    * index.html
    */
   if (strcmp(file_name, "/") == 0)
      strcpy(file_name, "/index.html");

   /*
    * Setting where to serve content form
    */
   char path[MAX_BUF];
   snprintf(path, MAX_BUF, "content%s", file_name);

   /*
    * Opening the file, if it doesn't exist we stop here
    * and send a 404 Not found header to the client
    */
   FILE *file = fopen(path, "r");
   if (file == NULL)
   {
      fprintf(stderr, "\tFile not found.\n"); 
      snprintf(header, MAX_BUF, "HTTP/1.1 404 Not Found\r\n\r\n");
      if (gnutls_record_send(session, header, strlen(header)) < 0)
         err_exit();
   }
   else
   {
      /*
       * File found, get the mime type
       */
      char content_buffer[MAX_BUF];
      char *mime = get_content_type(path, content_buffer, MAX_BUF);
      printf("\tContent type detected: %s\n", mime);

      /*
       * If it is PHP, we will close the currentl file descriptor
       * and set it to the execution of the script. The output
       * of the command is now our file descriptor
       */
      if (strcmp(mime, "application/php") == 0)
      {
         printf("\tExecuting PHP file.\n");
         fclose(file);

         snprintf(path, MAX_BUF, "php content%s", file_name);
         file = popen(path, "r");

         if (file == NULL)
            err_exit();

         // change the mime type.
         strcpy(mime, "text/html");
      }

      /*
       * Check to see how big the file is
       */
      fseek(file, 0, SEEK_END);
      int file_size = ftell(file);
      fseek(file, 0, SEEK_SET);

      /*
       * Read the content into here
       */
      char *file_string = malloc(file_size+1);
      fread(file_string, 1, file_size, file);
   
      /*
       * Hotfix, PHP gives us a filesize of -1 apparently,
       * we need to use strlen to actually read the size of
       * the content from PHP
       */
      if (file_size == -1)
         file_size = strlen(file_string);

      printf("\tFile size: %d\n", file_size);

      /*
       * Send the HTTP 200 OK header, the content type
       * and the content length to the browser.
       */
      snprintf(header, MAX_BUF, "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n", mime, file_size);
      if (gnutls_record_send(session, header, strlen(header)) < 0)
         err_exit();

      /*
       * Sending the content to the client
       * Needs to be chuncked because of the sending
       * limitations of gnutls.
       */
      int bytes_read = 0;
      int bytes_sending;
      char *str_ptr = file_string;

      while (bytes_read < file_size)
      {  
         if ((file_size - bytes_read) < MAX_BUF) 
            bytes_sending = file_size - bytes_read;
         else
            bytes_sending = MAX_BUF;

         //printf("\tSent: %d bytes\n", bytes_sending);

         if (gnutls_record_send(session, str_ptr, bytes_sending) < 0)
            err_exit();

         str_ptr += bytes_sending;
         bytes_read += bytes_sending;
      }
   }
}
/**
 * video_shader_parse_imports:
 * @conf              : Preset file to read from.
 * @shader            : Shader passes handle.
 *
 * Resolves import parameters belonging to shaders.
 *
 * Returns: true (1) if successful, otherwise false (0).
 **/
static bool video_shader_parse_imports(config_file_t *conf,
      struct video_shader *shader)
{
   size_t path_size   = PATH_MAX_LENGTH * sizeof(char);
   const char *id     = NULL;
   char *save         = NULL;
   char *tmp_str      = NULL;
   char *imports      = (char*)malloc(1024 * sizeof(char));

   imports[0]         = '\0';

   if (!config_get_array(conf, "imports", imports,
            1024 * sizeof(char)))
   {
      free(imports);
      return true;
   }

   for (id = strtok_r(imports, ";", &save);
         id && shader->variables < GFX_MAX_VARIABLES;
         shader->variables++, id = strtok_r(NULL, ";", &save))
   {
      char semantic_buf[64];
      char wram_buf[64];
      char input_slot_buf[64];
      char mask_buf[64];
      char equal_buf[64];
      char semantic[64];
      unsigned addr           = 0;
      unsigned mask           = 0;
      unsigned equal          = 0;
      struct state_tracker_uniform_info *var =
         &shader->variable[shader->variables];

      semantic_buf[0] = wram_buf[0] = input_slot_buf[0] =
         mask_buf[0] = equal_buf[0] = semantic[0] = '\0';

      strlcpy(var->id, id, sizeof(var->id));

      snprintf(semantic_buf, sizeof(semantic_buf), "%s_semantic", id);

      if (!config_get_array(conf, semantic_buf, semantic, sizeof(semantic)))
      {
         RARCH_ERR("No semantic for import variable.\n");
         goto error;
      }

      snprintf(wram_buf, sizeof(wram_buf), "%s_wram", id);
      snprintf(input_slot_buf, sizeof(input_slot_buf), "%s_input_slot", id);
      snprintf(mask_buf, sizeof(mask_buf), "%s_mask", id);
      snprintf(equal_buf, sizeof(equal_buf), "%s_equal", id);

      if (string_is_equal(semantic, "capture"))
         var->type = RARCH_STATE_CAPTURE;
      else if (string_is_equal(semantic, "transition"))
         var->type = RARCH_STATE_TRANSITION;
      else if (string_is_equal(semantic, "transition_count"))
         var->type = RARCH_STATE_TRANSITION_COUNT;
      else if (string_is_equal(semantic, "capture_previous"))
         var->type = RARCH_STATE_CAPTURE_PREV;
      else if (string_is_equal(semantic, "transition_previous"))
         var->type = RARCH_STATE_TRANSITION_PREV;
      else if (string_is_equal(semantic, "python"))
         var->type = RARCH_STATE_PYTHON;
      else
      {
         RARCH_ERR("Invalid semantic.\n");
         goto error;
      }

      if (var->type != RARCH_STATE_PYTHON)
      {
         unsigned input_slot = 0;

         if (config_get_uint(conf, input_slot_buf, &input_slot))
         {
            switch (input_slot)
            {
               case 1:
                  var->ram_type = RARCH_STATE_INPUT_SLOT1;
                  break;

               case 2:
                  var->ram_type = RARCH_STATE_INPUT_SLOT2;
                  break;

               default:
                  RARCH_ERR("Invalid input slot for import.\n");
                  goto error;
            }
         }
         else if (config_get_hex(conf, wram_buf, &addr))
         {
            var->ram_type = RARCH_STATE_WRAM;
            var->addr = addr;
         }
         else
         {
            RARCH_ERR("No address assigned to semantic.\n");
            goto error;
         }
      }

      if (config_get_hex(conf, mask_buf, &mask))
         var->mask = mask;
      if (config_get_hex(conf, equal_buf, &equal))
         var->equal = equal;
   }

   tmp_str    = (char*)malloc(PATH_MAX_LENGTH * sizeof(char));
   tmp_str[0] = '\0';
   if (config_get_path(conf, "import_script", tmp_str, path_size))
      strlcpy(shader->script_path, tmp_str, sizeof(shader->script_path));
   config_get_array(conf, "import_script_class",
         shader->script_class, sizeof(shader->script_class));
   free(tmp_str);

   free(imports);
   return true;

error:
   free(imports);
   return false;
}
Exemple #8
0
static void ac_load_config(void)
{
	FILE *fp = open_config_file(cs_ac);
	if(!fp)
		{ return; }

	int32_t nr;
	char *saveptr1 = NULL, *token;
	if(!cs_malloc(&token, MAXLINESIZE))
		{ return; }
	struct s_cpmap *cur_cpmap, *first_cpmap = NULL, *last_cpmap = NULL;

	for(nr = 0; fgets(token, MAXLINESIZE, fp);)
	{
		int32_t i, skip;
		uint16_t caid, sid, chid, dwtime;
		uint32_t  provid;
		char *ptr, *ptr1;

		if(strlen(token) < 4) { continue; }

		caid = sid = chid = dwtime = 0;
		provid = 0;
		skip = 0;
		ptr1 = 0;
		for(i = 0, ptr = strtok_r(token, "=", &saveptr1); (i < 2) && (ptr); ptr = strtok_r(NULL, "=", &saveptr1), i++)
		{
			trim(ptr);
			if(*ptr == ';' || *ptr == '#' || *ptr == '-')
			{
				skip = 1;
				break;
			}
			switch(i)
			{
			case 0:
				ptr1 = ptr;
				break;
			case 1:
				dwtime = atoi(ptr);
				break;
			}
		}

		if(!skip)
		{
			for(i = 0, ptr = strtok_r(ptr1, ":", &saveptr1); (i < 4) && (ptr); ptr = strtok_r(NULL, ":", &saveptr1), i++)
			{
				trim(ptr);
				switch(i)
				{
				case 0:
					if(*ptr == '*') { caid = 0; }
					else { caid = a2i(ptr, 4); }
					break;
				case 1:
					if(*ptr == '*') { provid = 0; }
					else { provid = a2i(ptr, 6); }
					break;
				case 2:
					if(*ptr == '*') { sid = 0; }
					else { sid = a2i(ptr, 4); }
					break;
				case 3:
					if(*ptr == '*') { chid = 0; }
					else { chid = a2i(ptr, 4); }
					break;
				}
			}
			if(!cs_malloc(&cur_cpmap, sizeof(struct s_cpmap)))
			{
				for(cur_cpmap = first_cpmap; cur_cpmap;)
				{
					last_cpmap = cur_cpmap;
					cur_cpmap = cur_cpmap->next;
					free(last_cpmap);
				}
				free(token);
				return;
			}
			if(last_cpmap)
				{ last_cpmap->next = cur_cpmap; }
			else
				{ first_cpmap = cur_cpmap; }
			last_cpmap = cur_cpmap;

			cur_cpmap->caid   = caid;
			cur_cpmap->provid = provid;
			cur_cpmap->sid    = sid;
			cur_cpmap->chid   = chid;
			cur_cpmap->dwtime = dwtime;
			cur_cpmap->next   = 0;

			cs_debug_mask(D_CLIENT, "nr=%d, caid=%04X, provid=%06X, sid=%04X, chid=%04X, dwtime=%d",
						  nr, caid, provid, sid, chid, dwtime);
			nr++;
		}
	}
	free(token);
	fclose(fp);

	last_cpmap = cfg.cpmap;
	cfg.cpmap = first_cpmap;
	for(cur_cpmap = last_cpmap; cur_cpmap; cur_cpmap = cur_cpmap->next)
		{ add_garbage(cur_cpmap); }
	//cs_log("%d lengths for caid guessing loaded", nr);
	return;
}
Exemple #9
0
static int
mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset)
{
	char *next = NULL;
	char *str = NULL;
	int fd, result;
	ssize_t r, w, e;
	ssize_t skip = 0;
	uint32_t offset = 0;
	int jffs2_replaced = 0;
	int skip_bad_blocks = 0;

#ifdef FIS_SUPPORT
	static struct fis_part new_parts[MAX_ARGS];
	static struct fis_part old_parts[MAX_ARGS];
	int n_new = 0, n_old = 0;

	if (fis_layout) {
		const char *tmp = mtd;
		char *word, *brkt;
		int ret;

		memset(&old_parts, 0, sizeof(old_parts));
		memset(&new_parts, 0, sizeof(new_parts));

		do {
			next = strchr(tmp, ':');
			if (!next)
				next = (char *) tmp + strlen(tmp);

			memcpy(old_parts[n_old].name, tmp, next - tmp);

			n_old++;
			tmp = next + 1;
		} while(*next);

		for (word = strtok_r(fis_layout, ",", &brkt);
		     word;
			 word = strtok_r(NULL, ",", &brkt)) {

			tmp = strtok(word, ":");
			strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1);

			tmp = strtok(NULL, ":");
			if (!tmp)
				goto next;

			new_parts[n_new].size = strtoul(tmp, NULL, 0);

			tmp = strtok(NULL, ":");
			if (!tmp)
				goto next;

			new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16);
next:
			n_new++;
		}
		ret = fis_validate(old_parts, n_old, new_parts, n_new);
		if (ret < 0) {
			fprintf(stderr, "Failed to validate the new FIS partition table\n");
			exit(1);
		}
		if (ret == 0)
			fis_layout = NULL;
	}
#endif

	if (strchr(mtd, ':')) {
		str = strdup(mtd);
		mtd = str;
	}

	r = 0;

resume:
	next = strchr(mtd, ':');
	if (next) {
		*next = 0;
		next++;
	}

	fd = mtd_check_open(mtd);
	if(fd < 0) {
		fprintf(stderr, "Could not open mtd device: %s\n", mtd);
		exit(1);
	}
	if (part_offset > 0) {
		fprintf(stderr, "Seeking on mtd device '%s' to: %zu\n", mtd, part_offset);
		lseek(fd, part_offset, SEEK_SET);
	}

	indicate_writing(mtd);

	w = e = 0;
	for (;;) {
		/* buffer may contain data already (from trx check or last mtd partition write attempt) */
		while (buflen < erasesize) {
			r = read(imagefd, buf + buflen, erasesize - buflen);
			if (r < 0) {
				if ((errno == EINTR) || (errno == EAGAIN))
					continue;
				else {
					perror("read");
					break;
				}
			}

			if (r == 0)
				break;

			buflen += r;
		}

		if (buflen == 0)
			break;

		if (buflen < erasesize) {
			/* Pad block to eraseblock size */
			memset(&buf[buflen], 0xff, erasesize - buflen);
			buflen = erasesize;
		}

		if (skip > 0) {
			skip -= buflen;
			buflen = 0;
			if (skip <= 0)
				indicate_writing(mtd);

			continue;
		}

		if (jffs2file && w >= jffs2_skip_bytes) {
			if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) {
				if (!quiet)
					fprintf(stderr, "\b\b\b   ");
				if (quiet < 2)
					fprintf(stderr, "\nAppending jffs2 data from %s to %s...", jffs2file, mtd);
				/* got an EOF marker - this is the place to add some jffs2 data */
				skip = mtd_replace_jffs2(mtd, fd, e, jffs2file);
				jffs2_replaced = 1;

				/* don't add it again */
				jffs2file = NULL;

				w += skip;
				e += skip;
				skip -= buflen;
				buflen = 0;
				offset = 0;
				continue;
			}
			/* no EOF marker, make sure we figure out the last inode number
			 * before appending some data */
			mtd_parse_jffs2data(buf, jffs2dir);
		}

		/* need to erase the next block before writing data to it */
		if(!no_erase)
		{
			while (w + buflen > e - skip_bad_blocks) {
				if (!quiet)
					fprintf(stderr, "\b\b\b[e]");

				if (mtd_block_is_bad(fd, e)) {
					if (!quiet)
						fprintf(stderr, "\nSkipping bad block at 0x%08zx   ", e);

					skip_bad_blocks += erasesize;
					e += erasesize;

					// Move the file pointer along over the bad block.
					lseek(fd, erasesize, SEEK_CUR);
					continue;
				}

				if (mtd_erase_block(fd, e) < 0) {
					if (next) {
						if (w < e) {
							write(fd, buf + offset, e - w);
							offset = e - w;
						}
						w = 0;
						e = 0;
						close(fd);
						mtd = next;
						fprintf(stderr, "\b\b\b   \n");
						goto resume;
					} else {
						fprintf(stderr, "Failed to erase block\n");
						exit(1);
					}
				}

				/* erase the chunk */
				e += erasesize;
			}
		}

		if (!quiet)
			fprintf(stderr, "\b\b\b[w]");

		if ((result = write(fd, buf + offset, buflen)) < buflen) {
			if (result < 0) {
				fprintf(stderr, "Error writing image.\n");
				exit(1);
			} else {
				fprintf(stderr, "Insufficient space.\n");
				exit(1);
			}
		}
		w += buflen;

		buflen = 0;
		offset = 0;
	}

	if (jffs2_replaced && trx_fixup) {
		trx_fixup(fd, mtd);
	}

	if (!quiet)
		fprintf(stderr, "\b\b\b\b    ");

	if (quiet < 2)
		fprintf(stderr, "\n");

#ifdef FIS_SUPPORT
	if (fis_layout) {
		if (fis_remap(old_parts, n_old, new_parts, n_new) < 0)
			fprintf(stderr, "Failed to update the FIS partition table\n");
	}
#endif

	close(fd);
	return 0;
}
Exemple #10
0
static int powerdns_read_recursor (list_item_t *item) /* {{{ */
{
  char *buffer = NULL;
  size_t buffer_size = 0;
  int status;

  char *dummy;

  char *keys_list;
  char *key;
  char *key_saveptr;
  char *value;
  char *value_saveptr;

  if (item->command == NULL)
  {
    status = powerdns_update_recursor_command (item);
    if (status != 0)
    {
      ERROR ("powerdns plugin: powerdns_update_recursor_command failed.");
      return (-1);
    }

    DEBUG ("powerdns plugin: powerdns_read_recursor: item->command = %s;",
        item->command);
  }
  assert (item->command != NULL);

  status = powerdns_get_data (item, &buffer, &buffer_size);
  if (status != 0)
  {
    ERROR ("powerdns plugin: powerdns_get_data failed.");
    return (-1);
  }

  keys_list = strdup (item->command);
  if (keys_list == NULL)
  {
    FUNC_ERROR ("strdup");
    sfree (buffer);
    return (-1);
  }

  key_saveptr = NULL;
  value_saveptr = NULL;

  /* Skip the `get' at the beginning */
  strtok_r (keys_list, " \t", &key_saveptr);

  dummy = buffer;
  while ((value = strtok_r (dummy, " \t\n\r", &value_saveptr)) != NULL)
  {
    dummy = NULL;

    key = strtok_r (NULL, " \t", &key_saveptr);
    if (key == NULL)
      break;

    submit (item->instance, key, value);
  } /* while (strtok_r) */

  sfree (buffer);
  sfree (keys_list);

  return (0);
} /* }}} int powerdns_read_recursor */
int oP_Tab_main(opcd **pHead)
{
	FILE *fp;
	char *input,*str1, *str2, *subtoken, *type, *temp,*saveptr2, *buffer;
	int j, count=0;

	input = (char *) malloc(sizeof(char) * 70);

	fp=fopen("myInput.text","r");

	if(fp==NULL)
		printf("File Does Not Exist.");
	while(fgets(input, 70, fp) != NULL)
	{

		count++;
		str1=(char*)malloc(sizeof(char)*(strlen(input)+1));

		buffer=(char*)malloc(sizeof(char)*(strlen(input)+1));

		strcpy(str1,input);
		/////////////
		input = strtok(str1, ";");
		subtoken = strtok_r(input, " \t",&saveptr2);
		str2 = NULL;
		for (; ;str2 = NULL)
		{
			subtoken = strtok_r(str2, " \t", &saveptr2);
			if (subtoken == NULL)
				break;


			str1 = strtok_r(str2, " \t", &saveptr2);
			if (str1 == NULL)
				break;
			buffer = strtok_r(str2, " \t", &saveptr2);
			if (buffer == NULL)
				break;
			j=strlen(buffer);

			if(buffer[j-1]==':')
				buffer = strtok_r(str2, " \t", &saveptr2);
			if (buffer == NULL)
				break;
			type = strtok_r(str2, " ,\t", &saveptr2);
			if (type == NULL)
				break;
			temp = strtok_r(str2, " ,\t", &saveptr2);
			if (temp == NULL)
				break;

			optable(pHead,str1,buffer,type,temp);

			str1=buffer=type=temp=NULL; 


		}

		free(input);
		input = (char *) malloc(sizeof(char) * 70);
	}

	//prnt_opcd(pHead);
	fclose(fp);
	return 0;
}
Exemple #12
0
static int powerdns_read_server (list_item_t *item) /* {{{ */
{
  char *buffer = NULL;
  size_t buffer_size = 0;
  int status;

  char *dummy;
  char *saveptr;

  char *key;
  char *value;

  const char* const *fields;
  int fields_num;

  if (item->command == NULL)
    item->command = strdup (SERVER_COMMAND);
  if (item->command == NULL)
  {
    ERROR ("powerdns plugin: strdup failed.");
    return (-1);
  }

  status = powerdns_get_data (item, &buffer, &buffer_size);
  if (status != 0)
    return (-1);

  if (item->fields_num != 0)
  {
    fields = (const char* const *) item->fields;
    fields_num = item->fields_num;
  }
  else
  {
    fields = default_server_fields;
    fields_num = default_server_fields_num;
  }

  assert (fields != NULL);
  assert (fields_num > 0);

  /* corrupt-packets=0,deferred-cache-inserts=0,deferred-cache-lookup=0,latency=0,packetcache-hit=0,packetcache-miss=0,packetcache-size=0,qsize-q=0,query-cache-hit=0,query-cache-miss=0,recursing-answers=0,recursing-questions=0,servfail-packets=0,tcp-answers=0,tcp-queries=0,timedout-packets=0,udp-answers=0,udp-queries=0,udp4-answers=0,udp4-queries=0,udp6-answers=0,udp6-queries=0, */
  dummy = buffer;
  saveptr = NULL;
  while ((key = strtok_r (dummy, ",", &saveptr)) != NULL)
  {
    int i;

    dummy = NULL;

    value = strchr (key, '=');
    if (value == NULL)
      break;

    *value = '\0';
    value++;

    if (value[0] == '\0')
      continue;

    /* Check if this item was requested. */
    for (i = 0; i < fields_num; i++)
      if (strcasecmp (key, fields[i]) == 0)
	break;
    if (i >= fields_num)
      continue;

    submit (item->instance, key, value);
  } /* while (strtok_r) */

  sfree (buffer);

  return (0);
} /* }}} int powerdns_read_server */
Exemple #13
0
int main(int argc, char *argv[])
{   
	/* System call shell command */
    
	system("ls -l >> assignment.txt");
    
    /* Read shell command results */

    char temp_hold[LENGTH];
    char permission_hold[LENGTH];
    char *filesize_hold;
    int permission_check = 0;
    int filesize_check = 0;
    char *delim = " ";
    int loop_control;
    char *permission_argv;
    int condition = 0;
    char *filesize_temp;
    int temp_int = 0;
    int flag = 0;


	FILE *fp;
	fp = fopen("./assignment.txt", "r");
    if(fp == NULL)
    {
    	printf("No Such File !!!\n");
    }
    fgets(temp_hold, STRING, fp);
    


	char *num = "1234567890";
	char *p;
    if(argc == 2)
    {  
       p = strpbrk(argv[1], num);
       if(!p)
       {  
          //Only Permission Check
       	  while(!feof(fp))
          {  
             flag = 2;
             fgets(temp_hold, STRING, fp);
             strcpy(permission_hold, strtok(temp_hold, delim));
             permission_argv = strndup(permission_hold+1, 9);
             condition = check_permission(permission_argv, argv[1]);
             if(condition == 1)
             {
                permission_check += 1;
             }

          }
       }
       else
       {  
          //Only Filesize Check
          while(!feof(fp))
          { 
            flag = 1;
            loop_control = 0;
            fgets(temp_hold, STRING, fp);
            filesize_hold = strtok_r(temp_hold, " ", &filesize_temp);
            while(filesize_hold != NULL)
            {   
                if(loop_control == 4)
                {
                   break;
                }
                filesize_hold = strtok_r(NULL, " ", &filesize_temp);
                loop_control++;
            }
            if(filesize_hold)
            {
                temp_int = atoi(filesize_hold);
                if(temp_int >= atoi(argv[1]))
                {
                    filesize_check += 1;

                }
            }
            
          }
       }
    }
    else if(argc == 3)
    {
         while(!feof(fp))
          {
            loop_control = 0;
            fgets(temp_hold, STRING, fp);
            filesize_hold = strtok_r(temp_hold, " ", &filesize_temp);
            while (filesize_hold != NULL)
            {   
                if(loop_control == 4)
                {
                   break;
                }
                filesize_hold = strtok_r(NULL, " ", &filesize_temp);
                loop_control++;
            }
            if(filesize_hold)
            {
                temp_int = atoi(filesize_hold);
                if(temp_int >= atoi(argv[1]))
                {
                    filesize_check += 1;

                }
            }
            
          }

        fclose(fp);

        FILE *fptr;
        fptr = fopen("./assignment.txt", "r");
        if(fptr == NULL)
        {
            printf("No Such File !!!\n");
        }
        fgets(temp_hold, STRING, fptr);
        while(!feof(fptr))
        {  
             fgets(temp_hold, STRING, fptr);
             strcpy(permission_hold, strtok(temp_hold, delim));
             permission_argv = strndup(permission_hold+1, 9);
             condition = check_permission(permission_argv, argv[2]);
             if(condition == 1)
             {
                permission_check += 1;
             }

        }
        fclose(fptr);

    }
    else if(argc == 1)
    {
    	printf("No argument !!\n");
    }
    permission_check = permission_check - 1;
    if(argc == 2)
    {
        if(flag == 1)
        {
           printf("%d \n", filesize_check);
        }
        if(flag == 2)
        {
           printf("%d \n", permission_check);
        }
    }
    if(argc == 3)
    {   
        if(filesize_check > permission_check)
        {
            printf("%d \n", permission_check);
        }
        else
        {
            printf("%d \n", filesize_check);
        }
    }

    return 0;
}
Exemple #14
0
CURLdigest Curl_input_digest(struct connectdata *conn,
                             bool proxy,
                             const char *header) /* rest of the *-authenticate:
                                                    header */
{
  bool more = TRUE;
  char *token = NULL;
  char *tmp = NULL;
  bool foundAuth = FALSE;
  bool foundAuthInt = FALSE;
  struct SessionHandle *data=conn->data;
  bool before = FALSE; /* got a nonce before */
  struct digestdata *d;

  if(proxy) {
    d = &data->state.proxydigest;
  }
  else {
    d = &data->state.digest;
  }

  /* skip initial whitespaces */
  while(*header && ISSPACE(*header))
    header++;

  if(checkprefix("Digest", header)) {
    header += strlen("Digest");

    /* If we already have received a nonce, keep that in mind */
    if(d->nonce)
      before = TRUE;

    /* clear off any former leftovers and init to defaults */
    Curl_digest_cleanup_one(d);

    while(more) {
      char value[MAX_VALUE_LENGTH];
      char content[MAX_CONTENT_LENGTH];

      while(*header && ISSPACE(*header))
        header++;

      /* extract a value=content pair */
      if(!get_pair(header, value, content, &header)) {
        if(Curl_raw_equal(value, "nonce")) {
          d->nonce = strdup(content);
          if(!d->nonce)
            return CURLDIGEST_NOMEM;
        }
        else if(Curl_raw_equal(value, "stale")) {
          if(Curl_raw_equal(content, "true")) {
            d->stale = TRUE;
            d->nc = 1; /* we make a new nonce now */
          }
        }
        else if(Curl_raw_equal(value, "realm")) {
          d->realm = strdup(content);
          if(!d->realm)
            return CURLDIGEST_NOMEM;
        }
        else if(Curl_raw_equal(value, "opaque")) {
          d->opaque = strdup(content);
          if(!d->opaque)
            return CURLDIGEST_NOMEM;
        }
        else if(Curl_raw_equal(value, "qop")) {
          char *tok_buf;
          /* tokenize the list and choose auth if possible, use a temporary
             clone of the buffer since strtok_r() ruins it */
          tmp = strdup(content);
          if(!tmp)
            return CURLDIGEST_NOMEM;
          token = strtok_r(tmp, ",", &tok_buf);
          while(token != NULL) {
            if(Curl_raw_equal(token, "auth")) {
              foundAuth = TRUE;
            }
            else if(Curl_raw_equal(token, "auth-int")) {
              foundAuthInt = TRUE;
            }
            token = strtok_r(NULL, ",", &tok_buf);
          }
          free(tmp);
          /*select only auth o auth-int. Otherwise, ignore*/
          if(foundAuth) {
            d->qop = strdup("auth");
            if(!d->qop)
              return CURLDIGEST_NOMEM;
          }
          else if(foundAuthInt) {
            d->qop = strdup("auth-int");
            if(!d->qop)
              return CURLDIGEST_NOMEM;
          }
        }
        else if(Curl_raw_equal(value, "algorithm")) {
          d->algorithm = strdup(content);
          if(!d->algorithm)
            return CURLDIGEST_NOMEM;
          if(Curl_raw_equal(content, "MD5-sess"))
            d->algo = CURLDIGESTALGO_MD5SESS;
          else if(Curl_raw_equal(content, "MD5"))
            d->algo = CURLDIGESTALGO_MD5;
          else
            return CURLDIGEST_BADALGO;
        }
        else {
          /* unknown specifier, ignore it! */
        }
      }
      else
        break; /* we're done here */

      /* pass all additional spaces here */
      while(*header && ISSPACE(*header))
        header++;
      if(',' == *header)
        /* allow the list to be comma-separated */
        header++;
    }
    /* We had a nonce since before, and we got another one now without
       'stale=true'. This means we provided bad credentials in the previous
       request */
    if(before && !d->stale)
      return CURLDIGEST_BAD;

    /* We got this header without a nonce, that's a bad Digest line! */
    if(!d->nonce)
      return CURLDIGEST_BAD;
  }
  else
    /* else not a digest, get out */
    return CURLDIGEST_NONE;

  return CURLDIGEST_FINE;
}
Exemple #15
0
/**
 * Reads and parses the file request lines received from the client. 
 * @param req: location where this method writes the requested 
 *             filename or directory.
 * @param buff: buffer where the HTTP request is stored.
 * @param response: instance of Struct HTTP_Response which this method will
 *				    populate based on the HTTP request in buff.
 */
void ExtractFileRequest(char *req, char *buff, HTTP_Response *response ) {

	int lastPos = (int)(strchr(buff, '\n') - buff) - 1; //Newline is \r\n
	                                                      
	/* We should now have the ending position to get the following line:
	 * "GET / HTTP/1.0"
	 * So split it based on space delimeter to get URL path 
	 * and HTTP version.
	 */

	//printf("entire buffer: %s\nLast pos: %d\n", buff, lastPos);
	//printf("End of first line position: %d\n", lastPos);

	char *tempBuff = malloc(strlen(buff));
	strcpy(tempBuff, buff);

	char *split, *savePtr;
	int i = 0;
	int total = 0;
	while (total < lastPos)
	{
		if (total == 0)
		{
			split = strtok_r(tempBuff, " ", &savePtr);
		}
		else
		{
			split = strtok_r(NULL, " ", &savePtr);
		}
		int size = strlen(split);
		
		switch(i)
		{
			case 0: //Method (GET, POST, HEAD...)
				response->HTTP_Type = malloc(size + 1);
				strcpy(response -> HTTP_Type, split);
				break;
			case 1: //File content path
				strcpy(req, split);
				break;
			case 2: //HTTP Protocol (ex HTTP/1.1)
				
				/* There is no space after the version number, 
				 * only a newline character. So split again. */
				split = strtok(split, "\r\n");
				size = strlen(split);
				response->versionNum = malloc(size + 1);
				strcpy(response -> versionNum, split);
				break;
		}
		total += size + 1; //+1 to account for space
		i++;	
		printf("Split string: %s, size: %d\n", split, size); 
	}
	// Find the Accept: ... line in the get response
	strcpy(tempBuff, buff);

	split = strstr(tempBuff, "Accept: ");
	split = split + strlen("Accept: ");  //Should put us right after Accept: statement
	char *content_type = strtok(split, "\n");
	
	/* If content_type only contains one element, strtok will return NULL.
	 * If content_type has multiple elements (seperated by commas), strtok will 
	 * null terminate the first comma, so content_type will point to only the first element */	 
	strtok(content_type, ",");
	
	printf("Content-type: %s\n", content_type);
	response -> contentType = malloc(strlen(content_type) + 1);
	strcpy(response -> contentType, content_type);

	char *result = "200";
	response -> resultCode = malloc(strlen(result) + 1);
    strcpy(response -> resultCode, result);

	char *stat = "OK";	
	response -> status = malloc(strlen(stat) + 1);
	strcpy(response -> status, stat);

	/*
	 * Check if content requested (req) contains any user variables
	 * GET request contains data in content URL,
	 * POST containst data at the end of the buffer
	 */
	
	char *t = NULL;
	char *userVarStart = NULL;
    if (strcmp(response -> HTTP_Type, "POST") == 0)
	{
		//Print buffer for debug
		printf("Header:\n%s\n\n", buff);

		// Check if POST request with data AFTER the header
		printf("POST Request. Checking for user data\n");
		t = strstr(buff, "\r\n\r\n"); //CRLF is new line
	}
	else if ((t = strchr(req, '?')) != NULL)
	{
		// GET request with data in URL
		printf("GET Request. Checking for user data\n");
		*t = '\0'; //NULL '?' so file request is seperated from the user vars
		t++;
	}
	
	if (t != NULL)
	{
		userVarStart = malloc(strlen(t) + 14);
		sprintf(userVarStart, "QUERY_STRING=%s", t);
		printf("User data: %s\nFile: %s\n\n", userVarStart, req);

		// Add the user variables to QUERY_STRING environment variable
	    putenv(userVarStart); 
	}
		
}
Exemple #16
0
void apicmd_kvercmp2(int argc, char *argv[])
{
	int exit_value;

	struct tst_kern_exv vers[100];
	unsigned int count;

	char *saveptr1 = NULL;
	char *saveptr2 = NULL;
	char *token1;

	if (TCID == NULL)
		TCID = "outoftest";
	if (tst_cntstr == NULL)
		tst_count = 0;

	if (argc < 5) {
		fprintf(stderr, "Usage: %s NUM NUM NUM KVERS\n"
			"Compares to the running kernel version\n"
			"based on vanilla kernel version NUM NUM NUM\n"
			"or distribution specific kernel version KVERS\n\n"
			"\tNUM - A positive integer.\n"
			"\tThe first NUM is the kernel VERSION\n"
			"\tThe second NUM is the kernel PATCHLEVEL\n"
			"\tThe third NUM is the kernel SUBLEVEL\n\n"
			"\tKVERS is a string of the form "
			"\"DISTR1:VERS1 DISTR2:VERS2\",\n"
			"\twhere DISTR1 is a distribution name\n"
			"\tand VERS1 is the corresponding kernel version.\n"
			"\tExample: \"RHEL6:2.6.39-400.208\"\n\n"
			"\tIf running kernel matches a distribution in KVERS then\n"
			"\tcomparison is performed based on version in KVERS,\n"
			"\totherwise - based on NUM NUM NUM.\n\n"
			"\tExit status is 0 if the running kernel is older.\n"
			"\tExit status is 1 for kernels of the same age.\n"
			"\tExit status is 2 if the running kernel is newer.\n",
			cmd_name);
		exit(3);
	}

	count = 0;
	token1 = strtok_r(argv[3], " ", &saveptr1);
	while ((token1 != NULL) && (count < 99)) {
		vers[count].dist_name = strtok_r(token1, ":", &saveptr2);
		vers[count].extra_ver = strtok_r(NULL, ":", &saveptr2);

		if (vers[count].extra_ver == NULL) {
			fprintf(stderr, "Incorrect KVERS format\n");
			exit(3);
		}

		count++;

		token1 = strtok_r(NULL, " ", &saveptr1);
	}
	vers[count].dist_name = NULL;
	vers[count].extra_ver = NULL;

	exit_value = tst_kvercmp2(atoi(argv[0]), atoi(argv[1]),
				atoi(argv[2]), vers);

	if (exit_value < 0)
		exit_value = 0;
	else if (exit_value == 0)
		exit_value = 1;
	else if (exit_value > 0)
		exit_value = 2;
	exit(exit_value);
}
Exemple #17
0
/* Run a command.  Commands are defined in commands.h */
int runCommand() {
  int i = 0;
  char *p = argv1;
  char *str;
  int pid_args[4];
  arg1 = atoi(argv1);
  arg2 = atoi(argv2);

  switch(cmd) {
  case GET_TICKS:
	Serial.println(ticks);
	break;
  case GET_BAUDRATE:
    Serial.println(BAUDRATE);
    break;
  case ANALOG_READ:
    Serial.println(analogRead(arg1));
    break;
  case DIGITAL_READ:
    Serial.println(digitalRead(arg1));
    break;
  case ANALOG_WRITE:
    analogWrite(arg1, arg2);
    Serial.println("OK");
    break;
  case DIGITAL_WRITE:
    if (arg2 == 0) digitalWrite(arg1, LOW);
    else if (arg2 == 1) digitalWrite(arg1, HIGH);
    Serial.println("OK");
    break;
  case PIN_MODE:
    if (arg2 == 0) pinMode(arg1, INPUT);
    else if (arg2 == 1) pinMode(arg1, OUTPUT);
    Serial.println("OK");
    break;
  case PING:
    Serial.println(Ping(arg1));
    break;
#ifdef USE_SERVOS
  case SERVO_WRITE:
    servos[arg1].write(arg2);
    Serial.println("OK");
    break;
  case SERVO_READ:
    Serial.println(servos[arg1].read());
    break;
#endif

#ifdef USE_BASE

  case READ_ENCODERS:
    Serial.print(readEncoder(LEFT));
    Serial.print(" ");
    Serial.println(readEncoder(RIGHT));
    break;
   case RESET_ENCODERS:
    resetEncoders();
    Serial.println("OK");
    break;
   case READ_MOTORS:
	   Serial.print(leftPID.output);
	   Serial.print(" ");
	   Serial.println(rightPID.output);
	   break;
  case MOTOR_SPEEDS:
    /* Reset the auto stop timer */
    lastMotorCommand = millis();
    if (arg1 == 0 && arg2 == 0) {
      setMotorSpeeds(0, 0);
      moving = 0;
      resetPID();
    }
    else moving = 1;
    leftPID.TargetTicksPerFrame = arg1;
    rightPID.TargetTicksPerFrame = arg2;
    Serial.println("OK");
    break;
  case UPDATE_PID:
    while ((str = strtok_r(p, ":", &p)) != '\0') {
       pid_args[i] = atoi(str);
       i++;
    }
    Kp = pid_args[0];
    Kd = pid_args[1];
    Ki = pid_args[2];
    Ko = pid_args[3];
    Serial.println("OK");
    break;
#endif
  default:
    Serial.println("Invalid Command");
    break;
  }
}
Exemple #18
0
static int search_pemap(char *pecoremap, int pe)
{
  int *map = (int *)malloc(CmiNumPesGlobal()*sizeof(int));
  char *ptr = NULL;
  int h, i, j, k, count;
  int plusarr[128];
  char *str;

  char *mapstr = (char*)malloc(strlen(pecoremap)+1);
  strcpy(mapstr, pecoremap);

  str = strtok_r(mapstr, ",", &ptr);
  count = 0;
  while (str && count < CmiNumPesGlobal())
  {
      int hasdash=0, hascolon=0, hasdot=0, hasstar1=0, hasstar2=0, numplus=0;
      int start, end, stride=1, block=1;
      int iter=1;
      plusarr[0] = 0;
      for (i=0; i<strlen(str); i++) {
          if (str[i] == '-' && i!=0) hasdash=1;
          else if (str[i] == ':') hascolon=1;
	  else if (str[i] == '.') hasdot=1;
	  else if (str[i] == 'x') hasstar1=1;
	  else if (str[i] == 'X') hasstar2=1;
	  else if (str[i] == '+') {
            if (str[i+1] == '+' || str[i+1] == '-') {
              printf("Warning: Check the format of \"%s\".\n", str);
            } else if (sscanf(&str[i], "+%d", &plusarr[++numplus]) != 1) {
              printf("Warning: Check the format of \"%s\".\n", str);
              --numplus;
            }
          }
      }
      if (hasstar1 || hasstar2) {
          if (hasstar1) sscanf(str, "%dx", &iter);
          if (hasstar2) sscanf(str, "%dX", &iter);
          while (*str!='x' && *str!='X') str++;
          str++;
      }
      if (hasdash) {
          if (hascolon) {
            if (hasdot) {
              if (sscanf(str, "%d-%d:%d.%d", &start, &end, &stride, &block) != 4)
                 printf("Warning: Check the format of \"%s\".\n", str);
            }
            else {
              if (sscanf(str, "%d-%d:%d", &start, &end, &stride) != 3)
                 printf("Warning: Check the format of \"%s\".\n", str);
            }
          }
          else {
            if (sscanf(str, "%d-%d", &start, &end) != 2)
                 printf("Warning: Check the format of \"%s\".\n", str);
          }
      }
      else {
          sscanf(str, "%d", &start);
          end = start;
      }
      if (block > stride) {
        printf("Warning: invalid block size in \"%s\" ignored.\n", str);
        block=1;
      }
      //if (CmiMyPe() == 0) printf("iter: %d start: %d end: %d stride: %d, block: %d. plus %d \n", iter, start, end, stride, block, numplus);
      for (k = 0; k<iter; k++) {
        for (i = start; i<=end; i+=stride) {
          for (j=0; j<block; j++) {
            if (i+j>end) break;
            for (h=0; h<=numplus; h++) {
              map[count++] = i+j+plusarr[h];
              if (count == CmiNumPesGlobal()) break;
            }
            if (count == CmiNumPesGlobal()) break;
          }
          if (count == CmiNumPesGlobal()) break;
        }
        if (count == CmiNumPesGlobal()) break;
      }
      str = strtok_r(NULL, ",", &ptr);
  }
  i = map[pe % count];

  free(map);
  free(mapstr);
  return i;
}
/**
 * video_shader_parse_textures:
 * @conf              : Preset file to read from.
 * @shader            : Shader pass handle.
 *
 * Parses shader textures.
 *
 * Returns: true (1) if successful, otherwise false (0).
 **/
static bool video_shader_parse_textures(config_file_t *conf,
      struct video_shader *shader)
{
   size_t path_size     = PATH_MAX_LENGTH * sizeof(char);
   const char *id       = NULL;
   char *save           = NULL;
   char *textures       = (char*)malloc(1024 * sizeof(char));

   textures[0]          = '\0';

   if (!config_get_array(conf, "textures", textures, 1024 * sizeof(char)))
   {
      free(textures);
      return true;
   }

   for (id = strtok_r(textures, ";", &save);
         id && shader->luts < GFX_MAX_TEXTURES;
         shader->luts++, id = strtok_r(NULL, ";", &save))
   {
      char id_filter[64];
      char id_wrap[64];
      char wrap_mode[64];
      char id_mipmap[64];
      bool mipmap         = false;
      bool smooth         = false;
      char *tmp_path      = NULL;

      id_filter[0] = id_wrap[0] = wrap_mode[0] = id_mipmap[0] = '\0';

      if (!config_get_array(conf, id, shader->lut[shader->luts].path,
               sizeof(shader->lut[shader->luts].path)))
      {
         RARCH_ERR("Cannot find path to texture \"%s\" ...\n", id);
         free(textures);
         return false;
      }

      tmp_path            = (char*)malloc(PATH_MAX_LENGTH * sizeof(char));
      tmp_path[0]         = '\0';
      strlcpy(tmp_path, shader->lut[shader->luts].path,
            path_size);
      path_resolve_realpath(tmp_path, path_size);

      if (filestream_exists(tmp_path))
         strlcpy(shader->lut[shader->luts].path,
            tmp_path, sizeof(shader->lut[shader->luts].path));
      free(tmp_path);

      strlcpy(shader->lut[shader->luts].id, id,
            sizeof(shader->lut[shader->luts].id));

      snprintf(id_filter, sizeof(id_filter), "%s_linear", id);
      if (config_get_bool(conf, id_filter, &smooth))
         shader->lut[shader->luts].filter = smooth ?
            RARCH_FILTER_LINEAR : RARCH_FILTER_NEAREST;
      else
         shader->lut[shader->luts].filter = RARCH_FILTER_UNSPEC;

      snprintf(id_wrap, sizeof(id_wrap), "%s_wrap_mode", id);
      if (config_get_array(conf, id_wrap, wrap_mode, sizeof(wrap_mode)))
         shader->lut[shader->luts].wrap = wrap_str_to_mode(wrap_mode);

      snprintf(id_mipmap, sizeof(id_mipmap), "%s_mipmap", id);
      if (config_get_bool(conf, id_mipmap, &mipmap))
         shader->lut[shader->luts].mipmap = mipmap;
      else
         shader->lut[shader->luts].mipmap = false;
   }

   free(textures);
   return true;
}
static int memcached_read (void) /* {{{ */
{
	char buf[1024];
	char *fields[3];
	char *ptr;
	char *line;
	char *saveptr;
	int fields_num;

	gauge_t bytes_used = NAN;
	gauge_t bytes_total = NAN;
	gauge_t hits = NAN;
	gauge_t gets = NAN;
	counter_t rusage_user = 0;
	counter_t rusage_syst = 0;
	counter_t octets_rx = 0;
	counter_t octets_tx = 0;

	/* get data from daemon */
	if (memcached_query_daemon (buf, sizeof (buf)) < 0) {
		return -1;
	}

#define FIELD_IS(cnst) \
	(((sizeof(cnst) - 1) == name_len) && (strcmp (cnst, fields[1]) == 0))

	ptr = buf;
	saveptr = NULL;
	while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
	{
		int name_len;

		ptr = NULL;

		fields_num = strsplit(line, fields, 3);
		if (fields_num != 3)
			continue;

		name_len = strlen(fields[1]);
		if (name_len == 0)
			continue;

		/*
		 * For an explanation on these fields please refer to
		 * <http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt>
		 */

		/*
		 * CPU time consumed by the memcached process
		 */
		if (FIELD_IS ("rusage_user"))
		{
			rusage_user = atoll (fields[2]);
		}
		else if (FIELD_IS ("rusage_system"))
		{
			rusage_syst = atoll(fields[2]);
		}

		/*
		 * Number of threads of this instance
		 */
		else if (FIELD_IS ("threads"))
		{
			submit_gauge2 ("ps_count", NULL, NAN, atof (fields[2]));
		}

		/*
		 * Number of items stored
		 */
		else if (FIELD_IS ("curr_items"))
		{
			submit_gauge ("memcached_items", "current", atof (fields[2]));
		}

		/*
		 * Number of bytes used and available (total - used)
		 */
		else if (FIELD_IS ("bytes"))
		{
			bytes_used = atof (fields[2]);
		}
		else if (FIELD_IS ("limit_maxbytes"))
		{
			bytes_total = atof(fields[2]);
		}

		/*
		 * Connections
		 */
		else if (FIELD_IS ("curr_connections"))
		{
			submit_gauge ("memcached_connections", "current", atof (fields[2]));
		}

		/*
		 * Commands
		 */
		else if ((name_len > 4) && (strncmp (fields[1], "cmd_", 4) == 0))
		{
			const char *name = fields[1] + 4;
			submit_counter ("memcached_command", name, atoll (fields[2]));
			if (strcmp (name, "get") == 0)
				gets = atof (fields[2]);
		}

		/*
		 * Operations on the cache, i. e. cache hits, cache misses and evictions of items
		 */
		else if (FIELD_IS ("get_hits"))
		{
			submit_counter ("memcached_ops", "hits", atoll (fields[2]));
			hits = atof (fields[2]);
		}
		else if (FIELD_IS ("get_misses"))
		{
			submit_counter ("memcached_ops", "misses", atoll (fields[2]));
		}
		else if (FIELD_IS ("evictions"))
		{
			submit_counter ("memcached_ops", "evictions", atoll (fields[2]));
		}

		/*
		 * Network traffic
		 */
		else if (FIELD_IS ("bytes_read"))
		{
			octets_rx = atoll (fields[2]);
		}
		else if (FIELD_IS ("bytes_written"))
		{
			octets_tx = atoll (fields[2]);
		}
	} /* while ((line = strtok_r (ptr, "\n\r", &saveptr)) != NULL) */

	if (!isnan (bytes_used) && !isnan (bytes_total) && (bytes_used <= bytes_total))
		submit_gauge2 ("df", "cache", bytes_used, bytes_total - bytes_used);

	if ((rusage_user != 0) || (rusage_syst != 0))
		submit_counter2 ("ps_cputime", NULL, rusage_user, rusage_syst);

	if ((octets_rx != 0) || (octets_tx != 0))
		submit_counter2 ("memcached_octets", NULL, octets_rx, octets_tx);

	if (!isnan (gets) && !isnan (hits))
	{
		gauge_t rate = NAN;

		if (gets != 0.0)
			rate = 100.0 * hits / gets;

		submit_gauge ("percent", "hitratio", rate);
	}

	return 0;
}
Exemple #21
0
/*
** mo_flags
**      parv[0] = sender prefix
**      parv[1] = parameter
*/
static int
mo_flags(struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
	int i, j;
	int isadd;
	int setflags;
	int isgood;
	char *p;
	char *flag;

	if(parc < 2)
	{
		/* Generate a list of what flags you have and what you are missing,
		 ** and send it to the user
		 */
		sendto_one(source_p, ":%s NOTICE %s :Current flags:%s",
			   me.name, parv[0], set_flags_to_string(source_p));
		sendto_one(source_p, ":%s NOTICE %s :Current missing flags:%s",
			   me.name, parv[0], unset_flags_to_string(source_p));
		return 1;
	}

	/* Preserve the current flags */
	setflags = source_p->umodes;

/* XXX - change this to support a multiple last parameter like ISON */

	for(i = 1; i < parc; i++)
	{
		char *s = LOCAL_COPY(parv[i]);
		for(flag = strtok_r(s, " ", &p); flag; flag = strtok_r(NULL, " ", &p))
		{
			/* We default to being in ADD mode */
			isadd = 1;

			/* We default to being in BAD mode */
			isgood = 0;

			if(!isalpha(flag[0]))
			{
				if(flag[0] == '-')
					isadd = 0;
				else if(flag[0] == '+')
					isadd = 1;
				flag++;
			}

			/* support ALL here */
			if(!irccmp(flag, "ALL"))
			{
				if(isadd)
					source_p->umodes |= FL_ALL_OPER_FLAGS;
				else
					source_p->umodes &= ~FL_ALL_OPER_FLAGS;
				sendto_one(source_p, ":%s NOTICE %s :Current flags:%s",
					   me.name, parv[0], set_flags_to_string(source_p));
				sendto_one(source_p, ":%s NOTICE %s :Current missing flags:%s",
					   me.name, parv[0], unset_flags_to_string(source_p));
				send_umode_out(client_p, source_p, setflags);
				return 1;
			}

			if(!irccmp(flag, "NICKCHANGES"))
			{
				if(!IsOperN(source_p))
				{
					sendto_one(source_p,
						   ":%s NOTICE %s :*** You need oper and N flag for +n",
						   me.name, parv[0]);
					continue;
				}
				if(isadd)
					source_p->umodes |= UMODE_NCHANGE;
				else
					source_p->umodes &= ~UMODE_NCHANGE;
				isgood = 1;
				continue;
			}
			if(!irccmp(flag, "OWALLOPS"))
			{
				if(!IsOperOperwall(source_p))
				{
					sendto_one(source_p,
						   ":%s NOTICE %s :*** You need oper and operwall flag for +z",
						   me.name, parv[0]);
					continue;
				}
				if(isadd)
					source_p->umodes |= UMODE_OPERWALL;
				else
					source_p->umodes &= ~UMODE_OPERWALL;
				isgood = 1;
				continue;
			}

			for(j = 0; flag_table[j].name; j++)
			{
				if(!irccmp(flag, flag_table[j].name))
				{
					if(isadd)
						source_p->umodes |= flag_table[j].mode;
					else
						source_p->umodes &= ~(flag_table[j].mode);
					isgood = 1;
					continue;
				}
			}
			/* This for ended without matching a valid FLAG, here is where
			 ** I want to operate differently than ircd-comstud, and just ignore
			 ** the invalid flag, send a warning and go on.
			 */
			if(!isgood)
				sendto_one(source_p, ":%s NOTICE %s :Invalid FLAGS: %s (IGNORING)",
					   me.name, parv[0], flag);
		}
	}

	/* All done setting the flags, print the notices out to the user
	 ** telling what flags they have and what flags they are missing
	 */
	sendto_one(source_p, ":%s NOTICE %s :Current flags:%s",
		   me.name, parv[0], set_flags_to_string(source_p));
	sendto_one(source_p, ":%s NOTICE %s :Current missing flags:%s",
		   me.name, parv[0], unset_flags_to_string(source_p));

	send_umode_out(client_p, source_p, setflags);
	return 0;
}
Exemple #22
0
static int get_user_hash(const char *user, u8 *dst_hash, u32 dst_len)
{
	int fd, rc;
	u32 len;
	size_t buf_rd;
	char buf[VFS_LOAD_BUF_SZ];
	struct stat st;
	u32 tok_len;
	char *token, *save;
	const char *delim = "\n";
	u32 end, cleanup = 0;
	const char *path = CONFIG_LIBAUTH_FILE;

	fd = vfs_open(path, O_RDONLY, 0);
	if (fd < 0) {
		return VMM_EFAIL;
	}

	rc = vfs_fstat(fd, &st);
	if (rc) {
		vfs_close(fd);
		return VMM_EFAIL;
	}

	if (!(st.st_mode & S_IFREG)) {
		vfs_close(fd);
		return VMM_EFAIL;
	}

	len = st.st_size;
	while (len) {
		memset(buf, 0, sizeof(buf));

		buf_rd = (len < VFS_LOAD_BUF_SZ) ? len : VFS_LOAD_BUF_SZ;
		buf_rd = vfs_read(fd, buf, buf_rd);
		if (buf_rd < 1) {
			break;
		}

		end = buf_rd - 1;
		while (buf[end] != '\n') {
			buf[end] = 0;
			end--;
			cleanup++;
		}

		if (cleanup) {
			vfs_lseek(fd, (buf_rd - cleanup), SEEK_SET);
			cleanup = 0;
		}

		for (token = strtok_r(buf, delim, &save); token;
		     token = strtok_r(NULL, delim, &save)) {
			tok_len = strlen(token);
			if (*token != '#' && *token != '\n') {
				if (process_auth_entry(token, user,
						dst_hash, dst_len) == VMM_OK)
					return VMM_OK;
			}

			len -= (tok_len + 1);
		}
	}

	rc = vfs_close(fd);
	if (rc) {
		return VMM_EFAIL;
	}

	return VMM_EFAIL;
}
Exemple #23
0
char*
ldap_lookup(config_t agent_config, const char *username, char *external_uid)
{
	LDAP		*ld;
	LDAPMessage	*result = (LDAPMessage *) 0;
	LDAPMessage	*e;
	BerElement	*ber;
	char		*a, *dn;
	char		*sane_username = malloc(strlen(username)*2);
	char		*p = sane_username;
	char		**vals = NULL;
	struct		timeval	ldaptimeout = {.tv_sec = BIND_TIMEOUT, .tv_usec = 0};
	int			i, rc=0, num_entries=0;
	char		*transcoded_query = NULL;
	char		*ldap_uri = NULL;
	char		*end_ptr;
	char		*ldap_host = _ds_read_attribute(agent_config, "ExtLookupServer");
	char		*port = _ds_read_attribute(agent_config, "ExtLookupPort");
	long		lldap_port;
	int			ldap_port = 389;
	char		*ldap_binddn = _ds_read_attribute(agent_config, "ExtLookupLogin");
	char		*ldap_passwd = _ds_read_attribute(agent_config, "ExtLookupPassword");
	char		*ldap_base = _ds_read_attribute(agent_config, "ExtLookupDB");
	char		*ldap_attrs[] = {_ds_read_attribute(agent_config, "ExtLookupLDAPAttribute"),0};
	char		*version = _ds_read_attribute(agent_config, "ExtLookupLDAPVersion");
	long		lldap_version;
	int			ldap_version = 3;
	char		*ldap_filter = _ds_read_attribute(agent_config, "ExtLookupQuery");
	int			ldap_scope;

	if (port != NULL) {
		errno=0;
		lldap_port = strtol(port, &end_ptr, 0);
		if ( (errno != 0) || (lldap_port < INT_MIN) || (lldap_port > INT_MAX) || (*end_ptr != '\0')) {
			LOG(LOG_ERR, "External Lookup: bad LDAP port number");
			return NULL;
		} else
			ldap_port = (int)lldap_port;
	}

	/* set ldap protocol version */
	if (version != NULL) {
		errno=0;
		lldap_version = strtol(version, &end_ptr, 0);
		if ((errno != 0) || (lldap_version < 1) || (lldap_version > 3) || (*end_ptr != '\0')) {
			LOG(LOG_ERR, "External Lookup: bad LDAP protocol version");
			return NULL;
		} else
			ldap_version = (int)lldap_version;
	}
		
	if (_ds_match_attribute(agent_config, "ExtLookupLDAPScope", "one"))
		ldap_scope = LDAP_SCOPE_ONELEVEL;
	else /* defaults to sub */
		ldap_scope = LDAP_SCOPE_SUBTREE;

	/* set alarm handler */
	signal(SIGALRM, sig_alrm);

	/* sanitize username for filter integration */
	for (; *username != '\0'; username++) {
		switch(*username) {
			case 0x2a: /* '*' */
			case 0x28: /* '(' */
			case 0x29: /* ')' */
			case 0x5c: /* '\' */
			case 0x00: /* NUL */
				*p++ = 0x5c; /* '\' */
				*p++ = *username;
				break;

			default:
				*p++ = *username;
				break;
		}
	}

	*p = '\0';

	LOGDEBUG("External Lookup: sanitized username is %s\n", sane_username);

	/* build proper LDAP filter*/
	transcoded_query = strdup(transcode_query(ldap_filter, sane_username, transcoded_query));
	free(sane_username);
	if (transcoded_query == NULL) {
		LOG(LOG_ERR, "External Lookup: %s", ERR_EXT_LOOKUP_MISCONFIGURED); 
		return NULL;
	}

	if( ldap_host != NULL || ldap_port ) {
	/* construct URL */
		LDAPURLDesc url;
		memset( &url, 0, sizeof(url));

		url.lud_scheme = "ldap";
		url.lud_host = ldap_host;
		url.lud_port = ldap_port;
		url.lud_scope = LDAP_SCOPE_SUBTREE;

		ldap_uri = ldap_url_desc2str( &url );
	}

	rc = ldap_initialize( &ld, ldap_uri );
	if( rc != LDAP_SUCCESS ) {
		LOG(LOG_ERR, "External Lookup: Could not create LDAP session handle for URI=%s (%d): %s\n", ldap_uri, rc, ldap_err2string(rc));
		return NULL;
	}

	if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &ldap_version ) != LDAP_OPT_SUCCESS ) {
		LOG(LOG_ERR, "External Lookup: Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", ldap_version );
		return NULL;
	}

	/* use TLS if configured */
	if ( _ds_match_attribute(agent_config, "ExtLookupCrypto", "tls" )) {
		if (ldap_version != 3) {
			LOG(LOG_ERR, "External Lookup: TLS only supported with LDAP protocol version 3");
			return NULL;
		}
		if ( ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
			LOG(LOG_ERR, "External Lookup: %s: %s (%d)", ERR_EXT_LOOKUP_INIT_FAIL, strerror(errno), errno);
			return NULL;
		}
	}

	/* schedules alarm */
	alarm(BIND_TIMEOUT);
	
	/* authenticate to the directory */
	if ( (rc = ldap_simple_bind_s( ld, ldap_binddn, ldap_passwd )) != LDAP_SUCCESS ) {
		/* cancel alarms */
		alarm(0);
		
		LOG(LOG_ERR, "External Lookup: %s: %s", ERR_EXT_LOOKUP_INIT_FAIL, ldap_err2string(rc) );
		ldap_unbind(ld);
		return NULL;
	}
	/* cancel alarms */
	alarm(0);
	
	/* search for all entries matching the filter */

	if ( (rc = ldap_search_st( ld, 
				   ldap_base, 
				   ldap_scope,
				   transcoded_query,
				   ldap_attrs, 
				   0,
				   &ldaptimeout, 
				   &result )) != LDAP_SUCCESS ) {

	free(transcoded_query);

	switch(rc) {
		case LDAP_TIMEOUT:
		case LDAP_BUSY:
		case LDAP_UNAVAILABLE:
		case LDAP_UNWILLING_TO_PERFORM:
		case LDAP_SERVER_DOWN:
		case LDAP_TIMELIMIT_EXCEEDED:
			LOG(LOG_ERR, "External Lookup: %s: %s", ERR_EXT_LOOKUP_SEARCH_FAIL, ldap_err2string(ldap_result2error(ld, result, 1)) );
			ldap_unbind( ld );
			return NULL;
			break;
		case LDAP_FILTER_ERROR:
			LOG(LOG_ERR, "External Lookup: %s: %s", ERR_EXT_LOOKUP_SEARCH_FAIL, ldap_err2string(ldap_result2error(ld, result, 1)) );
			ldap_unbind( ld );
			return NULL;
			break;
		case LDAP_SIZELIMIT_EXCEEDED:
			if ( result == NULL ) {
				LOG(LOG_ERR, "External Lookup: %s: %s", ERR_EXT_LOOKUP_SEARCH_FAIL, ldap_err2string(ldap_result2error(ld, result, 1)) );
				ldap_unbind( ld );
				return NULL;
			}
			break;
		default:		       
			LOG(LOG_ERR, "External Lookup: %s: code=%d, %s", ERR_EXT_LOOKUP_SEARCH_FAIL, rc, ldap_err2string(ldap_result2error(ld, result, 1)) );
			ldap_unbind( ld );
			return NULL;
		}
	}

	num_entries=ldap_count_entries(ld,result);

	LOGDEBUG("External Lookup: found %d LDAP entries", num_entries);

    switch (num_entries) {
				case 1: /* only one entry, let's proceed */
					break;
					
				case -1: /* an error occured */
				    LOG(LOG_ERR, "External Lookup: %s: %s", ERR_EXT_LOOKUP_SEARCH_FAIL, ldap_err2string(ldap_result2error(ld, result, 1)));
					ldap_unbind( ld );
					return NULL ;
					
				case 0: /* no entries found */
					LOGDEBUG("External Lookup: %s: no entries found.", ERR_EXT_LOOKUP_SEARCH_FAIL);
					ldap_msgfree( result );
					ldap_unbind( ld );
					return NULL ;

				default: /* more than one entry returned */
					LOG(LOG_ERR, "External Lookup: %s: more than one entry returned.", ERR_EXT_LOOKUP_SEARCH_FAIL);
					ldap_msgfree( result );
					ldap_unbind( ld );
			    	return NULL;
	}

	/* for each entry print out name + all attrs and values */
	for ( e = ldap_first_entry( ld, result ); e != NULL;
	    e = ldap_next_entry( ld, e ) ) {
		if ( (dn = ldap_get_dn( ld, e )) != NULL ) {
		    ldap_memfree( dn );
		}
		for ( a = ldap_first_attribute( ld, e, &ber );
		    a != NULL; a = ldap_next_attribute( ld, e, ber ) ) {
			if ((vals = ldap_get_values( ld, e, a)) != NULL ) {
				for ( i = 0; vals[i] != NULL; i++ ) {
					external_uid = strdup(vals[i]);
				}
				ldap_value_free( vals );
			}
			ldap_memfree( a );
		}
		if ( ber != NULL ) {
			ber_free( ber, 0 );
		}
	}
	ldap_msgfree( result );
	ldap_unbind( ld );
	return external_uid;
}
#endif

char*
program_lookup(config_t agent_config, const char *username, char *external_uid)
{
	pid_t wstatus, pid;
	int i, status;
	int fd[2];
	char *output = malloc (1024);
	char **args = malloc (1024);
	char *token;
	char *saveptr;
	char *str;
	char *command_line = 0;
	
    /* build proper command line*/
	command_line = strdup(transcode_query(_ds_read_attribute(agent_config, "ExtLookupServer"), username, command_line));

	if (command_line == NULL) {
		LOG(LOG_ERR, ERR_EXT_LOOKUP_MISCONFIGURED);
		free(output);
		free(args);
		return NULL;
	}

	LOGDEBUG("command line is %s", command_line);
	
	/* break the command line into arguments */
	for (i = 0, str = command_line; ; i++, str = NULL) {
		token = strtok_r(str, " ", &saveptr);
		if (token == NULL)
			break;
		args[i] = token;
		LOGDEBUG("args[%d] = %s",i,token);
	}
	args[i] = (char *) 0;

	if (pipe(fd) == -1) {
		LOG(LOG_ERR, "%s: errno=%i (%s)", ERR_EXT_LOOKUP_INIT_FAIL, errno, strerror(errno));
		free(output);
		free(args);
		return NULL;
	}

	switch(pid=fork()) {

		case -1: /* couldn't fork - something went wrong */
			LOG(LOG_ERR, "%s: errno=%i (%s)", ERR_EXT_LOOKUP_INIT_FAIL, errno, strerror(errno));
			free(output);
			free(args);
			return NULL;

		case 0: /* execute the command and write to fd */
			close(fd[0]);
			dup2(fd[1], fileno(stdout));
			execve(args[0], args, 0);
			exit(EXIT_FAILURE);
			
		default: /* read from fd the first output line */
			do {
				wstatus = waitpid( pid, &status, WUNTRACED | WCONTINUED);
				if (wstatus == -1) {
					LOGDEBUG("waitpid() exited with an error: %s: errno=%i", strerror(errno), errno);
					free(output);
					free(args);
					return NULL;
				}
				if (WIFEXITED(status)) {
					LOGDEBUG("exited, status=%d\n", WEXITSTATUS(status));
					if (WEXITSTATUS(status)) {
						LOGDEBUG("Error running %s. Check path and permissions.\n", args[0]);
					}
				} else if (WIFSIGNALED(status)) {
					LOGDEBUG("killed by signal %d\n", WTERMSIG(status));
				} else if (WIFSTOPPED(status)) {
					LOGDEBUG("stopped by signal %d\n", WSTOPSIG(status));
				} else if (WIFCONTINUED(status)) {
					LOGDEBUG("continued\n");
				}
			} while (!WIFEXITED(status) && !WIFSIGNALED(status));
			close(fd[1]);
			/* just in case there's no line break at the end of the return... */
			memset(output, 0, 1024);
			if (read(fd[0], output, 1024) == -1) {
				LOG(LOG_ERR, "%s: errno=%i (%s)", ERR_EXT_LOOKUP_INIT_FAIL, errno, strerror(errno));
				free(output);
				free(args);
				return NULL;
			}
			close(fd[0]);
	}

	if (strlen(output) == 0) {
		free(output);
		free(args);
		return NULL;
	}
	
	/* terminate the output string at the first \n */
	token = strchr(output, '\n');
	if (token != NULL)
		*token = '\0';
	
	external_uid = strdup(output);
	free(output);
	free(command_line);
	free(args);
	return external_uid;
}
Exemple #24
0
/*
 * Read and process the bluegene.conf configuration file so to interpret what
 * blocks are static/dynamic, torus/mesh, etc.
 */
extern int read_bg_conf(void)
{
	int i;
	bool tmp_bool = 0;
	int count = 0;
	s_p_hashtbl_t *tbl = NULL;
	char *tmp_char = NULL;
	select_ba_request_t **blockreq_array = NULL;
	image_t **image_array = NULL;
	image_t *image = NULL;
	static time_t last_config_update = (time_t) 0;
	struct stat config_stat;
	ListIterator itr = NULL;
	char* bg_conf_file = NULL;
	static int *dims = NULL;

	if (!dims)
		dims = select_g_ba_get_dims();

	if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
		info("Reading the bluegene.conf file");

	/* check if config file has changed */
	bg_conf_file = get_extra_conf_path("bluegene.conf");

	if (stat(bg_conf_file, &config_stat) < 0)
		fatal("can't stat bluegene.conf file %s: %m", bg_conf_file);
	if (last_config_update) {
		_reopen_bridge_log();
		if (last_config_update == config_stat.st_mtime) {
			if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
				info("%s unchanged", bg_conf_file);
		} else {
			info("Restart slurmctld for %s changes "
			     "to take effect",
			     bg_conf_file);
		}
		last_config_update = config_stat.st_mtime;
		xfree(bg_conf_file);
		return SLURM_SUCCESS;
	}
	last_config_update = config_stat.st_mtime;

	/* initialization */
	/* bg_conf defined in bg_node_alloc.h */
	if (!(tbl = config_make_tbl(bg_conf_file)))
		fatal("something wrong with opening/reading bluegene "
		      "conf file");
	xfree(bg_conf_file);

#ifdef HAVE_BGL
	if (s_p_get_array((void ***)&image_array,
			  &count, "AltBlrtsImage", tbl)) {
		for (i = 0; i < count; i++) {
			list_append(bg_conf->blrts_list, image_array[i]);
			image_array[i] = NULL;
		}
	}
	if (!s_p_get_string(&bg_conf->default_blrtsimage, "BlrtsImage", tbl)) {
		if (!list_count(bg_conf->blrts_list))
			fatal("BlrtsImage not configured "
			      "in bluegene.conf");
		itr = list_iterator_create(bg_conf->blrts_list);
		image = list_next(itr);
		image->def = true;
		list_iterator_destroy(itr);
		bg_conf->default_blrtsimage = xstrdup(image->name);
		info("Warning: using %s as the default BlrtsImage.  "
		     "If this isn't correct please set BlrtsImage",
		     bg_conf->default_blrtsimage);
	} else {
		if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
			info("default BlrtsImage %s",
			     bg_conf->default_blrtsimage);
		image = xmalloc(sizeof(image_t));
		image->name = xstrdup(bg_conf->default_blrtsimage);
		image->def = true;
		image->groups = NULL;
		/* we want it to be first */
		list_push(bg_conf->blrts_list, image);
	}

	if (s_p_get_array((void ***)&image_array,
			  &count, "AltLinuxImage", tbl)) {
		for (i = 0; i < count; i++) {
			list_append(bg_conf->linux_list, image_array[i]);
			image_array[i] = NULL;
		}
	}
	if (!s_p_get_string(&bg_conf->default_linuximage, "LinuxImage", tbl)) {
		if (!list_count(bg_conf->linux_list))
			fatal("LinuxImage not configured "
			      "in bluegene.conf");
		itr = list_iterator_create(bg_conf->linux_list);
		image = list_next(itr);
		image->def = true;
		list_iterator_destroy(itr);
		bg_conf->default_linuximage = xstrdup(image->name);
		info("Warning: using %s as the default LinuxImage.  "
		     "If this isn't correct please set LinuxImage",
		     bg_conf->default_linuximage);
	} else {
		if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
			info("default LinuxImage %s",
			     bg_conf->default_linuximage);
		image = xmalloc(sizeof(image_t));
		image->name = xstrdup(bg_conf->default_linuximage);
		image->def = true;
		image->groups = NULL;
		/* we want it to be first */
		list_push(bg_conf->linux_list, image);
	}

	if (s_p_get_array((void ***)&image_array,
			  &count, "AltRamDiskImage", tbl)) {
		for (i = 0; i < count; i++) {
			list_append(bg_conf->ramdisk_list, image_array[i]);
			image_array[i] = NULL;
		}
	}
	if (!s_p_get_string(&bg_conf->default_ramdiskimage,
			    "RamDiskImage", tbl)) {
		if (!list_count(bg_conf->ramdisk_list))
			fatal("RamDiskImage not configured "
			      "in bluegene.conf");
		itr = list_iterator_create(bg_conf->ramdisk_list);
		image = list_next(itr);
		image->def = true;
		list_iterator_destroy(itr);
		bg_conf->default_ramdiskimage = xstrdup(image->name);
		info("Warning: using %s as the default RamDiskImage.  "
		     "If this isn't correct please set RamDiskImage",
		     bg_conf->default_ramdiskimage);
	} else {
		if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
			info("default RamDiskImage %s",
			     bg_conf->default_ramdiskimage);
		image = xmalloc(sizeof(image_t));
		image->name = xstrdup(bg_conf->default_ramdiskimage);
		image->def = true;
		image->groups = NULL;
		/* we want it to be first */
		list_push(bg_conf->ramdisk_list, image);
	}
#elif defined HAVE_BGP

	if (s_p_get_array((void ***)&image_array,
			  &count, "AltCnloadImage", tbl)) {
		for (i = 0; i < count; i++) {
			list_append(bg_conf->linux_list, image_array[i]);
			image_array[i] = NULL;
		}
	}
	if (!s_p_get_string(&bg_conf->default_linuximage, "CnloadImage", tbl)) {
		if (!list_count(bg_conf->linux_list))
			fatal("CnloadImage not configured "
			      "in bluegene.conf");
		itr = list_iterator_create(bg_conf->linux_list);
		image = list_next(itr);
		image->def = true;
		list_iterator_destroy(itr);
		bg_conf->default_linuximage = xstrdup(image->name);
		info("Warning: using %s as the default CnloadImage.  "
		     "If this isn't correct please set CnloadImage",
		     bg_conf->default_linuximage);
	} else {
		if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
			info("default CnloadImage %s",
			     bg_conf->default_linuximage);
		image = xmalloc(sizeof(image_t));
		image->name = xstrdup(bg_conf->default_linuximage);
		image->def = true;
		image->groups = NULL;
		/* we want it to be first */
		list_push(bg_conf->linux_list, image);
	}

	if (s_p_get_array((void ***)&image_array,
			  &count, "AltIoloadImage", tbl)) {
		for (i = 0; i < count; i++) {
			list_append(bg_conf->ramdisk_list, image_array[i]);
			image_array[i] = NULL;
		}
	}
	if (!s_p_get_string(&bg_conf->default_ramdiskimage,
			    "IoloadImage", tbl)) {
		if (!list_count(bg_conf->ramdisk_list))
			fatal("IoloadImage not configured "
			      "in bluegene.conf");
		itr = list_iterator_create(bg_conf->ramdisk_list);
		image = list_next(itr);
		image->def = true;
		list_iterator_destroy(itr);
		bg_conf->default_ramdiskimage = xstrdup(image->name);
		info("Warning: using %s as the default IoloadImage.  "
		     "If this isn't correct please set IoloadImage",
		     bg_conf->default_ramdiskimage);
	} else {
		if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
			info("default IoloadImage %s",
			     bg_conf->default_ramdiskimage);
		image = xmalloc(sizeof(image_t));
		image->name = xstrdup(bg_conf->default_ramdiskimage);
		image->def = true;
		image->groups = NULL;
		/* we want it to be first */
		list_push(bg_conf->ramdisk_list, image);
	}

#endif
	if (s_p_get_array((void ***)&image_array,
			  &count, "AltMloaderImage", tbl)) {
		for (i = 0; i < count; i++) {
			list_append(bg_conf->mloader_list, image_array[i]);
			image_array[i] = NULL;
		}
	}
	if (!s_p_get_string(&bg_conf->default_mloaderimage,
			    "MloaderImage", tbl)) {
		if (!list_count(bg_conf->mloader_list))
			fatal("MloaderImage not configured "
			      "in bluegene.conf");
		itr = list_iterator_create(bg_conf->mloader_list);
		image = list_next(itr);
		image->def = true;
		list_iterator_destroy(itr);
		bg_conf->default_mloaderimage = xstrdup(image->name);
		info("Warning: using %s as the default MloaderImage.  "
		     "If this isn't correct please set MloaderImage",
		     bg_conf->default_mloaderimage);
	} else {
		if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
			info("default MloaderImage %s",
			     bg_conf->default_mloaderimage);
		image = xmalloc(sizeof(image_t));
		image->name = xstrdup(bg_conf->default_mloaderimage);
		image->def = true;
		image->groups = NULL;
		/* we want it to be first */
		list_push(bg_conf->mloader_list, image);
	}

	if (!s_p_get_uint16(&bg_conf->mp_cnode_cnt, "MidplaneNodeCnt", tbl)) {
		if (!s_p_get_uint16(&bg_conf->mp_cnode_cnt,
				    "BasePartitionNodeCnt", tbl)) {
			error("MidplaneNodeCnt not configured in bluegene.conf "
			      "defaulting to 512 as MidplaneNodeCnt");
			bg_conf->mp_cnode_cnt = 512;
		}
	}

	if (bg_conf->mp_cnode_cnt <= 0)
		fatal("You should have more than 0 nodes "
		      "per base partition");
	bg_conf->actual_cnodes_per_mp = bg_conf->mp_cnode_cnt;
	bg_conf->quarter_cnode_cnt = bg_conf->mp_cnode_cnt/4;

	/* bg_conf->cpus_per_mp should had already been set from the
	 * node_init */
	if (bg_conf->cpus_per_mp < bg_conf->mp_cnode_cnt) {
		fatal("For some reason we have only %u cpus per mp, but "
		      "have %u cnodes per mp.  You need at least the same "
		      "number of cpus as you have cnodes per mp.  "
		      "Check the NodeName CPUs= "
		      "definition in the slurm.conf.",
		      bg_conf->cpus_per_mp, bg_conf->mp_cnode_cnt);
	}

	bg_conf->cpu_ratio = bg_conf->cpus_per_mp/bg_conf->mp_cnode_cnt;
	if (!bg_conf->cpu_ratio)
		fatal("We appear to have less than 1 cpu on a cnode.  "
		      "You specified %u for BasePartitionNodeCnt "
		      "in the blugene.conf and %u cpus "
		      "for each node in the slurm.conf",
		      bg_conf->mp_cnode_cnt, bg_conf->cpus_per_mp);

	num_unused_cpus = 1;
	for (i = 0; i<SYSTEM_DIMENSIONS; i++)
		num_unused_cpus *= dims[i];
	num_unused_cpus *= bg_conf->cpus_per_mp;
	num_possible_unused_cpus = num_unused_cpus;

	if (!s_p_get_uint16(&bg_conf->nodecard_cnode_cnt,
			    "NodeBoardNodeCnt", tbl)) {
		if (!s_p_get_uint16(&bg_conf->nodecard_cnode_cnt,
				    "NodeCardNodeCnt", tbl)) {
			error("NodeCardNodeCnt not configured in bluegene.conf "
			      "defaulting to 32 as NodeCardNodeCnt");
			bg_conf->nodecard_cnode_cnt = 32;
		}
	}

	if (bg_conf->nodecard_cnode_cnt <= 0)
		fatal("You should have more than 0 nodes per nodecard");

	bg_conf->mp_nodecard_cnt =
		bg_conf->mp_cnode_cnt / bg_conf->nodecard_cnode_cnt;

	if (!s_p_get_uint16(&bg_conf->ionodes_per_mp, "IONodesPerMP", tbl))
		if (!s_p_get_uint16(&bg_conf->ionodes_per_mp, "Numpsets", tbl))
			fatal("Warning: IONodesPerMP not configured "
			      "in bluegene.conf");

	s_p_get_uint16(&bg_conf->max_block_err, "MaxBlockInError", tbl);

	tmp_bool = 0;
	s_p_get_boolean(&tmp_bool, "SubMidplaneSystem", tbl);
	bg_conf->sub_mp_sys = tmp_bool;

#ifdef HAVE_BGQ
	tmp_bool = 0;
	s_p_get_boolean(&tmp_bool, "AllowSubBlockAllocations", tbl);
	bg_conf->sub_blocks = tmp_bool;

	/* You can only have 16 ionodes per midplane */
	if (bg_conf->ionodes_per_mp > bg_conf->mp_nodecard_cnt)
		bg_conf->ionodes_per_mp = bg_conf->mp_nodecard_cnt;
#endif

	for (i=0; i<SYSTEM_DIMENSIONS; i++)
		bg_conf->default_conn_type[i] = (uint16_t)NO_VAL;
	s_p_get_string(&tmp_char, "DefaultConnType", tbl);
	if (tmp_char) {
		verify_conn_type(tmp_char, bg_conf->default_conn_type);
		if ((bg_conf->default_conn_type[0] != SELECT_MESH)
		    && (bg_conf->default_conn_type[0] != SELECT_TORUS))
			fatal("Can't have a DefaultConnType of %s "
			      "(only Mesh or Torus values are valid).",
			      tmp_char);
		xfree(tmp_char);
	} else
		bg_conf->default_conn_type[0] = SELECT_TORUS;

#ifndef HAVE_BG_L_P
	int first_conn_type = bg_conf->default_conn_type[0];
	for (i=1; i<SYSTEM_DIMENSIONS; i++) {
		if (bg_conf->default_conn_type[i] == (uint16_t)NO_VAL)
			bg_conf->default_conn_type[i] = first_conn_type;
		else if (bg_conf->default_conn_type[i] >= SELECT_SMALL)
			fatal("Can't have a DefaultConnType of %s "
			      "(only Mesh or Torus values are valid).",
			      tmp_char);
	}
#endif

	if (bg_conf->ionodes_per_mp) {
		bitstr_t *tmp_bitmap = NULL;
		int small_size = 1;

		/* THIS IS A HACK TO MAKE A 1 NODECARD SYSTEM WORK,
		 * Sometime on a Q system the nodecard isn't in the 0
		 * spot so only do this if you know it is in that
		 * spot.  Otherwise say the whole midplane is there
		 * and just make blocks over the whole thing.  They
		 * you can error out the blocks that aren't usable. */
		if (bg_conf->sub_mp_sys
		    && bg_conf->mp_cnode_cnt == bg_conf->nodecard_cnode_cnt) {
#ifdef HAVE_BGQ
			bg_conf->quarter_ionode_cnt = 1;
			bg_conf->nodecard_ionode_cnt = 1;
#else
			bg_conf->quarter_ionode_cnt = 2;
			bg_conf->nodecard_ionode_cnt = 2;
#endif
		} else {
			bg_conf->quarter_ionode_cnt = bg_conf->ionodes_per_mp/4;
			bg_conf->nodecard_ionode_cnt =
				bg_conf->quarter_ionode_cnt/4;
		}

		/* How many nodecards per ionode */
		bg_conf->nc_ratio =
			((double)bg_conf->mp_cnode_cnt
			 / (double)bg_conf->nodecard_cnode_cnt)
			/ (double)bg_conf->ionodes_per_mp;
		/* How many ionodes per nodecard */
		bg_conf->io_ratio =
			(double)bg_conf->ionodes_per_mp /
			((double)bg_conf->mp_cnode_cnt
			 / (double)bg_conf->nodecard_cnode_cnt);

		/* How many cnodes per ionode */
		bg_conf->ionode_cnode_cnt =
			bg_conf->nodecard_cnode_cnt * bg_conf->nc_ratio;

		//info("got %f %f", bg_conf->nc_ratio, bg_conf->io_ratio);
		/* figure out the smallest block we can have on the
		   system */
#ifdef HAVE_BGL
		if (bg_conf->io_ratio >= 1)
			bg_conf->smallest_block=32;
		else
			bg_conf->smallest_block=128;
#else

		if (bg_conf->io_ratio >= 2)
			bg_conf->smallest_block=16;
		else if (bg_conf->io_ratio == 1)
			bg_conf->smallest_block=32;
		else if (bg_conf->io_ratio == .5)
			bg_conf->smallest_block=64;
		else if (bg_conf->io_ratio == .25)
			bg_conf->smallest_block=128;
		else if (bg_conf->io_ratio == .125)
			bg_conf->smallest_block=256;
		else {
			error("unknown ioratio %f.  Can't figure out "
			      "smallest block size, setting it to midplane",
			      bg_conf->io_ratio);
			bg_conf->smallest_block = 512;
		}
#endif
		if (bg_conf->slurm_debug_flags & DEBUG_FLAG_SELECT_TYPE)
			info("Smallest block possible on this system is %u",
			     bg_conf->smallest_block);
		/* below we are creating all the possible bitmaps for
		 * each size of small block
		 */
		if ((int)bg_conf->nodecard_ionode_cnt < 1) {
			bg_conf->nodecard_ionode_cnt = 0;
		} else {
			bg_lists->valid_small32 = list_create(_destroy_bitmap);
			/* This is suppose to be = and not ==, we only
			   want to decrement when small_size equals
			   something.
			*/
			if ((small_size = bg_conf->nodecard_ionode_cnt))
				small_size--;
			i = 0;
			while (i<bg_conf->ionodes_per_mp) {
				tmp_bitmap = bit_alloc(bg_conf->ionodes_per_mp);
				bit_nset(tmp_bitmap, i, i+small_size);
				i += small_size+1;
				list_append(bg_lists->valid_small32,
					    tmp_bitmap);
			}
		}
		/* If we only have 1 nodecard just jump to the end
		   since this will never need to happen below.
		   Pretty much a hack to avoid seg fault;). */
		if (bg_conf->mp_cnode_cnt == bg_conf->nodecard_cnode_cnt)
			goto no_calc;

		bg_lists->valid_small128 = list_create(_destroy_bitmap);
		if ((small_size = bg_conf->quarter_ionode_cnt))
			small_size--;
		i = 0;
		while (i<bg_conf->ionodes_per_mp) {
			tmp_bitmap = bit_alloc(bg_conf->ionodes_per_mp);
			bit_nset(tmp_bitmap, i, i+small_size);
			i += small_size+1;
			list_append(bg_lists->valid_small128, tmp_bitmap);
		}

#ifndef HAVE_BGL
		bg_lists->valid_small64 = list_create(_destroy_bitmap);
		if ((small_size = bg_conf->nodecard_ionode_cnt * 2))
			small_size--;
		i = 0;
		while (i<bg_conf->ionodes_per_mp) {
			tmp_bitmap = bit_alloc(bg_conf->ionodes_per_mp);
			bit_nset(tmp_bitmap, i, i+small_size);
			i += small_size+1;
			list_append(bg_lists->valid_small64, tmp_bitmap);
		}

		bg_lists->valid_small256 = list_create(_destroy_bitmap);
		if ((small_size = bg_conf->quarter_ionode_cnt * 2))
			small_size--;
		i = 0;
		while (i<bg_conf->ionodes_per_mp) {
			tmp_bitmap = bit_alloc(bg_conf->ionodes_per_mp);
			bit_nset(tmp_bitmap, i, i+small_size);
			i += small_size+1;
			list_append(bg_lists->valid_small256, tmp_bitmap);
		}
#endif
	} else {
		fatal("your ionodes_per_mp is 0");
	}

no_calc:

	if (!s_p_get_uint16(&bg_conf->bridge_api_verb, "BridgeAPIVerbose", tbl))
		info("Warning: BridgeAPIVerbose not configured "
		     "in bluegene.conf");
	if (!s_p_get_string(&bg_conf->bridge_api_file,
			    "BridgeAPILogFile", tbl))
		info("BridgeAPILogFile not configured in bluegene.conf");
	else
		_reopen_bridge_log();

	if (s_p_get_string(&tmp_char, "DenyPassthrough", tbl)) {
		if (strstr(tmp_char, "A"))
			ba_deny_pass |= PASS_DENY_A;
		if (strstr(tmp_char, "X"))
			ba_deny_pass |= PASS_DENY_X;
		if (strstr(tmp_char, "Y"))
			ba_deny_pass |= PASS_DENY_Y;
		if (strstr(tmp_char, "Z"))
			ba_deny_pass |= PASS_DENY_Z;
		if (!strcasecmp(tmp_char, "ALL"))
			ba_deny_pass |= PASS_DENY_ALL;
		bg_conf->deny_pass = ba_deny_pass;
		xfree(tmp_char);
	}

	if (!s_p_get_string(&tmp_char, "LayoutMode", tbl)) {
		info("Warning: LayoutMode was not specified in bluegene.conf "
		     "defaulting to STATIC partitioning");
		bg_conf->layout_mode = LAYOUT_STATIC;
	} else {
		if (!strcasecmp(tmp_char,"STATIC"))
			bg_conf->layout_mode = LAYOUT_STATIC;
		else if (!strcasecmp(tmp_char,"OVERLAP"))
			bg_conf->layout_mode = LAYOUT_OVERLAP;
		else if (!strcasecmp(tmp_char,"DYNAMIC"))
			bg_conf->layout_mode = LAYOUT_DYNAMIC;
		else {
			fatal("I don't understand this LayoutMode = %s",
			      tmp_char);
		}
		xfree(tmp_char);
	}

	/* add blocks defined in file */
	if (bg_conf->layout_mode != LAYOUT_DYNAMIC) {
		if (!s_p_get_array((void ***)&blockreq_array,
				   &count, "MPs", tbl)) {
			if (!s_p_get_array((void ***)&blockreq_array,
					   &count, "BPs", tbl)) {
				info("WARNING: no blocks defined in "
				     "bluegene.conf, "
				     "only making full system block");
				/* create_full_system_block(NULL); */
				if (bg_conf->sub_mp_sys ||
				    (bg_conf->mp_cnode_cnt ==
				     bg_conf->nodecard_cnode_cnt))
					fatal("On a sub-midplane system you "
					      "need to define the blocks you "
					      "want on your system.");
			}
		}

		for (i = 0; i < count; i++) {
			add_bg_record(bg_lists->main, NULL,
				      blockreq_array[i], 0, 0);
		}
	} else if (bg_conf->sub_mp_sys ||
		   (bg_conf->mp_cnode_cnt == bg_conf->nodecard_cnode_cnt))
		/* we can't do dynamic here on a sub-midplane system */
		fatal("On a sub-midplane system we can only do OVERLAP or "
		      "STATIC LayoutMode.  Please update your bluegene.conf.");

#ifdef HAVE_BGQ
	if (s_p_get_string(&tmp_char, "RebootQOSList", tbl)) {
		bool valid;
		char *token, *last = NULL;
		slurmdb_qos_rec_t *qos = NULL;

		bg_conf->reboot_qos_bitmap = bit_alloc(g_qos_count);
		itr = list_iterator_create(assoc_mgr_qos_list);

		token = strtok_r(tmp_char, ",", &last);
		while (token) {
			valid = false;
			while((qos = list_next(itr))) {
				if (!strcasecmp(token, qos->name)) {
					bit_set(bg_conf->reboot_qos_bitmap,
						qos->id);
					valid = true;
					break;
				}
			}
			if (!valid)
				error("Invalid RebootQOSList value: %s", token);
			list_iterator_reset(itr);
			token = strtok_r(NULL, ",", &last);
		}
		list_iterator_destroy(itr);
		xfree(tmp_char);
	}
#endif

	s_p_hashtbl_destroy(tbl);

	return SLURM_SUCCESS;
}
Exemple #25
0
/* options__process
 * A snippet from main() to get all the options sent via CLI, then verifies them.
 */
void options__process(int argc, char **argv) {
  /* Reset everything since there isn't an initialization function for Options structs. */
  /* Page Information */
  opts.page_directory = (char *)malloc(strlen("sample_data") + 1); strcpy(opts.page_directory, "sample_data");
  opts.page_count = 0;
  opts.page_limit = MAX_PAGE_LIMIT;
  opts.smallest_page = UINT16_MAX;
  opts.biggest_page = 0;
  opts.dataset_size = 0;
  opts.dataset_max = MAX_DATASET_MAX;
  /* Resource Control */
  opts.max_memory = 10 * 1024 * 1024;
  opts.fixed_ratio = -1;
  opts.workers = sysconf(_SC_NPROCESSORS_ONLN) > 0 ? (uint16_t)sysconf(_SC_NPROCESSORS_ONLN) : 1;
  opts.cpu_count = sysconf(_SC_NPROCESSORS_ONLN) > 0 ? (uint16_t)sysconf(_SC_NPROCESSORS_ONLN) : 1;
  /* Tyche Management */
  opts.duration = 5;
  opts.compressor_id = LZ4_COMPRESSOR_ID;
  opts.compressor_level = 1;
  opts.min_pages_retrieved = 5;
  opts.max_pages_retrieved = 5;
  opts.bias_percent = 1.0;
  opts.bias_aggregate = 1.0;
  opts.update_frequency = 0.0;
  opts.delete_frequency = 0.0;
  /* Run Test? */
  opts.test = NULL;
  opts.extended_test_options = NULL;
  /* Niceness Features */
  opts.quiet = 0;
  opts.verbosity = 0;

  /* Process everything passed from CLI now. */
  char *save_ptr = NULL;
  char *token = NULL;
  int c = 0;
  opterr = 0;
  while ((c = getopt(argc, argv, "b:B:c:Cd:D:f:hm:M:n:p:qt:U:w:X:v")) != -1) {
    switch (c) {
      case 'b':
        opts.dataset_max = (uint64_t)atoll(optarg);
        break;
      case 'B':
        token = strtok_r(optarg, ",", &save_ptr);
        if(token != NULL)
          opts.bias_percent = 1.0 * atof(token) / 100;
        token = strtok_r(NULL, ",", &save_ptr);
        if (token != NULL)
          opts.bias_aggregate = 1.0 * atof(token) / 100;
        break;
      case 'c':
        if(strcmp(optarg, "lz4") != 0 && strcmp(optarg, "zlib") != 0 && strcmp(optarg, "zstd"))
          show_error(E_BAD_CLI, "You must specify either 'lz4' or 'zlib' for compression (-c), not: %s", optarg);
        if(strcmp(optarg, "lz4") == 0)
          opts.compressor_id = LZ4_COMPRESSOR_ID;
        if(strcmp(optarg, "zlib") == 0)
          opts.compressor_id = ZLIB_COMPRESSOR_ID;
        if(strcmp(optarg, "zstd") == 0)
          opts.compressor_id = ZSTD_COMPRESSOR_ID;
        break;
      case 'C':
        opts.compressor_id = NO_COMPRESSOR_ID;
        break;
      case 'd':
        opts.duration = (uint16_t)atoi(optarg);
        if (atoi(optarg) > MAX_DURATION)
          opts.duration = MAX_DURATION;
        break;
      case 'D':
        opts.delete_frequency = 1.0 * atof(optarg) / 100;
        break;
      case 'f':
        opts.fixed_ratio = (int8_t)atoi(optarg);
        break;
      case 'h':
        options__show_help();
        exit(E_OK);
        break;
      case 'm':
        opts.max_memory = (uint64_t)atoll(optarg);
        break;
      case 'M':
        token = strtok_r(optarg, ",", &save_ptr);
        if(token != NULL)
          opts.min_pages_retrieved = atoi(token);
        token = strtok_r(NULL, ",", &save_ptr);
        if (token != NULL)
          opts.max_pages_retrieved = atoi(token);
        break;
      case 'n':
        opts.page_limit = (uint32_t)atoll(optarg);
        break;
      case 'p':
        opts.page_directory = optarg;
        break;
      case 'q':
        opts.quiet = 1;
        break;
      case 't':
        if (opts.test != NULL)
          show_error(E_BAD_CLI, "You cannot specify the -t option more than once.");
        opts.test = optarg;
        break;
      case 'U':
        opts.update_frequency = 1.0 * atof(optarg) / 100;
        break;
      case 'w':
        opts.workers = (uint16_t)atoi(optarg);
        if (atoi(optarg) > MAX_WORKERS)
          opts.workers = MAX_WORKERS;
        break;
      case 'X':
        free(opts.extended_test_options);
        opts.extended_test_options = optarg;
        if(strcmp(opts.extended_test_options, "help") == 0) {
          options__show_extended_test_options();
          exit(E_OK);
        }
        break;
      case 'v':
        if(opts.verbosity >= MAX_VERBOSITY)
          show_error(E_BAD_CLI, "Verbosity is already at maximum value: %d", opts.verbosity);
        opts.verbosity++;
        break;
      case '?':
        options__show_help();
        if (optopt == 'b' || optopt == 'B' || optopt == 'c' || optopt == 'd' || optopt == 'D' || optopt == 'f' || optopt == 'm' || optopt == 'M' || optopt == 'n' || optopt == 'p' || optopt == 't' || optopt == 'U' || optopt == 'w' || optopt == 'X')
          show_error(E_BAD_CLI, "Option -%c requires an argument.", optopt);
        if (isprint (optopt))
          show_error(E_BAD_CLI, "Unknown option `-%c'.", optopt);
        show_error(E_BAD_CLI, "Unknown option character `\\x%x'.\n", optopt);
        break;
      default:
        options__show_help();
        exit(E_BAD_CLI);
    }
  }

  /* Pre-flight Checks */
  // -- A page directory is always required.  If it's an invalid path, the io__* functions will catch it.
  if (opts.page_directory == NULL)
    show_error(E_BAD_CLI, "You must specify a directory to search for pages for the test (-p).");
  // -- Memory needs to be at least MIN_MEMORY and less than the installed physical memory.
  const size_t PHYSICAL_MEMORY = (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE);
  if (opts.max_memory < MIN_MEMORY)
    show_error(E_BAD_CLI, "The memory argument you supplied (-m) is too low.  You sent %"PRIu64", but a minimum of %"PRIu64" is required.", opts.max_memory, MIN_MEMORY);
  if (PHYSICAL_MEMORY == 0)
    show_error(E_GENERIC, "Unable to discern the amount of memory this system has.  Can't be sure we have enough memory to do this test.");
  if (opts.max_memory > PHYSICAL_MEMORY)
    show_error(E_BAD_CLI, "The memory argument you supplied (-m) is too high.  You sent %"PRIu64", but your system maximum physical memory is %d.", opts.max_memory, PHYSICAL_MEMORY);
  // -- Fixed ratio should be -1 (not fixed) or 1 to 100.  Zero is either an atoi() error or nonsensical (can't have just a compressed list and 0% raw.
  if (opts.fixed_ratio == 0)
    show_error(E_BAD_CLI, "The fixed ratio (-f) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option; fixed size of 0 would mean 0% for raw buffers which is nonsensical.");
  if (opts.fixed_ratio < -1)
    show_error(E_BAD_CLI, "The fixed ratio (-f) cannot be negative... that's just weird.  Why did you send %"PRIi8"?", opts.fixed_ratio);
  if (opts.fixed_ratio > 100)
    show_error(E_BAD_CLI, "The fixed ratio (-f) cannot be over 100... you can't have more than 100%% of your memory assigned to something.  You sent %"PRIi8".", opts.fixed_ratio);
  // -- Workers must be 1+.  Will be 0 if atoi() fails or user is derp.
  if (opts.workers == 0)
    show_error(E_BAD_CLI, "The worker count (-w) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option.  You need at least 1 worker to, ya know, do work.");
  if (opts.workers == MAX_WORKERS)
    show_error(E_BAD_CLI, "You specified more workers (-w) than allowed (max: %d).", MAX_WORKERS);
  // -- Duration must be non-zero and less than MAX_DURATION.
  if (opts.duration == 0)
    show_error(E_BAD_CLI, "The duration (-d) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option.  The test must run for at least 1 second.");
  if (opts.duration == MAX_DURATION)
    show_error(E_BAD_CLI, "You specified a duration (-d) greater than the max allowed (%d).", MAX_DURATION);
  // -- Dataset max cannot be 0.  Other than that... shrugs.
  if (opts.dataset_max == 0)
    show_error(E_BAD_CLI, "The maximum dataset bytes (-b) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option; it limits the number of bytes the scan functions will find before moving on with the test.");
  // -- Page limit cannot be 0.
  if (opts.page_limit == 0)
    show_error(E_BAD_CLI, "The page limit (-n) is 0.  You either sent invalid input (atoi() failed), or you misunderstood the option; it limits the number of pages the scan functions will find before moving on with the test.");
  // -- When compression is disabled, warn the user!
  if (opts.compressor_id == NO_COMPRESSOR_ID)
    fprintf(stderr, "WARNING!!  Compression is DISABLED (you sent -C).\n");
  // -- If bias isn't between 0 and 100 we're in trouble.
  if (opts.bias_percent < 0 || opts.bias_percent > 100)
    show_error(E_BAD_CLI, "The bias percentage (-B X,Y) must be between 0 and 100 inclusive, not %d.\n", opts.bias_percent);
  if (opts.bias_aggregate < 0 || opts.bias_aggregate > 100)
    show_error(E_BAD_CLI, "The bias aggregate (-B X,Y) must be between 0 and 100 inclusive, not %d.\n", opts.bias_aggregate);
  // -- If the update or delete frequencies aren't between 0 and 100 we're in trouble.
  if (opts.update_frequency < 0 || opts.update_frequency > 100)
    show_error(E_BAD_CLI, "The update frequency (-U) must be between 0 and 100 inclusive, not %d.\n", opts.update_frequency);
  if (opts.delete_frequency < 0 || opts.delete_frequency > 100)
    show_error(E_BAD_CLI, "The delete frequency (-D) must be between 0 and 100 inclusive, not %d.\n", opts.delete_frequency);
  // -- The min pages retrieved in a round can't greater than max...
  if (opts.min_pages_retrieved > opts.max_pages_retrieved)
    show_error(E_BAD_CLI, "You can't set the minimum pages per round (X) higher than the maximum per round (Y) for -M.\n");

  return;
}
Exemple #26
0
CCPUInfo::CCPUInfo(void)
{
#ifdef TARGET_POSIX
  m_fProcStat = m_fProcTemperature = m_fCPUFreq = NULL;
  m_cpuInfoForFreq = false;
#elif defined(TARGET_WINDOWS)
  m_cpuQueryFreq = nullptr;
  m_cpuQueryLoad = nullptr;
#endif
  m_lastUsedPercentage = 0;
  m_cpuFeatures = 0;

#if defined(TARGET_DARWIN)
  size_t len = 4;
  std::string cpuVendor;
  
  // The number of cores.
  if (sysctlbyname("hw.activecpu", &m_cpuCount, &len, NULL, 0) == -1)
      m_cpuCount = 1;

  // The model.
#if defined(__ppc__) || defined (TARGET_DARWIN_IOS)
  const NXArchInfo *info = NXGetLocalArchInfo();
  if (info != NULL)
    m_cpuModel = info->description;
#else
  // NXGetLocalArchInfo is ugly for intel so keep using this method
  char buffer[512];
  len = 512;
  if (sysctlbyname("machdep.cpu.brand_string", &buffer, &len, NULL, 0) == 0)
    m_cpuModel = buffer;

  // The CPU vendor
  len = 512;
  if (sysctlbyname("machdep.cpu.vendor", &buffer, &len, NULL, 0) == 0)
    cpuVendor = buffer;
  
#endif
  // Go through each core.
  for (int i=0; i<m_cpuCount; i++)
  {
    CoreInfo core;
    core.m_id = i;
    core.m_strModel = m_cpuModel;
    core.m_strVendor = cpuVendor;
    m_cores[core.m_id] = core;
  }

#elif defined(TARGET_WINDOWS)
  HKEY hKeyCpuRoot;

  if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor", 0, KEY_READ, &hKeyCpuRoot) == ERROR_SUCCESS)
  {
    DWORD num = 0;
    std::vector<CoreInfo> cpuCores;
    wchar_t subKeyName[200]; // more than enough
    DWORD subKeyNameLen = sizeof(subKeyName) / sizeof(wchar_t);
    while (RegEnumKeyExW(hKeyCpuRoot, num++, subKeyName, &subKeyNameLen, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS)
    {
      HKEY hCpuKey;
      if (RegOpenKeyExW(hKeyCpuRoot, subKeyName, 0, KEY_QUERY_VALUE, &hCpuKey) == ERROR_SUCCESS)
      {
        CoreInfo cpuCore;
        if (swscanf_s(subKeyName, L"%i", &cpuCore.m_id) != 1)
          cpuCore.m_id = num - 1;
        wchar_t buf[300]; // more than enough
        DWORD bufSize = sizeof(buf);
        DWORD valType;
        if (RegQueryValueExW(hCpuKey, L"ProcessorNameString", nullptr, &valType, LPBYTE(buf), &bufSize) == ERROR_SUCCESS &&
            valType == REG_SZ)
        {
          g_charsetConverter.wToUTF8(std::wstring(buf, bufSize / sizeof(wchar_t)), cpuCore.m_strModel);
          cpuCore.m_strModel = cpuCore.m_strModel.substr(0, cpuCore.m_strModel.find(char(0))); // remove extra null terminations
          StringUtils::RemoveDuplicatedSpacesAndTabs(cpuCore.m_strModel);
          StringUtils::Trim(cpuCore.m_strModel);
        }
        bufSize = sizeof(buf);
        if (RegQueryValueExW(hCpuKey, L"VendorIdentifier", nullptr, &valType, LPBYTE(buf), &bufSize) == ERROR_SUCCESS &&
            valType == REG_SZ)
        {
          g_charsetConverter.wToUTF8(std::wstring(buf, bufSize / sizeof(wchar_t)), cpuCore.m_strVendor);
          cpuCore.m_strVendor = cpuCore.m_strVendor.substr(0, cpuCore.m_strVendor.find(char(0))); // remove extra null terminations
        }
        DWORD mhzVal;
        bufSize = sizeof(mhzVal);
        if (RegQueryValueExW(hCpuKey, L"~MHz", nullptr, &valType, LPBYTE(&mhzVal), &bufSize) == ERROR_SUCCESS &&
            valType == REG_DWORD)
          cpuCore.m_fSpeed = double(mhzVal);

        RegCloseKey(hCpuKey);

        if (cpuCore.m_strModel.empty())
          cpuCore.m_strModel = "Unknown";
        cpuCores.push_back(cpuCore);
      }
      subKeyNameLen = sizeof(subKeyName) / sizeof(wchar_t); // restore length value
    }
    RegCloseKey(hKeyCpuRoot);
    std::sort(cpuCores.begin(), cpuCores.end()); // sort cores by id
    for (size_t i = 0; i < cpuCores.size(); i++)
      m_cores[i] = cpuCores[i]; // add in sorted order
  }

  if (!m_cores.empty())
    m_cpuModel = m_cores.begin()->second.m_strModel;
  else
    m_cpuModel = "Unknown";

  SYSTEM_INFO siSysInfo;
  GetNativeSystemInfo(&siSysInfo);
  m_cpuCount = siSysInfo.dwNumberOfProcessors;

  if (PdhOpenQueryW(nullptr, 0, &m_cpuQueryFreq) == ERROR_SUCCESS)
  {
    if (PdhAddEnglishCounterW(m_cpuQueryFreq, L"\\Processor Information(0,0)\\Processor Frequency", 0, &m_cpuFreqCounter) != ERROR_SUCCESS)
      m_cpuFreqCounter = nullptr;
  }
  else
    m_cpuQueryFreq = nullptr;
  
  if (PdhOpenQueryW(nullptr, 0, &m_cpuQueryLoad) == ERROR_SUCCESS)
  {
    for (size_t i = 0; i < m_cores.size(); i++)
    {
      if (PdhAddEnglishCounterW(m_cpuQueryLoad, StringUtils::Format(L"\\Processor(%d)\\%% Idle Time", int(i)).c_str(), 0, &m_cores[i].m_coreCounter) != ERROR_SUCCESS)
        m_cores[i].m_coreCounter = nullptr;
    }
  }
  else
    m_cpuQueryLoad = nullptr;
#elif defined(TARGET_FREEBSD)
  size_t len;
  int i;
  char cpumodel[512];

  len = sizeof(m_cpuCount);
  if (sysctlbyname("hw.ncpu", &m_cpuCount, &len, NULL, 0) != 0)
    m_cpuCount = 1;

  len = sizeof(cpumodel);
  if (sysctlbyname("hw.model", &cpumodel, &len, NULL, 0) != 0)
    (void)strncpy(cpumodel, "Unknown", 8);
  m_cpuModel = cpumodel;

  for (i = 0; i < m_cpuCount; i++)
  {
    CoreInfo core;
    core.m_id = i;
    core.m_strModel = m_cpuModel;
    m_cores[core.m_id] = core;
  }
#else
  m_fProcStat = fopen("/proc/stat", "r");
  m_fProcTemperature = fopen("/proc/acpi/thermal_zone/THM0/temperature", "r");
  if (m_fProcTemperature == NULL)
    m_fProcTemperature = fopen("/proc/acpi/thermal_zone/THRM/temperature", "r");
  if (m_fProcTemperature == NULL)
    m_fProcTemperature = fopen("/proc/acpi/thermal_zone/THR0/temperature", "r");
  if (m_fProcTemperature == NULL)
    m_fProcTemperature = fopen("/proc/acpi/thermal_zone/TZ0/temperature", "r");
  // read from the new location of the temperature data on new kernels, 2.6.39, 3.0 etc
  if (m_fProcTemperature == NULL)   
    m_fProcTemperature = fopen("/sys/class/hwmon/hwmon0/temp1_input", "r");
  if (m_fProcTemperature == NULL)   
    m_fProcTemperature = fopen("/sys/class/thermal/thermal_zone0/temp", "r");  // On Raspberry PIs

  m_fCPUFreq = fopen ("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", "r");
  if (!m_fCPUFreq)
  {
    m_cpuInfoForFreq = true;
    m_fCPUFreq = fopen("/proc/cpuinfo", "r");
  }
  else
    m_cpuInfoForFreq = false;


  FILE* fCPUInfo = fopen("/proc/cpuinfo", "r");
  m_cpuCount = 0;
  if (fCPUInfo)
  {
    char buffer[512];

    int nCurrId = 0;
    while (fgets(buffer, sizeof(buffer), fCPUInfo))
    {
      if (strncmp(buffer, "processor", strlen("processor"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle)
        {
          CoreInfo core;
          core.m_id = atoi(needle+2);
          nCurrId = core.m_id;
          m_cores[core.m_id] = core;
        }
        m_cpuCount++;
      }
      else if (strncmp(buffer, "vendor_id", strlen("vendor_id"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle && strlen(needle)>3)
        {
          needle+=2;
          m_cores[nCurrId].m_strVendor = needle;
          StringUtils::Trim(m_cores[nCurrId].m_strVendor);
        }
      }
      else if (strncmp(buffer, "Processor", strlen("Processor"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle && strlen(needle)>3)
        {
          needle+=2;
          m_cpuModel = needle;
          m_cores[nCurrId].m_strModel = m_cpuModel;
          StringUtils::Trim(m_cores[nCurrId].m_strModel);
        }
      }
      else if (strncmp(buffer, "BogoMIPS", strlen("BogoMIPS"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle && strlen(needle)>3)
        {
          needle+=2;
          m_cpuBogoMips = needle;
          m_cores[nCurrId].m_strBogoMips = m_cpuBogoMips;
          StringUtils::Trim(m_cores[nCurrId].m_strBogoMips);
        }
      }
      else if (strncmp(buffer, "Hardware", strlen("Hardware"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle && strlen(needle)>3)
        {
          needle+=2;
          m_cpuHardware = needle;
          m_cores[nCurrId].m_strHardware = m_cpuHardware;
          StringUtils::Trim(m_cores[nCurrId].m_strHardware);
        }
      }
      else if (strncmp(buffer, "Revision", strlen("Revision"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle && strlen(needle)>3)
        {
          needle+=2;
          m_cpuRevision = needle;
          m_cores[nCurrId].m_strRevision = m_cpuRevision;
          StringUtils::Trim(m_cores[nCurrId].m_strRevision);
        }
      }
      else if (strncmp(buffer, "Serial", strlen("Serial"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle && strlen(needle)>3)
        {
          needle+=2;
          m_cpuSerial = needle;
          m_cores[nCurrId].m_strSerial = m_cpuSerial;
          StringUtils::Trim(m_cores[nCurrId].m_strSerial);
        }
      }
      else if (strncmp(buffer, "model name", strlen("model name"))==0)
      {
        char *needle = strstr(buffer, ":");
        if (needle && strlen(needle)>3)
        {
          needle+=2;
          m_cpuModel = needle;
          m_cores[nCurrId].m_strModel = m_cpuModel;
          StringUtils::Trim(m_cores[nCurrId].m_strModel);
        }
      }
      else if (strncmp(buffer, "flags", 5) == 0)
      {
        char* needle = strchr(buffer, ':');
        if (needle)
        {
          char* tok = NULL,
              * save;
          needle++;
          tok = strtok_r(needle, " ", &save);
          while (tok)
          {
            if (0 == strcmp(tok, "mmx"))
              m_cpuFeatures |= CPU_FEATURE_MMX;
            else if (0 == strcmp(tok, "mmxext"))
              m_cpuFeatures |= CPU_FEATURE_MMX2;
            else if (0 == strcmp(tok, "sse"))
              m_cpuFeatures |= CPU_FEATURE_SSE;
            else if (0 == strcmp(tok, "sse2"))
              m_cpuFeatures |= CPU_FEATURE_SSE2;
            else if (0 == strcmp(tok, "sse3"))
              m_cpuFeatures |= CPU_FEATURE_SSE3;
            else if (0 == strcmp(tok, "ssse3"))
              m_cpuFeatures |= CPU_FEATURE_SSSE3;
            else if (0 == strcmp(tok, "sse4_1"))
              m_cpuFeatures |= CPU_FEATURE_SSE4;
            else if (0 == strcmp(tok, "sse4_2"))
              m_cpuFeatures |= CPU_FEATURE_SSE42;
            else if (0 == strcmp(tok, "3dnow"))
              m_cpuFeatures |= CPU_FEATURE_3DNOW;
            else if (0 == strcmp(tok, "3dnowext"))
              m_cpuFeatures |= CPU_FEATURE_3DNOWEXT;
            tok = strtok_r(NULL, " ", &save);
          }
        }
      }
    }
    fclose(fCPUInfo);
    //  /proc/cpuinfo is not reliable on some Android platforms
    //  At least we should get the correct cpu count for multithreaded decoding
#if defined(TARGET_ANDROID)
    if (CAndroidFeatures::GetCPUCount() > m_cpuCount)
    {
      for (int i = m_cpuCount; i < CAndroidFeatures::GetCPUCount(); i++)
      {
        // Copy info from cpu 0
        CoreInfo core(m_cores[0]);
        core.m_id = i;
        m_cores[core.m_id] = core;
      }

      m_cpuCount = CAndroidFeatures::GetCPUCount();
    }
#endif
  }
  else
  {
    m_cpuCount = 1;
    m_cpuModel = "Unknown";
  }

#endif
  StringUtils::Replace(m_cpuModel, '\r', ' ');
  StringUtils::Replace(m_cpuModel, '\n', ' ');
  StringUtils::RemoveDuplicatedSpacesAndTabs(m_cpuModel);
  StringUtils::Trim(m_cpuModel);

  /* Set some default for empty string variables */
  if (m_cpuBogoMips.empty())
    m_cpuBogoMips = "N/A";
  if (m_cpuHardware.empty())
    m_cpuHardware = "N/A";
  if (m_cpuRevision.empty())
    m_cpuRevision = "N/A";
  if (m_cpuSerial.empty())
    m_cpuSerial = "N/A";

  readProcStat(m_userTicks, m_niceTicks, m_systemTicks, m_idleTicks, m_ioTicks);
  m_nextUsedReadTime.Set(MINIMUM_TIME_BETWEEN_READS);

  ReadCPUFeatures();

  // Set MMX2 when SSE is present as SSE is a superset of MMX2 and Intel doesn't set the MMX2 cap
  if (m_cpuFeatures & CPU_FEATURE_SSE)
    m_cpuFeatures |= CPU_FEATURE_MMX2;

  if (HasNeon())
    m_cpuFeatures |= CPU_FEATURE_NEON;

}
Exemple #27
0
/* Perform any power change work to nodes */
static void _do_power_work(time_t now)
{
	static time_t last_log = 0, last_work_scan = 0;
	int i, wake_cnt = 0, sleep_cnt = 0, susp_total = 0;
	time_t delta_t;
	uint32_t susp_state;
	bitstr_t *wake_node_bitmap = NULL, *sleep_node_bitmap = NULL;
	struct node_record *node_ptr;
	bool run_suspend = false;

	if (last_work_scan == 0) {
		if (exc_nodes &&
		    (node_name2bitmap(exc_nodes, false, &exc_node_bitmap))) {
			error("Invalid SuspendExcNodes %s ignored", exc_nodes);
		}

		if (exc_parts) {
			char *tmp = NULL, *one_part = NULL, *part_list = NULL;
			struct part_record *part_ptr = NULL;

			part_list = xstrdup(exc_parts);
			one_part = strtok_r(part_list, ",", &tmp);
			while (one_part != NULL) {
				part_ptr = find_part_record(one_part);
				if (!part_ptr) {
					error("Invalid SuspendExcPart %s ignored",
					      one_part);
				} else if (exc_node_bitmap) {
					bit_or(exc_node_bitmap,
					       part_ptr->node_bitmap);
				} else {
					exc_node_bitmap =
						bit_copy(part_ptr->node_bitmap);
				}
				one_part = strtok_r(NULL, ",", &tmp);
			}
			xfree(part_list);
		}

		if (exc_node_bitmap) {
			char *tmp = bitmap2node_name(exc_node_bitmap);
			info("power_save module, excluded nodes %s", tmp);
			xfree(tmp);
		}
	}

	/* Set limit on counts of nodes to have state changed */
	delta_t = now - last_work_scan;
	if (delta_t >= 60) {
		suspend_cnt_f = 0.0;
		resume_cnt_f  = 0.0;
	} else {
		float rate = (60 - delta_t) / 60.0;
		suspend_cnt_f *= rate;
		resume_cnt_f  *= rate;
	}
	suspend_cnt = (suspend_cnt_f + 0.5);
	resume_cnt  = (resume_cnt_f  + 0.5);

	if (now > (last_suspend + suspend_timeout)) {
		/* ready to start another round of node suspends */
		run_suspend = true;
		if (last_suspend) {
			bit_nclear(suspend_node_bitmap, 0,
				   (node_record_count - 1));
			bit_nclear(resume_node_bitmap, 0,
				   (node_record_count - 1));
			last_suspend = (time_t) 0;
		}
	}

	last_work_scan = now;

	/* Build bitmaps identifying each node which should change state */
	for (i = 0, node_ptr = node_record_table_ptr;
	     i < node_record_count; i++, node_ptr++) {
		susp_state = IS_NODE_POWER_SAVE(node_ptr);

		if (susp_state)
			susp_total++;

		/* Resume nodes as appropriate */
		if (susp_state &&
		    ((resume_rate == 0) || (resume_cnt < resume_rate))	&&
		    (bit_test(suspend_node_bitmap, i) == 0)		&&
		    (IS_NODE_ALLOCATED(node_ptr) ||
		     (node_ptr->last_idle > (now - idle_time)))) {
			if (wake_node_bitmap == NULL) {
				wake_node_bitmap =
					bit_alloc(node_record_count);
			}
			wake_cnt++;
			resume_cnt++;
			resume_cnt_f++;
			node_ptr->node_state &= (~NODE_STATE_POWER_SAVE);
			node_ptr->node_state |=   NODE_STATE_POWER_UP;
			node_ptr->node_state |=   NODE_STATE_NO_RESPOND;
			bit_clear(power_node_bitmap, i);
			bit_clear(avail_node_bitmap, i);
			node_ptr->last_response = now + resume_timeout;
			bit_set(wake_node_bitmap,    i);
			bit_set(resume_node_bitmap,  i);
		}

		/* Suspend nodes as appropriate */
		if (run_suspend 					&&
		    (susp_state == 0)					&&
		    ((suspend_rate == 0) || (suspend_cnt < suspend_rate)) &&
		    (IS_NODE_IDLE(node_ptr) || IS_NODE_DOWN(node_ptr))	&&
		    (node_ptr->sus_job_cnt == 0)			&&
		    (!IS_NODE_COMPLETING(node_ptr))			&&
		    (!IS_NODE_POWER_UP(node_ptr))			&&
		    (node_ptr->last_idle != 0)				&&
		    (node_ptr->last_idle < (now - idle_time))		&&
		    ((exc_node_bitmap == NULL) ||
		     (bit_test(exc_node_bitmap, i) == 0))) {
			if (sleep_node_bitmap == NULL) {
				sleep_node_bitmap =
					bit_alloc(node_record_count);
			}
			sleep_cnt++;
			suspend_cnt++;
			suspend_cnt_f++;
			node_ptr->node_state |= NODE_STATE_POWER_SAVE;
			node_ptr->node_state &= (~NODE_STATE_NO_RESPOND);
			if (!IS_NODE_DOWN(node_ptr) &&
			    !IS_NODE_DRAIN(node_ptr) &&
			    !IS_NODE_FAIL(node_ptr))
				bit_set(avail_node_bitmap,   i);
			bit_set(power_node_bitmap,   i);
			bit_set(sleep_node_bitmap,   i);
			bit_set(suspend_node_bitmap, i);
			last_suspend = now;
		}
	}
	if (((now - last_log) > 600) && (susp_total > 0)) {
		info("Power save mode: %d nodes", susp_total);
		last_log = now;
	}

	if (sleep_node_bitmap) {
		char *nodes;
		nodes = bitmap2node_name(sleep_node_bitmap);
		if (nodes)
			_do_suspend(nodes);
		else
			error("power_save: bitmap2nodename");
		xfree(nodes);
		FREE_NULL_BITMAP(sleep_node_bitmap);
		/* last_node_update could be changed already by another thread!
		last_node_update = now; */
	}

	if (wake_node_bitmap) {
		char *nodes;
		nodes = bitmap2node_name(wake_node_bitmap);
		if (nodes)
			_do_resume(nodes);
		else
			error("power_save: bitmap2nodename");
		xfree(nodes);
		FREE_NULL_BITMAP(wake_node_bitmap);
		/* last_node_update could be changed already by another thread!
		last_node_update = now; */
	}
}
Exemple #28
0
static int blazer_status(const char *cmd)
{
	const struct {
		const char	*var;
		const char	*fmt;
		double	(*conv)(const char *, char **);
	} status[] = {
		{ "input.voltage", "%.1f", strtod },
		{ "input.voltage.fault", "%.1f", strtod },
		{ "output.voltage", "%.1f", strtod },
		{ "ups.load", "%.0f", blazer_load },
		{ "input.frequency", "%.1f", strtod },
		{ "battery.voltage", "%.2f", blazer_battery },
		{ "ups.temperature", "%.1f", strtod },
		{ NULL }
	};

	char	buf[SMALLBUF], *val, *last = NULL;
	int	i;

	/*
	 * > [Q1\r]
	 * < [(226.0 195.0 226.0 014 49.0 27.5 30.0 00001000\r]
	 *    01234567890123456789012345678901234567890123456
	 *    0         1         2         3         4
	 */
	if (blazer_command(cmd, buf, sizeof(buf)) < 46) {
		upsdebugx(2, "%s: short reply", __func__);
		return -1;
	}

	if (buf[0] != '(') {
		upsdebugx(2, "%s: invalid start character [%02x]", __func__, buf[0]);
		return -1;
	}

	for (i = 0, val = strtok_r(buf+1, " ", &last); status[i].var; i++, val = strtok_r(NULL, " \r\n", &last)) {

		if (!val) {
			upsdebugx(2, "%s: parsing failed", __func__);
			return -1;
		}

		if (strspn(val, "0123456789.") != strlen(val)) {
			upsdebugx(2, "%s: non numerical value [%s]", __func__, val);
			continue;
		}

		dstate_setinfo(status[i].var, status[i].fmt, status[i].conv(val, NULL));
	}

	if (!val) {
		upsdebugx(2, "%s: parsing failed", __func__);
		return -1;
	}

	if (strspn(val, "01") != 8) {
		upsdebugx(2, "Invalid status [%s]", val);
		return -1;
	}

	if (val[7] == '1') {	/* Beeper On */
		dstate_setinfo("ups.beeper.status", "enabled");
	} else {
		dstate_setinfo("ups.beeper.status", "disabled");
	}

	if (val[4] == '1') {	/* UPS Type is Standby (0 is On_line) */
		dstate_setinfo("ups.type", "offline / line interactive");
	} else {
		dstate_setinfo("ups.type", "online");
	}

	status_init();

	if (val[0] == '1') {	/* Utility Fail (Immediate) */
		status_set("OB");
		online = 0;
	} else {
		status_set("OL");
		online = 1;
	}

	if (val[1] == '1') {	/* Battery Low */
		status_set("LB");
	}

	if (val[2] == '1') {	/* Bypass/Boost or Buck Active */

		double	vi, vo;

		vi = strtod(dstate_getinfo("input.voltage"),  NULL);
		vo = strtod(dstate_getinfo("output.voltage"), NULL);

		if (vo < 0.5 * vi) {
			upsdebugx(2, "%s: output voltage too low", __func__);
		} else if (vo < 0.95 * vi) {
			status_set("TRIM");
		} else if (vo < 1.05 * vi) {
			status_set("BYPASS");
		} else if (vo < 1.5 * vi) {
			status_set("BOOST");
		} else {
			upsdebugx(2, "%s: output voltage too high", __func__);
		}
	}

	if (val[5] == '1') {	/* Test in Progress */
		status_set("CAL");
	}

	alarm_init();

	if (val[3] == '1') {	/* UPS Failed */
		alarm_set("UPS selftest failed!");
	}

	if (val[6] == '1') {	/* Shutdown Active */
		alarm_set("Shutdown imminent!");
		status_set("FSD");
	}

	alarm_commit();

	status_commit();

	return 0;
}
Exemple #29
0
void guava_router_mvc_route(guava_router_mvc_t *router, guava_request_t *req, guava_handler_t *handler) {
  if (!router || !req || !handler) {
    return;
  }

  char *ptr = strstr(req->path, router->route.mount_point);
  if (!ptr) {
    return;
  }

  ptr += guava_string_len(router->route.mount_point);

  const char *sep = "/";

  char *word, *save;

  guava_string_t module = NULL;
  guava_string_t cls = NULL;
  guava_string_t action = NULL;
  PyObject *args = NULL;
  PyObject *arg = NULL;

  size_t idx = 0;
  for (word = strtok_r(ptr, sep, &save); word; word = strtok_r(NULL, sep, &save), ++idx) {
    if (idx == 0) {
      module = guava_string_new(word);
      char s[1024];
      snprintf(s, sizeof(s), "%c%sController", toupper(word[0]), word+1);
      cls = guava_string_new(s);
    } else if (idx == 1) {
      action = guava_string_new(word);
    } else {
      arg = PyString_FromString(word);
      if (!args) {
        args = PyList_New(0);
      }
      PyList_Append(args, arg);
      Py_DECREF(arg);
    }
  }

  if (!module) {
    module = guava_string_new("index");
  }
  if (!cls) {
    cls = guava_string_new("IndexController");
  }
  if (!action) {
    action = guava_string_new("index");
  }

  handler->package = guava_string_new(router->route.package);
  handler->module = module;
  handler->cls = cls;
  handler->action = action;

  if (args) {
    handler->args = PyList_AsTuple(args);
    Py_DECREF(args);
  }

  guava_handler_mark_valid(handler);
}
Exemple #30
0
static int lirc_code2char_internal(const struct lirc_state *state,
								   struct lirc_config *config,char *code,
								   char **string, char **prog)
{
	int rep;
	char *backup, *strtok_state = NULL;
	char *remote,*button;
	char *s=NULL;
	struct lirc_config_entry *scan;
	int exec_level;
	int quit_happened;

	*string=NULL;
	if(sscanf(code,"%*20x %20x %*5000s %*5000s\n",&rep)==1)
	{
		backup=strdup(code);
		if(backup==NULL) return(-1);

		strtok_r(backup," ",&strtok_state);
		strtok_r(NULL," ",&strtok_state);
		button=strtok_r(NULL," ",&strtok_state);
		remote=strtok_r(NULL,"\n",&strtok_state);

		if(button==NULL || remote==NULL)
		{
			free(backup);
			return(0);
		}
		
		scan=config->next;
		quit_happened=0;
		while(scan!=NULL)
		{
			exec_level = lirc_iscode(scan,remote,button,rep);
			if(exec_level > 0 &&
			   (scan->mode==NULL ||
			    (scan->mode!=NULL && 
			     config->current_mode!=NULL &&
			     strcasecmp(scan->mode,config->current_mode)==0)) &&
			   quit_happened==0
			   )
			{
				if(exec_level > 1)
				{
					s=lirc_execute(state,config,scan);
					if(s != NULL && prog != NULL)
					{
						*prog = scan->prog;
					}
				}
				else
				{
					s = NULL;
				}
				if(scan->flags&quit)
				{
					quit_happened=1;
					config->next=NULL;
					scan=scan->next;
					continue;
				}
				else if(s!=NULL)
				{
					config->next=scan->next;
					break;
				}
			}
			scan=scan->next;
		}
		free(backup);
		if(s!=NULL)
		{
			*string=s;
			return(0);
		}
	}
	config->next=config->first;
	return(0);
}