capserver.c 11.5 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
/*
2
 * Copyright (c) 2000-2013 University of Utah and the Flux Group.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * 
 * {{{EMULAB-LICENSE
 * 
 * This file is part of the Emulab network testbed software.
 * 
 * This file is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 * 
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this file.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * }}}
22 23 24 25 26 27 28 29
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdio.h>
30
#include <paths.h>
31 32 33 34 35 36
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <assert.h>
#include <stdarg.h>
37
#include <errno.h>
38
#include <mysql/mysql.h>
39
#include <sys/time.h>
40
#include <signal.h>
41
#include <grp.h>
42
#include <netdb.h>
43
#include "capdecls.h"
44
#include "config.h"
45
#include "tbdb.h"
46 47 48 49 50

#define TESTMODE

static int	debug = 0;
static int	portnum = SERVERPORT;
51
static gid_t	admingid;
52 53 54
char		*Pidname;
void		sigterm(int);
void		cleanup(void);
55

56 57 58 59 60 61 62 63 64
static struct server {
	char *name;
	struct in_addr ip;
} *servers;
static int nservers; 

int regexinit(void);
int validwhoami(whoami_t *wai, int verbose);

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
char *usagestr = 
 "usage: capserver [-d] [-p #]\n"
 " -d              Turn on debugging.\n"
 " -p portnum	   Specify a port number to listen on.\n"
 "\n";

void
usage()
{
	fprintf(stderr, usagestr);
	exit(1);
}

int
main(int argc, char **argv)
{
	MYSQL_RES		*res;	
82
	MYSQL_ROW		row;
83
	int			tcpsock, ch;
84 85
	int			i, nrows;
	unsigned int		length;
86
	struct sockaddr_in	name;
87
	struct in_addr		bossaddr;
88
	struct timeval		timeout;
89
	struct group		*group;
90 91
	struct sigaction	sa;
	sigset_t		actionsigmask;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

	while ((ch = getopt(argc, argv, "dp:")) != -1)
		switch(ch) {
		case 'p':
			portnum = atoi(optarg);
			break;
		case 'd':
			debug++;
			break;
		case 'h':
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc)
		usage();

112
	openlog("capserver", LOG_PID, LOG_TESTBED);
113 114 115 116 117
	syslog(LOG_NOTICE, "daemon starting");

	if (!debug)
		(void)daemon(0, 0);

118 119 120 121 122
	if (!dbinit()) {
		syslog(LOG_ERR, "Could not connect to DB!");
		exit(1);
	}

123 124 125 126 127
	if (!regexinit()) {
		syslog(LOG_ERR, "Cannot compile REs!");
		exit(1);
	}

128 129 130 131 132 133 134 135 136
	sigemptyset(&actionsigmask);
	sigaddset(&actionsigmask, SIGINT);
	sigaddset(&actionsigmask, SIGTERM);
	memset(&sa, 0, sizeof sa);
	sa.sa_handler = sigterm;
	sa.sa_mask = actionsigmask;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

137 138
	inet_aton(BOSSNODE_IP, &bossaddr);

139 140 141 142 143 144 145 146 147
	/*
	 * Grab the GID for the default group.
	 */
	if ((group = getgrnam(TBADMINGROUP)) == NULL) {
		syslog(LOG_ERR, "Getting GID for %s", TBADMINGROUP);
		exit(1);
	}
	admingid = group->gr_gid;

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
	/*
	 * Find all the allowed tipserver machines and resolve their names.
	 */
	res = mydb_query("select server from tipservers", 1);
	if (!res) {
		syslog(LOG_ERR, "DB Error getting tipservers from DB!");
		exit(1);
	}
	if ((nrows = (int)mysql_num_rows(res)) == 0) {
		syslog(LOG_ERR, "No tipservers in DB!");
		mysql_free_result(res);
		exit(1);
	}

	servers = calloc(nrows, sizeof(struct sockaddr_in));
	if (servers == NULL) {
		syslog(LOG_ERR, "No memory for %d tipservers!", nrows);
		mysql_free_result(res);
		exit(1);
	}

	nservers = 0;
	while (nrows > 0) {
		struct hostent *he;

		nrows--;
		row = mysql_fetch_row(res);
		if ((he = gethostbyname(row[0])) == NULL) {
			syslog(LOG_WARNING,
			       "Could not resolve hostname '%s', ignored",
			       row[0]);
			continue;
		}
		if (he->h_addrtype != AF_INET ||
		    he->h_length != sizeof(struct in_addr)) {
			syslog(LOG_WARNING,
			       "Unknown addrtype/size for '%s', ignored",
			       row[0]);
			continue;
		}
		servers[nservers].name = strdup(row[0]);
		servers[nservers].ip = *(struct in_addr *)he->h_addr;
		nservers++;
	}
	mysql_free_result(res);

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
	/*
	 * Setup TCP socket
	 */

	/* Create socket from which to read. */
	tcpsock = socket(AF_INET, SOCK_STREAM, 0);
	if (tcpsock < 0) {
		syslog(LOG_ERR, "opening stream socket: %m");
		exit(1);
	}

	i = 1;
	if (setsockopt(tcpsock, SOL_SOCKET, SO_REUSEADDR,
		       (char *)&i, sizeof(i)) < 0)
		syslog(LOG_ERR, "control setsockopt: %m");;
	
	/* Create name. */
	name.sin_family = AF_INET;
	name.sin_addr.s_addr = INADDR_ANY;
	name.sin_port = htons((u_short) portnum);
	if (bind(tcpsock, (struct sockaddr *) &name, sizeof(name))) {
		syslog(LOG_ERR, "binding stream socket: %m");
		exit(1);
	}
	/* Find assigned port value and print it out. */
	length = sizeof(name);
	if (getsockname(tcpsock, (struct sockaddr *) &name, &length)) {
		syslog(LOG_ERR, "getting socket name: %m");
		exit(1);
	}
