Esempio n. 1
0
void CallSetuptState::processRequest(const std::string &data, User &context) {
    std::cout << context.getUid() << " in CallSetuptState " << data.substr(0, 10) << std::endl;

    if (data.compare(0, 3, "cnr") == 0) { // client wants to dial a peer

        string encrypted = data.substr(4); //take data part

        auto elements = StringHelper::split(encrypted, ',');

        string dest_uid(elements->at(0));
        string my_pub_key(elements->at(1));
        std::replace(my_pub_key.begin(), my_pub_key.end(), ':', '\n');
        context.setMypubKey(my_pub_key);
        try {
            if (context.getUid() == dest_uid) {
                throw Poco::InvalidAccessException("You cannot call yourself ");
            }
            auto receiver = LoggedUsersMap::getInstance().findUser(dest_uid); //throws out_of_range exception
            if (receiver != nullptr && receiver->getCurrentState()==&LoginState::getInstance()) { //this is not necessary. But checking it won't kill you
                shared_ptr <CallAggregator> session(new CallAggregator());
                context.setSession(session);
                receiver->setSession(context.Session()); // receiver will register itself as a observer on 'kcs' event

                int bytes = receiver->writeToClientBlocking(CERT_REQUEST, 5000);
                if (bytes < 0) {
                    throw IOException("write failed");
                }
                receiver->setCurrent_state(CallSetuptState::getInstance());

                context.Session()->registerAsCaller(context.shared_from_this());
                cout << "registered as a caller" << endl;
                std::thread async_thread(std::function<void()>([&context]() -> void {
                    //local variable should be copied
                    auto caller = context.shared_from_this();//we can use 'context' reference but need to keep User object until thread ends
                    string sessionKey = context.Session()->getSessionKey();

                    try {

                        cout << "waiting for receiver TID :" << std::this_thread::get_id() << endl;

                        bool timeoutReached = context.Session()->wait_for_receiver(10);//seconds
                        //encrpt and send skey
                        if (!timeoutReached &&
                            caller.use_count() > 1) { //if time out not reached and this is not the only reference
                            caller->_behaviours->getCallInitializerBehaviour().sendSessionKey(sessionKey, *caller,
                                                                                              false); //throws exceptions
                            caller->setCurrent_state(CallingState::getInstance());
                        } else {
                            throw Poco::NotFoundException("Receiver end failed");
                        }
                    } catch (const Poco::Exception &e) {
                        cerr << e.message() << endl;
                        caller->writeToClient(REMOTE_USER_NOT_AVAILABLE);
                        context.writeToClient(DISCONNECT);// DISCONNECT does not work

                        if (caller->Session().get()) {
                            caller->Session()->unregisterObserver(caller);
                            caller->Session() = nullptr;
                            cout << "session cleared" << endl;
                        }
                        caller->setCurrent_state(LoginState::getInstance());

                    } catch (exception &e) {
                        cerr << "In async thread " << e.what() << endl;
                    }
                }));
                /*std::this_thread::sleep_until(std::chrono::system_clock::now() +
                                              std::chrono::nanoseconds(1000));//wait till lambda func till copy args*/
                async_thread.detach(); // now thread object can be deleted without affecting the running thread


            } else{
                cout << "user " << dest_uid << " not available" << endl;
                //this_thread::__sleep_for(std::chrono::seconds(3),std::chrono::nanoseconds(0));
                context.writeToClient(REMOTE_USER_NOT_AVAILABLE);
                context.setCurrent_state(LoginState::getInstance());
            }
        } catch (const std::out_of_range &e) { // from find(uid)
            cout << "user " << dest_uid << " not available" << endl;
            //this_thread::__sleep_for(std::chrono::seconds(3),std::chrono::nanoseconds(0));
            context.writeToClient(REMOTE_USER_NOT_AVAILABLE);
            context.setCurrent_state(LoginState::getInstance());

        } catch (const Poco::InvalidAccessException &e) { //if caller==callie
            context.writeToClient(REMOTE_USER_NOT_AVAILABLE, 0);
            cerr << e.message() << endl;
            context.setCurrent_state(LoginState::getInstance());

        } catch (const IOException &e) { //when writing to a closed Socket
            context.writeToClient(REMOTE_USER_NOT_AVAILABLE, 0);
            cerr << e.message() << endl;
            context.setCurrent_state(LoginState::getInstance());

        } catch (const Poco::NullPointerException &e) { //when trying to write after SocketConnection is deleted;
            context.writeToClient(REMOTE_USER_NOT_AVAILABLE, 0);
            cerr << e.message() << endl;
            context.setCurrent_state(LoginState::getInstance());
        }
        // my_pub_key.replace(':','',);


    }//this part has to be extracted to a seperte state.
        // unless receiver can process call request prior receiving cert request
    else if (data.compare(0, 3, "kcs") == 0) { //certificate response to server's request
        string my_pub_key = data.substr(4); //take data part
        std::replace(my_pub_key.begin(), my_pub_key.end(), ':', '\n');
        context.setMypubKey(my_pub_key);

        if (context.Session().get()) {// session could have been ended by caller
            context.Session()->registerAsReceiver(context.shared_from_this());
            string sKey(context.Session()->getSessionKey());
            context.Session()->notify_caller(); //Notify waiting caller

            try {
                context._behaviours->getCallInitializerBehaviour().sendSessionKey(sKey, context, true);
                context.setCurrent_state(RingingState::getInstance());

            } catch (const Poco::Exception &e) {
                context.writeToClient(DISCONNECT);
                context.setCurrent_state(LoginState::getInstance());
            }

        } else {
            context.setCurrent_state(LoginState::getInstance());
        }
    } else if (data.compare(0, 3, "rej") == 0) {//while caller is waiting itself can cancel the call
        if (context.Session().get()) {
            context.Session()->interrupt_caller();

        }
    }
}
Esempio n. 2
0
void delete_sec(int n) {
  for (int i = n; i < session()->num_sec; i++) {
    gfilesec[i] = gfilesec[i + 1];
  }
  --session()->num_sec;
}
Esempio n. 3
0
PassRefPtrWillBeRawPtr<MediaKeySession> MediaKeySession::create(ExecutionContext* context, blink::WebContentDecryptionModule* cdm, WeakPtrWillBeRawPtr<MediaKeys> keys)
{
    RefPtrWillBeRawPtr<MediaKeySession> session(adoptRefWillBeRefCountedGarbageCollected(new MediaKeySession(context, cdm, keys)));
    session->suspendIfNeeded();
    return session.release();
}
Esempio n. 4
0
int
main (int argc,
      char **argv)
{
  pam_handle_t *pamh = NULL;
  const char *auth;
  char **env;
  int status;
  int flags;
  int res;
  int i;

  if (isatty (0))
    errx (2, "this command is not meant to be run from the console");

  if (argc != 3)
    errx (2, "invalid arguments to cockpit-session");

  save_environment ();

  /* When setuid root, make sure our group is also root */
  if (geteuid () == 0)
    {
      /* Never trust the environment when running setuid() */
      if (getuid() != 0)
        {
          if (clearenv () != 0)
            err (1, "couldn't clear environment");
        }

      /* set a minimal environment */
      setenv ("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);

      if (setgid (0) != 0 || setuid (0) != 0)
        err (1, "couldn't switch permissions correctly");
    }

  /* We should never leak our auth fd to other processes */
  flags = fcntl (AUTH_FD, F_GETFD);
  if (flags < 0 || fcntl (AUTH_FD, F_SETFD, flags | FD_CLOEXEC))
    err (1, "couldn't set auth fd flags");

  auth = argv[1];
  rhost = argv[2];

  signal (SIGALRM, SIG_DFL);
  signal (SIGQUIT, SIG_DFL);
  signal (SIGTSTP, SIG_IGN);
  signal (SIGHUP, SIG_IGN);
  signal (SIGPIPE, SIG_IGN);

  /* Switch namespaces if we've been requested to do so */
  maybe_nsenter ();

  if (strcmp (auth, "basic") == 0)
    pamh = perform_basic ();
  else if (strcmp (auth, "negotiate") == 0)
    pamh = perform_gssapi ();
  else
    errx (2, "unrecognized authentication method: %s", auth);

  for (i = 0; env_saved[i] != NULL; i++)
    pam_putenv (pamh, env_saved[i]);

  env = pam_getenvlist (pamh);
  if (env == NULL)
    errx (EX, "get pam environment failed");

  if (want_session)
    {
      assert (pwd != NULL);

      if (initgroups (pwd->pw_name, pwd->pw_gid) < 0)
        err (EX, "%s: can't init groups", pwd->pw_name);

      signal (SIGTERM, pass_to_child);
      signal (SIGINT, pass_to_child);
      signal (SIGQUIT, pass_to_child);

      utmp_log (1);

      status = fork_session (env);

      utmp_log (0);

      signal (SIGTERM, SIG_DFL);
      signal (SIGINT, SIG_DFL);
      signal (SIGQUIT, SIG_DFL);

      res = pam_setcred (pamh, PAM_DELETE_CRED);
      if (res != PAM_SUCCESS)
        err (EX, "%s: couldn't delete creds: %s", pwd->pw_name, pam_strerror (pamh, res));
      res = pam_close_session (pamh, 0);
      if (res != PAM_SUCCESS)
        err (EX, "%s: couldn't close session: %s", pwd->pw_name, pam_strerror (pamh, res));
    }
  else
    {
      status = session (env);
    }

  pam_end (pamh, PAM_SUCCESS);


  if (WIFEXITED(status))
    exit (WEXITSTATUS(status));
  else if (WIFSIGNALED(status))
    raise (WTERMSIG(status));
  else
    exit (127);
}
Esempio n. 5
0
bool HttpServlet::doRun(const char* memcached_addr, socket_stream* stream)
{
	memcache_session session(memcached_addr);
	return doRun(session, stream);
}
Esempio n. 6
0
static Iface_DEFUN incomingMsg(struct Message* msg, struct Pathfinder_pvt* pf)
{
    struct Address addr;
    struct RouteHeader* hdr = (struct RouteHeader*) msg->bytes;
    Message_shift(msg, -(RouteHeader_SIZE + DataHeader_SIZE), NULL);
    Bits_memcpyConst(addr.ip6.bytes, hdr->ip6, 16);
    Bits_memcpyConst(addr.key, hdr->publicKey, 32);
    addr.protocolVersion = Endian_bigEndianToHost32(hdr->version_be);
    addr.padding = 0;
    addr.path = Endian_bigEndianToHost64(hdr->sh.label_be);

    //Log_debug(pf->log, "Incoming DHT");

    struct DHTMessage dht = {
        .address = &addr,
        .binMessage = msg,
        .allocator = msg->alloc
    };

    DHTModuleRegistry_handleIncoming(&dht, pf->registry);

    struct Message* nodeMsg = Message_new(0, 256, msg->alloc);
    Iface_CALL(sendNode, nodeMsg, &addr, 0xfffffff0u, pf);

    if (dht.pleaseRespond) {
        // what a beautiful hack, see incomingFromDHT
        return Iface_next(&pf->pub.eventIf, msg);
    }

    return NULL;
}

static Iface_DEFUN incomingFromEventIf(struct Message* msg, struct Iface* eventIf)
{
    struct Pathfinder_pvt* pf = Identity_containerOf(eventIf, struct Pathfinder_pvt, pub.eventIf);
    enum PFChan_Core ev = Message_pop32(msg, NULL);
    if (Pathfinder_pvt_state_INITIALIZING == pf->state) {
        Assert_true(ev == PFChan_Core_CONNECT);
        return connected(pf, msg);
    }
    switch (ev) {
        case PFChan_Core_SWITCH_ERR: return switchErr(msg, pf);
        case PFChan_Core_SEARCH_REQ: return searchReq(msg, pf);
        case PFChan_Core_PEER: return peer(msg, pf);
        case PFChan_Core_PEER_GONE: return peerGone(msg, pf);
        case PFChan_Core_SESSION: return session(msg, pf);
        case PFChan_Core_SESSION_ENDED: return sessionEnded(msg, pf);
        case PFChan_Core_DISCOVERED_PATH: return discoveredPath(msg, pf);
        case PFChan_Core_MSG: return incomingMsg(msg, pf);
        case PFChan_Core_PING: return handlePing(msg, pf);
        case PFChan_Core_PONG: return handlePong(msg, pf);
        default:;
    }
    Assert_failure("unexpected event [%d]", ev);
}

static void sendEvent(struct Pathfinder_pvt* pf, enum PFChan_Pathfinder ev, void* data, int size)
{
    struct Allocator* alloc = Allocator_child(pf->alloc);
    struct Message* msg = Message_new(0, 512+size, alloc);
    Message_push(msg, data, size, NULL);
    Message_push32(msg, ev, NULL);
    Iface_send(&pf->pub.eventIf, msg);
    Allocator_free(alloc);
}

static void init(void* vpf)
{
    struct Pathfinder_pvt* pf = Identity_check((struct Pathfinder_pvt*) vpf);
    struct PFChan_Pathfinder_Connect conn = {
        .superiority_be = Endian_hostToBigEndian32(1),
        .version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL)
    };
    CString_strncpy(conn.userAgent, "Cjdns internal pathfinder", 64);
    sendEvent(pf, PFChan_Pathfinder_CONNECT, &conn, PFChan_Pathfinder_Connect_SIZE);
}

