aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/programs/Xserver/hw/nxagent/NXdispatch.c
blob: 852715fdfbfc447853417c1517ee6e1d1fcbef8d (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2014 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2011-2016 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2014-2016 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2014-2016 Ulrich Sibiller <uli42@gmx.de>                 */
/* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)           */
/*                                                                        */
/* NXAGENT, NX protocol compression and NX extensions to this software    */
/* are copyright of the aforementioned persons and companies.             */
/*                                                                        */
/* Redistribution and use of the present software is allowed according    */
/* to terms specified in the file LICENSE which comes in the source       */
/* distribution.                                                          */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/* NOTE: This software has received contributions from various other      */
/* contributors, only the core maintainers and supporters are listed as   */
/* copyright holders. Please contact us, if you feel you should be listed */
/* as copyright holder, as well.                                          */
/*                                                                        */
/**************************************************************************/

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

Copyright 1987, 1989, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

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
OPEN GROUP 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.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.


Copyright 1987, 1989 by Digital Equipment Corporation, Maynard, Massachusetts.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

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

/* The panoramix components contained the following notice */
/*****************************************************************

Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.

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.

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
DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL 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.

Except as contained in this notice, the name of Digital Equipment Corporation
shall not be used in advertising or otherwise to promote the sale, use or other
dealings in this Software without prior written authorization from Digital
Equipment Corporation.

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


#ifdef __sun
#define False 0
#define True 1
#endif

#include <X11/fonts/fontstruct.h>

#define GC XlibGC
#include <nx-X11/Xlib.h>
#undef GC

#include "../../dix/dispatch.c"

#include "windowstr.h"

#include "Atoms.h"
#include "Splash.h"
#include "Client.h"
#include "Clipboard.h"
#include "Reconnect.h"
#include "Millis.h"
#include "Font.h"
#include <nx/Shadow.h>
#include "Handlers.h"
#include "Keyboard.h"

const int nxagentMaxFontNames = 10000;

/*
 * This allows the agent to exit if no
 * client is connected within a timeout.
 */

int nxagentClients = 0;

void nxagentWaitDisplay(void);

void nxagentListRemoteFonts(const char *, int);

/*
 * Timeouts based on screen saver time.
 */

int nxagentAutoDisconnectTimeout = 0;

#include "Xatom.h"

/*
 * Set here the required log level.
 */

#define PANIC
#define WARNING
#undef  TEST
#undef  WATCH

/*
 * Log begin and end of the important handlers.
 */

#undef  BLOCKS

#ifdef WATCH
#include "unistd.h"
#endif

#ifdef TEST
#include "Literals.h"
#endif

#ifdef VIEWPORT_FRAME

extern WindowPtr nxagentViewportFrameLeft;
extern WindowPtr nxagentViewportFrameRight;
extern WindowPtr nxagentViewportFrameAbove;
extern WindowPtr nxagentViewportFrameBelow;

#define IsViewportFrame(pWin) ((pWin) == nxagentViewportFrameLeft || \
                                   (pWin) == nxagentViewportFrameRight || \
                                       (pWin) == nxagentViewportFrameAbove || \
                                           (pWin) == nxagentViewportFrameBelow)

#else

#define IsViewportFrame(pWin) (0)

#endif /* #ifdef VIEWPORT_FRAME */

extern int nxagentMaxAllowedResets;

extern int nxagentFindClientResource(int, RESTYPE, void *);

#ifdef NXAGENT_CLIPBOARD
extern int nxagentPrimarySelection;
extern int nxagentClipboardSelection;
extern int nxagentMaxSelections;
#endif

extern int nxOpenFont(ClientPtr, XID, Mask, unsigned, char*);

