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