示例#1
0
void process_request(int fd) {
	if (server.clients[fd] == NULL) {
		return;
	}

	buffer* in_buf = server.clients[fd] -> in_buf;
	buffer* out_buf = server.clients[fd] -> out_buf;
	int i, len = buflen(in_buf);
	int req_len_end_pos = -1;
	for (i = 0; i < len; i++) {
		if (in_buf -> buf[i] == SEPARATOR) {
			req_len_end_pos = i;
			break;
		}
	}
	
	if (req_len_end_pos == -1) {
		return;
	}
	int req_len = -1;
	char tmp;
	sscanf(in_buf -> buf, "%d%c", &req_len, &tmp);
	if (len - req_len_end_pos - 1 < req_len) {
		return;
	}
	
	char op[100], *rest, tmp_buf[1024];
	memcpy(tmp_buf, in_buf -> buf + req_len_end_pos + 1, req_len * sizeof(char));
	tmp_buf[req_len] = '\0';
	sscanf(tmp_buf, "%s", op);
	rest = tmp_buf + strlen(op) + 1;
	
	if (strcmp(op, "GET") == 0) {
		void* res = get_from_map(server.db, rest);
		if (res) {
			append_to_buffer(out_buf, (char*) res);
		} else {
			append_to_buffer(out_buf, "");
		}
	} else if (strcmp(op, "SET") == 0) {
		char key[100], value[100];
		sscanf(rest, "%s %s", key, value);
		free(remove_from_map(server.db, key));
		char* kivi_obj = malloc((strlen(value) + 1) * sizeof(char));
		memcpy(kivi_obj, value, (strlen(value) + 1) * sizeof(char));
		put_in_map(server.db, key, kivi_obj);
		append_to_buffer(out_buf, "OK");
	} else if (strcmp(op, "DEL") == 0) {
		free(remove_from_map(server.db, rest));
		append_to_buffer(out_buf, "OK");
	}
	
	memcpy(in_buf -> buf, in_buf -> buf + req_len_end_pos + 1 + req_len, (len - req_len_end_pos - 1 - req_len) * sizeof(char));
	in_buf -> end_pos -= req_len_end_pos + 1 + req_len;
	in_buf -> buf[in_buf -> end_pos] = '\0';
}
示例#2
0
void join_paths(char *path1,char *path2,char *new_path ){

/*	printf("strlen path1:%d\n",strlen(path1));
	printf("strlen path2:%d\n",strlen(path2));
	printf("path1; %s\n",path1);
*/
	add_to_buffer(&message_buffer, "joining paths:",MESSAGE_LEVEL_BASIC_TASKS,NPRINT);
	append_to_buffer(&message_buffer,path1,MESSAGE_LEVEL_BASIC_TASKS,NPRINT);
	append_to_buffer(&message_buffer, " and ",MESSAGE_LEVEL_BASIC_TASKS,NPRINT);
	append_to_buffer(&message_buffer, path2,MESSAGE_LEVEL_BASIC_TASKS,PRINT);
	if ( (path1[(sizeof(path1)/sizeof(char))-2]=='/') && path2[0]!='/') {
		/*paths are compatiable. concatanate them. note -2 is because of \0*/  
		strcat(new_path,path1);
		strcat(new_path,path2);		
		//char new_path[(sizeof(path1)/sizeof(char))+(sizeof(path2)/sizeof(char))];
		//strcpy(new_path,strcat(path1,path2)); 
		//return new_path;
	}	
	else if ((path1[(sizeof(path1)/sizeof(char))-2]!='/') && path2[0]=='/') {
		/*paths are compatiable. concatanate them*/  
		strcat(new_path,path1);
		strcat(new_path,path2);		
		//char new_path[(sizeof(path1)/sizeof(char))+(sizeof(path2)/sizeof(char))];
		//strcpy(new_path,strcat(path1,path2)); 
		//return new_path;
	}
	else if ((path1[(sizeof(path1)/sizeof(char))-2]!='/') && path2[0]!='/') {
			/*need to add a "/". */  
		strcat(new_path,path1);
		strcat(new_path,"/");
		strcat(new_path,path2);
		//strcpy(new_path,strcat(path1,strcat("/\0",path2)));

#if 0
		copy_array(path1,new_path,0,0);
		copy_array('\0',new_path,0,(sizeof(path1)/sizeof(char)));
		copy_array(path2,new_path,0,(sizeof(path1)/sizeof(char))+1);
 old method now trying to use copy_array
		//char new_path[(sizeof(path1)/sizeof(char))+(sizeof(path2)/sizeof(char))+1];
		for (x=0;x<=(sizeof(path1)/sizeof(char))-1;x++){ 
			new_path[x]=path1[x];
		}
		new_path[x+1]='/';
		for (x=(sizeof(path1)/sizeof(char)) ,i=0 ;i<=(sizeof(path2)/sizeof(char));x++,i++){ 
			new_path[x]=path2[i]; 
		}
#endif

		//return new_path;
	}
示例#3
0
/**
 * @brief read process stderr
 * @param c the child to read stderr from
 * @returns 0 on success, -1 on error.
 */
int read_stderr(child_node *c) {
  buffer bigbuff;
  char buff[255];
  char *line;
  int count, ret;
  
  ret = 0;
  memset(&(bigbuff), 0, sizeof(buffer));
  
  while((count=read(c->stderr_fd, buff, 255)) > 0) {
    if(append_to_buffer(&(bigbuff), buff, count)) {
      ret = -1;
      goto exit;
    }
    
    while((line = get_line_from_buffer(&(bigbuff)))) {
      ret = on_cmd_stderr(c, line);
      free(line);
      
      if(ret)
        goto exit;
    }
  }
  
  exit:
  
  if(count<0) {
    print( ERROR, "read: %s", strerror(errno));
    ret = -1;
  }
  
  release_buffer(&(bigbuff));
  
  return ret;
}
示例#4
0
void si_ui_draw_end(void)
{
    pthread_mutex_lock(&Si_Ui_Mutex); 

    append_to_buffer("draw_end"); 

    /* add a string containing only a newline, to keep the Java client happy, 
       NOTE: this may need to change, if problems occur e.g. when using a mix of 
       Windows and Linux */ 
    append_to_buffer("\n"); 

    /* send the buffer */ 
    send_buffer(); 

    pthread_mutex_unlock(&Si_Ui_Mutex); 
}
示例#5
0
void si_ui_draw_image(char image_name[], int x_coord, int y_coord)
{
    pthread_mutex_lock(&Si_Ui_Mutex); 

    sprintf(Message_String, "draw_image:%s:%08X:%08X", image_name, x_coord, y_coord); 

    append_to_buffer(Message_String); 

    pthread_mutex_unlock(&Si_Ui_Mutex); 
}
示例#6
0
void si_ui_draw_string(char string[], int x_coord, int y_coord)
{
    pthread_mutex_lock(&Si_Ui_Mutex); 

    sprintf(Message_String, "draw_string:%08X:%08X:%s", x_coord, y_coord, string); 

    append_to_buffer(Message_String); 

    pthread_mutex_unlock(&Si_Ui_Mutex); 
}
示例#7
0
void si_ui_draw_begin(void)
{
    pthread_mutex_lock(&Si_Ui_Mutex); 

    /* start from the beginning */ 
    Message_Pos = 0; 
        
    append_to_buffer("draw_begin"); 

    pthread_mutex_unlock(&Si_Ui_Mutex); 
}
示例#8
0
static int flatten_request_header(h2o_mruby_context_t *handler_ctx, h2o_iovec_t name, h2o_iovec_t value, void *_ctx)
{
    struct st_h2o_mruby_http_request_context_t *ctx = _ctx;

    /* ignore certain headers */
    if (h2o_lcstris(name.base, name.len, H2O_STRLIT("content-length")) ||
        h2o_lcstris(name.base, name.len, H2O_STRLIT("connection")) || h2o_lcstris(name.base, name.len, H2O_STRLIT("host")))
        return 0;

    /* mark the existence of transfer-encoding in order to prevent us from adding content-length header */
    if (h2o_lcstris(name.base, name.len, H2O_STRLIT("transfer-encoding")))
        ctx->req.has_transfer_encoding = 1;

    h2o_buffer_reserve(&ctx->req.buf, name.len + value.len + sizeof(": \r\n") - 1);
    append_to_buffer(&ctx->req.buf, name.base, name.len);
    append_to_buffer(&ctx->req.buf, H2O_STRLIT(": "));
    append_to_buffer(&ctx->req.buf, value.base, value.len);
    append_to_buffer(&ctx->req.buf, H2O_STRLIT("\r\n"));

    return 0;
}
/** dumps out stats about each stats bucket. */
char* item_stats_buckets(int *bytes) {
    size_t bufsize = (2 * 1024 * 1024), offset = 0;
    char *buf = (char *)malloc(bufsize); /* 2MB max response size */
    int i, j;
    char terminator[] = "END\r\n";

    *bytes = 0;
    if (buf == 0) {
        return NULL;
    }

#if defined(STATS_BUCKETS)
    GLOBAL_STATS_LOCK();
    /* write the buffer */
#define BUCKETS_RANGE(start, end, skip)                                 \
    for (i = start, j = 0; i < end; i += skip, j ++) {                  \
        if (set.size_ ## start ## _ ## end[j] != 0 ||                   \
            hit.size_ ## start ## _ ## end[j] != 0 ||                   \
            evict.size_ ## start ## _ ## end[j] != 0 ||                 \
            delete.size_ ## start ## _ ## end[j] != 0 ||                \
            overwrite.size_ ## start ## _ ## end[j] != 0) {             \
            offset = append_to_buffer(buf, bufsize, offset,             \
                                      sizeof(terminator),               \
                                      "%8d-%-8d:%16" PRINTF_INT64_MODIFIER \
                                      "u sets %16" PRINTF_INT64_MODIFIER \
                                      "u hits %16" PRINTF_INT64_MODIFIER \
                                      "u evicts %16" PRINTF_INT64_MODIFIER \
                                      "u deletes %16" PRINTF_INT64_MODIFIER \
                                      "u expires %16" PRINTF_INT64_MODIFIER \
                                      "u overwrites\r\n",               \
                                      i, i + skip - 1,                  \
                                      set.size_ ## start ## _ ## end[j], \
                                      hit.size_ ## start ## _ ## end[j], \
                                      evict.size_ ## start ## _ ## end[j], \
                                      delete.size_ ## start ## _ ## end[j], \
                                      expires.size_ ## start ## _ ## end[j], \
                                      overwrite.size_ ## start ## _ ## end[j]); \
        }                                                               \
}
#include "buckets.h"
    GLOBAL_STATS_UNLOCK();
#else
    (void) i;
    (void) j;
#endif /* #if defined(STATS_BUCKETS) */

    offset = append_to_buffer(buf, bufsize, offset, 0, terminator);
    *bytes = offset;
    return buf;
}
示例#10
0
void si_ui_show_error(char message[])
{
    si_ui_draw_begin(); 

    pthread_mutex_lock(&Si_Ui_Mutex); 

    sprintf(Message_String, "show_error:%s", message); 

    append_to_buffer(Message_String); 

    pthread_mutex_unlock(&Si_Ui_Mutex); 

    si_ui_draw_end(); 
}
/** dumps out stats about cost-benefit on a per-bucket basis. */
char* cost_benefit_stats(int *bytes) {
    size_t bufsize = (2 * 1024 * 1024), offset = 0;
    char *buf = (char *)malloc(bufsize); /* 2MB max response size */
    int i, j;
    char terminator[] = "END\r\n";
    rel_time_t now = current_time;
    (void) now;                                   /* if we're not dumping any stats, we need to
                                                   * consume the now variable. */

    *bytes = 0;
    if (buf == 0) {
        return NULL;
    }

#if defined(COST_BENEFIT_STATS)
    GLOBAL_STATS_LOCK();
    /* flush pending stats and write the buffer */
#define BUCKETS_RANGE(start, end, skip)                                 \
    for (i = start, j = 0;                                              \
         i < end;                                                       \
         i += skip, j ++) {                                             \
        cb_buckets.slot_seconds_ ## start ## _ ## end [j] +=            \
            (now - cb_buckets.last_update_ ## start ## _ ## end [j]) *  \
            cb_buckets.slots_ ## start ## _ ## end [j];                 \
        cb_buckets.last_update_ ## start ## _ ## end [j] = now;         \
        if (cb_buckets.slot_seconds_ ## start ## _ ## end[j] != 0 ||    \
            cb_buckets.hits_ ## start ## _ ## end[j] != 0) {            \
            offset = append_to_buffer(buf, bufsize, offset,             \
                                      sizeof(terminator),               \
                                      "%8d-%-8d:"                       \
                                      " cost: %16" PRINTF_INT64_MODIFIER "u" \
                                      " hits: %16" PRINTF_INT64_MODIFIER "u" \
                                      "\r\n",               \
                                      i, i + skip - 1,                  \
                                      cb_buckets.slot_seconds_ ## start ## _ ## end[j], \
                                      cb_buckets.hits_ ## start ## _ ## end[j]); \
        }                                                               \
    }
#include "buckets.h"
    GLOBAL_STATS_UNLOCK();
#else
    (void) i;
    (void) j;
    (void) now;
#endif /* #if defined(COST_BENEFIT_STATS) */

    offset = append_to_buffer(buf, bufsize, offset, 0, terminator);
    *bytes = offset;
    return buf;
}
示例#12
0
void si_ui_set_size(int x_size, int y_size)
{
    si_ui_draw_begin(); 

    pthread_mutex_lock(&Si_Ui_Mutex); 

    sprintf(Message_String, "set_size:%08X:%08X", x_size, y_size); 

    append_to_buffer(Message_String); 

    pthread_mutex_unlock(&Si_Ui_Mutex); 

    si_ui_draw_end(); 
}
示例#13
0
void init(char *yaffs_test_dir,char *yaffs_mount_dir,int argc, char *argv[]){
	char output=0;
	int x=0;
	int seed=-1;
	FILE *log_handle;
	/*these variables are already set to zero, but it is better not to take chances*/
	message_buffer.head=0;				 
	message_buffer.tail=0;


	log_handle=fopen(LOG_FILE,"w");
	if (log_handle!=NULL){
		fputs("log file for yaffs tester\n",log_handle);
		fclose(log_handle);
	}
	add_to_buffer(&message_buffer,"welcome to the yaffs tester",MESSAGE_LEVEL_BASIC_TASKS,PRINT);/* print boot up message*/	
	yaffs_start_up();
    	yaffs_mount(yaffs_mount_dir);
	for (x=0;x<argc;x++){
//		add_to_buffer(&message_buffer,"argv ",MESSAGE_LEVEL_BASIC_TASKS,PRINT);
//		add_to_buffer(&message_buffer,argv[x],MESSAGE_LEVEL_BASIC_TASKS,PRINT);
		if (strcmp("-seed",argv[x])==0){			/*warning only compares the length of the strings, quick fix*/
			seed= atoi(argv[x+1]);
			/*add_to_buffer(&message_buffer,"setting seed to ",MESSAGE_LEVEL_BASIC_TASKS,NPRINT);
			append_int_to_buffer(&message_buffer,seed,MESSAGE_LEVEL_BASIC_TASKS,NPRINT);			
			append_to_buffer(&message_buffer,"\n",MESSAGE_LEVEL_BASIC_TASKS,PRINT);*/
		}
	}
	if (seed==-1){
		seed=time(NULL);
		srand(seed); 
	}
	else {
	srand(seed);
	}
	add_to_buffer(&message_buffer,"setting seed to ",MESSAGE_LEVEL_BASIC_TASKS,NPRINT);
	append_int_to_buffer(&message_buffer,seed,MESSAGE_LEVEL_BASIC_TASKS,PRINT);/* print boot up message*/	

	if (yaffs_access(yaffs_test_dir,0))	/* if the test folder does not exist then create it */
	{
		add_to_buffer(&message_buffer,"creating dir: ",MESSAGE_LEVEL_BASIC_TASKS,NPRINT);
		append_to_buffer(&message_buffer,yaffs_test_dir,MESSAGE_LEVEL_BASIC_TASKS,PRINT);	
		output=yaffs_mkdir(yaffs_test_dir,S_IREAD | S_IWRITE);
		yaffs_check_for_errors(output, &message_buffer,"could not create dir","created dir\n\n");
	}
	
}
示例#14
0
static int send_report(LinphoneCall* call, reporting_session_report_t * report, const char * report_event) {
	LinphoneContent *content;
	int expires = -1;
	size_t offset = 0;
	size_t size = 2048;
	char * buffer;
	int ret = 0;
	LinphoneEvent *lev;
	LinphoneAddress *request_uri;
	char * domain;
	const char* route;

	/*if we are on a low bandwidth network, do not send reports to not overload it*/
	if (linphone_call_params_low_bandwidth_enabled(linphone_call_get_current_params(call))){
		ms_warning("QualityReporting[%p]: Avoid sending reports on low bandwidth network", call);
		ret = 1;
		goto end;
	}

	/*if the call was hung up too early, we might have invalid IPs information
	in that case, we abort the report since it's not useful data*/
	if (report->info.local_addr.ip == NULL || strlen(report->info.local_addr.ip) == 0
		|| report->info.remote_addr.ip == NULL || strlen(report->info.remote_addr.ip) == 0) {
		ms_warning("QualityReporting[%p]: Trying to submit a %s too early (call duration: %d sec) but %s IP could "
			"not be retrieved so dropping this report"
			, call
			, report_event
			, linphone_call_get_duration(call)
			, (report->info.local_addr.ip == NULL || strlen(report->info.local_addr.ip) == 0) ? "local" : "remote");
		ret = 2;
		goto end;
	}

	buffer = (char *) belle_sip_malloc(size);
	content = linphone_content_new();
	linphone_content_set_type(content, "application");
	linphone_content_set_subtype(content, "vq-rtcpxr");

	append_to_buffer(&buffer, &size, &offset, "%s\r\n", report_event);
	append_to_buffer(&buffer, &size, &offset, "CallID: %s\r\n", report->info.call_id);
	append_to_buffer(&buffer, &size, &offset, "LocalID: %s\r\n", report->info.local_addr.id);
	append_to_buffer(&buffer, &size, &offset, "RemoteID: %s\r\n", report->info.remote_addr.id);
	append_to_buffer(&buffer, &size, &offset, "OrigID: %s\r\n", report->info.orig_id);

	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "LocalGroup: %s\r\n", report->info.local_addr.group);
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "RemoteGroup: %s\r\n", report->info.remote_addr.group);
	append_to_buffer(&buffer, &size, &offset, "LocalAddr: IP=%s PORT=%d SSRC=%u\r\n", report->info.local_addr.ip, report->info.local_addr.port, report->info.local_addr.ssrc);
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "LocalMAC: %s\r\n", report->info.local_addr.mac);
	append_to_buffer(&buffer, &size, &offset, "RemoteAddr: IP=%s PORT=%d SSRC=%u\r\n", report->info.remote_addr.ip, report->info.remote_addr.port, report->info.remote_addr.ssrc);
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "RemoteMAC: %s\r\n", report->info.remote_addr.mac);

	append_to_buffer(&buffer, &size, &offset, "LocalMetrics:\r\n");
	append_metrics_to_buffer(&buffer, &size, &offset, report->local_metrics);

	if (are_metrics_filled(report->remote_metrics)!=0) {
		append_to_buffer(&buffer, &size, &offset, "RemoteMetrics:\r\n");
		append_metrics_to_buffer(&buffer, &size, &offset, report->remote_metrics);
	}
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "DialogID: %s\r\n", report->dialog_id);

	if (report->qos_analyzer.timestamp!=NULL){
		append_to_buffer(&buffer, &size, &offset, "AdaptiveAlg:");
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " NAME=\"%s\"", report->qos_analyzer.name);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " TS=\"%s\"", report->qos_analyzer.timestamp);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " IN_LEG=\"%s\"", report->qos_analyzer.input_leg);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " IN=\"%s\"", report->qos_analyzer.input);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " OUT_LEG=\"%s\"", report->qos_analyzer.output_leg);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " OUT=\"%s\"", report->qos_analyzer.output);
		append_to_buffer(&buffer, &size, &offset, "\r\n");
	}

