Proxy.h 25 KB
Newer Older
1 2
/**************************************************************************/
/*                                                                        */
3
/* Copyright (c) 2001, 2010 NoMachine, http://www.nomachine.com/.         */
4 5 6 7 8 9 10 11
/*                                                                        */
/* NXCOMP, NX protocol compression and NX extensions to this software     */
/* are copyright of NoMachine. Redistribution and use of the present      */
/* software is allowed according to terms specified in the file LICENSE   */
/* which comes in the source distribution.                                */
/*                                                                        */
/* Check http://www.nomachine.com/licensing.html for applicability.       */
/*                                                                        */
12
/* NX and NoMachine are trademarks of Medialogic S.p.A.                   */
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/**************************************************************************/

#ifndef Proxy_H
#define Proxy_H

#include <sys/types.h>

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

#include "Misc.h"
#include "Timestamp.h"

#include "List.h"
#include "Channel.h"
#include "Transport.h"
#include "EncodeBuffer.h"
#include "ProxyReadBuffer.h"
35
#include "ChannelEndPoint.h"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

//
// Forward declaration as we
// need a pointer.
//

class Agent;

//
// Set the verbosity level.
//

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

//
// Log the important tracepoints related
// to writing packets to the peer proxy.
//

#undef  FLUSH

//
// Codes used for control messages in
// proxy-to-proxy protocol.
//
// The following codes are currently
// unused.
//
// code_alert_reply,
// code_reset_request,
// code_reset_reply,
// code_load_reply,
// code_save_reply,
// code_shutdown_reply,
// code_configuration_request,
// code_configuration_reply.
//
// These are for compatibility with
// old versions.
//
// code_sync_request,
// code_sync_reply,
//
// The code_new_aux_connection should not
// be used anymore. Auxiliary X connections
// are treated as normal X channels since
// version 1.5.0.
//

typedef enum
{
  code_new_x_connection,
  code_new_cups_connection,
  code_new_aux_connection,
  code_new_smb_connection,
  code_new_media_connection,
  code_switch_connection,
  code_drop_connection,
  code_finish_connection,
  code_begin_congestion,
  code_end_congestion,
  code_alert_request,
  code_alert_reply,
  code_reset_request,
  code_reset_reply,
  code_load_request,
  code_load_reply,
  code_save_request,
  code_save_reply,
  code_shutdown_request,
  code_shutdown_reply,
  code_control_token_request,
  code_control_token_reply,
  code_configuration_request,
  code_configuration_reply,
  code_statistics_request,
  code_statistics_reply,
  code_new_http_connection,
  code_sync_request,
  code_sync_reply,
  code_new_font_connection,
  code_new_slave_connection,
  code_finish_listeners,
  code_split_token_request,
  code_split_token_reply,
  code_data_token_request,
  code_data_token_reply,
  code_last_tag

} T_proxy_code;

typedef enum
{
  operation_in_negotiation,
  operation_in_messages,
  operation_in_configuration,
  operation_in_statistics,
  operation_last_tag

} T_proxy_operation;

typedef enum
{
  frame_ping,
  frame_data,

} T_frame_type;

typedef enum
{
  token_control,
  token_split,
  token_data

} T_token_type;

typedef enum
{
  load_if_any,
  load_if_first

} T_load_type;

class Proxy
{
  public:

  //
  // Maximum number of supported channels.
  //

  static const int CONNECTIONS_LIMIT  = 256;

  //
  // Numboer of token types.
  //

  static const int TOKEN_TYPES = 3;

  //
  // Lenght of buffer we use to add our
  // control messages plus the length of
  // the data frame.
  //

  static const int CONTROL_CODES_LENGTH = ENCODE_BUFFER_PREFIX_SIZE - 5;

  static const int CONTROL_CODES_THRESHOLD = CONTROL_CODES_LENGTH - 9;

  Proxy(int fd);

  virtual ~Proxy();

  //
  // Inform the proxy that the negotiation phase is
  // completed and that it can start handling binary
  // messages.
  //

  int setOperational();

  int getOperational()
  {
    return (operation_ != operation_in_negotiation);
  }

  int setReadDescriptors(fd_set *fdSet, int &fdMax, T_timestamp &tsMax);

  int setWriteDescriptors(fd_set *fdSet, int &fdMax, T_timestamp &tsMax);

  //
  // Perform the operation on the proxy
  // link or its own channels.
  //

