コード例 #1
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    no(false)
{
   if(!IsAdmin()){
       this->hide();
       QMessageBox msg(this);
       msg.setText("Для коректної роботи програмі необхідні права адміністратора!");
       msg.exec();
       this->no = true;
       ShellExecute(NULL,
           L"runas",
           qApp->applicationFilePath().toStdWString().c_str(),
           L"",
           NULL,                        // default dir
           SW_SHOWNORMAL
       );
       return;
   }

   ui->setupUi(this);

   int res = checkWlanHosteed();
   QString msg = QString("%2\r\n%1").arg(getErrorMsg(res)).arg((!IsAdmin())?"is not Admin :(":"is Admin :)");
   ui->textBrowser->setPlainText(msg);
   qDebug() << msg;

}
コード例 #2
0
ファイル: parse.c プロジェクト: jmaurice/zorak-services-old
u_short
parse_mode(user_t *cptr, char *mode)
{
	u_short y = 0;

	if (!mode)
		return -1;
	while (*mode != '\0')
		switch (*mode++) {
			case '-':
				y = DEL;
				break;
			case '+':
				y = ADD;
				break;
			case 'o':
				switch (y) {
					case ADD:
						if (me.opernotice && me.eob && strncasecmp(cptr->server->nick,
							"services", 8) != 0 && !IsAdmin(cptr))
							is_an_oper_notice(cptr->server->nick, "%s!%s@%s on %s is now an operator (O)", cptr->nick, cptr->username, cptr->host, cptr->server->nick);
						add_privs(cptr, OPER);
						add_privs(cptr, SNOTICE);
						break;
					case DEL:
						del_privs(cptr, OPER);
						del_privs(cptr, SNOTICE);
						break;
				}
				break;
		}
	return 1;
}
コード例 #3
0
ファイル: Test.cpp プロジェクト: Tumba/Keeper
void CarAir(int playerid)
{
	if(InteriorChange[playerid] > 0)
	{
			InteriorChange[playerid] --;
                        goto update;
			return;

	}
	if(IsAdmin(playerid)) goto update;
        if(IsPlayerInPoint(playerid,10.0,617.5318,-1.9900,1000.6396)|| IsPlayerInPoint(playerid,10.0,615.2845,-124.2390,997.6873)\
        || IsPlayerInPoint(playerid,10.0,617.5356,-1.9900,1000.7245) || IsPlayerInPoint(playerid,10.0,616.7833,-74.8150,997.7633)) goto update;
	if(afk[playerid] > 0 ) goto update;
	if(!IsPlayerInPoint(playerid,10.0,PlayerAir[playerid].posx,PlayerAir[playerid].posy,PlayerAir[playerid].posz) &&  g_Invoke->callNative(&PAWN::GetPlayerState,playerid) == PLAYER_STATE_DRIVER && GetPlayerSpeed(playerid) < 10.0f )
	{
			SafeKick(playerid,"Air Break",AC_AIR);
			return;
		
	}
        else goto update;

	update:{
	float cord[3];
	g_Invoke->callNative(&PAWN::GetPlayerPos,playerid,&cord[0],&cord[1],&cord[2]);
	PlayerAir[playerid].posx = cord[0];
	PlayerAir[playerid].posy = cord[1];
	PlayerAir[playerid].posz = cord[2];}
}
コード例 #4
0
ファイル: authadmin.cpp プロジェクト: 00farts/italc-1
AUTHADMIN_API
BOOL CUGP(char * userin,char *password,char *machine,char *groupin,int locdom)
{
	DWORD dwLogonType;
	DWORD dwLogonProvider;
	HANDLE hToken;
	bool returnvalue=false;
	dwLogonType     = LOGON32_LOGON_INTERACTIVE;
	dwLogonProvider = LOGON32_PROVIDER_DEFAULT;

	byte *buf = 0;
	byte *buf2 = 0;
	char domain[MAXLEN * sizeof(wchar_t)];
	DWORD rcdomain = NetGetDCName( 0, 0, &buf );
	NetApiBufferFree( buf );
	printf("Logonuser: % s %s \n", userin, ".");
			if (LogonUser(userin, ".", password, dwLogonType, dwLogonProvider, &hToken))
					if (ImpersonateLoggedOnUser(hToken))
				{
					returnvalue=IsAdmin();
					RevertToSelf();
					CloseHandle(hToken);
				}
	if (returnvalue==true) return returnvalue;
	if (!rcdomain)
		{
			DWORD result=NetWkstaGetInfo( 0 , 100 , &buf2 ) ;
				if (!result)
				{
					wcstombs( domain, ((WKSTA_INFO_100_NT *) buf2)->wki100_langroup, MAXLEN );
					NetApiBufferFree( buf2 );
					printf("Logonuser: % s %s \n", userin, domain);
					if (LogonUser(userin, domain, password, dwLogonType, dwLogonProvider, &hToken))
						if (ImpersonateLoggedOnUser(hToken))
							{
								returnvalue=IsAdmin();
								RevertToSelf();
								CloseHandle(hToken);
							}
				}

		}
	
	return returnvalue;
	
}
コード例 #5
0
ファイル: ns_clients.cpp プロジェクト: svn2github/ncbi_tk
void CNSClientId::CheckAccess(TNSCommandChecks  cmd_reqs,
                              CNetScheduleServer *  server,
                              const string &  cmd)
{
    if (cmd_reqs & eNS_Queue) {
        if ((m_PassedChecks & eNS_Queue) == 0)
            NCBI_THROW(CNetScheduleException, eInvalidParameter,
                       "Invalid parameter: queue required");
    }

    if (IsAdmin())
        return;     // Admin can do everything

    if (cmd_reqs & eNS_Admin) {
        if ((m_PassedChecks & eNS_Admin) == 0) {
            server->RegisterAlert(eAccess, "admin privileges required "
                                  "to execute " + cmd);
            NCBI_THROW(CNetScheduleException, eAccessDenied,
                       "Access denied: admin privileges required");
        }
    }

    if (cmd_reqs & eNS_Submitter) {
        if ((m_PassedChecks & eNS_Submitter) == 0) {
            server->RegisterAlert(eAccess, "submitter privileges required "
                                  "to execute " + cmd);
            NCBI_THROW(CNetScheduleException, eAccessDenied,
                       "Access denied: submitter privileges required");
        }
    }

    if (cmd_reqs & eNS_Worker) {
        if ((m_PassedChecks & eNS_Worker) == 0) {
            server->RegisterAlert(eAccess, "worker node privileges required "
                                  "to execute " + cmd);
            NCBI_THROW(CNetScheduleException, eAccessDenied,
                       "Access denied: worker node privileges required");
        }
    }

    if (cmd_reqs & eNS_Reader) {
        if ((m_PassedChecks & eNS_Reader) == 0) {
            server->RegisterAlert(eAccess, "reader privileges required "
                                  "to execute " + cmd);
            NCBI_THROW(CNetScheduleException, eAccessDenied,
                       "Access denied: reader privileges required");
        }
    }

    if (cmd_reqs & eNS_Program) {
        if ((m_PassedChecks & eNS_Program) == 0) {
            server->RegisterAlert(eAccess, "program privileges required "
                                  "to execute " + cmd);
            NCBI_THROW(CNetScheduleException, eAccessDenied,
                       "Access denied: program privileges required");
        }
    }
}
コード例 #6
0
ファイル: chm_adminonly.c プロジェクト: alyx/ircd-cherry
static void
h_can_join(hook_data_channel *data)
{
	struct Client *source_p = data->client;
	struct Channel *chptr = data->chptr;

	if((chptr->mode.mode & chmode_flags['A']) && !IsAdmin(source_p)) {
		sendto_one_numeric(source_p, 519, "%s :Cannot join channel (+A) - you are not an IRC server administrator", chptr->chname);
		data->approved = ERR_CUSTOM;
	}
}
コード例 #7
0
u_short
list_channels(user_t *cptr, char *cm)
{
	channel *chan = main_channel;
	u_short i = 0;

	for (; chan && (i < 200 || IsAdmin(cptr)); chan = chan->next)
		if (match(cm, chan->name))
			reply(CS, cptr->nick, "%d) %s %d", ++i, chan->name, chan->nmembers);
	reply(CS, cptr->nick, "End of LIST.");
	return i;
}
コード例 #8
0
static int
mo_adminwall(struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
    if(!IsAdmin(source_p))
    {
        sendto_one_numeric(source_p, s_RPL(ERR_NOPRIVS), "adminwall");
        return 0;
    }
    sendto_wallops_flags(UMODE_ADMIN, source_p, "ADMINWALL - %s", parv[1]);
    sendto_match_servs(source_p, "*", CAP_ENCAP, NOCAPS, "ENCAP * ADMINWALL :%s", parv[1]);
    return 0;
}
コード例 #9
0
ファイル: m_sdesc.c プロジェクト: SwiftIRC/ircd
int m_sdesc(aClient *cptr, aClient *sptr, int parc, char *parv[])
{
	if (!IsAdmin(sptr) && !IsCoAdmin(sptr))
	{
		sendto_one(sptr, err_str(ERR_NOPRIVILEGES), me.name, sptr->name);
		return 0;
	}
	
	if (parc < 2)
	{
		sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS), me.name, sptr->name, "SDESC");
		return 0;
	}

	if (strlen(parv[1]) < 1)
		if (MyConnect(sptr))
		{
			sendto_one(sptr,
			    ":%s NOTICE %s :*** Nothing to change to (SDESC)",
			    me.name, sptr->name);
			return 0;
		}
	if (strlen(parv[1]) > (REALLEN))
	{
		if (MyConnect(sptr))
		{
			sendto_one(sptr,
			    ":%s NOTICE %s :*** /SDESC Error: \"Server info\" may maximum be %i characters of length",
			    me.name, sptr->name, REALLEN);
		}
		return 0;
	}

	ircsprintf(sptr->srvptr->info, "%s", parv[1]);

	sendto_serv_butone_token(cptr, sptr->name, MSG_SDESC, TOK_SDESC, ":%s",
	    parv[1]);

	if (MyConnect(sptr))
	{
		sendto_one(sptr,
		    ":%s NOTICE %s :Your \"server description\" is now set to be %s - you have to set it manually to undo it",
		    me.name, parv[0], parv[1]);
		return 0;
	}
	sendto_ops("Server description for %s is now '%s' changed by %s",
	    sptr->srvptr->name, sptr->srvptr->info, parv[0]);
	return 0;
}
コード例 #10
0
ファイル: Test.cpp プロジェクト: Tumba/Keeper
void AdminMes(int playerid,char mess[])
{
	char mes[128];
	sprintf(mes,"ID: %d подозревается в использовании читов{00BFFF}({00BFFF}%s)",playerid,mess);
	for(int i = 0; i < MAX_PLAYERS;i++)
	{
		if(!IsConnected[i]) continue;
		if(IsAdmin(i))
		{
			g_Invoke->callNative(&PAWN::SendClientMessage,i,COLOR_RED,mes);

		}
	}

}
コード例 #11
0
ファイル: m_sanick.c プロジェクト: wirelesspt/unreal
/*
** m_sanick() - PID - 08-08-2011
**
**      parv[0] - sender
**      parv[1] - nick to make join
**      parv[2] - channel(s) to join
*/
int m_sanick(aClient * cptr, aClient * sptr, int parc, char *parv[])  {
       aClient *acptr;
	char *param[3];
	int self = 0;
//	if (IsServer(sptr) || IsServices(sptr))
//		return 0; //Servers and Services should be invoking SVSNICK directly...
	if (!IsOper(sptr) && !IsAdmin(sptr) && !IsULine(sptr))   {
               sendto_one(sptr, err_str(ERR_NOPRIVILEGES), me.name, parv[0]);
               return 0;
       }
	if (parv[1] == NULL || !parv[1] || !parv[2]) {
		sendnotice(sptr, "*** Usage: \2/sanick oldnick newnick\2");
		return 0;
	}
       if (parv[2] == NULL || !(acptr = find_person(parv[1], NULL))) {
		sendnotice(sptr, "*** No such user, %s.", parv[1]);
		return 0;
	}
	if (!strcmp(parv[2], parv[1]) || !strcmp(parv[2], parv[0])) {
		sendnotice(sptr, "*** Perhaps I should warn people that they have given an idiot IRCOp access?");
		return 0;
	}
	if (!strcmp(parv[0], parv[1]))
		self = 1;
	if (find_client(parv[2], NULL)) {
		sendnotice(sptr, "*** WARNING: User %s already exists!", parv[2]);
		return 0;
	}
	if(acptr->umodes & UMODE_REGNICK)
		acptr->umodes &= ~UMODE_REGNICK;
	param[0] = acptr->name;
	param[1] = parv[2];
	param[2] = NULL;
	sendnotice(acptr, "*** You were forced to change your nick to %s", parv[2]);
	do_cmd(acptr, acptr, "NICK", 2, param);
	if(self) {
		sendto_realops("%s used \2SANICK\2 to change their nick to %s.", parv[1], parv[2]);
		ircd_log(LOG_SACMDS,"SANICK: %s used SANICK to change their nick to %s", parv[1], parv[2]);
	} else {
		sendto_realops("%s used \2SANICK\2 to make %s change their nick to %s.", parv[0], parv[1], parv[2]);
		ircd_log(LOG_SACMDS,"SANICK: %s used SANICK to make %s change their nick to %s", acptr->name, parv[1], parv[2]);
	}
	return 0;
}
コード例 #12
0
ファイル: Test.cpp プロジェクト: Tumba/Keeper
void AirCheck(int playerid)
{
	int a = g_Invoke->callNative(&PAWN::GetPlayerAnimationIndex,playerid);
	if(AirFix[playerid] > 0) AirFix[playerid] --;
	if(g_Invoke->callNative(&PAWN::GetPlayerSurfingVehicleID,playerid) != INVALID_VEHICLE_ID) goto update;
        if(IsPlayerInPoint(playerid,10.0,617.5318,-1.9900,1000.6396)|| IsPlayerInPoint(playerid,10.0,615.2845,-124.2390,997.6873)\
        || IsPlayerInPoint(playerid,10.0,617.5356,-1.9900,1000.7245) || IsPlayerInPoint(playerid,10.0,616.7833,-74.8150,997.7633)) goto update;
	if(InteriorChange[playerid] > 0)
	{
			InteriorChange[playerid] --;
                        goto update;
			return;

	}
	if(IsAdmin(playerid)) goto update;
	if(afk[playerid] > 0 ) goto update;
	if(!IsPlayerInPoint(playerid,400.0,PlayerAir[playerid].posx,PlayerAir[playerid].posy,PlayerAir[playerid].posz))
	{
		
		SafeKick(playerid,"Teleport",AC_AIR);
		return;
	}
	if( a== 958 || a == 959 || a == 961 || a == 962 || a == 965 || a == 971 || a == 1126 || a == 1130 || a == 1132 || a ==1134 || a == 1156 || a == 1208) goto update;

	if(!IsPlayerInPoint(playerid,30.0,PlayerAir[playerid].posx,PlayerAir[playerid].posy,PlayerAir[playerid].posz))
	{
		if(AirFix[playerid] == 0)
		{
			AirFix[playerid] = 10;
			goto update;
		}
		
		SafeKick(playerid,"Air Break",AC_AIR);
		return;
	}
	update:
	float cord[3];
	g_Invoke->callNative(&PAWN::GetPlayerPos,playerid,&cord[0],&cord[1],&cord[2]);
	PlayerAir[playerid].posx = cord[0];
	PlayerAir[playerid].posy = cord[1];
	PlayerAir[playerid].posz = cord[2];
}
コード例 #13
0
// CBootstrapperApp initialization
BOOL CBootstrapperApp::InitInstance()
{
    // check VC++ 2010
    /*if (!IsVC2010())
    {
    ::MessageBox(NULL, "This application requires 'Visual C++ 2010 Redistributable (x86)' to be installed first.\n"
    "Please install the prerequisite from the 'Setup' folder and run this setup again."
    , "Phalanger Setup", MB_OK | MB_ICONSTOP);
    return FALSE;
    }*/

    if (!IsAdmin())
    {
        ::MessageBox(NULL, "This application must be run under local administrator account.\n"
                     "Please log on as an administrator and try again.", "Phalanger Setup", MB_OK | MB_ICONSTOP);
        return FALSE;
    }

    HANDLE mutex = ::CreateMutex(NULL, TRUE, "Phalanger Setup: multiple instances preventing mutex");
    if (mutex != NULL && GetLastError() == ERROR_ALREADY_EXISTS)
    {
        ::CloseHandle(mutex);
        ::MessageBox(NULL, "Setup is already running.\nPlease finish the installation in progress and try again.",
                     "Phalanger Setup", MB_OK | MB_ICONSTOP);
        return FALSE;
    }

    CWinApp::InitInstance();

    AfxEnableControlContainer();

    CBootstrapperDlg dlg;

    m_pMainWnd = &dlg;
    dlg.DoModal();

    ::CloseHandle(mutex);

    // Since the dialog has been closed, return FALSE so that we exit the
    // application, rather than start the application's message pump.
    return FALSE;
}
コード例 #14
0
ファイル: m_set.c プロジェクト: Stanford-Online/edx_irc_chat
/* SET IDENTTIMEOUT */
static void
quote_identtimeout(struct Client *source_p, int newval)
{
  if (!IsAdmin(source_p))
  {
    sendto_one(source_p, form_str(ERR_NOPRIVS),
               me.name, source_p->name, "set");
    return;
  }

  if (newval > 0)
  {
    sendto_realops_flags(UMODE_ALL, L_ALL,
		         "%s has changed IDENTTIMEOUT to %d",
			 get_oper_name(source_p), newval);
    GlobalSetOptions.ident_timeout = newval;
  }
  else
    sendto_one(source_p, ":%s NOTICE %s :IDENTTIMEOUT is currently %d",
	       me.name, source_p->name, GlobalSetOptions.ident_timeout);
}
コード例 #15
0
ファイル: m_addmotd.c プロジェクト: Hamper/LineIRCd
/*
** m_addmotd (write a line to ircd.motd)
**
** De-Potvinized by codemastr
*/
DLLFUNC CMD_FUNC(m_addmotd)
{
	FILE *conf;
	char *text;

	text = parc > 1 ? parv[1] : NULL;

	if (!MyConnect(sptr))
		return 0;

	if (!IsAdmin(sptr))
	{
		sendto_one(sptr, err_str(ERR_NOPRIVILEGES), me.name, parv[0]);
		return 0;
	}
	if (parc < 2)
	{
		sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS),
		    me.name, parv[0], "ADDMOTD");
		return 0;
	}
	conf = fopen(MOTD, "a");
	if (conf == NULL)
	{
		return 0;
	}
	sendto_one(sptr, ":%s %s %s :*** Wrote (%s) to file: ircd.motd",
	    me.name, IsWebTV(sptr) ? "PRIVMSG" : "NOTICE", parv[0], text);
	/*      for (i=1 ; i<parc ; i++)
	   {
	   if (i!=parc-1)
	   fprintf (conf,"%s ",parv[i]);
	   else
	   fprintf (conf,"%s\n",parv[i]);
	   } */
	fprintf(conf, "%s\n", text);

	fclose(conf);
	return 1;
}
コード例 #16
0
/*
===============
Padd_Get
RPG-X | Marcin | 06/12/2008
===============
*/
char *Padd_Get( gentity_t *key, gentity_t *who )
{
    int i, j;
    for ( i = 0; i < PADD_DATA_MAX; ++i ) {
        if ( paddData[i].key == key ) {
            DPRINTF(("^3got: %i with %s on nr %i\n", key, paddData[i].value, i));
            //Inform admins
            for ( j = 0; j < level.maxclients; ++j ) {
                gentity_t *player = &g_entities[j];
                if ( !player->client->noAdminChat && IsAdmin( player ) && rpg_respectPrivacy.integer == 0 && player != who && paddData[i].value && paddData[i].value[0] ) {
                    trap_SendServerCommand( player-g_entities, va("print \"%s" S_COLOR_CYAN" (picked up by %s" S_COLOR_CYAN ") " S_COLOR_WHITE "%s\n\"", paddData[i].owner, who->client->pers.netname, paddData[i].value ) );
                }
            }

            //Store string
            Q_strncpyz( who->client->lastPaddMsg, paddData[i].value, sizeof( who->client->lastPaddMsg ) );
            return paddData[i].value;
        }
    }

    G_Printf( S_COLOR_RED "Padd_Get: Unable to find the text for this PADD!\n" S_COLOR_WHITE );
    return 0;
}
コード例 #17
0
ファイル: m_who.c プロジェクト: Cloudxtreme/bahamut
inline char *first_visible_channel(aClient *cptr, aClient *sptr)
{
    Link *lp;
    int secret = 0;
    aChannel *chptr = NULL;
    static char chnbuf[CHANNELLEN + 2];

    if(cptr->user->channel)
    {
	if(IsAdmin(sptr))
	{
	    chptr = cptr->user->channel->value.chptr;
	    if(!(ShowChannel(sptr, chptr)))
		secret = 1;
	}
	else
	{
	    for(lp = cptr->user->channel; lp; lp = lp->next)
	    {
		if(ShowChannel(sptr, lp->value.chptr))
		    break;
	    }
	    if(lp)
		chptr = lp->value.chptr;
	}

	if(chptr)
	{
	    if(!secret)
		return chptr->chname;
	    ircsprintf(chnbuf, "%%%s", chptr->chname);
	    return chnbuf;
	}
    }
    return "*";
}
コード例 #18
0
BOOL CSettingGitConfig::OnInitDialog()
{
	ISettingsPropPage::OnInitDialog();

	m_cSafeCrLf.AddString(_T("false"));
	m_cSafeCrLf.AddString(_T("true"));
	m_cSafeCrLf.AddString(_T("warn"));

	m_UserName = g_Git.GetUserName();
	m_UserEmail = g_Git.GetUserEmail();
	m_UserSigningKey = g_Git.GetConfigValue(_T("user.signingkey"));

	ProjectProperties::GetBOOLProps(this->m_bAutoCrlf, _T("core.autocrlf"));
	BOOL bSafeCrLf = FALSE;
	ProjectProperties::GetBOOLProps(bSafeCrLf, _T("core.safecrlf"));
	if (bSafeCrLf)
		m_cSafeCrLf.SetCurSel(1);
	else
	{
		CString sSafeCrLf;
		ProjectProperties::GetStringProps(sSafeCrLf, _T("core.safecrlf"));
		sSafeCrLf = sSafeCrLf.MakeLower().Trim();
		if (sSafeCrLf == _T("warn"))
			m_cSafeCrLf.SetCurSel(2);
		else
			m_cSafeCrLf.SetCurSel(0);
	}
	ProjectProperties::GetBOOLProps(this->m_bWarnNoSignedOffBy, _T("tgit.warnnosignedoffby"));

	CString str = ((CSettings*)GetParent())->m_CmdPath.GetWinPath();
	bool isBareRepo = g_GitAdminDir.IsBareRepo(str);
	CString proj;
	if (g_GitAdminDir.HasAdminDir(str, &proj) || isBareRepo)
	{
		CString title;
		this->GetWindowText(title);
		this->SetWindowText(title + _T(" - ") + proj);
		this->GetDlgItem(IDC_CHECK_GLOBAL)->EnableWindow(TRUE);
		this->GetDlgItem(IDC_EDITLOCALGITCONFIG)->EnableWindow(TRUE);
	}
	else
	{
		m_bGlobal = TRUE;
		this->GetDlgItem(IDC_CHECK_GLOBAL)->EnableWindow(FALSE);
		this->GetDlgItem(IDC_EDITLOCALGITCONFIG)->EnableWindow(FALSE);
	}

	if (isBareRepo)
		this->GetDlgItem(IDC_EDITLOCALGITCONFIG)->SetWindowText(CString(MAKEINTRESOURCE(IDS_PROC_GITCONFIG_EDITLOCALGONCFIG)));

	if (!IsAdmin())
	{
		((CButton *)this->GetDlgItem(IDC_EDITSYSTEMGITCONFIG))->SetShield(TRUE);
		this->GetDlgItem(IDC_VIEWSYSTEMGITCONFIG)->ShowWindow(SW_SHOW);
	}

	if (PathIsDirectory(g_Git.GetGitGlobalXDGConfigPath()))
		this->GetDlgItem(IDC_EDITGLOBALXDGGITCONFIG)->ShowWindow(SW_SHOW);

	this->UpdateData(FALSE);
	return TRUE;
}
コード例 #19
0
ファイル: Format.c プロジェクト: cocoon/VeraCrypt
int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams)
{
	int nStatus;
	PCRYPTO_INFO cryptoInfo = NULL;
	HANDLE dev = INVALID_HANDLE_VALUE;
	DWORD dwError;
	char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE];
	unsigned __int64 num_sectors, startSector;
	fatparams ft;
	FILETIME ftCreationTime;
	FILETIME ftLastWriteTime;
	FILETIME ftLastAccessTime;
	BOOL bTimeStampValid = FALSE;
	BOOL bInstantRetryOtherFilesys = FALSE;
	char dosDev[TC_MAX_PATH] = { 0 };
	char devName[MAX_PATH] = { 0 };
	int driveLetter = -1;
	WCHAR deviceName[MAX_PATH];
	uint64 dataOffset, dataAreaSize;
	LARGE_INTEGER offset;
	BOOL bFailedRequiredDASD = FALSE;
	HWND hwndDlg = volParams->hwndDlg;

	FormatSectorSize = volParams->sectorSize;

	if (FormatSectorSize < TC_MIN_VOLUME_SECTOR_SIZE
		|| FormatSectorSize > TC_MAX_VOLUME_SECTOR_SIZE
		|| FormatSectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
	{
		Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg);
		return ERR_DONT_REPORT; 
	}

	/* WARNING: Note that if Windows fails to format the volume as NTFS and the volume size is
	less than the maximum FAT size, the user is asked within this function whether he wants to instantly
	retry FAT format instead (to avoid having to re-create the whole container again). If the user
	answers yes, some of the input parameters are modified, the code below 'begin_format' is re-executed 
	and some destructive operations that were performed during the first attempt must be (and are) skipped. 
	Therefore, whenever adding or modifying any potentially destructive operations below 'begin_format',
	determine whether they (or their portions) need to be skipped during such a second attempt; if so, 
	use the 'bInstantRetryOtherFilesys' flag to skip them. */

	if (volParams->hiddenVol)
	{
		dataOffset = volParams->hiddenVolHostSize - TC_VOLUME_HEADER_GROUP_SIZE - volParams->size;
	}
	else
	{
		if (volParams->size <= TC_TOTAL_VOLUME_HEADERS_SIZE)
			return ERR_VOL_SIZE_WRONG;

		dataOffset = TC_VOLUME_DATA_OFFSET;
	}

	dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, volParams->size);

	num_sectors = dataAreaSize / FormatSectorSize;

	if (volParams->bDevice)
	{
		StringCbCopyA ((char *)deviceName, sizeof(deviceName), volParams->volumePath);
		ToUNICODE ((char *)deviceName, sizeof(deviceName));

		driveLetter = GetDiskDeviceDriveLetter (deviceName);
	}

	VirtualLock (header, sizeof (header));

	nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
				     header,
				     volParams->ea,
					 FIRST_MODE_OF_OPERATION_ID,
				     volParams->password,
				     volParams->pkcs5,
					  volParams->pim,
					 NULL,
				     &cryptoInfo,
					 dataAreaSize,
					 volParams->hiddenVol ? dataAreaSize : 0,
					 dataOffset,
					 dataAreaSize,
					 0,
					 volParams->headerFlags,
					 FormatSectorSize,
					 FALSE);

	if (nStatus != 0)
	{
		burn (header, sizeof (header));
		VirtualUnlock (header, sizeof (header));
		return nStatus;
	}

