예제 #1
0
static __inline void
unlink_dyn_rule_print(struct ipfw_flow_id *id)
{
	struct in_addr da;
#ifdef INET6
	char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
#else
	char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
#endif

#ifdef INET6
	if (IS_IP6_FLOW_ID(id)) {
		ip6_sprintf(src, &id->src_ip6);
		ip6_sprintf(dst, &id->dst_ip6);
	} else
#endif
	{
		da.s_addr = htonl(id->src_ip);
		inet_ntoa_r(da, src);
		da.s_addr = htonl(id->dst_ip);
		inet_ntoa_r(da, dst);
	}
	printf("ipfw: unlink entry %s %d -> %s %d, %d left\n",
	    src, id->src_port, dst, id->dst_port, V_dyn_count - 1);
}
예제 #2
0
/*********************************************************************************************************
** 函数名称: __aodvEntryPrint
** 功能描述: 打印 aodv 路由信息
** 输 入  : rt        aodv 路由条目
**           pcBuffer  缓冲区
**           stSize    缓冲区大小
**           pstOffset 偏移量
** 输 出  : NONE
** 全局变量: 
** 调用模块: 
*********************************************************************************************************/
static VOID __aodvEntryPrint (struct aodv_rtnode *rt, PCHAR  pcBuffer, size_t  stSize, size_t *pstOffset)
{
    CHAR    cIpDest[INET_ADDRSTRLEN];
    CHAR    cNextHop[INET_ADDRSTRLEN];
    CHAR    cMask[INET_ADDRSTRLEN];
    CHAR    cFlag[16] = "\0";
    CHAR    cIfName[IF_NAMESIZE] = "\0";
    
    inet_ntoa_r(rt->dest_addr, cIpDest, INET_ADDRSTRLEN);
    inet_ntoa_r(rt->next_hop, cNextHop, INET_ADDRSTRLEN);
    
    if (rt->state & AODV_VALID) {
        lib_strcat(cFlag, "U");
    }
    if (rt->hcnt > 0) {
        lib_strcat(cFlag, "G");
    }
    if ((rt->flags & AODV_RT_GATEWAY) == 0) {
        lib_strcat(cFlag, "H");
    }
    if ((rt->flags & AODV_RT_UNIDIR) == 0) {                            /*  单向连接                    */
        lib_strcat(cFlag, "-ud");
    }
    
    /*
     *  aodv 路由节点网络接口一定有效
     */
    ipaddr_ntoa_r(&rt->netif->netmask, cMask, INET_ADDRSTRLEN);
    if_indextoname(rt->netif->num, cIfName);
    
    *pstOffset = bnprintf(pcBuffer, stSize, *pstOffset,
                          "%-18s %-18s %-18s %-8s %8d %-3s\n",
                          cIpDest, cNextHop, cMask, cFlag, rt->hcnt, cIfName);
}
예제 #3
0
/*
 * Format an IPv4 address, more or less like inet_ntoa().
 *
 * Returns `dst' (as a const)
 * Note:
 *  - uses no statics
 *  - takes a unsigned char* not an in_addr as input
 */
static char *inet_ntop4 (const unsigned char *src, char *dst, size_t size)
{
#if defined(HAVE_INET_NTOA_R_2_ARGS)
  const char *ptr;
  DEBUGASSERT(size >= 16);
  ptr = inet_ntoa_r(*(struct in_addr*)src, dst);
  return (char *)memmove(dst, ptr, strlen(ptr)+1);

#elif defined(HAVE_INET_NTOA_R)

#if defined(HAVE_INT_INET_NTOA_R)
  return inet_ntoa_r(*(struct in_addr*)src, dst, size)? NULL: dst;
#else
  return inet_ntoa_r(*(struct in_addr*)src, dst, size);
#endif

#else
  const char *addr = inet_ntoa(*(struct in_addr*)src);

  if(strlen(addr) >= size)
  {
    SET_ERRNO(ENOSPC);
    return (NULL);
  }
  return strcpy(dst, addr);
#endif
}
예제 #4
0
char *
uinet_inet_ntoa(struct uinet_in_addr in, char *buf, unsigned int size)
{
	(void)size;

	return inet_ntoa_r(*((struct in_addr *)&in), buf); 
}
예제 #5
0
 int ObTbnetCallback::shadow_process(easy_request_t* r)
 {
   int ret = EASY_OK;
   if (NULL == r || NULL == r->ipacket)
   {
     TBSYS_LOG(ERROR, "request is empty, r = %p, r->ipacket = %p", r, r->ipacket);
     ret = EASY_BREAK;
   }
   else
   {
     ObShadowServer *server = (ObShadowServer*)r->ms->c->handler->user_data;
     ObPacket *req = (ObPacket*) r->ipacket;
     req->set_request(r);
     ret = server->handlePacket(req);
     if (OB_SUCCESS == ret)
     {
       r->ms->c->pool->ref++;
       easy_atomic_inc(&r->ms->pool->ref);
       easy_pool_set_lock(r->ms->pool);
       ret = EASY_AGAIN;
     }
     else
     {
       ret = EASY_OK;
       TBSYS_LOG(WARN, "can not push packet(src is %s, pcode is %u) to packet queue",
                 inet_ntoa_r(r->ms->c->addr), req->get_packet_code());
     }
   }
   return ret;
 }
