nexus: Flesh out VPN support a bit more, cleanup service handling

Signed-off-by: San Mehat <san@google.com>
diff --git a/nexus/OpenVpnController.cpp b/nexus/OpenVpnController.cpp
index eff653a..d326ad5 100644
--- a/nexus/OpenVpnController.cpp
+++ b/nexus/OpenVpnController.cpp
@@ -14,17 +14,27 @@
  * limitations under the License.
  */
 #include <errno.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
 
 #define LOG_TAG "OpenVpnController"
 #include <cutils/log.h>
 #include <cutils/properties.h>
 
+#include <sysutils/ServiceManager.h>
+
 #include "OpenVpnController.h"
 
 #define DAEMON_PROP_NAME "vpn.openvpn.status"
+#define DAEMON_CONFIG_FILE "/data/misc/openvpn/openvpn.conf"
 
 OpenVpnController::OpenVpnController() :
                    VpnController() {
+    mServiceManager = new ServiceManager();
+}
+
+OpenVpnController::~OpenVpnController() {
+    delete mServiceManager;
 }
 
 int OpenVpnController::start() {
@@ -37,68 +47,32 @@
 
 int OpenVpnController::enable() {
 
-    // Validate configuration file
-   
-    // Validate key file
-
-    if (startServiceDaemon())
-        return -1;
-
-    errno = -ENOSYS;
-    return -1;
-}
-
-int OpenVpnController::startServiceDaemon() {
-    char status[PROPERTY_VALUE_MAX];
-    int count = 100;
-
-    property_set("ctl.start", "openvpn");
-    sched_yield();
-
-    while (count-- > 0) {
-        if (property_get(DAEMON_PROP_NAME, status, NULL)) {
-            if (strcmp(status, "ok") == 0)
-                return 0;
-            else if (strcmp(DAEMON_PROP_NAME, "failed") == 0)
-                return -1;
-        }
-        usleep(200000);
-    }
-    property_set(DAEMON_PROP_NAME, "timeout");
-    return -1;
-}
-
-int OpenVpnController::stopServiceDaemon() {
-    char status[PROPERTY_VALUE_MAX] = {'\0'};
-    int count = 50;
-
-    if (property_get(DAEMON_PROP_NAME, status, NULL) &&
-        !strcmp(status, "stopped")) {
-        LOGD("Service already stopped");
-        return 0;
-    }
-
-    property_set("ctl.stop", "openvpn");
-    sched_yield();
-
-    while (count-- > 0) {
-        if (property_get(DAEMON_PROP_NAME, status, NULL)) {
-            if (!strcmp(status, "stopped"))
-                break;
-        }
-        usleep(100000);
-    }
-
-    if (!count) {
-        LOGD("Timed out waiting for openvpn to stop");
-        errno = ETIMEDOUT;
+    if (validateConfig()) {
+        LOGE("Error validating configuration file");
         return -1;
     }
 
+    if (mServiceManager->start("openvpn"))
+        return -1;
+
     return 0;
 }
 
 int OpenVpnController::disable() {
-    errno = -ENOSYS;
-    return -1;
+
+    if (mServiceManager->stop("openvpn"))
+        return -1;
+    return 0;
+}
+
+int OpenVpnController::validateConfig() {
+    unlink(DAEMON_CONFIG_FILE);
+
+    FILE *fp = fopen(DAEMON_CONFIG_FILE, "w");
+    if (!fp)
+        return -1;
+
+    fprintf(fp, "remote %s 1194\n", inet_ntoa(getVpnGateway()));
+    fclose(fp);
+    return 0;
 }