upstream.c 24.9 KB
Newer Older
Ondřej Kuzník's avatar
Ondřej Kuzník committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 1998-2020 The OpenLDAP Foundation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */

#include "portable.h"

#include <ac/socket.h>
#include <ac/errno.h>
#include <ac/string.h>
#include <ac/time.h>
#include <ac/unistd.h>

#include "lutil.h"
#include "slap.h"

Ondřej Kuzník's avatar
Ondřej Kuzník committed
27
int
Ondřej Kuzník's avatar
Ondřej Kuzník committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
forward_response( Operation *op, BerElement *ber )
{
    Connection *c = op->o_client;
    BerElement *output;
    BerValue response, controls = BER_BVNULL;
    ber_tag_t tag, response_tag;
    ber_len_t len;

    response_tag = ber_skip_element( ber, &response );

    tag = ber_peek_tag( ber, &len );
    if ( tag == LDAP_TAG_CONTROLS ) {
        ber_skip_element( ber, &controls );
    }

Ondřej Kuzník's avatar
Ondřej Kuzník committed
43
    Debug( LDAP_DEBUG_TRACE, "forward_response: "
Ondřej Kuzník's avatar
Ondřej Kuzník committed
44
            "%s to client connid=%lu request msgid=%d\n",
45
46
            slap_msgtype2str( response_tag ), op->o_client_connid,
            op->o_client_msgid );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

    ldap_pvt_thread_mutex_lock( &c->c_io_mutex );
    output = c->c_pendingber;
    if ( output == NULL && (output = ber_alloc()) == NULL ) {
        ber_free( ber, 1 );
        ldap_pvt_thread_mutex_unlock( &c->c_io_mutex );
        return -1;
    }
    c->c_pendingber = output;

    ber_printf( output, "t{titOtO}", LDAP_TAG_MESSAGE,
            LDAP_TAG_MSGID, op->o_client_msgid,
            response_tag, &response,
            LDAP_TAG_CONTROLS, BER_BV_OPTIONAL( &controls ) );

    ldap_pvt_thread_mutex_unlock( &c->c_io_mutex );

    ber_free( ber, 1 );
65
    connection_write_cb( -1, 0, c );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
66
67
68
    return 0;
}

Ondřej Kuzník's avatar
Ondřej Kuzník committed
69
int
Ondřej Kuzník's avatar
Ondřej Kuzník committed
70
71
72
73
forward_final_response( Operation *op, BerElement *ber )
{
    int rc;

Ondřej Kuzník's avatar
Ondřej Kuzník committed
74
    Debug( LDAP_DEBUG_STATS, "forward_final_response: "
Ondřej Kuzník's avatar
Ondřej Kuzník committed
75
76
77
            "connid=%lu msgid=%d finishing up with a request for "
            "client connid=%lu\n",
            op->o_upstream_connid, op->o_upstream_msgid, op->o_client_connid );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
78
    rc = forward_response( op, ber );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
79
80
81
    CONNECTION_LOCK_DECREF(op->o_upstream);
    operation_destroy_from_upstream( op );
    CONNECTION_UNLOCK_INCREF(op->o_upstream);
Ondřej Kuzník's avatar
Ondřej Kuzník committed
82
83
84
85
86
87
88

    return rc;
}

static int
handle_unsolicited( Connection *c, BerElement *ber )
{
89
90
    if ( c->c_state == LLOAD_C_READY ) {
        c->c_state = LLOAD_C_CLOSING;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
91
    }
92

Ondřej Kuzník's avatar
Ondřej Kuzník committed
93
    Debug( LDAP_DEBUG_CONNS, "handle_unsolicited: "
Ondřej Kuzník's avatar
Ondřej Kuzník committed
94
            "teardown for upstream connection connid=%lu\n",
Ondřej Kuzník's avatar
Ondřej Kuzník committed
95
96
            c->c_connid );

97
    CONNECTION_DESTROY(c);
Ondřej Kuzník's avatar
Ondřej Kuzník committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    ber_free( ber, 1 );

    return -1;
}

