Example #1
0
int UdpSocket::Bind(const std::string& intf, port_t &port, int range)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
	if (IsIpv6())
	{
		Ipv6Address ad(intf, port);
		if (ad.IsValid())
		{
			int n = Bind(ad, range);
			if (m_bind_ok)
				port = m_port;
			return n;
		}
		SetCloseAndDelete();
		return -1;
	}
#endif
#endif
	Ipv4Address ad(intf, port);
	if (ad.IsValid())
	{
		int n = Bind(ad, range);
		if (m_bind_ok)
			port = m_port;
		return n;
	}
	SetCloseAndDelete();
	return -1;
}
Example #2
0
void SctpSocket::OnException()
{
	if (Connecting())
	{
#ifdef ENABLE_SOCKS4
		if (Socks4())
			OnSocks4ConnectFailed();
		else
#endif
		if (GetConnectionRetry() == -1 ||
			(GetConnectionRetry() &&
			 GetConnectionRetries() < GetConnectionRetry() ))
		{
			// even though the connection failed at once, only retry after
			// the connection timeout
			// should we even try to connect again, when CheckConnect returns
			// false it's because of a connection error - not a timeout...
		}
		else
		{
			SetConnecting(false); // tnx snibbe
			SetCloseAndDelete();
			OnConnectFailed();
		}
		return;
	}
	// %! exception doesn't always mean something bad happened, this code should be reworked
	// errno valid here?
	int err = SoError();
	Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL);
	SetCloseAndDelete();
}
Example #3
0
void SctpSocket::OnRead()
{
/*
	int sctp_recvmsg(int sd, void * msg, size_t * len,
		struct sockaddr * from, socklen_t * fromlen,
		struct sctp_sndrcvinfo * sinfo, int * msg_flags);

	DESCRIPTION
	sctp_recvmsg  is  a  wrapper library function that can be used to receive a message from a socket while using the advanced
	features of SCTP.  sd is the socket descriptor on which the message pointed to by msg of length len is received.

	If from is not NULL, the source address of the message is filled in. The argument fromlen  is  a  value-result  parameter.
	initialized  to  the  size  of the buffer associated with from , and modified on return to indicate the actual size of the
	address stored.

	sinfo is a pointer to a sctp_sndrcvinfo structure to be filled upon receipt of the message.  msg_flags is a pointer  to  a
	integer that is filled with any message flags like MSG_NOTIFICATION or MSG_EOR.

*/
	struct sockaddr sa;
	socklen_t sa_len = 0;
	struct sctp_sndrcvinfo sinfo;
	int flags = 0;
	int n = sctp_recvmsg(GetSocket(), m_buf, SCTP_BUFSIZE_READ, &sa, &sa_len, &sinfo, &flags);
	if (n == -1)
	{
		Handler().LogError(this, "SctpSocket", Errno, StrError(Errno), LOG_LEVEL_FATAL);
		SetCloseAndDelete();
	}
	else
	{
		OnReceiveMessage(m_buf, n, &sa, sa_len, &sinfo, flags);
	}
}
Example #4
0
void ControlSocket::HandleString(std::string s)
{
    if(_instance->GetConf()->rmcontrolpass.size())
    {
        if(_authed)
        {
            _Execute(s);
        }
        else
        {
            if(s.size() > 3 && !memicmp(s.c_str(),"pw ",3)) // string format: "pw secret12345"
            {
                if(_instance->GetConf()->rmcontrolpass == s.c_str() + 3)
                {
                    logdetail("ControlSocket: Authenticated successfully with: \"%s\"",s.c_str());
                    SendTelnetText("+accepted");
                    _authed = true;
                }
                else
                {
                    SendTelnetText("+wrong password");
                    SetCloseAndDelete(true);
                }
            }
        }
    }
    else
    {
        _Execute(s);
    }
}
Example #5
0
void ControlSocket::OnAccept(void)
{
    logdetail("ControlSocket: Incoming connection from %s:%u [host:%s]",GetRemoteAddress().c_str(),GetRemotePort(),GetRemoteHostname().c_str());

    // must perform some crappy ptr conversion here, doesnt want to typecast SocketHandler -> ControlSocketHandler directly
    SocketHandler& hnd = Handler();
    ControlSocketHandler *chnd = static_cast<ControlSocketHandler*>(&hnd);
    _instance = chnd->GetInstance();
    DEBUG(logdebug("ControlSocket: setting instance = %X",_instance));

    // accept only connections from one host for now, if set
    if(_instance->GetConf()->rmcontrolhost.length()
        && !(GetRemoteAddress() == _instance->GetConf()->rmcontrolhost || GetRemoteHostname() == _instance->GetConf()->rmcontrolhost))
    {
        logdetail("ControlSocket: connection rejected. closing.");
        SetCloseAndDelete(true);
        return;
    }

    SendTelnetText(_instance->GetScripts()->variables.Get("@version"));
    if(_instance->GetConf()->rmcontrolpass.size())
    {
        SendTelnetText("Authentication?");
    }

    _ok = true;
}
Example #6
0
void pSocket::SendBitmap()
{
	Session *sess = m_sess; //ref.GetSession(m_hash);
	if (!sess)
	{
		SetCloseAndDelete();
		return;
	}
	piece_v& pcs = sess -> Complete();
	// TODO: uncomment..
//	if (pcs.size())
	{
		bitmap_t bitmap(sess -> GetNumberOfPieces());
		for (piece_v::iterator it = pcs.begin(); it != pcs.end(); it++)
		{
			Piece *p = *it;
			bitmap.set(p -> GetNumber());
		}
		uint32_t l = htonl(bitmap.GetBitmapSize() + 1);
		
		SendBuf( (char *)&l, 4);
		
		Send("\05");
		SendBuf( (char *)bitmap.GetBitmap(),bitmap.GetBitmapSize());
	}
}
Example #7
0
void HttpPutSocket::SetFile(const std::string& file)
{
	//struct stat st;
	
	// Added by Amir Krifa
	std::ifstream f;
	f.open(file.c_str(), std::ios_base::binary | std::ios_base::in);
	//if (!f.good() || f.eof() || !f.is_open()) { return 0; }
	
	if (!f.good() || f.eof() || !f.is_open()) 
	{ 
		Handler().LogError(this, "SetFile", Errno, StrError(Errno), LOG_LEVEL_FATAL);
		SetCloseAndDelete();
	}else
	{
		f.seekg(0, std::ios_base::beg);
		std::ifstream::pos_type begin_pos = f.tellg();
		f.seekg(0, std::ios_base::end);
		m_filename = file;
		m_content_length = static_cast<off_t>(f.tellg() - begin_pos);
	}
	
	//if (!stat(file.c_str(), &st))
	//{
	//	m_filename = file;
	//	m_content_length = st.st_size;
	//}
	//else
	//{
	//	Handler().LogError(this, "SetFile", Errno, StrError(Errno), LOG_LEVEL_FATAL);
	//	SetCloseAndDelete();
	//}
}
Example #8
0
void StdinLine::OnRead()
{
	char buf[m_bufsize];
	int n = read(GetSocket(), buf, m_bufsize - 1); //recv(0, buf, 1000, 0);
	if (n == -1)
	{
		Handler().LogError(this, "OnRead", errno, strerror(errno), LOG_LEVEL_FATAL);
		SetCloseAndDelete();
		return;
	}
	for (size_t i = 0; i < (size_t)n; i++)
	{
		switch (buf[i])
		{
		case 13: // ignore
			break;
		case 10:
			OnLine(m_line);
			m_line = "";
			break;
		default:
			m_line += buf[i];
		}
	}
}
Example #9
0
pSocket::pSocket(SocketHandler& h,const std::string& hash,unsigned char *p)
:TcpSocket(h,131072,131072)
,m_hash(hash)
,m_state(ACCEPT_LENGTH)
,m_server(false)
,m_cmd(0)
,m_slice(new unsigned char[iSliceSize])
,m_id(++m_next_id)
,m_interest(false)
,m_choke(false)
,m_t_choke(time(NULL))
,m_cts(false)
,m_sess(NULL)
,m_peer(NULL)
,m_last_r(0)
,m_last_w(0)
,pSocket_log(NULL)
{
	m_sess = static_cast<PeerHandler&>(h).GetSession(hash);
	if (!m_sess)
	{
		SetCloseAndDelete();
		return;
	}
	memcpy(m_remote_peer_id, p, 20);
	
}
void HttpClientSocket::OnData(const char *buf,size_t len)
{
	if (m_fil)
	{
		m_fil -> fwrite(buf, 1, len);
	}
	else
	if (m_data_ptr)
	{
		if (m_content_ptr + len > m_data_size)
		{
			Handler().LogError(this, "OnData", -1, "content buffer overflow", LOG_LEVEL_ERROR);
		}
		else
		{
			memcpy(m_data_ptr + m_content_ptr, buf, len);
		}
	}
	m_content_ptr += len;
	if (m_content_ptr == m_content_length && m_content_length)
	{
		if (m_fil)
		{
			m_fil -> fclose();
			delete m_fil;
			m_fil = NULL;
		}
		m_b_complete = true;
		OnContent();
		if (m_b_close_when_complete)
		{
			SetCloseAndDelete();
		}
	}
}
Example #11
0
int UdpSocket::Bind(SocketAddress& ad, int range)
{
	if (GetSocket() == INVALID_SOCKET)
	{
		Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp"));
	}
	if (GetSocket() != INVALID_SOCKET)
	{
		SetNonblocking(true);
		int n = bind(GetSocket(), ad, ad);
		int tries = range;
		while (n == -1 && tries--)
		{
			ad.SetPort(ad.GetPort() + 1);
			n = bind(GetSocket(), ad, ad);
		}
		if (n == -1)
		{
			Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL);
			SetCloseAndDelete();
#ifdef ENABLE_EXCEPTIONS
			throw Exception("bind() failed for UdpSocket, port:range: " + Utility::l2string(ad.GetPort()) + ":" + Utility::l2string(range));
#endif
			return -1;
		}
		m_bind_ok = true;
		m_port = ad.GetPort();
		return 0;
	}
	return -1;
}
Example #12
0
void UBSocket::OnLine(const std::string &line)
{
    bool popLast = false;

    SwitchEditors();

    if(m_editors.empty())
    {
        Global::Get()->bugf("UBSocket::OnLine(), m_editor == NULL!");
        Send("You don't have an editor mode set?\n");
        Send("Closing your connection now.\n");
        SetCloseAndDelete();
        return;
    }

    if(line.size() && line[0] == Global::Get()->OOCIdentifier)
    {
        m_editors.push(new EditorOOC(this));
        popLast = true;
    }

    m_editors.top()->OnLine(line);

    if(popLast)
        PopEditor();

    return;
}
Example #13
0
bool TcpSocket::Open(const std::string &host,port_t port)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
	if (IsIpv6())
	{
#ifdef ENABLE_RESOLVER
		if (!Handler().ResolverEnabled() || Utility::isipv6(host) )
		{
#endif
			in6_addr a;
			if (!Utility::u2ip(host, a))
			{
				SetCloseAndDelete();
				return false;
			}
			Ipv6Address ad(a, port);
			Ipv6Address local;
			return Open(ad, local);
#ifdef ENABLE_RESOLVER
		}
		m_resolver_id = Resolve6(host, port);
		return true;
#endif
	}
