Beispiel #1
0
static void initSignalHandler()
{
    SetConsoleCtrlHandler(winSignalHandler, TRUE);
}
Beispiel #2
0
int main(int argc, char *argv[]) {
  int i, rc;
  MDBX_env *env = NULL;
  MDBX_txn *txn = NULL;
  MDBX_cursor *mc = NULL;
  MDBX_dbi dbi;
  char *envname = NULL;
  int envflags = MDBX_UTTERLY_NOSYNC, putflags = 0;
  int append = 0;
  MDBX_val prevk;

  prog = argv[0];
  if (argc < 2)
    usage();

  /* -a: append records in input order
   * -f: load file instead of stdin
   * -n: use NOSUBDIR flag on env_open
   * -s: load into named subDB
   * -N: use NOOVERWRITE on puts
   * -T: read plaintext
   * -V: print version and exit
   */
  while ((i = getopt(argc, argv, "af:ns:NTV")) != EOF) {
    switch (i) {
    case 'V':
      printf("%s (%s, build %s)\n", mdbx_version.git.describe,
             mdbx_version.git.datetime, mdbx_build.datetime);
      exit(EXIT_SUCCESS);
      break;
    case 'a':
      append = 1;
      break;
    case 'f':
      if (freopen(optarg, "r", stdin) == NULL) {
        fprintf(stderr, "%s: %s: reopen: %s\n", prog, optarg,
                mdbx_strerror(errno));
        exit(EXIT_FAILURE);
      }
      break;
    case 'n':
      envflags |= MDBX_NOSUBDIR;
      break;
    case 's':
      subname = mdbx_strdup(optarg);
      break;
    case 'N':
      putflags = MDBX_NOOVERWRITE | MDBX_NODUPDATA;
      break;
    case 'T':
      mode |= NOHDR | PRINT;
      break;
    default:
      usage();
    }
  }

  if (optind != argc - 1)
    usage();

#if defined(_WIN32) || defined(_WIN64)
  SetConsoleCtrlHandler(ConsoleBreakHandlerRoutine, true);
#else
#ifdef SIGPIPE
  signal(SIGPIPE, signal_handler);
#endif
#ifdef SIGHUP
  signal(SIGHUP, signal_handler);
#endif
  signal(SIGINT, signal_handler);
  signal(SIGTERM, signal_handler);
#endif /* !WINDOWS */

  dbuf.iov_len = 4096;
  dbuf.iov_base = mdbx_malloc(dbuf.iov_len);

  /* read first header for mapsize= */
  if (!(mode & NOHDR))
    readhdr();

  envname = argv[optind];
  rc = mdbx_env_create(&env);
  if (rc) {
    fprintf(stderr, "mdbx_env_create failed, error %d %s\n", rc,
            mdbx_strerror(rc));
    return EXIT_FAILURE;
  }

  mdbx_env_set_maxdbs(env, 2);

  if (envinfo.mi_maxreaders)
    mdbx_env_set_maxreaders(env, envinfo.mi_maxreaders);

  if (envinfo.mi_mapsize) {
    if (envinfo.mi_mapsize > SIZE_MAX) {
      fprintf(stderr, "mdbx_env_set_mapsize failed, error %d %s\n", rc,
              mdbx_strerror(MDBX_TOO_LARGE));
      return EXIT_FAILURE;
    }
    mdbx_env_set_mapsize(env, (size_t)envinfo.mi_mapsize);
  }

#ifdef MDBX_FIXEDMAP
  if (info.mi_mapaddr)
    envflags |= MDBX_FIXEDMAP;
#endif

  rc = mdbx_env_open(env, envname, envflags, 0664);
  if (rc) {
    fprintf(stderr, "mdbx_env_open failed, error %d %s\n", rc,
            mdbx_strerror(rc));
    goto env_close;
  }

  kbuf.iov_len = mdbx_env_get_maxkeysize(env);
  if (kbuf.iov_len >= SIZE_MAX / 4) {
    fprintf(stderr, "mdbx_env_get_maxkeysize failed, returns %zu\n",
            kbuf.iov_len);
    goto env_close;
  }
  kbuf.iov_len = (kbuf.iov_len + 1) * 2;
  kbuf.iov_base = malloc(kbuf.iov_len * 2);
  k0buf.iov_len = kbuf.iov_len;
  k0buf.iov_base = (char *)kbuf.iov_base + kbuf.iov_len;
  prevk.iov_base = k0buf.iov_base;

  while (!Eof) {
    if (user_break) {
      rc = MDBX_EINTR;
      break;
    }

    rc = mdbx_txn_begin(env, NULL, 0, &txn);
    if (rc) {
      fprintf(stderr, "mdbx_txn_begin failed, error %d %s\n", rc,
              mdbx_strerror(rc));
      goto env_close;
    }

    rc = mdbx_dbi_open_ex(txn, subname, dbi_flags | MDBX_CREATE, &dbi,
                          append ? anyway_greater : NULL,
                          append ? anyway_greater : NULL);
    if (rc) {
      fprintf(stderr, "mdbx_open failed, error %d %s\n", rc, mdbx_strerror(rc));
      goto txn_abort;
    }

    rc = mdbx_cursor_open(txn, dbi, &mc);
    if (rc) {
      fprintf(stderr, "mdbx_cursor_open failed, error %d %s\n", rc,
              mdbx_strerror(rc));
      goto txn_abort;
    }

    int batch = 0;
    prevk.iov_len = 0;
    while (1) {
      MDBX_val key;
      rc = readline(&key, &kbuf);
      if (rc) /* rc == EOF */
        break;

      MDBX_val data;
      rc = readline(&data, &dbuf);
      if (rc) {
        fprintf(stderr, "%s: line %" PRIiSIZE ": failed to read key value\n",
                prog, lineno);
        goto txn_abort;
      }

      int appflag = 0;
      if (append) {
        appflag = MDBX_APPEND;
        if (dbi_flags & MDBX_DUPSORT) {
          if (prevk.iov_len == key.iov_len &&
              memcmp(prevk.iov_base, key.iov_base, key.iov_len) == 0)
            appflag = MDBX_APPEND | MDBX_APPENDDUP;
          else
            memcpy(prevk.iov_base, key.iov_base, prevk.iov_len = key.iov_len);
        }
      }
      rc = mdbx_cursor_put(mc, &key, &data, putflags | appflag);
      if (rc == MDBX_KEYEXIST && putflags)
        continue;
      if (rc) {
        fprintf(stderr, "mdbx_cursor_put failed, error %d %s\n", rc,
                mdbx_strerror(rc));
        goto txn_abort;
      }
      batch++;
      if (batch == 100) {
        rc = mdbx_txn_commit(txn);
        if (rc) {
          fprintf(stderr, "%s: line %" PRIiSIZE ": txn_commit: %s\n", prog,
                  lineno, mdbx_strerror(rc));
          goto env_close;
        }
        rc = mdbx_txn_begin(env, NULL, 0, &txn);
        if (rc) {
          fprintf(stderr, "mdbx_txn_begin failed, error %d %s\n", rc,
                  mdbx_strerror(rc));
          goto env_close;
        }
        rc = mdbx_cursor_open(txn, dbi, &mc);
        if (rc) {
          fprintf(stderr, "mdbx_cursor_open failed, error %d %s\n", rc,
                  mdbx_strerror(rc));
          goto txn_abort;
        }
        batch = 0;
      }
    }
    rc = mdbx_txn_commit(txn);
    txn = NULL;
    if (rc) {
      fprintf(stderr, "%s: line %" PRIiSIZE ": txn_commit: %s\n", prog, lineno,
              mdbx_strerror(rc));
      goto env_close;
    }
    mdbx_dbi_close(env, dbi);

    /* try read next header */
    if (!(mode & NOHDR))
      readhdr();
  }

txn_abort:
  mdbx_txn_abort(txn);
env_close:
  mdbx_env_close(env);

  return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}
Beispiel #3
0
/* Attaches a signal handler for Ctrl+C or Ctrl+Break signals
 * Returns 1 if successful or -1 on error
 */
int cregtools_signal_attach(
     void (*signal_handler)( cregtools_signal_t ),
     libcerror_error_t **error )
{
	static char *function = "cregtools_signal_attach";

	if( signal_handler == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid signal handler.",
		 function );

		return( -1 );
	}
	cregtools_signal_signal_handler = signal_handler;

	if( SetConsoleCtrlHandler(
	     cregtools_signal_handler,
	     TRUE ) == 0 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_SET_FAILED,
		 "%s: unable to attach signal handler.",
		 function );

		return( -1 );
	}
	if( SetConsoleCtrlHandler(
	     NULL,
	     FALSE ) == 0 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_SET_FAILED,
		 "%s: unable to attach break signal.",
		 function );

		return( -1 );
	}
#if defined( _MSC_VER )
	cregtools_signal_initialize_memory_debug();
#endif

	SetErrorMode(
	 SEM_FAILCRITICALERRORS );

#if defined( LOCALE_SUPPORT )
	/* Allow subsequent threads to have their own locale.
	 * If the application is single threaded this call has
	 * no practical effect.
	 */
	_configthreadlocale(
	  _ENABLE_PER_THREAD_LOCALE );

	/* Set the current thread locale to the user default
	 * ANSI code page.
	 */
	setlocale(
	 LC_ALL,
	 "" );

	/* Set the the code page used by multibyte functions
	 * to use the same code page as the previous call to setlocale.
	 */
	_setmbcp(
	  _MB_CP_LOCALE );

