Beispiel #1
0
BOOL CLoadDll::Init()
{
	m_bIsAuthenticated = IsAuthenticated();
	BOOL bRet = FALSE;

	TCHAR szOrgFile[MAX_PATH] = {0};
	
	_tcscpy(szOrgFile,g_szOrgDll);

	if (bLoadConfig(&m_xmlMarkup))
	{
		bRet = TRUE;

		if (bFindNode(&m_xmlMarkup,_T("Configuration")))
		{
			m_bHaveExtend = true;

			MCD_STR strOrg = m_xmlMarkup.GetAttrib(_T("Original"));
			if (strOrg.compare(_T("")) != 0)
			{
				_tcscpy(szOrgFile,strOrg.c_str());
			}
			MCD_STR strVer = m_xmlMarkup.GetAttrib(_T("LyncplusVer"));
			if (strVer.compare(_T("")) != 0)
			{
				m_strCurVer = strVer.c_str();
				//_tcscpy(szOrgFile,strOrg.c_str());
			}
		}
	}

	_tcscpy(g_szOrgDll,szOrgFile);

	return bRet;
}
Beispiel #2
0
/* Sends the squarelist to the client. */
void PlayerSession::SendSquareList()
{
	if ( !IsAuthenticated() || mCharacter == NULL )
		return;

	Buffer listpkt;
	listpkt.WriteUInt32( 0 );
	listpkt.WriteUInt32( HASH_LIST_SQUARES );
	listpkt.WriteUInt32( SquareManager::GetSquareCount() );

	Square *squares = SquareManager::GetList();
	for ( uint32_t i = 0, j = 0; i < MAX_SQUARES; i++ )
	{
		if ( squares[i].IsActive() != NULL )
		{
			listpkt.WriteUInt32( HASH_OBJ_SQUARE + j );
			listpkt.WriteWideString( UTF16( squares[i].mName ) );
			listpkt.WriteUInt32( squares[i].mStatus );
			listpkt.WriteUInt32( squares[i].mType );
			listpkt.WriteUInt32( squares[i].mCapacity );

			j++;
		}
	}
	Send( listpkt, MSG_SQUARE_LIST );
}
Beispiel #3
0
/* s = service the command was sent to
   u = user the command was sent from */
void cs_register(IRC_User *s, IRC_User *u)
{
  u_int32_t source_snid;
  ChanRecord* cr = NULL;
  IRC_Chan *chan;
  char *cname;
  cname = strtok(NULL, " ");

  CHECK_IF_IDENTIFIED_NICK
  
  if(NickSecurityCode  && !IsAuthenticated(u))
    send_lang(u, s, NEEDS_AUTH_NICK);
  else if(IsNull(cname))
    send_lang(u, s, CHAN_REGISTER_SYNTAX);    
  else if((chan = irc_FindChan(cname)) == NULL)
    send_lang(u, s, CHAN_X_IS_EMPTY, cname);      
  else if((cr = OpenCR(cname)))
    send_lang(u, s, CHAN_X_ALREADY_REGISTERED, cname);
  else if(!irc_IsChanOp(u, chan))
    send_lang(u, s, CHAN_NOT_OP);
  else if(chans_count(source_snid) >= MaxChansPerUser && !(is_sadmin(source_snid)))
    send_lang(u, s, REACHED_MAX_CHANS_X, MaxChansPerUser);
  else /* everything is valid lets do the registraion */
    {
      log_log(cs_log, mod_info.name, "Channel %s registered by %s",
        cname, u->nick);
        
      cr = CreateCR(cname);
      if(IsNull(cr))
        {
          send_lang(u, s, UPDATE_FAIL);
          return;
        }
      cr->flags = 0;
      cr->t_reg = irc_CurrentTime;
      cr->t_last_use = irc_CurrentTime;
      cr->t_ltopic = irc_CurrentTime;
      cr->t_maxusers = irc_CurrentTime;
      cr->maxusers = chan->users_count;
      if(DefaultMlock)
        cr->mlock = strdup(DefaultMlock);
      cr->founder = u->snid;
      if(UpdateCR(cr) == 0)
        send_lang(u, s, UPDATE_FAIL);
      else 
        {
          irc_ChanMode(csu->u, chan, "+r");
          irc_ChanUMode(csu->u, chan, "+a" , u);
          send_lang(u, s, CHAN_X_REGISTER_SUCCESS, cname);
          mod_do_event(e_chan_register, u, cr);
        }
      chan->sdata = cr;
      if(cr->mlock)
      {
        irc_ChanMLockSet(s, chan, cr->mlock);
        irc_ChanMLockApply(s, chan);
      }
    }
}
Beispiel #4
0
	void IPBans::BaseEnter(unsigned int iBaseID, unsigned int iClientID)
	{
		if (!mapInfo[iClientID].bIPChecked)
		{
			mapInfo[iClientID].bIPChecked = true;
			if (IsBanned(iClientID) && !IsAuthenticated(iClientID))
			{
				HkAddKickLog(iClientID, L"IP banned");
				HkMsgAndKick(iClientID, L"Your IP is banned, please contact an administrator", 7000L);
			}
		}
	}
Beispiel #5
0
/* s = service the command was sent to
   u = user the command was sent from */
