• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ session函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中session函数的典型用法代码示例。如果您正苦于以下问题:C++ session函数的具体用法?C++ session怎么用?C++ session使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了session函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: dest_uid

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(':','',);

//.........这里部分代码省略.........
开发者ID:thilinamh,项目名称:VoIPserver,代码行数:101,代码来源:CallSetuptState.cpp


示例2: delete_sec

void delete_sec(int n) {
  for (int i = n; i < session()->num_sec; i++) {
    gfilesec[i] = gfilesec[i + 1];
  }
  --session()->num_sec;
}
开发者ID:bhaggerty,项目名称:wwiv-1,代码行数:6,代码来源:gfledit.cpp


示例3: main

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);
    }
//.........这里部分代码省略.........
开发者ID:maxamillion,项目名称:cockpit,代码行数:101,代码来源:session.c


示例4: session

bool HttpServlet::doRun(const char* memcached_addr, socket_stream* stream)
{
	memcache_session session(memcached_addr);
	return doRun(session, stream);
}
开发者ID:lunlun1992,项目名称:acl,代码行数:5,代码来源:HttpServlet.cpp


示例5: incomingMsg

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);

//.........这里部分代码省略.........
开发者ID:ansuz,项目名称:cjdns,代码行数:101,代码来源:Pathfinder.c


示例6: OpenEtelServerL

/**
 * @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;
//.........这里部分代码省略.........
开发者ID:cdaffara,项目名称:symbiandump-os1,代码行数:101,代码来源:cctsyucasembms020.cpp


示例7: tasklet

// [P]
void X86ValuesTask::ProcessFunction(Function& fn) {
  ValuesTasklet tasklet(session(), fn.module());
  tasklet.Run(fn);
} // ProcessFunction
开发者ID:eval1749,项目名称:evm,代码行数:5,代码来源:_X86ValuesTasks.cpp


示例8: start

    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();
//.........这里部分代码省略.........
开发者ID:tvi123,项目名称:redemption,代码行数:101,代码来源:session_server.hpp


示例9: timelog

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);
}
开发者ID:ACMEware,项目名称:Paper-Hurricane,代码行数:80,代码来源:main.cpp


示例10: pack

    _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);
开发者ID:ey6es,项目名称:witgap,代码行数:31,代码来源:EditUserDialog.cpp


示例11: do_lq_request

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();
//.........这里部分代码省略.........
开发者ID:ClusterLabs,项目名称:fence-virt,代码行数:101,代码来源:libvirt-qmf.cpp


示例12: answer_mode

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);
}
开发者ID:sisoftrg,项目名称:qico,代码行数:73,代码来源:main.c


示例13: userLogin

/*!
  \~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();
}
开发者ID:deniskin82,项目名称:treefrog-framework,代码行数:15,代码来源:tactioncontroller.cpp


示例14: session

bool AuthHostInstance::inDarkWake()
{
	return session().server().inDarkWake();
}
开发者ID:unofficial-opensource-apple,项目名称:Security,代码行数:4,代码来源:authhost.cpp


示例15: _

/* 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;

}
开发者ID:Apple-FOSS-Mirror,项目名称:Security,代码行数:94,代码来源:RSA_asymmetric.cpp


示例16: peer

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;
}
开发者ID:HiPiH,项目名称:Oreka,代码行数:84,代码来源:MultiThreadedServer.cpp


示例17: MatchMaker_ReceiveMessage

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;
}
开发者ID:BITINT,项目名称:DEFCON2,代码行数:82,代码来源:matchmaker.cpp


示例18: main

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(hos 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ session_destroy函数代码示例发布时间:2022-05-30
下一篇:
C++ service_start函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap