rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
"""Handle received packets. | r"""Handle received packets. | def handle_packet(self, data, addr): """Handle received packets. |
>>> c.handle_packet("A"*6,()) DATA:UNKNOWN PREFIX! 414141 6 bytes from () | >>> c.handle_packet("AAA\x00\x00\x00\x01\xdc\xeb\xa0\x89hello",()) DATA:UNKNOWN PREFIX! 414141 16 bytes from () | def handle_packet(self, data, addr): """Handle received packets. |
c.nick(e.arguments()[0] + "_") | def on_nickinuse(c, e): print "Nickname in use" c.nick(e.arguments()[0] + "_") old_nick = e.arguments()[0] #new_nick = old_nick + "_" new_nick = old_nick[:-1] + chr(ord(old_nick[:1]) + 1) print "%s nick in use, using %s" % (old_nick, new_nick) cfg["irc_nick"] = new_nick c.nick(new_nick) | |
new_nick = old_nick[:-1] + chr(ord(old_nick[:1]) + 1) | new_nick = old_nick[:-1] + chr(ord(old_nick[-1]) + 1) | def on_nickinuse(c, e): print "Nickname in use" c.nick(e.arguments()[0] + "_") old_nick = e.arguments()[0] #new_nick = old_nick + "_" new_nick = old_nick[:-1] + chr(ord(old_nick[:1]) + 1) print "%s nick in use, using %s" % (old_nick, new_nick) cfg["irc_nick"] = new_nick c.nick(new_nick) |
(libsumi) CRC32 FAILURE: -2dca16cd vs 0e97bd2c | (libsumi) ** CRC32 Failure from ['foo'] in 1482184792: -2dca16cd vs 0e97bd2c | def check_crc(pkt): r'''Check the CRC32 of a packet, returning True if it is correct. >>> pkt = calc_crc("fooXXXX\0\0\0\0ZZZZZZ") >>> pkt 'fooXXXX\xd25\xe93ZZZZZZ' >>> check_crc(pkt) True >>> check_crc(pkt[0:11]) # Detect truncation (libsumi) CRC32 FAILURE: -2dca16cd vs 0e97bd2c False >>> check_crc('g' + pkt[... |
(libsumi) CRC32 FAILURE: -2dca16cd vs 55932270 | (libsumi) ** CRC32 Failure from ['goo'] in 1482184792: -2dca16cd vs 55932270 | def check_crc(pkt): r'''Check the CRC32 of a packet, returning True if it is correct. >>> pkt = calc_crc("fooXXXX\0\0\0\0ZZZZZZ") >>> pkt 'fooXXXX\xd25\xe93ZZZZZZ' >>> check_crc(pkt) True >>> check_crc(pkt[0:11]) # Detect truncation (libsumi) CRC32 FAILURE: -2dca16cd vs 0e97bd2c False >>> check_crc('g' + pkt[... |
SRC_IP_MASK = (0xffffffffL >> (32 - cidr) << (32 - cidr)) | SRC_IP_MASK = ~(0xffffffffL << cidr) & 0xffffffffL | def set_src_allow(allow_cidr): """Set the allowed source address in CIDR-notation. For example: set_src_allow("4.0.0.0/24") -> allow 4.0.0.0 - 4.255.255.255""" global SRC_IP_MASK, SRC_IP_ALLOW (allow, cidr) = allow_cidr.split("/") cidr = int(cidr) SRC_IP_MASK = (0xffffffffL >> (32 - cidr) << (32 - cidr)) allow_list = m... |
(SRC_IP_ALLOW, ) = struct.unpack("L", struct.pack("BBBB", a, b, c, d)) | SRC_IP_ALLOW = d + c*256 + b*256**2 + a*256**3 | def set_src_allow(allow_cidr): """Set the allowed source address in CIDR-notation. For example: set_src_allow("4.0.0.0/24") -> allow 4.0.0.0 - 4.255.255.255""" global SRC_IP_MASK, SRC_IP_ALLOW (allow, cidr) = allow_cidr.split("/") cidr = int(cidr) SRC_IP_MASK = (0xffffffffL >> (32 - cidr) << (32 - cidr)) allow_list = m... |
file_info = struct.pack("!L", \ | file_info = struct.pack("!I", \ | def handle_send(nick, msg): """Handle sumi send -- setup a new transfer.""" log("%s is sumi sending" % nick) args = handle_request(nick, msg) try: #(file, offset, ip, port, mss, b64prefix, speed)=msg.split("\t") filename = args["f"] except: return sendmsg_error(nick, "not enough fields for send") log("FILE=%s" % fil... |
pkt += struct.pack("!L", seqno)[1:] | pkt += struct.pack("!I", seqno)[1:] | def datapkt(nick, seqno): """Send data packet number "seqno" to nick, for its associated file. Returns the length of the block sent. Delegates actual sending to a send_packet_* function.""" if seqno > 16777216: destroy_client(nick) return sendmsg_error(nick, "file too large: 8-10GB is "+ "the limit, depending on MSS")... |
raw_ip &= SRC_IP_MASK raw_ip |= SRC_IP_ALLOW str_ip = ".".join(map(str, struct.unpack("BBBB", struct.pack("L", raw_ip)))) | raw_ip &= SRC_IP_MASK raw_ip |= SRC_IP_ALLOW str_ip =".".join(map(str,struct.unpack("!BBBB", struct.pack("!I", raw_ip)))) | def randip(): """Generate a random IP and port to use as a source address.""" # CIDR notation; 4/24 = 4.0.0.0 - 4.255.255.255, masks, and TODO: excludes raw_ip = random.randint(0, 2 ** 32) raw_ip &= SRC_IP_MASK raw_ip |= SRC_IP_ALLOW str_ip = ".".join(map(str, struct.unpack("BBBB", struct.pack("L", raw_ip)))) # TODO: g... |
random_init() | if cfg["crypto"]: random_init() | def setup_config(): """Load file database and configuration.""" for offer in cfg["filedb"]: fn = offer["fn"] if not "gets" in offer: offer["gets"] = 0 if not "desc" in offer: offer["desc"] = fn try: size = os.path.getsize(fn) except OSError: fatal(21, ("Exception occured while reading size of %s" % fn)+ "\nPlease ch... |
def wrap(): try: self.crypto_thread(u["nick"]) except: print "(thread) Exception: %s at %s" % (x, sys.exc_info()[2].tb_lineno) raise x | def wrap(): try: self.crypto_thread(u["nick"]) except: #Exception, x: print "(thread) Exception: %s at %s" % (x, sys.exc_info()[2].tb_lineno) raise x | |
def wrap_thread(f, args): | def wrap_thread(self, f, args): | def wrap_thread(f, args): try: f(*args) except Exception, x: print "(thread) Exception: %s at %s" % (x, sys.exc_info()[2].tb_lineno) raise x |
return "Your download directory, %s, is not writable. You can \n"+\ | return "Your download directory, " + self.config["dl_dir"] + ", is not writable. You can \n"+\ | def validate_config(self): """Return None if configuration is valid, or an error message if not.""" if self.config.has_key("myip"): if self.config["myip"] != "": self.myip = self.config["myip"] else: self.myip = get_default_ip() print "Using IP: ", self.myip else: print "IP not specified, getting network interface list... |
"clicking the ... button." % self.config["dl_dir"] | "clicking the ... button." | def validate_config(self): """Return None if configuration is valid, or an error message if not.""" if self.config.has_key("myip"): if self.config["myip"] != "": self.myip = self.config["myip"] else: self.myip = get_default_ip() print "Using IP: ", self.myip else: print "IP not specified, getting network interface list... |
Please choose a real, valid IP address. If you are not sure what your IP is, go to http://whatismyip.coo/. Your IP can be set in the Client tab of sumigetw.""" % (self.myip, self.config["myip"]) | Please choose an Internet-accessible IP address. If you are not sure what your IP is, go to http://whatismyip.com/. Your IP can be set in the Client tab of sumigetw.""" % (self.myip, self.config["myip"]) | def validate_config(self): """Validate configuration after loading it, possibly modifying it by filling in defaults. |
if not os.access(self.config["dl_dir"], os.W_OK | os.X_OK | os.R_OK): | if len(self.config.get("dl_dir", "")) == 0 or not \ os.access(self.config["dl_dir"], os.W_OK | os.X_OK | os.R_OK): | def validate_config(self): """Validate configuration after loading it, possibly modifying it by filling in defaults. |
self.validate_config() | e = self.validate_config() if e: log("Configuration error") log(e) raise SystemExit | def main(self, transport, nick, filename): """Text-mode client. There isn't much user-friendliness here--the callbacks simply dump the passed arguments to stdout. There used to be an interactive interface, cli_user_input, but it is no longer supported. In the future, this interface should be more usable.""" |
if fs is None: | if fs is None or fs.closed: | def save_lost(self, u, finished=False): r'''Write the resume file for transfer from the user. |
fs.close() | def save_lost(self, u, finished=False): r'''Write the resume file for transfer from the user. | |
def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} | def recv_multipart(nick, msg): """Accumulate a continued message (beginning with >), returning True if the message is currently incomplete or False if the message is complete and should be processed. In order to handle messages which may be too long for the transport, we allow splitting up the message by beginning all... | def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} # handle multi-part segmented continued msgs, >asdf\n>asdf\nasdf if (msg[0] == ">"): if (not clients[nick].has_key("msg... |
return | return True | def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} # handle multi-part segmented continued msgs, >asdf\n>asdf\nasdf if (msg[0] == ">"): if (not clients[nick].has_key("msg... |
print nick, " is request security" args = msg[len("sumi sec "):] clients[nick] = { } clients[nick]["preauth"] = 1 clients[nick]["crypto"] = args[0] key_ = args[1:] clients[nick]["sec_acks"] = 0 if (clients[nick]["crypto"] >= "a" and clients[nick]["crypto"] <= "z"): clients[nick]["sec_acks"] = 1 try: print "Decodi... | return handle_sec(nick, msg) | def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} # handle multi-part segmented continued msgs, >asdf\n>asdf\nasdf if (msg[0] == ">"): if (not clients[nick].has_key("msg... |
print nick, "is sumi sending" if (clients.has_key(nick) and not clients[nick].has_key("preauth")): print "CLEARING LEFT OVERS" clients[nick].clear() msg = msg[len("sumi send "):] try: args = unpack_args(msg) print "ARGS=",args file = args["f"] offset = int(args["o"]) ip = args["i"] port = int(args["n"]... | return handle_send(nick, msg) | def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} # handle multi-part segmented continued msgs, >asdf\n>asdf\nasdf if (msg[0] == ">"): if (not clients[nick].has_key("msg... |
if (not clients.has_key(nick) or clients[nick]["authenticated"] != 1): return sendmsg_error(nick, "step 1 not complete") print "message: ", msg msg = msg[len("sumi auth "):] args = unpack_args(msg) print "args: ", args their_mss = int(args["m"]) asrc = args["s"] hash = args["h"] offset = int(args["o"]) ... | return handle_auth(nick, msg) | def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} # handle multi-part segmented continued msgs, >asdf\n>asdf\nasdf if (msg[0] == ">"): if (not clients[nick].has_key("msg... |
pass | return sendmsg_error(nick, "sumi dir not yet implemented") | def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} # handle multi-part segmented continued msgs, >asdf\n>asdf\nasdf if (msg[0] == ">"): if (not clients[nick].has_key("msg... |
print "Transfer to %s complete\n" % nick try: casts[clients[nick]["addr"]].remove(nick) except: pass if (clients[nick].has_key("file")): cfg["filedb"][clients[nick]["file"]]["gets"] += 1 print "NUMBER OF GETS: ", cfg["filedb"][clients[nick]["file"]]["gets"] else: print "Somehow lost filename" destroy_client(nick) | return handle_done(nick, msg) return True | def recvmsg(nick, msg, no_decrypt=0): """Handle an incoming message.""" if nick == None and msg == "on_exit": on_exit() print "<%s>%s" % (nick, msg) if not clients.has_key(nick): clients[nick] = {} # handle multi-part segmented continued msgs, >asdf\n>asdf\nasdf if (msg[0] == ">"): if (not clients[nick].has_key("msg... |
eth_hdr = pkt_data[0:14] ip_hdr = pkt_data[14:14+20] t_hdr = pkt_data[14+20:14+20+transport_size] | def get_transport_data(pkt_data, transport_size): """Returns the data inside a transport header of transport_size encapsulated in IPv4 over Ethernet, or None.""" try: # TODO: Other transport types besides Ethernet eth_hdr = pkt_data[0:14] # Dst MAC, src MAC, ethertype ip_hdr = pkt_data[14:14+20] # 20-byte IPv4 hea... | |
if 0 and clients[nick]["mcast"]: | if clients[nick]["mcast"]: | def xfer_thread_loop(nick): """Transfer the file, possibly in a loop for multicast.""" if 0 and clients[nick]["mcast"]: i = 0 while 1: print "Multicast detected - loop #%d" % i # "data carousel" i += 1 xfer_thread(nick) else: xfer_thread(nick) |
blocksz = clients[nick]["mss"] - SUMIHDRSZ | def xfer_thread(nick): """File transfer thread, called for each file transfer.""" print "clients[nick][seqno] exists?", clients[nick].has_key("seqno") blocksz = clients[nick]["mss"] - SUMIHDRSZ while 1: # Resend queued resends if they come up, but don't dwell try: while 1: resend = resend_queue.get_nowait() # TODO: ... | |
if (msg[0] == "k"): | if msg[0] == "k": | def transfer_control(nick, msg): """Handle an in-transfer control message.""" global resend_queue print "(authd)%s: %s" % (nick, msg) if (msg[0] == "k"): # TFTP-style transfer, no longer supported here pass elif (msg[0] == "n"): # n<win>,<resend-1>,<resend-2> (neg acks) resends = msg[1:].split(",") resends... |
elif (msg[0] == "n"): resends = msg[1:].split(",") resends.reverse() if (msg == "n"): if (not clients[nick].has_key("last_winsz")): winsz = 1024 else: winsz = clients[nick]["last_winsz"] else: winsz = int(resends.pop()) clients[nick]["last_winsz"] = winsz clients[nick]["ack_ts"] = time.time() if (clients[nick]["xfer_l... | elif msg[0] == "n": handle_nak(nick, msg) | def transfer_control(nick, msg): """Handle an in-transfer control message.""" global resend_queue print "(authd)%s: %s" % (nick, msg) if (msg[0] == "k"): # TFTP-style transfer, no longer supported here pass elif (msg[0] == "n"): # n<win>,<resend-1>,<resend-2> (neg acks) resends = msg[1:].split(",") resends... |
Returns the length of the block sent.""" if (seqno > 16777216): clients[nick] = [] return sendmsg_error(nick, "file too large") if (random.randint(0, 100) == 0): | Returns the length of the block sent. Delegates actual sending to a send_packet_* function.""" if seqno > 16777216: destroy_client(nick) return sendmsg_error(nick, "file too large: 8-10GB is "+ "the limit, depending on MSS") if cfg["noise"] and random.randint(0, int(cfg["noise"])) == 0: | def datapkt(nick, seqno): """Send data packet number "seqno" to nick, for its associated file. Returns the length of the block sent.""" if (seqno > 16777216): # 8-10GB is limit, depends on MSS clients[nick] = [] return sendmsg_error(nick, "file too large") if (random.randint(0, 100) == 0): # lose packet (testing p... |
a packet, use the <H format specifier.)""" sum=0 | a packet, use the <H format specifier.) From http://mail.python.org/pipermail/python-list/2003-January/137366.html with slight Pythonic improvements.""" csum=0 | def in_cksum(str): """Calculate the Internet checksum of str. (Note, when packing for a packet, use the <H format specifier.)""" sum=0 countTo=(len(str)/2)*2 count=0 while count<countTo: thisVal=ord(str[count+1])*256+ord(str[count]) sum=sum+thisVal sum=sum & 0xffffffffL # Necessary? count=count+2 if countTo<len(str): ... |
sum=sum+thisVal sum=sum & 0xffffffffL count=count+2 | csum+=thisVal csum&=0xffffffffL count+=2 | def in_cksum(str): """Calculate the Internet checksum of str. (Note, when packing for a packet, use the <H format specifier.)""" sum=0 countTo=(len(str)/2)*2 count=0 while count<countTo: thisVal=ord(str[count+1])*256+ord(str[count]) sum=sum+thisVal sum=sum & 0xffffffffL # Necessary? count=count+2 if countTo<len(str): ... |
sum=sum+ord(str[len(str)-1]) sum=sum & 0xffffffffL sum=(sum >> 16) + (sum & 0xffff) sum=sum+(sum >> 16) answer=~sum answer=answer & 0xffff | csum+=ord(str[len(str)-1]) csum&=0xffffffffL csum=(csum >> 16) + (csum & 0xffff) csum+=csum >> 16 answer=~csum answer&=0xffff | def in_cksum(str): """Calculate the Internet checksum of str. (Note, when packing for a packet, use the <H format specifier.)""" sum=0 countTo=(len(str)/2)*2 count=0 while count<countTo: thisVal=ord(str[count+1])*256+ord(str[count]) sum=sum+thisVal sum=sum & 0xffffffffL # Necessary? count=count+2 if countTo<len(str): ... |
else: fatal(23, "'dchanmode' must be one of: debug raw pcap libnet") return False | def send_packet_UDP(src, dst, payload): if cfg["dchanmode"] == "debug": # For debugging, no spoofing return send_packet_UDP_DEBUG(src, dst, payload) elif cfg["dchanmode"] == "raw": # Raw sockets return send_packet_UDP_SOCKET(src, dst, payload) elif cfg["dchanmode"] == "pcap": # Link-layer frames return send_pac... | |
set_options = 1 if (os.environ.has_key("RAWSOCKFD")): | set_options = True if os.environ.has_key("RAWSOCKFD"): | def setup_raw(argv): """Setup the raw socket. Only one raw socket is needed to send any number of packets, so it can be created at startup and root can be dropped; alternatively, a setuid program can set envar RAWSOCKFD and pass it here. The third option is to set raw_proxy in sumiserv.cfg to the address of a server ru... |
raw_proxy_addr_pw = cfg["raw_proxy"].split(" ") if len(raw_proxy_addr_pw) == 1: raw_proxy_ipport = raw_proxy_addr_pw[0] pw = "" elif len(raw_proxy_addr_pw) == 2: (raw_proxy_ipport, pw) = raw_proxy_addr_pw else: fatal(11, "Invalid raw proxy format: " + cfg["raw_proxy"]) raw_proxy_list = raw_proxy_ipport.split(":") if ... | setup_rawproxd() set_options = False | def setup_raw(argv): """Setup the raw socket. Only one raw socket is needed to send any number of packets, so it can be created at startup and root can be dropped; alternatively, a setuid program can set envar RAWSOCKFD and pass it here. The third option is to set raw_proxy in sumiserv.cfg to the address of a server ru... |
if (dir(os).__contains__("geteuid")): | if hasattr(os, "geteuid") and hasattr(os, "getuid"): | def setup_raw(argv): """Setup the raw socket. Only one raw socket is needed to send any number of packets, so it can be created at startup and root can be dropped; alternatively, a setuid program can set envar RAWSOCKFD and pass it here. The third option is to set raw_proxy in sumiserv.cfg to the address of a server ru... |
if (dir(os).__contains__("setuid")): | if hasattr(os, "setuid"): | def setup_raw(argv): """Setup the raw socket. Only one raw socket is needed to send any number of packets, so it can be created at startup and root can be dropped; alternatively, a setuid program can set envar RAWSOCKFD and pass it here. The third option is to set raw_proxy in sumiserv.cfg to the address of a server ru... |
fatal(15, "setsockopt IP_HDRINCL: ",err) | fatal(15, "setsockopt IP_HDRINCL: %s" % err) | def setup_raw(argv): """Setup the raw socket. Only one raw socket is needed to send any number of packets, so it can be created at startup and root can be dropped; alternatively, a setuid program can set envar RAWSOCKFD and pass it here. The third option is to set raw_proxy in sumiserv.cfg to the address of a server ru... |
fatal(16, "setsockopt SO_BROADCAST: ",err) | fatal(16, "setsockopt SO_BROADCAST: %s" % err) | def setup_raw(argv): """Setup the raw socket. Only one raw socket is needed to send any number of packets, so it can be created at startup and root can be dropped; alternatively, a setuid program can set envar RAWSOCKFD and pass it here. The third option is to set raw_proxy in sumiserv.cfg to the address of a server ru... |
include pcap_sendpacket (and also pcap_inject from OpenBSD).""" | include pcap_sendpacket (and also pcap_inject from OpenBSD, which we don't use).""" | def send_packet_UDP_PCAP(src, dst, payload): """Send a UDP packet using pcap's pcap_sendpacket. This call originated in WinPcap, but newer TcpDump versions of libpcap include pcap_sendpacket (and also pcap_inject from OpenBSD).""" # Regular socket() calls work fine on Win2K/XP, but WinPcap's will work # on 95, 98, Me..... |
gets = offer["gets"] | def setup_config(): """Load file database and configuration.""" for offer in cfg["filedb"]: gets = offer["gets"] fn = offer["fn"] desc = offer["desc"] try: size = os.path.getsize(fn) except OSError: fatal(21, ("Exception occured while reading size of %s" % fn)+ "\nPlease check that the file exists and is readable.")... | |
desc = offer["desc"] | if not "gets" in offer: offer["gets"] = 0 if not "desc" in offer: offer["desc"] = fn | def setup_config(): """Load file database and configuration.""" for offer in cfg["filedb"]: gets = offer["gets"] fn = offer["fn"] desc = offer["desc"] try: size = os.path.getsize(fn) except OSError: fatal(21, ("Exception occured while reading size of %s" % fn)+ "\nPlease check that the file exists and is readable.")... |
print "Re-reading config file" | print "Re-reading config file (got: ", a, b, ")" | def sigusr2(a, b): print "Re-reading config file" load_cfg() |
except KeyboardInterrupt, SystemExit: | except (KeyboardInterrupt, SystemExit): | def make_thread(f, arg): try: f(arg) except KeyboardInterrupt, SystemExit: on_exit() except KeyError: # Client finished while we were trying to help it, oh well print "Lost client" pass except: import sys x = sys.exc_info() print "Unhandled exception in ",f,": ",x[0]," line",x[2].tb_lineno,x[1] |
import sys | def make_thread(f, arg): try: f(arg) except KeyboardInterrupt, SystemExit: on_exit() except KeyError: # Client finished while we were trying to help it, oh well print "Lost client" pass except: import sys x = sys.exc_info() print "Unhandled exception in ",f,": ",x[0]," line",x[2].tb_lineno,x[1] | |
sys._exit(1) | def on_exit(): global config_file, cfg print "Cleaning up..." import pprint # pretty print instead of ugly print repr pprint.pprint(cfg, open(config_file, "w")) #print "CFG=",cfg sys.exit() sys._exit(1) raise SystemExit raise KeyboardInterrupt | |
def __init__(self): | def __init__(self, argv): self.argv = argv | def __init__(self): wx.App.__init__(self, 0) |
print "Sys args=", sys.argv if len(sys.argv) != 1: | print "Args=", self.argv if "-e" in self.argv: n = self.argv.index("-e") + 1 if n > len(self.argv): log("-e requires filename") raise SystemExit eval_fn = self.argv[n] if not os.access(eval_fn, os.R_OK): log("-e can't access %s, not readable" % eval_fn) raise SystemExit self.argv.remove("-e") self.argv.remove(eval_fn) ... | def OnInit(self): print "OnInit" # Setup receive requests thread/send requests. Do this first because # it might be the last thing we do. self.RecvReq() |
(self.ReqThread, [sys.argv[1:]])) | (self.ReqThread, [self.argv[1:]])) | def OnInit(self): print "OnInit" # Setup receive requests thread/send requests. Do this first because # it might be the last thing we do. self.RecvReq() |
if len(sys.argv) == 1: | if len(self.argv) == 1: | def OnInit(self): print "OnInit" # Setup receive requests thread/send requests. Do this first because # it might be the last thing we do. self.RecvReq() |
ss.send("\t".join(sys.argv[1:])) | ss.send("\t".join(self.argv[1:])) | def RecvReq(self): """Sets up the request receiving, passes to an existing instance if there is one, otherwise listens for commands using RecvReqThread. This is used to allow one sumigetw instance to handle multiple requests, not serving.""" |
def main(): | def main(argv=None): if argv is None: argv = sys.argv | def main(): print "Loading app..." app = SUMIApp() print "Running main loop" app.MainLoop() |
app = SUMIApp() | app = SUMIApp(argv) | def main(): print "Loading app..." app = SUMIApp() print "Running main loop" app.MainLoop() |
main() | sys.exit(main()) | def getSmallDnArrowImage(): import wx import cStringIO stream = cStringIO.StringIO(getSmallDnArrowData()) return wx.ImageFromStream(stream) |
if u.get("bytes", 0) >= u.get("size", -1): | if u.get("bytes", -1) >= u.get("size", 0): | def request(self, args): """Request a file from a server. args are (.sumi filename) or (transport, nick, filename). |
def save_lost(self, u, finished=0): """Write the resume file for transfer from the user.""" | def save_lost(self, u, finished=False): r'''Write the resume file for transfer from the user. The saved file will clobber the previous resume file, but will contain enough information to resume the transfer from its current state. The data is written to the filehandle from the "fs" key: >>> import tempfile >>> u = {}... | def save_lost(self, u, finished=0): """Write the resume file for transfer from the user.""" |
if finished: fs.close() | def save_lost(self, u, finished=0): """Write the resume file for transfer from the user.""" | |
only way to identify the source. Return None if no user.""" | only way to identify the source. Return None if no user. O(n) performance, time-wise. >>> c.senders["alice"] = {"prefix": 'ABC', "nick": 'alice'} >>> c.senders["bob"] = {"prefix": 'DEF', "nick": 'bob'} >>> c.prefix2user("ABC") == c.senders["alice"] True >>> c.prefix2user("DEF") == c.senders["bob"] True >>> c.... | def prefix2user(self, prefix): """Find user that is associated with the random prefix; which is the only way to identify the source. Return None if no user.""" # The data structures aren't setup very efficiently. for x in self.senders: if self.senders[x].has_key("prefix") and \ self.senders[x]["prefix"] == prefix: #xp... |
if self.senders[x].has_key("prefix") and \ self.senders[x]["prefix"] == prefix: | if self.senders[x].get("prefix") == prefix: | def prefix2user(self, prefix): """Find user that is associated with the random prefix; which is the only way to identify the source. Return None if no user.""" # The data structures aren't setup very efficiently. for x in self.senders: if self.senders[x].has_key("prefix") and \ self.senders[x]["prefix"] == prefix: #xp... |
if u["crypt_data"]: | if u.get("crypt_data"): | def handle_auth(self, u, prefix, addr, data): """Handle the authentication packet.""" log("Got auth packet from %s for %s" % (addr,u["nick"])) |
self.save_lost(u, 1) | self.save_lost(u, True) | def finish_xfer(self, u): """Finish the file transfer.""" |
if len(sys.argv) == 2 and sys.argv[1] == "-t": | if len(sys.argv) >= 2 and sys.argv[1] == "-t": | def doctest(): import doctest log("sumiget running doctests...") failures, tests = doctest.testmod()#verbose=1) sys.exit(failures != 0) |
ckeys.append(ecc(ord(random_bytes(1)))) | ckeys.append(ecc(ord(random_bytes(1)) + 1)) | def setup_transport_crypto(self, u): """Send sumi sec (secure) command, setting up an encrypted channel.""" log("Setting up cryptography...") |
elif x.eit is None: | else: | def isInTimer(self, eventid, begin, duration, service): time_match = 0 for x in self.timer_list: if str(x.service_ref) == str(service): #if x.eit is not None and x.repeated == 0: # if x.eit == eventid: # return duration if x.repeated != 0: chktime = localtime(begin) time = localtime(x.begin) chktimecmp = chktime.tm_wd... |
self.diseqccommand("store", int(self.positioner_storage.value) | self.diseqccommand("store", int(self.positioner_storage.value)) | def greenKey(self): entry = self.getCurrentConfigPath() if entry == "move": if self.isMoving: self.diseqccommand("stop") self.isMoving = False self.stopOnLock = False else: self.isMoving = True self.stopOnLock = True self.diseqccommand("moveWest", 0) self.updateColors("move") elif entry == "finemove": print "stepping w... |
parent["menu"].onSelectionChanged.append(self.selectionChanged) | def __init__(self, session, parent): Screen.__init__(self, session) self["MenuTitle"] = Label(parent.menu_title) self["MenuEntry"] = Label("") self["Clock"] = Clock() parent["menu"].onSelectionChanged.append(self.selectionChanged) self.parent = parent self.selectionChanged() | |
def finishedAlternativeSelection(self, args): self.alternatives[self["serviceslist"].getCurrent()[1]].append(str(ServiceReference(args))) addAlternative(self["serviceslist"].getCurrent()[1], str(ServiceReference(args))) self.updateAlternatives() | def finishedAlternativeSelection(self, *args): if len(args): self.alternatives[self["serviceslist"].getCurrent()[1]].append(str(ServiceReference(args))) addAlternative(self["serviceslist"].getCurrent()[1], str(ServiceReference(args))) self.updateAlternatives() | def finishedAlternativeSelection(self, args): self.alternatives[self["serviceslist"].getCurrent()[1]].append(str(ServiceReference(args))) addAlternative(self["serviceslist"].getCurrent()[1], str(ServiceReference(args))) self.updateAlternatives() |
self.close(True) | def okbuttonClick(self): self.selectedFunc(self["menu"].getCurrent()[1]) self.close(True) | |
self.session.openWithCallback(self.bouquetSelClosed, BouquetSelector, bouquets, self.addCurrentServiceToBouquet) | self.session.openWithCallback(self.bouquetSelClosed, BouquetSelector, bouquets, self.bouquetSelected) | def addServiceToBouquetSelected(self): bouquets = self.csel.getBouquetList() if bouquets is None: cnt = 0 else: cnt = len(bouquets) if cnt > 1: # show bouquet list self.session.openWithCallback(self.bouquetSelClosed, BouquetSelector, bouquets, self.addCurrentServiceToBouquet) elif cnt == 1: # add to only one existing b... |
self.volumeDialog.instance.setValue(eDVBVolumecontrol.getInstance().getVolume()) | self.volumeDialog.setValue(eDVBVolumecontrol.getInstance().getVolume()) | def toggleShow(self): if self.state == self.STATE_SHOWN: self.instance.hide() #pls check animation support, sorry |
print "update: " + str(self) + " SHOW" | def activateCondition(self, condition): if (condition): if (self.state == self.HIDDEN): print "update: " + str(self) + " SHOW" self.showWidget() else: if (self.state == self.SHOWN): print "update: " + str(self) + " HIDE" self.hideWidget() | |
print "update: " + str(self) + " HIDE" | def activateCondition(self, condition): if (condition): if (self.state == self.HIDDEN): print "update: " + str(self) + " SHOW" self.showWidget() else: if (self.state == self.SHOWN): print "update: " + str(self) + " HIDE" self.hideWidget() | |
"cancel": self.cancel, | "cancel": self.close, | def __init__(self, session, title): ChannelSelectionBase.__init__(self, session) self.title = title self.onShown.append(self.__onExecCallback) |
self.updateAlternatives() | def finishedChannelSelection(self, args): serviceString = str(ServiceReference(args)) if not self.alternatives.has_key(serviceString): self.alternatives[serviceString] = [] self.updateServices() self.updateAlternatives() self.selectService(serviceString) | |
self.updateAlternatives() | def finishedChannelSelection(self, args): serviceString = str(ServiceReference(args)) if not self.alternatives.has_key(serviceString): self.alternatives[serviceString] = [] self.updateServices() self.updateAlternatives() self.selectService(serviceString) | |
class SkinError(str): pass | class SkinError(Exception): def __init__(self, message): self.message = message def __str__(self): return self.message | def dump(x, i=0): print " " * i + str(x) try: for n in x.childNodes: dump(n, i + 1) except: None |
sec.setRotorPosNum(currSat.rotorposition.value) | sec.setRotorPosNum(currSat.rotorposition.value[0]) | def updateAdvanced(self, sec, slotid): lnbSat = {} for x in range(1,33): lnbSat[x] = [] for x in self.NimManager.satList: lnb = config.Nims[slotid].advanced.sat[x[1]].lnb.value if lnb != 0: print "add", x[1], "to", lnb lnbSat[lnb].append(x[1]) for x in range(1,33): if len(lnbSat[x]) > 0: currLnb = config.Nims[slotid].a... |
self.timer_list.remove(entry) | try: self.timer_list.remove(entry) except: pass | def removeEntry(self, entry): print "[Timer] Remove " + str(entry) |
sec.setLNBTunerMask(tunermask) | def addLNBSimple(self, sec, slotid, diseqcmode, toneburstmode = 0, diseqcpos = 0, orbpos = 0, longitude = 0, latitude = 0, loDirection = 0, laDirection = 0): #simple defaults sec.addLNB() tunermask = 1 << slotid if self.equal.has_key(slotid): tunermask |= (1 << self.equal[slotid]) elif self.linked.has_key(slotid): tune... | |
self.equal[nim.equalTo.value]=x | self.equal[nim.equalTo.index]=x | def update(self): sec = eDVBSatelliteEquipmentControl.getInstance() sec.clear() ## this do unlinking NIMs too !! print "sec config cleared" self.satList = [] |
self.linkNIMs(sec, x, nim.linkedTo.value) self.linked[nim.linkedTo.value]=x | self.linkNIMs(sec, x, nim.linkedTo.index) self.linked[nim.linkedTo.index]=x | def update(self): sec = eDVBSatelliteEquipmentControl.getInstance() sec.clear() ## this do unlinking NIMs too !! print "sec config cleared" self.satList = [] |
self.satposdepends[nim.satposDependsTo.value]=x | self.satposdepends[nim.satposDependsTo.index]=x | def update(self): sec = eDVBSatelliteEquipmentControl.getInstance() sec.clear() ## this do unlinking NIMs too !! print "sec config cleared" self.satList = [] |
"looptrough": _("loopthrough to socket A"), | "loopthrough": _("loopthrough to socket A"), | def nimPortDChanged(slotid, configElement): nimmgr.nimPortDChanged(slotid, configElement.value) |
default = "looptrough") | default = "loopthrough") | def nimPortDChanged(slotid, configElement): nimmgr.nimPortDChanged(slotid, configElement.value) |
exclusive_satellites = [0,0] print "exclusive satellites", exclusive_satellites | two_sat_tuners = False | def keyGo(self): scanList = [] if nimmanager.getNimType(0) == nimmanager.nimType["DVB-S"] and nimmanager.getNimType(0) == nimmanager.getNimType(1): sec = eDVBSatelliteEquipmentControl.getInstance() if sec is not None: exclusive_satellites = sec.get_exclusive_satellites(0,1) else: exclusive_satellites = [0,0] else: excl... |
if slotid > 0: idx = exclusive_satellites[0]+1 else: idx = 0 exclusive_nim_sats = exclusive_satellites[idx+1:idx+1+exclusive_satellites[idx]] print "exclusive_nim_sats", exclusive_nim_sats | if two_sat_tuners: if slotid > 0: idx = exclusive_satellites[0]+1 else: idx = 0 exclusive_nim_sats = exclusive_satellites[idx+1:idx+1+exclusive_satellites[idx]] print "exclusive_nim_sats", exclusive_nim_sats | def keyGo(self): scanList = [] if nimmanager.getNimType(0) == nimmanager.nimType["DVB-S"] and nimmanager.getNimType(0) == nimmanager.getNimType(1): sec = eDVBSatelliteEquipmentControl.getInstance() if sec is not None: exclusive_satellites = sec.get_exclusive_satellites(0,1) else: exclusive_satellites = [0,0] else: excl... |
if sat[1] in exclusive_nim_sats or slotid == 0: | if not two_sat_tuners or (sat[1] in exclusive_nim_sats or slotid == 0): | def keyGo(self): scanList = [] if nimmanager.getNimType(0) == nimmanager.nimType["DVB-S"] and nimmanager.getNimType(0) == nimmanager.getNimType(1): sec = eDVBSatelliteEquipmentControl.getInstance() if sec is not None: exclusive_satellites = sec.get_exclusive_satellites(0,1) else: exclusive_satellites = [0,0] else: excl... |
print "getting scope", scope, "with base", base | def resolveFilename(scope, base = ""): print "getting scope", scope, "with base", base path = defaultPaths[scope] print "path:", path if path[1] == PATH_CREATE: if (not pathExists(defaultPaths[scope][0])): os.mkdir(path[0]) if not fileExists(path[0] + base): #try: if fallbackPaths.has_key(scope): for x in fallbackPat... | |
print "path:", path | def resolveFilename(scope, base = ""): print "getting scope", scope, "with base", base path = defaultPaths[scope] print "path:", path if path[1] == PATH_CREATE: if (not pathExists(defaultPaths[scope][0])): os.mkdir(path[0]) if not fileExists(path[0] + base): #try: if fallbackPaths.has_key(scope): for x in fallbackPat... | |
ScanPossible = True | scanPossible = True | def keyGo(self): scanList = [] if nimmanager.getNimType(0) == nimmanager.nimType["DVB-S"] and nimmanager.getNimType(0) == nimmanager.getNimType(1): sec = eDVBSatelliteEquipmentControl.getInstance() if sec is not None: exclusive_satellites = sec.get_exclusive_satellites(0,1) else: exclusive_satellites = [0,0] print "exc... |
print data | def datatoFile(self, control, data): if control == ConfigSlider: return str(data) elif control == configSelection: if len(self.vals) < data + 1: return "0" if isinstance(self.vals[data], str): return str(data) else: confList = [] count = 0 for x in self.vals: if count == data: confList.append("*" + str(x[0] + "*")) els... | |
elif: | else: | def getBool(self): assert self.type in [self.LOCK, selef.BER], "the boolean output of FrontendInfo can only be used for lock or BER info" if self.type == self.LOCK: return self.source.lock elif: return self.source.ber > 0 |
servicepath = '(type == 1)' + servicepath[pos:] | if self.mode == MODE_TV: servicepath = '(type == 1)' + servicepath[pos:] else: servicepath = '(type == 2)' + servicepath[pos:] | def setCurrentSelection(self, service): servicepath = service.getPath() pos = servicepath.find(" FROM BOUQUET") if pos != -1: servicepath = '(type == 1)' + servicepath[pos:] service.setPath(servicepath) self.servicelist.setCurrent(service) |
return None | names = key.split('.') if len(names) > 1: if names[0] == "config": ret=self.__resolveValue(names[1:], config.content.items) if ret and len(ret): return ret print "getResolvedKey", key, "failed !! (Typo??)" return "" | def getResolvedKey(self, key): return None # FIXME |
self.terrestrialsList.append((tname, tname, tflags)) | self.terrestrialsList.append((tname, tflags)) | def startElement(self, name, attrs): if (name == "terrestrial"): #print "found sat " + attrs.get('name',"") + " " + str(attrs.get('position',"")) tname = attrs.get('name',"").encode("UTF-8") tflags = attrs.get('flags',"") self.terrestrialsList.append((tname, tname, tflags)) self.parsedTer = str(tname) elif (name == "tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.