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