/*
 * Pull c->c_currentber from the connection and try to look up the operation on
 * the upstream.
 *
 * If it's a notice of disconnection, we won't find it and need to tear down
 * the connection and tell the clients, if we can't find the operation, ignore
 * the message (either client already disconnected/abandoned it or the upstream
 * is pulling our leg).
 *
 * Some responses need special handling:
 * - Bind response
 * - VC response where the client requested a Bind (both need to update the
 *   client's bind status)
 * - search entries/referrals and intermediate responses (will not trigger
 *   operation to be removed)
 *
 * If the worker pool is overloaded, we might be called directly from
120
 * the read callback, at that point, the connection hasn't been muted.
Ondřej Kuzník's avatar
Ondřej Kuzník committed
121
122
123
124
 *
 * TODO: when the client already has data pending on write, we should mute the
 * upstream.
 * - should record the BerElement on the Op and the Op on the client
Ondřej Kuzník's avatar
Ondřej Kuzník committed
125
126
127
128
129
 *
 * The following hold on entering any of the handlers:
 * - op->o_upstream_refcnt > 0
 * - op->o_upstream->c_refcnt > 0
 * - op->o_client->c_refcnt > 0
Ondřej Kuzník's avatar
Ondřej Kuzník committed
130
131
132
133
134
 */
static int
handle_one_response( Connection *c )
{
    BerElement *ber;
135
    Operation *op = NULL, needle = { .o_upstream_connid = c->c_connid };
Ondřej Kuzník's avatar
Ondřej Kuzník committed
136
137
138
    OperationHandler handler = NULL;
    ber_tag_t tag;
    ber_len_t len;
139
    int rc = LDAP_SUCCESS;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

    ber = c->c_currentber;
    c->c_currentber = NULL;

    tag = ber_get_int( ber, &needle.o_upstream_msgid );
    if ( tag != LDAP_TAG_MSGID ) {
        rc = -1;
        ber_free( ber, 1 );
        goto fail;
    }

    if ( needle.o_upstream_msgid == 0 ) {
        return handle_unsolicited( c, ber );
    } else if ( !( op = tavl_find(
                           c->c_ops, &needle, operation_upstream_cmp ) ) ) {
        /* Already abandoned, do nothing */
156
157
        ber_free( ber, 1 );
        return rc;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        /*
    } else if ( op->o_response_pending ) {
        c->c_pendingop = op;
        event_del( c->c_read_event );
    */
    } else {
        /*
        op->o_response_pending = ber;
        */

        tag = ber_peek_tag( ber, &len );
        switch ( tag ) {
            case LDAP_RES_SEARCH_ENTRY:
            case LDAP_RES_SEARCH_REFERENCE:
            case LDAP_RES_INTERMEDIATE:
                handler = forward_response;
                break;
            case LDAP_RES_BIND:
                handler = handle_bind_response;
                break;
            case LDAP_RES_EXTENDED:
179
#ifdef LDAP_API_FEATURE_VERIFY_CREDENTIALS
Ondřej Kuzník's avatar
Ondřej Kuzník committed
180
181
182
                if ( op->o_tag == LDAP_REQ_BIND ) {
                    handler = handle_vc_bind_response;
                }
183
#endif /* LDAP_API_FEATURE_VERIFY_CREDENTIALS */
Ondřej Kuzník's avatar
Ondřej Kuzník committed
184
185
186
187
188
189
190
                break;
        }
        if ( !handler ) {
            handler = forward_final_response;
        }
    }
    if ( op ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
191
        Debug( LDAP_DEBUG_STATS2, "handle_one_response: "
Ondřej Kuzník's avatar
Ondřej Kuzník committed
192
193
                "upstream connid=%lu, processing response for "
                "client connid=%lu, msgid=%d\n",
194
                c->c_connid, op->o_client_connid, op->o_client_msgid );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
195
196
    } else {
        tag = ber_peek_tag( ber, &len );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
197
198
199
        Debug( LDAP_DEBUG_STATS2, "handle_one_response: "
                "upstream connid=%lu, %s, msgid=%d not for a pending "
                "operation\n",
Ondřej Kuzník's avatar
Ondřej Kuzník committed
200
201
202
203
                c->c_connid, slap_msgtype2str( tag ), needle.o_upstream_msgid );
    }

    if ( handler ) {
204
205
        Connection *client;

Ondřej Kuzník's avatar
Ondřej Kuzník committed
206
207
        op->o_upstream_refcnt++;
        CONNECTION_UNLOCK_INCREF(c);
208

Ondřej Kuzník's avatar
Ondřej Kuzník committed
209
        ldap_pvt_thread_mutex_lock( &op->o_link_mutex );
210
211
212
        client = op->o_client;
        if ( client ) {
            CONNECTION_LOCK(client);
213
214
215
216
217
218
219
            if ( client->c_live ) {
                op->o_client_refcnt++;
                CONNECTION_UNLOCK_INCREF(client);
            } else {
                CONNECTION_UNLOCK(client);
                client = NULL;
            }
220
        }
Ondřej Kuzník's avatar
Ondřej Kuzník committed
221
        ldap_pvt_thread_mutex_unlock( &op->o_link_mutex );
222
223
224
225

        if ( client ) {
            rc = handler( op, ber );
            CONNECTION_LOCK_DECREF(client);
226
227
228
229
            op->o_client_refcnt--;
            if ( !op->o_client_refcnt ) {
                operation_destroy_from_client( op );
            }
230
            CONNECTION_UNLOCK_OR_DESTROY(client);
231
232
233
234
        } else {
            ber_free( ber, 1 );
        }

Ondřej Kuzník's avatar
Ondřej Kuzník committed
235
236
        CONNECTION_LOCK_DECREF(c);
        op->o_upstream_refcnt--;
237
        if ( !client || !op->o_upstream_refcnt ) {
238
239
            if ( c->c_state == LLOAD_C_BINDING ) {
                c->c_state = LLOAD_C_READY;
240
            }
Ondřej Kuzník's avatar
Ondřej Kuzník committed
241
242
            operation_destroy_from_upstream( op );
        }
243
244
    } else {
        ber_free( ber, 1 );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
245
246
247
248
    }

fail:
    if ( rc ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
249
250
251
252
        Debug( LDAP_DEBUG_STATS, "handle_one_response: "
                "error on processing a response (%s) on upstream connection "
                "connid=%ld, tag=%lx\n",
                slap_msgtype2str( tag ), c->c_connid, tag );
253
        CONNECTION_DESTROY(c);
Ondřej Kuzník's avatar
Ondřej Kuzník committed
254
    }
255
    /* We leave the connection locked */
Ondřej Kuzník's avatar
Ondřej Kuzník committed
256
257
258
    return rc;
}

