/usr/share/hplip/base/mdns.py is in hplip-data 3.14.3-0ubuntu3.4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | # -*- coding: utf-8 -*-
#
# (c) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Author: Don Welch
#
# RFC 1035
# Std Lib
import sys
import time
import socket
import select
import struct
import random
import re
import cStringIO
# Local
from g import *
import utils
MAX_ANSWERS_PER_PACKET = 24
QTYPE_A = 1
QTYPE_TXT = 16
QTYPE_SRV = 33
QTYPE_AAAA = 28
QTYPE_PTR = 12
QCLASS_IN = 1
def read_utf8(offset, data, l):
return offset+l, data[offset:offset+l].decode('utf-8')
def read_data(offset, data, l):
return offset+l, data[offset:offset+l]
def read_data_unpack(offset, data, fmt):
l = struct.calcsize(fmt)
return offset+l, struct.unpack(fmt, data[offset:offset+l])
def read_name(offset, data):
result = ''
off = offset
next = -1
first = off
while True:
l = ord(data[off])
off += 1
if l == 0:
break
t = l & 0xC0
if t == 0x00:
off, utf8 = read_utf8(off, data, l)
result = ''.join([result, utf8, '.'])
elif t == 0xC0:
if next < 0:
next = off + 1
off = ((l & 0x3F) << 8) | ord(data[off])
if off >= first:
log.error("Bad domain name (circular) at 0x%04x" % off)
break
first = off
else:
log.error("Bad domain name at 0x%04x" % off)
break
if next >= 0:
offset = next
else:
offset = off
return offset, result
def write_name(packet, name):
for p in name.split('.'):
utf8_string = p.encode('utf-8')
packet.write(struct.pack('!B', len(utf8_string)))
packet.write(utf8_string)
def create_outgoing_packets(answers):
index = 0
num_questions = 1
first_packet = True
packets = []
packet = cStringIO.StringIO()
answer_record = cStringIO.StringIO()
while True:
packet.seek(0)
packet.truncate()
num_answers = len(answers[index:index+MAX_ANSWERS_PER_PACKET])
if num_answers == 0 and num_questions == 0:
break
flags = 0x0200 # truncated
if len(answers) - index <= MAX_ANSWERS_PER_PACKET:
flags = 0x0000 # not truncated
# ID/FLAGS/QDCOUNT/ANCOUNT/NSCOUNT/ARCOUNT
packet.write(struct.pack("!HHHHHH", 0x0000, flags, num_questions, num_answers, 0x0000, 0x0000))
if num_questions:
# QNAME
write_name(packet, "_pdl-datastream._tcp.local") # QNAME
packet.write(struct.pack("!B", 0x00))
# QTYPE/QCLASS
packet.write(struct.pack("!HH", QTYPE_PTR, QCLASS_IN))
first_record = True
for d in answers[index:index+MAX_ANSWERS_PER_PACKET]:
answer_record.seek(0)
answer_record.truncate()
# NAME
if not first_packet and first_record:
first_record = False
write_name(answer_record, "_pdl-datastream._tcp.local")
answer_record.write(struct.pack("!B", 0x00))
else:
answer_record.write(struct.pack("!H", 0xc00c)) # Pointer
# TYPE/CLASS
answer_record.write(struct.pack("!HH", QTYPE_PTR, QCLASS_IN))
# TTL
answer_record.write(struct.pack("!I", 0xffff))
rdlength_pos = answer_record.tell()
# RDLENGTH
answer_record.write(struct.pack("!H", 0x0000)) # (adj later)
# RDATA
write_name(answer_record, d)
answer_record.write(struct.pack("!H", 0xc00c)) # Ptr
# RDLENGTH
rdlength = answer_record.tell() - rdlength_pos - 2
answer_record.seek(rdlength_pos)
answer_record.write(struct.pack("!H", rdlength))
answer_record.seek(0)
packet.write(answer_record.read())
packets.append(packet.getvalue())
index += 20
if first_packet:
num_questions = 0
first_packet = False
return packets
def detectNetworkDevices(ttl=4, timeout=10):
mcast_addr, mcast_port ='224.0.0.251', 5353
found_devices = {}
answers = []
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
x = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
x.connect(('1.2.3.4', 56))
intf = x.getsockname()[0]
x.close()
s.setblocking(0)
ttl = struct.pack('B', ttl)
except socket.error:
log.error("Network error")
return {}
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except (AttributeError, socket.error):
pass
try:
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, ttl)
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(intf) + socket.inet_aton('0.0.0.0'))
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP ,1)
except Exception, e:
log.error("Unable to setup multicast socket for mDNS: %s" % e)
return {}
now = time.time()
next = now
last = now + timeout
delay = 1
while True:
now = time.time()
if now > last:
break
if now >= next:
try:
for p in create_outgoing_packets(answers):
log.debug("Outgoing: (%d)" % len(p))
log.log_data(p, width=16)
s.sendto(p, 0, (mcast_addr, mcast_port))
except socket.error, e:
log.error("Unable to send broadcast DNS packet: %s" % e)
next += delay
delay *= 2
update_spinner()
r, w, e = select.select([s], [], [s], 0.5)
if not r:
continue
data, addr = s.recvfrom(16384)
if data:
update_spinner()
y = {'num_devices' : 1, 'num_ports': 1, 'product_id' : '', 'mac': '',
'status_code': 0, 'device2': '0', 'device3': '0', 'note': ''}
log.debug("Incoming: (%d)" % len(data))
log.log_data(data, width=16)
offset = 0
offset, (id, flags, num_questions, num_answers, num_authorities, num_additionals) = \
read_data_unpack(offset, data, "!HHHHHH")
log.debug("Response: ID=%d FLAGS=0x%x Q=%d A=%d AUTH=%d ADD=%d" %
(id, flags, num_questions, num_answers, num_authorities, num_additionals))
for question in range(num_questions):
update_spinner()
offset, name = read_name(offset, data)
offset, (typ, cls) = read_data_unpack(offset, data, "!HH")
log.debug("Q: %s TYPE=%d CLASS=%d" % (name, typ, cls))
fmt = '!HHiH'
for record in range(num_answers + num_authorities + num_additionals):
update_spinner()
offset, name = read_name(offset, data)
offset, info = read_data_unpack(offset, data, "!HHiH")
if info[0] == QTYPE_A: # ipv4 address
offset, result = read_data(offset, data, 4)
ip = '.'.join([str(ord(x)) for x in result])
log.debug("A: %s" % ip)
y['ip'] = ip
elif info[0] == QTYPE_PTR: # PTR
offset, name = read_name(offset, data)
log.debug("PTR: %s" % name)
y['mdns'] = name
answers.append(name.replace("._pdl-datastream._tcp.local.", ""))
elif info[0] == QTYPE_TXT:
offset, name = read_data(offset, data, info[3])
txt, off = {}, 0
while off < len(name):
l = ord(name[off])
off += 1
result = name[off:off+l]
try:
key, value = result.split('=')
txt[key] = value
except ValueError:
pass
off += l
log.debug("TXT: %s" % repr(txt))
try:
y['device1'] = "MFG:Hewlett-Packard;MDL:%s;CLS:PRINTER;" % txt['ty']
except KeyError:
log.debug("NO ty Key in txt: %s" % repr(txt))
if 'note' in txt:
y['note'] = txt['note']
elif info[0] == QTYPE_SRV:
offset, (priority, weight, port) = read_data_unpack(offset, data, "!HHH")
ttl = info[3]
offset, server = read_name(offset, data)
log.debug("SRV: %s TTL=%d PRI=%d WT=%d PORT=%d" % (server, ttl, priority, weight, port))
y['hn'] = server.replace('.local.', '')
elif info[0] == QTYPE_AAAA: # ipv6 address
offset, result = read_data(offset, data, 16)
log.debug("AAAA: %s" % repr(result))
else:
log.error("Unknown DNS record type (%d)." % info[0])
break
found_devices[y['ip']] = y
log.debug("Found %d devices" % len(found_devices))
return found_devices
|