Fix: status_loc argument of waitpid() is used on error
[lttng-tools.git] / src / bin / lttng-sessiond / main.c
1 /*
2 * Copyright (C) 2011 - David Goulet <david.goulet@polymtl.ca>
3 * Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License, version 2 only,
8 * as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #define _LGPL_SOURCE
21 #include <getopt.h>
22 #include <grp.h>
23 #include <limits.h>
24 #include <paths.h>
25 #include <pthread.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <inttypes.h>
31 #include <sys/mman.h>
32 #include <sys/mount.h>
33 #include <sys/resource.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <urcu/uatomic.h>
39 #include <unistd.h>
40 #include <ctype.h>
41
42 #include <common/common.h>
43 #include <common/compat/socket.h>
44 #include <common/compat/getenv.h>
45 #include <common/defaults.h>
46 #include <common/kernel-consumer/kernel-consumer.h>
47 #include <common/futex.h>
48 #include <common/relayd/relayd.h>
49 #include <common/utils.h>
50 #include <common/daemonize.h>
51 #include <common/config/session-config.h>
52
53 #include "lttng-sessiond.h"
54 #include "buffer-registry.h"
55 #include "channel.h"
56 #include "cmd.h"
57 #include "consumer.h"
58 #include "context.h"
59 #include "event.h"
60 #include "kernel.h"
61 #include "kernel-consumer.h"
62 #include "modprobe.h"
63 #include "shm.h"
64 #include "ust-ctl.h"
65 #include "ust-consumer.h"
66 #include "utils.h"
67 #include "fd-limit.h"
68 #include "health-sessiond.h"
69 #include "testpoint.h"
70 #include "ust-thread.h"
71 #include "agent-thread.h"
72 #include "save.h"
73 #include "load-session-thread.h"
74 #include "syscall.h"
75 #include "agent.h"
76 #include "ht-cleanup.h"
77
78 #define CONSUMERD_FILE "lttng-consumerd"
79
80 const char *progname;
81 static const char *tracing_group_name = DEFAULT_TRACING_GROUP;
82 static int tracing_group_name_override;
83 static char *opt_pidfile;
84 static int opt_sig_parent;
85 static int opt_verbose_consumer;
86 static int opt_daemon, opt_background;
87 static int opt_no_kernel;
88 static char *opt_load_session_path;
89 static pid_t ppid; /* Parent PID for --sig-parent option */
90 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
91 static char *rundir;
92 static int lockfile_fd = -1;
93
94 /* Set to 1 when a SIGUSR1 signal is received. */
95 static int recv_child_signal;
96
97 /*
98 * Consumer daemon specific control data. Every value not initialized here is
99 * set to 0 by the static definition.
100 */
101 static struct consumer_data kconsumer_data = {
102 .type = LTTNG_CONSUMER_KERNEL,
103 .err_unix_sock_path = DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
104 .cmd_unix_sock_path = DEFAULT_KCONSUMERD_CMD_SOCK_PATH,
105 .err_sock = -1,
106 .cmd_sock = -1,
107 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
108 .lock = PTHREAD_MUTEX_INITIALIZER,
109 .cond = PTHREAD_COND_INITIALIZER,
110 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
111 };
112 static struct consumer_data ustconsumer64_data = {
113 .type = LTTNG_CONSUMER64_UST,
114 .err_unix_sock_path = DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
115 .cmd_unix_sock_path = DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH,
116 .err_sock = -1,
117 .cmd_sock = -1,
118 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
119 .lock = PTHREAD_MUTEX_INITIALIZER,
120 .cond = PTHREAD_COND_INITIALIZER,
121 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
122 };
123 static struct consumer_data ustconsumer32_data = {
124 .type = LTTNG_CONSUMER32_UST,
125 .err_unix_sock_path = DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
126 .cmd_unix_sock_path = DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH,
127 .err_sock = -1,
128 .cmd_sock = -1,
129 .pid_mutex = PTHREAD_MUTEX_INITIALIZER,
130 .lock = PTHREAD_MUTEX_INITIALIZER,
131 .cond = PTHREAD_COND_INITIALIZER,
132 .cond_mutex = PTHREAD_MUTEX_INITIALIZER,
133 };
134
135 /* Command line options */
136 static const struct option long_options[] = {
137 { "client-sock", required_argument, 0, 'c' },
138 { "apps-sock", required_argument, 0, 'a' },
139 { "kconsumerd-cmd-sock", required_argument, 0, '\0' },
140 { "kconsumerd-err-sock", required_argument, 0, '\0' },
141 { "ustconsumerd32-cmd-sock", required_argument, 0, '\0' },
142 { "ustconsumerd32-err-sock", required_argument, 0, '\0' },
143 { "ustconsumerd64-cmd-sock", required_argument, 0, '\0' },
144 { "ustconsumerd64-err-sock", required_argument, 0, '\0' },
145 { "consumerd32-path", required_argument, 0, '\0' },
146 { "consumerd32-libdir", required_argument, 0, '\0' },
147 { "consumerd64-path", required_argument, 0, '\0' },
148 { "consumerd64-libdir", required_argument, 0, '\0' },
149 { "daemonize", no_argument, 0, 'd' },
150 { "background", no_argument, 0, 'b' },
151 { "sig-parent", no_argument, 0, 'S' },
152 { "help", no_argument, 0, 'h' },
153 { "group", required_argument, 0, 'g' },
154 { "version", no_argument, 0, 'V' },
155 { "quiet", no_argument, 0, 'q' },
156 { "verbose", no_argument, 0, 'v' },
157 { "verbose-consumer", no_argument, 0, '\0' },
158 { "no-kernel", no_argument, 0, '\0' },
159 { "pidfile", required_argument, 0, 'p' },
160 { "agent-tcp-port", required_argument, 0, '\0' },
161 { "config", required_argument, 0, 'f' },
162 { "load", required_argument, 0, 'l' },
163 { "kmod-probes", required_argument, 0, '\0' },
164 { "extra-kmod-probes", required_argument, 0, '\0' },
165 { NULL, 0, 0, 0 }
166 };
167
168 /* Command line options to ignore from configuration file */
169 static const char *config_ignore_options[] = { "help", "version", "config" };
170
171 /* Shared between threads */
172 static int dispatch_thread_exit;
173
174 /* Global application Unix socket path */
175 static char apps_unix_sock_path[PATH_MAX];
176 /* Global client Unix socket path */
177 static char client_unix_sock_path[PATH_MAX];
178 /* global wait shm path for UST */
179 static char wait_shm_path[PATH_MAX];
180 /* Global health check unix path */
181 static char health_unix_sock_path[PATH_MAX];
182
183 /* Sockets and FDs */
184 static int client_sock = -1;
185 static int apps_sock = -1;
186 int kernel_tracer_fd = -1;
187 static int kernel_poll_pipe[2] = { -1, -1 };
188
189 /*
190 * Quit pipe for all threads. This permits a single cancellation point
191 * for all threads when receiving an event on the pipe.
192 */
193 static int thread_quit_pipe[2] = { -1, -1 };
194
195 /*
196 * This pipe is used to inform the thread managing application communication
197 * that a command is queued and ready to be processed.
198 */
199 static int apps_cmd_pipe[2] = { -1, -1 };
200
201 int apps_cmd_notify_pipe[2] = { -1, -1 };
202
203 /* Pthread, Mutexes and Semaphores */
204 static pthread_t apps_thread;
205 static pthread_t apps_notify_thread;
206 static pthread_t reg_apps_thread;
207 static pthread_t client_thread;
208 static pthread_t kernel_thread;
209 static pthread_t dispatch_thread;
210 static pthread_t health_thread;
211 static pthread_t ht_cleanup_thread;
212 static pthread_t agent_reg_thread;
213 static pthread_t load_session_thread;
214
215 /*
216 * UST registration command queue. This queue is tied with a futex and uses a N
217 * wakers / 1 waiter implemented and detailed in futex.c/.h
218 *
219 * The thread_registration_apps and thread_dispatch_ust_registration uses this
220 * queue along with the wait/wake scheme. The thread_manage_apps receives down
221 * the line new application socket and monitors it for any I/O error or clean
222 * close that triggers an unregistration of the application.
223 */
224 static struct ust_cmd_queue ust_cmd_queue;
225
226 /*
227 * Pointer initialized before thread creation.
228 *
229 * This points to the tracing session list containing the session count and a
230 * mutex lock. The lock MUST be taken if you iterate over the list. The lock
231 * MUST NOT be taken if you call a public function in session.c.
232 *
233 * The lock is nested inside the structure: session_list_ptr->lock. Please use
234 * session_lock_list and session_unlock_list for lock acquisition.
235 */
236 static struct ltt_session_list *session_list_ptr;
237
238 int ust_consumerd64_fd = -1;
239 int ust_consumerd32_fd = -1;
240
241 static const char *consumerd32_bin = CONFIG_CONSUMERD32_BIN;
242 static const char *consumerd64_bin = CONFIG_CONSUMERD64_BIN;
243 static const char *consumerd32_libdir = CONFIG_CONSUMERD32_LIBDIR;
244 static const char *consumerd64_libdir = CONFIG_CONSUMERD64_LIBDIR;
245 static int consumerd32_bin_override;
246 static int consumerd64_bin_override;
247 static int consumerd32_libdir_override;
248 static int consumerd64_libdir_override;
249
250 static const char *module_proc_lttng = "/proc/lttng";
251
252 /*
253 * Consumer daemon state which is changed when spawning it, killing it or in
254 * case of a fatal error.
255 */
256 enum consumerd_state {
257 CONSUMER_STARTED = 1,
258 CONSUMER_STOPPED = 2,
259 CONSUMER_ERROR = 3,
260 };
261
262 /*
263 * This consumer daemon state is used to validate if a client command will be
264 * able to reach the consumer. If not, the client is informed. For instance,
265 * doing a "lttng start" when the consumer state is set to ERROR will return an
266 * error to the client.
267 *
268 * The following example shows a possible race condition of this scheme:
269 *
270 * consumer thread error happens
271 * client cmd arrives
272 * client cmd checks state -> still OK
273 * consumer thread exit, sets error
274 * client cmd try to talk to consumer
275 * ...
276 *
277 * However, since the consumer is a different daemon, we have no way of making
278 * sure the command will reach it safely even with this state flag. This is why
279 * we consider that up to the state validation during command processing, the
280 * command is safe. After that, we can not guarantee the correctness of the
281 * client request vis-a-vis the consumer.
282 */
283 static enum consumerd_state ust_consumerd_state;
284 static enum consumerd_state kernel_consumerd_state;
285
286 /*
287 * Socket timeout for receiving and sending in seconds.
288 */
289 static int app_socket_timeout;
290
291 /* Set in main() with the current page size. */
292 long page_size;
293
294 /* Application health monitoring */
295 struct health_app *health_sessiond;
296
297 /* Agent TCP port for registration. Used by the agent thread. */
298 unsigned int agent_tcp_port = DEFAULT_AGENT_TCP_PORT;
299
300 /* Am I root or not. */
301 int is_root; /* Set to 1 if the daemon is running as root */
302
303 const char * const config_section_name = "sessiond";
304
305 /* Load session thread information to operate. */
306 struct load_session_thread_data *load_info;
307
308 /* Global hash tables */
309 struct lttng_ht *agent_apps_ht_by_sock = NULL;
310
311 /*
312 * Whether sessiond is ready for commands/health check requests.
313 * NR_LTTNG_SESSIOND_READY must match the number of calls to
314 * sessiond_notify_ready().
315 */
316 #define NR_LTTNG_SESSIOND_READY 3
317 int lttng_sessiond_ready = NR_LTTNG_SESSIOND_READY;
318
319 int sessiond_check_thread_quit_pipe(int fd, uint32_t events)
320 {
321 return (fd == thread_quit_pipe[0] && (events & LPOLLIN)) ? 1 : 0;
322 }
323
324 /* Notify parents that we are ready for cmd and health check */
325 LTTNG_HIDDEN
326 void sessiond_notify_ready(void)
327 {
328 if (uatomic_sub_return(&lttng_sessiond_ready, 1) == 0) {
329 /*
330 * Notify parent pid that we are ready to accept command
331 * for client side. This ppid is the one from the
332 * external process that spawned us.
333 */
334 if (opt_sig_parent) {
335 kill(ppid, SIGUSR1);
336 }
337
338 /*
339 * Notify the parent of the fork() process that we are
340 * ready.
341 */
342 if (opt_daemon || opt_background) {
343 kill(child_ppid, SIGUSR1);
344 }
345 }
346 }
347
348 static
349 void setup_consumerd_path(void)
350 {
351 const char *bin, *libdir;
352
353 /*
354 * Allow INSTALL_BIN_PATH to be used as a target path for the
355 * native architecture size consumer if CONFIG_CONSUMER*_PATH
356 * has not been defined.
357 */
358 #if (CAA_BITS_PER_LONG == 32)
359 if (!consumerd32_bin[0]) {
360 consumerd32_bin = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
361 }
362 if (!consumerd32_libdir[0]) {
363 consumerd32_libdir = INSTALL_LIB_PATH;
364 }
365 #elif (CAA_BITS_PER_LONG == 64)
366 if (!consumerd64_bin[0]) {
367 consumerd64_bin = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
368 }
369 if (!consumerd64_libdir[0]) {
370 consumerd64_libdir = INSTALL_LIB_PATH;
371 }
372 #else
373 #error "Unknown bitness"
374 #endif
375
376 /*
377 * runtime env. var. overrides the build default.
378 */
379 bin = lttng_secure_getenv("LTTNG_CONSUMERD32_BIN");
380 if (bin) {
381 consumerd32_bin = bin;
382 }
383 bin = lttng_secure_getenv("LTTNG_CONSUMERD64_BIN");
384 if (bin) {
385 consumerd64_bin = bin;
386 }
387 libdir = lttng_secure_getenv("LTTNG_CONSUMERD32_LIBDIR");
388 if (libdir) {
389 consumerd32_libdir = libdir;
390 }
391 libdir = lttng_secure_getenv("LTTNG_CONSUMERD64_LIBDIR");
392 if (libdir) {
393 consumerd64_libdir = libdir;
394 }
395 }
396
397 static
398 int __sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size,
399 int *a_pipe)
400 {
401 int ret;
402
403 assert(events);
404
405 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
406 if (ret < 0) {
407 goto error;
408 }
409
410 /* Add quit pipe */
411 ret = lttng_poll_add(events, a_pipe[0], LPOLLIN | LPOLLERR);
412 if (ret < 0) {
413 goto error;
414 }
415
416 return 0;
417
418 error:
419 return ret;
420 }
421
422 /*
423 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
424 */
425 int sessiond_set_thread_pollset(struct lttng_poll_event *events, size_t size)
426 {
427 return __sessiond_set_thread_pollset(events, size, thread_quit_pipe);
428 }
429
430 /*
431 * Init thread quit pipe.
432 *
433 * Return -1 on error or 0 if all pipes are created.
434 */
435 static int __init_thread_quit_pipe(int *a_pipe)
436 {
437 int ret, i;
438
439 ret = pipe(a_pipe);
440 if (ret < 0) {
441 PERROR("thread quit pipe");
442 goto error;
443 }
444
445 for (i = 0; i < 2; i++) {
446 ret = fcntl(a_pipe[i], F_SETFD, FD_CLOEXEC);
447 if (ret < 0) {
448 PERROR("fcntl");
449 goto error;
450 }
451 }
452
453 error:
454 return ret;
455 }
456
457 static int init_thread_quit_pipe(void)
458 {
459 return __init_thread_quit_pipe(thread_quit_pipe);
460 }
461
462 /*
463 * Stop all threads by closing the thread quit pipe.
464 */
465 static void stop_threads(void)
466 {
467 int ret;
468
469 /* Stopping all threads */
470 DBG("Terminating all threads");
471 ret = notify_thread_pipe(thread_quit_pipe[1]);
472 if (ret < 0) {
473 ERR("write error on thread quit pipe");
474 }
475
476 /* Dispatch thread */
477 CMM_STORE_SHARED(dispatch_thread_exit, 1);
478 futex_nto1_wake(&ust_cmd_queue.futex);
479 }
480
481 /*
482 * Close every consumer sockets.
483 */
484 static void close_consumer_sockets(void)
485 {
486 int ret;
487
488 if (kconsumer_data.err_sock >= 0) {
489 ret = close(kconsumer_data.err_sock);
490 if (ret < 0) {
491 PERROR("kernel consumer err_sock close");
492 }
493 }
494 if (ustconsumer32_data.err_sock >= 0) {
495 ret = close(ustconsumer32_data.err_sock);
496 if (ret < 0) {
497 PERROR("UST consumerd32 err_sock close");
498 }
499 }
500 if (ustconsumer64_data.err_sock >= 0) {
501 ret = close(ustconsumer64_data.err_sock);
502 if (ret < 0) {
503 PERROR("UST consumerd64 err_sock close");
504 }
505 }
506 if (kconsumer_data.cmd_sock >= 0) {
507 ret = close(kconsumer_data.cmd_sock);
508 if (ret < 0) {
509 PERROR("kernel consumer cmd_sock close");
510 }
511 }
512 if (ustconsumer32_data.cmd_sock >= 0) {
513 ret = close(ustconsumer32_data.cmd_sock);
514 if (ret < 0) {
515 PERROR("UST consumerd32 cmd_sock close");
516 }
517 }
518 if (ustconsumer64_data.cmd_sock >= 0) {
519 ret = close(ustconsumer64_data.cmd_sock);
520 if (ret < 0) {
521 PERROR("UST consumerd64 cmd_sock close");
522 }
523 }
524 }
525
526 /*
527 * Generate the full lock file path using the rundir.
528 *
529 * Return the snprintf() return value thus a negative value is an error.
530 */
531 static int generate_lock_file_path(char *path, size_t len)
532 {
533 int ret;
534
535 assert(path);
536 assert(rundir);
537
538 /* Build lockfile path from rundir. */
539 ret = snprintf(path, len, "%s/" DEFAULT_LTTNG_SESSIOND_LOCKFILE, rundir);
540 if (ret < 0) {
541 PERROR("snprintf lockfile path");
542 }
543
544 return ret;
545 }
546
547 /*
548 * Wait on consumer process termination.
549 *
550 * Need to be called with the consumer data lock held or from a context
551 * ensuring no concurrent access to data (e.g: cleanup).
552 */
553 static void wait_consumer(struct consumer_data *consumer_data)
554 {
555 pid_t ret;
556 int status;
557
558 if (consumer_data->pid <= 0) {
559 return;
560 }
561
562 DBG("Waiting for complete teardown of consumerd (PID: %d)",
563 consumer_data->pid);
564 ret = waitpid(consumer_data->pid, &status, 0);
565 if (ret == -1) {
566 PERROR("consumerd waitpid pid: %d", consumer_data->pid)
567 } else if (!WIFEXITED(status)) {
568 ERR("consumerd termination with error: %d",
569 WEXITSTATUS(ret));
570 }
571 consumer_data->pid = 0;
572 }
573
574 /*
575 * Cleanup the session daemon's data structures.
576 */
577 static void sessiond_cleanup(void)
578 {
579 int ret;
580 struct ltt_session *sess, *stmp;
581 char path[PATH_MAX];
582
583 DBG("Cleanup sessiond");
584
585 /*
586 * Close the thread quit pipe. It has already done its job,
587 * since we are now called.
588 */
589 utils_close_pipe(thread_quit_pipe);
590
591 /*
592 * If opt_pidfile is undefined, the default file will be wiped when
593 * removing the rundir.
594 */
595 if (opt_pidfile) {
596 ret = remove(opt_pidfile);
597 if (ret < 0) {
598 PERROR("remove pidfile %s", opt_pidfile);
599 }
600 }
601
602 DBG("Removing sessiond and consumerd content of directory %s", rundir);
603
604 /* sessiond */
605 snprintf(path, PATH_MAX,
606 "%s/%s",
607 rundir, DEFAULT_LTTNG_SESSIOND_PIDFILE);
608 DBG("Removing %s", path);
609 (void) unlink(path);
610
611 snprintf(path, PATH_MAX, "%s/%s", rundir,
612 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE);
613 DBG("Removing %s", path);
614 (void) unlink(path);
615
616 /* kconsumerd */
617 snprintf(path, PATH_MAX,
618 DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
619 rundir);
620 DBG("Removing %s", path);
621 (void) unlink(path);
622
623 snprintf(path, PATH_MAX,
624 DEFAULT_KCONSUMERD_PATH,
625 rundir);
626 DBG("Removing directory %s", path);
627 (void) rmdir(path);
628
629 /* ust consumerd 32 */
630 snprintf(path, PATH_MAX,
631 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH,
632 rundir);
633 DBG("Removing %s", path);
634 (void) unlink(path);
635
636 snprintf(path, PATH_MAX,
637 DEFAULT_USTCONSUMERD32_PATH,
638 rundir);
639 DBG("Removing directory %s", path);
640 (void) rmdir(path);
641
642 /* ust consumerd 64 */
643 snprintf(path, PATH_MAX,
644 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH,
645 rundir);
646 DBG("Removing %s", path);
647 (void) unlink(path);
648
649 snprintf(path, PATH_MAX,
650 DEFAULT_USTCONSUMERD64_PATH,
651 rundir);
652 DBG("Removing directory %s", path);
653 (void) rmdir(path);
654
655 DBG("Cleaning up all sessions");
656
657 /* Destroy session list mutex */
658 if (session_list_ptr != NULL) {
659 pthread_mutex_destroy(&session_list_ptr->lock);
660
661 /* Cleanup ALL session */
662 cds_list_for_each_entry_safe(sess, stmp,
663 &session_list_ptr->head, list) {
664 cmd_destroy_session(sess, kernel_poll_pipe[1]);
665 }
666 }
667
668 wait_consumer(&kconsumer_data);
669 wait_consumer(&ustconsumer64_data);
670 wait_consumer(&ustconsumer32_data);
671
672 DBG("Cleaning up all agent apps");
673 agent_app_ht_clean();
674
675 DBG("Closing all UST sockets");
676 ust_app_clean_list();
677 buffer_reg_destroy_registries();
678
679 if (is_root && !opt_no_kernel) {
680 DBG2("Closing kernel fd");
681 if (kernel_tracer_fd >= 0) {
682 ret = close(kernel_tracer_fd);
683 if (ret) {
684 PERROR("close");
685 }
686 }
687 DBG("Unloading kernel modules");
688 modprobe_remove_lttng_all();
689 free(syscall_table);
690 }
691
692 close_consumer_sockets();
693
694 if (load_info) {
695 load_session_destroy_data(load_info);
696 free(load_info);
697 }
698
699 /*
700 * Cleanup lock file by deleting it and finaly closing it which will
701 * release the file system lock.
702 */
703 if (lockfile_fd >= 0) {
704 char lockfile_path[PATH_MAX];
705
706 ret = generate_lock_file_path(lockfile_path,
707 sizeof(lockfile_path));
708 if (ret > 0) {
709 ret = remove(lockfile_path);
710 if (ret < 0) {
711 PERROR("remove lock file");
712 }
713 ret = close(lockfile_fd);
714 if (ret < 0) {
715 PERROR("close lock file");
716 }
717 }
718 }
719
720 /*
721 * We do NOT rmdir rundir because there are other processes
722 * using it, for instance lttng-relayd, which can start in
723 * parallel with this teardown.
724 */
725
726 free(rundir);
727 }
728
729 /*
730 * Cleanup the daemon's option data structures.
731 */
732 static void sessiond_cleanup_options(void)
733 {
734 DBG("Cleaning up options");
735
736 /*
737 * If the override option is set, the pointer points to a *non* const
738 * thus freeing it even though the variable type is set to const.
739 */
740 if (tracing_group_name_override) {
741 free((void *) tracing_group_name);
742 }
743 if (consumerd32_bin_override) {
744 free((void *) consumerd32_bin);
745 }
746 if (consumerd64_bin_override) {
747 free((void *) consumerd64_bin);
748 }
749 if (consumerd32_libdir_override) {
750 free((void *) consumerd32_libdir);
751 }
752 if (consumerd64_libdir_override) {
753 free((void *) consumerd64_libdir);
754 }
755
756 free(opt_pidfile);
757 free(opt_load_session_path);
758 free(kmod_probes_list);
759 free(kmod_extra_probes_list);
760
761 run_as_destroy_worker();
762 }
763
764 /*
765 * Send data on a unix socket using the liblttsessiondcomm API.
766 *
767 * Return lttcomm error code.
768 */
769 static int send_unix_sock(int sock, void *buf, size_t len)
770 {
771 /* Check valid length */
772 if (len == 0) {
773 return -1;
774 }
775
776 return lttcomm_send_unix_sock(sock, buf, len);
777 }
778
779 /*
780 * Free memory of a command context structure.
781 */
782 static void clean_command_ctx(struct command_ctx **cmd_ctx)
783 {
784 DBG("Clean command context structure");
785 if (*cmd_ctx) {
786 if ((*cmd_ctx)->llm) {
787 free((*cmd_ctx)->llm);
788 }
789 if ((*cmd_ctx)->lsm) {
790 free((*cmd_ctx)->lsm);
791 }
792 free(*cmd_ctx);
793 *cmd_ctx = NULL;
794 }
795 }
796
797 /*
798 * Notify UST applications using the shm mmap futex.
799 */
800 static int notify_ust_apps(int active)
801 {
802 char *wait_shm_mmap;
803
804 DBG("Notifying applications of session daemon state: %d", active);
805
806 /* See shm.c for this call implying mmap, shm and futex calls */
807 wait_shm_mmap = shm_ust_get_mmap(wait_shm_path, is_root);
808 if (wait_shm_mmap == NULL) {
809 goto error;
810 }
811
812 /* Wake waiting process */
813 futex_wait_update((int32_t *) wait_shm_mmap, active);
814
815 /* Apps notified successfully */
816 return 0;
817
818 error:
819 return -1;
820 }
821
822 /*
823 * Setup the outgoing data buffer for the response (llm) by allocating the
824 * right amount of memory and copying the original information from the lsm
825 * structure.
826 *
827 * Return 0 on success, negative value on error.
828 */
829 static int setup_lttng_msg(struct command_ctx *cmd_ctx,
830 const void *payload_buf, size_t payload_len,
831 const void *cmd_header_buf, size_t cmd_header_len)
832 {
833 int ret = 0;
834 const size_t header_len = sizeof(struct lttcomm_lttng_msg);
835 const size_t cmd_header_offset = header_len;
836 const size_t payload_offset = cmd_header_offset + cmd_header_len;
837 const size_t total_msg_size = header_len + cmd_header_len + payload_len;
838
839 cmd_ctx->llm = zmalloc(total_msg_size);
840
841 if (cmd_ctx->llm == NULL) {
842 PERROR("zmalloc");
843 ret = -ENOMEM;
844 goto end;
845 }
846
847 /* Copy common data */
848 cmd_ctx->llm->cmd_type = cmd_ctx->lsm->cmd_type;
849 cmd_ctx->llm->pid = cmd_ctx->lsm->domain.attr.pid;
850 cmd_ctx->llm->cmd_header_size = cmd_header_len;
851 cmd_ctx->llm->data_size = payload_len;
852 cmd_ctx->lttng_msg_size = total_msg_size;
853
854 /* Copy command header */
855 if (cmd_header_len) {
856 memcpy(((uint8_t *) cmd_ctx->llm) + cmd_header_offset, cmd_header_buf,
857 cmd_header_len);
858 }
859
860 /* Copy payload */
861 if (payload_len) {
862 memcpy(((uint8_t *) cmd_ctx->llm) + payload_offset, payload_buf,
863 payload_len);
864 }
865
866 end:
867 return ret;
868 }
869
870 /*
871 * Version of setup_lttng_msg() without command header.
872 */
873 static int setup_lttng_msg_no_cmd_header(struct command_ctx *cmd_ctx,
874 void *payload_buf, size_t payload_len)
875 {
876 return setup_lttng_msg(cmd_ctx, payload_buf, payload_len, NULL, 0);
877 }
878 /*
879 * Update the kernel poll set of all channel fd available over all tracing
880 * session. Add the wakeup pipe at the end of the set.
881 */
882 static int update_kernel_poll(struct lttng_poll_event *events)
883 {
884 int ret;
885 struct ltt_session *session;
886 struct ltt_kernel_channel *channel;
887
888 DBG("Updating kernel poll set");
889
890 session_lock_list();
891 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
892 session_lock(session);
893 if (session->kernel_session == NULL) {
894 session_unlock(session);
895 continue;
896 }
897
898 cds_list_for_each_entry(channel,
899 &session->kernel_session->channel_list.head, list) {
900 /* Add channel fd to the kernel poll set */
901 ret = lttng_poll_add(events, channel->fd, LPOLLIN | LPOLLRDNORM);
902 if (ret < 0) {
903 session_unlock(session);
904 goto error;
905 }
906 DBG("Channel fd %d added to kernel set", channel->fd);
907 }
908 session_unlock(session);
909 }
910 session_unlock_list();
911
912 return 0;
913
914 error:
915 session_unlock_list();
916 return -1;
917 }
918
919 /*
920 * Find the channel fd from 'fd' over all tracing session. When found, check
921 * for new channel stream and send those stream fds to the kernel consumer.
922 *
923 * Useful for CPU hotplug feature.
924 */
925 static int update_kernel_stream(struct consumer_data *consumer_data, int fd)
926 {
927 int ret = 0;
928 struct ltt_session *session;
929 struct ltt_kernel_session *ksess;
930 struct ltt_kernel_channel *channel;
931
932 DBG("Updating kernel streams for channel fd %d", fd);
933
934 session_lock_list();
935 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
936 session_lock(session);
937 if (session->kernel_session == NULL) {
938 session_unlock(session);
939 continue;
940 }
941 ksess = session->kernel_session;
942
943 cds_list_for_each_entry(channel,
944 &ksess->channel_list.head, list) {
945 struct lttng_ht_iter iter;
946 struct consumer_socket *socket;
947
948 if (channel->fd != fd) {
949 continue;
950 }
951 DBG("Channel found, updating kernel streams");
952 ret = kernel_open_channel_stream(channel);
953 if (ret < 0) {
954 goto error;
955 }
956 /* Update the stream global counter */
957 ksess->stream_count_global += ret;
958
959 /*
960 * Have we already sent fds to the consumer? If yes, it
961 * means that tracing is started so it is safe to send
962 * our updated stream fds.
963 */
964 if (ksess->consumer_fds_sent != 1
965 || ksess->consumer == NULL) {
966 ret = -1;
967 goto error;
968 }
969
970 rcu_read_lock();
971 cds_lfht_for_each_entry(ksess->consumer->socks->ht,
972 &iter.iter, socket, node.node) {
973 pthread_mutex_lock(socket->lock);
974 ret = kernel_consumer_send_channel_stream(socket,
975 channel, ksess,
976 session->output_traces ? 1 : 0);
977 pthread_mutex_unlock(socket->lock);
978 if (ret < 0) {
979 rcu_read_unlock();
980 goto error;
981 }
982 }
983 rcu_read_unlock();
984 }
985 session_unlock(session);
986 }
987 session_unlock_list();
988 return ret;
989
990 error:
991 session_unlock(session);
992 session_unlock_list();
993 return ret;
994 }
995
996 /*
997 * For each tracing session, update newly registered apps. The session list
998 * lock MUST be acquired before calling this.
999 */
1000 static void update_ust_app(int app_sock)
1001 {
1002 struct ltt_session *sess, *stmp;
1003
1004 /* Consumer is in an ERROR state. Stop any application update. */
1005 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
1006 /* Stop the update process since the consumer is dead. */
1007 return;
1008 }
1009
1010 /* For all tracing session(s) */
1011 cds_list_for_each_entry_safe(sess, stmp, &session_list_ptr->head, list) {
1012 struct ust_app *app;
1013
1014 session_lock(sess);
1015 if (!sess->ust_session) {
1016 goto unlock_session;
1017 }
1018
1019 rcu_read_lock();
1020 assert(app_sock >= 0);
1021 app = ust_app_find_by_sock(app_sock);
1022 if (app == NULL) {
1023 /*
1024 * Application can be unregistered before so
1025 * this is possible hence simply stopping the
1026 * update.
1027 */
1028 DBG3("UST app update failed to find app sock %d",
1029 app_sock);
1030 goto unlock_rcu;
1031 }
1032 ust_app_global_update(sess->ust_session, app);
1033 unlock_rcu:
1034 rcu_read_unlock();
1035 unlock_session:
1036 session_unlock(sess);
1037 }
1038 }
1039
1040 /*
1041 * This thread manage event coming from the kernel.
1042 *
1043 * Features supported in this thread:
1044 * -) CPU Hotplug
1045 */
1046 static void *thread_manage_kernel(void *data)
1047 {
1048 int ret, i, pollfd, update_poll_flag = 1, err = -1;
1049 uint32_t revents, nb_fd;
1050 char tmp;
1051 struct lttng_poll_event events;
1052
1053 DBG("[thread] Thread manage kernel started");
1054
1055 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_KERNEL);
1056
1057 /*
1058 * This first step of the while is to clean this structure which could free
1059 * non NULL pointers so initialize it before the loop.
1060 */
1061 lttng_poll_init(&events);
1062
1063 if (testpoint(sessiond_thread_manage_kernel)) {
1064 goto error_testpoint;
1065 }
1066
1067 health_code_update();
1068
1069 if (testpoint(sessiond_thread_manage_kernel_before_loop)) {
1070 goto error_testpoint;
1071 }
1072
1073 while (1) {
1074 health_code_update();
1075
1076 if (update_poll_flag == 1) {
1077 /* Clean events object. We are about to populate it again. */
1078 lttng_poll_clean(&events);
1079
1080 ret = sessiond_set_thread_pollset(&events, 2);
1081 if (ret < 0) {
1082 goto error_poll_create;
1083 }
1084
1085 ret = lttng_poll_add(&events, kernel_poll_pipe[0], LPOLLIN);
1086 if (ret < 0) {
1087 goto error;
1088 }
1089
1090 /* This will add the available kernel channel if any. */
1091 ret = update_kernel_poll(&events);
1092 if (ret < 0) {
1093 goto error;
1094 }
1095 update_poll_flag = 0;
1096 }
1097
1098 DBG("Thread kernel polling");
1099
1100 /* Poll infinite value of time */
1101 restart:
1102 health_poll_entry();
1103 ret = lttng_poll_wait(&events, -1);
1104 DBG("Thread kernel return from poll on %d fds",
1105 LTTNG_POLL_GETNB(&events));
1106 health_poll_exit();
1107 if (ret < 0) {
1108 /*
1109 * Restart interrupted system call.
1110 */
1111 if (errno == EINTR) {
1112 goto restart;
1113 }
1114 goto error;
1115 } else if (ret == 0) {
1116 /* Should not happen since timeout is infinite */
1117 ERR("Return value of poll is 0 with an infinite timeout.\n"
1118 "This should not have happened! Continuing...");
1119 continue;
1120 }
1121
1122 nb_fd = ret;
1123
1124 for (i = 0; i < nb_fd; i++) {
1125 /* Fetch once the poll data */
1126 revents = LTTNG_POLL_GETEV(&events, i);
1127 pollfd = LTTNG_POLL_GETFD(&events, i);
1128
1129 health_code_update();
1130
1131 if (!revents) {
1132 /* No activity for this FD (poll implementation). */
1133 continue;
1134 }
1135
1136 /* Thread quit pipe has been closed. Killing thread. */
1137 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1138 if (ret) {
1139 err = 0;
1140 goto exit;
1141 }
1142
1143 /* Check for data on kernel pipe */
1144 if (revents & LPOLLIN) {
1145 if (pollfd == kernel_poll_pipe[0]) {
1146 (void) lttng_read(kernel_poll_pipe[0],
1147 &tmp, 1);
1148 /*
1149 * Ret value is useless here, if this pipe gets any actions an
1150 * update is required anyway.
1151 */
1152 update_poll_flag = 1;
1153 continue;
1154 } else {
1155 /*
1156 * New CPU detected by the kernel. Adding kernel stream to
1157 * kernel session and updating the kernel consumer
1158 */
1159 ret = update_kernel_stream(&kconsumer_data, pollfd);
1160 if (ret < 0) {
1161 continue;
1162 }
1163 break;
1164 }
1165 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1166 update_poll_flag = 1;
1167 continue;
1168 } else {
1169 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1170 goto error;
1171 }
1172 }
1173 }
1174
1175 exit:
1176 error:
1177 lttng_poll_clean(&events);
1178 error_poll_create:
1179 error_testpoint:
1180 utils_close_pipe(kernel_poll_pipe);
1181 kernel_poll_pipe[0] = kernel_poll_pipe[1] = -1;
1182 if (err) {
1183 health_error();
1184 ERR("Health error occurred in %s", __func__);
1185 WARN("Kernel thread died unexpectedly. "
1186 "Kernel tracing can continue but CPU hotplug is disabled.");
1187 }
1188 health_unregister(health_sessiond);
1189 DBG("Kernel thread dying");
1190 return NULL;
1191 }
1192
1193 /*
1194 * Signal pthread condition of the consumer data that the thread.
1195 */
1196 static void signal_consumer_condition(struct consumer_data *data, int state)
1197 {
1198 pthread_mutex_lock(&data->cond_mutex);
1199
1200 /*
1201 * The state is set before signaling. It can be any value, it's the waiter
1202 * job to correctly interpret this condition variable associated to the
1203 * consumer pthread_cond.
1204 *
1205 * A value of 0 means that the corresponding thread of the consumer data
1206 * was not started. 1 indicates that the thread has started and is ready
1207 * for action. A negative value means that there was an error during the
1208 * thread bootstrap.
1209 */
1210 data->consumer_thread_is_ready = state;
1211 (void) pthread_cond_signal(&data->cond);
1212
1213 pthread_mutex_unlock(&data->cond_mutex);
1214 }
1215
1216 /*
1217 * This thread manage the consumer error sent back to the session daemon.
1218 */
1219 static void *thread_manage_consumer(void *data)
1220 {
1221 int sock = -1, i, ret, pollfd, err = -1, should_quit = 0;
1222 uint32_t revents, nb_fd;
1223 enum lttcomm_return_code code;
1224 struct lttng_poll_event events;
1225 struct consumer_data *consumer_data = data;
1226
1227 DBG("[thread] Manage consumer started");
1228
1229 rcu_register_thread();
1230 rcu_thread_online();
1231
1232 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_CONSUMER);
1233
1234 health_code_update();
1235
1236 /*
1237 * Pass 3 as size here for the thread quit pipe, consumerd_err_sock and the
1238 * metadata_sock. Nothing more will be added to this poll set.
1239 */
1240 ret = sessiond_set_thread_pollset(&events, 3);
1241 if (ret < 0) {
1242 goto error_poll;
1243 }
1244
1245 /*
1246 * The error socket here is already in a listening state which was done
1247 * just before spawning this thread to avoid a race between the consumer
1248 * daemon exec trying to connect and the listen() call.
1249 */
1250 ret = lttng_poll_add(&events, consumer_data->err_sock, LPOLLIN | LPOLLRDHUP);
1251 if (ret < 0) {
1252 goto error;
1253 }
1254
1255 health_code_update();
1256
1257 /* Infinite blocking call, waiting for transmission */
1258 restart:
1259 health_poll_entry();
1260
1261 if (testpoint(sessiond_thread_manage_consumer)) {
1262 goto error;
1263 }
1264
1265 ret = lttng_poll_wait(&events, -1);
1266 health_poll_exit();
1267 if (ret < 0) {
1268 /*
1269 * Restart interrupted system call.
1270 */
1271 if (errno == EINTR) {
1272 goto restart;
1273 }
1274 goto error;
1275 }
1276
1277 nb_fd = ret;
1278
1279 for (i = 0; i < nb_fd; i++) {
1280 /* Fetch once the poll data */
1281 revents = LTTNG_POLL_GETEV(&events, i);
1282 pollfd = LTTNG_POLL_GETFD(&events, i);
1283
1284 health_code_update();
1285
1286 if (!revents) {
1287 /* No activity for this FD (poll implementation). */
1288 continue;
1289 }
1290
1291 /* Thread quit pipe has been closed. Killing thread. */
1292 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1293 if (ret) {
1294 err = 0;
1295 goto exit;
1296 }
1297
1298 /* Event on the registration socket */
1299 if (pollfd == consumer_data->err_sock) {
1300 if (revents & LPOLLIN) {
1301 continue;
1302 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1303 ERR("consumer err socket poll error");
1304 goto error;
1305 } else {
1306 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1307 goto error;
1308 }
1309 }
1310 }
1311
1312 sock = lttcomm_accept_unix_sock(consumer_data->err_sock);
1313 if (sock < 0) {
1314 goto error;
1315 }
1316
1317 /*
1318 * Set the CLOEXEC flag. Return code is useless because either way, the
1319 * show must go on.
1320 */
1321 (void) utils_set_fd_cloexec(sock);
1322
1323 health_code_update();
1324
1325 DBG2("Receiving code from consumer err_sock");
1326
1327 /* Getting status code from kconsumerd */
1328 ret = lttcomm_recv_unix_sock(sock, &code,
1329 sizeof(enum lttcomm_return_code));
1330 if (ret <= 0) {
1331 goto error;
1332 }
1333
1334 health_code_update();
1335 if (code == LTTCOMM_CONSUMERD_COMMAND_SOCK_READY) {
1336 /* Connect both socket, command and metadata. */
1337 consumer_data->cmd_sock =
1338 lttcomm_connect_unix_sock(consumer_data->cmd_unix_sock_path);
1339 consumer_data->metadata_fd =
1340 lttcomm_connect_unix_sock(consumer_data->cmd_unix_sock_path);
1341 if (consumer_data->cmd_sock < 0
1342 || consumer_data->metadata_fd < 0) {
1343 PERROR("consumer connect cmd socket");
1344 /* On error, signal condition and quit. */
1345 signal_consumer_condition(consumer_data, -1);
1346 goto error;
1347 }
1348 consumer_data->metadata_sock.fd_ptr = &consumer_data->metadata_fd;
1349 /* Create metadata socket lock. */
1350 consumer_data->metadata_sock.lock = zmalloc(sizeof(pthread_mutex_t));
1351 if (consumer_data->metadata_sock.lock == NULL) {
1352 PERROR("zmalloc pthread mutex");
1353 goto error;
1354 }
1355 pthread_mutex_init(consumer_data->metadata_sock.lock, NULL);
1356
1357 signal_consumer_condition(consumer_data, 1);
1358 DBG("Consumer command socket ready (fd: %d", consumer_data->cmd_sock);
1359 DBG("Consumer metadata socket ready (fd: %d)",
1360 consumer_data->metadata_fd);
1361 } else {
1362 ERR("consumer error when waiting for SOCK_READY : %s",
1363 lttcomm_get_readable_code(-code));
1364 goto error;
1365 }
1366
1367 /* Remove the consumerd error sock since we've established a connexion */
1368 ret = lttng_poll_del(&events, consumer_data->err_sock);
1369 if (ret < 0) {
1370 goto error;
1371 }
1372
1373 /* Add new accepted error socket. */
1374 ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLRDHUP);
1375 if (ret < 0) {
1376 goto error;
1377 }
1378
1379 /* Add metadata socket that is successfully connected. */
1380 ret = lttng_poll_add(&events, consumer_data->metadata_fd,
1381 LPOLLIN | LPOLLRDHUP);
1382 if (ret < 0) {
1383 goto error;
1384 }
1385
1386 health_code_update();
1387
1388 /* Infinite blocking call, waiting for transmission */
1389 restart_poll:
1390 while (1) {
1391 health_code_update();
1392
1393 /* Exit the thread because the thread quit pipe has been triggered. */
1394 if (should_quit) {
1395 /* Not a health error. */
1396 err = 0;
1397 goto exit;
1398 }
1399
1400 health_poll_entry();
1401 ret = lttng_poll_wait(&events, -1);
1402 health_poll_exit();
1403 if (ret < 0) {
1404 /*
1405 * Restart interrupted system call.
1406 */
1407 if (errno == EINTR) {
1408 goto restart_poll;
1409 }
1410 goto error;
1411 }
1412
1413 nb_fd = ret;
1414
1415 for (i = 0; i < nb_fd; i++) {
1416 /* Fetch once the poll data */
1417 revents = LTTNG_POLL_GETEV(&events, i);
1418 pollfd = LTTNG_POLL_GETFD(&events, i);
1419
1420 health_code_update();
1421
1422 if (!revents) {
1423 /* No activity for this FD (poll implementation). */
1424 continue;
1425 }
1426
1427 /*
1428 * Thread quit pipe has been triggered, flag that we should stop
1429 * but continue the current loop to handle potential data from
1430 * consumer.
1431 */
1432 should_quit = sessiond_check_thread_quit_pipe(pollfd, revents);
1433
1434 if (pollfd == sock) {
1435 /* Event on the consumerd socket */
1436 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
1437 && !(revents & LPOLLIN)) {
1438 ERR("consumer err socket second poll error");
1439 goto error;
1440 }
1441 health_code_update();
1442 /* Wait for any kconsumerd error */
1443 ret = lttcomm_recv_unix_sock(sock, &code,
1444 sizeof(enum lttcomm_return_code));
1445 if (ret <= 0) {
1446 ERR("consumer closed the command socket");
1447 goto error;
1448 }
1449
1450 ERR("consumer return code : %s",
1451 lttcomm_get_readable_code(-code));
1452
1453 goto exit;
1454 } else if (pollfd == consumer_data->metadata_fd) {
1455 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)
1456 && !(revents & LPOLLIN)) {
1457 ERR("consumer err metadata socket second poll error");
1458 goto error;
1459 }
1460 /* UST metadata requests */
1461 ret = ust_consumer_metadata_request(
1462 &consumer_data->metadata_sock);
1463 if (ret < 0) {
1464 ERR("Handling metadata request");
1465 goto error;
1466 }
1467 }
1468 /* No need for an else branch all FDs are tested prior. */
1469 }
1470 health_code_update();
1471 }
1472
1473 exit:
1474 error:
1475 /*
1476 * We lock here because we are about to close the sockets and some other
1477 * thread might be using them so get exclusive access which will abort all
1478 * other consumer command by other threads.
1479 */
1480 pthread_mutex_lock(&consumer_data->lock);
1481
1482 /* Immediately set the consumerd state to stopped */
1483 if (consumer_data->type == LTTNG_CONSUMER_KERNEL) {
1484 uatomic_set(&kernel_consumerd_state, CONSUMER_ERROR);
1485 } else if (consumer_data->type == LTTNG_CONSUMER64_UST ||
1486 consumer_data->type == LTTNG_CONSUMER32_UST) {
1487 uatomic_set(&ust_consumerd_state, CONSUMER_ERROR);
1488 } else {
1489 /* Code flow error... */
1490 assert(0);
1491 }
1492
1493 if (consumer_data->err_sock >= 0) {
1494 ret = close(consumer_data->err_sock);
1495 if (ret) {
1496 PERROR("close");
1497 }
1498 consumer_data->err_sock = -1;
1499 }
1500 if (consumer_data->cmd_sock >= 0) {
1501 ret = close(consumer_data->cmd_sock);
1502 if (ret) {
1503 PERROR("close");
1504 }
1505 consumer_data->cmd_sock = -1;
1506 }
1507 if (consumer_data->metadata_sock.fd_ptr &&
1508 *consumer_data->metadata_sock.fd_ptr >= 0) {
1509 ret = close(*consumer_data->metadata_sock.fd_ptr);
1510 if (ret) {
1511 PERROR("close");
1512 }
1513 }
1514 if (sock >= 0) {
1515 ret = close(sock);
1516 if (ret) {
1517 PERROR("close");
1518 }
1519 }
1520
1521 unlink(consumer_data->err_unix_sock_path);
1522 unlink(consumer_data->cmd_unix_sock_path);
1523 pthread_mutex_unlock(&consumer_data->lock);
1524
1525 /* Cleanup metadata socket mutex. */
1526 if (consumer_data->metadata_sock.lock) {
1527 pthread_mutex_destroy(consumer_data->metadata_sock.lock);
1528 free(consumer_data->metadata_sock.lock);
1529 }
1530 lttng_poll_clean(&events);
1531 error_poll:
1532 if (err) {
1533 health_error();
1534 ERR("Health error occurred in %s", __func__);
1535 }
1536 health_unregister(health_sessiond);
1537 DBG("consumer thread cleanup completed");
1538
1539 rcu_thread_offline();
1540 rcu_unregister_thread();
1541
1542 return NULL;
1543 }
1544
1545 /*
1546 * This thread manage application communication.
1547 */
1548 static void *thread_manage_apps(void *data)
1549 {
1550 int i, ret, pollfd, err = -1;
1551 ssize_t size_ret;
1552 uint32_t revents, nb_fd;
1553 struct lttng_poll_event events;
1554
1555 DBG("[thread] Manage application started");
1556
1557 rcu_register_thread();
1558 rcu_thread_online();
1559
1560 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_MANAGE);
1561
1562 if (testpoint(sessiond_thread_manage_apps)) {
1563 goto error_testpoint;
1564 }
1565
1566 health_code_update();
1567
1568 ret = sessiond_set_thread_pollset(&events, 2);
1569 if (ret < 0) {
1570 goto error_poll_create;
1571 }
1572
1573 ret = lttng_poll_add(&events, apps_cmd_pipe[0], LPOLLIN | LPOLLRDHUP);
1574 if (ret < 0) {
1575 goto error;
1576 }
1577
1578 if (testpoint(sessiond_thread_manage_apps_before_loop)) {
1579 goto error;
1580 }
1581
1582 health_code_update();
1583
1584 while (1) {
1585 DBG("Apps thread polling");
1586
1587 /* Inifinite blocking call, waiting for transmission */
1588 restart:
1589 health_poll_entry();
1590 ret = lttng_poll_wait(&events, -1);
1591 DBG("Apps thread return from poll on %d fds",
1592 LTTNG_POLL_GETNB(&events));
1593 health_poll_exit();
1594 if (ret < 0) {
1595 /*
1596 * Restart interrupted system call.
1597 */
1598 if (errno == EINTR) {
1599 goto restart;
1600 }
1601 goto error;
1602 }
1603
1604 nb_fd = ret;
1605
1606 for (i = 0; i < nb_fd; i++) {
1607 /* Fetch once the poll data */
1608 revents = LTTNG_POLL_GETEV(&events, i);
1609 pollfd = LTTNG_POLL_GETFD(&events, i);
1610
1611 health_code_update();
1612
1613 if (!revents) {
1614 /* No activity for this FD (poll implementation). */
1615 continue;
1616 }
1617
1618 /* Thread quit pipe has been closed. Killing thread. */
1619 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
1620 if (ret) {
1621 err = 0;
1622 goto exit;
1623 }
1624
1625 /* Inspect the apps cmd pipe */
1626 if (pollfd == apps_cmd_pipe[0]) {
1627 if (revents & LPOLLIN) {
1628 int sock;
1629
1630 /* Empty pipe */
1631 size_ret = lttng_read(apps_cmd_pipe[0], &sock, sizeof(sock));
1632 if (size_ret < sizeof(sock)) {
1633 PERROR("read apps cmd pipe");
1634 goto error;
1635 }
1636
1637 health_code_update();
1638
1639 /*
1640 * Since this is a command socket (write then read),
1641 * we only monitor the error events of the socket.
1642 */
1643 ret = lttng_poll_add(&events, sock,
1644 LPOLLERR | LPOLLHUP | LPOLLRDHUP);
1645 if (ret < 0) {
1646 goto error;
1647 }
1648
1649 DBG("Apps with sock %d added to poll set", sock);
1650 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1651 ERR("Apps command pipe error");
1652 goto error;
1653 } else {
1654 ERR("Unknown poll events %u for sock %d", revents, pollfd);
1655 goto error;
1656 }
1657 } else {
1658 /*
1659 * At this point, we know that a registered application made
1660 * the event at poll_wait.
1661 */
1662 if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
1663 /* Removing from the poll set */
1664 ret = lttng_poll_del(&events, pollfd);
1665 if (ret < 0) {
1666 goto error;
1667 }
1668
1669 /* Socket closed on remote end. */
1670 ust_app_unregister(pollfd);
1671 } else {
1672 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1673 goto error;
1674 }
1675 }
1676
1677 health_code_update();
1678 }
1679 }
1680
1681 exit:
1682 error:
1683 lttng_poll_clean(&events);
1684 error_poll_create:
1685 error_testpoint:
1686 utils_close_pipe(apps_cmd_pipe);
1687 apps_cmd_pipe[0] = apps_cmd_pipe[1] = -1;
1688
1689 /*
1690 * We don't clean the UST app hash table here since already registered
1691 * applications can still be controlled so let them be until the session
1692 * daemon dies or the applications stop.
1693 */
1694
1695 if (err) {
1696 health_error();
1697 ERR("Health error occurred in %s", __func__);
1698 }
1699 health_unregister(health_sessiond);
1700 DBG("Application communication apps thread cleanup complete");
1701 rcu_thread_offline();
1702 rcu_unregister_thread();
1703 return NULL;
1704 }
1705
1706 /*
1707 * Send a socket to a thread This is called from the dispatch UST registration
1708 * thread once all sockets are set for the application.
1709 *
1710 * The sock value can be invalid, we don't really care, the thread will handle
1711 * it and make the necessary cleanup if so.
1712 *
1713 * On success, return 0 else a negative value being the errno message of the
1714 * write().
1715 */
1716 static int send_socket_to_thread(int fd, int sock)
1717 {
1718 ssize_t ret;
1719
1720 /*
1721 * It's possible that the FD is set as invalid with -1 concurrently just
1722 * before calling this function being a shutdown state of the thread.
1723 */
1724 if (fd < 0) {
1725 ret = -EBADF;
1726 goto error;
1727 }
1728
1729 ret = lttng_write(fd, &sock, sizeof(sock));
1730 if (ret < sizeof(sock)) {
1731 PERROR("write apps pipe %d", fd);
1732 if (ret < 0) {
1733 ret = -errno;
1734 }
1735 goto error;
1736 }
1737
1738 /* All good. Don't send back the write positive ret value. */
1739 ret = 0;
1740 error:
1741 return (int) ret;
1742 }
1743
1744 /*
1745 * Sanitize the wait queue of the dispatch registration thread meaning removing
1746 * invalid nodes from it. This is to avoid memory leaks for the case the UST
1747 * notify socket is never received.
1748 */
1749 static void sanitize_wait_queue(struct ust_reg_wait_queue *wait_queue)
1750 {
1751 int ret, nb_fd = 0, i;
1752 unsigned int fd_added = 0;
1753 struct lttng_poll_event events;
1754 struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
1755
1756 assert(wait_queue);
1757
1758 lttng_poll_init(&events);
1759
1760 /* Just skip everything for an empty queue. */
1761 if (!wait_queue->count) {
1762 goto end;
1763 }
1764
1765 ret = lttng_poll_create(&events, wait_queue->count, LTTNG_CLOEXEC);
1766 if (ret < 0) {
1767 goto error_create;
1768 }
1769
1770 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1771 &wait_queue->head, head) {
1772 assert(wait_node->app);
1773 ret = lttng_poll_add(&events, wait_node->app->sock,
1774 LPOLLHUP | LPOLLERR);
1775 if (ret < 0) {
1776 goto error;
1777 }
1778
1779 fd_added = 1;
1780 }
1781
1782 if (!fd_added) {
1783 goto end;
1784 }
1785
1786 /*
1787 * Poll but don't block so we can quickly identify the faulty events and
1788 * clean them afterwards from the wait queue.
1789 */
1790 ret = lttng_poll_wait(&events, 0);
1791 if (ret < 0) {
1792 goto error;
1793 }
1794 nb_fd = ret;
1795
1796 for (i = 0; i < nb_fd; i++) {
1797 /* Get faulty FD. */
1798 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
1799 int pollfd = LTTNG_POLL_GETFD(&events, i);
1800
1801 if (!revents) {
1802 /* No activity for this FD (poll implementation). */
1803 continue;
1804 }
1805
1806 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1807 &wait_queue->head, head) {
1808 if (pollfd == wait_node->app->sock &&
1809 (revents & (LPOLLHUP | LPOLLERR))) {
1810 cds_list_del(&wait_node->head);
1811 wait_queue->count--;
1812 ust_app_destroy(wait_node->app);
1813 free(wait_node);
1814 /*
1815 * Silence warning of use-after-free in
1816 * cds_list_for_each_entry_safe which uses
1817 * __typeof__(*wait_node).
1818 */
1819 wait_node = NULL;
1820 break;
1821 } else {
1822 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
1823 goto error;
1824 }
1825 }
1826 }
1827
1828 if (nb_fd > 0) {
1829 DBG("Wait queue sanitized, %d node were cleaned up", nb_fd);
1830 }
1831
1832 end:
1833 lttng_poll_clean(&events);
1834 return;
1835
1836 error:
1837 lttng_poll_clean(&events);
1838 error_create:
1839 ERR("Unable to sanitize wait queue");
1840 return;
1841 }
1842
1843 /*
1844 * Dispatch request from the registration threads to the application
1845 * communication thread.
1846 */
1847 static void *thread_dispatch_ust_registration(void *data)
1848 {
1849 int ret, err = -1;
1850 struct cds_wfcq_node *node;
1851 struct ust_command *ust_cmd = NULL;
1852 struct ust_reg_wait_node *wait_node = NULL, *tmp_wait_node;
1853 struct ust_reg_wait_queue wait_queue = {
1854 .count = 0,
1855 };
1856
1857 rcu_register_thread();
1858
1859 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG_DISPATCH);
1860
1861 if (testpoint(sessiond_thread_app_reg_dispatch)) {
1862 goto error_testpoint;
1863 }
1864
1865 health_code_update();
1866
1867 CDS_INIT_LIST_HEAD(&wait_queue.head);
1868
1869 DBG("[thread] Dispatch UST command started");
1870
1871 while (!CMM_LOAD_SHARED(dispatch_thread_exit)) {
1872 health_code_update();
1873
1874 /* Atomically prepare the queue futex */
1875 futex_nto1_prepare(&ust_cmd_queue.futex);
1876
1877 do {
1878 struct ust_app *app = NULL;
1879 ust_cmd = NULL;
1880
1881 /*
1882 * Make sure we don't have node(s) that have hung up before receiving
1883 * the notify socket. This is to clean the list in order to avoid
1884 * memory leaks from notify socket that are never seen.
1885 */
1886 sanitize_wait_queue(&wait_queue);
1887
1888 health_code_update();
1889 /* Dequeue command for registration */
1890 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
1891 if (node == NULL) {
1892 DBG("Woken up but nothing in the UST command queue");
1893 /* Continue thread execution */
1894 break;
1895 }
1896
1897 ust_cmd = caa_container_of(node, struct ust_command, node);
1898
1899 DBG("Dispatching UST registration pid:%d ppid:%d uid:%d"
1900 " gid:%d sock:%d name:%s (version %d.%d)",
1901 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
1902 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
1903 ust_cmd->sock, ust_cmd->reg_msg.name,
1904 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
1905
1906 if (ust_cmd->reg_msg.type == USTCTL_SOCKET_CMD) {
1907 wait_node = zmalloc(sizeof(*wait_node));
1908 if (!wait_node) {
1909 PERROR("zmalloc wait_node dispatch");
1910 ret = close(ust_cmd->sock);
1911 if (ret < 0) {
1912 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1913 }
1914 lttng_fd_put(LTTNG_FD_APPS, 1);
1915 free(ust_cmd);
1916 goto error;
1917 }
1918 CDS_INIT_LIST_HEAD(&wait_node->head);
1919
1920 /* Create application object if socket is CMD. */
1921 wait_node->app = ust_app_create(&ust_cmd->reg_msg,
1922 ust_cmd->sock);
1923 if (!wait_node->app) {
1924 ret = close(ust_cmd->sock);
1925 if (ret < 0) {
1926 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1927 }
1928 lttng_fd_put(LTTNG_FD_APPS, 1);
1929 free(wait_node);
1930 free(ust_cmd);
1931 continue;
1932 }
1933 /*
1934 * Add application to the wait queue so we can set the notify
1935 * socket before putting this object in the global ht.
1936 */
1937 cds_list_add(&wait_node->head, &wait_queue.head);
1938 wait_queue.count++;
1939
1940 free(ust_cmd);
1941 /*
1942 * We have to continue here since we don't have the notify
1943 * socket and the application MUST be added to the hash table
1944 * only at that moment.
1945 */
1946 continue;
1947 } else {
1948 /*
1949 * Look for the application in the local wait queue and set the
1950 * notify socket if found.
1951 */
1952 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
1953 &wait_queue.head, head) {
1954 health_code_update();
1955 if (wait_node->app->pid == ust_cmd->reg_msg.pid) {
1956 wait_node->app->notify_sock = ust_cmd->sock;
1957 cds_list_del(&wait_node->head);
1958 wait_queue.count--;
1959 app = wait_node->app;
1960 free(wait_node);
1961 DBG3("UST app notify socket %d is set", ust_cmd->sock);
1962 break;
1963 }
1964 }
1965
1966 /*
1967 * With no application at this stage the received socket is
1968 * basically useless so close it before we free the cmd data
1969 * structure for good.
1970 */
1971 if (!app) {
1972 ret = close(ust_cmd->sock);
1973 if (ret < 0) {
1974 PERROR("close ust sock dispatch %d", ust_cmd->sock);
1975 }
1976 lttng_fd_put(LTTNG_FD_APPS, 1);
1977 }
1978 free(ust_cmd);
1979 }
1980
1981 if (app) {
1982 /*
1983 * @session_lock_list
1984 *
1985 * Lock the global session list so from the register up to the
1986 * registration done message, no thread can see the application
1987 * and change its state.
1988 */
1989 session_lock_list();
1990 rcu_read_lock();
1991
1992 /*
1993 * Add application to the global hash table. This needs to be
1994 * done before the update to the UST registry can locate the
1995 * application.
1996 */
1997 ust_app_add(app);
1998
1999 /* Set app version. This call will print an error if needed. */
2000 (void) ust_app_version(app);
2001
2002 /* Send notify socket through the notify pipe. */
2003 ret = send_socket_to_thread(apps_cmd_notify_pipe[1],
2004 app->notify_sock);
2005 if (ret < 0) {
2006 rcu_read_unlock();
2007 session_unlock_list();
2008 /*
2009 * No notify thread, stop the UST tracing. However, this is
2010 * not an internal error of the this thread thus setting
2011 * the health error code to a normal exit.
2012 */
2013 err = 0;
2014 goto error;
2015 }
2016
2017 /*
2018 * Update newly registered application with the tracing
2019 * registry info already enabled information.
2020 */
2021 update_ust_app(app->sock);
2022
2023 /*
2024 * Don't care about return value. Let the manage apps threads
2025 * handle app unregistration upon socket close.
2026 */
2027 (void) ust_app_register_done(app);
2028
2029 /*
2030 * Even if the application socket has been closed, send the app
2031 * to the thread and unregistration will take place at that
2032 * place.
2033 */
2034 ret = send_socket_to_thread(apps_cmd_pipe[1], app->sock);
2035 if (ret < 0) {
2036 rcu_read_unlock();
2037 session_unlock_list();
2038 /*
2039 * No apps. thread, stop the UST tracing. However, this is
2040 * not an internal error of the this thread thus setting
2041 * the health error code to a normal exit.
2042 */
2043 err = 0;
2044 goto error;
2045 }
2046
2047 rcu_read_unlock();
2048 session_unlock_list();
2049 }
2050 } while (node != NULL);
2051
2052 health_poll_entry();
2053 /* Futex wait on queue. Blocking call on futex() */
2054 futex_nto1_wait(&ust_cmd_queue.futex);
2055 health_poll_exit();
2056 }
2057 /* Normal exit, no error */
2058 err = 0;
2059
2060 error:
2061 /* Clean up wait queue. */
2062 cds_list_for_each_entry_safe(wait_node, tmp_wait_node,
2063 &wait_queue.head, head) {
2064 cds_list_del(&wait_node->head);
2065 wait_queue.count--;
2066 free(wait_node);
2067 }
2068
2069 /* Empty command queue. */
2070 for (;;) {
2071 /* Dequeue command for registration */
2072 node = cds_wfcq_dequeue_blocking(&ust_cmd_queue.head, &ust_cmd_queue.tail);
2073 if (node == NULL) {
2074 break;
2075 }
2076 ust_cmd = caa_container_of(node, struct ust_command, node);
2077 ret = close(ust_cmd->sock);
2078 if (ret < 0) {
2079 PERROR("close ust sock exit dispatch %d", ust_cmd->sock);
2080 }
2081 lttng_fd_put(LTTNG_FD_APPS, 1);
2082 free(ust_cmd);
2083 }
2084
2085 error_testpoint:
2086 DBG("Dispatch thread dying");
2087 if (err) {
2088 health_error();
2089 ERR("Health error occurred in %s", __func__);
2090 }
2091 health_unregister(health_sessiond);
2092 rcu_unregister_thread();
2093 return NULL;
2094 }
2095
2096 /*
2097 * This thread manage application registration.
2098 */
2099 static void *thread_registration_apps(void *data)
2100 {
2101 int sock = -1, i, ret, pollfd, err = -1;
2102 uint32_t revents, nb_fd;
2103 struct lttng_poll_event events;
2104 /*
2105 * Get allocated in this thread, enqueued to a global queue, dequeued and
2106 * freed in the manage apps thread.
2107 */
2108 struct ust_command *ust_cmd = NULL;
2109
2110 DBG("[thread] Manage application registration started");
2111
2112 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_APP_REG);
2113
2114 if (testpoint(sessiond_thread_registration_apps)) {
2115 goto error_testpoint;
2116 }
2117
2118 ret = lttcomm_listen_unix_sock(apps_sock);
2119 if (ret < 0) {
2120 goto error_listen;
2121 }
2122
2123 /*
2124 * Pass 2 as size here for the thread quit pipe and apps socket. Nothing
2125 * more will be added to this poll set.
2126 */
2127 ret = sessiond_set_thread_pollset(&events, 2);
2128 if (ret < 0) {
2129 goto error_create_poll;
2130 }
2131
2132 /* Add the application registration socket */
2133 ret = lttng_poll_add(&events, apps_sock, LPOLLIN | LPOLLRDHUP);
2134 if (ret < 0) {
2135 goto error_poll_add;
2136 }
2137
2138 /* Notify all applications to register */
2139 ret = notify_ust_apps(1);
2140 if (ret < 0) {
2141 ERR("Failed to notify applications or create the wait shared memory.\n"
2142 "Execution continues but there might be problem for already\n"
2143 "running applications that wishes to register.");
2144 }
2145
2146 while (1) {
2147 DBG("Accepting application registration");
2148
2149 /* Inifinite blocking call, waiting for transmission */
2150 restart:
2151 health_poll_entry();
2152 ret = lttng_poll_wait(&events, -1);
2153 health_poll_exit();
2154 if (ret < 0) {
2155 /*
2156 * Restart interrupted system call.
2157 */
2158 if (errno == EINTR) {
2159 goto restart;
2160 }
2161 goto error;
2162 }
2163
2164 nb_fd = ret;
2165
2166 for (i = 0; i < nb_fd; i++) {
2167 health_code_update();
2168
2169 /* Fetch once the poll data */
2170 revents = LTTNG_POLL_GETEV(&events, i);
2171 pollfd = LTTNG_POLL_GETFD(&events, i);
2172
2173 if (!revents) {
2174 /* No activity for this FD (poll implementation). */
2175 continue;
2176 }
2177
2178 /* Thread quit pipe has been closed. Killing thread. */
2179 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
2180 if (ret) {
2181 err = 0;
2182 goto exit;
2183 }
2184
2185 /* Event on the registration socket */
2186 if (pollfd == apps_sock) {
2187 if (revents & LPOLLIN) {
2188 sock = lttcomm_accept_unix_sock(apps_sock);
2189 if (sock < 0) {
2190 goto error;
2191 }
2192
2193 /*
2194 * Set socket timeout for both receiving and ending.
2195 * app_socket_timeout is in seconds, whereas
2196 * lttcomm_setsockopt_rcv_timeout and
2197 * lttcomm_setsockopt_snd_timeout expect msec as
2198 * parameter.
2199 */
2200 if (app_socket_timeout >= 0) {
2201 (void) lttcomm_setsockopt_rcv_timeout(sock,
2202 app_socket_timeout * 1000);
2203 (void) lttcomm_setsockopt_snd_timeout(sock,
2204 app_socket_timeout * 1000);
2205 }
2206
2207 /*
2208 * Set the CLOEXEC flag. Return code is useless because
2209 * either way, the show must go on.
2210 */
2211 (void) utils_set_fd_cloexec(sock);
2212
2213 /* Create UST registration command for enqueuing */
2214 ust_cmd = zmalloc(sizeof(struct ust_command));
2215 if (ust_cmd == NULL) {
2216 PERROR("ust command zmalloc");
2217 ret = close(sock);
2218 if (ret) {
2219 PERROR("close");
2220 }
2221 goto error;
2222 }
2223
2224 /*
2225 * Using message-based transmissions to ensure we don't
2226 * have to deal with partially received messages.
2227 */
2228 ret = lttng_fd_get(LTTNG_FD_APPS, 1);
2229 if (ret < 0) {
2230 ERR("Exhausted file descriptors allowed for applications.");
2231 free(ust_cmd);
2232 ret = close(sock);
2233 if (ret) {
2234 PERROR("close");
2235 }
2236 sock = -1;
2237 continue;
2238 }
2239
2240 health_code_update();
2241 ret = ust_app_recv_registration(sock, &ust_cmd->reg_msg);
2242 if (ret < 0) {
2243 free(ust_cmd);
2244 /* Close socket of the application. */
2245 ret = close(sock);
2246 if (ret) {
2247 PERROR("close");
2248 }
2249 lttng_fd_put(LTTNG_FD_APPS, 1);
2250 sock = -1;
2251 continue;
2252 }
2253 health_code_update();
2254
2255 ust_cmd->sock = sock;
2256 sock = -1;
2257
2258 DBG("UST registration received with pid:%d ppid:%d uid:%d"
2259 " gid:%d sock:%d name:%s (version %d.%d)",
2260 ust_cmd->reg_msg.pid, ust_cmd->reg_msg.ppid,
2261 ust_cmd->reg_msg.uid, ust_cmd->reg_msg.gid,
2262 ust_cmd->sock, ust_cmd->reg_msg.name,
2263 ust_cmd->reg_msg.major, ust_cmd->reg_msg.minor);
2264
2265 /*
2266 * Lock free enqueue the registration request. The red pill
2267 * has been taken! This apps will be part of the *system*.
2268 */
2269 cds_wfcq_enqueue(&ust_cmd_queue.head, &ust_cmd_queue.tail, &ust_cmd->node);
2270
2271 /*
2272 * Wake the registration queue futex. Implicit memory
2273 * barrier with the exchange in cds_wfcq_enqueue.
2274 */
2275 futex_nto1_wake(&ust_cmd_queue.futex);
2276 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2277 ERR("Register apps socket poll error");
2278 goto error;
2279 } else {
2280 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2281 goto error;
2282 }
2283 }
2284 }
2285 }
2286
2287 exit:
2288 error:
2289 /* Notify that the registration thread is gone */
2290 notify_ust_apps(0);
2291
2292 if (apps_sock >= 0) {
2293 ret = close(apps_sock);
2294 if (ret) {
2295 PERROR("close");
2296 }
2297 }
2298 if (sock >= 0) {
2299 ret = close(sock);
2300 if (ret) {
2301 PERROR("close");
2302 }
2303 lttng_fd_put(LTTNG_FD_APPS, 1);
2304 }
2305 unlink(apps_unix_sock_path);
2306
2307 error_poll_add:
2308 lttng_poll_clean(&events);
2309 error_listen:
2310 error_create_poll:
2311 error_testpoint:
2312 DBG("UST Registration thread cleanup complete");
2313 if (err) {
2314 health_error();
2315 ERR("Health error occurred in %s", __func__);
2316 }
2317 health_unregister(health_sessiond);
2318
2319 return NULL;
2320 }
2321
2322 /*
2323 * Start the thread_manage_consumer. This must be done after a lttng-consumerd
2324 * exec or it will fails.
2325 */
2326 static int spawn_consumer_thread(struct consumer_data *consumer_data)
2327 {
2328 int ret, clock_ret;
2329 struct timespec timeout;
2330
2331 /*
2332 * Make sure we set the readiness flag to 0 because we are NOT ready.
2333 * This access to consumer_thread_is_ready does not need to be
2334 * protected by consumer_data.cond_mutex (yet) since the consumer
2335 * management thread has not been started at this point.
2336 */
2337 consumer_data->consumer_thread_is_ready = 0;
2338
2339 /* Setup pthread condition */
2340 ret = pthread_condattr_init(&consumer_data->condattr);
2341 if (ret) {
2342 errno = ret;
2343 PERROR("pthread_condattr_init consumer data");
2344 goto error;
2345 }
2346
2347 /*
2348 * Set the monotonic clock in order to make sure we DO NOT jump in time
2349 * between the clock_gettime() call and the timedwait call. See bug #324
2350 * for a more details and how we noticed it.
2351 */
2352 ret = pthread_condattr_setclock(&consumer_data->condattr, CLOCK_MONOTONIC);
2353 if (ret) {
2354 errno = ret;
2355 PERROR("pthread_condattr_setclock consumer data");
2356 goto error;
2357 }
2358
2359 ret = pthread_cond_init(&consumer_data->cond, &consumer_data->condattr);
2360 if (ret) {
2361 errno = ret;
2362 PERROR("pthread_cond_init consumer data");
2363 goto error;
2364 }
2365
2366 ret = pthread_create(&consumer_data->thread, default_pthread_attr(),
2367 thread_manage_consumer, consumer_data);
2368 if (ret) {
2369 errno = ret;
2370 PERROR("pthread_create consumer");
2371 ret = -1;
2372 goto error;
2373 }
2374
2375 /* We are about to wait on a pthread condition */
2376 pthread_mutex_lock(&consumer_data->cond_mutex);
2377
2378 /* Get time for sem_timedwait absolute timeout */
2379 clock_ret = lttng_clock_gettime(CLOCK_MONOTONIC, &timeout);
2380 /*
2381 * Set the timeout for the condition timed wait even if the clock gettime
2382 * call fails since we might loop on that call and we want to avoid to
2383 * increment the timeout too many times.
2384 */
2385 timeout.tv_sec += DEFAULT_SEM_WAIT_TIMEOUT;
2386
2387 /*
2388 * The following loop COULD be skipped in some conditions so this is why we
2389 * set ret to 0 in order to make sure at least one round of the loop is
2390 * done.
2391 */
2392 ret = 0;
2393
2394 /*
2395 * Loop until the condition is reached or when a timeout is reached. Note
2396 * that the pthread_cond_timedwait(P) man page specifies that EINTR can NOT
2397 * be returned but the pthread_cond(3), from the glibc-doc, says that it is
2398 * possible. This loop does not take any chances and works with both of
2399 * them.
2400 */
2401 while (!consumer_data->consumer_thread_is_ready && ret != ETIMEDOUT) {
2402 if (clock_ret < 0) {
2403 PERROR("clock_gettime spawn consumer");
2404 /* Infinite wait for the consumerd thread to be ready */
2405 ret = pthread_cond_wait(&consumer_data->cond,
2406 &consumer_data->cond_mutex);
2407 } else {
2408 ret = pthread_cond_timedwait(&consumer_data->cond,
2409 &consumer_data->cond_mutex, &timeout);
2410 }
2411 }
2412
2413 /* Release the pthread condition */
2414 pthread_mutex_unlock(&consumer_data->cond_mutex);
2415
2416 if (ret != 0) {
2417 errno = ret;
2418 if (ret == ETIMEDOUT) {
2419 int pth_ret;
2420
2421 /*
2422 * Call has timed out so we kill the kconsumerd_thread and return
2423 * an error.
2424 */
2425 ERR("Condition timed out. The consumer thread was never ready."
2426 " Killing it");
2427 pth_ret = pthread_cancel(consumer_data->thread);
2428 if (pth_ret < 0) {
2429 PERROR("pthread_cancel consumer thread");
2430 }
2431 } else {
2432 PERROR("pthread_cond_wait failed consumer thread");
2433 }
2434 /* Caller is expecting a negative value on failure. */
2435 ret = -1;
2436 goto error;
2437 }
2438
2439 pthread_mutex_lock(&consumer_data->pid_mutex);
2440 if (consumer_data->pid == 0) {
2441 ERR("Consumerd did not start");
2442 pthread_mutex_unlock(&consumer_data->pid_mutex);
2443 goto error;
2444 }
2445 pthread_mutex_unlock(&consumer_data->pid_mutex);
2446
2447 return 0;
2448
2449 error:
2450 return ret;
2451 }
2452
2453 /*
2454 * Join consumer thread
2455 */
2456 static int join_consumer_thread(struct consumer_data *consumer_data)
2457 {
2458 void *status;
2459
2460 /* Consumer pid must be a real one. */
2461 if (consumer_data->pid > 0) {
2462 int ret;
2463 ret = kill(consumer_data->pid, SIGTERM);
2464 if (ret) {
2465 PERROR("Error killing consumer daemon");
2466 return ret;
2467 }
2468 return pthread_join(consumer_data->thread, &status);
2469 } else {
2470 return 0;
2471 }
2472 }
2473
2474 /*
2475 * Fork and exec a consumer daemon (consumerd).
2476 *
2477 * Return pid if successful else -1.
2478 */
2479 static pid_t spawn_consumerd(struct consumer_data *consumer_data)
2480 {
2481 int ret;
2482 pid_t pid;
2483 const char *consumer_to_use;
2484 const char *verbosity;
2485 struct stat st;
2486
2487 DBG("Spawning consumerd");
2488
2489 pid = fork();
2490 if (pid == 0) {
2491 /*
2492 * Exec consumerd.
2493 */
2494 if (opt_verbose_consumer) {
2495 verbosity = "--verbose";
2496 } else if (lttng_opt_quiet) {
2497 verbosity = "--quiet";
2498 } else {
2499 verbosity = "";
2500 }
2501
2502 switch (consumer_data->type) {
2503 case LTTNG_CONSUMER_KERNEL:
2504 /*
2505 * Find out which consumerd to execute. We will first try the
2506 * 64-bit path, then the sessiond's installation directory, and
2507 * fallback on the 32-bit one,
2508 */
2509 DBG3("Looking for a kernel consumer at these locations:");
2510 DBG3(" 1) %s", consumerd64_bin);
2511 DBG3(" 2) %s/%s", INSTALL_BIN_PATH, CONSUMERD_FILE);
2512 DBG3(" 3) %s", consumerd32_bin);
2513 if (stat(consumerd64_bin, &st) == 0) {
2514 DBG3("Found location #1");
2515 consumer_to_use = consumerd64_bin;
2516 } else if (stat(INSTALL_BIN_PATH "/" CONSUMERD_FILE, &st) == 0) {
2517 DBG3("Found location #2");
2518 consumer_to_use = INSTALL_BIN_PATH "/" CONSUMERD_FILE;
2519 } else if (stat(consumerd32_bin, &st) == 0) {
2520 DBG3("Found location #3");
2521 consumer_to_use = consumerd32_bin;
2522 } else {
2523 DBG("Could not find any valid consumerd executable");
2524 ret = -EINVAL;
2525 break;
2526 }
2527 DBG("Using kernel consumer at: %s", consumer_to_use);
2528 ret = execl(consumer_to_use,
2529 "lttng-consumerd", verbosity, "-k",
2530 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2531 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2532 "--group", tracing_group_name,
2533 NULL);
2534 break;
2535 case LTTNG_CONSUMER64_UST:
2536 {
2537 char *tmpnew = NULL;
2538
2539 if (consumerd64_libdir[0] != '\0') {
2540 char *tmp;
2541 size_t tmplen;
2542
2543 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2544 if (!tmp) {
2545 tmp = "";
2546 }
2547 tmplen = strlen("LD_LIBRARY_PATH=")
2548 + strlen(consumerd64_libdir) + 1 /* : */ + strlen(tmp);
2549 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2550 if (!tmpnew) {
2551 ret = -ENOMEM;
2552 goto error;
2553 }
2554 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2555 strcat(tmpnew, consumerd64_libdir);
2556 if (tmp[0] != '\0') {
2557 strcat(tmpnew, ":");
2558 strcat(tmpnew, tmp);
2559 }
2560 ret = putenv(tmpnew);
2561 if (ret) {
2562 ret = -errno;
2563 free(tmpnew);
2564 goto error;
2565 }
2566 }
2567 DBG("Using 64-bit UST consumer at: %s", consumerd64_bin);
2568 ret = execl(consumerd64_bin, "lttng-consumerd", verbosity, "-u",
2569 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2570 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2571 "--group", tracing_group_name,
2572 NULL);
2573 if (consumerd64_libdir[0] != '\0') {
2574 free(tmpnew);
2575 }
2576 break;
2577 }
2578 case LTTNG_CONSUMER32_UST:
2579 {
2580 char *tmpnew = NULL;
2581
2582 if (consumerd32_libdir[0] != '\0') {
2583 char *tmp;
2584 size_t tmplen;
2585
2586 tmp = lttng_secure_getenv("LD_LIBRARY_PATH");
2587 if (!tmp) {
2588 tmp = "";
2589 }
2590 tmplen = strlen("LD_LIBRARY_PATH=")
2591 + strlen(consumerd32_libdir) + 1 /* : */ + strlen(tmp);
2592 tmpnew = zmalloc(tmplen + 1 /* \0 */);
2593 if (!tmpnew) {
2594 ret = -ENOMEM;
2595 goto error;
2596 }
2597 strcpy(tmpnew, "LD_LIBRARY_PATH=");
2598 strcat(tmpnew, consumerd32_libdir);
2599 if (tmp[0] != '\0') {
2600 strcat(tmpnew, ":");
2601 strcat(tmpnew, tmp);
2602 }
2603 ret = putenv(tmpnew);
2604 if (ret) {
2605 ret = -errno;
2606 free(tmpnew);
2607 goto error;
2608 }
2609 }
2610 DBG("Using 32-bit UST consumer at: %s", consumerd32_bin);
2611 ret = execl(consumerd32_bin, "lttng-consumerd", verbosity, "-u",
2612 "--consumerd-cmd-sock", consumer_data->cmd_unix_sock_path,
2613 "--consumerd-err-sock", consumer_data->err_unix_sock_path,
2614 "--group", tracing_group_name,
2615 NULL);
2616 if (consumerd32_libdir[0] != '\0') {
2617 free(tmpnew);
2618 }
2619 break;
2620 }
2621 default:
2622 PERROR("unknown consumer type");
2623 exit(EXIT_FAILURE);
2624 }
2625 if (errno != 0) {
2626 PERROR("Consumer execl()");
2627 }
2628 /* Reaching this point, we got a failure on our execl(). */
2629 exit(EXIT_FAILURE);
2630 } else if (pid > 0) {
2631 ret = pid;
2632 } else {
2633 PERROR("start consumer fork");
2634 ret = -errno;
2635 }
2636 error:
2637 return ret;
2638 }
2639
2640 /*
2641 * Spawn the consumerd daemon and session daemon thread.
2642 */
2643 static int start_consumerd(struct consumer_data *consumer_data)
2644 {
2645 int ret;
2646
2647 /*
2648 * Set the listen() state on the socket since there is a possible race
2649 * between the exec() of the consumer daemon and this call if place in the
2650 * consumer thread. See bug #366 for more details.
2651 */
2652 ret = lttcomm_listen_unix_sock(consumer_data->err_sock);
2653 if (ret < 0) {
2654 goto error;
2655 }
2656
2657 pthread_mutex_lock(&consumer_data->pid_mutex);
2658 if (consumer_data->pid != 0) {
2659 pthread_mutex_unlock(&consumer_data->pid_mutex);
2660 goto end;
2661 }
2662
2663 ret = spawn_consumerd(consumer_data);
2664 if (ret < 0) {
2665 ERR("Spawning consumerd failed");
2666 pthread_mutex_unlock(&consumer_data->pid_mutex);
2667 goto error;
2668 }
2669
2670 /* Setting up the consumer_data pid */
2671 consumer_data->pid = ret;
2672 DBG2("Consumer pid %d", consumer_data->pid);
2673 pthread_mutex_unlock(&consumer_data->pid_mutex);
2674
2675 DBG2("Spawning consumer control thread");
2676 ret = spawn_consumer_thread(consumer_data);
2677 if (ret < 0) {
2678 ERR("Fatal error spawning consumer control thread");
2679 goto error;
2680 }
2681
2682 end:
2683 return 0;
2684
2685 error:
2686 /* Cleanup already created sockets on error. */
2687 if (consumer_data->err_sock >= 0) {
2688 int err;
2689
2690 err = close(consumer_data->err_sock);
2691 if (err < 0) {
2692 PERROR("close consumer data error socket");
2693 }
2694 }
2695 return ret;
2696 }
2697
2698 /*
2699 * Setup necessary data for kernel tracer action.
2700 */
2701 static int init_kernel_tracer(void)
2702 {
2703 int ret;
2704
2705 /* Modprobe lttng kernel modules */
2706 ret = modprobe_lttng_control();
2707 if (ret < 0) {
2708 goto error;
2709 }
2710
2711 /* Open debugfs lttng */
2712 kernel_tracer_fd = open(module_proc_lttng, O_RDWR);
2713 if (kernel_tracer_fd < 0) {
2714 DBG("Failed to open %s", module_proc_lttng);
2715 ret = -1;
2716 goto error_open;
2717 }
2718
2719 /* Validate kernel version */
2720 ret = kernel_validate_version(kernel_tracer_fd);
2721 if (ret < 0) {
2722 goto error_version;
2723 }
2724
2725 ret = modprobe_lttng_data();
2726 if (ret < 0) {
2727 goto error_modules;
2728 }
2729
2730 DBG("Kernel tracer fd %d", kernel_tracer_fd);
2731 return 0;
2732
2733 error_version:
2734 modprobe_remove_lttng_control();
2735 ret = close(kernel_tracer_fd);
2736 if (ret) {
2737 PERROR("close");
2738 }
2739 kernel_tracer_fd = -1;
2740 return LTTNG_ERR_KERN_VERSION;
2741
2742 error_modules:
2743 ret = close(kernel_tracer_fd);
2744 if (ret) {
2745 PERROR("close");
2746 }
2747
2748 error_open:
2749 modprobe_remove_lttng_control();
2750
2751 error:
2752 WARN("No kernel tracer available");
2753 kernel_tracer_fd = -1;
2754 if (!is_root) {
2755 return LTTNG_ERR_NEED_ROOT_SESSIOND;
2756 } else {
2757 return LTTNG_ERR_KERN_NA;
2758 }
2759 }
2760
2761
2762 /*
2763 * Copy consumer output from the tracing session to the domain session. The
2764 * function also applies the right modification on a per domain basis for the
2765 * trace files destination directory.
2766 *
2767 * Should *NOT* be called with RCU read-side lock held.
2768 */
2769 static int copy_session_consumer(int domain, struct ltt_session *session)
2770 {
2771 int ret;
2772 const char *dir_name;
2773 struct consumer_output *consumer;
2774
2775 assert(session);
2776 assert(session->consumer);
2777
2778 switch (domain) {
2779 case LTTNG_DOMAIN_KERNEL:
2780 DBG3("Copying tracing session consumer output in kernel session");
2781 /*
2782 * XXX: We should audit the session creation and what this function
2783 * does "extra" in order to avoid a destroy since this function is used
2784 * in the domain session creation (kernel and ust) only. Same for UST
2785 * domain.
2786 */
2787 if (session->kernel_session->consumer) {
2788 consumer_output_put(session->kernel_session->consumer);
2789 }
2790 session->kernel_session->consumer =
2791 consumer_copy_output(session->consumer);
2792 /* Ease our life a bit for the next part */
2793 consumer = session->kernel_session->consumer;
2794 dir_name = DEFAULT_KERNEL_TRACE_DIR;
2795 break;
2796 case LTTNG_DOMAIN_JUL:
2797 case LTTNG_DOMAIN_LOG4J:
2798 case LTTNG_DOMAIN_PYTHON:
2799 case LTTNG_DOMAIN_UST:
2800 DBG3("Copying tracing session consumer output in UST session");
2801 if (session->ust_session->consumer) {
2802 consumer_output_put(session->ust_session->consumer);
2803 }
2804 session->ust_session->consumer =
2805 consumer_copy_output(session->consumer);
2806 /* Ease our life a bit for the next part */
2807 consumer = session->ust_session->consumer;
2808 dir_name = DEFAULT_UST_TRACE_DIR;
2809 break;
2810 default:
2811 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2812 goto error;
2813 }
2814
2815 /* Append correct directory to subdir */
2816 strncat(consumer->subdir, dir_name,
2817 sizeof(consumer->subdir) - strlen(consumer->subdir) - 1);
2818 DBG3("Copy session consumer subdir %s", consumer->subdir);
2819
2820 ret = LTTNG_OK;
2821
2822 error:
2823 return ret;
2824 }
2825
2826 /*
2827 * Create an UST session and add it to the session ust list.
2828 *
2829 * Should *NOT* be called with RCU read-side lock held.
2830 */
2831 static int create_ust_session(struct ltt_session *session,
2832 struct lttng_domain *domain)
2833 {
2834 int ret;
2835 struct ltt_ust_session *lus = NULL;
2836
2837 assert(session);
2838 assert(domain);
2839 assert(session->consumer);
2840
2841 switch (domain->type) {
2842 case LTTNG_DOMAIN_JUL:
2843 case LTTNG_DOMAIN_LOG4J:
2844 case LTTNG_DOMAIN_PYTHON:
2845 case LTTNG_DOMAIN_UST:
2846 break;
2847 default:
2848 ERR("Unknown UST domain on create session %d", domain->type);
2849 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
2850 goto error;
2851 }
2852
2853 DBG("Creating UST session");
2854
2855 lus = trace_ust_create_session(session->id);
2856 if (lus == NULL) {
2857 ret = LTTNG_ERR_UST_SESS_FAIL;
2858 goto error;
2859 }
2860
2861 lus->uid = session->uid;
2862 lus->gid = session->gid;
2863 lus->output_traces = session->output_traces;
2864 lus->snapshot_mode = session->snapshot_mode;
2865 lus->live_timer_interval = session->live_timer;
2866 session->ust_session = lus;
2867 if (session->shm_path[0]) {
2868 strncpy(lus->root_shm_path, session->shm_path,
2869 sizeof(lus->root_shm_path));
2870 lus->root_shm_path[sizeof(lus->root_shm_path) - 1] = '\0';
2871 strncpy(lus->shm_path, session->shm_path,
2872 sizeof(lus->shm_path));
2873 lus->shm_path[sizeof(lus->shm_path) - 1] = '\0';
2874 strncat(lus->shm_path, "/ust",
2875 sizeof(lus->shm_path) - strlen(lus->shm_path) - 1);
2876 }
2877 /* Copy session output to the newly created UST session */
2878 ret = copy_session_consumer(domain->type, session);
2879 if (ret != LTTNG_OK) {
2880 goto error;
2881 }
2882
2883 return LTTNG_OK;
2884
2885 error:
2886 free(lus);
2887 session->ust_session = NULL;
2888 return ret;
2889 }
2890
2891 /*
2892 * Create a kernel tracer session then create the default channel.
2893 */
2894 static int create_kernel_session(struct ltt_session *session)
2895 {
2896 int ret;
2897
2898 DBG("Creating kernel session");
2899
2900 ret = kernel_create_session(session, kernel_tracer_fd);
2901 if (ret < 0) {
2902 ret = LTTNG_ERR_KERN_SESS_FAIL;
2903 goto error;
2904 }
2905
2906 /* Code flow safety */
2907 assert(session->kernel_session);
2908
2909 /* Copy session output to the newly created Kernel session */
2910 ret = copy_session_consumer(LTTNG_DOMAIN_KERNEL, session);
2911 if (ret != LTTNG_OK) {
2912 goto error;
2913 }
2914
2915 /* Create directory(ies) on local filesystem. */
2916 if (session->kernel_session->consumer->type == CONSUMER_DST_LOCAL &&
2917 strlen(session->kernel_session->consumer->dst.trace_path) > 0) {
2918 ret = run_as_mkdir_recursive(
2919 session->kernel_session->consumer->dst.trace_path,
2920 S_IRWXU | S_IRWXG, session->uid, session->gid);
2921 if (ret < 0) {
2922 if (errno != EEXIST) {
2923 ERR("Trace directory creation error");
2924 goto error;
2925 }
2926 }
2927 }
2928
2929 session->kernel_session->uid = session->uid;
2930 session->kernel_session->gid = session->gid;
2931 session->kernel_session->output_traces = session->output_traces;
2932 session->kernel_session->snapshot_mode = session->snapshot_mode;
2933
2934 return LTTNG_OK;
2935
2936 error:
2937 trace_kernel_destroy_session(session->kernel_session);
2938 session->kernel_session = NULL;
2939 return ret;
2940 }
2941
2942 /*
2943 * Count number of session permitted by uid/gid.
2944 */
2945 static unsigned int lttng_sessions_count(uid_t uid, gid_t gid)
2946 {
2947 unsigned int i = 0;
2948 struct ltt_session *session;
2949
2950 DBG("Counting number of available session for UID %d GID %d",
2951 uid, gid);
2952 cds_list_for_each_entry(session, &session_list_ptr->head, list) {
2953 /*
2954 * Only list the sessions the user can control.
2955 */
2956 if (!session_access_ok(session, uid, gid)) {
2957 continue;
2958 }
2959 i++;
2960 }
2961 return i;
2962 }
2963
2964 /*
2965 * Process the command requested by the lttng client within the command
2966 * context structure. This function make sure that the return structure (llm)
2967 * is set and ready for transmission before returning.
2968 *
2969 * Return any error encountered or 0 for success.
2970 *
2971 * "sock" is only used for special-case var. len data.
2972 *
2973 * Should *NOT* be called with RCU read-side lock held.
2974 */
2975 static int process_client_msg(struct command_ctx *cmd_ctx, int sock,
2976 int *sock_error)
2977 {
2978 int ret = LTTNG_OK;
2979 int need_tracing_session = 1;
2980 int need_domain;
2981
2982 DBG("Processing client command %d", cmd_ctx->lsm->cmd_type);
2983
2984 assert(!rcu_read_ongoing());
2985
2986 *sock_error = 0;
2987
2988 switch (cmd_ctx->lsm->cmd_type) {
2989 case LTTNG_CREATE_SESSION:
2990 case LTTNG_CREATE_SESSION_SNAPSHOT:
2991 case LTTNG_CREATE_SESSION_LIVE:
2992 case LTTNG_DESTROY_SESSION:
2993 case LTTNG_LIST_SESSIONS:
2994 case LTTNG_LIST_DOMAINS:
2995 case LTTNG_START_TRACE:
2996 case LTTNG_STOP_TRACE:
2997 case LTTNG_DATA_PENDING:
2998 case LTTNG_SNAPSHOT_ADD_OUTPUT:
2999 case LTTNG_SNAPSHOT_DEL_OUTPUT:
3000 case LTTNG_SNAPSHOT_LIST_OUTPUT:
3001 case LTTNG_SNAPSHOT_RECORD:
3002 case LTTNG_SAVE_SESSION:
3003 case LTTNG_SET_SESSION_SHM_PATH:
3004 case LTTNG_REGENERATE_METADATA:
3005 case LTTNG_REGENERATE_STATEDUMP:
3006 need_domain = 0;
3007 break;
3008 default:
3009 need_domain = 1;
3010 }
3011
3012 if (opt_no_kernel && need_domain
3013 && cmd_ctx->lsm->domain.type == LTTNG_DOMAIN_KERNEL) {
3014 if (!is_root) {
3015 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3016 } else {
3017 ret = LTTNG_ERR_KERN_NA;
3018 }
3019 goto error;
3020 }
3021
3022 /* Deny register consumer if we already have a spawned consumer. */
3023 if (cmd_ctx->lsm->cmd_type == LTTNG_REGISTER_CONSUMER) {
3024 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3025 if (kconsumer_data.pid > 0) {
3026 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3027 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3028 goto error;
3029 }
3030 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3031 }
3032
3033 /*
3034 * Check for command that don't needs to allocate a returned payload. We do
3035 * this here so we don't have to make the call for no payload at each
3036 * command.
3037 */
3038 switch(cmd_ctx->lsm->cmd_type) {
3039 case LTTNG_LIST_SESSIONS:
3040 case LTTNG_LIST_TRACEPOINTS:
3041 case LTTNG_LIST_TRACEPOINT_FIELDS:
3042 case LTTNG_LIST_DOMAINS:
3043 case LTTNG_LIST_CHANNELS:
3044 case LTTNG_LIST_EVENTS:
3045 case LTTNG_LIST_SYSCALLS:
3046 case LTTNG_LIST_TRACKER_PIDS:
3047 case LTTNG_DATA_PENDING:
3048 break;
3049 default:
3050 /* Setup lttng message with no payload */
3051 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0);
3052 if (ret < 0) {
3053 /* This label does not try to unlock the session */
3054 goto init_setup_error;
3055 }
3056 }
3057
3058 /* Commands that DO NOT need a session. */
3059 switch (cmd_ctx->lsm->cmd_type) {
3060 case LTTNG_CREATE_SESSION:
3061 case LTTNG_CREATE_SESSION_SNAPSHOT:
3062 case LTTNG_CREATE_SESSION_LIVE:
3063 case LTTNG_LIST_SESSIONS:
3064 case LTTNG_LIST_TRACEPOINTS:
3065 case LTTNG_LIST_SYSCALLS:
3066 case LTTNG_LIST_TRACEPOINT_FIELDS:
3067 case LTTNG_SAVE_SESSION:
3068 need_tracing_session = 0;
3069 break;
3070 default:
3071 DBG("Getting session %s by name", cmd_ctx->lsm->session.name);
3072 /*
3073 * We keep the session list lock across _all_ commands
3074 * for now, because the per-session lock does not
3075 * handle teardown properly.
3076 */
3077 session_lock_list();
3078 cmd_ctx->session = session_find_by_name(cmd_ctx->lsm->session.name);
3079 if (cmd_ctx->session == NULL) {
3080 ret = LTTNG_ERR_SESS_NOT_FOUND;
3081 goto error;
3082 } else {
3083 /* Acquire lock for the session */
3084 session_lock(cmd_ctx->session);
3085 }
3086 break;
3087 }
3088
3089 /*
3090 * Commands that need a valid session but should NOT create one if none
3091 * exists. Instead of creating one and destroying it when the command is
3092 * handled, process that right before so we save some round trip in useless
3093 * code path.
3094 */
3095 switch (cmd_ctx->lsm->cmd_type) {
3096 case LTTNG_DISABLE_CHANNEL:
3097 case LTTNG_DISABLE_EVENT:
3098 switch (cmd_ctx->lsm->domain.type) {
3099 case LTTNG_DOMAIN_KERNEL:
3100 if (!cmd_ctx->session->kernel_session) {
3101 ret = LTTNG_ERR_NO_CHANNEL;
3102 goto error;
3103 }
3104 break;
3105 case LTTNG_DOMAIN_JUL:
3106 case LTTNG_DOMAIN_LOG4J:
3107 case LTTNG_DOMAIN_PYTHON:
3108 case LTTNG_DOMAIN_UST:
3109 if (!cmd_ctx->session->ust_session) {
3110 ret = LTTNG_ERR_NO_CHANNEL;
3111 goto error;
3112 }
3113 break;
3114 default:
3115 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3116 goto error;
3117 }
3118 default:
3119 break;
3120 }
3121
3122 if (!need_domain) {
3123 goto skip_domain;
3124 }
3125
3126 /*
3127 * Check domain type for specific "pre-action".
3128 */
3129 switch (cmd_ctx->lsm->domain.type) {
3130 case LTTNG_DOMAIN_KERNEL:
3131 if (!is_root) {
3132 ret = LTTNG_ERR_NEED_ROOT_SESSIOND;
3133 goto error;
3134 }
3135
3136 /* Kernel tracer check */
3137 if (kernel_tracer_fd == -1) {
3138 /* Basically, load kernel tracer modules */
3139 ret = init_kernel_tracer();
3140 if (ret != 0) {
3141 goto error;
3142 }
3143 }
3144
3145 /* Consumer is in an ERROR state. Report back to client */
3146 if (uatomic_read(&kernel_consumerd_state) == CONSUMER_ERROR) {
3147 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3148 goto error;
3149 }
3150
3151 /* Need a session for kernel command */
3152 if (need_tracing_session) {
3153 if (cmd_ctx->session->kernel_session == NULL) {
3154 ret = create_kernel_session(cmd_ctx->session);
3155 if (ret < 0) {
3156 ret = LTTNG_ERR_KERN_SESS_FAIL;
3157 goto error;
3158 }
3159 }
3160
3161 /* Start the kernel consumer daemon */
3162 pthread_mutex_lock(&kconsumer_data.pid_mutex);
3163 if (kconsumer_data.pid == 0 &&
3164 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3165 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3166 ret = start_consumerd(&kconsumer_data);
3167 if (ret < 0) {
3168 ret = LTTNG_ERR_KERN_CONSUMER_FAIL;
3169 goto error;
3170 }
3171 uatomic_set(&kernel_consumerd_state, CONSUMER_STARTED);
3172 } else {
3173 pthread_mutex_unlock(&kconsumer_data.pid_mutex);
3174 }
3175
3176 /*
3177 * The consumer was just spawned so we need to add the socket to
3178 * the consumer output of the session if exist.
3179 */
3180 ret = consumer_create_socket(&kconsumer_data,
3181 cmd_ctx->session->kernel_session->consumer);
3182 if (ret < 0) {
3183 goto error;
3184 }
3185 }
3186
3187 break;
3188 case LTTNG_DOMAIN_JUL:
3189 case LTTNG_DOMAIN_LOG4J:
3190 case LTTNG_DOMAIN_PYTHON:
3191 case LTTNG_DOMAIN_UST:
3192 {
3193 if (!ust_app_supported()) {
3194 ret = LTTNG_ERR_NO_UST;
3195 goto error;
3196 }
3197 /* Consumer is in an ERROR state. Report back to client */
3198 if (uatomic_read(&ust_consumerd_state) == CONSUMER_ERROR) {
3199 ret = LTTNG_ERR_NO_USTCONSUMERD;
3200 goto error;
3201 }
3202
3203 if (need_tracing_session) {
3204 /* Create UST session if none exist. */
3205 if (cmd_ctx->session->ust_session == NULL) {
3206 ret = create_ust_session(cmd_ctx->session,
3207 &cmd_ctx->lsm->domain);
3208 if (ret != LTTNG_OK) {
3209 goto error;
3210 }
3211 }
3212
3213 /* Start the UST consumer daemons */
3214 /* 64-bit */
3215 pthread_mutex_lock(&ustconsumer64_data.pid_mutex);
3216 if (consumerd64_bin[0] != '\0' &&
3217 ustconsumer64_data.pid == 0 &&
3218 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3219 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3220 ret = start_consumerd(&ustconsumer64_data);
3221 if (ret < 0) {
3222 ret = LTTNG_ERR_UST_CONSUMER64_FAIL;
3223 uatomic_set(&ust_consumerd64_fd, -EINVAL);
3224 goto error;
3225 }
3226
3227 uatomic_set(&ust_consumerd64_fd, ustconsumer64_data.cmd_sock);
3228 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3229 } else {
3230 pthread_mutex_unlock(&ustconsumer64_data.pid_mutex);
3231 }
3232
3233 /*
3234 * Setup socket for consumer 64 bit. No need for atomic access
3235 * since it was set above and can ONLY be set in this thread.
3236 */
3237 ret = consumer_create_socket(&ustconsumer64_data,
3238 cmd_ctx->session->ust_session->consumer);
3239 if (ret < 0) {
3240 goto error;
3241 }
3242
3243 /* 32-bit */
3244 pthread_mutex_lock(&ustconsumer32_data.pid_mutex);
3245 if (consumerd32_bin[0] != '\0' &&
3246 ustconsumer32_data.pid == 0 &&
3247 cmd_ctx->lsm->cmd_type != LTTNG_REGISTER_CONSUMER) {
3248 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3249 ret = start_consumerd(&ustconsumer32_data);
3250 if (ret < 0) {
3251 ret = LTTNG_ERR_UST_CONSUMER32_FAIL;
3252 uatomic_set(&ust_consumerd32_fd, -EINVAL);
3253 goto error;
3254 }
3255
3256 uatomic_set(&ust_consumerd32_fd, ustconsumer32_data.cmd_sock);
3257 uatomic_set(&ust_consumerd_state, CONSUMER_STARTED);
3258 } else {
3259 pthread_mutex_unlock(&ustconsumer32_data.pid_mutex);
3260 }
3261
3262 /*
3263 * Setup socket for consumer 64 bit. No need for atomic access
3264 * since it was set above and can ONLY be set in this thread.
3265 */
3266 ret = consumer_create_socket(&ustconsumer32_data,
3267 cmd_ctx->session->ust_session->consumer);
3268 if (ret < 0) {
3269 goto error;
3270 }
3271 }
3272 break;
3273 }
3274 default:
3275 break;
3276 }
3277 skip_domain:
3278
3279 /* Validate consumer daemon state when start/stop trace command */
3280 if (cmd_ctx->lsm->cmd_type == LTTNG_START_TRACE ||
3281 cmd_ctx->lsm->cmd_type == LTTNG_STOP_TRACE) {
3282 switch (cmd_ctx->lsm->domain.type) {
3283 case LTTNG_DOMAIN_NONE:
3284 break;
3285 case LTTNG_DOMAIN_JUL:
3286 case LTTNG_DOMAIN_LOG4J:
3287 case LTTNG_DOMAIN_PYTHON:
3288 case LTTNG_DOMAIN_UST:
3289 if (uatomic_read(&ust_consumerd_state) != CONSUMER_STARTED) {
3290 ret = LTTNG_ERR_NO_USTCONSUMERD;
3291 goto error;
3292 }
3293 break;
3294 case LTTNG_DOMAIN_KERNEL:
3295 if (uatomic_read(&kernel_consumerd_state) != CONSUMER_STARTED) {
3296 ret = LTTNG_ERR_NO_KERNCONSUMERD;
3297 goto error;
3298 }
3299 break;
3300 default:
3301 ret = LTTNG_ERR_UNKNOWN_DOMAIN;
3302 goto error;
3303 }
3304 }
3305
3306 /*
3307 * Check that the UID or GID match that of the tracing session.
3308 * The root user can interact with all sessions.
3309 */
3310 if (need_tracing_session) {
3311 if (!session_access_ok(cmd_ctx->session,
3312 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3313 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds))) {
3314 ret = LTTNG_ERR_EPERM;
3315 goto error;
3316 }
3317 }
3318
3319 /*
3320 * Send relayd information to consumer as soon as we have a domain and a
3321 * session defined.
3322 */
3323 if (cmd_ctx->session && need_domain) {
3324 /*
3325 * Setup relayd if not done yet. If the relayd information was already
3326 * sent to the consumer, this call will gracefully return.
3327 */
3328 ret = cmd_setup_relayd(cmd_ctx->session);
3329 if (ret != LTTNG_OK) {
3330 goto error;
3331 }
3332 }
3333
3334 /* Process by command type */
3335 switch (cmd_ctx->lsm->cmd_type) {
3336 case LTTNG_ADD_CONTEXT:
3337 {
3338 /*
3339 * An LTTNG_ADD_CONTEXT command might have a supplementary
3340 * payload if the context being added is an application context.
3341 */
3342 if (cmd_ctx->lsm->u.context.ctx.ctx ==
3343 LTTNG_EVENT_CONTEXT_APP_CONTEXT) {
3344 char *provider_name = NULL, *context_name = NULL;
3345 size_t provider_name_len =
3346 cmd_ctx->lsm->u.context.provider_name_len;
3347 size_t context_name_len =
3348 cmd_ctx->lsm->u.context.context_name_len;
3349
3350 if (provider_name_len == 0 || context_name_len == 0) {
3351 /*
3352 * Application provider and context names MUST
3353 * be provided.
3354 */
3355 ret = -LTTNG_ERR_INVALID;
3356 goto error;
3357 }
3358
3359 provider_name = zmalloc(provider_name_len + 1);
3360 if (!provider_name) {
3361 ret = -LTTNG_ERR_NOMEM;
3362 goto error;
3363 }
3364 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name =
3365 provider_name;
3366
3367 context_name = zmalloc(context_name_len + 1);
3368 if (!context_name) {
3369 ret = -LTTNG_ERR_NOMEM;
3370 goto error_add_context;
3371 }
3372 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name =
3373 context_name;
3374
3375 ret = lttcomm_recv_unix_sock(sock, provider_name,
3376 provider_name_len);
3377 if (ret < 0) {
3378 goto error_add_context;
3379 }
3380
3381 ret = lttcomm_recv_unix_sock(sock, context_name,
3382 context_name_len);
3383 if (ret < 0) {
3384 goto error_add_context;
3385 }
3386 }
3387
3388 /*
3389 * cmd_add_context assumes ownership of the provider and context
3390 * names.
3391 */
3392 ret = cmd_add_context(cmd_ctx->session,
3393 cmd_ctx->lsm->domain.type,
3394 cmd_ctx->lsm->u.context.channel_name,
3395 &cmd_ctx->lsm->u.context.ctx,
3396 kernel_poll_pipe[1]);
3397
3398 cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name = NULL;
3399 cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name = NULL;
3400 error_add_context:
3401 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.provider_name);
3402 free(cmd_ctx->lsm->u.context.ctx.u.app_ctx.ctx_name);
3403 if (ret < 0) {
3404 goto error;
3405 }
3406 break;
3407 }
3408 case LTTNG_DISABLE_CHANNEL:
3409 {
3410 ret = cmd_disable_channel(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3411 cmd_ctx->lsm->u.disable.channel_name);
3412 break;
3413 }
3414 case LTTNG_DISABLE_EVENT:
3415 {
3416
3417 /*
3418 * FIXME: handle filter; for now we just receive the filter's
3419 * bytecode along with the filter expression which are sent by
3420 * liblttng-ctl and discard them.
3421 *
3422 * This fixes an issue where the client may block while sending
3423 * the filter payload and encounter an error because the session
3424 * daemon closes the socket without ever handling this data.
3425 */
3426 size_t count = cmd_ctx->lsm->u.disable.expression_len +
3427 cmd_ctx->lsm->u.disable.bytecode_len;
3428
3429 if (count) {
3430 char data[LTTNG_FILTER_MAX_LEN];
3431
3432 DBG("Discarding disable event command payload of size %zu", count);
3433 while (count) {
3434 ret = lttcomm_recv_unix_sock(sock, data,
3435 count > sizeof(data) ? sizeof(data) : count);
3436 if (ret < 0) {
3437 goto error;
3438 }
3439
3440 count -= (size_t) ret;
3441 }
3442 }
3443 /* FIXME: passing packed structure to non-packed pointer */
3444 ret = cmd_disable_event(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3445 cmd_ctx->lsm->u.disable.channel_name,
3446 &cmd_ctx->lsm->u.disable.event);
3447 break;
3448 }
3449 case LTTNG_ENABLE_CHANNEL:
3450 {
3451 ret = cmd_enable_channel(cmd_ctx->session, &cmd_ctx->lsm->domain,
3452 &cmd_ctx->lsm->u.channel.chan, kernel_poll_pipe[1]);
3453 break;
3454 }
3455 case LTTNG_TRACK_PID:
3456 {
3457 ret = cmd_track_pid(cmd_ctx->session,
3458 cmd_ctx->lsm->domain.type,
3459 cmd_ctx->lsm->u.pid_tracker.pid);
3460 break;
3461 }
3462 case LTTNG_UNTRACK_PID:
3463 {
3464 ret = cmd_untrack_pid(cmd_ctx->session,
3465 cmd_ctx->lsm->domain.type,
3466 cmd_ctx->lsm->u.pid_tracker.pid);
3467 break;
3468 }
3469 case LTTNG_ENABLE_EVENT:
3470 {
3471 struct lttng_event_exclusion *exclusion = NULL;
3472 struct lttng_filter_bytecode *bytecode = NULL;
3473 char *filter_expression = NULL;
3474
3475 /* Handle exclusion events and receive it from the client. */
3476 if (cmd_ctx->lsm->u.enable.exclusion_count > 0) {
3477 size_t count = cmd_ctx->lsm->u.enable.exclusion_count;
3478
3479 exclusion = zmalloc(sizeof(struct lttng_event_exclusion) +
3480 (count * LTTNG_SYMBOL_NAME_LEN));
3481 if (!exclusion) {
3482 ret = LTTNG_ERR_EXCLUSION_NOMEM;
3483 goto error;
3484 }
3485
3486 DBG("Receiving var len exclusion event list from client ...");
3487 exclusion->count = count;
3488 ret = lttcomm_recv_unix_sock(sock, exclusion->names,
3489 count * LTTNG_SYMBOL_NAME_LEN);
3490 if (ret <= 0) {
3491 DBG("Nothing recv() from client var len data... continuing");
3492 *sock_error = 1;
3493 free(exclusion);
3494 ret = LTTNG_ERR_EXCLUSION_INVAL;
3495 goto error;
3496 }
3497 }
3498
3499 /* Get filter expression from client. */
3500 if (cmd_ctx->lsm->u.enable.expression_len > 0) {
3501 size_t expression_len =
3502 cmd_ctx->lsm->u.enable.expression_len;
3503
3504 if (expression_len > LTTNG_FILTER_MAX_LEN) {
3505 ret = LTTNG_ERR_FILTER_INVAL;
3506 free(exclusion);
3507 goto error;
3508 }
3509
3510 filter_expression = zmalloc(expression_len);
3511 if (!filter_expression) {
3512 free(exclusion);
3513 ret = LTTNG_ERR_FILTER_NOMEM;
3514 goto error;
3515 }
3516
3517 /* Receive var. len. data */
3518 DBG("Receiving var len filter's expression from client ...");
3519 ret = lttcomm_recv_unix_sock(sock, filter_expression,
3520 expression_len);
3521 if (ret <= 0) {
3522 DBG("Nothing recv() from client car len data... continuing");
3523 *sock_error = 1;
3524 free(filter_expression);
3525 free(exclusion);
3526 ret = LTTNG_ERR_FILTER_INVAL;
3527 goto error;
3528 }
3529 }
3530
3531 /* Handle filter and get bytecode from client. */
3532 if (cmd_ctx->lsm->u.enable.bytecode_len > 0) {
3533 size_t bytecode_len = cmd_ctx->lsm->u.enable.bytecode_len;
3534
3535 if (bytecode_len > LTTNG_FILTER_MAX_LEN) {
3536 ret = LTTNG_ERR_FILTER_INVAL;
3537 free(filter_expression);
3538 free(exclusion);
3539 goto error;
3540 }
3541
3542 bytecode = zmalloc(bytecode_len);
3543 if (!bytecode) {
3544 free(filter_expression);
3545 free(exclusion);
3546 ret = LTTNG_ERR_FILTER_NOMEM;
3547 goto error;
3548 }
3549
3550 /* Receive var. len. data */
3551 DBG("Receiving var len filter's bytecode from client ...");
3552 ret = lttcomm_recv_unix_sock(sock, bytecode, bytecode_len);
3553 if (ret <= 0) {
3554 DBG("Nothing recv() from client car len data... continuing");
3555 *sock_error = 1;
3556 free(filter_expression);
3557 free(bytecode);
3558 free(exclusion);
3559 ret = LTTNG_ERR_FILTER_INVAL;
3560 goto error;
3561 }
3562
3563 if ((bytecode->len + sizeof(*bytecode)) != bytecode_len) {
3564 free(filter_expression);
3565 free(bytecode);
3566 free(exclusion);
3567 ret = LTTNG_ERR_FILTER_INVAL;
3568 goto error;
3569 }
3570 }
3571
3572 ret = cmd_enable_event(cmd_ctx->session, &cmd_ctx->lsm->domain,
3573 cmd_ctx->lsm->u.enable.channel_name,
3574 &cmd_ctx->lsm->u.enable.event,
3575 filter_expression, bytecode, exclusion,
3576 kernel_poll_pipe[1]);
3577 break;
3578 }
3579 case LTTNG_LIST_TRACEPOINTS:
3580 {
3581 struct lttng_event *events;
3582 ssize_t nb_events;
3583
3584 session_lock_list();
3585 nb_events = cmd_list_tracepoints(cmd_ctx->lsm->domain.type, &events);
3586 session_unlock_list();
3587 if (nb_events < 0) {
3588 /* Return value is a negative lttng_error_code. */
3589 ret = -nb_events;
3590 goto error;
3591 }
3592
3593 /*
3594 * Setup lttng message with payload size set to the event list size in
3595 * bytes and then copy list into the llm payload.
3596 */
3597 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3598 sizeof(struct lttng_event) * nb_events);
3599 free(events);
3600
3601 if (ret < 0) {
3602 goto setup_error;
3603 }
3604
3605 ret = LTTNG_OK;
3606 break;
3607 }
3608 case LTTNG_LIST_TRACEPOINT_FIELDS:
3609 {
3610 struct lttng_event_field *fields;
3611 ssize_t nb_fields;
3612
3613 session_lock_list();
3614 nb_fields = cmd_list_tracepoint_fields(cmd_ctx->lsm->domain.type,
3615 &fields);
3616 session_unlock_list();
3617 if (nb_fields < 0) {
3618 /* Return value is a negative lttng_error_code. */
3619 ret = -nb_fields;
3620 goto error;
3621 }
3622
3623 /*
3624 * Setup lttng message with payload size set to the event list size in
3625 * bytes and then copy list into the llm payload.
3626 */
3627 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, fields,
3628 sizeof(struct lttng_event_field) * nb_fields);
3629 free(fields);
3630
3631 if (ret < 0) {
3632 goto setup_error;
3633 }
3634
3635 ret = LTTNG_OK;
3636 break;
3637 }
3638 case LTTNG_LIST_SYSCALLS:
3639 {
3640 struct lttng_event *events;
3641 ssize_t nb_events;
3642
3643 nb_events = cmd_list_syscalls(&events);
3644 if (nb_events < 0) {
3645 /* Return value is a negative lttng_error_code. */
3646 ret = -nb_events;
3647 goto error;
3648 }
3649
3650 /*
3651 * Setup lttng message with payload size set to the event list size in
3652 * bytes and then copy list into the llm payload.
3653 */
3654 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, events,
3655 sizeof(struct lttng_event) * nb_events);
3656 free(events);
3657
3658 if (ret < 0) {
3659 goto setup_error;
3660 }
3661
3662 ret = LTTNG_OK;
3663 break;
3664 }
3665 case LTTNG_LIST_TRACKER_PIDS:
3666 {
3667 int32_t *pids = NULL;
3668 ssize_t nr_pids;
3669
3670 nr_pids = cmd_list_tracker_pids(cmd_ctx->session,
3671 cmd_ctx->lsm->domain.type, &pids);
3672 if (nr_pids < 0) {
3673 /* Return value is a negative lttng_error_code. */
3674 ret = -nr_pids;
3675 goto error;
3676 }
3677
3678 /*
3679 * Setup lttng message with payload size set to the event list size in
3680 * bytes and then copy list into the llm payload.
3681 */
3682 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, pids,
3683 sizeof(int32_t) * nr_pids);
3684 free(pids);
3685
3686 if (ret < 0) {
3687 goto setup_error;
3688 }
3689
3690 ret = LTTNG_OK;
3691 break;
3692 }
3693 case LTTNG_SET_CONSUMER_URI:
3694 {
3695 size_t nb_uri, len;
3696 struct lttng_uri *uris;
3697
3698 nb_uri = cmd_ctx->lsm->u.uri.size;
3699 len = nb_uri * sizeof(struct lttng_uri);
3700
3701 if (nb_uri == 0) {
3702 ret = LTTNG_ERR_INVALID;
3703 goto error;
3704 }
3705
3706 uris = zmalloc(len);
3707 if (uris == NULL) {
3708 ret = LTTNG_ERR_FATAL;
3709 goto error;
3710 }
3711
3712 /* Receive variable len data */
3713 DBG("Receiving %zu URI(s) from client ...", nb_uri);
3714 ret = lttcomm_recv_unix_sock(sock, uris, len);
3715 if (ret <= 0) {
3716 DBG("No URIs received from client... continuing");
3717 *sock_error = 1;
3718 ret = LTTNG_ERR_SESSION_FAIL;
3719 free(uris);
3720 goto error;
3721 }
3722
3723 ret = cmd_set_consumer_uri(cmd_ctx->session, nb_uri, uris);
3724 free(uris);
3725 if (ret != LTTNG_OK) {
3726 goto error;
3727 }
3728
3729
3730 break;
3731 }
3732 case LTTNG_START_TRACE:
3733 {
3734 ret = cmd_start_trace(cmd_ctx->session);
3735 break;
3736 }
3737 case LTTNG_STOP_TRACE:
3738 {
3739 ret = cmd_stop_trace(cmd_ctx->session);
3740 break;
3741 }
3742 case LTTNG_CREATE_SESSION:
3743 {
3744 size_t nb_uri, len;
3745 struct lttng_uri *uris = NULL;
3746
3747 nb_uri = cmd_ctx->lsm->u.uri.size;
3748 len = nb_uri * sizeof(struct lttng_uri);
3749
3750 if (nb_uri > 0) {
3751 uris = zmalloc(len);
3752 if (uris == NULL) {
3753 ret = LTTNG_ERR_FATAL;
3754 goto error;
3755 }
3756
3757 /* Receive variable len data */
3758 DBG("Waiting for %zu URIs from client ...", nb_uri);
3759 ret = lttcomm_recv_unix_sock(sock, uris, len);
3760 if (ret <= 0) {
3761 DBG("No URIs received from client... continuing");
3762 *sock_error = 1;
3763 ret = LTTNG_ERR_SESSION_FAIL;
3764 free(uris);
3765 goto error;
3766 }
3767
3768 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
3769 DBG("Creating session with ONE network URI is a bad call");
3770 ret = LTTNG_ERR_SESSION_FAIL;
3771 free(uris);
3772 goto error;
3773 }
3774 }
3775
3776 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris, nb_uri,
3777 &cmd_ctx->creds, 0);
3778
3779 free(uris);
3780
3781 break;
3782 }
3783 case LTTNG_DESTROY_SESSION:
3784 {
3785 ret = cmd_destroy_session(cmd_ctx->session, kernel_poll_pipe[1]);
3786
3787 /* Set session to NULL so we do not unlock it after free. */
3788 cmd_ctx->session = NULL;
3789 break;
3790 }
3791 case LTTNG_LIST_DOMAINS:
3792 {
3793 ssize_t nb_dom;
3794 struct lttng_domain *domains = NULL;
3795
3796 nb_dom = cmd_list_domains(cmd_ctx->session, &domains);
3797 if (nb_dom < 0) {
3798 /* Return value is a negative lttng_error_code. */
3799 ret = -nb_dom;
3800 goto error;
3801 }
3802
3803 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, domains,
3804 nb_dom * sizeof(struct lttng_domain));
3805 free(domains);
3806
3807 if (ret < 0) {
3808 goto setup_error;
3809 }
3810
3811 ret = LTTNG_OK;
3812 break;
3813 }
3814 case LTTNG_LIST_CHANNELS:
3815 {
3816 ssize_t payload_size;
3817 struct lttng_channel *channels = NULL;
3818
3819 payload_size = cmd_list_channels(cmd_ctx->lsm->domain.type,
3820 cmd_ctx->session, &channels);
3821 if (payload_size < 0) {
3822 /* Return value is a negative lttng_error_code. */
3823 ret = -payload_size;
3824 goto error;
3825 }
3826
3827 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, channels,
3828 payload_size);
3829 free(channels);
3830
3831 if (ret < 0) {
3832 goto setup_error;
3833 }
3834
3835 ret = LTTNG_OK;
3836 break;
3837 }
3838 case LTTNG_LIST_EVENTS:
3839 {
3840 ssize_t nb_event;
3841 struct lttng_event *events = NULL;
3842 struct lttcomm_event_command_header cmd_header;
3843 size_t total_size;
3844
3845 memset(&cmd_header, 0, sizeof(cmd_header));
3846 /* Extended infos are included at the end of events */
3847 nb_event = cmd_list_events(cmd_ctx->lsm->domain.type,
3848 cmd_ctx->session, cmd_ctx->lsm->u.list.channel_name,
3849 &events, &total_size);
3850
3851 if (nb_event < 0) {
3852 /* Return value is a negative lttng_error_code. */
3853 ret = -nb_event;
3854 goto error;
3855 }
3856
3857 cmd_header.nb_events = nb_event;
3858 ret = setup_lttng_msg(cmd_ctx, events, total_size,
3859 &cmd_header, sizeof(cmd_header));
3860 free(events);
3861
3862 if (ret < 0) {
3863 goto setup_error;
3864 }
3865
3866 ret = LTTNG_OK;
3867 break;
3868 }
3869 case LTTNG_LIST_SESSIONS:
3870 {
3871 unsigned int nr_sessions;
3872 void *sessions_payload;
3873 size_t payload_len;
3874
3875 session_lock_list();
3876 nr_sessions = lttng_sessions_count(
3877 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3878 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3879 payload_len = sizeof(struct lttng_session) * nr_sessions;
3880 sessions_payload = zmalloc(payload_len);
3881
3882 if (!sessions_payload) {
3883 session_unlock_list();
3884 ret = -ENOMEM;
3885 goto setup_error;
3886 }
3887
3888 cmd_list_lttng_sessions(sessions_payload,
3889 LTTNG_SOCK_GET_UID_CRED(&cmd_ctx->creds),
3890 LTTNG_SOCK_GET_GID_CRED(&cmd_ctx->creds));
3891 session_unlock_list();
3892
3893 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, sessions_payload,
3894 payload_len);
3895 free(sessions_payload);
3896
3897 if (ret < 0) {
3898 goto setup_error;
3899 }
3900
3901 ret = LTTNG_OK;
3902 break;
3903 }
3904 case LTTNG_REGISTER_CONSUMER:
3905 {
3906 struct consumer_data *cdata;
3907
3908 switch (cmd_ctx->lsm->domain.type) {
3909 case LTTNG_DOMAIN_KERNEL:
3910 cdata = &kconsumer_data;
3911 break;
3912 default:
3913 ret = LTTNG_ERR_UND;
3914 goto error;
3915 }
3916
3917 ret = cmd_register_consumer(cmd_ctx->session, cmd_ctx->lsm->domain.type,
3918 cmd_ctx->lsm->u.reg.path, cdata);
3919 break;
3920 }
3921 case LTTNG_DATA_PENDING:
3922 {
3923 int pending_ret;
3924 uint8_t pending_ret_byte;
3925
3926 pending_ret = cmd_data_pending(cmd_ctx->session);
3927
3928 /*
3929 * FIXME
3930 *
3931 * This function may returns 0 or 1 to indicate whether or not
3932 * there is data pending. In case of error, it should return an
3933 * LTTNG_ERR code. However, some code paths may still return
3934 * a nondescript error code, which we handle by returning an
3935 * "unknown" error.
3936 */
3937 if (pending_ret == 0 || pending_ret == 1) {
3938 /*
3939 * ret will be set to LTTNG_OK at the end of
3940 * this function.
3941 */
3942 } else if (pending_ret < 0) {
3943 ret = LTTNG_ERR_UNK;
3944 goto setup_error;
3945 } else {
3946 ret = pending_ret;
3947 goto setup_error;
3948 }
3949
3950 pending_ret_byte = (uint8_t) pending_ret;
3951
3952 /* 1 byte to return whether or not data is pending */
3953 ret = setup_lttng_msg_no_cmd_header(cmd_ctx,
3954 &pending_ret_byte, 1);
3955
3956 if (ret < 0) {
3957 goto setup_error;
3958 }
3959
3960 ret = LTTNG_OK;
3961 break;
3962 }
3963 case LTTNG_SNAPSHOT_ADD_OUTPUT:
3964 {
3965 struct lttcomm_lttng_output_id reply;
3966
3967 ret = cmd_snapshot_add_output(cmd_ctx->session,
3968 &cmd_ctx->lsm->u.snapshot_output.output, &reply.id);
3969 if (ret != LTTNG_OK) {
3970 goto error;
3971 }
3972
3973 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, &reply,
3974 sizeof(reply));
3975 if (ret < 0) {
3976 goto setup_error;
3977 }
3978
3979 /* Copy output list into message payload */
3980 ret = LTTNG_OK;
3981 break;
3982 }
3983 case LTTNG_SNAPSHOT_DEL_OUTPUT:
3984 {
3985 ret = cmd_snapshot_del_output(cmd_ctx->session,
3986 &cmd_ctx->lsm->u.snapshot_output.output);
3987 break;
3988 }
3989 case LTTNG_SNAPSHOT_LIST_OUTPUT:
3990 {
3991 ssize_t nb_output;
3992 struct lttng_snapshot_output *outputs = NULL;
3993
3994 nb_output = cmd_snapshot_list_outputs(cmd_ctx->session, &outputs);
3995 if (nb_output < 0) {
3996 ret = -nb_output;
3997 goto error;
3998 }
3999
4000 assert((nb_output > 0 && outputs) || nb_output == 0);
4001 ret = setup_lttng_msg_no_cmd_header(cmd_ctx, outputs,
4002 nb_output * sizeof(struct lttng_snapshot_output));
4003 free(outputs);
4004
4005 if (ret < 0) {
4006 goto setup_error;
4007 }
4008
4009 ret = LTTNG_OK;
4010 break;
4011 }
4012 case LTTNG_SNAPSHOT_RECORD:
4013 {
4014 ret = cmd_snapshot_record(cmd_ctx->session,
4015 &cmd_ctx->lsm->u.snapshot_record.output,
4016 cmd_ctx->lsm->u.snapshot_record.wait);
4017 break;
4018 }
4019 case LTTNG_CREATE_SESSION_SNAPSHOT:
4020 {
4021 size_t nb_uri, len;
4022 struct lttng_uri *uris = NULL;
4023
4024 nb_uri = cmd_ctx->lsm->u.uri.size;
4025 len = nb_uri * sizeof(struct lttng_uri);
4026
4027 if (nb_uri > 0) {
4028 uris = zmalloc(len);
4029 if (uris == NULL) {
4030 ret = LTTNG_ERR_FATAL;
4031 goto error;
4032 }
4033
4034 /* Receive variable len data */
4035 DBG("Waiting for %zu URIs from client ...", nb_uri);
4036 ret = lttcomm_recv_unix_sock(sock, uris, len);
4037 if (ret <= 0) {
4038 DBG("No URIs received from client... continuing");
4039 *sock_error = 1;
4040 ret = LTTNG_ERR_SESSION_FAIL;
4041 free(uris);
4042 goto error;
4043 }
4044
4045 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4046 DBG("Creating session with ONE network URI is a bad call");
4047 ret = LTTNG_ERR_SESSION_FAIL;
4048 free(uris);
4049 goto error;
4050 }
4051 }
4052
4053 ret = cmd_create_session_snapshot(cmd_ctx->lsm->session.name, uris,
4054 nb_uri, &cmd_ctx->creds);
4055 free(uris);
4056 break;
4057 }
4058 case LTTNG_CREATE_SESSION_LIVE:
4059 {
4060 size_t nb_uri, len;
4061 struct lttng_uri *uris = NULL;
4062
4063 nb_uri = cmd_ctx->lsm->u.uri.size;
4064 len = nb_uri * sizeof(struct lttng_uri);
4065
4066 if (nb_uri > 0) {
4067 uris = zmalloc(len);
4068 if (uris == NULL) {
4069 ret = LTTNG_ERR_FATAL;
4070 goto error;
4071 }
4072
4073 /* Receive variable len data */
4074 DBG("Waiting for %zu URIs from client ...", nb_uri);
4075 ret = lttcomm_recv_unix_sock(sock, uris, len);
4076 if (ret <= 0) {
4077 DBG("No URIs received from client... continuing");
4078 *sock_error = 1;
4079 ret = LTTNG_ERR_SESSION_FAIL;
4080 free(uris);
4081 goto error;
4082 }
4083
4084 if (nb_uri == 1 && uris[0].dtype != LTTNG_DST_PATH) {
4085 DBG("Creating session with ONE network URI is a bad call");
4086 ret = LTTNG_ERR_SESSION_FAIL;
4087 free(uris);
4088 goto error;
4089 }
4090 }
4091
4092 ret = cmd_create_session_uri(cmd_ctx->lsm->session.name, uris,
4093 nb_uri, &cmd_ctx->creds, cmd_ctx->lsm->u.session_live.timer_interval);
4094 free(uris);
4095 break;
4096 }
4097 case LTTNG_SAVE_SESSION:
4098 {
4099 ret = cmd_save_sessions(&cmd_ctx->lsm->u.save_session.attr,
4100 &cmd_ctx->creds);
4101 break;
4102 }
4103 case LTTNG_SET_SESSION_SHM_PATH:
4104 {
4105 ret = cmd_set_session_shm_path(cmd_ctx->session,
4106 cmd_ctx->lsm->u.set_shm_path.shm_path);
4107 break;
4108 }
4109 case LTTNG_REGENERATE_METADATA:
4110 {
4111 ret = cmd_regenerate_metadata(cmd_ctx->session);
4112 break;
4113 }
4114 case LTTNG_REGENERATE_STATEDUMP:
4115 {
4116 ret = cmd_regenerate_statedump(cmd_ctx->session);
4117 break;
4118 }
4119 default:
4120 ret = LTTNG_ERR_UND;
4121 break;
4122 }
4123
4124 error:
4125 if (cmd_ctx->llm == NULL) {
4126 DBG("Missing llm structure. Allocating one.");
4127 if (setup_lttng_msg_no_cmd_header(cmd_ctx, NULL, 0) < 0) {
4128 goto setup_error;
4129 }
4130 }
4131 /* Set return code */
4132 cmd_ctx->llm->ret_code = ret;
4133 setup_error:
4134 if (cmd_ctx->session) {
4135 session_unlock(cmd_ctx->session);
4136 }
4137 if (need_tracing_session) {
4138 session_unlock_list();
4139 }
4140 init_setup_error:
4141 assert(!rcu_read_ongoing());
4142 return ret;
4143 }
4144
4145 /*
4146 * Thread managing health check socket.
4147 */
4148 static void *thread_manage_health(void *data)
4149 {
4150 int sock = -1, new_sock = -1, ret, i, pollfd, err = -1;
4151 uint32_t revents, nb_fd;
4152 struct lttng_poll_event events;
4153 struct health_comm_msg msg;
4154 struct health_comm_reply reply;
4155
4156 DBG("[thread] Manage health check started");
4157
4158 rcu_register_thread();
4159
4160 /* We might hit an error path before this is created. */
4161 lttng_poll_init(&events);
4162
4163 /* Create unix socket */
4164 sock = lttcomm_create_unix_sock(health_unix_sock_path);
4165 if (sock < 0) {
4166 ERR("Unable to create health check Unix socket");
4167 goto error;
4168 }
4169
4170 if (is_root) {
4171 /* lttng health client socket path permissions */
4172 ret = chown(health_unix_sock_path, 0,
4173 utils_get_group_id(tracing_group_name));
4174 if (ret < 0) {
4175 ERR("Unable to set group on %s", health_unix_sock_path);
4176 PERROR("chown");
4177 goto error;
4178 }
4179
4180 ret = chmod(health_unix_sock_path,
4181 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
4182 if (ret < 0) {
4183 ERR("Unable to set permissions on %s", health_unix_sock_path);
4184 PERROR("chmod");
4185 goto error;
4186 }
4187 }
4188
4189 /*
4190 * Set the CLOEXEC flag. Return code is useless because either way, the
4191 * show must go on.
4192 */
4193 (void) utils_set_fd_cloexec(sock);
4194
4195 ret = lttcomm_listen_unix_sock(sock);
4196 if (ret < 0) {
4197 goto error;
4198 }
4199
4200 /*
4201 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4202 * more will be added to this poll set.
4203 */
4204 ret = sessiond_set_thread_pollset(&events, 2);
4205 if (ret < 0) {
4206 goto error;
4207 }
4208
4209 /* Add the application registration socket */
4210 ret = lttng_poll_add(&events, sock, LPOLLIN | LPOLLPRI);
4211 if (ret < 0) {
4212 goto error;
4213 }
4214
4215 sessiond_notify_ready();
4216
4217 while (1) {
4218 DBG("Health check ready");
4219
4220 /* Inifinite blocking call, waiting for transmission */
4221 restart:
4222 ret = lttng_poll_wait(&events, -1);
4223 if (ret < 0) {
4224 /*
4225 * Restart interrupted system call.
4226 */
4227 if (errno == EINTR) {
4228 goto restart;
4229 }
4230 goto error;
4231 }
4232
4233 nb_fd = ret;
4234
4235 for (i = 0; i < nb_fd; i++) {
4236 /* Fetch once the poll data */
4237 revents = LTTNG_POLL_GETEV(&events, i);
4238 pollfd = LTTNG_POLL_GETFD(&events, i);
4239
4240 if (!revents) {
4241 /* No activity for this FD (poll implementation). */
4242 continue;
4243 }
4244
4245 /* Thread quit pipe has been closed. Killing thread. */
4246 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4247 if (ret) {
4248 err = 0;
4249 goto exit;
4250 }
4251
4252 /* Event on the registration socket */
4253 if (pollfd == sock) {
4254 if (revents & LPOLLIN) {
4255 continue;
4256 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4257 ERR("Health socket poll error");
4258 goto error;
4259 } else {
4260 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4261 goto error;
4262 }
4263 }
4264 }
4265
4266 new_sock = lttcomm_accept_unix_sock(sock);
4267 if (new_sock < 0) {
4268 goto error;
4269 }
4270
4271 /*
4272 * Set the CLOEXEC flag. Return code is useless because either way, the
4273 * show must go on.
4274 */
4275 (void) utils_set_fd_cloexec(new_sock);
4276
4277 DBG("Receiving data from client for health...");
4278 ret = lttcomm_recv_unix_sock(new_sock, (void *)&msg, sizeof(msg));
4279 if (ret <= 0) {
4280 DBG("Nothing recv() from client... continuing");
4281 ret = close(new_sock);
4282 if (ret) {
4283 PERROR("close");
4284 }
4285 continue;
4286 }
4287
4288 rcu_thread_online();
4289
4290 memset(&reply, 0, sizeof(reply));
4291 for (i = 0; i < NR_HEALTH_SESSIOND_TYPES; i++) {
4292 /*
4293 * health_check_state returns 0 if health is
4294 * bad.
4295 */
4296 if (!health_check_state(health_sessiond, i)) {
4297 reply.ret_code |= 1ULL << i;
4298 }
4299 }
4300
4301 DBG2("Health check return value %" PRIx64, reply.ret_code);
4302
4303 ret = send_unix_sock(new_sock, (void *) &reply, sizeof(reply));
4304 if (ret < 0) {
4305 ERR("Failed to send health data back to client");
4306 }
4307
4308 /* End of transmission */
4309 ret = close(new_sock);
4310 if (ret) {
4311 PERROR("close");
4312 }
4313 }
4314
4315 exit:
4316 error:
4317 if (err) {
4318 ERR("Health error occurred in %s", __func__);
4319 }
4320 DBG("Health check thread dying");
4321 unlink(health_unix_sock_path);
4322 if (sock >= 0) {
4323 ret = close(sock);
4324 if (ret) {
4325 PERROR("close");
4326 }
4327 }
4328
4329 lttng_poll_clean(&events);
4330 stop_threads();
4331 rcu_unregister_thread();
4332 return NULL;
4333 }
4334
4335 /*
4336 * This thread manage all clients request using the unix client socket for
4337 * communication.
4338 */
4339 static void *thread_manage_clients(void *data)
4340 {
4341 int sock = -1, ret, i, pollfd, err = -1;
4342 int sock_error;
4343 uint32_t revents, nb_fd;
4344 struct command_ctx *cmd_ctx = NULL;
4345 struct lttng_poll_event events;
4346
4347 DBG("[thread] Manage client started");
4348
4349 rcu_register_thread();
4350
4351 health_register(health_sessiond, HEALTH_SESSIOND_TYPE_CMD);
4352
4353 health_code_update();
4354
4355 ret = lttcomm_listen_unix_sock(client_sock);
4356 if (ret < 0) {
4357 goto error_listen;
4358 }
4359
4360 /*
4361 * Pass 2 as size here for the thread quit pipe and client_sock. Nothing
4362 * more will be added to this poll set.
4363 */
4364 ret = sessiond_set_thread_pollset(&events, 2);
4365 if (ret < 0) {
4366 goto error_create_poll;
4367 }
4368
4369 /* Add the application registration socket */
4370 ret = lttng_poll_add(&events, client_sock, LPOLLIN | LPOLLPRI);
4371 if (ret < 0) {
4372 goto error;
4373 }
4374
4375 sessiond_notify_ready();
4376 ret = sem_post(&load_info->message_thread_ready);
4377 if (ret) {
4378 PERROR("sem_post message_thread_ready");
4379 goto error;
4380 }
4381
4382 /* This testpoint is after we signal readiness to the parent. */
4383 if (testpoint(sessiond_thread_manage_clients)) {
4384 goto error;
4385 }
4386
4387 if (testpoint(sessiond_thread_manage_clients_before_loop)) {
4388 goto error;
4389 }
4390
4391 health_code_update();
4392
4393 while (1) {
4394 DBG("Accepting client command ...");
4395
4396 /* Inifinite blocking call, waiting for transmission */
4397 restart:
4398 health_poll_entry();
4399 ret = lttng_poll_wait(&events, -1);
4400 health_poll_exit();
4401 if (ret < 0) {
4402 /*
4403 * Restart interrupted system call.
4404 */
4405 if (errno == EINTR) {
4406 goto restart;
4407 }
4408 goto error;
4409 }
4410
4411 nb_fd = ret;
4412
4413 for (i = 0; i < nb_fd; i++) {
4414 /* Fetch once the poll data */
4415 revents = LTTNG_POLL_GETEV(&events, i);
4416 pollfd = LTTNG_POLL_GETFD(&events, i);
4417
4418 health_code_update();
4419
4420 if (!revents) {
4421 /* No activity for this FD (poll implementation). */
4422 continue;
4423 }
4424
4425 /* Thread quit pipe has been closed. Killing thread. */
4426 ret = sessiond_check_thread_quit_pipe(pollfd, revents);
4427 if (ret) {
4428 err = 0;
4429 goto exit;
4430 }
4431
4432 /* Event on the registration socket */
4433 if (pollfd == client_sock) {
4434 if (revents & LPOLLIN) {
4435 continue;
4436 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
4437 ERR("Client socket poll error");
4438 goto error;
4439 } else {
4440 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
4441 goto error;
4442 }
4443 }
4444 }
4445
4446 DBG("Wait for client response");
4447
4448 health_code_update();
4449
4450 sock = lttcomm_accept_unix_sock(client_sock);
4451 if (sock < 0) {
4452 goto error;
4453 }
4454
4455 /*
4456 * Set the CLOEXEC flag. Return code is useless because either way, the
4457 * show must go on.
4458 */
4459 (void) utils_set_fd_cloexec(sock);
4460
4461 /* Set socket option for credentials retrieval */
4462 ret = lttcomm_setsockopt_creds_unix_sock(sock);
4463 if (ret < 0) {
4464 goto error;
4465 }
4466
4467 /* Allocate context command to process the client request */
4468 cmd_ctx = zmalloc(sizeof(struct command_ctx));
4469 if (cmd_ctx == NULL) {
4470 PERROR("zmalloc cmd_ctx");
4471 goto error;
4472 }
4473
4474 /* Allocate data buffer for reception */
4475 cmd_ctx->lsm = zmalloc(sizeof(struct lttcomm_session_msg));
4476 if (cmd_ctx->lsm == NULL) {
4477 PERROR("zmalloc cmd_ctx->lsm");
4478 goto error;
4479 }
4480
4481 cmd_ctx->llm = NULL;
4482 cmd_ctx->session = NULL;
4483
4484 health_code_update();
4485
4486 /*
4487 * Data is received from the lttng client. The struct
4488 * lttcomm_session_msg (lsm) contains the command and data request of
4489 * the client.
4490 */
4491 DBG("Receiving data from client ...");
4492 ret = lttcomm_recv_creds_unix_sock(sock, cmd_ctx->lsm,
4493 sizeof(struct lttcomm_session_msg), &cmd_ctx->creds);
4494 if (ret <= 0) {
4495 DBG("Nothing recv() from client... continuing");
4496 ret = close(sock);
4497 if (ret) {
4498 PERROR("close");
4499 }
4500 sock = -1;
4501 clean_command_ctx(&cmd_ctx);
4502 continue;
4503 }
4504
4505 health_code_update();
4506
4507 // TODO: Validate cmd_ctx including sanity check for
4508 // security purpose.
4509
4510 rcu_thread_online();
4511 /*
4512 * This function dispatch the work to the kernel or userspace tracer
4513 * libs and fill the lttcomm_lttng_msg data structure of all the needed
4514 * informations for the client. The command context struct contains
4515 * everything this function may needs.
4516 */
4517 ret = process_client_msg(cmd_ctx, sock, &sock_error);
4518 rcu_thread_offline();
4519 if (ret < 0) {
4520 ret = close(sock);
4521 if (ret) {
4522 PERROR("close");
4523 }
4524 sock = -1;
4525 /*
4526 * TODO: Inform client somehow of the fatal error. At
4527 * this point, ret < 0 means that a zmalloc failed
4528 * (ENOMEM). Error detected but still accept
4529 * command, unless a socket error has been
4530 * detected.
4531 */
4532 clean_command_ctx(&cmd_ctx);
4533 continue;
4534 }
4535
4536 health_code_update();
4537
4538 DBG("Sending response (size: %d, retcode: %s (%d))",
4539 cmd_ctx->lttng_msg_size,
4540 lttng_strerror(-cmd_ctx->llm->ret_code),
4541 cmd_ctx->llm->ret_code);
4542 ret = send_unix_sock(sock, cmd_ctx->llm, cmd_ctx->lttng_msg_size);
4543 if (ret < 0) {
4544 ERR("Failed to send data back to client");
4545 }
4546
4547 /* End of transmission */
4548 ret = close(sock);
4549 if (ret) {
4550 PERROR("close");
4551 }
4552 sock = -1;
4553
4554 clean_command_ctx(&cmd_ctx);
4555
4556 health_code_update();
4557 }
4558
4559 exit:
4560 error:
4561 if (sock >= 0) {
4562 ret = close(sock);
4563 if (ret) {
4564 PERROR("close");
4565 }
4566 }
4567
4568 lttng_poll_clean(&events);
4569 clean_command_ctx(&cmd_ctx);
4570
4571 error_listen:
4572 error_create_poll:
4573 unlink(client_unix_sock_path);
4574 if (client_sock >= 0) {
4575 ret = close(client_sock);
4576 if (ret) {
4577 PERROR("close");
4578 }
4579 }
4580
4581 if (err) {
4582 health_error();
4583 ERR("Health error occurred in %s", __func__);
4584 }
4585
4586 health_unregister(health_sessiond);
4587
4588 DBG("Client thread dying");
4589
4590 rcu_unregister_thread();
4591
4592 /*
4593 * Since we are creating the consumer threads, we own them, so we need
4594 * to join them before our thread exits.
4595 */
4596 ret = join_consumer_thread(&kconsumer_data);
4597 if (ret) {
4598 errno = ret;
4599 PERROR("join_consumer");
4600 }
4601
4602 ret = join_consumer_thread(&ustconsumer32_data);
4603 if (ret) {
4604 errno = ret;
4605 PERROR("join_consumer ust32");
4606 }
4607
4608 ret = join_consumer_thread(&ustconsumer64_data);
4609 if (ret) {
4610 errno = ret;
4611 PERROR("join_consumer ust64");
4612 }
4613 return NULL;
4614 }
4615
4616 static int string_match(const char *str1, const char *str2)
4617 {
4618 return (str1 && str2) && !strcmp(str1, str2);
4619 }
4620
4621 /*
4622 * Take an option from the getopt output and set it in the right variable to be
4623 * used later.
4624 *
4625 * Return 0 on success else a negative value.
4626 */
4627 static int set_option(int opt, const char *arg, const char *optname)
4628 {
4629 int ret = 0;
4630
4631 if (string_match(optname, "client-sock") || opt == 'c') {
4632 if (!arg || *arg == '\0') {
4633 ret = -EINVAL;
4634 goto end;
4635 }
4636 if (lttng_is_setuid_setgid()) {
4637 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4638 "-c, --client-sock");
4639 } else {
4640 snprintf(client_unix_sock_path, PATH_MAX, "%s", arg);
4641 }
4642 } else if (string_match(optname, "apps-sock") || opt == 'a') {
4643 if (!arg || *arg == '\0') {
4644 ret = -EINVAL;
4645 goto end;
4646 }
4647 if (lttng_is_setuid_setgid()) {
4648 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4649 "-a, --apps-sock");
4650 } else {
4651 snprintf(apps_unix_sock_path, PATH_MAX, "%s", arg);
4652 }
4653 } else if (string_match(optname, "daemonize") || opt == 'd') {
4654 opt_daemon = 1;
4655 } else if (string_match(optname, "background") || opt == 'b') {
4656 opt_background = 1;
4657 } else if (string_match(optname, "group") || opt == 'g') {
4658 if (!arg || *arg == '\0') {
4659 ret = -EINVAL;
4660 goto end;
4661 }
4662 if (lttng_is_setuid_setgid()) {
4663 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4664 "-g, --group");
4665 } else {
4666 /*
4667 * If the override option is set, the pointer points to a
4668 * *non* const thus freeing it even though the variable type is
4669 * set to const.
4670 */
4671 if (tracing_group_name_override) {
4672 free((void *) tracing_group_name);
4673 }
4674 tracing_group_name = strdup(arg);
4675 if (!tracing_group_name) {
4676 PERROR("strdup");
4677 ret = -ENOMEM;
4678 }
4679 tracing_group_name_override = 1;
4680 }
4681 } else if (string_match(optname, "help") || opt == 'h') {
4682 ret = utils_show_man_page(8, "lttng-sessiond");
4683 if (ret) {
4684 ERR("Cannot view man page lttng-sessiond(8)");
4685 perror("exec");
4686 }
4687 exit(ret ? EXIT_FAILURE : EXIT_SUCCESS);
4688 } else if (string_match(optname, "version") || opt == 'V') {
4689 fprintf(stdout, "%s\n", VERSION);
4690 exit(EXIT_SUCCESS);
4691 } else if (string_match(optname, "sig-parent") || opt == 'S') {
4692 opt_sig_parent = 1;
4693 } else if (string_match(optname, "kconsumerd-err-sock")) {
4694 if (!arg || *arg == '\0') {
4695 ret = -EINVAL;
4696 goto end;
4697 }
4698 if (lttng_is_setuid_setgid()) {
4699 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4700 "--kconsumerd-err-sock");
4701 } else {
4702 snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4703 }
4704 } else if (string_match(optname, "kconsumerd-cmd-sock")) {
4705 if (!arg || *arg == '\0') {
4706 ret = -EINVAL;
4707 goto end;
4708 }
4709 if (lttng_is_setuid_setgid()) {
4710 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4711 "--kconsumerd-cmd-sock");
4712 } else {
4713 snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4714 }
4715 } else if (string_match(optname, "ustconsumerd64-err-sock")) {
4716 if (!arg || *arg == '\0') {
4717 ret = -EINVAL;
4718 goto end;
4719 }
4720 if (lttng_is_setuid_setgid()) {
4721 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4722 "--ustconsumerd64-err-sock");
4723 } else {
4724 snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4725 }
4726 } else if (string_match(optname, "ustconsumerd64-cmd-sock")) {
4727 if (!arg || *arg == '\0') {
4728 ret = -EINVAL;
4729 goto end;
4730 }
4731 if (lttng_is_setuid_setgid()) {
4732 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4733 "--ustconsumerd64-cmd-sock");
4734 } else {
4735 snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4736 }
4737 } else if (string_match(optname, "ustconsumerd32-err-sock")) {
4738 if (!arg || *arg == '\0') {
4739 ret = -EINVAL;
4740 goto end;
4741 }
4742 if (lttng_is_setuid_setgid()) {
4743 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4744 "--ustconsumerd32-err-sock");
4745 } else {
4746 snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX, "%s", arg);
4747 }
4748 } else if (string_match(optname, "ustconsumerd32-cmd-sock")) {
4749 if (!arg || *arg == '\0') {
4750 ret = -EINVAL;
4751 goto end;
4752 }
4753 if (lttng_is_setuid_setgid()) {
4754 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4755 "--ustconsumerd32-cmd-sock");
4756 } else {
4757 snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX, "%s", arg);
4758 }
4759 } else if (string_match(optname, "no-kernel")) {
4760 opt_no_kernel = 1;
4761 } else if (string_match(optname, "quiet") || opt == 'q') {
4762 lttng_opt_quiet = 1;
4763 } else if (string_match(optname, "verbose") || opt == 'v') {
4764 /* Verbose level can increase using multiple -v */
4765 if (arg) {
4766 /* Value obtained from config file */
4767 lttng_opt_verbose = config_parse_value(arg);
4768 } else {
4769 /* -v used on command line */
4770 lttng_opt_verbose++;
4771 }
4772 /* Clamp value to [0, 3] */
4773 lttng_opt_verbose = lttng_opt_verbose < 0 ? 0 :
4774 (lttng_opt_verbose <= 3 ? lttng_opt_verbose : 3);
4775 } else if (string_match(optname, "verbose-consumer")) {
4776 if (arg) {
4777 opt_verbose_consumer = config_parse_value(arg);
4778 } else {
4779 opt_verbose_consumer++;
4780 }
4781 } else if (string_match(optname, "consumerd32-path")) {
4782 if (!arg || *arg == '\0') {
4783 ret = -EINVAL;
4784 goto end;
4785 }
4786 if (lttng_is_setuid_setgid()) {
4787 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4788 "--consumerd32-path");
4789 } else {
4790 if (consumerd32_bin_override) {
4791 free((void *) consumerd32_bin);
4792 }
4793 consumerd32_bin = strdup(arg);
4794 if (!consumerd32_bin) {
4795 PERROR("strdup");
4796 ret = -ENOMEM;
4797 }
4798 consumerd32_bin_override = 1;
4799 }
4800 } else if (string_match(optname, "consumerd32-libdir")) {
4801 if (!arg || *arg == '\0') {
4802 ret = -EINVAL;
4803 goto end;
4804 }
4805 if (lttng_is_setuid_setgid()) {
4806 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4807 "--consumerd32-libdir");
4808 } else {
4809 if (consumerd32_libdir_override) {
4810 free((void *) consumerd32_libdir);
4811 }
4812 consumerd32_libdir = strdup(arg);
4813 if (!consumerd32_libdir) {
4814 PERROR("strdup");
4815 ret = -ENOMEM;
4816 }
4817 consumerd32_libdir_override = 1;
4818 }
4819 } else if (string_match(optname, "consumerd64-path")) {
4820 if (!arg || *arg == '\0') {
4821 ret = -EINVAL;
4822 goto end;
4823 }
4824 if (lttng_is_setuid_setgid()) {
4825 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4826 "--consumerd64-path");
4827 } else {
4828 if (consumerd64_bin_override) {
4829 free((void *) consumerd64_bin);
4830 }
4831 consumerd64_bin = strdup(arg);
4832 if (!consumerd64_bin) {
4833 PERROR("strdup");
4834 ret = -ENOMEM;
4835 }
4836 consumerd64_bin_override = 1;
4837 }
4838 } else if (string_match(optname, "consumerd64-libdir")) {
4839 if (!arg || *arg == '\0') {
4840 ret = -EINVAL;
4841 goto end;
4842 }
4843 if (lttng_is_setuid_setgid()) {
4844 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4845 "--consumerd64-libdir");
4846 } else {
4847 if (consumerd64_libdir_override) {
4848 free((void *) consumerd64_libdir);
4849 }
4850 consumerd64_libdir = strdup(arg);
4851 if (!consumerd64_libdir) {
4852 PERROR("strdup");
4853 ret = -ENOMEM;
4854 }
4855 consumerd64_libdir_override = 1;
4856 }
4857 } else if (string_match(optname, "pidfile") || opt == 'p') {
4858 if (!arg || *arg == '\0') {
4859 ret = -EINVAL;
4860 goto end;
4861 }
4862 if (lttng_is_setuid_setgid()) {
4863 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4864 "-p, --pidfile");
4865 } else {
4866 free(opt_pidfile);
4867 opt_pidfile = strdup(arg);
4868 if (!opt_pidfile) {
4869 PERROR("strdup");
4870 ret = -ENOMEM;
4871 }
4872 }
4873 } else if (string_match(optname, "agent-tcp-port")) {
4874 if (!arg || *arg == '\0') {
4875 ret = -EINVAL;
4876 goto end;
4877 }
4878 if (lttng_is_setuid_setgid()) {
4879 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4880 "--agent-tcp-port");
4881 } else {
4882 unsigned long v;
4883
4884 errno = 0;
4885 v = strtoul(arg, NULL, 0);
4886 if (errno != 0 || !isdigit(arg[0])) {
4887 ERR("Wrong value in --agent-tcp-port parameter: %s", arg);
4888 return -1;
4889 }
4890 if (v == 0 || v >= 65535) {
4891 ERR("Port overflow in --agent-tcp-port parameter: %s", arg);
4892 return -1;
4893 }
4894 agent_tcp_port = (uint32_t) v;
4895 DBG3("Agent TCP port set to non default: %u", agent_tcp_port);
4896 }
4897 } else if (string_match(optname, "load") || opt == 'l') {
4898 if (!arg || *arg == '\0') {
4899 ret = -EINVAL;
4900 goto end;
4901 }
4902 if (lttng_is_setuid_setgid()) {
4903 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4904 "-l, --load");
4905 } else {
4906 free(opt_load_session_path);
4907 opt_load_session_path = strdup(arg);
4908 if (!opt_load_session_path) {
4909 PERROR("strdup");
4910 ret = -ENOMEM;
4911 }
4912 }
4913 } else if (string_match(optname, "kmod-probes")) {
4914 if (!arg || *arg == '\0') {
4915 ret = -EINVAL;
4916 goto end;
4917 }
4918 if (lttng_is_setuid_setgid()) {
4919 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4920 "--kmod-probes");
4921 } else {
4922 free(kmod_probes_list);
4923 kmod_probes_list = strdup(arg);
4924 if (!kmod_probes_list) {
4925 PERROR("strdup");
4926 ret = -ENOMEM;
4927 }
4928 }
4929 } else if (string_match(optname, "extra-kmod-probes")) {
4930 if (!arg || *arg == '\0') {
4931 ret = -EINVAL;
4932 goto end;
4933 }
4934 if (lttng_is_setuid_setgid()) {
4935 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
4936 "--extra-kmod-probes");
4937 } else {
4938 free(kmod_extra_probes_list);
4939 kmod_extra_probes_list = strdup(arg);
4940 if (!kmod_extra_probes_list) {
4941 PERROR("strdup");
4942 ret = -ENOMEM;
4943 }
4944 }
4945 } else if (string_match(optname, "config") || opt == 'f') {
4946 /* This is handled in set_options() thus silent skip. */
4947 goto end;
4948 } else {
4949 /* Unknown option or other error.
4950 * Error is printed by getopt, just return */
4951 ret = -1;
4952 }
4953
4954 end:
4955 if (ret == -EINVAL) {
4956 const char *opt_name = "unknown";
4957 int i;
4958
4959 for (i = 0; i < sizeof(long_options) / sizeof(struct option);
4960 i++) {
4961 if (opt == long_options[i].val) {
4962 opt_name = long_options[i].name;
4963 break;
4964 }
4965 }
4966
4967 WARN("Invalid argument provided for option \"%s\", using default value.",
4968 opt_name);
4969 }
4970
4971 return ret;
4972 }
4973
4974 /*
4975 * config_entry_handler_cb used to handle options read from a config file.
4976 * See config_entry_handler_cb comment in common/config/session-config.h for the
4977 * return value conventions.
4978 */
4979 static int config_entry_handler(const struct config_entry *entry, void *unused)
4980 {
4981 int ret = 0, i;
4982
4983 if (!entry || !entry->name || !entry->value) {
4984 ret = -EINVAL;
4985 goto end;
4986 }
4987
4988 /* Check if the option is to be ignored */
4989 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
4990 if (!strcmp(entry->name, config_ignore_options[i])) {
4991 goto end;
4992 }
4993 }
4994
4995 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1;
4996 i++) {
4997
4998 /* Ignore if not fully matched. */
4999 if (strcmp(entry->name, long_options[i].name)) {
5000 continue;
5001 }
5002
5003 /*
5004 * If the option takes no argument on the command line, we have to
5005 * check if the value is "true". We support non-zero numeric values,
5006 * true, on and yes.
5007 */
5008 if (!long_options[i].has_arg) {
5009 ret = config_parse_value(entry->value);
5010 if (ret <= 0) {
5011 if (ret) {
5012 WARN("Invalid configuration value \"%s\" for option %s",
5013 entry->value, entry->name);
5014 }
5015 /* False, skip boolean config option. */
5016 goto end;
5017 }
5018 }
5019
5020 ret = set_option(long_options[i].val, entry->value, entry->name);
5021 goto end;
5022 }
5023
5024 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry->name);
5025
5026 end:
5027 return ret;
5028 }
5029
5030 /*
5031 * daemon configuration loading and argument parsing
5032 */
5033 static int set_options(int argc, char **argv)
5034 {
5035 int ret = 0, c = 0, option_index = 0;
5036 int orig_optopt = optopt, orig_optind = optind;
5037 char *optstring;
5038 const char *config_path = NULL;
5039
5040 optstring = utils_generate_optstring(long_options,
5041 sizeof(long_options) / sizeof(struct option));
5042 if (!optstring) {
5043 ret = -ENOMEM;
5044 goto end;
5045 }
5046
5047 /* Check for the --config option */
5048 while ((c = getopt_long(argc, argv, optstring, long_options,
5049 &option_index)) != -1) {
5050 if (c == '?') {
5051 ret = -EINVAL;
5052 goto end;
5053 } else if (c != 'f') {
5054 /* if not equal to --config option. */
5055 continue;
5056 }
5057
5058 if (lttng_is_setuid_setgid()) {
5059 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
5060 "-f, --config");
5061 } else {
5062 config_path = utils_expand_path(optarg);
5063 if (!config_path) {
5064 ERR("Failed to resolve path: %s", optarg);
5065 }
5066 }
5067 }
5068
5069 ret = config_get_section_entries(config_path, config_section_name,
5070 config_entry_handler, NULL);
5071 if (ret) {
5072 if (ret > 0) {
5073 ERR("Invalid configuration option at line %i", ret);
5074 ret = -1;
5075 }
5076 goto end;
5077 }
5078
5079 /* Reset getopt's global state */
5080 optopt = orig_optopt;
5081 optind = orig_optind;
5082 while (1) {
5083 option_index = -1;
5084 /*
5085 * getopt_long() will not set option_index if it encounters a
5086 * short option.
5087 */
5088 c = getopt_long(argc, argv, optstring, long_options,
5089 &option_index);
5090 if (c == -1) {
5091 break;
5092 }
5093
5094 /*
5095 * Pass NULL as the long option name if popt left the index
5096 * unset.
5097 */
5098 ret = set_option(c, optarg,
5099 option_index < 0 ? NULL :
5100 long_options[option_index].name);
5101 if (ret < 0) {
5102 break;
5103 }
5104 }
5105
5106 end:
5107 free(optstring);
5108 return ret;
5109 }
5110
5111 /*
5112 * Creates the two needed socket by the daemon.
5113 * apps_sock - The communication socket for all UST apps.
5114 * client_sock - The communication of the cli tool (lttng).
5115 */
5116 static int init_daemon_socket(void)
5117 {
5118 int ret = 0;
5119 mode_t old_umask;
5120
5121 old_umask = umask(0);
5122
5123 /* Create client tool unix socket */
5124 client_sock = lttcomm_create_unix_sock(client_unix_sock_path);
5125 if (client_sock < 0) {
5126 ERR("Create unix sock failed: %s", client_unix_sock_path);
5127 ret = -1;
5128 goto end;
5129 }
5130
5131 /* Set the cloexec flag */
5132 ret = utils_set_fd_cloexec(client_sock);
5133 if (ret < 0) {
5134 ERR("Unable to set CLOEXEC flag to the client Unix socket (fd: %d). "
5135 "Continuing but note that the consumer daemon will have a "
5136 "reference to this socket on exec()", client_sock);
5137 }
5138
5139 /* File permission MUST be 660 */
5140 ret = chmod(client_unix_sock_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5141 if (ret < 0) {
5142 ERR("Set file permissions failed: %s", client_unix_sock_path);
5143 PERROR("chmod");
5144 goto end;
5145 }
5146
5147 /* Create the application unix socket */
5148 apps_sock = lttcomm_create_unix_sock(apps_unix_sock_path);
5149 if (apps_sock < 0) {
5150 ERR("Create unix sock failed: %s", apps_unix_sock_path);
5151 ret = -1;
5152 goto end;
5153 }
5154
5155 /* Set the cloexec flag */
5156 ret = utils_set_fd_cloexec(apps_sock);
5157 if (ret < 0) {
5158 ERR("Unable to set CLOEXEC flag to the app Unix socket (fd: %d). "
5159 "Continuing but note that the consumer daemon will have a "
5160 "reference to this socket on exec()", apps_sock);
5161 }
5162
5163 /* File permission MUST be 666 */
5164 ret = chmod(apps_unix_sock_path,
5165 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
5166 if (ret < 0) {
5167 ERR("Set file permissions failed: %s", apps_unix_sock_path);
5168 PERROR("chmod");
5169 goto end;
5170 }
5171
5172 DBG3("Session daemon client socket %d and application socket %d created",
5173 client_sock, apps_sock);
5174
5175 end:
5176 umask(old_umask);
5177 return ret;
5178 }
5179
5180 /*
5181 * Check if the global socket is available, and if a daemon is answering at the
5182 * other side. If yes, error is returned.
5183 */
5184 static int check_existing_daemon(void)
5185 {
5186 /* Is there anybody out there ? */
5187 if (lttng_session_daemon_alive()) {
5188 return -EEXIST;
5189 }
5190
5191 return 0;
5192 }
5193
5194 /*
5195 * Set the tracing group gid onto the client socket.
5196 *
5197 * Race window between mkdir and chown is OK because we are going from more
5198 * permissive (root.root) to less permissive (root.tracing).
5199 */
5200 static int set_permissions(char *rundir)
5201 {
5202 int ret;
5203 gid_t gid;
5204
5205 gid = utils_get_group_id(tracing_group_name);
5206
5207 /* Set lttng run dir */
5208 ret = chown(rundir, 0, gid);
5209 if (ret < 0) {
5210 ERR("Unable to set group on %s", rundir);
5211 PERROR("chown");
5212 }
5213
5214 /*
5215 * Ensure all applications and tracing group can search the run
5216 * dir. Allow everyone to read the directory, since it does not
5217 * buy us anything to hide its content.
5218 */
5219 ret = chmod(rundir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
5220 if (ret < 0) {
5221 ERR("Unable to set permissions on %s", rundir);
5222 PERROR("chmod");
5223 }
5224
5225 /* lttng client socket path */
5226 ret = chown(client_unix_sock_path, 0, gid);
5227 if (ret < 0) {
5228 ERR("Unable to set group on %s", client_unix_sock_path);
5229 PERROR("chown");
5230 }
5231
5232 /* kconsumer error socket path */
5233 ret = chown(kconsumer_data.err_unix_sock_path, 0, 0);
5234 if (ret < 0) {
5235 ERR("Unable to set group on %s", kconsumer_data.err_unix_sock_path);
5236 PERROR("chown");
5237 }
5238
5239 /* 64-bit ustconsumer error socket path */
5240 ret = chown(ustconsumer64_data.err_unix_sock_path, 0, 0);
5241 if (ret < 0) {
5242 ERR("Unable to set group on %s", ustconsumer64_data.err_unix_sock_path);
5243 PERROR("chown");
5244 }
5245
5246 /* 32-bit ustconsumer compat32 error socket path */
5247 ret = chown(ustconsumer32_data.err_unix_sock_path, 0, 0);
5248 if (ret < 0) {
5249 ERR("Unable to set group on %s", ustconsumer32_data.err_unix_sock_path);
5250 PERROR("chown");
5251 }
5252
5253 DBG("All permissions are set");
5254
5255 return ret;
5256 }
5257
5258 /*
5259 * Create the lttng run directory needed for all global sockets and pipe.
5260 */
5261 static int create_lttng_rundir(const char *rundir)
5262 {
5263 int ret;
5264
5265 DBG3("Creating LTTng run directory: %s", rundir);
5266
5267 ret = mkdir(rundir, S_IRWXU);
5268 if (ret < 0) {
5269 if (errno != EEXIST) {
5270 ERR("Unable to create %s", rundir);
5271 goto error;
5272 } else {
5273 ret = 0;
5274 }
5275 }
5276
5277 error:
5278 return ret;
5279 }
5280
5281 /*
5282 * Setup sockets and directory needed by the kconsumerd communication with the
5283 * session daemon.
5284 */
5285 static int set_consumer_sockets(struct consumer_data *consumer_data,
5286 const char *rundir)
5287 {
5288 int ret;
5289 char path[PATH_MAX];
5290
5291 switch (consumer_data->type) {
5292 case LTTNG_CONSUMER_KERNEL:
5293 snprintf(path, PATH_MAX, DEFAULT_KCONSUMERD_PATH, rundir);
5294 break;
5295 case LTTNG_CONSUMER64_UST:
5296 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD64_PATH, rundir);
5297 break;
5298 case LTTNG_CONSUMER32_UST:
5299 snprintf(path, PATH_MAX, DEFAULT_USTCONSUMERD32_PATH, rundir);
5300 break;
5301 default:
5302 ERR("Consumer type unknown");
5303 ret = -EINVAL;
5304 goto error;
5305 }
5306
5307 DBG2("Creating consumer directory: %s", path);
5308
5309 ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP);
5310 if (ret < 0) {
5311 if (errno != EEXIST) {
5312 PERROR("mkdir");
5313 ERR("Failed to create %s", path);
5314 goto error;
5315 }
5316 ret = -1;
5317 }
5318 if (is_root) {
5319 ret = chown(path, 0, utils_get_group_id(tracing_group_name));
5320 if (ret < 0) {
5321 ERR("Unable to set group on %s", path);
5322 PERROR("chown");
5323 goto error;
5324 }
5325 }
5326
5327 /* Create the kconsumerd error unix socket */
5328 consumer_data->err_sock =
5329 lttcomm_create_unix_sock(consumer_data->err_unix_sock_path);
5330 if (consumer_data->err_sock < 0) {
5331 ERR("Create unix sock failed: %s", consumer_data->err_unix_sock_path);
5332 ret = -1;
5333 goto error;
5334 }
5335
5336 /*
5337 * Set the CLOEXEC flag. Return code is useless because either way, the
5338 * show must go on.
5339 */
5340 ret = utils_set_fd_cloexec(consumer_data->err_sock);
5341 if (ret < 0) {
5342 PERROR("utils_set_fd_cloexec");
5343 /* continue anyway */
5344 }
5345
5346 /* File permission MUST be 660 */
5347 ret = chmod(consumer_data->err_unix_sock_path,
5348 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
5349 if (ret < 0) {
5350 ERR("Set file permissions failed: %s", consumer_data->err_unix_sock_path);
5351 PERROR("chmod");
5352 goto error;
5353 }
5354
5355 error:
5356 return ret;
5357 }
5358
5359 /*
5360 * Signal handler for the daemon
5361 *
5362 * Simply stop all worker threads, leaving main() return gracefully after
5363 * joining all threads and calling cleanup().
5364 */
5365 static void sighandler(int sig)
5366 {
5367 switch (sig) {
5368 case SIGINT:
5369 DBG("SIGINT caught");
5370 stop_threads();
5371 break;
5372 case SIGTERM:
5373 DBG("SIGTERM caught");
5374 stop_threads();
5375 break;
5376 case SIGUSR1:
5377 CMM_STORE_SHARED(recv_child_signal, 1);
5378 break;
5379 default:
5380 break;
5381 }
5382 }
5383
5384 /*
5385 * Setup signal handler for :
5386 * SIGINT, SIGTERM, SIGPIPE
5387 */
5388 static int set_signal_handler(void)
5389 {
5390 int ret = 0;
5391 struct sigaction sa;
5392 sigset_t sigset;
5393
5394 if ((ret = sigemptyset(&sigset)) < 0) {
5395 PERROR("sigemptyset");
5396 return ret;
5397 }
5398
5399 sa.sa_mask = sigset;
5400 sa.sa_flags = 0;
5401
5402 sa.sa_handler = sighandler;
5403 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
5404 PERROR("sigaction");
5405 return ret;
5406 }
5407
5408 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
5409 PERROR("sigaction");
5410 return ret;
5411 }
5412
5413 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
5414 PERROR("sigaction");
5415 return ret;
5416 }
5417
5418 sa.sa_handler = SIG_IGN;
5419 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
5420 PERROR("sigaction");
5421 return ret;
5422 }
5423
5424 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
5425
5426 return ret;
5427 }
5428
5429 /*
5430 * Set open files limit to unlimited. This daemon can open a large number of
5431 * file descriptors in order to consume multiple kernel traces.
5432 */
5433 static void set_ulimit(void)
5434 {
5435 int ret;
5436 struct rlimit lim;
5437
5438 /* The kernel does not allow an infinite limit for open files */
5439 lim.rlim_cur = 65535;
5440 lim.rlim_max = 65535;
5441
5442 ret = setrlimit(RLIMIT_NOFILE, &lim);
5443 if (ret < 0) {
5444 PERROR("failed to set open files limit");
5445 }
5446 }
5447
5448 /*
5449 * Write pidfile using the rundir and opt_pidfile.
5450 */
5451 static int write_pidfile(void)
5452 {
5453 int ret;
5454 char pidfile_path[PATH_MAX];
5455
5456 assert(rundir);
5457
5458 if (opt_pidfile) {
5459 if (lttng_strncpy(pidfile_path, opt_pidfile, sizeof(pidfile_path))) {
5460 ret = -1;
5461 goto error;
5462 }
5463 } else {
5464 /* Build pidfile path from rundir and opt_pidfile. */
5465 ret = snprintf(pidfile_path, sizeof(pidfile_path), "%s/"
5466 DEFAULT_LTTNG_SESSIOND_PIDFILE, rundir);
5467 if (ret < 0) {
5468 PERROR("snprintf pidfile path");
5469 goto error;
5470 }
5471 }
5472
5473 /*
5474 * Create pid file in rundir.
5475 */
5476 ret = utils_create_pid_file(getpid(), pidfile_path);
5477 error:
5478 return ret;
5479 }
5480
5481 /*
5482 * Create lockfile using the rundir and return its fd.
5483 */
5484 static int create_lockfile(void)
5485 {
5486 int ret;
5487 char lockfile_path[PATH_MAX];
5488
5489 ret = generate_lock_file_path(lockfile_path, sizeof(lockfile_path));
5490 if (ret < 0) {
5491 goto error;
5492 }
5493
5494 ret = utils_create_lock_file(lockfile_path);
5495 error:
5496 return ret;
5497 }
5498
5499 /*
5500 * Write agent TCP port using the rundir.
5501 */
5502 static int write_agent_port(void)
5503 {
5504 int ret;
5505 char path[PATH_MAX];
5506
5507 assert(rundir);
5508
5509 ret = snprintf(path, sizeof(path), "%s/"
5510 DEFAULT_LTTNG_SESSIOND_AGENTPORT_FILE, rundir);
5511 if (ret < 0) {
5512 PERROR("snprintf agent port path");
5513 goto error;
5514 }
5515
5516 /*
5517 * Create TCP agent port file in rundir.
5518 */
5519 ret = utils_create_pid_file(agent_tcp_port, path);
5520
5521 error:
5522 return ret;
5523 }
5524
5525 /*
5526 * main
5527 */
5528 int main(int argc, char **argv)
5529 {
5530 int ret = 0, retval = 0;
5531 void *status;
5532 const char *home_path, *env_app_timeout;
5533
5534 init_kernel_workarounds();
5535
5536 rcu_register_thread();
5537
5538 if (set_signal_handler()) {
5539 retval = -1;
5540 goto exit_set_signal_handler;
5541 }
5542
5543 setup_consumerd_path();
5544
5545 page_size = sysconf(_SC_PAGESIZE);
5546 if (page_size < 0) {
5547 PERROR("sysconf _SC_PAGESIZE");
5548 page_size = LONG_MAX;
5549 WARN("Fallback page size to %ld", page_size);
5550 }
5551
5552 /*
5553 * Parse arguments and load the daemon configuration file.
5554 *
5555 * We have an exit_options exit path to free memory reserved by
5556 * set_options. This is needed because the rest of sessiond_cleanup()
5557 * depends on ht_cleanup_thread, which depends on lttng_daemonize, which
5558 * depends on set_options.
5559 */
5560 progname = argv[0];
5561 if (set_options(argc, argv)) {
5562 retval = -1;
5563 goto exit_options;
5564 }
5565
5566 /* Daemonize */
5567 if (opt_daemon || opt_background) {
5568 int i;
5569
5570 ret = lttng_daemonize(&child_ppid, &recv_child_signal,
5571 !opt_background);
5572 if (ret < 0) {
5573 retval = -1;
5574 goto exit_options;
5575 }
5576
5577 /*
5578 * We are in the child. Make sure all other file descriptors are
5579 * closed, in case we are called with more opened file
5580 * descriptors than the standard ones.
5581 */
5582 for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
5583 (void) close(i);
5584 }
5585 }
5586
5587 if (run_as_create_worker(argv[0]) < 0) {
5588 goto exit_create_run_as_worker_cleanup;
5589 }
5590
5591 /*
5592 * Starting from here, we can create threads. This needs to be after
5593 * lttng_daemonize due to RCU.
5594 */
5595
5596 /*
5597 * Initialize the health check subsystem. This call should set the
5598 * appropriate time values.
5599 */
5600 health_sessiond = health_app_create(NR_HEALTH_SESSIOND_TYPES);
5601 if (!health_sessiond) {
5602 PERROR("health_app_create error");
5603 retval = -1;
5604 goto exit_health_sessiond_cleanup;
5605 }
5606
5607 /* Create thread to clean up RCU hash tables */
5608 if (init_ht_cleanup_thread(&ht_cleanup_thread)) {
5609 retval = -1;
5610 goto exit_ht_cleanup;
5611 }
5612
5613 /* Create thread quit pipe */
5614 if (init_thread_quit_pipe()) {
5615 retval = -1;
5616 goto exit_init_data;
5617 }
5618
5619 /* Check if daemon is UID = 0 */
5620 is_root = !getuid();
5621
5622 if (is_root) {
5623 rundir = strdup(DEFAULT_LTTNG_RUNDIR);
5624 if (!rundir) {
5625 retval = -1;
5626 goto exit_init_data;
5627 }
5628
5629 /* Create global run dir with root access */
5630 if (create_lttng_rundir(rundir)) {
5631 retval = -1;
5632 goto exit_init_data;
5633 }
5634
5635 if (strlen(apps_unix_sock_path) == 0) {
5636 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5637 DEFAULT_GLOBAL_APPS_UNIX_SOCK);
5638 if (ret < 0) {
5639 retval = -1;
5640 goto exit_init_data;
5641 }
5642 }
5643
5644 if (strlen(client_unix_sock_path) == 0) {
5645 ret = snprintf(client_unix_sock_path, PATH_MAX,
5646 DEFAULT_GLOBAL_CLIENT_UNIX_SOCK);
5647 if (ret < 0) {
5648 retval = -1;
5649 goto exit_init_data;
5650 }
5651 }
5652
5653 /* Set global SHM for ust */
5654 if (strlen(wait_shm_path) == 0) {
5655 ret = snprintf(wait_shm_path, PATH_MAX,
5656 DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH);
5657 if (ret < 0) {
5658 retval = -1;
5659 goto exit_init_data;
5660 }
5661 }
5662
5663 if (strlen(health_unix_sock_path) == 0) {
5664 ret = snprintf(health_unix_sock_path,
5665 sizeof(health_unix_sock_path),
5666 DEFAULT_GLOBAL_HEALTH_UNIX_SOCK);
5667 if (ret < 0) {
5668 retval = -1;
5669 goto exit_init_data;
5670 }
5671 }
5672
5673 /* Setup kernel consumerd path */
5674 ret = snprintf(kconsumer_data.err_unix_sock_path, PATH_MAX,
5675 DEFAULT_KCONSUMERD_ERR_SOCK_PATH, rundir);
5676 if (ret < 0) {
5677 retval = -1;
5678 goto exit_init_data;
5679 }
5680 ret = snprintf(kconsumer_data.cmd_unix_sock_path, PATH_MAX,
5681 DEFAULT_KCONSUMERD_CMD_SOCK_PATH, rundir);
5682 if (ret < 0) {
5683 retval = -1;
5684 goto exit_init_data;
5685 }
5686
5687 DBG2("Kernel consumer err path: %s",
5688 kconsumer_data.err_unix_sock_path);
5689 DBG2("Kernel consumer cmd path: %s",
5690 kconsumer_data.cmd_unix_sock_path);
5691 } else {
5692 home_path = utils_get_home_dir();
5693 if (home_path == NULL) {
5694 /* TODO: Add --socket PATH option */
5695 ERR("Can't get HOME directory for sockets creation.");
5696 retval = -1;
5697 goto exit_init_data;
5698 }
5699
5700 /*
5701 * Create rundir from home path. This will create something like
5702 * $HOME/.lttng
5703 */
5704 ret = asprintf(&rundir, DEFAULT_LTTNG_HOME_RUNDIR, home_path);
5705 if (ret < 0) {
5706 retval = -1;
5707 goto exit_init_data;
5708 }
5709
5710 if (create_lttng_rundir(rundir)) {
5711 retval = -1;
5712 goto exit_init_data;
5713 }
5714
5715 if (strlen(apps_unix_sock_path) == 0) {
5716 ret = snprintf(apps_unix_sock_path, PATH_MAX,
5717 DEFAULT_HOME_APPS_UNIX_SOCK,
5718 home_path);
5719 if (ret < 0) {
5720 retval = -1;
5721 goto exit_init_data;
5722 }
5723 }
5724
5725 /* Set the cli tool unix socket path */
5726 if (strlen(client_unix_sock_path) == 0) {
5727 ret = snprintf(client_unix_sock_path, PATH_MAX,
5728 DEFAULT_HOME_CLIENT_UNIX_SOCK,
5729 home_path);
5730 if (ret < 0) {
5731 retval = -1;
5732 goto exit_init_data;
5733 }
5734 }
5735
5736 /* Set global SHM for ust */
5737 if (strlen(wait_shm_path) == 0) {
5738 ret = snprintf(wait_shm_path, PATH_MAX,
5739 DEFAULT_HOME_APPS_WAIT_SHM_PATH,
5740 getuid());
5741 if (ret < 0) {
5742 retval = -1;
5743 goto exit_init_data;
5744 }
5745 }
5746
5747 /* Set health check Unix path */
5748 if (strlen(health_unix_sock_path) == 0) {
5749 ret = snprintf(health_unix_sock_path,
5750 sizeof(health_unix_sock_path),
5751 DEFAULT_HOME_HEALTH_UNIX_SOCK,
5752 home_path);
5753 if (ret < 0) {
5754 retval = -1;
5755 goto exit_init_data;
5756 }
5757 }
5758 }
5759
5760 lockfile_fd = create_lockfile();
5761 if (lockfile_fd < 0) {
5762 retval = -1;
5763 goto exit_init_data;
5764 }
5765
5766 /* Set consumer initial state */
5767 kernel_consumerd_state = CONSUMER_STOPPED;
5768 ust_consumerd_state = CONSUMER_STOPPED;
5769
5770 DBG("Client socket path %s", client_unix_sock_path);
5771 DBG("Application socket path %s", apps_unix_sock_path);
5772 DBG("Application wait path %s", wait_shm_path);
5773 DBG("LTTng run directory path: %s", rundir);
5774
5775 /* 32 bits consumerd path setup */
5776 ret = snprintf(ustconsumer32_data.err_unix_sock_path, PATH_MAX,
5777 DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH, rundir);
5778 if (ret < 0) {
5779 PERROR("snprintf 32-bit consumer error socket path");
5780 retval = -1;
5781 goto exit_init_data;
5782 }
5783 ret = snprintf(ustconsumer32_data.cmd_unix_sock_path, PATH_MAX,
5784 DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH, rundir);
5785 if (ret < 0) {
5786 PERROR("snprintf 32-bit consumer command socket path");
5787 retval = -1;
5788 goto exit_init_data;
5789 }
5790
5791 DBG2("UST consumer 32 bits err path: %s",
5792 ustconsumer32_data.err_unix_sock_path);
5793 DBG2("UST consumer 32 bits cmd path: %s",
5794 ustconsumer32_data.cmd_unix_sock_path);
5795
5796 /* 64 bits consumerd path setup */
5797 ret = snprintf(ustconsumer64_data.err_unix_sock_path, PATH_MAX,
5798 DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH, rundir);
5799 if (ret < 0) {
5800 PERROR("snprintf 64-bit consumer error socket path");
5801 retval = -1;
5802 goto exit_init_data;
5803 }
5804 ret = snprintf(ustconsumer64_data.cmd_unix_sock_path, PATH_MAX,
5805 DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH, rundir);
5806 if (ret < 0) {
5807 PERROR("snprintf 64-bit consumer command socket path");
5808 retval = -1;
5809 goto exit_init_data;
5810 }
5811
5812 DBG2("UST consumer 64 bits err path: %s",
5813 ustconsumer64_data.err_unix_sock_path);
5814 DBG2("UST consumer 64 bits cmd path: %s",
5815 ustconsumer64_data.cmd_unix_sock_path);
5816
5817 /*
5818 * See if daemon already exist.
5819 */
5820 if (check_existing_daemon()) {
5821 ERR("Already running daemon.\n");
5822 /*
5823 * We do not goto exit because we must not cleanup()
5824 * because a daemon is already running.
5825 */
5826 retval = -1;
5827 goto exit_init_data;
5828 }
5829
5830 /*
5831 * Init UST app hash table. Alloc hash table before this point since
5832 * cleanup() can get called after that point.
5833 */
5834 if (ust_app_ht_alloc()) {
5835 ERR("Failed to allocate UST app hash table");
5836 retval = -1;
5837 goto exit_init_data;
5838 }
5839
5840 /*
5841 * Initialize agent app hash table. We allocate the hash table here
5842 * since cleanup() can get called after this point.
5843 */
5844 if (agent_app_ht_alloc()) {
5845 ERR("Failed to allocate Agent app hash table");
5846 retval = -1;
5847 goto exit_init_data;
5848 }
5849
5850 /*
5851 * These actions must be executed as root. We do that *after* setting up
5852 * the sockets path because we MUST make the check for another daemon using
5853 * those paths *before* trying to set the kernel consumer sockets and init
5854 * kernel tracer.
5855 */
5856 if (is_root) {
5857 if (set_consumer_sockets(&kconsumer_data, rundir)) {
5858 retval = -1;
5859 goto exit_init_data;
5860 }
5861
5862 /* Setup kernel tracer */
5863 if (!opt_no_kernel) {
5864 init_kernel_tracer();
5865 if (kernel_tracer_fd >= 0) {
5866 ret = syscall_init_table();
5867 if (ret < 0) {
5868 ERR("Unable to populate syscall table. "
5869 "Syscall tracing won't work "
5870 "for this session daemon.");
5871 }
5872 }
5873 }
5874
5875 /* Set ulimit for open files */
5876 set_ulimit();
5877 }
5878 /* init lttng_fd tracking must be done after set_ulimit. */
5879 lttng_fd_init();
5880
5881 if (set_consumer_sockets(&ustconsumer64_data, rundir)) {
5882 retval = -1;
5883 goto exit_init_data;
5884 }
5885
5886 if (set_consumer_sockets(&ustconsumer32_data, rundir)) {
5887 retval = -1;
5888 goto exit_init_data;
5889 }
5890
5891 /* Setup the needed unix socket */
5892 if (init_daemon_socket()) {
5893 retval = -1;
5894 goto exit_init_data;
5895 }
5896
5897 /* Set credentials to socket */
5898 if (is_root && set_permissions(rundir)) {
5899 retval = -1;
5900 goto exit_init_data;
5901 }
5902
5903 /* Get parent pid if -S, --sig-parent is specified. */
5904 if (opt_sig_parent) {
5905 ppid = getppid();
5906 }
5907
5908 /* Setup the kernel pipe for waking up the kernel thread */
5909 if (is_root && !opt_no_kernel) {
5910 if (utils_create_pipe_cloexec(kernel_poll_pipe)) {
5911 retval = -1;
5912 goto exit_init_data;
5913 }
5914 }
5915
5916 /* Setup the thread apps communication pipe. */
5917 if (utils_create_pipe_cloexec(apps_cmd_pipe)) {
5918 retval = -1;
5919 goto exit_init_data;
5920 }
5921
5922 /* Setup the thread apps notify communication pipe. */
5923 if (utils_create_pipe_cloexec(apps_cmd_notify_pipe)) {
5924 retval = -1;
5925 goto exit_init_data;
5926 }
5927
5928 /* Initialize global buffer per UID and PID registry. */
5929 buffer_reg_init_uid_registry();
5930 buffer_reg_init_pid_registry();
5931
5932 /* Init UST command queue. */
5933 cds_wfcq_init(&ust_cmd_queue.head, &ust_cmd_queue.tail);
5934
5935 /*
5936 * Get session list pointer. This pointer MUST NOT be free'd. This list
5937 * is statically declared in session.c
5938 */
5939 session_list_ptr = session_get_list();
5940
5941 cmd_init();
5942
5943 /* Check for the application socket timeout env variable. */
5944 env_app_timeout = getenv(DEFAULT_APP_SOCKET_TIMEOUT_ENV);
5945 if (env_app_timeout) {
5946 app_socket_timeout = atoi(env_app_timeout);
5947 } else {
5948 app_socket_timeout = DEFAULT_APP_SOCKET_RW_TIMEOUT;
5949 }
5950
5951 ret = write_pidfile();
5952 if (ret) {
5953 ERR("Error in write_pidfile");
5954 retval = -1;
5955 goto exit_init_data;
5956 }
5957 ret = write_agent_port();
5958 if (ret) {
5959 ERR("Error in write_agent_port");
5960 retval = -1;
5961 goto exit_init_data;
5962 }
5963
5964 /* Initialize communication library */
5965 lttcomm_init();
5966 /* Initialize TCP timeout values */
5967 lttcomm_inet_init();
5968
5969 if (load_session_init_data(&load_info) < 0) {
5970 retval = -1;
5971 goto exit_init_data;
5972 }
5973 load_info->path = opt_load_session_path;
5974
5975 /* Create health-check thread */
5976 ret = pthread_create(&health_thread, default_pthread_attr(),
5977 thread_manage_health, (void *) NULL);
5978 if (ret) {
5979 errno = ret;
5980 PERROR("pthread_create health");
5981 retval = -1;
5982 goto exit_health;
5983 }
5984
5985 /* Create thread to manage the client socket */
5986 ret = pthread_create(&client_thread, default_pthread_attr(),
5987 thread_manage_clients, (void *) NULL);
5988 if (ret) {
5989 errno = ret;
5990 PERROR("pthread_create clients");
5991 retval = -1;
5992 goto exit_client;
5993 }
5994
5995 /* Create thread to dispatch registration */
5996 ret = pthread_create(&dispatch_thread, default_pthread_attr(),
5997 thread_dispatch_ust_registration, (void *) NULL);
5998 if (ret) {
5999 errno = ret;
6000 PERROR("pthread_create dispatch");
6001 retval = -1;
6002 goto exit_dispatch;
6003 }
6004
6005 /* Create thread to manage application registration. */
6006 ret = pthread_create(&reg_apps_thread, default_pthread_attr(),
6007 thread_registration_apps, (void *) NULL);
6008 if (ret) {
6009 errno = ret;
6010 PERROR("pthread_create registration");
6011 retval = -1;
6012 goto exit_reg_apps;
6013 }
6014
6015 /* Create thread to manage application socket */
6016 ret = pthread_create(&apps_thread, default_pthread_attr(),
6017 thread_manage_apps, (void *) NULL);
6018 if (ret) {
6019 errno = ret;
6020 PERROR("pthread_create apps");
6021 retval = -1;
6022 goto exit_apps;
6023 }
6024
6025 /* Create thread to manage application notify socket */
6026 ret = pthread_create(&apps_notify_thread, default_pthread_attr(),
6027 ust_thread_manage_notify, (void *) NULL);
6028 if (ret) {
6029 errno = ret;
6030 PERROR("pthread_create notify");
6031 retval = -1;
6032 goto exit_apps_notify;
6033 }
6034
6035 /* Create agent registration thread. */
6036 ret = pthread_create(&agent_reg_thread, default_pthread_attr(),
6037 agent_thread_manage_registration, (void *) NULL);
6038 if (ret) {
6039 errno = ret;
6040 PERROR("pthread_create agent");
6041 retval = -1;
6042 goto exit_agent_reg;
6043 }
6044
6045 /* Don't start this thread if kernel tracing is not requested nor root */
6046 if (is_root && !opt_no_kernel) {
6047 /* Create kernel thread to manage kernel event */
6048 ret = pthread_create(&kernel_thread, default_pthread_attr(),
6049 thread_manage_kernel, (void *) NULL);
6050 if (ret) {
6051 errno = ret;
6052 PERROR("pthread_create kernel");
6053 retval = -1;
6054 goto exit_kernel;
6055 }
6056 }
6057
6058 /* Create session loading thread. */
6059 ret = pthread_create(&load_session_thread, default_pthread_attr(),
6060 thread_load_session, load_info);
6061 if (ret) {
6062 errno = ret;
6063 PERROR("pthread_create load_session_thread");
6064 retval = -1;
6065 goto exit_load_session;
6066 }
6067
6068 /*
6069 * This is where we start awaiting program completion (e.g. through
6070 * signal that asks threads to teardown).
6071 */
6072
6073 ret = pthread_join(load_session_thread, &status);
6074 if (ret) {
6075 errno = ret;
6076 PERROR("pthread_join load_session_thread");
6077 retval = -1;
6078 }
6079 exit_load_session:
6080
6081 if (is_root && !opt_no_kernel) {
6082 ret = pthread_join(kernel_thread, &status);
6083 if (ret) {
6084 errno = ret;
6085 PERROR("pthread_join");
6086 retval = -1;
6087 }
6088 }
6089 exit_kernel:
6090
6091 ret = pthread_join(agent_reg_thread, &status);
6092 if (ret) {
6093 errno = ret;
6094 PERROR("pthread_join agent");
6095 retval = -1;
6096 }
6097 exit_agent_reg:
6098
6099 ret = pthread_join(apps_notify_thread, &status);
6100 if (ret) {
6101 errno = ret;
6102 PERROR("pthread_join apps notify");
6103 retval = -1;
6104 }
6105 exit_apps_notify:
6106
6107 ret = pthread_join(apps_thread, &status);
6108 if (ret) {
6109 errno = ret;
6110 PERROR("pthread_join apps");
6111 retval = -1;
6112 }
6113 exit_apps:
6114
6115 ret = pthread_join(reg_apps_thread, &status);
6116 if (ret) {
6117 errno = ret;
6118 PERROR("pthread_join");
6119 retval = -1;
6120 }
6121 exit_reg_apps:
6122
6123 /*
6124 * Join dispatch thread after joining reg_apps_thread to ensure
6125 * we don't leak applications in the queue.
6126 */
6127 ret = pthread_join(dispatch_thread, &status);
6128 if (ret) {
6129 errno = ret;
6130 PERROR("pthread_join");
6131 retval = -1;
6132 }
6133 exit_dispatch:
6134
6135 ret = pthread_join(client_thread, &status);
6136 if (ret) {
6137 errno = ret;
6138 PERROR("pthread_join");
6139 retval = -1;
6140 }
6141 exit_client:
6142
6143 ret = pthread_join(health_thread, &status);
6144 if (ret) {
6145 errno = ret;
6146 PERROR("pthread_join health thread");
6147 retval = -1;
6148 }
6149 exit_health:
6150
6151 exit_init_data:
6152 /*
6153 * Wait for all pending call_rcu work to complete before tearing
6154 * down data structures. call_rcu worker may be trying to
6155 * perform lookups in those structures.
6156 */
6157 rcu_barrier();
6158 /*
6159 * sessiond_cleanup() is called when no other thread is running, except
6160 * the ht_cleanup thread, which is needed to destroy the hash tables.
6161 */
6162 rcu_thread_online();
6163 sessiond_cleanup();
6164 rcu_thread_offline();
6165 rcu_unregister_thread();
6166
6167 /*
6168 * Ensure all prior call_rcu are done. call_rcu callbacks may push
6169 * hash tables to the ht_cleanup thread. Therefore, we ensure that
6170 * the queue is empty before shutting down the clean-up thread.
6171 */
6172 rcu_barrier();
6173
6174 ret = fini_ht_cleanup_thread(&ht_cleanup_thread);
6175 if (ret) {
6176 retval = -1;
6177 }
6178 exit_ht_cleanup:
6179
6180 health_app_destroy(health_sessiond);
6181 exit_health_sessiond_cleanup:
6182 exit_create_run_as_worker_cleanup:
6183
6184 exit_options:
6185 sessiond_cleanup_options();
6186
6187 exit_set_signal_handler:
6188
6189 if (!retval) {
6190 exit(EXIT_SUCCESS);
6191 } else {
6192 exit(EXIT_FAILURE);
6193 }
6194 }
This page took 0.219318 seconds and 6 git commands to generate.