Putting out of test mode.
[vsys-wrappers.git] / fuse / reroutemount.c
1 #include <assert.h>
2 #include <errno.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <sys/socket.h>
6 #include <sys/un.h>
7 #include "fdpass.h"
8
9 char *socket_name = "/vsys/fd_fusemount.control";
10
11 unsigned int arg_length = 128;
12
13 void send_argument(int control_channel_fd, const char *source) {
14     int sent;
15     sent=send(control_channel_fd, source, arg_length, 0);
16     if (sent<arg_length) {
17         printf("Error receiving arguments over the control buffer\n");
18         exit(1);
19     }
20 }
21
22 int connect_socket() {
23   int fd = socket( AF_UNIX, SOCK_STREAM, 0 );
24   struct sockaddr_un addr;
25   addr.sun_family = AF_UNIX;
26   strcpy( addr.sun_path, socket_name );
27   int len = strlen(socket_name) + sizeof(addr.sun_family);
28   printf("Connecting to %s\n", socket_name);
29   assert( connect( fd, (struct sockaddr *) &addr, len ) == 0 );
30   return fd;
31 }
32
33 int get_magic_fd (char *data) {
34     char *ptr;
35     int fd;
36
37     data[arg_length-1]='\0';
38     ptr = strstr(data,"fd=");
39     if (!ptr)
40         return -1;
41
42     // Found two fd= expressions
43     if (strstr(ptr+3,"fd="))
44         return -1;
45
46     if (*(ptr+3)!='\0') {
47         sscanf(ptr+3,"%d",&fd);
48         return fd;
49     }
50     else
51         return -1;
52 }
53
54 int mount(const char *source, const char *target, const char *filesystemtype,
55         unsigned long mountflags, const void *data) {
56   int fd = connect_socket();
57   int old_fuse_fd, new_fuse_fd;
58   int dupfd;
59
60   char buf[1024];
61
62   send_argument(fd, source);
63   send_argument(fd, target );
64   send_argument(fd, filesystemtype );
65   send_argument(fd, data );
66
67   old_fuse_fd = get_magic_fd (data);
68
69
70   if (old_fuse_fd == -1) {
71       printf ("Reroutemount: Could not identify FUSE fd: %d\n", old_fuse_fd);
72       exit(1);
73   }
74
75   send_fd(fd, old_fuse_fd);
76   new_fuse_fd=receive_fd(fd);
77
78   if (new_fuse_fd == -1) {
79       printf ("Reroutemount: Fusemount returned bad fd: %d\n", new_fuse_fd);
80       exit(1);
81   }
82
83   if( (dupfd=dup2(new_fuse_fd, old_fuse_fd )) != old_fuse_fd ) {
84       printf ("Could not duplicate returned file descriptor: %d\n",dupfd);
85       exit(1);
86   }
87
88   close(fd);
89   return 0;
90
91 }