connections.c 30 KB
Newer Older
Linus Tolke Y's avatar
Linus Tolke Y committed
1
/*
2
 * Copyright (C) 1991-2003  Lysator Academic Computer Association.
Linus Tolke Y's avatar
Linus Tolke Y committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * 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.
 *
Per Cederqvist's avatar
Per Cederqvist committed
22
 * Please report bugs at http://bugzilla.lysator.liu.se/. 
Linus Tolke Y's avatar
Linus Tolke Y committed
23
 */
Per Cederqvist's avatar
Per Cederqvist committed
24 25 26 27 28 29 30 31
/*
 * 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
32 33 34 35 36

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

Per Cederqvist's avatar
Per Cederqvist committed
37
#include <errno.h>
Per Cederqvist's avatar
Per Cederqvist committed
38
#include <stdio.h>
Per Cederqvist's avatar
Per Cederqvist committed
39
#include <setjmp.h>
Per Cederqvist's avatar
Per Cederqvist committed
40 41 42
#ifdef HAVE_STRING_H
#  include <string.h>
#endif
Per Cederqvist's avatar
Per Cederqvist committed
43
#include <sys/types.h>
Per Cederqvist's avatar
Per Cederqvist committed
44
#include <sys/stat.h>
45
#include "timewrap.h"
46
#include <sys/socket.h>
47
#include <signal.h>
48
#include <assert.h>
49
#include <netdb.h>
Per Cederqvist's avatar
Per Cederqvist committed
50
#include <stdlib.h>
Per Cederqvist's avatar
Per Cederqvist committed
51

52
#include "adns.h"
53 54 55
#include "oop.h"

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

92 93
oop_source_sys * kom_server_oop_src = NULL;
struct isc_mcb * kom_server_mcb    = NULL;
Per Cederqvist's avatar
Per Cederqvist committed
94 95
Connection     * active_connection = NULL;

Per Cederqvist's avatar
Per Cederqvist committed
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
99
 * privileges issues a `shutdown', or of lyskomd receives a SIGTERM.
Per Cederqvist's avatar
Per Cederqvist committed
100 101
 * This not an abort: all data is saved before we exit.
 */
102
Bool go_and_die = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
103 104

/*
105 106 107 108 109 110 111 112 113
 * 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
114
 */
115 116
static Bool work_done = FALSE;
static Bool is_idle = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
117 118 119 120 121 122 123 124

jmp_buf 	 parse_env;


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

125
const int num_fnc_defs = sizeof (fnc_defs) / sizeof (Fnc_descriptor);
126

Per Cederqvist's avatar
Per Cederqvist committed
127
unsigned long service_statistics[sizeof (fnc_defs) / sizeof (Fnc_descriptor)];
Per Cederqvist's avatar
Per Cederqvist committed
128 129 130

BUGDECL;

131 132 133
static oop_call_fd data_available_callback;
static oop_call_time check_kill_flg;
static oop_call_time check_idle_callback;
134 135 136
static isc_write_error_cb write_err_cb;
static isc_stale_output_cb stale_cb;
static isc_stale_output_cb idle_cb;
137

Per Cederqvist's avatar
Per Cederqvist committed
138 139
/* head and tail pointers for the wait queue that uses the queue_prev,
   queue_next and on_queue fields of Connection. */
140 141 142
static Connection *queue_first = NULL;
static Connection *queue_last = NULL;

143 144 145
static void busy(void);


Per Cederqvist's avatar
Per Cederqvist committed
146
/* Add c to the end of the wait queue. */
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
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;
162
    update_stat(STAT_RUN_QUEUE, 1);
163 164
}

Per Cederqvist's avatar
Per Cederqvist committed
165
/* Remove c from the wait queue. Any element on the queue can be removed. */
166 167 168 169 170 171 172 173 174 175 176 177 178 179
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
180
	queue_first = c->queue_next;
Per Cederqvist's avatar
Per Cederqvist committed
181

