kio_ldap.cpp 23.4 KB
Newer Older
Laurent Montel's avatar
Laurent Montel committed
1
/*
2
3
4
  SPDX-FileCopyrightText: 2004-2007 Szombathelyi György <gyurco@freemail.hu>

  SPDX-License-Identifier: MIT
Laurent Montel's avatar
Laurent Montel committed
5
6
7
8
9
10
11
12
13
14

*/

#include "kio_ldap.h"
#include "kldap_debug.h"

#include <kldap/ldif.h>

#include <KLocalizedString>
#include <QCoreApplication>
Laurent Montel's avatar
Laurent Montel committed
15
#include <QDebug>
Laurent Montel's avatar
Laurent Montel committed
16

Daniel Vrátil's avatar
Daniel Vrátil committed
17
18
19
#ifdef Q_OS_WIN
#include <Winsock2.h>
#else
Laurent Montel's avatar
Laurent Montel committed
20
21
#include <netdb.h>
#include <netinet/in.h>
Daniel Vrátil's avatar
Daniel Vrátil committed
22
#endif
Laurent Montel's avatar
Laurent Montel committed
23
24
25
26
27
#include <sys/stat.h>

using namespace KIO;
using namespace KLDAP;

28
29
30
31
32
33
34
// Pseudo plugin class to embed meta data
class KIOPluginForMetaData : public QObject
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.kde.kio.slave.ldap" FILE "ldap.json")
};

Laurent Montel's avatar
Laurent Montel committed
35
extern "C" {
Laurent Montel's avatar
Laurent Montel committed
36
int Q_DECL_EXPORT kdemain(int argc, char **argv);
Laurent Montel's avatar
Laurent Montel committed
37
38
39
40
41
42
43
}

/**
 * The main program.
 */
int kdemain(int argc, char **argv)
{
Laurent Montel's avatar
Laurent Montel committed
44
    QCoreApplication app(argc, argv); // needed for QSocketNotifier
Laurent Montel's avatar
Laurent Montel committed
45
46
47
48
49
    app.setApplicationName(QStringLiteral("kio_ldap"));

    qCDebug(KLDAP_LOG) << "Starting kio_ldap instance";

    if (argc != 4) {
50
        qCritical() << "Usage kio_ldap protocol pool app";
Laurent Montel's avatar
Laurent Montel committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        return -1;
    }

    // let the protocol class do its work
    LDAPProtocol slave(argv[1], argv[2], argv[3]);
    slave.dispatchLoop();

    qCDebug(KLDAP_LOG) << "Done";
    return 0;
}

/**
 * Initialize the ldap slave
 */
Laurent Montel's avatar
Laurent Montel committed
65
LDAPProtocol::LDAPProtocol(const QByteArray &protocol, const QByteArray &pool, const QByteArray &app)
Laurent Montel's avatar
Laurent Montel committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    : SlaveBase(protocol, pool, app)
{
    mConnected = false;
    mOp.setConnection(mConn);
    qCDebug(KLDAP_LOG) << "LDAPProtocol::LDAPProtocol (" << protocol << ")";
}

LDAPProtocol::~LDAPProtocol()
{
    closeConnection();
}

