Example #1
0
/**
 * Called when the context has been activated to set our IP address and get
 * any other required settings from CommDB.
 *
 * @param aConfig The new context config
 */
void CIPv4Binder::UpdateContextConfigL(const TPacketDataConfigBase& aConfig)
	{
	OstTraceDef0(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CIPV4BINDER_UPDATECONTEXTCONFIGL_1, "CIPv4Binder::UpdateContextConfig");

	// Get our IP address from the GPRS context config.
	TInetAddr address;
	
	TBuf<RPacketContext::KMaxPDPAddressLength> tempAddr;
	
	const RPacketContext::TProtocolConfigOptionV2* pco;
	TInt rel = const_cast<TPacketDataConfigBase&>(aConfig).ExtensionId();
	if (rel == TPacketDataConfigBase::KConfigGPRS) 
	    {
	    tempAddr.Copy(static_cast<const RPacketContext::TContextConfigGPRS&>(aConfig).iPdpAddress);
	    pco = &static_cast<const RPacketContext::TContextConfigGPRS&>(aConfig).iProtocolConfigOption;
	    }
    else
        {
        ASSERT(rel == TPacketDataConfigBase::KConfigRel99Rel4 || rel == TPacketDataConfigBase::KConfigRel5);
	    tempAddr.Copy(static_cast<const RPacketContext::TContextConfigR99_R4&>(aConfig).iPdpAddress);
	    pco = &static_cast<const RPacketContext::TContextConfigR99_R4&>(aConfig).iProtocolConfigOption;
        }
	TInt ret = address.Input(tempAddr);

	// We've got our IP address! Let's save it.
	if (ret == KErrNone)
		{
		iSettings.iLocalAddr = address.Address();
		OstTraceDefExt4(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CIPV4BINDER_UPDATECONTEXTCONFIGL_2, "Got local IP address from context = %u.%u.%u.%u",iSettings.iLocalAddr >> 24, (iSettings.iLocalAddr >> 16) & 0xFF, (iSettings.iLocalAddr >> 8) & 0xFF, iSettings.iLocalAddr & 0xFF);
		iSettings.iDefGateway = address.Address();
		OstTraceDef0(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CIPV4BINDER_UPDATECONTEXTCONFIGL_3, "Set Default Gateway to local IP address");
		}
Example #2
0
// ---------------------------------------------------------------------------
// SdpUtil::SetDefaultNetTypeAndAddrType
// Sets network type and address type to their "default" values
// ---------------------------------------------------------------------------
//
void SdpUtil::SetDefaultNetTypeAndAddrType( 
    RStringPool aPool, 
    const TInetAddr& aAddress,
    RStringF& aNetType, 
    RStringF& aAddressType )
    {
     // Sets network type to IN
    aNetType.Close();
    aNetType = aPool.StringF( SdpCodecStringConstants::ENetType,
                              SdpCodecStringConstants::Table ).Copy();
    // Address type       
    aAddressType.Close();

    TBuf16 <KMaxAddressLength> output;
    aAddress.Output(output);


    //addresstype for IPv4    
	if((aAddress.Address() &&  !aAddress.IsV4Mapped()) ||
       (!aAddress.Address() && aAddress.IsWildAddr() && 
        output.Match(KWildAddr) == 0))
        {
        aAddressType = aPool.StringF( SdpCodecStringConstants::EAddressTypeIP4,
                                      SdpCodecStringConstants::Table ).Copy();
        }
    else
        {
		//addresstype for IPv4-Mapped IPv6 && IPv6
        aAddressType = aPool.StringF( SdpCodecStringConstants::EAddressType,
                                      SdpCodecStringConstants::Table ).Copy();
        }
    }
Example #3
0
/**
 * Handle incoming connects
 */
void tcp_sock::tcp_conn_handler()
{
	if (!ctc) {
		DEBUG_WARNING("conn handler: no pending socket\n");
	}

	TInetAddr ia;
	struct sa peer;
	ctc->iSocket.RemoteName(ia);
	sa_set_in(&peer, ia.Address(), ia.Port());

	DEBUG_INFO("conn handler: incoming connect from %J\n", &peer);

	ctc->blank = false;

	/*
	 * Application handler might call tcp_accept(), tcp_reject()
	 * or do nothing
	 */
	if (connh)
		connh(&peer, arg);

	if (ctc) {
		DEBUG_INFO("delete ctc\n");
		delete ctc;
		ctc = NULL;
	}

	/* Create blank socket for the next incoming CONNECT */
	blank_socket();

	cts->Accepting();
}
Example #4
0
TSAHostCacheEntry::TSAHostCacheEntry(const TInetAddr& aAddress, TInt aQuality)
{
	iPort = aAddress.Port();
	iAddress = aAddress.Address();

	iQuality = aQuality;
}
void UT_CTBCPFloorControlImpl::UT_CTBCPFloorControlImpl_SetAddressLL(  )
    {
    TBuf<KBufLength> addressbuffer;
    TInetAddr addr;
    addr.Input(KAddr2);
    addr.Output(addressbuffer);
    iPlugIn->SetAddressL(addressbuffer, KPort1);
    EUNIT_ASSERT( iPlugIn->iRemoteAddr.Address()==addr.Address());
    }
Example #6
0
int udp_sock::local_get(struct sa *local) const
{
	TInetAddr ia;

	cus->iSocket.LocalName(ia);
	sa_set_in(local, ia.Address(), ia.Port());

	return 0;
}
Example #7
0
/**
 * Get the local IP address of the device
 *
 * @note Requires at least one IP packet sent in advance!
 */
int net_if_getaddr4(const char *ifname, int af, struct sa *ip)
{
	(void)ifname;

	if (AF_INET != af)
		return EAFNOSUPPORT;

	/* Already cached? */
	if (sa_isset(&local_ip, SA_ADDR)) {
		sa_cpy(ip, &local_ip);
		return 0;
	}

	RSocketServ ss;
	RSocket s;
	TInt ret;

	ret = ss.Connect();
	if (KErrNone != ret) {
		DEBUG_WARNING("connecting to socket server fail (ret=%d)\n",
			      ret);
		return ECONNREFUSED;
	}

	ret = s.Open(ss, KAfInet, KSockDatagram, KProtocolInetUdp);
	if (KErrNone != ret) {
		DEBUG_WARNING("open socket failed (ret=%d)\n", ret);
		return ECONNREFUSED;
	}

	TInetAddr bind;
	bind.SetPort(0);
	bind.SetAddress(KInetAddrAny);

	ret = s.Bind(bind);
	if (KErrNone != ret) {
		DEBUG_WARNING("bind socket failed (ret=%d)\n", ret);
		return ECONNREFUSED;
	}

	TInetAddr local;
	s.LocalName(local);

	s.Close();
	ss.Close();

	sa_set_in(&local_ip, local.Address(), local.Port());

	DEBUG_NOTICE("local IP addr: %j\n", &local_ip);

	if (!sa_isset(&local_ip, SA_ADDR))
		return EINVAL;

	sa_cpy(ip, &local_ip);

	return 0;
}
QHostAddress qt_QHostAddressFromTInetAddr(const TInetAddr& addr)
{
    if (addr.IsV4Mapped() || addr.Family() == KAfInet) {
        //convert v4 host address
        return QHostAddress(addr.Address());
    } else {
        //convert v6 host address
        return QHostAddress((quint8 *)(addr.Ip6Address().u.iAddr8));
    }
}
Example #9
0
int tcp_conn_peer_get(const struct tcp_conn *tc, struct sa *peer)
{
	if (!tc || !peer)
		return EINVAL;

	TInetAddr ia;
	tc->ctc->iSocket.RemoteName(ia);
	sa_set_in(peer, ia.Address(), ia.Port());

	return 0;
}
Example #10
0
int tcp_conn_local_get(const struct tcp_conn *tc, struct sa *local)
{
	if (!tc || !local)
		return EINVAL;

	TInetAddr ia;
	tc->ctc->iSocket.LocalName(ia);
	sa_set_in(local, ia.Address(), ia.Port());

	return 0;
}
Example #11
0
int tcp_sock_local_get(const struct tcp_sock *ts, struct sa *local)
{
	if (!ts || !local)
		return EINVAL;

	TInetAddr ia;
	ts->cts->iSocket.LocalName(ia);
	sa_set_in(local, ia.Address(), ia.Port());

	return 0;
}
//TODO: share this, at least QHostInfo needs to do the same thing
static QHostAddress qt_QHostAddressFromTInetAddr(const TInetAddr& addr)
{
    //TODO: do we want to call v4 mapped addresses v4 or v6 outside of this file?
    if (addr.IsV4Mapped() || addr.Family() == KAfInet) {
        //convert v4 host address
        return QHostAddress(addr.Address());
    } else {
        //convert v6 host address
        return QHostAddress((quint8 *)(addr.Ip6Address().u.iAddr8));
    }
}
int ILibSocketWrapper_recvfrom(int socketObject, char *buffer, int bufferLength, struct sockaddr *src)
{
	RSocket *s = (RSocket*)SocketArray[socketObject];
	TRequestStatus status;
	TInetAddr addr;
	int RetVal=0;
	RBuf8 *buf = new RBuf8();
	
	if(buf->Create(bufferLength)==KErrNone)
	{
		TProtocolDesc aProtocol;
		
		s->Info(aProtocol);
		if(aProtocol.iSockType==KSockStream)
		{
			s->RemoteName(addr);
			((struct in_addr*)src->sa_data)->s_addr = ntohl(addr.Address());
			src->sa_port = htons(addr.Port());
			RetVal = ILibSocketWrapper_recv(socketObject, buffer, bufferLength);
		}
		else
		{
			s->RecvFrom(*buf,addr,(unsigned int)0,status);
			User::WaitForRequest(status);
			if(status!=KErrNone)
			{
				RetVal = 0;
			}
			else
			{
				((struct in_addr*)src->sa_data)->s_addr = ntohl(addr.Address());
				src->sa_port = htons(addr.Port());
				Mem::Copy(buffer,buf->Ptr(),buf->Length());
				RetVal = buf->Length();
			}
		}
	}
	buf->Close();
	delete buf;
	return(RetVal);
}
Example #14
0
/*
 * Convert text to IPv4/IPv6 address.
 */
PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst)
{
    char tempaddr[PJ_INET6_ADDRSTRLEN];

    PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6, PJ_EINVAL);
    PJ_ASSERT_RETURN(src && src->slen && dst, PJ_EINVAL);

    /* Initialize output with PJ_IN_ADDR_NONE for IPv4 (to be 
     * compatible with pj_inet_aton()
     */
    if (af==PJ_AF_INET) {
	((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE;
    }

    /* Caution:
     *	this function might be called with cp->slen >= 46
     *  (i.e. when called with hostname to check if it's an IP addr).
     */
    if (src->slen >= PJ_INET6_ADDRSTRLEN) {
	return PJ_ENAMETOOLONG;
    }

    pj_memcpy(tempaddr, src->ptr, src->slen);
    tempaddr[src->slen] = '\0';


    wchar_t tempaddr16[PJ_INET6_ADDRSTRLEN];
    pj_ansi_to_unicode(tempaddr, pj_ansi_strlen(tempaddr),
		       tempaddr16, sizeof(tempaddr16));

    TBuf<PJ_INET6_ADDRSTRLEN> ip_addr((const TText*)tempaddr16);

    TInetAddr addr;
    addr.Init(KAfInet6);
    if (addr.Input(ip_addr) == KErrNone) {
	if (af==PJ_AF_INET) {
	    /* Success (Symbian IP address is in host byte order) */
	    pj_uint32_t ip = pj_htonl(addr.Address());
	    pj_memcpy(dst, &ip, 4);
	} else if (af==PJ_AF_INET6) {
	    const TIp6Addr & ip6 = addr.Ip6Address();
	    pj_memcpy(dst, ip6.u.iAddr8, 16);
	} else {
	    pj_assert(!"Unexpected!");
	    return PJ_EBUG;
	}
	return PJ_SUCCESS;
    } else {
	/* Error */
	return PJ_EINVAL;
    }
}
Example #15
0
MFactoryQuery::TMatchResult THttpClientFlowQuery::Compare(TFactoryObjectInfo& aFactoryObjectInfo )
	{
	const CHttpClientFlow* flow = static_cast<const CHttpClientFlow*>(aFactoryObjectInfo.iInfo.iFactoryObject);
	
	// iClientFlags == ECreateNew is handled by factory, other needs to be checked here	
 	TInetAddr remName;
   	flow->RemName( remName );
  	if ( remName.Address ( ) == iSockAddr.iAddr && remName.Port ( ) ==  iSockAddr.iPort && flow->Status( ) == KErrNone )
		{
		return MFactoryQuery::EMatch;
		}
	return MFactoryQuery::EContinue;
	}
Example #16
0
TBool CSTTorrentManager::AcceptSocketL(RSocket* aSocket, TUint /*aPort*/, CNetworkConnection& aConnection, TInt aConnIndex)
{
	TBool isLocal = (aConnIndex == 1);
	
	if (isLocal && (aConnection.Type() == CNetworkConnection::ERConnectionBased))
	{
		TInetAddr localAddress;
		iNetworkManager->GetLocalAddress(aConnIndex, localAddress);
		
		TInetAddr remoteAddress;
		aSocket->RemoteName(remoteAddress);
		
		if (localAddress.Address() == remoteAddress.Address())
		{
			LWRITELN(iLog, _L("[TorrentMgr] Connected to ourselves via local connection, closing"));
			return EFalse;
		}
	}
	
	RegisterIncomingConnectionL(aSocket, isLocal);	
	
	return ETrue;
}
// -----------------------------------------------------------------------------
// CSdpOriginField::TypeMatchesWithFormat
// Checks if address type is aligned with the address format
// -----------------------------------------------------------------------------
//
TBool CSdpOriginField::TypeMatchesWithFormat( 
    const TDesC8& aAddress, 
    const TDesC8& aType,
    RStringPool aPool ) const
    {
    RStringF addrTypeIP4 = 
        aPool.StringF( SdpCodecStringConstants::EAddressTypeIP4,
                              SdpCodecStringConstants::Table );
    RStringF addrTypeIP6 = 
        aPool.StringF( SdpCodecStringConstants::EAddressType,
                              SdpCodecStringConstants::Table );
    
    TBool valid( ETrue );
    
    // Check that address type and address matches together
    TInetAddr addr;
    TBuf<KMaxAddressLength> address16;
    address16.Copy( aAddress );
    TInt err = addr.Input( address16 );    
    if ( err == KErrNone && !addr.IsUnspecified())
        {
        TBool ip4Type = ( addrTypeIP4.DesC().CompareF( aType ) == 0 );
        TBool ip6Type = ( addrTypeIP6.DesC().CompareF( aType ) == 0 );
             
        if ( ip4Type || ip6Type )
            {
            if ( ( addr.Address() && !addr.IsV4Mapped() && !ip4Type ) ||
				 (addr.Address() && addr.IsV4Mapped() && !ip6Type) ||
                 ( !addr.Address() && !ip6Type ) )
                {
                valid = EFalse;
                }
            }
        } 
    
    return valid;
    }
// -----------------------------------------------------------------------------
// CSdpConnectionField::IsValidAddress
// Checks if the given address is valid
// -----------------------------------------------------------------------------
//
TInt CSdpConnectionField::IsValidAddress(
    const TInetAddr& aAddress,
    TInt aTTL,
    TUint aNumOfAddress ) const
    {
    TInt err( KErrSdpCodecConnectionField );
    // 0 <= TTL <= 255 or KErrNotFound if not defined
    // Number of addresses > 0
    if ( ( aTTL == KErrNotFound || ( aTTL >= 0 && aTTL <= 255 ) ) &&
           aNumOfAddress > 0 )
        {
        TBuf16 <KMaxAddressLength> output;
        aAddress.Output(output);

        // Address has to be either of type IP4 or IP6
        // If IP4 and multicast then it must contain TTL attribute
        // If IP4 and unicast then it must NOT contain TTL and must have 1 address
        // If IP6 and multicast then it must NOT contain TTL
        // If IP6 and unicast then it must NOT contain TTL and must have 1 address
        if ( ( aAddress.Address() && 
               ( ( aAddress.IsMulticast() && aTTL != KErrNotFound ) ||
                 ( aAddress.IsUnicast() && aTTL == KErrNotFound &&
                   aNumOfAddress == 1 ) ) ) ||
             ( !aAddress.Address() &&
               ( ( aAddress.IsMulticast() && aTTL == KErrNotFound ) ||
                 ( aAddress.IsUnicast() && aTTL == KErrNotFound &&
                   aNumOfAddress == 1 ) )   ||
               ( aAddress.IsWildAddr() && 
               ( output.Match(KWildAddr) == 0||
               	 output.Match(KWildAddrIPv6) == 0 )) ) )
           {
           err = KErrNone;
           }
        }

    return err;
    }
	void CSender::DoInitL(const TInetAddr& anAddr, const TInt aPort)
#endif
	{
		iRemote.SetV4MappedAddress(anAddr.Address());
		iRemote.SetPort(aPort);
		
		TInt err = iSock.Open(iSS, KAfInet, KSockStream, KProtocolInetTcp);
		User::LeaveIfError(err);
#ifdef _USE_QOS
		if (parameters)
			{
			iQosParams = new(ELeave) CQoSParameters;
			iQosParams->CopyL(*parameters);
			}
#endif
		}
int ILibSocketWrapper_getsockname(int socketObject, struct sockaddr* local, int* length)
{
  struct sockaddr_in* localAddr = (struct sockaddr_in*)local;
	RSocket *s = (RSocket*)SocketArray[socketObject];
  TInetAddr sockAddr;

  // get the local name
  s->LocalName(sockAddr);

  // convert from Symbian
  localAddr->sin_family = sockAddr.Family();
  localAddr->sin_port = sockAddr.Port();
  localAddr->sin_addr.s_addr = ntohl(sockAddr.Address());
  
  return 0;
}
// -----------------------------------------------------------------------------
// CSdpOriginField::SetIPAddressType
// -----------------------------------------------------------------------------
//
void CSdpOriginField::SetIPAddressType( const TInetAddr& aAddr )
    {
    iAddressType.Close();
    if ( aAddr.Address() || aAddr.IsUnspecified() )
        {
        //IPv4, IPv4-Mapped IPv6 and 0.0.0.0
	    iAddressType =
            iPool.StringF( SdpCodecStringConstants::EAddressTypeIP4,
                           SdpCodecStringConstants::Table ).Copy();
        }
    else
        {
        //IPv6
        iAddressType =
            iPool.StringF( SdpCodecStringConstants::EAddressType,
                           SdpCodecStringConstants::Table ).Copy();
 		}
    }
Example #22
0
// ---------------------------------------------------------------------------
// Build internal address info object from internal address information. 
// ---------------------------------------------------------------------------
//
EXPORT_C void VPNAddrInfo::BuildVPNAddrInfo( const CInternalAddress* aInternalAddr,
                                    const TInetAddr& aDnsServerAddr,
                                    TVPNAddress& aVPNAddress,
                                    MIkeDebug& aDebug )
    {
    __ASSERT_DEBUG( aInternalAddr != NULL,
                    User::Invariant() );
    
    aVPNAddress.iVPNIfAddr = aInternalAddr->iClientIntAddr;

    //
    // Add DNS address(es) to the virtual TVPNAddress object
    // 
    TInt dnsCount = aInternalAddr->Count();
    if ( dnsCount )
        {
        aVPNAddress.iVPNIfDNS1 = *(aInternalAddr->At(0));
        if ( dnsCount > 1 )
            {
            aVPNAddress.iVPNIfDNS2 = *(aInternalAddr->At(1));          
            }
        }
    else
        {
        if ( aDnsServerAddr.Address() != KAFUnspec )
            {
#ifdef _DEBUG                   
            TBuf<39> addrBuf;
            aDnsServerAddr.OutputWithScope( addrBuf );
            aDebug.LogWriteF(_L("DNS Server Address in IKE data %S"), &addrBuf);
#endif //_DEBUG                         
            aVPNAddress.iVPNIfDNS1 = aDnsServerAddr;
            }
        else
            {
#ifdef _DEBUG            
            aDebug.LogWrite(_L("DNS server not defined in policy"));            
#endif // _DEBUG            
            }
        }   
    }   
Example #23
0
/*
 * This function converts the Internet host address cp from the standard
 * numbers-and-dots notation into binary data and stores it in the structure
 * that inp points to. 
 */
PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, struct pj_in_addr *inp)
{
    enum { MAXIPLEN = PJ_INET_ADDRSTRLEN };

    /* Initialize output with PJ_INADDR_NONE.
     * Some apps relies on this instead of the return value
     * (and anyway the return value is quite confusing!)
     */
    inp->s_addr = PJ_INADDR_NONE;

    /* Caution:
     *	this function might be called with cp->slen >= 16
     *  (i.e. when called with hostname to check if it's an IP addr).
     */
    PJ_ASSERT_RETURN(cp && cp->slen && inp, 0);
    if (cp->slen >= 16) {
	return 0;
    }

    char tempaddr8[MAXIPLEN];
    pj_memcpy(tempaddr8, cp->ptr, cp->slen);
    tempaddr8[cp->slen] = '\0';

    wchar_t tempaddr16[MAXIPLEN];
    pj_ansi_to_unicode(tempaddr8, pj_ansi_strlen(tempaddr8),
		       tempaddr16, sizeof(tempaddr16));

    TBuf<MAXIPLEN> ip_addr((const TText*)tempaddr16);

    TInetAddr addr;
    addr.Init(KAfInet);
    if (addr.Input(ip_addr) == KErrNone) {
	/* Success (Symbian IP address is in host byte order) */
	inp->s_addr = pj_htonl(addr.Address());
	return 1;
    } else {
	/* Error */
	return 0;
    }
}
// -----------------------------------------------------------------------------
// CSdpConnectionField::SetInetAddressL
// Sets address from TInetAddr
// -----------------------------------------------------------------------------
//
EXPORT_C void CSdpConnectionField::SetInetAddressL(
    const TInetAddr& aAddress,
    TInt aTTL,
    TUint aNumOfAddress )
	{
	__TEST_INVARIANT;

    if ( IsValidAddress( aAddress, aTTL, aNumOfAddress ) == KErrNone )
        {
        TBuf<KMaxAddressLength> addr16;
       	//If aAddress IPv4-Mapped IPv6, result of Output IPv4
         aAddress.Output( addr16 );

        HBufC8* tempBuf = HBufC8::NewL( addr16.Length() );
        tempBuf->Des().Copy( addr16 );

        SdpUtil::SetDefaultNetTypeAndAddrType(
            iPool, aAddress, iNetType, iAddressType );
        if(aAddress.Address() && aAddress.IsV4Mapped())
			{
			iAddressType.Close();
			iAddressType = iPool.StringF( SdpCodecStringConstants::EAddressTypeIP4,
                                      SdpCodecStringConstants::Table ).Copy();
			}
        // Set address
        delete iAddress;
        iAddress = tempBuf;
        // Set attributes for address
        iTTL = aTTL;
        iNumOfAddress = aNumOfAddress;
        }
    else
        {
        User::Leave( KErrSdpCodecConnectionField );
        }

	__TEST_INVARIANT;
	}