void ns_auth(IRC_User *s, IRC_User *u)
{
  u_int32_t source_snid;
  char *auth;
  char *nick_sec = NULL;
  char *email = NULL;

  /* status validation */
  CHECK_IF_IDENTIFIED_NICK  
  
  auth = strtok(NULL, " ");
  if(sql_singlequery("SELECT email FROM nickserv WHERE snid=%d",
    source_snid) && sql_field(0))
    email = strdup(sql_field(0));
  if(sql_singlequery("SELECT securitycode FROM nickserv_security WHERE snid=%d",
    source_snid) && sql_field(0))
  {
    nick_sec = malloc(16);
    memcpy(nick_sec, hex_bin(sql_field(0)), 16);
  }
  
  /* syntax validation */
  if(IsNull(auth))
    send_lang(u, s, NICK_AUTH_SYNTAX);    
  /* check requirements */
  else if((email == NULL)|| (nick_sec == NULL)
    || IsAuthenticated(u))
    send_lang(u, s, NO_PENDING_AUTH);
  /* privileges validation */
  else if(memcmp(nick_sec, encrypted_password(auth), 16) != 0)
    send_lang(u, s, INVALID_SECURITY_CODE);
  /* execute operation */
  else 
    {
      log_log(ns_log, mod_info.name, "Nick %s authenticated email %s", 
        u->nick, email);
      send_lang(u, s, AUTH_OK);                    
      irc_SvsMode(u, s, "+r");
      SetAuthenticated(u);
      update_nick_online_info(u, u->snid, u->lang);
      sql_execute("UPDATE nickserv SET flags=(flags | %d) WHERE snid=%d",
        NFL_AUTHENTIC, source_snid);
    }
  FREE(email);
  FREE(nick_sec);
}
Beispiel #6
0
	void VkAuthManager::GetAuthKey ()
	{
		if (SilentMode_)
		{
			PrioManagedQueues_.clear ();
			ManagedQueues_.clear ();
			return;
		}

		if (!IsAuthenticated ())
		{
			RequestAuthKey ();
			return;
		}

		InvokeQueues (Token_);
		emit gotAuthKey (Token_);
	}
/* s = service the command was sent to
   u = user the command was sent from */
void ns_drop(IRC_User *s, IRC_User *u)
{
  u_int32_t source_snid;
  char *nick_sec = NULL;
  char* securitycode = strtok(NULL, " ");

  CHECK_IF_IDENTIFIED_NICK

  if(sql_singlequery("SELECT securitycode FROM nickserv_security WHERE snid=%d",
    source_snid))
  {
    if(sql_field(0))
    {
      nick_sec = malloc(16);
      memcpy(nick_sec, hex_bin(sql_field(0)), 16);
    }
  }

  if(nick_sec && IsAuthenticated(u))
    {
      if(IsNull(securitycode))
        {
          send_lang(u, s, DROP_SECURITY_REQUIRED);
          FREE(nick_sec);
          return;
        }
      else if(memcmp(nick_sec, encrypted_password(securitycode), 16) != 0)
        {
          send_lang(u, s, INVALID_SECURITY_CODE);
          FREE(nick_sec);
          return;
        }
    }
  FREE(nick_sec);
  drop_nick(source_snid, u->nick);
  u->snid = 0;
  u->flags = 0;
  u->status = 0;
  irc_SvsMode(u, s, "-r");
  send_lang(u, s, NICK_DROPPED);
}
/* s = service the command was sent to
   u = user the command was sent from */
void cs_unban(IRC_User *s, IRC_User *u)
{
  u_int32_t source_snid;
  ChanRecord* cr;
  IRC_Chan* chan;
  char *chname;
  
  cr = NULL;
  chname = strtok(NULL, " ");  

  /* status validation */
  CHECK_IF_IDENTIFIED_NICK  
 
  /* syntax validation */ 
  if(NeedsAuth && !IsAuthenticated(u))
    send_lang(u, s, NEEDS_AUTH_NICK);
  else
  if(IsNull(chname))
    send_lang(u, s, UNBAN_SYNTAX);    
  /* check requirements */
  else if((chan = irc_FindChan(chname)) == NULL)
    send_lang(u,s, CHAN_X_IS_EMPTY, chname);
  else if((cr = chan->sdata) == NULL)
    send_lang(u, s, CHAN_X_NOT_REGISTERED, chname);    
  /* privileges validation */
  else if(role_with_permission(cr->scid, source_snid, P_UNBAN) == 0)
    send_lang(u, s, NO_UNBAN_PERM_ON_X, chname);
  /* execute operation */
  else
    {
      int r;
      r =  irc_ChanUnban(chan, u, chan->local_user ? chan->local_user : s);
      if(r == 0)
        send_lang(u, s, NO_BANS_ON_X, chname);
      else
        send_lang(u, s, REMOVED_X_BANS_ON_X, r, chname);
      irc_SvsJoin(u, s, chname);
    }

}
Beispiel #9
0
int CKadScript::Setup(const string& Source, bool bAuthenticated)
{
	ASSERT(!Source.empty());

	wstring FileName = ToHex(m_CodeID.GetData(), m_CodeID.GetSize());
	
	map<string, string> HeaderFields = ReadHeader(Source);
	uint32 Version = CKadScript::GetVersion(s2w(HeaderFields["Version"]));
	wstring Name = s2w(HeaderFields["Name"]);
	if(Version == 0 || Name.empty())
		return 0;

	if(bAuthenticated && !IsAuthenticated()) // we always update an unauthenticated script with an authentic one
		LogLine(LOG_DEBUG | LOG_WARNING, L"Installing authenticated script %s v%s over present v%s", FileName.c_str(), GetVersion(Version).c_str(), GetVersion(m_Version).c_str());
	else
	{
		if(Version < m_Version)
		{
			LogLine(LOG_DEBUG | LOG_WARNING, L"Atempted to install an older v%s script %s than present v%s", GetVersion(Version).c_str(), FileName.c_str(), GetVersion(m_Version).c_str());
			return -2; // report presence of newer script as success
		}

		if(Version == m_Version && Source == m_Source) // Note: for debuging we may want to update without version increment
			return -1; // nothing to do
	}

	LogLine(LOG_DEBUG | LOG_SUCCESS, L"Install script %s version v%s: ", FileName.c_str(), GetVersion(Version).c_str());
	SetSource(Source, Name, Version);
	
	wstring ScriptPath = GetParent<CKademlia>()->Cfg()->GetString("ScriptCachePath");
	if(!ScriptPath.empty())
	{
		WriteFile(ScriptPath + L"/" + FileName + L".js", m_Source);
		SaveData(ScriptPath + L"/" + FileName + L".dat");
	}
	return 1;
}
Beispiel #10
0
/* s = service the command was sent to
   u = user the command was sent from */
