1#!/usr/bin/python
2#
3# Copyright 2014 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Partial Python implementation of iproute functionality."""
18
19# pylint: disable=g-bad-todo
20
21import errno
22import os
23import socket
24import struct
25import sys
26
27import cstruct
28
29
30# Request constants.
31NLM_F_REQUEST = 1
32NLM_F_ACK = 4
33NLM_F_REPLACE = 0x100
34NLM_F_EXCL = 0x200
35NLM_F_CREATE = 0x400
36NLM_F_DUMP = 0x300
37
38# Message types.
39NLMSG_ERROR = 2
40NLMSG_DONE = 3
41
42# Data structure formats.
43# These aren't constants, they're classes. So, pylint: disable=invalid-name
44NLMsgHdr = cstruct.Struct("NLMsgHdr", "=LHHLL", "length type flags seq pid")
45NLMsgErr = cstruct.Struct("NLMsgErr", "=i", "error")
46NLAttr = cstruct.Struct("NLAttr", "=HH", "nla_len nla_type")
47
48# Alignment / padding.
49NLA_ALIGNTO = 4
50
51
52def PaddedLength(length):
53  # TODO: This padding is probably overly simplistic.
54  return NLA_ALIGNTO * ((length / NLA_ALIGNTO) + (length % NLA_ALIGNTO != 0))
55
56
57class NetlinkSocket(object):
58  """A basic netlink socket object."""
59
60  BUFSIZE = 65536
61  DEBUG = False
62  # List of netlink messages to print, e.g., [], ["NEIGH", "ROUTE"], or ["ALL"]
63  NL_DEBUG = []
64
65  def _Debug(self, s):
66    if self.DEBUG:
67      print s
68
69  def _NlAttr(self, nla_type, data):
70    datalen = len(data)
71    # Pad the data if it's not a multiple of NLA_ALIGNTO bytes long.
72    padding = "\x00" * (PaddedLength(datalen) - datalen)
73    nla_len = datalen + len(NLAttr)
74    return NLAttr((nla_len, nla_type)).Pack() + data + padding
75
76  def _NlAttrU32(self, nla_type, value):
77    return self._NlAttr(nla_type, struct.pack("=I", value))
78
79  def _GetConstantName(self, module, value, prefix):
80    thismodule = sys.modules[module]
81    for name in dir(thismodule):
82      if name.startswith("INET_DIAG_BC"):
83        continue
84      if (name.startswith(prefix) and
85          not name.startswith(prefix + "F_") and
86          name.isupper() and getattr(thismodule, name) == value):
87          return name
88    return value
89
90  def _Decode(self, command, msg, nla_type, nla_data):
91    """No-op, nonspecific version of decode."""
92    return nla_type, nla_data
93
94  def _ParseAttributes(self, command, msg, data):
95    """Parses and decodes netlink attributes.
96
97    Takes a block of NLAttr data structures, decodes them using Decode, and
98    returns the result in a dict keyed by attribute number.
99
100    Args:
101      command: An integer, the rtnetlink command being carried out.
102      msg: A Struct, the type of the data after the netlink header.
103      data: A byte string containing a sequence of NLAttr data structures.
104
105    Returns:
106      A dictionary mapping attribute types (integers) to decoded values.
107
108    Raises:
109      ValueError: There was a duplicate attribute type.
110    """
111    attributes = {}
112    while data:
113      # Read the nlattr header.
114      nla, data = cstruct.Read(data, NLAttr)
115
116      # Read the data.
117      datalen = nla.nla_len - len(nla)
118      padded_len = PaddedLength(nla.nla_len) - len(nla)
119      nla_data, data = data[:datalen], data[padded_len:]
120
121      # If it's an attribute we know about, try to decode it.
122      nla_name, nla_data = self._Decode(command, msg, nla.nla_type, nla_data)
123
124      # We only support unique attributes for now, except for INET_DIAG_NONE,
125      # which can appear more than once but doesn't seem to contain any data.
126      if nla_name in attributes and nla_name != "INET_DIAG_NONE":
127        raise ValueError("Duplicate attribute %s" % nla_name)
128
129      attributes[nla_name] = nla_data
130      self._Debug("      %s" % str((nla_name, nla_data)))
131
132    return attributes
133
134  def __init__(self):
135    # Global sequence number.
136    self.seq = 0
137    self.sock = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, self.FAMILY)
138    self.sock.connect((0, 0))  # The kernel.
139    self.pid = self.sock.getsockname()[1]
140
141  def MaybeDebugCommand(self, command, flags, data):
142    # Default no-op implementation to be overridden by subclasses.
143    pass
144
145  def _Send(self, msg):
146    # self._Debug(msg.encode("hex"))
147    self.seq += 1
148    self.sock.send(msg)
149
150  def _Recv(self):
151    data = self.sock.recv(self.BUFSIZE)
152    # self._Debug(data.encode("hex"))
153    return data
154
155  def _ExpectDone(self):
156    response = self._Recv()
157    hdr = NLMsgHdr(response)
158    if hdr.type != NLMSG_DONE:
159      raise ValueError("Expected DONE, got type %d" % hdr.type)
160
161  def _ParseAck(self, response):
162    # Find the error code.
163    hdr, data = cstruct.Read(response, NLMsgHdr)
164    if hdr.type == NLMSG_ERROR:
165      error = NLMsgErr(data).error
166      if error:
167        raise IOError(error, os.strerror(-error))
168    else:
169      raise ValueError("Expected ACK, got type %d" % hdr.type)
170
171  def _ExpectAck(self):
172    response = self._Recv()
173    self._ParseAck(response)
174
175  def _SendNlRequest(self, command, data, flags):
176    """Sends a netlink request and expects an ack."""
177    length = len(NLMsgHdr) + len(data)
178    nlmsg = NLMsgHdr((length, command, flags, self.seq, self.pid)).Pack()
179
180    self.MaybeDebugCommand(command, flags, nlmsg + data)
181
182    # Send the message.
183    self._Send(nlmsg + data)
184
185    if flags & NLM_F_ACK:
186      self._ExpectAck()
187
188  def _ParseNLMsg(self, data, msgtype):
189    """Parses a Netlink message into a header and a dictionary of attributes."""
190    nlmsghdr, data = cstruct.Read(data, NLMsgHdr)
191    self._Debug("  %s" % nlmsghdr)
192
193    if nlmsghdr.type == NLMSG_ERROR or nlmsghdr.type == NLMSG_DONE:
194      print "done"
195      return (None, None), data
196
197    nlmsg, data = cstruct.Read(data, msgtype)
198    self._Debug("    %s" % nlmsg)
199
200    # Parse the attributes in the nlmsg.
201    attrlen = nlmsghdr.length - len(nlmsghdr) - len(nlmsg)
202    attributes = self._ParseAttributes(nlmsghdr.type, nlmsg, data[:attrlen])
203    data = data[attrlen:]
204    return (nlmsg, attributes), data
205
206  def _GetMsg(self, msgtype):
207    data = self._Recv()
208    if NLMsgHdr(data).type == NLMSG_ERROR:
209      self._ParseAck(data)
210    return self._ParseNLMsg(data, msgtype)[0]
211
212  def _GetMsgList(self, msgtype, data, expect_done):
213    out = []
214    while data:
215      msg, data = self._ParseNLMsg(data, msgtype)
216      if msg is None:
217        break
218      out.append(msg)
219    if expect_done:
220      self._ExpectDone()
221    return out
222
223  def _Dump(self, command, msg, msgtype, attrs):
224    """Sends a dump request and returns a list of decoded messages.
225
226    Args:
227      command: An integer, the command to run (e.g., RTM_NEWADDR).
228      msg: A struct, the request (e.g., a RTMsg). May be None.
229      msgtype: A cstruct.Struct, the data type to parse the dump results as.
230      attrs: A string, the raw bytes of any request attributes to include.
231
232    Returns:
233      A list of (msg, attrs) tuples where msg is of type msgtype and attrs is
234      a dict of attributes.
235    """
236    # Create a netlink dump request containing the msg.
237    flags = NLM_F_DUMP | NLM_F_REQUEST
238    msg = "" if msg is None else msg.Pack()
239    length = len(NLMsgHdr) + len(msg) + len(attrs)
240    nlmsghdr = NLMsgHdr((length, command, flags, self.seq, self.pid))
241
242    # Send the request.
243    request = nlmsghdr.Pack() + msg + attrs
244    self.MaybeDebugCommand(command, flags, request)
245    self._Send(request)
246
247    # Keep reading netlink messages until we get a NLMSG_DONE.
248    out = []
249    while True:
250      data = self._Recv()
251      response_type = NLMsgHdr(data).type
252      if response_type == NLMSG_DONE:
253        break
254      elif response_type == NLMSG_ERROR:
255        # Likely means that the kernel didn't like our dump request.
256        # Parse the error and throw an exception.
257        self._ParseAck(data)
258      out.extend(self._GetMsgList(msgtype, data, False))
259
260    return out
261