#endif /* defined( LOCALE_SUPPORT ) */

	return( 1 );
}
Beispiel #4
0
R_API RCons *r_cons_new() {
	I.refcnt++;
	if (I.refcnt != 1) {
		return &I;
	}
	I.line = r_line_new ();
	I.highlight = NULL;
	I.event_interrupt = NULL;
	I.is_wine = -1;
	I.fps = 0;
	I.use_color = false;
	I.blankline = true;
	I.teefile = NULL;
	I.fix_columns = 0;
	I.fix_rows = 0;
	I.mouse_event = 0;
	I.force_rows = 0;
	I.force_columns = 0;
	I.event_resize = NULL;
	I.data = NULL;
	I.event_data = NULL;
	I.is_interactive = true;
	I.noflush = false;
	I.linesleep = 0;
	I.fdin = stdin;
	I.fdout = 1;
	I.breaked = false;
	//I.lines = 0;
	I.buffer = NULL;
	I.buffer_sz = 0;
	I.buffer_len = 0;
	r_cons_get_size (&I.pagesize);
	I.num = NULL;
	I.null = 0;
#if __WINDOWS__ && !__CYGWIN__
	I.ansicon = r_sys_getenv ("ANSICON");
#endif
#if EMSCRIPTEN
	/* do nothing here :? */
#elif __UNIX__ || __CYGWIN__
	tcgetattr (0, &I.term_buf);
	memcpy (&I.term_raw, &I.term_buf, sizeof (I.term_raw));
	I.term_raw.c_iflag &= ~(BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
	I.term_raw.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
	I.term_raw.c_cflag &= ~(CSIZE|PARENB);
	I.term_raw.c_cflag |= CS8;
	I.term_raw.c_cc[VMIN] = 1; // Solaris stuff hehe
	signal (SIGWINCH, resize);
#elif __WINDOWS__
	h = GetStdHandle (STD_INPUT_HANDLE);
	GetConsoleMode (h, (PDWORD) &I.term_buf);
	I.term_raw = 0;
	if (!SetConsoleCtrlHandler ((PHANDLER_ROUTINE)__w32_control, TRUE)) {
		eprintf ("r_cons: Cannot set control console handler\n");
	}
#endif
	I.pager = NULL; /* no pager by default */
	I.truecolor = 0;
	I.mouse = 0;
	I.cons_stack = r_stack_newf (6, cons_stack_free);
	I.break_stack = r_stack_newf (6, break_stack_free);
	r_cons_pal_null ();
	r_cons_pal_init (NULL);
	r_cons_rgb_init ();
	r_cons_reset ();
	return &I;
}
Beispiel #5
0
void set_signal_blocking(int sig, int block)
{
  SetConsoleCtrlHandler(blocking_handler, block ? TRUE : FALSE);
}
Beispiel #6
0
int 
daemonize(int port, int bg)
{
	int sock = 0;
	struct sockaddr_in serv;
	int on = 1;
	int fdtty;	
	pid_t pid;
		
	if (bg) {
		pid = fork();
		if (pid < 0) {
			perror("Daemon fork");
			return (-1);
		}
		if (pid > 0)
			exit(0);
	}

	daemon_port = port;
	
	setsid();
	
#ifdef cygwin
	SetConsoleCtrlHandler(handler_routine, TRUE);
#endif

	signal(SIGTERM, &sig_term);
	signal(SIGQUIT, &sig_quit);
	signal(SIGINT, &sig_int);
	signal(SIGHUP, SIG_IGN);
	signal(SIGUSR1, &sig_usr1);
   	signal(SIGUSR2, &sig_usr2);
   	signal(SIGCHLD, SIG_IGN);
	signal(SIGPIPE, SIG_IGN);
	
   	/* open an tty as standard I/O for vpcs */
   	fdtty_pid = forkpty(&fdtty, NULL, NULL, NULL);
   	
   	if (fdtty_pid < 0) {
   		perror("Daemon fork tty\n");
   		return (-1);
	}
	
   	/* child process, the 'real' vpcs */
   	if (fdtty_pid == 0) 
   		return 0;
   	
   	/* daemon socket */
   	sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock < 0) {
		perror("Daemon socket");
		goto err;
	}
	(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
	    (char *)&on, sizeof(on));

	bzero((char *) &serv, sizeof(serv));
	serv.sin_family = AF_INET;
	serv.sin_addr.s_addr = htonl(INADDR_ANY);
	serv.sin_port = htons(port);
	
	if (bind(sock, (struct sockaddr *) &serv, sizeof(serv)) < 0) {
		perror("Daemon bind port");
		goto err;
	}
	if (listen(sock, 5) < 0) {
		perror("Daemon listen");
		goto err;
	}

	daemon_proc(sock, fdtty);
err:
	if (sock >= 0)
		close(sock);

	close(fdtty);
	kill(fdtty_pid, 9);
	exit(-1);
}
Beispiel #7
0
void init_ctrlc(void)
{
    int_detected = 0;
    SetConsoleCtrlHandler( handle_ctrlc, TRUE );
}
Beispiel #8
0
NTSTATUS
LsapAdtInitialize(
    IN ULONG Pass
    )

/*++

Routine Description:

    This function performs initialization of auditing within the LSA, and
    it also issues commands to the Reference Monitor to enable it to
    complete any initialization of auditing variables that is dependent
    on the content of the LSA Database.  At time of call, the main
    System Init thread is in the Reference Monitor awaiting completion
    of all LSA initialization, and the Reference Monitor Command
    Server thread is waiting for commands.

    The following steps are performed:

    o Read the Audit Event and Audit Log information from the LSA
      Database.
    o Call the Event Logging function to open the Audit Log
    o Issue a Reference Monitor command to write the Audit Event Info
      to the Reference-Monitor's in-memory database.

Arguments:

    Pass - Specifies the stage of initialization to be performed.

         Pass 1 - Initialization required before Audit Records can
             be written to the Audit Log.  Any Audit Records received
             during this time will be "cached" by the LSA and will
             be written out at Pass 2.

         Pass 2 - Write out Audit Records cached during Pass 1.

Return Value:

    NTSTATUS - Standard Nt Result Code.

        All Result Codes are generated by called routines.
--*/

{
    NTSTATUS Status = STATUS_SUCCESS;
    NTSTATUS SecondaryStatus = STATUS_SUCCESS;
    ULONG AuditLogInfoLength = sizeof (POLICY_AUDIT_LOG_INFO);
    ULONG AuditEventInfoLength = sizeof (LSARM_POLICY_AUDIT_EVENTS_INFO);
    ULONG AuditFullQueryInfoLength = sizeof (POLICY_AUDIT_FULL_QUERY_INFO);
    BOOLEAN AcquiredLock = FALSE;
    UNICODE_STRING UnicodeString;
    PUNICODE_STRING Strings;
    PSID Sid = NULL;
    LSARM_POLICY_AUDIT_EVENTS_INFO AuditEventsInfo;

    Strings = &UnicodeString;

    RtlInitUnicodeString( Strings, L"System Restart");

    RtlInitUnicodeString( &LsapSubsystemName, L"Security" );

    if (Pass == 1) {

        Status = LsapAdtInitializeLogQueue();

        if (!NT_SUCCESS(Status)) {

            goto AuditInitError;
        }

        //
        // Acquire the LSA Database Lock.
        //

        Status = LsapDbAcquireLock();

        if (!NT_SUCCESS(Status)) {

             goto AuditInitError;
        }

        AcquiredLock = TRUE;

        //
        // Read the Audit Log Information from the PolAdtLg attribute of the Lsa
        // Database object.
        //

        Status = LsapDbReadAttributeObject(
                     LsapDbHandle,
                     &LsapDbNames[PolAdtLg],
                     &LsapAdtLogInformation,
                     &AuditLogInfoLength
                     );

        if (!NT_SUCCESS(Status)) {

            LsapLogError(
                "LsapAdtInitialize: Read Audit Log Info returned 0x%lx\n",
                Status
                );

            goto AuditInitError;
        }

        //
        // Query the Audit Log Full Information in the LSA Database.  Note
        // that it is too early to update a log full condition, so don't
        // try to write to the Audit Log.
        //

        Status = LsapAdtQueryAuditLogFullInfo(
                     LsapDbHandle,
                     (ULONG) 0,
                     &LsapAdtLogFullInformation
                     );

        if (!NT_SUCCESS(Status)) {

            LsapLogError(
                "LsapAdtInitialize: Update Audit Log Full Info returned 0x%lx\n",
                Status
                );

            goto AuditInitError;
        }

        //
        // Read the Audit Event Information from the AdtEvent attribute of the Lsa
        // Database object.  The information consists of the Auditing Mode and
        // the Auditing Options for each Audit Event Type.
        //

        Status = LsapDbReadAttributeObject(
                     LsapDbHandle,
                     &LsapDbNames[PolAdtEv],
                     &AuditEventsInfo,
                     &AuditEventInfoLength
                     );

        if (!NT_SUCCESS(Status)) {

            //
            // This section of code is temporary and allows an old
            // Policy Database to work with the new Audit Event Categories
            // without the need to re-install.  The Audit Event Information
            // is overwritten with the new format and all auditing is turned
            // off.
            //

            if (Status == STATUS_BUFFER_OVERFLOW) {

                KdPrint(("LsapAdtInitialize: Old Audit Event Info detected\n"
                        "Replacing with new format, all auditing disabled\n"));

                //
                // Initialize Default Event Auditing Options.  No auditing is specified
                // for any event type.
                //

                Status = LsapAdtInitializeDefaultAuditing(
                             LSAP_DB_UPDATE_POLICY_DATABASE,
                             &AuditEventsInfo
                             );

                if (!NT_SUCCESS(Status)) {

                    goto AuditInitError;
                }

            } else {

                LsapLogError(
                    "LsapAdtInitialize: Read Audit Event Info returned 0x%lx\n",
                    Status
                    );
                goto AuditInitError;
            }
        }

        //
        // Set global flags to tell us if we're supposed to be auditing
        // successful logons, failed logons, or both
        //
        //

        LsapAdtAuditingLogon( &AuditEventsInfo );

        //
        // During system initialization, we are effectively logged on as
        // system.
        //

        LsapAdtSystemRestart( &AuditEventsInfo );

        (VOID) LsapAdtInitializeCrashOnFail();

        //
        // Send a command to the Reference Monitor to write the Auditing
        // State to its in-memory data.
        //

        Status = LsapCallRm(
                     RmAuditSetCommand,
                     &AuditEventsInfo,
                     sizeof (LSARM_POLICY_AUDIT_EVENTS_INFO),
                     NULL,
                     0
                     );

        if (!NT_SUCCESS(Status)) {

            LsapLogError("LsapAdtInitialize: LsapCallRm returned 0x%lx\n", Status);
            goto AuditInitError;
        }

        RtlCopyMemory(
            &LsapAdtEventsInformation,
            &AuditEventsInfo,
            sizeof(LSARM_POLICY_AUDIT_EVENTS_INFO)
            );


        LsapAdtInitializeDriveLetters();

        //
        // Initialize privilege values we need
        //

        ChangeNotifyPrivilege       = RtlConvertLongToLuid( SE_CHANGE_NOTIFY_PRIVILEGE      );
        AuditPrivilege              = RtlConvertLongToLuid( SE_AUDIT_PRIVILEGE              );
        CreateTokenPrivilege        = RtlConvertLongToLuid( SE_CREATE_TOKEN_PRIVILEGE       );
        AssignPrimaryTokenPrivilege = RtlConvertLongToLuid( SE_ASSIGNPRIMARYTOKEN_PRIVILEGE );
        BackupPrivilege             = RtlConvertLongToLuid( SE_BACKUP_PRIVILEGE             );
        RestorePrivilege            = RtlConvertLongToLuid( SE_RESTORE_PRIVILEGE            );
        DebugPrivilege              = RtlConvertLongToLuid( SE_DEBUG_PRIVILEGE              );

        //
        // Tell base/wincon how to shut us down.
        // First, tell base to shut us down as late in the game as possible.
        //

        SetProcessShutdownParameters(LSAP_SHUTDOWN_LEVEL, SHUTDOWN_NORETRY);

        // And, tell them what function to call when we are being shutdown:

        SetConsoleCtrlHandler(LsapShutdownNotification, TRUE);


    } else if (Pass == 2) {

        //
        // Write out any Audit Records that were cached during the
        // first stage of initialization.  The Audit Log will be opened
        // on the first write if necessary.
        //

        //
        // BUGBUG - ScottBi 8/6/92 - This action cannot be taken here
        // unless we know that the EventLog service is running.  For now,
        // an attempt is made to open the log each time an Audit Record
        // is generated, and the cache grows until a limit is reached,
        // at which point auditing is turned off and subsequent records
        // are discarded.
        //

        /*
        Status = LsapAdtWriteLog( NULL, (ULONG) 0);

        if (!NT_SUCCESS(Status)) {

            goto AuditInitError;
        }
        */
    }

AuditInitFinish:

    if (AcquiredLock) {

        LsapDbReleaseLock();
    }

    return(Status);

AuditInitError:

    //
    // If the Audit Log is full, signal the Log Full condition
    //

    if (Status == STATUS_LOG_FILE_FULL) {

        SecondaryStatus = LsapAdtSignalLogFull();
    }

    //
    // If auditing failed to initialize, output warning and disable
    // auditing.
    //

    if (Pass == 1) {

        LsapLogError(
            "LSA: Warning - Audit Initialization Pass 1 Returned 0x%lx\n"
            "     Auditing has been disabled\n",
            Status
            );

    } else {

        LsapLogError(
            "LSA: Warning - Audit Initialization Pass 2 Returned 0x%lx\n"
            "     Auditing has been disabled\n",
            Status
            );
    }

    LsapAdtEventsInformation.AuditingMode = FALSE;

    Status = LsarSetInformationPolicy(
                 LsapDbHandle,
                 PolicyAuditEventsInformation,
                 (PLSAPR_POLICY_INFORMATION) &LsapAdtEventsInformation
                 );

    goto AuditInitFinish;
}
Beispiel #9
0
PyMODINIT_FUNC
PyInit__multiprocess(void)
{
    PyObject *module, *temp, *value;

    /* Initialize module */
    module = PyModule_Create(&multiprocessing_module);
    if (!module)
        return NULL;

    /* Get copy of objects from pickle */
    temp = PyImport_ImportModule("dill");
    if (!temp)
        temp = PyImport_ImportModule(PICKLE_MODULE);
    if (!temp)
        return NULL;
    pickle_dumps = PyObject_GetAttrString(temp, "dumps");
    pickle_loads = PyObject_GetAttrString(temp, "loads");
    pickle_protocol = PyObject_GetAttrString(temp, "DEFAULT_PROTOCOL");
    if (!pickle_protocol)
        pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
    Py_XDECREF(temp);

    /* Get copy of BufferTooShort */
    temp = PyImport_ImportModule("multiprocess");
    if (!temp)
        return NULL;
    BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
    Py_XDECREF(temp);

    /* Add connection type to module */
    if (PyType_Ready(&ConnectionType) < 0)
        return NULL;
    Py_INCREF(&ConnectionType);
    PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);

