Пример #1
0
    void testEndpoint ()
    {
        testcase ("Endpoint");

        {
            std::pair <Endpoint, bool> result (
                Endpoint::from_string_checked ("1.2.3.4"));
            expect (result.second);
            if (expect (result.first.address().is_v4 ()))
            {
                expect (result.first.address().to_v4() ==
                    AddressV4 (1, 2, 3, 4));
                expect (result.first.port() == 0);
                expect (to_string (result.first) == "1.2.3.4");
            }
        }

        {
            std::pair <Endpoint, bool> result (
                Endpoint::from_string_checked ("1.2.3.4:5"));
            expect (result.second);
            if (expect (result.first.address().is_v4 ()))
            {
                expect (result.first.address().to_v4() ==
                    AddressV4 (1, 2, 3, 4));
                expect (result.first.port() == 5);
                expect (to_string (result.first) == "1.2.3.4:5");
            }
        }

        Endpoint ep;

        ep = Endpoint (AddressV4 (127,0,0,1), 80);
        expect (! is_unspecified (ep));
        expect (! is_public (ep));
        expect (  is_private (ep));
        expect (! is_multicast (ep));
        expect (  is_loopback (ep));
        expect (to_string (ep) == "127.0.0.1:80");

        ep = Endpoint (AddressV4 (10,0,0,1));
        expect (AddressV4::get_class (ep.to_v4()) == 'A');
        expect (! is_unspecified (ep));
        expect (! is_public (ep));
        expect (  is_private (ep));
        expect (! is_multicast (ep));
        expect (! is_loopback (ep));
        expect (to_string (ep) == "10.0.0.1");

        ep = Endpoint (AddressV4 (166,78,151,147));
        expect (! is_unspecified (ep));
        expect (  is_public (ep));
        expect (! is_private (ep));
        expect (! is_multicast (ep));
        expect (! is_loopback (ep));
        expect (to_string (ep) == "166.78.151.147");
    }
void FMakeshiftServer::Init()
{
	ISocketSubsystem* SocketSubsystem = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM);

	if (SocketSubsystem != nullptr)
	{
		FString SocketDescription("MakeshiftServerSocket");

		FIPv4Endpoint Endpoint(FIPv4Address(192, 168, 1, 205), 9915);
		UE_LOG_ONLINE(Warning, TEXT("Connecting to %s"), *Endpoint.ToString());
		//Socket = FTcpSocketBuilder(*SocketName).BoundToEndpoint(Endpoint).Build();

		bool Error = true;
		Socket = SocketSubsystem->CreateSocket(NAME_Stream, *SocketDescription, true);
		if (Socket != nullptr)
		{
			Error = !Socket->Connect(*SocketSubsystem->CreateInternetAddr(Endpoint.GetAddress().GetValue(), Endpoint.GetPort()));
		}

		if (Error)
		{
			UE_LOG_ONLINE(Warning, TEXT("Failed to connect to %s"), *Endpoint.ToString());
		}
		else
		{
			int32 sent;
			char data[] = "hello there";
			Socket->Send(reinterpret_cast<const uint8 *>(data), 5, sent);
			UE_LOG_ONLINE(Warning, TEXT("Sent %d bytes"), sent);
		}
	}
}
Пример #3
0
bool FLiveEditorManager::ConnectToRemoteHost( FString IPAddress )
{
	IPAddress.Replace( TEXT(" "), TEXT("") );

	TArray<FString> Parts;
	IPAddress.ParseIntoArray( Parts, TEXT("."), true );
	if ( Parts.Num() != 4 )
		return false;

	uint8 NumericParts[4];
	for ( int32 i = 0; i < 4; ++i )
	{
		NumericParts[i] = FCString::Atoi( *Parts[i] );
	}

	FSocket* Socket = FTcpSocketBuilder(TEXT("FLiveEditorManager.RemoteConnection"));
	FIPv4Endpoint Endpoint(FIPv4Address(NumericParts[0], NumericParts[1], NumericParts[2], NumericParts[3]), LIVEEDITORLISTENSERVER_DEFAULT_PORT);
	if ( Socket->Connect(*Endpoint.ToInternetAddr()) )
	{
		RemoteConnections.Add(IPAddress, Socket);
		return true;
	}
	else
	{
		return false;
	}
}
Пример #4
0
// Automatically starts when UE4 is started.
// Populates the Token variable with the robot user's token.
void CloudyWebAPIImpl::StartupModule()
{
    UE_LOG(CloudyWebAPILog, Warning, TEXT("CloudyWebAPI started"));

    // Initialize the array with InitialArraySize
    SaveFileUrls.SetNumUninitialized(InitialArraySize);

    // BaseUrl will be updated with the correct URL
    BaseUrl = get_env_var(ENV_VAR_CLOUDYWEB_URL).c_str();
    // Token variable will be populated with the robot user's token.
    AttemptAuthentication();

    // Set up socket listener to receive commands from CloudyWeb

    //Create Socket
    FIPv4Endpoint Endpoint(SERVER_ENDPOINT);
    ListenSocket = FTcpSocketBuilder(SERVER_NAME).AsReusable().BoundToEndpoint(Endpoint).Listening(8);

    //Set Buffer Size
    int32 NewSize = 0;
    ListenSocket->SetReceiveBufferSize(BUFFER_SIZE, NewSize);

    TcpListener = new FTcpListener(*ListenSocket, CONNECTION_THREAD_TIME);
    TcpListener->OnConnectionAccepted().BindRaw(this, &CloudyWebAPIImpl::InputHandler);

    FTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateRaw(this, &CloudyWebAPIImpl::CheckConnection), CONNECTION_THREAD_TIME);


    // initialise class variables
    InputStr = "";
    HasInputStrChanged = false;

}
Пример #5
0
        void PacketHandler::handleSessionCreated(ByteArrayConstItr &begin, ByteArrayConstItr end, EstablishmentStatePtr const &state)
        {
            if(state->getState() != EstablishmentState::State::REQUEST_SENT)
                return;

            state->setTheirDH(begin, begin + 256), begin += 256;

            unsigned char ipSize = *(begin++);

            if(ipSize != 4 && ipSize != 16)
                return;

            ByteArray ip(begin, begin + ipSize);
            begin += ipSize;
            uint16_t port = parseUint16(begin);

            state->setMyEndpoint(Endpoint(ip, port));

            uint32_t relayTag = parseUint32(begin);
            state->setRelayTag(relayTag);

            uint32_t ts = parseUint32(begin);
            state->setSignatureTimestamp(ts);

            state->setSignature(begin, begin + 48);

            state->setState(EstablishmentState::State::CREATED_RECEIVED);
            m_context.establishmentManager.post(state);
        }