void
InitSelections(void)
{
    xorg_InitSelections();

#ifdef NXAGENT_CLIPBOARD
    {
      Selection *newsels;
      newsels = (Selection *)malloc(nxagentMaxSelections * sizeof(Selection));
      if (!newsels)
        return;
      NumCurrentSelections += nxagentMaxSelections;
      CurrentSelections = newsels;

      CurrentSelections[nxagentPrimarySelection].selection = XA_PRIMARY;
      CurrentSelections[nxagentPrimarySelection].lastTimeChanged = ClientTimeToServerTime(0);
      CurrentSelections[nxagentPrimarySelection].window = screenInfo.screens[0]->root->drawable.id;
      CurrentSelections[nxagentPrimarySelection].pWin = NULL;
      CurrentSelections[nxagentPrimarySelection].client = NullClient;

      CurrentSelections[nxagentClipboardSelection].selection = MakeAtom("CLIPBOARD", 9, 1);
      CurrentSelections[nxagentClipboardSelection].lastTimeChanged = ClientTimeToServerTime(0);
      CurrentSelections[nxagentClipboardSelection].window = screenInfo.screens[0]->root->drawable.id;
      CurrentSelections[nxagentClipboardSelection].pWin = NULL;
      CurrentSelections[nxagentClipboardSelection].client = NullClient;
    }
#endif
}

#define MAJOROP ((xReq *)client->requestBuffer)->reqType

