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
, 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
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
= request
.getClientIP()
188 nick
= request
.args
.get("nick")
190 raise AJAXException
, "Nickname not supplied."
191 nick
= ircclient
.irc_decode(nick
[0])
193 password
= request
.args
.get("password")
194 if password
is not None:
195 password
= ircclient
.irc_decode(password
[0])
198 id = get_session_id()
199 if not Sessions
.get(id):
202 raise IDGenerationException()
204 session
= IRCSession(id)
206 qticket
= getSessionData(request
).get("qticket")
210 service_mask
= config
.AUTH_SERVICE
211 msg_mask
= service_mask
.split("!")[0] + "@" + service_mask
.split("@", 1)[1]
212 perform
= ["PRIVMSG %s :TICKETAUTH %s" % (msg_mask
, qticket
)]
214 ident
, realname
= config
.IDENT
, config
.REALNAME
215 if ident
is config_options
.IDENT_HEX
or ident
is None: # latter is legacy
216 ident
= socket
.inet_aton(ip
).encode("hex")
217 elif ident
is config_options
.IDENT_NICKNAME
:
222 def proceed(hostname
):
223 kwargs
= dict(nick
=nick
, ident
=ident
, ip
=ip
, realname
=realname
, perform
=perform
, hostname
=hostname
)
224 if password
is not None:
225 kwargs
["password"] = password
227 client
= ircclient
.createIRC(session
, **kwargs
)
228 session
.client
= client
230 if not hasattr(config
, "WEBIRC_MODE") or config
.WEBIRC_MODE
== "hmac":
232 elif config
.WEBIRC_MODE
!= "hmac":
233 notice
= lambda x
: session
.event(connect_notice(x
))
234 notice("Looking up your hostname...")
235 def callback(hostname
):
236 notice("Found your hostname.")
238 def errback(failure
):
239 notice("Couldn't look up your hostname!")
241 qdns
.lookupAndVerifyPTR(ip
, timeout
=[config
.DNS_TIMEOUT
]).addCallbacks(callback
, errback
)
243 Sessions
[id] = session
247 def getSession(self
, request
):
248 bad_session_message
= "Invalid session, this most likely means the server has restarted; close this dialog and then try refreshing the page."
250 sessionid
= request
.args
.get("s")
251 if sessionid
is None:
252 raise AJAXException
, bad_session_message
254 session
= Sessions
.get(sessionid
[0])
256 raise AJAXException
, bad_session_message
259 def subscribe(self
, request
):
260 request
.channel
.cancelTimeout()
261 self
.getSession(request
).subscribe(SingleUseChannel(request
), request
.notifyFinish())
264 def push(self
, request
):
265 command
= request
.args
.get("c")
267 raise AJAXException
, "No command specified."
270 decoded
= ircclient
.irc_decode(command
[0])
272 session
= self
.getSession(request
)
274 if len(decoded
) > config
.MAXLINELEN
:
276 raise AJAXException
, "Line too long."
279 session
.push(decoded
)
280 except AttributeError: # occurs when we haven't noticed an error
282 raise AJAXException
, "Connection closed by server; try reconnecting by reloading the page."
283 except Exception, e
: # catch all
285 traceback
.print_exc(file=sys
.stderr
)
286 raise AJAXException
, "Unknown error."
290 def closeById(self
, k
):
294 s
.client
.client
.error("Closed by admin interface")
297 def adminEngine(self
):
299 "Sessions": [(str(v
.client
.client
), AdminEngineAction("close", self
.closeById
, k
)) for k
, v
in Sessions
.iteritems() if not v
.closed
],
300 "Connections": [(self
.__connect
_hit
,)],
301 "Total hits": [(self
.__total
_hit
,)],
304 COMMANDS
= dict(p
=push
, n
=newConnection
, s
=subscribe
)