void LDAPProtocol::LDAPErr(int err)
{
    QString extramsg;
    if (mConnected) {
        if (err == KLDAP_SUCCESS) {
            err = mConn.ldapErrorCode();
        }
        if (err != KLDAP_SUCCESS) {
            extramsg = i18n("\nAdditional info: ") + mConn.ldapErrorString();
        }
    }
    if (err == KLDAP_SUCCESS) {
        return;
    }

Laurent Montel's avatar
Laurent Montel committed
93
    qDebug() << "error code: " << err << " msg: " << LdapConnection::errorString(err) << extramsg << "'";
Laurent Montel's avatar
Laurent Montel committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    QString msg;
    msg = mServer.url().toDisplayString();
    if (!extramsg.isEmpty()) {
        msg += extramsg;
    }

    /* FIXME: No need to close on all errors */
    closeConnection();

    switch (err) {
    /* FIXME: is it worth mapping the following error codes to kio errors?

      LDAP_OPERATIONS_ERROR
      LDAP_STRONG_AUTH_REQUIRED
      LDAP_PROTOCOL_ERROR
      LDAP_TIMELIMIT_EXCEEDED
      LDAP_SIZELIMIT_EXCEEDED
      LDAP_COMPARE_FALSE
      LDAP_COMPARE_TRUE
      LDAP_PARTIAL_RESULTS
      LDAP_NO_SUCH_ATTRIBUTE
      LDAP_UNDEFINED_TYPE
      LDAP_INAPPROPRIATE_MATCHING
      LDAP_CONSTRAINT_VIOLATION
      LDAP_INVALID_SYNTAX
      LDAP_NO_SUCH_OBJECT
      LDAP_ALIAS_PROBLEM
      LDAP_INVALID_DN_SYNTAX
      LDAP_IS_LEAF
      LDAP_ALIAS_DEREF_PROBLEM
      LDAP_INAPPROPRIATE_AUTH
      LDAP_BUSY
      LDAP_UNAVAILABLE
      LDAP_UNWILLING_TO_PERFORM
      LDAP_LOOP_DETECT
      LDAP_NAMING_VIOLATION
      LDAP_OBJECT_CLASS_VIOLATION
      LDAP_NOT_ALLOWED_ON_NONLEAF
      LDAP_NOT_ALLOWED_ON_RDN
      LDAP_NO_OBJECT_CLASS_MODS
      LDAP_OTHER
      LDAP_LOCAL_ERROR
      LDAP_ENCODING_ERROR
      LDAP_DECODING_ERROR
      LDAP_FILTER_ERROR
    */
    case KLDAP_AUTH_UNKNOWN:
    case KLDAP_INVALID_CREDENTIALS:
    case KLDAP_STRONG_AUTH_NOT_SUPPORTED:
143
        error(ERR_CANNOT_AUTHENTICATE, msg);
Laurent Montel's avatar
Laurent Montel committed
144
145
146
147
148
149
150
151
152
        break;
    case KLDAP_ALREADY_EXISTS:
        error(ERR_FILE_ALREADY_EXIST, msg);
        break;
    case KLDAP_INSUFFICIENT_ACCESS:
        error(ERR_ACCESS_DENIED, msg);
        break;
    case KLDAP_CONNECT_ERROR:
    case KLDAP_SERVER_DOWN:
153
        error(ERR_CANNOT_CONNECT, msg);
Laurent Montel's avatar
Laurent Montel committed
154
155
156
157
158
159
160
161
162
163
164
165
166
        break;
    case KLDAP_TIMEOUT:
        error(ERR_SERVER_TIMEOUT, msg);
        break;
    case KLDAP_PARAM_ERROR:
        error(ERR_INTERNAL, msg);
        break;
    case KLDAP_NO_MEMORY:
        error(ERR_OUT_OF_MEMORY, msg);
        break;

    default:
        error(ERR_SLAVE_DEFINED,
Laurent Montel's avatar
Laurent Montel committed
167
              i18n("LDAP server returned the error: %1 %2\nThe LDAP URL was: %3", LdapConnection::errorString(err), extramsg, mServer.url().toDisplayString()));
Laurent Montel's avatar
Laurent Montel committed
168
169
170
    }
}