begin_format:

	if (volParams->bDevice)
	{
		/* Device-hosted volume */

		DWORD dwResult;
		int nPass;

		if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0)
			return ERR_OS_ERROR;

		if (IsDeviceMounted (devName))
		{
			if ((dev = DismountDrive (devName, volParams->volumePath)) == INVALID_HANDLE_VALUE)
			{
				Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg);
				nStatus = ERR_DONT_REPORT; 
				goto error;
			}

			/* Gain "raw" access to the partition (it contains a live filesystem and the filesystem driver 
			would otherwise prevent us from writing to hidden sectors). */

			if (!DeviceIoControl (dev,
				FSCTL_ALLOW_EXTENDED_DASD_IO,
				NULL,
				0,   
				NULL,
				0,
				&dwResult,
				NULL))
			{
				bFailedRequiredDASD = TRUE;
			}
		}
		else if (IsOSAtLeast (WIN_VISTA) && driveLetter == -1)
		{
			// Windows Vista doesn't allow overwriting sectors belonging to an unformatted partition 
			// to which no drive letter has been assigned under the system. This problem can be worked
			// around by assigning a drive letter to the partition temporarily.

			char szDriveLetter[] = { 'A', ':', 0 };
			char rootPath[] = { 'A', ':', '\\', 0 };
			char uniqVolName[MAX_PATH+1] = { 0 };
			int tmpDriveLetter = -1;
			BOOL bResult = FALSE;

			tmpDriveLetter = GetFirstAvailableDrive ();
 
			if (tmpDriveLetter != -1)
			{
				rootPath[0] += (char) tmpDriveLetter;
				szDriveLetter[0] += (char) tmpDriveLetter;

				if (DefineDosDevice (DDD_RAW_TARGET_PATH, szDriveLetter, volParams->volumePath))
				{
					bResult = GetVolumeNameForVolumeMountPoint (rootPath, uniqVolName, MAX_PATH);

					DefineDosDevice (DDD_RAW_TARGET_PATH|DDD_REMOVE_DEFINITION|DDD_EXACT_MATCH_ON_REMOVE,
						szDriveLetter,
						volParams->volumePath);

					if (bResult 
						&& SetVolumeMountPoint (rootPath, uniqVolName))
					{
						// The drive letter can be removed now
						DeleteVolumeMountPoint (rootPath);
					}
				}
			}
		}

		// For extra safety, we will try to gain "raw" access to the partition. Note that this should actually be
		// redundant because if the filesystem was mounted, we already tried to obtain DASD above. If we failed,
		// bFailedRequiredDASD was set to TRUE and therefore we will perform pseudo "quick format" below. However, 
		// for extra safety, in case IsDeviceMounted() failed to detect a live filesystem, we will blindly
		// send FSCTL_ALLOW_EXTENDED_DASD_IO (possibly for a second time) without checking the result.

		DeviceIoControl (dev,
			FSCTL_ALLOW_EXTENDED_DASD_IO,
			NULL,
			0,   
			NULL,
			0,
			&dwResult,
			NULL);


		// If DASD is needed but we failed to obtain it, perform open - 'quick format' - close - open 
		// so that the filesystem driver does not prevent us from formatting hidden sectors.
		for (nPass = (bFailedRequiredDASD ? 0 : 1); nPass < 2; nPass++)
		{
			int retryCount;

			retryCount = 0;

			// Try exclusive access mode first
			// Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries).
			while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES)
			{
				dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

				if (retryCount > 1)
					Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY);
			}

			if (dev == INVALID_HANDLE_VALUE)
			{
				// Exclusive access denied -- retry in shared mode
				dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
				if (dev != INVALID_HANDLE_VALUE)
				{
					if (!volParams->bForceOperation && (Silent || (IDNO == MessageBoxW (volParams->hwndDlg, GetString ("DEVICE_IN_USE_FORMAT"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2))))
					{
						nStatus = ERR_DONT_REPORT; 
						goto error;
					}
				}
				else
				{
					handleWin32Error (volParams->hwndDlg, SRC_POS);
					Error ("CANT_ACCESS_VOL", hwndDlg);
					nStatus = ERR_DONT_REPORT; 
					goto error;
				}
			}

			if (volParams->hiddenVol || bInstantRetryOtherFilesys)
				break;	// The following "quick format" operation would damage the outer volume

			if (nPass == 0)
			{
				char buf [2 * TC_MAX_VOLUME_SECTOR_SIZE];
				DWORD bw;

				// Perform pseudo "quick format" so that the filesystem driver does not prevent us from 
				// formatting hidden sectors
				memset (buf, 0, sizeof (buf));

				if (!WriteFile (dev, buf, sizeof (buf), &bw, NULL))
				{
					nStatus = ERR_OS_ERROR; 
					goto error;
				}

				FlushFileBuffers (dev);
				CloseHandle (dev);
				dev = INVALID_HANDLE_VALUE;
			}
		}

		if (DeviceIoControl (dev, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dwResult, NULL))
		{
			Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg);
			nStatus = ERR_DONT_REPORT; 
			goto error;
		}
	}
	else
	{
		/* File-hosted volume */

		dev = CreateFile (volParams->volumePath, GENERIC_READ | GENERIC_WRITE,
			(volParams->hiddenVol || bInstantRetryOtherFilesys) ? (FILE_SHARE_READ | FILE_SHARE_WRITE) : 0,
			NULL, (volParams->hiddenVol || bInstantRetryOtherFilesys) ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL);

		if (dev == INVALID_HANDLE_VALUE)
		{
			nStatus = ERR_OS_ERROR; 
			goto error;
		}

		DisableFileCompression (dev);

		if (!volParams->hiddenVol && !bInstantRetryOtherFilesys)
		{
			LARGE_INTEGER volumeSize;
			volumeSize.QuadPart = dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE;

			if (volParams->sparseFileSwitch && volParams->quickFormat)
			{
				// Create as sparse file container
				DWORD tmp;
				if (!DeviceIoControl (dev, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &tmp, NULL))
				{
					nStatus = ERR_OS_ERROR; 
					goto error;
				}
			}

			// Preallocate the file
			if (!SetFilePointerEx (dev, volumeSize, NULL, FILE_BEGIN)
				|| !SetEndOfFile (dev)
				|| SetFilePointer (dev, 0, NULL, FILE_BEGIN) != 0)
			{
				nStatus = ERR_OS_ERROR;
				goto error;
			}
		}
	}

	if (volParams->hiddenVol && !volParams->bDevice && bPreserveTimestamp)
	{
		if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0)
			bTimeStampValid = FALSE;
		else
			bTimeStampValid = TRUE;
	}

	if (volParams->hwndDlg && volParams->bGuiMode) KillTimer (volParams->hwndDlg, TIMER_ID_RANDVIEW);

	/* Volume header */

	// Hidden volume setup
	if (volParams->hiddenVol)
	{
		LARGE_INTEGER headerOffset;

		// Check hidden volume size
		if (volParams->hiddenVolHostSize < TC_MIN_HIDDEN_VOLUME_HOST_SIZE || volParams->hiddenVolHostSize > TC_MAX_HIDDEN_VOLUME_HOST_SIZE)
		{		
			nStatus = ERR_VOL_SIZE_WRONG;
			goto error;
		}

		// Seek to hidden volume header location
		
		headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET;

		if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}
	}
	else if (bInstantRetryOtherFilesys)
	{
		// The previous file system format failed and the user wants to try again with a different file system.
		// The volume header had been written successfully so we need to seek to the byte after the header.

		LARGE_INTEGER offset;
		offset.QuadPart = TC_VOLUME_DATA_OFFSET;
		if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}
	}

	if (!bInstantRetryOtherFilesys)
	{
		// Write the volume header
		if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}

		// To prevent fragmentation, write zeroes to reserved header sectors which are going to be filled with random data
		if (!volParams->bDevice && !volParams->hiddenVol)
		{
			byte buf[TC_VOLUME_HEADER_GROUP_SIZE - TC_VOLUME_HEADER_EFFECTIVE_SIZE];
			DWORD bytesWritten;
			ZeroMemory (buf, sizeof (buf));

			if (!WriteFile (dev, buf, sizeof (buf), &bytesWritten, NULL))
			{
				nStatus = ERR_OS_ERROR;
				goto error;
			}

			if (bytesWritten != sizeof (buf))
			{
				nStatus = ERR_PARAMETER_INCORRECT;
				goto error;
			}
		}
	}

	if (volParams->hiddenVol)
	{
		// Calculate data area position of hidden volume
		cryptoInfo->hiddenVolumeOffset = dataOffset;

		// Validate the offset
		if (dataOffset % FormatSectorSize != 0)
		{
			nStatus = ERR_VOL_SIZE_WRONG; 
			goto error;
		}

		volParams->quickFormat = TRUE;		// To entirely format a hidden volume would be redundant
	}

	/* Data area */
	startSector = dataOffset / FormatSectorSize;

	// Format filesystem

	switch (volParams->fileSystem)
	{
	case FILESYS_NONE:
	case FILESYS_NTFS:

		if (volParams->bDevice && !StartFormatWriteThread())
		{
			nStatus = ERR_OS_ERROR; 
			goto error;
		}

		nStatus = FormatNoFs (hwndDlg, startSector, num_sectors, dev, cryptoInfo, volParams->quickFormat);

		if (volParams->bDevice)
			StopFormatWriteThread();

		break;
		
	case FILESYS_FAT:
		if (num_sectors > 0xFFFFffff)
		{
			nStatus = ERR_VOL_SIZE_WRONG; 
			goto error;
		}

		// Calculate the fats, root dir etc
		ft.num_sectors = (unsigned int) (num_sectors);

#if TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF
#error TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF
#endif

		ft.sector_size = (uint16) FormatSectorSize;
		ft.cluster_size = volParams->clusterSize;
		memcpy (ft.volume_name, "NO NAME    ", 11);
		GetFatParams (&ft); 
		*(volParams->realClusterSize) = ft.cluster_size * FormatSectorSize;

		if (volParams->bDevice && !StartFormatWriteThread())
		{
			nStatus = ERR_OS_ERROR; 
			goto error;
		}

		nStatus = FormatFat (hwndDlg, startSector, &ft, (void *) dev, cryptoInfo, volParams->quickFormat);

		if (volParams->bDevice)
			StopFormatWriteThread();

		break;

	default:
		nStatus = ERR_PARAMETER_INCORRECT; 
		goto error;
	}

	if (nStatus != ERR_SUCCESS)
		goto error;

	// Write header backup
	offset.QuadPart = volParams->hiddenVol ? volParams->hiddenVolHostSize - TC_HIDDEN_VOLUME_HEADER_OFFSET : dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE;

	if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN))
	{
		nStatus = ERR_OS_ERROR;
		goto error;
	}

	nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
		header,
		volParams->ea,
		FIRST_MODE_OF_OPERATION_ID,
		volParams->password,
		volParams->pkcs5,
		volParams->pim,
		cryptoInfo->master_keydata,
		&cryptoInfo,
		dataAreaSize,
		volParams->hiddenVol ? dataAreaSize : 0,
		dataOffset,
		dataAreaSize,
		0,
		volParams->headerFlags,
		FormatSectorSize,
		FALSE);

	if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header))
	{
		nStatus = ERR_OS_ERROR;
		goto error;
	}

	// Fill reserved header sectors (including the backup header area) with random data
	if (!volParams->hiddenVol)
	{
		nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, FALSE);

		if (nStatus != ERR_SUCCESS)
			goto error;
	}

