static void
nmea_reader_parse( NmeaReader*  r )
{
   /* we received a complete sentence, now parse it to generate
    * a new GPS fix...
    */
    NmeaTokenizer  tzer[1];
    Token          tok;

    D("Received: '%.*s'", r->pos, r->in);
    if (r->pos < 9) {
        D("Too short. discarded.");
        return;
    }

    nmea_tokenizer_init(tzer, r->in, r->in + r->pos);
#if GPS_DEBUG
    {
        int  n;
        D("Found %d tokens", tzer->count);
        for (n = 0; n < tzer->count; n++) {
            Token  tok = nmea_tokenizer_get(tzer,n);
            D("%2d: '%.*s'", n, tok.end-tok.p, tok.p);
        }
    }
#endif

    tok = nmea_tokenizer_get(tzer, 0);
    if (tok.p + 5 > tok.end) {
        D("sentence id '%.*s' too short, ignored.", tok.end-tok.p, tok.p);
        return;
    }

    // ignore first two characters.
    tok.p += 2;
    if ( !memcmp(tok.p, "GGA", 3) ) {
        // GPS fix
        Token  tok_time          = nmea_tokenizer_get(tzer,1);
        Token  tok_latitude      = nmea_tokenizer_get(tzer,2);
        Token  tok_latitudeHemi  = nmea_tokenizer_get(tzer,3);
        Token  tok_longitude     = nmea_tokenizer_get(tzer,4);
        Token  tok_longitudeHemi = nmea_tokenizer_get(tzer,5);
        Token  tok_altitude      = nmea_tokenizer_get(tzer,9);
        Token  tok_altitudeUnits = nmea_tokenizer_get(tzer,10);

        nmea_reader_update_time(r, tok_time);
        nmea_reader_update_latlong(r, tok_latitude,
                                      tok_latitudeHemi.p[0],
                                      tok_longitude,
                                      tok_longitudeHemi.p[0]);
        nmea_reader_update_altitude(r, tok_altitude, tok_altitudeUnits);

    } else if ( !memcmp(tok.p, "GSA", 3) ) {
        int i;
				Token  tok_fixStatus   = nmea_tokenizer_get(tzer, 2); 
				
				if (tok_fixStatus.p[0] != '\0' && tok_fixStatus.p[0] != '1') { 
				  Token  tok_accuracy      = nmea_tokenizer_get(tzer, 15); 
				  nmea_reader_update_accuracy(r, tok_accuracy); 
				} 
				
        for(i = 3; i <= 14; i++){
            Token tok_prn = nmea_tokenizer_get(tzer, i);
            if(tok_prn.p >= tok_prn.end){
                r->status.used_in_fix_mask &= ~(1 << (i-3));
            }else{
                r->status.used_in_fix_mask |= 1 << (i-3);
            }
        }
    } else if ( !memcmp(tok.p, "GSV", 3) ) {
        Token  tok_numgsv          = nmea_tokenizer_get(tzer,1);
        Token  tok_indexgsv          = nmea_tokenizer_get(tzer,2);
        Token  tok_numsvs          = nmea_tokenizer_get(tzer,3);
        int numgsv = str2int(tok_numgsv.p, tok_numgsv.end);
        int indexgsv = str2int(tok_indexgsv.p, tok_indexgsv.end);
        int numsvs = str2int(tok_numsvs.p, tok_numsvs.end);

	if((indexgsv <= numgsv) && (indexgsv >= 1)) //________
        if (numsvs > 0){
            int i, j = 4;
            for(i = (indexgsv-1) << 2; i < indexgsv << 2; i++){
                Token  tok_prn          = nmea_tokenizer_get(tzer,j++);
                Token  tok_elevation          = nmea_tokenizer_get(tzer,j++);
                Token  tok_azimuth          = nmea_tokenizer_get(tzer,j++);
                Token  tok_snr          = nmea_tokenizer_get(tzer,j++);
                nmea_reader_update_sv_list(&r->status.sv_list[i], tok_prn, tok_elevation, tok_azimuth, tok_snr);
            }
            if(indexgsv == numgsv){
                r->status.num_svs = numsvs;
                if(r->sv_status_cb)
                    r->sv_status_cb(&r->status);
            }
        }
    } else if ( !memcmp(tok.p, "RMC", 3) ) {
        Token  tok_time          = nmea_tokenizer_get(tzer,1);
        Token  tok_fixStatus     = nmea_tokenizer_get(tzer,2);
        Token  tok_latitude      = nmea_tokenizer_get(tzer,3);
        Token  tok_latitudeHemi  = nmea_tokenizer_get(tzer,4);
        Token  tok_longitude     = nmea_tokenizer_get(tzer,5);
        Token  tok_longitudeHemi = nmea_tokenizer_get(tzer,6);
        Token  tok_speed         = nmea_tokenizer_get(tzer,7);
        Token  tok_bearing       = nmea_tokenizer_get(tzer,8);
        Token  tok_date          = nmea_tokenizer_get(tzer,9);

        D("in RMC, fixStatus=%c", tok_fixStatus.p[0]);
        if (tok_fixStatus.p[0] == 'A')
        {
            nmea_reader_update_date( r, tok_date, tok_time );

            nmea_reader_update_latlong( r, tok_latitude,
                                           tok_latitudeHemi.p[0],
                                           tok_longitude,
                                           tok_longitudeHemi.p[0] );

            nmea_reader_update_bearing( r, tok_bearing );
            nmea_reader_update_speed  ( r, tok_speed );
        }
    } else {
        tok.p -= 2;
        D("unknown sentence '%.*s", tok.end-tok.p, tok.p);
    }
    if ((r->fix.flags & GPS_LOCATION_HAS_LAT_LONG) &&
           (r->fix.flags & GPS_LOCATION_HAS_ALTITUDE) &&
           (r->fix.flags & (GPS_LOCATION_HAS_SPEED | GPS_LOCATION_HAS_BEARING))) {

#if GPS_DEBUG
        char   temp[256];
        char*  p   = temp;
        char*  end = p + sizeof(temp);
        struct tm   utc;

        p += snprintf( p, end-p, "sending fix" );
        if (r->fix.flags & GPS_LOCATION_HAS_LAT_LONG) {
            p += snprintf(p, end-p, " time=%llu", r->fix.timestamp);
            p += snprintf(p, end-p, " lat=%g lon=%g", r->fix.latitude, r->fix.longitude);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_ALTITUDE) {
            p += snprintf(p, end-p, " altitude=%g", r->fix.altitude);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_SPEED) {
            p += snprintf(p, end-p, " speed=%g", r->fix.speed);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_BEARING) {
            p += snprintf(p, end-p, " bearing=%g", r->fix.bearing);
        }
        if (r->fix.flags & GPS_LOCATION_HAS_ACCURACY) {
            p += snprintf(p,end-p, " accuracy=%g", r->fix.accuracy);
        }
        D("%s",temp);
#endif
        if (r->location_cb) {
            r->location_cb( &r->fix );
            r->fix.flags = 0;
        }
        else {
            D("no location_cb, keeping data until needed !");
        }
    }
}
Beispiel #2
0
int bla_handle_notify(struct sip_msg* msg, char* s1, char* s2)
{
	publ_info_t publ;
	struct to_body *pto= NULL, TO, *pfrom = NULL;
	str body;
	ua_pres_t dialog;
	unsigned int expires= 0;
	struct hdr_field* hdr;
	str subs_state;
	str extra_headers= {0, 0};
	static char buf[255];
	str contact;

	memset(&publ, 0, sizeof(publ_info_t));
	memset(&dialog, 0, sizeof(ua_pres_t));

	if ( parse_headers(msg,HDR_EOH_F, 0)==-1 )
	{
		LM_ERR("parsing headers\n");
		return -1;
	}

	if( msg->to==NULL || msg->to->body.s==NULL)
	{
		LM_ERR("cannot parse TO header\n");
		return -1;
	}
	/* examine the to header */
	if(msg->to->parsed != NULL)
	{
		pto = (struct to_body*)msg->to->parsed;
		LM_DBG("'To' header ALREADY PARSED: <%.*s>\n",
				pto->uri.len, pto->uri.s );
	}
	else
	{
		parse_to(msg->to->body.s,msg->to->body.s + msg->to->body.len + 1, &TO);
		if(TO.uri.len <= 0)
		{
			LM_DBG("'To' header NOT parsed\n");
			return -1;
		}
		pto = &TO;
	}
	publ.pres_uri= &pto->uri;
	dialog.watcher_uri= publ.pres_uri;

	if (pto->tag_value.s==NULL || pto->tag_value.len==0 )
	{
		LM_ERR("NULL to_tag value\n");
		return -1;
	}
	dialog.from_tag= pto->tag_value;

	if( msg->callid==NULL || msg->callid->body.s==NULL)
	{
		LM_ERR("cannot parse callid header\n");
		return -1;
	}
	dialog.call_id = msg->callid->body;

	if (!msg->from || !msg->from->body.s)
	{
		LM_ERR("cannot find 'from' header!\n");
		return -1;
	}
	if (msg->from->parsed == NULL)
	{
		LM_DBG(" 'From' header not parsed\n");
		/* parsing from header */
		if ( parse_from_header( msg )<0 )
		{
			LM_DBG(" ERROR cannot parse From header\n");
			return -1;
		}
	}
	pfrom = (struct to_body*)msg->from->parsed;
	dialog.to_uri= pfrom->uri;

	if( pfrom->tag_value.s ==NULL || pfrom->tag_value.len == 0)
	{
		LM_ERR("no from tag value present\n");
		return -1;
	}
	if ( get_content_length(msg) == 0 )
	{
		LM_DBG("content length= 0\n");
		return 1;
	}
	else
	{
		body.s=get_body(msg);
		if (body.s== NULL)
		{
			LM_ERR("cannot extract body from msg\n");
			return -1;
		}
		body.len = get_content_length( msg );

		if (!bla_body_is_valid( &body ))
		{
			LM_ERR("bad XML body!");
			return -1;
		}
	}
   	
	if(msg->contact== NULL || msg->contact->body.s== NULL)
	{
		LM_ERR("no contact header found");
		return -1;
	}
	if( parse_contact(msg->contact) <0 )
	{
		LM_ERR(" cannot parse contact header\n");
		return -1;
	}

	if(msg->contact->parsed == NULL)
	{
		LM_ERR("cannot parse contact header\n");
		return -1;
	}
	contact = ((contact_body_t* )msg->contact->parsed)->contacts->uri;

	dialog.to_tag= pfrom->tag_value;
	dialog.event= BLA_EVENT;
	dialog.flag= BLA_SUBSCRIBE;
	if(pua_is_dialog(&dialog)< 0)
	{
		LM_ERR("Notify in a non existing dialog\n");
		return -2;
	}

	/* parse Subscription-State and extract expires if existing */
	hdr = get_header_by_static_name( msg, "Subscription-State");
	if( hdr==NULL )
	{
		LM_ERR("No Subscription-State header found\n");
		return -1;
	}
	subs_state= hdr->body;
	if(strncasecmp(subs_state.s, "terminated", 10)== 0)
		expires= 0;
	else
	{
		if(strncasecmp(subs_state.s, "active", 6)== 0 ||
				strncasecmp(subs_state.s, "pending", 7)==0 )
		{
			expires = DEFAULT_EXPIRES;
			char* sep= NULL;
			str exp= {NULL, 0};
			sep= strchr(subs_state.s, ';');
			if(sep)
			{
				if(strncasecmp(sep+1, "expires=", 8)== 0)
				{
					exp.s= sep+ 9;
					sep= exp.s;
					while((*sep)>='0' && (*sep)<='9')
					{
						sep++;
						exp.len++;
					}
					if( str2int(&exp, &expires)< 0)
					{
						LM_ERR("while parsing int\n");
						return -1;
					}
				}
			}
		}
		else
		{
			LM_ERR("unknown Subscription-state token\n");
			return -1;
		}
	}

	/* +2 for ": " between header name and value */
	if ((header_name.len + 2 + contact.len + CRLF_LEN) >= sizeof(buf)) {
		LM_ERR("Sender header too large");
		return -1;
	}

	/* build extra_headers with Sender*/
	extra_headers.s= buf;
	memcpy(extra_headers.s, header_name.s, header_name.len);
	extra_headers.len= header_name.len;
	memcpy(extra_headers.s+extra_headers.len,": ",2);
	extra_headers.len+= 2;
	memcpy(extra_headers.s+ extra_headers.len, contact.s, contact.len);
	extra_headers.len+= contact.len;
	memcpy(extra_headers.s+ extra_headers.len, CRLF, CRLF_LEN);
	extra_headers.len+= CRLF_LEN;

	publ.id= contact;
	publ.body= &body;
	publ.source_flag= BLA_PUBLISH;
	publ.expires= expires;
	publ.event= BLA_EVENT;
	publ.extra_headers= &extra_headers;
	publ.outbound_proxy = presence_server;

	if(pua_send_publish(&publ)< 0)
	{
		LM_ERR("failed to send Publish message\n");
		return -1;
	}

	return 1;
}
Beispiel #3
0
dlg_t * build_dialog_info(struct dlg_cell * cell, int dst_leg, int src_leg,char *reply_marker)
{
	dlg_t* td = NULL;
	str cseq;
	unsigned int loc_seq;

	td = (dlg_t*)pkg_malloc(sizeof(dlg_t));
	if(!td){
		LM_ERR("out of pkg memory\n");
		return NULL;
	}
	memset(td, 0, sizeof(dlg_t));

	/*local sequence number*/
	cseq = cell->legs[dst_leg].r_cseq;
	if( !cseq.s || !cseq.len || str2int(&cseq, &loc_seq) != 0){
		LM_ERR("invalid cseq\n");
		goto error;
	}

	if (cell->legs[dst_leg].last_gen_cseq == 0)
		cell->legs[dst_leg].last_gen_cseq = loc_seq+1;
	else
		cell->legs[dst_leg].last_gen_cseq++;

	*reply_marker = 0;

	td->loc_seq.value = cell->legs[dst_leg].last_gen_cseq -1;

	td->loc_seq.is_set = 1;

	/*route set*/
	if( cell->legs[dst_leg].route_set.s && cell->legs[dst_leg].route_set.len){
		if( parse_rr_body(cell->legs[dst_leg].route_set.s,
			cell->legs[dst_leg].route_set.len, &td->route_set) !=0){
		 	LM_ERR("failed to parse route set\n");
			goto error;
		}
	}

	/*remote target--- Request URI*/
	if (cell->legs[dst_leg].contact.s==0 || cell->legs[dst_leg].contact.len==0){
		LM_ERR("no contact available\n");
		goto error;
	}
	td->rem_target = cell->legs[dst_leg].contact;

	td->rem_uri = (dst_leg==DLG_CALLER_LEG)? *dlg_leg_from_uri(cell,dst_leg):
					 *dlg_leg_to_uri(cell,dst_leg);
	td->loc_uri = (dst_leg==DLG_CALLER_LEG)? *dlg_leg_to_uri(cell,dst_leg):
					 *dlg_leg_from_uri(cell,dst_leg);
	td->id.call_id = cell->callid;
	td->id.rem_tag = cell->legs[dst_leg].tag;
	td->id.loc_tag = cell->legs[src_leg].tag;

	td->state= DLG_CONFIRMED;
	td->send_sock = cell->legs[dst_leg].bind_addr;

	/* link the dialog cell here - it will eventually be linked
	 * within the upcoming created transaction */
	td->dialog_ctx = cell;

	return td;

error:
	free_tm_dlg(td);
	return NULL;
}
Beispiel #4
0
boolean Plugin_021(byte function, struct NodoEventStruct *event, char *string)
  {
  boolean success=false;

  switch(function)
   {
   case PLUGIN_INIT:
     {
       LCD_I2C_init();
       break;
     }

  case PLUGIN_COMMAND:
     {
     byte Par2=event->Par2 & 0xff;		// Column
     byte Par3=event->Par2>>8 & 0xff;		// Data to display
     byte Par4=event->Par2>>16 & 0xff;		// In case of var, variable number
     boolean Print = true;

     if (event->Par1 >= 0 && event->Par1 <= PLUGIN_021_ROWS)
       {
       char TempString[80];
       TempString[0]=0;

       switch (Par3)
         {
           case 0:
           case CMD_RESET:
             if (event->Par1 == 0)
               LCD_I2C_clear();
             else
               LCD_I2C_printline(event->Par1-1,0, (char*)"");
             Print=false;
             break;

           case EVENT_BOOT:
             LCD_I2C_init();
             break;

           case VALUE_ON:
             _backlightval=LCD_BACKLIGHT;
             LCD_I2C_expanderWrite(0);
             Print=false;
             break;

           case VALUE_OFF:
             _backlightval=LCD_NOBACKLIGHT;
             LCD_I2C_expanderWrite(0);
             Print=false;
             break;

           case EVENT_MESSAGE:
             if ((Par4 > 0) && (Par4 <= LCDI2C_MSG_MAX))
               {
                 sprintf(TempString,"%s", LCDText_tabel[Par4-1]);
                 LCD_I2C_printline(event->Par1-1, Par2-1, TempString);
               }
             break;

           case EVENT_VARIABLE:
             if (Par4 > 0 && Par4 <16)
               {
                 int d1 = UserVar[Par4-1];            // Get the integer part
                 float f2 = UserVar[Par4-1] - d1;     // Get fractional part
                 int d2 = trunc(f2 * 10);   // Turn into integer
                 if (d2<0) d2=d2*-1;
                 sprintf(TempString,"%d.%01d", d1,d2);
                 LCD_I2C_printline(event->Par1-1, Par2-1, TempString);
               }
             break;

         }  // case

         //if (Print)
         //  LCD_I2C_printline(event->Par1-1, Par2-1, TempString);

         Wire.endTransmission(true);
         success=true;
       } // if

     break;
     }

   case PLUGIN_MMI_IN:
     {
     char *TempStr=(char*)malloc(INPUT_COMMAND_SIZE);
     
     if(GetArgv(string,TempStr,1))
       {
       if(strcasecmp(TempStr,PLUGIN_NAME_021)==0)
         {
         if(event->Par1 >= 0 && event->Par1 <= PLUGIN_021_ROWS)
           {

           if(GetArgv(string,TempStr,4))
               event->Par2|=str2cmd(TempStr)<<8;

           if(GetArgv(string,TempStr,5))
               event->Par2|=str2int(TempStr)<<16;

           event->Type = ESP_TYPE_PLUGIN_COMMAND;
           event->Command = PLUGIN_ID_021;
           success=true;
           }
         }
       }
     free(TempStr);
     break;
     }

   case PLUGIN_MMI_OUT:
     {
     //strcpy(string,PLUGIN_NAME_021);
     //strcat(string," ");
     //strcat(string,int2str(event->Par1));
     //strcat(string,",");
     //strcat(string,int2str(event->Par2 & 0xff));
     //strcat(string,",");
     //strcat(string,cmd2str(event->Par2>>8 & 0xff));
     //strcat(string,",");
     //strcat(string,int2str(event->Par2>>16 & 0xff));
     sprintf(string,"%s",PLUGIN_NAME_021);
     sprintf(string,"%s%s",string," ");
     sprintf(string,"%s%s",string,int2str(event->Par1));
     sprintf(string,"%s%s",string,",");
     sprintf(string,"%s%s",string,int2str(event->Par2 & 0xff));
     sprintf(string,"%s%s",string,",");
     sprintf(string,"%s%s",string,cmd2str(event->Par2>>8 & 0xff));
     sprintf(string,"%s%s",string,",");
     sprintf(string,"%s%s",string,int2str(event->Par2>>16 & 0xff));
     break;
     }
 }      
 return success;
}
Beispiel #5
0
void reader_mmt_standard(char* fname, int fid, obsmeta* meta, model* m, observations* obs)
{
    int ncid;
    int dimid_nprof, dimid_nz;
    size_t nprof, nz;
    int varid_lon, varid_lat, varid_z, varid_type;
    int varid_v = -1;
    double* lon;
    double* lat;
    double** z;
    double** v;
    double missval;
    double validmin = DBL_MAX;
    double validmax = -DBL_MAX;
    char* type;
    char buf[MAXSTRLEN];
    int len;
    int year, month, day;
    double tunits_multiple, tunits_offset;
    int mvid;
    int p, i;

    if (meta->nstds == 0)
        enkf_quit("ERROR_STD is necessary but not specified for product \"%s\"", meta->product);

    ncw_open(fname, NC_NOWRITE, &ncid);

    ncw_inq_dimid(fname, ncid, "N_PROF", &dimid_nprof);
    ncw_inq_dimlen(fname, ncid, dimid_nprof, &nprof);

    ncw_inq_dimid(fname, ncid, "N_LEVELS", &dimid_nz);
    ncw_inq_dimlen(fname, ncid, dimid_nz, &nz);
    enkf_printf("        # profiles = %u\n", (unsigned int) nprof);

    if (nprof == 0) {
        ncw_close(fname, ncid);
        return;
    }

    enkf_printf("        # z levels = %u\n", (unsigned int) nz);

    ncw_inq_varid(fname, ncid, "LONGITUDE", &varid_lon);
    lon = malloc(nprof * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_lon, lon);

    ncw_inq_varid(fname, ncid, "LATITUDE", &varid_lat);
    lat = malloc(nprof * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_lat, lat);

    ncw_inq_varid(fname, ncid, "PRES_BLUELINK", &varid_z);
    z = alloc2d(nprof, nz, sizeof(double));
    ncw_get_var_double(fname, ncid, varid_z, z[0]);

    if (strncmp(meta->type, "TEM", 3) == 0) {
        validmin = -2.0;
        validmax = 40.0;
        ncw_inq_varid(fname, ncid, "TEMP_BLUELINK", &varid_v);
    } else if (strncmp(meta->type, "SAL", 3) == 0) {
        validmin = 0;
        validmax = 50.0;
        ncw_inq_varid(fname, ncid, "PSAL_BLUELINK", &varid_v);
    } else
        enkf_quit("observation type \"%s\" not handled for MMT product", meta->type);
    v = alloc2d(nprof, nz, sizeof(double));
    ncw_get_var_double(fname, ncid, varid_v, v[0]);
    ncw_get_att_double(fname, ncid, varid_v, "_FillValue", &missval);

    ncw_inq_varid(fname, ncid, "WMO_INST_TYPE", &varid_type);
    type = malloc(nprof * WMO_INSTSIZE);
    ncw_get_var_text(fname, ncid, varid_type, type);

    ncw_close(fname, ncid);

    strcpy(buf, fname);
    len = strlen(buf);
    buf[len - 10] = 0;          /* _mmt_qc.nc */
    if (!str2int(&buf[len - 12], &day))
        enkf_quit("MMT reader: could not convert file name \"%s\" to date", fname);
    buf[len - 12] = 0;
    if (!str2int(&buf[len - 14], &month))
        enkf_quit("MMT reader: could not convert file name \"%s\" to date", fname);
    buf[len - 14] = 0;
    if (!str2int(&buf[len - 18], &year))
        enkf_quit("MMT reader: could not convert file name \"%s\" to date", fname);
    snprintf(buf, MAXSTRLEN, "days since %4d-%02d-%02d", year, month, day);

    tunits_convert(buf, &tunits_multiple, &tunits_offset);

    mvid = model_getvarid(m, obs->obstypes[obstype_getid(obs->nobstypes, obs->obstypes, meta->type)].varname, 1);

    for (p = 0; p < (int) nprof; ++p) {
        char inststr[MAXSTRLEN];

        snprintf(inststr, MAXSTRLEN, "WMO%04u", type[p * WMO_INSTSIZE]);

        for (i = 0; i < (int) nz; ++i) {
            observation* o;
            obstype* ot;

            if (fabs(v[p][i] - missval) < EPS || v[p][i] < validmin || v[p][i] > validmax)
                continue;
            if (z[p][i] < 0.0)
                continue;

            obs_checkalloc(obs);
            o = &obs->data[obs->nobs];

            o->product = st_findindexbystring(obs->products, meta->product);
            assert(o->product >= 0);
            o->type = obstype_getid(obs->nobstypes, obs->obstypes, meta->type);
            assert(o->type >= 0);
            ot = &obs->obstypes[o->type];
            o->instrument = st_add_ifabscent(obs->instruments, inststr, -1);
            o->id = obs->nobs;
            o->fid = fid;
            o->batch = p;
            o->value = v[p][i];
            o->std = 0.0;
            o->lon = lon[p];
            o->lat = lat[p];
            o->depth = z[p][i];
            o->status = model_xy2fij(m, mvid, o->lon, o->lat, &o->fi, &o->fj);
            if (!obs->allobs && o->status == STATUS_OUTSIDEGRID)
                break;
            if (o->status == STATUS_OK)
                o->status = model_z2fk(m, mvid, o->fi, o->fj, o->depth, &o->fk);
            else
                o->fk = NaN;
            if ((o->status == STATUS_OK) && (o->lon <= ot->xmin || o->lon >= ot->xmax || o->lat <= ot->ymin || o->lat >= ot->ymax || o->depth <= ot->zmin || o->depth >= ot->zmax))
                o->status = STATUS_OUTSIDEOBSDOMAIN;
            o->date = tunits_offset + 0.5;
            o->aux = -1;

            obs->nobs++;
        }
    }

    free(lon);
    free(lat);
    free2d(v);
    free2d(z);
    free(type);
}
Beispiel #6
0
int dlg_cseq_update(sip_msg_t *msg)
{
	dlg_cell_t *dlg = NULL;
	unsigned int direction;
	unsigned int ninc = 0;
	unsigned int vinc = 0;
	str nval;
	str *pval;

	if(dlg_cseq_prepare_msg(msg)!=0) {
		goto error;
	}
	if(msg->first_line.type==SIP_REPLY) {
		/* nothing to do for outgoing replies */
		goto done;
	}

	LM_DBG("initiating cseq updates\n");

	direction = DLG_DIR_NONE;
	dlg = dlg_lookup_msg_dialog(msg, &direction);

	if(dlg == NULL) {
		LM_DBG("no dialog for this request\n");
		goto done;
	}

	/* supported only for downstrem direction */
	if(direction != DLG_DIR_DOWNSTREAM) {
		LM_DBG("request not going downstream (%u)\n", direction);
		goto done;
	}

	ninc = 1;

	/* take the increment value from dialog */
	if((dlg->iflags&DLG_IFLAG_CSEQ_DIFF)==DLG_IFLAG_CSEQ_DIFF) {
		/* get dialog variable holding cseq diff */
		pval = get_dlg_variable(dlg, &_dlg_cseq_diff_var_name);
		if(pval==NULL || pval->s==NULL || pval->len<=0) {
			LM_DBG("dialog marked with cseq diff but no variable set yet\n");
			goto done;
		}
		if(str2int(pval, &vinc)<0) {
			LM_ERR("invalid dlg cseq diff var value: %.*s\n",
					pval->len, pval->s);
			goto done;
		}
	}
	vinc += ninc;
	if(vinc==0) {
		LM_DBG("nothing to increment\n");
		goto done;
	}
	nval.s = int2str(vinc, &nval.len);
	if(set_dlg_variable(dlg, &_dlg_cseq_diff_var_name, &nval) <0) {
		LM_ERR("failed to set the dlg cseq diff var\n");
		goto done;
	}
	str2int(&get_cseq(msg)->number, &ninc);
	vinc += ninc;
	nval.s = int2str(vinc, &nval.len);
	trim(&nval);

	LM_DBG("adding auth cseq header value: %.*s\n", nval.len, nval.s);
	parse_headers(msg, HDR_EOH_F, 0);
	sr_hdr_add_zs(msg, "P-K-Auth-CSeq", &nval);

done:
	if(dlg!=NULL) dlg_release(dlg);
	return 0;

error:
	if(dlg!=NULL) dlg_release(dlg);
	return -1;
}
/*
 * IMPORTANT: if a dialog reference is returned, the dialog hash entry will
   be kept locked when this function returns
   NOTE: if a reply tree is returned, no dialog reference is returned.
 */
