Ejemplo n.º 1
0
int test1()
{
    double pre, post;
    int *tmp;
    array_t a = array_init( int, 1 );
    pre = gettime_ms();
    for ( int i = 0; i < 1E7; i++ ) array_int_append( &a, i );
    post = gettime_ms();

    int success = 0;
    int counter = 0;
    for ( int i = 0; i < 1E7; i++ ) {
        tmp = array_int( a );
        /* char *dame = array_char( a ); /\**< incorrect type will be asserted *\/ */
        /* printf( "%c\n", dame[i] ); */
        if ( tmp[i] == i ) success++;
        counter++;
    }
    printf( "# array has %lld elems and malloced %lld Bytes\n",
            array_size( a ), a.alloced * sizeof(int) );
    printf( "# %5d / %5d are correct.\n", success, counter );
    printf( "# %6.2lf[ms] is elapsed.\n", post - pre );

    array_destroy( &a );

    return success==counter;
}
Ejemplo n.º 2
0
int main(int argc,char **argv)
{
  if (argc>2&&argv[2]) start_addr=strtoll(argv[2],NULL,16);
  if (argc>3&&argv[3]) end_addr=strtoll(argv[3],NULL,16);
  printf("Dumping memory from $%x to $%x\n",start_addr,end_addr);

  errno=0;
  fd=open(argv[1],O_RDWR);
  perror("A");
  if (fd==-1) perror("open");
  perror("B");
  fcntl(fd,F_SETFL,fcntl(fd, F_GETFL, NULL)|O_NONBLOCK);
  perror("C");
  struct termios t;
  if (cfsetospeed(&t, B230400)) perror("Failed to set output baud rate");
  perror("D");
  if (cfsetispeed(&t, B230400)) perror("Failed to set input baud rate");
  perror("E");
  t.c_cflag &= ~PARENB;
  t.c_cflag &= ~CSTOPB;
  t.c_cflag &= ~CSIZE;
  t.c_cflag &= ~CRTSCTS;
  t.c_cflag |= CS8 | CLOCAL;
  t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO | ECHOE);
  t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR |
                 INPCK | ISTRIP | IXON | IXOFF | IXANY | PARMRK);
  t.c_oflag &= ~OPOST;
  if (tcsetattr(fd, TCSANOW, &t)) perror("Failed to set terminal parameters");
  perror("F");

  unsigned long long last_check = gettime_ms();

  while(1)
    {
      int b;
      char read_buff[1024];
      switch(state) {
      case 0: case 99:
	errno=0;
	b=read(fd,read_buff,1024);
	if (b>0) {
	  int i;
	  for(i=0;i<b;i++) {
	    process_char(read_buff[i],1);
	  }
	} else {
	  usleep(1000);
	}
	if (gettime_ms()>last_check) {
	  if (state==99) printf("sending M command to sync.\n");
	  sprintf(filename,"M%x\r",start_addr);
	  slow_write(fd,filename,strlen(filename));
	  last_check=gettime_ms()+50;
	}
	break;
      }
    }

  return 0;
}
Ejemplo n.º 3
0
int main(int argc,char **argv)
{
  search_path=argv[2];
  fd=open(argv[1],O_RDWR);
  if (fd==-1) perror("open");
  if (fcntl(fd,F_SETFL,fcntl(fd, F_GETFL, NULL)|O_NONBLOCK))
    perror("fcntl");
  struct termios t;
  if (cfsetospeed(&t, B230400)) perror("Failed to set output baud rate");
  if (cfsetispeed(&t, B230400)) perror("Failed to set input baud rate");
  t.c_cflag &= ~PARENB;
  t.c_cflag &= ~CSTOPB;
  t.c_cflag &= ~CSIZE;
  t.c_cflag |= CS8;
  t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO | ECHOE);
  t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR |
                 INPCK | ISTRIP | IXON | IXOFF | IXANY | PARMRK);
  t.c_oflag &= ~OPOST;
  if (tcsetattr(fd, TCSANOW, &t)) perror("Failed to set terminal parameters");

  // Send ^U r <return> to print registers and get into a known state.
  usleep(20000);
  slow_write(fd,"\r",1);
  usleep(50000);
  slow_write(fd,"r\r",2);

  unsigned long long last_check = gettime_ms();

  while(1)
    {
      int b;
      char read_buff[1024];
	b=read(fd,read_buff,1024);
	if (b>0) {
	  int i;
	  for(i=0;i<b;i++) {
	    process_char(read_buff[i],1);
	  }
	} else usleep(10000);
	if (gettime_ms()>last_check) {
	  if (!toggle) {
	    char cmd[1024];
	    // set debug coordinates
	    debug_x++;
	    debug_x&=0xfff;
	    sprintf(cmd,"sffd30fc %02x %02x %02x %02x\r",
		    debug_x&0xff,debug_x>>8,debug_y&0xff,debug_y>>8);
	    slow_write(fd,cmd,strlen(cmd));
	  } else {
	    // read debug registers
	    slow_write(fd,"mffd30f0\r",9);
	  }
	  toggle^=1;
	  // Allow 2 frames before advancing debug point
	  last_check=gettime_ms()+(1000/60)*2;
	}
Ejemplo n.º 4
0
	int PeerCon::sendPeerMsg(const Message& pm, int64& msgid){

		int ret = 0;

		MsgDB* c = DBConn::getMsgDB();
		if(!c){
			return DB_ERROR;		
		}

		Message m = pm;

		ret = c->incrId("peer_" + pm.to() + "_last_msgid", msgid);
		if(ret < 0){
			return DB_ERROR;
		}

		m.set_id(msgid);
		m.set_time(gettime_ms());
		m.set_sn(getPackSN());
	
		ret = c->addMsg("peer_" + m.to(), m);	

		return ret; 

	}
Ejemplo n.º 5
0
static void free_acked_packets(struct msp_window *window, uint16_t seq)
{
  if (!window->_head)
    return;
  
  struct msp_packet *p = window->_head;
  
  uint32_t rtt=0;
  time_ms_t now = gettime_ms();

  while(p && compare_wrapped_uint16(p->seq, seq)<=0){
    if (p->sent)
      rtt = now - p->sent;
    struct msp_packet *free_me=p;
    p=p->_next;
    if (free_me->payload)
      free((void *)free_me->payload);
    free(free_me);
    window->packet_count--;
  }
  window->_head = p;
  if (rtt){
    if (rtt < 10)
      rtt=10;
    window->rtt = rtt;
    if (window->base_rtt > rtt)
      window->base_rtt = rtt;
    if (config.debug.msp)
      DEBUGF("RTT %u, base %u", rtt, window->base_rtt);
  }
  if (!p)
    window->_tail = NULL;
}
Ejemplo n.º 6
0
// called when we discover a route to the directory service SID
int directory_registration(){
  // give the route & SAS keys a moment to propagate
  unschedule(&directory_alarm);
  directory_alarm.alarm = gettime_ms() + 200;
  directory_alarm.deadline = directory_alarm.alarm + 10000;
  schedule(&directory_alarm);
  return 0;
}
Ejemplo n.º 7
0
/* When should we next allow this thing to occur? */
time_ms_t limit_next_allowed(struct limit_state *state){
  time_ms_t now = gettime_ms();
  update_limit_state(state, now);
  
  if (state->sent < state->burst_size)
    return now;
  return state->next_interval;
}
Ejemplo n.º 8
0
int
main()
{
	int mdp_sock;
	MSP_SOCKET msp_sock;
	struct mdp_sockaddr addr;
	struct sigaction act;
	struct timeval timeout;
 	time_ms_t now;
	time_ms_t next_time = 0;

	/* sample message to reply to clients */
	strcpy((char *)outbuf, "Hello World!");

	if ((mdp_sock = mdp_socket()) < 0) {
		std::cerr << "server: error creating mdp socket" << std::endl;
		return -1;
	}
	msp_sock = msp_socket(mdp_sock, 0);

	addr.sid = SID_ANY;
	addr.port = PORT;

	msp_set_local(msp_sock, &addr);
	msp_set_handler(msp_sock, listen_handler, NULL);
	msp_listen(msp_sock);
	if (!msp_socket_is_open(msp_sock)) {
		std::cerr << "server: error listening on msp socket" << std::endl;
		return -1;
	}

	/* cleanup on CTRL-C */
	memset(&act, 0, sizeof(act));
	act.sa_handler = &cleanup;
	if (sigaction(SIGINT, &act, NULL) < 0) {
		fprintf(stderr, "error registering signal handler\n");
		return -1;
	}

	/* main loop */
	std::cout << "server: starting server..." << std::endl;
	quit = 0;
	while (!quit) {
		now = gettime_ms();
		if (now < next_time) {
			struct timeval timeout = time_ms_to_timeval(next_time - now);
			setsockopt(mdp_sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
			msp_recv(mdp_sock);
		}
		msp_processing(&next_time);
	}

	std::cout << "server: cleanup..." << std::endl;
	msp_close_all(mdp_sock);
	mdp_close(mdp_sock);

	return 0;
}
Ejemplo n.º 9
0
static void monitor_requests(struct sched_ent *alarm)
{
  if (config.debug.dnahelper) {
    DEBUGF("sched_requests.poll.fd=%d .revents=%s",
	sched_requests.poll.fd,
	strbuf_str(strbuf_append_poll_events(strbuf_alloca(40), sched_requests.poll.revents))
      );
  }
  assert(alarm == &sched_requests);
  // On Linux, poll(2) returns ERR when the remote reader dies.  On Mac OS X, poll(2) returns NVAL,
  // which is documented to mean the file descriptor is not open, but testing revealed that in this
  // case it is still open.  See issue #5.
  if (sched_requests.poll.revents & (POLLHUP | POLLERR | POLLNVAL)) {
    if (config.debug.dnahelper)
      DEBUGF("DNAHELPER closing stdin fd=%d", dna_helper_stdin);
    close(dna_helper_stdin);
    dna_helper_stdin = -1;
    unwatch(&sched_requests);
    sched_requests.poll.fd = -1;
    dna_helper_kill();
  }
  else if (sched_requests.poll.revents & POLLOUT) {
    if (request_bufptr) {
      if (request_bufptr < request_bufend) {
	size_t remaining = request_bufend - request_bufptr;
	sigPipeFlag = 0;
	ssize_t written = write_nonblock(dna_helper_stdin, request_bufptr, remaining);
	if (sigPipeFlag) {
	  /* Broken pipe is probably due to a dead helper, but make sure the helper is dead, just to be
	    sure.  It will be harvested at the next harvester() timeout, and restarted on the first
	    request that arrives after a suitable pause has elapsed.  Losing the current request is not
	    a big problem, because DNA preemptively retries.
	  */
	  INFO("DNAHELPER got SIGPIPE on write -- stopping process");
	  dna_helper_kill();
	} else if (written > 0) {
	  if (config.debug.dnahelper)
	    DEBUGF("DNAHELPER wrote request %s", alloca_toprint(-1, request_bufptr, written));
	  request_bufptr += written;
	}
      }
      if (request_bufptr >= request_bufend) {
	// Request sent successfully.  Start watching for reply.
	request_bufptr = request_bufend = NULL;
	awaiting_reply = 1;
	sched_timeout.alarm = gettime_ms() + 1500;
	sched_timeout.deadline = sched_timeout.alarm + 3000;
	schedule(&sched_timeout);
      }
    }
    // If no request to send, stop monitoring the helper's stdin pipe.
    if (!request_bufptr) {
      unwatch(&sched_requests);
      sched_requests.poll.fd = -1;
    }
  }
}
Ejemplo n.º 10
0
/* Can we do this now? if so, track it */
int limit_is_allowed(struct limit_state *state){
  time_ms_t now = gettime_ms();
  update_limit_state(state, now);
  if (state->sent >= state->burst_size){
    return -1;
  }
  state->sent ++;
  return 0;
}
Ejemplo n.º 11
0
int overlay_send_tick_packet(struct overlay_interface *interface){
  struct outgoing_packet packet;
  bzero(&packet, sizeof(struct outgoing_packet));
  packet.seq=-1;
  overlay_init_packet(&packet, NULL, 0, 0, interface, interface->broadcast_address);
  
  overlay_fill_send_packet(&packet, gettime_ms());
  return 0;
}
Ejemplo n.º 12
0
static void harvester(struct sched_ent *alarm)
{
  // While the helper process appears to still be running, keep calling this function.
  // Otherwise, wait a while before re-starting the helper.
  if (dna_helper_harvest(0) <= 0) {
    sched_harvester.alarm = gettime_ms() + 1000;
    sched_harvester.deadline = sched_harvester.alarm + 1000;
    schedule(&sched_harvester);
  } else {
    const int delay_ms = 500;
    if (debug & DEBUG_DNAHELPER)
      DEBUGF("DNAHELPER process died, pausing %d ms before restart", delay_ms);
    dna_helper_pid = 0; // Will be set to -1 after delay
    sched_restart.function = restart_delayer;
    sched_restart.alarm = gettime_ms() + delay_ms;
    sched_restart.deadline = sched_restart.alarm + 500;
    schedule(&sched_restart);
  }
}
Ejemplo n.º 13
0
int msp_set_remote(struct msp_sock *sock, struct mdp_sockaddr remote)
{
  assert(sock->state == MSP_STATE_UNINITIALISED);
  sock->header.remote = remote;
  sock->state|=MSP_STATE_DATAOUT;
  // make sure we send a packet soon
  sock->next_ack = gettime_ms()+10;
  sock->next_action = sock->next_ack;
  return 0;
}
Ejemplo n.º 14
0
static int add_packet(struct msp_window *window, uint16_t seq, uint8_t flags, 
  const uint8_t *payload, size_t len)
{
  
  struct msp_packet **insert_pos=NULL;
  
  if (!window->_head){
    insert_pos = &window->_head;
  }else{
    if (window->_tail->seq == seq){
      // ignore duplicate packets
      return 0;
    }else if (compare_wrapped_uint16(window->_tail->seq, seq)<0){
      if (compare_wrapped_uint16(window->_head->seq, seq)>0){
	// this is ambiguous
	return WHYF("%04x is both < tail (%04x) and > head (%04x)", seq, window->_tail->seq, window->_head->seq);
      }
      insert_pos = &window->_tail->_next;
    }else{
      insert_pos = &window->_head;
      while(compare_wrapped_uint16((*insert_pos)->seq, seq)<0)
	insert_pos = &(*insert_pos)->_next;
      if ((*insert_pos)->seq == seq){
	// ignore duplicate packets
	return 0;
      }
    }
  }
  
  struct msp_packet *packet = emalloc_zero(sizeof(struct msp_packet));
  if (!packet)
    return -1;
    
  packet->_next = (*insert_pos);
  *insert_pos = packet;
  if (!packet->_next)
    window->_tail = packet;
  packet->added = gettime_ms();
  packet->seq = seq;
  packet->flags = flags;
  packet->len = len;
  
  if (payload && len){
    uint8_t *p = emalloc(len);
    if (!p){
      free(packet);
      return -1;
    }
    packet->payload = p;
    bcopy(payload, p, len);
  }
  window->packet_count++;
  return 1;
}
Ejemplo n.º 15
0
Archivo: s2.cpp Proyecto: dCache/s2
static void
init_s2(void)
{
  /* s2 options */
  opts.help = 0;			/* 0: no help; 1: basic help; ... */
  opts.ansi = FALSE;			/* use ansi colors */
  opts.verbose = 0;			/* -2: no errors; -1: no warnings; 0: normal; 1: verbose */
  opts.pp_indent = PP_INDENT;		/* pretty-printer indentation value */
  opts.show_defaults = FALSE;		/* show default values (pretty-printer, evaluator) */
  opts.scr_fname = NULL;		/* script filename */
  opts.simple_name = FALSE;		/* whether ${0} has the simple name */
  opts.progress_bar = TRUE;		/* show progres bar */
  opts.pp_fname = NULL;			/* pretty-printer output filename */
  opts.pp_file = PP_DEFAULT_OUTPUT;	/* pretty-printer output file */
  opts.log_fname = NULL;		/* log messages output filename */
  opts.dbg_fname = NULL;		/* debug messages output filename */
  opts.warn_fname = NULL;		/* warning messages output filename */
  opts.err_fname = NULL;		/* error messages output filename */
  opts.e0_fname = NULL;			/* before-execution log messages filename */
  opts.e0_file = E0_DEFAULT_OUTPUT;	/* before-execution log messages file */
  opts.e1_fname = NULL;			/* after-execution log messages filename */
  opts.e1_file = E1_DEFAULT_OUTPUT;	/* after-execution log messages file */
  opts.e2_fname = NULL;			/* after-evaluation log messages filename */
  opts.e2_file = E2_DEFAULT_OUTPUT;	/* after-evaluation log messages file */
  opts.s2_eval = S2_EVAL;		/* default evaluation threshold for branches */
  opts.s2_timeout = S2_TIMEOUT;		/* default timeout for branches in microseconds */
  opts.tp_size = TP_THREADS_DEF;	/* number of threads to use in the thread pool */

  /* diagnose library */
  DM_PGMNAME_SET(PNAME());
  DM_ANSI_SET(opts.ansi);		/* environment variable DM_ANSI takes preference over this */
  DM_LOG_OPEN(opts.log_fname);
  DM_DBG_OPEN(opts.dbg_fname);
  DM_WARN_OPEN(opts.warn_fname);
  DM_ERR_OPEN(opts.err_fname);
  /* no debug (apart 0-level messages), environment variable DG_DBG takes preference over this */
  DM_DBG_SET_L(0);

  /* callback functions */
  DM_WARN_CB(WarnCB);
  DM_ERR_CB(ErrCB);

  /* open output files */
  f_open(opts.pp_fname, &opts.pp_file);
  f_open(opts.e0_fname, &opts.e0_file);
  f_open(opts.e1_fname, &opts.e1_file);
  f_open(opts.e2_fname, &opts.e2_file);

  /* initialise random number generation */
  srandom(gettime_ms() + (getpid() << 16));
}
Ejemplo n.º 16
0
static void *ir_thread() {
	char *code;
	
	while (fd > 0 && LIRC(i, nextcode, &code) == 0) {
		
		u32_t now = gettime_ms();
		u32_t ir_code = 0;
		
		if (code == NULL) continue;
		
		if (config) {
			// allow lirc_client to decode then lookup cmd in our table
			// we can only send one IR event to slimproto so break after first one
			char *c;
			while (LIRC(i, code2char, config, code, &c) == 0 && c != NULL) {
				ir_code = ir_cmd_map(c);
				if (ir_code) {
					LOG_DEBUG("ir cmd: %s -> %x", c, ir_code);
				}
			}
		}

		if (!ir_code) {
			// try to match on lirc button name if it is from the standard namespace
			// this allows use of non slim remotes without a specific entry in .lircrc
			char *b, *r;
			strtok(code, " \n");     // discard
			r = strtok(NULL, " \n"); // repeat count
			b = strtok(NULL, " \n"); // key name
			if (r && b) {
				ir_code = ir_key_map(b, r);
				LOG_DEBUG("ir lirc: %s [%s] -> %x", b, r, ir_code);
			}
		}

		if (ir_code) {
			LOCK_I;
			if (ir.code) {
				LOG_DEBUG("code dropped");
			}
			ir.code = ir_code;
			ir.ts = now;
			UNLOCK_I;
			wake_controller();
		}
		
		free(code);
	}
	
	return 0;
}
Ejemplo n.º 17
0
int parse_rfd900_rssi(char *s)
{
  int lrssi,rrssi,lnoise,rnoise,rxpackets,temp;

  // L/R RSSI: 48/0  L/R noise: 62/0 pkts: 0  txe=0 rxe=0 stx=0 srx=0 ecc=0/0 temp=21 dco=0
  if (sscanf(s,"L/R RSSI: %d/%d  L/R noise: %d/%d pkts: %d  txe=%*d rxe=%*d stx=%*d srx=%*d ecc=%*d/%*d temp=%d dco=%*d",
	     &lrssi,&rrssi,&lnoise,&rnoise,&rxpackets, &temp)==6)
    {
      int lmargin=(lrssi-lnoise)/1.9;
      int rmargin=(rrssi-rnoise)/1.9;
      int maxmargin=lmargin; if (rmargin>maxmargin) maxmargin=rmargin;
      last_radio_rssi=maxmargin;
      last_radio_temperature=temp;
      last_radio_rxpackets=rxpackets;

      if (gettime_ms()-last_rssi_time>30000) {
	INFOF("Link budget = %+ddB, temperature=%dC",maxmargin,temp);
	last_rssi_time=gettime_ms();
      }
    }

  return 0;
}
Ejemplo n.º 18
0
void rhizome_server_poll(struct sched_ent *alarm)
{
  if (alarm->poll.revents & (POLLIN | POLLOUT)) {
    struct sockaddr addr;
    unsigned int addr_len = sizeof addr;
    int sock;
    while ((sock = accept(rhizome_server_socket, &addr, &addr_len)) != -1) {
      if (addr.sa_family == AF_INET) {
	struct sockaddr_in *peerip = (struct sockaddr_in *)&addr;
	INFOF("RHIZOME HTTP SERVER, ACCEPT addrlen=%u family=%u port=%u addr=%u.%u.%u.%u",
	    addr_len, peerip->sin_family, peerip->sin_port,
	    ((unsigned char*)&peerip->sin_addr.s_addr)[0],
	    ((unsigned char*)&peerip->sin_addr.s_addr)[1],
	    ((unsigned char*)&peerip->sin_addr.s_addr)[2],
	    ((unsigned char*)&peerip->sin_addr.s_addr)[3]
	  );
      } else {
	INFOF("RHIZOME HTTP SERVER, ACCEPT addrlen=%u family=%u data=%s",
	  addr_len, addr.sa_family, alloca_tohex((unsigned char *)addr.sa_data, sizeof addr.sa_data)
	);
      }
      rhizome_http_request *request = calloc(sizeof(rhizome_http_request), 1);
      if (request == NULL) {
	WHYF_perror("calloc(%u, 1)", sizeof(rhizome_http_request));
	WHY("Cannot respond to request, out of memory");
      } else {
	/* We are now trying to read the HTTP request */
	request->request_type=RHIZOME_HTTP_REQUEST_RECEIVING;
	request->alarm.function = rhizome_client_poll;
	connection_stats.name="rhizome_client_poll";
	request->alarm.stats=&connection_stats;
	request->alarm.poll.fd=sock;
	request->alarm.poll.events=POLLIN;
	request->alarm.alarm = gettime_ms()+RHIZOME_IDLE_TIMEOUT;
	request->alarm.deadline = request->alarm.alarm+RHIZOME_IDLE_TIMEOUT;
	// watch for the incoming http request
	watch(&request->alarm);
	// set an inactivity timeout to close the connection
	schedule(&request->alarm);
      }
    }
    if (errno != EAGAIN) {
      WARN_perror("accept");
    }
  }
  
  if (alarm->poll.revents & (POLLHUP | POLLERR)) {
    INFO("Error on tcp listen socket");
  }
}
Ejemplo n.º 19
0
static void directory_update(struct sched_ent *alarm){
  load_directory_config();
  
  if (directory_service){
    if (subscriber_is_reachable(directory_service) != REACHABLE_NONE){
      directory_send_keyring(directory_service);
      
      alarm->alarm = gettime_ms() + DIRECTORY_UPDATE_INTERVAL;
      alarm->deadline = alarm->alarm + 10000;
      schedule(alarm);
    }else
      DEBUGF("Directory service is not reachable");
  }
}
Ejemplo n.º 20
0
// de-queue all packets that have been sent to this subscriber & have arrived.
int overlay_queue_ack(struct subscriber *neighbour, struct overlay_interface *interface, uint32_t ack_mask, int ack_seq)
{
  int interface_id = interface - overlay_interfaces;
  int i;
  time_ms_t now = gettime_ms();
  for (i=0;i<OQ_MAX;i++){
    struct overlay_frame *frame = overlay_tx[i].first;

    while(frame){
      int frame_seq = frame->interface_sent_sequence[interface_id];
      if (frame_seq >=0 && (frame->next_hop == neighbour || !frame->destination)){
	int seq_delta = (ack_seq - frame_seq)&0xFF;
	char acked = (seq_delta==0 || (seq_delta <= 32 && ack_mask&(1<<(seq_delta-1))))?1:0;

	if (acked){
          frame->interface_sent_sequence[interface_id] = FRAME_DONT_SEND;
	  int discard = 1;
	  if (!frame->destination){
            int j;
            for(j=0;j<OVERLAY_MAX_INTERFACES;j++){
	      if (overlay_interfaces[j].state==INTERFACE_STATE_UP &&
                  frame->interface_sent_sequence[j]!=FRAME_DONT_SEND &&
		  link_state_interface_has_neighbour(&overlay_interfaces[j])){
	        discard = 0;
	        break;
	      }
	    }
	  }
	  if (discard){
	    if (config.debug.overlayframes)
	      DEBUGF("Dequeing packet %p to %s sent by seq %d, due to ack of seq %d", frame, alloca_tohex_sid(neighbour->sid), frame_seq, ack_seq);
            frame = overlay_queue_remove(&overlay_tx[i], frame);
	    continue;
	  }
	}

	if (seq_delta < 128 && frame->destination && frame->dont_send_until>now){
	  // resend immediately
	  if (config.debug.overlayframes)
	    DEBUGF("Requeue packet %p to %s sent by seq %d due to ack of seq %d", frame, alloca_tohex_sid(neighbour->sid), frame_seq, ack_seq);
	  frame->dont_send_until = now;
	  overlay_calc_queue_time(&overlay_tx[i], frame);
	}
      }
      frame = frame->next;
    }
  }
  return 0;
}
Ejemplo n.º 21
0
void msp_debug()
{
  time_ms_t now = gettime_ms();
  struct msp_sock *p=root;
  DEBUGF("Msp sockets;");
  while(p){
    DEBUGF("State %d, from %s:%d to %s:%d, next %"PRId64"ms, ack %"PRId64"ms timeout %"PRId64"ms", 
      p->state, 
      alloca_tohex_sid_t(p->header.local.sid), p->header.local.port, 
      alloca_tohex_sid_t(p->header.remote.sid), p->header.remote.port,
      (p->next_action - now),
      (p->next_ack - now),
      (p->timeout - now));
    p=p->_next;
  }
}
Ejemplo n.º 22
0
void rhizome_client_poll(struct sched_ent *alarm)
{
  rhizome_http_request *r = (rhizome_http_request *)alarm;
  if (alarm->poll.revents == 0){
    rhizome_server_free_http_request(r);
    return;
  }
  switch(r->request_type)
    {
    case RHIZOME_HTTP_REQUEST_RECEIVING:
      /* Keep reading until we have two CR/LFs in a row */
      r->request[r->request_length] = '\0';
      sigPipeFlag=0;
      int bytes = read_nonblock(r->alarm.poll.fd, &r->request[r->request_length], RHIZOME_HTTP_REQUEST_MAXLEN - r->request_length);
      /* If we got some data, see if we have found the end of the HTTP request */
      if (bytes > 0) {
	// reset inactivity timer
	r->alarm.alarm = gettime_ms() + RHIZOME_IDLE_TIMEOUT;
	r->alarm.deadline = r->alarm.alarm + RHIZOME_IDLE_TIMEOUT;
	unschedule(&r->alarm);
	schedule(&r->alarm);
	r->request_length += bytes;
	if (http_header_complete(r->request, r->request_length, bytes + 4)) {
	  /* We have the request. Now parse it to see if we can respond to it */
	  rhizome_server_parse_http_request(r);
	}
      } else {
	if (debug & DEBUG_RHIZOME_TX)
	  DEBUG("Empty read, closing connection");
	rhizome_server_free_http_request(r);
	return;
      }
      if (sigPipeFlag) {
	if (debug & DEBUG_RHIZOME_TX)
	  DEBUG("Received SIGPIPE, closing connection");
	rhizome_server_free_http_request(r);
	return;
      }
      break;
    default:
      /* Socket already has request -- so just try to send some data. */
      rhizome_server_http_send_bytes(r);
      break;
  }
  return;
}
Ejemplo n.º 23
0
int msp_listen(struct msp_sock *sock)
{
  assert(sock->state == MSP_STATE_UNINITIALISED);
  assert(sock->header.local.port);
  
  sock->state |= MSP_STATE_LISTENING;
  sock->header.flags |= MDP_FLAG_BIND;
  
  if (mdp_send(sock->mdp_sock, &sock->header, NULL, 0)==-1){
    sock->state|=MSP_STATE_ERROR|MSP_STATE_CLOSED;
    return -1;
  }
  
  sock->timeout = gettime_ms()+1000;
  sock->next_action = sock->timeout;
  return 0;
}
Ejemplo n.º 24
0
struct msp_sock * msp_socket(int mdp_sock)
{
  struct msp_sock *ret = emalloc_zero(sizeof(struct msp_sock));
  ret->mdp_sock = mdp_sock;
  ret->state = MSP_STATE_UNINITIALISED;
  ret->_next = root;
  // TODO set base rtt to ensure that we send the first packet a few times before giving up
  ret->tx.base_rtt = ret->tx.rtt = 0xFFFFFFFF;
  ret->tx.last_activity = TIME_NEVER_HAS;
  ret->rx.last_activity = TIME_NEVER_HAS;
  ret->next_action = TIME_NEVER_WILL;
  ret->timeout = gettime_ms() + 10000;
  ret->previous_ack = 0x7FFF;
  if (root)
    root->_prev=ret;
  root = ret;
  return ret;
}
Ejemplo n.º 25
0
static void sendSTAT(const char *event, u32_t server_timestamp) {
	struct STAT_packet pkt;
	u32_t now = gettime_ms();
	u32_t ms_played;

	if (status.current_sample_rate && status.frames_played && status.frames_played > status.device_frames) {
		ms_played = (u32_t)(((u64_t)(status.frames_played - status.device_frames) * (u64_t)1000) / (u64_t)status.current_sample_rate);
		if (now > status.updated) ms_played += (now - status.updated);
	} else {
		ms_played = 0;
	}
	
	memset(&pkt, 0, sizeof(struct STAT_packet));
	memcpy(&pkt.opcode, "STAT", 4);
	pkt.length = htonl(sizeof(struct STAT_packet) - 8);
	memcpy(&pkt.event, event, 4);
	// num_crlf
	// mas_initialized; mas_mode;
	packN(&pkt.stream_buffer_fullness, status.stream_full);
	packN(&pkt.stream_buffer_size, status.stream_size);
	packN(&pkt.bytes_received_H, (u64_t)status.stream_bytes >> 32);
	packN(&pkt.bytes_received_L, (u64_t)status.stream_bytes & 0xffffffff);
	pkt.signal_strength = 0xffff;
	packN(&pkt.jiffies, now);
	packN(&pkt.output_buffer_size, status.output_size);
	packN(&pkt.output_buffer_fullness, status.output_full);
	packN(&pkt.elapsed_seconds, ms_played / 1000);
	// voltage;
	packN(&pkt.elapsed_milliseconds, ms_played);
	pkt.server_timestamp = server_timestamp; // keep this is server format - don't unpack/pack
	// error_code;

	LOG_INFO("STAT: %s", event);

	if (loglevel == lSDEBUG) {
		LOG_SDEBUG("received bytesL: %u streambuf: %u outputbuf: %u calc elapsed: %u real elapsed: %u (diff: %u) device: %u delay: %d",
				   (u32_t)status.stream_bytes, status.stream_full, status.output_full, ms_played, now - status.stream_start,
				   ms_played - now + status.stream_start, status.device_frames * 1000 / status.current_sample_rate, now - status.updated);
	}

	send_packet((u8_t *)&pkt, sizeof(pkt));
}
Ejemplo n.º 26
0
int restful_rhizome_newsince(httpd_request *r, const char *remainder)
{
  r->http.response.header.content_type = CONTENT_TYPE_JSON;
  if (!is_rhizome_http_enabled())
    return 403;
  uint64_t rowid;
  const char *end = NULL;
  if (!strn_to_list_token(remainder, &rowid, &end) || strcmp(end, "/bundlelist.json") != 0)
    return 404;
  if (r->http.verb != HTTP_VERB_GET)
    return 405;
  int ret = authorize(&r->http);
  if (ret)
    return ret;
  r->u.rhlist.phase = LIST_HEADER;
  r->u.rhlist.rowcount = 0;
  bzero(&r->u.rhlist.cursor, sizeof r->u.rhlist.cursor);
  r->u.rhlist.cursor.rowid_since = rowid;
  r->u.rhlist.end_time = gettime_ms() + config.rhizome.api.restful.newsince_timeout * 1000;
  http_request_response_generated(&r->http, 200, CONTENT_TYPE_JSON, restful_rhizome_bundlelist_json_content);
  return 1;
}
Ejemplo n.º 27
0
/* Collection of unicast echo responses to detect working links */
int
overlay_mdp_service_probe(overlay_mdp_frame *mdp)
{
  IN();
  if (mdp->out.src.port!=MDP_PORT_ECHO || mdp->out.payload_length != sizeof(struct probe_contents)){
    WARN("Probe packets should be returned from remote echo port");
    RETURN(-1);
  }
  
  struct subscriber *peer = find_subscriber(mdp->out.src.sid, SID_SIZE, 0);
  if (peer->reachable == REACHABLE_SELF)
    RETURN(0);
  
  struct probe_contents probe;
  bcopy(&mdp->out.payload, &probe, sizeof(struct probe_contents));
  if (probe.addr.sin_family!=AF_INET)
    RETURN(WHY("Unsupported address family"));
  
  struct overlay_interface *interface = &overlay_interfaces[probe.interface];
  // if a peer is already reachable, and this probe would change the interface, ignore it
  // TODO track unicast links better in route_link.c
  if (peer->reachable & REACHABLE_INDIRECT)
    RETURN(0);
  if (peer->reachable & REACHABLE_DIRECT && peer->interface && peer->interface != interface)
    RETURN(0);

  peer->last_probe_response = gettime_ms();
  peer->interface = &overlay_interfaces[probe.interface];
  peer->address.sin_family = AF_INET;
  peer->address.sin_addr = probe.addr.sin_addr;
  peer->address.sin_port = probe.addr.sin_port;
  int r=REACHABLE_UNICAST;
  // Don't turn assumed|broadcast into unicast|broadcast
  if (!(peer->reachable & REACHABLE_ASSUMED))
    r |= (peer->reachable & REACHABLE_DIRECT);
  set_reachable(peer, r);
  RETURN(0);
  OUT();
}
Ejemplo n.º 28
0
int overlay_send_stun_request(struct subscriber *server, struct subscriber *request){
  if ((!server) || (!request))
    return -1;
  if (!(subscriber_is_reachable(server)&REACHABLE))
    return -1;
  // don't bother with a stun request if the peer is already reachable directly
  // TODO link timeouts
  if (subscriber_is_reachable(request)&REACHABLE_DIRECT)
    return -1;
  
  time_ms_t now = gettime_ms();
  if (request->last_stun_request +1000 > now)
    return -1;
  
  request->last_stun_request=now;
  
  overlay_mdp_frame mdp;
  bzero(&mdp, sizeof(mdp));
  mdp.packetTypeAndFlags=MDP_TX;
  
  bcopy(my_subscriber->sid, mdp.out.src.sid, SID_SIZE);
  bcopy(server->sid, mdp.out.dst.sid, SID_SIZE);
  mdp.out.src.port=MDP_PORT_STUN;
  mdp.out.dst.port=MDP_PORT_STUNREQ;
  mdp.out.queue=OQ_MESH_MANAGEMENT;
  
  struct overlay_buffer *payload = ob_static(mdp.out.payload, sizeof(mdp.out.payload));
  overlay_address_append(NULL, payload, request);
  mdp.out.payload_length=ob_position(payload);
  if (config.debug.overlayrouting)
    DEBUGF("Sending STUN request to %s", alloca_tohex_sid(server->sid));
  overlay_mdp_dispatch(&mdp,0 /* system generated */,
		       NULL,0);
  ob_free(payload);
  return 0;
}
Ejemplo n.º 29
0
int main(int argc,char **argv)
{
  if ((argc<3|| argc>4)
      ||(argc==4&&strcasecmp(argv[3],"force"))) {
    fprintf(stderr,"usage: flash900 <firmware> <serial port> [force]\n");
    exit(-1);
  }

  int fd=open(argv[2],O_RDWR);
  if (fd==-1) {
    fprintf(stderr,"Could not open serial port '%s'\n",argv[2]);
    exit(-1);
  }
    if (set_nonblock(fd)) {
      fprintf(stderr,"Could not set serial port '%s' non-blocking\n",argv[2]);
      exit(-1);
    }
    
    int speeds[8]={230400,115200,57600,38400,19200,9600,2400,1200};
    int speed_count=8;

  printf("Trying to get command mode...\n");
  int i;
  for(i=0;i<speed_count;i++) {
    // set port speed and non-blocking, and disable CTSRTS 
    if (setup_serial_port(fd,speeds[i])) {
      fprintf(stderr,"Could not setup serial port '%s'\n",argv[2]);
      exit(-1);
    }

    int last_char = 0;
    
    // Make sure we have left command mode and bootloader mode
    // 0 = $30 = bootloader reboot command
    unsigned char cmd[260]; bzero(&cmd[0],260);
    
    printf("Checking if stuck in bootloader\n");
    // Make sure there is no command in progress with the boot loader
    write(fd,cmd,260);
    // Try to sync with bootloader if it is already running
    cmd[0]=GET_DEVICE;
    cmd[1]=EOC;
    write(fd,cmd,2);
    unsigned char bootloaderdetect[4]={0x43,0x91,0x12,0x10};
    int state=0;
    long long timeout=gettime_ms()+1250;
    while(gettime_ms()<timeout) {
      unsigned char buffer[2];
      int r=read(fd,buffer,1);
      if (r==1) {
	//	printf("  read %02X\n",buffer[0]);
	if (buffer[0]==bootloaderdetect[state]) state++; else state=0;
	if (state==4) {
	  printf("Looks like we are in the bootloader already\n");
	  break;
	}
      }
    }
    
    if (state==4)
      printf("Detected RFD900 is already in bootloader\n");
    else
      {
	printf("Trying to switch to AT command mode\n");
	write(fd,"\b\b\b\b\b\b\b\b\b\b\b\b\r",14);
	// give it time to process the above, so that the first character of ATO
	// doesn't get eaten.
	usleep(10000);        
	write(fd,"ATO\r",4);
	// sleep(2); // allow 2 sec to reboot if it was in bootloader mode already
	
	// now try to get to AT command mode
	sleep(1);
	write(fd,"+++",3);
	
	// now wait for upto 1.2 seconds for "OK" 
	timeout=gettime_ms()+1200;
	state=0;
	while(gettime_ms()<timeout) {
	  char buffer[1];
	  int r=read(fd,buffer,1);
	  if (r==1) {
	    //	    printf("  read %02X\n",buffer[0]);
	    if ((buffer[0]=='K') && (last_char == 'O')) state=2; else state=0;
	    last_char = buffer[0];
	    if (state==2) break;
	  } else usleep(10000);
	}
	if (state==2) {	 
	  // try AT&UPDATE or ATS1=115\rAT&W\rATZ if the modem isn't already on 115200bps
	  printf("Switching to boot loader...\n");
	  char *cmd="AT&UPDATE\r\n";

	  if (speeds[i]==115200) {
	    write(fd,cmd,strlen(cmd));
	  } else {
	    char *cmd="ATS1=115\r\n";
	    write(fd,cmd,strlen(cmd));
	    sleep(1);
	    cmd="AT&W\r\n";
	    write(fd,cmd,strlen(cmd));
	    sleep(1);
	    cmd="ATZ\r\n";	  
	    write(fd,cmd,strlen(cmd));
	    sleep(1);

	    // Go back to looking for modem at 115200
	    printf("Changing modem from %d to 115200bps\n",
		   speeds[i]);
	    i=-1; continue;
	  }
	  
	  // then switch to 115200 regardless of the speed we were at,
	  // since the bootloader always talks 115200
	  setup_serial_port(fd,115200);
      
	  // give time to switch to boot loader
	  // and consume any characters that arrive in the meantime
	  timeout=gettime_ms()+1500;
	  while(gettime_ms()<timeout) {
	    unsigned char buffer[2];
	    int r=read(fd,(char *)buffer,1);
	    // fprintf(stderr,"Read %02X from bootloader.\n",buffer[0]);
	    if (r!=1) usleep(100000); else {
	      // printf("  read %02X\n",buffer[0]);
	    }
	  }
      
	  state=4;
	}
      }
    if (state==4) {
      // got command mode (probably)
      printf("Got OK at %d\n",speeds[i]);
      
      // ask for board ID
      unsigned char cmd[1024];
      cmd[0]=GET_DEVICE;
      cmd[1]=EOC;
      write(fd,cmd,2);

      int id = next_char(fd);
      int freq = next_char(fd);
      expect_insync(fd);
      expect_ok(fd);
     
      char filename[1024];
      snprintf(filename,1024,"%s-%02X-%02X.ihx",argv[1],id,freq);

      printf("Board id = $%02x, freq = $%02x : Will load firmware from '%s'\n",
	     id,freq,filename);
      
      ihex_recordset_t *ihex=ihex_rs_from_file(filename);
      if (!ihex) {
	fprintf(stderr,"Could not read intelhex from file '%s'\n",filename);

	// Reboot radio
	write(fd,"0",1);
	
	exit(-2);
      }
      printf("Read %d IHEX records from firmware file\n",ihex->ihrs_count);
      
      // Sort IHEX records into ascending address order so that when we flash 
      // them we don't mess things up by writing the flash data in the wrong order 
      qsort(ihex->ihrs_records,ihex->ihrs_count,sizeof(ihex_record_t),
	    compare_ihex_record);
      
      int i;
      if (0)
	for(i=0;i<ihex->ihrs_count;i++)
	  printf("$%04x - $%04x\n",
		 ihex->ihrs_records[i].ihr_address,
		 ihex->ihrs_records[i].ihr_address+
		 ihex->ihrs_records[i].ihr_length-1);
      
      
      // Reset parameters
      cmd[0]=PARAM_ERASE;
      cmd[1]=EOC;
      write(fd,cmd,2);
      expect_insync(fd);
      expect_ok(fd);

      printf("Erased parameters.\n");

      // Program all parts of the firmware and verify that that got written
      printf("Checking if the radio already has this version of firmware...\n");
      int fail=0;
      if (argc==3) {
	// read flash and compare with ihex records
	unsigned char buffer[65536];
	printf("Bulk reading from flash...\n");
	read_64kb_flash(fd,buffer);
	printf("Read all 64KB flash. Now verifying...\n");
	
	int i;
	for(i=0;i<ihex->ihrs_count;i++)
	  if (ihex->ihrs_records[i].ihr_type==0x00)
	    {
	      if (fail) break;
	      
	      if (memcmp(&buffer[ihex->ihrs_records[i].ihr_address],
			 ihex->ihrs_records[i].ihr_data,
			 ihex->ihrs_records[i].ihr_length))
		fail=1;
	    }
	
      }
      if ((argc==4)||fail)
	{
	  printf("\nFirmware differs: erasing and flashing...\n");

	  // Erase ROM
	  printf("Erasing flash.\n");
	  cmd[0]=CHIP_ERASE;
	  cmd[1]=EOC;
	  write(fd,cmd,2);
	  expect_insync(fd);
	  expect_ok(fd);

	  // Write ROM
	  printf("Flash erased, now writing new firmware.\n");
	  write_or_verify_flash(fd,ihex,1);
	}

      // Reboot radio
      write(fd,"0",1);

      break;
    } else {
      printf("Modem doesn't seem to be at %dbps\n",speeds[i]);
    }
    
  }

  return 0;
}
Ejemplo n.º 30
0
int overlay_send_probe(struct subscriber *peer, struct sockaddr_in addr, overlay_interface *interface, int queue){
  if (interface==NULL)
    interface = overlay_interface_find(addr.sin_addr, 1);
  
  if (!interface)
    return WHY("I don't know which interface to use");
  
  if (interface->state!=INTERFACE_STATE_UP)
    return WHY("I can't send a probe if the interface is down.");
  
  // don't send a unicast probe unless its on the same interface that is already known to be reachable
  if (peer && peer->reachable & REACHABLE_INDIRECT)
    return -1;
  if (peer && (peer->reachable & REACHABLE_DIRECT) && peer->interface && peer->interface != interface)
    return -1;

    if (addr.sin_addr.s_addr==0) {
      if (config.debug.overlayinterfaces) 
	DEBUG("I can't send a probe to address 0.0.0.0");
      return -1;
    }
    if (addr.sin_port==0) {
      if (config.debug.overlayinterfaces) 
	DEBUG("I can't send a probe to port 0");
      return -1;
    }
  
  // never send unicast probes over a stream interface
  if (interface->socket_type==SOCK_STREAM)
    return 0;
  
  time_ms_t now = gettime_ms();
  
  if (peer && peer->last_probe+1000>now)
    return -1;
  
  struct overlay_frame *frame=malloc(sizeof(struct overlay_frame));
  bzero(frame,sizeof(struct overlay_frame));
  frame->type=OF_TYPE_DATA;
  frame->source = my_subscriber;
  frame->next_hop = frame->destination = peer;
  frame->ttl=1;
  frame->queue=queue;
  frame->destination_resolved=1;
  frame->recvaddr=addr;
  frame->unicast=1;
  frame->interface=interface;
  frame->payload = ob_new();
  frame->source_full = 1;
  // TODO call mdp payload encryption / signing without calling overlay_mdp_dispatch...
  
  if (peer)
    peer->last_probe=gettime_ms();
  
  if (overlay_mdp_encode_ports(frame->payload, MDP_PORT_ECHO, MDP_PORT_PROBE)){
    op_free(frame);
    return -1;
  }
  // not worried about byte order here as we are the only node that should be parsing the contents.
  unsigned char *dst=ob_append_space(frame->payload, sizeof(struct probe_contents));
  if (!dst){
    op_free(frame);
    return -1;
  }
  struct probe_contents probe;
  probe.addr=addr;
  // get interface number
  probe.interface = interface - overlay_interfaces;
  bcopy(&probe, dst, sizeof(struct probe_contents));
  if (overlay_payload_enqueue(frame)){
    op_free(frame);
    return -1;
  }
  if (config.debug.overlayrouting)
    DEBUGF("Queued probe packet on interface %s to %s:%d for %s", 
	 interface->name, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), peer?alloca_tohex_sid(peer->sid):"ANY");
  return 0;
}