示例#1
0
bool
ProxyAutoConfig::SrcAddress(const NetAddr *remoteAddress, nsCString &localAddress)
{
  PRFileDesc *fd;
  fd = PR_OpenUDPSocket(remoteAddress->raw.family);
  if (!fd)
    return false;

  PRNetAddr prRemoteAddress;
  NetAddrToPRNetAddr(remoteAddress, &prRemoteAddress);
  if (PR_Connect(fd, &prRemoteAddress, 0) != PR_SUCCESS) {
    PR_Close(fd);
    return false;
  }

  PRNetAddr localName;
  if (PR_GetSockName(fd, &localName) != PR_SUCCESS) {
    PR_Close(fd);
    return false;
  }

  PR_Close(fd);
  
  char dottedDecimal[128];
  if (PR_NetAddrToString(&localName, dottedDecimal, sizeof(dottedDecimal)) != PR_SUCCESS)
    return false;
  
  localAddress.Assign(dottedDecimal);

  return true;
}
示例#2
0
static int
prldap_getpeername( LDAP *ld, struct sockaddr *addr, char *buffer, int buflen)
{
    PRLDAPIOSocketArg *sa;
    PRFileDesc	*fd;
    PRNetAddr	iaddr;
    int		ret;

    if (NULL != ld) {
        ret = prldap_socket_arg_from_ld( ld, &sa );
        if (ret != LDAP_SUCCESS) {
            return (-1);
        }
        ret = PR_GetPeerName(sa->prsock_prfd, &iaddr);
        if( ret == PR_FAILURE ) {
            return( -1 );
        }
        *addr = *((struct sockaddr *)&iaddr.raw);
        ret = PR_NetAddrToString(&iaddr, buffer, buflen);
        if( ret == PR_FAILURE ) {
            return( -1 );
        }
        return (0);
    }
    return (-1);
}
// Used to return connection info to Dashboard.cpp
void
nsSocketTransportService::AnalyzeConnection(nsTArray<SocketInfo> *data,
        struct SocketContext *context, bool aActive)
{
    if (context->mHandler->mIsPrivate)
        return;
    PRFileDesc *aFD = context->mFD;

    PRFileDesc *idLayer = PR_GetIdentitiesLayer(aFD, PR_NSPR_IO_LAYER);

    NS_ENSURE_TRUE_VOID(idLayer);

    bool tcp = PR_GetDescType(idLayer) == PR_DESC_SOCKET_TCP;

    PRNetAddr peer_addr;
    PR_GetPeerName(aFD, &peer_addr);

    char host[64] = {0};
    PR_NetAddrToString(&peer_addr, host, sizeof(host));

    uint16_t port;
    if (peer_addr.raw.family == PR_AF_INET)
        port = peer_addr.inet.port;
    else
        port = peer_addr.ipv6.port;
    port = PR_ntohs(port);
    uint64_t sent = context->mHandler->ByteCountSent();
    uint64_t received = context->mHandler->ByteCountReceived();
    SocketInfo info = { nsCString(host), sent, received, port, aActive, tcp };