static inline struct mi_root* process_mi_params(struct mi_root *cmd_tree,
			struct dlg_cell **dlg_p, unsigned int *idx, unsigned int *cnt)
{
	struct mi_node* node;
	struct dlg_entry *d_entry;
	struct dlg_cell *dlg;
	str *p1;
	str *p2;
	unsigned int h_entry;

	node = cmd_tree->node.kids;
	if (node == NULL) {
		/* no parameters at all */
		*dlg_p = NULL;
		*idx = *cnt = 0;
		return NULL;
	}

	/* we have params -> get p1 and p2 */
	p1 = &node->value;
	LM_DBG("p1='%.*s'\n", p1->len, p1->s);

	node = node->next;
	if ( !node || !node->value.s || !node->value.len) {
		p2 = NULL;
	} else {
		p2 = &node->value;
		LM_DBG("p2='%.*s'\n", p2->len, p2->s);
		if ( node->next!=NULL )
			return init_mi_tree( 400, MI_SSTR(MI_MISSING_PARM));
	}

	/* check the params */
	if (p2 && str2int(p1,idx)==0 && str2int(p2,cnt)==0) {
		/* 2 numerical params -> index and counter */
		*dlg_p = NULL;
		return NULL;
	}

	*idx = *cnt = 0;

	h_entry = dlg_hash( p1/*callid*/ );

	d_entry = &(d_table->entries[h_entry]);
	dlg_lock( d_table, d_entry);

	for( dlg = d_entry->first ; dlg ; dlg = dlg->next ) {
		if (match_downstream_dialog( dlg, p1/*callid*/, p2/*from_tag*/)==1) {
			if (dlg->state==DLG_STATE_DELETED) {
				*dlg_p = NULL;
				break;
			} else {
				*dlg_p = dlg;
				return 0;
			}
		}
	}
	dlg_unlock( d_table, d_entry);

