Bool16 IsAuthentic(QTSS_Filter_Params* inParams,StringParser *fullRequestPtr)
{
    Bool16 isAuthentic = false;

    if (!sAuthenticationEnabled) // no authentication
    {
        isAuthentic = true;
    }
    else // must authenticate
    {
        StrPtrLen theClientIPAddressStr;
        (void) QTSS_GetValuePtr(inParams->inRTSPSession, qtssRTSPSesRemoteAddrStr, 0, (void**)&theClientIPAddressStr.Ptr, &theClientIPAddressStr.Len);
        Bool16 isLocal =  IPComponentStr(&theClientIPAddressStr).IsLocal(); 
        
        StrPtrLen authenticateName;
        StrPtrLen authenticatePassword;
        StrPtrLen authType;
        Bool16 hasAuthentication = HasAuthentication(fullRequestPtr,&authenticateName,&authenticatePassword, &authType);               
        if (hasAuthentication) 
        {
            if (authType.Equal(sAuthRef))
            {    
                if (isLocal)
                    isAuthentic = OSXAuthenticate(&authenticatePassword);
            }
            else
                isAuthentic = Authenticate(inParams->inRTSPRequest, &authenticateName,&authenticatePassword);
       }
    }
//    if (isAuthentic)
//        isAuthentic = AuthorizeAdminRequest(inParams->inRTSPRequest);
    (void) QTSS_SetValue(inParams->inRTSPRequest, sAuthenticatedID, 0, (void*)&isAuthentic, sizeof(isAuthentic));

    return isAuthentic;
}
Exemple #2
0
    Return onRaw(NoString& line) override
    {
        if (No::token(line, 0).equals("AUTHENTICATE")) {
            Authenticate(No::tokens(line, 1));
        } else if (No::token(line, 1).equals("903")) {
            /* SASL success! */
            network()->ircSocket()->resumeCap();
            m_bAuthenticated = true;
            NO_DEBUG("sasl: Authenticated with mechanism [" << m_Mechanisms.GetCurrent() << "]");
        } else if (No::token(line, 1).equals("904") || No::token(line, 1).equals("905")) {
            NO_DEBUG("sasl: Mechanism [" << m_Mechanisms.GetCurrent() << "] failed.");
            putModule(m_Mechanisms.GetCurrent() + " mechanism failed.");

            if (m_Mechanisms.HasNext()) {
                m_Mechanisms.IncrementIndex();
                putIrc("AUTHENTICATE " + m_Mechanisms.GetCurrent());
            } else {
                CheckRequireAuth();
                network()->ircSocket()->resumeCap();
            }
        } else if (No::token(line, 1).equals("906")) {
            /* CAP wasn't paused? */
            NO_DEBUG("sasl: Reached 906.");
            CheckRequireAuth();
        } else if (No::token(line, 1).equals("907")) {
            m_bAuthenticated = true;
            network()->ircSocket()->resumeCap();
            NO_DEBUG("sasl: Received 907 -- We are already registered");
        } else {
            return Continue;
        }

        return Halt;
    }
Exemple #3
0
 EModRet OnRawMessage(CMessage& msg) override {
     if (msg.GetCommand().Equals("AUTHENTICATE")) {
         Authenticate(msg.GetParam(0));
         return HALT;
     }
     return CONTINUE;
 }
Exemple #4
0
BOOL CALLBACK dlgFunc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
{

	switch (msg)
	{

		case WM_INITDIALOG:
			return TRUE;
		break;

		case WM_COMMAND:

			switch(LOWORD(wp))
			{
				case IDOK:
					Authenticate(hwnd, def_password);
				break;

				case IDCANCEL:
					EndDialog(hwnd,1);
				break;

				default: break;
			}

		break;

	}

	return FALSE;
}
Exemple #5
0
	virtual EModRet OnRaw(CString &sLine) {
		if (sLine.Token(0).Equals("AUTHENTICATE")) {
			Authenticate(sLine.Token(1, true));
		} else if (sLine.Token(1).Equals("903")) {
			/* SASL success! */
			m_pNetwork->GetIRCSock()->ResumeCap();
			m_bAuthenticated = true;
			DEBUG("sasl: Authenticated with mechanism [" << m_Mechanisms.GetCurrent() << "]");
		} else if (sLine.Token(1).Equals("904") || sLine.Token(1).Equals("905")) {
			DEBUG("sasl: Mechanism [" << m_Mechanisms.GetCurrent() << "] failed.");
			PutModule(m_Mechanisms.GetCurrent() + " mechanism failed.");

			if (m_Mechanisms.HasNext()) {
				m_Mechanisms.IncrementIndex();
				PutIRC("AUTHENTICATE " + m_Mechanisms.GetCurrent());
			} else {
				CheckRequireAuth();
				m_pNetwork->GetIRCSock()->ResumeCap();
			}
		} else if (sLine.Token(1).Equals("906")) {
			/* CAP wasn't paused? */
			DEBUG("sasl: Reached 906.");
			CheckRequireAuth();
		} else if (sLine.Token(1).Equals("907")) {
			m_bAuthenticated = true;
			m_pNetwork->GetIRCSock()->ResumeCap();
			DEBUG("sasl: Received 907 -- We are already registered");
		} else {
			return CONTINUE;
		}

		return HALT;
	}
