server.cpp 36 KB
Newer Older
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
27
28
29
30
31
32
33
34
/*****************************************************************
ksmserver - the KDE session management server

Copyright 2000 Matthias Ettrich <ettrich@kde.org>
Copyright 2005 Lubos Lunak <l.lunak@kde.org>

relatively small extensions by Oswald Buddenhagen <ob6@inf.tu-dresden.de>

some code taken from the dcopserver (part of the KDE libraries), which is
Copyright 1999 Matthias Ettrich <ettrich@kde.org>
Copyright 1999 Preston Brown <pbrown@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include "server.h"
#include "global.h"
#include "client.h"
Hrvoje Senjan's avatar
Hrvoje Senjan committed
35
#include "ksmserver_debug.h"
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "ksmserverinterfaceadaptor.h"
#include "klocalizedstring.h"
#include "kglobalaccel.h"

#include <config-workspace.h>
#include <config-unix.h> // HAVE_LIMITS_H
#include <config-ksmserver.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/socket.h>
#include <sys/un.h>

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>

#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif

#include <QFile>
#include <QPushButton>
#include <QRegExp>
69
#include <QDBusConnection>
70
#include <QDBusMessage>
71
72
#include <QSocketNotifier>
#include <QStandardPaths>
73
74
#include <QDebug>
#include <QAction>
Laurent Montel's avatar
Laurent Montel committed
75
#include <QApplication>
76
77
78
79

#include <kactioncollection.h>
#include <kauthorized.h>
#include <kconfig.h>
80
#include <KSharedConfig>
81
#include <kdesktopfile.h>
82
#include <QTemporaryFile>
83
84
85
86
#include <kconfiggroup.h>
#include <kprocess.h>
#include <kshell.h>

87
#include <KScreenLocker/KsldApp>
88
89
90
91
92
93
94

#include <kdisplaymanager.h>
#include <QX11Info>
#include <krandom.h>
#include <klauncher_interface.h>
#include <qstandardpaths.h>

95
#include "kscreenlocker_interface.h"
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
96

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
97
KSMServer* the_server = nullptr;
98
99
100
101
102
103
104
105
106
107
108
109
110
111

KSMServer* KSMServer::self()
{
    return the_server;
}

/*! Utility function to execute a command on the local machine. Used
 * to restart applications.
 */
KProcess* KSMServer::startApplication( const QStringList& cmd, const QString& clientMachine,
    const QString& userId, bool wm )
{
    QStringList command = cmd;
    if ( command.isEmpty() )
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
112
        return nullptr;
113
114
    if ( !userId.isEmpty()) {
        struct passwd* pw = getpwuid( getuid());
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
115
        if( pw != nullptr && userId != QString::fromLocal8Bit( pw->pw_name )) {
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
            command.prepend( QStringLiteral("--") );
            command.prepend( userId );
            command.prepend( QStringLiteral("-u") );
            command.prepend( QStandardPaths::findExecutable(QStringLiteral("kdesu")));
        }
    }
    if ( !clientMachine.isEmpty() && clientMachine != QStringLiteral("localhost") ) {
        command.prepend( clientMachine );
        command.prepend( xonCommand ); // "xon" by default
    }

// TODO this function actually should not use KProcess at all and use klauncher (kdeinit) instead.
// Klauncher should also have support for tracking whether the launched process is still alive
// or not, so this should be redone. For now, use KProcess for wm's, as they need to be tracked,
// klauncher for the rest where ksmserver doesn't care.
    if( wm ) {
        KProcess* process = new KProcess( this );
        *process << command;
        // make it auto-delete
Laurent Montel's avatar
Laurent Montel committed
135
136
        connect(process, static_cast<void (KProcess::*)(QProcess::ProcessError)>(&KProcess::error), process, &KProcess::deleteLater);
        connect(process, static_cast<void (KProcess::*)(int, QProcess::ExitStatus)>(&KProcess::finished), process, &KProcess::deleteLater);
137
138
139
140
141
142
143
144
145
146
147
        process->start();
        return process;
    } else {
        int n = command.count();
        org::kde::KLauncher klauncher(QStringLiteral("org.kde.klauncher5"),
                                      QStringLiteral("/KLauncher"), QDBusConnection::sessionBus());
        QString app = command[0];
        QStringList argList;
        for ( int i=1; i < n; i++)
           argList.append( command[i]);
        klauncher.exec_blind(app, argList );
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
148
        return nullptr;
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    }
}

