summaryrefslogtreecommitdiffstats
path: root/qarshd.c
blob: 78b9dda5d5d80a79a2d623d2ea62d3502bb0c3f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
/*
 * Copyright © 2005-2008  Red Hat, Inc. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions of the
 * GNU General Public License v.2.  This program is distributed in the hope
 * that it will be useful, but WITHOUT ANY WARRANTY expressed or implied,
 * including the implied warranties of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
 * trademarks that are incorporated in the source code or documentation are not
 * subject to the GNU General Public License and may only be used or replicated
 * with the express permission of Red Hat, Inc.
 *
 * Red Hat Author(s): Nathan Straz <nstraz@redhat.com>
 *                    Dean Jansa <djansa@redhat.com>
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <assert.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/sendfile.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pwd.h>
#include <grp.h>
#include <stdarg.h>


#include "sockutil.h"
#include "qarsh_packet.h"

#define QARSHD_BUFSIZE QARSH_MAX_PACKET_SIZE/2
/*
 * QA Remote Shell Daemon
 */

int debug = 0;
int dopause = 0;

/* Globals */
const int qinfd = 0; /* qarshd in file descriptor */
const int qoutfd = 1; /* qarshd out file descriptor */
int child_exitted = 0;
pid_t child_pid;
sigset_t orig_sigmask;
int childfds[3] = { -1, -1, -1 }; /* pipes to child for stdin/stdout/stderr */
int receivefd = -1;
off_t recvsize = 0;
off_t received = 0;

/* A mini cache for rstat so we can check it in pushfile */
char *saved_path = NULL;
struct stat saved_stat;

void
lprintf(int priority, const char *format, ...)
{
	char buf[4096];
	va_list ap;

	va_start(ap, format);
	vsnprintf(buf, 4096, format, ap);
	va_end(ap);

	syslog(priority, "%s", buf);
}

int
setup_user(char *user, char *group)
{
	struct passwd *pw;
	struct group *grp;

	if ((pw = getpwnam(user)) == NULL) {
		syslog(LOG_WARNING, "User \"%s\" not found\n", user);
		return 0;
	}

	if (group && (grp = getgrnam(group))) {
		setgid(grp->gr_gid);
		initgroups(pw->pw_name, grp->gr_gid);
	} else {
		setgid(pw->pw_gid);
		initgroups(pw->pw_name, pw->pw_gid);
	}

	/* setuid is last so we can still do setgid and initgroups */
	setuid(pw->pw_uid);

	if (pw->pw_dir) chdir(pw->pw_dir);
	
	return 1;
}

void
sig_handler(int sig)
{
	if (sig == SIGCHLD) child_exitted++;
}

pid_t 
run_cmd(const char *cmd)
{
	pid_t pid;
	int pipefds[2], parentfds[3];

	pipe(pipefds);
	childfds[0] = pipefds[1]; parentfds[0] = pipefds[0]; /* stdin */
	pipe(pipefds);
	childfds[1] = pipefds[0]; parentfds[1] = pipefds[1]; /* stdout */
	pipe(pipefds);
	childfds[2] = pipefds[0]; parentfds[2] = pipefds[1]; /* stderr */


	syslog(LOG_INFO, "Running cmdline: %s\n", cmd);
	if ((pid = fork()) < 0) {
		syslog(LOG_WARNING, 
			"Could not fork() in run_cmd(): %s\n", strerror(errno));
		exit(1);
	}

	if (pid == 0) { /* child */
		setpgrp();
		sigprocmask(SIG_SETMASK, &orig_sigmask, NULL);

		/* Connect stdin, stdout, and stderr to parent's pipes */
		dup2(parentfds[0], fileno(stdin));
		dup2(parentfds[1], fileno(stdout));
		dup2(parentfds[2], fileno(stderr));
		/* close end of pipes we're not using */
		close(parentfds[0]);
		close(parentfds[1]);
		close(parentfds[2]);
		close(childfds[0]);
		close(childfds[1]);
		close(childfds[2]);

		execlp("sh", "sh", "-c", cmd, NULL);
		fprintf(stderr, "exec of %s failed: %d, %s\n", cmd, errno, strerror(errno));
		exit(127);
	} 
	close(parentfds[0]);
	close(parentfds[1]);
	close(parentfds[2]);
	return pid;
}

