capserver.c 11.3 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1
/*
2
 * Copyright (c) 2000-2012 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 timeval		timeout;
88
	struct group		*group;
89 90
	struct sigaction	sa;
	sigset_t		actionsigmask;
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

	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();

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

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

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

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

127 128 129 130 131 132 133 134 135
	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);

136 137 138 139 140 141 142 143 144
	/*
	 * 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;

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
	/*
	 * 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);

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
	/*
	 * 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);
	}
221
	if (listen(tcpsock, 40) < 0) {
222 223 224 225 226
		syslog(LOG_ERR, "listening on socket: %m");
		exit(1);
	}
	syslog(LOG_NOTICE, "listening on TCP port %d", ntohs(name.sin_port));

227 228 229 230 231 232 233 234 235 236 237 238 239
	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);
		}
	}

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

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

266 267 268 269 270 271 272 273 274 275 276 277
		/*
		 * Check IP address of server. Must be in tipservers table.
		 */
		for (srv = 0; srv < nservers; srv++)
			if (client.sin_addr.s_addr == servers[srv].ip.s_addr)
				break;
		if (srv == nservers) {
			syslog(LOG_ERR, "%s: Illegal server ignored.",
			       inet_ntoa(client.sin_addr));
			goto done;
		}

278 279 280 281
		/*
		 * Check port number of sender. Must be a reserved port.
		 */
		if (port >= IPPORT_RESERVED || port < IPPORT_RESERVED / 2) {
282 283
			syslog(LOG_ERR, "%s: Illegal port %d Ignoring.",
			       inet_ntoa(client.sin_addr), port);
284 285
			goto done;
		}
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

		/*
		 * 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;
		}
303 304
		
		/*
305
		 * Read and validate the whoami info.
306 307 308 309
		 */
		if ((cc = read(clientsock, &whoami, sizeof(whoami))) <= 0) {
			if (cc < 0)
				syslog(LOG_ERR, "Reading request: %m");
310 311
			syslog(LOG_ERR, "%s: Connection aborted (read)",
			       inet_ntoa(client.sin_addr));
312 313 314
			goto done;
		}
		if (cc != sizeof(whoami)) {
315 316 317 318 319 320 321
			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));
322 323 324 325 326 327 328 329 330
			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.
		 */
331
		res = mydb_query("select server,node_id,portnum from tiplines "
332
				 "where tipname='%s'",
333
				 3, whoami.name);
334 335
		if (!res) {
			syslog(LOG_ERR, "DB Error getting tiplines for %s!",
336
			       whoami.name);
337 338 339
			goto done;
		}
		if ((int)mysql_num_rows(res) == 0) {
340 341
			syslog(LOG_ERR, "%s: No tipline info for %s!",
			       inet_ntoa(client.sin_addr), whoami.name);
342 343 344
			mysql_free_result(res);
			goto done;
		}
345
		row = mysql_fetch_row(res);
346 347 348 349 350 351 352
		if (strcmp(row[0], servers[srv].name) != 0) {
			syslog(LOG_WARNING,
			       "%s: caller ('%s') is not the right server "
			       "('%s') for node '%s'",
			       inet_ntoa(client.sin_addr), servers[srv].name,
			       row[0], row[1]);
		}
353
		strcpy(node_id, row[1]);
354 355
		port = -1;
		sscanf(row[2], "%d", &port);
356 357 358 359 360 361
		mysql_free_result(res);

		/*
		 * Figure out current owner. Might not be a reserved node,
		 * in which case set it to root/wheel by default. 
		 */
362 363 364 365 366
		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 "
367 368 369 370 371 372 373 374 375 376
				 "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);
377

378
			tipown.uid = 0;
379 380 381 382
			if (row[0])
				tipown.gid = atoi(row[0]);
			else
				tipown.gid = admingid;
383 384 385 386 387 388
		}
		else {
			/*
			 * Default to root/root.
			 */
			tipown.uid = 0;
389
			tipown.gid = admingid;
390
		}
391 392
		mysql_free_result(res);

393 394 395 396
		if (whoami.portnum == -1) {
			reply = &port;
			reply_size = sizeof(port);
		}
397 398 399
		/*
		 * Update the DB.
		 */
400 401 402 403 404 405
		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)) {
406
			syslog(LOG_ERR, "DB Error updating tiplines for %s!",
407
			       whoami.name);
408 409
			goto done;
		}
410 411 412 413

		/*
		 * And now send the reply.
		 */
414
		if ((cc = write(clientsock, reply, reply_size)) <= 0) {
415 416 417 418 419
			if (cc < 0)
				syslog(LOG_ERR, "Writing reply: %m");
			syslog(LOG_ERR, "Connection aborted (write)");
			goto done;
		}
420
		if (cc != reply_size) {
421 422 423 424 425 426 427 428
			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);
429 430 431 432 433
	done:
		close(clientsock);
	}
	close(tcpsock);
	syslog(LOG_NOTICE, "daemon terminating");
434
	cleanup();
435 436 437
	exit(0);
}

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
void
sigterm(int sig)
{
	cleanup();
	exit(0);
}

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

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

#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;
}