libtmcd.c 167 KB
Newer Older
1
/*
2
 * Copyright (c) 2008-2011 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 30 31 32 33 34 35 36 37 38
#include "libtmcd.h"

#include <libxml/tree.h>
#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <signal.h>
#include <setjmp.h>
#include <sys/time.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/param.h>
39
#include "tmcd.h"
40 41 42 43 44 45 46 47 48
#include "log.h"
#include "config.h"
#include "bootwhat.h"
#include "bootinfo.h"

#ifdef EVENTSYS
#include "event.h"
#endif

49 50 51 52 53
#define	XML_MIME_TYPE	"text/xml"
#define	GZIP_MIME_TYPE	"application/x-gzip"

int debug = 0;

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
/*
 * XXX This needs to be localized!
 */
#define FSPROJDIR	FSNODE ":" FSDIR_PROJ
#define FSGROUPDIR	FSNODE ":" FSDIR_GROUPS
#define FSUSERDIR	FSNODE ":" FSDIR_USERS
#ifdef  FSDIR_SHARE
#define FSSHAREDIR	FSNODE ":" FSDIR_SHARE
#endif
#ifdef  FSDIR_SCRATCH
#define FSSCRATCHDIR	FSNODE ":" FSDIR_SCRATCH
#endif
#define PROJDIR		PROJROOT_DIR
#define GROUPDIR	GROUPSROOT_DIR
#define USERDIR		USERSROOT_DIR
#define SCRATCHDIR	SCRATCHROOT_DIR
#define SHAREDIR	SHAREROOT_DIR
#define NETBEDDIR	"/netbed"
#define PLISALIVELOGDIR "/usr/testbed/log/plabisalive"
#define RELOADPID	"emulab-ops"
#define RELOADEID	"reloading"
#define FSHOSTID	"/usr/testbed/etc/fshostid"
#define DOTSFS		".sfs"
#define NTPSERVER       "ntp1"
#define DEFAULTNETMASK	"255.255.255.0"

/* Defined in configure and passed in via the makefile */
#define DEFAULT_DBNAME	TBDBNAME
#define DBNAME_SIZE	64
#define HOSTID_SIZE	(32+64)