void
Dispatch(void)
{
    register int        *clientReady;     /* array of request ready clients */
    register int	result;
    register ClientPtr	client;
    register int	nready;
    register HWEventQueuePtr* icheck = checkForInput;
    long			start_tick;

    nextFreeClientID = 1;
    InitSelections();
    nClients = 0;

#ifdef NXAGENT_SERVER
    /*
     * The agent initialization was successfully
     * completed. We can now handle our clients.
     */

    #ifdef XKB

    nxagentInitXkbWrapper();

    nxagentTuneXkbWrapper();

    #endif

    #ifdef NXAGENT_ONSTART

    /*
     * Set NX_WM property (used by NX client to identify the agent's
     * window) three seconds since the first client connects.
     */

    unsigned int nxagentWMtimeout = GetTimeInMillis() + 3000;

    #endif

#endif /* NXAGENT_SERVER */
    clientReady = (int *) malloc(sizeof(int) * MaxClients);
    if (!clientReady)
	return;

#ifdef NXAGENT_SERVER
    #ifdef WATCH

    fprintf(stderr, "Dispatch: Watchpoint 12.\n");

/*
Reply   Total	Cached	Bits In			Bits Out		Bits/Reply	  Ratio
------- -----	------	-------			--------		----------	  -----
#3      1		352 bits (0 KB) ->	236 bits (0 KB) ->	352/1 -> 236/1	= 1.492:1
#14     1		256 bits (0 KB) ->	101 bits (0 KB) ->	256/1 -> 101/1	= 2.535:1
#16     1		256 bits (0 KB) ->	26 bits (0 KB) ->	256/1 -> 26/1	= 9.846:1
#20     2	2	12256 bits (1 KB) ->	56 bits (0 KB) ->	6128/1 -> 28/1	= 218.857:1
#43     1		256 bits (0 KB) ->	45 bits (0 KB) ->	256/1 -> 45/1	= 5.689:1
#47     2	2	42304 bits (5 KB) ->	49 bits (0 KB) ->	21152/1 -> 24/1	= 863.347:1
#98     1		256 bits (0 KB) ->	34 bits (0 KB) ->	256/1 -> 34/1	= 7.529:1
*/

    sleep(30);

    #endif

    #ifdef TEST
    fprintf(stderr, "Dispatch: Value of dispatchException is [%x].\n",
                dispatchException);

    fprintf(stderr, "Dispatch: Value of dispatchExceptionAtReset is [%x].\n",
                dispatchExceptionAtReset);
    #endif

    if (!(dispatchException & DE_TERMINATE))
        dispatchException = 0;
#endif /* NXAGENT_SERVER */

    while (!dispatchException)
    {
        if (*icheck[0] != *icheck[1])
	{
	    ProcessInputEvents();
	    FlushIfCriticalOutputPending();
	}

#ifdef NXAGENT_SERVER
        /*
         * Ensure we remove the splash after the timeout.
         * Initializing clientReady[0] to -1 will tell
         * WaitForSomething() to yield control after the
         * timeout set in clientReady[1].
         */

        clientReady[0] = 0;

        if (nxagentSplashWindow != None || (nxagentOption(Xdmcp) == 1 && nxagentXdmcpUp == 0))
        {
          #ifdef TEST
          fprintf(stderr, "******Dispatch: Requesting a timeout of [%d] Ms.\n",
                      NXAGENT_WAKEUP);
          #endif

          clientReady[0] = -1;
          clientReady[1] = NXAGENT_WAKEUP;
        }

        if (serverGeneration > nxagentMaxAllowedResets &&
                nxagentSessionState == SESSION_STARTING &&
                    (nxagentOption(Xdmcp) == 0 || nxagentXdmcpUp == 1))
        {
          #ifdef NX_DEBUG_INPUT
          fprintf(stderr, "Session: Session started at '%s' timestamp [%lu].\n",
                      GetTimeAsString(), GetTimeInMillis());
          #else
          fprintf(stderr, "Session: Session started at '%s'.\n",
                      GetTimeAsString());
          #endif

          nxagentSessionState = SESSION_UP;
          saveAgentState("RUNNING");
        }

        #ifdef BLOCKS
        fprintf(stderr, "[End dispatch]\n");
        #endif
#endif /* NXAGENT_SERVER */

	nready = WaitForSomething(clientReady);

#ifdef NXAGENT_SERVER
        #ifdef BLOCKS
        fprintf(stderr, "[Begin dispatch]\n");
        #endif

        #ifdef TEST
        fprintf(stderr, "******Dispatch: Running with [%d] clients ready.\n",
                    nready);
        #endif
        
        #ifdef NXAGENT_ONSTART

	/*
	 * If the timeout is expired set the selection informing the
	 * NX client that the agent is ready.
	 */

	if (nxagentWMtimeout < GetTimeInMillis())
	{
	  nxagentRemoveSplashWindow();
	}

        nxagentClients = nClients;

        #endif
#endif /* NXAGENT_SERVER */

	if (nready)
	{
	    clientReady[0] = SmartScheduleClient (clientReady, nready);
	    nready = 1;
	}
       /***************** 
	*  Handle events in round robin fashion, doing input between 
	*  each round 
	*****************/

	while (!dispatchException && (--nready >= 0))
	{
	    client = clients[clientReady[nready]];
	    if (! client)
	    {
		/* KillClient can cause this to happen */
		continue;
	    }
	    /* GrabServer activation can cause this to be true */
	    if (grabState == GrabKickout)
	    {
		grabState = GrabActive;
		break;
	    }
	    isItTimeToYield = FALSE;
 
            requestingClient = client;
	    start_tick = SmartScheduleTime;
	    while (!isItTimeToYield)
	    {
	        if (*icheck[0] != *icheck[1])
		{
		    ProcessInputEvents();
		    FlushIfCriticalOutputPending();
		}
		if ((SmartScheduleTime - start_tick) >= SmartScheduleSlice)
		{
		    /* Penalize clients which consume ticks */
		    if (client->smart_priority > SMART_MIN_PRIORITY)
			client->smart_priority--;
		    break;
		}
		/* now, finally, deal with client requests */

#ifdef NXAGENT_SERVER
                #ifdef TEST
                fprintf(stderr, "******Dispatch: Reading request from client [%d].\n",
                            client->index);
                #endif
#endif /* NXAGENT_SERVER */

	        result = ReadRequestFromClient(client);
	        if (result <= 0) 
	        {
		    if (result < 0)
			CloseDownClient(client);
		    break;
	        }

#ifdef NXAGENT_SERVER
                #ifdef TEST

                else
                {

                    if (MAJOROP > 127)
                    {
                      fprintf(stderr, "******Dispatch: Read [Extension] request OPCODE#%d MINOR#%d "
                                  "size [%d] client [%d].\n", MAJOROP, *((char *) client->requestBuffer + 1),
                                      client->req_len << 2, client->index);
                    }
                    else
                    {
                      fprintf(stderr, "******Dispatch: Read [%s] request OPCODE#%d size [%d] client [%d].\n",
                                  nxagentRequestLiteral[MAJOROP], MAJOROP, client->req_len << 2,
                                      client->index);
                    }
                }

                #endif
#endif

		client->sequence++;
		if (result > (maxBigRequestSize << 2))
		    result = BadLength;
		else
                {
                    result = (* client->requestVector[MAJOROP])(client);
#ifdef NXAGENT_SERVER
                    #ifdef TEST

                    if (MAJOROP > 127)
                    {
                      fprintf(stderr, "******Dispatch: Handled [Extension] request OPCODE#%d MINOR#%d "
                                  "size [%d] client [%d] result [%d].\n", MAJOROP,
                                      *((char *) client->requestBuffer + 1), client->req_len << 2,
                                          client->index, result);
                    }
                    else
                    {
                      fprintf(stderr, "******Dispatch: Handled [%s] request OPCODE#%d size [%d] client [%d] "
                                  "result [%d].\n", nxagentRequestLiteral[MAJOROP], MAJOROP,
                                      client->req_len << 2, client->index, result);
                    }

                    #endif

                    /*
                     * Can set isItTimeToYield to force
                     * the dispatcher to pay attention
                     * to another client.
                     */

                    nxagentDispatchHandler(client, client->req_len << 2, 0);
#endif
                }

                if (!SmartScheduleSignalEnable)
                    SmartScheduleTime = GetTimeInMillis();

		if (result != Success) 
		{
		    if (client->noClientException != Success)
                        CloseDownClient(client);
                    else
		        SendErrorToClient(client, MAJOROP,
					  MinorOpcodeOfRequest(client),
					  client->errorValue, result);
		    break;
	        }
#ifdef DAMAGEEXT
		FlushIfCriticalOutputPending ();
#endif
	    }
	    FlushAllOutput();
	    client = clients[clientReady[nready]];
	    if (client)
		client->smart_stop_tick = SmartScheduleTime;
	    requestingClient = NULL;
	}
	dispatchException &= ~DE_PRIORITYCHANGE;
    }
#if defined(DDXBEFORERESET)
    ddxBeforeReset ();
#endif

#ifdef NXAGENT_SERVER
    /* FIXME: maybe move the code up to the KillAllClients() call to ddxBeforeReset? */
    if ((dispatchException & DE_RESET) && 
            (serverGeneration > nxagentMaxAllowedResets))
    {
        dispatchException &= ~DE_RESET;
        dispatchException |= DE_TERMINATE;

        fprintf(stderr, "Info: Reached threshold of maximum allowed resets.\n");
    }

    nxagentResetAtomMap();

    if (serverGeneration > nxagentMaxAllowedResets)
    {
      /*
       * The session is terminating. Force an I/O
       * error on the display and wait until the
       * NX transport is gone.
       */
  
      fprintf(stderr, "Session: Terminating session at '%s'.\n", GetTimeAsString());
      saveAgentState("TERMINATING");

      nxagentWaitDisplay();

      fprintf(stderr, "Session: Session terminated at '%s'.\n", GetTimeAsString());
    }

    if (nxagentOption(Shadow) == 1)
    {
      NXShadowDestroy();
    }
    saveAgentState("TERMINATED");
#endif /* NXAGENT_SERVER */

    KillAllClients();
    free(clientReady);
    dispatchException &= ~DE_RESET;
}

