void main(int argc, char **argv) 
{

	bool matched  = false;
	if (argv[0]) {
		if (argv[1]) {
			if (!strcmp(argv[1], "install")) {
				removeService();
				installService(argv[2]);
				matched = true;
			}
			if (!strcmp(argv[1], "remove")) {
				removeService();
				matched = true;
			}
		}
	}
	if (matched) {
		return;
	}
	_chdir(argv[1]);

	SERVICE_TABLE_ENTRY ServiceTable[2];
	ServiceTable[0].lpServiceName = "Stream Transcoder V3";
	ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

	ServiceTable[1].lpServiceName = NULL;
	ServiceTable[1].lpServiceProc = NULL;
	// Start the control dispatcher thread for our service
	StartServiceCtrlDispatcher(ServiceTable);  
}
Beispiel #2
0
void Browser::resolverCallback(AvahiSServiceResolver *r,
                               AvahiIfIndex iface,
                               AvahiProtocol protocol,
                               AvahiResolverEvent event,
                               const char *name,
                               const char *type,
                               const char *domain,
                               const char *host_name,
                               const AvahiAddress *a,
                               uint16_t port,
                               AvahiStringList *txt,
                               AvahiLookupResultFlags flags,
                               void *userdata) noexcept {
    auto browser = static_cast<Browser*>(userdata);

    switch (event) {
    case AVAHI_RESOLVER_FOUND:
        printf("Resolved %s to %s\n", name, host_name);
        browser->updateService(name, host_name, a, port, txt);
        break;
    case AVAHI_RESOLVER_FAILURE:
        browser->removeService(name);
        break;
    }
}
Beispiel #3
0
void Browser::browserCallback(AvahiSServiceBrowser *b,
                              AvahiIfIndex iface,
                              AvahiProtocol protocol,
                              AvahiBrowserEvent event,
                              const char *name,
                              const char *type,
                              const char *domain,
                              AvahiLookupResultFlags flags,
                              void *userdata)  noexcept {
    auto browser = static_cast<Browser*>(userdata);

    switch (event) {
    case AVAHI_BROWSER_NEW:
        printf("Found %s of type %s in domain %s\n", name, type, domain);
        browser->addService(iface, protocol, name, type, domain);
        break;
    case AVAHI_BROWSER_REMOVE:
        printf("Removing %s of type %s in domain %s\n", name, type, domain);
        browser->removeService(name);
        break;
    case AVAHI_BROWSER_FAILURE:
        printf("Error: %s\n", avahi_strerror(avahi_server_errno(browser->server_.get())));
        break;
    default:
        break;
    }
}
void QDBusServiceWatcherPrivate::setConnection(const QStringList &s, const QDBusConnection &c, QDBusServiceWatcher::WatchMode wm)
{
    if (connection.isConnected()) {
        // remove older rules
        foreach (const QString &s, servicesWatched)
            removeService(s);
    }
 void init(QString serviceType)
 {
     delete browser;
     browser = new ZConfServiceBrowser(q);
     type = serviceType;
     QObject::connect(browser, SIGNAL(serviceEntryAdded(QString)), q, SLOT(addService(QString)));
     QObject::connect(browser, SIGNAL(serviceEntryRemoved(QString)), q, SLOT(removeService(QString)));
     q->clear();
     browser->browse(type);
 }
Beispiel #6
0
static bool process(cchar *operation)
{
    bool    rc;

    rc = 1;

    if (smatch(operation, "install")) {
        rc = installService(app->serviceArgs);

    } else if (smatch(operation, "uninstall")) {
        rc = removeService(1);

    } else if (smatch(operation, "enable")) {
        rc = enableService(1);

    } else if (smatch(operation, "disable")) {
        rc = enableService(0);

    } else if (smatch(operation, "start")) {
        rc = startService();

    } else if (smatch(operation, "stop")) {
        rc = removeService(0);

    } else if (smatch(operation, "reload")) {
        rc = process("restart");

    } else if (smatch(operation, "restart")) {
        process("stop");
        return process("start");

    } else if (smatch(operation, "run")) {
        /*
            This thread will block if being started by SCM. While blocked, the serviceMain 
            will be called which becomes the effective main program. 
         */
        startDispatcher(serviceMain);
    }
    return rc;
}
int main (int argc, char *argv[]) 
{
    if (argc < 2)
    {
        printf (PACKAGE_STRING "\n\n"
                "Usage: icecastService [remove] | [install <path>]\n"
                "       icecastService -c icecast.xml\n\n");
        return -1;
    }
    if (!strcmp(argv[1], "install"))
    {
        if (argc > 2)
            installService(argv[2]);
        else
            printf ("install requires a path arg as well\n");
        Sleep (1000);
        return 0;
    }
    if (!strcmp(argv[1], "remove") || !strcmp(argv[1], "uninstall"))
    {
        removeService();
        return 0;
    }

    if (strcmp (argv[1], "-c") == 0)
        return run_server (argc, argv);

    if (_chdir(argv[1]) < 0)
    {
        char buffer [256];
        snprintf (buffer, sizeof(buffer), "Unable to change to directory %s", argv[1]);
        MessageBox (NULL, buffer, NULL, MB_SERVICE_NOTIFICATION);
        return -1;
    }

    SERVICE_TABLE_ENTRY ServiceTable[2];
    ServiceTable[0].lpServiceName = (char*)PACKAGE_STRING;
    ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

    ServiceTable[1].lpServiceName = NULL;
    ServiceTable[1].lpServiceProc = NULL;
    // Start the control dispatcher thread for our service
    if (StartServiceCtrlDispatcher (ServiceTable) == 0)
        MessageBox (NULL, "StartServiceCtrlDispatcher failed", NULL, MB_SERVICE_NOTIFICATION);
    return 0;
}
Beispiel #8
0
int main(int argc, char **argv) 
{
    if (argc < 2)
    {
        printf ("Usage:\n %s  remove\n %s  install path\n", argv[0], argv[0]);
        return 0;
    }
    if (!strcmp(argv[1], "install"))
    {
        if (argc > 2)
        {
            printf ("Installing service from %s\n", argv[2]);
            installService(argv[2]);
        }
        else
            printf ("install requires a path arg as well\n");
        Sleep (2000);
        return 0;
    }
    if (!strcmp(argv[1], "remove") || !strcmp(argv[1], "uninstall"))
    {
        printf ("removing service\n");
        removeService();
        Sleep (2000);
        return 0;
    }

    if (_chdir(argv[1]) < 0)
    {
        printf ("unable to change to directory %s\n", argv[1]);
        Sleep (2000);
        return 0;
    }

	SERVICE_TABLE_ENTRY ServiceTable[2];
	ServiceTable[0].lpServiceName = PACKAGE_STRING;
	ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

	ServiceTable[1].lpServiceName = NULL;
	ServiceTable[1].lpServiceProc = NULL;
	// Start the control dispatcher thread for our service
	StartServiceCtrlDispatcher(ServiceTable);  

    return 0;
}
Beispiel #9
0
int main(int argc, char **argv)
{
  AString strCommand(argv[1]);
  try
  {
    if (strCommand.equalsNoCase("install"))
    {
      if (installService())
        std::cout << "Service installed." << std::endl;
      else
        std::cout << "Service install failed." << std::endl;
    }
    else if (strCommand.equalsNoCase("remove"))
    {
      if (removeService())
        std::cout << "Service removed." << std::endl;
      else
        std::cout << "Service remove failed." << std::endl;
    }
    else
    {
      // When service dispatch action is requested this main() is called with no parameters
      // This connects the handler with service
      connectToServiceDispatch();
    }
  }
  catch(AException& ex)
  {
    AFILE_TRACER_DEBUG_MESSAGE((AString("main: ")+ex.what()).c_str(), NULL);
    std::cerr << ex.what() << std::endl;
  }
  catch(std::exception& ex)
  {
    AFILE_TRACER_DEBUG_MESSAGE((AString("main: ")+ex.what()).c_str(), NULL);
    std::cerr << ex.what() << std::endl;
  }
  catch(...)
  {
    AFILE_TRACER_DEBUG_MESSAGE("main: Unknown exception", NULL);
    std::cerr << "Unknown exception" << std::endl;
  }

  return 1;
}
///<summary> Remove the supplied service from the connection list and close it. </summary>
void removeConnection(POLYM_CONNECTION_INFO *connection_info)
{
	switch (connection_info->realm)
	{

	case POLY_REALM_SERVICE:
		// close a service control connection
		removeService(connection_info->connectionID);
		break;

	case POLY_REALM_PEER:
		// close a peer connection
		removePeer(connection_info->connectionID);
		break;

	default:
		break;
	}
}
void DNSSDNetworkBuilder::addServiceType( const QString& serviceType )
{
kDebug()<<serviceType<<mServiceBrowserTable.contains(serviceType);
    if( mServiceBrowserTable.contains(serviceType))
        return;

// kDebug()<<serviceType;
    DNSSD::ServiceBrowser* serviceBrowser = new DNSSD::ServiceBrowser( serviceType, true );
    connect( serviceBrowser, SIGNAL(serviceAdded(DNSSD::RemoteService::Ptr)),
            SLOT(addService(DNSSD::RemoteService::Ptr)) );
    connect( serviceBrowser, SIGNAL(serviceRemoved(DNSSD::RemoteService::Ptr)),
            SLOT(removeService(DNSSD::RemoteService::Ptr)) );

    if( mIsInit )
    {
        ++mNoOfInitServiceTypes;
        connect( serviceBrowser, SIGNAL(finished()), SLOT(onServiceBrowserFinished()) );
    }

    mServiceBrowserTable[serviceType] = serviceBrowser;
    serviceBrowser->startBrowse();
}
Beispiel #12
0
void main(int argc, char **argv)
{
	// Statup wx
	wxInitialize();

	wxFileName file = wxString::FromAscii(*argv++);
	file.MakeAbsolute();
	wxString executable = file.GetFullPath();

	if (argc < 3)
	{
		usage(executable);
		return;
	}

	wxString command;
	command = wxString::FromAscii(*argv++);

	if (command != wxT("DEBUG"))
	{
		serviceName = wxString::FromAscii(*argv++);
		argc -= 3;
	}
	else
		argc -= 2;

	if (command == wxT("INSTALL"))
	{
		wxString displayname = _("PostgreSQL Scheduling Agent - ") + serviceName;
		wxString args = wxT("RUN ") + serviceName;

		while (argc-- > 0)
		{
			if (argv[0][0] == '-')
			{
				switch (argv[0][1])
				{
					case 'u':
					{
						user = getArg(argc, argv);
						break;
					}
					case 'p':
					{
						password = getArg(argc, argv);
						break;
					}
					case 'd':
					{
						displayname = getArg(argc, argv);
						break;
					}
					default:
					{
						args += wxT(" ") + wxString::FromAscii(*argv);
						break;
					}
				}
			}
			else
			{
				args += wxT(" ") + wxString::FromAscii(*argv);
			}

			argv++;
		}

		bool rc = installService(serviceName, executable, args, displayname, user, password);
	}
	else if (command == wxT("REMOVE"))
	{
		bool rc = removeService(serviceName);
	}
	else if (command == wxT("DEBUG"))
	{
		setupForRun(argc, argv, true, executable);

		initService();
#if START_SUSPENDED
		continueService();
#endif

		WaitForSingleObject(threadHandle, INFINITE);
	}
	else if (command == wxT("RUN"))
	{
		wxString app = _("pgAgent Service");

		SERVICE_TABLE_ENTRY serviceTable[] =
		{ (LPWSTR)app.wc_str(), serviceMain, 0, 0};

		setupForRun(argc, argv, false, executable);

		if (!StartServiceCtrlDispatcher(serviceTable))
		{
			DWORD rc = GetLastError();
			if (rc)
			{
			}
		}
	}
	else
	{
		usage(executable);
	}

	return;
}
Beispiel #13
0
 void Session_Service::onServiceRemoved(const unsigned int &index, const std::string &service) {
   qiLogVerbose() << "Remote Service Removed:" << service << " #" << index;
   removeService(service);
 }
Beispiel #14
0
void SthenoCore::stopLocalService(UUIDPtr& sid, UUIDPtr& iid) throw (RuntimeException&, ServiceException&) {
    if (!isValid()) {
        throw RuntimeException(RuntimeException::INVALID_RUNTIME);
    }
    removeService(sid, iid);
}
/**
 * This function moves the instance object to the correct thread and invokes the init() function on the instance.
 * @param instance Pointer to the activated instance object.
 */
void ServerProtocolListenerBase::prepareInstance(ServerProtocolInstanceBase* instance, QThread* thread)
{
#ifndef Q_OS_WIN32
	if (qxt_d().serv->threadType() == Server::ProcessPerInstance)
	{
		QMetaObject::invokeMethod(instance, "deleteLater", Qt::QueuedConnection);
		QStringList args = qApp->arguments();
		int ret = fork();
		if (ret == -1)
		{
			qCritical() << "Failed to fork for incoming connection!" << strerror(errno);
			return;
		}
		if (ret == 0)
		{
			char** argv = new char*[5];
			argv[4] = NULL;

			argv[0] = new char[args.at(0).size()+1];
			memcpy(argv[0], qPrintable(args.at(0)), args.at(0).size());
			argv[0][args.at(0).size()] = NULL;

			QString argv1 = "FORK_PROCESS";
			argv[1] = new char[argv1.size()+1];
			memcpy(argv[1], qPrintable(argv1), argv1.size());
			argv[1][argv1.size()] = NULL;

			QString fd = QString("%1").arg(dup(instance->getProperty("descriptor").toInt()));
			argv[2] = new char[fd.size()+1];
			memcpy(argv[2], qPrintable(fd), fd.size());
			argv[2][fd.size()] = NULL;

			QString protocol = "tcp";
			argv[3] = new char[protocol.size()+1];
			memcpy(argv[3], qPrintable(protocol), protocol.size());
			argv[3][protocol.size()] = NULL;

			execvp(qPrintable(args.at(0)), argv);
			QFile file("/tmp/qtrpc_failure");
			file.open(QFile::WriteOnly | QFile::Truncate);
			file.write(qPrintable(QString("Failed to execv! %1 %2").arg(strerror(errno)).arg(errno)));
			file.close();
			qFatal(strerror(errno));
		}
		close(instance->getProperty("descriptor").toInt());
		return;
	}
#endif

	if (thread == 0)
		thread = qxt_d().serv->requestThread();
	instance->moveToThread(thread);
	switch (qxt_d().serv->threadType())
	{
		case Server::SingleThread:
			break;
		case Server::ThreadPool:
			if (instance == 0)
			{
				qCritical() << "A null instance was passed to prepareInstance!";
				return;
			}
			QObject::connect(instance, SIGNAL(destroyed()), qxt_d().serv, SLOT(removeService()), Qt::DirectConnection);
			break;
		case Server::ThreadPerInstance:
			if (instance == 0)
			{
				qCritical() << "A null instance was passed to prepareInstance!";
				thread->quit();
				return;
			}
			QObject::connect(instance, SIGNAL(destroyed()), thread, SLOT(quit()));
			break;
#ifndef Q_OS_WIN32
		case Server::ProcessPerInstance:
			qCritical() << "fixme: Threading model is ProcessPerInstance but it still made it to the case statement in prepareInstance, this should never happen.";
			break;
#endif
	}
	QMetaObject::invokeMethod(instance, "init", Qt::QueuedConnection);
}
Beispiel #16
0
int APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *args, int junk2)
{
    char    **argv, *argp, *serviceArgs, *homeDir;
    int     argc, err, nextArg, installFlag;

    mpr = mprCreate(0, NULL, NULL);

    appInst = inst;
    serviceArgs = 0;
    err = 0;
    exiting = 0;
    installFlag = 0;
    homeDir = 0;
    heartBeatPeriod = HEART_BEAT_PERIOD;

    initService();

    mprSetAppName(mpr, BLD_PRODUCT "Angel", BLD_NAME "Angel", BLD_VERSION);
    appName = mprGetAppName(mpr);
    appTitle = mprGetAppTitle(mpr);

    mprSetLogHandler(mpr, logHandler, NULL);

    /*
     *  Create the window 
     */
    if (initWindow() < 0) {
        mprError(mpr, "Can't initialize application Window");
        return FALSE;
    }

    /*
     *  Parse command line arguments
     */
    if (mprMakeArgv(mpr, "", args, &argc, &argv) < 0) {
        return FALSE;
    }
    for (nextArg = 1; nextArg < argc; nextArg++) {
        argp = argv[nextArg];
        if (*argp != '-' || strcmp(argp, "--") == 0) {
            break;
        }

        if (strcmp(argp, "--args") == 0) {
            /*
             *  Args to pass to service when it starts
             */
            if (nextArg >= argc) {
                err++;
            } else {
                serviceArgs = argv[++nextArg];
            }

        } else if (strcmp(argp, "--console") == 0) {
            /*
             *  Allow the service to interact with the console
             */
            createConsole++;

        } else if (strcmp(argp, "--daemon") == 0) {
            /* Ignored on windows */

        } else if (strcmp(argp, "--heartBeat") == 0) {
            /*
             *  Set the heart beat period
             */
            if (nextArg >= argc) {
                err++;
            } else {
                heartBeatPeriod = atoi(argv[++nextArg]) * 1000;
            }

        } else if (strcmp(argp, "--home") == 0) {
            /*
             *  Change to this directory before starting the service
             */
            if (nextArg >= argc) {
                err++;
            } else {
                homeDir = argv[++nextArg];
            }

        } else if (strcmp(argp, "--program") == 0) {
            if (nextArg >= argc) {
                err++;
            } else {
                serviceProgram = argv[++nextArg];
            }

        } else if (strcmp(argp, "--install") == 0) {
            installFlag++;

        } else if (strcmp(argp, "--start") == 0) {
            /*
             *  Start the angel
             */
            if (startService() < 0) {
                return FALSE;
            }
            mprSleep(mpr, 2000);    /* Time for service to really start */

        } else if (strcmp(argp, "--stop") == 0) {
            /*
             *  Stop the  angel
             */
            if (removeService(0) < 0) {
                return FALSE;
            }

        } else if (strcmp(argp, "--uninstall") == 0) {
            /*
             *  Remove the  angel
             */
            if (removeService(1) < 0) {
                return FALSE;
            }

        } else if (strcmp(argp, "--verbose") == 0 || strcmp(argp, "-v") == 0) {
            verbose++;

        } else {
            err++;
        }

        if (err) {
            mprUserError(mpr, 
                "Bad command line: %s\n"
                "  Usage: %s [options] [program args]\n"
                "  Switches:\n"
                "    --args               # Args to pass to service\n"
                "    --console            # Display the service console\n"
                "    --heartBeat interval # Heart beat interval period (secs)\n"
                "    --home path          # Home directory for service\n"
                "    --install            # Install the service\n"
                "    --program            # Service program to start\n"
                "    --start              # Start the service\n"
                "    --stop               # Stop the service\n"
                "    --uninstall          # Uninstall the service",
                args, appName);
            return -1;
        }
    }

    if (installFlag) {
        /*
         *  Install the angel
         */
        if (installService(homeDir, serviceArgs) < 0) {
            return FALSE;
        }
    }

    if (argc <= 1) {
        /*
         *  This will block if we are a service and are being started by the
         *  service control manager. While blocked, the svcMain will be called
         *  which becomes the effective main program. 
         */
        startDispatcher(serviceMain);
    }
    return 0;
}
Beispiel #17
0
void main(int argc, char **argv)
{
  // The StartServiceCtrlDispatcher requires this table to specify
  // the ServiceMain function to run in the calling process. The first
  // member in this example is actually ignored, since we will install
  // our service as a SERVICE_WIN32_OWN_PROCESS service type. The NULL
  // members of the last entry are necessary to indicate the end of
  // the table;
  SERVICE_TABLE_ENTRY serviceTable[] =
    {
      { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)serviceMain },
      { NULL, NULL }
    };

  TCHAR szAppParameters[8192];

 // pthread_win32_process_attach_np();

  if(!isWinNT()) {
    convertArgListToArgString((LPTSTR) szAppParameters,0, argc, argv);
    if(NULL == szAppParameters){
      _tprintf(TEXT("Could not create AppParameters string.\n"));
    }
    invokelprobe(szAppParameters);
    return;
  }
  thisIsAservice = 0;

  // This app may be started with one of three arguments, /i, /r, and
  // /c, or /?, followed by actual program arguments. These arguments
  // indicate if the program is to be installed, removed, run as a
  // console application, or to display a usage message.
  if(argc > 1){
    char *service_name = "lprobe for Win32";

    if(!stricmp(argv[1],"/i")){
      if(argc >2)
	installService(argv[2], argc, argv);
      else
	_tprintf(TEXT("/i requires the service name as parameter\n"));
    }
    else if(!stricmp(argv[1],"/r")){
      if(argc >1)
	removeService(argv[2]);
      else
	_tprintf(TEXT("/r requires the service name as parameter\n"));
    }
    else if(!stricmp(argv[1],"/c")){
      bConsole = TRUE;
      runService(argc,argv);
    }
    else{
      if(stricmp(argv[1],"/h")) printf("\nUnrecognized option: %s\n", argv[1]);
      printf("Available options:\n");
      printf("/i <service name> [lprobe options] - Install lprobe as service\n");
      printf("/c [lprobe options]                - Run lprobe on a console\n");
      printf("/r <service name>                  - Deinstall the service\n\n");
      printf("Example:\n"
	     "Install lprobe as a service: 'lprobe /i my_lprobe -i 0 -n 192.168.0.1:2055'\n"
	     "Remove the lprobe service:   'lprobe /r my_lprobe'\n\n");
      printf("Notes:\n"
	     "1. Type 'lprobe /c -h' to see all options\n"
	     "1. In order to reinstall a service with new options\n"
	     "   it is necessary to first remove the service, then add it\n"
	     "   again with the new options.\n"
	     "2. Services are started/stopped using the Services\n"
	     "   control panel item.\n"
	     "3. You can install the lprobe service multiple times\n"
	     "   as long as you use different service names.\n\n");
    }
    exit(0);
  }
  thisIsAservice = 1;

  // If main is called without any arguments, it will probably be by the
  // service control manager, in which case StartServiceCtrlDispatcher
  // must be called here. A message will be printed just in case this
  // happens from the console.
  printf("\nNOTE:\nUnder your version of Windows, lprobe is started as a service.\n");
  printf("Please open the services control panel to start/stop lprobe,\n");
  printf("or type lprobe /h to see all the available options.\n");

  if(!StartServiceCtrlDispatcher(serviceTable)) {
    printf("\n%s\n", SZFAILURE);
    AddToMessageLog(TEXT(SZFAILURE));
  }
}
Beispiel #18
0
/*
 *
 * Main Windows entry point.
 *
 * We parse the command line and either calls the main App
 *   or starts up the service.
 */
