Fix: uninitialized directory handle finalized on error path
[lttng-tools.git] / src / bin / lttng-relayd / main.c
1 /*
2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 2 only,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #define _LGPL_SOURCE
22 #include <getopt.h>
23 #include <grp.h>
24 #include <limits.h>
25 #include <pthread.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/mman.h>
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <inttypes.h>
38 #include <urcu/futex.h>
39 #include <urcu/uatomic.h>
40 #include <urcu/rculist.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <strings.h>
44
45 #include <lttng/lttng.h>
46 #include <common/common.h>
47 #include <common/compat/poll.h>
48 #include <common/compat/socket.h>
49 #include <common/compat/endian.h>
50 #include <common/compat/getenv.h>
51 #include <common/defaults.h>
52 #include <common/daemonize.h>
53 #include <common/futex.h>
54 #include <common/sessiond-comm/sessiond-comm.h>
55 #include <common/sessiond-comm/inet.h>
56 #include <common/sessiond-comm/relayd.h>
57 #include <common/uri.h>
58 #include <common/utils.h>
59 #include <common/align.h>
60 #include <common/config/session-config.h>
61 #include <common/dynamic-buffer.h>
62 #include <common/buffer-view.h>
63 #include <common/string-utils/format.h>
64
65 #include "cmd.h"
66 #include "ctf-trace.h"
67 #include "index.h"
68 #include "utils.h"
69 #include "lttng-relayd.h"
70 #include "live.h"
71 #include "health-relayd.h"
72 #include "testpoint.h"
73 #include "viewer-stream.h"
74 #include "session.h"
75 #include "stream.h"
76 #include "connection.h"
77 #include "tracefile-array.h"
78 #include "tcp_keep_alive.h"
79 #include "sessiond-trace-chunks.h"
80
81 static const char *help_msg =
82 #ifdef LTTNG_EMBED_HELP
83 #include <lttng-relayd.8.h>
84 #else
85 NULL
86 #endif
87 ;
88
89 enum relay_connection_status {
90 RELAY_CONNECTION_STATUS_OK,
91 /* An error occurred while processing an event on the connection. */
92 RELAY_CONNECTION_STATUS_ERROR,
93 /* Connection closed/shutdown cleanly. */
94 RELAY_CONNECTION_STATUS_CLOSED,
95 };
96
97 /* command line options */
98 char *opt_output_path;
99 static int opt_daemon, opt_background;
100
101 /*
102 * We need to wait for listener and live listener threads, as well as
103 * health check thread, before being ready to signal readiness.
104 */
105 #define NR_LTTNG_RELAY_READY 3
106 static int lttng_relay_ready = NR_LTTNG_RELAY_READY;
107
108 /* Size of receive buffer. */
109 #define RECV_DATA_BUFFER_SIZE 65536
110
111 static int recv_child_signal; /* Set to 1 when a SIGUSR1 signal is received. */
112 static pid_t child_ppid; /* Internal parent PID use with daemonize. */
113
114 static struct lttng_uri *control_uri;
115 static struct lttng_uri *data_uri;
116 static struct lttng_uri *live_uri;
117
118 const char *progname;
119
120 const char *tracing_group_name = DEFAULT_TRACING_GROUP;
121 static int tracing_group_name_override;
122
123 const char * const config_section_name = "relayd";
124
125 /*
126 * Quit pipe for all threads. This permits a single cancellation point
127 * for all threads when receiving an event on the pipe.
128 */
129 int thread_quit_pipe[2] = { -1, -1 };
130
131 /*
132 * This pipe is used to inform the worker thread that a command is queued and
133 * ready to be processed.
134 */
135 static int relay_conn_pipe[2] = { -1, -1 };
136
137 /* Shared between threads */
138 static int dispatch_thread_exit;
139
140 static pthread_t listener_thread;
141 static pthread_t dispatcher_thread;
142 static pthread_t worker_thread;
143 static pthread_t health_thread;
144
145 /*
146 * last_relay_stream_id_lock protects last_relay_stream_id increment
147 * atomicity on 32-bit architectures.
148 */
149 static pthread_mutex_t last_relay_stream_id_lock = PTHREAD_MUTEX_INITIALIZER;
150 static uint64_t last_relay_stream_id;
151
152 /*
153 * Relay command queue.
154 *
155 * The relay_thread_listener and relay_thread_dispatcher communicate with this
156 * queue.
157 */
158 static struct relay_conn_queue relay_conn_queue;
159
160 /* Global relay stream hash table. */
161 struct lttng_ht *relay_streams_ht;
162
163 /* Global relay viewer stream hash table. */
164 struct lttng_ht *viewer_streams_ht;
165
166 /* Global relay sessions hash table. */
167 struct lttng_ht *sessions_ht;
168
169 /* Relayd health monitoring */
170 struct health_app *health_relayd;
171
172 struct sessiond_trace_chunk_registry *sessiond_trace_chunk_registry;
173
174 static struct option long_options[] = {
175 { "control-port", 1, 0, 'C', },
176 { "data-port", 1, 0, 'D', },
177 { "live-port", 1, 0, 'L', },
178 { "daemonize", 0, 0, 'd', },
179 { "background", 0, 0, 'b', },
180 { "group", 1, 0, 'g', },
181 { "help", 0, 0, 'h', },
182 { "output", 1, 0, 'o', },
183 { "verbose", 0, 0, 'v', },
184 { "config", 1, 0, 'f' },
185 { "version", 0, 0, 'V' },
186 { NULL, 0, 0, 0, },
187 };
188
189 static const char *config_ignore_options[] = { "help", "config", "version" };
190
191 /*
192 * Take an option from the getopt output and set it in the right variable to be
193 * used later.
194 *
195 * Return 0 on success else a negative value.
196 */
197 static int set_option(int opt, const char *arg, const char *optname)
198 {
199 int ret;
200
201 switch (opt) {
202 case 0:
203 fprintf(stderr, "option %s", optname);
204 if (arg) {
205 fprintf(stderr, " with arg %s\n", arg);
206 }
207 break;
208 case 'C':
209 if (lttng_is_setuid_setgid()) {
210 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
211 "-C, --control-port");
212 } else {
213 ret = uri_parse(arg, &control_uri);
214 if (ret < 0) {
215 ERR("Invalid control URI specified");
216 goto end;
217 }
218 if (control_uri->port == 0) {
219 control_uri->port = DEFAULT_NETWORK_CONTROL_PORT;
220 }
221 }
222 break;
223 case 'D':
224 if (lttng_is_setuid_setgid()) {
225 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
226 "-D, -data-port");
227 } else {
228 ret = uri_parse(arg, &data_uri);
229 if (ret < 0) {
230 ERR("Invalid data URI specified");
231 goto end;
232 }
233 if (data_uri->port == 0) {
234 data_uri->port = DEFAULT_NETWORK_DATA_PORT;
235 }
236 }
237 break;
238 case 'L':
239 if (lttng_is_setuid_setgid()) {
240 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
241 "-L, -live-port");
242 } else {
243 ret = uri_parse(arg, &live_uri);
244 if (ret < 0) {
245 ERR("Invalid live URI specified");
246 goto end;
247 }
248 if (live_uri->port == 0) {
249 live_uri->port = DEFAULT_NETWORK_VIEWER_PORT;
250 }
251 }
252 break;
253 case 'd':
254 opt_daemon = 1;
255 break;
256 case 'b':
257 opt_background = 1;
258 break;
259 case 'g':
260 if (lttng_is_setuid_setgid()) {
261 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
262 "-g, --group");
263 } else {
264 tracing_group_name = strdup(arg);
265 if (tracing_group_name == NULL) {
266 ret = -errno;
267 PERROR("strdup");
268 goto end;
269 }
270 tracing_group_name_override = 1;
271 }
272 break;
273 case 'h':
274 ret = utils_show_help(8, "lttng-relayd", help_msg);
275 if (ret) {
276 ERR("Cannot show --help for `lttng-relayd`");
277 perror("exec");
278 }
279 exit(EXIT_FAILURE);
280 case 'V':
281 fprintf(stdout, "%s\n", VERSION);
282 exit(EXIT_SUCCESS);
283 case 'o':
284 if (lttng_is_setuid_setgid()) {
285 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 "-o, --output");
287 } else {
288 ret = asprintf(&opt_output_path, "%s", arg);
289 if (ret < 0) {
290 ret = -errno;
291 PERROR("asprintf opt_output_path");
292 goto end;
293 }
294 }
295 break;
296 case 'v':
297 /* Verbose level can increase using multiple -v */
298 if (arg) {
299 lttng_opt_verbose = config_parse_value(arg);
300 } else {
301 /* Only 3 level of verbosity (-vvv). */
302 if (lttng_opt_verbose < 3) {
303 lttng_opt_verbose += 1;
304 }
305 }
306 break;
307 default:
308 /* Unknown option or other error.
309 * Error is printed by getopt, just return */
310 ret = -1;
311 goto end;
312 }
313
314 /* All good. */
315 ret = 0;
316
317 end:
318 return ret;
319 }
320
321 /*
322 * config_entry_handler_cb used to handle options read from a config file.
323 * See config_entry_handler_cb comment in common/config/session-config.h for the
324 * return value conventions.
325 */
326 static int config_entry_handler(const struct config_entry *entry, void *unused)
327 {
328 int ret = 0, i;
329
330 if (!entry || !entry->name || !entry->value) {
331 ret = -EINVAL;
332 goto end;
333 }
334
335 /* Check if the option is to be ignored */
336 for (i = 0; i < sizeof(config_ignore_options) / sizeof(char *); i++) {
337 if (!strcmp(entry->name, config_ignore_options[i])) {
338 goto end;
339 }
340 }
341
342 for (i = 0; i < (sizeof(long_options) / sizeof(struct option)) - 1; i++) {
343 /* Ignore if entry name is not fully matched. */
344 if (strcmp(entry->name, long_options[i].name)) {
345 continue;
346 }
347
348 /*
349 * If the option takes no argument on the command line,
350 * we have to check if the value is "true". We support
351 * non-zero numeric values, true, on and yes.
352 */
353 if (!long_options[i].has_arg) {
354 ret = config_parse_value(entry->value);
355 if (ret <= 0) {
356 if (ret) {
357 WARN("Invalid configuration value \"%s\" for option %s",
358 entry->value, entry->name);
359 }
360 /* False, skip boolean config option. */
361 goto end;
362 }
363 }
364
365 ret = set_option(long_options[i].val, entry->value, entry->name);
366 goto end;
367 }
368
369 WARN("Unrecognized option \"%s\" in daemon configuration file.",
370 entry->name);
371
372 end:
373 return ret;
374 }
375
376 static int set_options(int argc, char **argv)
377 {
378 int c, ret = 0, option_index = 0, retval = 0;
379 int orig_optopt = optopt, orig_optind = optind;
380 char *default_address, *optstring;
381 const char *config_path = NULL;
382
383 optstring = utils_generate_optstring(long_options,
384 sizeof(long_options) / sizeof(struct option));
385 if (!optstring) {
386 retval = -ENOMEM;
387 goto exit;
388 }
389
390 /* Check for the --config option */
391
392 while ((c = getopt_long(argc, argv, optstring, long_options,
393 &option_index)) != -1) {
394 if (c == '?') {
395 retval = -EINVAL;
396 goto exit;
397 } else if (c != 'f') {
398 continue;
399 }
400
401 if (lttng_is_setuid_setgid()) {
402 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
403 "-f, --config");
404 } else {
405 config_path = utils_expand_path(optarg);
406 if (!config_path) {
407 ERR("Failed to resolve path: %s", optarg);
408 }
409 }
410 }
411
412 ret = config_get_section_entries(config_path, config_section_name,
413 config_entry_handler, NULL);
414 if (ret) {
415 if (ret > 0) {
416 ERR("Invalid configuration option at line %i", ret);
417 }
418 retval = -1;
419 goto exit;
420 }
421
422 /* Reset getopt's global state */
423 optopt = orig_optopt;
424 optind = orig_optind;
425 while (1) {
426 c = getopt_long(argc, argv, optstring, long_options, &option_index);
427 if (c == -1) {
428 break;
429 }
430
431 ret = set_option(c, optarg, long_options[option_index].name);
432 if (ret < 0) {
433 retval = -1;
434 goto exit;
435 }
436 }
437
438 /* assign default values */
439 if (control_uri == NULL) {
440 ret = asprintf(&default_address,
441 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS ":%d",
442 DEFAULT_NETWORK_CONTROL_PORT);
443 if (ret < 0) {
444 PERROR("asprintf default data address");
445 retval = -1;
446 goto exit;
447 }
448
449 ret = uri_parse(default_address, &control_uri);
450 free(default_address);
451 if (ret < 0) {
452 ERR("Invalid control URI specified");
453 retval = -1;
454 goto exit;
455 }
456 }
457 if (data_uri == NULL) {
458 ret = asprintf(&default_address,
459 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS ":%d",
460 DEFAULT_NETWORK_DATA_PORT);
461 if (ret < 0) {
462 PERROR("asprintf default data address");
463 retval = -1;
464 goto exit;
465 }
466
467 ret = uri_parse(default_address, &data_uri);
468 free(default_address);
469 if (ret < 0) {
470 ERR("Invalid data URI specified");
471 retval = -1;
472 goto exit;
473 }
474 }
475 if (live_uri == NULL) {
476 ret = asprintf(&default_address,
477 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS ":%d",
478 DEFAULT_NETWORK_VIEWER_PORT);
479 if (ret < 0) {
480 PERROR("asprintf default viewer control address");
481 retval = -1;
482 goto exit;
483 }
484
485 ret = uri_parse(default_address, &live_uri);
486 free(default_address);
487 if (ret < 0) {
488 ERR("Invalid viewer control URI specified");
489 retval = -1;
490 goto exit;
491 }
492 }
493
494 exit:
495 free(optstring);
496 return retval;
497 }
498
499 static void print_global_objects(void)
500 {
501 rcu_register_thread();
502
503 print_viewer_streams();
504 print_relay_streams();
505 print_sessions();
506
507 rcu_unregister_thread();
508 }
509
510 /*
511 * Cleanup the daemon
512 */
513 static void relayd_cleanup(void)
514 {
515 print_global_objects();
516
517 DBG("Cleaning up");
518
519 if (viewer_streams_ht)
520 lttng_ht_destroy(viewer_streams_ht);
521 if (relay_streams_ht)
522 lttng_ht_destroy(relay_streams_ht);
523 if (sessions_ht)
524 lttng_ht_destroy(sessions_ht);
525
526 /* free the dynamically allocated opt_output_path */
527 free(opt_output_path);
528
529 /* Close thread quit pipes */
530 utils_close_pipe(thread_quit_pipe);
531
532 uri_free(control_uri);
533 uri_free(data_uri);
534 /* Live URI is freed in the live thread. */
535
536 if (tracing_group_name_override) {
537 free((void *) tracing_group_name);
538 }
539 }
540
541 /*
542 * Write to writable pipe used to notify a thread.
543 */
544 static int notify_thread_pipe(int wpipe)
545 {
546 ssize_t ret;
547
548 ret = lttng_write(wpipe, "!", 1);
549 if (ret < 1) {
550 PERROR("write poll pipe");
551 goto end;
552 }
553 ret = 0;
554 end:
555 return ret;
556 }
557
558 static int notify_health_quit_pipe(int *pipe)
559 {
560 ssize_t ret;
561
562 ret = lttng_write(pipe[1], "4", 1);
563 if (ret < 1) {
564 PERROR("write relay health quit");
565 goto end;
566 }
567 ret = 0;
568 end:
569 return ret;
570 }
571
572 /*
573 * Stop all relayd and relayd-live threads.
574 */
575 int lttng_relay_stop_threads(void)
576 {
577 int retval = 0;
578
579 /* Stopping all threads */
580 DBG("Terminating all threads");
581 if (notify_thread_pipe(thread_quit_pipe[1])) {
582 ERR("write error on thread quit pipe");
583 retval = -1;
584 }
585
586 if (notify_health_quit_pipe(health_quit_pipe)) {
587 ERR("write error on health quit pipe");
588 }
589
590 /* Dispatch thread */
591 CMM_STORE_SHARED(dispatch_thread_exit, 1);
592 futex_nto1_wake(&relay_conn_queue.futex);
593
594 if (relayd_live_stop()) {
595 ERR("Error stopping live threads");
596 retval = -1;
597 }
598 return retval;
599 }
600
601 /*
602 * Signal handler for the daemon
603 *
604 * Simply stop all worker threads, leaving main() return gracefully after
605 * joining all threads and calling cleanup().
606 */
607 static void sighandler(int sig)
608 {
609 switch (sig) {
610 case SIGINT:
611 DBG("SIGINT caught");
612 if (lttng_relay_stop_threads()) {
613 ERR("Error stopping threads");
614 }
615 break;
616 case SIGTERM:
617 DBG("SIGTERM caught");
618 if (lttng_relay_stop_threads()) {
619 ERR("Error stopping threads");
620 }
621 break;
622 case SIGUSR1:
623 CMM_STORE_SHARED(recv_child_signal, 1);
624 break;
625 default:
626 break;
627 }
628 }
629
630 /*
631 * Setup signal handler for :
632 * SIGINT, SIGTERM, SIGPIPE
633 */
634 static int set_signal_handler(void)
635 {
636 int ret = 0;
637 struct sigaction sa;
638 sigset_t sigset;
639
640 if ((ret = sigemptyset(&sigset)) < 0) {
641 PERROR("sigemptyset");
642 return ret;
643 }
644
645 sa.sa_mask = sigset;
646 sa.sa_flags = 0;
647
648 sa.sa_handler = sighandler;
649 if ((ret = sigaction(SIGTERM, &sa, NULL)) < 0) {
650 PERROR("sigaction");
651 return ret;
652 }
653
654 if ((ret = sigaction(SIGINT, &sa, NULL)) < 0) {
655 PERROR("sigaction");
656 return ret;
657 }
658
659 if ((ret = sigaction(SIGUSR1, &sa, NULL)) < 0) {
660 PERROR("sigaction");
661 return ret;
662 }
663
664 sa.sa_handler = SIG_IGN;
665 if ((ret = sigaction(SIGPIPE, &sa, NULL)) < 0) {
666 PERROR("sigaction");
667 return ret;
668 }
669
670 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
671
672 return ret;
673 }
674
675 void lttng_relay_notify_ready(void)
676 {
677 /* Notify the parent of the fork() process that we are ready. */
678 if (opt_daemon || opt_background) {
679 if (uatomic_sub_return(&lttng_relay_ready, 1) == 0) {
680 kill(child_ppid, SIGUSR1);
681 }
682 }
683 }
684
685 /*
686 * Init thread quit pipe.
687 *
688 * Return -1 on error or 0 if all pipes are created.
689 */
690 static int init_thread_quit_pipe(void)
691 {
692 int ret;
693
694 ret = utils_create_pipe_cloexec(thread_quit_pipe);
695
696 return ret;
697 }
698
699 /*
700 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
701 */
702 static int create_thread_poll_set(struct lttng_poll_event *events, int size)
703 {
704 int ret;
705
706 if (events == NULL || size == 0) {
707 ret = -1;
708 goto error;
709 }
710
711 ret = lttng_poll_create(events, size, LTTNG_CLOEXEC);
712 if (ret < 0) {
713 goto error;
714 }
715
716 /* Add quit pipe */
717 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
718 if (ret < 0) {
719 goto error;
720 }
721
722 return 0;
723
724 error:
725 return ret;
726 }
727
728 /*
729 * Check if the thread quit pipe was triggered.
730 *
731 * Return 1 if it was triggered else 0;
732 */
733 static int check_thread_quit_pipe(int fd, uint32_t events)
734 {
735 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
736 return 1;
737 }
738
739 return 0;
740 }
741
742 /*
743 * Create and init socket from uri.
744 */
745 static struct lttcomm_sock *relay_socket_create(struct lttng_uri *uri)
746 {
747 int ret;
748 struct lttcomm_sock *sock = NULL;
749
750 sock = lttcomm_alloc_sock_from_uri(uri);
751 if (sock == NULL) {
752 ERR("Allocating socket");
753 goto error;
754 }
755
756 ret = lttcomm_create_sock(sock);
757 if (ret < 0) {
758 goto error;
759 }
760 DBG("Listening on sock %d", sock->fd);
761
762 ret = sock->ops->bind(sock);
763 if (ret < 0) {
764 PERROR("Failed to bind socket");
765 goto error;
766 }
767
768 ret = sock->ops->listen(sock, -1);
769 if (ret < 0) {
770 goto error;
771
772 }
773
774 return sock;
775
776 error:
777 if (sock) {
778 lttcomm_destroy_sock(sock);
779 }
780 return NULL;
781 }
782
783 /*
784 * This thread manages the listening for new connections on the network
785 */
786 static void *relay_thread_listener(void *data)
787 {
788 int i, ret, pollfd, err = -1;
789 uint32_t revents, nb_fd;
790 struct lttng_poll_event events;
791 struct lttcomm_sock *control_sock, *data_sock;
792
793 DBG("[thread] Relay listener started");
794
795 health_register(health_relayd, HEALTH_RELAYD_TYPE_LISTENER);
796
797 health_code_update();
798
799 control_sock = relay_socket_create(control_uri);
800 if (!control_sock) {
801 goto error_sock_control;
802 }
803
804 data_sock = relay_socket_create(data_uri);
805 if (!data_sock) {
806 goto error_sock_relay;
807 }
808
809 /*
810 * Pass 3 as size here for the thread quit pipe, control and
811 * data socket.
812 */
813 ret = create_thread_poll_set(&events, 3);
814 if (ret < 0) {
815 goto error_create_poll;
816 }
817
818 /* Add the control socket */
819 ret = lttng_poll_add(&events, control_sock->fd, LPOLLIN | LPOLLRDHUP);
820 if (ret < 0) {
821 goto error_poll_add;
822 }
823
824 /* Add the data socket */
825 ret = lttng_poll_add(&events, data_sock->fd, LPOLLIN | LPOLLRDHUP);
826 if (ret < 0) {
827 goto error_poll_add;
828 }
829
830 lttng_relay_notify_ready();
831
832 if (testpoint(relayd_thread_listener)) {
833 goto error_testpoint;
834 }
835
836 while (1) {
837 health_code_update();
838
839 DBG("Listener accepting connections");
840
841 restart:
842 health_poll_entry();
843 ret = lttng_poll_wait(&events, -1);
844 health_poll_exit();
845 if (ret < 0) {
846 /*
847 * Restart interrupted system call.
848 */
849 if (errno == EINTR) {
850 goto restart;
851 }
852 goto error;
853 }
854
855 nb_fd = ret;
856
857 DBG("Relay new connection received");
858 for (i = 0; i < nb_fd; i++) {
859 health_code_update();
860
861 /* Fetch once the poll data */
862 revents = LTTNG_POLL_GETEV(&events, i);
863 pollfd = LTTNG_POLL_GETFD(&events, i);
864
865 /* Thread quit pipe has been closed. Killing thread. */
866 ret = check_thread_quit_pipe(pollfd, revents);
867 if (ret) {
868 err = 0;
869 goto exit;
870 }
871
872 if (revents & LPOLLIN) {
873 /*
874 * A new connection is requested, therefore a
875 * sessiond/consumerd connection is allocated in
876 * this thread, enqueued to a global queue and
877 * dequeued (and freed) in the worker thread.
878 */
879 int val = 1;
880 struct relay_connection *new_conn;
881 struct lttcomm_sock *newsock;
882 enum connection_type type;
883
884 if (pollfd == data_sock->fd) {
885 type = RELAY_DATA;
886 newsock = data_sock->ops->accept(data_sock);
887 DBG("Relay data connection accepted, socket %d",
888 newsock->fd);
889 } else {
890 assert(pollfd == control_sock->fd);
891 type = RELAY_CONTROL;
892 newsock = control_sock->ops->accept(control_sock);
893 DBG("Relay control connection accepted, socket %d",
894 newsock->fd);
895 }
896 if (!newsock) {
897 PERROR("accepting sock");
898 goto error;
899 }
900
901 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
902 sizeof(val));
903 if (ret < 0) {
904 PERROR("setsockopt inet");
905 lttcomm_destroy_sock(newsock);
906 goto error;
907 }
908
909 ret = socket_apply_keep_alive_config(newsock->fd);
910 if (ret < 0) {
911 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
912 newsock->fd);
913 lttcomm_destroy_sock(newsock);
914 goto error;
915 }
916
917 new_conn = connection_create(newsock, type);
918 if (!new_conn) {
919 lttcomm_destroy_sock(newsock);
920 goto error;
921 }
922
923 /* Enqueue request for the dispatcher thread. */
924 cds_wfcq_enqueue(&relay_conn_queue.head, &relay_conn_queue.tail,
925 &new_conn->qnode);
926
927 /*
928 * Wake the dispatch queue futex.
929 * Implicit memory barrier with the
930 * exchange in cds_wfcq_enqueue.
931 */
932 futex_nto1_wake(&relay_conn_queue.futex);
933 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
934 ERR("socket poll error");
935 goto error;
936 } else {
937 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
938 goto error;
939 }
940 }
941 }
942
943 exit:
944 error:
945 error_poll_add:
946 error_testpoint:
947 lttng_poll_clean(&events);
948 error_create_poll:
949 if (data_sock->fd >= 0) {
950 ret = data_sock->ops->close(data_sock);
951 if (ret) {
952 PERROR("close");
953 }
954 }
955 lttcomm_destroy_sock(data_sock);
956 error_sock_relay:
957 if (control_sock->fd >= 0) {
958 ret = control_sock->ops->close(control_sock);
959 if (ret) {
960 PERROR("close");
961 }
962 }
963 lttcomm_destroy_sock(control_sock);
964 error_sock_control:
965 if (err) {
966 health_error();
967 ERR("Health error occurred in %s", __func__);
968 }
969 health_unregister(health_relayd);
970 DBG("Relay listener thread cleanup complete");
971 lttng_relay_stop_threads();
972 return NULL;
973 }
974
975 /*
976 * This thread manages the dispatching of the requests to worker threads
977 */
978 static void *relay_thread_dispatcher(void *data)
979 {
980 int err = -1;
981 ssize_t ret;
982 struct cds_wfcq_node *node;
983 struct relay_connection *new_conn = NULL;
984
985 DBG("[thread] Relay dispatcher started");
986
987 health_register(health_relayd, HEALTH_RELAYD_TYPE_DISPATCHER);
988
989 if (testpoint(relayd_thread_dispatcher)) {
990 goto error_testpoint;
991 }
992
993 health_code_update();
994
995 for (;;) {
996 health_code_update();
997
998 /* Atomically prepare the queue futex */
999 futex_nto1_prepare(&relay_conn_queue.futex);
1000
1001 if (CMM_LOAD_SHARED(dispatch_thread_exit)) {
1002 break;
1003 }
1004
1005 do {
1006 health_code_update();
1007
1008 /* Dequeue commands */
1009 node = cds_wfcq_dequeue_blocking(&relay_conn_queue.head,
1010 &relay_conn_queue.tail);
1011 if (node == NULL) {
1012 DBG("Woken up but nothing in the relay command queue");
1013 /* Continue thread execution */
1014 break;
1015 }
1016 new_conn = caa_container_of(node, struct relay_connection, qnode);
1017
1018 DBG("Dispatching request waiting on sock %d", new_conn->sock->fd);
1019
1020 /*
1021 * Inform worker thread of the new request. This
1022 * call is blocking so we can be assured that
1023 * the data will be read at some point in time
1024 * or wait to the end of the world :)
1025 */
1026 ret = lttng_write(relay_conn_pipe[1], &new_conn, sizeof(new_conn));
1027 if (ret < 0) {
1028 PERROR("write connection pipe");
1029 connection_put(new_conn);
1030 goto error;
1031 }
1032 } while (node != NULL);
1033
1034 /* Futex wait on queue. Blocking call on futex() */
1035 health_poll_entry();
1036 futex_nto1_wait(&relay_conn_queue.futex);
1037 health_poll_exit();
1038 }
1039
1040 /* Normal exit, no error */
1041 err = 0;
1042
1043 error:
1044 error_testpoint:
1045 if (err) {
1046 health_error();
1047 ERR("Health error occurred in %s", __func__);
1048 }
1049 health_unregister(health_relayd);
1050 DBG("Dispatch thread dying");
1051 lttng_relay_stop_threads();
1052 return NULL;
1053 }
1054
1055 static bool session_streams_have_index(const struct relay_session *session)
1056 {
1057 return session->minor >= 4 && !session->snapshot;
1058 }
1059
1060 /*
1061 * Handle the RELAYD_CREATE_SESSION command.
1062 *
1063 * On success, send back the session id or else return a negative value.
1064 */
1065 static int relay_create_session(const struct lttcomm_relayd_hdr *recv_hdr,
1066 struct relay_connection *conn,
1067 const struct lttng_buffer_view *payload)
1068 {
1069 int ret = 0;
1070 ssize_t send_ret;
1071 struct relay_session *session = NULL;
1072 struct lttcomm_relayd_create_session_reply_2_11 reply = {};
1073 char session_name[LTTNG_NAME_MAX] = {};
1074 char hostname[LTTNG_HOST_NAME_MAX] = {};
1075 uint32_t live_timer = 0;
1076 bool snapshot = false;
1077 bool session_name_contains_creation_timestamp = false;
1078 /* Left nil for peers < 2.11. */
1079 char base_path[LTTNG_PATH_MAX] = {};
1080 lttng_uuid sessiond_uuid = {};
1081 LTTNG_OPTIONAL(uint64_t) id_sessiond = {};
1082 LTTNG_OPTIONAL(uint64_t) current_chunk_id = {};
1083 LTTNG_OPTIONAL(time_t) creation_time = {};
1084 struct lttng_dynamic_buffer reply_payload;
1085
1086 lttng_dynamic_buffer_init(&reply_payload);
1087
1088 if (conn->minor < 4) {
1089 /* From 2.1 to 2.3 */
1090 ret = 0;
1091 } else if (conn->minor >= 4 && conn->minor < 11) {
1092 /* From 2.4 to 2.10 */
1093 ret = cmd_create_session_2_4(payload, session_name,
1094 hostname, &live_timer, &snapshot);
1095 } else {
1096 bool has_current_chunk;
1097 uint64_t current_chunk_id_value;
1098 time_t creation_time_value;
1099 uint64_t id_sessiond_value;
1100
1101 /* From 2.11 to ... */
1102 ret = cmd_create_session_2_11(payload, session_name, hostname,
1103 base_path, &live_timer, &snapshot, &id_sessiond_value,
1104 sessiond_uuid, &has_current_chunk,
1105 &current_chunk_id_value, &creation_time_value,
1106 &session_name_contains_creation_timestamp);
1107 if (lttng_uuid_is_nil(sessiond_uuid)) {
1108 /* The nil UUID is reserved for pre-2.11 clients. */
1109 ERR("Illegal nil UUID announced by peer in create session command");
1110 ret = -1;
1111 goto send_reply;
1112 }
1113 LTTNG_OPTIONAL_SET(&id_sessiond, id_sessiond_value);
1114 LTTNG_OPTIONAL_SET(&creation_time, creation_time_value);
1115 if (has_current_chunk) {
1116 LTTNG_OPTIONAL_SET(&current_chunk_id,
1117 current_chunk_id_value);
1118 }
1119 }
1120
1121 if (ret < 0) {
1122 goto send_reply;
1123 }
1124
1125 session = session_create(session_name, hostname, base_path, live_timer,
1126 snapshot, sessiond_uuid,
1127 id_sessiond.is_set ? &id_sessiond.value : NULL,
1128 current_chunk_id.is_set ? &current_chunk_id.value : NULL,
1129 creation_time.is_set ? &creation_time.value : NULL,
1130 conn->major, conn->minor,
1131 session_name_contains_creation_timestamp);
1132 if (!session) {
1133 ret = -1;
1134 goto send_reply;
1135 }
1136 assert(!conn->session);
1137 conn->session = session;
1138 DBG("Created session %" PRIu64, session->id);
1139
1140 reply.generic.session_id = htobe64(session->id);
1141
1142 send_reply:
1143 if (ret < 0) {
1144 reply.generic.ret_code = htobe32(LTTNG_ERR_FATAL);
1145 } else {
1146 reply.generic.ret_code = htobe32(LTTNG_OK);
1147 }
1148
1149 if (conn->minor < 11) {
1150 /* From 2.1 to 2.10 */
1151 ret = lttng_dynamic_buffer_append(&reply_payload,
1152 &reply.generic, sizeof(reply.generic));
1153 if (ret) {
1154 ERR("Failed to append \"create session\" command reply header to payload buffer");
1155 ret = -1;
1156 goto end;
1157 }
1158 } else {
1159 const uint32_t output_path_length =
1160 strlen(session->output_path) + 1;
1161
1162 reply.output_path_length = htobe32(output_path_length);
1163 ret = lttng_dynamic_buffer_append(&reply_payload, &reply,
1164 sizeof(reply));
1165 if (ret) {
1166 ERR("Failed to append \"create session\" command reply header to payload buffer");
1167 goto end;
1168 }
1169
1170 ret = lttng_dynamic_buffer_append(&reply_payload,
1171 session->output_path, output_path_length);
1172 if (ret) {
1173 ERR("Failed to append \"create session\" command reply path to payload buffer");
1174 goto end;
1175 }
1176 }
1177
1178 send_ret = conn->sock->ops->sendmsg(conn->sock, reply_payload.data,
1179 reply_payload.size, 0);
1180 if (send_ret < (ssize_t) reply_payload.size) {
1181 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1182 reply_payload.size, send_ret);
1183 ret = -1;
1184 }
1185 end:
1186 if (ret < 0 && session) {
1187 session_put(session);
1188 }
1189 lttng_dynamic_buffer_reset(&reply_payload);
1190 return ret;
1191 }
1192
1193 /*
1194 * When we have received all the streams and the metadata for a channel,
1195 * we make them visible to the viewer threads.
1196 */
1197 static void publish_connection_local_streams(struct relay_connection *conn)
1198 {
1199 struct relay_stream *stream;
1200 struct relay_session *session = conn->session;
1201
1202 /*
1203 * We publish all streams belonging to a session atomically wrt
1204 * session lock.
1205 */
1206 pthread_mutex_lock(&session->lock);
1207 rcu_read_lock();
1208 cds_list_for_each_entry_rcu(stream, &session->recv_list,
1209 recv_node) {
1210 stream_publish(stream);
1211 }
1212 rcu_read_unlock();
1213
1214 /*
1215 * Inform the viewer that there are new streams in the session.
1216 */
1217 if (session->viewer_attached) {
1218 uatomic_set(&session->new_streams, 1);
1219 }
1220 pthread_mutex_unlock(&session->lock);
1221 }
1222
1223 static int conform_channel_path(char *channel_path)
1224 {
1225 int ret = 0;
1226
1227 if (strstr("../", channel_path)) {
1228 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1229 channel_path);
1230 ret = -1;
1231 goto end;
1232 }
1233
1234 if (*channel_path == '/') {
1235 const size_t len = strlen(channel_path);
1236
1237 /*
1238 * Channel paths from peers prior to 2.11 are expressed as an
1239 * absolute path that is, in reality, relative to the relay
1240 * daemon's output directory. Remove the leading slash so it
1241 * is correctly interpreted as a relative path later on.
1242 *
1243 * len (and not len - 1) is used to copy the trailing NULL.
1244 */
1245 bcopy(channel_path + 1, channel_path, len);
1246 }
1247 end:
1248 return ret;
1249 }
1250
1251 /*
1252 * relay_add_stream: allocate a new stream for a session
1253 */
1254 static int relay_add_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1255 struct relay_connection *conn,
1256 const struct lttng_buffer_view *payload)
1257 {
1258 int ret;
1259 ssize_t send_ret;
1260 struct relay_session *session = conn->session;
1261 struct relay_stream *stream = NULL;
1262 struct lttcomm_relayd_status_stream reply;
1263 struct ctf_trace *trace = NULL;
1264 uint64_t stream_handle = -1ULL;
1265 char *path_name = NULL, *channel_name = NULL;
1266 uint64_t tracefile_size = 0, tracefile_count = 0;
1267 LTTNG_OPTIONAL(uint64_t) stream_chunk_id = {};
1268
1269 if (!session || !conn->version_check_done) {
1270 ERR("Trying to add a stream before version check");
1271 ret = -1;
1272 goto end_no_session;
1273 }
1274
1275 if (session->minor == 1) {
1276 /* For 2.1 */
1277 ret = cmd_recv_stream_2_1(payload, &path_name,
1278 &channel_name);
1279 } else if (session->minor > 1 && session->minor < 11) {
1280 /* From 2.2 to 2.10 */
1281 ret = cmd_recv_stream_2_2(payload, &path_name,
1282 &channel_name, &tracefile_size, &tracefile_count);
1283 } else {
1284 /* From 2.11 to ... */
1285 ret = cmd_recv_stream_2_11(payload, &path_name,
1286 &channel_name, &tracefile_size, &tracefile_count,
1287 &stream_chunk_id.value);
1288 stream_chunk_id.is_set = true;
1289 }
1290
1291 if (ret < 0) {
1292 goto send_reply;
1293 }
1294
1295 if (conform_channel_path(path_name)) {
1296 goto send_reply;
1297 }
1298
1299 trace = ctf_trace_get_by_path_or_create(session, path_name);
1300 if (!trace) {
1301 goto send_reply;
1302 }
1303 /* This stream here has one reference on the trace. */
1304
1305 pthread_mutex_lock(&last_relay_stream_id_lock);
1306 stream_handle = ++last_relay_stream_id;
1307 pthread_mutex_unlock(&last_relay_stream_id_lock);
1308
1309 /* We pass ownership of path_name and channel_name. */
1310 stream = stream_create(trace, stream_handle, path_name,
1311 channel_name, tracefile_size, tracefile_count);
1312 path_name = NULL;
1313 channel_name = NULL;
1314
1315 /*
1316 * Streams are the owners of their trace. Reference to trace is
1317 * kept within stream_create().
1318 */
1319 ctf_trace_put(trace);
1320
1321 send_reply:
1322 memset(&reply, 0, sizeof(reply));
1323 reply.handle = htobe64(stream_handle);
1324 if (!stream) {
1325 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1326 } else {
1327 reply.ret_code = htobe32(LTTNG_OK);
1328 }
1329
1330 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1331 sizeof(struct lttcomm_relayd_status_stream), 0);
1332 if (send_ret < (ssize_t) sizeof(reply)) {
1333 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1334 send_ret);
1335 ret = -1;
1336 }
1337
1338 end_no_session:
1339 free(path_name);
1340 free(channel_name);
1341 return ret;
1342 }
1343
1344 /*
1345 * relay_close_stream: close a specific stream
1346 */
1347 static int relay_close_stream(const struct lttcomm_relayd_hdr *recv_hdr,
1348 struct relay_connection *conn,
1349 const struct lttng_buffer_view *payload)
1350 {
1351 int ret;
1352 ssize_t send_ret;
1353 struct relay_session *session = conn->session;
1354 struct lttcomm_relayd_close_stream stream_info;
1355 struct lttcomm_relayd_generic_reply reply;
1356 struct relay_stream *stream;
1357
1358 DBG("Close stream received");
1359
1360 if (!session || !conn->version_check_done) {
1361 ERR("Trying to close a stream before version check");
1362 ret = -1;
1363 goto end_no_session;
1364 }
1365
1366 if (payload->size < sizeof(stream_info)) {
1367 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1368 sizeof(stream_info), payload->size);
1369 ret = -1;
1370 goto end_no_session;
1371 }
1372 memcpy(&stream_info, payload->data, sizeof(stream_info));
1373 stream_info.stream_id = be64toh(stream_info.stream_id);
1374 stream_info.last_net_seq_num = be64toh(stream_info.last_net_seq_num);
1375
1376 stream = stream_get_by_id(stream_info.stream_id);
1377 if (!stream) {
1378 ret = -1;
1379 goto end;
1380 }
1381
1382 /*
1383 * Set last_net_seq_num before the close flag. Required by data
1384 * pending check.
1385 */
1386 pthread_mutex_lock(&stream->lock);
1387 stream->last_net_seq_num = stream_info.last_net_seq_num;
1388 pthread_mutex_unlock(&stream->lock);
1389
1390 /*
1391 * This is one of the conditions which may trigger a stream close
1392 * with the others being:
1393 * 1) A close command is received for a stream
1394 * 2) The control connection owning the stream is closed
1395 * 3) We have received all of the stream's data _after_ a close
1396 * request.
1397 */
1398 try_stream_close(stream);
1399 if (stream->is_metadata) {
1400 struct relay_viewer_stream *vstream;
1401
1402 vstream = viewer_stream_get_by_id(stream->stream_handle);
1403 if (vstream) {
1404 if (vstream->metadata_sent == stream->metadata_received) {
1405 /*
1406 * Since all the metadata has been sent to the
1407 * viewer and that we have a request to close
1408 * its stream, we can safely teardown the
1409 * corresponding metadata viewer stream.
1410 */
1411 viewer_stream_put(vstream);
1412 }
1413 /* Put local reference. */
1414 viewer_stream_put(vstream);
1415 }
1416 }
1417 stream_put(stream);
1418 ret = 0;
1419
1420 end:
1421 memset(&reply, 0, sizeof(reply));
1422 if (ret < 0) {
1423 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1424 } else {
1425 reply.ret_code = htobe32(LTTNG_OK);
1426 }
1427 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1428 sizeof(struct lttcomm_relayd_generic_reply), 0);
1429 if (send_ret < (ssize_t) sizeof(reply)) {
1430 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1431 send_ret);
1432 ret = -1;
1433 }
1434
1435 end_no_session:
1436 return ret;
1437 }
1438
1439 /*
1440 * relay_reset_metadata: reset a metadata stream
1441 */
1442 static
1443 int relay_reset_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1444 struct relay_connection *conn,
1445 const struct lttng_buffer_view *payload)
1446 {
1447 int ret;
1448 ssize_t send_ret;
1449 struct relay_session *session = conn->session;
1450 struct lttcomm_relayd_reset_metadata stream_info;
1451 struct lttcomm_relayd_generic_reply reply;
1452 struct relay_stream *stream;
1453
1454 DBG("Reset metadata received");
1455
1456 if (!session || !conn->version_check_done) {
1457 ERR("Trying to reset a metadata stream before version check");
1458 ret = -1;
1459 goto end_no_session;
1460 }
1461
1462 if (payload->size < sizeof(stream_info)) {
1463 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1464 sizeof(stream_info), payload->size);
1465 ret = -1;
1466 goto end_no_session;
1467 }
1468 memcpy(&stream_info, payload->data, sizeof(stream_info));
1469 stream_info.stream_id = be64toh(stream_info.stream_id);
1470 stream_info.version = be64toh(stream_info.version);
1471
1472 DBG("Update metadata to version %" PRIu64, stream_info.version);
1473
1474 /* Unsupported for live sessions for now. */
1475 if (session->live_timer != 0) {
1476 ret = -1;
1477 goto end;
1478 }
1479
1480 stream = stream_get_by_id(stream_info.stream_id);
1481 if (!stream) {
1482 ret = -1;
1483 goto end;
1484 }
1485 pthread_mutex_lock(&stream->lock);
1486 if (!stream->is_metadata) {
1487 ret = -1;
1488 goto end_unlock;
1489 }
1490
1491 ret = stream_reset_file(stream);
1492 if (ret < 0) {
1493 ERR("Failed to reset metadata stream %" PRIu64
1494 ": stream_path = %s, channel = %s",
1495 stream->stream_handle, stream->path_name,
1496 stream->channel_name);
1497 goto end_unlock;
1498 }
1499 end_unlock:
1500 pthread_mutex_unlock(&stream->lock);
1501 stream_put(stream);
1502
1503 end:
1504 memset(&reply, 0, sizeof(reply));
1505 if (ret < 0) {
1506 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1507 } else {
1508 reply.ret_code = htobe32(LTTNG_OK);
1509 }
1510 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1511 sizeof(struct lttcomm_relayd_generic_reply), 0);
1512 if (send_ret < (ssize_t) sizeof(reply)) {
1513 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1514 send_ret);
1515 ret = -1;
1516 }
1517
1518 end_no_session:
1519 return ret;
1520 }
1521
1522 /*
1523 * relay_unknown_command: send -1 if received unknown command
1524 */
1525 static void relay_unknown_command(struct relay_connection *conn)
1526 {
1527 struct lttcomm_relayd_generic_reply reply;
1528 ssize_t send_ret;
1529
1530 memset(&reply, 0, sizeof(reply));
1531 reply.ret_code = htobe32(LTTNG_ERR_UNK);
1532 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1533 if (send_ret < sizeof(reply)) {
1534 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret);
1535 }
1536 }
1537
1538 /*
1539 * relay_start: send an acknowledgment to the client to tell if we are
1540 * ready to receive data. We are ready if a session is established.
1541 */
1542 static int relay_start(const struct lttcomm_relayd_hdr *recv_hdr,
1543 struct relay_connection *conn,
1544 const struct lttng_buffer_view *payload)
1545 {
1546 int ret = 0;
1547 ssize_t send_ret;
1548 struct lttcomm_relayd_generic_reply reply;
1549 struct relay_session *session = conn->session;
1550
1551 if (!session) {
1552 DBG("Trying to start the streaming without a session established");
1553 ret = htobe32(LTTNG_ERR_UNK);
1554 }
1555
1556 memset(&reply, 0, sizeof(reply));
1557 reply.ret_code = htobe32(LTTNG_OK);
1558 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1559 sizeof(reply), 0);
1560 if (send_ret < (ssize_t) sizeof(reply)) {
1561 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1562 send_ret);
1563 ret = -1;
1564 }
1565
1566 return ret;
1567 }
1568
1569 /*
1570 * relay_recv_metadata: receive the metadata for the session.
1571 */
1572 static int relay_recv_metadata(const struct lttcomm_relayd_hdr *recv_hdr,
1573 struct relay_connection *conn,
1574 const struct lttng_buffer_view *payload)
1575 {
1576 int ret = 0;
1577 struct relay_session *session = conn->session;
1578 struct lttcomm_relayd_metadata_payload metadata_payload_header;
1579 struct relay_stream *metadata_stream;
1580 uint64_t metadata_payload_size;
1581 struct lttng_buffer_view packet_view;
1582
1583 if (!session) {
1584 ERR("Metadata sent before version check");
1585 ret = -1;
1586 goto end;
1587 }
1588
1589 if (recv_hdr->data_size < sizeof(struct lttcomm_relayd_metadata_payload)) {
1590 ERR("Incorrect data size");
1591 ret = -1;
1592 goto end;
1593 }
1594 metadata_payload_size = recv_hdr->data_size -
1595 sizeof(struct lttcomm_relayd_metadata_payload);
1596
1597 memcpy(&metadata_payload_header, payload->data,
1598 sizeof(metadata_payload_header));
1599 metadata_payload_header.stream_id = be64toh(
1600 metadata_payload_header.stream_id);
1601 metadata_payload_header.padding_size = be32toh(
1602 metadata_payload_header.padding_size);
1603
1604 metadata_stream = stream_get_by_id(metadata_payload_header.stream_id);
1605 if (!metadata_stream) {
1606 ret = -1;
1607 goto end;
1608 }
1609
1610 packet_view = lttng_buffer_view_from_view(payload,
1611 sizeof(metadata_payload_header), metadata_payload_size);
1612 if (!packet_view.data) {
1613 ERR("Invalid metadata packet length announced by header");
1614 ret = -1;
1615 goto end_put;
1616 }
1617
1618 pthread_mutex_lock(&metadata_stream->lock);
1619 ret = stream_write(metadata_stream, &packet_view,
1620 metadata_payload_header.padding_size);
1621 pthread_mutex_unlock(&metadata_stream->lock);
1622 if (ret){
1623 ret = -1;
1624 goto end_put;
1625 }
1626 end_put:
1627 stream_put(metadata_stream);
1628 end:
1629 return ret;
1630 }
1631
1632 /*
1633 * relay_send_version: send relayd version number
1634 */
1635 static int relay_send_version(const struct lttcomm_relayd_hdr *recv_hdr,
1636 struct relay_connection *conn,
1637 const struct lttng_buffer_view *payload)
1638 {
1639 int ret;
1640 ssize_t send_ret;
1641 struct lttcomm_relayd_version reply, msg;
1642 bool compatible = true;
1643
1644 conn->version_check_done = true;
1645
1646 /* Get version from the other side. */
1647 if (payload->size < sizeof(msg)) {
1648 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1649 sizeof(msg), payload->size);
1650 ret = -1;
1651 goto end;
1652 }
1653
1654 memcpy(&msg, payload->data, sizeof(msg));
1655 msg.major = be32toh(msg.major);
1656 msg.minor = be32toh(msg.minor);
1657
1658 memset(&reply, 0, sizeof(reply));
1659 reply.major = RELAYD_VERSION_COMM_MAJOR;
1660 reply.minor = RELAYD_VERSION_COMM_MINOR;
1661
1662 /* Major versions must be the same */
1663 if (reply.major != msg.major) {
1664 DBG("Incompatible major versions (%u vs %u), deleting session",
1665 reply.major, msg.major);
1666 compatible = false;
1667 }
1668
1669 conn->major = reply.major;
1670 /* We adapt to the lowest compatible version */
1671 if (reply.minor <= msg.minor) {
1672 conn->minor = reply.minor;
1673 } else {
1674 conn->minor = msg.minor;
1675 }
1676
1677 reply.major = htobe32(reply.major);
1678 reply.minor = htobe32(reply.minor);
1679 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
1680 sizeof(reply), 0);
1681 if (send_ret < (ssize_t) sizeof(reply)) {
1682 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1683 send_ret);
1684 ret = -1;
1685 goto end;
1686 } else {
1687 ret = 0;
1688 }
1689
1690 if (!compatible) {
1691 ret = -1;
1692 goto end;
1693 }
1694
1695 DBG("Version check done using protocol %u.%u", conn->major,
1696 conn->minor);
1697
1698 end:
1699 return ret;
1700 }
1701
1702 /*
1703 * Check for data pending for a given stream id from the session daemon.
1704 */
1705 static int relay_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1706 struct relay_connection *conn,
1707 const struct lttng_buffer_view *payload)
1708 {
1709 struct relay_session *session = conn->session;
1710 struct lttcomm_relayd_data_pending msg;
1711 struct lttcomm_relayd_generic_reply reply;
1712 struct relay_stream *stream;
1713 ssize_t send_ret;
1714 int ret;
1715 uint64_t stream_seq;
1716
1717 DBG("Data pending command received");
1718
1719 if (!session || !conn->version_check_done) {
1720 ERR("Trying to check for data before version check");
1721 ret = -1;
1722 goto end_no_session;
1723 }
1724
1725 if (payload->size < sizeof(msg)) {
1726 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1727 sizeof(msg), payload->size);
1728 ret = -1;
1729 goto end_no_session;
1730 }
1731 memcpy(&msg, payload->data, sizeof(msg));
1732 msg.stream_id = be64toh(msg.stream_id);
1733 msg.last_net_seq_num = be64toh(msg.last_net_seq_num);
1734
1735 stream = stream_get_by_id(msg.stream_id);
1736 if (stream == NULL) {
1737 ret = -1;
1738 goto end;
1739 }
1740
1741 pthread_mutex_lock(&stream->lock);
1742
1743 if (session_streams_have_index(session)) {
1744 /*
1745 * Ensure that both the index and stream data have been
1746 * flushed up to the requested point.
1747 */
1748 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
1749 } else {
1750 stream_seq = stream->prev_data_seq;
1751 }
1752 DBG("Data pending for stream id %" PRIu64 ": prev_data_seq %" PRIu64
1753 ", prev_index_seq %" PRIu64
1754 ", and last_seq %" PRIu64, msg.stream_id,
1755 stream->prev_data_seq, stream->prev_index_seq,
1756 msg.last_net_seq_num);
1757
1758 /* Avoid wrapping issue */
1759 if (((int64_t) (stream_seq - msg.last_net_seq_num)) >= 0) {
1760 /* Data has in fact been written and is NOT pending */
1761 ret = 0;
1762 } else {
1763 /* Data still being streamed thus pending */
1764 ret = 1;
1765 }
1766
1767 stream->data_pending_check_done = true;
1768 pthread_mutex_unlock(&stream->lock);
1769
1770 stream_put(stream);
1771 end:
1772
1773 memset(&reply, 0, sizeof(reply));
1774 reply.ret_code = htobe32(ret);
1775 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1776 if (send_ret < (ssize_t) sizeof(reply)) {
1777 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1778 send_ret);
1779 ret = -1;
1780 }
1781
1782 end_no_session:
1783 return ret;
1784 }
1785
1786 /*
1787 * Wait for the control socket to reach a quiescent state.
1788 *
1789 * Note that for now, when receiving this command from the session
1790 * daemon, this means that every subsequent commands or data received on
1791 * the control socket has been handled. So, this is why we simply return
1792 * OK here.
1793 */
1794 static int relay_quiescent_control(const struct lttcomm_relayd_hdr *recv_hdr,
1795 struct relay_connection *conn,
1796 const struct lttng_buffer_view *payload)
1797 {
1798 int ret;
1799 ssize_t send_ret;
1800 struct relay_stream *stream;
1801 struct lttcomm_relayd_quiescent_control msg;
1802 struct lttcomm_relayd_generic_reply reply;
1803
1804 DBG("Checking quiescent state on control socket");
1805
1806 if (!conn->session || !conn->version_check_done) {
1807 ERR("Trying to check for data before version check");
1808 ret = -1;
1809 goto end_no_session;
1810 }
1811
1812 if (payload->size < sizeof(msg)) {
1813 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1814 sizeof(msg), payload->size);
1815 ret = -1;
1816 goto end_no_session;
1817 }
1818 memcpy(&msg, payload->data, sizeof(msg));
1819 msg.stream_id = be64toh(msg.stream_id);
1820
1821 stream = stream_get_by_id(msg.stream_id);
1822 if (!stream) {
1823 goto reply;
1824 }
1825 pthread_mutex_lock(&stream->lock);
1826 stream->data_pending_check_done = true;
1827 pthread_mutex_unlock(&stream->lock);
1828
1829 DBG("Relay quiescent control pending flag set to %" PRIu64, msg.stream_id);
1830 stream_put(stream);
1831 reply:
1832 memset(&reply, 0, sizeof(reply));
1833 reply.ret_code = htobe32(LTTNG_OK);
1834 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1835 if (send_ret < (ssize_t) sizeof(reply)) {
1836 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1837 send_ret);
1838 ret = -1;
1839 } else {
1840 ret = 0;
1841 }
1842
1843 end_no_session:
1844 return ret;
1845 }
1846
1847 /*
1848 * Initialize a data pending command. This means that a consumer is about
1849 * to ask for data pending for each stream it holds. Simply iterate over
1850 * all streams of a session and set the data_pending_check_done flag.
1851 *
1852 * This command returns to the client a LTTNG_OK code.
1853 */
1854 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1855 struct relay_connection *conn,
1856 const struct lttng_buffer_view *payload)
1857 {
1858 int ret;
1859 ssize_t send_ret;
1860 struct lttng_ht_iter iter;
1861 struct lttcomm_relayd_begin_data_pending msg;
1862 struct lttcomm_relayd_generic_reply reply;
1863 struct relay_stream *stream;
1864
1865 assert(recv_hdr);
1866 assert(conn);
1867
1868 DBG("Init streams for data pending");
1869
1870 if (!conn->session || !conn->version_check_done) {
1871 ERR("Trying to check for data before version check");
1872 ret = -1;
1873 goto end_no_session;
1874 }
1875
1876 if (payload->size < sizeof(msg)) {
1877 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1878 sizeof(msg), payload->size);
1879 ret = -1;
1880 goto end_no_session;
1881 }
1882 memcpy(&msg, payload->data, sizeof(msg));
1883 msg.session_id = be64toh(msg.session_id);
1884
1885 /*
1886 * Iterate over all streams to set the begin data pending flag.
1887 * For now, the streams are indexed by stream handle so we have
1888 * to iterate over all streams to find the one associated with
1889 * the right session_id.
1890 */
1891 rcu_read_lock();
1892 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1893 node.node) {
1894 if (!stream_get(stream)) {
1895 continue;
1896 }
1897 if (stream->trace->session->id == msg.session_id) {
1898 pthread_mutex_lock(&stream->lock);
1899 stream->data_pending_check_done = false;
1900 pthread_mutex_unlock(&stream->lock);
1901 DBG("Set begin data pending flag to stream %" PRIu64,
1902 stream->stream_handle);
1903 }
1904 stream_put(stream);
1905 }
1906 rcu_read_unlock();
1907
1908 memset(&reply, 0, sizeof(reply));
1909 /* All good, send back reply. */
1910 reply.ret_code = htobe32(LTTNG_OK);
1911
1912 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
1913 if (send_ret < (ssize_t) sizeof(reply)) {
1914 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1915 send_ret);
1916 ret = -1;
1917 } else {
1918 ret = 0;
1919 }
1920
1921 end_no_session:
1922 return ret;
1923 }
1924
1925 /*
1926 * End data pending command. This will check, for a given session id, if
1927 * each stream associated with it has its data_pending_check_done flag
1928 * set. If not, this means that the client lost track of the stream but
1929 * the data is still being streamed on our side. In this case, we inform
1930 * the client that data is in flight.
1931 *
1932 * Return to the client if there is data in flight or not with a ret_code.
1933 */
1934 static int relay_end_data_pending(const struct lttcomm_relayd_hdr *recv_hdr,
1935 struct relay_connection *conn,
1936 const struct lttng_buffer_view *payload)
1937 {
1938 int ret;
1939 ssize_t send_ret;
1940 struct lttng_ht_iter iter;
1941 struct lttcomm_relayd_end_data_pending msg;
1942 struct lttcomm_relayd_generic_reply reply;
1943 struct relay_stream *stream;
1944 uint32_t is_data_inflight = 0;
1945
1946 DBG("End data pending command");
1947
1948 if (!conn->session || !conn->version_check_done) {
1949 ERR("Trying to check for data before version check");
1950 ret = -1;
1951 goto end_no_session;
1952 }
1953
1954 if (payload->size < sizeof(msg)) {
1955 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1956 sizeof(msg), payload->size);
1957 ret = -1;
1958 goto end_no_session;
1959 }
1960 memcpy(&msg, payload->data, sizeof(msg));
1961 msg.session_id = be64toh(msg.session_id);
1962
1963 /*
1964 * Iterate over all streams to see if the begin data pending
1965 * flag is set.
1966 */
1967 rcu_read_lock();
1968 cds_lfht_for_each_entry(relay_streams_ht->ht, &iter.iter, stream,
1969 node.node) {
1970 if (!stream_get(stream)) {
1971 continue;
1972 }
1973 if (stream->trace->session->id != msg.session_id) {
1974 stream_put(stream);
1975 continue;
1976 }
1977 pthread_mutex_lock(&stream->lock);
1978 if (!stream->data_pending_check_done) {
1979 uint64_t stream_seq;
1980
1981 if (session_streams_have_index(conn->session)) {
1982 /*
1983 * Ensure that both the index and stream data have been
1984 * flushed up to the requested point.
1985 */
1986 stream_seq = min(stream->prev_data_seq, stream->prev_index_seq);
1987 } else {
1988 stream_seq = stream->prev_data_seq;
1989 }
1990 if (!stream->closed || !(((int64_t) (stream_seq - stream->last_net_seq_num)) >= 0)) {
1991 is_data_inflight = 1;
1992 DBG("Data is still in flight for stream %" PRIu64,
1993 stream->stream_handle);
1994 pthread_mutex_unlock(&stream->lock);
1995 stream_put(stream);
1996 break;
1997 }
1998 }
1999 pthread_mutex_unlock(&stream->lock);
2000 stream_put(stream);
2001 }
2002 rcu_read_unlock();
2003
2004 memset(&reply, 0, sizeof(reply));
2005 /* All good, send back reply. */
2006 reply.ret_code = htobe32(is_data_inflight);
2007
2008 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2009 if (send_ret < (ssize_t) sizeof(reply)) {
2010 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2011 send_ret);
2012 ret = -1;
2013 } else {
2014 ret = 0;
2015 }
2016
2017 end_no_session:
2018 return ret;
2019 }
2020
2021 /*
2022 * Receive an index for a specific stream.
2023 *
2024 * Return 0 on success else a negative value.
2025 */
2026 static int relay_recv_index(const struct lttcomm_relayd_hdr *recv_hdr,
2027 struct relay_connection *conn,
2028 const struct lttng_buffer_view *payload)
2029 {
2030 int ret;
2031 ssize_t send_ret;
2032 struct relay_session *session = conn->session;
2033 struct lttcomm_relayd_index index_info;
2034 struct lttcomm_relayd_generic_reply reply;
2035 struct relay_stream *stream;
2036 size_t msg_len;
2037
2038 assert(conn);
2039
2040 DBG("Relay receiving index");
2041
2042 if (!session || !conn->version_check_done) {
2043 ERR("Trying to close a stream before version check");
2044 ret = -1;
2045 goto end_no_session;
2046 }
2047
2048 msg_len = lttcomm_relayd_index_len(
2049 lttng_to_index_major(conn->major, conn->minor),
2050 lttng_to_index_minor(conn->major, conn->minor));
2051 if (payload->size < msg_len) {
2052 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2053 msg_len, payload->size);
2054 ret = -1;
2055 goto end_no_session;
2056 }
2057 memcpy(&index_info, payload->data, msg_len);
2058 index_info.relay_stream_id = be64toh(index_info.relay_stream_id);
2059 index_info.net_seq_num = be64toh(index_info.net_seq_num);
2060 index_info.packet_size = be64toh(index_info.packet_size);
2061 index_info.content_size = be64toh(index_info.content_size);
2062 index_info.timestamp_begin = be64toh(index_info.timestamp_begin);
2063 index_info.timestamp_end = be64toh(index_info.timestamp_end);
2064 index_info.events_discarded = be64toh(index_info.events_discarded);
2065 index_info.stream_id = be64toh(index_info.stream_id);
2066
2067 if (conn->minor >= 8) {
2068 index_info.stream_instance_id =
2069 be64toh(index_info.stream_instance_id);
2070 index_info.packet_seq_num = be64toh(index_info.packet_seq_num);
2071 }
2072
2073 stream = stream_get_by_id(index_info.relay_stream_id);
2074 if (!stream) {
2075 ERR("stream_get_by_id not found");
2076 ret = -1;
2077 goto end;
2078 }
2079
2080 pthread_mutex_lock(&stream->lock);
2081 ret = stream_add_index(stream, &index_info);
2082 pthread_mutex_unlock(&stream->lock);
2083 if (ret) {
2084 goto end_stream_put;
2085 }
2086
2087 end_stream_put:
2088 stream_put(stream);
2089 end:
2090 memset(&reply, 0, sizeof(reply));
2091 if (ret < 0) {
2092 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2093 } else {
2094 reply.ret_code = htobe32(LTTNG_OK);
2095 }
2096 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2097 if (send_ret < (ssize_t) sizeof(reply)) {
2098 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret);
2099 ret = -1;
2100 }
2101
2102 end_no_session:
2103 return ret;
2104 }
2105
2106 /*
2107 * Receive the streams_sent message.
2108 *
2109 * Return 0 on success else a negative value.
2110 */
2111 static int relay_streams_sent(const struct lttcomm_relayd_hdr *recv_hdr,
2112 struct relay_connection *conn,
2113 const struct lttng_buffer_view *payload)
2114 {
2115 int ret;
2116 ssize_t send_ret;
2117 struct lttcomm_relayd_generic_reply reply;
2118
2119 assert(conn);
2120
2121 DBG("Relay receiving streams_sent");
2122
2123 if (!conn->session || !conn->version_check_done) {
2124 ERR("Trying to close a stream before version check");
2125 ret = -1;
2126 goto end_no_session;
2127 }
2128
2129 /*
2130 * Publish every pending stream in the connection recv list which are
2131 * now ready to be used by the viewer.
2132 */
2133 publish_connection_local_streams(conn);
2134
2135 memset(&reply, 0, sizeof(reply));
2136 reply.ret_code = htobe32(LTTNG_OK);
2137 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply, sizeof(reply), 0);
2138 if (send_ret < (ssize_t) sizeof(reply)) {
2139 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2140 send_ret);
2141 ret = -1;
2142 } else {
2143 /* Success. */
2144 ret = 0;
2145 }
2146
2147 end_no_session:
2148 return ret;
2149 }
2150
2151 /*
2152 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2153 * session rotation feature (not the tracefile rotation feature).
2154 */
2155 static int relay_rotate_session_streams(
2156 const struct lttcomm_relayd_hdr *recv_hdr,
2157 struct relay_connection *conn,
2158 const struct lttng_buffer_view *payload)
2159 {
2160 int ret = 0;
2161 uint32_t i;
2162 ssize_t send_ret;
2163 enum lttng_error_code reply_code = LTTNG_ERR_UNK;
2164 struct relay_session *session = conn->session;
2165 struct lttcomm_relayd_rotate_streams rotate_streams;
2166 struct lttcomm_relayd_generic_reply reply = {};
2167 struct relay_stream *stream = NULL;
2168 const size_t header_len = sizeof(struct lttcomm_relayd_rotate_streams);
2169 struct lttng_trace_chunk *next_trace_chunk = NULL;
2170 struct lttng_buffer_view stream_positions;
2171 char chunk_id_buf[MAX_INT_DEC_LEN(uint64_t)];
2172 const char *chunk_id_str = "none";
2173
2174 if (!session || !conn->version_check_done) {
2175 ERR("Trying to rotate a stream before version check");
2176 ret = -1;
2177 goto end_no_reply;
2178 }
2179
2180 if (session->major == 2 && session->minor < 11) {
2181 ERR("Unsupported feature before 2.11");
2182 ret = -1;
2183 goto end_no_reply;
2184 }
2185
2186 if (payload->size < header_len) {
2187 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2188 header_len, payload->size);
2189 ret = -1;
2190 goto end_no_reply;
2191 }
2192
2193 memcpy(&rotate_streams, payload->data, header_len);
2194
2195 /* Convert header to host endianness. */
2196 rotate_streams = (typeof(rotate_streams)) {
2197 .stream_count = be32toh(rotate_streams.stream_count),
2198 .new_chunk_id = (typeof(rotate_streams.new_chunk_id)) {
2199 .is_set = !!rotate_streams.new_chunk_id.is_set,
2200 .value = be64toh(rotate_streams.new_chunk_id.value),
2201 }
2202 };
2203
2204 if (rotate_streams.new_chunk_id.is_set) {
2205 /*
2206 * Retrieve the trace chunk the stream must transition to. As
2207 * per the protocol, this chunk should have been created
2208 * before this command is received.
2209 */
2210 next_trace_chunk = sessiond_trace_chunk_registry_get_chunk(
2211 sessiond_trace_chunk_registry,
2212 session->sessiond_uuid, session->id,
2213 rotate_streams.new_chunk_id.value);
2214 if (!next_trace_chunk) {
2215 char uuid_str[UUID_STR_LEN];
2216
2217 lttng_uuid_to_str(session->sessiond_uuid, uuid_str);
2218 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2219 ", trace_chunk_id = %" PRIu64,
2220 uuid_str, session->id,
2221 rotate_streams.new_chunk_id.value);
2222 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2223 ret = -1;
2224 goto end;
2225 }
2226
2227 ret = snprintf(chunk_id_buf, sizeof(chunk_id_buf), "%" PRIu64,
2228 rotate_streams.new_chunk_id.value);
2229 if (ret < 0 || ret >= sizeof(chunk_id_buf)) {
2230 chunk_id_str = "formatting error";
2231 } else {
2232 chunk_id_str = chunk_id_buf;
2233 }
2234 session->has_rotated = true;
2235 }
2236
2237 DBG("Rotate %" PRIu32 " streams of session \"%s\" to chunk \"%s\"",
2238 rotate_streams.stream_count, session->session_name,
2239 chunk_id_str);
2240
2241 stream_positions = lttng_buffer_view_from_view(payload,
2242 sizeof(rotate_streams), -1);
2243 if (!stream_positions.data ||
2244 stream_positions.size <
2245 (rotate_streams.stream_count *
2246 sizeof(struct lttcomm_relayd_stream_rotation_position))) {
2247 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2248 ret = -1;
2249 goto end;
2250 }
2251
2252 for (i = 0; i < rotate_streams.stream_count; i++) {
2253 struct lttcomm_relayd_stream_rotation_position *position_comm =
2254 &((typeof(position_comm)) stream_positions.data)[i];
2255 const struct lttcomm_relayd_stream_rotation_position pos = {
2256 .stream_id = be64toh(position_comm->stream_id),
2257 .rotate_at_seq_num = be64toh(
2258 position_comm->rotate_at_seq_num),
2259 };
2260
2261 stream = stream_get_by_id(pos.stream_id);
2262 if (!stream) {
2263 reply_code = LTTNG_ERR_INVALID;
2264 ret = -1;
2265 goto end;
2266 }
2267
2268 pthread_mutex_lock(&stream->lock);
2269 ret = stream_set_pending_rotation(stream, next_trace_chunk,
2270 pos.rotate_at_seq_num);
2271 pthread_mutex_unlock(&stream->lock);
2272 if (ret) {
2273 reply_code = LTTNG_ERR_FILE_CREATION_ERROR;
2274 goto end;
2275 }
2276
2277 stream_put(stream);
2278 stream = NULL;
2279 }
2280
2281 reply_code = LTTNG_OK;
2282 end:
2283 if (stream) {
2284 stream_put(stream);
2285 }
2286
2287 reply.ret_code = htobe32((uint32_t) reply_code);
2288 send_ret = conn->sock->ops->sendmsg(conn->sock, &reply,
2289 sizeof(struct lttcomm_relayd_generic_reply), 0);
2290 if (send_ret < (ssize_t) sizeof(reply)) {
2291 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2292 send_ret);
2293 ret = -1;
2294 }
2295
2296 ret = 0;
2297 end_no_reply:
2298 lttng_trace_chunk_put(next_trace_chunk);
2299 return ret;
2300 }
2301
2302
2303
2304 /*
2305 * relay_create_trace_chunk: create a new trace chunk
2306 */
2307 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2308 struct relay_connection *conn,
2309 const struct lttng_buffer_view *payload)
2310 {
2311 int ret = 0;
2312 ssize_t send_ret;
2313 struct relay_session *session = conn->session;
2314 struct lttcomm_relayd_create_trace_chunk *msg;
2315 struct lttcomm_relayd_generic_reply reply = {};
2316 struct lttng_buffer_view header_view;
2317 struct lttng_buffer_view chunk_name_view;
2318 struct lttng_trace_chunk *chunk = NULL, *published_chunk = NULL;
2319 enum lttng_error_code reply_code = LTTNG_OK;
2320 enum lttng_trace_chunk_status chunk_status;
2321 struct lttng_directory_handle session_output;
2322
2323 if (!session || !conn->version_check_done) {
2324 ERR("Trying to create a trace chunk before version check");
2325 ret = -1;
2326 goto end_no_reply;
2327 }
2328
2329 if (session->major == 2 && session->minor < 11) {
2330 ERR("Chunk creation command is unsupported before 2.11");
2331 ret = -1;
2332 goto end_no_reply;
2333 }
2334
2335 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2336 if (!header_view.data) {
2337 ERR("Failed to receive payload of chunk creation command");
2338 ret = -1;
2339 goto end_no_reply;
2340 }
2341
2342 /* Convert to host endianness. */
2343 msg = (typeof(msg)) header_view.data;
2344 msg->chunk_id = be64toh(msg->chunk_id);
2345 msg->creation_timestamp = be64toh(msg->creation_timestamp);
2346 msg->override_name_length = be32toh(msg->override_name_length);
2347
2348 chunk = lttng_trace_chunk_create(
2349 msg->chunk_id, msg->creation_timestamp);
2350 if (!chunk) {
2351 ERR("Failed to create trace chunk in trace chunk creation command");
2352 ret = -1;
2353 reply_code = LTTNG_ERR_NOMEM;
2354 goto end;
2355 }
2356
2357 if (msg->override_name_length) {
2358 const char *name;
2359
2360 chunk_name_view = lttng_buffer_view_from_view(payload,
2361 sizeof(*msg),
2362 msg->override_name_length);
2363 name = chunk_name_view.data;
2364 if (!name || name[msg->override_name_length - 1]) {
2365 ERR("Failed to receive payload of chunk creation command");
2366 ret = -1;
2367 reply_code = LTTNG_ERR_INVALID;
2368 goto end;
2369 }
2370
2371 chunk_status = lttng_trace_chunk_override_name(
2372 chunk, chunk_name_view.data);
2373 switch (chunk_status) {
2374 case LTTNG_TRACE_CHUNK_STATUS_OK:
2375 break;
2376 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT:
2377 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2378 reply_code = LTTNG_ERR_INVALID;
2379 ret = -1;
2380 goto end;
2381 default:
2382 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2383 reply_code = LTTNG_ERR_UNK;
2384 ret = -1;
2385 goto end;
2386 }
2387 }
2388
2389 chunk_status = lttng_trace_chunk_set_credentials_current_user(chunk);
2390 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2391 reply_code = LTTNG_ERR_UNK;
2392 ret = -1;
2393 goto end;
2394 }
2395
2396 ret = session_init_output_directory_handle(
2397 conn->session, &session_output);
2398 if (ret) {
2399 reply_code = LTTNG_ERR_CREATE_DIR_FAIL;
2400 goto end;
2401 }
2402 chunk_status = lttng_trace_chunk_set_as_owner(chunk, &session_output);
2403 lttng_directory_handle_fini(&session_output);
2404 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2405 reply_code = LTTNG_ERR_UNK;
2406 ret = -1;
2407 goto end;
2408 }
2409
2410 published_chunk = sessiond_trace_chunk_registry_publish_chunk(
2411 sessiond_trace_chunk_registry,
2412 conn->session->sessiond_uuid,
2413 conn->session->id,
2414 chunk);
2415 if (!published_chunk) {
2416 char uuid_str[UUID_STR_LEN];
2417
2418 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2419 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2420 uuid_str,
2421 conn->session->id,
2422 msg->chunk_id);
2423 ret = -1;
2424 reply_code = LTTNG_ERR_NOMEM;
2425 goto end;
2426 }
2427
2428 pthread_mutex_lock(&conn->session->lock);
2429 if (conn->session->pending_closure_trace_chunk) {
2430 /*
2431 * Invalid; this means a second create_trace_chunk command was
2432 * received before a close_trace_chunk.
2433 */
2434 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2435 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2436 ret = -1;
2437 goto end_unlock_session;
2438 }
2439 conn->session->pending_closure_trace_chunk =
2440 conn->session->current_trace_chunk;
2441 conn->session->current_trace_chunk = published_chunk;
2442 published_chunk = NULL;
2443 end_unlock_session:
2444 pthread_mutex_unlock(&conn->session->lock);
2445 end:
2446 reply.ret_code = htobe32((uint32_t) reply_code);
2447 send_ret = conn->sock->ops->sendmsg(conn->sock,
2448 &reply,
2449 sizeof(struct lttcomm_relayd_generic_reply),
2450 0);
2451 if (send_ret < (ssize_t) sizeof(reply)) {
2452 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2453 send_ret);
2454 ret = -1;
2455 }
2456 end_no_reply:
2457 lttng_trace_chunk_put(chunk);
2458 lttng_trace_chunk_put(published_chunk);
2459 return ret;
2460 }
2461
2462 /*
2463 * relay_close_trace_chunk: close a trace chunk
2464 */
2465 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr *recv_hdr,
2466 struct relay_connection *conn,
2467 const struct lttng_buffer_view *payload)
2468 {
2469 int ret = 0;
2470 ssize_t send_ret;
2471 struct relay_session *session = conn->session;
2472 struct lttcomm_relayd_close_trace_chunk *msg;
2473 struct lttcomm_relayd_close_trace_chunk_reply reply = {};
2474 struct lttng_buffer_view header_view;
2475 struct lttng_trace_chunk *chunk = NULL;
2476 enum lttng_error_code reply_code = LTTNG_OK;
2477 enum lttng_trace_chunk_status chunk_status;
2478 uint64_t chunk_id;
2479 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type) close_command = {};
2480 time_t close_timestamp;
2481 char closed_trace_chunk_path[LTTNG_PATH_MAX];
2482 size_t path_length = 0;
2483 const char *chunk_name = NULL;
2484 struct lttng_dynamic_buffer reply_payload;
2485
2486 lttng_dynamic_buffer_init(&reply_payload);
2487
2488 if (!session || !conn->version_check_done) {
2489 ERR("Trying to close a trace chunk before version check");
2490 ret = -1;
2491 goto end_no_reply;
2492 }
2493
2494 if (session->major == 2 && session->minor < 11) {
2495 ERR("Chunk close command is unsupported before 2.11");
2496 ret = -1;
2497 goto end_no_reply;
2498 }
2499
2500 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2501 if (!header_view.data) {
2502 ERR("Failed to receive payload of chunk close command");
2503 ret = -1;
2504 goto end_no_reply;
2505 }
2506
2507 /* Convert to host endianness. */
2508 msg = (typeof(msg)) header_view.data;
2509 chunk_id = be64toh(msg->chunk_id);
2510 close_timestamp = (time_t) be64toh(msg->close_timestamp);
2511 close_command = (typeof(close_command)){
2512 .value = be32toh(msg->close_command.value),
2513 .is_set = msg->close_command.is_set,
2514 };
2515
2516 chunk = sessiond_trace_chunk_registry_get_chunk(
2517 sessiond_trace_chunk_registry,
2518 conn->session->sessiond_uuid,
2519 conn->session->id,
2520 chunk_id);
2521 if (!chunk) {
2522 char uuid_str[UUID_STR_LEN];
2523
2524 lttng_uuid_to_str(conn->session->sessiond_uuid, uuid_str);
2525 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64 ", chunk_id = %" PRIu64,
2526 uuid_str,
2527 conn->session->id,
2528 msg->chunk_id);
2529 ret = -1;
2530 reply_code = LTTNG_ERR_NOMEM;
2531 goto end;
2532 }
2533
2534 pthread_mutex_lock(&session->lock);
2535 if (session->pending_closure_trace_chunk &&
2536 session->pending_closure_trace_chunk != chunk) {
2537 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2538 session->session_name);
2539 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2540 ret = -1;
2541 goto end_unlock_session;
2542 }
2543
2544 chunk_status = lttng_trace_chunk_set_close_timestamp(
2545 chunk, close_timestamp);
2546 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2547 ERR("Failed to set trace chunk close timestamp");
2548 ret = -1;
2549 reply_code = LTTNG_ERR_UNK;
2550 goto end_unlock_session;
2551 }
2552
2553 if (close_command.is_set) {
2554 chunk_status = lttng_trace_chunk_set_close_command(
2555 chunk, close_command.value);
2556 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2557 ret = -1;
2558 reply_code = LTTNG_ERR_INVALID;
2559 goto end_unlock_session;
2560 }
2561 }
2562 chunk_status = lttng_trace_chunk_get_name(chunk, &chunk_name, NULL);
2563 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2564 ERR("Failed to get chunk name");
2565 ret = -1;
2566 reply_code = LTTNG_ERR_UNK;
2567 goto end_unlock_session;
2568 }
2569 if (!session->has_rotated && !session->snapshot) {
2570 ret = lttng_strncpy(closed_trace_chunk_path,
2571 session->output_path,
2572 sizeof(closed_trace_chunk_path));
2573 if (ret) {
2574 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2575 strlen(session->output_path),
2576 sizeof(closed_trace_chunk_path));
2577 reply_code = LTTNG_ERR_NOMEM;
2578 ret = -1;
2579 goto end_unlock_session;
2580 }
2581 } else {
2582 if (session->snapshot) {
2583 ret = snprintf(closed_trace_chunk_path,
2584 sizeof(closed_trace_chunk_path),
2585 "%s/%s", session->output_path,
2586 chunk_name);
2587 } else {
2588 ret = snprintf(closed_trace_chunk_path,
2589 sizeof(closed_trace_chunk_path),
2590 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
2591 "/%s",
2592 session->output_path, chunk_name);
2593 }
2594 if (ret < 0 || ret == sizeof(closed_trace_chunk_path)) {
2595 ERR("Failed to format closed trace chunk resulting path");
2596 reply_code = ret < 0 ? LTTNG_ERR_UNK : LTTNG_ERR_NOMEM;
2597 ret = -1;
2598 goto end_unlock_session;
2599 }
2600 }
2601 DBG("Reply chunk path on close: %s", closed_trace_chunk_path);
2602 path_length = strlen(closed_trace_chunk_path) + 1;
2603 if (path_length > UINT32_MAX) {
2604 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
2605 ret = -1;
2606 reply_code = LTTNG_ERR_INVALID_PROTOCOL;
2607 goto end_unlock_session;
2608 }
2609
2610 if (session->current_trace_chunk == chunk) {
2611 /*
2612 * After a trace chunk close command, no new streams
2613 * referencing the chunk may be created. Hence, on the
2614 * event that no new trace chunk have been created for
2615 * the session, the reference to the current trace chunk
2616 * is released in order to allow it to be reclaimed when
2617 * the last stream releases its reference to it.
2618 */
2619 lttng_trace_chunk_put(session->current_trace_chunk);
2620 session->current_trace_chunk = NULL;
2621 }
2622 lttng_trace_chunk_put(session->pending_closure_trace_chunk);
2623 session->pending_closure_trace_chunk = NULL;
2624 end_unlock_session:
2625 pthread_mutex_unlock(&session->lock);
2626
2627 end:
2628 reply.generic.ret_code = htobe32((uint32_t) reply_code);
2629 reply.path_length = htobe32((uint32_t) path_length);
2630 ret = lttng_dynamic_buffer_append(
2631 &reply_payload, &reply, sizeof(reply));
2632 if (ret) {
2633 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
2634 goto end_no_reply;
2635 }
2636
2637 if (reply_code == LTTNG_OK) {
2638 ret = lttng_dynamic_buffer_append(&reply_payload,
2639 closed_trace_chunk_path, path_length);
2640 if (ret) {
2641 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
2642 goto end_no_reply;
2643 }
2644 }
2645
2646 send_ret = conn->sock->ops->sendmsg(conn->sock,
2647 reply_payload.data,
2648 reply_payload.size,
2649 0);
2650 if (send_ret < reply_payload.size) {
2651 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
2652 reply_payload.size, send_ret);
2653 ret = -1;
2654 goto end_no_reply;
2655 }
2656 end_no_reply:
2657 lttng_trace_chunk_put(chunk);
2658 lttng_dynamic_buffer_reset(&reply_payload);
2659 return ret;
2660 }
2661
2662 /*
2663 * relay_trace_chunk_exists: check if a trace chunk exists
2664 */
2665 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr *recv_hdr,
2666 struct relay_connection *conn,
2667 const struct lttng_buffer_view *payload)
2668 {
2669 int ret = 0;
2670 ssize_t send_ret;
2671 struct relay_session *session = conn->session;
2672 struct lttcomm_relayd_trace_chunk_exists *msg;
2673 struct lttcomm_relayd_trace_chunk_exists_reply reply = {};
2674 struct lttng_buffer_view header_view;
2675 struct lttng_trace_chunk *chunk = NULL;
2676 uint64_t chunk_id;
2677
2678 if (!session || !conn->version_check_done) {
2679 ERR("Trying to close a trace chunk before version check");
2680 ret = -1;
2681 goto end_no_reply;
2682 }
2683
2684 if (session->major == 2 && session->minor < 11) {
2685 ERR("Chunk close command is unsupported before 2.11");
2686 ret = -1;
2687 goto end_no_reply;
2688 }
2689
2690 header_view = lttng_buffer_view_from_view(payload, 0, sizeof(*msg));
2691 if (!header_view.data) {
2692 ERR("Failed to receive payload of chunk close command");
2693 ret = -1;
2694 goto end_no_reply;
2695 }
2696
2697 /* Convert to host endianness. */
2698 msg = (typeof(msg)) header_view.data;
2699 chunk_id = be64toh(msg->chunk_id);
2700
2701 chunk = sessiond_trace_chunk_registry_get_chunk(
2702 sessiond_trace_chunk_registry,
2703 conn->session->sessiond_uuid,
2704 conn->session->id,
2705 chunk_id);
2706
2707 reply = (typeof(reply)) {
2708 .generic.ret_code = htobe32((uint32_t) LTTNG_OK),
2709 .trace_chunk_exists = !!chunk,
2710 };
2711 send_ret = conn->sock->ops->sendmsg(conn->sock,
2712 &reply, sizeof(reply), 0);
2713 if (send_ret < (ssize_t) sizeof(reply)) {
2714 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2715 send_ret);
2716 ret = -1;
2717 }
2718 end_no_reply:
2719 lttng_trace_chunk_put(chunk);
2720 return ret;
2721 }
2722
2723 #define DBG_CMD(cmd_name, conn) \
2724 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2725
2726 static int relay_process_control_command(struct relay_connection *conn,
2727 const struct lttcomm_relayd_hdr *header,
2728 const struct lttng_buffer_view *payload)
2729 {
2730 int ret = 0;
2731
2732 switch (header->cmd) {
2733 case RELAYD_CREATE_SESSION:
2734 DBG_CMD("RELAYD_CREATE_SESSION", conn);
2735 ret = relay_create_session(header, conn, payload);
2736 break;
2737 case RELAYD_ADD_STREAM:
2738 DBG_CMD("RELAYD_ADD_STREAM", conn);
2739 ret = relay_add_stream(header, conn, payload);
2740 break;
2741 case RELAYD_START_DATA:
2742 DBG_CMD("RELAYD_START_DATA", conn);
2743 ret = relay_start(header, conn, payload);
2744 break;
2745 case RELAYD_SEND_METADATA:
2746 DBG_CMD("RELAYD_SEND_METADATA", conn);
2747 ret = relay_recv_metadata(header, conn, payload);
2748 break;
2749 case RELAYD_VERSION:
2750 DBG_CMD("RELAYD_VERSION", conn);
2751 ret = relay_send_version(header, conn, payload);
2752 break;
2753 case RELAYD_CLOSE_STREAM:
2754 DBG_CMD("RELAYD_CLOSE_STREAM", conn);
2755 ret = relay_close_stream(header, conn, payload);
2756 break;
2757 case RELAYD_DATA_PENDING:
2758 DBG_CMD("RELAYD_DATA_PENDING", conn);
2759 ret = relay_data_pending(header, conn, payload);
2760 break;
2761 case RELAYD_QUIESCENT_CONTROL:
2762 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn);
2763 ret = relay_quiescent_control(header, conn, payload);
2764 break;
2765 case RELAYD_BEGIN_DATA_PENDING:
2766 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn);
2767 ret = relay_begin_data_pending(header, conn, payload);
2768 break;
2769 case RELAYD_END_DATA_PENDING:
2770 DBG_CMD("RELAYD_END_DATA_PENDING", conn);
2771 ret = relay_end_data_pending(header, conn, payload);
2772 break;
2773 case RELAYD_SEND_INDEX:
2774 DBG_CMD("RELAYD_SEND_INDEX", conn);
2775 ret = relay_recv_index(header, conn, payload);
2776 break;
2777 case RELAYD_STREAMS_SENT:
2778 DBG_CMD("RELAYD_STREAMS_SENT", conn);
2779 ret = relay_streams_sent(header, conn, payload);
2780 break;
2781 case RELAYD_RESET_METADATA:
2782 DBG_CMD("RELAYD_RESET_METADATA", conn);
2783 ret = relay_reset_metadata(header, conn, payload);
2784 break;
2785 case RELAYD_ROTATE_STREAMS:
2786 DBG_CMD("RELAYD_ROTATE_STREAMS", conn);
2787 ret = relay_rotate_session_streams(header, conn, payload);
2788 break;
2789 case RELAYD_CREATE_TRACE_CHUNK:
2790 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn);
2791 ret = relay_create_trace_chunk(header, conn, payload);
2792 break;
2793 case RELAYD_CLOSE_TRACE_CHUNK:
2794 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn);
2795 ret = relay_close_trace_chunk(header, conn, payload);
2796 break;
2797 case RELAYD_TRACE_CHUNK_EXISTS:
2798 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn);
2799 ret = relay_trace_chunk_exists(header, conn, payload);
2800 break;
2801 case RELAYD_UPDATE_SYNC_INFO:
2802 default:
2803 ERR("Received unknown command (%u)", header->cmd);
2804 relay_unknown_command(conn);
2805 ret = -1;
2806 goto end;
2807 }
2808
2809 end:
2810 return ret;
2811 }
2812
2813 static enum relay_connection_status relay_process_control_receive_payload(
2814 struct relay_connection *conn)
2815 {
2816 int ret = 0;
2817 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2818 struct lttng_dynamic_buffer *reception_buffer =
2819 &conn->protocol.ctrl.reception_buffer;
2820 struct ctrl_connection_state_receive_payload *state =
2821 &conn->protocol.ctrl.state.receive_payload;
2822 struct lttng_buffer_view payload_view;
2823
2824 if (state->left_to_receive == 0) {
2825 /* Short-circuit for payload-less commands. */
2826 goto reception_complete;
2827 }
2828
2829 ret = conn->sock->ops->recvmsg(conn->sock,
2830 reception_buffer->data + state->received,
2831 state->left_to_receive, MSG_DONTWAIT);
2832 if (ret < 0) {
2833 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2834 PERROR("Unable to receive command payload on sock %d",
2835 conn->sock->fd);
2836 status = RELAY_CONNECTION_STATUS_ERROR;
2837 }
2838 goto end;
2839 } else if (ret == 0) {
2840 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2841 status = RELAY_CONNECTION_STATUS_CLOSED;
2842 goto end;
2843 }
2844
2845 assert(ret > 0);
2846 assert(ret <= state->left_to_receive);
2847
2848 state->left_to_receive -= ret;
2849 state->received += ret;
2850
2851 if (state->left_to_receive > 0) {
2852 /*
2853 * Can't transition to the protocol's next state, wait to
2854 * receive the rest of the header.
2855 */
2856 DBG3("Partial reception of control connection protocol payload (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2857 state->received, state->left_to_receive,
2858 conn->sock->fd);
2859 goto end;
2860 }
2861
2862 reception_complete:
2863 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64 " bytes",
2864 conn->sock->fd, state->received);
2865 /*
2866 * The payload required to process the command has been received.
2867 * A view to the reception buffer is forwarded to the various
2868 * commands and the state of the control is reset on success.
2869 *
2870 * Commands are responsible for sending their reply to the peer.
2871 */
2872 payload_view = lttng_buffer_view_from_dynamic_buffer(reception_buffer,
2873 0, -1);
2874 ret = relay_process_control_command(conn,
2875 &state->header, &payload_view);
2876 if (ret < 0) {
2877 status = RELAY_CONNECTION_STATUS_ERROR;
2878 goto end;
2879 }
2880
2881 ret = connection_reset_protocol_state(conn);
2882 if (ret) {
2883 status = RELAY_CONNECTION_STATUS_ERROR;
2884 }
2885 end:
2886 return status;
2887 }
2888
2889 static enum relay_connection_status relay_process_control_receive_header(
2890 struct relay_connection *conn)
2891 {
2892 int ret = 0;
2893 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
2894 struct lttcomm_relayd_hdr header;
2895 struct lttng_dynamic_buffer *reception_buffer =
2896 &conn->protocol.ctrl.reception_buffer;
2897 struct ctrl_connection_state_receive_header *state =
2898 &conn->protocol.ctrl.state.receive_header;
2899
2900 assert(state->left_to_receive != 0);
2901
2902 ret = conn->sock->ops->recvmsg(conn->sock,
2903 reception_buffer->data + state->received,
2904 state->left_to_receive, MSG_DONTWAIT);
2905 if (ret < 0) {
2906 if (errno != EAGAIN && errno != EWOULDBLOCK) {
2907 PERROR("Unable to receive control command header on sock %d",
2908 conn->sock->fd);
2909 status = RELAY_CONNECTION_STATUS_ERROR;
2910 }
2911 goto end;
2912 } else if (ret == 0) {
2913 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
2914 status = RELAY_CONNECTION_STATUS_CLOSED;
2915 goto end;
2916 }
2917
2918 assert(ret > 0);
2919 assert(ret <= state->left_to_receive);
2920
2921 state->left_to_receive -= ret;
2922 state->received += ret;
2923
2924 if (state->left_to_receive > 0) {
2925 /*
2926 * Can't transition to the protocol's next state, wait to
2927 * receive the rest of the header.
2928 */
2929 DBG3("Partial reception of control connection protocol header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
2930 state->received, state->left_to_receive,
2931 conn->sock->fd);
2932 goto end;
2933 }
2934
2935 /* Transition to next state: receiving the command's payload. */
2936 conn->protocol.ctrl.state_id =
2937 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD;
2938 memcpy(&header, reception_buffer->data, sizeof(header));
2939 header.circuit_id = be64toh(header.circuit_id);
2940 header.data_size = be64toh(header.data_size);
2941 header.cmd = be32toh(header.cmd);
2942 header.cmd_version = be32toh(header.cmd_version);
2943 memcpy(&conn->protocol.ctrl.state.receive_payload.header,
2944 &header, sizeof(header));
2945
2946 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32 ", cmd_version = %" PRIu32 ", payload size = %" PRIu64 " bytes",
2947 conn->sock->fd, header.cmd, header.cmd_version,
2948 header.data_size);
2949
2950 if (header.data_size > DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE) {
2951 ERR("Command header indicates a payload (%" PRIu64 " bytes) that exceeds the maximal payload size allowed on a control connection.",
2952 header.data_size);
2953 status = RELAY_CONNECTION_STATUS_ERROR;
2954 goto end;
2955 }
2956
2957 conn->protocol.ctrl.state.receive_payload.left_to_receive =
2958 header.data_size;
2959 conn->protocol.ctrl.state.receive_payload.received = 0;
2960 ret = lttng_dynamic_buffer_set_size(reception_buffer,
2961 header.data_size);
2962 if (ret) {
2963 status = RELAY_CONNECTION_STATUS_ERROR;
2964 goto end;
2965 }
2966
2967 if (header.data_size == 0) {
2968 /*
2969 * Manually invoke the next state as the poll loop
2970 * will not wake-up to allow us to proceed further.
2971 */
2972 status = relay_process_control_receive_payload(conn);
2973 }
2974 end:
2975 return status;
2976 }
2977
2978 /*
2979 * Process the commands received on the control socket
2980 */
2981 static enum relay_connection_status relay_process_control(
2982 struct relay_connection *conn)
2983 {
2984 enum relay_connection_status status;
2985
2986 switch (conn->protocol.ctrl.state_id) {
2987 case CTRL_CONNECTION_STATE_RECEIVE_HEADER:
2988 status = relay_process_control_receive_header(conn);
2989 break;
2990 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD:
2991 status = relay_process_control_receive_payload(conn);
2992 break;
2993 default:
2994 ERR("Unknown control connection protocol state encountered.");
2995 abort();
2996 }
2997
2998 return status;
2999 }
3000
3001 static enum relay_connection_status relay_process_data_receive_header(
3002 struct relay_connection *conn)
3003 {
3004 int ret;
3005 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3006 struct data_connection_state_receive_header *state =
3007 &conn->protocol.data.state.receive_header;
3008 struct lttcomm_relayd_data_hdr header;
3009 struct relay_stream *stream;
3010
3011 assert(state->left_to_receive != 0);
3012
3013 ret = conn->sock->ops->recvmsg(conn->sock,
3014 state->header_reception_buffer + state->received,
3015 state->left_to_receive, MSG_DONTWAIT);
3016 if (ret < 0) {
3017 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3018 PERROR("Unable to receive data header on sock %d", conn->sock->fd);
3019 status = RELAY_CONNECTION_STATUS_ERROR;
3020 }
3021 goto end;
3022 } else if (ret == 0) {
3023 /* Orderly shutdown. Not necessary to print an error. */
3024 DBG("Socket %d performed an orderly shutdown (received EOF)", conn->sock->fd);
3025 status = RELAY_CONNECTION_STATUS_CLOSED;
3026 goto end;
3027 }
3028
3029 assert(ret > 0);
3030 assert(ret <= state->left_to_receive);
3031
3032 state->left_to_receive -= ret;
3033 state->received += ret;
3034
3035 if (state->left_to_receive > 0) {
3036 /*
3037 * Can't transition to the protocol's next state, wait to
3038 * receive the rest of the header.
3039 */
3040 DBG3("Partial reception of data connection header (received %" PRIu64 " bytes, %" PRIu64 " bytes left to receive, fd = %i)",
3041 state->received, state->left_to_receive,
3042 conn->sock->fd);
3043 goto end;
3044 }
3045
3046 /* Transition to next state: receiving the payload. */
3047 conn->protocol.data.state_id = DATA_CONNECTION_STATE_RECEIVE_PAYLOAD;
3048
3049 memcpy(&header, state->header_reception_buffer, sizeof(header));
3050 header.circuit_id = be64toh(header.circuit_id);
3051 header.stream_id = be64toh(header.stream_id);
3052 header.data_size = be32toh(header.data_size);
3053 header.net_seq_num = be64toh(header.net_seq_num);
3054 header.padding_size = be32toh(header.padding_size);
3055 memcpy(&conn->protocol.data.state.receive_payload.header, &header, sizeof(header));
3056
3057 conn->protocol.data.state.receive_payload.left_to_receive =
3058 header.data_size;
3059 conn->protocol.data.state.receive_payload.received = 0;
3060 conn->protocol.data.state.receive_payload.rotate_index = false;
3061
3062 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64 ", stream_id = %" PRIu64 ", data_size = %" PRIu32 ", net_seq_num = %" PRIu64 ", padding_size = %" PRIu32,
3063 conn->sock->fd, header.circuit_id,
3064 header.stream_id, header.data_size,
3065 header.net_seq_num, header.padding_size);
3066
3067 stream = stream_get_by_id(header.stream_id);
3068 if (!stream) {
3069 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64,
3070 header.stream_id);
3071 /* Protocol error. */
3072 status = RELAY_CONNECTION_STATUS_ERROR;
3073 goto end;
3074 }
3075
3076 pthread_mutex_lock(&stream->lock);
3077 /* Prepare stream for the reception of a new packet. */
3078 ret = stream_init_packet(stream, header.data_size,
3079 &conn->protocol.data.state.receive_payload.rotate_index);
3080 pthread_mutex_unlock(&stream->lock);
3081 if (ret) {
3082 ERR("Failed to rotate stream output file");
3083 status = RELAY_CONNECTION_STATUS_ERROR;
3084 goto end_stream_unlock;
3085 }
3086
3087 end_stream_unlock:
3088 stream_put(stream);
3089 end:
3090 return status;
3091 }
3092
3093 static enum relay_connection_status relay_process_data_receive_payload(
3094 struct relay_connection *conn)
3095 {
3096 int ret;
3097 enum relay_connection_status status = RELAY_CONNECTION_STATUS_OK;
3098 struct relay_stream *stream;
3099 struct data_connection_state_receive_payload *state =
3100 &conn->protocol.data.state.receive_payload;
3101 const size_t chunk_size = RECV_DATA_BUFFER_SIZE;
3102 char data_buffer[chunk_size];
3103 bool partial_recv = false;
3104 bool new_stream = false, close_requested = false, index_flushed = false;
3105 uint64_t left_to_receive = state->left_to_receive;
3106 struct relay_session *session;
3107
3108 DBG3("Receiving data for stream id %" PRIu64 " seqnum %" PRIu64 ", %" PRIu64" bytes received, %" PRIu64 " bytes left to receive",
3109 state->header.stream_id, state->header.net_seq_num,
3110 state->received, left_to_receive);
3111
3112 stream = stream_get_by_id(state->header.stream_id);
3113 if (!stream) {
3114 /* Protocol error. */
3115 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64,
3116 state->header.stream_id);
3117 status = RELAY_CONNECTION_STATUS_ERROR;
3118 goto end;
3119 }
3120
3121 pthread_mutex_lock(&stream->lock);
3122 session = stream->trace->session;
3123 if (!conn->session) {
3124 ret = connection_set_session(conn, session);
3125 if (ret) {
3126 status = RELAY_CONNECTION_STATUS_ERROR;
3127 goto end_stream_unlock;
3128 }
3129 }
3130
3131 /*
3132 * The size of the "chunk" received on any iteration is bounded by:
3133 * - the data left to receive,
3134 * - the data immediately available on the socket,
3135 * - the on-stack data buffer
3136 */
3137 while (left_to_receive > 0 && !partial_recv) {
3138 size_t recv_size = min(left_to_receive, chunk_size);
3139 struct lttng_buffer_view packet_chunk;
3140
3141 ret = conn->sock->ops->recvmsg(conn->sock, data_buffer,
3142 recv_size, MSG_DONTWAIT);
3143 if (ret < 0) {
3144 if (errno != EAGAIN && errno != EWOULDBLOCK) {
3145 PERROR("Socket %d error", conn->sock->fd);
3146 status = RELAY_CONNECTION_STATUS_ERROR;
3147 }
3148 goto end_stream_unlock;
3149 } else if (ret == 0) {
3150 /* No more data ready to be consumed on socket. */
3151 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64,
3152 state->header.stream_id);
3153 status = RELAY_CONNECTION_STATUS_CLOSED;
3154 break;
3155 } else if (ret < (int) recv_size) {
3156 /*
3157 * All the data available on the socket has been
3158 * consumed.
3159 */
3160 partial_recv = true;
3161 recv_size = ret;
3162 }
3163