コード例 #1
0
ファイル: napt.cpp プロジェクト: cdaffara/symbiandump-os2
void CProtocolNapt::NetworkAttachedL()
	/**
	* The TCP/IP stack has been attached to this plugin.
	*
	* The CProtocolPosthook impelements the basic BindL/BindToL and Unbind
	* processing. The NetworkAttached is called when the TCP/IP
	* is connected with this protocol module.
	*
	* This function installs a hook for forwarded packets. The function
	* ApplyL will be called for each received packet that enters the
	* forward path (before actual forwarding decision).
	*
	* Could also install any other hooks to pull packets.
	*/
	{
	//Read Timer Configuration Parameters
	ReadConfigurationFile();
			
	NetworkService()->BindL(this, BindForwardHook());
	
	//Binding Inbound hook as hook all. This will take packets from all the interfaces
	//and translate only thise which are required.This seperate class optimise RAM usage. 
	//and implemented to avoid usage of heavy calls like IsForMeAddress.
	NetworkService()->BindL((CProtocolBase*)iProtInbound, BindHookAll());

	iManager = NetworkService()->Interfacer();

	}
コード例 #2
0
/*
Name: main
Description: this is the main entry point of the application. It will just call other functions to do the activity
Parameters: argc - Argument count - It will have only 1 - application name
			argv - values of the argument passed - it will have only application name
ReturnValue: 0 for success else error codes
*/
int main(int argc, char** argv)
{
	int nReturnValue = 0;
	char szMessage[1024] = { '\0' };

	printf("\nBHS:INFO:Started BASIC HTTP SERVER.....\n");
	printf_s("\nBHS:INFO:Started reading server configuraiton file\n");
	nReturnValue = ConfigFileParserInitialization();
	if (nReturnValue != 0)
	{
		printf_s("\nBHS:ERROR:Initialization of configuraition file reading failed with error:%d\n", nReturnValue);
		return nReturnValue;
	}
	nReturnValue = ReadConfigurationFile();
	if (nReturnValue != 0)
	{
		printf_s("\nBHS:ERROR:Error in reading configuraiton file = %d\n", nReturnValue);
		return nReturnValue;
	}
	nReturnValue = InitializeLogger();
	//printf("\nBHS:INFO:Initializing Socket......\n");
	if (nReturnValue != 0)
	{
		printf("\nBHS:ERROR:Initialization of logger failed... ending the server: %d\n", nReturnValue);
		//sprintf_s(szMessage, 1024, "Initialization of logger failed... ending the server: %d\n", nReturnValue);
		//LogMessage(LOG_ERROR, szMessage);
		UninitializeConfigurationParameters();
		return nReturnValue;
	}

	nReturnValue = InitializeSocket();
	if (nReturnValue != 0)
	{
		//printf_s("BHS:ERROR:Error has occured during initialization of socket\n");
		sprintf_s(szMessage, 1024, "BHS:ERROR:Error has occured during initialization of socket %d", nReturnValue);
		LogMessage(LOG_ERROR, szMessage);
	}
	else
	{
		//printf("\nBHS:INFO:Finished Socket initialization......\n");
		//printf("\nBHS:INFO:Started listening for client socket connection.......\n");
		nReturnValue = ListenForClientConnection();
		if (nReturnValue != 0)
		{
			printf_s("BHS:ERROR:ERROR has occurred during listening to client connection\n");
		}
	}

	printf_s("\nBHS:INFO:Uninitializing the parameters configured after reading configuration files\n");
	nReturnValue = UninitializeConfigurationParameters();
	if (nReturnValue != 0)
	{
		printf_s("\nBHS:ERROR:error during uninitializing the parameters: %d\n", nReturnValue);
	}
	printf("\nBHS:INFO:Exiting BASIC HTTP SERVER.......\n");

	nReturnValue = UninitializeLogger();

	return nReturnValue;
}
コード例 #3
0
ファイル: Makescan.c プロジェクト: greggman/elibs
/********************************* M A I N ********************************/
int main (
	int argc,
	char **argv
) {
	char		**newargs = NULL;
	LST_LIST	*configlist;
	ConfigType	*config;
	int  		 status = TRUE;

	printf ("MakeScan (c) Echidna 1990\n");

	if (!(argc == 2 && argv[1][0] == '?' && argv[1][1] == '\0')) {
		newargs = argparse (argc, argv, Template);
	}
	if (!newargs) {
		if (GlobalErrMsg) {
			printf ("%s\n", GlobalErrMsg);
		}
		printarghelp (Usage, Template);
	} else {
		DebugSwitch = (int  )((long)newargs[ARG_DEBUG]);
		if ((configlist = ReadConfigurationFile (newargs[ARG_CONFIG]))) {
			if (DebugSwitch) {
				PrintConfigList (configlist);
			}
			if (newargs[ARG_RULE]) {
				strupr (newargs[ARG_RULE]);
				if (!(config = (ConfigType*)LST_FindName (configlist, newargs[ARG_RULE]))) {
					SetGlobalErr (ERR_GENERIC);
					GEprintf1 ("No such rule '%s'", newargs[ARG_RULE]);
					status = FALSE;
				}
			} else {
				config = (ConfigType*)LST_Head (configlist);
			}
			if (status) {
				if (!CreateFiles (config, newargs[ARG_MAKEFILE])) {
					status = FALSE;
				}
			}
		} else {
			status = FALSE;
		}

		if (GlobalErr) {
			printf ("%s\n", GlobalErrMsg);
			status = FALSE;
		}
	}
	return (status ? 0 : 20);
}
コード例 #4
0
int CDisplaySettingsList::ReadConfigurationFile( const char *path )
{
std::ifstream stream;

stream.open(path);

if ( stream.is_open() )
	{
	ReadConfigurationFile( stream );
	stream.close();

	return true;	
	}

return false;
}
コード例 #5
0
ファイル: IniFile.c プロジェクト: BackupTheBerlios/tap-svn
void LoadConfiguration( void )
{
	if ( !ReadConfigurationFile() )
	{
		unitModelType = TF5800;

		mainActivationKey = RKEY_Recall;
		schMainPerformSearchMode = SCH_CONFIG_SEARCH_PERIOD_TEN_MINS;
		schMainPerformSearchTime = 0;
		FirmwareCallsEnabled = FALSE;
		schMainTRCEnabled = TRUE;
		schMainPerformSearchDays = 14;
		schMainDateFormat = 0;
		schMainTimeFormat = 0;
		keyboardLanguage = 0;
		schMainConflictOption = 0;

		SaveConfigurationToFile();
	}
}
コード例 #6
0
ファイル: test-doc.c プロジェクト: metux/wwwoffle
int main(int argc,char **argv)
{
 URL *Url;
 URL **list,*refresh;
 int j;

 if(argc==1)
   {fprintf(stderr,"usage: test-doc URL < contents-of-url\n");return(1);}

 StderrLevel=ExtraDebug;

 InitErrorHandler("test-doc",0,1);

 InitConfigurationFile("./wwwoffle.conf");

 init_io(STDERR_FILENO);

 if(ReadConfigurationFile(STDERR_FILENO))
    PrintMessage(Fatal,"Error in configuration file 'wwwoffle.conf'.");

 finish_io(STDERR_FILENO);

 Url=SplitURL(argv[1]);

 init_io(0);

 ParseDocument(0,Url,1);

 if((refresh=GetReference(RefMetaRefresh)))
    printf("Refresh = %s\n",refresh->file);

 if((list=GetReferences(RefStyleSheet)))
    for(j=0;list[j];j++)
       printf("StyleSheet = %s\n",list[j]->file);

 if((list=GetReferences(RefImage)))
    for(j=0;list[j];j++)
       printf("Image = %s\n",list[j]->file);

 if((list=GetReferences(RefFrame)))
    for(j=0;list[j];j++)
       printf("Frame = %s\n",list[j]->file);

 if((list=GetReferences(RefScript)))
    for(j=0;list[j];j++)
       printf("Script = %s\n",list[j]->file);

 if((list=GetReferences(RefObject)))
    for(j=0;list[j];j++)
       printf("Object = %s\n",list[j]->file);

 if((list=GetReferences(RefInlineObject)))
    for(j=0;list[j];j++)
       printf("InlineObject = %s\n",list[j]->file);

 if((list=GetReferences(RefLink)))
    for(j=0;list[j];j++)
       printf("Link = %s\n",list[j]->file);

 FreeURL(Url);

 finish_io(0);

 return(0);
}
コード例 #7
0
// MainFrame::MainFrame(const wxString& title, int argc, wxChar* argv[])
//MainFrame::MainFrame(const wxString& title, int argc, char** argv)
MainFrame::MainFrame(const wxString& title, int argc, char* argv[])
:wxFrame(NULL, -1, title, wxPoint(0,0), wxSize(1000,1000)),
    m_nTimer(this, ID_TIMER),
    isTrackingFinished(true)
{

    // read configuration file
    ReadConfigurationFile(argc,argv);

    // set up imagesourceEngine and tracking engine
    SetupInputAndTracker();

    wxGetApp().m_pMainFrame = this;

    // splitter the Panel to controlPanel and rightPanel
    wxSplitterWindow* splittermain = new wxSplitterWindow(this, wxID_ANY);
    splittermain->SetSashGravity(0);
    splittermain->SetMinimumPaneSize(210);
    m_pControlPanel = new controlPanel(splittermain);
    wxPanel* rightPanel = new wxPanel(splittermain);
    splittermain->SplitVertically(m_pControlPanel, rightPanel);
    splittermain->SetSashPosition(200);

    wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
    sizer->Add(splittermain, 1, wxEXPAND, 0);
    this->SetSizer(sizer);
    sizer->SetSizeHints(this);

    // split the rightPanel to glPanel and imagePanel
    wxSplitterWindow* splitterRenderImage = new wxSplitterWindow(rightPanel, wxID_ANY);
    splitterRenderImage->SetSashGravity(0.5);

    wxBoxSizer* rightSizer = new wxBoxSizer(wxVERTICAL);
    rightSizer->Add(splitterRenderImage,1,wxEXPAND);
    rightPanel->SetSizer(rightSizer);

    wxPanel* glPanel = new wxPanel(splitterRenderImage);
    wxPanel* imagePanel = new wxPanel(splitterRenderImage);
    splitterRenderImage->SplitVertically(glPanel, imagePanel);

    // do something on glPanel
    int args[] = {WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 16, 0};
    m_pGLPane = new BasicGLPane(glPanel, args);
    m_pGLPane->setImageHeight(m_nHeight);
    m_pGLPane->setImageWidth(m_nWidth);
    m_pGLPane->setIntrinsicMatrix(KK);
    m_pGLPane->setProjectionMatrix();

    // update the opengl panel pointer in control panel
    m_pControlPanel->m_pGLPane = m_pGLPane;

    wxBoxSizer* glSizer = new wxBoxSizer(wxVERTICAL);
    //wxBoxSizer* glSizer = new wxBoxSizer(wxHORIZONTAL);
    glSizer->Add(m_pGLPane,1,wxEXPAND);
    glPanel->SetSizer(glSizer);

    // splitter the imagePanel vertically to inputImagePanel and overlayPanel
    wxSplitterWindow* splitterImage = new wxSplitterWindow(imagePanel, wxID_ANY);
    splitterImage->SetSashGravity(0.5);
    wxPanel* inputImagePanel = new wxPanel(splitterImage);
    wxPanel* overlayPanel = new wxPanel(splitterImage);
    splitterImage->SplitHorizontally(inputImagePanel, overlayPanel);
    // splitterImage->SplitVertically(inputImagePanel, overlayPanel);

    // do something on imagePanel
    // m_pOverlayPane = new wxPanel(inputImagePanel);
    // m_pImagePane = new wxPanel(overlayPanel);
    m_pImagePane = new wxImagePanel(inputImagePanel,m_pColorImageRGB,m_nWidth,m_nHeight, false);
    m_pOverlayPane = new wxImagePanel(overlayPanel,m_pColorImageRGB,m_nWidth,m_nHeight, true);

    m_pOverlayPane->setMainFrame(this);
    m_pImagePane->setMainFrame(this);
    m_pOverlayPane->setNumPnts(m_nWidth*m_nHeight*shapeLoadingSettings.shapeSamplingScale*
        shapeLoadingSettings.shapeSamplingScale);
    m_pImagePane->setNumPnts(m_nWidth*m_nHeight*shapeLoadingSettings.shapeSamplingScale*
        shapeLoadingSettings.shapeSamplingScale);

    // wxBoxSizer* imagePaneSizer = new wxBoxSizer(wxHORIZONTAL);
    // wxBoxSizer* OverlayPaneSizer = new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer* imagePaneSizer = new wxBoxSizer(wxVERTICAL);
    wxBoxSizer* OverlayPaneSizer = new wxBoxSizer(wxVERTICAL);
    imagePaneSizer->Add(m_pImagePane,1,wxEXPAND,0);
    OverlayPaneSizer->Add(m_pOverlayPane,1,wxEXPAND,0);
    inputImagePanel->SetSizer(imagePaneSizer);
    overlayPanel->SetSizer(OverlayPaneSizer);

    // wxBoxSizer* imageSizer = new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer* imageSizer = new wxBoxSizer(wxVERTICAL);
    imageSizer->Add(splitterImage, 1, wxEXPAND);
    imagePanel->SetSizer(imageSizer);

    if(trackerSettings.showWindow)
    {
        this->SetAutoLayout(true);
        this->Show(true);
        this->Maximize(true);
    }
    else
    {
        // wxCommandEvent dummyEvent;
        // m_pControlPanel->ProcessWholeSequence(dummyEvent);
        cout << "not showing window " << endl;
        while(m_nCurrentFrame <= m_NumTrackingFrames)
        {
            //m_nCurrentFrame++;
            m_nCurrentFrame += m_nFrameStep;
            ProcessOneFrame(m_nCurrentFrame);
        }
    }
}
コード例 #8
0
ファイル: wwwoffled.c プロジェクト: metux/wwwoffle
int main(int argc, char** argv)
{
 int i;
 int err;
 struct stat buf;
 int uid,gid;

 /* Parse the command line options */

 for(i=1;i<argc;i++)
   {
    if(!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help"))
       usage(1);

    if(!strcmp(argv[i],"--version"))
       usage(2);

    if(!strcmp(argv[i],"-d"))
      {
       detached=0;

       if(i<(argc-1) && isdigit(argv[i+1][0]))
         {
          StderrLevel=Fatal+1-atoi(argv[++i]);

          if(StderrLevel<0 || StderrLevel>Fatal)
            {fprintf(stderr,"wwwoffled: The '-d' option requires a number between 0 and %d.\n",Fatal+1); exit(1);}
         }

       continue;
      }

    if(!strcmp(argv[i],"-l"))
      {
       if(++i>=argc)
         {fprintf(stderr,"wwwoffled: The '-l' option requires a filename.\n"); exit(1);}
       if(argv[i][0]!='/')
         {fprintf(stderr,"wwwoffled: The '-l' option requires an absolute pathname.\n"); exit(1);}

       log_file=argv[i];
       continue;
      }

    if(!strcmp(argv[i],"-p"))
      {
       print_pid=1;
       continue;
      }

    if(!strcmp(argv[i],"-f"))
      {
       nofork=1;
       detached=0;
       continue;
      }

    if(!strcmp(argv[i],"-c"))
      {
       if(++i>=argc)
         {fprintf(stderr,"wwwoffled: The '-c' option requires a filename.\n"); exit(1);}

       config_file=argv[i];
       continue;
      }

    fprintf(stderr,"wwwoffled: Unknown option '%s'.\n",argv[i]); exit(1);
   }

 /* Combination options */

 if(log_file)
   {
    if(nofork)
       log_file=NULL;           /* -f overrides -l */
    else
       detached=1;              /* -l overrides -d */

    if(StderrLevel==-1)
       StderrLevel=Inform;      /* -l sets log level if no -d */
   }

 /* Initialise things. */

 for(i=0;i<MAX_FETCH_SERVERS;i++)
    fetch_pids[i]=0;

 for(i=0;i<MAX_SERVERS;i++)
    server_pids[i]=0;

 if(log_file)
    OpenErrorLog(log_file);

 InitErrorHandler("wwwoffled",0,1); /* use stderr and not syslog to start with. */

 /* Read the configuration file. */

 InitConfigurationFile(config_file);

 init_io(STDERR_FILENO);

 if(ReadConfigurationFile(STDERR_FILENO))
    PrintMessage(Fatal,"Error in configuration file '%s'.",ConfigurationFileName());

 finish_io(STDERR_FILENO);

 InitErrorHandler("wwwoffled",ConfigInteger(UseSyslog),1); /* enable syslog if requested. */

 /* Print a startup message. */

#if USE_IPV6
#define IPV6_STRING "with ipv6"
#else
#define IPV6_STRING "without ipv6"
#endif

#define ZLIB_STRING "with zlib"

#define GNUTLS_STRING "with gnutls"

 PrintMessage(Important,"WWWOFFLE Demon Version %s (%s,%s,%s) started.",WWWOFFLE_VERSION,IPV6_STRING,ZLIB_STRING,GNUTLS_STRING);
 PrintMessage(Inform,"WWWOFFLE Read Configuration File '%s'.",ConfigurationFileName());

 /* Change the user and group. */

 gid=ConfigInteger(WWWOFFLE_Gid);
 uid=ConfigInteger(WWWOFFLE_Uid);

 if(uid!=-1)
    seteuid(0);

 if(log_file && (uid!=-1 || gid!=-1))
    chown(log_file,(uid_t)uid,(gid_t)gid);

 if(gid!=-1)
   {
#if HAVE_SETGROUPS
    if(getuid()==0 || geteuid()==0)
       if(setgroups(0,NULL)<0)
          PrintMessage(Fatal,"Cannot clear supplementary group list [%!s].");
#endif

#if HAVE_SETRESGID
    if(setresgid((gid_t)gid,(gid_t)gid,(gid_t)gid)<0)
       PrintMessage(Fatal,"Cannot set real/effective/saved group id to %d [%!s].",gid);
#else
    if(geteuid()==0)
      {
       if(setgid((gid_t)gid)<0)
          PrintMessage(Fatal,"Cannot set group id to %d [%!s].",gid);
      }
    else
      {
#if HAVE_SETREGID
       if(setregid(getegid(),(gid_t)gid)<0)
          PrintMessage(Fatal,"Cannot set effective group id to %d [%!s].",gid);
       if(setregid((gid_t)gid,(gid_t)~1)<0)
          PrintMessage(Fatal,"Cannot set real group id to %d [%!s].",gid);
#else
       PrintMessage(Fatal,"Must be root to totally change group id.");
#endif
      }
#endif
   }

 if(uid!=-1)
   {
#if HAVE_SETRESUID
    if(setresuid((uid_t)uid,(uid_t)uid,(uid_t)uid)<0)
       PrintMessage(Fatal,"Cannot set real/effective/saved user id to %d [%!s].",uid);
#else
    if(geteuid()==0)
      {
       if(setuid((uid_t)uid)<0)
          PrintMessage(Fatal,"Cannot set user id to %d [%!s].",uid);
      }
    else
      {
#if HAVE_SETREUID
       if(setreuid(geteuid(),(uid_t)uid)<0)
          PrintMessage(Fatal,"Cannot set effective user id to %d [%!s].",uid);
       if(setreuid((uid_t)uid,(uid_t)~1)<0)
          PrintMessage(Fatal,"Cannot set real user id to %d [%!s].",uid);
#else
       PrintMessage(Fatal,"Must be root to totally change user id.");
#endif
      }
#endif
   }

 if(uid!=-1 || gid!=-1)
    PrintMessage(Inform,"Running with uid=%d, gid=%d.",geteuid(),getegid());

 if(geteuid()==0 || getegid()==0)
    PrintMessage(Warning,"Running with root user or group privileges is not recommended.");

 /* Create, Change to and open the spool directory. */

 umask(0);

 if(stat(ConfigString(SpoolDir),&buf))
   {
    err=mkdir(ConfigString(SpoolDir),(mode_t)ConfigInteger(DirPerm));
    if(err==-1 && errno!=EEXIST)
       PrintMessage(Fatal,"Cannot create spool directory %s [%!s].",ConfigString(SpoolDir));
    stat(ConfigString(SpoolDir),&buf);
   }

 if(!S_ISDIR(buf.st_mode))
    PrintMessage(Fatal,"The spool directory %s is not a directory.",SpoolDir);

 err=ChangeToSpoolDir(ConfigString(SpoolDir));
 if(err==-1)
    PrintMessage(Fatal,"Cannot change to spool directory %s [%!s].",ConfigString(SpoolDir));

 /* Bind the HTTP proxy socket(s). */

#if USE_IPV6
 if(ConfigString(Bind_IPv6))
   {
    http_fd[1]=OpenServerSocket(ConfigString(Bind_IPv6),ConfigInteger(HTTP_Port));
    if(http_fd[1]==-1)
       PrintMessage(Fatal,"Cannot create HTTP IPv6 server socket.");
   }
#endif

 if(ConfigString(Bind_IPv4))
   {
    http_fd[0]=OpenServerSocket(ConfigString(Bind_IPv4),ConfigInteger(HTTP_Port));
    if(http_fd[0]==-1)
      {
#if USE_IPV6
       if(http_fd[1]!=-1 && /* PS 2003-01-13 redundant? If IPv6 is listening to 0 then it doesn't matter what address IPv4 is listening to... (at least on linux?) */
                            /* ConfigString(Bind_IPv4) && !strcmp(ConfigString(Bind_IPv4),"0.0.0.0") && */
                            ConfigString(Bind_IPv6) && !strcmp(ConfigString(Bind_IPv6),"[0:0:0:0:0:0:0:0]"))
          PrintMessage(Warning,"Cannot create HTTP IPv4 server socket (but the IPv6 one might accept IPv4 connections).");
       else
          PrintMessage(Fatal,"Cannot create HTTP IPv4 server socket.");
#else
       PrintMessage(Fatal,"Cannot create HTTP server socket.");
#endif
      }
   }

 if(http_fd[0]==-1 && http_fd[1]==-1)
   {
#if USE_IPV6
    PrintMessage(Fatal,"The IPv4 and IPv6 HTTP sockets were not bound; are they disabled in the config file?");
#else
    PrintMessage(Fatal,"The HTTP socket was not bound; is it disabled in the config file?");
#endif
   }

 /* Bind the HTTPS socket(s). */

 if(LoadRootCredentials())
   {
    PrintMessage(Warning,"Failed to read (or create if needed) the WWWOFFLE root certificates.");
   }

 if(LoadTrustedCertificates())
   {
    PrintMessage(Warning,"Failed to read in any trusted certificates.");
   }

#if USE_IPV6
 if(ConfigString(Bind_IPv6))
   {
    https_fd[1]=OpenServerSocket(ConfigString(Bind_IPv6),ConfigInteger(HTTPS_Port));
    if(https_fd[1]==-1)
       PrintMessage(Fatal,"Cannot create HTTPS IPv6 server socket.");
   }
#endif

 if(ConfigString(Bind_IPv4))
   {
    https_fd[0]=OpenServerSocket(ConfigString(Bind_IPv4),ConfigInteger(HTTPS_Port));
    if(https_fd[0]==-1)
      {
#if USE_IPV6
       if(https_fd[1]!=-1 && ConfigString(Bind_IPv4) && !strcmp(ConfigString(Bind_IPv4),"0.0.0.0") &&
                             ConfigString(Bind_IPv6) && !strcmp(ConfigString(Bind_IPv6),"[0:0:0:0:0:0:0:0]"))
          PrintMessage(Warning,"Cannot create HTTPS IPv4 server socket (but the IPv6 one might accept IPv4 connections).");
       else
          PrintMessage(Fatal,"Cannot create HTTPS IPv4 server socket.");
#else
       PrintMessage(Fatal,"Cannot create HTTPS server socket.");
#endif
      }
   }

 if(https_fd[0]==-1 && https_fd[1]==-1)
   {
#if USE_IPV6
    PrintMessage(Fatal,"The IPv4 and IPv6 HTTPS sockets were not bound; are they disabled in the config file?");
#else
    PrintMessage(Fatal,"The HTTPS socket was not bound; is it disabled in the config file?");
#endif
   }

 /* Bind the WWWOFFLE control socket(s). */

#if USE_IPV6
 if(ConfigString(Bind_IPv6))
   {
    wwwoffle_fd[1]=OpenServerSocket(ConfigString(Bind_IPv6),ConfigInteger(WWWOFFLE_Port));
    if(wwwoffle_fd[1]==-1)
       PrintMessage(Fatal,"Cannot create WWWOFFLE IPv6 server socket.");
   }
#endif

 if(ConfigString(Bind_IPv4))
   {
    wwwoffle_fd[0]=OpenServerSocket(ConfigString(Bind_IPv4),ConfigInteger(WWWOFFLE_Port));
    if(wwwoffle_fd[0]==-1)
      {
#if USE_IPV6
       if(wwwoffle_fd[1]!=-1 && ConfigString(Bind_IPv4) && !strcmp(ConfigString(Bind_IPv4),"0.0.0.0") &&
                                ConfigString(Bind_IPv6) && !strcmp(ConfigString(Bind_IPv6),"[0:0:0:0:0:0:0:0]")) {
          PrintMessage(Warning,"Cannot create WWWOFFLE IPv4 server socket (but the IPv6 one might accept IPv4 connections).");
          PrintMessage(Warning,"Consider adding \"bind-ipv4 = none\" to wwwoffle.conf if using IPv6.");
       }
       else
          PrintMessage(Fatal,"Cannot create WWWOFFLE IPv4 server socket.");
#else
       PrintMessage(Fatal,"Cannot create WWWOFFLE server socket.");
#endif
      }
   }

 if(wwwoffle_fd[0]==-1 && wwwoffle_fd[1]==-1)
   {
#if USE_IPV6
    PrintMessage(Fatal,"The IPv4 and IPv6 WWWOFFLE sockets were not bound; are they disabled in the config file?");
#else
    PrintMessage(Fatal,"The WWWOFFLE socket was not bound; is it disabled in the config file?");
#endif
   }

 /* Detach from terminal */

 if(detached)
   {
    demoninit();

    PrintMessage(Important,"Detached from terminal and changed pid to %d.",getpid());

    if(log_file)
       InitErrorHandler("wwwoffled",-1,-1); /* pid changes after detaching, keep stderr as was. */
    else
       InitErrorHandler("wwwoffled",-1, 0); /* pid changes after detaching, disable stderr. */

    if(!log_file)
       close(STDERR_FILENO);
   }

 close(STDIN_FILENO);
 close(STDOUT_FILENO);

 install_sighandlers();

 max_servers=ConfigInteger(MaxServers);
 max_fetch_servers=ConfigInteger(MaxFetchServers);

 /* Loop around waiting for connections. */

 PrintMessage(Inform,"WWWOFFLE Ready to accept connections.");

 do
   {
    struct timeval tv;
    fd_set readfd;
    int nfds=0,nfd=0;

    FD_ZERO(&readfd);

#if USE_IPV6
       for(nfd=0;nfd<=1;nfd++)
         {
#endif
          if(http_fd[nfd]>=nfds)
             nfds=http_fd[nfd]+1;
          if(https_fd[nfd]>=nfds)
             nfds=https_fd[nfd]+1;
          if(wwwoffle_fd[nfd]>=nfds)
             nfds=wwwoffle_fd[nfd]+1;

          if(n_servers<max_servers)
            {
             if(http_fd[nfd]!=-1)
                FD_SET(http_fd[nfd],&readfd);
             if(https_fd[nfd]!=-1)
                FD_SET(https_fd[nfd],&readfd);
            }

          if(wwwoffle_fd[nfd]!=-1)
             FD_SET(wwwoffle_fd[nfd],&readfd);
#if USE_IPV6
         }
#endif

    tv.tv_sec=10;
    tv.tv_usec=0;

    if(select(nfds,&readfd,NULL,NULL,&tv)!=-1)
      {
#if USE_IPV6
       for(nfd=0;nfd<=1;nfd++)
         {
#endif
          if(wwwoffle_fd[nfd]!=-1 && FD_ISSET(wwwoffle_fd[nfd],&readfd))
            {
             char *host,*ip;
             int port,client;

             client=AcceptConnect(wwwoffle_fd[nfd]);

             if(client>=0)
               {
                init_io(client);
                configure_io_timeout(client,ConfigInteger(SocketTimeout),ConfigInteger(SocketTimeout));

                if(SocketRemoteName(client,&host,&ip,&port))
                  {
                   finish_io(client);
                   CloseSocket(client);
                  }
                else
                  {
                   char *canonical_ip=CanonicaliseHost(ip);

                   if(IsAllowedConnectHost(host) || IsAllowedConnectHost(canonical_ip))
                     {
                      PrintMessage(Important,"WWWOFFLE Connection from host %s (%s).",host,canonical_ip); /* Used in audit-usage.pl */

                      CommandConnect(client);

                      if(fetch_fd!=client)
                        {
                         finish_io(client);
                         CloseSocket(client);
                        }
                     }
                   else
                     {
                      PrintMessage(Warning,"WWWOFFLE Connection rejected from host %s (%s).",host,canonical_ip); /* Used in audit-usage.pl */
                      finish_io(client);
                      CloseSocket(client);
                     }

                   free(canonical_ip);
                  }
               }
            }

          if(http_fd[nfd]!=-1 && FD_ISSET(http_fd[nfd],&readfd))
            {
             char *host,*ip;
             int port,client;

             client=AcceptConnect(http_fd[nfd]);

             if(client>=0)
               {
                init_io(client);
                configure_io_timeout(client,ConfigInteger(SocketTimeout),ConfigInteger(SocketTimeout));

                if(!SocketRemoteName(client,&host,&ip,&port))
                  {
                   char *canonical_ip=CanonicaliseHost(ip);

                   if(IsAllowedConnectHost(host) || IsAllowedConnectHost(canonical_ip))
                     {
                      PrintMessage(Inform,"HTTP Proxy connection from host %s (%s).",host,canonical_ip); /* Used in audit-usage.pl */
                      ForkServer(client);
                     }
                   else
                      PrintMessage(Warning,"HTTP Proxy connection rejected from host %s (%s).",host,canonical_ip); /* Used in audit-usage.pl */

                   free(canonical_ip);
                  }

                if(nofork)
                   got_sigexit=1;

                if(!nofork)
                  {
                   finish_io(client);
                   CloseSocket(client);
                  }
               }
            }

          if(https_fd[nfd]!=-1 && FD_ISSET(https_fd[nfd],&readfd))
            {
             char *host,*ip;
             int port,client;

             client=AcceptConnect(https_fd[nfd]);

             if(client>=0)
               {
                init_io(client);
                configure_io_timeout(client,ConfigInteger(SocketTimeout),ConfigInteger(SocketTimeout));

                if(!SocketRemoteName(client,&host,&ip,&port))
                  {
                   char *canonical_ip=CanonicaliseHost(ip);

                   if(IsAllowedConnectHost(host) || IsAllowedConnectHost(canonical_ip))
                     {
                      PrintMessage(Inform,"HTTPS Proxy connection from host %s (%s).",host,canonical_ip); /* Used in audit-usage.pl */
                      ForkServer(client);
                     }
                   else
                      PrintMessage(Warning,"HTTPS Proxy connection rejected from host %s (%s).",host,canonical_ip); /* Used in audit-usage.pl */

                   free(canonical_ip);
                  }

                if(nofork)
                   got_sigexit=1;

                if(!nofork)
                  {
                   finish_io(client);
                   CloseSocket(client);
                  }
               }
            }

#if USE_IPV6
         }
#endif
      }

    if(got_sighup)
      {
       got_sighup=0;

       PrintMessage(Important,"SIGHUP signalled.");

       if(log_file)
         {
          PrintMessage(Important,"Closing and opening log file.");

          OpenErrorLog(log_file);
         }

       PrintMessage(Important,"WWWOFFLE Re-reading Configuration File.");

       if(ReadConfigurationFile(-1))
          PrintMessage(Warning,"Error in configuration file; keeping old values.");

       PrintMessage(Important,"WWWOFFLE Finished Re-reading Configuration File.");
      }

    if(got_sigchld)
      {
       int pid, status;
       int isserver=0;

       /* To avoid race conditions, reset the flag before fetching the status */

       got_sigchld=0;

       while((pid=waitpid(-1,&status,WNOHANG))>0)
         {
          int i;
          int exitval=0;

          if(WIFEXITED(status))
             exitval=WEXITSTATUS(status);
          else if(WIFSIGNALED(status))
             exitval=-WTERMSIG(status);

          if(purging)
             if(purge_pid==pid)
               {
                if(exitval>=0)
                   PrintMessage(Inform,"Purge process exited with status %d (pid=%d).",exitval,pid);
                else
                   PrintMessage(Important,"Purge process terminated by signal %d (pid=%d).",-exitval,pid);

                purging=0;
               }

          for(i=0;i<max_servers;i++)
             if(server_pids[i]==pid)
               {
                n_servers--;
                server_pids[i]=0;
                isserver=1;

                if(exitval>=0)
                   PrintMessage(Inform,"Child wwwoffles exited with status %d (pid=%d).",exitval,pid);
                else
                   PrintMessage(Important,"Child wwwoffles terminated by signal %d (pid=%d).",-exitval,pid);

                break;
               }

          /* Check if the child that terminated is one of the fetching wwwoffles */

          for(i=0;i<max_fetch_servers;i++)
             if(fetch_pids[i]==pid)
               {
                n_fetch_servers--;
                fetch_pids[i]=0;
                break;
               }

          if(exitval==3)
             fetching=0;

          if(exitval==4 && online!=0)
             fetching=1;

          if(online==0)
             fetching=0;
         }

       if(isserver)
          PrintMessage(Debug,"Currently running: %d servers total, %d fetchers.",n_servers,n_fetch_servers);
      }

    /* The select timed out or we got a signal. If we are currently fetching,
       start fetch servers to look for jobs in the spool directory. */

    while(fetching && n_fetch_servers<max_fetch_servers && n_servers<max_servers)
       ForkServer(fetch_fd);

    if(fetch_fd!=-1 && !fetching && n_fetch_servers==0)
      {
       write_string(fetch_fd,"WWWOFFLE No more to fetch.\n");

       finish_io(fetch_fd);
       CloseSocket(fetch_fd);
       fetch_fd=-1;

       PrintMessage(Important,"WWWOFFLE Fetch finished.");

       ForkRunModeScript(ConfigString(RunFetch),"fetch","stop",-1);
      }
   }
 while(!got_sigexit);

 /* Close down and exit. */

 /* These four sockets don't need finish_io() calling because they never
    had init_io() called, they are just bound to a port listening. */

 if(http_fd[0]!=-1) CloseSocket(http_fd[0]);
 if(http_fd[1]!=-1) CloseSocket(http_fd[1]);
 if(wwwoffle_fd[0]!=-1) CloseSocket(wwwoffle_fd[0]);
 if(wwwoffle_fd[1]!=-1) CloseSocket(wwwoffle_fd[1]);

 if(!nofork)
   {
    if(n_servers)
       PrintMessage(Important,"Exit signalled - waiting for %d child wwwoffles servers.",n_servers);
    else
       PrintMessage(Important,"Exit signalled.");
   }

 while(n_servers)
   {
    int i;
    int pid,status,exitval=0;

    while((pid=waitpid(-1,&status,0))>0)
      {
       if(WIFEXITED(status))
          exitval=WEXITSTATUS(status);
       else if(WIFSIGNALED(status))
          exitval=-WTERMSIG(status);

       for(i=0;i<max_servers;i++)
          if(server_pids[i]==pid)
            {
             n_servers--;
             server_pids[i]=0;

             if(exitval>=0)
                PrintMessage(Inform,"Child wwwoffles exited with status %d (pid=%d).",exitval,pid);
             else
                PrintMessage(Important,"Child wwwoffles terminated by signal %d (pid=%d).",-exitval,pid);

             break;
            }

       if(purging)
          if(purge_pid==pid)
            {
             if(exitval>=0)
                PrintMessage(Inform,"Purge process exited with status %d (pid=%d).",exitval,pid);
             else
                PrintMessage(Important,"Purge process terminated by signal %d (pid=%d).",-exitval,pid);

             purging=0;
            }
      }
   }

 PrintMessage(Important,"Exiting.");

 FinishConfigurationFile();

 FreeLoadedCredentials();

 return(0);
}