#if defined(MS_WINDOWS) ||                                              \
  (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
    /* Add SemLock type to module */
    if (PyType_Ready(&SemLockType) < 0)
        return NULL;
    Py_INCREF(&SemLockType);
    {
        PyObject *py_sem_value_max;
        /* Some systems define SEM_VALUE_MAX as an unsigned value that
         * causes it to be negative when used as an int (NetBSD). */
        if ((int)(SEM_VALUE_MAX) < 0)
            py_sem_value_max = PyLong_FromLong(INT_MAX);
        else
            py_sem_value_max = PyLong_FromLong(SEM_VALUE_MAX);
        if (py_sem_value_max == NULL)
            return NULL;
        PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX",
                             py_sem_value_max);
    }
    PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);
#endif

#ifdef MS_WINDOWS
    /* Add PipeConnection to module */
    if (PyType_Ready(&PipeConnectionType) < 0)
        return NULL;
    Py_INCREF(&PipeConnectionType);
    PyModule_AddObject(module, "PipeConnection",
                       (PyObject*)&PipeConnectionType);

    /* Initialize win32 class and add to multiprocessing */
    temp = create_win32_namespace();
    if (!temp)
        return NULL;
    PyModule_AddObject(module, "win32", temp);

    /* Initialize the event handle used to signal Ctrl-C */
    sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!sigint_event) {
        PyErr_SetFromWindowsErr(0);
        return NULL;
    }
    if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
        PyErr_SetFromWindowsErr(0);
        return NULL;
    }
#endif

    /* Add configuration macros */
    temp = PyDict_New();
    if (!temp)
        return NULL;

#define ADD_FLAG(name)                                            \
    value = Py_BuildValue("i", name);                             \
    if (value == NULL) { Py_DECREF(temp); return NULL; }          \
    if (PyDict_SetItemString(temp, #name, value) < 0) {           \
        Py_DECREF(temp); Py_DECREF(value); return NULL; }                 \
    Py_DECREF(value)

#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
    ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
    ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
    ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
    ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
    ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif

    if (PyModule_AddObject(module, "flags", temp) < 0)
        return NULL;

    return module;
}
Beispiel #10
0
void enable_exit_signaller()
{
    SetConsoleCtrlHandler( control_handler, TRUE );
}
int adb_server_main(int is_daemon, int server_port, int ack_reply_fd) {
#if defined(_WIN32)
    // adb start-server starts us up with stdout and stderr hooked up to
    // anonymous pipes. When the C Runtime sees this, it makes stderr and
    // stdout buffered, but to improve the chance that error output is seen,
    // unbuffer stdout and stderr just like if we were run at the console.
    // This also keeps stderr unbuffered when it is redirected to adb.log.
    if (is_daemon) {
        if (setvbuf(stdout, NULL, _IONBF, 0) == -1) {
            fatal("cannot make stdout unbuffered: %s", strerror(errno));
        }
        if (setvbuf(stderr, NULL, _IONBF, 0) == -1) {
            fatal("cannot make stderr unbuffered: %s", strerror(errno));
        }
    }

    SetConsoleCtrlHandler(ctrlc_handler, TRUE);
#endif

    init_transport_registration();

    usb_init();
    local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
    adb_auth_init();

    std::string error;
    std::string local_name = android::base::StringPrintf("tcp:%d", server_port);
    if (install_listener(local_name, "*smartsocket*", nullptr, 0, &error)) {
        fatal("could not install *smartsocket* listener: %s", error.c_str());
    }

    // Inform our parent that we are up and running.
    if (is_daemon) {
        close_stdin();
        setup_daemon_logging();

        // Any error output written to stderr now goes to adb.log. We could
        // keep around a copy of the stderr fd and use that to write any errors
        // encountered by the following code, but that is probably overkill.
#if defined(_WIN32)
        const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
        const CHAR ack[] = "OK\n";
        const DWORD bytes_to_write = arraysize(ack) - 1;
        DWORD written = 0;
        if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) {
            fatal("adb: cannot write ACK to handle 0x%p: %s", ack_reply_handle,
                  SystemErrorCodeToString(GetLastError()).c_str());
        }
        if (written != bytes_to_write) {
            fatal("adb: cannot write %lu bytes of ACK: only wrote %lu bytes",
                  bytes_to_write, written);
        }
        CloseHandle(ack_reply_handle);
#else
        // TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not
        // "OKAY".
        if (!android::base::WriteStringToFd("OK\n", ack_reply_fd)) {
            fatal_errno("error writing ACK to fd %d", ack_reply_fd);
        }
        unix_close(ack_reply_fd);
#endif
    }

    D("Event loop starting");
    fdevent_loop();

    return 0;
}
Beispiel #12
0
static int add_connection(struct service *service, struct command_context *cmd_ctx)
{
	socklen_t address_size;
	struct connection *c, **p;
	int retval;
	int flag = 1;

	c = malloc(sizeof(struct connection));
	c->fd = -1;
	c->fd_out = -1;
	memset(&c->sin, 0, sizeof(c->sin));
	c->cmd_ctx = copy_command_context(cmd_ctx);
	c->service = service;
	c->input_pending = 0;
	c->priv = NULL;
	c->next = NULL;

	if (service->type == CONNECTION_TCP) {
		address_size = sizeof(c->sin);

		c->fd = accept(service->fd, (struct sockaddr *)&service->sin, &address_size);
		c->fd_out = c->fd;

		/* This increases performance dramatically for e.g. GDB load which
		 * does not have a sliding window protocol.
		 *
		 * Ignore errors from this fn as it probably just means less performance
		 */
		setsockopt(c->fd,	/* socket affected */
			IPPROTO_TCP,			/* set option at TCP level */
			TCP_NODELAY,			/* name of option */
			(char *)&flag,			/* the cast is historical cruft */
			sizeof(int));			/* length of option value */

		LOG_INFO("accepting '%s' connection from %s", service->name, service->port);
		retval = service->new_connection(c);
		if (retval != ERROR_OK) {
			close_socket(c->fd);
			LOG_ERROR("attempted '%s' connection rejected", service->name);
			command_done(c->cmd_ctx);
			free(c);
			return retval;
		}
	} else if (service->type == CONNECTION_STDINOUT) {
		c->fd = service->fd;
		c->fd_out = fileno(stdout);

#ifdef _WIN32
		/* we are using stdin/out so ignore ctrl-c under windoze */
		SetConsoleCtrlHandler(NULL, TRUE);
#endif

		/* do not check for new connections again on stdin */
		service->fd = -1;

		LOG_INFO("accepting '%s' connection from pipe", service->name);
		retval = service->new_connection(c);
		if (retval != ERROR_OK) {
			LOG_ERROR("attempted '%s' connection rejected", service->name);
			command_done(c->cmd_ctx);
			free(c);
			return retval;
		}
	} else if (service->type == CONNECTION_PIPE) {
		c->fd = service->fd;
		/* do not check for new connections again on stdin */
		service->fd = -1;

		char *out_file = alloc_printf("%so", service->port);
		c->fd_out = open(out_file, O_WRONLY);
		free(out_file);
		if (c->fd_out == -1) {
			LOG_ERROR("could not open %s", service->port);
			exit(1);
		}

		LOG_INFO("accepting '%s' connection from pipe %s", service->name, service->port);
		retval = service->new_connection(c);
		if (retval != ERROR_OK) {
			LOG_ERROR("attempted '%s' connection rejected", service->name);
			command_done(c->cmd_ctx);
			free(c);
			return retval;
		}
	}

	/* add to the end of linked list */
	for (p = &service->connections; *p; p = &(*p)->next)
		;
	*p = c;

	service->max_connections--;

	return ERROR_OK;
}
Beispiel #13
0
/* main entry point function */
int __cdecl main( int argc, char **argv ) 

