-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmpp
573 lines (479 loc) · 20 KB
/
xmpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:rdfe="http://redfoot.net/3.0/rdf#"
xmlns:code="http://redfoot.net/3.0/code#"
xmlns:command="http://redfoot.net/3.0/command#"
>
<rdfe:Namespace rdf:about="#">
<rdfs:label>XMPP</rdfs:label>
<rdfs:comment>The Redfoot xmpp namespace.</rdfs:comment>
</rdfe:Namespace>
<rdfs:Class rdf:ID="XMPPID">
<rdfs:label>XMPP ID</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:subClassOf rdf:resource="http://redfoot.net/xmpp#Resource"/>
</rdfs:Class>
<rdf:Property rdf:ID="uid">
<rdfs:label>xmpp id</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:domain rdf:resource="http://redfoot.net/user#User"/>
<rdfs:range rdf:resource="#XMPPID"/>
</rdf:Property>
<rdf:Property rdf:ID="real_id">
<rdfs:label>real xmpp id</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:domain rdf:resource="#XMPPID"/>
<rdfs:range rdf:resource="#XMPPID"/>
</rdf:Property>
<rdfs:Class rdf:ID="Handler">
<rdfs:label>XMPP Handler</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:subClassOf rdf:resource="http://redfoot.net/3.0/code#Code"/>
</rdfs:Class>
<rdf:Property rdf:ID="handler">
<rdfs:label>xmpp handler</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:domain rdf:resource="http://redfoot.net/user#User"/>
<rdfs:range rdf:resource="#Handler"/>
</rdf:Property>
<code:Module rdf:about="#client">
<rdfs:label>XMPP Client</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
from twisted.words.protocols.jabber import client
try:
client.XMPPClientFactory
module_uri = URIRef("#client_2.5.0", base=__uri__)
except AttributeError, e:
_logger.info("Falling back to 2.4.0 client implementation")
module_uri = URIRef("#client_2.4.0", base=__uri__)
XMPP = redfoot.namespace("%s#" % __uri__.defrag())
xmpp = redfoot.module(module_uri)
from twisted.words.xish import domish
from twisted.words.protocols.jabber import jid
from rdflib.events import Event
class AuthenticatedEvent(Event):
"""
This event is fired when the client has authenticated itself, it has the following attributes:
- 'client_id' identifier of client
"""
class Client(xmpp.Client):
###
def authenticated(self, xmlstream):
_logger.info("XMPP Client Authenticated")
self.xmlstream = xmlstream
#presence = domish.Element((None, 'presence'))
#xmlstream.send(presence)
presence = domish.Element(('jabber:client','presence'))
photo = presence.addElement("photo", "vcard-temp:x:update", "0709d4740da5b3325678f2ee1062993c9a7113fa")
presence.addElement("x", 'vcard-temp:x:update', photo)
xmlstream.send(presence)
xmlstream.addObserver('/message', self.message)
xmlstream.addObserver('/presence', self.presence)
xmlstream.addObserver('/iq', self.iq)
xmlstream.addObserver('/*', self.debug)
if self.pending:
pending = list(self.pending)
self.pending = []
for message in pending:
self.xmlstream.send(message)
try:
redfoot.dispatcher.dispatch(AuthenticatedEvent(client=self))
except Exception, e:
_logger.exception(e)
def message(self, message):
try:
import sys
from optparse import OptionParser
from StringIO import StringIO
#import threading
from threading import Thread
from_id = message["from"]
body = None
error = False
for e in message.elements():
if e.name=="body":
body = "%s" % e
elif e.name=="error":
error = True
if body is None:
_logger.warning("Did not find body element in: %s" % message.toXml().encode('utf-8'))
_logger.info("from_id: '%s'" % from_id)
xmpp_id = URIRef("xmpp:%s" % jid.JID(from_id).userhost())
uri = redfoot.value(predicate=XMPP.uid, object=xmpp_id)
is_admin = uri and (uri, RDF.type, KERNEL.Admin) in redfoot
_logger.debug("from_id: '%s' is_admin: '%s' xmpp_id: '%s'" % (from_id, is_admin, xmpp_id))
if error:
_logger.debug("error: %s" % message.toXml().encode('utf-8'))
elif body and body.startswith("redfoot"):
def run_command(command_line, from_id, xmpp):
sio = StringIO()
orig = sys.stdout, sys.stderr
sys.stdout = sio
sys.stderr = sio
parser = OptionParser("usage: command <options>")
parser.allow_interspersed_args = False
args = command_line.split()
(options, args) = parser.parse_args(args[1:])
options.program = None
redfoot.main(options, args)
sys.stdout, sys.stderr = orig
# TODO: pipe command stdout back to user
result = sio.getvalue()
for line in result.split("\n"):
xmpp.send(from_id, line)
if is_admin:
_logger.debug("running command")
t = Thread(target=run_command, args=(body, from_id, self))
t.start()
else:
self.send(from_id, "You need to be an admin to run commands.")
else:
xmpp_handlers = redfoot.instances(XMPP.Handler)
for xmpp_handler in xmpp_handlers:
_logger.debug("xmpp_handler: %s" % xmpp_handler)
if xmpp_handler:
redfoot.execute(xmpp_handler, xmpp=self, message=message)
#else:
# self.send(from_id, "Thank you for your input. But I'm going to ignore it.")
except Exception, e:
_logger.exception(e)
def presence(self, presence):
try:
_logger.debug(presence.toXml().encode('utf-8'))
if presence.hasAttribute("type") and presence["type"]=="subscribe":
response = domish.Element(('jabber:client','presence'))
response["to"] = presence["from"]
response["from"] = self.client_jid.full()
response["type"] = "subscribed"
_logger.debug("responding to presence with: %s" % response.toXml().encode('utf-8'))
self.xmlstream.send(response)
else:
# Example:
# <presence xmlns='jabber:client'
# to='test@eikeon.com/26837695781166401341104343'
# from='test@conference.example.com/test'><priority>0</priority><x
# xmlns='http://jabber.org/protocol/muc#user'><item
# affiliation='owner'
# jid='test@eikeon.com/26837695781166401341104343'
# role='moderator'/></x></presence>
# TODO: should be keying off of full uri not just the name
# part... but no convient interface... so for now.
x = presence.x
if x:
item = x.item
if item:
try:
real_id = item["jid"]
room_id = presence["from"]
except Exception, e:
_logger.debug("didn't have jid or from as expected")
real_id = None
room_id = None
if real_id and room_id:
real_id = URIRef("xmpp:%s" % jid.JID(real_id).userhost())
room_id = URIRef("xmpp:%s" % jid.JID(room_id).full())
c = redfoot.get_context(redfoot.context_id(room_id, "context"), creator=__uri__)
c.set((room_id, XMPP.real_id, real_id))
_logger.debug("room_id: %s -> read_id: %s" % (room_id, real_id))
except Exception, e:
_logger.exception(e)
def iq(self, iq):
try:
pass
except Exception, e:
_logger.exception(e)
def debug(self, element):
if element.error:
return
_logger.debug(element.toXml().encode('utf-8'))
def send(self, to, msg, html=None):
"""to is an identifier of a person or a class of people. msg is the
text message to send and html is an html version of the message. """
users = []
if isinstance(to, URIRef):
if (to, RDF.type, RDFS.Class) in redfoot:
for user in redfoot.subjects(RDF.type, to):
xmpp_id = redfoot.value(user, XMPP.uid, any=True)
if xmpp_id:
users.append(xmpp_id)
else:
if not to.startswith("xmpp:"):
_logger.warning("Not adding '%s'. Not a xmpp id" % to)
users.append(to)
else:
users.append(to)
for user in users:
message = domish.Element(('jabber:client','message'))
message["to"] = user.split("xmpp:")[-1]
message["from"] = self.client_jid.full()
message["id"] = "%s" % __uri__ # uri of this module
if "conference" in user:
message["type"] = "groupchat"
else:
message["type"] = "chat"
message.addElement("body", "jabber:client", msg)
if html:
e = message.addElement("html", "http://jabber.org/protocol/xhtml-im")
e.addRawXml(html)
if self.xmlstream:
self.xmlstream.send(message)
else:
self.pending.append(message)
def join(self, room_id):
_logger.info("%s join %s" % (self.client_jid.user, room_id))
if room_id.startswith("xmpp:"):
room_id = room_id[5:]
nick = self.client_jid.user
message = """<presence to="%s/%s" >
<priority>0</priority>
</presence>""" % (room_id, nick)
_logger.debug("%s" % message)
if self.xmlstream:
self.xmlstream.send(message)
else:
self.pending.append(message)
]]>
</code:python>
</code:Module>
<code:Module rdf:about="#client_2.5.0">
<rdfs:label>XMPP Client</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
from twisted.internet import reactor
from twisted.names.srvconnect import SRVConnector
from twisted.words.protocols.jabber import xmlstream, client, jid
class XMPPClientConnector(SRVConnector):
def __init__(self, reactor, domain, factory):
SRVConnector.__init__(self, reactor, 'xmpp-client', domain, factory)
self.tried_fallback = False
def pickServer(self):
host, port = SRVConnector.pickServer(self)
if not self.servers and not self.orderedServers:
# no SRV record, fall back..
port = 5222
return host, port
def connectionFailed(self, reason):
if self.tried_fallback:
SRVConnector.connectionFailed(self, reason)
else:
self.tried_fallback = True
self.servers = [(1, 1, self.domain, 5222)]
self.orderedServers = []
self.connect()
class Client(object):
def __init__(self, client_id, secret):
_logger.debug("Creating client for '%s'" % client_id)
self.xmlstream = None
self.pending = []
if client_id.startswith("xmpp:"):
client_id = client_id.replace("xmpp:", "", 1)
self.client_jid = client_jid = jid.JID(client_id)
f = client.XMPPClientFactory(client_jid, secret)
f.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.connected)
f.addBootstrap(xmlstream.STREAM_END_EVENT, self.disconnected)
f.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
f.addBootstrap(xmlstream.INIT_FAILED_EVENT, self.init_failed)
connector = XMPPClientConnector(reactor, client_jid.host, f)
connector.connect()
def connected(self, xs):
_logger.info('Connected.')
self.xmlstream = xs
def disconnected(self, xs):
_logger.info('Disconnected.')
def init_failed(self, failure):
_logger.info("Initialization failed.")
_logger.info(failure)
self.xmlstream.sendFooter()
]]>
</code:python>
</code:Module>
<code:Module rdf:about="#client_2.4.0">
<rdfs:label>XMPP Client</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
from twisted.words.protocols.jabber import client, jid
from twisted.words.xish import domish
from twisted.internet import reactor
from twisted.words.protocols.jabber.client import BasicAuthenticator
class Client(object):
def __init__(self, client_id, password):
self.xmlstream = None
self.pending = []
self.client_jid = client_jid = jid.JID(client_id)
factory = client.basicClientFactory(client_jid, password)
factory.addBootstrap('//event/stream/authd', self.authenticated)
factory.addBootstrap(BasicAuthenticator.INVALID_USER_EVENT, self._invalid_user)
factory.addBootstrap(BasicAuthenticator.AUTH_FAILED_EVENT, self._auth_failed)
factory.addBootstrap(BasicAuthenticator.REGISTER_FAILED_EVENT, self._register_failed)
reactor.connectTCP(host, port, factory)
def _invalid_user(self, failure):
_logger.error("Invalid User: %s" % failure)
def _auth_failed(self, failure):
_logger.error("Auth Failed: %s" % failure)
def _register_failed(self, failure):
_logger.error("Register User: %s" % failure)
]]>
</code:python>
</code:Module>
<code:Module rdf:about="#logging">
<rdfs:label>XMPP Loggin</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
import logging
class XMPPHandler(logging.Handler):
"""
A handler class which sends an XMPP message for each logging event to a list of users.
"""
def __init__(self, who=None):
logging.Handler.__init__(self)
self.who = who
def emit(self, record):
try:
msg = self.format(record)
redfoot.xmpp.send(self.who, msg)
except:
self.handleError(record)
def install(who):
_root_logger = logging.getLogger()
_root_logger.setLevel(logging.INFO)
_root_formatter = logging.Formatter('[%(name)s] %(message)s')
_root_handler = XMPPHandler(who)
_root_handler.setFormatter(_root_formatter)
_root_logger.addHandler(_root_handler)
]]>
</code:python>
</code:Module>
<command:Command rdf:ID="xmpp_info">
<rdfs:label>xmpp_info</rdfs:label>
<rdfs:comment>A command for setting the jabber id and password redfoot will try to connect using.</rdfs:comment>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
try:
import twisted
except ImportError, e:
raise ImportError("Twisted is not installed. Please install Twisted-2.5.0. 1) download http://twistedmatrix.com/trac/#Downloading 2) unpack 3) python setup.py install")
if twisted.__version__.startswith("2.5.0"):
assert len(args)==2, "expecting 2 arguments: xmpp_id, xmpp_password"
redfoot.xmpp_id = args[0]
redfoot.xmpp_password = args[1]
else:
assert len(args)==4, "expecting 4 arguments: xmpp_id, xmpp_password, xmpp_host, xmpp_port"
redfoot.xmpp_id = args[0]
redfoot.xmpp_password = args[1]
redfoot.xmpp_host = args[2]
redfoot.xmpp_port = args[3]
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="xmpp_auth">
<rdfs:label>xmpp_auth</rdfs:label>
<rdfs:comment>An ejabberd external authentication script</rdfs:comment>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
import sys, traceback, struct, time, sha, md5
_logger.info("xmpp_auth %s" % sys.stdin)
USER = redfoot.namespace("http://redfoot.net/3.0/user#")
XMPP = redfoot.namespace("http://redfoot.net/3.0/xmpp#")
def authenticate_user(username, hostname, password):
#_logger.debug("username '%s' hostname '%s' password '%s'" % (username, hostname, password))
uid = URIRef("xmpp:%s@%s" % (username, hostname))
user_uri = redfoot.value(predicate=XMPP.uid, object=uid) or uid
_logger.debug("found user_uri: %s" % user_uri)
if user_uri is not None:
hexdigest = sha.new(password).hexdigest()
if (user_uri, USER.hexdigest, Literal(hexdigest)) in redfoot:
return True
md5_digest = md5.new(password).hexdigest()
if (user_uri, USER.hexdigest, Literal(md5_digest)) in redfoot:
return True
return False
def is_user(username, hostname):
uid = URIRef("xmpp:%s@%s" % (username, hostname))
user_uri = redfoot.value(predicate=XMPP.uid, object=uid) or uid
return user_uri and (user_uri, RDF.type, USER.User) in redfoot
def main():
'''
The main loop
'''
while True:
time.sleep(2)
try:
nread = sys.stdin.read(2)
now = time.strftime('%d/%m/%Y %H:%M:%S',time.localtime())
if len(nread) < 2:
_logger.debug('time=%s bytes_read=%d\n' % (now, len(nread)))
if len(nread)==0:
break
continue
size = struct.unpack('>h', nread)[0]
data = sys.stdin.read(size)
try:
(operation, rest) = data.split(':', 1)
except Exception, e:
_logger.debug("data: '%s'" % data)
_logger.exception(e)
break
_logger.info('time=%s operation=%s\n' % (now, operation))
if operation == 'auth':
try:
user, host, password = rest.split(":", 2)
except Exception, e:
_logger.exception(e)
result = authenticate_user(user, host, password)
_logger.info("authenticate_user: %s %s -> %s\n" % (user, host, result))
if result:
sys.stdout.write(struct.pack('>hh', 2, 1))
else:
sys.stdout.write(struct.pack('>hh', 2, 0))
sys.stdout.flush()
elif operation == 'isuser':
try:
user, host = rest.split(":", 1)
except Exception, e:
_logger.exception(e)
result = is_user(user, host)
if result:
sys.stdout.write(struct.pack('>hh', 2, 1))
else:
sys.stdout.write(struct.pack('>hh', 2, 0))
sys.stdout.flush()
else:
#setpass(usr, oldpwd, newpwd, domain, dc=None, verb=0):
sys.stdout.write(struct.pack('>hh', 2, 0))
sys.stdout.flush()
except Exception, e:
_logger.exception(e)
main()
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="xmpp_subscribe">
<rdfs:label>xmpp_subscribe</rdfs:label>
<rdfs:comment>A command to request the presence of another entity</rdfs:comment>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
jid = args[0]
redfoot.xmpp.xmlsteam("""<presence to='%s' type='subscribe'/>""" % jid)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="xmpp_join">
<rdfs:label>xmpp_join</rdfs:label>
<rdfs:comment>A command to request the presence of another entity</rdfs:comment>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
room_id = args[0] # include /nick ex. room@conference.domain.com/nick
redfoot.xmpp.xmlstream.send("""<presence to="%s" >
<priority>0</priority>
</presence>""" % room_id)
]]>
</code:python>
</command:Command>
</rdf:RDF>