Laurent Montel's avatar
Laurent Montel committed
171
void LDAPProtocol::controlsFromMetaData(LdapControls &serverctrls, LdapControls &clientctrls)
Laurent Montel's avatar
Laurent Montel committed
172
173
174
175
176
177
178
179
{
    QString oid;
    bool critical;
    QByteArray value;
    int i = 0;
    while (hasMetaData(QStringLiteral("SERVER_CTRL%1").arg(i))) {
        QByteArray val = metaData(QStringLiteral("SERVER_CTRL%1").arg(i)).toUtf8();
        Ldif::splitControl(val, oid, critical, value);
Laurent Montel's avatar
Laurent Montel committed
180
181
        qCDebug(KLDAP_LOG) << "server ctrl #" << i << " value: " << val << " oid: " << oid << " critical: " << critical
                           << " value: " << QString::fromUtf8(value.constData(), value.size());
Laurent Montel's avatar
Laurent Montel committed
182
183
184
185
186
187
188
189
        LdapControl ctrl(oid, val, critical);
        serverctrls.append(ctrl);
        i++;
    }
    i = 0;
    while (hasMetaData(QStringLiteral("CLIENT_CTRL%1").arg(i))) {
        QByteArray val = metaData(QStringLiteral("CLIENT_CTRL%1").arg(i)).toUtf8();
        Ldif::splitControl(val, oid, critical, value);
Laurent Montel's avatar
Laurent Montel committed
190
191
        qCDebug(KLDAP_LOG) << "client ctrl #" << i << " value: " << val << " oid: " << oid << " critical: " << critical
                           << " value: " << QString::fromUtf8(value.constData(), value.size());
Laurent Montel's avatar
Laurent Montel committed
192
193
194
195
196
197
        LdapControl ctrl(oid, val, critical);
        clientctrls.append(ctrl);
        i++;
    }
}

Laurent Montel's avatar
Laurent Montel committed
198
void LDAPProtocol::LDAPEntry2UDSEntry(const LdapDN &dn, UDSEntry &entry, const LdapUrl &usrc, bool dir)
Laurent Montel's avatar
Laurent Montel committed
199
200
201
202
203
{
    int pos;
    entry.clear();
    QString name = dn.toString();
    if ((pos = name.indexOf(QLatin1Char(','))) > 0) {
Laurent Montel's avatar
Laurent Montel committed
204
        name.truncate(pos);
Laurent Montel's avatar
Laurent Montel committed
205
206
207
208
209
210
211
212
    }
    if ((pos = name.indexOf(QLatin1Char('='))) > 0) {
        name.remove(0, pos + 1);
    }
    name.replace(QLatin1Char(' '), QLatin1String("_"));
    if (!dir) {
        name += QLatin1String(".ldif");
    }
Laurent Montel's avatar
Laurent Montel committed
213
    entry.fastInsert(KIO::UDSEntry::UDS_NAME, name);
Laurent Montel's avatar
Laurent Montel committed
214
215

    // the file type
Laurent Montel's avatar
Laurent Montel committed
216
    entry.fastInsert(KIO::UDSEntry::UDS_FILE_TYPE, dir ? S_IFDIR : S_IFREG);
Laurent Montel's avatar
Laurent Montel committed
217
218
219

    // the mimetype
    if (!dir) {
Laurent Montel's avatar
Laurent Montel committed
220
        entry.fastInsert(KIO::UDSEntry::UDS_MIME_TYPE, QStringLiteral("text/plain"));
Laurent Montel's avatar
Laurent Montel committed
221
222
    }

Laurent Montel's avatar
Laurent Montel committed
223
    entry.fastInsert(KIO::UDSEntry::UDS_ACCESS, dir ? 0500 : 0400);
Laurent Montel's avatar
Laurent Montel committed
224
225
226
227
228

    // the url
    LdapUrl url = usrc;
    url.setPath(QLatin1Char('/') + dn.toString());
    url.setScope(dir ? LdapUrl::One : LdapUrl::Base);
Laurent Montel's avatar
Laurent Montel committed
229
    entry.fastInsert(KIO::UDSEntry::UDS_URL, url.toDisplayString());
Laurent Montel's avatar
Laurent Montel committed
230
231
232
233
234
235
236
237
}

