connections.c 19.8 KB
Newer Older
Linus Tolke Y's avatar
Linus Tolke Y committed
1
/*
2
 * $Id: connections.c,v 0.92 2003/03/15 22:30:10 ceder Exp $
Per Cederqvist's avatar
Per Cederqvist committed
3
 * Copyright (C) 1991-2002  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

Per Cederqvist's avatar
Per Cederqvist committed
38
#include <errno.h>
Per Cederqvist's avatar
Per Cederqvist committed
39
#include <stdio.h>
Per Cederqvist's avatar
Per Cederqvist committed
40
#include <setjmp.h>
Per Cederqvist's avatar
Per Cederqvist committed
41 42 43
#ifdef HAVE_STRING_H
#  include <string.h>
#endif
Per Cederqvist's avatar
Per Cederqvist committed
44
#include <sys/types.h>
Per Cederqvist's avatar
Per Cederqvist committed
45
#include <sys/stat.h>
Per Cederqvist's avatar
Per Cederqvist committed
46
#ifdef TIME_WITH_SYS_TIME
47 48
#  include <sys/time.h>
#  include <time.h>
Per Cederqvist's avatar
Per Cederqvist committed
49
#else
50 51 52 53 54
#  ifdef HAVE_SYS_TIME_H
#    include <sys/time.h>
#  else
#    include <time.h>
#  endif
Per Cederqvist's avatar
Per Cederqvist committed
55
#endif
56
#include <sys/socket.h>
57
#include <signal.h>
Per Cederqvist's avatar
Per Cederqvist committed
58

59
#include "ldifftime.h"
Per Cederqvist's avatar
Per Cederqvist committed
60
#include "misc-types.h"
61
#include "s-string.h"
Per Cederqvist's avatar
Per Cederqvist committed
62
#include "kom-types.h"
63
#include "kom-memory.h"
Per Cederqvist's avatar
Per Cederqvist committed
64
#include "debug.h"
65
#include "isc-interface.h"
Per Cederqvist's avatar
Per Cederqvist committed
66
#include "com.h"
67
#include "async.h"
Per Cederqvist's avatar
Per Cederqvist committed
68
#include "connections.h"
Per Cederqvist's avatar
Per Cederqvist committed
69
#include "internal-connections.h"
Per Cederqvist's avatar
Per Cederqvist committed
70
#include "prot-a-parse-arg.h"
Per Cederqvist's avatar
Per Cederqvist committed
71 72 73 74 75
#include "log.h"
#include "lyskomd.h"
#include "services.h"
#include "isc-parse.h"
#include "prot-a.h"
76
#include "prot-a-parse.h"
Per Cederqvist's avatar
Per Cederqvist committed
77 78 79 80
#include "server/smalloc.h"
#include "end-of-atomic.h"
#include "send-async.h"
#include "cache.h"
81
#include "rfc931.h"
82
#include "param.h"
David Byers's avatar
David Byers committed
83
#include "kom-config.h"
84
#include "kom-errno.h"
Per Cederqvist's avatar
Per Cederqvist committed
85
#include "sigflags.h"
Per Cederqvist's avatar
Per Cederqvist committed
86
#include "server-time.h"
87
#include "aux-items.h"
88
#include "eintr.h"
Per Cederqvist's avatar
Per Cederqvist committed
89

Per Cederqvist's avatar
Per Cederqvist committed
90
IscMaster      * kom_server_mcb    = NULL;
Per Cederqvist's avatar
Per Cederqvist committed
91 92
Connection     * active_connection = NULL;

Per Cederqvist's avatar
Per Cederqvist committed
93 94 95 96 97 98
/*
 * 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.
 */
99
volatile sig_atomic_t go_and_die = 0;
Per Cederqvist's avatar
Per Cederqvist committed
100 101

/*
102 103
 * 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
104
 */
105
volatile sig_atomic_t do_statistics = 0;
Per Cederqvist's avatar
Per Cederqvist committed
106 107 108 109 110 111 112 113

jmp_buf 	 parse_env;


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

114
const int num_fnc_defs = sizeof (fnc_defs) / sizeof (Fnc_descriptor);
115

