void layer3(char *layer3p, uint16_t type) {
	struct arp_hdr *arpheader;
	struct ip_hdr *ipheader;

	switch(type){
		case ETH_TYPE_IP:
			ipheader = (struct ip_hdr *) layer3p;
			printf("	IP\n");
			printf("	IP len = %d\n", ipheader->ip_hl*4);
			printf("	IP src = %s\n", ip_ntoa(&ipheader->ip_src));
			printf("	IP dst = %s\n", ip_ntoa(&ipheader->ip_dst));
			layer4(layer3p+(ipheader->ip_hl*4),ipheader->ip_p);
			break;
		case ETH_TYPE_ARP:
			arpheader = (struct arp_hdr *) layer3p;
			printf("	ARP\n");
			if(arpheader->ar_op == 1)
				printf("	ARP Operation = ARP_OP_REQUEST\n");
			else if (arpheader->ar_op == 2)
				printf("	ARP Operation = ARP_OP_REPLY\n");
			else if (arpheader->ar_op == 3)
				printf("	ARP Operation = ARP_OP_REVREQUEST\n");
			else if (arpheader->ar_op == 4)
				printf("	ARP Operation = ARP_OP_REVREPLY\n");
			break;
		default:
			printf("	OTHER\n");
			break;
	}
}
Example #2
0
static void
_print_ip(u_char *p, int length)
{
	struct ip_hdr *ip;
	u_int ip_off, ip_hl, ip_len;
	
	ip = (struct ip_hdr *)p;
	
	if (length < IP_HDR_LEN) {
		printf("truncated-ip %d", length);
		return;
	}
	ip_hl = ip->ip_hl * 4;
	ip_len = ntohs(ip->ip_len);
	
	if (length < ip_len) {
		printf("truncated-ip - %d bytes missing!", ip_len - length);
		return;
	}
	ip_off = ntohs(ip->ip_off);
	
	/* Handle first fragment. */
	if ((ip_off & IP_OFFMASK) == 0) {
		switch (ip->ip_p) {
		case IP_PROTO_TCP:
			_print_tcp(AF_INET, p, ip_len);
			break;
		case IP_PROTO_UDP:
			_print_udp(AF_INET, p, ip_len);
			break;
		case IP_PROTO_ICMP:
			_print_icmp(p, ip_len);
			break;
		default:
			printf("%s > %s:", ip_ntoa(&ip->ip_src),
			    ip_ntoa(&ip->ip_dst));
			printf(" ip-proto-%d %d", ip->ip_p, ip_len);
			break;
		}
	}
	/* Handle more frags. */
	if (ip_off & (IP_MF|IP_OFFMASK)) {
		if (ip_off & IP_OFFMASK)
			printf("%s > %s:", ip_ntoa(&ip->ip_src),
			    ip_ntoa(&ip->ip_dst));
		printf(" (frag %d:%d@%d%s)", ntohs(ip->ip_id), ip_len - ip_hl,
		    (ip_off & IP_OFFMASK) << 3, (ip_off & IP_MF) ? "+" : "");
	} else if (ip_off & IP_DF)
		printf(" (DF)");
	
	if (ip->ip_tos)
		printf(" [tos 0x%x]", ip->ip_tos);
	if (ip->ip_ttl <= 1)
		printf(" [ttl %d]", ip->ip_ttl);
}
Example #3
0
void
pppLinkStatusCallback(void *ctx, int errCode, void *arg)
{
  LWIP_UNUSED_ARG(ctx);

  switch(errCode) {
    case PPPERR_NONE: {             /* No error. */
      struct ppp_addrs *ppp_addrs = arg;

      printf("pppLinkStatusCallback: PPPERR_NONE\n");
      printf(" our_ipaddr=%s\n", ip_ntoa(&ppp_addrs->our_ipaddr));
      printf(" his_ipaddr=%s\n", ip_ntoa(&ppp_addrs->his_ipaddr));
      printf(" netmask   =%s\n", ip_ntoa(&ppp_addrs->netmask));
      printf(" dns1      =%s\n", ip_ntoa(&ppp_addrs->dns1));
      printf(" dns2      =%s\n", ip_ntoa(&ppp_addrs->dns2));
      break;
    }
    case PPPERR_PARAM: {           /* Invalid parameter. */
      printf("pppLinkStatusCallback: PPPERR_PARAM\n");
      break;
    }
    case PPPERR_OPEN: {            /* Unable to open PPP session. */
      printf("pppLinkStatusCallback: PPPERR_OPEN\n");
      break;
    }
    case PPPERR_DEVICE: {          /* Invalid I/O device for PPP. */
      printf("pppLinkStatusCallback: PPPERR_DEVICE\n");
      break;
    }
    case PPPERR_ALLOC: {           /* Unable to allocate resources. */
      printf("pppLinkStatusCallback: PPPERR_ALLOC\n");
      break;
    }
    case PPPERR_USER: {            /* User interrupt. */
      printf("pppLinkStatusCallback: PPPERR_USER\n");
      break;
    }
    case PPPERR_CONNECT: {         /* Connection lost. */
      printf("pppLinkStatusCallback: PPPERR_CONNECT\n");
      break;
    }
    case PPPERR_AUTHFAIL: {        /* Failed authentication challenge. */
      printf("pppLinkStatusCallback: PPPERR_AUTHFAIL\n");
      break;
    }
    case PPPERR_PROTOCOL: {        /* Failed to meet protocol. */
      printf("pppLinkStatusCallback: PPPERR_PROTOCOL\n");
      break;
    }
    default: {
      printf("pppLinkStatusCallback: unknown errCode %d\n", errCode);
      break;
    }
  }
}
int nk_pppoe_conn_up(u_int32_t hisaddr, char *nk_iprange)
{
	char buf[512],cmdBuf[512],times[32];
	int i=0;
		
    if(!nk_checkip(hisaddr, nk_iprange))
    {
		return 1;
	}

	nk_GetClientStatuslink(1);
	nk_GetClientInfolink(1);
	nk_GetIPInfolink(1);
	nk_GetServerInfolink(1);
	
	ClientStatus[UserIdx].Conn = ClientStatus[UserIdx].Conn + 1;
		
	for(i=0; i< ServerInfo->MaxConnClient; i++)
	{
		if(ClientConn[i].SaveData == 0)
		{
			ClientConn[i].SaveData = 1;
			nk_PeerConnClientIdx = i;
			break;
		}
	}
	
	sprintf(ClientConn[nk_PeerConnClientIdx].username, "%s", peer_authname);		
	sprintf(ClientConn[nk_PeerConnClientIdx].eth, "%s", remote_number);
	sprintf(ClientConn[nk_PeerConnClientIdx].ifname, "%s", ifname);
	ClientConn[nk_PeerConnClientIdx].pid = getpid();
	
	IPInfoTable[nk_PeerIPInfoIdx].IsUsed = 1;
	
	nk_DisconnServerInfolink();
	nk_DisconnClientStatuslink();
	nk_DisconnClientInfolink();
	nk_DisconnIPInfolink();
	
	nk_displaySharedMemData();
	
	nk_pppoe_gettime(times);

	sprintf(cmdBuf,"echo \"ID=%d&MAC=%s&NAME=%s&IP=%s&PID=%d&STARTTIME=%s&IFNAME=%s&SESS=%d&\" > %s",
			getpid(), remote_number, peer_authname, ip_ntoa(hisaddr), getpid(), times, ifname, req_unit, NKPPPOE_FIFO1_IPC);
	system(cmdBuf);
	
	/* sprintf(buf,"(PPPoE Server) User %s connection success, ip=[%s], MAC=[%s]",peer_authname,ip_ntoa(hisaddr),remote_number);
	 NK_LOG_PPPoE(LOG_WARNING,buf); */
	info("connection success, User=[%s], ip=[%s], MAC=[%s]", peer_authname, ip_ntoa(hisaddr), remote_number);
	return 0;
}
Example #5
0
static void
_print_icmp(u_char *p, int length)
{
	struct ip_hdr *ip;
	struct icmp_hdr *icmp;
	
	ip = (struct ip_hdr *)p;
	icmp = (struct icmp_hdr *)(p + (ip->ip_hl * 4));

	/* XXX - truncation? */
	printf("%s > %s:", ip_ntoa(&ip->ip_src), ip_ntoa(&ip->ip_dst));
	printf(" icmp: type %d code %d", icmp->icmp_type, icmp->icmp_code);
}
Example #6
0
File: fw.c Project: r-mite/nat
void printIPHeader(u_char *buf) {
	struct iphdr *ptr;
	ptr = (struct iphdr *)buf;
	printf("----------- IP -----------\n");
	printf("version=%u\n", ptr->version);
	printf("ihl=%u\n", ptr->ihl);
	printf("tos=%x\n", ptr->tos);
	printf("tot_len=%u\n", ntohs(ptr->tot_len));
	printf("id=%u\n", ntohs(ptr->id));
	printf("ttl=%u\n", ptr->ttl);
	printf("protocol=%u\n", ptr->protocol);
	printf("src addr=%s\n", ip_ntoa(ptr->saddr));
	printf("dst addr=%s\n", ip_ntoa(ptr->daddr));
}
Example #7
0
/* Dumps crawler nodes list to log file. */
static int crawler_dump_log(Crawler *cwl)
{
    char log_path[PATH_MAX];
    if (get_log_path(log_path, sizeof(log_path)) == -1) {
        return -1;
    }

    char log_path_temp[strlen(log_path) + strlen(TEMP_FILE_EXT) + 1];
    snprintf(log_path_temp, sizeof(log_path_temp), "%s%s", log_path, TEMP_FILE_EXT);

    FILE *fp = fopen(log_path_temp, "w");

    if (fp == NULL) {
        return -2;
    }

    LOCK;   // ip_ntoa() isn't thread safe
    for (uint32_t i = 0; i < cwl->num_nodes; ++i) {
        fprintf(fp, "%s ", ip_ntoa(&cwl->nodes_list[i].ip_port.ip));
    }
    UNLOCK;

    fclose(fp);

    if (rename(log_path_temp, log_path) != 0) {
        return -3;
    }

    return 0;
}
/**
 * Returns an entry containing addresses of address family AF_INET
 * for the host with name name.
 * Due to dns_gethostbyname limitations, only one address is returned.
 *
 * @param name the hostname to resolve
 * @return an entry containing addresses of address family AF_INET
 *         for the host with name name
 */
