CommandListener.cpp revision 36801cccf27152c9eca5aab6ba3527221525110f
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
29#define LOG_TAG "VoldCmdListener"
30#include <cutils/log.h>
31
32#include <sysutils/SocketClient.h>
33#include <private/android_filesystem_config.h>
34
35#include "CommandListener.h"
36#include "VolumeManager.h"
37#include "VolumeBase.h"
38#include "ResponseCode.h"
39#include "Process.h"
40#include "Loop.h"
41#include "Devmapper.h"
42#include "cryptfs.h"
43#include "fstrim.h"
44
45#define DUMP_ARGS 0
46
47CommandListener::CommandListener() :
48                 FrameworkListener("vold", true) {
49    registerCmd(new DumpCmd());
50    registerCmd(new VolumeCmd());
51    registerCmd(new AsecCmd());
52    registerCmd(new ObbCmd());
53    registerCmd(new StorageCmd());
54    registerCmd(new CryptfsCmd());
55    registerCmd(new FstrimCmd());
56}
57
58#if DUMP_ARGS
59void CommandListener::dumpArgs(int argc, char **argv, int argObscure) {
60    char buffer[4096];
61    char *p = buffer;
62
63    memset(buffer, 0, sizeof(buffer));
64    int i;
65    for (i = 0; i < argc; i++) {
66        unsigned int len = strlen(argv[i]) + 1; // Account for space
67        if (i == argObscure) {
68            len += 2; // Account for {}
69        }
70        if (((p - buffer) + len) < (sizeof(buffer)-1)) {
71            if (i == argObscure) {
72                *p++ = '{';
73                *p++ = '}';
74                *p++ = ' ';
75                continue;
76            }
77            strcpy(p, argv[i]);
78            p+= strlen(argv[i]);
79            if (i != (argc -1)) {
80                *p++ = ' ';
81            }
82        }
83    }
84    SLOGD("%s", buffer);
85}
86#else
87void CommandListener::dumpArgs(int /*argc*/, char ** /*argv*/, int /*argObscure*/) { }
88#endif
89
90int CommandListener::sendGenericOkFail(SocketClient *cli, int cond) {
91    if (!cond) {
92        return cli->sendMsg(ResponseCode::CommandOkay, "Command succeeded", false);
93    } else {
94        return cli->sendMsg(ResponseCode::OperationFailed, "Command failed", false);
95    }
96}
97
98CommandListener::DumpCmd::DumpCmd() :
99                 VoldCommand("dump") {
100}
101
102int CommandListener::DumpCmd::runCommand(SocketClient *cli,
103                                         int /*argc*/, char ** /*argv*/) {
104    cli->sendMsg(0, "Dumping loop status", false);
105    if (Loop::dumpState(cli)) {
106        cli->sendMsg(ResponseCode::CommandOkay, "Loop dump failed", true);
107    }
108    cli->sendMsg(0, "Dumping DM status", false);
109    if (Devmapper::dumpState(cli)) {
110        cli->sendMsg(ResponseCode::CommandOkay, "Devmapper dump failed", true);
111    }
112    cli->sendMsg(0, "Dumping mounted filesystems", false);
113    FILE *fp = fopen("/proc/mounts", "r");
114    if (fp) {
115        char line[1024];
116        while (fgets(line, sizeof(line), fp)) {
117            line[strlen(line)-1] = '\0';
118            cli->sendMsg(0, line, false);;
119        }
120        fclose(fp);
121    }
122
123    cli->sendMsg(ResponseCode::CommandOkay, "dump complete", false);
124    return 0;
125}
126
127CommandListener::VolumeCmd::VolumeCmd() :
128                 VoldCommand("volume") {
129}
130
131int CommandListener::VolumeCmd::runCommand(SocketClient *cli,
132                                           int argc, char **argv) {
133    dumpArgs(argc, argv, -1);
134
135    if (argc < 2) {
136        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
137        return 0;
138    }
139
140    VolumeManager *vm = VolumeManager::Instance();
141
142    // TODO: tease out methods not directly related to volumes
143
144    std::string cmd(argv[1]);
145    if (cmd == "reset") {
146        return sendGenericOkFail(cli, vm->reset());
147
148    } else if (cmd == "shutdown") {
149        return sendGenericOkFail(cli, vm->shutdown());
150
151    } else if (cmd == "partition" && argc > 3) {
152        // partition [diskId] [public|private|mixed] [ratio]
153        std::string id(argv[2]);
154        auto disk = vm->findDisk(id);
155        if (disk == nullptr) {
156            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown disk", false);
157        }
158
159        std::string type(argv[3]);
160        if (type == "public") {
161            return sendGenericOkFail(cli, disk->partitionPublic());
162        } else if (type == "private") {
163            return sendGenericOkFail(cli, disk->partitionPrivate());
164        } else if (type == "mixed") {
165            if (argc < 4) {
166                return cli->sendMsg(ResponseCode::CommandSyntaxError, nullptr, false);
167            }
168            int frac = atoi(argv[4]);
169            return sendGenericOkFail(cli, disk->partitionMixed(frac));
170        } else {
171            return cli->sendMsg(ResponseCode::CommandSyntaxError, nullptr, false);
172        }
173
174    } else if (cmd == "mkdirs" && argc > 2) {
175        // mkdirs [path]
176        return sendGenericOkFail(cli, vm->mkdirs(argv[2]));
177
178    } else if (cmd == "start_user" && argc > 2) {
179        // start_user [user]
180        return sendGenericOkFail(cli, vm->startUser(atoi(argv[2])));
181
182    } else if (cmd == "cleanup_user" && argc > 2) {
183        // cleanup_user [user]
184        return sendGenericOkFail(cli, vm->cleanupUser(atoi(argv[2])));
185
186    } else if (cmd == "mount" && argc > 2) {
187        // mount [volId] [flags] [user]
188        std::string id(argv[2]);
189        auto vol = vm->findVolume(id);
190        if (vol == nullptr) {
191            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
192        }
193
194        int flags = (argc > 3) ? atoi(argv[3]) : 0;
195        userid_t user = (argc > 4) ? atoi(argv[4]) : -1;
196
197        if (flags & android::vold::VolumeBase::Flags::kPrimary) {
198            vm->setPrimary(vol);
199        }
200
201        vol->setFlags(flags);
202        vol->setUser(user);
203
204        return sendGenericOkFail(cli, vol->mount());
205
206    } else if (cmd == "unmount" && argc > 2) {
207        // unmount [volId]
208        std::string id(argv[2]);
209        auto vol = vm->findVolume(id);
210        if (vol == nullptr) {
211            return cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume", false);
212        }
213
214        return sendGenericOkFail(cli, vol->unmount());
215
216    } else if (cmd == "format" && argc > 2) {
217        // format [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->format());
225    }
226
227    return cli->sendMsg(ResponseCode::CommandSyntaxError, nullptr, false);
228}
229
230CommandListener::StorageCmd::StorageCmd() :
231                 VoldCommand("storage") {
232}
233
234int CommandListener::StorageCmd::runCommand(SocketClient *cli,
235                                                      int argc, char **argv) {
236    /* Guarantied to be initialized by vold's main() before the CommandListener is active */
237    extern struct fstab *fstab;
238
239    dumpArgs(argc, argv, -1);
240
241    if (argc < 2) {
242        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
243        return 0;
244    }
245
246    if (!strcmp(argv[1], "mountall")) {
247        if (argc != 2) {
248            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: mountall", false);
249            return 0;
250        }
251        fs_mgr_mount_all(fstab);
252        cli->sendMsg(ResponseCode::CommandOkay, "Mountall ran successfully", false);
253        return 0;
254    }
255    if (!strcmp(argv[1], "users")) {
256        DIR *dir;
257        struct dirent *de;
258
259        if (argc < 3) {
260            cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument: user <mountpoint>", false);
261            return 0;
262        }
263        if (!(dir = opendir("/proc"))) {
264            cli->sendMsg(ResponseCode::OperationFailed, "Failed to open /proc", true);
265            return 0;
266        }
267
268        while ((de = readdir(dir))) {
269            int pid = Process::getPid(de->d_name);
270
271            if (pid < 0) {
272                continue;
273            }
274
275            char processName[255];
276            Process::getProcessName(pid, processName, sizeof(processName));
277
278            if (Process::checkFileDescriptorSymLinks(pid, argv[2]) ||
279                Process::checkFileMaps(pid, argv[2]) ||
280                Process::checkSymLink(pid, argv[2], "cwd") ||
281                Process::checkSymLink(pid, argv[2], "root") ||
282                Process::checkSymLink(pid, argv[2], "exe")) {
283
284                char msg[1024];
285                snprintf(msg, sizeof(msg), "%d %s", pid, processName);
286                cli->sendMsg(ResponseCode::StorageUsersListResult, msg, false);
287            }
288        }
289        closedir(dir);
290        cli->sendMsg(ResponseCode::CommandOkay, "Storage user list complete", false);
291    } else {
292        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown storage cmd", false);
293    }
294    return 0;
295}
296
297CommandListener::AsecCmd::AsecCmd() :
298                 VoldCommand("asec") {
299}
300
301void CommandListener::AsecCmd::listAsecsInDirectory(SocketClient *cli, const char *directory) {
302    DIR *d = opendir(directory);
303
304    if (!d) {
305        cli->sendMsg(ResponseCode::OperationFailed, "Failed to open asec dir", true);
306        return;
307    }
308
309    size_t dirent_len = offsetof(struct dirent, d_name) +
310            fpathconf(dirfd(d), _PC_NAME_MAX) + 1;
311
312    struct dirent *dent = (struct dirent *) malloc(dirent_len);
313    if (dent == NULL) {
314        cli->sendMsg(ResponseCode::OperationFailed, "Failed to allocate memory", true);
315        return;
316    }
317
318    struct dirent *result;
319
320    while (!readdir_r(d, dent, &result) && result != NULL) {
321        if (dent->d_name[0] == '.')
322            continue;
323        if (dent->d_type != DT_REG)
324            continue;
325        size_t name_len = strlen(dent->d_name);
326        if (name_len > 5 && name_len < 260 &&
327                !strcmp(&dent->d_name[name_len - 5], ".asec")) {
328            char id[255];
329            memset(id, 0, sizeof(id));
330            strlcpy(id, dent->d_name, name_len - 4);
331            cli->sendMsg(ResponseCode::AsecListResult, id, false);
332        }
333    }
334    closedir(d);
335
336    free(dent);
337}
338
339int CommandListener::AsecCmd::runCommand(SocketClient *cli,
340                                                      int argc, char **argv) {
341    if (argc < 2) {
342        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
343        return 0;
344    }
345
346    VolumeManager *vm = VolumeManager::Instance();
347    int rc = 0;
348
349    if (!strcmp(argv[1], "list")) {
350        dumpArgs(argc, argv, -1);
351
352        listAsecsInDirectory(cli, Volume::SEC_ASECDIR_EXT);
353        listAsecsInDirectory(cli, Volume::SEC_ASECDIR_INT);
354    } else if (!strcmp(argv[1], "create")) {
355        dumpArgs(argc, argv, 5);
356        if (argc != 8) {
357            cli->sendMsg(ResponseCode::CommandSyntaxError,
358                    "Usage: asec create <container-id> <size_mb> <fstype> <key> <ownerUid> "
359                    "<isExternal>", false);
360            return 0;
361        }
362
363        unsigned int numSectors = (atoi(argv[3]) * (1024 * 1024)) / 512;
364        const bool isExternal = (atoi(argv[7]) == 1);
365        rc = vm->createAsec(argv[2], numSectors, argv[4], argv[5], atoi(argv[6]), isExternal);
366    } else if (!strcmp(argv[1], "resize")) {
367        dumpArgs(argc, argv, -1);
368        if (argc != 5) {
369            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec resize <container-id> <size_mb> <key>", false);
370            return 0;
371        }
372        unsigned int numSectors = (atoi(argv[3]) * (1024 * 1024)) / 512;
373        rc = vm->resizeAsec(argv[2], numSectors, argv[4]);
374    } else if (!strcmp(argv[1], "finalize")) {
375        dumpArgs(argc, argv, -1);
376        if (argc != 3) {
377            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec finalize <container-id>", false);
378            return 0;
379        }
380        rc = vm->finalizeAsec(argv[2]);
381    } else if (!strcmp(argv[1], "fixperms")) {
382        dumpArgs(argc, argv, -1);
383        if  (argc != 5) {
384            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fixperms <container-id> <gid> <filename>", false);
385            return 0;
386        }
387
388        char *endptr;
389        gid_t gid = (gid_t) strtoul(argv[3], &endptr, 10);
390        if (*endptr != '\0') {
391            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fixperms <container-id> <gid> <filename>", false);
392            return 0;
393        }
394
395        rc = vm->fixupAsecPermissions(argv[2], gid, argv[4]);
396    } else if (!strcmp(argv[1], "destroy")) {
397        dumpArgs(argc, argv, -1);
398        if (argc < 3) {
399            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec destroy <container-id> [force]", false);
400            return 0;
401        }
402        bool force = false;
403        if (argc > 3 && !strcmp(argv[3], "force")) {
404            force = true;
405        }
406        rc = vm->destroyAsec(argv[2], force);
407    } else if (!strcmp(argv[1], "mount")) {
408        dumpArgs(argc, argv, 3);
409        if (argc != 6) {
410            cli->sendMsg(ResponseCode::CommandSyntaxError,
411                    "Usage: asec mount <namespace-id> <key> <ownerUid> <ro|rw>", false);
412            return 0;
413        }
414        bool readOnly = true;
415        if (!strcmp(argv[5], "rw")) {
416            readOnly = false;
417        }
418        rc = vm->mountAsec(argv[2], argv[3], atoi(argv[4]), readOnly);
419    } else if (!strcmp(argv[1], "unmount")) {
420        dumpArgs(argc, argv, -1);
421        if (argc < 3) {
422            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec unmount <container-id> [force]", false);
423            return 0;
424        }
425        bool force = false;
426        if (argc > 3 && !strcmp(argv[3], "force")) {
427            force = true;
428        }
429        rc = vm->unmountAsec(argv[2], force);
430    } else if (!strcmp(argv[1], "rename")) {
431        dumpArgs(argc, argv, -1);
432        if (argc != 4) {
433            cli->sendMsg(ResponseCode::CommandSyntaxError,
434                    "Usage: asec rename <old_id> <new_id>", false);
435            return 0;
436        }
437        rc = vm->renameAsec(argv[2], argv[3]);
438    } else if (!strcmp(argv[1], "path")) {
439        dumpArgs(argc, argv, -1);
440        if (argc != 3) {
441            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec path <container-id>", false);
442            return 0;
443        }
444        char path[255];
445
446        if (!(rc = vm->getAsecMountPath(argv[2], path, sizeof(path)))) {
447            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
448            return 0;
449        }
450    } else if (!strcmp(argv[1], "fspath")) {
451        dumpArgs(argc, argv, -1);
452        if (argc != 3) {
453            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fspath <container-id>", false);
454            return 0;
455        }
456        char path[255];
457
458        if (!(rc = vm->getAsecFilesystemPath(argv[2], path, sizeof(path)))) {
459            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
460            return 0;
461        }
462    } else {
463        dumpArgs(argc, argv, -1);
464        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown asec cmd", false);
465    }
466
467    if (!rc) {
468        cli->sendMsg(ResponseCode::CommandOkay, "asec operation succeeded", false);
469    } else {
470        rc = ResponseCode::convertFromErrno();
471        cli->sendMsg(rc, "asec operation failed", true);
472    }
473
474    return 0;
475}
476
477CommandListener::ObbCmd::ObbCmd() :
478                 VoldCommand("obb") {
479}
480
481int CommandListener::ObbCmd::runCommand(SocketClient *cli,
482                                                      int argc, char **argv) {
483    if (argc < 2) {
484        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
485        return 0;
486    }
487
488    VolumeManager *vm = VolumeManager::Instance();
489    int rc = 0;
490
491    if (!strcmp(argv[1], "list")) {
492        dumpArgs(argc, argv, -1);
493
494        rc = vm->listMountedObbs(cli);
495    } else if (!strcmp(argv[1], "mount")) {
496            dumpArgs(argc, argv, 3);
497            if (argc != 5) {
498                cli->sendMsg(ResponseCode::CommandSyntaxError,
499                        "Usage: obb mount <filename> <key> <ownerGid>", false);
500                return 0;
501            }
502            rc = vm->mountObb(argv[2], argv[3], atoi(argv[4]));
503    } else if (!strcmp(argv[1], "unmount")) {
504        dumpArgs(argc, argv, -1);
505        if (argc < 3) {
506            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: obb unmount <source file> [force]", false);
507            return 0;
508        }
509        bool force = false;
510        if (argc > 3 && !strcmp(argv[3], "force")) {
511            force = true;
512        }
513        rc = vm->unmountObb(argv[2], force);
514    } else if (!strcmp(argv[1], "path")) {
515        dumpArgs(argc, argv, -1);
516        if (argc != 3) {
517            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: obb path <source file>", false);
518            return 0;
519        }
520        char path[255];
521
522        if (!(rc = vm->getObbMountPath(argv[2], path, sizeof(path)))) {
523            cli->sendMsg(ResponseCode::AsecPathResult, path, false);
524            return 0;
525        }
526    } else {
527        dumpArgs(argc, argv, -1);
528        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown obb cmd", false);
529    }
530
531    if (!rc) {
532        cli->sendMsg(ResponseCode::CommandOkay, "obb operation succeeded", false);
533    } else {
534        rc = ResponseCode::convertFromErrno();
535        cli->sendMsg(rc, "obb operation failed", true);
536    }
537
538    return 0;
539}
540
541CommandListener::CryptfsCmd::CryptfsCmd() :
542                 VoldCommand("cryptfs") {
543}
544
545static int getType(const char* type)
546{
547    if (!strcmp(type, "default")) {
548        return CRYPT_TYPE_DEFAULT;
549    } else if (!strcmp(type, "password")) {
550        return CRYPT_TYPE_PASSWORD;
551    } else if (!strcmp(type, "pin")) {
552        return CRYPT_TYPE_PIN;
553    } else if (!strcmp(type, "pattern")) {
554        return CRYPT_TYPE_PATTERN;
555    } else {
556        return -1;
557    }
558}
559
560int CommandListener::CryptfsCmd::runCommand(SocketClient *cli,
561                                                      int argc, char **argv) {
562    if ((cli->getUid() != 0) && (cli->getUid() != AID_SYSTEM)) {
563        cli->sendMsg(ResponseCode::CommandNoPermission, "No permission to run cryptfs commands", false);
564        return 0;
565    }
566
567    if (argc < 2) {
568        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
569        return 0;
570    }
571
572    int rc = 0;
573
574    if (!strcmp(argv[1], "checkpw")) {
575        if (argc != 3) {
576            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs checkpw <passwd>", false);
577            return 0;
578        }
579        dumpArgs(argc, argv, 2);
580        rc = cryptfs_check_passwd(argv[2]);
581    } else if (!strcmp(argv[1], "restart")) {
582        if (argc != 2) {
583            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs restart", false);
584            return 0;
585        }
586        dumpArgs(argc, argv, -1);
587        rc = cryptfs_restart();
588    } else if (!strcmp(argv[1], "cryptocomplete")) {
589        if (argc != 2) {
590            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs cryptocomplete", false);
591            return 0;
592        }
593        dumpArgs(argc, argv, -1);
594        rc = cryptfs_crypto_complete();
595    } else if (!strcmp(argv[1], "enablecrypto")) {
596        const char* syntax = "Usage: cryptfs enablecrypto <wipe|inplace> "
597                             "default|password|pin|pattern [passwd]";
598        if ( (argc != 4 && argc != 5)
599             || (strcmp(argv[2], "wipe") && strcmp(argv[2], "inplace")) ) {
600            cli->sendMsg(ResponseCode::CommandSyntaxError, syntax, false);
601            return 0;
602        }
603        dumpArgs(argc, argv, 4);
604
605        int tries;
606        for (tries = 0; tries < 2; ++tries) {
607            int type = getType(argv[3]);
608            if (type == -1) {
609                cli->sendMsg(ResponseCode::CommandSyntaxError, syntax,
610                             false);
611                return 0;
612            } else if (type == CRYPT_TYPE_DEFAULT) {
613              rc = cryptfs_enable_default(argv[2], /*allow_reboot*/false);
614            } else {
615                rc = cryptfs_enable(argv[2], type, argv[4],
616                                    /*allow_reboot*/false);
617            }
618
619            if (rc == 0) {
620                break;
621            } else if (tries == 0) {
622                Process::killProcessesWithOpenFiles(DATA_MNT_POINT, SIGKILL);
623            }
624        }
625    } else if (!strcmp(argv[1], "changepw")) {
626        const char* syntax = "Usage: cryptfs changepw "
627                             "default|password|pin|pattern [newpasswd]";
628        const char* password;
629        if (argc == 3) {
630            password = "";
631        } else if (argc == 4) {
632            password = argv[3];
633        } else {
634            cli->sendMsg(ResponseCode::CommandSyntaxError, syntax, false);
635            return 0;
636        }
637        int type = getType(argv[2]);
638        if (type == -1) {
639            cli->sendMsg(ResponseCode::CommandSyntaxError, syntax, false);
640            return 0;
641        }
642        SLOGD("cryptfs changepw %s {}", argv[2]);
643        rc = cryptfs_changepw(type, password);
644    } else if (!strcmp(argv[1], "verifypw")) {
645        if (argc != 3) {
646            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs verifypw <passwd>", false);
647            return 0;
648        }
649        SLOGD("cryptfs verifypw {}");
650        rc = cryptfs_verify_passwd(argv[2]);
651    } else if (!strcmp(argv[1], "getfield")) {
652        char *valbuf;
653        int valbuf_len = PROPERTY_VALUE_MAX;
654
655        if (argc != 3) {
656            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs getfield <fieldname>", false);
657            return 0;
658        }
659        dumpArgs(argc, argv, -1);
660
661        // Increase the buffer size until it is big enough for the field value stored.
662        while (1) {
663            valbuf = (char*)malloc(valbuf_len);
664            if (valbuf == NULL) {
665                cli->sendMsg(ResponseCode::OperationFailed, "Failed to allocate memory", false);
666                return 0;
667            }
668            rc = cryptfs_getfield(argv[2], valbuf, valbuf_len);
669            if (rc != CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL) {
670                break;
671            }
672            free(valbuf);
673            valbuf_len *= 2;
674        }
675        if (rc == CRYPTO_GETFIELD_OK) {
676            cli->sendMsg(ResponseCode::CryptfsGetfieldResult, valbuf, false);
677        }
678        free(valbuf);
679    } else if (!strcmp(argv[1], "setfield")) {
680        if (argc != 4) {
681            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs setfield <fieldname> <value>", false);
682            return 0;
683        }
684        dumpArgs(argc, argv, -1);
685        rc = cryptfs_setfield(argv[2], argv[3]);
686    } else if (!strcmp(argv[1], "mountdefaultencrypted")) {
687        SLOGD("cryptfs mountdefaultencrypted");
688        dumpArgs(argc, argv, -1);
689        rc = cryptfs_mount_default_encrypted();
690    } else if (!strcmp(argv[1], "getpwtype")) {
691        SLOGD("cryptfs getpwtype");
692        dumpArgs(argc, argv, -1);
693        switch(cryptfs_get_password_type()) {
694        case CRYPT_TYPE_PASSWORD:
695            cli->sendMsg(ResponseCode::PasswordTypeResult, "password", false);
696            return 0;
697        case CRYPT_TYPE_PATTERN:
698            cli->sendMsg(ResponseCode::PasswordTypeResult, "pattern", false);
699            return 0;
700        case CRYPT_TYPE_PIN:
701            cli->sendMsg(ResponseCode::PasswordTypeResult, "pin", false);
702            return 0;
703        case CRYPT_TYPE_DEFAULT:
704            cli->sendMsg(ResponseCode::PasswordTypeResult, "default", false);
705            return 0;
706        default:
707          /** @TODO better error and make sure handled by callers */
708            cli->sendMsg(ResponseCode::OpFailedStorageNotFound, "Error", false);
709            return 0;
710        }
711    } else if (!strcmp(argv[1], "getpw")) {
712        SLOGD("cryptfs getpw");
713        dumpArgs(argc, argv, -1);
714        const char* password = cryptfs_get_password();
715        if (password) {
716            char* message = 0;
717            int size = asprintf(&message, "{{sensitive}} %s", password);
718            if (size != -1) {
719                cli->sendMsg(ResponseCode::CommandOkay, message, false);
720                memset(message, 0, size);
721                free (message);
722                return 0;
723            }
724        }
725        rc = -1;
726    } else if (!strcmp(argv[1], "clearpw")) {
727        SLOGD("cryptfs clearpw");
728        dumpArgs(argc, argv, -1);
729        cryptfs_clear_password();
730        rc = 0;
731    } else {
732        dumpArgs(argc, argv, -1);
733        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown cryptfs cmd", false);
734        return 0;
735    }
736
737    // Always report that the command succeeded and return the error code.
738    // The caller will check the return value to see what the error was.
739    char msg[255];
740    snprintf(msg, sizeof(msg), "%d", rc);
741    cli->sendMsg(ResponseCode::CommandOkay, msg, false);
742
743    return 0;
744}
745
746CommandListener::FstrimCmd::FstrimCmd() :
747                 VoldCommand("fstrim") {
748}
749int CommandListener::FstrimCmd::runCommand(SocketClient *cli,
750                                                      int argc, char **argv) {
751    if ((cli->getUid() != 0) && (cli->getUid() != AID_SYSTEM)) {
752        cli->sendMsg(ResponseCode::CommandNoPermission, "No permission to run fstrim commands", false);
753        return 0;
754    }
755
756    if (argc < 2) {
757        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
758        return 0;
759    }
760
761    int rc = 0;
762
763    if (!strcmp(argv[1], "dotrim")) {
764        if (argc != 2) {
765            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: fstrim dotrim", false);
766            return 0;
767        }
768        dumpArgs(argc, argv, -1);
769        rc = fstrim_filesystems(0);
770    } else if (!strcmp(argv[1], "dodtrim")) {
771        if (argc != 2) {
772            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: fstrim dodtrim", false);
773            return 0;
774        }
775        dumpArgs(argc, argv, -1);
776        rc = fstrim_filesystems(1);   /* Do Deep Discard trim */
777    } else {
778        dumpArgs(argc, argv, -1);
779        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown fstrim cmd", false);
780    }
781
782    // Always report that the command succeeded and return the error code.
783    // The caller will check the return value to see what the error was.
784    char msg[255];
785    snprintf(msg, sizeof(msg), "%d", rc);
786    cli->sendMsg(ResponseCode::CommandOkay, msg, false);
787
788    return 0;
789}
790