Beispiel #1
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_writeBuf() {
  int result;
  int fd = KNI_GetParameterAsInt(1);
  int offset = KNI_GetParameterAsInt(3);
  int length = KNI_GetParameterAsInt(4);

  KNI_StartHandles(1);
  KNI_DeclareHandle(buffer_object);
  KNI_GetParameterAsObject(2, buffer_object);
  char *buffer = (char *) SNI_GetRawArrayPointer(buffer_object) + offset;

  result = jvm_send(fd, buffer, length, 0); // We rely on open0() for setting the socket to non-blocking
  KNI_EndHandles();

  if (result < 0) {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *) SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_WRITE;
      }
      SNI_BlockThread();
    }
  }

  KNI_ReturnInt(result);
}
Beispiel #2
0
static jboolean
asynchronous_socket_read(void *parameter, jboolean is_non_blocking) {
  int n;
  SocketBufferParameter *p = (SocketBufferParameter *) parameter;

  //JVMSPI_PrintRaw("[");
  n = recv(p->fd, p->buffer, p->buffer_size, 0);
  //JVMSPI_PrintRaw("]");
  if (n == 0) {
    // If remote side has shut down the connection gracefully, and all
    // data has been received, recv() will complete immediately with
    // zero bytes received.
    //
    // This is true for Win32/CE and Linux
    n = -1;
  }

  if (n < 0) {
    if (GET_LAST_ERROR() == EWOULDBLOCK && is_non_blocking) {
      return KNI_FALSE;
    }
  }
  p->buffer_size = n;

  return KNI_TRUE;
}
Beispiel #3
0
/**
 * Send a packet over UDP
 * @param p    the packet to send
 * @param recv the receiver (target) of the packet
 * @param all  send the packet using all sockets that can send it
 * @param broadcast whether to send a broadcast message
 */
void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool all, bool broadcast)
{
	if (this->sockets.Length() == 0) this->Listen();

	for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
		/* Make a local copy because if we resolve it we cannot
		 * easily unresolve it so we can resolve it later again. */
		NetworkAddress send(*recv);

		/* Not the same type */
		if (!send.IsFamily(s->first.GetAddress()->ss_family)) continue;

		p->PrepareToSend();

#ifndef BEOS_NET_SERVER /* will work around this, some day; maybe. */
		if (broadcast) {
			/* Enable broadcast */
			unsigned long val = 1;
			if (setsockopt(s->second, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) {
				DEBUG(net, 1, "[udp] setting broadcast failed with: %i", GET_LAST_ERROR());
			}
		}
#endif

		/* Send the buffer */
		int res = sendto(s->second, (const char*)p->buffer, p->size, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength());
		DEBUG(net, 7, "[udp] sendto(%s)", send.GetAddressAsString());

		/* Check for any errors, but ignore it otherwise */
		if (res == -1) DEBUG(net, 1, "[udp] sendto(%s) failed with: %i", send.GetAddressAsString(), GET_LAST_ERROR());

		if (!all) break;
	}
}
Beispiel #4
0
int ConfigOpenFile(ConfigFileInfo *Info, const char *File)
{
	Info -> fp = fopen(File, "r");
	if( Info -> fp == NULL )
		return GET_LAST_ERROR();
	else
		return 0;
}
Beispiel #5
0
static jboolean
asynchronous_socket_write(void *parameter, jboolean is_non_blocking) {
  SocketBufferParameter *p = (SocketBufferParameter *) parameter;
  int n = send(p->fd, p->buffer, p->buffer_size, 0);
  done_count ++;
  if (n < 0) {
    if (GET_LAST_ERROR() == EWOULDBLOCK && is_non_blocking) {
      return KNI_FALSE;
    }
  }
  p->buffer_size = n;

  return KNI_TRUE;
}
Beispiel #6
0
/**
 * Sends all the buffered packets out for this client. It stops when:
 *   1) all packets are send (queue is empty)
 *   2) the OS reports back that it can not send any more
 *      data right now (full network-buffer, it happens ;))
 *   3) sending took too long
 * @param closing_down Whether we are closing down the connection.
 * @return \c true if a (part of a) packet could be sent and
 *         the connection is not closed yet.
 */
SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
{
	ssize_t res;
	Packet *p;

	/* We can not write to this socket!! */
	if (!this->writable) return SPS_NONE_SENT;
	if (!this->IsConnected()) return SPS_CLOSED;

	p = this->packet_queue;
	while (p != NULL) {
		res = send(this->sock, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
		if (res == -1) {
			int err = GET_LAST_ERROR();
			if (err != EWOULDBLOCK) {
				/* Something went wrong.. close client! */
				if (!closing_down) {
					DEBUG(net, 0, "send failed with error %d", err);
					this->CloseConnection();
				}
				return SPS_CLOSED;
			}
			return SPS_PARTLY_SENT;
		}
		if (res == 0) {
			/* Client/server has left us :( */
			if (!closing_down) this->CloseConnection();
			return SPS_CLOSED;
		}

		p->pos += res;

		/* Is this packet sent? */
		if (p->pos == p->size) {
			/* Go to the next packet */
			this->packet_queue = p->next;
			delete p;
			p = this->packet_queue;
		} else {
			return SPS_PARTLY_SENT;
		}
	}

	return SPS_ALL_SENT;
}
Beispiel #7
0
void PrepareEnvironment(void)
{
	char ConfigDirectory[2048];

	GetConfigDirectory(ConfigDirectory);

	if( mkdir(ConfigDirectory, S_IRWXU | S_IRGRP | S_IROTH) != 0 )
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		printf("mkdir : %s failed : %s\n", ConfigDirectory, ErrorMessage);
	}

	printf("Please put configure file into `%s' and rename it to `config'.\n", ConfigDirectory);
}
Beispiel #8
0
void ShowErrorMassage(ThreadContext *Context, char ProtocolCharacter)
{
	char	DateAndTime[32];

	int		ErrorNum = GET_LAST_ERROR();
	char	ErrorMessage[320];

	if( ErrorMessages == TRUE || DEBUGMODE )
	{
		GetCurDateAndTime(DateAndTime, sizeof(DateAndTime));

		ErrorMessage[0] ='\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

	}

	if( ErrorMessages == TRUE )
	{
		printf("%s[%c][%s][%s][%s] An error occured : %d : %s .\n",
			   DateAndTime,
			   ProtocolCharacter,
			   Context -> ClientIP,
			   DNSGetTypeName(Context -> RequestingType),
			   Context -> RequestingDomain,
			   ErrorNum,
			   ErrorMessage
			   );
	}

	DEBUG_FILE("[%c][%s][%s][%s] An error occured : %d : %s .\n",
			   ProtocolCharacter,
			   Context -> ClientIP,
			   DNSGetTypeName(Context -> RequestingType),
			   Context -> RequestingDomain,
			   ErrorNum,
			   ErrorMessage
			   );
}
Beispiel #9
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_readBuf() {
  int result;
  int fd = KNI_GetParameterAsInt(1);
  int offset = KNI_GetParameterAsInt(3);
  int length = KNI_GetParameterAsInt(4);

  KNI_StartHandles(1);
  KNI_DeclareHandle(buffer_object);
  KNI_GetParameterAsObject(2, buffer_object);
  char *buffer = (char *) SNI_GetRawArrayPointer(buffer_object) + offset;

  result = jvm_recv(fd, buffer, length, 0); // We rely on open0() for setting the socket to non-blocking
  KNI_EndHandles();

  if (result == 0) {
    // If remote side has shut down the connection gracefully, and all
    // data has been received, recv() will complete immediately with
    // zero bytes received.
    //
    // This is true for Win32/CE and Linux
    result = -1;
  }
  else if (result < 0) {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *)SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_READ;
      }
      SNI_BlockThread();
    }
  }

  KNI_ReturnInt(result);
}
Beispiel #10
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_writeByte() {
  int fd = KNI_GetParameterAsInt(1);
  char byte = (char) KNI_GetParameterAsInt(2);

  // We rely on open0() for setting the socket to non-blocking
  int result = jvm_send(fd, &byte, 1, 0);

  if (result < 0) {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *)SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_WRITE;
      }
      SNI_BlockThread();
    }
  }

  KNI_ReturnInt(result);
}
Beispiel #11
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_readByte() {
  jint result = -1;
  unsigned char byte;

  int fd = KNI_GetParameterAsInt(1);
  int n = jvm_recv(fd, (char*)&byte, 1, 0);

  if (n == 1) {
    result = byte; // do not sign-extend
    GUARANTEE(0 <= result && result <= 255, "no sign extension");
  }
  else if (n == 0) {
    // If remote side has shut down the connection gracefully, and all
    // data has been received, recv() will complete immediately with
    // zero bytes received.
    //
    // This is true for Win32/CE and Linux
    result = -1;
  }
  else {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *)SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_READ;
      }
      SNI_BlockThread();
    } else {
      result = -1;
    }
  }

  KNI_ReturnInt(result);
}
Beispiel #12
0
/**
 * Receives a packet for the given client
 * @return The received packet (or NULL when it didn't receive one)
 */