struct Pathfinder* Pathfinder_register(struct Allocator* allocator,
                                       struct Log* log,
                                       struct EventBase* base,
                                       struct Random* rand,
                                       struct Admin* admin)
{
    struct Allocator* alloc = Allocator_child(allocator);
    struct Pathfinder_pvt* pf = Allocator_calloc(alloc, sizeof(struct Pathfinder_pvt), 1);
    Identity_set(pf);
    pf->alloc = alloc;
    pf->log = log;
    pf->base = base;
    pf->rand = rand;
    pf->admin = admin;

    pf->pub.eventIf.send = incomingFromEventIf;

    pf->dhtModule.context = pf;
    pf->dhtModule.handleOutgoing = incomingFromDHT;

    // This needs to be done asynchronously so the pf can be plumbed to the core
    Timeout_setTimeout(init, pf, 0, base, alloc);

    return &pf->pub;
}
/**
 * @SYMTestCaseID BA-CTSY-INT-MB-0036
 * @SYMFssID BA/CTSY/MB-0036
 * @SYMTestCaseDesc MBMS is currently used
 * @SYMTestPriority High
 * @SYMTestActions RPacketContext::InitialiseContext, RPacketContext::SetConfig, RPacketService::NotifyDynamicCapsChange, RPacketService::GetDynamicCaps, RPacketContext::Activate, RPacketService::NotifyStatusChange, RPacketService::GetStatus, RPacketContext::NotifyStatusChange, RPacketContext::GetStatus, RPacketContext::Deactivate
 * @SYMTestExpectedResults Pass - Client gets correct capability  
 * @SYMTestType CIT
 * @SYMTestCaseDependencies live/manual
 *
 * Reason for test: Verify that client get correct capability.
 *
 * @return - none
 */
void CCTsyUCaseMbms020::CCtsyIntegrationTestMbms0001L()
    {

        
	//
	// SET UP
	//
	        
    OpenEtelServerL( EUseExtendedError );
	CleanupStack::PushL( TCleanupItem( Cleanup, this ) );
	OpenPhoneL();	
	
	RPacketService packetService;
    OpenPacketServiceL( packetService );
    CleanupClosePushL( packetService );
              
	TInfoName contextId;
    RPacketMbmsContext mbmsContext;
    mbmsContext.OpenNewContext( packetService, contextId );
    CleanupClosePushL( mbmsContext );
    
    RBuf8 data;
    CleanupClosePushL(data);
    
    RBuf8 expectData;
    CleanupClosePushL(expectData);	        
	
	// initialisation of the context 
	TInt status = InitMbmsContextL(mbmsContext, contextId); 
    ASSERT_EQUALS(KErrNone, status);	
    
    // data for SetConfig
    TRequestStatus requestStatus;
    RPacketMbmsContext::TContextConfigMbmsV1 setConfig;
    setConfig.iTmgi.SetServiceId(1); 
    setConfig.iTmgi.SetMCC(111);
    setConfig.iTmgi.SetMNC(111);
    setConfig.iMbmsAccessBearer = E3GBearer;
    setConfig.iMbmsServicePriority = EMbmsHighServicePriority;
    setConfig.iMbmsServiceMode = KBroadcast;
    setConfig.iMbmsSessionFlag = ETrue;
	
	// configure context
    status = SetMbmsConfigL(mbmsContext, contextId, setConfig);
	ASSERT_EQUALS(KErrNone, status);	

	
	// add sessions
	TInt maxSessions( 1 );	
	
	TMockLtsyData1 <TInfoName > expData( contextId );
	expData.SerialiseL( expectData );
	
 	TMockLtsyData1 <TInfoName> outData( contextId );
	outData.SerialiseL( data );	
    
    for( TInt i = 0; i < maxSessions; i++ )
	    {
	    TMbmsSessionId session(i);  
	    
	    iMockLTSY.ExpectL(EPacketContextUpdateMbmsSessionList, expectData);
	    iMockLTSY.CompleteL(EPacketContextUpdateMbmsSessionList, KErrNone, data);            
	    mbmsContext.UpdateMbmsSessionList(requestStatus, EAddEntries, session);    
	    
	    User::WaitForRequest( requestStatus );
	    ASSERT_EQUALS( KErrNone, requestStatus.Int() ) ;	
	    }
    
	// Activate MBMS context
	status = SetMbmsActiveL(mbmsContext, setConfig, contextId);
	ASSERT_EQUALS(KErrNone, status);
	
	RPacketService::TStatus sendStatus = RPacketService::EStatusActive;
	TBool isResumed = EFalse;	
	TInt err = SetPacketServiceStatusL(sendStatus, isResumed);	
	ASSERT_EQUALS(KErrNone, err);
	
	
	RPacketService::TStatus attachStatus;
    TInt ret = packetService.GetStatus(attachStatus);
    ASSERT_EQUALS(KErrNone, ret);
    ASSERT_EQUALS(RPacketService::EStatusActive, attachStatus);
	
	// Ensure MBMS Context status is Active
	RPacketContext::TContextStatus expectedStatus = RPacketContext::EStatusActive;
	RPacketContext::TContextStatus contextStatus;
	ret = mbmsContext.GetStatus(contextStatus);
	ASSERT_EQUALS(KErrNone, ret);
    ASSERT_EQUALS((TInt)expectedStatus, (TInt)contextStatus);
	
	// Add a session
	CFilteringActiveScheduler scheduler;
	CActiveScheduler::Install(&scheduler);    
	
    RPacketMbmsContext::CMbmsSession* session = RPacketMbmsContext::CMbmsSession::NewL();  
    CleanupStack::PushL(session);	
    	
	CRetrievePcktMbmsSessionList* sessionList = CRetrievePcktMbmsSessionList::NewL(mbmsContext, *session);        
    CleanupStack::PushL(sessionList);

    CActiveRetriever::ResetRequestsNumber();
    CActiveRetriever retriever(*sessionList);
    
    scheduler.AddRetrieverL(retriever);
        
    sessionList->Start( retriever.Status() );	 	
	retriever.Activate();
	scheduler.StartScheduler();
	ASSERT_EQUALS(KErrNone, retriever.iStatus.Int());
    
    // ensure there is session added to a MBMS context 
	for( TUint i = 0; i < session->iSessionIdList.Count(); i++)
	    {
	    TMbmsSessionId sessionId = session->iSessionIdList[i];
	    ASSERT_EQUALS( sessionId, i);	    
	    }
	
	ASSERT_EQUALS(0, CActiveRetriever::ResetRequestsNumber());	 	
 	AssertMockLtsyStatusL();
    
    
    
	//
	// SET UP END
	//    
            
	//
	// TEST START
	//

	// Network sends MBMS Notification to handset indicating MBMS service delivery about to start.
	// post notify RPacketContext::NotifyStatusChange
 	mbmsContext.NotifyStatusChange(requestStatus, contextStatus);	

    // post RPacketService::NotifyDynamicCapsChange
    RPacketService::TDynamicCapsFlags caps;
	TRequestStatus dynamicCapsStatus;
	packetService.NotifyDynamicCapsChange(dynamicCapsStatus, caps);

    TContextMisc  completeMisc;
    completeMisc.iStatus = RPacketContext::EStatusReceiving;
 	TMockLtsyData2 <TInfoName, TContextMisc>ltsyData1(contextId, completeMisc);
	ltsyData1.SerialiseL(data);
    TRequestStatus mockLtsyStatus;
	iMockLTSY.NotifyTerminated(mockLtsyStatus);	
		
	iMockLTSY.CompleteL(EPacketContextNotifyStatusChange , KErrNone, data);
	User::WaitForRequest(mockLtsyStatus);
    User::WaitForRequest(requestStatus);
	
	// Ensure RPacketContext::NotifyStatusChange completes MBMS context status RPacketContext::EStatusReceiving	
	ASSERT_EQUALS(KErrNone, requestStatus.Int());
	ASSERT_EQUALS(completeMisc.iStatus, contextStatus);	
	AssertMockLtsyStatusL();
    
    // Check RPacketContext::GetStatus returns RPacketContext::EStatusReceiving
	expectedStatus = RPacketContext::EStatusReceiving;
	ret = mbmsContext.GetStatus(contextStatus);
	ASSERT_EQUALS(KErrNone, ret);
    ASSERT_EQUALS((TInt)expectedStatus, (TInt)contextStatus);

	// Ensure RPacketService::NotifyDynamicCapsChange doens't return RPacketService::KCapsMBMS
   	User::WaitForRequest(dynamicCapsStatus);
   	ASSERT_EQUALS(KErrNone, dynamicCapsStatus.Int());
   	ASSERT_TRUE(RPacketService::KCapsMBMS & caps);
   	
   	// Ensure GetDynamicCaps capabilities return RPacketService::KCapsMBMS caps
	packetService.GetDynamicCaps(caps);
	ASSERT_TRUE(RPacketService::KCapsMBMS & caps);	

    AssertMockLtsyStatusL();

	// deactivate context 
	status = SetMbmsDeactiveL(mbmsContext, contextId);
	ASSERT_EQUALS(KErrNone, status);
	
	// delete context
	status = SetMbmsDeleteL(mbmsContext, contextId);
	ASSERT_EQUALS(KErrNone, status);
	
	// close context
	mbmsContext.Close( );     
	        
    	
	//
	// TEST END
	//	
	
	AssertMockLtsyStatusL();
	CActiveScheduler::Install(NULL);    
	CleanupStack::PopAndDestroy( 7, this ); // sessionList, session, expectData, data, mbmsContext, packetService, this
      }