	return init_mi_tree( 404, MI_SSTR("Nu such dialog"));
}
Beispiel #8
0
int run_reg_tm_cback(void *e_data, void *data, void *r_data)
{
	struct sip_msg *msg;
	int statuscode = 0;
	unsigned int exp = 0;
	reg_record_t *rec = (reg_record_t*)e_data;
	struct hdr_field *c_ptr, *head_contact;
	struct uac_credential crd;
	contact_t *contact;
	struct authenticate_body *auth = NULL;
	static struct authenticate_nc_cnonce auth_nc_cnonce;
	HASHHEX response;
	str *new_hdr;
	struct reg_tm_cback_data *tm_cback_data = (struct reg_tm_cback_data*)data;
	struct cell *t;
	struct tmcb_params *ps;
	time_t now;
	reg_tm_cb_t *cb_param;

	cb_param = tm_cback_data->cb_param;
	if (rec!=cb_param->uac) {
		/* no action on current list elemnt */
		return 0; /* continue list traversal */
	}

	t = tm_cback_data->t;
	ps = tm_cback_data->ps;
	now = tm_cback_data->now;

	reg_print_record(rec);

	if (ps->rpl==FAKED_REPLY)
		memset(&rec->td.forced_to_su, 0, sizeof(union sockaddr_union));
	else if (rec->td.forced_to_su.s.sa_family == AF_UNSPEC)
		rec->td.forced_to_su = t->uac[0].request.dst.to;

	statuscode = ps->code;
	switch(statuscode) {
	case 200:
		msg = ps->rpl;
		if(msg==FAKED_REPLY) {
			LM_ERR("FAKED_REPLY\n");
			goto done;
		}
		if (parse_headers(msg, HDR_EOH_F, 0) == -1) {
			LM_ERR("failed to parse headers\n");
			goto done;
		}
		if (msg->contact) {
			c_ptr = msg->contact;
			while(c_ptr) {
				if (c_ptr->type == HDR_CONTACT_T) {
					if (!c_ptr->parsed && (parse_contact(c_ptr)<0)) {
						LM_ERR("failed to parse Contact body\n");
						goto done;
					}
				}
				c_ptr = c_ptr->next;
			}
		} else {
			LM_ERR("No contact header in received 200ok\n");
			goto done;
		}
		head_contact = msg->contact;
		contact = ((contact_body_t*)msg->contact->parsed)->contacts;
		while (contact) {
			/* Check for binding */
			if (contact->uri.len==rec->contact_uri.len &&
				strncmp(contact->uri.s,rec->contact_uri.s,contact->uri.len)==0){
				if (contact->expires && contact->expires->body.len) {
					if (str2int(&contact->expires->body, &exp)<0) {
						LM_ERR("Unable to extract expires from [%.*s]"
							" for binding [%.*s]\n",
							contact->expires->body.len,
							contact->expires->body.s,
							contact->uri.len, contact->uri.s);
					}
				}
				break;
			}
					
			/* get the next contact */
			if (contact->next == NULL) {
				contact = NULL;
				c_ptr = head_contact->next;
				while(c_ptr) {
					if (c_ptr->type == HDR_CONTACT_T) {
						head_contact = c_ptr;
						contact = ((contact_body_t*)c_ptr->parsed)->contacts;
						break;
					}
					c_ptr = c_ptr->next;
				}
			} else {
				contact = contact->next;
			}
		}
		rec->state = REGISTERED_STATE;
		if (exp) rec->expires = exp;
		rec->registration_timeout = now + rec->expires - timer_interval;
		break;

	case WWW_AUTH_CODE:
	case PROXY_AUTH_CODE:
		msg = ps->rpl;
		if(msg==FAKED_REPLY) {
			LM_ERR("FAKED_REPLY\n");
			goto done;
		}

		if (rec->auth_user.s==NULL || rec->auth_user.len==0 ||
			rec->auth_password.s==NULL || rec->auth_password.len==0) {
			LM_ERR("Credentials not provisioned\n");
			rec->state = WRONG_CREDENTIALS_STATE;
			rec->registration_timeout = 0;
			/* action successfuly completed on current list element */
			return 1; /* exit list traversal */
		}

		if (statuscode==WWW_AUTH_CODE) {
			if (0 == parse_www_authenticate_header(msg))
				auth = get_www_authenticate(msg);
		} else if (statuscode==PROXY_AUTH_CODE) {
			if (0 == parse_proxy_authenticate_header(msg))
				auth = get_proxy_authenticate(msg);
		}
		if (auth == NULL) {
			LM_ERR("Unable to extract authentication info\n");
			goto done;
		}
		LM_DBG("flags=[%d] realm=[%.*s] domain=[%.*s] nonce=[%.*s]"
			" opaque=[%.*s] qop=[%.*s]\n",
			auth->flags,
			auth->realm.len, auth->realm.s,
			auth->domain.len, auth->domain.s,
			auth->nonce.len, auth->nonce.s,
			auth->opaque.len, auth->opaque.s,
			auth->qop.len, auth->qop.s);

		switch(rec->state) {
		case REGISTERING_STATE:
			break;
		case AUTHENTICATING_STATE:
			/* We already sent an authenticated REGISTER and we are still challanged! */
			LM_WARN("Wrong credentials for [%.*s]\n",
				rec->td.rem_uri.len, rec->td.rem_uri.s);
			rec->state = WRONG_CREDENTIALS_STATE;
			rec->registration_timeout = 0;
			/* action successfuly completed on current list element */
			return 1; /* exit list traversal */
		default:
			LM_ERR("Unexpected [%d] notification cb in state [%d]\n",
				statuscode, rec->state);
			goto done;
		}

		/* perform authentication */
		if (auth->realm.s && auth->realm.len) {
			crd.realm.s = auth->realm.s; crd.realm.len = auth->realm.len;
		} else {
			LM_ERR("No realm found\n");
			goto done;
		}
		crd.user.s = rec->auth_user.s; crd.user.len = rec->auth_user.len;
		crd.passwd.s = rec->auth_password.s; crd.passwd.len = rec->auth_password.len;

		memset(&auth_nc_cnonce, 0, sizeof(struct authenticate_nc_cnonce));
		uac_auth_api._do_uac_auth(&register_method, &rec->td.rem_target, &crd,
					auth, &auth_nc_cnonce, response);
		new_hdr = uac_auth_api._build_authorization_hdr(statuscode, &rec->td.rem_target,
					&crd, auth, &auth_nc_cnonce, response);
		if (!new_hdr) {
			LM_ERR("failed to build authorization hdr\n");
			goto done;
		}
		if(send_register(cb_param->hash_index, rec, new_hdr)==1) {
			rec->state = AUTHENTICATING_STATE;
		} else {
			rec->state = INTERNAL_ERROR_STATE;
		}
		pkg_free(new_hdr->s);
		new_hdr->s = NULL; new_hdr->len = 0;
		break;

	case 423: /* Interval Too Brief */
		msg = ps->rpl;
		if(msg==FAKED_REPLY) {
			LM_ERR("FAKED_REPLY\n");
			goto done;
		}
		if (0 == parse_min_expires(msg)) {
			rec->expires = (unsigned int)(long)msg->min_expires->parsed;
			if(send_register(cb_param->hash_index, rec, NULL)==1)
				rec->state = REGISTERING_STATE;
			else
				rec->state = INTERNAL_ERROR_STATE;
		} else {
			rec->state = REGISTRAR_ERROR_STATE;
			rec->registration_timeout = now + rec->expires - timer_interval;
		}
		break;

	case 408: /* Interval Too Brief */
		rec->state = REGISTER_TIMEOUT_STATE;
		rec->registration_timeout = now + rec->expires - timer_interval;
		break;

	default:
		if(statuscode<400 && statuscode>=300) {
			LM_ERR("Redirection not implemented yet\n");
			rec->state = INTERNAL_ERROR_STATE;
		} else {
			/* we got an error from the server */
			rec->state = REGISTRAR_ERROR_STATE;
			rec->registration_timeout = now + rec->expires - timer_interval;
			
		}
	}

	/* action successfuly completed on current list element */
	return 1; /* exit list traversal */
done:
	rec->state = INTERNAL_ERROR_STATE;
	rec->registration_timeout = now + rec->expires;
	return -1; /* exit list traversal */
}
Beispiel #9
0
void subs_cback_func(struct cell *t, int cb_type, struct tmcb_params *ps)
{
	struct sip_msg* msg= NULL;
	int lexpire= 0;
	unsigned int cseq;
	ua_pres_t* presentity= NULL, *hentity= NULL;
	struct to_body *pto = NULL, TO = {0}, *pfrom = NULL;
	int size= 0;
	unsigned int hash_code;
	int flag ;
	str record_route= {0, 0};
	int rt;
	str contact;
	int initial_request = 0;
	int end_transaction = 1;

	if( ps->param== NULL || *ps->param== NULL )
	{
		LM_ERR("null callback parameter\n");
		return;
	}

	if (dbmode == PUA_DB_ONLY && pua_dbf.start_transaction)
	{
		if (pua_dbf.start_transaction(pua_db, DB_LOCKING_WRITE) < 0)
		{
			LM_ERR("in start_transaction\n");
			goto error;
		}
	}

	LM_DBG("completed with status %d\n",ps->code) ;
	hentity= (ua_pres_t*)(*ps->param);
	hash_code= core_hash(hentity->pres_uri,hentity->watcher_uri,
				HASH_SIZE);
	flag= hentity->flag;
	if(hentity->flag & XMPP_INITIAL_SUBS)
		hentity->flag= XMPP_SUBSCRIBE;

	/* get dialog information from reply message: callid, to_tag, from_tag */
	msg= ps->rpl;
	if(msg == NULL)
	{
		LM_ERR("no reply message found\n ");
		goto error;
	}

	if(msg== FAKED_REPLY)
	{
		struct hdr_field *callid = NULL, *from = NULL;
		struct to_body FROM = {0};

		callid = (struct hdr_field *) pkg_malloc(sizeof(struct hdr_field));
		if (callid == NULL)
		{
			LM_ERR("Out of memory\n");
			goto faked_error;
		}
		memset(callid, 0, sizeof(struct hdr_field));
		get_hdr_field(t->callid.s, t->callid.s + t->callid.len, callid);
		hentity->call_id = callid->body;

		from = (struct hdr_field *) pkg_malloc(sizeof(struct hdr_field));
		if (from == NULL)
		{
			LM_ERR("Out of memory\n");
			goto faked_error;
		}
		memset(from, 0, sizeof(struct hdr_field));
		get_hdr_field(t->from.s, t->from.s + t->from.len, from);
		parse_to(from->body.s, from->body.s + from->body.len + 1, &FROM);
		if(FROM.uri.len <= 0) 
		{
			LM_ERR("'From' header NOT parsed\n");
			goto faked_error;
		}
	
		hentity->call_id = callid->body;
		hentity->from_tag = (&FROM)->tag_value;
		hentity->to_tag.s = NULL;
		hentity->to_tag.len = 0;

		find_and_delete_dialog(hentity, hash_code);
faked_error:
		if (callid) pkg_free(callid);
		free_to_params(&FROM);
		if (from) pkg_free(from);
		goto done;
	}
	
	if ( parse_headers(msg,HDR_EOH_F, 0)==-1 )
	{
		LM_ERR("when parsing headers\n");
		goto error;
	}

	if(ps->rpl->expires && msg->expires->body.len > 0)
	{
		if (!msg->expires->parsed && (parse_expires(msg->expires) < 0))
		{
			LM_ERR("cannot parse Expires header\n");
			goto error;
		}
		lexpire = ((exp_body_t*)msg->expires->parsed)->val;
		LM_DBG("lexpire= %d\n", lexpire);
	}

	/*if initial request */
	if(hentity->call_id.s== NULL)
	{
		initial_request = 1;

		if( msg->callid==NULL || msg->callid->body.s==NULL)
		{
			LM_ERR("cannot parse callid header\n");
			goto error;
		}
		
		if (!msg->from || !msg->from->body.s)
		{
			LM_ERR("cannot find 'from' header!\n");
			goto error;
		}
		if (msg->from->parsed == NULL)
		{
			if ( parse_from_header( msg )<0 ) 
			{
				LM_ERR("cannot parse From header\n");
				goto error;
			}
		}
		pfrom = (struct to_body*)msg->from->parsed;
	
		if( pfrom->tag_value.s ==NULL || pfrom->tag_value.len == 0)
		{
			LM_ERR("no from tag value present\n");
			goto error;
		}

		hentity->call_id=  msg->callid->body;
		hentity->from_tag= pfrom->tag_value;

		if(ps->code >= 300 || lexpire == 0)
		{
			hentity->to_tag.s = NULL;
			hentity->to_tag.len = 0;
			find_and_delete_dialog(hentity, hash_code);
			goto done;
		}

		if( msg->to==NULL || msg->to->body.s==NULL)
		{
			LM_ERR("cannot parse TO header\n");
			goto error;
		}			
		if(msg->to->parsed != NULL)
		{
			pto = (struct to_body*)msg->to->parsed;
			LM_DBG("'To' header ALREADY PARSED: <%.*s>\n",pto->uri.len,pto->uri.s);
		}
		else
		{
			parse_to(msg->to->body.s,msg->to->body.s +
				msg->to->body.len + 1, &TO);
			if(TO.uri.len <= 0) 
			{
				LM_ERR("'To' header NOT parsed\n");
				goto error;
			}
			pto = &TO;
		}			
		if( pto->tag_value.s ==NULL || pto->tag_value.len == 0)
		{
			LM_ERR("no to tag value present\n");
			goto error;
		}
		hentity->to_tag= pto->tag_value;
	}

	if(ps->code >= 300 )
	{	/* if an error code and a stored dialog delete it and try to send 
		   a subscription with type= INSERT_TYPE, else return*/	
		
		subs_info_t subs;

		hentity->to_tag.s = NULL;
		hentity->to_tag.len = 0;
		find_and_delete_dialog(hentity, hash_code);

		if (dbmode == PUA_DB_ONLY && pua_dbf.end_transaction)
		{
			if (pua_dbf.end_transaction(pua_db) < 0)
			{
				LM_ERR("in end_transaction\n");
				goto error;
			}
		}

		end_transaction = 0;

		/* Redirect if the response 3XX */
		memset(&subs, 0, sizeof(subs_info_t));
		subs.pres_uri= hentity->pres_uri; 
		subs.watcher_uri= hentity->watcher_uri;
		subs.contact= &hentity->contact;

		if(hentity->remote_contact.s)
			subs.remote_target= &hentity->remote_contact;

		if(hentity->desired_expires== 0)
			subs.expires= -1;
		else
		if(hentity->desired_expires< (int)time(NULL))
			subs.expires= 0;
		else
			subs.expires= hentity->desired_expires- (int)time(NULL)+ 3;

		subs.flag= INSERT_TYPE;
		subs.source_flag= flag;
		subs.event= hentity->event;
		subs.id= hentity->id;
		subs.outbound_proxy= hentity->outbound_proxy;
		subs.extra_headers= hentity->extra_headers;
		subs.cb_param= hentity->cb_param;
	
		if(send_subscribe(&subs)< 0)
		{
			LM_ERR("when trying to send SUBSCRIBE\n");
			goto error;
		}
		goto done;
	}

	if(lexpire== 0 )
	{
		LM_DBG("lexpire= 0 Delete from hash table");
		find_and_delete_dialog(hentity, hash_code);
		goto done;
	}

	/* extract the contact */
	if(msg->contact== NULL || msg->contact->body.s== NULL)
	{
		LM_ERR("no contact header found");
		goto error;
	}
	if( parse_contact(msg->contact) <0 )
	{
		LM_ERR(" cannot parse contact header\n");
		goto error;
	}
	if(msg->contact->parsed == NULL)
	{
		LM_ERR("cannot parse contact header\n");
		goto error;
	}
	contact = ((contact_body_t* )msg->contact->parsed)->contacts->uri;

	if( msg->cseq==NULL || msg->cseq->body.s==NULL)
	{
		LM_ERR("cannot parse cseq header\n");
		goto error;
	}

	if( str2int( &(get_cseq(msg)->number), &cseq)< 0)
	{
		LM_ERR("while converting str to int\n");
		goto error;
	}

	if(initial_request == 0)
	{
		hentity->cseq = cseq;
		find_and_update_dialog(hentity, hash_code, lexpire, &contact);
		goto done;
	}

	/*process record route and add it to a string*/
	if (msg->record_route!=NULL)
	{
		rt = print_rr_body(msg->record_route, &record_route, 1, 0);
		if(rt != 0)
		{
			LM_ERR("parsing record route [%d]\n", rt);	
			record_route.s=NULL;
			record_route.len=0;
		}
	}

	size= sizeof(ua_pres_t)+ 2*sizeof(str)+( pto->uri.len+
		pfrom->uri.len+ pto->tag_value.len+ pfrom->tag_value.len
		+msg->callid->body.len+ record_route.len+ hentity->contact.len+
		hentity->id.len )*sizeof(char);

	if(hentity->extra_headers)
		size+= sizeof(str)+ hentity->extra_headers->len*sizeof(char);

	presentity= (ua_pres_t*)shm_malloc(size);
	if(presentity== NULL)
	{
		LM_ERR("no more share memory\n");
		goto error;
	}
	
	memset(presentity, 0, size);
	size= sizeof(ua_pres_t);

	presentity->pres_uri= (str*)( (char*)presentity+ size);
	size+= sizeof(str);
	presentity->pres_uri->s= (char*)presentity+ size;
	memcpy(presentity->pres_uri->s, pto->uri.s, pto->uri.len);
	presentity->pres_uri->len= pto->uri.len;
	size+= pto->uri.len;

	presentity->watcher_uri= (str*)( (char*)presentity+ size);
	size+= sizeof(str);
	presentity->watcher_uri->s= (char*)presentity+ size;
	memcpy(presentity->watcher_uri->s, pfrom->uri.s, pfrom->uri.len);
	presentity->watcher_uri->len= pfrom->uri.len;
	size+= pfrom->uri.len;

	presentity->call_id.s= (char*)presentity + size;
	memcpy(presentity->call_id.s,msg->callid->body.s, 
		msg->callid->body.len);
	presentity->call_id.len= msg->callid->body.len;
	size+= presentity->call_id.len;

	presentity->to_tag.s= (char*)presentity + size;
	memcpy(presentity->to_tag.s,pto->tag_value.s, 
			pto->tag_value.len);
	presentity->to_tag.len= pto->tag_value.len;
	size+= pto->tag_value.len;

	presentity->from_tag.s= (char*)presentity + size;
	memcpy(presentity->from_tag.s,pfrom->tag_value.s, 
			pfrom->tag_value.len);
	presentity->from_tag.len= pfrom->tag_value.len;
	size+= pfrom->tag_value.len;

	if(record_route.len && record_route.s)
	{
		presentity->record_route.s= (char*)presentity + size;
		memcpy(presentity->record_route.s, record_route.s, record_route.len);
		presentity->record_route.len= record_route.len;
		size+= record_route.len;
		pkg_free(record_route.s);
		record_route.s = NULL;
	}

	presentity->contact.s= (char*)presentity + size;
	memcpy(presentity->contact.s, hentity->contact.s, hentity->contact.len);
	presentity->contact.len= hentity->contact.len;
	size+= hentity->contact.len;

	if(hentity->id.s)
	{
		presentity->id.s=(char*)presentity+ size;
		memcpy(presentity->id.s, hentity->id.s, 
			hentity->id.len);
		presentity->id.len= hentity->id.len; 
		size+= presentity->id.len;
	}

	if(hentity->extra_headers)
	{
		presentity->extra_headers= (str*)((char*)presentity+ size);
		size+= sizeof(str);
		presentity->extra_headers->s=(char*)presentity+ size;
		memcpy(presentity->extra_headers->s, hentity->extra_headers->s, 
			hentity->extra_headers->len);
		presentity->extra_headers->len= hentity->extra_headers->len; 
		size+= hentity->extra_headers->len;
	}

	/* write the remote contact filed */
	presentity->remote_contact.s= (char*)shm_malloc(contact.len* sizeof(char));
	if(presentity->remote_contact.s==NULL)
	{
		ERR_MEM(SHARE_MEM);
	}
	memcpy(presentity->remote_contact.s, contact.s, contact.len);
	presentity->remote_contact.len= contact.len;

	presentity->event|= hentity->event;
	presentity->flag= hentity->flag;
	presentity->etag.s= NULL;
	presentity->cseq= cseq;
	presentity->desired_expires= hentity->desired_expires;
	presentity->expires= lexpire+ (int)time(NULL);
	if(BLA_SUBSCRIBE & presentity->flag)
	{
		LM_DBG("BLA_SUBSCRIBE FLAG inserted\n");
	}	
	LM_DBG("record for subscribe from %.*s to %.*s inserted in datatbase\n",
			presentity->watcher_uri->len, presentity->watcher_uri->s,
			presentity->pres_uri->len, presentity->pres_uri->s);

	if (dbmode==PUA_DB_ONLY)
	{
		if (pua_dbf.end_transaction)
		{
			if (pua_dbf.end_transaction(pua_db) < 0)
			{
				LM_ERR("in end_transaction\n");
				goto error;
			}
		}

		if (pua_dbf.start_transaction)
		{
			if (pua_dbf.start_transaction(pua_db, DB_LOCKING_WRITE) < 0)
			{
				LM_ERR("in start_transaction\n");
				goto error;
			}
		}

		if (convert_temporary_dialog_puadb(presentity) < 0)
		{
			LM_ERR("Could not convert temporary dialog into a dialog\n");
			goto error;
		}
	}
	else
	{
		if (convert_temporary_dialog(presentity) < 0)
		{
			LM_ERR("Could not convert temporary dialog into a dialog\n");
			goto error;
		}
	}

done:
	if(hentity->ua_flag == REQ_OTHER)
	{
		hentity->flag= flag;
		run_pua_callbacks( hentity, msg);
	}

	if (dbmode == PUA_DB_ONLY && pua_dbf.end_transaction && end_transaction)
	{
		if (pua_dbf.end_transaction(pua_db) < 0)
		{
			LM_ERR("in end_transaction\n");
			goto error;
		}
	}

	goto end;

error:	
        if (presentity)
	{
		if (presentity->remote_contact.s) shm_free(presentity->remote_contact.s);
	 	shm_free(presentity);
	}

	if(record_route.s)
		pkg_free(record_route.s);

	if (dbmode == PUA_DB_ONLY && pua_dbf.abort_transaction)
	{
		if (pua_dbf.abort_transaction(pua_db) < 0)
			LM_ERR("in abort_transaction\n");
	}

end:

	if(hentity)
	{	
		shm_free(hentity);
		hentity= NULL;
	}

	free_to_params(&TO);
	return;
}
Beispiel #10
0
struct lb_res_str_list *parse_resources_list(char *r_list, int has_val)
{
	struct lb_res_str_list *lb_rl;
	unsigned int n;
	unsigned int len;
	char *p;
	char *s;
	char *end;
	str name;
	str val;

	/* validate and count */
	n = 0;
	len = 0;

	p = r_list;
	do {
		/* eat spaces */
		for( ; *p && isspace(*p) ; p++);
		if (!*p) break;
		/* name and value */
		end = strchr(p,';');
		if (end)
			*end = 0;
		name.s = p;
		p = strchr(p,'=');
		if (end)
			*end = ';';
		if (p) {
			if (!has_val) {
				LM_ERR("resource must not has value!\n");
				goto error;
			}
		} else {
			if (has_val) {
				LM_ERR("resource must has value!\n");
				goto error;
			}
			p = end?end:(r_list+strlen(r_list));
		}
		for(; (p-1)!=name.s && isspace(*(p-1)) ; p-- );
		if (p==name.s) {
			LM_ERR("empty resource name around %d\n",(unsigned int)(p-r_list));
			goto error;
		}
		name.len = p-name.s;
		/* mark */
		n++;
		len += name.len;
		/* next */
		p = end+1;
	} while(end && *p);

	if (n==0) {
		LM_ERR("empty list of resorces\n");
		goto error;
	}
	LM_DBG("discovered %d resources\n",n);

	/* allocate stuff*/
	lb_rl = (struct lb_res_str_list *)pkg_malloc
		(sizeof(struct lb_res_str_list) + n*sizeof(struct lb_res_str) + len);
	if (lb_rl==NULL) {
		LM_ERR("no more pkg memory\n");
		goto error;
	}

	/* init the strucuture */
	lb_rl->n = n;
	lb_rl->resources =(struct lb_res_str*)(lb_rl+1);
	s = (char*)(lb_rl->resources + n);


