connections.c 29.3 KB
Newer Older
Linus Tolke's avatar
Linus Tolke committed
1
/*
Per Cederqvist's avatar
Per Cederqvist committed
2
 * $Id: connections.c,v 0.123 2003/08/16 11:29:03 ceder Exp $
Per Cederqvist's avatar
Per Cederqvist committed
3
 * Copyright (C) 1991-2002  Lysator Academic Computer Association.
Linus Tolke's avatar
Linus Tolke committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * 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
23
 * Please report bugs at http://bugzilla.lysator.liu.se/. 
Linus Tolke's avatar
Linus Tolke committed
24
 */
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>
46
#include "timewrap.h"
47
#include <sys/socket.h>
48
#include <signal.h>
49
#include <assert.h>
50
#include <netdb.h>
Per Cederqvist's avatar
Per Cederqvist committed
51
#include <stdlib.h>
Per Cederqvist's avatar
Per Cederqvist committed
52

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

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

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

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

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

jmp_buf 	 parse_env;


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

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

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

BUGDECL;

132
133
134
static oop_call_fd data_available_callback;
static oop_call_time check_kill_flg;
static oop_call_time check_idle_callback;
135
136
137
static isc_write_error_cb write_err_cb;
static isc_stale_output_cb stale_cb;
static isc_stale_output_cb idle_cb;
138
139
140
141

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

142
143
144
static void busy(void);


145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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;
160
    update_stat(STAT_RUN_QUEUE, 1);
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
}

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
177
	queue_first = c->queue_next;
Per Cederqvist's avatar
Per Cederqvist committed
178

179
180
    c->queue_prev = NULL;
    c->queue_next = NULL;
181
    update_stat(STAT_RUN_QUEUE, -1);
182
183
}

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

    last_time = current_time;
191
192
193
194
195
196
197
198
199
200
201
    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))
202
203
204
205
206
    {
	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
207

Per Cederqvist's avatar
Per Cederqvist committed
208
static void
Per Cederqvist's avatar
Per Cederqvist committed
209
210
211
logout_client(Connection *cp)
{
    Connection *real_active_connection;
212
    int ret;
Per Cederqvist's avatar
Per Cederqvist committed
213
214
215

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

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

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

    kill_client(cp);		/* Free the Connection */
269
    update_stat(STAT_CLIENTS, -1);
Per Cederqvist's avatar
Per Cederqvist committed
270
271
}

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

    if ( traverse_connections (0) != 0)
293
	restart_kom("logout_all_clients(): traverse_connections(0) == %ld.\n",
Per Cederqvist's avatar
Per Cederqvist committed
294
295
296
297
		    traverse_connections(0));
}

    
Per Cederqvist's avatar
Per Cederqvist committed
298
299
300
301
302
303
304
305
    

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

    if ( active_connection != NULL )
    {
313
	kom_log("call_function(%ld): active_connection = %ld\n",
Per Cederqvist's avatar
Per Cederqvist committed
314
315
	    client->session_no, active_connection->session_no);
    }
316
317
318

    if (client->function == illegal_fnc) 
    {
319
        err_stat = 0;
320
321
322
323
	kom_errno = KOM_NOT_IMPL;
	return FAILURE;
    }

Per Cederqvist's avatar
Per Cederqvist committed
324
325
    active_connection = client;

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

#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';
350
351
	    isc_puts("%%LysKOM unsupported protocol.\n", client->isc_session);
	    isc_flush(client->isc_session);
Per Cederqvist's avatar
Per Cederqvist committed
352
	    BUG(("%%%%Unsupported protocol.\n"));
353
	    longjmp(parse_env, KOM_LOGOUT);
Per Cederqvist's avatar
Per Cederqvist committed
354
355
356
357
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
	}
    }

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

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

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

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

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


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

    return code;
}


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

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

513
    if (timeval_zero(last_dump))
Per Cederqvist's avatar
Per Cederqvist committed
514
515
    {
	fprintf(fp, "RESTART\n");
Per Cederqvist's avatar
Per Cederqvist committed
516
	last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
517
518
    }
    
519
520
    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
521
    fprintf(fp, "STATISTICS:");
522
523
524
525
526

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

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

Per Cederqvist's avatar
Per Cederqvist committed
535
    last_dump = current_time;
Per Cederqvist's avatar
Per Cederqvist committed
536
537
}

538
539
/* List of connections to kill. */

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

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

551
552
553
554
555
556
557
558
    if (conn->kill_pending)
    {
	for (i = 0; i < kill_list_size; i++)
	    if (kill_list[i] == conn->session_no)
		return;
	restart_kom("add_to_kill_list(): kill_pending set but not on list.\n");
    }