void LDAPProtocol::changeCheck(const LdapUrl &url)
{
    LdapServer server;
    server.setUrl(url);

    if (mConnected) {
Laurent Montel's avatar
Laurent Montel committed
238
239
240
241
        if (server.host() != mServer.host() || server.port() != mServer.port() || server.baseDn() != mServer.baseDn() || server.user() != mServer.user()
            || server.bindDn() != mServer.bindDn() || server.realm() != mServer.realm() || server.password() != mServer.password()
            || server.timeLimit() != mServer.timeLimit() || server.sizeLimit() != mServer.sizeLimit() || server.version() != mServer.version()
            || server.security() != mServer.security() || server.auth() != mServer.auth() || server.mech() != mServer.mech()) {
Laurent Montel's avatar
Laurent Montel committed
242
243
244
245
246
247
248
249
250
251
            closeConnection();
            mServer = server;
            openConnection();
        }
    } else {
        mServer = server;
        openConnection();
    }
}

Laurent Montel's avatar
Laurent Montel committed
252
void LDAPProtocol::setHost(const QString &host, quint16 port, const QString &user, const QString &password)
Laurent Montel's avatar
Laurent Montel committed
253
{
Laurent Montel's avatar
Laurent Montel committed
254
    if (mServer.host() != host || mServer.port() != port || mServer.user() != user || mServer.password() != password) {
Laurent Montel's avatar
Laurent Montel committed
255
256
257
258
259
260
261
262
        closeConnection();
    }

    mServer.host() = host;
    if (port > 0) {
        mServer.setPort(port);
    } else {
        struct servent *pse;
263
        if ((pse = getservbyname(mProtocol.constData(), "tcp")) == nullptr) {
Laurent Montel's avatar
Laurent Montel committed
264
265
266
267
268
269
270
271
272
273
274
275
            if (mProtocol == "ldaps") {
                mServer.setPort(636);
            } else {
                mServer.setPort(389);
            }
        } else {
            mServer.setPort(ntohs(pse->s_port));
        }
    }
    mServer.setUser(user);
    mServer.setPassword(password);

Laurent Montel's avatar
Laurent Montel committed
276
    qCDebug(KLDAP_LOG) << "setHost: " << host << " port: " << port << " user: " << user << " pass: [protected]";
Laurent Montel's avatar
Laurent Montel committed
277
278
279
280
281
282
283
284
285
286
}

void LDAPProtocol::openConnection()
{
    if (mConnected) {
        return;
    }

    mConn.setServer(mServer);
    if (mConn.connect() != 0) {
287
        error(ERR_CANNOT_CONNECT, mConn.connectionError());
Laurent Montel's avatar
Laurent Montel committed
288
289
290
291
292
293
294
295
296
297
298
        return;
    }

    mConnected = true;

    AuthInfo info;
    info.url.setScheme(QLatin1String(mProtocol));
    info.url.setHost(mServer.host());
    info.url.setPort(mServer.port());
    info.url.setUserName(mServer.user());
    info.caption = i18n("LDAP Login");
Laurent Montel's avatar
Laurent Montel committed
299
    info.comment = QString::fromLatin1(mProtocol) + QLatin1String("://") + mServer.host() + QLatin1Char(':') + QString::number(mServer.port());
Laurent Montel's avatar
Laurent Montel committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    info.commentLabel = i18n("site:");
    info.username = mServer.auth() == LdapServer::SASL ? mServer.user() : mServer.bindDn();
    info.password = mServer.password();
    info.keepPassword = true;
    bool cached = checkCachedAuthentication(info);

    bool firstauth = true;
    int retval;

    while (true) {
        retval = mOp.bind_s();
        if (retval == 0) {
            qCDebug(KLDAP_LOG) << "connected!";
            connected();
            return;
        }
Laurent Montel's avatar
Laurent Montel committed
316
        if (retval == KLDAP_INVALID_CREDENTIALS || retval == KLDAP_INSUFFICIENT_ACCESS || retval == KLDAP_INAPPROPRIATE_AUTH
Laurent Montel's avatar
Laurent Montel committed
317
            || retval == KLDAP_UNWILLING_TO_PERFORM) {
Laurent Montel's avatar
Laurent Montel committed
318
319
320
321
322
323
324
325
326
327
            if (firstauth && cached) {
                if (mServer.auth() == LdapServer::SASL) {
                    mServer.setUser(info.username);
                } else {
                    mServer.setBindDn(info.username);
                }
                mServer.setPassword(info.password);
                mConn.setServer(mServer);
                cached = false;
            } else {
Laurent Montel's avatar
Laurent Montel committed
328
                const int errorCode = firstauth ? openPasswordDialogV2(info) : openPasswordDialogV2(info, i18n("Invalid authorization information."));
329
                if (!errorCode) {
Laurent Montel's avatar
Laurent Montel committed
330
                    if (info.keepPassword) { // user asked password be save/remembered
331
332
333
334
335
336
337
338
                        cacheAuthentication(info);
                    }
                } else {
                    if (errorCode == ERR_USER_CANCELED) {
                        error(ERR_USER_CANCELED, i18n("LDAP connection canceled."));
                    } else {
                        error(errorCode, QString());
                    }
Laurent Montel's avatar
Laurent Montel committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
                    closeConnection();
                    return;
                }
                if (mServer.auth() == LdapServer::SASL) {
                    mServer.setUser(info.username);
                } else {
                    mServer.setBindDn(info.username);
                }
                mServer.setPassword(info.password);
                firstauth = false;
                mConn.setServer(mServer);
            }
        } else {
            LDAPErr(retval);
            closeConnection();
            return;
        }
    }
}

