コード例 #1
0
EJ_BIND_FUNCTION(EJBindingHttpRequest, abort, ctx, argc, argv) {
    if (connection) {
        clearConnection();
        EJBindingEventedBase::triggerEvent(NSStringMake("abort"), 0, NULL);
    }
    return NULL;
}
コード例 #2
0
EJ_BIND_FUNCTION(EJBindingHttpRequest, open, ctx, argc, argv) {
    if (argc < 2) { return NULL; }
    
    // Cleanup previous request, if any
    clearConnection();
    clearRequest();
    
    method = JSValueToNSString(ctx, argv[0]); method->retain();
    url = JSValueToNSString(ctx, argv[1]); url->retain();
    async = argc > 2 ? JSValueToBoolean(ctx, argv[2]) : true;
    
    if (argc > 4) {
        user = JSValueToNSString(ctx, argv[3]); user->retain();
        password = JSValueToNSString(ctx, argv[4]); password->retain();
    }
    
    state = kEJHttpRequestStateOpened;
    return NULL;
}
コード例 #3
0
void WebProcessProxy::disconnect()
{
    clearConnection();

    if (m_webConnection) {
        m_webConnection->invalidate();
        m_webConnection = nullptr;
    }

    m_responsivenessTimer.stop();

    Vector<RefPtr<WebFrameProxy> > frames;
    copyValuesToVector(m_frameMap, frames);

    for (size_t i = 0, size = frames.size(); i < size; ++i)
        frames[i]->disconnect();
    m_frameMap.clear();

    m_context->disconnectProcess(this);
}
コード例 #4
0
EJ_BIND_FUNCTION(EJBindingHttpRequest, send, ctx, argc, argv) {
    if (!method || !url) { return NULL; }
    
    clearConnection();
    
    NSLOG("XHR: URL %s ", url->getCString());
    
    Uri u0 = Uri::Parse(string(url->getCString()));
    std::string host = u0.Host;
    
    EJHttpRequest* request = new EJHttpRequest();
    request->setUrl(url->getCString());
    
    // if( !requestUrl.host ) {
    //      No host? Assume we have a local file
    // 	requestUrl = [NSURL fileURLWithPath:[[EJApp instance] pathForResource:url]];
    // }

    if (host.empty()) {
        NSLOG("no host");
        EJBindingHttpRequest::loadLocalhost();
        return NULL;
    }
    
    // NSURL * requestUrl = [NSURL URLWithString:url];

    // NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:requestUrl];
    // [request setHTTPMethod:method];

    // for( NSString * header in requestHeaders ) {
    // 	[request setValue:[requestHeaders objectForKey:header] forHTTPHeaderField:header];
    // }

    // if( argc > 0 ) {
    // 	NSString * requestBody = JSValueToNSString( ctx, argv[0] );
    // 	NSData * requestData = [NSData dataWithBytes:[requestBody UTF8String] length:[requestBody length]];
    // 	[request setHTTPBody:requestData];
    // }

    // if( timeout ) {
    // 	NSTimeInterval timeoutSeconds = (float)timeout/1000.0f;
    // 	[request setTimeoutInterval:timeoutSeconds];
    // }	

    if (method->isEqual(NSStringMake("GET"))) {
        request->setRequestType(EJHttpRequest::kHttpGet);
    } else if (method->isEqual(NSStringMake("POST"))) {
        request->setRequestType(EJHttpRequest::kHttpPost);
    } else if (method->isEqual(NSStringMake("PUT"))) {
        request->setRequestType(EJHttpRequest::kHttpPut);
    } else if (method->isEqual(NSStringMake("DELETE"))) {
        request->setRequestType(EJHttpRequest::kHttpDelete);
    } else {
        request->setRequestType(EJHttpRequest::kHttpUnkown);
    }
    request->setResponseCallback(this, callfuncND_selector(EJBindingHttpRequest::onHttpRequestCompleted));

    connection = EJHttpClient::getInstance();
    connection->setTimeoutForConnect(timeout/1000);

    NSLOG("XHR: %s %s", method->getCString(), url->getCString());
    EJBindingEventedBase::triggerEvent(NSStringMake("loadstart"), 0, NULL);

    // if( async ) {
    // 	state = kEJHttpRequestStateLoading;
    // 	connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    // }
    // else {	
    // 	NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    // 	responseBody = [[NSMutableData alloc] initWithData:data];
    // 	[response retain];

    // 	state = kEJHttpRequestStateDone;
    // 	if( [response isKindOfClass:[NSHTTPURLResponse class]] ) {
    // 		NSHTTPURLResponse * urlResponse = (NSHTTPURLResponse *)response;
    // 		if( urlResponse.statusCode == 200 ) {
    // 			[self triggerEvent:@"load" argc:0 argv:NULL];
    // 		}
    // 	}
    // 	else {
    // 		[self triggerEvent:@"load" argc:0 argv:NULL];
    // 	}
    // 	[self triggerEvent:@"loadend" argc:0 argv:NULL];
    // 	[self triggerEvent:@"readystatechange" argc:0 argv:NULL];
    // }
    // [request release];

    state = kEJHttpRequestStateLoading;
    connection->send(request);
    request->release();
    EJBindingEventedBase::triggerEvent(NSStringMake("load"), 0, NULL);

    return NULL;
}
コード例 #5
0
EJBindingHttpRequest::~EJBindingHttpRequest() {
    requestHeaders->release();
    clearRequest();
    clearConnection();
}
コード例 #6
0
ファイル: ContactUser.cpp プロジェクト: HariArika/ricochet
void ContactUser::assignConnection(const QSharedPointer<Protocol::Connection> &connection)
{
    if (connection == m_connection) {
        BUG() << "Connection is already assigned to this ContactUser";
        return;
    }

    if (connection->purpose() == Protocol::Connection::Purpose::KnownContact) {
        BUG() << "Connection is already assigned to a contact";
        connection->close();
        return;
    }

    bool isOutbound = connection->direction() == Protocol::Connection::ClientSide;

    if (!connection->isConnected()) {
        BUG() << "Connection assigned to contact but isn't connected; discarding";
        connection->close();
        return;
    }

    if (!connection->hasAuthenticatedAs(Protocol::Connection::HiddenServiceAuth, hostname())) {
        BUG() << "Connection assigned to contact without matching authentication";
        connection->close();
        return;
    }

    /* KnownToPeer is set for an outbound connection when the remote end indicates
     * that it knows us as a contact. If this is set, we can assume that the
     * connection is fully built and will be kept open.
     *
     * If this isn't a request and KnownToPeer is not set, the connection has
     * effectively failed: it will be timed out and closed without a purpose.
     * This probably means that peer removed us a contact.
     */
    if (isOutbound) {
        bool knownToPeer = connection->hasAuthenticated(Protocol::Connection::KnownToPeer);
        if (m_contactRequest && knownToPeer) {
            m_contactRequest->accept();
            if (m_contactRequest)
                BUG() << "Outgoing contact request not unset after implicit accept during connection";
        } else if (!m_contactRequest && !knownToPeer) {
            qDebug() << "Contact says we're unknown; marking as rejected";
            settings()->write("rejected", true);
            connection->close();
            updateStatus();
            updateOutgoingSocket();
            return;
        }
    }

    if (m_connection && !m_connection->isConnected()) {
        qDebug() << "Replacing dead connection with new connection";
        clearConnection();
    }

    /* To resolve a race if two contacts try to connect at the same time:
     *
     * If the existing connection is in the same direction as the new one,
     * always use the new one.
     */
    if (m_connection && connection->direction() == m_connection->direction()) {
        qDebug() << "Replacing existing connection with contact because the new one goes the same direction";
        clearConnection();
    }

    /* If the existing connection is more than 30 seconds old, measured from
     * when it was successfully established, it's replaced with the new one.
     */
    if (m_connection && m_connection->age() > 30) {
        qDebug() << "Replacing existing connection with contact because it's more than 30 seconds old";
        clearConnection();
    }

    /* Otherwise, close the connection for which the server's onion-formatted
     * hostname compares less with a strcmp function
     */
    bool preferOutbound = QString::compare(hostname(), identity->hostname()) < 0;
    if (m_connection) {
        if (isOutbound == preferOutbound) {
            // New connection wins
            clearConnection();
        } else {
            // Old connection wins
            qDebug() << "Closing new connection with contact because the old connection won comparison";
            connection->close();
            return;
        }
    }

     /* If this connection is inbound and we have an outgoing connection attempt,
      * use the inbound connection if we haven't sent authentication yet, or if
      * we would lose the strcmp comparison above.
      */
    if (!isOutbound && m_outgoingSocket) {
        if (m_outgoingSocket->status() != Protocol::OutboundConnector::Authenticating || !preferOutbound) {
            // Inbound connection wins; outbound connection attempt will abort when status changes
            qDebug() << "Aborting outbound connection attempt because we got an inbound connection instead";
        } else {
            // Outbound attempt wins
            qDebug() << "Closing inbound connection with contact because the pending outbound connection won comparison";
            connection->close();
            return;
        }
    }

    if (m_connection) {
        BUG() << "After resolving connection races, ContactUser still has two connections";
        connection->close();
        return;
    }

    qDebug() << "Assigned" << (isOutbound ? "outbound" : "inbound") << "connection to contact" << uniqueID;

    if (m_contactRequest && isOutbound) {
        if (!connection->setPurpose(Protocol::Connection::Purpose::OutboundRequest)) {
            qWarning() << "BUG: Failed setting connection purpose for request";
            connection->close();
            return;
        }
    } else {
        if (m_contactRequest && !isOutbound) {
            qDebug() << "Implicitly accepting outgoing contact request for" << uniqueID << "due to incoming connection";
            m_contactRequest->accept();
        }

        if (!connection->setPurpose(Protocol::Connection::Purpose::KnownContact)) {
            qWarning() << "BUG: Failed setting connection purpose";
            connection->close();
            return;
        }
    }

    m_connection = connection;

    /* Use a queued connection to onDisconnected, because it clears m_connection.
     * If we cleared that immediately, it would be possible for the value to change
     * effectively any time we call into protocol code, which would be dangerous.
     */
    connect(m_connection.data(), &Protocol::Connection::closed, this, &ContactUser::onDisconnected, Qt::QueuedConnection);

    /* Delay the call to onConnected to allow protocol code to finish before everything
     * kicks in. In particular, this is important to allow AuthHiddenServiceChannel to
     * respond before other channels are created. */
    if (!metaObject()->invokeMethod(this, "onConnected", Qt::QueuedConnection))
        BUG() << "Failed queuing invocation of onConnected method";
}
コード例 #7
0
Boolean TPZCrossbarFlowCTMux :: dispatchEvent(const TPZEvent& event)
{        
   if( ( event.type() == _CrossbarRequest_ ) ||
       ( event.type() == _CrossbarPass_ ) )
   {
      TPZCrossbar& crossbar = (TPZCrossbar&)(getComponent());
      unsigned iPort =   event.source();
      unsigned oPort =   getOutputForInput(iPort).left();
      unsigned channel = getOutputForInput(iPort).right();
      
      if(event.type() == _CrossbarRequest_)
      {
        oPort=event.destiny();
        channel=event.channel();  
      } 
      TPZMessage *msg;
      m_MessageReceivedTable->valueAt(iPort,&msg);
      
      if(!msg) return true;
      
      if(!channel)
      {
         if(_CrossbarRequest_)
         {
           EXIT_PROGRAM("Channel set to 0 in request Not allowed");
         }
         else
         {
           EXIT_PROGRAM("Channel set to 0 in data Not allowed");
         }
      }  
      else if( ! iPort )
      {
         TPZString err;
         err.sprintf( ERR_TPZCFLOC_001, 
                      (char*)getComponent().asString(),
                      (char*)msg->asString() );
         EXIT_PROGRAM(err);
      }
      else if(!oPort)
      {
         TPZString err;
         err.sprintf( ERR_TPZCFLOC_002, 
                      (char*)getComponent().asString(),
                      (char*)msg->asString() );
         EXIT_PROGRAM(err);
      }
      
      //Here's the difference with the normal version
      if( event.type() == _CrossbarRequest_)
      {
         for(int i=1; i<=crossbar.numberOfInputs(); i++)
         {
            uPAIR temp;
            m_PortAsignamentTable->valueAt(i,temp);
            if(i!=iPort && (temp.left()==oPort) )
            {
                inputInterfaz(iPort)->sendStop();
                uTIME delayTime = getOwnerRouter().getCurrentTime() + 1;
                getEventQueue().enqueue(event,delayTime); 

   #ifndef NO_TRAZA 
                TPZString time = getOwnerRouter().getCurrentTime();       
                TPZString texto = getComponent().asString() + " CONTENTION  STOP TIME = ";
                texto += time + msg->asString() + " i=" + TPZString(iPort) +
                    ", o=" + TPZString(oPort) + ", OPORT used by i=" + TPZString(i);
                TPZWRITE2LOG( texto );
   #endif
                return true;
            }
         }
      
         if( (outputInterfaz(oPort)->isStopActive(channel)))
         {
            inputInterfaz(iPort)->sendStop();
            uTIME delayTime = getOwnerRouter().getCurrentTime() + 1;
            getEventQueue().enqueue(event,delayTime);

   #ifndef NO_TRAZA 
      TPZString time = getOwnerRouter().getCurrentTime();       
      TPZString texto = getComponent().asString() + " QUEUES  STOP TIME = ";
      texto += time + msg->asString() + " i=" + TPZString(iPort) +
               ", o=" + TPZString(oPort);
             
      TPZWRITE2LOG( texto );
   #endif
               return true;
         }
               establishConnection(iPort,oPort,channel);

      setStateForInput(iPort,Connect);   
      }

   
    
      inputInterfaz(iPort)->clearStopRightNow();
     
      outputInterfaz(oPort)->sendData(msg,channel);
      ((TPZNetwork*)(getOwnerRouter().getOwner()))->incrEventCount( TPZNetwork::SWTraversal);
      if (msg->getRoutingPort()!=_LocalNode_) 
      ((TPZNetwork*)(getOwnerRouter().getOwner()))->incrEventCount( TPZNetwork::LinkTraversal);
           
   #ifndef NO_TRAZA 
      TPZString time = getOwnerRouter().getCurrentTime();       
      TPZString texto = getComponent().asString() + " Flit Tx. TIME = ";
      texto += time + msg->asString() + " i=" + TPZString(iPort) +
               ", o=" + TPZString(oPort);
            
      TPZWRITE2LOG( texto );
   #endif
   
      if( msg->isTail() )
      {
         clearConnection(iPort);
         uPAIR temp;
         temp = getConnectionRequestForWith(oPort);
         iPort=temp.left();
         channel=temp.right();
         if( iPort != 0 )
         {
            establishConnection(iPort,oPort,channel);
            TPZEvent requestEvent(_CrossbarRequest_,iPort,oPort,channel);
            uTIME delayTime = getOwnerRouter().getCurrentTime() +
                              MAXIMO(1,getHeaderDelay());
            
            if( ((TPZCrossbar&)getComponent()).isLocalNodeOutput(oPort) )
            {
               if( getHeaderDelay() > 1 )
                  delayTime -= 1;
            }
            
            getEventQueue().enqueue(requestEvent,delayTime);
         }
      }
   }  
   return true;
}