259
int
Ondřej Kuzník's avatar
Ondřej Kuzník committed
260
upstream_bind_cb( Connection *c )
261
{
Ondřej Kuzník's avatar
Ondřej Kuzník committed
262
263
    BerElement *ber = c->c_currentber;
    Backend *b = c->c_private;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
264
    BerValue matcheddn, message;
265
266
267
268
269
270
    ber_tag_t tag;
    ber_int_t msgid, result;

    c->c_currentber = NULL;

    if ( ber_scanf( ber, "it", &msgid, &tag ) == LBER_ERROR ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
271
272
        Debug( LDAP_DEBUG_ANY, "upstream_bind_cb: "
                "protocol violation from server\n" );
273
274
275
276
        goto fail;
    }

    if ( msgid != ( c->c_next_msgid - 1 ) || tag != LDAP_RES_BIND ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
277
278
        Debug( LDAP_DEBUG_ANY, "upstream_bind_cb: "
                "unexpected %s from server, msgid=%d\n",
279
                slap_msgtype2str( tag ), msgid );
280
281
282
        goto fail;
    }

Ondřej Kuzník's avatar
Ondřej Kuzník committed
283
    if ( ber_scanf( ber, "{emm" /* "}" */, &result, &matcheddn, &message ) ==
284
                 LBER_ERROR ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
285
286
        Debug( LDAP_DEBUG_ANY, "upstream_bind_cb: "
                "response does not conform with a bind response\n" );
287
288
289
290
        goto fail;
    }

    switch ( result ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
291
292
        case LDAP_SUCCESS: {
            c->c_pdu_cb = handle_one_response;
293
294
            c->c_state = LLOAD_C_READY;
            c->c_type = LLOAD_C_OPEN;
295
296
297
298
299
            c->c_read_timeout = NULL;
            event_add( c->c_read_event, c->c_read_timeout );
            Debug( LDAP_DEBUG_CONNS, "upstream_bind_cb: "
                    "connid=%lu finished binding, now active\n",
                    c->c_connid );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
300
301
302
303
304
305
            CONNECTION_UNLOCK_INCREF(c);
            ldap_pvt_thread_mutex_lock( &b->b_mutex );
            LDAP_CIRCLEQ_REMOVE( &b->b_preparing, c, c_next );
            b->b_active++;
            b->b_opening--;
            b->b_failed = 0;
306
307
308
309
310
311
312
            if ( b->b_last_conn ) {
                LDAP_CIRCLEQ_INSERT_AFTER(
                        &b->b_conns, b->b_last_conn, c, c_next );
            } else {
                LDAP_CIRCLEQ_INSERT_HEAD( &b->b_conns, c, c_next );
            }
            b->b_last_conn = c;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
313
314
315
316
            ldap_pvt_thread_mutex_unlock( &b->b_mutex );
            backend_retry( b );
            CONNECTION_LOCK_DECREF(c);
        } break;
317
318
319
320
321
322
323
#ifdef HAVE_CYRUS_SASL
        case LDAP_SASL_BIND_IN_PROGRESS:
            /* TODO: fallthrough until we implement SASL */
#endif /* HAVE_CYRUS_SASL */
        default:
            Debug( LDAP_DEBUG_ANY, "upstream_bind_cb: "
                    "upstream bind failed, rc=%d, message='%s'\n",
Ondřej Kuzník's avatar
Ondřej Kuzník committed
324
                    result, message.bv_val );
325
326
327
            goto fail;
    }

Ondřej Kuzník's avatar
Ondřej Kuzník committed
328
    ber_free( ber, 1 );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
329
    return LDAP_SUCCESS;
330

Ondřej Kuzník's avatar
Ondřej Kuzník committed
331
fail:
332
    ber_free( ber, 1 );
333
    CONNECTION_DESTROY(c);
Ondřej Kuzník's avatar
Ondřej Kuzník committed
334
    return -1;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
335
336
}