#undef MAJOROP

int
ProcReparentWindow(register ClientPtr client)
{
    register WindowPtr pWin, pParent;
    REQUEST(xReparentWindowReq);
    register int result;

    REQUEST_SIZE_MATCH(xReparentWindowReq);
    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
					   DixWriteAccess);
    if (!pWin)
        return(BadWindow);

#ifdef NXAGENT_SERVER
    nxagentRemoveSplashWindow();
#endif

    pParent = (WindowPtr)SecurityLookupWindow(stuff->parent, client,
					      DixWriteAccess);
    if (!pParent)
        return(BadWindow);
    if (SAME_SCREENS(pWin->drawable, pParent->drawable))
    {
        if ((pWin->backgroundState == ParentRelative) &&
            (pParent->drawable.depth != pWin->drawable.depth))
            return BadMatch;
	if ((pWin->drawable.class != InputOnly) &&
	    (pParent->drawable.class == InputOnly))
	    return BadMatch;
        result =  ReparentWindow(pWin, pParent, 
			 (short)stuff->x, (short)stuff->y, client);
	if (client->noClientException != Success)
            return(client->noClientException);
	else
            return(result);
    }
    else 
        return (BadMatch);
}


int
ProcQueryTree(register ClientPtr client)
{
    xQueryTreeReply reply = {0};
    int numChildren = 0;
    register WindowPtr pChild, pWin, pHead;
    Window  *childIDs = (Window *)NULL;
    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    pWin = (WindowPtr)SecurityLookupWindow(stuff->id, client,
					   DixReadAccess);
    if (!pWin)
        return(BadWindow);
    reply.type = X_Reply;
    reply.root = pWin->drawable.pScreen->root->drawable.id;
    reply.sequenceNumber = client->sequence;
    if (pWin->parent)
	reply.parent = pWin->parent->drawable.id;
    else
        reply.parent = (Window)None;
    pHead = RealChildHead(pWin);
    for (pChild = pWin->lastChild; pChild != pHead; pChild = pChild->prevSib)
#ifdef NXAGENT_SERVER
    {
        if (!IsViewportFrame(pChild))
        {
            numChildren++;
        }

    }
#else
        numChildren++;
#endif
    if (numChildren)
    {
	int curChild = 0;

	childIDs = (Window *) malloc(numChildren * sizeof(Window));
	if (!childIDs)
	    return BadAlloc;
	for (pChild = pWin->lastChild; pChild != pHead; pChild = pChild->prevSib)
#ifdef NXAGENT_SERVER
	{
            if (!IsViewportFrame(pChild))
            {
	        childIDs[curChild++] = pChild->drawable.id;
            }
        }
#else
            childIDs[curChild++] = pChild->drawable.id;
#endif
    }
    
    reply.nChildren = numChildren;
    reply.length = (numChildren * sizeof(Window)) >> 2;
    
    WriteReplyToClient(client, sizeof(xQueryTreeReply), &reply);
    if (numChildren)
    {
    	client->pSwapReplyFunc = (ReplySwapPtr) Swap32Write;
	WriteSwappedDataToClient(client, numChildren * sizeof(Window), childIDs);
	free(childIDs);
    }

    return(client->noClientException);
}


