rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return d def requestList(self, listType): """ request the desired list type @param listType: 2-letter list type (as defined by the *_LIST constants) @return: A Deferred, the callback of which will be fired when the list has been retrieved. The callback argument will be a tuple with the only element being a list of M...
def _cb(r): self.factory.status = r[0] return r return d.addCallback(_cb)
def changeStatus(self, status): """ change my current status.
""" set my privacy mode on the server. B{Note}: This only keeps the current privacy setting on the server for later retrieval, it does not effect the way the server works at all. @param privLevel: This parameter can be true, in which case the server will keep the state as 'al' which the official client interprets as ...
""" Set my privacy mode on the server. B{Note}: This only keeps the current privacy setting on the server for later retrieval, it does not effect the way the server works at all. @param privLevel: This parameter can be true, in which case the server will keep the state as 'al' which the official client interprets as ...
def setPrivacyMode(self, privLevel): """ set my privacy mode on the server.
self._setState('SYNC')
def syncList(self, version): """ used for keeping an up-to-date contact list.
return d def requestListGroups(self): """ Request (forward) list groups. @return: A Deferred, the callback for which will be called when the server responds with the list groups. The callback argument will be a tuple with two elements, a dictionary mapping group IDs to group names and the current list version. """ ...
def _cb(r): self.changeStatus(STATUS_ONLINE) if r[0] is not None: self.factory.contacts = r[0] return r return d.addCallback(_cb)
def syncList(self, version): """ used for keeping an up-to-date contact list.
""" used to create a new list group. @param name: The desired name of the new group. @return: A Deferred, the callbacck for which will be called when the server clarifies that the new group has been created. The callback argument will be a tuple with 3 elements: the new list version (int), the new group name (str) a...
""" Used to create a new list group. A default callback is added to the returned Deferred which updates the contacts attribute of the factory. @param name: The desired name of the new group. @return: A Deferred, the callbacck for which will be called when the server clarifies that the new group has been created. The...
def addListGroup(self, name): """ used to create a new list group.
return d
def _cb(r): self.factory.contacts.version = r[0] self.factory.contacts.setGroup(r[1], r[2]) return r return d.addCallback(_cb)
def addListGroup(self, name): """ used to create a new list group.
""" used to remove a list group.
""" Used to remove a list group. A default callback is added to the returned Deferred which updates the contacts attribute of the factory.
def remListGroup(self, groupID): """ used to remove a list group.
return d
def _cb(r): self.factory.contacts.version = r[0] self.factory.contacts.remGroup(r[1]) return r return d.addCallback(_cb)
def remListGroup(self, groupID): """ used to remove a list group.
""" used to rename an existing list group. @param groupID: the ID of the desired group to rename. @param newName: the desired new name for the group. @return: A Deferred, the callback for which will be called when the server clarifies the renaming. The callback argument will be a tuple of 3 elements, the new list ve...
""" Used to rename an existing list group. A default callback is added to the returned Deferred which updates the contacts attribute of the factory. @param groupID: the ID of the desired group to rename. @param newName: the desired new name for the group. @return: A Deferred, the callback for which will be called whe...
def renameListGroup(self, groupID, newName): """ used to rename an existing list group.
return d
def _cb(r): self.factory.contacts.version = r[0] self.factory.contacts.setGroup(r[1], r[2]) return r return d.addCallback(_cb)
def renameListGroup(self, groupID, newName): """ used to rename an existing list group.
""" used to add a contact to the desired list. @param listType: 2-letter list type (as defined by the *_LIST constants) @param userHandle: the user handle (passport) of the contact that is being added @param groupID: the group ID for which to associate this contact with. (default 0 - no group). Groups are only valid i...
""" Used to add a contact to the desired list. A default callback is added to the returned Deferred which updates the contacts attribute of the factory with the new contact information. @param listType: (as defined by the *_LIST constants) @param userHandle: the user handle (passport) of the contact that is being adde...
def addContact(self, listType, userHandle, groupID=0): """ used to add a contact to the desired list.
if listType.upper() == "FL":
listType = listIDToCode[listType].upper() if listType == "FL":
def addContact(self, listType, userHandle, groupID=0): """ used to add a contact to the desired list.
self.sendLine("ADD %s %s %s %s" % (id, listType.upper(), userHandle, userHandle)) return d
self.sendLine("ADD %s %s %s %s" % (id, listType, userHandle, userHandle)) def _cb(r): self.factory.contacts.version = r[2] c = self.factory.contacts.getContact(r[1]) if not c: c = MSNContact(userHandle=r[1]) if r[3]: c.groups.append(r[3]) c.addToList(r[0]) return r return d.addCallback(_cb)
def addContact(self, listType, userHandle, groupID=0): """ used to add a contact to the desired list.
""" used to remove a contact from the desired list. @param listType: 2-letter list type (as defined by the *_LIST constants) @param userHandle: the user handle (passport) of the contact being removed @param groupID: the ID of the group to which this contact belongs (only relevant in the forward list, default is 0) @r...
""" Used to remove a contact from the desired list. A default callback is added to the returned deferred which updates the contacts attribute of the factory to reflect the new contact information. @param listType: (as defined by the *_LIST constants) @param userHandle: the user handle (passport) of the contact being r...
def remContact(self, listType, userHandle, groupID=0): """ used to remove a contact from the desired list.
if listType.upper() == "FL":
listType = listIDToCode[listType].upper() if listType == "FL":
def remContact(self, listType, userHandle, groupID=0): """ used to remove a contact from the desired list.
self.sendLine("REM %s %s %s" % (id, listType.upper(), userHandle)) return d
self.sendLine("REM %s %s %s" % (id, listType, userHandle)) def _cb(r): l = self.factory.contacts l.version = r[2] c = l.getContact(r[1]) c.removeFromList(r[0]) if c.lists == 0: l.remContact(c.userHandle) return r return d.addCallback(_cb)
def remContact(self, listType, userHandle, groupID=0): """ used to remove a contact from the desired list.
""" used to change your current screen name. @param newName: the new screen name @return: A Deferred, the callback for which will be called when the server sends an adequate reply. The callback argument will be a tuple of 2 elements: the new list version and the new screen name.
""" Used to change your current screen name. A default callback is added to the returned Deferred which updates the screenName attribute of the factory and also updates the contact list version. @param newName: the new screen name @return: A Deferred, the callback for which will be called when the server sends an ade...
def changeScreenName(self, newName): """ used to change your current screen name.
self.sendLine("REA %s %s %s" % (id, self.userHandle, quote(newName))) return d
self.sendLine("REA %s %s %s" % (id, self.factory.userHandle, quote(newName))) def _cb(r): self.factory.contacts.version = r[0] self.factory.screenName = r[1] return r return d.addCallback(_cb)
def changeScreenName(self, newName): """ used to change your current screen name.
""" used to request a switchboard server to use for conversations. @return: A Deferred, the callback for which will be called when the server responds with the switchboard information. The callback argument will be a tuple with 3 elements: the host of the switchboard server, the port and a key used for logging in.
""" Used to request a switchboard server to use for conversations. @return: A Deferred, the callback for which will be called when the server responds with the switchboard information. The callback argument will be a tuple with 3 elements: the host of the switchboard server, the port and a key used for logging in.
def requestSwitchboardServer(self): """ used to request a switchboard server to use for conversations.
""" used to log out of the notification server. After running the method the server is expected to close the connection.
""" Used to log out of the notification server. After running the method the server is expected to close the connection.
def logOut(self): """ used to log out of the notification server. After running the method the server is expected to close the connection. """ self.sendLine("OUT")
class MSNSwitchboardClient(MSNEventBase): """ this class provides support for clients connecting to a switchboard server. Switchboard servers are used for conversations with other people on the MSN network. This means that the number of conversations at any given time will be directly proportional to the number of con...
class NotificationFactory(ClientFactory): """ Factory for the NotificationClient protocol. This is basically responsible for keeping the state of the client and thus should be used in a 1:1 situation with clients. @ivar contacts: An MSNContactList instance reflecting the current contact list -- this is generally kept ...
def logOut(self): """ used to log out of the notification server. After running the method the server is expected to close the connection. """ self.sendLine("OUT")
id = int(params[0])
def handle_ANS(self, params): checkParamLen(len(params), 2, 'ANS') id = int(params[0]) if params[1] == "OK": #self._fireCallback(id) self.loggedIn()
""" called after connecting to an existing chat session. @param users: A dict mapping usre handles to screen names (current users taking part in the conversation)
""" called after connecting to an existing chat session. @param users: A dict mapping user handles to screen names (current users taking part in the conversation)
def gotChattingUsers(self, users): """ called after connecting to an existing chat session.
""" used to send a message. @param message: the corresponding MSNMessage object. @return: Depending on the value of message.ack. If set to MSNMessage.MESSAGE_ACK or MSNMessage.MESSAGE_NACK a Deferred will be returned, the callback for which will be fired when an ACK or NCK is received - the callback argument will be...
""" used to send a message. @param message: the corresponding MSNMessage object. @return: Depending on the value of message.ack. If set to MSNMessage.MESSAGE_ACK or MSNMessage.MESSAGE_NACK a Deferred will be returned, the callback for which will be fired when an ACK or NACK is received - the callback argument will be...
def sendMessage(self, message): """ used to send a message.
""" used to reply to a file transfer invitation. @param iCookie: the invitation cookie of the initial invitation @param accept: whether or not you accept this transfer, 1 = yes, 0 = no, default = 1. @return: A Deferred, the callback for which will be fired when the user responds with the transfer information. The cal...
""" used to reply to a file transfer invitation. @param iCookie: the invitation cookie of the initial invitation @param accept: whether or not you accept this transfer, 1 = yes, 0 = no, default = 1. @return: A Deferred, the callback for which will be fired when the user responds with the transfer information. The cal...
def fileInvitationReply(self, iCookie, accept=1): """ used to reply to a file transfer invitation.
""" send information relating to a file transfer session. @param accept: whether or not to go ahead with the transfer (1=yes, 0=no) @param iCookie: the invitation cookie of previous replies relating to this transfer @param authCookie: the authentication cookie obtained from an MSNFileSend instance @param ip: your ip @...
""" send information relating to a file transfer session. @param accept: whether or not to go ahead with the transfer (1=yes, 0=no) @param iCookie: the invitation cookie of previous replies relating to this transfer @param authCookie: the authentication cookie obtained from an FileSend instance @param ip: your ip @par...
def sendTransferInfo(self, accept, iCookie, authCookie, ip, port): """ send information relating to a file transfer session.
class MSNFileReceive(LineReceiver): """ This class provides support for receiving files from contacts. @ivar fileSize: the size of the receiving file. (you will have to set this) @ivar connected: true if a connection has been established. @ivar completed: true if the transfer is complete. @ivar bytesReceived: number o...
class FileReceive(LineReceiver): """ This class provides support for receiving files from contacts. @ivar fileSize: the size of the receiving file. (you will have to set this) @ivar connected: true if a connection has been established. @ivar completed: true if the transfer is complete. @ivar bytesReceived: number of b...
def sendTransferInfo(self, accept, iCookie, authCookie, ip, port): """ send information relating to a file transfer session.
class MSNFileSend(LineReceiver): """ This class provides support for sending files to other contacts. @ivar bytesSent: the number of bytes that have currently been sent. @ivar completed: true if the send has completed. @ivar connected: true if a connection has been established. @ivar targetUser: the target user (conta...
class FileSend(LineReceiver): """ This class provides support for sending files to other contacts. @ivar bytesSent: the number of bytes that have currently been sent. @ivar completed: true if the send has completed. @ivar connected: true if a connection has been established. @ivar targetUser: the target user (contact)...
def gotSegment(self, data): """ called when a segment (block) of data arrives. """ self.file.write(data)
for group in self._ingroups[nickname]: self.getGroupConversation(group).memberLeft(nickname) self._ingroups[nickname]=[]
if self._ingroups.has_key(nickname): for group in self._ingroups[nickname]: self.getGroupConversation(group).memberLeft(nickname) self._ingroups[nickname]=[] else: print '*** WARNING: ingroups had no such key %s' % nickname
def irc_QUIT(self,prefix,params): nickname=string.split(prefix,"!")[0] for group in self._ingroups[nickname]: self.getGroupConversation(group).memberLeft(nickname) self._ingroups[nickname]=[]
a = cPickle.load(open(options['append'], 'rb'))
if os.path.exists(options['append']): a = cPickle.load(open(options['append'], 'rb')) else: a = app.Application(options.subCommand, int(options['uid']), int(options['gid']))
def run(): tapLookup = loadPlugins() options = GeneralOptions(tapLookup) if hasattr(os, 'getgid'): options['uid'] = os.getuid() options['gid'] = os.getgid() try: options.parseOptions(sys.argv[1:]) # XXX - Yea, this is FILTH FILTH FILTH if options['debug'] or options['progress']: tapLookup = loadPlugins(options['debug']...
for doc in (template, document): fixLinks(doc, ext)
fixLinks(document, ext)
def munge(document, template, linkrel, d, fullpath, ext, cache): addMtime(template, fullpath) # things linked from the top for list in (domhelpers.findElementsWithAttribute(template,"src"), domhelpers.findElementsWithAttribute(template,"href"), domhelpers.findElementsWithAttribute(document, "fromtop")): fixFromTop(list...
if len(args)==1:
if len(args)==1 and not kw:
def parse(description, factory, default=None): """Parse a description of a reliable virtual circuit server @type description: C{str} @type factory: C{twisted.internet.interfaces.IProtocolFactory} @type default: C{str} or C{None} @rtype: C{tuple} @return: a tuple of string, tuple and dictionary. The string is the name ...
print '*************' print '\n'.join(lines) print '*************'
def testTracebackReporting(self): self.suite.addMethod(common.FailfulTests.testTracebackReporting) self.suite.run() lines = self.reporter.out.split('\n') while 1: if not lines: raise FailTest, "DOUBLE_SEPARATOR not found in lines" if lines[0] != DOUBLE_SEPARATOR: lines.pop(0) else: return
def startLogging(logfilename, syslog, prefix, nodaemon):
def startLogging(logfilename, sysLog, prefix, nodaemon):
def startLogging(logfilename, syslog, prefix, nodaemon): if logfilename == '-': if not nodaemon: print 'daemons cannot log to stdout' os._exit(1) logFile = sys.stdout elif nodaemon and not logfilename: logFile = sys.stdout elif syslog: syslog.startLogging(prefix) else: logPath = os.path.abspath(logfilename or 'twistd.l...
elif syslog:
elif sysLog:
def startLogging(logfilename, syslog, prefix, nodaemon): if logfilename == '-': if not nodaemon: print 'daemons cannot log to stdout' os._exit(1) logFile = sys.stdout elif nodaemon and not logfilename: logFile = sys.stdout elif syslog: syslog.startLogging(prefix) else: logPath = os.path.abspath(logfilename or 'twistd.l...
if not syslog:
if not sysLog:
def rotateLog(signal, frame, logFile=logFile): from twisted.internet import reactor reactor.callLater(0, logFile.rotate)
def sibLink(req, name): "Return the text that links to a sibling of the requested resource." if req.postpath: return (len(req.postpath)*"../") + name else: return name
rpyNoResource = """<p>You forgot to assign to the variable "resource" in your script. For example:</p> <pre>
def sibLink(req, name): "Return the text that links to a sibling of the requested resource." if req.postpath: return (len(req.postpath)*"../") + name else: return name
def childLink(req, name): "Return the text that links to a child of the requested resource." lpp = len(req.postpath) if lpp > 1: return ((lpp-1)*"../") + name if lpp == 1: return name if len(req.prepath) and req.prepath[-1]: return req.prepath[-1] + '/' + name else: return name
import mygreatresource
def childLink(req, name): "Return the text that links to a child of the requested resource." lpp = len(req.postpath) if lpp > 1: return ((lpp-1)*"../") + name if lpp == 1: return name if len(req.prepath) and req.prepath[-1]: return req.prepath[-1] + '/' + name else: return name
class IAppRoot(Interface): """attribute: root"""
resource = mygreatresource.MyGreatResource() </pre> """
def childLink(req, name): "Return the text that links to a child of the requested resource." lpp = len(req.postpath) if lpp > 1: return ((lpp-1)*"../") + name if lpp == 1: return name if len(req.prepath) and req.prepath[-1]: return req.prepath[-1] + '/' + name else: return name
class AppRoot: implements(IAppRoot) def __init__(self, request): url = prePathURL(request) self.root = url[:url.rindex("/")]
class AlreadyCached(Exception): """This exception is raised when a path has already been cached. """
def childLink(req, name): "Return the text that links to a child of the requested resource." lpp = len(req.postpath) if lpp > 1: return ((lpp-1)*"../") + name if lpp == 1: return name if len(req.prepath) and req.prepath[-1]: return req.prepath[-1] + '/' + name else: return name
components.registerAdapter(AppRoot, iweb.IRequest, IAppRoot)
class CacheScanner(object): def __init__(self, path, registry): self.path = path self.registry = registry self.doCache = 0
def __init__(self, request): url = prePathURL(request) self.root = url[:url.rindex("/")]
class ISession(Interface): pass
def cache(self): c = self.registry.getCachedPath(self.path) if c is not None: raise AlreadyCached(c) self.recache()
def __init__(self, request): url = prePathURL(request) self.root = url[:url.rindex("/")]
def getSession(request): cookiename = "_".join(['TWISTED_SESSION'] + self.sitepath) sessionCookie = request.getCookie(cookiename) if sessionCookie: try: return request.site.getSession(sessionCookie) except KeyError: pass session = Session(request.site, request.site.mkuid()) site.setSession(session) request.addCookie(co...
def recache(self): self.doCache = 1
def getSession(request): cookiename = "_".join(['TWISTED_SESSION'] + self.sitepath) sessionCookie = request.getCookie(cookiename) if sessionCookie: try: return request.site.getSession(sessionCookie) except KeyError: pass session = Session(request.site, request.site.mkuid()) site.setSession(session) request.addCookie(co...
components.registerAdapter(getSession, iweb.IRequest, ISession)
noRsrc = error.ErrorPage(500, "Whoops! Internal Error", rpyNoResource)
def getSession(request): cookiename = "_".join(['TWISTED_SESSION'] + self.sitepath) sessionCookie = request.getCookie(cookiename) if sessionCookie: try: return request.site.getSession(sessionCookie) except KeyError: pass session = Session(request.site, request.site.mkuid()) site.setSession(session) request.addCookie(co...
def prePathURL(request): port = request.getHost().port if request.isSecure(): default = 443 else: default = 80 if port == default: hostport = '' else: hostport = ':%d' % port return urllib.quote('http%s://%s%s/%s' % ( request.isSecure() and 's' or '', request.getRequestHostname(), hostport, '/'.join(request.prepath)), ...
def ResourceScript(path, registry): """ I am a normal py file which must define a 'resource' global, which should be an instance of (a subclass of) web.resource.Resource; it will be renderred. """ cs = CacheScanner(path, registry) glob = {'__file__': path, 'resource': noRsrc, 'registry': registry, 'cache': cs.cache, 'r...
def prePathURL(request): port = request.getHost().port if request.isSecure(): default = 443 else: default = 80 if port == default: hostport = '' else: hostport = ':%d' % port return urllib.quote('http%s://%s%s/%s' % ( request.isSecure() and 's' or '', request.getRequestHostname(), hostport, '/'.join(request.prepath)), ...
def URLPath(request): from twisted.python import urlpath return urlpath.URLPath.fromString(prePathURL(request))
def ResourceTemplate(path, registry): from quixote import ptl_compile
def URLPath(request): from twisted.python import urlpath return urlpath.URLPath.fromString(prePathURL(request))
class Session(components.Componentized): """A user's session with a system.
glob = {'__file__': path, 'resource': error.ErrorPage(500, "Whoops! Internal Error", rpyNoResource), 'registry': registry}
def URLPath(request): from twisted.python import urlpath return urlpath.URLPath.fromString(prePathURL(request))
This utility class contains only timeout functionality, but is used to represent a session. """ timeout = 15*60
e = ptl_compile.compile_template(open(path), path) exec e in glob return glob['resource']
def URLPath(request): from twisted.python import urlpath return urlpath.URLPath.fromString(prePathURL(request))
def __init__(self, site, uid): """Initialize a session with a unique ID for that session. """ components.Componentized.__init__(self) self.site = site self.uid = uid self.expireCallbacks = [] self.touch() self.sessionNamespaces = {} reactor.callLater(self.timeout, self._checkExpired)
def __init__(self, site, uid): """Initialize a session with a unique ID for that session. """ components.Componentized.__init__(self) self.site = site self.uid = uid self.expireCallbacks = [] self.touch() self.sessionNamespaces = {} reactor.callLater(self.timeout, self._checkExpired)
def notifyOnExpire(self): """Call this callback when the session expires or logs out. """ self.expireCallbacks.append(defer.Deferred()) return self.expireCallbacks[-1]
class ResourceScriptWrapper(resource.Resource):
def notifyOnExpire(self): """Call this callback when the session expires or logs out. """ self.expireCallbacks.append(defer.Deferred()) return self.expireCallbacks[-1]
def expire(self): """Expire/logout of the session. """ del self.site.sessions[self.uid] for c in self.expireCallbacks: c.callback(self) self.expireCallbacks = []
def __init__(self, path, registry=None): resource.Resource.__init__(self) self.path = path self.registry = registry or static.Registry()
def expire(self): """Expire/logout of the session. """ #log.msg("expired session %s" % self.uid) del self.site.sessions[self.uid] for c in self.expireCallbacks: c.callback(self) self.expireCallbacks = []
def touch(self): self.lastModified = time.time()
def render(self, request): res = ResourceScript(self.path, self.registry) return res.render(request)
def touch(self): self.lastModified = time.time()
if not groupID:
if groupID is None:
def addItemSSI(self, item, groupID = None, buddyID = None): """ add an item to the SSI server. if buddyID == 0, then this should be a group. this gets a callback when it's finished, but you can probably ignore it. """ if not groupID: groupID = item.group.group.findIDFor(item.group) if not buddyID: buddyID = item.group...
if not buddyID:
if buddyID is None:
def addItemSSI(self, item, groupID = None, buddyID = None): """ add an item to the SSI server. if buddyID == 0, then this should be a group. this gets a callback when it's finished, but you can probably ignore it. """ if not groupID: groupID = item.group.group.findIDFor(item.group) if not buddyID: buddyID = item.group...
if not groupID:
if groupID is None:
def modifyItemSSI(self, item, groupID = None, buddyID = None): if not groupID: groupID = item.group.group.findIDFor(item.group) if not buddyID: buddyID = item.group.findIDFor(item) return self.sendSNAC(0x13,0x09, item.oscarRep(groupID, buddyID))
if not buddyID:
if buddyID is None:
def modifyItemSSI(self, item, groupID = None, buddyID = None): if not groupID: groupID = item.group.group.findIDFor(item.group) if not buddyID: buddyID = item.group.findIDFor(item) return self.sendSNAC(0x13,0x09, item.oscarRep(groupID, buddyID))
if not groupID:
if groupID is None:
def delItemSSI(self, item, groupID = None, buddyID = None): if not groupID: groupID = item.group.group.findIDFor(item.group) if not buddyID: buddyID = item.group.findIDFor(item) return self.sendSNAC(0x13,0x0A, item.oscarRep(groupID, buddyID))
if not buddyID:
if buddyID is None:
def delItemSSI(self, item, groupID = None, buddyID = None): if not groupID: groupID = item.group.group.findIDFor(item.group) if not buddyID: buddyID = item.group.findIDFor(item) return self.sendSNAC(0x13,0x0A, item.oscarRep(groupID, buddyID))
if self.profile:
if self.profile is not None:
def setProfile(self, profile): """ set the profile. send None to not set a profile (different from '' for a blank one) """ self.profile = profile tlvs = '' if self.profile: tlvs = TLV(1,'text/aolrtf; charset="us-ascii"') + \ TLV(2,self.profile)
while node.childNodes.length:
while len(node.childNodes):
def clearNode(node): """ Remove all children from the given node. """ if node.hasChildNodes(): while node.childNodes.length: node.removeChild(node.lastChild)
self.reportingInterval = struct.unpack('!H',snac[3])[0]
self.reportingInterval = struct.unpack('!H',snac[3][:2])[0]
def oscar_0B_02(self, snac): """ stats reporting interval """ self.reportingInterval = struct.unpack('!H',snac[3])[0]
fd = 0 try: new = tty.tcgetattr(fd) except: log.msg('not a typewriter!') else: new[3] = new[3] & ~tty.ICANON & ~tty.ECHO new[6][tty.VMIN] = 1 new[6][tty.VTIME] = 0 tty.tcsetattr(fd, tty.TCSANOW, new) tty.setraw(fd)
_enterRawMode()
def channelOpen(self, foo): #global globalSession #globalSession = self # turn off local echo log.msg('session %s open' % self.id) if options['agent']: d = self.conn.sendRequest(self, 'auth-agent-req@openssh.com', '', wantReply=1) d.addBoth(lambda x:log.msg(x)) if options['noshell']: return if (options['command'] and o...
os.kill(os.getpid(), signal.SIGSTOP)
def _(): _leaveRawMode() sys.stdout.flush() sys.stdin.flush() os.kill(os.getpid(), signal.SIGTSTP) _enterRawMode() reactor.callLater(0, _)
def handleInput(self, char): #log.msg('handling %s' % repr(char)) if char in ('\n', '\r'): self.escapeMode = 1 self.write(char) elif self.escapeMode == 1 and char == options['escape']: self.escapeMode = 2 elif self.escapeMode == 2: self.escapeMode = 1 # so we can chain escapes together if char == '.': # disconnect log....
self.add(widgets.Text(data))
self.add(widgets.Text(cgi.escape(data)))
def setUp(self, request, node, data): """ Set up this Widget object before it gets rendered into HTML. Since self is a Widget, I can use the higher level widget API to add a Text widget to self. I then rely on Widget.generateDOM to convert from Widgets into the Document Object Model. """ self.add(widgets.Text(data))
iq = IQ(self.xmlstream, "set") iq.addElement(("jabber:iq:auth", "query")) iq.query.addElement("username", content = self.jid.user) iq.query.addElement("resource", content = self.jid.resource)
reply = IQ(self.xmlstream, "set") reply.addElement(("jabber:iq:auth", "query")) reply.query.addElement("username", content = self.jid.user) reply.query.addElement("resource", content = self.jid.resource)
def _authQueryResultEvent(self, iq): if iq["type"] == "result": # Construct auth request iq = IQ(self.xmlstream, "set") iq.addElement(("jabber:iq:auth", "query")) iq.query.addElement("username", content = self.jid.user) iq.query.addElement("resource", content = self.jid.resource) # Prefer digest over plaintext if Dige...
iq.query.addElement("digest", content = digest)
reply.query.addElement("digest", content = digest)
def _authQueryResultEvent(self, iq): if iq["type"] == "result": # Construct auth request iq = IQ(self.xmlstream, "set") iq.addElement(("jabber:iq:auth", "query")) iq.query.addElement("username", content = self.jid.user) iq.query.addElement("resource", content = self.jid.resource) # Prefer digest over plaintext if Dige...
iq.query.addElement("password", content = self.password)
reply.query.addElement("password", content = self.password)
def _authQueryResultEvent(self, iq): if iq["type"] == "result": # Construct auth request iq = IQ(self.xmlstream, "set") iq.addElement(("jabber:iq:auth", "query")) iq.query.addElement("username", content = self.jid.user) iq.query.addElement("resource", content = self.jid.resource) # Prefer digest over plaintext if Dige...
iq.addCallback(self._authResultEvent) iq.send()
reply.addCallback(self._authResultEvent) reply.send()
def _authQueryResultEvent(self, iq): if iq["type"] == "result": # Construct auth request iq = IQ(self.xmlstream, "set") iq.addElement(("jabber:iq:auth", "query")) iq.query.addElement("username", content = self.jid.user) iq.query.addElement("resource", content = self.jid.resource) # Prefer digest over plaintext if Dige...
if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']):
if len(self.conn.channels) == 0 and not (options['noshell'] and not options['nocache']):
def closed(self): global old log.msg('closed %s' % self) if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']): # just us left stopConnection() elif not options['nocache']: # fork into the background if os.fork(): if old: fd = sys.stdin.fileno() tty.tcsetattr(fd, tty.TCSANOW, old) if (...
if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']):
if len(self.conn.channels) == 0 and not (options['noshell'] and not options['nocache']):
def closed(self): forwarding.SSHListenClientForwardingChannel.closed(self) if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']): # just us left stopConnection()
if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']):
if len(self.conn.channels) == 0 and not (options['noshell'] and not options['nocache']):
def closed(self): forwarding.SSHConnectForwardingChannel.closed(self) if len(self.conn.channels) == 1 and not (options['noshell'] and not options['nocache']): # just us left stopConnection()
a=request.getComponent(simpleguard.Authenticated)
def wchild_secret(self, request): a=request.getComponent(simpleguard.Authenticated) if not request.getComponent(simpleguard.Authenticated): return InfiniChild(LoginPage()) return Authenticated()
a=request.getComponent(simpleguard.Authenticated)
def wchild_another(self, request): a=request.getComponent(simpleguard.Authenticated) if not request.getComponent(simpleguard.Authenticated): return InfiniChild(LoginPage()) return Another()
methodName = methodName.split('.')[-1]
self.methodName = methodName.split('.')[-1]
def __init__(self, methodName): if type(methodName) is types.StringType: self.testClass = reflect.namedObject('.'.join(methodName.split('.')[:-1])) methodName = methodName.split('.')[-1] else: self.testClass = methodName.im_class self.methodName = methodName.__name__
failure.Failure.printTraceback(file=self)
failure.Failure().printTraceback(file=self)
def processCommand(self, cmd): fn = '$telnet$' try: code = compile(cmd,fn,'eval') except: try: code = compile(cmd, fn, 'single') except: io = StringIO() failure.Failure().printTraceback(file=self) log.deferr() self.write('\r\n') return "Command" try: out = sys.stdout sys.stdout = self try: val = eval(code, self.factory...
pb.getObjectAt(self.host, self.port, 10).addCallbacks(self.connected, self.notConnected)
bf = pb.PBClientFactory() timeout = 10 if self.host == "unix": reactor.connectUNIX(self.port, bf, timeout) else: reactor.connectTCP(self.host, self.port, bf, timeout) d = bf.getRootObject() d.addCallbacks(self.connected, self.notConnected)
def render(self, request): """Render this request, from my server.
reactor.spawnProcess(p, '/bin/true', ['true'])
reactor.spawnProcess(p, cmd, ['true'])
def testNormalTermination(self): p = TrivialProcessProtocol() reactor.spawnProcess(p, '/bin/true', ['true']) while not p.finished: reactor.iterate(0.01) p.reason.trap(error.ProcessDone) self.assertEquals(p.reason.value.exitCode, 0)
reactor.spawnProcess(p, '/bin/false', ['false'])
reactor.spawnProcess(p, cmd, ['false'])
def testAbnormalTermination(self): p = TrivialProcessProtocol() reactor.spawnProcess(p, '/bin/false', ['false']) while not p.finished: reactor.iterate(0.01) p.reason.trap(error.ProcessTerminated) self.assertEquals(p.reason.value.exitCode, 1)
return open(self.path,'rb')
return open(self.path, "rb")
def openForReading(self): """Open a file and return it.""" return open(self.path,'rb')
if h1: h1 = h1[0] parent = h1.parentNode i = parent.childNodes.index(h1) parent.childNodes[i+1:i+1] = [toc]
empty = microdom.Element('span') for node in h1: node.parentNode.replaceChild(empty, node)
def putInToC(document, toc): h1 = domhelpers.findNodesNamed(document, 'h1') if h1: h1 = h1[0] parent = h1.parentNode i = parent.childNodes.index(h1) parent.childNodes[i+1:i+1] = [toc]
putInToC(document, generateToC(document))
putInToC(template, generateToC(document))
def munge(document, template, linkrel, d, fullpath, ext, url): addMtime(template, fullpath) expandAPI(document) fixAPI(document, url) fontifyPython(document) addPyListings(document, d) addHTMLListings(document, d) fixLinks(document, ext) putInToC(document, generateToC(document)) footnotes(document) notes(document) # t...
self.sendLine(":%s!%s@%s PRIVMSG %s :%s" % (senderName, senderName, self.servicename, self.nickname, message))
lines = string.split(message, '\n') for line in lines: self.sendLine(":%s!%s@%s PRIVMSG %s :%s" % (senderName, senderName, self.servicename, self.nickname, line))
def receiveDirectMessage(self, senderName, message): #>> :glyph_!glyph@adsl-64-123-27-108.dsl.austtx.swbell.net PRIVMSG glyph_ :hello #>> :glyph!glyph@adsl-64-123-27-108.dsl.austtx.swbell.net PRIVMSG glyph_ :hello
self.sendLine(":%s!%s@%s PRIVMSG (sender, sender, self.servicename, group, message))
lines = string.split(message, '\n') for line in lines: self.sendLine(":%s!%s@%s PRIVMSG (sender, sender, self.servicename, group, line))
def receiveGroupMessage(self, sender, group, message): if sender is not self: self.sendLine(":%s!%s@%s PRIVMSG #%s :%s" % (sender, sender, self.servicename, group, message))
print [result, path1, path2]
def comparePathFragments(self, path1, path2): result = LenientIntCompare()(path1, path2) print [result, path1, path2] return result
self.kexAlg = 'diffie-helmman-group-exchange-sha1-old'
self.kexAlg = 'diffie-hellman-group-exchange-sha1-old'
def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet): if self.ignoreNextPacket: self.ignoreNextPacket = 0 return if self.kexAlg == 'diffie-hellman-group1-sha1': # this is really KEXDH_INIT clientDHPubKey, foo = getMP(packet) y = Util.number.getRandomNumber(16, entropy.get_bytes) f = pow(DH_GENERATOR, y, DH_PRIME) sharedSecret ...
y = Util.number.getRandomNumber(16, entropy.get_bytes)
pSize = Util.number.size(self.p) y = Util.number.getRandomNumber(pSize, entropy.get_bytes)
def ssh_KEX_DH_GEX_INIT(self, packet): clientDHPubKey, foo = getMP(packet)
y = Util.number.getRandomNumber(16, entropy.get_bytes)
y = Util.number.getRandomNumber(pSize, entropy.get_bytes)
def ssh_KEX_DH_GEX_INIT(self, packet): clientDHPubKey, foo = getMP(packet)
def connectionFailed(self): self.socks.makeReply(91)
def connectionMade(self): junk, host, port = self.transport.getPeer() self.socks.makeReply(90, 0, port=port, ip=host) self.socks.otherConn=self
protocol.ClientCreator(reactor, SOCKSv4Outgoing, self).connectTCP(server,port)
d = protocol.ClientCreator(reactor, SOCKSv4Outgoing, self).connectTCP(server,port) d.addErrback(lambda result, self=self: self.makeReply(91))
def dataReceived(self,data): if self.otherConn: self.otherConn.write(data) return self.buf=self.buf+data if '\000' in self.buf[8:]: head,self.buf=self.buf[:8],self.buf[8:] try: version,code,port=struct.unpack("!BBH",head[:4]) except struct.error: raise RuntimeError, "struct error with head='%s' and buf='%s'"%(repr(head...
testdir = "_trial_temp"
testdir = os.path.abspath("_trial_temp")
def run(): if len(sys.argv) == 1: sys.argv.append("--help") config = Options() try: config.parseOptions() except usage.error, ue: print "%s: %s" % (sys.argv[0], ue) os._exit(1) suite = unittest.TestSuite() if config['recurse']: for package in config['packages']: suite.addPackageRecursive(package) else: for package in...
TLSTestCase.testTLS(self)
return TLSTestCase.testTLS(self) testTLS.suppress = [_bufferedSuppression] testTLS.todo = "startTLS doesn't empty buffer before starting TLS. :("
def testTLS(self): TLSTestCase.testTLS(self)
TLSTestCase.testBackwardsTLS(self) testTLS.todo = "startTLS doesn't empty buffer before starting TLS. :("
return TLSTestCase.testBackwardsTLS(self) testBackwardsTLS.suppress = [_bufferedSuppression]
def testBackwardsTLS(self): TLSTestCase.testBackwardsTLS(self)
for f in self.outgoingDccFiles:
for f in self._outgoingDccFiles:
def dcc_RESUME(self, user, channel, data): data = text.splitQuoted(data) if len(data) < 3: raise IRCBadMessage, "malformed DCC SEND RESUME request: %r" % (data,) (filename, port, resumePos) = data[:3] try: port = int(port) resumePos = int(resumePos) except ValueError: return # lets see which outgoingFile this goes to f...
return SMTPProtcolError(code, resp, str(self.log))
return SMTPProtocolError(code, resp, str(self.log))
def smtpTransferFailed(self, code, resp): if code < 0: # protocol error return SMTPProtcolError(code, resp, str(self.log)) return self.smtpState_msgSent(code, resp)
if os.geteuid() != uid: raise IOError(errno.EACCES) if os.getegid() != gid: raise IOError(errno.EACCES)
def _runAsUser(self, f, *args): euid = os.geteuid() egid = os.getegid() uid, gid = self.avatar.getUserGroupId() os.setegid(gid) os.seteuid(uid) # the next two lines fix some kind of timing error with WinSCP if os.geteuid() != uid: raise IOError(errno.EACCES) if os.getegid() != gid: raise IOError(errno.EACCES) try: if n...
signal.signal(signum, handler)
if handler is not None: signal.signal(signum, handler)
def restore(self): for signum, handler in self._store.iteritems(): signal.signal(signum, handler)
fileId = str(id(fileObj))
fileId = str(hash(fileObj))
def _cbOpenFile(self, fileObj, requestId): fileId = str(id(fileObj)) if fileId in self.openFiles: raise KeyError, 'id already open' self.openFiles[fileId] = fileObj self.sendPacket(FXP_HANDLE, struct.pack('!L', requestId) + NS(fileId))
handle = str(id(dirObj))
handle = str(hash(dirObj))
def _cbOpenDirectory(self, dirObj, requestId): handle = str(id(dirObj)) if handle in self.openDirs: raise KeyError, "already opened this directory" self.openDirs[handle] = [dirObj, iter(dirObj)] self.sendPacket(FXP_HANDLE, struct.pack('!L', requestId) + NS(handle))
except:
finally:
def _runAsUser(self, f, *args): euid = os.geteuid() egid = os.getegid() uid, gid = self.avatar.getUserGroupId() os.setegid(0) os.seteuid(0) os.setegid(gid) os.seteuid(uid) try: if not hasattr(f,'__iter__'): f = [(f, ) + args] for i in f: r = i[0](*i[1:]) except: os.setegid(0) os.seteuid(0) os.setegid(egid) os.seteuid(e...
raise else: os.setegid(0) os.seteuid(0) os.setegid(egid) os.seteuid(euid) return r
return r
def _runAsUser(self, f, *args): euid = os.geteuid() egid = os.getegid() uid, gid = self.avatar.getUserGroupId() os.setegid(0) os.seteuid(0) os.setegid(gid) os.seteuid(uid) try: if not hasattr(f,'__iter__'): f = [(f, ) + args] for i in f: r = i[0](*i[1:]) except: os.setegid(0) os.seteuid(0) os.setegid(egid) os.seteuid(e...