struct hostent*
lwip_gethostbyname(const char *name)
{
  err_t err;
  ip_addr_t addr;

  /* buffer variables for lwip_gethostbyname() */
  HOSTENT_STORAGE struct hostent s_hostent;
  HOSTENT_STORAGE char *s_aliases;
  HOSTENT_STORAGE ip_addr_t s_hostent_addr;
  HOSTENT_STORAGE ip_addr_t *s_phostent_addr[2];

  /* query host IP address */
  err = netconn_gethostbyname(name, &addr);
  if (err != ERR_OK) {
    LWIP_DEBUGF(DNS_DEBUG, ("lwip_gethostbyname(%s) failed, err=%d\n", name, err));
    h_errno = HOST_NOT_FOUND;
    return NULL;
  }

  /* fill hostent */
  s_hostent_addr = addr;
  s_phostent_addr[0] = &s_hostent_addr;
  s_phostent_addr[1] = NULL;
  s_hostent.h_name = (char*)name;
  s_hostent.h_aliases = &s_aliases;
  s_hostent.h_addrtype = AF_INET;
  s_hostent.h_length = sizeof(ip_addr_t);
  s_hostent.h_addr_list = (char**)&s_phostent_addr;

#if DNS_DEBUG
  /* dump hostent */
  LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_name           == %s\n", s_hostent.h_name));
  LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_aliases        == %p\n", s_hostent.h_aliases));
  if (s_hostent.h_aliases != NULL) {
    u8_t idx;
    for ( idx=0; s_hostent.h_aliases[idx]; idx++) {
      LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_aliases[%i]->   == %p\n", idx, s_hostent.h_aliases[idx]));
      LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_aliases[%i]->   == %s\n", idx, s_hostent.h_aliases[idx]));
    }
  }
  LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addrtype       == %d\n", s_hostent.h_addrtype));
  LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_length         == %d\n", s_hostent.h_length));
  LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list      == %p\n", s_hostent.h_addr_list));
  if (s_hostent.h_addr_list != NULL) {
    u8_t idx;
    for ( idx=0; s_hostent.h_addr_list[idx]; idx++) {
      LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list[%i]   == %p\n", idx, s_hostent.h_addr_list[idx]));
      LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list[%i]-> == %s\n", idx, ip_ntoa((ip_addr_t*)s_hostent.h_addr_list[idx])));
    }
  }
#endif /* DNS_DEBUG */

#if LWIP_DNS_API_HOSTENT_STORAGE
  /* this function should return the "per-thread" hostent after copy from s_hostent */
  return sys_thread_hostent(&s_hostent);
#else
  return &s_hostent;
#endif /* LWIP_DNS_API_HOSTENT_STORAGE */
}
Example #9
0
void status_callback(struct netif *netif)
{
  if (netif_is_up(netif)) {
    printf("status_callback==UP, local interface IP is %s\n", ip_ntoa(&netif->ip_addr));
  } else {
    printf("status_callback==DOWN\n");
  }
}
Example #10
0
static char *packettoa(char *result,unsigned char *packet, int len)
{
	struct iphdr *iph = (struct iphdr*)packet;
	char nbuf1[40], nbuf2[40];
	if (verbose && iph->protocol == IPPROTO_TCP) {
		struct tcphdr *tcph = (struct tcphdr*) (packet + 4 * iph->ihl);
		sprintf(result,"proto=%s %d byte packet seq=%u ack=%u id=%u frag=%u from %s:%d to %s:%d",
			ip_proto_name(iph->protocol), len, tcph->seq, tcph->ack_seq,
			iph->id, iph->frag_off,
			ip_ntoa(iph->saddr,nbuf1),tcph->source,
			ip_ntoa(iph->daddr,nbuf2),tcph->dest);
	} else {
		sprintf(result,"proto=%s %d byte packet from %s to %s",
			ip_proto_name(iph->protocol), len,
			ip_ntoa(iph->saddr,nbuf1),
			ip_ntoa(iph->daddr,nbuf2));
	}
	return result;
}
Example #11
0
// If this is a duplicate TCP packet, throw it away.
// The MS is so slow to respond that the servers often send dups
// which are unnecessary because we have reliable communication between here
// and the MS, so just toss them.
// Update 3-2012: Always do the check to print messages for dup packets even if not discarded.
static int mg_toss_dup_packet(mg_con_t*mgp,unsigned char *packet, int packetlen)
{
	struct iphdr *iph = (struct iphdr*)packet;
	if (iph->protocol != IPPROTO_TCP) { return 0; }
	struct tcphdr *tcph = (struct tcphdr*) (packet + 4 * iph->ihl);
	if (tcph->rst | tcph->urg) { return 0; }
	int i;
	for (i = 0; i < MG_PACKET_HISTORY; i++) {
		// 3-2012: Jpegs are not going through the system properly.
		// I am adding some more checks here to see if we are tossing packets inappropriately.
		// The tot_len includes headers, but if they are not the same in the duplicate packet, oh well.
		// TODO: If the connection is reset we should zero out our history.
		if (mgp->mg_packets[i].saddr == iph->saddr &&
		    mgp->mg_packets[i].daddr == iph->daddr &&
		    mgp->mg_packets[i].totlen == iph->tot_len &&
		    //mgp->mg_packets[i].ipfragoff == iph->frag_off &&
		    //mgp->mg_packets[i].ipid == iph->id &&
		    mgp->mg_packets[i].seq == tcph->seq &&
		    mgp->mg_packets[i].source == tcph->source &&
		    mgp->mg_packets[i].dest == tcph->dest
			) {
				const char *what = ggConfig.mgIpTossDup ? "discarding " : "";
				char buf1[40],buf2[40];
				MGINFO("ggsn: %sduplicate %d byte packet seq=%d frag=%d id=%d src=%s:%d dst=%s:%d",what,
					packetlen,tcph->seq,iph->frag_off,iph->id,
					ip_ntoa(iph->saddr,buf1),tcph->source,
					ip_ntoa(iph->daddr,buf2),tcph->dest);
				return ggConfig.mgIpTossDup;	// Toss duplicate tcp packet if option set.
			}
	}
	i = mgp->mg_oldest_packet;
	if (++mgp->mg_oldest_packet >= MG_PACKET_HISTORY) { mgp->mg_oldest_packet = 0; }
	mgp->mg_packets[i].saddr = iph->saddr;
	mgp->mg_packets[i].daddr = iph->daddr;
	mgp->mg_packets[i].totlen = iph->tot_len;
	//mgp->mg_packets[i].ipfragoff = iph->frag_off;
	//mgp->mg_packets[i].ipid = iph->id;
	mgp->mg_packets[i].seq = tcph->seq;
	mgp->mg_packets[i].source = tcph->source;
	mgp->mg_packets[i].dest = tcph->dest;
	return 0;	// Do not toss.
}
Example #12
0
static const char *getsecret(uint32_t server)
{
	RADCLIENT *cl;

	cl = client_find(server);
	if (cl == NULL) {
		char buf[32];
		radlog(L_ERR|L_CONS, "No clients entry for %s",
		       ip_ntoa(buf,server));
		exit(1);
	}
	return (const char *)cl->secret;
}
Example #13
0
char* sock_peer_name(int fd, char* addrbuf, int* port)
{
    struct sockaddr_in sockinfo;
    struct in_addr     address;
    socklen_t          sockinfosize = sizeof(sockinfo);

    // Get the peer address for the client socket
    getpeername(fd, (struct sockaddr *)&sockinfo, &sockinfosize);
    memcpy(&address, &sockinfo.sin_addr, sizeof(address));
    if(port) *port = sockinfo.sin_port;

    return ip_ntoa(addrbuf, address.s_addr);
}
Example #14
0
int tcp_connect(const char *host, int port)
{
    SOCKET sockfd;
    struct sockaddr_in servaddr;
    char ipbuf[16];

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        log_socket_error(L_ERROR|L_CONS, "[tcp_connect] "
                         "socket() failed for %s, %d",
                         host, port);
        return -1;
    }

    memset(&servaddr, 0, sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = ip_getaddr(host);

    if(servaddr.sin_addr.s_addr == htonl(INADDR_NONE)) {
        radlog(L_ERROR|L_CONS, "[tcp_connect] "
               "invalid host %s", host);
        closesocket(sockfd);
        return -1;
    }

    if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR) {
        log_socket_error(L_ERROR|L_CONS, "[tcp_connect] "
                         "connect() failed for %s (%s), %d",
                         host, ip_ntoa(ipbuf, servaddr.sin_addr.s_addr), port);
        closesocket(sockfd);
        return -1;
    }

    DEBUG("[tcp_connect] %s (%s:%d), got sockfd(%d)", host,
          ip_ntoa(ipbuf, servaddr.sin_addr.s_addr), port, sockfd);

    return sockfd;
}
Example #15
0
int sysnet_interface_set_addr(VPNInterface *i)
{
    int err;

    struct nl_cache *link_cache;
    struct nl_sock *sock;
    struct rtnl_addr *addr;
    struct rtnl_link *link;
    struct nl_addr *local_addr;

    sock = nl_socket_alloc();
    nl_connect(sock, NETLINK_ROUTE);

    rtnl_link_alloc_cache(sock, AF_UNSPEC, &link_cache);

    addr = rtnl_addr_alloc();
    link = rtnl_link_get_by_name(link_cache, i->name);
    local_addr = nl_addr_build(i->address.ip.family, &i->address.ip.ip4, sizeof(i->address.ip.ip4));

    rtnl_addr_set_local(addr, local_addr);
    rtnl_addr_set_family(addr, i->address.ip.family);
    rtnl_addr_set_prefixlen(addr, i->address.prefix);
    rtnl_addr_set_link(addr, link);

    if ((err = rtnl_addr_add(sock, addr, 0)) < 0) {
        tox_trace(i->context->tox, "Unable to add address %s on %s: %s", ip_ntoa(&i->address.ip), rtnl_link_get_name(link), nl_geterror(err));
    }
    else {
        tox_trace(i->context->tox, "Added address %s on \"%s\"", ip_ntoa(&i->address.ip), i->name);
    }

    rtnl_link_put(link);
    rtnl_addr_put(addr);
    nl_cache_free(link_cache);
    nl_addr_put(local_addr);
    nl_socket_free(sock);

    return err;
}
Example #16
0
File: main.c Project: DINKIN/bertos
int main(void)
{
	struct netconn *server;

	/* Hardware initialization */
	init();

	proc_new(monitor_process, NULL, KERN_MINSTACKSIZE * 2, NULL);

	dhcp_start(&netif);
	/*
	 * Here we wait for an ip address, but it's not strictly
	 * necessary. The address is obtained in background and
	 * as long as we don't use network functions, we could go
	 * on with initialization
	 */
	while (!netif.ip_addr.addr)
		timer_delay(200);
	kprintf(">>> dhcp ok: ip = ip = %s (kernel %s)\n",
		ip_ntoa(&netif.ip_addr.addr),
		CONFIG_KERN_PREEMPT ? "preempt" : "coop");

	server = netconn_new(NETCONN_TCP);
	netconn_bind(server, IP_ADDR_ANY, 80);
	netconn_listen(server);

	while (1)
	{
		struct netconn *client;
		struct netbuf *rx_buf_conn;
		char *rx_buf;
		u16_t len;

		client = netconn_accept(server);
		if (!client)
			continue;

		tot_req++;
		rx_buf_conn = netconn_recv(client);
		if (rx_buf_conn)
		{
			netbuf_data(rx_buf_conn, (void **)&rx_buf, &len);
			if (rx_buf)
				netconn_write(client, rx_buf, len, NETCONN_COPY);
			netbuf_delete(rx_buf_conn);
		}
		while (netconn_delete(client) != ERR_OK)
			cpu_relax();
	}
}
Example #17
0
void addShellRequest(const char *wCmd,GmmInfo*gmm,PdpContext *pdp)
{
	ShellRequest *req = new ShellRequest();
	req->msrCommand = wCmd;
	req->msrArg1 = gmm->mImsi.hexstr();
	if (pdp && pdp->mgp) {
		char ipaddr[40], nsapi[10];
		ip_ntoa(pdp->mgp->mg_ip, ipaddr);
		req->msrArg2 = ipaddr;
		sprintf(nsapi,"%d",pdp->mNSapi);
		req->msrArg3 = nsapi;
	}
	gGgsn.mShellQ.write(req);
}
Example #18
0
/* rt netlink dump function */
void rt_dump(struct rt_entry *r)
{
	while (r) {
		if (r->src) printf("src %s ", ip_ntoa(r->src));
		if (r->psrc) printf("prefsrc %s ", ip_ntoa(r->psrc));
		if (r->iif) printf("idev %s", ll_index_to_name(r->iif));

		if (r->dest) printf("dest %s ", ip_ntoa(r->dest));
		if (r->gate) printf("gateway %s ", ip_ntoa(r->gate));

		if (r->prio) printf("priority %d ", r->prio);
		if (r->metrics) printf("metrics %d ", r->metrics);

		if (r->oif) printf("odev %s ", ll_index_to_name(r->oif));

		/* rtmsg specifics */
		if (r->rtm->rtm_dst_len) printf("mask %d ", r->rtm->rtm_dst_len);
		if (r->rtm->rtm_scope == RT_SCOPE_LINK) printf("scope link");

		printf("\n");

		r = (struct rt_entry *)r->next;
	}
}
Example #19
0
static void loglogdata(char *message, uint8_t *buffer, size_t buflen, IP_Port *ip_port, ssize_t res)
{
    uint16_t port = ntohs(ip_port->port);
    uint32_t data[2];
    data[0] = buflen > 4 ? ntohl(*(uint32_t *)&buffer[1]) : 0;
    data[1] = buflen > 7 ? ntohl(*(uint32_t *)&buffer[5]) : 0;
    if (res < 0)
    {
        int written = snprintf(logbuffer, sizeof(logbuffer), "[%2u] %s %3hu%c %s:%hu (%u: %s) | %04x%04x\n",
                 buffer[0], message, (buflen < 999 ? (uint16_t)buflen : 999), 'E',
                 ip_ntoa(&ip_port->ip), port, errno, strerror(errno), data[0], data[1]);
    }
    else if ((res > 0) && ((size_t)res <= buflen))
        snprintf(logbuffer, sizeof(logbuffer), "[%2u] %s %3zu%c %s:%hu (%u: %s) | %04x%04x\n",
                 buffer[0], message, (res < 999 ? (size_t)res : 999), ((size_t)res < buflen ? '<' : '='),
                 ip_ntoa(&ip_port->ip), port, 0, errmsg_ok, data[0], data[1]);
    else /* empty or overwrite */
        snprintf(logbuffer, sizeof(logbuffer), "[%2u] %s %zu%c%zu %s:%hu (%u: %s) | %04x%04x\n",
                 buffer[0], message, (size_t)res, (!res ? '!' : '>'), buflen,
                 ip_ntoa(&ip_port->ip), port, 0, errmsg_ok, data[0], data[1]);

    logbuffer[sizeof(logbuffer) - 1] = 0;
    loglog(logbuffer);
}
Example #20
0
vector<string> getip(const char *host)
{
    vector<string> result;
    vector<unsigned long> addrs = getSockAddr(host);
    if (0 == addrs.size()) {
        fprintf (stderr, "warn: %s:%d getSockAddr %s\n", __FILE__, __LINE__, host);
    } else {
        for (int i = 0; i < addrs.size(); i++) {
            char ipstring[16] = {'\0'};
            if (0 == ip_ntoa(addrs[i], ipstring, 16)) {
                result.push_back(ipstring);
            }
        }
    }
    return result;
}
Example #21
0
/** Prepare HELO/EHLO message */
static enum smtp_session_state
smtp_prepare_helo(struct smtp_session *s, u16_t *tx_buf_len, struct tcp_pcb *pcb)
{
  size_t ipa_len;
  char *ipa = ip_ntoa(&pcb->local_ip);
  LWIP_ASSERT("ip_ntoa returned NULL", ipa != NULL);
  ipa_len = strlen(ipa);
  LWIP_ASSERT("string too long", ipa_len <= 0xffff);

  *tx_buf_len = SMTP_CMD_EHLO_1_LEN + (u16_t)ipa_len + SMTP_CMD_EHLO_2_LEN;
  LWIP_ASSERT("tx_buf overflow detected", *tx_buf_len <= SMTP_TX_BUF_LEN);

  SMEMCPY(s->tx_buf, SMTP_CMD_EHLO_1, SMTP_CMD_EHLO_1_LEN);
  MEMCPY(&s->tx_buf[SMTP_CMD_EHLO_1_LEN], ipa, ipa_len);
  SMEMCPY(&s->tx_buf[SMTP_CMD_EHLO_1_LEN + ipa_len], SMTP_CMD_EHLO_2, SMTP_CMD_EHLO_2_LEN);
  return SMTP_HELO;
}
Example #22
0
static int handle_LANdiscovery(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata)
{
    DHT *dht = (DHT *)object;

    char ip_str[IP_NTOA_LEN] = { 0 };
    ip_ntoa(&source.ip, ip_str, sizeof(ip_str));

    if (ip_is_lan(source.ip) == -1) {
        return 1;
    }

    if (length != CRYPTO_PUBLIC_KEY_SIZE + 1) {
        return 1;
    }

    DHT_bootstrap(dht, source, packet + 1);
    return 0;
}
Example #23
0
int dnsclient_main(int argc, FAR char *argv[])
#endif
{
	struct hostent *shost = NULL;
	ip_addr_t dns_addr;

	if (argc < 2) {
		show_usage(argv[0]);
		return 0;
	}

	if (argc == 3 && argv[2] != NULL) {
		printf("dnsclient : dns_add_nameserver : %s\n", argv[2]);
		IP_SET_TYPE_VAL(dns_addr, IPADDR_TYPE_V4);
#ifdef CONFIG_NET_IPv6
		dns_addr.u_addr.ip4.addr = inet_addr(argv[2]);
#else
		dns_addr.addr = inet_addr(argv[2]);
#endif /* CONFIG_NET_IPv6 */
		dns_setserver(0, &dns_addr);
	}

	memset(hostname, 0x00, DNS_NAME_MAXSIZE);

	if (strlen(argv[1]) > DNS_NAME_MAXSIZE) {
		printf("dnsclient : length of hostname has to lower than %d\n", DNS_NAME_MAXSIZE);
		return -1;
	}

	strncpy(hostname, argv[1], DNS_NAME_MAXSIZE);
	printf("\nHostname : %s [len %d]\n", hostname, strlen(hostname));

	if ((shost = gethostbyname(hostname)) == NULL || shost->h_addr_list == NULL) {
		printf("dnsclient : failed to resolve host's IP address, shost %p\n", shost);
		return -1;
	} else {
		printf("DNS results\n");
		printf("IP Address : %s\n", ip_ntoa((ip_addr_t *)shost->h_addr_list[0]));
	}

	return 0;
}
Example #24
0
// There is data available on the socket.  Go get it.
// see handle_nsip_read()
void miniggsn_handle_read()
{
	int packetlen;
	uint32_t dstaddr;
	unsigned char *packet = miniggsn_rcv_npdu(&packetlen, &dstaddr);
	if (!packet) { return; }

	// We need to reassociate the packet with the PdpContext to which it belongs.
	mg_con_t *mgp = mg_con_find_by_ip(dstaddr);
	if (mgp == NULL || mgp->mg_pdp == NULL) {
		MGERROR("ggsn: error: cannot find PDP context for incoming packet for IP dstaddr=%s",
			ip_ntoa(dstaddr,NULL));
		return;	// -1;
	}

	if (mg_toss_dup_packet(mgp,packet,packetlen)) { return; }

	PdpContext *pdp = mgp->mg_pdp;
	//MGDEBUG(2,"miniggsn_handle_read pdp=%p",pdp);
	pdp->pdpWriteHighSide(packet,packetlen);
}
Example #25
0
void dns_found(const char *name, ip_addr_t *addr, void *arg)
{
  LWIP_UNUSED_ARG(arg);
  printf("%s: %s\n", name, addr ? ip_ntoa(addr) : "<not found>");
}
Example #26
0
/* Initialize networking.
 * Bind to ip and port.
 * ip must be in network order EX: 127.0.0.1 = (7F000001).
 * port is in host byte order (this means don't worry about it).
 *
 *  return Networking_Core object if no problems
 *  return NULL if there are problems.
 */
