CommandListener.cpp revision a4f48d0f44d09b6a9a3b16f6c0121ffd5123eef3
1/*
2 * Copyright (C) 2008 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
17#include <stdlib.h>
18#include <sys/socket.h>
19#include <sys/types.h>
20#include <netinet/in.h>
21#include <arpa/inet.h>
22#include <dirent.h>
23#include <errno.h>
24#include <fcntl.h>
25#include <fs_mgr.h>
26#include <stdio.h>
27#include <string.h>
28#include <stdint.h>
29#include <inttypes.h>
30
31#define LOG_TAG "VoldCmdListener"
32
33#include <base/stringprintf.h>
34#include <cutils/fs.h>
35#include <cutils/log.h>
36
37#include <sysutils/SocketClient.h>
38#include <private/android_filesystem_config.h>
39
40#include "CommandListener.h"
41#include "VolumeManager.h"
42#include "VolumeBase.h"
43#include "ResponseCode.h"
44#include "Process.h"
45#include "Loop.h"
46#include "Devmapper.h"
47#include "Ext4Crypt.h"
48#include "cryptfs.h"
49#include "MoveTask.h"
50#include "TrimTask.h"
51
52#define DUMP_ARGS 0
53
54CommandListener::CommandListener() :
55                 FrameworkListener("vold", true) {
56    registerCmd(new DumpCmd());
57    registerCmd(new VolumeCmd());
58    registerCmd(new AsecCmd());
59    registerCmd(new ObbCmd());
60    registerCmd(new StorageCmd());
61    registerCmd(new FstrimCmd());
62}
63
64#if DUMP_ARGS
65void CommandListener::dumpArgs(int argc, char **argv, int argObscure) {
66    char buffer[4096];
67    char *p = buffer;
68
69    memset(buffer, 0, sizeof(buffer));
70    int i;
71    for (i = 0; i < argc; i++) {
72        unsigned int len = strlen(argv[i]) + 1; // Account for space
73        if (i == argObscure) {
74            len += 2; // Account for {}
75        }
76        if (((p - buffer) + len) < (sizeof(buffer)-1)) {
77            if (i == argObscure) {
78                *p++ = '{';
79                *p++ = '}';
80                *p++ = ' ';
81                continue;
82            }
83            strcpy(p, argv[i]);
84            p+= strlen(argv[i]);
85            if (i != (argc -1)) {
86                *p++ = ' ';
87            }
88        }
89    }
90    SLOGD("%s", buffer);
91}
92#else
93void CommandListener::dumpArgs(int /*argc*/, char ** /*argv*/, int /*argObscure*/) { }
94#endif
95
96int CommandListener::sendGenericOkFail(SocketClient *cli, int cond) {
97    if (!cond) {
98        return cli->sendMsg(ResponseCode::CommandOkay, "Command succeeded", false);
99    } else {
100        return cli->sendMsg(ResponseCode::OperationFailed, "Command failed", false);
101    }
102}
103
104CommandListener::DumpCmd::DumpCmd() :
105                 VoldCommand("dump") {
106}
107
108int CommandListener::DumpCmd::runCommand(SocketClient *cli,
109                                         int /*argc*/, char ** /*argv*/) {
110    cli->sendMsg(0, "Dumping loop status", false);
111    if (Loop::dumpState(cli)) {
112        cli->sendMsg(ResponseCode::CommandOkay, "Loop dump failed", true);
113    }
114    cli->sendMsg(0, "Dumping DM status", false);
115    if (Devmapper::dumpState(cli)) {
116        cli->sendMsg(ResponseCode::CommandOkay, "Devmapper dump failed", true);
117    }
118    cli->sendMsg(0, "Dumping mounted filesystems", false);
119    FILE *fp = fopen("/proc/mounts", "r");
120    if (fp) {
121        char line[1024];
122        while (fgets(line, sizeof(line), fp)) {
123            line[strlen(line)-1] = '\0';
124            cli->sendMsg(0, line, false);;
125        }
126        fclose(fp);
127    }
128
129    cli->sendMsg(ResponseCode::CommandOkay, "dump complete", false);
130    return 0;
131}
132
133CommandListener::VolumeCmd::VolumeCmd() :
134                 VoldCommand("volume") {
135}
136
137int CommandListener::VolumeCmd::runCommand(SocketClient *cli,
138                                           int argc, char **argv) {
139    dumpArgs(argc, argv, -1);
140
141    if (argc < 2) {
142        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
143        return 0;
144    }
145
146    VolumeManager *vm = VolumeManager::Instance();
147    std::lock_guard<std::mutex> lock(vm->getLock());
148
149    // TODO: tease out methods not directly related to volumes
150
151    std::string cmd(argv[1]);
152    if (cmd == "reset") {
153        return sendGenericOkFail(cli, vm->reset());
154
155    } else if (cmd == "shutdown") {
156        return sendGenericOkFail(cli, vm->shutdown());
157
158    } else if (cmd == "debug") {
159        return sendGenericOkFail(cli, vm->setDebug(true));
160
161    } else if (cmd == "partition" && argc > 3) {
162        // partition [diskId] [public|private|mixed] [ratio]
163        std::string id(argv[2]);
164        auto disk = vm->findDisk(id);
165        if (disk == nullptr) {
166            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown disk", false);
167        }
168
169        std::string type(argv[3]);
170        if (type == "public") {
171            return sendGenericOkFail(cli, disk->partitionPublic());
172        } else if (type == "private") {
173            return sendGenericOkFail(cli, disk->partitionPrivate());
174        } else if (type == "mixed") {
175            if (argc < 4) {
176                return cli->sendMsg(ResponseCode::CommandSyntaxError, nullptr, false);
177            }
178            int frac = atoi(argv[4]);
179            return sendGenericOkFail(cli, disk->partitionMixed(frac));
180        } else {
181            return cli->sendMsg(ResponseCode::CommandSyntaxError, nullptr, false);
182        }
183
184    } else if (cmd == "mkdirs" && argc > 2) {
185        // mkdirs [path]
186        return sendGenericOkFail(cli, vm->mkdirs(argv[2]));
187
188    } else if (cmd == "user_added" && argc > 3) {
189        // user_added [user] [serial]
190        return sendGenericOkFail(cli, vm->onUserAdded(atoi(argv[2]), atoi(argv[3])));
191
192    } else if (cmd == "user_removed" && argc > 2) {
193        // user_removed [user]
194        return sendGenericOkFail(cli, vm->onUserRemoved(atoi(argv[2])));
195
196    } else if (cmd == "user_started" && argc > 2) {
197        // user_started [user]
198        return sendGenericOkFail(cli, vm->onUserStarted(atoi(argv[2])));
199
200    } else if (cmd == "user_stopped" && argc > 2) {
201        // user_stopped [user]
202        return sendGenericOkFail(cli, vm->onUserStopped(atoi(argv[2])));
203
204    } else if (cmd == "mount" && argc > 2) {
205        // mount [volId] [flags] [user]
206        std::string id(argv[2]);
207        auto vol = vm->findVolume(id);
208        if (vol == nullptr) {
209            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
210        }
211
212        int mountFlags = (argc > 3) ? atoi(argv[3]) : 0;
213        userid_t mountUserId = (argc > 4) ? atoi(argv[4]) : -1;
214
215        vol->setMountFlags(mountFlags);
216        vol->setMountUserId(mountUserId);
217
218        int res = vol->mount();
219        if (mountFlags & android::vold::VolumeBase::MountFlags::kPrimary) {
220            vm->setPrimary(vol);
221        }
222        return sendGenericOkFail(cli, res);
223
224    } else if (cmd == "unmount" && argc > 2) {
225        // unmount [volId]
226        std::string id(argv[2]);
227        auto vol = vm->findVolume(id);
228        if (vol == nullptr) {
229            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
230        }
231
232        return sendGenericOkFail(cli, vol->unmount());
233
234    } else if (cmd == "format" && argc > 3) {
235        // format [volId] [fsType|auto]
236        std::string id(argv[2]);
237        std::string fsType(argv[3]);
238        auto vol = vm->findVolume(id);
239        if (vol == nullptr) {
240            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
241        }
242
243        return sendGenericOkFail(cli, vol->format(fsType));
244
245    } else if (cmd == "move_storage" && argc > 3) {
246        // move_storage [fromVolId] [toVolId]
247        auto fromVol = vm->findVolume(std::string(argv[2]));
248        auto toVol = vm->findVolume(std::string(argv[3]));
249        if (fromVol == nullptr || toVol == nullptr) {
250            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
251        }
252
253        (new android::vold::MoveTask(fromVol, toVol))->start();
254        return sendGenericOkFail(cli, 0);
255
256    } else if (cmd == "benchmark" && argc > 2) {
257        // benchmark [volId]
258        std::string id(argv[2]);
259        nsecs_t res = vm->benchmarkPrivate(id);
260        return cli->sendMsg(ResponseCode::CommandOkay,
261                android::base::StringPrintf("%" PRId64, res).c_str(), false);
262
263    } else if (cmd == "forget_partition" && argc > 2) {
264        // forget_partition [partGuid]
265        std::string partGuid(argv[2]);
266        return sendGenericOkFail(cli, vm->forgetPartition(partGuid));
267
268    } else if (cmd == "remount_uid" && argc > 3) {
269        // remount_uid [uid] [none|default|read|write]
270        uid_t uid = atoi(argv[2]);
271        std::string mode(argv[3]);
272        return sendGenericOkFail(cli, vm->remountUid(uid, mode));
273    }
274
275    return cli->sendMsg(ResponseCode::CommandSyntaxError, nullptr, false);
276}
277
278CommandListener::StorageCmd::StorageCmd() :
279                 VoldCommand("storage") {
280}
281
282int CommandListener::StorageCmd::runCommand(SocketClient *cli,
283                                                      int argc, char **argv) {
284    /* Guarantied to be initialized by vold's main() before the CommandListener is active */
285    extern struct fstab *fstab;
286
287    dumpArgs(argc, argv, -1);
288
289    if (argc < 2) {
290        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
291        return 0;
292    }
293
294    if (!strcmp(argv[1], "mountall")) {
295        if (argc != 2) {
296            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: mountall", false);
297            return 0;
298        }
299        fs_mgr_mount_all(fstab);
300        cli->sendMsg(ResponseCode::CommandOkay, "Mountall ran successfully", false);
301        return 0;
302    }
303    if (!strcmp(argv[1], "users")) {
304        DIR *dir;
305        struct dirent *de;
306
307        if (argc < 3) {
308            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument: user <mountpoint>", false);
309            return 0;
310        }
311        if (!(dir = opendir("/proc"))) {
312            cli->sendMsg(ResponseCode::OperationFailed, "Failed to open /proc", true);
313            return 0;
314        }
315
316        while ((de = readdir(dir))) {
317            int pid = Process::getPid(de->d_name);
318
319            if (pid < 0) {
320                continue;
321            }
322
323            char processName[255];
324            Process::getProcessName(pid, processName, sizeof(processName));
325
326            if (Process::checkFileDescriptorSymLinks(pid, argv[2]) ||
327                Process::checkFileMaps(pid, argv[2]) ||
328                Process::checkSymLink(pid, argv[2], "cwd") ||
329                Process::checkSymLink(pid, argv[2], "root") ||
330                Process::checkSymLink(pid, argv[2], "exe")) {
331
332                char msg[1024];
333                snprintf(msg, sizeof(msg), "%d %s", pid, processName);
334                cli->sendMsg(ResponseCode::StorageUsersListResult, msg, false);
335            }
336        }
337        closedir(dir);
338        cli->sendMsg(ResponseCode::CommandOkay, "Storage user list complete", false);
339    } else {
340        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown storage cmd", false);
341    }
342    return 0;
343}
344
345CommandListener::AsecCmd::AsecCmd() :
346                 VoldCommand("asec") {
347}
348
349void CommandListener::AsecCmd::listAsecsInDirectory(SocketClient *cli, const char *directory) {
350    DIR *d = opendir(directory);
351
352    if (!d) {
353        cli->sendMsg(ResponseCode::OperationFailed, "Failed to open asec dir", true);
354        return;
355    }
356
357    size_t dirent_len = offsetof(struct dirent, d_name) +
358            fpathconf(dirfd(d), _PC_NAME_MAX) + 1;
359
360    struct dirent *dent = (struct dirent *) malloc(dirent_len);
361    if (dent == NULL) {
362        cli->sendMsg(ResponseCode::OperationFailed, "Failed to allocate memory", true);
363        return;
364    }
365
366    struct dirent *result;
367
368    while (!readdir_r(d, dent, &result) && result != NULL) {
369        if (dent->d_name[0] == '.')
370            continue;
371        if (dent->d_type != DT_REG)
372            continue;
373        size_t name_len = strlen(dent->d_name);
374        if (name_len > 5 && name_len < 260 &&
375                !strcmp(&dent->d_name[name_len - 5], ".asec")) {
376            char id[255];
377            memset(id, 0, sizeof(id));
378            strlcpy(id, dent->d_name, name_len - 4);
379            cli->sendMsg(ResponseCode::AsecListResult, id, false);
380        }
381    }
382    closedir(d);
383
384    free(dent);
385}
386
387int CommandListener::AsecCmd::runCommand(SocketClient *cli,
388                                                      int argc, char **argv) {
389    if (argc < 2) {
390        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
391        return 0;
392    }
393
394    VolumeManager *vm = VolumeManager::Instance();
395    int rc = 0;
396
397    if (!strcmp(argv[1], "list")) {
398        dumpArgs(argc, argv, -1);
399
400        listAsecsInDirectory(cli, VolumeManager::SEC_ASECDIR_EXT);
401        listAsecsInDirectory(cli, VolumeManager::SEC_ASECDIR_INT);
402    } else if (!strcmp(argv[1], "create")) {
403        dumpArgs(argc, argv, 5);
404        if (argc != 8) {
405            cli->sendMsg(ResponseCode::CommandSyntaxError,
406                    "Usage: asec create <container-id> <size_mb> <fstype> <key> <ownerUid> "
407                    "<isExternal>", false);
408            return 0;
409        }
410
411        unsigned long numSectors = (atoi(argv[3]) * (1024 * 1024)) / 512;
412        const bool isExternal = (atoi(argv[7]) == 1);
413        rc = vm->createAsec(argv[2], numSectors, argv[4], argv[5], atoi(argv[6]), isExternal);
414    } else if (!strcmp(argv[1], "resize")) {
415        dumpArgs(argc, argv, -1);
416        if (argc != 5) {
417            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec resize <container-id> <size_mb> <key>", false);
418            return 0;
419        }
420        unsigned long numSectors = (atoi(argv[3]) * (1024 * 1024)) / 512;
421        rc = vm->resizeAsec(argv[2], numSectors, argv[4]);
422    } else if (!strcmp(argv[1], "finalize")) {
423        dumpArgs(argc, argv, -1);
424        if (argc != 3) {
425            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec finalize <container-id>", false);
426            return 0;
427        }
428        rc = vm->finalizeAsec(argv[2]);
429    } else if (!strcmp(argv[1], "fixperms")) {
430        dumpArgs(argc, argv, -1);
431        if  (argc != 5) {
432            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fixperms <container-id> <gid> <filename>", false);
433            return 0;
434        }
435
436        char *endptr;
437        gid_t gid = (gid_t) strtoul(argv[3], &endptr, 10);
438        if (*endptr != '\0') {
439            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fixperms <container-id> <gid> <filename>", false);
440            return 0;
441        }
442
443        rc = vm->fixupAsecPermissions(argv[2], gid, argv[4]);
444    } else if (!strcmp(argv[1], "destroy")) {
445        dumpArgs(argc, argv, -1);
446        if (argc < 3) {
447            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec destroy <container-id> [force]", false);
448            return 0;
449        }
450        bool force = false;
451        if (argc > 3 && !strcmp(argv[3], "force")) {
452            force = true;
453        }
454        rc = vm->destroyAsec(argv[2], force);
455    } else if (!strcmp(argv[1], "mount")) {
456        dumpArgs(argc, argv, 3);
457        if (argc != 6) {
458            cli->sendMsg(ResponseCode::CommandSyntaxError,
459                    "Usage: asec mount <namespace-id> <key> <ownerUid> <ro|rw>", false);
460            return 0;
461        }
462        bool readOnly = true;
463        if (!strcmp(argv[5], "rw")) {
464            readOnly = false;
465        }
466        rc = vm->mountAsec(argv[2], argv[3], atoi(argv[4]), readOnly);
467    } else if (!strcmp(argv[1], "unmount")) {
468        dumpArgs(argc, argv, -1);
469        if (argc < 3) {
470            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec unmount <container-id> [force]", false);
471            return 0;
472        }
473        bool force = false;
474        if (argc > 3 && !strcmp(argv[3], "force")) {
475            force = true;
476        }
477        rc = vm->unmountAsec(argv[2], force);
478    } else if (!strcmp(argv[1], "rename")) {
479        dumpArgs(argc, argv, -1);
480        if (argc != 4) {
481            cli->sendMsg(ResponseCode::CommandSyntaxError,
482                    "Usage: asec rename <old_id> <new_id>", false);
483            return 0;
484        }
485        rc = vm->renameAsec(argv[2], argv[3]);
486    } else if (!strcmp(argv[1], "path")) {
487        dumpArgs(argc, argv, -1);
488        if (argc != 3) {
489            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec path <container-id>", false);
490            return 0;
491        }
492        char path[255];
493
494        if (!(rc = vm->getAsecMountPath(argv[2], path, sizeof(path)))) {
495            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
496            return 0;
497        }
498    } else if (!strcmp(argv[1], "fspath")) {
499        dumpArgs(argc, argv, -1);
500        if (argc != 3) {
501            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fspath <container-id>", false);
502            return 0;
503        }
504        char path[255];
505
506        if (!(rc = vm->getAsecFilesystemPath(argv[2], path, sizeof(path)))) {
507            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
508            return 0;
509        }
510    } else {
511        dumpArgs(argc, argv, -1);
512        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown asec cmd", false);
513    }
514
515    if (!rc) {
516        cli->sendMsg(ResponseCode::CommandOkay, "asec operation succeeded", false);
517    } else {
518        rc = ResponseCode::convertFromErrno();
519        cli->sendMsg(rc, "asec operation failed", true);
520    }
521
522    return 0;
523}
524
525CommandListener::ObbCmd::ObbCmd() :
526                 VoldCommand("obb") {
527}
528
529int CommandListener::ObbCmd::runCommand(SocketClient *cli,
530                                                      int argc, char **argv) {
531    if (argc < 2) {
532        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
533        return 0;
534    }
535
536    VolumeManager *vm = VolumeManager::Instance();
537    int rc = 0;
538
539    if (!strcmp(argv[1], "list")) {
540        dumpArgs(argc, argv, -1);
541
542        rc = vm->listMountedObbs(cli);
543    } else if (!strcmp(argv[1], "mount")) {
544            dumpArgs(argc, argv, 3);
545            if (argc != 5) {
546                cli->sendMsg(ResponseCode::CommandSyntaxError,
547                        "Usage: obb mount <filename> <key> <ownerGid>", false);
548                return 0;
549            }
550            rc = vm->mountObb(argv[2], argv[3], atoi(argv[4]));
551    } else if (!strcmp(argv[1], "unmount")) {
552        dumpArgs(argc, argv, -1);
553        if (argc < 3) {
554            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: obb unmount <source file> [force]", false);
555            return 0;
556        }
557        bool force = false;
558        if (argc > 3 && !strcmp(argv[3], "force")) {
559            force = true;
560        }
561        rc = vm->unmountObb(argv[2], force);
562    } else if (!strcmp(argv[1], "path")) {
563        dumpArgs(argc, argv, -1);
564        if (argc != 3) {
565            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: obb path <source file>", false);
566            return 0;
567        }
568        char path[255];
569
570        if (!(rc = vm->getObbMountPath(argv[2], path, sizeof(path)))) {
571            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
572            return 0;
573        }
574    } else {
575        dumpArgs(argc, argv, -1);
576        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown obb cmd", false);
577    }
578
579    if (!rc) {
580        cli->sendMsg(ResponseCode::CommandOkay, "obb operation succeeded", false);
581    } else {
582        rc = ResponseCode::convertFromErrno();
583        cli->sendMsg(rc, "obb operation failed", true);
584    }
585
586    return 0;
587}
588
589CommandListener::FstrimCmd::FstrimCmd() :
590                 VoldCommand("fstrim") {
591}
592int CommandListener::FstrimCmd::runCommand(SocketClient *cli,
593                                                      int argc, char **argv) {
594    if ((cli->getUid() != 0) && (cli->getUid() != AID_SYSTEM)) {
595        cli->sendMsg(ResponseCode::CommandNoPermission, "No permission to run fstrim commands", false);
596        return 0;
597    }
598
599    if (argc < 2) {
600        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
601        return 0;
602    }
603
604    VolumeManager *vm = VolumeManager::Instance();
605    std::lock_guard<std::mutex> lock(vm->getLock());
606
607    int flags = 0;
608
609    std::string cmd(argv[1]);
610    if (cmd == "dotrim") {
611        flags = 0;
612    } else if (cmd == "dotrimbench") {
613        flags = android::vold::TrimTask::Flags::kBenchmarkAfter;
614    } else if (cmd == "dodtrim") {
615        flags = android::vold::TrimTask::Flags::kDeepTrim;
616    } else if (cmd == "dodtrimbench") {
617        flags = android::vold::TrimTask::Flags::kDeepTrim
618                | android::vold::TrimTask::Flags::kBenchmarkAfter;
619    }
620
621    (new android::vold::TrimTask(flags))->start();
622    return sendGenericOkFail(cli, 0);
623}
624