connections.c 21.9 KB
Newer Older
Linus Tolke Y's avatar
Linus Tolke Y committed
1
/*
2
 * $Id: connections.c,v 0.54 1999/04/03 22:06:36 ceder Exp $
Per Cederqvist's avatar
Per Cederqvist committed
3
 * Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996  Lysator Academic Computer Association.
Linus Tolke Y's avatar
Linus Tolke Y committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * This file is part of the LysKOM server.
 * 
 * LysKOM is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 1, or (at your option) 
 * any later version.
 * 
 * LysKOM 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 General Public License
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with LysKOM; see the file COPYING.  If not, write to
 * Lysator, c/o ISY, Linkoping University, S-581 83 Linkoping, SWEDEN,
 * or the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, 
 * MA 02139, USA.
 *
 * Please mail bug reports to bug-lyskom@lysator.liu.se. 
 */
Per Cederqvist's avatar
Per Cederqvist committed
25 26 27 28 29 30 31 32
/*
 * connections.c
 *
 * Denna fil inneh}ller niv}n ovanf|r isc.
 *
 * Created by Willf|r 31/3-90. Mostly written by ceder.
 */

David Byers's avatar
David Byers committed
33 34 35 36 37

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

38
static const char *
39
rcsid = "$Id: connections.c,v 0.54 1999/04/03 22:06:36 ceder Exp $";
40 41
#include "rcs.h"
USE(rcsid);
Per Cederqvist's avatar
Per Cederqvist committed
42

Per Cederqvist's avatar
Per Cederqvist committed
43
#include <errno.h>
Per Cederqvist's avatar
Per Cederqvist committed
44
#include <stdio.h>
Per Cederqvist's avatar
Per Cederqvist committed
45
#include <setjmp.h>
Per Cederqvist's avatar
Per Cederqvist committed
46 47 48
#ifdef HAVE_STRING_H
#  include <string.h>
#endif
Per Cederqvist's avatar
Per Cederqvist committed
49
#include <sys/types.h>
Per Cederqvist's avatar
Per Cederqvist committed
50
#include <sys/stat.h>
Per Cederqvist's avatar
Per Cederqvist committed
51 52
#ifdef TIME_WITH_SYS_TIME
#include <sys/time.h>
Per Cederqvist's avatar
Per Cederqvist committed
53
#include <time.h>
Per Cederqvist's avatar
Per Cederqvist committed
54 55
#else
#ifdef HAVE_SYS_TIME_H
Per Cederqvist's avatar
Per Cederqvist committed
56
#include <sys/time.h>
Per Cederqvist's avatar
Per Cederqvist committed
57 58 59 60
#else
#include <time.h>
#endif
#endif
61 62 63 64
#include <sys/socket.h>
#ifdef HAVE_STDARG_H
#  include <stdarg.h>
#endif
65
#include <signal.h>
Per Cederqvist's avatar
Per Cederqvist committed
66

67
#include "ldifftime.h"
Per Cederqvist's avatar
Per Cederqvist committed
68
#include "misc-types.h"
69
#include "s-string.h"
Per Cederqvist's avatar
Per Cederqvist committed
70
#include "kom-types.h"
71
#include "kom-memory.h"
Per Cederqvist's avatar
Per Cederqvist committed
72
#include "debug.h"
73
#include "isc-interface.h"
Per Cederqvist's avatar
Per Cederqvist committed
74
#include "com.h"
75
#include "async.h"
Per Cederqvist's avatar
Per Cederqvist committed
76
#include "connections.h"
Per Cederqvist's avatar
Per Cederqvist committed
77
#include "internal-connections.h"
Per Cederqvist's avatar
Per Cederqvist committed
78
#include "prot-a-parse-arg.h"
Per Cederqvist's avatar
Per Cederqvist committed
79 80 81
#include "log.h"
#include "lyskomd.h"
#include "services.h"
Per Cederqvist's avatar
Per Cederqvist committed
82
#include "mux.h"
Per Cederqvist's avatar
Per Cederqvist committed
83 84
#include "isc-parse.h"
#include "prot-a.h"
85
#include "prot-a-parse.h"
Per Cederqvist's avatar
Per Cederqvist committed
86 87
#include "server/smalloc.h"
#include "end-of-atomic.h"
Per Cederqvist's avatar
Per Cederqvist committed
88
#include "mux-parse.h"
Per Cederqvist's avatar
Per Cederqvist committed
89 90
#include "send-async.h"
#include "cache.h"
91
#include "rfc931.h"
92
#include "param.h"
David Byers's avatar
David Byers committed
93
#include "kom-config.h"
94
#include "kom-errno.h"
Per Cederqvist's avatar
Per Cederqvist committed
95

