コード例 #1
0
ファイル: telnet.cpp プロジェクト: Bobfrat/coi-services
int TelnetProtocol::Send(const void *pBuf, int count)
{
  for (int i = 0 ; i < count ; i++) {
    BYTE ch = ((const BYTE *)pBuf)[i];

    if (ch == cdIAC)
          SendRaw(&ch, 1);

    SendRaw(&ch, 1);
  }

  return count;
}
コード例 #2
0
ファイル: NetClient.cpp プロジェクト: zhww1/VODDev
BOOL CNetClient::SendData(DWORD dwCmdID,LPVOID pData,UINT nLen )
{
    VODHEADER header = {0};
    header.dwCmd = dwCmdID;
    header.dwLen = nLen;
    if (SendRaw(&header,sizeof(header))!=TRUE)
    {
        return FALSE;
    }
    if (SendRaw(pData,nLen) != TRUE)
    {
        return FALSE;
    }
    return TRUE;
}
コード例 #3
0
void
XDLink::Send
	(
	const JCharacter* text
	)
{
	if (itsLink != NULL)
		{
		if (ProgramIsRunning())
			{
			StopProgram();
			}

		JString arg = " -i not_command";

		JString s = text;
		JIndex i;
		if (s.LocateSubstring("@i", &i))
			{
			s.ReplaceSubstring(i, i+1, arg);
			}
		else
			{
			s += arg;
			}

		SendRaw(s);
		}
}
コード例 #4
0
ファイル: telnet.cpp プロジェクト: Bobfrat/coi-services
void TelnetProtocol::SendSubNegotiation(int option, const BYTE_vector &params)
{
  SendOption(cdSB, (BYTE)option);

  printf("  ");
  for (BYTE_vector::const_iterator i = params.begin() ; i != params.end() ; i++) {
    BYTE b = *i;

    printf("%u ", (unsigned)b);
    SendRaw(&b, sizeof(b));
  }
  printf("SE\n");

  BYTE buf[2] = {cdIAC, cdSE};

  SendRaw(buf, sizeof(buf));
}
コード例 #5
0
ファイル: telnet.cpp プロジェクト: Bobfrat/coi-services
void TelnetProtocol::SendOption(BYTE code, BYTE option)
{
  BYTE buf[3] = {cdIAC, code, option};

  printf("SEND: %s %u\n", code2name(code), (unsigned)option);

  SendRaw(buf, sizeof(buf));
}
コード例 #6
0
ファイル: ClientSocket.cpp プロジェクト: isongbo/MyCode
BOOL CClientSocket::SendData(DWORD dwCmdID,LPVOID pData,UINT nLen )
{
    VODHEADER header = {0};
    header.dwCmd = dwCmdID;
    header.dwLen = nLen;
	//发送数据包的包头
    if (SendRaw(&header,sizeof(header))!=TRUE)
    {
        return FALSE;
    }
	//发送登录数据包
    if (SendRaw(pData,nLen) != TRUE)
    {
        return FALSE;
    }
    return TRUE;
}
コード例 #7
0
ファイル: NetClient.cpp プロジェクト: zhww1/VODDev
//根据用户请求的影片ID,在数据库中查询文件路径,并下载
//该文件
BOOL CNetClient::OnMediaData()
{
    MEDIADATA data = {0};
    if(!RecvData(&data,sizeof(data)))
		return FALSE;
	//CMainFrame *pWnd=(CMainFrame*)AfxGetMainWnd();
	//CVideoManager videoMgr(&pWnd->m_adoConnection);
	CVideoManager videoMgr(&g_pWnd->m_adoConnection);
	CString strVideoPath=videoMgr.GetVideoPathByID(data.videoID);
    CFile file;
    MEDIADATARET dataret = {0};
    if(!file.Open(strVideoPath,CFile::modeRead))
	{
        return FALSE;
    }
    //从文件路径中获取文件名称
	int pos=strVideoPath.ReverseFind('\\');
	strcpy(dataret.szFileName,strVideoPath.Mid(pos+1));
    dataret.dwFileLen = file.GetLength();
    if(!SendData(VODNETCMD_MEDIADATA_RET,&dataret,sizeof(dataret)))
    {
        file.Close();
        return FALSE;
    }
	//如何文件已存在,不需要重复下载
	BOOL bExit=FALSE;
    if (RecvData(&bExit,sizeof(bExit)))
    {
		if (bExit)//文件已经存在
		{
			file.Close();
			return TRUE;
		}
    }
	else
	{
		return FALSE;
	}
	//向客户端发送文件数据
    CHAR szBuff[2000] = {0};
    LONG nLeft = dataret.dwFileLen;
    while(nLeft>0){
        int nSend = 2000;
        if (nLeft<nSend)
        {
            nSend = nLeft;
        }
        file.Read(szBuff,nSend);
        SendRaw(szBuff,nSend);
        nLeft = nLeft - nSend;
    }
    file.Close();
    return TRUE;
}
コード例 #8
0
	bool SecureSocket::SendFromBio(int flags)
	{
		uint8_t buf[4096];
		size_t pending = BIO_ctrl_pending(m_out);
		if (!pending) 
			return true;
		size_t bytes = BIO_read(m_out, buf, sizeof(buf));
		if (bytes > 0) 
			return SendRaw(buf, bytes, flags);
		else if (bytes == -1 || bytes == 0)
			return true;
		return false;
	}