224
	if (listen(tcpsock, 40) < 0) {
225 226 227 228 229
		syslog(LOG_ERR, "listening on socket: %m");
		exit(1);
	}
	syslog(LOG_NOTICE, "listening on TCP port %d", ntohs(name.sin_port));

230 231 232 233 234 235 236 237 238 239 240 241 242
	if (!getuid()) {
		FILE	*fp;
		char    mybuf[BUFSIZ];
	    
		sprintf(mybuf, "%s/capserver.pid", _PATH_VARRUN);
		fp = fopen(mybuf, "w");
		if (fp != NULL) {
			fprintf(fp, "%d\n", getpid());
			(void) fclose(fp);
			Pidname = strdup(mybuf);
		}
	}

243 244
	while (1) {
		struct sockaddr_in client;
245 246
		int		   clientsock;
		int		   cc, port, srv;
247
		whoami_t	   whoami;
248
		char		   node_id[64], *server = "";
249
		tipowner_t	   tipown;
250 251
		void		  *reply = &tipown;
		size_t		   reply_size = sizeof(tipown);
252

253
		length = sizeof(client);
254 255 256
		if ((clientsock = accept(tcpsock,
					 (struct sockaddr *)&client,
					 &length)) < 0) {
257 258 259 260 261 262
			if (errno == ECONNABORTED) {
				syslog(LOG_ERR, "accept failed: %m; "
				       "continuing");
				continue;
			}
			syslog(LOG_ERR, "accept failed: %m; exiting");
263 264
			exit(1);
		}
265 266 267 268
		port = ntohs(client.sin_port);
		syslog(LOG_INFO, "%s connected from port %d",
		       inet_ntoa(client.sin_addr), port);

269 270 271
		/*
		 * Check IP address of server. Must be in tipservers table.
		 */
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
		if (client.sin_addr.s_addr == bossaddr.s_addr) {
			server = BOSSNODE;
		}
		else {
			for (srv = 0; srv < nservers; srv++)
				if (client.sin_addr.s_addr ==
				    servers[srv].ip.s_addr) {
					server = servers[srv].name;
					break;
				}
			if (srv == nservers) {
				syslog(LOG_ERR, "%s: Illegal server ignored.",
				       inet_ntoa(client.sin_addr));
				goto done;
			}
287 288
		}

289 290 291 292
		/*
		 * Check port number of sender. Must be a reserved port.
		 */
		if (port >= IPPORT_RESERVED || port < IPPORT_RESERVED / 2) {
293 294
			syslog(LOG_ERR, "%s: Illegal port %d Ignoring.",
			       inet_ntoa(client.sin_addr), port);
295 296
			goto done;
		}
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

		/*
		 * Set timeouts
		 */
		timeout.tv_sec  = 6;
		timeout.tv_usec = 0;
		
		if (setsockopt(clientsock, SOL_SOCKET, SO_RCVTIMEO,
			       &timeout, sizeof(timeout)) < 0) {
			syslog(LOG_ERR, "SO_RCVTIMEO failed: %m");
			goto done;
		}
		if (setsockopt(clientsock, SOL_SOCKET, SO_SNDTIMEO,
			       &timeout, sizeof(timeout)) < 0) {
			syslog(LOG_ERR, "SO_SNDTIMEO failed: %m");
			goto done;
		}
314 315
		
		/*
316
		 * Read and validate the whoami info.
317 318 319 320
		 */
		if ((cc = read(clientsock, &whoami, sizeof(whoami))) <= 0) {
			if (cc < 0)
				syslog(LOG_ERR, "Reading request: %m");
321 322
			syslog(LOG_ERR, "%s: Connection aborted (read)",
			       inet_ntoa(client.sin_addr));
323 324 325
			goto done;
		}
		if (cc != sizeof(whoami)) {
326 327 328 329 330 331 332
			syslog(LOG_ERR, "%s: Wrong byte count (read)!",
			       inet_ntoa(client.sin_addr));
			goto done;
		}
		if (!validwhoami(&whoami, debug)) {
			syslog(LOG_ERR, "%s: Invalid whoami info ignored",
			       inet_ntoa(client.sin_addr));
333 334 335 336 337 338 339 340 341
			goto done;
		}

		/*
		 * Make sure there is an entry for this tipline in
		 * the DB. If not, we just drop the info with an error
		 * message in the log file. Local tip will still work but
		 * remote tip will not.
		 */
342
		res = mydb_query("select server,node_id,portnum from tiplines "
343
				 "where tipname='%s'",
344
				 3, whoami.name);
345 346
		if (!res) {
			syslog(LOG_ERR, "DB Error getting tiplines for %s!",
347
			       whoami.name);
348 349 350
			goto done;
		}
		if ((int)mysql_num_rows(res) == 0) {
351 352
			syslog(LOG_ERR, "%s: No tipline info for %s!",
			       inet_ntoa(client.sin_addr), whoami.name);
353 354 355
			mysql_free_result(res);
			goto done;
		}
356
		row = mysql_fetch_row(res);
357
		if (strcmp(row[0], server) != 0) {
358 359 360
			syslog(LOG_WARNING,
			       "%s: caller ('%s') is not the right server "
			       "('%s') for node '%s'",
361
			       inet_ntoa(client.sin_addr), server,
362 363
			       row[0], row[1]);
		}
364
		strcpy(node_id, row[1]);
365 366
		port = -1;
		sscanf(row[2], "%d", &port);
367 368 369 370 371 372
		mysql_free_result(res);

		/*
		 * Figure out current owner. Might not be a reserved node,
		 * in which case set it to root/wheel by default. 
		 */
373 374 375 376 377
		res = mydb_query("select g.unix_gid from reserved as r "
				 "left join experiments as e on "
				 " r.pid=e.pid and r.eid=e.eid "
				 "left join groups as g on "
				 " g.pid=e.pid and g.gid=e.gid "
378 379 380 381 382 383 384 385 386 387
				 "where r.node_id='%s'",
				 1, node_id);

		if (!res) {
			syslog(LOG_ERR, "DB Error getting info for %s/%s!",
			       node_id, whoami.name);
			goto done;
		}
		if ((int)mysql_num_rows(res)) {
			row = mysql_fetch_row(res);
388

389
			tipown.uid = 0;
390 391 392 393
			if (row[0])
				tipown.gid = atoi(row[0]);
			else
				tipown.gid = admingid;
394 395 396 397 398 399
		}
		else {
			/*
			 * Default to root/root.
			 */
			tipown.uid = 0;
400
			tipown.gid = admingid;
401
		}
402 403
		mysql_free_result(res);

404 405 406 407
		if (whoami.portnum == -1) {
			reply = &port;
			reply_size = sizeof(port);
		}
408 409 410
		/*
		 * Update the DB.
		 */
411 412 413 414 415 416
		else if (! mydb_update("update tiplines set portnum=%d, "
				       "keylen=%d, keydata='%s' "
				       "where tipname='%s'", 
				       whoami.portnum,
				       whoami.key.keylen, whoami.key.key,
				       whoami.name)) {
417
			syslog(LOG_ERR, "DB Error updating tiplines for %s!",
418
			       whoami.name);
419 420
			goto done;
		}
421 422 423 424

		/*
		 * And now send the reply.
		 */
425
		if ((cc = write(clientsock, reply, reply_size)) <= 0) {
426 427 428 429 430
			if (cc < 0)
				syslog(LOG_ERR, "Writing reply: %m");
			syslog(LOG_ERR, "Connection aborted (write)");
			goto done;
		}
431
		if (cc != reply_size) {
432 433 434 435 436 437 438 439
			syslog(LOG_ERR, "Wrong byte count (write)!");
			goto done;
		}

		syslog(LOG_INFO,
		       "Tipline %s/%s, Port %d, Keylen %d, Key %s, Group %d\n",
		       node_id, whoami.name, whoami.portnum,
		       whoami.key.keylen, whoami.key.key, tipown.gid);
440 441 442 443 444
	done:
		close(clientsock);
	}
	close(tcpsock);
	syslog(LOG_NOTICE, "daemon terminating");