예제 #6
0
char *Curl_if2ip(const char *interface, char *buf, int buf_size)
{
  int dummy;
  char *ip=NULL;

  if(!interface)
    return NULL;

  dummy = socket(AF_INET, SOCK_STREAM, 0);
  if (SYS_ERROR == dummy) {
    return NULL;
  }
  else {
    struct ifreq req;
    size_t len = strlen(interface);
    memset(&req, 0, sizeof(req));
    if(len >= sizeof(req.ifr_name))
      return NULL; /* this can't be a fine interface name */
    memcpy(req.ifr_name, interface, len+1);
    req.ifr_addr.sa_family = AF_INET;
#ifdef  IOCTL_3_ARGS
    if (SYS_ERROR == ioctl(dummy, SIOCGIFADDR, &req)) {
#else
    if (SYS_ERROR == ioctl(dummy, SIOCGIFADDR, &req, sizeof(req))) {
#endif
      sclose(dummy);
      return NULL;
    }
    else {
      struct in_addr in;

      union {
        struct sockaddr_in *sin;
        struct sockaddr *s;
      } soadd;

      soadd.s = &req.ifr_dstaddr;
      memcpy(&in, &(soadd.sin->sin_addr.s_addr), sizeof(in));
#if defined(HAVE_INET_NTOA_R)
      ip = inet_ntoa_r(in,buf,buf_size);
#else
      ip = strncpy(buf,inet_ntoa(in),buf_size);
      ip[buf_size - 1] = 0;
#endif
    }
    sclose(dummy);
  }
  return ip;
}

/* -- end of if2ip() -- */
#else
char *Curl_if2ip(const char *interface, char *buf, int buf_size)
{
    (void) interface;
    (void) buf;
    (void) buf_size;
    return NULL;
}
예제 #7
0
/*
*保存本端地址
*/
int CBaseSocket::SaveSockAddr()
{
    socklen_t len = sizeof(m_SockAddr);
    int n =  getsockname(m_iSocket, (struct sockaddr *)&m_SockAddr, &len);
    char buf[32] = {0};
    inet_ntoa_r(m_SockAddr.sin_addr, buf);
    return n;
}
예제 #8
0
파일: mountd.c 프로젝트: andreiw/polaris
/*
 * Get the client's hostname from the transport handle
 * If the name is not available then return "(anon)".
 */
void
getclientsnames(SVCXPRT *transp, struct netbuf **nbuf,
    struct nd_hostservlist **serv)
{
	struct netconfig *nconf;
	char tmp[MAXIPADDRLEN];
	char *host = NULL;

	nconf = getnetconfigent(transp->xp_netid);
	if (nconf == NULL) {
		syslog(LOG_ERR, "%s: getnetconfigent failed",
			transp->xp_netid);
		*serv = anon_client(host);
		return;
	}

	*nbuf = svc_getrpccaller(transp);
	if (*nbuf == NULL) {
		freenetconfigent(nconf);
		*serv = anon_client(host);
		return;
	}

	/*
	 * Use the this API instead of the netdir_getbyaddr()
	 * to avoid service lookup.
	 */
	if (__netdir_getbyaddr_nosrv(nconf, serv, *nbuf)) {
		host = &tmp[0];
		if (strcmp(nconf->nc_protofmly, NC_INET) == 0) {
			struct sockaddr_in *sa;

			/* LINTED pointer alignment */
			sa = (struct sockaddr_in *)((*nbuf)->buf);
			(void) inet_ntoa_r(sa->sin_addr, tmp);
			*serv =	anon_client(host);
			freenetconfigent(nconf);
			return;
		} else if (strcmp(nconf->nc_protofmly, NC_INET6) == 0) {
			struct sockaddr_in6 *sa;

			/* LINTED pointer alignment */
			sa = (struct sockaddr_in6 *)((*nbuf)->buf);
			(void) inet_ntop(AF_INET6, sa->sin6_addr.s6_addr,
					tmp, INET6_ADDRSTRLEN);
			*serv =	anon_client(host);
			freenetconfigent(nconf);
			return;
		}
		freenetconfigent(nconf);
		*serv = anon_client(host);
		return;
	}
	freenetconfigent(nconf);
}
예제 #9
0
const char *
tds_inet_ntoa_r(struct in_addr iaddr, char *ip, size_t len)
{
#if defined(AF_INET) && HAVE_INET_NTOP
    inet_ntop(AF_INET, &iaddr, ip, len);
#elif HAVE_INET_NTOA_R
    inet_ntoa_r(iaddr, ip, len);
#else
    tds_strlcpy(ip, inet_ntoa(iaddr), len);
#endif
    return ip;
}
예제 #10
0
파일: arp.c 프로젝트: rfujiyama/netmap-test
void arp_print(struct arp_pkt *arp) {
  char sha[6*3];
  char spa[4*4];
  char tha[6*3];
  char tpa[4*4];

  printf("ARP ");
  /*
  switch(arp->arp_h.ar_hrd) {
    case ARPHRD_ETHER:
    case ARPHRD_IEEE802:
    case ARPHRD_ARCNET:
    case ARPHRD_FRELAY:
    case ARPHRD_IEEE11394:
    case ARPHRD_INFINIBAND:
    default:
  }
  */
  switch(arp->arp_h.ar_op) {
    case ARP_OP_REQUEST:
      printf("Request\n");
      break;
    case ARP_OP_REPLY:
      printf("Reply\n");
      break;
    case ARP_OP_REVREQUEST:
    case ARP_OP_REVREPLY:
    case ARP_OP_INVREQUEST:
    case ARP_OP_INVREPLY:
    default:
      printf("Unknown Operation\n");
  }
  ether_ntoa_r(&arp->sha, sha);
  inet_ntoa_r(arp->spa, spa, sizeof(spa));
  ether_ntoa_r(&arp->tha, tha);
  inet_ntoa_r(arp->tpa, tpa, sizeof(tpa));

  printf("  Sender: %s (%s)\n", spa, sha); 
  printf("  Target: %s (%s)\n", tpa, tha);
}
예제 #11
0
파일: ip4.c 프로젝트: rfujiyama/netmap-test
void ip4_print(struct ip4_pkt *ip) {
  char ip_src[4*4];
  char ip_dst[4*4];
  uint16_t fragment;

  printf("IP4\n");
  printf("  version: %u\n", ip->ip_h.ip_v);
  printf("  header len: %u (32bit words)\n", ip->ip_h.ip_hl);
  printf("  TOS: %" PRIu8 "\n", ip->ip_h.ip_tos);
  printf("  total len: %hu\n", ntohs(ip->ip_h.ip_len));
  printf("  identification: %hu\n", ntohs(ip->ip_h.ip_id));
  printf("  fragment flags: ");
  fragment = ntohs(ip->ip_h.ip_off);
  printf("    reserved bit: %u ", fragment & IP_RF ? 1 : 0);
  printf("    DF bit: %u ", fragment & IP_DF ? 1 : 0);
  printf("    MF bit: %u\n", fragment & IP_MF ? 1 : 0);
  printf("  fragment offset: %hu\n", (unsigned short)(fragment & IP_OFFMASK));
  printf("  TTL: %" PRIu8 "\n", ip->ip_h.ip_ttl);
  printf("  protocol: ");

  switch (ip->ip_h.ip_p) {
    case IPPROTO_TCP:
      printf("TCP\n");
      break;
    case IPPROTO_UDP:
      printf("UDP\n");
      break;
    case IPPROTO_ICMP:
      printf("ICMP\n");
      break;
    default:
      printf("Unknown Protocol\n");
  }

  printf("  checksum: %hu\n", ntohs(ip->ip_h.ip_sum));
  printf("  src IP: %s\n", inet_ntoa_r(ip->ip_h.ip_src, ip_src,
          sizeof(ip_src)));
  printf("  dst IP: %s\n", inet_ntoa_r(ip->ip_h.ip_dst, ip_dst,
          sizeof(ip_dst)));
}
예제 #12
0
파일: ip4.c 프로젝트: rfujiyama/netmap-test
void ip4_print_line(struct ip4_pkt *ip) {
  char ip_src[4*4];
  char ip_dst[4*4];

  printf("IPv4: %s -> %s ",
          inet_ntoa_r(ip->ip_h.ip_src, ip_src, sizeof(ip_src)),
          inet_ntoa_r(ip->ip_h.ip_dst, ip_dst, sizeof(ip_dst)));
  switch (ip->ip_h.ip_p) {
    case IPPROTO_TCP:
      printf("TCP ");
      break;
    case IPPROTO_UDP:
      printf("UDP ");
      break;
    case IPPROTO_ICMP:
      printf("ICMP ");
      break;
    default:
      printf("UNK ");
  }
  printf("%u/%hu\n", 4*ip->ip_h.ip_hl, ntohs(ip->ip_h.ip_len));
}
예제 #13
0
파일: arp.c 프로젝트: rfujiyama/netmap-test
void arp_print_line(struct arp_pkt *arp) {
  char sha[6*3];
  char spa[4*4];
  char tha[6*3];
  char tpa[4*4];

  printf("ARP_");
  switch(arp->arp_h.ar_op) {
    case ARP_OP_REQUEST:
      printf("REQ");
      break;
    case ARP_OP_REPLY:
      printf("REP");
      break;
    default:
      printf("UNK");
  }
  ether_ntoa_r(&arp->sha, sha);
  inet_ntoa_r(arp->spa, spa, sizeof(spa));
  ether_ntoa_r(&arp->tha, tha);
  inet_ntoa_r(arp->tpa, tpa, sizeof(tpa));

  printf(": %s/%s > %s/%s\n", spa, sha, tpa, tha);
}
예제 #14
0
void arp_cache_print(struct arp_cache *arp_cache) {
  uint32_t i;
  char ip[4*4];
  char mac[6*3];
  struct in_addr temp;

  for (i=0; i < arp_cache->num_entries; i++) {
    if (arp_cache->values[i].timestamp.tv_sec == 0)
      continue;
    temp.s_addr = arp_cache->baseline + htonl(i);
    inet_ntoa_r(temp, ip, sizeof(ip));
    ether_ntoa_r(&arp_cache->values[i].mac, mac);
    printf("arp_cache[%u]: %s->%s\n", i, ip, mac);
  }
}
예제 #15
0
    int ObProxyCallback::process(easy_request_t *r)
    {
      int ret = EASY_OK;

      if (NULL == r)
      {
        TBSYS_LOG(WARN, "request is NULL, r = %p", r);
        ret = EASY_BREAK;
      }
      else if (NULL == r->ipacket)
      {
        TBSYS_LOG(WARN, "request is NULL, r->ipacket = %p", r->ipacket);
        ret = EASY_BREAK;
      }
      else
      {
        ObProxyServer* server = (ObProxyServer*)r->ms->c->handler->user_data;
        ObPacket* packet = (ObPacket*)r->ipacket;
        packet->set_request(r);
        //handle_request will send response
        if (OB_REQUIRE_HEARTBEAT == packet->get_packet_code())
        {
          server->handle_request(packet);
          ret = EASY_OK;
        }
        else
        {
          ret = server->handlePacket(packet);
          if (OB_SUCCESS == ret)
          {
            r->ms->c->pool->ref++;
            easy_atomic_inc(&r->ms->pool->ref);
            easy_pool_set_lock(r->ms->pool);
            ret = EASY_AGAIN;
          }
          else
          {
            ret = EASY_OK;
            TBSYS_LOG(WARN, "can not push packet(src is %s, pcode is %u) to packet queue",
                      inet_ntoa_r(r->ms->c->addr), packet->get_packet_code());

          }
        }
      }
      return ret;
    }
예제 #16
0
/*  
    Return a numerical IP address and port for the given socket info
 */
PUBLIC int socketAddress(struct sockaddr *addr, int addrlen, char *ip, int ipLen, int *port)
{
#if (ME_UNIX_LIKE || WINDOWS)
    char    service[NI_MAXSERV];

#ifdef IN6_IS_ADDR_V4MAPPED
    if (addr->sa_family == AF_INET6) {
        struct sockaddr_in6* addr6 = (struct sockaddr_in6*) addr;
        if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
            struct sockaddr_in addr4;
            memset(&addr4, 0, sizeof(addr4));
            addr4.sin_family = AF_INET;
            addr4.sin_port = addr6->sin6_port;
            memcpy(&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr + 12, sizeof(addr4.sin_addr.s_addr));
            memcpy(addr, &addr4, sizeof(addr4));
            addrlen = sizeof(addr4);
        }
    }
#endif
    if (getnameinfo(addr, addrlen, ip, ipLen, service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV | NI_NOFQDN)) {
        return -1;
    }
    if (port) {
        *port = atoi(service);
    }

#else
    struct sockaddr_in  *sa;

#if HAVE_NTOA_R
    sa = (struct sockaddr_in*) addr;
    inet_ntoa_r(sa->sin_addr, ip, ipLen);
#else
    uchar   *cp;
    sa = (struct sockaddr_in*) addr;
    cp = (uchar*) &sa->sin_addr;
    fmt(ip, ipLen, "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]);
#endif
    if (port) {
        *port = ntohs(sa->sin_port);
    }
#endif
    return 0;
}
 int ObUpdateCallback::process(easy_request_t* r)
 {
   int ret = EASY_OK;
   if (NULL == r)
   {
     TBSYS_LOG(ERROR, "request is empty, r = %p", r);
     ret = EASY_BREAK;
   }
   else if (NULL == r->ipacket)
   {
     TBSYS_LOG(ERROR, "request is empty, r->ipacket = %p", r->ipacket);
     ret = EASY_BREAK;
   }
   else
   {
     ObUpdateServer *server = reinterpret_cast<ObUpdateServer*>(r->ms->c->handler->user_data);
     ObPacket *req = reinterpret_cast<ObPacket*>(r->ipacket);
     req->set_request(r);
     r->ms->c->pool->ref ++;
     easy_atomic_inc(&r->ms->pool->ref);
     easy_pool_set_lock(r->ms->pool);
     ret = server->handlePacket(req);
     if (OB_SUCCESS == ret)
     {
       // enqueue success
       ret = EASY_AGAIN;
     }
     else if (OB_ENQUEUE_FAILED == ret)
     {
       TBSYS_LOG(WARN, "can not push packet(src is %s, pcode is %u) to packet queue", 
                 inet_ntoa_r(r->ms->c->addr), req->get_packet_code());
       r->ms->c->pool->ref --;
       easy_atomic_dec(&r->ms->pool->ref);
       ret = EASY_OK;
     }
     else /* OB_ERROR */
     {
       ret = EASY_AGAIN;
     }
   }
   return ret;
 }
예제 #18
0
static char *MakeIP(unsigned long num,char *addr, int addr_len)
{
#if defined(HAVE_INET_NTOA) || defined(HAVE_INET_NTOA_R)
  struct in_addr in;
  in.s_addr = htonl(num);

#if defined(HAVE_INET_NTOA_R)
  inet_ntoa_r(in,addr,addr_len);
#else
  strncpy(addr,inet_ntoa(in),addr_len);
#endif
#else
  unsigned char *paddr;

  num = htonl(num);  /* htonl() added to avoid endian probs */
  paddr = (unsigned char *)&num;
  sprintf(addr, "%u.%u.%u.%u", paddr[0], paddr[1], paddr[2], paddr[3]);
#endif
  return (addr);
}
예제 #19
0
/* Incomplete implementation, ipv4 only, port does not work, flags do not work */
int
tds_getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags)
{
    struct sockaddr_in *sin = (struct sockaddr_in *) sa;

    if (sa->sa_family != AF_INET)
        return EAI_FAMILY;

    if (host == NULL || hostlen < 16)
        return EAI_OVERFLOW;

#if defined(AF_INET) && HAVE_INET_NTOP
    inet_ntop(AF_INET, &sin->sin_addr, host, hostlen);
#elif HAVE_INET_NTOA_R
    inet_ntoa_r(sin->sin_addr, host, hostlen);
#else
    strlcpy(hostip, inet_ntoa(sin->sin_addr), hostlen);
#endif

    return 0;
}
예제 #20
0
파일: mkrootfs.c 프로젝트: gedare/rtems
int
rtems_rootfs_append_host_rec (in_addr_t cip,
                              const char    *cname,
                              const char    *dname)
{
  char           buf[128];
  char           *bufp = buf;
  const char     *bufl[1];
  struct in_addr ip;

  ip.s_addr = cip;

  if (cname && strlen (cname))
  {
    char addrbuf[INET_ADDRSTRLEN];

    snprintf (bufp, sizeof (buf), "%s\t\t%s", inet_ntoa_r (ip, addrbuf), cname);
    bufp += strlen (buf);

    if (dname && strlen (dname))
    {
      snprintf (bufp, sizeof (buf), "\t\t%s.%s", cname, dname);
      bufp += strlen (buf);
    }

    strcat (buf, "\n");

    bufl[0] = buf;

    if (rtems_rootfs_file_append ("/etc/hosts", MKFILE_MODE, 1, bufl) < 0)
      return -1;
  }
  else
  {
    printf ("rootfs hosts rec append, no cname supplied\n");
    return -1;
  }

  return 0;
}
예제 #21
0
/* TODO callers seem to set always connection info... change it */
void
tds_lookup_host(const char *servername,	/* (I) name of the server                  */
		char *ip	/* (O) dotted-decimal ip address of server */
	)
{				/* (O) port number of the service          */
	struct hostent *host = NULL;
	unsigned int ip_addr = 0;

	/* Storage for reentrant getaddrby* calls */
	struct hostent result;
	char buffer[4096];
	int h_errnop;

	/* Only call gethostbyname if servername is not an ip address. 
	 * This call take a while and is useless for an ip address.
	 * mlilback 3/2/02 */
	ip_addr = inet_addr(servername);
	if (ip_addr != INADDR_NONE) {
		strncpy(ip, servername, 17);
		return;
	}

	host = tds_gethostbyname_r(servername, &result, buffer, sizeof(buffer), &h_errnop);

	ip[0] = '\0';
	if (host) {
		struct in_addr *ptr = (struct in_addr *) host->h_addr;

#if defined(AF_INET) && HAVE_INET_NTOP
		inet_ntop(AF_INET, ptr, ip, 17);
#elif HAVE_INET_NTOA_R
		inet_ntoa_r(*ptr, ip, 17);
#else
		strncpy(ip, inet_ntoa(*ptr), 17);
#endif
	}
}				/* tds_lookup_host()  */
예제 #22
0
char *inet_ntoa(struct in_addr in)
{
	static pthread_mutex_t inet_ntoa_mutex = PTHREAD_MUTEX_INITIALIZER;
	static pthread_key_t inet_ntoa_key = -1;
	char *buf, *inet_ntoa_r();

	if (inet_ntoa_key < 0) {
		pthread_mutex_lock(&inet_ntoa_mutex);
		if (inet_ntoa_key < 0) {
			if (pthread_key_create(&inet_ntoa_key, free) < 0) {
				pthread_mutex_unlock(&inet_ntoa_mutex);
				return(NULL);
			}
		}
		pthread_mutex_unlock(&inet_ntoa_mutex);
	}
	if ((buf = pthread_getspecific(inet_ntoa_key)) == NULL) {
		if ((buf = (char *) malloc(18)) == NULL) {
			return(NULL);
		}
		pthread_setspecific(inet_ntoa_key, buf);
	}
	return inet_ntoa_r(in, buf, 18);
}
예제 #23
0
파일: pb_cgibin.c 프로젝트: dicoka/ESP8266
int wifi_cgi(char* buf)
{
#ifdef DEBUG_CGI
	printf("\nwificgi -> %s\n", PATH_INFO);
#endif
	char* radio_dhcp;
	char* radio_static;
	save_status = html_save_empt;
	ip_addr_t tmp_ip, tmp_netmask, tmp_gw, tmp_dns1, tmp_dns2;
	uint8 tmp_dhcp;
	int buf_cnt = 0;

#define WIFI_QUERY_NUM 8
CGI_QUERY wcq[WIFI_QUERY_NUM] =
	{
			{"ssid", NULL, "ok"},
			{"pswd", NULL, "ok"},
			{"dhcp", NULL, "ok"},
			{"ip",   "000.000.000.001", "ok"},
			{"mask", "000.000.000.002", "ok"},
			{"gate", "000.000.000.003", "ok"},
			{"dns1", "000.000.000.004", "ok"},
			{"dns2", "000.000.000.005", "ok"}
	};

	if (QUERY_STRING)
	{
		// break query to strings
		if (cgi_query_scan(QUERY_STRING, wcq, WIFI_QUERY_NUM) == CONN_FAIL)
			return 0;
		// convert query strings and check values
		if ( strlen(wcq[0].valstr)>32 ) {wcq[0].err=html_id_err; save_status = html_save_err;} //SSID
		if ( strlen(wcq[1].valstr)>32 ) {wcq[1].err=html_id_err; save_status = html_save_err;}//Password
		if ((strcmp(wcq[2].valstr, "0")) == 0)
		{
			radio_dhcp = "";
			radio_static = html_checked;
			tmp_dhcp = 0;
		}
		else
		{
			if ((strcmp(wcq[2].valstr, "1")) == 0)
			{
			radio_dhcp = html_checked;
			radio_static = "";
			tmp_dhcp = 1;
			}
			else
				return 0;
		}

		if ( !(inet_aton (wcq[3].valstr, &tmp_ip)) ) 		{wcq[3].err=html_id_err; save_status = html_save_err;}; //IP
		if ( !(inet_aton (wcq[4].valstr, &tmp_netmask)) ) 	{wcq[4].err=html_id_err; save_status = html_save_err;}; //Net mask
		if ( !(inet_aton (wcq[5].valstr, &tmp_gw)) )   	{wcq[5].err=html_id_err; save_status = html_save_err;}; //Gateway
		if ( !(inet_aton (wcq[6].valstr, &tmp_dns1)) ) 	{wcq[6].err=html_id_err; save_status = html_save_err;}; //DNS 1
		if ( !(inet_aton (wcq[7].valstr, &tmp_dns2)) ) 	{wcq[7].err=html_id_err; save_status = html_save_err;}; //DNS 2
		// if the query values are OK - save to flash
		if ( save_status != html_save_err )
		{
			if ( wcq[0].valstr[0] != 0 ) // if ssid is not empty
				{strcpy(sysCfg.sta_ssid, wcq[0].valstr);
				strcpy(sysCfg.sta_pswd, wcq[1].valstr);
				}
			sysCfg.sta_dhcp = tmp_dhcp;
			sysCfg.sta_ip_info.ip = tmp_ip;
			sysCfg.sta_ip_info.netmask = tmp_netmask;
			sysCfg.sta_ip_info.gw = tmp_gw;
			sysCfg.sta_dns[0] = tmp_dns1;
			sysCfg.sta_dns[1] = tmp_dns2;
			CFG_Save();
			save_status = html_save_ok;
		}

	}
	// if there was no query or the query was saved succefully
	// read values from saved config
	if (save_status != html_save_err)
	{
		int ii;
	//	for (ii = 3; ii<WIFI_QUERY_NUM-1; ii++)
	//		wcq[ii].valstr = malloc (16);

		//read from sysCfg
		wcq[0].valstr = ""; //SSID
		wcq[1].valstr = ""; //Password
		if (sysCfg.sta_dhcp == 0)
		{
			radio_dhcp = "";
			radio_static = html_checked;
		}
		else
		{
			radio_dhcp = html_checked;
			radio_static = "";
		}

		inet_ntoa_r(sysCfg.sta_ip_info.ip, wcq[3].valstr, 16);
		inet_ntoa_r(sysCfg.sta_ip_info.netmask, wcq[4].valstr, 16);
		inet_ntoa_r(sysCfg.sta_ip_info.gw, wcq[5].valstr, 16);
		inet_ntoa_r(sysCfg.sta_dns[0], wcq[6].valstr, 16);
		inet_ntoa_r(sysCfg.sta_dns[1], wcq[7].valstr, 16);
	}

#ifdef DEBUG_CGI
	printf ("F**K!!! we are here");
#endif

	buf_cnt += web_page_header (buf+buf_cnt, wifi_cgi);

	const char* wifi_cgi_html =
			"<p><form action=\"wifi.cgi\">"
			"SSID:\"%s\"<br>"
			"<p>Change SSID<br>"
			"(type or choose from list)<br>"
			"<input list=\"ide\" name=\"ssid\" value=\"%s\"  />"
			"<datalist id=\"ide\">";
	buf_cnt += sprintf (buf+buf_cnt, wifi_cgi_html, sysCfg.sta_ssid, wcq[0].valstr);
		//scanned SSIDs list generation

		struct bss_info* bss_tmp;
		while (bss_link)
		{
#ifdef DEBUG_CGI
			printf ("\n\n ssid p = %p", (void*)bss_link );
			printf ("\n\n ssid len = %u", bss_link->ssid_len );
			printf ("\n\n ssid = %s", bss_link->ssid );


#endif
			buf_cnt += sprintf(buf + buf_cnt, "<option value=\"%s\" />", bss_link->ssid);
			bss_tmp = bss_link;
			bss_link = bss_link->next.stqe_next;
		}

	 	 	 wifi_cgi_html = "</datalist><a href=/wifi_scan.cgi>SCAN</a><br>"
			"Password:<br><input type=\"text\" name=\"pswd\" value=\"%s\" ID=\"%s\"></p>"
			"<p><input type=\"radio\" name=\"dhcp\" value=\"1\" %s> DHCP client<br>"
	 	 	"<input type=\"radio\" name=\"dhcp\" value=\"0\" %s> Static address</p>"
			"Static - IP:<br><input type=\"text\" name=\"ip\" value=\"%s\" ID=\"%s\" pattern=\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"><br>"
			"Static - Netmask:<br><input type=\"text\" name=\"mask\" value=\"%s\" ID=\"%s\"><br>"
			"Static - Gate:<br><input type=\"text\" name=\"gate\" value=\"%s\" ID=\"%s\"><br>"
			"Static - DNS 1:<br><input type=\"text\" name=\"dns1\" value=\"%s\" ID=\"%s\"><br>"
			"Static - DNS 2:<br><input type=\"text\" name=\"dns2\" value=\"%s\" ID=\"%s\"><br>"
			"<br><input type=\"submit\">"
	 	 	"</form>%s"
	 		"</body></html>";

	buf_cnt += sprintf (buf+buf_cnt, wifi_cgi_html, wcq[1].valstr, wcq[1].err, radio_dhcp, radio_static,
			wcq[3].valstr, wcq[3].err, wcq[4].valstr, wcq[4].err, wcq[5].valstr, wcq[5].err,
			wcq[6].valstr, wcq[6].err, wcq[7].valstr, wcq[7].err, save_status );
/*
	char* valstrs[15];
	valstrs[0] = wcq[1].valstr; valstrs[1] = wcq[1].err, valstrs[2] = radio_dhcp; valstrs[3] =  radio_static;
	valstrs[4] = wcq[3].valstr; valstrs[5] = wcq[3].err; valstrs[6] =  wcq[4].valstr; valstrs[7] =  wcq[4].err; valstrs[8] =  wcq[5].valstr; valstrs[9] =  wcq[5].err;
	valstrs[10] = wcq[6].valstr; valstrs[11] =  wcq[6].err; valstrs[12] =  wcq[7].valstr; valstrs[13] =  wcq[7].err; valstrs[14] =  save_status;

	buf_cnt += sssprintf (buf+buf_cnt, wifi_cgi_html, valstrs);

*/
	/*

 	 wifi_cgi_html = "</datalist><a href=/wifi_scan.cgi>SCAN</a><br>"
			"Password:<br><input type=\"text\" name=\"pswd\" value=\"%s\" ID=\"%s\"><br><br>"
			"<input type=\"radio\" name=\"dhcp\" value=\"1\" %s> DHCP client<br>"
			"<input type=\"radio\" name=\"dhcp\" value=\"0\" %s> Static address<br>";
	buf_cnt += sprintf(buf + buf_cnt, wifi_cgi_html, wcq[1].valstr, wcq[1].err, radio_dhcp, radio_static);
	wifi_cgi_html =
			"Static - IP:<br><input type=\"text\" name=\"ip\" value=\"%s\" ID=\"%s\" pattern=\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"><br>"
					"Static - Netmask:<br><input type=\"text\" name=\"mask\" value=\"%s\" ID=\"%s\"><br>"
					"Static - Gate:<br><input type=\"text\" name=\"gate\" value=\"%s\" ID=\"%s\"><br>";
	buf_cnt += sprintf(buf + buf_cnt, wifi_cgi_html, wcq[3].valstr, wcq[3].err, wcq[4].valstr, wcq[4].err,
			wcq[5].valstr, wcq[5].err);
	wifi_cgi_html = "Static - DNS 1:<br><input type=\"text\" name=\"dns1\" value=\"%s\" ID=\"%s\"><br>"
			"Static - DNS 2:<br><input type=\"text\" name=\"dns2\" value=\"%s\" ID=\"%s\"><br>"
			"<br><input type=\"submit\">"
			"</form>%s"
			"</body></html>";

	buf_cnt += sprintf(buf + buf_cnt, wifi_cgi_html,wcq[6].valstr, wcq[6].err, wcq[7].valstr, wcq[7].err, save_status );

*/

	buf_cnt += web_page_footer (buf+buf_cnt, wifi_cgi);
	return buf_cnt;
}
예제 #24
0
/**
 * Install state of type 'type' for a dynamic session.
 * The hash table contains two type of rules:
 * - regular rules (O_KEEP_STATE)
 * - rules for sessions with limited number of sess per user
 *   (O_LIMIT). When they are created, the parent is
 *   increased by 1, and decreased on delete. In this case,
 *   the third parameter is the parent rule and not the chain.
 * - "parent" rules for the above (O_LIMIT_PARENT).
 */
