vold2: Wire up more of the mount function

Signed-off-by: San Mehat <san@android.com>
diff --git a/Android.mk b/Android.mk
index 07401e2..dda81ed 100644
--- a/Android.mk
+++ b/Android.mk
@@ -14,7 +14,8 @@
                   NetlinkHandler.cpp                   \
                   BlockDevice.cpp                      \
                   Volume.cpp                           \
-                  DirectVolume.cpp
+                  DirectVolume.cpp                     \
+                  logwrapper.c
 
 LOCAL_MODULE:= vold
 
diff --git a/CommandListener.cpp b/CommandListener.cpp
index f395818..a7bc807 100644
--- a/CommandListener.cpp
+++ b/CommandListener.cpp
@@ -53,9 +53,13 @@
 
 int CommandListener::MountVolumeCmd::runCommand(SocketClient *cli,
                                                       int argc, char **argv) {
-    VolumeManager *nm = VolumeManager::Instance();
-    errno = ENOSYS;
-    cli->sendMsg(ErrorCode::OperationFailed, "Failed to mount volume", true);
+    /* Synchronously mount a volume */
+    if (VolumeManager::Instance()->mountVolume(argv[1])) {
+        cli->sendMsg(ErrorCode::OperationFailed, "Failed to mount volume.", true);
+    } else {
+        cli->sendMsg(ErrorCode::CommandOkay, "Volume mounted.", false);
+    }
+
     return 0;
 }
 
@@ -65,9 +69,13 @@
 
 int CommandListener::UnmountVolumeCmd::runCommand(SocketClient *cli,
                                                       int argc, char **argv) {
-    VolumeManager *nm = VolumeManager::Instance();
-    errno = ENOSYS;
-    cli->sendMsg(ErrorCode::OperationFailed, "Failed to unmount volume", true);
+    /* Synchronously unmount a volume */
+    if (VolumeManager::Instance()->mountVolume(argv[1])) {
+        cli->sendMsg(ErrorCode::OperationFailed, "Failed to unmount volume.", true);
+    } else {
+        cli->sendMsg(ErrorCode::CommandOkay, "Volume unmounted.", false);
+    }
+
     return 0;
 }
 
diff --git a/DirectVolume.cpp b/DirectVolume.cpp
index 0817624..515a33a 100644
--- a/DirectVolume.cpp
+++ b/DirectVolume.cpp
@@ -119,3 +119,8 @@
 
 void DirectVolume::handlePartitionRemoved(const char *devpath, NetlinkEvent *evt) {
 }
+
+int DirectVolume::prepareToMount(int *major, int *minor) {
+    errno = ENOSYS;
+    return -1;
+}
diff --git a/DirectVolume.h b/DirectVolume.h
index b58d867..3dbe76c 100644
--- a/DirectVolume.h
+++ b/DirectVolume.h
@@ -38,12 +38,15 @@
     int addPath(const char *path);
 
     int handleBlockEvent(NetlinkEvent *evt);
+protected:
+    int prepareToMount(int *major, int *minor);
 
 private:
     void handleDiskAdded(const char *devpath, NetlinkEvent *evt);
     void handleDiskRemoved(const char *devpath, NetlinkEvent *evt);
     void handlePartitionAdded(const char *devpath, NetlinkEvent *evt);
     void handlePartitionRemoved(const char *devpath, NetlinkEvent *evt);
+
 };
 
 typedef android::List<DirectVolume *> DirectVolumeCollection;
diff --git a/Volume.cpp b/Volume.cpp
index 52d02cf..75767e9 100644
--- a/Volume.cpp
+++ b/Volume.cpp
@@ -14,9 +14,16 @@
  * limitations under the License.
  */
 
-#include <stdio.h>
-#include <errno.h>
+#include <stdlib.h>
 #include <string.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/mman.h>
 
 #define LOG_TAG "Vold"
 
@@ -24,6 +31,10 @@
 
 #include "Volume.h"
 
+extern "C" int logwrap(int argc, const char **argv, int background);
+
+static char FSCK_MSDOS_PATH[] = "/system/bin/fsck_msdos";
+
 Volume::Volume(const char *label, const char *mount_point) {
     mLabel = strdup(label);
     mMountpoint = strdup(mount_point);
@@ -44,3 +55,87 @@
     LOGD("Volume %s state changing %d -> %d", mLabel, mState, state);
     mState = state;
 }
