summaryrefslogtreecommitdiff
path: root/sites/pmikkelsen.com/plan9/basic_9p_server.md
blob: 7c1c514d391f449d30469a4aadf55695a28584f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
## Writing a basic 9P server

On plan 9 the entire system is build around the idea of namespaces
and that _"everything is a file"_. For this reason it is very easy to write
a new 9P fileserver in C since all the boring tasks are implemented in
libraries. This note describes a minimal program which serves a folder to
`/mnt/hello9p` containing a single synthetic file with the contents "Hello from 9P!".

## The code

	#include <u.h>
	#include <libc.h>
	#include <fcall.h>
	#include <thread.h>
	#include <9p.h>
	
	void
	fsread(Req *r)
	{
		readstr(r, "Hello from 9P!\n");
		respond(r, nil);
	}
	
	Srv fs = {
		.read = fsread,
	};
	
	void
	main(void)
	{
		Tree *tree;
	
		tree = alloctree(nil, nil, DMDIR|0555, nil);
		fs.tree = tree;
		createfile(tree->root, "hello", nil, 0555, nil);
	
		postmountsrv(&fs, nil, "/mnt/hello9p", MREPL | MCREATE);
	}

## Explanation

The global variable `fs` is a structure which contains function pointers
to all the 9P handlers, but since I only plan on reading from the file,
only the `read` field is set. The fsread function calls two helper functions
from the 9p(2) library which will create a response with the given string as
the file contents.

In `main` I start by allocating a new file tree, since this 9P server deals with
a fileserver that has a tree structure, and therefore I don't have to worry
about how directories are handled for example. A file is added with `createfile`
to the root of the tree.

The call to `postmountsrv` will mount the 9P server under `/mnt/hello9p`.

## Thats it

This is not very complicated, but see the manpages at 9p(2) and 9pfile(2)
and intro(5) for more information about the libraries and 9P itself.