/*! Utility function to execute a command on the local machine. Used
 * to discard session data
 */
void KSMServer::executeCommand( const QStringList& command )
{
    if ( command.isEmpty() )
        return;

    KProcess::execute( command );
}

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
163
IceAuthDataEntry *authDataEntries = nullptr;
164

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
165
static QTemporaryFile *remTempFile = nullptr;
166

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
167
static IceListenObj *listenObjs = nullptr;
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
int numTransports = 0;
static bool only_local = 0;

static Bool HostBasedAuthProc ( char* /*hostname*/)
{
    if (only_local)
        return true;
    else
        return false;
}


Status KSMRegisterClientProc (
    SmsConn             /* smsConn */,
    SmPointer           managerData,
    char *              previousId
)
{
    KSMClient* client = (KSMClient*) managerData;
    client->registerClient( previousId );
    return 1;
}

void KSMInteractRequestProc (
    SmsConn             /* smsConn */,
    SmPointer           managerData,
    int                 dialogType
)
{
    the_server->interactRequest( (KSMClient*) managerData, dialogType );
}

void KSMInteractDoneProc (
    SmsConn             /* smsConn */,
    SmPointer           managerData,
    Bool                        cancelShutdown
)
{
    the_server->interactDone( (KSMClient*) managerData, cancelShutdown );
}

void KSMSaveYourselfRequestProc (
    SmsConn             smsConn ,
    SmPointer           /* managerData */,
    int                 saveType,
    Bool                shutdown,
    int                 interactStyle,
    Bool                fast,
    Bool                global
)
{
    if ( shutdown ) {
        the_server->shutdown( fast ?
                              KWorkSpace::ShutdownConfirmNo :
                              KWorkSpace::ShutdownConfirmDefault,
                              KWorkSpace::ShutdownTypeDefault,
                              KWorkSpace::ShutdownModeDefault );
    } else if ( !global ) {
        SmsSaveYourself( smsConn, saveType, false, interactStyle, fast );
        SmsSaveComplete( smsConn );
    }
    // else checkpoint only, ksmserver does not yet support this
    // mode. Will come for KDE 3.1
}

void KSMSaveYourselfPhase2RequestProc (
    SmsConn             /* smsConn */,
    SmPointer           managerData
)
{
    the_server->phase2Request( (KSMClient*) managerData );
}

void KSMSaveYourselfDoneProc (
    SmsConn             /* smsConn */,
    SmPointer           managerData,
    Bool                success
)
{
    the_server->saveYourselfDone( (KSMClient*) managerData, success );
}

void KSMCloseConnectionProc (
    SmsConn             smsConn,
    SmPointer           managerData,
    int                 count,
    char **             reasonMsgs
)
{
    the_server->deleteClient( ( KSMClient* ) managerData );
    if ( count )
        SmFreeReasons( count, reasonMsgs );
    IceConn iceConn = SmsGetIceConnection( smsConn );
    SmsCleanUp( smsConn );
    IceSetShutdownNegotiation (iceConn, False);
    IceCloseConnection( iceConn );
}

void KSMSetPropertiesProc (
    SmsConn             /* smsConn */,
    SmPointer           managerData,
    int                 numProps,
    SmProp **           props
)
{
    KSMClient* client = ( KSMClient* ) managerData;
    for ( int i = 0; i < numProps; i++ ) {
        SmProp *p = client->property( props[i]->name );
        if ( p ) {
            client->properties.removeAll( p );
            SmFreeProperty( p );
        }
        client->properties.append( props[i] );
        if ( !qstrcmp( props[i]->name, SmProgram ) )
            the_server->clientSetProgram( client );
    }

    if ( numProps )
        free( props );

}

void KSMDeletePropertiesProc (
    SmsConn             /* smsConn */,
    SmPointer           managerData,
    int                 numProps,
    char **             propNames
)
{
    KSMClient* client = ( KSMClient* ) managerData;
    for ( int i = 0; i < numProps; i++ ) {
        SmProp *p = client->property( propNames[i] );
        if ( p ) {
            client->properties.removeAll( p );
            SmFreeProperty( p );
        }
    }
}

void KSMGetPropertiesProc (
    SmsConn             smsConn,
    SmPointer           managerData
)
{
    KSMClient* client = ( KSMClient* ) managerData;
    SmProp** props = new SmProp*[client->properties.count()];
    int i = 0;
    foreach( SmProp *prop, client->properties )
        props[i++] = prop;

    SmsReturnProperties( smsConn, i, props );
    delete [] props;
}


