1 /* 2 * Copyright (C) 2009 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 <errno.h> 18 #include <stdio.h> 19 #include <sys/socket.h> 20 #include <sys/types.h> 21 #include <unistd.h> 22 23 #include <cutils/properties.h> 24 #include <cutils/sockets.h> 25 26 // This program will trigger the dumpstate service to start a call to 27 // dumpstate, then connect to the dumpstate local client to read the 28 // output. All of the dumpstate output is written to stdout, including 29 // any errors encountered while reading/writing the output. 30 int main() { 31 // Start the dumpstate service. 32 property_set("ctl.start", "dumpstate"); 33 34 // Socket will not be available until service starts. 35 int s; 36 for (int i = 0; i < 20; i++) { 37 s = socket_local_client("dumpstate", ANDROID_SOCKET_NAMESPACE_RESERVED, 38 SOCK_STREAM); 39 if (s >= 0) 40 break; 41 // Try again in 1 second. 42 sleep(1); 43 } 44 45 if (s == -1) { 46 printf("Failed to connect to dumpstate service: %s\n", strerror(errno)); 47 return 1; 48 } 49 50 // Set a timeout so that if nothing is read in 3 minutes, we'll stop 51 // reading and quit. No timeout in dumpstate is longer than 60 seconds, 52 // so this gives lots of leeway in case of unforeseen time outs. 53 struct timeval tv; 54 tv.tv_sec = 3 * 60; 55 tv.tv_usec = 0; 56 if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) { 57 printf("WARNING: Cannot set socket timeout: %s\n", strerror(errno)); 58 } 59 60 while (1) { 61 char buffer[65536]; 62 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(s, buffer, sizeof(buffer))); 63 if (bytes_read == 0) { 64 break; 65 } else if (bytes_read == -1) { 66 // EAGAIN really means time out, so change the errno. 67 if (errno == EAGAIN) { 68 errno = ETIMEDOUT; 69 } 70 printf("\nBugreport read terminated abnormally (%s).\n", strerror(errno)); 71 break; 72 } 73 74 ssize_t bytes_to_send = bytes_read; 75 ssize_t bytes_written; 76 do { 77 bytes_written = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, 78 buffer + bytes_read - bytes_to_send, 79 bytes_to_send)); 80 if (bytes_written == -1) { 81 printf("Failed to write data to stdout: read %zd, trying to send %zd (%s)\n", 82 bytes_read, bytes_to_send, strerror(errno)); 83 return 1; 84 } 85 bytes_to_send -= bytes_written; 86 } while (bytes_written != 0 && bytes_to_send > 0); 87 } 88 89 close(s); 90 return 0; 91 } 92