int WINAPI WinMain(HINSTANCE Instance, HINSTANCE /*PrevInstance*/, PSTR CmdLine, 
                   int /*show*/)
{
   char *cmdLine = CmdLine;
   char *wordPtr, *tempPtr;
   int i, quote;
   OSVERSIONINFO osversioninfo;
   osversioninfo.dwOSVersionInfoSize = sizeof(osversioninfo);


   /* Save the application instance and main thread id */
   appInstance = Instance;
   mainthreadId = GetCurrentThreadId();

   if (GetVersionEx(&osversioninfo) && 
       osversioninfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
      have_service_api = true;
   }

   main_pid = getpid();
   main_tid = pthread_self();

   INITCOMMONCONTROLSEX initCC = {
      sizeof(INITCOMMONCONTROLSEX), 
      ICC_STANDARD_CLASSES
   };

   InitCommonControlsEx(&initCC);

   /*
    * Funny things happen with the command line if the
    * execution comes from c:/Program Files/bacula/bacula.exe
    * We get a command line like: Files/bacula/bacula.exe" options
    * I.e. someone stops scanning command line on a space, not
    * realizing that the filename is quoted!!!!!!!!!!
    * So if first character is not a double quote and
    * the last character before first space is a double
    * quote, we throw away the junk.
    */

   wordPtr = cmdLine;
   while (*wordPtr && *wordPtr != ' ')
      wordPtr++;
   if (wordPtr > cmdLine)      /* backup to char before space */
      wordPtr--;
   /* if first character is not a quote and last is, junk it */
   if (*cmdLine != '"' && *wordPtr == '"') {
      cmdLine = wordPtr + 1;
   }

   /*
    * Build Unix style argc *argv[] for the main "Unix" code
    *  stripping out any Windows options 
    */

   /* Don't NULL command_args[0] !!! */
   for (i=1;i<MAX_COMMAND_ARGS;i++) {
      command_args[i] = NULL;
   }

   char *pszArgs = bstrdup(cmdLine);
   wordPtr = pszArgs;
   quote = 0;
   while  (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
      wordPtr++;
   if (*wordPtr == '\"') {
      quote = 1;
      wordPtr++;
   } else if (*wordPtr == '/') {
      /* Skip Windows options */
      while (*wordPtr && (*wordPtr != ' ' && *wordPtr != '\t'))
         wordPtr++;
      while  (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
         wordPtr++;
   }
   if (*wordPtr) {
      while (*wordPtr && num_command_args < MAX_COMMAND_ARGS) {
         tempPtr = wordPtr;
         if (quote) {
            while (*tempPtr && *tempPtr != '\"')
               tempPtr++;
            quote = 0;
         } else {
            while (*tempPtr && *tempPtr != ' ')
            tempPtr++;
         }
         if (*tempPtr)
            *(tempPtr++) = '\0';
         command_args[num_command_args++] = wordPtr;
         wordPtr = tempPtr;
         while (*wordPtr && (*wordPtr == ' ' || *wordPtr == '\t'))
            wordPtr++;
         if (*wordPtr == '\"') {
            quote = 1;
            wordPtr++;
         }
      }
   }

   /*
    * Now process Windows command line options. Most of these options
    *  are single shot -- i.e. we accept one option, do something and
    *  terminate.
    */
   for (i = 0; i < (int)strlen(cmdLine); i++) {
      char *p = &cmdLine[i];

      if (*p <= ' ') {
         continue;                    /* toss junk */
      }

      if (*p != '/') {
         break;                       /* syntax error */
      }

      /* Start as a service? */
      if (strncasecmp(p, "/service", 8) == 0) {
         return baculaServiceMain();      /* yes, run as a service */
      }

      /* Stop any running copy? */
      if (strncasecmp(p, "/kill", 5) == 0) {
         return stopRunningBacula();
      }

      /* Run app as user program? */
      if (strncasecmp(p, "/run", 4) == 0) {
         return BaculaAppMain();         /* yes, run as a user program */
      }

      /* Install Bacula in registry? */
      if (strncasecmp(p, "/install", 8) == 0) {
         return installService(p+8);    /* Pass command options */
      }

      /* Remove Bacula registry entry? */
      if (strncasecmp(p, "/remove", 7) == 0) {
         return removeService();
      }

      /* Set debug mode? -- causes more dialogs to be displayed */
      if (strncasecmp(p, "/debug", 6) == 0) {
         opt_debug = true;
         i += 6;                /* skip /debug */
         continue;
      }

      /* Display help? -- displays usage */
      if (strncasecmp(p, "/help", 5) == 0) {
         MessageBox(NULL, usage, APP_DESC, MB_OK|MB_ICONINFORMATION);
         return 0;
      }
      
      MessageBox(NULL, cmdLine, _("Bad Command Line Option"), MB_OK);

      /* Show the usage dialog */
      MessageBox(NULL, usage, APP_DESC, MB_OK | MB_ICONINFORMATION);

      return 1;
   }
   return BaculaAppMain();
}
Beispiel #19
0
void main(int argc, char **argv)
{
  // The StartServiceCtrlDispatcher requires this table to specify
  // the ServiceMain function to run in the calling process. The first
  // member in this example is actually ignored, since we will install
  // our service as a SERVICE_WIN32_OWN_PROCESS service type. The NULL
  // members of the last entry are necessary to indicate the end of
  // the table;
  SERVICE_TABLE_ENTRY serviceTable[] =
    {
      { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)serviceMain },
      { NULL, NULL }
    };

  TCHAR szAppParameters[8192];

  if(!isWinNT()) {
    convertArgListToArgString((LPTSTR) szAppParameters,0, argc, argv);
    if(NULL == szAppParameters){
      _tprintf(TEXT("Could not create AppParameters string.\n"));
    }
    invokeNtop(szAppParameters);
    return;
  }

  isNtopAservice = 0;

  // This app may be started with one of three arguments, /i, /r, and
  // /c, or /?, followed by actual program arguments. These arguments
  // indicate if the program is to be installed, removed, run as a
  // console application, or to display a usage message.
  if(argc > 1){
    if(!stricmp(argv[1],"/i")){
      installService(argc,argv);
      printf("NOTE: the default password for the 'admin' user has been set to 'admin'.");
    }
    else if(!stricmp(argv[1],"/r")){
      removeService();
    }
    else if(!stricmp(argv[1],"/c")){
      bConsole = TRUE;
      runService(argc, argv);
    }
    else {
      printf("\nUnrecognized option: %s\n", argv[1]);
      printf("Available options:\n");
      printf("/i [ntopng options] - Install ntopng as service\n");
      printf("/c                  - Run ntopng on a console\n");
      printf("/r                  - Deinstall the service\n");
      printf("/h                  - Prints this help\n\n");

      usage();
    }

    exit(0);
  }

  // If main is called without any arguments, it will probably be by the
  // service control manager, in which case StartServiceCtrlDispatcher
  // must be called here. A message will be printed just in case this
  // happens from the console.
  printf("\nNOTE:\nUnder your version of Windows, ntopng is started as a service.\n");
  printf("Please open the services control panel to start/stop ntop,\n");
  printf("or type ntop /h to see all the available options.\n");

  isNtopAservice = 1;
  if(!StartServiceCtrlDispatcher(serviceTable)) {
    printf("\n%s\n", SZFAILURE);
    AddToMessageLog(TEXT(SZFAILURE));
  }
}