    data->AppendElement(info);
}
NSAPI_PUBLIC int INTnet_addr_to_string(const PRNetAddr *addr, char *buf, int sz)
{
    if (addr->raw.family != PR_AF_INET || sz < sizeof("255.255.255.255"))
        return PR_NetAddrToString(addr, buf, sz);

    unsigned char *octets = (unsigned char *)&addr->inet.ip;
    const char *string;

    string = octet_strings[octets[0]];
    while (*string)
       *buf++ = *string++;

    *buf++ = '.';

    string = octet_strings[octets[1]];
    while (*string)
       *buf++ = *string++;

    *buf++ = '.';

    string = octet_strings[octets[2]];
    while (*string)
       *buf++ = *string++;

    *buf++ = '.';

    string = octet_strings[octets[3]];
    while (*string)
       *buf++ = *string++;

    *buf = '\0';

    return PR_SUCCESS;
}
示例#5
0
static PRStatus PrintAddress(const PRNetAddr* address)
{
    PRNetAddr translation;
    char buffer[ADDR_BUFFER];
    PRStatus rv = PR_NetAddrToString(address, buffer, sizeof(buffer));
    if (PR_FAILURE == rv) PL_FPrintError(err, "PR_NetAddrToString");
    else
    {
        PR_fprintf(err, "\t%s\n", buffer);
        rv = PR_StringToNetAddr(buffer, &translation);
        if (PR_FAILURE == rv) PL_FPrintError(err, "PR_StringToNetAddr");
        else
        {
            PRSize addr_len = PR_NETADDR_SIZE(address);
            if (0 != memcmp(address, &translation, addr_len))
            {
                PR_fprintf(err, "Address translations do not match\n");
                DumpAddr(address, "original");
                DumpAddr(&translation, "translate");
                rv = PR_FAILURE;
            }
        }
    }
    return rv;
}  /* PrintAddress */
示例#6
0
static PRStatus PrintAddress(const PRNetAddr* address)
{
    char buffer[ADDR_BUFFER];
    PRStatus rv = PR_NetAddrToString(address, buffer, sizeof(buffer));
    if (PR_SUCCESS == rv)
        PR_fprintf(err, "%s:%u\n", buffer, PR_ntohs(address->inet.port));
    else PL_FPrintError(err, "PR_NetAddrToString");
    return rv;
}  /* PrintAddress */
示例#7
0
PRStatus
nsSOCKSSocketInfo::ConnectToProxy(PRFileDesc *fd)
{
    PRStatus status;
    nsresult rv;

    NS_ABORT_IF_FALSE(mState == SOCKS_DNS_COMPLETE,
                      "Must have DNS to make connection!");

    if (NS_FAILED(mLookupStatus)) {
        PR_SetError(PR_BAD_ADDRESS_ERROR, 0);
        return PR_FAILURE;
    }

    // Try socks5 if the destination addrress is IPv6
    if (mVersion == 4 &&
        PR_NetAddrFamily(&mDestinationAddr) == PR_AF_INET6) {
        mVersion = 5;
    }

    int32_t addresses = 0;
    do {
        if (addresses++)
            mDnsRec->ReportUnusable(mProxyPort);
        
        rv = mDnsRec->GetNextAddr(mProxyPort, &mInternalProxyAddr);
        // No more addresses to try? If so, we'll need to bail
        if (NS_FAILED(rv)) {
            LOGERROR(("socks: unable to connect to SOCKS proxy, %s",
                     mProxyHost.get()));
            return PR_FAILURE;
        }

#if defined(PR_LOGGING)
        char buf[64];
        PR_NetAddrToString(&mInternalProxyAddr, buf, sizeof(buf));
        LOGDEBUG(("socks: trying proxy server, %s:%hu",
                 buf, PR_ntohs(PR_NetAddrInetPort(&mInternalProxyAddr))));
#endif
        PRNetAddr proxy = mInternalProxyAddr;
        FixupAddressFamily(fd, &proxy);
        status = fd->lower->methods->connect(fd->lower, &proxy, mTimeout);
        if (status != PR_SUCCESS) {
            PRErrorCode c = PR_GetError();
            // If EINPROGRESS, return now and check back later after polling
            if (c == PR_WOULD_BLOCK_ERROR || c == PR_IN_PROGRESS_ERROR) {
                mState = SOCKS_CONNECTING_TO_PROXY;
                return status;
            }
        }
    } while (status != PR_SUCCESS);

    // Connected now, start SOCKS
    if (mVersion == 4)
        return WriteV4ConnectRequest();
    return WriteV5AuthRequest();
}
示例#8
0
static PRStatus PrintAddress(const PRNetAddr* address)
{
    char buffer[100];
    PRStatus rv = PR_NetAddrToString(address, buffer, sizeof(buffer));
    if (PR_FAILURE == rv) PL_FPrintError(err_out, "PR_NetAddrToString");
    else PR_fprintf(
        std_out, "Accepted connection from (0x%p)%s:%d\n",
        address, buffer, address->inet.port);
    return rv;
}  /* PrintAddress */
示例#9
0
std::string
addrStr(PRNetAddr addr)
{
  std::stringstream ss;
  char s[32];
  PR_NetAddrToString(&addr, s, 32);
  ss << s;
  if (addr.inet.port)
    ss << ":" << PR_ntohs(addr.inet.port);
  return ss.str();
}
NS_IMETHODIMP
HttpBaseChannel::GetRemoteAddress(nsACString& addr)
{
  if (mPeerAddr.raw.family == PR_AF_UNSPEC)
    return NS_ERROR_NOT_AVAILABLE;

  addr.SetCapacity(64);
  PR_NetAddrToString(&mPeerAddr, addr.BeginWriting(), 64);
  addr.SetLength(strlen(addr.BeginReading()));

  return NS_OK;
}
示例#11
0
NS_IMETHODIMP
nsDNSRecord::GetNextAddrAsString(nsACString &result)
{
    PRNetAddr addr;
    nsresult rv = GetNextAddr(0, &addr);
    if (NS_FAILED(rv)) return rv;

    char buf[64];
    if (PR_NetAddrToString(&addr, buf, sizeof(buf)) == PR_SUCCESS) {
        result.Assign(buf);
        return NS_OK;
    }
    NS_ERROR("PR_NetAddrToString failed unexpectedly");
    return NS_ERROR_FAILURE; // conversion failed for some reason
}
static
bool PACResolveToString(const nsCString &aHostName,
                        nsCString &aDottedDecimal,
                        unsigned int aTimeout)
{
  PRNetAddr netAddr;
  if (!PACResolve(aHostName, &netAddr, aTimeout))
    return false;

  char dottedDecimal[128];
  if (PR_NetAddrToString(&netAddr, dottedDecimal, sizeof(dottedDecimal)) != PR_SUCCESS)
    return false;

  aDottedDecimal.Assign(dottedDecimal);
  return true;
}
示例#13
0
int main(int argc, char **argv)
#endif
{
    const char **nexttestaddr = testaddrs;
    const char **nextbadaddr = badaddrs;
    const char *in, *expected_out;
    PRNetAddr addr;
    char buf[256];
    PRStatus rv;

    while ((in = *nexttestaddr++) != 0) {
	expected_out = *nexttestaddr++;
	rv = PR_StringToNetAddr(in, &addr);
	if (rv) {
	    printf("cannot convert %s to addr: %d\n", in, rv);
            failed_already = 1;
	    continue;
	}
	rv = PR_NetAddrToString(&addr, buf, sizeof(buf));
	if (rv) {
	    printf("cannot convert %s back to string: %d\n", in, rv);
            failed_already = 1;
	    continue;
	}
	if (strcmp(buf, expected_out)) {
            /* This is not necessarily an error */
	    printf("%s expected %s got %s\n", in, expected_out, buf);
	}
    }
    while ((in = *nextbadaddr++) != 0) {
        if (PR_StringToNetAddr(in, &addr) == PR_SUCCESS) {
            printf("converted bad addr %s\n", in);
            failed_already = 1;
        }
    }
    if (failed_already) {
        printf("FAIL\n");
        return 1;
    }
    printf("PASS\n");
    return 0;
}
示例#14
0
文件: testgetip.c 项目: Firstyear/ds
/*
 * Utility function to convert a PRNetAddr to a human readable string.
 */
