Esempio n. 1
0
int translateconnected(int uid)
{
    struct translatet *lkm;
    char buf[4096];
    char buf2[5190];
    char *pt;
    pcontext;
    lkm=gettranslate(uid);
    pcontext;
    if(lkm==NULL)
	return 0x0;
    pt=lkm->translatetext;
    while(*pt) /* $%&@ */
    {
	if(*pt==' ') *pt='+';
	pt++;
    }
    /*
     * Altavista changed to Microsoft-Products. This is bad,
     * i have to give more Header-Infos.
     *
     */
    ap_snprintf(buf,sizeof(buf),lngtxt(865),lkm->translatetext,lkm->lang);
    ap_snprintf(buf2,sizeof(buf2),lngtxt(866),strlen(buf),buf);
    writesock_URGENT(lkm->sock,buf2);
    return 0x0;
}
Esempio n. 2
0
int addtranslate(int usern, char *totranslate, char *from, char *dest, int direction, char *lang, char *command)
{
    struct translatet *lkm;
    int lastuid;
    int cnt=0;
    char buf[200];
    pcontext;
    if(translate==NULL)
    {
	translate=(struct translatet *)pmalloc(sizeof(struct translatet));
	lkm=translate;
	lastuid=0;
    } else {
	lkm=translate;
	lastuid=translate->uid;
	while(lkm->next!=NULL)
	{
	    lastuid=lkm->next->uid;
	    lkm=lkm->next;
	    cnt++;
	}
	lkm->next=(struct translatet *)pmalloc(sizeof(struct translatet));
	lkm=lkm->next;
    }
    if(cnt>MAXSYNTRANS) return -1;
    lastuid++;
    lkm->uid=lastuid;
    lkm->delayed=30; /* before it times out, doubled, altavista got slow */
    lkm->translatetext=(char *)pmalloc(strlen(totranslate)+1);
    strcpy(lkm->translatetext,totranslate);
    if(direction==TR_TO)
    {
	ap_snprintf(buf,sizeof(buf),lngtxt(861),command,dest);
    } else {
	if(strchr("&!#+",*dest)!=NULL)
	    ap_snprintf(buf,sizeof(buf),lngtxt(862),from,command,dest);
	else	
	    ap_snprintf(buf,sizeof(buf),lngtxt(863),from,command,user(usern)->nick);
    }
    lkm->translatedtext=(char *)pmalloc(strlen(buf)+1);
    strcpy(lkm->translatedtext,buf);
    lkm->dest=(char *)pmalloc(strlen(dest)+1);
    strcpy(lkm->dest,dest);
    lkm->source=(char *)pmalloc(strlen(from)+1);
    strcpy(lkm->source,from);
    lkm->lang=(char *)pmalloc(strlen(lang)+1);
    strcpy(lkm->lang,lang);
    lkm->direction=direction;
    lkm->usern=usern;
    lkm->sock=createsocket(0,ST_CONNECT,lastuid,SGR_NONE,NULL,translateconnected,translatederror,translatedpart1,translatedone,NULL,AF_INET,SSL_OFF);
    lkm->sock=connectto(lkm->sock,lngtxt(864),80,NULL);
    return 0x0;    
}
Esempio n. 3
0
static const char *log_request_time(request_rec *r, char *a)
{
    int timz;
    struct tm *t;
    char tstr[MAX_STRING_LEN];

    t = ap_get_gmtoff(&timz);

    if (a && *a) {              /* Custom format */
        strftime(tstr, MAX_STRING_LEN, a, t);
    }
    else {                      /* CLF format */
        char sign = (timz < 0 ? '-' : '+');

        if (timz < 0) {
            timz = -timz;
        }
        ap_snprintf(tstr, sizeof(tstr), "[%02d/%s/%d:%02d:%02d:%02d %c%.2d%.2d]",
                t->tm_mday, ap_month_snames[t->tm_mon], t->tm_year+1900, 
                t->tm_hour, t->tm_min, t->tm_sec,
                sign, timz / 60, timz % 60);
    }

    return ap_pstrdup(r->pool, tstr);
}
Esempio n. 4
0
int countconfentries(char *section, char *entry, char *fname)
{
    int cnt=0;
    char buf[256];
    char uitem[256];
    static int itemlist[MAXITEML];
    int i,rc;
    struct stringarray *wconf=conf;
    lastfree=0;
    ap_snprintf(buf,sizeof(buf),"%s.%s.%s=%%255s",fname,section,entry);
    memset(&itemlist[0],0x0,sizeof(itemlist));
    while (wconf)
    {
	rc=sscanf(wconf->entry,buf,&i,uitem);
	if(rc==2) 
	{
	    if(i<MAXITEML) itemlist[i]=1;
	    cnt++; 
	}
	wconf=wconf->next;
    }
    for(i=0;i<MAXITEML;i++)
    {
	if(itemlist[i]==0)
	{
	    lastfree=i;
	    break;
	}
    }
    return cnt;
}
Esempio n. 5
0
static int agent_log_transaction(request_rec *orig)
{
    agent_log_state *cls = ap_get_module_config(orig->server->module_config,
                                             &agent_log_module);

    char str[HUGE_STRING_LEN];
    const char *agent;
    request_rec *r;

    if (cls->agent_fd < 0)
        return OK;

    for (r = orig; r->next; r = r->next)
        continue;
    if (*cls->fname == '\0')    /* Don't log agent */
        return DECLINED;

    agent = ap_table_get(orig->headers_in, "User-Agent");
    if (agent != NULL) {
        ap_snprintf(str, sizeof(str), "%s\n", agent);
        write(cls->agent_fd, str, strlen(str));
    }

    return OK;
}
Esempio n. 6
0
static void ssl_io_data_dump(server_rec *srvr, const char *s, long len)
{
    char buf[256];
    char tmp[64];
    int i, j, rows, trunc;
    unsigned char ch;

    trunc = 0;
    for(; (len > 0) && ((s[len-1] == ' ') || (s[len-1] == '\0')); len--)
        trunc++;
    rows = (len / DUMP_WIDTH);
    if ((rows * DUMP_WIDTH) < len)
        rows++;
    ssl_log(srvr, SSL_LOG_DEBUG|SSL_NO_TIMESTAMP|SSL_NO_LEVELID,
            "+-------------------------------------------------------------------------+");
    for (i = 0 ; i< rows; i++) {
        ap_snprintf(tmp, sizeof(tmp), "| %04x: ", i * DUMP_WIDTH);
        ap_cpystrn(buf, tmp, sizeof(buf));
        for (j = 0; j < DUMP_WIDTH; j++) {
            if (((i * DUMP_WIDTH) + j) >= len)
                ap_cpystrn(buf+strlen(buf), "   ", sizeof(buf)-strlen(buf));
            else {
                ch = ((unsigned char)*((char *)(s) + i * DUMP_WIDTH + j)) & 0xff;
                ap_snprintf(tmp, sizeof(tmp), "%02x%c", ch , j==7 ? '-' : ' ');
                ap_cpystrn(buf+strlen(buf), tmp, sizeof(buf)-strlen(buf));
            }
        }
        ap_cpystrn(buf+strlen(buf), " ", sizeof(buf)-strlen(buf));
        for (j = 0; j < DUMP_WIDTH; j++) {
            if (((i * DUMP_WIDTH) + j) >= len)
                ap_cpystrn(buf+strlen(buf), " ", sizeof(buf)-strlen(buf));
            else {
                ch = ((unsigned char)*((char *)(s) + i * DUMP_WIDTH + j)) & 0xff;
                ap_snprintf(tmp, sizeof(tmp), "%c", ((ch >= ' ') && (ch <= '~')) ? ch : '.');
                ap_cpystrn(buf+strlen(buf), tmp, sizeof(buf)-strlen(buf));
            }
        }
        ap_cpystrn(buf+strlen(buf), " |", sizeof(buf)-strlen(buf));
        ssl_log(srvr, SSL_LOG_DEBUG|SSL_NO_TIMESTAMP|SSL_NO_LEVELID, "%s", buf);
    }
    if (trunc > 0)
        ssl_log(srvr, SSL_LOG_DEBUG|SSL_NO_TIMESTAMP|SSL_NO_LEVELID,
                "| %04lx - <SPACES/NULS>", len + trunc);
    ssl_log(srvr, SSL_LOG_DEBUG|SSL_NO_TIMESTAMP|SSL_NO_LEVELID,
            "+-------------------------------------------------------------------------+");
    return;
}
Esempio n. 7
0
static void dump_iphash_statistics(server_rec *main_s)
{
    unsigned count[IPHASH_TABLE_SIZE];
    int i;
    ipaddr_chain *src;
    unsigned total;
    char buf[HUGE_STRING_LEN];
    char *p;

    total = 0;
    for (i = 0; i < IPHASH_TABLE_SIZE; ++i) {
	count[i] = 0;
	for (src = iphash_table[i]; src; src = src->next) {
	    ++count[i];
	    if (i < IPHASH_TABLE_SIZE) {
		/* don't count the slop buckets in the total */
		++total;
	    }
	}
    }
    qsort(count, IPHASH_TABLE_SIZE, sizeof(count[0]), iphash_compare);
    p = buf + ap_snprintf(buf, sizeof(buf),
		    "iphash: total hashed = %u, avg chain = %u, "
		    "chain lengths (count x len):",
		    total, total / IPHASH_TABLE_SIZE);
    total = 1;
    for (i = 1; i < IPHASH_TABLE_SIZE; ++i) {
	if (count[i - 1] != count[i]) {
	    p += ap_snprintf(p, sizeof(buf) - (p - buf), " %ux%u",
			     total, count[i - 1]);
	    total = 1;
	}
	else {
	    ++total;
	}
    }
    p += ap_snprintf(p, sizeof(buf) - (p - buf), " %ux%u",
		     total, count[IPHASH_TABLE_SIZE - 1]);
    ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, main_s, buf);
}
Esempio n. 8
0
/* delete user files */
int deluser(int uind)
{
    char buf[60];
    pcontext;
#ifdef TRAFFICLOG
    /* close the trafficlog before deleting */
    if(user(uind)->trafficlog!=NULL)
    {
	fclose(user(uind)->trafficlog);
	user(uind)->trafficlog=NULL;
    }
#endif
    ap_snprintf(buf,sizeof(buf),lngtxt(380),uind);
    oldfile(buf);
    ap_snprintf(buf,sizeof(buf),lngtxt(381),uind);
    oldfile(buf);
    pcontext;
    ap_snprintf(buf,sizeof(buf),lngtxt(382),uind);
    clearsectionconfig(buf);
    flushconfig();
    pcontext;
    return 0x0;
}
Esempio n. 9
0
/*
 * Canonicalise http-like URLs.
 *  scheme is the scheme for the URL
 *  url    is the URL starting with the first '/'
 *  def_port is the default port for this scheme.
 */
int ap_proxy_http_canon(request_rec *r, char *url, const char *scheme, int def_port)
{
    char *host, *path, *search, sport[7];
    const char *err;
    int port;

    /*
     * do syntatic check. We break the URL into host, port, path, search
     */
    port = def_port;
    err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
    if (err)
        return HTTP_BAD_REQUEST;

    /* now parse path/search args, according to rfc1738 */
    /*
     * N.B. if this isn't a true proxy request, then the URL _path_ has
     * already been decoded.  True proxy requests have r->uri ==
     * r->unparsed_uri, and no others have that property.
     */
    if (r->uri == r->unparsed_uri) {
        search = strchr(url, '?');
        if (search != NULL)
            *(search++) = '\0';
    }
    else
        search = r->args;

    /* process path */
    path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path,
                             r->proxyreq);
    if (path == NULL)
        return HTTP_BAD_REQUEST;

    if (port != def_port)
        ap_snprintf(sport, sizeof(sport), ":%d", port);
    else
        sport[0] = '\0';

    r->filename = ap_pstrcat(r->pool, "proxy:", scheme, "://", host, sport, "/",
                   path, (search) ? "?" : "", (search) ? search : "", NULL);
    return OK;
}
Esempio n. 10
0
/* Set the service description regardless of platform.
 * We revert to set_service_description_string on NT/9x, the
 * very long way so any Apache management program can grab the
 * description.  This would be bad on Win2000, since it wouldn't
 * notify the service control manager of the name change.
 */