	/* fill in the structures*/
	p = r_list;
	n = 0;
	do {
		/* eat spaces */
		for( ; *p && isspace(*p) ; p++);
		if (!*p) break;
		/* name .... */
		end = strchr(p,';');
		if (end)
			*end = 0;
		name.s = p;
		val.s = 0;
		p = strchr(p,'=');
		if (end)
			*end = ';';
		if (!p) {
			p = end?end:(r_list+strlen(r_list));
		} else {
			val.s = p+1;
		}
		for(; (p-1)!=name.s && isspace(*(p-1)) ; p-- );
		name.len = p-name.s;
		lb_rl->resources[n].name.len = name.len;
		lb_rl->resources[n].name.s = s;
		memcpy( s, name.s, name.len );
		s += name.len;
		/* ....and value */
		if (has_val) {
			/* eat spaces */
			for( ; *val.s && isspace(*val.s) ; val.s++);
			if (!*val.s) {
				LM_ERR("empty val !\n");
				goto error1;
			}
			val.len = ( end?end:(r_list+strlen(r_list)) ) - val.s;
			for( ; isspace(val.s[val.len-1]) ; val.len--);
			if (str2int( &val , &lb_rl->resources[n].val)!=0) {
				LM_ERR("invalid value [%.*s]\n",val.len,val.s);
				goto error1;
			}
		} else {
			lb_rl->resources[n].val = 0;
		}
		/* next */
		n++;
		p = end+1;
	} while(end && *p);

	return lb_rl;

error1:
	pkg_free(lb_rl);
error:
	return NULL;
}
Beispiel #11
0
void reader_amsr2_standard(char* fname, int fid, obsmeta* meta, model* m, observations* obs)
{
    int ncid;
    int dimid_nobs;
    size_t nobs_local;
    int varid_lon, varid_lat, varid_sst, varid_error, varid_time;
    double* lon;
    double* lat;
    double* sst;
    double* error_std;
    double* time;
    int year, month, day;
    char tunits[MAXSTRLEN];
    size_t tunits_len;
    double tunits_multiple, tunits_offset;
    char* basename;
    int model_vid;
    int k, i;

    for (i = 0; i < meta->npars; ++i)
        enkf_quit("unknown PARAMETER \"%s\"\n", meta->pars[i].name);

    basename = strrchr(fname, '/');
    if (basename == NULL)
        basename = fname;
    else
        basename += 1;

    ncw_open(fname, NC_NOWRITE, &ncid);

    ncw_inq_dimid(fname, ncid, "nobs", &dimid_nobs);
    ncw_inq_dimlen(fname, ncid, dimid_nobs, &nobs_local);
    enkf_printf("        nobs = %u\n", (unsigned int) nobs_local);

    if (nobs_local == 0) {
        ncw_close(fname, ncid);
        return;
    }

    ncw_inq_varid(fname, ncid, "lon", &varid_lon);
    lon = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_lon, lon);

    ncw_inq_varid(fname, ncid, "lat", &varid_lat);
    lat = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_lat, lat);

    ncw_inq_varid(fname, ncid, "sst", &varid_sst);
    sst = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_sst, sst);

    ncw_inq_varid(fname, ncid, "error", &varid_error);
    error_std = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_error, error_std);

    ncw_inq_varid(fname, ncid, "age", &varid_time);
    time = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_time, time);
    ncw_inq_attlen(fname, ncid, varid_time, "units", &tunits_len);
    ncw_get_att_text(fname, ncid, varid_time, "units", tunits);
    basename[14] = 0;
    if (!str2int(&basename[12], &day))
        enkf_quit("AMSR2 reader: could not convert file name \"%s\" to date", fname);
    basename[12] = 0;
    if (!str2int(&basename[10], &month))
        enkf_quit("AMSR2 reader: could not convert file name \"%s\" to date", fname);
    basename[10] = 0;
    if (!str2int(&basename[6], &year))
        enkf_quit("AMSR2 reader: could not convert file name \"%s\" to date", fname);
    snprintf(&tunits[tunits_len], MAXSTRLEN - tunits_len, " since %4d-%02d-%02d", year, month, day);

    ncw_close(fname, ncid);

    tunits_convert(tunits, &tunits_multiple, &tunits_offset);

    model_vid = model_getvarid(m, obs->obstypes[obstype_getid(obs->nobstypes, obs->obstypes, meta->type)].varname, 1);
    k = grid_gettoplayerid(model_getvargrid(m, model_vid));

    for (i = 0; i < (int) nobs_local; ++i) {
        observation* o;
        obstype* ot;

        obs_checkalloc(obs);
        o = &obs->data[obs->nobs];

        o->product = st_findindexbystring(obs->products, meta->product);
        assert(o->product >= 0);
        o->type = obstype_getid(obs->nobstypes, obs->obstypes, meta->type);
        assert(o->type >= 0);
        ot = &obs->obstypes[o->type];
        o->instrument = st_add_ifabscent(obs->instruments, "AMSR-2", -1);
        o->id = obs->nobs;
        o->fid = fid;
        o->batch = 0;
        o->value = sst[i];
        o->std = error_std[i];
        o->lon = lon[i];
        o->lat = lat[i];
        o->depth = 0.0;
        o->status = model_xy2fij(m, model_vid, o->lon, o->lat, &o->fi, &o->fj);
        if (!obs->allobs && o->status == STATUS_OUTSIDEGRID)
            continue;
        if ((o->status == STATUS_OK) && (o->lon <= ot->xmin || o->lon >= ot->xmax || o->lat <= ot->ymin || o->lat >= ot->ymax || o->depth <= ot->zmin || o->depth >= ot->zmax))
            o->status = STATUS_OUTSIDEOBSDOMAIN;
        o->fk = (double) k;
        o->date = time[i] * tunits_multiple + tunits_offset;
        o->aux = -1;

        obs->nobs++;
    }

    free(lon);
    free(lat);
    free(sst);
    free(error_std);
    free(time);
}
Beispiel #12
0
/*! \brief
 * Fills the common part (for all contacts) of the info structure
 */
