File: nxsession.cpp

package info (click to toggle)
nxcl 0.9-3.1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, sid, stretch, wheezy
  • size: 560 kB
  • ctags: 412
  • sloc: cpp: 3,149; makefile: 114
file content (727 lines) | stat: -rw-r--r-- 25,014 bytes parent folder | download | duplicates (4)
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
35
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
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
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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
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
/***************************************************************************
                                nxsession.cpp
                             -------------------
    begin                : Wed 26th July 2006
    modifications        : July 2007
    copyright            : (C) 2006 by George Wright
    modifications        : (C) 2007 Embedded Software Foundry Ltd. (U.K.)
                         :     Author: Sebastian James
                         : (C) 2008 Defuturo Ltd
                         :     Author: George Wright
    email                : seb@esfnet.co.uk, gwright@kde.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

// Enumerated type defining the stages through which the client goes when
// connecting
enum { HELLO_NXCLIENT,
    ACKNOWLEDGE,
    SHELL_MODE,
    AUTH_MODE,
    LOGIN,
    LIST_SESSIONS,
    PARSESESSIONS,
    STARTSESSION,
    FINISHED };

#define CLIENT_VERSION "3.0.0"

#include <iostream>

#include "notQt.h"
#include "nxclientlib.h"
#include "nxsession.h"

using namespace std;
using namespace nxcl;

NXSession::NXSession() :
    devurand_fd(-1),
    stage(HELLO_NXCLIENT),
    sessionDataSet(false),
    nxUsername("nouser"),
    nxPassword("nopass")
{
}

NXSession::~NXSession()
{
}

void NXSession::resetSession()
{
    this->stage = 0;
    this->sessionDataSet = false;
}

string NXSession::parseSSH(string message)
{
    dbgln ("NXSession::parseSSH called for: " + message);

    int response = parseResponse (message);
    string returnMessage;

    if (response == 211) {
        if (doSSH == true) {
            returnMessage = "yes";
            doSSH = false;
        } else
            returnMessage = "no";
    }

    if (response == 204) { // Authentication failed
        returnMessage = "204";
    }

    if (response == 147) { // Server capacity reached
        returnMessage = "147";
        this->stage = FINISHED;
    }

    switch (this->stage) {
        case HELLO_NXCLIENT:
            dbgln ("HELLO_NXCLIENT stage");

            if (message.find("HELLO NXSERVER - Version") != string::npos) {
                this->callbacks->authenticatedSignal();
                returnMessage = "hello NXCLIENT - Version ";
                returnMessage.append(CLIENT_VERSION);
                this->stage++;
            }

            break;
        case ACKNOWLEDGE:
            dbgln ("ACKNOWLEDGE stage");

            if (response == 105)
                this->stage++;

            break;
        case SHELL_MODE:
            dbgln ("SHELL_MODE stage");

            if (response == 105) {
                returnMessage = "SET SHELL_MODE SHELL";
                this->stage++;
            }

            break;
        case AUTH_MODE:
            dbgln ("AUTH_MODE stage");

            if (response == 105) {
                returnMessage = "SET AUTH_MODE PASSWORD";
                this->stage++;
            }

            break;
        case LOGIN:
            dbgln ("LOGIN stage");

            switch (response) {
                case 105:
                    returnMessage = "login";
                    break;
                case 101:
                    returnMessage = nxUsername;
                    break;
                case 102:
                    returnMessage = nxPassword;
                    break;
                case 103:
                    this->stage++;
                    break;
                case 404:
                    this->callbacks->loginFailedSignal();
            }

            break;
        case LIST_SESSIONS:
            dbgln ("LIST_SESSIONS stage");

            if (this->sessionData->terminate == true) {
                // Wait for termination
                dbgln ("Waiting for termination");

                if (response == 900) {
                    stringstream termsession;

                    termsession << "NX> 900 Session id: "
                        << this->sessionData->id
                        << " terminated.";

                    if (message.find (termsession.str().c_str(), 0) == 0) {
                        // Session terminated.
                        this->sessionData->terminate = false;
                    } else {
                        usleep (10000);
                    }
                }

            } else if (response == 105) {
                // Get a list of the available sessions on the server, for
                // given user, with given status, and any type. Not sure if
                // geometry is ignored or not.
                stringstream ss;

                // We want to list suspended or running sessions, with this
                // command:
                dbgln ("this->resumeSessions.size() == "
                        << this->resumeSessions.size());

                if (this->sessionData->sessionType == "shadow") {
                    // This is how to list shadow sessions. Run NoMachine's
                    // client and see ~/.nx/temp/(pid)/sshlog for connection
                    // details
                    ss << "listsession --type=\"shadow\"";

                } else {

                    ss << "listsession --user=\"" << nxUsername
                        << "\" --status=\"suspended,running\" --geometry=\""
                        << this->sessionData->xRes << "x"
                        << this->sessionData->yRes << "x"
                        << this->sessionData->depth
                        << (this->sessionData->render ? "+render" : "")

                        // If you leave --type blank, you can re-connect to any
                        // sessions available.
                        << "\" --type=\"" << this->sessionData->sessionType
                        << "\"";
                }

                returnMessage = ss.str();
                this->stage++;
            }
            break;
        case PARSESESSIONS:
            dbgln ("PARSESESSIONS stage");

            if ((this->sessionData->sessionType == "shadow" &&
                        response != 105) ||
                    (this->sessionData->sessionType != "shadow" &&
                        response != 148)  ) {

                dbgln ("Building resumeSessions:"
                        << " resumeSessions.push_back(message);");

                this->resumeSessions.push_back(message);

            } else if ((this->sessionData->sessionType == "shadow" &&
                        response == 105)
                    || (this->sessionData->sessionType != "shadow" &&
                        response == 148)) {

                dbgln ("Parsing resumeSessions:"
                        << " parseResumeSessions(resumeSessions);");

                parseResumeSessions (this->resumeSessions);

                dbgln ("parseResumeSessions(resumeSessions) returned");

                // Now, the problem we have here, is that when
                // we return from the last 105 response, we
                // don't then get another stdout message to
                // act upon. So, we want to recurse back into
                // parseSSH to get onto the STARTSESSION stage here:
                returnMessage = this->parseSSH (message);
            }
            break;

        case STARTSESSION:
            dbgln ("STARTSESSION stage");
            if (response == 105 && sessionDataSet) {

                dbgln ("response is 105 and sessionDataSet is true");;
                int media = 0;
                string fullscreen = "";
                if (this->sessionData->media) {
                    media = 1;
                }

                if (this->sessionData->fullscreen) {
                    this->sessionData->geometry = "fullscreen";
                    fullscreen = "+fullscreen";
                }

                if (this->sessionData->sessionType == "shadow" &&
                        this->sessionData->terminate == false) {

                    dbgln ("It's a shadow session!");
                    stringstream ss;

                    // These are the session parameters that NoMachine's client
                    // sends for resume

                    ss << "attachsession "
                        << "--link=\"" << this->sessionData->linkType << "\" "
                        << "--backingstore=\""
                            << this->sessionData->backingstore << "\" "
                        << "--encryption=\"" << this->sessionData->encryption
                            << "\" "
                        << "--cache=\"" << this->sessionData->cache << "M\" "
                        << "--images=\"" << this->sessionData->images << "M\" "
                        // probably has been autodetected from my display
                        << "--shmem=\"1\" "
                        // probably has been autodetected from my display
                        << "--shpix=\"1\" "
                        // probably has been autodetected from my display
                        << "--strict=\"0\" "
                        // probably has been autodetected from my display
                        << "--composite=\"1\" "
                        << "--media=\"" << media << "\" "
                        << "--session=\"" << this->sessionData->sessionName
                            << "\" "
                        << "--type=\"" << this->sessionData->sessionType
                            << "\" "
                        // FIXME: This may be some other OS if you compile it on
                        // Sun, Windows, etc.
                        << "--client=\"linux\" "
                        << "--keyboard=\"" << this->sessionData->keyboard
                            << "\" "
                        << "--id=\"" << this->sessionData->id << "\" "
                        // This may be the key?
                        << "--display=\"0\" "
                        << "--geometry=\"" << this->sessionData->geometry
                            << "\" ";

                    returnMessage = ss.str();

                    dbgln ("session parameter command: " + ss.str());

                    this->stage++;

                } else if (this->sessionData->terminate == true) {

                    stringstream ss;

                    // These are the session parameters that NoMachine's client
                    // sends for resume
                    ss << "Terminate --sessionid=\"" << this->sessionData->id
                        << "\"";

                    returnMessage = ss.str();

                    dbgln ("session parameter command: " + ss.str());

                    // Back to listsessions after terminating a session.
                    this->stage -= 2;

                    // Clear the list of sessions to resume
                    this->resumeSessions.clear();
                    this->runningSessions.clear();

                } else if (this->sessionData->suspended) {

                    dbgln ("this->sessionData->suspended is true");

                    stringstream ss;

                    // These are the session parameters that NoMachine's client
                    // sends for resume
                    ss << "restoresession --id=\"" << this->sessionData->id <<
                        "\" --session=\"" << this->sessionData->sessionName <<
                        "\" --type=\"" << this->sessionData->sessionType <<
                        "\" --cache=\"" << this->sessionData->cache <<
                        "M\" --images=\"" << this->sessionData->images <<
                        "M\" --cookie=\"" << generateCookie() <<
                        "\" --link=\"" << this->sessionData->linkType <<
                        "\" --kbtype=\"" << this->sessionData->kbtype <<
                        "\" --nodelay=\"1\" --encryption=\""
                            << this->sessionData->encryption <<
                        "\" --backingstore=\""
                            << this->sessionData->backingstore <<
                        "\" --geometry=\"" << this->sessionData->geometry <<
                        "\" --media=\"" << media <<
                        "\" --agent_server=\""
                            << this->sessionData->agentServer <<
                        "\" --agent_user=\"" << this->sessionData->agentUser <<
                        "\" --agent_password=\""
                            << this->sessionData->agentPass << "\"";

                    returnMessage = ss.str();

                    dbgln ("session parameter command: " + ss.str());

                    this->stage++;

                } else {

                    dbgln ("this->sessionData->suspended is false, and it's" <<
                            " not a shadow session.");

                    stringstream ss;

                    ss << "startsession --session=\""
                            << this->sessionData->sessionName

                        << "\" --type=\"" << this->sessionData->sessionType
                        << "\" --cache=\"" << this->sessionData->cache
                        << "M\" --images=\"" << this->sessionData->images
                        << "M\" --cookie=\"" << generateCookie()
                        << "\" --link=\"" << this->sessionData->linkType
                        << "\" --render=\""
                            << (this->sessionData->render ? 1 : 0)

                        << "\" --encryption=\""
                            << this->sessionData->encryption

                        << "\" --backingstore=\""
                            << this->sessionData->backingstore

                        << "\" --imagecompressionmethod=\""
                        << this->sessionData->imageCompressionMethod
                        << "\" --geometry=\"" << this->sessionData->geometry
                        << "\" --screeninfo=\"" << this->sessionData->xRes
                        << "x" << this->sessionData->yRes << "x"
                        << this->sessionData->depth
                        << (this->sessionData->render ? "+render" : "")
                        << fullscreen << "\" --keyboard=\""
                            << this->sessionData->keyboard

                        << "\" --kbtype=\"" << this->sessionData->kbtype
                        << "\" --media=\"" << media
                        << "\" --agent_server=\""
                            << this->sessionData->agentServer

                        << "\" --agent_user=\""
                            << this->sessionData->agentUser

                        << "\" --agent_password=\""
                            << this->sessionData->agentPass

                        << "\"";

                    ss << " --title=\"sebtest\""; // testing a window title

                    if (this->sessionData->sessionType == "unix-application") {
                        ss << " --application=\"" 
                            << this->sessionData->customCommand << "\"";

                        if (this->sessionData->virtualDesktop == true) {
                            ss << " --rootless=\"0\" --virtualdesktop=\"1\"";
                        } else {
                            ss << " --rootless=\"1\" --virtualdesktop=\"0\"";
                        }

                    } else if
                        (this->sessionData->sessionType == "unix-console") {

                        if (this->sessionData->virtualDesktop == true) {
                            ss << " --rootless=\"0\" --virtualdesktop=\"1\"";
                        } else {
                            ss << " --rootless=\"1\" --virtualdesktop=\"0\"";
                        }

                    } else if
                        (this->sessionData->sessionType == "unix-default") {
                        // ignore this - does anyone use it?
                    }

                    returnMessage = ss.str();

                    dbgln ("session parameter command: " + ss.str());

                    this->stage++;
                }
            } else {
                dbgln ("either response is not 105 or sessionDataSet is"
                        << " false.");
            }
            break;

        case FINISHED:
            dbgln ("FINISHED stage. Response is " << response
                    << ". That should mean that session set up is complete.");
            this->callbacks->readyForProxySignal();
    }

    dbgln ("NXSession::parseSSH, about to return a message: " + returnMessage);

    if (!returnMessage.empty()) {
        returnMessage.append("\n");
        return returnMessage;
    } else
        return "";
}

void NXSession::setSessionData (NXSessionData *sd)
{
    this->sessionData = sd;
}

int NXSession::parseResponse(string message)
{
    string::size_type idx1, idx2;

    int response;

    dbgln ("NXSession::parseResponse called for message:" << message);

    if ((idx1 = message.find ("notQProcess error", 0)) != string::npos) {

        dbgln ("Found notQProcess error");

        // This means a process crashed, we're going to return a number >100000
        // to indicate this.
        if ( ((idx2 = message.find ("crashed", 0)) != string::npos) && 
                idx2 > idx1) {

            stringstream ss;
            ss << message.substr((idx1+19), idx2-1-(idx1+19));

            // This is the pid that crashed
            ss >> response;

            // Add 100000 and return this
            response += 100000;

            return response;
        } else {
            dbgln ("Uh oh, didn't find \"crashed\"");
        }
    }

    // Find out the server response number
    // This will only be present in strings which contain "NX>"
    if (message.find("NX>") != string::npos && message.find("NX>") == 0) {
        idx1 = message.find("NX>") + 4;

        if ((idx2 = message.find(" ", idx1)) == string::npos) {
            if ((idx2 = message.find("\n", idx1)) == string::npos) {
                idx2 = message.size();
            }
        }

        if (idx2>idx1) {
            stringstream ss;
            ss << message.substr(idx1, idx2-idx1);
            ss >> response;
        } else {
            response = 0;
        }

    } else {
        response = 0;
    }

    dbgln ("NXSession::parseResponse() returning " << response);
    return response;
}

void NXSession::parseResumeSessions(list<string> rawdata)
{
    // Was: QStringList sessions, and got rawdata appended to it?
    list<string> sessions;
    list<string>::iterator iter, at;

    dbgln ("NXSession::parseResumeSessions called.");

    for (iter = rawdata.begin(); iter != rawdata.end(); iter++) {
        if (((*iter).find("-------") != string::npos) && !(*iter).empty()) {
            at = iter;
        }
    }

    for (iter = ++at; iter != rawdata.end(); iter++) {
        if ((!(*iter).find("NX> 148") != string::npos) && !(*iter).empty()) {
            sessions.push_back(*iter);
        }
    }

    list < vector<string> > rawsessions;
    list < vector<string> >::iterator rsIter;

    // Clean up each string in sessions[i], then push back
    // sessions[i] onto rawsessions., except that means
    // rawsessions is then just a list<string>...
    vector<string> session;
    vector<string>::iterator seshIter;

    for (iter = sessions.begin(); iter != sessions.end(); iter++) {
        session.clear();

        // Simplify one line of list<string> sessions
        (*iter) = notQtUtilities::simplify (*iter); 

        // Split one line of list<string> sessions into a vector<string>
        notQtUtilities::splitString (*iter, ' ', session); 

        // Add that to rawsessions
        rawsessions.push_back(session);
    }

    NXResumeData resData;

    for (rsIter = rawsessions.begin(); rsIter != rawsessions.end(); rsIter++) {
        stringstream ss1, ss2;
        int tmp;

        dbgln ("*rsIter.size() == " << (*rsIter).size());
        ss1 << (*rsIter)[0];
        ss1 >> tmp;

        resData.display = tmp;

        dbgln ("resData.display = " << resData.display);
        resData.sessionType = (*rsIter)[1];

        dbgln ("resData.sessionType = " << resData.sessionType);
        resData.sessionID = (*rsIter)[2];

        dbgln ("resData.sessionID = " << resData.sessionID);
        resData.options = (*rsIter)[3];

        dbgln ("resData.options = " << resData.options);
        ss2 << (*rsIter)[4];
        ss2 >> tmp;

        resData.depth = tmp;

        dbgln ("resData.depth = " << resData.depth);
        resData.screen = (*rsIter)[5];

        dbgln ("resData.screen = " << resData.screen);
        resData.available = (*rsIter)[6];

        dbgln ("resData.available = " << resData.available);
        resData.sessionName = (*rsIter)[7];

        dbgln ("resData.sessionName = " << resData.sessionName);
        this->runningSessions.push_back(resData);
    }

    if (this->runningSessions.size() != 0) {
        this->suspendedSessions = true;

        dbgln ("NXSession::parseResumeSessions(): Calling sessionsSignal.");

        // runningSessions is a list of NXResumeData
        this->callbacks->sessionsSignal (this->runningSessions);
    } else {
        dbgln ("NXSession::parseResumeSessions(): Calling"
                << " this->callbacks->noSessionsSignal()");

        // In case we previously had one resumable session,
        // which the user terminated, then we listsessions and
        // got no resumable sessions, we need to make sure
        // startsession is called, not restoresession. hence
        // set sessionData->suspended to false.
        this->sessionData->suspended = false;
        this->callbacks->noSessionsSignal();
    }

    dbgln ("Increment stage");
    this->stage++;
    dbgln ("NXSession::parseResumeSessions() returning.");
}

void NXSession::wipeSessions()
{
    while (!this->runningSessions.empty()) {
        this->runningSessions.pop_front();
    }
}

string NXSession::generateCookie()
{
    unsigned long long int int1, int2;
    stringstream cookie;

    devurand_fd = open("/dev/urandom", O_RDONLY);

    fillRand((unsigned char*)&int1, sizeof(int1));
    fillRand((unsigned char*)&int2, sizeof(int2));
    cookie << int1 << int2;
    return cookie.str();
}

void NXSession::fillRand(unsigned char *buf, size_t nbytes)
{
    ssize_t r;
    unsigned char *where = buf;

    while (nbytes) {
        while ((r = read(devurand_fd, where, nbytes)) == -1)
            where  += r;
        nbytes -= r;
    }
}

bool NXSession::chooseResumable (int n)
{
    dbgln ("NXSession::chooseResumable called.");
    if (this->runningSessions.size() <= static_cast<unsigned int>(n)) {

        // No nth session to resume.
        dbgln ("No nth session to resume, return false.");
        return false;
    }

    // Set to false while we change contents of sessionData
    this->sessionDataSet = false;

    list<NXResumeData>::iterator it = this->runningSessions.begin();
    for (int i = 0; i<n; i++) { it++; }

    // If it's a shadow session, we don't want to replace "shadow" with
    // X11-local
    if (this->sessionData->sessionType != "shadow") {
        this->sessionData->sessionType = (*it).sessionType;
    }

    this->sessionData->display = (*it).display;
    this->sessionData->sessionName = (*it).sessionName;
    this->sessionData->id = (*it).sessionID;

    stringstream geom;	

    // Plus render, if necessary
    geom << (*it).screen << "x" << (*it).display;

    // FIXME: This not yet quite complete.
    // With depth in there too?
    this->sessionData->geometry = geom.str();
    this->sessionData->suspended=true;

    this->sessionDataSet = true;

    dbgln ("NXSession::chooseResumable returning true.");
    return true;
}

bool NXSession::terminateSession (int n)
{
    dbgln ("NXSession::terminateSession called.");
    if (this->runningSessions.size() <= static_cast<unsigned int>(n)) {

        // No nth session to terminate
        dbgln ("No nth session to terminate, return false.");
        return false;
    }

    // Set to false while we change the contents of sessionData
    this->sessionDataSet = false;

    list<NXResumeData>::iterator it = this->runningSessions.begin();
    for (int i = 0; i<n; i++) { it++; }

    this->sessionData->terminate = true;
    this->sessionData->display = (*it).display;
    this->sessionData->sessionName = (*it).sessionName;
    this->sessionData->id = (*it).sessionID;
    this->sessionData->suspended=true;

    this->sessionDataSet = true;

    return true;
}