static void set_service_description_string(const char *description)
{
    char szPath[MAX_PATH];
    HKEY hkey;

    /* Create/Find the Service key that Monitor Applications iterate */
    ap_snprintf(szPath, sizeof(szPath), 
                "SYSTEM\\CurrentControlSet\\Services\\%s", globdat.name);
    ap_remove_spaces(szPath, szPath);
    if (RegCreateKey(HKEY_LOCAL_MACHINE, szPath, &hkey) != ERROR_SUCCESS) {
        return;
    }

    /* Attempt to set the Description value for our service */
    RegSetValueEx(hkey, "Description", 0, REG_SZ,  
                  (unsigned char *) description, 
                  strlen(description) + 1);
    RegCloseKey(hkey);
}
Esempio n. 11
0
int getini(char *section, char *param,char *inidat)
{
   char ppuf[400];
   struct stringarray *wconf;
   char *po;
   wconf=conf;
   memset(value,0x0,sizeof(value));    
   ap_snprintf(ppuf,sizeof(ppuf),"%s.%s.%s=",inidat,section,param);
   while (wconf!=NULL) 
   {
	if(wconf->entry!=NULL)
	{
	    po = strstr(wconf->entry,ppuf);
	    if (po == wconf->entry) {
 		po = po + strlen(ppuf);
		strmncpy(value,po,sizeof(value));
		return 0x0; /* found, returning */
	    }
	}
	wconf=wconf->next;
   }
   /* not found */
   return -2;
}
Esempio n. 12
0
int getserver(int srvnr, int usernum)
{
   char fnmuser[20];
   char buf[100];
   int ern;
   ap_snprintf(fnmuser,sizeof(fnmuser),lngtxt(373),usernum);
   ap_snprintf(buf,sizeof(buf),lngtxt(374),srvnr);
   ern = getini(lngtxt(375),buf,fnmuser);
   if (ern != 0) { return ern; }
   ap_snprintf(user(usernum)->server,sizeof(user(usernum)->server),"%s",value);
   ap_snprintf(buf,sizeof(buf),lngtxt(376),srvnr);
   ern = getini(lngtxt(377),buf,fnmuser);
   if (ern != 0) { user(usernum)->port = 6667; } else { user(usernum)->port = atoi(value); }
   ap_snprintf(buf,sizeof(buf),lngtxt(378),srvnr);
   ern = getini(lngtxt(379),buf,fnmuser);
   if (ern != 0) { *user(usernum)->spass=0; return 0; }
   ap_snprintf(user(usernum)->spass,sizeof(user(usernum)->spass),"%s",value);
   return 0;
}
Esempio n. 13
0
static void exception_hook(ap_exception_info_t *ei)
{
    int msg_len;
    int logfd;
    char msg_prefix[60];
    time_t now;
    char *newline;
    int using_errorlog = 1;

    time(&now);
    ap_snprintf(msg_prefix, sizeof msg_prefix,
                "[%s pid %ld mod_whatkilledus",
                asctime(localtime(&now)),
                (long)getpid());
    newline = strchr(msg_prefix, '\n'); /* dang asctime() */
    if (newline) {                      /* silly we are */
        *newline = ']';
    }

    if (log_fname) {
        logfd = open(log_fname, O_WRONLY|O_APPEND|O_CREAT, 0644);
        if (logfd == -1) {
            logfd = 2; /* unix, so fd 2 is the web server error log */
            ap_snprintf(buffer, sizeof buffer,
                        "%s error %d opening %s\n",
                        msg_prefix, errno, log_fname);
            write(logfd, buffer, strlen(buffer));
        }
        else {
            using_errorlog = 0;
        }
    }
    else {
        logfd = 2;
    }

    msg_len = ap_snprintf(buffer, sizeof buffer,
                          "%s sig %d crash\n",
                          msg_prefix, ei->sig);
    write(logfd, buffer, msg_len);

    if (local_addr) {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s active connection: %s->%s\n",
                              msg_prefix, remote_addr, local_addr);
    }
    else {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s no active connection at crash\n",
                              msg_prefix);
    }

    write(logfd, buffer, msg_len);

    if (request_plus_headers) {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s active request:\n",
                              msg_prefix);
        write(logfd, buffer, msg_len);
        write(logfd, request_plus_headers, strlen(request_plus_headers));
    }
    else {
        msg_len = ap_snprintf(buffer, sizeof buffer,
                              "%s no request active at crash\n",
                              msg_prefix);
        write(logfd, buffer, msg_len);
    }
    msg_len = ap_snprintf(buffer, sizeof buffer,
                          "%s end of report\n",
                          msg_prefix);
    write(logfd, buffer, msg_len);
    if (!using_errorlog) {
        close(logfd);
    }
}
Esempio n. 14
0
int writeini(char *section, char *param, char *inidat, char *data)
{
    char ppuf[200];
    char spuf[200];
    char buf[2048];
    char *po;
    int wasinsection;
    char *data_p;
    struct stringarray *wconf,*xconf,*sectconf;
    wconf=conf;
    data_p = data;
    if (data_p != NULL)
       if (strlen(data) == 0) data_p = NULL;
    wasinsection = 0;
    ap_snprintf(ppuf,sizeof(ppuf),lngtxt(371),inidat,section,param);
    ap_snprintf(spuf,sizeof(spuf),lngtxt(372),inidat,section);
    if(data_p!=NULL)
	ap_snprintf(buf,sizeof(buf),"%s%s",ppuf,data_p);
    xconf=conf;
    sectconf=conf;
    while (wconf) 
    {
      if(wconf->entry!=NULL)
      {
    	   po = strstr(wconf->entry,spuf);
           if (po == wconf->entry) 
	   {
	      sectconf=xconf; /* save last entry of section */
	      wasinsection = 1; /* we had been in the section */
	      po = strstr(wconf->entry,ppuf);
	      if (po == wconf->entry) {
		 if(data_p==NULL)
		 {
		    if(wconf==conf)
		    {
			conf=wconf->next;
			xconf=conf;
		    } else {
			xconf->next=wconf->next;
		    }		     
		    free(wconf->entry);
		    free(wconf);
		    wconf=xconf;
		    return 0x0;
		 } else {
		    free(wconf->entry);
		    wconf->entry=(char *)pmalloc(strlen(buf)+2);
		    strmncpy(wconf->entry,buf,strlen(buf)+1);
		    return 0x0;
		 }    
	      }
	   }
      }
      xconf=wconf;
      wconf=wconf->next;
    }
    if(data_p==NULL) return 0x0;
    if(wasinsection==0) 
    {
	xconf->next=(struct stringarray *)pmalloc(sizeof(struct stringarray));
	xconf=xconf->next;
    } else {
	xconf=sectconf;
	wconf=(struct stringarray *)pmalloc(sizeof(struct stringarray));
	wconf->next=xconf->next;
	xconf->next=wconf;
	xconf=wconf;
    }
    xconf->entry=(char *)pmalloc(strlen(buf)+2);
    strmncpy(xconf->entry,buf,strlen(buf)+1);
    return 0x0;
}
Esempio n. 15
0
void InstallService(pool *p, char *display_name, int argc, char **argv, int reconfig)
{
    TCHAR szPath[MAX_PATH];
    TCHAR szQuotedPath[512];
    char *service_name;
    int regargc = 0;
    char default_depends[] = "Tcpip\0Afd\0";
    char *depends = default_depends;
    size_t depends_len = sizeof(default_depends);
    char **regargv = malloc((argc + 4) * sizeof(char*));
    char **newelem = regargv;

    regargc += 4;
    *(newelem++) = "-d";
    *(newelem++) = ap_server_root;
    *(newelem++) = "-f";
    *(newelem++) = ap_server_confname;

    while (++argv, --argc) {
        if ((**argv == '-') && strchr("kndf", argv[0][1]))
            --argc, ++argv; /* Skip already handled -k -n -d -f options */
        else if ((**argv == '-') && (argv[0][1] == 'W')) 
        {
            /* Catch this service -W dependency 
             * the depends list is null seperated, double-null terminated
             */
            char *service = get_service_name(*(argv + 1));
            size_t add_len = strlen(service) + 1;
            char *more_depends = malloc(depends_len + add_len);
            memcpy (more_depends, depends, depends_len - 1);
            memcpy (more_depends + depends_len - 1, service, add_len);
            depends_len += add_len;
            depends = more_depends;
            depends[depends_len - 1] = '\0';
            ++argv, --argc;
        }
        else if ((**argv != '-') || !strchr("iuw", argv[0][1]))
            *(newelem++) = *argv, ++regargc;  /* Ignoring -i -u -w options */
    }

    /* Remove spaces from display name to create service name */
    service_name = get_service_name(display_name);
    
    printf(reconfig ? "Reconfiguring the %s service\n"
                    : "Installing the %s service\n", 
           display_name);

    if (GetModuleFileName( NULL, szPath, 512 ) == 0)
    {
        ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
        "GetModuleFileName failed");
        return;
    }

    if (isWindowsNT())
    {
        SC_HANDLE schService;
        SC_HANDLE schSCManager;

        ap_snprintf(szQuotedPath, sizeof(szQuotedPath), "\"%s\" --ntservice", szPath);

        schSCManager = OpenSCManager(
                            NULL,                 // machine (local)
                            NULL,                 // database (default)
                            SC_MANAGER_ALL_ACCESS // access required
                            );
        if (!schSCManager) {
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "OpenSCManager failed");
            return;
        }
        
        /* Added dependencies for the following: TCPIP, AFD
         * AFD is the winsock handler, TCPIP is self evident
         *
         * RPCSS is the Remote Procedure Call (RPC) Locator
         * required for DCOM communication.  I am far from
         * convinced we should toggle this, but be warned that
         * future apache modules or ISAPI dll's may depend on it.
         * Also UNC share users may need the networking service 
         * started (usually "LanmanWorkstation").  "ProtectedStorage" 
         * may be needed depending on how files and registry keys are 
         * stored.  And W3SVC may be needed to wait until IIS has
         * glommed and released 0.0.0.0:80 if the admin allocates 
         * two different IP's to Apache and IIS on the same port.
         */
        if (reconfig) 
        {
            schService = OpenService(schSCManager, service_name, 
                                     SERVICE_ALL_ACCESS);
            if (!schService)
                ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL, 
                             "OpenService failed");
            else if (!ChangeServiceConfig(
                        schService,                 // Service handle
                        SERVICE_WIN32_OWN_PROCESS,  // service type
                        SERVICE_AUTO_START,         // start type
                        SERVICE_ERROR_NORMAL,       // error control type
                        szQuotedPath,               // service's binary
                        NULL,                       // no load ordering group
                        NULL,                       // no tag identifier
                        depends,                    // dependencies
                        NULL,                       // user account
                        NULL,                       // account password
                        display_name)) {            // service display name
                ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL, 
		             "ChangeServiceConfig failed");
                /* !schService aborts configuration below */
                CloseServiceHandle(schService);
                schService = NULL;
            }
        }
        else /* !reconfig */
        {
            schService = CreateService(
                        schSCManager,               // SCManager database
                        service_name,               // name of service
                        display_name,               // name to display
                        SERVICE_ALL_ACCESS,         // desired access
                        SERVICE_WIN32_OWN_PROCESS,  // service type
                        SERVICE_AUTO_START,         // start type
                        SERVICE_ERROR_NORMAL,       // error control type
                        szQuotedPath,               // service's binary
                        NULL,                       // no load ordering group
                        NULL,                       // no tag identifier
                        depends,                    // dependencies
                        NULL,                       // user account
                        NULL);                      // account password
            if (!schService)
                ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL, 
                             "CreateService failed");
        }
        if (schService)
            CloseServiceHandle(schService);
        
        CloseServiceHandle(schSCManager);
        
        if (!schService)
            return;
    }
    else /* !isWindowsNT() */
    {
        HKEY hkey;
        DWORD rv;

        ap_snprintf(szQuotedPath, sizeof(szQuotedPath),
                    "\"%s\" -k start -n %s", 
                    szPath, service_name);
        /* Create/Find the RunServices key */
        rv = RegCreateKey(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows"
                          "\\CurrentVersion\\RunServices", &hkey);
        if (rv != ERROR_SUCCESS) {
            SetLastError(rv);
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "Could not create/open the RunServices registry key");
            return;
        }

        /* Attempt to add the value for our service */
        rv = RegSetValueEx(hkey, service_name, 0, REG_SZ, 
                           (unsigned char *)szQuotedPath, 
                           strlen(szQuotedPath) + 1);
        if (rv != ERROR_SUCCESS) {
            SetLastError(rv);
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "Unable to install service: "
                         "Could not add to RunServices Registry Key");
            RegCloseKey(hkey);
            return;
        }

        RegCloseKey(hkey);

        /* Create/Find the Service key for Monitor Applications to iterate */
        ap_snprintf(szPath, sizeof(szPath), 
                    "SYSTEM\\CurrentControlSet\\Services\\%s", service_name);
        rv = RegCreateKey(HKEY_LOCAL_MACHINE, szPath, &hkey);
        if (rv != ERROR_SUCCESS) {
            SetLastError(rv);
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "Could not create/open the %s registry key", szPath);
            return;
        }

        /* Attempt to add the ImagePath value to identify it as Apache */
        rv = RegSetValueEx(hkey, "ImagePath", 0, REG_SZ, 
                           (unsigned char *)szQuotedPath, 
                           strlen(szQuotedPath) + 1);
        if (rv != ERROR_SUCCESS) {
            SetLastError(rv);
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "Unable to install service: "
                         "Could not add ImagePath to %s Registry Key", 
                         service_name);
            RegCloseKey(hkey);
            return;
        }

        /* Attempt to add the DisplayName value for our service */
        rv = RegSetValueEx(hkey, "DisplayName", 0, REG_SZ, 
                           (unsigned char *)display_name, 
                           strlen(display_name) + 1);
        if (rv != ERROR_SUCCESS) {
            SetLastError(rv);
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "Unable to install service: "
                         "Could not add DisplayName to %s Registry Key", 
                         service_name);
            RegCloseKey(hkey);
            return;
        }

        RegCloseKey(hkey);
    }

    /* Both Platforms: Now store the args in the registry */
    if (ap_registry_set_service_args(p, regargc, regargv, service_name)) {
        return;
    }

    printf("The %s service has been %s successfully.\n", 
           display_name, reconfig ? "reconfigured" : "installed");
}
Esempio n. 16
0
int
main (int argc, char **argv)
{
  int rc;
  char *pt;
  char *bversion;
  FILE *pidfile,*conffile;
  if(argc==2)
  {
      strmncpy(configfile,argv[1],sizeof(configfile));
  } else {
      strcpy(configfile,"psybnc.conf");  /* rcsid */
  }
  conffile=fopen(configfile,"r");
  if(conffile==NULL)
  {
     printf("Configuration File %s not found, aborting\nRun 'make menuconfig' for creating a configuration or create the file manually.\n",configfile); /* rcsid */
     exit (0x0);
  }
  fclose(conffile);
  readconfig();
  rc = getini("SYSTEM","LANGUAGE",INIFILE);  /* rcsid */
  if(rc!=0)
  {
      rc=loadlanguage("english");  /* rcsid */
  } else {
      rc=loadlanguage(value);  
      if(rc<0)
          rc=loadlanguage("english");  /* rcsid */
  }
  if(rc<0)
  {
      printf("Could not load language file, aborting.\n");  /* rcsid */
      exit(0x0);	  
  }
  printbanner();
  printf(lngtxt(991),configfile);
  printf(lngtxt(992),langname);
  ap_snprintf(logfile,sizeof(logfile),lngtxt(993));
  rc = getini(lngtxt(994),lngtxt(995),INIFILE);
  if (rc != 0) {
     printf("%s", lngtxt(996));
     exit (0x0);
  }
  listenport = atoi(value);
  rc = getini(lngtxt(997),"ME",INIFILE);
  if (rc < 0) {
     memset(value,0x0,sizeof(value));       
  }
  pt=strchr(value,' '); /* shortening bouncername to no spaces */
  if(pt)
      *pt=0;
  ap_snprintf(me,sizeof(me),"%s",value);
  rc = getini(lngtxt(998),lngtxt(999),INIFILE);
  if (rc < 0) {
     printf("%s", lngtxt(1000));
     ap_snprintf(value,sizeof(value),lngtxt(1001));
  }
  ap_snprintf(logfile,sizeof(logfile),"%s",value);
  oldfile(logfile);
  /* creating the socket-root */
  socketnode=(struct socketnodes *) pmalloc(sizeof(struct usernodes));
  socketnode->sock=NULL;
  socketnode->next=NULL;

  #ifdef IPV6
  /* set the default ipv6 preference for users without a PREFERIPV6 setting */
  rc = getini("SYSTEM", "DEFAULTIPV6", INIFILE);
  if (rc == 0)
  {
     defaultipv6 = atoi(value);
  }
  #endif

  /* creating the demon socket */
  rc = createlisteners();
  if (rc == 0) {
    printf("%s", lngtxt(1002));
    exit (0x0);
  }
  /* creating background */
  pidfile = fopen(lngtxt(1003),"w");
  if(pidfile==NULL)
  {
      printf("%s", lngtxt(1004));
      exit(0x0);
  }
  if(mainlog!=NULL)
  {
      fclose(mainlog);
      mainlog=NULL;
  }
  fflush(stdout);
  

  pid = fork();
  //pid = 0;
  if (pid < 0) {
  
  }
  if (pid == 0) {
     rc= errorhandling();
     makesalt();

#ifdef HAVE_SSL
     initSSL();
     pcontext;
#endif
     U_CREATE=0;
#ifdef PARTYCHANNEL
     /* partychannel setup */
     strmncpy(partytopic,lngtxt(1005),sizeof(partytopic));
     partyusers=NULL;
#endif
     /* creating the usernode-root */
     usernode=(struct usernodes *) pmalloc(sizeof(struct usernodes));
     usernode->uid=0;
     usernode->user=NULL;
     usernode->next=NULL;
     /* creating the newpeer-root */
     peernode=(struct peernodes *) pmalloc(sizeof(struct peernodes));
     peernode->uid=0;
     peernode->peer=NULL;
     peernode->next=NULL;
     /* creating the datalink-root */
     linknode=(struct linknodes *) pmalloc(sizeof(struct linknodes));
     linknode->uid=0;
     linknode->link=NULL;
     linknode->next=NULL;
     /* loading the users */
     loadusers();
     loadlinks();
     pcontext;
     /* loading the hostallows */
     hostallows=loadlist(lngtxt(1006),hostallows);
  }
  pcontext;
  if (pid) {
     bversion=buildversion();
     printf(lngtxt(1007),bversion,pid);
     p_log(LOG_INFO,-1,lngtxt(1008),bversion,pid);
     fprintf( pidfile,"%d\n",pid);
     fclose(pidfile);
     exit (0x0);
  }  
  pcontext;
//#ifndef BLOCKDNS
//  if(init_dns_core()==0)
//  {
//     dns_err(0,1);
//  }
//#endif

  p_dns_init();
  bncmain();
  return 0x0;
}
Esempio n. 17
0
int send_signal_to_service(char *display_name, char *sig, 
                           int argc, char **argv)
{
    DWORD       service_pid;
    HANDLE      hwnd;
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;
    char       *service_name;
    int success = FALSE;

    enum                        { start,      restart,      stop, unknown } action;
    static char *param[] =      { "start",    "restart",    "shutdown" };
    static char *participle[] = { "starting", "restarting", "stopping" };
    static char *past[]       = { "started",  "restarted",  "stopped"  };

    for (action = start; action < unknown; action++)
        if (!strcasecmp(sig, param[action]))
            break;

    if (action == unknown) {
        printf("signal must be start, restart, or shutdown\n");
        return FALSE;
    }

    service_name = get_service_name(display_name);

    if (isWindowsNT()) 
    {
        schSCManager = OpenSCManager(
                            NULL,                   // machine (NULL == local)
                            NULL,                   // database (NULL == default)
                            SC_MANAGER_ALL_ACCESS   // access required
                            );
        if (!schSCManager) {
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "OpenSCManager failed");
            return FALSE;
        }
        
        schService = OpenService(schSCManager, service_name, SERVICE_ALL_ACCESS);

        if (schService == NULL) {
            /* Could not open the service */
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "OpenService failed");
            CloseServiceHandle(schSCManager);
            return FALSE;
        }
        
        if (!QueryServiceStatus(schService, &globdat.ssStatus)) {
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "QueryService failed");
            CloseServiceHandle(schService);
            CloseServiceHandle(schSCManager);
        }
    }
    else /* !isWindowsNT() */
    {
        /* Locate the window named service_name of class ApacheWin95ServiceMonitor
         * from the active top level windows
         */
        hwnd = FindWindow("ApacheWin95ServiceMonitor", service_name);
        if (hwnd && GetWindowThreadProcessId(hwnd, &service_pid))
            globdat.ssStatus.dwCurrentState = SERVICE_RUNNING;
        else
            globdat.ssStatus.dwCurrentState = SERVICE_STOPPED;
    }

    if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED 
            && action == stop) {
        printf("The %s service is not started.\n", display_name);
        return FALSE;
    }
    else if (globdat.ssStatus.dwCurrentState == SERVICE_RUNNING 
                 && action == start) {
        printf("The %s service has already been started.\n", display_name);
        strcpy(sig, "");
        return FALSE;
    }
    else
    {
        printf("The %s service is %s.\n", display_name, participle[action]);

        if (isWindowsNT()) 
        {
            if (action == stop)
                success = ap_stop_service(schService);
            else if ((action == start) 
                     || ((action == restart) 
                            && (globdat.ssStatus.dwCurrentState 
                                    == SERVICE_STOPPED)))
            {
                /* start NT service needs service args */
                char **args = malloc(argc * sizeof(char*));
                int i, j;
                for (i = 1, j = 0; i < argc; i++) {
                    if ((argv[i][0] == '-') && ((argv[i][1] == 'k') 
                                             || (argv[i][1] == 'n')))
                        ++i;
                    else
                        args[j++] = argv[i];
                }
                success = ap_start_service(schService, j, args);
            }
            else if (action == restart)
                success = ap_restart_service(schService);
        }
        else /* !isWindowsNT()) */
        {
            char prefix[20];
            ap_snprintf(prefix, sizeof(prefix), "ap%ld", (long)service_pid);
            setup_signal_names(prefix);

            if (action == stop) {
                int ticks = 60;
                ap_start_shutdown();
                while (--ticks)
                {
                    if (!IsWindow(hwnd)) {
                        success = TRUE;
                        break;
                    }
                    Sleep(1000);
                }
            }
            else if (action == restart) 
            {   
                /* This gets a bit tricky... start and restart (of stopped service)
                 * will simply fall through and *THIS* process will fade into an
                 * invisible 'service' process, detaching from the user's console.
                 * We need to change the restart signal to "start", however,
                 * if the service was not -yet- running, and we do return FALSE
                 * to assure main() that we haven't done anything yet.
                 */
                if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) 
                {
                    printf("The %s service has %s.\n", display_name, 
                           past[action]);
                    strcpy(sig, "start");
                    return FALSE;
                }
                
                ap_start_restart(1);
                success = TRUE;
            }
            else /* action == start */
            {
                printf("The %s service is %s.\n", display_name, 
                       past[action]);
                return FALSE;
            }
        }

        if( success )
            printf("The %s service has %s.\n", display_name, past[action]);
        else
            printf("Failed to %s the %s service.\n", sig, display_name);
    }

    if (isWindowsNT()) {
        CloseServiceHandle(schService);
        CloseServiceHandle(schSCManager);
    }
    return success;
}
Esempio n. 18
0
/*
 * This handles http:// URLs, and other URLs using a remote proxy over http
 * If proxyhost is NULL, then contact the server directly, otherwise
 * go via the proxy.
 * Note that if a proxy is used, then URLs other than http: can be accessed,
 * also, if we have trouble which is clearly specific to the proxy, then
 * we return DECLINED so that we can try another proxy. (Or the direct
 * route.)
 */
