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
|
## client.py
##
## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
##
## 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, 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.
# $Id: client.py,v 1.52 2006/01/02 19:40:55 normanr Exp $
"""
Provides PlugIn class functionality to develop extentions for xmpppy.
Also provides Client and Component classes implementations as the
examples of xmpppy structures usage.
These classes can be used for simple applications "AS IS" though.
"""
import socket
import debug
Debug=debug
Debug.DEBUGGING_IS_ON=1
Debug.Debug.colors['socket']=debug.color_dark_gray
Debug.Debug.colors['CONNECTproxy']=debug.color_dark_gray
Debug.Debug.colors['nodebuilder']=debug.color_brown
Debug.Debug.colors['client']=debug.color_cyan
Debug.Debug.colors['component']=debug.color_cyan
Debug.Debug.colors['dispatcher']=debug.color_green
Debug.Debug.colors['browser']=debug.color_blue
Debug.Debug.colors['auth']=debug.color_yellow
Debug.Debug.colors['roster']=debug.color_magenta
Debug.Debug.colors['ibb']=debug.color_yellow
Debug.Debug.colors['down']=debug.color_brown
Debug.Debug.colors['up']=debug.color_brown
Debug.Debug.colors['data']=debug.color_brown
Debug.Debug.colors['ok']=debug.color_green
Debug.Debug.colors['warn']=debug.color_yellow
Debug.Debug.colors['error']=debug.color_red
Debug.Debug.colors['start']=debug.color_dark_gray
Debug.Debug.colors['stop']=debug.color_dark_gray
Debug.Debug.colors['sent']=debug.color_yellow
Debug.Debug.colors['got']=debug.color_bright_cyan
DBG_CLIENT='client'
DBG_COMPONENT='component'
class PlugIn:
""" Common xmpppy plugins infrastructure: plugging in/out, debugging. """
def __init__(self):
self._exported_methods=[]
self.DBG_LINE=self.__class__.__name__.lower()
def PlugIn(self,owner):
""" Attach to main instance and register ourself and all our staff in it. """
self._owner=owner
if self.DBG_LINE not in owner.debug_flags:
owner.debug_flags.append(self.DBG_LINE)
self.DEBUG('Plugging %s into %s'%(self,self._owner),'start')
if self.__class__.__name__ in owner.__dict__:
return self.DEBUG('Plugging ignored: another instance already plugged.','error')
self._old_owners_methods=[]
for method in self._exported_methods:
if method.__name__ in owner.__dict__:
self._old_owners_methods.append(owner.__dict__[method.__name__])
owner.__dict__[method.__name__]=method
owner.__dict__[self.__class__.__name__]=self
if 'plugin' in self.__class__.__dict__: return self.plugin(owner)
def PlugOut(self):
""" Unregister all our staff from main instance and detach from it. """
self.DEBUG('Plugging %s out of %s.'%(self,self._owner),'stop')
self._owner.debug_flags.remove(self.DBG_LINE)
for method in self._exported_methods: del self._owner.__dict__[method.__name__]
for method in self._old_owners_methods: self._owner.__dict__[method.__name__]=method
del self._owner.__dict__[self.__class__.__name__]
if 'plugout' in self.__class__.__dict__: return self.plugout()
del self._owner
def DEBUG(self,text,severity='info'):
""" Feed a provided debug line to main instance's debug facility along with our ID string. """
self._owner.DEBUG(self.DBG_LINE,text,severity)
import transports,dispatcher,auth,roster
class CommonClient:
""" Base for Client and Component classes."""
def __init__(self,server,port=5222,debug=['always', 'nodebuilder'],caller=None):
""" Caches server name and (optionally) port to connect to. "debug" parameter specifies
the debug IDs that will go into debug output. You can either specifiy an "include"
or "exclude" list. The latter is done via adding "always" pseudo-ID to the list.
Full list: ['nodebuilder', 'dispatcher', 'gen_auth', 'SASL_auth', 'bind', 'socket',
'CONNECTproxy', 'TLS', 'roster', 'browser', 'ibb'] . """
if self.__class__.__name__=='Client': self.Namespace,self.DBG='jabber:client',DBG_CLIENT
elif self.__class__.__name__=='Component': self.Namespace,self.DBG=dispatcher.NS_COMPONENT_ACCEPT,DBG_COMPONENT
self.defaultNamespace=self.Namespace
self.disconnect_handlers=[]
self.Server=server
self.Port=port
# Who initiated this client
# Used to register the EventDispatcher
self._caller=caller
if debug and type(debug)<>list: debug=['always', 'nodebuilder']
self._DEBUG=Debug.Debug(debug)
self.DEBUG=self._DEBUG.Show
self.debug_flags=self._DEBUG.debug_flags
self.debug_flags.append(self.DBG)
self._owner=self
self._registered_name=None
self.RegisterDisconnectHandler(self.DisconnectHandler)
self.connected=''
self._component=0
def RegisterDisconnectHandler(self,handler):
""" Register handler that will be called on disconnect."""
self.disconnect_handlers.append(handler)
def UnregisterDisconnectHandler(self,handler):
""" Unregister handler that is called on disconnect."""
self.disconnect_handlers.remove(handler)
def disconnected(self):
""" Called on disconnection. Calls disconnect handlers and cleans things up. """
self.connected=''
self.DEBUG(self.DBG,'Disconnect detected','stop')
self.disconnect_handlers.reverse()
for i in self.disconnect_handlers: i()
self.disconnect_handlers.reverse()
if 'TLS' in self.__dict__: self.TLS.PlugOut()
def DisconnectHandler(self):
""" Default disconnect handler. Just raises an IOError.
If you choosed to use this class in your production client,
override this method or at least unregister it. """
raise IOError('Disconnected from server.')
def event(self,eventName,args={}):
""" Default event handler. To be overriden. """
print "Event: ",(eventName,args)
def isConnected(self):
""" Returns connection state. F.e.: None / 'tls' / 'tcp+non_sasl' . """
return self.connected
def reconnectAndReauth(self):
""" Example of reconnection method. In fact, it can be used to batch connection and auth as well. """
handlerssave=self.Dispatcher.dumpHandlers()
self.Dispatcher.PlugOut()
if 'NonSASL' in self.__dict__: self.NonSASL.PlugOut()
if 'SASL' in self.__dict__: self.SASL.PlugOut()
if 'TLS' in self.__dict__: self.TLS.PlugOut()
if 'HTTPPROXYsocket' in self.__dict__: self.HTTPPROXYsocket.PlugOut()
if 'TCPsocket' in self.__dict__: self.TCPsocket.PlugOut()
if not self.connect(server=self._Server,proxy=self._Proxy): return
if not self.auth(self._User,self._Password,self._Resource): return
self.Dispatcher.restoreHandlers(handlerssave)
return self.connected
def get_peerhost(self):
''' get the ip address of the account, from which is made connection
to the server , (e.g. me).
We will create listening socket on the same ip '''
if hasattr(self, 'Connection'):
return self.Connection._sock.getsockname()
def connect(self,server=None,proxy=None,ssl=None,use_srv=None):
""" Make a tcp/ip connection, protect it with tls/ssl if possible and start XMPP stream.
Returns None or 'tcp' or 'tls', depending on the result."""
if not server: server=(self.Server,self.Port)
if proxy: socket=transports.HTTPPROXYsocket(proxy,server,use_srv)
else: socket=transports.TCPsocket(server,use_srv)
connected=socket.PlugIn(self)
if not connected:
socket.PlugOut()
return
self._Server,self._Proxy=server,proxy
self.connected='tcp'
if (ssl is None and self.Connection.getPort() in (5223, 443)) or ssl:
try: # FIXME. This should be done in transports.py
transports.TLS().PlugIn(self,now=1)
self.connected='ssl'
except socket.sslerror:
return
dispatcher.Dispatcher().PlugIn(self)
while self.Dispatcher.Stream._document_attrs is None:
if not self.Process(1): return
if 'version' in self.Dispatcher.Stream._document_attrs and self.Dispatcher.Stream._document_attrs['version']=='1.0':
while not self.Dispatcher.Stream.features and self.Process(): pass # If we get version 1.0 stream the features tag MUST BE presented
return self.connected
class Client(CommonClient):
""" Example client class, based on CommonClient. """
def connect(self,server=None,proxy=None,secure=None,use_srv=True):
""" Connect to jabber server. If you want to specify different ip/port to connect to you can
pass it as tuple as first parameter. If there is HTTP proxy between you and server
specify it's address and credentials (if needed) in the second argument.
If you want ssl/tls support to be discovered and enable automatically - leave third argument as None. (ssl will be autodetected only if port is 5223 or 443)
If you want to force SSL start (i.e. if port 5223 or 443 is remapped to some non-standard port) then set it to 1.
If you want to disable tls/ssl support completely, set it to 0.
Example: connect(('192.168.5.5',5222),{'host':'proxy.my.net','port':8080,'user':'me','password':'secret'})
Returns '' or 'tcp' or 'tls', depending on the result."""
if not CommonClient.connect(self,server,proxy,secure,use_srv) or secure<>None and not secure: return self.connected
transports.TLS().PlugIn(self)
if 'version' not in self.Dispatcher.Stream._document_attrs or not self.Dispatcher.Stream._document_attrs['version']=='1.0': return self.connected
while not self.Dispatcher.Stream.features and self.Process(): pass # If we get version 1.0 stream the features tag MUST BE presented
if not self.Dispatcher.Stream.features.getTag('starttls'): return self.connected # TLS not supported by server
while not self.TLS.starttls and self.Process(): pass
if not hasattr(self, 'TLS') or self.TLS.starttls!='success': self.event('tls_failed'); return self.connected
self.connected='tls'
return self.connected
def auth(self,user,password,resource='',sasl=1):
""" Authenticate connnection and bind resource. If resource is not provided
random one or library name used. """
self._User,self._Password,self._Resource=user,password,resource
while not self.Dispatcher.Stream._document_attrs and self.Process(): pass
if 'version' in self.Dispatcher.Stream._document_attrs and self.Dispatcher.Stream._document_attrs['version']=='1.0':
while not self.Dispatcher.Stream.features and self.Process(): pass # If we get version 1.0 stream the features tag MUST BE presented
if sasl: auth.SASL(user,password).PlugIn(self)
if not sasl or self.SASL.startsasl=='not-supported':
if not resource: resource='xmpppy'
if auth.NonSASL(user,password,resource).PlugIn(self):
self.connected+='+old_auth'
return 'old_auth'
return
self.SASL.auth()
while self.SASL.startsasl=='in-process' and self.Process(): pass
if self.SASL.startsasl=='success':
auth.Bind().PlugIn(self)
while self.Bind.bound is None and self.Process(): pass
if self.Bind.Bind(resource):
self.connected+='+sasl'
return 'sasl'
def initRoster(self):
""" Plug in the roster. """
if 'Roster' not in self.__dict__: roster.Roster().PlugIn(self)
def getRoster(self):
""" Return the Roster instance, previously plugging it in and
requesting roster from server if needed. """
self.initRoster()
return self.Roster.getRoster()
def sendInitPresence(self,requestRoster=1):
""" Send roster request and initial <presence/>.
You can disable the first by setting requestRoster argument to 0. """
self.sendPresence(requestRoster=requestRoster)
def sendPresence(self,jid=None,typ=None,requestRoster=0):
""" Send some specific presence state.
Can also request roster from server if according agrument is set."""
if requestRoster: roster.Roster().PlugIn(self)
self.send(dispatcher.Presence(to=jid, typ=typ))
class Component(CommonClient):
""" Component class. The only difference from CommonClient is ability to perform component authentication. """
def __init__(self,server,port=5347,typ=None,debug=['always', 'nodebuilder'],domains=None,component=0):
""" Init function for Components.
As components use a different auth mechanism which includes the namespace of the component.
Jabberd1.4 and Ejabberd use the default namespace then for all client messages.
Jabberd2 uses jabber:client.
'server' argument is a server name that you are connecting to (f.e. "localhost").
'port' can be specified if 'server' resolves to correct IP. If it is not then you'll need to specify IP
and port while calling "connect()"."""
CommonClient.__init__(self,server,port=port,debug=debug)
self.typ=typ
self.component=component
if domains:
self.domains=domains
else:
self.domains=[server]
def connect(self,server=None,proxy=None):
""" This will connect to the server, and if the features tag is found then set
the namespace to be jabber:client as that is required for jabberd2.
'server' and 'proxy' arguments have the same meaning as in xmpp.Client.connect() """
if self.component:
self.Namespace=auth.NS_COMPONENT_1
self.Server=server[0]
CommonClient.connect(self,server=server,proxy=proxy)
if self.connected and (self.typ=='jabberd2' or not self.typ and self.Dispatcher.Stream.features is not None):
self.defaultNamespace=auth.NS_CLIENT
self.Dispatcher.RegisterNamespace(self.defaultNamespace)
self.Dispatcher.RegisterProtocol('iq',dispatcher.Iq)
self.Dispatcher.RegisterProtocol('message',dispatcher.Message)
self.Dispatcher.RegisterProtocol('presence',dispatcher.Presence)
return self.connected
def auth(self,name,password,dup=None,sasl=0):
""" Authenticate component "name" with password "password"."""
self._User,self._Password,self._Resource=name,password,''
try:
if self.component: sasl=1
if sasl: auth.SASL(name,password).PlugIn(self)
if not sasl or self.SASL.startsasl=='not-supported':
if auth.NonSASL(name,password,'').PlugIn(self):
self.connected+='+old_auth'
return 'old_auth'
return
self.SASL.auth()
while self.SASL.startsasl=='in-process' and self.Process(): pass
if self.SASL.startsasl=='success':
if self.component:
self._component=self.component
for domain in self.domains:
auth.ComponentBind().PlugIn(self)
while self.ComponentBind.bound is None: self.Process()
if (not self.ComponentBind.Bind(domain)):
self.ComponentBind.PlugOut()
return
self.ComponentBind.PlugOut()
self.connected+='+sasl'
return 'sasl'
else:
raise auth.NotAuthorized(self.SASL.startsasl)
except:
self.DEBUG(self.DBG,"Failed to authenticate %s"%name,'error')
# vim: se ts=3:
|