Add UDP transport support to the NFS server.
[bluesky.git] / nfs3 / rpc.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2009  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 /* RPC handling: registration, marshalling and unmarshalling of messages.  For
10  * now this uses the standard Sun RPC mechanisms in the standard C library.
11  * Later, it might be changed to use something better.  Much of this code was
12  * generated with rpcgen from the XDR specifications, but has been hand-edited
13  * slightly. */
14
15 #include "mount_prot.h"
16 #include "nfs3_prot.h"
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <rpc/pmap_clnt.h>
20 #include <string.h>
21 #include <signal.h>
22 #include <memory.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <netinet/ip.h>
26
27 #include "bluesky.h"
28 extern BlueSkyFS *fs;
29
30 /* TCP port number to use for NFS protocol.  (Should be 2049.) */
31 #define NFS_SERVICE_PORT 2051
32
33 /* Maximum size of a single RPC message that we will accept (8 MB). */
34 #define MAX_RPC_MSGSIZE (8 << 20)
35
36 static void
37 mount_program_3(struct svc_req *rqstp, register SVCXPRT *transp)
38 {
39     union {
40         dirpath mountproc3_mnt_3_arg;
41         dirpath mountproc3_umnt_3_arg;
42     } argument;
43     char *result;
44     xdrproc_t _xdr_argument, _xdr_result;
45     char *(*local)(char *, struct svc_req *);
46
47     switch (rqstp->rq_proc) {
48     case MOUNTPROC3_NULL:
49         _xdr_argument = (xdrproc_t) xdr_void;
50         _xdr_result = (xdrproc_t) xdr_void;
51         local = (char *(*)(char *, struct svc_req *)) mountproc3_null_3_svc;
52         break;
53
54     case MOUNTPROC3_MNT:
55         _xdr_argument = (xdrproc_t) xdr_dirpath;
56         _xdr_result = (xdrproc_t) xdr_mountres3;
57         local = (char *(*)(char *, struct svc_req *)) mountproc3_mnt_3_svc;
58         break;
59
60     case MOUNTPROC3_DUMP:
61         _xdr_argument = (xdrproc_t) xdr_void;
62         _xdr_result = (xdrproc_t) xdr_mountlist;
63         local = (char *(*)(char *, struct svc_req *)) mountproc3_dump_3_svc;
64         break;
65
66     case MOUNTPROC3_UMNT:
67         _xdr_argument = (xdrproc_t) xdr_dirpath;
68         _xdr_result = (xdrproc_t) xdr_void;
69         local = (char *(*)(char *, struct svc_req *)) mountproc3_umnt_3_svc;
70         break;
71
72     case MOUNTPROC3_UMNTALL:
73         _xdr_argument = (xdrproc_t) xdr_void;
74         _xdr_result = (xdrproc_t) xdr_void;
75         local = (char *(*)(char *, struct svc_req *)) mountproc3_umntall_3_svc;
76         break;
77
78     case MOUNTPROC3_EXPORT:
79         _xdr_argument = (xdrproc_t) xdr_void;
80         _xdr_result = (xdrproc_t) xdr_exports;
81         local = (char *(*)(char *, struct svc_req *)) mountproc3_export_3_svc;
82         break;
83
84     default:
85         svcerr_noproc (transp);
86         return;
87     }
88     memset ((char *)&argument, 0, sizeof (argument));
89     if (!svc_getargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) {
90         svcerr_decode (transp);
91         return;
92     }
93     result = (*local)((char *)&argument, rqstp);
94     if (result != NULL && !svc_sendreply(transp, (xdrproc_t) _xdr_result, result)) {
95         svcerr_systemerr (transp);
96     }
97     if (!svc_freeargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) {
98         fprintf (stderr, "%s", "unable to free arguments");
99         exit (1);
100     }
101     return;
102 }
103
104 struct rpc_reply {
105     uint32_t xid;
106     uint32_t type;
107     uint32_t stat;
108     uint32_t verf_flavor;
109     uint32_t verf_len;
110     uint32_t accept_stat;
111 };
112
113 static void async_rpc_write(RPCConnection *rpc,
114                             const char *buf, gsize len);
115 static void async_rpc_flush(RPCConnection *rpc);
116
117 struct rpc_fail_reply {
118     uint32_t xid;
119     uint32_t type;
120     uint32_t stat;
121     uint32_t verf_flavor;
122     uint32_t verf_len;
123     uint32_t accept_stat;
124 };
125
126 static void
127 async_rpc_send_failure(RPCRequest *req, enum accept_stat stat)
128 {
129     struct rpc_fail_reply header;
130
131     header.xid = htonl(req->xid);
132     header.type = htonl(1);     /* REPLY */
133     header.stat = htonl(MSG_ACCEPTED);
134     header.verf_flavor = 0;
135     header.verf_len = 0;
136     header.accept_stat = htonl(stat);
137
138     g_mutex_lock(req->connection->send_lock);
139     uint32_t fragment = htonl(sizeof(header) | 0x80000000);
140     if (!req->connection->udp_transport)
141         async_rpc_write(req->connection, (const char *)&fragment,
142                         sizeof(fragment));
143     async_rpc_write(req->connection, (const char *)&header, sizeof(header));
144     async_rpc_flush(req->connection);
145     g_mutex_unlock(req->connection->send_lock);
146
147     if (req->args != NULL) {
148         char buf[4];
149         XDR xdr;
150         xdrmem_create(&xdr, buf, sizeof(buf), XDR_FREE);
151         if (!req->xdr_args_free(&xdr, req->args)) {
152             fprintf(stderr, "unable to free arguments");
153         }
154         g_free(req->args);
155     }
156
157     if (req->raw_args != NULL)
158         g_string_free(req->raw_args, TRUE);
159
160     while (req->cleanup != NULL) {
161         struct cleanup_list *c = req->cleanup;
162         req->cleanup = c->next;
163         c->func(c->arg);
164         g_free(c);
165     }
166
167     if (req->connection->udp_transport) {
168         /* For UDP, a connection only exists for the duration of a single
169          * message. */
170         g_mutex_free(req->connection->send_lock);
171         g_string_free(req->connection->sendbuf, TRUE);
172         g_free(req->connection);
173     }
174
175     g_free(req);
176 }
177
178 void
179 async_rpc_send_reply(RPCRequest *req, void *result)
180 {
181     bluesky_time_hires time_end;
182
183     GString *str = g_string_new("");
184     XDR xdr_out;
185     xdr_string_create(&xdr_out, str, XDR_ENCODE);
186     if (!req->xdr_result(&xdr_out, result)) {
187         async_rpc_send_failure(req, SYSTEM_ERR);
188         g_string_free(str, TRUE);
189         return;
190     }
191
192     struct rpc_reply header;
193     header.xid = htonl(req->xid);
194     header.type = htonl(1);     /* REPLY */
195     header.stat = htonl(MSG_ACCEPTED);
196     header.verf_flavor = 0;
197     header.verf_len = 0;
198     header.accept_stat = 0;
199
200     g_mutex_lock(req->connection->send_lock);
201     gsize msg_size = str->len;
202     uint32_t fragment = htonl((msg_size + sizeof(header)) | 0x80000000);
203     if (!req->connection->udp_transport)
204         async_rpc_write(req->connection, (const char *)&fragment,
205                         sizeof(fragment));
206     async_rpc_write(req->connection, (const char *)&header, sizeof(header));
207     async_rpc_write(req->connection, str->str, str->len);
208     async_rpc_flush(req->connection);
209     g_mutex_unlock(req->connection->send_lock);
210
211     time_end = bluesky_now_hires();
212
213     printf("RPC[%"PRIx32"]: time = %"PRId64" ns\n",
214            req->xid, time_end - req->time_start);
215
216     /* Clean up. */
217     g_string_free(str, TRUE);
218
219     if (req->args != NULL) {
220         char buf[4];
221         XDR xdr;
222         xdrmem_create(&xdr, buf, sizeof(buf), XDR_FREE);
223         if (!req->xdr_args_free(&xdr, req->args)) {
224             fprintf(stderr, "unable to free arguments");
225         }
226         g_free(req->args);
227     }
228
229     if (req->raw_args != NULL)
230         g_string_free(req->raw_args, TRUE);
231
232     while (req->cleanup != NULL) {
233         struct cleanup_list *c = req->cleanup;
234         req->cleanup = c->next;
235         c->func(c->arg);
236         g_free(c);
237     }
238
239     if (req->connection->udp_transport) {
240         /* For UDP, a connection only exists for the duration of a single
241          * message. */
242         g_mutex_free(req->connection->send_lock);
243         g_string_free(req->connection->sendbuf, TRUE);
244         g_free(req->connection);
245     }
246
247     g_free(req);
248 }
249
250 static const char *nfs_proc_names[] = {
251     [NFSPROC3_NULL] = "NULL",
252     [NFSPROC3_GETATTR] = "GETATTR",
253     [NFSPROC3_SETATTR] = "SETATTR",
254     [NFSPROC3_LOOKUP] = "LOOKUP",
255     [NFSPROC3_ACCESS] = "ACCESS",
256     [NFSPROC3_READLINK] = "READLINK",
257     [NFSPROC3_READ] = "READ",
258     [NFSPROC3_WRITE] = "WRITE",
259     [NFSPROC3_CREATE] = "CREATE",
260     [NFSPROC3_MKDIR] = "MKDIR",
261     [NFSPROC3_SYMLINK] = "SYMLINK",
262     [NFSPROC3_MKNOD] = "MKNOD",
263     [NFSPROC3_REMOVE] = "REMOVE",
264     [NFSPROC3_RMDIR] = "RMDIR",
265     [NFSPROC3_RENAME] = "RENAME",
266     [NFSPROC3_LINK] = "LINK",
267     [NFSPROC3_READDIR] = "READDIR",
268     [NFSPROC3_READDIRPLUS] = "READDIRPLUS",
269     [NFSPROC3_FSSTAT] = "FSSTAT",
270     [NFSPROC3_FSINFO] = "FSINFO",
271     [NFSPROC3_PATHCONF] = "PATHCONF",
272     [NFSPROC3_COMMIT] = "COMMIT",
273 };
274
275 static void
276 nfs_program_3(RPCRequest *req)
277 {
278     RPCConnection *connection = req->connection;
279     uint32_t xid = req->xid;
280     const char *msg_buf = req->raw_args->str + req->raw_args_header_bytes;
281     size_t msg_len = req->raw_args->len - req->raw_args_header_bytes;
282
283     union argtype {
284         nfs_fh3 nfsproc3_getattr_3_arg;
285         setattr3args nfsproc3_setattr_3_arg;
286         diropargs3 nfsproc3_lookup_3_arg;
287         access3args nfsproc3_access_3_arg;
288         nfs_fh3 nfsproc3_readlink_3_arg;
289         read3args nfsproc3_read_3_arg;
290         write3args nfsproc3_write_3_arg;
291         create3args nfsproc3_create_3_arg;
292         mkdir3args nfsproc3_mkdir_3_arg;
293         symlink3args nfsproc3_symlink_3_arg;
294         mknod3args nfsproc3_mknod_3_arg;
295         diropargs3 nfsproc3_remove_3_arg;
296         diropargs3 nfsproc3_rmdir_3_arg;
297         rename3args nfsproc3_rename_3_arg;
298         link3args nfsproc3_link_3_arg;
299         readdir3args nfsproc3_readdir_3_arg;
300         readdirplus3args nfsproc3_readdirplus_3_arg;
301         nfs_fh3 nfsproc3_fsstat_3_arg;
302         nfs_fh3 nfsproc3_fsinfo_3_arg;
303         nfs_fh3 nfsproc3_pathconf_3_arg;
304         commit3args nfsproc3_commit_3_arg;
305     };
306     char *result;
307     xdrproc_t _xdr_argument, _xdr_result;
308     char *(*local)(char *, RPCRequest *);
309
310     if (req->req_proc < sizeof(nfs_proc_names) / sizeof(const char *)) {
311         printf("Dispatched NFS RPC message type %s\n",
312                nfs_proc_names[req->req_proc]);
313     } else {
314         printf("Dispatched unknown NFS RPC message type %d\n", req->req_proc);
315     }
316
317     switch (req->req_proc) {
318     case NFSPROC3_NULL:
319         _xdr_argument = (xdrproc_t) xdr_void;
320         _xdr_result = (xdrproc_t) xdr_void;
321         local = (char *(*)(char *, RPCRequest *)) nfsproc3_null_3_svc;
322         break;
323
324     case NFSPROC3_GETATTR:
325         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
326         _xdr_result = (xdrproc_t) xdr_getattr3res;
327         local = (char *(*)(char *, RPCRequest *)) nfsproc3_getattr_3_svc;
328         break;
329
330     case NFSPROC3_SETATTR:
331         _xdr_argument = (xdrproc_t) xdr_setattr3args;
332         _xdr_result = (xdrproc_t) xdr_wccstat3;
333         local = (char *(*)(char *, RPCRequest *)) nfsproc3_setattr_3_svc;
334         break;
335
336     case NFSPROC3_LOOKUP:
337         _xdr_argument = (xdrproc_t) xdr_diropargs3;
338         _xdr_result = (xdrproc_t) xdr_lookup3res;
339         local = (char *(*)(char *, RPCRequest *)) nfsproc3_lookup_3_svc;
340         break;
341
342     case NFSPROC3_ACCESS:
343         _xdr_argument = (xdrproc_t) xdr_access3args;
344         _xdr_result = (xdrproc_t) xdr_access3res;
345         local = (char *(*)(char *, RPCRequest *)) nfsproc3_access_3_svc;
346         break;
347
348     case NFSPROC3_READLINK:
349         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
350         _xdr_result = (xdrproc_t) xdr_readlink3res;
351         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readlink_3_svc;
352         break;
353
354     case NFSPROC3_READ:
355         _xdr_argument = (xdrproc_t) xdr_read3args;
356         _xdr_result = (xdrproc_t) xdr_read3res;
357         local = (char *(*)(char *, RPCRequest *)) nfsproc3_read_3_svc;
358         break;
359
360     case NFSPROC3_WRITE:
361         _xdr_argument = (xdrproc_t) xdr_write3args;
362         _xdr_result = (xdrproc_t) xdr_write3res;
363         local = (char *(*)(char *, RPCRequest *)) nfsproc3_write_3_svc;
364         break;
365
366     case NFSPROC3_CREATE:
367         _xdr_argument = (xdrproc_t) xdr_create3args;
368         _xdr_result = (xdrproc_t) xdr_diropres3;
369         local = (char *(*)(char *, RPCRequest *)) nfsproc3_create_3_svc;
370         break;
371
372     case NFSPROC3_MKDIR:
373         _xdr_argument = (xdrproc_t) xdr_mkdir3args;
374         _xdr_result = (xdrproc_t) xdr_diropres3;
375         local = (char *(*)(char *, RPCRequest *)) nfsproc3_mkdir_3_svc;
376         break;
377
378     case NFSPROC3_SYMLINK:
379         _xdr_argument = (xdrproc_t) xdr_symlink3args;
380         _xdr_result = (xdrproc_t) xdr_diropres3;
381         local = (char *(*)(char *, RPCRequest *)) nfsproc3_symlink_3_svc;
382         break;
383
384     case NFSPROC3_MKNOD:
385         _xdr_argument = (xdrproc_t) xdr_mknod3args;
386         _xdr_result = (xdrproc_t) xdr_diropres3;
387         local = (char *(*)(char *, RPCRequest *)) nfsproc3_mknod_3_svc;
388         break;
389
390     case NFSPROC3_REMOVE:
391         _xdr_argument = (xdrproc_t) xdr_diropargs3;
392         _xdr_result = (xdrproc_t) xdr_wccstat3;
393         local = (char *(*)(char *, RPCRequest *)) nfsproc3_remove_3_svc;
394         break;
395
396     case NFSPROC3_RMDIR:
397         _xdr_argument = (xdrproc_t) xdr_diropargs3;
398         _xdr_result = (xdrproc_t) xdr_wccstat3;
399         local = (char *(*)(char *, RPCRequest *)) nfsproc3_rmdir_3_svc;
400         break;
401
402     case NFSPROC3_RENAME:
403         _xdr_argument = (xdrproc_t) xdr_rename3args;
404         _xdr_result = (xdrproc_t) xdr_rename3res;
405         local = (char *(*)(char *, RPCRequest *)) nfsproc3_rename_3_svc;
406         break;
407
408     case NFSPROC3_LINK:
409         _xdr_argument = (xdrproc_t) xdr_link3args;
410         _xdr_result = (xdrproc_t) xdr_link3res;
411         local = (char *(*)(char *, RPCRequest *)) nfsproc3_link_3_svc;
412         break;
413
414     case NFSPROC3_READDIR:
415         _xdr_argument = (xdrproc_t) xdr_readdir3args;
416         _xdr_result = (xdrproc_t) xdr_readdir3res;
417         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readdir_3_svc;
418         break;
419
420     case NFSPROC3_READDIRPLUS:
421         _xdr_argument = (xdrproc_t) xdr_readdirplus3args;
422         _xdr_result = (xdrproc_t) xdr_readdirplus3res;
423         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readdirplus_3_svc;
424         break;
425
426     case NFSPROC3_FSSTAT:
427         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
428         _xdr_result = (xdrproc_t) xdr_fsstat3res;
429         local = (char *(*)(char *, RPCRequest *)) nfsproc3_fsstat_3_svc;
430         break;
431
432     case NFSPROC3_FSINFO:
433         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
434         _xdr_result = (xdrproc_t) xdr_fsinfo3res;
435         local = (char *(*)(char *, RPCRequest *)) nfsproc3_fsinfo_3_svc;
436         break;
437
438     case NFSPROC3_PATHCONF:
439         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
440         _xdr_result = (xdrproc_t) xdr_pathconf3res;
441         local = (char *(*)(char *, RPCRequest *)) nfsproc3_pathconf_3_svc;
442         break;
443
444     case NFSPROC3_COMMIT:
445         _xdr_argument = (xdrproc_t) xdr_commit3args;
446         _xdr_result = (xdrproc_t) xdr_commit3res;
447         local = (char *(*)(char *, RPCRequest *)) nfsproc3_commit_3_svc;
448         break;
449
450     default:
451         async_rpc_send_failure(req, PROC_UNAVAIL);
452         return;
453     }
454
455     /* Decode incoming message */
456     req->xdr_args_free = _xdr_argument;
457     req->args = g_new0(union argtype, 1);
458     XDR xdr_in;
459     xdrmem_create(&xdr_in, (char *)msg_buf, msg_len, XDR_DECODE);
460     if (!_xdr_argument(&xdr_in, req->args)) {
461         async_rpc_send_failure(req, GARBAGE_ARGS);
462         fprintf(stderr, "RPC decode error!\n");
463         return;
464     }
465
466     /* Perform the call. */
467     req->xdr_result = _xdr_result;
468     result = (*local)((char *)req->args, req);
469
470     return;
471 }
472
473 /* Enhanced, asynchronous-friendly RPC layer.  This is a replacement for the
474  * built-in sunrpc parsing and dispatch that will allow for processing multiple
475  * requests at the same time. */
476 static GMainContext *main_context;
477 static GMainLoop *main_loop;
478
479 static GThreadPool *rpc_thread_pool;
480
481 static volatile int fs_dump_requested = 0;
482
483 static void sig_handler(int sig)
484 {
485     if (sig == SIGUSR1) {
486         fs_dump_requested = 1;
487     }
488 }
489
490 static gboolean async_flushd(gpointer data)
491 {
492     if (fs_dump_requested) {
493         bluesky_debug_dump(fs);
494         fs_dump_requested = 0;
495     }
496
497     bluesky_flushd_invoke(fs);
498     return TRUE;
499 }
500
501 static void async_rpc_task(gpointer data, gpointer user_data)
502 {
503     nfs_program_3((RPCRequest *)data);
504 }
505
506 static async_rpc_init()
507 {
508     main_context = g_main_context_new();
509     main_loop = g_main_loop_new(main_context, FALSE);
510
511     rpc_thread_pool = g_thread_pool_new(async_rpc_task, NULL, -1, FALSE, NULL);
512
513     /* Arrange to have the cache writeback code run every five seconds. */
514     GSource *source = g_timeout_source_new_seconds(5);
515     g_source_set_callback(source, async_flushd, NULL, NULL);
516     g_source_attach(source, main_context);
517     g_source_unref(source);
518
519     /* Signal USR1 is used to request a debugging dump of filesyste info */
520     struct sigaction sa;
521     sa.sa_handler = sig_handler;
522     sigemptyset(&sa.sa_mask);
523     sa.sa_flags = SA_RESTART;
524     if (sigaction(SIGUSR1, &sa, NULL) < 0) {
525         perror("sigaction");
526     }
527 }
528
529 struct rpc_call_header {
530     uint32_t xid;
531     uint32_t mtype;
532     uint32_t rpcvers;
533     uint32_t prog;
534     uint32_t vers;
535     uint32_t proc;
536 };
537
538 struct rpc_auth {
539     uint32_t flavor;
540     uint32_t len;
541 };
542
543 /* Decode an RPC message and process it.  Returns a boolean indicating whether
544  * the message could be processed; if false, an unrecoverable error occurred
545  * and the transport should be closed. */
546 static gboolean async_rpc_dispatch(RPCConnection *rpc)
547 {
548     bluesky_time_hires time_start = bluesky_now_hires();
549     int i;
550     GString *msg = rpc->msgbuf;
551     const char *buf = msg->str;
552
553     if (msg->len < sizeof(struct rpc_call_header)) {
554         fprintf(stderr, "Short RPC message: only %zd bytes!\n", msg->len);
555         return FALSE;
556     }
557
558     struct rpc_call_header *header = (struct rpc_call_header *)(msg->str);
559     uint32_t xid = ntohl(header->xid);
560
561     if (ntohl(header->mtype) != 0) {
562         /* Not an RPC call */
563         return FALSE;
564     }
565
566     if (ntohl(header->rpcvers) != 2) {
567         return FALSE;
568     }
569
570     RPCRequest *req = g_new0(RPCRequest, 1);
571     req->connection = rpc;
572     req->time_start = time_start;
573     req->xid = xid;
574
575     if (ntohl(header->prog) != NFS_PROGRAM) {
576         async_rpc_send_failure(req, PROG_UNAVAIL);
577         return TRUE;
578     } else if (ntohl(header->vers) != NFS_V3) {
579         /* FIXME: Should be PROG_MISMATCH */
580         async_rpc_send_failure(req, PROG_UNAVAIL);
581         return TRUE;
582     }
583
584     uint32_t proc = ntohl(header->proc);
585
586     /* Next, skip over authentication headers. */
587     buf += sizeof(struct rpc_call_header);
588     for (i = 0; i < 2; i++) {
589         struct rpc_auth *auth = (struct rpc_auth *)buf;
590         if (buf - msg->str + sizeof(struct rpc_auth) > msg->len)
591             return FALSE;
592
593         gsize authsize = ntohl(auth->len) + sizeof(struct rpc_auth);
594         if (authsize > MAX_RPC_MSGSIZE)
595             return FALSE;
596
597         buf += authsize;
598     }
599
600     if (buf - msg->str > msg->len)
601         return FALSE;
602
603     req->raw_args = msg;
604     req->raw_args_header_bytes = buf - msg->str;
605     req->req_proc = ntohl(header->proc);
606     rpc->msgbuf = g_string_new("");
607
608     if (bluesky_options.sync_frontends) {
609         nfs_program_3(req);
610     } else {
611         g_thread_pool_push(rpc_thread_pool, req, NULL);
612     }
613
614     return TRUE;
615 }
616
617 /* Write the given data to the RPC socket. */
618 static void async_rpc_write(RPCConnection *rpc,
619                             const char *buf, gsize len)
620 {
621     if (rpc->udp_transport) {
622         g_string_append_len(rpc->sendbuf, buf, len);
623         return;
624     }
625
626     /* Normal TCP path */
627     while (len > 0) {
628         gsize written = 0;
629         switch (g_io_channel_write_chars(rpc->channel, buf, len,
630                                          &written, NULL)) {
631         case G_IO_STATUS_ERROR:
632         case G_IO_STATUS_EOF:
633         case G_IO_STATUS_AGAIN:
634             fprintf(stderr, "Error writing to socket!\n");
635             return;
636         case G_IO_STATUS_NORMAL:
637             len -= written;
638             buf += written;
639             break;
640         }
641     }
642
643     // g_io_channel_flush(rpc->channel, NULL);
644 }
645
646 /* Flush a completed message out to the RPC socket */
647 static void async_rpc_flush(RPCConnection *rpc)
648 {
649     if (rpc->udp_transport) {
650         sendto(g_io_channel_unix_get_fd(rpc->channel),
651                rpc->sendbuf->str, rpc->sendbuf->len, 0,
652                (struct sockaddr *)&rpc->peer, sizeof(struct sockaddr_in));
653         return;
654     } else {
655         g_io_channel_flush(rpc->channel, NULL);
656     }
657 }
658
659 static gboolean async_rpc_do_read(GIOChannel *channel,
660                                   GIOCondition condition,
661                                   gpointer data)
662 {
663     RPCConnection *rpc = (RPCConnection *)data;
664
665     gsize bytes_to_read = 0;    /* Number of bytes to attempt to read. */
666
667     /* If we have not yet read in the fragment header, do that first.  This is
668      * 4 bytes that indicates the number of bytes in the message to follow
669      * (with the high bit set if this is the last fragment making up the
670      * message). */
671     if (rpc->frag_len == 0) {
672         bytes_to_read = 4 - rpc->frag_hdr_bytes;
673     } else {
674         bytes_to_read = rpc->frag_len & 0x7fffffff;
675     }
676
677     if (bytes_to_read > MAX_RPC_MSGSIZE
678         || rpc->msgbuf->len + bytes_to_read > MAX_RPC_MSGSIZE)
679     {
680         fprintf(stderr, "Excessive fragment size for RPC: %zd bytes\n",
681                 bytes_to_read);
682         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
683         return FALSE;
684     }
685
686     gsize bytes_read = 0;
687     g_string_set_size(rpc->msgbuf, rpc->msgbuf->len + bytes_to_read);
688     char *buf = &rpc->msgbuf->str[rpc->msgbuf->len - bytes_to_read];
689     switch (g_io_channel_read_chars(rpc->channel, buf,
690                                     bytes_to_read, &bytes_read, NULL)) {
691     case G_IO_STATUS_NORMAL:
692         break;
693     case G_IO_STATUS_AGAIN:
694         return TRUE;
695     case G_IO_STATUS_EOF:
696         if (bytes_read == bytes_to_read)
697             break;
698         /* else fall through */
699     case G_IO_STATUS_ERROR:
700         fprintf(stderr, "Unexpected error or end of file on RPC stream %d!\n",
701                 g_io_channel_unix_get_fd(rpc->channel));
702         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
703         /* TODO: Clean up connection object. */
704         return FALSE;
705     }
706
707     g_assert(bytes_read >= 0 && bytes_read <= bytes_to_read);
708
709     g_string_set_size(rpc->msgbuf,
710                       rpc->msgbuf->len - (bytes_to_read - bytes_read));
711
712     if (rpc->frag_len == 0) {
713         /* Handle reading in the fragment header.  If we've read the complete
714          * header, store the fragment size. */
715         rpc->frag_hdr_bytes += bytes_read;
716         if (rpc->frag_hdr_bytes == 4) {
717             memcpy((char *)&rpc->frag_len,
718                    &rpc->msgbuf->str[rpc->msgbuf->len - 4], 4);
719             rpc->frag_len = ntohl(rpc->frag_len);
720             g_string_set_size(rpc->msgbuf, rpc->msgbuf->len - 4);
721             rpc->frag_hdr_bytes = 0;
722         }
723     } else {
724         /* We were reading in the fragment body. */
725         rpc->frag_len -= bytes_read;
726
727         if (rpc->frag_len == 0x80000000) {
728             /* We have a complete message since this was the last fragment and
729              * there are no more bytes in it.  Dispatch the message. */
730             if (!async_rpc_dispatch(rpc)) {
731                 fprintf(stderr, "Invalid RPC message, closing channel\n");
732                 g_io_channel_shutdown(rpc->channel, TRUE, NULL);
733                 return FALSE;
734             }
735             rpc->frag_len = 0;
736             g_string_set_size(rpc->msgbuf, 0);
737         }
738     }
739
740     return TRUE;
741 }
742
743 static gboolean async_rpc_do_accept(GIOChannel *channel,
744                                     GIOCondition condition,
745                                     gpointer data)
746 {
747     int fd = g_io_channel_unix_get_fd(channel);
748     struct sockaddr_in addr;
749     socklen_t addrlen = sizeof(addr);
750
751     g_print("Received new connection on fd %d!\n", fd);
752     int nfd = accept(fd, (struct sockaddr *)&addr, &addrlen);
753     if (nfd < 0) {
754         fprintf(stderr, "Error accepting connection: %m\n");
755         return TRUE;
756     }
757
758     RPCConnection *rpc = g_new0(RPCConnection, 1);
759     rpc->channel = g_io_channel_unix_new(nfd);
760     rpc->msgbuf = g_string_new("");
761     g_io_channel_set_encoding(rpc->channel, NULL, NULL);
762     rpc->send_lock = g_mutex_new();
763     GSource *source = g_io_create_watch(rpc->channel, G_IO_IN);
764     g_source_set_callback(source, (GSourceFunc)async_rpc_do_read,
765                           rpc, NULL);
766     g_source_attach(source, main_context);
767     g_source_unref(source);
768
769     return TRUE;
770 }
771
772 static async_rpc_register_listening(int fd)
773 {
774     GIOChannel *channel = g_io_channel_unix_new(fd);
775     g_io_channel_set_encoding(channel, NULL, NULL);
776     GSource *source = g_io_create_watch(channel, G_IO_IN);
777     g_source_set_callback(source, (GSourceFunc)async_rpc_do_accept,
778                           NULL, NULL);
779     g_source_attach(source, main_context);
780     g_source_unref(source);
781 }
782
783 static gboolean async_rpc_do_udp(GIOChannel *channel,
784                                  GIOCondition condition,
785                                  gpointer data)
786 {
787     char buf[65536];
788
789     struct sockaddr_in src;
790     socklen_t addrlen = sizeof(struct sockaddr_in);
791     ssize_t len = recvfrom(g_io_channel_unix_get_fd(channel),
792                            buf, sizeof(buf), 0,
793                            (struct sockaddr *)&src, &addrlen);
794     if (len < 0) {
795         fprintf(stderr, "UDP read error: %m, shutting down UDP\n");
796         return FALSE;
797     }
798
799     g_assert(len < sizeof(buf));
800
801     RPCConnection *rpc = g_new0(RPCConnection, 1);
802     rpc->channel = channel;
803     rpc->msgbuf = g_string_new_len(buf, len);
804     rpc->send_lock = g_mutex_new();
805     rpc->udp_transport = TRUE;
806     memcpy(&rpc->peer, &src, sizeof(struct sockaddr_in));
807     rpc->sendbuf = g_string_new("");
808
809     /* We have a complete message since this was the last fragment and
810      * there are no more bytes in it.  Dispatch the message. */
811     async_rpc_dispatch(rpc);
812
813     return TRUE;
814 }
815
816 static async_rpc_register_listening_udp(int fd)
817 {
818     GIOChannel *channel = g_io_channel_unix_new(fd);
819     g_io_channel_set_encoding(channel, NULL, NULL);
820     GSource *source = g_io_create_watch(channel, G_IO_IN);
821     g_source_set_callback(source, (GSourceFunc)async_rpc_do_udp,
822                           NULL, NULL);
823     g_source_attach(source, main_context);
824     g_source_unref(source);
825 }
826
827 static gpointer async_rpc_run(gpointer data)
828 {
829     g_print("Starting NFS main loop...\n");
830     g_main_loop_run(main_loop);
831 }
832
833 void register_rpc()
834 {
835     SVCXPRT *transp;
836
837     async_rpc_init();
838
839     /* MOUNT protocol */
840     pmap_unset (MOUNT_PROGRAM, MOUNT_V3);
841
842     transp = svcudp_create(RPC_ANYSOCK);
843     if (transp == NULL) {
844         fprintf(stderr, "%s", "cannot create udp service.");
845         exit(1);
846     }
847     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_UDP)) {
848         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, udp).");
849         exit(1);
850     }
851
852     transp = svctcp_create(RPC_ANYSOCK, 0, 0);
853     if (transp == NULL) {
854         fprintf(stderr, "%s", "cannot create tcp service.");
855         exit(1);
856     }
857     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_TCP)) {
858         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, tcp).");
859         exit(1);
860     }
861
862     /* NFS protocol (version 3) */
863     pmap_unset (NFS_PROGRAM, NFS_V3);
864
865     int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
866     if (fd < 0) {
867         fprintf(stderr, "Unable to create NFS TCP socket: %m\n");
868         exit(1);
869     }
870
871     int n = 1;
872     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n));
873
874     struct sockaddr_in addr;
875     addr.sin_family = AF_INET;
876     addr.sin_port = htons(NFS_SERVICE_PORT);
877     addr.sin_addr.s_addr = INADDR_ANY;
878     if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
879         fprintf(stderr, "Unable to bind to NFS TCP address: %m\n");
880         exit(1);
881     }
882
883     if (listen(fd, SOMAXCONN) < 0) {
884         fprintf(stderr, "Unable to listen on NFS TCP socket: %m\n");
885         exit(1);
886     }
887
888     if (!pmap_set(NFS_PROGRAM, NFS_V3, IPPROTO_TCP, NFS_SERVICE_PORT)) {
889         fprintf(stderr, "Could not register NFS RPC service!\n");
890         exit(1);
891     }
892
893     async_rpc_register_listening(fd);
894
895     /* Minimal UDP NFSv3 support */
896     fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
897     if (fd < 0) {
898         fprintf(stderr, "Unable to create NFS UDP socket: %m\n");
899         exit(1);
900     }
901
902     addr.sin_family = AF_INET;
903     addr.sin_port = htons(NFS_SERVICE_PORT);
904     addr.sin_addr.s_addr = INADDR_ANY;
905     if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
906         fprintf(stderr, "Unable to bind to NFS UDP address: %m\n");
907         exit(1);
908     }
909
910     if (!pmap_set(NFS_PROGRAM, NFS_V3, IPPROTO_UDP, NFS_SERVICE_PORT)) {
911         fprintf(stderr, "Could not register NFS UDP RPC service!\n");
912         exit(1);
913     }
914
915     async_rpc_register_listening_udp(fd);
916
917     g_thread_create(async_rpc_run, NULL, TRUE, NULL);
918 }