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
= []
59 self
.cleanupschedule
= None
61 def subscribe(self
, channel
, notifier
):
62 timeout_entry
= reactor
.callLater(config
.HTTP_AJAX_REQUEST_TIMEOUT
, self
.timeout
, channel
)
63 def cancel_timeout(result
):
64 if channel
in self
.subscriptions
:
65 self
.subscriptions
.remove(channel
)
67 timeout_entry
.cancel()
68 except error
.AlreadyCalled
:
70 notifier
.addCallbacks(cancel_timeout
, cancel_timeout
)
72 if len(self
.subscriptions
) >= config
.MAXSUBSCRIPTIONS
:
73 self
.subscriptions
.pop(0).close()
75 self
.subscriptions
.append(channel
)
78 def timeout(self
, channel
):
82 channel
.write(simplejson
.dumps([]))
83 if channel
in self
.subscriptions
:
84 self
.subscriptions
.remove(channel
)
86 def flush(self
, scheduled
=False):
90 if not self
.buffer or not self
.subscriptions
:
97 self
.schedule
= reactor
.callLater(self
.throttle
- t
, self
.flush
, True)
100 # process the rest of the packet
102 if not self
.schedule
:
103 self
.schedule
= reactor
.callLater(0, self
.flush
, True)
106 self
.throttle
= t
+ config
.UPDATE_FREQ
108 encdata
= simplejson
.dumps(self
.buffer)
113 for x
in self
.subscriptions
:
117 self
.subscriptions
= newsubs
118 if self
.closed
and not self
.subscriptions
:
119 cleanupSession(self
.id)
121 def event(self
, data
):
122 newbuflen
= self
.buflen
+ len(data
)
123 if newbuflen
> config
.MAXBUFLEN
:
125 self
.client
.error("Buffer overflow.")
128 self
.buffer.append(data
)
129 self
.buflen
= newbuflen
132 def push(self
, data
):
134 self
.client
.write(data
)
136 def disconnect(self
):
137 # keep the session hanging around for a few seconds so the
138 # client has a chance to see what the issue was
141 reactor
.callLater(5, cleanupSession
, self
.id)
143 # DANGER! Breach of encapsulation!
144 def connect_notice(line
):
145 return "c", "NOTICE", "", ("AUTH", "*** (qwebirc) %s" % line
)
148 def __init__(self
, request
):
149 self
.request
= request
151 class SingleUseChannel(Channel
):
152 def write(self
, data
):
153 self
.request
.write(data
)
154 self
.request
.finish()
158 self
.request
.finish()
160 class MultipleUseChannel(Channel
):
161 def write(self
, data
):
162 self
.request
.write(data
)
165 class AJAXEngine(resource
.Resource
):
168 def __init__(self
, prefix
):
170 self
.__connect
_hit
= HitCounter()
171 self
.__total
_hit
= HitCounter()
174 def render_POST(self
, request
):
175 path
= request
.path
[len(self
.prefix
):]
177 handler
= self
.COMMANDS
.get(path
[1:])
178 if handler
is not None:
179 return handler(self
, request
)
181 raise PassthruException
, http_error
.NoResource().render(request
)
183 def newConnection(self
, request
):
184 ticket
= login_optional(request
)
186 _
, ip
, port
= request
.transport
.getPeer()
188 nick
= request
.args
.get("nick")
190 raise AJAXException
, "Nickname not supplied."
191 nick
= ircclient
.irc_decode(nick
[0])
194 id = get_session_id()
195 if not Sessions
.get(id):
198 raise IDGenerationException()
200 session
= IRCSession(id)
202 qticket
= getSessionData(request
).get("qticket")
206 service_mask
= config
.AUTH_SERVICE
207 msg_mask
= service_mask
.split("!")[0] + "@" + service_mask
.split("@", 1)[1]
208 perform
= ["PRIVMSG %s :TICKETAUTH %s" % (msg_mask
, qticket
)]
210 ident
, realname
= config
.IDENT
, config
.REALNAME
212 ident
= socket
.inet_aton(ip
).encode("hex")
216 def proceed(hostname
):
217 client
= ircclient
.createIRC(session
, nick
=nick
, ident
=ident
, ip
=ip
, realname
=realname
, perform
=perform
, hostname
=hostname
)
218 session
.client
= client
220 if config
.WEBIRC_MODE
!= "hmac":
221 notice
= lambda x
: session
.event(connect_notice(x
))
222 notice("Looking up your hostname...")
223 def callback(hostname
):
224 notice("Found your hostname.")
226 def errback(failure
):
227 notice("Couldn't look up your hostname!")
229 qdns
.lookupAndVerifyPTR(ip
, timeout
=[config
.DNS_TIMEOUT
]).addCallbacks(callback
, errback
)
231 proceed(None) # hmac doesn't care
233 Sessions
[id] = session
237 def getSession(self
, request
):
238 bad_session_message
= "Invalid session, this most likely means the server has restarted; close this dialog and then try refreshing the page."
240 sessionid
= request
.args
.get("s")
241 if sessionid
is None:
242 raise AJAXException
, bad_session_message
244 session
= Sessions
.get(sessionid
[0])
246 raise AJAXException
, bad_session_message
249 def subscribe(self
, request
):
250 request
.channel
.cancelTimeout()
251 self
.getSession(request
).subscribe(SingleUseChannel(request
), request
.notifyFinish())
254 def push(self
, request
):
255 command
= request
.args
.get("c")
257 raise AJAXException
, "No command specified."
260 decoded
= ircclient
.irc_decode(command
[0])
262 session
= self
.getSession(request
)
264 if len(decoded
) > config
.MAXLINELEN
:
266 raise AJAXException
, "Line too long."
269 session
.push(decoded
)
270 except AttributeError: # occurs when we haven't noticed an error
272 raise AJAXException
, "Connection closed by server; try reconnecting by reloading the page."
273 except Exception, e
: # catch all
275 traceback
.print_exc(file=sys
.stderr
)
276 raise AJAXException
, "Unknown error."
280 def closeById(self
, k
):
284 s
.client
.client
.error("Closed by admin interface")
287 def adminEngine(self
):
289 "Sessions": [(str(v
.client
.client
), AdminEngineAction("close", self
.closeById
, k
)) for k
, v
in Sessions
.iteritems() if not v
.closed
],
290 "Connections": [(self
.__connect
_hit
,)],
291 "Total hits": [(self
.__total
_hit
,)],
294 COMMANDS
= dict(p
=push
, n
=newConnection
, s
=subscribe
)