protoverse

A metaverse protocol
git clone git://jb55.com/protoverse
Log | Files | Refs | README | LICENSE

client.c (1998B)


      1 
      2 #include <sys/types.h>
      3 #include <sys/socket.h>
      4 #include <netinet/in.h>
      5 #include <arpa/inet.h>
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 #include <string.h>
      9 #include <errno.h>
     10 
     11 #include "client.h"
     12 #include "cursor.h"
     13 #include "describe.h"
     14 #include "net.h"
     15 
     16 int inet_aton(const char *cp, struct in_addr *inp);
     17 
     18 static int handle_data_response(struct parser *parser, const char *expected_path,
     19 				struct packet *packet)
     20 {
     21 	struct fetch_response_packet *resp = &packet->data.fetch_response;
     22 	int root;
     23 	int ok;
     24 
     25 	if (packet->type == PKT_FETCH_DATA_RESPONSE &&
     26 	    !strcmp(expected_path, resp->path))
     27 	{
     28 		ok = parse_buffer(parser, resp->data, resp->data_len, &root);
     29 		if (!ok) {
     30 			printf("could not parse space\n");
     31 			return 0;
     32 		}
     33 		describe(parser, root);
     34 	}
     35 
     36 	return 1;
     37 }
     38 
     39 int protoverse_connect(const char *server_ip_str, int port)
     40 {
     41 	static unsigned char buf[0xFFFF];
     42 
     43 	int sockfd;
     44 	struct in_addr server_in_addr;
     45 	struct sockaddr_in server_addr;
     46 	struct cursor cursor;
     47 	struct packet packet;
     48 	const char *expected_path;
     49 	struct parser parser;
     50 
     51 	init_parser(&parser);
     52 	make_cursor(buf, buf + sizeof(buf), &cursor);
     53 
     54 	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
     55 		printf("socket creation failed: %s\n", strerror(errno));
     56 		return 0;
     57 	}
     58 
     59 	if (inet_aton(server_ip_str, &server_in_addr) == 0) {
     60 		printf("could not parse server ip: %s\n", strerror(errno));
     61 		return 0;
     62 	}
     63 
     64 	server_addr.sin_family = AF_INET;
     65 	server_addr.sin_port = port == 0 || port == -1 ? 1988 : port;
     66 	server_addr.sin_addr = server_in_addr;
     67 
     68 	packet.type = PKT_MESSAGE;
     69 	packet.data.message.message = "hello, world";
     70 
     71 	send_packet(sockfd, &server_addr, &packet);
     72 	recv_packet(sockfd, &cursor, &server_addr, &packet);
     73 
     74 	expected_path = "index.space";
     75 	packet.type = PKT_FETCH_DATA;
     76 	packet.data.fetch.path = expected_path;
     77 
     78 	send_packet(sockfd, &server_addr, &packet);
     79 	recv_packet(sockfd, &cursor, &server_addr, &packet);
     80 
     81 	handle_data_response(&parser, expected_path, &packet);
     82 
     83 	free_parser(&parser);
     84 
     85 	return 1;
     86 }