Networking_Core *new_networking(IP ip, uint16_t port)
{
#ifdef TOX_ENABLE_IPV6

    /* maybe check for invalid IPs like 224+.x.y.z? if there is any IP set ever */
    if (ip.family != AF_INET && ip.family != AF_INET6) {
#ifdef DEBUG
        fprintf(stderr, "Invalid address family: %u\n", ip.family);
#endif
        return NULL;
    }

#endif

    if (at_startup() != 0)
        return NULL;

    Networking_Core *temp = calloc(1, sizeof(Networking_Core));

    if (temp == NULL)
        return NULL;

#ifdef TOX_ENABLE_IPV6
    temp->family = ip.family;
#else
    temp->family = AF_INET;
#endif
    temp->port = 0;

    /* Initialize our socket. */
    /* add log message what we're creating */
    temp->sock = socket(temp->family, SOCK_DGRAM, IPPROTO_UDP);

    /* Check for socket error. */
#ifdef WIN32

    if (temp->sock == INVALID_SOCKET) { /* MSDN recommends this. */
        free(temp);
        return NULL;
    }

#else

    if (temp->sock < 0) {
#ifdef DEBUG
        fprintf(stderr, "Failed to get a socket?! %u, %s\n", errno, strerror(errno));
#endif
        free(temp);
        return NULL;
    }

#endif

    /* Functions to increase the size of the send and receive UDP buffers.
     */
    int n = 1024 * 1024 * 2;
    setsockopt(temp->sock, SOL_SOCKET, SO_RCVBUF, (char *)&n, sizeof(n));
    setsockopt(temp->sock, SOL_SOCKET, SO_SNDBUF, (char *)&n, sizeof(n));

    /* Enable broadcast on socket */
    int broadcast = 1;
    setsockopt(temp->sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast));

    /* Set socket nonblocking. */
