Example #1
0
/**
 * Send an ICMP destination/protocol unreachable back to 'ip->source'.
 * Limit the rate of these to 20 per second. Ref. RFC-1812.
 */
int icmp_send_unreach (const in_Header *ip, int code)
{
  static DWORD next_time = 0UL;
  struct _pkt    *pkt;
  union ICMP_PKT *unr;
  unsigned        len;

  if (!icmp_check(ip,ICMP_UNREACH))
     return (0);

  if (next_time && !chk_timeout(next_time))
     return (0);

  next_time = set_timeout (50);

  pkt = (struct _pkt*) _eth_formatpacket (MAC_SRC(ip), IP4_TYPE);
  unr = &pkt->icmp;
  len = intel16 (ip->length) - in_GetHdrLen (ip);
  len = min (len, sizeof(*ip)+sizeof(unr->unused.spares));

  icmp_print (1, _LANG(icmp_unreach_str[code]), ip->destination);
  memcpy (&unr->unused.ip, ip, len);
  unr->unused.type = ICMP_UNREACH;
  unr->unused.code = (BYTE) code;

  return icmp_send (pkt, ip->destination, ip->source, sizeof(unr->unused));
}
Example #2
0
static BOOL modem_command (const char *cmd, const char *resp, int timeout)
{
  DWORD timer;
  int   len = cmd ? strlen (cmd) : strlen (resp);

  if (cmd)
     rc = pkt_send (cmd, len);  /**<\todo Bypass PKTDRVR ? */

  if (rc < len || !_eth_is_init)
     return (FALSE);

  timer = set_timeout (1000 * timeout);

  while (!chk_timeout(timer))
  {
    char *pkt = (char*) _eth_arrived (NULL NULL);

    if (!pkt)
       continue;

    outsn (pkt, len);                             /* print the modem echo */
    _eth_free (pkt, type);
    return (strncmp(pkt,resp,strlen(resp)) == 0); /* got modem response */
  }
  return (FALSE);
}
Example #3
0
/*
 * _dorarp - Checks global variable _rarptimeout
 *           returns 1 on success and sets ip address
 */
int _dorarp (void)
{
  DWORD rarptimeout    = set_timeout (1000 * _rarptimeout);
  WORD  magictimeout   = Random (7000, 14000);

  outs (_LANG("Configuring through RARP..."));

  while (1)
  {
    DWORD sendtimeout;

    if (!_rarp_request())
       break;

    sendtimeout   = set_timeout (magictimeout);
    magictimeout += Random (1000, 7000);

    while (!chk_timeout(sendtimeout))
    {
      const struct rarp_Header *rarp;
      WORD  eth_type;
      BOOL  bcast;

      if (chk_timeout(rarptimeout))
         return (0);

      WATT_YIELD();

      rarp = (rarp_Header*) _eth_arrived (&eth_type, &bcast);
      if (!rarp)
         continue;

      DEBUG_RX (NULL, rarp);

      if (eth_type == RARP_TYPE && !bcast &&
          rarp->opcode == RARP_REPLY && rarp->protType == IP4_TYPE &&
          !memcmp(rarp->dstEthAddr,_eth_addr,sizeof(mac_address)))
      {
        my_ip_addr = intel (rarp->dstIPAddr);
        _eth_free (rarp);
        return (1);
      }
      _eth_free (rarp);
    }
  }
  return (0);
}
Example #4
0
static int tcp_conn (_tcp_Socket *sock, ERROR_TYPE *error, DWORD timeout)
{
  DWORD timer  = set_timeout (timeout);
  int   status = _ip_delay0 ((sock_type*)sock, (int)timeout, NULL, NULL);

  if (status == -1)
  {
    *error = chk_timeout(timer) ? ETIMEDOUT : ECONNREFUSED;
    return (0);
  }
  *error = 0;
  return (1);
}
Example #5
0
/*
 * Handle non-blocking SOCK_STREAM connection.
 * Only called on 2nd (3rd etc) time a non-blocking
 * connect() is called.
 */