Packet *NetworkTCPSocketHandler::ReceivePacket()
{
	ssize_t res;

	if (!this->IsConnected()) return NULL;

	if (this->packet_recv == NULL) {
		this->packet_recv = new Packet(this);
	}

	Packet *p = this->packet_recv;

	/* Read packet size */
	if (p->pos < sizeof(PacketSize)) {
		while (p->pos < sizeof(PacketSize)) {
		/* Read the size of the packet */
			res = recv(this->sock, (char*)p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0);
			if (res == -1) {
				int err = GET_LAST_ERROR();
				if (err != EWOULDBLOCK) {
					/* Something went wrong... (104 is connection reset by peer) */
					if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
					this->CloseConnection();
					return NULL;
				}
				/* Connection would block, so stop for now */
				return NULL;
			}
			if (res == 0) {
				/* Client/server has left */
				this->CloseConnection();
				return NULL;
			}
			p->pos += res;
		}

		/* Read the packet size from the received packet */
		p->ReadRawPacketSize();

		if (p->size > SEND_MTU) {
			this->CloseConnection();
			return NULL;
		}
	}

	/* Read rest of packet */
	while (p->pos < p->size) {
		res = recv(this->sock, (char*)p->buffer + p->pos, p->size - p->pos, 0);
		if (res == -1) {
			int err = GET_LAST_ERROR();
			if (err != EWOULDBLOCK) {
				/* Something went wrong... (104 is connection reset by peer) */
				if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
				this->CloseConnection();
				return NULL;
			}
			/* Connection would block */
			return NULL;
		}
		if (res == 0) {
			/* Client/server has left */
			this->CloseConnection();
			return NULL;
		}

		p->pos += res;
	}

	/* Prepare for receiving a new packet */
	this->packet_recv = NULL;

	p->PrepareToRead();
	return p;
}
static int Query(	SOCKET				*PrimarySocket,
					SOCKET				*SecondarySocket,
					DNSQuaryProtocol	PrimaryProtocol,
					char				*QueryContent,
					int					QueryContentLength,

					SOCKET				*ClientSocket,
					CompatibleAddr		*ClientAddr,
					ExtendableBuffer	*Buffer
					)
{
	int					State;

	DNSRecordType		SourceType;
	char				*DNSBody = DNSGetDNSBody(QueryContent);

	char				ProtocolCharacter = ' ';

	char				QueryDomain[256];

	char				DateAndTime[32];

	QueryContext		Context;

	GetCurDateAndTime(DateAndTime, sizeof(DateAndTime));

	QueryDomain[0] = '\0';
	DNSGetHostName(DNSBody, DNSJumpHeader(DNSBody), QueryDomain);

	SourceType = (DNSRecordType)DNSGetRecordType(DNSJumpHeader(DNSBody));

	Context.PrimarySocket = PrimarySocket;
	Context.SecondarySocket = SecondarySocket;
	Context.PrimaryProtocolToServer = PrimaryProtocol;
	Context.ProtocolToSrc = DNS_QUARY_PROTOCOL_TCP;
	Context.Compress = TRUE;

	State = QueryBase(&Context,

					  QueryContent,
					  QueryContentLength,

					  Buffer,
					  QueryDomain,
					  SourceType,
					  &ProtocolCharacter
					  );

	switch( State )
	{
		case QUERY_RESULT_DISABLE:
			((DNSHeader *)DNSBody) -> Flags.Direction = 1;
			((DNSHeader *)DNSBody) -> Flags.ResponseCode = 5;
			send(*ClientSocket, QueryContent, QueryContentLength, 0);
			if( Family == AF_INET )
			{
				PRINT("%s[R][%s:%d][%s][%s] Refused.\n", DateAndTime, inet_ntoa(ClientAddr -> Addr4.sin_addr), ClientAddr -> Addr4.sin_port, DNSGetTypeName(SourceType), QueryDomain);
			} else {
				char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

				IPv6AddressToAsc(&(ClientAddr -> Addr6.sin6_addr), Addr);

				PRINT("%s[R][%s:%d][%s][%s] Refused.\n", DateAndTime, Addr, ClientAddr -> Addr6.sin6_port, DNSGetTypeName(SourceType), QueryDomain);

			}
			return -1;
			break;

		case QUERY_RESULT_ERROR:
			if( ErrorMessages == TRUE )
			{
				int		ErrorNum = GET_LAST_ERROR();
				char	ErrorMessage[320];

				ErrorMessage[0] ='\0';

				GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));
				if( Family == AF_INET )
				{
					printf("%s[%c][%s][%s][%s] Error occured : %d : %s .\n",
						   DateAndTime,
						   ProtocolCharacter,
						   inet_ntoa(ClientAddr -> Addr4.sin_addr),
						   DNSGetTypeName(SourceType),
						   QueryDomain,
						   ErrorNum,
						   ErrorMessage
						   );
				} else {
					char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

					IPv6AddressToAsc(&(ClientAddr -> Addr6.sin6_addr), Addr);

					printf("%s[%c][%s][%s][%s] Error occured : %d : %s .\n",
						   DateAndTime,
						   ProtocolCharacter,
						   Addr,
						   DNSGetTypeName(SourceType),
						   QueryDomain,
						   ErrorNum,
						   ErrorMessage
						   );
				}
			}
			return -1;
			break;

		default: /* Succeed */
			send(*ClientSocket, ExtendableBuffer_GetData(Buffer), State, 0);

			if( ShowMassages == TRUE )
			{
				char InfoBuffer[3072];
				InfoBuffer[0] = '\0';
				GetAllAnswers(DNSGetDNSBody(ExtendableBuffer_GetData(Buffer)), InfoBuffer);

				if( Family == AF_INET )
				{
					PRINT("%s[%c][%s][%s][%s] :\n%s", DateAndTime, ProtocolCharacter, inet_ntoa(ClientAddr ->Addr4.sin_addr), DNSGetTypeName(SourceType), QueryDomain, InfoBuffer);
				} else {
					char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

					IPv6AddressToAsc(&(ClientAddr -> Addr6.sin6_addr), Addr);

					PRINT("%s[%c][%s][%s][%s] :\n%s", DateAndTime, ProtocolCharacter, Addr, DNSGetTypeName(SourceType), QueryDomain, InfoBuffer);
				}
			}
			return 0;
			break;

	}
}
static int TCPRecv(RecvInfo *Info)
{
	SOCKET				Socket	=	Info -> Socket;
	CompatibleAddr		Peer	=	Info -> Peer;
	int					state;
	char				ResultBuffer[1024];
	ExtendableBuffer	Buffer;

	/* Sockets to server */
	SOCKET				TCPSocket = INVALID_SOCKET;
	SOCKET				UDPSocket = INVALID_SOCKET;
	SOCKET				*PrimarySocketPtr;
	SOCKET				*SecondarySocketPtr;
	DNSQuaryProtocol	PrimaryProtocol;

	char				ProtocolStr[8] = {0};

	strncpy(ProtocolStr, ConfigGetString(&ConfigInfo, "PrimaryServer"), 3);
	StrToLower(ProtocolStr);

	if( strcmp(ProtocolStr, "tcp") == 0 )
	{
		PrimaryProtocol = DNS_QUARY_PROTOCOL_TCP;
		PrimarySocketPtr = &TCPSocket;

		if( ConfigGetString(&ConfigInfo, "UDPServer") != NULL )
			SecondarySocketPtr = &UDPSocket;
		else
			SecondarySocketPtr = NULL;

	} else {
		PrimaryProtocol = DNS_QUARY_PROTOCOL_UDP;
		PrimarySocketPtr = &UDPSocket;

		if( ConfigGetString(&ConfigInfo, "TCPServer") != NULL )
			SecondarySocketPtr = &TCPSocket;
		else
			SecondarySocketPtr = NULL;
	}

	ExtendableBuffer_Init(&Buffer, 512, 10240);

	while(TRUE){
		state = recv(Socket, ResultBuffer, sizeof(ResultBuffer), MSG_NOSIGNAL);
		if(GET_LAST_ERROR() == TCP_TIME_OUT)
		{
			break;
		}

		if( state < 1 )
		{
			break;
		}

		Query(PrimarySocketPtr, SecondarySocketPtr, PrimaryProtocol, ResultBuffer, state, &Socket, &Peer, &Buffer);
		ExtendableBuffer_Reset(&Buffer);

	}

	CLOSE_SOCKET(TCPSocket);
	CLOSE_SOCKET(UDPSocket);

	CLOSE_SOCKET(Socket);

	if( Family == AF_INET )
	{
		INFO("Closed TCP connection to %s:%d\n", inet_ntoa(Peer.Addr4.sin_addr), Peer.Addr4.sin_port);
	} else {
		char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

		IPv6AddressToAsc(&(Peer.Addr6.sin6_addr), Addr);

		INFO("Closed TCP connection to %s:%d\n", Addr, Peer.Addr6.sin6_port);
	}

	SafeFree(Info);

	EXIT_THREAD(0);
}
/* Functions */
int QueryDNSListenTCPInit(void)
{
	static struct _Address	ListenAddr;

	const char	*LocalAddr = ConfigGetString(&ConfigInfo, "LocalInterface");
	int			LocalPort = ConfigGetInt32(&ConfigInfo, "LocalPort");

	int			AddrLen;

	Family = GetAddressFamily(LocalAddr);

	ListenSocketTCP = socket(Family, SOCK_STREAM, IPPROTO_TCP);
	if(ListenSocketTCP == INVALID_SOCKET)
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Creating TCP socket failed. %d : %s\n", ErrorNum, ErrorMessage);
		return -1;
	}

	memset(&ListenAddr, 0, sizeof(ListenAddr));

	if( Family == AF_INET )
	{
		FILL_ADDR4(ListenAddr.Addr.Addr4, AF_INET, LocalAddr, LocalPort);

		AddrLen = sizeof(struct sockaddr);
	} else {
		char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

		sscanf(LocalAddr, "[%s]", Addr);

		ListenAddr.Addr.Addr6.sin6_family = Family;
		ListenAddr.Addr.Addr6.sin6_port = htons(LocalPort);
		IPv6AddressToNum(Addr, &(ListenAddr.Addr.Addr6.sin6_addr));

		AddrLen = sizeof(struct sockaddr_in6);
	}

	if(	bind(ListenSocketTCP, (struct sockaddr*)&(ListenAddr.Addr), AddrLen) != 0 )
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Opening TCP socket failed. %d : %s\n", ErrorNum, ErrorMessage);
		return -2;
	}

	if( listen(ListenSocketTCP, 16) == SOCKET_ERROR )
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Opening TCP socket failed. %d : %s\n", ErrorNum, ErrorMessage);
		return -3;
	}

	Inited = TRUE;

	return 0;
}
Beispiel #16
0
/**
 * Handle receiving of HTTP data.
 * @return state of the receival of HTTP data.
 *         > 0: we need more cycles for downloading
 *         = 0: we are done downloading
 *         < 0: we have hit an error
 */
