| 1 |
from socket import * |
|---|
| 2 |
from threading import Timer |
|---|
| 3 |
import config |
|---|
| 4 |
|
|---|
| 5 |
class Beacon: |
|---|
| 6 |
|
|---|
| 7 |
UDPSock = socket(AF_INET, SOCK_DGRAM) |
|---|
| 8 |
UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) |
|---|
| 9 |
services = [] |
|---|
| 10 |
|
|---|
| 11 |
def add_service(self, service): |
|---|
| 12 |
self.services.append(service) |
|---|
| 13 |
self.send_beacon() |
|---|
| 14 |
|
|---|
| 15 |
def format_services(self): |
|---|
| 16 |
return ';'.join(self.services) |
|---|
| 17 |
|
|---|
| 18 |
def format_beacon(self, conntype): |
|---|
| 19 |
beacon = [] |
|---|
| 20 |
|
|---|
| 21 |
guid = config.getGUID() |
|---|
| 22 |
|
|---|
| 23 |
beacon.append('tivoconnect=1') |
|---|
| 24 |
beacon.append('swversion=1') |
|---|
| 25 |
beacon.append('method=%s' % conntype) |
|---|
| 26 |
beacon.append('identity=%s' % guid) |
|---|
| 27 |
|
|---|
| 28 |
beacon.append('machine=%s' % gethostname()) |
|---|
| 29 |
beacon.append('platform=pc') |
|---|
| 30 |
beacon.append('services=' + self.format_services()) |
|---|
| 31 |
|
|---|
| 32 |
return '\n'.join(beacon) |
|---|
| 33 |
|
|---|
| 34 |
def send_beacon(self): |
|---|
| 35 |
beacon_ips = config.getBeaconAddresses() |
|---|
| 36 |
for beacon_ip in beacon_ips.split(): |
|---|
| 37 |
if beacon_ip != 'listen': |
|---|
| 38 |
try: |
|---|
| 39 |
self.UDPSock.sendto(self.format_beacon('broadcast'), |
|---|
| 40 |
(beacon_ip, 2190)) |
|---|
| 41 |
except error, e: |
|---|
| 42 |
print e |
|---|
| 43 |
|
|---|
| 44 |
def start(self): |
|---|
| 45 |
self.send_beacon() |
|---|
| 46 |
self.timer = Timer(60, self.start) |
|---|
| 47 |
self.timer.start() |
|---|
| 48 |
|
|---|
| 49 |
def stop(self): |
|---|
| 50 |
self.timer.cancel() |
|---|
| 51 |
|
|---|
| 52 |
def listen(self): |
|---|
| 53 |
"""For the direct-connect, TCP-style beacon""" |
|---|
| 54 |
import thread |
|---|
| 55 |
|
|---|
| 56 |
def server(): |
|---|
| 57 |
import struct |
|---|
| 58 |
|
|---|
| 59 |
TCPSock = socket(AF_INET, SOCK_STREAM) |
|---|
| 60 |
TCPSock.bind(('', 2190)) |
|---|
| 61 |
TCPSock.listen(5) |
|---|
| 62 |
|
|---|
| 63 |
while True: |
|---|
| 64 |
|
|---|
| 65 |
client, address = TCPSock.accept() |
|---|
| 66 |
|
|---|
| 67 |
|
|---|
| 68 |
client_length = struct.unpack('!I', client.recv(4))[0] |
|---|
| 69 |
client_message = client.recv(client_length) |
|---|
| 70 |
|
|---|
| 71 |
print client_length |
|---|
| 72 |
|
|---|
| 73 |
|
|---|
| 74 |
message = self.format_beacon('connected') |
|---|
| 75 |
client.send(struct.pack('!I', len(message))) |
|---|
| 76 |
client.send(message) |
|---|
| 77 |
client.close() |
|---|
| 78 |
|
|---|
| 79 |
thread.start_new_thread(server, ()) |
|---|
| 80 |
|
|---|
| 81 |
if __name__ == '__main__': |
|---|
| 82 |
b = Beacon() |
|---|
| 83 |
|
|---|
| 84 |
b.add_service('TiVoMediaServer:9032/http') |
|---|
| 85 |
b.send_beacon() |
|---|