2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
25 #include <sys/socket.h>
26 #include <sys/select.h>
28 #include <sys/types.h>
31 #include <cutils/sockets.h>
32 #include <private/android_filesystem_config.h>
34 static void usage(char *progname);
35 static int do_monitor(int sock, int stop_after_cmd);
36 static int do_cmd(int sock, int argc, char **argv);
38 int main(int argc, char **argv) {
45 // try interpreting the first arg as the socket name - if it fails go back to netd
47 if ((sock = socket_local_client(argv[1],
48 ANDROID_SOCKET_NAMESPACE_RESERVED,
50 if ((sock = socket_local_client("netd",
51 ANDROID_SOCKET_NAMESPACE_RESERVED,
53 fprintf(stderr, "Error connecting (%s)\n", strerror(errno));
57 if (argc < 3) usage(argv[0]);
58 printf("Using alt socket %s\n", argv[1]);
62 if (!strcmp(argv[1+cmdOffset], "monitor"))
63 exit(do_monitor(sock, 0));
64 exit(do_cmd(sock, argc-cmdOffset, &(argv[cmdOffset])));
67 static int do_cmd(int sock, int argc, char **argv) {
68 char *final_cmd = strdup("0 ");
69 if (final_cmd == NULL) {
76 for (i = 1; i < argc; i++) {
77 if (index(argv[i], '"')) {
78 perror("argument with embedded quotes not allowed");
82 bool needs_quoting = index(argv[i], ' ');
83 const char *format = needs_quoting ? "%s\"%s\"%s" : "%s%s%s";
86 if (asprintf(&cmp, format, final_cmd, argv[i],
87 (i == (argc -1)) ? "" : " ") < 0) {
96 if (write(sock, final_cmd, strlen(final_cmd) + 1) < 0) {
103 return do_monitor(sock, 1);
106 static int do_monitor(int sock, int stop_after_cmd) {
107 char *buffer = malloc(4096);
110 printf("[Connected to Netd]\n");
121 FD_SET(sock, &read_fds);
123 if ((rc = select(sock +1, &read_fds, NULL, NULL, &to)) < 0) {
124 fprintf(stderr, "Error in select (%s)\n", strerror(errno));
129 fprintf(stderr, "[TIMEOUT]\n");
131 } else if (FD_ISSET(sock, &read_fds)) {
132 memset(buffer, 0, 4096);
133 if ((rc = read(sock, buffer, 4096)) <= 0) {
135 fprintf(stderr, "Lost connection to Netd - did it crash?\n");
137 fprintf(stderr, "Error reading data (%s)\n", strerror(errno));
147 for (i = 0; i < rc; i++) {
148 if (buffer[i] == '\0') {
152 strncpy(tmp, buffer + offset, 3);
156 printf("%s\n", buffer + offset);
157 if (stop_after_cmd) {
158 if (code >= 200 && code < 600)
170 static void usage(char *progname) {
171 fprintf(stderr, "Usage: %s [sockname] <monitor>|<cmd> [arg1] [arg2...]\n", progname);