示例#1
1
文件: im_udp.c 项目: rhaamo/sosyslog
int
im_udp_read(struct i_module *im, int infd, struct im_msg *ret)
{
	struct sockaddr_in	 frominet;
	struct im_udp_ctx	*c;
	char			*p;
	int			 slen;

	if (ret == NULL) {
		m_dprintf(MSYSLOG_SERIOUS, "im_udp: arg is null\n");
		return (-1);
	}

	ret->im_pid = -1;
	ret->im_pri = -1;
	ret->im_flags = 0;

	slen = sizeof(frominet);
	if ((ret->im_len = recvfrom(im->im_fd, ret->im_msg,
	    sizeof(ret->im_msg) - 1, 0, (struct sockaddr *)&frominet,
	    (socklen_t *)&slen)) < 1) {
		if (ret->im_len < 0 && errno != EINTR)
			logerror("recvfrom inet");
		return (1);
	}

	ret->im_msg[ret->im_len] = '\0';

	c = (struct im_udp_ctx *) im->im_ctx;

	/* change non printable chars to X, just in case */
	for(p = ret->im_msg; *p != '\0'; p++)
		if (!isprint((unsigned int) *p) && *p != '\n')
			*p = 'X';

	if (c->flags & M_USEMSGHOST) {
		char	host[90];
		int	n1, n2;

		n1 = 0;
		n2 = 0;
		/* extract hostname from message */
		if ((sscanf(ret->im_msg, "<%*d>%*3s %*i %*i:%*i:%*i %n%89s "
		    "%n%*s", &n1, host, &n2) != 1 &&
		    sscanf(ret->im_msg, "%*3s %*i %*i:%*i:%*i %n%89s %n%*s",
		    &n1, host, &n2) != 1 &&
		    sscanf(ret->im_msg, "%n%89s %n%*s", &n1, host,
		    &n2) != 1) ||
		    ret->im_msg[n2] == '\0') {
			m_dprintf(MSYSLOG_INFORMATIVE, "im_udp_read: skipped"
			    " invalid message [%s]\n", ret->im_msg);
			return (0);
		}

		if (ret->im_msg[n2] == '\0')
			return (0);

		/* remove host from message */
		while (ret->im_msg[n2] != '\0')
			ret->im_msg[n1++] = ret->im_msg[n2++];
		ret->im_msg[n1] = '\0';

		strncpy(ret->im_host, host, sizeof(ret->im_host) - 1);
		ret->im_host[sizeof(ret->im_host) - 1] = '\0';

	} else {
		struct hostent *hent;

		hent = gethostbyaddr((char *) &frominet.sin_addr,
		    sizeof(frominet.sin_addr), frominet.sin_family);
		if (hent) {
			strncpy(ret->im_host, hent->h_name,
			    sizeof(ret->im_host) - 1);
		} else {
			strncpy(ret->im_host, inet_ntoa(frominet.sin_addr),
			    sizeof(ret->im_host) - 1);
		}
	}

	ret->im_host[sizeof(ret->im_host) - 1] = '\0';

	if (c->flags & M_NOTFQDN) {
		char     *dot;

		if ((dot = strchr(ret->im_host, '.')) != NULL)
			*dot = '\0';
	}

	return (1);
}
示例#2
1
/**
 * @brief Receive data from a UDP/IP socket
 *
 * Receives data like `recvfrom(2)`. Pointers may be `NULL`, then the information (e.g. the source port) is lost (you may use
 * NULL pointers if you're not interested in some information)
 *
 * @param sfd The socket file descriptor.
 * @param buffer Where the data will be written
 * @param size The size of `buffer`
 * @param src_host Where the sending host's name/IP will be stored
 * @param src_host_len `src_host`'s length
 * @param src_service Where the port on remote side will be written to
 * @param src_service_len `src_service`'s length
 * @param recvfrom_flags Flags for `recvfrom(2)`
 * @param numeric `LIBSOCKET_NUMERIC` if you want the names to remain unresolved.
 *
 * @retval n *n* bytes of data were received.
 * @retval 0 Peer sent EOF.
 * @retval <0 An error occurred.
 */
ssize_t recvfrom_inet_dgram_socket(int sfd, void* buffer, size_t size, char* src_host, size_t src_host_len, char* src_service, size_t src_service_len, int recvfrom_flags, int numeric)
{
    struct sockaddr_storage client;

# ifdef _TRADITIONAL_RDNS
    struct sockaddr_storage oldsockaddr;
    socklen_t oldsockaddrlen = sizeof(struct sockaddr_storage);
    struct hostent* he;
    void* addrptr;
    size_t addrlen;
    uint16_t sport = 0;
# endif

    ssize_t bytes;

# ifndef _TRADITIONAL_RDNS
    int retval;
# endif

# ifdef VERBOSE
    const char* errstr;
# endif
    if ( sfd < 0 )
	return -1;

    if ( buffer == NULL || size == 0)
	return -1;
    else
	memset(buffer,0,size);

    if ( src_host )
	memset(src_host,0,src_host_len);
    if ( src_service )
	memset(src_service,0,src_service_len);

    socklen_t stor_addrlen = sizeof(struct sockaddr_storage);

    if ( -1 == check_error(bytes = recvfrom(sfd,buffer,size,recvfrom_flags,(struct sockaddr*)&client,&stor_addrlen)))
	return -1;

    if ( src_host_len > 0 || src_service_len > 0 ) // If one of the things is wanted. If you give a null pointer with a positive _len parameter, you won't get the address.
    {
	if ( numeric == LIBSOCKET_NUMERIC )
	{
	    numeric = NI_NUMERICHOST | NI_NUMERICSERV;
	}

	// getnameinfo() doesn't work on FreeBSD (here)
# ifndef _TRADITIONAL_RDNS
	if ( 0 != (retval = getnameinfo((struct sockaddr*)&client,sizeof(struct sockaddr_storage),src_host,src_host_len,src_service,src_service_len,numeric)) ) // Write information to the provided memory
	{
# ifdef VERBOSE
	    errstr = gai_strerror(retval);
	    debug_write(errstr);
# endif
	    return -1;
	}
# endif

	// so use traditional methods
# ifdef _TRADITIONAL_RDNS
	if ( -1 == check_error(getsockname(sfd,(struct sockaddr*)&oldsockaddr,&oldsockaddrlen)) )
	    return -1;

	if ( oldsockaddrlen > sizeof(struct sockaddr_storage) ) // If getsockname truncated the struct
	    return -1;

	if ( oldsockaddr.ss_family == AF_INET )
	{
	    addrptr = &(((struct sockaddr_in*)&client)->sin_addr);
	    addrlen = sizeof(struct in_addr);
	    sport = ntohs(((struct sockaddr_in*)&client)->sin_port);
	} else if ( oldsockaddr.ss_family == AF_INET6 )
	{
	    addrptr = &(((struct sockaddr_in6*)&client)->sin6_addr);
	    addrlen = sizeof(struct in6_addr);
	    sport = ntohs(((struct sockaddr_in6*)&client)->sin6_port);
	}

	if ( NULL == (he = gethostbyaddr(addrptr,addrlen,oldsockaddr.ss_family) ) )
	{
	    check_error(-1);
	    return -1;
	}

	strncpy(src_host,he->h_name,src_host_len);
	snprintf(src_service,src_service_len,"%u",sport);
# endif
    }

    return bytes;
}
示例#3
0
/**
@SYMTestCaseID          SYSLIB-STDLIB-CT-1073
@SYMTestCaseDesc	    Tests for ARPA net functions
@SYMTestPriority 	    High
@SYMTestActions  	    Tests for get host by name and host by address functions
@SYMTestExpectedResults Test must not fail
@SYMREQ                 REQ0000
*/
void testNetDB()
	{
	char hostname[128];
	struct in_addr addr, *addrp;
	int err, i;
	struct hostent *hp;

	test_Next("Get Host Name");

	err=gethostname(hostname,sizeof(hostname));
	test(err==0);
	printf("  hostname = >%s<\n", hostname);

	test_Next("Get Host By Name");

	for (i=0; i<N_NAMES; i++)
		{
		hp=gethostbyname(names[i][0]);
		test_ok(hp!=0);
		addrp=(struct in_addr*)(hp->h_addr_list[0]);
		printf("  %-30s => address %-15s\n", hp->h_name, inet_ntoa(*addrp));
		test(strcasecmp(hp->h_name,names[i][0])==0);
		test(addrp->s_addr==inet_addr(names[i][1]));
		}

	hp=gethostbyname("nosuchname.symbian.com");
	test_errno(hp==0,ENOENT);
	test(errno==HOST_NOT_FOUND);

	test_Next("Get Address of \"\"");
	hp=gethostbyname("");
	test_ok(hp!=0);
	addrp=(struct in_addr*)(hp->h_addr_list[0]);
	printf("  %-30s => address %-15s\n", hp->h_name, inet_ntoa(*addrp));

	test_Next("Get Host By Addr");

	for (i=0; i<N_NAMES; i++)
		{
		addr.s_addr=inet_addr(names[i][1]);
		hp=gethostbyaddr((const char *)&addr,sizeof(addr),AF_INET);
		test_ok(hp!=0);
		addrp=(struct in_addr*)(hp->h_addr_list[0]);
		printf("  address %-15s => %s\n", inet_ntoa(*addrp), hp->h_name);
		test(addrp->s_addr==addr.s_addr);
		test(strcasecmp(hp->h_name,names[i][2])==0);
		}

	addr.s_addr=inet_addr("10.11.199.255");
	hp=gethostbyaddr((const char *)&addr,sizeof(addr),AF_INET);
	test_errno(hp==0,ENOENT);
	test(errno==HOST_NOT_FOUND);
	
/*
	struct sockaddr_in testaddr;
	int fd;
	test_Next("Connect to the Imperial College Echo server");

	fd=socket(AF_INET, SOCK_STREAM, 0);
	test_ok(fd>=0);
	testaddr.sin_family=AF_INET;
	testaddr.sin_addr.s_addr=inet_addr("193.63.255.1");
	testaddr.sin_port=htons(7);	// echo
	err=connect(fd,(struct sockaddr*)&testaddr, sizeof(testaddr));
	test(err==0);
	close(fd);
*/

	test_Next("Get Address of roundrobin.test.intra which has multiple address");
	hp=gethostbyname("roundrobin.test.intra");	
	test_ok(hp!=0);

	if (hp)
		{
		if (hp->h_addr_list)
			{
			int Index = 0;
			while (hp->h_addr_list[Index])
				{
				addrp = (struct in_addr*)(hp->h_addr_list[Index]);
				printf("  %-30s => address %-15s\n", hp->h_name, inet_ntoa(*addrp));
				Index++;
				}
			}
		}

	test_Next("Get Host name of 192.168.255.4 which has multiple host name");
	addr.s_addr=inet_addr("192.168.255.4");
	hp=gethostbyaddr((const char *)&addr,sizeof(addr),AF_INET);
	test_ok(hp!=0);

	if (hp)
		{
		addrp=(struct in_addr*)(hp->h_addr_list[0]);
		printf("  address %-15s => %s\n", inet_ntoa(*addrp), hp->h_name);

		if (hp->h_aliases)
			{
			int Index = 0;
			while (hp->h_aliases[Index])
				{
				printf("  address %-15s => %s\n", inet_ntoa(*addrp), hp->h_aliases[Index]);
				Index++;
				}
			}
		}

	if (close_console)
		{
		test_Close();
		close(0);
		close(1);
		close(2);
		}
	}
示例#4
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;
    results.setHostName(hostName);

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    // Load res_init on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
#ifndef QT_NO_THREAD
        QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init));
#endif
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If res_init is available, poll it.
    if (local_res_init)
        local_res_init();

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
        sockaddr_in sa4;
#ifndef QT_NO_IPV6
        sockaddr_in6 sa6;
#endif
        sockaddr *sa = 0;
        QT_SOCKLEN_T saSize = 0;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        }
#ifndef QT_NO_IPV6
        else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }
#endif

        char hbuf[NI_MAXHOST];
        if (!sa || getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) != 0) {
            results.setError(QHostInfo::HostNotFound);
            results.setErrorString(tr("Host not found"));
            return results;
        }
        results.setHostName(QString::fromLatin1(hbuf));
#else
        in_addr_t inetaddr = inet_addr(hostName.toLatin1().constData());
        struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
        if (!ent) {
            results.setError(QHostInfo::HostNotFound);
            results.setErrorString(tr("Host not found"));
            return results;
        }
        results.setHostName(QString::fromLatin1(ent->h_name));
#endif
    }

#if !defined (QT_NO_GETADDRINFO)
    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
    hints.ai_flags = Q_ADDRCONFIG;
#endif

    int result = getaddrinfo(hostName.toLatin1().constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
    if (result == EAI_BADFLAGS) {
        // if the lookup failed with AI_ADDRCONFIG set, try again without it
        hints.ai_flags = 0;
        result = getaddrinfo(hostName.toLatin1().constData(), 0, &hints, &res);
    }
# endif

    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#ifndef QT_NO_IPV6
            else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                addr.setAddress(((sockaddr_in6 *) node->ai_addr)->sin6_addr.s6_addr);
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#endif
            node = node->ai_next;
        }
        if (addresses.isEmpty() && node == 0) {
            // Reached the end of the list, but no addresses were found; this
            // means the list contains one or more unknown address types.
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }

        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
	       // EAI_NODATA is deprecated in RFC 3493
	       || result == EAI_NODATA
#endif
	       ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }

#else
    // Fall back to gethostbyname for platforms that don't define
    // getaddrinfo. gethostbyname does not support IPv6, and it's not
    // reentrant on all platforms. For now this is okay since we only
    // use one QHostInfoAgent, but if more agents are introduced, locking
    // must be provided.
    QMutexLocker locker(::getHostByNameMutex());
    hostent *result = gethostbyname(hostName.toLatin1().constData());
    if (result) {
        if (result->h_addrtype == AF_INET) {
            QList<QHostAddress> addresses;
            for (char **p = result->h_addr_list; *p != 0; p++) {
                QHostAddress addr;
                addr.setAddress(ntohl(*((quint32 *)*p)));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            }
            results.setAddresses(addresses);
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }
    } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA
               || h_errno == NO_ADDRESS) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(tr("Unknown error"));
    }
#endif //  !defined (QT_NO_GETADDRINFO)

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
示例#5
0
文件: ttcoreex.cpp 项目: konelav/jmc
unsigned long __stdcall ConnectThread(void * pParam)
{
	USES_CONVERSION;

    CoInitialize ((void*)COINIT_MULTITHREADED);

    tintin_puts2(rs::rs(1184));

    SOCKET sock;
    int connectresult;
    struct sockaddr_in sockaddr;

    if(iswdigit(*strConnectAddress)) {                            /* interprete host part */
        sockaddr.sin_addr.s_addr=inet_addr(W2A(strConnectAddress));

		struct hostent *hp;
		if((hp=gethostbyaddr((const char*)&sockaddr, sizeof(sockaddr), AF_INET))==NULL) {
            wcscpy(MUDHostName, strConnectAddress);
        } else {
			wcscpy(MUDHostName, A2W(hp->h_name));
        }	
    } else {
		wcscpy(MUDHostName, strConnectAddress);

        struct hostent *hp;
        if((hp=gethostbyname(W2A(strConnectAddress)))==NULL) {
            tintin_puts2(rs::rs(1185));
            return 0;
        } else {
    	    struct in_addr inad;
            wchar_t ipaddr[256];

	        inad.S_un.S_addr = *(long*)hp->h_addr_list[0];
            swprintf(ipaddr , rs::rs(1186) , A2W(inet_ntoa(inad)));
	        tintin_puts2(ipaddr); 
        }
        memcpy((char *)&sockaddr.sin_addr, hp->h_addr, sizeof(sockaddr.sin_addr));
    }

    if(iswdigit(*strConnectPort))
        sockaddr.sin_port=htons((short)_wtoi(strConnectPort));      /* inteprete port part */
    else {
        tintin_puts2(rs::rs(1187));
        return 0;
    }

START1:
    if((sock=socket(AF_INET, SOCK_STREAM, 0))<0)
        tintin_puts2(rs::rs(1188));

	BOOL enable_opt = TRUE;
	/*
	 Something more than TCP_NODELAY should be done in case MUD server frequently sends tiny packets.
	 For example, if server sends prompt-line and IAC-GA in separate calls of send() then the first
	 packet (prompt) wouldn't ACKed by windows core for 200 milliseconds regardless of Nagle's algorithm,
	 leading to IAC-GA delayed for the same time. It's not a problem for visualizing since now JMC
	 prints out all incoming data immidiately; but processing of prompt line in described situation
	 by #acion and jmc.Incoming handlers will be delayed for 200 ms or value of Uncomplete line delay
	 setting in case it is less than 200.
	 Setting registry value on the client's machine (TcpAckFrequency := 1) is ugly, but effective solution.
	 No other solution (i.e. disabling delayed acknowledgement for particular socket) was found for
	 WinSock/WinSock2, WinXP/Vista/Win7/Win8. So it is responsibility of MUD servers to do wise and
	 accurate TCP bufferisation, though obviously it is possible only in MUDs where the smallest time period
	 between events (game-state updating period, "tick", time-quant) is less than 200ms.
	 At this point I giving up to solve this issue completely and mark it as part 
	 of global MUD problem called "Telnet Curse".
	*/
	if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&enable_opt, sizeof(enable_opt))) {
		tintin_puts2(L"#Can't disable Nagle's algorithm");
	}

    sockaddr.sin_family=AF_INET;


	reset_telnet_protocol();
	multiline_length = 0;

	if (ulProxyAddress) {
		wchar_t buf[BUFFER_SIZE];
		swprintf(buf, rs::rs(1303),
			(ulProxyAddress >> 24) & 0xff, (ulProxyAddress >> 16) & 0xff, (ulProxyAddress >> 8) & 0xff, (ulProxyAddress >> 0) & 0xff);
		tintin_puts2(buf);
	} else {
void CWE247_Reliance_on_DNS_Lookups_in_Security_Decision__w32_11_bad()
{
    if(globalReturnsTrue())
    {
        {
            WSADATA wsaData;
            BOOL wsaDataInit = FALSE;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET client = INVALID_SOCKET;
            struct sockaddr_in service;
            struct sockaddr_in serviceClient;
            int serviceClientLen;
            struct hostent *hostInfo;
            do
            {
                if (0 != WSAStartup(MAKEWORD(2, 2), &wsaData))
                {
                    break;
                }
                wsaDataInit = TRUE;
                listenSocket = socket(PF_INET, SOCK_STREAM, 0);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(LISTEN_PORT);
                if (SOCKET_ERROR == bind(listenSocket, (struct sockaddr*)&service, sizeof(service)))
                {
                    break;
                }
                if (SOCKET_ERROR == listen(listenSocket, LISTEN_BACKLOG))
                {
                    break;
                }
                serviceClientLen = sizeof(serviceClient);
                client = accept(listenSocket, (struct sockaddr*)&serviceClient, &serviceClientLen);
                if (client == INVALID_SOCKET)
                {
                    break;
                }
                if (serviceClient.sin_family != AF_INET)
                {
                    break;
                }
                hostInfo = gethostbyaddr((char*)&serviceClient.sin_addr, sizeof(serviceClient.sin_addr), AF_INET);
                if (hostInfo == NULL)
                {
                    break;
                }
                if (hostInfo->h_name == NULL)
                {
                    break;
                }
                printLine(hostInfo->h_name);
                /* INCIDENTAL: Some CWE about hardcoded information */
                /* FLAW: Using the reverse DNS of the client to determine whether to allow the connection */
                if (strcmp(hostInfo->h_name, SECRET_HOSTNAME) == 0)
                {
                    printLine("Access granted.");
                }
            }
            while (0);
            if (client != INVALID_SOCKET)
            {
                closesocket(client);
            }
            if (listenSocket != INVALID_SOCKET)
            {
                closesocket(listenSocket);
            }
            if (wsaDataInit)
            {
                WSACleanup();
            }
        }
    }
}
示例#7
0
net_socket* net_interface_tcp::connect(const char* c_host, int port)
{
	assert(c_host);
	assert(port > 0);

	m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (m_socket == INVALID_SOCKET)
	{
		fprintf(stderr, "can't open listen socket\n");
		return NULL;
	}

	// Set the address.
	SOCKADDR_IN saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_addr.s_addr = INADDR_ANY;
	m_port_number = get_proxy_port() > 0 ? get_proxy_port() : port;
	saddr.sin_port = htons(m_port_number);


	hostent* he;
	const char* host = get_proxy_port() > 0 ? get_proxy() : c_host;
	if (host[0] >= '0' && host[0] <= '9')	// absolue address ?
	{
		Uint32 addr = inet_addr(host);
		he = gethostbyaddr((char *) &addr, 4, AF_INET);
	}
	else
	{
		he = gethostbyname(host);
	}

	if (he == NULL)
	{
		fprintf(stderr, "can't find '%s'\n", host);
		closesocket(m_socket);
		m_socket = INVALID_SOCKET;
		return NULL;
	}

	// get server address
	memcpy(&saddr.sin_addr, he->h_addr, he->h_length);

	//      printf("The IP address is '%d.%d.%d.%d'\n", 
	//				saddr.sin_addr.S_un.S_un_b.s_b1,
	//				saddr.sin_addr.S_un.S_un_b.s_b2,
	//				saddr.sin_addr.S_un.S_un_b.s_b3,
	//				saddr.sin_addr.S_un.S_un_b.s_b4);

	int rc = ::connect(m_socket, (struct sockaddr*) &saddr, sizeof(struct sockaddr));
	if (rc != 0)
	{
		fprintf(stderr, "can't connect to '%s', port %d\n", host, m_port_number);
		closesocket(m_socket);
		m_socket = INVALID_SOCKET;
		return NULL;
	}

	// Set non-blocking mode for the socket, so that
	// accept() doesn't block if there's no pending
	// connection.
	set_nonblock();

	return new net_socket_tcp(m_socket);
}
示例#8
0
文件: get_ip.c 项目: basecq/q2dos
struct hostent * W32_CALL
getipnodebyaddr (const void *src, size_t len, int af, int *error)
{
  struct hostent *he1, *he2;
  const  BYTE *cp = (const BYTE*) src;

  SOCK_DEBUGF (("\ngetipnodebyaddr: "));

  if (!src)
  {
    *error = NO_RECOVERY;
    return (NULL);
  }

  switch (af)
  {
    case AF_INET:
         if (len < INADDRSZ)
         {
           *error = NO_RECOVERY;
           return (NULL);
         }
         break;
#if defined(USE_IPV6)
    case AF_INET6:
         if (len < IN6ADDRSZ)
         {
           *error = NO_RECOVERY;
           return (NULL);
         }
         break;
#endif
    default:
         *error = NO_RECOVERY;
         return (NULL);
  }

  /* Look up IPv4 and IPv4 mapped/compatible addresses.
   */
  if ((af == AF_INET6 && IN6_IS_ADDR_V4COMPAT(cp)) ||
      (af == AF_INET6 && IN6_IS_ADDR_V4MAPPED(cp)) ||
      (af == AF_INET))
  {
    if (af == AF_INET6)
       cp += 12;

    SOCK_ENTER_SCOPE();
    he1 = gethostbyaddr ((const char*)cp, 4, AF_INET);
    SOCK_LEAVE_SCOPE();

    if (af == AF_INET)
       goto ret_copy;

    /* Convert from AF_INET to AF_INET6.
     */
    he2 = copyandmerge (he1, NULL, af, error);
    if (he2)
    {
      memcpy (he2->h_addr, src, len);  /* Restore original address */
      SOCK_DEBUGF (("%s", af == AF_INET ?
                    inet_ntoa(*(struct in_addr*)&he2->h_addr) :
                    _inet6_ntoa(he2->h_addr)));
    }
    return (he2);
  }

  he1 = gethostbyaddr (src, len, AF_INET6);   /* Lookup IPv6 address */

ret_copy:
  if (!he1)
  {
    *error = HOST_NOT_FOUND;
    return (NULL);
  }
  return copyandmerge (he1, NULL, af, error);
}
示例#9
0
文件: tcp.c 项目: zsh-users/zsh
static int
bin_ztcp(char *nam, char **args, Options ops, UNUSED(int func))
{
    int herrno, err=1, destport, force=0, verbose=0, test=0, targetfd=0;
    ZSOCKLEN_T  len;
    char **addrp, *desthost;
    const char *localname, *remotename;
    struct hostent *zthost = NULL, *ztpeer = NULL;
    struct servent *srv;
    Tcp_session sess = NULL;

    if (OPT_ISSET(ops,'f'))
	force = 1;

    if (OPT_ISSET(ops,'v'))
	verbose = 1;

    if (OPT_ISSET(ops,'t'))
        test = 1;

    if (OPT_ISSET(ops,'d')) {
	targetfd = atoi(OPT_ARG(ops,'d'));
	if (!targetfd) {
	    zwarnnam(nam, "%s is an invalid argument to -d", OPT_ARG(ops,'d'));
	    return 1;
	}
    }


    if (OPT_ISSET(ops,'c')) {
	if (!args[0]) {
	    tcp_cleanup();
	}
	else {
	    targetfd = atoi(args[0]);
	    sess = zts_byfd(targetfd);
	    if(!targetfd) {
		zwarnnam(nam, "%s is an invalid argument to -c", args[0]);
		return 1;
	    }

	    if (sess)
	    {
		if ((sess->flags & ZTCP_ZFTP) && !force)
		{
		    zwarnnam(nam, "use -f to force closure of a zftp control connection");
		    return 1;
		}
		tcp_close(sess);
		return 0;
	    }
	    else
	    {
		zwarnnam(nam, "fd %s not found in tcp table", args[0]);
		return 1;
	    }
	}
    }
    else if (OPT_ISSET(ops,'l')) {
	int lport = 0;

	if (!args[0]) {
	    zwarnnam(nam, "-l requires an argument");
	    return 1;
	}

	srv = getservbyname(args[0], "tcp");
	if (srv)
	    lport = srv->s_port;
	else
	    lport = htons(atoi(args[0]));
	if (!lport) { zwarnnam(nam, "bad service name or port number");
	return 1;
	}
	sess = tcp_socket(PF_INET, SOCK_STREAM, 0, ZTCP_LISTEN);

	if (!sess) {
	    zwarnnam(nam, "unable to allocate a TCP session slot");
	    return 1;
	}
#ifdef SO_OOBINLINE
	len = 1;
	setsockopt(sess->fd, SOL_SOCKET, SO_OOBINLINE, (char *)&len, sizeof(len));
#endif
	if (!zsh_inet_aton("0.0.0.0", &(sess->sock.in.sin_addr)))
	{
	    zwarnnam(nam, "bad address: %s", "0.0.0.0");
	    return 1;
	}

	sess->sock.in.sin_family = AF_INET;
	sess->sock.in.sin_port = lport;


	if (bind(sess->fd, (struct sockaddr *)&sess->sock.in, sizeof(struct sockaddr_in)))
	{
	    char buf[DIGBUFSIZE];
	    convbase(buf, (zlong)ntohs(lport), 10);
	    zwarnnam(nam, "could not bind to port %s: %e", buf, errno);
	    tcp_close(sess);
	    return 1;
	}

	if (listen(sess->fd, 1))
	{
	    zwarnnam(nam, "could not listen on socket: %e", errno);
	    tcp_close(sess);
	    return 1;
	}

	if (targetfd) {
	    sess->fd = redup(sess->fd, targetfd);
	}
	else {
	    /* move the fd since no one will want to read from it */
	    sess->fd = movefd(sess->fd);
	}

	if (sess->fd == -1) {
	    zwarnnam(nam, "cannot duplicate fd %d: %e", sess->fd, errno);
	    tcp_close(sess);
	    return 1;
	}

	setiparam_no_convert("REPLY", (zlong)sess->fd);

	if (verbose)
	    printf("%d listener is on fd %d\n", ntohs(sess->sock.in.sin_port), sess->fd);

	return 0;

    }
    else if (OPT_ISSET(ops,'a'))
    {
	int lfd, rfd;

	if (!args[0]) {
	    zwarnnam(nam, "-a requires an argument");
	    return 1;
	}

	lfd = atoi(args[0]);

	if (!lfd) {
	    zwarnnam(nam, "invalid numerical argument");
	    return 1;
	}

	sess = zts_byfd(lfd);
	if (!sess) {
	    zwarnnam(nam, "fd %s is not registered as a tcp connection", args[0]);
	    return 1;
	}

	if (!(sess->flags & ZTCP_LISTEN))
	{
	    zwarnnam(nam, "tcp connection not a listener");
	    return 1;
	}

	if (test) {
#if defined(HAVE_POLL) || defined(HAVE_SELECT)
# ifdef HAVE_POLL
	    struct pollfd pfd;
	    int ret;

	    pfd.fd = lfd;
	    pfd.events = POLLIN;
	    if ((ret = poll(&pfd, 1, 0)) == 0) return 1;
	    else if (ret == -1)
	    {
		zwarnnam(nam, "poll error: %e", errno);
		return 1;
	    }
# else
	    fd_set rfds;
	    struct timeval tv;
	    int ret;
	    
	    FD_ZERO(&rfds);
	    FD_SET(lfd, &rfds);
	    tv.tv_sec = 0;
	    tv.tv_usec = 0;
	    
	    if ((ret = select(lfd+1, &rfds, NULL, NULL, &tv)) == 0) return 1;
	    else if (ret == -1)
	    {
		zwarnnam(nam, "select error: %e", errno);
		return 1;
	    }
	    
# endif
	    
#else
	    zwarnnam(nam, "not currently supported");
	    return 1;
#endif
	}
	sess = zts_alloc(ZTCP_INBOUND);

	len = sizeof(sess->peer.in);
	do {
	    rfd = accept(lfd, (struct sockaddr *)&sess->peer.in, &len);
	} while (rfd < 0 && errno == EINTR && !errflag);

	if (rfd == -1) {
	    zwarnnam(nam, "could not accept connection: %e", errno);
	    tcp_close(sess);
	    return 1;
	}

	/* redup expects fd is already registered */
	addmodulefd(rfd, FDT_MODULE);

	if (targetfd) {
	    sess->fd = redup(rfd, targetfd);
	    if (sess->fd < 0) {
		zerrnam(nam, "could not duplicate socket fd to %d: %e", targetfd, errno);
		return 1;
	    }
	}
	else {
	    sess->fd = rfd;
	}

	setiparam_no_convert("REPLY", (zlong)sess->fd);

	if (verbose)
	    printf("%d is on fd %d\n", ntohs(sess->peer.in.sin_port), sess->fd);
    }
    else
    {
	if (!args[0]) {
	    LinkNode node;
	    for(node = firstnode(ztcp_sessions); node; incnode(node))
	    {
		sess = (Tcp_session)getdata(node);

		if (sess->fd != -1)
		{
		    zthost = gethostbyaddr((const void *)&(sess->sock.in.sin_addr), sizeof(sess->sock.in.sin_addr), AF_INET);
		    if (zthost)
			localname = zthost->h_name;
		    else
			localname = inet_ntoa(sess->sock.in.sin_addr);
		    ztpeer = gethostbyaddr((const void *)&(sess->peer.in.sin_addr), sizeof(sess->peer.in.sin_addr), AF_INET);
		    if (ztpeer)
			remotename = ztpeer->h_name;
		    else
			remotename = inet_ntoa(sess->peer.in.sin_addr);
		    if (OPT_ISSET(ops,'L')) {
			int schar;
			if (sess->flags & ZTCP_ZFTP)
			    schar = 'Z';
			else if (sess->flags & ZTCP_LISTEN)
			    schar = 'L';
			else if (sess->flags & ZTCP_INBOUND)
			    schar = 'I';
			else
			    schar = 'O';
			printf("%d %c %s %d %s %d\n",
			       sess->fd, schar,
			       localname, ntohs(sess->sock.in.sin_port),
			       remotename, ntohs(sess->peer.in.sin_port));
		    } else {
			printf("%s:%d %s %s:%d is on fd %d%s\n",
			       localname, ntohs(sess->sock.in.sin_port),
			       ((sess->flags & ZTCP_LISTEN) ? "-<" :
				((sess->flags & ZTCP_INBOUND) ? "<-" : "->")),
			       remotename, ntohs(sess->peer.in.sin_port),
			       sess->fd,
			       (sess->flags & ZTCP_ZFTP) ? " ZFTP" : "");
		    }
		}
	    }
	    return 0;
	}
	else if (!args[1]) {
	    destport = htons(23);
	}
	else {

	    srv = getservbyname(args[1],"tcp");
	    if (srv)
		destport = srv->s_port;
	    else
		destport = htons(atoi(args[1]));
	}
	
	desthost = ztrdup(args[0]);
	
	zthost = zsh_getipnodebyname(desthost, AF_INET, 0, &herrno);
	if (!zthost || errflag) {
	    zwarnnam(nam, "host resolution failure: %s", desthost);
	    zsfree(desthost);
	    return 1;
	}
	
	sess = tcp_socket(PF_INET, SOCK_STREAM, 0, 0);

	if (!sess) {
	    zwarnnam(nam, "unable to allocate a TCP session slot");
	    zsfree(desthost);
	    return 1;
	}

#ifdef SO_OOBINLINE
	len = 1;
	setsockopt(sess->fd, SOL_SOCKET, SO_OOBINLINE, (char *)&len, sizeof(len));
#endif

	if (sess->fd < 0) {
	    zwarnnam(nam, "socket creation failed: %e", errno);
	    zsfree(desthost);
	    zts_delete(sess);
	    return 1;
	}
	
	for (addrp = zthost->h_addr_list; err && *addrp; addrp++) {
	    if (zthost->h_length != 4)
		zwarnnam(nam, "address length mismatch");
	    do {
		err = tcp_connect(sess, *addrp, zthost, destport);
	    } while (err && errno == EINTR && !errflag);
	}
	
	if (err) {
	    zwarnnam(nam, "connection failed: %e", errno);
	    tcp_close(sess);
	    zsfree(desthost);
	    return 1;
	}
	else
	{
	    if (targetfd) {
		sess->fd = redup(sess->fd, targetfd);
		if (sess->fd < 0) {
		    zerrnam(nam, "could not duplicate socket fd to %d: %e", targetfd, errno);
		    zsfree(desthost);
		    tcp_close(sess);
		    return 1;
		}
	    }

	    setiparam_no_convert("REPLY", (zlong)sess->fd);

	    if (verbose)
		printf("%s:%d is now on fd %d\n",
			desthost, destport, sess->fd);
	}
	
	zsfree(desthost);
    }

    return 0;
}
MyHostInfo::MyHostInfo(string& hostName,hostType type)
{
	#ifdef UNIX
		searchHostDB = 0;
	#endif

	try 
	{
		if (type == NAME)
		{
			//	¡¾gethostbyname¡¿
			// Retrieve host by name
			hostPtr = gethostbyname(hostName.c_str());

			if (hostPtr == NULL)
			{
				#ifdef WINDOWS_XP
					int errorCode;
					string errorMsg = "";
					detectErrorGethostbyname(&errorCode,errorMsg);
					MyException gethostbynameException(errorCode,errorMsg);
					throw gethostbynameException;
				#endif
	
				#ifdef UNIX
					MyException gethostbynameException(0,"unix: error getting host by name");
					throw gethostbynameException;
				#endif
			}
        }
		else if (type == ADDRESS)
		{
			// Retrieve host by address
		    unsigned long netAddr = inet_addr(hostName.c_str());
			if (netAddr == -1)
			{
				MyException inet_addrException(0,"Error calling inet_addr()");
				throw inet_addrException;
			}

			//	¡¾gethostbyaddr¡¿
	        hostPtr = gethostbyaddr((char *)&netAddr, sizeof(netAddr), AF_INET);
			if (hostPtr == NULL)
			{
				#ifdef WINDOWS_XP
					int errorCode;
					string errorMsg = "";
					detectErrorGethostbyaddr(&errorCode,errorMsg);
					MyException gethostbyaddrException(errorCode,errorMsg);
					throw gethostbyaddrException;
				#endif
	
				#ifdef UNIX
					MyException gethostbynameException(0,"unix: error getting host by name");
					throw gethostbynameException;
				#endif
			}
        }
		else
		{
			MyException unknownTypeException(0,"unknown host type: host name/address has to be given ");
			throw unknownTypeException;
		}
    }
	catch(MyException& excp)
	{
		excp.response();
		exit(1);
	}
}
示例#11
0
static int serve_client(CHSOCK *chsock, int sock)
{
    int i, stat = 0;
    char *inet_ntoa();
    char *hostname;  /* points to the remote host's name string */

    CLIENT *client = NULL;
    struct hostent *hp; /* pointer to host info for remote host */

    close(chsock->ls); /* Close the listen socket inherited from the daemon. */

    /* Look up the host information for the remote host
     * that we have connected with.  Its internet address
     * was returned by the accept call, in the main
     * daemon loop above.
     */
    hp = gethostbyaddr ((char *) &chsock->peeraddr_in.sin_addr,
       sizeof (struct in_addr),
       chsock->peeraddr_in.sin_family);

    if (hp == NULL) 
    {
        /* The information is unavailable for the remote
         * host.  Just format its internet address to be
         * printed out in the logging information.  The
         * address will be shown in "internet dot format".
         */
        hostname = inet_ntoa(chsock->peeraddr_in.sin_addr);
    } 
    else 
    {
        hostname = hp->h_name;  /* point to host's name */
    }

    /* The port number must be converted first to host byte
     * order before printing.  On most hosts, this is not
     * necessary, but the ntohs() call is included here so
     * that this program could easily be ported to a host
     * that does require it.
     */
    fprintf(stderr, "%s: %s: info: startup from %s port %u\n",
        timestamp(), ProgName, hostname, ntohs(chsock->peeraddr_in.sin_port));

    /* Set the socket for a lingering, graceful close.
     * This will cause a final close of this socket to wait until all of the
     * data sent on it has been received by the remote host.
     */
    chsock->linger.l_onoff  =1;
    chsock->linger.l_linger =1;
    if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &chsock->linger,
        sizeof(struct linger)) == -1) 
    {
        fprintf(stderr, "%s: %s: error: set socket options failed: %s\n", 
            timestamp(), ProgName, strerror(errno)); 
        return 1;
    }

    for ( i = 0; i < chsock->conf->nclients; i++ )
    {
        client = chsock->conf->clients[i];
        if ( !strncmp(client->hostname, hostname, strlen(client->hostname)) )
        {
            break;
        }
    }

    if ( i == chsock->conf->nclients )
    {
        fprintf(stderr, "%s: %s: info: refused connection with client %s: ", 
            timestamp(), ProgName, hostname); 
        fprintf(stderr, "not in configuration\n");
        return 1;
    }

    if ( client->recv_from )
    {
        fprintf(stderr, "%s: %s: info: receive from client \"%s\" enabled\n",
            timestamp(), ProgName, hostname); 
        return serve_client_in(client,sock,chsock->conf->datadir,hostname);
    }
    else if ( client->send_to )
    {
        fprintf(stderr, "%s: %s: info: send to client \"%s\" enabled\n",
            timestamp(), ProgName, hostname); 
        return serve_client_out(client,sock,chsock->conf->datadir,hostname);
    }

    fprintf(stderr, "%s: %s: error: connection with %s aborted: ",
            timestamp(), ProgName, hostname); 
    fprintf(stderr, "parameters 'recv_from' and 'send_to' not set in config\n");
    return 1;

} /* serve_client() */
示例#12
0
int main(int argc, char **argv)
{
	char Buffer[128];
	// default to localhost
	char *server_name= "localhost";
	unsigned short port = DEFAULT_PORT;
	int retval, loopflag = 0;
	int i, loopcount, maxloop=-1;
	unsigned int addr;
	int socket_type = DEFAULT_PROTO;
	struct sockaddr_in server;
	struct hostent *hp;
	WSADATA wsaData;
	SOCKET  conn_socket;

	if (argc >1)
	{
		for(i=1; i<argc; i++)
		{
			if ((argv[i][0] == '-') || (argv[i][0] == '/'))
			{
				switch(tolower(argv[i][1]))
				{
				case 'p':
					if (!stricmp(argv[i+1], "TCP"))
						socket_type = SOCK_STREAM;
					else if (!stricmp(argv[i+1], "UDP"))
						socket_type = SOCK_DGRAM;
					else
						Usage(argv[0]);
					i++;
					break;

				case 'n':
					server_name = argv[++i];
					break;

				case 'e':
					port = atoi(argv[++i]);
					break;

				case 'l':
					loopflag =1;
					if (argv[i+1]) {
						if (argv[i+1][0] != '-') 
							maxloop = atoi(argv[i+1]);
					}
					else
						maxloop = -1;
					i++;
					break;

				default:
					Usage(argv[0]);
					break;
				}
			}
			else
				Usage(argv[0]);
		}
	}

	if ((retval = WSAStartup(0x202, &wsaData)) != 0)
	{
		fprintf(stderr,"Client: WSAStartup() failed with error %d\n", retval);
		WSACleanup();
		return -1;
	}
	else
		printf("Client: WSAStartup() is OK.\n");

	if (port == 0)
	{
		Usage(argv[0]);
	}

	// Attempt to detect if we should call gethostbyname() or gethostbyaddr()
	if (isalpha(server_name[0]))
	{   // server address is a name
		hp = gethostbyname(server_name);
	}

	else
	{ // Convert nnn.nnn address to a usable one
		addr = inet_addr(server_name);
		hp = gethostbyaddr((char *)&addr, 4, AF_INET);
	}

	if (hp == NULL )
	{
		fprintf(stderr,"Client: Cannot resolve address \"%s\": Error %d\n", server_name, WSAGetLastError());
		WSACleanup();
		exit(1);
	}
	else
		printf("Client: gethostbyaddr() is OK.\n");

	// Copy the resolved information into the sockaddr_in structure
	memset(&server, 0, sizeof(server));
	memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);
	server.sin_family = hp->h_addrtype;
	server.sin_port = htons(port);

	conn_socket = socket(AF_INET, socket_type, 0); /* Open a socket */
	if (conn_socket <0 )
	{
		fprintf(stderr,"Client: Error Opening socket: Error %d\n", WSAGetLastError());
		WSACleanup();
		return -1;
	}
	else
		printf("Client: socket() is OK.\n");

	// Notice that nothing in this code is specific to whether we 
	// are using UDP or TCP.
	// We achieve this by using a simple trick.
	//    When connect() is called on a datagram socket, it does not 
	//    actually establish the connection as a stream (TCP) socket
	//    would. Instead, TCP/IP establishes the remote half of the
	//    (LocalIPAddress, LocalPort, RemoteIP, RemotePort) mapping.
	//    This enables us to use send() and recv() on datagram sockets,
	//    instead of recvfrom() and sendto()
	printf("Client: Client connecting to: %s.\n", hp->h_name);
	if (connect(conn_socket, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
	{
		fprintf(stderr,"Client: connect() failed: %d\n", WSAGetLastError());
		WSACleanup();
		return -1;
	}
	else
		printf("Client: connect() is OK.\n");

	// Test sending some string
	loopcount = 0;
	while(1)
	{
		wsprintf(Buffer,"This is a test message from client #%d", loopcount++);
		retval = send(conn_socket, Buffer, sizeof(Buffer), 0);
		if (retval == SOCKET_ERROR)
		{
			fprintf(stderr,"Client: send() failed: error %d.\n", WSAGetLastError());
			WSACleanup();
			return -1;
		}
		else
			printf("Client: send() is OK.\n");
		printf("Client: Sent data \"%s\"\n", Buffer);

		retval = recv(conn_socket, Buffer, sizeof(Buffer), 0);
		if (retval == SOCKET_ERROR)
		{
			fprintf(stderr,"Client: recv() failed: error %d.\n", WSAGetLastError());
			closesocket(conn_socket);
			WSACleanup();
			return -1;
		}
		else
			printf("Client: recv() is OK.\n");

		// We are not likely to see this with UDP, since there is no
		// 'connection' established.
		if (retval == 0)
		{
			printf("Client: Server closed connection.\n");
			closesocket(conn_socket);
			WSACleanup();
			return -1;
		}
		printf("Client: Received %d bytes, data \"%s\" from server.\n", retval, Buffer);

		if (!loopflag)
		{
			printf("Client: Terminating connection...\n");
			break;
		}
		else
		{
			if ((loopcount >= maxloop) && (maxloop >0))
				break;
		}
	}
	closesocket(conn_socket);
	WSACleanup();
	return 0;

}
示例#13
0
文件: getaddrinfo.c 项目: jokester/eb
/*
 * getnameinfo().
 */
int
getnameinfo(const struct sockaddr *sa, socklen_t salen, char *node,
    socklen_t nodelen, char *serv, socklen_t servlen, int flags)
{
    const struct sockaddr_in *sa_in = (const struct sockaddr_in *)sa;
    struct hostent *hostent;
    struct servent *servent;
    char *ntoa_address;
    int saved_h_errno;
    int result = 0;

#ifdef ENABLE_PTHREAD
    pthread_mutex_lock(&gai_mutex);
#endif

    saved_h_errno = h_errno;

    if (sa_in->sin_family != PF_INET) {
	result = EAI_FAMILY;
	goto end;
    } else if (node == NULL && serv == NULL) {
	result = EAI_NONAME;
	goto end;
    }

    if (serv != NULL && servlen > 0) {
	if (flags & NI_NUMERICSERV)
	    servent = NULL;
	else if (flags & NI_DGRAM)
	    servent = getservbyport(sa_in->sin_port, "udp");
	else
	    servent = getservbyport(sa_in->sin_port, "tcp");

	if (servent != NULL) {
	    if (servlen <= strlen(servent->s_name)) {
		result = EAI_OVERFLOW;
		goto end;
	    }
	    strcpy(serv, servent->s_name);
	} else {
	    if (servlen <= itoa_length(ntohs(sa_in->sin_port))) {
		result = EAI_OVERFLOW;
		goto end;
	    }
	    sprintf(serv, "%d", ntohs(sa_in->sin_port));
	}
    }

    if (node != NULL && nodelen > 0) {
	if (flags & NI_NUMERICHOST)
	    hostent = NULL;
	else {
	    hostent = gethostbyaddr((char *)&sa_in->sin_addr,
		sizeof(struct in_addr), AF_INET);
	}
	if (hostent != NULL) {
	    if (nodelen <= strlen(hostent->h_name)) {
		result = EAI_OVERFLOW;
		goto end;
	    }
	    strcpy(node, hostent->h_name);
	} else {
	    if (flags & NI_NAMEREQD) {
		result = EAI_NONAME;
		goto end;
	    }
	    ntoa_address = inet_ntoa(sa_in->sin_addr);
	    if (nodelen <= strlen(ntoa_address)) {
		result = EAI_OVERFLOW;
		goto end;
	    }
	    strcpy(node, ntoa_address);
	}

    }

  end:
#ifndef WINSOCK
    h_errno = saved_h_errno;
#else
    WSASetLastError(saved_h_errno);
#endif
#ifdef ENABLE_PTHREAD
    pthread_mutex_unlock(&gai_mutex);
#endif
    return result;
}
示例#14
0
文件: getaddrinfo.c 项目: jokester/eb
/*
 * getaddrinfo().
 */
int
getaddrinfo(const char *nodename, const char *servname,
    const struct addrinfo *hints, struct addrinfo **res)
{
    struct addrinfo *head_res = NULL;
    struct addrinfo *tail_res = NULL;
    struct addrinfo *new_res;
    struct sockaddr_in *sa_in;
    struct in_addr **addr_list;
    struct in_addr *addr_list_buf[2];
    struct in_addr addr_buf;
    struct in_addr **ap;
    struct servent *servent;
    struct hostent *hostent;
    const char *canonname = NULL;
    in_port_t port;
    int saved_h_errno;
    int result = 0;

#ifdef ENABLE_PTHREAD
    pthread_mutex_lock(&gai_mutex);
#endif

    saved_h_errno = h_errno;

    if (nodename == NULL && servname == NULL) {
	result = EAI_NONAME;
	goto end;
    }

    if (hints != NULL) {
	if (hints->ai_family != PF_INET && hints->ai_family != PF_UNSPEC) {
	    result = EAI_FAMILY;
	    goto end;
	}
	if (hints->ai_socktype != SOCK_DGRAM
	    && hints->ai_socktype != SOCK_STREAM
	    && hints->ai_socktype != 0) {
	    result = EAI_SOCKTYPE;
	    goto end;
	}
    } else {
	hints = &default_hints;
    }

    if (servname != NULL) {
	if (is_integer(servname))
	    port = htons(atoi(servname));
	else  {
	    if (hints->ai_flags & AI_NUMERICSERV) {
		result = EAI_NONAME;
		goto end;
	    }

	    if (hints->ai_socktype == SOCK_DGRAM)
		servent = getservbyname(servname, "udp");
	    else if (hints->ai_socktype == SOCK_STREAM)
		servent = getservbyname(servname, "tcp");
	    else if (hints->ai_socktype == 0)
		servent = getservbyname(servname, "tcp");
	    else {
		result = EAI_SOCKTYPE;
		goto end;
	    }

	    if (servent == NULL) {
		result = EAI_SERVICE;
		goto end;
	    }
	    port = servent->s_port;
	}
    } else {
	port = htons(0);
    }

    if (nodename != NULL) {
	if (is_address(nodename)) {
	    addr_buf.s_addr = inet_addr(nodename);
	    addr_list_buf[0] = &addr_buf;
	    addr_list_buf[1] = NULL;
	    addr_list = addr_list_buf;

	    if (hints->ai_flags & AI_CANONNAME
		&& !(hints->ai_flags & AI_NUMERICHOST)) {
		hostent = gethostbyaddr((char *)&addr_buf,
		    sizeof(struct in_addr), AF_INET);
		if (hostent != NULL)
		    canonname = hostent->h_name;
		else
		    canonname = nodename;
	    }
	} else {
	    if (hints->ai_flags & AI_NUMERICHOST) {
		result = EAI_NONAME;
		goto end;
	    }

	    hostent = gethostbyname(nodename);
	    if (hostent == NULL) {
		switch (h_errno) {
		case HOST_NOT_FOUND:
		case NO_DATA:
		    result = EAI_NONAME;
		    goto end;
		case TRY_AGAIN:
		    result = EAI_AGAIN;
		    goto end;
		default:
		    result = EAI_FAIL;
		    goto end;
                }
	    }
	    addr_list = (struct in_addr **)hostent->h_addr_list;

	    if (hints->ai_flags & AI_CANONNAME)
		canonname = hostent->h_name;
	}
    } else {
	if (hints->ai_flags & AI_PASSIVE)
	    addr_buf.s_addr = htonl(INADDR_ANY);
	else
	    addr_buf.s_addr = htonl(0x7F000001);
	addr_list_buf[0] = &addr_buf;
	addr_list_buf[1] = NULL;
	addr_list = addr_list_buf;
    }

    for (ap = addr_list; *ap != NULL; ap++) {
	new_res = (struct addrinfo *)malloc(sizeof(struct addrinfo));
	if (new_res == NULL) {
	    if (head_res != NULL)
		freeaddrinfo(head_res);
	    result = EAI_MEMORY;
	    goto end;
	}

	new_res->ai_family = PF_INET;
	new_res->ai_socktype = hints->ai_socktype;
	new_res->ai_protocol = hints->ai_protocol;
	new_res->ai_addr = NULL;
	new_res->ai_addrlen = sizeof(struct sockaddr_in);
	new_res->ai_canonname = NULL;
	new_res->ai_next = NULL;

	new_res->ai_addr = (struct sockaddr *)
	    malloc(sizeof(struct sockaddr_in));
	if (new_res->ai_addr == NULL) {
	    free(new_res);
	    if (head_res != NULL)
		freeaddrinfo(head_res);
	    result = EAI_MEMORY;
	    goto end;
	}

	sa_in = (struct sockaddr_in *)new_res->ai_addr;
	memset(sa_in, 0, sizeof(struct sockaddr_in));
	sa_in->sin_family = PF_INET;
	sa_in->sin_port = port;
	memcpy(&sa_in->sin_addr, *ap, sizeof(struct in_addr));

	if (head_res == NULL)
	    head_res = new_res;
	else
	    tail_res->ai_next = new_res;
	tail_res = new_res;
    }

    if (canonname != NULL && head_res != NULL) {
	head_res->ai_canonname = (char *)malloc(strlen(canonname) + 1);
	if (head_res->ai_canonname != NULL)
	    strcpy(head_res->ai_canonname, canonname);
    }

    *res = head_res;

  end:
#ifndef WINSOCK
    h_errno = saved_h_errno;
#else
    WSASetLastError(saved_h_errno);
#endif
#ifdef ENABLE_PTHREAD
    pthread_mutex_unlock(&gai_mutex);
#endif
    return result;
}
示例#15
0
/*
 * Construct an Internet address representation.
 * If the nflag has been supplied, give
 * numeric value, otherwise try for symbolic name.
 */
char *
inetname(struct in_addr *inp)
{
	char *cp;
	static char line[50];
	struct hostent *hp;
	struct netent *np;
	static char domain[MAXHOSTNAMELEN];
	static int first = 1;
#if defined (WIN32) || defined (cygwin)
        char host_temp[] = "localhost";
#endif

	if (first && !nflag) {
		first = 0;
		if (gethostname(domain, sizeof(domain)) == 0 &&
		    (cp = strchr(domain, '.')))
			(void) strlcpy(domain, cp + 1, sizeof domain);
		else
			domain[0] = '\0';
	}
	cp = NULL;
	if (!nflag && inp->s_addr != INADDR_ANY) {
		int net = inet_netof(*inp);
		int lna = inet_lnaof(*inp);

		if (lna == INADDR_ANY) {
			np = getnetbyaddr(net, AF_INET);
			if (np)
				cp = np->n_name;
		}
		if (cp == NULL) {
			hp = gethostbyaddr((char *)inp, sizeof (*inp), AF_INET);
			if (hp) {
				if ((cp = strchr(hp->h_name, '.')) &&
				    !strcmp(cp + 1, domain))
					*cp = '\0';
#if defined (WIN32) || defined (cygwin)
                                        /* Windows insists on returning the computer name for 127.0.0.1
                                         * even if the hosts file lists something else such as 'localhost'.
                                         * If we are trying to look up 127.0.0.1, just return 'localhost'   */
                                        if (!strcmp(inet_ntoa(*inp),"127.0.0.1"))
                                             cp = host_temp;
                                        else
#endif                                                                          
				cp = hp->h_name;
			}
		}
	}
	if (inp->s_addr == INADDR_ANY)
		snprintf(line, sizeof line, "*");
	else if (cp)
		snprintf(line, sizeof line, "%s", cp);
	else {
		inp->s_addr = ntohl(inp->s_addr);
#define C(x)	((x) & 0xff)
		snprintf(line, sizeof line, "%u.%u.%u.%u",
		    C(inp->s_addr >> 24), C(inp->s_addr >> 16),
		    C(inp->s_addr >> 8), C(inp->s_addr));
	}
	return (line);
}
示例#16
0
int configure (const options_t *options, interface_t *iface,
	       const dhcp_t *dhcp)
{
  route_t *route = NULL;
  route_t *new_route = NULL;
  route_t *old_route = NULL;
  struct hostent *he = NULL;
  char newhostname[HOSTNAME_MAX_LEN] = {0};
  char curhostname[HOSTNAME_MAX_LEN] = {0};
  char *dname = NULL;
  int dnamel = 0;

  if (! options || ! iface || ! dhcp)
    return -1;

  /* Remove old routes
     Always do this as the interface may have >1 address not added by us
     so the routes we added may still exist */
  if (iface->previous_routes)
    {
      for (route = iface->previous_routes; route; route = route->next)
	if (route->destination.s_addr || options->dogateway)
	  {
	    int have = 0;
	    if (dhcp->address.s_addr != 0)
	      for (new_route = dhcp->routes; new_route; new_route = new_route->next)
		if (new_route->destination.s_addr == route->destination.s_addr
		    && new_route->netmask.s_addr == route->netmask.s_addr
		    && new_route->gateway.s_addr == route->gateway.s_addr)
		  {
		    have = 1;
		    break;
		  }
	    if (! have)
	      del_route (iface->name, route->destination, route->netmask,
			 route->gateway, options->metric);
	  }
    }

  /* If we don't have an address, then return */
  if (dhcp->address.s_addr == 0)
    {
      if (iface->previous_routes)
	{
	  free_route (iface->previous_routes);
	  iface->previous_routes = NULL;
	}

      /* Only reset things if we had set them before */
      if (iface->previous_address.s_addr != 0)
	{
	  del_address (iface->name, iface->previous_address,
		       iface->previous_netmask);
	  memset (&iface->previous_address, 0, sizeof (struct in_addr));
	  memset (&iface->previous_netmask, 0, sizeof (struct in_addr));

	  restore_resolv (iface->name);

	  /* we currently don't have a resolvconf style programs for ntp/nis */
	  exec_script (options->script, iface->infofile, "down");
	}
      return 0;
    }

  if (add_address (iface->name, dhcp->address, dhcp->netmask,
		   dhcp->broadcast) < 0 && errno != EEXIST)
    return -1;

  /* Now delete the old address if different */
  if (iface->previous_address.s_addr != dhcp->address.s_addr
      && iface->previous_address.s_addr != 0)
    del_address (iface->name, iface->previous_address, iface->previous_netmask);

#ifdef __linux__
  /* On linux, we need to change the subnet route to have our metric. */
  if (iface->previous_address.s_addr != dhcp->address.s_addr
      && options->metric > 0 && dhcp->netmask.s_addr != INADDR_BROADCAST)
    {
      struct in_addr td;
      struct in_addr tg;
      memset (&td, 0, sizeof (td));
      memset (&tg, 0, sizeof (tg));
      td.s_addr = dhcp->address.s_addr & dhcp->netmask.s_addr;
      add_route (iface->name, td, dhcp->netmask, tg, options->metric);
      del_route (iface->name, td, dhcp->netmask, tg, 0);
    }
#endif

  /* Remember added routes */
  if (dhcp->routes)
    {
      route_t *new_routes = NULL;
      int remember;

      for (route = dhcp->routes; route; route = route->next)
	{
	  /* Don't set default routes if not asked to */
	  if (route->destination.s_addr == 0 && route->netmask.s_addr == 0
	      && ! options->dogateway)
	    continue;

	  remember = add_route (iface->name, route->destination,
				route->netmask,  route->gateway,
				options->metric);
	  /* If we failed to add the route, we may have already added it
	     ourselves. If so, remember it again. */
	  if (remember < 0)
	    for (old_route = iface->previous_routes; old_route;
		 old_route = old_route->next)
	      if (old_route->destination.s_addr == route->destination.s_addr
		  && old_route->netmask.s_addr == route->netmask.s_addr
		  && old_route->gateway.s_addr == route->gateway.s_addr)
		{
		  remember = 1;
		  break;
		}

	  if (remember >= 0)
	    {
	      if (! new_routes)
		{
		  new_routes = xmalloc (sizeof (route_t));
		  memset (new_routes, 0, sizeof (route_t));
		  new_route = new_routes;
		}
	      else
		{
		  new_route->next = xmalloc (sizeof (route_t));
		  new_route = new_route->next;
		}
	      memcpy (new_route, route, sizeof (route_t));
	      new_route -> next = NULL;
	    }
	}

      if (iface->previous_routes)
	free_route (iface->previous_routes);

      iface->previous_routes = new_routes;
    }

  if (options->dodns && dhcp->dnsservers)
    make_resolv(iface->name, dhcp);
  else
    logger (LOG_DEBUG, "no dns information to write");

  if (options->dontp && dhcp->ntpservers)
    make_ntp(iface->name, dhcp);

  if (options->donis && (dhcp->nisservers || dhcp->nisdomain))
    make_nis(iface->name, dhcp);

  /* Now we have made a resolv.conf we can obtain a hostname if we need one */
  if (options->dohostname && ! dhcp->hostname)
    {
      he = gethostbyaddr (inet_ntoa (dhcp->address),
			  sizeof (struct in_addr), AF_INET);
      if (he)
	{
	  dname = he->h_name;
	  while (*dname > 32)
	    dname++;
	  dnamel = dname - he->h_name;
	  memcpy (newhostname, he->h_name, dnamel);
	  newhostname[dnamel] = 0;
	}
    }

  gethostname (curhostname, sizeof (curhostname));

  if (options->dohostname
      || strlen (curhostname) == 0
      || strcmp (curhostname, "(none)") == 0
      || strcmp (curhostname, "localhost") == 0)
    {
      if (dhcp->hostname)
	strcpy (newhostname, dhcp->hostname); 

      if (*newhostname)
	{
	  logger (LOG_INFO, "setting hostname to `%s'", newhostname);
	  sethostname (newhostname, strlen (newhostname));
	}
    }

  write_info (iface, dhcp, options);

  if (iface->previous_address.s_addr != dhcp->address.s_addr ||
      iface->previous_netmask.s_addr != dhcp->netmask.s_addr)
    {
      memcpy (&iface->previous_address,
	      &dhcp->address, sizeof (struct in_addr));
      memcpy (&iface->previous_netmask,
	      &dhcp->netmask, sizeof (struct in_addr));
      exec_script (options->script, iface->infofile, "new");
    }
  else
    exec_script (options->script, iface->infofile, "up");

  return 0;
}
/* good2() reverses the bodies in the if statement */
static void good2()
{
    if(globalReturnsTrue())
    {
        {
            WSADATA wsaData;
            BOOL wsaDataInit = FALSE;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET client = INVALID_SOCKET;
            struct sockaddr_in service;
            struct sockaddr_in serviceClient;
            int serviceClientLen;
            struct hostent *hostInfo;
            FILE * pFile;
            do
            {
                if (0 != WSAStartup(MAKEWORD(2, 2), &wsaData))
                {
                    break;
                }
                wsaDataInit = TRUE;
                listenSocket = socket(PF_INET, SOCK_STREAM, 0);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(LISTEN_PORT);
                if (SOCKET_ERROR == bind(listenSocket, (struct sockaddr*)&service, sizeof(service)))
                {
                    break;
                }
                if (SOCKET_ERROR == listen(listenSocket, LISTEN_BACKLOG))
                {
                    break;
                }
                serviceClientLen = sizeof(serviceClient);
                client = accept(listenSocket, (struct sockaddr*)&serviceClient, &serviceClientLen);
                if (client == INVALID_SOCKET)
                {
                    break;
                }
                if (serviceClient.sin_family != AF_INET)
                {
                    break;
                }
                hostInfo = gethostbyaddr((char*)&serviceClient.sin_addr, sizeof(serviceClient.sin_addr), AF_INET);
                if (hostInfo == NULL)
                {
                    break;
                }
                if (hostInfo->h_name == NULL)
                {
                    break;
                }
                printLine(hostInfo->h_name);
                /* FIX: Copy the host name to a log - do not attempt to use the host name in a security decision */
                pFile = fopen("log.txt", "a+");
                fprintf(pFile, "Host name: %s\n", hostInfo->h_name);
                fclose(pFile);
            }
            while (0);
            if (client != INVALID_SOCKET)
            {
                closesocket(client);
            }
            if (listenSocket != INVALID_SOCKET)
            {
                closesocket(listenSocket);
            }
            if (wsaDataInit)
            {
                WSACleanup();
            }
        }
    }
}
示例#18
0
文件: http.c 项目: Thor1Khan/polipo
void
initHttp()
{
    char *buf = NULL;
    int namelen;
    int n;
    struct hostent *host;

    initHttpParser();

    atom100Continue = internAtom("100-continue");

    if(clientTimeout <= serverTimeout) {
        clientTimeout = serverTimeout + 1;
        do_log(L_WARN, "Value of clientTimeout too small -- setting to %d.\n",
               clientTimeout);
    }

    if(displayName == NULL)
        displayName = internAtom("Polipo");

    if(authCredentials != NULL && authRealm == NULL)
        authRealm = internAtom("Polipo");

    if(allowedClients) {
        allowedNets = parseNetAddress(allowedClients);
        if(allowedNets == NULL)
            exit(1);
    }

    if(allowedPorts == NULL) {
        allowedPorts = makeIntList(0);
        if(allowedPorts == NULL) {
            do_log(L_ERROR, "Couldn't allocate allowedPorts.\n");
            exit(1);
        }
        intListCons(80, 100, allowedPorts);
        intListCons(1024, 0xFFFF, allowedPorts);
    }

    if(tunnelAllowedPorts == NULL) {
        tunnelAllowedPorts = makeIntList(0);
        if(tunnelAllowedPorts == NULL) {
            do_log(L_ERROR, "Couldn't allocate tunnelAllowedPorts.\n");
            exit(1);
        }
        intListCons(22, 22, tunnelAllowedPorts);   /* ssh */
        intListCons(80, 80, tunnelAllowedPorts);   /* HTTP */
        intListCons(109, 110, tunnelAllowedPorts); /* POP 2 and 3*/
        intListCons(143, 143, tunnelAllowedPorts); /* IMAP 2/4 */
        intListCons(443, 443, tunnelAllowedPorts); /* HTTP/SSL */
        intListCons(873, 873, tunnelAllowedPorts); /* rsync */
        intListCons(993, 993, tunnelAllowedPorts); /* IMAP/SSL */
        intListCons(995, 995, tunnelAllowedPorts); /* POP/SSL */
        intListCons(2401, 2401, tunnelAllowedPorts); /* CVS */
        intListCons(5222, 5223, tunnelAllowedPorts); /* Jabber */
        intListCons(9418, 9418, tunnelAllowedPorts); /* Git */
    }

    if(proxyName)
        return;

    buf = get_chunk();
    if(buf == NULL) {
        do_log(L_ERROR, "Couldn't allocate chunk for host name.\n");
        goto fail;
    }

    n = gethostname(buf, CHUNK_SIZE);
    if(n != 0) {
        do_log_error(L_WARN, errno, "Gethostname");
        strcpy(buf, "polipo");
        goto success;
    }
    /* gethostname doesn't necessarily NUL-terminate on overflow */
    buf[CHUNK_SIZE - 1] = '\0';

    if(strcmp(buf, "(none)") == 0 ||
       strcmp(buf, "localhost") == 0 ||
       strcmp(buf, "localhost.localdomain") == 0) {
        do_log(L_WARN, "Couldn't determine host name -- using ``polipo''.\n");
        strcpy(buf, "polipo");
        goto success;
    }

    if(strchr(buf, '.') != NULL)
        goto success;

    host = gethostbyname(buf);
    if(host == NULL) {
        goto success;
    }

    if(host->h_addrtype != AF_INET)
        goto success;

    host = gethostbyaddr(host->h_addr_list[0], host->h_length,  AF_INET);

    if(!host || !host->h_name || strcmp(host->h_name, "localhost") == 0 ||
       strcmp(host->h_name, "localhost.localdomain") == 0)
        goto success;

    namelen = strlen(host->h_name);
    if(namelen >= CHUNK_SIZE) {
        do_log(L_ERROR, "Host name too long.\n");
        goto success;
    }

    memcpy(buf, host->h_name, namelen + 1);

 success:
    proxyName = internAtom(buf);
    if(proxyName == NULL) {
        do_log(L_ERROR, "Couldn't allocate proxy name.\n");
        goto fail;
    }
    dispose_chunk(buf);
    return;

 fail:
    if(buf)
        dispose_chunk(buf);
    exit(1);
    return;
}
示例#19
0
main (int argc, char *argv[])

{
   int rc,            /* system call return code */
       new_sd, sock,  /* server/listen socket descriptors */
       adrlen,        /* sockaddr length */
       cnt;           /* number of bytes I/O */

   struct sockaddr_in myname;  /* Internet socket name */
   struct sockaddr_in *nptr;   /* ptr to get port number */
   struct sockaddr    addr;    /* generic socket name */

   char buf[80];   /* I/O buffer, kind of small  */

   /* For lookup in /etc/hosts file.   */

   struct hostent *hp, *gethostbyaddr();

   /* Identify the server process. */

   printf("\nThis is the network server with pid %d\n",
        getpid() );

   /* As in UNIX domain sockets, create a "listen" socket */

   if (( sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
      printf("network server socket failure %d\n", errno);
      perror("network server");
      exit(1);
   /* Initialize the fields in the Internet socket name
      structure.                                          */

   myname.sin_family = AF_INET;  /* Internet address */
   myname.sin_port = 0;  /* System will assign port #  */
   myname.sin_addr.s_addr = INADDR_ANY;  /* "Wildcard" */

   /* Bind the Internet address to the Internet socket */

   if (bind(sock, &myname, sizeof(myname) ) < 0 ) {
      close(sock);  /* defensive programming  */
      printf("network server bind failure %d\n", errno);
      perror("network server");
      exit(2);
   }

   /*	Get the port number assigned to the Internet socket.
			getsockname() obtains the port number associated
			with the bound socket and returns it as part of the
			information in the sockaddr addr structure.  Note
			that, since the port number is not passed directly
			by this program to any client, the only way to
			"advertise" it is to print it, that is, send it to
			the user's stdout.  Other than this printout, this
			code is not intrinsic to the connectivity process.
	*/

   adrlen = sizeof(addr); /* need int for return value */
   if ( ( rc = getsockname( sock, &addr, &adrlen ) ) < 0 )
	{
      printf("setwork server getsockname failure %d\n",
				errno);
      perror("network server");
      close (sock);
      exit(3);
   }

   /*	DEBUG CODE: the generic address "addr" is used to
			return the socket value obtained from the
			getsockname() call.  Print this information.  In the
			generic structure definition, all but the address
			family is defined as a char string.  After this
			call, the generic address structure addr is used to
			hold information about the client process. */

   printf("\nAfter getsockname():");
   printf(" server listen socket data\n");
   printf("\taddr.sa_family field value is: %d\n",
        addr.sa_family);
   printf("\taddr.sa_data string is %d bytes long;\n",
        sizeof ( addr.sa_data ) );
   printf("\taddr.sa_data string is:");
   for ( cnt = 0: cnt < sizeof (addr.sa_data); cnt++)
        printf(" %x", addr.sa_data[cnt]);
   printf("\n");

   /*	Now "advertise" the port number assigned to the
			socket.  In this example, this port number must be
			used as the second command line parameter when
			starting up the client process.  */

   /*	Note the use of the pointer nptr, with a different
			mapping of the allocated memory, to point to the
			generic address structure. */

   nptr = (struct sockaddr_in *) &addr;  /* port # */
   printf("\n\tnetwork server: server has port number: %d\n",
      ntohs ( nptr -> sin_port ) );

   /*  Mark the socket as a "listen-only" or passive socket */

   if ( listen ( sock, 5 ) < 0 ) {
      printf("network server bind failure %d\n", errno);
      perror("network server");
      close (sock);
      exit(4);
   }

   /* Debug output: information contained in myname structure
      (the Internet socket).                                  */

   printf("Server has set up client socket with values:\n");
   printf("\tInternet address is %lx\n", myname.sin_addr.s_addr);
   printf("\tPort number used is %d\n", myname.sin_port);
   printf("\tInternet family ID is %d\n", myname.sin_family);
   printf("\tValues are filled in after connection request ");
   printf("is accepted.");

   /* Set up "infinite loop" to listen for clients.  Since the
      structure "myname" is bound to the listen socket, the
      socket structure name and socket length parameter
      values are omitted from the accept call.  The bound values
      are used.                                               */

   while (1) {
      if ( ( new_sd = accept ( sock, 0, 0 ) ) < 0 ) {
         printf("network server accept failure %d\n", errno);
         perror("network server");
         close (sock);
         exit(5);
      }

      /* Fork child process to handle client service request */

      if ( ( fork() ) == 0 ) {    /* Child process */

         int pid;

         pid = getpid();   /* PID of child process */
         close (sock); /* Do not need listen socket in child. */

         /* Find out who the client is.  Note the use of the
            generic address structure addr to hold information
            about the (connected) client.                    */

         if ((rc = getpeername( new_sd, &addr, &adrlen )) < 0) {
            printf("network server %d getpeername failure %d\n",
                 pid, errno);
            perror("network server");
            close(new_sd);
            exit(6);
         }
         /* Just for grins, "announce" the client.  Note that,
            since pointer nptr is of type struct sockaddr_in,
            the field names as defined in the structure template
            sockaddr_in can be used to access values in the addr
            generic structure.                               */

         printf("\n\tnetwork server %d:", pid);
         printf(" client socket from host %s\n",
              inet_ntoa ( nptr -> sin_addr ) );
         printf("\t     has port number %d\n",nptr -> sin_port);

         /* Now find all names associated with the client; this
            is the reason for the /etc/hosts file lookup
            declarations.   */

         if (( hp = gethostbyaddr (&nptr -> sin_addr,4,AF_INET))
                  != NULL ) {
            printf ("\tfrom hostname: %s\n\twith aliases: ",
                   hp -> h_name );
            while ( *hp -> h_aliases )
               printf ("\n\t\t\t%s", *hp -> h_aliases++ );
            printf("\n\n");
         }
         else {
            printf("network server %d ", pid);
            printf("gethostbyaddr failure %d\n", h_errno);
            perror("network server");
         }

         /*  Exchange data with client.  Clear buffer first. */

         do {
      
            /* Take your pick, depending on system pedigree.
               The System V function has not been tested as of
               this edition.                               */

            bzero( buf, sizeof(buf)); /* zero buf, BSD call. */
            /* memset (buf,0,sizeof(buf)); /* zero buf, S5. */

            /* Read message from remote client; if message length
               = 0, quit. */

            if (( cnt = read (new_sd, buf, sizeof(buf))) < 0 ) {
               printf("network server %d ", pid);
               printf("socket read failure &d\n", errno);
               perror("network server");
               close(new_sd);
               exit(7);
            }
            else
            if (cnt == 0) {
               printf("network server received message");
               printf(" of length %d\n", cnt);
               printf("network server closing");
               printf(" client connection...\n");
               close (new_sd);
               continue; /* break out of loop */
            }
            else {

               /*  Print out message received from client.  Send
                   a message back.        */

               printf("network server %d received message",pid);
               printf(" of length %d\n", cnt);
               printf("network server %d  received", pid));
               printf(" the message %s\n", buf);
               bzero (buf, sizeof(buf)); /* zero buf, BSD. */
               /* memset(buf,0,sizeof(buf)); /* zero buf, S5. */
               strcpy(buf, "Message from server to client");
               write (new_sd, buf, sizeof(buf));
            }  /* end of message-print else */

         }  /* end of do loop statement */

         while (cnt != 0);  /* do loop condition */
         exit(0);  /* Exit child process */

      } /* End of if-child-process true condition */

      else      /* Not child process; must be parent process */
示例#20
0
static int do_accept(int acc_sock, int *sock, char **host)
{
    int ret;
    struct hostent *h1, *h2;
    static struct sockaddr_in from;
    int len;
/*      struct linger ling; */

    if (!ssl_sock_init())
        return (0);

# ifndef OPENSSL_SYS_WINDOWS
 redoit:
# endif

    memset(&from, 0, sizeof(from));
    len = sizeof(from);
    /*
     * Note: under VMS with SOCKETSHR the fourth parameter is currently of
     * type (int *) whereas under other systems it is (void *) if you don't
     * have a cast it will choke the compiler: if you do have a cast then you
     * can either go for (int *) or (void *).
     */
    ret = accept(acc_sock, (struct sockaddr *)&from, (void *)&len);
    if (ret == INVALID_SOCKET) {
# if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
        int i;
        i = WSAGetLastError();
        BIO_printf(bio_err, "accept error %d\n", i);
# else
        if (errno == EINTR) {
            /*
             * check_timeout();
             */
            goto redoit;
        }
        BIO_printf(bio_err, "accept errno=%d, %s\n", errno, strerror(errno));
# endif
        return (0);
    }

    if (host == NULL)
        goto end;
# ifndef BIT_FIELD_LIMITS
    /* I should use WSAAsyncGetHostByName() under windows */
    h1 = gethostbyaddr((char *)&from.sin_addr.s_addr,
                       sizeof(from.sin_addr.s_addr), AF_INET);
# else
    h1 = gethostbyaddr((char *)&from.sin_addr,
                       sizeof(struct in_addr), AF_INET);
# endif
    if (h1 == NULL) {
        BIO_printf(bio_err, "bad gethostbyaddr\n");
        *host = NULL;
        /* return(0); */
    } else {
        *host = app_malloc(strlen(h1->h_name) + 1, "copy hostname");
        BUF_strlcpy(*host, h1->h_name, strlen(h1->h_name) + 1);

        h2 = gethostbyname(*host);
        if (h2 == NULL) {
            BIO_printf(bio_err, "gethostbyname failure\n");
            closesocket(ret);
            return (0);
        }
        if (h2->h_addrtype != AF_INET) {
            BIO_printf(bio_err, "gethostbyname addr is not AF_INET\n");
            closesocket(ret);
            return (0);
        }
    }
 end:
    *sock = ret;
    return (1);
}
示例#21
0
文件: daemon.c 项目: dank101/4.2BSD
getrequests()
{
	int t;
	union wait status;
	register struct servent *sp;

	/*
	**  Set up the address for the mailer.
	*/

	sp = getservbyname("smtp", "tcp");
	if (sp == NULL)
	{
		syserr("server \"smtp\" unknown");
		goto severe;
	}
	SendmailAddress.sin_family = AF_INET;
	SendmailAddress.sin_addr.s_addr = INADDR_ANY;
	SendmailAddress.sin_port = sp->s_port;

	/*
	**  Try to actually open the connection.
	*/

# ifdef DEBUG
	if (tTd(15, 1))
		printf("getrequests: port 0x%x\n", SendmailAddress.sin_port);
# endif DEBUG

	/* get a socket for the SMTP connection */
	DaemonSocket = socket(AF_INET, SOCK_STREAM, 0, 0);
	if (DaemonSocket < 0)
	{
		/* probably another daemon already */
		syserr("getrequests: can't create socket");
	  severe:
# ifdef LOG
		if (LogLevel > 0)
			syslog(LOG_SALERT, "cannot get connection");
# endif LOG
		finis();
	}

#ifdef DEBUG
	/* turn on network debugging? */
	if (tTd(15, 15))
		(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG, 0, 0);
#endif DEBUG

	if (bind(DaemonSocket, &SendmailAddress, sizeof SendmailAddress, 0) < 0)
	{
		syserr("getrequests: cannot bind");
		(void) close(DaemonSocket);
		goto severe;
	}
	listen(DaemonSocket, 10);

# ifdef DEBUG
	if (tTd(15, 1))
		printf("getrequests: %d\n", DaemonSocket);
# endif DEBUG

	for (;;)
	{
		register int pid;
		auto int lotherend;
		struct sockaddr_in otherend;
		extern int RefuseLA;

		/* see if we are rejecting connections */
		while (getla() > RefuseLA)
			sleep(5);

		/* wait for a connection */
		do
		{
			errno = 0;
			lotherend = sizeof otherend;
			t = accept(DaemonSocket, &otherend, &lotherend, 0);
		} while (t < 0 && errno == EINTR);
		if (t < 0)
		{
			syserr("getrequests: accept");
			sleep(5);
			continue;
		}

		/*
		**  Create a subprocess to process the mail.
		*/

# ifdef DEBUG
		if (tTd(15, 2))
			printf("getrequests: forking (fd = %d)\n", t);
# endif DEBUG

		pid = fork();
		if (pid < 0)
		{
			syserr("daemon: cannot fork");
			sleep(10);
			(void) close(t);
			continue;
		}

		if (pid == 0)
		{
			extern struct hostent *gethostbyaddr();
			register struct hostent *hp;
			extern char *RealHostName;	/* srvrsmtp.c */
			char buf[MAXNAME];

			/*
			**  CHILD -- return to caller.
			**	Collect verified idea of sending host.
			**	Verify calling user id if possible here.
			*/

			/* determine host name */
			hp = gethostbyaddr(&otherend.sin_addr, sizeof otherend.sin_addr, AF_INET);
			if (hp != NULL)
				(void) sprintf(buf, "%s.ARPA", hp->h_name);
			else
				/* this should produce a dotted quad */
				(void) sprintf(buf, "%lx", otherend.sin_addr.s_addr);
			RealHostName = newstr(buf);

			(void) close(DaemonSocket);
			InChannel = fdopen(t, "r");
			OutChannel = fdopen(t, "w");
# ifdef DEBUG
			if (tTd(15, 2))
				printf("getreq: returning\n");
# endif DEBUG
# ifdef LOG
			if (LogLevel > 11)
				syslog(LOG_DEBUG, "connected, pid=%d", getpid());
# endif LOG
			return;
		}

		/*
		**  PARENT -- wait for child to terminate.
		**	Perhaps we should allow concurrent processing?
		*/

# ifdef DEBUG
		if (tTd(15, 2))
		{
			sleep(2);
			printf("getreq: parent waiting\n");
		}
# endif DEBUG

		/* close the port so that others will hang (for a while) */
		(void) close(t);

		/* pick up old zombies */
		while (wait3(&status, WNOHANG, 0) > 0)
			continue;
	}
	/*NOTREACHED*/
}
示例#22
0
void main(int argc, char *argv[])
{
  if ( argc < 3 ) {
    fprintf(stderr, "Usage: %s <hostname> <masterport>\n", argv[0]);
    exit(1);
  }
  char *str = argv[1];
  char buf[LEN] = "Player Reporting";
  int cport, lport, rport, nport, id, port = 8888, nplayers, nextplayer;
  int len;
  int32_t info;
  struct sockaddr_in sin, incoming;
  struct hostent *ihp;
  int messageType, hopsLeft;
  port = atoi(argv[2]);
  srand(0);
  //printf("\nTriggering Send Message By Host:: %s", str);
  fflush(stdout);
  int p1, player;
  int master = createSendingSocket(str, port);
  len = send(master, buf, strlen(buf), 0);
  if ( len != strlen(buf) ) {
      perror("send");
      exit(1);
    }
  //printf("\nSent Message");
  //printf("\nReady to receive message: ");
  memset(&buf[0], 0, LEN);


  len = recv(master, &info, sizeof(uint32_t), 0);
  if ( len < 0 ) {
  perror("recv");
  exit(1);
  }
  id = ntohl(info);
  printf("\nConnected as player %d", ntohl(info));

  len = recv(master, &info, sizeof(uint32_t), 0);
  if ( len < 0 ) {
  perror("recv");
  exit(1);
  }
  nplayers = ntohl(info);

  len = recv(master, &info, sizeof(uint32_t), 0);
  if ( len < 0 ) {
  perror("recv");
  exit(1);
  }
  cport = ntohl(info);
  //printf("\nRecieved CPORT: %d", ntohl(info));

  len = recv(master, &info, sizeof(uint32_t), 0);
  if ( len < 0 ) {
  perror("recv");
  exit(1);
  }
  lport = ntohl(info);
  //printf("\nRecieved LPORT: %d", ntohl(info));

  len = recv(master, &info, sizeof(uint32_t), 0);
  if ( len < 0 ) {
  perror("recv");
  exit(1);
  }
  rport = ntohl(info);
  //printf("\nRecieved RPORT: %d", ntohl(info));


  //Creating player specific port
  int playerport = createReceiveSocket(cport, (struct sockaddr_in *)&sin, 10);



  //Sending readiness to master

  info = htonl(1);
    len = send(master, &info, sizeof(uint32_t), 0);
    if ( len != sizeof(uint32_t) ) {
        perror("send");
        exit(1);
      }

  //get a go ahead from master to connect to right and left players
  len = recv(master, &info, sizeof(uint32_t), 0);
  if ( len < 0 ) {
  perror("recv");
  exit(1);
  }
  //printf("\nRecieved GoAhead: %d", ntohl(info));

  //After this go ahead. Lets connect this node to the left and right nodes.

  
  //lplayer = createSendingSocket(str, lport);
  //rplayer = createSendingSocket(str, rport);
  close(master);

  while(1)
  {
    len = sizeof(sin);
    p1 = accept(playerport, (struct sockaddr *)&incoming, &len);
    if ( p1 < 0 ) {
      perror("bind2:");
      exit(p1);
    }
    ihp = gethostbyaddr((char *)&incoming.sin_addr, 
      sizeof(struct in_addr), AF_INET);
    //printf(">> Connected to %s\n", ihp->h_name);


    //Read the data

    len = recv(p1, &info, sizeof(uint32_t), 0);
    if ( len < 0 ) {
    perror("recv");
    exit(1);
    }
    messageType = ntohl(info);
    //printf("\nRecieved Message Type: %d", ntohl(info));
    if(messageType == 2)
      exit(0);


    len = recv(p1, &info, sizeof(uint32_t), 0);
    if ( len < 0 ) {
    perror("recv");
    exit(1);
    }
    hopsLeft = ntohl(info);
    //printf("\nRecieved Hops Left: %d", ntohl(info));

    memset(&buf[0], 0, LEN);
    len = recv(p1, buf, LEN, 0);
    if ( len < 0 ) {
    perror("recv");
    exit(1);
    }
    //printf("\n%s - Received Sequence\n", buf);

    if(hopsLeft == 1)
    {
      //todo
      sprintf(buf, "%s,%d", buf, id);
      printf("\n I'm it\n");
      
      master = createSendingSocket(str, port);
      len = send(master, buf, strlen(buf), 0);
      if ( len != strlen(buf) ) {
          perror("send");
          exit(1);
        }
      continue;
    }


    if(rand() % 2 == 0){
      nport = lport;
      if((id-1) < 0)
        nextplayer = nplayers-1;
      else
        nextplayer = id - 1;
    }
    else{
      nport = rport;
      nextplayer = (id+1)%nplayers;
    }

    printf("\nSending potato to %d", nextplayer);

    player = createSendingSocket(str, nport);
    info = htonl(1);
    len = send(player, &info, sizeof(uint32_t), 0);
    if ( len != sizeof(uint32_t) ) {
        perror("send");
        exit(1);
      }


    info = htonl(hopsLeft-1);
    len = send(player, &info, sizeof(uint32_t), 0);
    if ( len != sizeof(uint32_t) ) {
        perror("send");
        exit(1);
      }

    sprintf(buf, "%s,%d", buf, id);
      
    len = send(player, buf, strlen(buf), 0);
    if ( len != strlen(buf) ) {
        perror("send");
        exit(1);
      }

    close(player);


    close(p1);


  }


  //neighbours have been connected.













  fflush(stdout);
  close(master);
  printf("\n");
  return;
}
void paimei_connect (void)
{
    hostent      *he;
    sockaddr_in  sin;
    in_addr      addr;
    WSADATA      wsa_data;

    char server[256];

    memset(server, 0, sizeof(server));
    strcpy(server, "127.0.0.1");

    // if we are already connected then to do nothing.
    if (connection)
        return;

    if (Gettext("PaiMei Server:", server, 0x00, NM_NONAME, FIXEDFONT) == -1)
        return;

    // initialize winsock.
    if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0)
    {
        olly_add_to_list(0, 1, "[!] "PLUGIN_NAME"> WSAStartup() failed.");
        return;
    }

    // confirm that the requested winsock version is supported.
    if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
    {
        WSACleanup();
        olly_add_to_list(0, 1, PLUGIN_NAME"> Winsock version 2.2 not found.");
        return;
    }

    // if the provided server address is a hostname, then resolve it with gethostbyname().
    if (isalpha(server[0]))
    {
        if ((he = gethostbyname(server)) == NULL)
        {
            olly_add_to_list(0, 1, "[!] "PLUGIN_NAME"> Unable to resolve name: %s", server);
            return;
        }
    }
    // otherwise resolve the server address with gethostbyaddr().
    else
    {
        addr.s_addr = inet_addr(server);

        if ((he = gethostbyaddr((char *)&addr, sizeof(struct in_addr), AF_INET)) == NULL)
        {
            olly_add_to_list(0, 1, "[!] "PLUGIN_NAME"> Unable to resolve address");
            return;
        }
    }

    // create a socket.
    if ((connection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
    {
        WSACleanup();
        olly_add_to_list(0, 1, "[!] "PLUGIN_NAME"> Failed to create socket.");
        return;
    }

    // connect to the server.
    sin.sin_family = AF_INET;
    sin.sin_addr   = *((LPIN_ADDR)*he->h_addr_list);
    sin.sin_port   = htons(7033);

    if (connect(connection, (SOCKADDR *) &sin, sizeof(sin)) == SOCKET_ERROR)
    {
        WSACleanup();
        olly_add_to_list(0, 1, "[!] "PLUGIN_NAME"> Failed to connect to server.");
        return;
    }
}
示例#24
0
int single_request(char *hostname, int port)
{
    int sockfd;
    int status;

    struct sockaddr_in server_addr;
    struct hostent *hostp = NULL;
    //Linux manpage says socklen_t, Solaris says size_t
    //socklen_t sockaddrsize = sizeof(struct sockaddr);
    size_t sockaddrsize = sizeof(struct sockaddr);

    char buf[1024];
    int buflen = 1024;
    int len;
    char *servername;
    char *ptr;
    int i;

    printf("opening socket...\n");
    sockfd = socket(PF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
	perror("socket");
	return(-1);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);

    hostp = gethostbyname(hostname);
    if (NULL == hostp) {
	hostp = gethostbyaddr(hostname, strlen(hostname), AF_INET);
	if (NULL == hostp) {
	    perror("Error resolving server address");
	    return(-1);
	}
    }

    server_addr.sin_addr = *((struct in_addr *)hostp->h_addr);

    printf("connecting...\n");
    status = connect(sockfd, (struct sockaddr *) &server_addr, sockaddrsize);
    if (-1 == status) {
        perror("connect");
	return(-1);
    }

    ssl = SSL_new(ssl_ctx);
    if (!ssl) {
	fprintf(stderr, "SSL_new: failure\n");
	return(-1);
    }

    status = SSL_set_fd(ssl, sockfd);
    if (!status) {
	fprintf(stderr, "SSL_set_fd: failure\n");
	return(-1);
    }

    status = SSL_connect(ssl);
    if (status != 1) {
	fprintf(stderr, "SSL_connect: failure\n");

	printf("status %d\n", status);
	SSL_load_error_strings();
	printf("%d: ", SSL_get_error(ssl, status));
	printf("%s\n", ERR_error_string(SSL_get_error(ssl, status), NULL));

	return(-1);
    }

    //XXX: odd hack
    write_string("GET /\n");
	
    for (;;) {
	char marker[] = "<!-- PKG: ";
	i = strlen(marker);
	len = myssl_readline(ssl, buf, buflen);
	if (len <= 0) {
	    fprintf(stderr, "Doesn't seem to be a PKG\n");
	    return(-1);
	}
	if (!strncmp(buf, marker, i)) break;
    }

    servername = &buf[i];
    ptr = strstr(servername, " -->");
    if (ptr) ptr[0] = 0;

    SSL_shutdown(ssl);
    shutdown(sockfd, 2);

    printf("server name: %s\n", servername);
    sockfd = socket(PF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
	perror("socket");
	return(-1);
    }

    status = connect(sockfd, (struct sockaddr *) &server_addr, sockaddrsize);
    if (-1 == status) {
        perror("connect");
	return(-1);
    }

    status = SSL_set_fd(ssl, sockfd);
    if (!status) {
	fprintf(stderr, "SSL_set_fd: failure\n");
	return(-1);
    }

    status = SSL_connect(ssl);
    if (status != 1) {
	fprintf(stderr, "SSL_connect: failure\n");
	return(-1);
    }

    status = EVP_read_pw_string(password, 100, "share password: "******"error reading password\n");
	return 1;
    }

    write_string("POST /\n");
    write_string("Content-Length: ");

    //Windows doesn't have snprintf?

    sprintf(buf, "%d\n\n", 16 + strlen(emailaddr) + strlen(password));

    write_string(buf);

    sprintf(buf, "mail=%s&password=%s\n", emailaddr, password);

    write_string(buf);

    for (;;) {
	len = myssl_readline(ssl, buf, buflen);
	if (len <= 0) break;
	printf("server: %s", buf);
    }
    status = SSL_shutdown(ssl);
    if (status != 1) {
	fprintf(stderr, "SSL_shutdown: failure\n");
	printf("status %d\n", status);
	SSL_load_error_strings();
	printf("%d: ", SSL_get_error(ssl, status));
	printf("%s\n", ERR_error_string(SSL_get_error(ssl, status), NULL));
    }

    return 1;
}
示例#25
0
文件: rpc.c 项目: alcap-org/AlcapDAQ
void mrpc_server_loop(void)
{
   int i, status, sock, lsock, len, flag;
   struct sockaddr_in serv_addr, acc_addr;
   char str[256];
   struct hostent *phe;
   fd_set readfds;
   struct timeval timeout;

#ifdef _MSC_VER
   {
      WSADATA WSAData;

      /* Start windows sockets */
      if (WSAStartup(MAKEWORD(1, 1), &WSAData) != 0)
         return;
   }
#endif

   /* create a new socket */
   lsock = socket(AF_INET, SOCK_STREAM, 0);

   if (lsock == -1) {
      perror("mrpc_server_loop");
      return;
   }

   /* bind local node name and port to socket */
   memset(&serv_addr, 0, sizeof(serv_addr));
   serv_addr.sin_family = AF_INET;

   serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
   serv_addr.sin_port = htons((short) MSCB_RPC_PORT);

   /* try reusing address */
   flag = 1;
   setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, (char *) &flag, sizeof(INT));

   status = bind(lsock, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
   if (status < 0) {
      perror("mrpc_server_loop");
      return;
   }

   /* listen for connection */
   status = listen(lsock, SOMAXCONN);
   if (status < 0) {
      perror("mrpc_server_loop");
      return;
   }

   printf("Server listening...\n");
   do {
      FD_ZERO(&readfds);
      FD_SET(lsock, &readfds);

      for (i = 0; i < N_MAX_CONNECTION; i++)
         if (rpc_sock[i] > 0)
            FD_SET(rpc_sock[i], &readfds);

      timeout.tv_sec = 0;
      timeout.tv_usec = 100000;

      status = select(FD_SETSIZE, (void *) &readfds, NULL, NULL, (void *) &timeout);

      if (FD_ISSET(lsock, &readfds)) {
         len = sizeof(acc_addr);
         sock = accept(lsock, (struct sockaddr *) &acc_addr, &len);

         /* find new entry in socket table */
         for (i = 0; i < N_MAX_CONNECTION; i++)
            if (rpc_sock[i] == 0)
               break;

         if (i == N_MAX_CONNECTION) {
            printf("Maximum number of connections exceeded\n");
            closesocket(sock);
         } else {
            rpc_sock[i] = sock;

            phe = gethostbyaddr((char *) &acc_addr.sin_addr, 4, AF_INET);
            if (phe != NULL)
               strcpy(str, phe->h_name);
            else
               strcpy(str, (char *) inet_ntoa(acc_addr.sin_addr));

            printf("Open new connection from %s\n", str);
         }
      } else {
         /* check if open connection received data */
         for (i = 0; i < N_MAX_CONNECTION; i++)
            if (rpc_sock[i] > 0 && FD_ISSET(rpc_sock[i], &readfds)) {
               len = mrecv_tcp(rpc_sock[i], net_buffer, NET_BUFFER_SIZE);
               if (len < 0) {
                  /* remove stale fd */
                  mscb_cleanup(rpc_sock[i]);

                  /* close broken connection */
                  printf("Close connection\n");
                  closesocket(rpc_sock[i]);
                  rpc_sock[i] = 0;
               } else {
                  _server_sock = rpc_sock[i];
                  mrpc_execute(rpc_sock[i], net_buffer);
               }
            }
      }

   } while (1);

   printf("Server aborted.\n");
}
示例#26
0
static void getremotename(struct sockaddr_in *from, char *rhost, char *rname) {
    struct sockaddr_in our_sin;
    struct sockaddr_in rmt_sin;
    unsigned rmt_port, rmt_pt;
    unsigned our_port, our_pt;
    FILE *fp;
    char buffer[512], user[80], *cp;
    int s;
    static struct hostent *hp;
    
/* get remote host name */
    
    hp = NULL;
    if(setjmp(byebye) == 0) {
	signal(SIGALRM, timeout);
	alarm(3);
	hp = gethostbyaddr((char *) &from->sin_addr, sizeof(struct in_addr),
			   from->sin_family);
	alarm(0);
    }
    strcpy(rhost, hp ? hp->h_name : (char *) inet_ntoa(from->sin_addr));
    
/*
 * Use one unbuffered stdio stream for writing to and for reading from the
 * RFC931 etc. server. This is done because of a bug in the SunOS 4.1.x
 * stdio library. The bug may live in other stdio implementations, too.
 * When we use a single, buffered, bidirectional stdio stream ("r+" or "w+"
 * mode) we read our own output. Such behaviour would make sense with
 * resources that support random-access operations, but not with sockets.
 */
    
    s = sizeof(our_sin);
    if(getsockname(0, (struct sockaddr *) &our_sin, &s) < 0)
	return;
    
    if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	return;

    if(!(fp = fdopen(s, "r+"))) {
	close(s);
	return;
    }
/* Set up a timer so we won't get stuck while waiting for the server. */
    if(setjmp(byebye) == 0) {
	signal(SIGALRM, timeout);
	alarm(RFC931_TIMEOUT);
	
/*
 * Bind the local and remote ends of the query socket to the same IP
 * addresses as the connection under investigation. We go through all
 * this trouble because the local or remote system might have more than
 * one network address. The RFC931 etc. client sends only port numbers;
 * the server takes the IP addresses from the query socket.
 */
       	our_pt = ntohs(our_sin.sin_port);
	our_sin.sin_port = htons(ANY_PORT);
	
	rmt_sin = *from;
	rmt_pt = ntohs(rmt_sin.sin_port);
	rmt_sin.sin_port = htons(RFC931_PORT);
	
	setbuf(fp, (char *) 0);
	s = fileno(fp);
	
	if(bind(s, (struct sockaddr *) &our_sin, sizeof(our_sin)) >= 0 &&
	   connect(s, (struct sockaddr *) &rmt_sin, sizeof(rmt_sin)) >= 0) {
/*
 * Send query to server. Neglect the risk that a 13-byte write would
 * have to be fragmented by the local system and cause trouble with
 * buggy System V stdio libraries.
 */
	    fprintf(fp, "%u,%u\r\n", rmt_pt, our_pt);
	    fflush(fp);
/*
 * Read response from server. Use fgets()/sscanf() so we can work
 * around System V stdio libraries that incorrectly assume EOF when a
 * read from a socket returns less than requested.
 */
	    if(fgets(buffer, sizeof(buffer), fp) && !ferror(fp) && !feof(fp) &&
	       sscanf(buffer, "%u , %u : USERID :%*[^:]:%79s",
		      &rmt_port, &our_port, user) == 3 &&
	       rmt_pt == rmt_port && our_pt == our_port) {
		
/*
 * Strip trailing carriage return. It is part of the protocol, not
 * part of the data.
 */
		if((cp = (char *)strchr(user, '\r')))
		    *cp = 0;
		strcpy(rname, user);
	    }
	}
	alarm(0);
    }
    fclose(fp);
}
示例#27
0
//	 		       Socket    Src string      Src str len          Src service        Src service len         NUMERIC?
int accept_inet_stream_socket(int sfd, char* src_host, size_t src_host_len, char* src_service, size_t src_service_len, int flags, int accept_flags)
{
    struct sockaddr_storage client_info;
    int client_sfd;

# ifndef _TRADITIONAL_RDNS
    int retval;
# endif

# ifdef _TRADITIONAL_RDNS
    struct sockaddr_storage oldsockaddr;
    socklen_t oldsockaddrlen = sizeof(struct sockaddr_storage);
    struct hostent* he;
    void* addrptr;
    size_t in_addrlen;
    uint16_t sport = 0;
# endif

# ifdef VERBOSE
    const char* errstr;
# endif
    socklen_t addrlen = sizeof(struct sockaddr_storage);

    // Portable behavior
# if LIBSOCKET_LINUX
    if ( -1 == check_error((client_sfd = accept4(sfd,(struct sockaddr*)&client_info,&addrlen,accept_flags)))) // blocks
	return -1;
# else
    if ( -1 == check_error((client_sfd = accept(sfd,(struct sockaddr*)&client_info,&addrlen)))) // blocks
	return -1;
# endif

    if ( src_host_len > 0 || src_service_len > 0 ) // If one of the things is wanted. If you give a null pointer with a positive _len parameter, you won't get the address.
    {
	if ( flags == LIBSOCKET_NUMERIC )
	{
	    flags = NI_NUMERICHOST | NI_NUMERICSERV;
	} else
	{
	    flags = 0; // To prevent errors: Unknown flags are ignored
	}

# ifndef _TRADITIONAL_RDNS
	if ( 0 != (retval = getnameinfo((struct sockaddr*)&client_info,sizeof(struct sockaddr_storage),src_host,src_host_len,src_service,src_service_len,flags)) ) // Write information to the provided memory
	{
# ifdef VERBOSE
	    errstr = gai_strerror(retval);
	    debug_write(errstr);
# endif
	    return -1;
	}
# endif

# ifdef _TRADITIONAL_RDNS
	if ( -1 == check_error(getsockname(sfd,(struct sockaddr*)&oldsockaddr,&oldsockaddrlen)) )
	    return -1;

	if ( oldsockaddrlen > sizeof(struct sockaddr_storage) ) // If getsockname truncated the struct
	    return -1;

	if ( oldsockaddr.ss_family == AF_INET )
	{
	    addrptr = &(((struct sockaddr_in*)&client_info)->sin_addr);
	    in_addrlen = sizeof(struct in_addr);
	    sport = ntohs(((struct sockaddr_in*)&client_info)->sin_port);
	} else if ( oldsockaddr.ss_family == AF_INET6 )
	{
	    addrptr = &(((struct sockaddr_in6*)&client_info)->sin6_addr);
	    in_addrlen = sizeof(struct in6_addr);
	    sport = ntohs(((struct sockaddr_in6*)&client_info)->sin6_port);
	}

	if ( NULL == (he = gethostbyaddr(addrptr,in_addrlen,oldsockaddr.ss_family) ) )
	{
	    check_error(-1);
	    return -1;
	}

	strncpy(src_host,he->h_name,src_host_len);
	snprintf(src_service,src_service_len,"%u",sport);
# endif
    }

    return client_sfd;
}
示例#28
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    int err;
    struct hostent *host;
    u_long addr;
    BOOL errorFlag = FALSE;
    int i = 0;
    int strlength = 0;
    char ch;

    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }

    /*initialize to use winsock2.dll*/
    err = WSAStartup(VersionRequested, &WsaData);
    if(err != 0)
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /*Confirm that the WinSock DLL supports 2.2.*/
    if(LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2 )
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    addr = inet_addr("127.0.0.1");

    host = gethostbyaddr ((const char *)&addr, sizeof(addr), AF_INET );
    if(NULL == host)
    {
        Trace("\nFailed to call gethostbynaddr API to retrive host info, "
                "error code = %u\n", GetLastError());
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }


    /*
    *further check the struct host contains legal DNS name
    *with alphanumeric, dot, underscore and hyphan characters
    */ 
    strlength = (int)strlen(host->h_name); 
    
    for(i = 0; i < strlength; i++)
    {
        ch = host->h_name[i];
        if(!(ch == '.' || ch == '-' || (ch <= 'z' && ch >= 'a') ||
            (ch <= 'Z' && ch >= 'A') || (ch <='9' && ch >= '0') ||
            (ch == '_')))
        {
            errorFlag = TRUE;
        }
    }

    if(errorFlag)
    {
        Trace("\nFailed to call gethostbyaddr API to retrieve host info, "
                "the hostent struct does not contain valid host name "
                "the host name is = %s\n", host->h_name);
               
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
示例#29
0
文件: ident.c 项目: vedicveko/Dibrova
/********************************************************************
 * Function : id_lookup_username
 * Created  : 97/03/31
 * Author   : Joachim Pileborg
 * E-Mail   : [email protected]
 *
 * Try to get a username from a user.
 */
static char *id_lookup_username(struct sockaddr_in sa)
{
  static char        username[256];
  char               string[256];
  struct hostent    *hent;
  struct sockaddr_in saddr;
  int                sock;

  extern int port;

  sprintf(string, "%d, %d\r\n", ntohs(sa.sin_port), port);

  if (!(hent = gethostbyaddr((char *) &sa.sin_addr,
                             sizeof(sa.sin_addr), AF_INET)))
    perror("id_lookup_username(): gethostbyaddr");
  else
  {
    /* connect to the inetd super server */

    saddr.sin_family = hent->h_addrtype;
    saddr.sin_port   = htons(IDENTD_PORT);
    memcpy(&saddr.sin_addr, hent->h_addr, hent->h_length);

    if ((sock = socket(hent->h_addrtype, SOCK_STREAM, 0)) < 0)
    {
      perror("id_lookup_username(): socket");
      return NULL;
    }

    if (connect(sock, (struct sockaddr *) &saddr, sizeof(saddr)) < 0)
    {
      if (errno != ECONNREFUSED)
        perror("id_lookup_username(): connect");
      close(sock);
      return NULL;
    }

    /* write our message to the inetd super server */
    write(sock, &string, strlen(string));

    /* get the reply */
    read(sock, string, 256);

    /* close the socket */
    close(sock);

    /* extract what we need */
    {
      int sport, cport;
      char mtype[256], otype[256];

      sscanf(string, " %d , %d : %s : %s : %s ", &sport, &cport,
             mtype, otype, username);

      if (!strcmp(mtype, "USERID"))
	return username;
      else
        return NULL;
    }
  }

  return NULL;
}
示例#30
0
文件: websync.c 项目: aunali1/exopc
int
get_results(int count)
{
  int sockfd, n, i, clilen;
  int max = 0;
  int min = 0;
  struct hostent *serverent;
  struct sockaddr_in servaddr, cliaddr;        printf("Getting Results\n\n\n");
       
  results_data = malloc(sizeof(SWAMP_RESULTS));  
  totals = malloc(sizeof(FINAL_RESULTS));
  bzero(totals, sizeof(*totals));  

  clilen = sizeof(cliaddr);
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  bzero( &servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(SERV_PORT);

   
  if(n =  bind(sockfd, (struct sockaddr *)&servaddr,  sizeof(servaddr) ) < 0)
    printf("Error on bind:%d\n", errno);

    for( i=1; i<=count; i++){
  
    n = recvfrom(sockfd, results_data, sizeof(*results_data), 0, (struct sockaddr *)&cliaddr, &clilen);

    serverent = gethostbyaddr(  (char *)&cliaddr.sin_addr, 4, AF_INET );

    printf("Results from: %s\n", (*serverent).h_name  );
    printf(" Bytes:%d\n usecs:%d\n bytes/sec:%d\n pages/sec:%f\n",  ntohl(results_data->filesize), 
             ntohl(results_data->usecs), ntohl(results_data->bpms), 
             (1000*((double)(ntohl(results_data->webpages))/ntohl(results_data->usecs))) ); 
    printf ("Done (webpages %d, inpackets %d, outpackets %d)\n\n", ntohl(results_data->webpages), 
             ntohl(results_data->inpackets), ntohl(results_data->outpackets));
  
    /* Tally final results */  
    totals->filesize   += ntohl(results_data->filesize); 
    totals->usecs      += ntohl(results_data->usecs);
    totals->webpages   += ntohl(results_data->webpages);
    totals->inpackets  += ntohl(results_data->inpackets);
    totals->outpackets += ntohl(results_data->outpackets);
    
    if( i == 1){
      min = ntohl(results_data->usecs);
      max = ntohl(results_data->usecs);
    }
    else{
      if(min > ntohl(results_data->usecs))
         min =  ntohl(results_data->usecs);
      else if(max < ntohl(results_data->usecs))
         max = ntohl(results_data->usecs);
    }
   }
 
    /* Print out combined totals */
    printf("----------------------------------\n TOTALS:\n");
    printf("Total Bytes: %d\n", totals->filesize);
    printf("Mininum usecs: %d\n", min);
    printf("Maximum usecs: %d\n", max);
    printf("Average usces: %d\n", totals->usecs/count);
    printf("Pages/sec (max secs): %f\n", (1000*((double)totals->webpages)/max) );
    printf("Bytes/sec (max secs): %f\n\n",(1000*((double)totals->filesize)/max) );
    printf("Webpages: %d\n", totals->webpages);
    printf("Inpackets: %d\n", totals->inpackets);
    printf("Outpackets: %d\n", totals->outpackets);
	  
 return(0);
}