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