Per Cederqvist's avatar
Per Cederqvist committed
96
IscMaster      * kom_server_mcb    = NULL;
Per Cederqvist's avatar
Per Cederqvist committed
97 98
Connection     * active_connection = NULL;

Per Cederqvist's avatar
Per Cederqvist committed
99 100 101 102 103 104
/*
 * This is set TRUE when the server should be closed. It is checked
 * each time around the main loop. It is set if someone with enough
 * privileges issues a `shutdown', or of lyskomd receives a SIGHUP.
 * This not an abort: all data is saved before we exit.
 */
105
volatile sig_atomic_t go_and_die = 0;
Per Cederqvist's avatar
Per Cederqvist committed
106 107

/*
108 109
 * The lyskomd server will dump some statistics when it receives a
 * SIGUSR1 signal.  The signal handler sets the do_statistics flag.
Per Cederqvist's avatar
Per Cederqvist committed
110
 */
111
volatile sig_atomic_t do_statistics = 0;
Per Cederqvist's avatar
Per Cederqvist committed
112 113 114 115 116 117 118 119

jmp_buf 	 parse_env;


const Fnc_descriptor fnc_defs[]={
#include "fnc-def-init.incl"
};

120 121
const unsigned long num_fnc_defs = sizeof (fnc_defs) / sizeof (Fnc_descriptor);

Per Cederqvist's avatar
Per Cederqvist committed
122
unsigned long service_statistics[sizeof (fnc_defs) / sizeof (Fnc_descriptor)];
Per Cederqvist's avatar
Per Cederqvist committed
123 124 125 126 127

BUGDECL;



Per Cederqvist's avatar
Per Cederqvist committed
128
static void
Per Cederqvist's avatar
Per Cederqvist committed
129 130 131 132 133 134
logout_client(Connection *cp)
{
    Connection *real_active_connection;

    if ( active_connection != NULL )
    {
135
	log("BUGCHK: logout_client(%ld): connection %ld is active.\n",
Per Cederqvist's avatar
Per Cederqvist committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
	    cp->session_no, active_connection->session_no);
    }
    
    switch (cp->magic)
    {
    case CONN_MAGIC_ALLOC:
        break;

    case CONN_MAGIC_FREE:
	log("LOGOUT_CLIENT: Trying to free freed Connection - ignored!\n");
	return;

    default:
	restart_kom("LOGOUT_CLIENT: Bad magic number\n");
    }

    if ( cp->pers_no != 0 )
    {
	real_active_connection = active_connection; /* Shouldn't be needed +++ */
	active_connection = cp;
	logout();
	active_connection = real_active_connection;
    }
159 160 161 162
    else
    {
        async_logout( 0, cp->session_no );
    }
Per Cederqvist's avatar
Per Cederqvist committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

    switch(cp->protocol)
    {
    case 0:			/* Hasn't yet allocated any protocol. */
	break;
	
    case 'A':
	prot_a_destruct(cp);
	break;
	
    default:
	restart_kom("logout_client(): Bad protocol.\n");
    }

    mux_close(cp);		/* Close fd's. Clear mux and isc structures. */

    kill_client(cp);		/* Free the Connection */
}

Per Cederqvist's avatar
Per Cederqvist committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195
/*
 * This function is part of the shutdown tidy-up sequence.
 */
void
logout_all_clients(void)
{
    Session_no sess = 0;
    Connection *conn;
    
    while ( (sess = traverse_connections (sess)) != 0)
    {
	conn = get_conn_by_number (sess);

	if ( conn == NULL )
196
	    restart_kom("logout_all_clients(): cant get session %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
197 198 199 200 201 202
			sess);
	else
	    logout_client (conn);
    }

    if ( traverse_connections (0) != 0)
203
	restart_kom("logout_all_clients(): traverse_connections(0) == %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
204 205 206 207
		    traverse_connections(0));
}

    
Per Cederqvist's avatar
Per Cederqvist committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    

    
/*
 * Call a function in services.c. A pointer to the result is returned.
 * The pointer points to static data which is overwritten on each call.
 */