int ap_proxy_http_handler(request_rec *r, cache_req *c, char *url,
                              const char *proxyhost, int proxyport)
{
    const char *strp;
    char *strp2;
    const char *err, *desthost;
    int i, j, sock,/* len,*/ backasswards;
    table *req_hdrs, *resp_hdrs;
    array_header *reqhdrs_arr;
    table_entry *reqhdrs_elts;
    BUFF *f;
    char buffer[HUGE_STRING_LEN];
    char portstr[32];
    pool *p = r->pool;
    int chunked = 0, destport = 0;
    char *destportstr = NULL;
    const char *urlptr = NULL;
    const char *datestr, *urlstr;
    struct addrinfo hints, *res, *res0;
    int error;
    int result, major, minor;
    const char *content_length;
    const char *peer;
    int destportstrtonum;
    const char *errstr;

    void *sconf = r->server->module_config;
    proxy_server_conf *conf =
    (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
    struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
    struct nocache_entry *ncent = (struct nocache_entry *) conf->nocaches->elts;
    int nocache = 0;

    if (conf->cache.root == NULL)
        nocache = 1;

    /* We break the URL into host, port, path-search */

    urlptr = strstr(url, "://");
    if (urlptr == NULL)
        return HTTP_BAD_REQUEST;
    destport = DEFAULT_HTTP_PORT;
    urlptr += 3;
    ap_hook_use("ap::mod_proxy::http::handler::set_destport", 
                AP_HOOK_SIG2(int,ptr), 
                AP_HOOK_TOPMOST,
                &destport, r);
    ap_snprintf(portstr, sizeof(portstr), "%d", destport);
    destportstr = portstr;
    strp = strchr(urlptr, '/');
    if (strp == NULL) {
        desthost = ap_pstrdup(p, urlptr);
        urlptr = "/";
    }
    else {
        char *q = ap_palloc(p, strp - urlptr + 1);
        memcpy(q, urlptr, strp - urlptr);
        q[strp - urlptr] = '\0';
        urlptr = strp;
        desthost = q;
    }
    if (*desthost == '['){
      char *u = strrchr(desthost+1, ']');
      if (u){
          desthost++;
          *u = '\0';
          if (*(u+1) == ':'){ /* [host]:xx */
              strp2 = u+1;
          }
          else if (*(u+1) == '\0'){   /* [host] */
              strp2 = NULL;
          }
          else
              return HTTP_BAD_REQUEST;
      }
      else
          return HTTP_BAD_REQUEST;
    }
    else
       strp2 = strrchr(desthost, ':');

    if (strp2 != NULL) {
        *(strp2++) = '\0';
        if (ap_isdigit(*strp2))
            destportstr = strp2;
    }

    /* Make sure peer is always set to prevent a segfault in the SSL handler */
    peer = desthost;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    error = getaddrinfo(desthost, destportstr, &hints, &res0);
    if (error && proxyhost == NULL) {
      return ap_proxyerror(r, HTTP_INTERNAL_SERVER_ERROR,
                  gai_strerror(error));       /* give up */
     }
 
      /* check if ProxyBlock directive on this host */
      for (i = 0; i < conf->noproxies->nelts; i++) {
      int fail;
      struct sockaddr_in *sin;

      fail = 0;
      if (npent[i].name != NULL && strstr(desthost, npent[i].name))
          fail++;
      if (npent[i].name != NULL && strcmp(npent[i].name, "*") == 0)
          fail++;
      for (res = res0; res; res = res->ai_next) {
          switch (res->ai_family) {
          case AF_INET:
              sin = (struct sockaddr_in *)res->ai_addr;
              if (sin->sin_addr.s_addr == npent[i].addr.s_addr)
                  fail++;
              break;
		
          }
      }
      if (fail) {
          if (res0 != NULL)
              freeaddrinfo(res0);
          return ap_proxyerror(r, HTTP_FORBIDDEN,
                               "Connect to remote machine blocked");
      }
    }
    if (proxyhost != NULL) {
      char pbuf[10];

      if (res0 != NULL)
          freeaddrinfo(res0);

      ap_snprintf(pbuf, sizeof(pbuf), "%d", proxyport);
      memset(&hints, 0, sizeof(hints));
      hints.ai_family = PF_UNSPEC;
      hints.ai_socktype = SOCK_STREAM;
      hints.ai_protocol = IPPROTO_TCP;
      error = getaddrinfo(proxyhost, pbuf, &hints, &res0);
      if (error)
          return DECLINED;    /* try another */
    }

    /* check if ProxyBlock directive on this host */
    for (i = 0; i < conf->noproxies->nelts; i++) {
	peer =  ap_psprintf(p, "%s:%s", desthost, destportstr);  
    }


    /*
     * we have worked out who exactly we are going to connect to, now make
     * that connection...
     */
     sock = i = -1;
     for (res = res0; res; res = res->ai_next) {
       sock = ap_psocket(p, res->ai_family, res->ai_socktype,
           res->ai_protocol);
       if (sock < 0)
           continue;

      if (conf->recv_buffer_size) {
          if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
                         (const char *)&conf->recv_buffer_size, sizeof(int))
              == -1) {
              ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                            "setsockopt(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
          }
      }

      i = ap_proxy_doconnect(sock, res->ai_addr, r);
      if (i == 0)
          break;
      ap_pclosesocket(p, sock);
    }
    freeaddrinfo(res0);

    if (i == -1) {
        if (proxyhost != NULL)
            return DECLINED;    /* try again another way */
        else
            return ap_proxyerror(r, HTTP_BAD_GATEWAY, ap_pstrcat(r->pool,
                                    "Could not connect to remote machine: ",
                                                    strerror(errno), NULL));
    }

    /* record request_time for HTTP/1.1 age calculation */
    c->req_time = time(NULL);

    /*
     * build upstream-request headers by stripping r->headers_in from
     * connection specific headers. We must not remove the Connection: header
     * from r->headers_in, we still have to react to Connection: close
     */
    req_hdrs = ap_copy_table(r->pool, r->headers_in);
    ap_proxy_clear_connection(r->pool, req_hdrs);

    /*
     * At this point, we start sending the HTTP/1.1 request to the remote
     * server (proxy or otherwise).
     */
    f = ap_bcreate(p, B_RDWR | B_SOCKET);
    ap_bpushfd(f, sock, sock);

    {
        char *errmsg = NULL;
        ap_hook_use("ap::mod_proxy::http::handler::new_connection", 
                    AP_HOOK_SIG4(ptr,ptr,ptr,ptr), 
                    AP_HOOK_DECLINE(NULL),
                    &errmsg, r, f, peer);
        if (errmsg != NULL)
            return ap_proxyerror(r, HTTP_BAD_GATEWAY, errmsg);
    }

    ap_hard_timeout("proxy send", r);
    ap_bvputs(f, r->method, " ", proxyhost ? url : urlptr, " HTTP/1.1" CRLF,
              NULL);
    {
	int rc = DECLINED;
	ap_hook_use("ap::mod_proxy::http::handler::write_host_header", 
		    AP_HOOK_SIG6(int,ptr,ptr,ptr,ptr,ptr), 
		    AP_HOOK_DECLINE(DECLINED),
		    &rc, r, f, desthost, destportstr, destportstr);
        if (rc == DECLINED) {
	    destportstrtonum = strtonum(destportstr, 0, 65535, &errstr);
	    if (errstr)
		errx(1, "The destination port is %s: %s", errstr, destportstr);

	    if (destportstr != NULL && destportstrtonum != destport)
		ap_bvputs(f, "Host: ", desthost, ":", destportstr, CRLF, NULL);
	    else
		ap_bvputs(f, "Host: ", desthost, CRLF, NULL);
        }
    }

    if (conf->viaopt == via_block) {
        /* Block all outgoing Via: headers */
        ap_table_unset(req_hdrs, "Via");
    }
    else if (conf->viaopt != via_off) {
        /* Create a "Via:" request header entry and merge it */
        i = ap_get_server_port(r);
        if (ap_is_default_port(i, r)) {
            strlcpy(portstr, "", sizeof(portstr));
        }
        else {
            ap_snprintf(portstr, sizeof portstr, ":%d", i);
        }
        /* Generate outgoing Via: header with/without server comment: */
        ap_table_mergen(req_hdrs, "Via",
                        (conf->viaopt == via_full)
                        ? ap_psprintf(p, "%d.%d %s%s (%s)",
                                      HTTP_VERSION_MAJOR(r->proto_num),
                                      HTTP_VERSION_MINOR(r->proto_num),
                                      ap_get_server_name(r), portstr,
                                      SERVER_BASEVERSION)
                        : ap_psprintf(p, "%d.%d %s%s",
                                      HTTP_VERSION_MAJOR(r->proto_num),
                                      HTTP_VERSION_MINOR(r->proto_num),
                                      ap_get_server_name(r), portstr)
            );
    }

    /* the X-* headers are only added if we are a reverse
     * proxy, otherwise we would be giving away private information.
     */
    if (r->proxyreq == PROXY_PASS) {
        const char *buf;

        /*
         * Add X-Forwarded-For: so that the upstream has a chance to determine,
         * where the original request came from.
         */
        ap_table_mergen(req_hdrs, "X-Forwarded-For", r->connection->remote_ip);

        /* Add X-Forwarded-Host: so that upstream knows what the
         * original request hostname was.
         */
        if ((buf = ap_table_get(r->headers_in, "Host"))) {
            ap_table_mergen(req_hdrs, "X-Forwarded-Host", buf);
        }

        /* Add X-Forwarded-Server: so that upstream knows what the
         * name of this proxy server is (if there are more than one)
         * XXX: This duplicates Via: - do we strictly need it?
         */
        ap_table_mergen(req_hdrs, "X-Forwarded-Server", r->server->server_hostname);
    } 

    /* we don't yet support keepalives - but we will soon, I promise! */
    ap_table_set(req_hdrs, "Connection", "close");

    reqhdrs_arr = ap_table_elts(req_hdrs);
    reqhdrs_elts = (table_entry *)reqhdrs_arr->elts;
    for (i = 0; i < reqhdrs_arr->nelts; i++) {
        if (reqhdrs_elts[i].key == NULL || reqhdrs_elts[i].val == NULL

        /*
         * Clear out hop-by-hop request headers not to send: RFC2616 13.5.1
         * says we should strip these headers:
         */
            || !strcasecmp(reqhdrs_elts[i].key, "Host") /* Already sent */
            || !strcasecmp(reqhdrs_elts[i].key, "Keep-Alive")
            || !strcasecmp(reqhdrs_elts[i].key, "TE")
            || !strcasecmp(reqhdrs_elts[i].key, "Trailer")
            || !strcasecmp(reqhdrs_elts[i].key, "Transfer-Encoding")
            || !strcasecmp(reqhdrs_elts[i].key, "Upgrade")
        /*
         * XXX: @@@ FIXME: "Proxy-Authorization" should *only* be suppressed
         * if THIS server requested the authentication, not when a frontend
         * proxy requested it!
         * 
         * The solution to this problem is probably to strip out the
         * Proxy-Authorisation header in the authorisation code itself, not
         * here. This saves us having to signal somehow whether this request
         * was authenticated or not.
         */
            || !strcasecmp(reqhdrs_elts[i].key, "Proxy-Authorization"))
            continue;
        ap_bvputs(f, reqhdrs_elts[i].key, ": ", reqhdrs_elts[i].val, CRLF, NULL);
    }

    /* the obligatory empty line to mark the end of the headers */
    ap_bputs(CRLF, f);

    /* and flush the above away */
    ap_bflush(f);

    /* and kill the send timeout */
    ap_kill_timeout(r);


    /* read the request data, and pass it to the backend.
     * we might encounter a stray 100-continue reponse from a PUT or POST,
     * if this happens we ignore the 100 continue status line and read the
     * response again.
     */
    {
        /* send the request data, if any. */
        ap_hard_timeout("proxy receive request data", r);
        if (ap_should_client_block(r)) {
            while ((i = ap_get_client_block(r, buffer, sizeof buffer)) > 0) {
                ap_reset_timeout(r);
                ap_bwrite(f, buffer, i);
            }
        }
        ap_bflush(f);
        ap_kill_timeout(r);


        /* then, read a response line */
        ap_hard_timeout("proxy receive response status line", r);
        result = ap_proxy_read_response_line(f, r, buffer, sizeof(buffer)-1, &backasswards, &major, &minor);
        ap_kill_timeout(r);

        /* trap any errors */
        if (result != OK) {
            ap_bclose(f);
            return result;
        }

        /* if this response was 100-continue, a stray response has been caught.
         * read the line again for the real response
         */
        if (r->status == 100) {
            ap_hard_timeout("proxy receive response status line", r);
            result = ap_proxy_read_response_line(f, r, buffer, sizeof(buffer)-1, &backasswards, &major, &minor);
            ap_kill_timeout(r);

            /* trap any errors */
            if (result != OK) {
                ap_bclose(f);
                return result;
            }
        }
    }


    /*
     * We have our response status line from the convoluted code above,
     * now we read the headers to continue.
     */
    ap_hard_timeout("proxy receive response headers", r);

    /*
     * Is it an HTTP/1 response? Do some sanity checks on the response. (This
     * is buggy if we ever see an HTTP/1.10)
     */
    if (backasswards == 0) {

        /* read the response headers. */
        /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers */
        /* Also, take care with headers with multiple occurences. */

        resp_hdrs = ap_proxy_read_headers(r, buffer, sizeof(buffer), f);
        if (resp_hdrs == NULL) {
            ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, r->server,
                         "proxy: Bad HTTP/%d.%d header returned by %s (%s)",
                         major, minor, r->uri, r->method);
            resp_hdrs = ap_make_table(p, 20);
            nocache = 1;        /* do not cache this broken file */
        }

        /* handle Via header in the response */
        if (conf->viaopt != via_off && conf->viaopt != via_block) {
            /* Create a "Via:" response header entry and merge it */
            i = ap_get_server_port(r);
            if (ap_is_default_port(i, r)) {
                strlcpy(portstr, "", sizeof(portstr));
            }
            else {
                ap_snprintf(portstr, sizeof portstr, ":%d", i);
            }
            ap_table_mergen((table *)resp_hdrs, "Via",
                            (conf->viaopt == via_full)
                            ? ap_psprintf(p, "%d.%d %s%s (%s)",
                                          major, minor,
                                          ap_get_server_name(r), portstr,
                                          SERVER_BASEVERSION)
                            : ap_psprintf(p, "%d.%d %s%s",
                                          major, minor,
                                          ap_get_server_name(r), portstr)
                );
        }

        /* is this content chunked? */
        chunked = ap_find_last_token(r->pool,
                                     ap_table_get(resp_hdrs, "Transfer-Encoding"),
                                     "chunked");

        /* strip hop-by-hop headers defined by Connection and RFC2616 */
        ap_proxy_clear_connection(p, resp_hdrs);

        content_length = ap_table_get(resp_hdrs, "Content-Length");
        if (content_length != NULL) {
            c->len = ap_strtol(content_length, NULL, 10);

	    if (c->len < 0) {
		ap_kill_timeout(r);
		return ap_proxyerror(r, HTTP_BAD_GATEWAY, ap_pstrcat(r->pool,
				     "Invalid Content-Length from remote server",
                                      NULL));
	    }
        }

    }
    else {
        /* an http/0.9 response */

        /* no headers */
        resp_hdrs = ap_make_table(p, 20);
    }

    ap_kill_timeout(r);

    /*
     * HTTP/1.1 requires us to accept 3 types of dates, but only generate one
     * type
     */
    /*
     * we SET the dates here, obliterating possible multiple dates, as only
     * one of each date makes sense in each response.
     */
    if ((datestr = ap_table_get(resp_hdrs, "Date")) != NULL)
        ap_table_set(resp_hdrs, "Date", ap_proxy_date_canon(p, datestr));
    if ((datestr = ap_table_get(resp_hdrs, "Last-Modified")) != NULL)
        ap_table_set(resp_hdrs, "Last-Modified", ap_proxy_date_canon(p, datestr));
    if ((datestr = ap_table_get(resp_hdrs, "Expires")) != NULL)
        ap_table_set(resp_hdrs, "Expires", ap_proxy_date_canon(p, datestr));

    /* handle the ProxyPassReverse mappings */
    if ((urlstr = ap_table_get(resp_hdrs, "Location")) != NULL)
        ap_table_set(resp_hdrs, "Location", proxy_location_reverse_map(r, urlstr));
    if ((urlstr = ap_table_get(resp_hdrs, "URI")) != NULL)
        ap_table_set(resp_hdrs, "URI", proxy_location_reverse_map(r, urlstr));
    if ((urlstr = ap_table_get(resp_hdrs, "Content-Location")) != NULL)
        ap_table_set(resp_hdrs, "Content-Location", proxy_location_reverse_map(r, urlstr));