#endif
#endif
#ifdef ENABLE_RESOLVER
	if (!Handler().ResolverEnabled() || Utility::isipv4(host) )
	{
#endif
		ipaddr_t l;
		if (!Utility::u2ip(host,l))
		{
			SetCloseAndDelete();
			return false;
		}
		Ipv4Address ad(l, port);
		Ipv4Address local;
		return Open(ad, local);
#ifdef ENABLE_RESOLVER
	}
	// resolve using async resolver thread
	m_resolver_id = Resolve(host, port);
	return true;
#endif
}
Example #14
0
/// Reconnect Challenge command handler
bool AuthSocket::_HandleReconnectChallenge()
{
    DEBUG_LOG("Entering _HandleReconnectChallenge");
    if (ibuf.GetLength() < sizeof(sAuthLogonChallenge_C))
        return false;

    ///- Read the first 4 bytes (header) to get the length of the remaining of the packet
    std::vector<uint8> buf;
    buf.resize(4);

    ibuf.Read((char *)&buf[0], 4);

    EndianConvert(*((uint16*)(buf[0])));
    uint16 remaining = ((sAuthLogonChallenge_C *)&buf[0])->size;
    DEBUG_LOG("[ReconnectChallenge] got header, body is %#04x bytes", remaining);

    if ((remaining < sizeof(sAuthLogonChallenge_C) - buf.size()) || (ibuf.GetLength() < remaining))
        return false;

    //No big fear of memory outage (size is int16, i.e. < 65536)
    buf.resize(remaining + buf.size() + 1);
    buf[buf.size() - 1] = 0;
    sAuthLogonChallenge_C *ch = (sAuthLogonChallenge_C*)&buf[0];

    ///- Read the remaining of the packet
    ibuf.Read((char *)&buf[4], remaining);
    DEBUG_LOG("[ReconnectChallenge] got full packet, %#04x bytes", ch->size);
    DEBUG_LOG("[ReconnectChallenge] name(%d): '%s'", ch->I_len, ch->I);

    _login = (const char*)ch->I;
    _build = ch->build;

    _safelogin = _login;
    loginDatabase.escape_string(_safelogin);

    QueryResult *result = loginDatabase.PQuery ("SELECT sessionkey FROM account WHERE username = '******'", _safelogin.c_str ());

    // Stop if the account is not found
    if (!result)
    {
        sLog.outError("[ERROR] user %s tried to login and we cannot find his session key in the database.", _login.c_str());
        SetCloseAndDelete();
        return false;
    }

    Field* fields = result->Fetch ();
    K.SetHexStr (fields[0].GetString ());
    delete result;

    ///- Sending response
    ByteBuffer pkt;
    pkt << (uint8)  AUTH_RECONNECT_CHALLENGE;
    pkt << (uint8)  0x00;
    _reconnectProof.SetRand(16 * 8);
    pkt.append(_reconnectProof.AsByteArray(16),16);         // 16 bytes random
    pkt << (uint64) 0x00 << (uint64) 0x00;                  // 16 bytes zeros
    SendBuf((char const*)pkt.contents(), pkt.size());
    return true;
}
void HttpDebugSocket::OnDataComplete()
{
	if (!CloseAndDelete())
	{
		Send("</pre><hr></body></html>");
		SetCloseAndDelete();
	}
}
Example #16
0
void Socket::OnException()
{
	// %! exception doesn't always mean something bad happened, this code should be reworked
	// errno valid here?
	int err = SoError();
	Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL);
	SetCloseAndDelete();
}
Example #17
0
 void CreateNew() {
   if (g_b_off)
     return;
   MyHttpSocket *p = new MyHttpSocket(Handler(), m_url);
   p -> SetDeleteByHandler();
   Handler().Add(p);
   SetCloseAndDelete();
 }