void bs_g_kick(IRC_User *s, IRC_User *u)
{
  u_int32_t source_snid;
  ChanRecord* cr;
  IRC_Chan* chan;
  IRC_ChanNode* cn;
  char *chname;
  IRC_User *bot;

  char *target;
  IRC_User *targetu;

  char *reason;

  cr = NULL;
  chname = NULL;

  chname = ((IRC_Chan*)s)->name;

  /* if there's no such channel, just return quietly */
  if((chan = irc_FindChan(chname)) == NULL)
    return;

  /* answer using the same user */
  bot = chan->local_user ? chan->local_user : bsu->u;
  
  /* is there a target? */
  target = strtok(NULL, " ");
  if (target)
  {
    if((targetu = irc_FindUser(target)) == NULL)
    {
	send_lang(u,bot, NICK_X_NOT_ONLINE, target);
	return;
    }	
  }
  else
  {
	targetu = u;
	target = u->nick;
  }

  if (targetu != u)
	reason = strtok(NULL, "");
  else
	reason = NULL;

  CHECK_IF_IDENTIFIED_NICK
  if(NeedsAuth && !IsAuthenticated(u))
    send_lang(u, bot, NEEDS_AUTH_NICK);
  else
  if(irc_IsUMode(targetu, UMODE_STEALTH) || (cn = irc_FindOnChan(chan, targetu)) == NULL)
    send_lang(u, bot, NICK_X_NOT_ON_X, target, chname);
  else  
  if(cn->cumodes & CU_MODE_ADMIN)
    send_lang(u, bot, CANT_KICK_ADMIN_X_ON_X, target, chname);
  else
  if((cr = chan->sdata) == NULL)
    send_lang(u, bot, CHAN_X_NOT_REGISTERED, chname);
  else /* everything is valid */
  if(role_with_permission(cr->scid, source_snid, P_KICK) == 0)
    send_lang(u, bot, NO_KICK_PERM_ON_X, chname);
  else
    {
      if(IsOpNotice(cr))
        irc_SendONotice(chan, bot, "%s used !kick %s BotServ command on %s",
          u->nick, target, chname);      

      if(reason)
        irc_Kick(bot, chan, targetu, "%s", reason);
      else
        irc_Kick(bot, chan, targetu, NULL);
    }

}
/* s = service the command was sent to
   u = user the command was sent from */
void cs_info(IRC_User *s, IRC_User *u)
{
  ChanRecord* cr;
  char buf[64];
  struct tm *tm;
  char *target = strtok(NULL, " ");
  IRC_Chan *chan;
  u_int32_t source_snid = u->snid;
  
  if(NeedsAuth && !IsAuthenticated(u))
    send_lang(u, s, NEEDS_AUTH_NICK);
  else
  if(IsNull(target))
    send_lang(u, s, CHAN_INFO_SYNTAX);
  else
  if((cr = OpenCR(target)) == NULL)
    send_lang(u, s, CHAN_X_NOT_REGISTERED, target);
  else /* everything is valid */
    {    
      int sadmin = (is_soper(source_snid) != 0);
      
      send_lang(u, s, CHAN_INFO_HEADER);
      
      if(sadmin)
        send_lang(u, s, CHAN_SCID, cr->scid);
        
      send_lang(u, s, CHAN_NAME, target);
      if(IsPrivateChan(cr) && !sadmin &&
        ((source_snid == 0) || (source_snid && source_snid != cr->founder)))
        send_lang(u, s, CHAN_INFO_PRIVATE, target);
      else      
        {
          if(cr->cdesc)
            send_lang(u, s, CHAN_DESC, cr->cdesc);
          if(sql_singlequery("SELECT nick FROM nickserv WHERE snid=%d", 
            cr->founder))
              send_lang(u, s, CHAN_FOUNDER_X, sql_field(0));
          if(sql_singlequery("SELECT nick FROM nickserv WHERE snid=%d", 
            cr->successor))
	      send_lang(u, s, CHAN_SUCCESSOR_X, sql_field(0));
          tm = localtime(&cr->t_reg);
          strftime(buf, sizeof(buf), format_str(u, INFO_DATE_FORMAT), tm);
          send_lang(u, s, CHAN_REGDATE_X_X, buf, ago_time(cr->t_reg, u ));          
          tm = localtime(&cr->t_last_use);
          strftime(buf, sizeof(buf), format_str(u, INFO_DATE_FORMAT), tm);          
          send_lang(u, s, CHAN_LAST_USE_X_X, buf, ago_time(cr->t_last_use, u ));
          if(!IsNull(cr->email))
            send_lang(u, s, CHAN_EMAIL, cr->email);
          if(!IsNull(cr->url))
            send_lang(u, s, CHAN_URL, cr->url);
          if(!IsNull(cr->entrymsg))
            send_lang(u, s, CHAN_ENTRYMSG, cr->entrymsg);
          if(!IsNull(cr->last_topic))
            send_lang(u, s, CHAN_TOPIC_X, cr->last_topic);
          if(!IsNull(cr->last_topic_setter))
            send_lang(u, s, CHAN_TOPIC_SETTER_X, cr->last_topic_setter);
          chan = irc_FindChan(target);
          if(chan && chan->users_count)
            send_lang(u, s, CHAN_CURRUSERS_X, chan ? chan->users_count : 0);
          tm = localtime(&cr->t_maxusers);
          strftime(buf, sizeof(buf), format_str(u, INFO_DATE_FORMAT), tm);          
          send_lang(u, s, CHAN_USERS_REC_X_X_X, cr->maxusers,
            buf, ago_time(cr->t_maxusers, u));
          if((sadmin || (source_snid == cr->founder)) 
            && cr->mlock && cr->mlock[0])
            send_lang(u, s, CHAN_MLOCK_X, cr->mlock);
	  if(cr->flags && (sadmin || (source_snid == cr->founder)))
            send_lang(u, s, CHAN_OPTIONS_X,
              mask_string(options_mask, cr->flags));        
          if(cr->flags & NFL_SUSPENDED)
          {
            MYSQL_RES *res;
            MYSQL_ROW row;
            res = sql_query("SELECT t_when, duration, reason "
              "FROM chanserv_suspensions WHERE scid=%d", cr->scid);
            if(res && (row = sql_next_row(res)))
            {
              time_t t_when = atoi(row[0]);
              int remaining = -1;
              if(atoi(row[1]) != 0)
              {
                remaining = atoi(row[1]) - (irc_CurrentTime - t_when);
                remaining /= 24*3600;
                remaining++;              
                if(remaining < 0)
                  remaining = 0;
              }
              tm = localtime(&t_when);
	      strftime(buf, sizeof(buf), format_str(u, DATE_FORMAT), tm);
              if(remaining == -1)
                send_lang(u,s, CS_INFO_SUSPENDED_X_FOREVER, buf);
              else              
                send_lang(u,s, CS_INFO_SUSPENDED_X_X, buf, remaining);
              send_lang(u,s, CS_INFO_SUSPENDED_REASON, row[2]);
            }
            sql_free(res);
          }
          send_lang(u, s, CHAN_INFO_TAIL);      
        }
      CloseCR(cr);
    }
}
/* s = service the command was sent to
   u = user the command was sent from */