int
ProcConvertSelection(register ClientPtr client)
{
    Bool paramsOkay;
    xEvent event;
    WindowPtr pWin;
    REQUEST(xConvertSelectionReq);

    REQUEST_SIZE_MATCH(xConvertSelectionReq);
    pWin = (WindowPtr)SecurityLookupWindow(stuff->requestor, client,
					   DixReadAccess);
    if (!pWin)
        return(BadWindow);

#ifdef NXAGENT_CLIPBOARD
    if (((stuff->selection == XA_PRIMARY) ||
           (stuff->selection == MakeAtom("CLIPBOARD", 9, 0))) &&
               nxagentOption(Clipboard) != ClipboardNone)
    {
      int i = nxagentFindCurrentSelectionIndex(stuff->selection);
      if ((i < NumCurrentSelections) && (CurrentSelections[i].window != None))
      {
        if (nxagentConvertSelection(client, pWin, stuff->selection, stuff->requestor,
                                       stuff->property, stuff->target, stuff->time))
        {
          return (client->noClientException);
        }
      }
    }
#endif

    paramsOkay = (ValidAtom(stuff->selection) && ValidAtom(stuff->target));
    if (stuff->property != None)
	paramsOkay &= ValidAtom(stuff->property);
    if (paramsOkay)
    {
	int i;

	i = 0;
	while ((i < NumCurrentSelections) && 
	       CurrentSelections[i].selection != stuff->selection) i++;
	if ((i < NumCurrentSelections) &&
#ifdef NXAGENT_SERVER
	    (CurrentSelections[i].window != None) && (CurrentSelections[i].client != NullClient)
#else
	    (CurrentSelections[i].window != None))
#endif
#ifdef XCSECURITY
	    && (!client->CheckAccess ||
		(* client->CheckAccess)(client, CurrentSelections[i].window,
					RT_WINDOW, DixReadAccess,
					CurrentSelections[i].pWin))
#endif
	    )
	{        
	    memset(&event, 0, sizeof(xEvent));
	    event.u.u.type = SelectionRequest;
	    event.u.selectionRequest.time = stuff->time;
	    event.u.selectionRequest.owner = 
			CurrentSelections[i].window;
	    event.u.selectionRequest.requestor = stuff->requestor;
	    event.u.selectionRequest.selection = stuff->selection;
	    event.u.selectionRequest.target = stuff->target;
	    event.u.selectionRequest.property = stuff->property;
	    if (TryClientEvents(
		CurrentSelections[i].client, &event, 1, NoEventMask,
		NoEventMask /* CantBeFiltered */, NullGrab))
		return (client->noClientException);
	}
	memset(&event, 0, sizeof(xEvent));
	event.u.u.type = SelectionNotify;
	event.u.selectionNotify.time = stuff->time;
	event.u.selectionNotify.requestor = stuff->requestor;
	event.u.selectionNotify.selection = stuff->selection;
	event.u.selectionNotify.target = stuff->target;
	event.u.selectionNotify.property = None;
	(void) TryClientEvents(client, &event, 1, NoEventMask,
			       NoEventMask /* CantBeFiltered */, NullGrab);
	return (client->noClientException);
    }
    else 
    {
	client->errorValue = stuff->property;
        return (BadAtom);
    }
}