337
338
void *
upstream_bind( void *ctx, void *arg )
Ondřej Kuzník's avatar
Ondřej Kuzník committed
339
{
340
    Connection *c = arg;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
341
    BerElement *ber;
342
    ber_int_t msgid;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
343

344
    CONNECTION_LOCK(c);
Ondřej Kuzník's avatar
Ondřej Kuzník committed
345
346
    c->c_pdu_cb = upstream_bind_cb;
    CONNECTION_UNLOCK_INCREF(c);
Ondřej Kuzník's avatar
Ondřej Kuzník committed
347

Ondřej Kuzník's avatar
Ondřej Kuzník committed
348
349
350
351
352
    ldap_pvt_thread_mutex_lock( &c->c_io_mutex );
    ber = c->c_pendingber;
    if ( ber == NULL && (ber = ber_alloc()) == NULL ) {
        ldap_pvt_thread_mutex_unlock( &c->c_io_mutex );
        CONNECTION_LOCK_DESTROY(c);
353
        return NULL;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
354
    }
Ondřej Kuzník's avatar
Ondřej Kuzník committed
355
    c->c_pendingber = ber;
356
357
    msgid = c->c_next_msgid++;

358
    if ( bindconf.sb_method == LDAP_AUTH_SIMPLE ) {
359
        /* simple bind */
360
        ber_printf( ber, "{it{iOtON}}",
361
                msgid, LDAP_REQ_BIND, LDAP_VERSION3,
362
363
                &bindconf.sb_binddn, LDAP_AUTH_SIMPLE,
                &bindconf.sb_cred );
364
365
366

#ifdef HAVE_CYRUS_SASL
    } else {
367
368
369
        BerValue cred = BER_BVNULL;
        ber_printf( ber, "{it{iOt{OON}N}}",
                msgid, LDAP_REQ_BIND, LDAP_VERSION3,
370
371
                &bindconf.sb_binddn, LDAP_AUTH_SASL,
                &bindconf.sb_saslmech, BER_BV_OPTIONAL( &cred ) );
372
373
374
375
#endif /* HAVE_CYRUS_SASL */
    }
    ldap_pvt_thread_mutex_unlock( &c->c_io_mutex );

376
    connection_write_cb( -1, 0, c );
377

378
    CONNECTION_LOCK_DECREF(c);
379
380
    c->c_read_timeout = lload_timeout_net;
    event_add( c->c_read_event, c->c_read_timeout );
381
    CONNECTION_UNLOCK_OR_DESTROY(c);
382

383
384
385
    return NULL;
}

Ondřej Kuzník's avatar
Ondřej Kuzník committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
 * The backend is already locked when entering the function.
 */
