#!/usr/bin/pil -script (car (nth (argv) 1)) (nth (argv) 2) 
#
# Parse, Merge & display /proc/net/route & 'ip -d -j -p route show' output -
# will maintain a global IDX Tree of routes :
#  *Routes* : idx tree of all loaded routes , created by :
#  'load_routes, which can be called with a single callable LISP argument,
#  which will be called with a 'rt' obj for every route, which has at least the
#  following "fields" ('assoc list) in its CDR and the key of the route IP Address
#  in its CAR. (idx (cdr rt) $ATTR) should return CONS (key, value) object
#  for KEY in:
#   ( 'dev : interface name or '*'
#     'dst : Destination of Route : Key of all *Routes* Nodes :
#            a string of the form:
#             <ip_dot_quad>'/'<prefix> :
#            where ip_dot_quad is of the form
#              ${DDDo1}.${DDDo2}.${DDDo3}.${DDD04}
#            , each $DDDoX being from 1 to 3 decimal digits
#            specifying an IPv4 address octet 0-255 8-bit number value,
#            and where 'prefix' is a decimal number from 0 to 32 , specifying
#            the number of network prefix bits in the address .
#            Only the Default Route has 0 prefix bits .
#
#     'gw : Gateway / VIA IP
#
#     'flg: comma separated Flag String:
#         "UP":	RTF_UP		0x0001		/* route usable		  	*/
#         "GW": RTF_GATEWAY	0x0002		/* destination is a gateway	*/
#	  "HO": RTF_HOST	0x0004		/* host entry (net otherwise)	*/
#         "RE": RTF_REINSTATE	0x0008		/* reinstate route after tmout	*/
#	  "DY": RTF_DYNAMIC	0x0010		/* created dyn. (by redirect)	*/
#         "MO":	RTF_MODIFIED	0x0020		/* modified dyn. (by redirect)	*/
#         "MT": RTF_MTU /MSS	0x0040		/* specific MTU for this route	*/
#         "WN": RTF_WINDOW	0x0080		/* per route window clamping	*/
#         "RT": RTF_IRTT        0x0100		/* Initial round trip time	*/
#         "RJ": RTF_REJECT	0x0200		/* Reject route			*/
#
#     'nref : Reference Count decimal number
#     'use  : kernel 'use' code
#     'metric: metric / priority decimal number
#     'mask  : IP Mask Address for Prefix of 'dst .
#     'mtu   : if RTF_MTU flag , then non-zero MTU is path maximum trasfer unit size
#     'mss   : advmss Window Clamping
#     'irtt  : Round-Trip-Time, IFF RTF_IRTT flag speified.
#
#    Can also have attributes added by IP Route Netlink -
#    note, these use transient string constants, not symbols,
#    for attribute names:
#     "type"  : Route Type  
#     "src"   : Source IP Address for Route
#     "protocol": kernel protocol
#     "scope" : Route scope: link, host, global
#   )
#  An existing function which expects such a 'rt' object is 'prnl_route',
#  which prints the route to standard output file descriptor (FD) 1 .
#
# Utilities:
#  tbd - see per-function documentation.
#
# Jason Vas Dias<jason.vas.dias@pttireland.ie> July 2023
#
# Load Includes: uses $PIL_INC include path:

# main:
(symbols 'RT 'pico)
(symbols '(RT pico))

(def '_was-argv NIL)

(when (not  L_RT_ArgV)
(def 'L_RT_ArgV 
 (if L_RT_ArgV 
  L_RT_ArgV
  (let (r (rest))
   (if r
    (if (lst? (car r)) (car r) r)
    (prog
     (setq _was_argv T)
     (argv)
    )
   )
  )
 )
)
)

#(out 2 (prinl "ARGV:" (sym L_RT_ArgV)))

(def 'L_RT_Args ())

(def 'pil_inc (%@ "getenv" 'S "PIL_INC"))

# see: https://github.com/aw/picolisp-json/blob/master/json.l
(load (pack pil_inc "/json.l") "/dev/null" )

(when (not (bool pil_inc))
 (set 'pil_inc (pack (%@ "getenv" 'S "HOME") "/pil"))
)
#
# Globals:

(def '*verbose* (if (=0 (%@ "getenv" 'P "L_RT_VERBOSE")) NIL T))