class KSMListener : public QSocketNotifier
{
public:
    KSMListener( IceListenObj obj )
        : QSocketNotifier( IceGetListenConnectionNumber( obj ),
                           QSocketNotifier::Read )
{
    listenObj = obj;
}

    IceListenObj listenObj;
};

class KSMConnection : public QSocketNotifier
{
 public:
  KSMConnection( IceConn conn )
    : QSocketNotifier( IceConnectionNumber( conn ),
                       QSocketNotifier::Read )
    {
        iceConn = conn;
    }

    IceConn iceConn;
};


/* for printing hex digits */
static void fprintfhex (FILE *fp, unsigned int len, char *cp)
{
    static const char hexchars[] = "0123456789abcdef";

    for (; len > 0; len--, cp++) {
        unsigned char s = *cp;
        putc(hexchars[s >> 4], fp);
        putc(hexchars[s & 0x0f], fp);
    }
}

/*
 * We use temporary files which contain commands to add/remove entries from
 * the .ICEauthority file.
 */
static void write_iceauth (FILE *addfp, FILE *removefp, IceAuthDataEntry *entry)
{
    fprintf (addfp,
             "add %s \"\" %s %s ",
             entry->protocol_name,
             entry->network_id,
             entry->auth_name);
    fprintfhex (addfp, entry->auth_data_length, entry->auth_data);
    fprintf (addfp, "\n");

    fprintf (removefp,
             "remove protoname=%s protodata=\"\" netid=%s authname=%s\n",
             entry->protocol_name,
             entry->network_id,
             entry->auth_name);
}


#define MAGIC_COOKIE_LEN 16

Status SetAuthentication_local (int count, IceListenObj *listenObjs)
{
    int i;
    for (i = 0; i < count; i ++) {
        char *prot = IceGetListenConnectionString(listenObjs[i]);
        if (!prot) continue;
        char *host = strchr(prot, '/');
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
393
        char *sock = nullptr;
394
395
396
397
398
399
400
401
402
        if (host) {
            *host=0;
            host++;
            sock = strchr(host, ':');
            if (sock) {
                *sock = 0;
                sock++;
            }
        }
Hrvoje Senjan's avatar
Hrvoje Senjan committed
403
        qCDebug(KSMSERVER) << "KSMServer: SetAProc_loc: conn " << (unsigned)i << ", prot=" << prot << ", file=" << sock;
404
405
406
407
408
409
410
411
412
413
414
415
        if (sock && !strcmp(prot, "local")) {
            chmod(sock, 0700);
        }
        IceSetHostBasedAuthProc (listenObjs[i], HostBasedAuthProc);
        free(prot);
    }
    return 1;
}

Status SetAuthentication (int count, IceListenObj *listenObjs,
                          IceAuthDataEntry **authDataEntries)
{
416
417
    QTemporaryFile addTempFile;
    remTempFile = new QTemporaryFile;
418
419
420
421
422

    if (!addTempFile.open() || !remTempFile->open())
        return 0;

    if ((*authDataEntries = (IceAuthDataEntry *) malloc (
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
423
                         count * 2 * sizeof (IceAuthDataEntry))) == nullptr)
424
425
426
427
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
        return 0;

    FILE *addAuthFile = fopen(QFile::encodeName(addTempFile.fileName()).constData(), "r+");
    FILE *remAuthFile = fopen(QFile::encodeName(remTempFile->fileName()).constData(), "r+");

    for (int i = 0; i < numTransports * 2; i += 2) {
        (*authDataEntries)[i].network_id =
            IceGetListenConnectionString (listenObjs[i/2]);
        (*authDataEntries)[i].protocol_name = (char *) "ICE";
        (*authDataEntries)[i].auth_name = (char *) "MIT-MAGIC-COOKIE-1";

        (*authDataEntries)[i].auth_data =
            IceGenerateMagicCookie (MAGIC_COOKIE_LEN);
        (*authDataEntries)[i].auth_data_length = MAGIC_COOKIE_LEN;

        (*authDataEntries)[i+1].network_id =
            IceGetListenConnectionString (listenObjs[i/2]);
        (*authDataEntries)[i+1].protocol_name = (char *) "XSMP";
        (*authDataEntries)[i+1].auth_name = (char *) "MIT-MAGIC-COOKIE-1";

        (*authDataEntries)[i+1].auth_data =
            IceGenerateMagicCookie (MAGIC_COOKIE_LEN);
        (*authDataEntries)[i+1].auth_data_length = MAGIC_COOKIE_LEN;

        write_iceauth (addAuthFile, remAuthFile, &(*authDataEntries)[i]);
        write_iceauth (addAuthFile, remAuthFile, &(*authDataEntries)[i+1]);

        IceSetPaAuthData (2, &(*authDataEntries)[i]);

        IceSetHostBasedAuthProc (listenObjs[i/2], HostBasedAuthProc);
    }
    fclose(addAuthFile);
    fclose(remAuthFile);

    QString iceAuth = QStandardPaths::findExecutable(QStringLiteral("iceauth"));
    if (iceAuth.isEmpty())
    {
461
        qCWarning(KSMSERVER, "KSMServer: could not find iceauth");
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
        return 0;
    }

    KProcess p;
    p << iceAuth << QStringLiteral("source") << addTempFile.fileName();
    p.execute();

    return (1);
}