#ifdef WIN32
    /* I think this works for Windows. */
    u_long mode = 1;
    /* ioctl(sock, FIONBIO, &mode); */
    ioctlsocket(temp->sock, FIONBIO, &mode);
#else
    fcntl(temp->sock, F_SETFL, O_NONBLOCK, 1);
#endif

    /* Bind our socket to port PORT and the given IP address (usually 0.0.0.0 or ::) */
    uint16_t *portptr = NULL;
    struct sockaddr_storage addr;
    size_t addrsize;
#ifdef TOX_ENABLE_IPV6

    if (temp->family == AF_INET) {
        IP4 ip4 = ip.ip4;
#else
    IP4 ip4 = ip;
#endif
        addrsize = sizeof(struct sockaddr_in);
        struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr;
        addr4->sin_family = AF_INET;
        addr4->sin_port = 0;
        addr4->sin_addr = ip4.in_addr;

        portptr = &addr4->sin_port;
#ifdef TOX_ENABLE_IPV6
    } else if (temp->family == AF_INET6)
    {
        addrsize = sizeof(struct sockaddr_in6);
        struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr;
        addr6->sin6_family = AF_INET6;
        addr6->sin6_port = 0;
        addr6->sin6_addr = ip.ip6.in6_addr;

        addr6->sin6_flowinfo = 0;
        addr6->sin6_scope_id = 0;

        portptr = &addr6->sin6_port;
    } else
        return NULL;

    if (ip.family == AF_INET6)
    {
        char ipv6only = 0;
#ifdef LOGGING
        errno = 0;
        int res =
#endif
            setsockopt(temp->sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&ipv6only, sizeof(ipv6only));
#ifdef LOGGING

        if (res < 0) {
            sprintf(logbuffer,
                    "Failed to enable dual-stack on IPv6 socket, won't be able to receive from/send to IPv4 addresses. (%u, %s)\n",
                    errno, strerror(errno));
            loglog(logbuffer);
        } else
            loglog("Embedded IPv4 addresses enabled successfully.\n");

#endif

        /* multicast local nodes */
        struct ipv6_mreq mreq;
        memset(&mreq, 0, sizeof(mreq));
        mreq.ipv6mr_multiaddr.s6_addr[ 0] = 0xFF;
        mreq.ipv6mr_multiaddr.s6_addr[ 1] = 0x02;
        mreq.ipv6mr_multiaddr.s6_addr[15] = 0x01;
        mreq.ipv6mr_interface = 0;
#ifdef LOGGING
        errno = 0;
        res =
#endif
            setsockopt(temp->sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq));
