-- Copyright (C) 1983  by Xerox Corporation. All rights reserved. 
-- TranslationServer.mesa, HGM, 23-Sep-83 14:20:24

-- Provide a Pup address for machines that have a 48 bit host number.

DIRECTORY
  System USING [NetworkAddress],

  Buffer USING [NSBuffer],
  NameServerDefs USING [NSNameServer],
  Socket USING [
    ChannelHandle, Create, defaultWaitTime, Delete, GetPacket,
    LocalAddressFromSocket, ReturnBuffer, SetWaitTime, SwapSourceAndDestination,
    TimeOut],
  NSConstants USING [pupAddressTranslation];

TranslationServer: PROGRAM IMPORTS Socket, NameServerDefs =
  BEGIN

  -- These should move to NSTypes
  translationRequest: CARDINAL = 1;
  translationResponse: CARDINAL = 2;
  translationError: CARDINAL = 3;

  pleaseStop: BOOLEAN;
  translationFork: PROCESS;

  CreateServer: PUBLIC PROCEDURE =
    BEGIN
    pleaseStop ← FALSE;
    translationFork ← FORK TranslationServer[];
    END;

  -- The Cache and File modules are not prepared to unwind.
  --  DeleteServer: PUBLIC PROCEDURE =
  --    BEGIN
  --    pleaseStop ← TRUE;
  --    JOIN translationFork;
  --    END;

  TranslationServer: PROCEDURE =
    BEGIN
    cH: Socket.ChannelHandle;
    localAddr: System.NetworkAddress;
    b: Buffer.NSBuffer;
    localAddr ← Socket.LocalAddressFromSocket[
      NSConstants.pupAddressTranslation];
    cH ← Socket.Create[localAddr, 0, 2];
    Socket.SetWaitTime[cH, Socket.defaultWaitTime];
    UNTIL pleaseStop DO
      b ← NIL;
      b ← Socket.GetPacket[cH ! Socket.TimeOut => CONTINUE];
      IF b = NIL THEN LOOP;
      IF b.ns.nsWords[2] = translationRequest THEN
        BEGIN
        Socket.SwapSourceAndDestination[b];
        NameServerDefs.NSNameServer[cH, b];
        LOOP;
        END;
      Socket.ReturnBuffer[b];
      ENDLOOP;
    Socket.Delete[cH];
    END;

  CreateServer[];
  END.