netlink.py revision 21e26b590d9f4d401ad50d4d8d2f3f03521d30db
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(prefix) and
83          not name.startswith(prefix + "F_") and
84          name.isupper() and
85          getattr(thismodule, name) == value):
86        return name
87    return value
88
89  def _Decode(self, command, family, nla_type, nla_data):
90    """No-op, nonspecific version of decode."""
91    return nla_type, nla_data
92
93  def _ParseAttributes(self, command, family, data):
94    """Parses and decodes netlink attributes.
95
96    Takes a block of NLAttr data structures, decodes them using Decode, and
97    returns the result in a dict keyed by attribute number.
98
99    Args:
100      command: An integer, the rtnetlink command being carried out.
101      family: The address family.
102      data: A byte string containing a sequence of NLAttr data structures.
103
104    Returns:
105      A dictionary mapping attribute types (integers) to decoded values.
106
107    Raises:
108      ValueError: There was a duplicate attribute type.
109    """
110    attributes = {}
111    while data:
112      # Read the nlattr header.
113      nla, data = cstruct.Read(data, NLAttr)
114
115      # Read the data.
116      datalen = nla.nla_len - len(nla)
117      padded_len = PaddedLength(nla.nla_len) - len(nla)
118      nla_data, data = data[:datalen], data[padded_len:]
119
120      # If it's an attribute we know about, try to decode it.
121      nla_name, nla_data = self._Decode(command, family, nla.nla_type, nla_data)
122
123      # We only support unique attributes for now.
124      if nla_name in attributes:
125        raise ValueError("Duplicate attribute %d" % nla_name)
126
127      attributes[nla_name] = nla_data
128      self._Debug("      %s" % str((nla_name, nla_data)))
129
130    return attributes
131
132  def __init__(self):
133    # Global sequence number.
134    self.seq = 0
135    self.sock = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, self.FAMILY)
136    self.sock.connect((0, 0))  # The kernel.
137    self.pid = self.sock.getsockname()[1]
138
139  def _Send(self, msg):
140    # self._Debug(msg.encode("hex"))
141    self.seq += 1
142    self.sock.send(msg)
143
144  def _Recv(self):
145    data = self.sock.recv(self.BUFSIZE)
146    # self._Debug(data.encode("hex"))
147    return data
148
149  def _ExpectDone(self):
150    response = self._Recv()
151    hdr = NLMsgHdr(response)
152    if hdr.type != NLMSG_DONE:
153      raise ValueError("Expected DONE, got type %d" % hdr.type)
154
155  def _ParseAck(self, response):
156    # Find the error code.
157    hdr, data = cstruct.Read(response, NLMsgHdr)
158    if hdr.type == NLMSG_ERROR:
159      error = NLMsgErr(data).error
160      if error:
161        raise IOError(error, os.strerror(-error))
162    else:
163      raise ValueError("Expected ACK, got type %d" % hdr.type)
164
165  def _ExpectAck(self):
166    response = self._Recv()
167    self._ParseAck(response)
168
169  def _SendNlRequest(self, command, data, flags):
170    """Sends a netlink request and expects an ack."""
171    length = len(NLMsgHdr) + len(data)
172    nlmsg = NLMsgHdr((length, command, flags, self.seq, self.pid)).Pack()
173
174    self.MaybeDebugCommand(command, nlmsg + data)
175
176    # Send the message.
177    self._Send(nlmsg + data)
178
179    if flags & NLM_F_ACK:
180      self._ExpectAck()
181
182  def _ParseNLMsg(self, data, msgtype):
183    """Parses a Netlink message into a header and a dictionary of attributes."""
184    nlmsghdr, data = cstruct.Read(data, NLMsgHdr)
185    self._Debug("  %s" % nlmsghdr)
186
187    if nlmsghdr.type == NLMSG_ERROR or nlmsghdr.type == NLMSG_DONE:
188      print "done"
189      return (None, None), data
190
191    nlmsg, data = cstruct.Read(data, msgtype)
192    self._Debug("    %s" % nlmsg)
193
194    # Parse the attributes in the nlmsg.
195    attrlen = nlmsghdr.length - len(nlmsghdr) - len(nlmsg)
196    attributes = self._ParseAttributes(nlmsghdr.type, nlmsg.family,
197                                       data[:attrlen])
198    data = data[attrlen:]
199    return (nlmsg, attributes), data
200
201  def _GetMsgList(self, msgtype, data, expect_done):
202    out = []
203    while data:
204      msg, data = self._ParseNLMsg(data, msgtype)
205      if msg is None:
206        break
207      out.append(msg)
208    if expect_done:
209      self._ExpectDone()
210    return out
211
212  def _Dump(self, command, msg, msgtype):
213    """Sends a dump request and returns a list of decoded messages."""
214    # Create a netlink dump request containing the msg.
215    flags = NLM_F_DUMP | NLM_F_REQUEST
216    length = len(NLMsgHdr) + len(msg)
217    nlmsghdr = NLMsgHdr((length, command, flags, self.seq, self.pid))
218
219    # Send the request.
220    self._Send(nlmsghdr.Pack() + msg.Pack())
221
222    # Keep reading netlink messages until we get a NLMSG_DONE.
223    out = []
224    while True:
225      data = self._Recv()
226      response_type = NLMsgHdr(data).type
227      if response_type == NLMSG_DONE:
228        break
229      out.extend(self._GetMsgList(msgtype, data, False))
230
231    return out
232