#ifdef LOGGING

        if (res < 0) {
            sprintf(logbuffer, "Failed to activate local multicast membership. (%u, %s)\n",
                    errno, strerror(errno));
            loglog(logbuffer);
        } else
            loglog("Local multicast group FF02::1 joined successfully.\n");

#endif
    }

#endif

    /* a hanging program or a different user might block the standard port;
     * as long as it isn't a parameter coming from the commandline,
     * try a few ports after it, to see if we can find a "free" one
     *
     * if we go on without binding, the first sendto() automatically binds to
     * a free port chosen by the system (i.e. anything from 1024 to 65535)
     *
     * returning NULL after bind fails has both advantages and disadvantages:
     * advantage:
     *   we can rely on getting the port in the range 33445..33450, which
     *   enables us to tell joe user to open their firewall to a small range
     *
     * disadvantage:
     *   some clients might not test return of tox_new(), blindly assuming that
     *   it worked ok (which it did previously without a successful bind)
     */
    uint16_t port_to_try = port;
    *portptr = htons(port_to_try);
    int tries, res;

    for (tries = TOX_PORTRANGE_FROM; tries <= TOX_PORTRANGE_TO; tries++)
    {
        res = bind(temp->sock, (struct sockaddr *)&addr, addrsize);

        if (!res) {
            temp->port = *portptr;
#ifdef LOGGING
            loginit(temp->port);

            sprintf(logbuffer, "Bound successfully to %s:%u.\n", ip_ntoa(&ip), ntohs(temp->port));
            loglog(logbuffer);
#endif

            /* errno isn't reset on success, only set on failure, the failed
             * binds with parallel clients yield a -EPERM to the outside if
             * errno isn't cleared here */
            if (tries > 0)
                errno = 0;

            return temp;
        }

        port_to_try++;

        if (port_to_try > TOX_PORTRANGE_TO)
            port_to_try = TOX_PORTRANGE_FROM;

        *portptr = htons(port_to_try);
    }

#ifdef DEBUG
    fprintf(stderr, "Failed to bind socket: %u, %s (IP/Port: %s:%u\n", errno,
            strerror(errno), ip_ntoa(&ip), port);
#endif
    kill_networking(temp);
    return NULL;
}
Example #27
0
/* This function initializes all network interfaces */
static void
msvc_netif_init()
{
#if USE_ETHERNET
  ip_addr_t ipaddr, netmask, gw;
#endif /* USE_ETHERNET */

#if PPP_SUPPORT
  const char *username = NULL, *password = NULL;
#ifdef PPP_USERNAME
  username = PPP_USERNAME;
#endif
#ifdef PPP_PASSWORD
  password = PPP_PASSWORD;
#endif
  printf("pppInit\n");
  pppInit();
  pppSetAuth(PPPAUTHTYPE_ANY, username, password);
  printf("pppOpen: COM%d\n", (int)sio_idx);
#if PPPOS_SUPPORT
  ppp_sio = sio_open(sio_idx);
  if (ppp_sio == NULL) {
    printf("sio_open error\n");
  } else {
    ppp_desc = pppOpen(ppp_sio, pppLinkStatusCallback, NULL);
  }
#endif /* PPPOS_SUPPORT */
#endif  /* PPP_SUPPORT */

#if USE_ETHERNET
  ip_addr_set_zero(&gw);
  ip_addr_set_zero(&ipaddr);
  ip_addr_set_zero(&netmask);
#if USE_ETHERNET_TCPIP
#if USE_DHCP
  printf("Starting lwIP, local interface IP is dhcp-enabled\n");
#elif USE_AUTOIP
  printf("Starting lwIP, local interface IP is autoip-enabled\n");
#else /* USE_DHCP */
  LWIP_PORT_INIT_GW(&gw);
  LWIP_PORT_INIT_IPADDR(&ipaddr);
  LWIP_PORT_INIT_NETMASK(&netmask);
  printf("Starting lwIP, local interface IP is %s\n", ip_ntoa(&ipaddr));
#endif /* USE_DHCP */
#endif /* USE_ETHERNET_TCPIP */

#if NO_SYS
#if LWIP_ARP
  netif_set_default(netif_add(&netif, &ipaddr, &netmask, &gw, NULL, pcapif_init, ethernet_input));
#else /* LWIP_ARP */
  netif_set_default(netif_add(&netif, &ipaddr, &netmask, &gw, NULL, pcapif_init, ip_input));
#endif /* LWIP_ARP */
#else  /* NO_SYS */
  netif_set_default(netif_add(&netif, &ipaddr, &netmask, &gw, NULL, pcapif_init, tcpip_input));
#if LWIP_IPV6
  netif_create_ip6_linklocal_address(&netif, 1);
  printf("ip6 linklocal address: ");
  ip6_addr_debug_print(0xFFFFFFFF & ~LWIP_DBG_HALT, &netif.ip6_addr[0]);
  printf("\n");
#endif /* LWIP_IPV6 */
#endif /* NO_SYS */
#if LWIP_NETIF_STATUS_CALLBACK
  netif_set_status_callback(&netif, status_callback);
#endif /* LWIP_NETIF_STATUS_CALLBACK */
#if LWIP_NETIF_LINK_CALLBACK
  netif_set_link_callback(&netif, link_callback);
#endif /* LWIP_NETIF_LINK_CALLBACK */

#if USE_ETHERNET_TCPIP
#if LWIP_AUTOIP
  autoip_set_struct(&netif, &netif_autoip);
#endif /* LWIP_AUTOIP */
#if LWIP_DHCP
  dhcp_set_struct(&netif, &netif_dhcp);
#endif /* LWIP_DHCP */
#if USE_DHCP
  dhcp_start(&netif);
#elif USE_AUTOIP
  autoip_start(&netif);
#else /* USE_DHCP */
  netif_set_up(&netif);
#endif /* USE_DHCP */
#else /* USE_ETHERNET_TCPIP */
  /* Use ethernet for PPPoE only */
  netif.flags &= ~(NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP); /* no ARP */
  netif.flags |= NETIF_FLAG_ETHERNET; /* but pure ethernet */
#endif /* USE_ETHERNET_TCPIP */

#if PPP_SUPPORT && PPPOE_SUPPORT
  /* start PPPoE after ethernet netif is added! */
  ppp_desc = pppOverEthernetOpen(&netif, NULL, NULL, pppLinkStatusCallback, NULL);
#endif /* PPP_SUPPORT && PPPOE_SUPPORT */

#endif /* USE_ETHERNET */
}
Example #28
0
/*
 *	Store logins in the RADIUS utmp file.
 */