#if TARGET_OS_IPHONE
	{
		size_t namesize;
		char *machine;
		sysctlbyname("hw.machine", NULL, &namesize, NULL, 0);
		machine = malloc(namesize);
		sysctlbyname("hw.machine", machine, &namesize, NULL, 0);
		APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "Device: %s\r\n", machine);
	}
#endif

	linphone_content_set_buffer(content, buffer, strlen(buffer));
	ms_free(buffer);

	if (call->log->reporting.on_report_sent != NULL) {
		SalStreamType type = report == call->log->reporting.reports[0] ? LINPHONE_CALL_STATS_AUDIO : report == call->log->reporting.reports[1] ? LINPHONE_CALL_STATS_VIDEO : LINPHONE_CALL_STATS_TEXT;
		call->log->reporting.on_report_sent(call, type, content);
	}


	route = linphone_proxy_config_get_quality_reporting_collector(call->dest_proxy);
	domain = ms_strdup_printf("sip:%s", linphone_proxy_config_get_domain(call->dest_proxy));
	request_uri = linphone_address_new(route ? route : domain);
	ms_free(domain);
	lev=linphone_core_create_publish(call->core, request_uri, "vq-rtcpxr", expires);
	if (route) {
		ms_message("Publishing report with custom route %s", route);
		sal_op_set_route(lev->op, route);
	}

	if (linphone_event_send_publish(lev, content) != 0){
		linphone_event_unref(lev);
		lev=NULL;
		ret=4;
	} else {
		reset_avg_metrics(report);
		STR_REASSIGN(report->qos_analyzer.timestamp, NULL);
		STR_REASSIGN(report->qos_analyzer.input_leg, NULL);
		STR_REASSIGN(report->qos_analyzer.input, NULL);
		STR_REASSIGN(report->qos_analyzer.output_leg, NULL);
		STR_REASSIGN(report->qos_analyzer.output, NULL);
	}

	linphone_address_destroy(request_uri);
	linphone_content_unref(content);

	end:
	ms_message("QualityReporting[%p]: Send '%s' with status %d",
		call,
		report_event,
		ret
	);

	return ret;
}
示例#15
0
static void append_metrics_to_buffer(char ** buffer, size_t * size, size_t * offset, const reporting_content_metrics_t rm) {
	char * timestamps_start_str = NULL;
	char * timestamps_stop_str = NULL;
	char * network_packet_loss_rate_str = NULL;
	char * jitter_buffer_discard_rate_str = NULL;
	/*char * gap_loss_density_str = NULL;*/
	char * moslq_str = NULL;
	char * moscq_str = NULL;
	uint8_t available_metrics = are_metrics_filled(rm);

	if (rm.timestamps.start > 0)
		timestamps_start_str = linphone_timestamp_to_rfc3339_string(rm.timestamps.start);
	if (rm.timestamps.stop > 0)
		timestamps_stop_str = linphone_timestamp_to_rfc3339_string(rm.timestamps.stop);

	append_to_buffer(buffer, size, offset, "Timestamps:");
		APPEND_IF_NOT_NULL_STR(buffer, size, offset, " START=%s", timestamps_start_str);
		APPEND_IF_NOT_NULL_STR(buffer, size, offset, " STOP=%s", timestamps_stop_str);

	if ((available_metrics & METRICS_SESSION_DESCRIPTION) != 0){
		append_to_buffer(buffer, size, offset, "\r\nSessionDesc:");
			APPEND_IF(buffer, size, offset, " PT=%d", rm.session_description.payload_type, rm.session_description.payload_type != -1);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " PD=%s", rm.session_description.payload_desc);
			APPEND_IF(buffer, size, offset, " SR=%d", rm.session_description.sample_rate, rm.session_description.sample_rate != -1);
			APPEND_IF(buffer, size, offset, " FD=%d", rm.session_description.frame_duration, rm.session_description.frame_duration != -1);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " FMTP=\"%s\"", rm.session_description.fmtp);
			APPEND_IF(buffer, size, offset, " PLC=%d", rm.session_description.packet_loss_concealment, rm.session_description.packet_loss_concealment != -1);
	}

	if ((available_metrics & METRICS_JITTER_BUFFER) != 0){
		append_to_buffer(buffer, size, offset, "\r\nJitterBuffer:");
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBA=%d", rm.jitter_buffer.adaptive, 0, 3);
			if (rm.rtcp_xr_count){
				APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBN=%d", rm.jitter_buffer.nominal/rm.rtcp_xr_count, 0, 65535);
				APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBM=%d", rm.jitter_buffer.max/rm.rtcp_xr_count, 0, 65535);
			}
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " JBX=%d",  rm.jitter_buffer.abs_max, 0, 65535);

		append_to_buffer(buffer, size, offset, "\r\nPacketLoss:");
			IF_NUM_IN_RANGE(rm.packet_loss.network_packet_loss_rate, 0, 255, network_packet_loss_rate_str = float_to_one_decimal_string(rm.packet_loss.network_packet_loss_rate / 256));
			IF_NUM_IN_RANGE(rm.packet_loss.jitter_buffer_discard_rate, 0, 255, jitter_buffer_discard_rate_str = float_to_one_decimal_string(rm.packet_loss.jitter_buffer_discard_rate / 256));

			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " NLR=%s", network_packet_loss_rate_str);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " JDR=%s", jitter_buffer_discard_rate_str);
	}

		/*append_to_buffer(buffer, size, offset, "\r\nBurstGapLoss:");*/
			/*IF_NUM_IN_RANGE(rm.burst_gap_loss.gap_loss_density, 0, 10, gap_loss_density_str = float_to_one_decimal_string(rm.burst_gap_loss.gap_loss_density));*/
		/*	append_to_buffer(buffer, size, offset, " BLD=%d", rm.burst_gap_loss.burst_loss_density);*/
		/*	append_to_buffer(buffer, size, offset, " BD=%d", rm.burst_gap_loss.burst_duration);*/
		/*	APPEND_IF_NOT_NULL_STR(buffer, size, offset, " GLD=%s", gap_loss_density_str);*/
		/*	append_to_buffer(buffer, size, offset, " GD=%d", rm.burst_gap_loss.gap_duration);*/
		/*	append_to_buffer(buffer, size, offset, " GMIN=%d", rm.burst_gap_loss.min_gap_threshold);*/

	if ((available_metrics & METRICS_DELAY) != 0){
		append_to_buffer(buffer, size, offset, "\r\nDelay:");
			if (rm.rtcp_xr_count+rm.rtcp_sr_count){
				APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " RTD=%d", rm.delay.round_trip_delay/(rm.rtcp_xr_count+rm.rtcp_sr_count), 0, 65535);
			}
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " ESD=%d", rm.delay.end_system_delay, 0, 65535);
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " IAJ=%d", rm.delay.interarrival_jitter, 0, 65535);
			APPEND_IF_NUM_IN_RANGE(buffer, size, offset, " MAJ=%d", rm.delay.mean_abs_jitter, 0, 65535);
	}

	if ((available_metrics & METRICS_SIGNAL) != 0){
		append_to_buffer(buffer, size, offset, "\r\nSignal:");
			APPEND_IF(buffer, size, offset, " SL=%d", rm.signal.level, rm.signal.level != 127);
			APPEND_IF(buffer, size, offset, " NL=%d", rm.signal.noise_level, rm.signal.noise_level != 127);
	}

	/*if quality estimates metrics are available, rtcp_xr_count should be always not null*/
	if ((available_metrics & METRICS_QUALITY_ESTIMATES) != 0){
		IF_NUM_IN_RANGE(rm.quality_estimates.moslq, 1, 5, moslq_str = float_to_one_decimal_string(rm.quality_estimates.moslq));
		IF_NUM_IN_RANGE(rm.quality_estimates.moscq, 1, 5, moscq_str = float_to_one_decimal_string(rm.quality_estimates.moscq));

		append_to_buffer(buffer, size, offset, "\r\nQualityEst:");
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " MOSLQ=%s", moslq_str);
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " MOSCQ=%s", moscq_str);
	}

	if (rm.user_agent!=NULL){
		append_to_buffer(buffer, size, offset, "\r\nLinphoneExt:");
			APPEND_IF_NOT_NULL_STR(buffer, size, offset, " UA=\"%s\"", rm.user_agent);
	}

	append_to_buffer(buffer, size, offset, "\r\n");

	ms_free(timestamps_start_str);
	ms_free(timestamps_stop_str);
	ms_free(network_packet_loss_rate_str);
	ms_free(jitter_buffer_discard_rate_str);
	/*ms_free(gap_loss_density_str);*/
	ms_free(moslq_str);
	ms_free(moscq_str);
}
示例#16
0
static mrb_value http_request_method(mrb_state *mrb, mrb_value self)
{
    h2o_mruby_generator_t *generator;
    struct st_h2o_mruby_http_request_context_t *ctx;
    const char *arg_url;
    mrb_int arg_url_len;
    mrb_value arg_hash;
    h2o_iovec_t method;
    h2o_url_t url;

    /* parse args */
    arg_hash = mrb_nil_value();
    mrb_get_args(mrb, "s|H", &arg_url, &arg_url_len, &arg_hash);

    /* precond check */
    if ((generator = h2o_mruby_current_generator) == NULL || generator->req == NULL)
        mrb_exc_raise(mrb, create_downstream_closed_exception(mrb));

    /* allocate context and initialize */
    ctx = h2o_mem_alloc_shared(&generator->req->pool, sizeof(*ctx), on_dispose);
    memset(ctx, 0, sizeof(*ctx));
    ctx->generator = generator;
    ctx->receiver = mrb_nil_value();
    h2o_buffer_init(&ctx->req.buf, &h2o_socket_buffer_prototype);
    h2o_buffer_init(&ctx->resp.after_closed, &h2o_socket_buffer_prototype);
    ctx->refs.request = mrb_nil_value();
    ctx->refs.input_stream = mrb_nil_value();

    /* uri */
    if (h2o_url_parse(arg_url, arg_url_len, &url) != 0)
        mrb_raise(mrb, E_ARGUMENT_ERROR, "invaild URL");

    /* method */
    method = h2o_iovec_init(H2O_STRLIT("GET"));
    if (mrb_hash_p(arg_hash)) {
        mrb_value t = mrb_hash_get(mrb, arg_hash, mrb_symbol_value(generator->ctx->symbols.sym_method));
        if (!mrb_nil_p(t)) {
            t = mrb_str_to_str(mrb, t);
            method = h2o_iovec_init(RSTRING_PTR(t), RSTRING_LEN(t));
        }
    }

    /* start building the request */
    h2o_buffer_reserve(&ctx->req.buf, method.len + 1);
    append_to_buffer(&ctx->req.buf, method.base, method.len);
    append_to_buffer(&ctx->req.buf, H2O_STRLIT(" "));
    h2o_buffer_reserve(&ctx->req.buf,
                       url.path.len + url.authority.len + sizeof(" HTTP/1.1\r\nConnection: close\r\nHost: \r\n") - 1);
    append_to_buffer(&ctx->req.buf, url.path.base, url.path.len);
    append_to_buffer(&ctx->req.buf, H2O_STRLIT(" HTTP/1.1\r\nConnection: close\r\nHost: "));
    append_to_buffer(&ctx->req.buf, url.authority.base, url.authority.len);
    append_to_buffer(&ctx->req.buf, H2O_STRLIT("\r\n"));

    /* headers */
    if (mrb_hash_p(arg_hash)) {
        mrb_value headers = mrb_hash_get(mrb, arg_hash, mrb_symbol_value(generator->ctx->symbols.sym_headers));
        if (!mrb_nil_p(headers)) {
            if (h2o_mruby_iterate_headers(generator->ctx, headers, flatten_request_header, ctx) != 0) {
                mrb_value exc = mrb_obj_value(mrb->exc);
                mrb->exc = NULL;
                mrb_exc_raise(mrb, exc);
            }
        }
    }
    /* body */
    if (mrb_hash_p(arg_hash)) {
        mrb_value body = mrb_hash_get(mrb, arg_hash, mrb_symbol_value(generator->ctx->symbols.sym_body));
        if (!mrb_nil_p(body)) {
            if (mrb_obj_eq(mrb, body, generator->rack_input)) {
                /* fast path */
                mrb_int pos;
                mrb_input_stream_get_data(mrb, body, NULL, NULL, &pos, NULL, NULL);
                ctx->req.body = generator->req->entity;
                ctx->req.body.base += pos;
                ctx->req.body.len -= pos;
            } else {
                if (!mrb_string_p(body)) {
                    body = mrb_funcall(mrb, body, "read", 0);
                    if (!mrb_string_p(body))
                        mrb_raise(mrb, E_ARGUMENT_ERROR, "body.read did not return string");
                }
                ctx->req.body = h2o_strdup(&ctx->generator->req->pool, RSTRING_PTR(body), RSTRING_LEN(body));
            }
            if (!ctx->req.has_transfer_encoding) {
                char buf[64];
                size_t l = (size_t)sprintf(buf, "content-length: %zu\r\n", ctx->req.body.len);
                h2o_buffer_reserve(&ctx->req.buf, l);
                append_to_buffer(&ctx->req.buf, buf, l);
            }
        }
    }

    h2o_buffer_reserve(&ctx->req.buf, 2);
    append_to_buffer(&ctx->req.buf, H2O_STRLIT("\r\n"));

    /* build request and connect */
    h2o_http1client_connect(&ctx->client, ctx, &generator->req->conn->ctx->proxy.client_ctx, url.host, h2o_url_get_port(&url),
                            on_connect);

    ctx->refs.request = h2o_mruby_create_data_instance(mrb, mrb_ary_entry(generator->ctx->constants, H2O_MRUBY_HTTP_REQUEST_CLASS),
                                                       ctx, &request_type);
    return ctx->refs.request;
}
示例#17
0
static int send_report(LinphoneCall* call, reporting_session_report_t * report, const char * report_event) {
	LinphoneContent *content = linphone_content_new();
	LinphoneAddress *addr;
	int expires = -1;
	size_t offset = 0;
	size_t size = 2048;
	char * buffer;
	int ret = 0;

	/*if we are on a low bandwidth network, do not send reports to not overload it*/
	if (linphone_call_params_low_bandwidth_enabled(linphone_call_get_current_params(call))){
		ms_warning("QualityReporting[%p]: Avoid sending reports on low bandwidth network", call);
		ret = 1;
		goto end;
	}

	/*if the call was hung up too early, we might have invalid IPs information
	in that case, we abort the report since it's not useful data*/
	if (report->info.local_addr.ip == NULL || strlen(report->info.local_addr.ip) == 0
		|| report->info.remote_addr.ip == NULL || strlen(report->info.remote_addr.ip) == 0) {
		ms_warning("QualityReporting[%p]: Trying to submit a %s too early (call duration: %d sec) but %s IP could "
			"not be retrieved so dropping this report"
			, call
			, report_event
			, linphone_call_get_duration(call)
			, (report->info.local_addr.ip == NULL || strlen(report->info.local_addr.ip) == 0) ? "local" : "remote");
		ret = 2;
		goto end;
	}

	addr = linphone_address_new(linphone_proxy_config_get_quality_reporting_collector(call->dest_proxy));
	if (addr == NULL) {
		ms_warning("QualityReporting[%p]: Asked to submit reporting statistics but no collector address found"
			, call);
		ret = 3;
		goto end;
	}

	buffer = (char *) belle_sip_malloc(size);
	linphone_content_set_type(content, "application");
	linphone_content_set_subtype(content, "vq-rtcpxr");

	append_to_buffer(&buffer, &size, &offset, "%s\r\n", report_event);
	append_to_buffer(&buffer, &size, &offset, "CallID: %s\r\n", report->info.call_id);
	append_to_buffer(&buffer, &size, &offset, "LocalID: %s\r\n", report->info.local_addr.id);
	append_to_buffer(&buffer, &size, &offset, "RemoteID: %s\r\n", report->info.remote_addr.id);
	append_to_buffer(&buffer, &size, &offset, "OrigID: %s\r\n", report->info.orig_id);

	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "LocalGroup: %s\r\n", report->info.local_addr.group);
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "RemoteGroup: %s\r\n", report->info.remote_addr.group);
	append_to_buffer(&buffer, &size, &offset, "LocalAddr: IP=%s PORT=%d SSRC=%u\r\n", report->info.local_addr.ip, report->info.local_addr.port, report->info.local_addr.ssrc);
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "LocalMAC: %s\r\n", report->info.local_addr.mac);
	append_to_buffer(&buffer, &size, &offset, "RemoteAddr: IP=%s PORT=%d SSRC=%u\r\n", report->info.remote_addr.ip, report->info.remote_addr.port, report->info.remote_addr.ssrc);
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "RemoteMAC: %s\r\n", report->info.remote_addr.mac);

	append_to_buffer(&buffer, &size, &offset, "LocalMetrics:\r\n");
	append_metrics_to_buffer(&buffer, &size, &offset, report->local_metrics);

	if (are_metrics_filled(report->remote_metrics)!=0) {
		append_to_buffer(&buffer, &size, &offset, "RemoteMetrics:\r\n");
		append_metrics_to_buffer(&buffer, &size, &offset, report->remote_metrics);
	}
	APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, "DialogID: %s\r\n", report->dialog_id);

	if (report->qos_analyzer.timestamp!=NULL){
		append_to_buffer(&buffer, &size, &offset, "AdaptiveAlg:");
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " NAME=\"%s\"", report->qos_analyzer.name);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " TS=\"%s\"", report->qos_analyzer.timestamp);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " IN_LEG=\"%s\"", report->qos_analyzer.input_leg);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " IN=\"%s\"", report->qos_analyzer.input);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " OUT_LEG=\"%s\"", report->qos_analyzer.output_leg);
			APPEND_IF_NOT_NULL_STR(&buffer, &size, &offset, " OUT=\"%s\"", report->qos_analyzer.output);
		append_to_buffer(&buffer, &size, &offset, "\r\n");
	}

	linphone_content_set_buffer(content, buffer, strlen(buffer));
	ms_free(buffer);

	if (call->log->reporting.on_report_sent != NULL){
		call->log->reporting.on_report_sent(
			call,
			(report==call->log->reporting.reports[0])?LINPHONE_CALL_STATS_AUDIO:LINPHONE_CALL_STATS_VIDEO,
			content);
	}

	if (! linphone_core_publish(call->core, addr, "vq-rtcpxr", expires, content)){
		ret=4;
	} else {
		reset_avg_metrics(report);
		STR_REASSIGN(report->qos_analyzer.timestamp, NULL);
		STR_REASSIGN(report->qos_analyzer.input_leg, NULL);
		STR_REASSIGN(report->qos_analyzer.input, NULL);
		STR_REASSIGN(report->qos_analyzer.output_leg, NULL);
		STR_REASSIGN(report->qos_analyzer.output, NULL);
	}

	linphone_address_destroy(addr);

	linphone_content_unref(content);

	end:
	ms_message("QualityReporting[%p]: Send '%s' with status %d",
		call,
		report_event,
		ret
	);

	return ret;
}
示例#18
0
/**
 * @brief read from a child stdout.
 * @param c the child from read to
 * @returns 0 on success, -1 on error
 */