int
ProcOpenFont(register ClientPtr client)
{
    int	err;
    REQUEST(xOpenFontReq);

    REQUEST_FIXED_SIZE(xOpenFontReq, stuff->nbytes);
    client->errorValue = stuff->fid;
    LEGAL_NEW_RESOURCE(stuff->fid, client);

#ifdef NXAGENT_SERVER
    char fontReq[256];
    memcpy(fontReq,(char *)&stuff[1],(stuff->nbytes<256)?stuff->nbytes:255);
    fontReq[stuff->nbytes]=0;
    if (strchr(fontReq,'*') || strchr(fontReq,'?'))
    {
#ifdef NXAGENT_FONTMATCH_DEBUG
       fprintf(stderr, "Dispatch: ProcOpenFont try to find a common font with font pattern=%s\n",fontReq);
#endif
       nxagentListRemoteFonts(fontReq, nxagentMaxFontNames);
       err = nxOpenFont(client, stuff->fid, (Mask) 0,
		stuff->nbytes, (char *)&stuff[1]);
    }
    else
#endif
    err = OpenFont(client, stuff->fid, (Mask) 0,
		stuff->nbytes, (char *)&stuff[1]);
    if (err == Success)
    {
	return(client->noClientException);
    }
    else
	return err;
}

int
ProcCloseFont(register ClientPtr client)
{
    FontPtr pFont;
    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    pFont = (FontPtr)SecurityLookupIDByType(client, stuff->id, RT_FONT,
					    DixDestroyAccess);
    if ( pFont != (FontPtr)NULL)	/* id was valid */
    {
        #ifdef NXAGENT_SERVER

        /*
         * When a client closes a font the resource
         * should not be lost if the reference counter
         * is not 0, otherwise the server will not be
         * able to find this font looping through the
         * resources.
         */

        if (pFont -> refcnt > 0)
        {
          if (nxagentFindClientResource(serverClient -> index, RT_NX_FONT, pFont) == 0)
          {
            #ifdef TEST
            fprintf(stderr, "ProcCloseFont: Switching resource for font at [%p].\n",
                        (void *) pFont);
            #endif

            nxagentFontPriv(pFont) -> mirrorID = FakeClientID(serverClient -> index);

            AddResource(nxagentFontPriv(pFont) -> mirrorID, RT_NX_FONT, pFont);

          }
          #ifdef TEST
          else
          {
            fprintf(stderr, "ProcCloseFont: Found duplicated font at [%p], "
                        "resource switching skipped.\n", (void *) pFont);
          }
          #endif
        }

        #endif

        FreeResource(stuff->id, RT_NONE);
	return(client->noClientException);
    }
    else
    {
	client->errorValue = stuff->id;
        return (BadFont);
    }
}