コード例 #9
0
ファイル: TCPLinkImpl.cpp プロジェクト: Altenius/cuberite
bool cTCPLinkImpl::Send(const void * a_Data, size_t a_Length)
{
	if (m_ShouldShutdown)
	{
		LOGD("%s: Cannot send data, the link is already shut down.", __FUNCTION__);
		return false;
	}

	// If running in TLS mode, push the data into the TLS context instead:
	if (m_TlsContext != nullptr)
	{
		m_TlsContext->Send(a_Data, a_Length);
		return true;
	}

	// Send the data:
	return SendRaw(a_Data, a_Length);
}
コード例 #10
0
ファイル: ClientSocket.cpp プロジェクト: isongbo/MyCode
//下载文件
BOOL CClientSocket::GetMediaData(DWORD videoID,LPCSTR pszFilePath,CString & strFullPath)
{
    MEDIADATA data = {0};
    data.videoID=videoID;
    if(!SendData(VODNETCMD_MEDIADATA,&data,sizeof(data)))
        return FALSE;
    
    VODHEADER header = {0};
    if(!RecvData(&header,sizeof(header)))
	   return FALSE;
    
    MEDIADATARET dataret = {0};
    if(!RecvData(&dataret,sizeof(dataret)))
		return FALSE;
    if (dataret.dwFileLen==0)
    {
        return TRUE;
    }
    strFullPath = pszFilePath;
	strFullPath+=dataret.szFileName;
    //判断文件是否存在
    BOOL bExit=PathFileExists(strFullPath);
   	if (!SendRaw(&bExit,sizeof(bExit)))return FALSE;
    if (bExit)return TRUE;//文件存在,将不再接收文件内容
    CFile file;
    if(!file.Open(strFullPath,CFile::modeCreate|CFile::modeWrite))
		return FALSE;
        
    CHAR szBuff[2000] = {0};
    LONG nLeft = dataret.dwFileLen;
    while(nLeft>0){
        int nRecv = 2000;
        if (nLeft<nRecv)
        {
            nRecv = nLeft;
        }
        RecvData(szBuff,nRecv);
        file.Write(szBuff,nRecv);
        nLeft = nLeft - nRecv;
    }
    file.Close();

    return TRUE;
}
コード例 #11
0
ファイル: ClientSocket.cpp プロジェクト: isongbo/MyCode
//获取所有类型
BOOL CClientSocket::GetAllVideoTypes(CString & types)
{
	VODHEADER header={0};
	header.dwVer=1;
	header.dwCmd=VODNETCMD_TYPES;
	header.dwLen=0;
	if (SendRaw(&header,sizeof(header))!=TRUE)
    {
        return FALSE;
    }
	//返回所有类型
   
	RecvData(&header,sizeof(header));
	LPSTR pData=types.GetBuffer(header.dwLen);
	RecvData(pData,header.dwLen);
	//不调用该函数,不会有字符串的结束
	types.ReleaseBuffer(header.dwLen);
	return TRUE;
}
コード例 #12
0
void
XDLink::SendMedicCommand
	(
	CMCommand* command
	)
{
	command->Starting();

	JString arg = " -i ";
	arg        += JString(command->GetTransactionID(), JString::kBase10);

	JString s = command->GetCommand();
	JIndex i;
	if (s.LocateSubstring("@i", &i))
		{
		s.ReplaceSubstring(i, i+1, arg);
		}
	else
		{
		s += arg;
		}

	SendRaw(s);
}
コード例 #13
0
ファイル: DOSAPI.c プロジェクト: g8bpq/BPQ32
VOID CHOSTAPI(ULONG * pEAX, ULONG * pEBX, ULONG * pECX, ULONG * pEDX, VOID ** pESI, VOID ** pEDI)
{
	ULONG EAX = *pEAX;
	ULONG EBX = *pEBX;
	ULONG ECX = *pECX;
	ULONG EDX = *pEDX;
	VOID * ESI = *pESI;
	VOID * EDI = *pEDI;

	int Command;
	int Stream;
	int n;
	int Temp;
	PBPQVECSTRUC HostVec;
	TRANSPORTENTRY * Session;

/*
;	COMMANDS SUPPORTED ARE
;
;	AH = 0	Get node/switch version number and description.  On return
;		AH = major version number and AL = minor version number,
;		and user's buffer pointed to by ES:ESI is set to the text
;		string normally output by the USERS command, eg:
;		"G8BPQ Packet Switch Version 4.01 Dev".  CX is set to the
;		length of the text string.
;
;
;	AH = 1	Set application mask to value in DL (or even DX if 16
;		applications are ever to be supported).
;
;		Set application flag(s) to value in CL (or CX).
;		whether user gets connected/disconnected messages issued
;		by the node etc.
;
;
;	AH = 2	Send frame in ES:ESI (length CX)
;
;
;	AH = 3	Receive frame into buffer at ES:ESI, length of frame returned
;		in CX.  BX returns the number of outstanding frames still to
;		be received (ie. after this one) or zero if no more frames
;		(ie. this is last one).
;
;
;
;	AH = 4	Get stream status.  Returns:
;
;		CX = 0 if stream disconnected or CX = 1 if stream connected
;		DX = 0 if no change of state since last read, or DX = 1 if
;		       the connected/disconnected state has changed since
;		       last read (ie. delta-stream status).
;
;
;
;	AH = 6	Session control.
;
;		CX = 0 Conneect - _APPLMASK in DL
;		CX = 1 connect
;		CX = 2 disconnect
;		CX = 3 return user to node
;
;
;	AH = 7	Get buffer counts for stream.  Returns:
;
;		AX = number of status change messages to be received
;		BX = number of frames queued for receive
;		CX = number of un-acked frames to be sent
;		DX = number of buffers left in node
;		SI = number of trace frames queued for receive
;
;AH = 8		Port control/information.  Called with a stream number
;		in AL returns:
;
;		AL = Radio port on which channel is connected (or zero)
;		AH = SESSION TYPE BITS
;		BX = L2 paclen for the radio port
;		CX = L2 maxframe for the radio port
;		DX = L4 window size (if L4 circuit, or zero)
;		ES:EDI = CALLSIGN

;AH = 9		Fetch node/application callsign & alias.  AL = application
;		number:
;
;		0 = node
;		1 = BBS
;		2 = HOST
;		3 = SYSOP etc. etc.
;
;		Returns string with alias & callsign or application name in
;		user's buffer pointed to by ES:ESI length CX.  For example:
;
;		"WORCS:G8TIC"  or "TICPMS:G8TIC-10".
;
;
;	AH = 10	Unproto transmit frame.  Data pointed to by ES:ESI, of
;		length CX, is transmitted as a HDLC frame on the radio
;		port (not stream) in AL.
;
;
;	AH = 11 Get Trace (RAW Data) Frame into ES:EDI,
;			 Length to CX, Timestamp to AX
;
;
;	AH = 12 Update Switch. At the moment only Beacon Text may be updated
;		DX = Function
;		     1=update BT. ES:ESI, Len CX = Text
;		     2=kick off nodes broadcast
;
;	AH = 14 Internal Interface for IP Router
;
;		Send frame - to NETROM L3 if DL=0
;			     to L2 Session if DL<>0
;
;
; 	AH = 15 Get interval timer
;

*/

	Command = (EAX & 0xFFFF) >> 8;

	Stream = (EAX & 0xFF);
	n = Stream - 1;				// API Numbers Streams 1-64 

	if (n < 0 || n > 63)
		n = 64;

	HostVec = &BPQHOSTVECTOR[n];
	Session = HostVec->HOSTSESSION;

	switch (Command)
	{
	case 0:					// Check Loaded/Get Version
	
		EAX = ('P' << 8) | 'B';
		EBX =  ('Q' << 8) | ' ';
	
		EDX = (MAJORVERSION << 8) | MINORVERSION; 
		break;

	case 1:					// Set Appl mAsk
	
		HostVec->HOSTAPPLMASK = EDX;	// APPL MASK
		HostVec->HOSTAPPLFLAGS = (UCHAR)ECX;	// APPL FLAGS
	
		// If either is non-zero, set allocated and Process. This gets round problem with
		// stations that don't call allocate stream
	
		if (ECX || EBX)
		{
			HostVec->HOSTFLAGS |= 0x80;		// SET ALLOCATED BIT	
			HostVec->STREAMOWNER = GetCurrentProcessId();
	
			//	Set Program Name

			memcpy(&HostVec->PgmName, pgm, 31);
		}
		break;

	case 2:							// Send Frame

		//	ES:ESI = MESSAGE, CX = LENGTH, BX = VECTOR

		EAX = SendMsg(Stream, ESI, ECX);
		break;
	
	case 3:

	//	AH = 3	Receive frame into buffer at ES:EDI, length of frame returned
	//		in CX.  BX returns the number of outstanding frames still to
	//		be received (ie. after this one) or zero if no more frames
	//		(ie. this is last one).

		EAX = GetMsg(Stream, EDI, &ECX, &EBX);
		break;

	case 4:

	//	AH = 4	Get stream status.  Returns:
	//	CX = 0 if stream disconnected or CX = 1 if stream connected
	//	DX = 0 if no change of state since last read, or DX = 1 if
	//	       the connected/disconnected state has changed since
	//	       last read (ie. delta-stream status).

		ECX = EDX = 0;

		if (HostVec->HOSTFLAGS & 3)		//STATE CHANGE BITS
			EDX = 1;

		if (Session)
			ECX = 1;
		
		break;
		
	case 5:

	//	AH = 5	Ack stream status change

		HostVec->HOSTFLAGS &= 0xFC;		// Clear Chnage Bits
		break;

	case 6:

	//	AH = 6	Session control.

	//	CX = 0 Conneect - APPLMASK in DL
	//	CX = 1 connect
	//	CX = 2 disconnect
	//	CX = 3 return user to node

		SessionControl(Stream, ECX, EDX);
		break;

	case 7:

	//	AH = 7	Get buffer counts for stream.  Returns:

	//	AX = number of status change messages to be received
	//	BX = number of frames queued for receive
	//	CX = number of un-acked frames to be sent
	//	DX = number of buffers left in node
	//	SI = number of trace frames queued for receive


	ECX = 0;				// unacked frames
	EDX = QCOUNT;

	ESI = (void *)MONCount(Stream);
	EBX = RXCount(Stream);
	ECX = TXCount(Stream);

	EAX = 0;				// Is this right ???

	break;

	case 8:

	//	AH = 8		Port control/information.  Called with a stream number
	//		in AL returns:
	//
	//	AL = Radio port on which channel is connected (or zero)
	//	AH = SESSION TYPE BITS
	//	BX = L2 paclen for the radio port
	//	CX = L2 maxframe for the radio port
	//	DX = L4 window size (if L4 circuit, or zero)
	//	ES:EDI = CALLSIGN


		GetConnectionInfo(Stream, EDI, &EAX, &Temp, &EBX, &ECX, &EDX); // Return the Secure Session Flag rather than not connected
		EAX |= Temp <<8;

		break;


	case 9:

		// Not Implemented

		break;

	case 10:

	//	AH = 10	Unproto transmit frame.  Data pointed to by ES:ESI, of
	//	length CX, is transmitted as a HDLC frame on the radio
	//	port (not stream) in AL.

		EAX = SendRaw(EAX, ESI, ECX);
		return;

	case 11:

	//	AH = 11 Get Trace (RAW Data) Frame into ES:EDI,
	//	 Length to CX, Timestamp to AX

		EAX =  GetRaw(Stream, EDI, &ECX, &EBX);
		break;

	case 12:

	// Update Switch

		if (EDX == 2)
		{
			SENDNODESMSG();
			break;
		}
		if (EDX == 2)
		{
			//	UPDATE BT

			BTLENGTH = ECX;
			memcpy(BTEXTFLD, ESI, ECX + 7);
		}

		break;

	case 13:

		// BPQALLOC

		//	AL = 0 = Find Free
		//	AL != 0 Alloc or Release

		if (EAX == 0)
		{
			EAX = FindFreeStream();
			break;
		}

		if (ECX == 1)			// Allocate
		{
			 EAX = AllocateStream(Stream);
			 break;
		}
		
		DeallocateStream(Stream);
		break;

	case 14:

	//	AH = 14 Internal Interface for IP Router

	//	Send frame - to NETROM L3 if DL=0
	//	             to L2 Session if DL<>0

		break;			// Shouldn't be needed

	case 15:

		// GETTIME

		EAX = REALTIMETICKS;
		EBX = 0;
	
#ifdef EXCLUDEBITS
	
		EBX = (ULONG)ExcludeList;

#endif
		break;

	}

	*pEAX = EAX;
	*pEBX = EBX;
	*pECX = ECX;
	*pEDX = EDX;
	*pESI = ESI;
	*pEDI = EDI;

	return;
}	
コード例 #14
0
ファイル: child.c プロジェクト: xiu/child
int main(int argc, char **argv)
{
    startuptime = time(NULL);

    InitMem();

    int retval,mysql_lastconn,newfd,i,lastcheck,lastcheck2,nbfd;
    struct sockaddr_storage sa;
    socklen_t salen = sizeof(sa);
    Eclient *eclient;

    indata.nextline = indata.chunkbufentry = indata.chunkbuf;

    emerg = emerg_req = 0;

    eos = raws = verbose = vv = 0;
    int daemonize = 1;
    char op = 0;
    me.retry_attempts = me.nextretry = me.connected = 0;

    struct sigaction sig, old;
    memset(&sig,0,sizeof(sig));
    sig.sa_handler = sighandler;
    sigaction(SIGHUP,&sig,&old);
#ifdef USE_FILTER
    sigaction(SIGUSR1,&sig,&old);
#endif
    sigaction(SIGUSR2,&sig,&old);
    sigaction(SIGINT,&sig,&old);
    sigaction(SIGCHLD,&sig,&old);
    sigaction(SIGPIPE,&sig,&old);

    struct rlimit rlim;
    if ((getrlimit(RLIMIT_CORE, &rlim)) == -1) {
        perror("getrlimit");
        return -1;
    }
    rlim.rlim_cur = RLIM_INFINITY;
    if ((setrlimit(RLIMIT_CORE, &rlim)) == -1) {
        perror("setrlimit");
        return -1;
    }

    /* Setting default values */

    strcpy(me.nick,"C");
    strcpy(me.name,"services.geeknode.org");
    strcpy(me.ident,"cserve");
    strcpy(me.host,"geeknode.org");
    strcpy(me.linkpass,"f00p4ss");
    strcpy(me.mysql_host,"localhost");
    strcpy(me.mysql_db,"child");
    strcpy(me.mysql_login,"child");
    strcpy(me.mysql_passwd,"childp4ss");
    strcpy(me.logfile,"child.log");
    strcpy(me.guest_prefix,"Geek");
    strcpy(me.pl_logfile,"partyline.log");
    strcpy(me.sendmail,"/usr/sbin/sendmail -t");
    strcpy(me.sendfrom,"*****@*****.**");
    strcpy(me.usercloak,".users.geeknode.org");
    bzero(me.mysql_anope_host,32);
    bzero(me.mysql_anope_db,32);
    bzero(me.mysql_anope_login,32);
    bzero(me.mysql_anope_passwd,32);
    bzero(me.bindip,32);
    me.port = 4400;
    me.maxclones = 5;
    me.nick_expire = 45;
    me.chan_expire = 60;
    me.chanperuser = 10;
    me.level_oper = 100;
    me.level_admin = 500;
    me.level_root = 900;
    me.level_owner = 1000;
    me.limittime = 5;
    me.savedb_interval = 60;
    me.listen_port = 0;
#ifdef USE_GNUTLS
    me.ssl = 0;
#endif
    me.enable_exec = 0;
    me.anonymous_global = 0;
    me.maxmsgtime = 2;
    me.maxmsgnb = 5;
    me.ignoretime = 60;
    me.maxloginatt = 3;
    me.chlev_sadmin = 20;
    me.chlev_admin = 10;
    me.chlev_op = 5;
    me.chlev_halfop = 4;
    me.chlev_voice = 3;
    me.chlev_invite = 1;
    me.chlev_nostatus = -1;
    me.chlev_akick = -2;
    me.chlev_akb = -3;
    me.anopemd5 = 0;
#ifdef USE_FILTER
    me.filter = 0;
#endif
    me.emailreg = 0;

    /* -- */

    int ladb=0,cdb=0;

    while ((op = getopt(argc,argv,"acdhv")) != EOF) {
        switch(op) {
            case 'a':
                ladb = 1;
                break;
            case 'c':
                cdb = 1;
                break;
            case 'd':
                daemonize = 0;
                break;
            case 'v':
                if (verbose)
                    vv = 1;
                else
                    verbose = 1;
                break;
            case 'h':
            default:
                usage(argv[0]);
        }
    }

    loadconf(0);
#ifdef USE_FILTER
    if (me.filter)
        loadrulefile();
#endif

    if (ladb) {
        if (!connect_to_db()) {
            printf("Cannot connect to db\n");
            child_clean();
        }

        loadalldb();
        mysql_close(&mysql);

        if (!connect_to_anope_db()) {
            printf("Cannot connect to anope db\n");
            child_clean();
        }

        printf("Loading anope database... ");
        fflush(stdout);

        loadanopedb();
        mysql_close(&mysql2);
        printf("done.\n");
        printf("Saving databases... ");
        fflush(stdout);
        savealldb();
        printf("done.\n");
        printf("Anope database converted\n");
        child_clean();
    }

    if (cdb) {
        if (!connect_to_db()) {
            printf("Cannot connect to db\n");
            child_clean();
        }

        printf("Creating databases ... ");
        fflush(stdout);
        char tmp[512];
        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_chans` (chname varchar(50) not null, founder varchar(50) not null, entrymsg blob not null, options int not null, mlock varchar(32) not null, autolimit int not null, lastseen int not null, regtime int not null, topic blob not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_chan_access` (chname varchar(50) not null, username varchar(255) not null, level int not null, automode int not null default 1, suspended int not null, uflags int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_trusts` (hostname varchar(255) not null, clones int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_users` (username varchar(50) not null, authlevel int not null, seen int not null, vhost varchar(200) not null, md5_pass varchar(32) not null, options int not null, timeout int not null, email varchar(100) not null, regtime int not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_links` (master varchar(50) not null, slave varchar(50) not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_botserv_bots` (name varchar(50) not null, ident varchar(50) not null, host varchar(50) not null)");
        mysql_query(&mysql,tmp);

        sprintf(tmp,"CREATE TABLE IF NOT EXISTS `child_botserv_chans` (chan varchar(50) not null, bot varchar(50) not null)");
        mysql_query(&mysql,tmp);

        RunHooks(HOOK_CREATEDB,NULL,NULL,NULL,NULL);

        printf(" done.\n");
        mysql_close(&mysql);
        child_clean();
    }

    if (me.listen_port) {
        if (!Bind()) {
            fprintf(stderr,"Error while binding\n");
            child_clean();
        }
        pllog("Partyline created");
    }

    retval = ConnectToServer();
    switch(retval) {
        case -1:
            fprintf(stderr,"Failed to connect to %s:%d (connection timed out)\n",me.server,me.port);
            operlog("Failed to connect to %s:%d (connection timed out)",me.server,me.port);
            child_clean();
        case 0:
            fprintf(stderr,"Failed to connect to %s:%d",me.server,me.port);
            operlog("Failed to connect to %s:%d",me.server,me.port);
            child_clean();
    }

    if (verbose) printf("Connected to server\n");

    if (!connect_to_db()) {
        fprintf(stderr,"Cannot connect to mysql\n");
        operlog("Cannot connect to mysql db");
        child_clean();
    }

    if (verbose) printf("Connected to mysql DB\n");
    loadalldb();
    mysql_close(&mysql);
    if (verbose) printf("Logging in to server\n");
    SendInitToServer();
    me.connected = 1;
    if (verbose) printf("Logged in to server\n");

    SendRaw("EOS");

    lastcheck = lastcheck2 = mysql_lastconn = time(NULL);
    if (daemonize) daemon(1,0);
    write_pid();

    nbfd = build_poll();
    struct pollfd pfdout;
    pfdout.fd = sock;
    pfdout.events = POLLOUT;
    pfdout.revents = 0;

    while(1) {
        if (outdata.writebytes > 0) {
            retval = poll(&pfdout,1,1000);
            if (retval > 0 && (pfdout.revents & POLLOUT))
                flush_sendq();
        }
        retval = poll(ufds,nbfd,1000);
        if (retval > 0) {
            for (i=0;i<nbfd;i++) {
                if (ufds[i].revents & (POLLIN | POLLPRI)) {
                    switch(i) {
                        case 0:
                            if (!ReadChunk()) {
                                if (!me.connected || !eos) break;
                                operlog("Connection reset by peer");
                                savealldb();
                                eos = me.retry_attempts = me.connected = 0;
                                me.nextretry = time(NULL)+1;
                                cleanup_reconnect();
                                close(sock);
                                break;
                            }
                            while (GetLineFromChunk())
                                ParseLine();
                            break;
                        case 1:
                            if (!me.listen_port) break;
                            newfd = accept(esock,(struct sockaddr *)&sa,&salen);
                            if (eclient_list.size+1 >= ECL_MAXSOCK) {
                                close(newfd);
                                break;
                            }
                            fcntl(newfd,F_SETFL,O_NONBLOCK);
                            eclient = AddEclient(newfd,sa,salen);
                            sendto_all_butone(eclient,"*** Connection from %s (%s)",eclient->host,eclient->addr);
                            nbfd = build_poll(); i++;
                            break;
                        default:
                            eclient = find_eclient(ufds[i].fd);
                            if (!eclient) break;
                            int oldnbfd = nbfd;
                            int old_eclient_size = eclient_list.size;
                            if (!ReadPChunk(eclient)) {
                                if (eclient->authed == 1)
                                    sendto_all_butone(eclient,"*** User %s (%s) logged out (Connection reset by peer)",eclient->nick,eclient->host);
                                else
                                    sendto_all_butone(eclient,"*** Lost connection from %s",eclient->host);
                                close(eclient->fd);
                                DeleteEclient(eclient);
                                nbfd = build_poll();
                                i--;
                                break;
                            }
                            int tmpfd = eclient->fd;
                            while (GetLineFromPChunk(tmpfd))
                                ParseEclient(eclient);
                            if (old_eclient_size > eclient_list.size)
                                nbfd = build_poll();
                            if (nbfd < oldnbfd) i -= (oldnbfd - nbfd);
                            break;
                    }
                }
            }
        }

        int timenow = time(NULL);

        if (!me.connected && timenow - me.nextretry >= 0) {
            retval = ConnectToServer();
            if (retval == -1 || retval == 0) {
                me.retry_attempts++;
                operlog("Reconnecting attempt #%d failed (%s)",me.retry_attempts,retval ? "timeout" : "error");
                if (me.retry_attempts >= MAX_RECO_ATTEMPTS) {
                    operlog("Maximum reconnection attempts reached, exiting");
                    savealldb();
                    unloadallmod();
                    CloseAllSock();
                    child_clean();
                }
                me.nextretry = timenow + RECONNECT_DELAY;
            } else {
                SendInitToServer();
                me.connected = 1;
                me.nextretry = 0;
                SendRaw("EOS");
                operlog("Reconnected");
            }
            if (me.connected) continue;
        }

        if (timenow - mysql_lastconn >= 60*me.savedb_interval) {
            savealldb();
            mysql_lastconn = timenow;
        }

        if (timenow - lastcheck >= 1) {
            CheckGuests();
            CheckLimits();
            CheckTB();
            lastcheck = timenow;
        }

        if (timenow - lastcheck2 >= 60) {
            checkexpired();
            lastcheck2 = timenow;
        }
    }

    operlog("Program shouldn't reach this piece of code, WTF ? Saving DBs and exiting.");
    savealldb();
    unloadallmod();
    CloseAllSock();
    child_clean();

    return 0;
}