def _handleParentSide(pid, stdin, stdout, stderr, stdindata): stderrl = [] stdoutl = [] while 1: if stdindata: #if anything left to write to the CGI inlist = [stdin] else: inlist = [] r, w, e = select.select([stdout, stderr], inlist, [], 1) if stdout in r: rbytes = os.read(stdout, 1024) if not rbytes: r.remove(stdout) stdoutl.append(rbytes) if stderr in r: rbytes = os.read(stderr, 1024) if not rbytes: r.remove(stderr) stderrl.append(rbytes) if stdin in w: if stdindata: l = os.write(stdin, stdindata) stdindata = stdindata[l:] if not r and not w: #no pipes active, is child alive #check on process health status = os.waitpid(pid, os.WNOHANG)[1] #DEBUG(EXTCGI, "status was %s" % repr(status)) if os.WIFSIGNALED(status): # if process has died abnormally raise "CGIError", ( "cgi died by signal %s: %s" % (os.WTERMSIG(status), ''.join(stderrl))) if os.WIFEXITED(status): # if exited via exit() exitStatus = os.WEXITSTATUS(status) if exitStatus:# or stderrl: raise "CGIError", ''.join(stderrl) DEBUG(EXTCGI, 'cgi exited normally %d %d' % ( status, exitStatus)) return ''.join(stdoutl)
def removeSession(self): ''' clears and removes any active session. ''' DEBUG(SESSIONHANDLER, "in removeSession()") self.getSession(0) try: sess = self.__userSession except AttributeError: pass else: if sess: sess.delete() del self.__userSession self.__sessionID = None sesskey = Configuration.SessionIDKey if self.requestCookie.has_key(sesskey): self.responseCookie[sesskey] = "" self.responseCookie[sesskey]['expires'] = Cookie._getdate(-10000000)
def plainHandler(connObj, sessionDict): if not hasattr(connObj, 'statInfo'): return # file doesn't exist, screw it if not hasattr(connObj, 'mimeType'): return # file exists, but is a directory if connObj.mimeType in Configuration.hideMimeTypes: return # something that shouldn't be uri accessible modtime = HTTPDate(connObj.statInfo[2]) ims = connObj.requestHeaders.get('If-Modified-Since') if ims: if ims == modtime: connObj.setStatus(304) return connObj.response() connObj.responseHeaders['Content-Type'] = connObj.mimeType connObj.responseHeaders['Last-Modified'] = modtime DEBUG(TEMPLATING, "spewing raw file") connObj.write(AE.Cache._readDocRoot(connObj.uri)) return connObj.response()
def checkCredentials(self, conn): DEBUG(AUTH, "looking for auth cookie") auth = conn.requestCookie.get(self.cookieName) if not auth: return None #have cookie, now check, assuming basicAuth style cookie w/armoring auth = auth.value txt = armor.dearmor(self.cookieNonce, auth) if not txt: return bits = txt.split(':') user = bits[0] password = '******'.join(bits[1:]) conn.remoteUser = user conn.remotePassword = password conn.env['REMOTE_USER'] = conn.remoteUser conn.env['REMOTE_PASSWORD'] = conn.remotePassword return self.validate(user, password)
def marshalRequest(self, sock, sessionDict): """ Sends a handshake byte, obtains the content length from the value of the first ten bytes read, and then reads no more than that amount, which it marshals with the 'marshal' module. Finally, returns the marshalled request data """ headers = parseHeaders(recvstr(sock)) cl = int(headers.get('CONTENT_LENGTH', '0')) if cl: body = sock.recv(cl) else: body = '' ret = { 'stdin': body, 'environ': headers, 'headers': self.makeHeaders(headers) } DEBUG(SCGI, 'reqdata is %s' % ret) return ret
def _initArgs(self, requestData): stdin = cStringIO.StringIO(requestData['stdin']) env = requestData['environ'] try: query = cgi.FieldStorage(fp = stdin, environ = env, keep_blank_values = 1) self.args=self._convertArgs(query) ok=1 except: # may be some exotic content-type logException() DEBUG(WEB, "content-type: %s" % self.requestHeaders.get("content-type")) self.args={} ok=0 if ok and Configuration.mergeQueryStringWithPostData and \ env.get("REQUEST_METHOD")=='POST': #if POST, see if any GET args too environ = env.copy() environ["REQUEST_METHOD"] = 'GET' query = cgi.FieldStorage(fp = stdin, environ = environ, keep_blank_values = 1) self.args.update(self._convertArgs(query))
def redirect(self, url): self.responseHeaders['Location'] = url self.setStatus(301) self._output = NullOutput() DEBUG(WEB, "Redirecting to %s" % url)
# overlay of config information Configuration.trim() Configuration.scope(sessionDict) #Configuration.saveMash() DEBUG(WEB, 'executing PreHandleConnection hook') PreHandleConnection(Configuration.job, connection, sessionDict) except PreemptiveResponse, pr: DEBUG(WEB, 'got preemptive response') response = pr.responseData except: logException() else: DEBUG(WEB, 'handling connection') HandleConnection(Configuration.job, connection, sessionDict) response = connection.response() # the connection should be available to postResponse and cleanup hooks. sessionDict[constants.CONNECTION] = connection DEBUG(WEB, 'returning response: %s' % response) DEBUG(WEB, 'length of response: %d' % len(response)) return response def _cleanupConfig(requestData, sessionDict): """ function for requestHandler's CleanupRequest hook """ if sessionDict.has_key(constants.HOST):
def requestHandler(connObj, sessionDict): fixPath = AE.Cache._fixPath uri = connObj.uri try: DEBUG(TEMPLATING, "statting %s" % uri) fixed, fs, st = AE.Cache._getPathFSAndMinistat(uri) connObj.statInfo = st except vfs.VFSException: ACCESS("file not found: %s" % uri) return except: return _handleException(connObj) # if a directory fix uri as appropriate if fs.isdir(fixed): DEBUG(TEMPLATING, "%s is a directory" % fixed) if (not uri) or uri[-1] != '/': DEBUG(TEMPLATING, "doesn't end in / redirecting") return _pathSlashRedirect(connObj) else: DEBUG(TEMPLATING, "looping over indexDocuments") for i in Configuration.indexDocuments: s = "%s%s" % (uri, i) #DEBUG(TEMPLATING, "trying %s" % i) fixed = fixPath(Configuration.documentRoot, s) try: st = None st = fs.ministat(fixed) except: #DEBUG(TEMPLATING, "nope") pass else: DEBUG(TEMPLATING, "Bingo!") connObj.statInfo = st break if not st: #no index document exists if Configuration.defaultIndexHtml: s = Configuration.defaultIndexHtml st = AE.Cache._statDocRoot(uri) else: return connObj.uri = s DEBUG(TEMPLATING, "uri is now %s" % s) connObj.mimeType = mimeType = AE.MimeTypes.getMimeType(connObj.uri) DEBUG(TEMPLATING, 'mime type is %s' % mimeType) # don't handle a hidden mime type if mimeType in Configuration.hideMimeTypes: DEBUG(TEMPLATING, "hidden mime type: %s" % mimeType) return if Configuration.mimeHandlers.has_key(mimeType): DEBUG(TEMPLATING, "invoking special mime handler for mime type %s" % mimeType) return Configuration.mimeHandlers[mimeType](connObj, sessionDict) #if not a template, don't handle if not AE.Executables.executableByTypes.has_key( (mimeType, AE.Executables.DT_REGULAR)): DEBUG(TEMPLATING, "not a template mime type: %s" % mimeType) return #if a templatable thing, but we've been told not to interpret it but #to pass it through, ignore and let the plain handler do it if mimeType not in Configuration.interpretMimeTypes: return modTime = st[vfs.MST_CTIME] if mimeType == 'application/x-python': mimeType = 'text/html' connObj.responseHeaders['Content-Type'] = mimeType try: respText = AE.Component.callComponent(connObj.uri, {'CONNECTION': connObj}, srcModTime=modTime) except Redirect: pass except: DEBUG(TEMPLATING, "exception occurred rendering component") return _handleException(connObj) else: connObj.write(respText) return connObj.response()
def delete(self): DEBUG(SESSIONHANDLER, "in delete") args = {'id': self.__id, 'idCol': self.idCol, 'table': self.table} self.execSql(self.deleteSQL % args, expect=0) self._touched = int(time.time())
def send(self, c): DEBUG(FCGIPROT, 'sending %s' % c) self.contents.append(c)
def __call__(self, sock, addr): DEBUG(REQUESTHANDLER, "calling RequestHandler %s" % self) _processRequest(sock, addr, self.protocol)
signal.alarm(Configuration.DocumentTimeout) try: try: DEBUG(REQUESTHANDLER, 'marshalling request') requestData = protocolImpl.marshalRequest(sock, sessionDict) DEBUG(REQUESTHANDLER, 'InitRequest hook') InitRequest(Configuration.job, requestData, sessionDict) except PreemptiveResponse, pr: DEBUG(REQUESTHANDLER, 'got preemptive response') responseData=protocolImpl.marshalResponse(pr.responseData, sessionDict) else: DEBUG(REQUESTHANDLER, 'handling request') rawResponse=HandleRequest(Configuration.job, requestData, sessionDict) DEBUG(REQUESTHANDLER, 'response returned: %s' % rawResponse) DEBUG(REQUESTHANDLER, 'marshalling response') responseData=protocolImpl.marshalResponse(rawResponse, sessionDict) except: try: # the current exception is available anyway, so is not passed; # perhaps nothing should be DEBUG(REQUESTHANDLER, 'marshalling exception') responseData=protocolImpl.marshalException(logException(), sessionDict)
def reap(self): DEBUG(SESSIONHANDLER, "in reap()") args={'timeCol' : self.timeCol, 'timeout' : Session._timeout, 'table' : self.table} self.execSql(self.reapSQL % args, expect=0)