Charon logs to a file in the App's data directory
[strongswan.git] / src / frontends / android / jni / libandroidbridge / charonservice.c
1 /*
2 * Copyright (C) 2012 Giuliano Grassi
3 * Copyright (C) 2012 Ralf Sager
4 * Copyright (C) 2012 Tobias Brunner
5 * Hochschule fuer Technik Rapperswil
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 */
17
18 #include <signal.h>
19 #include <string.h>
20 #include <sys/utsname.h>
21 #include <android/log.h>
22 #include <errno.h>
23
24 #include "charonservice.h"
25 #include "android_jni.h"
26 #include "backend/android_attr.h"
27 #include "backend/android_creds.h"
28 #include "backend/android_service.h"
29 #include "kernel/android_ipsec.h"
30 #include "kernel/android_net.h"
31
32 #include <daemon.h>
33 #include <hydra.h>
34 #include <ipsec.h>
35 #include <library.h>
36 #include <threading/thread.h>
37
38 #define ANDROID_DEBUG_LEVEL 1
39 #define ANDROID_RETRASNMIT_TRIES 3
40 #define ANDROID_RETRANSMIT_TIMEOUT 3.0
41 #define ANDROID_RETRANSMIT_BASE 1.4
42
43 typedef struct private_charonservice_t private_charonservice_t;
44
45 /**
46 * private data of charonservice
47 */
48 struct private_charonservice_t {
49
50 /**
51 * public interface
52 */
53 charonservice_t public;
54
55 /**
56 * android_attr instance
57 */
58 android_attr_t *attr;
59
60 /**
61 * android_creds instance
62 */
63 android_creds_t *creds;
64
65 /**
66 * android_service instance
67 */
68 android_service_t *service;
69
70 /**
71 * VpnService builder (accessed via JNI)
72 */
73 vpnservice_builder_t *builder;
74
75 /**
76 * CharonVpnService reference
77 */
78 jobject vpn_service;
79 };
80
81 /**
82 * Single instance of charonservice_t.
83 */
84 charonservice_t *charonservice;
85
86 /**
87 * hook in library for debugging messages
88 */
89 extern void (*dbg)(debug_t group, level_t level, char *fmt, ...);
90
91 /**
92 * Logging hook for library logs, using android specific logging
93 */
94 static void dbg_android(debug_t group, level_t level, char *fmt, ...)
95 {
96 va_list args;
97
98 if (level <= ANDROID_DEBUG_LEVEL)
99 {
100 char sgroup[16], buffer[8192];
101 char *current = buffer, *next;
102
103 snprintf(sgroup, sizeof(sgroup), "%N", debug_names, group);
104 va_start(args, fmt);
105 vsnprintf(buffer, sizeof(buffer), fmt, args);
106 va_end(args);
107 while (current)
108 { /* log each line separately */
109 next = strchr(current, '\n');
110 if (next)
111 {
112 *(next++) = '\0';
113 }
114 __android_log_print(ANDROID_LOG_INFO, "charon", "00[%s] %s\n",
115 sgroup, current);
116 current = next;
117 }
118 }
119 }
120
121 /**
122 * Initialize file logger
123 */
124 static void initialize_logger(char *logfile)
125 {
126 file_logger_t *file_logger;
127 debug_t group;
128 FILE *file;
129
130 /* truncate an existing file */
131 file = fopen(logfile, "w");
132 if (!file)
133 {
134 DBG1(DBG_DMN, "opening file %s for logging failed: %s",
135 logfile, strerror(errno));
136 return;
137 }
138 /* flush each line */
139 setlinebuf(file);
140
141 file_logger = file_logger_create(file, "%b %e %T", FALSE);
142 for (group = 0; group < DBG_MAX; group++)
143 {
144 file_logger->set_level(file_logger, group, ANDROID_DEBUG_LEVEL);
145 }
146 charon->file_loggers->insert_last(charon->file_loggers, file_logger);
147 charon->bus->add_logger(charon->bus, &file_logger->logger);
148 }
149
150 METHOD(charonservice_t, update_status, bool,
151 private_charonservice_t *this, android_vpn_state_t code)
152 {
153 JNIEnv *env;
154 jmethodID method_id;
155 bool success = FALSE;
156
157 androidjni_attach_thread(&env);
158
159 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
160 "updateStatus", "(I)V");
161 if (!method_id)
162 {
163 goto failed;
164 }
165 (*env)->CallVoidMethod(env, this->vpn_service, method_id, (jint)code);
166 success = !androidjni_exception_occurred(env);
167
168 failed:
169 androidjni_exception_occurred(env);
170 androidjni_detach_thread();
171 return success;
172 }
173
174 METHOD(charonservice_t, bypass_socket, bool,
175 private_charonservice_t *this, int fd, int family)
176 {
177 JNIEnv *env;
178 jmethodID method_id;
179
180 androidjni_attach_thread(&env);
181
182 method_id = (*env)->GetMethodID(env, android_charonvpnservice_class,
183 "protect", "(I)Z");
184 if (!method_id)
185 {
186 goto failed;
187 }
188 if (!(*env)->CallBooleanMethod(env, this->vpn_service, method_id, fd))
189 {
190 DBG1(DBG_CFG, "VpnService.protect() failed");
191 goto failed;
192 }
193 androidjni_detach_thread();
194 return TRUE;
195
196 failed:
197 androidjni_exception_occurred(env);
198 androidjni_detach_thread();
199 return FALSE;
200 }
201
202 METHOD(charonservice_t, get_trusted_certificates, linked_list_t*,
203 private_charonservice_t *this)
204 {
205 JNIEnv *env;
206 jmethodID method_id;
207 jobjectArray jcerts;
208 linked_list_t *list;
209 jsize i;
210
211 androidjni_attach_thread(&env);
212
213 method_id = (*env)->GetMethodID(env,
214 android_charonvpnservice_class,
215 "getTrustedCertificates", "(Ljava/lang/String;)[[B");
216 if (!method_id)
217 {
218 goto failed;
219 }
220 jcerts = (*env)->CallObjectMethod(env, this->vpn_service, method_id, NULL);
221 if (!jcerts)
222 {
223 goto failed;
224 }
225 list = linked_list_create();
226 for (i = 0; i < (*env)->GetArrayLength(env, jcerts); ++i)
227 {
228 chunk_t *ca_cert;
229 jbyteArray jcert;
230
231 ca_cert = malloc_thing(chunk_t);
232 list->insert_last(list, ca_cert);
233
234 jcert = (*env)->GetObjectArrayElement(env, jcerts, i);
235 *ca_cert = chunk_alloc((*env)->GetArrayLength(env, jcert));
236 (*env)->GetByteArrayRegion(env, jcert, 0, ca_cert->len, ca_cert->ptr);
237 (*env)->DeleteLocalRef(env, jcert);
238 }
239 (*env)->DeleteLocalRef(env, jcerts);
240 androidjni_detach_thread();
241 return list;
242
243 failed:
244 androidjni_exception_occurred(env);
245 androidjni_detach_thread();
246 return NULL;
247 }
248
249 METHOD(charonservice_t, get_vpnservice_builder, vpnservice_builder_t*,
250 private_charonservice_t *this)
251 {
252 return this->builder;
253 }
254
255 /**
256 * Initiate a new connection
257 *
258 * @param local local ip address (gets owned)
259 * @param gateway gateway address (gets owned)
260 * @param username username (gets owned)
261 * @param password password (gets owned)
262 */
263 static void initiate(char *local, char *gateway, char *username, char *password)
264 {
265 private_charonservice_t *this = (private_charonservice_t*)charonservice;
266
267 this->creds->clear(this->creds);
268 this->creds->add_username_password(this->creds, username, password);
269 memwipe(password, strlen(password));
270 free(password);
271
272 DESTROY_IF(this->service);
273 this->service = android_service_create(local, gateway, username);
274 }
275
276 /**
277 * Initialize/deinitialize Android backend
278 */
279 static bool charonservice_register(void *plugin, plugin_feature_t *feature,
280 bool reg, void *data)
281 {
282 private_charonservice_t *this = (private_charonservice_t*)charonservice;
283 if (reg)
284 {
285 lib->credmgr->add_set(lib->credmgr, &this->creds->set);
286 hydra->attributes->add_handler(hydra->attributes,
287 &this->attr->handler);
288 }
289 else
290 {
291 lib->credmgr->remove_set(lib->credmgr, &this->creds->set);
292 hydra->attributes->remove_handler(hydra->attributes,
293 &this->attr->handler);
294 if (this->service)
295 {
296 this->service->destroy(this->service);
297 this->service = NULL;
298 }
299 }
300 return TRUE;
301 }
302
303 /**
304 * Initialize the charonservice object
305 */
306 static void charonservice_init(JNIEnv *env, jobject service, jobject builder)
307 {
308 private_charonservice_t *this;
309 static plugin_feature_t features[] = {
310 PLUGIN_CALLBACK(kernel_net_register, kernel_android_net_create),
311 PLUGIN_PROVIDE(CUSTOM, "kernel-net"),
312 PLUGIN_CALLBACK(kernel_ipsec_register, kernel_android_ipsec_create),
313 PLUGIN_PROVIDE(CUSTOM, "kernel-ipsec"),
314 PLUGIN_CALLBACK((plugin_feature_callback_t)charonservice_register, NULL),
315 PLUGIN_PROVIDE(CUSTOM, "Android backend"),
316 PLUGIN_DEPENDS(CUSTOM, "libcharon"),
317 };
318
319 INIT(this,
320 .public = {
321 .update_status = _update_status,
322 .bypass_socket = _bypass_socket,
323 .get_trusted_certificates = _get_trusted_certificates,
324 .get_vpnservice_builder = _get_vpnservice_builder,
325 },
326 .attr = android_attr_create(),
327 .creds = android_creds_create(),
328 .builder = vpnservice_builder_create(builder),
329 .vpn_service = (*env)->NewGlobalRef(env, service),
330 );
331 charonservice = &this->public;
332
333 lib->plugins->add_static_features(lib->plugins, "androidbridge", features,
334 countof(features), TRUE);
335
336 lib->settings->set_int(lib->settings,
337 "charon.plugins.android_log.loglevel", ANDROID_DEBUG_LEVEL);
338 lib->settings->set_int(lib->settings,
339 "charon.retransmit_tries", ANDROID_RETRASNMIT_TRIES);
340 lib->settings->set_double(lib->settings,
341 "charon.retransmit_timeout", ANDROID_RETRANSMIT_TIMEOUT);
342 lib->settings->set_double(lib->settings,
343 "charon.retransmit_base", ANDROID_RETRANSMIT_BASE);
344 lib->settings->set_bool(lib->settings,
345 "charon.close_ike_on_child_failure", TRUE);
346 /* setting the source address breaks the VpnService.protect() function which
347 * uses SO_BINDTODEVICE internally. the addresses provided to the kernel as
348 * auxiliary data have precedence over this option causing a routing loop if
349 * the gateway is contained in the VPN routes. alternatively, providing an
350 * explicit device (in addition or instead of the source address) in the
351 * auxiliary data would also work, but we currently don't have that
352 * information */
353 lib->settings->set_bool(lib->settings,
354 "charon.plugins.socket-default.set_source", FALSE);
355 }
356
357 /**
358 * Deinitialize the charonservice object
359 */
360 static void charonservice_deinit(JNIEnv *env)
361 {
362 private_charonservice_t *this = (private_charonservice_t*)charonservice;
363
364 this->builder->destroy(this->builder);
365 this->creds->destroy(this->creds);
366 this->attr->destroy(this->attr);
367 (*env)->DeleteGlobalRef(env, this->vpn_service);
368 free(this);
369 charonservice = NULL;
370 }
371
372 /**
373 * Handle SIGSEGV/SIGILL signals raised by threads
374 */
375 static void segv_handler(int signal)
376 {
377 dbg_android(DBG_DMN, 1, "thread %u received %d", thread_current_id(),
378 signal);
379 exit(1);
380 }
381
382 /**
383 * Initialize charon and the libraries via JNI
384 */
385 JNI_METHOD(CharonVpnService, initializeCharon, void,
386 jobject builder, jstring jlogfile)
387 {
388 struct sigaction action;
389 struct utsname utsname;
390 char *logfile;
391
392 /* logging for library during initialization, as we have no bus yet */
393 dbg = dbg_android;
394
395 /* initialize library */
396 if (!library_init(NULL))
397 {
398 library_deinit();
399 return;
400 }
401
402 if (!libhydra_init("charon"))
403 {
404 libhydra_deinit();
405 library_deinit();
406 return;
407 }
408
409 if (!libipsec_init())
410 {
411 libipsec_deinit();
412 libhydra_deinit();
413 library_deinit();
414 return;
415 }
416
417 if (!libcharon_init("charon"))
418 {
419 libcharon_deinit();
420 libipsec_deinit();
421 libhydra_deinit();
422 library_deinit();
423 return;
424 }
425
426 logfile = androidjni_convert_jstring(env, jlogfile);
427 initialize_logger(logfile);
428 free(logfile);
429
430 charonservice_init(env, this, builder);
431
432 if (uname(&utsname) != 0)
433 {
434 memset(&utsname, 0, sizeof(utsname));
435 }
436 DBG1(DBG_DMN, "Starting IKE charon daemon (strongSwan "VERSION", %s %s, %s)",
437 utsname.sysname, utsname.release, utsname.machine);
438
439 if (!charon->initialize(charon, PLUGINS))
440 {
441 libcharon_deinit();
442 charonservice_deinit(env);
443 libipsec_deinit();
444 libhydra_deinit();
445 library_deinit();
446 return;
447 }
448
449 /* add handler for SEGV and ILL etc. */
450 action.sa_handler = segv_handler;
451 action.sa_flags = 0;
452 sigemptyset(&action.sa_mask);
453 sigaction(SIGSEGV, &action, NULL);
454 sigaction(SIGILL, &action, NULL);
455 sigaction(SIGBUS, &action, NULL);
456 action.sa_handler = SIG_IGN;
457 sigaction(SIGPIPE, &action, NULL);
458
459 /* start daemon (i.e. the threads in the thread-pool) */
460 charon->start(charon);
461 }
462
463 /**
464 * Deinitialize charon and all libraries
465 */
466 JNI_METHOD(CharonVpnService, deinitializeCharon, void)
467 {
468 /* deinitialize charon before we destroy our own objects */
469 libcharon_deinit();
470 charonservice_deinit(env);
471 libipsec_deinit();
472 libhydra_deinit();
473 library_deinit();
474 }
475
476 /**
477 * Initiate SA
478 */
479 JNI_METHOD(CharonVpnService, initiate, void,
480 jstring jlocal_address, jstring jgateway, jstring jusername,
481 jstring jpassword)
482 {
483 char *local_address, *gateway, *username, *password;
484
485 local_address = androidjni_convert_jstring(env, jlocal_address);
486 gateway = androidjni_convert_jstring(env, jgateway);
487 username = androidjni_convert_jstring(env, jusername);
488 password = androidjni_convert_jstring(env, jpassword);
489
490 initiate(local_address, gateway, username, password);
491 }