static rlm_rcode_t mod_accounting(void *instance, REQUEST *request)
{
	rlm_rcode_t	rcode = RLM_MODULE_OK;
	struct radutmp	ut, u;
	vp_cursor_t	cursor;
	VALUE_PAIR	*vp;
	int		status = -1;
	int		protocol = -1;
	time_t		t;
	int		fd = -1;
	int		port_seen = 0;
	int		off;
	rlm_radutmp_t	*inst = instance;
	char		ip_name[32]; /* 255.255.255.255 */
	char const	*nas;
	NAS_PORT	*cache;
	int		r;

	char		*filename = NULL;
	char		*expanded = NULL;

	if (request->packet->src_ipaddr.af != AF_INET) {
		DEBUG("rlm_radutmp: IPv6 not supported!");
		return RLM_MODULE_NOOP;
	}

	/*
	 *	Which type is this.
	 */
	if ((vp = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE, 0, TAG_ANY)) == NULL) {
		RDEBUG("No Accounting-Status-Type record.");
		return RLM_MODULE_NOOP;
	}
	status = vp->vp_integer;

	/*
	 *	Look for weird reboot packets.
	 *
	 *	ComOS (up to and including 3.5.1b20) does not send
	 *	standard PW_STATUS_ACCOUNTING_XXX messages.
	 *
	 *	Check for:  o no Acct-Session-Time, or time of 0
	 *		    o Acct-Session-Id of "00000000".
	 *
	 *	We could also check for NAS-Port, that attribute
	 *	should NOT be present (but we don't right now).
	 */
	if ((status != PW_STATUS_ACCOUNTING_ON) &&
	    (status != PW_STATUS_ACCOUNTING_OFF)) do {
		int check1 = 0;
		int check2 = 0;

		if ((vp = pairfind(request->packet->vps, PW_ACCT_SESSION_TIME, 0, TAG_ANY))
		     == NULL || vp->vp_date == 0)
			check1 = 1;
		if ((vp = pairfind(request->packet->vps, PW_ACCT_SESSION_ID, 0, TAG_ANY))
		     != NULL && vp->length == 8 &&
		     memcmp(vp->vp_strvalue, "00000000", 8) == 0)
			check2 = 1;
		if (check1 == 0 || check2 == 0) {
			break;
		}
		INFO("rlm_radutmp: converting reboot records.");
		if (status == PW_STATUS_STOP)
			status = PW_STATUS_ACCOUNTING_OFF;
		if (status == PW_STATUS_START)
			status = PW_STATUS_ACCOUNTING_ON;
	} while(0);

	time(&t);
	memset(&ut, 0, sizeof(ut));
	ut.porttype = 'A';
	ut.nas_address = htonl(INADDR_NONE);

	/*
	 *	First, find the interesting attributes.
	 */
	for (vp = paircursor(&cursor, &request->packet->vps);
	     vp;
	     vp = pairnext(&cursor)) {
		if (!vp->da->vendor) switch (vp->da->attr) {
			case PW_LOGIN_IP_HOST:
			case PW_FRAMED_IP_ADDRESS:
				ut.framed_address = vp->vp_ipaddr;
				break;
			case PW_FRAMED_PROTOCOL:
				protocol = vp->vp_integer;
				break;
			case PW_NAS_IP_ADDRESS:
				ut.nas_address = vp->vp_ipaddr;
				break;
			case PW_NAS_PORT:
				ut.nas_port = vp->vp_integer;
				port_seen = 1;
				break;
			case PW_ACCT_DELAY_TIME:
				ut.delay = vp->vp_integer;
				break;
			case PW_ACCT_SESSION_ID:
				/*
				 *	If length > 8, only store the
				 *	last 8 bytes.
				 */
				off = vp->length - sizeof(ut.session_id);
				/*
				 * 	Ascend is br0ken - it adds a \0
				 * 	to the end of any string.
				 * 	Compensate.
				 */
				if (vp->length > 0 &&
				    vp->vp_strvalue[vp->length - 1] == 0)
					off--;
				if (off < 0) off = 0;
				memcpy(ut.session_id, vp->vp_strvalue + off,
					sizeof(ut.session_id));
				break;
			case PW_NAS_PORT_TYPE:
				if (vp->vp_integer <= 4)
					ut.porttype = porttypes[vp->vp_integer];
				break;
			case PW_CALLING_STATION_ID:
				if(inst->caller_id_ok)
					strlcpy(ut.caller_id,
						vp->vp_strvalue,
						sizeof(ut.caller_id));
				break;
		}
	}

	/*
	 *	If we didn't find out the NAS address, use the
	 *	originator's IP address.
	 */
	if (ut.nas_address == htonl(INADDR_NONE)) {
		ut.nas_address = request->packet->src_ipaddr.ipaddr.ip4addr.s_addr;
		nas = request->client->shortname;

	} else if (request->packet->src_ipaddr.ipaddr.ip4addr.s_addr == ut.nas_address) {		/* might be a client, might not be. */
		nas = request->client->shortname;

	} else {
		/*
		 *	The NAS isn't a client, it's behind
		 *	a proxy server.  In that case, just
		 *	get the IP address.
		 */
		nas = ip_ntoa(ip_name, ut.nas_address);
	}

	/*
	 *	Set the protocol field.
	 */
	if (protocol == PW_PPP) {
		ut.proto = 'P';
	} else if (protocol == PW_SLIP) {
		ut.proto = 'S';
	} else {
		ut.proto = 'T';
	}

	ut.time = t - ut.delay;

	/*
	 *	Get the utmp filename, via xlat.
	 */
	filename = NULL;
	if (radius_axlat(&filename, request, inst->filename, NULL, NULL) < 0) {
		return RLM_MODULE_FAIL;
	}

	/*
	 *	See if this was a reboot.
	 *
	 *	Hmm... we may not want to zap all of the users when the NAS comes up, because of issues with receiving
	 *	UDP packets out of order.
	 */
	if (status == PW_STATUS_ACCOUNTING_ON && (ut.nas_address != htonl(INADDR_NONE))) {
		RIDEBUG("NAS %s restarted (Accounting-On packet seen)", nas);
		rcode = radutmp_zap(request, filename, ut.nas_address, ut.time);

		goto finish;
	}

	if (status == PW_STATUS_ACCOUNTING_OFF && (ut.nas_address != htonl(INADDR_NONE))) {
		RIDEBUG("NAS %s rebooted (Accounting-Off packet seen)", nas);
		rcode = radutmp_zap(request, filename, ut.nas_address, ut.time);

		goto finish;
	}

	/*
	 *	If we don't know this type of entry pretend we succeeded.
	 */
	if (status != PW_STATUS_START && status != PW_STATUS_STOP && status != PW_STATUS_ALIVE) {
		REDEBUG("NAS %s port %u unknown packet type %d)", nas, ut.nas_port, status);
		rcode = RLM_MODULE_NOOP;

		goto finish;
	}

	/*
	 *	Translate the User-Name attribute, or whatever else they told us to use.
	 */
	if (radius_axlat(&expanded, request, inst->username, NULL, NULL) < 0) {
		rcode = RLM_MODULE_FAIL;

		goto finish;
	}
	strlcpy(ut.login, expanded, RUT_NAMESIZE);
	TALLOC_FREE(expanded);

	/*
	 *	Perhaps we don't want to store this record into
	 *	radutmp. We skip records:
	 *
	 *	- without a NAS-Port (telnet / tcp access)
	 *	- with the username "!root" (console admin login)
	 */
	if (!port_seen) {
		RWDEBUG2("No NAS-Port seen.  Cannot do anything. Checkrad will probably not work!");
		rcode = RLM_MODULE_NOOP;

		goto finish;
	}

	if (strncmp(ut.login, "!root", RUT_NAMESIZE) == 0) {
		RDEBUG2("Not recording administrative user");
		rcode = RLM_MODULE_NOOP;

		goto finish;
	}

	/*
	 *	Enter into the radutmp file.
	 */
	fd = open(filename, O_RDWR|O_CREAT, inst->permission);
	if (fd < 0) {
		REDEBUG("Error accessing file %s: %s", filename, strerror(errno));
		rcode = RLM_MODULE_FAIL;

		goto finish;
	}

	/*
	 *	Lock the utmp file, prefer lockf() over flock().
	 */
	rad_lockfd(fd, LOCK_LEN);

	/*
	 *	Find the entry for this NAS / portno combination.
	 */
	if ((cache = nas_port_find(inst->nas_port_list, ut.nas_address, ut.nas_port)) != NULL) {
		lseek(fd, (off_t)cache->offset, SEEK_SET);
	}

	r = 0;
	off = 0;
	while (read(fd, &u, sizeof(u)) == sizeof(u)) {
		off += sizeof(u);
		if ((u.nas_address != ut.nas_address) || (u.nas_port != ut.nas_port)) {
			continue;
		}

		/*
		 *	Don't compare stop records to unused entries.
		 */
		if (status == PW_STATUS_STOP && u.type == P_IDLE) {
			continue;
		}

		if ((status == PW_STATUS_STOP) && strncmp(ut.session_id, u.session_id, sizeof(u.session_id)) != 0) {
			/*
			 *	Don't complain if this is not a
			 *	login record (some clients can
			 *	send _only_ logout records).
			 */
			if (u.type == P_LOGIN) {
				RWDEBUG("Logout entry for NAS %s port %u has wrong ID", nas, u.nas_port);
			}

			r = -1;
			break;
		}

		if ((status == PW_STATUS_START) && strncmp(ut.session_id, u.session_id, sizeof(u.session_id)) == 0  &&
		    u.time >= ut.time) {
			if (u.type == P_LOGIN) {
				INFO("rlm_radutmp: Login entry for NAS %s port %u duplicate",
				       nas, u.nas_port);
				r = -1;
				break;
			}

			RWDEBUG("Login entry for NAS %s port %u wrong order", nas, u.nas_port);
			r = -1;
			break;
		}

		/*
		 *	FIXME: the ALIVE record could need some more checking, but anyway I'd
		 *	rather rewrite this mess -- miquels.
		 */
		if ((status == PW_STATUS_ALIVE) && strncmp(ut.session_id, u.session_id, sizeof(u.session_id)) == 0  &&
		    u.type == P_LOGIN) {
			/*
			 *	Keep the original login time.
			 */
			ut.time = u.time;
		}

		if (lseek(fd, -(off_t)sizeof(u), SEEK_CUR) < 0) {
			RWDEBUG("negative lseek!");
			lseek(fd, (off_t)0, SEEK_SET);
			off = 0;
		} else {
			off -= sizeof(u);
		}

		r = 1;
		break;
	} /* read the file until we find a match */

	/*
	 *	Found the entry, do start/update it with
	 *	the information from the packet.
	 */
	if ((r >= 0) && (status == PW_STATUS_START || status == PW_STATUS_ALIVE)) {
		/*
		 *	Remember where the entry was, because it's
		 *	easier than searching through the entire file.
		 */
		if (!cache) {
			cache = talloc_zero(inst, NAS_PORT);
			if (cache) {
				cache->nasaddr = ut.nas_address;
				cache->port = ut.nas_port;
				cache->offset = off;
				cache->next = inst->nas_port_list;
				inst->nas_port_list = cache;
			}
		}

		ut.type = P_LOGIN;
		if (write(fd, &ut, sizeof(u)) < 0) {
			REDEBUG("Failed writing: %s", strerror(errno));

			rcode = RLM_MODULE_FAIL;
			goto finish;
		}
	}

	/*
	 *	The user has logged off, delete the entry by
	 *	re-writing it in place.
	 */
	if (status == PW_STATUS_STOP) {
		if (r > 0) {
			u.type = P_IDLE;
			u.time = ut.time;
			u.delay = ut.delay;
			if (write(fd, &u, sizeof(u)) < 0) {
				REDEBUG("Failed writing: %s", strerror(errno));

				rcode = RLM_MODULE_FAIL;
				goto finish;
			}
		} else if (r == 0) {
			RWDEBUG("Logout for NAS %s port %u, but no Login record", nas, ut.nas_port);
		}
	}

	finish:

	talloc_free(filename);

	if (fd > -1) {
		close(fd);	/* and implicitely release the locks */
	}

	return rcode;
}
Example #29
0
/** Low-level initialization: find the correct adapter and initialize it.
 */