static char *
netaddr2str( PRNetAddr *addrp, char *buf, size_t buflen )
{
	char	*addrstr;

	*buf = '\0';
	if ( PR_NetAddrToString( addrp, buf, buflen ) != PR_SUCCESS ) {
		slapi_log_err(SLAPI_LOG_PLUGIN, "testgetip",
		    "PR_NetAddrToString failed.\n" );
		return( NULL );
	}

	/* skip past leading ::ffff: if IPv4 address */
	if ( strlen( buf ) > 7 && strncmp( buf, "::ffff:", 7 ) == 0 ) {
		addrstr = buf + 7;
	} else {
		addrstr = buf;
	}

	return( addrstr );
}
示例#15
0
NS_IMETHODIMP
nsLDAPConnection::OnLookupComplete(nsICancelable *aRequest,
                                   nsIDNSRecord  *aRecord,
                                   nsresult       aStatus)
{    
    nsresult rv = NS_OK;

    if (aRecord) {
        // Build mResolvedIP list
        //
        mResolvedIP.Truncate();

        PRInt32 index = 0;
        char addrbuf[64];
        PRNetAddr addr;

        while (NS_SUCCEEDED(aRecord->GetNextAddr(0, &addr))) {
            // We can only use v4 addresses
            //
            PRBool v4mapped = PR_FALSE;
            if (addr.raw.family == PR_AF_INET6)
                v4mapped = PR_IsNetAddrType(&addr, PR_IpAddrV4Mapped);
            if (addr.raw.family == PR_AF_INET || v4mapped) {
                // If there are more IPs in the list, we separate them with
                // a space, as supported/used by the LDAP C-SDK.
                //
                if (index++)
                    mResolvedIP.Append(' ');

                // Convert the IPv4 address to a string, and append it to our
                // list of IPs.  Strip leading '::FFFF:' (the IPv4-mapped-IPv6 
                // indicator) if present.
                //
                PR_NetAddrToString(&addr, addrbuf, sizeof(addrbuf));
                if ((addrbuf[0] == ':') && (strlen(addrbuf) > 7))
                    mResolvedIP.Append(addrbuf+7);
                else
                    mResolvedIP.Append(addrbuf);
            }
        }
    }

    if (NS_FAILED(aStatus)) {
        // The DNS service failed, lets pass something reasonable
        // back to the listener.
        //
        switch (aStatus) {
        case NS_ERROR_OUT_OF_MEMORY:
        case NS_ERROR_UNKNOWN_HOST:
        case NS_ERROR_FAILURE:
        case NS_ERROR_OFFLINE:
            rv = aStatus;
            break;

        default:
            rv = NS_ERROR_UNEXPECTED;
            break;
        }
    } else if (!mResolvedIP.Length()) {
        // We have no host resolved, that is very bad, and should most
        // likely have been caught earlier.
        //
        NS_ERROR("nsLDAPConnection::OnStopLookup(): the resolved IP "
                 "string is empty.\n");
        
        rv = NS_ERROR_UNKNOWN_HOST;
    } else {
        // We've got the IP(s) for the hostname, now lets setup the
        // LDAP connection using this information. Note that if the
        // LDAP server returns a referral, the C-SDK will perform a
        // new, synchronous DNS lookup, which might hang (but hopefully
        // if we've come this far, DNS is working properly).
        //
        mConnectionHandle = ldap_init(mResolvedIP.get(),
                                      mPort == -1 ? LDAP_PORT : mPort);
        // Check that we got a proper connection, and if so, setup the
        // threading functions for this connection.
        //
        if ( !mConnectionHandle ) {
            rv = NS_ERROR_FAILURE;  // LDAP C SDK API gives no useful error
        } else {
#if defined(DEBUG_dmose) || defined(DEBUG_bienvenu)
            const int lDebug = 0;
            ldap_set_option(mConnectionHandle, LDAP_OPT_DEBUG_LEVEL, &lDebug);
#endif

            // the C SDK currently defaults to v2.  if we're to use v3, 
            // tell it so.
            //
            int version;
            switch (mVersion) {
            case 2:
                break;
            case 3:
                version = LDAP_VERSION3;
                ldap_set_option(mConnectionHandle, LDAP_OPT_PROTOCOL_VERSION, 
                                &version);
		break;
            default:
                NS_ERROR("nsLDAPConnection::OnLookupComplete(): mVersion"
                         " invalid");
            }

#ifdef MOZ_PSM
            // This code sets up the current connection to use PSM for SSL
            // functionality.  Making this use libssldap instead for
            // non-browser user shouldn't be hard.

            extern nsresult nsLDAPInstallSSL(LDAP *ld, const char *aHostName);

            if (mSSL) {
                if (ldap_set_option(mConnectionHandle, LDAP_OPT_SSL,
                                    LDAP_OPT_ON) != LDAP_SUCCESS ) {
                    NS_ERROR("nsLDAPConnection::OnStopLookup(): Error"
                             " configuring connection to use SSL");
                    rv = NS_ERROR_UNEXPECTED;
                }

                rv = nsLDAPInstallSSL(mConnectionHandle, mDNSHost.get());
                if (NS_FAILED(rv)) {
                    NS_ERROR("nsLDAPConnection::OnStopLookup(): Error"
                             " installing secure LDAP routines for"
                             " connection");
                }
            }
#endif
        }

        // Create a new runnable object, and increment the refcnt. The
        // thread will also hold a strong ref to the runnable, but we need
        // to make sure it doesn't get destructed until we are done with
        // all locking etc. in nsLDAPConnection::Release().
        //
        mRunnable = new nsLDAPConnectionLoop();
        NS_IF_ADDREF(mRunnable);
        if (!mRunnable || NS_FAILED(mRunnable->Init())) {
            rv = NS_ERROR_OUT_OF_MEMORY;
        } else {
            // Here we keep a weak reference in the runnable object to the
            // nsLDAPConnection ("this"). This avoids the problem where a
            // connection can't get destructed because of the new thread
            // keeping a strong reference to it. It also helps us know when
            // we need to exit the new thread: when we can't convert the weak
            // reference to a strong ref, we know that the nsLDAPConnection
            // object is gone, and we need to stop the thread running.
            //
            nsCOMPtr<nsILDAPConnection> conn =
                static_cast<nsILDAPConnection *>(this);

            mRunnable->mWeakConn = do_GetWeakReference(conn);

            // kick off a thread for result listening and marshalling
            //
            rv = NS_NewThread(getter_AddRefs(mThread), mRunnable);
            if (NS_FAILED(rv)) {
                rv = NS_ERROR_NOT_AVAILABLE;
            }
            // XXX(darin): We need to shutdown this thread at some point.
            //             Otherwise, it will stick around until shutdown.
        }
    }

    // Drop the DNS request object, we no longer need it, and set the flag
    // indicating that DNS has finished.
    //
    mDNSRequest = 0;
    mDNSHost.Truncate();

    // Call the listener, and then we can release our reference to it.
    //
    mInitListener->OnLDAPInit(this, rv);
    mInitListener = 0;

    return rv;
}
示例#16
0
TPS_PUBLIC PSHttpResponse *HttpConnection::getResponse(int index, const char *servlet, const char *body) {
    char *host_port;
    char uri[800];
    char *nickname;
    const char *httpprotocol;

    ConnectionInfo *failoverList = GetFailoverList();
    int len = failoverList->ConnectionInfo::GetHostPortListLen(); 
    if (index >= len) {
      index = len - 1; // use the last one
    }
    host_port= (failoverList->GetHostPortList())[index];

    if (IsSSL()) {
        httpprotocol = "https";
    } else {
        httpprotocol = "http";
    }

    PR_snprintf((char *)uri, 800,
      "%s://%s/%s",
      httpprotocol, host_port, servlet);

    RA::Debug("HttpConnection::getResponse", "Send request to host %s servlet %s", host_port, servlet);

    RA::Debug(LL_PER_PDU, "HttpConnection::getResponse", "uri=%s", uri);
    RA::Debug(LL_PER_PDU, "HttpConnection::getResponse", "host_port=%s", host_port);

    char *pPort = NULL;
    char *pPortActual = NULL;


    char hostName[512];

    /*
     * Isolate the host name, account for IPV6 numeric addresses.
     *
     */

    if(host_port)
        strncpy(hostName,host_port,512);

    pPort = hostName;
    while(1)  {
        pPort = strchr(pPort, ':');
        if (pPort) {
            pPortActual = pPort;
            pPort++;
        } else
            break;
    }

    if(pPortActual)
        *pPortActual = '\0';


    /*
    *  Rifle through the values for the host
    */

    PRAddrInfo *ai;
    void *iter;
    PRNetAddr addr;
    int family = PR_AF_INET;

    ai = PR_GetAddrInfoByName(hostName, PR_AF_UNSPEC, PR_AI_ADDRCONFIG);
    if (ai) {
        printf("%s\n", PR_GetCanonNameFromAddrInfo(ai));
        iter = NULL;
        while ((iter = PR_EnumerateAddrInfo(iter, ai, 0, &addr)) != NULL) {
            char buf[512];
            PR_NetAddrToString(&addr, buf, sizeof buf);
            RA::Debug( LL_PER_PDU,
                       "HttpConnection::getResponse: ",
                           "Sending addr -- Msg='%s'\n",
                           buf );
            family = PR_NetAddrFamily(&addr);
            RA::Debug( LL_PER_PDU,
                       "HttpConnection::getResponse: ",
                           "Sending family -- Msg='%d'\n",
                           family );
            break;
        }
        PR_FreeAddrInfo(ai);
        
    }

    PSHttpServer httpserver(host_port, family);
    nickname = GetClientNickname();
    if (IsSSL())
       httpserver.setSSL(PR_TRUE);
    else
       httpserver.setSSL(PR_FALSE);

    PSHttpRequest httprequest(&httpserver, uri, HTTP11, 0);
    if (IsSSL()) {
        httprequest.setSSL(PR_TRUE);
        if (nickname != NULL) {
            httprequest.setCertNickName(nickname);
        } else {
            return NULL;
        }
    } else
        httprequest.setSSL(PR_FALSE);

    httprequest.setMethod("POST");

    if (body != NULL) {
        httprequest.setBody( strlen(body), body);
    }

    httprequest.addHeader( "Content-Type", "application/x-www-form-urlencoded" );
    if (m_headers != NULL) {
        for (int i=0; i<m_headers->Size(); i++) {
            char *name = m_headers->GetNameAt(i);
            httprequest.addHeader(name, m_headers->GetValue(name));
        }
    }

    if (IsKeepAlive())
        httprequest.addHeader( "Connection", "keep-alive" );

    HttpEngine httpEngine;
    return httpEngine.makeRequest(httprequest, httpserver, (PRIntervalTime)GetTimeout(),
      PR_FALSE /*expectChunked*/);
}
/* 
 * traverseTreeAndCompareIPs
 * This function compares bit by bit of IP address with the tree nodes
 * Input
 *   NSErr_t *errp
 *   PRNetAddr * ip_addr - IP address of the client
 *   LASIpContext *context
 *   char * attr_pattern - ip address/pattern passed into LASIpEval
 *   int ipVersion - ipVersion of clients IP Address
 *   bool comparator_is_equal - true if comparator is CMP_OP_EQ
 * Returns 
 * LAS_EVAL_TRUE or LAS_EVAL_FALSE, or  LAS_* error codes in case of error.
 */