182 183
    c->queue_prev = NULL;
    c->queue_next = NULL;
184
    update_stat(STAT_RUN_QUEUE, -1);
185 186
}

Per Cederqvist's avatar
Per Cederqvist committed
187
void
188 189
set_time(void)
{
190 191
    struct timeval last_time;
    static int limiter = 0;
192 193

    last_time = current_time;
194 195 196 197 198 199 200 201 202 203 204
    if (gettimeofday(&current_time, NULL) < 0)
    {
	if (limiter < 50)
	{
	    kom_log("WARNING: gettimeofday failed: %s\n", strerror(errno));
	    if (++limiter == 50)
		kom_log("WARNING: will not log the above message again.\n");
	}
    }

    if (timeval_less(current_time, last_time))
205
    {
Per Cederqvist's avatar
Per Cederqvist committed
206
	kom_log("WARNING: Time moved backward at least %g seconds.\n",
207
		timeval_diff_d(last_time, current_time));
208 209 210
	/* FIXME (bug 62): Should we take more decisive action here? */
    }
}
Per Cederqvist's avatar
Per Cederqvist committed
211

Per Cederqvist's avatar
Per Cederqvist committed
212
static void
Per Cederqvist's avatar
Per Cederqvist committed
213 214 215
logout_client(Connection *cp)
{
    Connection *real_active_connection;
216
    int ret;
Per Cederqvist's avatar
Per Cederqvist committed
217 218 219

    if ( active_connection != NULL )
    {
David Byers's avatar
David Byers committed
220
	kom_log("BUGCHK: logout_client(%ld): connection %ld is active.\n",
Per Cederqvist's avatar
Per Cederqvist committed
221 222 223 224 225
	    cp->session_no, active_connection->session_no);
    }
    
    if ( cp->pers_no != 0 )
    {
226 227 228 229 230 231 232 233 234 235 236 237
	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
238 239 240 241
	active_connection = cp;
	logout();
	active_connection = real_active_connection;
    }
242 243
    else
    {
244
#if 0
245
	/* FIXME (bug 908): send a new async here instead.  This causes the
246 247
	   elisp client to say that a secret (or unknown) person has
	   left the system.  */
248
        async_logout( 0, cp->session_no );
249
#endif
250
    }
Per Cederqvist's avatar
Per Cederqvist committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264

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

265 266
    ret = isc_destroy(kom_server_mcb, cp->isc_session);
    if (ret < 0)
David Byers's avatar
David Byers committed
267
	kom_log("logout_client(): isc_destroyed returned %d\n", ret);
268
    cp->isc_session = NULL;
269 270
    if (cp->on_queue)
	queue_remove(cp);
Per Cederqvist's avatar
Per Cederqvist committed
271 272

    kill_client(cp);		/* Free the Connection */
273
    update_stat(STAT_CLIENTS, -1);
Per Cederqvist's avatar
Per Cederqvist committed
274 275
}

Per Cederqvist's avatar
Per Cederqvist committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289
/*
 * 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 )
290
	    restart_kom("logout_all_clients(): cant get session %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
291 292 293 294 295 296
			sess);
	else
	    logout_client (conn);
    }

    if ( traverse_connections (0) != 0)
297
	restart_kom("logout_all_clients(): traverse_connections(0) == %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
298 299 300 301
		    traverse_connections(0));
}

    
Per Cederqvist's avatar
Per Cederqvist committed
302 303 304 305 306 307 308 309
    

    
/*
 * 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
310 311
call_function(Connection *client,
	      union result_holder *res)
Per Cederqvist's avatar
Per Cederqvist committed
312 313 314 315 316
{
    Success	status=FAILURE;	/* OK if the call was successful. */

    if ( active_connection != NULL )
    {
317
	kom_log("call_function(%ld): active_connection = %ld\n",
Per Cederqvist's avatar
Per Cederqvist committed
318 319
	    client->session_no, active_connection->session_no);
    }
320 321 322

    if (client->function == illegal_fnc) 
    {
323
        err_stat = 0;
324 325 326 327
	kom_errno = KOM_NOT_IMPL;
	return FAILURE;
    }

Per Cederqvist's avatar
Per Cederqvist committed
328 329
    active_connection = client;

330
    service_statistics[client->function_index]++;
Per Cederqvist's avatar
Per Cederqvist committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

#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';
354 355
	    isc_puts("%%LysKOM unsupported protocol.\n", client->isc_session);
	    isc_flush(client->isc_session);
Per Cederqvist's avatar
Per Cederqvist committed
356
	    BUG(("%%%%Unsupported protocol.\n"));
357
	    longjmp(parse_env, KOM_LOGOUT);
Per Cederqvist's avatar
Per Cederqvist committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	}
    }

    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
387 388 389
    sfree(client->misc_info_list.misc);
    client->misc_info_list.misc = 0;
    client->misc_info_list.no_of_misc = 0;
390
    s_clear(&client->aux_item.data);
391
    s_clear(&client->dummy_aux_item.data);
392 393 394
    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
395 396
    client->parse_pos = 0;
    client->fnc_parse_pos = 0;
397
    client->array_parse_index = 0;
David Byers's avatar
David Byers committed
398
    client->array_parse_parsed_length = 0;
Per Cederqvist's avatar
Per Cederqvist committed
399 400 401
    client->array_parse_pos = 0;
    client->struct_parse_pos = 0;
    client->string_parse_pos = 0;
David Byers's avatar
David Byers committed
402 403 404
    client->hunt_parse_pos = 0;
    client->array_hunt_num = 0;
    client->array_hunt_depth = 0;
405 406 407
    sfree(client->num_list.data);
    client->num_list.data = NULL;
    client->num_list.length = 0;
408 409
    free_aux_item_list(&client->aux_item_list);
    client->info.highest_aux_no = 0;
Per Cederqvist's avatar
Per Cederqvist committed
410 411 412 413 414 415 416
}

/*
 * Send a reply to a call.
 */
static void
reply(Connection *client,
417 418
      Success status,
      union result_holder *result)