static Success
call_function (Connection  * client,
	       Result_holder   * res)     /* This is a union. */
{
    Success	status=FAILURE;	/* OK if the call was successful. */

    if ( active_connection != NULL )
    {
223
	log("call_function(%ld): active_connection = %ld",
Per Cederqvist's avatar
Per Cederqvist committed
224 225
	    client->session_no, active_connection->session_no);
    }
226 227 228

    if (client->function == illegal_fnc) 
    {
229
        err_stat = 0;
230 231 232 233
	kom_errno = KOM_NOT_IMPL;
	return FAILURE;
    }

Per Cederqvist's avatar
Per Cederqvist committed
234 235
    active_connection = client;

236
    service_statistics[client->function_index]++;
Per Cederqvist's avatar
Per Cederqvist committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

#include "call-switch.incl"

    active_connection = NULL;

    return status;
}


static void
parse_packet(Connection *client)
{
    if ( client->protocol == '\0' ) /* Not known yet. */
    {
	client->protocol = parse_char(client);
	switch(client->protocol)
	{
	case 'A':
	    prot_a_init(client);
	    break;

	default:
	    client->protocol = '\0';
	    mux_printf(client,
		    "%%%%LysKOM unsupported protocol.\n");
	    mux_flush(client);
	    BUG(("%%%%Unsupported protocol.\n"));
	    longjmp(parse_env, ISC_LOGOUT);
	}
    }

    switch(client->protocol)
    {
    case 'A':
	prot_a_parse_packet(client);
	break;

    default:
	restart_kom("parse_packet(): Bad protocol.\n");
	break;
    }
}

/*
 * Free all parsed areas which are no longer needed. Re-initialize all
 * parse_pos fields so that the parse will expect a new function.
 *
 * This function is called
 *	when a parse error occurs
 *	when a parse is complete and the function has executed.
 */
static void
free_parsed(Connection *client)
{
    s_clear(&client->c_string0);
    s_clear(&client->c_string1);
    client->string0 = EMPTY_STRING; /* So that no one frees it. */
294
    sfree( client->c_misc_info_p );
Per Cederqvist's avatar
Per Cederqvist committed
295
    client->c_misc_info_p = NULL;
296
    s_clear(&client->aux_item.data);
Per Cederqvist's avatar
Per Cederqvist committed
297 298 299 300
    sfree( client->c_local_text_no_p);
    client->c_local_text_no_p = NULL;
    client->parse_pos = 0;
    client->fnc_parse_pos = 0;
301
    client->array_parse_index = 0;
Per Cederqvist's avatar
Per Cederqvist committed
302 303 304
    client->array_parse_pos = 0;
    client->struct_parse_pos = 0;
    client->string_parse_pos = 0;
305 306 307
    sfree(client->num_list.data);
    client->num_list.data = NULL;
    client->num_list.length = 0;
308 309
    free_aux_item_list(&client->aux_item_list);
    client->info.highest_aux_no = 0;
Per Cederqvist's avatar
Per Cederqvist committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
}

/*
 * Send a reply to a call.
 */
static void
reply(Connection *client,
      Success	      status,
      Result_holder  *result)
{
    switch(client->protocol)
    {
    case 'A':
	prot_a_reply(client, status, result);
	break;

    default:
	restart_kom("reply(): Bad protocol.\n");
	break;
    }
}


/*
 * Try to parse enough data from client->unparsed to call a function.
 * If more data is needed set client->more_to_parse to FALSE.
 */
static void
parse_unparsed(Connection *client)
{
    String        tmp_str = EMPTY_STRING;
    Success       status;
    Result_holder result;
        
    switch ( setjmp(parse_env) )
    {
    case 0 :
	/* Parse message. If message is complete call function and reply. */
	parse_packet(client);
	status = call_function(client, &result);
	reply(client, status, &result);
	free_parsed(client);
	end_of_atomic(FALSE);
	break;

    case ISC_PROTOCOL_ERR:
	s_clear(&client->string0);
	free_parsed(client);
	mux_printf(client, "%% LysKOM protocol error.\n");
	mux_flush(client);
	BUG(("%%%% Protocol error.\n"));
	s_clear(&client->unparsed);
	client->first_to_parse = 0;
	client->more_to_parse = FALSE;
	end_of_atomic(FALSE);
	break;

    case ISC_MSG_INCOMPLETE:
	client->more_to_parse = FALSE;
	break;

    case ISC_LOGOUT:
372
	add_to_kill_list(client);
Per Cederqvist's avatar
Per Cederqvist committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
	break;
    }
    
    /* Delete the parsed part of 'unparsed' */
    
    if ( s_substr(&tmp_str, client->unparsed,
		  client->first_to_parse, END_OF_STRING) != OK )
	restart_kom("parse_unparsed: s_substr\n");

    s_clear(&client->unparsed);
    client->unparsed = tmp_str;
    client->first_to_parse = 0;
}