static int nblk_connect (Socket *socket)
{
  if (socket->so_state & SS_ISCONNECTED)
  {
    SOCK_DEBUGF ((", connected!"));
    socket->so_error = 0;
    return (0);
  }

  /* Don't let tcp_Retransmitter() timeout this socket
   * (unless there is a ARP timeout etc.)
   */
  socket->tcp_sock->timeout = 0;

  if ((socket->so_state & (SS_ISDISCONNECTING | SS_CONN_REFUSED)) ||
      (socket->tcp_sock->state >= tcp_StateCLOSED))
  {
    if (socket->so_error != 0 && socket->so_error != EALREADY)
    {
      SOCK_DEBUGF ((", %s", short_strerror(socket->so_error)));
      SOCK_ERRNO (socket->so_error);
    }
    else if (chk_timeout(socket->nb_timer))
    {
      socket->so_state &= ~SS_ISCONNECTING;
      SOCK_DEBUGF ((", ETIMEDOUT (%s)", socket->tcp_sock->err_msg));
      socket->so_error = ETIMEDOUT;
      SOCK_ERRNO (ETIMEDOUT);
    }
    else
    {
      SOCK_DEBUGF ((", ECONNREFUSED"));
      socket->so_error = ECONNREFUSED;
      SOCK_ERRNO (ECONNREFUSED);       /* could also be ECONNRESET */
    }
    return (-1);
  }

  if (socket->so_state & SS_ISCONNECTING)
  {
    SOCK_DEBUGF ((", EALREADY"));
    socket->so_error = EALREADY;       /* should be redundant */
    SOCK_ERRNO (EALREADY);
    return (-1);
  }

  SOCK_FATAL (("%s (%d) Fatal: Unhandled non-block event\n",
              __FILE__, __LINE__));
  return (-1);
}
Example #6
0
/*
 * resolve()
 * 	convert domain name -> address resolution.
 * 	returns 0 if name is unresolvable right now
 */
longword resolve_fn( char *name, sockfunct_t fn )	// S. Lawson
{
    longword ipaddr;
    // S. Lawson
#define DNSCACHESIZE 4			// cache up to 4 names
#define DNSCACHELENGTH 32		//   up to 32 characters
#define DNSCACHETIMEOUT 120             //     for up to 2 minutes
    static char DNScacheName[DNSCACHESIZE][DNSCACHELENGTH];
    static longword DNScacheIP[DNSCACHESIZE];
    static longword DNScacheTimeout[DNSCACHESIZE]={0,0,0,0};
    static char DNScacheNext=0;
    int DNScacheScan;

    if( !name ) return 0L;

    rip( name );			// S. Lawson - trim for cache scan
    if ( isaddr( name ))
	 return( aton( name ));

    // S. Lawson
    for (DNScacheScan=0 ; DNScacheScan<DNSCACHESIZE ; DNScacheScan++) {
       if (DNScacheTimeout[DNScacheScan]==0L) continue;
       if (chk_timeout(DNScacheTimeout[DNScacheScan])) {
	  DNScacheTimeout[DNScacheScan]=0L;
	  continue;
       }
       if(!strcmpi(DNScacheName[DNScacheScan],name))
	  return DNScacheIP[DNScacheScan];
    }

#ifdef NOTUSED	// S. Lawson
    if( do_ns_lookup(name, DTYPEA, typea_unpacker, &ipaddr) )
       return (intel(ipaddr));
    else return (0L);
#else	// S. Lawson
    if( do_ns_lookup(name, DTYPEA, typea_unpacker, &ipaddr, fn) ) {
       strncpy(DNScacheName[DNScacheNext], name, DNSCACHELENGTH);
       DNScacheName[DNScacheNext][DNSCACHELENGTH-1]='\0';
       DNScacheIP[DNScacheNext]=intel(ipaddr);
       DNScacheTimeout[DNScacheNext]=set_timeout(DNSCACHETIMEOUT);
       if (++DNScacheNext>=DNSCACHESIZE) DNScacheNext=0;
       return (intel(ipaddr));
    }
    return (0L);
#endif	// S. Lawson
}
Example #7
0
static int reverse_lookup (question_t *q, char *name, DWORD nameserver)
{
  int        i, ret;
  int        ready = 0;
  udp_Socket dom_sock;

  if (!nameserver ||         /* no nameserver, give up */
      dns_timeout == 0)
     return (0);

  udp_open (&dom_sock, 997, nameserver, 53, NULL);

  for (i = 2; i < 17 && !_resolve_exit; i *= 2)
  {
    sock_write ((sock_type*)&dom_sock, (BYTE*)q, sizeof(*q));
    ip_timer_init (&dom_sock, i);
    do
    {
      kbhit();
      tcp_tick ((sock_type*)&dom_sock);

      if (watcbroke || (_resolve_hook && (*_resolve_hook)() == 0))
      {
        _resolve_exit = 1;
        break;
      }
      if (ip_timer_expired(&dom_sock) || chk_timeout(resolve_timeout))
         break;

      if (sock_dataready((sock_type*)&dom_sock))
         ready = 1;
    }
    while (!ready);
  }
  if (ready)
       ret = getresult (&dom_sock, name);
  else ret = 0;

  sock_close ((sock_type*)&dom_sock);
  return (ret);
}
Example #8
0
/*
 * This functiom is called once each second.
 */
