Beispiel #1
0
void Database::CreateTable(void)
{
	////////////////////////////////////////////////////////////////////////// create mission
	execute("CREATE TABLE IF NOT EXISTS mission( \
			missionid	INTEGER primary key autoincrement, \
			type		INTEGER, \
			missionname TEXT, \
			crtime		DATETIME, \
			retime		DATETIME, \
			sctime		DATETIME, \
			score		INTEGER, \
			frequency	BLOB \
			)");


	////////////////////////////////////////////////////////////////////////// create end
	execute( "CREATE TABLE IF NOT EXISTS end( \
			 missionid		INTEGER primary key autoincrement, \
			 type			INTEGER, \
			 missionname	TEXT, \
			 crtime			DATETIME, \
			 retime			DATETIME, \
			 sctime			DATETIME, \
			 score			INTEGER \
			 )");


	CreateUser();
}
Beispiel #2
0
// 새 유저객체를 만들어 유저매니저에 넣는다.
XSPUserBase XEWinSocketSvr::CreateAddToUserMng( XSPWinConnInServer spConnect, XSPDBAcc spAccount )
{
	// 커넥션이 끊긴채로 왔으면 생성하지 않는다. 
	// 커넥션이 생성되고 메인스레드의 Process에서 XUser가 연결되기까지 
	// 아주 잠깐동안의 시간이 있는데 이시간동안 만약 접속이 끊기면 유저 등록을 취소해야한다.
	if( spConnect->IsDisconnected() ) {
		// 드문경우라서 로그를 한번 남겨봄. 너무 자주나오면 없앰.
//#if _DEV_LEVEL <= DLV_DEV_EXTERNAL
		CONSOLE_THIS( "connect", "pConnect is disconnected. ip=%s", spConnect->GetszIP() );
//#endif		
		return nullptr;
	}
	XBREAK( m_pUserMng == nullptr );
	// 유저 생성
	auto spNewUser = CreateUser( spConnect );		// virtual
	// 아마도 메모리풀 꽉참? 혹은 CreateUser미구현?
	if( XBREAK( spNewUser == nullptr ) )
		return nullptr;
	spNewUser->SetspDBAccount( spAccount );
	// 유저매니저에 넣는다.
	// 넣기전 중복체크
	const ID idUser = spNewUser->GetidUser();
	{
		auto spExist = m_pUserMng->GetspUserFromidAcc( idUser );
		if( spExist ) {
#if _DEV_LEVEL <= DLV_DEV_EXTERNAL
			CONSOLE( "중복접속 계정: idAcc=%d", spExist->GetidUser() );
#endif			
			spExist->DoDisconnect();		// 일단 먼저 끊고
			spExist->DoDestroy();			// 커넥션 삭제되도록 파괴 메시지
			m_pUserMng->DelUser( spExist );		// 기존유저에게 이벤트핸들링 호출하고 리스트에서 삭제
			spExist.reset();
		}
	}
	// 새 유저객체 등록
	auto bSuccess = m_pUserMng->Add( spNewUser );
	//
// 	if( XBREAK( bSuccess == false ) ) {
// 		spNewUser = nullptr;
// 	}
	if( XASSERT( bSuccess ) ) {
		spConnect->SetspUser( spNewUser );	// 커넥션에 유저를 붙인다.
		// idAcc로 커넥션 찾는 맵에 등록.
		auto pMap = &m_Logined.m_shoMapByidAcc.GetSharedObj();
		(*pMap)[ spAccount->GetidAccount() ] = spConnect;
		m_Logined.m_shoMapByidAcc.ReleaseSharedObj();
		spNewUser->OnLogined();				// 유저객체로 핸들러를 날려준다.
	} else {
		spNewUser = nullptr;
	}
	return spNewUser;
}
Beispiel #3
0
	void CreateUserCommand(const CString &sLine) {
		CString sCreate = sLine.Token(1);

		if (!sCreate.empty()) {
			SetNV("CreateUser", sCreate);
		}

		if (CreateUser()) {
			PutModule("We will create users on their first login");
		} else {
			PutModule("We will not create users on their first login");
		}
	}