int traverseTreeAndCompareIPs(NSErr_t *errp, PRNetAddr *ip_addr, 
                              LASIpContext *context, char *attr_pattern,
                              int ipVersion, bool comparator_is_equal)
{
    // special case ip=*
    if (context->ipVersion == (PR_AF_INET6+PR_AF_INET)) {
        if (comparator_is_equal) {
            ereport(LOG_VERBOSE, "acl ip: match on ip = (%s)",
                    attr_pattern);
            return(LAS_EVAL_TRUE);
        } else {
            ereport(LOG_VERBOSE, "acl ip: no match on ip != (%s)",
                    attr_pattern);
            return(LAS_EVAL_FALSE);
        }
    }
     
    LASIpTree_t *node    = context->treetop;

    if (context->ipVersion != ipVersion || node == NULL) {
        ereport(LOG_VERBOSE,
                "ERROR IP Address returned by Attribute Getter for ACL_ATTR_IP did not match with IP Address Version set in ACL file.");
        if (comparator_is_equal) {
            return(LAS_EVAL_FALSE);
        } else {
            return(LAS_EVAL_TRUE);
        }
    }
    int max_bits=32;
    if (ipVersion == PR_AF_INET6)
        max_bits=128;
    else if (ipVersion != PR_AF_INET)
       return LAS_EVAL_INVALID;

    for (int bit=(max_bits-1); bit >=0; bit--) {
        int value = getBit(*ip_addr,bit,max_bits);
        if (LAS_IP_IS_CONSTANT(node->action[value])) {
            /* Reached a result, so return it */
            int r = (int)(size_t) node->action[value];
            if (comparator_is_equal) {
                ereport(LOG_VERBOSE, "acl ip: %s on ip = (%s)",
                        (r == LAS_EVAL_TRUE) ? "match" : "no match",
                        attr_pattern);
                return(r);
            }
            else {
                ereport(LOG_VERBOSE, "acl ip: %s on ip != (%s)",
                        (r == LAS_EVAL_TRUE) ? "no match" : "match",
                        attr_pattern);
                return((r == LAS_EVAL_TRUE) ? 
                    LAS_EVAL_FALSE : LAS_EVAL_TRUE);
            }
        }
        else {
            /* Move on to the next bit */
            node = node->action[value];
        }
    }

    /* Cannot reach here.  Even a 32 bit mismatch has a conclusion in 
     * the pattern tree.
     */
    char ip_str[124];
    memset(ip_str,0,124);
    PR_NetAddrToString(ip_addr,ip_str,124);
    nserrGenerate(errp, ACLERRINTERNAL, ACLERR5240, ACL_Program, 2, XP_GetAdminStr(DBT_lasipevalReach32BitsWithoutConcl_), max_bits, ip_str);
    return LAS_EVAL_INVALID;
}
示例#18
0
int main(int argc, char **argv)
#endif
{
    const char *hostName = DEFAULT_HOST_NAME;
    PRHostEnt he, reversehe;
    char buf[PR_NETDB_BUF_SIZE];
    char reversebuf[PR_NETDB_BUF_SIZE];
    PRIntn idx;
    PRNetAddr addr;
    PLOptStatus os;
    PLOptState *opt = PL_CreateOptState(argc, argv, "h");

    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option) {
            case 0:  /* naked */
                hostName = opt->value;
                break;
            case 'h':  /* Help message */
            default:
                Help();
                return 2;
        }
    }
    PL_DestroyOptState(opt);

    PR_STDIO_INIT();
    outFile = PR_GetSpecialFD(PR_StandardError);

    if (PR_GetHostByName(hostName, buf, sizeof(buf), &he) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_GetHostByName failed\n");
        exit(1);
    }
    PrintHostent(&he);
    idx = 0;

    while (1) {
        idx = PR_EnumerateHostEnt(idx, &he, 0, &addr);
        if (idx == -1) {
            PR_fprintf(outFile, "PR_EnumerateHostEnt failed\n");
            exit(1);
        }
        if (idx == 0) break;  /* normal loop termination */
        PR_fprintf(outFile, "reverse lookup\n");
        if (PR_GetHostByAddr(&addr, reversebuf, sizeof(reversebuf),
                &reversehe) == PR_FAILURE) {
            PR_fprintf(outFile, "PR_GetHostByAddr failed\n");
            exit(1);
        }
        PrintHostent(&reversehe);
    }

    PR_fprintf(outFile, "PR_GetIPNodeByName with PR_AF_INET\n");
    if (PR_GetIPNodeByName(hostName, PR_AF_INET, PR_AI_DEFAULT,
            buf, sizeof(buf), &he) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_GetIPNodeByName failed\n");
        exit(1);
    }
    PrintHostent(&he);
    PR_fprintf(outFile, "PR_GetIPNodeByName with PR_AF_INET6\n");
    if (PR_GetIPNodeByName(hostName, PR_AF_INET6, PR_AI_DEFAULT,
            buf, sizeof(buf), &he) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_GetIPNodeByName failed\n");
        exit(1);
    }
    PrintHostent(&he);
    idx = 0;
    PR_fprintf(outFile, "PR_GetHostByAddr with PR_AF_INET6\n");
    while (1) {
        idx = PR_EnumerateHostEnt(idx, &he, 0, &addr);
        if (idx == -1) {
            PR_fprintf(outFile, "PR_EnumerateHostEnt failed\n");
            exit(1);
        }
        if (idx == 0) break;  /* normal loop termination */
        PR_fprintf(outFile, "reverse lookup\n");
        if (PR_GetHostByAddr(&addr, reversebuf, sizeof(reversebuf),
                &reversehe) == PR_FAILURE) {
            PR_fprintf(outFile, "PR_GetHostByAddr failed\n");
            exit(1);
        }
        PrintHostent(&reversehe);
    }
    PR_fprintf(outFile, "PR_GetHostByAddr with PR_AF_INET6 done\n");
  
    PR_StringToNetAddr("::1", &addr);
    if (PR_IsNetAddrType(&addr, PR_IpAddrV4Mapped) == PR_TRUE) {
        PR_fprintf(outFile, "addr should not be ipv4 mapped address\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrLoopback) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be loopback address\n");
        exit(1);
    }

    PR_StringToNetAddr("127.0.0.1", &addr);
    if (PR_IsNetAddrType(&addr, PR_IpAddrLoopback) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be loopback address\n");
        exit(1);
    }
    PR_StringToNetAddr("::FFFF:127.0.0.1", &addr);
    if (PR_IsNetAddrType(&addr, PR_IpAddrV4Mapped) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be ipv4 mapped address\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrLoopback) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be loopback address\n");
        exit(1);
    }

    if (PR_InitializeNetAddr(PR_IpAddrAny, 0, &addr) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_InitializeNetAddr failed\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrAny) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be unspecified address\n");
        exit(1);
    }
    if (PR_InitializeNetAddr(PR_IpAddrLoopback, 0, &addr) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_InitializeNetAddr failed\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrLoopback) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be loopback address\n");
        exit(1);
    }

    if (PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET, 0, &addr) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_SetNetAddr failed\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrAny) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be unspecified address\n");
        exit(1);
    }
    if (PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET, 0, &addr) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_SetNetAddr failed\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrLoopback) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be loopback address\n");
        exit(1);
    }

    addr.inet.family = PR_AF_INET;
    addr.inet.port = 0;
    addr.inet.ip = PR_htonl(PR_INADDR_ANY);
    if (PR_IsNetAddrType(&addr, PR_IpAddrAny) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be unspecified address\n");
        exit(1);
    }
	{
		char buf[256];
		PR_NetAddrToString(&addr, buf, 256);
		PR_fprintf(outFile, "IPv4 INADDRANY: %s\n", buf);
	}
    addr.inet.family = PR_AF_INET;
    addr.inet.port = 0;
    addr.inet.ip = PR_htonl(PR_INADDR_LOOPBACK);
    if (PR_IsNetAddrType(&addr, PR_IpAddrLoopback) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be loopback address\n");
        exit(1);
    }
	{
		char buf[256];
		PR_NetAddrToString(&addr, buf, 256);
		PR_fprintf(outFile, "IPv4 LOOPBACK: %s\n", buf);
	}

    if (PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, 0, &addr) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_SetNetAddr failed\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrAny) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be unspecified address\n");
        exit(1);
    }
	{
		char buf[256];
		PR_NetAddrToString(&addr, buf, 256);
		PR_fprintf(outFile, "IPv6 INADDRANY: %s\n", buf);
	}
    if (PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET6, 0, &addr) == PR_FAILURE) {
        PR_fprintf(outFile, "PR_SetNetAddr failed\n");
        exit(1);
    }
    if (PR_IsNetAddrType(&addr, PR_IpAddrLoopback) == PR_FALSE) {
        PR_fprintf(outFile, "addr should be loopback address\n");
        exit(1);
    }
	{
		char buf[256];
		PR_NetAddrToString(&addr, buf, 256);
		PR_fprintf(outFile, "IPv6 LOOPBACK: %s\n", buf);
	}
	{
		PRIPv6Addr v6addr;
		char tmp_buf[256];

    	PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET, 0, &addr);

		PR_ConvertIPv4AddrToIPv6(addr.inet.ip, &v6addr);
    	PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, 0, &addr);
		addr.ipv6.ip = v6addr;
		PR_NetAddrToString(&addr, tmp_buf, 256);
		PR_fprintf(outFile, "IPv4-mapped IPv6 LOOPBACK: %s\n", tmp_buf);
	}
    PR_fprintf(outFile, "PASS\n");
    return 0;
}
示例#19
0
PRStatus RCNetAddr::ToString(char *string, PRSize size) const
    { return PR_NetAddrToString(&address, string, size); }