static void check_dead_gw (void)
{
  char   buf[20];
  static int i = 0;

  if (i >= gate_top)
      i = 0;

  for ( ; i < gate_top; i++)
  {
    struct gate_entry *gw = &gate_list [i];
    eth_address        eth;

    if (!is_on_LAN(gw->gate_ip))
       continue;

    if (!LAN_lookup(gw->gate_ip,&eth))
       continue;

    if (gw->chk_timer == 0UL || !chk_timeout(gw->chk_timer))
    {
      gw->chk_timer = set_timeout (DEAD_GW_TIMEOUT);
      continue;
    }

    if (gw->echo_pending &&
        _chk_ping(gw->gate_ip,NULL) == (DWORD)-1)
    {
      gw->is_dead      = TRUE;
      gw->echo_pending = FALSE;
      TCP_CONSOLE_MSG (1, ("Dead default GW %s (%d) detected\n",
                       _inet_ntoa(NULL,gw->gate_ip), i));
    }

    if (ping_gateway (gw->gate_ip, eth))
       gw->echo_pending = TRUE;

    gw->chk_timer = set_timeout (DEAD_GW_TIMEOUT);
    return;  /* only one ping per interval */
  }
}
Example #9
0
/**
 * Loop waiting for timeout or a PAD response.
 * Blocks until some got_X flags in by pppoe_handler().
 */
static BOOL pppoe_wait (int wait_code)
{
  DWORD timer = set_timeout (1000 * cfg.timeout);

  while (1)
  {
    tcp_tick (NULL);

    if ((wait_code == PPPOE_CODE_PADO && got_PADO) ||
        (wait_code == PPPOE_CODE_PADS && got_PADS))
    {
#if defined(USE_DEBUG)
      if (cfg.trace)
         (*_printf) ("PPPoE: got %s\n", pppoe_get_code(wait_code));
#endif
      return (TRUE);
    }
    if (chk_timeout(timer))
       break;
  }
  return (FALSE);
}
Example #10
0
/*  Sdomain
*   DOMAIN based name lookup
*   query a domain name server to get resource record data
*	Returns the data on a machine from a particular RR type.
*   Events generated will have this number tagged with them.
*   Returns various negative numbers on error conditions.
*
*   if adddom is nonzero, add default domain
*
*   Returns true if we got data, false otherwise.
*/
static int Sdomain( char *mname, byte dtype, unpacker_funct unpacker,
	    void *data, int adddom, longword nameserver, byte *timedout,
	    sockfunct_t fn ) 		// S. Lawson
/* int *timedout; set to 1 on timeout */
{
    char namebuff[512];
/*    int domainsremaining; */
    int /*status,*/ i;
    int result;
    int fnbroke;		// S. Lawson

    result = 0;
    fnbroke = 0;		// S. Lawson
    *timedout = 1;

    if (!nameserver) {	/* no nameserver, give up now */
	outs("No nameserver defined!\n\r");
	return(0);
    }

    while (*mname && *mname < 33) mname ++;   /* kill leading spaces */

    if (!(*mname))
	return(0);

    qinit();				/* initialize some flag fields */

    strcpy( namebuff, mname );

    if ( adddom ) {
	if(namebuff[strlen(namebuff)-1] != '.') {       /* if no trailing dot */
	    if(loc_domain) {             /* there is a search list */
//		domainsremaining = countpaths( loc_domain );    // why this here? -md

		strcat(namebuff,".");
		strcat(namebuff,getpath(loc_domain,1));
	    }
	} else
	    namebuff[ strlen(namebuff)-1] = 0;	/* kill trailing dot */
    }
    /*
     * This is not terribly good, but it attempts to use a binary
     * exponentially increasing delays.
     */

     for ( i = 2; i < 17; i *= 2) {
	sendom(namebuff,nameserver, 0xf001, dtype);	/* try UDP */

	ip_timer_init( dom_sock, i );
	do {
	    kbhit();
	    tcp_tick( dom_sock );
	    if (ip_timer_expired( dom_sock )) break;
	    if ( watcbroke ) {
		break;
	    }
	    if (chk_timeout( timeoutwhen ))
		break;

	    // S. Lawson - call the idle/break function
	    if (fn && fn(NULL)!=0) {
	       result=fnbroke=-1;
	       *timedout=1;
	       break;
	    }

	    if ( sock_dataready( dom_sock )) *timedout = 0;
	} while ( *timedout );

	if ( !*timedout ) break;	/* got an answer */
    }

    if ( !*timedout && !fnbroke)	// S. Lawson
	result = udpdom(dtype, unpacker, data);	/* process the received data */

    sock_close( dom_sock );
    return( result );
}
Example #11
0
/*
 * Handle SOCK_STREAM blocking connection. Or non-blocking connect
 * the first time connect() is called.
 */