static int
upstream_finish( Connection *c )
{
    Backend *b = c->c_private;
    int is_bindconn = 0, rc = 0;

    c->c_pdu_cb = handle_one_response;

    /* Unless we are configured to use the VC exop, consider allocating the
     * connection into the bind conn pool. Start off by allocating one for
     * general use, then one for binds, then we start filling up the general
     * connection pool, finally the bind pool */
    if (
#ifdef LDAP_API_FEATURE_VERIFY_CREDENTIALS
            !(lload_features & LLOAD_FEATURE_VC) &&
#endif /* LDAP_API_FEATURE_VERIFY_CREDENTIALS */
            b->b_active && b->b_numbindconns ) {
        if ( !b->b_bindavail ) {
            is_bindconn = 1;
        } else if ( b->b_active >= b->b_numconns &&
                b->b_bindavail < b->b_numbindconns ) {
            is_bindconn = 1;
        }
    }

    if ( is_bindconn ) {
        LDAP_CIRCLEQ_REMOVE( &b->b_preparing, c, c_next );
416
417
        c->c_state = LLOAD_C_READY;
        c->c_type = LLOAD_C_BIND;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
418
419
420
        b->b_bindavail++;
        b->b_opening--;
        b->b_failed = 0;
421
422
423
424
425
426
427
        if ( b->b_last_bindconn ) {
            LDAP_CIRCLEQ_INSERT_AFTER(
                    &b->b_bindconns, b->b_last_bindconn, c, c_next );
        } else {
            LDAP_CIRCLEQ_INSERT_HEAD( &b->b_bindconns, c, c_next );
        }
        b->b_last_bindconn = c;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
428
429
    } else if ( bindconf.sb_method == LDAP_AUTH_NONE ) {
        LDAP_CIRCLEQ_REMOVE( &b->b_preparing, c, c_next );
430
431
        c->c_state = LLOAD_C_READY;
        c->c_type = LLOAD_C_OPEN;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
432
433
434
        b->b_active++;
        b->b_opening--;
        b->b_failed = 0;
435
436
437
438
439
440
        if ( b->b_last_conn ) {
            LDAP_CIRCLEQ_INSERT_AFTER( &b->b_conns, b->b_last_conn, c, c_next );
        } else {
            LDAP_CIRCLEQ_INSERT_HEAD( &b->b_conns, c, c_next );
        }
        b->b_last_conn = c;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
441
442
443
444
445
446
447
448
449
450
451
452
    } else {
        rc = 1;
        ldap_pvt_thread_pool_submit( &connection_pool, upstream_bind, c );
    }

    Debug( LDAP_DEBUG_CONNS, "upstream_finish: "
            "%sconnection connid=%lu is%s ready for use\n",
            is_bindconn ? "bind " : "", c->c_connid, rc ? " almost" : "" );

    return rc;
}

Ondřej Kuzník's avatar
Ondřej Kuzník committed
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
static void
upstream_tls_handshake_cb( evutil_socket_t s, short what, void *arg )
{
    Connection *c = arg;
    Backend *b;
    int rc = LDAP_SUCCESS;

    CONNECTION_LOCK(c);
    if ( what & EV_TIMEOUT ) {
        Debug( LDAP_DEBUG_CONNS, "upstream_tls_handshake_cb: "
                "connid=%lu, timeout reached, destroying\n",
                c->c_connid );
        goto fail;
    }
    b = c->c_private;

469
    rc = ldap_pvt_tls_connect( slap_tls_backend_ld, c->c_sb, b->b_host );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
    if ( rc < 0 ) {
        goto fail;
    }

    if ( rc == 0 ) {
        struct event_base *base = event_get_base( c->c_read_event );

        /*
         * We're finished, replace the callbacks
         *
         * This is deadlock-safe, since both share the same base - the one
         * that's just running us.
         */
        event_del( c->c_read_event );
        event_del( c->c_write_event );

486
        c->c_read_timeout = NULL;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
487
488
        event_assign( c->c_read_event, base, c->c_fd, EV_READ|EV_PERSIST,
                connection_read_cb, c );
489
        event_add( c->c_read_event, c->c_read_timeout );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608

        event_assign( c->c_write_event, base, c->c_fd, EV_WRITE,
                connection_write_cb, c );
        Debug( LDAP_DEBUG_CONNS, "upstream_tls_handshake_cb: "
                "connid=%lu finished\n",
                c->c_connid );
        c->c_is_tls = LLOAD_TLS_ESTABLISHED;

        CONNECTION_UNLOCK_INCREF(c);
        ldap_pvt_thread_mutex_lock( &b->b_mutex );
        CONNECTION_LOCK_DECREF(c);

        rc = upstream_finish( c );

        ldap_pvt_thread_mutex_unlock( &b->b_mutex );

        if ( rc == LDAP_SUCCESS ) {
            backend_retry( b );
        }
    } else if ( ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_NEEDS_WRITE, NULL ) ) {
        event_add( c->c_write_event, lload_write_timeout );
        Debug( LDAP_DEBUG_CONNS, "upstream_tls_handshake_cb: "
                "connid=%lu need write rc=%d\n",
                c->c_connid, rc );
    }
    CONNECTION_UNLOCK_OR_DESTROY(c);
    return;

fail:
    Debug( LDAP_DEBUG_CONNS, "upstream_tls_handshake_cb: "
            "connid=%lu failed rc=%d\n",
            c->c_connid, rc );
    CONNECTION_DESTROY(c);
}