  int handleRead(int &resultFds, fd_set &fdSet);

  int handleFlush(int &resultFds, fd_set &fdSet);

  int handleRead();

  int handleRead(int fd, const char *data = NULL, int size = 0);

  int handleEvents();

  int handleFlush();

  int handleFlush(int fd);

  int handlePing();

  int handleFinish();

  int handleShutdown();

  int handleStatistics(int type, ostream *statofs);

  int handleAlert(int alert);

  int handleRotate()
  {
    activeChannels_.rotate();

    return 1;
  }

  int handleChannelConfiguration();

  int handleSocketConfiguration();

  int handleLinkConfiguration();

  int handleCacheConfiguration();

  //
  // These must be called just after initialization to
  // tell to the proxy where the network connections
  // have to be forwarded.
  //

  virtual void handleDisplayConfiguration(const char *xServerDisplay, int xServerAddrFamily,
                                              sockaddr * xServerAddr, unsigned int xServerAddrLength) = 0;

262 263 264 265 266
  virtual void handlePortConfiguration(ChannelEndPoint &cupsServerPort,
                                       ChannelEndPoint &smbServerPort,
                                       ChannelEndPoint &mediaServerPort,
                                       ChannelEndPoint &httpServerPort,
                                       const char *fontServerPort) = 0;
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284

  //
  // Create new tunneled channels.
  //

  virtual int handleNewConnection(T_channel_type type, int clientFd) = 0;

  virtual int handleNewConnectionFromProxy(T_channel_type type, int channelId) = 0;

  virtual int handleNewAgentConnection(Agent *agent) = 0;

  virtual int handleNewXConnection(int clientFd) = 0;

  virtual int handleNewXConnectionFromProxy(int channelId) = 0;

  int handleNewGenericConnection(int clientFd, T_channel_type type, const char *label);

  int handleNewGenericConnectionFromProxy(int channelId, T_channel_type type,
285
                                          ChannelEndPoint &endpoint, const char *label);
286

287 288 289 290 291
  int handleNewGenericConnectionFromProxyUnix(int channelId, T_channel_type type,
                                              const char *path, const char *label);

  int handleNewGenericConnectionFromProxyTCP(int channelId, T_channel_type type,
                                             const char *hostname, long port, const char *label);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994

  int handleNewSlaveConnection(int clientFd);

  int handleNewSlaveConnectionFromProxy(int channelId);

  //
  // Force closure of channels.
  //

  int handleCloseConnection(int clientFd);

  int handleCloseAllXConnections();

  int handleCloseAllListeners();

  //
  // Called when the loop has replaced
  // or closed a previous alert.
  //

  void handleResetAlert();

  //
  // Handle the persistent cache.
  //

  virtual int handleLoad(T_load_type type) = 0;

  virtual int handleSave() = 0;

  protected:

  //
  // Timeout related data:
  //
  // flush
  // split
  // motion
  //
  // Timeouts in milliseconds after which the
  // proxy will have to perform the operation.
  //
  // readTs, writeTs
  //
  // Timestamp of last packet received or sent
  // to remote proxy. Used to detect lost con-
  // nection.
  //
  // loopTs
  //
  // Timestamp of last loop completed by the
  // proxy
  //
  // pingTs
  //
  // Timestamp of last ping request sent to the
  // remote peer.
  //
  // alertTs
  //
  // Timestamp of last 'no data received' alert
  // dialog shown to the user.
  //
  // loadTs
  //
  // Were message stores populated from data on
  // disk.
  //
  // splitTs
  // motionTs
  //
  // Timestamps of the last operation of this
  // kind handled by the proxy.
  //

  typedef struct
  {
    int split;
    int motion;

    T_timestamp readTs;
    T_timestamp writeTs;

    T_timestamp loopTs;
    T_timestamp pingTs;
    T_timestamp alertTs;
    T_timestamp loadTs;

    T_timestamp splitTs;
    T_timestamp motionTs;

  } T_proxy_timeouts;

  //
  // Bytes accumulated so far while waiting
  // to send the next token, number of tokens
  // remaining for each token type and other
  // token related information.
  //

  typedef struct
  {
    int size;
    int limit;

    int bytes;
    int remaining;

    T_proxy_code request;
    T_proxy_code reply;

    T_token_type type;

  } T_proxy_token;

