Debian Codegraph @

src/ws/cockpitpipe.c

raw
1 /*
2 * Copyright (C) 2014 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 /* This gets logged as part of the (more verbose) protocol logging */
9 #ifdef G_LOG_DOMAIN
10 #undef G_LOG_DOMAIN
11 #endif
12 #define G_LOG_DOMAIN "cockpit-protocol"
13
14 #include "cockpitpipe.h"
15
16 #include "cockpitflow.h"
17 #include "cockpitunicode.h"
18
19 #include <glib-unix.h>
20
21 #include <sys/socket.h>
22 #include <sys/uio.h>
23 #include <sys/wait.h>
24
25 #include <dirent.h>
26 #include <errno.h>
27 #include <poll.h>
28 #include <pty.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33
34 #ifdef __linux
35 #include <sys/prctl.h>
36 #endif
37
38 /**
39 * CockpitPipe:
40 *
41 * A pipe with queued input and output similar in concept to a
42 * a unix shell pipe or pipe().
43 *
44 * When talking to a process the CockpitPipe:pid property
45 * will be non-zero. In that case the transport waits for the child
46 * process to exit before it closes.
47 *
48 * This pipe can do flow control in two ways:
49 *
50 * - Its input can be throttled, it can listen to a "pressure" signal
51 * from another object passed into cockpit_flow_throttle()
52 * - It can optionally control another flow, by emitting a "pressure" signal
53 * when its output queue is too large
54 */
55
56 #define DEF_PACKET_SIZE (64UL * 1024UL)
57
58 enum {
59 PROP_0,
60 PROP_NAME,
61 PROP_IN_FD,
62 PROP_OUT_FD,
63 PROP_ERR_FD,
64 PROP_PID,
65 PROP_PROBLEM,
66 };
67
68 typedef struct {
69 gchar *name;
70 GMainContext *context;
71
72 gboolean closed;
73 gboolean closing;
74 gboolean connecting;
75 gchar *problem;
76
77 GPid pid;
78 GSource *child;
79 gboolean exited;
80 gint status;
81 CockpitPipe **watch_arg;
82 gboolean is_process;
83
84 int out_fd;
85 gboolean out_done;
86 GSource *out_source;
87 GQueue *out_queue;
88 gsize out_queued;
89 gsize out_partial;
90
91 int in_fd;
92 gboolean in_done;
93 GSource *in_source;
94 GByteArray *in_buffer;
95
96 int err_fd;
97 gboolean err_done;
98 GSource *err_source;
99 GByteArray *err_buffer;
100 gboolean err_forward_to_log;
101
102 gboolean is_user_fd;
103
104 /* Pressure which throttles input on this pipe */
105 CockpitFlow *pressure;
106 gulong pressure_sig;
107 } CockpitPipePrivate;
108
109 typedef struct {
110 GSource source;
111 CockpitPipe *pipe;
112 } CockpitPipeSource;
113
114 /* A megabyte is when we start to consider queue full enough */
115 #define QUEUE_PRESSURE 1024UL * 1024UL
116
117 static guint cockpit_pipe_sig_read;
118 static guint cockpit_pipe_sig_close;
119
120 static void start_input (CockpitPipe *self);
121
122 static void start_output (CockpitPipe *self);
123
124 static void close_output (CockpitPipe *self);
125
126 static void cockpit_close_later (CockpitPipe *self);
127
128 static void set_problem_from_errno (CockpitPipe *self,
129 const gchar *message,
130 int errn);
131
132 static void cockpit_pipe_throttle (CockpitFlow *flow,
133 CockpitFlow *controlling);
134
135 static void cockpit_pipe_flow_iface_init (CockpitFlowInterface *iface);
136
137 G_DEFINE_TYPE_WITH_CODE (CockpitPipe, cockpit_pipe, G_TYPE_OBJECT,
138 G_IMPLEMENT_INTERFACE (COCKPIT_TYPE_FLOW, cockpit_pipe_flow_iface_init)
139 G_ADD_PRIVATE (CockpitPipe));
140
141 static void
142 cockpit_pipe_init (CockpitPipe *self)
143 {
144 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
145
146 priv->in_buffer = g_byte_array_new ();
147 priv->in_fd = -1;
148 priv->out_queue = g_queue_new ();
149 priv->out_fd = -1;
150 priv->err_fd = -1;
151 priv->status = -1;
152
153 priv->context = g_main_context_ref_thread_default ();
154 }
155
156 static void
157 stop_output (CockpitPipe *self)
158 {
159 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
160
161 g_assert (priv->out_source != NULL);
162 g_source_destroy (priv->out_source);
163 g_source_unref (priv->out_source);
164 priv->out_source = NULL;
165 }
166
167 static void
168 stop_input (CockpitPipe *self)
169 {
170 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
171
172 g_assert (priv->in_source != NULL);
173 g_source_destroy (priv->in_source);
174 g_source_unref (priv->in_source);
175 priv->in_source = NULL;
176 }
177
178 static void
179 stop_error (CockpitPipe *self)
180 {
181 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
182
183 g_assert (priv->err_source != NULL);
184 g_source_destroy (priv->err_source);
185 g_source_unref (priv->err_source);
186 priv->err_source = NULL;
187 }
188
189 static void
190 close_immediately (CockpitPipe *self,
191 const gchar *problem)
192 {
193 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
194
195 if (priv->closed)
196 return;
197
198 if (problem)
199 {
200 g_free (priv->problem);
201 priv->problem = g_strdup (problem);
202 }
203
204 priv->closed = TRUE;
205
206 g_debug ("%s: closing pipe%s%s", priv->name,
207 priv->problem ? ": " : "",
208 priv->problem ? priv->problem : "");
209
210 if (priv->in_source)
211 stop_input (self);
212 priv->in_done = TRUE;
213 if (priv->out_source)
214 stop_output (self);
215 priv->out_done = TRUE;
216 if (priv->err_source)
217 stop_error (self);
218 priv->err_done = TRUE;
219
220 if (priv->in_fd != -1)
221 {
222 close (priv->in_fd);
223 priv->in_fd = -1;
224 }
225 if (priv->out_fd != -1)
226 {
227 close (priv->out_fd);
228 priv->out_fd = -1;
229 }
230 if (priv->err_fd != -1)
231 {
232 close (priv->err_fd);
233 priv->err_fd = -1;
234 }
235
236
237 if (problem && priv->pid && !priv->exited)
238 {
239 g_debug ("%s: killing child: %d", priv->name, (int)priv->pid);
240 kill (priv->pid, SIGTERM);
241 }
242
243 /* If not tracking a pid, then we are now closed. */
244 if (!priv->child)
245 {
246 g_debug ("%s: no child process to wait for: closed", priv->name);
247 g_signal_emit (self, cockpit_pipe_sig_close, 0, priv->problem);
248 }
249 }
250
251 static void
252 close_maybe (CockpitPipe *self)
253 {
254 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
255
256 if (!priv->closed)
257 {
258 if (priv->in_done && priv->out_done && priv->err_done)
259 {
260 g_debug ("%s: input and output done", priv->name);
261 close_immediately (self, NULL);
262 }
263 }
264 }
265
266 static void
267 on_child_reap (GPid pid,
268 gint status,
269 gpointer user_data)
270 {
271 CockpitPipe **arg = user_data;
272 CockpitPipe *self = *arg;
273 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
274
275 /* This happens if this child watch outlasts the pipe */
276 if (!self)
277 return;
278
279 priv->status = status;
280 priv->exited = TRUE;
281 priv->watch_arg = NULL;
282
283 /* Release our reference on watch handler */
284 g_source_unref (priv->child);
285 priv->child = NULL;
286
287 /*
288 * We need to wait until both the process has exited *and*
289 * the output has closed before we fire our close signal.
290 */
291
292 g_debug ("%s: child process quit:%s %d %d", priv->name,
293 priv->closed ? " closed:" : "", (int)pid, status);
294
295 /* Start input and output to get to completion */
296 if (!priv->out_done)
297 close_output (self);
298 else if (priv->closed)
299 g_signal_emit (self, cockpit_pipe_sig_close, 0, priv->problem);
300 }
301
302 static gboolean
303 dispatch_input (gint fd,
304 GIOCondition cond,
305 gpointer user_data)
306 {
307 CockpitPipe *self = (CockpitPipe *)user_data;
308 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
309 gssize ret = 0;
310 gsize len;
311 int errn;
312
313 g_return_val_if_fail (priv->in_source, FALSE);
314 len = priv->in_buffer->len;
315
316 /*
317 * Enable clean shutdown by not reading when we just get
318 * G_IO_HUP. Note that when we get G_IO_ERR we do want to read
319 * just so we can get the appropriate detailed error message.
320 */
321 if (cond != G_IO_HUP)
322 {
323 g_byte_array_set_size (priv->in_buffer, len + DEF_PACKET_SIZE);
324 g_debug ("%s: reading input %x", priv->name, cond);
325 ret = read (priv->in_fd, priv->in_buffer->data + len, DEF_PACKET_SIZE);
326
327 errn = errno;
328 if (ret < 0)
329 {
330 g_byte_array_set_size (priv->in_buffer, len);
331 if (errn == EAGAIN || errn == EINTR)
332 {
333 return TRUE;
334 }
335 else if (errn == ECONNRESET)
336 {
337 g_debug ("couldn't read: %s", g_strerror (errn));
338 ret = 0;
339 }
340 else
341 {
342 set_problem_from_errno (self, "couldn't read", errn);
343 close_immediately (self, NULL); /* problem already set */
344 return FALSE;
345 }
346 }
347 }
348
349 g_byte_array_set_size (priv->in_buffer, len + ret);
350
351 if (ret == 0)
352 {
353 g_debug ("%s: end of input", priv->name);
354 priv->in_done = TRUE;
355 stop_input (self);
356 }
357
358 g_object_ref (self);
359
360 g_signal_emit (self, cockpit_pipe_sig_read, 0, priv->in_buffer, priv->in_done);
361
362 if (priv->in_done)
363 close_maybe (self);
364
365 g_object_unref (self);
366 return TRUE;
367 }
368
369 static void
370 forward_error (CockpitPipe *self)
371 {
372 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
373
374 if (priv->err_buffer->len > 0)
375 {
376 g_warning ("%s: unexpected stderr output: %.*s", priv->name, priv->err_buffer->len, priv->err_buffer->data);
377 g_byte_array_set_size (priv->err_buffer, 0);
378 }
379 }
380
381 static gboolean
382 dispatch_error (gint fd,
383 GIOCondition cond,
384 gpointer user_data)
385 {
386 CockpitPipe *self = (CockpitPipe *)user_data;
387 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
388 gssize ret = 0;
389 gsize len;
390
391 g_return_val_if_fail (priv->err_source, FALSE);
392 len = priv->err_buffer->len;
393
394 /*
395 * Enable clean shutdown by not reading when we just get
396 * G_IO_HUP. Note that when we get G_IO_ERR we do want to read
397 * just so we can get the appropriate detailed error message.
398 */
399 if (cond != G_IO_HUP)
400 {
401 g_debug ("%s: reading error", priv->name);
402
403 g_byte_array_set_size (priv->err_buffer, len + 1024);
404 ret = read (priv->err_fd, priv->err_buffer->data + len, 1024);
405 if (ret < 0)
406 {
407 g_byte_array_set_size (priv->err_buffer, len);
408 if (errno != EAGAIN && errno != EINTR)
409 {
410 g_warning ("%s: couldn't read error: %s", priv->name, g_strerror (errno));
411 close_immediately (self, "internal-error");
412 return FALSE;
413 }
414
415 if (priv->err_forward_to_log)
416 forward_error (self);
417
418 return TRUE;
419 }
420 }
421
422 g_byte_array_set_size (priv->err_buffer, len + ret);
423
424 if (priv->err_forward_to_log)
425 forward_error (self);
426
427 if (ret == 0)
428 {
429 g_debug ("%s: end of error", priv->name);
430 priv->err_done = TRUE;
431 stop_error (self);
432 }
433
434 g_object_ref (self);
435
436 if (priv->err_done)
437 close_maybe (self);
438
439 g_object_unref (self);
440 return TRUE;
441 }
442
443 static gboolean
444 fd_readable (int fd)
445 {
446 struct pollfd pfd = { .fd = fd, .events = POLLIN };
447 return poll (&pfd, 1, 0) > 0 && (pfd.revents & POLLIN);
448 }
449
450 static void
451 drain_error (CockpitPipe *self)
452 {
453 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
454
455 while (priv->err_source && fd_readable (priv->err_fd))
456 dispatch_error (priv->err_fd, G_IO_IN, self);
457 }
458
459 static void
460 close_output (CockpitPipe *self)
461 {
462 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
463
464 priv->out_done = TRUE;
465
466 if (priv->out_fd != -1)
467 {
468 g_debug ("%s: end of output", priv->name);
469
470 /* And if closing, then we need to shutdown the output fd */
471 if (shutdown (priv->out_fd, SHUT_WR) < 0)
472 {
473 if (errno == ENOTSOCK)
474 {
475 g_debug ("%s: not a socket, closing entirely", priv->name);
476 close (priv->out_fd);
477
478 if (priv->in_fd == priv->out_fd)
479 {
480 priv->in_done = TRUE;
481 priv->in_fd = -1;
482 if (priv->in_source)
483 {
484 g_debug ("%s: and closing input because same fd", priv->name);
485 stop_input (self);
486 }
487 }
488
489 priv->out_fd = -1;
490 }
491 else
492 {
493 g_warning ("%s: couldn't shutdown fd: %s", priv->name, g_strerror (errno));
494 close_immediately (self, "internal-error");
495 }
496 }
497 }
498
499 close_maybe (self);
500 }
501
502 static void
503 set_problem_from_errno (CockpitPipe *self,
504 const gchar *message,
505 int errn)
506 {
507 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
508 const gchar *problem = NULL;
509
510 if (errn == EPERM || errn == EACCES)
511 problem = "access-denied";
512 else if (errn == ENOENT || errn == ECONNREFUSED)
513 problem = "not-found";
514 /* only warn about Cockpit-internal fds, not opaque user ones */
515 else if (errn == EBADF && priv->is_user_fd)
516 problem = "protocol-error";
517
518 g_free (priv->problem);
519
520 if (problem)
521 {
522 g_message ("%s: %s: %s", priv->name, message, g_strerror (errn));
523 priv->problem = g_strdup (problem);
524 }
525 else
526 {
527 g_warning ("%s: %s: %s", priv->name, message, g_strerror (errn));
528 priv->problem = g_strdup ("internal-error");
529 }
530 }
531
532 static gboolean
533 dispatch_connect (CockpitPipe *self)
534 {
535 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
536 socklen_t slen;
537 int error;
538
539 priv->connecting = FALSE;
540
541 slen = sizeof (error);
542 if (getsockopt (priv->out_fd, SOL_SOCKET, SO_ERROR, &error, &slen) != 0)
543 {
544 g_warning ("%s: couldn't get connection result", priv->name);
545 close_immediately (self, "internal-error");
546 }
547 else if (error == EINPROGRESS)
548 {
549 /* keep connecting */
550 priv->connecting = TRUE;
551 }
552 else if (error != 0)
553 {
554 set_problem_from_errno (self, "couldn't connect", error);
555 close_immediately (self, NULL); /* problem already set */
556 }
557 else
558 {
559 return TRUE;
560 }
561
562 return FALSE;
563 }
564
565 static gboolean
566 dispatch_output (gint fd,
567 GIOCondition cond,
568 gpointer user_data)
569 {
570 CockpitPipe *self = (CockpitPipe *)user_data;
571 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
572 struct iovec iov[4];
573 gsize partial, size, before;
574 GBytes *popped;
575 gssize ret;
576 gint i, count;
577 GList *l;
578
579 /* A non-blocking connect is processed here */
580 if (priv->connecting && !dispatch_connect (self))
581 return TRUE;
582
583 g_return_val_if_fail (priv->out_source, FALSE);
584
585 before = priv->out_queued;
586
587 /* Note we fall through when nothing to write */
588 partial = priv->out_partial;
589 for (l = priv->out_queue->head, i = 0;
590 i < G_N_ELEMENTS (iov) && l != NULL;
591 i++, l = g_list_next (l))
592 {
593 iov[i].iov_base = (gpointer)g_bytes_get_data (l->data, &iov[i].iov_len);
594
595 if (partial)
596 {
597 g_assert (partial < iov[i].iov_len);
598 iov[i].iov_len -= partial;
599 iov[i].iov_base = ((gchar *)iov[i].iov_base) + partial;
600 partial = 0;
601 }
602 }
603 count = i;
604
605 if (count == 0)
606 ret = 0;
607 else
608 ret = writev (priv->out_fd, iov, count);
609 if (ret < 0)
610 {
611 if (errno != EAGAIN && errno != EINTR)
612 {
613 if (errno == EPIPE)
614 {
615 g_debug ("%s: couldn't write: %s", priv->name, g_strerror (errno));
616 close_immediately (self, "terminated");
617 }
618 else
619 {
620 set_problem_from_errno (self, "couldn't write", errno);
621 close_immediately (self, NULL); /* already set */
622 }
623 }
624 return FALSE;
625 }
626
627 /* Figure out what was written */
628 for (i = 0; ret > 0 && i < count; i++)
629 {
630 if (ret >= iov[i].iov_len)
631 {
632 g_debug ("%s: wrote %d bytes", priv->name, (int)iov[i].iov_len);
633 popped = g_queue_pop_head (priv->out_queue);
634 size = g_bytes_get_size (popped);
635 g_assert (size <= priv->out_queued);
636 priv->out_queued -= size;
637 g_bytes_unref (popped);
638 priv->out_partial = 0;
639 ret -= iov[i].iov_len;
640 }
641 else
642 {
643 g_debug ("%s: partial write %d of %d bytes", priv->name,
644 (int)ret, (int)iov[i].iov_len);
645 priv->out_partial += ret;
646 ret = 0;
647 }
648 }
649
650 /*
651 * If we're controlling another flow, turn it on again when our output
652 * buffer size becomes less than the low mark.
653 */
654 if (before >= QUEUE_PRESSURE && priv->out_queued < QUEUE_PRESSURE)
655 {
656 g_debug ("%s: have %" G_GSIZE_FORMAT " bytes queued, releasing pressure", priv->name, priv->out_queued);
657 cockpit_flow_emit_pressure (COCKPIT_FLOW (self), FALSE);
658 }
659
660 if (priv->out_queue->head)
661 return TRUE;
662
663 g_debug ("%s: output queue empty", priv->name);
664
665 /* If all messages are done, then stop polling out fd */
666 stop_output (self);
667
668 if (priv->closing)
669 close_output (self);
670 else
671 close_maybe (self);
672
673 return TRUE;
674 }
675
676 static void
677 start_output (CockpitPipe *self)
678 {
679 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
680
681 g_assert (priv->out_source == NULL);
682 priv->out_source = g_unix_fd_source_new (priv->out_fd, G_IO_OUT);
683 g_source_set_name (priv->out_source, "pipe-output");
684 g_source_set_callback (priv->out_source, (GSourceFunc)dispatch_output, self, NULL);
685 g_source_attach (priv->out_source, priv->context);
686 }
687
688 static void
689 start_input (CockpitPipe *self)
690 {
691 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
692
693 g_assert (priv->in_source == NULL);
694 priv->in_source = g_unix_fd_source_new (priv->in_fd, G_IO_IN);
695 g_source_set_name (priv->in_source, "pipe-input");
696 g_source_set_callback (priv->in_source, (GSourceFunc)dispatch_input, self, NULL);
697 g_source_attach (priv->in_source, priv->context);
698 }
699
700 static void
701 cockpit_pipe_constructed (GObject *object)
702 {
703 CockpitPipe *self = COCKPIT_PIPE (object);
704 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
705 GError *error = NULL;
706
707 G_OBJECT_CLASS (cockpit_pipe_parent_class)->constructed (object);
708
709 if (priv->name == NULL)
710 priv->name = g_strdup ("pipe");
711
712 if (priv->in_fd >= 0)
713 {
714 if (!g_unix_set_fd_nonblocking (priv->in_fd, TRUE, &error))
715 {
716 g_warning ("%s: couldn't set file descriptor to non-blocking: %s",
717 priv->name, error->message);
718 g_clear_error (&error);
719 }
720
721 start_input (self);
722 }
723 else
724 {
725 priv->in_done = TRUE;
726 }
727
728 if (priv->out_fd >= 0)
729 {
730 if (!g_unix_set_fd_nonblocking (priv->out_fd, TRUE, &error))
731 {
732 g_warning ("%s: couldn't set file descriptor to non-blocking: %s",
733 priv->name, error->message);
734 g_clear_error (&error);
735 }
736 start_output (self);
737 }
738 else
739 {
740 priv->out_done = TRUE;
741 }
742
743 if (priv->err_fd >= 0)
744 {
745 if (!g_unix_set_fd_nonblocking (priv->err_fd, TRUE, &error))
746 {
747 g_warning ("%s: couldn't set file descriptor to non-blocking: %s",
748 priv->name, error->message);
749 g_clear_error (&error);
750 }
751
752 priv->err_buffer = g_byte_array_new ();
753 priv->err_source = g_unix_fd_source_new (priv->err_fd, G_IO_IN);
754 g_source_set_name (priv->err_source, "pipe-error");
755 g_source_set_callback (priv->err_source, (GSourceFunc)dispatch_error, self, NULL);
756 g_source_attach (priv->err_source, priv->context);
757 }
758 else
759 {
760 priv->err_done = TRUE;
761 }
762
763 if (priv->pid)
764 {
765 priv->is_process = TRUE;
766
767 /* We may need this watch to outlast this process ... */
768 priv->watch_arg = g_new0 (CockpitPipe *, 1);
769 *(priv->watch_arg) = self;
770
771 priv->child = g_child_watch_source_new (priv->pid);
772 g_source_set_callback (priv->child, (GSourceFunc)on_child_reap,
773 priv->watch_arg, g_free);
774 g_source_attach (priv->child, priv->context);
775 }
776 }
777
778 static void
779 cockpit_pipe_set_property (GObject *obj,
780 guint prop_id,
781 const GValue *value,
782 GParamSpec *pspec)
783 {
784 CockpitPipe *self = COCKPIT_PIPE (obj);
785 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
786
787 switch (prop_id)
788 {
789 case PROP_NAME:
790 priv->name = g_value_dup_string (value);
791 break;
792 case PROP_IN_FD:
793 priv->in_fd = g_value_get_int (value);
794 break;
795 case PROP_OUT_FD:
796 priv->out_fd = g_value_get_int (value);
797 break;
798 case PROP_ERR_FD:
799 priv->err_fd = g_value_get_int (value);
800 break;
801 case PROP_PID:
802 priv->pid = g_value_get_int (value);
803 break;
804 case PROP_PROBLEM:
805 priv->problem = g_value_dup_string (value);
806 if (priv->problem)
807 cockpit_close_later (self);
808 break;
809 default:
810 G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
811 break;
812 }
813 }
814
815 static void
816 cockpit_pipe_get_property (GObject *obj,
817 guint prop_id,
818 GValue *value,
819 GParamSpec *pspec)
820 {
821 CockpitPipe *self = COCKPIT_PIPE (obj);
822 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
823
824 switch (prop_id)
825 {
826 case PROP_NAME:
827 g_value_set_string (value, priv->name);
828 break;
829 case PROP_IN_FD:
830 g_value_set_int (value, priv->in_fd);
831 break;
832 case PROP_OUT_FD:
833 g_value_set_int (value, priv->out_fd);
834 break;
835 case PROP_ERR_FD:
836 g_value_set_int (value, priv->err_fd);
837 break;
838 case PROP_PID:
839 g_value_set_int (value, priv->pid);
840 break;
841 case PROP_PROBLEM:
842 g_value_set_string (value, priv->problem);
843 break;
844 default:
845 G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
846 break;
847 }
848 }
849
850 static void
851 cockpit_pipe_dispose (GObject *object)
852 {
853 CockpitPipe *self = COCKPIT_PIPE (object);
854 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
855
856 if (priv->pid && !priv->exited)
857 {
858 g_debug ("%s: killing child: %d", priv->name, (int)priv->pid);
859 kill (priv->pid, SIGTERM);
860 }
861
862 if (!priv->closed)
863 close_immediately (self, "terminated");
864
865 cockpit_pipe_throttle (COCKPIT_FLOW (self), NULL);
866 g_assert (priv->pressure == NULL);
867
868 while (priv->out_queue->head)
869 g_bytes_unref (g_queue_pop_head (priv->out_queue));
870 priv->out_queued = 0;
871
872 G_OBJECT_CLASS (cockpit_pipe_parent_class)->dispose (object);
873 }
874
875 static void
876 cockpit_pipe_finalize (GObject *object)
877 {
878 CockpitPipe *self = COCKPIT_PIPE (object);
879 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
880
881 g_assert (priv->closed);
882 g_assert (!priv->in_source);
883 g_assert (!priv->out_source);
884
885 /* Release our reference on watch handler */
886 if (priv->child)
887 g_source_unref (priv->child);
888
889 /*
890 * Tell the child watch that we've gone away ...
891 * But note that if the child watch hasn't fired, it'll continue to wait
892 */
893 if (priv->watch_arg)
894 *(priv->watch_arg) = NULL;
895
896 g_byte_array_unref (priv->in_buffer);
897 if (priv->err_buffer)
898 g_byte_array_unref (priv->err_buffer);
899 g_queue_free (priv->out_queue);
900 g_free (priv->problem);
901 g_free (priv->name);
902
903 if (priv->context)
904 g_main_context_unref (priv->context);
905
906 G_OBJECT_CLASS (cockpit_pipe_parent_class)->finalize (object);
907 }
908
909 static void
910 cockpit_pipe_class_init (CockpitPipeClass *klass)
911 {
912 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
913
914 gobject_class->constructed = cockpit_pipe_constructed;
915 gobject_class->get_property = cockpit_pipe_get_property;
916 gobject_class->set_property = cockpit_pipe_set_property;
917 gobject_class->dispose = cockpit_pipe_dispose;
918 gobject_class->finalize = cockpit_pipe_finalize;
919
920 /**
921 * CockpitPipe:in-fd:
922 *
923 * The file descriptor the pipe reads from. The pipe owns the
924 * file descriptor and will close it.
925 */
926 g_object_class_install_property (gobject_class, PROP_IN_FD,
927 g_param_spec_int ("in-fd", "in-fd", "in-fd", -1, G_MAXINT, -1,
928 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
929
930 /**
931 * CockpitPipe:out-fd:
932 *
933 * The file descriptor the pipe writes to. The pipe owns the
934 * file descriptor and will close it.
935 */
936 g_object_class_install_property (gobject_class, PROP_OUT_FD,
937 g_param_spec_int ("out-fd", "out-fd", "out-fd", -1, G_MAXINT, -1,
938 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
939
940 /**
941 * CockpitPipe:err-fd:
942 *
943 * The file descriptor the pipe reads error output from. The pipe owns the
944 * file descriptor and will close it.
945 */
946 g_object_class_install_property (gobject_class, PROP_ERR_FD,
947 g_param_spec_int ("err-fd", "err-fd", "err-fd", -1, G_MAXINT, -1,
948 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
949
950 /**
951 * CockpitPipe:pid:
952 *
953 * The process id of the pipe, if the pipe is talking to a process.
954 * Otherwise set to zero.
955 *
956 * If you use cockpit_pipe_transport_spawn() to create the
957 * #CockpitPipe then this will be non zero.
958 */
959 g_object_class_install_property (gobject_class, PROP_PID,
960 g_param_spec_int ("pid", "pid", "pid", 0, G_MAXINT, 0,
961 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
962 /**
963 * CockpitPipe:name:
964 *
965 * Pipe name used for debugging purposes.
966 */
967 g_object_class_install_property (gobject_class, PROP_NAME,
968 g_param_spec_string ("name", "name", "name", "<unnamed>",
969 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
970
971 /**
972 * CockpitPipe:problem:
973 *
974 * The problem that the pipe closed with. If used as a constructor argument then
975 * the pipe will be created in a closed/failed state. Although 'closed' signal will
976 * only fire once main loop is hit.
977 */
978 g_object_class_install_property (gobject_class, PROP_PROBLEM,
979 g_param_spec_string ("problem", "problem", "problem", NULL,
980 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
981
982 /**
983 * CockpitPipe::read:
984 * @buffer: a GByteArray of the read data
985 * @eof: whether the pipe is done reading
986 *
987 * Emitted when data is read from the input file descriptor of the
988 * pipe.
989 *
990 * Data consumed from @buffer by the handler should be removed from
991 * the GByteArray. This can be done with the cockpit_pipe_consume()
992 * function.
993 *
994 * This handler will only be called once with @eof set to TRUE. But
995 * in error conditions it may not be called with @eof set to TRUE
996 * at all, and the CockpitPipe::close signal will simply fire.
997 */
998 cockpit_pipe_sig_read = g_signal_new ("read", COCKPIT_TYPE_PIPE, G_SIGNAL_RUN_LAST,
999 G_STRUCT_OFFSET (CockpitPipeClass, read),
1000 NULL, NULL, NULL,
1001 G_TYPE_NONE, 2, G_TYPE_BYTE_ARRAY, G_TYPE_BOOLEAN);
1002
1003 /**
1004 * CockpitPipe::close:
1005 * @problem: problem string or %NULL
1006 *
1007 * Emitted when the pipe closes, whether due to a problem or a normal
1008 * shutdown.
1009 *
1010 * @problem will be NULL if the pipe closed normally.
1011 */
1012 cockpit_pipe_sig_close = g_signal_new ("close", COCKPIT_TYPE_PIPE, G_SIGNAL_RUN_FIRST,
1013 G_STRUCT_OFFSET (CockpitPipeClass, close),
1014 NULL, NULL, NULL,
1015 G_TYPE_NONE, 1, G_TYPE_STRING);
1016 }
1017
1018 /**
1019 * cockpit_pipe_write:
1020 * @self: the pipe
1021 * @data: the data to write
1022 *
1023 * Write @data to the pipe. This is not done immediately, it's
1024 * queued and written when the pipe is ready.
1025 *
1026 * If you cockpit_pipe_close() with a @problem, then queued data
1027 * will be discarded.
1028 *
1029 * Calling this function on a closed or closing pipe (one on which
1030 * cockpit_pipe_close() has been called) is invalid.
1031 *
1032 * Zero length data blocks are ignored, it doesn't makes sense to
1033 * write zero bytes to a pipe.
1034 */
1035 void
1036 _cockpit_pipe_write (CockpitPipe *self,
1037 GBytes *data,
1038 const gchar *caller,
1039 int line)
1040 {
1041 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1042 gsize size, before;
1043
1044 g_return_if_fail (COCKPIT_IS_PIPE (self));
1045
1046 /* If priv->io is already gone but we are still waiting for the
1047 child to exit, then we haven't emitted the "close" signal yet
1048 and it isn't an error to try to send more messages. We drop them
1049 here.
1050 */
1051 if (priv->closed && priv->child && priv->pid != 0)
1052 {
1053 g_debug ("%s: dropping message while waiting for child to exit", priv->name);
1054 return;
1055 }
1056
1057 /*
1058 * Debugging this issue so have made thingcs more verbose.
1059 * HACK: https://github.com/cockpit-project/cockpit/issues/2978
1060 */
1061 if (priv->closed)
1062 {
1063 g_critical ("assertion priv->closed check failed at %s %d (%p %d)",
1064 caller, line, priv->child, priv->pid);
1065 return;
1066 }
1067
1068 size = g_bytes_get_size (data);
1069 if (size == 0)
1070 {
1071 g_debug ("%s: ignoring zero byte data block", priv->name);
1072 return;
1073 }
1074
1075 before = priv->out_queued;
1076 g_return_if_fail (G_MAXSIZE - size > priv->out_queued);
1077 priv->out_queued += size;
1078 g_queue_push_tail (priv->out_queue, g_bytes_ref (data));
1079
1080 /*
1081 * If we have too much data queued, and are controlling another flow
1082 * tell it to stop sending data, each time we cross over the high bound.
1083 */
1084 if (before < QUEUE_PRESSURE && priv->out_queued >= QUEUE_PRESSURE)
1085 {
1086 g_debug ("%s: have %" G_GSIZE_FORMAT "bytes queued, emitting pressure", priv->name, priv->out_queued);
1087 cockpit_flow_emit_pressure (COCKPIT_FLOW (self), TRUE);
1088 }
1089
1090 if (!priv->out_source && priv->out_fd >= 0)
1091 {
1092 start_output (self);
1093 }
1094
1095 /*
1096 * If this becomes thread-safe, then something like this is needed:
1097 * g_main_context_wakeup (g_source_get_context (priv->source));
1098 */
1099 }
1100
1101 /**
1102 * cockpit_pipe_close:
1103 * @self: a pipe
1104 * @problem: a problem or NULL
1105 *
1106 * Close the pipe. If @problem is non NULL, then it's treated
1107 * as if an error occurred, and the pipe is closed immediately.
1108 * Otherwise the pipe output is closed when all data has been sent.
1109 *
1110 * The 'close' signal will be fired when the pipe actually closes.
1111 * This may be during this function call (esp. in the case of a
1112 * non-NULL @problem) or later.
1113 */
1114 void
1115 cockpit_pipe_close (CockpitPipe *self,
1116 const gchar *problem)
1117 {
1118 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1119
1120 g_return_if_fail (COCKPIT_IS_PIPE (self));
1121
1122 priv->closing = TRUE;
1123
1124 if (problem)
1125 close_immediately (self, problem);
1126 else if (g_queue_is_empty (priv->out_queue))
1127 close_output (self);
1128 else
1129 g_debug ("%s: pipe closing when output queue empty", priv->name);
1130 }
1131
1132 static gboolean
1133 on_later_close (gpointer user_data)
1134 {
1135 close_immediately (user_data, NULL); /* problem already set */
1136 return FALSE;
1137 }
1138
1139 static void
1140 cockpit_close_later (CockpitPipe *self)
1141 {
1142 GSource *source = g_idle_source_new ();
1143 g_source_set_priority (source, G_PRIORITY_HIGH);
1144 g_source_set_callback (source, on_later_close, g_object_ref (self), g_object_unref);
1145 g_source_attach (source, g_main_context_get_thread_default ());
1146 g_source_unref (source);
1147 }
1148
1149 /**
1150 * cockpit_pipe_connect:
1151 * @name: name for pipe, for debugging
1152 * @address: socket address to connect to
1153 *
1154 * Create a new pipe connected as a client to the given socket
1155 * address, which can be a unix or inet address. Will connect
1156 * in stream mode.
1157 *
1158 * If the connection fails, a pipe is still returned. It will
1159 * close once the main loop is run with an appropriate problem.
1160 *
1161 * Returns: (transfer full): newly allocated CockpitPipe.
1162 */
1163 CockpitPipe *
1164 cockpit_pipe_connect (const gchar *name,
1165 GSocketAddress *address)
1166 {
1167 gboolean connecting = FALSE;
1168 gsize native_len;
1169 gpointer native;
1170 CockpitPipe *pipe;
1171 CockpitPipePrivate *priv;
1172 int errn = 0;
1173 int sock;
1174
1175 g_return_val_if_fail (G_IS_SOCKET_ADDRESS (address), NULL);
1176
1177 sock = socket (g_socket_address_get_family (address), SOCK_STREAM, 0);
1178 if (sock < 0)
1179 {
1180 errn = errno;
1181 }
1182 else
1183 {
1184 if (!g_unix_set_fd_nonblocking (sock, TRUE, NULL))
1185 {
1186 close (sock);
1187 g_return_val_if_reached (NULL);
1188 }
1189
1190 native_len = g_socket_address_get_native_size (address);
1191 native = g_malloc (native_len);
1192 if (!g_socket_address_to_native (address, native, native_len, NULL))
1193 {
1194 close (sock);
1195 g_return_val_if_reached (NULL);
1196 }
1197 if (connect (sock, native, native_len) < 0)
1198 {
1199 if (errno == EINPROGRESS)
1200 {
1201 connecting = TRUE;
1202 }
1203 else
1204 {
1205 errn = errno;
1206 close (sock);
1207 sock = -1;
1208 }
1209 }
1210 g_free (native);
1211 }
1212
1213 pipe = g_object_new (COCKPIT_TYPE_PIPE,
1214 "in-fd", sock,
1215 "out-fd", sock,
1216 "name", name,
1217 NULL);
1218 priv = cockpit_pipe_get_instance_private (pipe);
1219
1220 priv->connecting = connecting;
1221 if (errn != 0)
1222 {
1223 set_problem_from_errno (pipe, "couldn't connect", errn);
1224 cockpit_close_later (pipe);
1225 }
1226
1227 return pipe;
1228 }
1229
1230 static GSpawnFlags
1231 calculate_spawn_flags (const gchar **env,
1232 CockpitPipeFlags pflags)
1233 {
1234 GSpawnFlags flags = G_SPAWN_DO_NOT_REAP_CHILD;
1235 gboolean path_flag = FALSE;
1236
1237 for (; env && env[0]; env++)
1238 {
1239 if (g_str_has_prefix (env[0], "PATH="))
1240 {
1241 flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
1242 path_flag = TRUE;
1243 break;
1244 }
1245 }
1246
1247 if (!path_flag)
1248 flags |= G_SPAWN_SEARCH_PATH;
1249
1250 if (pflags & COCKPIT_PIPE_STDERR_TO_NULL)
1251 flags |= G_SPAWN_STDERR_TO_DEV_NULL;
1252
1253 return flags;
1254 }
1255
1256 static void
1257 spawn_setup (gpointer data)
1258 {
1259 CockpitPipeFlags flags = GPOINTER_TO_INT (data);
1260
1261 /* Send this signal to all direct child processes, when bridge dies */
1262 #ifdef __linux
1263 prctl (PR_SET_PDEATHSIG, SIGHUP);
1264 #endif
1265
1266 if (flags & COCKPIT_PIPE_STDERR_TO_STDOUT) {
1267 int r = dup2 (1, 2);
1268 g_assert (r == 2); /* that should really never fail */
1269 }
1270 }
1271
1272 /**
1273 * cockpit_pipe_spawn:
1274 * @argv: null terminated string array of command arguments
1275 * @env: optional null terminated string array of child environment
1276 * @directory: optional working directory of child process
1277 * @flags: flags pertaining to stderr
1278 *
1279 * Launch a child process and create a CockpitPipe for it. Standard
1280 * in and standard out are connected to the pipe. The default location
1281 * for standard error usually goes to the journal.
1282 *
1283 * If the spawn fails, a pipe is still returned. It will
1284 * close once the main loop is run with an appropriate problem.
1285 *
1286 * NOTE: Although we could probably implement this as construct arguments
1287 * and without the @pipe_gtype argument, this is just simpler
1288 * for now.
1289 *
1290 * Returns: (transfer full): newly allocated CockpitPipe.
1291 */
1292 CockpitPipe *
1293 cockpit_pipe_spawn (const gchar **argv,
1294 const gchar **env,
1295 const gchar *directory,
1296 CockpitPipeFlags flags)
1297 {
1298 CockpitPipe *pipe = NULL;
1299 CockpitPipePrivate *priv;
1300 int session_stdin = -1;
1301 int session_stdout = -1;
1302 int session_stderr = -1;
1303 GError *error = NULL;
1304 const gchar *problem = NULL;
1305 int *with_stderr = NULL;
1306 gchar *name;
1307 GPid pid = 0;
1308
1309 if (flags & COCKPIT_PIPE_STDERR_TO_MEMORY)
1310 with_stderr = &session_stderr;
1311
1312 g_spawn_async_with_pipes (directory, (gchar **)argv, (gchar **)env,
1313 calculate_spawn_flags (env, flags),
1314 spawn_setup, GINT_TO_POINTER (flags),
1315 &pid, &session_stdin, &session_stdout, with_stderr, &error);
1316
1317 name = g_path_get_basename (argv[0]);
1318 if (name == NULL)
1319 name = g_strdup (argv[0]);
1320
1321 pipe = g_object_new (COCKPIT_TYPE_PIPE,
1322 "name", name,
1323 "in-fd", session_stdout,
1324 "out-fd", session_stdin,
1325 "err-fd", session_stderr,
1326 "pid", pid,
1327 NULL);
1328
1329 priv = cockpit_pipe_get_instance_private (pipe);
1330
1331 /* Regardless of whether spawn succeeded or not */
1332 priv->is_process = TRUE;
1333
1334 if (error)
1335 {
1336 if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))
1337 problem = "not-found";
1338 else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_PERM) ||
1339 g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))
1340 problem = "access-denied";
1341
1342 if (problem)
1343 {
1344 g_debug ("%s: couldn't run %s: %s", name, argv[0], error->message);
1345 }
1346 else
1347 {
1348 g_message ("%s: couldn't run %s: %s", name, argv[0], error->message);
1349 problem = "internal-error";
1350 }
1351 priv->problem = g_strdup (problem);
1352 cockpit_close_later (pipe);
1353 g_error_free (error);
1354 }
1355 else
1356 {
1357 g_debug ("%s: spawned: %s", name, argv[0]);
1358 }
1359
1360 g_free (name);
1361
1362 return pipe;
1363 }
1364
1365
1366 /**
1367 * cockpit_pipe_get_pid:
1368 * @self: a pipe
1369 *
1370 * Get the pid of this pipe or zero if not a process
1371 * pipe.
1372 *
1373 * Returns: the pid or zero
1374 */
1375 gboolean
1376 cockpit_pipe_get_pid (CockpitPipe *self,
1377 GPid *pid)
1378 {
1379 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1380
1381 g_return_val_if_fail (COCKPIT_IS_PIPE (self), FALSE);
1382 if (!priv->is_process)
1383 return FALSE;
1384 if (pid)
1385 *pid = priv->pid;
1386 return TRUE;
1387 }
1388
1389 /**
1390 * cockpit_pipe_is_closed:
1391 * @self: a pipe
1392 *
1393 * Returns: TRUE if the pipe is closed
1394 */
1395 gboolean
1396 cockpit_pipe_is_closed (CockpitPipe *self)
1397 {
1398 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1399
1400 g_return_val_if_fail (COCKPIT_IS_PIPE (self), FALSE);
1401
1402 return priv->closed;
1403 }
1404
1405 /**
1406 * cockpit_pipe_get_name:
1407 * @self: a pipe
1408 *
1409 * Get the name of the pipe.
1410 *
1411 * This is used for logging.
1412 *
1413 * Returns: (transfer none): the name
1414 */
1415 const gchar *
1416 cockpit_pipe_get_name (CockpitPipe *self)
1417 {
1418 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1419
1420 g_return_val_if_fail (COCKPIT_IS_PIPE (self), NULL);
1421 return priv->name;
1422 }
1423
1424 /**
1425 * cockpit_pipe_get_buffer:
1426 * @self: a pipe
1427 *
1428 * Get the input buffer for the pipe.
1429 *
1430 * This can change when the main loop is run. You can use
1431 * cockpit_pipe_consume() to consume data from it.
1432 *
1433 * Returns: (transfer none): the buffer
1434 */
1435 GByteArray *
1436 cockpit_pipe_get_buffer (CockpitPipe *self)
1437 {
1438 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1439
1440 g_return_val_if_fail (COCKPIT_IS_PIPE (self), NULL);
1441 return priv->in_buffer;
1442 }
1443
1444 GByteArray *
1445 cockpit_pipe_get_stderr (CockpitPipe *self)
1446 {
1447 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1448
1449 g_return_val_if_fail (COCKPIT_IS_PIPE (self), NULL);
1450 return priv->err_buffer;
1451 }
1452
1453 gchar *
1454 cockpit_pipe_take_stderr_as_utf8 (CockpitPipe *self)
1455 {
1456 GByteArray *buffer;
1457 GBytes *clean;
1458 gchar *data;
1459 gsize length;
1460
1461 drain_error (self);
1462
1463 buffer = cockpit_pipe_get_stderr (self);
1464 if (!buffer)
1465 return NULL;
1466
1467 /* A little more complicated to avoid big copies */
1468 g_byte_array_ref (buffer);
1469 g_byte_array_append (buffer, (guint8 *)"x", 1); /* place holder for null terminate */
1470
1471 {
1472 g_autoptr(GBytes) bytes = g_byte_array_free_to_bytes (buffer);
1473 clean = cockpit_unicode_force_utf8 (bytes);
1474 }
1475
1476 data = g_bytes_unref_to_data (clean, &length);
1477
1478 /* Fill in null terminate, for x above */
1479 g_assert (length > 0);
1480 data[length - 1] = '\0';
1481
1482 return data;
1483 }
1484
1485 /**
1486 * cockpit_pipe_exit_status:
1487 * @self: a pipe
1488 *
1489 * Get the exit status of a process pipe. This is only
1490 * valid if this pipe has a CockpitPipe:pid property
1491 * and the CockpitPipe::closed signal has fired.
1492 *
1493 * This is the raw exit status from waitpid() and friends
1494 * and needs to be checked if it's a signal or exit return
1495 * value.
1496 *
1497 * Returns: the exit signal.
1498 */
1499 gint
1500 cockpit_pipe_exit_status (CockpitPipe *self)
1501 {
1502 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1503
1504 g_return_val_if_fail (COCKPIT_IS_PIPE (self), -1);
1505 return priv->status;
1506 }
1507
1508 /**
1509 * cockpit_pipe_consume:
1510 * @buffer: a data buffer
1511 * @before: amount of preceding bytes to discard
1512 * @length: length of data to consume
1513 * @after: amount of trailing bytes to discard
1514 *
1515 * Used to consume data from the buffer passed to the
1516 * read signal.
1517 *
1518 * @before + @length + @after bytes will be removed from the @buffer,
1519 * and @length bytes will be returned.
1520 *
1521 * As an omptimization of @before + @length + @after is equal to the
1522 * entire length of the buffer, then the data will not
1523 * be copied but ownership will be transferred to the returned
1524 * bytes.
1525 *
1526 * Returns: (transfer full): the read bytes
1527 */
1528 GBytes *
1529 cockpit_pipe_consume (GByteArray *buffer,
1530 gsize before,
1531 gsize length,
1532 gsize after)
1533 {
1534 GBytes *bytes;
1535 guint8 *buf;
1536
1537 g_return_val_if_fail (buffer != NULL, NULL);
1538
1539 /* Optimize when we match full buffer length */
1540 if (buffer->len == before + length + after)
1541 {
1542 /* When array is reffed, this just clears byte array */
1543 g_byte_array_ref (buffer);
1544 buf = g_byte_array_free (buffer, FALSE);
1545 bytes = g_bytes_new_with_free_func (buf + before, length, g_free, buf);
1546 }
1547 else
1548 {
1549 bytes = g_bytes_new (buffer->data + before, length);
1550 g_byte_array_remove_range (buffer, 0, before + length + after);
1551 }
1552
1553 return bytes;
1554 }
1555
1556 /**
1557 * cockpit_pipe_skip:
1558 * @buffer: a data buffer
1559 * @skip: amount of bytes to skip
1560 *
1561 * Used to remove data from the front of the buffer.
1562 * @skip should be less than the number of bytes in
1563 * the buffer.
1564 */
1565 void
1566 cockpit_pipe_skip (GByteArray *buffer,
1567 gsize skip)
1568 {
1569 g_return_if_fail (buffer != NULL);
1570 g_byte_array_remove_range (buffer, 0, skip);
1571 }
1572
1573 /**
1574 * cockpit_pipe_new:
1575 * @name: a name for debugging
1576 * @in_fd: the input file descriptor
1577 * @out_fd: the output file descriptor
1578 *
1579 * Create a pipe for the given file descriptors.
1580 *
1581 * Returns: (transfer full): a new CockpitPipe
1582 */
1583 CockpitPipe *
1584 cockpit_pipe_new (const gchar *name,
1585 gint in_fd,
1586 gint out_fd)
1587 {
1588 return g_object_new (COCKPIT_TYPE_PIPE,
1589 "name", name,
1590 "in-fd", in_fd,
1591 "out-fd", out_fd,
1592 NULL);
1593 }
1594
1595 /**
1596 * cockpit_pipe_new_user_fd:
1597 * @name: a name for debugging
1598 * @fd: the file descriptor (might be input or output or both)
1599 *
1600 * Create a pipe for the given user-supplied opaque file descriptor. This is
1601 * not being read/written by cockpit itself, but intended for passing fds.
1602 *
1603 * Returns: (transfer full): a new CockpitPipe
1604 */
1605 CockpitPipe *
1606 cockpit_pipe_new_user_fd (const gchar *name,
1607 gint fd)
1608 {
1609 CockpitPipe *p = g_object_new (COCKPIT_TYPE_PIPE,
1610 "name", name,
1611 "in-fd", fd,
1612 "out-fd", fd,
1613 NULL);
1614 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (p);
1615 priv->is_user_fd = TRUE;
1616 return p;
1617 }
1618
1619 static void
1620 on_throttle_pressure (GObject *object,
1621 gboolean throttle,
1622 gpointer user_data)
1623 {
1624 CockpitPipe *self = COCKPIT_PIPE (user_data);
1625 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1626
1627 if (throttle)
1628 {
1629 if (priv->in_source != NULL)
1630 {
1631 g_debug ("%s: applying back pressure in pipe", priv->name);
1632 stop_input (self);
1633 }
1634 }
1635 else
1636 {
1637 if (priv->in_source == NULL && !priv->in_done)
1638 {
1639 g_debug ("%s: relieving back pressure in pipe", priv->name);
1640 start_input (self);
1641 }
1642 }
1643 }
1644
1645 static void
1646 cockpit_pipe_throttle (CockpitFlow *flow,
1647 CockpitFlow *controlling)
1648 {
1649 CockpitPipe *self = COCKPIT_PIPE (flow);
1650 CockpitPipePrivate *priv = cockpit_pipe_get_instance_private (self);
1651
1652 if (priv->pressure)
1653 {
1654 g_signal_handler_disconnect (priv->pressure, priv->pressure_sig);
1655 g_object_remove_weak_pointer (G_OBJECT (priv->pressure), (gpointer *)&priv->pressure);
1656 priv->pressure = NULL;
1657 }
1658
1659 if (controlling)
1660 {
1661 priv->pressure = controlling;
1662 g_object_add_weak_pointer (G_OBJECT (priv->pressure), (gpointer *)&priv->pressure);
1663 priv->pressure_sig = g_signal_connect (controlling, "pressure", G_CALLBACK (on_throttle_pressure), self);
1664 }
1665 }
1666
1667 static void
1668 cockpit_pipe_flow_iface_init (CockpitFlowInterface *iface)
1669 {
1670 iface->throttle = cockpit_pipe_throttle;
1671 }