int read_stdout(child_node *c) {
  int count;
  int ret;
  char *buff;
  char *line;
  message *m;
  
  buff = malloc(STDOUT_BUFF_SIZE);
    
  if(!buff) {
    print( ERROR, "malloc: %s", strerror(errno));
    return -1;
  }
  
  ret = 0;
  
  if(c->handler->raw_output_parser) { // parse raw bytes
    while((count=read(c->stdout_fd, buff, STDOUT_BUFF_SIZE)) > 0) {
      if(c->handler->raw_output_parser(c, buff, count)) {
        ret = -1;
        break;
      }
    }
  } else if(c->handler->output_parser) { // parse lines
    while(!ret && (count=read(c->stdout_fd, buff, STDOUT_BUFF_SIZE)) > 0) {
      if(append_to_buffer(&(c->output_buff), buff, count)) {
        ret = -1;
        continue;
      }
      while((line = get_line_from_buffer(&(c->output_buff)))) {
        m = c->handler->output_parser(line);
        if(m) {
          m->head.id = c->id;
          m->head.seq = c->seq + 1;
          
#ifdef BROADCAST_EVENTS
          if(broadcast_message(m)) {
            print( ERROR, "cannot broadcast messages.");
#else
          if(enqueue_message(&(c->conn->outcoming), m)) {
            print( ERROR, "cannot enqueue messages.");
#endif
            dump_message(m);
            free_message(m);
            ret = -1;
            // events not sent are not fatal, just a missed event.
            // while in raw connection a missed message will de-align the output/input.
            // this is why a "break;" is missing here
          } else {
            c->seq++;
          }
        }
        free(line);
      }
    }
  } else { // send raw bytes
    while((count=read(c->stdout_fd, buff, STDOUT_BUFF_SIZE)) > 0) {
      m = create_message(c->seq + 1, count, c->id);
      if(!m) {
        buff[MIN(count, STDOUT_BUFF_SIZE -1)] = '\0';
        print( ERROR, "cannot send the following output: '%s'", buff);
        ret = -1;
        break;
      }
      memcpy(m->data, buff, count);
      if(enqueue_message(&(c->conn->outcoming), m)) {
        print( ERROR, "cannot enqueue messages.");
        dump_message(m);
        free_message(m);
        ret = -1;
        break;
      } else {
        c->seq++;
      }
    }
  }
  
  if(count<0) {
    print( ERROR, "read: %s", strerror(errno));
    ret = -1;
  }
  
  free(buff);
  
  release_buffer(&(c->output_buff));
  
  return ret;
}
/*@null@*/
char *stats_prefix_dump(int *length) {
#define STATS_PREFIX_DUMP_FORMAT \
    "PREFIX %.*s item %u get %" PRINTF_INT64_MODIFIER                   \
        "u hit %" PRINTF_INT64_MODIFIER "u set %" PRINTF_INT64_MODIFIER \
        "u del %" PRINTF_INT64_MODIFIER "u evict %" PRINTF_INT64_MODIFIER \
        "u ov %" PRINTF_INT64_MODIFIER "u exp %" PRINTF_INT64_MODIFIER  \
        "u bytes %" PRINTF_INT64_MODIFIER "u txed %" PRINTF_INT64_MODIFIER \
        "u byte-seconds %" PRINTF_INT64_MODIFIER "u\r\n"
    PREFIX_STATS *pfs;
    char *buf;
    int i;
    size_t size, offset = 0;
    const int format_len = sizeof("%" PRINTF_INT64_MODIFIER "u") - sizeof("");
    char terminator[] = "END\r\n";
    char wildcard_name[] = "*wildcard*";
    rel_time_t now = current_time;

    /*
     * Figure out how big the buffer needs to be. This is the sum of the
     * lengths of the prefixes themselves, plus the size of one copy of
     * the per-prefix output with 20-digit values for all the counts,
     * plus space for the "END" at the end.
     */
    GLOBAL_STATS_LOCK();
    size = total_prefix_size +
        (num_prefixes + 1) * (strlen(STATS_PREFIX_DUMP_FORMAT)
                              + 11 * (20 - format_len)) /* %llu replaced by 20-digit num */
        + sizeof(wildcard_name)
        + sizeof("END\r\n");
    buf = malloc(size);
    if (NULL == buf) {
        perror("Can't allocate stats response: malloc");
        GLOBAL_STATS_UNLOCK();
        return NULL;
    }

    for (i = 0; i < PREFIX_HASH_SIZE; i++) {
        for (pfs = prefix_stats[i]; NULL != pfs; pfs = pfs->next) {
            /*
             * increment total byte-seconds to reflect time elapsed since last
             * update.
             */
            pfs->total_byte_seconds += pfs->num_bytes * (now - pfs->last_update);
            pfs->last_update = now;

            offset = append_to_buffer(buf, size, offset, sizeof(terminator),
                                      STATS_PREFIX_DUMP_FORMAT, (unsigned) pfs->prefix_len,
                                      pfs->prefix, pfs->num_items, pfs->num_gets, pfs->num_hits,
                                      pfs->num_sets, pfs->num_deletes, pfs->num_evicts,
                                      pfs->num_overwrites, pfs->num_expires,
                                      pfs->num_bytes, pfs->bytes_txed,
                                      pfs->total_byte_seconds);
        }
    }

    /*
     * increment total byte-seconds to reflect time elapsed since last update.
     */
    wildcard.total_byte_seconds += wildcard.num_bytes * (now - wildcard.last_update);
    wildcard.last_update = now;

    if (wildcard.num_gets != 0 ||
        wildcard.num_sets != 0 ||
        wildcard.num_deletes != 0) {
        offset = append_to_buffer(buf, size, offset, sizeof(terminator),
                                  STATS_PREFIX_DUMP_FORMAT, (unsigned) (sizeof(wildcard_name) - 1),
                                  wildcard_name, wildcard.num_items,
                                  wildcard.num_gets, wildcard.num_hits,
                                  wildcard.num_sets, wildcard.num_deletes, wildcard.num_evicts,
                                  wildcard.num_overwrites, wildcard.num_expires,
                                  wildcard.num_bytes, wildcard.bytes_txed,
                                  wildcard.total_byte_seconds);
    }

    offset = append_to_buffer(buf, size, offset, 0, terminator);

    *length = offset;
    GLOBAL_STATS_UNLOCK();

    return buf;
}