Loop.cpp 348 KB
Newer Older
1 2
/**************************************************************************/
/*                                                                        */
3 4 5 6 7 8
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2014 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2014-2016 Ulrich Sibiller <uli42@gmx.de>                 */
/* Copyright (c) 2014-2016 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2011-2016 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)           */
9 10
/*                                                                        */
/* NXCOMP, NX protocol compression and NX extensions to this software     */
11
/* are copyright of the aforementioned persons and companies.             */
12
/*                                                                        */
13 14 15
/* Redistribution and use of the present software is allowed according    */
/* to terms specified in the file LICENSE.nxcomp which comes in the       */
/* source distribution.                                                   */
16 17 18
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
19 20 21 22 23
/* 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.                                          */
/*                                                                        */
24 25
/**************************************************************************/

26 27 28 29
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <errno.h>
#include <signal.h>
#include <setjmp.h>

#include <math.h>
#include <ctype.h>
#include <string.h>
#include <dirent.h>
#include <pwd.h>

#include <fcntl.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/utsname.h>
51
#include <sys/un.h>
52 53 54 55
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

56 57
#include "Misc.h"

58 59
#include <cstddef>

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
#ifdef __sun
#include <strings.h>
#endif

//
// MacOSX 10.4 defines socklen_t. This is
// intended to ensure compatibility with
// older versions.
//

#ifdef __APPLE__
#include <AvailabilityMacros.h>
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_3
typedef int socklen_t;
#endif
#endif

#ifdef _AIX
#include <strings.h>
#include <sys/select.h>
#endif

#ifndef __CYGWIN32__
#include <netinet/tcp.h>
#endif

//
// NX include files.
//

#include "NX.h"
#include "NXalert.h"

#include "Misc.h"
#include "Control.h"
#include "Socket.h"
#include "Statistics.h"
#include "Auth.h"
#include "Keeper.h"
#include "Agent.h"

#include "ClientProxy.h"
#include "ServerProxy.h"

#include "Message.h"
105
#include "ChannelEndPoint.h"
106
#include "Log.h"
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

//
// System specific defines.
//


//
// HP-UX hides this define.
//

#if defined(hpux) && !defined(RLIM_INFINITY)

#define RLIM_INFINITY  0x7fffffff

#endif

//
// Set the verbosity level.
//

#define PANIC
#define WARNING
#undef  TEST
#undef  DEBUG
#undef  DUMP

//
// Enable log output in signal handler.
// This is likely to hang the proxy at
// random, at least on Linux.
//

#undef UNSAFE

//
// Let all logs go to the standard error.
// This is useful to interleave the Xlib
// log output with the proxy output in a
// single file.
//

#undef  MIXED

//
// Define this to check if the client and
// server caches match at shutdown. This
// is a test facility as it requires that
// both proxies are running on the same
// host.
//

#undef  MATCH

//
// If defined, reduce the size of the log
// file and be sure it never exceeds the
// limit.
//

#undef  QUOTA

//
// If defined, force very strict limits for
// the proxy tokens and force the proxy to
// enter often in congestion state.
//

#undef  STRICT

//
// Print a line in the log if the time we
// spent inside the select or handling the
// messages exceeded a given time value.
//

#undef  TIME

//
// This can be useful when testing the forwarding
// of the SSHD connection by nxssh to the agent.
// The debug output will go to a well known file
// that will be opened also by nxssh when BINDER
// is enabled there.
//

#undef  BINDER

//
// Define this to override the limits on
// the core dump size.
//

#define COREDUMPS

//
// Upper limit of pre-allocated buffers
// for string parameters.
//

#define DEFAULT_STRING_LENGTH              256

//
// Maximum length of remote options data
// passed by peer proxy at startup.
//

#define DEFAULT_REMOTE_OPTIONS_LENGTH      512

//
// Maximum length of NX display string.
//

#define DEFAULT_DISPLAY_OPTIONS_LENGTH     1024

//
// Maximum number of cache file names to
// send to the server side.
//

#define DEFAULT_REMOTE_CACHE_ENTRIES       100

//
// Maximum length of remote options string
// that can be received from the peer proxy.
//

#define MAXIMUM_REMOTE_OPTIONS_LENGTH      4096

//
// Macro is true if we determined our proxy
// mode.
//

#define WE_SET_PROXY_MODE         (control -> ProxyMode != proxy_undefined)

//
// Macro is true if our side is the one that
// should connect to remote.
//

247
#define WE_INITIATE_CONNECTION    (connectSocket.enabled())
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

//
// Is true if we must provide our credentials
// to the remote peer.
//

#define WE_PROVIDE_CREDENTIALS    (control -> ProxyMode == proxy_server)

//
// Is true if we listen for a local forwarder
// that will tunnel the traffic through a SSH
// or HTTP link.
//

#define WE_LISTEN_FORWARDER       (control -> ProxyMode == proxy_server && \
263
                                           listenSocket.enabled())
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

//
// You must define FLUSH in Misc.h if
// you want an immediate flush of the
// log output.
//

ostream *logofs = NULL;

//
// Other stream destriptors used for
// logging.
//

ostream *statofs = NULL;
ostream *errofs  = NULL;

//
// Save standard error's rdbuf here
// and restore it when exiting.
//

static streambuf *errsbuf = NULL;

//
// Allow faults to be recovered by
// jumping back into the main loop.
//

jmp_buf context;

//
// Provide operational parameters.
//

Control *control = NULL;

//
// Collect and print statistics.
//

Statistics *statistics = NULL;

//
// Keep data for X11 authentication.
//

Auth *auth = NULL;

//
// This class makes the hard work.
//

Proxy *proxy = NULL;

//
// Used to handle memory-to-memory
// transport to the X agent.
//

Agent *agent = NULL;

//
// The image cache house-keeping class.
//

Keeper *keeper = NULL;

//
// Callback set by the child process
// to be notified about signals.
//

337
int (*signalHandler)(int) = NULL;
338 339

//
340
// Signal handling functions (that are not already mentioned in Misc.h).
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
//

void InstallSignals();

static void RestoreSignals();
static void HandleSignal(int signal);

//
// Signal handling utilities.
//

static void InstallSignal(int signal, int action);
static void RestoreSignal(int signal);

static int HandleChildren();

357
int HandleChild(int child);
358 359 360
static int CheckChild(int pid, int status);
static int WaitChild(int child, const char *label, int force);

361
int CheckParent(const char *name, const char *type, int parent);
362 363 364 365 366 367

void RegisterChild(int child);

static int CheckAbort();

//
368
// Timer handling utilities (that are not already mentioned in Misc.h).
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
//

static void HandleTimer(int signal);

//
// Kill or check a running child.
//

static int KillProcess(int pid, const char *label, int signal, int wait);
static int CheckProcess(int pid, const char *label);

//
// Macros used to test the pid of a child.
//

#define IsFailed(pid)       ((pid) < 0)
#define IsRunning(pid)      ((pid) > 1)
#define IsNotRunning(pid)   ((pid) == 0)
#define IsRestarting(pid)   ((pid) == 1)

#define SetNotRunning(pid)  ((pid) = 0)
#define SetRestarting(pid)  ((pid) = 1)

//
// Start or restart the house-keeper process.
//

396
static void StartKeeper();
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

//
// Cleanup functions.
//

void CleanupConnections();
void CleanupListeners();
void CleanupSockets();
void CleanupGlobal();

static void CleanupChildren();
static void CleanupLocal();
static void CleanupKeeper();
static void CleanupStreams();

//
// Loop forever until the connections
// to the peer proxy is dropped.
//

static void WaitCleanup();

//
// Initialization functions.
//

static int InitBeforeNegotiation();
static int SetupProxyConnection();
static int InitAfterNegotiation();
static int SetupProxyInstance();
static int SetupAuthInstance();
static int SetupAgentInstance();

430 431 432 433
static void SetupTcpSocket();
static void SetupUnixSocket();
static void SetupServiceSockets();
static void SetupDisplaySocket(int &addr_family, sockaddr *&addr,
434
                                  unsigned int &addr_length);
435 436 437 438 439 440

//
// Setup a listening socket and accept
// a new connection.
//

441 442
static int ListenConnection(ChannelEndPoint &endPoint, const char *label);
static int ListenConnectionTCP(const char *host, long port, const char *label);
443
static int ListenConnectionUnix(const char *path, const char *label);
444
static int ListenConnectionAny(sockaddr *addr, socklen_t addrlen, const char *label);
445 446 447 448 449 450
static int AcceptConnection(int fd, int domain, const char *label);

//
// Other convenience functions.
//

451 452
static int PrepareProxyConnectionTCP(char** hostName, long int* portNum, int* timeout, int* proxyFileDescriptor, int* reason);
static int PrepareProxyConnectionUnix(char** path, int* timeout, int* proxyFileDescriptor, int* reason);
453 454 455

static int WaitForRemote(ChannelEndPoint &socketAddress);
static int ConnectToRemote(ChannelEndPoint &socketAddress);
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

static int SendProxyOptions(int fd);
static int SendProxyCaches(int fd);
static int ReadProxyVersion(int fd);
static int ReadProxyOptions(int fd);
static int ReadProxyCaches(int fd);
static int ReadForwarderVersion(int fd);
static int ReadForwarderOptions(int fd);

static int ReadRemoteData(int fd, char *buffer, int size, char stop);
static int WriteLocalData(int fd, const char *buffer, int size);

static void PrintVersionInfo();
static void PrintProcessInfo();
static void PrintConnectionInfo();
static void PrintUsageInfo(const char *option, const int error);
static void PrintOptionIgnored(const char *type, const char *name, const char *value);

//
// This is not static to avoid a warning.
//

void PrintCopyrightInfo();

static const char *GetOptions(const char *options);
static const char *GetArg(int &argi, int argc, const char **argv);
static int CheckArg(const char *type, const char *name, const char *value);
static int ParseArg(const char *type, const char *name, const char *value);
static int ValidateArg(const char *type, const char *name, const char *value);
485 486
static void SetAndValidateChannelEndPointArg(const char *type, const char *name, const char *value,
                                             ChannelEndPoint &endPoint);
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
static int LowercaseArg(const char *type, const char *name, char *value);
static int CheckSignal(int signal);

extern "C"
{
  int ParseCommandLineOptions(int argc, const char **argv);
  int ParseEnvironmentOptions(const char *env, int force);
  int ParseBindOptions(char **host, int *port);
}

static int ParseFileOptions(const char *file);
static int ParseRemoteOptions(char *opts);
static int ParseForwarderOptions(char *opts);

//
// These functions are used to parse literal
// values provided by the user and set the
// control parameters accordingly.
//

static int ParseLinkOption(const char *opt);
static int ParseBitrateOption(const char *opt);
static int ParseCacheOption(const char *opt);
static int ParseShmemOption(const char *opt);
static int ParseImagesOption(const char *opt);
static int ParsePackOption(const char *opt);

//
// Set host and port where NX proxy is supposed
// to be listening in case such parameters are
// given on the command line.
//

520
static int ParseHostOption(const char *opt, char *host, long &port);
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

//
// Translate a font server port specification
// to the corresponding Unix socket path.
//

static int ParseFontPath(char *path);

//
// Translate a pack method id in a literal.
//

static int ParsePackMethod(const int method, const int quality);

//
// Try to increase the size of the allowed
// core dumps.
//

static int SetCore();

//
// Set the proxy mode to either client or
// server.
//

static int SetMode(int mode);

//
// Determine the path of the NX_* directories
// from the environment.
//

static int SetDirectories();

//
// Set the defaults used for the log file and
// statistics.
//

static int SetLogs();

//
// Check if local and remote protocol versions
// are compatible and, eventually, downgrade
// local version to the minimum level that is
// known to work.
//

static int SetVersion();

//
// Setup the listening TCP ports used for the
// additional channels according to user's
// wishes.
//

static int SetPorts();

//
// Set the maximum number of open descriptors.
//

static int SetDescriptors();

//
// Set the path used for choosing the cache.
// It must be selected after determining the
// session type.
//

static int SetCaches();

//
// Initialize, one after the other, all the
// configuration parameters.
//

static int SetParameters();

//
// Set the specific configuration parameter.
//

static int SetSession();
static int SetStorage();
static int SetShmem();
static int SetPack();
static int SetImages();
static int SetLimits();

//
// Set up the control parameters based on
// the link speed negotiated between the
// proxies.
//

static int SetLink();

static int SetLinkModem();
static int SetLinkIsdn();
static int SetLinkAdsl();
static int SetLinkWan();
static int SetLinkLan();

//
// Adjust the compression parameters.
//

static int SetCompression();

static int SetCompressionModem();
static int SetCompressionIsdn();
static int SetCompressionAdsl();
static int SetCompressionWan();
static int SetCompressionLan();

//
// Determine the NX paths based on the
// user's parameters or the environment.
//

char *GetClientPath();

static char *GetSystemPath();
static char *GetHomePath();
static char *GetTempPath();
static char *GetRootPath();
static char *GetCachePath();
static char *GetImagesPath();
static char *GetSessionPath();
static char *GetLastCache(char *list, const char *path);

static int OpenLogFile(char *name, ostream *&stream);
static int ReopenLogFile(char *name, ostream *&stream, int limit);

//
// Perform operations on the managed
// descriptors in the main loop.
//

static void handleCheckSessionInLoop();
static void handleCheckBitrateInLoop();

static void handleCheckSelectInLoop(int &setFDs, fd_set &readSet,
666 667
                                        fd_set &writeSet, T_timestamp selectTs);
static void handleCheckResultInLoop(int &resultFDs, int &errorFDs, int &setFDs, fd_set &readSet,
668 669
                                        fd_set &writeSet, struct timeval &selectTs,
                                            struct timeval &startTs);
670
static void handleCheckStateInLoop(int &setFDs);
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
static void handleCheckSessionInConnect();

static inline void handleSetReadInLoop(fd_set &readSet, int &setFDs, struct timeval &selectTs);
static inline void handleSetWriteInLoop(fd_set &writeSet, int &setFDs, struct timeval &selectTs);
static inline void handleSetListenersInLoop(fd_set &writeSet, int &setFDs);
static inline void handleSetAgentInLoop(int &setFDs, fd_set &readSet, fd_set &writeSet,
                                            struct timeval &selectTs);

static void handleAlertInLoop();
static void handleStatisticsInLoop();

static inline void handleAgentInLoop(int &resultFDs, int &errorFDs, int &setFDs, fd_set &readSet,
                                         fd_set &writeSet, struct timeval &selectTs);
static inline void handleAgentLateInLoop(int &resultFDs, int &errorFDs, int &setFDs, fd_set &readSet,
                                             fd_set &writeSet, struct timeval &selectTs);

static inline void handleReadableInLoop(int &resultFDs, fd_set &readSet);
static inline void handleWritableInLoop(int &resultFDs, fd_set &writeSet);

static inline void handleRotateInLoop();
static inline void handleEventsInLoop();
static inline void handleFlushInLoop();

//
// Manage the proxy link during the negotiation
// phase.
//

static void handleNegotiationInLoop(int &setFDs, fd_set &readSet,
                                        fd_set &writeSet, T_timestamp &selectTs);

//
// Print the 'terminating' messages in the
// session log.
//
 
static inline void handleTerminatingInLoop();
static inline void handleTerminatedInLoop();

//
// Monitor the size of the log file.
//

714
static void handleLogReopenInLoop(T_timestamp &lTs, T_timestamp &nTs);
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

//
// Directory where the NX binaries and libraries reside.
//

static char systemDir[DEFAULT_STRING_LENGTH] = { 0 };

//
// Directory used for temporary files.
//

static char tempDir[DEFAULT_STRING_LENGTH] = { 0 };

//
// Actually the full path to the client.
//

static char clientDir[DEFAULT_STRING_LENGTH] = { 0 };

//
// User's home directory.
//

static char homeDir[DEFAULT_STRING_LENGTH] = { 0 };

//
// Root of directory structure to be created by proxy.
//

static char rootDir[DEFAULT_STRING_LENGTH] = { 0 };

//
// Root of statistics and log files to be created by proxy.
//

static char sessionDir[DEFAULT_STRING_LENGTH] = { 0 };

//
// Log files for errors and statistics. Error log is
754
// the place where we print also debug information.
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
// Both files are closed, deleted and reopened as
// their size exceed the limit set in control class.
// The session log is not reopened, as it is used by
// the NX client and server to track the advance of
// the session.
//

static char errorsFileName[DEFAULT_STRING_LENGTH]  = { 0 };
static char statsFileName[DEFAULT_STRING_LENGTH]   = { 0 };
static char sessionFileName[DEFAULT_STRING_LENGTH] = { 0 };
static char optionsFileName[DEFAULT_STRING_LENGTH] = { 0 };

//
// String literal representing selected link speed
// parameter. Value is translated in control values
// used by proxies to stay synchronized.
//

static char linkSpeedName[DEFAULT_STRING_LENGTH] = { 0 };

//
// String literal representing selected
// cache size.
//

static char cacheSizeName[DEFAULT_STRING_LENGTH] = { 0 };

//
// String literal representing selected
// shared memory segment size.
//

static char shsegSizeName[DEFAULT_STRING_LENGTH] = { 0 };

//
// String literal of images cache size.
//

static char imagesSizeName[DEFAULT_STRING_LENGTH] = { 0 };

//
// String literal for bandwidth limit.
//

static char bitrateLimitName[DEFAULT_STRING_LENGTH] = { 0 };

//
// String literal for image packing method.
//

static char packMethodName[DEFAULT_STRING_LENGTH] = { 0 };

//
// Product name provided by the server or client.
//

static char productName[DEFAULT_STRING_LENGTH] = { 0 };

//
// Its corresponding value from NXpack.h.
//

static int packMethod  = -1;
static int packQuality = -1;

//
// String literal for session type. Persistent caches
// are searched in directory whose name matches this
// parameter.
//

static char sessionType[DEFAULT_STRING_LENGTH] = { 0 };

//
// Unique id assigned to session. It is used as
// name of directory where all files are placed.
//

static char sessionId[DEFAULT_STRING_LENGTH] = { 0 };

//
// Set if we already parsed the options.
//

static int parsedOptions = 0;
static int parsedCommand = 0;

//
// Buffer data received from the remote proxy at
// session negotiation.
//

static char remoteData[MAXIMUM_REMOTE_OPTIONS_LENGTH] = { 0 };
static int  remotePosition = 0;

//
// Main loop file descriptors.
//

static int tcpFD   = -1;
static int unixFD  = -1;
static int cupsFD  = -1;
static int auxFD   = -1;
static int smbFD   = -1;
static int mediaFD = -1;
static int httpFD  = -1;
static int fontFD  = -1;
static int slaveFD = -1;
static int proxyFD = -1;

//
// Used for internal communication
// with the X agent.
//

static int agentFD[2] = { -1, -1 };

//
// Flags determining which protocols and
// ports are forwarded.
//

int useUnixSocket = 1;

static int useTcpSocket   = 1;
static int useCupsSocket  = 0;
static int useAuxSocket   = 0;
static int useSmbSocket   = 0;
static int useMediaSocket = 0;
static int useHttpSocket  = 0;
static int useFontSocket  = 0;
static int useSlaveSocket = 0;
static int useAgentSocket = 0;

889 890 891 892 893 894 895
//
// Set if the launchd service is running
// and its socket must be used as X socket.
//

static int useLaunchdSocket = 0;

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
//
// Set by user if he/she wants to modify
// the default TCP_NODELAY option as set
// in control.
//

static int useNoDelay = -1;

//
// Set if user wants to override default
// flush timeout set according to link.
//

static int usePolicy = -1;

//
// Set if user wants to hide the RENDER
// extension or wants to short-circuit
// some simple replies at client side.
//

static int useRender = -1;
static int useTaint  = -1;

//
// Set if the user wants to reduce the
// nominal size of the token messages
// exchanged between the proxies.
//

static int useStrict = -1;

//
// Set if the proxy is running as part
// of SSH on the client.
//

static int useEncryption = -1;

//
// Name of Unix socket created by the client proxy to
// accept client connections. File must be unlinked
// by cleanup function.
//

static char unixSocketName[DEFAULT_STRING_LENGTH] = { 0 };

//
// Other parameters.
//

static char acceptHost[DEFAULT_STRING_LENGTH]  = { 0 };
static char displayHost[DEFAULT_STRING_LENGTH] = { 0 };
static char authCookie[DEFAULT_STRING_LENGTH]  = { 0 };

951
static int loopbackBind = DEFAULT_LOOPBACK_BIND;
952 953 954 955 956 957 958 959 960 961 962 963 964
static int proxyPort = DEFAULT_NX_PROXY_PORT;
static int xPort     = DEFAULT_NX_X_PORT;

//
// Used to setup the connection the real
// X display socket.
//

static int xServerAddrFamily          = -1;
static sockaddr *xServerAddr          = NULL;
static unsigned int xServerAddrLength = 0;

//
965 966 967 968 969 970 971 972 973 974
// The representation of a Unix socket path or
// a bind address, denoting where the local proxy
// will await the peer connection.
//

static ChannelEndPoint listenSocket;

//
// The TCP host and port or Unix file socket where
// the remote proxy will be contacted.
975 976
//

977
static ChannelEndPoint connectSocket;
978 979 980 981 982

//
// Helper channels are disabled by default.
//

983 984 985 986 987 988
static ChannelEndPoint cupsPort;
static ChannelEndPoint auxPort;
static ChannelEndPoint smbPort;
static ChannelEndPoint mediaPort;
static ChannelEndPoint httpPort;
static ChannelEndPoint slavePort;
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

//
// Can be either a port number or a Unix
// socket.
//

static char fontPort[DEFAULT_STRING_LENGTH] = { 0 };

//
// Host and port where the existing proxy
// is running.
//

static char bindHost[DEFAULT_STRING_LENGTH] = { 0 };
static int  bindPort = -1;

//
// Pointers to the callback functions and
// parameter set by the agent
//

static void (*flushCallback)(void *, int) = NULL;
static void *flushParameter = NULL;

static void (*statisticsCallback)(void *, int) = NULL;
static void *statisticsParameter = NULL;

//
// State variables shared between the init
// function and the main loop.
//

T_timestamp initTs;
T_timestamp startTs;
T_timestamp logsTs;
T_timestamp nowTs;

//
// This is set to the main proxy process id.
// 

int lastProxy = 0;

//
// Set to last dialog process launched by proxy.
// 

int lastDialog = 0;

//
// Set to watchdog process launched by proxy.
// 

int lastWatchdog = 0;

//
// Set if a cache house-keeper process is running.
// 

int lastKeeper = 0;

//
// Let an inner routine register the pid of a slave
// process.
//

static int lastChild = 0;

//
// Exit code of the last child process exited.
//

static int lastStatus = 0;

//
// Set if shutdown was requested through a signal.
//

static int lastKill = 0;

//
// Set if the agent confirmed the destruction of
// the NX transport.
//

static int lastDestroy = 0;

//
// This is set to the code and local flag of the
// last requested alert.
// 

static struct
{
  int code;
  int local;

} lastAlert;

//
// Manage the current signal masks.
//

static struct
{
  sigset_t saved;

  int blocked;
  int installed;

  int enabled[32];
  int forward[32];

  struct sigaction action[32];

} lastMasks;

//
// Manage the current timer.
//

static struct
{
  struct sigaction action;
  struct itimerval value;
  struct timeval   start;
  struct timeval   next;

} lastTimer;

//
// This is set to last signal received in handler.
//

static int lastSignal = 0;

//
// Set to the last time bytes readable were queried
// by the agent.
//

static T_timestamp lastReadableTs = nullTimestamp();

//
// Here are interfaces declared in NX.h.
//

int NXTransProxy(int fd, int mode, const char* options)
{
  //
  // Let the log temporarily go to the standard
  // error. Be also sure we have a jump context,
  // in the case any subsequent operation will
  // cause a cleanup.
  //

  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (setjmp(context) == 1)
  {
1152
    nxinfo << "NXTransProxy: Out of the long jump with pid '"
1153
           << lastProxy << "'.\n" << std::flush;
1154

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    return -1;
  }

  //
  // Check if have already performed a parsing of
  // parameters, as in the case we are running as
  // a stand-alone process. If needed create the
  // parameters repository
  //

  if (control == NULL)
  {
    control = new Control();
  }

  lastProxy = getpid();

1172
  nxinfo << "NXTransProxy: Main process started with pid '"
1173
         << lastProxy << "'.\n" << std::flush;
1174 1175 1176 1177 1178 1179 1180 1181

  SetMode(mode);

  if (mode == NX_MODE_CLIENT)
  {
    if (fd != NX_FD_ANY)
    {

1182
      nxinfo << "NXTransProxy: Agent descriptor for X client connections is FD#"
1183
             << fd << ".\n" << std::flush;
1184

1185
      nxinfo << "NXTransProxy: Disabling listening on further X client connections.\n"
1186
             << std::flush;
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199


      useTcpSocket   = 0;
      useUnixSocket  = 0;
      useAgentSocket = 1;

      agentFD[1] = fd;
    }
  }
  else if (mode == NX_MODE_SERVER)
  {
    if (fd != NX_FD_ANY)
    {
1200
      nxinfo << "NXTransProxy: PANIC! Agent descriptor for X server connections "
1201
             << "not supported yet.\n" << std::flush;
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

      cerr << "Error" << ": Agent descriptor for X server connections "
           << "not supported yet.\n";

      return -1;
    }
  }

  const char *env = GetOptions(options);

  if (ParseEnvironmentOptions(env, 0) < 0)
  {
    cerr << "Error" << ": Parsing of NX transport options failed.\n";

    return -1;
  }

  //
  // Set the path of the NX directories.
  //

  SetDirectories();

  //
  // Open the log files.
  //

  SetLogs();

1231
  nxinfo << "NXTransProxy: Going to run the NX transport loop.\n"
1232
         << std::flush;
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

  WaitCleanup();

  //
  // This function should never return.
  //

  exit(0);
}

void NXTransExit(int code)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  static int recurse;

  if (++recurse > 1)
  {
1254
    nxinfo << "NXTransExit: Aborting process with pid '"
1255 1256
           << getpid() << "' due to recursion through "
           << "exit.\n" << std::flush;
1257 1258 1259 1260

    abort();
  }

1261
  nxinfo << "NXTransExit: Process with pid '"
1262 1263
         << getpid() << "' called exit with code '"
         << code << "'.\n" << std::flush;
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

  if (control != NULL)
  {
    //
    // Be sure that there we can detect the
    // termination of the watchdog.
    //

    EnableSignals();

    //
    // Close the NX transport if it was not
    // shut down already.
    //

    NXTransDestroy(NX_FD_ANY);
  }

  exit(code);
}

int NXTransParseCommandLine(int argc, const char **argv)
{
  return ParseCommandLineOptions(argc, argv);
}

int NXTransParseEnvironment(const char *env, int force)
{
  return ParseEnvironmentOptions(env, force);
}

void NXTransCleanup()
{
  HandleCleanup();
}

1300 1301 1302 1303 1304
void NXTransCleanupForReconnect()
{
  HandleCleanupForReconnect();
}

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
//
// Check the parameters for subsequent
// initialization of the NX transport.
//

int NXTransCreate(int fd, int mode, const char* options)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  //
  // Be sure we have a jump context, in the
  // case a subsequent operation will cause
  // a cleanup.
  //

  if (setjmp(context) == 1)
  {
    return -1;
  }

  //
  // Create the parameters repository
  //

  if (control != NULL)
  {
1334 1335
    nxfatal << "NXTransCreate: PANIC! The NX transport seems "
            << "to be already running.\n" << std::flush;
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346

    cerr << "Error" << ": The NX transport seems "
         << "to be already running.\n";

    return -1;
  }

  control = new Control();

  if (control == NULL)
  {
1347 1348
    nxfatal << "Loop: PANIC! Error creating the NX transport.\n"
            << std::flush;
1349 1350 1351 1352 1353 1354 1355 1356

    cerr << "Error" << ": Error creating the NX transport.\n";

    return -1;
  }

  lastProxy = getpid();

1357
  nxinfo << "NXTransCreate: Caller process running with pid '"
1358
         << lastProxy << "'.\n" << std::flush;
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393

  //
  // Set the local proxy mode an parse the
  // display NX options.
  //

  SetMode(mode);

  const char *env = GetOptions(options);

  if (ParseEnvironmentOptions(env, 0) < 0)
  {
    cerr << "Error" << ": Parsing of NX transport options failed.\n";

    return -1;
  }

  //
  // Set the path of the NX directories.
  //

  SetDirectories();

  //
  // Open the log files.
  //

  SetLogs();

  //
  // Use the provided descriptor.
  //

  proxyFD = fd;

1394
  nxinfo << "NXTransCreate: Called with NX proxy descriptor '"
1395
         << proxyFD << "'.\n" << std::flush;
1396

1397
  nxinfo << "NXTransCreate: Creation of the NX transport completed.\n"
1398
         << std::flush;
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435

  return 1;
}

//
// Tell the proxy to use the descriptor as the internal
// connection to the X client side NX agent. This will
// have the side effect of disabling listening for add-
// itional X client connections.
//

int NXTransAgent(int fd[2])
{
  //
  // Be sure we have a jump context, in the
  // case a subsequent operation will cause
  // a cleanup.
  //

  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (setjmp(context) == 1)
  {
    return -1;
  }

  if (control == NULL)
  {
    cerr << "Error" << ": Can't set the NX agent without a NX transport.\n";

    return -1;
  }
  else if (control -> ProxyMode != proxy_client)
  {
1436 1437
    nxfatal << "NXTransAgent: Invalid mode while setting the NX agent.\n"
            << std::flush;
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451

    cerr << "Error" << ": Invalid mode while setting the NX agent.\n\n";

    return -1;
  }

  useTcpSocket   = 0;
  useUnixSocket  = 0;
  useAgentSocket = 1;

  agentFD[0] = fd[0];
  agentFD[1] = fd[1];


1452
  nxinfo << "NXTransAgent: Internal descriptors for agent are FD#"
1453 1454
         << agentFD[0] << " and FD#" << agentFD[1] << ".\n"
         << std::flush;
1455

1456
  nxinfo << "NXTransAgent: Disabling listening for further X client "
1457
         << "connections.\n" << std::flush;
1458 1459 1460 1461 1462 1463


  agent = new Agent(agentFD);

  if (agent == NULL || agent -> isValid() != 1)
  {
1464 1465
    nxfatal << "Loop: PANIC! Error creating the NX memory transport .\n"
            << std::flush;
1466 1467 1468 1469 1470 1471

    cerr << "Error" << ": Error creating the NX memory transport.\n";

    HandleCleanup();
  }

1472
  nxinfo << "NXTransAgent: Enabling memory-to-memory transport.\n"
1473
         << std::flush;
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490

  return 1;
}

int NXTransClose(int fd)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  /*
   * Only handle the proxy connection. The X
   * transport will take care of closing its
   * end of the socket pair.
   */

1491
  if (control != NULL && ((agent != NULL &&
1492
          (fd == agentFD[0] || fd == NX_FD_ANY)) ||
1493
              (fd == proxyFD || fd == NX_FD_ANY)))
1494 1495 1496
  {
    if (proxy != NULL)
    {
1497
      nxinfo << "NXTransClose: Closing down all the X connections.\n"
1498
             << std::flush;
1499 1500 1501 1502 1503 1504

      CleanupConnections();
    }
  }
  else
  {
1505
    nxinfo << "NXTransClose: The NX transport is not running.\n"
1506
           << std::flush;
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
  }

  return 1;
}

//
// Close down the transport and free the
// allocated NX resources.
//

int NXTransDestroy(int fd)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

1524
  if (control != NULL && ((agent != NULL &&
1525
          (fd == agentFD[0] || fd == NX_FD_ANY)) ||
1526
              (fd == proxyFD || fd == NX_FD_ANY)))
1527 1528 1529 1530 1531 1532 1533 1534
  {
    //
    // Shut down the X connections and
    // wait the cleanup to complete.
    //

    if (proxy != NULL)
    {
1535
      nxinfo << "NXTransDestroy: Closing down all the X connections.\n"
1536
             << std::flush;
1537 1538 1539 1540

      CleanupConnections();
    }

1541
    nxinfo << "NXTransDestroy: Waiting for the NX transport to terminate.\n"
1542
           << std::flush;
1543 1544 1545 1546 1547 1548 1549

    lastDestroy = 1;

    WaitCleanup();
  }
  else
  {
1550
    nxinfo << "NXTransDestroy: The NX transport is not running.\n"
1551
           << std::flush;
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
  }

  return 1;
}

//
// Assume that the NX transport is valid
// as long as the control class has not
// been destroyed.
//

int NXTransRunning(int fd)
{
  return (control != NULL);
}

1568 1569 1570 1571
//
// FIXME: why timeval? Passing milliseconds would be more convenient,
// the timeval struct/T_timestamp could be built on demand.
//
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
int NXTransContinue(struct timeval *selectTs)
{
  if (control != NULL)
  {
    //
    // If no timeout is provided use
    // the default.
    //

    T_timestamp newTs;

    if (selectTs == NULL)
    {
      setTimestamp(newTs, control -> PingTimeout);

      selectTs = &newTs;
    }

    //
    // Use empty masks and only get the
    // descriptors set by the proxy.
    //

    fd_set readSet;
    fd_set writeSet;

    int setFDs;
    int errorFDs;
    int resultFDs;

    setFDs = 0;

    FD_ZERO(&readSet);
    FD_ZERO(&writeSet);

    //
    // Run a new loop. If the transport
    // is gone avoid sleeping until the
    // timeout.
    //

    if (NXTransPrepare(&setFDs, &readSet, &writeSet, selectTs) != 0)
    {
      NXTransSelect(&resultFDs, &errorFDs, &setFDs, &readSet, &writeSet, selectTs);

      NXTransExecute(&resultFDs, &errorFDs, &setFDs, &readSet, &writeSet, selectTs);
    }
  }

  return (control != NULL);
}

int NXTransSignal(int signal, int action)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (control == NULL)
  {
    return 0;
  }

  if (action == NX_SIGNAL_RAISE)
  {
1638
    nxinfo << "NXTransSignal: Raising signal '" << DumpSignal(signal)
1639
           << "' in the proxy handler.\n" << std::flush;
1640 1641 1642 1643 1644 1645 1646

    HandleSignal(signal);

    return 1;
  }
  else if (signal == NX_SIGNAL_ANY)
  {
1647
    nxinfo << "NXTransSignal: Setting action of all signals to '"
1648
           << action << "'.\n" << std::flush;
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661

    for (int i = 0; i < 32; i++)
    {
      if (CheckSignal(i) == 1)
      {
        NXTransSignal(i, action);
      }
    }

    return 1;
  }
  else if (CheckSignal(signal) == 1)
  {
1662
    nxinfo << "NXTransSignal: Setting action of signal '"
1663 1664
           << DumpSignal(signal) << "' to '" << action
           << "'.\n" << std::flush;
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680

    if (action == NX_SIGNAL_ENABLE ||
            action == NX_SIGNAL_FORWARD)
    {
      InstallSignal(signal, action);

      return 1;
    }
    else if (action == NX_SIGNAL_DISABLE)
    {
      RestoreSignal(signal);

      return 1;
    }
  }

1681
  nxwarn << "NXTransSignal: WARNING! Unable to perform action '"
1682 1683
         << action << "' on signal '" << DumpSignal(signal)
         << "'.\n" << std::flush;
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697

  cerr << "Warning" << ": Unable to perform action '" << action
       << "' on signal '" << DumpSignal(signal)
       << "'.\n";

  return -1;
}

int NXTransCongestion(int fd)
{
  if (control != NULL && proxy != NULL)
  {

    int congestion = proxy -> getCongestion(proxyFD);
1698
    nxdbg << "NXTransCongestion: Returning " << congestion
1699
          << " as current congestion level.\n" << std::flush;
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739

    return congestion;

    return (proxy -> getCongestion(proxyFD));
  }

  return 0;
}

int NXTransHandler(int fd, int type, void (*handler)(void *parameter,
                       int reason), void *parameter)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  switch (type)
  {
    case NX_HANDLER_FLUSH:
    {
      flushCallback  = handler;
      flushParameter = parameter;

      break;
    }
    case NX_HANDLER_STATISTICS:
    {
      //
      // Reporting of statistics by the agent
      // still needs to be implemented.
      //

      statisticsCallback  = handler;
      statisticsParameter = parameter;

      break;
    }
    default:
    {
1740
      nxinfo << "NXTransHandler: WARNING! Failed to set "
1741 1742 1743
             << "the NX callback for event '" << type << "' to '"
             << (void *) handler << "' and parameter '"
             << parameter << "'.\n" << std::flush;
1744 1745 1746 1747 1748

      return 0;
    }
  }

1749
  nxinfo << "NXTransHandler: Set the NX "
1750 1751 1752
         << "callback for event '" << type << "' to '"
         << (void *) handler << "' and parameter '"
         << parameter << "'.\n" << std::flush;
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

  return 1;
}

int NXTransRead(int fd, char *data, int size)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (control != NULL && agent != NULL &&
          fd == agentFD[0])
  {
1767
    nxdbg << "NXTransRead: Dequeuing " << size << " bytes "
1768
          << "from FD#" << agentFD[0] << ".\n" << std::flush;
1769 1770 1771 1772 1773 1774

    int result = agent -> dequeueData(data, size);


    if (result < 0 && EGET() == EAGAIN)
    {
1775
      nxdbg << "NXTransRead: WARNING! Dequeuing from FD#"
1776
            << agentFD[0] << " would block.\n" << std::flush;
1777 1778 1779
    }
    else
    {
1780
      nxdbg << "NXTransRead: Dequeued " << result << " bytes "
1781
            << "to FD#" << agentFD[0] << ".\n" << std::flush;
1782 1783 1784 1785 1786 1787 1788
    }


    return result;
  }
  else
  {
1789
    nxdbg << "NXTransRead: Reading " << size << " bytes "
1790
          << "from FD#" << fd << ".\n" << std::flush;
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809

    return read(fd, data, size);
  }
}

int NXTransReadVector(int fd, struct iovec *iovdata, int iovsize)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (control != NULL && agent != NULL &&
          fd == agentFD[0])
  {

    if (control -> ProxyStage >= stage_operational &&
            agent -> localReadable() > 0)
    {
1810
      nxdbg << "NXTransReadVector: WARNING! Agent has data readable.\n"
1811
            << std::flush;
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
    }


    char *base;

    int length;
    int result;

    struct iovec *vector = iovdata;
    int count = iovsize;

    ESET(0);

    int i = 0;
    int total = 0;

    for (;  i < count;  i++, vector++)
    {
      length = vector -> iov_len;
      base = (char *) vector -> iov_base;

      while (length > 0)
      {
1835
        nxdbg << "NXTransReadVector: Dequeuing " << length
1836 1837
              << " bytes " << "from FD#" << agentFD[0] << ".\n"
              << std::flush;
1838 1839 1840 1841 1842 1843

        result = agent -> dequeueData(base, length);


        if (result < 0 && EGET() == EAGAIN)
        {
1844
          nxdbg << "NXTransReadVector: WARNING! Dequeuing from FD#"
1845
                << agentFD[0] << " would block.\n" << std::flush;
1846 1847 1848
        }
        else
        {
1849
          nxdbg << "NXTransReadVector: Dequeued " << result
1850 1851
                << " bytes " << "from FD#" << agentFD[0] << ".\n"
                << std::flush;
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
        }


        if (result < 0 && total == 0)
        {
          return result;
        }
        else if (result <= 0)
        {
          return total;
        }

        ESET(0);

        length -= result;
        total  += result;
        base   += result;
      }
    }

    return total;
  }
  else
  {
1876
    nxdbg << "NXTransReadVector: Reading vector with "
1877 1878
          << iovsize << " elements from FD#" << fd << ".\n"
          << std::flush;
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897

    return readv(fd, iovdata, iovsize);
  }
}

int NXTransReadable(int fd, int *readable)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (control == NULL || agent == NULL ||
          fd != agentFD[0])
  {

    int result = GetBytesReadable(fd, readable);
    if (result == -1)
    {
1898
      nxdbg << "NXTransReadable: Error detected on FD#"
1899
            << fd << ".\n" << std::flush;
1900 1901 1902
    }
    else
    {
1903
      nxdbg << "NXTransReadable: Returning " << *readable
1904 1905
            << " bytes as readable from FD#" << fd
            << ".\n" << std::flush;
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
    }

    return result;
  }

  int result = agent -> dequeuableData();

  switch (result)
  {
    case 0:
    {
      //
      // The client might have enqueued data to our side
      // and is now checking for the available events. As
      // _XEventsQueued() may omit to call _XSelect(), we
      // handle here the new data that is coming from the
      // proxy to avoid spinning through this function
      // again.
      //

      if (proxy != NULL && proxy -> canRead() == 1)
      {
1928
        nxinfo << "NXTransReadable: WARNING! Trying to "
1929 1930
               << "read to generate new agent data.\n"
               << std::flush;
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943

        //
        // Set the context as the function
        // can cause a cleanup.
        //

        if (setjmp(context) == 1)
        {
          return -1;
        }

        if (proxy -> handleRead() < 0)
        {
1944
          nxinfo << "NXTransReadable: Failure reading "
1945 1946
                 << "messages from proxy FD#" << proxyFD
                 << ".\n" << std::flush;
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959

          HandleShutdown();
        }

        //
        // Call again the routine. By reading
        // new control messages from the proxy
        // the agent channel may be gone.
        //

        return NXTransReadable(fd, readable);
      }

1960
      nxdbg << "NXTransReadable: Returning " << 0
1961 1962
            << " bytes as readable from FD#" << fd
            << " with result 0.\n" << std::flush;
1963 1964 1965 1966 1967 1968 1969

      *readable = 0;

      return 0;
    }
    case -1:
    {
1970
      nxdbg << "NXTransReadable: Returning " << 0
1971 1972
            << " bytes as readable from FD#" << fd
            << " with result -1.\n" << std::flush;
1973 1974 1975 1976 1977 1978 1979

      *readable = 0;

      return -1;
    }
    default:
    {
1980
      nxdbg << "NXTransReadable: Returning " << result
1981 1982
            << " bytes as readable from FD#" << fd
            << " with result 0.\n" << std::flush;
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010

      *readable = result;

      return 0;
    }
  }
}

int NXTransWrite(int fd, char *data, int size)
{
  //
  // Be sure we have a valid log file.
  //

  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (control != NULL && agent != NULL &&
          fd == agentFD[0])
  {
    int result;

    if (proxy != NULL)
    {
      if (proxy -> canRead(agentFD[1]) == 0)
      {
2011
        nxdbg << "NXTransWrite: WARNING! Delayed enqueuing to FD#"
2012 2013
              << agentFD[0] << " with proxy unable to read.\n"
              << std::flush;
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034

        ESET(EAGAIN);

        return -1;
      }

      //
      // Set the context as the function
      // can cause a cleanup.
      //

      if (setjmp(context) == 1)
      {
        return -1;
      }

      //
      // Don't enqueue the data to the transport
      // but let the channel borrow the buffer.
      //

2035
      nxdbg << "NXTransWrite: Letting the channel borrow "
2036 2037
            << size << " bytes from FD#" << agentFD[0]
            << ".\n" << std::flush;
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065

      result = proxy -> handleRead(agentFD[1], data, size);

      if (result == 1)
      {
        result = size;
      }
      else
      {
        if (result == 0)
        {
          ESET(EAGAIN);
        }
        else
        {
          ESET(EPIPE);
        }

        result = -1;
      }
    }
    else
    {
      //
      // We don't have a proxy connection, yet.
      // Enqueue the data to the agent transport.
      //

2066
      nxdbg << "NXTransWrite: Enqueuing " << size << " bytes "
2067
            << "to FD#" << agentFD[0] << ".\n" << std::flush;
2068 2069 2070 2071 2072 2073 2074 2075 2076

      result = agent -> enqueueData(data, size);
    }


    if (result < 0)
    {
      if (EGET() == EAGAIN)
      {
2077
        nxdbg << "NXTransWrite: WARNING! Enqueuing to FD#"
2078 2079
              << agentFD[0] << " would block.\n"
              << std::flush;
2080 2081 2082
      }
      else
      {
2083
        nxdbg << "NXTransWrite: WARNING! Error enqueuing to FD#"
2084
              << agentFD[0] << ".\n" << std::flush;
2085 2086 2087 2088
      }
    }
    else
    {
2089
      nxdbg << "NXTransWrite: Enqueued " << result << " bytes "
2090
            << "to FD#" << agentFD[0] << ".\n" << std::flush;
2091 2092 2093 2094 2095 2096 2097
    }


    return result;
  }
  else
  {
2098
    nxdbg << "NXTransWrite: Writing " << size << " bytes "
2099
          << "to FD#" << fd << ".\n" << std::flush;
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130

    return write(fd, data, size);
  }
}

int NXTransWriteVector(int fd, struct iovec *iovdata, int iovsize)
{
  //
  // Be sure we have a valid log file and a
  // jump context because we will later call
  // functions that can perform a cleanup.
  //

  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  int result = 0;

  if (control != NULL && agent != NULL &&
          fd == agentFD[0])
  {
    //
    // See the comment in NXTransWrite().
    //

    if (proxy != NULL)
    {
      if (proxy -> canRead(agentFD[1]) == 0)
      {
2131
        nxdbg << "NXTransWriteVector: WARNING! Delayed enqueuing to FD#"
2132 2133
              << agentFD[0] << " with proxy unable to read.\n"
              << std::flush;
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176

        ESET(EAGAIN);

        return -1;
      }
    }

    //
    // Set the context as the function
    // can cause a cleanup.
    //

    if (setjmp(context) == 1)
    {
      return -1;
    }

    char *base;

    int length;

    struct iovec *vector = iovdata;
    int count = iovsize;

    ESET(0);

    int i = 0;
    int total = 0;

    for (;  i < count;  i++, vector++)
    {
      length = vector -> iov_len;
      base = (char *) vector -> iov_base;

      while (length > 0)
      {
        if (proxy != NULL)
        {
          //
          // Don't enqueue the data to the transport
          // but let the channel borrow the buffer.
          //

2177
          nxdbg << "NXTransWriteVector: Letting the channel borrow "
2178 2179
                << length << " bytes from FD#" << agentFD[0]
                << ".\n" << std::flush;
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207

          result = proxy -> handleRead(agentFD[1], base, length);

          if (result == 1)
          {
            result = length;
          }
          else
          {
            if (result == 0)
            {
              ESET(EAGAIN);
            }
            else
            {
              ESET(EPIPE);
            }

            result = -1;
          }
        }
        else
        {
          //
          // We don't have a proxy connection, yet.
          // Enqueue the data to the agent transport.
          //

2208
          nxdbg << "NXTransWriteVector: Enqueuing " << length
2209 2210
                << " bytes " << "to FD#" << agentFD[0] << ".\n"
                << std::flush;
2211 2212 2213 2214 2215 2216 2217 2218 2219

          result = agent -> enqueueData(base, length);
        }


        if (result < 0)
        {
          if (EGET() == EAGAIN)
          {
2220
            nxdbg << "NXTransWriteVector: WARNING! Enqueuing to FD#"
2221 2222
                  << agentFD[0] << " would block.\n"
                  << std::flush;
2223 2224 2225
          }
          else
          {
2226
            nxdbg << "NXTransWriteVector: WARNING! Error enqueuing to FD#"
2227
                  << agentFD[0] << ".\n" << std::flush;
2228 2229 2230 2231
          }
        }
        else
        {
2232
          nxdbg << "NXTransWriteVector: Enqueued " << result
2233 2234
                << " bytes " << "to FD#" << agentFD[0] << ".\n"
                << std::flush;
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
        }


        if (result < 0 && total == 0)
        {
          return result;
        }
        else if (result <= 0)
        {
          return total;
        }

        ESET(0);

        length -= result;
        total  += result;
        base   += result;
      }
    }

    return total;
  }
  else
  {
2259
    nxdbg << "NXTransWriteVector: Writing vector with "
2260 2261
          << iovsize << " elements to FD#" << fd << ".\n"
          << std::flush;
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272

    return writev(fd, iovdata, iovsize);
  }
}

int NXTransPolicy(int fd, int type)
{
  if (control != NULL)
  {
    if (usePolicy == -1)
    {
2273
      nxinfo << "NXTransPolicy: Setting flush policy on "
2274 2275 2276 2277
             << "proxy FD#" << proxyFD << " to '"
             << DumpPolicy(type == NX_POLICY_DEFERRED ?
                           policy_deferred : policy_immediate)
             << "'.\n" << std::flush;
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290

      control -> FlushPolicy = (type == NX_POLICY_DEFERRED ?
                                    policy_deferred : policy_immediate);

      if (proxy != NULL)
      {
        proxy -> handleFlush();
      }

      return 1;
    }
    else
    {
2291
      nxinfo << "NXTransPolicy: Ignoring the agent "
2292 2293 2294
             << "setting with user policy set to '"
             << DumpPolicy(control -> FlushPolicy)
             << "'.\n" << std::flush;
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307

      return 0;
    }
  }

  return 0;
}

int NXTransFlushable(int fd)
{
  if (proxy == NULL || agent == NULL ||
          fd != agentFD[0])
  {
2308
    nxdbg << "NXTransFlushable: Returning 0 bytes as "
2309 2310
          << "flushable for unrecognized FD#" << fd
          << ".\n" << std::flush;
2311 2312 2313 2314 2315

    return 0;
  }
  else
  {
2316
    nxdbg << "NXTransFlushable: Returning " << proxy ->
2317 2318 2319
             getFlushable(proxyFD) << " as bytes flushable on "
          << "proxy FD#" << proxyFD << ".\n"
          << std::flush;
2320 2321 2322 2323 2324 2325 2326 2327 2328

    return proxy -> getFlushable(proxyFD);
  }
}

int NXTransFlush(int fd)
{
  if (proxy != NULL)
  {
2329
    nxinfo << "NXTransFlush: Requesting an immediate flush of "
2330 2331
           << "proxy FD#" << proxyFD << ".\n"
           << std::flush;
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352

    return proxy -> handleFlush();
  }

  return 0;
}

int NXTransChannel(int fd, int channelFd, int type)
{
  if (proxy != NULL)
  {
    //
    // Set the context as the function
    // can cause a cleanup.
    //

    if (setjmp(context) == 1)
    {
      return -1;
    }

2353
    nxinfo << "NXTransChannel: Going to create a new channel "
2354 2355
           << "with type '" << type << "' on FD#" << channelFd
           << ".\n" << std::flush;
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426

    int result = -1;

    switch (type)
    {
      case NX_CHANNEL_X11:
      {
        if (useUnixSocket == 1 || useTcpSocket == 1 ||
                useAgentSocket == 1 || useAuxSocket == 1)
        {
          result = proxy -> handleNewConnection(channel_x11, channelFd);
        }

        break;
      }
      case NX_CHANNEL_CUPS:
      {
        if (useCupsSocket == 1)
        {
          result = proxy -> handleNewConnection(channel_cups, channelFd);
        }

        break;
      }
      case NX_CHANNEL_SMB:
      {
        if (useSmbSocket == 1)
        {
          result = proxy -> handleNewConnection(channel_smb, channelFd);
        }

        break;
      }
      case NX_CHANNEL_MEDIA:
      {
        if (useMediaSocket == 1)
        {
          result = proxy -> handleNewConnection(channel_media, channelFd);
        }

        break;
      }
      case NX_CHANNEL_HTTP:
      {
        if (useHttpSocket == 1)
        {
          result = proxy -> handleNewConnection(channel_http, channelFd);
        }

        break;
      }
      case NX_CHANNEL_FONT:
      {
        if (useFontSocket == 1)
        {
          result = proxy -> handleNewConnection(channel_font, channelFd);
        }

        break;
      }
      case NX_CHANNEL_SLAVE:
      {
        if (useSlaveSocket == 1)
        {
          result = proxy -> handleNewConnection(channel_slave, channelFd);
        }

        break;
      }
      default:
      {
2427
        nxwarn << "NXTransChannel: WARNING! Unrecognized channel "
2428
               << "type '" << type << "'.\n" << std::flush;
2429 2430 2431 2432 2433 2434 2435 2436

        break;
      }
    }


    if (result != 1)
    {
2437
      nxwarn << "NXTransChannel: WARNING! Could not create the "
2438 2439
             << "new channel with type '" << type << "' on FD#"
             << channelFd << ".\n" << std::flush;
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
    }


    return result;
  }

  return 0;
}

const char *NXTransFile(int type)
{
  char *name = NULL;

  switch (type)
  {
    case NX_FILE_SESSION:
    {
      name = sessionFileName;

      break;
    }
    case NX_FILE_ERRORS:
    {
      name = errorsFileName;

      break;
    }
    case NX_FILE_OPTIONS:
    {
      name = optionsFileName;

      break;
    }
    case NX_FILE_STATS:
    {
      name = statsFileName;

      break;
    }
  }

  if (name != NULL && *name != '\0')
  {
    return name;
  }

  return NULL;
}

long NXTransTime()
{
  static T_timestamp last = getTimestamp();

  T_timestamp now = getTimestamp();

  long diff = diffTimestamp(last, now);

  last = now;

  return diff;
}

int NXTransAlert(int code, int local)
{
  if (proxy != NULL)
  {
2506
    nxdbg << "NXTransAlert: Requesting a NX dialog with code "
2507 2508
          << code << " and local " << local << ".\n"
          << std::flush;
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538

    if (local == 0)
    {
      //
      // Set the context as the function
      // can cause a cleanup.
      //

      if (setjmp(context) == 1)
      {
        return -1;
      }

      proxy -> handleAlert(code);
    }
    else
    {
      //
      // Show the alert at the next loop.
      //

      HandleAlert(code, local);
    }

    return 1;
  }
  else
  {
    if (logofs == NULL)
    {
2539 2540
      logofs = &cerr;
    }
2541

2542
    nxdbg << "NXTransAlert: Can't request an alert without "
2543
          << "a valid NX transport.\n" << std::flush;
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
  }

  return 0;
}

//
// Prepare the file sets and the timeout
// for a later execution of the select().
//

int NXTransPrepare(int *setFDs, fd_set *readSet,
                       fd_set *writeSet, struct timeval *selectTs)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  //
  // Control is NULL if the NX transport was
  // reset or was never created. If control
  // is valid then prepare to jump back when
  // the transport is destroyed.
  //

  if (control == NULL || setjmp(context) == 1)
  {
    return 0;
  }

2574
  nxinfo << "NXTransPrepare: Going to prepare the NX transport.\n"
2575
         << std::flush;
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585

  if (control -> ProxyStage < stage_operational)
  {
    handleNegotiationInLoop(*setFDs, *readSet, *writeSet, *selectTs);
  }
  else
  {

    if (isTimestamp(*selectTs) == 0)
    {
2586
      nxinfo << "Loop: WARNING! Preparing the select with requested "
2587 2588
             << "timeout of " << selectTs -> tv_sec << " s and "
             << (double) selectTs -> tv_usec / 1000 << " ms.\n"
2589
             << std::flush;
2590 2591 2592
    }
    else
    {
2593
      nxinfo << "Loop: Preparing the select with requested "
2594 2595
             << "timeout of " << selectTs -> tv_sec << " s and "
             << (double) selectTs -> tv_usec / 1000 << " ms.\n"
2596
             << std::flush;
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
    }


    //
    // Set descriptors of listening sockets.
    //

    handleSetListenersInLoop(*readSet, *setFDs);

    //
    // Set descriptors of both proxy and X
    // connections.
    //

    handleSetReadInLoop(*readSet, *setFDs, *selectTs);

    //
    // Find out which file descriptors have
    // data to write.
    //

    handleSetWriteInLoop(*writeSet, *setFDs, *selectTs);
  }

  //
  // Prepare the masks for handling the memory-
  // to-memory transport. This is required even
  // during session negotiation.
  //

  if (agent != NULL)
  {
    handleSetAgentInLoop(*setFDs, *readSet, *writeSet, *selectTs);
  }

  //
  // Register time spent handling messages.
  //

  nowTs = getNewTimestamp();

2638
  int diffTs = diffTimestamp(startTs, nowTs);
2639

2640
  nxinfo << "Loop: Mark - 0 - at " << strMsTimestamp()
2641
         << " with " << diffTs << " ms elapsed.\n"
2642
         << std::flush;
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657

  //
  // TODO: Should add the read time in two
  // parts otherwise the limits are checked
  // before the counters are updated with
  // time spent in the last loop.
  //

  if (control -> ProxyStage >= stage_operational)
  {
    statistics -> addReadTime(diffTs);
  }

  startTs = nowTs;

2658
  nxdbg << "Loop: New timestamp is " << strMsTimestamp(startTs)
2659
        << ".\n" << std::flush;
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673

  return 1;
}

//
// Let's say that we call select() to find out
// if any of the handled descriptors has data,
// but actually things are a bit more complex
// than that.
//

int NXTransSelect(int *resultFDs, int *errorFDs, int *setFDs, fd_set *readSet,
                      fd_set *writeSet, struct timeval *selectTs)
{
2674
  int diffTs;
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698

  static T_timestamp lastTs;

  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  //
  // Control is NULL if the NX transport was
  // reset or never created. If control is
  // valid then prepare for jumping back in
  // the case of an error.
  //

  if (control == NULL || setjmp(context) == 1)
  {
    *resultFDs = select(*setFDs, readSet, writeSet, NULL, selectTs);

    *errorFDs = errno;

    return 0;
  }

2699
  nxinfo << "NXTransSelect: Going to select the NX descriptors.\n"
2700
         << std::flush;
2701 2702 2703 2704 2705 2706 2707 2708


  handleCheckSelectInLoop(*setFDs, *readSet, *writeSet, *selectTs);


  diffTs = diffTimestamp(lastTs, getNewTimestamp());
  if (diffTs > 20)
  {
2709
    nxdbg << "Loop: TIME! Spent " << diffTs
2710
          << " ms handling messages for proxy FD#"
2711
          << proxyFD << ".\n" << std::flush;
2712 2713 2714 2715 2716 2717 2718
  }

  lastTs = getNewTimestamp();


  if (isTimestamp(*selectTs) == 0)
  {
2719
    nxinfo << "Loop: WARNING! Executing the select with requested "
2720 2721
           << "timeout of " << selectTs -> tv_sec << " s and "
           << (double) selectTs -> tv_usec / 1000 << " ms.\n"
2722
           << std::flush;
2723 2724 2725
  }
  else if (proxy != NULL && proxy -> getFlushable(proxyFD) > 0)
  {
2726
    nxinfo << "Loop: WARNING! Proxy FD#" << proxyFD
2727 2728
           << " has " << proxy -> getFlushable(proxyFD)
           << " bytes to write but timeout is "
2729 2730
           << selectTs -> tv_sec << " s and "
           << selectTs -> tv_usec / 1000 << " ms.\n"
2731
           << std::flush;
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
  }


  //
  // Wait for the selected sockets
  // or the timeout.
  //

  ESET(0);

  *resultFDs = select(*setFDs, readSet, writeSet, NULL, selectTs);

  *errorFDs = EGET();


  diffTs = diffTimestamp(lastTs, getNewTimestamp());
  if (diffTs > 100)
  {
2750
    nxdbg << "Loop: TIME! Spent " << diffTs
2751
          << " ms waiting for new data for proxy FD#"
2752
          << proxyFD << ".\n" << std::flush;
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
  }

  lastTs = getNewTimestamp();

  //
  // Check the result of the select.
  //


  handleCheckResultInLoop(*resultFDs, *errorFDs, *setFDs, *readSet, *writeSet, *selectTs, startTs);

  //
  // Get time spent in select. The accouting is done
  // in milliseconds. This is a real problem on fast
  // machines where each loop is unlikely to take
  // more than 500 us, so consider that the results
  // can be inaccurate.
  //

  nowTs = getNewTimestamp();

  diffTs = diffTimestamp(startTs, nowTs);

2776
  nxinfo << "Loop: Out of select after " << diffTs << " ms "
2777 2778
         << "at " << strMsTimestamp(nowTs) << " with result "
         << *resultFDs << ".\n" << std::flush;
2779 2780 2781

  startTs = nowTs;

2782
  nxdbg << "Loop: New timestamp is " << strMsTimestamp(startTs)
2783
        << ".\n" << std::flush;
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813

  if (control -> ProxyStage >= stage_operational)
  {
    statistics -> addIdleTime(diffTs);
  }

  if (*resultFDs < 0)
  {
    //
    // Check if the call was interrupted or if any of the
    // managed descriptors has become invalid. This can
    // happen to the X11 code, before the descriptor is
    // removed from the managed set.
    //

    #ifdef __sun

    if (*errorFDs == EINTR || *errorFDs == EBADF ||
            *errorFDs == EINVAL)

    #else

    if (*errorFDs == EINTR || *errorFDs == EBADF)

    #endif

    {

      if (*errorFDs == EINTR)
      {
2814
        nxinfo << "Loop: Select failed due to EINTR error.\n"
2815
               << std::flush;
2816 2817 2818
      }
      else
      {
2819
        nxinfo << "Loop: WARNING! Call to select failed. Error is "
2820 2821
               << EGET() << " '" << ESTR() << "'.\n"
               << std::flush;
2822 2823 2824 2825 2826
      }

    }
    else
    {
2827
      nxfatal << "Loop: PANIC! Call to select failed. Error is "
2828
              << EGET() << " '" << ESTR() << "'.\n"
2829
              << std::flush;
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865

      cerr << "Error" << ": Call to select failed. Error is "
           << EGET() << " '" << ESTR() << "'.\n";

      HandleCleanup();
    }
  }

  return 1;
}

//
// Perform the required actions on all
// the descriptors having I/O pending.
//

int NXTransExecute(int *resultFDs, int *errorFDs, int *setFDs, fd_set *readSet,
                       fd_set *writeSet, struct timeval *selectTs)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  //
  // Control is NULL if the NX transport was
  // reset or never created. If control is
  // valid then prepare for jumping back in
  // the case of an error.
  //

  if (control == NULL || setjmp(context) == 1)
  {
    return 0;
  }

2866
  nxinfo << "NXTransExecute: Going to execute I/O on the NX descriptors.\n"
2867
         << std::flush;
2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880

  if (control -> ProxyStage >= stage_operational)
  {
    //
    // Check if I/O is possible on the proxy and
    // local agent descriptors.
    //

    if (agent != NULL)
    {
      handleAgentInLoop(*resultFDs, *errorFDs, *setFDs, *readSet, *writeSet, *selectTs);
    }

2881
    nxinfo << "Loop: Mark - 1 - at " << strMsTimestamp()
2882
           << " with " << diffTimestamp(startTs, getTimestamp())
2883
           << " ms elapsed.\n" << std::flush;
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897

    //
    // Rotate the channel that will be handled
    // first.
    //

    handleRotateInLoop();

    //
    // Flush any data on newly writable sockets.
    //

    handleWritableInLoop(*resultFDs, *writeSet);

2898
    nxinfo << "Loop: Mark - 2 - at " << strMsTimestamp()
2899
           << " with " << diffTimestamp(startTs, getTimestamp())
2900
           << " ms elapsed.\n" << std::flush;
2901 2902 2903 2904 2905 2906 2907

    //
    // Check if any socket has become readable.
    //

    handleReadableInLoop(*resultFDs, *readSet);

2908
    nxinfo << "Loop: Mark - 3 - at " << strMsTimestamp()
2909
           << " with " << diffTimestamp(startTs, getTimestamp())
2910
           << " ms elapsed.\n" << std::flush;
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929

    //
    // Handle the scheduled events on channels.
    //
    // - Restart, if possible, any client that was
    //   put to sleep.
    //
    // - Check if there are pointer motion events to
    //   flush. This applies only to X server side.
    //
    // - Check if any channel has exited the conges-
    //   tion state.
    //
    // - Check if there are images that are currently
    //   being streamed.
    //

    handleEventsInLoop();

2930
    nxinfo << "Loop: Mark - 4 - at " << strMsTimestamp()
2931
           << " with " << diffTimestamp(startTs, getTimestamp())
2932
           << " ms elapsed.\n" << std::flush;
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952

    //
    // Check if user sent a signal to produce
    // statistics.
    //

    handleStatisticsInLoop();

    //
    // We may have flushed the proxy link or
    // handled data coming from the remote.
    // Post-process the masks and set the
    // selected agent descriptors as ready.
    //

    if (agent != NULL)
    {
      handleAgentLateInLoop(*resultFDs, *errorFDs, *setFDs, *readSet, *writeSet, *selectTs);
    }

2953
    nxinfo << "Loop: Mark - 5 - at " << strMsTimestamp()
2954
           << " with " << diffTimestamp(startTs, getTimestamp())
2955
           << " ms elapsed.\n" << std::flush;
2956 2957 2958 2959 2960 2961 2962 2963 2964

    //
    // Check if there is any data to flush.
    // Agents should flush the proxy link
    // explicitly.
    //

    handleFlushInLoop();

2965
    nxinfo << "Loop: Mark - 6 - at " << strMsTimestamp()
2966
           << " with " << diffTimestamp(startTs, getTimestamp())
2967
           << " ms elapsed.\n" << std::flush;
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
  }

  //
  // Check if we have an alert to show.
  //

  handleAlertInLoop();

  if (control -> ProxyStage >= stage_operational)
  {
    //
    // Check if it's time to give up.
    //

    handleCheckSessionInLoop();

    //
    // Check if local proxy is consuming
    // too many resources.
    //

    handleCheckBitrateInLoop();

    //
    // Check coherency of internal state.
    //


    handleCheckStateInLoop(*setFDs);

2998
    nxinfo << "Loop: Mark - 7 - at " << strMsTimestamp()
2999
           << " with " << diffTimestamp(startTs, getTimestamp())
3000
           << " ms elapsed.\n" << std::flush;
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040
  }

  //
  // Truncate the logs if needed.
  //

  handleLogReopenInLoop(logsTs, nowTs);

  return 1;
}

//
// Initialize the connection parameters and
// prepare for negotiating the link with the
// remote proxy.
//

int InitBeforeNegotiation()
{
  //
  // Disable limits on core dumps.
  //

  SetCore();

  //
  // Install the signal handlers.
  //

  InstallSignals();

  //
  // Track how much time we spent in initialization.
  //

  nowTs = getNewTimestamp();

  startTs = nowTs;
  initTs  = nowTs;

3041
  nxinfo << "Loop: INIT! Taking mark for initialization at "
3042 3043
         << strMsTimestamp(initTs) << ".\n"
         << std::flush;
3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065

  //
  // If not explicitly specified, determine if local
  // mode is client or server according to parameters
  // provided so far.
  //

  if (WE_SET_PROXY_MODE == 0)
  {
    cerr << "Error" << ": Please specify either the -C or -S option.\n";

    HandleCleanup();
  }

  //
  // Start a watchdog. If initialization cannot
  // be completed before timeout, then clean up
  // everything and exit.
  //

  if (control -> ProxyMode == proxy_client)
  {
3066
    nxinfo << "Loop: Starting watchdog process with timeout of "
3067 3068
           << control -> InitTimeout / 1000 << " seconds.\n"
           << std::flush;
3069 3070 3071 3072 3073

    lastWatchdog = NXTransWatchdog(control -> InitTimeout);

    if (IsFailed(lastWatchdog))
    {
3074 3075
      nxfatal << "Loop: PANIC! Can't start the NX watchdog process.\n"
              << std::flush;
3076 3077 3078 3079 3080

      SetNotRunning(lastWatchdog);
    }
    else
    {
3081
      nxinfo << "Loop: Watchdog started with pid '"
3082
             << lastWatchdog << "'.\n" << std::flush;
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
    }
  }

  //
  // Print preliminary info.
  //

  PrintProcessInfo();

  //
  // Set cups, multimedia and other
  // auxiliary ports.
  //

  SetPorts();

  //
  // Increase the number of maximum open
  // file descriptors for this process.
  //

  SetDescriptors();

  //
3107
  // Set local endianness.
3108 3109 3110 3111 3112 3113
  //

  unsigned int test = 1;

  setHostBigEndian(*((unsigned char *) (&test)) == 0);

3114
  nxinfo << "Loop: Local host is "
3115 3116
         << (hostBigEndian() ? "big endian" : "little endian")
         << ".\n" << std::flush;
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149

  if (control -> ProxyMode == proxy_client)
  {
    //
    // Listen on sockets that mimic an X display to
    // which X clients will be able to connect (e.g.
    // unix:8 and/or localhost:8).
    //

    if (useTcpSocket == 1)
    {
      SetupTcpSocket();
    }

    if (useUnixSocket == 1)
    {
      SetupUnixSocket();
    }
  }
  else
  {
    //
    // Don't listen for X connections.
    //

    useUnixSocket  = 0;
    useTcpSocket   = 0;
    useAgentSocket = 0;

    //
    // Get ready to open the local display.
    //

3150 3151 3152
    delete xServerAddr;
    xServerAddr = NULL;

3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172
    SetupDisplaySocket(xServerAddrFamily, xServerAddr, xServerAddrLength);
  }

  //
  // If we are the NX server-side proxy we need to
  // complete our initializazion. We will mandate
  // our parameters at the time the NX client will
  // connect.
  //

  if (control -> ProxyMode == proxy_client)
  {
    SetParameters();
  }

  return 1;
}

int SetupProxyConnection()
{
3173

3174 3175
  if (proxyFD == -1)
  {
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191

    char *socketUri = NULL;

    // Let's make sure, the default value for listenSocket is properly set. Doing this
    // here, because we have to make sure that we call it after the connectSocket
    // declaration is really really complete.

    if (listenSocket.disabled() && connectSocket.disabled())
    {
      char listenPortValue[20] = { 0 };
      sprintf(listenPortValue, "%ld", (long)(proxyPort + DEFAULT_NX_PROXY_PORT_OFFSET));

      SetAndValidateChannelEndPointArg("local", "listen", listenPortValue, listenSocket);
    }

    connectSocket.getSpec(&socketUri);
3192 3193 3194
    nxinfo << "Loop: connectSocket is "<< ( connectSocket.enabled() ? "enabled" : "disabled") << ". "
           << "The socket URI is '"<< ( socketUri != NULL ? socketUri : "<unset>") << "'.\n" << std::flush;

3195 3196
    SAFE_FREE(socketUri);

3197
    listenSocket.getSpec(&socketUri);
3198 3199
    nxinfo << "Loop: listenSocket is "<< ( listenSocket.enabled() ? "enabled" : "disabled") << ". "
           << "The socket URI is '"<< ( socketUri != NULL ? socketUri : "<unset>") << "'.\n" << std::flush;
3200

3201
    SAFE_FREE(socketUri);
3202

3203 3204
    if (WE_INITIATE_CONNECTION)
    {
3205
      if (connectSocket.getSpec(&socketUri))
3206
      {
3207
        nxinfo << "Loop: Going to connect to '" << socketUri
3208
               << "'.\n" << std::flush;
3209
        SAFE_FREE(socketUri);
3210

3211
        proxyFD = ConnectToRemote(connectSocket);
3212

3213
        nxinfo << "Loop: Connected to remote proxy on FD#"
3214
               << proxyFD << ".\n" << std::flush;
3215

3216 3217 3218
        cerr << "Info" << ": Connected to remote proxy on FD#"
             << proxyFD << ".\n";
      }
3219 3220 3221
    }
    else
    {
3222 3223

      if (listenSocket.isTCPSocket() && (listenSocket.getTCPPort() < 0))
3224
      {
3225
        listenSocket.setSpec(DEFAULT_NX_PROXY_PORT_OFFSET + proxyPort);
3226 3227
      }

3228 3229
      if (listenSocket.getSpec(&socketUri))
      {
3230
        nxinfo << "Loop: Going to wait for connection at '"
3231
               << socketUri << "'.\n" << std::flush;
3232
        SAFE_FREE(socketUri);
3233

3234
        proxyFD = WaitForRemote(listenSocket);
3235

3236 3237
        if (WE_LISTEN_FORWARDER)
        {
3238
          nxinfo << "Loop: Connected to remote forwarder on FD#"
3239
                 << proxyFD << ".\n" << std::flush;
3240 3241 3242
        }
        else
        {
3243
          nxinfo << "Loop: Connected to remote proxy on FD#"
3244
                 << proxyFD << ".\n" << std::flush;
3245
        }
3246 3247 3248 3249 3250 3251

      }
    }
  }
  else
  {
3252
    nxinfo << "Loop: Using the inherited connection on FD#"
3253
           << proxyFD << ".\n" << std::flush;
3254 3255 3256 3257 3258 3259 3260
  }

  //
  // Set TCP_NODELAY on proxy descriptor
  // to reduce startup time. Option will
  // later be disabled if needed.
  //
3261
  // either listenSocket or connectSocket is used here...
3262

3263 3264 3265
  if(listenSocket.isTCPSocket() || connectSocket.isTCPSocket())

    SetNoDelay(proxyFD, 1);
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283

  //
  // We need non-blocking input since the
  // negotiation phase.
  //

  SetNonBlocking(proxyFD, 1);

  return 1;
}

//
// Create the required proxy and channel classes
// and get ready for handling the encoded traffic.
//

int InitAfterNegotiation()
{
3284
  nxinfo << "Loop: Connection with remote proxy completed.\n"
3285
         << std::flush;
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370

  cerr << "Info" << ": Connection with remote proxy completed.\n"
        << logofs_flush;

  //
  // If we are the server proxy we completed
  // our initializazion phase according to
  // the values provided by the client side.
  //

  if (control -> ProxyMode == proxy_server)
  {
    SetParameters();
  }

  //
  // Set up the listeners for the additional
  // services.
  //

  SetupServiceSockets();

  //
  // Create the proxy class and the statistics
  // repository and pass all the configuration
  // data we negotiated with the remote peer.
  //

  SetupProxyInstance();

  //
  // We completed both parsing of user's parameters
  // and handlshaking with remote proxy. Now print
  // a brief summary including the most significant
  // control values.
  //

  PrintConnectionInfo();

  //
  // Cancel the initialization watchdog.
  //

  if (IsRunning(lastWatchdog))
  {
    KillProcess(lastWatchdog, "watchdog", SIGTERM, 1);

    SetNotRunning(lastWatchdog);

    lastSignal = 0;
  }

  //
  // Start the house-keeper process. It will
  // remove the oldest persistent caches, if
  // the amount of storage exceed the limits
  // set by the user.
  //

  StartKeeper();

  //
  // Set the log size check timestamp.
  //

  nowTs = getNewTimestamp();

  logsTs = nowTs;

  //
  // TODO: Due to the way the new NX transport is working,
  // the accounting of time spent handling messages must
  // be rewritten. In particular, at the moment it only
  // shows the time spent encoding and decoding messages
  // in the main loop, after executing a select. It doesn't
  // take into account the time spent in the NXTrans* calls
  // where messages can be encoded and decoded implicitly,
  // on demand of the agent. When the agent transport is
  // in use, these calls constitute the vast majority of
  // the encoding activity. The result is that the number
  // of KB encoded per second shown by the proxy statistics
  // is actually much lower than the real throughput gene-
  // rated by the proxy.
  //

3371
  nxinfo << "Loop: INIT! Completed initialization at "
3372
         << strMsTimestamp(nowTs) << " with "
3373
         << diffTimestamp(initTs, nowTs) << " ms "
3374
         << "since the init mark.\n" << std::flush;
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401

  initTs = getNewTimestamp();

  //
  // We can now start handling binary data from
  // our peer proxy.
  //

  if (agent == NULL)
  {
    cerr << "Session" << ": Session started at '"
         << strTimestamp() << "'.\n";
  }

  return 1;
}

int SetMode(int mode)
{
  //
  // Set the local proxy mode.
  //

  if (control -> ProxyMode == proxy_undefined)
  {
    if (mode == NX_MODE_CLIENT)
    {
3402
      nxinfo << "Loop: INIT! Initializing with mode "
3403 3404
             << "NX_MODE_CLIENT at " << strMsTimestamp()
             << ".\n" << std::flush;
3405 3406 3407 3408 3409

      control -> ProxyMode = proxy_client;
    }
    else if (mode == NX_MODE_SERVER)
    {
3410
      nxinfo << "Loop: INIT! Initializing with mode "
3411 3412
             << "NX_MODE_SERVER at " << strMsTimestamp()
             << ".\n" << std::flush;
3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440

      control -> ProxyMode = proxy_server;
    }
    else
    {
      cerr << "Error" << ": Please specify either "
           << "the -C or -S option.\n";

      HandleCleanup();
    }
  }

  return 1;
}

int SetupProxyInstance()
{
  if (control -> ProxyMode == proxy_client)
  {
    proxy = new ClientProxy(proxyFD);
  }
  else
  {
    proxy = new ServerProxy(proxyFD);
  }

  if (proxy == NULL)
  {
3441 3442
    nxfatal << "Loop: PANIC! Error creating the NX proxy.\n"
            << std::flush;
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456

    cerr << "Error" << ": Error creating the NX proxy.\n";

    HandleCleanup();
  }

  //
  // Create the statistics repository.
  //

  statistics = new Statistics(proxy);

  if (statistics == NULL)
  {
3457 3458
    nxfatal << "Loop: PANIC! Error creating the NX statistics.\n"
            << std::flush;
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509

    cerr << "Error" << ": Error creating the NX statistics.\n";

    HandleCleanup();
  }

  //
  // If user gave us a proxy cookie than create the
  // X11 authorization repository and find the real
  // cookie to be used for our X display.
  //

  SetupAuthInstance();

  //
  // Reset the static members in channels.
  //

  proxy -> handleChannelConfiguration();

  //
  // Inform the proxies about the ports where they
  // will have to forward the network connections.
  //

  proxy -> handleDisplayConfiguration(displayHost, xServerAddrFamily,
                                          xServerAddr, xServerAddrLength);

  proxy -> handlePortConfiguration(cupsPort, smbPort, mediaPort,
                                       httpPort, fontPort);

  //
  // We handed over the sockaddr structure we
  // created when we set up the display socket
  // to the proxy.
  //

  xServerAddr = NULL;

  //
  // Set socket options on proxy link, then propagate link
  // configuration to proxy. This includes translating some
  // control parameters in 'local' and 'remote'. Finally
  // adjust cache parameters according to pack method and
  // session type selected by user.
  //

  if (proxy -> handleSocketConfiguration() < 0 ||
          proxy -> handleLinkConfiguration() < 0 ||
              proxy -> handleCacheConfiguration() < 0)
  {
3510 3511
    nxfatal << "Loop: PANIC! Error configuring the NX transport.\n"
            << std::flush;
3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560

    cerr << "Error" << ": Error configuring the NX transport.\n";

    HandleCleanup();
  }

  //
  // Load the message stores from the persistent
  // cache.
  //

  proxy -> handleLoad(load_if_first);

  //
  // Inform the proxy that from now on it can
  // start handling the encoded data.
  //

  proxy -> setOperational();

  //
  // Are we going to use an internal IPC connection
  // with an agent? In this case create the channel
  // by using the socket descriptor provided by the
  // caller at the proxy initialization.
  //

  SetupAgentInstance();

  //
  // Check if we need to verify the existence of
  // a matching client cache at shutdown.
  //

  #ifdef MATCH

  control -> PersistentCacheCheckOnShutdown = 1;

  #endif

  //
  // Flush any data produced so far.
  //

  proxy -> handleFlush();


  if (proxy -> getFlushable(proxyFD) > 0)
  {
3561
    nxinfo << "Loop: WARNING! Proxy FD#" << proxyFD << " has data "
3562 3563
           << "to flush after setup of the NX transport.\n"
           << std::flush;
3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579
  }


  return 1;
}

int SetupAuthInstance()
{
  //
  // If user gave us a proxy cookie, then create the
  // X11 authorization repository and find the real
  // cookie to be used for our X display.
  //

  if (control -> ProxyMode == proxy_server)
  {
3580
    if (*authCookie != '\0')
3581
    {
3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
      if (useLaunchdSocket == 1)
      {
        //
        // If we are going to retrieve the X11 autho-
        // rization through the launchd service, make
        // a connection to its socket to trigger the
        // X server starting.
        //

        sockaddr_un launchdAddrUnix;

        unsigned int launchdAddrLength = sizeof(sockaddr_un);

        int launchdAddrFamily = AF_UNIX;

        launchdAddrUnix.sun_family = AF_UNIX;

3599 3600 3601 3602
        // determine the maximum number of characters that fit into struct
        // sockaddr_un's sun_path member
        std::size_t launchdAddrNameLength =
          sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path);
3603 3604 3605

        int success = -1;

3606
        snprintf(launchdAddrUnix.sun_path, launchdAddrNameLength, "%s", displayHost);
3607 3608 3609

        *(launchdAddrUnix.sun_path + launchdAddrNameLength - 1) = '\0';

3610
        nxinfo << "Loop: Connecting to launchd service "
3611
               << "on Unix port '" << displayHost << "'.\n" << std::flush;
3612 3613 3614 3615 3616

        int launchdFd = socket(launchdAddrFamily, SOCK_STREAM, PF_UNSPEC);

        if (launchdFd < 0)
        {
3617
          nxfatal << "Loop: PANIC! Call to socket failed. "
3618
                  << "Error is " << EGET() << " '" << ESTR()
3619
                  << "'.\n" << std::flush;
3620 3621 3622
        }
        else if ((success = connect(launchdFd, (sockaddr *) &launchdAddrUnix, launchdAddrLength)) < 0)
        {
3623
          nxwarn << "Loop: WARNING! Connection to launchd service "
3624 3625 3626
                 << "on Unix port '" << displayHost << "' failed "
                 << "with error " << EGET() << ", '" << ESTR() << "'.\n"
                 << std::flush;
3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
        }

        if (launchdFd >= 0)
        {
          close(launchdFd);
        }

        //
        // The real cookie will not be available
        // until the X server starts. Query for the
        // cookie in a loop, unless the connection
        // to the launchd service failed.
        //

        int attempts = (success < 0 ? 1 : 10);

        for (int i = 0; i < attempts; i++)
        {
          delete auth;

          auth = new Auth(displayHost, authCookie);

          if (auth != NULL && auth -> isFake() == 1)
          {
            usleep(200000);

            continue;
          }

          break;
        }
      }
      else
      {
        auth = new Auth(displayHost, authCookie);
      }
3663 3664 3665

      if (auth == NULL || auth -> isValid() != 1)
      {
3666 3667
        nxfatal << "Loop: PANIC! Error creating the X authorization.\n"
                << std::flush;
3668 3669 3670 3671 3672

        cerr << "Error" << ": Error creating the X authorization.\n";

        HandleCleanup();
      }
3673 3674
      else if (auth -> isFake() == 1)
      {
3675
        nxwarn << "Loop: WARNING! Could not retrieve the X server "
3676 3677
               << "authentication cookie.\n"
               << std::flush;
3678 3679 3680 3681 3682 3683 3684

        cerr << "Warning" << ": Failed to read data from the X "
             << "auth command.\n";

        cerr << "Warning" << ": Generated a fake cookie for X "
             << "authentication.\n";
      }
3685 3686 3687
    }
    else
    {
3688
      nxinfo << "Loop: No proxy cookie was provided for "
3689
             << "authentication.\n" << std::flush;
3690 3691 3692 3693

      cerr << "Info" << ": No proxy cookie was provided for "
           << "authentication.\n";

3694
      nxinfo << "Loop: Forwarding the real X authorization "
3695
             << "cookie.\n" << std::flush;
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730

      cerr << "Info" << ": Forwarding the real X authorization "
           << "cookie.\n";
    }
  }

  return 1;
}

int SetupAgentInstance()
{
  if (control -> ProxyMode == proxy_client &&
          useAgentSocket == 1)
  {
    //
    // This will temporarily disable signals to safely
    // load the cache, then will send a control packet
    // to the remote end, telling that cache has to be
    // loaded, so it's important that proxy is already
    // set in operational state.
    //

    int result;

    if (agent != NULL)
    {
      result = proxy -> handleNewAgentConnection(agent);
    }
    else
    {
      result = proxy -> handleNewConnection(channel_x11, agentFD[1]);
    }

    if (result < 0)
    {
3731 3732
      nxfatal << "Loop: PANIC! Error creating the NX agent connection.\n"
              << std::flush;
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742

      cerr << "Error" << ": Error creating the NX agent connection.\n";

      HandleCleanup();
    }
  }

  return 1;
}

3743
void SetupTcpSocket()
3744 3745 3746 3747 3748
{
  //
  // Open TCP socket emulating local display.
  //

3749
  tcpFD =  ListenConnectionTCP((loopbackBind ? "localhost" : "*"), X_TCP_PORT + proxyPort, "X11");
3750 3751
}

3752
void SetupUnixSocket()
3753 3754 3755 3756 3757
{
  //
  // Open UNIX domain socket for display.
  //

3758
  unsigned int required = snprintf(unixSocketName, DEFAULT_STRING_LENGTH, "/tmp/.X11-unix");
3759
  if (required < sizeof(unixSocketName)) {
3760

3761 3762 3763
    // No need to execute the following actions conditionally
    mkdir(unixSocketName, (0777 | S_ISVTX));
    chmod(unixSocketName, (0777 | S_ISVTX));
3764

3765
    required = snprintf(unixSocketName, DEFAULT_STRING_LENGTH, "/tmp/.X11-unix/X%d", proxyPort);
3766
    if (required < sizeof(unixSocketName)) {
3767

3768 3769 3770
      unixFD = ListenConnectionUnix(unixSocketName, "x11");
      if (unixFD >= 0)
        chmod(unixSocketName, 0777);
3771
      return;
3772
    }
3773 3774
  }

3775
  unixSocketName[0] = '\0'; // Just in case!
3776

3777
  nxfatal << "Loop: PANIC! path for unix socket is too long.\n" << std::flush;
3778

3779 3780
  cerr << "Error" << ": path for Unix socket is too long.\n";
  HandleCleanup();
3781 3782 3783 3784 3785 3786
}

//
// The following is a dumb copy-paste. The
// nxcompsh library should offer a better
// implementation.
3787
// addr is assumed to have been freed outside
3788 3789
//

3790
void SetupDisplaySocket(int &addr_family, sockaddr *&addr,
3791
                           unsigned int &addr_length)
3792
{
3793 3794
  addr_family = AF_INET;
  addr_length = 0;
3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810

  char *display;

  if (*displayHost == '\0')
  {
    //
    // Assume DISPLAY as the X server to which
    // we will forward the proxied connections.
    // This means that NX parameters have been
    // passed through other means.
    //

    display = getenv("DISPLAY");

    if (display == NULL || *display == '\0')
    {
3811 3812
      nxfatal << "Loop: PANIC! Host X server DISPLAY is not set.\n"
              << std::flush;
3813 3814 3815 3816 3817 3818 3819

      cerr << "Error" << ": Host X server DISPLAY is not set.\n";

      HandleCleanup();
    }
    else if (strncasecmp(display, "nx/nx,", 6) == 0 ||
                 strncasecmp(display, "nx,", 3) == 0 ||
3820 3821
                     strncasecmp(display, "nx/nx:", 6) == 0 ||
                         strncasecmp(display, "nx:", 3) == 0)
3822
    {
3823 3824
      nxfatal << "Loop: PANIC! NX transport on host X server '"
              << display << "' not supported.\n" << std::flush;
3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835

      cerr << "Error" << ": NX transport on host X server '"
           << display << "' not supported.\n";

      cerr << "Error" << ": Please run the local proxy specifying "
           << "the host X server to connect to.\n";

      HandleCleanup();
    }
    else if (strlen(display) >= DEFAULT_STRING_LENGTH)
    {
3836
      nxfatal << "Loop: PANIC! Host X server DISPLAY cannot exceed "
3837
              << DEFAULT_STRING_LENGTH << " characters.\n"
3838
              << std::flush;
3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852

      cerr << "Error" << ": Host X server DISPLAY cannot exceed "
           << DEFAULT_STRING_LENGTH << " characters.\n";

      HandleCleanup();
    }

    strcpy(displayHost, display);
  }

  display = new char[strlen(displayHost) + 1];

  if (display == NULL)
  {
3853 3854
    nxfatal << "Loop: PANIC! Out of memory handling DISPLAY variable.\n"
            << std::flush;
3855 3856 3857 3858 3859 3860 3861 3862

    cerr << "Error" << ": Out of memory handling DISPLAY variable.\n";

    HandleCleanup();
  }

  strcpy(display, displayHost);

3863 3864
  #ifdef __APPLE__

3865 3866
  if ((strncasecmp(display, "/tmp/launch", 11) == 0) ||
      (strncasecmp(display, "/private/tmp/com.apple.launchd", 30) == 0))
3867
  {
3868
    nxinfo << "Loop: Using launchd service on socket '"
3869
           << display << "'.\n" << std::flush;
3870 3871 3872 3873 3874 3875

    useLaunchdSocket = 1;
  }

  #endif

3876
  char *separator = strrchr(display, ':');
3877 3878 3879

  if ((separator == NULL) || !isdigit(*(separator + 1)))
  {
3880 3881
    nxfatal << "Loop: PANIC! Invalid display '" << display << "'.\n"
            << std::flush;
3882 3883 3884

    cerr << "Error" << ": Invalid display '" << display << "'.\n";

3885 3886
    delete [] display;

3887 3888 3889 3890 3891 3892 3893
    HandleCleanup();
  }

  *separator = '\0';

  xPort = atoi(separator + 1);

3894
  nxinfo << "Loop: Using local X display '" << displayHost
3895 3896
         << "' with host '" << display << "' and port '"
         << xPort << "'.\n" << std::flush;
3897

3898 3899 3900 3901 3902 3903 3904
  #ifdef __APPLE__

  if (separator == display || strcmp(display, "unix") == 0 ||
          useLaunchdSocket == 1)

  #else

3905
  if (separator == display || strcmp(display, "unix") == 0)
3906 3907

  #endif
3908 3909 3910 3911 3912
  {
    //
    // UNIX domain port.
    //

3913 3914 3915 3916 3917
    // determine the maximum number of characters that fit into struct
    // sockaddr_un's sun_path member
    std::size_t maxlen_un =
      sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path);

3918
    nxinfo << "Loop: Using real X server on UNIX domain socket.\n"
3919
           << std::flush;
3920

3921
    addr_family = AF_UNIX;
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936

    //
    // The scope of this function is to fill either the sockaddr_un
    // (when the display is set to the Unix Domain socket) or the
    // sockaddr_in structure (when connecting by TCP) only once, so
    // that the structure will be later used at the time the server
    // proxy will try to forward the connection to the X server. We
    // don't need to verify that the socket does exist at the pre-
    // sent moment. The method that forwards the connection will
    // perform the required checks and will retry, if needed. Anyway
    // we need to select the name of the socket, so we check if the
    // well-known directory exists and take that as an indication of
    // where the socket will be created.
    //

3937 3938 3939 3940
    // Try abstract X11 socket first (via a test connect), if that fails
    // fall back to Unix domain socket file.

    #ifdef __linux__
3941
    int testSocketFD = socket(addr_family, SOCK_STREAM, PF_UNSPEC);
3942

3943 3944
    // this name cannot be changed as it is defined this way by the
    // local X server
3945 3946
    int len = snprintf(unixSocketName + 1, DEFAULT_STRING_LENGTH - 1,
                       "/tmp/.X11-unix/X%d", xPort);
3947 3948 3949
    unixSocketName[0] = '\0';

    sockaddr_un *xServerAddrABSTRACT = new sockaddr_un;
3950
    memset(xServerAddrABSTRACT, 0, sizeof(struct sockaddr_un));
3951
    xServerAddrABSTRACT -> sun_family = AF_UNIX;
3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973

    if (maxlen_un < (unsigned int)len + 1)
    {
      nxfatal << "Loop: PANIC! Abstract socket name '" << unixSocketName + 1
              << "' is too long!" << std::flush;

      delete [] display;
      delete xServerAddrABSTRACT;

      HandleCleanup();
    }

    // copy including the leading '\0'
    memcpy(xServerAddrABSTRACT -> sun_path, unixSocketName, len + 1);

    // man 7 unix:
    // "an abstract socket address is distinguished (from a
    // pathname socket) by the fact that sun_path[0] is a null byte
    // ('\0').  The socket's address in this namespace is given by the
    // additional bytes in sun_path that are covered by the specified
    // length of the address structure."
    addr_length = offsetof(struct sockaddr_un, sun_path) + len + 1;
3974

3975 3976 3977
    int ret = connect(testSocketFD,
                      (struct sockaddr *) xServerAddrABSTRACT,
                      addr_length);
3978 3979
    close(testSocketFD);

3980 3981 3982 3983 3984
    if (ret == 0) {

        cerr << "Info" << ": Using abstract X11 socket in kernel namespace "
             << "for accessing DISPLAY=:" << xPort << ".\n";

3985
        addr = (sockaddr *) xServerAddrABSTRACT;
3986
        delete [] display;
3987
        return;
3988

3989
    }
3990

3991 3992
    cerr << "Info" << ": Falling back to file system X11 socket "
         << "for accessing DISPLAY=:" << xPort << ".\n";
3993

3994 3995 3996
    delete xServerAddrABSTRACT;

#endif
3997

3998 3999 4000 4001
    struct stat statInfo;

    char unixSocketDir[DEFAULT_STRING_LENGTH];

4002
    snprintf(unixSocketDir, DEFAULT_STRING_LENGTH, "/tmp/.X11-unix");
4003

4004 4005 4006 4007
    #ifdef __APPLE__

    if (useLaunchdSocket == 1)
    {
4008 4009 4010 4011 4012 4013 4014
      char *slash = rindex(display, '/');

      if (slash != NULL)
      {
        *slash = '\0';
      }

4015
      snprintf(unixSocketDir, DEFAULT_STRING_LENGTH, "%s", display);
4016 4017 4018 4019
    }

    #endif

4020 4021
    *(unixSocketDir + DEFAULT_STRING_LENGTH - 1) = '\0';

4022
    nxinfo << "Loop: Assuming X socket in directory '"
4023
           << unixSocketDir << "'.\n" << std::flush;
4024 4025 4026

    if (stat(unixSocketDir, &statInfo) < 0)
    {
4027 4028
      nxfatal << "Loop: PANIC! Can't determine the location of "
              << "the X display socket.\n" << std::flush;
4029 4030 4031 4032

      cerr << "Error" << ": Can't determine the location of "
           << "the X display socket.\n";

4033
      nxfatal << "Loop: PANIC! Error " << EGET() << " '" << ESTR()
4034
              << "' checking '" << unixSocketDir << "'.\n"
4035
              << std::flush;
4036 4037 4038 4039

      cerr << "Error" << ": Error " << EGET() << " '" << ESTR()
           << "' checking '" << unixSocketDir << "'.\n";

4040
      delete [] display;
4041 4042 4043
      HandleCleanup();
    }

4044 4045
    snprintf(unixSocketName, DEFAULT_STRING_LENGTH, "%s/X%d",
             unixSocketDir, xPort);
4046

4047 4048 4049 4050
    #ifdef __APPLE__

    if (useLaunchdSocket == 1)
    {
4051
      snprintf(unixSocketName, DEFAULT_STRING_LENGTH, "%s", displayHost);
4052 4053 4054 4055
    }

    #endif

4056
    nxinfo << "Loop: Assuming X socket name '" << unixSocketName
4057
           << "'.\n" << std::flush;
4058

4059 4060 4061 4062 4063 4064 4065 4066 4067
    if (maxlen_un < strlen(unixSocketName) + 1)
    {
      nxfatal << "Loop: PANIC! Socket name '" << unixSocketName
              << "' is too long!" << std::flush;

      delete [] display;

      HandleCleanup();
    }
4068

4069
    sockaddr_un *xServerAddrUNIX = new sockaddr_un;
4070
    xServerAddrUNIX -> sun_family = AF_UNIX;
4071 4072
    strcpy(xServerAddrUNIX -> sun_path, unixSocketName);

4073 4074
    addr = (sockaddr *) xServerAddrUNIX;
    addr_length = sizeof(sockaddr_un);
4075

4076 4077 4078 4079 4080 4081 4082
  }
  else
  {
    //
    // TCP port.
    //

4083
    nxinfo << "Loop: Using real X server on TCP port.\n"
4084
           << std::flush;
4085

4086
    addr_family = AF_INET;
4087 4088 4089 4090 4091

    int xServerIPAddr = GetHostAddress(display);

    if (xServerIPAddr == 0)
    {
4092 4093
      nxfatal << "Loop: PANIC! Unknown display host '" << display
              << "'.\n" << std::flush;
4094 4095 4096 4097

      cerr << "Error" << ": Unknown display host '" << display
           << "'.\n";

4098
      delete [] display;
4099 4100 4101 4102 4103 4104 4105 4106 4107
      HandleCleanup();
    }

    sockaddr_in *xServerAddrTCP = new sockaddr_in;

    xServerAddrTCP -> sin_family = AF_INET;
    xServerAddrTCP -> sin_port = htons(X_TCP_PORT + xPort);
    xServerAddrTCP -> sin_addr.s_addr = xServerIPAddr;

4108 4109
    addr = (sockaddr *) xServerAddrTCP;
    addr_length = sizeof(sockaddr_in);
4110 4111 4112 4113 4114
  }

  delete [] display;
}

4115
void SetupServiceSockets()
4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163
{
  if (control -> ProxyMode == proxy_client)
  {
    if (useCupsSocket)
    {
      if ((cupsFD = ListenConnection(cupsPort, "CUPS")) < 0)
      {
        useCupsSocket = 0;
      }
    }

    if (useAuxSocket)
    {
      if ((auxFD = ListenConnection(auxPort, "auxiliary X11")) < 0)
      {
        useAuxSocket = 0;
      }
    }

    if (useSmbSocket)
    {
      if ((smbFD = ListenConnection(smbPort, "SMB")) < 0)
      {
        useSmbSocket = 0;
      }
    }

    if (useMediaSocket)
    {
      if ((mediaFD = ListenConnection(mediaPort, "media")) < 0)
      {
        useMediaSocket = 0;
      }
    }

    if (useHttpSocket)
    {
      if ((httpFD = ListenConnection(httpPort, "http")) < 0)
      {
        useHttpSocket = 0;
      }
    }

    useFontSocket = 0;
  }
  else
  {
    //
4164
    // Get ready to listen for the font server connections
4165 4166 4167 4168
    //

    if (useFontSocket)
    {
4169 4170
      // Since ProtoStep7 (#issue 108)
      int port = atoi(fontPort);
4171

4172
      if ((fontFD = ListenConnectionTCP("localhost", port, "font")) < 0)
4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191
      {
        useFontSocket = 0;
      }
    }

    useCupsSocket  = 0;
    useAuxSocket   = 0;
    useSmbSocket   = 0;
    useMediaSocket = 0;
    useHttpSocket  = 0;
  }

  //
  // Slave channels can be originated
  // by both sides.
  //

  if (useSlaveSocket)
  {
4192 4193
    // Since ProtoStep7 (#issue 108)
    if ((slaveFD = ListenConnection(slavePort, "slave")) < 0)
4194 4195 4196 4197 4198 4199
    {
      useSlaveSocket = 0;
    }
  }
}

4200
int ListenConnectionAny(sockaddr *addr, socklen_t addrlen, const char *label)
4201
{
4202
  int newFD = socket(addr->sa_family, SOCK_STREAM, PF_UNSPEC);
4203 4204 4205

  if (newFD == -1)
  {
4206
    nxfatal << "Loop: PANIC! Call to socket failed for " << label
4207
            << " socket. Error is " << EGET() << " '"
4208
            << ESTR() << "'.\n" << std::flush;
4209 4210

    cerr << "Error" << ": Call to socket failed for " << label
4211
         << " socket. Error is " << EGET() << " '"
4212 4213 4214 4215
         << ESTR() << "'.\n";

    goto SetupSocketError;
  }
4216 4217 4218 4219 4220 4221 4222

  if (addr->sa_family == AF_INET)
    if (SetReuseAddress(newFD) < 0)
    {
      // SetReuseAddress already warns with an error
      goto SetupSocketError;
    }
4223

4224
  if (bind(newFD, addr, addrlen) == -1)
4225
  {
4226
    nxfatal << "Loop: PANIC! Call to bind failed for " << label
4227
            << ". Error is " << EGET()
4228
            << " '" << ESTR() << "'.\n" << std::flush;
4229 4230

    cerr << "Error" << ": Call to bind failed for " << label
4231
         << ". Error is " << EGET()
4232 4233 4234 4235 4236 4237
         << " '" << ESTR() << "'.\n";
    goto SetupSocketError;
  }

  if (listen(newFD, 8) == -1)
  {
4238
    nxfatal << "Loop: PANIC! Call to listen failed for " << label
4239
            << ". Error is " << EGET()
4240
            << " '" << ESTR() << "'.\n" << std::flush;
4241

4242
    cerr << "Error" << ": Call to listen failed for " << label
4243
         << ". Error is " << EGET()
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266
         << " '" << ESTR() << "'.\n";

    goto SetupSocketError;
  }

  return newFD;

SetupSocketError:

  if (newFD != -1)
  {
    close(newFD);
  }

  //
  // May optionally return. The session would
  // continue without the service. The problem
  // with this approach is that it would make
  // harder to track problems with allocation
  // of ports in clients and server.
  //

  HandleCleanup();
4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
  return -1;
}

int ListenConnectionUnix(const char *path, const char *label)
{

  sockaddr_un unixAddr;
  unixAddr.sun_family = AF_UNIX;
#ifdef UNIX_PATH_MAX
  if (strlen(path) >= UNIX_PATH_MAX)
#else
  if (strlen(path) >= sizeof(unixAddr.sun_path))
#endif
  {
4281 4282
    nxfatal << "Loop: PANIC! Socket path \"" << path << "\" for "
            << label << " is too long.\n" << std::flush;
4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313

    cerr << "Error" << ": Socket path \"" << path << "\" for "
         << label << " is too long.\n";

    HandleCleanup();
    return -1;
  }

  strcpy(unixAddr.sun_path, path);
  return ListenConnectionAny((sockaddr *)&unixAddr, sizeof(unixAddr), label);
}

int ListenConnectionTCP(const char *host, long port, const char *label)
{
  sockaddr_in tcpAddr;
  tcpAddr.sin_family = AF_INET;
  tcpAddr.sin_port = htons(port);

  if (loopbackBind ||
      !host ||
      !strcmp(host, "") ||
      !strcmp(host, "localhost")) {
    tcpAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  }
  else if(strcmp(host, "*") == 0) {
    tcpAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  }
  else {
    int ip = tcpAddr.sin_addr.s_addr = GetHostAddress(host);
    if (ip == 0)
    {
4314 4315
      nxfatal << "Loop: PANIC! Unknown " << label << " host '" << host
              << "'.\n" << std::flush;
4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329

      cerr << "Error" << ": Unknown " << label << " host '" << host
           << "'.\n";

      HandleCleanup();
      return -1;
    }
  }

  return ListenConnectionAny((sockaddr *)&tcpAddr, sizeof(tcpAddr), label);
}

int ListenConnection(ChannelEndPoint &endpoint, const char *label)
{
4330
  char *unixPath = NULL, *host = NULL;
4331
  long port;
4332
  int result = -1;
4333
  if (endpoint.getUnixPath(&unixPath)) {
4334
    result = ListenConnectionUnix(unixPath, label);
4335 4336
  }
  else if (endpoint.getTCPHostAndPort(&host, &port)) {
4337
    result = ListenConnectionTCP(host, port, label);
4338
  }
4339 4340
  SAFE_FREE(unixPath);
  SAFE_FREE(host);
4341
  return result;
4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352
}

static int AcceptConnection(int fd, int domain, const char *label)
{
  struct sockaddr newAddr;

  socklen_t addrLen = sizeof(newAddr);


  if (domain == AF_UNIX)
  {
4353
    nxinfo << "Loop: Going to accept new Unix " << label
4354 4355
           << " connection on FD#" << fd << ".\n"
           << std::flush;
4356 4357 4358
  }
  else
  {
4359
    nxinfo << "Loop: Going to accept new TCP " << label
4360 4361
           << " connection on FD#" << fd << ".\n"
           << std::flush;
4362 4363 4364 4365 4366 4367 4368
  }


  int newFD = accept(fd, &newAddr, &addrLen);

  if (newFD < 0)
  {
4369
    nxfatal << "Loop: PANIC! Call to accept failed for "
4370
            << label << " connection. Error is " << EGET()
4371
            << " '" << ESTR() << "'.\n" << std::flush;
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384

    cerr << "Error" << ": Call to accept failed for "
         << label << " connection. Error is " << EGET()
         << " '" << ESTR() << "'.\n";
  }

  return newFD;
}

void HandleShutdown()
{
  if (proxy -> getShutdown() == 0)
  {
4385
    nxfatal << "Loop: PANIC! No shutdown of proxy link "
4386
            << "performed by remote proxy.\n"
4387
            << std::flush;
4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403

    //
    // Close the socket before showing the alert.
    // It seems that the closure of the socket can
    // sometimes take several seconds, even after
    // the connection is broken. The result is that
    // the dialog can be shown long after the user
    // has gone after the failed session. Note that
    // disabling the linger timeout does not seem
    // to make any difference.
    //

    CleanupSockets();

    cerr << "Error" << ": Connection with remote peer broken.\n";

4404
    nxinfo << "Loop: Bytes received so far are "
4405 4406
           << (unsigned long long) statistics -> getBytesIn()
           << ".\n" << std::flush;
4407 4408 4409 4410 4411 4412 4413 4414

    cerr << "Error" << ": Please check the state of your "
         << "network and retry.\n";

    handleTerminatingInLoop();

    if (control -> ProxyMode == proxy_server)
    {
4415
      nxinfo << "Loop: Showing the proxy abort dialog.\n"
4416
             << std::flush;
4417 4418 4419 4420 4421 4422 4423 4424

      HandleAlert(ABORT_PROXY_CONNECTION_ALERT, 1);

      handleAlertInLoop();
    }
  }
  else
  {
4425
    nxinfo << "Loop: Finalized the remote proxy shutdown.\n"
4426
           << std::flush;
4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448
  }

  HandleCleanup();
}


void WaitCleanup()
{
  T_timestamp selectTs;

  while (NXTransRunning(NX_FD_ANY))
  {
    setTimestamp(selectTs, control -> PingTimeout);

    NXTransContinue(&selectTs);
  }
}

int KillProcess(int pid, const char *label, int signal, int wait)
{
  if (pid > 0)
  {
4449
    nxinfo << "Loop: Killing the " << label << " process '"
4450 4451 4452
           << pid << "' from process with pid '" << getpid()
           << "' with signal '" << DumpSignal(signal)
           << "'.\n" << std::flush;
4453 4454 4455 4456 4457

    signal = (signal == 0 ? SIGTERM : signal);

    if (kill(pid, signal) < 0 && EGET() != ESRCH)
    {
4458
      nxfatal << "Loop: PANIC! Couldn't kill the " << label
4459
              << " process with pid '" << pid << "'.\n"
4460
              << std::flush;
4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474

      cerr << "Error" << ": Couldn't kill the " << label
           << " process with pid '" << pid << "'.\n";
    }

    if (wait == 1)
    {
      WaitChild(pid, label, 1);
    }

    return 1;
  }
  else
  {
4475
    nxinfo << "Loop: No " << label << " process "
4476 4477
           << "to kill with pid '" << pid
           << "'.\n" << std::flush;
4478 4479 4480 4481 4482 4483 4484

    return 0;
  }
}

int CheckProcess(int pid, const char *label)
{
4485
  nxinfo << "Loop: Checking the " << label << " process '"
4486 4487
         << pid << "' from process with pid '" << getpid()
         << "'.\n" << std::flush;
4488 4489 4490

  if (kill(pid, SIGCONT) < 0 && EGET() == ESRCH)
  {
4491
    nxwarn << "Loop: WARNING! The " << label << " process "
4492 4493
           << "with pid '" << pid << "' has exited.\n"
           << std::flush;
4494 4495 4496 4497 4498 4499 4500 4501 4502 4503

    cerr << "Warning" << ": The " << label << " process "
         << "with pid '" << pid << "' has exited.\n";

    return 0;
  }

  return 1;
}

4504
void StartKeeper()
4505 4506 4507 4508 4509
{

  if (IsRunning(lastKeeper) == 1 ||
          IsRestarting(lastKeeper) == 1)
  {
4510
    nxfatal << "Loop: PANIC! The house-keeping process is "
4511
            << "already running with pid '" << lastKeeper
4512
            << "'.\n" << std::flush;
4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533

    HandleCleanup();
  }


  //
  // Don't care harvesting the persistent caches if
  // the memory cache is not enabled. If the memory
  // cache is not enabled neither we produced per-
  // sistent caches. The user can still delete any
  // persistent cache produced by the previous runs
  // by using the client GUI.
  //
  // TODO: At the moment the user doesn't have a way
  // to specify the amount of disk space to use for
  // the persistent caches, but only the amount of
  // space to use for images.
  //

  if (control -> LocalTotalStorageSize > 0)
  {
4534
    nxinfo << "Loop: Starting the house-keeping process with "
4535 4536
           << "storage size " << control -> PersistentCacheDiskLimit
           << ".\n" << std::flush;
4537 4538 4539 4540 4541 4542

    lastKeeper = NXTransKeeper(control -> PersistentCacheDiskLimit,
                                   0, control -> RootPath);

    if (IsFailed(lastKeeper))
    {
4543
      nxwarn << "Loop: WARNING! Failed to start the NX keeper process.\n"
4544
             << std::flush;
4545 4546 4547 4548 4549 4550 4551

      cerr << "Warning" << ": Failed to start the NX keeper process.\n";

      SetNotRunning(lastKeeper);
    }
    else
    {
4552
      nxinfo << "Loop: Keeper started with pid '"
4553
             << lastKeeper << "'.\n" << std::flush;
4554 4555 4556 4557
    }
  }
  else
  {
4558
    nxinfo << "Loop: Nothing to do for the keeper process "
4559 4560
           << "with persistent cache not enabled.\n"
           << std::flush;
4561 4562 4563
  }
}

4564 4565
void HandleCleanupForReconnect()
{
4566
  nxinfo << "Loop: Going to clean up system resources for Reconnect "
4567 4568
         << "in process '" << getpid() << "'.\n"
         << std::flush;
4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583
  handleTerminatedInLoop();
  DisableSignals();
  if (control)
    CleanupChildren();
  CleanupListeners();
  CleanupSockets();
  CleanupKeeper();
  CleanupStreams();
  CleanupLocal();
  CleanupGlobal();
  RestoreSignals();
  ServerCache::lastInitReply.set(0,NULL);
  ServerCache::lastKeymap.set(0,NULL);
  ServerCache::getKeyboardMappingLastMap.set(0,NULL);
}
4584 4585
void HandleCleanup(int code)
{
4586
  nxinfo << "Loop: Going to clean up system resources "
4587 4588
         << "in process '" << getpid() << "'.\n"
         << std::flush;
4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642

  handleTerminatedInLoop();

  //
  // Suspend any signal while cleaning up.
  //

  DisableSignals();

  if (getpid() == lastProxy)
  {
    //
    // Terminate all the children.
    //

    CleanupChildren();
  
    //
    // Close all listeners.
    //

    CleanupListeners();

    //
    // Close all sockets.
    //

    CleanupSockets();

    //
    // Release the global objects.
    //

    CleanupGlobal();

    //
    // Restore the original signal handlers.
    //

    RestoreSignals();
  }

  //
  // This is our last chance to print a message. If this
  // is the process which created the transport we will
  // jump back into the loop, letting the caller find out
  // that the connection is broken, otherwise we assume
  // that this is a child of the proxy and so we will
  // safely exit.
  //


  if (getpid() == lastProxy)
  {
4643
    nxinfo << "Loop: Reverting to loop context in process with "
4644 4645
           << "pid '" << getpid() << "' at " << strMsTimestamp()
           << ".\n" << std::flush;
4646 4647 4648
  }
  else
  {
4649
    nxinfo << "Loop: Exiting from child process with pid '"
4650 4651
           << getpid() << "' at " << strMsTimestamp()
           << ".\n" << std::flush;
4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685
  }


  if (getpid() == lastProxy)
  {
    //
    // Reset all values to their default.
    //

    CleanupLocal();

    CleanupStreams();

    longjmp(context, 1);
  }
  else
  {
    //
    // Give a last chance to the process
    // to cleanup the ancillary classes.
    //

    CleanupKeeper();

    CleanupStreams();

    exit(code);
  }
}

void CleanupKeeper()
{
  if (keeper != NULL)
  {
4686
    nxinfo << "Loop: Freeing up keeper in process "
4687 4688
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706

    delete keeper;

    keeper = NULL;
  }
}

void CleanupStreams()
{
  //
  // TODO: The cleanup procedure skips deletion of
  // the I/O streams under Windows. This is intended
  // to avoid a strange segfault occurring randomly,
  // at the time the proxy is being shut down.
  //

  #ifndef __CYGWIN32__

4707
  nxinfo << "Loop: Freeing up streams in process "
4708 4709
         << "with pid '" << getpid() << "'.\n"
         << std::flush;
4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804

  if (logofs != NULL && logofs != &cerr &&
          *errorsFileName != '\0')
  {
    *logofs << flush;

    delete logofs;

    //
    // Let the log go again to the standard
    // error.
    //

    logofs = &cerr;
  }

  if (statofs != NULL && statofs != &cerr &&
          *statsFileName != '\0')
  {
    *statofs << flush;

    delete statofs;

    statofs = NULL;
  }

  if (errofs != NULL)
  {
    *errofs << flush;

    if (errofs == &cerr)
    {
      errofs = NULL;
    }
    else if (errsbuf != NULL)
    {
      cerr.rdbuf(errsbuf);

      errsbuf = NULL;

      delete errofs;
    }

    errofs = NULL;
  }

  #endif /* #ifndef __CYGWIN32__ */

  //
  // Reset these as they can't be reset
  // in CleanupLocal().
  //

  *sessionFileName = '\0';
  *errorsFileName  = '\0';
  *optionsFileName = '\0';
  *statsFileName   = '\0';
}

void CleanupChildren()
{
  //
  // Remove any watchdog.
  //

  if (IsRunning(lastWatchdog))
  {
    KillProcess(lastWatchdog, "watchdog", SIGTERM, 1);

    SetNotRunning(lastWatchdog);

    lastSignal = 0;
  }

  //
  // Kill the cache house-keeping process.
  //

  if (IsRunning(lastKeeper))
  {
    KillProcess(lastKeeper, "house-keeping", SIGTERM, 1);

    SetNotRunning(lastKeeper);
  }

  //
  // Let any running dialog to continue until it is
  // closed by the user. In general this is the exp-
  // ected behaviour, as for example when we are
  // exiting because the link was abrouptedly shut
  // down.
  //

  if (IsRunning(lastDialog))
  {
4805
    nxinfo << "Loop: WARNING! Leaving the dialog process '"
4806 4807 4808
           << lastDialog << "' running in process "
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
4809 4810 4811 4812 4813 4814 4815 4816 4817 4818

    SetNotRunning(lastDialog);
  }

  //
  // Give user a chance to start a new session.
  //

  if (control -> EnableRestartOnShutdown == 1)
  {
4819
    nxwarn << "Loop: WARNING! Respawning the NX client "
4820 4821
           << "on display '" << displayHost << "'.\n"
           << std::flush;
4822 4823 4824 4825 4826 4827

    NXTransClient(displayHost);
  }

  for (int i = 0; i < control -> KillDaemonOnShutdownNumber; i++)
  {
4828
    nxwarn << "Loop: WARNING! Killing the NX daemon with "
4829 4830
           << "pid '" << control -> KillDaemonOnShutdown[i]
           << "'.\n" << std::flush;
4831 4832

    KillProcess(control -> KillDaemonOnShutdown[i], "daemon", SIGTERM, 0);
4833
  }
4834 4835 4836 4837 4838 4839
}

void CleanupGlobal()
{
  if (proxy != NULL)
  {
4840
    nxinfo << "Loop: Freeing up proxy in process "
4841 4842
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
4843 4844 4845 4846 4847 4848 4849 4850

    delete proxy;

    proxy = NULL;
  }

  if (agent != NULL)
  {
4851
    nxinfo << "Loop: Freeing up agent in process "
4852 4853
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
4854 4855 4856 4857 4858 4859 4860 4861

    delete agent;

    agent = NULL;
  }

  if (auth != NULL)
  {
4862
    nxinfo << "Loop: Freeing up auth data in process "
4863 4864
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
4865 4866 4867 4868 4869 4870 4871 4872

    delete auth;

    auth = NULL;
  }

  if (statistics != NULL)
  {
4873
    nxinfo << "Loop: Freeing up statistics in process "
4874 4875
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
4876 4877 4878 4879 4880 4881 4882 4883

    delete statistics;

    statistics = NULL;
  }

  if (control != NULL)
  {
4884
    nxinfo << "Loop: Freeing up control in process "
4885 4886
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897

    delete control;

    control = NULL;
  }
}

void CleanupConnections()
{
  if (proxy -> getChannels(channel_x11) != 0)
  {
4898
    nxinfo << "Loop: Closing any remaining X connections.\n"
4899
           << std::flush;
4900 4901 4902

    proxy -> handleCloseAllXConnections();

4903
    nxinfo << "Loop: Closing any remaining listener.\n"
4904
           << std::flush;
4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917

    proxy -> handleCloseAllListeners();
  }

  proxy -> handleFinish();
}

void CleanupListeners()
{
  if (useTcpSocket == 1)
  {
    if (tcpFD != -1)
    {
4918
      nxinfo << "Loop: Closing TCP listener in process "
4919 4920
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933

      close(tcpFD);

      tcpFD = -1;
    }

    useTcpSocket = 0;
  }

  if (useUnixSocket == 1)
  {
    if (unixFD != -1)
    {
4934
      nxinfo << "Loop: Closing UNIX listener in process "
4935 4936
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
4937 4938 4939 4940 4941 4942 4943 4944

      close(unixFD);

      unixFD = -1;
    }

    if (*unixSocketName != '\0')
    {
4945
      nxinfo << "Loop: Going to remove the Unix domain socket '"
4946 4947
             << unixSocketName << "' in process " << "with pid '"
             << getpid() << "'.\n" << std::flush;
4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968

      unlink(unixSocketName);
    }

    useUnixSocket = 0;
  }

  if (useAgentSocket == 1)
  {
    //
    // There is no listener for the
    // agent descriptor.
    //

    useAgentSocket = 0;
  }

  if (useCupsSocket == 1)
  {
    if (cupsFD != -1)
    {
4969
      nxinfo << "Loop: Closing CUPS listener in process "
4970 4971
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984

      close(cupsFD);

      cupsFD = -1;
    }

    useCupsSocket = 0;
  }

  if (useAuxSocket == 1)
  {
    if (auxFD != -1)
    {
4985
      nxinfo << "Loop: Closing auxiliary X11 listener "
4986 4987
             << "in process " << "with pid '" << getpid()
             << "'.\n" << std::flush;
4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000

      close(auxFD);

      auxFD = -1;
    }

    useAuxSocket = 0;
  }

  if (useSmbSocket == 1)
  {
    if (smbFD != -1)
    {
5001
      nxinfo << "Loop: Closing SMB listener in process "
5002 5003
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016

      close(smbFD);

      smbFD = -1;
    }

    useSmbSocket = 0;
  }

  if (useMediaSocket == 1)
  {
    if (mediaFD != -1)
    {
5017
      nxinfo << "Loop: Closing multimedia listener in process "
5018 5019
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032

      close(mediaFD);

      mediaFD = -1;
    }

    useMediaSocket = 0;
  }

  if (useHttpSocket == 1)
  {
    if (httpFD != -1)
    {
5033
      nxinfo << "Loop: Closing http listener in process "
5034 5035
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048

      close(httpFD);

      httpFD = -1;
    }

    useHttpSocket = 0;
  }

  if (useFontSocket == 1)
  {
    if (fontFD != -1)
    {
5049
      nxinfo << "Loop: Closing font server listener in process "
5050 5051
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064

      close(fontFD);

      fontFD = -1;
    }

    useFontSocket = 0;
  }

  if (useSlaveSocket == 1)
  {
    if (slaveFD != -1)
    {
5065
      nxinfo << "Loop: Closing slave listener in process "
5066 5067
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081

      close(slaveFD);

      slaveFD = -1;
    }

    useSlaveSocket = 0;
  }
}

void CleanupSockets()
{
  if (proxyFD != -1)
  {
5082
    nxinfo << "Loop: Closing proxy FD in process "
5083 5084
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
5085 5086 5087 5088 5089 5090 5091 5092

    close(proxyFD);

    proxyFD = -1;
  }

  if (agentFD[1] != -1)
  {
5093
    nxinfo << "Loop: Closing agent FD in process "
5094 5095
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177

    close(agentFD[1]);

    agentFD[0] = -1;
    agentFD[1] = -1;
  }
}

void CleanupLocal()
{
  *homeDir    = '\0';
  *rootDir    = '\0';
  *tempDir    = '\0';
  *systemDir  = '\0';
  *sessionDir = '\0';

  *linkSpeedName    = '\0';
  *cacheSizeName    = '\0';
  *shsegSizeName    = '\0';
  *imagesSizeName   = '\0';
  *bitrateLimitName = '\0';
  *packMethodName   = '\0';
  *productName      = '\0';

  packMethod  = -1;
  packQuality = -1;

  *sessionType = '\0';
  *sessionId   = '\0';

  parsedOptions = 0;
  parsedCommand = 0;

  *remoteData = '\0';
  remotePosition = 0;

  tcpFD   = -1;
  unixFD  = -1;
  cupsFD  = -1;
  auxFD   = -1;
  smbFD   = -1;
  mediaFD = -1;
  httpFD  = -1;
  fontFD  = -1;
  slaveFD = -1;
  proxyFD = -1;

  agentFD[0] = -1;
  agentFD[1] = -1;

  useUnixSocket  = 1;
  useTcpSocket   = 1;
  useCupsSocket  = 0;
  useAuxSocket   = 0;
  useSmbSocket   = 0;
  useMediaSocket = 0;
  useHttpSocket  = 0;
  useFontSocket  = 0;
  useSlaveSocket = 0;
  useAgentSocket = 0;

  useNoDelay = -1;
  usePolicy  = -1;
  useRender  = -1;
  useTaint   = -1;

  *unixSocketName = '\0';

  *acceptHost  = '\0';
  *displayHost = '\0';
  *authCookie  = '\0';

  proxyPort = DEFAULT_NX_PROXY_PORT;
  xPort     = DEFAULT_NX_X_PORT;

  xServerAddrFamily = -1;
  xServerAddrLength = 0;

  delete xServerAddr;

  xServerAddr = NULL;

5178 5179
  listenSocket.disable();
  connectSocket.disable();
5180

5181 5182 5183 5184 5185 5186
  cupsPort.disable();
  auxPort.disable();
  smbPort.disable();
  mediaPort.disable();
  httpPort.disable();
  slavePort.disable();
5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236

  *fontPort = '\0';

  *bindHost = '\0';
  bindPort = -1;

  initTs  = nullTimestamp();
  startTs = nullTimestamp();
  logsTs  = nullTimestamp();
  nowTs   = nullTimestamp();

  lastProxy    = 0;
  lastDialog   = 0;
  lastWatchdog = 0;
  lastKeeper   = 0;
  lastStatus   = 0;
  lastKill     = 0;
  lastDestroy  = 0;

  lastReadableTs = nullTimestamp();

  lastAlert.code  = 0;
  lastAlert.local = 0;

  lastMasks.blocked   = 0;
  lastMasks.installed = 0;

  memset(&lastMasks.saved, 0, sizeof(sigset_t));

  for (int i = 0; i < 32; i++)
  {
    lastMasks.enabled[i] = 0;
    lastMasks.forward[i] = 0;

    memset(&lastMasks.action[i], 0, sizeof(struct sigaction));
  }

  lastSignal = 0;

  memset(&lastTimer.action, 0, sizeof(struct sigaction));
  memset(&lastTimer.value,  0, sizeof(struct itimerval));

  lastTimer.start = nullTimestamp();
  lastTimer.next  = nullTimestamp();
}

int CheckAbort()
{
  if (lastSignal != 0)
  {
5237
    nxinfo << "Loop: Aborting the procedure due to signal '"
5238 5239
           << lastSignal << "', '" << DumpSignal(lastSignal)
           << "'.\n" << std::flush;
5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294

    cerr << "Info" << ": Aborting the procedure due to signal '"
         << lastSignal << "'.\n";

    lastSignal = 0;

    return 1;
  }

  return 0;
}

void HandleAbort()
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  *logofs << flush;

  handleTerminatingInLoop();

  if (lastSignal == SIGHUP)
  {
    lastSignal = 0;
  }

  //
  // The current default is to just quit the program.
  // Code has not been updated to deal with the new
  // NX transport loop.
  //

  if (control -> EnableCoreDumpOnAbort == 1)
  {
    if (agent != NULL)
    {
      cerr << "Session" << ": Terminating session at '"
           << strTimestamp() << "'.\n";
    }

    cerr << "Error" << ": Generating a core file to help "
         << "the investigations.\n";

    cerr << "Session" << ": Session terminated at '"
         << strTimestamp() << "'.\n";

    cerr << flush;

    signal(SIGABRT, SIG_DFL);

    raise(SIGABRT);
  }

5295
  nxinfo << "Loop: Showing the proxy abort dialog.\n"
5296
         << std::flush;
5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327

  if (control -> ProxyMode == proxy_server)
  {
    //
    // Close the socket before showing the alert.
    // It seems that the closure of the socket can
    // sometimes take several seconds, even after
    // the connection is broken.
    //

    CleanupSockets();

    if (lastKill == 0)
    {
      HandleAlert(ABORT_PROXY_CONNECTION_ALERT, 1);
    }
    else
    {
      HandleAlert(ABORT_PROXY_SHUTDOWN_ALERT, 1);
    }

    handleAlertInLoop();
  }

  HandleCleanup();
}

void HandleAlert(int code, int local)
{
  if (lastAlert.code == 0)
  {
5328
    nxinfo << "Loop: Requesting an alert dialog with code "
5329 5330
           << code << " and local " << local << ".\n"
           << std::flush;
5331 5332 5333 5334 5335 5336

    lastAlert.code  = code;
    lastAlert.local = local;
  }
  else
  {
5337
    nxinfo << "Loop: WARNING! Alert dialog already requested "
5338 5339
           << "with code " << lastAlert.code << ".\n"
           << std::flush;
5340 5341 5342 5343 5344 5345 5346 5347 5348
  }

  return;
}

void FlushCallback(int length)
{
  if (flushCallback != NULL)
  {
5349
    nxinfo << "Loop: Reporting a flush request at "
5350 5351
           << strMsTimestamp() << " with " << length
           << " bytes written.\n" << std::flush;
5352 5353 5354 5355 5356

    (*flushCallback)(flushParameter, length);
  }
  else if (control -> ProxyMode == proxy_client)
  {
5357
    nxinfo << "Loop: WARNING! Can't find a flush "
5358 5359
           << "callback in process with pid '" << getpid()
           << "'.\n" << std::flush;
5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374
  }
}

void KeeperCallback()
{
  if (IsRunning(lastKeeper) == 0)
  {
    //
    // Let the house-keeping process take care
    // of the persistent image cache.
    //

    if (control -> ImageCacheEnableLoad == 1 ||
            control -> ImageCacheEnableSave == 1)
    {
5375
      nxinfo << "Loop: Starting the house-keeping process with "
5376 5377
             << "image storage size " << control -> ImageCacheDiskLimit
             << ".\n" << std::flush;
5378 5379 5380 5381 5382 5383

      lastKeeper = NXTransKeeper(0, control -> ImageCacheDiskLimit,
                                     control -> RootPath);

      if (IsFailed(lastKeeper))
      {
5384
        nxwarn << "Loop: WARNING! Can't start the NX keeper process.\n"
5385
               << std::flush;
5386 5387 5388 5389 5390

        SetNotRunning(lastKeeper);
      }
      else
      {
5391
        nxinfo << "Loop: Keeper started with pid '"
5392
               << lastKeeper << "'.\n" << std::flush;
5393 5394 5395 5396
      }
    }
    else
    {
5397
      nxinfo << "Loop: Nothing to do for the keeper process "
5398 5399
             << "with image cache not enabled.\n"
             << std::flush;
5400 5401 5402 5403
    }
  }
  else
  {
5404
    nxinfo << "Loop: Nothing to do with the keeper process "
5405
           << "already running.\n" << std::flush;
5406 5407 5408 5409 5410
  }
}

void InstallSignals()
{
5411
  nxinfo << "Loop: Installing signals in process with pid '"
5412
         << getpid() << "'.\n" << std::flush;
5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427

  for (int i = 0; i < 32; i++)
  {
    if (CheckSignal(i) == 1 &&
          lastMasks.enabled[i] == 0)
    {
      InstallSignal(i, NX_SIGNAL_ENABLE);
    }
  }

  lastMasks.installed = 1;
}

void RestoreSignals()
{
5428
  nxinfo << "Loop: Restoring signals in process with pid '"
5429
         << getpid() << "'.\n" << std::flush;
5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471

  if (lastMasks.installed == 1)
  {
    //
    // Need to keep monitoring the children.
    //

    for (int i = 0; i < 32; i++)
    {
      if (lastMasks.enabled[i] == 1)
      {
        RestoreSignal(i);
      }
    }
  }

  lastMasks.installed = 0;

  if (lastMasks.blocked == 1)
  {
    EnableSignals();
  }
}

void DisableSignals()
{
  if (lastMasks.blocked == 0)
  {
    sigset_t newMask;

    sigemptyset(&newMask);

    //
    // Block also the other signals that may be
    // installed by the agent, that are those
    // signals for which the function returns 2.
    //

    for (int i = 0; i < 32; i++)
    {
      if (CheckSignal(i) > 0)
      {
5472
        nxdbg << "Loop: Disabling signal " << i << " '"
5473 5474
              << DumpSignal(i) << "' in process with pid '"
              << getpid() << "'.\n" << std::flush;
5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485

        sigaddset(&newMask, i);
      }
    }

    sigprocmask(SIG_BLOCK, &newMask, &lastMasks.saved);

    lastMasks.blocked++;
  }
  else
  {
5486
    nxinfo << "Loop: WARNING! Signals were already blocked in "
5487 5488
           << "process with pid '" << getpid() << "'.\n"
           << std::flush;
5489 5490 5491 5492 5493 5494 5495
  }
}

void EnableSignals()
{
  if (lastMasks.blocked == 1)
  {
5496
    nxinfo << "Loop: Enabling signals in process with pid '"
5497
           << getpid() << "'.\n" << std::flush;
5498 5499 5500 5501 5502 5503 5504

    sigprocmask(SIG_SETMASK, &lastMasks.saved, NULL);

    lastMasks.blocked = 0;
  }
  else
  {
5505
    nxwarn << "Loop: WARNING! Signals were not blocked in "
5506 5507
           << "process with pid '" << getpid() << "'.\n"
           << std::flush;
5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519

    cerr << "Warning" << ": Signals were not blocked in "
         << "process with pid '" << getpid() << "'.\n";
  }
}

void InstallSignal(int signal, int action)
{
  if (lastMasks.enabled[signal] == 1)
  {
    if (action == NX_SIGNAL_FORWARD)
    {
5520
      nxinfo << "Loop: Forwarding handler for signal " << signal
5521 5522 5523
             << " '" << DumpSignal(signal) << "' in process "
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
5524 5525 5526 5527 5528 5529 5530

      lastMasks.forward[signal] = 1;

      return;
    }
    else
    {
5531
      nxinfo << "Loop: Reinstalling handler for signal " << signal
5532 5533 5534
             << " '" << DumpSignal(signal) << "' in process "
             << "with pid '" << getpid() << "'.\n"
             << std::flush;
5535 5536 5537 5538
    }
  }
  else
  {
5539
    nxinfo << "Loop: Installing handler for signal " << signal
5540 5541 5542
           << " '" << DumpSignal(signal) << "' in process "
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
5543 5544 5545 5546 5547 5548 5549 5550 5551
  }

  if (signal == SIGALRM && isTimestamp(lastTimer.start))
  {
    ResetTimer();
  }

  struct sigaction newAction;

5552
  memset(&newAction, 0, sizeof(newAction));
Mike Gabriel's avatar
Mike Gabriel committed
5553

5554
  newAction.sa_handler = HandleSignal;
Mike Gabriel's avatar
Mike Gabriel committed
5555

5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580
  sigemptyset(&(newAction.sa_mask));

  if (signal == SIGCHLD)
  {
    newAction.sa_flags = SA_NOCLDSTOP;
  }
  else
  {
    newAction.sa_flags = 0;
  }

  sigaction(signal, &newAction, &lastMasks.action[signal]);

  lastMasks.enabled[signal] = 1;

  if (action == NX_SIGNAL_FORWARD)
  {
    lastMasks.forward[signal] = 1;
  }
}

void RestoreSignal(int signal)
{
  if (lastMasks.enabled[signal] == 0)
  {
5581
    nxwarn << "Loop: WARNING! Signal '" << DumpSignal(signal)
5582
           << "' not installed in process with pid '"
5583
           << getpid() << "'.\n" << std::flush;
5584 5585

    cerr << "Warning" << ": Signal '" << DumpSignal(signal)
5586
         << "' not installed in process with pid '"
5587 5588 5589 5590 5591
         << getpid() << "'.\n";

    return;
  }

5592
  nxinfo << "Loop: Restoring handler for signal " << signal
5593 5594 5595
         << " '" << DumpSignal(signal) << "' in process "
         << "with pid '" << getpid() << "'.\n"
         << std::flush;
5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617

  if (signal == SIGALRM && isTimestamp(lastTimer.start))
  {
    ResetTimer();
  }

  sigaction(signal, &lastMasks.action[signal], NULL);

  lastMasks.enabled[signal] = 0;
  lastMasks.forward[signal] = 0;
}

void HandleSignal(int signal)
{
  if (logofs == NULL)
  {
    logofs = &cerr;
  }


  if (lastSignal != 0)
  {
5618
    nxinfo << "Loop: WARNING! Last signal is '" << lastSignal
5619 5620 5621
           << "', '" << DumpSignal(signal) << "' and not zero "
           << "in process with pid '" << getpid() << "'.\n"
           << std::flush;
5622 5623
  }

5624
  nxinfo << "Loop: Signal '" << signal << "', '"
5625 5626
         << DumpSignal(signal) << "' received in process "
         << "with pid '" << getpid() << "'.\n" << std::flush;
5627 5628


5629
  if (getpid() != lastProxy && signalHandler != NULL)
5630
  {
5631
    nxinfo << "Loop: Calling slave handler in process "
5632 5633
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
5634

5635
    if ((*signalHandler)(signal) == 0)
5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670
    {
      return;
    }
  }

  switch (signal)
  {
    case SIGUSR1:
    {
      if (proxy != NULL && lastSignal == 0)
      {
        lastSignal = SIGUSR1;
      }

      break;
    }
    case SIGUSR2:
    {
      if (proxy != NULL && lastSignal == 0)
      {
        lastSignal = SIGUSR2;
      }

      break;
    }
    case SIGPIPE:
    {
      //
      // It can happen that SIGPIPE is delivered
      // to the proxy even in the case some other
      // descriptor is unexpectedly closed.
      //
      // if (agentFD[1] != -1)
      // {
      //   cerr << "Info" << ": Received signal 'SIGPIPE'. "
5671
      //        << "Closing agent connection.\n";
5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717
      //
      //   shutdown(agentFD[1], SHUT_RDWR);
      // }
      //

      break;
    }
    case SIGALRM:
    {
      //
      // Nothing to do. Just wake up the
      // process on blocking operations.
      //

      break;
    }
    case SIGCHLD:
    {
      //
      // Check if any of our children has exited.
      //

      if (HandleChildren() != 0)
      {
        signal = 0;
      }

      //
      // Don't save this signal or it will override
      // any previous signal sent by child before
      // exiting.
      //

      break;
    }

    #ifdef __CYGWIN32__

    case 12:
    {
      //
      // Nothing to do. This signal is what is delivered
      // by the Cygwin library when trying use a shared
      // memory function if the daemon is not running.
      //

5718
      nxinfo << "Loop: WARNING! Received signal '12' in "
5719 5720
             << "process with pid '" << getpid() << "'.\n"
             << std::flush;
5721

5722
      nxinfo << "Loop: WARNING! Please check that the "
5723 5724
             << "cygserver daemon is running.\n"
             << std::flush;
5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740

      break;
    }

    #endif

    default:
    {
      //
      // Register the signal so we can handle it
      // inside the main loop. We will probably
      // dispose any resource and exit.
      //

      if (getpid() == lastProxy)
      {
5741
        nxinfo << "Loop: Registering end of session request "
5742 5743 5744
               << "due to signal '" << signal << "', '"
               << DumpSignal(signal) << "'.\n"
               << std::flush;
5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763

        lastSignal = signal;
      }
      else
      {
        //
        // This is a child, so exit immediately.
        //

        HandleCleanup();
      }
    }
  }

  if (signal != 0 && lastMasks.forward[signal] == 1)
  {
    if (lastMasks.action[signal].sa_handler != NULL &&
            lastMasks.action[signal].sa_handler != HandleSignal)
    {
5764
      nxinfo << "Loop: Forwarding signal '" << signal << "', '"
5765 5766
             << DumpSignal(signal) << "' to previous handler.\n"
             << std::flush;
5767 5768 5769 5770 5771

      lastMasks.action[signal].sa_handler(signal);
    }
    else if (lastMasks.action[signal].sa_handler == NULL)
    {
5772
      nxwarn << "Loop: WARNING! Parent requested to forward "
5773 5774
             << "signal '" << signal << "', '" << DumpSignal(signal)
             << "' but didn't set a handler.\n" << std::flush;
5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788
    }
  }
}

int HandleChildren()
{
  //
  // Try to waitpid() for each child because the
  // call might have return ECHILD and so we may
  // have lost any of the processes.
  //

  if (IsRunning(lastDialog) && HandleChild(lastDialog) == 1)
  {
5789
    nxinfo << "Loop: Resetting pid of last dialog process "
5790
           << "in handler.\n" << std::flush;
5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803

    SetNotRunning(lastDialog);

    if (proxy != NULL)
    {
      proxy -> handleResetAlert();
    }

    return 1;
  }

  if (IsRunning(lastWatchdog) && HandleChild(lastWatchdog) == 1)
  {
5804
    nxinfo << "Loop: Watchdog is gone. Setting the last "
5805
           << "signal to SIGHUP.\n" << std::flush;
5806 5807 5808

    lastSignal = SIGHUP;

5809
    nxinfo << "Loop: Resetting pid of last watchdog process "
5810
           << "in handler.\n" << std::flush;
5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826

    SetNotRunning(lastWatchdog);

    return 1;
  }

  //
  // The house-keeping process exits after a
  // number of iterations to keep the memory
  // pollution low. It is restarted on demand
  // by the lower layers, using the callback
  // function.
  //

  if (IsRunning(lastKeeper) && HandleChild(lastKeeper) == 1)
  {
5827
    nxinfo << "Loop: Resetting pid of last house-keeping "
5828
           << "process in handler.\n" << std::flush;
5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841

    SetNotRunning(lastKeeper);

    return 1;
  }

  //
  // The pid will be checked by the code
  // that registered the child.
  //

  if (IsRunning(lastChild))
  {
5842
    nxinfo << "Loop: Resetting pid of last child process "
5843
           << "in handler.\n" << std::flush;
5844 5845 5846 5847 5848 5849

    SetNotRunning(lastChild);

    return 1;
  }

5850 5851
  proxy->checkSlaves();

5852 5853 5854 5855 5856 5857 5858
  //
  // This can actually happen either because we
  // reset the pid of the child process as soon
  // as we kill it, or because of a child process
  // of our parent.
  //

5859
  nxinfo << "Loop: Ignoring signal received for the "
5860
         << "unregistered child.\n" << std::flush;
5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886

  return 0;
}

int HandleChild(int child)
{
  int pid;

  int status  = 0;
  int options = WNOHANG | WUNTRACED;

  while ((pid = waitpid(child, &status, options)) &&
             pid == -1 && EGET() == EINTR);

  return CheckChild(pid, status);
}

int WaitChild(int child, const char* label, int force)
{
  int pid;

  int status  = 0;
  int options = WUNTRACED;

  for (;;)
  {
5887
    nxinfo << "Loop: Waiting for the " << label
5888 5889
           << " process '" << child << "' to die.\n"
           << std::flush;
5890 5891 5892 5893 5894 5895 5896 5897 5898 5899

    pid = waitpid(child, &status, options);

    if (pid == -1 && EGET() == EINTR)
    {
      if (force == 0)
      {
        return 0;
      }

5900
      nxwarn << "Loop: WARNING! Ignoring signal while "
5901 5902 5903
             << "waiting for the " << label << " process '"
             << child << "' to die.\n"
             << std::flush;
5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921

      continue;
    }

    break;
  }

  return (EGET() == ECHILD ? 1 : CheckChild(pid, status));
}

int CheckChild(int pid, int status)
{
  lastStatus = 0;

  if (pid > 0)
  {
    if (WIFSTOPPED(status))
    {
5922
      nxinfo << "Loop: Child process '" << pid << "' was stopped "
5923 5924
             << "with signal " << (WSTOPSIG(status)) << ".\n"
             << std::flush;
5925 5926 5927 5928 5929 5930 5931

      return 0;
    }
    else
    {
      if (WIFEXITED(status))
      {
5932
        nxinfo << "Loop: Child process '" << pid << "' exited "
5933 5934
               << "with status '" << (WEXITSTATUS(status))
               << "'.\n" << std::flush;
5935 5936 5937 5938 5939 5940 5941

        lastStatus = WEXITSTATUS(status);
      }
      else if (WIFSIGNALED(status))
      {
        if (CheckSignal(WTERMSIG(status)) != 1)
        {
5942
          nxwarn << "Loop: WARNING! Child process '" << pid
5943 5944 5945
                 << "' died because of signal " << (WTERMSIG(status))
                 << ", '" << DumpSignal(WTERMSIG(status)) << "'.\n"
                 << std::flush;
5946 5947 5948 5949 5950 5951 5952

          cerr << "Warning" << ": Child process '" << pid
               << "' died because of signal " << (WTERMSIG(status))
               << ", '" << DumpSignal(WTERMSIG(status)) << "'.\n";
        }
        else
        {
5953
          nxinfo << "Loop: Child process '" << pid
5954 5955 5956
                 << "' died because of signal " << (WTERMSIG(status))
                 << ", '" << DumpSignal(WTERMSIG(status)) << "'.\n"
                 << std::flush;
5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968
        }

        lastStatus = 1;
      }

      return 1;
    }
  }
  else if (pid < 0)
  {
    if (EGET() != ECHILD)
    {
5969
      nxfatal << "Loop: PANIC! Call to waitpid failed. "
5970
              << "Error is " << EGET() << " '" << ESTR()
5971
              << "'.\n" << std::flush;
5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985

      cerr << "Error" << ": Call to waitpid failed. "
           << "Error is " << EGET() << " '" << ESTR()
           << "'.\n";

      HandleCleanup();
    }

    //
    // This can happen when the waitpid() is
    // blocking, as the SIGCHLD is received
    // within the call.
    //

5986
    nxinfo << "Loop: No more children processes running.\n"
5987
           << std::flush;
5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999

    return 1;
  }

  return 0;
}

void RegisterChild(int child)
{

  if (IsNotRunning(lastChild))
  {
6000
    nxinfo << "Loop: Registering child process '" << child
6001 6002
           << "' in process with pid '" << getpid()
           << "'.\n" << std::flush;
6003 6004 6005
  }
  else
  {
6006
    nxinfo << "Loop: WARNING! Overriding registered child '"
6007 6008 6009
           << lastChild << "' with new child '" << child
           << "' in process with pid '" << getpid()
           << "'.\n" << std::flush;
6010 6011 6012 6013 6014 6015
  }


  lastChild = child;
}

6016
int CheckParent(const char *name, const char *type, int parent)
6017 6018 6019
{
  if (parent != getppid() || parent == 1)
  {
6020
    nxwarn << name << ": WARNING! Parent process appears "
6021 6022
           << "to be dead. Exiting " << type << ".\n"
           << std::flush;
6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038

    cerr << "Warning" << ": Parent process appears "
         << "to be dead. Exiting " << type << ".\n";

    return 0;
  }

  return 1;
}

void HandleTimer(int signal)
{
  if (signal == SIGALRM)
  {
    if (isTimestamp(lastTimer.start))
    {
6039
      nxinfo << "Loop: Timer expired at " << strMsTimestamp()
6040 6041
             << " in process with pid '" << getpid() << "'.\n"
             << std::flush;
6042 6043 6044 6045 6046 6047 6048 6049 6050 6051

      if (proxy != NULL)
      {
        proxy -> handleTimer();
      }

      ResetTimer();
    }
    else
    {
6052
      nxfatal << "Loop: PANIC! Inconsistent timer state "
6053
              << " in process with pid '" << getpid() << "'.\n"
6054
              << std::flush;
6055 6056 6057 6058 6059 6060 6061

      cerr << "Error" << ": Inconsistent timer state "
           << " in process with pid '" << getpid() << "'.\n";
    }
  }
  else
  {
6062
    nxfatal << "Loop: PANIC! Inconsistent signal '"
6063 6064
            << signal << "', '" << DumpSignal(signal)
            << "' received in process with pid '"
6065
            << getpid() << "'.\n" << std::flush;
6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083

    cerr << "Error" << ": Inconsistent signal '"
         << signal << "', '" << DumpSignal(signal)
         << "' received in process with pid '"
         << getpid() << "'.\n";
  }
}

void SetTimer(int value)
{
  getNewTimestamp();

  if (isTimestamp(lastTimer.start))
  {
    int diffTs = diffTimestamp(lastTimer.start, getTimestamp());

    if (diffTs > lastTimer.next.tv_usec / 1000 * 2)
    {
6084
      nxwarn << "Loop: WARNING! Timer missed to expire at "
6085 6086
             << strMsTimestamp() << " in process with pid '"
             << getpid() << "'.\n" << std::flush;
6087 6088 6089 6090 6091 6092 6093 6094 6095

      cerr << "Warning" << ": Timer missed to expire at "
           << strMsTimestamp() << " in process with pid '"
           << getpid() << "'.\n";

      HandleTimer(SIGALRM);
    }
    else
    {
6096
      nxinfo << "Loop: Timer already running at "
6097 6098
             << strMsTimestamp() << " in process with pid '"
             << getpid() << "'.\n" << std::flush;
6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109

      return;
    }
  }

  //
  // Save the former handler.
  //

  struct sigaction action;

6110
  memset(&action, 0, sizeof(action));
Mike Gabriel's avatar
Mike Gabriel committed
6111

6112
  action.sa_handler = HandleTimer;
Mike Gabriel's avatar
Mike Gabriel committed
6113

6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130
  sigemptyset(&action.sa_mask);

  action.sa_flags = 0;

  sigaction(SIGALRM, &action, &lastTimer.action);

  //
  // Start the timer.
  //

  lastTimer.next = getTimestamp(value);

  struct itimerval timer;

  timer.it_interval = lastTimer.next;
  timer.it_value    = lastTimer.next;

6131
  nxinfo << "Loop: Timer set to " << lastTimer.next.tv_sec
6132 6133
         << " s and " << lastTimer.next.tv_usec / 1000
         << " ms at " << strMsTimestamp() << " in process "
6134 6135
         << "with pid '" << getpid() << "'.\n"
         << std::flush;
6136 6137 6138

  if (setitimer(ITIMER_REAL, &timer, &lastTimer.value) < 0)
  {
6139
    nxfatal << "Loop: PANIC! Call to setitimer failed. "
6140
            << "Error is " << EGET() << " '" << ESTR()
6141
            << "'.\n" << std::flush;
6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158

    cerr << "Error" << ": Call to setitimer failed. "
         << "Error is " << EGET() << " '" << ESTR()
         << "'.\n";

    lastTimer.next = nullTimestamp();

    return;
  }

  lastTimer.start = getTimestamp();
}

void ResetTimer()
{
  if (isTimestamp(lastTimer.start) == 0)
  {
6159
    nxinfo << "Loop: Timer not running in process "
6160 6161
           << "with pid '" << getpid() << "'.\n"
           << std::flush;
6162 6163 6164 6165

    return;
  }

6166
  nxinfo << "Loop: Timer reset at " << strMsTimestamp()
6167 6168
         << " in process with pid '" << getpid()
         << "'.\n" << std::flush;
6169 6170 6171 6172 6173 6174 6175

  //
  // Restore the old signal mask and timer.
  //

  if (setitimer(ITIMER_REAL, &lastTimer.value, NULL) < 0)
  {
6176
    nxfatal << "Loop: PANIC! Call to setitimer failed. "
6177
            << "Error is " << EGET() << " '" << ESTR()
6178
            << "'.\n" << std::flush;
6179 6180 6181 6182 6183 6184 6185 6186

    cerr << "Error" << ": Call to setitimer failed. "
         << "Error is " << EGET() << " '" << ESTR()
         << "'.\n";
  }

  if (sigaction(SIGALRM, &lastTimer.action, NULL) < 0)
  {
6187
    nxfatal << "Loop: PANIC! Call to sigaction failed. "
6188
            << "Error is " << EGET() << " '" << ESTR()
6189
            << "'.\n" << std::flush;
6190 6191 6192 6193 6194 6195 6196 6197 6198 6199

    cerr << "Error" << ": Call to sigaction failed. "
         << "Error is " << EGET() << " '" << ESTR()
         << "'.\n";
  }

  lastTimer.start = lastTimer.next = nullTimestamp();
}

//
6200 6201 6202 6203
// Open TCP or UNIX file socket to listen for remote proxy
// and block until remote connects. If successful close
// the listening socket and return FD on which the other
// party is connected.
6204 6205
//

6206
int WaitForRemote(ChannelEndPoint &socketAddress)
6207 6208
{
  char hostLabel[DEFAULT_STRING_LENGTH] = { 0 };
6209
  char *socketUri = NULL;
6210 6211 6212

  int retryAccept  = -1;

6213
  int pFD = -1;
6214 6215 6216 6217
  int newFD   = -1;

  int acceptIPAddr = 0;

6218
  if (socketAddress.isTCPSocket())
6219 6220
  {

6221 6222 6223 6224 6225
    //
    // Get IP address of host to be awaited.
    //

    if (*acceptHost != '\0')
6226
    {
6227
      acceptIPAddr = GetHostAddress(acceptHost);
6228

6229 6230
      if (acceptIPAddr == 0)
      {
6231 6232
        nxfatal << "Loop: PANIC! Cannot accept connections from unknown host '"
                << acceptHost << "'.\n" << std::flush;
6233

6234 6235 6236 6237 6238
        cerr << "Error" << ": Cannot accept connections from unknown host '"
             << acceptHost << "'.\n";

        goto WaitForRemoteError;
      }
6239
      snprintf(hostLabel, sizeof(hostLabel), "'%s'", acceptHost);
6240 6241 6242
    }
    else
    {
6243
      strcpy(hostLabel, "any host");
6244 6245
    }

6246 6247
    long _bindPort;
    if (socketAddress.getTCPHostAndPort(NULL, &_bindPort))
6248
    {
6249
      socketAddress.setSpec(loopbackBind ? "localhost" : "*", _bindPort);
6250 6251 6252 6253 6254
    }
    else
    {
      // This should never happen
      cerr << "Error" << ": Unable to change bind host\n";
6255 6256
    }
  }
6257 6258
  else if (socketAddress.isUnixSocket())
    strcpy(hostLabel, "this host");
6259
  else
6260 6261
    strcpy(hostLabel, "unknown origin (something went wrong!!!)");

6262

6263
  pFD = ListenConnection(socketAddress, "NX");
6264

6265 6266
  SAFE_FREE(socketUri);

6267
  socketAddress.getSpec(&socketUri);
6268
  nxinfo << "Loop: Waiting for connection from "
6269 6270
         << hostLabel  << " on socket '" << socketUri
         << "'.\n" << std::flush;
6271
  cerr << "Info" << ": Waiting for connection from "
6272
       << hostLabel << " on socket '" << socketUri
6273
       << "'.\n";
6274
  SAFE_FREE(socketUri);
6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292

  //
  // How many times to loop waiting for connections
  // from the selected host? Each loop wait for at
  // most 20 seconds so a default value of 3 gives
  // a timeout of 1 minute.
  //
  // TODO: Handling of timeouts and retry attempts
  // must be rewritten.
  //

  retryAccept = control -> OptionProxyRetryAccept;

  for (;;)
  {
    fd_set readSet;

    FD_ZERO(&readSet);
6293
    FD_SET(pFD, &readSet);
6294 6295 6296 6297 6298 6299

    T_timestamp selectTs;

    selectTs.tv_sec  = 20;
    selectTs.tv_usec = 0;

6300
    int result = select(pFD + 1, &readSet, NULL, NULL, &selectTs);
6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314

    getNewTimestamp();

    if (result == -1)
    {
      if (EGET() == EINTR)
      {
        if (CheckAbort() != 0)
        {
          goto WaitForRemoteError;
        }

        continue;
      }
6315

6316
      nxfatal << "Loop: PANIC! Call to select failed. Error is "
6317
              << EGET() << " '" << ESTR() << "'.\n"
6318
              << std::flush;
6319 6320 6321 6322 6323 6324

      cerr << "Error" << ": Call to select failed. Error is "
           << EGET() << " '" << ESTR() << "'.\n";

      goto WaitForRemoteError;
    }
6325
    else if (result > 0 && FD_ISSET(pFD, &readSet))
6326 6327
    {

6328
      sockaddr_in newAddrINET;
6329

6330 6331 6332
      if (socketAddress.isUnixSocket())
      {
        socklen_t addrLen = sizeof(sockaddr_un);
6333
        newFD = accept(pFD, NULL, &addrLen);
6334 6335 6336 6337
      }
      else if (socketAddress.isTCPSocket())
      {
        socklen_t addrLen = sizeof(sockaddr_in);
6338
        newFD = accept(pFD, (sockaddr *) &newAddrINET, &addrLen);
6339
      }
6340 6341
      if (newFD == -1)
      {
6342
        nxfatal << "Loop: PANIC! Call to accept failed. Error is "
6343
                << EGET() << " '" << ESTR() << "'.\n"
6344
                << std::flush;
6345 6346 6347 6348 6349 6350 6351

        cerr << "Error" << ": Call to accept failed. Error is "
             << EGET() << " '" << ESTR() << "'.\n";

        goto WaitForRemoteError;
      }

6352
      if (socketAddress.isUnixSocket())
6353 6354
      {

6355 6356
        char * unixPath = NULL;
        socketAddress.getUnixPath(&unixPath);
6357
        nxinfo << "Loop: Accepted connection from this host on Unix file socket '"
6358 6359
               << unixPath << "'.\n"
               << std::flush;
6360

6361 6362
        cerr << "Info" << ": Accepted connection from this host on Unix file socket '"
             << unixPath << "'.\n";
6363
        SAFE_FREE(unixPath);
6364 6365 6366

        break;
      }
6367
      else if (socketAddress.isTCPSocket())
6368 6369
      {

6370
        char *connectedHost = inet_ntoa(newAddrINET.sin_addr);
6371

6372 6373
        if (*acceptHost == '\0' || (int) newAddrINET.sin_addr.s_addr == acceptIPAddr)
        {
6374

6375 6376

          unsigned int connectedPort = ntohs(newAddrINET.sin_port);
6377
          nxinfo << "Loop: Accepted connection from '" << connectedHost
6378 6379
                 << "' with port '" << connectedPort << "'.\n"
                 << std::flush;
6380 6381 6382 6383 6384 6385 6386 6387

          cerr << "Info" << ": Accepted connection from '"
               << connectedHost << "'.\n";

          break;
        }
        else
        {
6388 6389
          nxfatal << "Loop: WARNING! Refusing connection from '" << connectedHost
                  << "' on port '" << socketAddress.getTCPPort() << "'.\n" << std::flush;
6390 6391 6392

          cerr << "Warning" << ": Refusing connection from '"
               << connectedHost << "'.\n";
6393
        }
6394 6395 6396 6397 6398 6399 6400 6401 6402 6403

        //
        // Not the best way to elude a DOS attack...
        //

        sleep(5);

        close(newFD);

      }
6404 6405 6406 6407 6408

    }

    if (--retryAccept == 0)
    {
6409 6410
      if (socketAddress.isUnixSocket())
      {
6411
        nxfatal << "Loop: PANIC! Connection via Unix file socket from this host "
6412
                << "could not be established.\n"
6413
                << std::flush;
6414 6415 6416 6417 6418

        cerr << "Error" << ": Connection via Unix file socket from this host "
             << "could not be established.\n";
      }
      else if (*acceptHost == '\0')
6419
      {
6420
        nxfatal << "Loop: PANIC! Connection with remote host "
6421
                << "could not be established.\n"
6422
                << std::flush;
6423 6424 6425 6426 6427 6428

        cerr << "Error" << ": Connection with remote host "
             << "could not be established.\n";
      }
      else
      {
6429
        nxfatal << "Loop: PANIC! Connection with remote host '"
6430
                << acceptHost << "' could not be established.\n"
6431
                << std::flush;
6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444

        cerr << "Error" << ": Connection with remote host '"
             << acceptHost << "' could not be established.\n";
      }

      goto WaitForRemoteError;
    }
    else
    {
      handleCheckSessionInConnect();
    }
  }

6445
  close(pFD);
6446 6447 6448 6449 6450

  return newFD;

WaitForRemoteError:

6451
  close(pFD);
6452 6453 6454 6455

  HandleCleanup();
}

6456
int PrepareProxyConnectionTCP(char** hostName, long int* portNum, int* timeout, int* proxyFileDescriptor, int* reason)
6457 6458
{

6459
  if (!proxyFileDescriptor)
6460
  {
6461 6462
    nxfatal << "Loop: PANIC! Implementation error (PrepareProxyConnectionTCP). "
            << "'proxyFileDescriptor' must not be a NULL pointer.\n" << std::flush;
6463 6464

    cerr << "Error" << ":  Implementation error (PrepareProxyConnectionTCP). "
6465
            << "'proxyFileDescriptor' must not be a NULL pointer.\n";
6466 6467 6468 6469 6470 6471

    return -1;
  }

  if (!reason)
  {
6472 6473
    nxfatal << "Loop: PANIC! Implementation error (PrepareProxyConnectionTCP). "
            << "'reason' must not be a NULL pointer.\n" << std::flush;
6474

6475 6476 6477 6478 6479 6480 6481
    cerr << "Error" << ":  Implementation error (PrepareProxyConnectionTCP). "
            << "'reason' must not be a NULL pointer.\n";

    return -1;
  }

  int remoteIPAddr = GetHostAddress(*hostName);
6482 6483
  if (remoteIPAddr == 0)
  {
6484 6485
    nxfatal << "Loop: PANIC! Unknown remote host '"
            << *hostName << "'.\n" << std::flush;
6486 6487
        cerr << "Error" << ": Unknown remote host '"
         << *hostName << "'.\n";
6488

6489
    SAFE_FREE(*hostName);
6490 6491 6492
    HandleCleanup();
  }

6493 6494 6495
  nxinfo << "Loop: Connecting to remote host '"
         << *hostName << ":" << *portNum << "'.\n"
         << std::flush;
6496 6497

  cerr << "Info" << ": Connecting to remote host '"
6498
       << *hostName << ":" << *portNum << "'.\n"
6499 6500
       << logofs_flush;

6501
  *proxyFileDescriptor = -1;
6502 6503 6504 6505 6506 6507 6508
  *reason = -1;

  sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(*portNum);
  addr.sin_addr.s_addr = remoteIPAddr;

6509
  *proxyFileDescriptor = socket(AF_INET, SOCK_STREAM, PF_UNSPEC);
6510 6511
  *reason = EGET();

6512
  if (*proxyFileDescriptor == -1)
6513
  {
6514
    nxfatal << "Loop: PANIC! Call to socket failed. "
6515
            << "Error is " << *reason << " '" << ESTR()
6516
            << "'.\n" << std::flush;
6517 6518 6519 6520 6521 6522 6523

    cerr << "Error" << ": Call to socket failed. "
         << "Error is " << *reason << " '" << ESTR()
         << "'.\n";
    return -1;

  }
6524
  else if (SetReuseAddress(*proxyFileDescriptor) < 0)
6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538
  {
    return -1;
  }

  //
  // Ensure operation is timed out
  // if there is a network problem.
  //

  if (timeout)
    SetTimer(*timeout);
  else
    SetTimer(20000);

6539
  int result = connect(*proxyFileDescriptor, (sockaddr *) &addr, sizeof(sockaddr_in));
6540 6541 6542 6543 6544 6545 6546 6547 6548

  *reason = EGET();

  ResetTimer();

  return result;

}

6549
int PrepareProxyConnectionUnix(char** path, int* timeout, int* proxyFileDescriptor, int* reason)
6550 6551
{

6552
  if (!proxyFileDescriptor)
6553
  {
6554 6555
    nxfatal << "Loop: PANIC! Implementation error (PrepareProxyConnectionUnix). "
            << "proxyFileDescriptor must not be a NULL pointer.\n" << std::flush;
6556 6557

    cerr << "Error" << ":  Implementation error (PrepareProxyConnectionUnix). "
6558
            << "proxyFileDescriptor must not be a NULL pointer.\n";
6559 6560 6561 6562 6563 6564

    return -1;
  }

  if (!reason)
  {
6565 6566
    nxfatal << "Loop: PANIC! Implementation error (PrepareProxyConnectionUnix). "
            << "'reason' must not be a NULL pointer.\n" << std::flush;
6567 6568 6569 6570 6571 6572 6573 6574 6575

    cerr << "Error" << ":  Implementation error (PrepareProxyConnectionUnix). "
            << "'reason' must not be a NULL pointer.\n";

    return -1;
  }

  /* FIXME: Add socket file existence and permission checks */

6576

6577
  *proxyFileDescriptor = -1;
6578 6579
  *reason = -1;

6580 6581 6582 6583 6584
  // determine the maximum number of characters that fit into struct
  // sockaddr_un's sun_path member
  const std::size_t sockpathlen =
    sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path);

6585 6586
  sockaddr_un addr;
  addr.sun_family = AF_UNIX;
6587
  snprintf(addr.sun_path, sockpathlen, "%s", *path);
6588

6589
  *proxyFileDescriptor = socket(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
6590 6591
  *reason = EGET();

6592
  if (*proxyFileDescriptor == -1)
6593
  {
6594
    nxfatal << "Loop: PANIC! Call to socket failed. "
6595
            << "Error is " << *reason << " '" << ESTR()
6596
            << "'.\n" << std::flush;
6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614

    cerr << "Error" << ": Call to socket failed. "
         << "Error is " << *reason << " '" << ESTR()
         << "'.\n";

    return -1;
  }

  //
  // Ensure operation is timed out
  // if there is a network problem.
  //

  if (timeout)
    SetTimer(*timeout);
  else
    SetTimer(20000);

6615
  int result = connect(*proxyFileDescriptor, (sockaddr *) &addr, sizeof(sockaddr_un));
6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631

  *reason = EGET();

  ResetTimer();

  return result;
}

//
// Connect to remote proxy. If successful
// return FD of connection, else return -1.
//

int ConnectToRemote(ChannelEndPoint &socketAddress)
{

6632 6633
  //
  // How many times we retry to connect to remote
6634
  // host / Unix domain socket in case of failure?
6635 6636 6637 6638 6639 6640 6641 6642
  //

  int retryConnect = control -> OptionProxyRetryConnect;

  //
  // Show an alert after 20 seconds and use the
  // same timeout to interrupt the connect. The
  // retry timeout is incremental, starting from
6643
  // 100 milliseconds up to 1 second.
6644 6645 6646 6647 6648 6649 6650 6651
  //

  int alertTimeout   = 20000;
  int connectTimeout = 20000;
  int retryTimeout   = 100;

  T_timestamp lastRetry = getNewTimestamp();

6652 6653
  int result = -1;
  int reason = -1;
6654
  int pFD = -1;
6655

6656 6657 6658
  char *hostName = NULL;
  long int portNum = -1;
  char *unixPath = NULL;
6659 6660 6661 6662

  for (;;)
  {

6663
    nxdbg << "Loop: Timer set to " << connectTimeout / 1000
6664
          << " s " << "with retry set to " << retryConnect
6665 6666
          << " in process with pid '" << getpid()
          << "'.\n" << std::flush;
6667

6668
    SAFE_FREE(hostName);
6669
    SAFE_FREE(unixPath);
6670

6671
    if (socketAddress.getUnixPath(&unixPath))
6672
      result = PrepareProxyConnectionUnix(&unixPath, &connectTimeout, &pFD, &reason);
6673
    else if (socketAddress.getTCPHostAndPort(&hostName, &portNum))
6674
      result = PrepareProxyConnectionTCP(&hostName, &portNum, &connectTimeout, &pFD, &reason);
6675 6676 6677

    if (result < 0)
    {
6678
      close(pFD);
6679 6680 6681 6682 6683 6684 6685 6686 6687

      if (CheckAbort() != 0)
      {
        goto ConnectToRemoteError;
      }
      else if (--retryConnect == 0)
      {
        ESET(reason);

6688 6689
        if (socketAddress.isUnixSocket())
        {
6690
          nxfatal << "Loop: PANIC! Connection to Unix file socket '"
6691 6692
                  << unixPath << "' failed. Error is "
                  << EGET() << " '" << ESTR() << "'.\n"
6693
                  << std::flush;
6694

6695 6696 6697 6698 6699 6700
          cerr << "Error" << ": Connection to Unix file socket '"
                  << unixPath << "' failed. Error is "
                  << EGET() << " '" << ESTR() << "'.\n";
        }
        else
        {
6701

6702
          nxfatal << "Loop: PANIC! Connection to '" << hostName
6703 6704
                  << ":" << portNum << "' failed. Error is "
                  << EGET() << " '" << ESTR() << "'.\n"
6705
                  << std::flush;
6706 6707 6708 6709 6710

          cerr << "Error" << ": Connection to '" << hostName
               << ":" << portNum << "' failed. Error is "
               << EGET() << " '" << ESTR() << "'.\n";
        }
6711 6712 6713 6714
        goto ConnectToRemoteError;
      }
      else
      {
6715
        nxinfo << "Loop: Sleeping " << retryTimeout
6716 6717
               << " ms before retrying.\n"
               << std::flush;
6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773

        usleep(retryTimeout * 1000);

        retryTimeout <<= 1;

        if (retryTimeout > 1000 * 1000)
        {
          retryTimeout = 1000 * 1000;
        }
      }

      //
      // Check if it is time to show an alert dialog.
      //

      if (diffTimestamp(lastRetry, getNewTimestamp()) >=
              (alertTimeout - control -> LatencyTimeout))
      {
        if (IsNotRunning(lastDialog))
        {
          handleCheckSessionInConnect();

          //
          // Wait for the dialog process to die
          // unless a signal is received.
          //

          while (IsRunning(lastDialog))
          {
            WaitChild(lastDialog, "dialog", 0);

            if (CheckAbort() != 0)
            {
              //
              // The client ignores the TERM signal
              // on Windows.
              //

              #ifdef __CYGWIN32__

              KillProcess(lastDialog, "dialog", SIGKILL, 1);

              #else

              KillProcess(lastDialog, "dialog", SIGTERM, 1);

              #endif

              goto ConnectToRemoteError;
            }
          }

          lastRetry = getTimestamp();
        }
      }
      {
6774
        nxinfo << "Loop: Not showing the dialog with "
6775 6776
               << (diffTimestamp(lastRetry, getTimestamp()) / 1000)
               << " seconds elapsed.\n" << std::flush;
6777 6778 6779 6780
      }

      ESET(reason);

6781
      if (unixPath && unixPath[0] != '\0' )
6782
      {
6783
        nxinfo << "Loop: Connection to Unix socket file '"
6784 6785 6786
               << unixPath << "' failed with error '"
               << ESTR() << "'. Retrying.\n"
               << std::flush;
6787 6788 6789
      }
      else
      {
6790
        nxinfo << "Loop: Connection to '" << hostName
6791 6792 6793
               << ":" << portNum << "' failed with error '"
               << ESTR() << "'. Retrying.\n"
               << std::flush;
6794
      }
6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805
    }
    else
    {
      //
      // Connection was successful.
      //

      break;
    }
  }

6806 6807
  SAFE_FREE(unixPath);
  SAFE_FREE(hostName);
6808

6809
  return pFD;
6810 6811 6812

ConnectToRemoteError:

6813 6814
  SAFE_FREE(unixPath);
  SAFE_FREE(hostName);
6815

6816
  if (pFD != -1)
6817
  {
6818
    close(pFD);
6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839
  }

  HandleCleanup();
}

//
// Make a string of options for the remote
// proxy and write it to the descriptor.
// The string includes the local version.
//

int SendProxyOptions(int fd)
{
  char options[DEFAULT_REMOTE_OPTIONS_LENGTH];

  //
  // Send the "compatibility" version first, then our
  // actual version. Old proxies will take the first
  // value and ignore the second.
  //

6840 6841 6842 6843 6844
  sprintf(options, "NXPROXY-%s-%i.%i.%i",
              control -> NXPROXY_COMPATIBILITY_VERSION,
                  control -> LocalVersionMajor,
                      control -> LocalVersionMinor,
                          control -> LocalVersionPatch);
6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922

  //
  // If you want to send options from proxy
  // initiating the connection use something
  // like this:
  //
  // if (WE_PROVIDE_CREDENTIALS)
  // {
  //   sprintf(options + strlen(options), "%s=%s", option, value);
  // }
  //
  // If you want to send options according to
  // local proxy mode use something like this:
  //
  // if (control -> ProxyMode == proxy_client)
  // {
  //   sprintf(options + strlen(options), "%s=%s", option, value);
  // }
  //

  //
  // Send the authorization cookie if any. We assume
  // user can choose to not provide any auth cookie
  // and allow any connection to be accepted.
  //

  if (WE_PROVIDE_CREDENTIALS && *authCookie != '\0')
  {
    sprintf(options + strlen(options), " cookie=%s,", authCookie);
  }
  else
  {
    sprintf(options + strlen(options), " ");
  }

  //
  // Now link characteristics and compression
  // options. Delta compression, as well as
  // preferred pack method, are imposed by
  // client proxy.
  //

  if (control -> ProxyMode == proxy_client)
  {
    sprintf(options + strlen(options), "link=%s,pack=%s,cache=%s,",
                linkSpeedName, packMethodName, cacheSizeName);

    if (*bitrateLimitName != '\0')
    {
      sprintf(options + strlen(options), "limit=%s,",
                  bitrateLimitName);
    }

    //
    // Let the user disable the render extension
    // and let the X client proxy know if it can
    // short-circuit the X replies. Also pass
    // along the session type to ensure that the
    // remote proxy gets the right value.
    //

    sprintf(options + strlen(options), "render=%d,taint=%d,",
                (control -> HideRender == 0),
                    control -> TaintReplies);

    if (*sessionType != '\0')
    {
      sprintf(options + strlen(options), "type=%s,", sessionType);
    }
    else
    {
      sprintf(options + strlen(options), "type=default,");
    }

    //
    // Add the 'strict' option, if needed.
    //

6923 6924
    // Since ProtoStep7 (#issue 108)
    if (useStrict != -1)
6925 6926 6927 6928 6929 6930 6931 6932 6933
    {
      sprintf(options + strlen(options), "strict=%d,", useStrict);
    }

    //
    // Tell the remote the size of the shared
    // memory segment.
    //

6934 6935
    // Since ProtoStep7 (#issue 108)
    if (*shsegSizeName != '\0')
6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979
    {
      sprintf(options + strlen(options), "shseg=%s,", shsegSizeName);
    }

    //
    // Send image cache parameters.
    //

    sprintf(options + strlen(options), "images=%s,", imagesSizeName);

    sprintf(options + strlen(options), "delta=%d,stream=%d,data=%d ",
                control -> LocalDeltaCompression,
                    control -> LocalStreamCompressionLevel,
                        control -> LocalDataCompressionLevel);
  }
  else
  {
    //
    // If no special compression level was selected,
    // server side will use compression levels set
    // by client.
    //

    if (control -> LocalStreamCompressionLevel < 0)
    {
      sprintf(options + strlen(options), "stream=default,");
    }
    else
    {
      sprintf(options + strlen(options), "stream=%d,",
                  control -> LocalStreamCompressionLevel);
    }

    if (control -> LocalDataCompressionLevel < 0)
    {
      sprintf(options + strlen(options), "data=default ");
    }
    else
    {
      sprintf(options + strlen(options), "data=%d ",
                  control -> LocalDataCompressionLevel);
    }
  }

6980
  nxinfo << "Loop: Sending remote options '"
6981
         << options << "'.\n" << std::flush;
6982 6983 6984 6985 6986 6987

  return WriteLocalData(fd, options, strlen(options));
}

int ReadProxyVersion(int fd)
{
6988
  nxinfo << "Loop: Going to read the remote proxy version "
6989
         << "from FD#" << fd << ".\n" << std::flush;
6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014

  //
  // Read until the first space in string.
  // We expect the remote version number.
  //

  char options[DEFAULT_REMOTE_OPTIONS_LENGTH];

  int result = ReadRemoteData(fd, options, sizeof(options), ' ');

  if (result <= 0)
  {
    if (result < 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        HandleAlert(ABORT_PROXY_NEGOTIATION_ALERT, 1);
      }

      handleAlertInLoop();
    }

    return result;
  }

7015
  nxinfo << "Loop: Received remote version string '"
7016 7017
         << options << "' from FD#" << fd << ".\n"
         << std::flush;
7018 7019 7020

  if (strncmp(options, "NXPROXY-", strlen("NXPROXY-")) != 0)
  {
7021 7022
    nxfatal << "Loop: PANIC! Parse error in remote options string '"
            << options << "'.\n" << std::flush;
7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048

    cerr << "Error" << ": Parse error in remote options string '"
         << options << "'.\n";

    return -1;
  }

  //
  // Try to determine if this is a pre-2.0.0
  // version advertising itself as compatible
  // with the 1.2.2.
  //

  int major = -1;
  int minor = -1;
  int patch = -1;

  sscanf(options, "NXPROXY-%i.%i.%i-%i.%i.%i", &(control -> RemoteVersionMajor),
             &(control -> RemoteVersionMinor), &(control -> RemoteVersionPatch),
                 &major, &minor, &patch);

  if (control -> RemoteVersionMajor == 1 &&
          control -> RemoteVersionMinor == 2 &&
              control -> RemoteVersionPatch == 2 &&
                  major != -1 && minor != -1 && patch != -1)
  {
7049
    nxinfo << "Loop: Read trailing remote version '" << major
7050 7051
           << "." << minor << "." << patch << "'.\n"
           << std::flush;
7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103

    control -> CompatVersionMajor = major;
    control -> CompatVersionMinor = minor;
    control -> CompatVersionPatch = patch;

    control -> RemoteVersionMajor = major;
    control -> RemoteVersionMinor = minor;
    control -> RemoteVersionPatch = patch;
  }
  else
  {
    //
    // We read the remote version at the first
    // round. If the second version is missing,
    // we will retain the values read before.
    //

    sscanf(options, "NXPROXY-%i.%i.%i-%i.%i.%i", &(control -> CompatVersionMajor),
               &(control -> CompatVersionMinor), &(control -> CompatVersionPatch),
                   &(control -> RemoteVersionMajor), &(control -> RemoteVersionMinor),
                       &(control -> RemoteVersionPatch));
  }

  *logofs << "Loop: Identified remote version '" << control -> RemoteVersionMajor
          << "." << control -> RemoteVersionMinor << "." << control -> RemoteVersionPatch
          << "'.\n" << logofs_flush;

  *logofs << "Loop: Remote compatibility version '" << control -> CompatVersionMajor
          << "." << control -> CompatVersionMinor << "." << control -> CompatVersionPatch
          << "'.\n" << logofs_flush;

  *logofs << "Loop: Local version '" << control -> LocalVersionMajor
          << "." << control -> LocalVersionMinor << "." << control -> LocalVersionPatch
          << "'.\n" << logofs_flush;

  if (SetVersion() < 0)
  {
    if (control -> ProxyMode == proxy_server)
    {
      HandleAlert(WRONG_PROXY_VERSION_ALERT, 1);
    }

    handleAlertInLoop();

    return -1;
  }

  return 1;
}

int ReadProxyOptions(int fd)
{
7104
  nxinfo << "Loop: Going to read the remote proxy options "
7105
         << "from FD#" << fd << ".\n" << std::flush;
7106 7107 7108 7109 7110 7111 7112 7113 7114 7115

  char options[DEFAULT_REMOTE_OPTIONS_LENGTH];

  int result = ReadRemoteData(fd, options, sizeof(options), ' ');

  if (result <= 0)
  {
    return result;
  }

7116
  nxinfo << "Loop: Received remote options string '"
7117 7118
         << options << "' from FD#" << fd << ".\n"
         << std::flush;
7119 7120 7121 7122 7123 7124 7125 7126 7127

  //
  // Get the remote options, delimited by a space character.
  // Note that there will be a further initialization phase
  // at the time proxies negotiate cache file to restore.
  //

  if (ParseRemoteOptions(options) < 0)
  {
7128
    nxfatal << "Loop: PANIC! Couldn't negotiate a valid "
7129
            << "session with remote NX proxy.\n"
7130
            << std::flush;
7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142

    cerr << "Error" << ": Couldn't negotiate a valid "
         << "session with remote NX proxy.\n";

    return -1;
  }

  return 1;
}

int SendProxyCaches(int fd)
{
7143
  nxinfo << "Loop: Synchronizing local and remote caches.\n"
7144
         << std::flush;
7145 7146 7147 7148 7149 7150 7151 7152

  if (control -> ProxyMode == proxy_client)
  {
    //
    // Prepare a list of caches matching this
    // session type and send it to the remote.
    //

7153
    nxinfo << "Loop: Going to send the list of local caches.\n"
7154
           << std::flush;
7155 7156 7157 7158 7159 7160 7161 7162 7163 7164

    SetCaches();

    int entries = DEFAULT_REMOTE_CACHE_ENTRIES;

    const char prefix = 'C';

    if (control -> LocalDeltaCompression == 0 ||
            control -> PersistentCacheEnableLoad == 0)
    {
7165
      nxinfo << "Loop: Writing an empty list to FD#" << fd
7166
             << ".\n" << std::flush;
7167 7168 7169 7170 7171 7172

      return WriteLocalData(fd, "cachelist=none ", strlen("cachelist=none "));
    }

    int count = 0;

7173
    nxinfo << "Loop: Looking for cache files in directory '"
7174
           << control -> PersistentCachePath << "'.\n" << std::flush;
7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199

    DIR *cacheDir = opendir(control -> PersistentCachePath);

    if (cacheDir != NULL)
    {
      dirent *dirEntry;

      int prologue = 0;

      while (((dirEntry = readdir(cacheDir)) != NULL) && (count < entries))
      {
        if (*dirEntry -> d_name == prefix &&
                strlen(dirEntry -> d_name) == (MD5_LENGTH * 2 + 2))
        {
          if (prologue == 0)
          {
            WriteLocalData(fd, "cachelist=", strlen("cachelist="));

            prologue = 1;
          }
          else
          {
            WriteLocalData(fd, ",", strlen(","));
          }

7200
          nxinfo << "Loop: Writing entry '" << control -> PersistentCachePath
7201 7202
                 << "/" << dirEntry -> d_name << "' to FD#" << fd
                 << ".\n" << std::flush;
7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219

          //
          // Write cache file name to the socket,
          // including leading 'C-' or 'S-'.
          //

          WriteLocalData(fd, dirEntry -> d_name, MD5_LENGTH * 2 + 2);

          count++;
        }
      }

      closedir(cacheDir);
    }

    if (count == 0)
    {
7220
      nxinfo << "Loop: Writing an empty list to FD#" << fd
7221
             << ".\n" << std::flush;
7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235

      return WriteLocalData(fd, "cachelist=none ", strlen("cachelist=none "));
    }
    else
    {
      return WriteLocalData(fd, " ", 1);
    }
  }
  else
  {
    //
    // Send back the selected cache name.
    //

7236
    nxinfo << "Loop: Going to send the selected cache.\n"
7237
           << std::flush;
7238 7239 7240 7241 7242

    char buffer[DEFAULT_STRING_LENGTH];

    if (control -> PersistentCacheName != NULL)
    {
7243
      nxinfo << "Loop: Name of selected cache file is '"
7244 7245
             << control -> PersistentCacheName << "'.\n"
             << std::flush;
7246 7247 7248 7249 7250 7251 7252

      sprintf(buffer, "cachefile=%s%s ",
                  *(control -> PersistentCacheName) == 'C' ? "S-" : "C-",
                      control -> PersistentCacheName + 2);
    }
    else
    {
7253
      nxinfo << "Loop: No valid cache file was selected.\n"
7254
             << std::flush;
7255 7256 7257 7258

      sprintf(buffer, "cachefile=none ");
    }

7259
    nxinfo << "Loop: Sending string '" << buffer
7260 7261
           << "' as selected cache file.\n"
           << std::flush;
7262 7263 7264 7265 7266 7267 7268 7269 7270

    return WriteLocalData(fd, buffer, strlen(buffer));
  }
}

int ReadProxyCaches(int fd)
{
  if (control -> ProxyMode == proxy_client)
  {
7271
    nxinfo << "Loop: Going to receive the selected proxy cache.\n"
7272
           << std::flush;
7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294

    //
    // We will read the name of cache plus the stop character.
    //

    char buffer[DEFAULT_STRING_LENGTH];

    //
    // Leave space for a trailing null.
    //

    int result = ReadRemoteData(fd, buffer, sizeof("cachefile=") + MD5_LENGTH * 2 + 3, ' ');

    if (result <= 0)
    {
      return result;
    }

    char *cacheName = strstr(buffer, "cachefile=");

    if (cacheName == NULL)
    {
7295
      nxfatal << "Loop: PANIC! Invalid cache file option '"
7296
              << buffer << "' provided by remote proxy.\n"
7297
              << std::flush;
7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315

      cerr << "Error" << ": Invalid cache file option '"
           << buffer << "' provided by remote proxy.\n";

      HandleCleanup();
    }

    cacheName += strlen("cachefile=");

    if (control -> PersistentCacheName != NULL)
    {
      delete [] control -> PersistentCacheName;
    }

    control -> PersistentCacheName = NULL;

    if (strncasecmp(cacheName, "none", strlen("none")) == 0)
    {
7316
      nxinfo << "Loop: No cache file selected by remote proxy.\n"
7317
             << std::flush;
7318 7319 7320 7321
    }
    else if (strlen(cacheName) != MD5_LENGTH * 2 + 3 ||
                 *(cacheName + MD5_LENGTH * 2 + 2) != ' ')
    {
7322
      nxfatal << "Loop: PANIC! Invalid cache file name '"
7323
              << cacheName << "' provided by remote proxy.\n"
7324
              << std::flush;
7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342

      cerr << "Error" << ": Invalid cache file name '"
           << cacheName << "' provided by remote proxy.\n";

      HandleCleanup();
    }
    else
    {
      //
      // It is "C-" + 32 + "\0".
      //

      control -> PersistentCacheName = new char[MD5_LENGTH * 2 + 3];

      *(cacheName + MD5_LENGTH * 2 + 2) = '\0';

      strcpy(control -> PersistentCacheName, cacheName);

7343
      nxinfo << "Loop: Cache file '" << control -> PersistentCacheName
7344
             << "' selected by remote proxy.\n" << std::flush;
7345 7346 7347 7348
    }
  }
  else
  {
7349
    nxinfo << "Loop: Going to receive the list of remote caches.\n"
7350
           << std::flush;
7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367

    SetCaches();

    int size = ((MD5_LENGTH * 2 + 2) + strlen(",")) * DEFAULT_REMOTE_CACHE_ENTRIES +
                   strlen("cachelist=") + strlen(" ") + 1;

    char *buffer = new char[size];

    int result = ReadRemoteData(fd, buffer, size - 1, ' ');

    if (result <= 0)
    {
      delete [] buffer;

      return result;
    }

7368
    nxinfo << "Loop: Read list of caches from remote side as '"
7369
           << buffer << "'.\n" << std::flush;
7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380

    //
    // Prepare the buffer. What we want is a list
    // like "cache1,cache2,cache2" terminated by
    // null.
    //

    *(buffer + strlen(buffer) - 1) = '\0';

    if (strncasecmp(buffer, "cachelist=", strlen("cachelist=")) != 0)
    {
7381 7382
      nxfatal << "Loop: Wrong format for list of cache files "
              << "read from FD#" << fd << ".\n" << std::flush;
7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404

      cerr << "Error" << ": Wrong format for list of cache files.\n";

      delete [] buffer;

      return -1;
    }

    control -> PersistentCacheName = GetLastCache(buffer, control -> PersistentCachePath);

    //
    // Get rid of list of caches.
    //

    delete [] buffer;
  }

  return 1;
}

int ReadForwarderVersion(int fd)
{
7405
  nxinfo << "Loop: Going to negotiate the forwarder version.\n"
7406
         << std::flush;
7407 7408 7409 7410 7411 7412 7413

  //
  // Check if we actually expect the session cookie.
  //

  if (*authCookie == '\0')
  {
7414
    nxinfo << "Loop: No authentication cookie required "
7415
           << "from FD#" << fd << ".\n" << std::flush;
7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428

    return 1;
  }

  char options[DEFAULT_REMOTE_OPTIONS_LENGTH];

  int result = ReadRemoteData(fd, options, sizeof(options), ' ');

  if (result <= 0)
  {
    return result;
  }

7429
  nxinfo << "Loop: Received forwarder version string '" << options
7430
         << "' from FD#" << fd << ".\n" << std::flush;
7431 7432 7433

  if (strncmp(options, "NXSSH-", strlen("NXSSH-")) != 0)
  {
7434 7435
    nxfatal << "Loop: PANIC! Parse error in forwarder options string '"
            << options << "'.\n" << std::flush;
7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449

    cerr << "Error" << ": Parse error in forwarder options string '"
         << options << "'.\n";

    return -1;
  }

  //
  // Accept whatever forwarder version.
  //

  sscanf(options, "NXSSH-%i.%i.%i", &(control -> RemoteVersionMajor),
             &(control -> RemoteVersionMinor), &(control -> RemoteVersionPatch));

7450
  nxinfo << "Loop: Read forwarder version '" << control -> RemoteVersionMajor
7451 7452
         << "." << control -> RemoteVersionMinor << "." << control -> RemoteVersionPatch
         << "'.\n" << std::flush;
7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464

  return 1;
}

int ReadForwarderOptions(int fd)
{
  //
  // Get the forwarder cookie.
  //

  if (*authCookie == '\0')
  {
7465
    nxinfo << "Loop: No authentication cookie required "
7466
           << "from FD#" << fd << ".\n" << std::flush;
7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479

    return 1;
  }

  char options[DEFAULT_REMOTE_OPTIONS_LENGTH];

  int result = ReadRemoteData(fd, options, sizeof(options), ' ');

  if (result <= 0)
  {
    return result;
  }

7480
  nxinfo << "Loop: Received forwarder options string '"
7481 7482
         << options << "' from FD#" << fd << ".\n"
         << std::flush;
7483 7484 7485

  if (ParseForwarderOptions(options) < 0)
  {
7486
    nxfatal << "Loop: PANIC! Couldn't negotiate a valid "
7487
            << "cookie with the NX forwarder.\n"
7488
            << std::flush;
7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500

    cerr << "Error" << ": Couldn't negotiate a valid "
         << "cookie with the NX forwarder.\n";

    return -1;
  }

  return 1;
}

int ReadRemoteData(int fd, char *buffer, int size, char stop)
{
7501
  nxinfo << "Loop: Going to read remote data from FD#"
7502
         << fd << ".\n" << std::flush;
7503 7504 7505

  if (size >= MAXIMUM_REMOTE_OPTIONS_LENGTH)
  {
7506 7507
    nxfatal << "Loop: PANIC! Maximum remote options buffer "
            << "limit exceeded.\n" << std::flush;
7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526

    cerr << "Error" << ": Maximum remote options buffer "
         << "limit exceeded.\n";

    HandleCleanup();
  }

  while (remotePosition < (size - 1))
  {
    int result = read(fd, remoteData + remotePosition, 1);

    getNewTimestamp();

    if (result <= 0)
    {
      if (result == -1)
      {
        if (EGET() == EAGAIN)
        {
7527
          nxinfo << "Loop: Reading data from FD#" << fd
7528
                 << " would block.\n" << std::flush;
7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542

          return 0;
        }
        else if (EGET() == EINTR)
        {
          if (CheckAbort() != 0)
          {
            return -1;
          }

          continue;
        }
      }

7543 7544
      nxfatal << "Loop: PANIC! The remote NX proxy closed "
              << "the connection.\n" << std::flush;
7545 7546 7547 7548 7549 7550 7551 7552

      cerr << "Error" << ": The remote NX proxy closed "
           << "the connection.\n";

      return -1;
    }
    else if (*(remoteData + remotePosition) == stop)
    {
7553
      nxinfo << "Loop: Read stop character from FD#"
7554
             << fd << ".\n" << std::flush;
7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566

      remotePosition++;

      //
      // Copy the fake terminating null
      // in the buffer.
      //

      *(remoteData + remotePosition) = '\0';

      memcpy(buffer, remoteData, remotePosition + 1);

7567
      nxinfo << "Loop: Remote string '" << remoteData
7568 7569
             << "' read from FD#" << fd << ".\n"
             << std::flush;
7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585

      int t = remotePosition;

      remotePosition = 0;

      return t;
    }
    else
    {
      //
      // Make sure string received
      // from far end is printable.
      //

      if (isgraph(*(remoteData + remotePosition)) == 0)
      {
7586
        nxwarn << "Loop: WARNING! Non printable character decimal '"
7587 7588 7589
               << (unsigned int) *(remoteData + remotePosition)
               << "' received in remote data from FD#"
               << fd << ".\n" << std::flush;
7590 7591 7592 7593 7594 7595 7596 7597 7598

        cerr << "Warning" << ": Non printable character decimal '"
                << (unsigned int) *(remoteData + remotePosition)
                << "' received in remote data from FD#"
                << fd << ".\n" << logofs_flush;

        *(remoteData + remotePosition) = ' ';
      }

7599
      nxdbg << "Loop: Read a further character "
7600 7601
            << "from FD#" << fd << ".\n"
            << std::flush;
7602 7603 7604 7605 7606 7607 7608

      remotePosition++;
    }
  }

  *(remoteData + remotePosition) = '\0';

7609
  nxfatal << "Loop: PANIC! Stop character missing "
7610 7611
          << "from FD#" << fd << " after " << remotePosition 
          << " characters read in string '" << remoteData
7612
          << "'.\n" << std::flush;
7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625

  cerr << "Error" << ": Stop character missing "
       << "from FD#" << fd << " after " << remotePosition 
       << " characters read in string '" << remoteData
       << "'.\n";

  memcpy(buffer, remoteData, remotePosition);

  remotePosition = 0;

  return -1;
}

7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654
static int
hexval(char c) {
  if ((c >= '0') && (c <= '9'))
    return c - '0';
  if ((c >= 'a') && (c <= 'f'))
    return c - 'a' + 10;
  if ((c >= 'A') && (c <= 'F'))
    return c - 'A' + 10;
  return -1;
}

static void
URLDecodeInPlace(char *str) {
  if (str) {
    char *to = str;
    while (str[0]) {
      if ((str[0] == '%') &&
          (hexval(str[1]) >= 0) &&
          (hexval(str[2]) >= 0)) {
        *(to++) = hexval(str[1]) * 16 + hexval(str[2]);
        str += 3;
      }
      else
        *(to++) = *(str++);
    }
    *to = '\0';
  }
}

7655 7656 7657
int WriteLocalData(int fd, const char *buffer, int size)
{
  int position = 0;
7658 7659 7660
  int ret = 0;
  fd_set writeSet;
  struct timeval selectTs = {30, 0};
7661 7662 7663

  while (position < size)
  {
7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676

    // A write to a non-blocking socket may fail with EAGAIN. The problem is
    // that cache data is done in several writes, and there's no easy way
    // to handle failure without rewriting a significant amount of code.
    //
    // Bailing out of the outer loop would result in restarting the sending
    // of the entire cache list, which would confuse the other side.

    FD_ZERO(&writeSet);
    FD_SET(fd, &writeSet);

    ret = select(fd+1, NULL, &writeSet, NULL, &selectTs);

7677
    nxdbg << "Loop: WriteLocalData: select() returned with a code of " << ret << " and remaining timeout of "
7678
          << selectTs.tv_sec << " sec, " << selectTs.tv_usec << "usec\n" << std::flush;
7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694

    if ( ret < 0 )
    {
      *logofs << "Loop: Error in select() when writing data to FD#" << fd << ": " << strerror(EGET()) << "\n" << logofs_flush;

      if ( EGET() == EINTR )
        continue;

      return -1;
    }
    else if ( ret == 0 )
    {
      *logofs << "Loop: Timeout expired in select() when writing data to FD#" << fd << ": " << strerror(EGET()) << "\n" << logofs_flush;
      return -1;
    }

7695 7696 7697 7698 7699 7700
    int result = write(fd, buffer + position, size - position);

    getNewTimestamp();

    if (result <= 0)
    {
7701
      if (result < 0 && (EGET() == EINTR || EGET() == EAGAIN || EGET() == EWOULDBLOCK))
7702 7703 7704 7705
      {
        continue;
      }

7706
      nxinfo << "Loop: Error writing data to FD#"
7707
             << fd << ".\n" << std::flush;
7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749

      return -1;
    }

    position += result;
  }

  return position;
}

//
// Parse the string passed by calling process in
// the environment. This is not necessarily the
// content of DISPLAY variable, but can be the
// parameters passed when creating the process
// or thread.
//

int ParseEnvironmentOptions(const char *env, int force)
{
  //
  // Be sure log file is valid.
  //

  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  //
  // Be sure we have a parameters repository
  // and a context to jump into because this
  // can be called before creating the proxy.
  //

  if (control == NULL)
  {
    control = new Control();
  }

  if (setjmp(context) == 1)
  {
7750
    nxinfo << "Loop: Out of the long jump while parsing "
7751 7752
           << "the environment options.\n"
           << std::flush;
7753

7754 7755 7756 7757 7758
    return -1;
  }

  if (force == 0 && parsedOptions == 1)
  {
7759
    nxinfo << "Loop: Skipping a further parse of environment "
7760 7761
           << "options string '" << (env != NULL ? env : "")
           << "'.\n" << std::flush;
7762 7763 7764 7765 7766 7767

    return 1;
  }

  if (env == NULL || *env == '\0')
  {
7768
    nxinfo << "Loop: Nothing to do with empty environment "
7769 7770
           << "options string '" << (env != NULL ? env : "")
           << "'.\n" << std::flush;
7771 7772 7773 7774

    return 0;
  }

7775
  nxinfo << "Loop: Going to parse the environment options "
7776 7777
         << "string '" << env << "'.\n"
         << std::flush;
7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795

  parsedOptions = 1;

  //
  // Copy the string passed as parameter
  // because we need to modify it.
  //

  char opts[DEFAULT_DISPLAY_OPTIONS_LENGTH];

  #ifdef VALGRIND

  memset(opts, '\0', DEFAULT_DISPLAY_OPTIONS_LENGTH);

  #endif

  if (strlen(env) >= DEFAULT_DISPLAY_OPTIONS_LENGTH)
  {
7796
    nxfatal << "Loop: PANIC! Environment options string '" << env
7797
            << "' exceeds length of " << DEFAULT_DISPLAY_OPTIONS_LENGTH
7798
            << " characters.\n" << std::flush;
7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819

    cerr << "Error" << ": Environment options string '" << env
         << "' exceeds length of " << DEFAULT_DISPLAY_OPTIONS_LENGTH
         << " characters.\n";

    return -1;
  }

  strcpy(opts, env);

  char *nextOpts = opts;

  //
  // Ensure that DISPLAY environment variable
  // (roughly) follows the X convention for
  // transport notation.
  //

  if (strncasecmp(opts, "nx/nx,:", 7) == 0 ||
          strncasecmp(opts, "nx,:", 4) == 0)
  {
7820 7821
    nxfatal << "Loop: PANIC! Parse error in options string '"
            << opts << "' at 'nx,:'.\n" << std::flush;
7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841

    cerr << "Error" << ": Parse error in options string '"
         << opts << "' at 'nx,:'.\n";

    return -1;
  }
  else if (strncasecmp(opts, "nx/nx,", 6) == 0)
  {
    nextOpts += 6;
  }
  else if (strncasecmp(opts, "nx,", 3) == 0)
  {
    nextOpts += 3;
  }
  else if (strncasecmp(opts, "nx:", 3) == 0)
  {
    nextOpts += 3;
  }
  else if (force == 0)
  {
7842
    nxinfo << "Loop: Ignoring host X server display string '"
7843
           << opts << "'.\n" << std::flush;
7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864

    return 0;
  }

  //
  // Save here the name of the options file and
  // parse it after all the other options.
  //

  char fileOptions[DEFAULT_STRING_LENGTH] = { 0 };

  //
  // The options string is intended to be a series
  // of name/value tuples in the form name=value
  // separated by the ',' character ended by a ':'
  // followed by remote NX proxy port.
  //

  char *name;
  char *value;

7865
  value = strrchr(nextOpts, ':');
7866

7867
  if (value != NULL)
7868 7869 7870 7871 7872
  {
    char *check = value + 1;

    if (*check == '\0' || isdigit(*check) == 0)
    {
7873 7874
      nxfatal << "Loop: PANIC! Can't identify NX port in string '"
              << value << "'.\n" << std::flush;
7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896

      cerr << "Error" << ": Can't identify NX port in string '"
           << value << "'.\n";

      return -1;
    }

    proxyPort = atoi(check);

    //
    // Get rid of the port specification.
    //

    *value = '\0';
  }
  else if (proxyPort == DEFAULT_NX_PROXY_PORT && force == 0)
  {
    //
    // Complain only if user didn't specify
    // the port on the command line.
    //

7897 7898
    nxfatal << "Loop: PANIC! Can't identify NX port in string '"
            << opts << "'.\n" << std::flush;
7899 7900 7901 7902 7903 7904 7905

    cerr << "Error" << ": Can't identify NX port in string '"
         << opts << "'.\n";

    return -1;
  }

7906
  nxinfo << "Loop: Parsing options string '"
7907
         << nextOpts << "'.\n" << std::flush;
7908 7909 7910 7911 7912 7913 7914

  //
  // Now all the other optional parameters.
  //

  name = strtok(nextOpts, "=");

7915 7916 7917
  char connectHost[DEFAULT_STRING_LENGTH] = { 0 };
  long connectPort = -1;

7918 7919 7920
  while (name)
  {
    value = strtok(NULL, ",");
7921
    URLDecodeInPlace(value);
7922 7923 7924 7925 7926 7927 7928 7929

    if (CheckArg("environment", name, value) < 0)
    {
      return -1;
    }

    if (strcasecmp(name, "options") == 0)
    {
7930
      snprintf(fileOptions, DEFAULT_STRING_LENGTH, "%s", value);
7931 7932 7933
    }
    else if (strcasecmp(name, "display") == 0)
    {
7934
      snprintf(displayHost, DEFAULT_STRING_LENGTH, "%s", value);
7935 7936 7937
    }
    else if (strcasecmp(name, "link") == 0)
    {
7938

7939 7940 7941 7942 7943 7944
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else if (ParseLinkOption(value) < 0)
      {
7945 7946
        nxfatal << "Loop: PANIC! Can't identify 'link' option in string '"
                << value << "'.\n" << std::flush;
7947 7948 7949

        cerr << "Error" << ": Can't identify 'link' option in string '"
             << value << "'.\n";
7950 7951
        if (ParseLinkOption("adsl") < 0)
           return -1;
7952 7953 7954 7955 7956 7957 7958 7959 7960 7961
      }
    }
    else if (strcasecmp(name, "limit") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else if (ParseBitrateOption(value) < 0)
      {
7962 7963
        nxfatal << "Loop: PANIC! Can't identify option 'limit' in string '"
                << value << "'.\n" << std::flush;
7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989

        cerr << "Error" << ": Can't identify option 'limit' in string '"
             << value << "'.\n";

        return -1;
      }
    }
    else if (strcasecmp(name, "type") == 0)
    {
      //
      // Type of session, for example "desktop",
      // "application", "windows", etc.
      //

      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        if (strcasecmp(value, "default") == 0)
        {
          *sessionType = '\0';
        }
        else
        {
7990
          snprintf(sessionType, DEFAULT_STRING_LENGTH, "%s", value);
7991 7992 7993 7994 7995
        }
      }
    }
    else if (strcasecmp(name, "listen") == 0)
    {
7996 7997
      char *socketUri = NULL;
      if (connectSocket.getSpec(&socketUri))
7998
      {
7999 8000
        nxfatal << "Loop: PANIC! Can't handle 'listen' and 'connect' parameters "
                << "at the same time.\n" << std::flush;
8001

8002 8003
        nxfatal << "Loop: PANIC! Refusing 'listen' parameter with 'connect' being '"
                << socketUri << "'.\n" << std::flush;
8004 8005 8006 8007 8008

        cerr << "Error" << ": Can't handle 'listen' and 'connect' parameters "
             << "at the same time.\n";

        cerr << "Error" << ": Refusing 'listen' parameter with 'connect' being '"
8009
             << socketUri << "'.\n";
8010

8011
        SAFE_FREE(socketUri);
8012 8013 8014
        return -1;
      }

8015 8016
      SetAndValidateChannelEndPointArg("local", name, value, listenSocket);

8017
    }
8018 8019 8020 8021
    else if (strcasecmp(name, "loopback") == 0)
    {
      loopbackBind = ValidateArg("local", name, value);
    }
8022 8023
    else if (strcasecmp(name, "accept") == 0)
    {
8024 8025
      char *socketUri = NULL;
      if (connectSocket.getSpec(&socketUri))
8026
      {
8027 8028
        nxfatal << "Loop: PANIC! Can't handle 'accept' and 'connect' parameters "
                << "at the same time.\n" << std::flush;
8029

8030 8031
        nxfatal << "Loop: PANIC! Refusing 'accept' parameter with 'connect' being '"
                << socketUri << "'.\n" << std::flush;
8032 8033 8034 8035 8036

        cerr << "Error" << ": Can't handle 'accept' and 'connect' parameters "
             << "at the same time.\n";

        cerr << "Error" << ": Refusing 'accept' parameter with 'connect' being '"
8037
             << socketUri << "'.\n";
8038

8039
        SAFE_FREE(socketUri);
8040 8041 8042
        return -1;
      }

8043
      snprintf(acceptHost, DEFAULT_STRING_LENGTH, "%s", value);
8044 8045 8046 8047 8048
    }
    else if (strcasecmp(name, "connect") == 0)
    {
      if (*acceptHost != '\0')
      {
8049 8050
        nxfatal << "Loop: PANIC! Can't handle 'connect' and 'accept' parameters "
                << "at the same time.\n" << std::flush;
8051

8052 8053
        nxfatal << "Loop: PANIC! Refusing 'connect' parameter with 'accept' being '"
                << acceptHost << "'.\n" << std::flush;
8054 8055 8056 8057 8058 8059 8060 8061 8062

        cerr << "Error" << ": Can't handle 'connect' and 'accept' parameters "
             << "at the same time.\n";

        cerr << "Error" << ": Refusing 'connect' parameter with 'accept' being '"
             << acceptHost << "'.\n";

        return -1;
      }
8063 8064 8065 8066 8067 8068
      if ((strncmp(value, "tcp:", 4) == 0) || (strncmp(value, "unix:", 5) == 0))
        SetAndValidateChannelEndPointArg("local", name, value, connectSocket);
      else
        // if the "connect" parameter does not start with "unix:" or "tcp:" assume
        // old parameter usage style (providing hostname string only).
        strcpy(connectHost, value);
8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080
    }
    else if (strcasecmp(name, "port") == 0)
    {
      connectPort = ValidateArg("local", name, value);
    }
    else if (strcasecmp(name, "retry") == 0)
    {
      control -> OptionProxyRetryConnect  = ValidateArg("local", name, value);
      control -> OptionServerRetryConnect = ValidateArg("local", name, value);
    }
    else if (strcasecmp(name, "session") == 0)
    {
8081
      snprintf(sessionFileName, DEFAULT_STRING_LENGTH, "%s", value);
8082 8083 8084 8085 8086 8087 8088 8089 8090 8091
    }
    else if (strcasecmp(name, "errors") == 0)
    {
      //
      // The old name of the parameter was 'log'
      // but the default name for the file is
      // 'errors' so it is more logical to use
      // the same name.
      //

8092
      snprintf(errorsFileName, DEFAULT_STRING_LENGTH, "%s", value);
8093 8094 8095
    }
    else if (strcasecmp(name, "root") == 0)
    {
8096
      snprintf(rootDir, DEFAULT_STRING_LENGTH, "%s", value);
8097 8098 8099
    }
    else if (strcasecmp(name, "id") == 0)
    {
8100
      snprintf(sessionId, DEFAULT_STRING_LENGTH, "%s", value);
8101 8102 8103 8104 8105
    }
    else if (strcasecmp(name, "stats") == 0)
    {
      control -> EnableStatistics = 1;

8106
      snprintf(statsFileName, DEFAULT_STRING_LENGTH, "%s", value);
8107 8108 8109 8110 8111
    }
    else if (strcasecmp(name, "cookie") == 0)
    {
      LowercaseArg("local", name, value);

8112
      snprintf(authCookie, DEFAULT_STRING_LENGTH, "%s", value);
8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199
    }
    else if (strcasecmp(name, "nodelay") == 0)
    {
      useNoDelay = ValidateArg("local", name, value);
    }
    else if (strcasecmp(name, "policy") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        usePolicy = ValidateArg("local", name, value);
      }
    }
    else if (strcasecmp(name, "render") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        useRender = ValidateArg("local", name, value);
      }
    }
    else if (strcasecmp(name, "taint") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        useTaint = ValidateArg("local", name, value);
      }
    }
    else if (strcasecmp(name, "delta") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        control -> LocalDeltaCompression = ValidateArg("local", name, value);
      }
    }
    else if (strcasecmp(name, "data") == 0)
    {
      control -> LocalDataCompressionLevel = ValidateArg("local", name, value);

      if (control -> LocalDataCompressionLevel == 0)
      {
        control -> LocalDataCompression = 0;
      }
      else
      {
        control -> LocalDataCompression = 1;
      }
    }
    else if (strcasecmp(name, "stream") == 0)
    {
      control -> LocalStreamCompressionLevel = ValidateArg("local", name, value);

      if (control -> LocalStreamCompressionLevel == 0)
      {
        control -> LocalStreamCompression = 0;
      }
      else
      {
        control -> LocalStreamCompression = 1;
      }
    }
    else if (strcasecmp(name, "memory") == 0)
    {
      control -> LocalMemoryLevel = ValidateArg("local", name, value);
    }
    else if (strcasecmp(name, "cache") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else if (ParseCacheOption(value) < 0)
      {
8200 8201
        nxfatal << "Loop: PANIC! Can't identify cache size for string '"
                << value << "'.\n" << std::flush;
8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216

        cerr << "Error" << ": Can't identify cache size for string '"
             << value << "'.\n";

        return -1;
      }
    }
    else if (strcasecmp(name, "images") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else if (ParseImagesOption(value) < 0)
      {
8217 8218
        nxfatal << "Loop: PANIC! Can't identify images cache size for string '"
                << value << "'.\n" << std::flush;
8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242

        cerr << "Error" << ": Can't identify images cache size for string '"
             << value << "'.\n";

        return -1;
      }
    }
    else if (strcasecmp(name, "shseg") == 0)
    {
      //
      // The 'shmem' option is used by the agent, together
      // with 'shpix' literal. We make the 'shseg' option
      // specific to the proxy and use it to determine the
      // size of the shared memory segment, or otherwise 0,
      // if the use of the shared memory extension should
      // not be enabled on the real X server.
      //
 
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else if (ParseShmemOption(value) < 0)
      {
8243
        nxfatal << "Loop: PANIC! Can't identify size of shared memory "
8244
                << "segment in string '" << value << "'.\n"
8245
                << std::flush;
8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308

        cerr << "Error" << ": Can't identify size of shared memory "
             << "segment in string '" << value << "'.\n";

        return -1;
      }
    }
    else if (strcasecmp(name, "load") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        control -> PersistentCacheEnableLoad = ValidateArg("local", name, value);

        if (control -> PersistentCacheEnableLoad > 0)
        {
          control -> PersistentCacheEnableLoad = 1;
        }
        else
        {
          if (control -> PersistentCacheName != NULL)
          {
            delete [] control -> PersistentCacheName;
          }

          control -> PersistentCacheName = NULL;

          control -> PersistentCacheEnableLoad = 0;
        }
      }
    }
    else if (strcasecmp(name, "save") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        control -> PersistentCacheEnableSave = ValidateArg("local", name, value);

        if (control -> PersistentCacheEnableSave > 0)
        {
          control -> PersistentCacheEnableSave = 1;
        }
        else
        {
          if (control -> PersistentCacheName != NULL)
          {
            delete [] control -> PersistentCacheName;
          }

          control -> PersistentCacheName = NULL;

          control -> PersistentCacheEnableSave = 0;
        }
      }
    }
    else if (strcasecmp(name, "cups") == 0)
    {
8309
      SetAndValidateChannelEndPointArg("local", name, value, cupsPort);
8310 8311 8312
    }
    else if (strcasecmp(name, "sync") == 0)
    {
8313
      nxwarn << "Loop: WARNING! No 'sync' channel in current version. "
8314
             << "Assuming 'cups' channel.\n" << std::flush;
8315 8316 8317 8318

      cerr << "Warning" << ": No 'sync' channel in current version. "
           << "Assuming 'cups' channel.\n";

8319
      SetAndValidateChannelEndPointArg("local", name, value, cupsPort);
8320 8321 8322 8323
    }
    else if (strcasecmp(name, "keybd") == 0 ||
                 strcasecmp(name, "aux") == 0)
    {
8324
      SetAndValidateChannelEndPointArg("local", name, value, auxPort);
8325 8326 8327 8328
    }
    else if (strcasecmp(name, "samba") == 0 ||
                 strcasecmp(name, "smb") == 0)
    {
8329
      SetAndValidateChannelEndPointArg("local", name, value, smbPort);
8330 8331 8332
    }
    else if (strcasecmp(name, "media") == 0)
    {
8333
      SetAndValidateChannelEndPointArg("local", name, value, mediaPort);
8334 8335 8336
    }
    else if (strcasecmp(name, "http") == 0)
    {
8337
      SetAndValidateChannelEndPointArg("local", name, value, httpPort);
8338 8339 8340
    }
    else if (strcasecmp(name, "font") == 0)
    {
8341
      snprintf(fontPort, DEFAULT_STRING_LENGTH, "%s", value);
8342 8343 8344
    }
    else if (strcasecmp(name, "slave") == 0)
    {
8345
      SetAndValidateChannelEndPointArg("local", name, value, slavePort);
8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356
    }
    else if (strcasecmp(name, "mask") == 0)
    {
      control -> ChannelMask = ValidateArg("local", name, value);
    }
    else if (strcasecmp(name, "timeout") == 0)
    {
      int timeout = ValidateArg("local", name, value);

      if (timeout == 0)
      {
8357
        nxinfo << "Loop: Disabling timeout on broken "
8358
               << "proxy connection.\n" << std::flush;
8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372

        control -> ProxyTimeout = 0;
      }
      else
      {
        control -> ProxyTimeout = timeout * 1000;
      }
    }
    else if (strcasecmp(name, "cleanup") == 0)
    {
      int cleanup = ValidateArg("local", name, value);

      if (cleanup == 0)
      {
8373
        nxinfo << "Loop: Disabling grace timeout on "
8374
               << "proxy shutdown.\n" << std::flush;
8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390

        control -> CleanupTimeout = 0;
      }
      else
      {
        control -> CleanupTimeout = cleanup * 1000;
      }
    }
    else if (strcasecmp(name, "pack") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else if (ParsePackOption(value) < 0)
      {
8391 8392
        nxfatal << "Loop: PANIC! Can't identify pack method for string '"
                << value << "'.\n" << std::flush;
8393 8394 8395

        cerr << "Error" << ": Can't identify pack method for string '"
             << value << "'.\n";
8396 8397
        if (ParsePackOption("nopack")<0)
           return -1;
8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408
      }
    }
    else if (strcasecmp(name, "core") == 0)
    {
      control -> EnableCoreDumpOnAbort = ValidateArg("local", name, value);
    }
    else if (strcasecmp(name, "kill") == 0)
    {
      if (control -> KillDaemonOnShutdownNumber <
              control -> KillDaemonOnShutdownLimit)
      {
8409
        nxinfo << "Loop: WARNING! Adding process with pid '"
8410 8411 8412
               << ValidateArg("local", name, value) << " to the "
               << "daemons to kill at shutdown.\n"
               << std::flush;
8413 8414 8415 8416 8417 8418 8419 8420 8421

        control -> KillDaemonOnShutdown[control ->
                       KillDaemonOnShutdownNumber] =
                           ValidateArg("local", name, value);

        control -> KillDaemonOnShutdownNumber++;
      }
      else
      {
8422
        nxwarn << "Loop: WARNING! Number of daemons to kill "
8423
               << "at shutdown exceeded.\n" << std::flush;
8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445

        cerr << "Warning" << ": Number of daemons to kill "
             << "at shutdown exceeded.\n";
      }
    }
    else if (strcasecmp(name, "strict") == 0)
    {
      if (control -> ProxyMode == proxy_server)
      {
        PrintOptionIgnored("local", name, value);
      }
      else
      {
        useStrict = ValidateArg("local", name, value);
      }
    }
    else if (strcasecmp(name, "encryption") == 0)
    {
      useEncryption = ValidateArg("local", name, value);
    }
    else if (strcasecmp(name, "product") == 0)
    {
8446
      snprintf(productName, DEFAULT_STRING_LENGTH, "%s", value);
8447 8448 8449 8450 8451 8452 8453 8454
    }
    else if (strcasecmp(name, "rootless") == 0 ||
                 strcasecmp(name, "geometry") == 0 ||
                     strcasecmp(name, "resize") == 0 ||
                         strcasecmp(name, "fullscreen") == 0 ||
                             strcasecmp(name, "keyboard") == 0 ||
                                 strcasecmp(name, "clipboard") == 0 ||
                                     strcasecmp(name, "streaming") == 0 ||
8455
                                         strcasecmp(name, "backingstore") == 0 ||
8456
                                             strcasecmp(name, "sleep") == 0 ||
8457 8458
                                                 strcasecmp(name, "keyconv") == 0 ||
                                                     strcasecmp(name, "tolerancechecks") == 0)
8459
    {
8460
      nxdbg << "Loop: Ignoring agent option '" << name
8461 8462
            << "' with value '" << value << "'.\n"
            << std::flush;
8463 8464 8465 8466 8467 8468 8469 8470 8471
    }
    else if (strcasecmp(name, "composite") == 0 ||
                 strcasecmp(name, "shmem") == 0 ||
                     strcasecmp(name, "shpix") == 0 ||
                         strcasecmp(name, "kbtype") == 0 ||
                             strcasecmp(name, "client") == 0 ||
                                 strcasecmp(name, "shadow") == 0 ||
                                     strcasecmp(name, "shadowuid") == 0 ||
                                         strcasecmp(name, "shadowmode") == 0 ||
8472 8473
                                             strcasecmp(name, "clients") == 0 ||
                                                 strcasecmp(name, "xinerama") == 0)
8474
    {
8475
      nxdbg << "Loop: Ignoring agent option '" << name
8476 8477
            << "' with value '" << value << "'.\n"
            << std::flush;
8478 8479 8480
    }
    else if (strcasecmp(name, "defer") == 0 ||
                 strcasecmp(name, "tile") == 0 ||
8481
                     strcasecmp(name, "menu") == 0 ||
8482
                        strcasecmp(name, "magicpixel") == 0 ||
8483 8484
                          strcasecmp(name, "autodpi") == 0 ||
                            strcasecmp(name, "state") == 0 )
8485
    {
8486
      nxdbg << "Loop: Ignoring agent option '" << name
8487 8488
            << "' with value '" << value << "'.\n"
            << std::flush;
8489 8490 8491
    }
    else
    {
8492
      nxwarn << "Loop: WARNING! Ignoring unknown option '"
8493 8494
             << name << "' with value '" << value << "'.\n"
             << std::flush;
8495 8496 8497 8498 8499 8500 8501 8502 8503

      cerr << "Warning" << ": Ignoring unknown option '"
           << name << "' with value '" << value << "'.\n";
    }

    name = strtok(NULL, "=");

  } // End of while (name) ...

8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514
  // Assemble the connectSocket channel end point if parameter values have been old-school...
  if (connectSocket.disabled() && (connectHost[0] != '\0') && (proxyPort > 0 || connectPort > 0))
  {
    if (connectPort < 0)
      connectPort = proxyPort + DEFAULT_NX_PROXY_PORT_OFFSET;

    char tcpHostAndPort[DEFAULT_STRING_LENGTH] = { 0 };
    sprintf(tcpHostAndPort, "tcp:%s:%ld", connectHost, connectPort);
    SetAndValidateChannelEndPointArg("local", name, tcpHostAndPort, connectSocket);
  }

8515
  nxinfo << "Loop: Completed parsing of string '"
8516
         << env << "'.\n" << std::flush;
8517

8518
  if ((*fileOptions != '\0') && (strncmp(fileOptions, "/dev/", 5) != 0) && (strncmp(fileOptions, "/proc/", 6) != 0) && (strncmp(fileOptions, "/sys/", 5) != 0))
8519 8520 8521
  {
    if (strcmp(fileOptions, optionsFileName) != 0)
    {
8522
      nxinfo << "Loop: Reading options from '" << fileOptions
8523
             << "'.\n" << std::flush;
8524 8525 8526 8527 8528 8529 8530 8531

      if (ParseFileOptions(fileOptions) < 0)
      {
        return -1;
      }
    }
    else
    {
8532
      nxwarn << "Loop: WARNING! Name of the options file "
8533 8534
             << "specified multiple times. Not parsing "
             << "again.\n" << std::flush;
8535 8536 8537 8538
    }

    if (*optionsFileName == '\0')
    {
8539
      snprintf(optionsFileName, DEFAULT_STRING_LENGTH, "%s", value);
8540

8541
      nxinfo << "Loop: Assuming name of options file '"
8542 8543
             << optionsFileName << "'.\n"
             << std::flush;
8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582
    }
  }

  //
  // If port where proxy is acting as an X server
  // was not specified assume the same port where
  // proxy is listening for the remote peer.
  //

  if (xPort == DEFAULT_NX_X_PORT)
  {
    xPort = proxyPort;
  }

  return 1;
}

//
// Parse the command line options passed by user when
// running proxy in stand alone mode. Note that passing
// parameters this way is strongly discouraged. These
// command line switch can change (and they do often).
// Please, use the form "option=value" instead and set
// the DISPLAY environment variable.
//

int ParseCommandLineOptions(int argc, const char **argv)
{
  //
  // Be sure log file is valid.
  //

  if (logofs == NULL)
  {
    logofs = &cerr;
  }

  if (setjmp(context) == 1)
  {
8583
    nxinfo << "Loop: Out of the long jump while parsing "
8584 8585
           << "the command line options.\n"
           << std::flush;
8586

8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600
    return -1;
  }

  //
  // Be sure we have a parameters repository
  //

  if (control == NULL)
  {
    control = new Control();
  }

  if (parsedCommand == 1)
  {
8601
    nxinfo << "Loop: Skipping a further parse of command line options.\n"
8602
           << std::flush;
8603 8604 8605 8606

    return 1;
  }

8607
  nxinfo << "Loop: Going to parse the command line options.\n"
8608
         << std::flush;
8609 8610 8611 8612 8613 8614 8615 8616

  parsedCommand = 1;

  //
  // Print out arguments.
  //


8617
  nxinfo << "Loop: Argc is " << argc << ".\n" << std::flush;
8618 8619

  for (int argi = 0; argi < argc; argi++)
8620
  {
8621 8622
    nxinfo << "Loop: Argv[" << argi << "] is " << argv[argi]
           << ".\n" << std::flush;
8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651
  }


  //
  // Shall use getopt here.
  //

  for (int argi = 1; argi < argc; argi++)
  {
    const char *nextArg = argv[argi];

    if (*nextArg == '-')
    {
      switch (*(nextArg + 1))
      {
        case 'h':
        {
          PrintUsageInfo(nextArg, 0);

          return -1;
        }
        case 'C':
        {
          //
          // Start proxy in CLIENT mode.
          //

          if (WE_SET_PROXY_MODE == 0)
          {
8652
            nxinfo << "Loop: Setting local proxy mode to proxy_client.\n"
8653
                   << std::flush;
8654 8655 8656 8657 8658

            control -> ProxyMode = proxy_client;
          }
          else if (control -> ProxyMode != proxy_client)
          {
8659 8660
            nxfatal << "Loop: PANIC! Can't redefine local proxy to "
                    << "client mode.\n" << std::flush;
8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677

            cerr << "Error" << ": Can't redefine local proxy to "
                 << "client mode.\n";

            return -1;
          }

          break;
        }
        case 'S':
        {
          //
          // Start proxy in SERVER mode.
          //

          if (WE_SET_PROXY_MODE == 0)
          {
8678
            nxinfo << "Loop: Setting local proxy mode to proxy_server.\n"
8679
                   << std::flush;
8680 8681 8682 8683 8684

            control -> ProxyMode = proxy_server;
          }
          else if (control -> ProxyMode != proxy_server)
          {
8685 8686
            nxfatal << "Loop: PANIC! Can't redefine local proxy to "
                    << "server mode.\n" << std::flush;
8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701

            cerr << "Error" << ": Can't redefine local proxy to "
                 << "server mode.\n";

            return -1;
          }

          break;
        }
        case 'v':
        {
          PrintVersionInfo();

          return -1;
        }
8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797
        case 'd':
        {
          if ( argi+1 >= argc )
          {
            PrintUsageInfo(nextArg, 0);
            return -1;
          }

          int level = 0;
          errno = 0;
          level = strtol(argv[argi+1], NULL, 10);

          if ( errno && (level == 0) )
          {
            cerr << "Warning: Failed to parse log level. Ignoring option." << std::endl;
          }
          if ( level < 0 )
          {
            cerr << "Warning: Log level must be a positive integer. Ignoring option." << std::endl;
            level = nx_log.level();
          }
          else if ( level >= NXLOG_LEVEL_COUNT )
          {
            cerr << "Warning: Log level is greater than the maximum " << NXLOG_LEVEL_COUNT-1 << ". Setting to the maximum." << std::endl;
            level = NXLOG_LEVEL_COUNT-1;
          }

          nx_log.level( (NXLogLevel)level );

          argi++;
          break;

        }
        case 'o':
        {
          if ( argi + 1 >= argc )
          {
            PrintUsageInfo(nextArg, 0);
            return -1;
          }

          std::ofstream *logfile = new std::ofstream();

          // Unbuffered output
          logfile->rdbuf()->pubsetbuf(0, 0);
          logfile->open(argv[argi+1], std::ofstream::app);

          if ( logfile->is_open() )
          {
            nx_log.stream(logfile);
          }
          else
          {
            cerr << "Failed to open log file " << argv[argi+1] << endl;
            return -1;
          }

          argi++;
          break;
        }
        case 'f':
        {
          if ( argi + 1 >= argc )
          {
            PrintUsageInfo(nextArg, 0);
            return -1;
          }

          const char *format = argv[argi+1];
          size_t pos = 0;

          nx_log.log_level(false);
          nx_log.log_time(false);
          nx_log.log_unix_time(false);
          nx_log.log_location(false);
          nx_log.log_thread_id(false);

          for(pos =0;pos<strlen(format);pos++)
          {
            switch(format[pos])
            {
              case '0': break;
              case 't': nx_log.log_time(true); break;
              case 'u': nx_log.log_time(true); nx_log.log_unix_time(true); break;
              case 'l': nx_log.log_level(true); break;
              case 'T': nx_log.log_thread_id(true); break;
              case 'L': nx_log.log_location(true); break;
              default : cerr << "Unrecognized format specifier: " << format[pos] << endl; break;
            }
          }

          argi++;
          break;
        }


8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826
        default:
        {
          PrintUsageInfo(nextArg, 1);

          //
          // Function GetArg() is not used anymore.
          // Add a dummy call to avoid the warning.
          //

          if (0)
          {
            GetArg(argi, argc, argv);
          }

          return -1;
        }
      }
    }
    else
    {
      if (nextArg)
      {
        //
        // Try to parse the option as a remote host:port
        // specification as in 'localhost:8'. Such a
        // parameter can be specified at the end of the
        // command line at the connecting side.
        //

8827 8828
        char cHost[DEFAULT_STRING_LENGTH] = { '\0' };
        long cPort = 0;
8829

8830
        if (ParseHostOption(nextArg, cHost, cPort) > 0)
8831 8832 8833 8834
          {
            //
            // Assume port is at a proxied display offset.
            //
8835

8836 8837 8838 8839 8840 8841
            proxyPort = cPort;

            cPort += DEFAULT_NX_PROXY_PORT_OFFSET;
            connectSocket.setSpec(cHost, cPort);

          }
8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909
        else if (ParseEnvironmentOptions(nextArg, 1) < 0)
        {
          return -1;
        }
      }
    }
  }

  return 1;
}

//
// Set the variable to the values of host and
// port where this proxy is going to hook to
// an existing proxy.
//

int ParseBindOptions(char **host, int *port)
{
  if (*bindHost != '\0')
  {
    *host = bindHost;
    *port = bindPort;

    return 1;
  }
  else
  {
    return 0;
  }
}

//
// Read options from file and merge with environment.
//

int ParseFileOptions(const char *file)
{
  char *fileName;

  if (*file != '/' && *file != '.')
  {
    char *filePath = GetSessionPath();

    if (filePath == NULL)
    {
      cerr << "Error" << ": Cannot determine directory for NX option file.\n";

      HandleCleanup();
    }

    fileName = new char[strlen(filePath) + strlen("/") +
                            strlen(file) + 1];

    strcpy(fileName, filePath);

    strcat(fileName, "/");
    strcat(fileName, file);

    delete [] filePath;
  }
  else
  {
    fileName = new char[strlen(file) + 1];

    strcpy(fileName, file);
  }

8910
  nxinfo << "Loop: Going to read options from file '"
8911
         << fileName << "'.\n" << std::flush;
8912 8913 8914 8915 8916

  FILE *filePtr = fopen(fileName, "r");

  if (filePtr == NULL)
  {
8917
    nxfatal << "Loop: PANIC! Can't open options file '" << fileName
8918
            << "'. Error is " << EGET() << " '" << ESTR() << "'.\n"
8919
            << std::flush;
8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938

    cerr << "Error" << ": Can't open options file '" << fileName
         << "'. Error is " << EGET() << " '" << ESTR() << "'.\n";

    delete [] fileName;

    return -1;
  }

  char options[DEFAULT_DISPLAY_OPTIONS_LENGTH];

  #ifdef VALGRIND

  memset(options, '\0', DEFAULT_DISPLAY_OPTIONS_LENGTH);

  #endif

  if (fgets(options, DEFAULT_DISPLAY_OPTIONS_LENGTH, filePtr) == NULL)
  {
8939
    nxfatal << "Loop: PANIC! Can't read options from file '" << fileName
8940
            << "'. Error is " << EGET() << " '" << ESTR() << "'.\n"
8941
            << std::flush;
8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971

    cerr << "Error" << ": Can't read options from file '" << fileName
         << "'. Error is " << EGET() << " '" << ESTR() << "'.\n";

    fclose(filePtr);

    delete [] fileName;

    return -1;
  }

  fclose(filePtr);

  //
  // Purge the newline and the other non-
  // printable characters in the string.
  //

  char *next = options;
  
  while (*next != '\0')
  {
    if (isprint(*next) == 0)
    {
      *next = '\0';
    }

    next++;
  }

8972
  nxinfo << "Loop: Read options '" << options << "' from file '"
8973
         << fileName << "'.\n" << std::flush;
8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993

  if (ParseEnvironmentOptions(options, 1) < 0)
  {
    delete [] fileName;

    return -1;
  }

  delete [] fileName;

  return 1;
}

//
// Parse the option string passed from the
// remote proxy at startup.
//

int ParseRemoteOptions(char *opts)
{
8994
  nxinfo << "Loop: Going to parse the remote options "
8995 8996
         << "string '" << opts << "'.\n"
         << std::flush;
8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040

  char *name;
  char *value;

  //
  // The options string is intended to be a series
  // of name/value tuples in the form name=value
  // separated by the ',' character.
  //

  int hasCookie = 0;
  int hasLink   = 0;
  int hasPack   = 0;
  int hasCache  = 0;
  int hasImages = 0;
  int hasDelta  = 0;
  int hasStream = 0;
  int hasData   = 0;
  int hasType   = 0;

  //
  // Get rid of the terminating space.
  //

  if (*(opts + strlen(opts) - 1) == ' ')
  {
    *(opts + strlen(opts) - 1) = '\0';
  }

  name = strtok(opts, "=");

  while (name)
  {
    value = strtok(NULL, ",");

    if (CheckArg("remote", name, value) < 0)
    {
      return -1;
    }

    if (strcasecmp(name, "cookie") == 0)
    {
      if (WE_PROVIDE_CREDENTIALS)
      {
9041
        nxwarn << "Loop: WARNING! Ignoring remote option 'cookie' "
9042 9043
               << "with value '" << value << "' when initiating "
               << "connection.\n" << std::flush;
9044 9045 9046 9047 9048 9049 9050

        cerr << "Warning" << ": Ignoring remote option 'cookie' "
             << "with value '" << value << "' when initiating "
             << "connection.\n";
      }
      else if (strncasecmp(authCookie, value, strlen(authCookie)) != 0)
      {
9051
        nxfatal << "Loop: PANIC! Authentication cookie '" << value
9052
                << "' doesn't match '" << authCookie << "'.\n"
9053
                << std::flush;
9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072

        cerr << "Error" << ": Authentication cookie '" << value
             << "' doesn't match '" << authCookie << "'.\n";

        return -1;
      }

      hasCookie = 1;
    }
    else if (strcasecmp(name, "link") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        if (*linkSpeedName != '\0' && strcasecmp(linkSpeedName, value) != 0)
        {
9073
          nxwarn << "Loop: WARNING! Overriding option 'link' "
9074 9075
                 << "with new value '" << value << "'.\n"
                 << std::flush;
9076 9077 9078 9079 9080 9081 9082

          cerr << "Warning" << ": Overriding option 'link' "
               << "with new value '" << value << "'.\n";
        }

        if (ParseLinkOption(value) < 0)
        {
9083
          nxfatal << "Loop: PANIC! Can't identify remote 'link' "
9084
                  << "option in string '" << value << "'.\n"
9085
                  << std::flush;
9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105

          cerr << "Error" << ": Can't identify remote 'link' "
               << "option in string '" << value << "'.\n";

          return -1;
        }
      }

      hasLink = 1;
    }
    else if (strcasecmp(name, "pack") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        if (*packMethodName != '\0' && strcasecmp(packMethodName, value) != 0)
        {
9106
          nxwarn << "Loop: WARNING! Overriding option 'pack' "
9107 9108
                 << "with remote value '" << value << "'.\n"
                 << std::flush;
9109 9110 9111 9112 9113 9114 9115

          cerr << "Warning" << ": Overriding option 'pack' "
               << "with remote value '" << value << "'.\n";
        }

        if (ParsePackOption(value) < 0)
        {
9116
          nxfatal << "Loop: PANIC! Invalid pack option '"
9117
                  << value << "' requested by remote.\n"
9118
                  << std::flush;
9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145

          cerr << "Error" << ": Invalid pack option '"
               << value << "' requested by remote.\n";

          return -1;
        }
      }

      hasPack = 1;
    }
    else if (strcasecmp(name, "cache") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        //
        // Cache size is sent as a hint of how much memory
        // the remote proxy is going to consume. A very low
        // powered thin client could choose to refuse the
        // connection.
        //

        if (ParseCacheOption(value) < 0)
        {
9146
          nxfatal << "Loop: PANIC! Can't identify remote 'cache' "
9147
                  << "option in string '" << value << "'.\n"
9148
                  << std::flush;
9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174

          cerr << "Error" << ": Can't identify remote 'cache' "
               << "option in string '" << value << "'.\n";

          return -1;
        }
      }

      hasCache = 1;
    }
    else if (strcasecmp(name, "images") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        //
        // Images cache size is sent as a hint.
        // There is no obbligation for the local
        // proxy to use the persistent cache.
        //

        if (ParseImagesOption(value) < 0)
        {
9175
          nxfatal << "Loop: PANIC! Can't identify remote 'images' "
9176
                  << "option in string '" << value << "'.\n"
9177
                  << std::flush;
9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198

          cerr << "Error" << ": Can't identify remote 'images' "
               << "option in string '" << value << "'.\n";

          return -1;
        }
      }

      hasImages = 1;
    }
    else if (strcasecmp(name, "limit") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        if (*bitrateLimitName != '\0' &&
                strcasecmp(bitrateLimitName, value) != 0)
        {
9199
          nxwarn << "Loop: WARNING! Overriding option 'limit' "
9200 9201
                 << "with new value '" << value << "'.\n"
                 << std::flush;
9202 9203 9204 9205 9206 9207 9208

          cerr << "Warning" << ": Overriding option 'limit' "
               << "with new value '" << value << "'.\n";
        }

        if (ParseBitrateOption(value) < 0)
        {
9209
          nxfatal << "Loop: PANIC! Can't identify 'limit' "
9210
                  << "option in string '" << value << "'.\n"
9211
                  << std::flush;
9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258

          cerr << "Error" << ": Can't identify 'limit' "
               << "option in string '" << value << "'.\n";

          return -1;
        }
      }

    }
    else if (strcasecmp(name, "render") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        useRender = ValidateArg("remote", name, value);
      }

    }
    else if (strcasecmp(name, "taint") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        useTaint = ValidateArg("remote", name, value);
      }

    }
    else if (strcasecmp(name, "type") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        if (strcasecmp(value, "default") == 0)
        {
          *sessionType = '\0';
        }
        else
        {
9259
          snprintf(sessionType, DEFAULT_STRING_LENGTH, "%s", value);
9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284
        }
      }

      hasType = 1;
    }
    else if (strcasecmp(name, "strict") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        useStrict = ValidateArg("remote", name, value);
      }

    }
    else if (strcasecmp(name, "shseg") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else if (ParseShmemOption(value) < 0)
      {
9285
        nxfatal << "Loop: PANIC! Can't identify size of shared memory "
9286
                << "segment in string '" << value << "'.\n"
9287
                << std::flush;
9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416

        cerr << "Error" << ": Can't identify size of shared memory "
             << "segment in string '" << value << "'.\n";

        return -1;
      }

    }
    else if (strcasecmp(name, "delta") == 0)
    {
      if (control -> ProxyMode == proxy_client)
      {
        PrintOptionIgnored("remote", name, value);
      }
      else
      {
        control -> RemoteDeltaCompression = ValidateArg("remote", name, value);

        //
        // Follow for delta compression the
        // same settings as the client proxy.
        //

        control -> LocalDeltaCompression  = control -> RemoteDeltaCompression;
      }

      hasDelta = 1;
    }
    else if (strcasecmp(name, "stream") == 0)
    {
      //
      // If remote side didn't choose its own
      // stream compression level then assume
      // local settings.
      //

      if (strcasecmp(value, "default") == 0)
      {
        //
        // This applies only at client side.
        //

        control -> RemoteStreamCompression =
            control -> LocalStreamCompression;

        control -> RemoteStreamCompressionLevel =
            control -> LocalStreamCompressionLevel;
      }
      else
      {
        control -> RemoteStreamCompressionLevel = ValidateArg("remote", name, value);

        if (control -> RemoteStreamCompressionLevel > 0)
        {
          control -> RemoteStreamCompression = 1;
        }
        else
        {
          control -> RemoteStreamCompression = 0;
        }

        if (control -> LocalStreamCompressionLevel < 0)
        {
          control -> LocalStreamCompressionLevel = ValidateArg("remote", name, value);

          if (control -> LocalStreamCompressionLevel > 0)
          {
            control -> LocalStreamCompression = 1;
          }
          else
          {
            control -> LocalStreamCompression = 0;
          }
        }
      }

      hasStream = 1;
    }
    else if (strcasecmp(name, "data") == 0)
    {
      //
      // Apply the same to data compression level.
      //

      if (strcasecmp(value, "default") == 0)
      {
        control -> RemoteDataCompression =
            control -> LocalDataCompression;

        control -> RemoteDataCompressionLevel =
            control -> LocalDataCompressionLevel;
      }
      else
      {
        control -> RemoteDataCompressionLevel = ValidateArg("remote", name, value);

        if (control -> RemoteDataCompressionLevel > 0)
        {
          control -> RemoteDataCompression = 1;
        }
        else
        {
          control -> RemoteDataCompression = 0;
        }

        if (control -> LocalDataCompressionLevel < 0)
        {
          control -> LocalDataCompressionLevel = ValidateArg("remote", name, value);

          if (control -> LocalDataCompressionLevel > 0)
          {
            control -> LocalDataCompression = 1;
          }
          else
          {
            control -> LocalDataCompression = 0;
          }
        }
      }

      hasData = 1;
    }
    else if (strcasecmp(name, "flush") == 0)
    {
      //
      // This option has no effect in recent
      // versions.
      //

9417
      nxdbg << "Loop: Ignoring obsolete remote option '"
9418 9419
            << name << "' with value '" << value
            << "'.\n" << std::flush;
9420 9421 9422
    }
    else
    {
9423
      nxwarn << "Loop: WARNING! Ignoring unknown remote option '"
9424 9425
             << name << "' with value '" << value << "'.\n"
             << std::flush;
9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513

      cerr << "Warning" << ": Ignoring unknown remote option '"
           << name << "' with value '" << value << "'.\n";
    }

    name = strtok(NULL, "=");

  } // End of while (name) ...

  //
  // If we are client side, we need remote 'stream'
  // and 'data' options. If we are server, we need
  // all the above plus 'link' and some others.
  //

  char missing[DEFAULT_STRING_LENGTH];

  *missing = '\0';

  if (control -> ProxyMode == proxy_client)
  {
    if (hasStream == 0)
    {
      strcpy(missing, "stream");
    }
    else if (hasData == 0)
    {
      strcpy(missing, "data");
    }
  }
  else
  {
    //
    // Don't complain if the optional 'flush',
    // 'render' and 'taint' options are not
    // provided.
    //

    if (hasLink == 0)
    {
      strcpy(missing, "link");
    }
    else if (hasCache == 0)
    {
      strcpy(missing, "cache");
    }
    else if (hasPack == 0)
    {
      strcpy(missing, "pack");
    }
    else if (hasDelta == 0)
    {
      strcpy(missing, "delta");
    }
    else if (hasStream == 0)
    {
      strcpy(missing, "stream");
    }
    else if (hasData == 0)
    {
      strcpy(missing, "data");
    }
    else if (hasType == 0)
    {
      strcpy(missing, "type");
    }
    else if (hasImages == 0)
    {
      strcpy(missing, "images");
    }
  }

  if (WE_PROVIDE_CREDENTIALS == 0)
  {
    //
    // Can be that user doesn't have requested to
    // check the authorization cookie provided by
    // the connecting peer.
    //

    if (hasCookie == 0 && *authCookie != '\0')
    {
      strcpy(missing, "cookie");
    }
  }

  if (*missing != '\0')
  {
9514 9515
    nxfatal << "Loop: PANIC! The remote peer didn't specify the option '"
            << missing << "'.\n" << std::flush;
9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532

    cerr << "Error" << ": The remote peer didn't specify the option '"
         << missing << "'.\n";

    return -1;
  }

  return 1;
}

//
// Parse the cookie provided by the NX proxy
// connection forwarder.
//

int ParseForwarderOptions(char *opts)
{
9533
  nxinfo << "Loop: Going to parse the forwarder options "
9534 9535
         << "string '" << opts << "'.\n"
         << std::flush;
9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565

  char *name;
  char *value;

  int hasCookie = 0;

  //
  // Get rid of the terminating space.
  //

  if (*(opts + strlen(opts) - 1) == ' ')
  {
    *(opts + strlen(opts) - 1) = '\0';
  }

  name = strtok(opts, "=");

  while (name)
  {
    value = strtok(NULL, ",");

    if (CheckArg("forwarder", name, value) < 0)
    {
      return -1;
    }

    if (strcasecmp(name, "cookie") == 0)
    {
      if (strncasecmp(authCookie, value, strlen(authCookie)) != 0)
      {
9566
        nxfatal << "Loop: PANIC! The NX forwarder cookie '" << value
9567
                << "' doesn't match '" << authCookie << "'.\n"
9568
                << std::flush;
9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579

        cerr << "Error" << ": The NX forwarder cookie '" << value
             << "' doesn't match '" << authCookie << "'.\n";

        return -1;
      }

      hasCookie = 1;
    }
    else
    {
9580
      nxwarn << "Loop: WARNING! Ignoring unknown forwarder option '"
9581 9582
             << name << "' with value '" << value << "'.\n"
             << std::flush;
9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593

      cerr << "Warning" << ": Ignoring unknown forwarder option '"
           << name << "' with value '" << value << "'.\n";
    }

    name = strtok(NULL, "=");

  } // End of while (name) ...

  if (hasCookie == 0)
  {
9594 9595
    nxfatal << "Loop: PANIC! The NX forwarder didn't provide "
            << "the authentication cookie.\n" << std::flush;
9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613

    cerr << "Error" << ": The NX forwarder didn't provide "
         << "the authentication cookie.\n";

    return -1;
  }

  return 1;
}

int SetCore()
{
  #ifdef COREDUMPS

  rlimit rlim;

  if (getrlimit(RLIMIT_CORE, &rlim))
  {
9614
    nxinfo << "Cannot read RLIMIT_CORE. Error is '"
9615
           << ESTR() << "'.\n" << std::flush;
9616 9617 9618 9619 9620 9621 9622 9623 9624 9625

    return -1;
  }

  if (rlim.rlim_cur < rlim.rlim_max)
  {
    rlim.rlim_cur = rlim.rlim_max;

    if (setrlimit(RLIMIT_CORE, &rlim))
    {
9626
      nxinfo << "Loop: Cannot read RLIMIT_CORE. Error is '"
9627
             << ESTR() << "'.\n" << std::flush;
9628 9629 9630 9631 9632

      return -2;
    }
  }

9633
  nxinfo << "Loop: Set RLIMIT_CORE to "<< rlim.rlim_max
9634
         << ".\n" << std::flush;
9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645

  #endif // #ifdef COREDUMPS

  return 1;
}

char *GetLastCache(char *listBuffer, const char *searchPath)
{
  if (listBuffer == NULL || searchPath == NULL ||
          strncmp(listBuffer, "cachelist=", strlen("cachelist=")) != 0)
  {
9646
    nxinfo << "Loop: Invalid parameters '" << listBuffer << "' and '"
9647 9648
           << (searchPath != NULL ? searchPath : "")
           << "'. Can't select any cache.\n" << std::flush;
9649 9650 9651 9652 9653 9654 9655 9656

    return NULL;
  }

  char *selectedName = new char[MD5_LENGTH * 2 + 3];

  *selectedName = '\0';

9657 9658
  const char *localPrefix;
  const char *remotePrefix;
9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694

  if (control -> ProxyMode == proxy_client)
  {
    localPrefix  = "C-";
    remotePrefix = "S-";
  }
  else
  {
    localPrefix  = "S-";
    remotePrefix = "C-";
  }

  //
  // Get rid of prefix.
  //

  listBuffer += strlen("cachelist=");

  char *fileName;

  fileName = strtok(listBuffer, ",");

  //
  // It is "/path/to/file" + "/" + "C-" + 32 + "\0".
  //

  char fullPath[strlen(searchPath) + MD5_LENGTH * 2 + 4];

  time_t selectedTime = 0;

  struct stat fileStat;

  while (fileName)
  {
    if (strncmp(fileName, "none", strlen("none")) == 0)
    {
9695
      nxinfo << "Loop: No cache files seem to be available.\n"
9696
             << std::flush;
9697 9698 9699 9700 9701 9702 9703 9704

      delete [] selectedName;

      return NULL;
    }
    else if (strlen(fileName) != MD5_LENGTH * 2 + 2 ||
                 strncmp(fileName, remotePrefix, 2) != 0)
    {
9705
      nxfatal << "Loop: PANIC! Bad cache file name '"
9706
              << fileName << "'.\n" << std::flush;
9707 9708 9709 9710 9711 9712 9713 9714 9715

      cerr << "Error" << ": Bad cache file name '"
           << fileName << "'.\n";

      delete [] selectedName;

      HandleCleanup();
    }

9716
    nxinfo << "Loop: Parsing remote cache name '"
9717
           << fileName << "'.\n" << std::flush;
9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731

    //
    // Prefix, received as "S-", becomes
    // "C-" and viceversa.
    //

    *fileName = *localPrefix;

    strcpy(fullPath, searchPath);
    strcat(fullPath, "/");
    strcat(fullPath, fileName);

    if (stat(fullPath, &fileStat) == 0)
    {
9732
      nxinfo << "Loop: Found a matching cache '"
9733
             << std::string(fullPath) << "'.\n" << std::flush;
9734 9735 9736 9737 9738 9739 9740 9741 9742 9743

      if (fileStat.st_mtime >= selectedTime)
      {
        strcpy(selectedName, fileName);

        selectedTime = fileStat.st_mtime;
      }
    }
    else
    {
9744
      nxinfo << "Loop: Can't get stats of file '"
9745
             << std::string(fullPath) << "'.\n" << std::flush;
9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775
    }

    fileName = strtok(NULL, ",");
  }

  if (*selectedName != '\0')
  {
    return selectedName;
  }
  else
  {
    delete [] selectedName;

    return NULL;
  }
}

char *GetTempPath()
{
  if (*tempDir == '\0')
  {
    //
    // Check the NX_TEMP environment, first,
    // then the TEMP variable.
    //

    const char *tempEnv = getenv("NX_TEMP");

    if (tempEnv == NULL || *tempEnv == '\0')
    {
9776
      nxinfo << "Loop: WARNING! No environment for NX_TEMP.\n"
9777
             << std::flush;
9778 9779 9780 9781 9782

      tempEnv = getenv("TEMP");

      if (tempEnv == NULL || *tempEnv == '\0')
      {
9783
        nxinfo << "Loop: WARNING! No environment for TEMP.\n"
9784
               << std::flush;
9785 9786 9787 9788 9789 9790 9791

        tempEnv = "/tmp";
      }
    }

    if (strlen(tempEnv) > DEFAULT_STRING_LENGTH - 1)
    {
9792
      nxfatal << "Loop: PANIC! Invalid value for the NX "
9793
              << "temporary directory '" << tempEnv
9794
              << "'.\n" << std::flush;
9795 9796 9797 9798 9799 9800 9801 9802 9803 9804

      cerr << "Error" << ": Invalid value for the NX "
           << "temporary directory '" << tempEnv
           << "'.\n";

      HandleCleanup();
    }

    strcpy(tempDir, tempEnv);

9805
    nxinfo << "Loop: Assuming temporary NX directory '"
9806
           << tempDir << "'.\n" << std::flush;
9807 9808 9809 9810 9811 9812
  }

  char *tempPath = new char[strlen(tempDir) + 1];

  if (tempPath == NULL)
  {
9813 9814
    nxfatal << "Loop: PANIC! Can't allocate memory "
            << "for the temp path.\n" << std::flush;
9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838

    cerr << "Error" << ": Can't allocate memory "
         << "for the temp path.\n";

    HandleCleanup();
  }

  strcpy(tempPath, tempDir);

  return tempPath;
}

char *GetClientPath()
{
  if (*clientDir == '\0')
  {
    //
    // Check the NX_CLIENT environment.
    //

    const char *clientEnv = getenv("NX_CLIENT");

    if (clientEnv == NULL || *clientEnv == '\0')
    {
9839
      nxinfo << "Loop: WARNING! No environment for NX_CLIENT.\n"
9840
             << std::flush;
9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862

      //
      // Try to guess the location of the client.
      //

      clientEnv = "/usr/NX/bin/nxclient";

      #ifdef __APPLE__

      clientEnv = "/Applications/NX Client for OSX.app/Contents/MacOS/nxclient";

      #endif

      #ifdef __CYGWIN32__

      clientEnv = "C:\\Program Files\\NX Client for Windows\\nxclient";

      #endif
    }

    if (strlen(clientEnv) > DEFAULT_STRING_LENGTH - 1)
    {
9863
      nxfatal << "Loop: PANIC! Invalid value for the NX "
9864
              << "client directory '" << clientEnv
9865
              << "'.\n" << std::flush;
9866 9867 9868 9869 9870 9871 9872 9873 9874 9875

      cerr << "Error" << ": Invalid value for the NX "
           << "client directory '" << clientEnv
           << "'.\n";

      HandleCleanup();
    }

    strcpy(clientDir, clientEnv);

9876
    nxinfo << "Loop: Assuming NX client location '"
9877
           << clientDir << "'.\n" << std::flush;
9878 9879 9880 9881 9882 9883
  }

  char *clientPath = new char[strlen(clientDir) + 1];

  if (clientPath == NULL)
  {
9884 9885
    nxfatal << "Loop: PANIC! Can't allocate memory "
            << "for the client path.\n" << std::flush;
9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909

    cerr << "Error" << ": Can't allocate memory "
         << "for the client path.\n";

    HandleCleanup();
  }

  strcpy(clientPath, clientDir);

  return clientPath;
}

char *GetSystemPath()
{
  if (*systemDir == '\0')
  {
    //
    // Check the NX_SYSTEM environment.
    //

    const char *systemEnv = getenv("NX_SYSTEM");

    if (systemEnv == NULL || *systemEnv == '\0')
    {
9910
      nxinfo << "Loop: WARNING! No environment for NX_SYSTEM.\n"
9911
             << std::flush;
9912 9913 9914 9915 9916 9917

      systemEnv = "/usr/NX";
    }

    if (strlen(systemEnv) > DEFAULT_STRING_LENGTH - 1)
    {
9918
      nxfatal << "Loop: PANIC! Invalid value for the NX "
9919
              << "system directory '" << systemEnv
9920
              << "'.\n" << std::flush;
9921 9922 9923 9924 9925 9926 9927 9928 9929 9930

      cerr << "Error" << ": Invalid value for the NX "
           << "system directory '" << systemEnv
           << "'.\n";

      HandleCleanup();
    }

    strcpy(systemDir, systemEnv);

9931
    nxinfo << "Loop: Assuming system NX directory '"
9932
           << systemDir << "'.\n" << std::flush;
9933 9934 9935 9936 9937 9938
  }

  char *systemPath = new char[strlen(systemDir) + 1];

  if (systemPath == NULL)
  {
9939 9940
    nxfatal << "Loop: PANIC! Can't allocate memory "
            << "for the system path.\n" << std::flush;
9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964

    cerr << "Error" << ": Can't allocate memory "
         << "for the system path.\n";

    HandleCleanup();
  }

  strcpy(systemPath, systemDir);

  return systemPath;
}

char *GetHomePath()
{
  if (*homeDir == '\0')
  {
    //
    // Check the NX_HOME environment.
    //

    const char *homeEnv = getenv("NX_HOME");

    if (homeEnv == NULL || *homeEnv == '\0')
    {
9965
      nxinfo << "Loop: WARNING! No environment for NX_HOME.\n"
9966
             << std::flush;
9967 9968 9969 9970 9971

      homeEnv = getenv("HOME");

      if (homeEnv == NULL || *homeEnv == '\0')
      {
9972 9973
        nxfatal << "Loop: PANIC! No environment for HOME.\n"
                << std::flush;
9974 9975 9976 9977 9978 9979 9980 9981 9982

        cerr << "Error" << ": No environment for HOME.\n";

        HandleCleanup();
      }
    }

    if (strlen(homeEnv) > DEFAULT_STRING_LENGTH - 1)
    {
9983
      nxfatal << "Loop: PANIC! Invalid value for the NX "
9984
              << "home directory '" << homeEnv
9985
              << "'.\n" << std::flush;
9986 9987 9988 9989 9990 9991 9992 9993 9994 9995

      cerr << "Error" << ": Invalid value for the NX "
           << "home directory '" << homeEnv
           << "'.\n";

      HandleCleanup();
    }

    strcpy(homeDir, homeEnv);

9996
    nxinfo << "Loop: Assuming NX user's home directory '"
9997
           << homeDir << "'.\n" << std::flush;
9998 9999 10000 10001 10002 10003
  }

  char *homePath = new char[strlen(homeDir) + 1];

  if (homePath == NULL)
  {
10004 10005
    nxfatal << "Loop: PANIC! Can't allocate memory "
            << "for the home path.\n" << std::flush;
10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029

    cerr << "Error" << ": Can't allocate memory "
         << "for the home path.\n";

    HandleCleanup();
  }

  strcpy(homePath, homeDir);

  return homePath;
}

char *GetRootPath()
{
  if (*rootDir == '\0')
  {
    //
    // Check the NX_ROOT environment.
    //

    const char *rootEnv = getenv("NX_ROOT");

    if (rootEnv == NULL || *rootEnv == '\0')
    {
10030
      nxinfo << "Loop: WARNING! No environment for NX_ROOT.\n"
10031
             << std::flush;
10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043

      //
      // We will determine the root NX directory
      // based on the NX_HOME or HOME directory
      // settings.
      //

      const char *homeEnv = GetHomePath();

      if (strlen(homeEnv) > DEFAULT_STRING_LENGTH -
              strlen("/.nx") - 1)
      {
10044
        nxfatal << "Loop: PANIC! Invalid value for the NX "
10045
                << "home directory '" << homeEnv
10046
                << "'.\n" << std::flush;
10047 10048 10049 10050 10051 10052 10053 10054

        cerr << "Error" << ": Invalid value for the NX "
             << "home directory '" << homeEnv
             << "'.\n";

        HandleCleanup();
      }

10055
      nxinfo << "Loop: Assuming NX root directory in "
10056
             << "the user's home '" << homeEnv
10057
              << "'.\n" << std::flush;
10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073

      strcpy(rootDir, homeEnv);
      strcat(rootDir, "/.nx");

      delete [] homeEnv;

      //
      // Create the NX root directory.
      //

      struct stat dirStat;

      if ((stat(rootDir, &dirStat) == -1) && (EGET() == ENOENT))
      {
        if (mkdir(rootDir, 0700) < 0 && (EGET() != EEXIST))
        {
10074
          nxfatal << "Loop: PANIC! Can't create directory '"
10075
                  << rootDir << ". Error is " << EGET() << " '"
10076
                  << ESTR() << "'.\n" << std::flush;
10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089

          cerr << "Error" << ": Can't create directory '"
               << rootDir << ". Error is " << EGET() << " '"
               << ESTR() << "'.\n";

          HandleCleanup();
        }
      }
    }
    else
    {
      if (strlen(rootEnv) > DEFAULT_STRING_LENGTH - 1)
      {
10090
        nxfatal << "Loop: PANIC! Invalid value for the NX "
10091
                << "root directory '" << rootEnv
10092
                << "'.\n" << std::flush;
10093 10094 10095 10096 10097 10098 10099 10100 10101 10102

        cerr << "Error" << ": Invalid value for the NX "
             << "root directory '" << rootEnv
             << "'.\n";

        HandleCleanup();
      }

      strcpy(rootDir, rootEnv);
    }
10103

10104
    nxinfo << "Loop: Assuming NX root directory '"
10105
           << rootDir << "'.\n" << std::flush;
10106 10107 10108 10109 10110 10111
  }

  char *rootPath = new char[strlen(rootDir) + 1];

  if (rootPath == NULL)
  {
10112 10113
    nxfatal << "Loop: PANIC! Can't allocate memory "
            << "for the root path.\n" << std::flush;
10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164

    cerr << "Error" << ": Can't allocate memory "
         << "for the root path.\n";

    HandleCleanup();
  }

  strcpy(rootPath, rootDir);

  return rootPath;
}

char *GetCachePath()
{
  char *rootPath = GetRootPath();

  char *cachePath;

  if (*sessionType != '\0')
  {
    cachePath = new char[strlen(rootPath) + strlen("/cache-") +
                             strlen(sessionType) + 1];
  }
  else
  {
    cachePath = new char[strlen(rootPath) + strlen("/cache") + 1];
  }

  strcpy(cachePath, rootPath);

  if (*sessionType != '\0')
  {
    strcat(cachePath, "/cache-");

    strcat(cachePath, sessionType);
  }
  else
  {
    strcat(cachePath, "/cache");
  }

  //
  // Create the cache directory if needed.
  //

  struct stat dirStat;

  if ((stat(cachePath, &dirStat) == -1) && (EGET() == ENOENT))
  {
    if (mkdir(cachePath, 0700) < 0 && (EGET() != EEXIST))
    {
10165
      nxfatal << "Loop: PANIC! Can't create directory '" << cachePath
10166
              << ". Error is " << EGET() << " '" << ESTR() << "'.\n"
10167
              << std::flush;
10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203

      cerr << "Error" << ": Can't create directory '" << cachePath
           << ". Error is " << EGET() << " '" << ESTR() << "'.\n";

      delete [] rootPath;
      delete [] cachePath;

      return NULL;
    }
  }

  delete [] rootPath;

  return cachePath;
}

char *GetImagesPath()
{
  char *rootPath = GetRootPath();

  char *imagesPath = new char[strlen(rootPath) + strlen("/images") + 1];

  strcpy(imagesPath, rootPath);

  strcat(imagesPath, "/images");

  //
  // Create the cache directory if needed.
  //

  struct stat dirStat;

  if ((stat(imagesPath, &dirStat) == -1) && (EGET() == ENOENT))
  {
    if (mkdir(imagesPath, 0700) < 0 && (EGET() != EEXIST))
    {
10204
      nxfatal << "Loop: PANIC! Can't create directory '" << imagesPath
10205
              << ". Error is " << EGET() << " '" << ESTR() << "'.\n"
10206
              << std::flush;
10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240

      cerr << "Error" << ": Can't create directory '" << imagesPath
           << ". Error is " << EGET() << " '" << ESTR() << "'.\n";

      delete [] rootPath;
      delete [] imagesPath;

      return NULL;
    }
  }

  //
  // Create 16 directories in the path to
  // hold the images whose name begins with
  // the corresponding hexadecimal digit.
  //

  char *digitPath = new char[strlen(imagesPath) + 5];

  strcpy(digitPath, imagesPath);

  //
  // Image paths have format "[path][/I-c][\0]",
  // where c is the first digit of the checksum.
  //

  for (char digit = 0; digit < 16; digit++)
  {
    sprintf(digitPath + strlen(imagesPath), "/I-%01X", digit);

    if ((stat(digitPath, &dirStat) == -1) && (EGET() == ENOENT))
    {
      if (mkdir(digitPath, 0700) < 0 && (EGET() != EEXIST))
      {
10241
        nxfatal << "Loop: PANIC! Can't create directory '" << digitPath
10242
                << ". Error is " << EGET() << " '" << ESTR() << "'.\n"
10243
                << std::flush;
10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296

        cerr << "Error" << ": Can't create directory '" << digitPath
             << ". Error is " << EGET() << " '" << ESTR() << "'.\n";

        delete [] rootPath;
        delete [] imagesPath;
        delete [] digitPath;

        return NULL;
      }
    }
  }

  delete [] rootPath;
  delete [] digitPath;

  return imagesPath;
}

char *GetSessionPath()
{
  if (*sessionDir == '\0')
  {
    char *rootPath = GetRootPath();

    strcpy(sessionDir, rootPath);

    if (control -> ProxyMode == proxy_client)
    {
      strcat(sessionDir, "/C-");
    }
    else
    {
      strcat(sessionDir, "/S-");
    }

    if (*sessionId == '\0')
    {
      char port[DEFAULT_STRING_LENGTH];

      sprintf(port, "%d", proxyPort);

      strcpy(sessionId, port);
    }

    strcat(sessionDir, sessionId);

    struct stat dirStat;

    if ((stat(sessionDir, &dirStat) == -1) && (EGET() == ENOENT))
    {
      if (mkdir(sessionDir, 0700) < 0 && (EGET() != EEXIST))
      {
10297
        nxfatal << "Loop: PANIC! Can't create directory '" << sessionDir
10298
                << ". Error is " << EGET() << " '" << ESTR() << "'.\n"
10299
                << std::flush;
10300 10301 10302 10303 10304 10305 10306 10307 10308 10309

        cerr << "Error" << ": Can't create directory '" << sessionDir
             << ". Error is " << EGET() << " '" << ESTR() << "'.\n";

        delete [] rootPath;

        return NULL;
      }
    }

10310
    nxinfo << "Loop: Root of NX session is '" << sessionDir
10311
           << "'.\n" << std::flush;
10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380

    delete [] rootPath;
  }

  char *sessionPath = new char[strlen(sessionDir) + 1];

  strcpy(sessionPath, sessionDir);

  return sessionPath;
}

//
// Identify requested link characteristics
// and set control parameters accordingly.
//

int ParseLinkOption(const char *opt)
{
  //
  // Normalize the user input.
  //

  if (strcasecmp(opt, "modem") == 0 ||
          strcasecmp(opt, "33k") == 0 ||
              strcasecmp(opt, "56k") == 0)
  {
    strcpy(linkSpeedName, "MODEM");
  }
  else if (strcasecmp(opt, "isdn")  == 0 ||
               strcasecmp(opt, "64k")  == 0 ||
                   strcasecmp(opt, "128k") == 0)
  {
    strcpy(linkSpeedName, "ISDN");
  }
  else if (strcasecmp(opt, "adsl") == 0 ||
               strcasecmp(opt, "256k") == 0 ||
                   strcasecmp(opt, "640k") == 0)
  {
    strcpy(linkSpeedName, "ADSL");
  }
  else if (strcasecmp(opt, "wan")  == 0 ||
               strcasecmp(opt, "1m")  == 0 ||
                   strcasecmp(opt, "2m")  == 0 ||
                       strcasecmp(opt, "34m") == 0)
  {
    strcpy(linkSpeedName, "WAN");
  }
  else if (strcasecmp(opt, "lan")   == 0 ||
               strcasecmp(opt, "10m")   == 0 ||
                   strcasecmp(opt, "100m")  == 0 ||
                       strcasecmp(opt, "local") == 0)
  {
    strcpy(linkSpeedName, "LAN");
  }

  if (strcasecmp(linkSpeedName, "modem") != 0 &&
          strcasecmp(linkSpeedName, "isdn")  != 0 &&
              strcasecmp(linkSpeedName, "adsl")  != 0 &&
                  strcasecmp(linkSpeedName, "wan")   != 0 &&
                      strcasecmp(linkSpeedName, "lan")   != 0)
  {
    return -1;
  }

  return 1;
}

int ParsePackOption(const char *opt)
{
10381
  nxdbg << "Loop: Pack method is " << packMethod
10382 10383
        << " quality is " << packQuality << ".\n"
        << std::flush;
10384

10385
  nxdbg << "Loop: Parsing pack method '" << opt
10386
        << "'.\n" << std::flush;
10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566

  if (strcasecmp(opt, "0") == 0 ||
          strcasecmp(opt, "none") == 0 ||
              strcasecmp(opt, "nopack") == 0 ||
                  strcasecmp(opt, "no-pack") == 0)
  {
    packMethod = PACK_NONE;
  }
  else if (strcasecmp(opt, "8") == 0)
  {
    packMethod = PACK_MASKED_8_COLORS;
  }
  else if (strcasecmp(opt, "64") == 0)
  {
    packMethod = PACK_MASKED_64_COLORS;
  }
  else if (strcasecmp(opt, "256") == 0)
  {
    packMethod = PACK_MASKED_256_COLORS;
  }
  else if (strcasecmp(opt, "512") == 0)
  {
    packMethod = PACK_MASKED_512_COLORS;
  }
  else if (strcasecmp(opt, "4k") == 0)
  {
    packMethod = PACK_MASKED_4K_COLORS;
  }
  else if (strcasecmp(opt, "32k") == 0)
  {
    packMethod = PACK_MASKED_32K_COLORS;
  }
  else if (strcasecmp(opt, "64k") == 0)
  {
    packMethod = PACK_MASKED_64K_COLORS;
  }
  else if (strcasecmp(opt, "256k") == 0)
  {
    packMethod = PACK_MASKED_256K_COLORS;
  }
  else if (strcasecmp(opt, "2m") == 0)
  {
    packMethod = PACK_MASKED_2M_COLORS;
  }
  else if (strcasecmp(opt, "16m") == 0)
  {
    packMethod = PACK_MASKED_16M_COLORS;
  }
  else if (strncasecmp(opt, "8-jpeg", strlen("8-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_8_COLORS;
  }
  else if (strncasecmp(opt, "64-jpeg", strlen("64-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_64_COLORS;
  }
  else if (strncasecmp(opt, "256-jpeg", strlen("256-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_256_COLORS;
  }
  else if (strncasecmp(opt, "512-jpeg", strlen("512-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_512_COLORS;
  }
  else if (strncasecmp(opt, "4k-jpeg", strlen("4k-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_4K_COLORS;
  }
  else if (strncasecmp(opt, "32k-jpeg", strlen("32k-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_32K_COLORS;
  }
  else if (strncasecmp(opt, "64k-jpeg", strlen("64k-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_64K_COLORS;
  }
  else if (strncasecmp(opt, "256k-jpeg", strlen("256k-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_256K_COLORS;
  }
  else if (strncasecmp(opt, "2m-jpeg", strlen("2m-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_2M_COLORS;
  }
  else if (strncasecmp(opt, "16m-jpeg", strlen("16m-jpeg")) == 0)
  {
    packMethod = PACK_JPEG_16M_COLORS;
  }
  else if (strncasecmp(opt, "8-png", strlen("8-png")) == 0)
  {
    packMethod = PACK_PNG_8_COLORS;
  }
  else if (strncasecmp(opt, "64-png", strlen("64-png")) == 0)
  {
    packMethod = PACK_PNG_64_COLORS;
  }
  else if (strncasecmp(opt, "256-png", strlen("256-png")) == 0)
  {
    packMethod = PACK_PNG_256_COLORS;
  }
  else if (strncasecmp(opt, "512-png", strlen("512-png")) == 0)
  {
    packMethod = PACK_PNG_512_COLORS;
  }
  else if (strncasecmp(opt, "4k-png", strlen("4k-png")) == 0)
  {
    packMethod = PACK_PNG_4K_COLORS;
  }
  else if (strncasecmp(opt, "32k-png", strlen("32k-png")) == 0)
  {
    packMethod = PACK_PNG_32K_COLORS;
  }
  else if (strncasecmp(opt, "64k-png", strlen("64k-png")) == 0)
  {
    packMethod = PACK_PNG_64K_COLORS;
  }
  else if (strncasecmp(opt, "256k-png", strlen("256k-png")) == 0)
  {
    packMethod = PACK_PNG_256K_COLORS;
  }
  else if (strncasecmp(opt, "2m-png", strlen("2m-png")) == 0)
  {
    packMethod = PACK_PNG_2M_COLORS;
  }
  else if (strncasecmp(opt, "16m-png", strlen("16m-png")) == 0)
  {
    packMethod = PACK_PNG_16M_COLORS;
  }
  else if (strncasecmp(opt, "16m-rgb", strlen("16m-rgb")) == 0 ||
               strncasecmp(opt, "rgb", strlen("rgb")) == 0)
  {
    packMethod = PACK_RGB_16M_COLORS;
  }
  else if (strncasecmp(opt, "16m-rle", strlen("16m-rle")) == 0 ||
               strncasecmp(opt, "rle", strlen("rle")) == 0)
  {
    packMethod = PACK_RLE_16M_COLORS;
  }
  else if (strncasecmp(opt, "16m-bitmap", strlen("16m-bitmap")) == 0 ||
               strncasecmp(opt, "bitmap", strlen("bitmap")) == 0)
  {
    packMethod = PACK_BITMAP_16M_COLORS;
  }
  else if (strncasecmp(opt, "lossy", strlen("lossy")) == 0)
  {
    packMethod = PACK_LOSSY;
  }
  else if (strncasecmp(opt, "lossless", strlen("lossless")) == 0)
  {
    packMethod = PACK_LOSSLESS;
  }
  else if (strncasecmp(opt, "adaptive", strlen("adaptive")) == 0)
  {
    packMethod = PACK_ADAPTIVE;
  }
  else
  {
    return -1;
  }

  if (packMethod == PACK_NONE)
  {
    strcpy(packMethodName, "none");
  }
  else
  {
    strcpy(packMethodName, opt);
  }

  if (packMethod == PACK_RGB_16M_COLORS ||
          packMethod == PACK_RLE_16M_COLORS ||
              packMethod == PACK_BITMAP_16M_COLORS ||
                  (packMethod >= PACK_JPEG_8_COLORS &&
                      packMethod <= PACK_JPEG_16M_COLORS) ||
                          (packMethod >= PACK_PNG_8_COLORS &&
                              packMethod <= PACK_PNG_16M_COLORS) ||
                                  packMethod == PACK_LOSSY ||
                                      packMethod == PACK_LOSSLESS ||
                                          packMethod == PACK_ADAPTIVE)
  {
10567
    const char *dash = strrchr(opt, '-');
10568 10569 10570 10571 10572 10573

    if (dash != NULL && strlen(dash) == 2 &&
            *(dash + 1) >= '0' && *(dash + 1) <= '9')
    {
      packQuality = atoi(dash + 1);

10574
      nxdbg << "Loop: Using pack quality '"
10575
            << packQuality << "'.\n" << std::flush;
10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877
    }
  }
  else
  {
    packQuality = 0;
  }

  return 1;
}

int ParsePackMethod(const int method, const int quality)
{
  switch (method)
  {
    case PACK_NONE:
    {
      strcpy(packMethodName, "none");

      break;
    }
    case PACK_MASKED_8_COLORS:
    {
      strcpy(packMethodName, "8");

      break;
    }
    case PACK_MASKED_64_COLORS:
    {
      strcpy(packMethodName, "64");

      break;
    }
    case PACK_MASKED_256_COLORS:
    {
      strcpy(packMethodName, "256");

      break;
    }
    case PACK_MASKED_512_COLORS:
    {
      strcpy(packMethodName, "512");

      break;
    }
    case PACK_MASKED_4K_COLORS:
    {
      strcpy(packMethodName, "4k");

      break;
    }
    case PACK_MASKED_32K_COLORS:
    {
      strcpy(packMethodName, "32k");

      break;
    }
    case PACK_MASKED_64K_COLORS:
    {
      strcpy(packMethodName, "64k");

      break;
    }
    case PACK_MASKED_256K_COLORS:
    {
      strcpy(packMethodName, "256k");

      break;
    }
    case PACK_MASKED_2M_COLORS:
    {
      strcpy(packMethodName, "2m");

      break;
    }
    case PACK_MASKED_16M_COLORS:
    {
      strcpy(packMethodName, "16m");

      break;
    }
    case PACK_JPEG_8_COLORS:
    {
      strcpy(packMethodName, "8-jpeg");

      break;
    }
    case PACK_JPEG_64_COLORS:
    {
      strcpy(packMethodName, "64-jpeg");

      break;
    }
    case PACK_JPEG_256_COLORS:
    {
      strcpy(packMethodName, "256-jpeg");

      break;
    }
    case PACK_JPEG_512_COLORS:
    {
      strcpy(packMethodName, "512-jpeg");

      break;
    }
    case PACK_JPEG_4K_COLORS:
    {
      strcpy(packMethodName, "4k-jpeg");

      break;
    }
    case PACK_JPEG_32K_COLORS:
    {
      strcpy(packMethodName, "32k-jpeg");

      break;
    }
    case PACK_JPEG_64K_COLORS:
    {
      strcpy(packMethodName, "64k-jpeg");

      break;
    }
    case PACK_JPEG_256K_COLORS:
    {
      strcpy(packMethodName, "256k-jpeg");

      break;
    }
    case PACK_JPEG_2M_COLORS:
    {
      strcpy(packMethodName, "2m-jpeg");

      break;
    }
    case PACK_JPEG_16M_COLORS:
    {
      strcpy(packMethodName, "16m-jpeg");

      break;
    }
    case PACK_PNG_8_COLORS:
    {
      strcpy(packMethodName, "8-png");

      break;
    }
    case PACK_PNG_64_COLORS:
    {
      strcpy(packMethodName, "64-png");

      break;
    }
    case PACK_PNG_256_COLORS:
    {
      strcpy(packMethodName, "256-png");

      break;
    }
    case PACK_PNG_512_COLORS:
    {
      strcpy(packMethodName, "512-png");

      break;
    }
    case PACK_PNG_4K_COLORS:
    {
      strcpy(packMethodName, "4k-png");

      break;
    }
    case PACK_PNG_32K_COLORS:
    {
      strcpy(packMethodName, "32k-png");

      break;
    }
    case PACK_PNG_64K_COLORS:
    {
      strcpy(packMethodName, "64k-png");

      break;
    }
    case PACK_PNG_256K_COLORS:
    {
      strcpy(packMethodName, "256k-png");

      break;
    }
    case PACK_PNG_2M_COLORS:
    {
      strcpy(packMethodName, "2m-png");

      break;
    }
    case PACK_PNG_16M_COLORS:
    {
      strcpy(packMethodName, "16m-png");

      break;
    }
    case PACK_RGB_16M_COLORS:
    {
      strcpy(packMethodName, "16m-rgb");

      break;
    }
    case PACK_RLE_16M_COLORS:
    {
      strcpy(packMethodName, "16m-rle");

      break;
    }
    case PACK_BITMAP_16M_COLORS:
    {
      strcpy(packMethodName, "16m-bitmap");

      break;
    }
    case PACK_LOSSY:
    {
      strcpy(packMethodName, "lossy");

      break;
    }
    case PACK_LOSSLESS:
    {
      strcpy(packMethodName, "lossless");

      break;
    }
    case PACK_ADAPTIVE:
    {
      strcpy(packMethodName, "adaptive");

      break;
    }
    default:
    {
      return -1;
    }
  }

  if (quality < 0 || quality > 9)
  {
    return -1;
  }

  if (packMethod == PACK_RGB_16M_COLORS ||
          packMethod == PACK_RLE_16M_COLORS ||
              packMethod == PACK_BITMAP_16M_COLORS ||
                  (packMethod >= PACK_JPEG_8_COLORS &&
                      packMethod <= PACK_JPEG_16M_COLORS) ||
                          (packMethod >= PACK_PNG_8_COLORS &&
                              packMethod <= PACK_PNG_16M_COLORS) ||
                                  packMethod == PACK_LOSSY ||
                                      packMethod == PACK_LOSSLESS ||
                                          packMethod == PACK_ADAPTIVE)
  {
    sprintf(packMethodName + strlen(packMethodName),
                "-%d", quality);
  }

  packMethod  = method;
  packQuality = quality;

  control -> PackMethod  = packMethod;
  control -> PackQuality = packQuality;

  return 1;
}

int SetDirectories()
{
  //
  // Determine the location of the user's NX
  // directory and the other relevant paths.
  // The functions below will check the pa-
  // rameters passed to the program and will
  // query the environment, if needed.
  //

  control -> HomePath   = GetHomePath();
  control -> RootPath   = GetRootPath();
  control -> SystemPath = GetSystemPath();
  control -> TempPath   = GetTempPath();
  control -> ClientPath = GetClientPath();

  return 1;
}

int SetLogs()
{
  //
  // So far we used stderr (or stdout under
  // WIN32). Now use the files selected by
  // the user.
  //

  if (*statsFileName == '\0')
  {
    strcpy(statsFileName, "stats");

10878
    nxinfo << "Loop: Assuming default statistics file '"
10879
           << statsFileName << "'.\n" << std::flush;
10880 10881 10882
  }
  else
  {
10883
    nxinfo << "Loop: Name selected for statistics is '"
10884
           << statsFileName << "'.\n" << std::flush;
10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897
  }

  if (OpenLogFile(statsFileName, statofs) < 0)
  {
    HandleCleanup();
  }

  #ifndef MIXED

  if (*errorsFileName == '\0')
  {
    strcpy(errorsFileName, "errors");

10898
    nxinfo << "Loop: Assuming default log file name '"
10899
           << errorsFileName << "'.\n" << std::flush;
10900 10901 10902
  }
  else
  {
10903
    nxinfo << "Loop: Name selected for log file is '"
10904
           << errorsFileName << "'.\n" << std::flush;
10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925
  }

  //
  // Share the bebug output with the nxssh binder
  // process. The file must be made writable by
  // everybody because the nxssh process is run by
  // nxserver as the nx user.
  //

  #ifdef BINDER

  strcpy(errorsFileName, "/tmp/errors");

  ostream *tmpfs = new ofstream(errorsFileName, ios::out);

  delete tmpfs;

  chmod(errorsFileName, S_IRUSR | S_IWUSR | S_IRGRP |
            S_IWGRP | S_IROTH | S_IWOTH);

  #endif
10926

10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942
  if (OpenLogFile(errorsFileName, logofs) < 0)
  {
    HandleCleanup();
  }

  //
  // By default the session log is the standard error
  // of the process. It is anyway required to set the
  // option when running inside SSH, otherwise the
  // output will go to the same file as the SSH log,
  // depending where the NX client has redirected the
  // output.
  //

  if (*sessionFileName != '\0')
  {
10943
    nxinfo << "Loop: Name selected for session file is '"
10944
           << sessionFileName << "'.\n" << std::flush;
10945 10946 10947

    if (errofs != NULL)
    {
10948
      nxwarn << "Loop: WARNING! Unexpected value for stream errofs.\n"
10949
             << std::flush;
10950 10951 10952 10953 10954 10955

      cerr << "Warning" << ": Unexpected value for stream errofs.\n";
    }

    if (errsbuf != NULL)
    {
10956
      nxwarn << "Loop: WARNING! Unexpected value for buffer errsbuf.\n"
10957
             << std::flush;
10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002

      cerr << "Warning" << ": Unexpected value for buffer errsbuf.\n";
    }

    errofs  = NULL;
    errsbuf = NULL;

    if (OpenLogFile(sessionFileName, errofs) < 0)
    {
      HandleCleanup();
    }

    //
    // Redirect the standard error to the file.
    //

    errsbuf = cerr.rdbuf(errofs -> rdbuf());
  }

  #endif

  return 1;
}

int SetPorts()
{
  //
  // Depending on the proxy side, we need to determine on which
  // port to listen for the given protocol or to which port we
  // will have to forward the connection. Three possibilities
  // are given for each supported protocol:
  //
  // Port <= 0: Disable port forwarding.
  // Port == 1: Use the default port.
  // Port >  1: Use the specified port.
  //
  // At the connectiong side the user should always explicitly
  // set the ports where the connections will be forwarded. This
  // is both for security reasons and because, when running both
  // proxies on the same host, there is a concrete possibility
  // that, by using the default ports, the connection will be
  // forwarded to the same port where the peer proxy is listen-
  // ing, causing a loop.
  //

11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013
  if (control -> ProxyMode == proxy_client) {
    // ChannelEndPoint::enabled() implements the logic described above,
    // and takes the default port into consideration. If cups=1, and
    // there is a default port, then enabled() will return true.
    //
    // Therefore, we must set the default port before calling this
    // function.
    cupsPort.setDefaultTCPPort(DEFAULT_NX_CUPS_PORT_OFFSET + proxyPort);
    useCupsSocket = cupsPort.enabled();
  } else {
    cupsPort.setDefaultTCPPort(631);
11014 11015
  }

11016 11017


11018 11019
  nxinfo << "Loop: cups port: '" << cupsPort
         << "'.\n" << std::flush;
11020

11021 11022 11023 11024 11025
  if (control -> ProxyMode == proxy_client) {
    auxPort.setDefaultTCPPort(DEFAULT_NX_AUX_PORT_OFFSET + proxyPort);
    useAuxSocket = auxPort.enabled();
  } else {
    auxPort.setDefaultTCPPort(1);
11026

11027
    if ( auxPort.getTCPPort() != 1 ) {
11028
        nxwarn << "Loop: WARNING! Overriding auxiliary X11 "
11029 11030
               << "port with new value '" << 1 << "'.\n"
               << std::flush;
11031

11032 11033
      cerr << "Warning" << ": Overriding auxiliary X11 "
           << "port with new value '" << 1 << "'.\n";
11034

11035
      auxPort.setSpec("1");
11036 11037 11038
    }
  }

11039 11040
  nxinfo << "Loop: aux port: '" << auxPort
         << "'.\n" << std::flush;
11041

11042 11043 11044 11045 11046
  if (control -> ProxyMode == proxy_client) {
    smbPort.setDefaultTCPPort(DEFAULT_NX_SMB_PORT_OFFSET + proxyPort);
    useSmbSocket = smbPort.enabled();
  } else {
    smbPort.setDefaultTCPPort(139);
11047 11048 11049
  }


11050 11051
  nxinfo << "Loop: smb port: '" << smbPort
         << "'.\n" << std::flush;
11052

11053 11054 11055 11056 11057
  if ( mediaPort.configured() ) {
    if (control -> ProxyMode == proxy_client) {
      mediaPort.setDefaultTCPPort(DEFAULT_NX_MEDIA_PORT_OFFSET + proxyPort);
      useMediaSocket = mediaPort.enabled();
    } else {
11058

11059
      if ( mediaPort.getTCPPort() < 0 ) {
11060 11061
        nxfatal << "Loop: PANIC! No port specified for multimedia connections.\n"
                << std::flush;
11062

11063
        cerr << "Error" << ": No port specified for multimedia connections.\n";
11064

11065 11066
        HandleCleanup();
      }
11067 11068 11069
    }
  }

11070
  nxinfo << "Loop: Using multimedia port '" << mediaPort
11071
         << "'.\n" << std::flush;
11072

11073
  if (control -> ProxyMode == proxy_client) {
11074
      httpPort.setDefaultTCPPort(DEFAULT_NX_HTTP_PORT_OFFSET + proxyPort);
11075 11076
      useHttpSocket = httpPort.enabled();
  } else {
11077
      httpPort.setDefaultTCPPort(80);
11078 11079
  }

11080
  nxinfo << "Loop: Using HTTP port '" << httpPort
11081
         << "'.\n" << std::flush;
11082

11083 11084
  if (ParseFontPath(fontPort) <= 0)
  {
11085
    nxinfo << "Loop: Disabling font server connections.\n"
11086
           << std::flush;
11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109

    *fontPort = '\0';

    useFontSocket = 0;
  }
  else
  {
    //
    // We don't know yet if the remote proxy supports
    // the font server connections. If needed, we will
    // disable the font server connections at later
    // time.
    //

    if (control -> ProxyMode == proxy_server)
    {
      useFontSocket = 1;
    }
    else
    {
      useFontSocket = 0;
    }

11110
    nxinfo << "Loop: Using font server port '" << fontPort
11111
           << "'.\n" << std::flush;
11112 11113
  }

11114 11115 11116 11117 11118
  if (control -> ProxyMode == proxy_client) {
    slavePort.setDefaultTCPPort(DEFAULT_NX_SLAVE_PORT_CLIENT_OFFSET + proxyPort);
    useSlaveSocket = slavePort.enabled();
  } else {
    slavePort.setDefaultTCPPort(DEFAULT_NX_SLAVE_PORT_SERVER_OFFSET + proxyPort);
11119 11120
  }

11121
  nxinfo << "Loop: Using slave port '" << slavePort
11122
         << "'.\n" << std::flush;
11123

11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179
  return 1;
}

int SetDescriptors()
{
  unsigned int limit = 0;

  #ifdef RLIMIT_NOFILE

  rlimit limits;

  if (getrlimit(RLIMIT_NOFILE, &limits) == 0)
  {
    if (limits.rlim_max == RLIM_INFINITY)
    {
      limit = 0;
    }
    else
    {
      limit = (unsigned int) limits.rlim_max;
    }
  }

  #endif

  #ifdef _SC_OPEN_MAX

  if (limit == 0)
  {
    limit = sysconf(_SC_OPEN_MAX);
  }

  #endif

  #ifdef FD_SETSIZE

  if (limit > FD_SETSIZE)
  {
    limit = FD_SETSIZE;
  }

  #endif

  #ifdef RLIMIT_NOFILE

  if (limits.rlim_cur < limit)
  {
    limits.rlim_cur = limit;

    setrlimit(RLIMIT_NOFILE, &limits);
  }

  #endif

  if (limit == 0)
  {
11180 11181
    nxfatal << "Loop: PANIC! Cannot determine number of available "
            << "file descriptors.\n" << std::flush;
11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200

    cerr << "Error" << ": Cannot determine number of available "
         << "file descriptors.\n";

    return -1;
  }

  return 1;
}

//
// Find the directory containing the caches
// matching the session type.
//

int SetCaches()
{
  if ((control -> PersistentCachePath = GetCachePath()) == NULL)
  {
11201 11202
    nxfatal << "Loop: PANIC! Error getting or creating the cache path.\n"
            << std::flush;
11203 11204 11205 11206 11207 11208

    cerr << "Error" << ": Error getting or creating the cache path.\n";

    HandleCleanup();
  }

11209
  nxinfo << "Loop: Path of cache files is '" << control -> PersistentCachePath
11210
         << "'.\n" << std::flush;
11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325

  return 1;
}

//
// Initialize all configuration parameters.
//

int SetParameters()
{
  //
  // Find out the type of session.
  //

  SetSession();

  //
  // Initialize the network and compression
  // parameters according to the settings
  // suggested by the user.
  //

  SetLink();

  //
  // Set compression according to link speed.
  //

  SetCompression();

  //
  // Be sure that we have a literal for current
  // cache size. Value will reflect control's
  // default unless we already parsed a 'cache'
  // option. Server side has no control on size
  // of cache but is informed at session nego-
  // tiation about how much memory is going to
  // be used.
  //

  SetStorage();

  //
  // Set size of shared memory segments.
  //

  SetShmem();

  //
  // Make adjustments to cache based
  // on the pack method.
  //

  SetPack();

  //
  // Set disk-based image cache.
  //

  SetImages();

  //
  // Set CPU and bandwidth limits.
  //

  SetLimits();

  return 1;
}

//
// According to session literal determine
// the type of traffic that is going to be
// transported. Literals should be better
// standardized in future NX versions.
//

int SetSession()
{
  if (strncmp(sessionType, "agent", strlen("agent")) == 0 ||
          strncmp(sessionType, "desktop", strlen("desktop")) == 0 ||
              strncmp(sessionType, "rootless", strlen("rootless")) == 0 ||
                  strncmp(sessionType, "console", strlen("console")) == 0 ||
                      strncmp(sessionType, "default", strlen("default")) == 0 ||
                          strncmp(sessionType, "gnome", strlen("gnome")) == 0 ||
                              strncmp(sessionType, "kde", strlen("kde")) == 0 ||
                                  strncmp(sessionType, "cde", strlen("cde")) == 0 ||
                                      strncmp(sessionType, "xdm", strlen("xdm")) == 0)
  {
    control -> SessionMode = session_agent;
  }
  else if (strncmp(sessionType, "win", strlen("win")) == 0 ||
               strncmp(sessionType, "vnc", strlen("vnc")) == 0)
  {
    control -> SessionMode = session_agent;
  }
  else if (strncmp(sessionType, "shadow", strlen("shadow")) == 0)
  {
    control -> SessionMode = session_shadow;
  }
  else if (strncmp(sessionType, "proxy", strlen("proxy")) == 0 ||
               strncmp(sessionType, "application", strlen("application")) == 0 ||
                   strncmp(sessionType, "raw", strlen("raw")) == 0)
  {
    control -> SessionMode = session_proxy;
  }
  else
  {
    //
    // If the session type is not passed or
    // it is not among the recognized strings,
    // we assume that the proxy is connected
    // to the agent.
    //

11326 11327 11328 11329 11330 11331
    //
    // Since ProtoStep8 (#issue 108) and also
    // with older "unix-" sessions
    //

    if (*sessionType != '\0')
11332
    {
11333
      nxwarn << "Loop: WARNING! Unrecognized session type '"
11334 11335
             << sessionType << "'. Assuming agent session.\n"
             << std::flush;
11336 11337 11338 11339 11340 11341 11342 11343

      cerr << "Warning" << ": Unrecognized session type '"
           << sessionType << "'. Assuming agent session.\n";
    }

    control -> SessionMode = session_agent;
  }

11344
  nxinfo << "Loop: Assuming session type '"
11345 11346 11347
         << DumpSession(control -> SessionMode) << "' with "
         << "string '" << sessionType << "'.\n"
         << std::flush;
11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366

  //
  // By default the policy is immediate. Agents
  // will set a different policy, if they like.
  // Anyway we need to check if the user has
  // provided a custom flush policy.
  //

  if (usePolicy != -1)
  {
    if (usePolicy > 0)
    {
      control -> FlushPolicy = policy_deferred;
    }
    else
    {
      control -> FlushPolicy = policy_immediate;
    }

11367
    nxinfo << "Loop: WARNING! Forcing flush policy to '"
11368 11369
           << DumpPolicy(control -> FlushPolicy)
           << ".\n" << std::flush;
11370 11371 11372 11373 11374
  }
  else
  {
    control -> FlushPolicy = policy_immediate;

11375
    nxinfo << "Loop: Setting initial flush policy to '"
11376 11377
           << DumpPolicy(control -> FlushPolicy)
           << "'.\n" << std::flush;
11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399
  }

  //
  // Check if the proxy library is run inside
  // another program providing encryption, as
  // it is the case of the SSH client.
  //

  if (useEncryption != -1)
  {
    if (useEncryption > 0)
    {
      control -> LinkEncrypted = 1;
    }
    else
    {
      control -> LinkEncrypted = 0;
    }
  }

  if (control -> LinkEncrypted == 1)
  {
11400
    nxinfo << "Loop: Proxy running as part of an "
11401 11402
           << "encrypting client.\n"
           << std::flush;
11403 11404 11405
  }
  else
  {
11406
    nxinfo << "Loop: Assuming proxy running as a "
11407 11408
           << "standalone program.\n"
           << std::flush;
11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429
  }

  //
  // Check if the system administrator has
  // enabled the respawn of the client at
  // the end of session.
  //

  if (control -> ProxyMode == proxy_server)
  {
    struct stat fileStat;

    char fileName[DEFAULT_STRING_LENGTH];

    snprintf(fileName, DEFAULT_STRING_LENGTH - 1,
                 "%s/share/noexit", control -> SystemPath);

    *(fileName + DEFAULT_STRING_LENGTH - 1) = '\0';

    if (stat(fileName, &fileStat) == 0)
    {
11430
      nxinfo << "Loop: Enabling respawn of client at session shutdown.\n"
11431
             << std::flush;
11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484

      control -> EnableRestartOnShutdown = 1;
    }
  }

  return 1;
}

int SetStorage()
{
  //
  // If differential compression is disabled
  // we don't need a cache at all.
  //

  if (control -> LocalDeltaCompression == 0)
  {
    control -> ClientTotalStorageSize = 0;
    control -> ServerTotalStorageSize = 0;
  }

  //
  // Set a a cache size literal.
  //

  int size = control -> getUpperStorageSize();

  if (size / 1024 > 0)
  {
    sprintf(cacheSizeName, "%dk", size / 1024);
  }
  else
  { 
    sprintf(cacheSizeName, "%d", size);
  }

  if (control -> ProxyMode == proxy_client)
  {
    control -> LocalTotalStorageSize =
        control -> ClientTotalStorageSize;

    control -> RemoteTotalStorageSize =
        control -> ServerTotalStorageSize;
  }
  else
  {
    control -> LocalTotalStorageSize =
        control -> ServerTotalStorageSize;

    control -> RemoteTotalStorageSize =
        control -> ClientTotalStorageSize;
  }

11485
  nxdbg << "Loop: Storage size limit is "
11486 11487 11488 11489 11490
        << control -> ClientTotalStorageSize
        << " at client and "
        << control -> ServerTotalStorageSize
        << " at server.\n"
        << std::flush;
11491

11492
  nxdbg << "Loop: Storage local limit set to "
11493 11494 11495 11496
        << control -> LocalTotalStorageSize
        << " remote limit set to "
        << control -> RemoteTotalStorageSize
        << ".\n" << std::flush;
11497 11498 11499 11500 11501 11502 11503 11504 11505

  //
  // Never reserve for split store more than
  // half the memory available for messages.
  //

  if (size > 0 && control ->
          SplitTotalStorageSize > size / 2)
  {
11506
    nxinfo << "Loop: Reducing size of split store to "
11507 11508
           << size / 2 << " bytes.\n"
           << std::flush;
11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520

    control -> SplitTotalStorageSize = size / 2;
  }

  //
  // Don't load render from persistent
  // cache if extension is hidden or
  // not supported by agent.
  //

  if (control -> HideRender == 1)
  {
11521
    nxinfo << "Loop: Not loading render extension "
11522 11523
           << "from persistent cache.\n"
           << std::flush;
11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591

    control -> PersistentCacheLoadRender = 0;
  }

  return 1;
}

int SetShmem()
{
  //
  // If not set, adjust the size of the shared
  // memory segment according to size of the
  // message cache.
  //

  if (*shsegSizeName == '\0')
  {
    int size = control -> getUpperStorageSize();

    const int mega = 1048576;

    if (size > 0)
    {
      if (size <= 1 * mega)
      {
        size = 0;
      }
      else if (size <= 2 * mega)
      {
        size = 524288;
      }
      else if (size < 4 * mega)
      {
        size = 1048576;
      }
      else
      {
        size = size / 4;
      }

      if (size > 4194304)
      {
        size = 4194304;
      }

      control -> ShmemClientSize = size;
      control -> ShmemServerSize = size;
    }
    else
    {
      //
      // The delta compression is disabled.
      // Use a default segment size of 2 MB.
      //

      control -> ShmemServerSize = 2 * mega;
    }
  }

  //
  // Client side shared memory support is
  // not useful and not implemented.
  //

  if (control -> ShmemServerSize >= 524288)
  {
    control -> ShmemServer = 1;

11592
    nxinfo << "Loop: Set initial shared memory size "
11593 11594
           << "to " << control -> ShmemServerSize
           << " bytes.\n" << std::flush;
11595 11596 11597
  }
  else
  {
11598
    nxinfo << "Loop: Disabled use of the shared memory "
11599
           << "extension.\n" << std::flush;
11600 11601 11602 11603

    control -> ShmemServer = 0;
  }

11604 11605 11606 11607
  // For android, no shared memory available
  control -> ShmemServer = 0;
  control -> ShmemClientSize = 0;

11608 11609 11610 11611 11612 11613 11614 11615 11616 11617
  return 1;
}

//
// Adjust the pack method according to the
// type of the session.
//

int SetPack()
{
11618
  nxinfo << "Loop: Setting pack with initial method "
11619 11620
         << packMethod << " and quality " << packQuality
         << ".\n" << std::flush;
11621 11622 11623 11624 11625 11626 11627 11628 11629 11630

  //
  // Check if this is a proxy session and, in
  // this case, set the pack method to none.
  // Packed images are not supported by plain
  // X applications.
  //

  if (control -> SessionMode == session_proxy)
  {
11631
    nxinfo << "Loop: WARNING! Disabling pack with proxy session.\n"
11632
           << std::flush;
11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652

    packMethod = PACK_NONE;
  }

  //
  // Adjust the internal settings according
  // to the newly selected pack method.
  //

  ParsePackMethod(packMethod, packQuality);

  //
  // Don't load messages from persistent
  // cache if packed images are disabled.
  //

  if (control -> PackMethod == PACK_NONE)
  {
    control -> PersistentCacheLoadPacked = 0;

11653
    nxinfo << "Loop: Not loading packed images "
11654 11655
           << "from persistent cache.\n"
           << std::flush;
11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674
  }

  return 1;
}

//
// Set the disk-based image cache parameters
// according to the user's wishes.
//

int SetImages()
{
  //
  // Be sure we disable the image cache if we
  // are connecting to plain X clients.
  //

  if (control -> SessionMode == session_proxy)
  {
11675
    nxinfo << "Loop: Disabling image cache with "
11676 11677
           << "session '" << DumpSession(control ->
              SessionMode) << "'.\n" << std::flush;
11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706

    sprintf(imagesSizeName, "0");

    control -> ImageCacheEnableLoad = 0;
    control -> ImageCacheEnableSave = 0;

    return 1;
  }

  int size = control -> ImageCacheDiskLimit;

  if (size / 1024 > 0)
  {
    sprintf(imagesSizeName, "%dk", size / 1024);
  }
  else
  {
    sprintf(imagesSizeName, "%d", size);
  }

  if (size > 0)
  {
    control -> ImageCacheEnableLoad = 1;
    control -> ImageCacheEnableSave = 1;

    if (control -> ProxyMode == proxy_server)
    {
      if ((control -> ImageCachePath = GetImagesPath()) == NULL)
      {
11707 11708
        nxfatal << "Loop: PANIC! Error getting or creating image cache path.\n"
                << std::flush;
11709 11710 11711 11712 11713 11714

        cerr << "Error" << ": Error getting or creating image cache path.\n";

        HandleCleanup();
      }

11715
      nxinfo << "Loop: Path of image cache files is '" << control -> ImageCachePath
11716
             << "'.\n" << std::flush;
11717 11718 11719 11720
    }
  }
  else
  {
11721
    nxinfo << "Loop: Disabling the persistent image cache.\n"
11722
           << std::flush;
11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761

    control -> ImageCacheEnableLoad = 0;
    control -> ImageCacheEnableSave = 0;
  }

  return 1;
}

int SetVersion()
{
  //
  // Normalize the different proxy versions.
  //

  int local = (control -> LocalVersionMajor << 24) |
                  (control -> LocalVersionMinor << 16) |
                      control -> LocalVersionPatch;

  int remote = (control -> RemoteVersionMajor << 24) |
                   (control -> RemoteVersionMinor << 16) |
                       control -> RemoteVersionPatch;

  int major = -1;
  int minor = -1;
  int patch = -1;

  if (control -> RemoteVersionMajor <= 1)
  {
    //
    // The remote proxy uses a different
    // logic to determine the version so
    // we default to the compatibility
    // version.
    //

    major = control -> CompatVersionMajor;
    minor = control -> CompatVersionMinor;
    patch = control -> CompatVersionPatch;

11762
    nxinfo << "Loop: Using compatibility version '"
11763 11764
           << major << "." << minor << "." << patch
           << "'.\n" << std::flush;
11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778
  }
  else if (control -> LocalVersionMajor >
               control -> RemoteVersionMajor)
  {
    //
    // We use a more recent version. Let's
    // negotiate the version based on the
    // version supported by the remote.
    //

    major = control -> RemoteVersionMajor;
    minor = control -> RemoteVersionMinor;
    patch = control -> RemoteVersionPatch;

11779
    nxinfo << "Loop: Using remote version '"
11780 11781
           << major << "." << minor << "." << patch
           << "'.\n" << std::flush;
11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798
  }
  else
  {
    //
    // We support a major version that is
    // equal or older than the remote. We
    // assume the smaller version between
    // the two, including the minor and
    // the patch numbers.
    //

    if (local > remote)
    {
      major = control -> RemoteVersionMajor;
      minor = control -> RemoteVersionMinor;
      patch = control -> RemoteVersionPatch;

11799
      nxinfo << "Loop: Using remote version '"
11800 11801
             << major << "." << minor << "." << patch
             << "'.\n" << std::flush;
11802 11803 11804 11805 11806 11807 11808
    }
    else
    {
      major = control -> LocalVersionMajor;
      minor = control -> LocalVersionMinor;
      patch = control -> LocalVersionPatch;

11809
      nxinfo << "Loop: Using local version '"
11810 11811
             << major << "." << minor << "." << patch
             << "'.\n" << std::flush;
11812 11813 11814 11815
    }
  }

  //
11816 11817
  // Handle versions from 3.5.0. The protocol
  // step 10 is the minimum supported version.
11818 11819 11820 11821
  //

  int step = 0;

11822
  if (major == 3)
11823
  {
11824
    if (minor >= 5)
11825 11826 11827
    {
      step = 10;
    }
11828
  }
11829 11830 11831 11832
  else if (major > 3)
  {
    step = 10;
  }
11833 11834 11835

  if (step == 0)
  {
11836
    nxfatal << "Loop: PANIC! Unable to set the protocol step value from "
11837 11838
            << "the negotiated protocol version " << major << "." << minor
            << "." << patch << ".\n" << std::flush;
11839 11840 11841 11842 11843

    cerr << "Error" << ": Unable to set the protocol step value from "
         << "the negotiated protocol version " << major << "." << minor
         << "." << patch << ".\n";

11844
    nxfatal << "Loop: PANIC! Incompatible remote version "
11845 11846 11847
            << control -> RemoteVersionMajor << "." << control -> RemoteVersionMinor
            << "." << control -> RemoteVersionPatch << " with local version "
            << control -> LocalVersionMajor << "." << control -> LocalVersionMinor
11848
            << "." << control -> LocalVersionPatch << ".\n" << std::flush;
11849 11850 11851 11852 11853 11854 11855 11856 11857 11858

    cerr << "Error" << ": Incompatible remote version "
         << control -> RemoteVersionMajor << "." << control -> RemoteVersionMinor
         << "." << control -> RemoteVersionPatch << " with local version "
         << control -> LocalVersionMajor << "." << control -> LocalVersionMinor
         << "." << control -> LocalVersionPatch << ".\n";

    return -1;
  }

11859
  nxinfo << "Loop: Using NX protocol step "
11860
         << step << ".\n" << std::flush;
11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875

  control -> setProtoStep(step);

  //
  // Ignore the differences in patch version
  // and print a warning if the local version
  // is different or obsolete compared to
  // the remote.
  //

  local  &= 0xffff0000;
  remote &= 0xffff0000;

  if (local != remote)
  {
11876
    nxwarn << "Loop: WARNING! Connected to remote version "
11877 11878 11879 11880
           << control -> RemoteVersionMajor << "." << control -> RemoteVersionMinor
           << "." << control -> RemoteVersionPatch << " with local version "
           << control -> LocalVersionMajor << "." << control -> LocalVersionMinor
           << "." << control -> LocalVersionPatch << ".\n" << std::flush;
11881 11882 11883 11884 11885 11886 11887 11888 11889 11890

    cerr << "Warning" << ": Connected to remote version "
         << control -> RemoteVersionMajor << "." << control -> RemoteVersionMinor
         << "." << control -> RemoteVersionPatch << " with local version "
         << control -> LocalVersionMajor << "." << control -> LocalVersionMinor
         << "." << control -> LocalVersionPatch << ".\n" << logofs_flush;
  }

  if (local < remote)
  {
11891
    nxerr << "Warning" << ": Consider checking https://github.com/ArcticaProject/nx-libs/releases for updates.\n";
11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902
  }

  //
  // Now that we are aware of the remote
  // version, let's adjust the options to
  // be compatible with the remote proxy.
  //

  if (control -> ProxyMode == proxy_client)
  {
    //
11903
    // Since ProtoStep8 (#issue 108)
11904
    //
11905 11906 11907
    // Now it's assumed that the remote is
    // able to handle the selected pack
    // method
11908 11909
    //

11910
    nxinfo << __FILE__ << " : " << __LINE__ << " - "
11911 11912 11913 11914
           << "step = " << control -> getProtoStep()
           << " packMethod = " << packMethod
           << " packQuality = " << packQuality
           << ".\n"  << std::flush;
11915 11916 11917 11918 11919 11920 11921 11922 11923 11924

    //
    // Update the pack method name.
    //

    ParsePackMethod(packMethod, packQuality);
  }

  //
  // At the moment the image cache is not used by the
11925 11926 11927 11928 11929 11930 11931
  // agent. Proxy versions older than 3.0.0 assumed
  // that it was enabled and sent specific bits as part
  // of the encoding. Conversely, it is advisable to
  // disable the cache right now. By not enabling the
  // the image cache, the house-keeping process will
  // only take care of cleaning up the "cache-" direc-
  // tories.
11932 11933
  //

11934 11935 11936 11937 11938
  //
  // Considering that compatibility with older versions
  // has been set to cover as far as 3.5.0, the cache can
  // be disabled at this point without any concern
  //
11939

11940
  // Since ProtoStep8 (#issue 108)
11941
  nxinfo << "Loop: Disabling image cache with protocol "
11942 11943
         << "step '" << control -> getProtoStep()
         << "'.\n"  << std::flush;
11944

11945 11946 11947 11948
  sprintf(imagesSizeName, "0");

  control -> ImageCacheEnableLoad = 0;
  control -> ImageCacheEnableSave = 0;
11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960

  return 1;
}

//
// Identify the requested link settings
// and update the control parameters
// accordingly.
//

int SetLink()
{
11961
  nxinfo << "Loop: Setting link with initial value "
11962
         << linkSpeedName << ".\n" << std::flush;
11963 11964 11965 11966 11967 11968

  if (*linkSpeedName == '\0')
  {
    strcpy(linkSpeedName, "lan");
  }
  
11969
  nxinfo << "Loop: Link speed is " << linkSpeedName
11970
         << ".\n" << std::flush;
11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023

  if (strcasecmp(linkSpeedName, "modem") == 0)
  {
    SetLinkModem();
  }
  else if (strcasecmp(linkSpeedName, "isdn") == 0)
  {
    SetLinkIsdn();
  }
  else if (strcasecmp(linkSpeedName, "adsl") == 0)
  {
    SetLinkAdsl();
  }
  else if (strcasecmp(linkSpeedName, "wan") == 0)
  {
    SetLinkWan();
  }
  else if (strcasecmp(linkSpeedName, "lan") == 0)
  {
    SetLinkLan();
  }
  else
  {
    return -1;
  }

  //
  // Set TCP_NODELAY according to the user's
  // wishes.
  //

  if (useNoDelay != -1)
  {
    control -> OptionProxyClientNoDelay = useNoDelay;
    control -> OptionProxyServerNoDelay = useNoDelay;
  }

  //
  // Select the image compression method.
  //

  if (packMethod == -1)
  {
    packMethod = control -> PackMethod;
  }

  if (packQuality == -1)
  {
    packQuality = control -> PackQuality;
  }

  if (ParsePackMethod(packMethod, packQuality) < 0)
  {
12024
    nxfatal << "Loop: PANIC! Unrecognized pack method id "
12025
            << packMethod << " with quality " << packQuality
12026
            << ".\n" << std::flush;
12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048

    cerr << "Error" << ": Unrecognized pack method id "
         << packMethod << " with quality " << packQuality
         << ".\n";

    HandleCleanup();
  }

  //
  // Check if the user disabled the ability
  // to generate simple replies at the client
  // side.
  //

  if (control -> SessionMode == session_proxy)
  {
    if (useTaint != -1)
    {
      control -> TaintReplies = (useTaint == 1);
    }
    else
    {
12049
      nxwarn << "Loop: WARNING! Forcing taint of replies "
12050 12051
             << "with a proxy session.\n"
             << std::flush;
12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074

      control -> TaintReplies = 1;
    }
  }
  else
  {
    //
    // There is no need to taint the
    // replies if we have an agent.
    //

    control -> TaintReplies = 0;
  }

  //
  // Be sure that the requests needing a reply
  // are flushed immediately. Normal X clients
  // use so many replies to make the queuing
  // completely useless.
  //

  if (control -> SessionMode == session_proxy)
  {
12075
    nxwarn << "Loop: WARNING! Forcing flush on priority "
12076 12077
           << "with a proxy session.\n"
           << std::flush;
12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090

    control -> FlushPriority = 1;
  }

  return 1;
}

//
// Parameters for MODEM 28.8/33.6/56 Kbps.
//

int SetLinkModem()
{
12091
  nxinfo << "Loop: Setting parameters for MODEM.\n"
12092
         << std::flush;
12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118

  control -> LinkMode = LINK_TYPE_MODEM;

  control -> TokenSize  = 256;
  control -> TokenLimit = 24;

  control -> SplitMode             = 1;
  control -> SplitTotalSize        = 128;
  control -> SplitTotalStorageSize = 1048576;

  control -> SplitTimeout   = 50;
  control -> MotionTimeout  = 50;
  control -> IdleTimeout    = 50;

  control -> PackMethod  = PACK_ADAPTIVE;
  control -> PackQuality = 3;

  return 1;
}

//
// Parameters for ISDN 64/128 Kbps.
//

int SetLinkIsdn()
{
12119
  nxinfo << "Loop: Setting parameters for ISDN.\n"
12120
         << std::flush;
12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132

  control -> LinkMode = LINK_TYPE_ISDN;

  control -> TokenSize  = 384;
  control -> TokenLimit = 24;

  control -> SplitMode             = 1;
  control -> SplitTotalSize        = 128;
  control -> SplitTotalStorageSize = 1048576;

  control -> SplitTimeout   = 50;
  control -> MotionTimeout  = 20;
12133
  control -> IdleTimeout    = 50;
12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146

  control -> PackMethod  = PACK_ADAPTIVE;
  control -> PackQuality = 5;

  return 1;
}

//
// Parameters for ADSL 256 Kbps.
//

int SetLinkAdsl()
{
12147
  nxinfo << "Loop: Setting parameters for ADSL.\n"
12148
         << std::flush;
12149 12150 12151

  control -> LinkMode = LINK_TYPE_ADSL;

12152
  control -> TokenSize  = 1408;
12153 12154 12155 12156 12157 12158 12159 12160
  control -> TokenLimit = 24;

  control -> SplitMode             = 1;
  control -> SplitTotalSize        = 128;
  control -> SplitTotalStorageSize = 1048576;

  control -> SplitTimeout   = 50;
  control -> MotionTimeout  = 10;
12161
  control -> IdleTimeout    = 50;
12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174

  control -> PackMethod  = PACK_ADAPTIVE;
  control -> PackQuality = 7;

  return 1;
}

//
// Parameters for XDSL/FDDI/ATM 1/2/34 Mbps WAN.
//

int SetLinkWan()
{
12175
  nxinfo << "Loop: Setting parameters for WAN.\n"
12176
         << std::flush;
12177 12178 12179

  control -> LinkMode = LINK_TYPE_WAN;

12180
  control -> TokenSize  = 1408;
12181 12182 12183 12184 12185 12186 12187 12188
  control -> TokenLimit = 24;

  control -> SplitMode             = 1;
  control -> SplitTotalSize        = 128;
  control -> SplitTotalStorageSize = 1048576;

  control -> SplitTimeout   = 50;
  control -> MotionTimeout  = 5;
12189
  control -> IdleTimeout    = 50;
12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202

  control -> PackMethod  = PACK_ADAPTIVE;
  control -> PackQuality = 9;

  return 1;
}

//
// Parameters for LAN 10/100 Mbps.
//

int SetLinkLan()
{
12203
  nxinfo << "Loop: Setting parameters for LAN.\n"
12204
         << std::flush;
12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216

  control -> LinkMode = LINK_TYPE_LAN;

  control -> TokenSize  = 1536;
  control -> TokenLimit = 24;

  control -> SplitMode             = 1;
  control -> SplitTotalSize        = 128;
  control -> SplitTotalStorageSize = 1048576;

  control -> SplitTimeout   = 50;
  control -> MotionTimeout  = 0;
12217
  control -> IdleTimeout    = 50;
12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460

  control -> PackMethod  = PACK_ADAPTIVE;
  control -> PackQuality = 9;

  return 1;
}

//
// Identify the requested link type and set
// the control parameters accordingly.
//

int SetCompression()
{
  if (strcasecmp(linkSpeedName, "modem") == 0)
  {
    SetCompressionModem();
  }
  else if (strcasecmp(linkSpeedName, "isdn") == 0)
  {
    SetCompressionIsdn();
  }
  else if (strcasecmp(linkSpeedName, "adsl") == 0)
  {
    SetCompressionAdsl();
  }
  else if (strcasecmp(linkSpeedName, "wan") == 0)
  {
    SetCompressionWan();
  }
  else if (strcasecmp(linkSpeedName, "lan") == 0)
  {
    SetCompressionLan();
  }
  else
  {
    return -1;
  }

  if (control -> LocalDeltaCompression < 0)
  {
    control -> LocalDeltaCompression = 1;
  }

  //
  // If we didn't set remote delta compression
  // (as it should always be the case at client
  // side) assume value of local side.
  //

  if (control -> RemoteDeltaCompression < 0)
  {
    control -> RemoteDeltaCompression =
        control -> LocalDeltaCompression;
  }

  //
  // If we didn't set remote compression levels
  // assume values of local side.
  //

  if (control -> RemoteStreamCompression < 0)
  {
    control -> RemoteStreamCompressionLevel =
        control -> LocalStreamCompressionLevel;

    if (control -> RemoteStreamCompressionLevel > 0)
    {
      control -> RemoteStreamCompression = 1;
    }
    else
    {
      control -> RemoteStreamCompression = 0;
    }
  }

  if (control -> RemoteDataCompression < 0)
  {
    control -> RemoteDataCompressionLevel =
        control -> LocalDataCompressionLevel;

    if (control -> RemoteDataCompressionLevel > 0)
    {
      control -> RemoteDataCompression = 1;
    }
    else
    {
      control -> RemoteDataCompression = 0;
    }
  }

  return 1;
}

//
// Compression for MODEM.
//

int SetCompressionModem()
{
  if (control -> LocalDataCompression < 0)
  {
    control -> LocalDataCompression      = 1;
    control -> LocalDataCompressionLevel = 1;
  }

  if (control -> LocalDataCompressionThreshold < 0)
  {
    control -> LocalDataCompressionThreshold = 32;
  }

  if (control -> LocalStreamCompression < 0)
  {
    control -> LocalStreamCompression      = 1;
    control -> LocalStreamCompressionLevel = 9;
  }

  return 1;
}

//
// Compression for ISDN.
//

int SetCompressionIsdn()
{
  if (control -> LocalDataCompression < 0)
  {
    control -> LocalDataCompression      = 1;
    control -> LocalDataCompressionLevel = 1;
  }

  if (control -> LocalDataCompressionThreshold < 0)
  {
    control -> LocalDataCompressionThreshold = 32;
  }

  if (control -> LocalStreamCompression < 0)
  {
    control -> LocalStreamCompression      = 1;
    control -> LocalStreamCompressionLevel = 6;
  }

  return 1;
}

//
// Compression for ADSL.
//

int SetCompressionAdsl()
{
  if (control -> LocalDataCompression < 0)
  {
    control -> LocalDataCompression      = 1;
    control -> LocalDataCompressionLevel = 1;
  }

  if (control -> LocalDataCompressionThreshold < 0)
  {
    control -> LocalDataCompressionThreshold = 32;
  }

  if (control -> LocalStreamCompression < 0)
  {
    control -> LocalStreamCompression      = 1;
    control -> LocalStreamCompressionLevel = 4;
  }

  return 1;
}

//
// Compression for WAN.
//

int SetCompressionWan()
{
  if (control -> LocalDataCompression < 0)
  {
    control -> LocalDataCompression      = 1;
    control -> LocalDataCompressionLevel = 1;
  }

  if (control -> LocalDataCompressionThreshold < 0)
  {
    control -> LocalDataCompressionThreshold = 32;
  }

  if (control -> LocalStreamCompression < 0)
  {
    control -> LocalStreamCompression      = 1;
    control -> LocalStreamCompressionLevel = 1;
  }

  return 1;
}

//
// Compression for LAN.
//

int SetCompressionLan()
{
  //
  // Disable delta compression if not
  // explicitly enabled.
  //

  if (control -> LocalDeltaCompression < 0)
  {
    control -> LocalDeltaCompression = 0;
  }

  if (control -> LocalDataCompression < 0)
  {
    control -> LocalDataCompression      = 0;
    control -> LocalDataCompressionLevel = 0;
  }

  if (control -> LocalDataCompressionThreshold < 0)
  {
    control -> LocalDataCompressionThreshold = 0;
  }

  if (control -> LocalStreamCompression < 0)
  {
    control -> LocalStreamCompression      = 0;
    control -> LocalStreamCompressionLevel = 0;
  }

  return 1;
}

int SetLimits()
{
  //
  // Check if the user requested strict
  // control flow parameters.
  //

  if (useStrict == 1)
  {
12461
    nxinfo << "Loop: LIMIT! Decreasing the token limit "
12462 12463 12464
           << "to " << control -> TokenLimit / 2
           << " with option 'strict'.\n"
           << std::flush;
12465 12466 12467 12468 12469 12470 12471 12472

    control -> TokenLimit /= 2;
  }

  #ifdef STRICT

  control -> TokenLimit = 1;

12473
  nxinfo << "Loop: WARNING! LIMIT! Setting the token limit "
12474 12475 12476
         << "to " << control -> TokenLimit
         << " to simulate the proxy congestion.\n"
         << std::flush;
12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507

  #endif

  //
  // Reduce the size of the log file.
  //

  #ifdef QUOTA

  control -> FileSizeLimit = 8388608;

  #endif

  //
  // Check the bitrate limits.
  //

  if (control -> LocalBitrateLimit == -1)
  {
    if (control -> ProxyMode == proxy_client)
    {
      control -> LocalBitrateLimit =
          control -> ClientBitrateLimit;
    }
    else
    {
      control -> LocalBitrateLimit =
          control -> ServerBitrateLimit;
    }
  }

12508
  nxinfo << "Loop: LIMIT! Setting client bitrate limit "
12509 12510 12511 12512 12513
         << "to " << control -> ClientBitrateLimit
         << " server bitrate limit to " << control ->
            ServerBitrateLimit << " with local limit "
         << control -> LocalBitrateLimit << ".\n"
         << std::flush;
12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529

  return 1;
}

//
// These functions are used to parse literal
// values provided by the user and set the
// control parameters accordingly.
//

int ParseCacheOption(const char *opt)
{
  int size = ParseArg("", "cache", opt);

  if (size < 0)
  {
12530
    nxfatal << "Loop: PANIC! Invalid value '"
12531
            << opt << "' for option 'cache'.\n"
12532
            << std::flush;
12533 12534 12535 12536 12537 12538 12539

    cerr << "Error" << ": Invalid value '"
         << opt << "' for option 'cache'.\n";

    return -1;
  }

12540
  nxinfo << "Loop: Setting size of cache to "
12541
         << size << " bytes.\n" << std::flush;
12542 12543 12544 12545 12546 12547 12548 12549

  control -> ClientTotalStorageSize = size;
  control -> ServerTotalStorageSize = size;

  strcpy(cacheSizeName, opt);

  if (size == 0)
  {
12550
    nxwarn << "Loop: WARNING! Disabling NX delta compression.\n"
12551
           << std::flush;
12552 12553 12554

    control -> LocalDeltaCompression = 0;

12555
    nxwarn << "Loop: WARNING! Disabling use of NX persistent cache.\n"
12556
           << std::flush;
12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570

    control -> PersistentCacheEnableLoad = 0;
    control -> PersistentCacheEnableSave = 0;
  }

  return 1;
}

int ParseImagesOption(const char *opt)
{
  int size = ParseArg("", "images", opt);

  if (size < 0)
  {
12571
    nxfatal << "Loop: PANIC! Invalid value '"
12572
            << opt << "' for option 'images'.\n"
12573
            << std::flush;
12574 12575 12576 12577 12578 12579 12580

    cerr << "Error" << ": Invalid value '"
         << opt << "' for option 'images'.\n";

    return -1;
  }

12581
  nxinfo << "Loop: Setting size of images cache to "
12582
         << size << " bytes.\n" << std::flush;
12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596

  control -> ImageCacheDiskLimit = size;

  strcpy(imagesSizeName, opt);

  return 1;
}

int ParseShmemOption(const char *opt)
{
  int size = ParseArg("", "shseg", opt);

  if (size < 0)
  {
12597
    nxfatal << "Loop: PANIC! Invalid value '"
12598
            << opt << "' for option 'shseg'.\n"
12599
            << std::flush;
12600 12601 12602 12603 12604 12605 12606 12607 12608 12609

    cerr << "Error" << ": Invalid value '"
         << opt << "' for option 'shseg'.\n";

    return -1;
  }

  control -> ShmemClientSize = size;
  control -> ShmemServerSize = size;

12610
  nxinfo << "Loop: Set shared memory size to "
12611 12612
         << control -> ShmemServerSize << " bytes.\n"
         << std::flush;
12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624

  strcpy(shsegSizeName, opt);

  return 1;
}

int ParseBitrateOption(const char *opt)
{
  int bitrate = ParseArg("", "limit", opt);

  if (bitrate < 0)
  {
12625
    nxfatal << "Loop: PANIC! Invalid value '"
12626
            << opt << "' for option 'limit'.\n"
12627
            << std::flush;
12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638

    cerr << "Error" << ": Invalid value '"
         << opt << "' for option 'limit'.\n";

    return -1;
  }

  strcpy(bitrateLimitName, opt);

  if (bitrate == 0)
  {
12639
    nxinfo << "Loop: Disabling bitrate limit on proxy link.\n"
12640
           << std::flush;
12641 12642 12643 12644 12645

    control -> LocalBitrateLimit = 0;
  }
  else
  {
12646
    nxinfo << "Loop: Setting bitrate to " << bitrate
12647
           << " bits per second.\n" << std::flush;
12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659

    //
    // Internal representation is in bytes
    // per second.
    //

    control -> LocalBitrateLimit = bitrate >> 3;
  }

  return 1;
}

12660
int ParseHostOption(const char *opt, char *host, long &port)
12661
{
12662
  nxinfo << "Loop: Trying to parse options string '" << opt
12663
         << "' as a remote NX host.\n" << std::flush;
12664 12665 12666

  if (opt == NULL || *opt == '\0')
  {
12667 12668
    nxfatal << "Loop: PANIC! No host parameter provided.\n"
            << std::flush;
12669 12670 12671 12672 12673

    return 0;
  }
  else if (strlen(opt) >= DEFAULT_STRING_LENGTH)
  {
12674
    nxfatal << "Loop: PANIC! Host parameter exceeds length of "
12675
            << DEFAULT_STRING_LENGTH << " characters.\n"
12676
            << std::flush;
12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687

    return 0;
  }

  //
  // Look for a host name followed
  // by a colon followed by port.
  //

  int newPort = port;

12688
  const char *separator = strrchr(opt, ':');
12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703

  if (separator != NULL)
  {
    const char *check = separator + 1;

    while (*check != '\0' && *check != ',' &&
               *check != '=' && isdigit(*check) != 0)
    {
      check++;
    }

    newPort = atoi(separator + 1);

    if (newPort < 0 || *check != '\0')
    {
12704
      nxinfo << "Loop: Can't identify remote NX port in string '"
12705
             << separator << "'.\n" << std::flush;
12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716

      return 0;
    }
  }
  else if (newPort < 0)
  {
    //
    // Complain if port was not passed
    // by other means.
    //

12717
    nxinfo << "Loop: Can't identify remote NX port in string '"
12718
           << opt << "'.\n" << std::flush;
12719 12720 12721 12722 12723 12724 12725 12726 12727 12728

    return 0;
  }
  else
  {
    separator = opt + strlen(opt);
  }

  char newHost[DEFAULT_STRING_LENGTH] = { 0 };

12729
  // opt cannot be longer than DEFAULT_STRING_LENGTH, this is checked above
12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743
  strncpy(newHost, opt, strlen(opt) - strlen(separator));

  *(newHost + strlen(opt) - strlen(separator)) = '\0';

  const char *check = newHost;

  while (*check != '\0' && *check != ',' &&
             *check != '=')
  {
    check++;
  }

  if (*check != '\0')
  {
12744
    nxinfo << "Loop: Can't identify remote NX host in string '"
12745
           << newHost << "'.\n" << std::flush;
12746 12747 12748 12749 12750

    return 0;
  }
  else if (*acceptHost != '\0')
  {
12751 12752
    nxfatal << "Loop: PANIC! Can't manage to connect and accept connections "
            << "at the same time.\n" << std::flush;
12753

12754 12755
    nxfatal << "Loop: PANIC! Refusing remote NX host with string '"
            << opt << "'.\n" << std::flush;
12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767

    cerr << "Error" << ": Can't manage to connect and accept connections "
         << "at the same time.\n";

    cerr << "Error" << ": Refusing remote NX host with string '"
         << opt << "'.\n";

    return -1;
  }

  if (*host != '\0' && strcmp(host, newHost) != 0)
  {
12768
    nxwarn << "Loop: WARNING! Overriding remote NX host '"
12769 12770
           << host << "' with new value '" << newHost
           << "'.\n" << std::flush;
12771 12772 12773 12774 12775 12776
  }

  strcpy(host, newHost);

  if (port != -1 && port != newPort)
  {
12777
    nxwarn << "Loop: WARNING! Overriding remote NX port '"
12778 12779
           << port << "' with new value '" << newPort
           << "'.\n" << std::flush;
12780 12781
  }

12782
  nxinfo << "Loop: Parsed options string '" << opt
12783 12784
         << "' with host '" << newHost << "' and port '"
         << newPort << "'.\n" << std::flush;
12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801

  port = newPort;

  return 1;
}

int ParseFontPath(char *path)
{
  char oldPath[DEFAULT_STRING_LENGTH];

  strcpy(oldPath, path);

  if (path == NULL || *path == '\0' || strcmp(path, "0") == 0)
  {
    return 0;
  }

12802
  nxinfo << "Loop: Parsing font server option '" << path
12803
         << "'.\n" << std::flush;
12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832

  //
  // Convert the value to our default port.
  //

  if (strcmp(fontPort, "1") == 0)
  {
    if (control -> ProxyMode == proxy_server)
    {
      snprintf(fontPort, DEFAULT_STRING_LENGTH - 1, "%d",
                   DEFAULT_NX_FONT_PORT_OFFSET + proxyPort);
    }
    else
    {
      //
      // Let the client use the well-known
      // "unix/:7100" font path.
      //

      snprintf(fontPort, DEFAULT_STRING_LENGTH - 1, "unix/:7100");
    }
  }

  //
  // Check if a simple numaric value was given.
  //

  if (atoi(path) > 0)
  {
12833
    nxinfo << "Loop: Assuming numeric TCP port '" << atoi(path)
12834
           << "' for font server.\n" << std::flush;
12835 12836 12837 12838 12839 12840

    return 1;
  }

  //
  // Let's assume that a port specification "unix/:7100"
12841 12842
  // corresponds to "/tmp/.font-unix/fs7100" and a port
  // "unix/:-1" corresponds to "/tmp/.font-unix/fs-1".
12843 12844 12845 12846
  //

  if (strncmp("unix/:", path, 6) == 0)
  {
12847 12848
    snprintf(path, DEFAULT_STRING_LENGTH - 1, "/tmp/.font-unix/fs%s",
                 oldPath + 6);
12849 12850 12851

    *(path + DEFAULT_STRING_LENGTH - 1) = '\0';

12852
    nxinfo << "Loop: Assuming Unix socket '" << path
12853
           << "' for font server.\n" << std::flush;
12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865
  }
  else if (strncmp("tcp/:", path, 5) == 0)
  {
    snprintf(path, DEFAULT_STRING_LENGTH - 1, "%d", atoi(oldPath + 5));

    *(path + DEFAULT_STRING_LENGTH - 1) = '\0';

    if (atoi(path) <= 0)
    {
      goto ParseFontPathError;
    }

12866
    nxinfo << "Loop: Assuming TCP port '" << atoi(path)
12867
           << "' for font server.\n" << std::flush;
12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880
  }
  else
  {
    //
    // Accept an absolute file path as
    // a valid Unix socket.
    //

    if (*path != '/')
    {
      goto ParseFontPathError;
    }

12881
    nxinfo << "Loop: Assuming Unix socket '" << path
12882
           << "' for font server.\n" << std::flush;
12883 12884 12885 12886 12887 12888
  }

  return 1;

ParseFontPathError:

12889
  nxinfo << "Loop: Unable to determine the font server "
12890 12891
         << "port in string '" << path << "'.\n"
         << std::flush;
12892 12893 12894 12895 12896 12897 12898 12899

  return -1;
}

int OpenLogFile(char *name, ostream *&stream)
{
  if (name == NULL || *name == '\0')
  {
12900
    nxinfo << "Loop: WARNING! No name provided for output. Using standard error.\n"
12901
           << std::flush;
12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918

    if (stream == NULL)
    {
      stream = &cerr;
    }

    return 1;
  }

  if (stream == NULL || stream == &cerr)
  {
    if (*name != '/' && *name != '.')
    {
      char *filePath = GetSessionPath();

      if (filePath == NULL)
      {
12919 12920
        nxfatal << "Loop: PANIC! Cannot determine directory of NX session file.\n"
                << std::flush;
12921 12922 12923 12924 12925 12926 12927 12928 12929

        cerr << "Error" << ": Cannot determine directory of NX session file.\n";

        return -1;
      }

      if (strlen(filePath) + strlen("/") +
              strlen(name) + 1 > DEFAULT_STRING_LENGTH)
      {
12930
        nxfatal << "Loop: PANIC! Full name of NX file '" << name
12931
                << " would exceed length of " << DEFAULT_STRING_LENGTH
12932
                << " characters.\n" << std::flush;
12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973

        cerr << "Error" << ": Full name of NX file '" << name
             << " would exceed length of " << DEFAULT_STRING_LENGTH
             << " characters.\n";

        return -1;
      }

      char *file = new char[strlen(filePath) + strlen("/") +
                                strlen(name) + 1];

      //
      // Transform name in a fully qualified name.
      //

      strcpy(file, filePath);
      strcat(file, "/");
      strcat(file, name);

      strcpy(name, file);

      delete [] filePath;
      delete [] file;
    }

    mode_t fileMode = umask(0077);

    for (;;)
    {
      if ((stream = new ofstream(name, ios::app)) != NULL)
      {
        break;
      }

      usleep(200000);
    }

    umask(fileMode);
  }
  else
  {
12974 12975
    nxfatal << "Loop: PANIC! Bad stream provided for output.\n"
            << std::flush;
12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999

    cerr << "Error" << ": Bad stream provided for output.\n";

    return -1;
  }

  return 1;
}

int ReopenLogFile(char *name, ostream *&stream, int limit)
{
  if (*name != '\0' && limit >= 0)
  {
    struct stat fileStat;

    if (limit > 0)
    {
      //
      // This is used for the log file, if the
      // size exceeds the limit.
      //

      if (stat(name, &fileStat) != 0)
      {
13000
        nxwarn << "Loop: WARNING! Can't get stats of file '"
13001 13002
               << name  << "'. Error is " << EGET()
               << " '" << ESTR() << "'.\n" << std::flush;
13003 13004 13005 13006 13007 13008 13009 13010 13011

        return 0;
      }
      else if (fileStat.st_size < (long) limit)
      {
        return 0;
      }
    }

13012
    nxinfo << "Loop: Deleting file '" << name
13013 13014
           << "' with size " << fileStat.st_size
           << ".\n" << std::flush;
13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039

    //
    // Create a new stream over the previous
    // file. Trying to delete the file fails
    // to work on recent Cygwin installs.
    //

    *stream << flush;

    delete stream;

    mode_t fileMode = umask(0077);

    for (;;)
    {
      if ((stream = new ofstream(name, ios::out)) != NULL)
      {
        break;
      }

      usleep(200000);
    }

    umask(fileMode);

13040
    nxinfo << "Loop: Reopened file '" << name
13041
           << "'.\n" << std::flush;
13042 13043 13044 13045 13046 13047 13048 13049 13050
  }

  return 1;
}

void PrintProcessInfo()
{
  if (agent == NULL)
  {
13051 13052 13053 13054 13055 13056

    cerr << endl;

    PrintVersionInfo();

    cerr << endl;
13057

13058
    cerr << GetCopyrightInfo()
13059
         << endl
13060
         << GetOtherCopyrightInfo()
13061 13062
         << endl
         << "See https://github.com/ArcticaProject/nx-libs for more information." << endl << endl;
13063 13064 13065 13066 13067 13068 13069 13070 13071 13072
  }

  //
  // People get confused by the fact that client
  // mode is running on NX server and viceversa.
  // Let's adopt an user-friendly naming conven-
  // tion here.
  //

  cerr << "Info: Proxy running in "
13073
       << (control -> ProxyMode == proxy_client ? "client" : "server")
13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084
       << " mode with pid '" << getpid() << "'.\n";

  if (agent == NULL)
  {
    cerr << "Session" << ": Starting session at '"
         << strTimestamp() << "'.\n";
  }


  if (*errorsFileName != '\0')
  {
13085 13086
    cerr << "Info" << ": Using errors file '" << errorsFileName << "'.\n";
  }
13087 13088 13089

  if (*statsFileName != '\0')
  {
13090 13091
    cerr << "Info" << ": Using stats file '" << statsFileName << "'.\n";
  }
13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211

}

void PrintConnectionInfo()
{
  cerr << "Info" << ": Using "
       << linkSpeedName << " link parameters "
       << control -> TokenSize
       << "/" << control -> TokenLimit
       << "/" << control -> FlushPolicy + 1
       << "/" << control -> FlushPriority
       << ".\n";

  if (control -> ProxyMode == proxy_client)
  {
    cerr << "Info" << ": Using agent parameters "
         << control -> PingTimeout
         << "/" << control -> MotionTimeout
         << "/" << control -> IdleTimeout
         << "/" << control -> TaintReplies
         << "/" << control -> HideRender
         << ".\n";
  }

  if (control -> LocalDeltaCompression == 1)
  {
    cerr << "Info" << ": Using cache parameters "
         << control -> MinimumMessageSize
         << "/" << control -> MaximumMessageSize / 1024 << "KB"
         << "/" << control -> ClientTotalStorageSize / 1024 << "KB"
         << "/" << control -> ServerTotalStorageSize / 1024 << "KB"
         << ".\n";
  }

  if (control -> ImageCacheEnableLoad == 1 ||
          control -> ImageCacheEnableSave == 1)
  {
    cerr << "Info" << ": Using image streaming parameters "
         << control -> SplitTimeout
         << "/" << control -> SplitTotalSize
         << "/" << control -> SplitTotalStorageSize / 1024 << "KB"
         << "/" << control -> SplitDataThreshold
         << "/" << control -> SplitDataPacketLimit
         << ".\n";

    cerr << "Info" << ": Using image cache parameters "
         << control -> ImageCacheEnableLoad
         << "/" << control -> ImageCacheEnableSave
         << "/" << control -> ImageCacheDiskLimit / 1024 << "KB"
         << ".\n";
  }

  cerr << "Info" << ": Using pack method '"
       << packMethodName << "' with session '"
       << sessionType << "'.\n";

  if (*productName != '\0')
  {
    cerr << "Info" << ": Using product '" << productName
         << "'.\n" << logofs_flush;
  }

  if (control -> LocalDeltaCompression == 0)
  {
    cerr << "Info" << ": Not using NX delta compression.\n";
  }

  if (control -> LocalDataCompression == 1 ||
          control -> RemoteDataCompression == 1)
  {
    cerr << "Info" << ": Using ZLIB data compression "
         << control -> LocalDataCompressionLevel
         << "/" << control -> RemoteDataCompressionLevel
         << "/" << control -> LocalDataCompressionThreshold
         << ".\n";
  }
  else
  {
    cerr << "Info" << ": Not using ZLIB data compression.\n";
  }

  if (control -> LocalStreamCompression == 1 ||
          control -> RemoteStreamCompression == 1)
  {
    cerr << "Info" << ": Using ZLIB stream compression "
         << control -> LocalStreamCompressionLevel
         << "/" << control -> RemoteStreamCompressionLevel
         << ".\n";
  }
  else
  {
    cerr << "Info" << ": Not using ZLIB stream compression.\n";
  }

  if (control -> LocalBitrateLimit > 0)
  {
    cerr << "Info" << ": Using bandwidth limit of "
         << bitrateLimitName << " bits per second.\n";
  }

  if (control -> PersistentCacheName != NULL)
  {
    cerr << "Info" << ": Using cache file '"
         << control -> PersistentCachePath << "/"
         << control -> PersistentCacheName << "'.\n";
  }
  else
  {
    if (control -> PersistentCacheEnableLoad == 0 ||
            control -> LocalDeltaCompression == 0)
    {
      cerr << "Info" << ": Not using a persistent cache.\n";
    }
    else
    {
      cerr << "Info" << ": No suitable cache file found.\n";
    }
  }

  if (control -> ProxyMode == proxy_client &&
13212 13213
          (useUnixSocket > 0 || useTcpSocket > 0 ||
              useAgentSocket > 0))
13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224
  {
    cerr << "Info" << ": Listening to X11 connections "
         << "on display ':" << xPort << "'.\n";
  }
  else if (control -> ProxyMode == proxy_server)
  {
    cerr << "Info" << ": Forwarding X11 connections "
         << "to display '" << displayHost << "'.\n";
  }

  if (control -> ProxyMode == proxy_client &&
13225
      useCupsSocket > 0 && cupsPort.enabled())
13226 13227 13228 13229 13230
  {
    cerr << "Info" << ": Listening to CUPS connections "
         << "on port '" << cupsPort << "'.\n";
  }
  else if (control -> ProxyMode == proxy_server &&
13231
           cupsPort.enabled())
13232 13233 13234 13235 13236 13237
  {
    cerr << "Info" << ": Forwarding CUPS connections "
         << "to port '" << cupsPort << "'.\n";
  }

  if (control -> ProxyMode == proxy_client &&
13238
      useAuxSocket > 0 && auxPort.enabled())
13239 13240 13241 13242 13243
  {
    cerr << "Info" << ": Listening to auxiliary X11 connections "
         << "on port '" << auxPort << "'.\n";
  }
  else if (control -> ProxyMode == proxy_server &&
13244
           auxPort.enabled())
13245 13246 13247 13248 13249 13250
  {
    cerr << "Info" << ": Forwarding auxiliary X11 connections "
         << "to display '" << displayHost << "'.\n";
  }

  if (control -> ProxyMode == proxy_client &&
13251
      useSmbSocket > 0 && smbPort.enabled())
13252 13253 13254 13255 13256
  {
    cerr << "Info" << ": Listening to SMB connections "
         << "on port '" << smbPort << "'.\n";
  }
  else if (control -> ProxyMode == proxy_server &&
13257
           smbPort.enabled())
13258 13259 13260 13261 13262 13263
  {
    cerr << "Info" << ": Forwarding SMB connections "
         << "to port '" << smbPort << "'.\n";
  }

  if (control -> ProxyMode == proxy_client &&
13264
      useMediaSocket > 0 && mediaPort.enabled())
13265 13266 13267 13268 13269
  {
    cerr << "Info" << ": Listening to multimedia connections "
         << "on port '" << mediaPort << "'.\n";
  }
  else if (control -> ProxyMode == proxy_server &&
13270
           mediaPort.enabled())
13271 13272 13273 13274 13275 13276
  {
    cerr << "Info" << ": Forwarding multimedia connections "
         << "to port '" << mediaPort << "'.\n";
  }

  if (control -> ProxyMode == proxy_client &&
13277
      useHttpSocket > 0 && httpPort.enabled())
13278 13279 13280 13281 13282
  {
    cerr << "Info" << ": Listening to HTTP connections "
         << "on port '" << httpPort << "'.\n";
  }
  else if (control -> ProxyMode == proxy_server &&
13283
           httpPort.enabled())
13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301
  {
    cerr << "Info" << ": Forwarding HTTP connections "
         << "to port '" << httpPort << "'.\n";
  }

  if (control -> ProxyMode == proxy_server &&
          useFontSocket > 0 && *fontPort != '\0')
  {
    cerr << "Info" << ": Listening to font server connections "
         << "on port '" << fontPort << "'.\n";
  }
  else if (control -> ProxyMode == proxy_client &&
               *fontPort != '\0')
  {
    cerr << "Info" << ": Forwarding font server connections "
         << "to port '" << fontPort << "'.\n";
  }

13302
  if (useSlaveSocket > 0 && slavePort.enabled())
13303 13304 13305 13306 13307 13308 13309 13310
  {
    cerr << "Info" << ": Listening to slave connections "
         << "on port '" << slavePort << "'.\n";
  }
}

void PrintVersionInfo()
{
13311 13312 13313 13314
  cerr << "NXPROXY - Version "
#ifdef NX_VERSION_CUSTOM
       << NX_VERSION_CUSTOM << " ("
#endif
13315 13316
       << control -> LocalVersionMajor << "."
       << control -> LocalVersionMinor << "."
13317
       << control -> LocalVersionPatch << "."
13318 13319 13320 13321 13322
       << control -> LocalVersionMaintenancePatch
#ifdef NX_VERSION_CUSTOM
       << ")"
#endif
       << endl;
13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349
}

void PrintCopyrightInfo()
{
  cerr << endl;

  PrintVersionInfo();

  cerr << endl;

  cerr << GetCopyrightInfo();

  //
  // Print third party's copyright info.
  //

  cerr << endl;

  cerr << GetOtherCopyrightInfo();

  cerr << endl;
}

void PrintOptionIgnored(const char *type, const char *name, const char *value)
{
  if (control -> ProxyMode == proxy_server)
  {
13350
    nxwarn << "Loop: WARNING! Ignoring " << type
13351 13352 13353
           << " option '" << name << "' with value '"
           << value << "' at " << "NX client side.\n"
           << std::flush;
13354 13355 13356 13357 13358 13359 13360

    cerr << "Warning" << ": Ignoring " << type
         << " option '" << name << "' with value '"
         << value << "' at " << "NX client side.\n";
  }
  else
  {
13361
    nxwarn << "Loop: WARNING! Ignoring " << type
13362 13363 13364
           << " option '" << name << "' with value '"
           << value << "' at " << "NX server side.\n"
           << std::flush;
13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379

    cerr << "Warning" << ": Ignoring " << type
         << " option '" << name << "' with value '"
         << value << "' at " << "NX server side.\n";
  }
}

const char *GetOptions(const char *options)
{
  if (options != NULL)
  {
    if (strncasecmp(options, "nx/nx,", 6) != 0 &&
            strncasecmp(options, "nx,", 3) != 0 &&
                strncasecmp(options, "nx:", 3) != 0)
    {
13380
      nxinfo << "Loop: PANIC! Display options string '" << options
13381 13382
             << "' must start with 'nx' or 'nx/nx' prefix.\n"
             << std::flush;
13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426

      cerr << "Error" << ": Display options string '" << options
           << "' must start with 'nx' or 'nx/nx' prefix.\n";

      HandleCleanup();
    }
  }
  else
  {
    options = getenv("DISPLAY");
  }

  return options;
}

const char *GetArg(int &argi, int argc, const char **argv)
{
  //
  // Skip "-" and flag character.
  //

  const char *arg = argv[argi] + 2;

  if (*arg == 0)
  {
    if (argi + 1 == argc)
    {
      return NULL;
    }
    else
    {
      argi++;

      return (*argv[argi] == '-' ? NULL : argv[argi]);
    }
  }
  else
  {
    return (*arg == '-' ? NULL : arg);
  }
}

int CheckArg(const char *type, const char *name, const char *value)
{
13427
  nxinfo << "Loop: Parsing " << type << " option '" << name
13428 13429
         << "' with value '" << (value ? value : "(null)")
         << "'.\n" << std::flush;
13430 13431 13432

  if (value == NULL || strstr(value, "=") != NULL)
  {
13433
    nxfatal << "Loop: PANIC! Error in " << type << " option '"
13434
            << name << "'. No value found.\n"
13435
            << std::flush;
13436 13437 13438 13439 13440 13441 13442 13443

    cerr << "Error" << ": Error in " << type << " option '"
         << name << "'. No value found.\n";

    return -1;
  }
  else if (strstr(name, ",") != NULL)
  {
13444 13445
    nxfatal << "Loop: PANIC! Parse error at " << type << " option '"
            << name << "'.\n" << std::flush;
13446 13447 13448 13449 13450 13451 13452 13453

    cerr << "Error" << ": Parse error at " << type << " option '"
         << name << "'.\n";

    return -1;
  }
  else if (strlen(value) >= DEFAULT_STRING_LENGTH)
  {
13454
    nxfatal << "Loop: PANIC! Value '" << value << "' of "
13455 13456
            << type << " option '" << name << "' exceeds length of "
            << DEFAULT_STRING_LENGTH << " characters.\n"
13457
            << std::flush;
13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506

    cerr << "Error" << ": Value '" << value << "' of "
         << type << " option '" << name << "' exceeds length of "
         << DEFAULT_STRING_LENGTH << " characters.\n";

    return -1;
  }

  return 1;
}

int ParseArg(const char *type, const char *name, const char *value)
{
  if (strcasecmp(value, "0") == 0)
  {
    return 0;
  }

  //
  // Find the base factor.
  //

  double base;

  const char *id = value + strlen(value) - 1;

  if (strcasecmp(id, "g") == 0)
  {
    base = 1024 * 1024 * 1024;
  }
  else if (strcasecmp(id, "m") == 0)
  {
    base = 1024 * 1024;
  }
  else if (strcasecmp(id, "k") == 0)
  {
    base = 1024;
  }
  else if (strcasecmp(id, "b") == 0 || isdigit(*id) == 1)
  {
    base = 1;
  }
  else
  {
    return -1;
  }

  char *string = new char[strlen(value)];

13507 13508
  // copy value but cut off the last character
  snprintf(string, strlen(value), "%s", value);
13509

13510 13511
  nxinfo << "Loop: Parsing integer option '" << name
         << "' from string '" << string << "' with base set to ";
13512 13513 13514 13515 13516 13517

  switch (tolower(*id))
  {
    case 'k':
    case 'm':
    case 'g':
13518
    {
13519
      nxinfo_append << (char) toupper(*id);
13520
      break;
13521 13522 13523
    }
  }

13524
  nxinfo_append << ".\n" << std::flush;
13525 13526 13527

  double result = atof(string) * base;

13528 13529
  delete [] string;

13530 13531 13532 13533 13534
  if (result < 0 || result > (((unsigned) -1) >> 1))
  {
    return -1;
  }

13535
  nxinfo << "Loop: Integer option parsed to '"
13536
         << (int) result << "'.\n" << std::flush;
13537 13538 13539 13540

  return (int) result;
}

13541 13542 13543 13544
void SetAndValidateChannelEndPointArg(const char *type, const char *name, const char *value,
                                      ChannelEndPoint &endPoint) {
  endPoint.setSpec(value);
  if (!endPoint.validateSpec()) {
13545
    nxfatal << "Loop: PANIC! Invalid " << type
13546
            << " option '" << name << "' with value '"
13547
            << value << "'.\n" << std::flush;
13548 13549 13550 13551 13552 13553 13554 13555 13556 13557

    cerr << "Error" << ": Invalid " << type
         << " option '" << name << "' with value '"
         << value << "'.\n";

    HandleCleanup();
  }
}


13558 13559 13560 13561 13562 13563
int ValidateArg(const char *type, const char *name, const char *value)
{
  int number = atoi(value);

  if (number < 0)
  {
13564
    nxfatal << "Loop: PANIC! Invalid " << type
13565
            << " option '" << name << "' with value '"
13566
            << value << "'.\n" << std::flush;
13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670

    cerr << "Error" << ": Invalid " << type
         << " option '" << name << "' with value '"
         << value << "'.\n";

    HandleCleanup();
  }

  return number;
} 

int LowercaseArg(const char *type, const char *name, char *value)
{
  char *next = value;

  while (*next != '\0')
  {
    *next = tolower(*next);

    next++;
  }

  return 1;
}

int CheckSignal(int signal)
{
  //
  // Return 1 if the signal needs to be handled
  // by the proxy, 2 if the signal just needs to
  // be blocked to avoid interrupting a system
  // call.
  //

  switch (signal)
  {
    case SIGCHLD:
    case SIGUSR1:
    case SIGUSR2:
    case SIGHUP:
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGALRM:
    {
      return 1;
    }
    case SIGVTALRM:
    case SIGWINCH:
    case SIGIO:
    case SIGTSTP:
    case SIGTTIN:
    case SIGTTOU:
    {
      return 2;
    }
    default:
    {
      #ifdef __CYGWIN32__

      //
      // This signal can be raised by the Cygwin
      // library.
      //

      if (signal == 12)
      {
        return 1;
      }

      #endif

      return 0;
    }
  }
}

static void PrintUsageInfo(const char *option, int error)
{
  if (error == 1)
  {
    cerr << "Error" << ": Invalid command line option '" << option << "'.\n";
  }

  cerr << GetUsageInfo();

  if (error == 1)
  {
    cerr << "Error" << ": NX transport initialization failed.\n";
  }
}

static void handleCheckSessionInLoop()
{
  //
  // Check if we completed the shutdown procedure
  // and the remote confirmed the shutdown. The
  // tear down should be always initiated by the
  // agent, but the X server side may unilateral-
  // ly shut down the link without our permission.
  //

  if (proxy -> getShutdown() > 0)
  {
13671
    nxinfo << "Loop: End of NX transport requested "
13672
           << "by remote.\n" << std::flush;
13673 13674 13675 13676 13677

    handleTerminatingInLoop();

    if (control -> ProxyMode == proxy_server)
    {
13678
      nxinfo << "Loop: Bytes received so far are "
13679 13680
             << (unsigned long long) statistics -> getBytesIn()
             << ".\n" << std::flush;
13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692

      if (statistics -> getBytesIn() < 1024)
      {
        cerr << "Info" << ": Your session was closed before reaching "
             << "a usable state.\n";
        cerr << "Info" << ": This can be due to the local X server "
             << "refusing access to the client.\n";
        cerr << "Info" << ": Please check authorization provided "
             << "by the remote X application.\n";
      }
    }

13693
    nxinfo << "Loop: Shutting down the NX transport.\n"
13694
           << std::flush;
13695

13696 13697 13698 13699
    HandleCleanup();
  }
  else if (proxy -> handlePing() < 0)
  {
13700
    nxinfo << "Loop: Failure handling the ping for "
13701 13702
           << "proxy FD#" << proxyFD << ".\n"
           << std::flush;
13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714

    HandleShutdown();
  }

  //
  // Check if the watchdog has exited and we didn't
  // get the SIGCHLD. This can happen if the parent
  // has overridden our signal handlers.
  //

  if (IsRunning(lastWatchdog) && CheckProcess(lastWatchdog, "watchdog") == 0)
  {
13715
    nxwarn << "Loop: WARNING! Watchdog is gone unnoticed. "
13716 13717
           << "Setting the last signal to SIGTERM.\n"
           << std::flush;
13718 13719 13720

    lastSignal = SIGTERM;

13721
    nxwarn << "Loop: WARNING! Resetting pid of last "
13722
           << "watchdog process.\n" << std::flush;
13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739

    SetNotRunning(lastWatchdog);
  }

  //
  // Let the client proxy find out if the agent's
  // channel is gone. This is the normal shutdown
  // procedure in the case of an internal connect-
  // ion to the agent.
  // 

  int cleanup = 0;

  if (control -> ProxyMode == proxy_client &&
          agent != NULL && proxy -> getType(agentFD[1]) ==
              channel_none && lastKill == 0 && lastDestroy == 1)
  {
13740
    nxinfo << "Loop: End of NX transport requested "
13741
           << "by agent.\n" << std::flush;
13742

13743
    nxinfo << "Loop: Bytes sent so far are "
13744 13745
           << (unsigned long long) statistics -> getBytesOut()
           << ".\n" << std::flush;
13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809

    if (statistics -> getBytesOut() < 1024)
    {
      cerr << "Info" << ": Your session has died before reaching "
           << "an usable state.\n";
      cerr << "Info" << ": This can be due to the remote X server "
           << "refusing access to the client.\n";
      cerr << "Info" << ": Please check the authorization provided "
           << "by your X application.\n";
    }

    cleanup = 1;
  }

  //
  // Check if the user requested the end of the
  // session by sending a signal to the proxy.
  // All signals are handled in the main loop
  // so we need to reset the value to get ready
  // for the next iteration.
  //

  int signal = 0;

  if (lastSignal != 0)
  {
    switch (lastSignal)
    {
      case SIGCHLD:
      case SIGUSR1:
      case SIGUSR2:
      {
        break;
      }
      default:
      {
        signal = lastSignal;

        cleanup = 1;

        break;
      }
    }

    lastSignal = 0;
  }

  if (cleanup == 1)
  {
    //
    // The first time termination signal is received
    // disable all further connections, close down any
    // X channel and wait for a second signal.
    //

    if (lastKill == 0)
    {
      //
      // Don't print a message if cleanup is
      // due to normal termination of agent.
      //

      if (signal != 0)
      {
13810
        nxinfo << "Loop: End of NX transport requested by signal '"
13811 13812
               << signal << "' '" << DumpSignal(signal)
               << "'.\n" << std::flush;
13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840

        handleTerminatingInLoop();
      }

      //
      // Disable any further connection.
      //

      CleanupListeners();

      //
      // Close all the remaining X channels and
      // let proxies save their persistent cache
      // on disk.
      //

      CleanupConnections();

      //
      // We'll need to wait for the X channels
      // to be shut down before waiting for the
      // cleanup signal.
      //

      lastKill = 1;
    }
    else if (lastKill == 2)
    {
13841
      nxinfo << "Loop: Shutting down the NX transport.\n"
13842
             << std::flush;
13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874

      proxy -> handleShutdown();

      HandleCleanup();
    }
  }

  if (lastKill == 1 && proxy -> getChannels(channel_x11) == 0)
  {
    //
    // Save the message stores to the
    // persistent cache.
    //

    proxy -> handleSave();

    //
    // Run a watchdog process so we can finally
    // give up at the time the watchdog exits.
    //

    if (IsNotRunning(lastWatchdog))
    {
      int timeout = control -> CleanupTimeout;

      if (timeout > 0)
      {
        if (proxy -> getChannels() == 0)
        {
          timeout = 500;
        }

13875
        nxinfo << "Loop: Starting watchdog process with timeout "
13876
               << "of " << timeout << " ms.\n"
13877
               << std::flush;
13878 13879 13880
      }
      else
      {
13881
        nxinfo << "Loop: Starting watchdog process without "
13882
               << "a timeout.\n" << std::flush;
13883 13884 13885 13886 13887 13888
      }

      lastWatchdog = NXTransWatchdog(timeout);

      if (IsFailed(lastWatchdog))
      {
13889 13890
        nxfatal << "Loop: PANIC! Can't start the NX watchdog "
                << "process in shutdown.\n" << std::flush;
13891 13892 13893 13894 13895 13896 13897 13898

        cerr << "Error" << ": Can't start the NX watchdog "
             << "process in shutdown.\n";

        HandleCleanup();
      }
      else
      {
13899
        nxinfo << "Loop: Watchdog started with pid '"
13900
               << lastWatchdog << "'.\n" << std::flush;
13901 13902 13903 13904
      }
    }
    else
    {
13905
      nxfatal << "Loop: PANIC! Previous watchdog detected "
13906
              << "in shutdown with pid '" << lastWatchdog
13907
              << "'.\n" << std::flush;
13908 13909 13910 13911 13912 13913 13914 13915 13916 13917

      cerr << "Error" << ": Previous watchdog detected "
           << "in shutdown with pid '" << lastWatchdog
           << "'.\n";

      HandleCleanup();
    }

    if (control -> CleanupTimeout > 0)
    {
13918
      nxinfo << "Loop: Waiting the cleanup timeout to complete.\n"
13919
             << std::flush;
13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933

      cerr << "Info" << ": Waiting the cleanup timeout to complete.\n";
    }
    else
    {
      //
      // The NX server will kill the watchdog
      // process after having shut down the
      // service channels.
      //

      cerr << "Info" << ": Watchdog running with pid '" << lastWatchdog
           << "'.\n";

13934
      nxinfo << "Loop: Waiting the watchdog process to complete.\n"
13935
             << std::flush;
13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947

      cerr << "Info" << ": Waiting the watchdog process to complete.\n";
    }

    lastKill = 2;
  }
}

static void handleCheckBitrateInLoop()
{
  static long int slept = 0;

13948
  nxinfo << "Loop: Bitrate is " << statistics -> getBitrateInShortFrame()
13949 13950 13951 13952
         << " B/s and " << statistics -> getBitrateInLongFrame()
         << " B/s in " << control -> ShortBitrateTimeFrame / 1000
         << "/" << control -> LongBitrateTimeFrame / 1000
         << " seconds timeframes.\n" << std::flush;
13953 13954 13955 13956 13957 13958 13959 13960 13961

  //
  // This can be improved. We may not jump out
  // of the select often enough to guarantee
  // the necessary accuracy.
  //

  if (control -> LocalBitrateLimit > 0)
  {
13962
    nxinfo << "Loop: Calculating bandwidth usage with limit "
13963 13964
           << control -> LocalBitrateLimit << ".\n"
           << std::flush;
13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982

    int reference = (statistics -> getBitrateInLongFrame() +
                         statistics -> getBitrateInShortFrame()) / 2;

    if (reference > control -> LocalBitrateLimit)
    {
      double ratio = ((double) reference) /
                         ((double) control -> LocalBitrateLimit);

      if (ratio > 1.2)
      {
        ratio = 1.2;
      }

      slept += (unsigned int) (pow(50000, ratio) / 1000);

      if (slept > 2000)
      {
13983
        nxwarn << "Loop: WARNING! Sleeping due to "
13984 13985
               << "reference bitrate of " << reference
               << " B/s.\n" << std::flush;
13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008

        cerr << "Warning" << ": Sleeping due to "
             << "reference bitrate of " << reference
             << " B/s.\n";

        slept %= 2000;
      }

      T_timestamp idleTs = getNewTimestamp();

      usleep((unsigned int) pow(50000, ratio));

      int diffTs = diffTimestamp(idleTs, getNewTimestamp());

      statistics -> addIdleTime(diffTs);

      statistics -> subReadTime(diffTs);
    }
  }
}


static void handleCheckStateInLoop(int &setFDs)
14009 14010 14011 14012 14013
{
  int fdLength;
  int fdPending;
  int fdSplits;

14014 14015 14016 14017 14018 14019 14020
  for (int j = 0; j < setFDs; j++)
  {
    if (j != proxyFD)
    {
      fdPending = proxy -> getPending(j);
      if (fdPending > 0)
      {
14021
        nxfatal << "Loop: PANIC! Buffer for descriptor FD#"
14022
                << j << " has pending bytes to read.\n"
14023
                << std::flush;
14024 14025 14026 14027 14028 14029 14030 14031

        HandleCleanup();
      }

      fdLength = proxy -> getLength(j);

      if (fdLength > 0)
      {
14032
        nxinfo << "Loop: WARNING! Buffer for descriptor FD#"
14033 14034
               << j << " has " << fdLength << " bytes to write.\n"
               << std::flush;
14035 14036 14037 14038 14039 14040 14041 14042
      }
    }
  }

  fdPending = proxy -> getPending(proxyFD);

  if (fdPending > 0)
  {
14043
    nxfatal << "Loop: PANIC! Buffer for proxy descriptor FD#"
14044
            << proxyFD << " has pending bytes to read.\n"
14045
            << std::flush;
14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056

    HandleCleanup();
  }

  fdLength = proxy -> getFlushable(proxyFD);

  if (fdLength > 0)
  {
    if (control -> FlushPolicy == policy_immediate &&
            proxy -> getBlocked(proxyFD) == 0)
    {
14057
      nxfatal << "Loop: PANIC! Buffer for proxy descriptor FD#"
14058 14059
              << proxyFD << " has " << fdLength << " bytes "
              << "to write with policy 'immediate'.\n"
14060
              << std::flush;
14061 14062 14063 14064 14065

      HandleCleanup();
    }
    else
    {
14066
      nxinfo << "Loop: WARNING! Buffer for proxy descriptor FD#"
14067 14068
             << proxyFD << " has " << fdLength << " bytes "
             << "to write.\n" << std::flush;
14069 14070 14071 14072 14073 14074 14075
    }
  }

  fdSplits = proxy -> getSplitSize();

  if (fdSplits > 0)
  {
14076
    nxwarn << "Loop: WARNING! Proxy descriptor FD#" << proxyFD
14077 14078
           << " has " << fdSplits << " splits to send.\n"
           << std::flush;
14079 14080 14081 14082 14083 14084
  }
}

static void handleCheckSelectInLoop(int &setFDs, fd_set &readSet,
                                        fd_set &writeSet, T_timestamp selectTs)
{
14085
  nxinfo << "Loop: Maximum descriptors is ["
14086 14087
         << setFDs << "] at " << strMsTimestamp()
         << ".\n" << std::flush;
14088 14089 14090 14091 14092 14093 14094

  int i;

  if (setFDs > 0)
  {
    i = 0;

14095
    nxinfo << "Loop: Selected for read are";
14096 14097 14098 14099 14100

    for (int j = 0; j < setFDs; j++)
    {
      if (FD_ISSET(j, &readSet))
      {
14101
        nxinfo_append << " [" << j << "]";
14102 14103 14104 14105 14106 14107 14108

        i++;
      }
    }

    if (i > 0)
    {
14109
      nxinfo_append << ".\n" << std::flush;
14110 14111 14112
    }
    else
    {
14113
      nxinfo_append << " [none].\n" << std::flush;
14114 14115 14116 14117
    }

    i = 0;

14118
    nxinfo << "Loop: Selected for write are";
14119 14120 14121 14122 14123

    for (int j = 0; j < setFDs; j++)
    {
      if (FD_ISSET(j, &writeSet))
      {
14124
        nxinfo_append << " [" << j << "]";
14125 14126 14127 14128 14129 14130 14131

        i++;
      }
    }

    if (i > 0)
    {
14132
      nxinfo_append << ".\n" << std::flush;
14133 14134 14135
    }
    else
    {
14136
      nxinfo_append << " [none].\n" << std::flush;
14137 14138 14139
    }
  }

14140
  nxinfo << "Loop: Select timeout is "
14141
         << selectTs.tv_sec << " s and "
14142
         << (double) selectTs.tv_usec / 1000
14143
         << " ms.\n" << std::flush;
14144 14145 14146 14147
}

static void handleCheckResultInLoop(int &resultFDs, int &errorFDs, int &setFDs, fd_set &readSet,
                                        fd_set &writeSet, struct timeval &selectTs,
14148
                                            struct timeval &pstartTs)
14149
{
14150
  int diffTs = diffTimestamp(pstartTs, getNewTimestamp());
14151 14152 14153 14154 14155


  if (diffTs >= (control -> PingTimeout -
                     (control -> LatencyTimeout * 4)))
  {
14156
    nxinfo << "Loop: Select result is [" << resultFDs
14157 14158
           << "] at " << strMsTimestamp() << " with no "
           << "communication within " << diffTs
14159
           << " ms.\n" << std::flush;
14160 14161 14162
  }
  else
  {
14163
    nxinfo << "Loop: Select result is [" << resultFDs
14164 14165
           << "] error is [" << errorFDs << "] at "
           << strMsTimestamp() << " after " << diffTs
14166
           << " ms.\n" << std::flush;
14167 14168 14169 14170 14171 14172 14173 14174 14175
  }


  int i;

  if (resultFDs > 0)
  {
    i = 0;

14176
    nxinfo << "Loop: Selected for read are";
14177 14178 14179 14180 14181

    for (int j = 0; j < setFDs; j++)
    {
      if (FD_ISSET(j, &readSet))
      {
14182
        nxinfo_append << " [" << j << "]";
14183 14184 14185 14186 14187 14188 14189

        i++;
      }
    }

    if (i > 0)
    {
14190
      nxinfo_append << ".\n" << std::flush;
14191 14192 14193
    }
    else
    {
14194
      nxinfo_append << " [none].\n" << std::flush;
14195 14196 14197 14198
    }

    i = 0;

14199
    nxinfo << "Loop: Selected for write are";
14200 14201 14202 14203 14204

    for (int j = 0; j < setFDs; j++)
    {
      if (FD_ISSET(j, &writeSet))
      {
14205
        nxinfo_append << " [" << j << "]";
14206 14207 14208 14209 14210 14211 14212

        i++;
      }
    }

    if (i > 0)
    {
14213
      nxinfo_append << ".\n" << std::flush;
14214 14215 14216
    }
    else
    {
14217
      nxinfo_append << " [none].\n" << std::flush;
14218 14219 14220 14221 14222 14223 14224
    }
  }
}


static void handleCheckSessionInConnect()
{
14225
  nxinfo << "Loop: Going to check session in connect.\n"
14226
         << std::flush;
14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269

  if (control -> ProxyMode == proxy_client)
  {
    HandleAlert(FAILED_PROXY_CONNECTION_CLIENT_ALERT, 1);
  }
  else if (IsNotRunning(lastDialog))
  {
    HandleAlert(FAILED_PROXY_CONNECTION_SERVER_ALERT, 1);
  }

  handleAlertInLoop();
}

static void handleStatisticsInLoop()
{
  if (lastSignal == 0)
  {
    return;
  }

  int mode = NO_STATS;

  if (control -> EnableStatistics == 1)
  {
    if (lastSignal == SIGUSR1)
    {
      //
      // Print overall statistics.
      //

      mode = TOTAL_STATS;
    }
    else if (lastSignal == SIGUSR2)
    {
      //
      // Print partial statistics.
      //

      mode = PARTIAL_STATS;
    }

    if (mode == TOTAL_STATS || mode == PARTIAL_STATS)
    {
14270
      nxinfo << "Loop: Going to request proxy statistics "
14271 14272
             << "with signal '" << DumpSignal(lastSignal)
             << "'.\n" << std::flush;
14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293

      if (proxy != NULL)
      {
        if (ReopenLogFile(statsFileName, statofs, 0) < 0)
        {
          HandleCleanup();
        }

        proxy -> handleStatistics(mode, statofs);
      }
    }
  }
}

static void handleNegotiationInLoop(int &setFDs, fd_set &readSet,
                                        fd_set &writeSet, T_timestamp &selectTs)
{
  int yield = 0;

  while (yield == 0)
  {
14294
    nxinfo << "Loop: Going to run a new negotiation loop "
14295 14296 14297
           << "with stage " << control -> ProxyStage
           << " at " << strMsTimestamp() << ".\n"
           << std::flush;
14298 14299 14300 14301 14302

    switch (control -> ProxyStage)
    {
      case stage_undefined:
      {
14303
        nxinfo << "Loop: Handling negotiation with '"
14304 14305
               << "stage_undefined" << "'.\n"
               << std::flush;
14306 14307 14308 14309 14310 14311 14312

        control -> ProxyStage = stage_initializing;

        break;
      }
      case stage_initializing:
      {
14313
        nxinfo << "Loop: Handling negotiation with '"
14314 14315
               << "stage_initializing" << "'.\n"
               << std::flush;
14316 14317 14318 14319 14320 14321 14322 14323 14324

        InitBeforeNegotiation();

        control -> ProxyStage = stage_connecting;

        break;
      }
      case stage_connecting:
      {
14325
        nxinfo << "Loop: Handling negotiation with '"
14326 14327
               << "stage_connecting" << "'.\n"
               << std::flush;
14328 14329 14330 14331 14332 14333 14334 14335 14336

        SetupProxyConnection();

        control -> ProxyStage = stage_connected;

        break;
      }
      case stage_connected:
      {
14337
        nxinfo << "Loop: Handling negotiation with '"
14338 14339
               << "stage_connected" << "'.\n"
               << std::flush;
14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379

        //
        // Server side proxy must always be the one that
        // sends its version and options first, so, in
        // some way, client side can be the the one that
        // has the last word on the matter.
        //

        if (control -> ProxyMode == proxy_server)
        {
          //
          // Check if we have been listening for a
          // forwarder. In this case it will have to
          // authenticate itself.
          //

          if (WE_LISTEN_FORWARDER)
          {
            control -> ProxyStage = stage_waiting_forwarder_version;

            break;
          }

          control -> ProxyStage = stage_sending_proxy_options;
        }
        else
        {
          //
          // The X client side is the side that has to wait
          // for the authorization cookie and any remote
          // option.
          //

          control -> ProxyStage = stage_waiting_proxy_version;
        }

        break;
      }
      case stage_sending_proxy_options:
      {
14380
        nxinfo << "Loop: Handling negotiation with '"
14381 14382
               << "stage_sending_proxy_options" << "'.\n"
               << std::flush;
14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401

        if (SendProxyOptions(proxyFD) < 0)
        {
          goto handleNegotiationInLoopError;
        }

        if (control -> ProxyMode == proxy_server)
        {
          control -> ProxyStage = stage_waiting_proxy_version;
        }
        else
        {
          control -> ProxyStage = stage_sending_proxy_caches;
        }

        break;
      }
      case stage_waiting_forwarder_version:
      {
14402
        nxinfo << "Loop: Handling negotiation with '"
14403 14404
               << "stage_waiting_forwarder_version" << "'.\n"
               << std::flush;
14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424

        int result = ReadForwarderVersion(proxyFD);

        if (result == 0)
        {
          yield = 1;
        }
        else if (result == 1)
        {
          control -> ProxyStage = stage_waiting_forwarder_options;
        }
        else
        {
          goto handleNegotiationInLoopError;
        }

        break;
      }
      case stage_waiting_forwarder_options:
      {
14425
        nxinfo << "Loop: Handling negotiation with '"
14426 14427
               << "stage_waiting_forwarder_options" << "'.\n"
               << std::flush;
14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447

        int result = ReadForwarderOptions(proxyFD);

        if (result == 0)
        {
          yield = 1;
        }
        else if (result == 1)
        {
          control -> ProxyStage = stage_sending_proxy_options;
        }
        else
        {
          goto handleNegotiationInLoopError;
        }

        break;
      }
      case stage_waiting_proxy_version:
      {
14448
        nxinfo << "Loop: Handling negotiation with '"
14449 14450
               << "stage_waiting_proxy_version" << "'.\n"
               << std::flush;
14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470

        int result = ReadProxyVersion(proxyFD);

        if (result == 0)
        {
          yield = 1;
        }
        else if (result == 1)
        {
          control -> ProxyStage = stage_waiting_proxy_options;
        }
        else
        {
          goto handleNegotiationInLoopError;
        }

        break;
      }
      case stage_waiting_proxy_options:
      {
14471
        nxinfo << "Loop: Handling negotiation with '"
14472 14473
               << "stage_waiting_proxy_options" << "'.\n"
               << std::flush;
14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500

        int result = ReadProxyOptions(proxyFD);

        if (result == 0)
        {
          yield = 1;
        }
        else if (result == 1)
        {
          if (control -> ProxyMode == proxy_server)
          {
            control -> ProxyStage = stage_waiting_proxy_caches;
          }
          else
          {
            control -> ProxyStage = stage_sending_proxy_options;
          }
        }
        else
        {
          goto handleNegotiationInLoopError;
        }

        break;
      }
      case stage_sending_proxy_caches:
      {
14501
        nxinfo << "Loop: Handling negotiation with '"
14502 14503
               << "stage_sending_proxy_caches" << "'.\n"
               << std::flush;
14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522

        if (SendProxyCaches(proxyFD) < 0)
        {
          goto handleNegotiationInLoopError;
        }

        if (control -> ProxyMode == proxy_server)
        {
          control -> ProxyStage = stage_operational;
        }
        else
        {
          control -> ProxyStage = stage_waiting_proxy_caches;
        }

        break;
      }
      case stage_waiting_proxy_caches:
      {
14523
        nxinfo << "Loop: Handling negotiation with '"
14524 14525
               << "stage_waiting_proxy_caches" << "'.\n"
               << std::flush;
14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552

        int result = ReadProxyCaches(proxyFD);

        if (result == 0)
        {
          yield = 1;
        }
        else if (result == 1)
        {
          if (control -> ProxyMode == proxy_server)
          {
            control -> ProxyStage = stage_sending_proxy_caches;
          }
          else
          {
            control -> ProxyStage = stage_operational;
          }
        }
        else
        {
          goto handleNegotiationInLoopError;
        }

        break;
      }
      case stage_operational:
      {
14553
        nxinfo << "Loop: Handling negotiation with '"
14554 14555
               << "stage_operational" << "'.\n"
               << std::flush;
14556 14557 14558 14559 14560 14561 14562 14563 14564

        InitAfterNegotiation();

        yield = 1;

        break;
      }
      default:
      {
14565 14566
        nxfatal << "Loop: PANIC! Unmanaged case '" << control -> ProxyStage
                << "' while handling negotiation.\n" << std::flush;
14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599

        cerr << "Error" << ": Unmanaged case '" << control -> ProxyStage
             << "' while handling negotiation.\n";

        HandleCleanup();
      }
    }
  }

  //
  // Check if the user requested the end of
  // the session.
  //
  
  if (CheckAbort() != 0)
  {
    HandleCleanup();
  }

  //
  // Select the proxy descriptor so that we
  // can proceed negotiating the session.
  //

  FD_SET(proxyFD, &readSet);

  if (proxyFD >= setFDs)
  {
    setFDs = proxyFD + 1;
  }

  setMinTimestamp(selectTs, control -> PingTimeout);

14600
  nxinfo << "Loop: Selected proxy FD#" << proxyFD << " in negotiation "
14601 14602
         << "phase with timeout of " << selectTs.tv_sec << " s and "
         << selectTs.tv_usec << " ms.\n" << std::flush;
14603 14604 14605 14606 14607

  return;

handleNegotiationInLoopError:

14608 14609
  nxfatal << "Loop: PANIC! Failure negotiating the session in stage '"
          << control -> ProxyStage << "'.\n" << std::flush;
14610 14611 14612 14613 14614 14615 14616 14617

  cerr << "Error" << ": Failure negotiating the session in stage '"
       << control -> ProxyStage << "'.\n";


  if (control -> ProxyMode == proxy_server &&
          control -> ProxyStage == stage_waiting_proxy_version)
  {
14618 14619
    nxfatal << "Loop: PANIC! Wrong version or invalid session "
            << "authentication cookie.\n" << std::flush;
14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670

    cerr << "Error" << ": Wrong version or invalid session "
         << "authentication cookie.\n";
  }

  handleTerminatingInLoop();

  HandleCleanup();
}

static void handleTerminatingInLoop()
{
  if (getpid() == lastProxy)
  {
    if (control -> ProxyStage < stage_terminating)
    {
      if (agent == NULL)
      {
        cerr << "Session" << ": Terminating session at '"
             << strTimestamp() << "'.\n";
      }

      control -> ProxyStage = stage_terminating;
    }
  }
}

static void handleTerminatedInLoop()
{
  if (getpid() == lastProxy)
  {
    if (control -> ProxyStage < stage_terminated)
    {
      if (agent == NULL)
      {
        cerr << "Session" << ": Session terminated at '"
             << strTimestamp() << "'.\n";
      }

      control -> ProxyStage = stage_terminated;
    }
  }
}

static void handleAlertInLoop()
{
  if (lastAlert.code == 0)
  {
    return;
  }

14671 14672 14673 14674 14675 14676
  //
  // Since ProtoStep7 (#issue 108)
  //
  // Now the remote proxy should always
  // be able to handle the alert
  //
14677

14678
  if (lastAlert.local == 0)
14679 14680 14681
  {
    if (proxy != NULL)
    {
14682
      nxinfo << "Loop: Requesting a remote alert with code '"
14683
             << lastAlert.code << "'.\n" << std::flush;
14684 14685 14686 14687 14688 14689 14690 14691 14692

      if (proxy -> handleAlert(lastAlert.code) < 0)
      {
        HandleShutdown();
      }
    }
  }
  else
  {
14693
    nxinfo << "Loop: Handling a local alert with code '"
14694
           << lastAlert.code << "'.\n" << std::flush;
14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750

    if (control -> ProxyMode == proxy_client)
    {
      //
      // If we are at X client side and server
      // proxy is not responding, we don't have
      // any possibility to interact with user.
      //

      if (lastAlert.code != CLOSE_DEAD_PROXY_CONNECTION_CLIENT_ALERT &&
              lastAlert.code != RESTART_DEAD_PROXY_CONNECTION_CLIENT_ALERT &&
                  lastAlert.code != FAILED_PROXY_CONNECTION_CLIENT_ALERT)
      {
        //
        // Let the server proxy show the dialog.
        //

        if (proxy != NULL &&
                proxy -> handleAlert(lastAlert.code) < 0)
        {
          HandleShutdown();
        }
      }
    }
    else
    {
      char caption[DEFAULT_STRING_LENGTH];

      strcpy(caption, ALERT_CAPTION_PREFIX);

      int length = strlen(sessionId);

      //
      // Get rid of the trailing MD5 from session id.
      //

      if (length > (MD5_LENGTH * 2 + 1) &&
              *(sessionId + (length - (MD5_LENGTH * 2 + 1))) == '-')
      {
        strncat(caption, sessionId, length - (MD5_LENGTH * 2 + 1));
      }
      else
      {
        strcat(caption, sessionId);
      }

      //
      // Use the display to which we are forwarding
      // the remote X connections.
      // 

      char *display = displayHost;

      int replace = 1;
      int local   = 1;

14751 14752
      const char *message;
      const char *type;
14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927

      switch (lastAlert.code)
      {
        case CLOSE_DEAD_X_CONNECTION_CLIENT_ALERT:
        {
          message = CLOSE_DEAD_X_CONNECTION_CLIENT_ALERT_STRING;
          type    = CLOSE_DEAD_X_CONNECTION_CLIENT_ALERT_TYPE;

          break;
        }
        case CLOSE_DEAD_X_CONNECTION_SERVER_ALERT:
        {
          message = CLOSE_DEAD_X_CONNECTION_SERVER_ALERT_STRING;
          type    = CLOSE_DEAD_X_CONNECTION_SERVER_ALERT_TYPE;

          break;
        }
        case CLOSE_DEAD_PROXY_CONNECTION_SERVER_ALERT:
        {
          message = CLOSE_DEAD_PROXY_CONNECTION_SERVER_ALERT_STRING;
          type    = CLOSE_DEAD_PROXY_CONNECTION_SERVER_ALERT_TYPE;

          break;
        }
        case RESTART_DEAD_PROXY_CONNECTION_SERVER_ALERT:
        {
          message = RESTART_DEAD_PROXY_CONNECTION_SERVER_ALERT_STRING;
          type    = RESTART_DEAD_PROXY_CONNECTION_SERVER_ALERT_TYPE;

          break;
        }
        case CLOSE_UNRESPONSIVE_X_SERVER_ALERT:
        {
          message = CLOSE_UNRESPONSIVE_X_SERVER_ALERT_STRING;
          type    = CLOSE_UNRESPONSIVE_X_SERVER_ALERT_TYPE;

          break;
        }
        case WRONG_PROXY_VERSION_ALERT:
        {
          message = WRONG_PROXY_VERSION_ALERT_STRING;
          type    = WRONG_PROXY_VERSION_ALERT_TYPE;

          break;
        }
        case FAILED_PROXY_CONNECTION_SERVER_ALERT:
        {
          message = FAILED_PROXY_CONNECTION_SERVER_ALERT_STRING;
          type    = FAILED_PROXY_CONNECTION_SERVER_ALERT_TYPE;

          break;
        }
        case MISSING_PROXY_CACHE_ALERT:
        {
          message = MISSING_PROXY_CACHE_ALERT_STRING;
          type    = MISSING_PROXY_CACHE_ALERT_TYPE;

          break;
        }
        case ABORT_PROXY_CONNECTION_ALERT:
        {
          message = ABORT_PROXY_CONNECTION_ALERT_STRING;
          type    = ABORT_PROXY_CONNECTION_ALERT_TYPE;

          break;
        }
        case DISPLACE_MESSAGE_ALERT:
        {
          message = DISPLACE_MESSAGE_ALERT_STRING;
          type    = DISPLACE_MESSAGE_ALERT_TYPE;

          break;
        }
        case GREETING_MESSAGE_ALERT:
        {
          message = GREETING_MESSAGE_ALERT_STRING;
          type    = GREETING_MESSAGE_ALERT_TYPE;

          break;
        }
        case START_RESUME_SESSION_ALERT:
        {
          message = START_RESUME_SESSION_ALERT_STRING;
          type    = START_RESUME_SESSION_ALERT_TYPE;

          break;
        }
        case FAILED_RESUME_DISPLAY_ALERT:
        {
          message = FAILED_RESUME_DISPLAY_ALERT_STRING;
          type    = FAILED_RESUME_DISPLAY_ALERT_TYPE;

          break;
        }
        case FAILED_RESUME_DISPLAY_BROKEN_ALERT:
        {
          message = FAILED_RESUME_DISPLAY_BROKEN_STRING;
          type    = FAILED_RESUME_DISPLAY_BROKEN_TYPE;

          break;
        }
        case FAILED_RESUME_VISUALS_ALERT:
        {
          message = FAILED_RESUME_VISUALS_ALERT_STRING;
          type    = FAILED_RESUME_VISUALS_ALERT_TYPE;

          break;
        }
        case FAILED_RESUME_COLORMAPS_ALERT:
        {
          message = FAILED_RESUME_COLORMAPS_ALERT_STRING;
          type    = FAILED_RESUME_COLORMAPS_ALERT_TYPE;

          break;
        }
        case FAILED_RESUME_PIXMAPS_ALERT:
        {
          message = FAILED_RESUME_PIXMAPS_ALERT_STRING;
          type    = FAILED_RESUME_PIXMAPS_ALERT_TYPE;

          break;
        }
        case FAILED_RESUME_DEPTHS_ALERT:
        {
          message = FAILED_RESUME_DEPTHS_ALERT_STRING;
          type    = FAILED_RESUME_DEPTHS_ALERT_TYPE;

          break;
        }
        case FAILED_RESUME_RENDER_ALERT:
        {
          message = FAILED_RESUME_RENDER_ALERT_STRING;
          type    = FAILED_RESUME_RENDER_ALERT_TYPE;

          break;
        }
        case FAILED_RESUME_FONTS_ALERT:
        {
          message = FAILED_RESUME_FONTS_ALERT_STRING;
          type    = FAILED_RESUME_FONTS_ALERT_TYPE;

          break;
        }
        case INTERNAL_ERROR_ALERT:
        {
          message = INTERNAL_ERROR_ALERT_STRING;
          type    = INTERNAL_ERROR_ALERT_TYPE;

          break;
        }
        case ABORT_PROXY_NEGOTIATION_ALERT:
        {
          message = ABORT_PROXY_NEGOTIATION_ALERT_STRING;
          type    = ABORT_PROXY_NEGOTIATION_ALERT_TYPE;

          break;
        }
        case ABORT_PROXY_SHUTDOWN_ALERT:
        {
          message = ABORT_PROXY_SHUTDOWN_ALERT_STRING;
          type    = ABORT_PROXY_SHUTDOWN_ALERT_TYPE;

          break;
        }
        case FAILED_XDMCP_CONNECTION_ALERT:
        {
          message = FAILED_XDMCP_CONNECTION_ALERT_STRING;
          type    = FAILED_XDMCP_CONNECTION_ALERT_TYPE;

          break;
        }
        default:
        {
          if (lastAlert.code > LAST_PROTO_STEP_7_ALERT)
          {
14928
            nxwarn << "Loop: WARNING! An unrecognized alert type '"
14929 14930
                   << lastAlert.code << "' was requested.\n"
                   << std::flush;
14931 14932 14933 14934 14935 14936

            cerr << "Warning" << ": An unrecognized alert type '"
                 << lastAlert.code << "' was requested.\n";
          }
          else
          {
14937
            nxwarn << "Loop: WARNING! Ignoring obsolete alert type '"
14938
                   << lastAlert.code << "'.\n" << std::flush;
14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951
          }

          message = NULL;
          type    = NULL;

          replace = 0;

          break;
        }
      }

      if (replace == 1 && IsRunning(lastDialog))
      {
14952
        nxinfo << "Loop: Killing the previous dialog with pid '"
14953
               << lastDialog << "'.\n" << std::flush;
14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983

        //
        // The client ignores the TERM signal
        // on Windows.
        //

        #ifdef __CYGWIN32__

        KillProcess(lastDialog, "dialog", SIGKILL, 0);

        #else

        KillProcess(lastDialog, "dialog", SIGTERM, 0);

        #endif

        SetNotRunning(lastDialog);

        if (proxy != NULL)
        {
          proxy -> handleResetAlert();
        }
      }

      if (message != NULL && type != NULL)
      {
        lastDialog = NXTransDialog(caption, message, 0, type, local, display);

        if (IsFailed(lastDialog))
        {
14984 14985
          nxfatal << "Loop: PANIC! Can't start the NX dialog process.\n"
                  << std::flush;
14986 14987 14988 14989 14990

          SetNotRunning(lastDialog);
        }
        else
        {
14991
          nxinfo << "Loop: Dialog started with pid '"
14992
                 << lastDialog << "'.\n" << std::flush;
14993 14994 14995 14996
        }
      }
      else
      {
14997
        nxinfo << "Loop: No new dialog required for code '"
14998
               << lastAlert.code << "'.\n" << std::flush;
14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013
      }
    }
  }

  //
  // Reset state.
  //

  lastAlert.code  = 0;
  lastAlert.local = 0;
}

static inline void handleSetAgentInLoop(int &setFDs, fd_set &readSet,
                                            fd_set &writeSet, struct timeval &selectTs)
{
15014
  nxinfo << "Loop: Preparing the masks for the agent descriptors.\n"
15015
         << std::flush;
15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028

  agent -> saveChannelState();

  agent -> saveReadMask(&readSet);
  agent -> saveWriteMask(&writeSet);

  if (control -> ProxyStage >= stage_operational)
  {
    if (agent -> remoteCanRead(&readSet) ||
            agent -> remoteCanWrite(&writeSet) ||
                agent -> localCanRead() ||
                    agent -> proxyCanRead())
    {
15029
      nxinfo << "Loop: Setting a null timeout with agent descriptors ready.\n"
15030
             << std::flush;
15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042

      //
      // Force a null timeout so we'll bail out
      // of the select immediately. We will ac-
      // comodate the result code later.
      //

      selectTs.tv_sec  = 0;
      selectTs.tv_usec = 0;
    }
  }

15043
  nxinfo << "Loop: Clearing the read and write agent descriptors.\n"
15044
         << std::flush;
15045 15046 15047 15048 15049 15050 15051 15052

  agent -> clearReadMask(&readSet);
  agent -> clearWriteMask(&writeSet);
}

static inline void handleAgentInLoop(int &resultFDs, int &errorFDs, int &setFDs, fd_set &readSet,
                                         fd_set &writeSet, struct timeval &selectTs)
{
15053
  nxinfo << "Loop: Setting proxy and local agent descriptors.\n"
15054
         << std::flush;
15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069

  //
  // Check if I/O is possible on the local
  // agent or the proxy descriptor.
  //
  
  if (resultFDs >= 0)
  {
    //
    // Save if the proxy can read from the
    // the agent descriptor.
    //

    agent -> saveChannelState();

15070
    nxinfo << "Loop: Values were resultFDs " << resultFDs
15071 15072
           << " errorFDs " << errorFDs << " setFDs "
           << setFDs << ".\n" << std::flush;
15073 15074 15075

    if (agent -> localCanRead() == 1)
    {
15076
      nxinfo << "Loop: Setting agent descriptor FD#" << agent ->
15077 15078
                getLocalFd() << " as ready to read.\n"
             << std::flush;
15079 15080 15081 15082 15083 15084 15085 15086

      agent -> setLocalRead(&readSet, &resultFDs);
    }


    if (agent -> proxyCanRead(&readSet) == 0 &&
            agent -> proxyCanRead() == 1)
    {
15087
      nxinfo << "Loop: WARNING! Can read from proxy FD#"
15088 15089
             << proxyFD << " but the descriptor "
             << "is not selected.\n" << std::flush;
15090 15091 15092 15093
    }

    if (agent -> proxyCanRead(&readSet) == 1)
    {
15094
      nxinfo << "Loop: Setting proxy descriptor FD#" << agent ->
15095 15096
                getProxyFd() << " as ready to read.\n"
             << std::flush;
15097 15098 15099
    }


15100
    nxinfo << "Loop: Values are now resultFDs " << resultFDs
15101 15102
           << " errorFDs " << errorFDs << " setFDs "
           << setFDs << ".\n" << std::flush;
15103 15104 15105 15106 15107 15108
  }
}

static inline void handleAgentLateInLoop(int &resultFDs, int &errorFDs, int &setFDs, fd_set &readSet,
                                             fd_set &writeSet, struct timeval &selectTs)
{
15109
  nxinfo << "Loop: Setting remote agent descriptors.\n"
15110
         << std::flush;
15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130

  //
  // We reset the masks before calling our select.
  // We now set the descriptors that are ready but
  // only if they were set in the original mask.
  // We do this after having executed our loop as
  // we may have produced more data and the agent
  // descriptors may have become readable or writ-
  // able in the meanwhile.
  //
  
  if (resultFDs >= 0)
  {
    //
    // Save if the proxy can read from the
    // the agent descriptor.
    //

    agent -> saveChannelState();

15131
    nxinfo << "Loop: Values were resultFDs " << resultFDs
15132 15133
           << " errorFDs " << errorFDs << " setFDs "
           << setFDs << ".\n" << std::flush;
15134 15135 15136 15137

    if (agent -> remoteCanRead(agent ->
            getSavedReadMask()) == 1)
    {
15138
      nxinfo << "Loop: Setting agent descriptor FD#" << agent ->
15139 15140
                getRemoteFd() << " as ready to read.\n"
             << std::flush;
15141 15142 15143 15144 15145 15146 15147

      agent -> setRemoteRead(&readSet, &resultFDs);
    }

    if (agent -> remoteCanWrite(agent ->
            getSavedWriteMask()) == 1)
    {
15148
      nxinfo << "Loop: Setting agent descriptor FD#" << agent ->
15149 15150
                getRemoteFd() << " as ready to write.\n"
             << std::flush;
15151 15152 15153 15154

      agent -> setRemoteWrite(&writeSet, &resultFDs);
    }

15155
    nxinfo << "Loop: Values are now resultFDs " << resultFDs
15156 15157
           << " errorFDs " << errorFDs << " setFDs "
           << setFDs << ".\n" << std::flush;
15158 15159 15160 15161 15162 15163 15164 15165 15166
  }
}

static inline void handleReadableInLoop(int &resultFDs, fd_set &readSet)
{
  if (resultFDs > 0)
  {
    T_channel_type type = channel_none;

15167
    const char *label = NULL;
15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276
    int domain  = -1;
    int fd      = -1;

    if (tcpFD != -1 && FD_ISSET(tcpFD, &readSet))
    {
      type   = channel_x11;
      label  = "X";
      domain = AF_INET;
      fd     = tcpFD;

      resultFDs--;
    }

    if (unixFD != -1 && FD_ISSET(unixFD, &readSet))
    {
      type   = channel_x11;
      label  = "X";
      domain = AF_UNIX;
      fd     = unixFD;

      resultFDs--;
    }

    if (cupsFD != -1 && FD_ISSET(cupsFD, &readSet))
    {
      type   = channel_cups;
      label  = "CUPS";
      domain = AF_INET;
      fd     = cupsFD;

      resultFDs--;
    }

    if (auxFD != -1 && FD_ISSET(auxFD, &readSet))
    {
      //
      // Starting from version 1.5.0 we create real X
      // connections for the keyboard channel, so they
      // can use the fake authorization cookie. This
      // means that there is not such a thing like a
      // channel_aux anymore.
      //

      type   = channel_x11;
      label  = "auxiliary X11";
      domain = AF_INET;
      fd     = auxFD;

      resultFDs--;
    }

    if (smbFD != -1 && FD_ISSET(smbFD, &readSet))
    {
      type   = channel_smb;
      label  = "SMB";
      domain = AF_INET;
      fd     = smbFD;

      resultFDs--;
    }

    if (mediaFD != -1 && FD_ISSET(mediaFD, &readSet))
    {
      type   = channel_media;
      label  = "media";
      domain = AF_INET;
      fd     = mediaFD;

      resultFDs--;
    }

    if (httpFD != -1 && FD_ISSET(httpFD, &readSet))
    {
      type   = channel_http;
      label  = "HTTP";
      domain = AF_INET;
      fd     = httpFD;

      resultFDs--;
    }

    if (fontFD != -1 && FD_ISSET(fontFD, &readSet))
    {
      type   = channel_font;
      label  = "font server";
      domain = AF_INET;
      fd     = fontFD;

      resultFDs--;
    }

    if (slaveFD != -1 && FD_ISSET(slaveFD, &readSet))
    {
      type   = channel_slave;
      label  = "slave";
      domain = AF_INET;
      fd     = slaveFD;

      resultFDs--;
    }

    if (type != channel_none)
    {
      int newFD = AcceptConnection(fd, domain, label);

      if (newFD != -1)
      {
        if (proxy -> handleNewConnection(type, newFD) < 0)
        {
15277 15278
          nxfatal << "Loop: PANIC! Error creating new " << label
                  << " connection.\n" << std::flush;
15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297

          cerr << "Error" << ": Error creating new " << label
               << " connection.\n";

          close(newFD);

          //
          // Don't kill the proxy in the case of an error.
          //
          // HandleCleanup();
          //
        }
        else if (proxy -> getReadable(newFD) > 0)
        {
          //
          // Add the descriptor, so we can try
          // to read immediately.
          //

15298
          nxinfo << "Loop: Trying to read immediately "
15299 15300
                 << "from descriptor FD#" << newFD
                 << ".\n" << std::flush;
15301 15302 15303 15304 15305 15306 15307

          FD_SET(newFD, &readSet);

          resultFDs++;
        }
        else
        {
15308
          nxinfo << "Loop: Nothing to read immediately "
15309 15310
                 << "from descriptor FD#" << newFD
                 << ".\n" << std::flush;
15311 15312 15313 15314 15315
        }
      }
    }
  }

15316
  nxdbg << "Loop: Going to check the readable descriptors.\n"
15317
        << std::flush;
15318 15319 15320

  if (proxy -> handleRead(resultFDs, readSet) < 0)
  {
15321
    nxinfo << "Loop: Failure reading from descriptors "
15322 15323
           << "for proxy FD#" << proxyFD << ".\n"
           << std::flush;
15324 15325 15326 15327 15328 15329 15330

    HandleShutdown();
  }
}

static inline void handleWritableInLoop(int &resultFDs, fd_set &writeSet)
{
15331
  nxdbg << "Loop: Going to check the writable descriptors.\n"
15332
        << std::flush;
15333 15334 15335

  if (resultFDs > 0 && proxy -> handleFlush(resultFDs, writeSet) < 0)
  {
15336
    nxinfo << "Loop: Failure writing to descriptors "
15337 15338
           << "for proxy FD#" << proxyFD << ".\n"
           << std::flush;
15339 15340 15341 15342 15343 15344 15345

    HandleShutdown();
  }
}

static inline void handleFlushInLoop()
{
15346
  nxdbg << "Loop: Going to flush any data to the proxy.\n"
15347
        << std::flush;
15348 15349 15350 15351 15352 15353 15354 15355

  if (agent == NULL || control ->
          FlushPolicy == policy_immediate)
  {

    if (usePolicy == -1 && control ->
            ProxyMode == proxy_client)
    {
15356
      nxinfo << "Loop: WARNING! Flushing the proxy link "
15357
             << "on behalf of the agent.\n" << std::flush;
15358 15359 15360 15361 15362
    }


    if (proxy -> handleFlush() < 0)
    {
15363
      nxinfo << "Loop: Failure flushing the proxy FD#"
15364
             << proxyFD << ".\n" << std::flush;
15365 15366 15367 15368 15369 15370 15371 15372

      HandleShutdown();
    }
  }
}

static inline void handleRotateInLoop()
{
15373
  nxdbg << "Loop: Going to rotate channels "
15374 15375
        << "for proxy FD#" << proxyFD << ".\n"
        << std::flush;
15376 15377 15378 15379 15380 15381

  proxy -> handleRotate();
}

static inline void handleEventsInLoop()
{
15382
  nxdbg << "Loop: Going to check channel events "
15383 15384
        << "for proxy FD#" << proxyFD << ".\n"
        << std::flush;
15385 15386 15387

  if (proxy -> handleEvents() < 0)
  {
15388
    nxinfo << "Loop: Failure handling channel events "
15389 15390
           << "for proxy FD#" << proxyFD << ".\n"
           << std::flush;
15391 15392 15393 15394 15395

    HandleShutdown();
  }
}

15396
static void handleLogReopenInLoop(T_timestamp &lTs, T_timestamp &nTs)
15397 15398 15399 15400 15401 15402 15403 15404 15405
{
  //
  // If need to limit the size of the
  // log file, check the size at each
  // loop.
  //

  #ifndef QUOTA

15406
  if (diffTimestamp(lTs, nTs) > control -> FileSizeCheckTimeout)
15407 15408 15409

  #endif
  {
15410
    nxdbg << "Loop: Checking size of log file '"
15411
          << errorsFileName << "'.\n" << std::flush;
15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425

    #ifndef MIXED

    if (ReopenLogFile(errorsFileName, logofs, control -> FileSizeLimit) < 0)
    {
      HandleShutdown();
    }

    #endif

    //
    // Reset to current timestamp.
    //

15426
    lTs = nTs;
15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456
  }
}

static inline void handleSetReadInLoop(fd_set &readSet, int &setFDs, struct timeval &selectTs)
{
  proxy -> setReadDescriptors(&readSet, setFDs, selectTs);
}

static inline void handleSetWriteInLoop(fd_set &writeSet, int &setFDs, struct timeval &selectTs)
{
  proxy -> setWriteDescriptors(&writeSet, setFDs, selectTs);
}

static void handleSetListenersInLoop(fd_set &readSet, int &setFDs)
{
  //
  // Set descriptors of listening sockets.
  //

  if (control -> ProxyMode == proxy_client)
  {
    if (useTcpSocket == 1)
    {
      FD_SET(tcpFD, &readSet);

      if (tcpFD >= setFDs)
      {
        setFDs = tcpFD + 1;
      }

15457
      nxdbg << "Loop: Selected listener tcpFD " << tcpFD
15458 15459
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470
    }

    if (useUnixSocket == 1)
    {
      FD_SET(unixFD, &readSet);

      if (unixFD >= setFDs)
      {
        setFDs = unixFD + 1;
      }

15471
      nxdbg << "Loop: Selected listener unixFD " << unixFD
15472 15473
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484
    }

    if (useCupsSocket == 1)
    {
      FD_SET(cupsFD, &readSet);

      if (cupsFD >= setFDs)
      {
        setFDs = cupsFD + 1;
      }

15485
      nxdbg << "Loop: Selected listener cupsFD " << cupsFD
15486 15487
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498
    }

    if (useAuxSocket == 1)
    {
      FD_SET(auxFD, &readSet);

      if (auxFD >= setFDs)
      {
        setFDs = auxFD + 1;
      }

15499
      nxdbg << "Loop: Selected listener auxFD " << auxFD
15500 15501
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512
    }

    if (useSmbSocket == 1)
    {
      FD_SET(smbFD, &readSet);

      if (smbFD >= setFDs)
      {
        setFDs = smbFD + 1;
      }

15513
      nxdbg << "Loop: Selected listener smbFD " << smbFD
15514 15515
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526
    }

    if (useMediaSocket == 1)
    {
      FD_SET(mediaFD, &readSet);

      if (mediaFD >= setFDs)
      {
        setFDs = mediaFD + 1;
      }

15527
      nxdbg << "Loop: Selected listener mediaFD " << mediaFD
15528 15529
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540
    }

    if (useHttpSocket == 1)
    {
      FD_SET(httpFD, &readSet);

      if (httpFD >= setFDs)
      {
        setFDs = httpFD + 1;
      }

15541
      nxdbg << "Loop: Selected listener httpFD " << httpFD
15542 15543
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556
    }
  }
  else
  {
    if (useFontSocket == 1)
    {
      FD_SET(fontFD, &readSet);

      if (fontFD >= setFDs)
      {
        setFDs = fontFD + 1;
      }

15557
      nxdbg << "Loop: Selected listener fontFD " << fontFD
15558 15559
            << " with setFDs " << setFDs << ".\n"
            << std::flush;
15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571
    }
  }

  if (useSlaveSocket == 1)
  {
    FD_SET(slaveFD, &readSet);

    if (slaveFD >= setFDs)
    {
      setFDs = slaveFD + 1;
    }

15572
    nxdbg << "Loop: Selected listener slaveFD " << slaveFD
15573 15574
          << " with setFDs " << setFDs << ".\n"
          << std::flush;
15575 15576
  }
}