static ipfw_dyn_rule *
add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
{
	ipfw_dyn_rule *r;
	int i;

	IPFW_DYN_LOCK_ASSERT();

	if (V_ipfw_dyn_v == NULL ||
	    (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
		realloc_dynamic_table();
		if (V_ipfw_dyn_v == NULL)
			return NULL; /* failed ! */
	}
	i = hash_packet(id);

	r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
	if (r == NULL) {
		printf ("ipfw: sorry cannot allocate state\n");
		return NULL;
	}

	/* increase refcount on parent, and set pointer */
	if (dyn_type == O_LIMIT) {
		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
		if ( parent->dyn_type != O_LIMIT_PARENT)
			panic("invalid parent");
		parent->count++;
		r->parent = parent;
		rule = parent->rule;
	}

	r->id = *id;
	r->expire = time_uptime + V_dyn_syn_lifetime;
	r->rule = rule;
	r->dyn_type = dyn_type;
	r->pcnt = r->bcnt = 0;
	r->count = 0;

	r->bucket = i;
	r->next = V_ipfw_dyn_v[i];
	V_ipfw_dyn_v[i] = r;
	V_dyn_count++;
	DEB({
		struct in_addr da;
#ifdef INET6
		char src[INET6_ADDRSTRLEN];
		char dst[INET6_ADDRSTRLEN];
#else
		char src[INET_ADDRSTRLEN];
		char dst[INET_ADDRSTRLEN];
#endif

#ifdef INET6
		if (IS_IP6_FLOW_ID(&(r->id))) {
			ip6_sprintf(src, &r->id.src_ip6);
			ip6_sprintf(dst, &r->id.dst_ip6);
		} else
#endif
		{
			da.s_addr = htonl(r->id.src_ip);
			inet_ntoa_r(da, src);
			da.s_addr = htonl(r->id.dst_ip);
			inet_ntoa_r(da, dst);
		}
		printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n",
		    dyn_type, src, r->id.src_port, dst, r->id.dst_port,
		    V_dyn_count);
	})
	return r;
예제 #25
0
/*
 * We enter here when we have a rule with O_LOG.
 * XXX this function alone takes about 2Kbytes of code!
 */
void
ipfw_log(struct ip_fw_chain *chain, struct ip_fw *f, u_int hlen,
    struct ip_fw_args *args, struct mbuf *m, struct ifnet *oif,
    u_short offset, uint32_t tablearg, struct ip *ip)
{
	char *action;
	int limit_reached = 0;
	char action2[92], proto[128], fragment[32];

	if (V_fw_verbose == 0) {
		if (args->eh) /* layer2, use orig hdr */
			ipfw_bpf_mtap2(args->eh, ETHER_HDR_LEN, m);
		else {
			/* Add fake header. Later we will store
			 * more info in the header.
			 */
			if (ip->ip_v == 4)
				ipfw_bpf_mtap2("DDDDDDSSSSSS\x08\x00",
				    ETHER_HDR_LEN, m);
			else if (ip->ip_v == 6)
				ipfw_bpf_mtap2("DDDDDDSSSSSS\x86\xdd",
				    ETHER_HDR_LEN, m);
			else
				/* Obviously bogus EtherType. */
				ipfw_bpf_mtap2("DDDDDDSSSSSS\xff\xff",
				    ETHER_HDR_LEN, m);
		}
		return;
	}
	/* the old 'log' function */
	fragment[0] = '\0';
	proto[0] = '\0';

	if (f == NULL) {	/* bogus pkt */
		if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
			return;
		V_norule_counter++;
		if (V_norule_counter == V_verbose_limit)
			limit_reached = V_verbose_limit;
		action = "Refuse";
	} else {	/* O_LOG is the first action, find the real one */
		ipfw_insn *cmd = ACTION_PTR(f);
		ipfw_insn_log *l = (ipfw_insn_log *)cmd;

		if (l->max_log != 0 && l->log_left == 0)
			return;
		l->log_left--;
		if (l->log_left == 0)
			limit_reached = l->max_log;
		cmd += F_LEN(cmd);	/* point to first action */
		if (cmd->opcode == O_ALTQ) {
			ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;

			snprintf(SNPARGS(action2, 0), "Altq %d",
				altq->qid);
			cmd += F_LEN(cmd);
		}
		if (cmd->opcode == O_PROB || cmd->opcode == O_TAG ||
		    cmd->opcode == O_SETDSCP)
			cmd += F_LEN(cmd);

		action = action2;
		switch (cmd->opcode) {
		case O_DENY:
			action = "Deny";
			break;

		case O_REJECT:
			if (cmd->arg1==ICMP_REJECT_RST)
				action = "Reset";
			else if (cmd->arg1==ICMP_REJECT_ABORT)
				action = "Abort";
			else if (cmd->arg1==ICMP_UNREACH_HOST)
				action = "Reject";
			else
				snprintf(SNPARGS(action2, 0), "Unreach %d",
					cmd->arg1);
			break;

		case O_UNREACH6:
			if (cmd->arg1==ICMP6_UNREACH_RST)
				action = "Reset";
			else if (cmd->arg1==ICMP6_UNREACH_ABORT)
				action = "Abort";
			else
				snprintf(SNPARGS(action2, 0), "Unreach %d",
					cmd->arg1);
			break;

		case O_ACCEPT:
			action = "Accept";
			break;
		case O_COUNT:
			action = "Count";
			break;
		case O_DIVERT:
			snprintf(SNPARGS(action2, 0), "Divert %d",
				TARG(cmd->arg1, divert));
			break;
		case O_TEE:
			snprintf(SNPARGS(action2, 0), "Tee %d",
				TARG(cmd->arg1, divert));
			break;
		case O_SETFIB:
			snprintf(SNPARGS(action2, 0), "SetFib %d",
				TARG(cmd->arg1, fib) & 0x7FFF);
			break;
		case O_SKIPTO:
			snprintf(SNPARGS(action2, 0), "SkipTo %d",
				TARG(cmd->arg1, skipto));
			break;
		case O_PIPE:
			snprintf(SNPARGS(action2, 0), "Pipe %d",
				TARG(cmd->arg1, pipe));
			break;
		case O_QUEUE:
			snprintf(SNPARGS(action2, 0), "Queue %d",
				TARG(cmd->arg1, pipe));
			break;
		case O_FORWARD_IP: {
			char buf[INET_ADDRSTRLEN];
			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
			int len;
			struct in_addr dummyaddr;
			if (sa->sa.sin_addr.s_addr == INADDR_ANY)
				dummyaddr.s_addr = htonl(tablearg);
			else
				dummyaddr.s_addr = sa->sa.sin_addr.s_addr;

			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
				inet_ntoa_r(dummyaddr, buf));

			if (sa->sa.sin_port)
				snprintf(SNPARGS(action2, len), ":%d",
				    sa->sa.sin_port);
			}
			break;
#ifdef INET6
		case O_FORWARD_IP6: {
			char buf[INET6_ADDRSTRLEN];
			ipfw_insn_sa6 *sa = (ipfw_insn_sa6 *)cmd;
			int len;

			len = snprintf(SNPARGS(action2, 0), "Forward to [%s]",
			    ip6_sprintf(buf, &sa->sa.sin6_addr));

			if (sa->sa.sin6_port)
				snprintf(SNPARGS(action2, len), ":%u",
				    sa->sa.sin6_port);
			}
			break;
#endif
		case O_NETGRAPH:
			snprintf(SNPARGS(action2, 0), "Netgraph %d",
				cmd->arg1);
			break;
		case O_NGTEE:
			snprintf(SNPARGS(action2, 0), "Ngtee %d",
				cmd->arg1);
			break;
		case O_NAT:
			action = "Nat";
 			break;
		case O_REASS:
			action = "Reass";
			break;
		case O_CALLRETURN:
			if (cmd->len & F_NOT)
				action = "Return";
			else
				snprintf(SNPARGS(action2, 0), "Call %d",
				    cmd->arg1);
			break;
		case O_EXTERNAL_ACTION:
			snprintf(SNPARGS(action2, 0), "Eaction %s",
			    ((struct named_object *)SRV_OBJECT(chain,
			    cmd->arg1))->name);
			break;
		default:
			action = "UNKNOWN";
			break;
		}
	}

	if (hlen == 0) {	/* non-ip */
		snprintf(SNPARGS(proto, 0), "MAC");

	} else {
		int len;
#ifdef INET6
		char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
#else
		char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
#endif
		struct icmphdr *icmp;
		struct tcphdr *tcp;
		struct udphdr *udp;
#ifdef INET6
		struct ip6_hdr *ip6 = NULL;
		struct icmp6_hdr *icmp6;
		u_short ip6f_mf;
#endif
		src[0] = '\0';
		dst[0] = '\0';
#ifdef INET6
		ip6f_mf = offset & IP6F_MORE_FRAG;
		offset &= IP6F_OFF_MASK;

		if (IS_IP6_FLOW_ID(&(args->f_id))) {
			char ip6buf[INET6_ADDRSTRLEN];
			snprintf(src, sizeof(src), "[%s]",
			    ip6_sprintf(ip6buf, &args->f_id.src_ip6));
			snprintf(dst, sizeof(dst), "[%s]",
			    ip6_sprintf(ip6buf, &args->f_id.dst_ip6));

			ip6 = (struct ip6_hdr *)ip;
			tcp = (struct tcphdr *)(((char *)ip) + hlen);
			udp = (struct udphdr *)(((char *)ip) + hlen);
		} else
#endif
		{
			tcp = L3HDR(struct tcphdr, ip);
			udp = L3HDR(struct udphdr, ip);

			inet_ntop(AF_INET, &ip->ip_src, src, sizeof(src));
			inet_ntop(AF_INET, &ip->ip_dst, dst, sizeof(dst));
		}

		switch (args->f_id.proto) {
		case IPPROTO_TCP:
			len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
			if (offset == 0)
				snprintf(SNPARGS(proto, len), ":%d %s:%d",
				    ntohs(tcp->th_sport),
				    dst,
				    ntohs(tcp->th_dport));
			else
				snprintf(SNPARGS(proto, len), " %s", dst);
			break;

		case IPPROTO_UDP:
		case IPPROTO_UDPLITE:
			len = snprintf(SNPARGS(proto, 0), "UDP%s%s",
			    args->f_id.proto == IPPROTO_UDP ? " ": "Lite ",
			    src);
			if (offset == 0)
				snprintf(SNPARGS(proto, len), ":%d %s:%d",
				    ntohs(udp->uh_sport),
				    dst,
				    ntohs(udp->uh_dport));
			else
				snprintf(SNPARGS(proto, len), " %s", dst);
			break;

		case IPPROTO_ICMP:
			icmp = L3HDR(struct icmphdr, ip);
			if (offset == 0)
				len = snprintf(SNPARGS(proto, 0),
				    "ICMP:%u.%u ",
				    icmp->icmp_type, icmp->icmp_code);
			else
				len = snprintf(SNPARGS(proto, 0), "ICMP ");
			len += snprintf(SNPARGS(proto, len), "%s", src);
			snprintf(SNPARGS(proto, len), " %s", dst);
			break;
#ifdef INET6
		case IPPROTO_ICMPV6:
			icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
			if (offset == 0)
				len = snprintf(SNPARGS(proto, 0),
				    "ICMPv6:%u.%u ",
				    icmp6->icmp6_type, icmp6->icmp6_code);
			else
				len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
			len += snprintf(SNPARGS(proto, len), "%s", src);
			snprintf(SNPARGS(proto, len), " %s", dst);
			break;
#endif
		default:
			len = snprintf(SNPARGS(proto, 0), "P:%d %s",
			    args->f_id.proto, src);
			snprintf(SNPARGS(proto, len), " %s", dst);
			break;
		}

#ifdef INET6
		if (IS_IP6_FLOW_ID(&(args->f_id))) {
			if (offset || ip6f_mf)
				snprintf(SNPARGS(fragment, 0),
				    " (frag %08x:%d@%d%s)",
				    args->f_id.extra,
				    ntohs(ip6->ip6_plen) - hlen,
				    ntohs(offset) << 3, ip6f_mf ? "+" : "");
		} else
#endif
		{
			int ipoff, iplen;
			ipoff = ntohs(ip->ip_off);
			iplen = ntohs(ip->ip_len);
			if (ipoff & (IP_MF | IP_OFFMASK))
				snprintf(SNPARGS(fragment, 0),
				    " (frag %d:%d@%d%s)",
				    ntohs(ip->ip_id), iplen - (ip->ip_hl << 2),
				    offset << 3,
				    (ipoff & IP_MF) ? "+" : "");
		}
	}
#ifdef __FreeBSD__
	if (oif || m->m_pkthdr.rcvif)
		log(LOG_SECURITY | LOG_INFO,
		    "ipfw: %d %s %s %s via %s%s\n",
		    f ? f->rulenum : -1,
		    action, proto, oif ? "out" : "in",
		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
		    fragment);
	else
#endif
		log(LOG_SECURITY | LOG_INFO,
		    "ipfw: %d %s %s [no if info]%s\n",
		    f ? f->rulenum : -1,
		    action, proto, fragment);
	if (limit_reached)
		log(LOG_SECURITY | LOG_NOTICE,
		    "ipfw: limit %d reached on entry %d\n",
		    limit_reached, f ? f->rulenum : -1);
}
예제 #26
0
int CBaseSocket::Connect(struct sockaddr_in *addr, int timeout_usec /*=-1*/)
{
    char buf[32] = {0};
    inet_ntoa_r(addr->sin_addr, buf);
    socklen_t addr_len = sizeof(struct sockaddr_in);
    int retval = 0;
    if (timeout_usec < 0) // 阻塞
    {
        int n = connect(m_iSocket, (struct sockaddr *)addr, addr_len);
        if(n != 0)
        {
            perror("connect:");
            return -1;
        }

        //...........
        SaveAddr();
        return 0;
    }
    SetNonBlockOption(true);
    retval= connect(m_iSocket, (struct sockaddr *) addr, addr_len);
    if(retval < 0 && errno != EINPROGRESS)
    {
        Close();
        return -1;
    }


    if(retval == 0)
    {
    	SaveAddr();
        SetNonBlockOption(false);
        return 0;
    }

    if(timeout_usec == 0)   //timeout
    {
    	Close();
        return -1;
    }
    fd_set rset, wset;
    FD_ZERO(&rset);
    FD_SET(m_iSocket, &rset);
    FD_ZERO(&wset);
    FD_SET(m_iSocket, &wset);
    struct timeval timeout;
    MkTimeval(timeout, timeout_usec);
    int n = select(m_iSocket + 1, &rset, &wset, NULL, &timeout);
    if( n == 0) //timeout
    {
    	Close();
        return -1;
    }

    int error = 0;
    if(FD_ISSET(m_iSocket, &rset) || FD_ISSET(m_iSocket, &wset))
    {
        socklen_t len = sizeof(error);
        if(getsockopt(m_iSocket, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
        {
            Close();
            return -1;
        }

        SetNonBlockOption(false);

        if(error)
        {
        	    Close();
            return -1;
        }
        SaveAddr();
        return 0;
    }
        //not ready...
    Close();
    return -1;
}
예제 #27
0
/*
 * We enter here when we have a rule with O_LOG.
 * XXX this function alone takes about 2Kbytes of code!
 */
void
ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
    struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
    struct ip *ip)
{
	char *action;
	int limit_reached = 0;
	char action2[40], proto[128], fragment[32];

	if (V_fw_verbose == 0) {
#ifndef WITHOUT_BPF
		struct m_hdr mh;

		if (log_if == NULL || log_if->if_bpf == NULL)
			return;
		/* BPF treats the "mbuf" as read-only */
		mh.mh_next = m;
		mh.mh_len = ETHER_HDR_LEN;
		if (args->eh) { /* layer2, use orig hdr */
			mh.mh_data = (char *)args->eh;
		} else {
			/* add fake header. Later we will store
			 * more info in the header
			 */
			mh.mh_data = "DDDDDDSSSSSS\x08\x00";
		}
		BPF_MTAP(log_if, (struct mbuf *)&mh);
#endif /* !WITHOUT_BPF */
		return;
	}
	/* the old 'log' function */
	fragment[0] = '\0';
	proto[0] = '\0';

	if (f == NULL) {	/* bogus pkt */
		if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
			return;
		V_norule_counter++;
		if (V_norule_counter == V_verbose_limit)
			limit_reached = V_verbose_limit;
		action = "Refuse";
	} else {	/* O_LOG is the first action, find the real one */
		ipfw_insn *cmd = ACTION_PTR(f);
		ipfw_insn_log *l = (ipfw_insn_log *)cmd;

		if (l->max_log != 0 && l->log_left == 0)
			return;
		l->log_left--;
		if (l->log_left == 0)
			limit_reached = l->max_log;
		cmd += F_LEN(cmd);	/* point to first action */
		if (cmd->opcode == O_ALTQ) {
			ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;

			snprintf(SNPARGS(action2, 0), "Altq %d",
				altq->qid);
			cmd += F_LEN(cmd);
		}
		if (cmd->opcode == O_PROB)
			cmd += F_LEN(cmd);

		if (cmd->opcode == O_TAG)
			cmd += F_LEN(cmd);

		action = action2;
		switch (cmd->opcode) {
		case O_DENY:
			action = "Deny";
			break;

		case O_REJECT:
			if (cmd->arg1==ICMP_REJECT_RST)
				action = "Reset";
			else if (cmd->arg1==ICMP_UNREACH_HOST)
				action = "Reject";
			else
				snprintf(SNPARGS(action2, 0), "Unreach %d",
					cmd->arg1);
			break;

		case O_UNREACH6:
			if (cmd->arg1==ICMP6_UNREACH_RST)
				action = "Reset";
			else
				snprintf(SNPARGS(action2, 0), "Unreach %d",
					cmd->arg1);
			break;

		case O_ACCEPT:
			action = "Accept";
			break;
		case O_COUNT:
			action = "Count";
			break;
		case O_DIVERT:
			snprintf(SNPARGS(action2, 0), "Divert %d",
				cmd->arg1);
			break;
		case O_TEE:
			snprintf(SNPARGS(action2, 0), "Tee %d",
				cmd->arg1);
			break;
		case O_SETFIB:
			snprintf(SNPARGS(action2, 0), "SetFib %d",
				cmd->arg1);
			break;
		case O_SKIPTO:
			snprintf(SNPARGS(action2, 0), "SkipTo %d",
				cmd->arg1);
			break;
		case O_PIPE:
			snprintf(SNPARGS(action2, 0), "Pipe %d",
				cmd->arg1);
			break;
		case O_QUEUE:
			snprintf(SNPARGS(action2, 0), "Queue %d",
				cmd->arg1);
			break;
		case O_FORWARD_IP: {
			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
			int len;
			struct in_addr dummyaddr;
			if (sa->sa.sin_addr.s_addr == INADDR_ANY)
				dummyaddr.s_addr = htonl(tablearg);
			else
				dummyaddr.s_addr = sa->sa.sin_addr.s_addr;

			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
				inet_ntoa(dummyaddr));

			if (sa->sa.sin_port)
				snprintf(SNPARGS(action2, len), ":%d",
				    sa->sa.sin_port);
			}
			break;
		case O_NETGRAPH:
			snprintf(SNPARGS(action2, 0), "Netgraph %d",
				cmd->arg1);
			break;
		case O_NGTEE:
			snprintf(SNPARGS(action2, 0), "Ngtee %d",
				cmd->arg1);
			break;
		case O_NAT:
			action = "Nat";
 			break;
		case O_REASS:
			action = "Reass";
			break;
		default:
			action = "UNKNOWN";
			break;
		}
	}

	if (hlen == 0) {	/* non-ip */
		snprintf(SNPARGS(proto, 0), "MAC");

	} else {
		int len;
#ifdef INET6
		char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
#else
		char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
#endif
		struct icmphdr *icmp;
		struct tcphdr *tcp;
		struct udphdr *udp;
#ifdef INET6
		struct ip6_hdr *ip6 = NULL;
		struct icmp6_hdr *icmp6;
#endif
		src[0] = '\0';
		dst[0] = '\0';
#ifdef INET6
		if (IS_IP6_FLOW_ID(&(args->f_id))) {
			char ip6buf[INET6_ADDRSTRLEN];
			snprintf(src, sizeof(src), "[%s]",
			    ip6_sprintf(ip6buf, &args->f_id.src_ip6));
			snprintf(dst, sizeof(dst), "[%s]",
			    ip6_sprintf(ip6buf, &args->f_id.dst_ip6));

			ip6 = (struct ip6_hdr *)ip;
			tcp = (struct tcphdr *)(((char *)ip) + hlen);
			udp = (struct udphdr *)(((char *)ip) + hlen);
		} else
#endif
		{
			tcp = L3HDR(struct tcphdr, ip);
			udp = L3HDR(struct udphdr, ip);

			inet_ntoa_r(ip->ip_src, src);
			inet_ntoa_r(ip->ip_dst, dst);
		}

		switch (args->f_id.proto) {
		case IPPROTO_TCP:
			len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
			if (offset == 0)
				snprintf(SNPARGS(proto, len), ":%d %s:%d",
				    ntohs(tcp->th_sport),
				    dst,
				    ntohs(tcp->th_dport));
			else
				snprintf(SNPARGS(proto, len), " %s", dst);
			break;

		case IPPROTO_UDP:
			len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
			if (offset == 0)
				snprintf(SNPARGS(proto, len), ":%d %s:%d",
				    ntohs(udp->uh_sport),
				    dst,
				    ntohs(udp->uh_dport));
			else
				snprintf(SNPARGS(proto, len), " %s", dst);
			break;

		case IPPROTO_ICMP:
			icmp = L3HDR(struct icmphdr, ip);
			if (offset == 0)
				len = snprintf(SNPARGS(proto, 0),
				    "ICMP:%u.%u ",
				    icmp->icmp_type, icmp->icmp_code);
			else
				len = snprintf(SNPARGS(proto, 0), "ICMP ");
			len += snprintf(SNPARGS(proto, len), "%s", src);
			snprintf(SNPARGS(proto, len), " %s", dst);
			break;
#ifdef INET6
		case IPPROTO_ICMPV6:
			icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
			if (offset == 0)
				len = snprintf(SNPARGS(proto, 0),
				    "ICMPv6:%u.%u ",
				    icmp6->icmp6_type, icmp6->icmp6_code);
			else
				len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
			len += snprintf(SNPARGS(proto, len), "%s", src);
			snprintf(SNPARGS(proto, len), " %s", dst);
			break;
#endif
		default:
			len = snprintf(SNPARGS(proto, 0), "P:%d %s",
			    args->f_id.proto, src);
			snprintf(SNPARGS(proto, len), " %s", dst);
			break;
		}

#ifdef INET6
		if (IS_IP6_FLOW_ID(&(args->f_id))) {
			if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
				snprintf(SNPARGS(fragment, 0),
				    " (frag %08x:%d@%d%s)",
				    args->f_id.extra,
				    ntohs(ip6->ip6_plen) - hlen,
				    ntohs(offset & IP6F_OFF_MASK) << 3,
				    (offset & IP6F_MORE_FRAG) ? "+" : "");
		} else
#endif
		{
			int ipoff, iplen;
			ipoff = ntohs(ip->ip_off);
			iplen = ntohs(ip->ip_len);
			if (ipoff & (IP_MF | IP_OFFMASK))
				snprintf(SNPARGS(fragment, 0),
				    " (frag %d:%d@%d%s)",
				    ntohs(ip->ip_id), iplen - (ip->ip_hl << 2),
				    offset << 3,
				    (ipoff & IP_MF) ? "+" : "");
		}
	}
#ifdef __FreeBSD__
	if (oif || m->m_pkthdr.rcvif)
		log(LOG_SECURITY | LOG_INFO,
		    "ipfw: %d %s %s %s via %s%s\n",
		    f ? f->rulenum : -1,
		    action, proto, oif ? "out" : "in",
		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
		    fragment);
	else
#endif
		log(LOG_SECURITY | LOG_INFO,
		    "ipfw: %d %s %s [no if info]%s\n",
		    f ? f->rulenum : -1,
		    action, proto, fragment);
	if (limit_reached)
		log(LOG_SECURITY | LOG_NOTICE,
		    "ipfw: limit %d reached on entry %d\n",
		    limit_reached, f ? f->rulenum : -1);
}
예제 #28
0
static void tcp_server_task(void *pvParameters)
{
    char rx_buffer[128];
    char addr_str[128];
    int addr_family;
    int ip_protocol;

    while (1) {

#ifdef CONFIG_EXAMPLE_IPV4
        struct sockaddr_in destAddr;
        destAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        destAddr.sin_family = AF_INET;
        destAddr.sin_port = htons(PORT);
        addr_family = AF_INET;
        ip_protocol = IPPROTO_IP;
        inet_ntoa_r(destAddr.sin_addr, addr_str, sizeof(addr_str) - 1);
#else // IPV6
        struct sockaddr_in6 destAddr;
        bzero(&destAddr.sin6_addr.un, sizeof(destAddr.sin6_addr.un));
        destAddr.sin6_family = AF_INET6;
        destAddr.sin6_port = htons(PORT);
        addr_family = AF_INET6;
        ip_protocol = IPPROTO_IPV6;
        inet6_ntoa_r(destAddr.sin6_addr, addr_str, sizeof(addr_str) - 1);
#endif

        int listen_sock = socket(addr_family, SOCK_STREAM, ip_protocol);
        if (listen_sock < 0) {
            ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket created");

        int err = bind(listen_sock, (struct sockaddr *)&destAddr, sizeof(destAddr));
        if (err != 0) {
            ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket binded");

        err = listen(listen_sock, 1);
        if (err != 0) {
            ESP_LOGE(TAG, "Error occured during listen: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket listening");

#ifdef CONFIG_EXAMPLE_IPV6
        struct sockaddr_in6 sourceAddr; // Large enough for both IPv4 or IPv6
#else
        struct sockaddr_in sourceAddr;
#endif
        uint addrLen = sizeof(sourceAddr);
        int sock = accept(listen_sock, (struct sockaddr *)&sourceAddr, &addrLen);
        if (sock < 0) {
            ESP_LOGE(TAG, "Unable to accept connection: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket accepted");

        while (1) {
            int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
            // Error occured during receiving
            if (len < 0) {
                ESP_LOGE(TAG, "recv failed: errno %d", errno);
                break;
            }
            // Connection closed
            else if (len == 0) {
                ESP_LOGI(TAG, "Connection closed");
                break;
            }
            // Data received
            else {
#ifdef CONFIG_EXAMPLE_IPV6
                // Get the sender's ip address as string
                if (sourceAddr.sin6_family == PF_INET) {
                    inet_ntoa_r(((struct sockaddr_in *)&sourceAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
                } else if (sourceAddr.sin6_family == PF_INET6) {
                    inet6_ntoa_r(sourceAddr.sin6_addr, addr_str, sizeof(addr_str) - 1);
                }
#else
                inet_ntoa_r(((struct sockaddr_in *)&sourceAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
#endif

                rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
                ESP_LOGI(TAG, "Received %d bytes from %s:", len, addr_str);
                ESP_LOGI(TAG, "%s", rx_buffer);

                int err = send(sock, rx_buffer, len, 0);
                if (err < 0) {
                    ESP_LOGE(TAG, "Error occured during sending: errno %d", errno);
                    break;
                }
            }
        }

        if (sock != -1) {
            ESP_LOGE(TAG, "Shutting down socket and restarting...");
            shutdown(sock, 0);
            close(sock);
        }
    }
    vTaskDelete(NULL);
}
예제 #29
0
static int
AliasHandleUdpNbt(
    struct libalias *la,
    struct ip *pip,		/* IP packet to examine/patch */
    struct alias_link *lnk,
    struct in_addr *alias_address,
    u_short alias_port
)
{
	struct udphdr *uh;
	NbtDataHeader *ndh;
	u_char *p = NULL;
	char *pmax;
#ifdef LIBALIAS_DEBUG
	char addrbuf[INET_ADDRSTRLEN];
#endif

	(void)la;
	(void)lnk;

	/* Calculate data length of UDP packet */
	uh = (struct udphdr *)ip_next(pip);
	pmax = (char *)uh + ntohs(uh->uh_ulen);

	ndh = (NbtDataHeader *)udp_next(uh);
	if ((char *)(ndh + 1) > pmax)
		return (-1);
#ifdef LIBALIAS_DEBUG
	printf("\nType=%02x,", ndh->type);
#endif
	switch (ndh->type) {
	case DGM_DIRECT_UNIQ:
	case DGM_DIRECT_GROUP:
	case DGM_BROADCAST:
		p = (u_char *) ndh + 14;
		p = AliasHandleName(p, pmax);	/* Source Name */
		p = AliasHandleName(p, pmax);	/* Destination Name */
		break;
	case DGM_ERROR:
		p = (u_char *) ndh + 11;
		break;
	case DGM_QUERY:
	case DGM_POSITIVE_RES:
	case DGM_NEGATIVE_RES:
		p = (u_char *) ndh + 10;
		p = AliasHandleName(p, pmax);	/* Destination Name */
		break;
	}
	if (p == NULL || (char *)p > pmax)
		p = NULL;
#ifdef LIBALIAS_DEBUG
	printf("%s:%d-->", inet_ntoa_r(ndh->source_ip, INET_NTOA_BUF(addrbuf)),
	    ntohs(ndh->source_port));
#endif
	/* Doing an IP address and Port number Translation */
	if (uh->uh_sum != 0) {
		int acc;
		u_short *sptr;

		acc = ndh->source_port;
		acc -= alias_port;
		sptr = (u_short *) & (ndh->source_ip);
		acc += *sptr++;
		acc += *sptr;
		sptr = (u_short *) alias_address;
		acc -= *sptr++;
		acc -= *sptr;
		ADJUST_CHECKSUM(acc, uh->uh_sum);
	}
	ndh->source_ip = *alias_address;
	ndh->source_port = alias_port;
#ifdef LIBALIAS_DEBUG
	printf("%s:%d\n", inet_ntoa_r(ndh->source_ip, INET_NTOA_BUF(addrbuf)),
	    ntohs(ndh->source_port));
	fflush(stdout);
#endif
	return ((p == NULL) ? -1 : 0);
}
예제 #30
0
파일: log.c 프로젝트: gelraen/userfw
/*
 * XXX: will not work correctly with IPv6 extension headers
 */
static void
log_packet(struct mbuf **mb, userfw_chk_args *args, userfw_action *a, userfw_cache *cache)
{
	char *dir = (args->dir == USERFW_IN) ? "in" : "out";
	char *proto, *ipproto;
	struct ip *ip = mtod(*mb, struct ip *);
	struct ip6_hdr *ip6 = mtod(*mb, struct ip6_hdr *);
	struct tcphdr *tcp = NULL;
	struct udphdr *udp = NULL;
	struct sctphdr *sctp = NULL;
	char action[USERFW_NAME_LEN+1] = {0};
	char src[64] = {0};
	char dst[64] = {0};
	char iface[IFNAMSIZ+1] = "UNKNOWN";
	int l4proto = -1;
	char ipproto_buf[4] = {0};
	char portbuf[16] = {0};
	uint16_t srcport, dstport;
	int have_ports = 0;

	switch(ip->ip_v)
	{
	case 4:
		proto = "IPv4";
		l4proto = ip->ip_p;
		inet_ntoa_r(ip->ip_src, src);
		inet_ntoa_r(ip->ip_dst, dst);
		tcp = L3HDR(struct tcphdr, ip);
		udp = L3HDR(struct udphdr, ip);
		sctp = L3HDR(struct sctphdr, ip);
		break;
	case 6:
		proto = "IPv6";
		l4proto = ip6->ip6_nxt;
		char buf[INET6_ADDRSTRLEN];
		snprintf(src, sizeof(src), "[%s]", ip6_sprintf(buf, &(ip6->ip6_src)));
		snprintf(dst, sizeof(dst), "[%s]", ip6_sprintf(buf, &(ip6->ip6_dst)));
		tcp = (struct tcphdr *)(((char *)ip6) + sizeof(struct ip6_hdr));
		udp = (struct udphdr *)(((char *)ip6) + sizeof(struct ip6_hdr));
		sctp = (struct sctphdr *)(((char *)ip6) + sizeof(struct ip6_hdr));
		break;
	default:
		proto = "UNKNOWN_L3";
		break;
	}

	switch(l4proto)
	{
	case -1:
		ipproto = "UNKNOWN_L4";
		break;
	case IPPROTO_TCP:
		ipproto = "TCP";
		srcport = tcp->th_sport;
		dstport = tcp->th_dport;
		have_ports = 1;
		break;
	case IPPROTO_UDP:
		ipproto = "UDP";
		srcport = udp->uh_sport;
		dstport = udp->uh_dport;
		have_ports = 1;
		break;
	case IPPROTO_SCTP:
		ipproto = "SCTP";
		srcport = sctp->src_port;
		dstport = sctp->dest_port;
		have_ports = 1;
		break;
	case IPPROTO_ICMP:
		ipproto = "ICMP";
		break;
	default:
		sprintf(ipproto_buf, "%d", l4proto & 0xff);
		ipproto = ipproto_buf;
		break;
	}

	if (have_ports)
	{
		snprintf(portbuf, sizeof(portbuf), ":%u", ntohs(srcport));
		strlcat(src, portbuf, sizeof(src));
		snprintf(portbuf, sizeof(portbuf), ":%u", ntohs(dstport));
		strlcat(dst, portbuf, sizeof(dst));
	}

	if (args->ifp != NULL)
	{
		bcopy(args->ifp->if_xname, iface, IFNAMSIZ);
	}

	if (a != NULL)
	{
		const userfw_action_descr *descr = userfw_mod_find_action(a->mod, a->op);
		if (descr != NULL)
		{
			bcopy(descr->name, action, USERFW_NAME_LEN);
		}
	}

	log(LOG_SECURITY | LOG_INFO, "userfw: %s %s %s %s %s %s via %s\n", action, proto, ipproto, src, dst, dir, iface);
}