#ifndef DEBUG
	if (volParams->quickFormat && volParams->fileSystem != FILESYS_NTFS)
		Sleep (500);	// User-friendly GUI
#endif

error:
	dwError = GetLastError();

	burn (header, sizeof (header));
	VirtualUnlock (header, sizeof (header));

	if (dev != INVALID_HANDLE_VALUE)
	{
		if (!volParams->bDevice && !volParams->hiddenVol && nStatus != 0)
		{
			// Remove preallocated part before closing file handle if format failed
			if (SetFilePointer (dev, 0, NULL, FILE_BEGIN) == 0)
				SetEndOfFile (dev);
		}

		FlushFileBuffers (dev);

		if (bTimeStampValid)
			SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime);

		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}

	if (nStatus != 0)
	{
		SetLastError(dwError);
		goto fv_end;
	}

	if (volParams->fileSystem == FILESYS_NTFS)
	{
		// Quick-format volume as NTFS
		int driveNo = GetLastAvailableDrive ();
		MountOptions mountOptions;
		int retCode;

		ZeroMemory (&mountOptions, sizeof (mountOptions));

		if (driveNo == -1)
		{
			if (!Silent)
			{
				MessageBoxW (volParams->hwndDlg, GetString ("NO_FREE_DRIVES"), lpszTitle, ICON_HAND);
				MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND);
			}

			nStatus = ERR_NO_FREE_DRIVES;
			goto fv_end;
		}

		mountOptions.ReadOnly = FALSE;
		mountOptions.Removable = FALSE;
		mountOptions.ProtectHiddenVolume = FALSE;
		mountOptions.PreserveTimestamp = bPreserveTimestamp;
		mountOptions.PartitionInInactiveSysEncScope = FALSE;
		mountOptions.UseBackupHeader = FALSE;

		if (MountVolume (volParams->hwndDlg, driveNo, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1)
		{
			if (!Silent)
			{
				MessageBoxW (volParams->hwndDlg, GetString ("CANT_MOUNT_VOLUME"), lpszTitle, ICON_HAND);
				MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND);
			}
			nStatus = ERR_VOL_MOUNT_FAILED;
			goto fv_end;
		}

		if (!Silent && !IsAdmin () && IsUacSupported ())
			retCode = UacFormatNtfs (volParams->hwndDlg, driveNo, volParams->clusterSize);
		else
			retCode = FormatNtfs (driveNo, volParams->clusterSize);

		if (retCode != TRUE)
		{
			if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo) && !Silent)
				MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND);

			if (dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * FormatSectorSize)
			{
				if (AskErrYesNo ("FORMAT_NTFS_FAILED_ASK_FAT", hwndDlg) == IDYES)
				{
					// NTFS format failed and the user wants to try FAT format immediately
					volParams->fileSystem = FILESYS_FAT;
					bInstantRetryOtherFilesys = TRUE;
					volParams->quickFormat = TRUE;		// Volume has already been successfully TC-formatted
					volParams->clusterSize = 0;		// Default cluster size
					goto begin_format;
				}
			}
			else
				Error ("FORMAT_NTFS_FAILED", hwndDlg);

			nStatus = ERR_DONT_REPORT;
			goto fv_end;
		}

		if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo) && !Silent)
			MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND);
	}

