예제 #1
0
int FileTransferProtocol::recvFilename(net::Socket &s, string &filename) {
	int bytes_received;

	// First, receive the filename size (3 bytes ascii-encoded unsigned integer)
	char buf[3];
	bytes_received = s.recv(buf, 3, 0);
	if (bytes_received == SOCKET_ERROR || bytes_received != 3) {
		onTransferError("Could not receive filename header size!");
		return -1;
	}

	// Try to parse what we have received
	size_t len;
	if (EOF == sscanf_s(buf, "%3lu", &len)) {
		onTransferError("Could not parse filename header size!");
		return -1;
	}

	// Finally, allocate a string and receive the filename
	char *nameBuf = (char*)malloc(len + 1);
	nameBuf[len] = '\0';
	bytes_received = s.recv(nameBuf, len, 0);
	if (bytes_received == SOCKET_ERROR || bytes_received != len) {
		free(nameBuf);
		onTransferError("Could not receive filename header!");
	}

	filename = string(nameBuf);
	free(nameBuf);
	return 0;
}
예제 #2
0
int FileTransferProtocol::sendFilename(net::Socket &s, string filename) {
	int bytes_sent;
	char fNameHeader[4];
	sprintf_s(fNameHeader, "%03lu", (unsigned long)filename.size());
	bytes_sent = s.send(fNameHeader, 3, 0);
	if (bytes_sent == SOCKET_ERROR || bytes_sent != 3) {
		onTransferError("Could not send filename size");
		return -1;
	}
	bytes_sent = s.send(filename.c_str(), filename.size(), 0);
	if (bytes_sent == SOCKET_ERROR || bytes_sent != filename.size()) {
		onTransferError("Could not send filename");
		return -1;
	}
	return 0;
}
예제 #3
0
void Server::onSocketRecv(net::Socket& socket, const MutableBuffer& buffer,
                          const net::Address& peerAddress)
{
    TraceL << "Data received: " << buffer.size() << endl;

    stun::Message message;
    char* buf = bufferCast<char*>(buffer);
    std::size_t len = buffer.size();
    std::size_t nread = 0;
    while (len > 0 && (nread = message.read(constBuffer(buf, len))) > 0) {
        if (message.classType() == stun::Message::Request ||
            message.classType() == stun::Message::Indication) {
            Request request(message, socket.transport(), socket.address(),
                            peerAddress);

            // TODO: Only authenticate stun::Message::Request types
            handleRequest(request,
                          _observer.authenticateRequest(this, request));
        } else {
            assert(0 && "unknown request type");
        }

        buf += nread;
        len -= nread;
    }
    if (len == buffer.size())
        WarnL << "Non STUN packet received" << std::endl;

#if 0
    stun::Message message;
    if (message.read(constBuffer(packet.data(), packet.size()))) {
        assert(message.state() == stun::Message::Request);

        Request request(*info->socket, message, info->socket->address(), info->peerAddress);
        AuthenticationState state = _observer.authenticateRequest(this, request);
        handleRequest(request, state);
    }
    else
#endif
}


void Server::onTCPSocketClosed(net::Socket& socket)
{
    TraceL << "TCP socket closed" << endl;
    releaseTCPSocket(&socket);
}
예제 #4
0
int FileTransferProtocol::sendCommand(net::Socket &s, char command) {
	int bytes_sent = s.send(&command, 1, 0);
	if (bytes_sent == SOCKET_ERROR || bytes_sent != 1) {
		onTransferError("Could not send command!");
		return -1;
	}
	return 0;
}
예제 #5
0
int FileTransferProtocol::sendErr(net::Socket &s) {
	char buf[3] = { 'E', 'R', 'R' };
	int bytes_sent = s.send(buf, 3, 0);
	if (bytes_sent == SOCKET_ERROR || bytes_sent != 3) {
		onTransferError("Could not send error notice to client!");
		return -1;
	}
	return 0;
}
예제 #6
0
int FileTransferProtocol::waitForAck(net::Socket &s, string errmsg) {
	char ackbuf[4] = "   "; // Either ACK or ERR
	int bytes_received = s.recv(ackbuf, 3, 0);
	if (bytes_received == SOCKET_ERROR || bytes_received != 3 || strcmp(ackbuf, "ERR") == 0) {
		onTransferError(errmsg);
		return -1;
	}
	return 0;
}
예제 #7
0
int FileTransferProtocol::sendAck(net::Socket &s) {
	char buf[3] = { 'A', 'C', 'K' };
	int bytes_sent = s.send(buf, 3, 0);
	if (bytes_sent == SOCKET_ERROR || bytes_sent != 3) {
		onTransferError("Could not acknowledge client!");
		return -1;
	}
	return 0;
}
예제 #8
0
namespace Network {
	Net::Socket serverSocket;
	void cleanUp() {
		Net::cleanup();
	}
	void init() {
		Net::startup();
		serverSocket.listenIPv4(30001);
	}
}
예제 #9
0
bool accept_client(net::Socket remote, std::string origin)
{
  /*
  printf("Verifying origin: \"%s\"\n"
         "Verifying remote: \"%s\"\n",
         origin.c_str(), remote.to_string().c_str());
  */
  (void) origin;
  return remote.address() == net::ip4::Addr(10,0,0,1);
}
예제 #10
0
void checkResponse(net::Socket& socket) throw (Exception)
{
  iostream::XdrInputStream& istream = socket.getXdrInputStream();

  int responseType = 0;
  istream.read(responseType);

  if (responseType == net::MessageProtocol::ERROR) {
    throw Exception("Exception has occurred");
  } else if (responseType != net::MessageProtocol::REPLY) {
    throw Exception("Internal implementation error");
  }
}
예제 #11
0
void checkResponse(net::Socket& socket) throw (Exception)
{
  iostream::XdrInputStream& istream = socket.getXdrInputStream();

  int responseType = 0;
  istream.read(responseType);

  if (responseType == net::MessageProtocol::ERROR) {
    throw Exception();
  } else if (responseType != net::MessageProtocol::REPLY) {
    throw Exception();
  }
}
예제 #12
0
size_t StreamSocketReceiver::receiveHeader(net::Socket &s)
{
	char buf[20];
	size_t bytes_received;
	if (bytes_received = s.recv(buf, 20) != 20) {
		throw IncompleteReceiveException(bytes_received, 20);
	}

	// Try to parse length of payload in header
	size_t len;
	if (EOF == sscanf_s(buf, "%20lu", &len)) {
		throw UnparseableHeaderException(buf);
	}
	return len;
}
예제 #13
0
int FileTransferProtocol::recvCommand(net::Socket &s, char &command) {
	char d;
	int bytes_received;
	bytes_received = s.recv(&d, 1, 0);
	if (bytes_received == SOCKET_ERROR || bytes_received != 1) {
		onTransferError("Could not receive direction from client!");
		return -1;
	}
	if (d != 'D' && d != 'U' && d != 'L' && d != 'Q') {
		onTransferError("Client sent invalid direction!");
		return -1;
	}
	command = d;
	return 0;
}
예제 #14
0
	void init(string ip, unsigned short _port) {
		Net::startup();

		try {
			socketClient.connectIPv4(ip, _port);
		}
		catch (...) {
			DebugError("Cannot connect to the server!");
			return;
		}

		threadRun = true;
		mutex = MutexCreate();
		t = ThreadCreate(networkThread, NULL);
	}