  int handlePostConnectionFromProxy(int channelId, int serverFd,
                                        T_channel_type type, const char *label);

  int handleDrain();

  int handleFrame(T_frame_type type);

  int handleFinish(int channelId);

  int handleDrop(int channelId);

  int handleFinishFromProxy(int channelId);

  int handleDropFromProxy(int channelId);

  int handleStatisticsFromProxy(int type);

  int handleStatisticsFromProxy(const unsigned char *message, unsigned int length);

  int handleNegotiation(const unsigned char *message, unsigned int length);

  int handleNegotiationFromProxy(const unsigned char *message, unsigned int length);

  int handleToken(T_frame_type type);

  int handleTokenFromProxy(T_proxy_token &token, int count);

  int handleTokenReplyFromProxy(T_proxy_token &token, int count);

  int handleSyncFromProxy(int channelId);

  int handleSwitch(int channelId);

  int handleControl(T_proxy_code code, int data = -1);

  int handleControlFromProxy(const unsigned char *message);

  //
  // Interleave reads of the X server
  // events while writing data to the
  // remote proxy.
  //

  virtual int handleAsyncEvents() = 0;

  //
  // Timer related functions.
  //

  protected:

  void setTimer(int value)
  {
    SetTimer(value);
  }

  void resetTimer()
  {
    ResetTimer();

    timer_ = 0;
  }

  public:

  void handleTimer()
  {
    timer_ = 1;
  }

  int getTimer()
  {
    return timer_;
  }

  //
  // Can the channel consume data and the
  // proxy produce more output?
  //

  int canRead(int fd) const
  {
    return (isTimeToRead() == 1 &&
                isTimeToRead(getChannel(fd)) == 1);
  }

  //
  // Can the proxy read more data from its
  // peer?
  //

  int canRead() const
  {
    return (transport_ -> readable() != 0);
  }

  int canFlush() const
  {
    return (encodeBuffer_.getLength() +
                controlLength_ + transport_ -> length() +
                    transport_ -> flushable() > 0);
  }

  int needFlush(int channelId) const
  {
    return (outputChannel_ == channelId &&
                encodeBuffer_.getLength() > 0);
  }

  int needFlush() const
  {
    return (encodeBuffer_.getLength() > 0);
  }

  int shouldFlush() const
  {
    if ((int) ((encodeBuffer_.getLength() +
            controlLength_) / statistics ->
                getStreamRatio()) >= control -> TokenSize)
    {
      #if defined(TEST) || defined(INFO) || defined(FLUSH)
      *logofs << "Proxy: FLUSH! Requesting a flush with "
              << (encodeBuffer_.getLength() + controlLength_)
              << " bytes and stream ratio " << (double) statistics ->
                 getStreamRatio() << ".\n" << logofs_flush;
      #endif

      return 1;
    }

    #if defined(TEST) || defined(INFO) || defined(FLUSH)
    *logofs << "Proxy: Not requesting a flush with "
            << (encodeBuffer_.getLength() + controlLength_)
            << " bytes and stream ratio " << (double) statistics ->
               getStreamRatio() << ".\n" << logofs_flush;
    #endif

    return 0;
  }

  int needDrain() const
  {
    return (congestion_ == 1 || transport_ -> length() >
                control -> TransportProxyBufferThreshold);
  }

  int getFd() const
  {
    return fd_;
  }

  int getFlushable(int fd) const
  {
    if (fd == fd_)
    {
      return (encodeBuffer_.getLength() + controlLength_ +
                  transport_ -> flushable());
    }

    return 0;
  }

  int getSplitSize()
  {
    return (clientStore_ != NULL ? clientStore_ ->
                getSplitTotalSize() : 0);
  }

  int getSplitStorageSize()
  {
    return (clientStore_ != NULL ? clientStore_ ->
                getSplitTotalStorageSize() : 0);
  }

  //
  // Returns the number of active channels
  // that currently managed by this proxy.
  //

  int getChannels(T_channel_type type = channel_none);

  //
  // If descriptor corresponds to a valid
  // channel, returns the type of traffic
  // carried by it.
  //

  T_channel_type getType(int fd);

  //
  // Given a channel type, returns the
  // literal name.
  //

  const char *getTypeName(T_channel_type type);

  //
  // Get a convenient name for 'localhost'.
  //

  const char *getComputerName();

  //
  // Set if we have initiated the shutdown
  // procedure and if the shutdown request
  // has been received from the remote.
  //

