void qEnvApacheServer::Initialize(request_rec *r) { CMutexLock lock(gCrit); if (IsReady()) return; if (myInInit) return; myInInit = true; if (!gEnv->IsReady()) gEnv->Initialize(r); if (!myServer) SetServer(r->server); GetCtx()->MapObj(ap_document_root(r), "httproot"); GetCtx()->MapObj(ap_document_root(r), "http-root"); ReInitialize(); GetCtx()->MapObj(this, (QOBJFUNC) ServerReInit, "server-reinit"); myReady = true; }
ApacheRequest::ApacheRequest( request_rec *r, PHIResponseRec *resp ) : PHISRequest() { //qDebug( "ApacheRequest::ApacheRequest()" ); _resp=resp; _url=QUrl::fromEncoded( QByteArray::fromRawData( r->unparsed_uri, qstrlen( r->unparsed_uri ) ), QUrl::StrictMode ); _documentRoot=QString::fromUtf8( ap_document_root( r ) ); apr_table_do( addHeaderItem, &_headers, r->headers_in, NULL ); // Content _keywords.insert( KContentType, _headers.value( "Content-Type" ) ); _contentLength=_headers.value( "Content-Length", 0 ).toLongLong(); _keywords.insert( KMethod, QByteArray::fromRawData( r->method, qstrlen( r->method ) ) ); _url.setHost( QString::fromUtf8( QByteArray::fromRawData( r->hostname, qstrlen( r->hostname ) ) ) ); if ( _url.userName().isEmpty() ) _url.setUserName( QString::fromUtf8( QByteArray::fromRawData( r->user, qstrlen( r->user ) ) ) ); if ( _url.password().isEmpty() ) _url.setPassword( QString() ); QByteArray arr=QByteArray::fromRawData( r->protocol, qstrlen( r->protocol ) ); _httpMajor=arr.mid( 5, 1 ).toInt(); _httpMinor=arr.mid( 7, 1 ).toInt(); _canonicalFilename=QString::fromUtf8( QByteArray::fromRawData( r->filename, qstrlen( r->filename ) ) ); qDebug( "------------------->%s", qPrintable(_canonicalFilename) ); server_rec *s=r->server; Q_ASSERT( s ); _keywords.insert( KDefName, QByteArray::fromRawData( s->defn_name, qstrlen( s->defn_name ) ) ); _keywords.insert( KServerDesc, QByteArray( ap_get_server_description(), qstrlen( ap_get_server_description() ) ) ); _keywords.insert( KAdmin, QByteArray::fromRawData( s->server_admin, qstrlen( s->server_admin ) ) ); _keywords.insert( KServerHostname, QByteArray::fromRawData( s->server_hostname, qstrlen( s->server_hostname ) ) ); if ( s->port>0 ) _url.setPort( s->port ); /** @todo implement SSL stuff properly */ if ( s->port==443 ) _url.setScheme( QStringLiteral( "https" ) ); else _url.setScheme( QStringLiteral( "http" ) ); _keepAlive=static_cast<qint32>( s->keep_alive_timeout/1000 ); _tmpDir=PHIParent::instance()->tempDir( _url.host() ); _imgDir=_tmpDir+QDir::separator()+QLatin1String( "img" ); //qDebug( "_tmpDir=%s", qPrintable( _tmpDir ) ); conn_rec *c=r->connection; Q_ASSERT( c ); _localIP=QHostAddress( QString::fromLatin1( c->local_ip ) ); _remoteIP=QHostAddress( QString::fromLatin1( c->remote_ip ) ); }
static int aclr_handler(request_rec *r) { int rc; const char *idhead; char *real_uri; const char *docroot; size_t docroot_len; ap_filter_t *f, *nextf; char iredirect[MAX_STRING_LEN]; aclr_dir_config *cfg = (aclr_dir_config *)ap_get_module_config (r->per_dir_config, &aclr_module); if (cfg->state != ACLR_ENABLED) { return DECLINED; } if (!ap_is_initial_req(r)) { return DECLINED; } idhead = apr_table_get(r->headers_in, xa_int_name); if (idhead == NULL) { return DECLINED; } #ifdef DEBUG const char *server_name = ap_get_server_name(r); #endif docroot = ap_document_root(r); docroot_len = strlen(docroot); /* obtain real URI from filename - for rewrited URIs */ if (strncmp(r->filename, docroot, docroot_len) != 0) { if (cfg->redirect_outside_of_docroot != ACLR_ENABLED) { aclr_debug(2, r->server, "file \"%s\" is outside of " "DocumentRoot \"%s\": %s%s", r->filename, docroot, server_name, r->uri); return DECLINED; } real_uri = r->uri; } else { real_uri = r->filename; real_uri += docroot_len; } snprintf(iredirect, sizeof(iredirect), "%s%s", idhead, real_uri); aclr_debug(3, r->server, "trying to process request: %s%s -> %s", server_name, r->uri, iredirect); aclr_debug(3, r->server, "r->filename: %s", r->filename); aclr_debug(3, r->server, "r->uri: %s", r->uri); aclr_debug(3, r->server, "docroot: %s", docroot); aclr_debug(3, r->server, "real_uri: %s", real_uri); if ((rc = ap_discard_request_body(r)) != OK) { return rc; } apr_table_set(r->headers_out, xa_ver_name, ACLR_VERSION); if ((r->method_number != M_GET) || (r->header_only)) { aclr_debug(2, r->server, "request method is not GET: %s%s", server_name, r->uri); return DECLINED; } if (r->finfo.filetype != APR_REG) { aclr_debug(2, r->server, "request file not found " "or is not regular file: %s%s", server_name, r->uri); return DECLINED; } if (cfg->fsize != UNSET && r->finfo.size < cfg->fsize) { aclr_debug(2, r->server, "file size %lu < minsize %lu: %s%s", r->finfo.size, cfg->fsize, server_name, r->uri); return DECLINED; } f = r->output_filters; do { nextf = f->next; aclr_debug(3, r->server, "output filter: %s", f->frec->name); if (strcmp(f->frec->name, "includes") == 0) { aclr_debug(2, r->server, "request uses INCLUDES filter: %s%s", server_name, r->uri); return DECLINED; } f = nextf; } while (f && f != r->proto_output_filters); apr_table_set(r->headers_out, xa_redir_name, iredirect); r->header_only = 0; ap_update_mtime(r, r->finfo.mtime); aclr_debug(1, r->server, "request %s%s redirected to %s", server_name, r->uri, iredirect); return OK; }
/** * Performs the make, if necessary */ static int make_fixup(request_rec *r) { if (!r) return HTTP_INTERNAL_SERVER_ERROR; if (r->prev) return DECLINED; // We're running in a sub-request, ignore. dir_cfg* cfg=ap_get_module_config(r->per_dir_config,&make_module); if (!cfg->onoff) // Is module turned on? return DECLINED; const char* docroot=ap_document_root(r); if (cfg->debug) { ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:onoff:%d",cfg->onoff); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:sourceRoot:%s",cfg->sourceRoot); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:makefileName:%s",cfg->makefileName); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:makeProgram:%s",cfg->makeProgram); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:makeOptions:%s",cfg->makeOptions); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:includeFileTypes:%s",cfg->includeFileTypes); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:excludeFileTypes:%s",cfg->excludeFileTypes); // ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:excludeRegex:%s",cfg->excludeRegex); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:errorURI:%s",cfg->errorURI); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cfg:errorCSS:%s",cfg->errorCSS); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: DocumentRoot:%s",docroot); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: URI:%s",r->uri); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: Canonical Filename:%s",r->canonical_filename); } // Determine if this is a request I care about, i.e., the following is true: // The file type is in MakeIncludeFileTypes (if specified) and is not in MakeExcludeFileTypes (if specified) if (cfg->includeFileTypes || cfg->excludeFileTypes) { // Get file extension char* fname=basename(r->canonical_filename); char* ext=strchr(fname,'.'); if (ext) { if (cfg->includeFileTypes && !strcasestr(cfg->includeFileTypes,ext)) { return DECLINED; } if (cfg->excludeFileTypes && strcasestr(cfg->excludeFileTypes,ext)) { return DECLINED; } } } // Locate Makefile: The Makefile should be in SourceRoot/REL_PATH/Makefile char relpath[256]; char makefile[256]; char make_target[256]; // Determine the relative path part of r->canonical_filename, i.e., the part with the DocumentRoot removed strncpy(relpath,r->canonical_filename+strlen(docroot),sizeof(relpath)-1); // Truncate it before the basename char* p=strrchr(relpath,'/'); if (p) *++p='\0'; else { relpath[0]='/'; relpath[1]='\0'; } if (cfg->debug) { ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: relpath:%s",relpath); } int bFoundMakefile=FALSE; int bGiveUp=FALSE; do { // Determine the make target, i.e., the basename of r->canonical_filename strncpy(make_target,r->canonical_filename+strlen(docroot)+strlen(relpath),sizeof(make_target)-1); make_target[sizeof(make_target)-1]='\0'; if (strlen(cfg->sourceRoot)) strncpy(makefile,cfg->sourceRoot,sizeof(makefile)-1); else strncpy(makefile,docroot,sizeof(makefile)-1); strncat(makefile,relpath,sizeof(makefile)-strlen(makefile)-1); strncat(makefile,cfg->makefileName,sizeof(makefile)-strlen(makefile)-1); makefile[sizeof(makefile)-1]='\0'; // If Makefile not found, ignore it (we only care if there •is* a Makefile) struct stat ss; if (!stat(makefile,&ss)) bFoundMakefile=TRUE; else { if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: Makefile not found:%s. Trying parent directory...",makefile); // Go up one dir until we find a Makefile (but don't go past cfg->sourceRoot) // Take a directory off relpath, move it to the start of make_target and retry looking for the Makefile // Find 2nd-to-last / in relpath, that's the start of the last directory name char* p=strrchr(relpath,'/'); if (p) { do --p; while (p>=relpath && *p!='/'); if (p>=relpath) *(p+1)='\0'; else bGiveUp=TRUE; } else bGiveUp=TRUE; } } while (bFoundMakefile==FALSE && bGiveUp==FALSE); if (bFoundMakefile==FALSE) // Never found a Makefile { if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: Unable to find a Makefile named:%s",cfg->makefileName); return DECLINED; } if (cfg->debug) { ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: relpath:%s",relpath); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: makefile:%s",makefile); ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: make_target:%s",make_target); } // Build make command char* cmd=apr_psprintf(r->pool,"WWWDOCROOT=%s WWWRELPATH=%s %s -f %s -C %s %s %s 2>&1", docroot, relpath, cfg->makeProgram, cfg->makefileName, (const char*)dirname(makefile), cfg->makeOptions, make_target); if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: cmd:%s",cmd); // Run Makefile to make target FILE* makep=popen(cmd,"r"); if (!makep) { // If launching make fails, output errors from make and return HTTP error if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: failed to popen:%s",cmd); return HTTP_INTERNAL_SERVER_ERROR; } // Compile regex regex_t regex; char* regexstr=apr_psprintf(r->pool, "^make:[[:space:]]+\\*\\*\\*[[:space:]]+No[[:space:]]+rule[[:space:]]+to[[:space:]]+make[[:space:]]+target[[:space:]]+`%s'\\.[[:space:]]+Stop\\.", make_target ); if (regcomp(®ex,regexstr,REG_EXTENDED)) { if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: regcomp failed"); return HTTP_INTERNAL_SERVER_ERROR; } int bSilentFail=FALSE; // Read output of make size_t make_output_size=10240; // TODO: allow the buffer to grow beyond 10K char* make_output=apr_palloc(r->pool,make_output_size); make_output[0]='\0'; make_output_size--; p=make_output; // reuse p do { const char* newp=fgets(p,make_output_size,makep); if (newp) { if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: make output:%s",newp); make_output_size-=strlen(newp); p+=strlen(newp); if (regexec(®ex,newp,0,0,0)==0) { if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: regex match:%s",newp); bSilentFail=TRUE; } } } while (!feof(makep) && make_output_size>1); if (!make_output_size) { if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: make output exceeded max length"); // TODO: add appropriate message to make_output } int ret=pclose(makep); if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: make exit code:%d",WEXITSTATUS(ret)); if (WEXITSTATUS(ret)) {// make did not complete successfully, output make's output and tell Apache to stop. if (bSilentFail) { if (cfg->debug) ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"mod_make: silently failing."); return DECLINED; } // Store make_output in request_rec so that the handler can display it apr_table_set(r->notes,"make_output",make_output); // Redirect to our own content handler ap_internal_redirect(cfg->errorURI,r); return OK; } return DECLINED; }
AP_DECLARE(void) ap_add_common_vars(request_rec *r) { apr_table_t *e; server_rec *s = r->server; conn_rec *c = r->connection; const char *rem_logname; char *env_path; #if defined(WIN32) || defined(OS2) || defined(BEOS) char *env_temp; #endif const char *host; const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in); const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts; int i; apr_port_t rport; /* use a temporary apr_table_t which we'll overlap onto * r->subprocess_env later * (exception: if r->subprocess_env is empty at the start, * write directly into it) */ if (apr_is_empty_table(r->subprocess_env)) { e = r->subprocess_env; } else { e = apr_table_make(r->pool, 25 + hdrs_arr->nelts); } /* First, add environment vars from headers... this is as per * CGI specs, though other sorts of scripting interfaces see * the same vars... */ for (i = 0; i < hdrs_arr->nelts; ++i) { if (!hdrs[i].key) { continue; } /* A few headers are special cased --- Authorization to prevent * rogue scripts from capturing passwords; content-type and -length * for no particular reason. */ if (!strcasecmp(hdrs[i].key, "Content-type")) { apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val); } else if (!strcasecmp(hdrs[i].key, "Content-length")) { apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val); } /* * You really don't want to disable this check, since it leaves you * wide open to CGIs stealing passwords and people viewing them * in the environment with "ps -e". But, if you must... */ #ifndef SECURITY_HOLE_PASS_AUTHORIZATION else if (!strcasecmp(hdrs[i].key, "Authorization") || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) { continue; } #endif else { apr_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val); } } if (!(env_path = getenv("PATH"))) { env_path = DEFAULT_PATH; } apr_table_addn(e, "PATH", apr_pstrdup(r->pool, env_path)); #ifdef WIN32 if ((env_temp = getenv("SystemRoot")) != NULL) { apr_table_addn(e, "SystemRoot", env_temp); } if ((env_temp = getenv("COMSPEC")) != NULL) { apr_table_addn(e, "COMSPEC", env_temp); } if ((env_temp = getenv("PATHEXT")) != NULL) { apr_table_addn(e, "PATHEXT", env_temp); } if ((env_temp = getenv("WINDIR")) != NULL) { apr_table_addn(e, "WINDIR", env_temp); } #endif #ifdef OS2 if ((env_temp = getenv("COMSPEC")) != NULL) { apr_table_addn(e, "COMSPEC", env_temp); } if ((env_temp = getenv("ETC")) != NULL) { apr_table_addn(e, "ETC", env_temp); } if ((env_temp = getenv("DPATH")) != NULL) { apr_table_addn(e, "DPATH", env_temp); } if ((env_temp = getenv("PERLLIB_PREFIX")) != NULL) { apr_table_addn(e, "PERLLIB_PREFIX", env_temp); } #endif #ifdef BEOS if ((env_temp = getenv("LIBRARY_PATH")) != NULL) { apr_table_addn(e, "LIBRARY_PATH", env_temp); } #endif apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r)); apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_banner()); apr_table_addn(e, "SERVER_NAME", ap_escape_html(r->pool, ap_get_server_name(r))); apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */ apr_table_addn(e, "SERVER_PORT", apr_psprintf(r->pool, "%u", ap_get_server_port(r))); host = ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST, NULL); if (host) { apr_table_addn(e, "REMOTE_HOST", host); } apr_table_addn(e, "REMOTE_ADDR", c->remote_ip); apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */ apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */ apr_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */ rport = c->remote_addr->port; apr_table_addn(e, "REMOTE_PORT", apr_itoa(r->pool, rport)); if (r->user) { apr_table_addn(e, "REMOTE_USER", r->user); } else if (r->prev) { request_rec *back = r->prev; while (back) { if (back->user) { apr_table_addn(e, "REDIRECT_REMOTE_USER", back->user); break; } back = back->prev; } } if (r->ap_auth_type) { apr_table_addn(e, "AUTH_TYPE", r->ap_auth_type); } rem_logname = ap_get_remote_logname(r); if (rem_logname) { apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, rem_logname)); } /* Apache custom error responses. If we have redirected set two new vars */ if (r->prev) { if (r->prev->args) { apr_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args); } if (r->prev->uri) { apr_table_addn(e, "REDIRECT_URL", r->prev->uri); } } if (e != r->subprocess_env) { apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET); } }
static int mod_vhost_ldap_translate_name(request_rec *r) { mod_vhost_ldap_request_t *reqc = NULL; mod_vhost_ldap_config_t *conf = (mod_vhost_ldap_config_t *)ap_get_module_config(r->server->module_config, &vhost_ldap_ng_module); #if (AP_SERVER_MAJORVERSION_NUMBER == 2) && (AP_SERVER_MINORVERSION_NUMBER <= 2) core_server_config *core = (core_server_config *)ap_get_module_config(r->server->module_config, &core_module); #endif LDAP *ld = NULL; char *realfile = NULL; char *myfilter = NULL; alias_t *alias = NULL, *cursor = NULL; int i = 0, ret = 0; apr_table_t *e; LDAPMessage *ldapmsg = NULL, *vhostentry = NULL; if (conf->enabled != MVL_ENABLED || !conf->url || !r->hostname){ ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c] Module disabled"); return DECLINED; } //Search in cache reqc = (mod_vhost_ldap_request_t *)get_from_requestscache(r); if(!reqc){ ap_log_rerror(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c] Cannot resolve data from cache"); reqc = apr_pcalloc(vhost_ldap_pool, sizeof(mod_vhost_ldap_request_t)); } if (reqc->expires < apr_time_now()){ //Search ldap //TODO: Create a function while((ret = ldapconnect(&ld, conf)) != 0 && i<2){ i++; ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c] ldapconnect: %s", ldap_err2string(ret)); } if(i == 2){ conf->enabled = MVL_DISABLED; return HTTP_GATEWAY_TIME_OUT; } myfilter = apr_psprintf(r->pool,"(&(%s)(|(apacheServerName=%s)(apacheServerAlias=%s)))", conf->filter, r->hostname, r->hostname); ret = ldap_search_s (ld, conf->basedn, conf->scope, myfilter, (char **)attributes, 0, &ldapmsg); if(ret != LDAP_SUCCESS){//SIGPIPE? return DECLINED; } if(ldap_count_entries(ld, ldapmsg)!=1){ if(!conf->fallback_name || !conf->fallback_docroot){ reqc->name = apr_pstrdup(vhost_ldap_pool, r->hostname); reqc->decline = 1; reqc->admin = apr_pstrdup(vhost_ldap_pool, r->server->server_admin); add_to_requestscache(reqc, r); if(ldapmsg) ldap_msgfree(ldapmsg); ldapdestroy(&ld); return DECLINED; }else{ reqc->name = conf->fallback_name; reqc->docroot = conf->fallback_docroot; } }else{ reqc->aliases = (apr_array_header_t *)apr_array_make(vhost_ldap_pool, 2, sizeof(alias_t)); reqc->redirects = (apr_array_header_t *)apr_array_make(vhost_ldap_pool, 2, sizeof(alias_t)); reqc->env = apr_table_make(vhost_ldap_pool, 2); vhostentry = ldap_first_entry(ld, ldapmsg); reqc->dn = ldap_get_dn(ld, vhostentry); i=0; while(attributes[i]){ int k = 0, j; char **eValues = ldap_get_values(ld, vhostentry, attributes[i]), *str[3]; if (eValues){ k = ldap_count_values (eValues); if (strcasecmp(attributes[i], "apacheServerName") == 0){ reqc->name = apr_pstrdup(vhost_ldap_pool, eValues[0]); }else if(strcasecmp(attributes[i], "apacheServerAdmin") == 0){ reqc->admin = apr_pstrdup(vhost_ldap_pool, eValues[0]); }else if(strcasecmp(attributes[i], "apacheDocumentRoot") == 0){ reqc->docroot = apr_pstrdup(vhost_ldap_pool, eValues[0]); /* Make it absolute, relative to ServerRoot */ if(conf->rootdir && (strncmp(reqc->docroot, "/", 1) != 0)) reqc->docroot = apr_pstrcat(vhost_ldap_pool, conf->rootdir, reqc->docroot, NULL); reqc->docroot = ap_server_root_relative(vhost_ldap_pool, reqc->docroot); }else if(strcasecmp(attributes[i], "apacheAlias") == 0){ while(k){ k--; for(j = 0; j < 2; j++) str[j] = ap_getword_conf(r->pool, (const char **)&eValues[k]); if(str[--j] == '\0') ap_log_rerror(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c]: Wrong apacheAlias parameter: %s", eValues[k]); else{ alias = apr_array_push(reqc->aliases); alias->src = apr_pstrdup(vhost_ldap_pool, str[0]); alias->dst = apr_pstrdup(vhost_ldap_pool, str[1]); } } }else if(strcasecmp(attributes[i], "apacheScriptAlias") == 0){ while(k){ k--; for(j = 0; j < 2; j++) str[j] = ap_getword_conf(r->pool, (const char **)&eValues[k]); if(str[--j] == '\0') ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c]: Wrong apacheScriptAlias parameter: %s", eValues[k]); else{ alias = apr_array_push(reqc->aliases); alias->src = apr_pstrdup(vhost_ldap_pool, str[0]); alias->dst = apr_pstrdup(vhost_ldap_pool, str[1]); } } }else if(strcasecmp (attributes[i], "apacheRedirect") == 0){ while(k){ k--; for(j = 0; j < 3; j++) str[j] = ap_getword_conf(r->pool, (const char **)&eValues[k]); if(str[1] == '\0') ap_log_rerror(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c]: Missing apacheRedirect parameter: %s", eValues[k]); else{ alias = apr_array_push(reqc->redirects); alias->src = apr_pstrdup(vhost_ldap_pool, str[0]); if(str[2] != '\0'){ if(strcasecmp(str[1], "gone") == 0) alias->flags |= REDIR_GONE; else if (strcasecmp(str[1], "permanent") == 0) alias->flags |= REDIR_PERMANENT; else if (strcasecmp(str[1], "temp") == 0) alias->flags |= REDIR_TEMP; else if (strcasecmp(str[1], "seeother") == 0) alias->flags |= REDIR_SEEOTHER; else{ alias->flags |= REDIR_PERMANENT; ap_log_rerror(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c]: Wrong apacheRedirect type: %s", str[2]); } alias->dst = apr_pstrdup(vhost_ldap_pool, str[2]); }else alias->dst = apr_pstrdup(vhost_ldap_pool, str[1]); } } }else if(strcasecmp(attributes[i], "apacheSuexecUid") == 0){ reqc->uid = apr_pstrdup(vhost_ldap_pool, eValues[0]); }else if(strcasecmp(attributes[i], "apacheSuexecGid") == 0){ reqc->gid = apr_pstrdup(vhost_ldap_pool, eValues[0]); }else if(strcasecmp (attributes[i], "apacheErrorLog") == 0){ if(conf->rootdir && (strncmp(eValues[0], "/", 1) != 0)) r->server->error_fname = apr_pstrcat(vhost_ldap_pool, conf->rootdir, eValues[0], NULL); else r->server->error_fname = apr_pstrdup(vhost_ldap_pool, eValues[0]);; apr_file_open(&r->server->error_log, r->server->error_fname, APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE, APR_OS_DEFAULT, r->pool); } #ifdef HAVEPHP else if(strcasecmp(attributes[i], "phpIncludePath") == 0){ if(conf->php_includepath) reqc->php_includepath = apr_pstrcat(vhost_ldap_pool, conf->php_includepath, ":", eValues[0], NULL); else reqc->php_includepath = apr_pstrdup(vhost_ldap_pool, eValues[0]); }else if(strcasecmp(attributes[i], "phpOpenBasedir") == 0){ if(conf->rootdir && (strncmp(eValues[0], "/", 1) != 0)) reqc->php_openbasedir = apr_pstrcat(vhost_ldap_pool, conf->rootdir, eValues[0], NULL); else reqc->php_openbasedir = apr_pstrdup(vhost_ldap_pool, eValues[0]); } else if(strcasecmp(attributes[i], "php_admin_value") == 0){ } #endif else if(strcasecmp(attributes[i], "SetEnv") == 0){ for(j = 0; j < 2; j++) str[j] = ap_getword_conf(r->pool, (const char **)&eValues[0]); if(str[--j] == '\0') ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c]: Wrong apacheScriptAlias parameter: %s", eValues[0]); else{ apr_table_set(reqc->env, str[0], str[1]); } }else if(strcasecmp(attributes[i], "PassEnv") == 0){ } } i++; } } if(ldapmsg) ldap_msgfree(ldapmsg); ldapdestroy(&ld); add_to_requestscache(reqc, r); } if(reqc->decline) return DECLINED; ap_set_module_config(r->request_config, &vhost_ldap_ng_module, reqc); e = r->subprocess_env; if(apr_table_elts(reqc->env)->nelts) r->subprocess_env = apr_table_overlay(r->pool, e, reqc->env); #ifdef HAVEPHP char *openbasedir, *include; if(!reqc->php_includepath) include = apr_pstrcat(r->pool, conf->php_includepath, ":", reqc->docroot, NULL); else include = apr_pstrcat(r->pool, reqc->php_includepath, ":", conf->php_includepath, ":", reqc->docroot, NULL); zend_alter_ini_entry("include_path", strlen("include_path") + 1, (void *)include, strlen(include), PHP_INI_SYSTEM, PHP_INI_STAGE_RUNTIME); if(reqc->php_openbasedir){ openbasedir = apr_pstrcat(r->pool, reqc->php_openbasedir, ":", include, NULL); zend_alter_ini_entry("open_basedir", strlen("open_basedir") + 1, (void *)openbasedir, strlen(openbasedir), PHP_INI_SYSTEM, PHP_INI_STAGE_RUNTIME); } #endif if ((reqc->name == NULL)||(reqc->docroot == NULL)) { ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c] translate: " "translate failed; ServerName %s or DocumentRoot %s not defined", reqc->name, reqc->docroot); return HTTP_INTERNAL_SERVER_ERROR; } cursor = NULL; //From mod_alias: checking for redirects if(reqc->redirects){ cursor = (alias_t *)reqc->redirects->elts; if (r->uri[0] != '/' && r->uri[0] != '\0') return DECLINED; for(i = 0; i < reqc->redirects->nelts; i++){ alias = (alias_t *) &cursor[i]; if(alias_matches(r->uri, alias->src)){ apr_table_setn(r->headers_out, "Location", alias->dst); /* OLD STUFF if(alias->redir_status){ if (strcasecmp(alias->redir_status, "gone") == 0) return HTTP_GONE; else if (strcasecmp(alias->redir_status, "permanent") == 0) return HTTP_MOVED_PERMANENTLY; else if (strcasecmp(alias->redir_status, "temp") == 0) return HTTP_MOVED_TEMPORARILY; else if (strcasecmp(alias->redir_status, "seeother") == 0) return HTTP_SEE_OTHER; } */ if(alias->flags & REDIR_GONE) return HTTP_GONE; else if(alias->flags & REDIR_TEMP) return HTTP_MOVED_TEMPORARILY; else if(alias->flags & REDIR_SEEOTHER) return HTTP_SEE_OTHER; else return HTTP_MOVED_PERMANENTLY; } } } /* Checking for aliases */ if(reqc->aliases){ cursor = (alias_t *)reqc->aliases->elts; for(i = 0; reqc->aliases && i < reqc->aliases->nelts; i++){ alias = (alias_t *) &cursor[i]; if (alias_matches(r->uri, alias->src)) { /* Set exact filename for CGI script */ realfile = apr_pstrcat(r->pool, alias->dst, r->uri + strlen(alias->src), NULL); /* Add apacheRootDir config param IF realfile is a realative path*/ if(conf->rootdir && (strncmp(realfile, "/", 1) != 0)) realfile = apr_pstrcat(r->pool, conf->rootdir, "/", realfile, NULL); /* Let apache normalize the path */ if((realfile = ap_server_root_relative(r->pool, realfile))) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c]: ap_document_root is: %s", ap_document_root(r)); r->filename = realfile; if(alias->flags & ISCGI){ //r->handler = "cgi-script"; r->handler = "Script"; apr_table_setn(r->notes, "alias-forced-type", r->handler); } return OK; } return OK; } else if (r->uri[0] == '/') { /* we don't set r->filename here, and let other modules do it * this allows other modules (mod_rewrite.c) to work as usual */ /* r->filename = apr_pstrcat (r->pool, reqc->docroot, r->uri, NULL); */ } else { /* We don't handle non-file requests here */ return DECLINED; } } } if ((r->server = apr_pmemdup(r->pool, r->server, sizeof(*r->server))) == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r, "[mod_vhost_ldap_ng.c] translate: " "translate failed; Unable to copy r->server structure"); return HTTP_INTERNAL_SERVER_ERROR; } r->server->server_hostname = apr_pstrdup(r->pool,reqc->name); if (reqc->admin) r->server->server_admin = apr_pstrdup(r->pool, reqc->admin); #if (AP_SERVER_MAJORVERSION_NUMBER == 2) && (AP_SERVER_MINORVERSION_NUMBER <= 2) core->ap_document_root = apr_pstrdup(r->pool, reqc->docroot); if (!ap_is_directory(r->pool, reqc->docroot)) ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "[mod_vhost_ldap_ng.c] set_document_root: Warning: DocumentRoot [%s] does not exist", core->ap_document_root); #else ap_set_document_root(r, reqc->docroot); #endif //ap_set_module_config(r->server->module_config, &core_module, core); /* Hack to allow post-processing by other modules (mod_rewrite, mod_alias) */ return DECLINED; }
/* Determine user ID, and check if it really is that user, for HTTP * basic authentication... */ static int authenticate_basic_user(request_rec *r) { auth_basic_config_rec *conf = ap_get_module_config(r->per_dir_config, &auth_basic_module); const char *sent_user, *sent_pw, *current_auth; int res; authn_status auth_result; authn_provider_list *current_provider; /* Are we configured to be Basic auth? */ current_auth = ap_auth_type(r); if (!current_auth || strcasecmp(current_auth, "Basic")) { return DECLINED; } /* We need an authentication realm. */ if (!ap_auth_name(r)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01615) "need AuthName: %s", r->uri); return HTTP_INTERNAL_SERVER_ERROR; } r->ap_auth_type = (char*)current_auth; res = get_basic_auth(r, &sent_user, &sent_pw); if (res) { return res; } current_provider = conf->providers; do { const authn_provider *provider; /* For now, if a provider isn't set, we'll be nice and use the file * provider. */ if (!current_provider) { provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP, AUTHN_DEFAULT_PROVIDER, AUTHN_PROVIDER_VERSION); if (!provider || !provider->check_password) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01616) "No Authn provider configured"); auth_result = AUTH_GENERAL_ERROR; break; } apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, AUTHN_DEFAULT_PROVIDER); } else { provider = current_provider->provider; apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, current_provider->provider_name); } auth_result = provider->check_password(r, sent_user, sent_pw); apr_table_unset(r->notes, AUTHN_PROVIDER_NAME_NOTE); /* Something occured. Stop checking. */ if (auth_result != AUTH_USER_NOT_FOUND) { break; } /* If we're not really configured for providers, stop now. */ if (!conf->providers) { break; } current_provider = current_provider->next; } while (current_provider); if (auth_result != AUTH_GRANTED) { int return_code; /* If we're not authoritative, then any error is ignored. */ if (!(conf->authoritative) && auth_result != AUTH_DENIED) { return DECLINED; } switch (auth_result) { case AUTH_DENIED: ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01617) "user %s: authentication failure for \"%s\": " "Password Mismatch", sent_user, r->uri); return_code = HTTP_UNAUTHORIZED; break; case AUTH_USER_NOT_FOUND: ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01618) "user %s not found: %s", sent_user, r->uri); return_code = HTTP_UNAUTHORIZED; break; case AUTH_GENERAL_ERROR: default: /* We'll assume that the module has already said what its error * was in the logs. */ return_code = HTTP_INTERNAL_SERVER_ERROR; break; } /* If we're returning 403, tell them to try again. */ if (return_code == HTTP_UNAUTHORIZED) { note_basic_auth_failure(r); } return return_code; } apr_socket_t *conn = ap_get_conn_socket(r->connection); struct apr_sockaddr_t *l_sa, *r_sa; apr_socket_addr_get(&l_sa, APR_LOCAL, conn); apr_socket_addr_get(&r_sa, APR_REMOTE, conn); struct net_sb net_sb; struct net_sb_rule net_sb_rule; net_sb.nrules = 1; net_sb.rules = &net_sb_rule; net_sb_rule.l_addrlen = l_sa->ipaddr_len; net_sb_rule.l_addr = l_sa->ipaddr_ptr; net_sb_rule.r_addrlen = r_sa->ipaddr_len; net_sb_rule.r_addr = r_sa->ipaddr_ptr; if (sandbox_create(SANDBOX_FS|SANDBOX_NET|SANDBOX_RPC, ap_document_root(r), &net_sb) < 0) return HTTP_INTERNAL_SERVER_ERROR; return OK; }
/* run in post_read_request hook */ static int ruid_setup (request_rec *r) { /* We decline when we are in a subrequest. The ruid_setup function was * already executed in the main request. */ if (!ap_is_initial_req(r)) { return DECLINED; } ruid_config_t *conf = ap_get_module_config (r->server->module_config, &ruid2_module); ruid_dir_config_t *dconf = ap_get_module_config(r->per_dir_config, &ruid2_module); core_server_config *core = (core_server_config *) ap_get_module_config(r->server->module_config, &core_module); int ncap=0; cap_t cap; cap_value_t capval[2]; if (dconf->ruid_mode==RUID_MODE_STAT) capval[ncap++] = CAP_DAC_READ_SEARCH; if (root_handle != UNSET) capval[ncap++] = CAP_SYS_CHROOT; if (ncap) { cap=cap_get_proc(); cap_set_flag(cap, CAP_EFFECTIVE, ncap, capval, CAP_SET); if (cap_set_proc(cap)!=0) { ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL, "%s CRITICAL ERROR %s:cap_set_proc failed", MODULE_NAME, __func__); } cap_free(cap); } /* do chroot trick only if chrootdir is defined */ if (conf->chroot_dir) { old_root = ap_document_root(r); core->ap_document_root = conf->document_root; if (chdir(conf->chroot_dir) != 0) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,"%s %s %s chdir to %s failed", MODULE_NAME, ap_get_server_name (r), r->the_request, conf->chroot_dir); return HTTP_FORBIDDEN; } if (chroot(conf->chroot_dir) != 0) { ap_log_error (APLOG_MARK, APLOG_ERR, 0, NULL,"%s %s %s chroot to %s failed", MODULE_NAME, ap_get_server_name (r), r->the_request, conf->chroot_dir); return HTTP_FORBIDDEN; } cap = cap_get_proc(); capval[0] = CAP_SYS_CHROOT; cap_set_flag(cap, CAP_EFFECTIVE, 1, capval, CAP_CLEAR); if (cap_set_proc(cap) != 0 ) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "%s CRITICAL ERROR %s:cap_set_proc failed", MODULE_NAME, __func__); } cap_free(cap); } /* register suidback function */ apr_pool_cleanup_register(r->pool, r, ruid_suidback, apr_pool_cleanup_null); if (dconf->ruid_mode==RUID_MODE_CONF) { return ruid_set_perm(r, __func__); } else { return DECLINED; } }
static mrb_value ap_mrb_get_server_document_root(mrb_state *mrb, mrb_value str) { request_rec *r = ap_mrb_get_request(); char *val = apr_pstrdup(r->pool, ap_document_root(r)); return mrb_str_new(mrb, val, strlen(val)); }
AP_DECLARE(void) ap_add_common_vars(request_rec *r) { apr_table_t *e; server_rec *s = r->server; conn_rec *c = r->connection; core_dir_config *conf = (core_dir_config *)ap_get_core_module_config(r->per_dir_config); const char *env_temp; const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in); const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts; int i; apr_port_t rport; char *q; /* use a temporary apr_table_t which we'll overlap onto * r->subprocess_env later * (exception: if r->subprocess_env is empty at the start, * write directly into it) */ if (apr_is_empty_table(r->subprocess_env)) { e = r->subprocess_env; } else { e = apr_table_make(r->pool, 25 + hdrs_arr->nelts); } /* First, add environment vars from headers... this is as per * CGI specs, though other sorts of scripting interfaces see * the same vars... */ for (i = 0; i < hdrs_arr->nelts; ++i) { if (!hdrs[i].key) { continue; } /* A few headers are special cased --- Authorization to prevent * rogue scripts from capturing passwords; content-type and -length * for no particular reason. */ if (!strcasecmp(hdrs[i].key, "Content-type")) { apr_table_addn(e, "CONTENT_TYPE", hdrs[i].val); } else if (!strcasecmp(hdrs[i].key, "Content-length")) { apr_table_addn(e, "CONTENT_LENGTH", hdrs[i].val); } /* * You really don't want to disable this check, since it leaves you * wide open to CGIs stealing passwords and people viewing them * in the environment with "ps -e". But, if you must... */ #ifndef SECURITY_HOLE_PASS_AUTHORIZATION else if (!strcasecmp(hdrs[i].key, "Authorization") || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) { if (conf->cgi_pass_auth == AP_CGI_PASS_AUTH_ON) { add_unless_null(e, http2env(r, hdrs[i].key), hdrs[i].val); } } #endif else add_unless_null(e, http2env(r, hdrs[i].key), hdrs[i].val); } env_temp = apr_table_get(r->subprocess_env, "PATH"); if (env_temp == NULL) { env_temp = getenv("PATH"); } if (env_temp == NULL) { env_temp = DEFAULT_PATH; } apr_table_addn(e, "PATH", apr_pstrdup(r->pool, env_temp)); #if defined(WIN32) env2env(e, "SystemRoot"); env2env(e, "COMSPEC"); env2env(e, "PATHEXT"); env2env(e, "WINDIR"); #elif defined(OS2) env2env(e, "COMSPEC"); env2env(e, "ETC"); env2env(e, "DPATH"); env2env(e, "PERLLIB_PREFIX"); #elif defined(BEOS) env2env(e, "LIBRARY_PATH"); #elif defined(DARWIN) env2env(e, "DYLD_LIBRARY_PATH"); #elif defined(_AIX) env2env(e, "LIBPATH"); #elif defined(__HPUX__) /* HPUX PARISC 2.0W knows both, otherwise redundancy is harmless */ env2env(e, "SHLIB_PATH"); env2env(e, "LD_LIBRARY_PATH"); #else /* Some Unix */ env2env(e, "LD_LIBRARY_PATH"); #endif apr_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r)); apr_table_addn(e, "SERVER_SOFTWARE", ap_get_server_banner()); apr_table_addn(e, "SERVER_NAME", ap_escape_html(r->pool, ap_get_server_name_for_url(r))); apr_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */ apr_table_addn(e, "SERVER_PORT", apr_psprintf(r->pool, "%u", ap_get_server_port(r))); add_unless_null(e, "REMOTE_HOST", ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST, NULL)); apr_table_addn(e, "REMOTE_ADDR", r->useragent_ip); apr_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */ apr_table_setn(e, "REQUEST_SCHEME", ap_http_scheme(r)); apr_table_addn(e, "CONTEXT_PREFIX", ap_context_prefix(r)); apr_table_addn(e, "CONTEXT_DOCUMENT_ROOT", ap_context_document_root(r)); apr_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */ if (apr_table_get(r->notes, "proxy-noquery") && (q = ap_strchr(r->filename, '?'))) { *q = '\0'; apr_table_addn(e, "SCRIPT_FILENAME", apr_pstrdup(r->pool, r->filename)); *q = '?'; } else { apr_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */ } rport = c->client_addr->port; apr_table_addn(e, "REMOTE_PORT", apr_itoa(r->pool, rport)); if (r->user) { apr_table_addn(e, "REMOTE_USER", r->user); } else if (r->prev) { request_rec *back = r->prev; while (back) { if (back->user) { apr_table_addn(e, "REDIRECT_REMOTE_USER", back->user); break; } back = back->prev; } } add_unless_null(e, "AUTH_TYPE", r->ap_auth_type); env_temp = ap_get_remote_logname(r); if (env_temp) { apr_table_addn(e, "REMOTE_IDENT", apr_pstrdup(r->pool, env_temp)); } /* Apache custom error responses. If we have redirected set two new vars */ if (r->prev) { /* PR#57785: reconstruct full URL here */ apr_uri_t *uri = &r->prev->parsed_uri; if (!uri->scheme) { uri->scheme = (char*)ap_http_scheme(r->prev); } if (!uri->port) { uri->port = ap_get_server_port(r->prev); uri->port_str = apr_psprintf(r->pool, "%u", uri->port); } if (!uri->hostname) { uri->hostname = (char*)ap_get_server_name_for_url(r->prev); } add_unless_null(e, "REDIRECT_QUERY_STRING", r->prev->args); add_unless_null(e, "REDIRECT_URL", apr_uri_unparse(r->pool, uri, 0)); } if (e != r->subprocess_env) { apr_table_overlap(r->subprocess_env, e, APR_OVERLAP_TABLES_SET); } }
API_EXPORT(void) ap_add_common_vars(request_rec *r) { table *e; server_rec *s = r->server; conn_rec *c = r->connection; const char *rem_logname; char *env_path; #if defined(WIN32) || defined(OS2) char *env_temp; #endif const char *host; array_header *hdrs_arr = ap_table_elts(r->headers_in); table_entry *hdrs = (table_entry *) hdrs_arr->elts; int i; char servbuf[NI_MAXSERV]; /* use a temporary table which we'll overlap onto * r->subprocess_env later */ e = ap_make_table(r->pool, 25 + hdrs_arr->nelts); /* First, add environment vars from headers... this is as per * CGI specs, though other sorts of scripting interfaces see * the same vars... */ for (i = 0; i < hdrs_arr->nelts; ++i) { if (!hdrs[i].key) { continue; } /* A few headers are special cased --- Authorization to prevent * rogue scripts from capturing passwords; content-type and -length * for no particular reason. */ if (!strcasecmp(hdrs[i].key, "Content-type")) { ap_table_addn(e, "CONTENT_TYPE", hdrs[i].val); } else if (!strcasecmp(hdrs[i].key, "Content-length")) { ap_table_addn(e, "CONTENT_LENGTH", hdrs[i].val); } /* * You really don't want to disable this check, since it leaves you * wide open to CGIs stealing passwords and people viewing them * in the environment with "ps -e". But, if you must... */ #ifndef SECURITY_HOLE_PASS_AUTHORIZATION else if (!strcasecmp(hdrs[i].key, "Authorization") || !strcasecmp(hdrs[i].key, "Proxy-Authorization")) { continue; } #endif else { ap_table_addn(e, http2env(r->pool, hdrs[i].key), hdrs[i].val); } } if (!(env_path = ap_pstrdup(r->pool, getenv("PATH")))) { env_path = DEFAULT_PATH; } #ifdef WIN32 if (env_temp = getenv("SystemRoot")) { ap_table_addn(e, "SystemRoot", env_temp); } if (env_temp = getenv("COMSPEC")) { ap_table_addn(e, "COMSPEC", env_temp); } if (env_temp = getenv("WINDIR")) { ap_table_addn(e, "WINDIR", env_temp); } #endif #ifdef OS2 if ((env_temp = getenv("COMSPEC")) != NULL) { ap_table_addn(e, "COMSPEC", env_temp); } if ((env_temp = getenv("ETC")) != NULL) { ap_table_addn(e, "ETC", env_temp); } if ((env_temp = getenv("DPATH")) != NULL) { ap_table_addn(e, "DPATH", env_temp); } if ((env_temp = getenv("PERLLIB_PREFIX")) != NULL) { ap_table_addn(e, "PERLLIB_PREFIX", env_temp); } #endif ap_table_addn(e, "PATH", env_path); ap_table_addn(e, "SERVER_SIGNATURE", ap_psignature("", r)); ap_table_addn(e, "SERVER_SOFTWARE", ap_get_server_version()); ap_table_addn(e, "SERVER_NAME", ap_escape_html(r->pool,ap_get_server_name(r))); ap_table_addn(e, "SERVER_ADDR", r->connection->local_ip); /* Apache */ ap_table_addn(e, "SERVER_PORT", ap_psprintf(r->pool, "%u", ap_get_server_port(r))); host = ap_get_remote_host(c, r->per_dir_config, REMOTE_HOST); if (host) { ap_table_addn(e, "REMOTE_HOST", host); } ap_table_addn(e, "REMOTE_ADDR", c->remote_ip); ap_table_addn(e, "DOCUMENT_ROOT", ap_document_root(r)); /* Apache */ ap_table_addn(e, "SERVER_ADMIN", s->server_admin); /* Apache */ ap_table_addn(e, "SCRIPT_FILENAME", r->filename); /* Apache */ servbuf[0] = '\0'; if (!getnameinfo((struct sockaddr *)&c->remote_addr, #ifndef HAVE_SOCKADDR_LEN SA_LEN((struct sockaddr *)&c->remote_addr), #else c->remote_addr.ss_len, #endif NULL, 0, servbuf, sizeof(servbuf), NI_NUMERICSERV)){ ap_table_addn(e, "REMOTE_PORT", ap_pstrdup(r->pool, servbuf)); } if (c->user) { ap_table_addn(e, "REMOTE_USER", c->user); } if (c->ap_auth_type) { ap_table_addn(e, "AUTH_TYPE", c->ap_auth_type); } rem_logname = ap_get_remote_logname(r); if (rem_logname) { ap_table_addn(e, "REMOTE_IDENT", ap_pstrdup(r->pool, rem_logname)); } /* Apache custom error responses. If we have redirected set two new vars */ if (r->prev) { if (r->prev->args) { ap_table_addn(e, "REDIRECT_QUERY_STRING", r->prev->args); } if (r->prev->uri) { ap_table_addn(e, "REDIRECT_URL", r->prev->uri); } } ap_overlap_tables(r->subprocess_env, e, AP_OVERLAP_TABLES_SET); }
static int websync_handler(request_rec *r) { apr_socket_t *sock = NULL; apr_sockaddr_t *sa = NULL; apr_status_t rv; char errorbuf[120]; char *urip, *hostp; /* some sanitation checks */ if (strcmp(r->handler, "websync")) { return DECLINED; } if (M_GET != r->method_number) { return HTTP_METHOD_NOT_ALLOWED; } /* move the urip past the first portion of the uri, to the start of * the file path to sync * * http://web1/websync/img/test.gif * urip ^ * * http://web1/websync/img/test.gif * urip ^ */ urip = r->uri; if ('/' != *urip) return HTTP_INTERNAL_SERVER_ERROR; do { ++urip; } while ('/' != *urip && '\0' != *urip); /* ensure we have f= args */ if (NULL == r->args) return HTTP_INTERNAL_SERVER_ERROR; /* move hostp to the beginning of the hostname */ /* TODO: clean this up */ hostp = r->args; if ('f' != *hostp && '=' != *(hostp+1)) return HTTP_INTERNAL_SERVER_ERROR; hostp += 2; /* if we detect the X-Requestor: header then don't continue incase of recursive loop */ const char *x_requestor = NULL; x_requestor = apr_table_get(r->headers_in, "X-Requestor"); if (NULL != x_requestor) return HTTP_INTERNAL_SERVER_ERROR; /* some temporary debug info */ r->content_type = "text/html"; ap_rprintf(r, "the uri is %s<br>", r->uri); ap_rprintf(r, "the args %s<br>", r->args); ap_rprintf(r, "the file is %s<br>", urip); ap_rprintf(r, "calling GET : http://%s%s<br>", hostp, urip); ap_rprintf(r, "document root: %s<br>", ap_document_root(r)); /** * now create the return request and download the file * * Note, HTTP 1.1 must send Host: header */ const char *req_hdr = apr_pstrcat(r->pool, "GET ", urip, " ", "HTTP/1.1\r\n", "Host: ", hostp, "\r\n", "X-Requested-With: ", MODULE_VERSION, "\r\n", "\r\n", NULL); apr_size_t len = strlen(req_hdr); rv = apr_sockaddr_info_get(&sa, hostp, APR_INET, DEFAULT_HTTP_PORT, 0, r->pool); if (APR_SUCCESS != rv) return HTTP_INTERNAL_SERVER_ERROR; rv = apr_socket_create(&sock, APR_INET, SOCK_STREAM, APR_PROTO_TCP, r->pool); if (APR_SUCCESS != rv) return rv; rv = apr_socket_connect(sock, sa); if (APR_SUCCESS != rv) return HTTP_INTERNAL_SERVER_ERROR; rv = apr_socket_send(sock, req_hdr, &len); if (APR_SUCCESS != rv) return HTTP_INTERNAL_SERVER_ERROR; apr_file_t *fp; const char *filepath = apr_pstrcat(r->pool, ap_document_root(r), urip, NULL); ap_rprintf(r, "filepath %s<br>", filepath); rv = apr_file_open(&fp, filepath, APR_FOPEN_TRUNCATE | APR_FOPEN_WRITE | APR_FOPEN_CREATE, APR_OS_DEFAULT, r->pool); if (APR_SUCCESS != rv) { /* TODO: attempt to create the parent dir if it's missing */ ap_rprintf(r, "the file result %d : %s<br>", rv, (apr_strerror(rv, errorbuf, sizeof(errorbuf)))); } else { char buf[NET_BUFSIZE]; apr_size_t len = sizeof(buf); while (1) { rv = apr_socket_recv(sock, buf, &len); if (APR_EOF == rv || 0 == len) break; char *bufp = buf; int found = 0; /* skip the http headers ending at \r\n\r\n, TODO: find a more elegant method */ while (!found) { if (*bufp == 13 && *(bufp+1) == 10 && *(bufp+2) == 13 && *(bufp+3) == 10) ++found; ++bufp; } bufp += 3; /* adjust */ apr_file_write(fp, bufp, &len); } apr_file_close(fp); } apr_socket_close(sock); return OK; }
/* This function must remain safe to use for a non-SSL connection. */ char *ssl_var_lookup(apr_pool_t *p, server_rec *s, conn_rec *c, request_rec *r, char *var) { SSLModConfigRec *mc = myModConfig(s); const char *result; BOOL resdup; apr_time_exp_t tm; result = NULL; resdup = TRUE; /* * When no pool is given try to find one */ if (p == NULL) { if (r != NULL) p = r->pool; else if (c != NULL) p = c->pool; else p = mc->pPool; } /* * Request dependent stuff */ if (r != NULL) { switch (var[0]) { case 'H': case 'h': if (strcEQ(var, "HTTP_USER_AGENT")) result = apr_table_get(r->headers_in, "User-Agent"); else if (strcEQ(var, "HTTP_REFERER")) result = apr_table_get(r->headers_in, "Referer"); else if (strcEQ(var, "HTTP_COOKIE")) result = apr_table_get(r->headers_in, "Cookie"); else if (strcEQ(var, "HTTP_FORWARDED")) result = apr_table_get(r->headers_in, "Forwarded"); else if (strcEQ(var, "HTTP_HOST")) result = apr_table_get(r->headers_in, "Host"); else if (strcEQ(var, "HTTP_PROXY_CONNECTION")) result = apr_table_get(r->headers_in, "Proxy-Connection"); else if (strcEQ(var, "HTTP_ACCEPT")) result = apr_table_get(r->headers_in, "Accept"); else if (strlen(var) > 5 && strcEQn(var, "HTTP:", 5)) /* all other headers from which we are still not know about */ result = apr_table_get(r->headers_in, var+5); break; case 'R': case 'r': if (strcEQ(var, "REQUEST_METHOD")) result = r->method; else if (strcEQ(var, "REQUEST_SCHEME")) result = ap_http_scheme(r); else if (strcEQ(var, "REQUEST_URI")) result = r->uri; else if (strcEQ(var, "REQUEST_FILENAME")) result = r->filename; else if (strcEQ(var, "REMOTE_ADDR")) result = r->useragent_ip; else if (strcEQ(var, "REMOTE_HOST")) result = ap_get_useragent_host(r, REMOTE_NAME, NULL); else if (strcEQ(var, "REMOTE_IDENT")) result = ap_get_remote_logname(r); else if (strcEQ(var, "REMOTE_USER")) result = r->user; break; case 'S': case 's': if (strcEQn(var, "SSL", 3)) break; /* shortcut common case */ if (strcEQ(var, "SERVER_ADMIN")) result = r->server->server_admin; else if (strcEQ(var, "SERVER_NAME")) result = ap_get_server_name_for_url(r); else if (strcEQ(var, "SERVER_PORT")) result = apr_psprintf(p, "%u", ap_get_server_port(r)); else if (strcEQ(var, "SERVER_PROTOCOL")) result = r->protocol; else if (strcEQ(var, "SCRIPT_FILENAME")) result = r->filename; break; default: if (strcEQ(var, "PATH_INFO")) result = r->path_info; else if (strcEQ(var, "QUERY_STRING")) result = r->args; else if (strcEQ(var, "IS_SUBREQ")) result = (r->main != NULL ? "true" : "false"); else if (strcEQ(var, "DOCUMENT_ROOT")) result = ap_document_root(r); else if (strcEQ(var, "AUTH_TYPE")) result = r->ap_auth_type; else if (strcEQ(var, "THE_REQUEST")) result = r->the_request; else if (strlen(var) > 4 && strcEQn(var, "ENV:", 4)) { result = apr_table_get(r->notes, var+4); if (result == NULL) result = apr_table_get(r->subprocess_env, var+4); } break; } } /* * Connection stuff */ if (result == NULL && c != NULL) { SSLConnRec *sslconn = ssl_get_effective_config(c); if (strlen(var) > 4 && strcEQn(var, "SSL_", 4) && sslconn && sslconn->ssl) result = ssl_var_lookup_ssl(p, sslconn, r, var+4); else if (strcEQ(var, "HTTPS")) { if (sslconn && sslconn->ssl) result = "on"; else result = "off"; } } /* * Totally independent stuff */ if (result == NULL) { if (strlen(var) > 12 && strcEQn(var, "SSL_VERSION_", 12)) result = ssl_var_lookup_ssl_version(p, var+12); else if (strcEQ(var, "SERVER_SOFTWARE")) result = ap_get_server_banner(); else if (strcEQ(var, "API_VERSION")) { result = apr_itoa(p, MODULE_MAGIC_NUMBER_MAJOR); resdup = FALSE; } else if (strcEQ(var, "TIME_YEAR")) { apr_time_exp_lt(&tm, apr_time_now()); result = apr_psprintf(p, "%02d%02d", (tm.tm_year / 100) + 19, tm.tm_year % 100); resdup = FALSE; } #define MKTIMESTR(format, tmfield) \ apr_time_exp_lt(&tm, apr_time_now()); \ result = apr_psprintf(p, format, tm.tmfield); \ resdup = FALSE; else if (strcEQ(var, "TIME_MON")) { MKTIMESTR("%02d", tm_mon+1) } else if (strcEQ(var, "TIME_DAY")) { MKTIMESTR("%02d", tm_mday) } else if (strcEQ(var, "TIME_HOUR")) { MKTIMESTR("%02d", tm_hour) } else if (strcEQ(var, "TIME_MIN")) { MKTIMESTR("%02d", tm_min) } else if (strcEQ(var, "TIME_SEC")) { MKTIMESTR("%02d", tm_sec) } else if (strcEQ(var, "TIME_WDAY")) { MKTIMESTR("%d", tm_wday) } else if (strcEQ(var, "TIME")) { apr_time_exp_lt(&tm, apr_time_now()); result = apr_psprintf(p, "%02d%02d%02d%02d%02d%02d%02d", (tm.tm_year / 100) + 19, (tm.tm_year % 100), tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); resdup = FALSE; } /* all other env-variables from the parent Apache process */ else if (strlen(var) > 4 && strcEQn(var, "ENV:", 4)) { result = getenv(var+4); } } if (result != NULL && resdup) result = apr_pstrdup(p, result); if (result == NULL) result = ""; return (char *)result; }
static int sqlalias_redir(request_rec *r) { MYSQL *dblink = NULL; server_rec *s = r->server; sqlalias_conf_t *s_cfg = (sqlalias_conf_t *) ap_get_module_config(s->module_config, &sqlalias_module); if (r->uri[0] != '/' && r->uri[0] != '\0') { return DECLINED; } else if(!s_cfg->enable || sqlalias_filter(r, s_cfg->filters) == FILTERED_URI || !(dblink = sqlalias_dbconnect(r->server, s_cfg))) { return DECLINED; } else { MYSQL_RES *result = NULL; MYSQL_ROW row; char *query = NULL; int found = 0; int response = 0; const char *ccp; int uri_length = strlen(r->uri); char *uri = (char *) malloc(sizeof(char) * (uri_length * 2 + 1)); strcpy(uri, r->uri); #ifndef SQLALIAS_PERFECT_MATCH if (uri_length > 1 && uri[uri_length-1] == '/') { uri[uri_length-1] = '\0'; uri_length--; } #endif /* SQLALIAS_PERFECT_MATCH */ mysql_real_escape_string(dblink, uri, uri, uri_length); query = apr_psprintf(r->pool, s_cfg->db_query, uri); free(uri); if(mysql_real_query(dblink, query, strlen(query))) { ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r->server, "sqlalias: %s.", mysql_error(dblink)); #ifdef SQLALIAS_USE_PCONNECT apr_thread_mutex_unlock(sqlalias_mutex); #else DEBUG_MSG(r->server, "sqlalias: Database connection closed. (pid:%d)", getpid()); mysql_close(dblink); #endif /* SQLALIAS_USE_PCONNECT */ return DECLINED; } if (!(result = mysql_store_result(dblink))) { ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r->server, "sqlalias: %s.", mysql_error(dblink)); #ifdef SQLALIAS_USE_PCONNECT apr_thread_mutex_unlock(sqlalias_mutex); #else DEBUG_MSG(r->server, "sqlalias: Database connection closed. (pid:%d)", getpid()); mysql_close(dblink); #endif /* SQLALIAS_USE_PCONNECT */ return DECLINED; } if((row = mysql_fetch_row(result))) { found = 1; response = (mysql_num_fields(result) > 1) ? atoi(row[1]) : DECLINED ; if(ap_is_HTTP_REDIRECT(response) || (is_absolute_uri(row[0]) && (response = HTTP_MOVED_TEMPORARILY))) { char *destination = apr_pstrdup(r->pool, row[0]); DEBUG_MSG(r->server, "sqlalias: %s redirect to %s (R=%d)", r->uri, destination, response?response:HTTP_OK); apr_table_setn(r->headers_out, "Location", destination); } else { DEBUG_MSG(r->server, "sqlalias: rewrite %s -> %s", r->uri, row[0]); /* the filename must be either an absolute local path or an * absolute local URL. */ if (*row[0] != '/' && !ap_os_is_path_absolute(r->pool, row[0])) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "sqlalias: Bad redirection for %s (%s)", r->uri, row[0]); response = HTTP_BAD_REQUEST; } else if ((ccp = ap_document_root(r)) != NULL) { char *q = NULL; r->uri = apr_pstrdup(r->pool, row[0]); q = strchr(r->uri, '?'); if (q != NULL) { char *olduri = NULL; olduri = apr_pstrdup(r->pool, r->uri); *q++ = '\0'; if(r->args) r->args = apr_pstrcat(r->pool, q, "&", r->args, NULL); else r->args = apr_pstrdup(r->pool, q); if(strlen(r->args) == 0) r->args = NULL; } } } #ifdef SQLALIAS_DEBUG } else { DEBUG_MSG(r->server, "sqlalias: No entry for %s", r->uri); #endif /* SQLALIAS_DEBUG */ } mysql_free_result(result); #ifdef SQLALIAS_USE_PCONNECT apr_thread_mutex_unlock(sqlalias_mutex); #else DEBUG_MSG(r->server, "sqlalias: Database connection closed. (pid:%d)", getpid()); mysql_close(dblink); #endif /* SQLALIAS_USE_PCONNECT */ if(found && response != 200) return response; } return DECLINED; }