示例#20
0
// returns TRUE if SAN was used to produce names
// return FALSE if nothing was produced
// names => a single name or a list of names
// multipleNames => whether multiple names were delivered
static bool
GetSubjectAltNames(CERTCertificate *nssCert,
                   nsINSSComponent *component,
                   nsString &allNames,
                   uint32_t &nameCount)
{
    allNames.Truncate();
    nameCount = 0;

    SECItem altNameExtension = {siBuffer, nullptr, 0 };
    CERTGeneralName *sanNameList = nullptr;

    SECStatus rv = CERT_FindCertExtension(nssCert, SEC_OID_X509_SUBJECT_ALT_NAME,
                                          &altNameExtension);
    if (rv != SECSuccess) {
        return false;
    }

    ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
    if (!arena) {
        return false;
    }

    sanNameList = CERT_DecodeAltNameExtension(arena.get(), &altNameExtension);
    if (!sanNameList) {
        return false;
    }

    SECITEM_FreeItem(&altNameExtension, false);

    CERTGeneralName *current = sanNameList;
    do {
        nsAutoString name;
        switch (current->type) {
        case certDNSName:
        {
            nsDependentCSubstring nameFromCert(reinterpret_cast<char*>
                                               (current->name.other.data),
                                               current->name.other.len);
            // dNSName fields are defined as type IA5String and thus should
            // be limited to ASCII characters.
            if (IsASCII(nameFromCert)) {
                name.Assign(NS_ConvertASCIItoUTF16(nameFromCert));
                if (!allNames.IsEmpty()) {
                    allNames.AppendLiteral(", ");
                }
                ++nameCount;
                allNames.Append(name);
            }
        }
        break;

        case certIPAddress:
        {
            char buf[INET6_ADDRSTRLEN];
            PRNetAddr addr;
            if (current->name.other.len == 4) {
                addr.inet.family = PR_AF_INET;
                memcpy(&addr.inet.ip, current->name.other.data, current->name.other.len);
                PR_NetAddrToString(&addr, buf, sizeof(buf));
                name.AssignASCII(buf);
            } else if (current->name.other.len == 16) {
                addr.ipv6.family = PR_AF_INET6;
                memcpy(&addr.ipv6.ip, current->name.other.data, current->name.other.len);
                PR_NetAddrToString(&addr, buf, sizeof(buf));
                name.AssignASCII(buf);
            } else {
                /* invalid IP address */
            }
            if (!name.IsEmpty()) {
                if (!allNames.IsEmpty()) {
                    allNames.AppendLiteral(", ");
                }
                ++nameCount;
                allNames.Append(name);
            }
            break;
        }

        default: // all other types of names are ignored
            break;
        }
        current = CERT_GetNextGeneralName(current);
    } while (current != sanNameList); // double linked

    return true;
}
static void PR_CALLBACK Client(void *arg)
{
    PRStatus rv;
    PRIntn index;
    char buffer[1024];
    PRFileDesc *fd = NULL;
    PRUintn clipping = DEFAULT_CLIPPING;
    PRThread *me = PR_GetCurrentThread();
    CSClient_t *client = (CSClient_t*)arg;
    CSDescriptor_t *descriptor = PR_NEW(CSDescriptor_t);
    PRIntervalTime timeout = PR_MillisecondsToInterval(DEFAULT_CLIENT_TIMEOUT);


    for (index = 0; index < sizeof(buffer); ++index)
        buffer[index] = (char)index;

    client->started = PR_IntervalNow();

    PR_Lock(client->ml);
    client->state = cs_run;
    PR_NotifyCondVar(client->stateChange);
    PR_Unlock(client->ml);

    TimeOfDayMessage("Client started at", me);

    while (cs_run == client->state)
    {
        PRInt32 bytes, descbytes, filebytes, netbytes;

        (void)PR_NetAddrToString(&client->serverAddress, buffer, sizeof(buffer));
        TEST_LOG(cltsrv_log_file, TEST_LOG_INFO, 
            ("\tClient(0x%p): connecting to server at %s\n", me, buffer));

        fd = PR_Socket(domain, SOCK_STREAM, protocol);
        TEST_ASSERT(NULL != fd);
        rv = PR_Connect(fd, &client->serverAddress, timeout);
        if (PR_FAILURE == rv)
        {
            TEST_LOG(
                cltsrv_log_file, TEST_LOG_ERROR,
                ("\tClient(0x%p): conection failed (%d, %d)\n",
                me, PR_GetError(), PR_GetOSError()));
            goto aborted;
        }

        memset(descriptor, 0, sizeof(*descriptor));
        descriptor->size = PR_htonl(descbytes = rand() % clipping);
        PR_snprintf(
            descriptor->filename, sizeof(descriptor->filename),
            "CS%p%p-%p.dat", client->started, me, client->operations);
        TEST_LOG(
            cltsrv_log_file, TEST_LOG_VERBOSE,
            ("\tClient(0x%p): sending descriptor for %u bytes\n", me, descbytes));
        bytes = PR_Send(
            fd, descriptor, sizeof(*descriptor), SEND_FLAGS, timeout);
        if (sizeof(CSDescriptor_t) != bytes)
        {
            if (Aborted(PR_FAILURE)) goto aborted;
            if (PR_IO_TIMEOUT_ERROR == PR_GetError())
            {
                TEST_LOG(
                    cltsrv_log_file, TEST_LOG_ERROR,
                    ("\tClient(0x%p): send descriptor timeout\n", me));
                goto retry;
            }
        }
        TEST_ASSERT(sizeof(*descriptor) == bytes);

        netbytes = 0;
        while (netbytes < descbytes)
        {
            filebytes = sizeof(buffer);
            if ((descbytes - netbytes) < filebytes)
                filebytes = descbytes - netbytes;
            TEST_LOG(
                cltsrv_log_file, TEST_LOG_VERBOSE,
                ("\tClient(0x%p): sending %d bytes\n", me, filebytes));
            bytes = PR_Send(fd, buffer, filebytes, SEND_FLAGS, timeout);
            if (filebytes != bytes)
            {
                if (Aborted(PR_FAILURE)) goto aborted;
                if (PR_IO_TIMEOUT_ERROR == PR_GetError())
                {
                    TEST_LOG(
                        cltsrv_log_file, TEST_LOG_ERROR,
                        ("\tClient(0x%p): send data timeout\n", me));
                    goto retry;
                }
            }
            TEST_ASSERT(bytes == filebytes);
            netbytes += bytes;
        }
        filebytes = 0;
        while (filebytes < descbytes)
        {
            netbytes = sizeof(buffer);
            if ((descbytes - filebytes) < netbytes)
                netbytes = descbytes - filebytes;
            TEST_LOG(
                cltsrv_log_file, TEST_LOG_VERBOSE,
                ("\tClient(0x%p): receiving %d bytes\n", me, netbytes));
            bytes = PR_Recv(fd, buffer, netbytes, RECV_FLAGS, timeout);
            if (-1 == bytes)
            {
                if (Aborted(PR_FAILURE))
                {
                    TEST_LOG(
                        cltsrv_log_file, TEST_LOG_ERROR,
                        ("\tClient(0x%p): receive data aborted\n", me));
                    goto aborted;
                }
                else if (PR_IO_TIMEOUT_ERROR == PR_GetError())
                    TEST_LOG(
                        cltsrv_log_file, TEST_LOG_ERROR,
                        ("\tClient(0x%p): receive data timeout\n", me));
				else
                    TEST_LOG(
                        cltsrv_log_file, TEST_LOG_ERROR,
                        ("\tClient(0x%p): receive error (%d, %d)\n",
						me, PR_GetError(), PR_GetOSError()));
                goto retry;
           }
            if (0 == bytes)
            {
                TEST_LOG(
                    cltsrv_log_file, TEST_LOG_ERROR,
                    ("\t\tClient(0x%p): unexpected end of stream\n",
                    PR_GetCurrentThread()));
                break;
            }
            filebytes += bytes;
        }

        rv = PR_Shutdown(fd, PR_SHUTDOWN_BOTH);
        if (Aborted(rv)) goto aborted;
        TEST_ASSERT(PR_SUCCESS == rv);
retry:
        (void)PR_Close(fd); fd = NULL;
        TEST_LOG(
            cltsrv_log_file, TEST_LOG_INFO,
            ("\tClient(0x%p): disconnected from server\n", me));

        PR_Lock(client->ml);
        client->operations += 1;
        client->bytesTransferred += 2 * descbytes;
        rv = PR_WaitCondVar(client->stateChange, rand() % clipping);
        PR_Unlock(client->ml);
        if (Aborted(rv)) break;
    }

aborted:
    client->stopped = PR_IntervalNow();

    PR_ClearInterrupt();
    if (NULL != fd) rv = PR_Close(fd);

    PR_Lock(client->ml);
    client->state = cs_exit;
    PR_NotifyCondVar(client->stateChange);
    PR_Unlock(client->ml);
    PR_DELETE(descriptor);
    TEST_LOG(
        cltsrv_log_file, TEST_LOG_ALWAYS,
        ("\tClient(0x%p): stopped after %u operations and %u bytes\n",
        PR_GetCurrentThread(), client->operations, client->bytesTransferred));

}  /* Client */