/* check if NoCache directive on this host */
  {
    struct sockaddr_in *sin;
    struct sockaddr_in6 *sin6;

    if (nocache == 0) {
	for (i = 0; i < conf->nocaches->nelts; i++) {
	    if (ncent[i].name != NULL && 
		(ncent[i].name[0] == '*' ||
		 strstr(desthost, ncent[i].name) != NULL)) {
		nocache = 1;
		break;
	    }
	    switch (res->ai_addr->sa_family) {
	    case AF_INET:
		sin = (struct sockaddr_in *)res->ai_addr;
		if (sin->sin_addr.s_addr == ncent[i].addr.s_addr) {
		    nocache = 1;
		    break;
		}
	    }
	}

        /* update the cache file, possibly even fulfilling the request if
         * it turns out a conditional allowed us to serve the object from the
         * cache...
         */
        i = ap_proxy_cache_update(c, resp_hdrs, !backasswards, nocache);
        if (i != DECLINED) {
            ap_bclose(f);
            return i;
        }

        /* write status line and headers to the cache file */
        ap_proxy_write_headers(c, ap_pstrcat(p, "HTTP/1.1 ", r->status_line, NULL), resp_hdrs);
    }
  }

    /* Setup the headers for our client from upstreams response-headers */
    ap_proxy_table_replace(r->headers_out, resp_hdrs);
    /* Add X-Cache header - be careful not to obliterate any upstream headers */
    ap_table_mergen(r->headers_out, "X-Cache",
                    ap_pstrcat(r->pool, "MISS from ",
                               ap_get_server_name(r), NULL));
    /* The Content-Type of this response is the upstream one. */
    r->content_type = ap_table_get(r->headers_out, "Content-Type");
    ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, r->server, "Content-Type: %s", r->content_type);

    /* finally output the headers to the client */
    ap_send_http_header(r);

    /*
     * Is it an HTTP/0.9 respose? If so, send the extra data we read from
     * upstream as the start of the reponse to client
     */