int
ProcListFonts(register ClientPtr client)
{
    REQUEST(xListFontsReq);

    REQUEST_FIXED_SIZE(xListFontsReq, stuff->nbytes);

#ifdef NXAGENT_SERVER
    char tmp[256];
    memcpy(tmp,(unsigned char *) &stuff[1],(stuff->nbytes<256)?stuff->nbytes:255);
    tmp[stuff->nbytes]=0;

#ifdef NXAGENT_FONTMATCH_DEBUG
    fprintf(stderr, "Dispatch: ListFont request with pattern %s max_names=%d\n",tmp,stuff->maxNames);
#endif
    nxagentListRemoteFonts(tmp, stuff -> maxNames < nxagentMaxFontNames ? nxagentMaxFontNames : stuff->maxNames);
#endif

    return ListFonts(client, (unsigned char *) &stuff[1], stuff->nbytes, 
	stuff->maxNames);
}

int
ProcListFontsWithInfo(register ClientPtr client)
{
    REQUEST(xListFontsWithInfoReq);

    REQUEST_FIXED_SIZE(xListFontsWithInfoReq, stuff->nbytes);

#ifdef NXAGENT_SERVER
    char tmp[256];
    memcpy(tmp,(unsigned char *) &stuff[1],(stuff->nbytes<256)?stuff->nbytes:255);
    tmp[stuff->nbytes]=0;
#ifdef NXAGENT_FONTMATCH_DEBUG
    fprintf(stderr, "Dispatch: ListFont with info request with pattern %s max_names=%d\n",tmp,stuff->maxNames);
#endif
    nxagentListRemoteFonts(tmp, stuff -> maxNames < nxagentMaxFontNames ? nxagentMaxFontNames :stuff->maxNames);
#endif

    return StartListFontsWithInfo(client, stuff->nbytes,
				  (unsigned char *) &stuff[1], stuff->maxNames);
}

int
ProcFreePixmap(register ClientPtr client)
{
    PixmapPtr pMap;

    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    pMap = (PixmapPtr)SecurityLookupIDByType(client, stuff->id, RT_PIXMAP,
					     DixDestroyAccess);
    if (pMap) 
    {
        #ifdef NXAGENT_SERVER

        /*
         * When a client releases a pixmap the resource
         * should not be lost if the reference counter
         * is not 0, otherwise the server will not be
         * able to find this pixmap looping through the
         * resources.
         */

        if (pMap -> refcnt > 0)
        {
          if (nxagentFindClientResource(serverClient -> index, RT_NX_PIXMAP, pMap) == 0)
          {
            #ifdef TEST
            fprintf(stderr, "ProcFreePixmap: Switching resource for pixmap at [%p].\n",
                       (void *) pMap);
            #endif

            nxagentPixmapPriv(pMap) -> mid = FakeClientID(serverClient -> index);

            AddResource(nxagentPixmapPriv(pMap) -> mid, RT_NX_PIXMAP, pMap);
          }
          #ifdef TEST
          else
          {
            fprintf(stderr, "ProcFreePixmap: Found duplicated pixmap at [%p], "
                        "resource switching skipped.\n", (void *) pMap);
          }
          #endif
        }

        #endif

	FreeResource(stuff->id, RT_NONE);
	return(client->noClientException);
    }
    else 
    {
	client->errorValue = stuff->id;
	return (BadPixmap);
    }
}


