Exemplo n.º 1
0
int main(int argc, char *argv[])
{
  socket_t sock;
  struct sockaddr_in servaddr;
  char *server;
  int rc;
  char bye[3];
  int len;
  struct spindly_phys *phys_client;
  struct spindly_stream *stream_client;
  spindly_error_t spint;
  unsigned char *data;
  size_t datalen;

  server = "127.0.0.1";

  sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sock == SOCKET_BAD)
    errorout("socket() failed");

  /* create a spindly handle for the physical connection */
  phys_client = spindly_phys_init(SPINDLY_SIDE_CLIENT, SPINDLY_DEFAULT, NULL);

  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = inet_addr(server);
  servaddr.sin_port = htons(SERVER_PORT);

  /* Establish the connection to the echo server */
  rc = connect(sock, (struct sockaddr *) &servaddr, sizeof(servaddr));
  if (rc < 0)
    errorout("connect() failed");

  printf("Connected! Pretend TLS-NPN succeeded.\n");

  /* create a new stream on the physical connection */
  spint = spindly_stream_new(phys_client, 0, &stream_client, NULL, NULL);

  /* get data to send over the socket */
  spint = spindly_phys_outgoing(phys_client, &data, &datalen);

  printf("Ask for a new stream\n");

  /* send away the SPDY packet */
  rc = send(sock, data, datalen, 0);

  if(rc > 0) {
    /* tell spindly how much of that data that was actually sent */
    spindly_phys_sent(phys_client, rc);
    printf("Send %d bytes\n", rc);
  }

  /* now wait for data to arrive on the socket and demux it to figure out
     what the peer says to us */
  sleep(5);

  sclose(sock);

  return 0;
}
Exemplo n.º 2
0
void getDimension(Puzzle* puzzle, FILE* fp, int coord) {
	char buffer[BUFFERSIZE];
	if (fgets(buffer, sizeof(buffer), fp) == NULL)
		errorout(ERROR_BADFORMAT, "File ended unexpectedly (row num).");
	if (sscanf(buffer, "%d", &(puzzle->length[coord])) <= 0)
		errorout(ERROR_BADFORMAT, "Row number not an integer.");
}
Exemplo n.º 3
0
static int createserver(unsigned short port)
{
  socket_t sock;
  struct sockaddr_in servaddr;

  /* Create socket for incoming connections */
  if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    errorout("socket() failed");

  /* Construct local address structure */
  memset(&servaddr, 0, sizeof(servaddr));   /* Zero out structure */
  servaddr.sin_family = AF_INET;                /* Internet address family */
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
  servaddr.sin_port = htons(port);              /* Local port */

  /* Bind to the local address */
  if (bind(sock, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
    errorout("bind() failed");

  /* Mark the socket so it will listen for incoming connections */
  if (listen(sock, MAXPENDING) < 0)
    errorout("listen() failed");

  return sock;
}
Exemplo n.º 4
0
void checkblankln(FILE* fp) {
	char buffer[BUFFERSIZE];
	if (fgets(buffer, sizeof(buffer), fp) == NULL)	//do we even have a line to read?
		errorout(ERROR_BADFORMAT, "File ended unexpectedly (was expecting a blank line).");
	if (strcmp(buffer, "\n") != 0)	//line is there but not blank!
		errorout(ERROR_BADFORMAT, "Blank line was not blank.");
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
  socket_t sock;
  struct sockaddr_in servaddr;
  char *server;
  int rc;
  char bye[3];
  int len;

  server = "127.0.0.1";

  sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sock == SOCKET_BAD)
    errorout("socket() failed");

  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = inet_addr(server);
  servaddr.sin_port = htons(SERVER_PORT);

  /* Establish the connection to the echo server */
  rc = connect(sock, (struct sockaddr *) &servaddr, sizeof(servaddr));
  if (rc < 0)
    errorout("connect() failed");

  printf("Connected!\n");
  write(sock, "not spdy", strlen("not spdy"));
  len = read(sock, bye, sizeof(bye));
  printf("Recv: %.*s\n", 3, bye); 

  sclose(sock);

  return 0;
}
Exemplo n.º 6
0
Puzzle* getPuzzle(char* name) {
	FILE* fp = fopen(name, "r");
	if (fp == NULL)	errorout(ERROR_404, "Wrong directory or name for puzzle config.");
	Puzzle* puzzle = (Puzzle*) malloc(sizeof(Puzzle));
	if (puzzle == NULL) errorout(ERROR_MEM, "Could not create Puzzle.");
	
	if ((puzzle->length = (int*) malloc(AXES*sizeof(int))) == NULL)	errorout(ERROR_MEM, "Could not create lengths.");
	
	getDimension(puzzle, fp, ROW);	//get 1st line - L = number of rows
	getDimension(puzzle, fp, COL);	//get 2nd line - C = number of columns
	checkblankln(fp);				//3rd line - must be blank

	if ((puzzle->line = (Line**) malloc(AXES*sizeof(Line*))) == NULL)	errorout(ERROR_MEM, "Could not create lines.");	
	if ((puzzle->line[ROW] = (Line*) malloc(puzzle->length[COL]*sizeof(Line))) == NULL)	errorout(ERROR_MEM, "Could not create rows.");
	if ((puzzle->line[COL] = (Line*) malloc(puzzle->length[ROW]*sizeof(Line))) == NULL)	errorout(ERROR_MEM, "Could not create cols.");

	readBlockLenghtsRow(puzzle, fp);	//next L lines have row block lengths
	checkblankln(fp);				//get (3+L+1)th line - must be blank
	readBlockLenghtsCol(puzzle, fp);	//next C lines have col block lengths
	checkblankln(fp);				//get (3+L+1+C+1)th line - must be blank

	char buffer[BUFFERSIZE];
	if (fgets(buffer, sizeof(buffer), fp) != NULL) {	//file must end after previous blank line
		errorout(ERROR_BADFORMAT, "File did not end when expected.");
	}

	return puzzle;
}
Exemplo n.º 7
0
	void tsuite::test(std::string name, std::function<void()> testfunc)
	{
		try
		{
			testfunc();
			m_passed++;
			successout() << name;
		}
		catch (std::exception e)
		{
			m_failed++;
			errorout() << name << " -> failed because of " << e;
			breakdebugger();
		}
		catch (...)
		{
			errorout() << name << " -> failed because of uncatched (and non-std::exception based) exception";
			throw;
		}
	}
Exemplo n.º 8
0
void readBlockLenghtsRow(Puzzle* puzzle, FILE* fp) {
	int i, j, n;
	char buffer[BUFFERSIZE];
	for (i = 0; i < puzzle->length[ROW]; i++) {
		if (fgets(buffer, sizeof(buffer), fp) == NULL)	errorout(ERROR_BADFORMAT, "File ended unexpectedly (block lengths).");

		sscanf(buffer, " %d", &puzzle->line[ROW][i].blockNum);
		if (puzzle->line[ROW][i].blockNum > 0) {
			if ((puzzle->line[ROW][i].block = (Block*) malloc(puzzle->line[ROW][i].blockNum*sizeof(Block))) == NULL)	errorout(ERROR_MEM, "Could not create *block[ROW].");
		} else 
		if (puzzle->line[ROW][i].blockNum == 0) {	//special case: 0 means 1 block of 0 length (ie no blocks)
			if ((puzzle->line[ROW][i].block = (Block*) malloc(sizeof(Block))) == NULL)	errorout(ERROR_MEM, "Could not create *block[ROW].");
			puzzle->line[ROW][i].block[0].length = 0;
		} else {
			errorout(ERROR_BADFORMAT, "Found a negative number.");
		}
		
		if ((puzzle->line[ROW][i].cells = (Cell**) malloc(puzzle->length[COL]*sizeof(Cell*))) == NULL)	errorout(ERROR_MEM,"Could not create rows[i].cells.");
		for (j = 0; j < puzzle->length[COL]; j++) {
			puzzle->line[ROW][i].cells[j] = (Cell*) malloc(sizeof(Cell));
			puzzle->line[ROW][i].cells[j]->state = STATE_UNKN;
		}

		//note: if there are spaces before the first integer, the first number won't be 'deleted' - write function that is also mentioned a few lines of comment down
		for (n = 0; !isspace(buffer[n]); n++) {	//"delete" first number, which determined array size
			buffer[n] = ' ';
		}

		for (j = 0; j < puzzle->line[ROW][i].blockNum; j++) {	//read arraySize blocks
				//get first integer
			for (; !isspace(buffer[n]); n++) {	//replace all characters of the current word (ie the fetched integer) with whitespace
				buffer[n] = ' ';						//the goal of this is to have the "first" integer be the next one, so that with a single 
			}											//sscanf attribution we can read everything
			n++;	//+1 to get starting position of next word (ie next integer) to start on next whitespace-filling loop	- this doesnt currently account for multiple spaces! need a function with a loop to skip all the spaces (or error out if more than a space is found)
			sscanf(buffer, " %d ", &(puzzle->line[ROW][i].block[j].length));
		}
	}
}
Exemplo n.º 9
0
int main(int argc, CARGV argv)
{
	multi_argv = argv;
	multi_argc = argc;

	if (!compare(basename((char*)*argv), "vlmcsd"))
		return server_main(argc, argv);

	if (!compare(basename((char*)*argv), "vlmcs"))
		return client_main(argc, argv);

	#ifdef _WIN32
	if (!compare(basename((char*)*argv), "vlmcsd.exe"))
		return server_main(argc, argv);

	if (!compare(basename((char*)*argv), "vlmcs.exe"))
		return client_main(argc, argv);
	#endif // _WIN32

	if (argc > 1)
	{
		if (!strcmp((char*)argv[1],"vlmcsd"))
			return server_main(argc - 1, argv + 1);

		if (!strcmp((char*)argv[1],"vlmcs"))
			return client_main(argc - 1, argv + 1);
	}

	errorout(
			"vlmcsdmulti %s\n\n"
			"Usage:\n"
			"\t%s vlmcsd [<vlmcsd command line>]\n"
			"\t%s vlmcs [<vlmcs command line>]\n\n",
			Version, *argv, *argv
	);

	return !0;
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
  socket_t servsock;
  int maxfd;
  fd_set readfds;
  fd_set writefds;
  struct timeval seltimeout;
  int running = 1;

  /* initially we support only one client */
  socket_t clientsock = SOCKET_BAD;

  (void)argc;
  (void)argv;

  /* Create port socket */
  servsock = createserver(SERVER_PORT);

  /* Initialize maxfd for use by select() */
  maxfd = servsock;

  while (running) {
    int rc;
    FD_ZERO(&readfds);
    FD_ZERO(&writefds);
    FD_SET(STDIN_FILENO, &readfds);

    /* right now we only allow one client to connect, so when there's a client
       we don't listen for new connects */
    if (SOCKET_BAD != clientsock) {
      FD_SET(clientsock, &readfds);

      /* if there is anything to write, wait to send */
      FD_SET(clientsock, &writefds);
    }
    else
      FD_SET(servsock, &readfds);

    seltimeout.tv_sec =  TIMEOUT_SECS;
    seltimeout.tv_usec = 0;

    rc = select(maxfd + 1, &readfds, &writefds, NULL, &seltimeout);
    if (!rc)
      errorout("timeout expired!\n");
    else {
      if (FD_ISSET(STDIN_FILENO, &readfds)) {
        /* read stdin and pass as data to clients */
      }

      if (clientsock > 0) {
        if (FD_ISSET(clientsock, &readfds)) {
          /* client is readable */
          if (handleclient(&cl) < 0) {
            sclose(clientsock);
            clientsock = SOCKET_BAD;
          }
        }
        if (FD_ISSET(clientsock, &writefds)) {
          /* client is writeable */
        }
      }

      if (FD_ISSET(servsock, &readfds)) {
        printf("New client connects on port %d - assume fine TLS-NPN",
               SERVER_PORT);
        clientsock = acceptclient(servsock);

        /* create a spindly handle for the physical connection */
        cl.phys_server = spindly_phys_init(SPINDLY_SIDE_SERVER,
                                           SPINDLY_DEFAULT, NULL);
        cl.sock = clientsock; /* store the socket */
        maxfd = clientsock;
      }
    }
  }

  /* Close server socket */
  sclose(servsock);

  exit(0);
}
Exemplo n.º 11
0
int RpcBindClient(const SOCKET sock)
{
	RPC_HEADER *RequestHeader, ResponseHeader;
	RPC_BIND_REQUEST *bindRequest;
	RPC_BIND_RESPONSE *bindResponse;
	int status;
	#define NUM_CTX_ITEMS 1
	#define SIZE (sizeof(RPC_HEADER) + sizeof(RPC_BIND_REQUEST) + (NUM_CTX_ITEMS - 1) * sizeof(bindRequest->CtxItems[0]))

	BYTE _Request[SIZE];
	RequestHeader = (RPC_HEADER*)_Request;
	bindRequest = (RPC_BIND_REQUEST* )(_Request + sizeof(RPC_HEADER));

	CreateRpcRequestHeader(RequestHeader, RPC_PT_BIND_REQ, SIZE);
	RequestHeader->PacketFlags |=  UseMultiplexedRpc ? RPC_PF_MULTIPLEX : 0;

	bindRequest->AssocGroup		= 0;
	bindRequest->MaxRecvFrag	= bindRequest->MaxXmitFrag = LE16(5840);
	bindRequest->NumCtxItems	= LE32(NUM_CTX_ITEMS);

	bindRequest->CtxItems[0].ContextId			= 0;
	bindRequest->CtxItems[0].InterfaceVerMajor	= LE16(1);
	bindRequest->CtxItems[0].InterfaceVerMinor	= 0;
	bindRequest->CtxItems[0].NumTransItems		= LE16(1);
	bindRequest->CtxItems[0].SyntaxVersion		= LE32(2);

	memcpy(&bindRequest->CtxItems[0].TransferSyntax, TransferSyntaxNDR32, sizeof(GUID));
	memcpy(&bindRequest->CtxItems[0].InterfaceUUID, InterfaceUuid, sizeof(GUID));

	if (!_send(sock, _Request, SIZE))
	{
		errorout("\nFatal: Sending RPC bind request failed\n");
		return !0;
	}

	if (!_recv(sock, &ResponseHeader, sizeof(RPC_HEADER)))
	{
		errorout("\nFatal: Did not receive a response from server\n");
		return !0;
	}

	if ((status = CheckRpcHeaders(&ResponseHeader, RequestHeader, RPC_PT_BIND_ACK, &errorout))) return status;

	if (!(bindResponse = (RPC_BIND_RESPONSE*)malloc(LE16(ResponseHeader.FragLength) - sizeof(RPC_HEADER))))
	{
		errorout("\nFatal: Could not allocate memory for RPC bind response\n");
		return !0;
	}

	if (!_recv(sock, bindResponse, LE16(ResponseHeader.FragLength) - sizeof(RPC_HEADER)))
	{
		errorout("\nFatal: Incomplete RPC bind acknowledgement received\n");
		status = !0;
	}
	else
	{
		for (status = 0;;)
		{
			if (bindResponse->NumResults != bindRequest->NumCtxItems)
			{
				errorout("\nFatal: Expected %u CTX items but got %u\n",
						(uint32_t)LE32(bindRequest->NumCtxItems),
						(uint32_t)LE32(bindResponse->NumResults)
				);

				status = !0;
			}

			if (bindResponse->Results[0].AckResult != 0)
			{
				status = (int)(uint16_t)LE16(bindResponse->Results[0].AckResult);
				errorout("\nFatal: Server declined RPC bind request. AckResult is %i\n", status);
				break;
			}

			if (bindResponse->Results[0].SyntaxVersion != bindRequest->CtxItems[0].SyntaxVersion)
			{
				errorout("\nFatal: Expected syntax version %u but got %u\n",
						(uint32_t)LE32(bindRequest->CtxItems[0].SyntaxVersion),
						(uint32_t)LE32(bindResponse->Results[0].SyntaxVersion)
				);

				status = !0;
			}

			if (!IsEqualGUID(&bindResponse->Results[0].TransferSyntax, &bindRequest->CtxItems[0].TransferSyntax))
			{
				errorout("\nFatal: Transfer syntax of RPC bind request and response does not match\n");
				status = !0;
			}

			break;
		}
	}

	free(bindResponse);
	return status;
	#undef SIZE
}
Exemplo n.º 12
0
int RpcSendRequest(const SOCKET sock, const BYTE *const KmsRequest, const size_t requestSize, BYTE **KmsResponse, size_t *const responseSize)
{
	#define MAX_EXCESS_BYTES 16
	RPC_HEADER *RequestHeader, ResponseHeader;
	RPC_REQUEST *RpcRequest;
	RPC_RESPONSE _Response;
	int status = 0;
	size_t size = sizeof(RPC_HEADER) + sizeof(RPC_REQUEST) + requestSize;

	*KmsResponse = NULL;

	BYTE *_Request = (BYTE*)malloc(size);
	if (!_Request) return !0;

	RequestHeader = (RPC_HEADER*)_Request;
	RpcRequest = (RPC_REQUEST*)(_Request + sizeof(RPC_HEADER));

	CreateRpcRequestHeader(RequestHeader, RPC_PT_REQUEST, size);

	// Increment CallId for next Request
	CallId++;

	RpcRequest->ContextId = 0;
	RpcRequest->Opnum = 0;
	RpcRequest->AllocHint = requestSize + sizeof(RpcRequest->Ndr);
	RpcRequest->Ndr.DataLength = LE32(requestSize);
	RpcRequest->Ndr.DataSizeIs = LE32(requestSize);

	memcpy(RpcRequest->Data, KmsRequest, requestSize);

	for(;;)
	{
		int bytesread;

		if (!_send(sock, _Request, size))
		{
			errorout("\nFatal: Could not send RPC request\n");
			status = !0;
			break;
		}

		if (!_recv(sock, &ResponseHeader, sizeof(RPC_HEADER)))
		{
			errorout("\nFatal: No RPC response received from server\n");
			status = !0;
			break;
		}

		if ((status = CheckRpcHeaders(&ResponseHeader, RequestHeader, RPC_PT_RESPONSE, &errorout))) break;

		if (!_recv(sock, &_Response, sizeof(_Response)))
		{
			errorout("\nFatal: RPC response is incomplete\n");
			status = !0;
			break;
		}

		if (_Response.CancelCount != 0)
		{
			errorout("\nFatal: RPC response cancel count is not 0\n");
			status = !0;
		}

		if (_Response.ContextId != 0)
		{
			errorout("\nFatal: RPC response context id is not 0\n");
			status = !0;
		}

		*responseSize = LE32(_Response.Ndr.DataLength);

		if (!*responseSize || !_Response.Ndr.DataSizeIs1)
		{
			status = LE32(_Response.Ndr.DataSizeIs2);
			break;
		}

		if (_Response.Ndr.DataLength != _Response.Ndr.DataSizeIs2)
		{
			errorout("\nFatal: NDR data length (%u) does not match NDR data size (%u)\n",
					(uint32_t)*responseSize,
					(uint32_t)LE32(_Response.Ndr.DataSizeIs2)
			);

			status = !0;
		}

		*KmsResponse = (BYTE*)malloc(*responseSize + MAX_EXCESS_BYTES);

		if (!*KmsResponse)
		{
			errorout("\nFatal: Could not allocate memory for KMS response\n");
			status = !0;
			break;
		}

		// If RPC stub is too short, assume missing bytes are zero (same ill behavior as MS RPC)
		memset(*KmsResponse, 0, *responseSize + MAX_EXCESS_BYTES);

		// Read up to 16 bytes more than bytes expected to detect faulty KMS emulators
		if ((bytesread = recv(sock, (char*)*KmsResponse, *responseSize + MAX_EXCESS_BYTES, 0)) < (int)*responseSize)
		{
			errorout("\nFatal: No or incomplete KMS response received. Required %u bytes but only got %i\n",
					(uint32_t)*responseSize,
					(int32_t)(bytesread < 0 ? 0 : bytesread)
			);

			status = !0;
			break;
		}

		DWORD *pReturnCode;

		size_t len = *responseSize + sizeof(_Response.Ndr) + sizeof(*pReturnCode);
		size_t pad = ((~len & 3) + 1) & 3;

		if (len + pad != LE32(_Response.AllocHint))
		{
			errorout("\nWarning: RPC stub size is %u, should be %u (probably incorrect padding)\n", (uint32_t)LE32(_Response.AllocHint), (uint32_t)(len + pad));
		}
		else
		{
			size_t i;
			for (i = 0; i < pad; i++)
			{
				if (*(*KmsResponse + *responseSize + sizeof(*pReturnCode) + i))
				{
					errorout("\nWarning: RPC stub data not padded to zeros according to Microsoft standard\n");
					break;
				}
			}
		}

		pReturnCode = (DWORD*)(*KmsResponse + *responseSize);
		status = LE32(UA32(pReturnCode));

		if (status) errorout("\nWarning: RPC stub data reported Error %u\n", (uint32_t)status);

		break;
	}

	free(_Request);
	return status;
	#undef MAX_EXCESS_BYTES
}