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 simplejson
, md5
, sys
, os
, time
, config
, weakref
, 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
13 return md5
.md5(os
.urandom(16)).hexdigest()
15 class BufferOverflowException(Exception):
18 class AJAXException(Exception):
21 class IDGenerationException(Exception):
24 class PassthruException(Exception):
30 def decorator(*args
, **kwargs
):
32 x
= fn(*args
, **kwargs
)
34 return server
.NOT_DONE_YET
36 except AJAXException
, e
:
38 except PassthruException
, e
:
41 return simplejson
.dumps(x
)
44 def cleanupSession(id):
51 def __init__(self
, id):
53 self
.subscriptions
= []
58 self
.cleanupschedule
= None
60 def subscribe(self
, channel
, notifier
):
61 timeout_entry
= reactor
.callLater(config
.HTTP_AJAX_REQUEST_TIMEOUT
, self
.timeout
, channel
)
62 def cancel_timeout(result
):
63 if channel
in self
.subscriptions
:
64 self
.subscriptions
.remove(channel
)
66 timeout_entry
.cancel()
67 except error
.AlreadyCalled
:
69 notifier
.addCallbacks(cancel_timeout
, cancel_timeout
)
71 if len(self
.subscriptions
) >= config
.MAXSUBSCRIPTIONS
:
72 self
.subscriptions
.pop(0).close()
74 self
.subscriptions
.append(channel
)
77 def timeout(self
, channel
):
81 channel
.write(simplejson
.dumps([]))
82 if channel
in self
.subscriptions
:
83 self
.subscriptions
.remove(channel
)
85 def flush(self
, scheduled
=False):
89 if not self
.buffer or not self
.subscriptions
:
96 self
.schedule
= reactor
.callLater(self
.throttle
- t
, self
.flush
, True)
99 # process the rest of the packet
101 if not self
.schedule
:
102 self
.schedule
= reactor
.callLater(0, self
.flush
, True)
105 self
.throttle
= t
+ config
.UPDATE_FREQ
107 encdata
= simplejson
.dumps(self
.buffer)
111 for x
in self
.subscriptions
:
115 self
.subscriptions
= newsubs
116 if self
.closed
and not self
.subscriptions
:
117 cleanupSession(self
.id)
119 def event(self
, data
):
120 bufferlen
= sum(map(len, self
.buffer))
121 if bufferlen
+ len(data
) > config
.MAXBUFLEN
:
123 self
.client
.error("Buffer overflow.")
126 self
.buffer.append(data
)
129 def push(self
, data
):
131 self
.client
.write(data
)
133 def disconnect(self
):
134 # keep the session hanging around for a few seconds so the
135 # client has a chance to see what the issue was
138 reactor
.callLater(5, cleanupSession
, self
.id)
140 # DANGER! Breach of encapsulation!
141 def connect_notice(line
):
142 return "c", "NOTICE", "", ("AUTH", "*** (qwebirc) %s" % line
)
145 def __init__(self
, request
):
146 self
.request
= request
148 class SingleUseChannel(Channel
):
149 def write(self
, data
):
150 self
.request
.write(data
)
151 self
.request
.finish()
155 self
.request
.finish()
157 class MultipleUseChannel(Channel
):
158 def write(self
, data
):
159 self
.request
.write(data
)
162 class AJAXEngine(resource
.Resource
):
165 def __init__(self
, prefix
):
167 self
.__connect
_hit
= HitCounter()
168 self
.__total
_hit
= HitCounter()
171 def render_POST(self
, request
):
172 path
= request
.path
[len(self
.prefix
):]
174 handler
= self
.COMMANDS
.get(path
[1:])
175 if handler
is not None:
176 return handler(self
, request
)
178 raise PassthruException
, http_error
.NoResource().render(request
)
180 def newConnection(self
, request
):
181 ticket
= login_optional(request
)
183 _
, ip
, port
= request
.transport
.getPeer()
185 nick
= request
.args
.get("nick")
187 raise AJAXException
, "Nickname not supplied."
188 nick
= ircclient
.irc_decode(nick
[0])
191 id = get_session_id()
192 if not Sessions
.get(id):
195 raise IDGenerationException()
197 session
= IRCSession(id)
199 qticket
= getSessionData(request
).get("qticket")
203 service_mask
= config
.AUTH_SERVICE
204 msg_mask
= service_mask
.split("!")[0] + "@" + service_mask
.split("@", 1)[1]
205 perform
= ["PRIVMSG %s :TICKETAUTH %s" % (msg_mask
, qticket
)]
207 ident
, realname
= config
.IDENT
, config
.REALNAME
209 ident
= socket
.inet_aton(ip
).encode("hex")
213 def proceed(hostname
):
214 client
= ircclient
.createIRC(session
, nick
=nick
, ident
=ident
, ip
=ip
, realname
=realname
, perform
=perform
, hostname
=hostname
)
215 session
.client
= client
217 if config
.WEBIRC_MODE
!= "hmac":
218 notice
= lambda x
: session
.event(connect_notice(x
))
219 notice("Looking up your hostname...")
220 def callback(hostname
):
221 notice("Found your hostname.")
223 def errback(failure
):
224 notice("Couldn't look up your hostname!")
226 qdns
.lookupAndVerifyPTR(ip
, timeout
=[config
.DNS_TIMEOUT
]).addCallbacks(callback
, errback
)
228 proceed(None) # hmac doesn't care
230 Sessions
[id] = session
234 def getSession(self
, request
):
235 bad_session_message
= "Invalid session, this most likely means the server has restarted; close this dialog and then try refreshing the page."
237 sessionid
= request
.args
.get("s")
238 if sessionid
is None:
239 raise AJAXException
, bad_session_message
241 session
= Sessions
.get(sessionid
[0])
243 raise AJAXException
, bad_session_message
246 def subscribe(self
, request
):
247 request
.channel
.cancelTimeout()
248 self
.getSession(request
).subscribe(SingleUseChannel(request
), request
.notifyFinish())
251 def push(self
, request
):
252 command
= request
.args
.get("c")
254 raise AJAXException
, "No command specified."
257 decoded
= ircclient
.irc_decode(command
[0])
259 session
= self
.getSession(request
)
261 if len(decoded
) > config
.MAXLINELEN
:
263 raise AJAXException
, "Line too long."
266 session
.push(decoded
)
267 except AttributeError: # occurs when we haven't noticed an error
269 raise AJAXException
, "Connection closed by server; try reconnecting by reloading the page."
270 except Exception, e
: # catch all
272 traceback
.print_exc(file=sys
.stderr
)
273 raise AJAXException
, "Unknown error."
277 def closeById(self
, k
):
281 s
.client
.client
.error("Closed by admin interface")
284 def adminEngine(self
):
286 "Sessions": [(str(v
.client
.client
), AdminEngineAction("close", self
.closeById
, k
)) for k
, v
in Sessions
.iteritems() if not v
.closed
],
287 "Connections": [(self
.__connect
_hit
,)],
288 "Total hits": [(self
.__total
_hit
,)],
291 COMMANDS
= dict(p
=push
, n
=newConnection
, s
=subscribe
)