// -----------------------------------------------------------------------------
// CUpnpSecurityDbConnection::DeleteIpAddressL
// Delete ip address to DB.
// -----------------------------------------------------------------------------
//
void CUpnpSecurityDbConnection::DeleteIpAddressL( const TInetAddr& aIpAddress )
    {
    ExecStatementL( KUpnpSecSqlDeleteIpAddress, aIpAddress.Address() );
    }
// -----------------------------------------------------------------------------
// CUpnpSecurityDbConnection::AddIpAddressL
// Add ip address to DB.
// -----------------------------------------------------------------------------
//
void CUpnpSecurityDbConnection::AddIpAddressL( const TInetAddr& aIpAddress )
    {
    EnsureDiskSpaceL();
    ExecStatementL( KUpnpSecSqlInsertIpAddress, aIpAddress.Address() );
    }
Example #27
0
void CSTTorrentManager::OnLocalUDPReceiveL(TInetAddr aSender, const TDesC8& aData)
{
	HLWRITELN(iLog, _L("[TorrentManager] OnLocalUDPReceiveL begin"));
	
	TInetAddr localAddress;
	iNetworkManager->GetLocalAddress(1, localAddress);
	
	if (localAddress.Address() == aSender.Address())
	{
		HLWRITELN(iLog, _L("[TorrentManager] Throwing away own message"));
		return;
	}
	
#ifdef LOG_TO_FILE
	LWRITE(iLog, _L("[TorrentManager] UDP sender: "));
	TBuf<128> addressBuf;
	if (aSender.Address() == 0)
	{
		addressBuf = _L("? (could not get local address)");
	}
	else
	{
		aSender.Output(addressBuf);
		addressBuf.Append(_L(":"));
		TBuf<16> portBuf;
		portBuf.Num(localAddress.Port());
		addressBuf.Append(portBuf);
	}
	HLWRITELN(iLog, addressBuf);
#endif
	
	//HLWRITEL(iLog, _L("[TorrentManager] Data received: "));
	//HLWRITELN(iLog, aData);
	
	// TODO handle multiple torrents
	if (iTorrents.Count() == 0)
		return;
	
	if (aData.Size() >= 4)
	{
		TUint messageLength = NSTUtils::ReadInt32(aData);
		
		LWRITE(iLog, _L("[TorrentManager] Datagram length: "));
		LWRITELN(iLog, aData.Size());
				
		LWRITE(iLog, _L("[TorrentManager] Message length: "));
		LWRITELN(iLog, messageLength);
		
		if ((TUint(aData.Size()) >= (4 + messageLength)) && 
			(aData[4] == KMessageIdPiece))
		{
			TInt index = NSTUtils::ReadInt32(aData.Mid(5));
			TInt begin = NSTUtils::ReadInt32(aData.Mid(9));
			
			TBool pendingRequestFound = EFalse;
			
			// check if the incoming local piece is requested by this peer
			for (TInt i=0; i<iTorrents[0]->PeerCount(); i++)
			{
				if ((iTorrents[0]->Peer(i)->IsLocal()) && (iTorrents[0]->Peer(i)->Connection()) && (iTorrents[0]->Peer(i)->Connection()->State() == EPeerPwConnected))
				{
					pendingRequestFound = iTorrents[0]->Peer(i)->Connection()->HandleIncomingLocalPieceL(index, begin, aData.Mid(13, messageLength - 9));
					if (pendingRequestFound)
						break;
				}
			}
			
			if (!pendingRequestFound)
			{
				if ((iTorrents[0]->PieceCount() > index) && (!iTorrents[0]->Piece(index)->IsDownloaded()))
				{
					HLWRITELN(iLog, _L("[TorrentManager] Received unrequested piece"));
					
					CSTPiece* piece = iTorrents[0]->Piece(index);
					CSTPeer* peer = iTorrents[0]->GetPeer(aSender);
					
					if (piece->InsertBlockL(begin, aData.Mid(13, messageLength - 9), peer) != KErrNone)
					{
						LWRITELN(iLog, _L8("CRITICAL FAULT, Writing to piece failed")); // CRITICAL FAULT								
					}
					else
					{
						HLWRITELN(iLog, _L("[TorrentManager] Writing piece complete"));
						
						if (iTorrents[0]->EndGame())									
							iTorrents[0]->EndGamePieceReceivedL(piece, peer);
					}
					
					iTorrents[0]->iLocalSubPiecesNotRequested++;
					iTorrents[0]->iLocalSubPiecesNotRequestedSize += aData.Size();
					
					
					// TODO remove commented part if the code above is working
					/*if (piece->DownloadedSize() == begin)
					{
						CSTPeer* peer = iTorrents[0]->GetPeer(aSender);
						
						if (piece->AppendBlockL(aData, peer) != KErrNone)
						{
							LWRITELN(iLog, _L8("CRITICAL FAULT, Writing to piece failed")); // CRITICAL FAULT								
						}
						else
						{
							HLWRITELN(iLog, _L("[TorrentManager] Writing piece complete"));
							
							if (iTorrents[0]->EndGame())									
								iTorrents[0]->EndGamePieceReceivedL(piece, peer);
						}
						
						iTorrents[0]->iLocalSubPiecesNotRequested++;
					}
					else
						iTorrents[0]->iLocalSubPiecesReceivedNotMatchPieceBeginning++;*/
				}
				else
				{
					iTorrents[0]->iLocalSubPiecesReceivedAlreadyDownloaded++;
					iTorrents[0]->iLocalSubPiecesReceivedAlreadyDownloadedSize += aData.Size();
				}
			}
		}
	}
	
	HLWRITELN(iLog, _L("[TorrentManager] OnLocalUDPReceiveL end"));
}
Example #28
0
void CDHCPMessageHeaderIP4::FinishL(TDesC8& aClientId)
/**
  * Put finishing touches to message for sending
  * Basically copies in the magic cookie (99.130.83.99)
  * and the end marker then set the length of the descriptor
  * as we have been pushing data into the descriptor manually
  *
  * @param aClientId The client ID string to be added to the message
  * @see RFC 2131 for explanation of the magic cookie!
  *
  * @internalTechnology
  */
