connections.c 23.6 KB
Newer Older
Linus Tolke Y's avatar
Linus Tolke Y committed
1
/*
2
 * $Id: connections.c,v 0.95 2003/07/12 13:49:40 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>
58
#include <assert.h>
Per Cederqvist's avatar
Per Cederqvist committed
59

60 61 62
#include "oop.h"

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

95 96
oop_source_sys * kom_server_oop_src = NULL;
struct isc_mcb * 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 110 111 112 113 114 115 116
 * The number of times that the session penalties has been averaged.
 * Beware: this number will wrap around.
 */
static unsigned int penalty_generation = 0;

/*
 * These state variables are used to find out if we are busy or not.
 * When a packet arrives, data_available_callback() will set work_done
 * to TRUE and is_idle to FALSE.
Per Cederqvist's avatar
Per Cederqvist committed
117
 */
118 119
static Bool work_done = FALSE;
static Bool is_idle = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
120 121 122 123 124 125 126 127

jmp_buf 	 parse_env;


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

128
const int num_fnc_defs = sizeof (fnc_defs) / sizeof (Fnc_descriptor);
129

Per Cederqvist's avatar
Per Cederqvist committed
130
unsigned long service_statistics[sizeof (fnc_defs) / sizeof (Fnc_descriptor)];
Per Cederqvist's avatar
Per Cederqvist committed
131 132 133

BUGDECL;

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
static oop_call_fd data_available_callback;
static oop_call_time check_kill_flg;
static oop_call_time check_idle_callback;

static Connection *queue_first = NULL;
static Connection *queue_last = NULL;

static void
queue_add(Connection *c)
{
    assert(c->on_queue == FALSE);
    c->on_queue = TRUE;

    c->queue_prev = queue_last;
    c->queue_next = NULL;

    if (queue_first == NULL)
	queue_first = c;
    else
	queue_last->queue_next = c;

    queue_last = c;
}

static void
queue_remove(Connection *c)
{
    assert(c->on_queue == TRUE);
    c->on_queue = FALSE;

    if (c->queue_next != NULL)
	c->queue_next->queue_prev = c->queue_prev;
    else
	queue_last = c->queue_prev;
    
    if (c->queue_prev != NULL)
	c->queue_prev->queue_next = c->queue_next;
    else
	queue_first = c->queue_prev;
Per Cederqvist's avatar
Per Cederqvist committed
173

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    c->queue_prev = NULL;
    c->queue_next = NULL;
}

static void
set_time(void)
{
    time_t      last_time;

    last_time = current_time;
    current_time = time(NULL);
    if (current_time < last_time)
    {
	kom_log("WARNING: Time is moving in the wrong direction.\n");
	/* FIXME (bug 62): Should we take more decisive action here? */
    }
}
Per Cederqvist's avatar
Per Cederqvist committed
191