Per Cederqvist's avatar
Per Cederqvist committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
{
    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.
435 436
 * If more data is needed set client->more_to_parse to FALSE.  Returns
 * TRUE if anything was (or might have been) written to the client.
Per Cederqvist's avatar
Per Cederqvist committed
437
 */
438
static Bool
Per Cederqvist's avatar
Per Cederqvist committed
439 440 441
parse_unparsed(Connection *client)
{
    Success       status;
442
    union result_holder result;
Per Cederqvist's avatar
Per Cederqvist committed
443 444 445 446 447 448
        
    switch ( setjmp(parse_env) )
    {
    case 0 :
	/* Parse message. If message is complete call function and reply. */
	parse_packet(client);
449 450
	if (client->blocked_by_dns)
	    return TRUE;
451
	update_stat(STAT_REQUESTS, 1);
Per Cederqvist's avatar
Per Cederqvist committed
452
	status = call_function(client, &result);
453
	update_stat(STAT_REQUESTS, -1);
Per Cederqvist's avatar
Per Cederqvist committed
454
	reply(client, status, &result);
455
	client->penalty += param.penalty_per_call;
Per Cederqvist's avatar
Per Cederqvist committed
456
	free_parsed(client);
457
	end_of_atomic();
458
	return TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
459

460
    case KOM_PROTOCOL_ERR:
Per Cederqvist's avatar
Per Cederqvist committed
461 462
	s_clear(&client->string0);
	free_parsed(client);
463
	isc_puts("%% LysKOM protocol error.\n", client->isc_session);
Per Cederqvist's avatar
Per Cederqvist committed
464
	BUG(("%%%% Protocol error.\n"));
465
	client->penalty += param.max_penalty;
Per Cederqvist's avatar
Per Cederqvist committed
466 467 468
	s_clear(&client->unparsed);
	client->first_to_parse = 0;
	client->more_to_parse = FALSE;
469
	end_of_atomic();
470
	return TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
471

472
    case KOM_MSG_INCOMPLETE:
Per Cederqvist's avatar
Per Cederqvist committed
473
	client->more_to_parse = FALSE;
474
	return FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
475

476
    case KOM_LOGOUT:
477
	add_to_kill_list(client);
478
	client->more_to_parse = FALSE;
479 480 481
	return TRUE;
    default:
	restart_kom("Bad longjmp return value.\n");
Per Cederqvist's avatar
Per Cederqvist committed
482
    }
483
    /*NOTREACHED*/
Per Cederqvist's avatar
Per Cederqvist committed
484 485 486 487 488
}


/* Return 1 if the named file exists, 0 otherwise */
static int
Per Cederqvist's avatar
Per Cederqvist committed
489
fexists(const char *filename)
Per Cederqvist's avatar
Per Cederqvist committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503
{
    struct stat buf;
    int code;
  
    code = !stat(filename, &buf);
    errno = 0;

    return code;
}


void
dump_statistics(void)
{
504
    static struct timeval last_dump = {0, 0};
Per Cederqvist's avatar
Per Cederqvist committed
505 506 507
    int i;
    FILE *fp;

508
    if ((fp = i_fopen(param.statistic_name, "a")) == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
509
    {
510 511
	kom_log("dump_statistics(): can't open file %s\n",
		param.statistic_name);
Per Cederqvist's avatar
Per Cederqvist committed
512 513 514
	return;
    }

515
    if (timeval_zero(last_dump))
Per Cederqvist's avatar
Per Cederqvist committed
516 517
    {
	fprintf(fp, "RESTART\n");
Per Cederqvist's avatar
Per Cederqvist committed
518
	last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
519 520
    }
    
521 522
    fprintf(fp, "TIME: %s", ctime(&current_time.tv_sec));
    fprintf(fp, "SECONDS: %ld\n", timeval_diff_sec(current_time, last_dump));
Per Cederqvist's avatar
Per Cederqvist committed
523
    fprintf(fp, "STATISTICS:");
524 525 526 527 528

    /* 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
529
    {
530
	fprintf(fp, " %d:%lu", fnc_defs[i].function, service_statistics[i]);
Per Cederqvist's avatar
Per Cederqvist committed
531 532 533 534
	service_statistics[i]=0;
    }

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

Per Cederqvist's avatar
Per Cederqvist committed
537
    last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
538 539
}

540 541
/* List of connections to kill. */

Per Cederqvist's avatar
Per Cederqvist committed
542 543
static Session_no *kill_list = NULL;
static int kill_list_size = 0;
544
static int kill_pending = 0;
545 546 547 548 549

/* Schedule this client for termination. */
void
add_to_kill_list(Connection *conn)
{
550
    oop_source *source;
Per Cederqvist's avatar
Per Cederqvist committed
551 552
    int i;

553
    switch (conn->kill_status)
554
    {
555 556 557
    case ks_pending:
	/* A kill is already pending.  Do nothing--but check that the
	   the client really is present on the kill_list.  */
558 559 560
	for (i = 0; i < kill_list_size; i++)
	    if (kill_list[i] == conn->session_no)
		return;
561

562
	restart_kom("add_to_kill_list(): kill_pending set but not on list.\n");
563 564 565 566 567 568 569 570 571 572
	return;

    case ks_dying:
	/* Don't add this client to the kill list while it is being
	   killed.  */
	return;

    case ks_none:
	/* The normal case.  Do all the work below. */
	break;
573 574
    }

575
    /* Check that the client isn't already present on the kill_list. */
Per Cederqvist's avatar
Per Cederqvist committed
576
    for (i = 0; i < kill_list_size; i++)
577
	if (kill_list[i] == conn->session_no)
578
	    restart_kom("add_to_kill_list(): on list but not kill_pending.\n");
Per Cederqvist's avatar
Per Cederqvist committed
579

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    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;
595
    conn->kill_status = ks_pending;
596 597 598

    if (!kill_pending)
    {
599
	source = isc_getoopsource(conn->isc_session);
600 601 602
	source->on_time(source, OOP_TIME_NOW, check_kill_flg, NULL);
	kill_pending = 1;
    }
603
}
Per Cederqvist's avatar
Per Cederqvist committed
604

605

606
static void
607 608 609 610 611 612
dump_connections(void)
{
    Session_no s;
    Connection *conn;
    FILE *fp;

613
    if ((fp = i_fopen(param.connection_status_file_tmp, "w")) == NULL)
614
    {
615 616
	kom_log("dump_connections(): can't open file %s: %s\n",
		param.connection_status_file_tmp, strerror(errno));
617 618 619 620 621 622
	return;
    }

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

628 629 630 631 632 633
    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");

634
    if (i_fclose(fp) < 0)
635 636 637 638 639
    {
	kom_log("dump_connections(): fclose failed: %s (ignored)\n",
		strerror(errno));
    }

640 641 642
    errno = 0;
    if (i_rename(param.connection_status_file_tmp,
		 param.connection_status_file) < 0)
643
    {
644 645 646 647
	kom_log("dump_connections(): can't rename %s to %s: %s\n",
		param.connection_status_file_tmp,
		param.connection_status_file,
		strerror(errno));
648 649 650 651
    }
}


Per Cederqvist's avatar
Per Cederqvist committed
652 653 654
/*
 * check_kill_flg must NEVER be called inside an atomic call!
 */
655 656 657 658
static void *
check_kill_flg(oop_source *UNUSED(source),
	       struct timeval UNUSED(tv),
	       void *UNUSED(user))
Per Cederqvist's avatar
Per Cederqvist committed
659 660
{
    Connection *conn;
661
    Bool changed = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
662

663 664
    kill_pending = 0;

Per Cederqvist's avatar
Per Cederqvist committed
665 666
    if ( active_connection != NULL )
    {
667
	restart_kom("check_kill_flg: active_connection == %ld",
Per Cederqvist's avatar
Per Cederqvist committed
668 669 670
		    active_connection->session_no);
    }

671
    while (kill_list_size > 0)
Per Cederqvist's avatar
Per Cederqvist committed
672
    {
673 674 675
	--kill_list_size;
	conn = get_conn_by_number (kill_list[kill_list_size]);
	if (conn == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
676
	{
David Byers's avatar
David Byers committed
677
	    kom_log("check_kill_flg(): Connection %ld doesn't exist.\n",
678 679 680 681
		kill_list[kill_list_size]);
	}
	else
	{
682 683
	    assert(conn->kill_status == ks_pending);
	    conn->kill_status = ks_dying;
684 685
	    logout_client(conn);
	    end_of_atomic();
686
	    changed = TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
687 688
	}
    }
689

690 691 692 693 694
    if (kill_list != NULL)
    {
	sfree (kill_list);
	kill_list = NULL;
    }
695 696 697

    if (changed == TRUE)
	dump_connections();
698 699

    return OOP_CONTINUE;
Per Cederqvist's avatar
Per Cederqvist committed
700 701
}

702 703 704 705
static void *
dns_resolution(struct isc_scb *scb,
	       enum isc_resolve_status res,
	       long errcode)
706 707 708
{
    struct timeval after;
    double diff = -1.0;
709 710
    Connection *conn;
    char *hostname = NULL;
711

712
    update_stat(STAT_DNS_QUEUE, -1);
713

714
    conn = scb->udg;
715

716 717 718 719
    conn->dns_done = TRUE;
    if (conn->blocked_by_dns)
    {
	conn->blocked_by_dns = FALSE;
720 721
	if (!conn->on_queue)
	    queue_add(conn);
722 723
    }

724 725 726 727 728 729 730
    if (res == isc_resolve_aborted)
	return OOP_CONTINUE;

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

    diff = timeval_diff_d(after, conn->connect_time);
731

732 733 734
    busy();

    switch (res)
735
    {
736
    case isc_resolve_h_errno:
737
	if (hostname == NULL)
738 739 740 741 742 743 744 745 746 747
	    hostname = s_crea_c_str(scb->remote);

	if (errcode == HOST_NOT_FOUND)
	    kom_log("No hostname found for %s.\n", hostname);
	else if (errcode == TRY_AGAIN)
	    kom_log("Lookup of %s timed out.\n", hostname);
	else if (errcode == NO_RECOVERY)
	    kom_log("Non-recoverable error looking up %s.\n", hostname);
	else if (errcode == NO_ADDRESS)
	    kom_log("Got NO_ADDRESS error looking up %s.\n", hostname);
748
	else
749 750
	    kom_log("Unknown resolver error %ld looking up %s.\n",
		    errcode, hostname);
751
	break;
752

753
    case isc_resolve_adns_error:
754 755 756
	if (hostname == NULL)
	    hostname = s_crea_c_str(scb->remote);

757 758 759 760 761 762
	/* Misconfigurations of localhost are common and harmless.
	   Don't bother logging them, since that makes the test cases fail. */
	if ((errcode != adns_s_inconsistent && errcode != adns_s_nxdomain)
	    || strcmp(hostname, "127.0.0.1") != 0)
	    kom_log("Error looking up %s: %s\n",
		    hostname, adns_strerror(errcode));
763 764 765 766 767 768 769
	break;

    case isc_resolve_aborted:
	abort();

    case isc_resolve_ok:
	break;
770 771
    }

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    if (diff > param.dns_log_threshold)
    {
	if (hostname == NULL)
	    hostname = s_crea_c_str(scb->remote);

	if (res == isc_resolve_ok)
	    kom_log("Slow DNS: got %s after %f seconds\n", hostname, diff);
	else
	    kom_log("Slow bad DNS: %s failed after %f seconds\n",
		    hostname, diff);
   }

    if (hostname != NULL)
	string_free(hostname); 

787 788 789
    if (handshake_ok(conn, 0))
	dump_connections();

790
    return OOP_CONTINUE;
791 792
}

793
    
794
static void
795 796
write_err_cb(struct isc_scb *cb_session,
	     int saved_errno)
797
{
798
    Connection  * cp = cb_session->udg;
799
    if (saved_errno != ECONNRESET && saved_errno != EPIPE)
800 801
	kom_log("Failed to write to client %lu from %s: %s\n",
		cp->session_no, cp->peer, strerror(saved_errno));
802
    cp->penalty += param.max_penalty;
803 804 805 806
    add_to_kill_list(cp);
}


807
static void
808
stale_cb(struct isc_scb *cb_session)
809
{
810
    Connection *cp = cb_session->udg;
811 812 813 814 815 816
    kom_log("Client %lu from %s has stalled.  Killing it.\n",
	    cp->session_no, cp->peer);
    cp->penalty += param.max_penalty;
    add_to_kill_list(cp);
}
    
817

818
static void
819
idle_cb(struct isc_scb *cb_session)
820
{
821
    Connection *cp = cb_session->udg;
822 823 824 825 826 827 828
    kom_log("Client %lu from %s has been idle too long.  Killing it.\n",
	    cp->session_no, cp->peer);
    cp->penalty += param.max_penalty;
    add_to_kill_list(cp);
}


Per Cederqvist's avatar
Per Cederqvist committed
829
static void
830
login_request(struct isc_scb *session)
Per Cederqvist's avatar
Per Cederqvist committed
831 832
{
    Connection  * cp;
833
    const char *realuser;
834 835
    char portbuf[1+2+3*sizeof(long)];
    size_t portlen;
836
    char *remote_ip = NULL;
Per Cederqvist's avatar
Per Cederqvist committed
837 838

    /* Supress logins if /etc/nologin exists */
David Byers's avatar
David Byers committed
839
    if (fexists(param.nologin_file))
Per Cederqvist's avatar
Per Cederqvist committed
840
    {
841 842 843
	isc_puts("%% No logins allowed.\n", session);
	isc_flush(session);
 	isc_destroy(kom_server_mcb, session);
Per Cederqvist's avatar
Per Cederqvist committed
844 845 846
	return;
    }

847 848
    /* Create a Connection, and link the Connection and the
       isc_session together. */
849

850
    cp = new_client();
851 852
    cp->isc_session = session;
    session->udg = cp;
853
    update_stat(STAT_CLIENTS, 1);
854

855 856 857
    /* Store the IP address in readable form. */
    s_crea_str(&cp->remote_ip, isc_getipnum(session->raddr, NULL, 0));
    remote_ip = s_crea_c_str(cp->remote_ip);
858

859
    /* Initiate DNS lookup. */
860
    if (param.use_dns && isc_resolve_remote(session, dns_resolution) == 0)
861
	update_stat(STAT_DNS_QUEUE, 1);
862
    else
863
	s_strcpy(&session->remote, cp->remote_ip);
864

865 866 867 868 869 870
    /* Update the status file that contains all connection. */
    sprintf(portbuf, " %d", isc_getportnum(session->raddr));
    portlen = strlen(portbuf);
    cp->peer = smalloc(s_strlen(cp->remote_ip) + portlen + 1);
    strcpy(cp->peer, remote_ip);
    strcpy(cp->peer + s_strlen(cp->remote_ip), portbuf);
871

872
    dump_connections();
873

874 875 876 877
    /* Start with max penalty, so that it doesn't pay to make a lot of
       new connections.  */
    cp->penalty = param.max_penalty;
    cp->penalty_generation = penalty_generation;
878

879 880 881
    cp->schedule.priority = param.default_priority;
    cp->schedule.weight = param.default_weight;

882 883 884
    /* Get the real user name, as returned by the Ident protocol (rfc 931). */
    realuser = get_real_username(session, remote_ip);
    if (realuser == NULL && param.authentication_level == 2)
885
    {
886 887 888 889 890 891 892 893 894
	kom_log("Connection from %s rejected - no IDENT available.\n", 
		remote_ip);

	isc_puts("%% No IDENT server reachable at your site.\n",
		 session);
	isc_flush(session);
	logout_client(cp);
	string_free(remote_ip);
	return;
895 896
    }

897 898 899 900
    if (realuser != NULL)
	s_crea_str(&cp->ident_user, realuser);

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

902
    isc_set_read_callback(session, data_available_callback, write_err_cb,
903
			  stale_cb, idle_cb);
904
    string_free(remote_ip);
Per Cederqvist's avatar
Per Cederqvist committed
905 906 907
}

static void
908
adjust_penalty(Connection *conn)
Per Cederqvist's avatar
Per Cederqvist committed
909
{
910 911
    unsigned int gens = penalty_generation - conn->penalty_generation;
    if (gens > 0)
912
    {
913 914 915 916 917 918
	/* The weight is in the range 1-0xffff (inclusive).
	   The penalty is in the range 0-0x10000 (inclusive).
	   This means that the multiplication can never overflow. */

	if (conn->penalty <= gens)
	    conn->penalty = 0;
919
	else
920 921 922 923 924 925 926 927 928
	{
	    unsigned int tmp = conn->penalty - gens * conn->schedule.weight;
	    if (tmp < conn->penalty)
		conn->penalty = tmp;
	    else
		conn->penalty = 0;
	}

	conn->penalty_generation = penalty_generation;
929
    }
Per Cederqvist's avatar
Per Cederqvist committed
930 931 932 933
}


static void
934
read_from_connection(Connection *conn)
Per Cederqvist's avatar
Per Cederqvist committed
935