ninenano

Client implementation of the 9P protocol for constrained devices

git clone https://git.8pit.net/ninenano.git

  1#include <stdio.h>
  2#include <string.h>
  3#include <stdlib.h>
  4#include <netdb.h>
  5#include <unistd.h>
  6#include <errno.h>
  7
  8#include <sys/types.h>
  9#include <sys/socket.h>
 10
 11#include "9p.h"
 12
 13static int sockfd;
 14static _9pctx ctx;
 15
 16#define NINEPFS_FN  "hello"
 17#define NINEPFS_STR "Hello World!\n"
 18
 19static ssize_t
 20recvfn(void *buf, size_t count)
 21{
 22	return read(sockfd, buf, count);
 23}
 24
 25static ssize_t
 26sendfn(void *buf, size_t count)
 27{
 28	return write(sockfd, buf, count);
 29}
 30
 31int
 32writestr(void)
 33{
 34	int r;
 35	_9pfid *fid, *rfid;
 36
 37	if ((r = _9pversion(&ctx)))
 38		return r;
 39	if ((r = _9pattach(&ctx, &rfid, "glenda", NULL)))
 40		return r;
 41
 42	if ((r = _9pwalk(&ctx, &fid, "/")))
 43		return r;
 44	if ((r = _9pcreate(&ctx, fid, NINEPFS_FN,
 45			S_IRUSR|S_IWUSR, OWRITE|OTRUNC)))
 46		return r;
 47
 48	if ((r = _9pwrite(&ctx, fid, NINEPFS_STR,
 49			strlen(NINEPFS_STR))) < 0)
 50		return r;
 51
 52	_9pclunk(&ctx, fid);
 53	_9pclunk(&ctx, rfid);
 54
 55	return 0;
 56}
 57
 58int
 59main(int argc, char **argv)
 60{
 61	int r;
 62	struct addrinfo *addr, *a;
 63	struct addrinfo hints;
 64
 65	if (argc < 3) {
 66		fprintf(stderr, "Usage: %s HOST PORT\n", argv[0]);
 67		return EXIT_FAILURE;
 68	}
 69
 70	memset(&hints, 0, sizeof(struct addrinfo));
 71	hints.ai_family = AF_INET;
 72	hints.ai_socktype = SOCK_STREAM;
 73
 74	if ((r = getaddrinfo(argv[1], argv[2], &hints, &addr))) {
 75		fprintf(stderr, "getaddrinfo failed: %d\n", r);
 76		return EXIT_FAILURE;
 77	}
 78
 79	for (sockfd = -1, a = addr; a; sockfd = -1, a = a->ai_next) {
 80		if ((sockfd = socket(a->ai_family, a->ai_socktype,
 81				a->ai_protocol)) == -1)
 82			continue;
 83
 84		if (!connect(sockfd, a->ai_addr, a->ai_addrlen))
 85			break;
 86		close(sockfd);
 87	}
 88
 89        freeaddrinfo(addr);
 90	if (sockfd == -1) {
 91		perror("couldn't connect to server");
 92		return EXIT_FAILURE;
 93	}
 94
 95	_9pinit(&ctx, recvfn, sendfn);
 96	if ((r = writestr())) {
 97		errno = r * -1;
 98		perror("writestr failed");
 99		return EXIT_FAILURE;
100	}
101
102	return EXIT_SUCCESS;
103}