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