Per Cederqvist's avatar
Per Cederqvist committed
116
unsigned long service_statistics[sizeof (fnc_defs) / sizeof (Fnc_descriptor)];
Per Cederqvist's avatar
Per Cederqvist committed
117 118 119 120 121

BUGDECL;



Per Cederqvist's avatar
Per Cederqvist committed
122
static void
Per Cederqvist's avatar
Per Cederqvist committed
123 124 125
logout_client(Connection *cp)
{
    Connection *real_active_connection;
126
    int ret;
Per Cederqvist's avatar
Per Cederqvist committed
127 128 129

    if ( active_connection != NULL )
    {
David Byers's avatar
David Byers committed
130
	kom_log("BUGCHK: logout_client(%ld): connection %ld is active.\n",
Per Cederqvist's avatar
Per Cederqvist committed
131 132 133 134 135
	    cp->session_no, active_connection->session_no);
    }
    
    if ( cp->pers_no != 0 )
    {
136 137 138 139 140 141 142 143 144 145 146 147
	int ctr = 0;

	if (active_connection != NULL)
	{
	    kom_log("WNG: logout_client(): active_connection != NULL\n");
	    if (ctr < 100)
		ctr++;
	    else
		kom_log("WNG: won't log the above message more\n");
	}

	real_active_connection = active_connection;
Per Cederqvist's avatar
Per Cederqvist committed
148 149 150 151
	active_connection = cp;
	logout();
	active_connection = real_active_connection;
    }
152 153
    else
    {
154
#if 0
155
	/* FIXME (bug 908): send a new async here instead.  This causes the
156 157
	   elisp client to say that a secret (or unknown) person has
	   left the system.  */
158
        async_logout( 0, cp->session_no );
159
#endif
160
    }
Per Cederqvist's avatar
Per Cederqvist committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174

    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");
    }

175 176
    ret = isc_destroy(kom_server_mcb, cp->isc_session);
    if (ret < 0)
David Byers's avatar
David Byers committed
177
	kom_log("logout_client(): isc_destroyed returned %d\n", ret);
178
    cp->isc_session = NULL;
Per Cederqvist's avatar
Per Cederqvist committed
179 180 181 182

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

Per Cederqvist's avatar
Per Cederqvist committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196
/*
 * 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 )
197
	    restart_kom("logout_all_clients(): cant get session %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
198 199 200 201 202 203
			sess);
	else
	    logout_client (conn);
    }

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

    
Per Cederqvist's avatar
Per Cederqvist committed
209 210 211 212 213 214 215 216
    

    
/*
 * 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
217 218
call_function(Connection *client,
	      union result_holder *res)
Per Cederqvist's avatar
Per Cederqvist committed
219 220 221 222 223
{
    Success	status=FAILURE;	/* OK if the call was successful. */

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

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

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

237
    service_statistics[client->function_index]++;
Per Cederqvist's avatar
Per Cederqvist committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

#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';
261 262
	    isc_puts("%%LysKOM unsupported protocol.\n", client->isc_session);
	    isc_flush(client->isc_session);
Per Cederqvist's avatar
Per Cederqvist committed
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
	    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. */
David Byers's avatar
David Byers committed
294 295 296
    sfree(client->misc_info_list.misc);
    client->misc_info_list.misc = 0;
    client->misc_info_list.no_of_misc = 0;
297
    s_clear(&client->aux_item.data);
298
    s_clear(&client->dummy_aux_item.data);
Per Cederqvist's avatar
Per Cederqvist committed
299 300
    sfree( client->c_local_text_no_p);
    client->c_local_text_no_p = NULL;
301 302 303
    sfree(client->read_range_list.ranges);
    client->read_range_list.ranges = NULL;
    client->read_range_list.length = 0;
Per Cederqvist's avatar
Per Cederqvist committed
304 305
    client->parse_pos = 0;
    client->fnc_parse_pos = 0;
306
    client->array_parse_index = 0;
David Byers's avatar
David Byers committed
307
    client->array_parse_parsed_length = 0;
Per Cederqvist's avatar
Per Cederqvist committed
308 309 310
    client->array_parse_pos = 0;
    client->struct_parse_pos = 0;
    client->string_parse_pos = 0;
