Add general statistics-gathering infrastructure.
[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         bluesky_stats_dump_all();
512         fs_dump_requested = 0;
513     }
514
515     bluesky_flushd_invoke(fs);
516     return TRUE;
517 }
518
519 static void async_rpc_task(gpointer data, gpointer user_data)
520 {
521     nfs_program_3((RPCRequest *)data);
522 }
523
524 static async_rpc_init()
525 {
526     main_context = g_main_context_new();
527     main_loop = g_main_loop_new(main_context, FALSE);
528
529     rpc_thread_pool = g_thread_pool_new(async_rpc_task, NULL,
530                                         bluesky_max_threads, FALSE, NULL);
531
532     /* Arrange to have the cache writeback code run every five seconds. */
533     GSource *source = g_timeout_source_new_seconds(5);
534     g_source_set_callback(source, async_flushd, NULL, NULL);
535     g_source_attach(source, main_context);
536     g_source_unref(source);
537
538     /* Signal USR1 is used to request a debugging dump of filesyste info */
539     struct sigaction sa;
540     sa.sa_handler = sig_handler;
541     sigemptyset(&sa.sa_mask);
542     sa.sa_flags = SA_RESTART;
543     if (sigaction(SIGUSR1, &sa, NULL) < 0) {
544         perror("sigaction");
545     }
546 }
547
548 struct rpc_call_header {
549     uint32_t xid;
550     uint32_t mtype;
551     uint32_t rpcvers;
552     uint32_t prog;
553     uint32_t vers;
554     uint32_t proc;
555 };
556
557 struct rpc_auth {
558     uint32_t flavor;
559     uint32_t len;
560 };
561
562 /* Decode an RPC message and process it.  Returns a boolean indicating whether
563  * the message could be processed; if false, an unrecoverable error occurred
564  * and the transport should be closed. */
565 static gboolean async_rpc_dispatch(RPCConnection *rpc)
566 {
567     bluesky_time_hires time_start = bluesky_now_hires();
568     int i;
569     GString *msg = rpc->msgbuf;
570     const char *buf = msg->str;
571
572     if (msg->len < sizeof(struct rpc_call_header)) {
573         fprintf(stderr, "Short RPC message: only %zd bytes!\n", msg->len);
574         return FALSE;
575     }
576
577     struct rpc_call_header *header = (struct rpc_call_header *)(msg->str);
578     uint32_t xid = ntohl(header->xid);
579
580     if (ntohl(header->mtype) != 0) {
581         /* Not an RPC call */
582         return FALSE;
583     }
584
585     if (ntohl(header->rpcvers) != 2) {
586         return FALSE;
587     }
588
589     g_atomic_int_add(&outstanding_rpcs, 1);
590
591     RPCRequest *req = g_new0(RPCRequest, 1);
592     req->connection = rpc;
593     req->time_start = time_start;
594     req->xid = xid;
595
596     if (ntohl(header->prog) != NFS_PROGRAM) {
597         async_rpc_send_failure(req, PROG_UNAVAIL);
598         return TRUE;
599     } else if (ntohl(header->vers) != NFS_V3) {
600         /* FIXME: Should be PROG_MISMATCH */
601         async_rpc_send_failure(req, PROG_UNAVAIL);
602         return TRUE;
603     }
604
605     uint32_t proc = ntohl(header->proc);
606
607     /* Next, skip over authentication headers. */
608     buf += sizeof(struct rpc_call_header);
609     for (i = 0; i < 2; i++) {
610         struct rpc_auth *auth = (struct rpc_auth *)buf;
611         if (buf - msg->str + sizeof(struct rpc_auth) > msg->len) {
612             g_atomic_int_add(&outstanding_rpcs, -1);
613             return FALSE;
614         }
615
616         gsize authsize = ntohl(auth->len) + sizeof(struct rpc_auth);
617         if (authsize > MAX_RPC_MSGSIZE) {
618             g_atomic_int_add(&outstanding_rpcs, -1);
619             return FALSE;
620         }
621
622         buf += authsize;
623     }
624
625     if (buf - msg->str > msg->len) {
626         g_atomic_int_add(&outstanding_rpcs, -1);
627         return FALSE;
628     }
629
630     req->raw_args = msg;
631     req->raw_args_header_bytes = buf - msg->str;
632     req->req_proc = ntohl(header->proc);
633     rpc->msgbuf = g_string_new("");
634
635     if (bluesky_options.sync_frontends) {
636         nfs_program_3(req);
637     } else {
638         g_thread_pool_push(rpc_thread_pool, req, NULL);
639     }
640
641     return TRUE;
642 }
643
644 /* Write the given data to the RPC socket. */
645 static void async_rpc_write(RPCConnection *rpc,
646                             const char *buf, gsize len)
647 {
648     if (rpc->udp_transport) {
649         g_string_append_len(rpc->sendbuf, buf, len);
650         return;
651     }
652
653     /* Normal TCP path */
654     while (len > 0) {
655         gsize written = 0;
656         switch (g_io_channel_write_chars(rpc->channel, buf, len,
657                                          &written, NULL)) {
658         case G_IO_STATUS_ERROR:
659         case G_IO_STATUS_EOF:
660         case G_IO_STATUS_AGAIN:
661             fprintf(stderr, "Error writing to socket!\n");
662             return;
663         case G_IO_STATUS_NORMAL:
664             len -= written;
665             buf += written;
666             break;
667         }
668     }
669
670     // g_io_channel_flush(rpc->channel, NULL);
671 }
672
673 /* Flush a completed message out to the RPC socket */
674 static void async_rpc_flush(RPCConnection *rpc)
675 {
676     if (rpc->udp_transport) {
677         sendto(g_io_channel_unix_get_fd(rpc->channel),
678                rpc->sendbuf->str, rpc->sendbuf->len, 0,
679                (struct sockaddr *)&rpc->peer, sizeof(struct sockaddr_in));
680         return;
681     } else {
682         g_io_channel_flush(rpc->channel, NULL);
683     }
684 }
685
686 static gboolean async_rpc_do_read(GIOChannel *channel,
687                                   GIOCondition condition,
688                                   gpointer data)
689 {
690     RPCConnection *rpc = (RPCConnection *)data;
691
692     gsize bytes_to_read = 0;    /* Number of bytes to attempt to read. */
693
694     /* If we have not yet read in the fragment header, do that first.  This is
695      * 4 bytes that indicates the number of bytes in the message to follow
696      * (with the high bit set if this is the last fragment making up the
697      * message). */
698     if (rpc->frag_len == 0) {
699         bytes_to_read = 4 - rpc->frag_hdr_bytes;
700     } else {
701         bytes_to_read = rpc->frag_len & 0x7fffffff;
702     }
703
704     if (bytes_to_read > MAX_RPC_MSGSIZE
705         || rpc->msgbuf->len + bytes_to_read > MAX_RPC_MSGSIZE)
706     {
707         fprintf(stderr, "Excessive fragment size for RPC: %zd bytes\n",
708                 bytes_to_read);
709         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
710         return FALSE;
711     }
712
713     gsize bytes_read = 0;
714     g_string_set_size(rpc->msgbuf, rpc->msgbuf->len + bytes_to_read);
715     char *buf = &rpc->msgbuf->str[rpc->msgbuf->len - bytes_to_read];
716     switch (g_io_channel_read_chars(rpc->channel, buf,
717                                     bytes_to_read, &bytes_read, NULL)) {
718     case G_IO_STATUS_NORMAL:
719         break;
720     case G_IO_STATUS_AGAIN:
721         return TRUE;
722     case G_IO_STATUS_EOF:
723         if (bytes_read == bytes_to_read)
724             break;
725         /* else fall through */
726     case G_IO_STATUS_ERROR:
727         fprintf(stderr, "Unexpected error or end of file on RPC stream %d!\n",
728                 g_io_channel_unix_get_fd(rpc->channel));
729         g_io_channel_shutdown(rpc->channel, TRUE, NULL);
730         /* TODO: Clean up connection object. */
731         return FALSE;
732     }
733
734     g_assert(bytes_read >= 0 && bytes_read <= bytes_to_read);
735
736     g_string_set_size(rpc->msgbuf,
737                       rpc->msgbuf->len - (bytes_to_read - bytes_read));
738
739     if (rpc->frag_len == 0) {
740         /* Handle reading in the fragment header.  If we've read the complete
741          * header, store the fragment size. */
742         rpc->frag_hdr_bytes += bytes_read;
743         if (rpc->frag_hdr_bytes == 4) {
744             memcpy((char *)&rpc->frag_len,
745                    &rpc->msgbuf->str[rpc->msgbuf->len - 4], 4);
746             rpc->frag_len = ntohl(rpc->frag_len);
747             g_string_set_size(rpc->msgbuf, rpc->msgbuf->len - 4);
748             rpc->frag_hdr_bytes = 0;
749         }
750     } else {
751         /* We were reading in the fragment body. */
752         rpc->frag_len -= bytes_read;
753
754         if (rpc->frag_len == 0x80000000) {
755             /* We have a complete message since this was the last fragment and
756              * there are no more bytes in it.  Dispatch the message. */
757             if (!async_rpc_dispatch(rpc)) {
758                 fprintf(stderr, "Invalid RPC message, closing channel\n");
759                 g_io_channel_shutdown(rpc->channel, TRUE, NULL);
760                 return FALSE;
761             }
762             rpc->frag_len = 0;
763             g_string_set_size(rpc->msgbuf, 0);
764         }
765     }
766
767     return TRUE;
768 }
769
770 static gboolean async_rpc_do_accept(GIOChannel *channel,
771                                     GIOCondition condition,
772                                     gpointer data)
773 {
774     int fd = g_io_channel_unix_get_fd(channel);
775     struct sockaddr_in addr;
776     socklen_t addrlen = sizeof(addr);
777
778     g_print("Received new connection on fd %d!\n", fd);
779     int nfd = accept(fd, (struct sockaddr *)&addr, &addrlen);
780     if (nfd < 0) {
781         fprintf(stderr, "Error accepting connection: %m\n");
782         return TRUE;
783     }
784
785     RPCConnection *rpc = g_new0(RPCConnection, 1);
786     rpc->channel = g_io_channel_unix_new(nfd);
787     rpc->msgbuf = g_string_new("");
788     g_io_channel_set_encoding(rpc->channel, NULL, NULL);
789     rpc->send_lock = g_mutex_new();
790     GSource *source = g_io_create_watch(rpc->channel, G_IO_IN);
791     g_source_set_callback(source, (GSourceFunc)async_rpc_do_read,
792                           rpc, NULL);
793     g_source_attach(source, main_context);
794     g_source_unref(source);
795
796     return TRUE;
797 }
798
799 static async_rpc_register_listening(int fd)
800 {
801     GIOChannel *channel = g_io_channel_unix_new(fd);
802     g_io_channel_set_encoding(channel, NULL, NULL);
803     GSource *source = g_io_create_watch(channel, G_IO_IN);
804     g_source_set_callback(source, (GSourceFunc)async_rpc_do_accept,
805                           NULL, NULL);
806     g_source_attach(source, main_context);
807     g_source_unref(source);
808 }
809
810 static gboolean async_rpc_do_udp(GIOChannel *channel,
811                                  GIOCondition condition,
812                                  gpointer data)
813 {
814     char buf[65536];
815
816     struct sockaddr_in src;
817     socklen_t addrlen = sizeof(struct sockaddr_in);
818     ssize_t len = recvfrom(g_io_channel_unix_get_fd(channel),
819                            buf, sizeof(buf), 0,
820                            (struct sockaddr *)&src, &addrlen);
821     if (len < 0) {
822         fprintf(stderr, "UDP read error: %m, shutting down UDP\n");
823         return FALSE;
824     }
825
826     g_assert(len < sizeof(buf));
827
828     RPCConnection *rpc = g_new0(RPCConnection, 1);
829     rpc->channel = channel;
830     rpc->msgbuf = g_string_new_len(buf, len);
831     rpc->send_lock = g_mutex_new();
832     rpc->udp_transport = TRUE;
833     memcpy(&rpc->peer, &src, sizeof(struct sockaddr_in));
834     rpc->sendbuf = g_string_new("");
835
836     /* We have a complete message since this was the last fragment and
837      * there are no more bytes in it.  Dispatch the message. */
838     async_rpc_dispatch(rpc);
839
840     return TRUE;
841 }
842
843 static async_rpc_register_listening_udp(int fd)
844 {
845     GIOChannel *channel = g_io_channel_unix_new(fd);
846     g_io_channel_set_encoding(channel, NULL, NULL);
847     GSource *source = g_io_create_watch(channel, G_IO_IN);
848     g_source_set_callback(source, (GSourceFunc)async_rpc_do_udp,
849                           NULL, NULL);
850     g_source_attach(source, main_context);
851     g_source_unref(source);
852 }
853
854 static gpointer async_rpc_run(gpointer data)
855 {
856     g_print("Starting NFS main loop...\n");
857     g_main_loop_run(main_loop);
858 }
859
860 void register_rpc()
861 {
862     SVCXPRT *transp;
863
864     async_rpc_init();
865
866     /* MOUNT protocol */
867     pmap_unset (MOUNT_PROGRAM, MOUNT_V3);
868
869     transp = svcudp_create(RPC_ANYSOCK);
870     if (transp == NULL) {
871         fprintf(stderr, "%s", "cannot create udp service.");
872         exit(1);
873     }
874     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_UDP)) {
875         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, udp).");
876         exit(1);
877     }
878
879     transp = svctcp_create(RPC_ANYSOCK, 0, 0);
880     if (transp == NULL) {
881         fprintf(stderr, "%s", "cannot create tcp service.");
882         exit(1);
883     }
884     if (!svc_register(transp, MOUNT_PROGRAM, MOUNT_V3, mount_program_3, IPPROTO_TCP)) {
885         fprintf(stderr, "%s", "unable to register (MOUNT_PROGRAM, MOUNT_V3, tcp).");
886         exit(1);
887     }
888
889     /* NFS protocol (version 3) */
890     pmap_unset (NFS_PROGRAM, NFS_V3);
891
892     int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
893     if (fd < 0) {
894         fprintf(stderr, "Unable to create NFS TCP socket: %m\n");
895         exit(1);
896     }
897
898     int n = 1;
899     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n));
900
901     struct sockaddr_in addr;
902     addr.sin_family = AF_INET;
903     addr.sin_port = htons(NFS_SERVICE_PORT);
904     addr.sin_addr.s_addr = INADDR_ANY;
905     if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
906         fprintf(stderr, "Unable to bind to NFS TCP address: %m\n");
907         exit(1);
908     }
909
910     if (listen(fd, SOMAXCONN) < 0) {
911         fprintf(stderr, "Unable to listen on NFS TCP socket: %m\n");
912         exit(1);
913     }
914
915     if (!pmap_set(NFS_PROGRAM, NFS_V3, IPPROTO_TCP, NFS_SERVICE_PORT)) {
916         fprintf(stderr, "Could not register NFS RPC service!\n");
917         exit(1);
918     }
919
920     async_rpc_register_listening(fd);
921
922     /* Minimal UDP NFSv3 support */
923     fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
924     if (fd < 0) {
925         fprintf(stderr, "Unable to create NFS UDP socket: %m\n");
926         exit(1);
927     }
928
929     addr.sin_family = AF_INET;
930     addr.sin_port = htons(NFS_SERVICE_PORT);
931     addr.sin_addr.s_addr = INADDR_ANY;
932     if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
933         fprintf(stderr, "Unable to bind to NFS UDP address: %m\n");
934         exit(1);
935     }
936
937     if (!pmap_set(NFS_PROGRAM, NFS_V3, IPPROTO_UDP, NFS_SERVICE_PORT)) {
938         fprintf(stderr, "Could not register NFS UDP RPC service!\n");
939         exit(1);
940     }
941
942     async_rpc_register_listening_udp(fd);
943
944     g_thread_create(async_rpc_run, NULL, TRUE, NULL);
945 }