void LDAPProtocol::closeConnection()
{
    if (mConnected) {
        mConn.close();
    }
    mConnected = false;

    qCDebug(KLDAP_LOG) << "connection closed!";
}

/**
 * Get the information contained in the URL.
 */
void LDAPProtocol::get(const QUrl &_url)
{
    qCDebug(KLDAP_LOG) << "get(" << _url << ")";

    LdapUrl usrc(_url);
    int ret, id;

    changeCheck(usrc);
    if (!mConnected) {
        return;
    }

    LdapControls serverctrls, clientctrls;
    controlsFromMetaData(serverctrls, clientctrls);
    if (mServer.pageSize()) {
        LdapControls ctrls = serverctrls;
        ctrls.append(LdapControl::createPageControl(mServer.pageSize()));
        qCDebug(KLDAP_LOG) << "page size: " << mServer.pageSize();
        mOp.setServerControls(ctrls);
    } else {
        mOp.setServerControls(serverctrls);
    }
    mOp.setClientControls(clientctrls);

    if ((id = mOp.search(usrc.dn(), usrc.scope(), usrc.filter(), usrc.attributes())) == -1) {
        LDAPErr();
        return;
    }

    // tell the mimetype
    mimeType(QStringLiteral("text/plain"));
    // collect the result
Laurent Montel's avatar
Laurent Montel committed
404
    // QByteArray result;
Laurent Montel's avatar
Laurent Montel committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
    filesize_t processed_size = 0;

    while (true) {
        ret = mOp.waitForResult(id, -1);
        if (ret == -1 || mConn.ldapErrorCode() != KLDAP_SUCCESS) {
            LDAPErr();
            return;
        }
        qCDebug(KLDAP_LOG) << " ldap_result: " << ret;
        if (ret == LdapOperation::RES_SEARCH_RESULT) {
            if (mServer.pageSize()) {
                QByteArray cookie;
                int estsize = -1;
                for (int i = 0; i < mOp.controls().count(); ++i) {
                    qCDebug(KLDAP_LOG) << " control oid: " << mOp.controls().at(i).oid();
                    estsize = mOp.controls().at(i).parsePageControl(cookie);
                    if (estsize != -1) {
                        break;
                    }
                }
                qCDebug(KLDAP_LOG) << " estimated size: " << estsize;
                if (estsize != -1 && !cookie.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
427
                    LdapControls ctrls{serverctrls}; // clazy:exclude=container-inside-loop
Laurent Montel's avatar
Laurent Montel committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
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
                    qCDebug(KLDAP_LOG) << "page size: " << mServer.pageSize() << " estimated size: " << estsize;
                    ctrls.append(LdapControl::createPageControl(mServer.pageSize(), cookie));
                    mOp.setServerControls(ctrls);
                    if ((id = mOp.search(usrc.dn(), usrc.scope(), usrc.filter(), usrc.attributes())) == -1) {
                        LDAPErr();
                        return;
                    }
                    continue;
                }
            }
            break;
        }
        if (ret != LdapOperation::RES_SEARCH_ENTRY) {
            continue;
        }

        QByteArray entry = mOp.object().toString().toUtf8() + '\n';
        processed_size += entry.size();
        data(entry);
        processedSize(processed_size);
    }

    totalSize(processed_size);

    // tell we are finished
    data(QByteArray());
    finished();
}

