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