Per Cederqvist's avatar
Per Cederqvist committed
192
static void
Per Cederqvist's avatar
Per Cederqvist committed
193 194 195
logout_client(Connection *cp)
{
    Connection *real_active_connection;
196
    int ret;
Per Cederqvist's avatar
Per Cederqvist committed
197 198 199

    if ( active_connection != NULL )
    {
David Byers's avatar
David Byers committed
200
	kom_log("BUGCHK: logout_client(%ld): connection %ld is active.\n",
Per Cederqvist's avatar
Per Cederqvist committed
201 202 203 204 205
	    cp->session_no, active_connection->session_no);
    }
    
    if ( cp->pers_no != 0 )
    {
206 207 208 209 210 211 212 213 214 215 216 217
	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
218 219 220 221
	active_connection = cp;
	logout();
	active_connection = real_active_connection;
    }
222 223
    else
    {
224
#if 0
225
	/* FIXME (bug 908): send a new async here instead.  This causes the
226 227
	   elisp client to say that a secret (or unknown) person has
	   left the system.  */
228
        async_logout( 0, cp->session_no );
229
#endif
230
    }
Per Cederqvist's avatar
Per Cederqvist committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244

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

245 246
    ret = isc_destroy(kom_server_mcb, cp->isc_session);
    if (ret < 0)
David Byers's avatar
David Byers committed
247
	kom_log("logout_client(): isc_destroyed returned %d\n", ret);
248
    cp->isc_session = NULL;
249 250
    if (cp->on_queue)
	queue_remove(cp);
Per Cederqvist's avatar
Per Cederqvist committed
251 252 253 254

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

Per Cederqvist's avatar
Per Cederqvist committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268
/*
 * 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 )
269
	    restart_kom("logout_all_clients(): cant get session %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
270 271 272 273 274 275
			sess);
	else
	    logout_client (conn);
    }

    if ( traverse_connections (0) != 0)
276
	restart_kom("logout_all_clients(): traverse_connections(0) == %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
277 278 279 280
		    traverse_connections(0));
}

    
Per Cederqvist's avatar
Per Cederqvist committed
281 282 283 284 285 286 287 288
    

    
/*
 * 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
289 290
call_function(Connection *client,
	      union result_holder *res)
Per Cederqvist's avatar
Per Cederqvist committed
291 292 293 294 295
{
    Success	status=FAILURE;	/* OK if the call was successful. */

    if ( active_connection != NULL )
    {
296
	kom_log("call_function(%ld): active_connection = %ld\n",
Per Cederqvist's avatar
Per Cederqvist committed
297 298
	    client->session_no, active_connection->session_no);
    }
299 300 301

    if (client->function == illegal_fnc) 
    {
302
        err_stat = 0;
303 304 305 306
	kom_errno = KOM_NOT_IMPL;
	return FAILURE;
    }

Per Cederqvist's avatar
Per Cederqvist committed
307 308
    active_connection = client;

309
    service_statistics[client->function_index]++;
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

#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';
333 334
	    isc_puts("%%LysKOM unsupported protocol.\n", client->isc_session);
	    isc_flush(client->isc_session);
Per Cederqvist's avatar
Per Cederqvist committed
335
	    BUG(("%%%%Unsupported protocol.\n"));
336
	    longjmp(parse_env, KOM_LOGOUT);
Per Cederqvist's avatar
Per Cederqvist committed
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
	}
    }

    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
366 367 368
    sfree(client->misc_info_list.misc);
    client->misc_info_list.misc = 0;
    client->misc_info_list.no_of_misc = 0;
369
    s_clear(&client->aux_item.data);
370
    s_clear(&client->dummy_aux_item.data);
Per Cederqvist's avatar
Per Cederqvist committed
371 372
    sfree( client->c_local_text_no_p);
    client->c_local_text_no_p = NULL;
373 374 375
    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
376 377
    client->parse_pos = 0;
    client->fnc_parse_pos = 0;
378
    client->array_parse_index = 0;
David Byers's avatar
David Byers committed
379
    client->array_parse_parsed_length = 0;
Per Cederqvist's avatar
Per Cederqvist committed
380 381 382
    client->array_parse_pos = 0;
    client->struct_parse_pos = 0;
    client->string_parse_pos = 0;
David Byers's avatar
David Byers committed
383 384 385
    client->hunt_parse_pos = 0;
    client->array_hunt_num = 0;
    client->array_hunt_depth = 0;
386 387 388
    sfree(client->num_list.data);
    client->num_list.data = NULL;
    client->num_list.length = 0;
389 390
    free_aux_item_list(&client->aux_item_list);
    client->info.highest_aux_no = 0;
Per Cederqvist's avatar
Per Cederqvist committed
391 392 393 394 395 396 397
}

/*
 * Send a reply to a call.
 */
static void
reply(Connection *client,
398 399
      Success status,
      union result_holder *result)
Per Cederqvist's avatar
Per Cederqvist committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
{
    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)
{
    Success       status;
422
    union result_holder result;
Per Cederqvist's avatar
Per Cederqvist committed
423 424 425 426 427 428 429 430
        
    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);
431
	client->penalty += param.penalty_per_call;
Per Cederqvist's avatar
Per Cederqvist committed
432
	free_parsed(client);
433
	end_of_atomic();
Per Cederqvist's avatar
Per Cederqvist committed
434 435
	break;

436
    case KOM_PROTOCOL_ERR:
Per Cederqvist's avatar
Per Cederqvist committed
437 438
	s_clear(&client->string0);
	free_parsed(client);
439 440
	isc_puts("%% LysKOM protocol error.\n", client->isc_session);
	isc_flush(client->isc_session);
Per Cederqvist's avatar
Per Cederqvist committed
441
	BUG(("%%%% Protocol error.\n"));
442
	client->penalty += param.max_penalty;
Per Cederqvist's avatar
Per Cederqvist committed
443 444 445
	s_clear(&client->unparsed);
	client->first_to_parse = 0;
	client->more_to_parse = FALSE;
446
	end_of_atomic();
Per Cederqvist's avatar
Per Cederqvist committed
447 448
	break;