445
	cleanup();
446 447 448
	exit(0);
}

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
void
sigterm(int sig)
{
	cleanup();
	exit(0);
}

void
cleanup(void)
{
	syslog(LOG_NOTICE, "daemon exiting by signal");

	if (Pidname)
	    (void) unlink(Pidname);
}
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

#include <regex.h>
static regex_t re_nodeid, re_keystr;

int
regexinit(void)
{
	/* XXX get these from DB */
	if (regcomp(&re_nodeid, "^[-[:alnum:]_]+$",
		    REG_EXTENDED|REG_ICASE|REG_NOSUB))
		return 0;
	if (regcomp(&re_keystr, "^[0-9a-f]+$",
		    REG_EXTENDED|REG_ICASE|REG_NOSUB))
		return 0;

	return 1;
}

int
validwhoami(whoami_t *wai, int verbose)
{
	wai->name[sizeof(wai->name)-1] = '\0';
	if (regexec(&re_nodeid, wai->name, 0, NULL, 0)) {
		if (verbose)
			syslog(LOG_ERR, "Invalid node name string");
		return 0;
	}
	if (wai->portnum != -1 && (wai->portnum < 1 || wai->portnum > 65535)) {
		if (verbose)
			syslog(LOG_ERR, "Invalid port number");
		return 0;
	}
	if (wai->key.keylen < 0 || wai->key.keylen >= sizeof(wai->key.key)) {
		if (verbose)
			syslog(LOG_ERR, "Invalid key length");
		return 0;
	}
	wai->key.key[wai->key.keylen] = '\0';
	if (regexec(&re_keystr, wai->key.key, 0, NULL, 0)) {
		if (verbose)
			syslog(LOG_ERR, "Invalid key string");
		return 0;
	}

	return 1;
}