Esempio n. 8
0
// [P]
void X86ValuesTask::ProcessFunction(Function& fn) {
  ValuesTasklet tasklet(session(), fn.module());
  tasklet.Run(fn);
} // ProcessFunction
Esempio n. 9
0
void Client::threadedFunction()
{
    while (isThreadRunning())
    {
        Poco::Net::SocketAddress socketAddress(_settings.getHost(),
                                               _settings.getPort());
        SharedSocket pSocket;

        try
        {
            if (Settings::SSLTLS == _settings.getEncryptionType())
            {
                // Create a Poco::Net::SecureStreamSocket pointer.
                Poco::Net::SecureStreamSocket* _socket = 0;

                // We get a default context from ofSSLManager to make sure
                // that Poco::Net::SecureStreamSocket doesn't attempt to create
                // a default context using Poco::Net::SSLManager.
                Poco::Net::Context::Ptr _clientContext = ofSSLManager::getDefaultClientContext();

                // Create a Poco::Net::SecureStreamSocket and connect to it.
                // Use the Default Client context from ofSSLManager and
                // attempt to use saved Poco::Nett::Session on subsequent
                // attempts the Client SSL Context and server allow it,
                // and one was saved during a previous connection.
                _socket = new Poco::Net::SecureStreamSocket(socketAddress,
                                                            _clientContext,
                                                            _pSession);

                // Attempt to save an SSL Client session.
                _pSession = _socket->currentSession();

                // Let the shared pointer take ownership of the raw pointer.
                pSocket = SharedSocket(_socket);
            }
            else
            {
                pSocket = SharedSocket(new Poco::Net::StreamSocket(socketAddress));
            }

            #if defined(TARGET_OSX)
            // essential on early versions of Poco!  fixed in 1.4.6p2+ / 1.5.2+
            // https://github.com/pocoproject/poco/issues/235
            pSocket->setOption(SOL_SOCKET, SO_NOSIGPIPE, 1); // ignore SIGPIPE
            #endif

            Poco::Net::SecureSMTPClientSession session(*pSocket);
            
            session.setTimeout(_settings.getTimeout());
            
            if (Settings::STARTTLS == _settings.getEncryptionType())
            {
                // Make the initial connection.
                session.login();
                // TODO:
                // This is supposed to return true on succes, but it doesn't.
                session.startTLS(ofSSLManager::getDefaultClientContext());
            }

            if (_settings.getCredentials().getLoginMethod() !=
                Poco::Net::SMTPClientSession::AUTH_NONE)
            {
                session.login(_settings.getCredentials().getLoginMethod(),
                              _settings.getCredentials().getUsername(),
                              _settings.getCredentials().getPassword());
            }

            while (getOutboxSize() > 0 && isThreadRunning())
            {
                mutex.lock();
                _currentMessage = _outbox.front();
                _outbox.pop_front();
                mutex.unlock();

                session.sendMessage(*_currentMessage);

                ofNotifyEvent(events.onSMTPDelivery,
                              _currentMessage,
                              this);

                _currentMessage.reset();

                sleep(_settings.getMessageSendDelay().milliseconds());
            }

            ofLogVerbose("Client::threadedFunction") << "Closing session.";
            
            session.close();
            pSocket->close();

        }
        catch (Poco::Net::SMTPException& exc)
        {
            if (_currentMessage)
            {
                // 500 codes are permanent negative errors.
                if (5 != (exc.code() / 100))
                {
                    mutex.lock();
                    _outbox.push_front(_currentMessage);
                    mutex.unlock();
                }
            }

            pSocket->close();

            ErrorArgs args(exc, _currentMessage);
            ofNotifyEvent(events.onSMTPException,
                          args,
                          this);

            _currentMessage.reset();

        }
        catch (Poco::Net::SSLException& exc)
        {
            if (_currentMessage)
            {
                mutex.lock();
                _outbox.push_front(_currentMessage);
                mutex.unlock();
            }

            ofLogError("Client::threadedFunction") << exc.name() << " : " << exc.displayText();

            if (exc.displayText().find("SSL3_GET_SERVER_CERTIFICATE") != string::npos)
            {
                ofLogError("Client::threadedFunction") << "\t\t" << "This may be because you asked your SSL context to verify the server's certificate, but your certificate authority (ca) file is missing.";
            }

            ErrorArgs args(exc, _currentMessage);
            ofNotifyEvent(events.onSMTPException,
                          args,
                          this);

            _currentMessage.reset();
            
        }
        catch (Poco::Net::NetException& exc)
        {
            if (_currentMessage)
            {
                mutex.lock();
                _outbox.push_front(_currentMessage);
                mutex.unlock();
            }

            ofLogError("Client::threadedFunction") << exc.name() << " : " << exc.displayText();

                       ErrorArgs args(exc, _currentMessage);
            ofNotifyEvent(events.onSMTPException,
                          args,
                          this);

            _currentMessage.reset();
            
        }
        catch (Poco::Exception &exc)
        {
            if (_currentMessage)
            {
                mutex.lock();
                _outbox.push_front(_currentMessage);
                mutex.unlock();
            }

            ofLogError("Client::threadedFunction") << exc.name() << " : " << exc.displayText();

            ErrorArgs args(exc, _currentMessage);
            ofNotifyEvent(events.onSMTPException,
                          args,
                          this);

            _currentMessage.reset();
            
        }
        catch (std::exception& exc)
        {
            if (_currentMessage)
            {
                mutex.lock();
                _outbox.push_front(_currentMessage);
                mutex.unlock();
            }

            ofLogError("Client::threadedFunction") << exc.what();

            ErrorArgs args(Poco::Exception(exc.what()), _currentMessage);

            ofNotifyEvent(events.onSMTPException,
                          args,
                          this);

            _currentMessage.reset();
            
        }
        
        ofLogVerbose("Client::threadedFunction") << "Waiting for more messages.";

        _messageReady.wait();
        _messageReady.reset();
    }
}
Esempio n. 10
0
    virtual Server_status start(int incoming_sck)
    {
        union
        {
            struct sockaddr s;
            struct sockaddr_storage ss;
            struct sockaddr_in s4;
            struct sockaddr_in6 s6;
        } u;
        unsigned int sin_size = sizeof(u);
        memset(&u, 0, sin_size);

        int sck = accept(incoming_sck, &u.s, &sin_size);
        if (-1 == sck) {
            LOG(LOG_INFO, "Accept failed on socket %u (%s)", incoming_sck, strerror(errno));
            _exit(1);
        }

        char source_ip[256];
        strcpy(source_ip, inet_ntoa(u.s4.sin_addr));
        const int source_port = ntohs(u.s4.sin_port);
        /* start new process */
        const pid_t pid = fork();
        switch (pid) {
        case 0: /* child */
            {
                close(incoming_sck);

                Inifile ini;
                ini.set<cfg::debug::config>(this->debug_config);
                { ConfigurationLoader cfg_loader(ini, this->config_filename.c_str()); }

                if (ini.get<cfg::globals::wab_agent_alternate_shell>().empty()) {
                    ini.set<cfg::globals::wab_agent_alternate_shell>(
                        this->parametersHldr.get_agent_alternate_shell()
                    );
                }

                ini.get_ref<cfg::crypto::key0>().setmem(this->parametersHldr.get_crypto_key_0());
                ini.get_ref<cfg::crypto::key1>().setmem(this->parametersHldr.get_crypto_key_1());

                if (ini.get<cfg::debug::session>()){
                    LOG(LOG_INFO, "Setting new session socket to %d\n", sck);
                }

                union
                {
                    struct sockaddr s;
                    struct sockaddr_storage ss;
                    struct sockaddr_in s4;
                    struct sockaddr_in6 s6;
                } localAddress;
                socklen_t addressLength = sizeof(localAddress);


                if (-1 == getsockname(sck, &localAddress.s, &addressLength)){
                    LOG(LOG_INFO, "getsockname failed error=%s", strerror(errno));
                    _exit(1);
                }

                char target_ip[256];
                const int target_port = ntohs(localAddress.s4.sin_port);
//                strcpy(real_target_ip, inet_ntoa(localAddress.s4.sin_addr));
                strcpy(target_ip, inet_ntoa(localAddress.s4.sin_addr));

                if (0 != strcmp(source_ip, "127.0.0.1")){
                    // do not log early messages for localhost (to avoid tracing in watchdog)
                    LOG(LOG_INFO, "src=%s sport=%d dst=%s dport=%d", source_ip, source_port, target_ip, target_port);
                }

                char real_target_ip[256];
                if (ini.get<cfg::globals::enable_ip_transparent>() &&
                    (0 != strcmp(source_ip, "127.0.0.1"))) {
                    int fd = open("/proc/net/ip_conntrack", O_RDONLY);
                    // source and dest are inverted because we get the information we want from reply path rule
                    int res = parse_ip_conntrack(fd, target_ip, source_ip, target_port, source_port, real_target_ip, sizeof(real_target_ip), 1);
                    if (res){
                        LOG(LOG_WARNING, "Failed to get transparent proxy target from ip_conntrack: %d", fd);
                    }
                    close(fd);

                    if (setgid(this->gid) != 0){
                        LOG(LOG_WARNING, "Changing process group to %u failed with error: %s\n", this->gid, strerror(errno));
                        _exit(1);
                    }
                    if (setuid(this->uid) != 0){
                        LOG(LOG_WARNING, "Changing process group to %u failed with error: %s\n", this->gid, strerror(errno));
                        _exit(1);
                    }

                    LOG(LOG_INFO, "src=%s sport=%d dst=%s dport=%d", source_ip, source_port, real_target_ip, target_port);
                }
                else {
                    ::memset(real_target_ip, 0, sizeof(real_target_ip));
                }

                int nodelay = 1;
                if (0 == setsockopt(sck, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay))){
                    // Create session file
                    int child_pid = getpid();
                    char session_file[256];
                    sprintf(session_file, "%s/redemption/session_%d.pid", PID_PATH, child_pid);
                    int fd = open(session_file, O_WRONLY | O_CREAT, S_IRWXU);
                    if (fd == -1) {
                        LOG(LOG_ERR, "Writing process id to SESSION ID FILE failed. Maybe no rights ?:%d:%d\n", errno, strerror(errno));
                        _exit(1);
                    }
                    char text[256];
                    const size_t lg = snprintf(text, 255, "%d", child_pid);
                    if (write(fd, text, lg) == -1) {
                        LOG(LOG_ERR, "Couldn't write pid to %s: %s", PID_PATH "/redemption/session_<pid>.pid", strerror(errno));
                        _exit(1);
                    }
                    close(fd);

                    // Launch session
                    if (0 != strcmp(source_ip, "127.0.0.1")){
                        // do not log early messages for localhost (to avoid tracing in watchdog)
                        LOG(LOG_INFO,
                            "New session on %u (pid=%u) from %s to %s",
                            (unsigned)sck, (unsigned)child_pid, source_ip, (real_target_ip[0] ? real_target_ip : target_ip));
                    }
                    ini.set_acl<cfg::globals::host>(source_ip);
//                    ini.context_set_value(AUTHID_TARGET, real_target_ip);
                    ini.set_acl<cfg::globals::target>(target_ip);
                    if (ini.get<cfg::globals::enable_ip_transparent>()
                        &&  strncmp(target_ip, real_target_ip, strlen(real_target_ip))) {
                        ini.set_acl<cfg::context::real_target_device>(real_target_ip);
                    }
                    Session session(sck, ini);

                    // Suppress session file
                    unlink(session_file);

                    if (ini.get<cfg::debug::session>()){
                        LOG(LOG_INFO, "Session::end of Session(%u)", sck);
                    }

                    shutdown(sck, 2);
                    close(sck);
                }
                else {
                    LOG(LOG_ERR, "Failed to set socket TCP_NODELAY option on client socket");
                }
                return START_WANT_STOP;
            }
            break;
        default: /* father */
            {
                close(sck);
            }
            break;
        case -1:
            // error forking
            LOG(LOG_ERR, "Error creating process for new session : %s\n", strerror(errno));
            break;
        }
        return START_FAILED;
    }
