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