static inline ucontact_info_t* pack_ci( struct sip_msg* _m, contact_t* _c,
		unsigned int _e, unsigned int _f, int _use_regid)
{
	static ucontact_info_t ci;
	static str no_ua = str_init("n/a");
	static str callid;
	static str path_received = {0,0};
	static str path;
	static str received = {0,0};
	static int received_found;
	static unsigned int allowed, allow_parsed;
	static struct sip_msg *m = 0;
	int_str val;

	if (_m!=0) {
		memset( &ci, 0, sizeof(ucontact_info_t));

		/* Get callid of the message */
		callid = _m->callid->body;
		trim_trailing(&callid);
		if (callid.len > CALLID_MAX_SIZE) {
			rerrno = R_CALLID_LEN;
			LM_ERR("callid too long\n");
			goto error;
		}
		ci.callid = &callid;

		/* Get CSeq number of the message */
		if (str2int(&get_cseq(_m)->number, (unsigned int*)&ci.cseq) < 0) {
			rerrno = R_INV_CSEQ;
			LM_ERR("failed to convert cseq number\n");
			goto error;
		}

		/* set received socket */
		if (_m->flags&sock_flag) {
			ci.sock = get_sock_val(_m);
			if (ci.sock==0)
				ci.sock = _m->rcv.bind_address;
		} else {
			ci.sock = _m->rcv.bind_address;
		}

		/* set tcp connection id */
		if (_m->rcv.proto==PROTO_TCP || _m->rcv.proto==PROTO_TLS
				|| _m->rcv.proto==PROTO_WS  || _m->rcv.proto==PROTO_WSS) {
			ci.tcpconn_id = _m->rcv.proto_reserved1;
		} else {
			ci.tcpconn_id = -1;
		}

		/* additional info from message */
		if (parse_headers(_m, HDR_USERAGENT_F, 0) != -1 && _m->user_agent &&
				_m->user_agent->body.len>0 && _m->user_agent->body.len<MAX_UA_SIZE) {
			ci.user_agent = &_m->user_agent->body;
		} else {
			ci.user_agent = &no_ua;
		}

		/* extract Path headers */
		if (path_enabled) {
			if (build_path_vector(_m, &path, &path_received) < 0) {
				rerrno = R_PARSE_PATH;
				goto error;
			}
			if (path.len && path.s) {
				ci.path = &path;
				if (path_mode != PATH_MODE_OFF) {
					/* save in msg too for reply */
					if (set_path_vector(_m, &path) < 0) {
						rerrno = R_PARSE_PATH;
						goto error;
					}
				}
			}
		}

		ci.last_modified = act_time;

		/* set flags */
		ci.flags  = _f;
		getbflagsval(0, &ci.cflags);

		/* get received */
		if (path_received.len && path_received.s) {
			ci.cflags |= ul.nat_flag;
			ci.received = path_received;
		}

		ci.server_id = server_id;
		if(_m->contact) {
			_c = (((contact_body_t*)_m->contact->parsed)->contacts);
			if(_c->instance!=NULL && _c->instance->body.len>0) {
				ci.instance = _c->instance->body;
				LM_DBG("set instance[%.*s]\n", ci.instance.len, ci.instance.s);
			}
			if(_use_regid && _c->instance!=NULL && _c->reg_id!=NULL && _c->reg_id->body.len>0) {
				if(str2int(&_c->reg_id->body, &ci.reg_id)<0 || ci.reg_id==0)
				{
					LM_ERR("invalid reg-id value\n");
					goto error;
				}
			}
		}

		allow_parsed = 0; /* not parsed yet */
		received_found = 0; /* not found yet */
		m = _m; /* remember the message */
	}
	else {
		memset( &ci.instance, 0, sizeof(str));
	}

	if(_c!=0) {
		/* hook uri address - should be more than 'sip:' chars */
		if(_c->uri.s!=NULL && _c->uri.len>4)
			ci.c = &_c->uri;

		/* Calculate q value of the contact */
		if (m && m->id == q_override_msg_id)
		{
			ci.q = q_override_value;
		}
		else if (calc_contact_q(_c->q, &ci.q) < 0) {
			rerrno = R_INV_Q;
			LM_ERR("failed to calculate q\n");
			goto error;
		}

		/* set expire time */
		ci.expires = _e;

		/* Get methods of contact */
		if (_c->methods) {
			if (parse_methods(&(_c->methods->body), &ci.methods) < 0) {
				rerrno = R_PARSE;
				LM_ERR("failed to parse contact methods\n");
				goto error;
			}
		} else {
			/* check on Allow hdr */
			if (allow_parsed == 0) {
				if (m && parse_allow( m ) != -1) {
					allowed = get_allow_methods(m);
				} else {
					allowed = ALL_METHODS;
				}
				allow_parsed = 1;
			}
			ci.methods = allowed;
		}

		/* get received */
		if (ci.received.len==0) {
			if (_c->received) {
				ci.received = _c->received->body;
			} else {
				if (received_found==0) {
					memset(&val, 0, sizeof(int_str));
					if (rcv_avp_name.n!=0
							&& search_first_avp(rcv_avp_type, rcv_avp_name, &val, 0)
							&& val.s.len > 0) {
						if (val.s.len>RECEIVED_MAX_SIZE) {
							rerrno = R_CONTACT_LEN;
							LM_ERR("received too long\n");
							goto error;
						}
						received = val.s;
					} else {
						received.s = 0;
						received.len = 0;
					}
					received_found = 1;
				}
				ci.received = received;
			}
		}
		if(_c->instance!=NULL && _c->instance->body.len>0)
			ci.instance = _c->instance->body;
		if(_use_regid && _c->instance!=NULL && _c->reg_id!=NULL && _c->reg_id->body.len>0) {
			if(str2int(&_c->reg_id->body, &ci.reg_id)<0 || ci.reg_id==0)
			{
				LM_ERR("invalid reg-id value\n");
				rerrno = R_INV_REGID;
				goto error;
			}
		}
		if(sruid_next(&_reg_sruid)<0)
			goto error;
		ci.ruid = _reg_sruid.uid;
		LM_DBG("generated ruid is: %.*s\n", ci.ruid.len, ci.ruid.s);
	}

	return &ci;
error:
	return 0;
}
Beispiel #13
0
int CCBLRedis::onLoad() {
  AmConfigReader cfg;

  string redis_server = "127.0.0.1";
  string redis_port = "6379";
  string redis_reconnect_timers = "5,10,20,50,100,500,1000";
  string redis_connections = "10";
  string redis_max_conn_wait = "1000";
  pass_on_bl_unavailable = false;

  full_logging = false;

  if(cfg.loadPluginConf(MOD_NAME)) {
    INFO(MOD_NAME "configuration  file not found, assuming default "
	 "configuration is fine\n");
  } else {
    redis_server = cfg.getParameter("redis_server", redis_server);
    redis_port = cfg.getParameter("redis_port", redis_port);
    redis_reconnect_timers =
      cfg.getParameter("redis_reconnect_timers", redis_reconnect_timers);
    redis_connections = cfg.getParameter("redis_connections", redis_connections);
    redis_max_conn_wait = cfg.getParameter("redis_max_conn_wait", redis_max_conn_wait);
    full_logging = cfg.getParameter("redis_full_logging", "no")=="yes";

    pass_on_bl_unavailable = cfg.getParameter("pass_on_bl_unavailable", "no")=="yes";
  }

  unsigned int i_redis_connections;
  if (str2i(redis_connections, i_redis_connections)) {
    ERROR("could not understand redis_connections=%s\n", redis_connections.c_str());
    return -1;
  }

  unsigned int i_redis_port;
  if (str2i(redis_port, i_redis_port)) {
    ERROR("could not understand redis_port=%s\n", redis_port.c_str());
    return -1;
  }

 unsigned int i_redis_max_conn_wait;
  if (str2i(redis_max_conn_wait, i_redis_max_conn_wait)) {
    ERROR("could not understand redis_max_conn_wait=%s\n", redis_max_conn_wait.c_str());
    return -1;
  }

 std::vector<unsigned int> reconnect_timers;
 std::vector<string> timeouts_v = explode(redis_reconnect_timers, ",");
  for (std::vector<string>::iterator it=
         timeouts_v.begin(); it != timeouts_v.end(); it++) {
    int r;
    if (!str2int(*it, r)) {
      ERROR("REDIS reconnect timeout '%s' not understood\n",
            it->c_str());
      return -1;
    }
    reconnect_timers.push_back(r);
  }

  connection_pool.set_config(redis_server, i_redis_port,
			     reconnect_timers, i_redis_max_conn_wait);
  connection_pool.add_connections(i_redis_connections);
  connection_pool.start();

  DBG("setting max number max_retries to %u (as connections)\n", i_redis_connections);
  max_retries = i_redis_connections;

  return 0;
}
Beispiel #14
0
enum MqErrorE
pReadHDR (
  register struct MqS  * context,
  struct MqS ** a_context
)
{
  struct MqReadS * read = context->link.read;
  MQ_SIZE ctxId;
  MQ_SIZE size;
  register int const string = context->config.isString;
  register struct HdrS * cur;
  int debug;
  register struct MqBufferS * bdy;
  struct MqBufferS * hdr = read->hdr;

  // 1. preset context
  *a_context = context;

  // 2. read
  MqErrorSwitch (pIoRead (context->link.io, hdr, HDR_SIZE));
  cur = (struct HdrS *) hdr->cur.B;

//MqDLogV (context, __func__, 0, "START (%c%c%c%c)\n", cur->tok[0], cur->tok[1], cur->tok[2], cur->tok[3]);
//pReadLog(context, "pReadHDR->1");

  // check "HDR"
#ifdef MQ_SAVE
  if (unlikely (strncmp (cur->ID, "HDR", 3))) {
    MQ_BUF save = MqBufferCreate (MQ_ERROR_PANIC, 1000);
    do {
      MqBufferAppendC (save, (MQ_STR) hdr->data);
    } while (pIoRead (context->link.io, hdr, HDR_SIZE) == MQ_OK);
    *(hdr->data+hdr->cursize) = '\0';
    MqBufferAppendC (save, (MQ_STR) hdr->data);
    MqErrorDb (MQ_ERROR_INVALID_HEADER);
    MqErrorSAppendV (context, "but got: %s", (MQ_STR) save->data);
    MqBufferDelete (&save);
    return MQ_ERROR;
  }
#endif

  // 3. read binary data
  if (unlikely(string)) {
    ctxId  = str2int(cur->ctxId.S,NULL,16);
    size   = str2int(cur->size.S,NULL,16);
  } else {
    ctxId  = cur->ctxId.B;
    size   = cur->size.B;
    // 3.b fix byte-order
    if (context->link.bits.endian) {
      pSwap4 (&ctxId);
      pSwap4 (&size);
    }
  }

  // 4. set my context
  if (ctxId != context->link.ctxId) {
    // check if ctxId is out of range
    if (ctxId > context->link.ctxIdP->link.ctxIdR) 
	return MqErrorV (context, __func__, -1, "invalid context-id '%i'", ctxId);
    // do the context-switch if the message does !!not!! belongs to the
    // original context
    context = context->link.ctxIdP->link.ctxIdA[ctxId];
    // check if entry was already deleted
    if (!context) return MQ_CONTINUE;
    *a_context = context;
  }
//MqDLogV (context, __func__, 0, "cur->ctxId.B<%i>, context->context.ctxId<%i>\n", cur->ctxId.B, context->context.ctxId);
//MqDLogV (context, __func__, 0, "hex\n<%s>\n", pLogHEX (hdr->data, sizeof (struct HdrS)));
  debug = context->config.debug;
  context->link._trans = cur->trans;

  // 6. log message
  if (unlikely (debug >= 5)) {
    hdr->type = MQ_STRING_TYPE(string);
    pLogHDR (context, __func__, 5, hdr);
  }

  // 7. setup read
  read = context->link.read;
  read->handShake = (enum MqHandShakeE) cur->code;
  read->returnNum = 0;
  // MqReadBDY need the original "header", save this header in the current context
  read->hdrorig = hdr;
  bdy = read->bdy;

  // 8. read token
  pTokenSetCurrent (context->link.srvT, cur->tok);

  // 9. read BDY
  if ((bdy->cursize = size)) {
    bdy->type = MQ_STRING_TYPE(string);
    if (unlikely (debug >= 6))
      MqLogV (context, __func__, 6, "BDY -> " MQ_FORMAT_Z " bytes\n", size);

    // 1. read
    MqErrorSwitch (pIoRead (context->link.io, bdy, bdy->cursize));

    // 2. read 'HDR'
#ifdef MQ_SAVE
    if (unlikely (strncmp (bdy->cur.C, "BDY", 3))) {
      return MqErrorV (context, __func__, "expect 'BDY' but got '%s'", bdy->cur.C);
    }
#endif
    bdy->cur.B += BDY_NumItems_S;

    // 3. read NumItems
    if (unlikely(string)) {
      bdy->numItems = str2int(bdy->cur.C,NULL,16);
    } else {
      if (context->link.bits.endian) {
	pSwapBDY(bdy->data);
      }
      bdy->numItems = iBufU2INT(bdy->cur);
    }
    bdy->cur.B = (bdy->data + BDY_SIZE);

    // 4. if required, log package
    if (unlikely (debug >= 7 && size > BDY_SIZE))
      pLogBDY (context, __func__, 7, bdy);

    // 5. if in a longterm-transaction, read the transaction-item
    if (read->handShake == MQ_HANDSHAKE_TRANSACTION) {
      MQ_CBI itm; MQ_SIZE len;
      enum MqErrorE ret;
      MqErrorCheck (MqReadN (context, &itm, &len));
      // answer first call with an empty return package
      if (context->link._trans != 0) {
	MqErrorCheck (MqSendSTART  (context));
	read->handShake = MQ_HANDSHAKE_START;
	ret = MqSendRETURN (context);
	read->handShake = MQ_HANDSHAKE_TRANSACTION;
	MqErrorCheck (ret);
	context->link._trans = 0;
      }
      read->trans_item = itm; 
      read->trans_size = len;
    }
  }

  // reset data
  read->canUndo = MQ_NO;
  read->save = NULL;
  
  // 11. check if it's a System-pToken
  // this line have to use the 'return' because pTokenCheckSystem usually return
  // MQ_CONTINUE if a system token (_*) was found
  return pTokenCheckSystem (context->link.srvT);

error:
  return MqErrorStack (context);
}
Beispiel #15
0
void reg_tm_cback(struct cell *t, int type, struct tmcb_params *ps)
{
	struct sip_msg *msg;
	reg_tm_cb_t *cb_param;
	int statuscode = 0;
	unsigned int exp = 0;
	reg_record_t *rec;
	struct hdr_field *c_ptr, *head_contact;
	struct uac_credential crd;
	contact_t *contact;
	struct authenticate_body *auth = NULL;
	static struct authenticate_nc_cnonce auth_nc_cnonce;
	HASHHEX response;
	str *new_hdr;
	time_t now;

	if(ps==NULL || ps->rpl==NULL) {
		LM_ERR("wrong ps parameter\n");
		return;
	}
	if(ps->param==NULL || *ps->param==NULL) {
		LM_ERR("null callback parameter\n");
		return;
	}
	cb_param = (reg_tm_cb_t *)*ps->param;
	if(cb_param->uac == NULL) {
		LM_ERR("null record\n");
		return;
	}
	statuscode = ps->code;
	now = time(0);
	LM_DBG("tm [%p] notification cb for %s [%d] reply at [%d]\n",
			t, (ps->rpl==FAKED_REPLY)?"FAKED_REPLY":"", statuscode, (unsigned int)now);

	if(statuscode<200) return;

	lock_get(&reg_htable[cb_param->hash_index].lock);
	rec = reg_htable[cb_param->hash_index].first;
	while(rec) {
		if (rec==cb_param->uac) {
			break;
		}
		rec = rec->next;
	}
	if(!rec) {
		LM_ERR("record [%p] not found on hash index [%d]\n",
		cb_param->uac, cb_param->hash_index);
		lock_release(&reg_htable[cb_param->hash_index].lock);
		return;
	}
	reg_print_record(rec);

	switch(statuscode) {
	case 200:
		msg = ps->rpl;
		if(msg==FAKED_REPLY) {
			LM_ERR("FAKED_REPLY\n");
			goto done;
		}
		if (parse_headers(msg, HDR_EOH_F, 0) == -1) {
			LM_ERR("failed to parse headers\n");
			goto done;
		}
		if (msg->contact) {
			c_ptr = msg->contact;
			while(c_ptr) {
				if (c_ptr->type == HDR_CONTACT_T) {
					if (!c_ptr->parsed && (parse_contact(c_ptr)<0)) {
						LM_ERR("failed to parse Contact body\n");
						goto done;
					}
				}
				c_ptr = c_ptr->next;
			}
		} else {
			LM_ERR("No contact header in received 200ok\n");
			goto done;
		}
		head_contact = msg->contact;
		contact = ((contact_body_t*)msg->contact->parsed)->contacts;
		while (contact) {
			/* Check for binding */
			if (contact->uri.len==rec->contact_uri.len &&
				strncmp(contact->uri.s,rec->contact_uri.s,contact->uri.len)==0){
				if (contact->expires && contact->expires->body.len) {
					if (str2int(&contact->expires->body, &exp)<0) {
						LM_ERR("Unable to extract expires from [%.*s]"
							" for binding [%.*s]\n",
							contact->expires->body.len,
							contact->expires->body.s,
							contact->uri.len, contact->uri.s);
					} else {
						rec->expires = exp;
					}
				}
				break;
			}
					
			/* get the next contact */
			if (contact->next == NULL) {
				contact = NULL;
				c_ptr = head_contact->next;
				while(c_ptr) {
					if (c_ptr->type == HDR_CONTACT_T) {
						head_contact = c_ptr;
						contact = ((contact_body_t*)c_ptr->parsed)->contacts;
						break;
					}
					c_ptr = c_ptr->next;
				}
			} else {
				contact = contact->next;
			}
		}
		rec->state = REGISTERED_STATE;
		rec->registration_timeout = now + rec->expires - timer_interval;
		break;

	case WWW_AUTH_CODE:
	case PROXY_AUTH_CODE:
		msg = ps->rpl;
		if(msg==FAKED_REPLY) {
			LM_ERR("FAKED_REPLY\n");
			goto done;
		}

		if (rec->auth_user.s==NULL || rec->auth_user.len==0 ||
			rec->auth_password.s==NULL || rec->auth_password.len==0) {
			LM_ERR("Credentials not provisioned\n");
			rec->state = WRONG_CREDENTIALS_STATE;
			rec->registration_timeout = 0;
			lock_release(&reg_htable[cb_param->hash_index].lock);
			return;
		}

		if (statuscode==WWW_AUTH_CODE) {
			if (0 == parse_www_authenticate_header(msg))
				auth = get_www_authenticate(msg);
		} else if (statuscode==PROXY_AUTH_CODE) {
			if (0 == parse_proxy_authenticate_header(msg))
				auth = get_proxy_authenticate(msg);
		}
		if (auth == NULL) {
			LM_ERR("Unable to extract authentication info\n");
			goto done;
		}
		LM_DBG("flags=[%d] realm=[%.*s] domain=[%.*s] nonce=[%.*s]"
			" opaque=[%.*s] qop=[%.*s]\n",
			auth->flags,
			auth->realm.len, auth->realm.s,
			auth->domain.len, auth->domain.s,
			auth->nonce.len, auth->nonce.s,
			auth->opaque.len, auth->opaque.s,
			auth->qop.len, auth->qop.s);

		switch(rec->state) {
		case REGISTERING_STATE:
			break;
		case AUTHENTICATING_STATE:
			/* We already sent an authenticated REGISTER and we are still challanged! */
			LM_ERR("Wrong credentials for \n");
			rec->state = WRONG_CREDENTIALS_STATE;
			rec->registration_timeout = 0;
			lock_release(&reg_htable[cb_param->hash_index].lock);
			return;
		default:
			LM_ERR("Unexpected [%d] notification cb in state [%d]\n",
				statuscode, rec->state);
			goto done;
		}

		/* perform authentication */
		if (auth->realm.s && auth->realm.len) {
			crd.realm.s = auth->realm.s; crd.realm.len = auth->realm.len;
		} else {
			LM_ERR("No realm found\n");
			goto done;
		}
		crd.user.s = rec->auth_user.s; crd.user.len = rec->auth_user.len;
		crd.passwd.s = rec->auth_password.s; crd.passwd.len = rec->auth_password.len;

		memset(&auth_nc_cnonce, 0, sizeof(struct authenticate_nc_cnonce));
		uac_auth_api._do_uac_auth(&register_method, &rec->td.rem_target, &crd,
					auth, &auth_nc_cnonce, response);
		new_hdr = uac_auth_api._build_authorization_hdr(statuscode, &rec->td.rem_target,
					&crd, auth, &auth_nc_cnonce, response);
		if (!new_hdr) {
			LM_ERR("failed to build authorization hdr\n");
			goto done;
		}
		if(send_register(cb_param->hash_index, rec, new_hdr)==1) {
			rec->state = AUTHENTICATING_STATE;
		} else {
			rec->state = INTERNAL_ERROR_STATE;
		}
		break;

	default:
		if(statuscode<400 && statuscode>=300) {
			LM_ERR("Redirection not implemented yet\n");
			rec->state = INTERNAL_ERROR_STATE;
		} else {
			/* we got an error from the server */
			rec->state = REGISTRAR_ERROR_STATE;
			rec->registration_timeout = now + rec->expires - timer_interval;
			
		}
	}

	lock_release(&reg_htable[cb_param->hash_index].lock);

	return;
done:
	rec->state = INTERNAL_ERROR_STATE;
	rec->registration_timeout = now + rec->expires;
	lock_release(&reg_htable[cb_param->hash_index].lock);
	return;
}
Beispiel #16
0
int atoi(const char *src)
{
  long val;
  str2int(src, 10, (long) INT_MIN, (long) INT_MAX, &val);
  return (int) val;
}
Beispiel #17
0
int main(int argc, char **argv){
	if(argc < 6 || argc > 7){
		printf("Wrong number of arguments!");
		exit(-1);
	}
	
	int workerID = str2int(argv[1]);
	int nBuffers = str2int(argv[2]);
	float sleepTime = str2float(argv[3]);
	int msgID = str2int(argv[4]);
	int shmID = str2int(argv[5]);
	int semID;
	BOOL lock = FALSE;
	if(argc == 7){ //if a semID is given
		semID = str2int(argv[6]);
		lock = TRUE;
	}

	//connect to message queue
	int msgQ = msgID;
	if(msgQ == -1){
		perror("Error connecting to message queue");
		exit(-1);
	}

	//send startup message
	struct message msg;
	msg.mtype = 1;
	msg.workerID = workerID;
	msg.sleepTime = sleepTime;

	if(msgsnd(msgQ, &msg, sizeof(struct message) - sizeof(long), 0) == -1){
		perror("Error sending message");
		exit(-1);
	}

	//attatch to shared memory
	int *shm = shmat(shmID, (void *)0, 0);
	if(shm == (int *) -1){
		perror("Error attatching to shared memory");
		exit(-1);
	}
	
	//===================== PART 5 ==============================
	
	//use semaphores
	if(lock){
		int i;
		int currentBuffer = workerID;
		for(i=0; i<nBuffers; i++){
			int j;
	
			for(j=0; j<2; j++){ //read twice
				wait(currentBuffer, semID, nBuffers);
		
				int read = shm[currentBuffer];
	
				if(usleep(sleepTime*1000000) == -1){
					perror("Error sleeping");
					exit(-1);
				}
	
				//check if changed
				if(shm[currentBuffer] != read){
					msg.mtype = 3;
					msg.workerID = workerID;
					msg.changedBuffer = currentBuffer;
					msg.initVal = read;
					msg.newVal = shm[currentBuffer];
					if(msgsnd(msgQ, &msg, sizeof(struct message), 0) == -1){
						perror("Error sending message");
						exit(-1);
					}
				}

				signal(currentBuffer, semID, nBuffers);
		
				currentBuffer += workerID;
				if(currentBuffer >= nBuffers)
					currentBuffer -= nBuffers;
			}
	
			//write
			wait(currentBuffer, semID, nBuffers);

			int read = shm[currentBuffer];
	
			if(usleep(sleepTime*1000000) == -1){
				perror("Error sleeping");
				exit(-1);
			}
			
			shm[currentBuffer] = read | (1<<(workerID -1));

			signal(currentBuffer, semID, nBuffers);
	
			currentBuffer += workerID;
			if(currentBuffer >= nBuffers)
				currentBuffer -= nBuffers;
	
		}
	}

	//===================== PART 3/4 ============================

	//dont use semaphores
	else{	
		int i;
		int currentBuffer = workerID;
		for(i=0; i<nBuffers; i++){
			int j;

			for(j=0; j<2; j++){ //read twice
				int read = shm[currentBuffer];
	
				if(usleep(sleepTime*1000000) == -1){
					perror("Error sleeping");
					exit(-1);
				}
	
				//check if changed
				if(shm[currentBuffer] != read){
					msg.mtype = 3;
					msg.workerID = workerID;
					msg.changedBuffer = currentBuffer;
					msg.initVal = read;
					msg.newVal = shm[currentBuffer];
					if(msgsnd(msgQ, &msg, sizeof(struct message), 0) == -1){
						perror("Error sending message");
						exit(-1);
					}
				}
				
				currentBuffer += workerID;
				if(currentBuffer >= nBuffers)
					currentBuffer -= nBuffers;
			}
	
			//write
			int read = shm[currentBuffer];
	
			if(usleep(sleepTime*1000000) == -1){
				perror("Error sleeping");
				exit(-1);
			}
			
			shm[currentBuffer] = read | (1<<(workerID -1));
	
			currentBuffer += workerID;
			if(currentBuffer >= nBuffers)
				currentBuffer -= nBuffers;
	
		}
	}
	
	//cleanup message
	msg.mtype = 2;
	msg.workerID = workerID;
	if(msgsnd(msgQ, &msg, sizeof(struct message), 0) == -1){
		perror("Error sending message");
		exit(-1);
	}

	exit(0);
}
Beispiel #18
0
long atol(const char *src)
{
  long val;
  str2int(src, 10, LONG_MIN, LONG_MAX, &val);
  return val;
}
Beispiel #19
0
int apply_cseq_op(struct sip_msg *msg,int val)
{
	int offset,len,olen;
	struct lump *tmp;
	char *buf,*obuf;
	unsigned int cseq_no;
	str pkg_cseq;

	if (!msg) {
		LM_ERR("null pointer provided\n");
		return -1;
	}

	if(parse_headers(msg, HDR_CSEQ_F, 0) <0 ) {
		LM_ERR("failed to parse headers \n");
		return -1;
	}

	if (str2int(&(((struct cseq_body *)msg->cseq->parsed)->number),&cseq_no) < 0) {
		LM_ERR("Failed to convert cseq to integer \n");
		return -1;
	}

	cseq_no=cseq_no+val;
	obuf = int2str(cseq_no,&olen);
	if (obuf == NULL) {
		LM_ERR("Failed to convert new integer to string \n");
		return -1;
	}

	pkg_cseq.s = pkg_malloc(olen);
	if (!pkg_cseq.s) {
		LM_ERR("No more pkg mem \n");
		return -1;
	}

	memcpy(pkg_cseq.s,obuf,olen);
	pkg_cseq.len = olen;
	
	buf = msg->buf;
	len = ((struct cseq_body *)msg->cseq->parsed)->number.len;
	offset = ((struct cseq_body *)msg->cseq->parsed)->number.s - buf;

	if ((tmp = del_lump(msg,offset,len,0)) == 0)
	{
		LM_ERR("failed to remove the existing CSEQ\n");
		pkg_free(pkg_cseq.s);
		return -1;
	}

	if (insert_new_lump_after(tmp,pkg_cseq.s,pkg_cseq.len,0) == 0)
	{
		LM_ERR("failed to insert new CSEQ\n");
		pkg_free(pkg_cseq.s);
		return -1;
	}

	LM_DBG("Message CSEQ translated from [%.*s] to [%.*s]\n",
			((struct cseq_body *)msg->cseq->parsed)->number.len,
			((struct cseq_body *)msg->cseq->parsed)->number.s,pkg_cseq.len,
			pkg_cseq.s);
	
	return cseq_no;
}
Beispiel #20
0
int ht_table_spec(char *spec)
{
	keyvalue_t kval;
	str name;
	str dbtable = {0, 0};
	unsigned int autoexpire = 0;
	unsigned int size = 4;
	unsigned int dbmode = 0;
	unsigned int updateexpire = 1;
	str in;
	str tok;
	param_t *pit=NULL;
	int_str ival;
	int itype;

	if(!shm_initialized())
	{
		LM_ERR("shared memory was not initialized\n");
		return -1;
	}
	/* parse: name=>dbtable=abc;autoexpire=123;size=123 */
	in.s = spec;
	in.len = strlen(in.s);
	if(keyvalue_parse_str(&in, KEYVALUE_TYPE_PARAMS, &kval)<0)
	{
		LM_ERR("failed parsing: %.*s\n", in.len, in.s);
		return -1;
	}
	name = kval.key;
	itype = PV_VAL_NONE;
	memset(&ival, 0, sizeof(int_str));

	for (pit = kval.u.params; pit; pit=pit->next)
	{
		tok = pit->body;
		if(pit->name.len==7 && strncmp(pit->name.s, "dbtable", 7)==0) {
			dbtable = tok;
			LM_DBG("htable [%.*s] - dbtable [%.*s]\n", name.len, name.s,
					dbtable.len, dbtable.s);
		} else if(pit->name.len==10 && strncmp(pit->name.s, "autoexpire", 10)==0) {
			if(str2int(&tok, &autoexpire)!=0)
				goto error;
			LM_DBG("htable [%.*s] - expire [%u]\n", name.len, name.s,
					autoexpire);
		} else if(pit->name.len==4 && strncmp(pit->name.s, "size", 4)==0) {
			if(str2int(&tok, &size)!=0)
				goto error;
			LM_DBG("htable [%.*s] - size [%u]\n", name.len, name.s,
					size);
		} else if(pit->name.len==6 && strncmp(pit->name.s, "dbmode", 6)==0) {
			if(str2int(&tok, &dbmode)!=0)
				goto error;
			LM_DBG("htable [%.*s] - dbmode [%u]\n", name.len, name.s,
					dbmode);
		} else if(pit->name.len==7 && strncmp(pit->name.s, "initval", 7)==0) {
			if(str2sint(&tok, &ival.n)!=0)
				goto error;
			itype = PV_VAL_INT;
			LM_DBG("htable [%.*s] - initval [%d]\n", name.len, name.s,
					ival.n);
		} else if(pit->name.len == 12 && strncmp(pit->name.s, "updateexpire", 12) == 0) {
			if(str2int(&tok, &updateexpire) != 0)
				goto error;

			LM_DBG("htable [%.*s] - updateexpire [%u]\n", name.len, name.s, updateexpire); 
		} else { goto error; }
	}

	return ht_add_table(&name, autoexpire, &dbtable, size, dbmode,
			itype, &ival, updateexpire);

error:
	LM_ERR("invalid htable parameter [%.*s]\n", in.len, in.s);
	return -1;
}
Beispiel #21
0
int main (int argc, char** argv)
{
    int socket_fd = -1;
    int optInfo = 0;
    int optClock = 0;
    int optStethoscope = 0;
    int optSockets = 0;
    double runtime;
    int hasDRAM = 0;
    int c;
    bstring argString;
    bstring eventString = bfromcstr("CLOCK");
    int numSockets=1;
    int numThreads=0;
    int threadsSockets[MAX_NUM_NODES*2];
    int threads[MAX_NUM_THREADS];

    threadsSockets[0] = 0;
    
    if (argc == 1)
    {
    	HELP_MSG;
    	exit (EXIT_SUCCESS);
    }

    while ((c = getopt (argc, argv, "+c:hiM:ps:v")) != -1)
    {
        switch (c)
        {
            case 'c':
                CHECK_OPTION_STRING;
                numSockets = bstr_to_cpuset_physical((uint32_t*) threadsSockets, argString);
                bdestroy(argString);
                optSockets = 1;
                break;

            case 'h':
                HELP_MSG;
                exit (EXIT_SUCCESS);
            case 'i':
                optInfo = 1;
                break;
            case 'M':  /* Set MSR Access mode */
                CHECK_OPTION_STRING;
                accessClient_setaccessmode(str2int((char*) argString->data));
                bdestroy(argString);
                break;
            case 'p':
                optClock = 1;
                break;
            case 's':
                CHECK_OPTION_STRING;
                optStethoscope = str2int((char*) argString->data);
                bdestroy(argString);
                break;
            case 'v':
                VERSION_MSG;
                exit (EXIT_SUCCESS);
            case '?':
            	if (optopt == 's' || optopt == 'M' || optopt == 'c')
            	{
            		HELP_MSG;
            	}
                else if (isprint (optopt))
                {
                    fprintf (stderr, "Unknown option `-%c'.\n", optopt);
                }
                else
                {
                    fprintf (stderr,
                            "Unknown option character `\\x%x'.\n",
                            optopt);
                }
                exit( EXIT_FAILURE);
            default:
                HELP_MSG;
                exit (EXIT_SUCCESS);
        }
    }

    if (!lock_check())
    {
        fprintf(stderr,"Access to performance counters is locked.\n");
        exit(EXIT_FAILURE);
    }
    
    if (optClock && optind == argc)
    {
    	fprintf(stderr,"Commandline option -p requires an executable.\n");
    	exit(EXIT_FAILURE);
    }
    if (optSockets && !optStethoscope && optind == argc)
    {
    	fprintf(stderr,"Commandline option -c requires an executable if not used in combination with -s.\n");
    	exit(EXIT_FAILURE);
    }

    if (cpuid_init() == EXIT_FAILURE)
    {
        fprintf(stderr, "CPU not supported\n");
        exit(EXIT_FAILURE);
    }
    
    if (numSockets > cpuid_topology.numSockets)
    {
    	fprintf(stderr, "System has only %d sockets but %d are given on commandline\n",
    			cpuid_topology.numSockets, numSockets);
    	exit(EXIT_FAILURE);
    }

    numa_init(); /* consider NUMA node as power unit for the moment */
    accessClient_init(&socket_fd);
    msr_init(socket_fd);
    timer_init();

    /* check for supported processors */
    if ((cpuid_info.model == SANDYBRIDGE_EP) ||
            (cpuid_info.model == SANDYBRIDGE) ||
            (cpuid_info.model == IVYBRIDGE) ||
            (cpuid_info.model == IVYBRIDGE_EP) ||
            (cpuid_info.model == HASWELL) ||
            (cpuid_info.model == NEHALEM_BLOOMFIELD) ||
            (cpuid_info.model == NEHALEM_LYNNFIELD) ||
            (cpuid_info.model == NEHALEM_WESTMERE))
    {
        power_init(numa_info.nodes[0].processors[0]);
    }
    else
    {
        fprintf (stderr, "Query Turbo Mode only supported on Intel Nehalem/Westmere/SandyBridge/IvyBridge/Haswell processors!\n");
        exit(EXIT_FAILURE);
    }

    double clock = (double) timer_getCpuClock();

    printf(HLINE);
    printf("CPU name:\t%s \n",cpuid_info.name);
    printf("CPU clock:\t%3.2f GHz \n",  (float) clock * 1.E-09);
    printf(HLINE);

    if (optInfo)
    {
        if (power_info.turbo.numSteps != 0)
        {
            printf("Base clock:\t%.2f MHz \n",  power_info.baseFrequency );
            printf("Minimal clock:\t%.2f MHz \n",  power_info.minFrequency );
            printf("Turbo Boost Steps:\n");
            for (int i=0; i < power_info.turbo.numSteps; i++ )
            {
                printf("C%d %.2f MHz \n",i+1,  power_info.turbo.steps[i] );
            }
        }
        printf(HLINE);
    }

    if (cpuid_info.model == SANDYBRIDGE_EP)
    {
        hasDRAM = 1;
    }
    else if ((cpuid_info.model != SANDYBRIDGE) &&
            (cpuid_info.model != SANDYBRIDGE_EP)  &&
            (cpuid_info.model != IVYBRIDGE)  &&
            (cpuid_info.model != IVYBRIDGE_EP)  &&
            (cpuid_info.model != HASWELL))
    {
        fprintf (stderr, "RAPL not supported on this processor!\n");
        exit(EXIT_FAILURE);
    }

    if (optInfo)
    {
        printf("Thermal Spec Power: %g Watts \n", power_info.tdp );
        printf("Minimum  Power: %g Watts \n", power_info.minPower);
        printf("Maximum  Power: %g Watts \n", power_info.maxPower);
        printf("Maximum  Time Window: %g micro sec \n", power_info.maxTimeWindow);
        printf(HLINE);
        exit(EXIT_SUCCESS);
    }

    if (optClock)
    {
        affinity_init();
        argString = bformat("S%u:0-%u", threadsSockets[0], cpuid_topology.numCoresPerSocket-1);
        for (int i=1; i<numSockets; i++)
        {
            bstring tExpr = bformat("@S%u:0-%u", threadsSockets[i], cpuid_topology.numCoresPerSocket-1);
            bconcat(argString, tExpr);
        }
        numThreads = bstr_to_cpuset(threads, argString);
        bdestroy(argString);
        perfmon_init(numThreads, threads, stdout);
        perfmon_setupEventSet(eventString, NULL);
    }

    {
        PowerData pDataPkg[MAX_NUM_NODES*2];
        PowerData pDataDram[MAX_NUM_NODES*2];
        printf("Measure on sockets: %d", threadsSockets[0]);
        for (int i=1; i<numSockets; i++)
        {
            printf(", %d", threadsSockets[i]);
        }
        printf("\n");

        if (optStethoscope)
        {
            if (optClock)
            {
                perfmon_startCounters();
            }
            else
            {
                for (int i=0; i<numSockets; i++)
                {
                    int cpuId = numa_info.nodes[threadsSockets[i]].processors[0];
                    if (hasDRAM) power_start(pDataDram+i, cpuId, DRAM);
                    power_start(pDataPkg+i, cpuId, PKG);
                }
            }
            sleep(optStethoscope);

            if (optClock)
            {
                perfmon_stopCounters();
                perfmon_printCounterResults();
                perfmon_finalize();
            }
            else
            {
                for (int i=0; i<numSockets; i++)
                {
                    int cpuId = numa_info.nodes[threadsSockets[i]].processors[0];
                    power_stop(pDataPkg+i, cpuId, PKG);
                    if (hasDRAM) power_stop(pDataDram+i, cpuId, DRAM);
                }
            }
            runtime = (double) optStethoscope;
        }
        else
        {
            TimerData time;
            argv +=  optind;
            bstring exeString = bfromcstr(argv[0]);

            for (int i=1; i<(argc-optind); i++)
            {
                bconchar(exeString, ' ');
                bcatcstr(exeString, argv[i]);
            }
            printf("%s\n",bdata(exeString));


            if (optClock)
            {
                perfmon_startCounters();
            }
            else
            {
                for (int i=0; i<numSockets; i++)
                {
                    int cpuId = numa_info.nodes[threadsSockets[i]].processors[0];
                    if (hasDRAM) power_start(pDataDram+i, cpuId, DRAM);
                    power_start(pDataPkg+i, cpuId, PKG);
                }

                timer_start(&time);
            }

            if (system(bdata(exeString)) == EOF)
            {
                fprintf(stderr, "Failed to execute %s!\n", bdata(exeString));
                exit(EXIT_FAILURE);
            }

            if (optClock)
            {
                perfmon_stopCounters();
                perfmon_printCounterResults();
                perfmon_finalize();
            }
            else
            {
                timer_stop(&time);

                for (int i=0; i<numSockets; i++)
                {
                    int cpuId = numa_info.nodes[threadsSockets[i]].processors[0];
                    power_stop(pDataPkg+i, cpuId, PKG);
                    if (hasDRAM) power_stop(pDataDram+i, cpuId, DRAM);
                }
                runtime = timer_print(&time);
            }
        }

        if (!optClock)
        {
            printf("Runtime: %g second \n",runtime);
            printf(HLINE);
            for (int i=0; i<numSockets; i++)
            {
                printf("Socket %d\n",threadsSockets[i]);
                printf("Domain: PKG \n");
                printf("Energy consumed: %g Joules \n", power_printEnergy(pDataPkg+i));
                printf("Power consumed: %g Watts \n", power_printEnergy(pDataPkg+i) / runtime );
                if (hasDRAM)
                {
                    printf("Domain: DRAM \n");
                    printf("Energy consumed: %g Joules \n", power_printEnergy(pDataDram+i));
                    printf("Power consumed: %g Watts \n", power_printEnergy(pDataDram+i) / runtime );
                }
                printf("\n");
            }
        }
    }

#if 0
    if ( cpuid_hasFeature(TM2) )
    {
        thermal_init(0);
        printf("Current core temperatures:\n");

        for (uint32_t i = 0; i < cpuid_topology.numCoresPerSocket; i++ )
        {
            printf("Core %d: %u C\n",
                    numa_info.nodes[socketId].processors[i],
                    thermal_read(numa_info.nodes[socketId].processors[i]));
        }
    }
#endif

    msr_finalize();
    return EXIT_SUCCESS;
}
Beispiel #22
0
int glp_read_mincost(glp_graph *G, int v_rhs, int a_low, int a_cap,
      int a_cost, const char *fname)
{     struct csa _csa, *csa = &_csa;
      glp_vertex *v;
      glp_arc *a;
      int i, j, k, nv, na, ret = 0;
      double rhs, low, cap, cost;
      char *flag = NULL;
      if (v_rhs >= 0 && v_rhs > G->v_size - (int)sizeof(double))
         xerror("glp_read_mincost: v_rhs = %d; invalid offset\n",
            v_rhs);
      if (a_low >= 0 && a_low > G->a_size - (int)sizeof(double))
         xerror("glp_read_mincost: a_low = %d; invalid offset\n",
            a_low);
      if (a_cap >= 0 && a_cap > G->a_size - (int)sizeof(double))
         xerror("glp_read_mincost: a_cap = %d; invalid offset\n",
            a_cap);
      if (a_cost >= 0 && a_cost > G->a_size - (int)sizeof(double))
         xerror("glp_read_mincost: a_cost = %d; invalid offset\n",
            a_cost);
      glp_erase_graph(G, G->v_size, G->a_size);
      if (setjmp(csa->jump))
      {  ret = 1;
         goto done;
      }
      csa->fname = fname;
      csa->fp = NULL;
      csa->count = 0;
      csa->c = '\n';
      csa->field[0] = '\0';
      csa->empty = csa->nonint = 0;
      xprintf("Reading min-cost flow problem data from `%s'...\n",
         fname);
      csa->fp = xfopen(fname, "r");
      if (csa->fp == NULL)
      {  xprintf("Unable to open `%s' - %s\n", fname, xerrmsg());
         longjmp(csa->jump, 1);
      }
      /* read problem line */
      read_designator(csa);
      if (strcmp(csa->field, "p") != 0)
         error(csa, "problem line missing or invalid");
      read_field(csa);
      if (strcmp(csa->field, "min") != 0)
         error(csa, "wrong problem designator; `min' expected");
      read_field(csa);
      if (!(str2int(csa->field, &nv) == 0 && nv >= 0))
         error(csa, "number of nodes missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &na) == 0 && na >= 0))
         error(csa, "number of arcs missing or invalid");
      xprintf("Flow network has %d node%s and %d arc%s\n",
         nv, nv == 1 ? "" : "s", na, na == 1 ? "" : "s");
      if (nv > 0) glp_add_vertices(G, nv);
      end_of_line(csa);
      /* read node descriptor lines */
      flag = xcalloc(1+nv, sizeof(char));
      memset(&flag[1], 0, nv * sizeof(char));
      if (v_rhs >= 0)
      {  rhs = 0.0;
         for (i = 1; i <= nv; i++)
         {  v = G->v[i];
            memcpy((char *)v->data + v_rhs, &rhs, sizeof(double));
         }
      }
      for (;;)
      {  read_designator(csa);
         if (strcmp(csa->field, "n") != 0) break;
         read_field(csa);
         if (str2int(csa->field, &i) != 0)
            error(csa, "node number missing or invalid");
         if (!(1 <= i && i <= nv))
            error(csa, "node number %d out of range", i);
         if (flag[i])
            error(csa, "duplicate descriptor of node %d", i);
         read_field(csa);
         if (str2num(csa->field, &rhs) != 0)
            error(csa, "node supply/demand missing or invalid");
         check_int(csa, rhs);
         if (v_rhs >= 0)
         {  v = G->v[i];
            memcpy((char *)v->data + v_rhs, &rhs, sizeof(double));
         }
         flag[i] = 1;
         end_of_line(csa);
      }
      xfree(flag), flag = NULL;
      /* read arc descriptor lines */
      for (k = 1; k <= na; k++)
      {  if (k > 1) read_designator(csa);
         if (strcmp(csa->field, "a") != 0)
            error(csa, "wrong line designator; `a' expected");
         read_field(csa);
         if (str2int(csa->field, &i) != 0)
            error(csa, "starting node number missing or invalid");
         if (!(1 <= i && i <= nv))
            error(csa, "starting node number %d out of range", i);
         read_field(csa);
         if (str2int(csa->field, &j) != 0)
            error(csa, "ending node number missing or invalid");
         if (!(1 <= j && j <= nv))
            error(csa, "ending node number %d out of range", j);
         read_field(csa);
         if (!(str2num(csa->field, &low) == 0 && low >= 0.0))
            error(csa, "lower bound of arc flow missing or invalid");
         check_int(csa, low);
         read_field(csa);
         if (!(str2num(csa->field, &cap) == 0 && cap >= low))
            error(csa, "upper bound of arc flow missing or invalid");
         check_int(csa, cap);
         read_field(csa);
         if (str2num(csa->field, &cost) != 0)
            error(csa, "per-unit cost of arc flow missing or invalid");
         check_int(csa, cost);
         a = glp_add_arc(G, i, j);
         if (a_low >= 0)
            memcpy((char *)a->data + a_low, &low, sizeof(double));
         if (a_cap >= 0)
            memcpy((char *)a->data + a_cap, &cap, sizeof(double));
         if (a_cost >= 0)
            memcpy((char *)a->data + a_cost, &cost, sizeof(double));
         end_of_line(csa);
      }
      xprintf("%d lines were read\n", csa->count);
done: if (ret) glp_erase_graph(G, G->v_size, G->a_size);
      if (csa->fp != NULL) xfclose(csa->fp);
      if (flag != NULL) xfree(flag);
      return ret;
}
Beispiel #23
0
static int ksr_tls_parse_hostport(int* type, struct ip_addr* ip, unsigned int* port,
		cfg_token_t* token, cfg_parser_t* st)
{
	int ret;
	cfg_token_t t;
	cfg_option_t* opt;

	ret = cfg_get_token(&t, st, 0);
	if (ret < 0) return -1;
	if (ret > 0) {
		LM_ERR("%s:%d:%d: Missing IP address\n", st->file,
				token->start.line, token->start.col);
		return -1;
	}

	if (t.type == '[') {
		if (parse_ipv6(ip, &t, st) < 0) return -1;
	} else if (t.type == CFG_TOKEN_ALPHA) {
		opt = cfg_lookup_token(token_default, &t.val);
		if (opt) {
			*type = TLS_DOMAIN_DEF;
			/* Default domain */
			return 0;
		} else {
			opt = cfg_lookup_token(ksr_tls_token_any, &t.val);
			if (opt) {
				*type = TLS_DOMAIN_ANY;
				/* Default domain */
				return 0;
			} else {
				if (parse_ipv4(ip, &t, st) < 0) return -1;
			}
		}
	} else {
		LM_ERR("%s:%d:%d: Syntax error, IP address expected\n",
				st->file, t.start.line, t.start.col);
		return -1;
	}
	*type = 0;

	/* Parse port */
	ret = cfg_get_token(&t, st, 0);
	if (ret < 0) return -1;
	if (ret > 0) {
		LM_ERR("%s:%d:%d: Syntax error, ':' expected\n", st->file, st->line,
				st->col);
		return -1;
	}

	if (t.type != ':') {
		LM_ERR("%s:%d:%d: Syntax error, ':' expected\n",
				st->file, t.start.line, t.start.col);
		return -1;
	}

	ret = cfg_get_token(&t, st, 0);
	if (ret < 0) return -1;
	if (ret > 0) {
		LM_ERR("%s:%d:%d: Premature end of file, port number missing\n",
				st->file, t.start.line, t.start.col);
		return -1;
	}

	if (t.type != CFG_TOKEN_ALPHA || (str2int(&t.val, port) < 0)) {
		LM_ERR("%s:%d:%d: Invalid port number '%.*s'\n",
				st->file, t.start.line, t.start.col, STR_FMT(&t.val));
		return -1;
	}
	return 0;
}
Beispiel #24
0
int glp_read_maxflow(glp_graph *G, int *_s, int *_t, int a_cap,
      const char *fname)
{     struct csa _csa, *csa = &_csa;
      glp_arc *a;
      int i, j, k, s, t, nv, na, ret = 0;
      double cap;
      if (a_cap >= 0 && a_cap > G->a_size - (int)sizeof(double))
         xerror("glp_read_maxflow: a_cap = %d; invalid offset\n",
            a_cap);
      glp_erase_graph(G, G->v_size, G->a_size);
      if (setjmp(csa->jump))
      {  ret = 1;
         goto done;
      }
      csa->fname = fname;
      csa->fp = NULL;
      csa->count = 0;
      csa->c = '\n';
      csa->field[0] = '\0';
      csa->empty = csa->nonint = 0;
      xprintf("Reading maximum flow problem data from `%s'...\n",
         fname);
      csa->fp = xfopen(fname, "r");
      if (csa->fp == NULL)
      {  xprintf("Unable to open `%s' - %s\n", fname, xerrmsg());
         longjmp(csa->jump, 1);
      }
      /* read problem line */
      read_designator(csa);
      if (strcmp(csa->field, "p") != 0)
         error(csa, "problem line missing or invalid");
      read_field(csa);
      if (strcmp(csa->field, "max") != 0)
         error(csa, "wrong problem designator; `max' expected");
      read_field(csa);
      if (!(str2int(csa->field, &nv) == 0 && nv >= 2))
         error(csa, "number of nodes missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &na) == 0 && na >= 0))
         error(csa, "number of arcs missing or invalid");
      xprintf("Flow network has %d node%s and %d arc%s\n",
         nv, nv == 1 ? "" : "s", na, na == 1 ? "" : "s");
      if (nv > 0) glp_add_vertices(G, nv);
      end_of_line(csa);
      /* read node descriptor lines */
      s = t = 0;
      for (;;)
      {  read_designator(csa);
         if (strcmp(csa->field, "n") != 0) break;
         read_field(csa);
         if (str2int(csa->field, &i) != 0)
            error(csa, "node number missing or invalid");
         if (!(1 <= i && i <= nv))
            error(csa, "node number %d out of range", i);
         read_field(csa);
         if (strcmp(csa->field, "s") == 0)
         {  if (s > 0)
               error(csa, "only one source node allowed");
            s = i;
         }
         else if (strcmp(csa->field, "t") == 0)
         {  if (t > 0)
               error(csa, "only one sink node allowed");
            t = i;
         }
         else
            error(csa, "wrong node designator; `s' or `t' expected");
         if (s > 0 && s == t)
            error(csa, "source and sink nodes must be distinct");
         end_of_line(csa);
      }
      if (s == 0)
         error(csa, "source node descriptor missing\n");
      if (t == 0)
         error(csa, "sink node descriptor missing\n");
      if (_s != NULL) *_s = s;
      if (_t != NULL) *_t = t;
      /* read arc descriptor lines */
      for (k = 1; k <= na; k++)
      {  if (k > 1) read_designator(csa);
         if (strcmp(csa->field, "a") != 0)
            error(csa, "wrong line designator; `a' expected");
         read_field(csa);
         if (str2int(csa->field, &i) != 0)
            error(csa, "starting node number missing or invalid");
         if (!(1 <= i && i <= nv))
            error(csa, "starting node number %d out of range", i);
         read_field(csa);
         if (str2int(csa->field, &j) != 0)
            error(csa, "ending node number missing or invalid");
         if (!(1 <= j && j <= nv))
            error(csa, "ending node number %d out of range", j);
         read_field(csa);
         if (!(str2num(csa->field, &cap) == 0 && cap >= 0.0))
            error(csa, "arc capacity missing or invalid");
         check_int(csa, cap);
         a = glp_add_arc(G, i, j);
         if (a_cap >= 0)
            memcpy((char *)a->data + a_cap, &cap, sizeof(double));
         end_of_line(csa);
      }
      xprintf("%d lines were read\n", csa->count);
done: if (ret) glp_erase_graph(G, G->v_size, G->a_size);
      if (csa->fp != NULL) xfclose(csa->fp);
      return ret;
}
Beispiel #25
0
struct mi_root* refreshXcapDoc(struct mi_root* cmd, void* param)
{
	struct mi_node* node= NULL;
	str doc_url;
	xcap_doc_sel_t doc_sel;
	char* serv_addr;
	str stream= {0, 0};
	int type;
	unsigned int xcap_port;
	char* etag= NULL;

	node = cmd->node.kids;
	if(node == NULL)
		return 0;

	doc_url = node->value;
	if(doc_url.s == NULL || doc_url.len== 0)
	{
		LM_ERR("empty uri\n");
		return init_mi_tree(404, "Empty document URL", 20);
	}
	node= node->next;
	if(node== NULL)
		return 0;
	if(node->value.s== NULL || node->value.len== 0)
	{
		LM_ERR("port number\n");
		return init_mi_tree(404, "Empty document URL", 20);
	}
	if(str2int(&node->value, &xcap_port)< 0)
	{
		LM_ERR("while converting string to int\n");
		goto error;
	}

	if(node->next!= NULL)
		return 0;

	/* send GET HTTP request to the server */
	stream.s = send_http_get(doc_url.s, xcap_port, NULL, 0, &etag, &stream.len);
	if(stream.s== NULL)
	{
		LM_ERR("in http get\n");
		return 0;
	}
	
	/* call registered functions with document argument */
	if(parse_doc_url(doc_url, &serv_addr, &doc_sel)< 0)
	{
		LM_ERR("parsing document url\n");
		return 0;
	}

	type = xcap_doc_type(&doc_sel.auid);
	if (type < 0)
	{
		LM_ERR("incorect auid: %.*s\n",
				doc_sel.auid.len, doc_sel.auid.s);
		goto error;
	}

	run_xcap_update_cb(type, doc_sel.xid, stream.s);
	pkg_free(stream.s);

	return init_mi_tree(200, "OK", 2);

error:
	if(stream.s)
		pkg_free(stream.s);
	return 0;
}
Beispiel #26
0
bool toolkit_setting(char *key, char *value, t_url_toolkit *toolkit) {
	t_toolkit_rule *new_rule, *rule;
	char *rest;
	int loop, time, cflags;
	size_t len;

	if ((key == NULL) || (value == NULL) || (toolkit == NULL)) {
		return false;
	}

	if (strcmp(key, "toolkitid") == 0) {
		return (toolkit->toolkit_id = strdup(value)) != NULL;
	}

	if ((new_rule = (t_toolkit_rule*)malloc(sizeof(t_toolkit_rule))) == NULL) {
		return false;
	} else if (toolkit->toolkit_rule == NULL) {
		toolkit->toolkit_rule = new_rule;
	} else {
		rule = toolkit->toolkit_rule;
		while (rule->next != NULL) {
			rule = rule->next;
		}
		rule->next = new_rule;
	}

	new_rule->condition = tc_none;
	new_rule->operation = to_none;
	new_rule->flow = tf_continue;
	new_rule->match_loop = 1;
	new_rule->neg_match = false;
	new_rule->parameter = NULL;
	new_rule->header = NULL;
	new_rule->value = 0;
	new_rule->case_insensitive = false;
	new_rule->next = NULL;

	if (strcmp(key, "matchci") == 0) {
		new_rule->case_insensitive = true;
		key = "match";
	}

	if (strcasecmp(key, "call") == 0) {
		/* Call
		 */
		new_rule->operation = to_sub;

		if ((new_rule->parameter = strdup(value)) == NULL) {
			return false;
		}
	} else if (strcasecmp(key, "header") == 0) {
		/* Header
		 */
		new_rule->condition = tc_header;

		if (split_string(value, &value, &rest, ' ') == -1) {
			return false;
		}

		len = strlen(value);
		if ((new_rule->header = (char*)malloc(len + 2)) == NULL) {
			return false;
		}
		sprintf(new_rule->header, "%s:", value);

		if ((*rest == '\'') || (*rest == '"')) {
			value = rest + 1;
			if ((rest = strchr(rest + 1, *rest)) == NULL) {
				return false;
			}
			*rest = '\0';
			rest = remove_spaces(rest + 1);
		} else if (split_string(rest, &value, &rest, ' ') == -1) {
			return false;
		}

		if (*value == '!') {
			new_rule->neg_match = true;
			value++;
		}
		if (regcomp(&(new_rule->pattern), value, REG_EXTENDED | REG_ICASE | REG_NOSUB) != 0) {
			return false;
		}

		split_string(rest, &value, &rest, ' ');

		if (strcasecmp(value, "call") == 0) {
			/* Header Call
			 */
			new_rule->operation = to_sub;

			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "denyaccess") == 0) {
			/* Header Deny access
			 */
			new_rule->operation = to_deny_access;
			new_rule->flow = tf_exit;
		} else if (strcasecmp(value, "exit") == 0) {
			/* Header Exit
			 */
			new_rule->flow = tf_exit;
		} else if (strcasecmp(value, "goto") == 0) {
			/* Header Goto
			 */
			new_rule->operation = to_sub;
			new_rule->flow = tf_exit;

			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "redirect") == 0) {
			/* Header Redirect
			 */
			new_rule->operation = to_redirect;
			new_rule->flow = tf_exit;

			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "return") == 0) {
			/* Header Return
			 */
			new_rule->flow = tf_return;
		} else if (strcasecmp(value, "skip") == 0) {
			/* Header Skip
			 */
			if ((new_rule->value = str2int(rest)) < 1) {
				return false;
			}
		} else if (strcasecmp(value, "use") == 0) {
			/* Header Use
			 */
			new_rule->operation = to_replace;
			new_rule->flow = tf_exit;

			if (valid_uri(rest, false) == false) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else {
			return false;
		}
	} else if (strcmp(key, "match") == 0) {
		/* Match
		 */
		cflags = REG_EXTENDED;
		if (new_rule->case_insensitive) {
			cflags |= REG_ICASE;
		}

		new_rule->condition = tc_match;
		if (split_string(value, &value, &rest, ' ') == -1) {
			return false;
		}
		if (*value == '!') {
			new_rule->neg_match = true;
			value++;
		}
		if (regcomp(&(new_rule->pattern), value, cflags) != 0) {
			return false;
		}
		split_string(rest, &value, &rest, ' ');

		if (strcasecmp(value, "ban") == 0) {
			/* Match Ban
			 */
			new_rule->operation = to_ban;

			if ((new_rule->value = str2int(rest)) == false) {
				return false;
			}
		} else if (strcasecmp(value, "call") == 0) {
			/* Match Call
			 */
			new_rule->operation = to_sub;

			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "denyaccess") == 0) {
			/* Match DenyAccess
			 */
			new_rule->operation = to_deny_access;
			new_rule->flow = tf_exit;
		} else if (strcasecmp(value, "exit") == 0) {
			/* Match Exit
			 */
			new_rule->flow = tf_exit;
		} else if (strcasecmp(value, "expire") == 0) {
			/* Match Expire
			 */
			new_rule->operation = to_expire;

			if (split_string(rest, &value, &rest, ' ') == -1) {
				return false;
			}
			if ((new_rule->value = str2int(value)) == -1) {
				return false;
			}

			time = new_rule->value;

			split_string(rest, &value, &rest, ' ');
			if (strcasecmp(value, "minutes") == 0) {
				new_rule->value *= MINUTE;
			} else if (strcasecmp(value, "hours") == 0) {
				new_rule->value *= HOUR;
			} else if (strcasecmp(value, "days") == 0) {
				new_rule->value *= DAY;
			} else if (strcasecmp(value, "weeks") == 0) {
				new_rule->value *= 7 * DAY;
			} else if (strcasecmp(value, "months") == 0) {
				new_rule->value *= 30.5 * DAY;
			} else if (strcasecmp(value, "seconds") != 0) {
				return false;
			}

			if (new_rule->value < time) {
				return false;
			}

			if (rest != NULL) {
				if (strcasecmp(rest, "exit") == 0) {
					new_rule->flow = tf_exit;
				} else if (strcasecmp(rest, "return") == 0) {
					new_rule->flow = tf_return;
				} else {
					return false;
				}
			}
		} else if (strcasecmp(value, "goto") == 0) {
			/* Match Goto
			 */
			new_rule->operation = to_sub;
			new_rule->flow = tf_exit;

			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "redirect") == 0) {
			/* Match Redirect
			 */
			new_rule->operation = to_redirect;
			new_rule->flow = tf_exit;

			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "return") == 0) {
			/* Match Return
			 */
			new_rule->flow = tf_return;
		} else if (strcasecmp(value, "rewrite") == 0) {
			/* Match Rewrite
			 */
			new_rule->operation = to_rewrite;
			new_rule->flow = tf_exit;

			split_string(rest, &value, &rest, ' ');
			if (value == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(value)) == NULL) {
				return false;
			}

			if (rest != NULL) {
				split_string(rest, &value, &rest, ' ');
				if ((loop = str2int(value)) > 0) {
					if (loop > MAX_MATCH_LOOP) {
						return false;
					}
					new_rule->match_loop = loop;
					if ((value = rest) == NULL) {
						return true;
					}
				} else if (rest != NULL) {
					return false;
				}

				if (strcasecmp(value, "continue") == 0) {
					new_rule->flow = tf_continue;
				} else if (strcasecmp(value, "return") == 0) {
					new_rule->flow = tf_return;
				} else {
					return false;
				}
			}
		} else if (strcasecmp(value, "skip") == 0) {
			/* Match Skip
			 */
			new_rule->operation = to_skip;

			if ((new_rule->value = str2int(rest)) < 1) {
				return false;
			}
		} else if (strcasecmp(value, "usefastcgi") == 0) {
			/* Match UseFastCGI
			 */
			new_rule->operation = to_fastcgi;
			new_rule->flow = tf_exit;

			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else {
			return false;
		}
	} else if (strcasecmp(key, "requesturi") == 0) {
		/* RequestURI
		 */
		new_rule->condition = tc_request_uri;

		if (split_string(value, &value, &rest, ' ') == -1) {
			return false;
		}

		if (strcasecmp(value, "exists") == 0) {
			new_rule->value = IU_EXISTS;
		} else if (strcasecmp(value, "isfile") == 0) {
			new_rule->value = IU_ISFILE;
		} else if (strcasecmp(value, "isdir") == 0) {
			new_rule->value = IU_ISDIR;
		} else {
			return false;
		}

		if (strcasecmp(rest, "return") == 0) {
			new_rule->flow = tf_return;
		} else if (strcasecmp(rest, "exit") == 0) {
			new_rule->flow = tf_exit;
		} else {
			return false;
		}
	} else if (strcasecmp(key, "skip") == 0) {
		/* Skip
		 */
		new_rule->operation = to_skip;

		if ((new_rule->value = str2int(value)) < 1) {
			return false;
		}
#ifdef ENABLE_SSL
	} else if (strcmp(key, "usessl") == 0) {
		/* UseSSL
		 */
		new_rule->condition = tc_use_ssl;
		split_string(value, &value, &rest, ' ');

		if (strcasecmp(value, "call") == 0) {
			/* UseSSL Call
			 */
			new_rule->operation = to_sub;
			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "exit") == 0) {
			/* UseSSL Exit
			 */
			new_rule->flow = tf_exit;
		} else if (strcasecmp(value, "goto") == 0) {
			/* UseSSL Goto
			 */
			new_rule->operation = to_sub;
			new_rule->flow = tf_exit;
			if (rest == NULL) {
				return false;
			} else if ((new_rule->parameter = strdup(rest)) == NULL) {
				return false;
			}
		} else if (strcasecmp(value, "return") == 0) {
			/* UseSSL Return
			 */
			new_rule->flow = tf_return;
		} else if (strcasecmp(value, "skip") == 0) {
			/* UseSSL Skip
			 */
			new_rule->operation = to_skip;
			if ((new_rule->value = str2int(rest)) < 1) {
				return false;
			}
		} else {
			return false;
		}