Per Cederqvist's avatar
Per Cederqvist committed
559
    for (i = 0; i < kill_list_size; i++)
560
	if (kill_list[i] == conn->session_no)
561
	    restart_kom("add_to_kill_list(): on list but not kill_pending.\n");
Per Cederqvist's avatar
Per Cederqvist committed
562

563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    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;
578
    conn->kill_pending = TRUE;
579
580
581

    if (!kill_pending)
    {
582
	source = isc_getoopsource(conn->isc_session);
583
584
585
	source->on_time(source, OOP_TIME_NOW, check_kill_flg, NULL);
	kill_pending = 1;
    }
586
}
Per Cederqvist's avatar
Per Cederqvist committed
587

588
589
590
591
592
593
594
595

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

596
    if ((fp = i_fopen(param.connection_status_file_tmp, "w")) == NULL)
597
    {
598
599
	kom_log("dump_connections(): can't open file %s: %s\n",
		param.connection_status_file_tmp, strerror(errno));
600
601
602
603
604
605
	return;
    }

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

611
612
613
614
615
616
    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");

617
    if (i_fclose(fp) < 0)
618
619
620
621
622
    {
	kom_log("dump_connections(): fclose failed: %s (ignored)\n",
		strerror(errno));
    }

623
    errno = 0;
624
625
    if (i_rename(param.connection_status_file_tmp,
		 param.connection_status_file) < 0)
626
    {
627
	kom_log("dump_connections(): can't rename %s to %s: %s\n",
628
		param.connection_status_file_tmp,
629
630
		param.connection_status_file,
		strerror(errno));
631
632
633
634
    }
}


Per Cederqvist's avatar
Per Cederqvist committed
635
636
637
/*
 * check_kill_flg must NEVER be called inside an atomic call!
 */
638
639
640
641
static void *
check_kill_flg(oop_source *UNUSED(source),
	       struct timeval UNUSED(tv),
	       void *UNUSED(user))
Per Cederqvist's avatar
Per Cederqvist committed
642
643
{
    Connection *conn;
644
    Bool changed = FALSE;
Per Cederqvist's avatar
Per Cederqvist committed
645

646
647
    kill_pending = 0;

Per Cederqvist's avatar
Per Cederqvist committed
648
649
    if ( active_connection != NULL )
    {
650
	restart_kom("check_kill_flg: active_connection == %ld",
Per Cederqvist's avatar
Per Cederqvist committed
651
652
653
		    active_connection->session_no);
    }

654
    while (kill_list_size > 0)
Per Cederqvist's avatar
Per Cederqvist committed
655
    {
656
657
658
	--kill_list_size;
	conn = get_conn_by_number (kill_list[kill_list_size]);
	if (conn == NULL)
Per Cederqvist's avatar
Per Cederqvist committed
659
	{
David Byers's avatar
David Byers committed
660
	    kom_log("check_kill_flg(): Connection %ld doesn't exist.\n",
661
662
663
664
		kill_list[kill_list_size]);
	}
	else
	{
665
666
	    assert(conn->kill_pending);
	    conn->kill_pending = FALSE;
667
668
	    logout_client(conn);
	    end_of_atomic();
669
	    changed = TRUE;
Per Cederqvist's avatar
Per Cederqvist committed
670
671
	}
    }
672

673
674
675
676
677
    if (kill_list != NULL)
    {
	sfree (kill_list);
	kill_list = NULL;
    }
678
679
680

    if (changed == TRUE)
	dump_connections();
681
682

    return OOP_CONTINUE;
Per Cederqvist's avatar
Per Cederqvist committed
683
684
}

685
686
687
688
static void *
dns_resolution(struct isc_scb *scb,
	       enum isc_resolve_status res,
	       long errcode)
689
690
691
{
    struct timeval after;
    double diff = -1.0;
692
693
    Connection *conn;
    char *hostname = NULL;
694

695
    update_stat(STAT_DNS_QUEUE, -1);
696

697
    conn = scb->udg;
698

699
700
701
702
    conn->dns_done = TRUE;
    if (conn->blocked_by_dns)
    {
	conn->blocked_by_dns = FALSE;
703
704
	if (!conn->on_queue)
	    queue_add(conn);
705
706
    }

707
708
709
710
711
712
713
    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);
714

715
716
717
    busy();

    switch (res)
718
    {
719
    case isc_resolve_h_errno:
720
	if (hostname == NULL)
721
722
723
724
725
726
727
728
729
730
	    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);
731
	else
732
733
	    kom_log("Unknown resolver error %ld looking up %s.\n",
		    errcode, hostname);
734
	break;