/*
 * Free up authentication data.
 */
void FreeAuthenticationData(int count, IceAuthDataEntry *authDataEntries)
{
    /* Each transport has entries for ICE and XSMP */
    if (only_local)
        return;

    for (int i = 0; i < count * 2; i++) {
        free (authDataEntries[i].network_id);
        free (authDataEntries[i].auth_data);
    }

    free (authDataEntries);

    QString iceAuth = QStandardPaths::findExecutable(QStringLiteral("iceauth"));
    if (iceAuth.isEmpty())
    {
491
        qCWarning(KSMSERVER, "KSMServer: could not find iceauth");
492
493
494
495
496
497
498
499
500
501
502
        return;
    }

    if (remTempFile)
    {
        KProcess p;
        p << iceAuth << QStringLiteral("source") << remTempFile->fileName();
        p.execute();
    }

    delete remTempFile;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
503
    remTempFile = nullptr;
504
505
506
507
}

static int Xio_ErrorHandler( Display * )
{
508
    qCWarning(KSMSERVER, "ksmserver: Fatal IO error: client killed");
509
510
511
512
513

    // Don't do anything that might require the X connection
    if (the_server)
    {
       KSMServer *server = the_server;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
514
       the_server = nullptr;
515
516
517
518
519
520
521
522
523
524
525
526
527
       server->cleanUp();
       // Don't delete server!!
    }

    exit(0); // Don't report error, it's not our fault.
    return 0; // Bogus return value, notreached
}

void KSMServer::setupXIOErrorHandler()
{
    XSetIOErrorHandler(Xio_ErrorHandler);
}

528
static int wake_up_socket = -1;
529
530
531
532
533
534
535
static void sighandler(int sig)
{
    if (sig == SIGHUP) {
        signal(SIGHUP, sighandler);
        return;
    }

536
537
    char ch = 0;
    (void)::write(wake_up_socket, &ch, 1);
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
}


void KSMWatchProc ( IceConn iceConn, IcePointer client_data, Bool opening, IcePointer* watch_data)
{
    KSMServer* ds = ( KSMServer*) client_data;

    if (opening) {
        *watch_data = (IcePointer) ds->watchConnection( iceConn );
    }
    else  {
        ds->removeConnection( (KSMConnection*) *watch_data );
    }
}

static Status KSMNewClientProc ( SmsConn conn, SmPointer manager_data,
                                 unsigned long* mask_ret, SmsCallbacks* cb, char** failure_reason_ret)
{
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
556
    *failure_reason_ret = nullptr;
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

    void* client =  ((KSMServer*) manager_data )->newClient( conn );

    cb->register_client.callback = KSMRegisterClientProc;
    cb->register_client.manager_data = client;
    cb->interact_request.callback = KSMInteractRequestProc;
    cb->interact_request.manager_data = client;
    cb->interact_done.callback = KSMInteractDoneProc;
    cb->interact_done.manager_data = client;
    cb->save_yourself_request.callback = KSMSaveYourselfRequestProc;
    cb->save_yourself_request.manager_data = client;
    cb->save_yourself_phase2_request.callback = KSMSaveYourselfPhase2RequestProc;
    cb->save_yourself_phase2_request.manager_data = client;
    cb->save_yourself_done.callback = KSMSaveYourselfDoneProc;
    cb->save_yourself_done.manager_data = client;
    cb->close_connection.callback = KSMCloseConnectionProc;
    cb->close_connection.manager_data = client;
    cb->set_properties.callback = KSMSetPropertiesProc;
    cb->set_properties.manager_data = client;
    cb->delete_properties.callback = KSMDeletePropertiesProc;
    cb->delete_properties.manager_data = client;
    cb->get_properties.callback = KSMGetPropertiesProc;
    cb->get_properties.manager_data = client;

    *mask_ret = SmsRegisterClientProcMask |
                SmsInteractRequestProcMask |
                SmsInteractDoneProcMask |
                SmsSaveYourselfRequestProcMask |
                SmsSaveYourselfP2RequestProcMask |
                SmsSaveYourselfDoneProcMask |
                SmsCloseConnectionProcMask |
                SmsSetPropertiesProcMask |
                SmsDeletePropertiesProcMask |
                SmsGetPropertiesProcMask;
    return 1;
}