  int getFinish() const
  {
    return finish_;
  }

  int getShutdown() const
  {
    return shutdown_;
  }

  //
  // Interfaces to the transport buffers.
  //

  int getLength(int fd) const
  {
    if (fd == fd_)
    {
      return transport_ -> length();
    }

    int channelId = getChannel(fd);

    if (channelId < 0 || channels_[channelId] == NULL)
    {
      return 0;
    }

    return transports_[channelId] -> length();
  }

  int getPending(int fd) const
  {
    if (fd == fd_)
    {
      return transport_ -> pending();
    }

    int channelId = getChannel(fd);

    if (channelId < 0 || channels_[channelId] == NULL)
    {
      return 0;
    }

    return transports_[channelId] -> pending();
  }

  //
  // Check if the proxy or the given channel
  // has data in the buffer because of a
  // blocking write.
  //

  int getBlocked(int fd) const
  {
    if (fd == fd_)
    {
      return transport_ -> blocked();
    }

    int channelId = getChannel(fd);

    if (channelId < 0 || channels_[channelId] == NULL)
    {
      return 0;
    }

    return transports_[channelId] -> blocked();
  }

  //
  // Check if the proxy or the given channel has
  // data to read.
  //

  int getReadable(int fd) const
  {
    if (fd == fd_)
    {
      return transport_ -> readable();
    }

    int channelId = getChannel(fd);

    if (channelId < 0 || channels_[channelId] == NULL)
    {
      return 0;
    }

    return transports_[channelId] -> readable();
  }

  //
  // Return a vale between 0 and 9 in the case
  // of the proxy descriptor.
  //

  int getCongestion(int fd) const
  {
    if (fd == fd_)
    {
      return (agent_ != nothing && congestions_[agent_] == 1 ? 9 :
                  (int) statistics -> getCongestionInFrame());
    }

    int channelId = getChannel(fd);

    if (channelId < 0 || channels_[channelId] == NULL)
    {
      return 0;
    }

    return channels_[channelId] -> getCongestion();
  }

  //
  // Let the statistics class get info
  // from the message stores.
  //

  const ClientStore * const getClientStore() const
  {
    return clientStore_;
  }

  const ServerStore * const getServerStore() const
  {
    return serverStore_;
  }

  //
  // These can be called asynchronously by
  // channels during their read or write
  // loop.
  //

  int handleAsyncRead(int fd)
  {
    return handleRead(fd);
  }

  int handleAsyncCongestion(int fd)
  {
    int channelId = getChannel(fd);

    return handleControl(code_begin_congestion, channelId);
  }

  int handleAsyncDecongestion(int fd)
  {
    int channelId = getChannel(fd);

    return handleControl(code_end_congestion, channelId);
  }

  int handleAsyncSplit(int fd, Split *split)
  {
    return channels_[getChannel(fd)] ->
               handleSplitEvent(encodeBuffer_, split);
  }

  int handleAsyncPriority()
  {
    if (control -> FlushPriority == 1)
    {
      return handleFlush();
    }

    return 0;
  }

  int canAsyncFlush() const
  {
    return shouldFlush();
  }

  int handleAsyncFlush()
  {
    return handleFlush();
  }

  int handleAsyncSwitch(int fd)
  {
    return handleSwitch(getChannel(fd));
  }

  int handleAsyncKeeperCallback()
  {
    KeeperCallback();

    return 1;
  }

  //
  // Internal interfaces used to verify the
  // availability of channels and the proxy
  // link.
  //

  protected:

  int isTimeToRead() const
  {
    if (congestion_ == 0 && transport_ ->
            blocked() == 0)
    {
      return 1;
    }
    else
    {
      #if defined(TEST) || defined(INFO)
      *logofs << "Proxy: Can't read from channels "
              << "with congestion " << congestion_
              << " and blocked " << transport_ ->
                 blocked() << ".\n" << logofs_flush;
      #endif

      return 0;
    }
  }