+
+int Volume::mount() {
+    char nodepath[255];
+    int major = -1, minor = -1;
+
+    if (prepareToMount(&major, &minor)) {
+        LOGE("Volume failed to prepare: %s", strerror(errno));
+        return -1;
+    }
+
+    /* Create device nodes */
+    mode_t mode = 0660 | S_IFBLK;
+    dev_t dev = (major << 8) | minor;
+    sprintf(nodepath, "/dev/block/vold/%d:%d", major, minor);
+    if (mknod(nodepath, mode, dev) < 0) {
+        LOGE("Error making device nodes for '%s' (%s)",
+             nodepath, strerror(errno));
+        return -1;
+    }
+
+    /* Run disk checker */
+    if (checkFilesystem(nodepath)) {
+        setState(Volume::State_Idle);
+        return -1;
+    }
+
+    setState(Volume::State_Idle);
+    return 0;
+}
+
+int Volume::checkFilesystem(const char *nodepath) {
+
+    bool rw = true;
+    if (access(FSCK_MSDOS_PATH, X_OK)) {
+        LOGW("Skipping fs checks\n");
+        return 0;
+    }
+
+    setState(Volume::State_Checking);
+    int pass = 1;
+    int rc = 0;
+    do {
+        const char *args[5];
+        args[0] = FSCK_MSDOS_PATH;
+        args[1] = "-p";
+        args[2] = "-f";
+        args[3] = nodepath;
+        args[4] = NULL;
+
+        rc = logwrap(4, args, 1);
+
+        switch(rc) {
+        case 0:
+            LOGI("Filesystem check completed OK");
+            return 0;
+
+        case 2:
+            LOGE("Filesystem check failed (not a FAT filesystem)");
+            errno = ENODATA;
+            return -1;
+
+        case 4:
+            if (pass++ <= 3) {
+                LOGW("Filesystem modified - rechecking (pass %d)",
+                        pass);
+                continue;
+            }
+            LOGE("Failing check after too many rechecks");
+            errno = EIO;
+            return -1;
+
+        default:
+            LOGE("Filesystem check failed (unknown exit code %d)", rc);
+            errno = EIO;
+            return -1;
+        }
+    } while (0);
+
+    return 0;
+}
+
+int Volume::unmount() {
+    return 0;
+}
diff --git a/Volume.h b/Volume.h
index f428e91..70169f6 100644
--- a/Volume.h
+++ b/Volume.h
@@ -41,6 +41,9 @@
     Volume(const char *label, const char *mount_point);
     virtual ~Volume();
 
+    int mount();
+    int unmount();
+
     const char *getLabel() { return mLabel; }
     const char *getMountpoint() { return mMountpoint; }
     int getState() { return mState; }
@@ -49,6 +52,11 @@
 
 protected:
     void setState(int state);
+
+    virtual int prepareToMount(int *major, int *minor) = 0;
+
+private:
+    int checkFilesystem(const char *nodepath);
 };
 
 typedef android::List<Volume *> VolumeCollection;
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index a724a8d..024645d 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -89,6 +89,48 @@
         cli->sendMsg(ErrorCode::VolumeListResult, buffer, false);
         free(buffer);
     }
-    cli->sendMsg(ErrorCode::CommandOkay, "Volumes Listed", false);
+    cli->sendMsg(ErrorCode::CommandOkay, "Volumes listed.", false);
     return 0;
 }
+
+int VolumeManager::mountVolume(const char *label) {
+    Volume *v = lookupVolume(label);
+
+    if (!v) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    if (v->getState() != Volume::State_Idle) {
+        errno = EBUSY;
+        return -1;
+    }
+
+    return v->mount();
+}
+
+int VolumeManager::unmountVolume(const char *label) {
+    Volume *v = lookupVolume(label);
+
+    if (!v) {
+        errno = ENOENT;
+        return -1;
+    }
+
+    if (v->getState() != Volume::State_Mounted) {
+        errno = EBUSY;
+        return -1;
+    }
+
+    return v->unmount();
+}
+
+Volume *VolumeManager::lookupVolume(const char *label) {
+    VolumeCollection::iterator i;
+
+    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
+        if (!strcmp(label, (*i)->getLabel()))
+            return (*i);
+    }
+    return NULL;
+}
diff --git a/VolumeManager.h b/VolumeManager.h
index c6beb2a..c3d65e0 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -46,6 +46,8 @@
     int addVolume(Volume *v);
 
     int listVolumes(SocketClient *cli);
+    int mountVolume(const char *label);
+    int unmountVolume(const char *label);
 
     void setBroadcaster(SocketListener *sl) { mBroadcaster = sl; }
     SocketListener *getBroadcaster() { return mBroadcaster; }
@@ -54,5 +56,6 @@
 
 private:
     VolumeManager();
+    Volume *lookupVolume(const char *label);
 };
 #endif
