1/*
2 * Copyright (C) 2015 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#define LOG_TAG "cmd"
18
19#include <utils/Log.h>
20#include <binder/Parcel.h>
21#include <binder/ProcessState.h>
22#include <binder/IResultReceiver.h>
23#include <binder/IServiceManager.h>
24#include <binder/TextOutput.h>
25#include <utils/Vector.h>
26
27#include <getopt.h>
28#include <stdlib.h>
29#include <stdio.h>
30#include <string.h>
31#include <unistd.h>
32#include <sys/time.h>
33
34using namespace android;
35
36static int sort_func(const String16* lhs, const String16* rhs)
37{
38    return lhs->compare(*rhs);
39}
40
41class MyResultReceiver : public BnResultReceiver
42{
43public:
44    virtual void send(int32_t /*resultCode*/) {
45    }
46};
47
48int main(int argc, char* const argv[])
49{
50    signal(SIGPIPE, SIG_IGN);
51    sp<ProcessState> proc = ProcessState::self();
52    proc->startThreadPool();
53
54    sp<IServiceManager> sm = defaultServiceManager();
55    fflush(stdout);
56    if (sm == NULL) {
57        ALOGE("Unable to get default service manager!");
58        aerr << "cmd: Unable to get default service manager!" << endl;
59        return 20;
60    }
61
62    if (argc == 1) {
63        aout << "cmd: no service specified; use -l to list all services" << endl;
64        return 20;
65    }
66
67    if ((argc == 2) && (strcmp(argv[1], "-l") == 0)) {
68        Vector<String16> services = sm->listServices();
69        services.sort(sort_func);
70        aout << "Currently running services:" << endl;
71
72        for (size_t i=0; i<services.size(); i++) {
73            sp<IBinder> service = sm->checkService(services[i]);
74            if (service != NULL) {
75                aout << "  " << services[i] << endl;
76            }
77        }
78        return 0;
79    }
80
81    Vector<String16> args;
82    for (int i=2; i<argc; i++) {
83        args.add(String16(argv[i]));
84    }
85    String16 cmd = String16(argv[1]);
86    sp<IBinder> service = sm->checkService(cmd);
87    if (service == NULL) {
88        aerr << "Can't find service: " << argv[1] << endl;
89        return 20;
90    }
91
92    // TODO: block until a result is returned to MyResultReceiver.
93    IBinder::shellCommand(service, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO, args,
94            new MyResultReceiver());
95    return 0;
96}
97