449
    case KOM_MSG_INCOMPLETE:
Per Cederqvist's avatar
Per Cederqvist committed
450 451 452
	client->more_to_parse = FALSE;
	break;

453
    case KOM_LOGOUT:
454
	add_to_kill_list(client);
455
	client->more_to_parse = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
456 457 458 459 460 461 462
	break;
    }
}


/* Return 1 if the named file exists, 0 otherwise */
static int
Per Cederqvist's avatar
Per Cederqvist committed
463
fexists(const char *filename)
Per Cederqvist's avatar
Per Cederqvist committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
{
    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;

482
    if ((fp = i_fopen(param.statistic_name, "a")) == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
483
    {
484 485
	kom_log("dump_statistics(): can't open file %s\n",
		param.statistic_name);
Per Cederqvist's avatar
Per Cederqvist committed
486 487 488 489 490 491
	return;
    }

    if (last_dump == NO_TIME)
    {
	fprintf(fp, "RESTART\n");
Per Cederqvist's avatar
Per Cederqvist committed
492
	last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
493 494
    }
    
Per Cederqvist's avatar
Per Cederqvist committed
495 496
    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
497
    fprintf(fp, "STATISTICS:");
498 499 500 501 502

    /* 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
503
    {
504
	fprintf(fp, " %d:%lu", fnc_defs[i].function, service_statistics[i]);
Per Cederqvist's avatar
Per Cederqvist committed
505 506 507 508
	service_statistics[i]=0;
    }

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

Per Cederqvist's avatar
Per Cederqvist committed
511
    last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
512 513
}

514 515
/* List of connections to kill. */

Per Cederqvist's avatar
Per Cederqvist committed
516 517
static Session_no *kill_list = NULL;
static int kill_list_size = 0;
518
static int kill_pending = 0;
519 520 521 522 523

/* Schedule this client for termination. */
void
add_to_kill_list(Connection *conn)
{
524
    oop_source *source;
Per Cederqvist's avatar
Per Cederqvist committed
525 526 527
    int i;

    for (i = 0; i < kill_list_size; i++)
528
	if (kill_list[i] == conn->session_no)
Per Cederqvist's avatar
Per Cederqvist committed
529 530
	    return;

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    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;
546 547 548 549 550 551 552

    if (!kill_pending)
    {
	source = conn->isc_session->master->event_source;
	source->on_time(source, OOP_TIME_NOW, check_kill_flg, NULL);
	kill_pending = 1;
    }
553
}
Per Cederqvist's avatar
Per Cederqvist committed
554

555 556 557 558 559 560 561 562

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

563
    if ((fp = i_fopen(param.connection_status_file_tmp, "w")) == NULL)
564
    {
565 566
	kom_log("dump_connections(): can't open file %s: %s\n",
		param.connection_status_file_tmp, strerror(errno));
567 568 569 570 571 572 573 574 575 576
	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);
    }

577 578 579 580 581 582
    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");

583
    if (i_fclose(fp) < 0)
584 585 586 587 588
    {
	kom_log("dump_connections(): fclose failed: %s (ignored)\n",
		strerror(errno));
    }

589
    errno = 0;
590 591
    if (i_rename(param.connection_status_file_tmp,
		 param.connection_status_file) < 0)
592
    {
593
	kom_log("dump_connections(): can't rename %s to %s: %s\n",
594
		param.connection_status_file_tmp,
595 596
		param.connection_status_file,
		strerror(errno));
597 598 599 600
    }
}


Per Cederqvist's avatar
Per Cederqvist committed
601 602 603
/*
 * check_kill_flg must NEVER be called inside an atomic call!
 */
604 605 606 607
static void *
check_kill_flg(oop_source *UNUSED(source),
	       struct timeval UNUSED(tv),
	       void *UNUSED(user))