Beispiel #4
0
void CUserManager::AddUser( SOCKET hSocket, sockaddr_in* pRemoteAddress )
{
	/*
	> add user stack
	*/

	CUser* pUser = CreateUser( );
	{
		size_t nId = m_nNextId.fetch_add( 1, std::memory_order::memory_order_relaxed );

		pUser->BindUser( nId, hSocket, pRemoteAddress );

		m_mapIdToUser.insert( std::make_pair( nId, pUser ) );
	}
}
Beispiel #5
0
	virtual EModRet OnLoginAttempt(CSmartPtr<CAuthBase> Auth) {
		const CString& sUsername = Auth->GetUsername();
		const CString& sPassword = Auth->GetPassword();
		CUser *pUser(CZNC::Get().FindUser(sUsername));
		sasl_conn_t *sasl_conn(NULL);
		bool bSuccess = false;

		if (!pUser && !CreateUser()) {
			return CONTINUE;
		}

		const CString sCacheKey(CString(sUsername + ":" + sPassword).MD5());
		if (m_Cache.HasItem(sCacheKey)) {
			bSuccess = true;
			DEBUG("saslauth: Found [" + sUsername + "] in cache");
		} else if (sasl_server_new("znc", NULL, NULL, NULL, NULL, m_cbs, 0, &sasl_conn) == SASL_OK &&
				sasl_checkpass(sasl_conn, sUsername.c_str(), sUsername.size(), sPassword.c_str(), sPassword.size()) == SASL_OK) {
			m_Cache.AddItem(sCacheKey);

			DEBUG("saslauth: Successful SASL authentication [" + sUsername + "]");

			bSuccess = true;
		}

		sasl_dispose(&sasl_conn);

		if (bSuccess) {
			if (!pUser) {
				CString sErr;
				pUser = new CUser(sUsername);

				if (ShouldCloneUser()) {
					CUser *pBaseUser = CZNC::Get().FindUser(CloneUser());

					if (!pBaseUser) {
						DEBUG("saslauth: Clone User [" << CloneUser() << "] User not found");
						delete pUser;
						pUser = NULL;
					}

					if (pUser && !pUser->Clone(*pBaseUser, sErr)) {
						DEBUG("saslauth: Clone User [" << CloneUser() << "] failed: " << sErr);
						delete pUser;
						pUser = NULL;
					}
				}

				if (pUser) {
					// "::" is an invalid MD5 hash, so user won't be able to login by usual method
					pUser->SetPass("::", CUser::HASH_MD5, "::");
				}

				if (pUser && !CZNC::Get().AddUser(pUser, sErr)) {
					DEBUG("saslauth: Add user [" << sUsername << "] failed: " << sErr);
					delete pUser;
					pUser = NULL;
				}
			}

			if (pUser) {
				Auth->AcceptLogin(*pUser);
				return HALT;
			}
		}

		return CONTINUE;
	}
