示例#1
0
/*
 * Calculate dialog hooks
 */
static inline int calculate_hooks(dlg_t* _d)
{
	str* uri;
	struct sip_uri puri;
	param_hooks_t hooks;
	param_t* params;

	if (_d->route_set) {
		uri = &_d->route_set->nameaddr.uri;
		if (parse_uri(uri->s, uri->len, &puri) < 0) {
			LOG(L_ERR, "calculate_hooks(): Error while parsing URI\n");
			return -1;
		}

		if (parse_params(&puri.params, CLASS_URI, &hooks, &params) < 0) {
			LOG(L_ERR, "calculate_hooks(): Error while parsing parameters\n");
			return -2;
		}
		free_params(params);
		
		if (hooks.uri.lr) {
			if (_d->rem_target.s) _d->hooks.request_uri = &_d->rem_target;
			else _d->hooks.request_uri = &_d->rem_uri;
			_d->hooks.next_hop = &_d->route_set->nameaddr.uri;
			_d->hooks.first_route = _d->route_set;
		} else {
			_d->hooks.request_uri = &_d->route_set->nameaddr.uri;
			_d->hooks.next_hop = _d->hooks.request_uri;
			_d->hooks.first_route = _d->route_set->next;
			if (_d->rem_target.len > 0) 
				_d->hooks.last_route = &_d->rem_target;
			else 
				_d->hooks.last_route = NULL; /* ? */
		}
	} else {
		if (_d->rem_target.s) _d->hooks.request_uri = &_d->rem_target;
		else _d->hooks.request_uri = &_d->rem_uri;
		
		if (_d->dst_uri.s) _d->hooks.next_hop = &_d->dst_uri;
		else _d->hooks.next_hop = _d->hooks.request_uri;
		/* 
		 * the routes need to be reset because if the route_set was dropped by somebody else 
		 * then this will remain set without the actual routes 
		 */
		_d->hooks.first_route = 0;
		_d->hooks.last_route = 0;
	}

	if ((_d->hooks.request_uri) && (_d->hooks.request_uri->s) && (_d->hooks.request_uri->len)) {
		_d->hooks.ru.s = _d->hooks.request_uri->s;
		_d->hooks.ru.len = _d->hooks.request_uri->len;
		_d->hooks.request_uri = &_d->hooks.ru;
		get_raw_uri(_d->hooks.request_uri);
	}
	if ((_d->hooks.next_hop) && (_d->hooks.next_hop->s) && (_d->hooks.next_hop->len)) {
		_d->hooks.nh.s = _d->hooks.next_hop->s;
		_d->hooks.nh.len = _d->hooks.next_hop->len;
		_d->hooks.next_hop = &_d->hooks.nh;
		get_raw_uri(_d->hooks.next_hop);
	}

	return 0;
}
示例#2
0
static int ds_parse_reply_codes() {
	param_t* params_list = NULL;
	param_t *pit=NULL;
	int list_size = 0;
	int i = 0;
	int pos = 0;
	int code = 0;
	str input = {0, 0};
	int* ds_ping_reply_codes_new = NULL;
	int* ds_ping_reply_codes_old = NULL;

	/* Validate String: */
	if (cfg_get(dispatcher, dispatcher_cfg, ds_ping_reply_codes_str).s == 0 
			|| cfg_get(dispatcher, dispatcher_cfg, ds_ping_reply_codes_str).len<=0)
		return 0;

	/* parse_params will modify the string pointer of .s, so we need to make a copy. */
	input.s = cfg_get(dispatcher, dispatcher_cfg, ds_ping_reply_codes_str).s;
	input.len = cfg_get(dispatcher, dispatcher_cfg, ds_ping_reply_codes_str).len;

	/* Parse the parameters: */
	if (parse_params(&input, CLASS_ANY, 0, &params_list)<0)
		return -1;

	/* Get the number of entries in the list */
	for (pit = params_list; pit; pit=pit->next)
	{
		if (pit->name.len==4
				&& strncasecmp(pit->name.s, "code", 4)==0) {
			str2sint(&pit->body, &code);
			if ((code >= 100) && (code < 700))
				list_size += 1;
		} else if (pit->name.len==5
				&& strncasecmp(pit->name.s, "class", 5)==0) {
			str2sint(&pit->body, &code);
			if ((code >= 1) && (code < 7))
				list_size += 100;
		}
	}
	LM_DBG("Should be %d Destinations.\n", list_size);

	if (list_size > 0) {
		/* Allocate Memory for the new list: */
		ds_ping_reply_codes_new = (int*)shm_malloc(list_size * sizeof(int));
		if(ds_ping_reply_codes_new== NULL)
		{
			free_params(params_list);
			LM_ERR("no more memory\n");
			return -1;
		}

		/* Now create the list of valid reply-codes: */
		for (pit = params_list; pit; pit=pit->next)
		{
			if (pit->name.len==4
					&& strncasecmp(pit->name.s, "code", 4)==0) {
				str2sint(&pit->body, &code);
				if ((code >= 100) && (code < 700))
					ds_ping_reply_codes_new[pos++] = code;
			} else if (pit->name.len==5
					&& strncasecmp(pit->name.s, "class", 5)==0) {
				str2sint(&pit->body, &code);
				if ((code >= 1) && (code < 7)) {
					/* Add every code from this class, e.g. 100 to 199 */
					for (i = (code*100); i <= ((code*100)+99); i++) 
						ds_ping_reply_codes_new[pos++] = i;
				}
			}
		}
	} else {
		ds_ping_reply_codes_new = 0;
	}
	free_params(params_list);

	/* More reply-codes? Change Pointer and then set number of codes. */
	if (list_size > *ds_ping_reply_codes_cnt) {
		// Copy Pointer
		ds_ping_reply_codes_old = *ds_ping_reply_codes;
		*ds_ping_reply_codes = ds_ping_reply_codes_new;
		// Done: Set new Number of entries:
		*ds_ping_reply_codes_cnt = list_size;
		// Free the old memory area:
		if(ds_ping_reply_codes_old)
			shm_free(ds_ping_reply_codes_old);	
		/* Less or equal? Set the number of codes first. */
	} else {
		// Done:
		*ds_ping_reply_codes_cnt = list_size;
		// Copy Pointer
		ds_ping_reply_codes_old = *ds_ping_reply_codes;
		*ds_ping_reply_codes = ds_ping_reply_codes_new;
		// Free the old memory area:
		if(ds_ping_reply_codes_old)
			shm_free(ds_ping_reply_codes_old);	
	}
	/* Print the list as INFO: */
	for (i =0; i< *ds_ping_reply_codes_cnt; i++)
	{
		LM_DBG("Dispatcher: Now accepting Reply-Code %d (%d/%d) as valid\n",
				(*ds_ping_reply_codes)[i], (i+1), *ds_ping_reply_codes_cnt);
	}
	return 0;
}
示例#3
0
int main(int argc, char *argv[])
{
    int fd, ret;
    struct source_control *c;
    char *pkgdir;

    if (parse_params(argc, argv) != 0) {
        fprintf(stderr, "Usage: pkgbuild OPTIONS SOURCE-CONTROL\n");
        fprintf(stderr, "  Options:\n");
        fprintf(stderr, "    -U       No unpack\n");
        fprintf(stderr, "    -B       No build\n");
        fprintf(stderr, "    -C       Do not generate control files\n");
        fprintf(stderr, "    -o ODIR  Output directory for binary package\n");
        fprintf(stderr, "    -w WDIR  Work directory\n");
        fprintf(stderr, "    -d DDIR  Directory for distfiles\n");
        fprintf(stderr, "    -v VER   Set binary package version\n");
        fprintf(stderr, "    -V AVER  Append AVER to binary package version\n");
        fprintf(stderr, "    -p PDIR  Package directory, if withpkg to be used\n");
        return EXIT_FAILURE;
    }

    /* parse source control file */
    if ((fd = open(control_path, O_RDONLY)) == -1) {
        perror("Opening control file failed");
        return EXIT_FAILURE;
    }
    ret = source_control_parsefd(fd, &c);
    close(fd);
    if (ret != 0) {
        fprintf(stderr, "Parsing source control file failed\n");
        return EXIT_FAILURE;
    }

    /* figure out version */
    version = c->version;
    if (ver_mode == VERSION_OVERRIDE) {
        version = ver_param;
    } else if (ver_mode == VERSION_APPEND) {
        if (asprintf(&version, "%s%s", c->version, ver_param) == -1) {
          perror("asprintf version failed");
          return EXIT_FAILURE;
        }
    }

    /* setup environment */
    if (asprintf(&pkgdir, "/packages/%s/%s", c->source, version) == -1) {
        perror("asprintf pkgdir failed");
        return EXIT_FAILURE;
    }
    if (setenv("PKG_NAME", c->source, 1) != 0 ||
            setenv("PKG_SRCVERSION", c->version, 1) != 0 ||
            setenv("PKG_VERSION", version, 1) != 0 ||
            setenv("PKG_DIR", pkgdir, 1) != 0)
    {
        perror("setenv failed");
        return EXIT_FAILURE;
    }
    if (chdir(work_dir) != 0) {
        perror("chdir failed");
        return EXIT_FAILURE;
    }

    if (do_unpack && unpack(c) != 0)
        return EXIT_FAILURE;

    if (do_build && build(c) != 0)
        return EXIT_FAILURE;

    if (do_gencontrol && gencontrol(c) != 0)
        return EXIT_FAILURE;

    source_control_destroy(c);
    return EXIT_SUCCESS;
}
示例#4
0
/*
 * Parse Route and Record-Route header fields
 */
int parse_rr(struct hdr_field* _h)
{
	rr_t* r, *last;
	str s;
	param_hooks_t hooks;

	if (!_h) {
		LOG(L_ERR, "parse_rr(): Invalid parameter value\n");
		return -1;
	}

	if (_h->parsed) {
		     /* Already parsed, return */
		return 0;
	}

	     /* Make a temporary copy of the string pointer */
	s.s = _h->body.s;
	s.len = _h->body.len;
	trim_leading(&s);

	last = 0;

	while(1) {
		     /* Allocate and clear rr stucture */
		r = (rr_t*)pkg_malloc(sizeof(rr_t));
		if (!r) {
			LOG(L_ERR, "parse_rr(): No memory left\n");
			goto error;
		}
		memset(r, 0, sizeof(rr_t));
		
		     /* Parse name-addr part of the header */
		if (parse_nameaddr(&s, &r->nameaddr) < 0) {
			LOG(L_ERR, "parse_rr(): Error while parsing name-addr\n");
			goto error;
		}
		r->len = r->nameaddr.len;

		     /* Shift just behind the closing > */
		s.s = r->nameaddr.name.s + r->nameaddr.len;  /* Point just behind > */
		s.len -= r->nameaddr.len;

		trim_leading(&s); /* Skip any whitechars */
		
		     /* Nothing left, finish */
		if (s.len == 0) goto ok;
		
		if (s.s[0] == ';') {         /* Contact parameter found */
			s.s++;
			s.len--;
			trim_leading(&s);
			
			if (s.len == 0) {
				LOG(L_ERR, "parse_rr(): Error while parsing params\n");
				goto error;
			}

			     /* Parse all parameters */
			if (parse_params(&s, CLASS_ANY, &hooks, &r->params) < 0) {
				LOG(L_ERR, "parse_rr(): Error while parsing params\n");
				goto error;
			}
			r->len = r->params->name.s + r->params->len - r->nameaddr.name.s;

			     /* Copy hooks */
			     /*r->r2 = hooks.rr.r2; */
			trim_leading(&s);
			if (s.len == 0) goto ok;
		}

		if (s.s[0] != ',') {
			LOG(L_ERR, "parse_rr(): Invalid character '%c', comma expected\n", s.s[0]);
			goto error;
		}

		     /* Next character is comma or end of header*/
		s.s++;
		s.len--;
		trim_leading(&s);

		if (s.len == 0) {
			LOG(L_ERR, "parse_rr(): Text after comma missing\n");
			goto error;
		}

		     /* Append the structure as last parameter of the linked list */
		if (!_h->parsed) _h->parsed = (void*)r;
		if (last) last->next = r;
		last = r;
	}

 error:
	if (r) pkg_free(r);
	free_rr((rr_t**)&_h->parsed); /* Free any contacts created so far */
	return -1;

 ok:
	if (!_h->parsed) _h->parsed = (void*)r;
	if (last) last->next = r;
	return 0;
}
示例#5
0
/**
 * @brief build a dmq node
 */
