1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * main.c - main function
17  */
18 
19 #include <arpa/inet.h>
20 #include <errno.h>
21 #include <netinet/in.h>
22 #include <stdbool.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/personality.h>
27 #include <sys/utsname.h>
28 #include <unistd.h>
29 
30 #include "clatd.h"
31 #include "common.h"
32 #include "config.h"
33 #include "logging.h"
34 
35 #define DEVICEPREFIX "v4-"
36 
37 /* function: stop_loop
38  * signal handler: stop the event loop
39  */
stop_loop()40 static void stop_loop() { running = 0; };
41 
42 /* function: print_help
43  * in case the user is running this on the command line
44  */
print_help()45 void print_help() {
46   printf("android-clat arguments:\n");
47   printf("-i [uplink interface]\n");
48   printf("-p [plat prefix]\n");
49   printf("-4 [IPv4 address]\n");
50   printf("-6 [IPv6 address]\n");
51   printf("-t [tun file descriptor number]\n");
52   printf("-r [read socket descriptor number]\n");
53   printf("-w [write socket descriptor number]\n");
54 }
55 
56 /* function: main
57  * allocate and setup the tun device, then run the event loop
58  */
main(int argc,char ** argv)59 int main(int argc, char **argv) {
60   struct tun_data tunnel;
61   int opt;
62   char *uplink_interface = NULL, *plat_prefix = NULL;
63   char *v4_addr = NULL, *v6_addr = NULL, *tunfd_str = NULL, *read_sock_str = NULL,
64        *write_sock_str = NULL;
65   unsigned len;
66 
67   while ((opt = getopt(argc, argv, "i:p:4:6:t:r:w:h")) != -1) {
68     switch (opt) {
69       case 'i':
70         uplink_interface = optarg;
71         break;
72       case 'p':
73         plat_prefix = optarg;
74         break;
75       case '4':
76         v4_addr = optarg;
77         break;
78       case '6':
79         v6_addr = optarg;
80         break;
81       case 't':
82         tunfd_str = optarg;
83         break;
84       case 'r':
85         read_sock_str = optarg;
86         break;
87       case 'w':
88         write_sock_str = optarg;
89         break;
90       case 'h':
91         print_help();
92         exit(0);
93       default:
94         logmsg(ANDROID_LOG_FATAL, "Unknown option -%c. Exiting.", (char)optopt);
95         exit(1);
96     }
97   }
98 
99   if (uplink_interface == NULL) {
100     logmsg(ANDROID_LOG_FATAL, "clatd called without an interface");
101     exit(1);
102   }
103 
104   if (tunfd_str != NULL && !parse_int(tunfd_str, &tunnel.fd4)) {
105     logmsg(ANDROID_LOG_FATAL, "invalid tunfd %s", tunfd_str);
106     exit(1);
107   }
108   if (!tunnel.fd4) {
109     logmsg(ANDROID_LOG_FATAL, "no tunfd specified on commandline.");
110     exit(1);
111   }
112 
113   if (read_sock_str != NULL && !parse_int(read_sock_str, &tunnel.read_fd6)) {
114     logmsg(ANDROID_LOG_FATAL, "invalid read socket %s", read_sock_str);
115     exit(1);
116   }
117   if (!tunnel.read_fd6) {
118     logmsg(ANDROID_LOG_FATAL, "no read_fd6 specified on commandline.");
119     exit(1);
120   }
121 
122   if (write_sock_str != NULL && !parse_int(write_sock_str, &tunnel.write_fd6)) {
123     logmsg(ANDROID_LOG_FATAL, "invalid write socket %s", write_sock_str);
124     exit(1);
125   }
126   if (!tunnel.write_fd6) {
127     logmsg(ANDROID_LOG_FATAL, "no write_fd6 specified on commandline.");
128     exit(1);
129   }
130 
131   len = snprintf(tunnel.device4, sizeof(tunnel.device4), "%s%s", DEVICEPREFIX, uplink_interface);
132   if (len >= sizeof(tunnel.device4)) {
133     logmsg(ANDROID_LOG_FATAL, "interface name too long '%s'", tunnel.device4);
134     exit(1);
135   }
136 
137   Global_Clatd_Config.native_ipv6_interface = uplink_interface;
138   if (!plat_prefix || inet_pton(AF_INET6, plat_prefix, &Global_Clatd_Config.plat_subnet) <= 0) {
139     logmsg(ANDROID_LOG_FATAL, "invalid IPv6 address specified for plat prefix: %s", plat_prefix);
140     exit(1);
141   }
142 
143   if (!v4_addr || !inet_pton(AF_INET, v4_addr, &Global_Clatd_Config.ipv4_local_subnet.s_addr)) {
144     logmsg(ANDROID_LOG_FATAL, "Invalid IPv4 address %s", v4_addr);
145     exit(1);
146   }
147 
148   if (!v6_addr || !inet_pton(AF_INET6, v6_addr, &Global_Clatd_Config.ipv6_local_subnet)) {
149     logmsg(ANDROID_LOG_FATAL, "Invalid source address %s", v6_addr);
150     exit(1);
151   }
152 
153   logmsg(ANDROID_LOG_INFO, "Starting clat version %s on %s plat=%s v4=%s v6=%s", CLATD_VERSION,
154          uplink_interface, plat_prefix ? plat_prefix : "(none)", v4_addr ? v4_addr : "(none)",
155          v6_addr ? v6_addr : "(none)");
156 
157   {
158     // Compile time detection of 32 vs 64-bit build. (note: C does not have 'constexpr')
159     // Avoid use of preprocessor macros to get compile time syntax checking even on 64-bit.
160     const int user_bits = sizeof(void*) * 8;
161     const bool user32 = (user_bits == 32);
162 
163     // Note that on 64-bit all this personality related code simply compile optimizes out.
164     // 32-bit: fetch current personality (see 'man personality': 0xFFFFFFFF means retrieve only)
165     // On Linux fetching personality cannot fail.
166     const int prev_personality = user32 ? personality(0xFFFFFFFFuL) : PER_LINUX;
167     // 32-bit: attempt to get rid of kernel spoofing of 'uts.machine' architecture,
168     // In theory this cannot fail, as PER_LINUX should always be supported.
169     if (user32) (void)personality((prev_personality & ~PER_MASK) | PER_LINUX);
170     // 64-bit: this will compile time evaluate to false.
171     const bool was_linux32 = (prev_personality & PER_MASK) == PER_LINUX32;
172 
173     struct utsname uts = {};
174     if (uname(&uts)) exit(1); // only possible error is EFAULT, but 'uts' is on stack
175 
176     // sysname is likely 'Linux', release is 'kver', machine is kernel's *true* architecture
177     logmsg(ANDROID_LOG_INFO, "%d-bit userspace on %s kernel %s for %s%s.", user_bits,
178            uts.sysname, uts.release, uts.machine, was_linux32 ? " (was spoofed)" : "");
179 
180     // 32-bit: try to return to the 'default' personality
181     // In theory this cannot fail, because it was already previously in use.
182     if (user32) (void)personality(prev_personality);
183   }
184 
185   // Loop until someone sends us a signal or brings down the tun interface.
186   if (signal(SIGTERM, stop_loop) == SIG_ERR) {
187     logmsg(ANDROID_LOG_FATAL, "sigterm handler failed: %s", strerror(errno));
188     exit(1);
189   }
190 
191   event_loop(&tunnel);
192 
193   logmsg(ANDROID_LOG_INFO, "Shutting down clat on %s", uplink_interface);
194 
195   if (running) {
196     logmsg(ANDROID_LOG_INFO, "Clatd on %s waiting for SIGTERM", uplink_interface);
197     // let's give higher level java code 15 seconds to kill us,
198     // but eventually terminate anyway, in case system server forgets about us...
199     // sleep() should be interrupted by SIGTERM, the handler should clear running
200     sleep(15);
201     logmsg(ANDROID_LOG_INFO, "Clatd on %s %s SIGTERM", uplink_interface,
202            running ? "timed out waiting for" : "received");
203   } else {
204     logmsg(ANDROID_LOG_INFO, "Clatd on %s already received SIGTERM", uplink_interface);
205   }
206   return 0;
207 }
208