Module: IANA::Protocol

Defined in:
lib/iana/protocol.rb

Defined Under Namespace

Classes: Protocol

Class Method Summary collapse

Class Method Details

.load(pathname) ⇒ Object

load IANA protocols list from flat file: www.iana.org/assignments/protocol-numbers

Raises:

  • (ArgumentError)


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
# File 'lib/iana/protocol.rb', line 12

def self.load(pathname)
  raise ArgumentError, 'nil pathname' if pathname.nil?
  raise ArgumentError, 'invalid pathname class' if pathname.class != String
  raise ArgumentError, 'empty pathname' if pathname.empty?

  # TODO: better error checking for files with incorrect content

  protocols = {}
  updated = nil

  begin
    f = File.new(pathname, 'r')
    while (line = f.gets)
      line.chomp!

      # extract update stamp
      if line =~ /^\(last updated (\d{4}-\d{2}-\d{2})\)\s*$/
        updated = $1
        next
      end

      # match spaces d[dd][-ddd] spaces
      if line =~ /^\s+\d{1,3}([\-]{1}\d{3})?\s+/
        line.strip!
        line.gsub!(/\t/, ' ')
        line.gsub!(/\s{2,}/, '|')
        data = line.split('|')
        raw_decimal = data[0]

        if raw_decimal =~ /\-/
          first,second = raw_decimal.split(' ')
          raw_low,raw_high = first.split('-')
          low = raw_low.to_i
          high = raw_high.to_i
          low.upto(high) do |i|
            p = Protocol.new
            p.keyword = '<unassigned>'
            p.description = '<unassigned>'
            p.references = '[IANA]'
            protocols[i] = p
          end
        else
          p = Protocol.new
          decimal = raw_decimal.to_i
          case data.size
            when 3
              p.keyword = nil
              p.description = data[1]
              p.references = data[2]
            else
              p.keyword = data[1]
              p.description = data[2]
              p.references = data[3]
          end
          protocols[decimal] = p
        end
      end
    end
  ensure
    f.close if !f.nil?
  end

  return protocols, updated
end