Per Cederqvist's avatar
Per Cederqvist committed
608 609
{
    Connection *conn;
610
    Bool changed = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
611

612 613
    kill_pending = 0;

Per Cederqvist's avatar
Per Cederqvist committed
614 615
    if ( active_connection != NULL )
    {
616
	restart_kom("check_kill_flg: active_connection == %ld",
Per Cederqvist's avatar
Per Cederqvist committed
617 618 619
		    active_connection->session_no);
    }

620
    while (kill_list_size > 0)
Per Cederqvist's avatar
Per Cederqvist committed
621
    {
622 623 624
	--kill_list_size;
	conn = get_conn_by_number (kill_list[kill_list_size]);
	if (conn == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
625
	{
David Byers's avatar
David Byers committed
626
	    kom_log("check_kill_flg(): Connection %ld doesn't exist.\n",
627 628 629 630
		kill_list[kill_list_size]);
	}
	else
	{
631 632
	    logout_client(conn);
	    end_of_atomic();
633
	    changed = TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
634 635
	}
    }
636

637 638 639 640 641
    if (kill_list != NULL)
    {
	sfree (kill_list);
	kill_list = NULL;
    }
642 643 644

    if (changed == TRUE)
	dump_connections();
645 646

    return OOP_CONTINUE;
Per Cederqvist's avatar
Per Cederqvist committed
647 648
}

649 650

static char *
651
get_host_name(union isc_address *addr)
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
{
    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;
}

687 688 689 690 691 692 693
static void
write_err_cb(struct isc_mcb *UNUSED(cb_mcb),
	     struct isc_scb *UNUSED(cb_session),
	     int saved_errno,
	     void *user)
{
    Connection  * cp = user;
694 695 696
    if (saved_errno != ECONNRESET)
	kom_log("Failed to write to client %lu from %s: %s\n",
		cp->session_no, cp->peer, strerror(saved_errno));
697 698 699 700
    add_to_kill_list(cp);
}


701

Per Cederqvist's avatar
Per Cederqvist committed
702
static void
703
login_request(struct isc_scb *session)
Per Cederqvist's avatar
Per Cederqvist committed
704 705
{
    Connection  * cp;
706
    const char *realuser;
707
    char *hostname = NULL;
708
    char peername[256];
709 710 711
    char portbuf[1+2+3*sizeof(long)];
    size_t hostlen;
    size_t portlen;
Per Cederqvist's avatar
Per Cederqvist committed
712 713

    /* Supress logins if /etc/nologin exists */
David Byers's avatar
David Byers committed
714
    if (fexists(param.nologin_file))
Per Cederqvist's avatar
Per Cederqvist committed
715
    {
716 717 718
	isc_puts("%% No logins allowed.\n", session);
	isc_flush(session);
 	isc_destroy(kom_server_mcb, session);
Per Cederqvist's avatar
Per Cederqvist committed
719 720 721
	return;
    }

722
    hostname = get_host_name(session->raddr);
723
    if (hostname == NULL)
David Byers's avatar
David Byers committed
724
	kom_log("WNG: login_request(): unknown hostid.\n");
725

726
    /* Get the real user name, as returned by the Ident protocol (rfc 931). */
727
    realuser = get_real_username(session, hostname);
728
    if (realuser == NULL && param.authentication_level == 2)
Per Cederqvist's avatar
Per Cederqvist committed
729
    {
David Byers's avatar
David Byers committed
730
	kom_log("Connection from %s rejected - no IDENT available.\n", 
731
	     hostname);
Per Cederqvist's avatar
Per Cederqvist committed
732

733
	isc_puts("%% No IDENT server reachable at your site.\n",
734 735 736
		 session);
	isc_flush(session);
	isc_destroy(kom_server_mcb, session);
737
	return;
Per Cederqvist's avatar
Per Cederqvist committed
738
    }
739

740 741
    /* Create a Connection, and link the Connection and the
       isc_session together. */
742

743
    cp = new_client();
744 745
    cp->isc_session = session;
    session->udg = cp;
746

747 748
    if (hostname == NULL)
	s_crea_str(&cp->hostname, "unknown");
749
    else
750 751 752 753 754 755
	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));
756 757


758
    isc_getipnum(session->raddr, peername, sizeof(peername));
759 760
    hostlen = strlen(peername);
    if (hostlen >= sizeof(peername)-1)
761 762 763 764
    {
	kom_log("login_request(): truncated remote peer address %s.\n",
		peername);
    }
765
    sprintf(portbuf, " %d", isc_getportnum(session->raddr));
766 767
    portlen = strlen(portbuf);
    cp->peer = smalloc(hostlen + portlen + 1);
768
    strcpy(cp->peer, peername);
769
    strcpy(cp->peer + hostlen, portbuf);
770 771

    dump_connections();
772 773

    isc_set_read_callback(session, data_available_callback, write_err_cb, cp);
Per Cederqvist's avatar
Per Cederqvist committed
774 775 776
}