struct qa_packet *
prepare_recvfile(struct qa_packet *qp)
{
	int fd;

	syslog(LOG_INFO, "Receive file %s, size = %lld, mode = %o\n",
		qp->qp_recvfile.qp_path,
		(long long int)qp->qp_recvfile.qp_count,
		qp->qp_recvfile.qp_mode);

	if ((fd = open(qp->qp_recvfile.qp_path, O_TRUNC|O_CREAT|O_WRONLY,
					qp->qp_recvfile.qp_mode)) < 0) {
		syslog(LOG_WARNING, "Could not open %s to receive file: %s\n",
				qp->qp_recvfile.qp_path, strerror(errno));
		return make_qp_returncode(-1, errno, strerror(errno));
	}

	/* Set permissions again to override umask */
	fchmod(fd, qp->qp_recvfile.qp_mode);

	/* Store fd to check data packets against */
	receivefd = fd;
	recvsize = qp->qp_recvfile.qp_count;
	received = 0;

	return make_qp_data_allow(0, QARSHD_BUFSIZE);
}

struct qa_packet *
receive_data(struct qa_packet *qp)
{
	ssize_t ret, nwrote;

	if (qp->qp_data.qp_count == 0) { /* EOF */
		close(receivefd);
		if (debug) syslog(LOG_DEBUG, "Transfer complete\n");
		return make_qp_returncode(0, 0, "Transfer complete");
	}
	if (debug) syslog(LOG_DEBUG, "Data for %d, %d@%ld\n",
			receivefd, qp->qp_data.qp_count, qp->qp_data.qp_offset);
	nwrote = 0;
	do {
		ret = write(receivefd, qp->qp_data.qp_blob + nwrote, qp->qp_data.qp_count - nwrote);
		if (ret < 0) {
			return make_qp_returncode(-1, errno, strerror(errno));
		} 
		nwrote += ret;
	} while (nwrote < qp->qp_data.qp_count);
	received += nwrote;
	return make_qp_data_allow(0, nwrote);
}

ssize_t
pushfile(const char *path)
{
	int infd;
	off_t offset;
	ssize_t nbytes, fsize = 0;
	struct stat sb;
	const int bufsize = 16384;
	char buf[bufsize];
	struct qa_packet *qp;

	infd = open(path, O_RDONLY);
	if (infd == -1) {
		syslog(LOG_WARNING, "Could not open %s: %s\n",
		       path, strerror(errno));
		return -1;
	}

	if (strcmp(saved_path, path)) {
		if (fstat(infd, &sb) < 0) {
			syslog(LOG_WARNING, "Could not stat %s: %s\n",
		 			path, strerror(errno));
			close(infd);
			return -1;
		} else {
			fsize = sb.st_size;
		}
	} else {
		fsize = saved_stat.st_size;
	}
	if (!fsize) {
		fprintf(stderr, "Unknown file size to send\n");
		close(infd);
		return -1;
	}
	offset = 0;
	do {
		nbytes = read(infd, buf, bufsize);
		if (nbytes < 0) {
			fprintf(stderr, "read() error: %s\n", strerror(errno));
			qp = make_qp_returncode(-1, errno, strerror(errno));
		} else {
			qp = make_qp_data(0, offset, nbytes, buf);
		}
		send_packet(qoutfd, qp);
		offset += nbytes;
		qpfree(qp);
	} while (nbytes > 0);

	close(infd);

	return offset;
}

void
save_stat(const char *path, const struct stat *sb)
{
	if (saved_path) free(saved_path);
	saved_path = strdup(path);
	memcpy(&saved_stat, sb, sizeof saved_stat);
}

