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