CommandListener.cpp revision d6a77b518ca951d8b527f97d3e3732756c641a74
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 "fstrim.h"
50#include "MoveTask.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 == "start_user" && argc > 2) {
189        // start_user [user]
190        return sendGenericOkFail(cli, vm->startUser(atoi(argv[2])));
191
192    } else if (cmd == "cleanup_user" && argc > 2) {
193        // cleanup_user [user]
194        return sendGenericOkFail(cli, vm->cleanupUser(atoi(argv[2])));
195
196    } else if (cmd == "mount" && argc > 2) {
197        // mount [volId] [flags] [user]
198        std::string id(argv[2]);
199        auto vol = vm->findVolume(id);
200        if (vol == nullptr) {
201            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
202        }
203
204        int mountFlags = (argc > 3) ? atoi(argv[3]) : 0;
205        userid_t mountUserId = (argc > 4) ? atoi(argv[4]) : -1;
206
207        vol->setMountFlags(mountFlags);
208        vol->setMountUserId(mountUserId);
209
210        int res = vol->mount();
211        if (mountFlags & android::vold::VolumeBase::MountFlags::kPrimary) {
212            vm->setPrimary(vol);
213        }
214        return sendGenericOkFail(cli, res);
215
216    } else if (cmd == "unmount" && argc > 2) {
217        // unmount [volId]
218        std::string id(argv[2]);
219        auto vol = vm->findVolume(id);
220        if (vol == nullptr) {
221            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
222        }
223
224        return sendGenericOkFail(cli, vol->unmount());
225
226    } else if (cmd == "format" && argc > 3) {
227        // format [volId] [fsType|auto]
228        std::string id(argv[2]);
229        std::string fsType(argv[3]);
230        auto vol = vm->findVolume(id);
231        if (vol == nullptr) {
232            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
233        }
234
235        return sendGenericOkFail(cli, vol->format(fsType));
236
237    } else if (cmd == "move_storage" && argc > 3) {
238        // move_storage [fromVolId] [toVolId]
239        auto fromVol = vm->findVolume(std::string(argv[2]));
240        auto toVol = vm->findVolume(std::string(argv[3]));
241        if (fromVol == nullptr || toVol == nullptr) {
242            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
243        }
244
245        (new android::vold::MoveTask(fromVol, toVol))->start();
246        return sendGenericOkFail(cli, 0);
247
248    } else if (cmd == "benchmark" && argc > 2) {
249        // benchmark [volId]
250        std::string id(argv[2]);
251        nsecs_t res = vm->benchmarkVolume(id);
252        return cli->sendMsg(ResponseCode::CommandOkay,
253                android::base::StringPrintf("%" PRId64, res).c_str(), false);
254    }
255
256    return cli->sendMsg(ResponseCode::CommandSyntaxError, nullptr, false);
257}
258
259CommandListener::StorageCmd::StorageCmd() :
260                 VoldCommand("storage") {
261}
262
263int CommandListener::StorageCmd::runCommand(SocketClient *cli,
264                                                      int argc, char **argv) {
265    /* Guarantied to be initialized by vold's main() before the CommandListener is active */
266    extern struct fstab *fstab;
267
268    dumpArgs(argc, argv, -1);
269
270    if (argc < 2) {
271        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
272        return 0;
273    }
274
275    if (!strcmp(argv[1], "mountall")) {
276        if (argc != 2) {
277            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: mountall", false);
278            return 0;
279        }
280        fs_mgr_mount_all(fstab);
281        cli->sendMsg(ResponseCode::CommandOkay, "Mountall ran successfully", false);
282        return 0;
283    }
284    if (!strcmp(argv[1], "users")) {
285        DIR *dir;
286        struct dirent *de;
287
288        if (argc < 3) {
289            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument: user <mountpoint>", false);
290            return 0;
291        }
292        if (!(dir = opendir("/proc"))) {
293            cli->sendMsg(ResponseCode::OperationFailed, "Failed to open /proc", true);
294            return 0;
295        }
296
297        while ((de = readdir(dir))) {
298            int pid = Process::getPid(de->d_name);
299
300            if (pid < 0) {
301                continue;
302            }
303
304            char processName[255];
305            Process::getProcessName(pid, processName, sizeof(processName));
306
307            if (Process::checkFileDescriptorSymLinks(pid, argv[2]) ||
308                Process::checkFileMaps(pid, argv[2]) ||
309                Process::checkSymLink(pid, argv[2], "cwd") ||
310                Process::checkSymLink(pid, argv[2], "root") ||
311                Process::checkSymLink(pid, argv[2], "exe")) {
312
313                char msg[1024];
314                snprintf(msg, sizeof(msg), "%d %s", pid, processName);
315                cli->sendMsg(ResponseCode::StorageUsersListResult, msg, false);
316            }
317        }
318        closedir(dir);
319        cli->sendMsg(ResponseCode::CommandOkay, "Storage user list complete", false);
320    } else {
321        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown storage cmd", false);
322    }
323    return 0;
324}
325
326CommandListener::AsecCmd::AsecCmd() :
327                 VoldCommand("asec") {
328}
329
330void CommandListener::AsecCmd::listAsecsInDirectory(SocketClient *cli, const char *directory) {
331    DIR *d = opendir(directory);
332
333    if (!d) {
334        cli->sendMsg(ResponseCode::OperationFailed, "Failed to open asec dir", true);
335        return;
336    }
337
338    size_t dirent_len = offsetof(struct dirent, d_name) +
339            fpathconf(dirfd(d), _PC_NAME_MAX) + 1;
340
341    struct dirent *dent = (struct dirent *) malloc(dirent_len);
342    if (dent == NULL) {
343        cli->sendMsg(ResponseCode::OperationFailed, "Failed to allocate memory", true);
344        return;
345    }
346
347    struct dirent *result;
348
349    while (!readdir_r(d, dent, &result) && result != NULL) {
350        if (dent->d_name[0] == '.')
351            continue;
352        if (dent->d_type != DT_REG)
353            continue;
354        size_t name_len = strlen(dent->d_name);
355        if (name_len > 5 && name_len < 260 &&
356                !strcmp(&dent->d_name[name_len - 5], ".asec")) {
357            char id[255];
358            memset(id, 0, sizeof(id));
359            strlcpy(id, dent->d_name, name_len - 4);
360            cli->sendMsg(ResponseCode::AsecListResult, id, false);
361        }
362    }
363    closedir(d);
364
365    free(dent);
366}
367
368int CommandListener::AsecCmd::runCommand(SocketClient *cli,
369                                                      int argc, char **argv) {
370    if (argc < 2) {
371        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
372        return 0;
373    }
374
375    VolumeManager *vm = VolumeManager::Instance();
376    int rc = 0;
377
378    if (!strcmp(argv[1], "list")) {
379        dumpArgs(argc, argv, -1);
380
381        listAsecsInDirectory(cli, VolumeManager::SEC_ASECDIR_EXT);
382        listAsecsInDirectory(cli, VolumeManager::SEC_ASECDIR_INT);
383    } else if (!strcmp(argv[1], "create")) {
384        dumpArgs(argc, argv, 5);
385        if (argc != 8) {
386            cli->sendMsg(ResponseCode::CommandSyntaxError,
387                    "Usage: asec create <container-id> <size_mb> <fstype> <key> <ownerUid> "
388                    "<isExternal>", false);
389            return 0;
390        }
391
392        unsigned int numSectors = (atoi(argv[3]) * (1024 * 1024)) / 512;
393        const bool isExternal = (atoi(argv[7]) == 1);
394        rc = vm->createAsec(argv[2], numSectors, argv[4], argv[5], atoi(argv[6]), isExternal);
395    } else if (!strcmp(argv[1], "resize")) {
396        dumpArgs(argc, argv, -1);
397        if (argc != 5) {
398            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec resize <container-id> <size_mb> <key>", false);
399            return 0;
400        }
401        unsigned int numSectors = (atoi(argv[3]) * (1024 * 1024)) / 512;
402        rc = vm->resizeAsec(argv[2], numSectors, argv[4]);
403    } else if (!strcmp(argv[1], "finalize")) {
404        dumpArgs(argc, argv, -1);
405        if (argc != 3) {
406            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec finalize <container-id>", false);
407            return 0;
408        }
409        rc = vm->finalizeAsec(argv[2]);
410    } else if (!strcmp(argv[1], "fixperms")) {
411        dumpArgs(argc, argv, -1);
412        if  (argc != 5) {
413            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fixperms <container-id> <gid> <filename>", false);
414            return 0;
415        }
416
417        char *endptr;
418        gid_t gid = (gid_t) strtoul(argv[3], &endptr, 10);
419        if (*endptr != '\0') {
420            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fixperms <container-id> <gid> <filename>", false);
421            return 0;
422        }
423
424        rc = vm->fixupAsecPermissions(argv[2], gid, argv[4]);
425    } else if (!strcmp(argv[1], "destroy")) {
426        dumpArgs(argc, argv, -1);
427        if (argc < 3) {
428            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec destroy <container-id> [force]", false);
429            return 0;
430        }
431        bool force = false;
432        if (argc > 3 && !strcmp(argv[3], "force")) {
433            force = true;
434        }
435        rc = vm->destroyAsec(argv[2], force);
436    } else if (!strcmp(argv[1], "mount")) {
437        dumpArgs(argc, argv, 3);
438        if (argc != 6) {
439            cli->sendMsg(ResponseCode::CommandSyntaxError,
440                    "Usage: asec mount <namespace-id> <key> <ownerUid> <ro|rw>", false);
441            return 0;
442        }
443        bool readOnly = true;
444        if (!strcmp(argv[5], "rw")) {
445            readOnly = false;
446        }
447        rc = vm->mountAsec(argv[2], argv[3], atoi(argv[4]), readOnly);
448    } else if (!strcmp(argv[1], "unmount")) {
449        dumpArgs(argc, argv, -1);
450        if (argc < 3) {
451            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec unmount <container-id> [force]", false);
452            return 0;
453        }
454        bool force = false;
455        if (argc > 3 && !strcmp(argv[3], "force")) {
456            force = true;
457        }
458        rc = vm->unmountAsec(argv[2], force);
459    } else if (!strcmp(argv[1], "rename")) {
460        dumpArgs(argc, argv, -1);
461        if (argc != 4) {
462            cli->sendMsg(ResponseCode::CommandSyntaxError,
463                    "Usage: asec rename <old_id> <new_id>", false);
464            return 0;
465        }
466        rc = vm->renameAsec(argv[2], argv[3]);
467    } else if (!strcmp(argv[1], "path")) {
468        dumpArgs(argc, argv, -1);
469        if (argc != 3) {
470            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec path <container-id>", false);
471            return 0;
472        }
473        char path[255];
474
475        if (!(rc = vm->getAsecMountPath(argv[2], path, sizeof(path)))) {
476            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
477            return 0;
478        }
479    } else if (!strcmp(argv[1], "fspath")) {
480        dumpArgs(argc, argv, -1);
481        if (argc != 3) {
482            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fspath <container-id>", false);
483            return 0;
484        }
485        char path[255];
486
487        if (!(rc = vm->getAsecFilesystemPath(argv[2], path, sizeof(path)))) {
488            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
489            return 0;
490        }
491    } else {
492        dumpArgs(argc, argv, -1);
493        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown asec cmd", false);
494    }
495
496    if (!rc) {
497        cli->sendMsg(ResponseCode::CommandOkay, "asec operation succeeded", false);
498    } else {
499        rc = ResponseCode::convertFromErrno();
500        cli->sendMsg(rc, "asec operation failed", true);
501    }
502
503    return 0;
504}
505
506CommandListener::ObbCmd::ObbCmd() :
507                 VoldCommand("obb") {
508}
509
510int CommandListener::ObbCmd::runCommand(SocketClient *cli,
511                                                      int argc, char **argv) {
512    if (argc < 2) {
513        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
514        return 0;
515    }
516
517    VolumeManager *vm = VolumeManager::Instance();
518    int rc = 0;
519
520    if (!strcmp(argv[1], "list")) {
521        dumpArgs(argc, argv, -1);
522
523        rc = vm->listMountedObbs(cli);
524    } else if (!strcmp(argv[1], "mount")) {
525            dumpArgs(argc, argv, 3);
526            if (argc != 5) {
527                cli->sendMsg(ResponseCode::CommandSyntaxError,
528                        "Usage: obb mount <filename> <key> <ownerGid>", false);
529                return 0;
530            }
531            rc = vm->mountObb(argv[2], argv[3], atoi(argv[4]));
532    } else if (!strcmp(argv[1], "unmount")) {
533        dumpArgs(argc, argv, -1);
534        if (argc < 3) {
535            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: obb unmount <source file> [force]", false);
536            return 0;
537        }
538        bool force = false;
539        if (argc > 3 && !strcmp(argv[3], "force")) {
540            force = true;
541        }
542        rc = vm->unmountObb(argv[2], force);
543    } else if (!strcmp(argv[1], "path")) {
544        dumpArgs(argc, argv, -1);
545        if (argc != 3) {
546            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: obb path <source file>", false);
547            return 0;
548        }
549        char path[255];
550
551        if (!(rc = vm->getObbMountPath(argv[2], path, sizeof(path)))) {
552            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
553            return 0;
554        }
555    } else {
556        dumpArgs(argc, argv, -1);
557        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown obb cmd", false);
558    }
559
560    if (!rc) {
561        cli->sendMsg(ResponseCode::CommandOkay, "obb operation succeeded", false);
562    } else {
563        rc = ResponseCode::convertFromErrno();
564        cli->sendMsg(rc, "obb operation failed", true);
565    }
566
567    return 0;
568}
569
570CommandListener::FstrimCmd::FstrimCmd() :
571                 VoldCommand("fstrim") {
572}
573int CommandListener::FstrimCmd::runCommand(SocketClient *cli,
574                                                      int argc, char **argv) {
575    if ((cli->getUid() != 0) && (cli->getUid() != AID_SYSTEM)) {
576        cli->sendMsg(ResponseCode::CommandNoPermission, "No permission to run fstrim commands", false);
577        return 0;
578    }
579
580    if (argc < 2) {
581        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
582        return 0;
583    }
584
585    int rc = 0;
586
587    if (!strcmp(argv[1], "dotrim")) {
588        if (argc != 2) {
589            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: fstrim dotrim", false);
590            return 0;
591        }
592        dumpArgs(argc, argv, -1);
593        rc = fstrim_filesystems(0);
594    } else if (!strcmp(argv[1], "dodtrim")) {
595        if (argc != 2) {
596            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: fstrim dodtrim", false);
597            return 0;
598        }
599        dumpArgs(argc, argv, -1);
600        rc = fstrim_filesystems(1);   /* Do Deep Discard trim */
601    } else {
602        dumpArgs(argc, argv, -1);
603        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown fstrim cmd", false);
604    }
605
606    // Always report that the command succeeded and return the error code.
607    // The caller will check the return value to see what the error was.
608    char msg[255];
609    snprintf(msg, sizeof(msg), "%d", rc);
610    cli->sendMsg(ResponseCode::CommandOkay, msg, false);
611
612    return 0;
613}
614