Beispiel #6
0
void ProfileManager::LoadV1Profiles(JSON* v1)
{
    JSON* item0 = v1->GetFirstItem();
    JSON* item1 = v1->GetNextItem(item0);
    JSON* item2 = v1->GetNextItem(item1);

    // Create the new profile database
    Ptr<JSON> root = *JSON::CreateObject();
    root->AddNumberItem("Oculus Profile Version", 2.0);
    root->AddItem("Users", JSON::CreateArray());
    root->AddItem("TaggedData", JSON::CreateArray());
    ProfileCache = root;

    const char* default_dk1_user = item1->Value;
    
    // Read the number of profiles
    int   profileCount = (int)item2->dValue;
    JSON* profileItem  = item2;

    for (int p=0; p<profileCount; p++)
    {
        profileItem = root->GetNextItem(profileItem);
        if (profileItem == NULL)
            break;

        if (profileItem->Name == "Profile")
        {
            // Read the required Name field
            const char* profileName;
            JSON* item = profileItem->GetFirstItem();
        
            if (item && (item->Name == "Name"))
            {   
                profileName = item->Value;
            }
            else
            {
                return;   // invalid field
            }
            
            // Read the user profile fields
            if (CreateUser(profileName, profileName))
            {
                const char* tag_names[2] = {"User", "Product"};
                const char* tags[2];
                tags[0] = profileName;

                Ptr<Profile> user_profile = *CreateProfile();
                user_profile->SetValue(OVR_KEY_NAME, profileName);

                float neckeye[2] = { 0, 0 };

                item = profileItem->GetNextItem(item);
                while (item)
                {
                    if (item->Type != JSON_Object)
                    {
                        if (item->Name == OVR_KEY_PLAYER_HEIGHT)
                        {   // Add an explicit eye height

                        }
                        if (item->Name == "NeckEyeHori")
                            neckeye[0] = (float)item->dValue;
                        else if (item->Name == "NeckEyeVert")
                            neckeye[1] = (float)item->dValue;
                        else 
                            user_profile->SetValue(item);
                    }
                    else
                    {   
                        // Add the user/device tag values
                        const char* device_name = item->Name.ToCStr();
                        Ptr<Profile> device_profile = *CreateProfile();

                        JSON* device_item = item->GetFirstItem();
                        while (device_item)
                        {
                            device_profile->SetValue(device_item);
                            device_item = item->GetNextItem(device_item);
                        }

                        tags[1] = device_name;
                        SetTaggedProfile(tag_names, tags, 2, device_profile);
                    }

                    item = profileItem->GetNextItem(item);
                }

                // Add an explicit eye-height field
                float player_height = user_profile->GetFloatValue(OVR_KEY_PLAYER_HEIGHT,
                                                                  OVR_DEFAULT_PLAYER_HEIGHT);
                if (player_height > 0)
                {
                    char gender[16];
                    user_profile->GetValue(OVR_KEY_GENDER, gender, 16);
        
                    const float EYE_TO_HEADTOP_RATIO =   0.44538f;
                    const float MALE_AVG_HEAD_HEIGHT =   0.232f;
                    const float FEMALE_AVG_HEAD_HEIGHT = 0.218f;
     
                    // compute distance from top of skull to the eye
                    float head_height;
                    if (OVR_strcmp(gender, "Female") == 0)
                        head_height = FEMALE_AVG_HEAD_HEIGHT;
                    else
                        head_height = MALE_AVG_HEAD_HEIGHT;

                    float skull = EYE_TO_HEADTOP_RATIO * head_height;
                    float eye_height = player_height - skull;

                    user_profile->SetFloatValue(OVR_KEY_EYE_HEIGHT, eye_height);
                }

                // Convert NeckEye values to an array
                if (neckeye[0] > 0 && neckeye[1] > 0)
                    user_profile->SetFloatValues(OVR_KEY_NECK_TO_EYE_DISTANCE, neckeye, 2);

                // Add the user tag values
                SetTaggedProfile(tag_names, tags, 1, user_profile);
            }
        }
    }

    // since V1 profiles were only for DK1, the assign the user to all DK1's
    const char* tag_names[1] = { "Product" };
    const char* tags[1] = { "RiftDK1" };
    Ptr<Profile> product_profile = *CreateProfile();
    product_profile->SetValue("DefaultUser", default_dk1_user);
    SetTaggedProfile(tag_names, tags, 1, product_profile);
}
Beispiel #7
0
int main(void) {
	users_t users[MAX_USERS];
	char buf[100];
	int done = 0;

//	BusyWork();

	// set a global pointer for easier function access
	USERS = users;

	// init some vars
	ADMIN_ACCESS = 0;
	CURRENT_USER = -1;
	NUM_USERS = 0;
	zero((char *)USERS, sizeof(users_t)*MAX_USERS);

	while (!done) {
		if (ADMIN_ACCESS) {
			zero(buf, 100);
			PrintAdminMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					SendBroadcastMessage();
					break;

				case '2':
					ADMIN_ACCESS = 0;
					break;

				case '3':
					print("Exiting...\n");
					done = 1;
					break;

				default:
					continue;
			}
		} else if (CURRENT_USER == -1) {
			zero(buf, 100);
			PrintLoggedOutMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					CreateUser();
					break;
				case '2':
					Login();
					break;
				case '3':
					print("Exiting...\n");
					_terminate(0);
					break;
				default:
					print("[-] Invalid choice\n");
					continue;
			}
		} else {
			zero(buf, 100);
			PrintNewMessages();
			PrintLoggedInMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					SendMessage();
					break;
				case '2':
					ReadMessage();
					break;
				case '3':
					ListMessages();
					break;
				case '4':
					DeleteMessage();
					break;
				case '5':
					CURRENT_USER = -1;
					print("Logging out...\n");
					break;
				case '6':
					print("Exiting...\n");
					_terminate(0);
					break;
				case 'a':
					AdminLogin();
					break;
				default:
					print("[-] Invalid choice\n");
					continue;
			}
		}
	}

	return(0);
}
Beispiel #8
0
// Send가 완료 되지 않았는데 다시 Send를 요청한다면? 어떻게 해야 하나...
// Recv에서 패킷을 다받지 못했거나 더 많이 받았을 때는 어떻게 해야하나...
int CPacketProcess::Procedure(CUser * pUser)
{
	// 이 부분 처리를 어떤 식으로 해야 할지 모르겠다.
	// 따로 클래스를 만들자니.. 머하고.. 동기화도 그렇고..
	// 근데 지금 크리티컬세션을 넣었는데.. 꼭 해야 하나? 솔직히 모르겠다.
	// 지금은 CPU가 한개라서 IOCP 스레드는 한개가 돌아 가니 동기화가 그렇게 필요는 없다.
	// (IOCP는 CPU개수만큼 스레드 스위칭을 한다.)
	// 하지만, CPU가 두개인 컴퓨터라면... ㅜ.ㅠ 어케해야하너....
	// 두개 만들고 테스트 해봐야겠다.
	// 2로 지정을 하고 테스트를 했는데 잘 돌아 간다..
	// 2명으로는 무리인가... 더 많은 사람.. 인터넷 안좋은 사람이 필요하다..-_-;;
	if(m_pProcessThread == NULL)
	{
		ServerLog()->Log("CPacketProcess Var Init Error.");
		return PROCEDURE_ERROR;
	}

	char PacketID = -1;

	if(!pUser->GetRecvPacket()->Get8Bit(PacketID))
	{
		ServerLog()->Log("ChatProcedure() : Packet ID get Error.");
		return PROCEDURE_ERROR;
	}

	switch((int)PacketID)
	{
	case MSG_CLNT_CHATMSG:
		{
			// 채팅 메시지
			if(!BroadcastMessage(pUser))
				return PROCEDURE_ERROR;
		}
		break;

	case MSG_CLNT_LOGIN:
		{
			return ClientLogin(pUser);
		}
		break;

	case MSG_CLNT_DISCONNECT:
		{
			return PROCEDURE_CLIENTCLOSE;
		}
		break;

	case MSG_CLNT_TOUSERMSG: // 귀속말
		{
			if(!FromToMessage(pUser))
				return PROCEDURE_ERROR;
		}
		break;

	case MSG_CLNT_CREATEUSER:
		{
			if(!CreateUser(pUser))
				return PROCEDURE_ERROR;
			return PROCEDURE_SENDNCLOSE;
		}
		break;

	default:
		{
			// 무엇인지 알 수 없는 패킷을 보내면 연결을 닫는다.
			ServerLog()->Log("Client send bad Packet. Client will Close.");
			return PROCEDURE_ERROR;
		}
		break;
	}
	return PROCEDURE_SUCCESS;
}
/* Note: Using the UNICODE version of main().
   this removes the need for the sample to include
   UNICODE-ANSI conversion routines
*/
void wmain( int argc, wchar_t *argv[ ])
{
    WCHAR pwszTemp[4096];
    
    // We have now scanned PAST whitespace- so copy the string:
    wcscpy_s(pwszTemp,4096,L" A String");

    Trim(pwszTemp);

    HRESULT hr;
    IDirectoryObject * pDirObjectContainer = NULL;
    IDirectoryObject * pDirObjRet = NULL;

    if (!ParseCommandLine(argc,argv))
        return;

    // Initialize COM
    CoInitialize(0);
 
    // Bind to the container passed 
    // If USER and PASS passed in, use ADsOpenObject()
    if (bsUSER)
        hr = ADsOpenObject(bsLDAP, bsUSER, bsPASS, 
                                   ADS_SECURE_AUTHENTICATION,IID_IDirectoryObject, (void**) &pDirObjectContainer);
    else
        hr = ADsGetObject(  bsLDAP, IID_IDirectoryObject,(void **)&pDirObjectContainer);
    
    if (SUCCEEDED(hr))
    {
        // if a file is NOT passed in- Do the simple version
        if (!bsFILE)
        {
            // Call the helper funtion to create the User
            hr = CreateUser(pDirObjectContainer, bsUNAME,bsSAMNAME,
                             &pDirObjRet);
        }
        else // file was passed in
        {
            // Call the helper funtion to create the User
            hr = CreateUserFromFile(pDirObjectContainer, bsUNAME,bsSAMNAME,
                                    &pDirObjRet,bsFILE);
        }        
        if (SUCCEEDED(hr))
        {
            _putws(L"\n\n New User created with the following properties:\n");
        
            IADs * pIADsNewGoup = NULL;
        
            // User succeeded- now get an IADs interface to it 
            // and print some properties
            hr = pDirObjRet->QueryInterface(IID_IADs,(void**)&pIADsNewGoup);

            if (SUCCEEDED(hr))
            {
                PrintIADSObject(pIADsNewGoup);
                        
                pIADsNewGoup->Release();
                pIADsNewGoup = NULL;
            }
            else
                CheckADHRESULT(hr,L"QueryInterface() - New User for IADs");
            pDirObjRet->Release();
            pDirObjRet = NULL;    
        }
        else
            CheckADHRESULT(hr,L"CreateUser()");

        pDirObjectContainer->Release();
        pDirObjectContainer = NULL;    
    }
    else
        if (bsUSER)
            CheckADHRESULT(hr,L"ADsOpenObject()");
        else
            CheckADHRESULT(hr,L"ADsGetObject()");


	if ( bsLDAP )
		::SysFreeString(bsLDAP);
	if ( bsUNAME )
		::SysFreeString(bsUNAME);
	if ( bsSAMNAME )
		::SysFreeString(bsSAMNAME);
	if ( bsFILE )
		::SysFreeString(bsFILE);
	if ( bsUSER )
		::SysFreeString(bsUSER);
	if ( bsPASS )
		::SysFreeString(bsPASS);

    CoUninitialize();
 }