735

736
    case isc_resolve_adns_error:
737
738
739
	if (hostname == NULL)
	    hostname = s_crea_c_str(scb->remote);

740
741
742
743
744
745
	/* 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));
746
747
748
749
750
751
752
	break;

    case isc_resolve_aborted:
	abort();

    case isc_resolve_ok:
	break;
753
754
    }

755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    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); 

    return OOP_CONTINUE;
771
772
}

773
    
774
static void
775
776
write_err_cb(struct isc_scb *cb_session,
	     int saved_errno)
777
{
778
    Connection  * cp = cb_session->udg;
779
    if (saved_errno != ECONNRESET && saved_errno != EPIPE)
780
781
	kom_log("Failed to write to client %lu from %s: %s\n",
		cp->session_no, cp->peer, strerror(saved_errno));
782
    cp->penalty += param.max_penalty;
783
784
785
786
    add_to_kill_list(cp);
}


787
static void
788
stale_cb(struct isc_scb *cb_session)
789
{
790
    Connection *cp = cb_session->udg;
791
792
793
794
795
796
    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);
}
    
797

798
static void
799
idle_cb(struct isc_scb *cb_session)
800
{
801
    Connection *cp = cb_session->udg;
802
803
804
805
806
807
808
    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
809
static void
810
login_request(struct isc_scb *session)
Per Cederqvist's avatar
Per Cederqvist committed
811
812
{
    Connection  * cp;
813
    const char *realuser;
814
815
    char portbuf[1+2+3*sizeof(long)];
    size_t portlen;
816
    char *remote_ip = NULL;
Per Cederqvist's avatar
Per Cederqvist committed
817
818

    /* Supress logins if /etc/nologin exists */
David Byers's avatar
David Byers committed
819
    if (fexists(param.nologin_file))
Per Cederqvist's avatar
Per Cederqvist committed
820
    {
821
822
823
	isc_puts("%% No logins allowed.\n", session);
	isc_flush(session);
 	isc_destroy(kom_server_mcb, session);
Per Cederqvist's avatar
Per Cederqvist committed
824
825
826
	return;
    }

827
828
    /* Create a Connection, and link the Connection and the
       isc_session together. */
829

830
    cp = new_client();
831
832
    cp->isc_session = session;
    session->udg = cp;
833
    update_stat(STAT_CLIENTS, 1);
834

835
836
837
    /* 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);
838

839
    /* Initiate DNS lookup. */
840
    if (param.use_dns && isc_resolve_remote(session, dns_resolution) == 0)
841
	update_stat(STAT_DNS_QUEUE, 1);
842
    else
843
	s_strcpy(&session->remote, cp->remote_ip);
844

845
846
847
848
849
850
    /* 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);
851

852
    dump_connections();
853

854
855
856
857
    /* 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;
858

859
860
861
    cp->schedule.priority = param.default_priority;
    cp->schedule.weight = param.default_weight;

862
863
864
    /* 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)
865
    {
866
867
868
869
870
871
872
873
874
	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;
875
876
    }

877
878
879
880
    if (realuser != NULL)
	s_crea_str(&cp->ident_user, realuser);

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

882
    isc_set_read_callback(session, data_available_callback, write_err_cb,
883
			  stale_cb, idle_cb);
884
    string_free(remote_ip);
Per Cederqvist's avatar
Per Cederqvist committed
885
886
887
}

static void
888
adjust_penalty(Connection *conn)
Per Cederqvist's avatar
Per Cederqvist committed
889
{
890
891
    unsigned int gens = penalty_generation - conn->penalty_generation;
    if (gens > 0)
892
    {
893
894
895
896
897
898
	/* 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;
899
	else
900
901
902
903
904
905
906
907
908
	{
	    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;
909
    }
Per Cederqvist's avatar
Per Cederqvist committed
910
911
912
913
}


static void
914
read_from_connection(Connection *conn)
Per Cederqvist's avatar
Per Cederqvist committed
915
{
916
    Bool would_block = FALSE;
917
    Bool need_flush = FALSE;
918
    String_size pre;
Per Cederqvist's avatar
Per Cederqvist committed
919

920
921
    adjust_penalty(conn);

922
    while (!would_block && !go_and_die && conn->penalty < param.max_penalty
923
	   && !conn->kill_pending && !conn->blocked_by_dns)
924
    {
925
	pre = s_strlen(conn->unparsed) - conn->first_to_parse;
926
	while (conn->more_to_parse
927
	       && !go_and_die && conn->penalty < param.max_penalty
928
	       && !conn->kill_pending && !conn->blocked_by_dns)
929
	    need_flush |= parse_unparsed(conn);
930
931
	update_stat(STAT_RECV_QUEUE,
		    s_strlen(conn->unparsed) - conn->first_to_parse - pre);
932

933
	if (go_and_die || conn->penalty >= param.max_penalty
934
	    || conn->kill_pending || conn->blocked_by_dns)
935
936
937
938
	    break;

	if (!conn->more_to_parse)
	{
939
	    pre = s_strlen(conn->unparsed) - conn->first_to_parse;
940
941
942
943
944
	    switch (isc_read_data(conn->isc_session,
				  &conn->unparsed,
				  &conn->first_to_parse))
	    {
	    case ISC_READ_DATA:
945
946
947
		update_stat(STAT_RECV_QUEUE,
			    s_strlen(conn->unparsed) - conn->first_to_parse
			    - pre);
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
		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;
	}
    }
970

971
    if (need_flush)
972
973
	isc_flush(conn->isc_session);

974
975
976
977
978
    /* 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;

979
    if (conn->penalty >= param.max_penalty && !conn->blocked_by_dns)
980
    {
981
982
983
984
985
	/* isc_disable() will fail if we have received EPIPE on
	   this socket.  In that case will soon close it, since
	   write_err_cb() has added it to the kill list. */
	if (isc_disable(conn->isc_session) == 0)
	    queue_add(conn);