(def '*Routes*  NIL) # Global Tree of Routes

(def '*Endianness* 
 (in  (list "/usr/bin/bash" "-c" 
"echo '#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# warning LE
#else
# warning BE
#endif
' | gcc -E - 2>&1 | sed -nr '/\^.*\[\[:space:\]\]\(\(B|L\)E\)\[\[:space:\]\].\*\$/\{s/\^.*\[\[:space:\]\]\(\(B|L\)E\)\[\[:space:\]\]\.\*\$/\\1/g;p;\}'\;"
      )
  (any (pack (line NIL)))
 )
)

# Functions:

(de join ( c l )
 # Create string representation of List l , with one occurrence
 # of character 'c betwween each list item.
 (let (s ""
       lok '((c)(and (bool l) (lst? l) c))
      )
  (if (lok T)
   (loop (NIL l s)
    (if (lok (bool (cdr l)))
     (setq s (pack s (car l) c ) l (cdr l))
     (setq s (pack s (car l)) l NIL)
    )
   )
  )
 )
)

(de htonl (n)
 # Reverse High to Low Order of binary number n
 # as number returned.
 (if (= *Endianness* 'LE)
  (if (or (not (num? n)) (> n (- (>> -32 1) 1)))
   (throw (pack "Not an IP Address Number: " n))
   (|
    (>> -24 (& n 255))
    (>> -16 (& (>> 8 n) 255))
    (>> -8  (& (>> 16 n) 255))
            (& (>> 24 n) 255)
   )
  )
  n
 )
)

(de ipv4-quad ( n )
 # Return IPv4 Dotted Quad of 4 period ('.') separated 0-255 decimal octet numbers
 (if (or (not (num? n)) (> n (- (>> -32 1) 1)))
  (throw (pack "Not an IP Address Number: " n))
  (join "."
   (list
    (& (>> 24 n) 255)
    (& (>> 16 n) 255)
    (& (>> 8 n) 255)
    (& n 255)
   )
  )
 )
)

(de ipv4-mask-to-prefix ( n )
 # Return network prefix bits number for mask
 (if (or (not (num? n)) (> n (- (>> -32 1) 1)))
  (throw (pack "Not an IP Address Number: " n))
  (let
   (hb 0
    pn 32
   )
   (loop (T (> (& (>> (- hb) 1) n) 0) pn) (T (=0 pn) pn) (inc 'hb) (dec 'pn))
  )
 ) 
)

(de ipv4-prefix-to-mask ( n )
 # Return mask for network address prefix number
 (if (or (not (num? n)) (> n 32) (< n 0))
  (throw (pack "Not an IP Address Prefix Number: " n))
  (let
   (ls (- 32 n))
   (>> (- ls) (>> ls (- (>> (- 32) 1) 1)))
  )
 )  
)

(de ipv4-from-quad ( qs )
 # Return Hex IP in network byte order from ip dotted quad string
 (when (and (str? qs) (not (= qs "")))
  (let (octl (mapcar 'pack (split (chop qs) ".")))
   (when (= 4 (length (octl)))
    (let ((o1 o2 o3 o3) octl)
     (hex          
      (|(>> (- 24) (& o1 255))
        (>> (- 16) (& o2 255))
        (>> (- 8)  (& o3 255))
        (& o4 255)
      )
     )
    )
   )
  )
 )
)

(de ipv4-quad-pfx ( q )
 (if (and (bool q) (not (str? q)))
  (throw (pack "ipv4-quad-pfx: not string: " (sym q)))
  (if (not (bool q))
   (throw (pack "ipv4-quad-pfx: null q argument not allowed."))
   (let (octl (mapcar 'pack (split (chop q) "." "/")) pfx 32)
    (let (ln (length octl))
     (if (>= ln 4)
      (prog
       (when (> ln 4)
        (setq pfx (last octl))
       )
       (let ( (o1 o2 o3 o4 ig) (mapcar 'any octl) )
        (cons
         (hex          
           (| (>> (- 24) (& o1 255))
              (>> (- 16) (& o2 255))
              (>> (- 8)  (& o3 255))
              (& o4 255)
           )            
         )
         pfx
        )
       )
      )
      (if (and (> ln 0) (< ln 4))
       (let (ls 24 n 0 oN 0)
        (loop
         (when (< oN ln)
          (setq n (| n (>> (- ls) (& (pop octl) 255))))
         )
         (inc 'oN)
         (T (= (dec 'ls) 0) (cons (hex n) 32))
        )
       )
       (cons 0 32)
      )
     )
    )
   )
  )
 )
)

(de ipv4-route-flag ( f )
 # convert flag bitmask number 'f to flag string
 (let
  (b 0
   fs NI
   ft NIL
   fs+ '((i)
         (if (bool fs)
          (setq ft (con ft (cons i ())))
          (setq fs (setq ft (cons i ())))
         )
        )          
  )
  (loop
   (when (> (& f (>> (- (- (inc 'b) 1)) 1)) 0)
    (case b
     (1 (fs+ "UP"))
     (2 (fs+ "GW"))
     (3 (fs+ "HO"))
     (4 (fs+ "RE"))
     (5 (fs+ "DY"))
     (6 (fs+ "MO"))
     (7 (fs+ "MT"))
     (8 (fs+ "WN"))
     (9 (fs+ "RT"))
     (10 (fs+ "RJ"))
    )
   )
   (T (= b 10) (join "," fs))
  )
 )
)

(de ipv4-route-flags ( fs )
 # convert flag string 'fs to flag bitmask number.
 (let
  (f 0)
  (for flg (mapcar 'pack (split (chop fs) ","))
   (prog
    (case flg
     ( "UP" (setq f (| f 1)))
     ( "GW" (setq f (| f 2)))
     ( "HO" (setq f (| f 4)))
     ( "RE" (setq f (| f 8)))
     ( "DY" (setq f (| f 16)))
     ( "MO" (setq f (| f 32)))
     ( "MT" (setq f (| f 64)))
     ( "WN" (setq f (| f 128)))
     ( "RT" (setq f (| f 256)))
     ( "RJ" (setq f (| f 512)))
    )
    f
   )
  )
 )
)

(de route ( Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT  .  hex_ip)
 # Process a Route into the *Routes* tree & optionally print it.
 (let (dst NIL msk NIL flg NIL gw NIL)
  (if *verbose*
   (prog
    (prinl
     (join "^I"
      (list
       Iface 
       (setq dst (join "/" (list (ipv4-quad (htonl (hex Destination))) (ipv4-mask-to-prefix (htonl (hex Mask))))))
       (setq gw (ipv4-quad (htonl (hex Gateway))))
       (setq flg (ipv4-route-flag (hex Flags)))
       RefCnt
       Use
       Metric
       (setq msk (ipv4-quad (htonl (hex Mask))))
       MTU
       Window
       IRTT
      )
     )
    )
   )
   (prog
    (setq dst (join "/" (list (ipv4-quad (htonl (hex Destination))) (ipv4-mask-to-prefix (htonl (hex Mask))))))
    (setq gw (ipv4-quad (htonl (hex Gateway))))
    (setq flg (ipv4-route-flag (hex Flags)))
    (setq msk (ipv4-quad (htonl (hex Mask))))
   )
  )
  (when (and (bool dst) (bool gw) (bool flg) (bool msk))
   (let (attrs NIL)
    (prog
     (for c
      (list
       (cons 'dev Iface)      
       (cons 'dst dst)
       (cons 'gw  gw)
       (cons 'flg flg)
       (cons 'nref RefCnt)
       (cons 'use Use)
       (cons 'metric Metric)
       (cons 'mask msk)
       (cons 'mtu  MTU)
       (cons 'mss  Window)
       (cons 'irtt IRTT)
      )
      (idx 'attrs c T)
     )
     (idx '*Routes* (cons dst attrs) T)
    )
   )
  )
 ) 
)

(de load-routes ()
 # Populates *Routes* global '(idx ...) (IDX) index tree of Routes with
 # IDX trees of /proc/net/route attributes :
 # ( 'dst 'dev 'gw 'flg 'nref 'use 'metric 'nask 'mtu 'mss 'irtt ... )
 # AND merges with any OTHER attributes from 'ip -d -j -p route show' output .
 (prog
  (off *Routes*)
  # Parse /proc/net/route :
  (in '/proc/net/route
   (let ( cnt 0 tits NIL)
    (while (not (eof))
     (let
      (ln  (filter '((it)(when (bool it) it)) (mapcar 'pack (split (line NIL) " " "^I" "^M" "^J")))
       n   (and (bool ln) (lst? ln) (length ln))
      )
      (when (and (bool n) (== n 11))
       (if (not tits) # first line is "Variable Titles" line
        (prog
         (set 'tits (mapcar '((tit)(any tit)) ln))
         (when *verbose*
          (prinl (pack "^I" (sym tits)))
         )
        )
        (prog
         (apply 'route ln)
         (inc 'cnt)
        )
       )
      )
     )
    )
   )
  )
  # Parse 'ip -d -j -p route show' output:
  (in (list "/usr/sbin/ip" "-d" "-j" "-p" "route" "show") 
   (for o  (json-decode (fd) T)
    (let
     (dsti NIL
      idst (assoc "dst" o)
      odst NIL
     )
     (if (or (bool idst) (bool (setq idst (assoc 'dst o))))
      (let
       ( rtp (mapcar 'pack (split (chop (setq dsti (cdr idst))) "/"))
        (ip pfx) rtp
        is_default NIL
       )
       (prog
#        (prinl (sym ip) " / " (sym pfx))
        (if (and (bool ip) (not (bool pfx)))
         (prog
#          (prinl "NO PFX")
          (if (and (bool ip) (= ip "default"))
#           (prog  (prinl "A")
            (setq odst "0.0.0.0/0" is_default T)
#           )
#           (prog (prinl "B")
            (setq odst (copy (pack ip "/32")))
#           )
          )
         )
         (if (and (bool ip) (bool pfx))
          (setq odst dsti)
          (if (not (bool ip))
           (out 2 (prinl "NO IP: " (sym idst)))
           (setq odst  (pack ip "/32"))
          )
         )
        )
        (if (bool odst)
         (let
          (rt (lup *Routes* odst))
          (if (bool rt)
           (when (bool rt)
            (let (rta (cdr rt))
             (prog
              (when (and rta is_default)
               (idx 'rta (cons "default" "1") T)
              )
              (for attr o
               (when (not (= (car attr) 'dst))
                (let
                 (ea (lup rta (car attr)))
                 (prog
                  (if (bool ea)
                   (prog
 #                   (prinl "UPD ATTR: " (car attr) (cdr attr))
                    (when (not (= (cdr ea) (cdr attr)))
                     (con ea (copy (cdr attr)))
                    )
                   ) 
                   (prog
 #                   (prinl "INS ATTTR: " (car attr))
                    (cond
                     ((= "flags" (car attr))
                      (let
                       (flg (lup rta 'flg))
                       (when (bool flg)
                        (idx 'rta (cons "flags" (ipv4-route-flags (copy (cdr flg)))) T)
                       )
                      )
                     )
                     (T                   
                      (idx 'rta (cons (car attr) (copy (cdr attr))) T)
                     )
                    )
                   )
                  )
                 )
                )
               )
              )
             )
            )
           )
           (out 2 (prinl "route in 'ip route', not in /proc/net/route: " (cdr (lup o "dst"))))
          )
         )
         (prinl (sym idst) ": NO ODST") 
        ) # fi
       ) # prog
      ) # let
      (when (not (= o T)) (prinl "NO IDST : " (sym o)))
     ) # fi
    ) # let
   ) # for
  ) # in
  cnt
 ) # prog
)

(de prin_route (rt)
 # provide function to print each route entry
 (if (or (not (bool rt)) (not (lst? rt)) (not (bool (cdr rt))))
  (throw "rt argument cannot be NIL and must have a non-NIL (cdr).")
  (let
   (dst (car rt)
    atr (cdr rt)
    dstc (copy dst)
    dstr (loop
          (T (>= (length dstc) 23) dstc)
          (setq dstc (pack dstc " "))            
         )
    gws  ""
    pgws '((gws)
           (loop
            (T (>= (length gws) 23) dst)
            (setq gws (pack gws " "))            
           )
           gws 
         )
    fls ""
    pfls '((fls)
           (loop
            (T (>= (length fls) 16) dst)
            (setq fls (pack fls " "))            
           )
           fls
          )
    dvs ""
   )
   (prog
#    (out 2 (prinl "latr:" (bool latr) " ratr:" (bool ratr) " eq:" (== ratr latr)))
#    (out 2 (prinl (sym atr)))
    (let
     (dev (cdr (lup atr 'dev))
      gw  (cdr (lup atr 'gw))
      flg (cdr (lup atr 'flg))
      mtr (cdr (lup atr 'metric))
      r   NIL
     )
     (if (or (not (bool dst)) (not (bool dev)) (not (bool gw)) (not (bool flg)) (not (bool mtr)))
      (prog
       (out 2 (prinl "Bad Route: dst:" (not (bool dst)) " dev:" (not (bool dev)) " gw:" (not (bool gw)) " flg:" (not (bool flg)) " mtr:" (not (bool mtr))))
       (throw (pack "Invalid Route: " (sym rt)))
      )
      (prog
       (setq fls dev)
       (setq dvs (pfls (setq dvs dev)))
       (setq gws (pgws (setq gws gw)))
       (setq fls (pfls (setq fls flg)))
       (out 1 (prin dstr "^I" dvs "^I" gws "^I" fls "^I" mtr "^I{^I"))
       #       (out 2 (prinl (sym ratr)))
       (for r (idx 'atr)
        (when (and (bool r) (lst? r))
         (let
          ( (k . v) r )
          (case k
           (( "dst" "gw" "gateway" "dev" "flg" "metric"  ))
           (T
            (let (ov (any v))
             (when (or (not (num? ov)) (> ov 0))
              (out 1 (prin (pack k ":" v "^I")))
             )
            )
           )
          )
         )
        )
       )
       (out 1 (prinl "}"))
      )
     )
    )
   )
  )
 ) 
)

(de has-args( argl )
 (if (and (bool L_RT_Args) (> (length L_RT_Args) 0))
  T
  (if (and (bool argl) (> (length argl) 0))
   (let
    ( rtal   ()
      t_rtal ()
    )
    (for a argl
     (let
      (ours
        (case (uppc a)
         ( ( "-P" "-PR" "-PRN" "-PRINT" "-prin_route")
           T
         )
         (T
          NIL
         )
        )
      )
      (let
       ( theirs
         (if (and (not ours) (bool (getd (any a))))
          T
          NIL
         )
       )
       (prog
        (if ours
         (setq a 'prin_route)
         (when theirs
          (setq a (any a))
         )
        )
#        (out 2 (prinl "ARG:" a " ours: " ours " theirs: " theirs))
        (when (and (or ours theirs) a
                   (or (not (bool rtal))
                       (not (bool (member a rtal)))
                   )
              )
         (let (c (cons (any a)))
          (if (bool rtal)           
           (setq t_rtal (con t_rtal c))
           (setq rtal  (setq t_rtal c))
          )
#          (out 2 (prinl "RTAL: " (sym rtal)))          
         )
        )
       )
      )
     )
    )
    (bool (set 'L_RT_Args rtal))
   )
   (nil
    (out 2 (prinl "NO ARGS"))
   )
  )
 )
)

(de process-routes ()
 (prog
  (if (bool *Routes*)
   (for a1 L_RT_Args
    (let
     (prg (any a1)
      okr 0 
     )
     (prog
      (case prg
       (('-P "-P" '-p "-p" '-PR "-PR" '-pr "-pr") (setq prg 'prin_route))
       (( '-bye ) (setq prg NIL))
      )
      (when (and (bool prg) (not (lst? prg)))
       (setq prg (list prg))
      )
      (if (bool prg)
       (for rout (idx '*Routes*)
        (let
         (evl (append (copy prg) (cons (append (list 'quote) rout))))
         (prog
#           (out 2 (prinl "expr: " (sym evl)))         
          (if (not (bool (eval evl)))
           (prinl "eval failed for: " (sym rout))
           (inc 'okr)
          )
          (setq ok (if (> okr 0) 0 1))
          (when (and (bool rout) *verbose*)
           (prinl (sym rout))
          )
         )
        )
       )
       (out 2 (prinl (pack "No Last (Program/Function name) Argument: " (sym L_RT_Args))))
      )
     )
    )
   )
   (out 2 (prinl (pack "No Routes " (bool *Routes*) " / No Last Arg: " a1 (not (bool a1)))))
  )
 )
)
#(out 2 (prinl "ARGS NOW:" (sym L_RT_ArgV)))
(when (and _was-argv L_RT_argv (> (length L_RT_ARGV 0)))
 (let ((pth fil . lin) (file))
  (script (join "/" pth file) L_RT_ARGV)
 )
)

(when (and L_RT_ArgV (has-args L_RT_ArgV))
 (let (ok 0)
  (catch T ()
   (if (> (load-routes) 0)
    (process-routes)
    (out 2 (prinl (pack "No Routes " (bool *Routes*) " / No Last Arg: " (sym L_RT_ArgV))))
   )
   (finally
    (bye ok)
   )
  )
 )
)

(symbols '( pico ))
  