#ifdef HAVE__ICETRANSNOLISTEN
extern "C" int _IceTransNoListen(const char * protocol);
#endif

599
KSMServer::KSMServer( const QString& windowManager, InitFlags flags )
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
600
  : wmProcess( nullptr )
601
  , sessionGroup( QStringLiteral( "" ) )
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
602
  , logoutEffectWidget( nullptr )
603
  , sockets{ -1, -1 }
604
{
605
606
607
608
609
    if (!flags.testFlag(InitFlag::NoLockScreen)) {
        ScreenLocker::KSldApp::self()->initialize();
        if (flags.testFlag(InitFlag::ImmediateLockScreen)) {
            ScreenLocker::KSldApp::self()->lock(ScreenLocker::EstablishLock::Immediate);
        }
610
611
    }

612
613
614
615
616
617
    if(::socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sockets) != 0)
        qFatal("Could not create socket pair, error %d (%s)", errno, strerror(errno));
    wake_up_socket = sockets[0];
    QSocketNotifier* n = new QSocketNotifier(sockets[1], QSocketNotifier::Read, this);
    qApp->connect(n, &QSocketNotifier::activated, &QApplication::quit);

618
619
    new KSMServerInterfaceAdaptor( this );
    QDBusConnection::sessionBus().registerObject(QStringLiteral("/KSMServer"), this);
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
620
    kcminitSignals = nullptr;
621
622
623
624
625
626
    the_server = this;
    clean = false;

    shutdownType = KWorkSpace::ShutdownTypeNone;

    state = Idle;
627
    dialogActive = false;
628
629
630
    saveSession = false;
    wmPhase1WaitingCount = 0;
    KConfigGroup config(KSharedConfig::openConfig(), "General");
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
631
    clientInteracting = nullptr;
632
633
634
635
    xonCommand = config.readEntry( "xonCommand", "xon" );

    selectWm( windowManager );

Laurent Montel's avatar
Laurent Montel committed
636
637
    connect(&startupSuspendTimeoutTimer, &QTimer::timeout, this, &KSMServer::startupSuspendTimeout);
    connect(&pendingShutdown, &QTimer::timeout, this, &KSMServer::pendingShutdownTimeout);
638

639
    only_local = flags.testFlag(InitFlag::OnlyLocal);
640
641
642
643
644
645
646
647
648
649
650
651
652
#ifdef HAVE__ICETRANSNOLISTEN
    if (only_local)
        _IceTransNoListen("tcp");
#else
    only_local = false;
#endif

    char        errormsg[256];
    if (!SmsInitialize ( (char*) KSMVendorString, (char*) KSMReleaseString,
                         KSMNewClientProc,
                         (SmPointer) this,
                         HostBasedAuthProc, 256, errormsg ) ) {

653
        qCWarning(KSMSERVER, "KSMServer: could not register XSM protocol");
654
655
656
657
658
    }

    if (!IceListenForConnections (&numTransports, &listenObjs,
                                  256, errormsg))
    {
659
660
        qCWarning(KSMSERVER, "KSMServer: Error listening for connections: %s", errormsg);
        qCWarning(KSMSERVER, "KSMServer: Aborting.");
661
662
663
664
665
666
667
668
        exit(1);
    }

    {
        // publish available transports.
        QByteArray fName = QFile::encodeName(QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation)
                                             + QDir::separator()
                                             + QStringLiteral("KSMserver"));
Hrvoje Senjan's avatar
Hrvoje Senjan committed
669
        qCDebug(KSMSERVER) << fName;