Exemple #6
0
const char* NntpConnection::Request(const char* req)
{
    if (!req)
    {
        return nullptr;
    }

    m_authError = false;

    WriteLine(req);

    char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr);

    if (!answer)
    {
        return nullptr;
    }

    if (!strncmp(answer, "480", 3))
    {
        debug("%s requested authorization", GetHost());

        if (!Authenticate())
        {
            return nullptr;
        }

        //try again
        WriteLine(req);
        answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr);
    }

    return answer;
}
Exemple #7
0
const char* NNTPConnection::Request(const char* req)
{
	if (!req)
	{
		return NULL;
	}

	m_bAuthError = false;

	WriteLine(req);

	char* answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL);

	if (!answer)
	{
		return NULL;
	}

	if (!strncmp(answer, "480", 3))
	{
		debug("%s requested authorization", GetHost());

		if (!Authenticate())
		{
			return NULL;
		}

		//try again
		WriteLine(req);
		answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL);
	}

	return answer;
}
Exemple #8
0
//////////////////////////////////////////////////////////////////
/// <summary>
/// Establishes a connection to a site.
/// </summary>
void MgSiteConnection::Open(MgUserInformation* userInformation)
{
    // We can not have null userInformation
    if (NULL == userInformation)
    {
        throw new MgAuthenticationFailedException(L"MgSiteConnection.Open", __LINE__, __WFILE__, NULL, L"", NULL);
    }

    m_connProp = NULL;

    // If none of them is valid, means we have a problem.
    if (!m_http && !m_isWebTier && !m_isServer && !m_isSiteServer)
    {
        MgStringCollection arguments;
        arguments.Add(NULL == m_config ?
            MgConfigProperties::DefaultConfigurationFilename :
            m_config->GetFileName());

        throw new MgConfigurationException(L"MgSiteConnection.Open",
            __LINE__, __WFILE__, &arguments, L"", NULL);
    }

    // Get the service IP address from the site server
    if (m_http)
    {
        // Connection property for HTTP request
         m_connProp = new MgConnectionProperties(userInformation, m_url);
    }
    // Site connection properties for local site
    // We need to first determine whether it is site server.
    else if (m_isSiteServer)
    {
        m_connProp = new MgConnectionProperties(userInformation, L"", 0);
    }
    // Site connection properties for web-tier or server-2-server interaction
    else if (m_isWebTier)
    {
        MgSiteManager* siteManager = MgSiteManager::GetInstance();
        m_connProp = siteManager->GetConnectionProperties(userInformation, MgSiteInfo::Client, true);
    }
    else if(m_isServer)
    {
        MgSiteManager* siteManager = MgSiteManager::GetInstance();
        m_connProp = siteManager->GetConnectionProperties(userInformation, MgSiteInfo::Client, false);
    }

    if (m_connProp == NULL)
    {
        // There might not be any MapGuide servers running for the site
        throw new MgConnectionFailedException(L"MgSiteConnection.Open",
            __LINE__, __WFILE__, NULL, L"", NULL);
    }

    if (!m_connProp->IsLocal())
    {
        Authenticate(userInformation);
    }
}
Exemple #9
0
long UserTable::CreateUser(string const& username, string const& password,
		long permissions, bool fullPayment, User& user) {
	if (username.empty() || password.empty())
		throw CREATE_USER_FAILURE;

	vector<string> values;

	values.push_back(username);
	values.push_back(password);
	values.push_back(Utilities::long_to_string(permissions));
	values.push_back(fullPayment ? "1" : "0");

	int id;
	long err;
	db_rows rows;

	//Check to see if the user exists in the database already
	string query = Db::Db::ParamertizedQuery(
			"SELECT * FROM user WHERE username=?", values);

	try {
		err = Db::Db::Select(query, rows);

		//At least one row should've been returned to represent the user
		if (rows.rows.size() > 0)
			throw CREATE_USER_FAILURE_USER_EXISTS;
	} catch (int) {
		throw CREATE_USER_FAILURE;
	}

	query =
			Db::Db::ParamertizedQuery(
					"INSERT INTO user(username,password,permissions,full_payment) VALUES (?,password(?),?,?)",
					values);

	try {
		err = Db::Db::Insert(query, id);
	} catch (int) {
		throw CREATE_USER_FAILURE;
	}

	//Make sure there was no error and that an ID was returned
	if (id < 1 || err != SUCCESS)
		throw CREATE_USER_FAILURE;

	try {
		//Get the new user object
		err = Authenticate(username, password, user);
	} catch (int) {
		throw CREATE_USER_FAILURE;
	}

	if (err != SUCCESS)
		throw CREATE_USER_FAILURE;

	return SUCCESS;
}
Exemple #10
0
int HTTPServerAuthenticate(HTTPSession *Session)
{
	int result=FALSE;

	//This handles someone clicking a 'logout' button
	if (! HTTPServerHandleRegister(Session, LOGIN_CHECK_ALLOWED))
	{
		LogToFile(Settings.LogPath,"AUTH: Forcing Relogin for  %s@%s (%s) %s %s",Session->ClientIP,Session->ClientHost,Session->ClientIP,Session->Method,Session->Path);
		return(FALSE);
	}


	if (Session->Flags & SESSION_AUTHENTICATED) 
	{
		if (strcmp(Session->UserName,Session->AuthenticatedUser)==0) 
		{
			LogToFile(Settings.LogPath,"AUTH: Session Keep-Alive active, reusing authentication for %s@%s (%s) %s %s",Session->ClientIP,Session->ClientHost,Session->ClientIP,Session->Method,Session->Path);
			return(TRUE);
		}
		else LogToFile(Settings.LogPath,"AUTH: ERROR: Session Keep-Alive active, but user has changed to %s@%s (%s) %s %s. Refusing authentication",Session->ClientIP,Session->ClientHost,Session->ClientIP,Session->Method,Session->Path);
	}



	//Consider AccessToken Authentication for this URL!
	if ((! (Session->Flags & SESSION_AUTHENTICATED)) && (Session->AuthFlags & FLAG_AUTH_ACCESS_TOKEN)) ParseAccessToken(Session);


	if (Session->AuthFlags & FLAG_AUTH_PRESENT)
	{
		//if this looks back-to-front it's because for some methods we only get the username
		//after we've completed authentication (e.g. it's taken from a cookie)

		//ANYTHING OTHER THAN TRUE FROM AUTHENTICATE MEANS IT FAILED
		if ((Authenticate(Session)==TRUE) && StrLen(Session->UserName)) result=TRUE;

		//If authentication provided any users settings, then apply those
		if (StrLen(Session->UserSettings)) ParseConfigItemList(Session->UserSettings);

		//The FLAG_SSL_CERT_REQUIRED flag might have been set by user settings
		//during authentication, so check it again here
		if (! HTTPServerCheckCertificate(Session, Session->S)) result=FALSE;

		if (result) HTTPServerHandleRegister(Session, LOGGED_IN);
		else HTTPServerHandleRegister(Session, LOGIN_FAIL);
	}

	if (result==TRUE) 
	{
		Session->AuthenticatedUser=CopyStr(Session->AuthenticatedUser,Session->UserName);
		Session->Flags |= SESSION_AUTHENTICATED;
	}

	return(result);
}
Exemple #11
0
bool CWebserverRequest::SendResponse()
{
	RewriteURL();		// Erst mal die URL umschreiben

	if( Client_Addr.find(IADDR_LOCAL)>0 ) // != local
	{
		if(!Authenticate()) // Jeder Aufruf muss geprueft werden
        		return false;
	}

	return SendFile(Path,Filename);
}
Exemple #12
0
void HandleGetNextRequest(req *r) {
	uint8_t i;
	tlv *oid;
	tree *t;
	req response;
	unsigned char nextoid[256];
	uint8_t nextlen = 0;
	tlv *auth;
	
	if (r == NULL) {
		return;
	}

	// basic authentication to make sure the community provided is even valid
	if (Authenticate(r, &auth) == AUTH_DENIED) {
		ErrCount++;
		return;
	}

	bzero(&response, sizeof(req));
	response.version = r->version;
	response.community = r->community;
	response.community_len = r->community_len;
	response.type = GET_RESPONSE;
	response.request_id = r->request_id;
	response.count = r->count;

	// handle each oid
	for (i = 0; i < r->count; i++) {
		oid = &(r->oid[i]);
		if ((t = FindNextOID(NULL, NULL, (unsigned char *)oid->value, oid->len, nextoid, &nextlen, r)) == NULL) {
			if (response.error == ERROR_NOERROR) {
				response.error = ERROR_NOTFOUND;
				response.error_index = i;
			}
			response.value[i].type = TYPE_NULL;
			response.value[i].len = 0;
			continue;
		}
		memcpy(oid->value, nextoid, nextlen);
		oid->len = nextlen;
		memcpy(&(response.oid[i]), oid, sizeof(tlv));
		response.value[i].type = t->data.type;
		response.value[i].len = t->data.len;
		response.value[i].value = t->data.value;
	}	

	SendResponse(&response);

}
Exemple #13
0
	void OnResult(SQLResult& res)
	{
		User* user = ServerInstance->FindNick(uid);
		if (user)
		{
			SQLEntries row;
			if (res.Rows() && res.GetRow(row) && Authenticate(row[0]))
			{
				pendingExt.set(user, AUTH_STATE_NONE);
			}
			else
			{
				pendingExt.set(user, AUTH_STATE_FAIL);
			}
		}
	}
QTSS_Error  QTSSDemoRedirectModuleDispatch(QTSS_Role inRole, QTSS_RoleParamPtr inParams)
{
   switch (inRole)
    {  
       case QTSS_Register_Role:
            return Register(&inParams->regParams);
        case QTSS_Initialize_Role:
            return Initialize(&inParams->initParams);
        case QTSS_RereadPrefs_Role:
            return RereadPrefs();
        case QTSS_RTSPAuthenticate_Role:
            return Authenticate(&inParams->rtspRequestParams);
        case QTSS_Shutdown_Role:
            return Shutdown();
    }
    return QTSS_NoErr;
}
Exemple #15
0
bool NNTPConnection::Connect()
{
	debug("Opening connection to %s", GetHost());

	if (m_eStatus == csConnected)
	{
		return true;
	}

	if (!Connection::Connect())
	{
		return false;
	}

	char* answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL);

	if (!answer)
	{
		ReportErrorAnswer("Connection to server%i (%s) failed: Connection closed by remote host", NULL);
		Disconnect();
		return false;
	}

	if (strncmp(answer, "2", 1))
	{
		ReportErrorAnswer("Connection to server%i (%s) failed (Answer: %s)", answer);
		Disconnect();
		return false;
	}

	if ((m_pNewsServer->GetUser() && strlen(m_pNewsServer->GetUser()) > 0 &&
		 m_pNewsServer->GetPassword() && strlen(m_pNewsServer->GetPassword()) > 0) &&
		!Authenticate())
	{
		return false;
	}

	debug("Connection to %s established", GetHost());

	return true;
}
Exemple #16
0
bool NntpConnection::Connect()
{
    debug("Opening connection to %s", GetHost());

    if (m_status == csConnected)
    {
        return true;
    }

    if (!Connection::Connect())
    {
        return false;
    }

    char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr);

    if (!answer)
    {
        ReportErrorAnswer("Connection to %s (%s) failed: Connection closed by remote host", nullptr);
        Disconnect();
        return false;
    }

    if (strncmp(answer, "2", 1))
    {
        ReportErrorAnswer("Connection to %s (%s) failed: %s", answer);
        Disconnect();
        return false;
    }

    if ((strlen(m_newsServer->GetUser()) > 0 && strlen(m_newsServer->GetPassword()) > 0) &&
            !Authenticate())
    {
        return false;
    }

    debug("Connection to %s established", GetHost());

    return true;
}
void WorldServerSocket::_HandleAuthSession(WorldPacket* recvPacket)
{
	std::string pname;
	uint32 unk2, mClientBuild;
	
	_latency = (uint32)time(NULL) - _latency;
	
	*recvPacket >> mClientBuild;
	*recvPacket >> unk2;
	*recvPacket >> pname;

	// Send out a request for this account.
	mRequestID = PID.GeneratePlayerId();//sLogonCommHandler.ClientConnected(account, this);
	
	if(mRequestID == 0xFFFFFFFF)
	{
		Disconnect();
		return;
	}

	// shitty hash !
	FullPlayerName = new string( pname );

	sLog.outDebug("Name of Player is %s, Player ID is %u, Client Build is %u", pname.c_str(), mRequestID, mClientBuild);

	// Set the authentication packet 
    pAuthenticationPacket = recvPacket;

	mSession = new PlayerSession(mRequestID, pname, this);

	Player* plr = new Player((uint64)mRequestID);
	ASSERT(plr);
	plr->SetSession(mSession);
	mSession->SetPlayer(plr);

	mSession->InitPlayer();
	Authenticate();
}
bool CPacketConn::RcvPacket()
{
	if (!m_Trusted) {	// if not authenticated yet
		m_Trusted = Authenticate();
		// if we're a client and connection was bogus, end receive loop
		// if we're a server, there could be new clients, so keep looping
		return(m_Trusted || m_Server);
	}
	PACKET_HDR	hdr;
	if (!TcpRead(&hdr, sizeof(hdr)))	// read header
		return(FALSE);
	UINT	PackLen = sizeof(hdr) + hdr.DataLen;
	// allocate packet on heap; recipient is responsible for deleting packet
	GENERIC_PACKET	*pp = (GENERIC_PACKET *)new BYTE[PackLen];
	if (hdr.DataLen) {
		if (!TcpRead(pp->Data, hdr.DataLen))	// read data
			return(FALSE);
	}
	PACKET_HDR	*pHdr = pp;	// upcast to base class
	*pHdr = hdr;
	PostMessage(m_hWnd, UWM_RCVPACKET, (WPARAM)pp, m_Cookie);	// post packet to window
	return(TRUE);
}
//----------------------------------------------------------------------------
//
void TelnetTCPClient::SocketReadyRead()
{
    //Keep adding to the command buffer
    QByteArray Data = Socket->readAll();
    CommandBuffer.append(Data);

    //Check to see if the CommandBuffer has a command
    if( ! CommandBuffer.endsWith('\n') )
    {
        return;
    }

    //Process the command

    if(!isAuthenticated)
    {
        //Authenticate the client
        if ( Authenticate(CommandBuffer) )
        {
            SendResponse(QString("success to login.") + strCR);
            SendResponse(strShell);
        }
        else
        {
            SendResponse("failed to login. enter password:");
        }

        CommandBuffer.clear();
        return;
    }

    DispatchCommand( CommandBuffer );
    CommandBuffer.clear();

    SendResponse( strShell );
}
void WorldSocket::InformationRetreiveCallback(WorldPacket & recvData, uint32 requestid)
{
	if(requestid != mRequestID)
		return;

	uint32 error;
	recvData >> error;

	if(error != 0)
	{
		// something happened wrong @ the logon server
		OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
		return;
	}

	// Extract account information from the packet.
	string AccountName;
	uint32 AccountID;
	string GMFlags;
	uint32 AccountFlags;

	recvData >> AccountID >> AccountName >> GMFlags >> AccountFlags;
	sLog.outDebug( " >> got information packet from logon: `%s` ID %u (request %u)", AccountName.c_str(), AccountID, mRequestID);
	//	sLog.outColor(TNORMAL, "\n");

	mRequestID = 0;
	// Pull the session key.
	uint8 K[40];
	recvData.read(K, 40);

	BigNumber BNK;
	BNK.SetBinary(K, 40);

	// Initialize crypto.
	_crypt.SetKey(K, 40);
	_crypt.Init();

	Session * session = sClientMgr.CreateSession(AccountID);
	if(session == NULL)
	{
		/* we are already logged in. send auth failed. (if anyone has a better error lemme know :P) */
		OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
		return;
	}

	m_session = session;
	session->m_socket = this;
    Sha1Hash sha;

	uint8 digest[20];
	pAuthenticationPacket->read(digest, 20);

	uint32 t = 0;
	sha.UpdateData(AccountName);
	sha.UpdateData((uint8 *)&t, 4);
	sha.UpdateData((uint8 *)&mClientSeed, 4);
	sha.UpdateData((uint8 *)&mSeed, 4);
	sha.UpdateBigNumbers(&BNK, NULL);
	sha.Finalize();

	if (memcmp(sha.GetDigest(), digest, 20))
	{
		// AUTH_UNKNOWN_ACCOUNT = 21
		OutPacket(SMSG_AUTH_RESPONSE, 1, "\x15");
		return;
	}

	// Allocate session
	m_session->m_accountFlags = AccountFlags;
	m_session->m_GMPermissions = GMFlags;
	m_session->m_accountId = AccountID;
	m_session->m_latency = _latency;
	m_session->m_accountName = AccountName;

	Log.Notice("Auth", "%s from %s:%u [%ums]", AccountName.c_str(), GetRemoteIP().c_str(), GetRemotePort(), _latency);
	Authenticate();
}
Exemple #21
0
/*
 * Simple "main" function for multiple platforms.
 *
 * Note the special "--" option which terminates the processing of
 * standard options.  All non-standard options (if any) are passed
 * directly to the "init_xxx()" function.
 */
