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