670
671
        QString display = QString::fromLocal8Bit(::getenv("DISPLAY"));
        // strip the screen number from the display
672
        display.remove(QRegExp(QStringLiteral("\\.[0-9]+$")));
673
674
675
676
677
678
679
680
681
682
683
        int i;
        while( (i = display.indexOf(QLatin1Char(':'))) >= 0)
           display[i] = '_';
        while( (i = display.indexOf(QLatin1Char('/'))) >= 0)
           display[i] = '_';

        fName += '_'+display.toLocal8Bit();
        FILE *f;
        f = ::fopen(fName.data(), "w+");
        if (!f)
        {
684
685
            qCWarning(KSMSERVER, "KSMServer: cannot open %s: %s", fName.data(), strerror(errno));
            qCWarning(KSMSERVER, "KSMServer: Aborting.");
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
            exit(1);
        }
        char* session_manager = IceComposeNetworkIdList(numTransports, listenObjs);
        fprintf(f, "%s\n%i\n", session_manager, getpid());
        fclose(f);
        setenv( "SESSION_MANAGER", session_manager, true  );

        // Pass env. var to kdeinit.
        org::kde::KLauncher klauncher( QStringLiteral( "org.kde.klauncher5" ), QStringLiteral( "/KLauncher" ), QDBusConnection::sessionBus());
        klauncher.setLaunchEnv( QStringLiteral( "SESSION_MANAGER" ), QString::fromLocal8Bit( (const char*) session_manager ) );

        free(session_manager);
    }

    if (only_local) {
        if (!SetAuthentication_local(numTransports, listenObjs))
            qFatal("KSMSERVER: authentication setup failed.");
    } else {
        if (!SetAuthentication(numTransports, listenObjs, &authDataEntries))
            qFatal("KSMSERVER: authentication setup failed.");
    }

    IceAddConnectionWatch (KSMWatchProc, (IcePointer) this);

    KSMListener* con;
    for ( int i = 0; i < numTransports; i++) {
        fcntl( IceGetListenConnectionNumber( listenObjs[i] ), F_SETFD, FD_CLOEXEC );
        con = new KSMListener( listenObjs[i] );
        listener.append( con );
Laurent Montel's avatar
Laurent Montel committed
715
        connect(con, &KSMListener::activated, this, &KSMServer::newConnection);
716
717
718
719
720
721
722
    }

    signal(SIGHUP, sighandler);
    signal(SIGTERM, sighandler);
    signal(SIGINT, sighandler);
    signal(SIGPIPE, SIG_IGN);

Laurent Montel's avatar
Laurent Montel committed
723
724
725
    connect(&protectionTimer, &QTimer::timeout, this, &KSMServer::protectionTimeout);
    connect(&restoreTimer, &QTimer::timeout, this, &KSMServer::tryRestoreNext);
    connect(qApp, &QApplication::aboutToQuit, this, &KSMServer::cleanUp);
726
727
728
729
730
}

KSMServer::~KSMServer()
{
    qDeleteAll( listener );
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
731
    the_server = nullptr;
732
733
734
735
736
737
738
739
740
    cleanUp();
}

void KSMServer::cleanUp()
{
    if (clean) return;
    clean = true;
    IceFreeListenObjs (numTransports, listenObjs);

741
742
743
744
745
746
    wake_up_socket = -1;
    ::close(sockets[1]);
    ::close(sockets[0]);
    sockets[0] = -1;
    sockets[1] = -1;

747
748
749
    QByteArray fName = QFile::encodeName(QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + QLatin1Char('/') + QStringLiteral("KSMserver"));
    QString display  = QString::fromLocal8Bit(::getenv("DISPLAY"));
    // strip the screen number from the display
750
    display.remove(QRegExp(QStringLiteral("\\.[0-9]+$")));
751
752
753
754
755
756
757
758
759
760
761
762
763
    int i;
    while( (i = display.indexOf(QLatin1Char(':'))) >= 0)
         display[i] = '_';
    while( (i = display.indexOf(QLatin1Char('/'))) >= 0)
         display[i] = '_';

    fName += '_'+display.toLocal8Bit();
    ::unlink(fName.data());

    FreeAuthenticationData(numTransports, authDataEntries);
    signal(SIGTERM, SIG_DFL);
    signal(SIGINT, SIG_DFL);

764
765
    runShutdownScripts();

766
767
768
769
770
771
772
773
    KDisplayManager().shutdown( shutdownType, shutdownMode, bootOption );
}