/*
 * There is a message in the event. Parse it.
 */
static void
parse_message(Connection *cp, String tmp_str)
{
    VBUGSTR(tmp_str);

    cp->more_to_parse = TRUE;
    
    if ( s_strcat(&cp->unparsed, tmp_str) != OK )
	restart_kom("parse_message(): s_strcat\n");

    tmp_str = EMPTY_STRING;
    
    /* Parse this packet, but leave the last token if it isn't complete. */

    parse_unparsed(cp);

    return;
}

static void
mux_handle_packet(Mux *mux)
{
    Mux_client *mcp = NULL;
    Connection *cp = NULL;

    switch(mux->parse.function)
    {
    case 0:			/* ping */
	isc_printf(mux->scb, "0\n");
	isc_flush(mux->scb);
	break;

    case 1:			/* login */

	mcp = mux_getclientbyid(mux, mux->parse.num);
	if (mcp)
	{			/* ERROR %d: Already logged in\n */
	    isc_printf(mux->scb, "4\n");
	    isc_flush(mux->scb);
	    return;
	}
    
	cp = new_client();
	cp->mux = mux;
	cp->hostname = mux->parse.string;
	mux->parse.string = EMPTY_STRING;
	
	mux_addclient(mux, mux->parse.num, cp);

    
441
	BUG(("\n[Client %lu from %.*s via MUX %s",
Per Cederqvist's avatar
Per Cederqvist committed
442
	     cp->session_no,
Per Cederqvist's avatar
Per Cederqvist committed
443
	     (int)cp->hostname.len,
Per Cederqvist's avatar
Per Cederqvist committed
444
	     cp->hostname.string,
Per Cederqvist's avatar
Per Cederqvist committed
445
	     isc_gethostname(mux->scb->info.tcp.raddr, NULL, 0)));
Per Cederqvist's avatar
Per Cederqvist committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
	BUG((" is connecting]\n"));

	break;
    
    case 2:			/* logout */
	mcp = mux_getclientbyid(mux, mux->parse.num);
	if (!mcp)
	{			/* ERROR %d: No such mux-session */
	    isc_printf(mux->scb, "4\n");
	    isc_flush(mux->scb);
	    return;
	}

	cp = mcp->conn;
    
461
	BUG(("\n[Client %lu via MUX(%s)",
Per Cederqvist's avatar
Per Cederqvist committed
462
	     cp->session_no,
Per Cederqvist's avatar
Per Cederqvist committed
463
	     isc_gethostname(mux->scb->info.tcp.raddr, NULL, 0)));
Per Cederqvist's avatar
Per Cederqvist committed
464 465
	BUG((" is logging out by request]\n"));

466
	add_to_kill_list(cp);
Per Cederqvist's avatar
Per Cederqvist committed
467 468 469 470 471 472 473 474 475 476 477 478 479
	break;

    case 3:			/* msg */
	mcp = mux_getclientbyid(mux, mux->parse.num);
	if (!mcp)
	{			/* ERROR %d: No such mux-session */
	    isc_printf(mux->scb, "4\n");
	    isc_flush(mux->scb);
	    return;
	}
    
	cp = mcp->conn;
    
480 481
	VBUG(("\n[Message client %lu via MUX #%lu]\n",
	      cp->session_no, (unsigned long)mux->scb));
Per Cederqvist's avatar
Per Cederqvist committed
482 483 484 485 486 487

	parse_message(cp, mux->parse.string);
	break;

    default:
	
488 489
	VBUG(("\nMUX Protocol error from MUX #%lu]\n",
	      (unsigned long)mux->scb));
Per Cederqvist's avatar
Per Cederqvist committed
490 491 492 493 494 495 496 497

	isc_printf(mux->scb, "5\n");
	isc_flush(mux->scb);
	break;
	
    }
}
	
Per Cederqvist's avatar
Per Cederqvist committed
498
static void
Per Cederqvist's avatar
Per Cederqvist committed
499 500 501 502 503 504 505
mux_logout(Mux *mp)
{
    int i;

    for (i = 0; i < mp->client_c; i++)
	if (mp->client_v[i].conn)
	{
506
	    BUG(("\n[Client %lu via MUX(%s)",
Per Cederqvist's avatar
Per Cederqvist committed
507
		 mp->client_v[i].conn->session_no,
Per Cederqvist's avatar
Per Cederqvist committed
508
		 isc_gethostname(mp->scb->info.tcp.raddr, NULL, 0)));
Per Cederqvist's avatar
Per Cederqvist committed
509 510 511 512 513
	    BUG((" is logging out by MUX shutdown]\n"));
	    logout_client(mp->client_v[i].conn);
	    end_of_atomic(FALSE);
	}
	      
Per Cederqvist's avatar
Per Cederqvist committed
514
    isc_destroy(kom_server_mcb, mp->scb);
Per Cederqvist's avatar
Per Cederqvist committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    mux_destruct(mp);
}