986
    }
Per Cederqvist's avatar
Per Cederqvist committed
987
988
}

989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005

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;
1006
1007
    Connection *head = NULL;
    Connection *tail = NULL;
1008
1009
1010
1011
1012
1013
1014
1015
1016

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

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

1018
	for (next = queue_first; next != NULL; )
Per Cederqvist's avatar
Per Cederqvist committed
1019
	{
1020
1021
1022
1023
	    c = next;
	    next = next->queue_next;
	    adjust_penalty(c);
	    if (c->penalty < param.low_penalty)
Per Cederqvist's avatar
Per Cederqvist committed
1024
	    {
1025
		queue_remove(c);
1026
1027
1028
1029
1030
1031

		if (head == NULL)
		    head = c;
		else
		    tail->queue_next = c;
		tail = c;
Per Cederqvist's avatar
Per Cederqvist committed
1032
	    }
1033
1034
1035
	}
    }

1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
    for (next = head; next != NULL; )
    {
	c = next;
	next = next->queue_next;
	c->queue_next = NULL;
	if (isc_enable(c->isc_session) < 0)
	    restart_kom("failed to re-enable session\n");

	/* The call to read_from_connection() might add the
	   connection to the queue.  That's why we remove all entries
	   first, and use a private queue within this function.  */
	if (!go_and_die)
	    read_from_connection(c);
    }

1051
1052
1053
    if (!is_idle)
	enable_idle_check();

1054
1055
    /* Check if a client issued a shutdown command.  */
    return go_and_die ? OOP_HALT : OOP_CONTINUE;
1056
1057
1058
}

static void *
Per Cederqvist's avatar
Per Cederqvist committed
1059
saver_callback(oop_source *source,
1060
1061
1062
	       struct timeval UNUSED(tv),
	       void *user)
{
1063
    struct timeval timeout;
1064
    struct timeval *next_timer = user;
1065

1066
    timeout = end_of_atomic();
1067
1068
    if (setup_timer(next_timer, timeout) < 0)
	kom_log("gettimeofday failed: %s\n", strerror(errno));
Per Cederqvist's avatar
Per Cederqvist committed
1069

1070
1071
1072
    source->on_time(source, *next_timer, saver_callback, user);
    return OOP_CONTINUE;
}
Per Cederqvist's avatar
Per Cederqvist committed
1073
1074


1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
static void
busy(void)
{
    /* Something arrived, so we are busy.  */
    if (is_idle)
    {
	is_idle = FALSE;
	enable_idle_check();
    }
	
    work_done = TRUE;
}

1088
1089
1090
1091
1092
1093
static void *
data_available_callback(oop_source *source,
			int fd,
			oop_event event,
			void *user)
{
1094
    Connection *conn = ((struct isc_scb*)user)->udg;
1095
1096
1097

    assert(event == OOP_READ);
    assert(conn->isc_session->fd == fd);
1098
    assert(isc_getoopsource(conn->isc_session) == source);
1099
    assert(conn->on_queue == FALSE);
1100

1101
    busy();
1102
1103
1104
1105
1106
1107
1108
1109
1110
    set_time();
    read_from_connection(conn);

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


void *
1111
handle_accept_event(struct isc_scb *UNUSED(accepting_session),
1112
1113
		    struct isc_scb *new_session)
{
1114
    new_session->udg = NULL;
1115