gnatprove_11.2.3_f7ece6d3/share/examples/spark/tokeneer/tcpip.adb

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
------------------------------------------------------------------
-- Tokeneer ID Station Support Software
--
-- Copyright (2003) United States Government, as represented
-- by the Director, National Security Agency. All rights reserved.
--
-- This material was originally developed by Praxis High Integrity
-- Systems Ltd. under contract to the National Security Agency.
------------------------------------------------------------------

with Ada.Text_IO;
with Ada.Strings.Fixed;
with GNAT.Sockets;
with MsgProc;
with Ada.Command_Line;

use type GNAT.Sockets.Selector_Status;

package body TcpIp
  with SPARK_Mode => Off  --  exception handlers
is

   --
   -- Current SPRE information...
   --
   PortalPort : GNAT.Sockets.Port_Type := 12001;
   AdminPort  : GNAT.Sockets.Port_Type := 12000;

   type SPREMachineT is
   record
     Data   : String(1 .. 30);
     Length : Natural range 0 .. 30;
   end record;

   SPREMachine : SPREMachineT :=
     (Data => "                              ",
      Length => 20);

   -- Enumeration of the currently available servers
   type ServerT is (Admin,Portal);

   --
   -- PortTo:
   --
   --    Used internally to keep track of the state of
   --    each of the available SPRE device driver server ports.
   --

   type PortStateT is (Connected, NotConnected);

   -- Are we connected to the port? if so, which socket and channel?
   type PortInfoT is record
      State   : PortStateT;
      Socket  : GNAT.Sockets.Socket_Type;
      Channel : GNAT.Sockets.Stream_Access;
   end record;

   type ConnectStateT is array (ServerT) of PortInfoT;
   PortTo : ConnectStateT := (others  =>
                                 (State   => NotConnected,
                                  Socket  => GNAT.Sockets.No_Socket,
                                  Channel => GNAT.Sockets.Stream(
                                                 GNAT.Sockets.No_Socket) ));

   -- Has the socket library been initialized?
   type WinSockStateT is (Uninitialized, Initialized);
   WinSockState : WinSockStateT := Uninitialized;


   -- Once a socket is open, can use GNAT.Sockets.Check_Selector to
   -- monitor changes in state of a set of sockets. ReadSet and WriteSet
   -- represent the two sets of sockets that will be maintained.

   ReadSet      : GNAT.Sockets.Socket_Set_Type;
   WriteSet     : GNAT.Sockets.Socket_Set_Type;
   CheckStatus  : GNAT.Sockets.Selector_Status;
   CheckTimeout : constant Duration := 5.0;
   Selector     : GNAT.Sockets.Selector_Type;

   --------------------------------------------------------------------
   --
   -- Local Subprograms
   --
   --------------------------------------------------------------------

   --------------------------------------------------------------------
   -- StartDebug
   --
   -- Description:
   --   Starts a TCPIP log file.
   --
   -- Implementation Notes:
   --    Set to Null in delivered system.
   --
   --------------------------------------------------------------------
   procedure StartDebug
   is
      --      MyError : Ada.Text_IO.File_Type;

   begin
      null;

      --      Ada.Text_IO.Create(File => MyError,
      --                         Mode => Ada.Text_IO.Out_File,
      --                         Name => "TCPIP.Log");
      --      Ada.Text_Io.Close(MyError);
   end StartDebug;

   --------------------------------------------------------------------
   -- DebugOutput
   --
   -- Description:
   --   Writes a debug message to the TCPIP log file.
   --
   -- Implementation Notes:
   --    Set to Null in delivered system.
   --
   --------------------------------------------------------------------
   procedure DebugOutput(Text : String)
   is
      --      MyError : Ada.Text_IO.File_Type;

   begin

      null;
      --         Ada.Text_IO.Open(File => MyError,
      --                          Mode => Ada.Text_IO.Append_File,
      --                          Name => "TCPIP.Log");
      --         Ada.Text_IO.Put_Line(File => MyError,
      --                              Item => Text);
      --         Ada.Text_IO.Close(MyError);
   end DebugOutput;

   --------------------------------------------------------------------
   -- MsgToRead
   --
   -- Description:
   --    Checks whether there is a message waiting to be read from a socket.
   --
   -- Implementation Notes:
   --    Adds socket to ReadSet, so shouldn't really be a function...
   --
   --------------------------------------------------------------------
   function MsgToRead (Server : in ServerT) return Boolean is
      LocalReturn : Boolean := False;
   begin

      -- Add socket to the ReadSet, and check for a message
      -- from the Server.
      GNAT.Sockets.Set ( Item   => ReadSet,
                         Socket => PortTo(Server).Socket );

      GNAT.Sockets.Check_Selector ( Selector     => Selector,
                                    R_Socket_Set => ReadSet,
                                    W_Socket_Set => WriteSet,
                                    Status       => CheckStatus,
                                    Timeout      => CheckTimeout );

      if CheckStatus = GNAT.Sockets.Completed and then
         GNAT.Sockets.Is_Set( Item   => ReadSet,
                              Socket => PortTo(Server).Socket ) then

         LocalReturn := True;

      -- For debugging...
      else
         DebugOutput("Data not available to read");
      end if;

      return LocalReturn;

   end MsgToRead;

   --------------------------------------------------------------------
   -- ReadMsg
   --
   -- Description:
   --    Reads message from Server, terminating on reading the message
   --    delineation sequence (CR,LF). The Length field does not include
   --    the delineation sequence i.e. only length of actual message data.
   --
   -- Implementation Notes:
   --    There may well be more data to read. This will be 'cleared' when
   --    we next attempt to SendMsg.
   --
   --------------------------------------------------------------------
   procedure ReadMsg (Server  : in     ServerT;
                      Msg     :    out MessageT;
                      Success :    out Boolean)
   is
   begin
      Success := True;

      for i in MessageIndexT'Range loop

         Character'Read ( PortTo(Server).Channel,
                          Msg.Data(i) );

         if Msg.Data(i)     = ASCII.Lf and then
            Msg.Data(i - 1) = ASCII.Cr then

            Msg.Data(i - 1 .. i) := (others => ASCII.Nul);
            Msg.Length := i - 2;
            exit;

         end if;

      end loop;

      -- For debugging...
      DebugOutput("Rcvd: " & Msg.Data(1..Msg.Length));

   exception
      when E : others =>
         Success := False;
         DebugOutput("Read Error.");
   end ReadMsg;

   --------------------------------------------------------------------
   -- SendMsg
   --
   -- Description:
   --    Sends Msg.Data to Channel.
   --
   -- Implementation Notes:
   --    Check status of Socket before sending data. If the Socket has data
   --    waiting to be read, Success is set to false, and the channel is read
   --    until an exception is raised (to clear the channel).
   --
   --------------------------------------------------------------------
   procedure SendMsg (Server  : in     ServerT;
                      Msg     : in     MessageT;
                      Success :    out Boolean)
   is
   begin
      Success := False;

      GNAT.Sockets.Set ( Item   => WriteSet,
                         Socket => PortTo(Server).Socket );

      GNAT.Sockets.Check_Selector ( Selector     => Selector,
                                    R_Socket_Set => ReadSet,
                                    W_Socket_Set => WriteSet,
                                    Status       => CheckStatus,
                                    Timeout      => 0.01 );

      if GNAT.Sockets.Is_Set ( Item   => ReadSet,
                               Socket => PortTo(Server).Socket ) then

         GNAT.Sockets.Clear ( Item   => ReadSet,
                              Socket => PortTo(Server).Socket );

         declare
            DummyChar : Character;
         begin
            for i in MessageIndexT'Range loop
               Character'Read ( PortTo(Server).Channel,
                                DummyChar );
            end loop;

         exception
            when E : others =>
               DebugOutput("Socket had readable data.");

         end;

      elsif GNAT.Sockets.Is_Set ( Item   => WriteSet,
                                  Socket => PortTo(Server).Socket ) then

         GNAT.Sockets.Clear ( Item   => WriteSet,
                              Socket => PortTo(Server).Socket );

         Success := True;

         for i in MessageIndexT range 1 .. Msg.Length loop

            Character'Write ( PortTo(Server).Channel,
                              Msg.Data(i) );

         end loop;

         Character'Write ( PortTo(Server).Channel,
                           ASCII.Cr );
         Character'Write ( PortTo(Server).Channel,
                           ASCII.Lf );

      end if;

      -- For debugging...
      DebugOutput("Sent: " & Msg.Data(1..Msg.Length));

   exception
      when E : others =>
         DebugOutput("Send Error.");
   end SendMsg;

   ------------------------------------------------------------------
   -- CommsIsOK
   --
   -- Description:
   --    Extracts the value corresponding to the SPRE response code from Msg.
   --    Returns true if the code is 'OK'.
   --
   -- Implementation notes:
   --    Find the first quote, and check the value of the next two characters.
   --
   ------------------------------------------------------------------
   function CommsIsOK (Msg : MessageT) return Boolean is
      CodeStart : MessageLengthT;
   begin
      CodeStart := Ada.Strings.Fixed.Index(Source  => Msg.Data(1..Msg.Length),
                                           Pattern => "'") + 1;
      return Msg.Data(CodeStart..CodeStart+1) = "OK";
   end CommsIsOk;

   --------------------------------------------------------------------
   --
   -- Exported Subprograms
   --
   --------------------------------------------------------------------
   --------------------------------------------------------------------
   -- ConnectToSPRE
   --
   -- Implementation Notes:
   --    Initializes the socket library.
   --
   --------------------------------------------------------------------
   procedure ConnectToSPRE (IsAdmin : in     Boolean;
                            Success :    out Boolean)
   is
      Address      : GNAT.Sockets.Sock_Addr_Type := GNAT.Sockets.No_Sock_Addr;
      Server       : ServerT;
      DummyMessage : MessageT;
      ReadOK       : Boolean := False;
   begin
      -- First ensure that socket library is available.
      if WinSockState = Uninitialized then

         pragma Warnings (Off);
         --  The following call is no longer needed with latst GNAT version
         GNAT.Sockets.Initialize;
         pragma Warnings (On);
         WinSockState := Initialized;

         GNAT.Sockets.Create_Selector ( Selector => Selector );
      end if;


      -- Set up socket address and Server into PortTo
      Address.Addr := GNAT.Sockets.Addresses
        (E => GNAT.Sockets.Get_Host_By_Name
              (Name => SPREMachine.Data(1 .. SPREMachine.Length) ),
         N => 1);

      if IsAdmin then
         Address.Port := AdminPort;
         Server       := Admin;
      else
         Address.Port := PortalPort;
         Server       := Portal;
      end if;


      -- If we are already connected, then do nothing.
      if PortTo(Server).State = NotConnected then

         GNAT.Sockets.Create_Socket ( Socket => PortTo(Server).Socket );

         GNAT.Sockets.Set_Socket_Option (
             Socket => PortTo(Server).Socket,
             Level  => GNAT.Sockets.Socket_Level,
             Option => ( Name    => GNAT.Sockets.Reuse_Address,
                         Enabled => True ));

         GNAT.Sockets.Connect_Socket ( Socket => PortTo(Server).Socket,
                                       Server => Address );
         PortTo(Server).Channel := GNAT.Sockets.Stream (PortTo(Server).Socket);

         PortTo(Server).State := Connected;

         -- A message should be sent back, don't care about the
         -- content, just read and discard.
         if MsgToRead( Server => Server ) then

            ReadMsg ( Server  => Server,
                      Msg     => DummyMessage,
                      Success => ReadOK );

         end if;

      end if;

      -- Return success unless exception.
      Success := ReadOK;

   exception
      when E : others =>

         if IsAdmin then
            DebugOutput(   "Error connecting to server... "
                           & SPREMachine.Data(1 .. SPREMachine.Length)
                           & " Port"
                           & GNAT.Sockets.Port_Type'Image(AdminPort));
         else
            DebugOutput(   "Error connecting to server... "
                           & SPREMachine.Data(1 .. SPREMachine.Length)
                           & " Port"
                           & GNAT.Sockets.Port_Type'Image(PortalPort));
         end if;

         if PortTo(Server).State = Connected then
            GNAT.Sockets.Close_Socket (PortTo(Server).Socket);
         end if;
         Success := False;
   end ConnectToSPRE;

   --------------------------------------------------------------------
   -- DisconnectFromSPRE
   --
   -- Implementation Notes:
   --    Finalizes the socket library if both ports are disconnected.
   --
   --------------------------------------------------------------------
   procedure DisconnectFromSPRE (IsAdmin : in     Boolean;
                                 Success :    out Boolean)
   is
      Address      : GNAT.Sockets.Sock_Addr_Type := GNAT.Sockets.No_Sock_Addr;
      Server       : ServerT;
      OtherDevice  : ServerT;
      SendOK       : Boolean  := False;
   begin

      if WinSockState = Initialized then
         -- Set up socket address and Server into PortTo
         Address.Addr := GNAT.Sockets.Addresses
           (GNAT.Sockets.Get_Host_By_Name
                (SPREMachine.Data(1 .. SPREMachine.Length)),
            1);

         if IsAdmin then
            Address.Port := AdminPort;
            Server       := Admin;
            OtherDevice  := Portal;
         else
            Address.Port := PortalPort;
            Server       := Portal;
            OtherDevice  := Admin;
         end if;

         -- If we are not connected, then do nothing.
         if PortTo(Server).State = Connected then

            GNAT.Sockets.Close_Socket ( PortTo(Server).Socket );

            PortTo(Server).Socket  := GNAT.Sockets.No_Socket;
            PortTo(Server).Channel :=
              GNAT.Sockets.Stream (GNAT.Sockets.No_Socket);
            PortTo(Server).State   := NotConnected;

         end if;

         -- If all ports are closed, finalize socket library
         if PortTo(OtherDevice).State = NotConnected then

            GNAT.Sockets.Close_Selector ( Selector => Selector );
            pragma Warnings (Off);
            --  The following call is no longer needed with latest GNAT version
            GNAT.Sockets.Finalize;
            pragma Warnings (On);
            WinSockState := Uninitialized;

         end if;

      end if;

      Success := True;

   exception
      when E : others =>

         if IsAdmin then
            DebugOutput(   "Error disconnecting from server... "
                           & SPREMachine.Data(1 .. SPREMachine.Length)
                           & " Port"
                           & GNAT.Sockets.Port_Type'Image(AdminPort));
         else
            DebugOutput(   "Error disconnecting from server... "
                           & SPREMachine.Data(1 .. SPREMachine.Length)
                           & " Port"
                           & GNAT.Sockets.Port_Type'Image(PortalPort));
         end if;

         if PortTo(Server).State = Connected then
            GNAT.Sockets.Close_Socket (PortTo(Server).Socket);
         end if;
         Success := False;
   end DisconnectFromSPRE;

   --------------------------------------------------------------------
   -- OpenAll
   --
   -- Implementation Notes:
   --    Suppress success flags - TIS will shutdown after failure to
   --    communicate with peripherals.
   --
   --------------------------------------------------------------------
   procedure OpenAll (Success : out Boolean)
   is
      ConnectOK : Boolean;
   begin
      StartDebug;

      ConnectToSPRE (IsAdmin => True,
                     Success => Success);
      ConnectToSPRE (IsAdmin => False,
                     Success => ConnectOK);
      Success := Success and ConnectOK;

   end OpenAll;

   --------------------------------------------------------------------
   -- CloseAll
   --
   -- Implementation Notes:
   --    Suppress success flags - TIS will force closure by shutting down.
   --
   --------------------------------------------------------------------
   procedure CloseAll
   is
      Ignored : Boolean;
   begin
      DisconnectFromSPRE (IsAdmin => False,
                          Success => Ignored);
      DisconnectFromSPRE (IsAdmin => True,
                          Success => Ignored);

   end CloseAll;

   --------------------------------------------------------------------
   -- SendAndReceive
   --
   -- Implementation Notes:
   --    None.
   --
   --------------------------------------------------------------------
   procedure SendAndReceive (IsAdmin  : in     Boolean;
                             Outgoing : in     MessageT;
                             Incoming :    out MessageT;
                             Success  :    out Boolean)
   is
      Address : GNAT.Sockets.Sock_Addr_Type := GNAT.Sockets.No_Sock_Addr;
      Server  : ServerT;
      SendOK  : Boolean := False;
      ReadOK  : Boolean := False;
   begin

      if WinSockState = Initialized then

         -- Set up socket address and Server details
         Address.Addr := GNAT.Sockets.Addresses
            (GNAT.Sockets.Get_Host_By_Name
                 (SPREMachine.Data(1 .. SPREMachine.Length)),
             1);

         if IsAdmin then
            Address.Port := AdminPort;
            Server       := Admin;
         else
            Address.Port := PortalPort;
            Server       := Portal;
         end if;

         -- Communicate with the server
         if PortTo(Server).State = Connected then

            SendMsg  ( Server  => Server,
                       Msg     => Outgoing,
                       Success => SendOK );

            if MsgToRead( Server => Server ) then

               ReadMsg ( Server  => Server,
                         Msg     => Incoming,
                         Success => ReadOK );

            end if;

         end if;

      end if;

      Success := SendOK and ReadOK and CommsIsOK(Msg => InComing);

   exception
      when E : others =>

         DebugOutput( "Error communicating with server. " );
         Success := False;
   end SendAndReceive;

   --------------------------------------------------------------------
   -- Init
   --
   -- Implementation Notes:
   --    None.
   --
   --------------------------------------------------------------------
   procedure Init (Success :    out Boolean)
   is
      Arg_Count : constant Natural := Ada.Command_Line.Argument_Count;

      InvalidArgument : exception;

      procedure PrintHelp is
      begin
         Ada.Text_IO.Put_Line("Optional arguments are:");
         Ada.Text_IO.Put_Line("[<device server name> [<Workstation port> [<Portal #1 port>]]]");
         Ada.Text_IO.Put_Line("where <device server name> must not exceed 30 characters");
         Ada.Text_IO.Put_Line("                           - default value: " &
                              SPREMachine.Data(1..SPREMachine.Length));
         Ada.Text_IO.Put_Line("      <Workstation port>   is a numeric");
         Ada.Text_IO.Put_Line("                           - default value: " &
                              GNAT.Sockets.Port_Type'Image(AdminPort));
         Ada.Text_IO.Put_Line("      <Portal #1 port>     is a numeric ");
         Ada.Text_IO.Put_Line("                           - default value: " &
                              GNAT.Sockets.Port_Type'Image(PortalPort));

      end PrintHelp;

   begin
      pragma Warnings (Off);
      --  The following call is no longer needed with latest GNAT version
      GNAT.Sockets.Initialize; -- needed so we can safely call Host_Name below.
      pragma Warnings (On);

      Success := True;
      case Arg_Count is
         when 0 =>
            -- No argument, so default to localhost
            declare
               This_Host : constant String := GNAT.Sockets.Host_Name;
            begin
               if This_Host'Last > SPREMachine.Data'Last then
                  raise InvalidArgument;
               else
                  SPREMachine.Data
                    (1 .. This_Host'Last) := This_Host;
                  SPREMachine.Length := This_Host'Last;
               end if;
            end;
         when 1 | 2 | 3 =>
            if Ada.Command_Line.Argument(1) = "help" then
               PrintHelp;
               Success := False;
            else
               if Ada.Command_Line.Argument(1)'Last > SPREMachine.Data'Last then
                  raise InvalidArgument;
               else
                  SPREMachine.Data (1 .. Ada.Command_Line.Argument(1)'Last) :=
                    Ada.Command_Line.Argument(1);
                  SPREMachine.Length := Ada.Command_Line.Argument(1)'Last;
               end if;
               if Arg_Count >= 2 then
                  AdminPort :=
                    GNAT.Sockets.Port_Type'Value(Ada.Command_Line.Argument(2));
               end if;
               if Arg_Count >= 3 then
                  PortalPort :=
                    GNAT.Sockets.Port_Type'Value(Ada.Command_Line.Argument(3));
               end if;
            end if;
         when others =>
            Ada.Text_IO.Put_Line("Wrong number of Arguments - optional arguments are:");
            Ada.Text_IO.Put_Line("  [<device server name> [<Workstation port> [<Portal #1 port>]]]");
            Ada.Text_IO.Put_Line("  supply single argument 'help' for more information");
            Success := False;
      end case;

   exception

      when E : others =>

         Success := False;
         Ada.Text_IO.Put_Line("Invalid Arguments - optional arguments are:");
         Ada.Text_IO.Put_Line("  [<device server name> [<Workstation port> [<Portal #1 port>]]]");
         Ada.Text_IO.Put_Line("  supply single argument 'help' for more information");

   end Init;

end TcpIp;