예제 #15
0
void StreamSocketReceiver::receivePayload(net::Socket &s, ostream &stream, size_t len)
{
	void *buf = malloc(this->packet_size);
	size_t bytes_read = 0;
	while (bytes_read < len) {
		size_t exp_bytes = min(this->packet_size, len - bytes_read);
		size_t bytes_recv = s.recv((char*)buf, exp_bytes);
		if (bytes_recv != exp_bytes) {
			free(buf);
			throw IncompleteReceiveException(bytes_read + bytes_recv, len);
		}
		bytes_read += bytes_recv;
		stream.write((char*)buf, bytes_recv);
	}
	free(buf);
}
예제 #16
0
namespace Network {

	Net::Socket socketClient;
	Thread_t t;
	Mutex_t mutex;
	std::queue<Request> reqs;
	bool threadRun = true;

	void init(string ip, unsigned short _port) {
		Net::startup();

		try {
			socketClient.connectIPv4(ip, _port);
		}
		catch (...) {
			DebugError("Cannot connect to the server!");
			return;
		}

		threadRun = true;
		mutex = MutexCreate();
		t = ThreadCreate(networkThread, NULL);
	}

	int getRequestCount() { return reqs.size(); }
	Net::Socket& getClientSocket() { return socketClient; }

	ThreadFunc networkThread(void *) {
		while (true) {
			MutexLock(mutex);
			if (!threadRun) {
				MutexUnlock(mutex);
				break;
			}
			if (reqs.empty()) {
				MutexUnlock(mutex);
				continue;
			}
			Request& r = reqs.front();
			//if (r._signal == PLAYER_PACKET_SEND && ((PlayerPacket*)r._dataSend)->onlineID != player::onlineID)
			//	cout << "[ERROR]WTF!!!" << endl;
			if (r._dataSend != nullptr && r._dataLen != 0) {
				Net::Buffer buffer(r._dataLen + sizeof(int) * 2);
				int len = r._dataLen + sizeof(int);
				buffer.write((void*)&len, sizeof(int));
				buffer.write((void*)&r._signal, sizeof(int));
				buffer.write((void*)r._dataSend, r._dataLen);
				getClientSocket().send(buffer);
			}
			else {
				Net::Buffer buffer(sizeof(int) * 2);
				int len = sizeof(int);
				buffer.write((void*)&len, sizeof(int));
				buffer.write((void*)&r._signal, sizeof(int));
				getClientSocket().send(buffer);
			}
			if (r._callback) { //判断有无回调函数
				auto callback = r._callback;
				MutexUnlock(mutex);
				int len = getClientSocket().recvInt();   //获得数据长度
				Net::Buffer buffer(len);
				getClientSocket().recv(buffer, Net::BufferConditionExactLength(len));
				if (len > 0) callback(buffer.getData(), len); //调用回调函数
				MutexLock(mutex);
			}
			reqs.pop();
			MutexUnlock(mutex);
		}
		return 0;
	}

	void pushRequest(Request& r) {
		if (reqs.size() + 1 > networkRequestMax) {  //超过请求队列长度,试图精简队列
			if (!reqs.front().isImportant()) reqs.pop();
		}
		if (reqs.size() + 1 > networkRequestMax * 2) {  //大量超过请求队列长度,只保留重要请求
			std::queue<Request> q;
			while (reqs.size() != 0) {
				if (reqs.front().isImportant()) q.push(reqs.front());
				reqs.pop();
			}
			reqs = q;
		}
		reqs.push(r);
	}
	
	void cleanUp() {
		threadRun = false;
		ThreadWait(t);
		ThreadDestroy(t);
		MutexDestroy(mutex);
		getClientSocket().close();
		Net::cleanup();
	}
}
예제 #17
0
	void init() {
		Net::startup();
		serverSocket.listenIPv4(30001);
	}