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