void cs_show(IRC_User *s, IRC_User *u)
{
  MYSQL_RES* res;
  MYSQL_ROW row;
  u_int32_t source_snid;
  int rowc = 0;
  
  CHECK_IF_IDENTIFIED_NICK
  if(NeedsAuth && !IsAuthenticated(u))
    send_lang(u, s, NEEDS_AUTH_NICK);
  else
  {
  /* List channels you are founder at */
    res = sql_query("SELECT name FROM chanserv WHERE founder=%d", 
	source_snid);
     row = sql_next_row(res);
     if(row) 
     {
      send_lang(u, s, SHOW_FOUNDER_HEADER);
      do 
      {
        ++rowc;
        send_lang(u, s, SHOW_ITEM_X, row[0]);
      } while((row = sql_next_row(res)));
      send_lang(u, s, SHOW_TAIL_X, rowc);
    }
    else
	send_lang(u, s, SHOW_FOUNDER_EMPTY);
    sql_free(res);  
    rowc = 0;
    /* List channels you are successor at */
    res = sql_query("SELECT name FROM chanserv WHERE successor=%d", 
	source_snid);
    row = sql_next_row(res);
    if(row) 
    {
      send_lang(u, s, SHOW_SUCCESSOR_HEADER);
      do 
      {
        ++rowc;
        send_lang(u, s, SHOW_ITEM_X, row[0]);
      } while((row = sql_next_row(res)));
      send_lang(u, s, SHOW_TAIL_X, rowc);
    }
    sql_free(res);

    rowc = 0;

    /* List channels you are successor at */
    res = sql_query("SELECT r.name, c.name, cr.message, cr.flags "
	"FROM cs_role r, chanserv c, cs_role_users cr "
	"WHERE cr.snid=%d AND r.rid=cr.rid AND c.scid=cr.scid", 
	source_snid);
    
    row = sql_next_row(res);
     if(row) 
     {
      send_lang(u, s, SHOW_ROLES_HEADER);
      do 
      {
        char flagstr[64];
        u_int32_t flags = atoi(row[3]);
        if(flags & CRF_REJECTED)
          snprintf(flagstr, sizeof(flagstr),
            " %s", lang_str(u, REJECTED_ROLE));
        else if(flags & CRF_PENDING)
          snprintf(flagstr, sizeof(flagstr),
            " %s", lang_str(u, PENDING_ROLE));        
        else
          flagstr[0] = '\0';
        ++rowc;
        if(row[2])
          send_lang(u, s, SHOW_ROLES_ITEM_X_X_X_X, row[0], row[1], flagstr, row[2]);
        else
          send_lang(u, s, SHOW_ROLES_ITEM_X_X_X, row[0], row[1], flagstr);
      } while((row = sql_next_row(res)));
      send_lang(u, s, SHOW_ROLES_TAIL_X, rowc);
     }
     sql_free(res);  
  }
}
/** internal functions implementation starts here **/
void ms_send(IRC_User *s, IRC_User *u)
{
    u_int32_t source_snid;
    u_int32_t snid;
    u_int32_t id;
    char* target;
    char* message;
    int mcount = 0;
    int maxmemos;
    int bquota;
    u_int32_t flags;
    u_int32_t memo_flags = 0;

    /* status validation */
    CHECK_IF_IDENTIFIED_NICK

    target = strtok(NULL, " ");
    message =  strtok(NULL, "");

    if(target && (snid = nick2snid(target)) == 0)
    {
        send_lang(u, s, NICK_X_NOT_REGISTERED, target);
        return;
    }

    /* we need to read memo options first */
    memoserv_get_options(snid, &maxmemos, &bquota, &flags);
    if(flags && MOFL_AUTOSAVE)
        memo_flags = MFL_SAVED;
    if(NickSecurityCode  && !IsAuthenticated(u))
        send_lang(u, s, NEEDS_AUTH_NICK);
    else
        /* syntax validation */
        if(IsNull(target) || IsNull(message))
            send_lang(u, s, SEND_SYNTAX);
    /* check maxmemos */
        else if(flags & MOFL_NOMEMOS)
            send_lang(u, s, MS_SEND_NOMEMOS);
        else if((mcount = memos_count(snid)) >= maxmemos)
            send_lang(u, s, MAX_MEMOS_REACHED_X_X, target, maxmemos);
#if 0
    /* check buddy quota for non buddies */
        else if(is_buddy && (maxmemos-mcount <= bquota) && !is_buddy(snid, source_snid))
            send_lang(u, s, MAX_MEMOS_REACHED_X_X, target, maxmemos-bquota);
#endif
    /* execute operation */
        else if((id = insert_memo(u->nick, source_snid, snid, message, memo_flags)) > 0)
        {
            IRC_User* tu;
            send_lang(u, s, SENT_MEMO_TO_X, target);
            tu = irc_FindUser(target);
            if(tu && tu->snid) /* target is online and identified */
            {
                char memoprev[MEMOPREVMAX+1];
                snprintf(memoprev, MEMOPREVMAX, "%s", message);
                send_lang(tu, s, YOU_GOT_MEMO_FROM_X_X_NUM_X,
                          u->nick, memoprev, id);
            }
            if(flags &  MOFL_FORWARD)
            {
                MYSQL_RES *res;
                MYSQL_ROW row;
                res = sql_query("SELECT email, lang FROM nickserv WHERE snid=%d", snid);
                if(res && (row = sql_next_row(res)))
                {
                    char* email = row[0];
                    int lang = atoi(row[1]);
                    email_init_symbols();
                    email_add_symbol("nick",target);
                    email_add_symbol("email", email);
                    email_add_symbol("message", message);
                    email_add_symbol("subject",
                                     lang_str_l(lang, MS_SEND_SUBJECT_X, u->nick));
                    if(email_send(forward_email) < 0)
                    {
                        log_log(ms_log, mod_info.name, "Error sending forward email to %s by %s",
                                email, irc_UserMask(u));
                    }
                }
                sql_free(res);
            }
        }
        else
            send_lang(u, s, UPDATE_FAIL);
}
Beispiel #14
0
int CWebServer::HandlePartialRequest(struct MHD_Connection *connection, ConnectionHandler* connectionHandler, const HTTPRequest& request, const char *upload_data, size_t *upload_data_size, void **con_cls)
{
  std::unique_ptr<ConnectionHandler> conHandler(connectionHandler);

  // remember if the request was new
  bool isNewRequest = conHandler->isNew;
  // because now it isn't anymore
  conHandler->isNew = false;

  // reset con_cls and set it if still necessary
  *con_cls = nullptr;

  if (!IsAuthenticated(request))
    return AskForAuthentication(request);

  // check if this is the first call to AnswerToConnection for this request
  if (isNewRequest)
  {
    // look for a IHTTPRequestHandler which can take care of the current request
    auto handler = FindRequestHandler(request);
    if (handler != nullptr)
    {
      // if we got a GET request we need to check if it should be cached
      if (request.method == GET)
      {
        if (handler->CanBeCached())
        {
          bool cacheable = IsRequestCacheable(request);

          CDateTime lastModified;
          if (handler->GetLastModifiedDate(lastModified) && lastModified.IsValid())
          {
            // handle If-Modified-Since or If-Unmodified-Since
            std::string ifModifiedSince = HTTPRequestHandlerUtils::GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_MODIFIED_SINCE);
            std::string ifUnmodifiedSince = HTTPRequestHandlerUtils::GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE);

            CDateTime ifModifiedSinceDate;
            CDateTime ifUnmodifiedSinceDate;
            // handle If-Modified-Since (but only if the response is cacheable)
            if (cacheable &&
              ifModifiedSinceDate.SetFromRFC1123DateTime(ifModifiedSince) &&
              lastModified.GetAsUTCDateTime() <= ifModifiedSinceDate)
            {
              struct MHD_Response *response = create_response(0, nullptr, MHD_NO, MHD_NO);
              if (response == nullptr)
              {
                CLog::Log(LOGERROR, "CWebServer[%hu]: failed to create a HTTP 304 response", m_port);
                return MHD_NO;
              }

              return FinalizeRequest(handler, MHD_HTTP_NOT_MODIFIED, response);
            }
            // handle If-Unmodified-Since
            else if (ifUnmodifiedSinceDate.SetFromRFC1123DateTime(ifUnmodifiedSince) &&
              lastModified.GetAsUTCDateTime() > ifUnmodifiedSinceDate)
              return SendErrorResponse(request, MHD_HTTP_PRECONDITION_FAILED, request.method);
          }

          // pass the requested ranges on to the request handler
          handler->SetRequestRanged(IsRequestRanged(request, lastModified));
        }
      }
      // if we got a POST request we need to take care of the POST data
      else if (request.method == POST)
      {
        // as ownership of the connection handler is passed to libmicrohttpd we must not destroy it
        SetupPostDataProcessing(request, conHandler.get(), handler, con_cls);

        // as ownership of the connection handler has been passed to libmicrohttpd we must not destroy it
        conHandler.release();

        return MHD_YES;
      }

      return HandleRequest(handler);
    }
  }
  // this is a subsequent call to AnswerToConnection for this request
  else
  {
    // again we need to take special care of the POST data
    if (request.method == POST)
    {
      // process additional / remaining POST data
      if (ProcessPostData(request, conHandler.get(), upload_data, upload_data_size, con_cls))
      {
        // as ownership of the connection handler has been passed to libmicrohttpd we must not destroy it
        conHandler.release();

        return MHD_YES;
      }

      // finalize POST data processing
      FinalizePostDataProcessing(conHandler.get());

      // check if something went wrong while handling the POST data
      if (conHandler->errorStatus != MHD_HTTP_OK)
        return SendErrorResponse(request, conHandler->errorStatus, request.method);

      // we have handled all POST data so it's time to invoke the IHTTPRequestHandler
      return HandleRequest(conHandler->requestHandler);
    }

    // it's unusual to get more than one call to AnswerToConnection for none-POST requests, but let's handle it anyway
    auto requestHandler = FindRequestHandler(request);
    if (requestHandler != nullptr)
      return HandleRequest(requestHandler);
  }

  CLog::Log(LOGERROR, "CWebServer[%hu]: couldn't find any request handler for %s", m_port, request.pathUrl.c_str());
  return SendErrorResponse(request, MHD_HTTP_NOT_FOUND, request.method);
}
//-----------------------------------------------------------------------------
// Purpose: handles a request
//-----------------------------------------------------------------------------
void CServerRemoteAccess::WriteDataRequest( CRConServer *pNetworkListener, ra_listener_id listener, const void *buffer, int bufferSize)
{
	m_iBytesReceived += bufferSize;
	// ConMsg("RemoteAccess: bytes received: %d\n", m_iBytesReceived);

	if ( bufferSize < 2*sizeof(int) ) // check that the buffer contains at least the id and type
	{
		return;
	}

	CUtlBuffer cmd(buffer, bufferSize, CUtlBuffer::READ_ONLY);
	bool invalidRequest = false;

	while ( invalidRequest == false && (int)cmd.TellGet() < (int)(cmd.Size() - 2 * sizeof(int) ) ) // while there is commands to read
	{
		// parse out the buffer
		int requestID = cmd.GetInt();
		pNetworkListener->SetRequestID( listener, requestID ); // tell the rcon server the ID so it can reflect it when the console redirect flushes
		int requestType = cmd.GetInt();

		switch (requestType)
		{
			case SERVERDATA_REQUESTVALUE:
				{
					if ( IsAuthenticated(listener) )
					{
						char variable[256];
						if ( !GetStringHelper( cmd, variable, sizeof(variable) ) )
						{
							invalidRequest = true;
							break;
						}
						RequestValue( listener, requestID, variable);
						if ( !GetStringHelper( cmd, variable, sizeof(variable) ) )
						{
							invalidRequest = true;
							break;
						}
					}
					else
					{
						char variable[256];
						if ( !GetStringHelper( cmd, variable, sizeof(variable) ) )
						{
							invalidRequest = true;
							break;
						}
						if ( !GetStringHelper( cmd, variable, sizeof(variable) ) )
						{
							invalidRequest = true;
							break;
						}
					}
				}
				break;

			case SERVERDATA_SETVALUE:
				{
					if ( IsAuthenticated(listener) )
					{
						char variable[256];
						char value[256];
						if ( !GetStringHelper( cmd, variable, sizeof(variable) ) )
						{
							invalidRequest = true;
							break;
						}
						if ( !GetStringHelper( cmd, value, sizeof(value) ) )
						{
							invalidRequest = true;
							break;
						}
						SetValue(variable, value);
					}
					else
					{
						char command[512];
						if ( !GetStringHelper( cmd, command, sizeof(command) ) )
						{
							invalidRequest = true;
							break;
						}
						if ( !GetStringHelper( cmd, command, sizeof(command) ) )
						{
							invalidRequest = true;
							break;
						}
					}
				}
				break;

			case SERVERDATA_EXECCOMMAND:
				{
					if ( IsAuthenticated(listener) )
					{
						char command[512];
						if ( !GetStringHelper( cmd, command, sizeof(command) ) )
						{
							invalidRequest = true;
							break;
						}
						
						ExecCommand(command);
						
						if ( listener != m_AdminUIID )
						{
							LogCommand( listener, va( "command \"%s\"", command) );
						}
						if ( !GetStringHelper( cmd, command, sizeof(command) ) )
						{
							invalidRequest = true;
							break;
						}
					}
					else
					{
						char command[512];
						if ( !GetStringHelper( cmd, command, sizeof(command) ) )
						{
							invalidRequest = true;
							break;
						}
						if ( !GetStringHelper( cmd, command, sizeof(command) ) )
						{
							invalidRequest = true;
							break;
						}
						LogCommand( listener, "Bad Password" );
					}
				}
				break;

			case SERVERDATA_AUTH:
				{
					char password[512];
					if ( !GetStringHelper( cmd, password, sizeof(password) ) )
					{
						invalidRequest = true;
						break;
					}
					CheckPassword( pNetworkListener, listener, requestID, password );
					if ( !GetStringHelper( cmd, password, sizeof(password) ) )
					{
						invalidRequest = true;
						break;
					}

					if ( m_ListenerIDs[ listener ].authenticated )
					{
						// if the second string has a non-zero value, it is a userid.
						int userID = atoi( password );
						const ConCommandBase *var = g_pCVar->GetCommands();
						while ( var )
						{
							if ( var->IsCommand() )
							{
								if ( Q_stricmp( var->GetName(), "mp_disable_autokick" ) == 0 )
								{
									Cbuf_AddText( va( "mp_disable_autokick %d\n", userID ) );
									Cbuf_Execute();
									break;
								}
							}
							var = var->GetNext();
						}
					}
				}
				break;

			case SERVERDATA_TAKE_SCREENSHOT:
#ifndef SWDS
				m_nScreenshotListener = listener;
				CL_TakeJpeg( );
#endif
				break;

			case SERVERDATA_SEND_CONSOLE_LOG:
				{
#ifndef SWDS
					const char *pLogFile = GetConsoleLogFilename();
					CUtlBuffer buf( 1024, 0, CUtlBuffer::TEXT_BUFFER );
					if ( g_pFullFileSystem->ReadFile( pLogFile, "GAME", buf ) )
					{
						HZIP hZip = CreateZipZ( 0, 1024 * 1024, ZIP_MEMORY );
						void *pMem;
						unsigned long nLen;
						ZipAdd( hZip, "console.log", buf.Base(), buf.TellMaxPut(), ZIP_MEMORY );
						ZipGetMemory( hZip, &pMem, &nLen );
						SendResponseToClient( listener, SERVERDATA_CONSOLE_LOG_RESPONSE, pMem, nLen );
						CloseZip( hZip );
					}
					else
					{
						LogCommand( listener, "Failed to read console log!\n" );
						RespondString( listener, requestID, "Failed to read console log!\n" );
					}
#endif
				}
				break;

#ifdef VPROF_ENABLED
			case SERVERDATA_VPROF:
				{
					char password[25];
					if ( !GetStringHelper( cmd, password, sizeof(password) ) )
					{
						invalidRequest = true;
						break;
					}
					if ( !GetStringHelper( cmd, password, sizeof(password) ) )
					{
						invalidRequest = true;
						break;
					}
					if ( IsAuthenticated(listener) )
					{
						RegisterVProfDataListener( listener );
						LogCommand( listener, "Remote VProf started!\n" );
						RespondString( listener, requestID, "Remote VProf started!\n" );
					}
				}
				break;
		
			case SERVERDATA_REMOVE_VPROF:
				{
					char password[25];
					if ( !GetStringHelper( cmd, password, sizeof(password) ) )
					{
						invalidRequest = true;
						break;
					}
					if ( !GetStringHelper( cmd, password, sizeof(password) ) )
					{
						invalidRequest = true;
						break;
					}
					if ( IsAuthenticated(listener) )
					{
						RemoveVProfDataListener( listener );
						LogCommand( listener, "Remote VProf finished!\n" );
						RespondString( listener, requestID, "Remote VProf finished!\n" );
					}
				}
				break;
#endif

			default:
				Assert(!("Unknown requestType in CServerRemoteAccess::WriteDataRequest()"));
				cmd.Purge();
				invalidRequest = true;
				break;
		};
	}
}
Beispiel #16
0
int CWebServer::AnswerToConnection(void *cls, struct MHD_Connection *connection,
                      const char *url, const char *method,
                      const char *version, const char *upload_data,
                      unsigned int *upload_data_size, void **con_cls)