Esempio n. 11
0
void
Main::launch_game()
{
  SDLSubsystem sdl_subsystem;
  ConsoleBuffer console_buffer;

  timelog("controller");
  InputManager input_manager(g_config->keyboard_config, g_config->joystick_config);

  timelog("commandline");

  timelog("video");
  std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
  DrawingContext context(*video_system);
  init_video();

  timelog("audio");
  SoundManager sound_manager;
  sound_manager.enable_sound(g_config->sound_enabled);
  sound_manager.enable_music(g_config->music_enabled);

  Console console(console_buffer);

  timelog("scripting");
  scripting::Scripting scripting(g_config->enable_script_debugger);

  timelog("resources");
  TileManager tile_manager;
  SpriteManager sprite_manager;
  Resources resources;

  timelog("addons");
  AddonManager addon_manager("addons", g_config->addons);

  timelog(0);

  const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));

  GameManager game_manager;
  ScreenManager screen_manager;

  if(g_config->start_level != "") {
    // we have a normal path specified at commandline, not a physfs path.
    // So we simply mount that path here...
    std::string dir = FileSystem::dirname(g_config->start_level);
    std::string fileProtocol = "file://";
    std::string::size_type position = dir.find(fileProtocol);
    if(position != std::string::npos) {
      dir = dir.replace(position, fileProtocol.length(), "");
    }
    log_debug << "Adding dir: " << dir << std::endl;
    PHYSFS_addToSearchPath(dir.c_str(), true);

    if(g_config->start_level.size() > 4 &&
       g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0)
    {
      screen_manager.push_screen(std::unique_ptr<Screen>(
                                              new worldmap::WorldMap(
                                                FileSystem::basename(g_config->start_level), *default_savegame)));
    } else {
      std::unique_ptr<GameSession> session (
        new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));

      g_config->random_seed = session->get_demo_random_seed(g_config->start_demo);
      g_config->random_seed = gameRandom.srand(g_config->random_seed);
      graphicsRandom.srand(0);

      if(g_config->start_demo != "")
        session->play_demo(g_config->start_demo);

      if(g_config->record_demo != "")
        session->record_demo(g_config->record_demo);
      screen_manager.push_screen(std::move(session));
    }
  } else {
    screen_manager.push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
  }

  screen_manager.run(context);
}
Esempio n. 12
0
    _search->setEnabled(FullUsernameExp.exactMatch(_username->text()));
    _apply->setVisible(false);
    _ok->setVisible(false);
    _delete->setVisible(false);

    pack();
    center();

    _username->requestFocus();
}

void EditUserDialog::search ()
{
    // send the request off to the database
    QMetaObject::invokeMethod(
        session()->app()->databaseThread()->userRepository(), "loadUser",
        Q_ARG(const QString&, _username->text()),
        Q_ARG(const Callback&, Callback(_this, "userMaybeLoaded(UserRecord)")));
}