Пример #6
0
	Endpoint BroadcastReceiver::GetNextRemote(timeval *timeout) throw (FatalError)
	{
		UdpSocket udpSock(INADDR_ANY, mPort, true, 1);
		sockaddr_storage remoteAddr;
		socklen_t remoteAddrLength = sizeof(remoteAddr);

		BroadcastMessage msg;
		const size_t bytesRead = udpSock.RecvFrom((uint8_t *)&msg, sizeof(msg), timeout, (sockaddr *)&remoteAddr, &remoteAddrLength);
		TraceBuffer(ZONE_VERBOSE, msg.deviceId, sizeof(msg.deviceId), "%c", "%zu bytes broadcast message received DeviceId: \n", bytesRead);
		if(msg.IsWiflyBroadcast(bytesRead)) {
			Trace(ZONE_INFO, "Broadcast detected\n");
			Endpoint newRemote(remoteAddr, remoteAddrLength, msg.port, std::string((char *)&msg.deviceId[0]));
			newRemote.SetScore(1);
			return LockedInsert(newRemote) ? newRemote : Endpoint();
		}
		return Endpoint();
	}
Пример #7
0
// VFALCO NOTE This is a hack to support legacy data format
//
Endpoint Endpoint::from_string_altform (std::string const& s)
{
    // Accept the regular form if it parses
    {
        Endpoint ep (Endpoint::from_string (s));
        if (! is_unspecified (ep))
            return ep;
    }

    // Now try the alt form
    std::stringstream is (s);

    AddressV4 v4;
    is >> v4;
    if (! is.fail())
    {
        Endpoint ep (v4);

        if (is.rdbuf()->in_avail()>0)
        {
            if (! IP::detail::expect (is, ' '))
                return Endpoint();

            while (is.rdbuf()->in_avail()>0)
            {
                char c;
                is.get(c);
                if (c != ' ')
                {
                    is.unget();
                    break;
                }
            }

            Port port;
            is >> port;
            if (is.fail())
                return Endpoint();

            return ep.at_port (port);
        }
        else
        {
            // Just an address with no port
            return ep;
Пример #8
0
bool UNetworkManager::Start(int32 InPortNum) // Restart the server if configuration changed
{
	if (InPortNum == this->PortNum && this->bIsListening) return true; // Already started

	if (ConnectionSocket) // Release previous connection
	{
		ConnectionSocket->Close();
		ConnectionSocket = NULL;
	}

	if (TcpListener) // Delete previous configuration first
	{
		UE_LOG(LogUnrealCV, Warning, TEXT("Stop previous server"));
		TcpListener->Stop(); // TODO: test the robustness, will this operation successful?
		delete TcpListener;
	}

	this->PortNum = InPortNum; // Start a new TCPListener
	FIPv4Address IPAddress = FIPv4Address(0, 0, 0, 0);
	// int32 PortNum = this->PortNum; // Make this configuable
	FIPv4Endpoint Endpoint(IPAddress, PortNum);

	FSocket* ServerSocket = FTcpSocketBuilder(TEXT("FTcpListener server")) // TODO: Need to realease this socket
		// .AsReusable()
		.BoundToEndpoint(Endpoint)
		.Listening(8);

	if (ServerSocket)
	{
		int32 NewSize = 0;
		ServerSocket->SetReceiveBufferSize(2 * 1024 * 1024, NewSize);
	}
	else
	{
		this->bIsListening = false;
		UE_LOG(LogUnrealCV, Warning, TEXT("Cannot start listening on port %d, Port might be in use"), PortNum);
		return false;
	}

	TcpListener = new FTcpListener(*ServerSocket);
	// TcpListener = new FTcpListener(Endpoint); // This will be released after start
	// In FSocket, when a FSocket is set as reusable, it means SO_REUSEADDR, not SO_REUSEPORT.  see SocketsBSD.cpp
	TcpListener->OnConnectionAccepted().BindUObject(this, &UNetworkManager::Connected);
	if (TcpListener->Init())
	{
		this->bIsListening = true;
		UE_LOG(LogUnrealCV, Warning, TEXT("Start listening on %d"), PortNum);
		return true;
	}
	else
	{
		this->bIsListening = false;
		UE_LOG(LogUnrealCV, Error, TEXT("Can not start listening on port %d"), PortNum);
		return false;
	}
}
Пример #9
0
void TCPSocket::PopulateRemoteEndpoint(int socket)
{
  struct sockaddr_storage remoteAddrStor;
  socklen_t remoteLen = sizeof(remoteAddrStor);
  struct sockaddr* remoteAddr = reinterpret_cast<struct sockaddr*>(&remoteAddrStor);

  if (getpeername(socket, (struct sockaddr*) remoteAddr, &remoteLen) < 0)
    throw NetworkSystemError(errno);
    
  remoteEndpoint = Endpoint(*remoteAddr, remoteLen);
}
Пример #10
0
Endpoint Connection::peer() const
{
    socklen_t n = sizeof( sa );

    if ( valid() && !d->peer.valid() ) {
        if ( ::getpeername( d->fd, (sockaddr *)&sa, &n ) >= 0 )
            d->peer = Endpoint( (sockaddr *)&sa, n );
    }

    return d->peer;
}
Пример #11
0
Endpoint Connection::self() const
{
    socklen_t n = sizeof( sa );

    if ( valid() && !d->self.valid() ) {
        if ( ::getsockname( d->fd, (sockaddr *)&sa, &n ) >= 0 )
            d->self = Endpoint( (sockaddr *)&sa, n );
    }

    return d->self;
}
Пример #12
0
void TCPSocket::PopulateLocalEndpoint(int socket)
{
  struct sockaddr_storage localAddrStor;
  socklen_t localLen = sizeof(localAddrStor);
  struct sockaddr* localAddr = reinterpret_cast<struct sockaddr*>(&localAddrStor);
    
  if (getsockname(socket, (struct sockaddr*) localAddr, &localLen) < 0)
    throw NetworkSystemError(errno);

  localEndpoint = Endpoint(*localAddr, localLen);
}
void CTestHostlet::DescribeServiceL(CSenXmlServiceDescription& aSD) 
    { 
    if( ip2DescribeServiceL ) 
    	{
   		(*ip2DescribeServiceL)(aSD);
    	}
        else
            {
            aSD.SetEndPointL(Endpoint());
            aSD.SetContractL(Contract()); 
            aSD.SetFrameworkIdL(FrameworkId());	
            }
    }
Пример #14
0
void Resolver::Resolve()
{
  const char* charService = nullptr;
  if (port >= 0)
  {
    std::string service;
    try
    {
      service = boost::lexical_cast<std::string>(port);
    }
    catch (const boost::bad_lexical_cast&)
    {
      throw NetworkError("Invalid port number");
    }
    
    charService = service.c_str();
  }

  struct addrinfo hints;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = PF_UNSPEC;
  hints.ai_flags = AI_PASSIVE;
  hints.ai_socktype = static_cast<int>(socketType);

  const char* charHostname = nullptr;
  if (!hostname.empty()) charHostname = hostname.c_str();
  
  int error = getaddrinfo(charHostname, charService, &hints, &res);
  if (error)
  {
    if (error == EAI_SYSTEM) throw NetworkSystemError(errno);
    else throw ResolverError(error);
  }

  struct addrinfo* current = res;
  while (current)
  {
    results.emplace_back(Endpoint(*current->ai_addr, current->ai_addrlen));
    current = current->ai_next;
  }

  freeaddrinfo(res);
  res = nullptr;
}
Пример #15
0
        void PacketHandler::handleSessionRequest(ByteArrayConstItr &begin, ByteArrayConstItr end, EstablishmentStatePtr const &state)
        {
            state->setTheirDH(begin, begin + 256), begin += 256;

            unsigned char ipSize = *(begin++);

            if(ipSize != 4 && ipSize != 16)
                return;

            ByteArray ip(begin, begin + ipSize);
            begin += ipSize;
            short port = parseUint16(begin);

            state->setMyEndpoint(Endpoint(ip, port));

            state->setRelayTag(0); // TODO Relay support

            state->setState(EstablishmentState::State::REQUEST_RECEIVED);
            m_context.establishmentManager.post(state);
        }
Пример #16
0
int Connection::connect( const EString & address, uint port )
{
    EStringList names( Resolver::resolve( address ) );
    if ( names.count() == 1 )
        return connect( Endpoint( address, port ) );

    List<SerialConnector> * l = new List<SerialConnector>;

    EStringList::Iterator it( names );
    while ( it ) {
        EString name( *it );
        Endpoint e( name, port );
        if ( e.valid() )
            l->append( new SerialConnector( this, l, e ) );
        ++it;
    }

    if ( l->count() == 0 )
        return -1;

    l->first()->connect();
    return 0;
}
Пример #17
0
void UMyGameInstance::run()
{
	//Socket = SGI->Socket;
	//Connection = SGI->Connection;


	//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "URUCHOMIONO");
	if (!dupy)
	{
		dupy = 1;
		FString address = TEXT("0.0.0.0");
		int32 port = 65000;

		bool valid = true;

		TSharedRef<FInternetAddr> addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
		//ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->GetLocalHostAddr;
		addr->SetIp(*address, valid);
		addr->SetPort(port);
		//addr->GetIp(addresssss);

		FIPv4Endpoint Endpoint(addr);

		Socket = FTcpSocketBuilder(TEXT("default")).AsReusable().BoundToEndpoint(Endpoint).Listening(16);
		//Socket->GetAddress(*adddre);
		int32 new_size;
		Socket->SetReceiveBufferSize(2 << 20, new_size);



		//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Connection ~> %d"), Socket != nullptr));
		FTimerHandle czaso;
		GetWorld()->GetTimerManager().ClearTimer(czaso);
		GetWorld()->GetTimerManager().SetTimer(czaso, this, &UMyGameInstance::TCPConnectionListener, 0.01f, true);//*/

	}
}
Пример #18
0
    void testEndpoint ()
    {
        testcase ("Endpoint");

        {
            std::pair <Endpoint, bool> result (
                Endpoint::from_string_checked ("1.2.3.4"));
            expect (result.second);
            if (expect (result.first.address().is_v4 ()))
            {
                expect (result.first.address().to_v4() ==
                    AddressV4 (1, 2, 3, 4));
                expect (result.first.port() == 0);
                expect (to_string (result.first) == "1.2.3.4");
            }
        }

        {
            std::pair <Endpoint, bool> result (
                Endpoint::from_string_checked ("1.2.3.4:5"));
            expect (result.second);
            if (expect (result.first.address().is_v4 ()))
            {
                expect (result.first.address().to_v4() ==
                    AddressV4 (1, 2, 3, 4));
                expect (result.first.port() == 5);
                expect (to_string (result.first) == "1.2.3.4:5");
            }
        }

        Endpoint ep;

        ep = Endpoint (AddressV4 (127,0,0,1), 80);
        expect (! is_unspecified (ep));
        expect (! is_public (ep));
        expect (  is_private (ep));
        expect (! is_multicast (ep));
        expect (  is_loopback (ep));
        expect (to_string (ep) == "127.0.0.1:80");

        ep = Endpoint (AddressV4 (10,0,0,1));
        expect (AddressV4::get_class (ep.to_v4()) == 'A');
        expect (! is_unspecified (ep));
        expect (! is_public (ep));
        expect (  is_private (ep));
        expect (! is_multicast (ep));
        expect (! is_loopback (ep));
        expect (to_string (ep) == "10.0.0.1");

        ep = Endpoint (AddressV4 (166,78,151,147));
        expect (! is_unspecified (ep));
        expect (  is_public (ep));
        expect (! is_private (ep));
        expect (! is_multicast (ep));
        expect (! is_loopback (ep));
        expect (to_string (ep) == "166.78.151.147");

        {
            ep = Endpoint::from_string ("192.0.2.112");
            expect (! is_unspecified (ep));
            expect (ep == Endpoint::from_string_altform ("192.0.2.112"));

            auto const ep1 = Endpoint::from_string ("192.0.2.112:2016");
            expect (! is_unspecified (ep1));
            expect (ep.address() == ep1.address());
            expect (ep1.port() == 2016);

            auto const ep2 =
                Endpoint::from_string_altform ("192.0.2.112:2016");
            expect (! is_unspecified (ep2));
            expect (ep.address() == ep2.address());
            expect (ep2.port() == 2016);
            expect (ep1 == ep2);

            auto const ep3 =
                Endpoint::from_string_altform ("192.0.2.112 2016");
            expect (! is_unspecified (ep3));
            expect (ep.address() == ep3.address());
            expect (ep3.port() == 2016);
            expect (ep2 == ep3);

            auto const ep4 =
                Endpoint::from_string_altform ("192.0.2.112     2016");
            expect (! is_unspecified (ep4));
            expect (ep.address() == ep4.address());
            expect (ep4.port() == 2016);
            expect (ep3 == ep4);

            expect (to_string(ep1) == to_string(ep2));
            expect (to_string(ep1) == to_string(ep3));
            expect (to_string(ep1) == to_string(ep4));
        }

        // Failures:
        expect (is_unspecified (
            Endpoint::from_string ("192.0.2.112:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("192.0.2.112:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("192.0.2.112 port")));

        expect (is_unspecified (
            Endpoint::from_string ("ip:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("ip:port")));
        expect (is_unspecified (
            Endpoint::from_string_altform ("ip port")));

        expect (is_unspecified (
            Endpoint::from_string("")));
        expect (is_unspecified (
            Endpoint::from_string_altform("")));

        expect (is_unspecified (
            Endpoint::from_string("255")));
        expect (is_unspecified (
            Endpoint::from_string_altform("255")));

        expect (is_unspecified (
            Endpoint::from_string("512")));
        expect (is_unspecified (
            Endpoint::from_string_altform("512")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3.256")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3.256")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3:80")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3:80")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3 80")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3.4:65536")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3:65536")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3 65536")));

        expect (is_unspecified (
            Endpoint::from_string("1.2.3.4:89119")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3:89119")));
        expect (is_unspecified (
            Endpoint::from_string_altform("1.2.3 89119")));
    }
Пример #19
0
Endpoint Database::server()
{
    return Endpoint( Configuration::DbAddress, Configuration::DbPort );
}
Пример #20
0
bool ClientSocket::Connect(const std::string& ip, size_t port)
{
	return Socket::Connect(Endpoint(ip, port));
}
Пример #21
0
int main( int argc, char *argv[] )
{
    Scope global;

    Server s( "archiveopteryx", argc, argv );
    s.setup( Server::Report );

    bool security( Configuration::toggle( Configuration::Security ) );
    EString root( Configuration::text( Configuration::JailDir ) );

    if ( Configuration::toggle( Configuration::UseSmtp ) ||
            Configuration::toggle( Configuration::UseLmtp ) )
    {
        EString mc( Configuration::text( Configuration::MessageCopy ) );
        EString mcd( Configuration::text( Configuration::MessageCopyDir ) );
        if ( mc == "all" || mc == "errors" || mc == "delivered" ) {
            struct stat st;
            if ( mcd.isEmpty() )
                log( "message-copy-directory not set", Log::Disaster );
            else if ( ::stat( mcd.cstr(), &st ) < 0 || !S_ISDIR( st.st_mode ) )
                log( "Inaccessible message-copy-directory: " + mcd,
                     Log::Disaster );
            else if ( security && !mcd.startsWith( root ) )
                log( "message-copy-directory must be under jail directory " +
                     root, Log::Disaster );
        }
        else if ( mc == "none" ) {
            if ( Configuration::present( Configuration::MessageCopyDir ) )
                log( "Disregarding message-copy-directory (value " + mcd +
                     ") because message-copy is set to none " );
        }
        else {
            log( "Invalid value for message-copy: " + mc, Log::Disaster );
        }
    }


    EString sA( Configuration::text( Configuration::SmartHostAddress ) );
    uint sP( Configuration::scalar( Configuration::SmartHostPort ) );

    if ( Configuration::toggle( Configuration::UseSmtp ) &&
            Configuration::scalar( Configuration::SmtpPort ) == sP &&
            ( Configuration::text( Configuration::SmtpAddress ) == sA ||
              ( Configuration::text( Configuration::SmtpAddress ) == "" &&
                sA == "127.0.0.1" ) ) )
    {
        log( "smarthost-address/port are the same as smtp-address/port",
             Log::Disaster );
    }

    if ( Configuration::toggle( Configuration::UseLmtp ) &&
            Configuration::scalar( Configuration::LmtpPort ) == sP &&
            ( Configuration::text( Configuration::LmtpAddress ) == sA ||
              ( Configuration::text( Configuration::LmtpAddress ) == "" &&
                sA == "127.0.0.1" ) ) )
    {
        log( "smarthost-address/port are the same as lmtp-address/port",
             Log::Disaster );
    }

    if ( Configuration::toggle( Configuration::UseSmtpSubmit ) &&
            Configuration::scalar( Configuration::SmtpSubmitPort ) == sP &&
            ( Configuration::text( Configuration::SmtpSubmitAddress ) == sA ||
              ( Configuration::text( Configuration::SmtpSubmitAddress ) == "" &&
                sA == "127.0.0.1" ) ) )
    {
        log( "smarthost-address/port are the same as "
             "smtp-submit-address/port", Log::Disaster );
    }


    EString app =
        Configuration::text( Configuration::AllowPlaintextPasswords ).lower();
    if ( !( app == "always" || app == "never" ) )
        ::log( "Unknown value for allow-plaintext-passwords: " + app,
               Log::Disaster );
    if ( app == "never" &&
            Configuration::toggle( Configuration::UseTls ) == false &&
            Configuration::toggle( Configuration::AuthCramMd5 ) == false &&
            Configuration::toggle( Configuration::AuthDigestMd5 ) == false )
        ::log( "allow-plaintext-passwords is 'never' and use-tls is 'false', "
               "but only plaintext authentication mechanisms are allowed",
               Log::Disaster );

    EString apa =
        Configuration::text( Configuration::AllowPlaintextAccess ).lower();
    if ( !( apa == "always" || apa == "localhost" || apa == "never" ) )
        ::log( "Unknown value for allow-plaintext-access: " + apa,
               Log::Disaster );
    if ( apa == "never" &&
            Configuration::toggle( Configuration::UseTls ) == false )
        ::log( "allow-plaintext-access is 'never', but use-tls is 'false'",
               Log::Disaster );

    // set up an EGD server for openssl
    Entropy::setup();
    EString egd( root );
    if ( !egd.endsWith( "/" ) )
        egd.append( "/" );
    egd.append( "var/run/egd-pool" );
    (void)new Listener< EntropyProvider >( Endpoint( egd, 0 ), "EGD" );
    if ( !security ) {
        struct stat st;
        if ( stat( "/var/run/edg-pool", &st ) < 0 ) {
            log( "Security is disabled and /var/run/edg-pool does not exist. "
                 "Creating it just in case openssl wants to access it." );
            (void)new Listener< EntropyProvider >(
                Endpoint( "/var/run/edg-pool", 0 ), "EGD(/)" );
        }
    }
    if ( ::chmod( egd.cstr(), 0666 ) < 0 )
        log( "Could not grant r/w access to EGD socket", Log::Disaster );

    Listener< IMAP >::create(
        "IMAP", Configuration::toggle( Configuration::UseImap ),
        Configuration::ImapAddress, Configuration::ImapPort
    );
    Listener< IMAPS >::create(
        "IMAPS", Configuration::toggle( Configuration::UseImaps ),
        Configuration::ImapsAddress, Configuration::ImapsPort
    );
    Listener< POP >::create(
        "POP3", Configuration::toggle( Configuration::UsePop ),
        Configuration::PopAddress, Configuration::PopPort
    );
    Listener< POPS >::create(
        "POP3S", Configuration::toggle( Configuration::UsePops ),
        Configuration::PopsAddress, Configuration::PopsPort
    );
    Listener< ManageSieve >::create(
        "Sieve", Configuration::toggle( Configuration::UseSieve ),
        Configuration::ManageSieveAddress, Configuration::ManageSievePort
    );
    Listener< SMTP >::create(
        "SMTP", Configuration::toggle( Configuration::UseSmtp ),
        Configuration::SmtpAddress, Configuration::SmtpPort
    );
    Listener< LMTP >::create(
        "LMTP", Configuration::toggle( Configuration::UseLmtp ),
        Configuration::LmtpAddress, Configuration::LmtpPort
    );
    Listener< SMTPSubmit >::create(
        "SMTP-Submit", Configuration::toggle( Configuration::UseSmtpSubmit ),
        Configuration::SmtpSubmitAddress, Configuration::SmtpSubmitPort
    );
    Listener< SMTPS >::create(
        "SMTPS", Configuration::toggle( Configuration::UseSmtps ),
        Configuration::SmtpsAddress, Configuration::SmtpsPort
    );

    if ( Configuration::toggle( Configuration::UseTls ) ) {
        TlsThread::setup();
    }

    s.setup( Server::LogStartup );

    Listener< GraphDumper >::create(
        "Statistics", Configuration::toggle( Configuration::UseStatistics ),
        Configuration::StatisticsAddress, Configuration::StatisticsPort
    );

    EventLoop::global()->setMemoryUsage(
        1024 * 1024 * Configuration::scalar( Configuration::MemoryLimit ) );

    Database::setup();

    s.setup( Server::Finish );

    StartupWatcher * w = new StartupWatcher;

    Database::checkSchema( w );
    if ( security )
        Database::checkAccess( w );
    EventLoop::global()->setStartup( true );
    Mailbox::setup( w );

    SpoolManager::setup();
    Selector::setup();
    Flag::setup();
    IMAP::setup();

    if ( !security )
        (void)new ConnectionObliterator;

    s.run();
}
Пример #22
0
		Endpoint read_v6_endpoint(InIt& in)
		{
			address addr = read_v6_address(in);
			int port = read_uint16(in);
			return Endpoint(addr, port);
		}
Пример #23
0
void metaxml(ofstream * fout) {

  *fout<<"     <configFile>&lt;?xml version='1.0'?&gt;"<<endl;
  *fout<<"&lt;xc:Partition xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"  xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xc=\"http://xdaq.web.cern.ch/xdaq/xsd/2004/XMLConfiguration-30\"&gt;"<<endl;

  if (!ttc_) { //a (successful) test -- this is a modification from the working configurations in the past
    *fout<<Context("GlobalErrorDispatcher")<<endl;
    
    *fout<<App("GlobalErrorDispatcher")<<endl;
    *fout<<Module("GlobalErrorDispatcher")<<endl;
    *fout<<App("AjaxLogReader")<<endl;
    *fout<<Module("AjaxLogReader")<<endl;
    *fout<<CloseContext()<<endl;
  }

  *fout<<Context("PixelSupervisor")<<endl;
  *fout<<Endpoint("PixelSupervisor")<<endl;
  *fout<<App("PixelSupervisor")<<endl;
  if (!ttc_) *fout<<Module("xdaq2rc")<<endl;
  if (!ttc_)   *fout<<Module("PixelSupervisor")<<endl;
  *fout<<CloseContext()<<endl;

  *fout<<Context("PixelDCSFSMInterface")<<endl;
  *fout<<Endpoint("PixelDCSFSMInterface")<<endl;
  *fout<<App("PixelDCSFSMInterface")<<endl;

  *fout<<App("PixelDCStoTrkFECDpInterface")<<endl;
  if (!ttc_)   *fout<<Module("PixelDCSFSMInterface")<<endl;

  *fout<<App("tstore::TStore")<<endl;
  if (!ttc_) {
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libtstoreutils.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libxalan-c.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libxoapfilter.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libtstore.so")<<endl;
  }
  *fout<<CloseContext()<<endl;

  for (int jj=1; jj<=3; jj++) {

    if (fpixonly_ && jj!=3) continue;
    if (bpixonly_ && jj==3) continue;

    *fout<<Context("PixelFEDSupervisor",jj)<<endl;
    *fout<<Endpoint("PixelFEDSupervisor",jj)<<endl;
    
    *fout<<App("PixelFEDSupervisor",jj)<<endl;
  if (!ttc_)     *fout<<Module("PixelFEDSupervisor")<<endl;
    
    *fout<<XApp("xplore::Application","appshort")<<endl;
    if (!ttc_) {
      *fout<<MiscModule("/lib/libslp.so")<<endl;
      *fout<<MiscModule("${XDAQ_ROOT}/lib/libxslp.so")<<endl;
      *fout<<MiscModule("${XDAQ_ROOT}/lib/libxploreutils.so")<<endl;
      *fout<<MiscModule("${XDAQ_ROOT}/lib/libxplore.so")<<endl;
    }    

    *fout<<XApp("sentinel::Application","applong")<<endl;
    if (!ttc_) {
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libwsaddressing.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libwseventing.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libsentinelutils.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libsentinel.so")<<endl;
    }
    
    *fout<<XApp("xmas::sensor::Application","applong")<<endl;
    if (!ttc_) {
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libwsutils.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libxmasutils.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libwsbrokerutils.so")<<endl;
    *fout<<MiscModule("${XDAQ_ROOT}/lib/libxmassensor.so")<<endl;
    }
    *fout<<CloseContext()<<endl;
  }

  for (int jj=1; jj<=2; jj++) {

    if (fpixonly_ && jj!=2) continue;
    if (bpixonly_ && jj!=1) continue;

    *fout<<Context("PixelFECSupervisor",jj)<<endl;
    *fout<<Endpoint("PixelFECSupervisor",jj)<<endl;
    *fout<<App("PixelFECSupervisor",jj)<<endl;
    if (!ttc_)     *fout<<Module("PixelFECSupervisor")<<endl;
    *fout<<CloseContext()<<endl;
  }

  for (int jj=1; jj<=2; jj++) {

    if (fpixonly_ && jj!=2) continue;
    if (bpixonly_ && jj!=1) continue;

    *fout<<Context("PixelTKFECSupervisor",jj)<<endl;
    //for reasons that i do not understand, there is no endpoint in our model configuration for instance 1
    //it appears that our configurations are inconsistent in their use of endpoints
    if (jj==2) *fout<<Endpoint("PixelTKFECSupervisor",jj)<<endl;
    *fout<<App("PixelTKFECSupervisor",jj)<<endl;
    if (!ttc_)     *fout<<Module("PixelTKFECSupervisor")<<endl;
    *fout<<CloseContext()<<endl;
  }

  for (int jj=1; jj<=2; jj++) {

    if (fpixonly_ && jj!=2) continue;
    if (bpixonly_ && jj!=1) continue;

    *fout<<Context("ttc::TTCciControl",jj)<<endl;
    //it seems that some configs have no endpoints for the ttc , but others do
    *fout<<Endpoint("ttc::TTCciControl",jj)<<endl;
    *fout<<App("ttc::TTCciControl",jj)<<endl;
    //this 'if' is new. If we are running from rpm then we only want this included in the TTC xdaq application block

    if (ttc_)  {
		*fout<<Module("ttc::TTCciControl")<<endl;
    	// marc *fout<<MiscModule("${XDAQ_ROOT}/lib/libttcttcci.so")<<endl;
    	*fout<<MiscModuleTTC("file:///opt/xdaq/lib/libttcutils.so")<<endl;
    	*fout<<MiscModuleTTC("file:///opt/xdaq/lib/libttcmonitoring.so")<<endl;
	}
    *fout<<CloseContext()<<endl;
  }

  *fout<<Context("psx")<<endl;
  //this is going to leave the instance=0 out of the psx server def'n
  //i will have to test if this is ok
  *fout<<XApp("psx","applong")<<endl;
  *fout<<CloseContext()<<endl;

  //not using this anymore!
//   *fout<<Context("psxtk")<<endl;
//   *fout<<XApp("psxtk","applong")<<endl;
//   *fout<<CloseContext()<<endl;

  *fout<<RCMS()<<endl;
  *fout<<JobControlBlock()<<endl;
  *fout<<"&lt;/xc:Partition&gt;</configFile>\n   </XdaqExecutive>"<<endl<<endl;


}
Пример #24
0
int main( int argc, char ** argv )
{
    Scope global;
    EventLoop::setup();

    const char * error = 0;
    bool ok = true;
    if ( argc != 5 ) {
        error = "Wrong number of arguments";
        ok = false;
    }

    uint port = 0;
    if ( ok ) {
        port = EString( argv[1] ).number( &ok );
        if ( !ok )
            error = "Could not parse own port number";
    }
    if ( ok ) {
        Listener<RecorderServer> * l4
            = new Listener<RecorderServer>( Endpoint( "0.0.0.0", port ),
                                            "recording relay/4" );
        Allocator::addEternal( l4, "recording listener" );
        Listener<RecorderServer> * l6
            = new Listener<RecorderServer>( Endpoint( "::", port ),
                                            "recording relay/6" );
        Allocator::addEternal( l6, "recording listener" );

        if ( l4->state() != Connection::Listening &&
             l6->state() != Connection::Listening )
            error = "Could not listen for connections";
    }

    if ( ok ) {
        port = EString( argv[3] ).number( &ok );
        if ( !ok )
            error = "Could not parse server's port number";
    }

    if ( ok ) {
        EStringList l = Resolver::resolve( argv[2] );
        if ( l.isEmpty() ) {
            ok = false;
            error = (EString("Cannot resolve ") + argv[2] +
                     ": " + Resolver::errors().join( ", " ) ).cstr();
        }
        else {
            ep = new Endpoint( *l.first(), port );
            Allocator::addEternal( ep, "target server endpoint" );
        }
        if ( ep && !ep->valid() ) {
            ok = false;
            error = "Invalid server address";
        }
    }

    if ( !ok ) {
        fprintf( stderr,
                 "Error: %s\n"
                 "Usage: recorder port address port filebase\n"
                 "       First port: The recorder's own port.\n"
                 "       Address: The IP address of the server to forward to.\n"
                 "       Second port: The server port to forward to.\n"
                 "       Filebase: The filename base (.<blah> is added).\n",
                 error );
        exit( 1 );
    }

    ::base = new EString( argv[4] );
    Allocator::addEternal( ::base, "base of recorded file names" );

    global.setLog( new Log );
    EventLoop::global()->start();
}
Пример #25
0
/*
      DMDAGetFaceInterpolation - Gets the interpolation for a face based coarse space

*/
PetscErrorCode DMDAGetFaceInterpolation(DM da,PC_Exotic *exotic,Mat Aglobal,MatReuse reuse,Mat *P)
{
    PetscErrorCode         ierr;
    PetscInt               dim,i,j,k,m,n,p,dof,Nint,Nface,Nwire,Nsurf,*Iint,*Isurf,cint = 0,csurf = 0,istart,jstart,kstart,*II,N,c = 0;
    PetscInt               mwidth,nwidth,pwidth,cnt,mp,np,pp,Ntotal,gl[6],*globals,Ng,*IIint,*IIsurf,Nt;
    Mat                    Xint, Xsurf,Xint_tmp;
    IS                     isint,issurf,is,row,col;
    ISLocalToGlobalMapping ltg;
    MPI_Comm               comm;
    Mat                    A,Aii,Ais,Asi,*Aholder,iAii;
    MatFactorInfo          info;
    PetscScalar            *xsurf,*xint;
#if defined(PETSC_USE_DEBUG_foo)
    PetscScalar            tmp;
#endif
    PetscTable             ht;

    PetscFunctionBegin;
    ierr = DMDAGetInfo(da,&dim,0,0,0,&mp,&np,&pp,&dof,0,0,0,0,0);
    CHKERRQ(ierr);
    if (dof != 1) SETERRQ(PetscObjectComm((PetscObject)da),PETSC_ERR_SUP,"Only for single field problems");
    if (dim != 3) SETERRQ(PetscObjectComm((PetscObject)da),PETSC_ERR_SUP,"Only coded for 3d problems");
    ierr   = DMDAGetCorners(da,0,0,0,&m,&n,&p);
    CHKERRQ(ierr);
    ierr   = DMDAGetGhostCorners(da,&istart,&jstart,&kstart,&mwidth,&nwidth,&pwidth);
    CHKERRQ(ierr);
    istart = istart ? -1 : 0;
    jstart = jstart ? -1 : 0;
    kstart = kstart ? -1 : 0;

    /*
      the columns of P are the interpolation of each coarse grid point (one for each vertex and edge)
      to all the local degrees of freedom (this includes the vertices, edges and faces).

      Xint are the subset of the interpolation into the interior

      Xface are the interpolation onto faces but not into the interior

      Xsurf are the interpolation onto the vertices and edges (the surfbasket)
                                        Xint
      Symbolically one could write P = (Xface) after interchanging the rows to match the natural ordering on the domain
                                        Xsurf
    */
    N     = (m - istart)*(n - jstart)*(p - kstart);
    Nint  = (m-2-istart)*(n-2-jstart)*(p-2-kstart);
    Nface = 2*((m-2-istart)*(n-2-jstart) + (m-2-istart)*(p-2-kstart) + (n-2-jstart)*(p-2-kstart));
    Nwire = 4*((m-2-istart) + (n-2-jstart) + (p-2-kstart)) + 8;
    Nsurf = Nface + Nwire;
    ierr  = MatCreateSeqDense(MPI_COMM_SELF,Nint,6,NULL,&Xint);
    CHKERRQ(ierr);
    ierr  = MatCreateSeqDense(MPI_COMM_SELF,Nsurf,6,NULL,&Xsurf);
    CHKERRQ(ierr);
    ierr  = MatDenseGetArray(Xsurf,&xsurf);
    CHKERRQ(ierr);

    /*
       Require that all 12 edges and 6 faces have at least one grid point. Otherwise some of the columns of
       Xsurf will be all zero (thus making the coarse matrix singular).
    */
    if (m-istart < 3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Number of grid points per process in X direction must be at least 3");
    if (n-jstart < 3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Number of grid points per process in Y direction must be at least 3");
    if (p-kstart < 3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Number of grid points per process in Z direction must be at least 3");

    cnt = 0;
    for (j=1; j<n-1-jstart; j++) {
        for (i=1; i<m-istart-1; i++) xsurf[cnt++ + 0*Nsurf] = 1;
    }

    for (k=1; k<p-1-kstart; k++) {
        for (i=1; i<m-istart-1; i++) xsurf[cnt++ + 1*Nsurf] = 1;
        for (j=1; j<n-1-jstart; j++) {
            xsurf[cnt++ + 2*Nsurf] = 1;
            /* these are the interior nodes */
            xsurf[cnt++ + 3*Nsurf] = 1;
        }
        for (i=1; i<m-istart-1; i++) xsurf[cnt++ + 4*Nsurf] = 1;
    }
    for (j=1; j<n-1-jstart; j++) {
        for (i=1; i<m-istart-1; i++) xsurf[cnt++ + 5*Nsurf] = 1;
    }

#if defined(PETSC_USE_DEBUG_foo)
    for (i=0; i<Nsurf; i++) {
        tmp = 0.0;
        for (j=0; j<6; j++) tmp += xsurf[i+j*Nsurf];

        if (PetscAbsScalar(tmp-1.0) > 1.e-10) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Wrong Xsurf interpolation at i %D value %g",i,(double)PetscAbsScalar(tmp));
    }
#endif
    ierr = MatDenseRestoreArray(Xsurf,&xsurf);
    CHKERRQ(ierr);
    /* ierr = MatView(Xsurf,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);*/


    /*
         I are the indices for all the needed vertices (in global numbering)
         Iint are the indices for the interior values, I surf for the surface values
              (This is just for the part of the global matrix obtained with MatGetSubMatrix(), it
               is NOT the local DMDA ordering.)
         IIint and IIsurf are the same as the Iint, Isurf except they are in the global numbering
    */
#define Endpoint(a,start,b) (a == 0 || a == (b-1-start))
    ierr = PetscMalloc3(N,&II,Nint,&Iint,Nsurf,&Isurf);
    CHKERRQ(ierr);
    ierr = PetscMalloc2(Nint,&IIint,Nsurf,&IIsurf);
    CHKERRQ(ierr);
    for (k=0; k<p-kstart; k++) {
        for (j=0; j<n-jstart; j++) {
            for (i=0; i<m-istart; i++) {
                II[c++] = i + j*mwidth + k*mwidth*nwidth;

                if (!Endpoint(i,istart,m) && !Endpoint(j,jstart,n) && !Endpoint(k,kstart,p)) {
                    IIint[cint]  = i + j*mwidth + k*mwidth*nwidth;
                    Iint[cint++] = i + j*(m-istart) + k*(m-istart)*(n-jstart);
                } else {
                    IIsurf[csurf]  = i + j*mwidth + k*mwidth*nwidth;
                    Isurf[csurf++] = i + j*(m-istart) + k*(m-istart)*(n-jstart);
                }
            }
        }
    }
    if (c != N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"c != N");
    if (cint != Nint) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"cint != Nint");
    if (csurf != Nsurf) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"csurf != Nsurf");
    ierr = DMGetLocalToGlobalMapping(da,&ltg);
    CHKERRQ(ierr);
    ierr = ISLocalToGlobalMappingApply(ltg,N,II,II);
    CHKERRQ(ierr);
    ierr = ISLocalToGlobalMappingApply(ltg,Nint,IIint,IIint);
    CHKERRQ(ierr);
    ierr = ISLocalToGlobalMappingApply(ltg,Nsurf,IIsurf,IIsurf);
    CHKERRQ(ierr);
    ierr = PetscObjectGetComm((PetscObject)da,&comm);
    CHKERRQ(ierr);
    ierr = ISCreateGeneral(comm,N,II,PETSC_COPY_VALUES,&is);
    CHKERRQ(ierr);
    ierr = ISCreateGeneral(PETSC_COMM_SELF,Nint,Iint,PETSC_COPY_VALUES,&isint);
    CHKERRQ(ierr);
    ierr = ISCreateGeneral(PETSC_COMM_SELF,Nsurf,Isurf,PETSC_COPY_VALUES,&issurf);
    CHKERRQ(ierr);
    ierr = PetscFree3(II,Iint,Isurf);
    CHKERRQ(ierr);

    ierr = ISSort(is);
    CHKERRQ(ierr);
    ierr = MatGetSubMatrices(Aglobal,1,&is,&is,MAT_INITIAL_MATRIX,&Aholder);
    CHKERRQ(ierr);
    A    = *Aholder;
    ierr = PetscFree(Aholder);
    CHKERRQ(ierr);

    ierr = MatGetSubMatrix(A,isint,isint,MAT_INITIAL_MATRIX,&Aii);
    CHKERRQ(ierr);
    ierr = MatGetSubMatrix(A,isint,issurf,MAT_INITIAL_MATRIX,&Ais);
    CHKERRQ(ierr);
    ierr = MatGetSubMatrix(A,issurf,isint,MAT_INITIAL_MATRIX,&Asi);
    CHKERRQ(ierr);

    /*
       Solve for the interpolation onto the interior Xint
    */
    ierr = MatMatMult(Ais,Xsurf,MAT_INITIAL_MATRIX,PETSC_DETERMINE,&Xint_tmp);
    CHKERRQ(ierr);
    ierr = MatScale(Xint_tmp,-1.0);
    CHKERRQ(ierr);

    if (exotic->directSolve) {
        ierr = MatGetFactor(Aii,MATSOLVERPETSC,MAT_FACTOR_LU,&iAii);
        CHKERRQ(ierr);
        ierr = MatFactorInfoInitialize(&info);
        CHKERRQ(ierr);
        ierr = MatGetOrdering(Aii,MATORDERINGND,&row,&col);
        CHKERRQ(ierr);
        ierr = MatLUFactorSymbolic(iAii,Aii,row,col,&info);
        CHKERRQ(ierr);
        ierr = ISDestroy(&row);
        CHKERRQ(ierr);
        ierr = ISDestroy(&col);
        CHKERRQ(ierr);
        ierr = MatLUFactorNumeric(iAii,Aii,&info);
        CHKERRQ(ierr);
        ierr = MatMatSolve(iAii,Xint_tmp,Xint);
        CHKERRQ(ierr);
        ierr = MatDestroy(&iAii);
        CHKERRQ(ierr);
    } else {
        Vec         b,x;
        PetscScalar *xint_tmp;

        ierr = MatDenseGetArray(Xint,&xint);
        CHKERRQ(ierr);
        ierr = VecCreateSeqWithArray(PETSC_COMM_SELF,1,Nint,0,&x);
        CHKERRQ(ierr);
        ierr = MatDenseGetArray(Xint_tmp,&xint_tmp);
        CHKERRQ(ierr);
        ierr = VecCreateSeqWithArray(PETSC_COMM_SELF,1,Nint,0,&b);
        CHKERRQ(ierr);
        ierr = KSPSetOperators(exotic->ksp,Aii,Aii);
        CHKERRQ(ierr);
        for (i=0; i<6; i++) {
            ierr = VecPlaceArray(x,xint+i*Nint);
            CHKERRQ(ierr);
            ierr = VecPlaceArray(b,xint_tmp+i*Nint);
            CHKERRQ(ierr);
            ierr = KSPSolve(exotic->ksp,b,x);
            CHKERRQ(ierr);
            ierr = VecResetArray(x);
            CHKERRQ(ierr);
            ierr = VecResetArray(b);
            CHKERRQ(ierr);
        }
        ierr = MatDenseRestoreArray(Xint,&xint);
        CHKERRQ(ierr);
        ierr = MatDenseRestoreArray(Xint_tmp,&xint_tmp);
        CHKERRQ(ierr);
        ierr = VecDestroy(&x);
        CHKERRQ(ierr);
        ierr = VecDestroy(&b);
        CHKERRQ(ierr);
    }
    ierr = MatDestroy(&Xint_tmp);
    CHKERRQ(ierr);

#if defined(PETSC_USE_DEBUG_foo)
    ierr = MatDenseGetArray(Xint,&xint);
    CHKERRQ(ierr);
    for (i=0; i<Nint; i++) {
        tmp = 0.0;
        for (j=0; j<6; j++) tmp += xint[i+j*Nint];

        if (PetscAbsScalar(tmp-1.0) > 1.e-10) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Wrong Xint interpolation at i %D value %g",i,(double)PetscAbsScalar(tmp));
    }
    ierr = MatDenseRestoreArray(Xint,&xint);
    CHKERRQ(ierr);
    /* ierr =MatView(Xint,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); */
#endif


    /*         total faces    */
    Ntotal =  mp*np*(pp+1) + mp*pp*(np+1) + np*pp*(mp+1);

    /*
        For each vertex, edge, face on process (in the same orderings as used above) determine its local number including ghost points
    */
    cnt = 0;
    {
        gl[cnt++] = mwidth+1;
    }
    {
        {
            gl[cnt++] = mwidth*nwidth+1;
        }
        {
            gl[cnt++] = mwidth*nwidth + mwidth; /* these are the interior nodes */ gl[cnt++] = mwidth*nwidth + mwidth+m-istart-1;
        }
        {
            gl[cnt++] = mwidth*nwidth+mwidth*(n-jstart-1)+1;
        }
    }
    {
        gl[cnt++] = mwidth*nwidth*(p-kstart-1) + mwidth+1;
    }

    /* PetscIntView(6,gl,PETSC_VIEWER_STDOUT_WORLD); */
    /* convert that to global numbering and get them on all processes */
    ierr = ISLocalToGlobalMappingApply(ltg,6,gl,gl);
    CHKERRQ(ierr);
    /* PetscIntView(6,gl,PETSC_VIEWER_STDOUT_WORLD); */
    ierr = PetscMalloc1(6*mp*np*pp,&globals);
    CHKERRQ(ierr);
    ierr = MPI_Allgather(gl,6,MPIU_INT,globals,6,MPIU_INT,PetscObjectComm((PetscObject)da));
    CHKERRQ(ierr);

    /* Number the coarse grid points from 0 to Ntotal */
    ierr = MatGetSize(Aglobal,&Nt,NULL);
    CHKERRQ(ierr);
    ierr = PetscTableCreate(Ntotal/3,Nt+1,&ht);
    CHKERRQ(ierr);
    for (i=0; i<6*mp*np*pp; i++) {
        ierr = PetscTableAddCount(ht,globals[i]+1);
        CHKERRQ(ierr);
    }
    ierr = PetscTableGetCount(ht,&cnt);
    CHKERRQ(ierr);
    if (cnt != Ntotal) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Hash table size %D not equal to total number coarse grid points %D",cnt,Ntotal);
    ierr = PetscFree(globals);
    CHKERRQ(ierr);
    for (i=0; i<6; i++) {
        ierr = PetscTableFind(ht,gl[i]+1,&gl[i]);
        CHKERRQ(ierr);
        gl[i]--;
    }
    ierr = PetscTableDestroy(&ht);
    CHKERRQ(ierr);
    /* PetscIntView(6,gl,PETSC_VIEWER_STDOUT_WORLD); */

    /* construct global interpolation matrix */
    ierr = MatGetLocalSize(Aglobal,&Ng,NULL);
    CHKERRQ(ierr);
    if (reuse == MAT_INITIAL_MATRIX) {
        ierr = MatCreateAIJ(PetscObjectComm((PetscObject)da),Ng,PETSC_DECIDE,PETSC_DECIDE,Ntotal,Nint+Nsurf,NULL,Nint,NULL,P);
        CHKERRQ(ierr);
    } else {
        ierr = MatZeroEntries(*P);
        CHKERRQ(ierr);
    }
    ierr = MatSetOption(*P,MAT_ROW_ORIENTED,PETSC_FALSE);
    CHKERRQ(ierr);
    ierr = MatDenseGetArray(Xint,&xint);
    CHKERRQ(ierr);
    ierr = MatSetValues(*P,Nint,IIint,6,gl,xint,INSERT_VALUES);
    CHKERRQ(ierr);
    ierr = MatDenseRestoreArray(Xint,&xint);
    CHKERRQ(ierr);
    ierr = MatDenseGetArray(Xsurf,&xsurf);
    CHKERRQ(ierr);
    ierr = MatSetValues(*P,Nsurf,IIsurf,6,gl,xsurf,INSERT_VALUES);
    CHKERRQ(ierr);
    ierr = MatDenseRestoreArray(Xsurf,&xsurf);
    CHKERRQ(ierr);
    ierr = MatAssemblyBegin(*P,MAT_FINAL_ASSEMBLY);
    CHKERRQ(ierr);
    ierr = MatAssemblyEnd(*P,MAT_FINAL_ASSEMBLY);
    CHKERRQ(ierr);
    ierr = PetscFree2(IIint,IIsurf);
    CHKERRQ(ierr);


#if defined(PETSC_USE_DEBUG_foo)
    {
        Vec         x,y;
        PetscScalar *yy;
        ierr = VecCreateMPI(PetscObjectComm((PetscObject)da),Ng,PETSC_DETERMINE,&y);
        CHKERRQ(ierr);
        ierr = VecCreateMPI(PetscObjectComm((PetscObject)da),PETSC_DETERMINE,Ntotal,&x);
        CHKERRQ(ierr);
        ierr = VecSet(x,1.0);
        CHKERRQ(ierr);
        ierr = MatMult(*P,x,y);
        CHKERRQ(ierr);
        ierr = VecGetArray(y,&yy);
        CHKERRQ(ierr);
        for (i=0; i<Ng; i++) {
            if (PetscAbsScalar(yy[i]-1.0) > 1.e-10) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Wrong p interpolation at i %D value %g",i,(double)PetscAbsScalar(yy[i]));
        }
        ierr = VecRestoreArray(y,&yy);
        CHKERRQ(ierr);
        ierr = VecDestroy(x);
        CHKERRQ(ierr);
        ierr = VecDestroy(y);
        CHKERRQ(ierr);
    }
#endif

    ierr = MatDestroy(&Aii);
    CHKERRQ(ierr);
    ierr = MatDestroy(&Ais);
    CHKERRQ(ierr);
    ierr = MatDestroy(&Asi);
    CHKERRQ(ierr);
    ierr = MatDestroy(&A);
    CHKERRQ(ierr);
    ierr = ISDestroy(&is);
    CHKERRQ(ierr);
    ierr = ISDestroy(&isint);
    CHKERRQ(ierr);
    ierr = ISDestroy(&issurf);
    CHKERRQ(ierr);
    ierr = MatDestroy(&Xint);
    CHKERRQ(ierr);
    ierr = MatDestroy(&Xsurf);
    CHKERRQ(ierr);
    PetscFunctionReturn(0);
}
Пример #26
0
		Endpoint read_v4_endpoint(InIt&& in)
		{
			address addr = read_v4_address(in);
			std::uint16_t port = read_uint16(in);
			return Endpoint(addr, port);
		}