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