void EditUserDialog::updateApply ()
{
    QString password = _password->text();
    QString email = _email->text();
    bool enable = FullUsernameExp.exactMatch(_newUsername->text()) &&
        password == _confirmPassword->text() &&
            (password.isEmpty() || FullPasswordExp.exactMatch(password)) &&
        QDate::fromString(_dob->text(), "MM-dd-yyyy").isValid() &&
        (email.isEmpty() || FullEmailExp.exactMatch(email));
    _apply->setEnabled(enable);
    _ok->setEnabled(enable);
Esempio n. 13
0
int
do_lq_request(struct lq_info *info, const char *vm_name,
	      const char *action)
{
	std::string vm_state;
	const char *property = "name";
	if (is_uuid(vm_name) == 1) {
		property = "uuid";
	}
	
	qmf::ConsoleSession session(lq_open_session(info));
	if (!session.isValid()) {
		std::cout << "Invalid session." << std::endl;
		return 1;
	}

	qmf::Agent agent;
	qmf::Data domain;
	int result;

	unsigned tries = 0;
	bool found = false;
	while (++tries < 10 && !found) {
		sleep(1);

		uint32_t numAgents = session.getAgentCount();
		for (unsigned a = 0; !found && a < numAgents; a++) {
			agent = session.getAgent(a);

			qmf::ConsoleEvent event(queryDomain(agent));
			uint32_t numDomains = event.getDataCount();
			for (unsigned d = 0; !found && d < numDomains; d++) {
				domain = event.getData(d);
				qpid::types::Variant prop;
				try {
					prop = domain.getProperty(property);
				} catch (qmf::KeyNotFound e) {
					std::cout << e.what() << " - skipping" << std::endl;
					continue;
				}

				if (prop.asString() != vm_name) {
					continue;
				}

				found = true;
			}
		}
	}

	if (!found) {
		result = 1;
		goto out;
	}

	vm_state = domain.getProperty("state").asString();

	std::cout << vm_name << " " << vm_state << std::endl;

	int r;
	if (vm_state == "running" ||
	    vm_state == "idle" ||
	    vm_state == "paused" ||
	    vm_state == "no state") {
		r = RESP_OFF;
	} else {
		r = 0;
	}

	if (strcasecmp(action, "state") == 0) {
		result = r;
		goto out;
	}

	result = 1;
	if (!r && strcasecmp(action, "destroy") == 0) {
		std::cout << "Domain is inactive; nothing to do" << std::endl;
		result = 0;
		goto out;
	}
	if (r && strcasecmp(action, "create") == 0) {
		std::cout << "Domain is active; nothing to do" << std::endl;
		result = 0;
		goto out;
	}

	{
		qmf::ConsoleEvent response;
		response = agent.callMethod(action,
				qpid::types::Variant::Map(),
				domain.getAddr());

		if (response.getType() == qmf::CONSOLE_EXCEPTION) {
			std::string errorText;
			if (response.getDataCount()) {
				qmf::Data responseData(response.getData(0));

				qpid::types::Variant code(responseData.getProperty("error_code"));
				if (code.getType() == qpid::types::VAR_INT32) {
					result = responseData.getProperty("error_code").asInt32();
				} else {
					result = 7; // Exception
				}
				qpid::types::Variant text(responseData.getProperty("error_text"));
				if (text.getType() != qpid::types::VAR_VOID) {
					errorText = text.asString();
				}
			} else {
				result = 7; // Exception
			}

			std::cout << "Response: " << result;
			if (errorText.length()) {
				std::cout << " (" << errorText << ")";
			}
			std::cout << std::endl;
		} else { // Success
			result = 0;
		}
	}

out:
	session.close();

	return result;
}
Esempio n. 14
0
File: main.c Progetto: sisoftrg/qico
static void answer_mode(int type)
{
	int rc, spd;char *cs;
	struct sockaddr_in sa;
	socklen_t ss=sizeof(sa);
	sts_t sts;
	if(cfgs(CFG_ROOTDIR)&&ccs[0])chdir(ccs);
	rnode=xcalloc(1,sizeof(ninfo_t));
	is_ip=!isatty(0);
	xstrcpy(ip_id,"ipline",10);
	rnode->tty=xstrdup(is_ip?(bink?"binkp":"tcpip"):basename(ttyname(0)));
	rnode->options|=O_INB;
	if(!log_init(cfgs(CFG_LOG),rnode->tty)) {
		printf("can't open log %s!\n",ccs);
		exit(S_FAILURE);
	}
	signal(SIGINT,SIG_IGN);
	signal(SIGTERM,sigerr);
	signal(SIGSEGV,sigerr);
	signal(SIGFPE,sigerr);
	signal(SIGPIPE,SIG_IGN);
	IFPerl(perl_init(cfgs(CFG_PERLFILE),0));
	log_callback=NULL;xsend_cb=NULL;
	ssock=cls_conn(CLS_LINE,cfgs(CFG_SERVER),NULL);
	if(ssock<0)write_log("can't connect to server: %s",strerror(errno));
	    else log_callback=vlogs;

	rc=aso_init(cfgs(CFG_ASOOUTBOUND),cfgs(CFG_BSOOUTBOUND),cfgs(CFG_QSTOUTBOUND),cfgal(CFG_ADDRESS)->addr.z);
	if(!rc) {
		write_log("No outbound defined");
		stopit(S_FAILURE);
	}

	write_log("answering incoming call");vidle();
	if(is_ip&&!getpeername(0,(struct sockaddr*)&sa,&ss)) {
		write_log("remote is %s",inet_ntoa(sa.sin_addr));
		spd=TCP_SPEED;
	} else {
		cs=getenv("CONNECT");spd=cs?atoi(cs):0;
		xfree(connstr);connstr=xstrdup(cs);
		if(cs&&spd)write_log("*** CONNECT %s",cs);
		    else {
			write_log("*** CONNECT Unknown");
			spd=DEFAULT_SPEED;
		}
	}
	if((cs=getenv("CALLER_ID"))&&strcasecmp(cs,"none")&&strlen(cs)>3)write_log("caller-id: %s",cs);
	tty_setattr(0);
	tty_local(0);
	rc=session(0,type,NULL,spd);
	tty_local(1);
	if(!is_ip) {
		hangup();
		stat_collect();
	}
	tty_cooked();
	if((S_OK==(rc&S_MASK))&&cfgi(CFG_HOLDONSUCCESS)) {
		log_done();
		log_init(cfgs(CFG_MASTERLOG),NULL);
		aso_getstatus(&rnode->addrs->addr, &sts);
		sts.flags|=(Q_WAITA|Q_WAITR|Q_WAITX);
		sts.htime=MAX(t_set(cci*60),sts.htime);
		write_log("calls to %s delayed for %d min after successful incoming session",
				ftnaddrtoa(&rnode->addrs->addr),cci);
		aso_setstatus(&rnode->addrs->addr,&sts);
		log_done();
		log_init(cfgs(CFG_LOG),rnode->tty);
	}
	title("Waiting...");
	vidle();sline("");
	aso_done();
	stopit(rc);
}
/*!
  \~english
  Returns the identity key of the user, i.e., TAbstractUser object,
  logged in.
  
  This is a virtual function.
  \~japanese
  ログインユーザのアイデンティティキーを返す
  \~
  \sa userLogin()
*/
QString TActionController::identityKeyOfLoginUser() const
{
    return session().value(LOGIN_USER_NAME_KEY).toString();
}
bool AuthHostInstance::inDarkWake()
{
	return session().server().inDarkWake();
}
/* called by CSPFullPluginSession */
void RSA_CryptContext::init(const Context &context, bool encoding /*= true*/)
{
	StLock<Mutex> _(gMutex());
	
	if(mInitFlag && !opStarted()) {
		/* reusing - e.g. query followed by encrypt */
		return;
	}

	/* optional mode to use alternate key class (e.g., decrypt with public key) */
	CSSM_KEYCLASS  keyClass;
    switch (context.getInt(CSSM_ATTRIBUTE_MODE)) {
        case CSSM_ALGMODE_PUBLIC_KEY:
			keyClass = CSSM_KEYCLASS_PUBLIC_KEY;
            break;
        case CSSM_ALGMODE_PRIVATE_KEY:
			keyClass = CSSM_KEYCLASS_PRIVATE_KEY;
            break;
        case CSSM_ALGMODE_NONE:	
			/* default, not present in context: infer from op type */
			keyClass = encoding ? CSSM_KEYCLASS_PUBLIC_KEY : CSSM_KEYCLASS_PRIVATE_KEY;
			break;
		default:
			CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_MODE);
	}
	
	/* fetch key from context */
	if(mRsaKey == NULL) {
		assert(!opStarted());
		CSSM_DATA label = {0, NULL};
		mRsaKey = contextToRsaKey(context,
			session(),
			keyClass,
			encoding ? CSSM_KEYUSE_ENCRYPT : CSSM_KEYUSE_DECRYPT,
			mAllocdRsaKey,
			label);
		if(label.Data) {
			mLabel.copy(label);
			mOaep = true;
			free(label.Data);
		}
	}
	else {
		assert(opStarted());	
	}

	unsigned cipherBlockSize = RSA_size(mRsaKey);
	unsigned plainBlockSize;

	/* padding - not present means value zero, CSSM_PADDING_NONE */
	uint32 padding = context.getInt(CSSM_ATTRIBUTE_PADDING);
	switch(padding) {
		case CSSM_PADDING_NONE:
			mPadding = RSA_NO_PADDING;
			plainBlockSize = cipherBlockSize;
			break;
		case CSSM_PADDING_PKCS1:
			mPadding = RSA_PKCS1_PADDING;
			plainBlockSize = cipherBlockSize - 11;
			break;
		case CSSM_PADDING_APPLE_SSLv2:
			rsaCryptDebug("RSA_CryptContext::init using CSSM_PADDING_APPLE_SSLv2");
			mPadding = RSA_SSLV23_PADDING;
			plainBlockSize = cipherBlockSize - 11;
			break;
		default:
			rsaCryptDebug("RSA_CryptContext::init bad padding (0x%x)",
				(unsigned)padding);
			CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_PADDING);
	}
	
	/* optional blinding attribute */
	uint32 blinding = context.getInt(CSSM_ATTRIBUTE_RSA_BLINDING);
	if(blinding) {
		if(RSA_blinding_on(mRsaKey, NULL) <= 0) {
			/* actually no legit failures */
			CssmError::throwMe(CSSMERR_CSP_INTERNAL_ERROR);
		}
	}
	else {
		RSA_blinding_off(mRsaKey);
	}

	/* finally, have BlockCryptor set up its stuff. */
	setup(encoding ? plainBlockSize  : cipherBlockSize, // blockSizeIn
		  encoding ? cipherBlockSize : plainBlockSize,	// blockSizeOut
		  false,										// pkcs5Pad
		  false,										// needsFinal
		  BCM_ECB,
		  NULL);											// IV
	mInitFlag = true;

}
Esempio n. 18
0
int EventStreamingServer::svc(void)
{
	ACE_Time_Value timeout;
	char buf[2048];
	CStdString logMsg;
	CStdString sessionId;
	int messagesSent = 0;

	ssize_t size = peer().recv(buf, 2040);

	if(size <= 5)
	{
		CStdString notFound("HTTP/1.0 404 not found\r\nContent-type: text/html\r\n\r\nNot found\r\n");
		peer().send(notFound, notFound.GetLength(), MSG_NOSIGNAL);
		return 0;
	}

	try
	{
		int startUrlOffset = 5;
		char* stopUrl = ACE_OS::strstr(buf+startUrlOffset, " HTTP");

		if(!stopUrl)
		{
			throw (CStdString("Malformed http request"));
		}

		CStdString header;
		struct tm date = {0};
		time_t now = time(NULL);
		CStdString rfc822Date;

		ACE_OS::gmtime_r(&now, &date);
		rfc822Date.Format("Tue, %.2d Nov %.4d %.2d:%.2d:%.2d GMT", date.tm_mday, (date.tm_year+1900), date.tm_hour, date.tm_min, date.tm_sec);
		header.Format("HTTP/1.1 200 OK\r\nLast-Modified:%s\r\nContent-Type:text/plain\r\n\r\n", rfc822Date);
		peer().send(header, header.GetLength(), MSG_NOSIGNAL);

		time_t startTime = time(NULL);

		sessionId = EventStreamingSingleton::instance()->GetNewSessionId() + " -";
		logMsg.Format("%s Event streaming start", sessionId);
		LOG4CXX_INFO(s_log, logMsg);

		EventStreamingSessionRef session(new EventStreamingSession());
		EventStreamingSingleton::instance()->AddSession(session);

		int sendRes = 0;
		while(sendRes >= 0)
		{
			session->WaitForMessages();

			while(session->GetNumMessages() && sendRes >= 0)
			{
				MessageRef message;

				session->GetTapeMessage(message);
				if(message.get())
				{
					CStdString msgAsSingleLineString;
					msgAsSingleLineString = message->SerializeUrl() + "\r\n";

					sendRes = peer().send(msgAsSingleLineString, msgAsSingleLineString.GetLength(), MSG_NOSIGNAL);
					if(sendRes >= 0)
					{
						messagesSent += 1;
					}
				}
			}
		}

		EventStreamingSingleton::instance()->RemoveSession(session);
		logMsg.Format("%s Stream client stop - sent %d messages in %d sec", sessionId, messagesSent, (time(NULL) - startTime));
		LOG4CXX_INFO(s_log, logMsg);
	}
	catch (CStdString& e)
	{
		CStdString error("HTTP/1.0 404 not found\r\nContent-type: text/html\r\n\r\nError\r\n");
		error = error + e + "\r\n";
		LOG4CXX_ERROR(s_log, e);
		peer().send(error, error.GetLength(), MSG_NOSIGNAL);
	}

	return 0;
}
Esempio n. 19
0
bool MatchMaker_ReceiveMessage( NetSocketListener *_listener, Directory *_message )
{
    AppAssert( _message );
    AppAssert( strcmp(_message->m_name, NET_MATCHMAKER_MESSAGE) == 0 );
    AppAssert( _message->HasData( NET_METASERVER_COMMAND, DIRECTORY_TYPE_STRING ) );

    char *cmd = _message->GetDataString( NET_METASERVER_COMMAND );

    if( strcmp( cmd, NET_MATCHMAKER_IDENTIFY ) == 0 )
    {
        //
        // This message contains the external IP and port of one of our connections

        if( !_message->HasData( NET_MATCHMAKER_UNIQUEID, DIRECTORY_TYPE_INT ) ||
            !_message->HasData( NET_MATCHMAKER_YOURIP, DIRECTORY_TYPE_STRING ) ||
            !_message->HasData( NET_MATCHMAKER_YOURPORT, DIRECTORY_TYPE_INT ) )
        {
            AppDebugOut( "MatchMaker : Received badly formed identity message, discarded\n" );
        }
        else
        {
            int uniqueId = _message->GetDataInt( NET_MATCHMAKER_UNIQUEID );
            
            s_listenersMutex.Lock();
            for( int i = 0; i < s_listeners.Size(); ++i )
            {
                if( s_listeners.ValidIndex(i) )
                {
                    MatchMakerListener *listener = s_listeners[i];
                    if( listener->m_uniqueId == uniqueId )
                    {
                        if( !listener->m_identified )
                        {                        
                            listener->m_ip = strdup( _message->GetDataString(NET_MATCHMAKER_YOURIP) );
                            listener->m_port = _message->GetDataInt(NET_MATCHMAKER_YOURPORT);
                            listener->m_identified = true;
                            AppDebugOut( "Socket %d identified as public IP %s:%d\n", 
                                            listener->m_listener->GetBoundSocketHandle(), listener->m_ip, listener->m_port );
                        }
                        break;
                    }
                }
            }
            s_listenersMutex.Unlock();
        }
    }
    else if( strcmp( cmd, NET_MATCHMAKER_REQUEST_CONNECT ) == 0 )
    {
        //
        // This is a request from a client for the server to set up a UDP hole punch
        
        if( !_message->HasData( NET_METASERVER_IP, DIRECTORY_TYPE_STRING ) ||
            !_message->HasData( NET_METASERVER_PORT, DIRECTORY_TYPE_INT ) )
        {
            AppDebugOut( "MatchMaker : Received badly formed connection request, discarded\n" );
        }
        else
        {
            char *ip = _message->GetDataString( NET_METASERVER_IP );
            int port = _message->GetDataInt( NET_METASERVER_PORT );

            AppDebugOut( "MatchMaker : SERVER Received request to allow client to join from %s:%d\n", ip, port );

            Directory dir;
            dir.SetName( NET_MATCHMAKER_MESSAGE );
            dir.CreateData( NET_METASERVER_COMMAND, NET_MATCHMAKER_RECEIVED_CONNECT );

            NetSocketSession session( *_listener, ip, port );            
            MetaServer_SendDirectory( &dir, &session );
        }
    }
    else if( strcmp( cmd, NET_MATCHMAKER_RECEIVED_CONNECT ) == 0 )
    {
        AppDebugOut( "MatchMaker : CLIENT received confirmation from Server that Hole Punch is set up\n" );
    }
    else
    {
        AppAbort( "unrecognised matchmaker message" );
    }

    return true;
}
Esempio n. 20
0
int 
main(int /*argc*/, char** /*argv*/)
{
    TestPrivateKeys();
    
    /* test a connection */
    const char* hostname = "koala.bok.net";
    printf("[1] Connecting to %s...\n", hostname);
    NPT_Socket* client_socket = new NPT_TcpClientSocket();
    NPT_IpAddress server_ip;
    server_ip.ResolveName(hostname);
    NPT_SocketAddress server_addr(server_ip, 443);
    NPT_Result result = client_socket->Connect(server_addr);
    printf("[2] Connection result = %d (%s)\n", result, NPT_ResultText(result));
    if (NPT_FAILED(result)) {
        printf("!ERROR\n");
        return 1;
    }
    
    NPT_InputStreamReference input;
    NPT_OutputStreamReference output;
    client_socket->GetInputStream(input);
    client_socket->GetOutputStream(output);
    NPT_TlsContextReference context(new NPT_TlsContext());
    NPT_TlsClientSession session(context, input, output);
    printf("[3] Performing Handshake\n");
    result = session.Handshake();
    printf("[4] Handshake Result = %d (%s)\n", result, NPT_ResultText(result));
    if (NPT_FAILED(result)) {
        printf("!ERROR\n");
        return 1;
    }
    NPT_DataBuffer session_id;
    result = session.GetSessionId(session_id);
    CHECK(result == NPT_SUCCESS);
    CHECK(session_id.GetDataSize() > 0);
    printf("[5] Session ID: ");
    printf(NPT_HexString(session_id.GetData(), session_id.GetDataSize()).GetChars());
    printf("\n");
    
    NPT_TlsCertificateInfo cert_info;
    result = session.GetPeerCertificateInfo(cert_info);
    CHECK(result == NPT_SUCCESS);
    printf("[6] Fingerprints:\n");
    printf("MD5: %s\n", NPT_HexString(cert_info.fingerprint.md5, sizeof(cert_info.fingerprint.md5), ":").GetChars());
    printf("SHA1: %s\n", NPT_HexString(cert_info.fingerprint.sha1, sizeof(cert_info.fingerprint.sha1), ":").GetChars());
    printf("Subject Certificate:\n");
    printf("  Common Name         = %s\n", cert_info.subject.common_name.GetChars());
    printf("  Organization        = %s\n", cert_info.subject.organization.GetChars());
    printf("  Organizational Name = %s\n", cert_info.subject.organizational_name.GetChars());
    printf("Issuer Certificate:\n");
    printf("  Common Name         = %s\n", cert_info.issuer.common_name.GetChars());
    printf("  Organization        = %s\n", cert_info.issuer.organization.GetChars());
    printf("  Organizational Name = %s\n", cert_info.issuer.organizational_name.GetChars());
    printf("\n");
    printf("[7] Cipher Type = %d (%s)\n", session.GetCipherSuiteId(), GetCipherSuiteName(session.GetCipherSuiteId()));
    
    NPT_InputStreamReference  ssl_input;
    NPT_OutputStreamReference ssl_output;
    session.GetInputStream(ssl_input);
    session.GetOutputStream(ssl_output);
    
    printf("[8] Getting / Document\n");
    ssl_output->WriteString("GET / HTTP/1.0\n\n");
    for (;;) {
        unsigned char buffer[1];
        NPT_Size bytes_read = 0;
        result = ssl_input->Read(&buffer[0], 1, &bytes_read);
        if (NPT_SUCCEEDED(result)) {
            CHECK(bytes_read == 1);
            printf("%c", buffer[0]);
        } else {
            if (result != NPT_ERROR_EOS) {
                printf("!ERROR: Read() returned %d (%s)\n", result, NPT_ResultText(result)); 
            }
            break;
        }
    }
    printf("[9] SUCCESS\n");
}
Esempio n. 21
0
 explicit session_iterator(session p = session(), endpoint::state s = 0) :
     iter_base<session>(p, s) {}