fv_end:
	dwError = GetLastError();

	if (dosDev[0])
		RemoveFakeDosName (volParams->volumePath, dosDev);

	crypto_close (cryptoInfo);

	SetLastError (dwError);
	return nStatus;
}
コード例 #20
0
/**
 * \brief Handles firing the grenade launcher.
 *
 * Handles firing the grenade launcher.
 *
 * @param ent the player
 * @param alt_fire was this alt fire mode?
 */
static void WP_FireGrenade( gentity_t *ent, qboolean alt_fire )
{
	gentity_t	*grenade;
	gentity_t	*tripwire = NULL;
	gentity_t	*tent = 0;
	vec3_t		dir, start;
	int		tripcount = 0;
	int		foundTripWires[MAX_GENTITIES] = {ENTITYNUM_NONE};
	int		tripcount_org;
	int		lowestTimeStamp;
	int		removeMe;
	int		i;
	trace_t		tr;
	vec3_t		end;

	VectorCopy( forward, dir );
	VectorCopy( muzzle, start );

	if(RPGEntityCount != ENTITYNUM_MAX_NORMAL-20){
		if ( alt_fire )
		{
			/* RPG-X: RedTechie - Moved here to stop entities from being sucked up */
			grenade = G_Spawn();
			
			/* kef -- make sure count is 0 so it won't get its bounciness removed like the tetrion projectile */
			grenade->count = 0;

			/* RPG-X: RedTechie - Forced Tripwires */
			if ( rpg_invisibletripmines.integer == 1 )
			{
				/* 
 				 * limit to 10 placed at any one time
				 * see how many there are now
				 */
				while ( (tripwire = G_Find( tripwire, FOFS(classname), "tripwire" )) != NULL )
				{
					if ( tripwire->parent != ent )
					{
						continue;
					}
					foundTripWires[tripcount++] = tripwire->s.number;
				}
				/* now remove first ones we find until there are only 9 left */
				tripwire = NULL;
				tripcount_org = tripcount;
				lowestTimeStamp = level.time;
				/* RPG-X: RedTechie - Added 51 tripwires for each person */
				while ( tripcount > 50 ) /* 9 */
				{
					removeMe = -1;
					for ( i = 0; i < tripcount_org; i++ )
					{
						if ( foundTripWires[i] == ENTITYNUM_NONE )
						{
							continue;
						}
						tripwire = &g_entities[foundTripWires[i]];
						if ( tripwire && tripwire->timestamp < lowestTimeStamp )
						{
							removeMe = i;
							lowestTimeStamp = tripwire->timestamp;
						}
					}
					if ( removeMe != -1 )
					{
						/* remove it... or blow it? */
						if ( &g_entities[foundTripWires[removeMe]] == NULL )
						{
							break;
						}
						else
						{
							G_FreeEntity( &g_entities[foundTripWires[removeMe]] );
						}
						foundTripWires[removeMe] = ENTITYNUM_NONE;
						tripcount--;
					}
					else
					{
						break;
					}
				}
				/* now make the new one */
				grenade->classname = "tripwire";
				if(rpg_dmgFlags.integer & 8) { 
					grenade->splashDamage = GRENADE_SPLASH_DAM*2;
					grenade->splashRadius = GRENADE_SPLASH_RAD*2;
				} else {
					grenade->splashDamage = 0;
					grenade->splashRadius = 0;

				}
				grenade->s.pos.trType = TR_LINEAR;
				grenade->nextthink = level.time + 1000; /* How long 'til she blows */
				grenade->count = 1; 			/* tell it it's a tripwire for when it sticks */
				grenade->timestamp = level.time; 	/* remember when we placed it */
				grenade->s.otherEntityNum2 = ent->client->sess.sessionTeam;
			}
			else
			{
				grenade->classname = "grenade_alt_projectile";
				if(rpg_dmgFlags.integer & 8) {
					grenade->splashDamage = GRENADE_SPLASH_DAM;
					grenade->splashRadius = GRENADE_SPLASH_RAD;
				} else {
					grenade->splashDamage = 0;
					grenade->splashRadius = 0;
				}
				grenade->s.pos.trType = TR_GRAVITY;
				grenade->nextthink = level.time + GRENADE_ALT_TIME; /* How long 'til she blows */
			}
			grenade->think = grenadeSpewShrapnel;
			grenade->s.eFlags |= EF_MISSILE_STICK;
			VectorScale( dir, 1000, grenade->s.pos.trDelta );

			grenade->damage = (rpg_dmgFlags.integer & 8) ? (GRENADE_ALT_DAMAGE*DMG_VAR) : (grenade->damage = 0);
			grenade->methodOfDeath = MOD_GRENADE_ALT;
			grenade->splashMethodOfDeath = MOD_GRENADE_ALT_SPLASH;
			grenade->s.eType = ET_ALT_MISSILE;

			/* RPG-X: RedTechie - Moved here to stop entities from being sucked up */
			grenade->r.svFlags = SVF_USE_CURRENT_ORIGIN;
			grenade->s.weapon = WP_8;
			grenade->r.ownerNum = ent->s.number;
			grenade->parent = ent;

			VectorSet(grenade->r.mins, -GRENADE_SIZE, -GRENADE_SIZE, -GRENADE_SIZE);
			VectorSet(grenade->r.maxs, GRENADE_SIZE, GRENADE_SIZE, GRENADE_SIZE);

			grenade->clipmask = MASK_SHOT;

			grenade->s.pos.trTime = level.time;		/* move a bit on the very first frame */
			VectorCopy( start, grenade->s.pos.trBase );
			SnapVector( grenade->s.pos.trBase );		/* save net bandwidth */
			
			SnapVector( grenade->s.pos.trDelta );		/* save net bandwidth */
			VectorCopy (start, grenade->r.currentOrigin);

			VectorCopy( start, grenade->pos2 );
		}
		else
		{
			/* RPG-X: RedTechie - Check to see if there admin if so grant them effects gun */
			if( IsAdmin(ent) && (rpg_effectsgun.integer == 1))
			{
				VectorMA (muzzle, MAXRANGE_CRIFLE, forward, end);
				trap_Trace (&tr, muzzle, NULL, NULL, end, ent->s.number, MASK_SHOT );

				/*
 				 * TiM : FX Gun additional effects.
				 * Okay... screw the generic args. it's giving me a headache
				 * Case in this case... harhar is teh solution
				 */
				if ( ent->client->fxGunData.eventNum > 0 ) 
				{
					fxGunData_t *fxGunData = &ent->client->fxGunData;

					/* set the entity event */
					tent = G_TempEntity( tr.endpos, fxGunData->eventNum );
					
					/* based on the event, add additional args */
					switch ( fxGunData->eventNum ) {
						/* sparks */
						case EV_FX_SPARK:
							/* Direction vector based off of trace normal */
							VectorCopy( tr.plane.normal, tent->s.angles2 );
							VectorShort( tent->s.angles2 );

							/* spark interval */
							tent->s.time2 = fxGunData->arg_float1;
							/* spark time length */
							tent->s.time = fxGunData->arg_int2;
							break;
						case EV_FX_STEAM:
							/* Direction vector based off of trace normal */
							VectorCopy( tr.plane.normal, tent->s.angles2 );
							VectorShort( tent->s.angles2 );
							/* time length */
							tent->s.time = fxGunData->arg_int2;
							break;
						case EV_FX_FIRE:
							VectorCopy( tr.plane.normal, tent->s.angles2 );
							VectorShort( tent->s.angles2 );
							tent->s.time = fxGunData->arg_int1;
							tent->s.time2 = fxGunData->arg_int2;
							break;
						case EV_FX_SHAKE:
							VectorCopy( tr.plane.normal, tent->s.angles2 );
							VectorShort( tent->s.angles2 );
							tent->s.time = fxGunData->arg_int1;
							tent->s.time2 = fxGunData->arg_int2;
							break;
						case EV_FX_CHUNKS:
							/* normal direction */
							VectorCopy( tr.plane.normal, tent->s.angles2 );
							VectorShort( tent->s.angles2 );	

							/* scale/radius */
							tent->s.time2 = fxGunData->arg_int1;
							/* material type */
							tent->s.powerups = fxGunData->arg_int2;
							break;
						case EV_FX_DRIP:
							/* type of drip */
							tent->s.time2 = fxGunData->arg_int1;
							/* degree of drippiness */
							tent->s.angles2[0] = fxGunData->arg_float1;
							/* length of effect */
							tent->s.powerups = fxGunData->arg_int2;
							break;
						case EV_FX_SMOKE:
							/* Direction vector based off of trace normal */
							VectorCopy( tr.plane.normal, tent->s.angles2 );
							VectorShort( tent->s.angles2 );
							/* smoke radius */
							tent->s.time = fxGunData->arg_int1;
							/* killtime  */
							tent->s.time2 = fxGunData->arg_int2;

							/* set ent origin for dir calcs */
							VectorCopy( tent->s.origin, tent->s.origin2 );
							/* VectorMA( tent->s.origin2, 6, tr.plane.normal, tent->s.origin2 ); */
							tent->s.origin2[2] += 6;
							break;
						case EV_FX_SURFACE_EXPLOSION:
							/* radius */
							tent->s.angles2[0] = fxGunData->arg_float1;
							/* camera shake */
							tent->s.angles2[1] = fxGunData->arg_float2;
							/* orient the dir to the plane we shot at */
							VectorCopy( tr.plane.normal, tent->s.origin2 );
							/* Meh... generic hardcoded data for the rest lol */
							tent->s.time2 = 0;
							break;
						case EV_FX_ELECTRICAL_EXPLOSION:
							/* Set direction */
							VectorCopy( tr.plane.normal, tent->s.origin2 );
							/* Set Radius */
							tent->s.angles2[0] = fxGunData->arg_float1;
							break;
					}

					/* Little hack to make the Detpack sound global */
					if ( fxGunData->eventNum == EV_DETPACK ) {
						gentity_t	*te;
						te = G_TempEntity( tr.endpos, EV_GLOBAL_SOUND );
						te->s.eventParm = G_SoundIndex( "sound/weapons/explosions/detpakexplode.wav" );
						te->r.svFlags |= SVF_BROADCAST;
					}
				}
				else {
					tent = G_TempEntity( tr.endpos, EV_EFFECTGUN_SHOOT );
				}
				
				tent->s.eFlags |= EF_FIRING;
				
			}else{
				/* RPG-X: RedTechie - Moved here to stop entities from being sucked up */
				grenade = G_Spawn();
			
				/* kef -- make sure count is 0 so it won't get its bounciness removed like the tetrion projectile */
				grenade->count = 0;


				grenade->classname = "grenade_projectile";
				grenade->nextthink = level.time + GRENADE_TIME; /* How long 'til she blows */
				grenade->think = grenadeExplode;
				grenade->s.eFlags |= EF_BOUNCE_HALF;
				VectorScale( dir, GRENADE_VELOCITY, grenade->s.pos.trDelta );
				grenade->s.pos.trType = TR_GRAVITY;

				if(rpg_dmgFlags.integer & 8) {
					grenade->damage = GRENADE_DAMAGE*DMG_VAR;
					grenade->splashDamage = GRENADE_SPLASH_DAM;
					grenade->splashRadius = GRENADE_SPLASH_RAD;
				} else {
					grenade->damage = 0;
					grenade->splashDamage = 0;
					grenade->splashRadius = 0;
				}
				grenade->methodOfDeath = MOD_GRENADE;
				grenade->splashMethodOfDeath = MOD_GRENADE_SPLASH;
				grenade->s.eType = ET_MISSILE;

				/* RPG-X: RedTechie - Moved here to stop entities from being sucked up */
				grenade->r.svFlags = SVF_USE_CURRENT_ORIGIN;
				grenade->s.weapon = WP_8;
				grenade->r.ownerNum = ent->s.number;
				grenade->parent = ent;

				VectorSet(grenade->r.mins, -GRENADE_SIZE, -GRENADE_SIZE, -GRENADE_SIZE);
				VectorSet(grenade->r.maxs, GRENADE_SIZE, GRENADE_SIZE, GRENADE_SIZE);

				grenade->clipmask = MASK_SHOT;

				grenade->s.pos.trTime = level.time;		/* move a bit on the very first frame */
				VectorCopy( start, grenade->s.pos.trBase );
				SnapVector( grenade->s.pos.trBase );		/* save net bandwidth */
				
				SnapVector( grenade->s.pos.trDelta );		/* save net bandwidth */
				VectorCopy (start, grenade->r.currentOrigin);

				VectorCopy( start, grenade->pos2 );
			}
		}

		G_LogWeaponFire(ent->s.number, WP_8);
	}else{
		G_LogPrintf("RPG-X WARNING: Max entities about to be hit! Restart the server ASAP or suffer a server crash!\n");
		trap_SendServerCommand( -1, va("print \"^1RPG-X WARNING: Max entities about to be hit! Restart the server ASAP or suffer a server crash!\n\""));
	}
}
コード例 #21
0
ファイル: m_ojoin.c プロジェクト: BackupTheBerlios/shadowircd
/* mo_ojoin()
 *      parv[0] = sender prefix
 *      parv[1] = channels separated by commas (#ifdef OJOIN_MULTIJOIN)
 */
