1 from twisted
.web
import resource
, server
, static
, error
as http_error
2 from twisted
.names
import client
3 from twisted
.internet
import reactor
, error
4 from authgateengine
import login_optional
, getSessionData
5 import md5
, sys
, os
, time
, config
, qwebirc
.config_options
as config_options
, traceback
, socket
6 import qwebirc
.ircclient
as ircclient
7 from adminengine
import AdminEngineAction
8 from qwebirc
.util
import HitCounter
9 import qwebirc
.dns
as qdns
10 import qwebirc
.util
.qjson
as json
13 TRANSPORTS
= ["longpoll"]
16 import autobahn
.websocket
17 import autobahn
.resource
19 TRANSPORTS
.append("websocket")
23 BAD_SESSION_MESSAGE
= "Invalid session, this most likely means the server has restarted; close this dialog and then try refreshing the page."
27 return md5
.md5(os
.urandom(16)).hexdigest()
29 class BufferOverflowException(Exception):
32 class AJAXException(Exception):
35 class IDGenerationException(Exception):
38 class LineTooLongException(Exception):
41 EMPTY_JSON_LIST
= json
.dumps([])
43 def cleanupSession(id):
50 def __init__(self
, id):
52 self
.subscriptions
= []
58 self
.cleanupschedule
= None
60 def subscribe(self
, channel
):
61 if len(self
.subscriptions
) >= config
.MAXSUBSCRIPTIONS
:
62 self
.subscriptions
.pop(0).close()
64 self
.subscriptions
.append(channel
)
67 def unsubscribe(self
, channel
):
69 self
.subscriptions
.remove(channel
)
73 def timeout(self
, channel
):
77 self
.unsubscribe(channel
)
78 channel
.write(EMPTY_JSON_LIST
)
80 def flush(self
, scheduled
=False):
84 if not self
.buffer or not self
.subscriptions
:
91 self
.schedule
= reactor
.callLater(self
.throttle
- t
, self
.flush
, True)
94 # process the rest of the packet
97 self
.schedule
= reactor
.callLater(0, self
.flush
, True)
100 self
.throttle
= t
+ config
.UPDATE_FREQ
102 encdata
= json
.dumps(self
.buffer)
106 subs
= self
.subscriptions
107 self
.subscriptions
= newsubs
= []
112 if self
.closed
and not newsubs
:
113 cleanupSession(self
.id)
115 def event(self
, data
):
116 newbuflen
= self
.buflen
+ len(data
)
117 if newbuflen
> config
.MAXBUFLEN
:
119 self
.client
.error("Buffer overflow.")
122 self
.buffer.append(data
)
123 self
.buflen
= newbuflen
126 def push(self
, data
):
130 if len(data
) > config
.MAXLINELEN
:
131 raise LineTooLongException
133 self
.client
.write(data
)
135 def disconnect(self
):
136 # keep the session hanging around for a few seconds so the
137 # client has a chance to see what the issue was
140 reactor
.callLater(5, cleanupSession
, self
.id)
142 # DANGER! Breach of encapsulation!
143 def connect_notice(line
):
144 return "c", "NOTICE", "", ("AUTH", "*** (qwebirc) %s" % line
)
146 class RequestChannel(object):
147 def __init__(self
, request
):
148 self
.request
= request
150 def write(self
, data
):
151 self
.request
.write(data
)
152 self
.request
.finish()
156 self
.request
.finish()
158 class AJAXEngine(resource
.Resource
):
161 def __init__(self
, prefix
):
163 self
.__connect
_hit
= HitCounter()
164 self
.__total
_hit
= HitCounter()
166 def render_POST(self
, request
):
167 path
= request
.path
[len(self
.prefix
):]
169 handler
= self
.COMMANDS
.get(path
[1:])
170 if handler
is not None:
172 return handler(self
, request
)
173 except AJAXException
, e
:
174 return json
.dumps((False, e
[0]))
176 return "404" ## TODO: tidy up
178 def newConnection(self
, request
):
179 ticket
= login_optional(request
)
181 ip
= request
.getClientIP()
183 nick
= request
.args
.get("nick")
185 raise AJAXException
, "Nickname not supplied."
186 nick
= ircclient
.irc_decode(nick
[0])
188 password
= request
.args
.get("password")
189 if password
is not None:
190 password
= ircclient
.irc_decode(password
[0])
193 id = get_session_id()
194 if not Sessions
.get(id):
197 raise IDGenerationException()
199 session
= IRCSession(id)
201 qticket
= getSessionData(request
).get("qticket")
205 service_mask
= config
.AUTH_SERVICE
206 msg_mask
= service_mask
.split("!")[0] + "@" + service_mask
.split("@", 1)[1]
207 perform
= ["PRIVMSG %s :TICKETAUTH %s" % (msg_mask
, qticket
)]
209 ident
, realname
= config
.IDENT
, config
.REALNAME
210 if ident
is config_options
.IDENT_HEX
or ident
is None: # latter is legacy
211 ident
= socket
.inet_aton(ip
).encode("hex")
212 elif ident
is config_options
.IDENT_NICKNAME
:
217 def proceed(hostname
):
218 kwargs
= dict(nick
=nick
, ident
=ident
, ip
=ip
, realname
=realname
, perform
=perform
, hostname
=hostname
)
219 if password
is not None:
220 kwargs
["password"] = password
222 client
= ircclient
.createIRC(session
, **kwargs
)
223 session
.client
= client
225 if not hasattr(config
, "WEBIRC_MODE") or config
.WEBIRC_MODE
== "hmac":
227 elif config
.WEBIRC_MODE
!= "hmac":
228 notice
= lambda x
: session
.event(connect_notice(x
))
229 notice("Looking up your hostname...")
230 def callback(hostname
):
231 notice("Found your hostname.")
233 def errback(failure
):
234 notice("Couldn't look up your hostname!")
236 qdns
.lookupAndVerifyPTR(ip
, timeout
=[config
.DNS_TIMEOUT
]).addCallbacks(callback
, errback
)
238 Sessions
[id] = session
240 return json
.dumps((True, id, TRANSPORTS
))
242 def getSession(self
, request
):
243 bad_session_message
= "Invalid session, this most likely means the server has restarted; close this dialog and then try refreshing the page."
245 sessionid
= request
.args
.get("s")
246 if sessionid
is None:
247 raise AJAXException
, bad_session_message
249 session
= Sessions
.get(sessionid
[0])
251 raise AJAXException
, bad_session_message
254 def subscribe(self
, request
):
255 request
.channel
.setTimeout(None)
257 channel
= RequestChannel(request
)
258 session
= self
.getSession(request
)
259 notifier
= request
.notifyFinish()
260 session
.subscribe(channel
)
262 timeout_entry
= reactor
.callLater(config
.HTTP_AJAX_REQUEST_TIMEOUT
, session
.timeout
, channel
)
263 def cancel_timeout(result
):
265 timeout_entry
.cancel()
266 except error
.AlreadyCalled
:
268 session
.unsubscribe(channel
)
269 notifier
.addCallbacks(cancel_timeout
, cancel_timeout
)
270 return server
.NOT_DONE_YET
272 def push(self
, request
):
273 command
= request
.args
.get("c")
275 raise AJAXException
, "No command specified."
278 session
= self
.getSession(request
)
280 session
.push(ircclient
.irc_decode(command
[0]))
281 except AttributeError: # occurs when we haven't noticed an error
283 raise AJAXException
, "Connection closed by server; try reconnecting by reloading the page."
284 except Exception, e
: # catch all
286 traceback
.print_exc(file=sys
.stderr
)
287 raise AJAXException
, "Unknown error."
289 return json
.dumps((True, True))
291 def closeById(self
, k
):
295 s
.client
.client
.error("Closed by admin interface")
298 def adminEngine(self
):
300 "Sessions": [(str(v
.client
.client
), AdminEngineAction("close", self
.closeById
, k
)) for k
, v
in Sessions
.iteritems() if not v
.closed
],
301 "Connections": [(self
.__connect
_hit
,)],
302 "Total hits": [(self
.__total
_hit
,)],
305 COMMANDS
= dict(p
=push
, n
=newConnection
, s
=subscribe
)
308 class WebSocketChannel(object):
309 def __init__(self
, channel
):
310 self
.channel
= channel
312 def write(self
, data
):
313 self
.channel
.send("c", data
)
319 class WebSocketEngineProtocol(autobahn
.websocket
.WebSocketServerProtocol
):
320 AWAITING_AUTH
, AUTHED
= 0, 1
322 def __init__(self
, *args
, **kwargs
):
323 self
.__state
= self
.AWAITING_AUTH
324 self
.__session
= None
325 self
.__channel
= None
326 self
.__timeout
= None
329 self
.__timeout
= reactor
.callLater(5, self
.close
, "Authentication timeout")
331 def onClose(self
, wasClean
, code
, reason
):
332 self
.__cancelTimeout
()
334 self
.__session
.unsubscribe(self
.__channel
)
335 self
.__session
= None
337 def onMessage(self
, msg
, binary
):
338 # we don't bother checking the Origin header, as if you can auth then you've been able to pass the browser's
339 # normal origin handling (POSTed the new connection request and managed to get the session id)
341 message_type
, message
= msg
[:1], msg
[1:]
342 if state
== self
.AWAITING_AUTH
:
343 if message_type
== "s": # subscribe
344 session
= Sessions
.get(message
)
346 self
.close(BAD_SESSION_MESSAGE
)
349 self
.__cancelTimeout
()
350 self
.__session
= session
351 self
.send("s", "True")
352 self
.__state
= self
.AUTHED
353 self
.__channel
= WebSocketChannel(self
)
354 session
.subscribe(self
.__channel
)
356 elif state
== self
.AUTHED
:
357 if message_type
== "p": # push
358 self
.__session
.push(ircclient
.irc_decode(message
))
361 self
.close("Bad message type")
363 def __cancelTimeout(self
):
364 if self
.__timeout
is not None:
366 self
.__timeout
.cancel()
367 except error
.AlreadyCalled
:
369 self
.__timeout
= None
371 def close(self
, reason
=None):
372 self
.__cancelTimeout
()
374 self
.sendClose(4999, reason
)
379 self
.__session
.unsubscribe(self
.__channel
)
380 self
.__session
= None
382 def send(self
, message_type
, message
):
383 self
.sendMessage(message_type
+ message
)
385 class WebSocketResource(autobahn
.resource
.WebSocketResource
):
386 def render(self
, request
):
387 request
.channel
.setTimeout(None)
388 return autobahn
.resource
.WebSocketResource
.render(self
, request
)
390 def WebSocketEngine(path
=None):
391 parsed
= urlparse
.urlparse(config
.BASE_URL
)
394 if parsed
.scheme
== "http":
396 elif parsed
.scheme
== "https":
399 raise Exception("Unable to determine port from BASE_URL: " + config
.BASE_URL
)
401 factory
= autobahn
.websocket
.WebSocketServerFactory("ws://localhost:%d" % port
)
402 factory
.protocol
= WebSocketEngineProtocol
403 factory
.setProtocolOptions(maxMessagePayloadSize
=512, maxFramePayloadSize
=512, tcpNoDelay
=False)
404 resource
= WebSocketResource(factory
)