Esempio n. 22
0
void main() 
{
	Manager manager("fdimail.com");
	Session session(&manager);
}
Esempio n. 23
0
void HTTPWSTest::testHandShake()
{
    try
    {
        int bytes;
        int flags;
        char buffer[1024];
        // Load a document and get its status.
        const std::string documentPath = Util::getTempFilePath(TDOC, "hello.odt");
        const std::string documentURL = "file://" + Poco::Path(documentPath).makeAbsolute().toString();

        Poco::Net::HTTPResponse response;
        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, documentURL);
#if ENABLE_SSL
        Poco::Net::HTTPSClientSession session(_uri.getHost(), _uri.getPort());
#else
        Poco::Net::HTTPClientSession session(_uri.getHost(), _uri.getPort());
#endif
        Poco::Net::WebSocket socket(session, request, response);

        const std::string prefixEdit = "editlock:";
        const char* fail = "error:";
        std::string payload("statusindicator: find");

        std::string receive;
        socket.setReceiveTimeout(0);
        bytes = socket.receiveFrame(buffer, sizeof(buffer), flags);
        CPPUNIT_ASSERT_EQUAL((int) payload.size(), bytes);
        CPPUNIT_ASSERT(payload.compare(0, payload.size(), buffer, 0, bytes) == 0);
        CPPUNIT_ASSERT(flags == Poco::Net::WebSocket::FRAME_TEXT);

        bytes = socket.receiveFrame(buffer, sizeof(buffer), flags);
        if (!std::strstr(buffer, fail))
        {
            // After document broker finish searching it sends editlok
            // it should be at end on handshake
            CPPUNIT_ASSERT(prefixEdit.compare(0, prefixEdit.size(), buffer, 0, prefixEdit.size()) == 0);
            CPPUNIT_ASSERT(flags == Poco::Net::WebSocket::FRAME_TEXT);

            payload = "statusindicator: connect";
            bytes = socket.receiveFrame(buffer, sizeof(buffer), flags);
            CPPUNIT_ASSERT_EQUAL((int) payload.size(), bytes);
            CPPUNIT_ASSERT(payload.compare(0, payload.size(), buffer, 0, bytes) == 0);
            CPPUNIT_ASSERT(flags == Poco::Net::WebSocket::FRAME_TEXT);

            bytes = socket.receiveFrame(buffer, sizeof(buffer), flags);
            if (!std::strstr(buffer, fail))
            {
                payload = "statusindicator: ready";
                CPPUNIT_ASSERT_EQUAL((int) payload.size(), bytes);
                CPPUNIT_ASSERT(payload.compare(0, payload.size(), buffer, 0, bytes) == 0);
                CPPUNIT_ASSERT(flags == Poco::Net::WebSocket::FRAME_TEXT);
            }
            else
            {
                // check error message
                CPPUNIT_ASSERT(std::strstr(buffer, SERVICE_UNAVALABLE_INTERNAL_ERROR) != nullptr);
                CPPUNIT_ASSERT(flags == Poco::Net::WebSocket::FRAME_TEXT);

                // close frame message
                bytes = socket.receiveFrame(buffer, sizeof(buffer), flags);
                CPPUNIT_ASSERT(std::strstr(buffer, SERVICE_UNAVALABLE_INTERNAL_ERROR) != nullptr);
                CPPUNIT_ASSERT((flags & Poco::Net::WebSocket::FRAME_OP_BITMASK) == Poco::Net::WebSocket::FRAME_OP_CLOSE);
            }
        }
        else
        {
            // check error message
            CPPUNIT_ASSERT(std::strstr(buffer, SERVICE_UNAVALABLE_INTERNAL_ERROR) != nullptr);
            CPPUNIT_ASSERT(flags == Poco::Net::WebSocket::FRAME_TEXT);

            // close frame message
            bytes = socket.receiveFrame(buffer, sizeof(buffer), flags);
            CPPUNIT_ASSERT(std::strstr(buffer, SERVICE_UNAVALABLE_INTERNAL_ERROR) != nullptr);
            CPPUNIT_ASSERT((flags & Poco::Net::WebSocket::FRAME_OP_BITMASK) == Poco::Net::WebSocket::FRAME_OP_CLOSE);
        }

        socket.shutdown();
        Util::removeFile(documentPath);
    }
    catch (const Poco::Exception& exc)
    {
        CPPUNIT_FAIL(exc.displayText());
    }
}
Esempio n. 24
0
                break;
            }
        }
        /* If there is no focused view but views are present we will use the first one: */
        if (iFocusedView == -1 && !screenIds.isEmpty())
            iFocusedView = screenIds[0];
        /* Capture mouse using that view: */
        if (iFocusedView != -1)
            captureMouse(iFocusedView);
    }