#endif //SYMBIAN_NETWORKING_DHCP_MSG_HEADERS
	{
	__CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("CDHCPMessageBase::FinishL")));
	
#ifdef SYMBIAN_NETWORKING_DHCPSERVER
	if(!iDHCPServerImpl)
	{
#endif // SYMBIAN_NETWORKING_DHCPSERVER	
	
	TUint8 reqListArray[KDhcpParameterRequestListLen] = {EDHCPHostName, EDHCPDomainNameServer, 
							EDHCPDomainName, EDHCPSubnetMask, EDHCPRouter, EDHCPBroadcastAddr, EDHCPSIPServers};
	TPtr8 ptr(reqListArray, KDhcpParameterRequestListLen, KDhcpParameterRequestListLen);
	
	// +++++++++++++++++++++++ Client ID +++++++++++++++++++++++++++++++++++++++++/
	AddOptionL(EDHCPClientID, aClientId.Length())->GetBodyDes().Copy(aClientId);
		
#ifdef SYMBIAN_NETWORKING_DHCP_MSG_HEADERS
	RBuf8 appendOpCodeList;
	appendOpCodeList.CreateL(ptr);
	if (aOptionsPtr)
		{
		TInt optLen=aOptionsPtr->Length();
		appendOpCodeList.ReAllocL(KDhcpParameterRequestListLen+optLen);
		appendOpCodeList.Append(aOptionsPtr->Ptr(),optLen);
		}
	AddOptionL(EDHCPParameterReqList, appendOpCodeList.Length())->GetBodyDes().Copy(appendOpCodeList);
	appendOpCodeList.Close();
#else
	// +++++++++++++++++++++++ Parameter Request List ++++++++++++++++++++++++++++/
	AddOptionL(EDHCPParameterReqList, ptr.Length())->GetBodyDes().Copy(ptr);
#endif		
	// +++++++++++++++++++++++ Maximum message size (2 bytes) ++++++++++++++++++++/
	AddOptionL(EDHCPMaxMsgSize, 2)->SetBigEndian(KDhcpMaxMsgSizeIP4);
	
#ifdef SYMBIAN_NETWORKING_DHCPSERVER
	}