static void
mux_parse_unparsed(Mux *mux)
{
    String        tmp_str;

    while ( mux->parse.more_to_parse )
    {
	switch ( setjmp(mux_parse_env) )
	{
	case 0 :
	    /* Parse message. Take apropriate action if message is complete. */
	    mux_parse_packet(mux);
	    mux_handle_packet(mux);
	    mux_free_parsed(mux);
	    break;

	case MUX_PROTOCOL_ERR:
	    s_clear(&mux->parse.string);
	    mux_free_parsed(mux);
	    isc_printf(mux->scb, "5\n");
	    isc_flush(mux->scb);
	    BUG(("%%%% Mux protocol error.\n"));
	    s_clear(&mux->parse.unparsed);
	    mux->parse.first_to_parse = 0;
	    mux->parse.more_to_parse = FALSE;
	    break;

	case MUX_MSG_INCOMPLETE:
	    mux->parse.more_to_parse = FALSE;
	    break;

	case MUX_LOGOUT:
	    mux_logout(mux);
	    return;
	}
    
	/* Delete the parsed part of 'unparsed' */

	tmp_str = EMPTY_STRING;

	if ( s_substr(&tmp_str, mux->parse.unparsed,
		      mux->parse.first_to_parse, END_OF_STRING) != OK )
	    restart_kom("mux_parse_unparsed: s_substr\n");

	s_clear(&mux->parse.unparsed);
	mux->parse.unparsed = tmp_str;
	mux->parse.first_to_parse = 0;
    }
}


static void
mux_parse_message(Mux *mp, String tmp_str)
{
    VBUGSTR(tmp_str);

575
    BUG(("%s(): mp->parse.unparsed = { len = %lu, string = %p }\n", 
Per Cederqvist's avatar
Per Cederqvist committed
576 577
	 "mux_parse_message",
	 mp->parse.unparsed.len,
Per Cederqvist's avatar
Per Cederqvist committed
578
	 (void *)mp->parse.unparsed.string));
Per Cederqvist's avatar
Per Cederqvist committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    
    if ( s_strcat(&mp->parse.unparsed, tmp_str) != OK )
	restart_kom("mux_parse_message(): s_strcat\n");

    tmp_str = EMPTY_STRING;
    
    /* Parse this packet, but leave the last token if it isn't complete. */

    mux_parse_unparsed(mp);

    return;
}

/*
 * parse data in client->unparsed and mux->unparsed if there
 * is data that has not yet been taken care of. Return TRUE
 * if there was no data to take care of.
 */
Per Cederqvist's avatar
Per Cederqvist committed
597 598
static Bool
parse_forgotten(void)
Per Cederqvist's avatar
Per Cederqvist committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
{
    Bool flg = FALSE;			/* Was there anything? */
    Connection *ci;
    Session_no session_no = 0;

    if ( traverse_connections(0) == 0 )
	return TRUE;

    while ( ( session_no = traverse_connections( session_no ) ) != 0 )
    {
	ci = get_conn_by_number (session_no);

	if ( ci->more_to_parse )
	{
	    parse_unparsed(ci);
	    flg = TRUE;
	}
    }

618
    return flg ? FALSE : TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
619 620 621 622 623
}


/* Return 1 if the named file exists, 0 otherwise */
static int
Per Cederqvist's avatar
Per Cederqvist committed
624
fexists(const char *filename)
Per Cederqvist's avatar
Per Cederqvist committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
{
    struct stat buf;
    int code;
  
    code = !stat(filename, &buf);
    errno = 0;

    return code;
}