static void
pcapif_low_level_init(struct netif *netif)
{
  u8_t my_mac_addr[ETHARP_HWADDR_LEN] = LWIP_MAC_ADDR_BASE;
  int adapter_num = PACKET_LIB_ADAPTER_NR;
  struct pcapif_private *pa;

  /* If 'state' is != NULL at this point, we assume it is an 'int' giving
     the index of the adapter to use (+ 1 because 0==NULL is invalid).
     This can be used to instantiate multiple PCAP drivers. */
  if (netif->state != NULL) {
    adapter_num = ((int)netif->state) - 1;
    if (adapter_num < 0) {
      printf("ERROR: invalid adapter index \"%d\"!\n", adapter_num);
      LWIP_ASSERT("ERROR initializing network adapter!\n", 0);
      return;
    }
  }

#ifdef PACKET_LIB_GET_ADAPTER_NETADDRESS
  ip_addr_t netaddr;
#define GUID_LEN 128
  char guid[GUID_LEN + 1];
  memset(&guid, 0, sizeof(guid));
  PACKET_LIB_GET_ADAPTER_NETADDRESS(&netaddr);
  if (get_adapter_index_from_addr((struct in_addr *)&netaddr, guid, GUID_LEN) < 0) {
     printf("ERROR initializing network adapter, failed to get GUID for network address %s\n", ip_ntoa(&netaddr));
     LWIP_ASSERT("ERROR initializing network adapter, failed to get GUID for network address!", 0);
     return;
  }
  adapter_num = get_adapter_index(guid);
  if (adapter_num < 0) {
     printf("ERROR finding network adapter with GUID \"%s\"!\n", guid);
     LWIP_ASSERT("ERROR finding network adapter with expected GUID!", 0);
     return;
  }

#else /* PACKET_LIB_GET_ADAPTER_NETADDRESS */
#ifdef PACKET_LIB_ADAPTER_GUID
  /* get adapter index for guid string */
  adapter_num = get_adapter_index(PACKET_LIB_ADAPTER_GUID);
  if (adapter_num < 0) {
    printf("ERROR finding network adapter with GUID \"%s\"!\n", PACKET_LIB_ADAPTER_GUID);
    LWIP_ASSERT("ERROR initializing network adapter!\n", 0);
    return;
  }
#endif /* PACKET_LIB_ADAPTER_GUID */
#endif /* PACKET_LIB_GET_ADAPTER_NETADDRESS */

  /* Do whatever else is needed to initialize interface. */
  pa = pcapif_init_adapter(adapter_num, netif);
  if (pa == NULL) {
    printf("ERROR initializing network adapter %d!\n", adapter_num);
    LWIP_ASSERT("ERROR initializing network adapter!", 0);
    return;
  }
  netif->state = pa;

  /* change the MAC address to a unique value
     so that multiple ethernetifs are supported */
  /* @todo: this does NOT support multiple processes using this adapter! */
  my_mac_addr[ETHARP_HWADDR_LEN - 1] += netif->num;
  /* Copy MAC addr */
  memcpy(&netif->hwaddr, my_mac_addr, ETHARP_HWADDR_LEN);

  /* get the initial link state of the selected interface */
#if PCAPIF_HANDLE_LINKSTATE
  pa->last_link_event = pcapifh_linkstate_get(pa->link_state);
  if (pa->last_link_event == PCAPIF_LINKEVENT_DOWN) {
    netif_set_link_down(netif);
  } else {
    netif_set_link_up(netif);
  }
  sys_timeout(PCAPIF_LINKCHECK_INTERVAL_MS, pcapif_check_linkstate, netif);
#endif /* PCAPIF_HANDLE_LINKSTATE */

#if PCAPIF_RX_USE_THREAD
  pa->rx_run = 1;
  pa->rx_running = 1;
  sys_thread_new("pcapif_rxthread", pcapif_input_thread, netif, 0, 0);
#endif

  LWIP_DEBUGF(NETIF_DEBUG, ("pcapif: eth_addr %02X%02X%02X%02X%02X%02X\n",netif->hwaddr[0],netif->hwaddr[1],netif->hwaddr[2],netif->hwaddr[3],netif->hwaddr[4],netif->hwaddr[5]));
}
Example #30
0
File: auth.c Project: ebichu/dd-wrt
/*
 *	Process and reply to an authentication request
 *
 *	The return value of this function isn't actually used right now, so
 *	it's not entirely clear if it is returning the right things. --Pac.
 */