#endif // SYMBIAN_NETWORKING_DHCPSERVER	
		
	TInetAddr magic;
	_LIT(magicCookie, "99.83.130.99");
	User::LeaveIfError(magic.Input(magicCookie));	// essential the magic cookie is correct
	iCookie.SetLittleEndian(magic.Address());
		
	ASSERT(!iOptions.FindOption(EDHCPEnd));
	AddOptionL(EDHCPEnd, 0);

   //add padding if msg shorter than 300 bytes
 	TInt len=iMsg->Length();
 	TPtr8 des=iMsg->Des();
	if (len<300)
      {
		des.AppendFill(EDHCPPad, 300-len);
      }
	}
static QList<QNetworkInterfacePrivate *> interfaceListing()
{
    TInt err(KErrNone);
    QList<QNetworkInterfacePrivate *> interfaces;
    QList<QHostAddress> addressesWithEstimatedNetmasks;

    // Open dummy socket for interface queries
    RSocket socket;
    err = socket.Open(qt_symbianGetSocketServer(), _L("udp"));
    if (err) {
        return interfaces;
    }

    // Ask socket to start enumerating interfaces
    err =  socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);
    if (err) {
        socket.Close();
        return interfaces;
    }

    int ifindex = 0;
    TPckgBuf<TSoInetInterfaceInfo> infoPckg;
    TSoInetInterfaceInfo &info = infoPckg();
    while (socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, infoPckg) == KErrNone) {
        if (info.iName != KNullDesC) {
            TName address;
            QNetworkAddressEntry entry;
            QNetworkInterfacePrivate *iface = 0;

            iface = new QNetworkInterfacePrivate;
            iface->index = ifindex++;
            interfaces << iface;
            iface->name = qt_TDesC2QString(info.iName);
            iface->flags = convertFlags(info);

            if (/*info.iFeatures&KIfHasHardwareAddr &&*/ info.iHwAddr.Family() != KAFUnspec) {
                for (TInt i = sizeof(SSockAddr); i < sizeof(SSockAddr) + info.iHwAddr.GetUserLen(); i++) {
                    address.AppendNumFixedWidth(info.iHwAddr[i], EHex, 2);
                    if ((i + 1) < sizeof(SSockAddr) + info.iHwAddr.GetUserLen())
                        address.Append(_L(":"));
                }
                address.UpperCase();
                iface->hardwareAddress = qt_TDesC2QString(address);
            }

            // Get the address of the interface
            entry.setIp(qt_QHostAddressFromTInetAddr(info.iAddress));

#if defined(QNETWORKINTERFACE_DEBUG)
            qDebug() << "address is" << info.iAddress.Family() << entry.ip();
            qDebug() << "netmask is" << info.iNetMask.Family() << qt_QHostAddressFromTInetAddr( info.iNetMask );
#endif

            // Get the interface netmask
            if (info.iNetMask.IsUnspecified()) {
                // For some reason netmask is always 0.0.0.0 for IPv4 interfaces
                // and loopback interfaces (which we statically know)
                if (info.iAddress.IsV4Mapped()) {
                    if (info.iFeatures & KIfIsLoopback) {
                        entry.setPrefixLength(32);
                    } else {
                        // Workaround: Let Symbian determine netmask based on IP address class (IPv4 only API)
                        TInetAddr netmask;
                        netmask.NetMask(info.iAddress);
                        entry.setNetmask(QHostAddress(netmask.Address())); //binary convert v4 address
                        addressesWithEstimatedNetmasks << entry.ip();
#if defined(QNETWORKINTERFACE_DEBUG)
                        qDebug() << "address class determined netmask" << entry.netmask();
#endif
                    }
                } else {
                    // For IPv6 interfaces
                    if (info.iFeatures & KIfIsLoopback) {
                        entry.setPrefixLength(128);
                    } else if (info.iNetMask.IsUnspecified()) {
                        //Don't see this error for IPv6, but try to handle it if it happens
                        entry.setPrefixLength(64); //most common
#if defined(QNETWORKINTERFACE_DEBUG)
                        qDebug() << "total guess netmask" << entry.netmask();
#endif
                        addressesWithEstimatedNetmasks << entry.ip();
                    }
                }
            } else {
                //Expected code path for IPv6 non loopback interfaces (IPv4 could come here if symbian is fixed)
                entry.setNetmask(qt_QHostAddressFromTInetAddr(info.iNetMask));
#if defined(QNETWORKINTERFACE_DEBUG)
                qDebug() << "reported netmask" << entry.netmask();
#endif
            }

            // broadcast address is determined from the netmask in postProcess()

            // Add new entry to interface address entries
            iface->addressEntries << entry;

#if defined(QNETWORKINTERFACE_DEBUG)
            qDebug("\n       Found network interface %s, interface flags:\n\
                IsUp = %d, IsRunning = %d, CanBroadcast = %d,\n\
                IsLoopBack = %d, IsPointToPoint = %d, CanMulticast = %d, \n\
                ip = %s, netmask = %s, broadcast = %s,\n\
                hwaddress = %s",
                   iface->name.toLatin1().constData(),
                   iface->flags & QNetworkInterface::IsUp, iface->flags & QNetworkInterface::IsRunning, iface->flags & QNetworkInterface::CanBroadcast,
                   iface->flags & QNetworkInterface::IsLoopBack, iface->flags & QNetworkInterface::IsPointToPoint, iface->flags & QNetworkInterface::CanMulticast,
                   entry.ip().toString().toLatin1().constData(), entry.netmask().toString().toLatin1().constData(), entry.broadcast().toString().toLatin1().constData(),
                   iface->hardwareAddress.toLatin1().constData());
#endif
        }
    }