void
dump_statistics(void)
{
    static time_t last_dump = NO_TIME;
    int i;
    time_t now;
    FILE *fp;

644
    if ((fp = fopen(param.statistic_name, "a")) == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
645
    {
Per Cederqvist's avatar
Per Cederqvist committed
646 647
	log("%s: dump_statistics(): can't open file %s\n",
	    __FILE__,
648
	    param.statistic_name);
Per Cederqvist's avatar
Per Cederqvist committed
649 650 651 652 653 654 655 656 657 658 659 660
	return;
    }

    time(&now);

    if (last_dump == NO_TIME)
    {
	fprintf(fp, "RESTART\n");
	last_dump = now;
    }
    
    fprintf(fp, "TIME: %s", ctime(&now));
661
    fprintf(fp, "SECONDS: %d\n", (int)ldifftime(now, last_dump));
Per Cederqvist's avatar
Per Cederqvist committed
662
    fprintf(fp, "STATISTICS:");
David Byers's avatar
David Byers committed
663
    for ( i = 0; (size_t)i < sizeof(service_statistics) / sizeof(unsigned long); i++)
Per Cederqvist's avatar
Per Cederqvist committed
664
    {
665 666 667 668
	fprintf(fp, " %d:%lu",
                fnc_defs[i].function,
                service_statistics[i]
                );
Per Cederqvist's avatar
Per Cederqvist committed
669 670 671 672 673 674 675 676 677
	service_statistics[i]=0;
    }

    fprintf(fp, "\n");
    fclose(fp);

    last_dump = now;
}

678 679 680 681 682 683 684 685 686
/* List of connections to kill. */

Session_no *kill_list = NULL;
int kill_list_size = 0;

/* Schedule this client for termination. */
void
add_to_kill_list(Connection *conn)
{
Per Cederqvist's avatar
Per Cederqvist committed
687 688 689
    int i;

    for (i = 0; i < kill_list_size; i++)
690
	if (kill_list[i] == conn->session_no)
Per Cederqvist's avatar
Per Cederqvist committed
691
	{
692
	    log("add_to_kill_list(%ld): already present as %d of %d.\n",
Per Cederqvist's avatar
Per Cederqvist committed
693 694 695 696
		conn->session_no, i, kill_list_size);
	    return;
	}

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    if (kill_list == NULL)
    {
	if (kill_list_size != 0)
	    restart_kom("add_to_kill_list(): size = %d\n", kill_list_size);

	kill_list_size = 1;
	kill_list = smalloc(sizeof(Session_no));
    }
    else
    {
	kill_list_size++;
	kill_list = srealloc(kill_list, kill_list_size * sizeof(Session_no));
    }

    kill_list[kill_list_size-1] = conn->session_no;
}
Per Cederqvist's avatar
Per Cederqvist committed
713 714 715 716 717 718 719 720 721 722 723

/*
 * check_kill_flg must NEVER be called inside an atomic call!
 */
static void
check_kill_flg(void)
{
    Connection *conn;

    if ( active_connection != NULL )
    {
724
	restart_kom("check_kill_flg: active_connection == %ld",
Per Cederqvist's avatar
Per Cederqvist committed
725 726 727
		    active_connection->session_no);
    }

728
    while (kill_list_size > 0)
Per Cederqvist's avatar
Per Cederqvist committed
729
    {
730 731 732
	--kill_list_size;
	conn = get_conn_by_number (kill_list[kill_list_size]);
	if (conn == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
733
	{
734
	    log("check_kill_flg(): Connection %ld doesn't exist.\n",
735 736 737 738 739 740
		kill_list[kill_list_size]);
	}
	else
	{
	    logout_client (conn);
	    end_of_atomic (FALSE);
Per Cederqvist's avatar
Per Cederqvist committed
741 742
	}
    }
743

744 745 746 747 748
    if (kill_list != NULL)
    {
	sfree (kill_list);
	kill_list = NULL;
    }
Per Cederqvist's avatar
Per Cederqvist committed
749 750 751
}

static void
Per Cederqvist's avatar
Per Cederqvist committed
752
login_request(IscEvent  *event)
Per Cederqvist's avatar
Per Cederqvist committed
753 754
{
    Connection  * cp;
755
    const char *realuser;
756 757
    int localport;
    IscAddress *isc_adr;
758
    char *hostname = NULL;
Per Cederqvist's avatar
Per Cederqvist committed
759 760 761 762 763 764

    if (isc_sessions(kom_server_mcb) >= MAX_NO_OF_CONNECTIONS)
    {
	BUG(("Connection attempt rejected.\n"));
	isc_printf(event->session, "%s", "%% No connections left.\n");
	isc_flush(event->session);
Per Cederqvist's avatar
Per Cederqvist committed
765
	isc_destroy(kom_server_mcb, event->session);
Per Cederqvist's avatar
Per Cederqvist committed
766 767 768 769 770 771 772 773 774 775
	      
	async_rejected_connection();
	return;
    }

    /* Supress logins if /etc/nologin exists */
    if (fexists("/etc/nologin"))
    {
	isc_printf(event->session, "%s", "%% No logins allowed.\n");
	isc_flush(event->session);
Per Cederqvist's avatar
Per Cederqvist committed
776
 	isc_destroy(kom_server_mcb, event->session);
Per Cederqvist's avatar
Per Cederqvist committed
777 778 779
	return;
    }

780 781 782 783 784 785
    /* Find out if it is a mux or a client that tries to connect to
       us.  Do it by getting the local port number. */

    isc_adr = isc_getladdress (event->session);
    if (isc_adr == NULL)
	restart_kom("login_request(): can't isc_getladdress (%lu)\n",
786
		    (unsigned long)event->session);
787 788 789 790

    localport = isc_getportnum (isc_adr);
    isc_freeaddress (isc_adr);
    
791
    if (localport == param.num_ip_mux_port)
Per Cederqvist's avatar
Per Cederqvist committed
792 793 794 795 796 797 798 799
    {
	/* Multiplexer requesting connection */

	/*
	 ** Create, and setup the MUX for the MUX case
	 */
	event->session->udg = mux_create(MUX_TYPE_MUX, event->session);
	      
800 801
	BUG(("MUX #%lu at %s connecting.\n",
	     (unsigned long)event->session,
Per Cederqvist's avatar
Per Cederqvist committed
802
	     isc_gethostname(event->session->info.tcp.raddr, NULL, 0)));
Per Cederqvist's avatar
Per Cederqvist committed
803
    }
804
    else if (localport == param.num_ip_client_port)
Per Cederqvist's avatar
Per Cederqvist committed
805 806 807
    {
	/* Client requesting connection */
	      
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
	hostname = isc_gethostname(event->session->info.tcp.raddr, NULL, 0);
	if (hostname == NULL)
	    hostname = isc_getipnum(event->session->info.tcp.raddr, NULL, 0);
	if (hostname == NULL)
	    log("WNG: login_request(): unknown hostid.\n");

	/* Get the real user name, as returned by the Ident protocol
	   (rfc 931). */
	realuser = get_real_username(event->session, hostname);
	if (realuser == NULL && param.authentication_level == 2)
	{
	    log ("Connection from %s rejected - no IDENT available.\n", 
		 hostname);

	    isc_printf(event->session, "%s", 
		       "%% No IDENT server reachable at your site.\n");
	    isc_flush(event->session);
	    isc_destroy(kom_server_mcb, event->session);
	    return;
	}

Per Cederqvist's avatar
Per Cederqvist committed
829 830 831 832 833 834 835 836
	/*
	 ** Create, and setup the MUX for the CLIENT case
	 */
	event->session->udg = mux_create(MUX_TYPE_CLIENT,
					 event->session);
	      
	cp = new_client();
	cp->mux = event->session->udg;
837 838 839 840
	if (hostname == NULL)
	    s_crea_str(&cp->hostname, "unknown");
	else
	    s_crea_str(&cp->hostname, hostname);
841 842 843 844

	if (realuser != NULL)
	    s_crea_str(&cp->ident_user, realuser);

Per Cederqvist's avatar
Per Cederqvist committed
845 846
	mux_addclient(event->session->udg, 0, cp);
	      
847 848
	BUG(("\n[Client %lu from %s is connecting]\n", cp->session_no, 
	     hostname));
849 850 851 852 853 854
    }
    else
    {
	/* Help! It was neither a client, nor a mux. */
	restart_kom("login_request(): Neither client, nor mux.\n");
    }
Per Cederqvist's avatar
Per Cederqvist committed
855 856 857
}

static void
Per Cederqvist's avatar
Per Cederqvist committed
858
logout_request(IscEvent *event)
Per Cederqvist's avatar
Per Cederqvist committed
859 860 861 862 863
{
    Connection  * cp;
    
    if (event->session->udg->type == MUX_TYPE_MUX)
    {
864
	BUG(("\n[MUX #%lu at %s", (unsigned long)event->session,
Per Cederqvist's avatar
Per Cederqvist committed
865
	     isc_gethostname(event->session->info.tcp.raddr, NULL, 0)));
Per Cederqvist's avatar
Per Cederqvist committed
866 867 868 869 870 871 872 873 874 875 876
	BUG((" is logging out]\n"));

	/*
	 ** Logout any remaining clients
	 */
	mux_logout(event->session->udg);
    }
    else
    {
	cp = event->session->udg->client_v[0].conn;
	      
877
	BUG(("\n[Client %lu from %s", cp->session_no,
Per Cederqvist's avatar
Per Cederqvist committed
878
	     isc_gethostname(event->session->info.tcp.raddr, NULL, 0)));
Per Cederqvist's avatar
Per Cederqvist committed
879 880
	BUG((" is logging out]\n"));
	      
881
	add_to_kill_list(cp);
Per Cederqvist's avatar
Per Cederqvist committed
882 883 884 885 886
    }
}


static void
Per Cederqvist's avatar
Per Cederqvist committed
887
message_request(IscEvent *event)
Per Cederqvist's avatar
Per Cederqvist committed
888 889 890 891 892 893 894
{
    Connection *cp;
    String      tmp_str;

    if (event->session->udg->type == MUX_TYPE_MUX)
    {
	event->session->udg->parse.more_to_parse = TRUE;
895
	tmp_str.string = (unsigned char *)event->msg->buffer;
Per Cederqvist's avatar
Per Cederqvist committed
896 897 898 899 900 901
	tmp_str.len    = event->msg->length;
	mux_parse_message(event->session->udg, tmp_str);
    }
    else
    {
	cp = event->session->udg->client_v[0].conn;
902
	VBUG(("\n[Message from client %lu]\n",
Per Cederqvist's avatar
Per Cederqvist committed
903 904 905 906
	      cp->session_no));
	/*
	 ** Pass the message on to the parser
	 */
907
	tmp_str.string = (unsigned char *)event->msg->buffer;
Per Cederqvist's avatar
Per Cederqvist committed
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	tmp_str.len    = event->msg->length;
	parse_message(cp, tmp_str);
    }
}

static long
timevaldiff(struct timeval a,
	    struct timeval b)
{
    return 1000000 * (a.tv_sec - b.tv_sec) + a.tv_usec - b.tv_usec;
}

void
toploop(void)
{
Per Cederqvist's avatar
Per Cederqvist committed
923
    IscEvent      * event;
Per Cederqvist's avatar
Per Cederqvist committed
924 925 926 927
    Bool	pending_input = TRUE; /* Should be TRUE whenever there
				         is or might be pending input
					 from any client in the unparsed
					 buffer. */
928 929 930
    long	timeout = 0;        /* In milliseconds. Start with a
				       small value since we should
				       start garbing right away. */
Per Cederqvist's avatar
Per Cederqvist committed
931 932 933 934
    struct timeval before, after;
    
    while ( !go_and_die )
    {
935
        if (do_statistics)
Per Cederqvist's avatar
Per Cederqvist committed
936 937
	{
	    dump_statistics();
938
	    do_statistics = 0;
Per Cederqvist's avatar
Per Cederqvist committed
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
	}

	gettimeofday(&before, NULL);
	event = isc_getnextevent(kom_server_mcb,
				 pending_input ? 0 : timeout );
	gettimeofday(&after, NULL);

	timeout -= timevaldiff(after, before) / 1000;

	if ( timeout < 0 )
	    timeout = 0;
	
	if ( event == NULL )
	    restart_kom("toploop(): Got NULL event - shouldn't happen...\n");

	switch ( event->event )
	{
	case ISC_EVENT_ERROR:
	    if (errno != EINTR)
	    {
		log("toploop: ISC_EVENT_ERROR (error = '%s'):\n   '%s'\n",
		    strerror(errno), event->msg ? event->msg->buffer
		    : "(unknown)");
	    }
	    break;
	    
	case ISC_EVENT_TIMEOUT:
	    BUG((">"));
967
#ifndef NDEBUG
968 969
	    if (buglevel > 0)
		fflush(stdout);
Per Cederqvist's avatar
Per Cederqvist committed
970 971 972 973 974 975 976
#endif
	    if ( pending_input == FALSE )
		timeout = end_of_atomic(TRUE); /* Idle. Do some cleaning up. */
	    else
	    {
		if ( timeout == 0 )
		    end_of_atomic(FALSE);
977
		pending_input = (parse_forgotten() ? FALSE : TRUE);
Per Cederqvist's avatar
Per Cederqvist committed
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
	    }
	    
	    	    
	    break;
	    
	case ISC_EVENT_LOGIN:
	    pending_input = TRUE;
	    login_request(event);
	    break;

	case ISC_EVENT_LOGOUT:
	    pending_input = TRUE;
	    logout_request(event);
	    break;

 	case ISC_EVENT_MESSAGE:
	    pending_input = TRUE;
	    message_request(event);
	    break;

	default:
	    pending_input = TRUE;
	    log("ERROR: toploop(): Unknown ISC_EVENT\n");
	    break;
	}

        isc_dispose(event);

	check_kill_flg();
    }
}