dmq_node_t* build_dmq_node(str* uri, int shm) {
    dmq_node_t* ret = NULL;
    param_hooks_t hooks;
    param_t* params;

    /* For DNS-Lookups */
    static char hn[256];
    struct hostent* he;

    LM_DBG("build_dmq_node %.*s with %s memory\n", STR_FMT(uri), shm?"shm":"private");

    if(shm) {
        ret = shm_malloc(sizeof(dmq_node_t));
        if(ret==NULL) {
            LM_ERR("no more shm\n");
            goto error;
        }
        memset(ret, 0, sizeof(dmq_node_t));
        if(shm_str_dup(&ret->orig_uri, uri)<0) {
            goto error;
        }
    } else {
        ret = pkg_malloc(sizeof(dmq_node_t));
        if(ret==NULL) {
            LM_ERR("no more pkg\n");
            goto error;
        }
        memset(ret, 0, sizeof(dmq_node_t));
        if(pkg_str_dup(&ret->orig_uri, uri)<0) {
            goto error;
        }
    }
    set_default_dmq_node_params(ret);
    if(parse_uri(ret->orig_uri.s, ret->orig_uri.len, &ret->uri) < 0 || ret->uri.host.len > 254) {
        LM_ERR("error parsing uri\n");
        goto error;
    }
    /* if any parameters found, parse them */
    if(parse_params(&ret->uri.params, CLASS_ANY, &hooks, &params) < 0) {
        LM_ERR("error parsing params\n");
        goto error;
    }
    /* if any params found */
    if(params) {
        if(shm) {
            if(shm_duplicate_params(&ret->params, params) < 0) {
                LM_ERR("error duplicating params\n");
                free_params(params);
                goto error;
            }
            free_params(params);
        } else {
            ret->params = params;
        }
        if(set_dmq_node_params(ret, ret->params) < 0) {
            LM_ERR("error setting parameters\n");
            goto error;
        }
    } else {
        LM_DBG("no dmqnode params found\n");
    }
    /* resolve hostname */
    strncpy(hn, ret->uri.host.s, ret->uri.host.len);
    hn[ret->uri.host.len]='\0';
    he=resolvehost(hn);
    if (he==0) {
        LM_ERR("could not resolve %.*s\n", ret->uri.host.len, ret->uri.host.s);
        goto error;
    }
    hostent2ip_addr(&ret->ip_address, he, 0);

    return ret;

error:
    if(ret!=NULL) {
        destroy_dmq_node(ret, shm);
    }
    return NULL;
}
示例#6
0
文件: ht_api.c 项目: tsudot/kamailio
/**
 * parse a string like: 'key=>value'
 *   - the value can be parameter list: 'name1=value1;...;nameX=valueX'
 */