Beispiel #10
0
GroupServer::UserStatus GroupServer::UserAlive(
        const char *userName, const char *userPassword,
        const IpEndpointName& privateEndpoint,
		const IpEndpointName& publicEndpoint,
        const char **groupNamesAndPasswords,
        UserStatus *userGroupsStatus, int groupCount )
{
    // find or create the user, aborting if the password for an existing
    // user is incorrect, or if the maximum number of users has been reached

    User *user = FindUser( userName );
    if( user ){
        if( user->password.compare( userPassword ) != 0 ){
            Log() << "attempt to update user '"
                    << userName << "' with incorrect password." << std::endl;
            return USER_STATUS_WRONG_PASSWORD;
        }
    }else{
        if( userCount_ == maxUsers_ ){
            Log() << "user limit reached, user '"
                    << userName << "' not admitted." << std::endl;
            return USER_STATUS_SERVER_LIMIT_REACHED;
        }else{
            user = CreateUser( userName, userPassword );
        }
    }

    UpdateEndpoint(
            user->privateEndpoint, privateEndpoint, userName, "private" );
    UpdateEndpoint( user->publicEndpoint, publicEndpoint, userName, "public" );

    user->lastAliveMessageArrivalTime = time(0);


    // previousButNotCurrentGroups begins containing all the groups the user
    // was in before the current message was received. We remove those which
    // the user is still a member of, leaving the set that the user is no
    // longer a member of. We then use the set to remove associations with
    // non-current groups.

    std::set<Group*> previousButNotCurrentGroups( user->groups_ );

    for( int i=0; i < groupCount; ++i ){
        const char *groupName = groupNamesAndPasswords[i*2];
        const char *groupPassword = groupNamesAndPasswords[i*2 + 1];

        Group *group = FindGroup( groupName );
        if( group ){
            if( user->IsMemberOf( group ) ){
                // check that previousButNotCurrentGroups contains group before
                // removing it. it won't if we were passed the same group
                // multiple times
                std::set<Group*>::iterator j =
                        previousButNotCurrentGroups.find( group );
                if( j != previousButNotCurrentGroups.end() )
                    previousButNotCurrentGroups.erase( j );

                userGroupsStatus[i] = USER_STATUS_OK;
            }else{
                // user isn't in group so join it
                if( group->password.compare( groupPassword ) == 0 ){
                    AssociateUserWithGroup( user, group );
                    userGroupsStatus[i] = USER_STATUS_OK;
                }else{                                   
                    userGroupsStatus[i] = USER_STATUS_WRONG_PASSWORD;
                }
            }
        }else{  // group doesn't exist
            if( groupCount_ == maxGroups_ ){
                Log() << "group limit reached, group '"
                        << groupName << "' not created." << std::endl;
                userGroupsStatus[i] = USER_STATUS_SERVER_LIMIT_REACHED;
            }else{
                group = CreateGroup( groupName, groupPassword );
                AssociateUserWithGroup( user, group );
                userGroupsStatus[i] = USER_STATUS_OK;
            }
        }
    }

    for( std::set<Group*>::iterator j = previousButNotCurrentGroups.begin();
            j != previousButNotCurrentGroups.end(); ++j ){

        SeparateUserFromGroup( user, *j );
    }

    return USER_STATUS_OK;
}