  int isTimeToRead(int channelId) const
  {
    if (channelId >= 0 && channelId < CONNECTIONS_LIMIT &&
            channels_[channelId] != NULL &&
                congestions_[channelId] == 0)
    {
      if (channels_[channelId] -> getType() == channel_x11 ||
              tokens_[token_data].remaining > 0 ||
                  channels_[channelId] ->
                      getFinish() == 1)
      {
        return 1;
      }

      #if defined(TEST) || defined(INFO)
      *logofs << "Proxy: Can't read from generic "
              << "descriptor FD#" << getFd(channelId)
              << " channel ID#" << channelId << " with "
              << tokens_[token_data].remaining
              << " data tokens remaining.\n"
              << logofs_flush;
      #endif

      return 0;
    }

    #if defined(TEST) || defined(INFO)

    if (channelId < 0 || channelId >= CONNECTIONS_LIMIT ||
            channels_[channelId] == NULL)
    {
      *logofs << "Proxy: WARNING! No valid channel for ID#"
              << channelId << ".\n" << logofs_flush;
    }
    else if (channels_[channelId] -> getFinish())
    {
      *logofs << "Proxy: Can't read from finishing "
              << "descriptor FD#" << getFd(channelId)
              << " channel ID#" << channelId << ".\n"
              << logofs_flush;
    }
    else if (congestions_[channelId] == 1)
    {
      *logofs << "Proxy: Can't read from congested "
              << "descriptor FD#" << getFd(channelId)
              << " channel ID#" << channelId << ".\n"
              << logofs_flush;
    }

    #endif

    return 0;
  }

  //
  // Handle the flush and split timeouts.
  // All these functions should round up
  // to the value of the latency timeout
  // to save a further loop.
  //

  protected:

  int isTimeToSplit() const
  {
    if (isTimestamp(timeouts_.splitTs) &&
            getTimeToNextSplit() <= control ->
                LatencyTimeout)
    {
      if (tokens_[token_split].remaining > 0)
      {
        return 1;
      }

      #if defined(TEST) || defined(INFO)
      *logofs << "Proxy: WARNING! Can't encode splits "
              << "with " << tokens_[token_split].remaining
              << " split tokens remaining.\n"
              << logofs_flush;
      #endif
    }

    return 0;
  }

  int isTimeToMotion() const
  {
    return (isTimestamp(timeouts_.motionTs) &&
                getTimeToNextMotion() <= control ->
                    LatencyTimeout);
  }

  int getTimeToNextSplit() const
  {
    #if defined(TEST) || defined(INFO) || defined(FLUSH)

    if (isTimestamp(timeouts_.splitTs) == 0)
    {
      #ifdef PANIC
      *logofs << "Proxy: PANIC! No split timeout was set "
              << "for proxy FD#" << fd_ << ".\n"
              << logofs_flush;
      #endif

      cerr << "Error" << ": No split timeout was set "
           << "for proxy FD#" << fd_ << ".\n";

      HandleCleanup();
    }

    #endif

    int diffTs = timeouts_.split -
                     diffTimestamp(timeouts_.splitTs,
                         getTimestamp());

    return (diffTs > 0 ? diffTs : 0);
  }

  int getTimeToNextMotion() const
  {
    #if defined(TEST) || defined(INFO) || defined(FLUSH)

    if (isTimestamp(timeouts_.motionTs) == 0)
    {
      #ifdef PANIC
      *logofs << "Proxy: PANIC! No motion timeout was set "
              << "for proxy FD#" << fd_ << ".\n"
              << logofs_flush;
      #endif

      cerr << "Error" << ": No motion timeout was set "
           << "for proxy FD#" << fd_ << ".\n";

      HandleCleanup();
    }

    #endif

    int diffTs = timeouts_.motion -
                     diffTimestamp(timeouts_.motionTs,
                         getTimestamp());

    return (diffTs > 0 ? diffTs : 0);
  }

  protected:

  //
  // Implement persistence of cache on disk.
  //

  virtual int handleLoadFromProxy() = 0;
  virtual int handleSaveFromProxy() = 0;

  int handleLoadStores();
  int handleSaveStores();

995
  char *handleSaveAllStores(const char *savePath, bool & isTooSmall) const;
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 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 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

  virtual int handleSaveAllStores(ostream *cachefs, md5_state_t *md5StateStream,
                                      md5_state_t *md5StateClient) const = 0;

  int handleSaveVersion(unsigned char *buffer, int &major, int &minor, int &patch) const;

  void handleFailOnSave(const char *fullName, const char *failContext) const;

  const char *handleLoadAllStores(const char *loadPath, const char *loadName) const;

  virtual int handleLoadAllStores(istream *cachefs, md5_state_t *md5StateStream) const = 0;