void* KSMServer::watchConnection( IceConn iceConn )
{
    KSMConnection* conn = new KSMConnection( iceConn );
Laurent Montel's avatar
Laurent Montel committed
774
    connect(conn, &KSMConnection::activated, this, &KSMServer::processData);
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
    return (void*) conn;
}

void KSMServer::removeConnection( KSMConnection* conn )
{
    delete conn;
}


/*!
  Called from our IceIoErrorHandler
 */
void KSMServer::ioError( IceConn /*iceConn*/  )
{
}

void KSMServer::processData( int /*socket*/ )
{
    IceConn iceConn = ((KSMConnection*)sender())->iceConn;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
794
    IceProcessMessagesStatus status = IceProcessMessages( iceConn, nullptr, nullptr );
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
    if ( status == IceProcessMessagesIOError ) {
        IceSetShutdownNegotiation( iceConn, False );
        QList<KSMClient*>::iterator it = clients.begin();
        QList<KSMClient*>::iterator const itEnd = clients.end();
        while ( ( it != itEnd ) && *it && ( SmsGetIceConnection( ( *it )->connection() ) != iceConn ) )
            ++it;
        if ( ( it != itEnd ) && *it ) {
            SmsConn smsConn = (*it)->connection();
            deleteClient( *it );
            SmsCleanUp( smsConn );
        }
        (void) IceCloseConnection( iceConn );
    }
}

KSMClient* KSMServer::newClient( SmsConn conn )
{
    KSMClient* client = new KSMClient( conn );
    clients.append( client );
    return client;
}

void KSMServer::deleteClient( KSMClient* client )
{
    if ( !clients.contains( client ) ) // paranoia
        return;
    clients.removeAll( client );
    clientsToKill.removeAll( client );
    clientsToSave.removeAll( client );
    if ( client == clientInteracting ) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
825
        clientInteracting = nullptr;
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
        handlePendingInteractions();
    }
    delete client;
    if ( state == Shutdown || state == Checkpoint || state == ClosingSubSession )
        completeShutdownOrCheckpoint();
    if ( state == Killing )
        completeKilling();
    else if ( state == KillingSubSession )
        completeKillingSubSession();
    if ( state == KillingWM )
        completeKillingWM();
}

void KSMServer::newConnection( int /*socket*/ )
{
    IceAcceptStatus status;
    IceConn iceConn = IceAcceptConnection( ((KSMListener*)sender())->listenObj, &status);
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
843
    if( iceConn == nullptr )
844
845
846
847
        return;
    IceSetShutdownNegotiation( iceConn, False );
    IceConnectStatus cstatus;
    while ((cstatus = IceConnectionStatus (iceConn))==IceConnectPending) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
848
        (void) IceProcessMessages( iceConn, nullptr, nullptr );
849
850
851
852
    }

    if (cstatus != IceConnectAccepted) {
        if (cstatus == IceConnectIOError)
Hrvoje Senjan's avatar
Hrvoje Senjan committed
853
            qCDebug(KSMSERVER) << "IO error opening ICE Connection!";
854
        else
Hrvoje Senjan's avatar
Hrvoje Senjan committed
855
            qCDebug(KSMSERVER) << "ICE Connection rejected!";
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
        (void )IceCloseConnection (iceConn);
        return;
    }

    // don't leak the fd
    fcntl( IceConnectionNumber(iceConn), F_SETFD, FD_CLOEXEC );
}


QString KSMServer::currentSession()
{
    if ( sessionGroup.startsWith( QLatin1String( "Session: " ) ) )
        return sessionGroup.mid( 9 );
    return QStringLiteral( "" ); // empty, not null, since used for KConfig::setGroup
}

void KSMServer::discardSession()
{
    KConfigGroup config(KSharedConfig::openConfig(), sessionGroup );
    int count =  config.readEntry( "count", 0 );
	foreach ( KSMClient *c, clients ) {
        QStringList discardCommand = c->discardCommand();
        if ( discardCommand.isEmpty())
            continue;
        // check that non of the old clients used the exactly same
        // discardCommand before we execute it. This used to be the
        // case up to KDE and Qt < 3.1
        int i = 1;
        while ( i <= count &&
                config.readPathEntry( QStringLiteral("discardCommand") + QString::number(i), QStringList() ) != discardCommand )
            i++;
        if ( i <= count )
            executeCommand( discardCommand );
    }
}