David Byers's avatar
David Byers committed
311 312 313
    client->hunt_parse_pos = 0;
    client->array_hunt_num = 0;
    client->array_hunt_depth = 0;
314 315 316
    sfree(client->num_list.data);
    client->num_list.data = NULL;
    client->num_list.length = 0;
317 318
    free_aux_item_list(&client->aux_item_list);
    client->info.highest_aux_no = 0;
Per Cederqvist's avatar
Per Cederqvist committed
319 320 321 322 323 324 325
}

/*
 * Send a reply to a call.
 */
static void
reply(Connection *client,
326 327
      Success status,
      union result_holder *result)
Per Cederqvist's avatar
Per Cederqvist committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
{
    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;
351
    union result_holder result;
Per Cederqvist's avatar
Per Cederqvist committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        
    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);
367 368
	isc_puts("%% LysKOM protocol error.\n", client->isc_session);
	isc_flush(client->isc_session);
Per Cederqvist's avatar
Per Cederqvist committed
369 370 371 372 373 374 375 376 377 378 379 380
	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:
381
	add_to_kill_list(client);
Per Cederqvist's avatar
Per Cederqvist committed
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
	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;
}


/*
421
 * parse data in client->unparsed if there
Per Cederqvist's avatar
Per Cederqvist committed
422 423 424
 * 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
425 426
static Bool
parse_forgotten(void)
Per Cederqvist's avatar
Per Cederqvist committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
{
    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;
	}
    }

446
    return flg ? FALSE : TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
447 448 449 450 451
}


/* Return 1 if the named file exists, 0 otherwise */
static int
Per Cederqvist's avatar
Per Cederqvist committed
452
fexists(const char *filename)
Per Cederqvist's avatar
Per Cederqvist committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
{
    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;
    FILE *fp;

471
    if ((fp = i_fopen(param.statistic_name, "a")) == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
472
    {
473 474
	kom_log("dump_statistics(): can't open file %s\n",
		param.statistic_name);
Per Cederqvist's avatar
Per Cederqvist committed
475 476 477 478 479 480
	return;
    }

    if (last_dump == NO_TIME)
    {
	fprintf(fp, "RESTART\n");
Per Cederqvist's avatar
Per Cederqvist committed
481
	last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
482 483
    }
    
Per Cederqvist's avatar
Per Cederqvist committed
484 485
    fprintf(fp, "TIME: %s", ctime(&current_time));
    fprintf(fp, "SECONDS: %d\n", (int)ldifftime(current_time, last_dump));
Per Cederqvist's avatar
Per Cederqvist committed
486
    fprintf(fp, "STATISTICS:");
487 488 489 490 491

    /* The last entry corresponds to the dummy entry that is used to
       skip arguments to unimplemented requests.  Skip that, since it
       contains no useful statistics.  */
    for (i = 0; i < num_fnc_defs - 1; i++)
Per Cederqvist's avatar
Per Cederqvist committed
492
    {
493
	fprintf(fp, " %d:%lu", fnc_defs[i].function, service_statistics[i]);
Per Cederqvist's avatar
Per Cederqvist committed
494 495 496 497
	service_statistics[i]=0;
    }

    fprintf(fp, "\n");
498
    i_fclose(fp);
Per Cederqvist's avatar
Per Cederqvist committed
499

Per Cederqvist's avatar
Per Cederqvist committed
500
    last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
501 502
}

503 504
/* List of connections to kill. */

Per Cederqvist's avatar
Per Cederqvist committed
505 506
static Session_no *kill_list = NULL;
static int kill_list_size = 0;
507 508 509 510 511

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

    for (i = 0; i < kill_list_size; i++)
515
	if (kill_list[i] == conn->session_no)
Per Cederqvist's avatar
Per Cederqvist committed
516
	{
David Byers's avatar
David Byers committed
517
	    kom_log("add_to_kill_list(%ld): already present as %d of %d.\n",
Per Cederqvist's avatar
Per Cederqvist committed
518 519 520 521
		conn->session_no, i, kill_list_size);
	    return;
	}

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    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
538

539 540 541 542 543 544 545 546

void
dump_connections(void)
{
    Session_no s;
    Connection *conn;
    FILE *fp;

547
    if ((fp = i_fopen(param.connection_status_file_tmp, "w")) == NULL)
548
    {
549 550
	kom_log("dump_connections(): can't open file %s: %s\n",
		param.connection_status_file_tmp, strerror(errno));
551 552 553 554 555 556 557 558 559 560
	return;
    }

    for (s = 0; (s = traverse_connections(s)) != 0;)
    {
	conn = get_conn_by_number(s);
	fprintf(fp, "%d %lu %s\n", conn->isc_session->fd, conn->session_no,
		conn->peer);
    }

561 562 563 564 565 566
    if (fflush(fp) != 0)
	kom_log("dump_connections(): fflush() says an error has occured.\n");
	
    if (ferror(fp))
	kom_log("dump_connections(): ferror() says an error has occured.\n");

567
    if (i_fclose(fp) < 0)
568 569 570 571 572
    {
	kom_log("dump_connections(): fclose failed: %s (ignored)\n",
		strerror(errno));
    }

573
    errno = 0;
574 575
    if (i_rename(param.connection_status_file_tmp,
		 param.connection_status_file) < 0)
576
    {
577
	kom_log("dump_connections(): can't rename %s to %s: %s\n",
578
		param.connection_status_file_tmp,
579 580
		param.connection_status_file,
		strerror(errno));
581 582 583 584
    }
}


Per Cederqvist's avatar
Per Cederqvist committed
585 586 587 588 589 590 591
/*
 * check_kill_flg must NEVER be called inside an atomic call!
 */
static void
check_kill_flg(void)
{
    Connection *conn;
592
    Bool changed = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
593 594 595

    if ( active_connection != NULL )
    {
596
	restart_kom("check_kill_flg: active_connection == %ld",
Per Cederqvist's avatar
Per Cederqvist committed
597 598 599
		    active_connection->session_no);
    }

600
    while (kill_list_size > 0)
Per Cederqvist's avatar
Per Cederqvist committed
601
    {
602 603 604
	--kill_list_size;
	conn = get_conn_by_number (kill_list[kill_list_size]);
	if (conn == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
605
	{
David Byers's avatar
David Byers committed
606
	    kom_log("check_kill_flg(): Connection %ld doesn't exist.\n",
607 608 609 610 611 612
		kill_list[kill_list_size]);
	}
	else
	{
	    logout_client (conn);
	    end_of_atomic (FALSE);
613
	    changed = TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
614 615
	}
    }
616

617 618 619 620 621
    if (kill_list != NULL)
    {
	sfree (kill_list);
	kill_list = NULL;
    }
622 623 624

    if (changed == TRUE)
	dump_connections();
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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

static char *
get_host_name(IscAddress *addr)
{
    char *res = NULL;
    char *hostname = NULL;
    struct timeval before;
    struct timeval after;
    double diff = -1.0;

    if (param.use_dns)
    {
	if (gettimeofday(&before, NULL) < 0)
	    kom_log("gettimeofday failed: %s\n", strerror(errno));

	res = hostname = isc_gethostname(addr, NULL, 0);

	if (gettimeofday(&after, NULL) < 0)
	    kom_log("gettimeofday failed: %s\n", strerror(errno));

	diff = (after.tv_sec - before.tv_sec
		+ 1e-6 * (after.tv_usec - before.tv_usec));
    }

    if (res == NULL)
	res = isc_getipnum(addr, NULL, 0);

    if (param.use_dns && diff > param.dns_log_threshold)
    {
	if (hostname == NULL)
	    kom_log("Slow bad DNS: %s failed after %f seconds\n", res, diff);
	else
	    kom_log("Slow DNS: got %s after %f seconds\n", res, diff);
    }

    return res;
}


Per Cederqvist's avatar
Per Cederqvist committed
666
static void
Per Cederqvist's avatar
Per Cederqvist committed
667
login_request(IscEvent  *event)
Per Cederqvist's avatar
Per Cederqvist committed
668 669
{
    Connection  * cp;
670
    const char *realuser;
671
    char *hostname = NULL;
672
    char peername[256];
673 674 675
    char portbuf[1+2+3*sizeof(long)];
    size_t hostlen;
    size_t portlen;
Per Cederqvist's avatar
Per Cederqvist committed
676 677

    /* Supress logins if /etc/nologin exists */
David Byers's avatar
David Byers committed
678
    if (fexists(param.nologin_file))
Per Cederqvist's avatar
Per Cederqvist committed
679
    {
680
	isc_puts("%% No logins allowed.\n", event->session);
Per Cederqvist's avatar
Per Cederqvist committed
681
	isc_flush(event->session);
Per Cederqvist's avatar
Per Cederqvist committed
682
 	isc_destroy(kom_server_mcb, event->session);
Per Cederqvist's avatar
Per Cederqvist committed
683 684 685
	return;
    }

686
    hostname = get_host_name(event->session->info.tcp.raddr);
687
    if (hostname == NULL)
David Byers's avatar
David Byers committed
688
	kom_log("WNG: login_request(): unknown hostid.\n");
689

690 691 692
    /* 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)
Per Cederqvist's avatar
Per Cederqvist committed
693
    {
David Byers's avatar
David Byers committed
694
	kom_log("Connection from %s rejected - no IDENT available.\n", 
695
	     hostname);
Per Cederqvist's avatar
Per Cederqvist committed
696

697 698 699 700 701
	isc_puts("%% No IDENT server reachable at your site.\n",
		 event->session);
	isc_flush(event->session);
	isc_destroy(kom_server_mcb, event->session);
	return;
Per Cederqvist's avatar
Per Cederqvist committed
702
    }
703

704 705
    /* Create a Connection, and link the Connection and the
       isc_session together. */
706

707 708 709
    cp = new_client();
    cp->isc_session = event->session;
    event->session->udg = cp;
710

711 712
    if (hostname == NULL)
	s_crea_str(&cp->hostname, "unknown");
713
    else
714 715 716 717 718 719
	s_crea_str(&cp->hostname, hostname);

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

    BUG(("\n[Client %lu from %s is connecting]\n", cp->session_no, hostname));
720 721


722 723 724
    isc_getipnum(event->session->info.tcp.raddr, peername, sizeof(peername));
    hostlen = strlen(peername);
    if (hostlen >= sizeof(peername)-1)
725 726 727 728
    {
	kom_log("login_request(): truncated remote peer address %s.\n",
		peername);
    }
729 730 731
    sprintf(portbuf, " %d", isc_getportnum(event->session->info.tcp.raddr));
    portlen = strlen(portbuf);
    cp->peer = smalloc(hostlen + portlen + 1);
732
    strcpy(cp->peer, peername);
733
    strcpy(cp->peer + hostlen, portbuf);
734 735

    dump_connections();
Per Cederqvist's avatar
Per Cederqvist committed
736 737 738
}

static void
Per Cederqvist's avatar
Per Cederqvist committed
739
logout_request(IscEvent *event)
Per Cederqvist's avatar
Per Cederqvist committed
740 741 742
{
    Connection  * cp;
    
743
    cp = event->session->udg;
Per Cederqvist's avatar
Per Cederqvist committed
744
	      
745
    BUG(("\n[Client %lu from %s", cp->session_no,
746
	 get_host_name(event->session->info.tcp.raddr)));
747 748 749
    BUG((" is logging out]\n"));

    add_to_kill_list(cp);
Per Cederqvist's avatar
Per Cederqvist committed
750 751 752 753
}


static void
Per Cederqvist's avatar
Per Cederqvist committed
754
message_request(IscEvent *event)
Per Cederqvist's avatar
Per Cederqvist committed
755 756 757 758
{
    Connection *cp;
    String      tmp_str;

759 760 761 762 763 764 765
    cp = event->session->udg;
    VBUG(("\n[Message from client %lu]\n", cp->session_no));

    /* Pass the message on to the parser */
    tmp_str.string = (unsigned char *)event->msg->buffer;
    tmp_str.len    = event->msg->length;
    parse_message(cp, tmp_str);
Per Cederqvist's avatar
Per Cederqvist committed
766 767 768 769 770
}

void
toploop(void)
{
David Byers's avatar
David Byers committed
771
    time_t      last_time;
772
    IscEvent  * event;
Per Cederqvist's avatar
Per Cederqvist committed
773 774 775 776
    Bool	pending_input = TRUE; /* Should be TRUE whenever there
				         is or might be pending input
					 from any client in the unparsed
					 buffer. */
777 778 779
    long	timeout = 0;        /* In milliseconds. Start with a
				       small value since we should
				       start garbing right away. */
Per Cederqvist's avatar
Per Cederqvist committed
780 781
    while ( !go_and_die )
    {
782
        if (do_statistics)
Per Cederqvist's avatar
Per Cederqvist committed
783 784
	{
	    dump_statistics();
785
	    do_statistics = 0;
Per Cederqvist's avatar
Per Cederqvist committed
786 787
	}

788 789 790 791 792
        if (reread_param)
        {
            free_aux_item_definitions();
            initialize_aux_items(param.aux_def_file);
            reread_param = FALSE;
793
            kom_log("Signal WINCH received. aux definitions reloaded.\n");
794 795
        }

796
	intr_syscalls_on_intr();
Per Cederqvist's avatar
Per Cederqvist committed
797 798
	event = isc_getnextevent(kom_server_mcb,
				 pending_input ? 0 : timeout );
799
	restart_syscalls_on_intr();
Per Cederqvist's avatar
Per Cederqvist committed
800

David Byers's avatar
David Byers committed
801
        last_time = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
802
	current_time = time(NULL);
David Byers's avatar
David Byers committed
803 804
        if (current_time < last_time)
        {
805
            kom_log("WARNING: Time is moving in the wrong direction\n");
806
            /* FIXME (bug 62): Should we take more decisive action here? */
David Byers's avatar
David Byers committed
807 808
        }

Per Cederqvist's avatar
Per Cederqvist committed
809
	timeout = 0;
Per Cederqvist's avatar
Per Cederqvist committed
810 811 812 813

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

814
#ifndef USING_RLIMIT_NOFILE
815 816 817
	if (event->event == ISC_EVENT_LOGIN
	    && event->session->fd >= fd_ceiling)
	{
818
	    event->event = ISC_EVENT_LOGIN_UNRELOCATED;
819
	}
820 821
#endif

Per Cederqvist's avatar
Per Cederqvist committed
822 823 824 825 826
	switch ( event->event )
	{
	case ISC_EVENT_ERROR:
	    if (errno != EINTR)
	    {
David Byers's avatar
David Byers committed
827
		kom_log("toploop: ISC_EVENT_ERROR (error = '%s'):\n   '%s'\n",
Per Cederqvist's avatar
Per Cederqvist committed
828 829 830 831 832 833 834
		    strerror(errno), event->msg ? event->msg->buffer
		    : "(unknown)");
	    }
	    break;
	    
	case ISC_EVENT_TIMEOUT:
	    BUG((">"));
835
#ifndef NDEBUG
836 837
	    if (buglevel > 0)
		fflush(stdout);
Per Cederqvist's avatar
Per Cederqvist committed
838 839 840 841
#endif
	    if ( pending_input == FALSE )
		timeout = end_of_atomic(TRUE); /* Idle. Do some cleaning up. */
	    else
842
		pending_input = (parse_forgotten() ? FALSE : TRUE);
Per Cederqvist's avatar
Per Cederqvist committed
843 844 845 846 847 848 849 850
	    	    
	    break;
	    
	case ISC_EVENT_LOGIN:
	    pending_input = TRUE;
	    login_request(event);
	    break;

851 852 853
	case ISC_EVENT_LOGIN_UNRELOCATED:
	    pending_input = TRUE;
	    BUG(("Connection attempt rejected.\n"));
854
	    isc_puts("%% No connections left.\n", event->session);
855 856 857 858 859 860
	    isc_flush(event->session);
	    isc_destroy(kom_server_mcb, event->session);

	    async_rejected_connection();
	    break;

Per Cederqvist's avatar
Per Cederqvist committed
861 862 863 864 865 866 867 868 869 870 871 872
	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;
David Byers's avatar
David Byers committed
873
	    kom_log("ERROR: toploop(): Unknown ISC_EVENT\n");
Per Cederqvist's avatar
Per Cederqvist committed
874 875 876 877 878 879 880 881
	    break;
	}

        isc_dispose(event);

	check_kill_flg();
    }
}