int
ProcSetScreenSaver (register ClientPtr client)
{
    int blankingOption, exposureOption;
    REQUEST(xSetScreenSaverReq);

    REQUEST_SIZE_MATCH(xSetScreenSaverReq);
    blankingOption = stuff->preferBlank;
    if ((blankingOption != DontPreferBlanking) &&
        (blankingOption != PreferBlanking) &&
        (blankingOption != DefaultBlanking))
    {
	client->errorValue = blankingOption;
        return BadValue;
    }
    exposureOption = stuff->allowExpose;
    if ((exposureOption != DontAllowExposures) &&
        (exposureOption != AllowExposures) &&
        (exposureOption != DefaultExposures))
    {
	client->errorValue = exposureOption;
        return BadValue;
    }
    if (stuff->timeout < -1)
    {
	client->errorValue = stuff->timeout;
        return BadValue;
    }
    if (stuff->interval < -1)
    {
	client->errorValue = stuff->interval;
        return BadValue;
    }

#ifdef NXAGENT_SERVER
    /*
     * The NX agent uses the screen saver procedure
     * to monitor the user activities and launch its
     * handlers (like timeout feature), so we can't
     * always allow the clients to change our values.
     */

    #ifdef TEST
    fprintf(stderr, "ProcSetScreenSaver: Called with timeout [%d] interval [%d] Blanking [%d] Exposure [%d].\n",
                stuff -> timeout, stuff -> interval, blankingOption, exposureOption);
    #endif

    if (nxagentOption(Timeout) == 0)
    {
#endif
      if (blankingOption == DefaultBlanking)
      {
	ScreenSaverBlanking = defaultScreenSaverBlanking;
      }
      else
      {
	ScreenSaverBlanking = blankingOption; 
      }

      if (exposureOption == DefaultExposures)
      {
	ScreenSaverAllowExposures = defaultScreenSaverAllowExposures;
      }
      else
      {
        ScreenSaverAllowExposures = exposureOption;
      }

      if (stuff->timeout >= 0)
      {
        ScreenSaverTime = stuff->timeout * MILLI_PER_SECOND;
      }
      else
      {
        ScreenSaverTime = defaultScreenSaverTime;
      }

      if (stuff->interval >= 0)
      {
        ScreenSaverInterval = stuff->interval * MILLI_PER_SECOND;
      }
      else
      {
        ScreenSaverInterval = defaultScreenSaverInterval;
      }

      SetScreenSaverTimer();
#ifdef NXAGENT_SERVER
    }

    #ifdef TEST

    else
    {
      fprintf(stderr, "ProcSetScreenSaver: Keeping auto-disconnect timeout set to [%d] seconds.\n",
                  nxagentOption(Timeout));
    }

    #endif
#endif
    return (client->noClientException);
}


int ProcForceScreenSaver(register ClientPtr client)
{
    REQUEST(xForceScreenSaverReq);

    REQUEST_SIZE_MATCH(xForceScreenSaverReq);

    if ((stuff->mode != ScreenSaverReset) &&
	(stuff->mode != ScreenSaverActive))
    {
	client->errorValue = stuff->mode;
        return BadValue;
    }

#ifdef NXAGENT_SERVER
    /*
     * The NX agent uses the screen saver procedure
     * to monitor the user activities and launch its
     * handlers (like timeout feature), so we can't
     * always allow the clients to force the screen
     * saver handler execution.
     */

    if (nxagentOption(Timeout) == 0)
    {
#endif
      SaveScreens(SCREEN_SAVER_FORCER, (int)stuff->mode);
#ifdef NXAGENT_SERVER
    }

    #ifdef TEST

    else
    {
      fprintf(stderr, "ProcForceScreenSaver: Ignoring the client request with mode [%d].\n",
                  stuff -> mode);
    }

    #endif
#endif

    return client->noClientException;
}


/**********************
 * CloseDownClient
 *
 *  Client can either mark his resources destroy or retain.  If retained and
 *  then killed again, the client is really destroyed.
 *********************/

void
CloseDownClient(register ClientPtr client)
{
#ifdef NXAGENT_SERVER
    /*
     * There must be a better way to hook a
     * call-back function to be called any
     * time a client is going to be closed.
     */

    nxagentClearClipboard(client, NULL);

    /*
     * Need to reset the karma counter and
     * get rid of the pending sync replies.
     */

    nxagentWakeupByReset(client);

    /*
     * Check if the client
     * is a shadow nxagent.
     */

    nxagentCheckIfShadowAgent(client);
#endif

    xorg_CloseDownClient(client);
}

/* FIXME: Instead of having a own function use the provided Callback
   mechanism */
int
InitClientPrivates(ClientPtr client)
{
    int ret = xorg_InitClientPrivates(client);

#ifdef NXAGENT_SERVER
    if (ret == 1)
    {

      /*
       * Initialize the private members.
       */

      nxagentInitClientPrivates(client);
    }
#endif

    return ret;
}