void CConfigControl::GetDbServiceParamsL()
/**
 * Retrieves the required service parameters.
 *
 * @internalComponent
 *
 * @leave If any of the called methods leaves.
 */
	{
	TInt rc;
	TBuf<255> address;
	iService->RefreshL(*iSession);

	iDaemonConfiguration = iService->iIwfName;
	
	address = iService->iIpAddr;
	rc = iAddress.Input(address);
	if (rc != KErrNone)
		{
		__FLOG_STATIC(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::GetDbServiceParamsL - Invalid IP address format"));
		User::Leave(rc);
		}

	// So we know that we're not just picking up a static address.
	iAddress.SetAddress(iAddress.Address() + 1);

	address = iService->iIpNetMask;
	rc = iSubnetMask.Input(address);
	if (rc != KErrNone)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::GetDbServiceParamsL - Invalid netmask format [%d]"), rc);
		User::Leave(rc);
		}

	address = iService->iIpGateway;
	rc = iDefGateway.Input(address);
	if (rc != KErrNone)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::GetDbServiceParamsL - Invalid default gateway format [%d]"), rc);
		User::Leave(rc);
		}

	address = iService->iIpNameServer1;
	rc = iNameServer1.Input(address);	
	if (rc != KErrNone)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::GetDbServiceParamsL - Invalid name server format [%d]"), rc);
		User::Leave(rc);
		}

	address = iService->iIpNameServer2;
	rc = iNameServer2.Input(address);	
	if (rc != KErrNone)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::GetDbServiceParamsL - Invalid name server format [%d]"), rc);
		User::Leave(rc);
		}

	// set up the broadcast address		
	TInetAddr broadcast;
	broadcast.SubNetBroadcast(iAddress, iSubnetMask);
	iBroadcastAddress = broadcast.Address();		
	}