/**
 * Test if the url contains a directory or a file.
 */
void LDAPProtocol::stat(const QUrl &_url)
{
    qCDebug(KLDAP_LOG) << "stat(" << _url << ")";

    QStringList att, saveatt;
    LdapUrl usrc(_url);
    int ret, id;

    changeCheck(usrc);
    if (!mConnected) {
        return;
    }

    // look how many entries match
    saveatt = usrc.attributes();
    att.append(QStringLiteral("dn"));

    if ((id = mOp.search(usrc.dn(), usrc.scope(), usrc.filter(), att)) == -1) {
        LDAPErr();
        return;
    }

    qCDebug(KLDAP_LOG) << "stat() getting result";
    do {
        ret = mOp.waitForResult(id, -1);
        if (ret == -1 || mConn.ldapErrorCode() != KLDAP_SUCCESS) {
            LDAPErr();
            return;
        }
        if (ret == LdapOperation::RES_SEARCH_RESULT) {
            error(ERR_DOES_NOT_EXIST, _url.toDisplayString());
            return;
        }
    } while (ret != LdapOperation::RES_SEARCH_ENTRY);

    mOp.abandon(id);

    usrc.setAttributes(saveatt);

    UDSEntry uds;
    bool critical;
    LDAPEntry2UDSEntry(usrc.dn(), uds, usrc, usrc.extension(QStringLiteral("x-dir"), critical) != QLatin1String("base"));

    statEntry(uds);
    // we are done
    finished();
}

/**
 * Deletes one entry;
 */
void LDAPProtocol::del(const QUrl &_url, bool)
{
    qCDebug(KLDAP_LOG) << "del(" << _url << ")";

    LdapUrl usrc(_url);
    int id, ret;

    changeCheck(usrc);
    if (!mConnected) {
        return;
    }

    LdapControls serverctrls, clientctrls;
    controlsFromMetaData(serverctrls, clientctrls);
    mOp.setServerControls(serverctrls);
    mOp.setClientControls(clientctrls);

    qCDebug(KLDAP_LOG) << " del: " << usrc.dn().toString().toUtf8();

    if ((id = mOp.del(usrc.dn())) == -1) {
        LDAPErr();
        return;
    }
    ret = mOp.waitForResult(id, -1);
    if (ret == -1 || mConn.ldapErrorCode() != KLDAP_SUCCESS) {
        LDAPErr();
        return;
    }

    finished();
}