#else /* but just to switch the guest mouse into relative mode! */
    /* If mouse-integration deactivated or mouse doesn't supports absolute pointing: */
    else
    {
        /* Switch guest mouse to the relative mode: */
        CMouse mouse = session().GetConsole().GetMouse();
        mouse.PutMouseEvent(0, 0, 0, 0, 0);
    }
#endif

    /* Notify user about mouse supports or not absolute pointing if that method was called by signal: */
    if (sender())
    {
        /* don't annoy the user while restoring a VM */
        KMachineState state = uisession()->machineState();
        if (state != KMachineState_Restoring)
            popupCenter().remindAboutMouseIntegration(uisession()->machineLogic()->activeMachineWindow(),
                                                      uisession()->isMouseSupportsAbsolute());
    }

    /* Notify all listeners: */
Esempio n. 25
0
DWORD CHttpClient::Request(LPCTSTR lpszURL, CString &strPostData,
						 CFile *pFileSave, CString *pstrResult,
						 PROGRESS_CALLBACK fnCallback, void *cookie )
{
	DWORD	dwRet	=	HTTP_STATUS_BAD_REQUEST;

	if( NULL == lpszURL || strlen(lpszURL) == 0 )
		return dwRet;

	int	nContentLength = 0;
	int nContentLengthLocal = 0;
	int nContentLengthFinished = 0;
	int nContentLengthTotal = 0;

	// prepare header
	CString	strHeader;
	CMapStringToString	mapHeader;
	if( pFileSave && pFileSave->GetPosition() > 0 )
	{
		nContentLengthFinished = (int)pFileSave->GetPosition();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
		
	}
	if( pstrResult && pstrResult->GetLength() > 0 )
	{
		nContentLengthFinished = pstrResult->GetLength();
		CString strRange;
		strRange.Format( "bytes=%u-", nContentLengthFinished );
		mapHeader.SetAt( szRange, strRange );
	}
	if( m_strCookie.GetLength() > 0 )
		mapHeader.SetAt( szCookieKey, m_strCookie );
	MakeHttpHeader( mapHeader, strHeader );

	// default type and flags
	DWORD dwHttpRequestFlags =	INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD
								| INTERNET_FLAG_DONT_CACHE
								| INTERNET_FLAG_EXISTING_CONNECT; // | INTERNET_FLAG_KEEP_CONNECTION;
	
	CString	strProxy;
	if( !m_strProxyAddress.IsEmpty() )
		strProxy = FormatProxyString( m_nProxyType, m_strProxyAddress, m_nProxyPort );
	CInternetSession session(	szUserAgentValue, 1, m_nAccessType,
							strProxy, NULL, INTERNET_FLAG_DONT_CACHE );
	// 以下SetOption似乎不起作用
	if( !strProxy.IsEmpty() && !m_strProxyAddress.IsEmpty() )
	{
		session.SetOption( INTERNET_OPTION_PROXY_USERNAME, (LPVOID)(LPCTSTR)m_strProxyUser, m_strProxyUser.GetLength() );
		session.SetOption( INTERNET_OPTION_PROXY_PASSWORD, (LPVOID)(LPCTSTR)m_strProxyPasswd, m_strProxyPasswd.GetLength() );
	}
	session.SetOption( INTERNET_OPTION_RECEIVE_TIMEOUT, 300000 );
	session.SetOption( INTERNET_OPTION_SEND_TIMEOUT, 30000 );
	session.SetOption( INTERNET_OPTION_CONNECT_TIMEOUT, 30000 );

	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	try
	{
		// check to see if this is a reasonable URL
		DoOpenURL( lpszURL, dwHttpRequestFlags, strHeader, strPostData, &session, &pServer, &pFile, fnCallback, cookie );
		if( NULL == pServer || NULL == pFile )
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		pFile->QueryInfoStatusCode(dwRet);

		if (dwRet == HTTP_STATUS_MOVED ||
			dwRet == HTTP_STATUS_REDIRECT ||
			dwRet == HTTP_STATUS_REDIRECT_METHOD)
		{
			CString strNewLocation = GetNewLocation( pFile );

			// close up the redirected site
			pFile->Close();
			delete pFile;
			pFile	=	NULL;
			pServer->Close();
			delete pServer;
			pServer	=	NULL;

			// progress callback
			if( fnCallback )
				fnCallback( PROG_REDIRECTING, 0, NULL, cookie );

			// open new url
			DoOpenURL( strNewLocation, dwHttpRequestFlags,
						strHeader, strPostData,
						&session, &pServer, &pFile, fnCallback, cookie );
			
			pFile->QueryInfoStatusCode(dwRet);
		}

		if (dwRet == HTTP_STATUS_PARTIAL_CONTENT)
			dwRet = HTTP_STATUS_OK;
		if (dwRet != HTTP_STATUS_OK)
			ThrowTearException( ERR_TEAR_INTERRUPTED );

		CString	strInfo;
		pFile->QueryInfo( HTTP_QUERY_SET_COOKIE, strInfo );
		pFile->QueryInfo( HTTP_QUERY_COOKIE, strInfo );
		if( strInfo.GetLength() )
			m_strCookie	=	strInfo;
		pFile->QueryInfo( HTTP_QUERY_CONTENT_LENGTH, strInfo );
		nContentLength	=	atol( strInfo );
		nContentLengthTotal = nContentLength + nContentLengthFinished;
		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->GetBuffer( nContentLengthTotal+5 );

		DWORD	dwCheckSum	=	0;
		BOOL	bHasCheckSum	=	FALSE;
		CString	strCheckSum;
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strCheckSum);
		int nPlace = strCheckSum.Find( szCheckSumKeySuffix );
		if ( -1 != nPlace )
		{
			strCheckSum = strCheckSum.Mid( nPlace+strlen(szCheckSumKeySuffix) );
			nPlace = strCheckSum.Find( '\n' );
			if( nPlace > 0 )
			{
				dwCheckSum = atol( strCheckSum.Left( nPlace ) );
				bHasCheckSum	=	TRUE;
			}
		}

		if( fnCallback )
			fnCallback( PROG_TRANSFERRING, 0, NULL, cookie );

		DWORD	dwCheckSumLocal	=	0;
		TCHAR sz[1028];
		int nRead = pFile->Read(sz+4, 1023);
		while (nRead > 0)
		{
			sz[4+nRead] = '\0';
			if( NULL != pFileSave )
				pFileSave->Write( sz+4, nRead );
			if( NULL != pstrResult )
				*pstrResult	+=	(TCHAR *)(sz+4);
			nContentLengthLocal	+=	nRead;

			if( fnCallback && nContentLengthTotal > 0 )
				fnCallback( PROG_PROGRESS, DWORD(STKLIB_MAXF_PROGRESS*(nContentLengthFinished+nContentLengthLocal)/nContentLengthTotal), NULL, cookie );

			if( bHasCheckSum )
			{
				*((DWORD *)sz)	=	dwCheckSumLocal;
				dwCheckSumLocal = CRC32( sz, nRead );
			}

			nRead = pFile->Read(sz+4, 1023);
		}

		if( pstrResult && nContentLengthTotal > 0 )
			pstrResult->ReleaseBuffer();

		if( (nContentLength > 0 && nContentLengthLocal != nContentLength)
				|| (bHasCheckSum && dwCheckSum != dwCheckSumLocal) )
			ThrowTearException( ERR_TEAR_DATATRANSFER );

		if( fnCallback )
			fnCallback( PROG_PROGRESS, STKLIB_MAX_PROGRESS, NULL, cookie );
	}
	catch (CInternetException* pEx)
	{
		// catch errors from WinINet
		if (HTTP_STATUS_OK == dwRet)
			dwRet	=	HTTP_STATUS_PARTIAL;
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch (CTearException* pEx)
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}
	catch( CException * pEx )
	{
		TCHAR szErr[1024];
		pEx->GetErrorMessage(szErr, 1024);
		m_strLastErrorMessage	=	szErr;
		pEx->Delete();
	}

	if (pFile != NULL)
	{
		pFile->Close();
		delete pFile;
	}
	if (pServer != NULL)
	{
		pServer->Close();
		delete pServer;
	}
	session.Close();

	if(nContentLength > 0 && nContentLengthLocal != nContentLength)
		return Request( lpszURL, strPostData, pFileSave, pstrResult, fnCallback, cookie );

	return dwRet;
}
/*!
  \~english
  Logs out of the system.
  
  This is a virtual function.
  \~japanese
  ユーザをログアウトさせる
  \~
  \sa userLogin()
*/
void TActionController::userLogout()
{
    session().take(LOGIN_USER_NAME_KEY);
}
Esempio n. 27
0
void modify_sec(int n) {
  char s[81];

  gfiledirrec r = gfilesec[n];
  bool done = false;
  do {
    bout.cls();
    bout.litebar("Editing G-File Area # %d", n);
    bout << "|#9A) Name       : |#2" << r.name << wwiv::endl;
    bout << "|#9B) Filename   : |#2" << r.filename << wwiv::endl;
    bout << "|#9C) SL         : |#2" << static_cast<int>(r.sl) << wwiv::endl;
    bout << "|#9D) Min. Age   : |#2" << static_cast<int>(r.age) << wwiv::endl;
    bout << "|#9E) Max Files  : |#2" << r.maxfiles << wwiv::endl;
    bout << "|#9F) AR         : |#2" << GetArString(r, s) << wwiv::endl;
    bout.nl();
    bout << "|#7(|#2Q|#7=|#1Quit|#7) Which (|#1A|#7-|#1F,|#1[|#7,|#1]|#7) : ";
    char ch = onek("QABCDEF[]", true);
    switch (ch) {
    case 'Q':
      done = true;
      break;
    case '[':
      gfilesec[n] = r;
      if (--n < 0) {
        n = session()->num_sec - 1;
      }
      r = gfilesec[n];
      break;
    case ']':
      gfilesec[n] = r;
      if (++n >= session()->num_sec) {
        n = 0;
      }
      r = gfilesec[n];
      break;
    case 'A':
      bout.nl();
      bout << "|#2New name? ";
      inputl(s, 40);
      if (s[0]) {
        strcpy(r.name, s);
      }
      break;
    case 'B': {
      bout.nl();
      File dir(syscfg.gfilesdir, r.filename);
      if (dir.Exists()) {
        bout << "\r\nThere is currently a directory for this g-file section.\r\n";
        bout << "If you change the filename, the directory will still be there.\r\n\n";
      }
      bout.nl();
      bout << "|#2New filename? ";
      input(s, 8);
      if ((s[0] != 0) && (strchr(s, '.') == 0)) {
        strcpy(r.filename, s);
        File dir(syscfg.gfilesdir, r.filename);
        if (!dir.Exists()) {
          bout.nl();
          bout << "|#5Create directory for this section? ";
          if (yesno()) {
            File dir(syscfg.gfilesdir, r.filename);
            File::mkdirs(dir);
          } else {
            bout << "\r\nYou will have to create the directory manually, then.\r\n\n";
          }
        } else {
          bout << "\r\nA directory already exists under this filename.\r\n\n";
        }
        pausescr();
      }
    }
    break;
    case 'C': {
      bout.nl();
      bout << "|#2New SL? ";
      input(s, 3);
      int i = atoi(s);
      if (i >= 0 && i < 256 && s[0]) {
        r.sl = static_cast<unsigned char>(i);
      }
    }
    break;
    case 'D': {
      bout.nl();
      bout << "|#2New Min Age? ";
      input(s, 3);
      int i = atoi(s);
      if ((i >= 0) && (i < 128) && (s[0])) {
        r.age = static_cast<unsigned char>(i);
      }
    }
    break;
    case 'E': {
      bout.nl();
      bout << "|#1Max 99 files/section.\r\n|#2New max files? ";
      input(s, 3);
      int i = atoi(s);
      if ((i >= 0) && (i < 99) && (s[0])) {
        r.maxfiles = static_cast<unsigned short>(i);
      }
    }
    break;
    case 'F':
      bout.nl();
      bout << "|#2New AR (<SPC>=None) ? ";
      char ch2 = onek("ABCDEFGHIJKLMNOP ");
      if (ch2 == SPACE) {
        r.ar = 0;
      } else {
        r.ar = 1 << (ch2 - 'A');
      }
      break;
    }
  } while (!done && !hangup);
  gfilesec[n] = r;
}
/*!
  \~english
  Returns true if a user is logged in to the system; otherwise returns false.
  
  This is a virtual function.
  \~japanese
  ユーザがログインしている場合は true を返し、そうでない場合は false を返す
  \~
  \sa userLogin()
*/
bool TActionController::isUserLoggedIn() const
{
    return session().contains(LOGIN_USER_NAME_KEY);
}
			void EventConnection::internalProcess()
			{
				try
				{
					Poco::URI uri(_eventReceiverURI);

                    // prepare session
					Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
        		    session.setKeepAlive(false);

					if(_soapAction.find("ErrorEvent") != std::string::npos)
					{
						session.setTimeout(Poco::Timespan(10,0,0,0,0));
					}
                
                    // prepare request
                    std::string path (uri.getPathAndQuery());
				    if(path.empty())
				    {
                        path = "/";
				    }
					Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPMessage::HTTP_1_1);
				    request.setContentLength(_content.length());
					request.setContentType("text/xml; charset=utf-8");
					request.setKeepAlive(false);

                    request.set("SOAPAction","\"" + _soapAction + "\"");

                    // send request
                    std::ostream& outStream = session.sendRequest(request);
                    outStream << _content;

                    // get response
                    Poco::Net::HTTPResponse response;
                    std::istream& inStream = session.receiveResponse(response);

					std::ostringstream responseContentStream;
					Poco::StreamCopier::copyStream(inStream, responseContentStream);
					_responseContent = responseContentStream.str();

					if(response.getStatus() != 200)
					{
						std::ostringstream strout;
						strout << "EventConnection HTTP-Error: " << response.getStatus() << " - " << response.getReason();
						_errorMessage = strout.str();
						_error = true;
					}

					while(session.connected())
					{
						session.abort();
					}

					_finished = true;
				}
                catch (std::exception e)
				{
					std::ostringstream strout;
					strout << "EventConnection Exception: " << e.what();
					_errorMessage = strout.str();
					_error = true;
					_finished = true;
				}


			}
