Remove some debugging messages.
[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 <memory.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <netinet/ip.h>
25
26 #include "bluesky.h"
27 extern BlueSkyFS *fs;
28
29 /* TCP port number to use for NFS protocol.  (Should be 2049.) */
30 #define NFS_SERVICE_PORT 2051
31
32 /* Maximum size of a single RPC message that we will accept (8 MB). */
33 #define MAX_RPC_MSGSIZE (8 << 20)
34
35 static void
36 mount_program_3(struct svc_req *rqstp, register SVCXPRT *transp)
37 {
38     union {
39         dirpath mountproc3_mnt_3_arg;
40         dirpath mountproc3_umnt_3_arg;
41     } argument;
42     char *result;
43     xdrproc_t _xdr_argument, _xdr_result;
44     char *(*local)(char *, struct svc_req *);
45
46     switch (rqstp->rq_proc) {
47     case MOUNTPROC3_NULL:
48         _xdr_argument = (xdrproc_t) xdr_void;
49         _xdr_result = (xdrproc_t) xdr_void;
50         local = (char *(*)(char *, struct svc_req *)) mountproc3_null_3_svc;
51         break;
52
53     case MOUNTPROC3_MNT:
54         _xdr_argument = (xdrproc_t) xdr_dirpath;
55         _xdr_result = (xdrproc_t) xdr_mountres3;
56         local = (char *(*)(char *, struct svc_req *)) mountproc3_mnt_3_svc;
57         break;
58
59     case MOUNTPROC3_DUMP:
60         _xdr_argument = (xdrproc_t) xdr_void;
61         _xdr_result = (xdrproc_t) xdr_mountlist;
62         local = (char *(*)(char *, struct svc_req *)) mountproc3_dump_3_svc;
63         break;
64
65     case MOUNTPROC3_UMNT:
66         _xdr_argument = (xdrproc_t) xdr_dirpath;
67         _xdr_result = (xdrproc_t) xdr_void;
68         local = (char *(*)(char *, struct svc_req *)) mountproc3_umnt_3_svc;
69         break;
70
71     case MOUNTPROC3_UMNTALL:
72         _xdr_argument = (xdrproc_t) xdr_void;
73         _xdr_result = (xdrproc_t) xdr_void;
74         local = (char *(*)(char *, struct svc_req *)) mountproc3_umntall_3_svc;
75         break;
76
77     case MOUNTPROC3_EXPORT:
78         _xdr_argument = (xdrproc_t) xdr_void;
79         _xdr_result = (xdrproc_t) xdr_exports;
80         local = (char *(*)(char *, struct svc_req *)) mountproc3_export_3_svc;
81         break;
82
83     default:
84         svcerr_noproc (transp);
85         return;
86     }
87     memset ((char *)&argument, 0, sizeof (argument));
88     if (!svc_getargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) {
89         svcerr_decode (transp);
90         return;
91     }
92     result = (*local)((char *)&argument, rqstp);
93     if (result != NULL && !svc_sendreply(transp, (xdrproc_t) _xdr_result, result)) {
94         svcerr_systemerr (transp);
95     }
96     if (!svc_freeargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) {
97         fprintf (stderr, "%s", "unable to free arguments");
98         exit (1);
99     }
100     return;
101 }
102
103 struct rpc_reply {
104     uint32_t xid;
105     uint32_t type;
106     uint32_t stat;
107     uint32_t verf_flavor;
108     uint32_t verf_len;
109     uint32_t accept_stat;
110 };
111
112 static void async_rpc_write(RPCConnection *rpc,
113                             const char *buf, gsize len);
114
115 struct rpc_fail_reply {
116     uint32_t xid;
117     uint32_t type;
118     uint32_t stat;
119     uint32_t verf_flavor;
120     uint32_t verf_len;
121     uint32_t accept_stat;
122 };
123
124 /* Routines for XDR-encoding to a growable string. */
125 static bool_t xdr_string_putlong(XDR *xdrs, const long *lp)
126 {
127     GString *str = (GString *)xdrs->x_private;
128     uint32_t data = htonl(*lp);
129     g_string_set_size(str, str->len + 4);
130     memcpy(str->str + str->len - 4, &data, 4);
131     return TRUE;
132 }
133
134 static bool_t xdr_string_putbytes(XDR *xdrs, const char *addr, u_int len)
135 {
136     GString *str = (GString *)xdrs->x_private;
137     g_string_set_size(str, str->len + len);
138     memcpy(str->str + str->len - len, addr, len);
139     return TRUE;
140 }
141
142 static u_int xdr_string_getpos(const XDR *xdrs)
143 {
144     GString *str = (GString *)xdrs->x_private;
145     return str->len;
146 }
147
148 static bool_t xdr_string_putint32(XDR *xdrs, const int32_t *ip)
149 {
150     GString *str = (GString *)xdrs->x_private;
151     uint32_t data = htonl(*ip);
152     g_string_set_size(str, str->len + 4);
153     memcpy(str->str + str->len - 4, &data, 4);
154     return TRUE;
155 }
156
157 static int32_t *xdr_string_inline(XDR *xdrs, u_int len)
158 {
159     GString *str = (GString *)xdrs->x_private;
160     g_string_set_size(str, str->len + len);
161     return (int32_t *)(str->str + str->len - len);
162 }
163
164 static void xdr_string_destroy(XDR *xdrs)
165 {
166 }
167
168 static struct xdr_ops xdr_string_ops = {
169     .x_putlong = xdr_string_putlong,
170     .x_putbytes = xdr_string_putbytes,
171     .x_getpostn = xdr_string_getpos,
172     .x_putint32 = xdr_string_putint32,
173     .x_inline = xdr_string_inline,
174     .x_destroy = xdr_string_destroy,
175 };
176
177 static void xdr_string_create(XDR *xdrs, GString *string, enum xdr_op op)
178 {
179     xdrs->x_op = op;
180     xdrs->x_ops = &xdr_string_ops;
181     xdrs->x_private = (char *)string;
182     xdrs->x_base = NULL;
183     xdrs->x_handy = 0;
184 }
185
186 static void
187 async_rpc_send_failure(RPCRequest *req, enum accept_stat stat)
188 {
189     struct rpc_fail_reply header;
190
191     header.xid = htonl(req->xid);
192     header.type = htonl(1);     /* REPLY */
193     header.stat = htonl(MSG_ACCEPTED);
194     header.verf_flavor = 0;
195     header.verf_len = 0;
196     header.accept_stat = htonl(stat);
197
198     uint32_t fragment = htonl(sizeof(header) | 0x80000000);
199     async_rpc_write(req->connection, (const char *)&fragment, sizeof(fragment));
200     async_rpc_write(req->connection, (const char *)&header, sizeof(header));
201     g_io_channel_flush(req->connection->channel, NULL);
202
203     if (req->args != NULL) {
204         char buf[4];
205         XDR xdr;
206         xdrmem_create(&xdr, buf, sizeof(buf), XDR_FREE);
207         if (!req->xdr_args_free(&xdr, req->args)) {
208             fprintf(stderr, "unable to free arguments");
209         }
210     }
211
212     if (req->raw_args != NULL)
213         g_string_free(req->raw_args, TRUE);
214
215     g_free(req);
216 }
217
218 void
219 async_rpc_send_reply(RPCRequest *req, void *result)
220 {
221     GString *str = g_string_new("");
222     XDR xdr_out;
223     xdr_string_create(&xdr_out, str, XDR_ENCODE);
224     if (!req->xdr_result(&xdr_out, result)) {
225         async_rpc_send_failure(req, SYSTEM_ERR);
226         g_string_free(str, TRUE);
227         return;
228     }
229
230     struct rpc_reply header;
231     header.xid = htonl(req->xid);
232     header.type = htonl(1);     /* REPLY */
233     header.stat = htonl(MSG_ACCEPTED);
234     header.verf_flavor = 0;
235     header.verf_len = 0;
236     header.accept_stat = 0;
237
238     gsize msg_size = str->len;
239     uint32_t fragment = htonl((msg_size + sizeof(header)) | 0x80000000);
240     async_rpc_write(req->connection, (const char *)&fragment, sizeof(fragment));
241     async_rpc_write(req->connection, (const char *)&header, sizeof(header));
242     async_rpc_write(req->connection, str->str, str->len);
243     g_io_channel_flush(req->connection->channel, NULL);
244
245     /* Clean up. */
246     g_string_free(str, TRUE);
247
248     if (req->args != NULL) {
249         char buf[4];
250         XDR xdr;
251         xdrmem_create(&xdr, buf, sizeof(buf), XDR_FREE);
252         if (!req->xdr_args_free(&xdr, req->args)) {
253             fprintf(stderr, "unable to free arguments");
254         }
255     }
256
257     if (req->raw_args != NULL)
258         g_string_free(req->raw_args, TRUE);
259
260     g_free(req);
261 }
262
263 static void
264 nfs_program_3(RPCRequest *req)
265 {
266     RPCConnection *connection = req->connection;
267     uint32_t xid = req->xid;
268     const char *msg_buf = req->raw_args->str + req->raw_args_header_bytes;
269     size_t msg_len = req->raw_args->len - req->raw_args_header_bytes;
270
271     union argtype {
272         nfs_fh3 nfsproc3_getattr_3_arg;
273         setattr3args nfsproc3_setattr_3_arg;
274         diropargs3 nfsproc3_lookup_3_arg;
275         access3args nfsproc3_access_3_arg;
276         nfs_fh3 nfsproc3_readlink_3_arg;
277         read3args nfsproc3_read_3_arg;
278         write3args nfsproc3_write_3_arg;
279         create3args nfsproc3_create_3_arg;
280         mkdir3args nfsproc3_mkdir_3_arg;
281         symlink3args nfsproc3_symlink_3_arg;
282         mknod3args nfsproc3_mknod_3_arg;
283         diropargs3 nfsproc3_remove_3_arg;
284         diropargs3 nfsproc3_rmdir_3_arg;
285         rename3args nfsproc3_rename_3_arg;
286         link3args nfsproc3_link_3_arg;
287         readdir3args nfsproc3_readdir_3_arg;
288         readdirplus3args nfsproc3_readdirplus_3_arg;
289         nfs_fh3 nfsproc3_fsstat_3_arg;
290         nfs_fh3 nfsproc3_fsinfo_3_arg;
291         nfs_fh3 nfsproc3_pathconf_3_arg;
292         commit3args nfsproc3_commit_3_arg;
293     };
294     char *result;
295     xdrproc_t _xdr_argument, _xdr_result;
296     char *(*local)(char *, RPCRequest *);
297
298     switch (req->req_proc) {
299     case NFSPROC3_NULL:
300         _xdr_argument = (xdrproc_t) xdr_void;
301         _xdr_result = (xdrproc_t) xdr_void;
302         local = (char *(*)(char *, RPCRequest *)) nfsproc3_null_3_svc;
303         break;
304
305     case NFSPROC3_GETATTR:
306         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
307         _xdr_result = (xdrproc_t) xdr_getattr3res;
308         local = (char *(*)(char *, RPCRequest *)) nfsproc3_getattr_3_svc;
309         break;
310
311     case NFSPROC3_SETATTR:
312         _xdr_argument = (xdrproc_t) xdr_setattr3args;
313         _xdr_result = (xdrproc_t) xdr_wccstat3;
314         local = (char *(*)(char *, RPCRequest *)) nfsproc3_setattr_3_svc;
315         break;
316
317     case NFSPROC3_LOOKUP:
318         _xdr_argument = (xdrproc_t) xdr_diropargs3;
319         _xdr_result = (xdrproc_t) xdr_lookup3res;
320         local = (char *(*)(char *, RPCRequest *)) nfsproc3_lookup_3_svc;
321         break;
322
323     case NFSPROC3_ACCESS:
324         _xdr_argument = (xdrproc_t) xdr_access3args;
325         _xdr_result = (xdrproc_t) xdr_access3res;
326         local = (char *(*)(char *, RPCRequest *)) nfsproc3_access_3_svc;
327         break;
328
329     case NFSPROC3_READLINK:
330         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
331         _xdr_result = (xdrproc_t) xdr_readlink3res;
332         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readlink_3_svc;
333         break;
334
335     case NFSPROC3_READ:
336         _xdr_argument = (xdrproc_t) xdr_read3args;
337         _xdr_result = (xdrproc_t) xdr_read3res;
338         local = (char *(*)(char *, RPCRequest *)) nfsproc3_read_3_svc;
339         break;
340
341     case NFSPROC3_WRITE:
342         _xdr_argument = (xdrproc_t) xdr_write3args;
343         _xdr_result = (xdrproc_t) xdr_write3res;
344         local = (char *(*)(char *, RPCRequest *)) nfsproc3_write_3_svc;
345         break;
346
347     case NFSPROC3_CREATE:
348         _xdr_argument = (xdrproc_t) xdr_create3args;
349         _xdr_result = (xdrproc_t) xdr_diropres3;
350         local = (char *(*)(char *, RPCRequest *)) nfsproc3_create_3_svc;
351         break;
352
353     case NFSPROC3_MKDIR:
354         _xdr_argument = (xdrproc_t) xdr_mkdir3args;
355         _xdr_result = (xdrproc_t) xdr_diropres3;
356         local = (char *(*)(char *, RPCRequest *)) nfsproc3_mkdir_3_svc;
357         break;
358
359     case NFSPROC3_SYMLINK:
360         _xdr_argument = (xdrproc_t) xdr_symlink3args;
361         _xdr_result = (xdrproc_t) xdr_diropres3;
362         local = (char *(*)(char *, RPCRequest *)) nfsproc3_symlink_3_svc;
363         break;
364
365     case NFSPROC3_MKNOD:
366         _xdr_argument = (xdrproc_t) xdr_mknod3args;
367         _xdr_result = (xdrproc_t) xdr_diropres3;
368         local = (char *(*)(char *, RPCRequest *)) nfsproc3_mknod_3_svc;
369         break;
370
371     case NFSPROC3_REMOVE:
372         _xdr_argument = (xdrproc_t) xdr_diropargs3;
373         _xdr_result = (xdrproc_t) xdr_wccstat3;
374         local = (char *(*)(char *, RPCRequest *)) nfsproc3_remove_3_svc;
375         break;
376
377     case NFSPROC3_RMDIR:
378         _xdr_argument = (xdrproc_t) xdr_diropargs3;
379         _xdr_result = (xdrproc_t) xdr_wccstat3;
380         local = (char *(*)(char *, RPCRequest *)) nfsproc3_rmdir_3_svc;
381         break;
382
383     case NFSPROC3_RENAME:
384         _xdr_argument = (xdrproc_t) xdr_rename3args;
385         _xdr_result = (xdrproc_t) xdr_rename3res;
386         local = (char *(*)(char *, RPCRequest *)) nfsproc3_rename_3_svc;
387         break;
388
389     case NFSPROC3_LINK:
390         _xdr_argument = (xdrproc_t) xdr_link3args;
391         _xdr_result = (xdrproc_t) xdr_link3res;
392         local = (char *(*)(char *, RPCRequest *)) nfsproc3_link_3_svc;
393         break;
394
395     case NFSPROC3_READDIR:
396         _xdr_argument = (xdrproc_t) xdr_readdir3args;
397         _xdr_result = (xdrproc_t) xdr_readdir3res;
398         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readdir_3_svc;
399         break;
400
401     case NFSPROC3_READDIRPLUS:
402         _xdr_argument = (xdrproc_t) xdr_readdirplus3args;
403         _xdr_result = (xdrproc_t) xdr_readdirplus3res;
404         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readdirplus_3_svc;
405         break;
406
407     case NFSPROC3_FSSTAT:
408         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
409         _xdr_result = (xdrproc_t) xdr_fsstat3res;
410         local = (char *(*)(char *, RPCRequest *)) nfsproc3_fsstat_3_svc;
411         break;
412
413     case NFSPROC3_FSINFO:
414         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
415         _xdr_result = (xdrproc_t) xdr_fsinfo3res;
416         local = (char *(*)(char *, RPCRequest *)) nfsproc3_fsinfo_3_svc;
417         break;
418
419     case NFSPROC3_PATHCONF:
420         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
421         _xdr_result = (xdrproc_t) xdr_pathconf3res;
422         local = (char *(*)(char *, RPCRequest *)) nfsproc3_pathconf_3_svc;
423         break;
424
425     case NFSPROC3_COMMIT:
426         _xdr_argument = (xdrproc_t) xdr_commit3args;
427         _xdr_result = (xdrproc_t) xdr_commit3res;
428         local = (char *(*)(char *, RPCRequest *)) nfsproc3_commit_3_svc;
429         break;
430
431     default:
432         async_rpc_send_failure(req, PROC_UNAVAIL);
433         return;
434     }
435
436     /* Decode incoming message */
437     req->xdr_args_free = _xdr_argument;
438     req->args = g_new0(union argtype, 1);
439     XDR xdr_in;
440     xdrmem_create(&xdr_in, (char *)msg_buf, msg_len, XDR_DECODE);
441     if (!_xdr_argument(&xdr_in, req->args)) {
442         async_rpc_send_failure(req, GARBAGE_ARGS);
443         fprintf(stderr, "RPC decode error!\n");
444         return;
445     }
446
447     /* Perform the call. */
448     req->xdr_result = _xdr_result;
449     result = (*local)((char *)req->args, req);
450
451     bluesky_flushd_invoke(fs);
452
453     return;
454 }
455
456 /* Enhanced, asynchronous-friendly RPC layer.  This is a replacement for the
457  * built-in sunrpc parsing and dispatch that will allow for processing multiple
458  * requests at the same time. */
459 static GMainContext *main_context;
460 static GMainLoop *main_loop;
461
462 static async_rpc_init()
463 {
464     main_context = g_main_context_new();
465     main_loop = g_main_loop_new(main_context, FALSE);
466 }
467
468 struct rpc_call_header {
469     uint32_t xid;
470     uint32_t mtype;
471     uint32_t rpcvers;
472     uint32_t prog;
473     uint32_t vers;
474     uint32_t proc;
475 };
476
477 struct rpc_auth {
478     uint32_t flavor;
479     uint32_t len;
480 };
481
482 /* Decode an RPC message and process it.  Returns a boolean indicating whether
483  * the message could be processed; if false, an unrecoverable error occurred
484  * and the transport should be closed. */
485 static gboolean async_rpc_dispatch(RPCConnection *rpc)
486 {
487     int i;
488     GString *msg = rpc->msgbuf;
489     const char *buf = msg->str;
490
491     if (msg->len < sizeof(struct rpc_call_header)) {
492         fprintf(stderr, "Short RPC message: only %zd bytes!\n", msg->len);
493         return FALSE;
494     }
495
496     struct rpc_call_header *header = (struct rpc_call_header *)(msg->str);
497     uint32_t xid = ntohl(header->xid);
498
499     if (ntohl(header->mtype) != 0) {
500         /* Not an RPC call */
501         return FALSE;
502     }
503
504     if (ntohl(header->rpcvers) != 2) {
505         return FALSE;
506     }
507
508     RPCRequest *req = g_new0(RPCRequest, 1);
509     req->connection = rpc;
510     req->xid = xid;
511
512     if (ntohl(header->prog) != NFS_PROGRAM) {
513         async_rpc_send_failure(req, PROG_UNAVAIL);
514         return TRUE;
515     } else if (ntohl(header->vers) != NFS_V3) {
516         /* FIXME: Should be PROG_MISMATCH */
517         async_rpc_send_failure(req, PROG_UNAVAIL);
518         return TRUE;
519     }
520
521     uint32_t proc = ntohl(header->proc);
522
523     /* Next, skip over authentication headers. */
524     buf += sizeof(struct rpc_call_header);
525     for (i = 0; i < 2; i++) {
526         struct rpc_auth *auth = (struct rpc_auth *)buf;
527         if (buf - msg->str + sizeof(struct rpc_auth) > msg->len)
528             return FALSE;
529
530         gsize authsize = ntohl(auth->len) + sizeof(struct rpc_auth);
531         if (authsize > MAX_RPC_MSGSIZE)
532             return FALSE;
533
534         buf += authsize;
535     }
536
537     if (buf - msg->str > msg->len)
538         return FALSE;
539
540     req->raw_args = msg;
541     req->raw_args_header_bytes = buf - msg->str;
542     req->req_proc = ntohl(header->proc);
543     rpc->msgbuf = g_string_new("");
544
545     nfs_program_3(req);
546
547     return TRUE;
548 }
549
550 /* Write the given data to the RPC socket. */
551 static void async_rpc_write(RPCConnection *rpc,
552                             const char *buf, gsize len)
553 {
554     while (len > 0) {
555         gsize written = 0;
556         switch (g_io_channel_write_chars(rpc->channel, buf, len,
557                                          &written, NULL)) {
558         case G_IO_STATUS_ERROR:
559         case G_IO_STATUS_EOF:
560         case G_IO_STATUS_AGAIN:
561             fprintf(stderr, "Error writing to socket!\n");
562             return;
563         case G_IO_STATUS_NORMAL:
564             len -= written;
565             buf += written;
566             break;
567         }
568     }
569
570     // g_io_channel_flush(rpc->channel, NULL);
571 }
572
573 static gboolean async_rpc_do_read(GIOChannel *channel,
574                                   GIOCondition condition,
575                                   gpointer data)
576 {
577     RPCConnection *rpc = (RPCConnection *)data;
578
579     gsize bytes_to_read = 0;    /* Number of bytes to attempt to read. */
580
581     /* If we have not yet read in the fragment header, do that first.  This is
582      * 4 bytes that indicates the number of bytes in the message to follow
583      * (with the high bit set if this is the last fragment making up the
584      * message). */
585     if (rpc->frag_len == 0) {
586         bytes_to_read = 4 - rpc->frag_hdr_bytes;
587     } else {
588         bytes_to_read = rpc->frag_len & 0x7fffffff;
589     }
590
591     if (bytes_to_read > MAX_RPC_MSGSIZE
592         || rpc->msgbuf->len + bytes_to_read > MAX_RPC_MSGSIZE)
593     {
594         fprintf(stderr, "Excessive fragment size for RPC: %zd bytes\n",
595                 bytes_to_read);
596         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
597         return FALSE;
598     }
599
600     gsize bytes_read = 0;
601     g_string_set_size(rpc->msgbuf, rpc->msgbuf->len + bytes_to_read);
602     char *buf = &rpc->msgbuf->str[rpc->msgbuf->len - bytes_to_read];
603     switch (g_io_channel_read_chars(rpc->channel, buf,
604                                     bytes_to_read, &bytes_read, NULL)) {
605     case G_IO_STATUS_NORMAL:
606         break;
607     case G_IO_STATUS_AGAIN:
608         return TRUE;
609     case G_IO_STATUS_EOF:
610         if (bytes_read == bytes_to_read)
611             break;
612         /* else fall through */
613     case G_IO_STATUS_ERROR:
614         fprintf(stderr, "Unexpected error or end of file on RPC stream %d!\n",
615                 g_io_channel_unix_get_fd(rpc->channel));
616         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
617         return FALSE;
618     }
619
620     g_assert(bytes_read >= 0 && bytes_read <= bytes_to_read);
621
622     g_string_set_size(rpc->msgbuf,
623                       rpc->msgbuf->len - (bytes_to_read - bytes_read));
624
625     if (rpc->frag_len == 0) {
626         /* Handle reading in the fragment header.  If we've read the complete
627          * header, store the fragment size. */
628         rpc->frag_hdr_bytes += bytes_read;
629         if (rpc->frag_hdr_bytes == 4) {
630             memcpy((char *)&rpc->frag_len,
631                    &rpc->msgbuf->str[rpc->msgbuf->len - 4], 4);
632             rpc->frag_len = ntohl(rpc->frag_len);
633             g_string_set_size(rpc->msgbuf, rpc->msgbuf->len - 4);
634             rpc->frag_hdr_bytes = 0;
635             g_print("RPC fragment header: %08x\n", rpc->frag_len);
636         }
637     } else {
638         /* We were reading in the fragment body. */
639         rpc->frag_len -= bytes_read;
640
641         if (rpc->frag_len = 0x80000000) {
642             /* We have a complete message since this was the last fragment and
643              * there are no more bytes in it.  Dispatch the message. */
644             g_print("Complete RPC message: %zd bytes\n", rpc->msgbuf->len);
645             if (!async_rpc_dispatch(rpc)) {
646                 fprintf(stderr, "Invalid RPC message, closing channel\n");
647                 g_io_channel_shutdown(rpc->channel, TRUE, NULL);
648                 return FALSE;
649             }
650             rpc->frag_len = 0;
651             g_string_set_size(rpc->msgbuf, 0);
652         }
653     }
654
655     return TRUE;
656 }
657
658 static gboolean async_rpc_do_accept(GIOChannel *channel,
659                                     GIOCondition condition,
660                                     gpointer data)
661 {
662     int fd = g_io_channel_unix_get_fd(channel);
663     struct sockaddr_in addr;
664     socklen_t addrlen = sizeof(addr);
665
666     g_print("Received new connection on fd %d!\n", fd);
667     int nfd = accept(fd, (struct sockaddr *)&addr, &addrlen);
668     if (nfd < 0) {
669         fprintf(stderr, "Error accepting connection: %m\n");
670         return TRUE;
671     }
672
673     RPCConnection *rpc = g_new0(RPCConnection, 1);
674     rpc->channel = g_io_channel_unix_new(nfd);
675     rpc->msgbuf = g_string_new("");
676     g_io_channel_set_encoding(rpc->channel, NULL, NULL);
677     GSource *source = g_io_create_watch(rpc->channel, G_IO_IN);
678     g_source_set_callback(source, (GSourceFunc)async_rpc_do_read,
679                           rpc, NULL);
680     g_source_attach(source, main_context);
681     g_source_unref(source);
682
683     return TRUE;
684 }
685
686 static async_rpc_register_listening(int fd)
687 {
688     GIOChannel *channel = g_io_channel_unix_new(fd);
689     g_io_channel_set_encoding(channel, NULL, NULL);
690     GSource *source = g_io_create_watch(channel, G_IO_IN);
691     g_source_set_callback(source, (GSourceFunc)async_rpc_do_accept,
692                           NULL, NULL);
693     g_source_attach(source, main_context);
694     g_source_unref(source);
695 }
696
697 static gpointer async_rpc_run(gpointer data)
698 {
699     g_print("Starting NFS main loop...\n");
700     g_main_loop_run(main_loop);
701 }
702
703 void register_rpc()
704 {
705     SVCXPRT *transp;
706
707     async_rpc_init();
708
709     /* MOUNT protocol */
710     pmap_unset (MOUNT_PROGRAM, MOUNT_V3);
711
712     transp = svcudp_create(RPC_ANYSOCK);
713     if (transp == NULL) {
714         fprintf(stderr, "%s", "cannot create udp service.");
715         exit(1);
716     }
717     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_UDP)) {
718         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, udp).");
719         exit(1);
720     }
721
722     transp = svctcp_create(RPC_ANYSOCK, 0, 0);
723     if (transp == NULL) {
724         fprintf(stderr, "%s", "cannot create tcp service.");
725         exit(1);
726     }
727     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_TCP)) {
728         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, tcp).");
729         exit(1);
730     }
731
732     /* NFS protocol (version 3) */
733     pmap_unset (NFS_PROGRAM, NFS_V3);
734
735     int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
736     if (fd < 0) {
737         fprintf(stderr, "Unable to create NFS TCP socket: %m\n");
738         exit(1);
739     }
740
741     int n = 1;
742     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n));
743
744     struct sockaddr_in addr;
745     addr.sin_family = AF_INET;
746     addr.sin_port = htons(NFS_SERVICE_PORT);
747     addr.sin_addr.s_addr = INADDR_ANY;
748     if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
749         fprintf(stderr, "Unable to bind to NFS TCP address: %m\n");
750         exit(1);
751     }
752
753     if (listen(fd, SOMAXCONN) < 0) {
754         fprintf(stderr, "Unable to listen on NFS TCP socket: %m\n");
755         exit(1);
756     }
757
758     if (!pmap_set(NFS_PROGRAM, NFS_V3, IPPROTO_TCP, NFS_SERVICE_PORT)) {
759         fprintf(stderr, "Could not register NFS RPC service!\n");
760         exit(1);
761     }
762
763     async_rpc_register_listening(fd);
764
765     g_thread_create(async_rpc_run, NULL, TRUE, NULL);
766 }