static int
upstream_starttls( Connection *c )
{
    BerValue matcheddn, message, responseOid,
             startTLSOid = BER_BVC(LDAP_EXOP_START_TLS);
    BerElement *ber = c->c_currentber;
    struct event_base *base;
    ber_int_t msgid, result;
    ber_tag_t tag;

    c->c_currentber = NULL;

    if ( ber_scanf( ber, "it", &msgid, &tag ) == LBER_ERROR ) {
        Debug( LDAP_DEBUG_ANY, "upstream_starttls: "
                "protocol violation from server\n" );
        goto fail;
    }

    if ( msgid != ( c->c_next_msgid - 1 ) || tag != LDAP_RES_EXTENDED ) {
        Debug( LDAP_DEBUG_ANY, "upstream_starttls: "
                "unexpected %s from server, msgid=%d\n",
                slap_msgtype2str( tag ), msgid );
        goto fail;
    }

    if ( ber_scanf( ber, "{emm}", &result, &matcheddn, &message ) ==
                 LBER_ERROR ) {
        Debug( LDAP_DEBUG_ANY, "upstream_starttls: "
                "protocol violation on StartTLS response\n" );
        goto fail;
    }

    if ( (tag = ber_get_tag( ber )) != LBER_DEFAULT ) {
        if ( tag != LDAP_TAG_EXOP_RES_OID ||
                ber_scanf( ber, "{m}", &responseOid ) == LBER_DEFAULT ) {
            Debug( LDAP_DEBUG_ANY, "upstream_starttls: "
                    "protocol violation on StartTLS response\n" );
            goto fail;
        }

        if ( ber_bvcmp( &responseOid, &startTLSOid ) ) {
            Debug( LDAP_DEBUG_ANY, "upstream_starttls: "
                    "oid=%s not a StartTLS response\n",
                    responseOid.bv_val );
            goto fail;
        }
    }

    if ( result != LDAP_SUCCESS ) {
        Backend *b = c->c_private;
        int rc;

        Debug( LDAP_DEBUG_STATS, "upstream_starttls: "
                "server doesn't support StartTLS rc=%d message='%s'%s\n",
                result, message.bv_val,
                (c->c_is_tls == LLOAD_STARTTLS_OPTIONAL) ? ", ignored" : "" );
        if ( c->c_is_tls != LLOAD_STARTTLS_OPTIONAL ) {
            goto fail;
        }
        c->c_is_tls = LLOAD_CLEARTEXT;

        ber_free( ber, 1 );

        CONNECTION_UNLOCK_INCREF(c);
        ldap_pvt_thread_mutex_lock( &b->b_mutex );
        CONNECTION_LOCK_DECREF(c);

        rc = upstream_finish( c );

        ldap_pvt_thread_mutex_unlock( &b->b_mutex );

        if ( rc == LDAP_SUCCESS ) {
            backend_retry( b );
        }

        CONNECTION_UNLOCK_OR_DESTROY(c);
        return rc;
    }

    base = event_get_base( c->c_read_event );

    event_del( c->c_read_event );
    event_del( c->c_write_event );

609
    c->c_read_timeout = lload_timeout_net;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
610
611
612
613
614
    event_assign( c->c_read_event, base, c->c_fd, EV_READ|EV_PERSIST,
            upstream_tls_handshake_cb, c );
    event_assign( c->c_write_event, base, c->c_fd, EV_WRITE,
            upstream_tls_handshake_cb, c );

615
    event_add( c->c_read_event, c->c_read_timeout );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
616
617
618
619
620
621
622
623
624
625
626
627
628
    event_add( c->c_write_event, lload_write_timeout );

    CONNECTION_UNLOCK(c);

    ber_free( ber, 1 );
    return -1;

fail:
    ber_free( ber, 1 );
    CONNECTION_DESTROY(c);
    return -1;
}

629
630
631
/*
 * We must already hold b->b_mutex when called.
 */