struct qa_packet *
rstat(const char *path)
{
	struct stat sb;
	struct qa_packet *rp;

	if (stat(path, &sb) < 0) {
		rp = make_qp_returncode(-1, errno, strerror(errno));
	} else {
		rp =  make_qp_rstat(path, &sb);
	}
	save_stat(path, &sb);

	return rp;
}

/* Handle only qarsh related packets */
void
handle_qarsh()
{
	fd_set rfds, wfds;
	int nfd, maxfd;
	struct timespec timeout;
	sigset_t sigmask;
	struct sigaction sa;
	int child_status;
	struct qa_packet *qp = NULL, *rp = NULL;
	int allowed_out = 0, allowed_err = 0; /* number of bytes we can send to client */
	char buf[QARSHD_BUFSIZE];		/* short term buffer for stdout and stderr */
	char buf_in[QARSHD_BUFSIZE];	/* long term buffer for stdin */
	int z_in = 0;		/* Number of bytes in stdin buffer */
	int eof_in = 0;		/* Have we seen EOF on stdin yet? */
	int nbytes;

	sigemptyset(&sigmask);
	sigaddset(&sigmask, SIGCHLD);
	sigprocmask(SIG_BLOCK, &sigmask, &orig_sigmask);
	sa.sa_handler = sig_handler;
	sa.sa_mask = sigmask;
	sa.sa_flags = SA_RESTART;
	sigaction(SIGCHLD, &sa, NULL);
	signal(SIGPIPE, SIG_IGN);

	qp = make_qp_data_allow(0, QARSHD_BUFSIZE);
	send_packet(qoutfd, qp);
	qpfree(qp);
	
	for (;;) {

		timeout.tv_sec = 3;
		timeout.tv_nsec = 0;
		FD_ZERO(&rfds); FD_ZERO(&wfds);
		FD_SET(qinfd, &rfds);
		maxfd = qinfd;
		if (childfds[0] > -1 && z_in) {
			FD_SET(childfds[0], &wfds);
			maxfd = childfds[0] > maxfd ? childfds[0] : maxfd;
		}
		if (childfds[1] > -1 && allowed_out) {
			FD_SET(childfds[1], &rfds);
			maxfd = childfds[1] > maxfd ? childfds[1] : maxfd;
		}
		if (childfds[2] > -1 && allowed_err) {
			FD_SET(childfds[2], &rfds);
			maxfd = childfds[2] > maxfd ? childfds[2] : maxfd;
		}

		nfd = pselect(maxfd+1, &rfds, &wfds, NULL, &timeout, &orig_sigmask);

		if (child_exitted) {
			waitpid(child_pid, &child_status, 0);
			child_exitted--;
			child_pid = 0;
			rp = make_qp_cmdexit(child_pid, child_status);
			send_packet(qoutfd, rp);
			qpfree(rp);
		}
		if (nfd < 0) {
			if (errno == EINTR) {
				/* signals handled above here */
				continue;
			} else {
				syslog(LOG_ERR, "select errno %d, %s\n", 
				       errno, strerror(errno));
			}
		} else if (nfd > 0) {
			if (nfd && FD_ISSET(qinfd, &rfds)) {
				qp = recv_packet(qinfd);
				if (qp == NULL) {
					if (debug) syslog(LOG_DEBUG, "That's enough\n");
					break;
				}
				if (debug) dump_qp(qp);
				switch(qp->qp_type) {
				case QP_KILL:
					if (child_pid) {
						syslog(LOG_INFO, "Sending child %d signal %d", 
							child_pid, qp->qp_kill.qp_sig);
						kill(child_pid * -1, qp->qp_kill.qp_sig);
					}
					break;
				case QP_RUNCMD:
					syslog(LOG_ERR, "Only one command allowed per connection");
					break;
				case QP_DATA:
					if (qp->qp_data.qp_remfd != 0) {
						syslog(LOG_ERR, "Received data for fd %d\n", qp->qp_data.qp_remfd);
						break;
					}
					if (qp->qp_data.qp_count > (QARSHD_BUFSIZE - z_in)) {
						syslog(LOG_ERR, "Received too much data for fd %d, %d > %d\n",
								qp->qp_data.qp_remfd, qp->qp_data.qp_count, QARSHD_BUFSIZE - z_in);
						break;
					}
					if (eof_in) {
						syslog(LOG_ERR, "Received data on stdin after EOF\n");
						break;
					}
					if (qp->qp_data.qp_count == 0) {
						eof_in = 1;
						if (z_in == 0) {
							close(childfds[0]);
							childfds[0] = -1;
						}
					} else {
						memcpy(buf_in+z_in, qp->qp_data.qp_blob, qp->qp_data.qp_count);
						z_in += qp->qp_data.qp_count;
					}
					break;
				case QP_DALLOW:
					if (qp->qp_dallow.qp_remfd == 1) {
						allowed_out += qp->qp_dallow.qp_count;
					} else if (qp->qp_dallow.qp_remfd == 2) {
						allowed_err += qp->qp_dallow.qp_count;
					} else {
						syslog(LOG_ERR, "Received data allow for fd %d\n", qp->qp_dallow.qp_remfd);
					}
					break;
				default:
					syslog(LOG_ERR, "Unexpected message type %s", qp_packet_type(qp->qp_type));
					break;
				}
				nfd--;
				qpfree(qp);
			}
			if (nfd && FD_ISSET(childfds[0], &wfds)) {
				/* Child is ready for data on stdin */
				nbytes = write(childfds[0], buf_in, z_in);
				if (nbytes == -1) {  /* Don't try writing to the child again */
					close(childfds[0]);
					childfds[0] = -1;
					qp = make_qp_returncode(-1, errno, strerror(errno));
					send_packet(qoutfd, qp);
					qpfree(qp);
				} else if (nbytes == z_in) {
					z_in = 0;
					if (eof_in) {
						close(childfds[0]);
						childfds[0] = -1;
					}
				} else {
					memmove(buf_in, buf_in+nbytes, z_in - nbytes);
					z_in -= nbytes;
				}
				if (!eof_in && nbytes > 0) {
					qp = make_qp_data_allow(0, nbytes);
					send_packet(qoutfd, qp);
					qpfree(qp);
				}
				nfd--;
			}
			if (nfd && FD_ISSET(childfds[1], &rfds)) {
				/* Child has something to send to stdout */
				nbytes = read(childfds[1], buf, allowed_out);
				qp = make_qp_data(1, 0, nbytes, buf);
				send_packet(qoutfd, qp);
				qpfree(qp);
				allowed_out -= nbytes;
				if (nbytes == 0) {
					close(childfds[1]);
					childfds[1] = -1;
					allowed_out = 0;
				}
				nfd--;
			}
			if (nfd && FD_ISSET(childfds[2], &rfds)) {
				/* Child has something to send to stderr */
				nbytes = read(childfds[2], buf, allowed_err);
				qp = make_qp_data(2, 0, nbytes, buf);
				send_packet(qoutfd, qp);
				qpfree(qp);
				allowed_err -= nbytes;
				if (nbytes == 0) {
					close(childfds[2]);
					childfds[2] = -1;
					allowed_err = 0;
				}
				nfd--;
			}

		} else {
			if (debug) syslog(LOG_DEBUG, "Nothing to do in handle_qarsh\n");
		}
	}
}