Example #18
0
void UBSocket::SwitchEditors()
{
    if(!m_popeditor && !m_nexteditor)
        return;

    if(m_popeditor && m_nexteditor)
    {
        Global::Get()->bug("UBSocket::SwitchEditors() was called, but we don't have both a new editor and we want to pop one?!");
        Send("Something went wrong, somehow you are switching to another editor but you're also deleting the top one?!\n");
        Send("Closing your connection now.\n");
        SetCloseAndDelete();
        return;
    }

    if(m_popeditor || m_popLast)
    {
        if(m_editors.empty()) // should never happen
        {
            Global::Get()->bug("UBSocket::SwitchEditors() was called, but we don't have a current editor?!");
            Send("Something went wrong, somehow you are switching to another editor but you don't have one set?!\n");
            Send("Closing your connection now.\n");
            SetCloseAndDelete();
            return;
        }

        delete m_editors.top();
        m_editors.pop();
        m_popeditor = false;
        m_popLast = false;
        SetPrompt(m_editors.top()->prompt());
    }

    if(m_nexteditor)
    {
        m_editors.push(m_nexteditor);
        m_nexteditor = NULL;
        SetPrompt(m_editors.top()->prompt());
    }

    m_editors.top()->OnFocus();

    if(m_nexteditor)
        SwitchEditors();
    else
        SendPrompt();
}
void HttpClientSocket::OnFirst()
{
	if (!IsResponse())
	{
		Handler().LogError(this, "OnFirst", 0, "Response expected but not received - aborting", LOG_LEVEL_FATAL);
		SetCloseAndDelete();
	}
	m_content = GetHttpVersion() + " " + GetStatus() + " " + GetStatusText() + "\r\n";
}
void HttpDebugSocket::OnData(const char *p,size_t l)
{
	SendBuf(p,l);
	m_read_ptr += (int)l;
	if (m_read_ptr >= m_content_length && m_content_length)
	{
		Send("</pre><hr></body></html>");
		SetCloseAndDelete();
	}
}
Example #21
0
void HttpGetSocket::DoConnect(const std::string& host, unsigned short port)
{
	if (!Open(host, port))
	{
		if (!Connecting())
		{
			Handler().LogError(this, "HttpGetSocket", -1, "connect() failed miserably", LOG_LEVEL_FATAL);
			SetCloseAndDelete();
		}
	}
}
Example #22
0
/// Cancel patch transfer
bool AuthSocket::_HandleXferCancel()
{
    DEBUG_LOG("Entering _HandleXferCancel");

    ///- Close and delete the socket
    ibuf.Remove(1);                                         // clear input buffer

    SetCloseAndDelete();

    return true;
}
void CGeneralAgentHttpServer::GenerateDocument()
{
    std::string strSendBuf = "CGeneralAgentHttpServer.\n\r";

    strSendBuf += GetHttpDate()+"\r\n";
    strSendBuf += "Your Body:["+m_strBody+"]\r\n";

    Send(strSendBuf);

    SetCloseAndDelete();
}
void HttpDebugSocket::OnHeaderComplete()
{
	if (m_content_length || IsChunked())
	{
		Send("</pre><h3>Request Body</h3><pre style='background: #e0e0e0'>");
	}
	else
	{
		Send("</pre><hr></body></html>");
		SetCloseAndDelete();
	}
}
Example #25
0
void pSocket::cmdPiece(size_t piece, size_t offset, unsigned char *data)
{
	Session *sess = m_sess; 
	if (!sess)
	{
		SetCloseAndDelete();
		return;
	}
	
	Peer *peer = GetPeer();
	
	size_t length = peer ? peer -> GotSlice(piece, offset) : 0;
	
	if (length)
	{
		// Trafic Log
		std::string sMl;
		sMl.append("R ");
		// Local ip @
		sMl.append(m_sess->GetLocalIpAdr());
		sMl.append(" ");
		// Remote ip @
		sMl.append(this->GetRemoteAddress());
		sMl.append(" ");
		// Number of hops to the remote ip @
		std::ostringstream oss;
		oss<<this->m_peer->GetNumberOfHops();
		sMl.append(oss.str());
		sMl.append(" ");
		 // Number of bytes received from the remote peer
		std::ostringstream oss2;
		oss2<<length;
		sMl.append(oss2.str());
		sMl.append("\n");
		if(ACTIVATE_LOG)
		{	
			sess->AddDBytesToTrafficMatrix(this->GetRemoteAddress(), length);
			sess ->matrix_log->add_line(sMl,false);
		}
		sess -> SaveSlice(piece, offset, length, data);
		sess -> SetCheckComplete();
		//TOVERIFY
		sess -> GenerateRequest(peer);
	}
	else
	{
		char sMessage[100];
		sprintf(sMessage,  "(%d)cmdPiece: no length for slice write", m_id);
		if(ACTIVATE_LOG)
			this->pSocket_log->add_line(sMessage,true);
		
	}
}
Example #26
0
// --------------------------------------------------------------------------------------
void Ajp13Socket::OnHeader( short id, short len )
{
    if (id != 0x1234)
    {
        fprintf(stderr, "ABORT: bad packet id: %x\n", id);
        SetCloseAndDelete();
    }
    else
    {
        DEB(fprintf(stderr, "Packet size: %d bytes\n", len);)
    }
}
Example #27
0
 void OnEvent(int id) {
   if (id == m_event_open)
   {
     if (connected < antal)
     {
       TestSocket *p = new TestSocket(static_cast<EventHandler&>(Handler()));
       p -> SetDeleteByHandler();
       p -> Open(host, port);
       Handler().Add(p);
     }
     else
     {
       printf("Finished connecting. %d connected / %d failed / %d lost\n", connected, failed, lost);
     }
     m_event_open = AddEvent(interval / 1000, (interval % 1000) * 1000);
   }
   else
   if (id == m_event_request)
   {
     if (m_req_index < full_request.size())
     {
       if (full_request[m_req_index] == '\r')
       {
         printf("<CR>");
         fflush(stdout);
       }
       if (full_request[m_req_index] == '\n')
       {
         printf("<LF>");
         fflush(stdout);
       }
       SendBuf( &full_request[m_req_index], 1 );
       m_req_index++;
       m_event_request = AddEvent(delay / 1000, (delay % 1000) * 1000);
     }
     else
     {
       m_event_restart = AddEvent(3, 0);
     }
   }
   else
   if (id == m_event_restart)
   {
     m_req_index = 0;
     m_event_request = AddEvent(delay / 1000, (delay % 1000) * 1000);
   }
   else
   {
     fprintf(stderr, "%9lu %5u Unknown event id\n", UniqueIdentifier(), GetSockPort());
     SetCloseAndDelete();
   }
 }