632
633
634
635
636
637
Connection *
upstream_init( ber_socket_t s, Backend *b )
{
    Connection *c;
    struct event_base *base = slap_get_base( s );
    struct event *event;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
638
    int flags, rc = -1;
639
640
641

    assert( b != NULL );

Ondřej Kuzník's avatar
Ondřej Kuzník committed
642
    flags = (b->b_proto == LDAP_PROTO_IPC) ? CONN_IS_IPC : 0;
643
644
645
646
    if ( (c = connection_init( s, b->b_host, flags )) == NULL ) {
        return NULL;
    }

647
    c->c_private = b;
648
649
    c->c_is_tls = b->b_tls;
    c->c_pdu_cb = handle_one_response;
650

Ondřej Kuzník's avatar
Ondřej Kuzník committed
651
    LDAP_CIRCLEQ_INSERT_HEAD( &b->b_preparing, c, c_next );
652
    c->c_type = LLOAD_C_PREPARING;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
653

654
655
656
657
658
    {
        ber_len_t max = sockbuf_max_incoming_upstream;
        ber_sockbuf_ctrl( c->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );
    }

659
660
661
662
663
664
665
666
667
    event = event_new( base, s, EV_READ|EV_PERSIST, connection_read_cb, c );
    if ( !event ) {
        Debug( LDAP_DEBUG_ANY, "upstream_init: "
                "Read event could not be allocated\n" );
        goto fail;
    }
    c->c_read_event = event;

    event = event_new( base, s, EV_WRITE, connection_write_cb, c );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
668
    if ( !event ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
669
670
        Debug( LDAP_DEBUG_ANY, "upstream_init: "
                "Write event could not be allocated\n" );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
671
672
        goto fail;
    }
673
    /* We only add the write event when we have data pending */
Ondřej Kuzník's avatar
Ondřej Kuzník committed
674
675
    c->c_write_event = event;

Ondřej Kuzník's avatar
Ondřej Kuzník committed
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
    if ( c->c_is_tls == LLOAD_CLEARTEXT ) {
        rc = upstream_finish( c );
        if ( rc < 0 ) {
            goto fail;
        }
    } else if ( c->c_is_tls == LLOAD_LDAPS ) {
        event_assign( c->c_read_event, base, s, EV_READ|EV_PERSIST,
                upstream_tls_handshake_cb, c );
        event_assign( c->c_write_event, base, s, EV_WRITE,
                upstream_tls_handshake_cb, c );
        event_add( c->c_write_event, lload_write_timeout );
    } else if ( c->c_is_tls == LLOAD_STARTTLS ||
            c->c_is_tls == LLOAD_STARTTLS_OPTIONAL ) {
        BerElement *output;

        ldap_pvt_thread_mutex_lock( &c->c_io_mutex );
        if ( (output = c->c_pendingber = ber_alloc()) == NULL ) {
            ldap_pvt_thread_mutex_unlock( &c->c_io_mutex );
            goto fail;
        }
        ber_printf( output, "t{tit{ts}}", LDAP_TAG_MESSAGE,
                LDAP_TAG_MSGID, c->c_next_msgid++,
                LDAP_REQ_EXTENDED,
                LDAP_TAG_EXOP_REQ_OID, LDAP_EXOP_START_TLS );
        ldap_pvt_thread_mutex_unlock( &c->c_io_mutex );
701

Ondřej Kuzník's avatar
Ondřej Kuzník committed
702
703
704
705
706
        c->c_pdu_cb = upstream_starttls;
        CONNECTION_UNLOCK_INCREF(c);
        connection_write_cb( s, 0, c );
        CONNECTION_LOCK_DECREF(c);
    }
707
    event_add( c->c_read_event, c->c_read_timeout );
708

Ondřej Kuzník's avatar
Ondřej Kuzník committed
709
710
711
712
713
714
715
716
    c->c_destroy = upstream_destroy;
    CONNECTION_UNLOCK_OR_DESTROY(c);

    /* has upstream_finish() finished? */
    if ( rc == LDAP_SUCCESS ) {
        ldap_pvt_thread_mutex_unlock( &b->b_mutex );
        backend_retry( b );
        ldap_pvt_thread_mutex_lock( &b->b_mutex );
717
    }
Ondřej Kuzník's avatar
Ondřej Kuzník committed
718
719

    return c;
720

Ondřej Kuzník's avatar
Ondřej Kuzník committed
721
722
723
724
725
726
727
728
729
fail:
    if ( c->c_write_event ) {
        event_del( c->c_write_event );
        event_free( c->c_write_event );
    }
    if ( c->c_read_event ) {
        event_del( c->c_read_event );
        event_free( c->c_read_event );
    }
730

731
    c->c_state = LLOAD_C_INVALID;
732
733
734
    CONNECTION_DESTROY(c);
    assert( c == NULL );

Ondřej Kuzník's avatar
Ondřej Kuzník committed
735
736
737
    return NULL;
}