void ConfigStorage::checkFile()
{
	if (m_cfg_file >= 0)
		return;

	char* cfg_file_name = m_sharedMemory->getHeader()->cfg_file_name;

	if (!(*cfg_file_name))
	{
		fb_assert(m_sharedMemory->getHeader()->cnt_uses == 0);

		char dir[MAXPATHLEN];
		iscPrefixLock(dir, "", true);

		PathName filename = TempFile::create("fb_trace_", dir);
		filename.copyTo(cfg_file_name, sizeof(m_sharedMemory->getHeader()->cfg_file_name));
		m_cfg_file = os_utils::openCreateSharedFile(cfg_file_name, O_BINARY);
	}
	else
	{
		m_cfg_file = ::open(cfg_file_name, O_RDWR | O_BINARY);

		if (m_cfg_file < 0)
			checkFileError(cfg_file_name, "open", isc_io_open_err);
	}

	// put default (audit) trace file contents into storage
	if (m_sharedMemory->getHeader()->change_number == 0)
	{
		FILE* cfgFile = NULL;

		try
		{
			PathName configFileName(Config::getAuditTraceConfigFile());

			// remove quotes around path if present
			{ // scope
				const FB_SIZE_T pathLen = configFileName.length();
				if (pathLen > 1 && configFileName[0] == '"' &&
					configFileName[pathLen - 1] == '"')
				{
					configFileName.erase(0, 1);
					configFileName.erase(pathLen - 2, 1);
				}
			}

			if (configFileName.empty())
				return;

			if (PathUtils::isRelative(configFileName))
			{
				PathName root(Config::getRootDirectory());
				PathUtils::ensureSeparator(root);
				configFileName.insert(0, root);
			}

			cfgFile = fopen(configFileName.c_str(), "rb");
			if (!cfgFile) {
				checkFileError(configFileName.c_str(), "fopen", isc_io_open_err);
			}

			TraceSession session(*getDefaultMemoryPool());

			fseek(cfgFile, 0, SEEK_END);
			const long len = ftell(cfgFile);
			if (len)
			{
				fseek(cfgFile, 0, SEEK_SET);
				char* p = session.ses_config.getBuffer(len + 1);

				if (fread(p, 1, len, cfgFile) != size_t(len)) {
					checkFileError(configFileName.c_str(), "fread", isc_io_read_err);
				}
				p[len] = 0;
			}
			else {
				gds__log("Audit configuration file \"%s\" is empty", configFileName.c_str());
			}

			session.ses_user = SYSDBA_USER_NAME;
			session.ses_name = "Firebird Audit";
			session.ses_flags = trs_admin | trs_system;

			addSession(session);
		}
		catch(const Exception& ex)
		{
			ISC_STATUS_ARRAY temp;
			ex.stuff_exception(temp);
			iscLogStatus("Cannot open audit configuration file", temp);
		}

		if (cfgFile) {
			fclose(cfgFile);
		}
	}
}