void LDAPProtocol::put(const QUrl &_url, int, KIO::JobFlags flags)
{
    qCDebug(KLDAP_LOG) << "put(" << _url << ")";

    LdapUrl usrc(_url);

    changeCheck(usrc);
    if (!mConnected) {
        return;
    }

    LdapControls serverctrls, clientctrls;
    controlsFromMetaData(serverctrls, clientctrls);
    mOp.setServerControls(serverctrls);
    mOp.setClientControls(clientctrls);

    LdapObject addObject;
    LdapOperation::ModOps modops;
    QByteArray buffer;
    int result = 0;
    Ldif::ParseValue ret;
    Ldif ldif;
    ret = Ldif::MoreData;
    int ldaperr;

    do {
        if (ret == Ldif::MoreData) {
            dataReq(); // Request for data
            result = readData(buffer);
            ldif.setLdif(buffer);
        }
        if (result < 0) {
Laurent Montel's avatar
Laurent Montel committed
575
            // error
Laurent Montel's avatar
Laurent Montel committed
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
            return;
        }
        if (result == 0) {
            qCDebug(KLDAP_LOG) << "EOF!";
            ldif.endLdif();
        }
        do {
            ret = ldif.nextItem();
            qCDebug(KLDAP_LOG) << "nextitem: " << ret;

            switch (ret) {
            case Ldif::None:
            case Ldif::NewEntry:
            case Ldif::MoreData:
                break;
            case Ldif::EndEntry:
                ldaperr = KLDAP_SUCCESS;
                switch (ldif.entryType()) {
                case Ldif::Entry_None:
                    error(ERR_INTERNAL, i18n("The Ldif parser failed."));
                    return;
                case Ldif::Entry_Del:
                    qCDebug(KLDAP_LOG) << "kio_ldap_del";
                    ldaperr = mOp.del_s(ldif.dn());
                    break;
                case Ldif::Entry_Modrdn:
Laurent Montel's avatar
Laurent Montel committed
602
603
604
                    qCDebug(KLDAP_LOG) << "kio_ldap_modrdn olddn:" << ldif.dn().toString() << " newRdn: " << ldif.newRdn()
                                       << " newSuperior: " << ldif.newSuperior() << " deloldrdn: " << ldif.delOldRdn();
                    ldaperr = mOp.rename_s(ldif.dn(), ldif.newRdn(), ldif.newSuperior(), ldif.delOldRdn());
Laurent Montel's avatar
Laurent Montel committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
                    break;
                case Ldif::Entry_Mod:
                    qCDebug(KLDAP_LOG) << "kio_ldap_mod";
                    ldaperr = mOp.modify_s(ldif.dn(), modops);
                    modops.clear();
                    break;
                case Ldif::Entry_Add:
                    qCDebug(KLDAP_LOG) << "kio_ldap_add " << ldif.dn().toString();
                    addObject.setDn(ldif.dn());
                    ldaperr = mOp.add_s(addObject);
                    if (ldaperr == KLDAP_ALREADY_EXISTS && (flags & KIO::Overwrite)) {
                        qCDebug(KLDAP_LOG) << ldif.dn().toString() << " already exists, delete first";
                        ldaperr = mOp.del_s(ldif.dn());
                        if (ldaperr == KLDAP_SUCCESS) {
                            ldaperr = mOp.add_s(addObject);
                        }
                    }
                    addObject.clear();
                    break;
                }
                if (ldaperr != KLDAP_SUCCESS) {
                    qCDebug(KLDAP_LOG) << "put ldap error: " << ldaperr;
                    LDAPErr(ldaperr);
                    return;
                }
                break;
            case Ldif::Item:
                switch (ldif.entryType()) {
Laurent Montel's avatar
Laurent Montel committed
633
                case Ldif::Entry_Mod: {
Laurent Montel's avatar
Laurent Montel committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
                    LdapOperation::ModOp op;
                    op.type = LdapOperation::Mod_None;
                    switch (ldif.modType()) {
                    case Ldif::Mod_None:
                        op.type = LdapOperation::Mod_None;
                        break;
                    case Ldif::Mod_Add:
                        op.type = LdapOperation::Mod_Add;
                        break;
                    case Ldif::Mod_Replace:
                        op.type = LdapOperation::Mod_Replace;
                        break;
                    case Ldif::Mod_Del:
                        op.type = LdapOperation::Mod_Del;
                        break;
                    }
                    op.attr = ldif.attr();
                    if (!ldif.value().isNull()) {
                        op.values.append(ldif.value());
                    }
                    modops.append(op);
                    break;
                }
                case Ldif::Entry_Add:
Laurent Montel's avatar
Laurent Montel committed
658
                    if (!ldif.value().isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
659
660
661
662
663
664
665
666
                        addObject.addValue(ldif.attr(), ldif.value());
                    }
                    break;
                default:
                    error(ERR_INTERNAL, i18n("The Ldif parser failed."));
                    return;
                }
                break;
Laurent Montel's avatar
Laurent Montel committed
667
            case Ldif::Control: {
Laurent Montel's avatar
Laurent Montel committed
668
669
670
671
672
673
674
                LdapControl control;
                control.setControl(ldif.oid(), ldif.value(), ldif.isCritical());
                serverctrls.append(control);
                mOp.setServerControls(serverctrls);
                break;
            }
            case Ldif::Err:
Laurent Montel's avatar
Laurent Montel committed
675
                error(ERR_SLAVE_DEFINED, i18n("Invalid Ldif file in line %1.", ldif.lineNumber()));
Laurent Montel's avatar
Laurent Montel committed
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
                return;
            }
        } while (ret != Ldif::MoreData);
    } while (result > 0);

    finished();
}