Ondřej Kuzník's avatar
Ondřej Kuzník committed
738
void
Ondřej Kuzník's avatar
Ondřej Kuzník committed
739
740
741
upstream_destroy( Connection *c )
{
    Backend *b = c->c_private;
742
    struct event *read_event, *write_event;
743
    TAvlnode *root;
744
    long freed, executing;
745
    enum sc_state state;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
746

747
    Debug( LDAP_DEBUG_CONNS, "upstream_destroy: "
Ondřej Kuzník's avatar
Ondřej Kuzník committed
748
            "freeing connection connid=%lu\n",
749
750
            c->c_connid );

751
    assert( c->c_state != LLOAD_C_INVALID );
752
    state = c->c_state;
753
    c->c_state = LLOAD_C_INVALID;
754

755
756
    root = c->c_ops;
    c->c_ops = NULL;
757
    executing = c->c_n_ops_executing;
758
    c->c_n_ops_executing = 0;
759

760
761
    read_event = c->c_read_event;
    write_event = c->c_write_event;
762

763
764
    CONNECTION_UNLOCK_INCREF(c);

765
    freed = tavl_free( root, (AVL_FREE)operation_lost_upstream );
766
    assert( freed == executing );
767

768
769
770
771
772
    /*
     * Avoid a deadlock:
     * event_del will block if the event is currently executing its callback,
     * that callback might be waiting to lock c->c_mutex
     */
Ondřej Kuzník's avatar
Ondřej Kuzník committed
773
774
775
    if ( read_event ) {
        event_del( read_event );
    }
776

Ondřej Kuzník's avatar
Ondřej Kuzník committed
777
778
779
    if ( write_event ) {
        event_del( write_event );
    }
Ondřej Kuzník's avatar
Ondřej Kuzník committed
780

781
    /* Remove from the backend on first pass */
782
    if ( state != LLOAD_C_CLOSING ) {
783
        ldap_pvt_thread_mutex_lock( &b->b_mutex );
784
        if ( c->c_type == LLOAD_C_PREPARING ) {
Ondřej Kuzník's avatar
Ondřej Kuzník committed
785
786
787
            LDAP_CIRCLEQ_REMOVE( &b->b_preparing, c, c_next );
            b->b_opening--;
            b->b_failed++;
788
        } else if ( c->c_type == LLOAD_C_BIND ) {
789
790
791
792
793
794
795
796
797
            if ( c == b->b_last_bindconn ) {
                Connection *prev =
                        LDAP_CIRCLEQ_LOOP_PREV( &b->b_bindconns, c, c_next );
                if ( prev == c ) {
                    b->b_last_bindconn = NULL;
                } else {
                    b->b_last_bindconn = prev;
                }
            }
798
799
800
            LDAP_CIRCLEQ_REMOVE( &b->b_bindconns, c, c_next );
            b->b_bindavail--;
        } else {
801
802
803
804
805
806
807
808
809
            if ( c == b->b_last_conn ) {
                Connection *prev =
                        LDAP_CIRCLEQ_LOOP_PREV( &b->b_conns, c, c_next );
                if ( prev == c ) {
                    b->b_last_conn = NULL;
                } else {
                    b->b_last_conn = prev;
                }
            }
810
811
812
813
814
815
            LDAP_CIRCLEQ_REMOVE( &b->b_conns, c, c_next );
            b->b_active--;
        }
        b->b_n_ops_executing -= executing;
        ldap_pvt_thread_mutex_unlock( &b->b_mutex );
        backend_retry( b );
Ondřej Kuzník's avatar
Ondřej Kuzník committed
816
    }
817

818
    CONNECTION_LOCK_DECREF(c);
Ondřej Kuzník's avatar
Ondřej Kuzník committed
819

Ondřej Kuzník's avatar
Ondřej Kuzník committed
820
821
822
823
824
825
826
827
828
829
    if ( c->c_read_event ) {
        event_free( c->c_read_event );
        c->c_read_event = NULL;
    }

    if ( c->c_write_event ) {
        event_free( c->c_write_event );
        c->c_write_event = NULL;
    }

Ondřej Kuzník's avatar
Ondřej Kuzník committed
830
831
832
833
834
835
836
    /*
     * If we attempted to destroy any operations, we might have lent a new
     * refcnt token for a thread that raced us to that, let them call us again
     * later
     */
    assert( c->c_refcnt >= 0 );
    if ( c->c_refcnt ) {
837
        c->c_state = LLOAD_C_CLOSING;
Ondřej Kuzník's avatar
Ondřej Kuzník committed
838
839
840
841
842
843
        Debug( LDAP_DEBUG_CONNS, "upstream_destroy: "
                "connid=%lu aborting with refcnt=%d\n",
                c->c_connid, c->c_refcnt );
        CONNECTION_UNLOCK(c);
        return;
    }
Ondřej Kuzník's avatar
Ondřej Kuzník committed
844
845
    connection_destroy( c );
}