static int tcp_connect (Socket *socket)
{
  DWORD timeout;
  int   status;

#if defined(USE_IPV6)
  if (socket->so_family == AF_INET6)
  {
    const struct sockaddr_in6 *la = (const struct sockaddr_in6*) socket->local_addr;
    const struct sockaddr_in6 *ra = (const struct sockaddr_in6*) socket->remote_addr;

    if (!_TCP6_open (socket, &ra->sin6_addr, la->sin6_port, ra->sin6_port))
    {
      /* errno already set in _TCP6_open() */
      SOCK_DEBUGF ((", %s", socket->tcp_sock->err_msg));
      return (-1);
    }
  }
  else
#endif
  if (!_TCP_open (socket,
                  socket->remote_addr->sin_addr,
                  socket->local_addr->sin_port,
                  socket->remote_addr->sin_port))
  {
    /* errno already set in tcp_open() */
    SOCK_DEBUGF ((", %s", socket->tcp_sock->err_msg));
    return (-1);
  }

  /* Don't let tcp_Retransmitter() kill this socket
   * before our `socket->timeout' expires
   */
  socket->tcp_sock->locflags |= LF_RCVTIMEO;

  /* We're here only when connect() is called the 1st time
   * (blocking or non-blocking socket).
   */
  socket->so_state |= SS_ISCONNECTING;
  timeout = set_timeout (1000 * socket->timeout);

  if (socket->so_state & SS_NBIO)
  {
    /* if user calls getsockopt(SO_ERROR) before calling connect() again
     */
    socket->so_error = EALREADY;
    socket->nb_timer = timeout;
    SOCK_DEBUGF ((", EINPROGRESS"));
    SOCK_ERRNO (EINPROGRESS);
    return (-1);
  }

  /* Handle blocking stream socket connect.
   * Maybe we should use select_s() instead ?
   * Maybe set LF_NOCLOSE for all BSD sockets?
   */
  status = _ip_delay0 ((sock_type*)socket->tcp_sock,
                       socket->timeout, (UserHandler)chk_signals,
                       NULL);

  if (socket->so_error == EHOSTUNREACH)
  {
    SOCK_DEBUGF ((", %s", socket->tcp_sock->err_msg ?
                  socket->tcp_sock->err_msg : "no route"));
    SOCK_ERRNO (EHOSTUNREACH);
    return (-1);
  }

  /* We got an ICMP_UNREACH from someone
   */
  if (socket->so_state & SS_CONN_REFUSED)
  {
    socket->so_state &= ~SS_ISCONNECTING;
    SOCK_DEBUGF ((", ECONNREFUSED"));
    SOCK_ERRNO (ECONNREFUSED);
    return (-1);
  }

  if (status < 0 && chk_timeout(timeout))
  {
    socket->so_state &= ~SS_ISCONNECTING;
    SOCK_DEBUGF ((", ETIMEDOUT"));
    SOCK_ERRNO (ETIMEDOUT);
    return (-1);
  }

  if (status < 0)
  {
    socket->so_state &= ~SS_ISCONNECTING;
    SOCK_DEBUGF ((", ECONNRESET"));
    SOCK_ERRNO (ECONNRESET);
    return (-1);
  }

  socket->so_state &= ~(SS_UNCONNECTED | SS_ISCONNECTING);
  socket->so_state |=  SS_ISCONNECTED;
  return (0);
}
Example #12
0
/*
 * ___trace2com() - Strings passed here are dumped to the set-up serial
 * "com" port. If the string is < 16 chars long, it will fit into the
 * 16550 UARTs FIFO and will not cause any significant delay.
 * No interrupts are used, so this will not interfere with anything
 * else that might be happening.
 */