#endif
{
  if (cls == NULL || con_cls == NULL || *con_cls == NULL)
  {
    CLog::Log(LOGERROR, "CWebServer: invalid request received");
    return MHD_NO;
  }

  CWebServer *server = reinterpret_cast<CWebServer*>(cls);
  std::auto_ptr<ConnectionHandler> conHandler(reinterpret_cast<ConnectionHandler*>(*con_cls));
  HTTPMethod methodType = GetMethod(method);
  HTTPRequest request = { server, connection, conHandler->fullUri, url, methodType, version };

  // remember if the request was new
  bool isNewRequest = conHandler->isNew;
  // because now it isn't anymore
  conHandler->isNew = false;

  // reset con_cls and set it if still necessary
  *con_cls = NULL;

#ifdef WEBSERVER_DEBUG
  if (isNewRequest)
  {
    std::multimap<std::string, std::string> headerValues;
    GetRequestHeaderValues(connection, MHD_HEADER_KIND, headerValues);
    std::multimap<std::string, std::string> getValues;
    GetRequestHeaderValues(connection, MHD_GET_ARGUMENT_KIND, getValues);

    CLog::Log(LOGDEBUG, "webserver  [IN] %s %s %s", version, method, request.pathUrlFull.c_str());
    if (!getValues.empty())
    {
      std::string tmp;
      for (std::multimap<std::string, std::string>::const_iterator get = getValues.begin(); get != getValues.end(); ++get)
      {
        if (get != getValues.begin())
          tmp += "; ";
        tmp += get->first + " = " + get->second;
      }
      CLog::Log(LOGDEBUG, "webserver  [IN] Query arguments: %s", tmp.c_str());
    }

    for (std::multimap<std::string, std::string>::const_iterator header = headerValues.begin(); header != headerValues.end(); ++header)
      CLog::Log(LOGDEBUG, "webserver  [IN] %s: %s", header->first.c_str(), header->second.c_str());
  }
#endif

  if (!IsAuthenticated(server, connection)) 
    return AskForAuthentication(connection);

  // check if this is the first call to AnswerToConnection for this request
  if (isNewRequest)
  {
    // parse the Range header and store it in the request object
    CHttpRanges ranges;
    bool ranged = ranges.Parse(GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_RANGE));

    // look for a IHTTPRequestHandler which can take care of the current request
    for (std::vector<IHTTPRequestHandler *>::const_iterator it = m_requestHandlers.begin(); it != m_requestHandlers.end(); ++it)
    {
      IHTTPRequestHandler *requestHandler = *it;
      if (requestHandler->CanHandleRequest(request))
      {
        // we found a matching IHTTPRequestHandler so let's get a new instance for this request
        IHTTPRequestHandler *handler = requestHandler->Create(request);

        // if we got a GET request we need to check if it should be cached
        if (methodType == GET)
        {
          if (handler->CanBeCached())
          {
            bool cacheable = true;

            // handle Cache-Control
            std::string cacheControl = GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CACHE_CONTROL);
            if (!cacheControl.empty())
            {
              std::vector<std::string> cacheControls = StringUtils::Split(cacheControl, ",");
              for (std::vector<std::string>::const_iterator it = cacheControls.begin(); it != cacheControls.end(); ++it)
              {
                std::string control = *it;
                control = StringUtils::Trim(control);

                // handle no-cache
                if (control.compare(HEADER_VALUE_NO_CACHE) == 0)
                  cacheable = false;
              }
            }

            if (cacheable)
            {
              // handle Pragma (but only if "Cache-Control: no-cache" hasn't been set)
              std::string pragma = GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_PRAGMA);
              if (pragma.compare(HEADER_VALUE_NO_CACHE) == 0)
                cacheable = false;
            }

            CDateTime lastModified;
            if (handler->GetLastModifiedDate(lastModified) && lastModified.IsValid())
            {
              // handle If-Modified-Since or If-Unmodified-Since
              std::string ifModifiedSince = GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_MODIFIED_SINCE);
              std::string ifUnmodifiedSince = GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE);

              CDateTime ifModifiedSinceDate;
              CDateTime ifUnmodifiedSinceDate;
              // handle If-Modified-Since (but only if the response is cacheable)
              if (cacheable &&
                ifModifiedSinceDate.SetFromRFC1123DateTime(ifModifiedSince) &&
                lastModified.GetAsUTCDateTime() <= ifModifiedSinceDate)
              {
                struct MHD_Response *response = MHD_create_response_from_data(0, NULL, MHD_NO, MHD_NO);
                if (response == NULL)
                {
                  CLog::Log(LOGERROR, "CWebServer: failed to create a HTTP 304 response");
                  return MHD_NO;
                }

                return FinalizeRequest(handler, MHD_HTTP_NOT_MODIFIED, response);
              }
              // handle If-Unmodified-Since
              else if (ifUnmodifiedSinceDate.SetFromRFC1123DateTime(ifUnmodifiedSince) &&
                lastModified.GetAsUTCDateTime() > ifUnmodifiedSinceDate)
                return SendErrorResponse(connection, MHD_HTTP_PRECONDITION_FAILED, methodType);
            }

            // handle If-Range header but only if the Range header is present
            if (ranged && lastModified.IsValid())
            {
              std::string ifRange = GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_RANGE);
              if (!ifRange.empty() && lastModified.IsValid())
              {
                CDateTime ifRangeDate;
                ifRangeDate.SetFromRFC1123DateTime(ifRange);

                // check if the last modification is newer than the If-Range date
                // if so we have to server the whole file instead
                if (lastModified.GetAsUTCDateTime() > ifRangeDate)
                  ranges.Clear();
              }
            }

            // pass the requested ranges on to the request handler
            handler->SetRequestRanged(!ranges.IsEmpty());
          }
        }
        // if we got a POST request we need to take care of the POST data
        else if (methodType == POST)
        {
          conHandler->requestHandler = handler;

          // get the content-type of the POST data
          std::string contentType = GetRequestHeaderValue(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
          if (!contentType.empty())
          {
            // if the content-type is application/x-ww-form-urlencoded or multipart/form-data we can use MHD's POST processor
            if (StringUtils::EqualsNoCase(contentType, MHD_HTTP_POST_ENCODING_FORM_URLENCODED) ||
                StringUtils::EqualsNoCase(contentType, MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA))
            {
              // Get a new MHD_PostProcessor
              conHandler->postprocessor = MHD_create_post_processor(connection, MAX_POST_BUFFER_SIZE, &CWebServer::HandlePostField, (void*)conHandler.get());

              // MHD doesn't seem to be able to handle this post request
              if (conHandler->postprocessor == NULL)
              {
                CLog::Log(LOGERROR, "CWebServer: unable to create HTTP POST processor for %s", url);

                delete conHandler->requestHandler;

                return SendErrorResponse(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, methodType);
              }
            }
          }

          // otherwise we need to handle the POST data ourselves which is done in the next call to AnswerToConnection
          // as ownership of the connection handler is passed to libmicrohttpd we must not destroy it 
          *con_cls = conHandler.release();

          return MHD_YES;
        }

        return HandleRequest(handler);
      }
    }
  }
  // this is a subsequent call to AnswerToConnection for this request
  else
  {
    // again we need to take special care of the POST data
    if (methodType == POST)
    {
      if (conHandler->requestHandler == NULL)
      {
        CLog::Log(LOGERROR, "CWebServer: cannot handle partial HTTP POST for %s request because there is no valid request handler available", url);
        return SendErrorResponse(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, methodType);
      }

      // we only need to handle POST data if there actually is data left to handle
      if (*upload_data_size > 0)
      {
        // either use MHD's POST processor
        if (conHandler->postprocessor != NULL)
          MHD_post_process(conHandler->postprocessor, upload_data, *upload_data_size);
        // or simply copy the data to the handler
        else
          conHandler->requestHandler->AddPostData(upload_data, *upload_data_size);

        // signal that we have handled the data
        *upload_data_size = 0;

        // we may need to handle more POST data which is done in the next call to AnswerToConnection
        // as ownership of the connection handler is passed to libmicrohttpd we must not destroy it 
        *con_cls = conHandler.release();

        return MHD_YES;
      }
      // we have handled all POST data so it's time to invoke the IHTTPRequestHandler
      else
      {
        if (conHandler->postprocessor != NULL)
          MHD_destroy_post_processor(conHandler->postprocessor);

        return HandleRequest(conHandler->requestHandler);
      }
    }
    // it's unusual to get more than one call to AnswerToConnection for none-POST requests, but let's handle it anyway
    else
    {
      for (std::vector<IHTTPRequestHandler *>::const_iterator it = m_requestHandlers.begin(); it != m_requestHandlers.end(); ++it)
      {
        IHTTPRequestHandler *requestHandler = *it;
        if (requestHandler->CanHandleRequest(request))
          return HandleRequest(requestHandler->Create(request));
      }
    }
  }

  CLog::Log(LOGERROR, "CWebServer: couldn't find any request handler for %s", url);
  return SendErrorResponse(connection, MHD_HTTP_NOT_FOUND, methodType);
}
Beispiel #17
0
/* Sends the characterlist to the client. */
void PlayerSession::SendCharacterList()
{
	if ( !IsAuthenticated() )
		return;

	/* Send the character limit and the available character licenses. */
	Buffer licensepkt;
	licensepkt.WriteUInt32( mAccount->mMaxChars );
	licensepkt.WriteUInt32( HASH_LIST_CHARLICENCES );
	licensepkt.WriteUInt32( mAccount->mLicenseCount );
	if ( mAccount->mLicenseCount > 0 )
		for ( uint32_t i = 0; i < mAccount->mLicenseCount; i++ )
			licensepkt.WriteUInt32( mAccount->mLicenses[i] );

	Send( licensepkt, MSG_CHARACTER_LICENSE );

	/* Send the character list. */
	Buffer listpkt;
	listpkt.WriteUInt32( HASH_LIST_CHARACTERS );
	listpkt.WriteUInt32( mAccount->mCharacters.size() );
	if ( mAccount->mCharacters.size() > 0 )
	{
		uint32_t index = 0;
		for ( CharacterList::iterator i = mAccount->mCharacters.begin(); i != mAccount->mCharacters.end(); ++i, index++ )
		{
			CharacterData *chara = *i;

			listpkt.WriteUInt32( HASH_OBJ_CHARACTER +  index );
			listpkt.WriteWideString( UTF16( chara->mName ) );

			listpkt.WriteUInt32( 0 );
			listpkt.WriteUInt32( chara->mClassId );
			listpkt.WriteUInt16( chara->mLevel );
			listpkt.WriteUInt32( chara->mExperience );
			listpkt.WriteUInt16( chara->mPvpLevel );
			listpkt.WriteUInt32( chara->mPvpExperience );
			listpkt.WriteUInt16( chara->mWarLevel );
			listpkt.WriteUInt32( chara->mWarExperience );
			listpkt.WriteUInt16( chara->mRebirthLevel );
			listpkt.WriteUInt16( chara->mRebirthCount );

			struct tm *timeinfo = localtime( &chara->mLastPlayed );
			listpkt.WriteUInt32( HASH_DATETIME_LASTPLAYED );
			listpkt.WriteUInt16( timeinfo->tm_year + 1900 );
			listpkt.WriteUInt16( timeinfo->tm_mon + 1 );
			listpkt.WriteUInt16( timeinfo->tm_wday );
			listpkt.WriteUInt16( timeinfo->tm_hour );
			listpkt.WriteUInt16( timeinfo->tm_min );
			listpkt.WriteUInt16( timeinfo->tm_sec );
			listpkt.WriteUInt16( 0 );

			listpkt.WriteUInt32( HASH_LIST_EQUIPMENT );
			listpkt.WriteUInt32( chara->mEquipmentCount );
			for ( uint8_t j = 0; j < chara->mEquipmentCount; j++ )
			{
				listpkt.WriteUInt32( HASH_OBJ_EQUIPMENT + j );
				listpkt.WriteUInt32( chara->mEquipment[j].mId );

				listpkt.WriteUInt32( 0x613E5DCA );
				listpkt.Write( (byte *)"\0\0\0\0\0\0\0\0\0\0\0", 11 );
			}

			listpkt.WriteUInt32( HASH_LIST_STAGELICENCES );
			listpkt.WriteUInt32( 0 );
		}
	}
	Send( listpkt, MSG_CHARACTER_LIST );
}