/**
 * List the contents of a directory.
 */
void LDAPProtocol::listDir(const QUrl &_url)
{
    int ret, ret2, id, id2;
    unsigned long total = 0;
    QStringList att, saveatt;
    LdapUrl usrc(_url), usrc2;
    bool critical = true;
    bool isSub = (usrc.extension(QStringLiteral("x-dir"), critical) == QLatin1String("sub"));

Laurent Montel's avatar
Laurent Montel committed
696
    qCDebug(KLDAP_LOG) << "listDir(" << _url << ")";
Laurent Montel's avatar
Laurent Montel committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742

    changeCheck(usrc);
    if (!mConnected) {
        return;
    }
    usrc2 = usrc;

    saveatt = usrc.attributes();
    // look up the entries
    if (isSub) {
        att.append(QStringLiteral("dn"));
        usrc.setAttributes(att);
    }
    if (_url.query().isEmpty()) {
        usrc.setScope(LdapUrl::One);
    }

    if ((id = mOp.search(usrc.dn(), usrc.scope(), usrc.filter(), usrc.attributes())) == -1) {
        LDAPErr();
        return;
    }

    usrc.setAttributes(QStringList() << QLatin1String(""));
    usrc.setExtension(QStringLiteral("x-dir"), QStringLiteral("base"));
    // publish the results
    UDSEntry uds;

    while (true) {
        ret = mOp.waitForResult(id, -1);
        if (ret == -1 || mConn.ldapErrorCode() != KLDAP_SUCCESS) {
            LDAPErr();
            return;
        }
        if (ret == LdapOperation::RES_SEARCH_RESULT) {
            break;
        }
        if (ret != LdapOperation::RES_SEARCH_ENTRY) {
            continue;
        }
        qCDebug(KLDAP_LOG) << " ldap_result: " << ret;

        total++;
        uds.clear();

        LDAPEntry2UDSEntry(mOp.object().dn(), uds, usrc);
        listEntry(uds);
Laurent Montel's avatar
Laurent Montel committed
743
        //      processedSize( total );
Laurent Montel's avatar
Laurent Montel committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
        qCDebug(KLDAP_LOG) << " total: " << total << " " << usrc.toDisplayString();

        // publish the sub-directories (if dirmode==sub)
        if (isSub) {
            LdapDN dn = mOp.object().dn();
            usrc2.setDn(dn);
            usrc2.setScope(LdapUrl::One);
            usrc2.setAttributes(saveatt);
            usrc2.setFilter(usrc.filter());
            qCDebug(KLDAP_LOG) << "search2 " << dn.toString();
            if ((id2 = mOp.search(dn, LdapUrl::One, QString(), att)) != -1) {
                while (true) {
                    qCDebug(KLDAP_LOG) << " next result ";
                    ret2 = mOp.waitForResult(id2, -1);
                    if (ret2 == -1 || ret2 == LdapOperation::RES_SEARCH_RESULT) {
                        break;
                    }
                    if (ret2 == LdapOperation::RES_SEARCH_ENTRY) {
                        LDAPEntry2UDSEntry(dn, uds, usrc2, true);
                        listEntry(uds);
                        total++;
                        mOp.abandon(id2);
                        break;
                    }
                }
            }
        }
    }

Laurent Montel's avatar
Laurent Montel committed
773
    //  totalSize( total );
Laurent Montel's avatar
Laurent Montel committed
774
775
776
777
778

    uds.clear();
    // we are done
    finished();
}
779
780

#include "kio_ldap.moc"