forked from dimbor-ru/freenx-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnxserver
executable file
·1968 lines (1764 loc) · 57.3 KB
/
nxserver
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Free implementation of nxserver components
#
# To use nxserver add the user "nx"
# and use nxserver as default shell.
#
# Also make sure that hostkey based authentification works.
#
# Copyright (c) 2004 by Fabian Franz <FreeNX@fabian-franz.de>.
# (c) 2008-19 by Dmitry Borisov <i@dimbor.ru>
#
# License: GNU GPL, version 2
#
# SVN: $Id: nxserver 612 2008-08-25 03:28:15Z fabianx $
#
# Read the config file
. $(PATH=$(cd $(dirname $0) && pwd):$PATH which nxloadconfig) --
# following two functions are Copyright by Klaus Knopper
stringinstring() { case "$2" in *$1*) return 0;; esac; return 1; }
# Reread boot command line; echo last parameter's argument or return false.
getparam(){
pattern=".*&$1=([^&]*)"
str="&$CMDLINE"
[[ $str =~ $pattern ]]
echo ${BASH_REMATCH[1]}
[ "$BASH_REMATCH" != "" ]
}
############### PACKAGE log.bm #######################
#
# Library of log functions (outsource)
#
# Loglevels:
# 1: Errors
# 2: Warnings
# 3: Important information
# 4: Server - Client communication
# 5: Information
# 6: Debugging information
# 7: stderror-channel of some applications
log() {
[ "$NX_LOG_LEVEL" -ge "$1" -a -w "$NX_LOGFILE" ] && shift && {
[ -n "$1" ] &&
echo -n "[$(date "+%d.%m %X")] " >> "$NX_LOGFILE"
echo $@ >> "$NX_LOGFILE"
}
}
# Log in a way that is secure for passwords / cookies / ...
echo_secure() {
[ -n "$1" ] &&
echo -n "[$(date "+%d.%m %X")] " >> "$NX_LOGFILE"
echo $@ | sed -e 's/--cookie="[^"]*"/--cookie="******"/g' \
-e 's/\(--.*password=\)"[^"]*"/\1"******"/g'\
-e 's/password=[^&]*/password=******/g;'
}
log_secure() {
if [ "$NX_LOG_SECURE" = "0" ]; then log "$@"
elif [ "$NX_LOG_LEVEL" -ge "$1" -a -w "$NX_LOGFILE" ]; then
shift && echo_secure "$@" >> "$NX_LOGFILE"
fi
}
log_tee() {
[ "$NX_LOG_LEVEL" -ge "4" -a -w "$NX_LOGFILE" ] && exec tee -a "$NX_LOGFILE"
[ "$NX_LOG_LEVEL" -ge "4" -a -w "$NX_LOGFILE" ] || exec cat -
}
log_error() {
[ "$NX_LOG_LEVEL" -ge "7" -a -w "$NX_LOGFILE" ] && exec tee -a "$NX_LOGFILE"
[ "$NX_LOG_LEVEL" -ge "7" -a -w "$NX_LOGFILE" ] || exec cat -
}
echo_x() { log "4" "$@"; echo "$@"; }
############### PACKAGE passdb.bm #######################
#
# Library of passdb functions (outsource)
#
# Policy: Variable and function names _must_ start with passdb_ / PASSDB_
# Needed global vars: $NX_ETC_DIR, $PATH_BIN
# Needed nonstd functions: md5sum
passdb_get_crypt_pass() { echo "$@" | $COMMAND_MD5SUM | cut -d" " -f1; }
passdb_get_pass() {
PASSDB_CHUSER="$1"
PASSDB_PASS=$(egrep "^$PASSDB_CHUSER:" $NX_ETC_DIR/passwords 2>/dev/null | cut -d":" -f2)
if [ "$ENABLE_PASSDB_AUTHENTICATION" = "1" ]; then
egrep -q "^$PASSDB_CHUSER:" $NX_ETC_DIR/passwords 2>/dev/null && echo $PASSDB_PASS
egrep -q "^$PASSDB_CHUSER:" $NX_ETC_DIR/passwords 2>/dev/null || echo "NOT_VALID"
else
echo "NOT_VALID"
fi
}
passdb_chpass() {
PASSDB_CHUSER="$1"; PASSDB_ENC_PASS="$2"
cp -f $NX_ETC_DIR/passwords $NX_ETC_DIR/passwords.orig
sed -i -e "s/$PASSDB_CHUSER:.*/$PASSDB_CHUSER:$PASSDB_ENC_PASS/g" $NX_ETC_DIR/passwords
}
passdb_user_exists() {
PASSDB_CHUSER="$1"
egrep -q "^$PASSDB_CHUSER:" $NX_ETC_DIR/passwords 2>/dev/null
}
passdb_remove_user() {
PASSDB_CHUSER="$1"
cp -f $NX_ETC_DIR/passwords $NX_ETC_DIR/passwords.orig
sed -i -e "/$PASSDB_CHUSER:/d" $NX_ETC_DIR/passwords
}
passdb_add_user() {
PASSDB_CHUSER="$1"
cp -f $NX_ETC_DIR/passwords $NX_ETC_DIR/passwords.orig
echo "$PASSDB_CHUSER:*" >> $NX_ETC_DIR/passwords
# deactivated to avoid problems with comm-server
su - $PASSDB_CHUSER -c "$PATH_BIN/nxnode --setkey"
}
passdb_list_user() {
cat $NX_ETC_DIR/passwords | cut -d":" -f1
}
#
# End of passdb Library
#
############### PACKAGE session.bm #######################
#
# Library of session management functions
#
# Needed global vars: $NX_SESS_DIR
# drop types from filds str
flds_wo_types() { echo "$1" | sed 's/[ \t]*INT//g'; }
# ============== structure of sessions db ================
ssid="sessionId"
fls0_t="sessionName,\
display,\
status,\
startTime INT,\
foreignAddress,\
sessionRootlessMode INT,\
type,\
creationTime INT,\
userName,\
serverPid,\
screeninfo,\
geometry,\
host,\
shadowcookie"
fls0=$(flds_wo_types "$fls0_t")
fls_ext_t="endTime INT"
fls_ext=$(flds_wo_types "$fls_ext_t")
fls_orig="$ssid, $fls0"
fls_full="$fls_orig, $fls_ext"
# =================== sqlite3 stuff =====================
sqcmd="$(which sqlite3)"; sqbd="$NX_SESS_DIR/sessions.sq3"; sqtname="sess"
# sqlite3 main query function
q_db() { echo -e ".timeout $SQ3_TIMEOUT\n$@" | $sqcmd $sqbd; }
ins_sess_file() {
txt="$(cat $1)"
fields=""; vals=""
txt="$(echo "$txt" | tr '=' ' ')"
while read field val; do
fields="$fields${fields:+,}$field"
vals="$vals${vals:+,}'$val'"
done <<< "$txt"
q_db "INSERT INTO $sqtname($fields) VALUES($vals);"
}
init_db() {
[ ! -r "$NX_SESS_DIR" ] && return
isdb=""; [ -f $sqbd ] && isdb="1"
qstr="CREATE TABLE IF NOT EXISTS $sqtname($ssid TEXT PRIMARY KEY, $fls0_t, $fls_ext_t);"
qstr="$qstr CREATE INDEX IF NOT EXISTS idx_statusUserName ON $sqtname(status,userName);"
q_db "$qstr"
[ -n "$isdb" ] && return
for fn in $NX_SESS_DIR/{closed,failed,running}/*; do
ins_sess_file $fn;
done >/dev/null 2>&1
log 1 "Info: Sessions db migrated to sqlite3 format."
rm -rf $NX_SESS_DIR/{closed,failed,running} >/dev/null 2>&1
}
str_eq_cond() {
#params: cond,"A|B|C..."
#ret: "cond IN ('A','B','C'...)" OR "cond='A'"
[ -z "$2" ] && return
comma=""; vals=""
txt="$(echo -n "$2" | tr '|' '\n')"
while read val; do
comma="${vals:+,}"
vals="$vals$comma'$val'"
done <<< "$txt"
if [ -n "$comma" ]; then echo "$1 IN ($vals)"
else echo "$1=$vals"
fi
}
fls_timeformat() {
echo "$@" | sed -e \
"s/,[ \t]\(\w*Time\)/, datetime(\1,'unixepoch','localtime') AS \1/g" #"
}
qtxt2cmdstrs() {
#params: text from sqlite3 query (.mode line)
#ret: nx command strings
echo "$@" | awk 'BEGIN{FS="\n"; RS=""; OFS="&"; ORS="\n"}
{for (i=1;i<=NF;i++) {
split($i,a,"=");
for (j=1;j<=2;j++) {
e=length(a[j]);
for (bi=1;bi<e;bi++) if (substr(a[j],bi,1)""!~"[ \t]") break;
for (ei=e;ei>bi;ei--) if (substr(a[j],ei,1)""!~"[ \t]") break;
a[j]=substr(a[j],bi,ei-bi+1);
if (a[j]==" ") a[j]="";
};
$i=a[1]"" "=" a[2];
}
print "a=b&" $0 "&";
}'
}
#-------------------------------------------------------------------
session_list() {
#params: sessId ["format_times"]
#if you need to humane output put something in $2
if [ -n "$2" ]; then fls=$(fls_timeformat "$fls_full")
else # original order of fields
fls="sessionName, display, status, startTime, foreignAddress,\
sessionRootlessMode, type, sessionId, creationTime, userName,\
serverPid, screeninfo,geometry, host, shadowcookie"
fi
res=$(q_db ".mode line\n SELECT $fls FROM $sqtname WHERE sessionId='$1';")
if [ -z "$2" ]; then
echo "$res" | sed -e 's/^[ \t]*//g' -e 's/[ \t]*=[ \t]*/=/g'
else
echo "$res" | sed -e 's/^[ \t]*//g'
fi
}
session_find_cmdstrs() {
#params: [sessid] [user] [display] [status="Running|Suspended"]
#ret: sessions command strings delimited by \n
st="Running|Suspended"; [ -n "$4" ] && st="$4"
wstr="WHERE $(str_eq_cond status $st)"
[ -n "$1" ] && wstr="$wstr AND $(str_eq_cond sessionId $1)"
[ -n "$2" -a "$2" != "all" -a "$2" != ".*" ] && \
wstr="$wstr AND $(str_eq_cond userName $2)"
[ -n "$3" ] && wstr="$wstr AND $(str_eq_cond display $3)"
res="$(q_db ".mode line\nSELECT $fls_full" "FROM $sqtname" "$wstr" "ORDER BY startTime DESC;")"
qtxt2cmdstrs "$res"
}
# Find all running session-filenames
session_find_all() { session_find_cmdstrs; }
# Find all running sessions of a id
session_find_id() { session_find_cmdstrs "$1"; }
# Finds out if a session belongs to a user
session_find_user() { session_find_cmdstrs "" "$1"; }
# Find all running sessions of a display
session_find_display() { session_find_cmdstrs "" "" "$1"; }
# Finds out if a session belongs to a user
session_find_id_user() {
#params: sessid user
wstr="WHERE status IN ('Running', 'Suspended') AND sessionId='$1' AND username='$2'"
res=$(q_db "SELECT sessionId FROM $sqtname" "$wstr" ";")
[ -n "$res" ] && return 0
return 1
}
# session_get <uniqueid>
session_get() { session_find_cmdstrs "$1"; }
# Get the first session, which can be resumed
session_get_user_suspended() {
#params: user status
#ret: sessionId line[s] or empty
wstr="WHERE status='$2'AND username='$1'"
q_db "SELECT sessionId FROM $sqtname" "$wstr" "ORDER BY startTime DESC;" \
| head -1
}
# Count all sessions of a user
# and save it in SESSION_COUNT and SESSION_COUNT_USER
session_count_user() {
#params: userName [status]
SESSION_COUNT=0; SESSION_COUNT_USER=0
st="Running|Suspended"; [ -n "$2" ] && st="$2"
wstr="WHERE $(str_eq_cond status $st)"
if [ "$1" = ".*" -o "$1" = "all" ]; then
SESSION_COUNT=$(q_db "SELECT count(*) FROM $sqtname" "$wstr" ";") #"
SESSION_COUNT_USER=$SESSION_COUNT
return 0
fi
txt=$(q_db ".mode tabs\nSELECT userName,count(*) FROM $sqtname" "$wstr" " GROUP BY userName;") #"
u=""; sc=""
while read u sc; do
[ -z "$sc" ] && continue
let SESSION_COUNT=SESSION_COUNT+$sc
[ "$u" = "$1" ] && SESSION_COUNT_USER=$sc
done <<< "$txt"
return 0
}
# Cache the session list output for up to 30 seconds because nxclient
# repeatedly queries it very fast, which creates performance problems.
session_list_user_suspended() {
args="$1 $2 $3 $4"
if [[ "$args" != "$SESSION_LIST_CACHE_ARGS" || $(($(date +%s) - ${SESSION_LIST_CACHE_TIME:-0})) -gt 30 ]] ; then
SESSION_LIST_CACHE_ARGS="$args"
SESSION_LIST_CACHE_TIME=$(date +%s)
SESSION_LIST_CACHE_DATA=$(_session_list_user_suspended "$@")
fi
echo "$SESSION_LIST_CACHE_DATA"
}
_session_list_user_suspended() {
TMPFILE=$(mktemp /tmp/nxserver_tmp.XXXXXXXXX)
echo "NX> 127 Sessions list of user '$1' for reconnect:" > $TMPFILE
echo >> $TMPFILE
if [ -z "$4" ]; then
echo "Display Type Session ID Options Depth Screensize Available Session Name" >> $TMPFILE
echo "------- ---------------- -------------------------------- -------- ----- -------------- --------- ----------------------" >> $TMPFILE
else
echo "Display Type Session ID Options Depth Screen Status Session Name" >> $TMPFILE
echo "------- ---------------- -------------------------------- -------- ----- -------------- ----------- ------------------------------" >> $TMPFILE
fi
cmdstrs=$(session_find_cmdstrs "" "$1" "" "$2")
while read CMDLINE; do
[ -z "$CMDLINE" ] && continue
if [ "$4" = "shadow" -a "$(getparam userName)" != "$USER" ]; then
[ -z "$(getparam shadowcookie)" ] && continue
if [ -x "$COMMAND_NXSHADOWACL" ]; then
$COMMAND_NXSHADOWACL "$(getparam userName)" "$USER" || continue
fi
fi
pattern='^([0-9]*x[0-9]*)x([0-9]*)\+?([^+]*)'
[[ $(getparam screeninfo) =~ $pattern ]]
geom=${BASH_REMATCH[1]}; depth=${BASH_REMATCH[2]}; render=${BASH_REMATCH[3]}
[[ $3 =~ $pattern ]]
udepth=${BASH_REMATCH[2]}; urender=${BASH_REMATCH[3]}
mode="D"; [ "$(getparam sessionRootlessMode)" = "1" ] && mode="-"
options="-"; stringinstring "fullscreen" "$3" && options="F"
[ "$(getparam geometry)" = "fullscreen" ] || options="-"
[ "$urender" = "render" ] && options="${options}R${mode}--PSA"
[ "$urender" = "render" ] || options="${options}-${mode}--PSA"
[ "$udepth" = "$depth" -a "$urender" = "$render" ] && available=$(getparam status)
# FIXME: HACK !!! to keep compatibility with old snapshot version (Knoppix 3.6 based for example)
if [ -z "$4" -a "$available" != "N/A" ]; then
available="Yes"
fi
# We automatically offer VNC shadowed sessions for "remote" support
if [ "$4" = "vnc" -a "$ENABLE_MIRROR_VIA_VNC" = "1" ] \
&& stringinstring "unix-" "$(getparam type)"; then
available=$(getparam status)
printf "%-7s %-16s %32s %8s %5s %-14s %-11s %s\n" "$(getparam display)" "vnc-shadowed" "$(getparam sessionId)" "$options" "$depth" "$geom" "$available" "$(getparam sessionName) (Mirrored)" >> $TMPFILE
elif [ "$4" = "shadow" ]; then
available=$(getparam status)
printf "%-7s %-16s %32s %8s %5s %-14s %-11s %s\n" "$(getparam display)" "$(getparam type)" "$(getparam sessionId)" "$options" "$depth" "$geom" "$available" "$(getparam sessionName) ($(getparam userName)) (Shadowed)" >> $TMPFILE
else
# only unix-* sessions can be resumed, but other session types can still be terminated
stringinstring "unix-" "$4" || available="N/A"
printf "%-7s %-16s %32s %8s %5s %-14s %-11s %s\n" "$(getparam display)" "$(getparam type)" "$(getparam sessionId)" "$options" "$depth" "$geom" "$available" "$(getparam sessionName)" >> $TMPFILE
fi
done <<< "$cmdstrs"
if [ "$4" = "vnc" -o "$4" = "shadow" -a "$ENABLE_DESKTOP_SHARING" = "1" ]; then
export DESKTOP_SHARING_IDS=""
for i in $(LC_ALL=C netstat -ln --protocol=unix | egrep 'X11-unix/X[0-9]$' | sed 's/.*X\(.*\)/\1/g'); do #'
uniqueid=$(echo $[$RANDOM*$RANDOM] | $COMMAND_MD5SUM | cut -d" " -f1 | tr "[a-z]" "[A-Z]")
DESKTOP_SHARING_IDS="$DESKTOP_SHARING_IDS $uniqueid=$i"
printf "%-7s %-16s %32s %8s %5s %-14s %-11s %s\n" "$i" "Local" "$uniqueid" "--------" "$udepth" "$(echo $3 | cut -d'x' -f1,2)" "Running" "X$i (Local)" >> $TMPFILE
done
fi
echo "" >> $TMPFILE
echo "" >> $TMPFILE
#SESSION_COUNT=0; SESSION_COUNT_USER=0
session_count_user "$1"
if [ "$SESSION_COUNT" -ge "$SESSION_LIMIT" -o \
"$SESSION_COUNT_USER" -ge "$SESSION_USER_LIMIT" ]; then
echo "NX> 147 Server capacity: reached for user: $1" >> $TMPFILE
else
echo "NX> 148 Server capacity: not reached for user: $1" >> $TMPFILE
fi
cat $TMPFILE | log_tee
rm -f $TMPFILE
}
session_list_user() {
#params: userName [status="Running|Suspended"]
echo -n "NX> 127 Sessions list"
if [ -n "$1" -a "$1" != "all" ]; then echo " of user '$1'"
else echo ":"
fi
echo
echo "Server Display Username Remote IP Session ID"
echo "------ ------- --------------- --------------- --------------------------------"
st="Running|Suspended"; [ -n "$2" ] && st="$2"
wstr="WHERE $(str_eq_cond status $st)"
[ -n "$1" -a "$1" != "all" ] && wstr="$wstr AND $(str_eq_cond userName $1)"
q_db ".mode tabs\nSELECT host,display,userName,foreignAddress,sessionId\
FROM $sqtname" "$wstr" "ORDER BY startTime DESC;" # ! check order !
}
session_history() {
#params: userName sessionId
echo "NX> 127 Session list:"
echo
echo "Display Username Remote IP Session ID Date Status"
echo "------- --------------- --------------- -------------------------------- ------------------- -----------"
wstr=""
[ -n "$1" -a "$1" != "all" ] && wstr="$(str_eq_cond userName $1)"
[ -n "$wstr" -a -n "$2" ] && wstr="$wstr AND "
[ -n "$2" ] && wstr="$wstr sessionId='$2'"
[ -n "$wstr" ] && wstr="WHERE $wstr"
q_db ".mode tabs\nSELECT display,userName,foreignAddress,sessionId,\
datetime(startTime,'unixepoch','localtime'),status\
FROM $sqtname" "$wstr" "ORDER BY startTime;"
}
# remove all sessions older than $SESSION_HISTORY seconds in failed/closed.
session_cleanup() {
[ "$SESSION_HISTORY" -gt "-1" ] || return
let checkTime=$(date +%s)-$SESSION_HISTORY
st="Finished|Failed";
wstr="WHERE $(str_eq_cond status $st) AND startTime < $checkTime"
q_db "DELETE FROM $sqtname" "$wstr" ";"
}
session_list_all() { session_list_user "all"; }
session_add() {
#params: <session_id> <options>
shift #sessid present separately for compat only
txt=$(echo "$@" | tr '&' '\n' | tr '=' ' ')
fields=""; vals=""
while read field val; do
fields="$fields${fields:+,}$field"; vals="$vals${vals:+,}'$val'"
done <<< "$txt"
q_db "INSERT INTO $sqtname($fields) VALUES($vals);"
}
session_change() {
# <session_id> <parameter> <new_value> [<parameter> <new_value>]...
ssid="$1"; shift
setls=""
while [ -n "$1" -a -n "$2" ]; do
setls="$setls${setls:+,}$1='$2'"
shift; shift
done
q_db "UPDATE $sqtname SET $setls WHERE sessionId='$ssid';"
}
# session_set_status <session_id> <new status>
session_set_status() { session_change "$1" "status" "$2"; }
# session_running <session_id> (? now dublicated session_find_id_user ?)
# return: true if running, false if not
session_running() { session_find_id_user "$1"; }
session_close() {
#param: <session_id>
if [ "$SESSION_HISTORY" = "0" ] ; then
q_db "DELETE FROM $sqtname WHERE sessionId='$1';"
else
session_change "$1" "status" "Finished" "endTime" "$(date +%s)"
fi
}
session_fail() {
#param: <session_id>
if [ "$SESSION_HISTORY" = "0" ] ; then
q_db "DELETE FROM $sqtname WHERE sessionId='$1';"
else
session_change "$1" "status" "Failed" "endTime" "$(date +%s)"
fi
}
session_suspend() {
#param: <session_id>
session_change "$1" "status" "Suspended" "foreignAddress" "-"
}
#
# end of library
#
#
# Main nxserver <-> nxclient communication module
#
# do not run in server mode loop
SERVER_MODE="0"
# For users nxfree and nx run in SERVER MODE
[ "$USER" = "nxfree" -o "$USER" = "nx" ] && SERVER_MODE="1"
# We can override usermode via environment var
[ "$NX_USERMODE" = "1" ] && ENABLE_USERMODE_AUTHENTICATION="1"
# When usermode is 1, we only run in server loop
# if nxserver was run without any arguments or just with -c nxserver.
if [ "$ENABLE_USERMODE_AUTHENTICATION" = "1" ]; then
# do not run in server mode loop regardless of username
SERVER_MODE="0"
[ -z "$*" -o "$*" = "-c $PATH_BIN/nxserver" ] && SERVER_MODE="1"
# Reread the config files (so that $USER.node.conf get sourced)
. $(PATH=$(cd $(dirname $0) && pwd):$PATH which nxloadconfig) --userconf
# We might need to reactivate this now
ENABLE_USERMODE_AUTHENTICATION="1"
# export the necessary variables
export NX_SESS_DIR="$USER_FAKE_HOME/.nx/db/"
export NX_LOGFILE="$USER_FAKE_HOME/.nx/temp/nxserver.log"
mkdir -p $(dirname $NX_LOGFILE)
init_db
# we are logged in already
LOGIN_SUCCESS="1"
LOGIN_METHOD="USERMODE"
# we do not use SLAVE mode for usermode
ENABLE_SLAVE_MODE="0"
# we do not use loadbalancing mode for usermode
LOAD_BALANCE_SERVERS=""
fi
if [ "$SERVER_MODE" = "1" ]; then
#
# needed for slave mode
#
nxnode_login_stop_slave() {
if [ -n "$NXNODE_LOGIN_SLAVE" ]; then
log 3 "Info: Closing connection to slave with pid $NXNODE_LOGIN_SLAVE."
# send quit command
echo "--quit" >&$NX_COMMFD
# kill process
kill "$NXNODE_LOGIN_SLAVE"
sleep 2
kill -0 "$NXNODE_LOGIN_SLAVE" && kill -9 "$NXNODE_LOGIN_SLAVE"
unset NXNODE_LOGIN_SLAVE
fi
}
nxnode_login() {
PASS="$1"; shift
if [ "$NXNODE_LOGIN_SLAVE_ENABLED" != "1" ]; then
NXNODE_TOSEND="$NXNODE_TOSEND" echo $PASS | \
$PATH_BIN/nxnode-login "$@"
else
if [ -z "$NXNODE_LOGIN_SLAVE" -a -z "$NX_TRUSTED_USER" ]; then
# Send password
echo "$PASS" >&$NX_COMMFD
# Connect to NXNODE
( $PATH_BIN/nxnode-login "$1" "$2" "$3" "$4" "$5" \
"--slave" <&$NX_SERVERFD >&$NX_SERVERFD 2>&$NX_SERVERFD \
|| echo "FREENX> 716 Slave mode failed to start." \
>&$NX_SERVERFD ) &
NXNODE_LOGIN_SLAVE="$!"
disown $!
trap nxnode_login_stop_slave EXIT
NXNODE_SLAVE_STARTED=""
# FIXME: Make timeout configurable
while read -t 10 line <&$NX_COMMFD
do
log 6 "$line"
case "$line" in
"NX> 716 Slave mode started successfully.")
NXNODE_SLAVE_STARTED="1"
break
;;
"FREENX> 716 Slave mode failed to start.")
break
;;
esac
done
if [ -z "$NXNODE_SLAVE_STARTED" ]; then
# stop it, if it still exists
nxnode_login_stop_slave
unset NXNODE_LOGIN_SLAVE
# return an error
return 1
fi
fi
#send CMD to nxnode
echo "$6" >&$NX_COMMFD
[ -n "$NXNODE_TOSEND" ] && echo "$NXNODE_TOSEND" >&$NX_COMMFD
NXNODE_RETURN="1"
if [ -z "$NXNODE_READER" ]; then
while read line <&$NX_COMMFD
do
log 6 "nxnode_reader: $line"
echo "$line"
case "$line" in
"NX> 716"*)
NXNODE_RETURN="0"
;;
"NX> 1001"*)
break
;;
esac
done
fi
test "$NXNODE_RETURN" = "0"
fi
}
nxnode_login_register_reader() {
# Register a reader
NXNODE_READER="1"
}
# Start!
init_db
log 3 "-- NX SERVER START: $@ - ORIG_COMMAND=$SSH_ORIGINAL_COMMAND"
if [ "$ENABLE_SERVER_FORWARD" = "1" -a -n "$SERVER_FORWARD_HOST" ]; then
log 3 "Info: Forwarding connection to $SERVER_FORWARD_HOST with secret key $SERVER_FORWARD_KEY."
$COMMAND_SSH -i "$SERVER_FORWARD_KEY" "-p$SERVER_FORWARD_PORT" \
"nx@$SERVER_FORWARD_HOST" "host=$SERVER_NAME"
exit 0
fi
# Get the hostname out of SSH_ORIGINAL_COMMAND
PREFERRED_HOST=$(echo $SSH_ORIGINAL_COMMAND | tr '&' '\n' | grep "^host=" | \
cut -d'=' -f2)
# forward the connection to commercial NoMachine server?
if [ "$ENABLE_NOMACHINE_FORWARD_PORT" = "1" -a "$NOMACHINE_FORWARD_PORT" = \
"$(echo $SSH_CLIENT $SSH2_CLIENT| cut -d' ' -f3)" -a \
-n "$NOMACHINE_SERVER" ]; then
log 3 "Info: Detected SSH destination port $NOMACHINE_FORWARD_PORT. Forwarding connection to commercial NoMachine server."
exec $NOMACHINE_SERVER
log 1 "Error: Forwarding to NoMachine Server $NOMACHINE_SERVER failed. Using FreeNX server instead."
fi
#
# nxnode slave mode preparations
#
NXNODE_LOGIN_SLAVE_ENABLED="0"; NXNODE_LOGIN_SLAVE=""
# slave mode does not work with load balancing
if [ -n "$LOAD_BALANCE_SERVERS" -a "$ENABLE_SLAVE_MODE" = "1" ]; then
log 2 "Warning: Disabled slave mode. It does not work together with load balancing."
ENABLE_SLAVE_MODE="0"
fi
if [ "$ENABLE_SLAVE_MODE" = "1" -a "$NXSERVER_HELPER_ACTIVE" != "1" -a \
-z "$NX_TRUSTED_USER" ]; then
export SSH_ORIGINAL_COMMAND; export NXSERVER_HELPER_ACTIVE="1"
exec $PATH_BIN/nxserver-helper "$0"
log 1 "Error: Execution of $PATH_BIN/nxserver-helper failed. Disabling slave mode of nxnode."
export NXSERVER_HELPER_ACTIVE="0"
fi
if [ "$ENABLE_SLAVE_MODE" = "1" -a "$NXSERVER_HELPER_ACTIVE" = "1" ]; then
log 3 "Info: Using fds #$NX_SERVERFD and #$NX_COMMFD for communication with nxnode."
NXNODE_LOGIN_SLAVE_ENABLED="1"
fi
if [ -n "$NX_TRUSTED_USER" -a -n "$NX_COMMFD" ]; then
NXNODE_LOGIN_SLAVE_ENABLED="1"
USER=$NX_TRUSTED_USER
# check that communication works
nxnode_login "" -- su "$USER" "" "$PATH_BIN/nxnode" --check 2>&1 >/dev/null
if [ $? -ne 0 ]; then
log 1 "Error: Could not establish communication with trusted user ($USER) nxnode."
echo_x "NX> 404 ERROR: wrong password or login"
echo_x "NX> 999 Bye"
exit 1
fi
LOGIN_SUCCESS="1"; LOGIN_METHOD="SU"
log 3 "Info: Using fd #$NX_COMMFD for communication with trusted user ($USER) established nxnode."
# Reread the config files (so that $USER.node.conf get sourced)
. $(PATH=$(cd $(dirname $0) && pwd):$PATH which nxloadconfig) --userconf
elif [ "$NX_USERMODE" = "1" ]; then
log 3 "Info: Usermode authentication: Logged in as $USER."
else
echo_x "HELLO NXSERVER - Version $NX_VERSION $NX_LICENSE"
# Login stage
while true; do
echo_x -n "NX> 105 "
read CMD
# FIXME?
[ "$CMD" = "" ] && CMD="quit"
echo_x "$CMD"
case "$CMD" in
quit|QUIT)
echo_x "Quit"
echo_x "NX> 999 Bye"
exit 0
;;
exit|EXIT)
echo_x "Exit"
echo_x "NX> 999 Bye"
exit 0
;;
bye|BYE)
echo_x "Bye"
echo_x "NX> 999 Bye"
exit 0
;;
hello*|HELLO*)
PROTO=$(echo $CMD | sed 's/.*Version \(.*\)/\1/g') #'
echo_x "NX> 134 Accepted protocol: $PROTO"
if [ "$PROTO" = "1.3.0" -o "$PROTO" = "1.3.2" ]
then
[ "$ENABLE_AUTORECONNECT_BEFORE_140" = "1" ] && \
ENABLE_AUTORECONNECT="1"
fi
;;
"set auth_mode*"|"SET AUTH_MODE*")
if [ "$CMD" = "set auth_mode password" -o \
"$CMD" = "SET AUTH_MODE PASSWORD" ]; then
echo_x "Set auth_mode: password"
else
echo_x "NX> 500 ERROR: unknown auth mode ''"
fi
;;
login|LOGIN)
LOGIN_SUCCESS="0"
echo_x -n "NX> 101 User: "
read USER2
echo_x $USER2
echo_x -n "NX> 102 Password: "
old_ifs="$IFS"
export IFS=$'\n'
read -r -s PASS
export IFS="$old_ifs"
echo_x ""
log 6 -n "Info: Auth method: "
# USER already logged in?
if [ "$ENABLE_USERMODE_AUTHENTICATION" = "1" ]; then
LOGIN_SUCCESS="1"
# we have read the user config already above,
# so we don't get any new information here
break
fi
USER=$USER2
# Guest authentication
if [ "$USER" = "NX guest user" ]; then
if [ "$ENABLE_GUEST_LOGIN" != "1" -o \
! -x "$COMMAND_GUEST_LOGIN" ]; then
if [ "$ENABLE_GUEST_LOGIN" != "1" ]; then
echo_x "NX> 404 ERROR: guest authentication not enabled"
else
echo_x "NX> 404 ERROR: $COMMAND_GUEST_LOGIN not correct"
fi
echo_x "NX> 999 Bye"
if [ "$ENABLE_LOG_FAILED_LOGINS" = "1" ]; then
logger -t nxserver -i -p auth.info \
"($(whoami)) Failed login for user=$USER from IP=$(echo $SSH_CLIENT \
| awk '{print $1}')"
fi
exit 1
fi
log 6 -n "guest "
nxnode_login "" -- guest "" "" "$COMMAND_GUEST_LOGIN" \
--check 2>&1 >/dev/null
if [ $? -eq 0 ]; then LOGIN_SUCCESS="1"; LOGIN_METHOD="GUEST"; fi
fi
# PASSDB based auth
if [ "$ENABLE_PASSDB_AUTHENTICATION" = "1" -a \
"$LOGIN_SUCCESS" = "0" ]; then
log 6 -n "passdb "
if [ $(passdb_get_crypt_pass "$PASS") = \
$(passdb_get_pass "$USER") ]; then
LOGIN_SUCCESS="1"; LOGIN_METHOD="PASSDB"
fi
fi
# SSH based auth
if [ "$ENABLE_SSH_AUTHENTICATION" = "1" -a "$LOGIN_SUCCESS" = "0" ]; then
log 6 -n "ssh "
export COMMAND_SSH
nxnode_login "$PASS" -- ssh "$USER" "$SSHD_PORT" \
"$PATH_BIN/nxnode" --check 2>&1 >/dev/null
if [ $? -eq 0 ]; then LOGIN_SUCCESS="1"; LOGIN_METHOD="SSH"; fi
fi
# SU based auth
if [ "$ENABLE_SU_AUTHENTICATION" = "1" -a \
"$LOGIN_SUCCESS" = "0" ]; then
log 6 -n "su "
nxnode_login "$PASS" -- su "$USER" "" \
"$PATH_BIN/nxnode" --check 2>&1 >/dev/null
if [ $? -eq 0 ]; then LOGIN_SUCCESS="1"; LOGIN_METHOD="SU"; fi
fi
# Check if user in passdb
if [ "$ENABLE_USER_DB" = "1" ]; then
log 6 "userdb check"
passdb_user_exists "$USER" || LOGIN_SUCCESS="0"
fi
log 6 ""
if [ "$LOGIN_SUCCESS" = "1" ]; then
# Reread the config files (so that $USER.node.conf get sourced)
. $(PATH=$(cd $(dirname $0) && pwd):$PATH which nxloadconfig) --userconf
break
else
echo_x "NX> 404 ERROR: wrong password or login"
echo_x "NX> 999 Bye"
if [ "$ENABLE_LOG_FAILED_LOGINS" = "1" ]; then
logger -t nxserver -i -p auth.info \
"($(whoami)) Failed login for user=$USER from IP=$(echo $SSH_CLIENT \
| awk '{print $1}')"
fi
exit 1
fi
;;
esac
done
fi
echo_x "NX> 103 Welcome to: $SERVER_NAME user: $USER"
# Add the slave mode shutdown trap (just in case)
[ -n "$NXNODE_LOGIN_SLAVE" ] && trap nxnode_login_stop_slave EXIT
# remove old session infos from history
session_cleanup
#
# call it with: server_get_params $CMD # no ""!
#
server_get_params() {
SERVER_PARAMS=$(echo "$@" | sed "s/^$1/\"/g; s/\" --/\&/g; s/\"//g; s/%20/ /g")
if [ "$SERVER_PARAMS" = "" ]; then
echo_x -n "NX> 106 Parameters: "
read SERVER_PARAMS2
SERVER_PARAMS=$(echo $SERVER_PARAMS2 | sed 's/%2B/+/g; s/%20/ /g')
echo_x
fi
}
nxnode_start() {
:
#CMD="$1"
#shift
#echo "$@" | $PATH_BIN/nxnode "$CMD"
}
#NX> 1002 Commit
#NX> 1006 Session status: running
server_nxnode_start() {
CMD="$1"; USER="$2";
shift; shift;
# Find NODE_HOSTNAME
NODE_HOSTNAME=""
CMDLINE="$@"
uniqueid=$(getparam uniqueid)
[ -z "$uniqueid" ] && uniqueid=$(getparam sessionid)
[ -z "$uniqueid" ] && uniqueid=$(getparam session_id)
CMDLINE=$(session_get "$uniqueid")
NODE_HOSTNAME="$(getparam host)"
[ -z "$NODE_HOSTNAME" ] && NODE_HOSTNAME="127.0.0.1"
export NODE_HOSTNAME
# Use nxnode-login?
if [ "$LOGIN_METHOD" = "GUEST" ]; then
NXNODE_TOSEND="$@" nxnode_login "" -- \
guest "" "" "$COMMAND_GUEST_LOGIN" "$CMD" 2>&1 | log_tee
elif [ "$LOGIN_METHOD" = "SSH" ]; then
export COMMAND_SSH
NXNODE_TOSEND="$@" nxnode_login "$PASS" -- \
ssh "$USER" "$SSHD_PORT" "$PATH_BIN/nxnode" "$CMD" 2>&1 | log_tee
elif [ "$LOGIN_METHOD" = "SU" ]; then
NXNODE_TOSEND="$@" nxnode_login "$PASS" -- \
su "$USER" "" "$PATH_BIN/nxnode" "$CMD" 2>&1 | log_tee
elif [ "$LOGIN_METHOD" = "USERMODE" ]; then
# we need to unset SSH_* variables so that nxnode
# chooses the right accept= value.
unset SSH_CLIENT SSH_CLIENT2
echo "$@" | $PATH_BIN/nxnode "$CMD" 2>&1 | log_tee
else
echo "$@" | $COMMAND_SSH -l "$USER" "$NODE_HOSTNAME" -p $SSHD_PORT \
-x -2 -i $NX_ETC_DIR/users.id_dsa -o 'PubkeyAuthentication yes' \
-o 'RSAAuthentication yes' -o 'RhostsAuthentication no' \
-o 'PasswordAuthentication no' -o 'RhostsRSAAuthentication no' \
-o 'StrictHostKeyChecking no' $PATH_BIN/nxnode "$CMD" | log_tee
fi
}
server_add_usession() {
[ "$ENABLE_USESSION" = "1" ] || return
$COMMAND_SESSREG -l ":$SESS_DISPLAY" -h "$USERIP" -a $USER 2>&1 | \
log_error
}
server_remove_usession() {
[ "$ENABLE_USESSION" = "1" ] || return
$COMMAND_SESSREG -l ":$SESS_DISPLAY" -h "$USERIP" -d $USER 2>&1 | \
log_error
}
server_nxnode_echo() {
log 6 "server_nxnode_echo: $@"
[ "$SERVER_CHANNEL" = "1" ] && /bin/echo "$@"
[ "$SERVER_CHANNEL" = "2" ] && /bin/echo "$@" >&2
}
server_nxnode_exit_func() {
log 1 "Info: Emergency-Shutting down due to kill signal ..."
session_fail $uniqueid
server_remove_usession
# remove lock file
[ -e "/tmp/.nX$SESS_DISPLAY-lock" ] && rm -f /tmp/.nX$SESS_DISPLAY-lock
# Kill possible slave node
nxnode_login_stop_slave
}
server_nxnode_start_wait() {
if [ "$1" = "--startsession" ]; then
server_add_usession
# We need to stop sending things when a SIGPIPE arrives
trap "SERVER_CHANNEL=0" SIGPIPE
trap server_nxnode_exit_func EXIT
SERVER_CHANNEL=1; KILL_WAIT_PID=1
server_nxnode_start "$@" | while read CMD;
do
case "$CMD" in
"NX> 706"*)
if [ -x "$COMMAND_NXSHADOWACL" ]; then
# check if we should save the cookie
$COMMAND_NXSHADOWACL "$USER"
if [ $? -eq 0 ]; then
SHADOW_COOKIE=$(echo $CMD | cut -d: -f2 | sed 's/ //g')
session_change "$uniqueid" "shadowcookie" "$SHADOW_COOKIE"
fi
fi
;;
"NX> 1006"*|"NX> 1005"*|"NX> 1009"*)
case "$CMD" in
*running*)
[ "$KILL_WAIT_PID" = "1" ] && kill $SERVER_WAIT_PID
KILL_WAIT_PID=0
log 6 session_set_status $uniqueid "Running"
session_set_status $uniqueid "Running"
[ "$SERVER_CHANNEL" = "1" ] && SERVER_CHANNEL=2
;;
*closed*)
log 6 session_close $uniqueid
session_close $uniqueid
;;
*suspended*)
[ "$KILL_WAIT_PID" = "1" ] && kill $SERVER_WAIT_PID