void KSMServer::storeSession()
{
    KSharedConfig::Ptr config = KSharedConfig::openConfig();
    config->reparseConfiguration(); // config may have changed in the KControl module
    KConfigGroup generalGroup(config, "General");
    excludeApps = generalGroup.readEntry( "excludeApps" ).toLower()
                  .split( QRegExp( QStringLiteral("[,:]") ), QString::SkipEmptyParts );
    KConfigGroup configSessionGroup(config, sessionGroup);
    int count =  configSessionGroup.readEntry( "count", 0 );
    for ( int i = 1; i <= count; i++ ) {
        QStringList discardCommand = configSessionGroup.readPathEntry( QLatin1String("discardCommand") + QString::number(i), QStringList() );
        if ( discardCommand.isEmpty())
            continue;
        // check that non of the new clients uses the exactly same
        // discardCommand before we execute it. This used to be the
        // case up to KDE and Qt < 3.1
        QList<KSMClient*>::iterator it = clients.begin();
        QList<KSMClient*>::iterator const itEnd = clients.end();
        while ( ( it != itEnd ) && *it && (discardCommand != ( *it )->discardCommand() ) )
            ++it;
        if ( ( it != itEnd ) && *it )
            continue;
        executeCommand( discardCommand );
    }
    config->deleteGroup( sessionGroup ); //### does not work with global config object...
	KConfigGroup cg( config, sessionGroup);
    count =  0;

    if (state != ClosingSubSession) {
        // put the wm first
        foreach ( KSMClient *c, clients )
            if ( c->program() == wm ) {
                clients.removeAll( c );
                clients.prepend( c );
                break;
            }
    }

    foreach ( KSMClient *c, clients ) {
        int restartHint = c->restartStyleHint();
        if (restartHint == SmRestartNever)
           continue;
        QString program = c->program();
        QStringList restartCommand = c->restartCommand();
        if (program.isEmpty() && restartCommand.isEmpty())
           continue;
        if (state == ClosingSubSession && ! clientsToSave.contains(c))
            continue;

        // 'program' might be (mostly) fullpath, or (sometimes) just the name.
        // 'name' is just the name.
        QFileInfo info(program);
        const QString& name = info.fileName();

        if ( excludeApps.contains(program.toLower()) ||
             excludeApps.contains(name.toLower()) ) {
            continue;
        }

        count++;
        QString n = QString::number(count);
        cg.writeEntry( QStringLiteral("program")+n, program );
        cg.writeEntry( QStringLiteral("clientId")+n, c->clientId() );
        cg.writeEntry( QStringLiteral("restartCommand")+n, restartCommand );
        cg.writePathEntry( QStringLiteral("discardCommand")+n, c->discardCommand() );
        cg.writeEntry( QStringLiteral("restartStyleHint")+n, restartHint );
        cg.writeEntry( QStringLiteral("userId")+n, c->userId() );
        cg.writeEntry( QStringLiteral("wasWm")+n, isWM( c ));
    }
    cg.writeEntry( "count", count );

    KConfigGroup cg2( config, "General");
    cg2.writeEntry( "screenCount", ScreenCount(QX11Info::display()));

966
    storeLegacySession(config.data());
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    config->sync();
}

QStringList KSMServer::sessionList()
{
    QStringList sessions( QStringLiteral( "default" ) );
    KSharedConfig::Ptr config = KSharedConfig::openConfig();
    const QStringList groups = config->groupList();
    for ( QStringList::ConstIterator it = groups.constBegin(); it != groups.constEnd(); ++it )
        if ( (*it).startsWith( QLatin1String( "Session: " ) ) )
            sessions << (*it).mid( 9 );
    return sessions;
}

bool KSMServer::isWM( const KSMClient* client ) const
{
    return isWM( client->program());
}

986
bool KSMServer::isWM( const QString& program ) const
987
{
988
989
990
991
    // Strip possible paths, so that even /usr/bin/kwin is recognized as kwin.
    QString wmName = wm.mid( wm.lastIndexOf( QDir::separator()) + 1 );
    QString programName = program.mid( program.lastIndexOf( QDir::separator()) + 1 );
    return programName == wmName;
992
993
994
995
996
997
998
999
1000
}

bool KSMServer::defaultSession() const
{
    return sessionGroup.isEmpty();
}

// selection logic:
// - $KDEWM is set - use that
For faster browsing, not all history is shown. View entire blame