guile-netlink/ip/utils.scm

utils.scm

1
;;;; This file is part of Guile Netlink
2
;;;;
3
;;;; Copyright (C) 2021 Julien Lepiller <julien@lepiller.eu>
4
;;;; 
5
;;;; This library is free software: you can redistribute it and/or modify
6
;;;; it under the terms of the GNU General Public License as published by
7
;;;; the Free Software Foundation, either version 3 of the License, or
8
;;;; (at your option) any later version.
9
;;;;
10
;;;; This library is distributed in the hope that it will be useful,
11
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
;;;; GNU General Public License for more details.
14
;;;;
15
;;;; You should have received a copy of the GNU General Public License
16
;;;; along with this library.  If not, see <https://www.gnu.org/licenses/>.
17
18
(define-module (ip utils)
19
  #:use-module (ice-9 match)
20
  #:use-module (netlink constant)
21
  #:use-module (netlink data)
22
  #:use-module (netlink error)
23
  #:use-module (netlink message)
24
  #:use-module (netlink route attrs)
25
  #:use-module (netlink standard)
26
  #:use-module (srfi srfi-34)
27
  #:use-module (srfi srfi-35)
28
  #:export (answer-ok?
29
            get-attr
30
            split-flags
31
            cidr->addr
32
            cidr->prefix))
33
34
(define (answer-ok? answer)
35
  (cond
36
    ((equal? (message-kind answer) NLMSG_DONE)
37
     #t)
38
    ((equal? (message-kind answer) NLMSG_ERROR)
39
     (let ((data (message-data answer)))
40
       (if (nl-data-data data)
41
           (let ((err (error-message-err data)))
42
             (if (equal? err 0)
43
                 #t
44
                 (raise (condition (&netlink-response-error (errno (- err)))))))
45
           (raise (condition (&netlink-response-error (errno 0)))))))))
46
47
(define (get-attr attrs type)
48
  (let ((attrs (filter (lambda (attr) (equal? (route-attr-kind attr) type)) attrs)))
49
    (match attrs
50
      (() #f)
51
      ((attr) (nl-data-data (route-attr-data attr))))))
52
53
(define (split-flags flags)
54
  (let loop ((max-flag 262144) (flags flags) (result '()))
55
    (cond
56
      ((equal? max-flag 1)
57
       (if (equal? flags 1)
58
           (cons 1 result)
59
           result))
60
      ((< flags max-flag)
61
       (loop (/ max-flag 2) flags result))
62
      (else
63
        (loop (/ max-flag 2) (- flags max-flag)
64
              (cons max-flag result))))))
65
66
(define (cidr->addr str)
67
  (match (string-split str #\/)
68
    ((addr) addr)
69
    ((addr prefix) addr)
70
    (_ (raise (condition (&netlink-cidr-error (str str)))))))
71
72
(define (cidr->prefix str)
73
  (match (string-split str #\/)
74
    ((addr) #f)
75
    ((addr prefix) (string->number prefix))
76
    (_ (raise (condition (&netlink-cidr-error (str str)))))))
77