int keyvalue_parse_str(str *data, int type, keyvalue_t *res)
{
	char *p;
	str s;
	str in;
	param_hooks_t phooks;

	if(data==NULL || data->s==NULL || data->len<=0 || res==NULL)
	{
		LM_ERR("invalid parameters\n");
		return -1;
	}

	memset(res, 0, sizeof(keyvalue_t));

	in.s = data->s;
	in.len = data->len;

	p = in.s;
	while(p<in.s+in.len && (*p==' ' || *p=='\t' || *p=='\n' || *p=='\r'))
		p++;
	if(p>in.s+in.len || *p=='\0')
		goto error;
	res->key.s = p;
	while(p < in.s + in.len)
	{
		if(*p=='=' || *p==' ' || *p=='\t' || *p=='\n' || *p=='\r')
			break;
		p++;
	}
	if(p>in.s+in.len || *p=='\0')
		goto error;
	res->key.len = (int)(p - res->key.s);
	if(*p!='=')
	{
		while(p<in.s+in.len && (*p==' ' || *p=='\t' || *p=='\n' || *p=='\r'))
			p++;
		if(p>in.s+in.len || *p=='\0' || *p!='=')
			goto error;
	}
	p++;
	if(*p!='>')
		goto error;
	p++;
	while(p<in.s+in.len && (*p==' ' || *p=='\t' || *p=='\n' || *p=='\r'))
		p++;

	s.s = p;
	s.len = in.s + in.len - p;
	res->value.s = s.s;
	res->value.len = s.len;
	res->type = type;
	if(type==KEYVALUE_TYPE_PARAMS)
	{
		if(s.s[s.len-1]==';')
			s.len--;
		if (parse_params(&s, CLASS_ANY, &phooks, &res->u.params)<0)
		{
			LM_ERR("failed parsing params value\n");
			goto error;
		}
	}
	return 0;
error:
	LM_ERR("invalid input parameter [%.*s] at [%d]\n", in.len, in.s,
			(int)(p-in.s));
	return -1;
}
示例#7
0
文件: strings.c 项目: smarter/thor
static int parse_params(int argc, char **argv, enc_params *params, param_list *list)
{
    int i, j;
    FILE *config;
    char **file_params;
    int num_file_params;

    char *tmp;
    int cnt;
    
    for (i = 1; i < argc; i++)
    {
      /* Check if parameter is in the list of known parameters */
      for (j = 0; j < list->num; j++)
      {
        if (strcmp(argv[i], list->params[j].name) == 0)
          break;
      }
      if (j == list->num)
      {
        fprintf(stderr, "Unknown parameter: %s\n", argv[i]);
        return -1;
      }

      /* Parse parameter value according to its type */
      switch (list->params[j].type)
      {

      /* Parameter value is a filename */
      case ARG_FILENAME:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No filename found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        if (strcmp(argv[i-1], "-cf") == 0)
        {
          /* Read the config file and parse it recursively */
          config = fopen(argv[i], "r");
          if (config == NULL)
          {
            fprintf(stderr, "Cannot open config file: %s\n", argv[i]);
            return -1;
          }
          file_params = read_config_file(config, &num_file_params);
          fclose(config);
          if (file_params == NULL)
          {
            return -1;
          }
          if (parse_params(num_file_params, file_params, params, list) < 0)
          {
            return -1;
          }
          delete_config_file_params(file_params);
          }
          else
          {
            if (*((char **)list->params[j].value) != NULL)
            {
              free(*((char **)list->params[j].value));
            }
            *((char **)list->params[j].value) = malloc((strlen(argv[i])+1)*sizeof(char));
            if (*((char **)list->params[j].value) == NULL)
            {
              fprintf(stderr, "Memory allocation failed\n");
              return -1;
            }
            strcpy(*((char **)list->params[j].value), argv[i]);
          }
          break;

      /* Parameter value is a comma-separated list of integers */
      case ARG_INTLIST:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No integer list found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        cnt = 1;
        if ((tmp = strtok(argv[i], ", ")) == NULL)
        {
          fprintf(stderr,"Error reading integer list for parameter: %s\n", argv[i-1]);
          return -1;
        }
        else
        {
          *(((int *)list->params[j].value)+cnt++) = atoi(tmp);
        }
        while ((tmp = strtok(NULL,", ")) != NULL)
        {
           *(((int *)list->params[j].value)+cnt++) = atoi(tmp);
        }
        *(((int *)list->params[j].value)+0) = cnt-1;
        break;
      /* Parameter value is an integer */
      case ARG_INTEGER:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No value found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        *((int *)list->params[j].value) = atoi(argv[i]);
        break;

      /* Parameter value is a floating point value */
      case ARG_FLOAT:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No value found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        *((float *)list->params[j].value) = (float)atof(argv[i]);
        break;

      /* Parameter is a flag and does not have value */
      case ARG_NONE:
        *((int *)list->params[j].value) = 1;
        break;
      default:
        break;
      }
    }
    return 0;
}
示例#8
0
int main(int argc, char *argv[])
{
  // timing variables
  double start_total, stop_total, start_step, stop_step;
  #ifdef CPU_TIME
  double stop_init, init_min, init_max, init_avg;
  double start_bound, stop_bound, bound_min, bound_max, bound_avg;
  double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
  double init, bound, hydro;
  init = bound = hydro = 0;
  #endif //CPU_TIME

  // start the total time
  start_total = get_time();

  /* Initialize MPI communication */
  #ifdef MPI_CHOLLA
  InitializeChollaMPI(&argc, &argv);
  #endif /*MPI_CHOLLA*/

  // declare Cfl coefficient and initial inverse timestep
  Real C_cfl = 0.4; // CFL coefficient 0 < C_cfl < 0.5 
  Real dti = 0; // inverse time step, 1.0 / dt

  // input parameter variables
  char *param_file;
  struct parameters P;
  int nfile = 0; // number of output files
  Real outtime = 0; // current output time

  // read in command line arguments
  if (argc != 2)
  {
    chprintf("usage: %s <parameter_file>\n", argv[0]);
    chexit(0);
  } else {
    param_file = argv[1];
  }

  // create the grid
  Grid3D G;

  // read in the parameters
  parse_params (param_file, &P);
  // and output to screen
  chprintf ("Parameter values:  nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n", 
    P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
  chprintf ("Output directory:  %s\n", P.outdir);


  // initialize the grid
  G.Initialize(&P);
  chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);

  // Set initial conditions and calculate first dt
  chprintf("Setting initial conditions...\n");
  G.Set_Initial_Conditions(P, C_cfl);
  chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
  chprintf("Ratio of specific heats gamma = %f\n",gama);
  chprintf("Nstep = %d  Timestep = %f  Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);
  // set main variables for Read_Grid inital conditions
  if (strcmp(P.init, "Read_Grid") == 0) {
    outtime += G.H.t;
    nfile = P.nfile;
    dti = 1.0 / G.H.dt;
  }

  // set boundary conditions (assign appropriate values to ghost cells)
  chprintf("Setting boundary conditions...\n");
  G.Set_Boundary_Conditions(P);
  chprintf("Boundary conditions set.\n");


  #ifdef OUTPUT
  // write the initial conditions to file
  chprintf("Writing initial conditions to file...\n");
  WriteData(G, P, nfile);
  // add one to the output file count
  nfile++;
  #endif //OUTPUT
  // increment the next output time
  outtime += P.outstep;

  #ifdef CPU_TIME
  stop_init = get_time();
  init = stop_init - start_total;
  #ifdef MPI_CHOLLA
  init_min = ReduceRealMin(init);
  init_max = ReduceRealMax(init);
  init_avg = ReduceRealAvg(init);
  chprintf("Init  min: %9.4f  max: %9.4f  avg: %9.4f\n", init_min, init_max, init_avg);
  #else
  printf("Init %9.4f\n", init);
  #endif //MPI_CHOLLA
  #endif //CPU_TIME


  // Evolve the grid, one timestep at a time
  chprintf("Starting caclulations.\n");
  while (G.H.t < P.tout)
  //while (G.H.n_step < 1)
  {
    // get the start time
    start_step = get_time();

    // calculate the timestep
    G.set_dt(C_cfl, dti);
    
    if (G.H.t + G.H.dt > outtime) 
    {
      G.H.dt = outtime - G.H.t;
    }

    // Advance the grid by one timestep
    #ifdef CPU_TIME
    start_hydro = get_time();
    #endif //CPU_TIME
    dti = G.Update_Grid();
    #ifdef CPU_TIME
    stop_hydro = get_time();
    hydro = stop_hydro - start_hydro;
    #ifdef MPI_CHOLLA
    hydro_min = ReduceRealMin(hydro);
    hydro_max = ReduceRealMax(hydro);
    hydro_avg = ReduceRealAvg(hydro);
    #endif //MPI_CHOLLA
    #endif //CPU_TIME

    // update the time
    G.H.t += G.H.dt;

    // add one to the timestep count
    G.H.n_step++;

    // set boundary conditions for next time step 
    #ifdef CPU_TIME
    start_bound = get_time();
    #endif //CPU_TIME
    G.Set_Boundary_Conditions(P);
    #ifdef CPU_TIME
    stop_bound = get_time();
    bound = stop_bound - start_bound;
    #ifdef MPI_CHOLLA
    bound_min = ReduceRealMin(bound);
    bound_max = ReduceRealMax(bound);
    bound_avg = ReduceRealAvg(bound);
    #endif //MPI_CHOLLA
    #endif //CPU_TIME

    #ifdef CPU_TIME
    #ifdef MPI_CHOLLA
    chprintf("hydro min: %9.4f  max: %9.4f  avg: %9.4f\n", hydro_min, hydro_max, hydro_avg);
    chprintf("bound min: %9.4f  max: %9.4f  avg: %9.4f\n", bound_min, bound_max, bound_avg);
    #endif //MPI_CHOLLA
    #endif //CPU_TIME


    // get the time to compute the total timestep
    stop_step = get_time();
    stop_total = get_time();
    G.H.t_wall = stop_total-start_total;
    #ifdef MPI_CHOLLA
    G.H.t_wall = ReduceRealMax(G.H.t_wall);
    #endif 
    chprintf("n_step: %d   sim time: %10.7f   sim timestep: %7.4e  timestep time = %9.3f ms   total time = %9.4f s\n", 
      G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);

    if (G.H.t == outtime)
    {
      #ifdef OUTPUT
      /*output the grid data*/
      WriteData(G, P, nfile);
      // add one to the output file count
      nfile++;
      #endif //OUTPUT
      // update to the next output time
      outtime += P.outstep;      
    }

  } /*end loop over timesteps*/

  // free the grid
  G.Reset();

  #ifdef MPI_CHOLLA
  MPI_Finalize();
  #endif /*MPI_CHOLLA*/

  return 0;

}
示例#9
0
Datum
xslt_process(PG_FUNCTION_ARGS)
{
	text	   *doct = PG_GETARG_TEXT_P(0);
	text	   *ssheet = PG_GETARG_TEXT_P(1);
	text	   *paramstr;
	const char *params[MAXPARAMS + 1];	/* +1 for the terminator */
	xsltStylesheetPtr stylesheet = NULL;
	xmlDocPtr	doctree;
	xmlDocPtr	restree;
	xmlDocPtr	ssdoc = NULL;
	xmlChar    *resstr;
	int			resstat;
	int			reslen;

	if (fcinfo->nargs == 3)
	{
		paramstr = PG_GETARG_TEXT_P(2);
		parse_params(params, paramstr);
	}
	else
		/* No parameters */
		params[0] = NULL;

	/* Setup parser */
	pgxml_parser_init();

	/* Check to see if document is a file or a literal */

	if (VARDATA(doct)[0] == '<')
		doctree = xmlParseMemory((char *) VARDATA(doct), VARSIZE(doct) - VARHDRSZ);
	else
		doctree = xmlParseFile(text_to_cstring(doct));

	if (doctree == NULL)
	{
		xmlCleanupParser();
		elog_error(ERROR, "error parsing XML document", 0);

		PG_RETURN_NULL();
	}

	/* Same for stylesheet */
	if (VARDATA(ssheet)[0] == '<')
	{
		ssdoc = xmlParseMemory((char *) VARDATA(ssheet),
							   VARSIZE(ssheet) - VARHDRSZ);
		if (ssdoc == NULL)
		{
			xmlFreeDoc(doctree);
			xmlCleanupParser();
			elog_error(ERROR, "error parsing stylesheet as XML document", 0);
			PG_RETURN_NULL();
		}

		stylesheet = xsltParseStylesheetDoc(ssdoc);
	}
	else
		stylesheet = xsltParseStylesheetFile((xmlChar *) text_to_cstring(ssheet));


	if (stylesheet == NULL)
	{
		xmlFreeDoc(doctree);
		xsltCleanupGlobals();
		xmlCleanupParser();
		elog_error(ERROR, "failed to parse stylesheet", 0);
		PG_RETURN_NULL();
	}

	restree = xsltApplyStylesheet(stylesheet, doctree, params);
	resstat = xsltSaveResultToString(&resstr, &reslen, restree, stylesheet);

	xsltFreeStylesheet(stylesheet);
	xmlFreeDoc(restree);
	xmlFreeDoc(doctree);

	xsltCleanupGlobals();
	xmlCleanupParser();

	if (resstat < 0)
		PG_RETURN_NULL();

	PG_RETURN_TEXT_P(cstring_to_text_with_len((char *) resstr, reslen));
}
示例#10
0
/*! \brief
 * Combines all Path HF bodies into one string.
 */
int build_path_vector(struct sip_msg *_m, str *path, str *received)
{
	static char buf[MAX_PATH_SIZE];
	static char uri_buf[MAX_URI_SIZE];
	static str uri_str;
	char *p;
	struct hdr_field *hdr;
	struct sip_uri puri;

	rr_t *route = 0;

	path->len = 0;
	path->s = 0;
	received->s = 0;
	received->len = 0;

	if(parse_headers(_m, HDR_EOH_F, 0) < 0) {
		LM_ERR("failed to parse the message\n");
		goto error;
	}

	for( hdr=_m->path,p=buf ; hdr ; hdr = next_sibling_hdr(hdr)) {
		/* check for max. Path length */
		if( p-buf+hdr->body.len+1 >= MAX_PATH_SIZE) {
			LM_ERR("Overall Path body exceeds max. length of %d\n",
					MAX_PATH_SIZE);
			goto error;
		}
		if(p!=buf)
			*(p++) = ',';
		memcpy( p, hdr->body.s, hdr->body.len);
		p +=  hdr->body.len;
	}

	if (p!=buf) {
		/* check if next hop is a loose router */
		if (parse_rr_body( buf, p-buf, &route) < 0) {
			LM_ERR("failed to parse Path body, no head found\n");
			goto error;
		}
		if (parse_uri(route->nameaddr.uri.s,route->nameaddr.uri.len,&puri)<0){
			LM_ERR("failed to parse the first Path URI\n");
			goto error;
		}
		if (!puri.lr.s) {
			LM_ERR("first Path URI is not a loose-router, not supported\n");
			goto error;
		}
		if (path_use_params) {
			param_hooks_t hooks;
			param_t *params;

			if (parse_params(&(puri.params),CLASS_CONTACT,&hooks,&params)!=0){
				LM_ERR("failed to parse parameters of first hop\n");
				goto error;
			}
			/* Not interested in param body - just the hooks */
			free_params(params);

			if (hooks.contact.received) {
				uri_str.s = uri_buf;
				uri_str.len = MAX_URI_SIZE;
				if (unescape_user(&(hooks.contact.received->body), &uri_str) < 0) {
					LM_ERR("unescaping received failed\n");
					goto error;
				}
				*received = uri_str;
				LM_DBG("received is <%.*s>\n", received->len, received->s);
			}
		}
		free_rr(&route);
	}

	path->s = buf;
	path->len = p-buf;
	LM_DBG("path is <%.*s>\n", path->len, path->s);
	return 0;
error:
	if(route) free_rr(&route);
	return -1;
}
示例#11
0
int main (int argc, char* argv[]) {
    if (argc <= 2) {
        print_usage(argv);
        exit(1);
    }

    struct comp_params p = parse_params("./bin/" + string(NAME) + ".params");

    mpz_t prime;
    mpz_init_set_str(prime, "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10);



    if (!strcmp(argv[1], "setup")) {
        if (argc != 4 && argc != 5) {
            print_usage(argv);
            exit(1);
        }
        string verification_key_fn = std::string(v_dir) + argv[2];
        string proving_key_fn = std::string(p_dir) + argv[3];
        string unprocessed_vkey_fn;
        if (argc == 5) {
            unprocessed_vkey_fn = std::string(v_dir) + argv[4];
        }
        std::cout << "Creating proving/verification keys, will write to " << verification_key_fn
                  << ", " << proving_key_fn << std::endl;
        run_setup(p.n_constraints, p.n_inputs, p.n_outputs, p.n_vars, prime, verification_key_fn, proving_key_fn, unprocessed_vkey_fn);
    }
    else if (!strcmp(argv[1], "gen_input")) {
        if (argc < 3) {
            print_usage(argv);
            exit(1);
        }

        std::string input_filename = std::string(shared_dir) + argv[2];
        std::cout << "Generating inputs, will write to " << input_filename << std::endl;

        mpq_t * input_q;
        alloc_init_vec(&input_q, p.n_inputs);

        gen_input(input_q, p.n_inputs, argv);

        std::ofstream inputs_file(input_filename);

        for (int i = 0; i < p.n_inputs; i++) {
            inputs_file << input_q[i] << std::endl;
        }
        inputs_file.close();

        clear_del_vec(input_q, p.n_inputs);
    }
    else if(!strcmp(argv[1], "verify")) {
        if(argc != 6) {
            print_usage(argv);
            exit(1);
        }
        std::string verification_key_fn = std::string(v_dir) + argv[2];
        std::string inputs_fn = std::string(shared_dir) + argv[3];
        std::string outputs_fn = std::string(shared_dir) + argv[4];
        std::string proof_fn = std::string(shared_dir) + argv[5];
        verify(verification_key_fn, inputs_fn, outputs_fn, proof_fn, p.n_inputs, p.n_outputs, prime);
    }
    else {
        print_usage(argv);
        exit(1);
    }
}
示例#12
0
Datum
xslt_process(PG_FUNCTION_ARGS)
{
#ifdef USE_LIBXSLT

	text	   *doct = PG_GETARG_TEXT_P(0);
	text	   *ssheet = PG_GETARG_TEXT_P(1);
	text	   *paramstr;
	const char **params;
	xsltStylesheetPtr stylesheet = NULL;
	xmlDocPtr	doctree;
	xmlDocPtr	restree;
	xmlDocPtr	ssdoc = NULL;
	xmlChar    *resstr;
	int			resstat;
	int			reslen;

	if (fcinfo->nargs == 3)
	{
		paramstr = PG_GETARG_TEXT_P(2);
		params = parse_params(paramstr);
	}
	else
	{
		/* No parameters */
		params = (const char **) palloc(sizeof(char *));
		params[0] = NULL;
	}

	/* Setup parser */
	pgxml_parser_init();

	/* Check to see if document is a file or a literal */

	if (VARDATA(doct)[0] == '<')
		doctree = xmlParseMemory((char *) VARDATA(doct), VARSIZE(doct) - VARHDRSZ);
	else
		doctree = xmlParseFile(text_to_cstring(doct));

	if (doctree == NULL)
		xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION,
					"error parsing XML document");

	/* Same for stylesheet */
	if (VARDATA(ssheet)[0] == '<')
	{
		ssdoc = xmlParseMemory((char *) VARDATA(ssheet),
							   VARSIZE(ssheet) - VARHDRSZ);
		if (ssdoc == NULL)
		{
			xmlFreeDoc(doctree);
			xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION,
						"error parsing stylesheet as XML document");
		}

		stylesheet = xsltParseStylesheetDoc(ssdoc);
	}
	else
		stylesheet = xsltParseStylesheetFile((xmlChar *) text_to_cstring(ssheet));


	if (stylesheet == NULL)
	{
		xmlFreeDoc(doctree);
		xsltCleanupGlobals();
		xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION,
					"failed to parse stylesheet");
	}

	restree = xsltApplyStylesheet(stylesheet, doctree, params);
	resstat = xsltSaveResultToString(&resstr, &reslen, restree, stylesheet);

	xsltFreeStylesheet(stylesheet);
	xmlFreeDoc(restree);
	xmlFreeDoc(doctree);

	xsltCleanupGlobals();

	if (resstat < 0)
		PG_RETURN_NULL();

	PG_RETURN_TEXT_P(cstring_to_text_with_len((char *) resstr, reslen));