diff --git a/logwrapper.c b/logwrapper.c
new file mode 100644
index 0000000..c96426f
--- /dev/null
+++ b/logwrapper.c
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
+
+#include "private/android_filesystem_config.h"
+#include "cutils/log.h"
+
+int parent(const char *tag, int parent_read) {
+    int status;
+    char buffer[4096];
+
+    int a = 0;  // start index of unprocessed data
+    int b = 0;  // end index of unprocessed data
+    int sz;
+    while ((sz = read(parent_read, &buffer[b], sizeof(buffer) - 1 - b)) > 0) {
+
+        sz += b;
+        // Log one line at a time
+        for (b = 0; b < sz; b++) {
+            if (buffer[b] == '\r') {
+                buffer[b] = '\0';
+            } else if (buffer[b] == '\n') {
+                buffer[b] = '\0';
+
+                LOG(LOG_INFO, tag, "%s", &buffer[a]);
+                a = b + 1;
+            }
+        }
+
+        if (a == 0 && b == sizeof(buffer) - 1) {
+            // buffer is full, flush
+            buffer[b] = '\0';
+            LOG(LOG_INFO, tag, &buffer[a]);
+            b = 0;
+        } else if (a != b) {
+            // Keep left-overs
+            b -= a;
+            memmove(buffer, &buffer[a], b);
+            a = 0;
+        } else {
+            a = 0;
+            b = 0;
+        }
+
+    }
+    // Flush remaining data
+    if (a != b) {
+        buffer[b] = '\0';
+        LOG(LOG_INFO, tag, &buffer[a]);
+    }
+    status = 0xAAAA;
+    if (wait(&status) != -1) {  // Wait for child
+        if (WIFEXITED(status)) {
+            LOG(LOG_INFO, "logwrapper", "%s terminated by exit(%d)", tag,
+                    WEXITSTATUS(status));
+            return WEXITSTATUS(status);
+        } else if (WIFSIGNALED(status))
+            LOG(LOG_INFO, "logwrapper", "%s terminated by signal %d", tag,
+                    WTERMSIG(status));
+        else if (WIFSTOPPED(status))
+            LOG(LOG_INFO, "logwrapper", "%s stopped by signal %d", tag,
+                    WSTOPSIG(status));
+    } else
+        LOG(LOG_INFO, "logwrapper", "%s wait() failed: %s (%d)", tag,
+                strerror(errno), errno);
+    return -EAGAIN;
+}
+
+void child(int argc, const char**argv) {
+    // create null terminated argv_child array
+    char* argv_child[argc + 1];
+    memcpy(argv_child, argv, argc * sizeof(char *));
+    argv_child[argc] = NULL;
+
+    // XXX: PROTECT FROM VIKING KILLER
+    if (execv(argv_child[0], argv_child)) {
+        LOG(LOG_ERROR, "logwrapper",
+            "executing %s failed: %s", argv_child[0], strerror(errno));
+        exit(-1);
+    }
+}
+
+int logwrap(int argc, const char* argv[], int background)
+{
+    pid_t pid;
+
+    int parent_ptty;
+    int child_ptty;
+    char *child_devname = NULL;
+
+    /* Use ptty instead of socketpair so that STDOUT is not buffered */
+    parent_ptty = open("/dev/ptmx", O_RDWR);
+    if (parent_ptty < 0) {
+	LOG(LOG_ERROR, "logwrapper", "Cannot create parent ptty");
+	return -errno;
+    }
+
+    if (grantpt(parent_ptty) || unlockpt(parent_ptty) ||
+            ((child_devname = (char*)ptsname(parent_ptty)) == 0)) {
+	LOG(LOG_ERROR, "logwrapper", "Problem with /dev/ptmx");
+	return -1;
+    }
+
+    pid = fork();
+    if (pid < 0) {
+	LOG(LOG_ERROR, "logwrapper", "Failed to fork");
+        return -errno;
+    } else if (pid == 0) {
+        child_ptty = open(child_devname, O_RDWR);
+        if (child_ptty < 0) {
+	    LOG(LOG_ERROR, "logwrapper", "Problem with child ptty");
+            return -errno;
+        }
+
+        // redirect stdout and stderr
+        close(parent_ptty);
+        dup2(child_ptty, 1);
+        dup2(child_ptty, 2);
+        close(child_ptty);
+
+        if (background) {
+            int fd = open("/dev/cpuctl/bg_non_interactive/tasks", O_WRONLY);
+      
+            if (fd >=0 ) {
+                char text[64];
+
+                sprintf(text, "%d", getpid());
+                if (write(fd, text, strlen(text)) < 0) {
+                    LOG(LOG_WARN, "logwrapper",
+                        "Unable to background process (%s)", strerror(errno));
+                    close(fd);
+                }
+                close(fd);
+            } else {
+                LOG(LOG_WARN, "logwrapper",
+                    "Unable to background process (%s)", strerror(errno));
+            }
+        }
+
+        child(argc, argv);
+    } else {
+        return parent(argv[0], parent_ptty);
+    }
+
+    return 0;
+}