{
    /* local variables */
    BOOL    ret = PASS;


    /* PAL initialization */
    if( (PAL_Initialize(argc, argv)) != 0 )
    {
        return( FAIL );
    }


    /* set the console control handler function */
    if( ! SetConsoleCtrlHandler( CtrlHandler1, TRUE ) )
    {
        ret = FAIL;
        Trace( "ERROR:%lu:SetConsoleCtrlHandler() failed to add "
                "CtrlHandler1\n",
                GetLastError() );
        Fail( "Test failed\n" );
    }
    
    /* test that the right control handler functions are set */
    if( ! GenerateConsoleCtrlEvent( CTRL_C_EVENT, 0 ) )
    {
        Trace( "ERROR:%lu:GenerateConsoleCtrlEvent() failed\n",
                GetLastError() );
        ret = FAIL;
        goto done;
    }

    /* give the handlers a chance to execute */    
    Sleep( 2000 );
    
    /* check the results */
    if( g_bFlag2 )
    {
        Trace( "ERROR:CtrlHandler2() was inexplicably called\n" );
        ret = FAIL;
        goto done;
    }
    
    if( ! g_bFlag1 )
    {
        Trace( "ERROR:CtrlHandler1() was not called but should have been\n" );
        ret = FAIL;
        goto done;
    }
    
    /* reset our flags */
    g_bFlag1 = FALSE;

    
    /* try to unset CtrlHandler2, which isn't set in the first place */
    if( SetConsoleCtrlHandler( CtrlHandler2, FALSE ) )
    {
        ret = FAIL;
        Trace( "ERROR:SetConsoleCtrlHandler() succeeded trying to "
                "remove CtrlHandler2, which isn't set\n" );
        goto done;
    }


    /* make sure that the existing control handler functions are still set */
    if( ! GenerateConsoleCtrlEvent( CTRL_C_EVENT, 0 ) )
    {
        Trace( "ERROR:%lu:GenerateConsoleCtrlEvent() failed\n",
                GetLastError() );
        ret = FAIL;
        goto done;
    }

    /* give the handlers a chance to execute */    
    Sleep( 2000 );
    
    /* check the results */
    if( g_bFlag2 )
    {
        Trace( "ERROR:CtrlHandler2() was inexplicably called\n" );
        ret = FAIL;
        goto done;
    }
    
    if( ! g_bFlag1 )
    {
        Trace( "ERROR:CtrlHandler1() was not called but should have been\n" );
        ret = FAIL;
        goto done;
    }
    
    
    
done:
    /* unset any handlers that were set */
    if( ! SetConsoleCtrlHandler( CtrlHandler1, FALSE ) )
    {
        ret = FAIL;
        Trace( "ERROR:%lu:SetConsoleCtrlHandler() failed to "
                "remove CtrlHandler1\n",
                GetLastError() );
        Fail( "Test failed\n" );
    }
    
    
    /* PAL termination */
    PAL_Terminate();

    
    /* return our result */
    return ret;
}
int smpd_parse_command_args(int *argcp, char **argvp[])
{
    int result = 0;
#ifdef HAVE_WINDOWS_H
    char str[20], read_handle_str[20], write_handle_str[20];
    int port;
    SMPDU_Sock_t listener;
    SMPDU_Sock_set_t set;
    HANDLE hWrite, hRead;
    DWORD num_written, num_read;
#endif
    int dbg_flag;
    char domain[SMPD_MAX_HOST_LENGTH];
    char opt[SMPD_MAX_NAME_LENGTH];
    char opt_val[SMPD_MAX_VALUE_LENGTH];
    char filename[SMPD_MAX_FILENAME];
    int i;

    smpd_enter_fn(FCNAME);

    /* check for help option */
    if (
#ifndef HAVE_WINDOWS_H
	*argcp < 2 || /* unix: print the options if no arguments are supplied */
#endif
	smpd_get_opt(argcp, argvp, "-help") || smpd_get_opt(argcp, argvp, "-?"))
    {
	smpd_print_options();
	smpd_exit(0);
    }

    /* check for the printprocs option */
    if (smpd_get_opt(argcp, argvp, "-printprocs"))
    {
	smpd_watch_processes();
	smpd_exit(0);
    }

    if (smpd_get_opt(argcp, argvp, "-hosts"))
    {
	char first_host[SMPD_MAX_HOST_LENGTH], host[SMPD_MAX_HOST_LENGTH], alt_host[SMPD_MAX_HOST_LENGTH];

	smpd_get_default_hosts();

	result = smpd_get_next_hostname(first_host, alt_host);
	if (result != SMPD_SUCCESS)
	    smpd_exit(result);
	printf("%s\n", first_host);
	result = smpd_get_next_hostname(host, alt_host);
	if (result != SMPD_SUCCESS)
	    smpd_exit(result);
	while (strcmp(host, first_host) != 0)
	{
	    printf("%s\n", host);
	    result = smpd_get_next_hostname(host, alt_host);
	    if (result != SMPD_SUCCESS)
		smpd_exit(result);
	}
	smpd_exit(0);
    }

    if (smpd_get_opt(argcp, argvp, "-sethosts"))
    {
	char *buffer, *iter;
	int i, length;

	length = (*argcp) * SMPD_MAX_HOST_LENGTH;
	buffer = MPIU_Malloc(length);
	if (buffer == NULL)
	{
	    smpd_err_printf("unable to allocate memory to store the host names.\n");
	    smpd_exit(-1);
	}
	iter = buffer;
	for (i=1; i<*argcp; i++)
	{
	    result = MPIU_Str_add_string(&iter, &length, (*argvp)[i]);
	    if (result)
	    {
		printf("unable to add host #%d, %s\n", i, (*argvp)[i]);
		MPIU_Free(buffer);
		smpd_exit(-1);
	    }
	}
	/*printf("hosts: %s\n", buffer);*/
	result = smpd_set_smpd_data("hosts", buffer);
	if (result == SMPD_SUCCESS)
	{
	    printf("hosts data saved successfully.\n");
	}
	else
	{
	    printf("Error: unable to save the hosts data.\n");
	}
	MPIU_Free(buffer);
	smpd_exit(0);
    }

    if (smpd_get_opt_two_strings(argcp, argvp, "-set", opt, SMPD_MAX_NAME_LENGTH, opt_val, SMPD_MAX_VALUE_LENGTH))
    {
	/* The do loop allows for multiple -set operations to be specified on the command line */
	do
	{
	    if (strlen(opt) == 0)
	    {
		printf("invalid option specified.\n");
		smpd_exit(-1);
	    }
	    if (strlen(opt_val) == 0)
	    {
		result = smpd_delete_smpd_data(opt);
	    }
	    else
	    {
		result = smpd_set_smpd_data(opt, opt_val);
	    }
	    if (result == SMPD_SUCCESS)
	    {
		printf("%s = %s\n", opt, opt_val);
	    }
	    else
	    {
		printf("unable to set %s option.\n", opt);
	    }
	} while (smpd_get_opt_two_strings(argcp, argvp, "-set", opt, SMPD_MAX_NAME_LENGTH, opt_val, SMPD_MAX_VALUE_LENGTH));
	smpd_exit(0);
    }

    if (smpd_get_opt_string(argcp, argvp, "-get", opt, SMPD_MAX_NAME_LENGTH))
    {
	if (strlen(opt) == 0)
	{
	    printf("invalid option specified.\n");
	    smpd_exit(-1);
	}
	result = smpd_get_smpd_data(opt, opt_val, SMPD_MAX_VALUE_LENGTH);
	if (result == SMPD_SUCCESS)
	{
	    printf("%s\n", opt_val);
	}
	else
	{
	    printf("default\n");
	}
	smpd_exit(0);
    }

    /* If we've made it here and there still is "-set" or "-get" on the command line then the user
     * probably didn't supply the correct number of parameters.  So print the usage message
     * and exit.
     */
    if (smpd_get_opt(argcp, argvp, "-set") || smpd_get_opt(argcp, argvp, "-get"))
    {
	smpd_print_options();
	smpd_exit(-1);
    }

    if (smpd_get_opt(argcp, argvp, "-enumerate") || smpd_get_opt(argcp, argvp, "-enum"))
    {
	smpd_data_t *data;
	if (smpd_get_all_smpd_data(&data) == SMPD_SUCCESS)
	{
	    smpd_data_t *iter = data;
	    while (iter != NULL)
	    {
		printf("%s\n%s\n", iter->name, iter->value);
		iter = iter->next;
	    }
	    while (data != NULL)
	    {
		iter = data;
		data = data->next;
		MPIU_Free(iter);
	    }
	}
	smpd_exit(0);
    }

    if (smpd_get_opt_string(argcp, argvp, "-query", domain, SMPD_MAX_HOST_LENGTH))
    {
	printf("querying hosts in the %s domain:\n", domain);
	printf("Not implemented.\n");
	smpd_exit(0);
    }
    if (smpd_get_opt(argcp, argvp, "-query"))
    {
	printf("querying hosts in the default domain:\n");
	printf("Not implemented.\n");
	smpd_exit(0);
    }

    /* check for the service/silent option */
#ifdef HAVE_WINDOWS_H
    smpd_process.bService = SMPD_TRUE;
#endif

    if (smpd_get_opt(argcp, argvp, "-s"))
    {
#ifdef HAVE_WINDOWS_H
	printf("The -s option is only available under unix.\n");
	smpd_print_options();
	smpd_exit(0);
#else
	smpd_process.bNoTTY = SMPD_TRUE;
#endif
    }

    if (smpd_get_opt(argcp, argvp, "-r"))
    {
#ifdef HAVE_WINDOWS_H
	printf("The -r option is only available under unix.\n");
	smpd_print_options();
#else
	printf("The -r root option is not yet implemented.\n");
#endif
	smpd_exit(0);
    }

    /* check for debug option */
    if (smpd_get_opt_int(argcp, argvp, "-d", &dbg_flag))
    {
	smpd_process.dbg_state = dbg_flag;
	smpd_process.bNoTTY = SMPD_FALSE;
	smpd_process.bService = SMPD_FALSE;
    }
    if (smpd_get_opt(argcp, argvp, "-d"))
    {
	smpd_process.dbg_state = SMPD_DBG_STATE_ERROUT | SMPD_DBG_STATE_STDOUT | SMPD_DBG_STATE_PREPEND_RANK | SMPD_DBG_STATE_TRACE;
	smpd_process.bNoTTY = SMPD_FALSE;
	smpd_process.bService = SMPD_FALSE;
    }
    if (smpd_get_opt_int(argcp, argvp, "-debug", &dbg_flag))
    {
	smpd_process.dbg_state = dbg_flag;
	smpd_process.bNoTTY = SMPD_FALSE;
	smpd_process.bService = SMPD_FALSE;
    }
    if (smpd_get_opt(argcp, argvp, "-debug"))
    {
	smpd_process.dbg_state = SMPD_DBG_STATE_ERROUT | SMPD_DBG_STATE_STDOUT | SMPD_DBG_STATE_PREPEND_RANK | SMPD_DBG_STATE_TRACE;
	smpd_process.bNoTTY = SMPD_FALSE;
	smpd_process.bService = SMPD_FALSE;
    }

    /* check for port option */
    smpd_get_opt_int(argcp, argvp, "-p", &smpd_process.port);
    smpd_get_opt_int(argcp, argvp, "-port", &smpd_process.port);
    if (smpd_get_opt(argcp, argvp, "-anyport"))
    {
	smpd_process.port = 0;
	smpd_process.dbg_state = 0; /* turn of debugging or you won't be able to read the port from stdout */
	smpd_process.bNoTTY = SMPD_FALSE;
	smpd_process.bService = SMPD_FALSE;
    }

    smpd_process.noprompt = smpd_get_opt(argcp, argvp, "-noprompt");

#ifdef HAVE_WINDOWS_H

    /* check for service options */
    if (smpd_get_opt(argcp, argvp, "-remove") ||
	smpd_get_opt(argcp, argvp, "-unregserver") ||
	smpd_get_opt(argcp, argvp, "-uninstall") ||
	smpd_get_opt(argcp, argvp, "/Remove") ||
	smpd_get_opt(argcp, argvp, "/Uninstall"))
    {
	/*RegDeleteKey(HKEY_CURRENT_USER, MPICHKEY);*/
	smpd_remove_service(SMPD_TRUE);
	ExitProcess(0);
    }
    if (smpd_get_opt(argcp, argvp, "-install") ||
	smpd_get_opt(argcp, argvp, "-regserver") ||
	smpd_get_opt(argcp, argvp, "/Install") ||
	smpd_get_opt(argcp, argvp, "/install") ||
	smpd_get_opt(argcp, argvp, "/RegServer"))
    {
	char phrase[SMPD_PASSPHRASE_MAX_LENGTH]="", port_str[SMPD_MAX_PORT_STR_LENGTH]="";

	if (smpd_remove_service(SMPD_FALSE) == SMPD_FALSE)
	{
	    printf("Unable to remove the previous installation, install failed.\n");
	    ExitProcess(0);
	}

	if (smpd_get_opt_string(argcp, argvp, "-phrase", phrase, SMPD_PASSPHRASE_MAX_LENGTH) ||
	    smpd_get_win_opt_string(argcp, argvp, "/phrase", phrase, SMPD_PASSPHRASE_MAX_LENGTH))
	{
	    smpd_set_smpd_data("phrase", phrase);
	}
	if (smpd_get_opt(argcp, argvp, "-getphrase"))
	{
	    printf("passphrase for smpd: ");fflush(stdout);
	    smpd_get_password(phrase);
	    smpd_set_smpd_data("phrase", phrase);
	}
	if (smpd_process.port != SMPD_LISTENER_PORT)
	{
        snprintf(port_str, SMPD_MAX_PORT_STR_LENGTH, "%d", smpd_process.port);
	    smpd_set_smpd_data("port", port_str);
	}

	smpd_install_service(SMPD_FALSE, SMPD_TRUE, smpd_get_opt(argcp, argvp, "-delegation"));
	smpd_set_smpd_data("version", SMPD_VERSION);
	ExitProcess(0);
    }
    if (smpd_get_opt(argcp, argvp, "-start"))
    {
	smpd_start_service();
	ExitProcess(0);
    }
    if (smpd_get_opt(argcp, argvp, "-stop"))
    {
	smpd_stop_service();
	ExitProcess(0);
    }
    if (smpd_get_opt(argcp, argvp, "-register_spn"))
    {
        char filename[SMPD_MAX_FILENAME];

        if(smpd_get_opt_string(argcp, argvp, "-f", filename, SMPD_MAX_FILENAME)){
            result = smpd_setup_scps_with_file(filename);
            if(result != SMPD_SUCCESS){
                printf("Failed to register smpd's Service Principal Names (at least one failed) with Domain Controller\n");
                ExitProcess((UINT )-1);
            }
        }
        else{
            result = smpd_setup_scp(NULL);
            if(result != SMPD_SUCCESS){
                printf("Failed to register smpd's Service Principal Name with Domain Controller\n");
                ExitProcess((UINT )-1);
            }
        }
        printf("Service Principal Name registered with the domain controller.\n");
        printf("SMPD is now capable of launching processes using passwordless delegation.\n");
        printf("The system administrator must ensure the following:\n");
        printf(" 1) This host is trusted for delegation in Active Directory\n");
        printf(" 2) All users who will run jobs are trusted for delegation.\n");
        printf("Domain administrators can enable these options for hosts and users\nin Active Directory on the domain controller.\n");
        ExitProcess(0);
    }
    if (smpd_get_opt(argcp, argvp, "-remove_spn"))
    {
        char filename[SMPD_MAX_FILENAME];
        smpd_spn_list_hnd_t hnd;

        result = smpd_spn_list_init(&hnd);
        if(result != SMPD_SUCCESS){
            printf("Unable to initialize SPN list\n");
            ExitProcess((UINT ) -1);
        }

        if(smpd_get_opt_string(argcp, argvp, "-f", filename, SMPD_MAX_FILENAME)){
            result = smpd_remove_scps_with_file(filename, hnd);
            if(result != SMPD_SUCCESS){
                printf("Failed to remove smpd's Service Principal Names (at least one failed) with Domain Controller\n");
                ExitProcess((UINT )-1);
            }
            printf("Removed smpd's Service Principal Names successfully\n");
        }
        else{
            result = smpd_remove_scp(NULL, hnd);
            if(result != SMPD_SUCCESS){
                printf("Failed to remove smpd's Service Principal Name with Domain Controller\n");
                ExitProcess((UINT )-1);
            }
            printf("Removed smpd's Service Principal Name successfully\n");
        }
        smpd_spn_list_finalize(&hnd);
        ExitProcess(0);
    }

    if (smpd_get_opt(argcp, argvp, "-mgr"))
    {
	/* Set a ctrl-handler to kill child processes if this smpd is killed */
	if (!SetConsoleCtrlHandler(smpd_ctrl_handler, TRUE))
	{
	    result = GetLastError();
	    smpd_dbg_printf("unable to set the ctrl handler for the smpd manager, error %d.\n", result);
	}
#ifdef HAVE_WINDOWS_H
    {
        BOOL ret;
        ret = smpd_init_affinity_table();
        if(!ret){
            smpd_dbg_printf("Initializing smpd affinity table failed\n");
        }
    }
#endif

	smpd_process.bService = SMPD_FALSE;
	if (!smpd_get_opt_string(argcp, argvp, "-read", read_handle_str, 20))
	{
	    smpd_err_printf("manager started without a read pipe handle.\n");
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	if (!smpd_get_opt_string(argcp, argvp, "-write", write_handle_str, 20))
	{
	    smpd_err_printf("manager started without a write pipe handle.\n");
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	hRead = smpd_decode_handle(read_handle_str);
	hWrite = smpd_decode_handle(write_handle_str);

	smpd_dbg_printf("manager creating listener and session sets.\n");

	result = SMPDU_Sock_create_set(&set);
	if (result != SMPD_SUCCESS)
	{
	    smpd_err_printf("SMPDU_Sock_create_set(listener) failed,\nsock error: %s\n", get_sock_error_string(result));
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	smpd_process.set = set;
	smpd_dbg_printf("created set for manager listener, %d\n", SMPDU_Sock_get_sock_set_id(set));
	port = 0;
	result = SMPDU_Sock_listen(set, NULL, &port, &listener); 
	if (result != SMPD_SUCCESS)
	{
	    smpd_err_printf("SMPDU_Sock_listen failed,\nsock error: %s\n", get_sock_error_string(result));
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	smpd_dbg_printf("smpd manager listening on port %d\n", port);

	result = smpd_create_context(SMPD_CONTEXT_LISTENER, set, listener, -1, &smpd_process.listener_context);
	if (result != SMPD_SUCCESS)
	{
	    smpd_err_printf("unable to create a context for the smpd listener.\n");
	    smpd_exit_fn(FCNAME);
	    return result;
	}
	result = SMPDU_Sock_set_user_ptr(listener, smpd_process.listener_context);
	if (result != SMPD_SUCCESS)
	{
	    smpd_err_printf("SMPDU_Sock_set_user_ptr failed,\nsock error: %s\n", get_sock_error_string(result));
	    smpd_exit_fn(FCNAME);
	    return result;
	}
	smpd_process.listener_context->state = SMPD_MGR_LISTENING;

	memset(str, 0, 20);
	snprintf(str, 20, "%d", port);
	smpd_dbg_printf("manager writing port back to smpd.\n");
	if (!WriteFile(hWrite, str, 20, &num_written, NULL))
	{
	    smpd_err_printf("WriteFile failed, error %d\n", GetLastError());
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	CloseHandle(hWrite);
	if (num_written != 20)
	{
	    smpd_err_printf("wrote only %d bytes of 20\n", num_written);
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	smpd_dbg_printf("manager reading account and password from smpd.\n");
	if (!ReadFile(hRead, smpd_process.UserAccount, SMPD_MAX_ACCOUNT_LENGTH, &num_read, NULL))
	{
	    smpd_err_printf("ReadFile failed, error %d\n", GetLastError());
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	if (num_read != SMPD_MAX_ACCOUNT_LENGTH)
	{
	    smpd_err_printf("read only %d bytes of %d\n", num_read, SMPD_MAX_ACCOUNT_LENGTH);
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	if (!ReadFile(hRead, smpd_process.UserPassword, SMPD_MAX_PASSWORD_LENGTH, &num_read, NULL))
	{
	    smpd_err_printf("ReadFile failed, error %d\n", GetLastError());
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	if (num_read != SMPD_MAX_PASSWORD_LENGTH)
	{
	    smpd_err_printf("read only %d bytes of %d\n", num_read, SMPD_MAX_PASSWORD_LENGTH);
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	if (!ReadFile(hRead, smpd_process.passphrase, SMPD_PASSPHRASE_MAX_LENGTH, &num_read, NULL))
	{
	    smpd_err_printf("ReadFile failed, error %d\n", GetLastError());
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	if (num_read != SMPD_PASSPHRASE_MAX_LENGTH)
	{
	    smpd_err_printf("read only %d bytes of %d\n", num_read, SMPD_PASSPHRASE_MAX_LENGTH);
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	smpd_process.credentials_prompt = SMPD_FALSE;

	result = smpd_enter_at_state(set, SMPD_MGR_LISTENING);
	if (result != SMPD_SUCCESS)
	{
	    smpd_err_printf("state machine failed.\n");
	}

	/*
	result = SMPDU_Sock_finalize();
	if (result != SMPD_SUCCESS)
	{
	    smpd_err_printf("SMPDU_Sock_finalize failed,\nsock error: %s\n", get_sock_error_string(result));
	}
	*/
	smpd_exit(0);
	smpd_exit_fn(FCNAME);
	ExitProcess(0);
    }
#endif

    /* check for the status option */
    if (smpd_get_opt_string(argcp, argvp, "-status", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
    {
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_DO_STATUS;
    }
    else if (smpd_get_opt(argcp, argvp, "-status"))
    {
	smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_DO_STATUS;
    }

    /* check for console options */
    if (smpd_get_opt_string(argcp, argvp, "-console", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
    {
	smpd_process.do_console = 1;
    }
    else if (smpd_get_opt(argcp, argvp, "-console"))
    {
	smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	smpd_process.do_console = 1;
    }
    if (smpd_process.do_console)
    {
	/* This may need to be changed to avoid conflict */
	if (smpd_get_opt(argcp, argvp, "-p"))
	{
	    smpd_process.use_process_session = 1;
	}
    }

    if (smpd_get_opt_string(argcp, argvp, "-shutdown", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
    {
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_SHUTDOWN;
    }
    else if (smpd_get_opt(argcp, argvp, "-shutdown"))
    {
	smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_SHUTDOWN;
    }

    if (smpd_get_opt_string(argcp, argvp, "-restart", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
    {
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_RESTART;
    }
    else if (smpd_get_opt(argcp, argvp, "-restart"))
    {
#ifdef HAVE_WINDOWS_H
	printf("restarting the smpd service...\n");
	smpd_stop_service();
	Sleep(1000);
	smpd_start_service();
	smpd_exit(0);
#else
	smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_RESTART;
#endif
    }

    if (smpd_get_opt_string(argcp, argvp, "-version", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
    {
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_VERSION;
    }
    else if (smpd_get_opt(argcp, argvp, "-version"))
    {
	printf("%s\n", SMPD_VERSION);
	fflush(stdout);
	smpd_exit(0);
    }

    /* These commands are handled by mpiexec although doing them here is an alternate solution.
    if (smpd_get_opt_two_strings(argcp, argvp, "-add_job", smpd_process.job_key, SMPD_MAX_NAME_LENGTH, smpd_process.job_key_account, SMPD_MAX_ACCOUNT_LENGTH))
    {
	if (!smpd_get_opt_string(argcp, argvp, "-host", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
	    smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	if (smpd_get_opt_string(argcp, argvp, "-password", smpd_process.job_key_password, SMPD_MAX_PASSWORD_LENGTH)
	    smpd_process.builtin_cmd = SMPD_CMD_ADD_JOB_KEY_AND_PASSWORD;
	else
	    smpd_process.builtin_cmd = SMPD_CMD_ADD_JOB_KEY;
	smpd_process.do_console = 1;
    }

    if (smpd_get_opt_string(argcp, argvp, "-remove_job", smpd_process.job_key, SMPD_MAX_NAME_LENGTH))
    {
	if (!smpd_get_opt_string(argcp, argvp, "-host", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
	    smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_REMOVE_JOB_KEY;
    }

    if (smpd_get_opt_string(argcp, argvp, "-associate_job", smpd_process.job_key, SMPD_MAX_NAME_LENGTH))
    {
	if (!smpd_get_opt_string(argcp, argvp, "-host", smpd_process.console_host, SMPD_MAX_HOST_LENGTH))
	    smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	smpd_process.do_console = 1;
	smpd_process.builtin_cmd = SMPD_CMD_ASSOCIATE_JOB_KEY;
    }
    */

    smpd_get_opt_string(argcp, argvp, "-phrase", smpd_process.passphrase, SMPD_PASSPHRASE_MAX_LENGTH);
    if (smpd_get_opt(argcp, argvp, "-getphrase"))
    {
	printf("passphrase for smpd: ");fflush(stdout);
	smpd_get_password(smpd_process.passphrase);
    }

    if (smpd_get_opt_string(argcp, argvp, "-smpdfile", smpd_process.smpd_filename, SMPD_MAX_FILENAME))
    {
	struct stat s;

	if (stat(smpd_process.smpd_filename, &s) == 0)
	{
	    if (s.st_mode & 00077)
	    {
		printf(".smpd file cannot be readable by anyone other than the current user.\n");
		smpd_exit_fn(FCNAME);
		return SMPD_FAIL;
	    }
	}
    }

    if (smpd_get_opt_string(argcp, argvp, "-traceon", filename, SMPD_MAX_FILENAME))
    {
	smpd_process.do_console_returns = SMPD_TRUE;
	if (*argcp > 1)
	{
	    for (i=1; i<*argcp; i++)
	    {
		strcpy(smpd_process.console_host, (*argvp)[i]);

		smpd_process.do_console = 1;
		smpd_process.builtin_cmd = SMPD_CMD_SET;
		strcpy(smpd_process.key, "logfile");
		strcpy(smpd_process.val, filename);
		result = smpd_do_console();
		if (result != SMPD_SUCCESS)
		{
		    smpd_err_printf("Unable to set the logfile name on host '%s'\n", smpd_process.console_host);
		    smpd_exit_fn(FCNAME);
		    return result;
		}

		smpd_process.do_console = 1;
		smpd_process.builtin_cmd = SMPD_CMD_SET;
		strcpy(smpd_process.key, "log");
		strcpy(smpd_process.val, "yes");
		result = smpd_do_console();
		if (result != SMPD_SUCCESS)
		{
		    smpd_err_printf("Unable to set the log option on host '%s'\n", smpd_process.console_host);
		    smpd_exit_fn(FCNAME);
		    return result;
		}

		smpd_process.do_console = 1;
		smpd_process.builtin_cmd = SMPD_CMD_RESTART;
		result = smpd_do_console();
		if (result != SMPD_SUCCESS)
		{
		    smpd_err_printf("Unable to restart the smpd on host '%s'\n", smpd_process.console_host);
		    smpd_exit_fn(FCNAME);
		    return result;
		}
	    }
	}
	else
	{
	    result = smpd_set_smpd_data("logfile", filename);
	    result = smpd_set_smpd_data("log", "yes");

#ifdef HAVE_WINDOWS_H
	    printf("restarting the smpd service...\n");
	    smpd_stop_service();
	    Sleep(1000);
	    smpd_start_service();
#else
	    smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	    smpd_process.do_console = 1;
	    smpd_process.builtin_cmd = SMPD_CMD_RESTART;
	    result = smpd_do_console();
	    if (result != SMPD_SUCCESS)
	    {
		smpd_err_printf("Unable to restart the smpd on host '%s'\n", smpd_process.console_host);
		smpd_exit_fn(FCNAME);
		return result;
	    }
#endif
	}
	smpd_exit_fn(FCNAME);
	smpd_exit(result);
    }

    if (smpd_get_opt(argcp, argvp, "-traceoff"))
    {
	smpd_process.do_console_returns = SMPD_TRUE;
	if (*argcp > 1)
	{
	    for (i=1; i<*argcp; i++)
	    {
		strcpy(smpd_process.console_host, (*argvp)[i]);

		smpd_process.do_console = 1;
		smpd_process.builtin_cmd = SMPD_CMD_SET;
		strcpy(smpd_process.key, "log");
		strcpy(smpd_process.val, "no");
		result = smpd_do_console();
		if (result != SMPD_SUCCESS)
		{
		    smpd_err_printf("Unable to set the log option on host '%s'\n", smpd_process.console_host);
		    smpd_exit_fn(FCNAME);
		    return result;
		}

		smpd_process.do_console = 1;
		smpd_process.builtin_cmd = SMPD_CMD_RESTART;
		result = smpd_do_console();
		if (result != SMPD_SUCCESS)
		{
		    smpd_err_printf("Unable to restart the smpd on host '%s'\n", smpd_process.console_host);
		    smpd_exit_fn(FCNAME);
		    return result;
		}
	    }
	}
	else
	{
	    result = smpd_set_smpd_data("log", "no");

#ifdef HAVE_WINDOWS_H
	    printf("restarting the smpd service...\n");
	    smpd_stop_service();
	    Sleep(1000);
	    smpd_start_service();
#else
	    smpd_get_hostname(smpd_process.console_host, SMPD_MAX_HOST_LENGTH);
	    smpd_process.do_console = 1;
	    smpd_process.builtin_cmd = SMPD_CMD_RESTART;
	    result = smpd_do_console();
	    if (result != SMPD_SUCCESS)
	    {
		smpd_err_printf("Unable to restart the smpd on host '%s'\n", smpd_process.console_host);
		smpd_exit_fn(FCNAME);
		return result;
	    }
#endif
	}
	smpd_exit_fn(FCNAME);
	smpd_exit(result);
    }

    if (smpd_process.do_console)
    {
	result = smpd_do_console();
	smpd_exit_fn(FCNAME);
	return result;
    }

    smpd_exit_fn(FCNAME);
    return SMPD_SUCCESS;
}
Beispiel #15
0
static void cevents_init()
{
	if (SetConsoleCtrlHandler(console_handler,TRUE)==FALSE)
		ShowWarning ("Unable to install the console handler!\n");
}
Beispiel #16
0
/*
 * Function: initDefaultHandlers()
 *
 * Install any default signal/console handlers. Currently we install a
 * Ctrl+C handler that shuts down the RTS in an orderly manner.
 */
void initDefaultHandlers(void)
{
    if ( !SetConsoleCtrlHandler(shutdown_handler, true) ) {
        errorBelch("warning: failed to install default console handler");
    }
}
Beispiel #17
0
void restore_signals(void)
{
    SetConsoleCtrlHandler(NULL, 0); //turn on ctrl-c handler
}
Beispiel #18
0
void resetDefaultHandlers(void)
{
    if ( !SetConsoleCtrlHandler(shutdown_handler, false) ) {
        errorBelch("warning: failed to uninstall default console handler");
    }
}
Beispiel #19
0
int main(int argc, char **argv)
{
	int ds, dms, ret;
	double mb, rmb;
	struct timeval t1, t2;
#ifndef _WIN32
	sigset_t sigset;
#endif
	struct optstruct *opts;
	const struct optstruct *opt;

    if(check_flevel())
	exit(2);

#if !defined(_WIN32) && !defined(C_BEOS)
    sigemptyset(&sigset);
    sigaddset(&sigset, SIGXFSZ);
    sigprocmask(SIG_SETMASK, &sigset, NULL);
#endif


    if((opts = optparse(NULL, argc, argv, 1, OPT_CLAMSCAN, 0, NULL)) == NULL) {
	mprintf("!Can't parse command line options\n");
	return 2;
    }

    if(optget(opts, "verbose")->enabled) {
	mprintf_verbose = 1;
	logg_verbose = 1;
    }

    if(optget(opts, "quiet")->enabled)
	mprintf_quiet = 1;

    if(optget(opts, "stdout")->enabled)
	mprintf_stdout = 1;


    if(optget(opts, "debug")->enabled) {
#if defined(C_LINUX)
	    /* [email protected]: create a dump if needed */
	    struct rlimit rlim;

	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
	if(setrlimit(RLIMIT_CORE, &rlim) < 0)
	    perror("setrlimit");
#endif
	cl_debug(); /* enable debug messages */
    }

    if(optget(opts, "version")->enabled) {
	print_version(optget(opts, "database")->strarg);
	optfree(opts);
	return 0;
    }

    if(optget(opts, "help")->enabled) {
	optfree(opts);
    	help();
	return 0;
    }

    if(optget(opts, "recursive")->enabled)
	recursion = 1;

    if(optget(opts, "infected")->enabled)
	printinfected = 1;

    if(optget(opts, "bell")->enabled)
	bell = 1;

    /* initialize logger */
    if((opt = optget(opts, "log"))->enabled) {
	logg_file = opt->strarg;
	if(logg("#\n-------------------------------------------------------------------------------\n\n")) {
	    mprintf("!Problem with internal logger.\n");
	    optfree(opts);
	    return 2;
	}
    } else 
	logg_file = NULL;

    if(actsetup(opts)) {
	optfree(opts);
	logg_close();
	exit(2);
    }

    memset(&info, 0, sizeof(struct s_info));

#ifdef _WIN32
    if(optget(opts, "no-summary")->enabled)
        SetConsoleCtrlHandler(cw_stop_ctrl_handler, FALSE);
#endif

    gettimeofday(&t1, NULL);

    ret = scanmanager(opts);

    if(!optget(opts, "no-summary")->enabled) {
	gettimeofday(&t2, NULL);

    ds = t2.tv_sec - t1.tv_sec;
	dms = t2.tv_usec - t1.tv_usec;
	ds -= (dms < 0) ? (1):(0);
	dms += (dms < 0) ? (1000000):(0);
	logg("\n----------- SCAN SUMMARY -----------\n");
	logg("Known viruses: %u\n", info.sigs);
	logg("Engine version: %s\n", get_version());
	logg("Scanned directories: %u\n", info.dirs);
	logg("Scanned files: %u\n", info.files);
	logg("Infected files: %u\n", info.ifiles);
	if(info.errors)
	    logg("Total errors: %u\n", info.errors);
	if(notremoved) {
	    logg("Not removed: %u\n", notremoved);
	}
	if(notmoved) {
	    logg("Not %s: %u\n", optget(opts, "copy")->enabled ? "moved" : "copied", notmoved);
	}
	mb = info.blocks * (CL_COUNT_PRECISION / 1024) / 1024.0;
	logg("Data scanned: %2.2lf MB\n", mb);
	rmb = info.rblocks * (CL_COUNT_PRECISION / 1024) / 1024.0;
	logg("Data read: %2.2lf MB (ratio %.2f:1)\n", rmb, info.rblocks ? (double)info.blocks/(double)info.rblocks : 0);
	logg("Time: %u.%3.3u sec (%u m %u s)\n", ds, dms/1000, ds/60, ds%60);
    }

    optfree(opts);

    return ret;
}
Beispiel #20
0
static void handle_signals(void)
{
    SetConsoleCtrlHandler(signal_handler, TRUE);
}
Beispiel #21
0
void remove_ctrlc(void)
{
    SetConsoleCtrlHandler( handle_ctrlc, FALSE );
}
Beispiel #22
0
int main(int argc, char** argv) {
	enum {
		 envbufsize = 1024*32
		,exebufsize = 1024
		,cmdbufsize = envbufsize
	};

	char *envbuf, *sep, *resbuf, *cmdbuf;
	DWORD len, exitCode;
	STARTUPINFO si;
	PROCESS_INFORMATION pi;

	DIE_IF_FALSE(
		(envbuf = malloc(envbufsize))
	);
	DIE_IF_FALSE(
		(cmdbuf = malloc(cmdbufsize))
	);
	*cmdbuf = 0;

	DIE_IF_FALSE(
		GetEnvironmentVariable("PATH", envbuf, envbufsize)
	);
    dbg_printf("env: %s\n", envbuf);

	DIE_IF_FALSE(
		GetModuleFileName(0, cmdbuf, exebufsize)
	);
    dbg_printf("curdir: %s\n", cmdbuf);

	DIE_IF_FALSE(
		(sep = strrchr(cmdbuf, '\\'))
	);
	*(sep+1) = 0;
	strcat(cmdbuf, GDB_TO_PYTHON_REL_DIR);
	dbg_printf("sep: %s\n", cmdbuf);

	len = strlen(envbuf)+strlen(cmdbuf)
		+1  /* for envronment separator */
		+1; /* for zero-terminator */
	
	DIE_IF_FALSE(
		(resbuf = malloc(len))
	);

	DIE_IF_FALSE(
		(snprintf(resbuf, len, "%s;%s", cmdbuf, envbuf) > 0)
	);
    dbg_printf("PATH: %s\n", resbuf);

	DIE_IF_FALSE(
		SetEnvironmentVariable("PATH", resbuf)
	);

	*(sep+1) = 0;
	strcat(cmdbuf, PYTHONHOME_REL_DIR);
	dbg_printf("PYTHONHOME: %s\n", cmdbuf);
	DIE_IF_FALSE(
		SetEnvironmentVariable("PYTHONHOME", cmdbuf)
	);
	
	*(sep+1) = 0;
	strcat(cmdbuf, GDB_EXECUTABLE_ORIG_FILENAME" ");
	
	if ( argc > 1 ) {
		for ( ++argv; *argv; ++argv ) {
			len = strlen(cmdbuf);
			snprintf(cmdbuf+len, cmdbufsize-len, "%s ", *argv);
		}
	}
	dbg_printf("cmd: %s\n", cmdbuf);

	HANDLE ghJob = CreateJobObject(NULL, "Gdb-Wrapper\0"/*NULL*/);
	if ( ghJob == NULL ) {
		dbg_printf("Could not create job object\n");
	} else {
		JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
		// Configure all child processes associated with the job to terminate when the last handle to the job is closed
		jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
		if ( SetInformationJobObject(ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)) == 0 ) {
			dbg_printf("Could not SetInformationJobObject\n");
		}
	}

	memset(&si, 0, sizeof(si));
	si.cb = sizeof(si);
	si.dwFlags |= STARTF_USESTDHANDLES;
	si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
	si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	si.hStdError = GetStdHandle(STD_ERROR_HANDLE);

	memset(&pi, 0, sizeof(pi));

	DIE_IF_FALSE(
		CreateProcess(
			 0			// exe name
			,cmdbuf	// command line
			,0			// process security attributes
			,0			// primary thread security attributes
			,TRUE		// handles are inherited
			,0			// creation flags
			,0			// use parent's environment
			,0			// use parent's current directory
			,&si		// STARTUPINFO pointer
			,&pi		// receives PROCESS_INFORMATION
		)
	);

	if ( ghJob != NULL && AssignProcessToJobObject(ghJob, pi.hProcess) == 0 ) {
		dbg_printf("Could not AssignProcessToObject\n");
	}

	// Do not handle Ctrl-C in the wrapper
	SetConsoleCtrlHandler(NULL, TRUE);

	WaitForSingleObject(pi.hProcess, INFINITE);
	
	DIE_IF_FALSE(
		GetExitCodeProcess(pi.hProcess, &exitCode)
	);

	if ( ghJob != NULL )
		CloseHandle(ghJob);
	CloseHandle( pi.hProcess );
	CloseHandle( pi.hThread );

	free(envbuf);
	free(resbuf);
	free(cmdbuf);
	
	dbg_printf("exiting with exitCode %d", exitCode);

	return exitCode;
}
Beispiel #23
0
void signal_handler_init(void)
{
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
}
Beispiel #24
0
/* main entry point function */
int __cdecl main( int argc, char **argv ) 

{
    /* local variables */
    int     i;
    BOOL    ret = PASS;
    BOOL    bSetFinalHandler = FALSE;
    int     nSetCount = 0;


    /* PAL initialization */
    if( (PAL_Initialize(argc, argv)) != 0 )
    {
        return( FAIL );
    }


    /* set our final console control handler function */
    if( SetConsoleCtrlHandler( FinalCtrlHandler, TRUE ) )
    {
        bSetFinalHandler = TRUE;
    }
    else
    {
        ret = FAIL;
        Trace( "ERROR:%lu:SetConsoleCtrlHandler() failed to add "
                "FinalCtrlHandler\n",
                GetLastError() );
        Fail( "Test failed\n" );
    }
    
    /* try to set our test handler multiple times */
    for( i=0; i<HANDLER_SET_COUNT; i++ )
    {
        if( SetConsoleCtrlHandler( CtrlHandler1, TRUE ) )
        {
            nSetCount++;
        }
        else
        {
            ret = FAIL;
            Trace( "ERROR:%lu:SetConsoleCtrlHandler() failed to add "
                    "CtrlHandler1 at attempt #%d\n",
                    GetLastError(),
                    i );
            goto done;
        }
    }

    /* loop here -- generate an event and verify that our handler */
    /* was called the correct number of times, then unset it one  */
    /* time and repeat until it's completely unset.               */
    for( ; nSetCount>0; nSetCount-- )
    {
        /* test that the control handler functions are set */
        if( ! GenerateConsoleCtrlEvent( CTRL_C_EVENT, 0 ) )
        {
            Trace( "ERROR:%lu:GenerateConsoleCtrlEvent() failed\n",
                    GetLastError() );
            ret = FAIL;
            goto done;
        }
    
        /* give the handlers a chance to execute */    
        Sleep( 2000 );
        
        /* check the results */
        if( g_count != nSetCount )
        {
            Trace( "ERROR:CtrlHandler1() was not called %d times, "
                    "expected %d\n",
                    g_count,
                    nSetCount );
            ret = FAIL;
            goto done;
        }
        
        /* unset the control handler one time */
        if( ! SetConsoleCtrlHandler( CtrlHandler1, FALSE ) )
        {
            ret = FAIL;
            Trace( "ERROR:%lu:SetConsoleCtrlHandler() failed to "
                    "remove CtrlHandler instance #%d\n",
                    GetLastError(),
                    nSetCount );
            Fail( "Test failed\n" );
        }
        
        /* reset our counter */
        g_count = 0;
    }
    
    
    
done:
    /* unset any lingering instances of our test control handler */
    for( ; nSetCount>0; nSetCount-- )
    {
        /* unset the control handler one time */
        if( ! SetConsoleCtrlHandler( CtrlHandler1, FALSE ) )
        {
            ret = FAIL;
            Trace( "ERROR:%lu:SetConsoleCtrlHandler() failed to "
                    "remove CtrlHandler instance #%d\n",
                    GetLastError(),
                    nSetCount );
            Fail( "Test failed\n" );
        }
    }
    
    
    /* unset our final control handler if it was set */
    if( bSetFinalHandler )
    {
        if( ! SetConsoleCtrlHandler( FinalCtrlHandler, FALSE ) )
        {
            ret = FAIL;
            Trace( "ERROR:%lu:SetConsoleCtrlHandler() failed to "
                    "remove FinalCtrlHandler\n",
                    GetLastError() );
            Fail( "Test failed\n" );
        }
    }
    
    
    /* PAL termination */
    PAL_Terminate();

    
    /* return our result */
    return ret;
}
int adb_main(int is_daemon, int server_port)
{
#if !ADB_HOST
    int port;
    char value[PROPERTY_VALUE_MAX];

    umask(000);
#endif

    atexit(adb_cleanup);
#ifdef HAVE_WIN32_PROC
    SetConsoleCtrlHandler( ctrlc_handler, TRUE );
#elif defined(HAVE_FORKEXEC)
    // No SIGCHLD. Let the service subproc handle its children.
    signal(SIGPIPE, SIG_IGN);
#endif

    init_transport_registration();


#if ADB_HOST
    HOST = 1;
    usb_vendors_init();
    usb_init();
    local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);

    char local_name[30];
    build_local_name(local_name, sizeof(local_name), server_port);
    if(install_listener(local_name, "*smartsocket*", NULL)) {
        exit(1);
    }
#else

    /* don't listen on a port (default 5037) if running in secure mode */
    /* don't run as root if we are running in secure mode */
    if (should_drop_privileges()) {
        struct __user_cap_header_struct header;
        struct __user_cap_data_struct cap;

        if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
            exit(1);
        }

        /* add extra groups:
        ** AID_ADB to access the USB driver
        ** AID_LOG to read system logs (adb logcat)
        ** AID_INPUT to diagnose input issues (getevent)
        ** AID_INET to diagnose network issues (netcfg, ping)
        ** AID_GRAPHICS to access the frame buffer
        ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
        ** AID_SDCARD_R to allow reading from the SD card
        ** AID_SDCARD_RW to allow writing to the SD card
        ** AID_MOUNT to allow unmounting the SD card before rebooting
        ** AID_NET_BW_STATS to read out qtaguid statistics
        */
        gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
                           AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
                           AID_MOUNT, AID_NET_BW_STATS };
        if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
            exit(1);
        }

        /* then switch user and group to "shell" */
        if (setgid(AID_SHELL) != 0) {
            exit(1);
        }
        if (setuid(AID_SHELL) != 0) {
            exit(1);
        }

        /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
        header.version = _LINUX_CAPABILITY_VERSION;
        header.pid = 0;
        cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
        cap.inheritable = 0;
        capset(&header, &cap);

        D("Local port disabled\n");
    } else {
        char local_name[30];
        build_local_name(local_name, sizeof(local_name), server_port);
        if(install_listener(local_name, "*smartsocket*", NULL)) {
            exit(1);
        }
    }

        /* for the device, start the usb transport if the
        ** android usb device exists and the "service.adb.tcp.port" and
        ** "persist.adb.tcp.port" properties are not set.
        ** Otherwise start the network transport.
        */
    property_get("service.adb.tcp.port", value, "");
    if (!value[0])
        property_get("persist.adb.tcp.port", value, "");
    if (sscanf(value, "%d", &port) == 1 && port > 0) {
        // listen on TCP port specified by service.adb.tcp.port property
        local_init(port);
    } else if (access("/dev/android_adb", F_OK) == 0) {
        // listen on USB
        usb_init();
    } else {
        // listen on default port
        local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
    }
    D("adb_main(): pre init_jdwp()\n");
    init_jdwp();
    D("adb_main(): post init_jdwp()\n");
#endif

    if (is_daemon)
    {
        // inform our parent that we are up and running.
#ifdef HAVE_WIN32_PROC
        DWORD  count;
        WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
#elif defined(HAVE_FORKEXEC)
        fprintf(stderr, "OK\n");
#endif
        start_logging();
    }
    D("Event loop starting\n");

    fdevent_loop();

    usb_cleanup();

    return 0;
}
int main(int argc, char* argv[]) {
    // Get an OSVR client context to use to access the devices
    // that we need.
    osvr::clientkit::ClientContext context(
        "org.opengoggles.exampleclients.TrackerCallback");

    // Construct button devices and connect them to a callback
    // that will set the "quit" variable to true when it is
    // pressed.  Use button "1" on the left-hand or
    // right-hand controller.
    osvr::clientkit::Interface leftButton1 =
        context.getInterface("/controller/left/1");
    leftButton1.registerCallback(&myButtonCallback, &quit);

    osvr::clientkit::Interface rightButton1 =
        context.getInterface("/controller/right/1");
    rightButton1.registerCallback(&myButtonCallback, &quit);

    // Open Direct3D and set up the context for rendering to
    // an HMD.  Do this using the OSVR RenderManager interface,
    // which maps to the nVidia or other vendor direct mode
    // to reduce the latency.
    osvr::renderkit::RenderManager* render =
        osvr::renderkit::createRenderManager(context.get(), "Direct3D11");

    if ((render == nullptr) || (!render->doingOkay())) {
        std::cerr << "Could not create RenderManager" << std::endl;
        return 1;
    }

    // Set callback to handle setting up rendering in an eye
    render->SetDisplayCallback(SetupDisplay);

    // Register callbacks to render things in left hand, right
    // hand, and world space.
    render->AddRenderCallback("/", DrawWorld);

// Set up a handler to cause us to exit cleanly.
#ifdef _WIN32
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
#endif

    // Open the display and make sure this worked.
    osvr::renderkit::RenderManager::OpenResults ret = render->OpenDisplay();
    if (ret.status == osvr::renderkit::RenderManager::OpenStatus::FAILURE) {
        std::cerr << "Could not open display" << std::endl;
        return 2;
    }
    if (ret.library.D3D11 == nullptr) {
        std::cerr << "Attempted to run a Direct3D11 program with a config file "
                  << "that specified a different rendering library."
                  << std::endl;
        return 3;
    }

    // Set up the rendering state we need.
    if (!SetupRendering(ret.library)) {
        return 4;
    }

    // Continue rendering until it is time to quit.
    while (!quit) {
        // Update the context so we get our callbacks called and
        // update tracker state.
        context.update();

        if (!render->Render()) {
            std::cerr
                << "Render() returned false, maybe because it was asked to quit"
                << std::endl;
            quit = true;
        }
    }

    g_vertexBuffer->Release();

    // Close the Renderer interface cleanly.
    delete render;

    return 0;
}
Beispiel #27
0
_tmain (int argc, LPTSTR argv [])
{
	/* MAX_CLIENTS is defined in ClientServer.h. */
	/* Currently limited to MAXIMUM_WAIT_OBJECTS WaitForMultipleObjects */
	/* is used by the main thread to wait for the server threads */

	HANDLE hNp, hMonitor, hSrvrThread [MAX_CLIENTS], hSecHeap = NULL;
	DWORD iNp, MonitorId, ThreadId;
	DWORD AceMasks [] =	/* Named pipe access rights - Only clients
		* run by the owner will be able to connect. */
		{FILE_GENERIC_READ | FILE_GENERIC_WRITE, 0, 0 };
	LPSECURITY_ATTRIBUTES pNPSA = NULL;
	THREAD_ARG ThArgs [MAX_CLIENTS];

	if (!WindowsVersionOK (3, 1)) 
		ReportError (_T("This program requires Windows NT 3.1 or greater"), 1, FALSE);

	/* Console control handler to permit server shutdown */
	if (!SetConsoleCtrlHandler (Handler, TRUE))
		ReportError (_T("Cannot create Ctrl handler"), 1, TRUE);

	
	if (argc == 4)		/* Optional pipe security. */
		pNPSA = InitializeAccessOnlySA (0440, argv [1], argv [2], AceMasks, &hSecHeap);
			
	/* Create a thread broadcast pipe name periodically. */
	hMonitor = (HANDLE) _beginthreadex (NULL, 0, ServerBroadcast, NULL, 0, &MonitorId);

	/*	Create a pipe instance for every server thread.
	 *	Create a temp file name for each thread.
	 *	Create a thread to service that pipe. */

	for (iNp = 0; iNp < MAX_CLIENTS; iNp++) {
		hNp = CreateNamedPipe ( SERVER_PIPE, PIPE_ACCESS_DUPLEX,
				PIPE_READMODE_MESSAGE | PIPE_TYPE_MESSAGE | PIPE_WAIT,
				MAX_CLIENTS, 0, 0, INFINITE, pNPSA);

		if (hNp == INVALID_HANDLE_VALUE)
			ReportError (_T ("Failure to open named pipe."), 1, TRUE);
		ThArgs [iNp].hNamedPipe = hNp;
		ThArgs [iNp].ThreadNo = iNp;
		GetTempFileName (_T ("."), _T ("CLP"), 0, ThArgs [iNp].TmpFileName);
		hSrvrThread [iNp] = (HANDLE)_beginthreadex (NULL, 0, Server,
				&ThArgs [iNp], 0, &ThreadId);
		if (hSrvrThread [iNp] == NULL)
			ReportError (_T ("Failure to create server thread."), 2, TRUE);
	}
	
	/* Wait for all the threads to terminate. */

	WaitForMultipleObjects (MAX_CLIENTS, hSrvrThread, TRUE, INFINITE);
	_tprintf (_T("All Server worker threads have shut down.\n"));

	WaitForSingleObject (hMonitor, INFINITE);
	_tprintf (_T("Monitor thread has shut down.\n"));

	CloseHandle (hMonitor);
	for (iNp = 0; iNp < MAX_CLIENTS; iNp++) { 
		/* Close pipe handles and delete temp files */
		/* Closing temp files is redundant, as the worker threads do it */
		CloseHandle (hSrvrThread [iNp]);
		DeleteFile (ThArgs [iNp].TmpFileName);
	}
	if (hSecHeap != NULL) HeapDestroy (hSecHeap);
	_tprintf (_T("Server process will exit.\n"));
	/*	ExitProcess assures a clean exit. All DLL entry points will be 
		called, indicating process detach. Among other reasons that this is
		important is that connection threads may still be blocked on
		ConnectNamedPipe calls. */
	ExitProcess (0);

	return 0;
}
Beispiel #28
0
int main(
    int argc,
    char *argv[])
{
    unsigned long hThread = 0;
    uint32_t arg_value = 0;
    char lpBuf[1];
    DWORD dwRead = 0;
    unsigned i = 0, len = 0, count = 0;
    char hex_pair[5] = "0xff";
    char ch = ' ';
    int lsb = 0, msb = 0;
    long my_baud = 38400;
    uint8_t buffer[501] = { 0 };

    if (argc > 1) {
        RS485_Set_Interface(argv[1]);
    }
    if (argc > 2) {
        my_baud = strtol(argv[2], NULL, 0);
    }
    RS485_Set_Baud_Rate(my_baud);
    RS485_Initialize();
#if defined(_WIN32)
    SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_PROCESSED_INPUT);
    SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlCHandler, TRUE);
#endif
#ifdef TEST_RS485_TRANSMIT
    /* read a stream of characters from stdin or argument */
    if (argc > 3) {
        len = strlen(argv[3]);
        for (i = 0; i < len; i++) {
            /* grab pairs of hex characters, skip spaces */
            ch = argv[3][i];
            if (ch == ' ') {
                continue;
            }
            msb = ascii_hex_to_int(ch);
            if (msb >= 0) {
                i++;
                ch = argv[3][i];
                lsb = ascii_hex_to_int(ch);
                if (lsb >= 0) {
                    buffer[count] = msb << 4 | lsb;
                } else {
                    buffer[count] = msb;
                }
                count++;
                if (count >= sizeof(buffer)) {
                    break;
                }
            }
        }
        RS485_Send_Frame(NULL, buffer, count);
    }
#endif
#ifdef TEST_RS485_RECEIVE
    /* receive task */
    for (;;) {
        if (!ReadFile(RS485_Handle, lpBuf, sizeof(lpBuf), &dwRead, NULL)) {
            if (GetLastError() != ERROR_IO_PENDING) {
                RS485_Print_Error();
            }
        } else {
            /* print any characters received */
            if (dwRead) {
                for (i = 0; i < dwRead; i++) {
                    fprintf(stderr, "%02X ", lpBuf[i]);
                }
            }
            dwRead = 0;
        }
    }
#endif
}
Beispiel #29
0
int _tmain(int argc, _TCHAR* argv[])
{
	bool force_slave = false;
	int32_t offset = 0;
	bool syntonize = false;
	uint8_t priority1 = 248;
	int i;

	// Register default network interface
	WindowsPCAPNetworkInterfaceFactory *default_factory = new WindowsPCAPNetworkInterfaceFactory();
	OSNetworkInterfaceFactory::registerFactory( factory_name_t( "default" ), default_factory );

	// Create thread, lock, timer, timerq factories
	WindowsThreadFactory *thread_factory = new WindowsThreadFactory();
	WindowsTimerQueueFactory *timerq_factory = new WindowsTimerQueueFactory();
	WindowsLockFactory *lock_factory = new WindowsLockFactory();
	WindowsTimerFactory *timer_factory = new WindowsTimerFactory();
	WindowsConditionFactory *condition_factory = new WindowsConditionFactory();
	WindowsNamedPipeIPC *ipc = new WindowsNamedPipeIPC();
	if( !ipc->init() ) {
		delete ipc;
		ipc = NULL;
	}

	/* Process optional arguments */
	for( i = 1; i < argc-1; ++i ) {
		if( ispunct(argv[i][0]) ) {
			if( toupper( argv[i][1] ) == 'H' ) {
				print_usage( argv[0] );
				return -1;
			}
			else if( toupper( argv[i][1] ) == 'R' ) {
				if( i+1 >= argc ) {
					printf( "Priority 1 value must be specified on "
						"command line, using default value\n" );
				} else {
					unsigned long tmp = strtoul( argv[i], NULL, 0 ); ++i;
					if( tmp > 254 ) {
						printf( "Invalid priority 1 value, using "
							"default value\n" );
					} else {
						priority1 = (uint8_t) tmp;
					}
				}
			}
		}
	}

	// Create Low level network interface object
	uint8_t local_addr_ostr[ETHER_ADDR_OCTETS];
	if( i >= argc ) {
		print_usage( argv[0] );
		return -1;
	}
	parseMacAddr( argv[i], local_addr_ostr );
	LinkLayerAddress local_addr(local_addr_ostr);

	// Create HWTimestamper object
	HWTimestamper *timestamper = new WindowsTimestamper();
	// Create Clock object
	IEEE1588Clock *clock = new IEEE1588Clock( false, false, priority1, timestamper, timerq_factory, ipc );  // Do not force slave
	// Create Port Object linked to clock and low level
	IEEE1588Port *port = new IEEE1588Port( clock, 1, false, 0, timestamper, 0, &local_addr,
		condition_factory, thread_factory, timer_factory, lock_factory );
	if( !port->init_port() ) {
		printf( "Failed to initialize port\n" );
		return -1;
	}
	port->processEvent( POWERUP );

	// Wait for Ctrl-C
	if( !SetConsoleCtrlHandler( ctrl_handler, true )) {
		printf( "Unable to register Ctrl-C handler\n" );
		return -1;
	}

	while( !exit_flag ) Sleep( 1200 );

	delete( ipc );

	return 0;
}
Beispiel #30
0
int __cdecl
main(int argc, char ** argv)
{
	int i;

	SERVICE_TABLE_ENTRY serviceTable[] = 
	{ 
		{ SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
		{ NULL, NULL }
	};

	BOOL success;

	if (argc == 1)
	{
		//
		// Register with the SCM
		//
		success = StartServiceCtrlDispatcher(serviceTable);
	
		if (!success)
		{
			service_error_handler("StartServiceCtrlDispatcher", GetLastError());
			exit(0);
		}
	}
	else for (i = 1; i < argc; i++)
	{
		if (strcmp(argv[i], "-run") == 0)
		{
			g_console_event = CreateEvent(NULL, FALSE, FALSE, NULL);

			if (g_console_event == NULL)
			{
				sw_debug(SW_LOG_ERROR, "CreateEvent failed: %d\n", GetLastError());
				exit(-1);
			}

			SetConsoleCtrlHandler(console_ctrl_handler, TRUE);

			if (start_mDNSResponder() != S_OK)
			{
				exit(-1);
			}

			WaitForSingleObject(g_console_event, INFINITE);

			CloseHandle(g_console_event);

			stop_mDNSResponder();

			exit(0);
		}
		else if (strcmp(argv[i], "-install") == 0)
		{
			register_service(argc, argv);
			break;
		}
		else if (strcmp(argv[i], "-remove") == 0)
		{
			unregister_service(argc, argv);
			break;
		}
		else if (strcmp(argv[i], "-debug") == 0)
		{
			// sw_debug_enable(1);
		}
		else
		{
			fprintf(stderr, "usage: %s [-run][-install][-remove]\n", argv[0]);
			break;
		}
	}

	return 0;
}