void
handle_packets()
{
	fd_set rfds;
	int nfd;
	struct timeval timeout;
	struct qa_packet *qp = NULL, *rp = NULL;

	off_t nbytes;	

	if (dopause) {
		signal(SIGALRM, sig_handler);
		pause();
		signal(SIGALRM, SIG_DFL);
	}

	for (;;) {
		FD_SET(qinfd, &rfds);
		timeout.tv_sec = 3;
		timeout.tv_usec = 0;

		nfd = select(qinfd+1, &rfds, NULL, NULL, &timeout);
		if (nfd < 0) {
			if (errno == EINTR) {
				/* signals handled above here */
				continue;
			} else {
				syslog(LOG_ERR, "select errno %d, %s\n", 
				       errno, strerror(errno));
			}
		} else if (nfd > 0) {
			qp = recv_packet(qinfd);
			if (qp == NULL) {
				if (debug) syslog(LOG_DEBUG, "That's enough\n");
				break;
			}
			if (debug) dump_qp(qp);
			switch (qp->qp_type) {
			case QP_SETUSER:
				if (setup_user(qp->qp_setuser.qp_user,
						qp->qp_setuser.qp_group) == 0) {
					rp = make_qp_returncode(-1, 0, "User not found");
				} else {
					rp = make_qp_ack(QP_SETUSER, 1);
				}
				send_packet(qoutfd, rp);
				qpfree(rp);
				break;
			case QP_RUNCMD:
				child_pid = run_cmd(qp->qp_runcmd.qp_cmdline);
				qpfree(qp);
				handle_qarsh(); /* continue processing qarsh separately */
				return;
				break;
			case QP_RECVFILE: /* Setup file descriptors to handle incoming data */
				rp = prepare_recvfile(qp);
				send_packet(qoutfd, rp);
				qpfree(rp);
				break;
			case QP_DATA:
				rp = receive_data(qp);
				if (rp) {
					send_packet(qoutfd, rp);
					qpfree(rp);
				}
				break;
			case QP_SENDFILE:
				syslog(LOG_INFO, "Sending file %s\n",
				        qp->qp_sendfile.qp_path);
				nbytes = pushfile(qp->qp_sendfile.qp_path);
				if (nbytes < 0) {
					rp = make_qp_returncode(-1, errno, strerror(errno));
				} else {
					rp = make_qp_returncode(0, 0, "Transfer Complete");
				}
				send_packet(qoutfd, rp);
				qpfree(rp);
				break;
			case QP_RSTAT:
				if (debug) syslog(LOG_DEBUG, "Got a QP_RSTAT with path = %s\n",
				       qp->qp_rstat.qp_path);
				rp = rstat(qp->qp_rstat.qp_path);
				send_packet(qoutfd, rp);
				qpfree(rp);
				break;
			default:
				syslog(LOG_WARNING, 
					"Packet type %s unimplemented",
					qp_packet_type(qp->qp_type));
			}
			qpfree(qp);
		} else {
			if (debug) syslog(LOG_DEBUG, "Nothing to do in handle_packets\n");
		}
		
	}
}

int
main(int argc, char *argv[])
{
	int ch;
	socklen_t peerlen;
	struct sockaddr_storage peername;
	char peer_hoststr[NI_MAXHOST];
	char peer_portstr[NI_MAXSERV];

	openlog("qarshd", LOG_PID, LOG_DAEMON);

	while ((ch = getopt(argc, argv, "pd")) != -1) {
		switch (ch) {
			case 'd':
				debug = 1;
				break;
			case 'p':
				dopause = 1;
				break;
			case '?':
			default:
				printf("unknown option '%c'\n", optopt);
				exit(1);
		}
	}

	/* daemon initialization */
	peerlen = sizeof peername;
	getpeername(0, (struct sockaddr *)&peername, &peerlen);
	getnameinfo((struct sockaddr *)&peername, peerlen, 
	            peer_hoststr, NI_MAXHOST, peer_portstr, 
	            NI_MAXSERV, NI_NUMERICHOST);
	syslog(LOG_INFO, "Talking to peer %s:%s (%s)", peer_hoststr, peer_portstr,
		peername.ss_family == AF_INET ? "IPv4" : "IPv6");

	/* Start reading packets from stdin */
	handle_packets();

	return 0;
}