#else							/* !USE_LIBXSLT */

	ereport(ERROR,
			(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			 errmsg("xslt_process() is not available without libxslt")));
	PG_RETURN_NULL();
#endif   /* USE_LIBXSLT */
}
示例#13
0
static int xlog_log_colors_param(modparam_t type, void *val)
{
	param_t* params_list = NULL;
	param_hooks_t phooks;
	param_t *pit=NULL;
	str s;
	int level;

	if(val==NULL)
		goto error;

	s.s = (char*)val;
	s.len = strlen(s.s);

	if(s.len<=0)
		goto error;

	if(s.s[s.len-1]==';')
		s.len--;
	if (parse_params(&s, CLASS_ANY, &phooks, &params_list)<0)
		goto error;

	for (pit = params_list; pit; pit=pit->next)
	{
		if (pit->name.len==7
				&& strncasecmp(pit->name.s, "l_alert", 7)==0) {
			level = L_ALERT;
		} else if (pit->name.len==5
				&& strncasecmp(pit->name.s, "l_bug", 5)==0) {
			level = L_BUG;
		} else if (pit->name.len==7
				&& strncasecmp(pit->name.s, "l_crit2", 7)==0) {
			level = L_CRIT2;
		} else if (pit->name.len==6
				&& strncasecmp(pit->name.s, "l_crit", 6)==0) {
			level = L_CRIT;
		} else if (pit->name.len==5
				&& strncasecmp(pit->name.s, "l_err", 5)==0) {
			level = L_ERR;
		} else if (pit->name.len==6
				&& strncasecmp(pit->name.s, "l_warn", 6)==0) {
			level = L_WARN;
		} else if (pit->name.len==8
				&& strncasecmp(pit->name.s, "l_notice", 8)==0) {
			level = L_NOTICE;
		} else if (pit->name.len==6
				&& strncasecmp(pit->name.s, "l_info", 6)==0) {
			level = L_INFO;
		} else if (pit->name.len==5
				&& strncasecmp(pit->name.s, "l_dbg", 5)==0) {
			level = L_DBG;
		} else {
			LM_ERR("invalid level name %.*s\n",
					pit->name.len, pit->name.s);
			goto error;
		}
			
		if(pit->body.len!=2) {
			LM_ERR("invalid color spec for level %.*s (%.*s)\n",
					pit->name.len, pit->name.s,
					pit->body.len, pit->body.s);
			goto error;
		}
		dprint_color_update(level, pit->body.s[0], pit->body.s[1]);
	}

	if(params_list!=NULL)
		free_params(params_list);
	return 0;

error:
	if(params_list!=NULL)
		free_params(params_list);
	return -1;

}
示例#14
0
int evrexec_param(modparam_t type, void *val)
{
	param_t* params_list = NULL;
	param_hooks_t phooks;
	param_t *pit=NULL;
	evrexec_task_t *it;
	evrexec_task_t tmp;
	sr_kemi_eng_t *keng = NULL;
	str s;

	if(val==NULL)
		return -1;
	s.s = (char*)val;
	s.len = strlen(s.s);
	if(s.s[s.len-1]==';')
		s.len--;
	if (parse_params(&s, CLASS_ANY, &phooks, &params_list)<0)
		return -1;
	memset(&tmp, 0, sizeof(evrexec_task_t));
	for (pit = params_list; pit; pit=pit->next) {
		if (pit->name.len==4
				&& strncasecmp(pit->name.s, "name", 4)==0) {
			tmp.ename = pit->body;
		} else if(pit->name.len==4
				&& strncasecmp(pit->name.s, "wait", 4)==0) {
			if(tmp.wait==0) {
				if (str2int(&pit->body, &tmp.wait) < 0) {
					LM_ERR("invalid wait: %.*s\n", pit->body.len, pit->body.s);
					return -1;
				}
			}
		} else if(pit->name.len==7
				&& strncasecmp(pit->name.s, "workers", 7)==0) {
			if(tmp.workers==0) {
				if (str2int(&pit->body, &tmp.workers) < 0) {
					LM_ERR("invalid workers: %.*s\n", pit->body.len, pit->body.s);
					return -1;
				}
			}
		} else {
			LM_ERR("invalid attribute: %.*s\n", pit->body.len, pit->body.s);
			return -1;
		}
	}
	if(tmp.ename.s==NULL || tmp.ename.len<=0) {
		LM_ERR("missing or invalid name attribute\n");
		free_params(params_list);
		return -1;
	}
	/* set '\0' at the end of route name */
	tmp.ename.s[tmp.ename.len] = '\0';
	keng = sr_kemi_eng_get();
	if(keng==NULL) {
		tmp.rtid = route_get(&event_rt, tmp.ename.s);
		if(tmp.rtid == -1) {
			LM_ERR("event route not found: %.*s\n", tmp.ename.len, tmp.ename.s);
			free_params(params_list);
			return -1;
		}
	} else {
		tmp.rtid = -1;
	}

	it = (evrexec_task_t*)pkg_malloc(sizeof(evrexec_task_t));
	if(it==0) {
		LM_ERR("no more pkg memory\n");
		free_params(params_list);
		return -1;
	}
	memcpy(it, &tmp, sizeof(evrexec_task_t));
	if(it->workers==0) it->workers=1;
	it->next = _evrexec_list;
	_evrexec_list = it;
	free_params(params_list);
	return 0;
}
示例#15
0
文件: save.c 项目: SipSeb/kamailio
int save(struct sip_msg* _m, udomain_t* _d, int _cflags, str *_uri)
{
	contact_t* c;
	int st, mode;
	str aor;
	int ret;
	sip_uri_t *u;
	rr_t *route;
	struct sip_uri puri;
	param_hooks_t hooks;
	param_t *params;
	contact_t *contact;
	int use_ob = 1, use_regid = 1;
	int novariation = 0;


	u = parse_to_uri(_m);
	if(u==NULL)
		goto error;

	rerrno = R_FINE;
	ret = 1;

	if (parse_message(_m) < 0) {
		goto error;
	}

	if (check_contacts(_m, &st) > 0) {
		goto error;
	}

	if (parse_supported(_m) == 0) {
		if (!(get_supported(_m)	& F_OPTION_TAG_OUTBOUND)
				&& reg_outbound_mode == REG_OUTBOUND_REQUIRE) {
			LM_WARN("Outbound required by server and not supported by UAC\n");
			rerrno = R_OB_UNSUP;
			goto error;
		}
	}

	if (parse_require(_m) == 0) {
		if ((get_require(_m) & F_OPTION_TAG_OUTBOUND)
				&& reg_outbound_mode == REG_OUTBOUND_NONE) {
			LM_WARN("Outbound required by UAC and not supported by server\n");
			rerrno = R_OB_REQD;
			goto error;
		}
	}

	if (reg_outbound_mode != REG_OUTBOUND_NONE
			&& _m->contact && _m->contact->parsed
			&& !(parse_headers(_m, HDR_VIA2_F, 0) == -1 || _m->via2 == 0
				|| _m->via2->error != PARSE_OK)) {
		/* Outbound supported on server, and more than one Via: - not the first hop */

		if (!(parse_headers(_m, HDR_PATH_F, 0) == -1 || _m->path == 0)) {
			route = (rr_t *)0;
			if (parse_rr_body(_m->path->body.s, _m->path->body.len, &route) < 0) {
				LM_ERR("Failed to parse Path: header body\n");
				goto error;
			}
			if (parse_uri(route->nameaddr.uri.s, route->nameaddr.uri.len, &puri) < 0) {
				LM_ERR("Failed to parse Path: URI\n");
				free_rr(&route);
				goto error;
			}
			if (parse_params(&puri.params, CLASS_URI, &hooks, &params) != 0) {
				LM_ERR("Failed to parse Path: URI parameters\n");
				free_rr(&route);
				goto error;
			}
			/* Not interested in param body - just the hooks */
			free_params(params);
			if (!hooks.uri.ob) {
				/* No ;ob parameter to top Path: URI - no outbound */
				use_ob = 0;
			}
			free_rr(&route);
		} else {
			/* No Path: header - no outbound */
			use_ob = 0;

		}

		contact = ((contact_body_t *) _m->contact->parsed)->contacts;
		if (!contact) {
			LM_ERR("empty Contact:\n");
			goto error;
		}

		if ((use_ob == 0) && (reg_regid_mode == REG_REGID_OUTBOUND)) {
			if ((get_supported(_m) & F_OPTION_TAG_OUTBOUND)
					&& contact->reg_id) {
				LM_WARN("Outbound used by UAC but not supported by edge proxy\n");
				rerrno = R_OB_UNSUP_EDGE;
				goto error;
			} else {
				/* ignore ;reg-id parameter */
				use_regid = 0;
			}
		}
	}

	get_act_time();
	c = get_first_contact(_m);

	if (extract_aor((_uri)?_uri:&get_to(_m)->uri, &aor, NULL) < 0) {
		LM_ERR("failed to extract Address Of Record\n");
		goto error;
	}

	mem_only = is_cflag_set(REG_SAVE_MEM_FL)?FL_MEM:FL_NONE;
	novariation = is_cflag_set(REG_SAVE_NOVARIATION_FL)? 1:0;

	if (c == 0) {
		if (st) {
			if (star(_m, (udomain_t*)_d, &aor, &u->host) < 0) goto error;
			else ret=3;
		} else {
			if (no_contacts(_m, (udomain_t*)_d, &aor, &u->host) < 0) goto error;
			else ret=4;
		}
	} else {
		mode = is_cflag_set(REG_SAVE_REPL_FL)?1:0;
		if ((ret=add_contacts(_m, (udomain_t*)_d, &aor, mode, use_regid, novariation)) < 0)
			goto error;
		ret = (ret==0)?1:ret;
	}

	update_stat(accepted_registrations, 1);

	/* Only send reply upon request, not upon reply */
	if ((is_route_type(REQUEST_ROUTE) || is_route_type(FAILURE_ROUTE))
			&& !is_cflag_set(REG_SAVE_NORPL_FL) && (reg_send_reply(_m) < 0))
		return -1;

	if (path_enabled && path_mode != PATH_MODE_OFF) {
		reset_path_vector(_m);
	}
	return ret;
error:
	update_stat(rejected_registrations, 1);
	if (is_route_type(REQUEST_ROUTE) && !is_cflag_set(REG_SAVE_NORPL_FL) )
		reg_send_reply(_m);
    if (R_TOO_MANY == rerrno)
	    return -2; 
	/* for all other */
	return 0;
}
示例#16
0
static int
extract_reqmod_data(const char *data, SiteInfoType *si, unsigned int *eid,
		    unsigned int *pid, unsigned int *uid, unsigned int *gid) {
  int ret = -1;
  char *enc = NULL, *dec = NULL, *dummy_url = NULL;
  ParamNodeType *pl = NULL;
  const char *s, *bldata;
  size_t len_output;
  uint32_t _eid, _pid, _uid, _gid;

  enc = Strdup(data);
  if(!enc) {
    goto cleanup;
  }

  nag("Processing policy data header: %s\n", enc);

  dec = (char *)decrypt_data(poldata_key, strlen(poldata_key),
			     enc, &len_output);
  if(!dec) {
    goto cleanup;
  }
  nag("Decrypted: %s\n", dec);

  pl = parse_params(dec, "&");

#define GET_PARAM_VAL(param) \
  if(!(s = get_param_value(pl, #param, 0))) { \
    nag(#param " param not found\n"); \
    goto cleanup; \
  } \
  if(lex_u32(&s, &_ ## param)) { \
    nag("Error lexing " #param " [%s]\n", s); \
    goto cleanup; \
  }

  GET_PARAM_VAL(eid)
  GET_PARAM_VAL(pid)
  GET_PARAM_VAL(uid)
  GET_PARAM_VAL(gid)

#undef GET_PARAM_VAL

  // si
  bldata = get_param_value(pl, "bldata", 0);
  if(!decode_block_page_data(bldata, &dummy_url, si, 0)) { // returns false on error... argh!
    nag("Error decoding meta data\n");
    goto cleanup; 
  }

  *eid = _eid;
  *pid = _pid;
  *uid = _uid;
  *gid = _gid;

  ret = 0;
 cleanup:
  Free(dummy_url);
  Free(enc);
  Free(dec);
  delete_param_list(pl);
  return ret;
}
示例#17
0
static int assemble_msg(struct sip_msg* msg, struct tw_info *twi)
{
	static char     id_buf[IDBUF_LEN];
	static char     route_buffer[ROUTE_BUFFER_MAX];
	static char     append_buf[APPEND_BUFFER_MAX];
	static char     cmd_buf[CMD_BUFFER_MAX];
	static str      empty_param = {".",1};
	unsigned int      hash_index, label;
	contact_body_t*   cb=0;
	contact_t*        c=0;
	name_addr_t       na;
	rr_t*             record_route;
	struct hdr_field* p_hdr;
	param_hooks_t     hooks;
	int               l;
	char*             s, fproxy_lr;
	str               route, next_hop, append, tmp_s, body, str_uri;

	if(msg->first_line.type != SIP_REQUEST){
		LM_ERR("called for something else then a SIP request\n");
		goto error;
	}

	/* parse all -- we will need every header field for a UAS */
	if ( parse_headers(msg, HDR_EOH_F, 0)==-1) {
		LM_ERR("parse_headers failed\n");
		goto error;
	}

	/* find index and hash; (the transaction can be safely used due 
	 * to refcounting till script completes) */
	if( t_get_trans_ident(msg,&hash_index,&label) == -1 ) {
		LM_ERR("t_get_trans_ident failed\n");
		goto error;
	}

	 /* parse from header */
	if (msg->from->parsed==0 && parse_from_header(msg)<0 ) {
		LM_ERR("failed to parse <From:> header\n");
		goto error;
	}

	/* parse the RURI (doesn't make any malloc) */
	msg->parsed_uri_ok = 0; /* force parsing */
	if (parse_sip_msg_uri(msg)<0) {
		LM_ERR("uri has not been parsed\n");
		goto error;
	}

	/* parse contact header */
	str_uri.s = 0;
	str_uri.len = 0;
	if(msg->contact) {
		if (msg->contact->parsed==0 && parse_contact(msg->contact)<0) {
			LM_ERR("failed to parse <Contact:> header\n");
			goto error;
		}
		cb = (contact_body_t*)msg->contact->parsed;
		if(cb && (c=cb->contacts)) {
			str_uri = c->uri;
			if (find_not_quoted(&str_uri,'<')) {
				parse_nameaddr(&str_uri,&na);
				str_uri = na.uri;
			}
		}
	}

	/* str_uri is taken from caller's contact or from header
	 * for backwards compatibility with pre-3261 (from is already parsed)*/
	if(!str_uri.len || !str_uri.s)
		str_uri = get_from(msg)->uri;

	/* parse Record-Route headers */
	route.s = s = route_buffer; route.len = 0;
	fproxy_lr = 0;
	next_hop = empty_param;

	p_hdr = msg->record_route;
	if(p_hdr) {
		if (p_hdr->parsed==0 && parse_rr(p_hdr)!=0 ) {
			LM_ERR("failed to parse 'Record-Route:' header\n");
			goto error;
		}
		record_route = (rr_t*)p_hdr->parsed;
	} else {
		record_route = 0;
	}

	if( record_route ) {
		if ( (tmp_s.s=find_not_quoted(&record_route->nameaddr.uri,';'))!=0 &&
		tmp_s.s+1!=record_route->nameaddr.uri.s+
		record_route->nameaddr.uri.len) {
			/* Parse all parameters */
			tmp_s.len = record_route->nameaddr.uri.len - (tmp_s.s-
				record_route->nameaddr.uri.s);
			if (parse_params( &tmp_s, CLASS_URI, &hooks, 
			&record_route->params) < 0) {
				LM_ERR("failed to parse record route uri params\n");
				goto error;
			}
			fproxy_lr = (hooks.uri.lr != 0);
			LM_DBG("record_route->nameaddr.uri: %.*s\n",
				record_route->nameaddr.uri.len,record_route->nameaddr.uri.s);
			if(fproxy_lr){
				LM_DBG("first proxy has loose routing\n");
				copy_route(s,route.len,record_route->nameaddr.uri.s,
					record_route->nameaddr.uri.len);
			}
		}
		for(p_hdr = p_hdr->next;p_hdr;p_hdr = p_hdr->next) {
			/* filter out non-RR hdr and empty hdrs */
			if( (p_hdr->type!=HDR_RECORDROUTE_T) || p_hdr->body.len==0)
				continue;

			if(p_hdr->parsed==0 && parse_rr(p_hdr)!=0 ){
				LM_ERR("failed to parse <Record-route:> header\n");
				goto error;
			}
			for(record_route=p_hdr->parsed; record_route;
				record_route=record_route->next){
				LM_DBG("record_route->nameaddr.uri: <%.*s>\n",
					record_route->nameaddr.uri.len,
					record_route->nameaddr.uri.s);
				copy_route(s,route.len,record_route->nameaddr.uri.s,
					record_route->nameaddr.uri.len);
			}
		}

		if(!fproxy_lr){
			copy_route(s,route.len,str_uri.s,str_uri.len);
			str_uri = ((rr_t*)msg->record_route->parsed)->nameaddr.uri;
		} else {
			next_hop = ((rr_t*)msg->record_route->parsed)->nameaddr.uri;
		}
	}

	LM_DBG("calculated route: %.*s\n",route.len,route.len ? route.s : "");
	LM_DBG("next r-uri: %.*s\n",str_uri.len,str_uri.len ? str_uri.s : "");

	if ( REQ_LINE(msg).method_value==METHOD_INVITE || 
	(twi->append && twi->append->add_body) ) {
		/* get body */
		if( (body.s = get_body(msg)) == 0 ){
			LM_ERR("get_body failed\n");
			goto error;
		}
		body.len = msg->len - (body.s - msg->buf);
	} else {
		body = empty_param;
	}

	/* flags & additional headers */
	append.s = s = append_buf;
	if (sizeof(flag_t)*2+12+1 >= APPEND_BUFFER_MAX) {
		LM_ERR("buffer overflow while copying flags\n");
		goto error;
	}
	append_str(s,"P-MsgFlags: ",12);
	l = APPEND_BUFFER_MAX - (12+1); /* include trailing `\n'*/

	if (int2reverse_hex(&s, &l, (int)msg->msg_flags) == -1) {
		LM_ERR("buffer overflow while copying optional header\n");
		goto error;
	}
	append_chr(s,'\n');

	if ( twi->append && ((s=append2buf( s, APPEND_BUFFER_MAX-(s-append.s), msg,
	twi->append->elems))==0) )
		goto error;

	/* body separator */
	append_chr(s,'.');
	append.len = s-append.s;

	eol_line(1).s = s = cmd_buf;
	if(twi->action.len+12 >= CMD_BUFFER_MAX){
		LM_ERR("buffer overflow while copying command name\n");
		goto error;
	}
	append_str(s,"sip_request.",12);
	append_str(s,twi->action.s,twi->action.len);
	eol_line(1).len = s-eol_line(1).s;

	eol_line(2)=REQ_LINE(msg).method;     /* method type */
	eol_line(3)=msg->parsed_uri.user;     /* user from r-uri */
	eol_line(4)=msg->parsed_uri.host;     /* domain */

	eol_line(5)=msg->rcv.bind_address->address_str; /* dst ip */

	eol_line(6)=msg->rcv.dst_port==SIP_PORT ?
			empty_param : msg->rcv.bind_address->port_no_str; /* port */

	/* r_uri ('Contact:' for next requests) */
	eol_line(7)=*GET_RURI(msg);

	/* r_uri for subsequent requests */
	eol_line(8)=str_uri.len?str_uri:empty_param;

	eol_line(9)=get_from(msg)->body;		/* from */
	eol_line(10)=msg->to->body;			/* to */
	eol_line(11)=msg->callid->body;		/* callid */
	eol_line(12)=get_from(msg)->tag_value;	/* from tag */
	eol_line(13)=get_to(msg)->tag_value;	/* to tag */
	eol_line(14)=get_cseq(msg)->number;	/* cseq number */

	eol_line(15).s=id_buf;       /* hash:label */
	s = int2str(hash_index, &l);
	if (l+1>=IDBUF_LEN) {
		LM_ERR("too big hash\n");
		goto error;
	}
	memcpy(id_buf, s, l);
	id_buf[l]=':';
	eol_line(15).len=l+1;
	s = int2str(label, &l);
	if (l+1+eol_line(15).len>=IDBUF_LEN) {
		LM_ERR("too big label\n");
		goto error;
	}
	memcpy(id_buf+eol_line(15).len, s, l);
	eol_line(15).len+=l;

	eol_line(16) = route.len ? route : empty_param;
	eol_line(17) = next_hop;
	eol_line(18) = append;
	eol_line(19) = body;

	/* success */
	return 1;
error:
	/* 0 would lead to immediate script exit -- -1 returns
	 * with 'false' to script processing */
	return -1;
}
示例#18
0
/*
 * Get number portability parameter from Request-Line
 * param msg SIP message
 * param rn Routing number
 * param rnbufsize Size of rn buffer
 * param cic Carrier identification code
 * param cicbufsize Size of cic buffer
 * param npdi NP database dip indicator
 * return 0 success, 1 not use NP or without NP parameters, -1 failure
 */
int ospGetNpParameters(
    struct sip_msg* msg,
    char* rn,
    int rnbufsize,
    char* cic,
    int cicbufsize,
    int* npdi)
{
    str sv;
    param_hooks_t phooks;
    param_t* params = NULL;
    param_t* pit;
    int result = -1;

    if (((rn != NULL) && (rnbufsize > 0)) && ((cic != NULL) && (cicbufsize > 0)) && (npdi != NULL)) {
        rn[0] = '\0';
        cic[0] = '\0';
        *npdi = 0;

        if (_osp_use_np != 0) {
            if (parse_sip_msg_uri(msg) >= 0) {
                switch (msg->parsed_uri.type) {
                case TEL_URI_T:
                case TELS_URI_T:
                    sv = msg->parsed_uri.params;
                    break;
                case ERROR_URI_T:
                case SIP_URI_T:
                case SIPS_URI_T:
                default:
                    sv = msg->parsed_uri.user;
                    break;
                }
                parse_params(&sv, CLASS_ANY, &phooks, &params);
                for (pit = params; pit; pit = pit->next) {
                    if ((pit->name.len == OSP_RN_SIZE) &&
                        (strncasecmp(pit->name.s, OSP_RN_NAME, OSP_RN_SIZE) == 0) &&
                        (rn[0] == '\0'))
                    {
                        ospCopyStrToBuffer(&pit->body, rn, rnbufsize);
                    } else if ((pit->name.len == OSP_CIC_SIZE) &&
                        (strncasecmp(pit->name.s, OSP_CIC_NAME, OSP_CIC_SIZE) == 0) &&
                        (cic[0] == '\0'))
                    {
                        ospCopyStrToBuffer(&pit->body, cic, cicbufsize);
                    } else if ((pit->name.len == OSP_NPDI_SIZE) &&
                        (strncasecmp(pit->name.s, OSP_NPDI_NAME, OSP_NPDI_SIZE) == 0))
                    {
                        *npdi = 1;
                    }
                }
                if (params != NULL) {
                    free_params(params);
                }
                if ((rn[0] != '\0') || (cic[0] != '\0') || (*npdi != 0)) {
                    result = 0;
                } else {
                    LM_DBG("without number portability parameters\n");
                    result = 1;
                }
            } else {
                LM_ERR("failed to parse Request-Line URI\n");
            }
        } else {
            LM_DBG("do not use number portability\n");
            result = 1;
        }
    } else {
        LM_ERR("bad parameters to parse number portability parameters\n");
    }

    return result;
}
示例#19
0
文件: main.c 项目: epowers/palacios
/**
 * This is the architecture-independent kernel entry point. Before it is
 * called, architecture-specific code has done the bare minimum initialization
 * necessary. This function initializes the kernel and its various subsystems.
 * It calls back to architecture-specific code at several well defined points,
 * which all architectures must implement (e.g., setup_arch()).
 */
void
start_kernel()
{
	unsigned int cpu;
	unsigned int timeout;

	/*
 	 * Parse the kernel boot command line.
 	 * This is where boot-time configurable variables get set,
 	 * e.g., the ones with param() and driver_param() specifiers.
 	 */
	parse_params(lwk_command_line);

	/*
 	 * Initialize the console subsystem.
 	 * printk()'s will be visible after this.
 	 */
	console_init();

	/*
	 * Hello, Dave.
	 */
	printk(lwk_banner);
	printk(KERN_DEBUG "%s\n", lwk_command_line);

	/*
	 * Do architecture specific initialization.
	 * This detects memory, CPUs, etc.
	 */
	setup_arch();

	/*
	 * Initialize the kernel memory subsystem. Up until now, the simple
	 * boot-time memory allocator (bootmem) has been used for all dynamic
	 * memory allocation. Here, the bootmem allocator is destroyed and all
	 * of the free pages it was managing are added to the kernel memory
	 * pool (kmem) or the user memory pool (umem).
	 *
	 * After this point, any use of the bootmem allocator will cause a
	 * kernel panic. The normal kernel memory subsystem API should be used
	 * instead (e.g., kmem_alloc() and kmem_free()).
	 */
	mem_subsys_init();

	/*
 	 * Initialize the address space management subsystem.
 	 */
	aspace_subsys_init();

	/*
 	 * Initialize the task management subsystem.
 	 */
	task_subsys_init();

	/*
 	 * Initialize the task scheduling subsystem.
 	 */
	sched_subsys_init();

	/*
 	 * Initialize the task scheduling subsystem.
 	 */
	timer_subsys_init();

	/*
	 * Boot all of the other CPUs in the system, one at a time.
	 */
	printk(KERN_INFO "Number of CPUs detected: %d\n", num_cpus());
	for_each_cpu_mask(cpu, cpu_present_map) {
		/* The bootstrap CPU (that's us) is already booted. */
		if (cpu == 0) {
			cpu_set(cpu, cpu_online_map);
			continue;
		}

		printk(KERN_DEBUG "Booting CPU %u.\n", cpu);
		arch_boot_cpu(cpu);

		/* Wait for ACK that CPU has booted (5 seconds max). */
		for (timeout = 0; timeout < 50000; timeout++) {
			if (cpu_isset(cpu, cpu_online_map))
				break;
			udelay(100);
		}

		if (!cpu_isset(cpu, cpu_online_map))
			panic("Failed to boot CPU %d.\n", cpu);
	}

#ifdef CONFIG_V3VEE
	v3vee_run_vmm();
	printk( "%s: VMM returned.  We're spinning\n", __func__ );
	while(1) { asm( "hlt" ); }
#else
	/*
	 * Start up user-space...
	 */
	printk(KERN_INFO "Loading initial user-level task (init_task)...\n");
	int status;
	if ((status = create_init_task()) != 0)
		panic("Failed to create init_task (status=%d).", status);

	schedule();  /* This should not return */
	BUG();
#endif
}
示例#20
0
/*
 * Get operator name from Request-Line
 * param msg SIP message
 * param type Operator name type
 * param name Operator name buffer
 * param namebufsize Size of name buffer
 * return 0 success, 1 not use NP or without operator name, -1 failure
 */
int ospGetOperatorName(
    struct sip_msg* msg,
    OSPE_OPERATOR_NAME type,
    char* name,
    int namebufsize)
{
    str sv;
    param_hooks_t phooks;
    param_t* params = NULL;
    param_t* pit;
    int result = -1;

    if (((name != NULL) && (namebufsize > 0))) {
        name[0] = '\0';

        if (_osp_use_np != 0) {
            if (parse_sip_msg_uri(msg) >= 0) {
                switch (msg->parsed_uri.type) {
                case TEL_URI_T:
                case TELS_URI_T:
                    sv = msg->parsed_uri.params;
                    break;
                case ERROR_URI_T:
                case SIP_URI_T:
                case SIPS_URI_T:
                default:
                    sv = msg->parsed_uri.user;
                    break;
                }
                parse_params(&sv, CLASS_ANY, &phooks, &params);
                for (pit = params; pit; pit = pit->next) {
                    switch (type) {
                    case OSPC_OPNAME_SPID:
                        if ((pit->name.len == OSP_SPID_SIZE) &&
                            (strncasecmp(pit->name.s, OSP_SPID_NAME, OSP_SPID_SIZE) == 0) &&
                            (name[0] == '\0'))
                        {
                            ospCopyStrToBuffer(&pit->body, name, namebufsize);
                        }
                        break;
                    case OSPC_OPNAME_OCN:
                        if ((pit->name.len == OSP_OCN_SIZE) &&
                            (strncasecmp(pit->name.s, OSP_OCN_NAME, OSP_OCN_SIZE) == 0) &&
                            (name[0] == '\0'))
                        {
                            ospCopyStrToBuffer(&pit->body, name, namebufsize);
                        }
                        break;
                    case OSPC_OPNAME_SPN:
                        if ((pit->name.len == OSP_SPN_SIZE) &&
                            (strncasecmp(pit->name.s, OSP_SPN_NAME, OSP_SPN_SIZE) == 0) &&
                            (name[0] == '\0'))
                        {
                            ospCopyStrToBuffer(&pit->body, name, namebufsize);
                        }
                        break;
                    case OSPC_OPNAME_ALTSPN:
                        if ((pit->name.len == OSP_ALTSPN_SIZE) &&
                            (strncasecmp(pit->name.s, OSP_ALTSPN_NAME, OSP_ALTSPN_SIZE) == 0) &&
                            (name[0] == '\0'))
                        {
                            ospCopyStrToBuffer(&pit->body, name, namebufsize);
                        }
                        break;
                    case OSPC_OPNAME_MCC:
                        if ((pit->name.len == OSP_MCC_SIZE) &&
                            (strncasecmp(pit->name.s, OSP_MCC_NAME, OSP_MCC_SIZE) == 0) &&
                            (name[0] == '\0'))
                        {
                            ospCopyStrToBuffer(&pit->body, name, namebufsize);
                        }
                        break;
                    case OSPC_OPNAME_MNC:
                        if ((pit->name.len == OSP_MNC_SIZE) &&
                            (strncasecmp(pit->name.s, OSP_MNC_NAME, OSP_MNC_SIZE) == 0) &&
                            (name[0] == '\0'))
                        {
                            ospCopyStrToBuffer(&pit->body, name, namebufsize);
                        }
                        break;
                    default:
                        break;
                    }
                }
                if (params != NULL) {
                    free_params(params);
                }
                if (name[0] != '\0') {
                    result = 0;
                } else {
                    LM_DBG("without operator name\n");
                    result = 1;
                }
            } else {
                LM_ERR("failed to parse Request-Line URI\n");
            }
        } else {
            LM_DBG("do not use number portability\n");
            result = 1;
        }
    } else {
        LM_ERR("bad parameters to parse operator name\n");
    }

    return result;
}
示例#21
0
文件: strings.c 项目: smarter/thor
enc_params *parse_config_params(int argc, char **argv)
{
  FILE *infile;
  param_list list;
  enc_params *params;
  char *default_argv[MAX_PARAMS*2];
  int default_argc;
  int i;

  params = (enc_params *)malloc(sizeof(enc_params));
  if (params == NULL)
  {
    fprintf(stderr, "Memory allocation failed\n");
    return NULL;
  }

  memset(params, 0, sizeof(enc_params));
  memset(&list, 0, sizeof(param_list));

  add_param_to_list(&list, "-cf",                   NULL, ARG_FILENAME, NULL);
  add_param_to_list(&list, "-if",                   NULL, ARG_FILENAME, &params->infilestr);
  add_param_to_list(&list, "-ph",                    "0", ARG_INTEGER,  &params->file_headerlen);
  add_param_to_list(&list, "-fh",                    "0", ARG_INTEGER,  &params->frame_headerlen);
  add_param_to_list(&list, "-of",                   NULL, ARG_FILENAME, &params->outfilestr);
  add_param_to_list(&list, "-rf",                   NULL, ARG_FILENAME, &params->reconfilestr);
  add_param_to_list(&list, "-stat",                 NULL, ARG_FILENAME, &params->statfilestr);
  add_param_to_list(&list, "-n",                   "600", ARG_INTEGER,  &params->num_frames);
  add_param_to_list(&list, "-skip",                  "0", ARG_INTEGER,  &params->skip);
  add_param_to_list(&list, "-width",              "1920", ARG_INTEGER,  &params->width);
  add_param_to_list(&list, "-height",             "1080", ARG_INTEGER,  &params->height);
  add_param_to_list(&list, "-qp",                   "32", ARG_INTEGER,  &params->qp);  
  add_param_to_list(&list, "-f",                    "60", ARG_FLOAT,    &params->frame_rate);
  add_param_to_list(&list, "-lambda_coeffI",       "1.0", ARG_FLOAT,    &params->lambda_coeffI);
  add_param_to_list(&list, "-lambda_coeffP",       "1.0", ARG_FLOAT,    &params->lambda_coeffP);
  add_param_to_list(&list, "-lambda_coeffB",       "1.0", ARG_FLOAT,    &params->lambda_coeffB);
  add_param_to_list(&list, "-lambda_coeffB0",      "1.0", ARG_FLOAT,    &params->lambda_coeffB0);
  add_param_to_list(&list, "-lambda_coeffB1",      "1.0", ARG_FLOAT,    &params->lambda_coeffB1);
  add_param_to_list(&list, "-lambda_coeffB2",      "1.0", ARG_FLOAT,    &params->lambda_coeffB2);
  add_param_to_list(&list, "-lambda_coeffB3",      "1.0", ARG_FLOAT,    &params->lambda_coeffB3);
  add_param_to_list(&list, "-early_skip_thr",      "0.0", ARG_FLOAT,    &params->early_skip_thr);
  add_param_to_list(&list, "-enable_tb_split",       "0", ARG_INTEGER,  &params->enable_tb_split);
  add_param_to_list(&list, "-enable_pb_split",       "0", ARG_INTEGER,  &params->enable_pb_split);
  add_param_to_list(&list, "-max_num_ref",           "1", ARG_INTEGER,  &params->max_num_ref);
  add_param_to_list(&list, "-HQperiod",              "1", ARG_INTEGER,  &params->HQperiod);
  add_param_to_list(&list, "-num_reorder_pics",      "0", ARG_INTEGER,  &params->num_reorder_pics);
  add_param_to_list(&list, "-dyadic_coding",         "1", ARG_INTEGER,  &params->dyadic_coding);
  add_param_to_list(&list, "-interp_ref",            "0", ARG_INTEGER,  &params->interp_ref);
  add_param_to_list(&list, "-dqpP",                  "0", ARG_INTEGER,  &params->dqpP);
  add_param_to_list(&list, "-dqpB",                  "0", ARG_INTEGER,  &params->dqpB);
  add_param_to_list(&list, "-dqpB0",                 "0", ARG_INTEGER,  &params->dqpB0);
  add_param_to_list(&list, "-dqpB1",                 "0", ARG_INTEGER,  &params->dqpB1);
  add_param_to_list(&list, "-dqpB2",                 "0", ARG_INTEGER,  &params->dqpB2);
  add_param_to_list(&list, "-dqpB3",                 "0", ARG_INTEGER,  &params->dqpB3);
  add_param_to_list(&list, "-mqpP",                "1.0", ARG_FLOAT,    &params->mqpP);
  add_param_to_list(&list, "-mqpB",                "1.0", ARG_FLOAT,    &params->mqpB);
  add_param_to_list(&list, "-mqpB0",               "1.0", ARG_FLOAT,    &params->mqpB0);
  add_param_to_list(&list, "-mqpB1",               "1.0", ARG_FLOAT,    &params->mqpB1);
  add_param_to_list(&list, "-mqpB2",               "1.0", ARG_FLOAT,    &params->mqpB2);
  add_param_to_list(&list, "-mqpB3",               "1.0", ARG_FLOAT,    &params->mqpB3);
  add_param_to_list(&list, "-dqpI",                  "0", ARG_INTEGER,  &params->dqpI);
  add_param_to_list(&list, "-intra_period",          "0", ARG_INTEGER,  &params->intra_period);
  add_param_to_list(&list, "-intra_rdo",             "0", ARG_INTEGER,  &params->intra_rdo);
  add_param_to_list(&list, "-rdoq",                  "0", ARG_INTEGER,  &params->rdoq);
  add_param_to_list(&list, "-max_delta_qp",          "0", ARG_INTEGER,  &params->max_delta_qp);
  add_param_to_list(&list, "-encoder_speed",         "0", ARG_INTEGER,  &params->encoder_speed);
  add_param_to_list(&list, "-sync",                  "0", ARG_INTEGER,  &params->sync);
  add_param_to_list(&list, "-deblocking",            "1", ARG_INTEGER,  &params->deblocking);
  add_param_to_list(&list, "-clpf",                  "1", ARG_INTEGER,  &params->clpf);
  add_param_to_list(&list, "-snrcalc",               "1", ARG_INTEGER,  &params->snrcalc);
  add_param_to_list(&list, "-use_block_contexts",    "0", ARG_INTEGER,  &params->use_block_contexts);
  add_param_to_list(&list, "-enable_bipred",         "0", ARG_INTEGER,  &params->enable_bipred);

  /* Generate "argv" and "argc" for default parameters */
  default_argc = 1;
  for (i = 0; i < list.num; i++)
  {
    if (list.params[i].default_string != NULL)
    {
      default_argv[default_argc++] = list.params[i].name;
      default_argv[default_argc++] = list.params[i].default_string;
    }
  }

  /* Parse default parameters */
  parse_params(default_argc, default_argv, params, &list);

  /* Parse parameters from command line and config files */
  if (parse_params(argc, argv, params, &list) < 0)
    return NULL;

  /* Check if input file is y4m and if so use its geometry */
  if ((infile = fopen(params->infilestr, "rb"))) {
    char buf[256];
    int len = fread(buf, 1, sizeof(buf), infile);
    int pos = 10;
    int num, den;
    buf[255] = 0;
    if (!strncmp(buf, "YUV4MPEG2 ", 10)) {
      char *end;
      while (pos < len && buf[pos] != '\n') {
          switch (buf[pos++]) {
          case 'W':
            params->width = strtol(buf+pos, &end, 10);
            pos = end-buf+1;
            break;
          case 'H':
            params->height = strtol(buf+pos, &end, 10);
            pos = end-buf+1;
            break;
          case 'F':
            den = strtol(buf+pos, &end, 10);
            pos = end-buf+1;
            num = strtol(buf+pos, &end, 10);
            pos = end-buf+1;
            params->frame_rate = (double)den/num;
            break;
          case 'I':
            if (buf[pos] != 'p') {
              fprintf(stderr, "Only progressive input supported\n");
              return NULL;
            }
            break;
          case 'C':
            if (strcmp(buf+pos, "C420")) {
            }
            /* Fallthrough */
          case 'A': /* Ignored */
          case 'X':
          default:
            while (buf[pos] != ' ' && buf[pos] != '\n' && pos < len)
              pos++;
            break;
          }
        }
        if (strncmp(buf+pos, "\nFRAME\n", 7)) {
          fprintf(stderr, "Corrupt Y4M file\n");
          return NULL;
        }
        params->file_headerlen = pos + 1;
        params->frame_headerlen = 6;
    }
    fclose(infile);
  }
  return params;
}
示例#22
0
/*
 * Find if Request URI has a given parameter with matching value
 */
int uri_param_2(struct sip_msg* _msg, char* _param, char* _value)
{
	str param, value, t;

	param_hooks_t hooks;
	param_t* params;


	if (get_str_fparam(&param, _msg, (fparam_t *)_param) < 0) {
		ERR("is_user: failed to recover 1st parameter.\n");
		return -1;
	}
	if (_value) {
		if (get_str_fparam(&value, _msg, (fparam_t *)_value) < 0) {
			ERR("is_user: failed to recover 1st parameter.\n");
			return -1;
		}
	} else {
	    value.s = 0;
	}

	if (parse_sip_msg_uri(_msg) < 0) {
	        LOG(L_ERR, "uri_param(): ruri parsing failed\n");
	        return -1;
	}

	t = _msg->parsed_uri.params;

	if (parse_params(&t, CLASS_ANY, &hooks, &params) < 0) {
	        LOG(L_ERR, "uri_param(): ruri parameter parsing failed\n");
	        return -1;
	}

	while (params) {
		if ((params->name.len == param.len) &&
		    (strncmp(params->name.s, param.s, param.len) == 0)) {
			if (value.s) {
				if ((value.len == params->body.len) &&
				    strncmp(value.s, params->body.s, value.len) == 0) {
					goto ok;
				} else {
					goto nok;
				}
			} else {
				if (params->body.len > 0) {
					goto nok;
				} else {
					goto ok;
				}
			}
		} else {
			params = params->next;
		}
	}
	
nok:
	free_params(params);
	return -1;

ok:
	free_params(params);
	return 1;
}
示例#23
0
int event_parser(char* s, int len, event_t* e)
{
	int i;
	str tmp;
	char* end;
	param_hooks_t* phooks = NULL;
	enum pclass pclass = CLASS_ANY;

	if (e == NULL) {
		ERR("event_parser: Invalid parameter value\n");
		return -1;
	}

	tmp.s = s;
	tmp.len = len;
	trim_leading(&tmp);

	if (tmp.len == 0) {
		LOG(L_ERR, "event_parser: Empty body\n");
		return -1;
	}

	e->name.s = tmp.s;
	end = skip_token(tmp.s, tmp.len);
	e->name.len = end - tmp.s;

	e->type = EVENT_OTHER;
	for(i = 0; events[i].name.len; i++) {
		if (e->name.len == events[i].name.len &&
			!strncasecmp(e->name.s, events[i].name.s, e->name.len)) {
			e->type = events[i].type;
			break;
		}
	}

	tmp.len -= end - tmp.s;
	tmp.s = end;
	trim_leading(&tmp);

	e->params.list = NULL;
	
	if (tmp.len && (tmp.s[0] == ';')) {
		/* Shift the semicolon and skip any leading whitespace, this is needed
		 * for parse_params to work correctly. */
		tmp.s++; tmp.len--;
		trim_leading(&tmp);
		if (!tmp.len) return 0;

		/* We have parameters to parse */
		if (e->type == EVENT_DIALOG) {
			pclass = CLASS_EVENT_DIALOG;
			phooks = (param_hooks_t*)&e->params.hooks;
		}

		if (parse_params(&tmp, pclass, phooks, &e->params.list) < 0) {
			ERR("event_parser: Error while parsing parameters parameters\n");
			return -1;
		}
	}
	return 0;
}
示例#24
0
/*
 * Parse contacts in a Contact HF
 */
int parse_contacts(str* _s, contact_t** _c)
{
	contact_t* c;
	contact_t* last;
	param_hooks_t hooks;

	last = NULL;

	while(1) {
		/* Allocate and clear contact structure */
		c = (contact_t*)pkg_malloc(sizeof(contact_t));
		if (c == 0) {
			LM_ERR("no pkg memory left\n");
			goto error;
		}
		memset(c, 0, sizeof(contact_t));

		c->name.s = _s->s;

		if (skip_name(_s) < 0) {
			LM_ERR("failed to skip name part\n");
			goto error;
		}

		c->uri.s = _s->s;
		c->name.len = _s->s - c->name.s;
		trim_trailing(&c->name);

		/* Find the end of the URI */
		if (skip_uri(_s) < 0) {
			LM_ERR("failed to skip URI\n");
			goto error;
		}

		c->uri.len = _s->s - c->uri.s; /* Calculate URI length */
		trim_trailing(&(c->uri));    /* Remove any trailing spaces from URI */

		/* Remove <> if any */
		if ((c->uri.len >= 2) && (c->uri.s[0] == '<') &&
		(c->uri.s[c->uri.len - 1] == '>')) {
			c->uri.s++;
			c->uri.len -= 2;
		}

		trim(&c->uri);

		/* RFC3261 grammar enforces the existance of an URI */
		if (c->uri.len==0) {
			LM_ERR("Empty URI found in contact body\n");
			goto error;
		}

		if (_s->len == 0) goto ok;

		if (_s->s[0] == ';') {         /* Contact parameter found */
			_s->s++;
			_s->len--;
			trim_leading(_s);

			if (_s->len == 0) {
				LM_ERR("failed to parse params\n");
				goto error;
			}

			if (parse_params(_s, CLASS_CONTACT, &hooks, &c->params) < 0) {
				LM_ERR("failed to parse contact parameters\n");
				goto error;
			}

			c->q = hooks.contact.q;
			c->expires = hooks.contact.expires;
			c->received = hooks.contact.received;
			c->methods = hooks.contact.methods;
			c->instance = hooks.contact.instance;

			if (_s->len == 0) goto ok;
		}

		/* Next character is comma */
		c->len = _s->s - c->name.s;
		_s->s++;
		_s->len--;
		trim_leading(_s);

		if (_s->len == 0) {
			LM_ERR("text after comma missing\n");
			goto error;
		}

		if (last) {last->next=c;} else {*_c = c;}
		last = c;
	}

 error:
	if (c) pkg_free(c);
	free_contacts(_c); /* Free any contacts created so far */
	return -1;

 ok:
	c->len = _s->s - c->name.s;
	if (last) {last->next=c;} else {*_c = c;}
	last = c;
	return 0;
}
示例#25
0
文件: isx.c 项目: habanero-rice/hclib
int main(const int argc,  char ** argv)
{
  shmem_init();

  my_bucket_keys = (KEY_TYPE *)shmem_malloc(KEY_BUFFER_SIZE * sizeof(KEY_TYPE));
  assert(my_bucket_keys);
  // fprintf(stderr, "PE %d allocating %llu bytes at %p\n", shmem_my_pe(),
  //         KEY_BUFFER_SIZE * sizeof(KEY_TYPE), my_bucket_keys);

  #ifdef EXTRA_STATS
  _timer_t total_time;
  if(shmem_my_pe() == 0) {
    printf("\n-----\nmkdir timedrun fake\n\n");
    timer_start(&total_time);
  }
#endif

  init_shmem_sync_array(pSync); 

  char * log_file = parse_params(argc, argv);

  int err = bucket_sort();

  log_times(log_file);

  #ifdef EXTRA_STATS
  if(shmem_my_pe() == 0) {
    just_timer_stop(&total_time);
    double tTime = ( total_time.stop.tv_sec - total_time.start.tv_sec ) + ( total_time.stop.tv_nsec - total_time.start.tv_nsec )/1E9;
    avg_time *= 1000;
    avg_time_all2all *= 1000;

    printf("\n============================ MMTk Statistics Totals ============================\n");
    if(NUM_ITERATIONS == 1) { //TODO: fix time calculation below for more number of iterations
      printf("time.mu\tt.ATA_KEYS\tt.MAKE_INPUT\tt.COUNT_BUCKET_SIZES\tt.BUCKETIZE\tt.COMPUTE_OFFSETS\tt.LOCAL_SORT\tBARRIER_AT_START\tBARRIER_AT_EXCHANGE\tBARRIER_AT_END\tnWorkers\tnPEs\n");
      double TIMES[TIMER_NTIMERS];
      memset(TIMES, 0x00, sizeof(double) * TIMER_NTIMERS);
      for(int i=0; i<NUM_PES; i++) {
        for(int t = 0; t < TIMER_NTIMERS; ++t){
          if(timers[t].all_times != NULL){
            TIMES[t] += timers[t].all_times[i];
          }
        }
      }
      for(int t = 0; t < TIMER_NTIMERS; ++t){
        printf("%.3f\t", (TIMES[t]/NUM_PES)*1000);
      }
      printf("1\t%d\n",NUM_PES);
      printf("Total time: %.3f\n",(TIMES[0]/NUM_PES)*1000);
    }
    else {
      printf("time.mu\ttimeAll2All\tnWorkers\tnPEs\n");
      printf("%.3f\t%.3f\t1\t%d\n",avg_time,avg_time_all2all,NUM_PES);
      printf("Total time: %.3f\n",avg_time);
    }
    printf("------------------------------ End MMTk Statistics -----------------------------\n");
    printf("===== TEST PASSED in %.3f msec =====\n",(tTime*1000));
  }
#endif

  shmem_finalize();
  return err;
}
示例#26
0
int main(int argc __unused, char **argv)
{
	int fd;
	struct usbmon_packet_1 hdrb;
	struct usbmon_packet_1 *hdr;
	struct usbmon_get_arg getb;
	enum { MFETCH_NM = 3 };
	unsigned int offs[MFETCH_NM];
	unsigned int off;
	struct usbmon_mfetch_arg mfb;
	unsigned char *data_buff;
	unsigned int toflush;
	int i;
	int rc;

	if (sizeof(struct usbmon_packet) != 48) {
		extern void usbmon_packet_size_is_bolixed(void);
		usbmon_packet_size_is_bolixed();	/* link-time error */
	}
	if (sizeof(struct usbmon_packet_1) != 64) {
		extern void usbmon_packet_1_size_is_bolixed(void);
		usbmon_packet_1_size_is_bolixed();	/* link-time error */
	}

	parse_params(&par, argv+1);

	/*
	 * Two reasons to do this:
	 * 1. Reduce weird error messages.
	 * 2. If we create device nodes, we want them owned by root.
	 */
	if (geteuid() != 0) {
		fprintf(stderr, TAG ": Must run as root\n");
		exit(1);
	}

	if ((fd = open(par.devname, O_RDWR)) == -1) {
		if (errno == ENOENT) {
			make_device(&par);
			fd = open(par.devname, O_RDWR);
		}
		if (fd == -1) {
			if (errno == ENODEV && par.ifnum == 0) {
				fprintf(stderr, TAG
				    ": Can't open pseudo-bus zero at %s"
				    " (probably not supported by kernel)\n",
				    par.devname);
			} else {
				fprintf(stderr, TAG ": Can't open %s: %s\n",
				    par.devname, strerror(errno));
			}
			exit(1);
		}
	}


	if (par.api == API_B1M) {
		rc = ioctl(fd, MON_IOCQ_RING_SIZE, 0);
		if (rc == -1) {
			fprintf(stderr, TAG ": Cannot get ring size: %s\n",
			    strerror(errno));
			exit(1);
		}
		printf("Ring size: %d\n", rc); /* P3 */
		par.map_size = rc;
		data_buff = mmap(0, par.map_size, PROT_READ, MAP_SHARED, fd, 0);
		if (data_buff == MAP_FAILED) {
			fprintf(stderr, TAG ": Cannot mmap: %s\n",
			    strerror(errno));
			exit(1);
		}
	} else {
		if ((data_buff = malloc(par.data_size)) == NULL) {
			fprintf(stderr, TAG ": No core\n");
			exit(1);
		}
	}

	if (par.format == TFMT_HUMAN && par.api == API_B0) {
		/*
		 * Zero fields which are not present in old (zero) API
		 */
		memset(&hdrb, 0, sizeof(struct usbmon_packet_1));
	} else {
		/*
		 * Make uninitialized fields visible.
		 */
		memset(&hdrb, 0xdb, sizeof(struct usbmon_packet_1));
	}

	toflush = 0;
	for (;;) {
		if (par.api == API_B0) {
			getb.hdr = &hdrb;
			getb.data = data_buff;
			getb.alloc = par.data_size;
			if ((rc = ioctl(fd, MON_IOCX_GET, &getb)) != 0) {
				fprintf(stderr, TAG ": MON_IOCX_GET: %s\n",
				    strerror(errno));
				exit(1);
			}
			print(&par, &hdrb, data_buff);
		} else if (par.api == API_B1) {
			getb.hdr = &hdrb;
			getb.data = data_buff;
			getb.alloc = par.data_size;
			if ((rc = ioctl(fd, MON_IOCX_GETX, &getb)) != 0) {
				fprintf(stderr, TAG ": MON_IOCX_GETX: %s\n",
				    strerror(errno));
				exit(1);
			}
			print(&par, &hdrb, data_buff);
		} else if (par.api == API_B1M) {
			mfb.offvec = offs;
			mfb.nfetch = MFETCH_NM;
			mfb.nflush = toflush;
			if ((rc = ioctl(fd, MON_IOCX_MFETCH, &mfb)) != 0) {
				fprintf(stderr, TAG ": MON_IOCX_MFETCH: %s\n",
				    strerror(errno));
				exit(1);
			}
			for (i = 0; i < mfb.nfetch; i++) {
				off = offs[i];
				if (off >= par.map_size) {
					fprintf(stderr, TAG ": offset\n");
					continue;
				}
				hdr = (struct usbmon_packet_1 *)(data_buff + off);
				if (hdr->type == '@')
					continue;
				print(&par, hdr, (const unsigned char *)(hdr + 1));
			}
			toflush = mfb.nfetch;
		} else {
			getb.hdr = &hdrb;
			getb.data = data_buff;
			getb.alloc = par.data_size;
			if ((rc = ioctl(fd, MON_IOCX_GETX, &getb)) != 0) {
				if (errno == ENOTTY) {
					par.api = API_B0;
					rc = ioctl(fd, MON_IOCX_GET, &getb);
					if (rc != 0) {
						fprintf(stderr, TAG
						    ": MON_IOCX_GET: %s\n",
						    strerror(errno));
						exit(1);
					}
				} else {
					fprintf(stderr, TAG
					    ": MON_IOCX_GETX: %s\n",
					    strerror(errno));
					exit(1);
				}
			}
			print(&par, &hdrb, data_buff);
		}
	}

	// return 0;
}
示例#27
0
/*
 * Parse Route or Record-Route body
 */
static inline int do_parse_rr_body(char *buf, int len, rr_t **head)
{
	rr_t* r, *last;
	str s;
	param_hooks_t hooks;

	/* Make a temporary copy of the string pointer */
	if(buf==0 || len<=0)
	{
		LM_DBG("no body for record-route\n");
		*head = 0;
		return -2;
	}
	s.s = buf;
	s.len = len;
	trim_leading(&s);

	last = 0;

	while(1) {
		     /* Allocate and clear rr structure */
		r = (rr_t*)pkg_malloc(sizeof(rr_t));
		if (!r) {
			LM_ERR("no pkg memory left\n");
			goto error;
		}
		memset(r, 0, sizeof(rr_t));
		
		     /* Parse name-addr part of the header */
		if (parse_nameaddr(&s, &r->nameaddr) < 0) {
			LM_ERR("failed to parse name-addr\n");
			goto error;
		}
		r->len = r->nameaddr.len;

		     /* Shift just behind the closing > */
		s.s = r->nameaddr.name.s + r->nameaddr.len;  /* Point just behind > */
		s.len -= r->nameaddr.len;

		trim_leading(&s); /* Skip any white-chars */

		if (s.len == 0) goto ok; /* Nothing left, finish */
		
		if (s.s[0] == ';') {         /* Route parameter found */
			s.s++;
			s.len--;
			trim_leading(&s);
			
			if (s.len == 0) {
				LM_ERR("failed to parse params\n");
				goto error;
			}

			     /* Parse all parameters */
			if (parse_params(&s, CLASS_ANY, &hooks, &r->params) < 0) {
				LM_ERR("failed to parse params\n");
				goto error;
			}
			r->len = r->params->name.s + r->params->len - r->nameaddr.name.s;

			     /* Copy hooks */
			     /*r->r2 = hooks.rr.r2; */

			trim_leading(&s);
			if (s.len == 0) goto ok;
		}

		if (s.s[0] != ',') {
			LM_ERR("invalid character '%c', comma expected\n", s.s[0]);
			goto error;
		}
		
		     /* Next character is comma or end of header*/
		s.s++;
		s.len--;
		trim_leading(&s);

		if (s.len == 0) {
			LM_ERR("text after comma missing\n");
			goto error;
		}

		     /* Append the structure as last parameter of the linked list */
		if (!*head) *head = r;
		if (last) last->next = r;
		last = r;
	}

 error:
	if (r) pkg_free(r);
	free_rr(head); /* Free any contacts created so far */
	return -1;

 ok:
	if (!*head) *head = r;
	if (last) last->next = r;
	return 0;
}
示例#28
0
/*
 * Combines all Path HF bodies into one string.
 */
int build_path_vector(struct sip_msg *_m, str *path, str *received)
{
	static char buf[MAX_PATH_SIZE];
	char *p;
	struct hdr_field *hdr;
	struct sip_uri puri;

	rr_t *route = 0;

	path->len = 0;
	path->s = 0;
	received->s = 0;
	received->len = 0;

	if(parse_headers(_m, HDR_EOH_F, 0) < 0) {
		LM_ERR("failed to parse the message\n");
		goto error;
	}

	for( hdr=_m->path,p=buf ; hdr ; hdr=hdr->sibling) {
		/* check for max. Path length */
		if( p-buf+hdr->body.len+1 >= MAX_PATH_SIZE) {
			LM_ERR("Overall Path body exceeds max. length of %d\n",
					MAX_PATH_SIZE);
			goto error;
		}
		if(p!=buf)
			*(p++) = ',';
		memcpy( p, hdr->body.s, hdr->body.len);
		p +=  hdr->body.len;
	}

	if (p!=buf) {
		/* check if next hop is a loose router */
		if (parse_rr_body( buf, p-buf, &route) < 0) {
			LM_ERR("failed to parse Path body, no head found\n");
			goto error;
		}
		if (parse_uri(route->nameaddr.uri.s,route->nameaddr.uri.len,&puri)<0){
			LM_ERR("failed to parse the first Path URI\n");
			goto error;
		}
		if (!puri.lr.s) {
			LM_ERR("first Path URI is not a loose-router, not supported\n");
			goto error;
		}
		if (path_use_params) {
			param_hooks_t hooks;
			param_t *params;

			if (parse_params(&(puri.params),CLASS_CONTACT,&hooks,&params)!=0){
				LM_ERR("failed to parse parameters of first hop\n");
				goto error;
			}
			if (hooks.contact.received)
				*received = hooks.contact.received->body;
			/*for (;params; params = params->next) {
				if (params->type == P_RECEIVED) {
					*received = hooks.contact.received->body;
					break;
				}
			}*/
			free_params(params);
		}
		free_rr(&route);
	}

	path->s = buf;
	path->len = p-buf;
	return 0;
error:
	if(route) free_rr(&route);
	return -1;
}