int MS_CDECL __trace2com (const char *fmt, ...)
{
  int     fifoLeft = 0; /* Assume TX FIFO is full on first round -> force check */
  char    buf [256];
  int     len, i;
  va_list args;

  if (trace2com_base <= 0)   /* Not yet initialized */
     return (0);

  va_start (args, fmt);

#if defined(VSNPRINTF)
  len = VSNPRINTF (buf, sizeof(buf)-1, fmt, args);
  if (len < 0 || len >= SIZEOF(buf)-1)
  {
    outsnl (_LANG("ERROR: __trace2com() overrun"));
    len = sizeof(buf)-1;
    buf [len] = '\0';
  }
#else
  len = vsprintf (buf, fmt, args);
  if (len > SIZEOF(buf))  /* harm already done, but better than no test */
  {
    outsnl (_LANG("ERROR: __trace2com() overrun"));
    return (0);
  }
#endif

  for (i = 0; i < len; i++)
  {
    DWORD to = set_timeout (400000/trace2com_speed); /* 10ms at 38kB/s */

    if (--fifoLeft < 0) /* Is the TX FIFO full? */
    {
      /* Wait until THRE or TX FIFO empty
       */
      while (!(_inportb (trace2com_base+LSR_REG) & LSR_THRE))
      {
        if (chk_timeout(to))
           return (i);
      }
      fifoLeft = trace2com_fifoSize_1; /* Now we can fill it up again */
    }
    _outportb (trace2com_base+TXRX_REG, buf[i]);
  }

  if (--fifoLeft < 0)
  {
    DWORD to = set_timeout (400000/trace2com_speed);

    /* Wait until THRE or TX FIFO empty
     */
    while (!(_inportb (trace2com_base+LSR_REG) & LSR_THRE))
    {
      if (chk_timeout(to))
         return (len);
    }
  }
  _outportb (trace2com_base+TXRX_REG, '\r');
  _outportb (trace2com_base+TXRX_REG, '\n');
  return (len+2);
}
Example #13
0
int accept (int s, struct sockaddr *addr, int *addrlen)
{
  Socket  *clone, *socket;
  volatile DWORD   timeout;
  volatile int     newsock = -1;
  volatile int     que_idx;
  volatile int     maxconn;

  socket = _socklist_find (s);

  SOCK_PROLOGUE (socket, "\naccept:%d", s);

  if (!socket->local_addr)
  {
    SOCK_DEBUGF ((socket, ", not bound"));
    SOCK_ERR (ENOTCONN);
    return (-1);
  }

  if (socket->so_type != SOCK_STREAM)
  {
    SOCK_DEBUGF ((socket, ", EOPNOTSUPP"));
    SOCK_ERR (EOPNOTSUPP);
    return (-1);
  }

  if (!(socket->so_options & SO_ACCEPTCONN)) /* listen() not called */
  {
    SOCK_DEBUGF ((socket, ", not SO_ACCEPTCONN"));
    SOCK_ERR (EINVAL);
    return (-1);
  }

  if (!(socket->so_state & (SS_ISLISTENING | SS_ISCONNECTING)))
  {
    SOCK_DEBUGF ((socket, ", not listening"));
    SOCK_ERR (ENOTCONN);
    return (-1);
  }

  if (addr && addrlen)
  {
    if (*addrlen < sizeof(*addr))
    {
      SOCK_DEBUGF ((socket, ", EFAULT"));
      SOCK_ERR (EFAULT);
      return (-1);
    }
    VERIFY_RW (addr, *addrlen);
  }

  /* Get max possible TCBs on listen-queue.
   * Some (or all) may be NULL until a SYN comes in.
   */
  maxconn = socket->backlog;
  if (maxconn < 1 || maxconn > SOMAXCONN)
  {
    SOCK_FATAL (("%s(%d): Illegal socket backlog %d",
                __FILE__, __LINE__, maxconn));
    SOCK_ERR (EINVAL);
    return (-1);
  }

  if (socket->timeout)
       timeout = set_timeout (1000 * socket->timeout);
  else timeout = 0UL;


  if (_sock_sig_setup() < 0)
  {
    SOCK_ERR (EINTR);
    goto accept_fail;
  }

  /* Loop over all queue-slots and accept first connected TCB
   */
  for (que_idx = 0; ; que_idx = (++que_idx % maxconn))
  {
    tcp_Socket *sk = socket->listen_queue [que_idx];

    tcp_tick (NULL);

    SOCK_YIELD();

    /* No SYNs received yet. This shouldn't happen if we called 'accept()'
     * after 'select_s()' said that socket was readable. (At least one
     * connection on the listen-queue).
     */
    if (sk)
    {
      /* This could happen if 'accept()' was called too long after connection
       * was established and then closed by peer. This could also happen if
       * someone did a portscan on us. I.e. he sent 'SYN', we replied with
       * 'SYN+ACK' and he never sent an 'ACK'. Thus we timeout in
       * 'tcp_Retransmitter()' and abort the TCB.
       *
       * Queue slot is in any case ready for another 'SYN' to come and be
       * handled by '_sock_append()'.
       */
      if (sk->state >= tcp_StateLASTACK && sk->ip_type == 0)
      {
        SOCK_DEBUGF ((socket, ", aborted TCB (idx %d)", que_idx));
        listen_free (socket, que_idx);
        continue;
      }

      /* !!to-do: Should maybe loop over all maxconn TCBs and accept the
       *          one with oldest 'syn_timestamp'.
       */
      if (tcp_established(sk))
      {
        SOCK_DEBUGF ((socket, ", connected! (idx %d)", que_idx));
        break;
      }
    }

    /* We've polled all listen-queue slots and none are connected.
     * Return fail if socket is non-blocking.
     */
    if (que_idx == maxconn-1 && (socket->so_state & SS_NBIO))
    {
      SOCK_DEBUGF ((socket, ", would block"));
      SOCK_ERR (EWOULDBLOCK);
      goto accept_fail;
    }

    if (chk_timeout(timeout))
    {
      SOCK_DEBUGF ((socket, ", ETIMEDOUT"));
      SOCK_ERR (ETIMEDOUT);
      goto accept_fail;
    }
  }

  /* We're here only when above 'tcp_established()' succeeded.
   * Now duplicate 'socket' into a new listening socket 'clone'
   * with handle 'newsock'.
   */
  _sock_enter_scope();
  newsock = dup_bind (socket, &clone, que_idx);
  if (newsock < 0)
     goto accept_fail;

  if (alloc_addr(socket, clone) < 0)
  {
    SOCK_DEL_FD (newsock);
    goto accept_fail;
  }

  /* Clone is connected, but *not* listening/accepting.
   * Note: other 'so_state' bits from parent is unchanged.
   *       e.g. clone may be non-blocking.
   */
  clone->so_state   |=  SS_ISCONNECTED;
  clone->so_state   &= ~(SS_ISLISTENING | SS_ISCONNECTING);
  clone->so_options &= ~SO_ACCEPTCONN;

  /* Prevent a PUSH on first segment sent.
   */
  sock_noflush ((sock_type*)clone->tcp_sock);

  SOCK_DEBUGF ((clone, "\nremote %s (%d)",
                inet_ntoa (clone->remote_addr->sin_addr),
                ntohs (clone->remote_addr->sin_port)));

  if (addr && addrlen)
  {
    struct sockaddr_in *sa = (struct sockaddr_in*)addr;

    sa->sin_family = AF_INET;
    sa->sin_port   = clone->remote_addr->sin_port;
    sa->sin_addr   = clone->remote_addr->sin_addr;
    memset (sa->sin_zero, 0, sizeof(sa->sin_zero));
    *addrlen = sizeof(*sa);
  }

  _sock_leave_scope();
  _sock_sig_restore();
  return (newsock);

accept_fail:
  _sock_leave_scope();
  _sock_sig_restore();
  return (-1);
}
Example #14
0
File: ping.c Project: suborb/zsock
void Ping()
{
    char	buffer[80];
    char	buffer2[20];
    u16_t	i;
    u16_t	sequence;
    u32_t	ident;
    u32_t	timeout;
    ipaddr_t  addr;
    
    printf("Enter hostname/IP to ping\n");

    fgets_cons(buffer,79);
    if ( (addr=resolve_i(buffer) ) == 0L ) {
	printf("\nUnknown host\n");
	return;
    }

    

    memset(pingstat,0,sizeof(pingstat));
    
    ident = sequence = 0;
    received = pingav = pingmin = pingmax = 0;
    
    if ( icmp_register(ping_handler) == NULL ) {
	printf("\nCan't register handler..\n");
	return;
    }
    
    printf("\nPING %s (%s): 56 data bytes\n",buffer,inet_ntoa_i(addr,buffer2));


    timeout = set_timeout(50);
    for (;;) {
	if (  chk_timeout(timeout) ) {
	    timeout = set_timeout(100);
	    if ( ping_send(addr,&ident) ) 
		ident++;
	    else
		break;
	} 
#ifdef __Z88__
	if (getk() == 27 ) break;
#else
	if ( ident == 4 )
	    break;
#endif
	BUSYINT();
   }


    icmp_deregister();
    /* Just to test the resolver.... */
    if (reverse_addr_lookup_i(addr,buffer) == 0 )
	inet_ntoa_i(addr,buffer);
    printf("\n--- %s ping statistics ---\n",buffer);
    printf("%lu packets transmitted, %d packets received, %d%% packet loss\n",ident,received, 100-((received*100)/ident)  );
    printf("round-trip time min/avg/max= %d/%d/%d ms\n",pingmin,(pingav*10)/received,pingmax);
    return;
}
Example #15
0
debug
void main()
{
   longword host, timer, new_rcvd;
   longword tot_timeout, itts, send_timeout;
   word i;
   word sequence_mode, is_new_line;
   word debug_on;
   static unsigned char tempbuffer[255];

   sent=received=tot_delays=last_rcvd=0L;
   tot_timeout=itts=send_timeout=0L;
   sequence_mode=debug_on=0;
   is_new_line=1;

	// Start network and wait for interface to come up (or error exit).
	sock_init_or_exit(1);

   name=PINGWHO;
   itts=10;

   if (!(host = resolve( name ))) {
      printf("Unable to resolve '%s'\n", name );
      exit( 3 );
   }
   if ( isaddr( name ))
      printf("Pinging [%s]",inet_ntoa(tempbuffer, host));
   else
      printf("Pinging '%s' [%s]",name, inet_ntoa(tempbuffer, host));

   if (itts) printf(" %u times", itts);
   else
      itts = sequence_mode ? 0xffffffffL : 1;

   if (sequence_mode) printf(" once per_second");
   printf("\n");


   if (!_arp_resolve( host, (eth_address *)tempbuffer, 0 )) {  /* resolve it before timer starts */
   	printf("Could not resolve hardware address\n");
   	exit(2);
   }
   tot_timeout = _SET_TIMEOUT((itts + 2)*1000L);
   if ( debug_on ) printf("ETH -> %02x:%02x:%02x:%02x:%02x:%02x\n",
      (int)tempbuffer[0],(int)tempbuffer[1],(int)tempbuffer[2],(int)tempbuffer[3],
      (int)tempbuffer[4],(int)tempbuffer[5]);

	send_timeout = _SET_TIMEOUT(0);
   do {
      /* once per second - do all this */
      if ( chk_timeout( send_timeout )) {
         send_timeout = _SET_TIMEOUT(1000L);
         if (chk_timeout( tot_timeout )) {
            stats();
            break;
         }
         if ( sent < itts ) {
            sent++;
            if (_ping( host , sent ))
               stats();
            if (!is_new_line) printf("\n");
            printf("sent PING # %lu ", sent );
            is_new_line = 0;
         }
      }

      if ( kbhit() ) {
         getchar();    /* trash the character */
         stats();
      }

      tcp_tick(NULL);
      if ((timer = _chk_ping( host , &new_rcvd)) != 0xffffffffL) {
         tot_delays += timer;
         ++received;
         if ( new_rcvd != last_rcvd + 1 ) {
            if (!is_new_line) printf("\n");
            printf("PING receipt received out of order!\n");
            is_new_line = 1;
         }
         last_rcvd = new_rcvd;
         if (!is_new_line) printf(", ");
         printf("PING receipt # %lu : response time %lu ms\n", received, timer);
         is_new_line = 1;
         if ( received == itts )
            stats();
      }
   } while (1);
}
Example #16
0
debug
void main()
{
   longword host, timer, new_rcvd;
   longword tot_timeout, itts, send_timeout;
   word i;
   word sequence_mode, is_new_line;
   word debug_on;
   static unsigned char tempbuffer[255];
   word arping;
   auto char ip[16], netmask[16];
   auto int status;

   sent=received=tot_delays=last_rcvd=0L;
   tot_timeout=itts=send_timeout=0L;
   debug_on=0;
   is_new_line=1;
   arping = 1;

	// Start network and wait for interface to come up (or error exit).
	printf("Starting/joining ad-hoc network...\n");
	sock_init_or_exit(1);

   name=PINGWHO;
   itts=0;		// 0 == continuous

   if (!(host = resolve( name ))) {
      printf("Unable to resolve '%s'\n", name );
      exit( 3 );
   }
   if ( isaddr( name ))
      printf("Pinging [%s]",inet_ntoa(tempbuffer, host));
   else
      printf("Pinging '%s' [%s]",name, inet_ntoa(tempbuffer, host));

	if (!itts)
		itts = 1000000L;

   printf(" %lu times\n", itts);




   tot_timeout = _SET_TIMEOUT((itts + 2)*1000L);

	send_timeout = _SET_TIMEOUT(0);
   do {
      /* once per second - do all this */
      if ( chk_timeout( send_timeout )) {
         send_timeout = _SET_TIMEOUT(1000L);
         if (chk_timeout( tot_timeout )) {
            stats();
            break;
         }
         if (arping) {
	         if (!_arp_resolve( host, (eth_address *)tempbuffer, 0 ))
	            printf("Could not resolve hardware address (maybe other host not up yet)\n");
	         else {
	         	arping = 0;
	            printf("Hardware address resolved to %02x:%02x:%02x:%02x:%02x:%02x\n",
	               (int)tempbuffer[0],(int)tempbuffer[1],(int)tempbuffer[2],(int)tempbuffer[3],
	               (int)tempbuffer[4],(int)tempbuffer[5]);
	         }
         }
         if (!arping && sent < itts) {
            sent++;
            if (_ping( host , sent ))
               stats();
            if (!is_new_line) printf("\n");
            printf("sent PING # %lu ", sent );
            is_new_line = 0;
         }
      }

      if ( kbhit() ) {
         getchar();    /* trash the character */
         stats();
      }

      tcp_tick(NULL);
      if (arping)
      	continue;
      if ((timer = _chk_ping( host , &new_rcvd)) != 0xffffffffL) {
         tot_delays += timer;
         ++received;
         if ( new_rcvd != last_rcvd + 1 ) {
            if (!is_new_line) printf("\n");
            printf("PING receipt received out of order!\n");
            is_new_line = 1;
         }
         last_rcvd = new_rcvd;
         if (!is_new_line) printf(", ");
         printf("PING receipt # %lu : response time %lu ms\n", received, timer);
         is_new_line = 1;
         if ( received == itts )
            stats();
      }
   } while (1);
}
Example #17
0
unsigned  sytek_int( unsigned ax /*, unsigned dx */ )
{
    unsigned char ah;
    unsigned char ch;
/*    int sent; */
    unsigned int status;


    if ( !s ) {
        return( 0x1000 );   /* timeout */
    }

    if (chk_timeout( recvtimeout )) {
        do_reception();
        recvtimeout = set_ttimeout( 2 );    /* 10 ms */
    }

    /* disable(); receive_clock = RECEIVE_TICKS; enable(); } */

    ah = ax >> 8;

    if( ah == 1 ) {			/* send char in AL */
	ch = ax & 0x0FF;
/*	if (ch == '\r') ch = '\n'; */

	if( ((tran_in + 1) % TRANSMIT_BUF_SIZE) == tran_out ) {
	    outs( "?tr_buf_full?" );
	    status = 0x08000 | ch;
	} else {
	    if ((ch == '\r') && echo ) stuff_char( '\n' );
	    else stuff_char( ch );

	    status = 0x06000 | ch;

	    /* local echoing if requested */
	    if ( echo ) {
		receive_buffer[ rec_in ] = ch;
		rec_in = (rec_in + 1) % RECEIVE_BUF_SIZE;
		if (ch == '\r') {
		    receive_buffer[ rec_in ] = '\n';
		    rec_in = (rec_in + 1) % RECEIVE_BUF_SIZE;
		}
	    }
	}
    } else if( ah == 2 ) {		/* receive char into AL */
        do {
            ch = 0;
            if( rec_in == rec_out )
	        status = 0x08000;
            else {
		status = ch = (ttinc( 0 ) & 0xff);
                if ( ch == IAC ) {
                    /* process this stuff */
		    ch = ttinc( 0 );
                    if ( ch == IAC ) ch = 0; /* let it pass through */
		    else tn_doop(ch);
                }
            }
	} while ( ch == IAC );
	/* status = 0x0800; timeout */
    }
    else if( ah == 3 ) {		/* get status */
	if( rec_in == rec_out )
	    status = 0x06010;
	else {
	    status = 0x06110;
	}

    } else if( ah == 0 ) {		/* init port */
	status = 0x06010;
    } else {
	status = ax;
	outs( "?command_err?" );
    }

    /* here we do the io */
    if( transmit_clock <= 0 ) {
        do_transmission();
        disable();
        transmit_clock = TRANSMIT_TICKS;
        enable();
    }

    return( status );
}