/* FIXME: This code is broken: we try and write a buffer and length that
 * were never intelligently initialised. Rather have a bit of broken protocol
 * handling for now than broken code.
 */
/*
    if (backasswards) {
        ap_hard_timeout("proxy send assbackward", r);

        ap_bwrite(r->connection->client, buffer, len);
        if (c != NULL && c->fp != NULL && ap_bwrite(c->fp, buffer, len) != len) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, c->req,
                      "proxy: error writing extra data to %s", c->tempfile);
            c = ap_proxy_cache_error(c);
        }
        ap_kill_timeout(r);
    }
*/

/* send body */
/* if header only, then cache will be NULL */
/* HTTP/1.0 tells us to read to EOF, rather than content-length bytes */
/* XXX CHANGEME: We want to eventually support keepalives, which means
 * we must read content-length bytes... */
    if (!r->header_only) {
/* we need to set this for ap_proxy_send_fb()... */
        c->cache_completion = conf->cache.cache_completion;

/* XXX CHECKME: c->len should be the expected content length, or -1 if the
 * content length is not known. We need to make 100% sure c->len is always
 * set correctly before we get here to correctly do keepalive.
 */
        ap_proxy_send_fb(f, r, c, c->len, 0, chunked, conf->io_buffer_size);
    }

    /* ap_proxy_send_fb() closes the socket f for us */

    ap_proxy_cache_tidy(c);

    ap_proxy_garbage_coll(r);
    return OK;
}
Esempio n. 19
0
void RemoveService(char *display_name)
{
    char *service_name;
    BOOL success = FALSE;

    printf("Removing the %s service\n", display_name);

    /* Remove spaces from display name to create service name */
    service_name = get_service_name(display_name);
    
    if (isWindowsNT())
    {
        SC_HANDLE   schService;
        SC_HANDLE   schSCManager;
    
        schSCManager = OpenSCManager(
                            NULL,                   // machine (NULL == local)
                            NULL,                   // database (NULL == default)
                            SC_MANAGER_ALL_ACCESS   // access required
                            );
        if (!schSCManager) {
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "OpenSCManager failed");
            return;
        }

        schService = OpenService(schSCManager, service_name, SERVICE_ALL_ACCESS);

        if (schService == NULL) {
            /* Could not open the service */
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "OpenService failed");
        }
        else {
            /* try to stop the service */
            ap_stop_service(schService);

            // now remove the service
            if (DeleteService(schService) == 0)
                ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                             "DeleteService failed");
            else
                success = TRUE;
            CloseServiceHandle(schService);
        }
        /* SCM removes registry parameters  */
        CloseServiceHandle(schSCManager);
    }
    else /* !isWindowsNT() */
    {
        HKEY hkey;
        DWORD service_pid;
        DWORD rv;
        HWND hwnd;

        /* Locate the named window of class ApacheWin95ServiceMonitor
         * from the active top level windows
         */
        hwnd = FindWindow("ApacheWin95ServiceMonitor", service_name);
        if (hwnd && GetWindowThreadProcessId(hwnd, &service_pid))
        {
            int ticks = 120;
            char prefix[20];
            ap_snprintf(prefix, sizeof(prefix), "ap%ld", (long)service_pid);
            setup_signal_names(prefix);
            ap_start_shutdown();
            while (--ticks) {
                if (!IsWindow(hwnd))
                    break;
                Sleep(1000);
            }
        }

        /* Open the RunServices key */
        rv = RegOpenKey(HKEY_LOCAL_MACHINE, 
                "Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",
                    &hkey);
        if (rv != ERROR_SUCCESS) {
            SetLastError(rv);
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "Could not open the RunServices registry key.");
        } 
        else {
            /* Delete the registry value for this service */
            rv = RegDeleteValue(hkey, service_name);
            if (rv != ERROR_SUCCESS) {
                SetLastError(rv);
                ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                             "Unable to remove service: "
                             "Could not delete the RunServices entry.");
            }
            else
                success = TRUE;
        }
        RegCloseKey(hkey);

        /* Open the Services key */
        rv = RegOpenKey(HKEY_LOCAL_MACHINE, 
                        "SYSTEM\\CurrentControlSet\\Services", &hkey);
        if (rv != ERROR_SUCCESS) {
            rv = RegDeleteValue(hkey, service_name);
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "Could not open the Services registry key.");
            success = FALSE;
        } 
        else {
            /* Delete the registry key for this service */
            rv = RegDeleteKey(hkey, service_name);
            if (rv != ERROR_SUCCESS) {
                SetLastError(rv);
                ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                             "Unable to remove service: "
                             "Could not delete the Services registry key.");
                success = FALSE;
            }
        }
        RegCloseKey(hkey);
    }
    if (success)
        printf("The %s service has been removed successfully.\n", 
               display_name);
}
Esempio n. 20
0
static int suphp_handler(request_rec *r) {
    suphp_conf *sconf;
    suphp_conf *dconf;

#ifdef SUPHP_USE_USERGROUP
    char *ud_user = NULL;
    char *ud_group = NULL;
    int ud_success = 0;
#endif

    struct stat finfo;

    int rv;

    char *auth_user = NULL;
    char *auth_pass = NULL;

    pool *p;

    BUFF *script_in, *script_out, *script_err;

    const char *handler;

    sconf = ap_get_module_config(r->server->module_config, &suphp_module);
    dconf = ap_get_module_config(r->per_dir_config, &suphp_module);

    p = r->main ? r->main->pool : r->pool;

    /* only handle request if mod_suphp is active for this handler */
    /* check only first byte of value (second has to be \0) */
    if (r->handler != NULL) {
        handler = r->handler;
    } else {
        handler = r->content_type;
    }
    if ((ap_table_get(dconf->handlers, handler) == NULL)) {
        if ((ap_table_get(sconf->handlers, handler) == NULL)
            || (*(ap_table_get(sconf->handlers, handler)) == '0')) {
            return DECLINED;
        }
    } else if (*(ap_table_get(dconf->handlers, handler)) == '0') {
        return DECLINED;
    }

    /* check if suPHP is enabled for this request */

    if (((sconf->engine != SUPHP_ENGINE_ON)
         && (dconf->engine != SUPHP_ENGINE_ON))
        || ((sconf->engine == SUPHP_ENGINE_ON)
            && (dconf->engine == SUPHP_ENGINE_OFF)))
        return DECLINED;

    /* check if file is existing and accessible */

    rv = stat(ap_pstrdup(p, r->filename), &finfo);
    if (rv == 0) {
        ; /* do nothing */
    } else if (errno == EACCES) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "access to %s denied",
                      r->filename);
        return HTTP_FORBIDDEN;
    } else if (errno == ENOENT || errno == ENOTDIR) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "File does not exist: %s",
                      r->filename);
        return HTTP_NOT_FOUND;
    } else {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r, "could not get fileinfo: %s",
                      r->filename);
        return HTTP_NOT_FOUND;
    }

#ifdef SUPHP_USE_USERGROUP
    if ((sconf->target_user == NULL || sconf->target_group == NULL)
        && (dconf->target_user == NULL || dconf->target_group == NULL)) {

        /* Identify mod_userdir request
           As Apache 1.3 does not yet provide a clean way to see
           whether a request was handled by mod_userdir, we assume
           this is true for any request beginning with ~ */

        int ud_success = 0; /* set to 1 on success */

        if (!strncmp("/~", r->uri, 2)) {
            char *username = ap_pstrdup(r->pool, r->uri + 2);
            char *pos = strchr(username, '/');
            if (pos) {
                *pos = 0;
                if (strlen(username)) {
                    struct passwd *pw;
                    struct group *gr;
                    gid_t gid;
                    char *grpname;
                    if ((pw = getpwnam(username)) != NULL) {
                        gid = pw->pw_gid;

                        if ((gr = getgrgid(gid)) != NULL) {
                            grpname = gr->gr_name;
                        } else {
                            if ((grpname = ap_palloc(r->pool, 16)) == NULL) {
                                return HTTP_INTERNAL_SERVER_ERROR;
                            }
                            ap_snprintf(grpname, 16, "#%ld", (long) gid);
                        }

                        ud_user = username;
                        ud_group = grpname;
                        ud_success = 1;
                    }
                }
            }
        }

        if (!ud_success) {
            /* This is not a userdir request and user/group are not
               set, so log the error and return */
            ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                          "No user or group set - set suPHP_UserGroup");
            return HTTP_INTERNAL_SERVER_ERROR;
        }
    }
#endif /* SUPHP_USE_USERGROUP */


    /* prepare environment for new process */

    ap_add_common_vars(r);
    ap_add_cgi_vars(r);

    ap_table_unset(r->subprocess_env, "SUPHP_PHP_CONFIG");
    ap_table_unset(r->subprocess_env, "SUPHP_AUTH_USER");
    ap_table_unset(r->subprocess_env, "SUPHP_AUTH_PW");

