Debian Codegraph @

tools/idevicesyslog.c

raw
1 /*
2 * idevicesyslog.c
3 * Relay the syslog of a device to stdout
4 *
5 * Copyright (c) 2010-2020 Nikias Bassen, All Rights Reserved.
6 * Copyright (c) 2009 Martin Szulecki All Rights Reserved.
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #define TOOL_NAME "idevicesyslog"
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <signal.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <getopt.h>
36 #include <time.h>
37
38 #ifdef _WIN32
39 #include <windows.h>
40 #define sleep(x) Sleep(x*1000)
41 #endif
42
43 #include <libimobiledevice/libimobiledevice.h>
44 #include <libimobiledevice/syslog_relay.h>
45 #include <libimobiledevice-glue/termcolors.h>
46 #include <libimobiledevice/ostrace.h>
47
48 static int quit_flag = 0;
49 static int exit_on_disconnect = 0;
50 static int show_device_name = 0;
51 static int force_syslog_relay = 0;
52
53 static char* udid = NULL;
54 static char** proc_filters = NULL;
55 static int num_proc_filters = 0;
56 static int proc_filter_excluding = 0;
57
58 static int* pid_filters = NULL;
59 static int num_pid_filters = 0;
60
61 static char** msg_filters = NULL;
62 static int num_msg_filters = 0;
63
64 static char** msg_reverse_filters = NULL;
65 static int num_msg_reverse_filters = 0;
66
67 static char** trigger_filters = NULL;
68 static int num_trigger_filters = 0;
69 static char** untrigger_filters = NULL;
70 static int num_untrigger_filters = 0;
71 static int triggered = 0;
72
73 static idevice_t device = NULL;
74 static syslog_relay_client_t syslog = NULL;
75 static ostrace_client_t ostrace = NULL;
76
77 static const char QUIET_FILTER[] = "CircleJoinRequested|CommCenter|HeuristicInterpreter|MobileMail|PowerUIAgent|ProtectedCloudKeySyncing|SpringBoard|UserEventAgent|WirelessRadioManagerd|accessoryd|accountsd|aggregated|analyticsd|appstored|apsd|assetsd|assistant_service|backboardd|biometrickitd|bluetoothd|calaccessd|callservicesd|cloudd|com.apple.Safari.SafeBrowsing.Service|contextstored|corecaptured|coreduetd|corespeechd|cdpd|dasd|dataaccessd|distnoted|dprivacyd|duetexpertd|findmydeviced|fmfd|fmflocatord|gpsd|healthd|homed|identityservicesd|imagent|itunescloudd|itunesstored|kernel|locationd|maild|mDNSResponder|mediaremoted|mediaserverd|mobileassetd|nanoregistryd|nanotimekitcompaniond|navd|nsurlsessiond|passd|pasted|photoanalysisd|powerd|powerlogHelperd|ptpd|rapportd|remindd|routined|runningboardd|searchd|sharingd|suggestd|symptomsd|timed|thermalmonitord|useractivityd|vmd|wifid|wirelessproxd";
78
79 static int use_network = 0;
80
81 static long long start_time = -1;
82 static long long size_limit = -1;
83 static long long age_limit = -1;
84
85 static char *line = NULL;
86 static int line_buffer_size = 0;
87 static int lp = 0;
88
89 static void add_filter(const char* filterstr)
90 {
91 int filter_len = strlen(filterstr);
92 const char* start = filterstr;
93 const char* end = filterstr + filter_len;
94 const char* p = start;
95 while (p <= end) {
96 if ((*p == '|') || (*p == '\0')) {
97 if (p-start > 0) {
98 char* procn = malloc(p-start+1);
99 if (!procn) {
100 fprintf(stderr, "ERROR: malloc() failed\n");
101 exit(EXIT_FAILURE);
102 }
103 memcpy(procn, start, p-start);
104 procn[p-start] = '\0';
105 char* endp = NULL;
106 int pid_value = (int)strtol(procn, &endp, 10);
107 if (!endp || *endp == 0) {
108 int *new_pid_filters = realloc(pid_filters, sizeof(int) * (num_pid_filters+1));
109 if (!new_pid_filters) {
110 fprintf(stderr, "ERROR: realloc() failed\n");
111 exit(EXIT_FAILURE);
112 }
113 pid_filters = new_pid_filters;
114 pid_filters[num_pid_filters] = pid_value;
115 num_pid_filters++;
116 } else {
117 char **new_proc_filters = realloc(proc_filters, sizeof(char*) * (num_proc_filters+1));
118 if (!new_proc_filters) {
119 fprintf(stderr, "ERROR: realloc() failed\n");
120 exit(EXIT_FAILURE);
121 }
122 proc_filters = new_proc_filters;
123 proc_filters[num_proc_filters] = procn;
124 num_proc_filters++;
125 }
126 }
127 start = p+1;
128 }
129 p++;
130 }
131 }
132
133 static int find_char(char c, char** p, const char* end)
134 {
135 while ((**p != c) && (*p < end)) {
136 (*p)++;
137 }
138 return (**p == c);
139 }
140
141 static void stop_logging(void);
142
143 static int message_filter_matching(const char* message)
144 {
145 if (num_msg_filters > 0) {
146 int found = 0;
147 int i;
148 for (i = 0; i < num_msg_filters; i++) {
149 if (strstr(message, msg_filters[i])) {
150 found = 1;
151 break;
152 }
153 }
154 if (!found) {
155 return 0;
156 }
157 }
158 if (num_msg_reverse_filters > 0) {
159 int found = 0;
160 int i;
161 for (i = 0; i < num_msg_reverse_filters; i++) {
162 if (strstr(message, msg_reverse_filters[i])) {
163 found = 1;
164 break;
165 }
166 }
167 if (found) {
168 return 0;
169 }
170 }
171 return 1;
172 }
173
174 static int process_filter_matching(int pid, const char* process_name, int process_name_length)
175 {
176 int proc_matched = 0;
177 if (num_pid_filters > 0) {
178 int found = proc_filter_excluding;
179 int i = 0;
180 for (i = 0; i < num_pid_filters; i++) {
181 if (pid == pid_filters[i]) {
182 found = !proc_filter_excluding;
183 break;
184 }
185 }
186 if (found) {
187 proc_matched = 1;
188 }
189 }
190 if (num_proc_filters > 0 && !proc_matched) {
191 int found = proc_filter_excluding;
192 int i = 0;
193 for (i = 0; i < num_proc_filters; i++) {
194 if (!proc_filters[i]) continue;
195 if (strncmp(proc_filters[i], process_name, process_name_length) == 0) {
196 found = !proc_filter_excluding;
197 break;
198 }
199 }
200 if (found) {
201 proc_matched = 1;
202 }
203 }
204 return proc_matched;
205 }
206
207 static void syslog_callback(char c, void *user_data)
208 {
209 if (lp >= line_buffer_size-1) {
210 line_buffer_size+=1024;
211 char* _line = realloc(line, line_buffer_size);
212 if (!_line) {
213 fprintf(stderr, "ERROR: realloc failed\n");
214 exit(EXIT_FAILURE);
215 }
216 line = _line;
217 }
218 line[lp++] = c;
219 if (c == '\0') {
220 int shall_print = 0;
221 int trigger_off = 0;
222 lp--;
223 char* linep = &line[0];
224 do {
225 if (lp < 16) {
226 shall_print = 1;
227 cprintf(FG_WHITE);
228 break;
229 }
230
231 if (line[3] == ' ' && line[6] == ' ' && line[15] == ' ') {
232 char* end = &line[lp];
233 char* p = &line[16];
234
235 /* device name */
236 char* device_name_start = p;
237 char* device_name_end = p;
238 if (!find_char(' ', &p, end)) break;
239 device_name_end = p;
240 p++;
241
242 /* check if we have any triggers/untriggers */
243 if (num_untrigger_filters > 0 && triggered) {
244 int found = 0;
245 int i;
246 for (i = 0; i < num_untrigger_filters; i++) {
247 if (strstr(device_name_end+1, untrigger_filters[i])) {
248 found = 1;
249 break;
250 }
251 }
252 if (!found) {
253 shall_print = 1;
254 } else {
255 shall_print = 1;
256 trigger_off = 1;
257 }
258 } else if (num_trigger_filters > 0 && !triggered) {
259 int found = 0;
260 int i;
261 for (i = 0; i < num_trigger_filters; i++) {
262 if (strstr(device_name_end+1, trigger_filters[i])) {
263 found = 1;
264 break;
265 }
266 }
267 if (!found) {
268 shall_print = 0;
269 break;
270 }
271 triggered = 1;
272 shall_print = 1;
273 } else if (num_trigger_filters == 0 && num_untrigger_filters > 0 && !triggered) {
274 shall_print = 0;
275 quit_flag++;
276 break;
277 }
278
279 /* check message filters */
280 shall_print = message_filter_matching(device_name_end+1);
281 if (!shall_print) {
282 break;
283 }
284
285 /* process name */
286 char* proc_name_start = p;
287 char* proc_name_end = p;
288 if (!find_char('[', &p, end)) break;
289 char* process_name_start = proc_name_start;
290 char* process_name_end = p;
291 char* pid_start = p+1;
292 char* pp = process_name_start;
293 if (find_char('(', &pp, p)) {
294 process_name_end = pp;
295 }
296 if (!find_char(']', &p, end)) break;
297 p++;
298 if (*p != ' ') break;
299 proc_name_end = p;
300 p++;
301
302 /* match pid / process name */
303 char* endp = NULL;
304 int pid_value = (int)strtol(pid_start, &endp, 10);
305 if (process_filter_matching(pid_value, process_name_start, process_name_end-process_name_start)) {
306 shall_print = 1;
307 } else {
308 if (num_pid_filters > 0 || num_proc_filters > 0) {
309 shall_print = 0;
310 break;
311 }
312 }
313
314 /* log level */
315 char* level_start = p;
316 char* level_end = p;
317 const char* level_color = NULL;
318 if (!strncmp(p, "<Notice>:", 9)) {
319 level_end += 9;
320 level_color = FG_GREEN;
321 } else if (!strncmp(p, "<Error>:", 8)) {
322 level_end += 8;
323 level_color = FG_RED;
324 } else if (!strncmp(p, "<Warning>:", 10)) {
325 level_end += 10;
326 level_color = FG_YELLOW;
327 } else if (!strncmp(p, "<Debug>:", 8)) {
328 level_end += 8;
329 level_color = FG_MAGENTA;
330 } else {
331 level_color = FG_WHITE;
332 }
333
334 /* write date and time */
335 cprintf(FG_LIGHT_GRAY);
336 fwrite(line, 1, 16, stdout);
337
338 if (show_device_name) {
339 /* write device name */
340 cprintf(FG_DARK_YELLOW);
341 fwrite(device_name_start, 1, device_name_end-device_name_start+1, stdout);
342 cprintf(COLOR_RESET);
343 }
344
345 /* write process name */
346 cprintf(FG_BRIGHT_CYAN);
347 fwrite(process_name_start, 1, process_name_end-process_name_start, stdout);
348 cprintf(FG_CYAN);
349 fwrite(process_name_end, 1, proc_name_end-process_name_end+1, stdout);
350
351 /* write log level */
352 cprintf(level_color);
353 if (level_end > level_start) {
354 fwrite(level_start, 1, level_end-level_start, stdout);
355 p = level_end;
356 }
357
358 lp -= p - linep;
359 linep = p;
360
361 cprintf(FG_WHITE);
362
363 } else {
364 shall_print = 1;
365 cprintf(FG_WHITE);
366 }
367 } while (0);
368
369 if ((num_msg_filters == 0 && num_msg_reverse_filters == 0 && num_proc_filters == 0 && num_pid_filters == 0 && num_trigger_filters == 0 && num_untrigger_filters == 0) || shall_print) {
370 fwrite(linep, 1, lp, stdout);
371 cprintf(COLOR_RESET);
372 fflush(stdout);
373 if (trigger_off) {
374 triggered = 0;
375 }
376 }
377 line[0] = '\0';
378 lp = 0;
379 return;
380 }
381 }
382
383 static void ostrace_syslog_callback(const void* buf, size_t len, void* user_data)
384 {
385 if (len < 0x81) {
386 fprintf(stderr, "Error: not enough data in callback function?!\n");
387 return;
388 }
389
390 struct ostrace_packet_header_t *trace_hdr = (struct ostrace_packet_header_t*)buf;
391
392 if (trace_hdr->marker != 2 || (trace_hdr->type != 8 && trace_hdr->type != 2)) {
393 fprintf(stderr, "unexpected packet data %02x %08x\n", trace_hdr->marker, trace_hdr->type);
394 }
395
396 const char* dataptr = (const char*)buf + trace_hdr->header_size;
397 const char* process_name = dataptr;
398 const char* image_name = (trace_hdr->imagepath_len > 0) ? dataptr + trace_hdr->procpath_len : NULL;
399 const char* message = (trace_hdr->message_len > 0) ? dataptr + trace_hdr->procpath_len + trace_hdr->imagepath_len : NULL;
400 //const char* subsystem = (trace_hdr->subsystem_len > 0) ? dataptr + trace_hdr->procpath_len + trace_hdr->imagepath_len + trace_hdr->message_len : NULL;
401 //const char* category = (trace_hdr->category_len > 0) ? dataptr + trace_hdr->procpath_len + trace_hdr->imagepath_len + trace_hdr->message_len + trace_hdr->subsystem_len : NULL;
402
403 int shall_print = 1;
404 int trigger_off = 0;
405 const char* process_name_short = (process_name) ? strrchr(process_name, '/') : "";
406 process_name_short = (process_name_short) ? process_name_short+1 : process_name;
407 const char* image_name_short = (image_name) ? strrchr(image_name, '/') : NULL;
408 image_name_short = (image_name_short) ? image_name_short+1 : process_name;
409 if (image_name_short && !strcmp(image_name_short, process_name_short)) {
410 image_name_short = NULL;
411 }
412
413 do {
414 /* check if we have any triggers/untriggers */
415 if (num_untrigger_filters > 0 && triggered) {
416 int found = 0;
417 int i;
418 for (i = 0; i < num_untrigger_filters; i++) {
419 if (strstr(message, untrigger_filters[i])) {
420 found = 1;
421 break;
422 }
423 }
424 if (!found) {
425 shall_print = 1;
426 } else {
427 shall_print = 1;
428 trigger_off = 1;
429 }
430 } else if (num_trigger_filters > 0 && !triggered) {
431 int found = 0;
432 int i;
433 for (i = 0; i < num_trigger_filters; i++) {
434 if (strstr(message, trigger_filters[i])) {
435 found = 1;
436 break;
437 }
438 }
439 if (!found) {
440 shall_print = 0;
441 break;
442 }
443 triggered = 1;
444 shall_print = 1;
445 } else if (num_trigger_filters == 0 && num_untrigger_filters > 0 && !triggered) {
446 shall_print = 0;
447 quit_flag++;
448 break;
449 }
450
451 /* check message filters */
452 shall_print = message_filter_matching(message);
453 if (!shall_print) {
454 break;
455 }
456
457 /* check process filters */
458 if (process_filter_matching(trace_hdr->pid, process_name_short, strlen(process_name_short))) {
459 shall_print = 1;
460 } else {
461 if (num_pid_filters > 0 || num_proc_filters > 0) {
462 shall_print = 0;
463 }
464 }
465 if (!shall_print) {
466 break;
467 }
468 } while (0);
469
470 if (!shall_print) {
471 return;
472 }
473
474 const char* level_str = "Unknown";
475 const char* level_color = FG_YELLOW;
476 switch (trace_hdr->level) {
477 case 0:
478 level_str = "Notice";
479 level_color = FG_GREEN;
480 break;
481 case 0x01:
482 level_str = "Info";
483 level_color = FG_WHITE;
484 break;
485 case 0x02:
486 level_str = "Debug";
487 level_color = FG_MAGENTA;
488 break;
489 case 0x10:
490 level_str = "Error";
491 level_color = FG_RED;
492 break;
493 case 0x11:
494 level_str = "Fault";
495 level_color = FG_RED;
496 default:
497 break;
498 }
499
500 char datebuf[24];
501 struct tm *tp;
502 time_t time_sec = (time_t)trace_hdr->time_sec;
503 #ifdef HAVE_LOCALTIME_R
504 struct tm tp_ = {0, };
505 tp = localtime_r(&time_sec, &tp_);
506 #else
507 tp = localtime(&time_sec);
508 #endif
509 #ifdef _WIN32
510 strftime(datebuf, 16, "%b %#d %H:%M:%S", tp);
511 #else
512 strftime(datebuf, 16, "%b %e %H:%M:%S", tp);
513 #endif
514 snprintf(datebuf+15, 9, ".%06u", trace_hdr->time_usec);
515
516 /* write date and time */
517 cprintf(FG_LIGHT_GRAY "%s ", datebuf);
518
519 if (show_device_name) {
520 /* write device name TODO do we need this? */
521 //cprintf(FG_DARK_YELLOW "%s ", device_name);
522 }
523
524 /* write process name */
525 cprintf(FG_BRIGHT_CYAN "%s" FG_CYAN, process_name_short);
526 if (image_name_short) {
527 cprintf("(%s)", image_name_short);
528 }
529 cprintf("[%d]" COLOR_RESET " ", trace_hdr->pid);
530
531 /* write log level */
532 cprintf(level_color);
533 cprintf("<%s>:" COLOR_RESET " ", level_str);
534
535 /* write message */
536 cprintf(FG_WHITE);
537 cprintf("%s" COLOR_RESET "\n", message);
538 fflush(stdout);
539
540 if (trigger_off) {
541 triggered = 0;
542 }
543 }
544
545 static plist_t get_pid_list()
546 {
547 plist_t list = NULL;
548 ostrace_client_t ostrace_tmp = NULL;
549 ostrace_client_start_service(device, &ostrace_tmp, TOOL_NAME);
550 if (ostrace_tmp) {
551 ostrace_get_pid_list(ostrace_tmp, &list);
552 ostrace_client_free(ostrace_tmp);
553 }
554 return list;
555 }
556
557 static int pid_valid(int pid)
558 {
559 plist_t list = get_pid_list();
560 if (!list) return 0;
561 char valbuf[16];
562 snprintf(valbuf, 16, "%d", pid);
563 return (plist_dict_get_item(list, valbuf)) ? 1 : 0;
564 }
565
566 static int pid_for_proc(const char* procname)
567 {
568 int result = -1;
569 plist_t list = get_pid_list();
570 if (!list) {
571 return result;
572 }
573 plist_dict_iter iter = NULL;
574 plist_dict_new_iter(list, &iter);
575 if (iter) {
576 plist_t node = NULL;
577 do {
578 char* key = NULL;
579 node = NULL;
580 plist_dict_next_item(list, iter, &key, &node);
581 if (!key) {
582 break;
583 }
584 if (PLIST_IS_DICT(node)) {
585 plist_t pname = plist_dict_get_item(node, "ProcessName");
586 if (PLIST_IS_STRING(pname)) {
587 if (!strcmp(plist_get_string_ptr(pname, NULL), procname)) {
588 result = (int)strtol(key, NULL, 10);
589 }
590 }
591 }
592 free(key);
593 } while (node);
594 plist_mem_free(iter);
595 }
596 plist_free(list);
597 return result;
598 }
599
600 static int connect_service(int ostrace_required)
601 {
602 if (!device) {
603 idevice_error_t ret = idevice_new_with_options(&device, udid, (use_network) ? IDEVICE_LOOKUP_NETWORK : IDEVICE_LOOKUP_USBMUX);
604 if (ret != IDEVICE_E_SUCCESS) {
605 fprintf(stderr, "Device with udid %s not found!?\n", udid);
606 return -1;
607 }
608 }
609
610 lockdownd_client_t lockdown = NULL;
611 lockdownd_error_t lerr = lockdownd_client_new_with_handshake(device, &lockdown, TOOL_NAME);
612 if (lerr != LOCKDOWN_E_SUCCESS) {
613 fprintf(stderr, "ERROR: Could not connect to lockdownd: %d\n", lerr);
614 idevice_free(device);
615 device = NULL;
616 return -1;
617 }
618 lockdownd_service_descriptor_t svc = NULL;
619
620 const char* service_name = OSTRACE_SERVICE_NAME;
621 int use_ostrace = 1;
622 if (idevice_get_device_version(device) < IDEVICE_DEVICE_VERSION(9,0,0) || force_syslog_relay) {
623 service_name = SYSLOG_RELAY_SERVICE_NAME;
624 use_ostrace = 0;
625 }
626 if (ostrace_required && !use_ostrace) {
627 fprintf(stderr, "ERROR: This operation requires iOS 9 or later.\n");
628 lockdownd_client_free(lockdown);
629 idevice_free(device);
630 device = NULL;
631 return -1;
632 }
633
634 /* start syslog_relay/os_trace_relay service */
635 lerr = lockdownd_start_service(lockdown, service_name, &svc);
636 if (lerr == LOCKDOWN_E_PASSWORD_PROTECTED) {
637 fprintf(stderr, "*** Device is passcode protected, enter passcode on the device to continue ***\n");
638 while (!quit_flag) {
639 lerr = lockdownd_start_service(lockdown, service_name, &svc);
640 if (lerr != LOCKDOWN_E_PASSWORD_PROTECTED) {
641 break;
642 }
643 sleep(1);
644 }
645 }
646 if (lerr != LOCKDOWN_E_SUCCESS) {
647 fprintf(stderr, "ERROR: Could not start %s service: %s (%d)\n", service_name, lockdownd_strerror(lerr), lerr);
648 idevice_free(device);
649 device = NULL;
650 return -1;
651 }
652 lockdownd_client_free(lockdown);
653
654 if (use_ostrace) {
655 /* connect to os_trace_relay service */
656 ostrace_error_t serr = OSTRACE_E_UNKNOWN_ERROR;
657 serr = ostrace_client_new(device, svc, &ostrace);
658 lockdownd_service_descriptor_free(svc);
659 if (serr != OSTRACE_E_SUCCESS) {
660 fprintf(stderr, "ERROR: Could not connect to %s service (%d)\n", service_name, serr);
661 idevice_free(device);
662 device = NULL;
663 return -1;
664 }
665 } else {
666 /* connect to syslog_relay service */
667 syslog_relay_error_t serr = SYSLOG_RELAY_E_UNKNOWN_ERROR;
668 serr = syslog_relay_client_new(device, svc, &syslog);
669 lockdownd_service_descriptor_free(svc);
670 if (serr != SYSLOG_RELAY_E_SUCCESS) {
671 fprintf(stderr, "ERROR: Could not connect to %s service (%d)\n", service_name, serr);
672 idevice_free(device);
673 device = NULL;
674 return -1;
675 }
676 }
677 return 0;
678 }
679
680 static int start_logging(void)
681 {
682 if (connect_service(0) < 0) {
683 return -1;
684 }
685
686 /* start capturing syslog */
687 if (ostrace) {
688 plist_t options = plist_new_dict();
689 if (num_proc_filters == 0 && num_pid_filters == 1 && !proc_filter_excluding) {
690 if (pid_filters[0] > 0) {
691 if (!pid_valid(pid_filters[0])) {
692 fprintf(stderr, "NOTE: A process with pid doesn't exists!\n");
693 }
694 }
695 plist_dict_set_item(options, "Pid", plist_new_int(pid_filters[0]));
696 } else if (num_proc_filters == 1 && num_pid_filters == 0 && !proc_filter_excluding) {
697 int pid = pid_for_proc(proc_filters[0]);
698 if (!strcmp(proc_filters[0], "kernel")) {
699 pid = 0;
700 }
701 if (pid >= 0) {
702 plist_dict_set_item(options, "Pid", plist_new_int(pid));
703 }
704 }
705 ostrace_error_t serr = ostrace_start_activity(ostrace, options, ostrace_syslog_callback, NULL);
706 if (serr != OSTRACE_E_SUCCESS) {
707 fprintf(stderr, "ERROR: Unable to start capturing syslog.\n");
708 ostrace_client_free(ostrace);
709 ostrace = NULL;
710 idevice_free(device);
711 device = NULL;
712 return -1;
713 }
714 } else if (syslog) {
715 syslog_relay_error_t serr = syslog_relay_start_capture_raw(syslog, syslog_callback, NULL);
716 if (serr != SYSLOG_RELAY_E_SUCCESS) {
717 fprintf(stderr, "ERROR: Unable to start capturing syslog.\n");
718 syslog_relay_client_free(syslog);
719 syslog = NULL;
720 idevice_free(device);
721 device = NULL;
722 return -1;
723 }
724 } else {
725 return -1;
726 }
727
728 fprintf(stdout, "[connected:%s]\n", udid);
729 fflush(stdout);
730
731 return 0;
732 }
733
734 static void stop_logging(void)
735 {
736 fflush(stdout);
737
738 if (syslog) {
739 syslog_relay_client_free(syslog);
740 syslog = NULL;
741 }
742 if (ostrace) {
743 ostrace_stop_activity(ostrace);
744 ostrace_client_free(ostrace);
745 ostrace = NULL;
746 }
747
748 if (device) {
749 idevice_free(device);
750 device = NULL;
751 }
752 }
753
754 static int write_callback(const void* buf, size_t len, void *user_data)
755 {
756 FILE* f = (FILE*)user_data;
757 ssize_t res = fwrite(buf, 1, len, f);
758 if (res < 0) {
759 return -1;
760 }
761 if (quit_flag > 0) {
762 return -1;
763 }
764 return 0;
765 }
766
767 static void print_sorted_pidlist(plist_t list)
768 {
769 struct listelem;
770 struct listelem {
771 int val;
772 struct listelem *next;
773 };
774 struct listelem* sortedlist = NULL;
775
776 plist_dict_iter iter = NULL;
777 plist_dict_new_iter(list, &iter);
778 if (iter) {
779 plist_t node = NULL;
780 do {
781 char* key = NULL;
782 node = NULL;
783 plist_dict_next_item(list, iter, &key, &node);
784 if (key) {
785 int pidval = (int)strtol(key, NULL, 10);
786 struct listelem* elem = (struct listelem*)malloc(sizeof(struct listelem));
787 elem->val = pidval;
788 elem->next = NULL;
789 struct listelem* prev = NULL;
790 struct listelem* curr = sortedlist;
791
792 while (curr && pidval > curr->val) {
793 prev = curr;
794 curr = curr->next;
795 }
796
797 elem->next = curr;
798 if (prev == NULL) {
799 sortedlist = elem;
800 } else {
801 prev->next = elem;
802 }
803 free(key);
804 }
805 } while (node);
806 plist_mem_free(iter);
807 }
808 struct listelem *listp = sortedlist;
809 char pidstr[16];
810 while (listp) {
811 snprintf(pidstr, 16, "%d", listp->val);
812 plist_t node = plist_dict_get_item(list, pidstr);
813 if (PLIST_IS_DICT(node)) {
814 plist_t pname = plist_dict_get_item(node, "ProcessName");
815 if (PLIST_IS_STRING(pname)) {
816 printf("%d %s\n", listp->val, plist_get_string_ptr(pname, NULL));
817 }
818 }
819 struct listelem *curr = listp;
820 listp = listp->next;
821 free(curr);
822 }
823 }
824
825 static void device_event_cb(const idevice_event_t* event, void* userdata)
826 {
827 if (use_network && event->conn_type != CONNECTION_NETWORK) {
828 return;
829 }
830 if (!use_network && event->conn_type != CONNECTION_USBMUXD) {
831 return;
832 }
833 if (event->event == IDEVICE_DEVICE_ADD) {
834 if (!syslog && !ostrace) {
835 if (!udid) {
836 udid = strdup(event->udid);
837 }
838 if (strcmp(udid, event->udid) == 0) {
839 if (start_logging() != 0) {
840 fprintf(stderr, "Could not start logger for udid %s\n", udid);
841 }
842 }
843 }
844 } else if (event->event == IDEVICE_DEVICE_REMOVE) {
845 if ((syslog || ostrace) && (strcmp(udid, event->udid) == 0)) {
846 stop_logging();
847 fprintf(stdout, "[disconnected:%s]\n", udid);
848 if (exit_on_disconnect) {
849 quit_flag++;
850 }
851 }
852 }
853 }
854
855 /**
856 * signal handler function for cleaning up properly
857 */
858 static void clean_exit(int sig)
859 {
860 fprintf(stderr, "\nExiting...\n");
861 quit_flag++;
862 }
863
864 static void print_usage(int argc, char **argv, int is_error)
865 {
866 char *name = strrchr(argv[0], '/');
867 fprintf(is_error ? stderr : stdout, "Usage: %s [OPTIONS]\n", (name ? name + 1: argv[0]));
868 fprintf(is_error ? stderr : stdout,
869 "\n"
870 "Relay syslog of a connected device.\n"
871 "\n"
872 "OPTIONS:\n"
873 " -u, --udid UDID target specific device by UDID\n"
874 " -n, --network connect to network device\n"
875 " -x, --exit exit when device disconnects\n"
876 " -h, --help prints usage information\n"
877 " -d, --debug enable communication debugging\n"
878 " -v, --version prints version information\n"
879 " --no-colors disable colored output\n"
880 " -o, --output FILE write to FILE instead of stdout\n"
881 " (existing FILE will be overwritten)\n"
882 " --colors force writing colored output, e.g. for --output\n"
883 " --syslog-relay force use of syslog_relay service\n"
884 "\n"
885 "COMMANDS:\n"
886 " pidlist Print pid and name of all running processes.\n"
887 " archive PATH Request a logarchive and write it to PATH.\n"
888 " Output can be piped to another process using - as PATH.\n"
889 " The file data will be in .tar format.\n"
890 " --start-time VALUE start time of the log data as UNIX timestamp\n"
891 " --age-limit VALUE maximum age of the log data\n"
892 " --size-limit VALUE limit the size of the archive\n"
893 "\n"
894 "FILTER OPTIONS:\n"
895 " -m, --match STRING only print messages that contain STRING\n"
896 " -M, --unmatch STRING print messages that not contain STRING\n"
897 " -t, --trigger STRING start logging when matching STRING\n"
898 " -T, --untrigger STRING stop logging when matching STRING\n"
899 " -p, --process PROCESS only print messages from matching process(es)\n"
900 " -e, --exclude PROCESS print all messages except matching process(es)\n"
901 " PROCESS is a process name or multiple process names\n"
902 " separated by \"|\".\n"
903 " -q, --quiet set a filter to exclude common noisy processes\n"
904 " --quiet-list prints the list of processes for --quiet and exits\n"
905 " -k, --kernel only print kernel messages\n"
906 " -K, --no-kernel suppress kernel messages\n"
907 "\n"
908 "For filter examples consult idevicesyslog(1) man page.\n"
909 "\n"
910 "Homepage: <" PACKAGE_URL ">\n"
911 "Bug Reports: <" PACKAGE_BUGREPORT ">\n"
912 );
913 }
914
915 int main(int argc, char *argv[])
916 {
917 int include_filter = 0;
918 int exclude_filter = 0;
919 int include_kernel = 0;
920 int exclude_kernel = 0;
921 int force_colors = 0;
922 int c = 0;
923 const struct option longopts[] = {
924 { "debug", no_argument, NULL, 'd' },
925 { "help", no_argument, NULL, 'h' },
926 { "udid", required_argument, NULL, 'u' },
927 { "network", no_argument, NULL, 'n' },
928 { "exit", no_argument, NULL, 'x' },
929 { "trigger", required_argument, NULL, 't' },
930 { "untrigger", required_argument, NULL, 'T' },
931 { "match", required_argument, NULL, 'm' },
932 { "process", required_argument, NULL, 'p' },
933 { "exclude", required_argument, NULL, 'e' },
934 { "quiet", no_argument, NULL, 'q' },
935 { "kernel", no_argument, NULL, 'k' },
936 { "no-kernel", no_argument, NULL, 'K' },
937 { "quiet-list", no_argument, NULL, 1 },
938 { "no-colors", no_argument, NULL, 2 },
939 { "colors", no_argument, NULL, 3 },
940 { "syslog_relay", no_argument, NULL, 4 },
941 { "syslog-relay", no_argument, NULL, 4 },
942 { "legacy", no_argument, NULL, 4 },
943 { "start-time", required_argument, NULL, 5 },
944 { "size-limit", required_argument, NULL, 6 },
945 { "age-limit", required_argument, NULL, 7 },
946 { "output", required_argument, NULL, 'o' },
947 { "version", no_argument, NULL, 'v' },
948 { NULL, 0, NULL, 0}
949 };
950
951 signal(SIGINT, clean_exit);
952 signal(SIGTERM, clean_exit);
953 #ifndef _WIN32
954 signal(SIGQUIT, clean_exit);
955 signal(SIGPIPE, SIG_IGN);
956 #endif
957
958 while ((c = getopt_long(argc, argv, "dhu:nxt:T:m:M:e:p:qkKo:v", longopts, NULL)) != -1) {
959 switch (c) {
960 case 'd':
961 idevice_set_debug_level(1);
962 break;
963 case 'u':
964 if (!*optarg) {
965 fprintf(stderr, "ERROR: UDID must not be empty!\n");
966 print_usage(argc, argv, 1);
967 return 2;
968 }
969 free(udid);
970 udid = strdup(optarg);
971 break;
972 case 'n':
973 use_network = 1;
974 break;
975 case 'q':
976 exclude_filter++;
977 add_filter(QUIET_FILTER);
978 break;
979 case 'p':
980 case 'e':
981 if (c == 'p') {
982 include_filter++;
983 } else if (c == 'e') {
984 exclude_filter++;
985 }
986 if (!*optarg) {
987 fprintf(stderr, "ERROR: filter string must not be empty!\n");
988 print_usage(argc, argv, 1);
989 return 2;
990 }
991 add_filter(optarg);
992 break;
993 case 'm':
994 if (!*optarg) {
995 fprintf(stderr, "ERROR: message filter string must not be empty!\n");
996 print_usage(argc, argv, 1);
997 return 2;
998 } else {
999 char **new_msg_filters = realloc(msg_filters, sizeof(char*) * (num_msg_filters+1));
1000 if (!new_msg_filters) {
1001 fprintf(stderr, "ERROR: realloc() failed\n");
1002 exit(EXIT_FAILURE);
1003 }
1004 msg_filters = new_msg_filters;
1005 msg_filters[num_msg_filters] = strdup(optarg);
1006 num_msg_filters++;
1007 }
1008 break;
1009 case 'M':
1010 if (!*optarg) {
1011 fprintf(stderr, "ERROR: reverse message filter string must not be empty!\n");
1012 print_usage(argc, argv, 1);
1013 return 2;
1014 } else {
1015 char **new_msg_filters = realloc(msg_reverse_filters, sizeof(char*) * (num_msg_reverse_filters+1));
1016 if (!new_msg_filters) {
1017 fprintf(stderr, "ERROR: realloc() failed\n");
1018 exit(EXIT_FAILURE);
1019 }
1020 msg_reverse_filters = new_msg_filters;
1021 msg_reverse_filters[num_msg_reverse_filters] = strdup(optarg);
1022 num_msg_reverse_filters++;
1023 }
1024 break;
1025 case 't':
1026 if (!*optarg) {
1027 fprintf(stderr, "ERROR: trigger filter string must not be empty!\n");
1028 print_usage(argc, argv, 1);
1029 return 2;
1030 } else {
1031 char **new_trigger_filters = realloc(trigger_filters, sizeof(char*) * (num_trigger_filters+1));
1032 if (!new_trigger_filters) {
1033 fprintf(stderr, "ERROR: realloc() failed\n");
1034 exit(EXIT_FAILURE);
1035 }
1036 trigger_filters = new_trigger_filters;
1037 trigger_filters[num_trigger_filters] = strdup(optarg);
1038 num_trigger_filters++;
1039 }
1040 break;
1041 case 'T':
1042 if (!*optarg) {
1043 fprintf(stderr, "ERROR: untrigger filter string must not be empty!\n");
1044 print_usage(argc, argv, 1);
1045 return 2;
1046 } else {
1047 char **new_untrigger_filters = realloc(untrigger_filters, sizeof(char*) * (num_untrigger_filters+1));
1048 if (!new_untrigger_filters) {
1049 fprintf(stderr, "ERROR: realloc() failed\n");
1050 exit(EXIT_FAILURE);
1051 }
1052 untrigger_filters = new_untrigger_filters;
1053 untrigger_filters[num_untrigger_filters] = strdup(optarg);
1054 num_untrigger_filters++;
1055 }
1056 break;
1057 case 'k':
1058 include_kernel++;
1059 break;
1060 case 'K':
1061 exclude_kernel++;
1062 break;
1063 case 'x':
1064 exit_on_disconnect = 1;
1065 break;
1066 case 'h':
1067 print_usage(argc, argv, 0);
1068 return 0;
1069 case 1: {
1070 printf("%s\n", QUIET_FILTER);
1071 return 0;
1072 }
1073 case 2:
1074 term_colors_set_enabled(0);
1075 break;
1076 case 3:
1077 force_colors = 1;
1078 break;
1079 case 4:
1080 force_syslog_relay = 1;
1081 break;
1082 case 5:
1083 start_time = strtoll(optarg, NULL, 10);
1084 break;
1085 case 6:
1086 size_limit = strtoll(optarg, NULL, 10);
1087 break;
1088 case 7:
1089 age_limit = strtoll(optarg, NULL, 10);
1090 break;
1091 case 'o':
1092 if (!*optarg) {
1093 fprintf(stderr, "ERROR: --output option requires an argument!\n");
1094 print_usage(argc, argv, 1);
1095 return 2;
1096 } else {
1097 if (freopen(optarg, "w", stdout) == NULL) {
1098 fprintf(stderr, "ERROR: Failed to open output file '%s' for writing: %s\n", optarg, strerror(errno));
1099 return 1;
1100 }
1101 term_colors_set_enabled(0);
1102 }
1103 break;
1104 case 'v':
1105 printf("%s %s\n", TOOL_NAME, PACKAGE_VERSION);
1106 return 0;
1107 default:
1108 print_usage(argc, argv, 1);
1109 return 2;
1110 }
1111 }
1112
1113 if (force_colors) {
1114 term_colors_set_enabled(1);
1115 }
1116
1117 if (include_kernel > 0 && exclude_kernel > 0) {
1118 fprintf(stderr, "ERROR: -k and -K cannot be used together.\n");
1119 print_usage(argc, argv, 1);
1120 return 2;
1121 }
1122
1123 if (include_filter > 0 && exclude_filter > 0) {
1124 fprintf(stderr, "ERROR: -p and -e/-q cannot be used together.\n");
1125 print_usage(argc, argv, 1);
1126 return 2;
1127 }
1128 if (include_filter > 0 && exclude_kernel > 0) {
1129 fprintf(stderr, "ERROR: -p and -K cannot be used together.\n");
1130 print_usage(argc, argv, 1);
1131 return 2;
1132 }
1133
1134 if (exclude_filter > 0) {
1135 proc_filter_excluding = 1;
1136 if (include_kernel) {
1137 int i = 0;
1138 for (i = 0; i < num_proc_filters; i++) {
1139 if (!strcmp(proc_filters[i], "kernel")) {
1140 free(proc_filters[i]);
1141 proc_filters[i] = NULL;
1142 }
1143 }
1144 } else if (exclude_kernel) {
1145 add_filter("kernel");
1146 }
1147 } else {
1148 if (include_kernel) {
1149 add_filter("kernel");
1150 } else if (exclude_kernel) {
1151 proc_filter_excluding = 1;
1152 add_filter("kernel");
1153 }
1154 }
1155
1156 if (num_untrigger_filters > 0 && num_trigger_filters == 0) {
1157 triggered = 1;
1158 }
1159
1160 argc -= optind;
1161 argv += optind;
1162
1163 if (argc > 0) {
1164 if (!strcmp(argv[0], "pidlist")) {
1165 if (connect_service(1) < 0) {
1166 return 1;
1167 }
1168 plist_t list = NULL;
1169 ostrace_get_pid_list(ostrace, &list);
1170 ostrace_client_free(ostrace);
1171 ostrace = NULL;
1172 idevice_free(device);
1173 device = NULL;
1174 if (!list) {
1175 return 1;
1176 }
1177 print_sorted_pidlist(list);
1178 plist_free(list);
1179 return 0;
1180 } else if (!strcmp(argv[0], "archive")) {
1181 if (force_syslog_relay) {
1182 force_syslog_relay = 0;
1183 }
1184 if (argc < 2) {
1185 fprintf(stderr, "Please specify an output filename.\n");
1186 return 1;
1187 }
1188 FILE* outf = NULL;
1189 if (!strcmp(argv[1], "-")) {
1190 if (isatty(1)) {
1191 fprintf(stderr, "Refusing to directly write to stdout. Pipe the output to another process.\n");
1192 return 1;
1193 }
1194 outf = stdout;
1195 } else {
1196 outf = fopen(argv[1], "w");
1197 }
1198 if (!outf) {
1199 fprintf(stderr, "Failed to open %s: %s\n", argv[1], strerror(errno));
1200 return 1;
1201 }
1202 if (connect_service(1) < 0) {
1203 if (outf != stdout) {
1204 fclose(outf);
1205 }
1206 return 1;
1207 }
1208 plist_t options = plist_new_dict();
1209 if (start_time > 0) {
1210 plist_dict_set_item(options, "StartTime", plist_new_int(start_time));
1211 }
1212 if (size_limit > 0) {
1213 plist_dict_set_item(options, "SizeLimit", plist_new_int(size_limit));
1214 }
1215 if (age_limit > 0) {
1216 plist_dict_set_item(options, "AgeLimit", plist_new_int(age_limit));
1217 }
1218 ostrace_create_archive(ostrace, options, write_callback, outf);
1219 ostrace_client_free(ostrace);
1220 ostrace = NULL;
1221 idevice_free(device);
1222 device = NULL;
1223 if (outf != stdout) {
1224 fclose(outf);
1225 }
1226 return 0;
1227 } else {
1228 fprintf(stderr, "Unknown command '%s'. See --help for valid commands.\n", argv[0]);
1229 return 1;
1230 }
1231 }
1232
1233 int num = 0;
1234 idevice_info_t *devices = NULL;
1235 idevice_get_device_list_extended(&devices, &num);
1236 int count = 0;
1237 for (int i = 0; i < num; i++) {
1238 if (devices[i]->conn_type == CONNECTION_NETWORK && use_network) {
1239 count++;
1240 } else if (devices[i]->conn_type == CONNECTION_USBMUXD) {
1241 count++;
1242 }
1243 }
1244 idevice_device_list_extended_free(devices);
1245 if (count == 0) {
1246 if (!udid) {
1247 fprintf(stderr, "No device found. Plug in a device or pass UDID with -u to wait for device to become available.\n");
1248 return 1;
1249 }
1250
1251 fprintf(stderr, "Waiting for device with UDID %s to become available...\n", udid);
1252 }
1253
1254 line_buffer_size = 1024;
1255 line = malloc(line_buffer_size);
1256
1257 idevice_subscription_context_t context = NULL;
1258 idevice_events_subscribe(&context, device_event_cb, NULL);
1259
1260 while (!quit_flag) {
1261 sleep(1);
1262 }
1263 idevice_events_unsubscribe(context);
1264 stop_logging();
1265
1266 if (num_proc_filters > 0) {
1267 int i;
1268 for (i = 0; i < num_proc_filters; i++) {
1269 free(proc_filters[i]);
1270 }
1271 free(proc_filters);
1272 }
1273 if (num_pid_filters > 0) {
1274 free(pid_filters);
1275 }
1276 if (num_msg_filters > 0) {
1277 int i;
1278 for (i = 0; i < num_msg_filters; i++) {
1279 free(msg_filters[i]);
1280 }
1281 free(msg_filters);
1282 }
1283 if (num_msg_reverse_filters > 0) {
1284 int i;
1285 for (i = 0; i < num_msg_reverse_filters; i++) {
1286 free(msg_reverse_filters[i]);
1287 }
1288 free(msg_reverse_filters);
1289 }
1290 if (num_trigger_filters > 0) {
1291 int i;
1292 for (i = 0; i < num_trigger_filters; i++) {
1293 free(trigger_filters[i]);
1294 }
1295 free(trigger_filters);
1296 }
1297 if (num_untrigger_filters > 0) {
1298 int i;
1299 for (i = 0; i < num_untrigger_filters; i++) {
1300 free(untrigger_filters[i]);
1301 }
1302 free(untrigger_filters);
1303 }
1304
1305 free(line);
1306
1307 free(udid);
1308
1309 return 0;
1310 }