aboutsummaryrefslogtreecommitdiffstats
path: root/modules/by-name/ns/nsd/dns/util/default.nix
blob: 59e661d760670e6b764a46183e8235fbd48cd89c (plain) (blame)
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
# SPDX-FileCopyrightText: 2021 Kirill Elagin <https://kir.elagin.me/>
#
# SPDX-License-Identifier: MPL-2.0 or MIT
{lib}: let
  inherit
    (builtins)
    concatStringsSep
    genList
    stringLength
    substring
    ;
  inherit
    (lib.strings)
    concatMapStrings
    concatMapStringsSep
    fixedWidthString
    splitString
    stringToCharacters
    ;
  inherit (lib.lists) filter reverseList;

  /*
  Split a string into byte chunks, such that each output String is less then or equal to
  `n` bytes.

  # Type

  splitInGroupsOf :: Integer -> String -> [String]

  # Arguments

    n
    : The number of bytes to put into each String.

    s
    : The String to split.
  */
  splitInGroupsOf = n: s: let
    groupCount = (stringLength s - 1) / n + 1;
  in
    genList (i: substring (i * n) n s) groupCount;

  # : str -> str
  # Prepares a Nix string to be written to a zone file as a character-string
  # literal: breaks it into chunks of 255 (per RFC 1035, 3.3) and encloses
  # each chunk in quotation marks.
  writeCharacterString = s:
    if stringLength s <= 255
    then ''"${s}"''
    else concatMapStringsSep " " (x: ''"${x}"'') (splitInGroupsOf 255 s);

  # : str -> str, with length 4 (zeros are padded to the left)
  align4Bytes = fixedWidthString 4 "0";

  # : int -> str -> str
  # Expands "" to 4n zeros and aligns the rest on 4 bytes
  align4BytesOrExpand = n: v:
    if v == ""
    then (fixedWidthString (4 * n) "0" "")
    else align4Bytes v;

  # : str -> [ str ]
  # Returns the record of the ipv6 as a list
  mkRecordAux = v6: let
    splitted = splitString ":" v6;
    n = 8 - builtins.length (filter (x: x != "") splitted);
  in
    stringToCharacters (concatMapStrings (align4BytesOrExpand n) splitted);

  # : str -> str
  # Returns the reversed record of the ipv6
  mkReverseRecord = v6:
    concatStringsSep "." (reverseList (mkRecordAux v6)) + ".ip6.arpa";
in {
  inherit writeCharacterString mkReverseRecord;
}