#ifdef SUPHP_USE_USERGROUP
    ap_table_unset(r->subprocess_env, "SUPHP_USER");
    ap_table_unset(r->subprocess_env, "SUPHP_GROUP");
    ap_table_unset(r->subprocess_env, "SUPHP_USERDIR_USER");
    ap_table_unset(r->subprocess_env, "SUPHP_USERDIR_GROUP");
#endif /* SUPHP_USE_USERGROUP */

    if (dconf->php_config) {
        ap_table_set(r->subprocess_env, "SUPHP_PHP_CONFIG", dconf->php_config);
    }

    ap_table_set(r->subprocess_env, "SUPHP_HANDLER", handler);

    if (r->headers_in) {
        const char *auth;
        auth = ap_table_get(r->headers_in, "Authorization");
        if (auth && auth[0] != 0 && strncmp(auth, "Basic ", 6) == 0) {
            char *user;
            char *pass;
            user = ap_pbase64decode(p, auth + 6);
            if (user) {
                pass = strchr(user, ':');
                if (pass) {
                    *pass++ = '\0';
                    auth_user = ap_pstrdup(p, user);
                    auth_pass = ap_pstrdup(p, pass);
                }
            }
        }
    }

    if (auth_user && auth_pass) {
        ap_table_setn(r->subprocess_env, "SUPHP_AUTH_USER", auth_user);
        ap_table_setn(r->subprocess_env, "SUPHP_AUTH_PW", auth_pass);
    }

#ifdef SUPHP_USE_USERGROUP
    if (dconf->target_user) {
        ap_table_set(r->subprocess_env, "SUPHP_USER", dconf->target_user);
    } else if (sconf->target_user) {
        ap_table_set(r->subprocess_env, "SUPHP_USER", sconf->target_user);
    } else {
        ap_table_set(r->subprocess_env, "SUPHP_USER", ud_user);
    }

    if (dconf->target_group) {
        ap_table_set(r->subprocess_env, "SUPHP_GROUP", dconf->target_group);
    } else if (sconf->target_group) {
        ap_table_set(r->subprocess_env, "SUPHP_GROUP", sconf->target_group);
    } else {
        ap_table_set(r->subprocess_env, "SUPHP_GROUP", ud_group);
    }
    if (ud_success) {
	ap_table_set(r->subprocess_env, "SUPHP_USERDIR_USER", ud_user);
	ap_table_set(r->subprocess_env, "SUPHP_USERDIR_GROUP", ud_group);
    }