static void
777
adjust_penalty(Connection *conn)
Per Cederqvist's avatar
Per Cederqvist committed
778
{
779 780 781 782 783 784 785 786
    while (penalty_generation - conn->penalty_generation > 0)
    {
	conn->penalty /= 2;
	if (conn->penalty == 0)
	    conn->penalty_generation = penalty_generation;
	else
	    conn->penalty_generation++;
    }
Per Cederqvist's avatar
Per Cederqvist committed
787 788 789 790
}


static void
791
read_from_connection(Connection *conn)
Per Cederqvist's avatar
Per Cederqvist committed
792
{
793
    Bool would_block = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
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
    adjust_penalty(conn);

    while (!would_block && !go_and_die && conn->penalty < param.max_penalty)
    {
	while (conn->more_to_parse
	       && !go_and_die && conn->penalty < param.max_penalty)
	    parse_unparsed(conn);

	if (go_and_die || conn->penalty >= param.max_penalty)
	    break;

	if (!conn->more_to_parse)
	{
	    switch (isc_read_data(conn->isc_session,
				  &conn->unparsed,
				  &conn->first_to_parse))
	    {
	    case ISC_READ_DATA:
		conn->penalty += param.penalty_per_read;
		conn->more_to_parse = TRUE;
		break;
	    case ISC_READ_ERROR:
		if (errno != ECONNRESET)
		    kom_log("Error reading from client: %s\n",
			    strerror(errno));
		/*FALLTHROUGH*/
	    case ISC_READ_LOGOUT:
		add_to_kill_list(conn);
		break;
	    case ISC_READ_WOULDBLOCK:
		would_block = TRUE;
		break;
	    case ISC_READ_NOMEM:
		restart_kom("isc_read_data() reports no memory\n");
	    }

	    if (!conn->more_to_parse)
		break;
	}
    }
835

836 837 838 839 840 841 842 843 844 845
    /* Delete the parsed part of 'unparsed' */
    if (s_trim_left(&conn->unparsed, conn->first_to_parse) != OK)
	restart_kom("parse_unparsed: s_trim_left\n");
    conn->first_to_parse = 0;

    if (conn->penalty >= param.max_penalty)
    {
	isc_disable(conn->isc_session);
	queue_add(conn);
    }
Per Cederqvist's avatar
Per Cederqvist committed
846 847
}

848 849 850 851

static void
setup_timer(struct timeval *tv,
	    long milliseconds)
Per Cederqvist's avatar
Per Cederqvist committed
852
{
853 854 855 856 857
    static int errcnt = 0;

    if (gettimeofday(tv, NULL) < 0)
    {
	if (errcnt < 20)
Per Cederqvist's avatar
Per Cederqvist committed
858
	{
859 860 861 862 863
	    kom_log("setup_timer(): gettimeofday failed: %s\n",
		    strerror(errno));
	    if (++errcnt == 20)
		kom_log("setup_timer():"
			" will not log any more gettimeofday failures\n");
Per Cederqvist's avatar
Per Cederqvist committed
864
	}
865 866 867 868 869
	
	*tv = OOP_TIME_NOW;
    }
    else
    {
870 871 872
	tv->tv_sec += milliseconds / 1000;
	tv->tv_usec += 1000 * (milliseconds % 1000);
	if (tv->tv_usec > 1000000)
873
	{
874
	    tv->tv_usec -= 1000000;
875
	    tv->tv_sec++;
876
	}
877
    }
878 879
    assert(tv->tv_usec >= 0);
    assert(tv->tv_usec < 1000000);
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
}

static void
enable_idle_check(void)
{
    oop_source *source = oop_sys_source(kom_server_oop_src);

    source->on_time(source, OOP_TIME_NOW, check_idle_callback, NULL);
}


static void *
check_idle_callback(oop_source *UNUSED(source),
		    struct timeval UNUSED(tv),
		    void *UNUSED(user))
{
    Connection *c;
    Connection *next;

    set_time();
    is_idle = !work_done;
    work_done = FALSE;

    if (is_idle && queue_first != NULL)
    {
	is_idle = FALSE;
	++penalty_generation;
907

908
	for (next = queue_first; next != NULL; )
Per Cederqvist's avatar
Per Cederqvist committed
909
	{
910 911 912 913
	    c = next;
	    next = next->queue_next;
	    adjust_penalty(c);
	    if (c->penalty < param.low_penalty)
Per Cederqvist's avatar
Per Cederqvist committed
914
	    {
915 916 917
		queue_remove(c);
		isc_enable(c->isc_session);
		read_from_connection(c);
Per Cederqvist's avatar
Per Cederqvist committed
918
	    }
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
	}
    }

    if (!is_idle)
	enable_idle_check();

    return OOP_CONTINUE;
}