static void
mo_ojoin(struct Client *client_p, struct Client *source_p,
         int parc, char *parv[])
{
    struct Channel *chptr;
    char *name = parv[1], modeletter;
#ifdef OJOIN_MULTIJOIN
    char *t;
#endif
    short move_me = 1;
    unsigned int tmp_flags;

    /* admins only */
    if (!IsAdmin(source_p))
    {
        sendto_one(source_p, form_str(ERR_NOPRIVILEGES),
                   me.name, source_p->name);
        return;
    }

#ifdef OJOIN_MULTIJOIN
    for (name = strtoken (&t, name, ","); name;
            name = strtoken (&t, NULL, ","))
    {
#endif

        move_me = 1;

        switch (*name)
        {
#ifndef DISABLE_CHAN_OWNER
        case '!':
            tmp_flags = CHFL_CHANOWNER;
            modeletter = 'u';
            name++;
            break;
#endif
        case '@':
            tmp_flags = CHFL_CHANOP;
            modeletter = 'o';
            name++;
            break;
        case '+':
            tmp_flags = CHFL_VOICE;
            modeletter = 'v';
            name++;
            break;
        case '%':
            tmp_flags = CHFL_HALFOP;
            modeletter = 'h';
            name++;
            break;
        case '#':
        case '&':
            tmp_flags = 0;
            modeletter = '\0';
            break;

        /* We're not joining a channel, or we don't know the mode,
        * what ARE we joining? */
        default:
            sendto_one (source_p, form_str(ERR_NOSUCHCHANNEL),
                        me.name, source_p->name, name);

#ifdef OJOIN_MULTIJOIN
            continue;
#else
            return;
#endif
        }

        /* Error checking here */

        if ((chptr = hash_find_channel(name)) == NULL)
        {
            sendto_one(source_p, form_str(ERR_NOSUCHCHANNEL),
                       me.name, source_p->name, name);
        }

        else if (IsMember(source_p, chptr))
        {
            sendto_one(source_p, ":%s NOTICE %s :Please part %s before using OJOIN",
                       me.name, source_p->name, name);
        }

        else
        {
            if (move_me == 1)
                name--;

            add_user_to_channel(chptr, source_p, tmp_flags);

            if (chptr->chname[0] == '#')
            {
                sendto_server(client_p, CAP_TS6, NOCAPS,
                              ":%s SJOIN %lu %s + :%c%s",
                              me.id, (unsigned long)chptr->channelts, chptr->chname,
                              (modeletter != '\0') ? *name : ' ',
                              source_p->id);
                sendto_server(client_p, NOCAPS, CAP_TS6,
                              ":%s SJOIN %lu %s + :%c%s", me.name,
                              (unsigned long)chptr->channelts,
                              chptr->chname, (modeletter != '\0') ? *name : ' ',
                              source_p->name);
            }

            sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s",
                                 source_p->name,
                                 source_p->username,
                                 GET_CLIENT_HOST(source_p),
                                 chptr->chname);

            if (modeletter != '\0')
            {
                sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +%c %s",
                                     me.name, chptr->chname, modeletter, source_p->name);
            }

            /* send the topic... */
            if (chptr->topic != NULL)
            {
                sendto_one(source_p, form_str(RPL_TOPIC),
                           me.name, source_p->name, chptr->chname,
                           chptr->topic);
                sendto_one(source_p, form_str(RPL_TOPICWHOTIME),
                           me.name, source_p->name, chptr->chname,
                           chptr->topic_info, chptr->topic_time);
            }

            source_p->localClient->last_join_time = CurrentTime;
            channel_member_names(source_p, chptr, 1);
        }
#ifdef OJOIN_MULTIJOIN
    }
#endif
}
コード例 #22
0
ファイル: m_ircops.c プロジェクト: diegoagudo/taps-ircd
/*
** m_ircops() By Claudio
** Rewritten by HAMLET
**   Lists online IRCOps
**
*/
int m_ircops(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
  struct Client *acptr;
  char *status;
  char buf[BUFSIZE];
  int locals = 0, globals = 0;

  if (!IRCopsForAll && !IsPrivileged(cptr))
    {
      sendto_one(sptr, form_str(ERR_NOPRIVILEGES), me.name, parv[0]);
      return 0;
    }
	
  strcpy(buf, "========================================================================================");
  sendto_one(sptr, form_str(RPL_LISTS), me.name, parv[0], buf);
  strcpy(buf, "\2Nick                           Status                           Server\2");
  sendto_one(sptr, form_str(RPL_LISTS), me.name, parv[0], buf);
  strcpy(buf, "----------------------------------------------------------------------------------------");
  sendto_one(sptr, form_str(RPL_LISTS), me.name, parv[0], buf);
  for (acptr = GlobalClientList; acptr; acptr = acptr->next)
	{
  	  if (!IsService(acptr) && !IsStealth(acptr) &&  IsAnOper(acptr)
  	     && (!IsHideOper(acptr) || IsAnOper(sptr)) ) {
    
          if (!acptr->user) continue;

	  if (IsTechAdmin(acptr)) 
		status = "Technical Administrator";
	  else if (IsNetAdmin(acptr)) 
		status = "Network Administrator";
	  else if (IsSAdmin(acptr)) 
		status = "Services Administrator";
	  else if (IsAdmin(acptr)) 
		status = "Server Administrator";		
	  else if(IsOper(acptr))
		status = "Global IRC Operator"; 
	  else
		status = "Local IRC Operator";  	
	  

/* vlinks on /IRCops
* code by openglx
* idea to this by Midnight_Commander
*/
    if (acptr->user && acptr->user->vlink)
      {
        ircsprintf(buf, "\2%-29s\2  %-23s  %-6s  %s", acptr->name ? acptr->name : "<unknown>", status,
                              acptr->user->away ? "(AWAY)" : "", acptr->user->vlink->name);
      }
    else
      {
      ircsprintf(buf, "\2%-29s\2  %-23s  %-6s  %s", acptr->name ? acptr->name : "<unknown>", status,
                            acptr->user->away ? "(AWAY)" : "", acptr->user->server);
      }
      
/* end of the vlink support code */
                                                                                                 
          sendto_one(sptr, form_str(RPL_LISTS), me.name, parv[0], buf);
          sendto_one(sptr, form_str(RPL_LISTS), me.name, parv[0], "-");
          if (IsOper(acptr)) globals++;
          else locals++;
    	}
    }
 
  ircsprintf(buf, "Total: \2%d\2 IRCOp%s connected - \2%d\2 Globa%s, \2%d\2 Loca%s", globals+locals,
                        (globals+locals) > 1 ? "s" : "",
                        globals, globals > 1 ? "ls" : "l", locals, locals > 1 ? "ls" : "l");
  sendto_one(sptr, form_str(RPL_LISTS), me.name, parv[0], buf);
  strcpy(buf, "========================================================================================");
  sendto_one(sptr, form_str(RPL_LISTS), me.name, parv[0], buf);
  sendto_one(sptr, form_str(RPL_ENDOFLISTS), me.name, parv[0], "IRCOPS");
  return 0;
}
コード例 #23
0
/*
 * mo_connect - CONNECT command handler
 * 
 * Added by Jto 11 Feb 1989
 *
 * m_connect
 *      parv[0] = sender prefix
 *      parv[1] = servername
 *      parv[2] = port number
 *      parv[3] = remote server
 */