int NetworkHTTPSocketHandler::Receive()
{
	for (;;) {
		ssize_t res = recv(this->sock, (char *)this->recv_buffer + this->recv_pos, lengthof(this->recv_buffer) - this->recv_pos, 0);
		if (res == -1) {
			int err = GET_LAST_ERROR();
			if (err != EWOULDBLOCK) {
				/* Something went wrong... (104 is connection reset by peer) */
				if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
				return -1;
			}
			/* Connection would block, so stop for now */
			return 1;
		}

		/* No more data... did we get everything we wanted? */
		if (res == 0) {
			if (this->recv_length != 0) return -1;

			this->callback->OnReceiveData(NULL, 0);
			return 0;
		}

		/* Wait till we read the end-of-header identifier */
		if (this->recv_length == 0) {
			int read = this->recv_pos + res;
			int end = min(read, lengthof(this->recv_buffer) - 1);

			/* Do a 'safe' search for the end of the header. */
			char prev = this->recv_buffer[end];
			this->recv_buffer[end] = '\0';
			char *end_of_header = strstr(this->recv_buffer, END_OF_HEADER);
			this->recv_buffer[end] = prev;

			if (end_of_header == NULL) {
				if (read == lengthof(this->recv_buffer)) {
					DEBUG(net, 0, "[tcp/http] header too big");
					return -1;
				}
				this->recv_pos = read;
			} else {
				int ret = this->HandleHeader();
				if (ret <= 0) return ret;

				this->recv_length = ret;

				end_of_header += strlen(END_OF_HEADER);
				int len = min(read - (end_of_header - this->recv_buffer), res);
				if (len != 0) {
					this->callback->OnReceiveData(end_of_header, len);
					this->recv_length -= len;
				}

				this->recv_pos = 0;
			}
		} else {
			res = min(this->recv_length, res);
			/* Receive whatever we're expecting. */
			this->callback->OnReceiveData(this->recv_buffer, res);
			this->recv_length -= res;
		}
	}
}
Beispiel #17
0
/* Functions */
int QueryDNSListenUDPInit(ConfigFileInfo *ConfigInfo)
{
	CompatibleAddr ListenAddr;

	const char	*LocalAddr = ConfigGetRawString(ConfigInfo, "LocalInterface");

	int			LocalPort = ConfigGetInt32(ConfigInfo, "LocalPort");

	int			AddrLen;

	RefusingResponseCode = ConfigGetInt32(ConfigInfo, "RefusingResponseCode");

	Family = GetAddressFamily(LocalAddr);

	ListenSocketUDP = socket(Family, SOCK_DGRAM, IPPROTO_UDP);

	if(ListenSocketUDP == INVALID_SOCKET)
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Creating UDP socket failed. %d : %s\n",
				 ErrorNum,
				 ErrorMessage
				 );
		return -1;
	}

	memset(&ListenAddr, 0, sizeof(ListenAddr));

	if( Family == AF_INET )
	{
		FILL_ADDR4(ListenAddr.Addr4, AF_INET, LocalAddr, LocalPort);

		AddrLen = sizeof(struct sockaddr);
	} else {
		char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

		sscanf(LocalAddr, "[%s]", Addr);

		ListenAddr.Addr6.sin6_family = Family;
		ListenAddr.Addr6.sin6_port = htons(LocalPort);
		IPv6AddressToNum(Addr, &(ListenAddr.Addr6.sin6_addr));

		AddrLen = sizeof(struct sockaddr_in6);
	}

	if(	bind(ListenSocketUDP, (struct sockaddr*)&(ListenAddr), AddrLen)
			!= 0
		)
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Opening UDP socket failed. %d : %s\n",
				 ErrorNum,
				 ErrorMessage
				 );
		return -2;
	}

	CREATE_MUTEX(ListenMutex);
	EFFECTIVE_LOCK_INIT(LockOfSendBack);

	MaximumMessageSize = GetMaximumMessageSize(ListenSocketUDP);
	if(MaximumMessageSize < 0)
	{
		MaximumMessageSize = 1000;
	}
	Inited = TRUE;

	return 0;
}
Beispiel #18
0
static int QueryDNSListenUDP(void *ID){
	socklen_t			AddrLen;

	CompatibleAddr		ClientAddr;

	int					State;

	ThreadContext		Context;

	char				RequestEntity[1024];

	InitContext(&Context, RequestEntity);

	/* Listen and accept requests */
	while(TRUE)
	{
		memset(&ClientAddr, 0, sizeof(ClientAddr));

		GET_MUTEX(ListenMutex);

		if( Family == AF_INET )
		{
			AddrLen = sizeof(struct sockaddr);
			State = recvfrom(ListenSocketUDP,
							 RequestEntity,
							 sizeof(RequestEntity),
							 0,
							 (struct sockaddr *)&(ClientAddr.Addr4),
							 &AddrLen
							 );

		} else {
			AddrLen = sizeof(struct sockaddr_in6);
			State = recvfrom(ListenSocketUDP,
							 RequestEntity,
							 sizeof(RequestEntity),
							 0,
							 (struct sockaddr *)&(ClientAddr.Addr6),
							 &AddrLen
							 );

		}
		RELEASE_MUTEX(ListenMutex);

		if(State < 1)
		{
			if( ErrorMessages == TRUE )
			{
				int		ErrorNum = GET_LAST_ERROR();
				char	ErrorMessage[320];

				ErrorMessage[0] ='\0';

				GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));
				if( Family == AF_INET )
				{
					printf("An error occured while receiving from %s : %d : %s .\n",
						   inet_ntoa(ClientAddr.Addr4.sin_addr),
						   ErrorNum,
						   ErrorMessage
						   );
				} else {
					char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

					IPv6AddressToAsc(&(ClientAddr.Addr6.sin6_addr), Addr);

					printf("An error occured while receiving from %s : %d : %s .\n",
						   Addr,
						   ErrorNum,
						   ErrorMessage
						   );

				}
			}
			continue;
		}

		Context.RequestLength = State;

		Query(&Context, &ClientAddr);
		ExtendableBuffer_Reset(Context.ResponseBuffer);

	}

	return 0;
}
Beispiel #19
0
/**
 * Function to handle node discovery process
 *
 * @param args
 *
 * @return NCSCC_RC_SUCCESS
 * @return NCSCC_RC_FAILURE
 *
 */