static void *
garb_callback(oop_source *UNUSED(source),
	      struct timeval UNUSED(tv),
	      void *user)
{
    struct timeval *next_timer = user;

    if (is_idle)
    {
	set_time();
	if (garb_text() == FALSE)
	    setup_timer(next_timer, param.garbtimeout);
	else
	{
	    if (gettimeofday(next_timer, NULL) < 0)
		*next_timer = OOP_TIME_NOW;
Per Cederqvist's avatar
Per Cederqvist committed
944
	    else
945 946 947 948 949
		next_timer->tv_sec += 60 * param.garb_interval;
	}
    }
    else
	setup_timer(next_timer, param.garb_busy_postponement);
Per Cederqvist's avatar
Per Cederqvist committed
950

951 952 953
    source->on_time(source, *next_timer, garb_callback, user);
    return OOP_CONTINUE;
}
954

955 956 957 958 959 960 961
static void *
saver_callback(oop_source *UNUSED(source),
	       struct timeval UNUSED(tv),
	       void *user)
{
    long timeout;
    struct timeval *next_timer = user;
962

963 964
    timeout = end_of_atomic();
    setup_timer(next_timer, timeout);
Per Cederqvist's avatar
Per Cederqvist committed
965

966 967 968
    source->on_time(source, *next_timer, saver_callback, user);
    return OOP_CONTINUE;
}
Per Cederqvist's avatar
Per Cederqvist committed
969 970


971 972 973 974 975 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
static void *
data_available_callback(oop_source *source,
			int fd,
			oop_event event,
			void *user)
{
    Connection *conn = user;

    assert(event == OOP_READ);
    assert(conn->isc_session->fd == fd);
    assert(conn->isc_session->master->event_source == source);

    /* Something arrived, so we are busy.  */
    if (is_idle)
    {
	is_idle = FALSE;
	enable_idle_check();
    }
	
    work_done = TRUE;

    set_time();
    read_from_connection(conn);

    /* Check if the client issued a shutdown command.  */
    return go_and_die ? OOP_HALT : OOP_CONTINUE;
}


void *
handle_accept_event(struct isc_mcb *mcb,
		    struct isc_scb *UNUSED(accepting_session),
		    struct isc_scb *new_session)
{
    assert(mcb == kom_server_mcb);

    if (new_session->fd <= PROTECTED_FDS || new_session->fd >= fd_ceiling)
    {
	BUG(("Connection attempt rejected.\n"));
	isc_puts("%% No connections left.\n", new_session);
	isc_flush(new_session);
	isc_destroy(mcb, new_session);
Per Cederqvist's avatar
Per Cederqvist committed
1013

1014
	async_rejected_connection();
Per Cederqvist's avatar
Per Cederqvist committed
1015
    }
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
    else
	login_request(new_session);

    return OOP_CONTINUE;
}


void
toploop(void)
{
    struct timeval garb_timer;
    struct timeval saver_timer;

    void *exit_reason;
    oop_source *source = oop_sys_source(kom_server_oop_src);

    /* Start the garb right away. */
    garb_timer = OOP_TIME_NOW;
    source->on_time(source, garb_timer, garb_callback, &garb_timer);

    /* Hack to find out when we are idle. */
    source->on_time(source, OOP_TIME_NOW, check_idle_callback, NULL);

    /* Save the database even if we happen to be idle. */
    saver_timer = OOP_TIME_NOW;
    source->on_time(source, saver_timer, saver_callback, &saver_timer);

    exit_reason = oop_sys_run(kom_server_oop_src);

    if (exit_reason == OOP_ERROR)
	kom_log("ERROR: unexpected error from oop_sys_run: %s\n",
		strerror(errno));
    else if (exit_reason == OOP_CONTINUE)
	kom_log("ERROR: all oop sinks disappeared\n");
    else if (exit_reason != OOP_HALT)
	kom_log("ERROR: unexpected error from oop_sys_run: %s\n",
		strerror(errno));

    if (kill_pending)
    {
	source->cancel_time(source, OOP_TIME_NOW, check_kill_flg, NULL);
	kill_pending = 0;
    }

    if (is_idle == FALSE)
        source->cancel_time(source, OOP_TIME_NOW, check_idle_callback, NULL);

    source->cancel_time(source, saver_timer, saver_callback, &saver_timer);
    source->cancel_time(source, garb_timer, garb_callback, &garb_timer);
Per Cederqvist's avatar
Per Cederqvist committed
1065
}