Example #28
0
/// Cancel patch transfer
bool AuthSocket::_HandleXferCancel()
{
    DEBUG_LOG("Entering _HandleXferCancel");

    ///- Close and delete the socket
    ibuf.Remove(1);                                         //clear input buffer

    //ZThread::Thread::sleep(15);
    /// \todo What is the difference between SetCloseAndDelete() and the this->Close() higher?
    SetCloseAndDelete();

    return true;
}
Example #29
0
SOCKET Socket::CreateSocket(int af,int type, const std::string& protocol)
{
	struct protoent *p = NULL;
	SOCKET s;

#ifdef ENABLE_POOL
	m_socket_type = type;
	m_socket_protocol = protocol;
#endif
	if (protocol.size())
	{
		p = getprotobyname( protocol.c_str() );
		if (!p)
		{
			Handler().LogError(this, "getprotobyname", Errno, StrError(Errno), LOG_LEVEL_FATAL);
			SetCloseAndDelete();
#ifdef ENABLE_EXCEPTIONS
			throw Exception(std::string("getprotobyname() failed: ") + StrError(Errno));
#endif
			return INVALID_SOCKET;
		}
	}
	int protno = p ? p -> p_proto : 0;

	s = socket(af, type, protno);
	if (s == INVALID_SOCKET)
	{
		Handler().LogError(this, "socket", Errno, StrError(Errno), LOG_LEVEL_FATAL);
		SetCloseAndDelete();
#ifdef ENABLE_EXCEPTIONS
		throw Exception(std::string("socket() failed: ") + StrError(Errno));
#endif
		return INVALID_SOCKET;
	}
	Attach(s);
	OnOptions(af, type, protno, s);
	Attach(INVALID_SOCKET);
	return s;
}
Example #30
0
void UBSocket::PopEditor()
{
    if(m_popeditor)
    {
        Global::Get()->bug("UBSocket::PopEditor() was called, but the top editor is already being popped?!");
        Send("Something went wrong, somehow you are popping the top editor but it was already being popped?!\n");
        Send("Closing your connection now.\n");
        SetCloseAndDelete();
        return;
    }

    m_popeditor = true;
    SetPrompt();
}