#endif /* SUPHP_USE_USERGROUP */

    /* Fork child process */

    if (!ap_bspawn_child(p, suphp_child, (void *) r, kill_after_timeout,
                         &script_in, &script_out, &script_err)) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
                      "couldn't spawn child process for: %s", r->filename);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Transfer request body to script */

    if ((rv = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)) != OK) {
        /* Call failed, return status */
        return rv;
    }

    if (ap_should_client_block(r)) {
        char buffer[HUGE_STRING_LEN];
        int len_read;

        ap_hard_timeout("reading request body", r);

        while ((len_read = ap_get_client_block(r, buffer, HUGE_STRING_LEN))
               > 0) {
            ap_reset_timeout(r);
            if (ap_bwrite(script_in, buffer, len_read) < len_read) {
                /* silly script stopped reading, soak up remaining message */
                while (ap_get_client_block(r, buffer, HUGE_STRING_LEN) > 0) {
                    /* dump it */
                }
                break;
            }
        }

        ap_bflush(script_in);
        ap_kill_timeout(r);
    }

    ap_bclose(script_in);

    /* Transfer output from script to client */

    if (script_out) {
        const char *location;
        char hbuffer[MAX_STRING_LEN];
        char buffer[HUGE_STRING_LEN];

        rv = ap_scan_script_header_err_buff(r, script_out, hbuffer);
        if (rv == HTTP_NOT_MODIFIED) {
            return rv;
        } else if (rv) {
            return HTTP_INTERNAL_SERVER_ERROR;
        }

        location = ap_table_get(r->headers_out, "Location");
        if (location && r->status == 200) {
            /* Soak up all the script output */
            ap_hard_timeout("reading from script", r);
            while (ap_bgets(buffer, HUGE_STRING_LEN, script_out) > 0) {
                continue;
            }
            ap_kill_timeout(r);
            ap_bclose(script_out);
            ap_bclose(script_err);

            if (location[0] == '/') {
                /* Redirect has always GET method */
                r->method = ap_pstrdup(p, "GET");
                r->method_number = M_GET;

                /* Remove Content-Length - redirect should not read  *
                 * request body                                      */
                ap_table_unset(r->headers_in, "Content-Length");

                /* Do the redirect */
                ap_internal_redirect_handler(location, r);
                return OK;
            } else {
                /* Script did not set status 302 - so it does not want *
                 * to send its own body. Simply set redirect status    */
                return REDIRECT;
            }
        }

        /* Output headers and body */

        ap_send_http_header(r);
        if (!r->header_only) {
            ap_send_fb(script_out, r);
        }
        ap_bclose(script_out);
        /* Errors have already been logged by child */
        ap_bclose(script_err);
    }

    return OK;
}
Esempio n. 21
0
API_EXPORT(void) ap_log_error (const char *file, int line, int level,
			      const server_rec *s, const char *fmt, ...)
{
    va_list args;
    char errstr[MAX_STRING_LEN];
    size_t len;
    int save_errno = errno;
    FILE *logf;

    if (s == NULL) {
	/*
	 * If we are doing stderr logging (startup), don't log messages that are
	 * above the default server log level unless it is a startup/shutdown
	 * notice
	 */
	if (((level & APLOG_LEVELMASK) != APLOG_NOTICE) &&
	    ((level & APLOG_LEVELMASK) > DEFAULT_LOGLEVEL))
	    return;
	logf = stderr;
    }
    else if (s->error_log) {
	/*
	 * If we are doing normal logging, don't log messages that are
	 * above the server log level unless it is a startup/shutdown notice
	 */
	if (((level & APLOG_LEVELMASK) != APLOG_NOTICE) &&
	    ((level & APLOG_LEVELMASK) > s->loglevel))
	    return;
	logf = s->error_log;
    }
    else {
	/*
	 * If we are doing syslog logging, don't log messages that are
	 * above the server log level (including a startup/shutdown notice)
	 */
	if ((level & APLOG_LEVELMASK) > s->loglevel)
	    return;
	logf = NULL;
    }

    if (logf) {
	len = ap_snprintf(errstr, sizeof(errstr), "[%s] ", ap_get_time());
    } else {
	len = 0;
    }

    len += ap_snprintf(errstr + len, sizeof(errstr) - len,
	    "[%s] ", priorities[level & APLOG_LEVELMASK].t_name);

    if (file && (level & APLOG_LEVELMASK) == APLOG_DEBUG) {
#ifdef _OSD_POSIX
	char tmp[256];
	char *e = strrchr(file, '/');

	/* In OSD/POSIX, the compiler returns for __FILE__
	 * a string like: __FILE__="*POSIX(/usr/include/stdio.h)"
	 * (it even returns an absolute path for sources in
	 * the current directory). Here we try to strip this
	 * down to the basename.
	 */
	if (e != NULL && e[1] != '\0') {
	    ap_snprintf(tmp, sizeof(tmp), "%s", &e[1]);
	    e = &tmp[strlen(tmp)-1];
	    if (*e == ')')
		*e = '\0';
	    file = tmp;
	}
#endif /*_OSD_POSIX*/
	len += ap_snprintf(errstr + len, sizeof(errstr) - len,
		"%s(%d): ", file, line);
    }
    if (!(level & APLOG_NOERRNO)
	&& (save_errno != 0)
#ifdef WIN32
	&& !(level & APLOG_WIN32ERROR)
#endif
	) {
	len += ap_snprintf(errstr + len, sizeof(errstr) - len,
		"(%d)%s: ", save_errno, strerror(save_errno));
    }
#ifdef WIN32
    if (level & APLOG_WIN32ERROR) {
	int nChars;
	int nErrorCode;

	nErrorCode = GetLastError();
	len += ap_snprintf(errstr + len, sizeof(errstr) - len,
	    "(%d)", nErrorCode);

	nChars = FormatMessage( 
	    FORMAT_MESSAGE_FROM_SYSTEM,
	    NULL,
	    nErrorCode,
	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
	    (LPTSTR) errstr + len,
	    sizeof(errstr) - len,
	    NULL 
	);
	len += nChars;
	if (nChars == 0) {
	    /* Um, error occurred, but we can't recurse to log it again
	     * (and it would probably only fail anyway), so lets just
	     * log the numeric value.
	     */
	    nErrorCode = GetLastError();
	    len += ap_snprintf(errstr + len, sizeof(errstr) - len,
		"(FormatMessage failed with code %d): ", nErrorCode);
	}
	else {
	    /* FormatMessage put the message in the buffer, but it may
	     * have appended a newline (\r\n). So remove it and use
	     * ": " instead like the Unix errors. The error may also
	     * end with a . before the return - if so, trash it.
	     */
	    if (len > 1 && errstr[len-2] == '\r' && errstr[len-1] == '\n') {
		if (len > 2 && errstr[len-3] == '.')
		    len--;
		errstr[len-2] = ':';
		errstr[len-1] = ' ';
	    }
	}
    }
#endif

    va_start(args, fmt);
    len += ap_vsnprintf(errstr + len, sizeof(errstr) - len, fmt, args);
    va_end(args);

    /* NULL if we are logging to syslog */
    if (logf) {
	fputs(errstr, logf);
	fputc('\n', logf);
	fflush(logf);
    }
#ifdef HAVE_SYSLOG
    else {
	syslog(level & APLOG_LEVELMASK, "%s", errstr);
    }
#endif
}
Esempio n. 22
0
static void vhost_alias_interpolate(request_rec *r, const char *name,
				    const char *map, const char *uri)
{
    /* 0..9 9..0 */
    enum { MAXDOTS = 19 };
    const char *dots[MAXDOTS+1];
    int ndots;

    char buf[HUGE_STRING_LEN];
    char *dest, last;

    int N, M, Np, Mp, Nd, Md;
    const char *start, *end;

    const char *p;

    ndots = 0;
    dots[ndots++] = name-1; /* slightly naughty */
    for (p = name; *p; ++p){
	if (*p == '.' && ndots < MAXDOTS) {
	    dots[ndots++] = p;
	}
    }
    dots[ndots] = p;

    r->filename = NULL;
  
    dest = buf;
    last = '\0';
    while (*map) {
	if (*map != '%') {
	    /* normal characters */
	    vhost_alias_checkspace(r, buf, &dest, 1);
	    last = *dest++ = *map++;
	    continue;
	}
	/* we are in a format specifier */
	++map;
	/* can't be a slash */
	last = '\0';
	/* %% -> % */
	if (*map == '%') {
	    ++map;
	    vhost_alias_checkspace(r, buf, &dest, 1);
	    *dest++ = '%';
	    continue;
	}
	/* port number */
	if (*map == 'p') {
	    ++map;
	    /* no. of decimal digits in a short plus one */
	    vhost_alias_checkspace(r, buf, &dest, 7);
	    dest += ap_snprintf(dest, 7, "%d", ap_get_server_port(r));
	    continue;
	}
	/* deal with %-N+.-M+ -- syntax is already checked */
	N = M = 0;   /* value */
	Np = Mp = 0; /* is there a plus? */
	Nd = Md = 0; /* is there a dash? */
	if (*map == '-') ++map, Nd = 1;
	N = *map++ - '0';
	if (*map == '+') ++map, Np = 1;
	if (*map == '.') {
	    ++map;
	    if (*map == '-') {
		++map, Md = 1;
	    }
	    M = *map++ - '0';
	    if (*map == '+') {
		++map, Mp = 1;
	    }
	}
	/* note that N and M are one-based indices, not zero-based */
	start = dots[0]+1; /* ptr to the first character */
	end = dots[ndots]; /* ptr to the character after the last one */
	if (N != 0) {
	    if (N > ndots) {
		start = "_";
		end = start+1;
	    }
	    else if (!Nd) {
		start = dots[N-1]+1;
		if (!Np) {
		    end = dots[N];
		}
	    }
	    else {
		if (!Np) {
		    start = dots[ndots-N]+1;
		}
		end = dots[ndots-N+1];
	    }
	}
	if (M != 0) {
	    if (M > end - start) {
		start = "_";
		end = start+1;
	    }
	    else if (!Md) {
		start = start+M-1;
		if (!Mp) {
		    end = start+1;
		}
	    }
	    else {
		if (!Mp) {
		    start = end-M;
		}
		end = end-M+1;
	    }
	}
	vhost_alias_checkspace(r, buf, &dest, end - start);
	for (p = start; p < end; ++p) {
	    *dest++ = ap_tolower(*p);
	}
    }
    *dest = '\0';
    /* no double slashes */
    if (last == '/') {
	++uri;
    }
    if (r->filename) {
	r->filename = ap_pstrcat(r->pool, r->filename, buf, uri, NULL);
    }
    else {
	r->filename = ap_pstrcat(r->pool, buf, uri, NULL);
    }
}
Esempio n. 23
0
/* Ambarish fix this. Very broken */
static int get_rfc1413(int sock, const struct sockaddr_in *our_sin,
		       const struct sockaddr_in *rmt_sin, 
		       char user[RFC1413_USERLEN+1], server_rec *srv)
{
    struct sockaddr_in rmt_query_sin, our_query_sin;
    unsigned int rmt_port, our_port;
    int i;
    char *cp;
    char buffer[RFC1413_MAXDATA + 1];
    int buflen;

    /*
     * Bind the local and remote ends of the query socket to the same
     * IP addresses as the connection under investigation. We go
     * through all this trouble because the local or remote system
     * might have more than one network address. The RFC1413 etc.
     * client sends only port numbers; the server takes the IP
     * addresses from the query socket.
     */

    our_query_sin = *our_sin;
    our_query_sin.sin_port = htons(ANY_PORT);
#ifdef MPE 
    our_query_sin.sin_addr.s_addr = INADDR_ANY;
#endif
    rmt_query_sin = *rmt_sin;
    rmt_query_sin.sin_port = htons(RFC1413_PORT);

    if (bind(sock, (struct sockaddr *) &our_query_sin,
	     sizeof(struct sockaddr_in)) < 0) {
	ap_log_error(APLOG_MARK, APLOG_CRIT, srv,
		    "bind: rfc1413: Error binding to local port");
	return -1;
    }

/*
 * errors from connect usually imply the remote machine doesn't support
 * the service
 */
    if (connect(sock, (struct sockaddr *) &rmt_query_sin,
		sizeof(struct sockaddr_in)) < 0)
	            return -1;

/* send the data */
    buflen = ap_snprintf(buffer, sizeof(buffer), "%u,%u\r\n", ntohs(rmt_sin->sin_port),
		ntohs(our_sin->sin_port));

    /* send query to server. Handle short write. */
#ifdef CHARSET_EBCDIC
    ebcdic2ascii(buffer, buffer, buflen);
#endif
    i = 0;
    while(i < (int)strlen(buffer)) {
        int j;
	j = write(sock, buffer+i, (strlen(buffer+i)));
	if (j < 0 && errno != EINTR) {
	  ap_log_error(APLOG_MARK, APLOG_CRIT, srv,
		       "write: rfc1413: error sending request");
	  return -1;
	}
	else if (j > 0) {
	    i+=j; 
	}
    }

    /*
     * Read response from server. - the response should be newline 
     * terminated according to rfc - make sure it doesn't stomp it's
     * way out of the buffer.
     */

    i = 0;
    memset(buffer, '\0', sizeof(buffer));
    /*
     * Note that the strchr function below checks for \012 instead of '\n'
     * this allows it to work on both ASCII and EBCDIC machines.
     */
    while((cp = strchr(buffer, '\012')) == NULL && i < sizeof(buffer) - 1) {
        int j;
  
#ifdef TPF
        /*
         * socket read on TPF doesn't get interrupted by
         * signals so additional processing is needed
         */
        j = ap_set_callback_and_alarm(NULL, 0);
        ap_set_callback_and_alarm(ident_timeout, j);
        j = select(&sock, 1, 0, 0, j * 1000);
        if (j < 1) {
            ap_set_callback_and_alarm(NULL, 0);
            ap_check_signals();
            return -1;
        }
#endif /* TPF */
	j = read(sock, buffer+i, (sizeof(buffer) - 1) - i);
	if (j < 0 && errno != EINTR) {
	   ap_log_error(APLOG_MARK, APLOG_CRIT, srv,
			"read: rfc1413: error reading response");
	   return -1;
	}
	else if (j > 0) {
	    i+=j; 
	}
    }

/* RFC1413_USERLEN = 512 */
#ifdef CHARSET_EBCDIC
    ascii2ebcdic(buffer, buffer, (size_t)i);
#endif
    if (sscanf(buffer, "%u , %u : USERID :%*[^:]:%512s", &rmt_port, &our_port,
	       user) != 3 || ntohs(rmt_sin->sin_port) != rmt_port
	|| ntohs(our_sin->sin_port) != our_port)
	return -1;

    /*
     * Strip trailing carriage return. It is part of the
     * protocol, not part of the data.
     */

    if ((cp = strchr(user, '\r')))
	*cp = '\0';

    return 0;
}
Esempio n. 24
0
void ssl_log(server_rec *s, int level, const char *msg, ...)
{
    char tstr[80];
    char lstr[20];
    char vstr[1024];
    char str[1024];
    char nstr[2];
    int timz;
    struct tm *t;
    va_list ap;
    int add;
    int i;
    char *astr;
    int safe_errno;
    unsigned long e;
    SSLSrvConfigRec *sc;
    char *cpE;
    char *cpA;

    /*  initialization  */
    va_start(ap, msg);
    safe_errno = errno;
    sc = mySrvConfig(s);

    /*  strip out additional flags  */
    add   = (level & ~SSL_LOG_MASK);
    level = (level & SSL_LOG_MASK);

    /*  reduce flags when not reasonable in context  */
    if (add & SSL_ADD_ERRNO && errno == 0)
        add &= ~SSL_ADD_ERRNO;
    if (add & SSL_ADD_SSLERR && ERR_peek_error() == 0)
        add &= ~SSL_ADD_SSLERR;

    /*  we log only levels below, except for errors */
    if (   sc->fileLogFile == NULL
        && !(level & SSL_LOG_ERROR))
        return;
    if (   level > sc->nLogLevel
        && !(level & SSL_LOG_ERROR))
        return;

    /*  determine the time entry string  */
    if (add & SSL_NO_TIMESTAMP)
        tstr[0] = NUL;
    else {
        t = ap_get_gmtoff(&timz);
        strftime(tstr, 80, "[%d/%b/%Y %H:%M:%S", t);
        i = strlen(tstr);
        ap_snprintf(tstr+i, 80-i, " %05d] ", (unsigned int)getpid());
    }

    /*  determine whether newline should be written */
    if (add & SSL_NO_NEWLINE)
        nstr[0] = NUL;
    else {
        nstr[0] = '\n';
        nstr[1] = NUL;
    }

    /*  determine level name  */
    lstr[0] = NUL;
    if (!(add & SSL_NO_LEVELID)) {
        for (i = 0; ssl_log_level2string[i].nLevel != 0; i++) {
            if (ssl_log_level2string[i].nLevel == level) {
                ap_snprintf(lstr, sizeof(lstr), "[%s]", ssl_log_level2string[i].szLevel);
                break;
            }
        }
        for (i = strlen(lstr); i <= 7; i++)
            lstr[i] = ' ';
        lstr[i] = NUL;
    }

    /*  create custom message  */
    ap_vsnprintf(vstr, sizeof(vstr), msg, ap);

    /*  write out SSLog message  */
    if ((add & SSL_ADD_ERRNO) && (add & SSL_ADD_SSLERR))
        astr = " (System and " SSL_LIBRARY_NAME " library errors follow)";
    else if (add & SSL_ADD_ERRNO)
        astr = " (System error follows)";
    else if (add & SSL_ADD_SSLERR)
        astr = " (" SSL_LIBRARY_NAME " library error follows)";
    else
        astr = "";
    if (level <= sc->nLogLevel && sc->fileLogFile != NULL) {
        ap_snprintf(str, sizeof(str), "%s%s%s%s%s", tstr, lstr, vstr, astr, nstr);
        fprintf(sc->fileLogFile, "%s", str);
    }
    if (level & SSL_LOG_ERROR)
        ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, s,
                     "mod_ssl: %s%s", vstr, astr);

    /*  write out additional attachment messages  */
    if (add & SSL_ADD_ERRNO) {
        if (level <= sc->nLogLevel && sc->fileLogFile != NULL) {
            ap_snprintf(str, sizeof(str), "%s%sSystem: %s (errno: %d)%s",
                        tstr, lstr, strerror(safe_errno), safe_errno, nstr);
            fprintf(sc->fileLogFile, "%s", str);
        }
        if (level & SSL_LOG_ERROR)
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, s,
                         "System: %s (errno: %d)",
                         strerror(safe_errno), safe_errno);
    }
    if (add & SSL_ADD_SSLERR) {
        while ((e = ERR_get_error())) {
            cpE = ERR_error_string(e, NULL);
            cpA = ssl_log_annotation(cpE);
            if (level <= sc->nLogLevel && sc->fileLogFile != NULL) {
                ap_snprintf(str, sizeof(str), "%s%s%s: %s%s%s%s%s",
                            tstr, lstr, SSL_LIBRARY_NAME, cpE,
                            cpA != NULL ? " [Hint: " : "",
                            cpA != NULL ? cpA : "", cpA != NULL ? "]" : "",
                            nstr);
                fprintf(sc->fileLogFile, "%s", str);
            }
            if (level & SSL_LOG_ERROR)
                ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, s,
                             "%s: %s%s%s%s", SSL_LIBRARY_NAME, cpE,
                             cpA != NULL ? " [Hint: " : "",
                             cpA != NULL ? cpA : "", cpA != NULL ? "]" : "");
        }
    }
    /* make sure the next log starts from a clean base */
    /* ERR_clear_error(); */

    /*  cleanup and return  */
    if (sc->fileLogFile != NULL)
        fflush(sc->fileLogFile);
    errno = safe_errno;
    va_end(ap);
    return;
}
Esempio n. 25
0
static void bt_show_backtrace(int sig)
{
    char msgbuf[128];
    size_t size;
    void *array[20];
    extern int main();
    int logfd;
    time_t now;
    char msg_prefix[60];
    char *newline;
    int using_errorlog = 1;

    time(&now);
    ap_snprintf(msg_prefix, sizeof msg_prefix,
                "[%s pid %ld mod_backtrace",
                asctime(localtime(&now)),
                (long)getpid());
    newline = strchr(msg_prefix, '\n'); /* dang asctime() */
    if (newline) {                      /* silly we are */
        *newline = ']';
    }

    if (log_fname) {
        logfd = open(log_fname, O_WRONLY|O_APPEND|O_CREAT, 0644);
        if (logfd == -1) {
            logfd = 2; /* unix, so fd 2 is the web server error log */
            ap_snprintf(msgbuf, sizeof msgbuf,
                        "%s error %d opening %s\n",
                        msg_prefix, errno, log_fname);
            write(logfd, msgbuf, strlen(msgbuf));
        }
        else {
            using_errorlog = 0;
        }
    }
    else {
        logfd = 2;
    }
    
    ap_snprintf(msgbuf, sizeof msgbuf,
                "%s backtrace for signal %d\n",
                msg_prefix, sig);
    write(logfd, msgbuf, strlen(msgbuf));

    /* the address of main() can be useful if we're on old 
     * glibc and get only addresses for stack frames... knowing
     * where main() is then is a useful clue
     */
    ap_snprintf(msgbuf, sizeof msgbuf,
                "%s main() is at %pp\n",
                msg_prefix,
                main);/* don't you DARE put parens after "main" */
    write(logfd, msgbuf, strlen(msgbuf));

    size = backtrace(array, sizeof array / sizeof array[0]);
    backtrace_symbols_fd(array, size, logfd);
    ap_snprintf(msgbuf, sizeof msgbuf,
                "%s end of report\n",
                msg_prefix);
    write(logfd, msgbuf, strlen(msgbuf));
    if (!using_errorlog) {
        close(logfd);
    }
}
Esempio n. 26
0
int processlink(int nlink, int sock, int state)
{
    struct usernodes *th;
    struct linknodes *lh;
    int rc;
    char *pt,*pt2;
#ifdef PARTYCHANNEL
    int rr = 0;
    char buf[600] = "";
    char buf1[400] = "";
#endif
    char l;
    char o[]="->";
    char i[]="<-";
    char r[]="R ";
    char sic[500];
    int last;
    pcontext;
    if (state!=STD_CONN) return 0x0;
    parse();
    pcontext;
    if (!ifcommand("IAM") && !ifcommand(lngtxt(521))) broadcast(nlink); /* if its the IAM message, it does NOT
						get broadcasted */
    pcontext;
    pt=strchr(ircto,'@');
#ifdef PARTYCHANNEL
    if(pt==NULL) pt=strchr(ircto,'*');
#endif
    pcontext;
    if (pt!=NULL) 
    {
	*pt=0;
	pt++;
	if (strmcmp(pt,me)!=0 || (*ircto=='*' && strlen(pt)==1))
	{
	    pcontext;
	    if (ifcommand(lngtxt(522)))
	    {
		rc=checkuser(ircto);
		if (rc==0)
		{
		    ap_snprintf(ircbuf,sizeof(ircbuf),lngtxt(523),me,ircnick,irchost,ircto);
		    broadcast(0);	    
		    return 0x0;
		}
#ifdef PARTYCHANNEL
		ssnprintf(user(rc)->insock,lngtxt(524),ircnick,irchost,user(rc)->nick,irccontent);
#else
		ssnprintf(user(rc)->insock,lngtxt(525),ircnick,irchost,user(rc)->nick,irccontent);
#endif
		return 0x0;
	    }
	    pcontext;
	    if (ifcommand(lngtxt(526)))
	    {
		if(strstr(irccontent,o)!=NULL || strstr(irccontent,i)!=NULL) /* this is a listlink for the topology */
		{
		    pt=strchr(irccontent,'[');
		    if(pt!=NULL)
		    {
			pt++;
			pt2=strstr(pt,"]*");
			if(pt2!=NULL)
			{
			    *pt2=0;
			    strmncpy(sic,pt,sizeof(sic)); /* in sic we got the first linker */
			    pt2++;
			    pt=strstr(pt2,o);
			    if(pt==NULL) pt=strstr(pt2,i);
			    if(pt==NULL) return 0x0;		    
			    pt2=strchr(pt+3,' ');
			    if(pt2!=NULL)
			    {
				*pt2=0;
				if(strstr(pt,o)==pt)
				{
				    pt+=3;
				    addtopology(sic,pt);
				} else {
				    pt+=3;
				    addtopology(pt,sic);
				}
				return 0x0;
			    }
			}
		    }
		}
		pcontext;
#ifdef PARTYCHANNEL
		if(strstr(ircbuf,lngtxt(527))==ircbuf)
		{
		    if(*ircto=='*') /* systemrequest */
		    {
			pt=strchr(irccontent,']');
			if(pt!=NULL)
			{
			    pt+=2;
			    if(*pt=='*')
			    {
				pt2=strchr(pt,'(');
				if (pt2!=NULL)
				{
				    pt+=2;
				    *pt2=0;
				    ap_snprintf(buf,sizeof(buf),lngtxt(528),pt,irchost);
				    if(partyadd(buf)==1)
				    {
					ap_snprintf(buf1,sizeof(buf1),"%s%s\r\n",lngtxt(529),PARTYCHAN);
					ap_snprintf(buf,sizeof(buf),buf1,pt,irchost,pt,irchost);
					th=usernode;
					while(th!=NULL)
					{
					    rc=th->uid;
					    if(user(rc)->instate==STD_CONN && user(rc)->sysmsg==1 && user(rc)->parent==0)
					    {
						writesock(user(rc)->insock,buf);
					    }
					    th=th->next;
					}
					return 0x0;
				    }
				}
			    }
			}
		    }
		}
#endif
		rc=checkuser(ircto);
		if (rc!=0)
		{
		    ssnprintf(user(rc)->insock,lngtxt(530),ircnick,user(rc)->nick,irccontent);
		    return 0x0;
		}
	    }
	}
    }
    pcontext;
    if (ifcommand("IAM"))
    {
	if(*ircnick==0 || strchr(ircnick,' ')!=NULL || strchr(ircnick,'@')!=NULL || strchr(ircnick,'*')!=NULL)
	{
	    sysparty(lngtxt(531));
	    killsocket(sock);
	    datalink(nlink)->instate=STD_NOCON;
	    datalink(nlink)->outstate=STD_NOCON;
	    datalink(nlink)->insock=0;
	    datalink(nlink)->outsock=0;
	    clearlink(nlink);
	    eraselinkini(nlink);
	    return 0x0;
	}
	strmncpy(datalink(nlink)->iam,ircnick,sizeof(datalink(nlink)->iam));
	addtopology(me,datalink(nlink)->iam);
	writelink(nlink);
    }
    pcontext;
    if (ifcommand(lngtxt(532)))
    {
	if (strmcmp(me,ircto)!=0)
	{
	    p_log(LOG_ERROR,-1,lngtxt(533),
	      nlink,datalink(nlink)->host,datalink(nlink)->port);
	    killsocket(sock);
	    removetopology(me,datalink(nlink)->iam,lostlink);
	    datalink(nlink)->instate=STD_NOCON;
	    datalink(nlink)->outstate=STD_NOCON;
	    datalink(nlink)->insock=0;
	    datalink(nlink)->outsock=0;
	    clearlink(nlink);
	    eraselinkini(nlink);
	    return 0x0;	
	}
    }
    pcontext;
    if (ifcommand(lngtxt(534)))
    {
	th=usernode;
	while (th!=NULL) {
	    rc=th->uid;
	    if ((user(rc)->instate==STD_CONN && user(rc)->parent==0 && user(rc)->sysmsg==1) || rc==1)
	    {
		strmncpy(sic,irccontent,sizeof(sic));
#ifdef PARTYCHANNEL
		strmncpy(irccommand,lngtxt(535),sizeof(irccommand));
		strmncpy(ircto,PARTYCHAN,sizeof(ircto));
		if(strlen(ircto+1)<sizeof(ircto))
		    strcat(ircto," ");
#endif
		/* keeping being compatible with earlier versions requires this */
		if(strlen(ircnick)==6 && strstr(ircnick,lngtxt(536))==ircnick)
		{
#ifdef PARTYCHANNEL
		    if(strstr(irccontent,lngtxt(537))!=NULL)
		    {
			pt=strstr(irccontent,lngtxt(538));
			if(pt!=NULL)
			{
			    pt+=5;
			    pt2=strchr(pt,' ');
			    if (pt2!=NULL) *pt2=0;
			    strmncpy(ircnick,pt,sizeof(ircnick));
			    ap_snprintf(buf,sizeof(buf),lngtxt(539),pt,irchost);
			    strcpy(irccommand,"JOIN");
			    strmncpy(irccontent,PARTYCHAN,sizeof(irccontent));
			    *ircto=0;
			    if(rr==0) { partyadd(buf); rr=1; }
			}
		    }
		    if(strstr(irccontent,lngtxt(540))!=NULL)    
		    {
			pt=strstr(irccontent,lngtxt(541));
			if(pt!=NULL)
			{
			    pt+=5;
			    pt2=strchr(pt,' ');
			    if (pt2!=NULL) *pt2=0;
			    strmncpy(ircnick,pt,sizeof(ircnick));
			    ap_snprintf(buf,sizeof(buf),lngtxt(542),pt,irchost);
			    strcpy(irccommand,"PART");
			    strmncpy(irccontent,lngtxt(543),sizeof(irccontent));
			    if(rr==0) { partyremove(buf); rr=1; }
			}
		    }
#endif
		    if(strstr(irccontent,lngtxt(544))==irccontent)
		    {
			ap_snprintf(ircbuf,sizeof(ircbuf),lngtxt(545),me);
			broadcast(0);
			return 0x0;
		    }
		    if(strstr(irccontent,lngtxt(546))==irccontent)    
		    {
			pt=irccontent+11;
			pt2=strchr(pt,')');
			if(pt2!=NULL) *pt2=0;
			removetopology(irchost,pt,lostlink);
			if(pt2!=NULL) *pt2=')';
		    }
		}
#ifdef PARTYCHANNEL
		ap_snprintf(buf,sizeof(buf),lngtxt(547),
						    ircnick,irchost,ircnick,irchost,
						    irccommand,ircto,irccontent);
		if(user(rc)->instate==STD_CONN && user(rc)->parent==0 && user(rc)->sysmsg==1)
		    writesock(user(rc)->insock,buf);						    
#endif	
		ap_snprintf(irccontent,sizeof(irccontent),"%s",sic);
	    }
	    th=th->next;
	}	
	return 0x0;
    }
    pcontext;
    if (ifcommand("BWHO"))
    {
	th=usernode;
	while (th!=NULL) {
	    rc=th->uid;last=0;
	    if (user(rc)->instate!=STD_NOUSE)
	    {
	       if (user(rc)->parent != 0) l='^'; else { l='*';last=1; }
	       if (user(rc)->sysmsg == 0) l='+';
	       if (*user(rc)->host==0) l=' '; else last=0;
	       if(last==1)
      	           ap_snprintf(ircbuf,sizeof(ircbuf),lngtxt(548),me,ircnick,irchost,me,l,user(rc)->login,user(rc)->nick,user(rc)->network,user(rc)->server,user(rc)->user,user(rc)->last);
	       else	 
      	           ap_snprintf(ircbuf,sizeof(ircbuf),lngtxt(549),me,ircnick,irchost,me,l,user(rc)->login,user(rc)->nick,user(rc)->network,user(rc)->server,user(rc)->user);
	       broadcast(0);						    
	    }
	    th=th->next;
	}
	return 0x0;	
    }
    pcontext;
    if (ifcommand(lngtxt(550)))
    {
	lh=linknode;	
	while (lh!=NULL)
	{	
	    rc=lh->uid;
	    l=' ';
	    if (datalink(rc)->type!=0)
	    {
		if (datalink(rc)->type==LI_LINK) 
		{
		    pt=o;
		    if (datalink(rc)->outstate==STD_CONN) l='*';
		}
		if (datalink(rc)->type==LI_ALLOW) 
		{
		    if (datalink(rc)->instate==STD_CONN) l='*';
		    pt=i;
		}
		if (datalink(rc)->type==LI_RELAY) { pt=r; l='*';}
		ap_snprintf(ircbuf,sizeof(ircbuf),lngtxt(551),me,ircnick,irchost,me,l,rc,pt,datalink(rc)->iam,datalink(rc)->host,datalink(rc)->port); 
		broadcast(0);
	    }    
	    lh=lh->next;
	}
	return 0x0;
    }
    pcontext;
#ifdef PARTYCHANNEL
    if (ifcommand(lngtxt(552)))
    {
	strmncpy(partytopic,irccontent,sizeof(partytopic));
	th=usernode;
	while (th!=NULL) {
	    rc=th->uid;
	    if (user(rc)->instate==STD_CONN && user(rc)->parent==0)
	    {
	       ap_snprintf(buf1,sizeof(buf1),"%s%s%s",lngtxt(553),PARTYCHAN,lngtxt(554));
  	       ssnprintf(user(rc)->insock,buf1,
	                       ircnick,irchost,ircnick,irchost,irccontent);
	    }
	    th=th->next;
	}
    }
#endif
#ifdef INTNET
    if (ifcommand(lngtxt(555)))
    {
	pt=strchr(ircbuf,'\r');
	if(pt==NULL) pt=strchr(ircbuf,'\n');
	if(pt!=NULL) *pt=0;
	strmncpy(ircbuf,rtrim(irccontent),sizeof(ircbuf));
	internalinbound(0,nlink);
    }
#endif
    pcontext;
    return 0x0;
}
Esempio n. 27
0
/*
 * Make a password record from the given information.  A zero return
 * indicates success; failure means that the output buffer contains an
 * error message instead.
 */