int rad_authenticate(REQUEST *request)
{
	VALUE_PAIR	*namepair;
#ifdef WITH_SESSION_MGMT
	VALUE_PAIR	*check_item;
#endif
	VALUE_PAIR	*auth_item = NULL;
	VALUE_PAIR	*module_msg;
	VALUE_PAIR	*tmp = NULL;
	int		result;
	const char	*password;
	char		autz_retry = 0;
	int		autz_type = 0;

	password = "";

#ifdef WITH_PROXY
	/*
	 *	If this request got proxied to another server, we need
	 *	to check whether it authenticated the request or not.
	 */
	if (request->proxy_reply) {
		switch (request->proxy_reply->code) {
		/*
		 *	Reply of ACCEPT means accept, thus set Auth-Type
		 *	accordingly.
		 */
		case PW_AUTHENTICATION_ACK:
			tmp = radius_paircreate(request,
						&request->config_items,
						PW_AUTH_TYPE, PW_TYPE_INTEGER);
			if (tmp) tmp->vp_integer = PW_AUTHTYPE_ACCEPT;
#ifdef WITH_POST_PROXY_AUTHORIZE
			if (mainconfig.post_proxy_authorize) break;
#endif
			goto authenticate;

		/*
		 *	Challenges are punted back to the NAS without any
		 *	further processing.
		 */
		case PW_ACCESS_CHALLENGE:
			request->reply->code = PW_ACCESS_CHALLENGE;
			return RLM_MODULE_OK;
		/*
		 *	ALL other replies mean reject. (this is fail-safe)
		 *
		 *	Do NOT do any authorization or authentication. They
		 *	are being rejected, so we minimize the amount of work
		 *	done by the server, by rejecting them here.
		 */
		case PW_AUTHENTICATION_REJECT:
			rad_authlog("Login incorrect (Home Server says so)",
				    request, 0);
			request->reply->code = PW_AUTHENTICATION_REJECT;
			return RLM_MODULE_REJECT;

		default:
			rad_authlog("Login incorrect (Home Server failed to respond)",
				    request, 0);
			return RLM_MODULE_REJECT;
		}
	}
#endif

	/*
	 *	Get the username from the request.
	 *
	 *	Note that namepair MAY be NULL, in which case there
	 *	is no User-Name attribute in the request.
	 */
	namepair = request->username;

	/*
	 *	Look for, and cache, passwords.
	 */
	if (!request->password) {
		request->password = pairfind(request->packet->vps,
					     PW_USER_PASSWORD);
	}

	/*
	 *	Discover which password we want to use.
	 */
	auth_item = request->password;
	if (auth_item) {
		password = (const char *)auth_item->vp_strvalue;

	} else {
		/*
		 *	Maybe there's a CHAP-Password?
		 */
		if ((auth_item = pairfind(request->packet->vps,
					  PW_CHAP_PASSWORD)) != NULL) {
			password = "******";

		} else {
			/*
			 *	No password we recognize.
			 */
			password = "******";
		}
	}
	request->password = auth_item;

	/*
	 *	Get the user's authorization information from the database
	 */
autz_redo:
	result = module_authorize(autz_type, request);
	switch (result) {
		case RLM_MODULE_NOOP:
		case RLM_MODULE_NOTFOUND:
		case RLM_MODULE_OK:
		case RLM_MODULE_UPDATED:
			break;
		case RLM_MODULE_HANDLED:
			return result;
		case RLM_MODULE_FAIL:
		case RLM_MODULE_INVALID:
		case RLM_MODULE_REJECT:
		case RLM_MODULE_USERLOCK:
		default:
			if ((module_msg = pairfind(request->packet->vps,
					PW_MODULE_FAILURE_MESSAGE)) != NULL) {
				char msg[MAX_STRING_LEN + 16];
				snprintf(msg, sizeof(msg), "Invalid user (%s)",
					 module_msg->vp_strvalue);
				rad_authlog(msg,request,0);
			} else {
				rad_authlog("Invalid user", request, 0);
			}
			request->reply->code = PW_AUTHENTICATION_REJECT;
			return result;
	}
	if (!autz_retry) {
		tmp = pairfind(request->config_items, PW_AUTZ_TYPE);
		if (tmp) {
			autz_type = tmp->vp_integer;
			RDEBUG2("Using Autz-Type %s",
				dict_valnamebyattr(PW_AUTZ_TYPE, autz_type));
			autz_retry = 1;
			goto autz_redo;
		}
	}

	/*
	 *	If we haven't already proxied the packet, then check
	 *	to see if we should.  Maybe one of the authorize
	 *	modules has decided that a proxy should be used. If
	 *	so, get out of here and send the packet.
	 */
	if (
#ifdef WITH_PROXY
	    (request->proxy == NULL) &&
#endif
	    ((tmp = pairfind(request->config_items, PW_PROXY_TO_REALM)) != NULL)) {
		REALM *realm;

		realm = realm_find2(tmp->vp_strvalue);

		/*
		 *	Don't authenticate, as the request is going to
		 *	be proxied.
		 */
		if (realm && realm->auth_pool) {
			return RLM_MODULE_OK;
		}

		/*
		 *	Catch users who set Proxy-To-Realm to a LOCAL
		 *	realm (sigh).  But don't complain if it is
		 *	*the* LOCAL realm.
		 */
		if (realm &&(strcmp(realm->name, "LOCAL") != 0)) {
			RDEBUG2("WARNING: You set Proxy-To-Realm = %s, but it is a LOCAL realm!  Cancelling proxy request.", realm->name);
		}

		if (!realm) {
			RDEBUG2("WARNING: You set Proxy-To-Realm = %s, but the realm does not exist!  Cancelling invalid proxy request.", tmp->vp_strvalue);
		}
	}

#ifdef WITH_PROXY
 authenticate:
#endif

	/*
	 *	Perhaps there is a Stripped-User-Name now.
	 */
	namepair = request->username;

	/*
	 *	Validate the user
	 */
	do {
		result = rad_check_password(request);
		if (result > 0) {
			/* don't reply! */
			return RLM_MODULE_HANDLED;
		}
	} while(0);

	/*
	 *	Failed to validate the user.
	 *
	 *	We PRESUME that the code which failed will clean up
	 *	request->reply->vps, to be ONLY the reply items it
	 *	wants to send back.
	 */
	if (result < 0) {
		RDEBUG2("Failed to authenticate the user.");
		request->reply->code = PW_AUTHENTICATION_REJECT;

		if ((module_msg = pairfind(request->packet->vps,PW_MODULE_FAILURE_MESSAGE)) != NULL){
			char msg[MAX_STRING_LEN+19];

			snprintf(msg, sizeof(msg), "Login incorrect (%s)",
				 module_msg->vp_strvalue);
			rad_authlog(msg, request, 0);
		} else {
			rad_authlog("Login incorrect", request, 0);
		}

		/* double check: maybe the secret is wrong? */
		if ((debug_flag > 1) && (auth_item != NULL) &&
				(auth_item->attribute == PW_USER_PASSWORD)) {
			uint8_t *p;

			p = (uint8_t *) auth_item->vp_strvalue;
			while (*p) {
				int size;

				size = fr_utf8_char(p);
				if (!size) {
					log_debug("  WARNING: Unprintable characters in the password.  Double-check the shared secret on the server and the NAS!");
					break;
				}
				p += size;
			}
		}
	}

#ifdef WITH_SESSION_MGMT
	if (result >= 0 &&
	    (check_item = pairfind(request->config_items, PW_SIMULTANEOUS_USE)) != NULL) {
		int r, session_type = 0;
		char		logstr[1024];
		char		umsg[MAX_STRING_LEN + 1];
		const char	*user_msg = NULL;

		tmp = pairfind(request->config_items, PW_SESSION_TYPE);
		if (tmp) {
			session_type = tmp->vp_integer;
			RDEBUG2("Using Session-Type %s",
				dict_valnamebyattr(PW_SESSION_TYPE, session_type));
		}

		/*
		 *	User authenticated O.K. Now we have to check
		 *	for the Simultaneous-Use parameter.
		 */
		if (namepair &&
		    (r = module_checksimul(session_type, request, check_item->vp_integer)) != 0) {
			char mpp_ok = 0;

			if (r == 2){
				/* Multilink attempt. Check if port-limit > simultaneous-use */
				VALUE_PAIR *port_limit;

				if ((port_limit = pairfind(request->reply->vps, PW_PORT_LIMIT)) != NULL &&
					port_limit->vp_integer > check_item->vp_integer){
					RDEBUG2("MPP is OK");
					mpp_ok = 1;
				}
			}
			if (!mpp_ok){
				if (check_item->vp_integer > 1) {
		  		snprintf(umsg, sizeof(umsg),
							"\r\nYou are already logged in %d times  - access denied\r\n\n",
							(int)check_item->vp_integer);
					user_msg = umsg;
				} else {
					user_msg = "\r\nYou are already logged in - access denied\r\n\n";
				}

				request->reply->code = PW_AUTHENTICATION_REJECT;

				/*
				 *	They're trying to log in too many times.
				 *	Remove ALL reply attributes.
				 */
				pairfree(&request->reply->vps);
				radius_pairmake(request, &request->reply->vps,
						"Reply-Message",
						user_msg, T_OP_SET);

				snprintf(logstr, sizeof(logstr), "Multiple logins (max %d) %s",
					check_item->vp_integer,
					r == 2 ? "[MPP attempt]" : "");
				rad_authlog(logstr, request, 1);

				result = -1;
			}
		}
	}
#endif

	/*
	 *	Result should be >= 0 here - if not, it means the user
	 *	is rejected, so we just process post-auth and return.
	 */
	if (result < 0) {
		return RLM_MODULE_REJECT;
	}

	/*
	 *	Add the port number to the Framed-IP-Address if
	 *	vp->addport is set.
	 */
	if (((tmp = pairfind(request->reply->vps,
			     PW_FRAMED_IP_ADDRESS)) != NULL) &&
	    (tmp->flags.addport != 0)) {
		VALUE_PAIR *vpPortId;

		/*
		 *  Find the NAS port ID.
		 */
		if ((vpPortId = pairfind(request->packet->vps,
					 PW_NAS_PORT)) != NULL) {
		  unsigned long tvalue = ntohl(tmp->vp_integer);
		  tmp->vp_integer = htonl(tvalue + vpPortId->vp_integer);
		  tmp->flags.addport = 0;
		  ip_ntoa(tmp->vp_strvalue, tmp->vp_integer);
		} else {
			RDEBUG2("WARNING: No NAS-Port attribute in request.  CANNOT return a Framed-IP-Address + NAS-Port.\n");
			pairdelete(&request->reply->vps, PW_FRAMED_IP_ADDRESS);
		}
	}

	/*
	 *	Set the reply to Access-Accept, if it hasn't already
	 *	been set to something.  (i.e. Access-Challenge)
	 */
	if (request->reply->code == 0)
	  request->reply->code = PW_AUTHENTICATION_ACK;

	if ((module_msg = pairfind(request->packet->vps,PW_MODULE_SUCCESS_MESSAGE)) != NULL){
		char msg[MAX_STRING_LEN+12];

		snprintf(msg, sizeof(msg), "Login OK (%s)",
			 module_msg->vp_strvalue);
		rad_authlog(msg, request, 1);
	} else {
		rad_authlog("Login OK", request, 1);
	}

	/*
	 *	Run the modules in the 'post-auth' section.
	 */
	result = rad_postauth(request);

	return result;
}