void node_discovery_process(void *arg)
{
	TRACE_ENTER();

	int poll_ret = 0;
	int end_server = FALSE, compress_array = FALSE;
	int close_conn = FALSE;
	DTM_INTERNODE_CB *dtms_cb = dtms_gl_cb;

	int current_size = 0, i, j;

	/* Data Received */
	uns8 inbuf[DTM_INTERNODE_RECV_BUFFER_SIZE];
	uns8 *data1;		/* Used for DATAGRAM decoding */
	uns16 recd_bytes = 0;
	uns16 recd_buf_len = 0;
	int node_info_buffer_len = 0;
	uns8 node_info_hrd[NODE_INFO_PKT_SIZE];
	char node_ip[INET6_ADDRSTRLEN];

	memset(&node_ip, 0, INET6_ADDRSTRLEN);
	/*************************************************************/
	/* Set up the initial bcast or mcast receiver socket */
	/*************************************************************/

	if (dtms_cb->mcast_flag != TRUE) {

		if (NCSCC_RC_SUCCESS != dtm_dgram_bcast_listener(dtms_cb)) {
			LOG_ER("DTM:Set up the initial bcast  receiver socket   failed");
			exit(1);
		}

	} else {

		if (NCSCC_RC_SUCCESS != dtm_dgram_mcast_listener(dtms_cb)) {
			LOG_ER("DTM:Set up the initial mcast  receiver socket   failed");
			exit(1);
		}
	}

	/*************************************************************/
	/* Set up the initial listening socket */
	/*************************************************************/
	if (NCSCC_RC_SUCCESS != dtm_stream_nonblocking_listener(dtms_cb)) {
		LOG_ER("DTM: Set up the initial stream nonblocking serv  failed");
		exit(1);
	}
#if 0

	if (add_self_node(dtms_cb) != NCSCC_RC_SUCCESS) {
		LOG_ER("DTM: add_self_node  failed");
		exit(1);
	}
#endif

	/*************************************************************/
	/* Initialize the pollfd structure */
	/*************************************************************/
	memset(fds, 0, sizeof(fds));

	/*************************************************************/
	/* Set up the initial listening socket */
	/*************************************************************/

	fds[0].fd = dtms_cb->dgram_sock_rcvr;
	fds[0].events = POLLIN;

	/*************************************************************/
	/* Set up the initial listening socket */
	/*************************************************************/

	fds[1].fd = dtms_cb->stream_sock;
	fds[1].events = POLLIN;

	fds[2].fd = dtms_cb->mbx_fd;
	fds[2].events = POLLIN;
	nfds = 3;

	/*************************************************************/
	/* Set up the initial listening socket */
	/*************************************************************/

	if (dtm_construct_node_info_hdr(dtms_cb, node_info_hrd, &node_info_buffer_len) != NCSCC_RC_SUCCESS) {

		LOG_ER("DTM: dtm_construct_node_info_hdr failed"); 
		goto done;

	}

	/*************************************************************/
	/* Loop waiting for incoming connects or for incoming data */
	/* on any of the connected sockets. */
	/*************************************************************/

	do {
		/***********************************************************/
		/* Call poll() and wait . */
		/***********************************************************/
		int fd_check = 0;
		poll_ret = poll(fds, nfds, DTM_TCP_POLL_TIMEOUT);
		/***********************************************************/

		/* Check to see if the poll call failed. */
		/***********************************************************/
		if (poll_ret < 0) {
			LOG_ER(" poll() failed");
			continue;
		}
		/***********************************************************/
		/* Check to see if the 3 minute time out expired. */
		/***********************************************************/
		if (poll_ret == 0) {
			TRACE("DTM : poll() timed out");
			continue;
		}

		/***********************************************************/
		/* One or more descriptors are readable. Need to */
		/* determine which ones they are. */
		/***********************************************************/
		current_size = nfds;
		for (i = 0; i < current_size; i++) {

			/*********************************************************/
			/* Loop through to find the descriptors that returned */
			/* POLLIN and determine whether it’s the listening */
			/* or the active connection. */
			/*********************************************************/
			if (POLLIN & fds[i].revents) {

				if (fds[i].fd == dtms_cb->dgram_sock_rcvr) {

					fd_check++;
					/* Data Received */
					memset(inbuf, 0, DTM_INTERNODE_RECV_BUFFER_SIZE);
					recd_bytes = 0;
					recd_buf_len = 0;

					recd_bytes = dtm_dgram_recvfrom_bmcast(dtms_cb, node_ip, inbuf, sizeof(inbuf));

					if (recd_bytes == 0) {
						LOG_ER("DTM: recd bytes=0 on DGRAM sock");
						continue;
					}

					data1 = inbuf;	/* take care of previous address */

					recd_buf_len = ncs_decode_16bit(&data1);

					if (recd_buf_len == recd_bytes) {

						int new_sd = -1;

						new_sd = dtm_process_connect(dtms_cb, node_ip, inbuf, (recd_bytes - 2));

						if (new_sd == -1)
							continue;

					/*****************************************************/
						/* Add the new incoming connection to the */
						/* pollfd structure */
					/*****************************************************/
						LOG_IN("DTM: add New incoming connection to fd : %d\n", new_sd);
						fds[nfds].fd = new_sd;
						fds[nfds].events = POLLIN | POLLERR | POLLHUP | POLLNVAL;
						nfds++;

					} else {
						/* Log message that we are dropping the data */
						LOG_ER("DTM: BRoadcastLEN-MISMATCH: dropping the data");
					}

				} else if (fds[i].fd == dtms_cb->stream_sock) {

					int new_sd = -1;
					uns32 local_rc = NCSCC_RC_SUCCESS;
					fd_check++;
				/*******************************************************/
					/* Listening descriptor is readable. */
				/*******************************************************/
					TRACE(" DTM :Listening socket is readable");
				/*******************************************************/
					/* Accept all incoming connections that are */
					/* queued up on the listening socket before we */
					/* loop back and call poll again. */
				/*******************************************************/
					/* do { */
				/*****************************************************/
					/* Accept each incoming connection. If */
					/* accept fails with EWOULDBLOCK, then we */
					/* have accepted all of them. Any other */
					/* failure on accept will cause us to end the */
					/* serv. */
				/*****************************************************/
					new_sd = dtm_process_accept(dtms_cb, dtms_cb->stream_sock);
					if (new_sd < 0) {
						
						if (!IS_BLOCKIN_ERROR(GET_LAST_ERROR())) {

							LOG_ER("DTM: accept() failed");
							end_server = TRUE;
						}
						break;

					}

		

				/*****************************************************/
					/* Node info data back to the accept with node info  */
				/*****************************************************/

					local_rc = dtm_comm_socket_send(new_sd, node_info_hrd, node_info_buffer_len);
					if (local_rc != NCSCC_RC_SUCCESS) {
						dtm_comm_socket_close(&new_sd);
						LOG_ER("DTM: send() failed errno : %d ", GET_LAST_ERROR());
						break;
					}
					
				/*****************************************************/
					/* Add the new incoming connection to the */
					/* pollfd structure */
				/*****************************************************/
					TRACE("DTM :add New incoming connection to fd : %d\n", new_sd);
					fds[nfds].fd = new_sd;
					fds[nfds].events = POLLIN | POLLERR | POLLHUP | POLLNVAL;
					nfds++;

				/*****************************************************/
					/* Loop back up and accept another incoming */
					/* connection */
				/*****************************************************/
					/* } while (new_sd != -1); */	/* accept one at a time */

				} else if (fds[i].fd == dtms_cb->mbx_fd) {
					/* MBX fd messages that need to be sent out from this node */
					/* Process the mailbox events */
					DTM_SND_MSG_ELEM *msg_elem = NULL;

					fd_check++;
					msg_elem =
					    (DTM_SND_MSG_ELEM *) (m_NCS_IPC_NON_BLK_RECEIVE(&dtms_cb->mbx, NULL));

					if (NULL == msg_elem) {
						LOG_ER("DTM: Inter Node Mailbox IPC_NON_BLK_RECEIVE Failed");
						continue;
					} else if (DTM_MBX_ADD_DISTR_TYPE == msg_elem->type) {
						dtm_internode_add_to_svc_dist_list(msg_elem->info.svc_event.server_type,
										   msg_elem->info.svc_event.server_inst,
										   msg_elem->info.svc_event.pid);
						free(msg_elem);
						msg_elem = NULL;
					} else if (DTM_MBX_DEL_DISTR_TYPE == msg_elem->type) {
						dtm_internode_del_from_svc_dist_list(msg_elem->info.
										     svc_event.server_type,
										     msg_elem->info.
										     svc_event.server_inst,
										     msg_elem->info.svc_event.pid);
						free(msg_elem);
						msg_elem = NULL;
					} else if (DTM_MBX_DATA_MSG_TYPE == msg_elem->type) {
						dtm_prepare_data_msg(msg_elem->info.data.buffer,
								     msg_elem->info.data.buff_len);
						dtm_internode_snd_msg_to_node(msg_elem->info.data.buffer,
									      msg_elem->info.data.buff_len,
									      msg_elem->info.data.dst_nodeid);
						free(msg_elem);
						msg_elem = NULL;
					} else {
						LOG_ER("DTM Intranode :Invalid evt type from mbx");
						free(msg_elem);
						msg_elem = NULL;
					}
				} else {

			/*********************************************************/
					/* This is not the listening socket, therefore an */
					/* existing connection must be readable */
			/*********************************************************/
					fd_check++;
					dtm_internode_process_poll_rcv_msg(fds[i].fd, &close_conn, node_info_hrd,
									   node_info_buffer_len);

				}
			} else if (fds[i].revents & POLLOUT) {
				fd_check++;
				dtm_internode_process_pollout(fds[i].fd);
			}

		/*******************************************************/
			/* If the close_conn flag was turned on, we need */
			/* to clean up this active connection. This */
			/* clean up process includes removing the */
			/* descriptor. */
		/*******************************************************/
			if (close_conn) {
				dtm_comm_socket_close(&fds[i].fd);
				close_conn = FALSE;
				compress_array = TRUE;
			}
			/* End of existing connection is readable */
			if (poll_ret == fd_check) {
				break;
			}
		}

		/***********************************************************/
		/* If the compress_array flag was turned on, we need */
		/* to squeeze together the array and decrement the number */
		/* of file descriptors. We do not need to move back the */
		/* events and revents fields because the events will always */
		/* be POLLIN in this case, and revents is output. */
		/***********************************************************/

		if (compress_array) {
			compress_array = FALSE;
			for (i = 0; i < nfds; i++) {
				if (fds[i].fd == -1) {
					for (j = i; j < nfds; j++) {
						fds[j].fd = fds[j + 1].fd;
					}
					nfds--;
				}
			}
		}

	} while (end_server == FALSE);

	/* End of serving running. */
	/*************************************************************/
	/* Clean up all of the sockets that are open */
	/*************************************************************/
 done:
	for (i = 0; i < nfds; i++) {
		if (fds[i].fd >= 0)
			dtm_comm_socket_close(&fds[i].fd);
	}
	TRACE_LEAVE();
	return;
}
Beispiel #20
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_open0() {
  init_sockets();

  SocketOpenParameter *p = (SocketOpenParameter*) SNI_GetReentryData(NULL);
  if (p == NULL) {
    p = (SocketOpenParameter*) SNI_AllocateReentryData(sizeof(*p));
    p->fd = -1;

    struct hostent *phostent;
    KNI_StartHandles(1);
    KNI_DeclareHandle(hostname_object);
    KNI_GetParameterAsObject(1, hostname_object);

    // hostname is always NUL terminated. See socket/Protocol.java for detail.
    char *hostname = (char*) SNI_GetRawArrayPointer(hostname_object);
    phostent = (struct hostent*)jvm_gethostbyname(hostname);
    KNI_EndHandles();

    if (phostent == NULL) {
      KNI_ReturnInt(-1);
    }
    struct sockaddr_in destination_sin;
    destination_sin.sin_family = AF_INET;
    int port = KNI_GetParameterAsInt(2);
    destination_sin.sin_port = jvm_htons(port);
    jvm_memcpy((char *) &destination_sin.sin_addr, phostent->h_addr,
                phostent->h_length);

    p->fd = jvm_socket(AF_INET, SOCK_STREAM, 0);
    if (p->fd < 0) {
       KNI_ReturnInt(-1);
    }
    if (!set_blocking_flags(&p->fd, /*is_blocking*/ KNI_FALSE)) {
      KNI_ReturnInt(-1);
    }

    if (jvm_connect(p->fd, (struct sockaddr *) &destination_sin,
                    sizeof(destination_sin)) < 0) {
      int err_code = GET_LAST_ERROR();
      if (err_code == EINPROGRESS) {
        // When the socket is ready for connect, it becomes *writable*
        // (according to BSD socket spec of select())
        p->check_flags = CHECK_WRITE | CHECK_EXCEPTION;
        SNI_BlockThread();
      } else {
        jvm_shutdown(p->fd, 2);
        closesocket(p->fd);
        p->fd = -1;
      }
    }
    KNI_ReturnInt(p->fd);
  } else {
    // When we come to here, a CheckEvent() call has reported one of the
    // following:
    // [1] connect() has succeeded. In this case we return the socket fd.
    // [2] connect() has failed. In this case CheckEvent has already closed
    //     the socket and set p->fd to -1. So we'd be returning -1.
    KNI_ReturnInt(p->fd);
  }
}
Beispiel #21
0
jboolean followCall(CallTempStruct* call, ValueType returnType, DCValue* result, void* callback, CallFlags flags) 
{
	JNIEnv* env = call->env;
	switch (returnType) {
#define GET_LAST_ERROR() \
		if (flags & SETS_LASTERROR) call->lastError = getLastError();
#define CALL_CASE(valueType, capCase, hiCase, uni) \
		case valueType: \
			result->uni = dcCall ## capCase(call->vm, callback); \
			GET_LAST_ERROR(); \
			break;
		CALL_CASE(eIntValue, Int, INT, i)
		CALL_CASE(eLongValue, LongLong, LONGLONG, l)
		CALL_CASE(eShortValue, Short, SHORT, s)
		CALL_CASE(eFloatValue, Float, FLOAT, f)
		CALL_CASE(eDoubleValue, Double, DOUBLE, d)
		case eBooleanValue:
		CALL_CASE(eByteValue, Char, CHAR, c)
		case eCLongValue:
			result->L = (jlong)dcCallLong(call->vm, callback);
			GET_LAST_ERROR();
			break;
		case eSizeTValue:
			result->L = (size_t)dcCallPointer(call->vm, callback);
			GET_LAST_ERROR();
			break;
		    
		#define CALL_BOXED_INTEGRAL(type, capitalized) \
			if (flags & CALLING_JAVA) { \
				void* pt = dcCallPointer(call->vm, callback); \
				type tt; \
				GET_LAST_ERROR(); \
				tt = (type)Unbox ## capitalized(env, pt); \
				if (sizeof(type) == 4) \
					result->i = (jint)tt; \
				else \
					result->l = (jlong)tt; \
			} else { \
				type tt = (sizeof(type) == 4) ? (type)dcCallInt(call->vm, callback) : (type)dcCallLongLong(call->vm, callback); \
				GET_LAST_ERROR(); \
				result->p = Box ## capitalized(env, tt); \
			}
			
		case eCLongObjectValue:
			CALL_BOXED_INTEGRAL(long, CLong);
			break;
		case eSizeTObjectValue:
			CALL_BOXED_INTEGRAL(size_t, SizeT);
		    break;
		case eTimeTObjectValue: 
			CALL_BOXED_INTEGRAL(time_t, TimeT);
		    break;
		case eVoidValue:
			dcCallVoid(call->vm, callback);
			GET_LAST_ERROR();
			break;
		case eIntFlagSet:
			{
				int flags = dcCallInt(call->vm, callback);
				jobject callIO, obj;
				GET_LAST_ERROR();
				callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL;
				obj = createPointerFromIO(env, JLONG_TO_PTR ((jlong)flags), callIO);
				result->p = obj;
			}
			break;
		case ePointerValue:
			{
				void* ptr = dcCallPointer(call->vm, callback);
				GET_LAST_ERROR();
				if (flags & CALLING_JAVA)
					result->p = ptr ? getPointerPeer(env, ptr) : NULL;
					//result->p = ptr;
				else
				{
					jobject callIO = call && call->pCallIOs ? *(call->pCallIOs++) : NULL;
					result->p = createPointerFromIO(env, ptr, callIO);
				}
			}
			break;
		case eWCharValue:
			switch (sizeof(wchar_t)) {
			case 1:
				result->c = dcCallChar(call->vm, callback);
				break;
			case 2:
				result->s = dcCallShort(call->vm, callback);
				break;
			case 4:
				result->i = dcCallInt(call->vm, callback);
				break;
			default:
				throwException(env, "Invalid wchar_t size !");
				return JNI_FALSE;
			}
			GET_LAST_ERROR();
			break;
		default:
			if (flags & FORCE_VOID_RETURN) 
			{
				dcCallVoid(call->vm, callback);
				GET_LAST_ERROR();
				break;
			}
			throwException(env, "Invalid return value type !");
			return JNI_FALSE;
	}
	HACK_REFETCH_ENV(); 
	if ((flags & CALLING_JAVA) && (*env)->ExceptionCheck(env))
		return JNI_FALSE;
	return JNI_TRUE;
}