Properly decrement inode refcounts when finishing a request.
[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     while (req->cleanup != NULL) {
216         struct cleanup_list *c = req->cleanup;
217         req->cleanup = c->next;
218         c->func(c->arg);
219         g_free(c);
220     }
221
222     g_free(req);
223 }
224
225 void
226 async_rpc_send_reply(RPCRequest *req, void *result)
227 {
228     bluesky_time_hires time_end;
229
230     GString *str = g_string_new("");
231     XDR xdr_out;
232     xdr_string_create(&xdr_out, str, XDR_ENCODE);
233     if (!req->xdr_result(&xdr_out, result)) {
234         async_rpc_send_failure(req, SYSTEM_ERR);
235         g_string_free(str, TRUE);
236         return;
237     }
238
239     struct rpc_reply header;
240     header.xid = htonl(req->xid);
241     header.type = htonl(1);     /* REPLY */
242     header.stat = htonl(MSG_ACCEPTED);
243     header.verf_flavor = 0;
244     header.verf_len = 0;
245     header.accept_stat = 0;
246
247     gsize msg_size = str->len;
248     uint32_t fragment = htonl((msg_size + sizeof(header)) | 0x80000000);
249     async_rpc_write(req->connection, (const char *)&fragment, sizeof(fragment));
250     async_rpc_write(req->connection, (const char *)&header, sizeof(header));
251     async_rpc_write(req->connection, str->str, str->len);
252     g_io_channel_flush(req->connection->channel, NULL);
253
254     time_end = bluesky_now_hires();
255
256     printf("RPC[%"PRIx32"]: time = %"PRId64" ns\n",
257            req->xid, time_end - req->time_start);
258
259     /* Clean up. */
260     g_string_free(str, TRUE);
261
262     if (req->args != NULL) {
263         char buf[4];
264         XDR xdr;
265         xdrmem_create(&xdr, buf, sizeof(buf), XDR_FREE);
266         if (!req->xdr_args_free(&xdr, req->args)) {
267             fprintf(stderr, "unable to free arguments");
268         }
269     }
270
271     if (req->raw_args != NULL)
272         g_string_free(req->raw_args, TRUE);
273
274     while (req->cleanup != NULL) {
275         struct cleanup_list *c = req->cleanup;
276         req->cleanup = c->next;
277         c->func(c->arg);
278         g_free(c);
279     }
280
281     g_free(req);
282 }
283
284 static void
285 nfs_program_3(RPCRequest *req)
286 {
287     RPCConnection *connection = req->connection;
288     uint32_t xid = req->xid;
289     const char *msg_buf = req->raw_args->str + req->raw_args_header_bytes;
290     size_t msg_len = req->raw_args->len - req->raw_args_header_bytes;
291
292     union argtype {
293         nfs_fh3 nfsproc3_getattr_3_arg;
294         setattr3args nfsproc3_setattr_3_arg;
295         diropargs3 nfsproc3_lookup_3_arg;
296         access3args nfsproc3_access_3_arg;
297         nfs_fh3 nfsproc3_readlink_3_arg;
298         read3args nfsproc3_read_3_arg;
299         write3args nfsproc3_write_3_arg;
300         create3args nfsproc3_create_3_arg;
301         mkdir3args nfsproc3_mkdir_3_arg;
302         symlink3args nfsproc3_symlink_3_arg;
303         mknod3args nfsproc3_mknod_3_arg;
304         diropargs3 nfsproc3_remove_3_arg;
305         diropargs3 nfsproc3_rmdir_3_arg;
306         rename3args nfsproc3_rename_3_arg;
307         link3args nfsproc3_link_3_arg;
308         readdir3args nfsproc3_readdir_3_arg;
309         readdirplus3args nfsproc3_readdirplus_3_arg;
310         nfs_fh3 nfsproc3_fsstat_3_arg;
311         nfs_fh3 nfsproc3_fsinfo_3_arg;
312         nfs_fh3 nfsproc3_pathconf_3_arg;
313         commit3args nfsproc3_commit_3_arg;
314     };
315     char *result;
316     xdrproc_t _xdr_argument, _xdr_result;
317     char *(*local)(char *, RPCRequest *);
318
319     printf("Dispatched NFS RPC message type %d\n", req->req_proc);
320
321     switch (req->req_proc) {
322     case NFSPROC3_NULL:
323         _xdr_argument = (xdrproc_t) xdr_void;
324         _xdr_result = (xdrproc_t) xdr_void;
325         local = (char *(*)(char *, RPCRequest *)) nfsproc3_null_3_svc;
326         break;
327
328     case NFSPROC3_GETATTR:
329         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
330         _xdr_result = (xdrproc_t) xdr_getattr3res;
331         local = (char *(*)(char *, RPCRequest *)) nfsproc3_getattr_3_svc;
332         break;
333
334     case NFSPROC3_SETATTR:
335         _xdr_argument = (xdrproc_t) xdr_setattr3args;
336         _xdr_result = (xdrproc_t) xdr_wccstat3;
337         local = (char *(*)(char *, RPCRequest *)) nfsproc3_setattr_3_svc;
338         break;
339
340     case NFSPROC3_LOOKUP:
341         _xdr_argument = (xdrproc_t) xdr_diropargs3;
342         _xdr_result = (xdrproc_t) xdr_lookup3res;
343         local = (char *(*)(char *, RPCRequest *)) nfsproc3_lookup_3_svc;
344         break;
345
346     case NFSPROC3_ACCESS:
347         _xdr_argument = (xdrproc_t) xdr_access3args;
348         _xdr_result = (xdrproc_t) xdr_access3res;
349         local = (char *(*)(char *, RPCRequest *)) nfsproc3_access_3_svc;
350         break;
351
352     case NFSPROC3_READLINK:
353         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
354         _xdr_result = (xdrproc_t) xdr_readlink3res;
355         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readlink_3_svc;
356         break;
357
358     case NFSPROC3_READ:
359         _xdr_argument = (xdrproc_t) xdr_read3args;
360         _xdr_result = (xdrproc_t) xdr_read3res;
361         local = (char *(*)(char *, RPCRequest *)) nfsproc3_read_3_svc;
362         break;
363
364     case NFSPROC3_WRITE:
365         _xdr_argument = (xdrproc_t) xdr_write3args;
366         _xdr_result = (xdrproc_t) xdr_write3res;
367         local = (char *(*)(char *, RPCRequest *)) nfsproc3_write_3_svc;
368         break;
369
370     case NFSPROC3_CREATE:
371         _xdr_argument = (xdrproc_t) xdr_create3args;
372         _xdr_result = (xdrproc_t) xdr_diropres3;
373         local = (char *(*)(char *, RPCRequest *)) nfsproc3_create_3_svc;
374         break;
375
376     case NFSPROC3_MKDIR:
377         _xdr_argument = (xdrproc_t) xdr_mkdir3args;
378         _xdr_result = (xdrproc_t) xdr_diropres3;
379         local = (char *(*)(char *, RPCRequest *)) nfsproc3_mkdir_3_svc;
380         break;
381
382     case NFSPROC3_SYMLINK:
383         _xdr_argument = (xdrproc_t) xdr_symlink3args;
384         _xdr_result = (xdrproc_t) xdr_diropres3;
385         local = (char *(*)(char *, RPCRequest *)) nfsproc3_symlink_3_svc;
386         break;
387
388     case NFSPROC3_MKNOD:
389         _xdr_argument = (xdrproc_t) xdr_mknod3args;
390         _xdr_result = (xdrproc_t) xdr_diropres3;
391         local = (char *(*)(char *, RPCRequest *)) nfsproc3_mknod_3_svc;
392         break;
393
394     case NFSPROC3_REMOVE:
395         _xdr_argument = (xdrproc_t) xdr_diropargs3;
396         _xdr_result = (xdrproc_t) xdr_wccstat3;
397         local = (char *(*)(char *, RPCRequest *)) nfsproc3_remove_3_svc;
398         break;
399
400     case NFSPROC3_RMDIR:
401         _xdr_argument = (xdrproc_t) xdr_diropargs3;
402         _xdr_result = (xdrproc_t) xdr_wccstat3;
403         local = (char *(*)(char *, RPCRequest *)) nfsproc3_rmdir_3_svc;
404         break;
405
406     case NFSPROC3_RENAME:
407         _xdr_argument = (xdrproc_t) xdr_rename3args;
408         _xdr_result = (xdrproc_t) xdr_rename3res;
409         local = (char *(*)(char *, RPCRequest *)) nfsproc3_rename_3_svc;
410         break;
411
412     case NFSPROC3_LINK:
413         _xdr_argument = (xdrproc_t) xdr_link3args;
414         _xdr_result = (xdrproc_t) xdr_link3res;
415         local = (char *(*)(char *, RPCRequest *)) nfsproc3_link_3_svc;
416         break;
417
418     case NFSPROC3_READDIR:
419         _xdr_argument = (xdrproc_t) xdr_readdir3args;
420         _xdr_result = (xdrproc_t) xdr_readdir3res;
421         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readdir_3_svc;
422         break;
423
424     case NFSPROC3_READDIRPLUS:
425         _xdr_argument = (xdrproc_t) xdr_readdirplus3args;
426         _xdr_result = (xdrproc_t) xdr_readdirplus3res;
427         local = (char *(*)(char *, RPCRequest *)) nfsproc3_readdirplus_3_svc;
428         break;
429
430     case NFSPROC3_FSSTAT:
431         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
432         _xdr_result = (xdrproc_t) xdr_fsstat3res;
433         local = (char *(*)(char *, RPCRequest *)) nfsproc3_fsstat_3_svc;
434         break;
435
436     case NFSPROC3_FSINFO:
437         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
438         _xdr_result = (xdrproc_t) xdr_fsinfo3res;
439         local = (char *(*)(char *, RPCRequest *)) nfsproc3_fsinfo_3_svc;
440         break;
441
442     case NFSPROC3_PATHCONF:
443         _xdr_argument = (xdrproc_t) xdr_nfs_fh3;
444         _xdr_result = (xdrproc_t) xdr_pathconf3res;
445         local = (char *(*)(char *, RPCRequest *)) nfsproc3_pathconf_3_svc;
446         break;
447
448     case NFSPROC3_COMMIT:
449         _xdr_argument = (xdrproc_t) xdr_commit3args;
450         _xdr_result = (xdrproc_t) xdr_commit3res;
451         local = (char *(*)(char *, RPCRequest *)) nfsproc3_commit_3_svc;
452         break;
453
454     default:
455         async_rpc_send_failure(req, PROC_UNAVAIL);
456         return;
457     }
458
459     /* Decode incoming message */
460     req->xdr_args_free = _xdr_argument;
461     req->args = g_new0(union argtype, 1);
462     XDR xdr_in;
463     xdrmem_create(&xdr_in, (char *)msg_buf, msg_len, XDR_DECODE);
464     if (!_xdr_argument(&xdr_in, req->args)) {
465         async_rpc_send_failure(req, GARBAGE_ARGS);
466         fprintf(stderr, "RPC decode error!\n");
467         return;
468     }
469
470     /* Perform the call. */
471     req->xdr_result = _xdr_result;
472     result = (*local)((char *)req->args, req);
473
474     bluesky_flushd_invoke(fs);
475     bluesky_debug_dump(fs);
476
477     return;
478 }
479
480 /* Enhanced, asynchronous-friendly RPC layer.  This is a replacement for the
481  * built-in sunrpc parsing and dispatch that will allow for processing multiple
482  * requests at the same time. */
483 static GMainContext *main_context;
484 static GMainLoop *main_loop;
485
486 static async_rpc_init()
487 {
488     main_context = g_main_context_new();
489     main_loop = g_main_loop_new(main_context, FALSE);
490 }
491
492 struct rpc_call_header {
493     uint32_t xid;
494     uint32_t mtype;
495     uint32_t rpcvers;
496     uint32_t prog;
497     uint32_t vers;
498     uint32_t proc;
499 };
500
501 struct rpc_auth {
502     uint32_t flavor;
503     uint32_t len;
504 };
505
506 /* Decode an RPC message and process it.  Returns a boolean indicating whether
507  * the message could be processed; if false, an unrecoverable error occurred
508  * and the transport should be closed. */
509 static gboolean async_rpc_dispatch(RPCConnection *rpc)
510 {
511     bluesky_time_hires time_start = bluesky_now_hires();
512     int i;
513     GString *msg = rpc->msgbuf;
514     const char *buf = msg->str;
515
516     if (msg->len < sizeof(struct rpc_call_header)) {
517         fprintf(stderr, "Short RPC message: only %zd bytes!\n", msg->len);
518         return FALSE;
519     }
520
521     struct rpc_call_header *header = (struct rpc_call_header *)(msg->str);
522     uint32_t xid = ntohl(header->xid);
523
524     if (ntohl(header->mtype) != 0) {
525         /* Not an RPC call */
526         return FALSE;
527     }
528
529     if (ntohl(header->rpcvers) != 2) {
530         return FALSE;
531     }
532
533     RPCRequest *req = g_new0(RPCRequest, 1);
534     req->connection = rpc;
535     req->time_start = time_start;
536     req->xid = xid;
537
538     if (ntohl(header->prog) != NFS_PROGRAM) {
539         async_rpc_send_failure(req, PROG_UNAVAIL);
540         return TRUE;
541     } else if (ntohl(header->vers) != NFS_V3) {
542         /* FIXME: Should be PROG_MISMATCH */
543         async_rpc_send_failure(req, PROG_UNAVAIL);
544         return TRUE;
545     }
546
547     uint32_t proc = ntohl(header->proc);
548
549     /* Next, skip over authentication headers. */
550     buf += sizeof(struct rpc_call_header);
551     for (i = 0; i < 2; i++) {
552         struct rpc_auth *auth = (struct rpc_auth *)buf;
553         if (buf - msg->str + sizeof(struct rpc_auth) > msg->len)
554             return FALSE;
555
556         gsize authsize = ntohl(auth->len) + sizeof(struct rpc_auth);
557         if (authsize > MAX_RPC_MSGSIZE)
558             return FALSE;
559
560         buf += authsize;
561     }
562
563     if (buf - msg->str > msg->len)
564         return FALSE;
565
566     req->raw_args = msg;
567     req->raw_args_header_bytes = buf - msg->str;
568     req->req_proc = ntohl(header->proc);
569     rpc->msgbuf = g_string_new("");
570
571     nfs_program_3(req);
572
573     return TRUE;
574 }
575
576 /* Write the given data to the RPC socket. */
577 static void async_rpc_write(RPCConnection *rpc,
578                             const char *buf, gsize len)
579 {
580     while (len > 0) {
581         gsize written = 0;
582         switch (g_io_channel_write_chars(rpc->channel, buf, len,
583                                          &written, NULL)) {
584         case G_IO_STATUS_ERROR:
585         case G_IO_STATUS_EOF:
586         case G_IO_STATUS_AGAIN:
587             fprintf(stderr, "Error writing to socket!\n");
588             return;
589         case G_IO_STATUS_NORMAL:
590             len -= written;
591             buf += written;
592             break;
593         }
594     }
595
596     // g_io_channel_flush(rpc->channel, NULL);
597 }
598
599 static gboolean async_rpc_do_read(GIOChannel *channel,
600                                   GIOCondition condition,
601                                   gpointer data)
602 {
603     RPCConnection *rpc = (RPCConnection *)data;
604
605     gsize bytes_to_read = 0;    /* Number of bytes to attempt to read. */
606
607     /* If we have not yet read in the fragment header, do that first.  This is
608      * 4 bytes that indicates the number of bytes in the message to follow
609      * (with the high bit set if this is the last fragment making up the
610      * message). */
611     if (rpc->frag_len == 0) {
612         bytes_to_read = 4 - rpc->frag_hdr_bytes;
613     } else {
614         bytes_to_read = rpc->frag_len & 0x7fffffff;
615     }
616
617     if (bytes_to_read > MAX_RPC_MSGSIZE
618         || rpc->msgbuf->len + bytes_to_read > MAX_RPC_MSGSIZE)
619     {
620         fprintf(stderr, "Excessive fragment size for RPC: %zd bytes\n",
621                 bytes_to_read);
622         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
623         return FALSE;
624     }
625
626     gsize bytes_read = 0;
627     g_string_set_size(rpc->msgbuf, rpc->msgbuf->len + bytes_to_read);
628     char *buf = &rpc->msgbuf->str[rpc->msgbuf->len - bytes_to_read];
629     switch (g_io_channel_read_chars(rpc->channel, buf,
630                                     bytes_to_read, &bytes_read, NULL)) {
631     case G_IO_STATUS_NORMAL:
632         break;
633     case G_IO_STATUS_AGAIN:
634         return TRUE;
635     case G_IO_STATUS_EOF:
636         if (bytes_read == bytes_to_read)
637             break;
638         /* else fall through */
639     case G_IO_STATUS_ERROR:
640         fprintf(stderr, "Unexpected error or end of file on RPC stream %d!\n",
641                 g_io_channel_unix_get_fd(rpc->channel));
642         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
643         return FALSE;
644     }
645
646     g_assert(bytes_read >= 0 && bytes_read <= bytes_to_read);
647
648     g_string_set_size(rpc->msgbuf,
649                       rpc->msgbuf->len - (bytes_to_read - bytes_read));
650
651     if (rpc->frag_len == 0) {
652         /* Handle reading in the fragment header.  If we've read the complete
653          * header, store the fragment size. */
654         rpc->frag_hdr_bytes += bytes_read;
655         if (rpc->frag_hdr_bytes == 4) {
656             memcpy((char *)&rpc->frag_len,
657                    &rpc->msgbuf->str[rpc->msgbuf->len - 4], 4);
658             rpc->frag_len = ntohl(rpc->frag_len);
659             g_string_set_size(rpc->msgbuf, rpc->msgbuf->len - 4);
660             rpc->frag_hdr_bytes = 0;
661         }
662     } else {
663         /* We were reading in the fragment body. */
664         rpc->frag_len -= bytes_read;
665
666         if (rpc->frag_len = 0x80000000) {
667             /* We have a complete message since this was the last fragment and
668              * there are no more bytes in it.  Dispatch the message. */
669             if (!async_rpc_dispatch(rpc)) {
670                 fprintf(stderr, "Invalid RPC message, closing channel\n");
671                 g_io_channel_shutdown(rpc->channel, TRUE, NULL);
672                 return FALSE;
673             }
674             rpc->frag_len = 0;
675             g_string_set_size(rpc->msgbuf, 0);
676         }
677     }
678
679     return TRUE;
680 }
681
682 static gboolean async_rpc_do_accept(GIOChannel *channel,
683                                     GIOCondition condition,
684                                     gpointer data)
685 {
686     int fd = g_io_channel_unix_get_fd(channel);
687     struct sockaddr_in addr;
688     socklen_t addrlen = sizeof(addr);
689
690     g_print("Received new connection on fd %d!\n", fd);
691     int nfd = accept(fd, (struct sockaddr *)&addr, &addrlen);
692     if (nfd < 0) {
693         fprintf(stderr, "Error accepting connection: %m\n");
694         return TRUE;
695     }
696
697     RPCConnection *rpc = g_new0(RPCConnection, 1);
698     rpc->channel = g_io_channel_unix_new(nfd);
699     rpc->msgbuf = g_string_new("");
700     g_io_channel_set_encoding(rpc->channel, NULL, NULL);
701     GSource *source = g_io_create_watch(rpc->channel, G_IO_IN);
702     g_source_set_callback(source, (GSourceFunc)async_rpc_do_read,
703                           rpc, NULL);
704     g_source_attach(source, main_context);
705     g_source_unref(source);
706
707     return TRUE;
708 }
709
710 static async_rpc_register_listening(int fd)
711 {
712     GIOChannel *channel = g_io_channel_unix_new(fd);
713     g_io_channel_set_encoding(channel, NULL, NULL);
714     GSource *source = g_io_create_watch(channel, G_IO_IN);
715     g_source_set_callback(source, (GSourceFunc)async_rpc_do_accept,
716                           NULL, NULL);
717     g_source_attach(source, main_context);
718     g_source_unref(source);
719 }
720
721 static gpointer async_rpc_run(gpointer data)
722 {
723     g_print("Starting NFS main loop...\n");
724     g_main_loop_run(main_loop);
725 }
726
727 void register_rpc()
728 {
729     SVCXPRT *transp;
730
731     async_rpc_init();
732
733     /* MOUNT protocol */
734     pmap_unset (MOUNT_PROGRAM, MOUNT_V3);
735
736     transp = svcudp_create(RPC_ANYSOCK);
737     if (transp == NULL) {
738         fprintf(stderr, "%s", "cannot create udp service.");
739         exit(1);
740     }
741     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_UDP)) {
742         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, udp).");
743         exit(1);
744     }
745
746     transp = svctcp_create(RPC_ANYSOCK, 0, 0);
747     if (transp == NULL) {
748         fprintf(stderr, "%s", "cannot create tcp service.");
749         exit(1);
750     }
751     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_TCP)) {
752         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, tcp).");
753         exit(1);
754     }
755
756     /* NFS protocol (version 3) */
757     pmap_unset (NFS_PROGRAM, NFS_V3);
758
759     int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
760     if (fd < 0) {
761         fprintf(stderr, "Unable to create NFS TCP socket: %m\n");
762         exit(1);
763     }
764
765     int n = 1;
766     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n));
767
768     struct sockaddr_in addr;
769     addr.sin_family = AF_INET;
770     addr.sin_port = htons(NFS_SERVICE_PORT);
771     addr.sin_addr.s_addr = INADDR_ANY;
772     if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
773         fprintf(stderr, "Unable to bind to NFS TCP address: %m\n");
774         exit(1);
775     }
776
777     if (listen(fd, SOMAXCONN) < 0) {
778         fprintf(stderr, "Unable to listen on NFS TCP socket: %m\n");
779         exit(1);
780     }
781
782     if (!pmap_set(NFS_PROGRAM, NFS_V3, IPPROTO_TCP, NFS_SERVICE_PORT)) {
783         fprintf(stderr, "Could not register NFS RPC service!\n");
784         exit(1);
785     }
786
787     async_rpc_register_listening(fd);
788
789     g_thread_create(async_rpc_run, NULL, TRUE, NULL);
790 }