static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
		    int alg)
{
    char *pw;
    char cpw[120];
    char pwin[MAX_STRING_LEN];
    char pwv[MAX_STRING_LEN];
    char salt[9];

    if (passwd != NULL) {
	pw = passwd;
    }
    else {
#ifdef TPF
        fprintf(stderr, "Invalid entry. The -b option is required on TPF.\n");
        return usage();
#else
	if (ap_getpass("New password: "******"password too long (>%lu)",
			(unsigned long) (sizeof(pwin) - 1));
	    return ERR_OVERFLOW;
	}
	ap_getpass("Re-type new password: "******"password verification error", (rlen - 1));
	    return ERR_PWMISMATCH;
	}
	pw = pwin;
        memset(pwv, '\0', sizeof(pwin));
#endif /* TPF */
    }
    switch (alg) {

    case ALG_APSHA:
	/* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
 	ap_sha1_base64(pw,strlen(pw),cpw);
	break;

    case ALG_APMD5: 
        (void) srand((int) time((time_t *) NULL));
        ap_to64(&salt[0], rand(), 8);
        salt[8] = '\0';

	ap_MD5Encode((const unsigned char *)pw, (const unsigned char *)salt,
		     cpw, sizeof(cpw));
	break;

    case ALG_PLAIN:
	/* XXX this len limitation is not in sync with any HTTPd len. */
	ap_cpystrn(cpw,pw,sizeof(cpw));
	break;

    case ALG_CRYPT:
    default:
        (void) srand((int) time((time_t *) NULL));
        ap_to64(&salt[0], rand(), 8);
        salt[8] = '\0';

	ap_cpystrn(cpw, (char *)crypt(pw, salt), sizeof(cpw) - 1);
	break;
    }
    memset(pw, '\0', strlen(pw));

    /*
     * Check to see if the buffer is large enough to hold the username,
     * hash, and delimiters.
     */
    if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
	ap_cpystrn(record, "resultant record too long", (rlen - 1));
	return ERR_OVERFLOW;
    }
    strcpy(record, user);
    strcat(record, ":");
    strcat(record, cpw);
    return 0;
}