  int handleLoadVersion(const unsigned char *buffer, int &major, int &minor, int &patch) const;

  void handleFailOnLoad(const char *fullName, const char *failContext) const;

  //
  // Prepare for a new persistent cache.
  //

  int handleResetPersistentCache();

  //
  // Reset the stores in the case of a
  // failure loading the cache.
  //

  int handleResetStores();

  //
  // Reset the transport buffer and the
  // other counters.
  //

  void handleResetFlush();

  //
  // Utility functions used to map file
  // descriptors to channel ids.
  //

  protected:

  int allocateChannelMap(int fd);
  int checkChannelMap(int channelId);
  int assignChannelMap(int channelId, int fd);

  void cleanupChannelMap(int channelId);

  virtual int checkLocalChannelMap(int channelId) = 0;

  int addControlCodes(T_proxy_code code, int data);
  int addTokenCodes(T_proxy_token &token);

  int getFd(int channelId) const
  {
    if (channelId >= 0 && channelId < CONNECTIONS_LIMIT)
    {
      return fdMap_[channelId];
    }

    return -1;
  }

  int getChannel(int fd) const
  {
    if (fd >= 0 && fd < CONNECTIONS_LIMIT)
    {
      return channelMap_[fd];
    }

    return -1;
  }

  protected:

  void setSplitTimeout(int channelId);
  void setMotionTimeout(int channelId);

  void increaseChannels(int channelId);
  void decreaseChannels(int channelId);

  int allocateTransport(int channelFd, int channelId);
  int deallocateTransport(int channelId);

  //
  // The proxy has its own transport.
  //

  ProxyTransport *transport_;

  //
  // The static compressor is shared among
  // channels and all the message stores.
  //

  StaticCompressor *compressor_;

  //
  // Map NX specific opcodes.
  //

  OpcodeStore *opcodeStore_;

  //
  // Stores are shared between channels.
  //

  ClientStore *clientStore_;
  ServerStore *serverStore_;

  //
  // Client and server caches are shared
  // between channels.
  //

  ClientCache *clientCache_;
  ServerCache *serverCache_;

  //
  // The proxy's file descriptor.
  //

  int fd_;

  //
  // Channels currently selected for I/O
  // operations.
  //

  int inputChannel_;
  int outputChannel_;

  //
  // List of active channels.
  //

  List activeChannels_;

  //
  // Used to read data sent from peer proxy.
  //

  ProxyReadBuffer readBuffer_;

  //
  // Used to send data to peer proxy.
  //

  EncodeBuffer encodeBuffer_;

  //
  // Control messages' array.
  //

  int controlLength_;

  unsigned char controlCodes_[CONTROL_CODES_LENGTH];

  //
  // Table of channel classes taking
  // care of open X connections.
  //

  Channel *channels_[CONNECTIONS_LIMIT];

  //
  // Table of open sockets.
  //

  Transport *transports_[CONNECTIONS_LIMIT];

  //
  // Timeout related data.
  //

  T_proxy_timeouts timeouts_;

  //
  // Proxy can be decoding messages,
  // handling a link reconfiguration,
  // or decoding statistics.
  //

  int operation_;

  //
  // True if we are currently draining
  // the proxy link.
  //

  int draining_;

  //
  // Force flush because of prioritized
  // control messages to send.
  //

  int priority_;

  //
  // Set if we have initiated the close
  // down procedure.
  //

  int finish_;

  //
  // Remote peer requested the shutdown.
  //

  int shutdown_;

  //
  // We are in the middle of a network
  // congestion in the path to remote
  // proxy.
  //

  int congestion_;

  //
  // Channels at the remote end that
  // are not consuming their data.
  //

  int congestions_[CONNECTIONS_LIMIT];

  //
  // Is the timer expired?
  //

  int timer_;

  //
  // Did the proxy request an alert?
  //

  int alert_;

  //
  // The channel id of the agent.
  //

  int agent_;

  //
  // Token related data.
  //

  T_proxy_token tokens_[TOKEN_TYPES];

  //
  // Pointer to stream descriptor where
  // proxy is producing statistics.
  //

  ostream *currentStatistics_;

  private:

  //
  // Map channel ids to file descriptors.
  //

  int channelMap_[CONNECTIONS_LIMIT];
  int fdMap_[CONNECTIONS_LIMIT];
};

#endif /* Proxy_H */