/* Output macro to check for string overflow */
#define OUTPUT(buf, size, format...) \
({ \
	int __count__ = snprintf((buf), (size), ##format); \
        \
        if (__count__ >= (size)) { \
		error("Not enough room in output buffer! line %d.\n", __LINE__);\
		return 1; \
	} \
	__count__; \
})

#ifdef EVENTSYS
98
int			myevent_send(tmcdreq_t* reqp, address_tuple_t address);
99 100
#endif

101 102
static MYSQL_RES *	mydb_query(tmcdreq_t* reqp, char *query, int ncols, ...);
static int		mydb_update(tmcdreq_t* reqp, char *query, ...);
103 104 105

static int	safesymlink(char *name1, char *name2);

106
xmlNode *add_node(xmlNode *root, const char *type)
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
{
	xmlNode *node = NULL;
	xmlAttr *attr = NULL;

	node = xmlNewChild(root, NULL, BAD_CAST type, NULL);
	if (node == NULL) {
		/* XXX Ryan: print error */
		return NULL;
	}

	return node;

	attr = xmlNewProp(node, BAD_CAST "type", BAD_CAST type);
	if (attr == NULL) {
		/* XXX Ryan: print error */
		/* XXX Ryan: should unlink and free the node */
		return NULL;
	}

	return node;
}

xmlNode *add_key(xmlNode *opt, const char *name, const char *value)
{
	xmlNode *node = NULL;
	xmlAttr *attr = NULL;

	node = xmlNewChild(opt, NULL, BAD_CAST "key",
			BAD_CAST value);
	if (node == NULL) {
		/* XXX Ryan: print error */
		return NULL;
	}

	attr = xmlNewProp(node, BAD_CAST "name", BAD_CAST name);
	if (attr == NULL) {
		/* XXX Ryan: print error */
		/* XXX Ryan: should unlink and free the node */
		return NULL;
	}

	return node;
}

xmlNode *add_format_key(xmlNode *opt, const char *name, const char *format, ...)
{
	xmlNode *node = NULL;
	xmlAttr *attr = NULL;
	char	value[MYBUFSIZE];
	va_list ap;

	va_start(ap, format);
	vsnprintf(value, sizeof(value), format, ap);
	va_end(ap);

	node = xmlNewChild(opt, NULL, BAD_CAST "key",
			BAD_CAST value);
	if (node == NULL) {
		/* XXX Ryan: print error */
		return NULL;
	}

	attr = xmlNewProp(node, BAD_CAST "name", BAD_CAST name);
	if (attr == NULL) {
		/* XXX Ryan: print error */
		/* XXX Ryan: should unlink and free the node */
		return NULL;
	}

	return node;
}

/* This can be tossed once all the changes are in place */
static char *
CHECKMASK(char *arg)
{
	if (arg && arg[0])
		return arg;

	error("No netmask defined!\n");
	return DEFAULTNETMASK;
}
/* #define CHECKMASK(arg)  ((arg) && (arg[0]) ? (arg) : DEFAULTNETMASK) */

#define DISKTYPE	"ad"
#define DISKNUM		0

/* Compiled in slothd parameters
 *
 * 1 - reg_interval  2 - agg_interval  3 - load_thresh  
 * 4 - expt_thresh   5 - ctl_thresh
 */
#define SDPARAMS        "reg=300 agg=5 load=1 expt=5 ctl=1000"

/*
 * Commands we support.
 */
#define XML_COMMAND_PROTOTYPE(x) \
	static int \
	x(xmlNode *root, tmcdreq_t *reqp, char *rdata)
#define RAW_COMMAND_PROTOTYPE(x) \
	static int \
209
	x(tmcdresp_t *response, tmcdreq_t *reqp, char *rdata)
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

XML_COMMAND_PROTOTYPE(doreboot);
XML_COMMAND_PROTOTYPE(donodeid);
XML_COMMAND_PROTOTYPE(dostatus);
XML_COMMAND_PROTOTYPE(doifconfig);
XML_COMMAND_PROTOTYPE(doaccounts);
XML_COMMAND_PROTOTYPE(dodelay);
XML_COMMAND_PROTOTYPE(dolinkdelay);
XML_COMMAND_PROTOTYPE(dohosts);
XML_COMMAND_PROTOTYPE(dorpms);
XML_COMMAND_PROTOTYPE(dodeltas);
XML_COMMAND_PROTOTYPE(dotarballs);
XML_COMMAND_PROTOTYPE(dostartcmd);
XML_COMMAND_PROTOTYPE(dostartstat);
XML_COMMAND_PROTOTYPE(doready);
XML_COMMAND_PROTOTYPE(doreadycount);
XML_COMMAND_PROTOTYPE(domounts);
XML_COMMAND_PROTOTYPE(dosfshostid);
XML_COMMAND_PROTOTYPE(doloadinfo);
XML_COMMAND_PROTOTYPE(doreset);
XML_COMMAND_PROTOTYPE(dorouting);
XML_COMMAND_PROTOTYPE(dotrafgens);
XML_COMMAND_PROTOTYPE(donseconfigs);
XML_COMMAND_PROTOTYPE(dostate);
XML_COMMAND_PROTOTYPE(docreator);
XML_COMMAND_PROTOTYPE(dotunnels);
XML_COMMAND_PROTOTYPE(dovnodelist);
XML_COMMAND_PROTOTYPE(dosubnodelist);
XML_COMMAND_PROTOTYPE(doisalive);
XML_COMMAND_PROTOTYPE(doipodinfo);
XML_COMMAND_PROTOTYPE(dontpinfo);
XML_COMMAND_PROTOTYPE(dontpdrift);
XML_COMMAND_PROTOTYPE(dojailconfig);
XML_COMMAND_PROTOTYPE(doplabconfig);
XML_COMMAND_PROTOTYPE(dosubconfig);
XML_COMMAND_PROTOTYPE(doixpconfig);
XML_COMMAND_PROTOTYPE(doslothdparams);
XML_COMMAND_PROTOTYPE(doprogagents);
XML_COMMAND_PROTOTYPE(dosyncserver);
XML_COMMAND_PROTOTYPE(dokeyhash);
XML_COMMAND_PROTOTYPE(doeventkey);
XML_COMMAND_PROTOTYPE(dofullconfig);
XML_COMMAND_PROTOTYPE(doroutelist);
XML_COMMAND_PROTOTYPE(dorole);
XML_COMMAND_PROTOTYPE(dorusage);
XML_COMMAND_PROTOTYPE(dodoginfo);
XML_COMMAND_PROTOTYPE(dohostkeys);
XML_COMMAND_PROTOTYPE(dofwinfo);
XML_COMMAND_PROTOTYPE(dohostinfo);
XML_COMMAND_PROTOTYPE(doemulabconfig);
XML_COMMAND_PROTOTYPE(doeplabconfig);
XML_COMMAND_PROTOTYPE(dolocalize);
262
XML_COMMAND_PROTOTYPE(dorootpswd);
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
XML_COMMAND_PROTOTYPE(dobooterrno);
XML_COMMAND_PROTOTYPE(dobattery);
XML_COMMAND_PROTOTYPE(douserenv);
XML_COMMAND_PROTOTYPE(dotiptunnels);
XML_COMMAND_PROTOTYPE(dorelayconfig);
XML_COMMAND_PROTOTYPE(dotraceconfig);
XML_COMMAND_PROTOTYPE(doelvindport);
XML_COMMAND_PROTOTYPE(doplabeventkeys);
XML_COMMAND_PROTOTYPE(dointfcmap);
XML_COMMAND_PROTOTYPE(domotelog);
XML_COMMAND_PROTOTYPE(doportregister);
XML_COMMAND_PROTOTYPE(dobootwhat);

RAW_COMMAND_PROTOTYPE(dotopomap);
RAW_COMMAND_PROTOTYPE(doltmap);
RAW_COMMAND_PROTOTYPE(doltpmap);
RAW_COMMAND_PROTOTYPE(dobootlog);

/*
 * The fullconfig slot determines what routines get called when pushing
 * out a full configuration. Physnodes get slightly different
 * than vnodes, and at some point we might want to distinguish different
 * types of vnodes (jailed, plab).
 */
#define FULLCONFIG_NONE		0x0
#define FULLCONFIG_PHYS		0x1
#define FULLCONFIG_VIRT		0x2
#define FULLCONFIG_ALL		(FULLCONFIG_PHYS|FULLCONFIG_VIRT)

/*
 * Flags encode a few other random properties of commands
 */
#define F_REMUDP	0x01	/* remote nodes can request using UDP */
#define F_MINLOG	0x02	/* record minimal logging info normally */
#define F_MAXLOG	0x04	/* record maximal logging info normally */
#define F_ALLOCATED	0x08	/* node must be allocated to make call */
#define F_REMNOSSL	0x10	/* remote nodes can request without SSL */
300
#define F_REMREQSSL	0x20	/* remote nodes must connect with SSL */
301 302 303 304 305 306 307

struct command {
	char	*cmdname;
	int	fullconfig;	
	int	flags;
	int    (*func)(xmlNode *, tmcdreq_t *, char *);
} xml_command_array[] = {
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
	{ "reboot",	  FULLCONFIG_NONE, 0, doreboot },
	{ "nodeid",	  FULLCONFIG_ALL,  0, donodeid },
	{ "status",	  FULLCONFIG_NONE, 0, dostatus },
	{ "ifconfig",	  FULLCONFIG_ALL,  F_ALLOCATED, doifconfig },
	{ "accounts",	  FULLCONFIG_ALL,  F_REMREQSSL, doaccounts },
	{ "delay",	  FULLCONFIG_ALL,  F_ALLOCATED, dodelay },
	{ "linkdelay",	  FULLCONFIG_ALL,  F_ALLOCATED, dolinkdelay },
	{ "hostnames",	  FULLCONFIG_NONE, F_ALLOCATED, dohosts },
	{ "rpms",	  FULLCONFIG_ALL,  F_ALLOCATED, dorpms },
	{ "deltas",	  FULLCONFIG_NONE, F_ALLOCATED, dodeltas },
	{ "tarballs",	  FULLCONFIG_ALL,  F_ALLOCATED, dotarballs },
	{ "startupcmd",	  FULLCONFIG_ALL,  F_ALLOCATED, dostartcmd },
	{ "startstatus",  FULLCONFIG_NONE, F_ALLOCATED, dostartstat }, /* Before startstat*/
	{ "startstat",	  FULLCONFIG_NONE, 0, dostartstat },
	{ "readycount",   FULLCONFIG_NONE, F_ALLOCATED, doreadycount },
	{ "ready",	  FULLCONFIG_NONE, F_ALLOCATED, doready },
	{ "mounts",	  FULLCONFIG_ALL,  F_ALLOCATED, domounts },
	{ "sfshostid",	  FULLCONFIG_NONE, F_ALLOCATED, dosfshostid },
	{ "loadinfo",	  FULLCONFIG_NONE, 0, doloadinfo},
	{ "reset",	  FULLCONFIG_NONE, 0, doreset},
	{ "routing",	  FULLCONFIG_ALL,  F_ALLOCATED, dorouting},
	{ "trafgens",	  FULLCONFIG_ALL,  F_ALLOCATED, dotrafgens},
330
	{ "nseconfigs",	  FULLCONFIG_ALL,  F_ALLOCATED, donseconfigs},
331 332 333 334 335 336
	{ "creator",	  FULLCONFIG_ALL,  F_ALLOCATED, docreator},
	{ "state",	  FULLCONFIG_NONE, 0, dostate},
	{ "tunnels",	  FULLCONFIG_ALL,  F_ALLOCATED, dotunnels},
	{ "vnodelist",	  FULLCONFIG_PHYS, 0, dovnodelist},
	{ "subnodelist",  FULLCONFIG_PHYS, 0, dosubnodelist},
	{ "isalive",	  FULLCONFIG_NONE, F_REMUDP|F_MINLOG, doisalive},
337 338 339
	{ "ipodinfo",	  FULLCONFIG_PHYS, 0, doipodinfo},
	{ "ntpinfo",	  FULLCONFIG_PHYS, 0, dontpinfo},
	{ "ntpdrift",	  FULLCONFIG_NONE, 0, dontpdrift},
340 341 342 343 344 345 346 347 348 349 350 351 352
	{ "jailconfig",	  FULLCONFIG_VIRT, F_ALLOCATED, dojailconfig},
	{ "plabconfig",	  FULLCONFIG_VIRT, F_ALLOCATED, doplabconfig},
	{ "subconfig",	  FULLCONFIG_NONE, 0, dosubconfig},
        { "sdparams",     FULLCONFIG_PHYS, 0, doslothdparams},
        { "programs",     FULLCONFIG_ALL,  F_ALLOCATED, doprogagents},
        { "syncserver",   FULLCONFIG_ALL,  F_ALLOCATED, dosyncserver},
        { "keyhash",      FULLCONFIG_ALL,  F_ALLOCATED|F_REMREQSSL, dokeyhash},
        { "eventkey",     FULLCONFIG_ALL,  F_ALLOCATED, doeventkey},
        { "fullconfig",   FULLCONFIG_NONE, F_ALLOCATED, dofullconfig},
        { "routelist",	  FULLCONFIG_PHYS, F_ALLOCATED, doroutelist},
        { "role",	  FULLCONFIG_PHYS, F_ALLOCATED, dorole},
        { "rusage",	  FULLCONFIG_NONE, F_REMUDP|F_MINLOG, dorusage},
        { "watchdoginfo", FULLCONFIG_ALL,  F_REMUDP|F_MINLOG, dodoginfo},
353
#if 0
354
        { "hostkeys",     FULLCONFIG_NONE, 0, dohostkeys},
355
#endif
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        { "firewallinfo", FULLCONFIG_ALL,  0, dofwinfo},
        { "hostinfo",     FULLCONFIG_NONE, 0, dohostinfo},
	{ "emulabconfig", FULLCONFIG_NONE, F_ALLOCATED, doemulabconfig},
	{ "eplabconfig",  FULLCONFIG_NONE, F_ALLOCATED, doeplabconfig},
	{ "localization", FULLCONFIG_PHYS, 0, dolocalize},
	{ "rootpswd",     FULLCONFIG_NONE, F_REMREQSSL, dorootpswd},
	{ "booterrno",    FULLCONFIG_NONE, 0, dobooterrno},
	{ "battery",      FULLCONFIG_NONE, F_REMUDP|F_MINLOG, dobattery},
	{ "userenv",      FULLCONFIG_ALL,  F_ALLOCATED, douserenv},
	{ "tiptunnels",	  FULLCONFIG_ALL,  F_ALLOCATED, dotiptunnels},
	{ "traceinfo",	  FULLCONFIG_ALL,  F_ALLOCATED, dotraceconfig },
	{ "elvindport",   FULLCONFIG_NONE, 0, doelvindport},
	{ "plabeventkeys",FULLCONFIG_NONE, F_REMREQSSL, doplabeventkeys},
	{ "intfcmap",     FULLCONFIG_NONE, 0, dointfcmap},
	{ "motelog",      FULLCONFIG_ALL,  F_ALLOCATED, domotelog},
	{ "portregister", FULLCONFIG_NONE, F_REMNOSSL, doportregister},
	{ "bootwhat",	  FULLCONFIG_NONE, 0, dobootwhat },
373 374 375 376 377 378 379
};
static int numcommands = sizeof(xml_command_array)/sizeof(struct command);

struct raw_command {
	char	*cmdname;
	int	fullconfig;	
	int	flags;
380 381 382
	int    (*func)(tmcdresp_t *, tmcdreq_t *, char *);
} raw_command_array[] = {
#if 0
383
	{ "bootlog",      FULLCONFIG_NONE, 0, dobootlog},
384
#endif
385 386 387
	{ "ltmap",        FULLCONFIG_NONE, F_MINLOG|F_ALLOCATED, doltmap},
	{ "ltpmap",       FULLCONFIG_NONE, F_MINLOG|F_ALLOCATED, doltpmap},
	{ "topomap",      FULLCONFIG_NONE, F_MINLOG|F_ALLOCATED, dotopomap},
388
};
389
static int numrawcommands = sizeof(raw_command_array)/sizeof(struct raw_command);
390 391 392 393 394 395 396

#ifdef EVENTSYS
/*
 * Connect to the event system. It's not an error to call this function if
 * already connected. Returns 1 on failure, 0 on sucess.
 */
int
397
event_connect(tmcdreq_t *reqp)
398
{
399 400
	if (!reqp->event_handle) {
		reqp->event_handle =
401 402 403
		  event_register("elvin://localhost:" BOSSEVENTPORT, 0);
	}

404
	if (reqp->event_handle) {
405 406 407 408 409 410 411 412 413 414 415 416
		return 0;
	} else {
		error("event_connect: "
		      "Unable to register with event system!\n");
		return 1;
	}
}

/*
 * Send an event to the event system. Automatically connects (registers)
 * if not already done. Returns 0 on sucess, 1 on failure.
 */
417
int myevent_send(tmcdreq_t *reqp, address_tuple_t tuple) {
418 419
	event_notification_t notification;

420
	if (event_connect(reqp)) {
421 422 423
		return 1;
	}

424
	notification = event_notification_alloc(reqp->event_handle,tuple);
425 426 427 428 429
	if (notification == (event_notification_t) NULL) {
		error("myevent_send: Unable to allocate notification!");
		return 1;
	}

430 431
	if (! event_notify(reqp->event_handle, notification)) {
		event_notification_free(reqp->event_handle, notification);
432 433 434 435 436 437

		error("myevent_send: Unable to send notification!");
		/*
		 * Let's try to disconnect from the event system, so that
		 * we'll reconnect next time around.
		 */
438
		if (!event_unregister(reqp->event_handle)) {
439 440 441
			error("myevent_send: "
			      "Unable to unregister with event system!");
		}
442
		reqp->event_handle = NULL;
443 444
		return 1;
	} else {
445
		event_notification_free(reqp->event_handle,notification);
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
		return 0;
	}
}

/*
 * This is for bootinfo inclusion.
 */
int	bievent_init(void) { return 0; }

int
bievent_send(struct in_addr ipaddr, void *opaque, char *event)
{
	tmcdreq_t		*reqp = (tmcdreq_t *) opaque;
	static address_tuple_t	tuple;

	if (!tuple) {
		tuple = address_tuple_alloc();
		if (tuple == NULL) {
			error("bievent_send: Unable to allocate tuple!\n");
			return -1;
		}
	}
	tuple->host      = BOSSNODE;
	tuple->objtype   = "TBNODESTATE";
	tuple->objname	 = reqp->nodeid;
	tuple->eventtype = event;

473
	if (myevent_send(reqp, tuple)) {
474 475 476 477 478 479 480
		error("bievent_send: Error sending event\n");
		return -1;
	}
	return 0;
}
#endif /* EVENTSYS */
 
481
int tmcd_handle_request(tmcdreq_t *reqp, tmcdresp_t **resp, char *command, char *rdata)
482 483
{
	xmlDoc *doc = NULL;
484
	xmlChar *xmlbuf = NULL;
485 486 487 488 489 490
	xmlNode *root = NULL;
	tmcdresp_t *response = NULL;
	int i, err = 0;
	int buffersize;
	int is_xml_command = 1;
	int flags = 0;
491
	int rc = TMCD_STATUS_OK;
492 493 494 495

	/*
	 * Figure out what command was given.
	 */
496 497
	for (i = 0; i < numcommands; i++) {
		if (strcmp(command, xml_command_array[i].cmdname) == 0) {
498 499 500
			flags = xml_command_array[i].flags;
			break;
		}
501
	}
502 503

	if (i == numcommands) {
504
		for (i = 0; i < numrawcommands; i++)  {
505
			if (strcmp(command, raw_command_array[i].cmdname) == 0) {
506
				is_xml_command = 0;
507
				flags = raw_command_array[i].flags;
508 509
			    	break;
			}
510 511
		}

512
		if (i == numrawcommands) {
Ryan Jackson's avatar
Ryan Jackson committed
513
			rc = TMCD_STATUS_UNKNOWN_COMMAND;
514 515 516 517 518
			goto skipit;
		}

	}

519
#if 0
520 521
	/* If this is a UDP request, make sure it is allowed */
	if (!reqp->istcp && (flags & F_UDP) == 0) {
522
		rc = TMCD_STATUS_INVALID_UDP_REQUEST;
523 524 525
		goto skipit;
	}

526 527 528 529 530 531
	/*
	 * If this is a UDP request from a remote node,
	 * make sure it is allowed.
	 */
	if (!reqp->istcp && !reqp->islocal &&
	    (flags & F_REMUDP) == 0) {
532
		rc = TMCD_STATUS_INVALID_REMOTE_UDP_REQUEST;
533 534
		goto skipit;
	}
Ryan Jackson's avatar
Ryan Jackson committed
535
#endif
536 537 538 539 540

	/*
	 * Ditto for remote node connection without SSL.
	 */
	if (reqp->istcp && !reqp->isssl && !reqp->islocal && 
541
	    (flags & F_REMREQSSL) != 0) {
542
		rc = TMCD_STATUS_REQUIRES_ENCRYPTION;
543 544 545 546
		goto skipit;
	}

	if (!reqp->allocated && (flags & F_ALLOCATED) != 0) {
547
		rc = TMCD_STATUS_NODE_NOT_ALLOCATED;
548 549 550 551 552 553 554 555
		goto skipit;
	}

	/*
	 * Execute it.
	 */
	if ((flags & F_MAXLOG) != 0) {
		/* XXX Ryan? overbose = verbose; */
556
		reqp->verbose = 1;
557 558
	}
#if 0
559
	if (reqp->verbose || (xml_command_array[i].flags & F_MINLOG) == 0)
560 561 562 563 564 565 566
		info("%s: reqp->version%d %s %s\n", reqp->nodeid,
		     version, cp, xml_command_array[i].cmdname);
	setproctitle("%s: %s %s", reqp->nodeid, cp, xml_command_array[i].cmdname);
#endif

#if 0
	if ((flags & F_MAXLOG) != 0)
567
		reqp->verbose = overbose;
568 569 570
#endif
	response = malloc(sizeof(tmcdresp_t));
	if (response == NULL) {
571
		rc = TMCD_STATUS_MALLOC_FAILED;
572 573 574 575 576 577 578 579 580
		goto skipit;
	}

	if (is_xml_command) {
		/* XXX Ryan error checking */
		doc = xmlNewDoc(BAD_CAST "1.0");
		root = xmlNewNode(NULL, BAD_CAST "tmcd");
		xmlDocSetRootElement(doc, root);
		err = xml_command_array[i].func(root, reqp, rdata);
Ryan Jackson's avatar
Ryan Jackson committed
581 582 583
		if (!err) {
			xmlDocDumpFormatMemory(doc, &xmlbuf, &buffersize, 1);
			response->length = strlen((char *)xmlbuf);
584 585 586 587 588
			response->data = malloc(response->length);
			if (response->data == NULL) {
				rc = TMCD_STATUS_MALLOC_FAILED;
				goto skipit;
			}
Ryan Jackson's avatar
Ryan Jackson committed
589 590 591 592 593 594
			response->type = malloc(strlen(XML_MIME_TYPE) + 1);
			if (response->type == NULL) {
				rc = TMCD_STATUS_MALLOC_FAILED;
				goto skipit;
			}
			strcpy(response->type, XML_MIME_TYPE);
595

Ryan Jackson's avatar
Ryan Jackson committed
596
			memcpy(response->data, (char *)xmlbuf, response->length);
597
		}
Ryan Jackson's avatar
Ryan Jackson committed
598 599 600
	} else {
		err = raw_command_array[i].func(response, reqp, rdata);
	}
601

Ryan Jackson's avatar
Ryan Jackson committed
602 603 604 605
	if (err) {
		rc = TMCD_STATUS_COMMAND_FAILED;
		response->length = strlen(xml_command_array[i].cmdname) +
			32 + 3; /* FIXME shouldn't use constant here */
606 607
		response->data = malloc(response->length);
		if (response->data == NULL) {
608 609 610
			rc = TMCD_STATUS_MALLOC_FAILED;
			goto skipit;
		}
611

Ryan Jackson's avatar
Ryan Jackson committed
612 613 614 615
		snprintf(response->data, response->length,
			"%s returned error code %d",
			xml_command_array[i].cmdname, err);
		goto skipit;
616 617 618
	}

skipit:
619 620 621 622
	if (doc)
		xmlFreeDoc(doc);
	if (xmlbuf)
		xmlFree(xmlbuf);
623

624 625
	*resp = response;
	return rc;
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
}

void tmcd_free_response(tmcdresp_t *response)
{
	if (response) {
		if (response->data)
			free(response->data);
		free(response);
	}
}

/*
 * Accept notification of reboot. 
 */
XML_COMMAND_PROTOTYPE(doreboot)
{
	/*
	 * This is now a no-op. The things this used to do are now
	 * done by stated when we hit RELOAD/RELOADDONE state
	 */
	return 0;
}

/*
 * Return emulab nodeid (not the experimental name).
 */
XML_COMMAND_PROTOTYPE(donodeid)
{
	xmlNode *node;

656
	node = add_node(root, "nodeid");
657 658 659 660 661 662 663 664 665 666 667 668
	add_key(node, "id", reqp->nodeid);

	return 0;
}

/*
 * Return status of node. Is it allocated to an experiment, or free.
 */
XML_COMMAND_PROTOTYPE(dostatus)
{
	xmlNode *node;

669
	node = add_node(root, "status");
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
	/*
	 * Now check reserved table
	 */
	if (! reqp->allocated) {
		info("STATUS: %s: FREE\n", reqp->nodeid);
		add_key(node, "status", "free");
	}
	else {
		add_key(node, "status", "allocated");
		add_key(node, "pid", reqp->pid);
		add_key(node, "eid", reqp->eid);
		add_key(node, "nickname", reqp->nickname);
	}

	return 0;
}

/*
 * Return ifconfig information to client.
 */
XML_COMMAND_PROTOTYPE(doifconfig)
{
	MYSQL_RES	*res;	
	MYSQL_ROW	row;
	char		clause[BUFSIZ];
	char		buf[MYBUFSIZE];
696
	xmlNode		*node, *ifconfigNode;
697 698 699 700 701 702 703 704 705 706 707 708 709 710
	int		nrows;
	int		num_interfaces=0;

	/* 
	 * For Virtual Nodes, we return interfaces that belong to it.
	 */
	if (reqp->isvnode && !reqp->issubnode)
		sprintf(clause, "i.vnode_id='%s'", reqp->vnodeid);
	else
		strcpy(clause, "i.vnode_id is NULL");

	/*
	 * Find all the interfaces.
	 */
711
	res = mydb_query(reqp, "select i.card,i.IP,i.MAC,i.current_speed,"
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
			 "       i.duplex,i.IPaliases,i.iface,i.role,i.mask,"
			 "       i.rtabid,i.interface_type,vl.vname "
			 "  from interfaces as i "
			 "left join virt_lans as vl on "
			 "  vl.pid='%s' and vl.eid='%s' and "
			 "  vl.vnode='%s' and vl.ip=i.IP "
			 "where i.node_id='%s' and %s",
			 12, reqp->pid, reqp->eid, reqp->nickname,
			 reqp->issubnode ? reqp->nodeid : reqp->pnodeid,
			 clause);

	/*
	 * We need pnodeid in the query. But error reporting is done
	 * by nodeid. For vnodes, nodeid is pcvmXX-XX and for the rest
	 * it is the same as pnodeid
	 */
	if (!res) {
		error("IFCONFIG: %s: DB Error getting interfaces!\n",
		      reqp->nodeid);
		return 1;
	}

734
	ifconfigNode = add_node(root, "ifconfig");
735

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
	nrows = (int)mysql_num_rows(res);
	while (nrows) {
		row = mysql_fetch_row(res);
		if (row[1] && row[1][0]) {
			char *iface  = row[6];
			char *role   = row[7];
			char *type   = row[10];
			char *lan    = row[11];
			char *speed  = "100";
			char *duplex = "full";
			char *mask;

			/* Never for the control net; sharks are dead */
			if (strcmp(role, TBDB_IFACEROLE_EXPERIMENT))
				goto skipit;

			/* Do this after above test to avoid error in log */
			mask = CHECKMASK(row[8]);

			/*
			 * Speed and duplex if not the default.
			 */
			if (row[3] && row[3][0])
				speed = row[3];
			if (row[4] && row[4][0])
				duplex = row[4];

			/*
			 * We now use the MAC to determine the interface, but
			 * older images still want that tag at the front.
			 */
767
			node = add_node(ifconfigNode, "interface");
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
			add_key(node, "type", type);
			add_key(node, "inet", row[1]);
			add_key(node, "mask", mask);
			add_key(node, "mac", row[2]);
			add_key(node, "speed", speed); /* in Mbps */
			add_key(node, "duplex", duplex);

#if 0
			/*
			 * For older clients, we tack on IPaliases.
			 * This used to be in the interfaces table as a
			 * comma separated list, now we have to extract
			 * it from the vinterfaces table.
			 */
			if (reqp->version>= 8 && reqp->version< 27) {
				MYSQL_RES *res2;
				MYSQL_ROW row2;
				int nrows2;
				
787
				res2 = mydb_query(reqp, "select IP "
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
						  "from vinterfaces "
						  "where type='alias' "
						  "and node_id='%s'",
						  1, reqp->nodeid);
				if (res2 == NULL)
					goto adone;

				nrows2 = (int)mysql_num_rows(res2);
				bufp += OUTPUT(bufp, ebufp - bufp,
					       " IPALIASES=\"");
				while (nrows2 > 0) {
					nrows2--;
					row2 = mysql_fetch_row(res2);
					if (!row2 || !row2[0])
						continue;
					bufp += OUTPUT(bufp, ebufp - bufp,
						       "%s", row2[0]);
					if (nrows2 > 0)
						bufp += OUTPUT(bufp,
							       ebufp - bufp,
							       ",");
				}
				bufp += OUTPUT(bufp, ebufp - bufp, "\"");
				mysql_free_result(res2);
			adone: ;
			}
#endif

			/*
			 * Tack on iface for IXPs. This should be a flag on
			 * the interface instead of a match against type.
			 */

			add_key(node, "iface", 
				       (strcmp(reqp->class, "ixp") ?
					"" : iface));
			add_key(node, "rtabid", row[9]);
			add_key(node, "lan", lan);

			num_interfaces++;
		}
	skipit:
		nrows--;
	}
	mysql_free_result(res);

	/*
	 * Interface settings.
	 */
837
	res = mydb_query(reqp, "select i.MAC,s.capkey,s.capval "
838 839 840 841 842 843 844
			 "from interface_settings as s "
			 "left join interfaces as i on "
			 "     s.node_id=i.node_id and s.iface=i.iface "
			 "where s.node_id='%s' and %s ",
			 3,
			 reqp->issubnode ? reqp->nodeid : reqp->pnodeid,
			 clause);
845

846 847 848 849 850
	if (!res) {
		error("IFCONFIG: %s: "
		      "DB Error getting interface_settings!\n",
		      reqp->nodeid);
		return 1;
851
	}
852 853 854
	nrows = (int)mysql_num_rows(res);
	while (nrows) {
		row = mysql_fetch_row(res);
855
		node = add_node(ifconfigNode, "interface-settings");
856 857 858
		add_key(node, "mac", row[0]);
		add_key(node, "key", row[1]);
		add_key(node, "val", row[2]);
859

860 861 862
		nrows--;
	}
	mysql_free_result(res);
863 864 865 866 867 868 869 870

	/*
	 * First, return config info the physical interfaces underlying
	 * the virtual interfaces so that those can be set up.
	 *
	 * For virtual nodes, we do this just for the physical node;
	 * no need to send it back for every vnode!
	 */
871
	if (!reqp->isvnode) {
872 873 874 875

		/*
		 * First do phys interfaces underlying veth/vlan interfaces
		 */
876
		res = mydb_query(reqp, "select distinct "
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
				 "       i.interface_type,i.mac, "
				 "       i.current_speed,i.duplex "
				 "  from vinterfaces as v "
				 "left join interfaces as i on "
				 "  i.node_id=v.node_id and i.iface=v.iface "
				 "where v.iface is not null and "
				 "      v.type!='alias' and v.node_id='%s'",
				 4, reqp->pnodeid);
		if (!res) {
			error("IFCONFIG: %s: "
			     "DB Error getting interfaces underlying veths!\n",
			      reqp->nodeid);
			return 1;
		}

		nrows = (int)mysql_num_rows(res);
		while (nrows) {
			row = mysql_fetch_row(res);
895
			node = add_node(ifconfigNode, "interface");
896 897 898 899 900 901 902 903 904 905 906 907
			add_key(node, "type", row[0]);
			add_key(node, "mac", row[1]);
			add_key(node, "speed", row[2]); /* in Mbps */
			add_key(node, "duplex", row[3]);

			nrows--;
		}
		mysql_free_result(res);

		/*
		 * Now do phys interfaces underlying delay interfaces.
		 */
908
		res = mydb_query(reqp, "select i.interface_type,i.MAC,"
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
				 "       i.current_speed,i.duplex, "
				 "       j.interface_type,j.MAC,"
				 "       j.current_speed,j.duplex "
				 " from delays as d "
				 "left join interfaces as i on "
				 "    i.node_id=d.node_id and i.iface=iface0 "
				 "left join interfaces as j on "
				 "    j.node_id=d.node_id and j.iface=iface1 "
				 "where d.node_id='%s'",
				 8, reqp->pnodeid);
		if (!res) {
			error("IFCONFIG: %s: "
			    "DB Error getting interfaces underlying delays!\n",
			      reqp->nodeid);
			return 1;
		}
		nrows = (int)mysql_num_rows(res);
		while (nrows) {
			row = mysql_fetch_row(res);

929
			node = add_node(ifconfigNode, "interface");
930 931 932 933 934
			add_key(node, "type", row[0]);
			add_key(node, "mac", row[1]);
			add_key(node, "speed", row[2]); /* in Mbps */
			add_key(node, "duplex", row[3]);

935
			node = add_node(ifconfigNode, "interface");
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
			add_key(node, "type", row[4]);
			add_key(node, "mac", row[5]);
			add_key(node, "speed", row[6]); /* in Mbps */
			add_key(node, "duplex", row[7]);

			nrows--;
		}
		mysql_free_result(res);
	}

	/*
	 * Outside a vnode, return only those virtual devices that have
	 * vnode=NULL, which indicates its an emulated interface on a
	 * physical node. When inside a vnode, only return virtual devices
	 * for which vnode=curvnode, which are the interfaces that correspond
	 * to a jail node.
	 */
	if (reqp->isvnode)
		sprintf(buf, "v.vnode_id='%s'", reqp->vnodeid);
	else
		strcpy(buf, "v.vnode_id is NULL");

	/*
	 * Find all the virtual interfaces.
	 */
961
	res = mydb_query(reqp, "select v.unit,v.IP,v.mac,i.mac,v.mask,v.rtabid, "
962 963 964 965 966 967 968 969
			 "       v.type,vll.vname,v.virtlanidx,la.attrvalue "
			 "  from vinterfaces as v "
			 "left join interfaces as i on "
			 "  i.node_id=v.node_id and i.iface=v.iface "
			 "left join virt_lan_lans as vll on "
			 "  vll.idx=v.virtlanidx and vll.exptidx='%d' "
			 "left join lan_attributes as la on "
			 "  la.lanid=v.vlanid and la.attrkey='vlantag' "
970 971 972 973 974 975
			 "left join lan_attributes as la2 on "
			 "  la2.lanid=v.vlanid and la2.attrkey='stack' "
			 "where v.node_id='%s' and "
			 "      (la2.attrvalue='Experimental' or "
			 "       la2.attrvalue is null) "
			 "      and %s",
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
			 10, reqp->exptidx, reqp->pnodeid, buf);
	if (!res) {
		error("IFCONFIG: %s: DB Error getting veth interfaces!\n",
		      reqp->nodeid);
		return 1;
	}
	if ((nrows = (int)mysql_num_rows(res)) == 0) {
		mysql_free_result(res);
		/* XXX not sure why this is ever an error? */
		if (!reqp->isplabdslice && num_interfaces == 0) {
			error("IFCONFIG: %s: No interfaces!\n", reqp->nodeid);
			return 1;
		}
		return 0;
	}
	while (nrows) {
		int isveth, doencap;

		row = mysql_fetch_row(res);
		nrows--;

		if (strcmp(row[6], "veth") == 0) {
			isveth = 1;
			doencap = 1;
		} else if (strcmp(row[6], "veth-ne") == 0) {
			isveth = 1;
			doencap = 0;
		} else {
			isveth = 0;
			doencap = 0;
		}

		/*
		 * Note that PMAC might be NULL, which happens if there is
		 * no underlying phys interface (say, colocated nodes in a
		 * link).
		 */

1014
		node = add_node(ifconfigNode, "interface");
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
		add_key(node, "type", isveth ? "veth" : row[6]);
		add_key(node, "inet", row[1]);
		add_key(node, "mask", CHECKMASK(row[4]));
		add_key(node, "id", row[0]);
		add_key(node, "vmac", row[2]);
		add_key(node, "pmac", row[3] ? row[3] : "none");
		add_key(node, "rtabid", row[5]);
		add_key(node, "encapsulate", doencap ? "1" : "0" );
		add_key(node, "lan", row[7]);

		/*
		 * Return a VLAN tag.
		 *
		 * XXX for veth devices it comes out of the virt_lan_lans
		 * table, for vlan devices it comes out of the vlans table,
		 * for anything else it is zero.
		 */
		{
			char *tag = "0";
			if (isveth)
				tag = row[8];
			else if (strcmp(row[6], "vlan") == 0)
				tag = row[9];

1039 1040 1041 1042 1043 1044
			/* sanity check the tag */
			if (!isdigit(tag[0])) {
				error("IFCONFIG: bogus encap tag '%s'\n", tag);
				tag = "0";
			}

1045 1046 1047
			add_key(node, "vtag", tag);
		}

1048
		if (reqp->verbose)
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
			info("IFCONFIG: %s", buf);
	}
	mysql_free_result(res);

	return 0;
}

/*
 * Return account stuff.
 */
XML_COMMAND_PROTOTYPE(doaccounts)
{
	MYSQL_RES	*res;	
	MYSQL_ROW	row;
	xmlNode *node, *accounts_node;
	int		nrows, gidint;
	int		tbadmin, didwidearea = 0, nodetypeprojects = 0;
1066
	int		didnonlocal = 0;
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

	/*
	 * Now check reserved table
	 */
	if ((reqp->islocal || reqp->isvnode) && !reqp->allocated) {
		error("%s: accounts: Invalid request from free node\n",
		      reqp->nodeid);
		return 1;
	}

	/*
	 * See if a per-node-type set of projects is specified for accounts.
	 */
1080
	res = mydb_query(reqp, "select na.attrvalue from nodes as n "
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
			 "left join node_type_attributes as na on "
			 "  n.type=na.type "
			 "where n.node_id='%s' and "
			 "na.attrkey='project_accounts'", 1, reqp->nodeid);
	if (res) {
		if ((int)mysql_num_rows(res) != 0) {
			nodetypeprojects = 1;
		}
		mysql_free_result(res);
	}

        /*
	 * We need the unix GID and unix name for each group in the project.
	 */
	if (reqp->iscontrol) {
		/*
		 * All groups! 
		 */
1099
		res = mydb_query(reqp, "select unix_name,unix_gid from groups", 2);
1100 1101 1102 1103 1104 1105 1106 1107
	}
	else if (nodetypeprojects) {
		/*
		 * The projects/groups are specified as a comma separated
		 * list in the node_type_attributes table. Return this
		 * set of groups, plus those in emulab-ops since we want
		 * to include admin people too.
		 */
1108
		res = mydb_query(reqp, "select g.unix_name,g.unix_gid "
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
				 " from projects as p "
				 "left join groups as g on "
				 "     p.pid_idx=g.pid_idx "
				 "where p.approved!=0 and "
				 "  (FIND_IN_SET(g.gid_idx, "
				 "   (select na.attrvalue from nodes as n "
				 "    left join node_type_attributes as na on "
				 "         n.type=na.type "
				 "    where n.node_id='%s' and "
				 "    na.attrkey='project_accounts')) > 0 or "
				 "   p.pid='%s')",
				 2, reqp->nodeid, RELOADPID);
	}
	else if (reqp->islocal || reqp->isvnode) {
1123
		res = mydb_query(reqp, "select unix_name,unix_gid from groups "
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
				 "where pid='%s'",
				 2, reqp->pid);
	}
	else if (reqp->jailflag) {
		/*
		 * A remote node, doing jails. We still want to return
		 * a group for the admin people who get accounts outside
		 * the jails. Lets use the same query as above for now,
		 * but switch over to emulab-ops. 
		 */
1134
		res = mydb_query(reqp, "select unix_name,unix_gid from groups "
1135 1136 1137 1138 1139 1140 1141 1142 1143
				 "where pid='%s'",
				 2, RELOADPID);
	}
	else {
		/*
		 * XXX - Old style node, not doing jails.
		 *
		 * Added this for Dave. I love subqueries!
		 */
1144
		res = mydb_query(reqp, "select g.unix_name,g.unix_gid "
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
				 " from projects as p "
				 "left join groups as g on p.pid=g.pid "
				 "where p.approved!=0 and "
				 "  FIND_IN_SET(g.gid_idx, "
				 "   (select attrvalue from node_attributes "
				 "      where node_id='%s' and "
				 "            attrkey='dp_projects')) > 0",
				 2, reqp->pnodeid);

		if (!res || (int)mysql_num_rows(res) == 0) {
		 /*
		  * Temporary hack until we figure out the right model for
		  * remote nodes. For now, we use the pcremote-ok slot in
		  * in the project table to determine what remote nodes are
		  * okay'ed for the project. If connecting node type is in
		  * that list, then return all of the project groups, for
		  * each project that is allowed to get accounts on the type.
		  */
1163
		  res = mydb_query(reqp, "select g.unix_name,g.unix_gid "
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
				   "  from projects as p "
				   "join groups as g on p.pid=g.pid "
				   "where p.approved!=0 and "
				   "      FIND_IN_SET('%s',pcremote_ok)>0",
				   2, reqp->type);
		}
	}
	if (!res) {
		error("ACCOUNTS: %s: DB Error getting gids!\n", reqp->pid);
		return 1;
	}

	if ((nrows = (int)mysql_num_rows(res)) == 0) {
		error("ACCOUNTS: %s: No Project!\n", reqp->pid);
		mysql_free_result(res);
		return 1;
	}

1182
	accounts_node = add_node(root, "accounts");
1183 1184 1185 1186 1187 1188 1189 1190 1191

	while (nrows) {
		row = mysql_fetch_row(res);
		if (!row[1] || !row[1][1]) {
			error("ACCOUNTS: %s: No Project GID!\n", reqp->pid);
			mysql_free_result(res);
			return 1;
		}

1192
		node = add_node(accounts_node, "addgroup");
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
		add_key(node, "name", row[0]);
		add_key(node, "gid", row[1]);

		nrows--;
	}
	mysql_free_result(res);

	/*
	 * Each time a node picks up accounts, decrement the update
	 * counter. This ensures that if someone kicks off another
	 * update after this point, the node will end up getting to
	 * do it again in case it missed something.
	 */
1206
	if (mydb_update(reqp, "update nodes set update_accounts=update_accounts-1 "
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
			"where node_id='%s' and update_accounts!=0",
			reqp->nodeid)) {
		error("ACCOUNTS: %s: DB Error setting exit update_accounts!\n",
		      reqp->nodeid);
	}
			 
	/*
	 * Now onto the users in the project.
	 */
	if (reqp->iscontrol) {
		/*
		 * All users! This is not currently used. The problem
		 * is that returning a list of hundreds of users whenever
		 * any single change is required is bad. Works fine for
		 * experimental nodes where the number of accounts is small,
		 * but is not scalable. 
		 */
1224
		res = mydb_query(reqp, "select distinct "
1225 1226 1227 1228
				 "  u.uid,u.usr_pswd,u.unix_uid,u.usr_name, "
				 "  p.trust,g.pid,g.gid,g.unix_gid,u.admin, "
				 "  u.emulab_pubkey,u.home_pubkey, "
				 "  UNIX_TIMESTAMP(u.usr_modified), "
1229
				 "  u.usr_email,u.usr_shell,u.uid_idx "
1230 1231 1232 1233 1234 1235 1236
				 "from group_membership as p "
				 "join users as u on p.uid_idx=u.uid_idx "
				 "join groups as g on p.pid=g.pid "
				 "where p.trust!='none' "
				 "      and u.webonly=0 "
                                 "      and g.unix_id is not NULL "
				 "      and u.status='active' order by u.uid",
1237
				 15, reqp->pid, reqp->gid);
1238 1239 1240 1241 1242
	}
	else if (nodetypeprojects) {
		/*
		 * The projects/groups are specified as a comma separated
		 * list in the node_type_attributes table. Return this
1243
		 * set of users.
1244
		 */
1245
		res = mydb_query(reqp, "select distinct  "
1246 1247 1248 1249 1250 1251
				 "u.uid,'*',u.unix_uid,u.usr_name, "
				 "m.trust,g.pid,g.gid,g.unix_gid,u.admin, "
				 "u.emulab_pubkey,u.home_pubkey, "
				 "UNIX_TIMESTAMP(u.usr_modified), "
				 "u.usr_email,u.usr_shell, "
				 "u.widearearoot,u.wideareajailroot, "
1252
				 "u.usr_w_pswd,u.uid_idx "
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
				 "from projects as p "
				 "join group_membership as m on "
				 "     m.pid_idx=p.pid_idx "
				 "join groups as g on "
				 "     g.gid_idx=m.gid_idx "
				 "join users as u on u.uid_idx=m.uid_idx "
				 "where p.approved!=0 "
				 "      and m.trust!='none' "
				 "      and u.webonly=0 "
                                 "      and g.unix_gid is not NULL "
1263 1264
				 "      and u.status='active' "
				 "      and u.admin=0 and "
1265 1266 1267 1268 1269
				 "  (FIND_IN_SET(g.gid_idx, "
				 "   (select na.attrvalue from nodes as n "
				 "    left join node_type_attributes as na on "
				 "         n.type=na.type "
				 "    where n.node_id='%s' and "
1270
				 "    na.attrkey='project_accounts')) > 0) "
1271
				 "order by u.uid",
1272
				 18, reqp->nodeid);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
	}
	else if (reqp->islocal || reqp->isvnode) {
		/*
		 * This crazy join is going to give us multiple lines for
		 * each user that is allowed on the node, where each line
		 * (for each user) differs by the project PID and it unix
		 * GID. The intent is to build up a list of GIDs for each
		 * user to return. Well, a primary group and a list of aux
		 * groups for that user.
		 */
1283 1284 1285 1286 1287
	  	char adminclause[MYBUFSIZE];
		strcpy(adminclause, "");
#ifdef ISOLATEADMINS
		sprintf(adminclause, "and u.admin=%d", reqp->swapper_isadmin);
#endif
1288
		res = mydb_query(reqp, "select distinct "
1289 1290 1291 1292 1293 1294
				 "  u.uid,u.usr_pswd,u.unix_uid,u.usr_name, "
				 "  p.trust,g.pid,g.gid,g.unix_gid,u.admin, "
				 "  u.emulab_pubkey,u.home_pubkey, "
				 "  UNIX_TIMESTAMP(u.usr_modified), "
				 "  u.usr_email,u.usr_shell, "
				 "  u.widearearoot,u.wideareajailroot, "
1295
				 "  u.usr_w_pswd,u.uid_idx "
1296 1297 1298 1299 1300 1301 1302
				 "from group_membership as p "
				 "join users as u on p.uid_idx=u.uid_idx "
				 "join groups as g on "
				 "     p.pid=g.pid and p.gid=g.gid "
				 "where ((p.pid='%s')) and p.trust!='none' "
				 "      and u.status='active' "
				 "      and u.webonly=0 "
1303
				 "      %s "
1304 1305
                                 "      and g.unix_gid is not NULL "
				 "order by u.uid",
1306
				 18, reqp->pid, adminclause);
1307 1308 1309 1310 1311 1312
	}
	else if (reqp->jailflag) {
		/*
		 * A remote node, doing jails. We still want to return
		 * accounts for the admin people outside the jails.
		 */
1313
		res = mydb_query(reqp, "select distinct "
1314 1315 1316 1317 1318 1319
			     "  u.uid,'*',u.unix_uid,u.usr_name, "
			     "  p.trust,g.pid,g.gid,g.unix_gid,u.admin, "
			     "  u.emulab_pubkey,u.home_pubkey, "
			     "  UNIX_TIMESTAMP(u.usr_modified), "
			     "  u.usr_email,u.usr_shell, "
			     "  u.widearearoot,u.wideareajailroot, "
1320
			     "  u.usr_w_pswd,u.uid_idx "
1321 1322 1323 1324 1325 1326 1327
			     "from group_membership as p "
			     "join users as u on p.uid_idx=u.uid_idx "
			     "join groups as g on "
			     "     p.pid=g.pid and p.gid=g.gid "
			     "where (p.pid='%s') and p.trust!='none' "
			     "      and u.status='active' and u.admin=1 "
			     "      order by u.uid",
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
			     18, RELOADPID);
	}
	else if (!reqp->islocal && reqp->isdedicatedwa) {
		/*
		 * Wonder why this code is a copy of the islocal || vnode
		 * case above?  It's because I don't want to prevent us from
		 * from the above case where !islocal && jailflag
		 * for dedicated widearea nodes.
		 */

		/*
		 * This crazy join is going to give us multiple lines for
		 * each user that is allowed on the node, where each line
		 * (for each user) differs by the project PID and it unix
		 * GID. The intent is to build up a list of GIDs for each
		 * user to return. Well, a primary group and a list of aux
		 * groups for that user.
		 */
	  	char adminclause[MYBUFSIZE];
		strcpy(adminclause, "");
#ifdef ISOLATEADMINS
		sprintf(adminclause, "and u.admin=%d", reqp->swapper_isadmin);
#endif
1351
		res = mydb_query(reqp, "select distinct "
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
				 "  u.uid,'*',u.unix_uid,u.usr_name, "
				 "  p.trust,g.pid,g.gid,g.unix_gid,u.admin, "
				 "  u.emulab_pubkey,u.home_pubkey, "
				 "  UNIX_TIMESTAMP(u.usr_modified), "
				 "  u.usr_email,u.usr_shell, "
				 "  u.widearearoot,u.wideareajailroot, "
				 "  u.usr_w_pswd,u.uid_idx "
				 "from group_membership as p "
				 "join users as u on p.uid_idx=u.uid_idx "
				 "join groups as g on "
				 "     p.pid=g.pid and p.gid=g.gid "
				 "where ((p.pid='%s')) and p.trust!='none' "
				 "      and u.status='active' "
				 "      and u.webonly=0 "
				 "      %s "
                                 "      and g.unix_gid is not NULL "
				 "order by u.uid",
				 18, reqp->pid, adminclause);
	}
	else if (!reqp->islocal && reqp->isdedicatedwa) {
	        /*
		 * Catch widearea nodes that are dedicated to a single pid/eid.
		 * Same as local case.
		 */
1376
		res = mydb_query(reqp, "select unix_name,unix_gid from groups "
1377 1378
				 "where pid='%s'",
				 2, reqp->pid);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
	}
	else {
		/*
		 * XXX - Old style node, not doing jails.
		 *
		 * Temporary hack until we figure out the right model for
		 * remote nodes. For now, we use the pcremote-ok slot in
		 * in the project table to determine what remote nodes are
		 * okay'ed for the project. If connecting node type is in
		 * that list, then return user info for all of the users
		 * in those projects (crossed with group in the project). 
		 */
		char subclause[MYBUFSIZE];
		int  count = 0;
		
1394
		res = mydb_query(reqp, "select attrvalue from node_attributes "
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
				 " where node_id='%s' and "
				 "       attrkey='dp_projects'",
				 1, reqp->pnodeid);

		if (res) {
			if ((int)mysql_num_rows(res) > 0) {
				row = mysql_fetch_row(res);

				count = snprintf(subclause,
					     sizeof(subclause) - 1,
					     "FIND_IN_SET(g.gid_idx,'%s')>0",
					     row[0]);
			}
			else {
				count = snprintf(subclause,
					     sizeof(subclause) - 1,
					     "FIND_IN_SET('%s',pcremote_ok)>0",
					     reqp->type);
			}
			mysql_free_result(res);
			
			if (count >= sizeof(subclause)) {
				error("ACCOUNTS: %s: Subclause too long!\n",
				      reqp->nodeid);
				return 1;
			}
		}
			
1423
		res = mydb_query(reqp, "select distinct  "
1424 1425 1426 1427 1428 1429
				 "u.uid,'*',u.unix_uid,u.usr_name, "
				 "m.trust,g.pid,g.gid,g.unix_gid,u.admin, "
				 "u.emulab_pubkey,u.home_pubkey, "
				 "UNIX_TIMESTAMP(u.usr_modified), "
				 "u.usr_email,u.usr_shell, "
				 "u.widearearoot,u.wideareajailroot, "
1430
				 "u.usr_w_pswd,u.uid_idx "
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
				 "from projects as p "
				 "join group_membership as m "
				 "  on m.pid=p.pid "
				 "join groups as g on "
				 "  g.pid=m.pid and g.gid=m.gid "
				 "join users as u on u.uid_idx=m.uid_idx "
				 "where p.approved!=0 "
				 "      and %s "
				 "      and m.trust!='none' "
				 "      and u.webonly=0 "
1441
				 "      and u.admin=0 "
1442 1443 1444
                                 "      and g.unix_gid is not NULL "
				 "      and u.status='active' "
				 "order by u.uid",
1445
				 18, subclause);
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
	}

	if (!res) {
		error("ACCOUNTS: %s: DB Error getting users!\n", reqp->pid);
		return 1;
	}

	if ((nrows = (int)mysql_num_rows(res)) == 0) {
		error("ACCOUNTS: %s: No Users!\n", reqp->pid);
		mysql_free_result(res);
		return 0;
	}

 again:
	row = mysql_fetch_row(res);
	while (nrows) {
		MYSQL_ROW	nextrow = 0;
		MYSQL_RES	*pubkeys_res;
		MYSQL_RES	*sfskeys_res;
		int		pubkeys_nrows, sfskeys_nrows, i;
		int 		is_root;
		int		auxgids[128], gcount = 0;
		char		glist[BUFSIZ];
		char		home_dir[BUFSIZ];
		char		*pswd, *wpswd, wpswd_buf[9];

		gidint     = -1;
		tbadmin    = is_root = atoi(row[8]);
		gcount     = 0;
		
		while (1) {
			
			/*
			 * The whole point of this mess. Figure out the
			 * main GID and the aux GIDs. Perhaps trying to make
			 * distinction between main and aux is unecessary, as
			 * long as the entire set is represented.
			 */
			if (strcmp(row[5], reqp->pid) == 0 &&
			    strcmp(row[6], reqp->gid) == 0) {
				gidint = atoi(row[7]);

				/*
				 * Only people in the main pid can get root
				 * at this time, so do this test here.
				 */
				if ((strcmp(row[4], "local_root") == 0) ||
				    (strcmp(row[4], "group_root") == 0) ||
				    (strcmp(row[4], "project_root") == 0))
					is_root = 1;
			}
			else {
				int k, newgid = atoi(row[7]);
				
				/*
				 * Avoid dups, which can happen because of
				 * different trust levels in the join.
				 */
				for (k = 0; k < gcount; k++) {
				    if (auxgids[k] == newgid)
					goto skipit;
				}
				auxgids[gcount++] = newgid;
			skipit:
				;
			}
			nrows--;

			if (!nrows)
				break;

			/*
			 * See if the next row is the same UID. If so,
			 * we go around the inner loop again.
			 */
			nextrow = mysql_fetch_row(res);
			if (strcmp(row[0], nextrow[0]))
				break;
			row = nextrow;
		}

		/*
		 * widearearoot and wideareajailroot override trust values
1529 1530 1531
		 * from the project (above) (IF the node is not isdedicatedwa,
		 * since these must behave like local). Of course, tbadmin
		 * overrides everthing!
1532
		 */
1533
		if (!reqp->islocal && !reqp->isdedicatedwa && !reqp->isplabdslice) {
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
			if (!reqp->isvnode)
				is_root = atoi(row[14]);
			else
				is_root = atoi(row[15]);

			if (tbadmin)
				is_root = 1;
		}

		/* There is an optional Windows password column. */
		pswd = row[1];
		wpswd = row[16];
		if (strncmp(rdata, "windows", 7) == 0) {
			if (wpswd != NULL && strlen(wpswd) > 0) {
				row[1] = wpswd;
			}
			else {

				/* The initial random default for the Windows Password
				 * is based on the Unix encrypted password hash, in
				 * particular the random salt when it's an MD5 crypt.
				 * THis is the 8 characters after an initial "$1$" and
				 * followed by a "$".  Just use the first 8 chars if
				 * the hash is not an MD5 crypt.
				 */
				strncpy(wpswd_buf, 
					(strncmp(pswd,"$1$",3)==0) ? pswd + 3 : pswd,
					8);
				wpswd_buf[8]='\0';
				row[1] = wpswd_buf;
			}
		}
		 
		/*
		 * Okay, process the UID. If there is no primary gid,
		 * then use one from the list. Then convert the rest of
		 * the list for the GLIST argument below.
		 */
		if (gidint == -1) {
			gidint = auxgids[--gcount];
		}
		glist[0] = '\0';
		for (i = 0; i < gcount; i++) {
			sprintf(&glist[strlen(glist)], "%d", auxgids[i]);

			if (i < gcount-1)
				strcat(glist, ",");
		}

		if (!reqp->islocal) {
			row[1] = "*";
		}

		strcpy(home_dir, USERDIR);
		strcat(home_dir, row[0]);

1590
		node = add_node(accounts_node, "adduser");
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
		add_key(node, "login", row[0]);
		add_key(node, "pswd", row[1]);
		add_key(node, "uid", row[2]);
		add_key(node, "gid", row[7]);
		add_key(node, "root", (is_root ? "1" : "0"));
		add_key(node, "name", row[3]);
		add_key(node, "homedir", home_dir);
		add_key(node, "glist", glist);
		add_key(node, "serial", row[11]);
		add_key(node, "email", row[12]);
		add_key(node, "shell", row[13]);

1603
		if (reqp->verbose)
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
			info("ACCOUNTS: "
			     "ADDUSER LOGIN=%s "
			     "UID=%s GID=%d ROOT=%d GLIST=%s\n",
			     row[0], row[2], gidint, is_root, glist);

		/*
		 * Locally, everything is NFS mounted so no point in
		 * sending back pubkey stuff; it's never used except on CygWin.
		 * Add an argument of "pubkeys" to get the PUBKEY data.
		 * An "windows" argument also returns a user's Windows Password.
		 */
1615 1616 1617
		if (reqp->islocal && !reqp->genisliver_idx &&
		    ! (strncmp(rdata, "pubkeys", 7) == 0
		       || strncmp(rdata, "windows", 7) == 0))
1618 1619 1620 1621 1622
			goto skipsshkeys;

		/*
		 * Need a list of keys for this user.
		 */
1623
		pubkeys_res = mydb_query(reqp, "select idx,pubkey "
1624
					 " from user_pubkeys "
1625 1626
					 "where uid_idx='%s'",
					 2, row[17]);
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
	
		if (!pubkeys_res) {
			error("ACCOUNTS: %s: DB Error getting keys\n", row[0]);
			goto skipkeys;
		}
		if ((pubkeys_nrows = (int)mysql_num_rows(pubkeys_res))) {
			while (pubkeys_nrows) {
				MYSQL_ROW	pubkey_row;

				pubkey_row = mysql_fetch_row(pubkeys_res);

				/*
				 * Pubkeys can be large, so we may have to
				 * malloc a special buffer.
				 */
1642
				node = add_node(accounts_node, "pubkey");
1643 1644 1645 1646
				add_key(node, "login", row[0]);
				add_key(node, "key", pubkey_row[1]);

				pubkeys_nrows--;
1647
			}
1648
			
1649 1650 1651 1652 1653 1654 1655 1656
		}
		mysql_free_result(pubkeys_res);

	skipsshkeys:
		/*
		 * Do not bother to send back SFS keys if the node is not
		 * running SFS.
		 */
1657
		if (!strlen(reqp->sfshostid))
1658 1659 1660 1661 1662
			goto skipkeys;

		/*
		 * Need a list of SFS keys for this user.
		 */
1663
		sfskeys_res = mydb_query(reqp, "select comment,pubkey "
1664
					 " from user_sfskeys "
1665 1666
					 "where uid_idx='%s'",
					 2, row[17]);
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677

		if (!sfskeys_res) {
			error("ACCOUNTS: %s: DB Error getting SFS keys\n", row[0]);
			goto skipkeys;
		}
		if ((sfskeys_nrows = (int)mysql_num_rows(sfskeys_res))) {
			while (sfskeys_nrows) {
				MYSQL_ROW	sfskey_row;

				sfskey_row = mysql_fetch_row(sfskeys_res);

1678
				node = add_node(accounts_node, "sfskey");
1679 1680 1681 1682
				add_key(node, "key", sfskey_row[1]);

				sfskeys_nrows--;

1683
				if (reqp->verbose)
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
					info("ACCOUNTS: SFSKEY LOGIN=%s "
					     "COMMENT=%s\n",
					     row[0], sfskey_row[0]);
			}
		}
		mysql_free_result(sfskeys_res);
		
	skipkeys:
		row = nextrow;
	}
	mysql_free_result(res);

	if (!(reqp->islocal || reqp->isvnode) && !didwidearea) {
		didwidearea = 1;

		/*
		 * Sleazy. The only real downside though is that
		 * we could get some duplicate entries, which won't
		 * really harm anything on the client.
		 */
1704
		res = mydb_query(reqp, "select distinct "
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
				 "u.uid,'*',u.unix_uid,u.usr_name, "
				 "w.trust,'guest','guest',31,u.admin, "
				 "u.emulab_pubkey,u.home_pubkey, "
				 "UNIX_TIMESTAMP(u.usr_modified), "
				 "u.usr_email,u.usr_shell, "
				 "u.widearearoot,u.wideareajailroot "
				 "from widearea_accounts as w "
				 "join users as u on u.uid_idx=w.uid_idx "
				 "where w.trust!='none' and "
				 "      u.status='active' and "
				 "      node_id='%s' "
				 "order by u.uid",
				 16, reqp->nodeid);

		if (res) {
			if ((nrows = mysql_num_rows(res)))
				goto again;
			else
				mysql_free_result(res);
		}
	}
1726 1727 1728
	if (reqp->genisliver_idx && !didnonlocal) {
	        didnonlocal = 1;

1729
		res = mydb_query(reqp, "select distinct "
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
				 "  u.uid,'*',u.uid_idx,u.name, "
				 "  'local_root',g.pid,g.gid,g.unix_gid,0, "
				 "  NULL,NULL,0, "
				 "  u.email,'csh', "
				 "  0,0, "
				 "  NULL,u.uid_idx "
				 "from nonlocal_user_bindings as b "
				 "join nonlocal_users as u on "
				 "     b.uid_idx=u.uid_idx "
				 "join groups as g on "
				 "     g.pid='%s' and g.pid=g.gid "
				 "where (b.exptidx='%d') "
				 "order by u.uid",
				 18, reqp->pid, reqp->exptidx);
		
		if (res) {
			if ((nrows = mysql_num_rows(res)))
				goto again;
			else
				mysql_free_result(res);
		}
	}
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
	return 0;
}

/*
 * Return delay config stuff.
 */
XML_COMMAND_PROTOTYPE(dodelay)
{
	MYSQL_RES	*res;	
	MYSQL_ROW	row;
	int		nrows;
	xmlNode *node;

	/*
	 * Get delay parameters for the machine. The point of this silly
	 * join is to get the type out so that we can pass it back. Of
	 * course, this assumes that the type is the BSD name, not linux.
	 */
1770
	res = mydb_query(reqp, "select i.MAC,j.MAC, "
1771 1772 1773 1774 1775 1776 1777 1778
		 "pipe0,delay0,bandwidth0,lossrate0,q0_red, "
		 "pipe1,delay1,bandwidth1,lossrate1,q1_red, "
		 "vname, "
		 "q0_limit,q0_maxthresh,q0_minthresh,q0_weight,q0_linterm, " 
		 "q0_qinbytes,q0_bytes,q0_meanpsize,q0_wait,q0_setbit, " 
		 "q0_droptail,q0_gentle, "
		 "q1_limit,q1_maxthresh,q1_minthresh,q1_weight,q1_linterm, "
		 "q1_qinbytes,q1_bytes,q1_meanpsize,q1_wait,q1_setbit, "
1779 1780
		 "q1_droptail,q1_gentle,vnode0,vnode1,noshaping, "
		 "backfill0,backfill1"
1781 1782 1783 1784 1785 1786
                 " from delays as d "
		 "left join interfaces as i on "
		 " i.node_id=d.node_id and i.iface=iface0 "
		 "left join interfaces as j on "
		 " j.node_id=d.node_id and j.iface=iface1 "
		 " where d.node_id='%s'",	 
1787
		 42, reqp->nodeid);
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
	if (!res) {
		error("DELAY: %s: DB Error getting delays!\n", reqp->nodeid);
		return 1;
	}

	if ((nrows = (int)mysql_num_rows(res)) == 0) {
		mysql_free_result(res);
		return 0;
	}
	while (nrows) {
		row = mysql_fetch_row(res);

		/*
		 * Yikes, this is ugly! Sanity check though, since I saw
		 * some bogus values in the DB.
		 */
		if (!row[0] || !row[1] || !row[2] || !row[3]) {
			error("DELAY: %s: DB values are bogus!\n",
			      reqp->nodeid);
			mysql_free_result(res);
			return 1;
		}


1812
		node = add_node(root, "delay");
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
		add_key(node, "int0", row[0]);
		add_key(node, "int1", row[1]);
		add_key(node, "pipe0", row[2]);
		add_key(node, "delay0", row[3]);
		add_key(node, "bw0", row[4]);
		add_key(node, "plr0", row[5]);
		add_key(node, "pipe1", row[7]);
		add_key(node, "delay1", row[8]);
		add_key(node, "bw1", row[9]);
		add_key(node, "plr1", row[10]);
		add_key(node, "linkname", row[12]);
		add_key(node, "red0", row[6]);
		add_key(node, "red1", row[11]);
		add_key(node, "limit0", row[13]);
		add_key(node, "maxthresh0", row[14]);
		add_key(node, "minthresh0", row[15]);
		add_key(node, "weight0", row[16]);
		add_key(node, "linterm0", row[17]);
		add_key(node, "qinbytes0", row[18]);
		add_key(node, "bytes0", row[19]);
		add_key(node, "meanpsize0", row[20]);
		add_key(node, "wait0", row[21]);
		add_key(node, "setbit0", row[22]);
		add_key(node, "droptail0", row[23]);
		add_key(node, "gentle0", row[24]);
		add_key(node, "limit1", row[25]);
		add_key(node, "maxthresh1", row[26]);
		add_key(node, "minthresh1", row[27]);
		add_key(node, "weight1", row[28]);
		add_key(node, "linterm1", row[29]);
		add_key(node, "qinbytes1", row[30]);
		add_key(node, "bytes1", row[31]);
		add_key(node, "meanpsize1", row[32]);
		add_key(node, "wait1", row[33]);
		add_key(node, "setbit1", row[34]);
		add_key(node, "droptail1", row[35]);
		add_key(node, "gentle1", row[36]);
		add_key(node, "vnode0", (row[37] ? row[37] : "foo"));
		add_key(node, "vnode1", (row[38] ? row[38] : "bar"));
		add_key(node, "noshaping", row[39]);
1853 1854
		add_key(node, "backfill0", row[40]);
		add_key(node, "backfill1", row[41]);
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895

		nrows--;
	}
	mysql_free_result(res);

	return 0;
}

/*
 * Return link delay config stuff.
 */
XML_COMMAND_PROTOTYPE(dolinkdelay)
{
	MYSQL_RES	*res;	
	MYSQL_ROW	row;
	char		buf[2*MYBUFSIZE];
	int		nrows;
	xmlNode		*node;

	/*
	 * Get link delay parameters for the machine. We store veth
	 * interfaces in another dynamic table, so must join with both
	 * interfaces and vinterfaces to see which iface this link
	 * delay corresponds to. If there is a veth entry use that, else
	 * use the normal interfaces entry. I do not like this much.
	 * Maybe we should use the regular interfaces table, with type veth,
	 * entries added/deleted on the fly. I avoided that cause I view
	 * the interfaces table as static and pertaining to physical
	 * interfaces.
	 *
	 * Outside a vnode, return only those linkdelays for veths that have
	 * vnode=NULL, which indicates its an emulated interface on a
	 * physical node. When inside a vnode, only return veths for which
	 * vnode=curvnode, which are the interfaces that correspond to a
	 * jail node.
	 */
	if (reqp->isvnode)
		sprintf(buf, "and v.vnode_id='%s'", reqp->vnodeid);
	else
		strcpy(buf, "and v.vnode_id is NULL");

1896
	res = mydb_query(reqp, "select i.MAC,d.type,vlan,vnode,d.ip,netmask, "
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
		 "pipe,delay,bandwidth,lossrate, "
		 "rpipe,rdelay,rbandwidth,rlossrate, "
		 "q_red,q_limit,q_maxthresh,q_minthresh,q_weight,q_linterm, " 
		 "q_qinbytes,q_bytes,q_meanpsize,q_wait,q_setbit, " 
		 "q_droptail,q_gentle,v.mac "
                 " from linkdelays as d "
		 "left join interfaces as i on "
		 " i.node_id=d.node_id and i.iface=d.iface "
		 "left join vinterfaces as v on "
		 " v.node_id=d.node_id and v.IP=d.ip "
		 "where d.node_id='%s' %s",
		 28, reqp->pnodeid, buf);
	if (!res) {
		error("LINKDELAY: %s: DB Error getting link delays!\n",
		      reqp->nodeid);
		return 1;
	}

	if ((nrows = (int)mysql_num_rows(res)) == 0) {
		mysql_free_result(res);
		return 0;
	}
	while (nrows) {
		row = mysql_fetch_row(res);
1921
		node = add_node(root, "linkdelay");
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951

		add_key(node, "iface", (row[27] ? row[27] : row[0]));
		add_key(node, "type", row[1]);
		add_key(node, "linkname", row[2]);
		add_key(node, "vnode", row[3]);
		add_key(node, "inet", row[4]);
		add_key(node, "mask", CHECKMASK(row[5]));
		add_key(node, "pipe", row[6]);
		add_key(node, "delay", row[7]);
		add_key(node, "bw", row[8]);
		add_key(node, "plr", row[9]);
		add_key(node, "rpipe", row[10]);
		add_key(node, "rdelay", row[11]);
		add_key(node, "rbw", row[12]);
		add_key(node, "rplr", row[14]);
		add_key(node, "red", row[14]);
		add_key(node, "limit", row[15]);
		add_key(node, "maxthresh", row[16]);
		add_key(node, "minthresh", row[17]);
		add_key(node, "weight", row[18]);
		add_key(node, "linterm", row[19]);
		add_key(node, "qinbytes", row[20]);
		add_key(node, "bytes", row[21]);
		add_key(node, "meanpsize", row[22]);
		add_key(node, "wait", row[23]);
		add_key(node, "setbit", row[24]);
		add_key(node, "droptail", row[25]);
		add_key(node, "gentle", row[26]);
			
		nrows--;
1952
		if (reqp->verbose)
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
			info("LINKDELAY: %s", buf);
	}
	mysql_free_result(res);

	return 0;
}

XML_COMMAND_PROTOTYPE(dohosts)
{
	MYSQL_RES	*res;	
	MYSQL_ROW	row;
	int		hostcount, nrows;
	int		rv = 0;
	char		*thisvnode = (char *) NULL;
	xmlNode		*node;

	/*
	 * We build up a canonical host table using this data structure.
	 * There is one item per node/iface. We need a shared structure
	 * though for each node, to allow us to compute the aliases.
	 */
	struct shareditem {
	    	int	hasalias;
		char	*firstvlan;	/* The first vlan to another node */
		int	is_me;          /* 1 if this node is the tmcc client */
	};
	struct shareditem *shareditem = (struct shareditem *) NULL;
	
	struct hostentry {
		char	nodeid[TBDB_FLEN_NODEID];
		char	vname[TBDB_FLEN_VNAME];
		char	vlan[TBDB_FLEN_VNAME];
		int	virtiface;
		struct in_addr	  ipaddr;
		struct shareditem *shared;
		struct hostentry  *next;
	} *hosts = 0, *host;

	/*
	 * Now use the virt_nodes table to get a list of all of the
	 * nodes and all of the IPs on those nodes. This is the basis
	 * for the canonical host table. Join it with the reserved
	 * table to get the node_id at the same time (saves a step).
	 *
	 * XXX NSE hack: Using the v2pmap table instead of reserved because
	 * of multiple simulated to one physical node mapping. Currently,
	 * reserved table contains a vname which is generated in the case of
	 * nse
	 *
	 * XXX PELAB hack: If virt_lans.protocol is 'ipv4' then this is a
	 * "LAN" of real internet nodes and we should return the control
	 * network IP address.  The intent is to give plab nodes some
	 * convenient aliases for refering to each other.
	 */
2007
	res = mydb_query(reqp, "select v.vname,v.vnode,v.ip,v.vport,v2p.node_id,"
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
			 "v.protocol,i.IP "
			 "    from virt_lans as v "
			 "left join v2pmap as v2p on "
			 "     v.vnode=v2p.vname and v.pid=v2p.pid and "
			 "     v.eid=v2p.eid "
			 "left join nodes as n on "
			 "     v2p.node_id=n.node_id "
			 "left join interfaces as i on "
			 "     n.phys_nodeid=i.node_id and i.role='ctrl' "
			 "where v.pid='%s' and v.eid='%s' and "
			 "      v2p.node_id is not null "
			 "      order by v.vnode,v.vname",
			 7, reqp->pid, reqp->eid);

	if (!res) {
		error("HOSTNAMES: %s: DB Error getting virt_lans!\n",
		      reqp->nodeid);
		return 1;
	}
	if (! (nrows = mysql_num_rows(res))) {
		mysql_free_result(res);
		return 0;
	}

	/*
	 * Parse the list, creating an entry for each node/IP pair.
	 */
	while (nrows--) {
		row = mysql_fetch_row(res);
		if (!row[0] || !row[0][0] ||
		    !row[1] || !row[1][0])
			continue;

		if (!thisvnode || strcmp(thisvnode, row[1])) {
			if (! (shareditem = (struct shareditem *)
			       calloc(1, sizeof(*shareditem)))) {
				error("HOSTNAMES: "
				      "Out of memory for shareditem!\n");
				exit(1);
			}
			thisvnode = row[1];
		}

		/*
		 * Check to see if this is the node we're talking to
		 */
		if (!strcmp(row[1], reqp->nickname)) {
		    shareditem->is_me = 1;
		}

		/*
		 * Alloc the per-link struct and fill in.
		 */
		if (! (host = (struct hostentry *) calloc(1, sizeof(*host)))) {
			error("HOSTNAMES: Out of memory!\n");
			exit(1);
		}

		strcpy(host->vlan, row[0]);
		strcpy(host->vname, row[1]);
		strcpy(host->nodeid, row[4]);
		host->virtiface = atoi(row[3]);
		host->shared = shareditem;

		/*
		 * As mentioned above, links with protocol 'ipv4'
		 * use the control net addresses of connected nodes.
		 */
		if (row[5] && strcmp("ipv4", row[5]) == 0 && row[6])
			inet_aton(row[6], &host->ipaddr);
		else
			inet_aton(row[2], &host->ipaddr);

		host->next = hosts;
		hosts = host;
	}
	mysql_free_result(res);

	/*
	 * The last part of the puzzle is to determine who is directly
	 * connected to this node so that we can add an alias for the
	 * first link to each connected node (could be more than one link
	 * to another node). Since we have the vlan names for all the nodes,
	 * its a simple matter of looking in the table for all of the nodes
	 * that are in the same vlan as the node that we are making the
	 * host table for.
	 */
	host = hosts;
	while (host) {
		/*
		 * Only care about this nodes vlans.
		 */
		if (strcmp(host->nodeid, reqp->nodeid) == 0 && host->vlan) {
			struct hostentry *tmphost = hosts;

			while (tmphost) {
				if (strlen(tmphost->vlan) &&
				    strcmp(host->vlan, tmphost->vlan) == 0 &&
				    strcmp(host->nodeid, tmphost->nodeid) &&
				    (!tmphost->shared->firstvlan ||
				     !strcmp(tmphost->vlan,
					     tmphost->shared->firstvlan))) {
					
					/*
					 * Use as flag to ensure only first
					 * link flagged as connected (gets
					 * an alias), but since a vlan could
					 * be a real lan with more than one
					 * other member, must tag all the
					 * members.
					 */
					tmphost->shared->firstvlan =
						tmphost->vlan;
				}
				tmphost = tmphost->next;
			}
		}
		host = host->next;
	}
#if 0
	host = hosts;
	while (host) {
		printf("%s %s %s %d %s %d\n", host->vname, host->nodeid,
		       host->vlan, host->virtiface, inet_ntoa(host->ipaddr),
		       host->connected);
		host = host->next;
	}
#endif

	/*
	 * Okay, spit the entries out!
	 */
	hostcount = 0;
	host = hosts;
	while (host) {
		char	*alias = " ";

		if ((host->shared->firstvlan &&
		     !strcmp(host->shared->firstvlan, host->vlan)) ||
		    /* Directly connected, first interface on this node gets an
		       alias */
		    (!strcmp(host->nodeid, reqp->nodeid) && !host->virtiface)){
			alias = host->vname;
		} else if (!host->shared->firstvlan &&
			   !host->shared->hasalias &&
			   !host->shared->is_me) {
		    /* Not directly connected, but we'll give it an alias
		       anyway */
		    alias = host->vname;
		    host->shared->hasalias = 1;
		}

2160
		node = add_node(root, "host");
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
		add_key(node, "name", host->vname);
		add_key(node, "vlan", host->vlan);
		add_key(node, "ip", inet_ntoa(host->ipaddr));
		add_format_key(node, "vertiface", "%d", host->virtiface);
		add_key(node, "aliases", alias);

#if 0
		OUTPUT(buf, sizeof(buf),
		       "NAME=%s-%s IP=%s ALIASES='%s-%i %s'\n",
		       host->vname, host->vlan,
		       inet_ntoa(host->ipaddr),
		       host->vname, host->virtiface, alias);
#endif

		host = host->next;
		hostcount++;
	}

	/*
	 * For plab slices, lets include boss and ops IPs as well
	 * in case of flaky name service on the nodes.
	 *
	 * XXX we only do this if we were going