static void
mo_connect(struct Client* client_p, struct Client* source_p,
           int parc, char* parv[])
{
  int port;
  int tmpport;
  struct ConfItem *conf = NULL;
  struct AccessItem *aconf = NULL;
  struct Client *target_p;

  /* always privileged with handlers */
  if (MyConnect(source_p) && !IsOperRemote(source_p) && parc > 3)
  {
    sendto_one(source_p, form_str(ERR_NOPRIVS),
               me.name, source_p->name, "connect");
    return;
  }

  if (hunt_server(client_p, source_p,
                  ":%s CONNECT %s %s :%s", 3, parc, parv) != HUNTED_ISME)
    return;

  if (*parv[1] == '\0')
  {
    sendto_one(source_p, form_str(ERR_NEEDMOREPARAMS),
               me.name, source_p->name, "CONNECT");
    return;
  }

  if ((target_p = find_server(parv[1])))
  {
    sendto_one(source_p,
	       ":%s NOTICE %s :Connect: Server %s already exists from %s.",
               me.name, source_p->name, parv[1], target_p->from->name);
    return;
  }

  /*
   * try to find the name, then host, if both fail notify ops and bail
   */
  if ((conf = find_matching_name_conf(SERVER_TYPE,
				      parv[1], NULL, NULL, 0)) != NULL)
    aconf = (struct AccessItem *)map_to_conf(conf);
  else if ((conf = find_matching_name_conf(SERVER_TYPE,
					   NULL, NULL, parv[1], 0)) != NULL)
    aconf = (struct AccessItem *)map_to_conf(conf);
  
  if (conf == NULL)
  {
    sendto_one(source_p,
	       ":%s NOTICE %s :Connect: Host %s not listed in ircd.conf",
	       me.name, source_p->name, parv[1]);
    return;
  }
    
  /* Get port number from user, if given. If not specified,
   * use the default form configuration structure. If missing
   * from there, then use the precompiled default.
   */
  tmpport = port = aconf->port;

  if (parc > 2 && !EmptyString(parv[2]))
  {
    if ((port = atoi(parv[2])) <= 0)
    {
      sendto_one(source_p, ":%s NOTICE %s :Connect: Illegal port number",
                 me.name, source_p->name);
      return;
    }
  }
  else if (port <= 0 && (port = PORTNUM) <= 0)
  {
    sendto_one(source_p, ":%s NOTICE %s :Connect: missing port number",
               me.name, source_p->name);
    return;
  }

  if (find_servconn_in_progress(conf->name))
  {
    sendto_one(source_p, ":%s NOTICE %s :Connect: a connection to %s "
               "is already in progress.", me.name, source_p->name, conf->name);
    return;
  }

  /*
   * Notify all operators about remote connect requests
   */
  ilog(L_TRACE, "CONNECT From %s : %s %s", 
       source_p->name, parv[1], parv[2] ? parv[2] : "");

  aconf->port = port;

  /* at this point we should be calling connect_server with a valid
   * C:line and a valid port in the C:line
   */
  if (serv_connect(aconf, source_p))
  {
    if (!ConfigServerHide.hide_server_ips && IsAdmin(source_p))
      sendto_one(source_p, ":%s NOTICE %s :*** Connecting to %s[%s].%d",
                 me.name, source_p->name, aconf->host,
                 conf->name, aconf->port);
    else
      sendto_one(source_p, ":%s NOTICE %s :*** Connecting to %s.%d",
                 me.name, source_p->name, conf->name, aconf->port);
  }
  else
  {
    sendto_one(source_p, ":%s NOTICE %s :*** Couldn't connect to %s.%d",
               me.name, source_p->name, conf->name, aconf->port);
  }

  /* client is either connecting with all the data it needs or has been
   * destroyed
   */
  aconf->port = tmpport;
}
コード例 #24
0
ファイル: User.cpp プロジェクト: b3rend/znc
CConfig CUser::ToConfig() {
	CConfig config;
	CConfig passConfig;

	CString sHash;
	switch (m_eHashType) {
	case HASH_NONE:
		sHash = "Plain";
		break;
	case HASH_MD5:
		sHash = "MD5";
		break;
	case HASH_SHA256:
		sHash = "SHA256";
		break;
	}
	passConfig.AddKeyValuePair("Salt", m_sPassSalt);
	passConfig.AddKeyValuePair("Method", sHash);
	passConfig.AddKeyValuePair("Hash", GetPass());
	config.AddSubConfig("Pass", "password", passConfig);

	config.AddKeyValuePair("Nick", GetNick());
	config.AddKeyValuePair("AltNick", GetAltNick());
	config.AddKeyValuePair("Ident", GetIdent());
	config.AddKeyValuePair("RealName", GetRealName());
	config.AddKeyValuePair("BindHost", GetBindHost());
	config.AddKeyValuePair("DCCBindHost", GetDCCBindHost());
	config.AddKeyValuePair("QuitMsg", GetQuitMsg());
	if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())
		config.AddKeyValuePair("StatusPrefix", GetStatusPrefix());
	config.AddKeyValuePair("Skin", GetSkinName());
	config.AddKeyValuePair("Language", GetLanguage());
	config.AddKeyValuePair("ChanModes", GetDefaultChanModes());
	config.AddKeyValuePair("Buffer", CString(GetBufferCount()));
	config.AddKeyValuePair("KeepBuffer", CString(KeepBuffer()));
	config.AddKeyValuePair("MultiClients", CString(MultiClients()));
	config.AddKeyValuePair("DenyLoadMod", CString(DenyLoadMod()));
	config.AddKeyValuePair("Admin", CString(IsAdmin()));
	config.AddKeyValuePair("DenySetBindHost", CString(DenySetBindHost()));
	config.AddKeyValuePair("TimestampFormat", GetTimestampFormat());
	config.AddKeyValuePair("AppendTimestamp", CString(GetTimestampAppend()));
	config.AddKeyValuePair("PrependTimestamp", CString(GetTimestampPrepend()));
	config.AddKeyValuePair("TimezoneOffset", CString(m_fTimezoneOffset));
	config.AddKeyValuePair("JoinTries", CString(m_uMaxJoinTries));
	config.AddKeyValuePair("MaxJoins", CString(m_uMaxJoins));
	config.AddKeyValuePair("IRCConnectEnabled", CString(GetIRCConnectEnabled()));

	// Allow Hosts
	if (!m_ssAllowedHosts.empty()) {
		for (set<CString>::iterator it = m_ssAllowedHosts.begin(); it != m_ssAllowedHosts.end(); ++it) {
			config.AddKeyValuePair("Allow", *it);
		}
	}

	// CTCP Replies
	if (!m_mssCTCPReplies.empty()) {
		for (MCString::const_iterator itb = m_mssCTCPReplies.begin(); itb != m_mssCTCPReplies.end(); ++itb) {
			config.AddKeyValuePair("CTCPReply", itb->first.AsUpper() + " " + itb->second);
		}
	}

	// Modules
	CModules& Mods = GetModules();

	if (!Mods.empty()) {
		for (unsigned int a = 0; a < Mods.size(); a++) {
			CString sArgs = Mods[a]->GetArgs();

			if (!sArgs.empty()) {
				sArgs = " " + sArgs;
			}

			config.AddKeyValuePair("LoadModule", Mods[a]->GetModName() + sArgs);
		}
	}

	// Networks
	for (unsigned int d = 0; d < m_vIRCNetworks.size(); d++) {
		CIRCNetwork *pNetwork = m_vIRCNetworks[d];
		config.AddSubConfig("Network", pNetwork->GetName(), pNetwork->ToConfig());
	}

	return config;
}
コード例 #25
0
ファイル: m_challenge.c プロジェクト: NX-Andro/nefarious
int m_challenge(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
{
#ifdef USE_SSL
  struct ConfItem *aconf;
  RSA *rsa_public_key;
  BIO *file = NULL;
  char *challenge = NULL;
  char *name;
  char *tmpname;
  char             chan[CHANNELLEN-1];
  char*            join[2];
  int nl;
  struct Flags old_mode = cli_flags(sptr);

  if (!MyUser(sptr))
    return 0;

  if (parc < 2)
    return need_more_params(sptr, "CHALLENGE");

  if (parc > 2) { /* This is a remote OPER Request */
    struct Client *srv;
    if (!string_has_wildcards(parv[1]))
      srv = FindServer(parv[1]);
    else
      srv = find_match_server(parv[1]);

    if (!feature_bool(FEAT_REMOTE_OPER))
      return send_reply(sptr, ERR_NOOPERHOST);

    if (!srv)
      return send_reply(sptr, ERR_NOOPERHOST);

    if (IsMe(srv)) {
      parv[1] = parv[2];
    } else {
      sendcmdto_one(sptr, CMD_CHALLENGE, srv, "%C %s", srv, parv[2]);
      return 0;
    }
  }

  /* if theyre an oper, reprint oper motd and ignore */
  if (IsOper(sptr))
  {
    send_reply(sptr, RPL_YOUREOPER);
    if (feature_bool(FEAT_OPERMOTD))
      m_opermotd(sptr, sptr, 1, parv);
  }

  if (*parv[1] == '+')
  {
    /* Ignore it if we aren't expecting this... -A1kmm */
    if (cli_user(sptr)->response == NULL)
      return 0;

    if (ircd_strcmp(cli_user(sptr)->response, ++parv[1]))
    {
      send_reply(sptr, ERR_PASSWDMISMATCH);
      sendto_allops(&me, SNO_OLDREALOP, "Failed OPER attempt by %s (%s@%s) (Password Incorrect)",
                         parv[0], cli_user(sptr)->realusername, cli_sockhost(sptr));
      tmpname = strdup(cli_user(sptr)->auth_oper);
      failed_challenge_notice(sptr, tmpname, "challenge failed");
      return 0;
    }

    name = strdup(cli_user(sptr)->auth_oper);
     
    aconf = find_conf_exact(cli_user(sptr)->auth_oper, cli_user(sptr)->realusername,
                            MyUser(sptr) ? cli_sockhost(sptr) :
                            cli_user(sptr)->realhost, CONF_OPS);

    if (!aconf)
      aconf = find_conf_exact(cli_user(sptr)->auth_oper, cli_user(sptr)->realusername,
                              ircd_ntoa((const char*) &(cli_ip(sptr))), CONF_OPS);

    if (!aconf)
      aconf = find_conf_cidr(cli_user(sptr)->auth_oper, cli_user(sptr)->realusername,
                              cli_ip(sptr), CONF_OPS);

    if (!aconf)
    {
      send_reply(sptr, ERR_NOOPERHOST);
      sendto_allops(&me, SNO_OLDREALOP, "Failed OPER attempt by %s (%s@%s) (No O:line)",
                         parv[0], cli_user(sptr)->realusername, cli_sockhost(sptr));
      return 0;
    }

    if (CONF_LOCOP == aconf->status) {
      ClearOper(sptr);
      SetLocOp(sptr);
    }
    else {
      /*
       * prevent someone from being both oper and local oper
       */
      ClearLocOp(sptr);
      if (!feature_bool(FEAT_OPERFLAGS) || !(aconf->port & OFLAG_ADMIN)) {
        /* Global Oper */
        SetOper(sptr);
        ClearAdmin(sptr);
      } else {
        /* Admin */
        SetOper(sptr);
        OSetGlobal(sptr);
        SetAdmin(sptr);
      }
      ++UserStats.opers;
    }
    cli_handler(cptr) = OPER_HANDLER;

    if (!feature_bool(FEAT_OPERFLAGS) || (aconf->port & OFLAG_WHOIS)) {
      OSetWhois(sptr);
    }
    if (!feature_bool(FEAT_OPERFLAGS) || (aconf->port & OFLAG_IDLE)) {
      OSetIdle(sptr);
    }
    if (!feature_bool(FEAT_OPERFLAGS) || (aconf->port & OFLAG_XTRAOP)) {
      OSetXtraop(sptr);
    }
    if (!feature_bool(FEAT_OPERFLAGS) || (aconf->port & OFLAG_HIDECHANS)) {
      OSetHideChans(sptr);
    }

    SetFlag(sptr, FLAG_WALLOP);
    SetFlag(sptr, FLAG_SERVNOTICE);
    SetFlag(sptr, FLAG_DEBUG);

    if (!IsAdmin(sptr))
      cli_oflags(sptr) = aconf->port;

    set_snomask(sptr, SNO_OPERDEFAULT, SNO_ADD);
    client_set_privs(sptr, aconf);
    cli_max_sendq(sptr) = 0; /* Get the sendq from the oper's class */
    send_umode_out(cptr, sptr, &old_mode, HasPriv(sptr, PRIV_PROPAGATE));
    send_reply(sptr, RPL_YOUREOPER);

    if (IsAdmin(sptr)) {
      sendto_allops(&me, SNO_OLDSNO, "%s (%s@%s) is now an IRC Administrator",
                    parv[0], cli_user(sptr)->username, cli_sockhost(sptr));

      /* Autojoin admins to admin channel and oper channel (if enabled) */
      if (feature_bool(FEAT_AUTOJOIN_ADMIN)) {
        if (feature_bool(FEAT_AUTOJOIN_ADMIN_NOTICE))
              sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :%s", sptr, feature_str(FEAT_AUTOJOIN_ADMIN_NOTICE_VALUE));

        ircd_strncpy(chan, feature_str(FEAT_AUTOJOIN_ADMIN_CHANNEL), CHANNELLEN-1);
        join[0] = cli_name(sptr);
        join[1] = chan;
        m_join(sptr, sptr, 2, join);
      }
      if (feature_bool(FEAT_AUTOJOIN_OPER) && IsOper(sptr)) {
        if (feature_bool(FEAT_AUTOJOIN_OPER_NOTICE))
              sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :%s", sptr, feature_str(FEAT_AUTOJOIN_OPER_NOTICE_VALUE));

        ircd_strncpy(chan, feature_str(FEAT_AUTOJOIN_OPER_CHANNEL), CHANNELLEN-1);
        join[0] = cli_name(sptr);
        join[1] = chan;
        m_join(sptr, sptr, 2, join);
      }
    } else {
      sendto_allops(&me, SNO_OLDSNO, "%s (%s@%s) is now an IRC Operator (%c)",
                         parv[0], cli_user(sptr)->username, cli_sockhost(sptr),
                         IsOper(sptr) ? 'O' : 'o');

      if (feature_bool(FEAT_AUTOJOIN_OPER) && IsOper(sptr)) {
        if (feature_bool(FEAT_AUTOJOIN_OPER_NOTICE))
              sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :%s", sptr, feature_str(FEAT_AUTOJOIN_OPER_NOTICE_VALUE));

        ircd_strncpy(chan, feature_str(FEAT_AUTOJOIN_OPER_CHANNEL), CHANNELLEN-1);
        join[0] = cli_name(sptr);
        join[1] = chan;
        m_join(sptr, sptr, 2, join);
      }
    }

    if (feature_bool(FEAT_OPERMOTD))
      m_opermotd(sptr, sptr, 1, parv);

    log_write(LS_OPER, L_INFO, 0, "OPER (%s) by (%#C)", name, sptr);

    ircd_snprintf(0, cli_user(sptr)->response, BUFSIZE+1, "%s", "");
    return 0;
  }

  ircd_snprintf(0, cli_user(sptr)->response, BUFSIZE+1, "%s", "");
  ircd_snprintf(0, cli_user(sptr)->auth_oper, NICKLEN+1, "%s", "");

  aconf = find_conf_exact(parv[1], cli_user(sptr)->realusername,
                          cli_user(sptr)->realhost, CONF_OPS);

  if (!aconf)
    aconf = find_conf_exact(parv[1], cli_user(sptr)->realusername,
                            ircd_ntoa((const char*) &(cli_ip(sptr))), CONF_OPS);

  if (!aconf)
    aconf = find_conf_cidr(parv[1], cli_user(sptr)->realusername,
                            cli_ip(sptr), CONF_OPS);

  if (aconf == NULL)
  {
    send_reply(sptr, ERR_NOOPERHOST);
    failed_challenge_notice(sptr, parv[1], "No o:line");
    sendto_allops(&me, SNO_OLDREALOP, "Failed OPER attempt by %s (%s@%s) (No O:line)",
                       parv[0], cli_user(sptr)->realusername, cli_sockhost(sptr));
    return 0;
  }

  if (!(aconf->port & OFLAG_RSA))
  {
    send_reply(sptr, RPL_NO_CHALL);
    return 0;
  }

  if (!verify_sslclifp(sptr, aconf))
  {
    sendto_allops(&me, SNO_OLDREALOP,
           "Failed OPER attempt by %s (%s@%s) (SSL Fingerprint Missmatch)",
           parv[0], cli_user(sptr)->realusername,
           cli_user(sptr)->realhost);
    send_reply(sptr, ERR_SSLCLIFP);
    return 0;
  }

  if ((file = BIO_new_file(aconf->passwd, "r")) == NULL)
  {
    send_reply(sptr, RPL_NO_KEY);
    return 0;
  }

  rsa_public_key = (RSA *)PEM_read_bio_RSA_PUBKEY(file, NULL, 0, NULL);
  if (rsa_public_key == NULL)
     return send_reply(sptr, RPL_INVALID_KEY);


  if (!generate_challenge(&challenge, rsa_public_key, sptr)) {
      Debug((DEBUG_DEBUG, "generating challenge sum (%s)", challenge));
      send_reply(sptr, RPL_RSACHALLENGE, challenge);
      ircd_snprintf(0, cli_user(sptr)->auth_oper, NICKLEN + 1, "%s", aconf->name);
  }
  nl = BIO_set_close(file, BIO_CLOSE);
  BIO_free(file);

  return 1;
#else
  return 1;
#endif
}
コード例 #26
0
ファイル: ns_clients.hpp プロジェクト: DmitrySigaev/ncbi
 // The admin check is done per connection so there is no need
 // to reset it when a queue is changed or when a queue is from a job
 // key.
 void ResetPassedCheck(void)
 { if (IsAdmin()) { m_PassedChecks = 0; SetPassedChecks(eNS_Admin); }
   else           { m_PassedChecks = 0; } }
コード例 #27
0
ファイル: m_who.c プロジェクト: Cloudxtreme/bahamut
int m_who(aClient *cptr, aClient *sptr, int parc, char *parv[])
{
    aClient *ac;
    chanMember *cm;
    Link *lp;
    int shown=0, i=0, showall=IsAnOper(sptr);
    char status[4];

    /* drop nonlocal clients */
    if(!MyClient(sptr))
	return 0;
    
    if(!build_searchopts(sptr, parc-1, parv+1))
	return 0; /* /who was no good */
    
    if(wsopts.gcos!=NULL && (strchr(wsopts.gcos, '?'))==NULL &&
       (strchr(wsopts.gcos, '*'))==NULL)
	gchkfn=mycmp;
    else
	gchkfn=match;
    if(wsopts.nick!=NULL && (strchr(wsopts.nick, '?'))==NULL &&
       (strchr(wsopts.nick, '*'))==NULL)
	nchkfn=mycmp;
    else
	nchkfn=match;
    if(wsopts.user!=NULL && (strchr(wsopts.user, '?'))==NULL &&
       (strchr(wsopts.user, '*'))==NULL)
	uchkfn=mycmp;
    else
	uchkfn=match;
    if(wsopts.host!=NULL && (strchr(wsopts.host, '?'))==NULL &&
       (strchr(wsopts.host, '*'))==NULL)
	hchkfn=mycmp;
    else
	hchkfn=match;

    if(wsopts.ip!=NULL && (strchr(wsopts.ip, '?'))==NULL &&
       (strchr(wsopts.ip, '*'))==NULL)
	ichkfn=mycmp;
    else
	ichkfn=match;

    if(wsopts.channel!=NULL)
    {
	if(IsMember(sptr,wsopts.channel) && (!(wsopts.channel->mode.mode & MODE_AUDITORIUM) ||
           is_chan_opvoice(sptr, wsopts.channel)))
	    showall=1;
	else if(SecretChannel(wsopts.channel) && IsAdmin(sptr))
	    showall=1;
	else if(!SecretChannel(wsopts.channel) && IsAnOper(sptr))
	    showall=1;
	else
	    showall=0;
	if(showall || !SecretChannel(wsopts.channel))
	{
	    for(cm=wsopts.channel->members; cm; cm=cm->next)
	    {
		ac=cm->cptr;
		i=0;
		if(!chk_who(ac,showall))
		    continue;
		/* If we have channel flags set, verify they match */
		if(wsopts.channelflags && ((cm->flags & wsopts.channelflags) == 0))
		    continue;
		/* get rid of the pidly stuff first */
		/* wow, they passed it all, give them the reply...
		 * IF they haven't reached the max, or they're an oper */
		status[i++]=(ac->user->away==NULL ? 'H' : 'G');
		status[i]=(IsAnOper(ac) ? '*' : ((IsInvisible(ac) &&
						  IsOper(sptr)) ? '%' : 0));
		status[((status[i]) ? ++i : i)]=((cm->flags&CHFL_CHANOP) ? '@'
						 : ((cm->flags&CHFL_VOICE) ? 
						    '+' : 0));
		status[++i]=0;
		sendto_one(sptr, getreply(RPL_WHOREPLY), me.name, sptr->name,
			   wsopts.channel->chname, ac->user->username,
			   WHO_HOST(ac), WHO_SERVER(sptr, ac), ac->name, status,
			   WHO_HOPCOUNT(sptr, ac),
			   ac->info);
	    }
	}
	sendto_one(sptr, getreply(RPL_ENDOFWHO), me.name, sptr->name,
		   wsopts.channel->chname, "WHO");
	return 0;
    }
    /* if (for whatever reason) they gave us a nick with no
     * wildcards, just do a find_person, bewm! */
    else if(nchkfn==mycmp)
    {
	ac=find_person(wsopts.nick,NULL);
	if(ac!=NULL)
	{
	    if(!chk_who(ac,1))
	    {
		sendto_one(sptr, getreply(RPL_ENDOFWHO), me.name, sptr->name,
			   wsopts.host!=NULL ? wsopts.host : wsopts.nick, "WHO");
		return 0;
	    }
	    else
	    {
		status[0]=(ac->user->away==NULL ? 'H' : 'G');
		status[1]=(IsAnOper(ac) ? '*' : (IsInvisible(ac) &&
						 IsAnOper(sptr) ? '%' : 0));
		status[2]=0;
		sendto_one(sptr, getreply(RPL_WHOREPLY), me.name, sptr->name,
			   wsopts.show_chan ? first_visible_channel(ac, sptr)
			   : "*", ac->user->username, WHO_HOST(ac),
			   WHO_SERVER(sptr, ac), ac->name, status,
			   WHO_HOPCOUNT(sptr, ac),
			   ac->info);
		sendto_one(sptr, getreply(RPL_ENDOFWHO), me.name, sptr->name,
			   wsopts.host!=NULL ? wsopts.host : wsopts.nick, "WHO");
		return 0;
	    }
	}
	sendto_one(sptr, getreply(RPL_ENDOFWHO), me.name, sptr->name,
		   wsopts.host!=NULL ? wsopts.host : wsopts.nick, "WHO");
	return 0;
    }
    
    if(wsopts.search_chan)
    {
	for(lp = sptr->user->channel; lp; lp = lp->next)
	{
	    for(cm = lp->value.chptr->members; cm; cm = cm->next)
	    {
		ac = cm->cptr;
		if(!chk_who(ac, 1))
		    continue;
		
		if(shown==MAXWHOREPLIES && !IsAnOper(sptr))
		{
		    sendto_one(sptr, getreply(ERR_WHOLIMEXCEED), me.name,
			       sptr->name, MAXWHOREPLIES, "WHO");
		    break;
		}
		
		i = 0;
		status[i++]=(ac->user->away==NULL ? 'H' : 'G');
		status[i]=(IsAnOper(ac) ? '*' : ((IsInvisible(ac) &&
						  IsOper(sptr)) ? '%' : 0));
		status[((status[i]) ? ++i : i)]=((cm->flags&CHFL_CHANOP) ? 
						 '@' : ((cm->flags&CHFL_VOICE)
							? '+' : 0));
		status[++i]=0;
		sendto_one(sptr, getreply(RPL_WHOREPLY), me.name, sptr->name,
			   lp->value.chptr->chname, ac->user->username,
			   WHO_HOST(ac),WHO_SERVER(sptr, ac), ac->name,
			   status, WHO_HOPCOUNT(sptr, ac), ac->info);
		shown++;
	    }
	}
    }
    else
    {
	for(ac=client;ac;ac=ac->next)
	{
	    if(!chk_who(ac,showall))
		continue;
	    /* wow, they passed it all, give them the reply...
	     * IF they haven't reached the max, or they're an oper */
	    if(shown==MAXWHOREPLIES && !IsAnOper(sptr))
	    {
		sendto_one(sptr, getreply(ERR_WHOLIMEXCEED), me.name, 
			   sptr->name, MAXWHOREPLIES, "WHO");
		break; /* break out of loop so we can send end of who */
	    }
	    status[0]=(ac->user->away==NULL ? 'H' : 'G');
	    status[1]=(IsAnOper(ac) ? '*' : (IsInvisible(ac) && 
					     IsAnOper(sptr) ? '%' : 0));
	    status[2]=0;
	    sendto_one(sptr, getreply(RPL_WHOREPLY), me.name, sptr->name,
		       wsopts.show_chan ? first_visible_channel(ac, sptr) :
		       "*", ac->user->username, WHO_HOST(ac),
		       WHO_SERVER(sptr, ac), ac->name, status,
		       WHO_HOPCOUNT(sptr, ac), ac->info);
	    shown++;
	}
    }
    sendto_one(sptr, getreply(RPL_ENDOFWHO), me.name, sptr->name,
	       (wsopts.host!=NULL ? wsopts.host :
		(wsopts.nick!=NULL ? wsopts.nick :
		 (wsopts.user!=NULL ? wsopts.user :
		  (wsopts.gcos!=NULL ? wsopts.gcos :
		   (wsopts.server!=NULL ? wsopts.server->name :
		    "*"))))), "WHO");
    return 0;
}
コード例 #28
0
ファイル: GSIOTUserMgr.cpp プロジェクト: asdfjkl697/projects
// �û����ñ��
defGSReturn GSIOTUserMgr::CfgChange_User( GSIOTUser *const pUser, const defCfgOprt_ oprt, const bool FailedIsErr, bool doTRANSACTION )
{
	if( !pUser )
	{
		return defGSReturn_Err;
	}

	pUser->FixJid();
	pUser->FixName();

	std::string jid = pUser->GetKeyJid();

	if( IsAdmin(pUser) )
	{
		return defGSReturn_Err;
	}

	switch( oprt )
	{
	case defCfgOprt_Add:
	case defCfgOprt_Modify:
	case defCfgOprt_AddModify:
		break;

	case defCfgOprt_Delete:
		{
			return Delete_User( jid, FailedIsErr );
		}

	default:
		assert(false);
		return defGSReturn_Err;
	}

	GSIOTUser *pCurUser = GetUser( jid );
	if( pCurUser )
	{
		// modify or addmodify
		LOGMSG( "CfgChange_User(oprt=%d) isbeing, %s\r\n", oprt, jid.c_str() );

		// �޸�ʱ���������ú������ö��Ѿ�������Ȩ�ޱ�־�����ñ������Ȩ�޼�¼
		bool Pass_mapAuthAdd = false;
		//if( pUser->IsAllAuthCfg() && pCurUser->IsAllAuthCfg() )
		if( pUser->IsAllAuthCfg() )
		{
			Pass_mapAuthAdd = true;
		}

		// update
		if( defCfgOprt_Modify == oprt
			|| defCfgOprt_AddModify == oprt )
		{
			bool doUpdate = false;

			if( pUser->IsValidAttribute(GSIOTUser::defAttr_enable)
				&& pUser->GetEnable() != pCurUser->GetEnable() )
			{
				doUpdate = true;
				pCurUser->SetEnable( pUser->GetEnable() );
			}

			if( pUser->IsValidAttribute(GSIOTUser::defAttr_UserLevel)
				&& pUser->GetUserLevel() != pCurUser->GetUserLevel() )
			{
				doUpdate = true;
				pCurUser->SetUserLevel( pUser->GetUserLevel() );
			}

			if( pUser->IsValidAttribute(GSIOTUser::defAttr_NoticeGroup)
				&& pUser->get_UserFlag(defUserFlag_NoticeGroup) != pCurUser->get_UserFlag(defUserFlag_NoticeGroup) )
			{
				doUpdate = true;
				pCurUser->set_UserFlag( defUserFlag_NoticeGroup, pUser->get_UserFlag(defUserFlag_NoticeGroup) );
			}

			if( pUser->IsValidAttribute(GSIOTUser::defAttr_name)
				&& pUser->GetName() != pCurUser->GetName() )
			{
				doUpdate = true;
				pCurUser->SetName( pUser->GetName() );
			}

			if( doUpdate )
			{
				LOGMSG( "CfgChange_User(oprt=%d) do modify newenable=%d, newname=%s, newNoticeGroup=%d, jid=%s\r\n", oprt, pCurUser->GetEnable(), pCurUser->GetName().c_str(), pCurUser->get_UserFlag(defUserFlag_NoticeGroup), jid.c_str() );

				db_Update_user_base( pCurUser );
			}
		}

		// �Ƚϱ仯
		UseDbTransAction dbta( doTRANSACTION?db:NULL );
		const defmapAuth &mapAuth = pUser->GetList_Auth();
		for( defmapAuth::const_iterator it=mapAuth.begin(); it!=mapAuth.end(); ++it )
		{
			const struAuth *pAuth = &(it->second);
			struAuth *pCurAuth = (struAuth*)pCurUser->Get_Auth( pAuth->device_type, pAuth->device_id );
			if( pCurAuth )
			{
				if( pAuth->authority != pCurAuth->authority )
				{
					//update
					//if( defCfgOprt_Modify == oprt
					//	|| defCfgOprt_AddModify == oprt )
					{
						macDebugLog_GSIOTUserMgr( "CfgChange_User(oprt=%d) do modify, %s\r\n", oprt, pAuth->Print( jid.c_str(), false ).c_str() );

						pCurAuth->authority = pAuth->authority;
						db_Update_user_auth( pCurUser->GetID(), *pCurAuth );
					}
				}
				else
				{
					macDebugLog_GSIOTUserMgr( "CfgChange_User(oprt=%d) authority is same, %s\r\n", oprt, pAuth->Print( jid.c_str(), false ).c_str() );
				}
			}
			else if( pAuth->authority > defUserAuth_Null ) // �µ���Ȩ�����ò����ӣ��������
			{
				if( Pass_mapAuthAdd )
				{
					if( !GSIOTUser::IsAllAuthConfig( pAuth->device_type, pAuth->device_id ) )
						continue;
				}

				{
					macDebugLog_GSIOTUserMgr( "CfgChange_User(oprt=%d) do add, %s\r\n", oprt, pAuth->Print( jid.c_str(), false ).c_str() );

					pCurUser->CfgChange_Auth( *pAuth, oprt, FailedIsErr );
					db_Insert_user_auth( pCurUser->GetID(), *pAuth );
				}
			}
			else
			{
				macDebugLog_GSIOTUserMgr( "CfgChange_User(oprt=%d) auth is null, no add, %s\r\n", oprt, pAuth->Print( jid.c_str(), false ).c_str() );
			}
		}
		dbta.Commit();
		
		this->OnNotify( defNotify_Update, pCurUser );
	}
	else
	{
		if( defCfgOprt_Modify==oprt )
		{
			//LOGMSGEX( defLOGNAME, FailedIsErr?defLOG_ERROR:defLOG_INFO, "CfgChange_User(oprt=%d) err, not found! %s\r\n", oprt, jid.c_str() );
			return defGSReturn_NoExist;
		}

		if( jid.empty() )
		{
			return defGSReturn_Err;
		}

		if( !g_CheckEMail( std::string(jid) ) )  
		{
			//return defGSReturn_Err;  //jyc20170301 remove   no <regex> lib
		}
		
		// add or addmodify
		LOGMSG( "CfgChange_User(oprt=%d) do add, %s\r\n", oprt, jid.c_str() );

		GSIOTUser *pNewUser = pUser->clone();

		// ���ʱ������Ѿ�������Ȩ�ޱ�־�����ñ������Ȩ�޼�¼
		if( pNewUser->IsAllAuthCfg() )
		{
			LOGMSG( "CfgChange_User(oprt=%d) do add IsAll_Auth, %s\r\n", oprt, jid.c_str() );
			pNewUser->ResetOnlyAuth(false,false);
		}

		pNewUser->SetID( db_Insert_user_base( pNewUser ) );
		GSIOTUserMgr::usermapInsert( m_mapUser, pNewUser );

		UseDbTransAction dbta( doTRANSACTION?db:NULL );
		const defmapAuth mapAuth = pNewUser->GetList_Auth();
		for( defmapAuth::const_iterator it=mapAuth.begin(); it!=mapAuth.end(); ++it )
		{
			db_Insert_user_auth( pNewUser->GetID(), it->second );
		}
		dbta.Commit();

		this->OnNotify( defNotify_Add, pNewUser );
	}

	return defGSReturn_Success;
}
コード例 #29
0
ファイル: User.cpp プロジェクト: bpcampbe/znc
bool CUser::WriteConfig(CFile& File) {
	File.Write("<User " + GetUserName().FirstLine() + ">\n");

	if (m_eHashType != HASH_NONE) {
		CString sHash = "md5";
		if (m_eHashType == HASH_SHA256)
			sHash = "sha256";
		if (m_sPassSalt.empty()) {
			PrintLine(File, "Pass", sHash + "#" + GetPass());
		} else {
			PrintLine(File, "Pass", sHash + "#" + GetPass() + "#" + m_sPassSalt + "#");
		}
	} else {
		PrintLine(File, "Pass", "plain#" + GetPass());
	}
	PrintLine(File, "Nick", GetNick());
	PrintLine(File, "AltNick", GetAltNick());
	PrintLine(File, "Ident", GetIdent());
	PrintLine(File, "RealName", GetRealName());
	PrintLine(File, "BindHost", GetBindHost());
	PrintLine(File, "DCCBindHost", GetDCCBindHost());
	PrintLine(File, "QuitMsg", GetQuitMsg());
	if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())
		PrintLine(File, "StatusPrefix", GetStatusPrefix());
	PrintLine(File, "Skin", GetSkinName());
	PrintLine(File, "ChanModes", GetDefaultChanModes());
	PrintLine(File, "Buffer", CString(GetBufferCount()));
	PrintLine(File, "KeepBuffer", CString(KeepBuffer()));
	PrintLine(File, "MultiClients", CString(MultiClients()));
	PrintLine(File, "BounceDCCs", CString(BounceDCCs()));
	PrintLine(File, "DenyLoadMod", CString(DenyLoadMod()));
	PrintLine(File, "Admin", CString(IsAdmin()));
	PrintLine(File, "DenySetBindHost", CString(DenySetBindHost()));
	PrintLine(File, "DCCLookupMethod", CString((UseClientIP()) ? "client" : "default"));
	PrintLine(File, "TimestampFormat", GetTimestampFormat());
	PrintLine(File, "AppendTimestamp", CString(GetTimestampAppend()));
	PrintLine(File, "PrependTimestamp", CString(GetTimestampPrepend()));
	PrintLine(File, "TimezoneOffset", CString(m_fTimezoneOffset));
	PrintLine(File, "JoinTries", CString(m_uMaxJoinTries));
	PrintLine(File, "MaxJoins", CString(m_uMaxJoins));
	PrintLine(File, "IRCConnectEnabled", CString(GetIRCConnectEnabled()));
	File.Write("\n");

	// Allow Hosts
	if (!m_ssAllowedHosts.empty()) {
		for (set<CString>::iterator it = m_ssAllowedHosts.begin(); it != m_ssAllowedHosts.end(); ++it) {
			PrintLine(File, "Allow", *it);
		}

		File.Write("\n");
	}

	// CTCP Replies
	if (!m_mssCTCPReplies.empty()) {
		for (MCString::const_iterator itb = m_mssCTCPReplies.begin(); itb != m_mssCTCPReplies.end(); ++itb) {
			PrintLine(File, "CTCPReply", itb->first.AsUpper() + " " + itb->second);
		}

		File.Write("\n");
	}

	// Modules
	CModules& Mods = GetModules();

	if (!Mods.empty()) {
		for (unsigned int a = 0; a < Mods.size(); a++) {
			CString sArgs = Mods[a]->GetArgs();

			if (!sArgs.empty()) {
				sArgs = " " + sArgs;
			}

			PrintLine(File, "LoadModule", Mods[a]->GetModName() + sArgs);
		}

		File.Write("\n");
	}

	// Servers
	for (unsigned int b = 0; b < m_vServers.size(); b++) {
		PrintLine(File, "Server", m_vServers[b]->GetString());
	}

	// Chans
	for (unsigned int c = 0; c < m_vChans.size(); c++) {
		CChan* pChan = m_vChans[c];
		if (pChan->InConfig()) {
			File.Write("\n");
			if (!pChan->WriteConfig(File)) {
				return false;
			}
		}
	}

	File.Write("</User>\n");

	return true;
}
コード例 #30
0
ファイル: m_stats.c プロジェクト: Apsu/bahamut
static void 
serv_info(aClient *cptr, char *name)
{
    static char Lformat[] = ":%s %d %s %s %u %u %u %u %u :%u %u %s";
    long        sendK, receiveK, uptime;
    aClient    *acptr;
    DLink      *lp;
    int         i = 0;

    sendK = receiveK = 0;

    for (lp = server_list; lp; lp = lp->next)
    {
        acptr = lp->value.cptr;

#ifdef HIDEULINEDSERVS
        if (IsULine(acptr) && !IsAnOper(cptr))
            continue;
#endif
        sendK += acptr->sendK;
        receiveK += acptr->receiveK;
        sendto_one(cptr, Lformat, me.name, RPL_STATSLINKINFO,
                    name, ( (MyClient(cptr) && IsAdmin(cptr))
                            ? get_client_name(acptr, FALSE)
                            : get_client_name(acptr, HIDEME) ),
                    (int) SBufLength(&acptr->sendQ),
                    (int) acptr->sendM, (int) acptr->sendK,
                    (int) acptr->receiveM, (int) acptr->receiveK,
                    timeofday - acptr->firsttime, timeofday - acptr->since,
                    IsServer(acptr) ? (DoesTS(acptr) ? "TS" : "NoTS") : "-");


        if(RC4EncLink(acptr))
            sendto_one(cptr, ":%s %d %s : - RC4 encrypted", me.name, 
                        RPL_STATSDEBUG, name);

        if(ZipOut(acptr))
        {
            unsigned long ib, ob;
            double rat;

            zip_out_get_stats(acptr->serv->zip_out, &ib, &ob, &rat);
            if(ib)
            {
                sendto_one(cptr, ":%s %d %s : - [O] Zip inbytes %lu, "
                            "outbytes %lu (%3.2f%%)", me.name, RPL_STATSDEBUG,
                             name, ib, ob, rat);
            }
        }

        if(ZipIn(acptr))
        {
            unsigned long ib, ob;
            double rat;

            zip_in_get_stats(acptr->serv->zip_in, &ib, &ob, &rat);
            if(ob)
            {
                sendto_one(cptr, ":%s %d %s : - [I] Zip inbytes %lu, "
                            "outbytes %lu (%3.2f%%)", me.name, RPL_STATSDEBUG,
                             name, ib, ob, rat);
            }
        }
        i++;
    }
    sendto_one(cptr, ":%s %d %s :%u total server%s",
           me.name, RPL_STATSDEBUG, name, i, (i == 1) ? "" : "s");
    sendto_one(cptr, ":%s %d %s :Sent total : %7.2f %s",
           me.name, RPL_STATSDEBUG, name, _GMKv(sendK), _GMKs(sendK));
    sendto_one(cptr, ":%s %d %s :Recv total : %7.2f %s",
           me.name, RPL_STATSDEBUG, name, _GMKv(receiveK),
           _GMKs(receiveK));

    uptime = (timeofday - me.since);
    sendto_one(cptr, ":%s %d %s :Server send: %7.2f %s (%4.1f K/s total,"
                     " %4.1f K/s current)", me.name, RPL_STATSDEBUG, name,
                     _GMKv(me.sendK), _GMKs(me.sendK), 
                    (float) ((float) me.sendK / (float) uptime), curSendK);
    sendto_one(cptr, ":%s %d %s :Server recv: %7.2f %s (%4.1f K/s total,"
                     " %4.1f K/s current)", me.name, RPL_STATSDEBUG, name, 
                    _GMKv(me.receiveK), _GMKs(me.receiveK),
                    (float) ((float) me.receiveK / (float) uptime), curRecvK);
}