#endif
	} else {
		/* Unknown condition
		 */
		return false;
	}

	return true;
}
Beispiel #27
0
void reader_cars_standard(char* fname, int fid, obsmeta* meta, grid* g, observations* obs)
{
    int ncid;
    int dimid_nprof, dimid_nz = -1;
    size_t nprof, nz;
    int varid_lon, varid_lat, varid_z, varid_type;
    int varid_v = -1;
    double* lon;
    double* lat;
    double** z;
    double** v;
    double missval, validmin, validmax;
    int* type;
    char buf[MAXSTRLEN];
    int len;
    int year, month, day;
    double tunits_multiple, tunits_offset;
    int p, i;

    for (i = 0; i < meta->npars; ++i)
        enkf_quit("unknown PARAMETER \"%s\"\n", meta->pars[i].name);

    if (meta->nstds == 0)
        enkf_quit("ERROR_STD is necessary but not specified for product \"%s\"", meta->product);

    ncw_open(fname, NC_NOWRITE, &ncid);
    ncw_inq_dimid(ncid, "nobs", &dimid_nprof);
    ncw_inq_dimlen(ncid, dimid_nprof, &nprof);
    enkf_printf("        # profiles = %u\n", (unsigned int) nprof);
    if (nprof == 0) {
        ncw_close(ncid);
        return;
    }

    if (ncw_dim_exists(ncid, "zt"))
        ncw_inq_dimid(ncid, "zt", &dimid_nz);
    else if (ncw_dim_exists(ncid, "ztd"))
        ncw_inq_dimid(ncid, "ztd", &dimid_nz);
    else
        enkf_quit("reader_cars_standard(): neither dimension \"zt\" ot \"ztd\" exist");
    ncw_inq_dimlen(ncid, dimid_nz, &nz);
    enkf_printf("        # z levels = %u\n", (unsigned int) nz);

    ncw_inq_varid(ncid, "lon", &varid_lon);
    lon = malloc(nprof * sizeof(double));
    ncw_get_var_double(ncid, varid_lon, lon);

    ncw_inq_varid(ncid, "lat", &varid_lat);
    lat = malloc(nprof * sizeof(double));
    ncw_get_var_double(ncid, varid_lat, lat);

    ncw_inq_varid(ncid, "zt", &varid_z);
    z = alloc2d(nprof, nz, sizeof(double));
    ncw_get_var_double(ncid, varid_z, z[0]);

    if (strncmp(meta->type, "TEM", 3) == 0)
        ncw_inq_varid(ncid, "temp", &varid_v);
    else if (strncmp(meta->type, "SAL", 3) == 0)
        ncw_inq_varid(ncid, "salt", &varid_v);
    else
        enkf_quit("observation type \"%s\" not handled for CARS product", meta->type);
    v = alloc2d(nprof, nz, sizeof(double));
    ncw_get_var_double(ncid, varid_v, v[0]);
    ncw_get_att_double(ncid, varid_v, "missing_value", &missval);
    ncw_get_att_double(ncid, varid_v, "valid_min", &validmin);
    ncw_get_att_double(ncid, varid_v, "valid_max", &validmax);

    ncw_inq_varid(ncid, "type", &varid_type);
    type = malloc(nprof * sizeof(int));
    ncw_get_var_int(ncid, varid_type, type);

    ncw_close(ncid);

    strcpy(buf, fname);
    len = strlen(buf);
    buf[len - 3] = 0;           /* .nc */
    if (!str2int(&buf[len - 5], &day))
        enkf_quit("CARS reader: could not convert file name \"%s\" to date", fname);
    buf[len - 17] = 0;
    if (!str2int(&buf[len - 19], &month))
        enkf_quit("CARS reader: could not convert file name \"%s\" to date", fname);
    buf[len - 21] = 0;
    if (!str2int(&buf[len - 25], &year))
        enkf_quit("CARS reader: could not convert file name \"%s\" to date", fname);
    snprintf(buf, MAXSTRLEN, "days since %4d-%02d-%02d", year, month, day);

    tunits_convert(buf, &tunits_multiple, &tunits_offset);

    for (p = 0; p < (int) nprof; ++p) {
        char inststr[MAXSTRLEN];

        if (type[p] == 11)
            strcpy(inststr, "ARGO");
        else if (type[p] == 12)
            strcpy(inststr, "TAO");
        else if (type[p] == 61)
            strcpy(inststr, "PIRATA");
        else if (type[p] == 7 || type[p] == 9 || type[p] == 13 || type[p] == 35 || type[p] == 41)
            strcpy(inststr, "CTD");
        else if (type[p] == 8 || type[p] == 17)
            strcpy(inststr, "XBT");
        else
            snprintf(inststr, MAXSTRLEN, "CARS%02u", type[p]);

        for (i = 0; i < (int) nz; ++i) {
            observation* o;
            obstype* ot;

            if (fabs(v[p][i] - missval) < EPS || v[p][i] < validmin || v[p][i] > validmax)
                continue;
            if (z[p][i] < 0.0)
                continue;

            obs_checkalloc(obs);
            o = &obs->data[obs->nobs];

            o->product = st_findindexbystring(obs->products, meta->product);
            assert(o->product >= 0);
            o->type = obstype_getid(obs->nobstypes, obs->obstypes, meta->type, 1);
            ot = &obs->obstypes[o->type];
            o->instrument = st_add_ifabsent(obs->instruments, inststr, -1);
            o->id = obs->nobs;
            o->fid = fid;
            o->batch = p;
            o->value = v[p][i];
            o->std = 0.0;
            o->lon = lon[p];
            o->lat = lat[p];
            o->depth = z[p][i];
            o->status = grid_xy2fij(g, o->lon, o->lat, &o->fi, &o->fj);
            if (!obs->allobs && o->status == STATUS_OUTSIDEGRID)
                break;
            if (o->status == STATUS_OK)
                o->status = grid_z2fk(g, o->fi, o->fj, o->depth, &o->fk);
            else
                o->fk = NAN;
            if ((o->status == STATUS_OK) && (o->lon <= ot->xmin || o->lon >= ot->xmax || o->lat <= ot->ymin || o->lat >= ot->ymax || o->depth <= ot->zmin || o->depth >= ot->zmax))
                o->status = STATUS_OUTSIDEOBSDOMAIN;
            o->model_depth = NAN;       /* set in obs_add() */
            o->date = tunits_offset + 0.5;
            o->aux = -1;

            obs->nobs++;
        }
    }

    free(lon);
    free(lat);
    free(v);
    free(z);
    free(type);
}
Beispiel #28
0
static void pua_rpc_publish(rpc_t* rpc, void* c)
{
	str pres_uri, expires, event, content_type, id, etag,
		outbound_proxy, extra_headers, body;
	rpc_delayed_ctx_t* dctx;
	int exp, sign, ret, err_ret, sip_error;
	char err_buf[MAX_REASON_LEN];
	struct sip_uri uri;
	publ_info_t publ;

	body.s = 0;
	body.len = 0;
	dctx = 0;

	LM_DBG("rpc publishing ...\n");

	if ((rpc->capabilities == 0) ||
	    !(rpc->capabilities(c) & RPC_DELAYED_REPLY)) {
		rpc->fault(c, 600, "Reply wait/async mode not supported"
			   " by this rpc transport");
		return;
	}

	ret = rpc->scan(c, "SSSSSSSS*S", &pres_uri, &expires, &event,
			&content_type, &id, &etag, &outbound_proxy,
			&extra_headers, &body);
	if (ret < 8) {
		rpc->fault(c, 400, "Too few or wrong type of parameters (%d)",
			   ret);
		return;
	}

	if (parse_uri(pres_uri.s, pres_uri.len, &uri) <0) {
		LM_ERR("bad resentity uri\n");
		rpc->fault(c, 400, "Invalid presentity uri '%s'", pres_uri.s);
		return;
	}
	LM_DBG("presentity uri '%.*s'\n", pres_uri.len, pres_uri.s);

	if (expires.s[0]== '-') {
		sign= -1;
		expires.s++;
		expires.len--;
	} else {
		sign = 1;
	}
	if (str2int(&expires, (unsigned int*)&exp) < 0) {
		LM_ERR("invalid expires parameter\n" );
		rpc->fault(c, 400, "Invalid expires value '%s'", expires.s);
		return;
	}
	exp = exp * sign;
	LM_DBG("expires '%d'\n", exp);

	LM_DBG("event '%.*s'\n", event.len, event.s);

	LM_DBG("content type '%.*s'\n", content_type.len, content_type.s);

	LM_DBG("id '%.*s'\n", id.len, id.s);

	LM_DBG("ETag '%.*s'\n", etag.len, etag.s);

	LM_DBG("outbound_proxy '%.*s'\n", outbound_proxy.len, outbound_proxy.s);

	LM_DBG("extra headers '%.*s'\n", extra_headers.len, extra_headers.s);

	if (body.len > 0) LM_DBG("body '%.*s'\n", body.len, body.s);

	if ((body.s == 0) &&
	    (content_type.len != 1 || content_type.s[0] != '.')) {
		LM_ERR("body is missing, but content type is not .\n");
		rpc->fault(c, 400, "Body is missing");
		return;
	}

	memset(&publ, 0, sizeof(publ_info_t));

	publ.pres_uri= &pres_uri;

	publ.expires= exp;

	publ.event= get_event_flag(&event);
	if (publ.event < 0) {
		LM_ERR("unknown event '%.*s'\n", event.len, event.s);
		rpc->fault(c, 400, "Unknown event");
		return;
	}

	if (content_type.len != 1) {
		publ.content_type= content_type;
	}

	if (!((id.len == 1) && (id.s[0]== '.'))) {
		publ.id= id;
	}

	if (!((etag.len== 1) && (etag.s[0]== '.'))) {
		publ.etag= &etag;
	}

	if (!((outbound_proxy.len == 1) && (outbound_proxy.s[0] == '.'))) {
		publ.outbound_proxy = &outbound_proxy;
	}

	if (!((extra_headers.len == 1) && (extra_headers.s[0] == '.'))) {
		publ.extra_headers = &extra_headers;
	}

	if (body.s != 0) {
		publ.body= &body;
	}

	dctx = rpc->delayed_ctx_new(c);
	if (dctx == 0) {
		LM_ERR("internal error: failed to create context\n");
		rpc->fault(c, 500, "Internal error: failed to create context");
		return;
	}
	publ.cb_param = dctx;
	publ.source_flag = MI_ASYN_PUBLISH;

	ret = pua_rpc_api.send_publish(&publ);
	LM_DBG("pua send_publish returned %d\n", ret);

	if (dctx->reply_ctx != 0) {
		/* callback was not executed or its execution failed */
		rpc = &dctx->rpc;
		c = dctx->reply_ctx;
	} else {
		return;
	}

	if (ret < 0) {
		LM_ERR("pua send_publish failed\n");
		err_ret = err2reason_phrase(ret, &sip_error, err_buf,
					    sizeof(err_buf), "RPC/PUBLISH") ;
		if (err_ret > 0 ) {
			rpc->fault(c, sip_error, "%s", err_buf);
		} else {
			rpc->fault(c, 500, "RPC/PUBLISH error");
		}
		rpc->delayed_ctx_close(dctx);
	}

	if (ret == 418) {
		rpc->fault(c, 500, "Wrong ETag");
		rpc->delayed_ctx_close(dctx);
	}


	return;
}
Beispiel #29
0
dlg_t * build_dlg_t(struct dlg_cell * cell, int dst_leg, int src_leg)
{
	dlg_t* td = NULL;
	str cseq;
	unsigned int loc_seq;

	td = (dlg_t*)pkg_malloc(sizeof(dlg_t));
	if(!td){
		LM_ERR("out of pkg memory\n");
		return NULL;
	}
	memset(td, 0, sizeof(dlg_t));

	if ((dst_leg == DLG_CALLER_LEG && (cell->flags & DLG_FLAG_PING_CALLER)) ||
		(dst_leg == callee_idx(cell) && (cell->flags & DLG_FLAG_PING_CALLEE)) || 
		(dst_leg == DLG_CALLER_LEG && (cell->flags & DLG_FLAG_REINVITE_PING_CALLER)) ||
		(dst_leg == callee_idx(cell) && (cell->flags & DLG_FLAG_REINVITE_PING_CALLEE)) || 
		cell->flags & DLG_FLAG_CSEQ_ENFORCE)
	{
		dlg_lock_dlg(cell);
		if (cell->legs[dst_leg].last_gen_cseq == 0)
		{
			/* no OPTIONS pings for this dlg yet */
			dlg_unlock_dlg(cell);
			goto before_strcseq;
		}
		else
		{
			/* OPTIONS pings sent, use new cseq */
			td->loc_seq.value = ++(cell->legs[dst_leg].last_gen_cseq);
			td->loc_seq.is_set=1;
			dlg_unlock_dlg(cell);
			goto after_strcseq;
		}
	}
before_strcseq:
	/*local sequence number*/
	cseq = cell->legs[dst_leg].r_cseq;
	if( !cseq.s || !cseq.len || str2int(&cseq, &loc_seq) != 0){
		LM_ERR("invalid cseq\n");
		goto error;
	}
	/*we don not increase here the cseq as this will be done by TM*/
	td->loc_seq.value = loc_seq;
	td->loc_seq.is_set = 1;

after_strcseq:

	/*route set*/
	if( cell->legs[dst_leg].route_set.s && cell->legs[dst_leg].route_set.len){
		if( parse_rr_body(cell->legs[dst_leg].route_set.s,
			cell->legs[dst_leg].route_set.len, &td->route_set) !=0){
		 	LM_ERR("failed to parse route set\n");
			goto error;
		}
	}

	/*remote target--- Request URI*/
	if (cell->legs[dst_leg].contact.s==0 || cell->legs[dst_leg].contact.len==0){
		LM_ERR("no contact available\n");
		goto error;
	}
	td->rem_target = cell->legs[dst_leg].contact;

	td->rem_uri = (dst_leg==DLG_CALLER_LEG)? *dlg_leg_from_uri(cell,dst_leg):
					 *dlg_leg_to_uri(cell,dst_leg);
	td->loc_uri = (dst_leg==DLG_CALLER_LEG)? *dlg_leg_to_uri(cell,dst_leg):
					 *dlg_leg_from_uri(cell,dst_leg);
	td->id.call_id = cell->callid;
	td->id.rem_tag = cell->legs[dst_leg].tag;
	td->id.loc_tag = cell->legs[src_leg].tag;

	td->state= DLG_CONFIRMED;
	td->send_sock = cell->legs[dst_leg].bind_addr;

	/* link the dialog cell here - it will eventually be linked
	 * within the upcoming created transaction */
	td->dialog_ctx = cell;

	return td;

error:
	free_tm_dlg(td);
	return NULL;
}
Beispiel #30
0
int sca_init_request(struct sip_msg* msg, str* p1, str* p2)
{
	int method_value, ret;
	//unsigned int size, hash_index, shared_entity;
	unsigned int hash_index, shared_entity, app_index;
	str *b2bl_key, *host, *port, *display, *uri, *shared_line;
	//char *p;
	//uri_type scheme;
	struct to_body *appearance_name_addr_body;
	pv_value_t pv_val;
	b2b_sca_record_t *record = NULL;
	b2b_sca_call_t *call = NULL;
	b2bl_cb_ctx_t *cb_params;

	str publish_hdr = {NULL, 0};
	str custom_hdr = {NULL, 0};
	str call_info_uri = {NULL, 0};
	str call_info_apperance_uri = {NULL, 0};

	if (parse_headers(msg, HDR_EOH_F, 0) < 0) {
		LM_ERR("failed to parse message\n");
		return -1;
	}
	method_value = msg->first_line.u.request.method_value;
	if (method_value != METHOD_INVITE) {
		LM_ERR("nonINVITE [%d] cannot initiate a call\n", method_value);
		return -1;
	}
	ret = tmb.t_newtran(msg);
	if(ret < 1) {
		if(ret == 0) {
			LM_DBG("It is a retransmission, drop\n");
			tmb.unref_cell(tmb.t_gett());
		} else {
			LM_ERR("Error when creating tm transaction\n");
		}
		return 0;
	}

	if (p1 && (pv_get_spec_value(msg, (pv_spec_t *)p1, &pv_val) == 0)) {
		if (pv_val.flags & PV_VAL_INT) {
			shared_entity = pv_val.ri;
			LM_DBG("got shared_entity %d\n", shared_entity);
		} else if (pv_val.flags & PV_VAL_STR) {
			if(str2int(&(pv_val.rs), (unsigned int*)&shared_entity) != 0) {
				LM_ERR("Unable to get entity_no from pv '%.*s'\n",
				pv_val.rs.len, pv_val.rs.s);
				return -1;
			}
		} else {
			LM_ERR("shared entity not a str or int type\n");
			return -1;
		}
	} else {
		LM_ERR("Unable to get shared entity from pv:%p\n", p1);
		return -1;
	}

	switch (shared_entity) {
	case 0:
		LM_DBG("Incoming call from shared line\n");
		break;
	case 1:
		LM_DBG("Outgoing call via a shared line\n");
		break;
	default:
		LM_ERR("shared line entity should be 0 or 1\n");
		return -1;
	}

	/* Get the hash index for the shared line.  */
	if (get_hash_index_and_shared_line(msg, &hash_index, &shared_line)<0)
		return -1;
	LM_DBG("got hash_index=[%d] for shared line [%.*s]\n",
			hash_index, shared_line->len, shared_line->s);

	/* Get the appearance name-addr for this call.  */
	appearance_name_addr_body = get_appearance_name_addr(msg);
	if (appearance_name_addr_body == NULL) {
		LM_ERR("unable to get apperance of this call\n");
		return -1;
	}
	//scheme = appearance_name_addr_body->parsed_uri.type;
	host = &appearance_name_addr_body->parsed_uri.host;
	port = &appearance_name_addr_body->parsed_uri.port;
	display = &appearance_name_addr_body->display;
	uri = &appearance_name_addr_body->uri;
	LM_DBG("display uri [%.*s][%.*s] from host:port [%.*s]:[%.*s]\n",
			display->len, display->s, uri->len, uri->s,
			host->len, host->s, port->len, port->s);


	/* Prepare absoluteURI for Call-Info header.
	 */
	if (build_absoluteURI(host, port, &call_info_uri) != 0)
		goto error1;

	/* Prepare appearanceURI param for Call-Info header.  */
	if (build_appearanceURI(display, uri, &call_info_apperance_uri) != 0)
		goto error1;

	/* Extract required appearance from the received request */
	app_index = get_app_index(msg);

	/* Adding call to the sca_table.  */
	lock_get(&b2b_sca_htable[hash_index].lock);
	if (b2b_sca_add_call_record(hash_index, shared_line, shared_entity, app_index,
			&call_info_uri, &call_info_apperance_uri, &record, &call) != 0) {
		LM_ERR("unable to add record to sca htable\n");
		goto error2;
	}

	/* Prepare INVITE Call-Info header.  */
	if (build_invite_call_info_header(call, &call_info_uri, &custom_hdr) != 0)
		goto error2;

	/* Prepare PUBLISH Call-Info header.  */
	if (build_publish_call_info_header(record, &publish_hdr) != 0) {
		LM_ERR("Unable to build PUBLISH Call-Info header\n");
		goto error2;
	}

	/* Prepare b2b_logic callback params. */
	cb_params = build_cb_params(hash_index, shared_line, call->appearance_index);
	if (cb_params == NULL)
		goto error2;

	LM_DBG("*** INITIALIZING \"top hiding\" SCENARIO with cb_params [%p]\n", cb_params);
	/* release the lock here to avoid deadlock while getting callback notifications */
	lock_release(&b2b_sca_htable[hash_index].lock);
	b2bl_key = b2bl_api.init(msg, &scenario, NULL, &sca_logic_notify, (void *)cb_params,
			B2B_RE_INVITE_CB|B2B_CONFIRMED_CB|B2B_DESTROY_CB, &custom_hdr);
	lock_get(&b2b_sca_htable[hash_index].lock);

	if (!b2bl_key || !b2bl_key->s || !b2bl_key->len)
		goto error2;
	else if (b2b_sca_update_call_record_key(call, b2bl_key) != 0)
		goto error3;

	/* Save the record to db. */
	if (push_sca_info_to_db(record, call->appearance_index, 0) != 0)
		goto error3;

	/* Notify the watchers. */
	sca_publish(record, &publish_hdr);

	lock_release(&b2b_sca_htable[hash_index].lock);


	if (publish_hdr.s != publish_call_info_hdr_buf)
		pkg_free(publish_hdr.s);
	if (custom_hdr.s != invite_call_info_hdr_buf)
		pkg_free(custom_hdr.s);
	if (call_info_uri.s != call_info_uri_buf)
		pkg_free(call_info_uri.s);
	if (call_info_apperance_uri.s != call_info_apperance_uri_buf)
		pkg_free(call_info_apperance_uri.s);

	return 1;

error3:
	/* Release the call */
	b2bl_api.terminate_call(b2bl_key);
error2:
	lock_release(&b2b_sca_htable[hash_index].lock);
error1:
	if (publish_hdr.s != publish_call_info_hdr_buf)
		pkg_free(publish_hdr.s);
	if (custom_hdr.s != invite_call_info_hdr_buf)
		pkg_free(custom_hdr.s);
	if (call_info_uri.s != call_info_uri_buf)
		pkg_free(call_info_uri.s);
	if (call_info_apperance_uri.s != call_info_apperance_uri_buf)
		pkg_free(call_info_apperance_uri.s);

	return -1;
}