int main(int argc, char *argv[])
{
	int i;

	bool done = FALSE;

	bool new_game = FALSE;

	int show_score = 0;

	cptr mstr = NULL;

	bool args = TRUE;


	/* Save the "program name" XXX XXX XXX */
	argv0 = argv[0];

#ifdef USE_286
	/* Attempt to use XMS (or EMS) memory for swap space */
	if (_OvrInitExt(0L, 0L))
	{
		_OvrInitEms(0, 0, 64);
	}
#endif


#ifdef SET_UID

	/* Default permissions on files */
	(void)umask(022);

# ifdef SECURE
	/* Authenticate */
	Authenticate();
# endif

#endif


	/* Get the file paths */
	init_stuff();


#ifdef SET_UID

	/* Get the user id (?) */
	player_uid = getuid();

#ifdef VMS
	/* Mega-Hack -- Factor group id */
	player_uid += (getgid() * 1000);
#endif

# ifdef SAFE_SETUID

#  ifdef _POSIX_SAVED_IDS

	/* Save some info for later */
	player_euid = geteuid();
	player_egid = getegid();

#  endif

#  if 0	/* XXX XXX XXX */

	/* Redundant setting necessary in case root is running the game */
	/* If not root or game not setuid the following two calls do nothing */

	if (setgid(getegid()) != 0)
	{
		quit("setgid(): cannot set permissions correctly!");
	}

	if (setuid(geteuid()) != 0)
	{
		quit("setuid(): cannot set permissions correctly!");
	}

#  endif

# endif

#endif


#ifdef SET_UID

	/* Initialize the "time" checker */
	if (check_time_init() || check_time())
	{
		quit("The gates to Angband are closed (bad time).");
	}

	/* Initialize the "load" checker */
	if (check_load_init() || check_load())
	{
		quit("The gates to Angband are closed (bad load).");
	}

	/* Acquire the "user name" as a default player name */
#ifdef ANGBAND_2_8_1
	user_name(player_name, player_uid);
#else /* ANGBAND_2_8_1 */
	user_name(op_ptr->full_name, player_uid);
#endif /* ANGBAND_2_8_1 */

#ifdef PRIVATE_USER_PATH

	/* Create a directory for the users files. */
	create_user_dir();

#endif /* PRIVATE_USER_PATH */

#endif /* SET_UID */


	/* Process the command line arguments */
	for (i = 1; args && (i < argc); i++)
	{
		/* Require proper options */
		if (argv[i][0] != '-') game_usage();

		/* Analyze option */
		switch (argv[i][1])
		{
			case 'N':
			case 'n':
			{
				new_game = TRUE;
				break;
			}

			case 'F':
			case 'f':
			{
				arg_fiddle = TRUE;
				break;
			}

			case 'W':
			case 'w':
			{
				arg_wizard = TRUE;
				break;
			}

			case 'V':
			case 'v':
			{
				arg_sound = TRUE;
				break;
			}

			case 'G':
			case 'g':
			{
				/* HACK - Graphics mode switches on the original tiles */
				arg_graphics = GRAPHICS_ORIGINAL;
				break;
			}

			case 'R':
			case 'r':
			{
				arg_force_roguelike = TRUE;
				break;
			}

			case 'O':
			case 'o':
			{
				arg_force_original = TRUE;
				break;
			}

			case 'S':
			case 's':
			{
				show_score = atoi(&argv[i][2]);
				if (show_score <= 0) show_score = 10;
				break;
			}

			case 'u':
			case 'U':
			{
				if (!argv[i][2]) game_usage();
#ifdef ANGBAND_2_8_1
				strncpy(player_name, &argv[i][2], 32);
				player_name[31] = '\0';
#else /* ANGBAND_2_8_1 */
				strncpy(op_ptr->full_name, &argv[i][2], 32);
				op_ptr->full_name[31] = '\0';
#endif /* ANGBAND_2_8_1 */
				break;
			}

			case 'm':
			{
				if (!argv[i][2]) game_usage();
				mstr = &argv[i][2];
				break;
			}

			case 'M':
			{
				arg_monochrome = TRUE;
				break;
			}

			case 'd':
			case 'D':
			{
				change_path(&argv[i][2]);
				break;
			}

			case '-':
			{
				argv[i] = argv[0];
				argc = argc - i;
				argv = argv + i;
				args = FALSE;
				break;
			}

			default:
			{
				 /* Default usage-help */
				 game_usage();
			}
		}
	}

	/* Hack -- Forget standard args */
	if (args)
	{
		argc = 1;
		argv[1] = NULL;
	}


	/* Process the player name */
	process_player_name(TRUE);



	/* Install "quit" hook */
	quit_aux = quit_hook;


	/* 
	 * Drop privs (so X11 will work correctly)
	 * unless we are running the Linux-SVGALib version.
	 *
	 * (In which case we initialize after safe_setuid_grab()
	 * is called.)
	 */
 
 	safe_setuid_drop();

#ifdef USE_XAW
	/* Attempt to use the "main-xaw.c" support */
	if (!done && (!mstr || (streq(mstr, "xaw"))))
	{
		if (0 == init_xaw(argc, argv))
		{
			ANGBAND_SYS = "xaw";
			done = TRUE;
		}
	}
#endif


#ifdef USE_X11
	/* Attempt to use the "main-x11.c" support */
	if (!done && (!mstr || (streq(mstr, "x11"))))
	{
		if (0 == init_x11(argc, argv))
		{
			ANGBAND_SYS = "x11";
			done = TRUE;
		}
	}
#endif


#ifdef USE_XPJ
	/* Attempt to use the "main-xpj.c" support */
	if (!done && (!mstr || (streq(mstr, "xpj"))))
	{
		if (0 == init_xpj(argc, argv))
		{
			ANGBAND_SYS = "xpj";
			done = TRUE;
		}
	}
#endif


#ifdef USE_GTK
	/* Attempt to use the "main-gtk.c" support */
	if (!done && (!mstr || (streq(mstr, "gtk"))))
	{
		if (0 == init_gtk((unsigned char*) &new_game, argc, argv))
		{
			done = TRUE;
		}
	}
#endif


#ifdef USE_GCU
	/* Attempt to use the "main-gcu.c" support */
	if (!done && (!mstr || (streq(mstr, "gcu"))))
	{
		if (0 == init_gcu())
		{
			ANGBAND_SYS = "gcu";
			done = TRUE;
		}
	}
#endif

#ifdef USE_CAP
	/* Attempt to use the "main-cap.c" support */
	if (!done && (!mstr || (streq(mstr, "cap"))))
	{
		if (0 == init_cap(argc, argv))
		{
			ANGBAND_SYS = "cap";
			done = TRUE;
		}
	}
#endif


#ifdef USE_DOS
	/* Attempt to use the "main-dos.c" support */
	if (!done && (!mstr || (streq(mstr, "dos"))))
	{
		if (0 == init_dos())
		{
			ANGBAND_SYS = "dos";
			done = TRUE;
		}
	}
#endif

#ifdef USE_IBM
	/* Attempt to use the "main-ibm.c" support */
	if (!done && (!mstr || (streq(mstr, "ibm"))))
	{
		if (0 == init_ibm())
		{
			ANGBAND_SYS = "ibm";
			done = TRUE;
		}
	}
#endif


#ifdef USE_EMX
	/* Attempt to use the "main-emx.c" support */
	if (!done && (!mstr || (streq(mstr, "emx"))))
	{
		if (0 == init_emx())
		{
			ANGBAND_SYS = "emx";
			done = TRUE;
		}
	}
#endif


#ifdef USE_SLA
	/* Attempt to use the "main-sla.c" support */
	if (!done && (!mstr || (streq(mstr, "sla"))))
	{
		if (0 == init_sla())
		{
			ANGBAND_SYS = "sla";
			done = TRUE;
		}
	}
#endif


#ifdef USE_AMI
	/* Attempt to use the "main-ami.c" support */
	if (!done && (!mstr || (streq(mstr, "ami"))))
	{
		if (0 == init_ami())
		{
			ANGBAND_SYS = "ami";
			done = TRUE;
		}
	}
#endif


#ifdef USE_VME
	/* Attempt to use the "main-vme.c" support */
	if (!done && (!mstr || (streq(mstr, "vme"))))
	{
		if (0 == init_vme())
		{
			ANGBAND_SYS = "vme";
			done = TRUE;
		}
	}
#endif

#ifdef USE_VCS
	/* Attempt to use the "main-vcs.c" support */
	if (!done && (!mstr || (streq(mstr, "vcs"))))
	{
		if (0 == init_vcs(argc, argv))
		{
			ANGBAND_SYS = "vcs";
			done = TRUE;
		}
	}
#endif /* USE_VCS */

	/* Grab privs (dropped above for X11) */
 	safe_setuid_grab();

#ifdef USE_LSL
	/* Attempt to use the "main-lsl.c" support */
	if (!done && (!mstr || (streq(mstr, "lsl"))))
	{
		if (0 == init_lsl())
		{
			ANGBAND_SYS = "lsl";
			done = TRUE;
		}
	}
#endif




	/* Make sure we have a display! */
	if (!done) quit("Unable to prepare any 'display module'!");


	/* Hack -- If requested, display scores and quit */
	if (show_score > 0) display_scores(0, show_score);

	/* Gtk initializes earlier */
	if (!streq(ANGBAND_SYS, "gtk"))
	{
		/* Catch nasty signals */
		signals_init();

		/* Initialize */
		init_angband();
	}
	
	/* Wait for response */
	pause_line(23);

	/* Play the game */
	play_game(new_game);

	/* Quit */
	quit(NULL);

	/* Exit */
	return (0);
}
bool BaseHTTPProtocol::ParseHeaders(IOBuffer& buffer) {
	//1. We have to have at least 4 bytes (double \r\n)
	if (GETAVAILABLEBYTESCOUNT(buffer) < 4) {
		return true;
	}

	//2. Detect the headers boundaries
	uint32_t headersSize = 0;
	bool markerFound = false;
	uint8_t *pBuffer = GETIBPOINTER(buffer);
	for (uint32_t i = 0; i <= GETAVAILABLEBYTESCOUNT(buffer) - 4; i++) {
		if ((pBuffer[i] == 0x0d)
				&& (pBuffer[i + 1] == 0x0a)
				&& (pBuffer[i + 2] == 0x0d)
				&& (pBuffer[i + 3] == 0x0a)) {
			markerFound = true;
			headersSize = i;
			break;
		}
		if (i >= HTTP_MAX_HEADERS_SIZE) {
			FATAL("Headers section too long");
			return false;
		}
	}

	//3. Are the boundaries correct?
	//Do we have enough data to parse the headers?
	if (headersSize == 0) {
		if (markerFound)
			return false;
		else
			return true;
	}

	//4. Get the raw headers and plit it into lines
	string rawHeaders = string((char *) GETIBPOINTER(buffer), headersSize);
	vector<string> lines;
	split(rawHeaders, "\r\n", lines);
	if (lines.size() == 0) {
		FATAL("Incorrect HTTP request");
		return false;
	}

	//4. Get the fisrt line and parse it. This is either a status code
	//for a previous request made by us, or the request that we just received
	if (!ParseFirstLine(lines[0], _headers[HTTP_FIRST_LINE])) {
		FATAL("Unable to parse the first line");
		return false;
	}

	//5. Consider the rest of the lines as key: value pairs and store them
	//0. Reset the headers
	_headers[HTTP_HEADERS].IsArray(false);
	for (uint32_t i = 1; i < lines.size(); i++) {
		string line = lines[i];
		string::size_type splitterPos = line.find(": ");

		if ((splitterPos == string::npos)
				|| (splitterPos == 0)
				|| (splitterPos == line.size() - 2)) {
			FATAL("Invalid header line");
			return false;
		}
		_headers[HTTP_HEADERS][line.substr(0, splitterPos)] = line.substr(splitterPos + 2, string::npos);
	}

	//6. default a transfer type to Content-Length: 0 if necessary
	if ((!_headers[HTTP_HEADERS].HasKey(HTTP_HEADERS_CONTENT_LENGTH, false)) &&
			(!_headers[HTTP_HEADERS].HasKey(HTTP_HEADERS_TRANSFER_ENCODING, false))) {
		_headers[HTTP_HEADERS][HTTP_HEADERS_CONTENT_LENGTH] = "0";
	}

	//7. read the transfer type and set this request or response flags
	if (_headers[HTTP_HEADERS].HasKey(HTTP_HEADERS_CONTENT_LENGTH, false)) {
		string contentLengthString = _headers[HTTP_HEADERS].GetValue(
				HTTP_HEADERS_CONTENT_LENGTH, false);
		replace(contentLengthString, " ", "");
		if (!isNumeric(contentLengthString)) {
			FATAL("Invalid HTTP headers:\n%s", STR(_headers.ToString()));
			return false;
		}
		_contentLength = atoi(STR(contentLengthString));
		_chunkedContent = false;
		_lastChunk = false;
	} else if (_headers[HTTP_HEADERS].HasKey(HTTP_HEADERS_TRANSFER_ENCODING, false)) {
		if (lowerCase(_headers[HTTP_HEADERS].GetValue(HTTP_HEADERS_TRANSFER_ENCODING, false)) !=
				lowerCase(HTTP_HEADERS_TRANSFER_ENCODING_CHUNKED)) {
			FATAL("The only supported %s is %s",
					HTTP_HEADERS_TRANSFER_ENCODING,
					HTTP_HEADERS_TRANSFER_ENCODING_CHUNKED);
			return false;
		}
		_chunkedContent = true;
		_lastChunk = false;
		_contentLength = 0;
	}

	//7. Advance the state and ignore the headers part from the buffer
	_state = HTTP_STATE_PAYLOAD;
	buffer.Ignore(headersSize + 4);

	return Authenticate();
}
Exemple #23
0
int main()
{
	printf("TODO Rename RackspaceConsole.\nAdd RackspaceServerManager, uses CloudClient to monitor load, reboot lost servers.\n");

#if OPEN_SSL_CLIENT_SUPPORT!=1
	printf("RakNet must be built with OPEN_SSL_CLIENT_SUPPORT");
	return 1;
#endif

	RakNet::Rackspace rackspaceApi;
	RakNet::TCPInterface tcpInterface;

	DisplayHTMLPage callback;
	rackspaceApi.AddEventCallback(&callback);

	tcpInterface.Start(0, 0, 1);

	if (!Authenticate(&rackspaceApi, &tcpInterface))
	{
		return 1;
	}
	//rackspaceApi.ListImages();

	PrintCommands();

	RakNet::SystemAddress systemAddress;
	RakNet::Packet *packet;
	while (1)
	{
		for (packet=tcpInterface.Receive(); packet; tcpInterface.DeallocatePacket(packet), packet=tcpInterface.Receive())
		{
			rackspaceApi.OnReceive(packet);
		}

		RakNet::SystemAddress lostConnectionAddress = tcpInterface.HasLostConnection();
		if (lostConnectionAddress!=RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			rackspaceApi.OnClosedConnection(lostConnectionAddress);

		if (kbhit())
		{
			printf("Command: ");

			char command[128];
			Gets(command, sizeof(command));

			if (stricmp(command,"Help")==0)
			{
				PrintCommands();
			}
			else if (stricmp(command,"Quit")==0)
			{
				break;
			}
			else if (stricmp(command,"Authenticate")==0)
			{
				Authenticate(&rackspaceApi, &tcpInterface);
			}
			else if (stricmp(command,"ListServers")==0)
			{
				rackspaceApi.ListServers();
			}
			else if (stricmp(command,"ListServersWithDetails")==0)
			{
				rackspaceApi.ListServersWithDetails();
			}
			else if (stricmp(command,"CreateServer")==0)
			{
				RakNet::RakString name;
				printf("Enter server name: ");
				Gets(command, sizeof(command));
				name=command;
				RakNet::RakString imageId;
				printf("Enter imageId: ");
				Gets(command, sizeof(command));
				imageId=command;
				RakNet::RakString flavorId;
				printf("Enter flavorId: ");
				Gets(command, sizeof(command));
				flavorId=command;

				rackspaceApi.CreateServer(name, imageId, flavorId);
			}
			else if (stricmp(command,"GetServerDetails")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetServerDetails(command);
			}
			else if (stricmp(command,"UpdateServerNameOrPassword")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString newName;
				printf("Enter newName: ");
				Gets(command, sizeof(command));
				newName=command;
				RakNet::RakString newPassword;
				printf("Enter newPassword: "******"DeleteServer")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.DeleteServer(command);
			}
			else if (stricmp(command,"ListServerAddresses")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.ListServerAddresses(command);
			}
			else if (stricmp(command,"ShareServerAddress")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString serverAddress;
				printf("Enter server serverAddress: ");
				Gets(command, sizeof(command));
				serverAddress=command;
				rackspaceApi.ShareServerAddress(serverId, serverAddress);
			}
			else if (stricmp(command,"DeleteServerAddress")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString serverAddress;
				printf("Enter server serverAddress: ");
				Gets(command, sizeof(command));
				serverAddress=command;
				rackspaceApi.DeleteServerAddress(serverId, serverAddress);
			}
			else if (stricmp(command,"RebootServer")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString rebootType;
				printf("Enter rebootType: ");
				Gets(command, sizeof(command));
				rebootType=command;
				rackspaceApi.RebootServer(serverId,rebootType);
			}
			else if (stricmp(command,"RebuildServer")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString imageId;
				printf("Enter imageId: ");
				Gets(command, sizeof(command));
				imageId=command;
				rackspaceApi.RebuildServer(serverId,imageId);
			}
			else if (stricmp(command,"ResizeServer")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString flavorId;
				printf("Enter flavorId: ");
				Gets(command, sizeof(command));
				flavorId=command;
				rackspaceApi.ResizeServer(serverId,flavorId);
			}
			else if (stricmp(command,"ConfirmResizedServer")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.ConfirmResizedServer(command);
			}
			else if (stricmp(command,"RevertResizedServer")==0)
			{
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				rackspaceApi.RevertResizedServer(command);
			}
			else if (stricmp(command,"ListFlavors")==0)
			{
				rackspaceApi.ListFlavors();
			}
			else if (stricmp(command,"GetFlavorDetails")==0)
			{
				printf("Enter flavor id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetFlavorDetails(command);
			}
			else if (stricmp(command,"ListImages")==0)
			{
				rackspaceApi.ListImages();
			}
			else if (stricmp(command,"CreateImage")==0)
			{
				RakNet::RakString serverId;
				printf("Enter server id: ");
				Gets(command, sizeof(command));
				serverId=command;
				RakNet::RakString imageName;
				printf("Enter imageName: ");
				Gets(command, sizeof(command));
				imageName=command;
				rackspaceApi.CreateImage(serverId,imageName);
			}
			else if (stricmp(command,"GetImageDetails")==0)
			{
				printf("Enter image id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetImageDetails(command);
			}
			else if (stricmp(command,"DeleteImage")==0)
			{
				printf("Enter image id: ");
				Gets(command, sizeof(command));
				rackspaceApi.DeleteImage(command);
			}
			else if (stricmp(command,"ListSharedIPGroups")==0)
			{
				rackspaceApi.ListSharedIPGroups();
			}
			else if (stricmp(command,"ListSharedIPGroupsWithDetails")==0)
			{
				rackspaceApi.ListSharedIPGroupsWithDetails();
			}
			else if (stricmp(command,"CreateSharedIPGroup")==0)
			{
				rackspaceApi.CreateSharedIPGroup("testSharedIPGroup","");
			}
			else if (stricmp(command,"GetSharedIPGroupDetails")==0)
			{
				printf("Enter group id: ");
				Gets(command, sizeof(command));
				rackspaceApi.GetSharedIPGroupDetails(command);
			}
			else if (stricmp(command,"DeleteSharedIPGroup")==0)
			{
				printf("Enter group id: ");
				Gets(command, sizeof(command));
				rackspaceApi.DeleteSharedIPGroup(command);
			}
			else
			{
				printf("Unknown command. Type 'help' for help.\n");
			}
		}

		RakSleep(30);
	}

	return 0;
}
Exemple #24
0
/*
 * Simple "main" function for multiple platforms.
 *
 * Note the special "--" option which terminates the processing of
 * standard options.  All non-standard options (if any) are passed
 * directly to the "init_xxx()" function.
 */
int main(int argc, char *argv[])
{
	int i;

	bool done = FALSE;

	bool new_game = FALSE;

	int show_score = 0;

	cptr mstr = NULL;

	bool args = TRUE;


	/* Save the "program name" XXX XXX XXX */
	argv0 = argv[0];

#ifdef USE_286
	/* Attempt to use XMS (or EMS) memory for swap space */
	if (_OvrInitExt(0L, 0L))
	{
		_OvrInitEms(0, 0, 64);
	}
#endif


#ifdef SET_UID

	/* Default permissions on files */
	(void)umask(022);

# ifdef SECURE
	/* Authenticate */
	Authenticate();
# endif

#endif


	/* Get the file paths */
	init_stuff();


#ifdef SET_UID

	/* Get the user id (?) */
	player_uid = getuid();

#ifdef VMS
	/* Mega-Hack -- Factor group id */
	player_uid += (getgid() * 1000);
#endif

# ifdef SAFE_SETUID

#  ifdef _POSIX_SAVED_IDS

	/* Save some info for later */
	player_euid = geteuid();
	player_egid = getegid();

#  endif

#  if 0	/* XXX XXX XXX */

	/* Redundant setting necessary in case root is running the game */
	/* If not root or game not setuid the following two calls do nothing */

	if (setgid(getegid()) != 0)
	{
		quit("setgid(): cannot set permissions correctly!");
	}

	if (setuid(geteuid()) != 0)
	{
		quit("setuid(): cannot set permissions correctly!");
	}

#  endif

# endif

#endif


	/* Drop permissions */
	safe_setuid_drop();


#ifdef SET_UID

	/* Initialize the "time" checker */
	if (check_time_init() || check_time())
	{
		quit("The gates to Angband are closed (bad time).");
	}

	/* Initialize the "load" checker */
	if (check_load_init() || check_load())
	{
		quit("The gates to Angband are closed (bad load).");
	}

	/* Acquire the "user name" as a default player name */
	user_name(player_name, player_uid);

#ifdef PRIVATE_USER_PATH

	/* Create a directory for the users files. */
	create_user_dir();

#endif /* PRIVATE_USER_PATH */

#endif /* SET_UID */


	/* Process the command line arguments */
	for (i = 1; args && (i < argc); i++)
	{
		/* Require proper options */
		if (argv[i][0] != '-') goto usage;

		/* Analyze option */
		switch (argv[i][1])
		{
			case 'N':
			case 'n':
			{
				new_game = TRUE;
				break;
			}

			case 'F':
			case 'f':
			{
				arg_fiddle = TRUE;
				break;
			}

			case 'W':
			case 'w':
			{
				arg_wizard = TRUE;
				break;
			}

			case 'V':
			case 'v':
			{
				arg_sound = TRUE;
				break;
			}

			case 'G':
			case 'g':
			{
				/* HACK - Graphics mode switches on the original tiles */
				arg_graphics = GRAPHICS_ORIGINAL;
				break;
			}

			case 'R':
			case 'r':
			{
				arg_force_roguelike = TRUE;
				break;
			}

			case 'O':
			case 'o':
			{
				arg_force_original = TRUE;
				break;
			}

			case 'S':
			case 's':
			{
				show_score = atoi(&argv[i][2]);
				if (show_score <= 0) show_score = 10;
				break;
			}

			case 'u':
			case 'U':
			{
				if (!argv[i][2]) goto usage;
				strcpy(player_name, &argv[i][2]);
				break;
			}

			case 'm':
			{
				if (!argv[i][2]) goto usage;
				mstr = &argv[i][2];
				break;
			}

			case 'M':
			{
				arg_monochrome = TRUE;
				break;
			}

			case 'd':
			case 'D':
			{
				change_path(&argv[i][2]);
				break;
			}


			case '-':
			{
				argv[i] = argv[0];
				argc = argc - i;
				argv = argv + i;
				args = FALSE;
				break;
			}

			default:
			usage:
			{
				/* Dump usage information */
				puts("Usage: angband [options] [-- subopts]");
				puts("  -n       Start a new character");
				puts("  -f       Request fiddle mode");
				puts("  -w       Request wizard mode");
				puts("  -v       Request sound mode");
				puts("  -g       Request graphics mode");
				puts("  -o       Request original keyset");
				puts("  -r       Request rogue-like keyset");
				puts("  -M       Request monochrome mode");
				puts("  -s<num>  Show <num> high scores");
				puts("  -u<who>  Use your <who> savefile");
				puts("  -m<sys>  Force 'main-<sys>.c' usage");
				puts("  -d<def>  Define a 'lib' dir sub-path");
				puts("");

#ifdef USE_SDL
				puts("  -msdl    To use SDL");
#endif /* USE_SDL */

#ifdef USE_X11
				puts("  -mx11    To use X11");
				puts("  --       Sub options");
				puts("  -- -d    Set display name");
				puts("  -- -o    Request old 8x8 tile graphics");
				puts("  -- -a    Request Adam Bolt 16x16 tile graphics");
				puts("  -- -b    Request Bigtile graphics mode");
				puts("  -- -s    Turn off smoothscaling graphics");
				puts("  -- -n#   Number of terms to use");
				puts("");
#endif /* USE_X11 */

#ifdef USE_GCU
				puts("  -mgcu    To use GCU (GNU Curses)");
#endif /* USE_GCU */

#ifdef USE_CAP
				puts("  -mcap    To use CAP (\"Termcap\" calls)");
#endif /* USE_CAP */

#ifdef USE_DOS
				puts("  -mdos    To use DOS (Graphics)");
#endif /* USE_DOS */

#ifdef USE_IBM
				puts("  -mibm    To use IBM (BIOS text mode)");
#endif /* USE_IBM */

#ifdef USE_SLA
				puts("  -msla    To use SLA (SLANG)");
#endif /* USE_SLA */

#ifdef USE_LSL
				puts("  -mlsl    To use LSL (Linux-SVGALIB)");
#endif /* USE_LSL */

#ifdef USE_AMI
				puts("  -mami    To use AMI (Amiga)");
#endif /* USE_AMI */

#ifdef USE_VME
				puts("  -mvme    To use VME (VAX/ESA)");
#endif /* USE_VME */

				/* Actually abort the process */
				quit(NULL);
			}
		}
	}

	/* Hack -- Forget standard args */
	if (args)
	{
		argc = 1;
		argv[1] = NULL;
	}


	/* Process the player name */
	process_player_name(TRUE);

	/* Create any missing directories */
	create_needed_dirs();

	/* Install "quit" hook */
	quit_aux = quit_hook;



#ifdef USE_XAW
	/* Attempt to use the "main-xaw.c" support */
	if (!done && (!mstr || (streq(mstr, "xaw"))))
	{
		extern errr init_xaw(int, char**);
		if (0 == init_xaw(argc, argv))
		{
			ANGBAND_SYS = "xaw";
			done = TRUE;
		}
	}
#endif

#ifdef USE_SDL
	/* Attempt to use the "main-sdl.c" support */
	if (!done && (!mstr || (streq(mstr, "sdl"))))
	{
		extern errr init_sdl(int, char**);
		if (0 == init_sdl(argc, argv))
		{
			ANGBAND_SYS = "sdl";
			done = TRUE;
		}
	}
#endif

#ifdef USE_X11
	/* Attempt to use the "main-x11.c" support */
	if (!done && (!mstr || (streq(mstr, "x11"))))
	{
		extern errr init_x11(int, char**);
		if (0 == init_x11(argc, argv))
		{
			ANGBAND_SYS = "x11";
			done = TRUE;
		}
	}
#endif

#ifdef USE_GCU
	/* Attempt to use the "main-gcu.c" support */
	if (!done && (!mstr || (streq(mstr, "gcu"))))
	{
		extern errr init_gcu(int, char**);
		if (0 == init_gcu(argc, argv))
		{
			ANGBAND_SYS = "gcu";
			done = TRUE;
		}
	}
#endif

#ifdef USE_CAP
	/* Attempt to use the "main-cap.c" support */
	if (!done && (!mstr || (streq(mstr, "cap"))))
	{
		extern errr init_cap(int, char**);
		if (0 == init_cap(argc, argv))
		{
			ANGBAND_SYS = "cap";
			done = TRUE;
		}
	}
#endif


#ifdef USE_DOS
	/* Attempt to use the "main-dos.c" support */
	if (!done && (!mstr || (streq(mstr, "dos"))))
	{
		extern errr init_dos(void);
		if (0 == init_dos())
		{
			ANGBAND_SYS = "dos";
			done = TRUE;
		}
	}
#endif

#ifdef USE_IBM
	/* Attempt to use the "main-ibm.c" support */
	if (!done && (!mstr || (streq(mstr, "ibm"))))
	{
		extern errr init_ibm(void);
		if (0 == init_ibm())
		{
			ANGBAND_SYS = "ibm";
			done = TRUE;
		}
	}
#endif


#ifdef USE_EMX
	/* Attempt to use the "main-emx.c" support */
	if (!done && (!mstr || (streq(mstr, "emx"))))
	{
		extern errr init_emx(void);
		if (0 == init_emx())
		{
			ANGBAND_SYS = "emx";
			done = TRUE;
		}
	}
#endif


#ifdef USE_SLA
	/* Attempt to use the "main-sla.c" support */
	if (!done && (!mstr || (streq(mstr, "sla"))))
	{
		extern errr init_sla(void);
		if (0 == init_sla())
		{
			ANGBAND_SYS = "sla";
			done = TRUE;
		}
	}
#endif


#ifdef USE_LSL
	/* Attempt to use the "main-lsl.c" support */
	if (!done && (!mstr || (streq(mstr, "lsl"))))
	{
		extern errr init_lsl(void);
		if (0 == init_lsl())
		{
			ANGBAND_SYS = "lsl";
			done = TRUE;
		}
	}
#endif


#ifdef USE_AMI
	/* Attempt to use the "main-ami.c" support */
	if (!done && (!mstr || (streq(mstr, "ami"))))
	{
		extern errr init_ami(void);
		if (0 == init_ami())
		{
			ANGBAND_SYS = "ami";
			done = TRUE;
		}
	}
#endif


#ifdef USE_VME
	/* Attempt to use the "main-vme.c" support */
	if (!done && (!mstr || (streq(mstr, "vme"))))
	{
		extern errr init_vme(void);
		if (0 == init_vme())
		{
			ANGBAND_SYS = "vme";
			done = TRUE;
		}
	}
#endif


	/* Make sure we have a display! */
	if (!done) quit("Unable to prepare any 'display module'!");


	/* Hack -- If requested, display scores and quit */
	if (show_score > 0) display_scores(0, show_score);


	/* Catch nasty signals */
	signals_init();

	/* Initialize */
	init_angband();

	/* Wait for response */
	pause_line(23);

	/* Play the game */
	play_game(new_game);

	/* Quit */
	quit(NULL);

	/* Exit */
	return (0);
}
Exemple #25
0
void HandleGetRequest(req *r) {
	uint8_t i;
	tlv *oid;
	tree *t;
	req response;
	tlv *auth;
	
	if (r == NULL) {
		return;
	}

	// basic authentication to make sure the community provided is even valid
	if (Authenticate(r, &auth) == AUTH_DENIED) {
		ErrCount++;
		return;
	}

	bzero(&response, sizeof(req));
	response.version = r->version;
	response.community = r->community;
	response.community_len = r->community_len;
	response.type = GET_RESPONSE;
	response.request_id = r->request_id;
	response.count = r->count;

	// handle each oid
	for (i = 0; i < r->count; i++) {
		oid = &(r->oid[i]);
		memcpy(&(response.oid[i]), oid, sizeof(tlv));
		if ((t = FindOID((unsigned char *)oid->value, oid->len)) == NULL) {
			if (response.error == ERROR_NOERROR) {
				response.error = ERROR_NOTFOUND;
				response.error_index = i;
			}
			response.value[i].type = TYPE_NULL;
			response.value[i].len = 0;
			continue;
		}
		// found the OID, but check its type
		if (t->data.type == 0) {
			// invalid
			if (response.error == ERROR_NOERROR) {
				response.error = ERROR_NOTFOUND;
				response.error_index = i;
			}
			response.value[i].type = TYPE_NULL;
			response.value[i].len = 0;
			continue;
		} else {
			// see if the requesting client is authorized for this tlv
			if (t->auth) {
				if (r->community_len != t->auth->len || memcmp(r->community, t->auth->value, t->auth->len) != 0) {
					ErrCount++;
					// invalid community, access denied
					if (response.error == ERROR_NOERROR) {
						response.error = ERROR_NOTFOUND;
						response.error_index = i;
					}
					response.value[i].type = TYPE_NULL;
					response.value[i].len = 0;
					continue;
				}
			}
			
			response.value[i].type = t->data.type;
			// BUG allowing reads past object's length
			response.value[i].len = (t->data.len > r->value[i].len) ? t->data.len : r->value[i].len;
			response.value[i].value = t->data.value;
		}
	}	

	SendResponse(&response);

}
Exemple #26
0
void HandleSetRequest(req *r) {
	uint8_t i;
	tlv *oid;
	tree *t;
	req response;
	uint32_t val;
	tlv *auth;
	
	if (r == NULL) {
		return;
	}

	// basic authentication to make sure the community provided is even valid
	if (Authenticate(r, &auth) != AUTH_WRITE) {
		ErrCount++;
		return;
	}

	bzero(&response, sizeof(req));
	response.version = r->version;
	response.community = r->community;
	response.community_len = r->community_len;
	response.type = GET_RESPONSE;
	response.request_id = r->request_id;
	response.count = r->count;

	// handle each oid
	for (i = 0; i < r->count; i++) {
		oid = &(r->oid[i]);
		memcpy(&(response.oid[i]), oid, sizeof(tlv));
		if ((t = FindOID((unsigned char *)oid->value, oid->len)) == NULL) {
			// only allow a few SETs per connection that create new objects
			if (SetCount < MAX_SET_PER_SESSION) {
				SetCount++;
				if (CreateNewOID(&response, i, r, auth) == 0) {
					continue;
				}
			}
			if (response.error == ERROR_NOERROR) {
				response.error = ERROR_NOTFOUND;
				response.error_index = i;
			}
			response.value[i].type = TYPE_NULL;
			response.value[i].len = 0;
			response.value[i].value = r->value[i].value;
			continue;
		}
		// see if the requesting client is authorized for this OID
		if (t->auth) {
			if (r->community_len != t->auth->len || memcmp(r->community, t->auth->value, t->auth->len) != 0) {
				ErrCount++;
				// invalid community, access denied
				if (response.error == ERROR_NOERROR) {
					response.error = ERROR_NOTFOUND;
					response.error_index = i;
				}
				response.value[i].type = TYPE_NULL;
				response.value[i].len = 0;
				continue;
			}
		}
		// found the OID, but check that its type matches the request
		if (t->data.type != r->value[i].type) {
			// invalid
			if (response.error == ERROR_NOERROR) {
				response.error = ERROR_BADTYPE;
				response.error_index = i;
			}
			response.value[i].type = r->value[i].type;
			response.value[i].len = r->value[i].len;
			response.value[i].value = r->value[i].value;
			continue;
		}

		// found the OID, but check that the value is within limits
		if (t->data.type == TYPE_INTEGER) {
			if (t->data.len != r->value[i].len) {
				// invalid
				if (response.error == ERROR_NOERROR) {
					response.error = ERROR_TOOLARGE;
					response.error_index = i;
				}
				response.value[i].type = r->value[i].type;
				response.value[i].len = r->value[i].len;
				response.value[i].value = r->value[i].value;
				continue;
			}
			// otherwise, update the object
			memcpy(t->data.value, r->value[i].value, r->value[i].len);
			// fix any endienness issues
			if (r->value[i].len == 4) {
				*((uint32_t *)t->data.value) = htonl(*((uint32_t *)(t->data.value)));
			} else if (r->value[i].len == 2) {
				*((uint16_t *)t->data.value) = htonl(*((uint16_t *)(t->data.value)));
			} 

		} else if (t->data.type == TYPE_OCTETSTRING || t->data.type == TYPE_OID || t->data.type == TYPE_SEQUENCE) {
			if (r->value[i].len > 256) {
				// invalid
				if (response.error == ERROR_NOERROR) {
					response.error = ERROR_TOOLARGE;
					response.error_index = i;
				}
				response.value[i].type = r->value[i].type;
				response.value[i].len = r->value[i].len;
				continue;
			}
			// otherwise, update the object
			// first free the current data

/*			Leaving this out is a BUG
			if (t->data.len != r->value[i].len) {
				if (t->data.value != NULL) {
					free(t->data.value);
				}
				if ((t->data.value = calloc(1, r->value[i].len)) == NULL) {
					exit(-1);
				}
				t->data.len = r->value[i].len;
			}
*/
			memcpy(t->data.value, r->value[i].value, r->value[i].len);
			
		} else if (t->data.type == TYPE_NULL) {
			if (oid->len > 0) {
				// invalid
				if (response.error == ERROR_NOERROR) {
					response.error = ERROR_TOOLARGE;
					response.error_index = i;
				}
				response.value[i].type = oid->type;
				response.value[i].len = oid->len;
				continue;
			}
			// nothing to do since null values are already null
		}

	
		response.value[i].type = t->data.type;
		response.value[i].len = t->data.len;
		response.value[i].value = t->data.value;
	}	

	SendResponse(&response);

}
Exemple #27
0
void WorldSocket::InformationRetreiveCallback(WorldPacket & recvData, uint32 requestid)
{
    if(requestid != mRequestID)
        return;

    uint32 error;
    recvData >> error;

    if(error != 0)
    {
        // something happened wrong @ the logon server
        OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
        printf("Information callback returns failure.\n");
        return;
    }

    // Extract account information from the packet.
    string AccountName;
    uint32 AccountID;
    string GMFlags;
    uint8 AccountFlags;

    recvData >> AccountID >> AccountName >> GMFlags >> AccountFlags;
    printf( " >> got information packet from logon: `%s` ID %u (request %u)", AccountName.c_str(), AccountID, mRequestID);
    //	sLog.outColor(TNORMAL, "\n");

    mRequestID = 0;
    //Pull the session key.

    recvData.read(K, 40);

    _crypt.Init(K);

    BigNumber BNK;
    BNK.SetBinary(K, 40);

    //checking if player is already connected
    //disconnect current player and login this one(blizzlike)

    string lang = "enUS";
    if(recvData.rpos() != recvData.wpos())
        recvData.read((uint8*)lang.data(), 4);

    Session * session = sClientMgr.CreateSession(AccountID);
    if(session == NULL)
    {
        /* we are already logged in. send auth failed. (if anyone has a better error lemme know :P) */
        OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
        printf("Duplicate client error.\n");
        return;
    }

    m_session = session;
    session->m_socket = this;
    Sha1Hash sha;

    uint8 digest[20];
    pAuthenticationPacket->read(digest, 20);

    uint32 t = 0;
    if( m_fullAccountName == NULL )				// should never happen !
        sha.UpdateData(AccountName);
    else
    {
        sha.UpdateData(*m_fullAccountName);

        // this is unused now. we may as well free up the memory.
        delete m_fullAccountName;
        m_fullAccountName = NULL;
    }

    sha.UpdateData((uint8 *)&t, 4);
    sha.UpdateData((uint8 *)&mClientSeed, 4);
    sha.UpdateData((uint8 *)&mSeed, 4);
    sha.UpdateBigNumbers(&BNK, NULL);
    sha.Finalize();

    if (memcmp(sha.GetDigest(), digest, 20))
    {
        // AUTH_UNKNOWN_ACCOUNT = 21
        OutPacket(SMSG_AUTH_RESPONSE, 1, "\x15");
        return;
    }

    //_crypt.Init(digest);

    // Allocate session
    m_session->m_accountFlags = AccountFlags;
    m_session->m_GMPermissions = GMFlags;
    m_session->m_accountId = AccountID;
    m_session->m_latency = _latency;
    m_session->m_accountName = AccountName;
    m_session->m_ClientBuild = mClientBuild;

    Log.Notice("Auth", "%s from %s:%u [%ums]", AccountName.c_str(), GetRemoteIP().c_str(), GetRemotePort(), _latency);
    Authenticate();
}
Exemple #28
0
void WorldSocket::InformationRetreiveCallback(WorldPacket & recvData, uint32 requestid)
{
	if(requestid != mRequestID)
		return;

	uint32 error;
	recvData >> error;

	if(error != 0 || pAuthenticationPacket == NULL)
	{
		// something happened wrong @ the logon server
		OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
		return;
	}

	// Extract account information from the packet.
	string AccountName;
	const string * ForcedPermissions;
	uint32 AccountID;
	string GMFlags;
	uint8 AccountFlags;
	string lang = "enUS";
	uint32 i;

	recvData >> AccountID >> AccountName >> GMFlags >> AccountFlags;
	ForcedPermissions = sLogonCommHandler.GetForcedPermissions(AccountName);
	if( ForcedPermissions != NULL )
		GMFlags.assign(ForcedPermissions->c_str());

	DEBUG_LOG( "WorldSocket","Received information packet from logon: `%s` ID %u (request %u)", AccountName.c_str(), AccountID, mRequestID);

	mRequestID = 0;
	// Pull the session key.

	BigNumber BNK;
	recvData.read(K, 40);
	_crypt.Init(K);
	BNK.SetBinary(K, 40);

	//checking if player is already connected
	//disconnect current player and login this one(blizzlike)

	if(recvData.rpos() != recvData.wpos())
		recvData.read((uint8*)lang.data(), 4);

	WorldSession *session = NULL;
	session = sWorld.FindSession( AccountID );
	if( session != NULL )
	{
		if(session->_player != NULL && session->_player->GetMapMgr() == NULL)
		{
			DEBUG_LOG("WorldSocket","_player found without m_mapmgr during logon, trying to remove him [player %s, map %d, instance %d].", session->_player->GetName(), session->_player->GetMapId(), session->_player->GetInstanceID() );
			if(objmgr.GetPlayer(session->_player->GetLowGUID()))
				objmgr.RemovePlayer(session->_player);
			session->LogoutPlayer(false);
		}
		// AUTH_FAILED = 0x0D
		session->Disconnect();

		// clear the logout timer so he times out straight away
		session->SetLogoutTimer(1);

		// we must send authentication failed here.
		// the stupid newb can relog his client.
		// otherwise accounts dupe up and disasters happen.
		OutPacket(SMSG_AUTH_RESPONSE, 1, "\x15");
		return;
	}

	Sha1Hash sha;

	uint8 digest[20];
	pAuthenticationPacket->read(digest, 20);

	uint32 t = 0;
	if( m_fullAccountName == NULL )				// should never happen !
		sha.UpdateData(AccountName);
	else
	{
		sha.UpdateData(*m_fullAccountName);
		
		// this is unused now. we may as well free up the memory.
		delete m_fullAccountName;
		m_fullAccountName = NULL;
	}

	sha.UpdateData((uint8 *)&t, 4);
	sha.UpdateData((uint8 *)&mClientSeed, 4);
	sha.UpdateData((uint8 *)&mSeed, 4);
	sha.UpdateBigNumbers(&BNK, NULL);
	sha.Finalize();

	if (memcmp(sha.GetDigest(), digest, 20))
	{
		// AUTH_UNKNOWN_ACCOUNT = 21
		OutPacket(SMSG_AUTH_RESPONSE, 1, "\x15");
		return;
	}

	// Allocate session
	WorldSession * pSession = new WorldSession(AccountID, AccountName, this);
	mSession = pSession;
	ASSERT(mSession);
	pSession->deleteMutex.Acquire();

	// Set session properties
	pSession->permissioncount = 0; // just to make sure it's 0
	pSession->SetClientBuild(mClientBuild);
	pSession->LoadSecurity(GMFlags);
	pSession->SetAccountFlags(AccountFlags);
	pSession->m_lastPing = (uint32)UNIXTIME;

	if(recvData.rpos() != recvData.wpos())
		recvData >> pSession->m_muted;

	for(uint32 i = 0; i < 8; i++)
		pSession->SetAccountData(i, NULL, true, 0);

	if(sWorld.m_useAccountData)
	{
		QueryResult * pResult = CharacterDatabase.Query("SELECT * FROM account_data WHERE acct = %u", AccountID);
		if( pResult == NULL )
			CharacterDatabase.Execute("INSERT INTO account_data VALUES(%u, '', '', '', '', '', '', '', '', '')", AccountID);
		else
		{
			char * d;
			size_t len;
			const char * data;
			for(i = 0; i < 8; i++)
			{
				data = pResult->Fetch()[1+i].GetString();
				len = data ? strlen(data) : 0;
				if(len > 1)
				{
					d = new char[len+1];
					memcpy(d, data, len+1);
					pSession->SetAccountData(i, d, true, (uint32)len);
				}
			}

			delete pResult;
		}
	}

	DEBUG_LOG("Auth", "%s from %s:%u [%ums]", AccountName.c_str(), GetRemoteIP().c_str(), GetRemotePort(), _latency);
#ifdef SESSION_CAP
	if( sWorld.GetSessionCount() >= SESSION_CAP )
	{
		OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
		Disconnect();
		return;
	}
#endif

	// Check for queue.
	if( (sWorld.GetSessionCount() < sWorld.GetPlayerLimit()) || pSession->HasGMPermissions() ) 
		Authenticate();
	else
	{
		// Queued, sucker.
		uint32 Position = sWorld.AddQueuedSocket(this);
		mQueued = true;
		DEBUG_LOG("Queue", "%s added to queue in position %u", AccountName.c_str(), Position);

		// Send packet so we know what we're doing
		UpdateQueuePosition(Position);
	}

	pSession->deleteMutex.Release();
}
Exemple #29
0
bool UsernameToken::Authenticate(std::istream& password,std::string& derived_key) {
  //Get the original password for this user
  std::string passwd_text = get_password_from_file(password, username_);
  //std::cout<<"Password get from local file -----"<<passwd_text<<std::endl;
  return Authenticate(passwd_text,derived_key);
}
void WorldSocket::InformationRetreiveCallback(WorldPacket & recvData, uint32 requestid)
{
    if(requestid != mRequestID)
        return;

    uint32 error;
    recvData >> error;

    if(error != 0 || pAuthenticationPacket == NULL)
    {
        // something happened wrong @ the logon server
        OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
        return;
    }

    // Extract account information from the packet.
    string AccountName;
    const string * ForcedPermissions;
    uint32 AccountID;
    string GMFlags;
    uint8 AccountFlags;
    string lang = "enUS";
    uint32 i;

    recvData >> AccountID >> AccountName >> GMFlags >> AccountFlags;
    ForcedPermissions = sLogonCommHandler.GetForcedPermissions(AccountName);
    if( ForcedPermissions != NULL )
        GMFlags.assign(ForcedPermissions->c_str());

    sLog.outDebug( " >> got information packet from logon: `%s` ID %u (request %u)", AccountName.c_str(), AccountID, mRequestID);
//	sLog.outColor(TNORMAL, "\n");

    mRequestID = 0;
    // Pull the session key.
    uint8 K[40];
    recvData.read(K, 40);

    BigNumber BNK;
    BNK.SetBinary(K, 40);

    uint8 *key = new uint8[20];
    WowCrypt::GenerateKey(key, K);

    // Initialize crypto.
    _crypt.SetKey(key, 20);
    _crypt.Init();
    delete [] key;

    //checking if player is already connected
    //disconnect corrent player and login this one(blizzlike)

    if(recvData.rpos() != recvData.wpos())
        recvData.read((uint8*)lang.data(), 4);

    WorldSession *session = sWorld.FindSession( AccountID );
    if( session)
    {
        // AUTH_FAILED = 0x0D
        session->Disconnect();

        // clear the logout timer so he times out straight away
        session->SetLogoutTimer(1);

        // we must send authentication failed here.
        // the stupid newb can relog his client.
        // otherwise accounts dupe up and disasters happen.
        OutPacket(SMSG_AUTH_RESPONSE, 1, "\x15");
        return;
    }

    Sha1Hash sha;

    uint8 digest[20];
    pAuthenticationPacket->read(digest, 20);

    uint32 t = 0;
    if( m_fullAccountName == NULL )				// should never happen !
        sha.UpdateData(AccountName);
    else
    {
        sha.UpdateData(*m_fullAccountName);

        // this is unused now. we may as well free up the memory.
        delete m_fullAccountName;
        m_fullAccountName = NULL;
    }

    sha.UpdateData((uint8 *)&t, 4);
    sha.UpdateData((uint8 *)&mClientSeed, 4);
    sha.UpdateData((uint8 *)&mSeed, 4);
    sha.UpdateBigNumbers(&BNK, NULL);
    sha.Finalize();

    if (memcmp(sha.GetDigest(), digest, 20))
    {
        // AUTH_UNKNOWN_ACCOUNT = 21
        OutPacket(SMSG_AUTH_RESPONSE, 1, "\x15");
        return;
    }

    // Allocate session
    WorldSession * pSession = new WorldSession(AccountID, AccountName, this);
    mSession = pSession;
    ASSERT(mSession);
    pSession->deleteMutex.Acquire();

    // Set session properties
    pSession->SetClientBuild(mClientBuild);
    pSession->LoadSecurity(GMFlags);
    pSession->SetAccountFlags(AccountFlags);
    pSession->m_lastPing = (uint32)UNIXTIME;
    pSession->language = sLocalizationMgr.GetLanguageId(lang);

    if(recvData.rpos() != recvData.wpos())
        recvData >> pSession->m_muted;

    for(uint32 i = 0; i < 8; ++i)
        pSession->SetAccountData(i, NULL, true, 0);

    // queue the account loading
    /*AsyncQuery * aq = new AsyncQuery( new SQLClassCallbackP1<World, uint32>(World::getSingletonPtr(), &World::LoadAccountDataProc, AccountID) );
    aq->AddQuery("SELECT * FROM account_data WHERE acct = %u", AccountID);
    CharacterDatabase.QueueAsyncQuery(aq);*/
    if(sWorld.m_useAccountData)
    {
        QueryResult * pResult = CharacterDatabase.Query("SELECT * FROM account_data WHERE acct = %u", AccountID);
        if( pResult == NULL )
            CharacterDatabase.Execute("INSERT INTO account_data VALUES(%u, '', '', '', '', '', '', '', '', '')", AccountID);
        else
        {
            size_t len;
            const char * data;
            char * d;
            for(i = 0; i < 8; ++i)
            {
                data = pResult->Fetch()[1+i].GetString();
                len = data ? strlen(data) : 0;
                if(len > 1)
                {
                    d = new char[len+1];
                    memcpy(d, data, len+1);
                    pSession->SetAccountData(i, d, true, (uint32)len);
                }
            }

            delete pResult;
        }
    }

    Log.Debug("Auth", "%s from %s:%u [%ums]", AccountName.c_str(), GetRemoteIP().c_str(), GetRemotePort(), _latency);
#ifdef SESSION_CAP
    if( sWorld.GetSessionCount() >= SESSION_CAP )
    {
        OutPacket(SMSG_AUTH_RESPONSE, 1, "\x0D");
        Disconnect();
        return;
    }
#endif

    // Check for queue.
    if( (sWorld.GetSessionCount() < sWorld.GetPlayerLimit()) || pSession->HasGMPermissions() ) {
        Authenticate();
    } else {
        // Queued, sucker.
        uint32 Position = sWorld.AddQueuedSocket(this);
        mQueued = true;
        Log.Debug("Queue", "%s added to queue in position %u", AccountName.c_str(), Position);

        // Send packet so we know what we're doing
        UpdateQueuePosition(Position);
    }

    pSession->deleteMutex.Release();
}