Esempio n. 1
0
/*
 * Portable version of setenv(), allowing editing of any environ-like
 * array
 */
pmix_status_t pmix_setenv(const char *name, const char *value, bool overwrite,
                          char ***env)
{
    int i;
    char *newvalue, *compare;
    size_t len;

    /* Make the new value */

    if (NULL == value) {
        i = asprintf(&newvalue, "%s=", name);
    } else {
        i = asprintf(&newvalue, "%s=%s", name, value);
    }
    if (NULL == newvalue || 0 > i) {
        return PMIX_ERR_OUT_OF_RESOURCE;
    }

    /* Check the bozo case */

    if( NULL == env ) {
        return PMIX_ERR_BAD_PARAM;
    } else if (NULL == *env) {
        i = 0;
        pmix_argv_append(&i, env, newvalue);
        free(newvalue);
        return PMIX_SUCCESS;
    }

    /* If this is the "environ" array, use putenv */
    if( *env == environ ) {
        /* THIS IS POTENTIALLY A MEMORY LEAK!  But I am doing it
           because so that we don't violate the law of least
           astonishmet for PMIX developers (i.e., those that don't
           check the return code of pmix_setenv() and notice that we
           returned an error if you passed in the real environ) */
        putenv(newvalue);
        return PMIX_SUCCESS;
    }

    /* Make something easy to compare to */

    i = asprintf(&compare, "%s=", name);
    if (NULL == compare || 0 > i) {
        free(newvalue);
        return PMIX_ERR_OUT_OF_RESOURCE;
    }
    len = strlen(compare);

    /* Look for a duplicate that's already set in the env */

    for (i = 0; (*env)[i] != NULL; ++i) {
        if (0 == strncmp((*env)[i], compare, len)) {
            if (overwrite) {
                free((*env)[i]);
                (*env)[i] = newvalue;
                free(compare);
                return PMIX_SUCCESS;
            } else {
                free(compare);
                free(newvalue);
                return PMIX_EXISTS;
            }
        }
    }

    /* If we found no match, append this value */

    i = pmix_argv_count(*env);
    pmix_argv_append(&i, env, newvalue);

    /* All done */

    free(compare);
    free(newvalue);
    return PMIX_SUCCESS;
}
Esempio n. 2
0
void init_gettext(const char *path, const std::string &configured_language, int argc, char** argv) {
#else
void init_gettext(const char *path, const std::string &configured_language) {
#endif
#if USE_GETTEXT
	/** first try to set user override environment **/
	if (configured_language.length() != 0) {
#ifndef _WIN32
		/* add user specified locale to environment */
		setenv("LANGUAGE", configured_language.c_str(), 1);

		/* reload locale with changed environment */
		setlocale(LC_ALL, "");
#elif defined(_MSC_VER)
		std::string current_language_var("");
		if (getenv("LANGUAGE") != 0) {
			current_language_var = std::string(getenv("LANGUAGE"));
		}

		char *lang_str = (char*)calloc(10 + configured_language.length(), sizeof(char));
		strcat(lang_str, "LANGUAGE=");
		strcat(lang_str, configured_language.c_str());
		putenv(lang_str);

		SetEnvironmentVariableA("LANGUAGE",configured_language.c_str());

#ifndef SERVER
		//very very dirty workaround to force gettext to see the right environment
		if (current_language_var != configured_language) {
			STARTUPINFO startupinfo;
			PROCESS_INFORMATION processinfo;
			memset(&startupinfo, 0, sizeof(startupinfo));
			memset(&processinfo, 0, sizeof(processinfo));
			errorstream << "MSVC localization workaround active restating minetest in new environment!" << std::endl;

			std::string parameters = "";

			for (unsigned int i=1;i < argc; i++) {
				if (parameters != "") {
					parameters += " ";
				}
				parameters += argv[i];
			}

			const char* ptr_parameters = 0;

			if (parameters != "") {
				ptr_parameters = parameters.c_str();
			}
			
			/** users may start by short name in commandline without extention **/
			std::string appname = argv[0];
			if (appname.substr(appname.length() - 4) != ".exe") {
				appname += ".exe";
			}

			if (!CreateProcess(appname.c_str(),
					(char*) ptr_parameters,
					NULL,
					NULL,
					false,
					DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT,
					NULL,
					NULL,
					&startupinfo,
					&processinfo)) {
				char buffer[1024];		
				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
					NULL,
					GetLastError(),
					MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
					buffer,
					sizeof(buffer)-1,
					NULL);
				errorstream << "*******************************************************" << std::endl;
				errorstream << "CMD: " << appname << std::endl;
				errorstream << "Failed to restart with current locale: " << std::endl;
				errorstream << buffer;
				errorstream << "Expect language to be broken!" << std::endl;
				errorstream << "*******************************************************" << std::endl;
			}
			else {
				exit(0);
			}
#else
			errorstream << "*******************************************************" << std::endl;
			errorstream << "Can't apply locale workaround for server!" << std::endl;
			errorstream << "Expect language to be broken!" << std::endl;
			errorstream << "*******************************************************" << std::endl;

#endif
		}

		setlocale(LC_ALL,configured_language.c_str());
#else // Mingw
		char *lang_str = (char*)calloc(10 + configured_language.length(), sizeof(char));
		strcat(lang_str, "LANGUAGE=");
		strcat(lang_str, configured_language.c_str());
		putenv(lang_str);

		setlocale(LC_ALL, "");
#endif // ifndef _WIN32
	}
	else {
		 /* set current system default locale */
		setlocale(LC_ALL, "");
	}

#if defined(_WIN32)
	if (getenv("LANGUAGE") != 0) {
		setlocale(LC_ALL, getenv("LANGUAGE"));
	}
#ifdef _MSC_VER
	else if (getenv("LANG") != 0) {
		setlocale(LC_ALL, getenv("LANG"));
	}
#endif
#endif

	static std::string name = lowercase(PROJECT_NAME);
	bindtextdomain(name.c_str(), path);
	textdomain(name.c_str());

#if defined(_WIN32)
	// Set character encoding for Win32
	char *tdomain = textdomain( (char *) NULL );
	if( tdomain == NULL )
	{
		errorstream << "Warning: domainname parameter is the null pointer" <<
				", default domain is not set" << std::endl;
		tdomain = (char *) "messages";
	}
	/* char *codeset = */bind_textdomain_codeset( tdomain, "UTF-8" );
	//errorstream << "Gettext debug: domainname = " << tdomain << "; codeset = "<< codeset << std::endl;
#endif // defined(_WIN32)

#else
	/* set current system default locale */
	setlocale(LC_ALL, "");
#endif // if USE_GETTEXT

	/* no matter what locale is used we need number format to be "C" */
	/* to ensure formspec parameters are evaluated correct!          */

	setlocale(LC_NUMERIC, "C");
	infostream << "Message locale is now set to: "
			<< setlocale(LC_ALL, 0) << std::endl;
}
Esempio n. 3
0
void DtPrinterIcon::DndCB(BaseUI *obj, char **value, int * /*len*/,
			  DNDProtocol dndProtocol)
{
   DtPrinterIcon *printer;
   if (obj->UIClass() == ICON)
      printer = (DtPrinterIcon *)obj;
   else
      printer = (DtPrinterIcon *)obj->Parent();
   DtActionArg ap[1];
   char *old_LPDEST = NULL;
   ap[0].argClass = DtACTION_FILE;

   char *buf = new char[100];
   switch (dndProtocol)
   {
   case FILENAME_TRANSFER: // Dropping an Object on a printer
      ap[0].u.file.name = *value;
      if (printer->PrintActionExists())
         sprintf(buf, "%s_Print", printer->queue->Name());
      else
       {
	 if (old_LPDEST = STRDUP(getenv("LPDEST")))
	  {
            sprintf(buf, "LPDEST=%s", printer->queue->Name());
	    putenv(buf);
	  }
         strcpy(buf, "Print");
       }

      DtActionInvoke(((AnyUI *)printer->mainw->Parent())->BaseWidget(), buf, ap,
		     1, NULL, NULL, NULL, True, NULL, NULL);
      if (old_LPDEST)
       {
	 sprintf(buf, "LPDEST=%s", old_LPDEST);
	 putenv(buf);
	 delete old_LPDEST;
       }
      break;
   case CONVERT_DATA: // Dragging a printer to an object
      if (printer->PrintActionExists())
       {
	 struct stat statbuff;
         *value = new char[strlen(homeDir) + strlen(PRINTERS_PERSONAL_DIR) +
			   strlen(printer->queue->Name()) + 10];
         sprintf(*value, "%s/%s/%s_Print", homeDir, PRINTERS_PERSONAL_DIR,
		 printer->queue->Name());
	 if (stat(*value, &statbuff) < 0)
	  {
	    int fd = creat(*value, 0755);
	    close(fd);
	  }
       }
      else
	 *value = NULL;
      break;
   case DROP_ON_ROOT:
      {
      char *x = *value;
      char *y = strchr(x, '\n');
      *y++ = '\0';
      char *filename = strchr(y, '\n');
      *filename++ = '\0';
      char *work_space = strchr(filename, '\n');
      if (work_space)
         *work_space++ = '\0';
      }
      break;
   case TEXT_TRANSFER:
      break;
   case BUFFER_TRANSFER:
      *value = new char[strlen(printer->queue->Name()) + 10];
      sprintf(*value, "%s_Print", printer->queue->Name());
      break;
   case CONVERT_DELETE:
      break;
   case ANIMATE:
      break;
   }
   delete [] buf;
}
Esempio n. 4
0
GenericAgentConfig *CheckOpts(int argc, char **argv)
{
    extern char *optarg;
    char ld_library_path[CF_BUFSIZE];
    int optindex = 0;
    int c;
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_SERVER);

    while ((c = getopt_long(argc, argv, "dvIKf:D:N:VSxLFMh", OPTIONS, &optindex)) != EOF)
    {
        switch ((char) c)
        {
        case 'f':

            if (optarg && (strlen(optarg) < 5))
            {
                FatalError(" -f used but argument \"%s\" incorrect", optarg);
            }

            GenericAgentConfigSetInputFile(config, optarg);
            MINUSF = true;
            break;

        case 'd':
            DEBUG = true;
            NO_FORK = true;

        case 'K':
            IGNORELOCK = true;
            break;

        case 'D':
            NewClassesFromString(optarg);
            break;

        case 'N':
            NegateClassesFromString(optarg);
            break;

        case 'I':
            INFORM = true;
            break;

        case 'v':
            VERBOSE = true;
            NO_FORK = true;
            break;

        case 'F':
            NO_FORK = true;
            break;

        case 'L':
            CfOut(cf_verbose, "", "Setting LD_LIBRARY_PATH=%s\n", optarg);
            snprintf(ld_library_path, CF_BUFSIZE - 1, "LD_LIBRARY_PATH=%s", optarg);
            putenv(ld_library_path);
            break;

        case 'V':
            PrintVersionBanner("cf-serverd");
            exit(0);

        case 'h':
            Syntax("cf-serverd - cfengine's server agent", OPTIONS, HINTS, ID);
            exit(0);

        case 'M':
            ManPage("cf-serverd - cfengine's server agent", OPTIONS, HINTS, ID);
            exit(0);

        case 'x':
            SelfDiagnostic();
            exit(0);

        default:
            Syntax("cf-serverd - cfengine's server agent", OPTIONS, HINTS, ID);
            exit(1);

        }
    }

    if (argv[optind] != NULL)
    {
        CfOut(cf_error, "", "Unexpected argument with no preceding option: %s\n", argv[optind]);
        FatalError("Aborted");
    }

    CfDebug("Set debugging\n");

    return config;
}
/* A binary wrapper is needed around python scripts if we want
 * to run them in sgid/suid mode.
 *
 * This is such a wrapper.
 */
int main(int argc, char **argv)
{
    /*
     * We disallow passing of arguments which point to writable dirs
     * and other files possibly not accessible to calling user.
     * This way, the script will always use default values for these arguments.
     */
    char **pp = argv;
    char *arg;
    while ((arg = *++pp) != NULL)
    {
        /* Allow taking ids from stdin */
        if (strcmp(arg, "--ids=-") == 0)
            continue;

        if (strncmp(arg, "--exact", 7) == 0)
            continue;

        if (strncmp(arg, "--cache", 7) == 0)
            error_msg_and_die("bad option %s", arg);
        if (strncmp(arg, "--tmpdir", 8) == 0)
            error_msg_and_die("bad option %s", arg);
        if (strncmp(arg, "--ids", 5) == 0)
            error_msg_and_die("bad option %s", arg);
    }

    /* Switch real user/group to effective ones.
     * Otherwise yum library gets confused - gets EPERM (why??).
     */
    gid_t g = getegid();
    /* do setregid only if we have to, to not upset selinux needlessly */
    if (g != getgid())
        IGNORE_RESULT(setregid(g, g));
    uid_t u = geteuid();
    if (u != getuid())
    {
        IGNORE_RESULT(setreuid(u, u));
        /* We are suid'ed! */
        /* Prevent malicious user from messing up with suid'ed process: */
#if 1
// We forgot to sanitize PYTHONPATH. And who knows what else we forgot
// (especially considering *future* new variables of this kind).
// We switched to clearing entire environment instead:

        // However since we communicate through environment variables
        // we have to keep a whitelist of variables to keep.
        static const char *whitelist[] = {
            "REPORT_CLIENT_SLAVE" //  Check if the app is being run as a slave
        };
        const size_t wlsize = sizeof(whitelist)/sizeof(char*);
        char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 };
        char *p = NULL;
        for (size_t i = 0; i < wlsize; i++)
            if ((p = getenv(whitelist[i])) != NULL)
                setlist[i] = xstrdup(p);

        // Now we can clear the environment
        clearenv();

        // And once again set whitelisted variables
        for (size_t i = 0; i < wlsize; i++)
            if (setlist[i] != NULL)
            {
                xsetenv(whitelist[i], setlist[i]);
                free(setlist[i]);
            }
#else
        /* Clear dangerous stuff from env */
        static const char forbid[] =
            "LD_LIBRARY_PATH" "\0"
            "LD_PRELOAD" "\0"
            "LD_TRACE_LOADED_OBJECTS" "\0"
            "LD_BIND_NOW" "\0"
            "LD_AOUT_LIBRARY_PATH" "\0"
            "LD_AOUT_PRELOAD" "\0"
            "LD_NOWARN" "\0"
            "LD_KEEPDIR" "\0"
        ;
        const char *p = forbid;
        do {
            unsetenv(p);
            p += strlen(p) + 1;
        } while (*p);
#endif
        /* Set safe PATH */
        // Adding configure --bindir and --sbindir to the PATH so that
        // abrt-action-install-debuginfo doesn't fail when spawning
        // abrt-action-trim-files
        char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR;
        if (u != 0)
            strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR);
        putenv(path_env);
    }

    execvp(EXECUTABLE, argv);
    error_msg_and_die("Can't execute %s", EXECUTABLE);
}
void setEnviron(char* param) {
	if (0 > putenv(param)) {
		perror("Cannot set or add env variable");
	}
}
Esempio n. 7
0
int run_pelog(

  int   which,      /* I (one of PE_*) */
  char *specpelog,  /* I - script path */
  job  *pjob,       /* I - associated job */
  int   pe_io_type) /* I */

  {
  char *id = "run_pelog";

  struct sigaction act;
  struct sigaction oldact;
  char *arg[12];
  int   fds1 = 0;
  int   fds2 = 0;
  int   fd_input;
  char  resc_list[2048];
  char  resc_used[2048];

  struct stat sbuf;
  char   sid[20];
  char   exit_stat[11];
  int    waitst;
  int    isjoined;  /* boolean */
  char   buf[MAXPATHLEN + 1024];
  char   pelog[MAXPATHLEN + 1024];

  uid_t  real_uid = 0;
  gid_t *real_gids = NULL;
  gid_t  real_gid = 0;
  int    num_gids = 0;

  int    jobtypespecified = 0;

  resource      *r;

  char          *EmptyString = "";

  int            LastArg;
  int            aindex;

  int            rc;

  char          *ptr;

  if ((pjob == NULL) || (specpelog == NULL) || (specpelog[0] == '\0'))
    {
    return(0);
    }

  ptr = pjob->ji_wattr[(int)JOB_ATR_jobtype].at_val.at_str;

  if (ptr != NULL)
    {
    jobtypespecified = 1;

    snprintf(pelog,sizeof(pelog),"%s.%s",
      specpelog,
      ptr);
    }
  else
    {
    strncpy(pelog,specpelog,sizeof(pelog));
    }

  /* to support root squashing, become the user before performing file checks */
  if ((which == PE_PROLOGUSER) || 
      (which == PE_EPILOGUSER) || 
      (which == PE_PROLOGUSERJOB) || 
      (which == PE_EPILOGUSERJOB))
    {
    real_uid = getuid();
    real_gid = getgid();

    if ((num_gids = getgroups(0,real_gids)) < 0)
      {
      log_err(errno,id,"getgroups failed\n");

      return(-1);
      }
    else
      {
      real_gids = malloc(sizeof(gid_t) * num_gids);
      
      if (real_gids == NULL)
        {
        log_err(ENOMEM,id,"Cannot allocate memory! FAILURE\n");

        return(-1);
        }

      if (getgroups(num_gids,real_gids) < 0)
        {
        log_err(errno,id,"getgroups failed\n");
        
        return(-1);
        }
      }

    /* pjob->ji_grpcache will not be set if using LDAP and LDAP not set */
    /* It is possible that ji_grpcache failed to allocate as well. 
       Make sure ji_grpcache is not NULL */
    if (pjob->ji_grpcache != NULL)
      {
      if (setgroups(
            pjob->ji_grpcache->gc_ngroup,
            (gid_t *)pjob->ji_grpcache->gc_groups) != 0)
        {
        snprintf(log_buffer,sizeof(log_buffer),
          "setgroups() for UID = %lu failed: %s\n",
          (unsigned long)pjob->ji_qs.ji_un.ji_momt.ji_exuid,
          strerror(errno));
      
        log_err(errno, id, log_buffer);
      
        undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
      
        return(-1);
        }
      }
    else
      {
      sprintf(log_buffer, "pjob->ji_grpcache is null. check_pwd likely failed.");
      log_err(-1, id, log_buffer);
      undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
      return(-1);
      }
    
    if (setegid(pjob->ji_qs.ji_un.ji_momt.ji_exgid) != 0)
      {
      snprintf(log_buffer,sizeof(log_buffer),
        "setegid(%lu) for UID = %lu failed: %s\n",
        (unsigned long)pjob->ji_qs.ji_un.ji_momt.ji_exgid,
        (unsigned long)pjob->ji_qs.ji_un.ji_momt.ji_exuid,
        strerror(errno));
      
      log_err(errno, id, log_buffer);
      
      undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
      
      return(-1);
      }
    
    if (seteuid(pjob->ji_qs.ji_un.ji_momt.ji_exuid) != 0)
      {
      snprintf(log_buffer,sizeof(log_buffer),
        "seteuid(%lu) failed: %s\n",
        (unsigned long)pjob->ji_qs.ji_un.ji_momt.ji_exuid,
        strerror(errno));
      
      log_err(errno, id, log_buffer);
      
      undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);

      return(-1);
      }
    }

  rc = stat(pelog,&sbuf);

  if ((rc == -1) && (jobtypespecified == 1))
    {
    strncpy(pelog,specpelog,sizeof(pelog));

    rc = stat(pelog,&sbuf);
    }

  if (rc == -1)
    {
    if (errno == ENOENT || errno == EBADF)
      {
      /* epilog/prolog script does not exist */

      if (LOGLEVEL >= 5)
        {
        static char tmpBuf[1024];

        sprintf(log_buffer, "%s script '%s' for job %s does not exist (cwd: %s,pid: %d)",
          PPEType[which],
          (pelog != NULL) ? pelog : "NULL",
          (pjob != NULL) ? pjob->ji_qs.ji_jobid : "NULL",
          getcwd(tmpBuf, sizeof(tmpBuf)),
          getpid());

        log_record(PBSEVENT_SYSTEM, 0, id, log_buffer);
        }

#ifdef ENABLE_CSA
      if ((which == PE_EPILOGUSER) && (!strcmp(pelog, path_epiloguser)))
        {
        /*
          * Add a workload management end record
        */
        if (LOGLEVEL >= 8)
          {
          sprintf(log_buffer, "%s calling add_wkm_end from run_pelog() - no user epilog",
            pjob->ji_qs.ji_jobid);

          log_err(-1, id, log_buffer);
          }

        add_wkm_end(pjob->ji_wattr[(int)JOB_ATR_pagg_id].at_val.at_ll,

                    pjob->ji_qs.ji_un.ji_momt.ji_exitstat, pjob->ji_qs.ji_jobid);
        }

#endif /* ENABLE_CSA */

      undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);

      return(0);
      }
      
    undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);

    return(pelog_err(pjob,pelog,errno,"cannot stat"));
    }

  if (LOGLEVEL >= 5)
    {
    sprintf(log_buffer,"running %s script '%s' for job %s",
      PPEType[which],
      (pelog != NULL) ? pelog : "NULL",
      pjob->ji_qs.ji_jobid);

    log_ext(-1,id,log_buffer,LOG_DEBUG);  /* not actually an error--but informational */
    }

  /* script must be owned by root, be regular file, read and execute by user *
   * and not writeable by group or other */

  if (reduceprologchecks == TRUE)
    {
    if ((!S_ISREG(sbuf.st_mode)) ||
        (!(sbuf.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
      {
      undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
      return(pelog_err(pjob,pelog,-1,"permission Error"));
      }
    }
  else
    {
    if (which == PE_PROLOGUSERJOB || which == PE_EPILOGUSERJOB)
      {
      if ((sbuf.st_uid != pjob->ji_qs.ji_un.ji_momt.ji_exuid) || 
          (!S_ISREG(sbuf.st_mode)) ||
          ((sbuf.st_mode & (S_IRUSR | S_IXUSR)) != (S_IRUSR | S_IXUSR)) ||
          (sbuf.st_mode & (S_IWGRP | S_IWOTH)))
        {
        undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
        return(pelog_err(pjob,pelog,-1,"permission Error"));
        }
      }
    else if ((sbuf.st_uid != 0) ||
        (!S_ISREG(sbuf.st_mode)) ||
        ((sbuf.st_mode & (S_IRUSR | S_IXUSR)) != (S_IRUSR | S_IXUSR)) ||\
        (sbuf.st_mode & (S_IWGRP | S_IWOTH)))
      {
      undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
      return(pelog_err(pjob,pelog,-1,"permission Error"));
      }
    
    if ((which == PE_PROLOGUSER) || (which == PE_EPILOGUSER))
      {
      /* script must also be read and execute by other */
      
      if ((sbuf.st_mode & (S_IROTH | S_IXOTH)) != (S_IROTH | S_IXOTH))
        {
        undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
        return(pelog_err(pjob, pelog, -1, "permission Error"));
        }
      }
    } /* END !reduceprologchecks */

  fd_input = pe_input(pjob->ji_qs.ji_jobid);

  if (fd_input < 0)
    {
    undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);
    return(pelog_err(pjob, pelog, -2, "no pro/epilogue input file"));
    }

  run_exit = 0;

  child = fork();

  if (child > 0)
    {
    int KillSent = FALSE;

    /* parent - watch for prolog/epilog to complete */

    close(fd_input);

    /* switch back to root if necessary */
    undo_set_euid_egid(which,real_uid,real_gid,num_gids,real_gids,id);

    act.sa_handler = pelogalm;

    sigemptyset(&act.sa_mask);

    act.sa_flags = 0;

    sigaction(SIGALRM, &act, &oldact);

    /* it would be nice if the harvest routine could block for 5 seconds,
       and if the prolog is not complete in that time, mark job as prolog
       pending, append prolog child, and continue */

    /* main loop should attempt to harvest prolog in non-blocking mode.
       If unsuccessful after timeout, job should be terminated, and failure
       reported.  If successful, mom should unset prolog pending, and
       continue with job start sequence.  Mom should report job as running
       while prologpending flag is set.  (NOTE:  must track per job prolog
       start time)
    */

    alarm(pe_alarm_time);

    while (waitpid(child, &waitst, 0) < 0)
      {
      if (errno != EINTR)
        {
        /* exit loop. non-alarm based failure occurred */

        run_exit = -3;

        MOMPrologFailureCount++;

        break;
        }

      if (run_exit == -4)
        {
        if (KillSent == FALSE)
          {
          MOMPrologTimeoutCount++;

          /* timeout occurred */

          KillSent = TRUE;

          /* NOTE:  prolog/epilog may be locked in KERNEL space and unkillable */

          alarm(5);
          }
        else
          {
          /* cannot kill prolog/epilog, give up */

          run_exit = -5;

          break;
          }
        }
      }    /* END while (wait(&waitst) < 0) */

    /* epilog/prolog child completed */
#ifdef ENABLE_CSA
    if ((which == PE_EPILOGUSER) && (!strcmp(pelog, path_epiloguser)))
      {
      /*
       * Add a workload management end record
      */
      if (LOGLEVEL >= 8)
        {
        sprintf(log_buffer, "%s calling add_wkm_end from run_pelog() - after user epilog",
                pjob->ji_qs.ji_jobid);

        log_err(-1, id, log_buffer);
        }

      add_wkm_end(pjob->ji_wattr[(int)JOB_ATR_pagg_id].at_val.at_ll,

                  pjob->ji_qs.ji_un.ji_momt.ji_exitstat, pjob->ji_qs.ji_jobid);
      }

#endif /* ENABLE_CSA */

    alarm(0);

    /* restore the previous handler */

    sigaction(SIGALRM, &oldact, 0);

    if (run_exit == 0)
      {
      if (WIFEXITED(waitst))
        {
        run_exit = WEXITSTATUS(waitst);
        }
      }
    }
  else
    {
    /* child - run script */

    log_close(0);

    if (lockfds >= 0)
      {
      close(lockfds);

      lockfds = -1;
      }

    net_close(-1);

    if (fd_input != 0)
      {
      close(0);

      if (dup(fd_input) == -1) {}

      close(fd_input);
      }

    if (pe_io_type == PE_IO_TYPE_NULL)
      {
      /* no output, force to /dev/null */

      fds1 = open("/dev/null", O_WRONLY, 0600);
      fds2 = open("/dev/null", O_WRONLY, 0600);
      }
    else if (pe_io_type == PE_IO_TYPE_STD)
      {
      /* open job standard out/error */

      /*
       * We need to know if files are joined or not.
       * If they are then open the correct file and duplicate it to the other
      */

      isjoined = is_joined(pjob);

      switch (isjoined)
        {
        case -1:

          fds2 = open_std_file(pjob, StdErr, O_WRONLY | O_APPEND,
                               pjob->ji_qs.ji_un.ji_momt.ji_exgid);

          fds1 = dup(fds2);

          break;

        case 1:

          fds1 = open_std_file(pjob, StdOut, O_WRONLY | O_APPEND,
                               pjob->ji_qs.ji_un.ji_momt.ji_exgid);

          fds2 = dup(fds1);

          break;

        default:

          fds1 = open_std_file(pjob, StdOut, O_WRONLY | O_APPEND,
                               pjob->ji_qs.ji_un.ji_momt.ji_exgid);

          fds2 = open_std_file(pjob, StdErr, O_WRONLY | O_APPEND,
                               pjob->ji_qs.ji_un.ji_momt.ji_exgid);
          break;
        }
      }

    if (pe_io_type != PE_IO_TYPE_ASIS)
      {
      /* If PE_IO_TYPE_ASIS, leave as is, already open to job */

      if (fds1 != 1)
        {
        close(1);

        if (dup(fds1) == -1) {}

        close(fds1);
        }

      if (fds2 != 2)
        {
        close(2);

        if (dup(fds2) == -1) {}

        close(fds2);
        }
      }

    if ((which == PE_PROLOGUSER) || (which == PE_EPILOGUSER) || (which == PE_PROLOGUSERJOB) || (which == PE_EPILOGUSERJOB))
      {
      if (chdir(pjob->ji_grpcache->gc_homedir) != 0)
        {
        /* warn only, no failure */

        sprintf(log_buffer,
          "PBS: chdir to %s failed: %s (running user %s in current directory)",
          pjob->ji_grpcache->gc_homedir,
          strerror(errno),
          which == PE_PROLOGUSER ? "prologue" : "epilogue");

        if (write(2, log_buffer, strlen(log_buffer)) == -1) {}

        fsync(2);
        }
      }

    /* for both prolog and epilog */

    if (DEBUGMODE == 1)
      {
      fprintf(stderr, "PELOGINFO:  script:'%s'  jobid:'%s'  euser:'******'  egroup:'%s'  jobname:'%s' SSID:'%ld'  RESC:'%s'\n",
              pelog,
              pjob->ji_qs.ji_jobid,
              pjob->ji_wattr[(int)JOB_ATR_euser].at_val.at_str,
              pjob->ji_wattr[(int)JOB_ATR_egroup].at_val.at_str,
              pjob->ji_wattr[(int)JOB_ATR_jobname].at_val.at_str,
              pjob->ji_wattr[(int)JOB_ATR_session_id].at_val.at_long,
              resc_to_string(pjob, (int)JOB_ATR_resource, resc_list, sizeof(resc_list)));
      }

    arg[0] = pelog;

    arg[1] = pjob->ji_qs.ji_jobid;
    arg[2] = pjob->ji_wattr[(int)JOB_ATR_euser].at_val.at_str;
    arg[3] = pjob->ji_wattr[(int)JOB_ATR_egroup].at_val.at_str;
    arg[4] = pjob->ji_wattr[(int)JOB_ATR_jobname].at_val.at_str;

    /* NOTE:  inside child */

    if ( which == PE_EPILOG || which == PE_EPILOGUSER || which == PE_EPILOGUSERJOB )
      {
      /* for epilog only */

      sprintf(sid, "%ld",
              pjob->ji_wattr[(int)JOB_ATR_session_id].at_val.at_long);
      sprintf(exit_stat,"%d",
              pjob->ji_qs.ji_un.ji_exect.ji_exitstat);

      arg[5] = sid;
      arg[6] = resc_to_string(pjob, (int)JOB_ATR_resource, resc_list, sizeof(resc_list));
      arg[7] = resc_to_string(pjob, (int)JOB_ATR_resc_used, resc_used, sizeof(resc_used));
      arg[8] = pjob->ji_wattr[(int)JOB_ATR_in_queue].at_val.at_str;
      arg[9] = pjob->ji_wattr[(int)JOB_ATR_account].at_val.at_str;
      arg[10] = exit_stat;
      arg[11] = NULL;

      LastArg = 11;
      }
    else
      {
      /* prolog */

      arg[5] = resc_to_string(pjob, (int)JOB_ATR_resource, resc_list, sizeof(resc_list));
      arg[6] = pjob->ji_wattr[(int)JOB_ATR_in_queue].at_val.at_str;
      arg[7] = pjob->ji_wattr[(int)JOB_ATR_account].at_val.at_str;
      arg[8] = NULL;

      LastArg = 8;
      }

    for (aindex = 0;aindex < LastArg;aindex++)
      {
      if (arg[aindex] == NULL)
        arg[aindex] = EmptyString;
      }  /* END for (aindex) */

    /*
     * Pass Resource_List.nodes request in environment
     * to allow pro/epi-logue setup/teardown of system
     * settings.  --pw, 2 Jan 02
     * Fixed to use putenv for sysV compatibility.
     *  --troy, 11 jun 03
     *
     */

    r = find_resc_entry(
          &pjob->ji_wattr[(int)JOB_ATR_resource],
          find_resc_def(svr_resc_def, "nodes", svr_resc_size));

    if (r != NULL)
      {
      /* setenv("PBS_RESOURCE_NODES",r->rs_value.at_val.at_str,1); */

      const char *envname = "PBS_RESOURCE_NODES=";
      char *envstr;

      envstr = malloc(
                 (strlen(envname) + strlen(r->rs_value.at_val.at_str) + 1) * sizeof(char));

      if (envstr != NULL)
        {
        strcpy(envstr,envname);

        strcat(envstr,r->rs_value.at_val.at_str);

        /* do _not_ free the string when using putenv */

        putenv(envstr);
        }
      }  /* END if (r != NULL) */

    r = find_resc_entry(
          &pjob->ji_wattr[(int)JOB_ATR_resource],
          find_resc_def(svr_resc_def, "gres", svr_resc_size));

    if (r != NULL)
      {
      /* setenv("PBS_RESOURCE_NODES",r->rs_value.at_val.at_str,1); */

      const char *envname = "PBS_RESOURCE_GRES=";
      char *envstr;

      envstr = malloc(
                 (strlen(envname) + strlen(r->rs_value.at_val.at_str) + 1) * sizeof(char));

      if (envstr != NULL)
        {
        strcpy(envstr,envname);

        strcat(envstr,r->rs_value.at_val.at_str);

        /* do _not_ free the string when using putenv */

        putenv(envstr);
        }
      }  /* END if (r != NULL) */

    if (TTmpDirName(pjob, buf))
      {
      const char *envname = "TMPDIR=";
      char *envstr;

      envstr = malloc(
                 (strlen(envname) + strlen(buf) + 1) * sizeof(char));

      if (envstr != NULL)
        {
        strcpy(envstr,envname);

        strcat(envstr,buf);

        /* do _not_ free the string when using putenv */

        putenv(envstr);
        }
      }  /* END if (TTmpDirName(pjob,&buf)) */

    /* Set PBS_SCHED_HINT */

      {
      char *envname = "PBS_SCHED_HINT";
      char *envval;
      char *envstr;

      if ((envval = get_job_envvar(pjob, envname)) != NULL)
        {
        envstr = malloc((strlen(envname) + strlen(envval) + 2) * sizeof(char));

        if (envstr != NULL)
          {
          sprintf(envstr,"%s=%s",
            envname,
            envval);

          putenv(envstr);
          }
        }
      }

    /* Set PBS_NODENUM */
      {
      char *envname = "PBS_NODENUM";
      char *envstr;

      sprintf(buf, "%d",
        pjob->ji_nodeid);

      envstr = malloc((strlen(envname) + strlen(buf) + 2) * sizeof(char));

      if (envstr != NULL)
        {
        sprintf(envstr,"%s=%d",
          envname,
          pjob->ji_nodeid);

        putenv(envstr);
        }
      }

    /* Set PBS_MSHOST */
      {
      char *envname = "PBS_MSHOST";
      char *envstr;

      if ((pjob->ji_vnods[0].vn_host != NULL) && (pjob->ji_vnods[0].vn_host->hn_host != NULL))
        {
        envstr = malloc((strlen(envname) + strlen(pjob->ji_vnods[0].vn_host->hn_host) + 2) * sizeof(char));

        if (envstr != NULL)
          {
          sprintf(envstr,"%s=%s",
            envname,
            pjob->ji_vnods[0].vn_host->hn_host);

          putenv(envstr);
          }
        }
      }

    /* Set PBS_NODEFILE */
      {
      char *envname = "PBS_NODEFILE";
      char *envstr;

      if (pjob->ji_flags & MOM_HAS_NODEFILE)
        {
        sprintf(buf, "%s/%s",
          path_aux,
          pjob->ji_qs.ji_jobid);

        envstr = malloc((strlen(envname) + strlen(buf) + 2) * sizeof(char));

        if (envstr != NULL)
          {
          sprintf(envstr,"%s=%s",
            envname,
            buf);

          putenv(envstr);
          }
        }
      }

    /* Set PBS_O_Workdir */
      {
      char *envname = "PBS_O_WORKDIR";
      char *workdir_val;
      char *envstr;

      workdir_val = get_job_envvar(pjob,envname);
      if (workdir_val != NULL)
        {
        envstr = malloc((strlen(workdir_val) + strlen(envname) + 2) * sizeof(char));

        if (envstr != NULL)
          {
          sprintf(envstr,"%s=%s",
            envname,
            workdir_val);

          putenv(envstr);
          }
        }
      }

    /* SET BEOWULF_JOB_MAP */

      {

      struct array_strings *vstrs;

      int VarIsSet = 0;
      int j;

      vstrs = pjob->ji_wattr[(int)JOB_ATR_variables].at_val.at_arst;

      for (j = 0;j < vstrs->as_usedptr;++j)
        {
        if (!strncmp(
              vstrs->as_string[j],
              "BEOWULF_JOB_MAP=",
              strlen("BEOWULF_JOB_MAP=")))
          {
          VarIsSet = 1;

          break;
          }
        }

      if (VarIsSet == 1)
        {
        char *envstr;

        envstr = malloc((strlen(vstrs->as_string[j])) * sizeof(char));

        if (envstr != NULL)
          {
          strcpy(envstr,vstrs->as_string[j]);

          putenv(envstr);
          }
        }
      }

  /*
   * if we want to run as user then we need to reset real user permissions
   * since it seems that some OSs use real not effective user id when execv'ing
   */

  if ((which == PE_PROLOGUSER) || 
      (which == PE_EPILOGUSER) || 
      (which == PE_PROLOGUSERJOB) || 
      (which == PE_EPILOGUSERJOB))
    {
      seteuid(pbsuser);
      setegid(pbsgroup);

    if (setgid(pjob->ji_qs.ji_un.ji_momt.ji_exgid) != 0)
      {
      snprintf(log_buffer,sizeof(log_buffer),
        "setgid(%lu) for UID = %lu failed: %s\n",
        (unsigned long)pjob->ji_qs.ji_un.ji_momt.ji_exgid,
        (unsigned long)pjob->ji_qs.ji_un.ji_momt.ji_exuid,
        strerror(errno));
      
      log_err(errno, id, log_buffer);
      
      return(-1);
      }
    
    if (setuid(pjob->ji_qs.ji_un.ji_momt.ji_exuid) != 0)
      {
      snprintf(log_buffer,sizeof(log_buffer),
        "setuid(%lu) failed: %s\n",
        (unsigned long)pjob->ji_qs.ji_un.ji_momt.ji_exuid,
        strerror(errno));
      
      log_err(errno, id, log_buffer);
      
      return(-1);
      }
    }

    execv(pelog,arg);

    sprintf(log_buffer,"execv of %s failed: %s\n",
      pelog,
      strerror(errno));

    if (write(2, log_buffer, strlen(log_buffer)) == -1) 
      {
      /* cannot write message to stderr */

      /* NO-OP */
      }

    fsync(2);

    exit(255);
    }  /* END else () */

  switch (run_exit)
    {
    case 0:

      /* SUCCESS */

      /* NO-OP */

      break;

    case - 3:

      pelog_err(pjob, pelog, run_exit, "child wait interrupted");

      break;

    case - 4:

      pelog_err(pjob, pelog, run_exit, "prolog/epilog timeout occurred, child cleaned up");

      break;

    case - 5:

      pelog_err(pjob, pelog, run_exit, "prolog/epilog timeout occurred, cannot kill child");

      break;

    default:

      pelog_err(pjob, pelog, run_exit, "nonzero p/e exit status");

      break;
    }  /* END switch (run_exit) */

  return(run_exit);
  }  /* END run_pelog() */
Esempio n. 8
0
void I_InitGraphics(void)
{
    SDL_Event dummy;
    byte *doompal;
    char *env;

    // Pass through the XSCREENSAVER_WINDOW environment variable to 
    // SDL_WINDOWID, to embed the SDL window into the Xscreensaver
    // window.

    env = getenv("XSCREENSAVER_WINDOW");

    if (env != NULL)
    {
        char winenv[30];
        int winid;

        sscanf(env, "0x%x", &winid);
        snprintf(winenv, sizeof(winenv), "SDL_WINDOWID=%i", winid);

        putenv(winenv);
    }

    SetSDLVideoDriver();
    SetWindowPositionVars();

    if (SDL_Init(SDL_INIT_VIDEO) < 0) 
    {
        I_Error("Failed to initialize video: %s", SDL_GetError());
    }

    // Set up title and icon.  Windows cares about the ordering; this
    // has to be done before the call to SDL_SetVideoMode.

    I_InitWindowTitle();
#if !SDL_VERSION_ATLEAST(1, 3, 0)
    I_InitWindowIcon();
#endif

    // Warning to OS X users... though they might never see it :(
#ifdef __MACOSX__
    if (fullscreen)
    {
        printf("Some old versions of OS X might crash in fullscreen mode.\n"
               "If this happens to you, switch back to windowed mode.\n");
    }
#endif

    //
    // Enter into graphics mode.
    //
    // When in screensaver mode, run full screen and auto detect
    // screen dimensions (don't change video mode)
    //

    if (screensaver_mode)
    {
        SetVideoMode(NULL, 0, 0);
    }
    else
    {
        int w, h;

        if (autoadjust_video_settings)
        {
            I_AutoAdjustSettings();
        }

        w = screen_width;
        h = screen_height;

        screen_mode = I_FindScreenMode(w, h);

        if (screen_mode == NULL)
        {
            I_Error("I_InitGraphics: Unable to find a screen mode small "
                    "enough for %ix%i", w, h);
        }

        if (w != screen_mode->width || h != screen_mode->height)
        {
            printf("I_InitGraphics: %s (%ix%i within %ix%i)\n",
                   WindowBoxType(screen_mode, w, h),
                   screen_mode->width, screen_mode->height, w, h);
        }

        SetVideoMode(screen_mode, w, h);
    }

    // Start with a clear black screen
    // (screen will be flipped after we set the palette)

    SDL_FillRect(screenbuffer, NULL, 0);

    // Set the palette

    doompal = W_CacheLumpName(DEH_String("PLAYPAL"), PU_CACHE);
    I_SetPalette(doompal);
    SDL_SetColors(screenbuffer, palette, 0, 256);

    CreateCursors();

    UpdateFocus();
    UpdateGrab();

    // On some systems, it takes a second or so for the screen to settle
    // after changing modes.  We include the option to add a delay when
    // setting the screen mode, so that the game doesn't start immediately
    // with the player unable to see anything.

    if (fullscreen && !screensaver_mode)
    {
        SDL_Delay(startup_delay);
    }

    // Check if we have a native surface we can use
    // If we have to lock the screen, draw to a buffer and copy
    // Likewise if the screen pitch is not the same as the width
    // If we have to multiply, drawing is done to a separate 320x200 buf

    native_surface = screen == screenbuffer
                  && !SDL_MUSTLOCK(screen)
                  && screen_mode == &mode_scale_1x
                  && screen->pitch == SCREENWIDTH
                  && aspect_ratio_correct;

    // If not, allocate a buffer and copy from that buffer to the
    // screen when we do an update

    if (native_surface)
    {
	I_VideoBuffer = (unsigned char *) screen->pixels;

        I_VideoBuffer += (screen->h - SCREENHEIGHT) / 2;
    }
    else
    {
	I_VideoBuffer = (unsigned char *) Z_Malloc (SCREENWIDTH * SCREENHEIGHT, 
                                                    PU_STATIC, NULL);
    }

    V_RestoreBuffer();

    // Clear the screen to black.

    memset(I_VideoBuffer, 0, SCREENWIDTH * SCREENHEIGHT);

    // We need SDL to give us translated versions of keys as well

    SDL_EnableUNICODE(1);

    // Repeat key presses - this is what Vanilla Doom does
    // Not sure about repeat rate - probably dependent on which DOS
    // driver is used.  This is good enough though.

    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    // clear out any events waiting at the start and center the mouse
  
    while (SDL_PollEvent(&dummy));

    initialized = true;

    // Call I_ShutdownGraphics on quit

    I_AtExit(I_ShutdownGraphics, true);
}
Esempio n. 9
0
void UIFrameBufferSDL::resizeEvent(UIResizeEvent *pEvent)
{
    /* Check whether the guest resolution has not been changed. */
    bool fSameResolutionRequested = (width()  == pEvent->width() && height() == pEvent->height());

    /* Check if the guest VRAM can be used as the source bitmap. */
    bool bFallback = false;

    Uint32 Rmask = 0;
    Uint32 Gmask = 0;
    Uint32 Bmask = 0;

    if (pEvent->pixelFormat() == FramebufferPixelFormat_FOURCC_RGB)
    {
        switch (pEvent->bitsPerPixel())
        {
            case 32:
                Rmask = 0x00FF0000;
                Gmask = 0x0000FF00;
                Bmask = 0x000000FF;
                break;
            case 24:
                Rmask = 0x00FF0000;
                Gmask = 0x0000FF00;
                Bmask = 0x000000FF;
                break;
            case 16:
                Rmask = 0xF800;
                Gmask = 0x07E0;
                Bmask = 0x001F;
                break;
            default:
                /* Unsupported format leads to the indirect buffer */
                bFallback = true;
                break;
        }
    }
    else
    {
        /* Unsupported format leads to the indirect buffer */
        bFallback = true;
    }

    m_width = pEvent->width();
    m_height = pEvent->height();

    /* Recreate the source surface. */
    if (m_pSurfVRAM)
    {
        SDL_FreeSurface(m_pSurfVRAM);
        m_pSurfVRAM = NULL;
    }

    if (!bFallback)
    {
        /* It is OK to create the source surface from the guest VRAM. */
        m_pSurfVRAM = SDL_CreateRGBSurfaceFrom(pEvent->VRAM(), pEvent->width(), pEvent->height(),
                                               pEvent->bitsPerPixel(),
                                               pEvent->bytesPerLine(),
                                               Rmask, Gmask, Bmask, 0);
        LogFlowFunc(("Created VRAM surface %p\n", m_pSurfVRAM));
        if (m_pSurfVRAM == NULL)
        {
            bFallback = true;
        }
    }

    if (fSameResolutionRequested)
    {
        LogFlowFunc(("the same resolution requested, skipping the resize.\n"));
        return;
    }

    /* close SDL so we can init it again */
    if (m_pScreen)
    {
        X11ScreenSaverSettingsSave();
        SDL_QuitSubSystem(SDL_INIT_VIDEO);
        X11ScreenSaverSettingsRestore();
        m_pScreen = NULL;
    }

    /*
     *  initialize the SDL library, use its super hack to integrate it with our client window
     */
    static char sdlHack[64];
    LogFlowFunc(("Using client window 0x%08lX to initialize SDL\n", m_pMachineView->viewport()->winId()));
    /* Note: SDL_WINDOWID must be decimal (not hex) to work on Win32 */
    sprintf(sdlHack, "SDL_WINDOWID=%lu", m_pMachineView->viewport()->winId());
    putenv(sdlHack);
    X11ScreenSaverSettingsSave();
    int rc = SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
    X11ScreenSaverSettingsRestore();
    AssertMsg(rc == 0, ("SDL initialization failed: %s\n", SDL_GetError()));
    NOREF(rc);

#ifdef Q_WS_X11
    /* undo signal redirections from SDL, it'd steal keyboard events from us! */
    signal(SIGINT, SIG_DFL);
    signal(SIGQUIT, SIG_DFL);
#endif

    LogFlowFunc(("Setting SDL video mode to %d x %d\n", m_width, m_height));

    /* Pixel format is RGB in any case */
    m_uPixelFormat = FramebufferPixelFormat_FOURCC_RGB;

    m_pScreen = SDL_SetVideoMode(m_width, m_height, 0, SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL);
    AssertMsg(m_pScreen, ("SDL video mode could not be set!\n"));
}
Esempio n. 10
0
EFI_STATUS
main(int argc, CHAR16 *argv[])
{
	char var[128];
	EFI_LOADED_IMAGE *img;
	EFI_GUID *guid;
	int i, j, vargood, unit, howto;
	struct devsw *dev;
	uint64_t pool_guid;
	UINTN k;
	int has_kbd;
	char buf[40];

	archsw.arch_autoload = efi_autoload;
	archsw.arch_getdev = efi_getdev;
	archsw.arch_copyin = efi_copyin;
	archsw.arch_copyout = efi_copyout;
	archsw.arch_readin = efi_readin;
#ifdef EFI_ZFS_BOOT
	/* Note this needs to be set before ZFS init. */
	archsw.arch_zfs_probe = efi_zfs_probe;
#endif

	/* Init the time source */
	efi_time_init();

	has_kbd = has_keyboard();

	/*
	 * XXX Chicken-and-egg problem; we want to have console output
	 * early, but some console attributes may depend on reading from
	 * eg. the boot device, which we can't do yet.  We can use
	 * printf() etc. once this is done.
	 */
	cons_probe();

	/*
	 * Initialise the block cache. Set the upper limit.
	 */
	bcache_init(32768, 512);

	/*
	 * Parse the args to set the console settings, etc
	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
	 * or iPXE may be setup to pass these in.
	 *
	 * Loop through the args, and for each one that contains an '=' that is
	 * not the first character, add it to the environment.  This allows
	 * loader and kernel env vars to be passed on the command line.  Convert
	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied.
	 */
	howto = 0;
	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			for (j = 1; argv[i][j] != 0; j++) {
				int ch;

				ch = argv[i][j];
				switch (ch) {
				case 'a':
					howto |= RB_ASKNAME;
					break;
				case 'd':
					howto |= RB_KDB;
					break;
				case 'D':
					howto |= RB_MULTIPLE;
					break;
				case 'h':
					howto |= RB_SERIAL;
					break;
				case 'm':
					howto |= RB_MUTE;
					break;
				case 'p':
					howto |= RB_PAUSE;
					break;
				case 'P':
					if (!has_kbd)
						howto |= RB_SERIAL | RB_MULTIPLE;
					break;
				case 'r':
					howto |= RB_DFLTROOT;
					break;
				case 's':
					howto |= RB_SINGLE;
					break;
				case 'S':
					if (argv[i][j + 1] == 0) {
						if (i + 1 == argc) {
							setenv("comconsole_speed", "115200", 1);
						} else {
							cpy16to8(&argv[i + 1][0], var,
							    sizeof(var));
							setenv("comconsole_speedspeed", var, 1);
						}
						i++;
						break;
					} else {
						cpy16to8(&argv[i][j + 1], var,
						    sizeof(var));
						setenv("comconsole_speed", var, 1);
						break;
					}
				case 'v':
					howto |= RB_VERBOSE;
					break;
				}
			}
		} else {
			vargood = 0;
			for (j = 0; argv[i][j] != 0; j++) {
				if (j == sizeof(var)) {
					vargood = 0;
					break;
				}
				if (j > 0 && argv[i][j] == '=')
					vargood = 1;
				var[j] = (char)argv[i][j];
			}
			if (vargood) {
				var[j] = 0;
				putenv(var);
			}
		}
	}
	for (i = 0; howto_names[i].ev != NULL; i++)
		if (howto & howto_names[i].mask)
			setenv(howto_names[i].ev, "YES", 1);
	if (howto & RB_MULTIPLE) {
		if (howto & RB_SERIAL)
			setenv("console", "comconsole efi" , 1);
		else
			setenv("console", "efi comconsole" , 1);
	} else if (howto & RB_SERIAL) {
		setenv("console", "comconsole" , 1);
	}

	if (efi_copy_init()) {
		printf("failed to allocate staging area\n");
		return (EFI_BUFFER_TOO_SMALL);
	}

	/*
	 * March through the device switch probing for things.
	 */
	for (i = 0; devsw[i] != NULL; i++)
		if (devsw[i]->dv_init != NULL)
			(devsw[i]->dv_init)();

	/* Get our loaded image protocol interface structure. */
	BS->HandleProtocol(IH, &imgid, (VOID**)&img);

	printf("Command line arguments:");
	for (i = 0; i < argc; i++)
		printf(" %S", argv[i]);
	printf("\n");

	printf("Image base: 0x%lx\n", (u_long)img->ImageBase);
	printf("EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
	    ST->Hdr.Revision & 0xffff);
	printf("EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);

	printf("\n");
	printf("%s, Revision %s\n", bootprog_name, bootprog_rev);
	printf("(%s, %s)\n", bootprog_maker, bootprog_date);

	/*
	 * Disable the watchdog timer. By default the boot manager sets
	 * the timer to 5 minutes before invoking a boot option. If we
	 * want to return to the boot manager, we have to disable the
	 * watchdog timer and since we're an interactive program, we don't
	 * want to wait until the user types "quit". The timer may have
	 * fired by then. We don't care if this fails. It does not prevent
	 * normal functioning in any way...
	 */
	BS->SetWatchdogTimer(0, 0, 0, NULL);

	if (find_currdev(img, &dev, &unit, &pool_guid) != 0)
		return (EFI_NOT_FOUND);

	switch (dev->dv_type) {
#ifdef EFI_ZFS_BOOT
	case DEVT_ZFS: {
		struct zfs_devdesc currdev;

		currdev.d_dev = dev;
		currdev.d_unit = unit;
		currdev.d_type = currdev.d_dev->dv_type;
		currdev.d_opendata = NULL;
		currdev.pool_guid = pool_guid;
		currdev.root_guid = 0;
		env_setenv("currdev", EV_VOLATILE, efi_fmtdev(&currdev),
			   efi_setcurrdev, env_nounset);
		env_setenv("loaddev", EV_VOLATILE, efi_fmtdev(&currdev), env_noset,
			   env_nounset);
		init_zfs_bootenv(zfs_fmtdev(&currdev));
		break;
	}
#endif
	default: {
		struct devdesc currdev;

		currdev.d_dev = dev;
		currdev.d_unit = unit;
		currdev.d_opendata = NULL;
		currdev.d_type = currdev.d_dev->dv_type;
		env_setenv("currdev", EV_VOLATILE, efi_fmtdev(&currdev),
			   efi_setcurrdev, env_nounset);
		env_setenv("loaddev", EV_VOLATILE, efi_fmtdev(&currdev), env_noset,
			   env_nounset);
		break;
	}
	}

	snprintf(var, sizeof(var), "%d.%02d", ST->Hdr.Revision >> 16,
	    ST->Hdr.Revision & 0xffff);
	env_setenv("efi-version", EV_VOLATILE, var, env_noset, env_nounset);
	setenv("LINES", "24", 1);	/* optional */

	for (k = 0; k < ST->NumberOfTableEntries; k++) {
		guid = &ST->ConfigurationTable[k].VendorGuid;
		if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
			snprintf(buf, sizeof(buf), "%p",
			    ST->ConfigurationTable[k].VendorTable);
			setenv("hint.smbios.0.mem", buf, 1);
			smbios_detect(ST->ConfigurationTable[k].VendorTable);
			break;
		}
	}

	interact(NULL);			/* doesn't return */

	return (EFI_SUCCESS);		/* keep compiler happy */
}
void I_InitGraphics(void)
{
    SDL_Event dummy;
    byte *doompal;
    int flags = 0;
    char *env;

    // Pass through the XSCREENSAVER_WINDOW environment variable to 
    // SDL_WINDOWID, to embed the SDL window into the Xscreensaver
    // window.

    env = getenv("XSCREENSAVER_WINDOW");

    if (env != NULL)
    {
        char winenv[30];
        int winid;

        sscanf(env, "0x%x", &winid);
        sprintf(winenv, "SDL_WINDOWID=%i", winid);

        putenv(winenv);
    }

    SetSDLVideoDriver();

    if (SDL_Init(SDL_INIT_VIDEO) < 0) 
    {
        I_Error("Failed to initialize video: %s", SDL_GetError());
    }

    // Check for command-line video-related parameters.

    CheckCommandLine();

    doompal = W_CacheLumpName (DEH_String("PLAYPAL"),PU_CACHE);

    if (screensaver_mode)
    {
        windowwidth = 0;
        windowheight = 0;
    }
    else
    {
        if (autoadjust_video_settings)
        {
            I_AutoAdjustSettings();
        }

        windowwidth = screen_width;
        windowheight = screen_height;

        screen_mode = I_FindScreenMode(windowwidth, windowheight);

        if (screen_mode == NULL)
        {
            I_Error("I_InitGraphics: Unable to find a screen mode small "
                    "enough for %ix%i", windowwidth, windowheight);
        }

        if (windowwidth != screen_mode->width
         || windowheight != screen_mode->height)
        {
            printf("I_InitGraphics: %s (%ix%i within %ix%i)\n",
                   WindowBoxType(screen_mode, windowwidth, windowheight),
                   screen_mode->width, screen_mode->height,
                   windowwidth, windowheight);
        }

        // Generate lookup tables before setting the video mode.

        if (screen_mode->InitMode != NULL)
        {
            screen_mode->InitMode(doompal);
        }
    }

    // Set up title and icon.  Windows cares about the ordering; this
    // has to be done before the call to SDL_SetVideoMode.

    I_SetWindowCaption();
#if !SDL_VERSION_ATLEAST(1, 3, 0)
    I_SetWindowIcon();
#endif

    // Set the video mode.

    flags |= SDL_SWSURFACE | SDL_HWPALETTE | SDL_DOUBLEBUF;

    if (fullscreen)
    {
        flags |= SDL_FULLSCREEN;
    }

    screen = SDL_SetVideoMode(windowwidth, windowheight, 8, flags);

    if (screen == NULL)
    {
        I_Error("Error setting video mode: %s\n", SDL_GetError());
    }

    // Start with a clear black screen
    // (screen will be flipped after we set the palette)

    if (SDL_LockSurface(screen) >= 0)
    {
        byte *screenpixels;
        int y;

        screenpixels = (byte *) screen->pixels;

        for (y=0; y<screen->h; ++y)
            memset(screenpixels + screen->pitch * y, 0, screen->w);

        SDL_UnlockSurface(screen);
    }

    // Set the palette

    I_SetPalette(doompal);
    SDL_SetColors(screen, palette, 0, 256);

    CreateCursors();

    UpdateFocus();
    UpdateGrab();

    // In screensaver mode, now find a screen_mode to use.

    if (screensaver_mode)
    {
        screen_mode = I_FindScreenMode(screen->w, screen->h);

        if (screen_mode == NULL)
        {
            I_Error("I_InitGraphics: Unable to find a screen mode small "
                    "enough for %ix%i", screen->w, screen->h);
        }

        // Generate lookup tables before setting the video mode.

        if (screen_mode->InitMode != NULL)
        {
            screen_mode->InitMode(doompal);
        }
    }
    
    // On some systems, it takes a second or so for the screen to settle
    // after changing modes.  We include the option to add a delay when
    // setting the screen mode, so that the game doesn't start immediately
    // with the player unable to see anything.

    if (fullscreen && !screensaver_mode)
    {
        SDL_Delay(startup_delay);
    }

    // Check if we have a native surface we can use
    // If we have to lock the screen, draw to a buffer and copy
    // Likewise if the screen pitch is not the same as the width
    // If we have to multiply, drawing is done to a separate 320x200 buf

    native_surface = !SDL_MUSTLOCK(screen) 
                  && screen_mode == &mode_scale_1x
                  && screen->pitch == SCREENWIDTH
                  && aspect_ratio_correct;

    // If not, allocate a buffer and copy from that buffer to the 
    // screen when we do an update

    if (native_surface)
    {
	screens[0] = (unsigned char *) screen->pixels;

        screens[0] += (screen->h - SCREENHEIGHT) / 2;
    }
    else
    {
	screens[0] = (unsigned char *) Z_Malloc (SCREENWIDTH * SCREENHEIGHT, 
                                                 PU_STATIC, NULL);
    }

    // "Loading from disk" icon

    LoadDiskImage();

    // Clear the screen to black.

    memset(screens[0], 0, SCREENWIDTH * SCREENHEIGHT);

    // We need SDL to give us translated versions of keys as well

    SDL_EnableUNICODE(1);

    // Repeat key presses - this is what Vanilla Doom does
    // Not sure about repeat rate - probably dependent on which DOS
    // driver is used.  This is good enough though.

    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    // clear out any events waiting at the start and center the mouse
  
    while (SDL_PollEvent(&dummy));

    if (usemouse && !nomouse && (fullscreen || grabmouse))
    {
        CenterMouse();
    }

    initialized = true;
}
Esempio n. 12
0
//----------------------------------- Main -------------------------------------
int main(int argc, char *argv[])
{
    std::string cheat_string = "cheat";
    //std::locale::global( std::locale( "" ) );
    events_init();
    game.log.File_Set("Star.P.G..log");
    game.log.File_Clear();
    if (argc > 1)
    {
        for (int count = 0; count < (argc+1); count++)
        {
            //game.log.File_Write(argv[count]);
            if (cheat_string.compare(argv[count]) == 0) game_o.cheats_enabled = true;
        }
    }
    //game_o.cheats_enabled = true; /// test!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    game.log.File_Write("------------------");
    game.log.File_Write("| Star.P.G V1.01 |");
    game.log.File_Write("------------------\n");
    game.log.File_Write("Starting up!");
    game.log.File_Write("");
    game.log.File_Write("------------------\n");
    //if (game_o.cheats_enabled) game.log.File_Write("Cheating enabled!\n");
    game.config.File_Set("Star.P.G..cfg");
    game.config.Set_Defaults();
    game.log.File_Write("Loading config...");
    game.config.File_Set("Star.P.G..cfg");
    game.config.File_Read();
    game.log.File_Write("Loading language file -> data/configuration/languages/"+game.config.language+".txt");
    game_o.language.load("data/configuration/languages/"+game.config.language+".txt");
 //----------------------------------- Start the PhysicsFS ----------------------
    //game.log.File_Write("Starting PhysicsFS...");
    //PHYSFS_init(argv[0]);
    //PHYSFS_addToSearchPath("Star.P.G..spg", 1);
//----------------------------------- SDL Video --------------------------------
    game.log.File_Write("Starting SDL...");
    char SDL_VID_WIN_POS[] = "SDL_VIDEO_WINDOW_POS";
    char SDL_VID_CENTERD[] = "SDL_VIDEO_CENTERED=1";
    putenv(SDL_VID_WIN_POS);
    putenv(SDL_VID_CENTERD);
    getenv("SDL_VIDEO_WINDOW_POS");
    getenv("SDL_VIDEO_CENTERED");
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD);
    game.log.File_Write("Starting OpenGL...");
    if (game.config.Display_Fullscreen) SDL_SetVideoMode(game.config.Display_X_Resolution,game.config.Display_Y_Resolution,game.config.Display_BPS,SDL_OPENGL | SDL_FULLSCREEN);
    else SDL_SetVideoMode(game.config.Display_X_Resolution,game.config.Display_Y_Resolution,game.config.Display_BPS,SDL_OPENGL/* | SDL_NOFRAME */);
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    App_Icon_Surface = SDL_LoadBMP(App_Icon);
    colorkey = SDL_MapRGB(App_Icon_Surface->format, 255, 0, 255);
    SDL_SetColorKey(App_Icon_Surface, SDL_SRCCOLORKEY, colorkey);
    SDL_WM_SetIcon(App_Icon_Surface,NULL);
    SDL_WM_SetCaption(App_Name, 0);
    //SDL_ShowCursor(SDL_DISABLE);
//----------------------------------- SDL Audio --------------------------------
    game.log.File_Write("Starting sound system...");
    SDL_Init(SDL_INIT_AUDIO);
    Mix_AllocateChannels(game.config.Audio_Channels);
    Mix_OpenAudio(game.config.Audio_Rate, AUDIO_S16, 2, game.config.Audio_Buffers);
    Mix_Volume(-1,game.config.Audio_Sound_Volume);
    Mix_VolumeMusic(game.config.Audio_Music_Volume);
    game.log.File_Write("Initializing joystick / gamepad...");
    SDL_Init(SDL_INIT_JOYSTICK);
    game.log.File_Write("Initializing game system...");
    init_game(false);
    game.log.File_Write("Initializing projectiles...");
    init_player_bullets();
    game.log.File_Write("Initializing explosions...");
    init_explosions();
    game.log.File_Write("Initializing NPCs...\n");
    init_active_npcs();
    init_npc_bullets();
    init_npcs(0);
    game_o.current_level = 0;
    game.log.File_Write("Initializing OpenGL...");
    game.graphics.init_gl(game.config.Display_X_Resolution,game.config.Display_Y_Resolution);
    seed_rand();
    TTF_Init();
    game.log.File_Write("Loading resources...");
    loading_screen_display("data/textures/misc/loading_screen.png");
    load_resources();
    game.log.File_Write("Initializing menu system...");
    init_menu();
    init_in_game_message_class();
    init_projectiles(false);
    init_powerups();
    init_shields(false);
    init_game(false);
    game.log.File_Write("Starting game...");
    game.log.File_Write("---------------\n");
//----------------------------------- Main loop --------------------------------
    game.timer.start();
    game.LastTicks = game.timer.getticks();
    for(int quit = 0; !quit;)
    {
        game.config.process(false);
        if (game.config.mouse_autohide) SDL_ShowCursor(SDL_DISABLE);
        else SDL_ShowCursor(SDL_ENABLE);
        proc_textures();
        events_process();
        if (game.status_quit_active) quit = 1;
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//****************************************** MENU *****************************************
        if (game.menu_active)
        {
            SDL_ShowCursor(SDL_ENABLE);
            if (game.music_next_track)
            {
                music.menu_00.play();
                game.music_next_track = false;
            }
            diplay_menu ();
            if (game.process_ready) game.background.process();
            if (game.process_ready) process_menu();
        }
//****************************************** GAME *****************************************
        if (game.game_active)
        {
            if (game.music_next_track)
            {
                game.music_next_track = false;
                if (game.music_track ==  0) music.level_00.play();
                if (game.music_track ==  1) music.level_01.play();
                if (game.music_track ==  2) music.level_02.play();
                if (game.music_track ==  3) music.level_03.play();
                if (game.music_track ==  4) music.level_04.play();
                if (game.music_track ==  5) music.level_05.play();
                if (game.music_track ==  6) music.level_06.play();
                if (game.music_track ==  7) music.level_07.play();
                if (game.music_track ==  8) music.level_08.play();
                if (game.music_track ==  9) music.level_09.play();
                if (game.music_track == 10) music.level_10.play();
                if (game.music_track == 11) music.level_11.play();
                if (game.music_track == 12) music.level_12.play();
                if (game.music_track == 13) music.level_13.play();
                if (game.music_track == 14) music.level_14.play();
                if (game.music_track == 15) music.level_15.play();
                if (game.music_track == 16) music.level_16.play();
                if (game.music_track == 17) music.level_17.play();
                if (game.music_track == 18) music.level_18.play();
                if (game.music_track == 19) music.level_19.play();
                if (game.music_track == 20) music.level_20.play();
                if (game.music_track == 21) music.level_21.play();
                if (game.music_track == 22) music.level_22.play();
                if (game.music_track == 23) music.level_23.play();
                if (game.music_track == 24) music.level_24.play();
                if (game.music_track == 25) music.level_25.play();
            }
            game.game_resume = true;
            if (game.process_ready) process_game();
            display_game();
            if ((game.config.Display_Touchscreen) && (game.process_ready))
            {
                if(game.physics.point_in_quadrangle(-0.875f,0.2f,-0.550f,0.2f,game.io.mouse_x,game.io.mouse_y)) game.io.left = true;
                if(game.physics.point_in_quadrangle(-0.475f,0.2f,-0.550f,0.2f,game.io.mouse_x,game.io.mouse_y)) game.io.right = true;
                if(game.physics.point_in_quadrangle(-0.675f,0.2f,-0.350f,0.2f,game.io.mouse_x,game.io.mouse_y)) game.io.up = true;
                if(game.physics.point_in_quadrangle(-0.675f,0.2f,-0.750f,0.2f,game.io.mouse_x,game.io.mouse_y)) game.io.down = true;
                if(game.physics.point_in_quadrangle( 0.875f,0.2f,-0.750f,0.2f,game.io.mouse_x,game.io.mouse_y)) game.io.shoot = true;
                if(game.physics.point_in_quadrangle( 0.575f,0.2f,-0.750f,0.2f,game.io.mouse_x,game.io.mouse_y)) game.io.key_b = true;
                if(game.physics.point_in_quadrangle( 0.875f,0.2f, 0.750f,0.2f,game.io.mouse_x,game.io.mouse_y)) game.io.escape = true;
            }
            if (game_o.player.health < 0)
            {
                sound.menu_select_00.play();
                game.game_active             = false;
                game.game_resume             = false;
                game.pdie_active             = true;
                game.menu_level              = 8;
                game.config.menu_delay_count = 0;
                music.level_pd.play();
                game.background.set_data  ( 2, 1, 1, 0.0f, 0.0f, 0.0050f, 0.0050f, texture.background_019.ref_number);
                game.background.set_data  ( 1, 1, 1, 0.0f, 0.0f, 0.0020f, 0.0020f, texture.background_008.ref_number);
                game.background.set_active( 3, false);
                game.background.set_active( 4, false);
                game.background.set_movement_type(BOUNCE);
                SDL_WarpMouse(game.graphics.gl_to_res(game_over_menu.get_button_x_pos(1),game.config.mouse_resolution_x),game.config.mouse_resolution_y-game.graphics.gl_to_res(game_over_menu.get_button_y_pos(1),game.config.mouse_resolution_y));
                game.log.File_Write("User terminated due to insufficient health...better luck next time buddy!");
            }
        if ((game.io.escape) && (game.process_ready))
        {
            sound.menu_select_01.play();
            game.music_next_track        = true;
            game.game_active             = false;
            game.menu_level              = 1;
            game.menu_active             = true;
            game.io.escape               = false;
            game.io.keyboard_delay_count = 0;
            game.config.menu_delay_count = 0;
            while (game.config.menu_delay_count < (game.config.menu_delay/2))
            {
                game.config.menu_delay_count++;
            }
        }

        if (game_o.bomb_delay_count < game_o.bomb_delay)//bomb delay counter
        {
            game_o.bomb_delay_count++;
            if (game_o.bomb_delay_count > game_o.bomb_delay) game_o.bomb_delay_count = game_o.bomb_delay;
        }
        if ((game.io.key_b) && (game.process_ready))//user pressed "b" for bomb
        {
            if ((game_o.number_bombs > 0) && (game_o.bomb_delay_count >= game_o.bomb_delay))
            {
                game_o.number_bombs--;
                use_bomb_powerup();
                game_o.bomb_delay_count = 0;
                if (!game_o.rumble.active) sound.explosion_001.play();
                if (!game_o.rumble.active) game_o.rumble.start(0.025f,45); // shake the screen about.
            }
        }
        if (game.io.pause)
        {
            if (!game.game_paused)
            {
                game_o.paused.spawn();
                game.game_paused = true;
                game.game_active = false;
                game.io.pause    = false;
                game.menu_level  = 11;
                SDL_WarpMouse(game.graphics.gl_to_res(pause_menu.get_button_x_pos(1),game.config.mouse_resolution_x),game.config.mouse_resolution_y-game.graphics.gl_to_res(pause_menu.get_button_y_pos(1),game.config.mouse_resolution_y));
                game.config.menu_delay_count = 0;
                while (game.config.menu_delay_count < (game.config.menu_delay*16))
                {
                    game.config.menu_delay_count++;
                }
            }
            else
            {
                game.menu_active = false;
                game.game_paused = false;
                game.game_active = true;
            }
        };

        if (game_o.cheats_enabled == true)
        {
            if (game.io.key_0) game_o.victory_kills = game_o.level_kills;  //complete level
            if (game.io.key_1) spawn_powerup(1.0f,random_GLcoord(), 1);//spawn health power-up
            if (game.io.key_2) spawn_powerup(1.0f,random_GLcoord(), 2);//spawn shield level power-up
            if (game.io.key_3) spawn_powerup(1.0f,random_GLcoord(), 3);//spawn shield new power-up
            if (game.io.key_4) spawn_powerup(1.0f,random_GLcoord(), 4);//spawn thruster level power-up
            if (game.io.key_5) spawn_powerup(1.0f,random_GLcoord(), 5);//spawn thruster new power-up
            if (game.io.key_6) spawn_powerup(1.0f,random_GLcoord(), 6);//spawn weapon level power-up
            if (game.io.key_7) spawn_powerup(1.0f,random_GLcoord(), 7);//spawn weapon new power-up
            if (game.io.key_8) unlock_levels();                        //unlock all levels
            if (game.io.key_9) spawn_powerup(1.0f,random_GLcoord(), 8);//spawn bomb power-up
            if (game.io.key_a) game_o.anc_enabled   = !game_o.anc_enabled; //toggle active NPC count display
            if (game.io.key_f) game_o.fps_enabled   = !game_o.fps_enabled; //toggle active NPC count display
            if (game.io.key_q) spawn_powerup(1.0f,random_GLcoord(), 9);//spawn support ship 0 power-up
            if (game.io.key_w) spawn_powerup(1.0f,random_GLcoord(),10);//spawn support ship 1 power-up
            if (game.io.key_e) spawn_powerup(1.0f,random_GLcoord(),11);//spawn support ship 2 power-up
            if (game.io.key_r) spawn_powerup(1.0f,random_GLcoord(),12);//spawn support ship 3 power-up
            if (game.io.key_s)
            {
                if (!game_o.rumble.active) sound.explosion_001.play();
                if (!game_o.rumble.active) game_o.rumble.start(); // shake the screen about.
            }
        }

        if (game.io.shoot)
        {
           process_supportships(true);
           if(game_o.fw_rof_count >= game_o.projectile[game_o.player.front_weapon].rate_of_fire)
           {
              spawn_player_bullet(0);
              game_o.fw_rof_count = 0;
           }
           if(game_o.sw_rof_count >= game_o.projectile[game_o.player.side_weapon].rate_of_fire)
           {
              spawn_player_bullet(1);
              game_o.sw_rof_count = 0;
           }
        }
        else
        {
            process_supportships(false);
        }
        if (game.process_ready)
        {
            if (game.io.up)    process_player(1);
            if (game.io.down)  process_player(2);
            if (game.io.right) process_player(3);
            if (game.io.left)  process_player(4);
        }
        if ((game.io.key_1) && (game_o.projectile[ 0].active))
        {
            game_o.player.front_weapon = 0;
        }
        if ((game.io.key_2) && (game_o.projectile[ 1].active))
        {
            game_o.player.front_weapon = 1;
        }
        if ((game.io.key_3) && (game_o.projectile[ 2].active))
        {
            game_o.player.front_weapon = 2;
        }
        if ((game.io.key_4) && (game_o.projectile[ 3].active))
        {
            game_o.player.front_weapon = 3;
        }
        if ((game.io.key_5) && (game_o.projectile[ 4].active))
        {
            game_o.player.front_weapon = 4;
        }
        if ((game.io.key_6) && (game_o.projectile[ 5].active))
        {
            game_o.player.front_weapon = 5;
        }
    }
//*********************************** Game paused *****************************************
        if (game.game_paused)
        {
            if ((game.io.pause) && (game.process_ready))
            {
                game.menu_active = false;
                game.game_paused = false;
                game.game_active = true;
            }
            if (game.music_next_track)
            {
                game.music_next_track = false;
                music.level_pd.play();
            }
            game.menu_level = 11;
            if (game.process_ready) game.background.process();
            if (game.process_ready) process_menu();
            display_game();
            diplay_menu ();
         }
//*********************************** PLAYER DEATH SCREEN *****************************************
        if (game.pdie_active)
        {
            if (game.music_next_track)
            {
                game.music_next_track = false;
                music.level_pd.play();
            }
            diplay_menu ();
            if (game.process_ready) game.background.process();
            if (game.process_ready) process_menu();
            if (!game.pdie_active)  init_game(true);
        }
//******************************* PLAYER NEXT LEVEL SCREEN *************************************
        if (game.nlvl_active)
        {
            if (game.music_next_track)
            {
                game.music_next_track = false;
                music.level_nl.play();
            }
            game.menu_level = 9;
            if (game.process_ready) game.background.process();
            if (game.process_ready) process_menu();
            diplay_menu ();
        }
//******************************* OUTRO SCREEN *************************************************
     if (game.outr_active)
        {
            if (game.music_next_track)
            {
                game.music_next_track = false;
                music.outro_00.play();
            }
            game.menu_level = 10;
            if (game.process_ready) game.background.process();
            if (game.process_ready) process_menu();
            diplay_menu ();
        }
//---------------------------- code for end of main loop -----------------------
        game.FPS = (game.timer.getticks() - game.LastTicks);
        if ((game.timer.getticks() - game.LastTicks) >= 2)
        {
            game.LastTicks = game.timer.getticks();
            game.process_ready = true;
        }
        else game.process_ready = false;
        SDL_GL_SwapBuffers();
    }
//----------------------------------- Exit -------------------------------------
    game.log.File_Write("Saving configuration...");
    game.config.File_Set("Star.P.G..cfg");
    game.config.File_Clear();
    game.config.File_Write();
    game.log.File_Write("\n");
    game.log.File_Write("Shutting down...");
    game.log.File_Write("---------------\n");
//    game.log.File_Write("PhysicsFS deinit...");
//    PHYSFS_deinit();
    game.log.File_Write("SDL deinit...");
    SDL_Quit();
    return(0);
}
Esempio n. 13
0
int
main(int argc, char *argv[])
{
    int authenticated = 0;
    int retcode;
    char *username;
    int setcred = 1;

    if (argc < 2 || argc > 3) {
	fprintf(stderr, "Usage: %s [-u] <user>\n", argv[0]);
	exit(1);
    }
    if (argc == 3) {
	if (strcmp(argv[1], "-u") != 0) {
	    fprintf(stderr, "Usage: %s [-u] <user>\n", argv[0]);
	    exit(1);
	}
	/* service = "unixtest"; */
	setcred = 0;
	username = argv[2];
    } else {
	username = argv[1];
    }

    if ((retcode =
	 pam_start(service, username, &pam_conv, &pamh)) != PAM_SUCCESS) {
	fprintf(stderr, "PAM error %d\n", retcode);
	exit(1);
    }

    authenticated = ((retcode = pam_authenticate(pamh, 0)) == PAM_SUCCESS);

    if (!authenticated) {
	fprintf(stderr, "PAM couldn't authenticate you.\n");
	pam_end(pamh, PAM_ABORT);
	exit(1);
    }

    if ((retcode = pam_acct_mgmt(pamh, 0)) != PAM_SUCCESS) {
	fprintf(stderr, "pam_acct_mgmt returned %d.\n", retcode);
	pam_end(pamh, PAM_ABORT);
	exit(1);
    }

    /* pam_open_session */

    if (setcred)
	if ((retcode = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
	    fprintf(stderr, "pam_setcred returned %d.\n", retcode);
	    pam_end(pamh, PAM_ABORT);
	    exit(1);
	}

    if ((retcode = pam_open_session(pamh, PAM_SILENT)) != PAM_SUCCESS) {
	fprintf(stderr, "pam_open_session returned %d.\n", retcode);
	pam_end(pamh, PAM_ABORT);
	exit(1);
    }
    pam_end(pamh, PAM_SUCCESS);

    putenv((char *)new_envstring);
    putenv((char *)new_homestring);

    if ((retcode = chdir("/tmp")) != 0) {
	fprintf(stderr, "chdir returned %d.\n", retcode);
	exit(1);
    }

    printf("Type exit to back out.\n");
    return execl("/bin/csh", "/bin/csh", NULL);
}
Esempio n. 14
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_db_connect                                                   *
 *                                                                            *
 * Purpose: connect to the database                                           *
 *                                                                            *
 * Return value: ZBX_DB_OK - succefully connected                             *
 *               ZBX_DB_DOWN - database is down                               *
 *               ZBX_DB_FAIL - failed to connect                              *
 *                                                                            *
 ******************************************************************************/
int	zbx_db_connect(char *host, char *user, char *password, char *dbname, char *dbschema, char *dbsocket, int port)
{
	int		ret = ZBX_DB_OK;
#if defined(HAVE_IBM_DB2)
	char		*connect = NULL;
#elif defined(HAVE_ORACLE)
	char		*connect = NULL;
	sword		err = OCI_SUCCESS;
#elif defined(HAVE_POSTGRESQL)
	char		*cport = NULL;
	DB_RESULT	result;
	DB_ROW		row;
#endif

	txn_init = 1;

	assert(NULL != host);

#if defined(HAVE_IBM_DB2)
	connect = zbx_strdup(connect, "PROTOCOL=TCPIP;");
	if ('\0' != *host)
		connect = zbx_strdcatf(connect, "HOSTNAME=%s;", host);
	if (NULL != dbname && '\0' != *dbname)
		connect = zbx_strdcatf(connect, "DATABASE=%s;", dbname);
	if (0 != port)
		connect = zbx_strdcatf(connect, "PORT=%d;", port);
	if (NULL != user && '\0' != *user)
		connect = zbx_strdcatf(connect, "UID=%s;", user);
	if (NULL != password && '\0' != *password)
		connect = zbx_strdcatf(connect, "PWD=%s;", password);

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

	/* allocate an environment handle */
	if (SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &ibm_db2.henv)))
		ret = ZBX_DB_FAIL;

	/* set attribute to enable application to run as ODBC 3.0 application; */
	/* recommended for pure IBM DB2 CLI, but not required */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetEnvAttr(ibm_db2.henv, SQL_ATTR_ODBC_VERSION,
			(void *)SQL_OV_ODBC3, 0)))
		ret = ZBX_DB_FAIL;

	/* allocate a database connection handle */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_DBC, ibm_db2.henv,
			&ibm_db2.hdbc)))
		ret = ZBX_DB_FAIL;

	/* connect to the database */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLDriverConnect(ibm_db2.hdbc, NULL, (SQLCHAR *)connect,
			SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT)))
		ret = ZBX_DB_FAIL;

	/* set autocommit on */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_AUTOCOMMIT,
								(SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* we do not generate vendor escape clause sequences */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_NOSCAN,
								(SQLPOINTER)SQL_NOSCAN_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* set current schema */
	if (NULL != dbschema && '\0' != *dbschema && ZBX_DB_OK == ret)
	{
		char	*dbschema_esc;

		dbschema_esc = DBdyn_escape_string(dbschema);
		DBexecute("set current schema='%s'", dbschema_esc);
		zbx_free(dbschema_esc);
	}

	/* output error information */
	if (ZBX_DB_OK != ret)
	{
		zbx_ibm_db2_log_errors(SQL_HANDLE_ENV, ibm_db2.henv);
		zbx_ibm_db2_log_errors(SQL_HANDLE_DBC, ibm_db2.hdbc);

		zbx_db_close();
	}

	zbx_free(connect);
#elif defined(HAVE_MYSQL)
	conn = mysql_init(NULL);

	if (!mysql_real_connect(conn, host, user, password, dbname, port, dbsocket, CLIENT_MULTI_STATEMENTS))
	{
		zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
		ret = ZBX_DB_FAIL;
	}

	if (ZBX_DB_OK == ret)
	{
		if (0 != mysql_select_db(conn, dbname))
		{
			zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		DBexecute("set names utf8");
	}

	if (ZBX_DB_FAIL == ret)
	{
		switch (mysql_errno(conn))
		{
			case CR_CONN_HOST_ERROR:
			case CR_SERVER_GONE_ERROR:
			case CR_CONNECTION_ERROR:
			case CR_SERVER_LOST:
			case ER_SERVER_SHUTDOWN:
			case ER_ACCESS_DENIED_ERROR:		/* wrong user or password */
			case ER_ILLEGAL_GRANT_FOR_TABLE:	/* user without any privileges */
			case ER_TABLEACCESS_DENIED_ERROR:	/* user without some privilege */
			case ER_UNKNOWN_ERROR:
				ret = ZBX_DB_DOWN;
				break;
			default:
				break;
		}
	}
#elif defined(HAVE_ORACLE)
#if defined(HAVE_GETENV) && defined(HAVE_PUTENV)
	if (NULL == getenv("NLS_LANG"))
		putenv("NLS_LANG=.UTF8");
#endif
	memset(&oracle, 0, sizeof(oracle));

	/* connection string format: [//]host[:port][/service name] */

	if ('\0' != *host)
	{
		connect = zbx_strdcatf(connect, "//%s", host);
		if (0 != port)
			connect = zbx_strdcatf(connect, ":%d", port);
		if (NULL != dbname && '\0' != *dbname)
			connect = zbx_strdcatf(connect, "/%s", dbname);
	}
	else
		ret = ZBX_DB_FAIL;

	if (ZBX_DB_OK == ret)
	{
		/* initialize environment */
		err = OCIEnvCreate((OCIEnv **)&oracle.envhp, (ub4)OCI_DEFAULT,
				(dvoid *)0, (dvoid * (*)(dvoid *,size_t))0,
				(dvoid * (*)(dvoid *, dvoid *, size_t))0,
				(void (*)(dvoid *, dvoid *))0, (size_t)0, (dvoid **)0);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		/* allocate an error handle */
		(void)OCIHandleAlloc((dvoid *)oracle.envhp, (dvoid **)&oracle.errhp, OCI_HTYPE_ERROR,
				(size_t)0, (dvoid **)0);

		/* get the session */
		err = OCILogon2(oracle.envhp, oracle.errhp, &oracle.svchp,
				(text *)user, (ub4)(NULL != user ? strlen(user) : 0),
				(text *)password, (ub4)(NULL != password ? strlen(password) : 0),
				(text *)connect, (ub4)strlen(connect),
				OCI_DEFAULT);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_DOWN;
		}
		else
		{
			err = OCIAttrGet((void *)oracle.svchp, OCI_HTYPE_SVCCTX, (void *)&oracle.srvhp, (ub4 *)0,
					OCI_ATTR_SERVER, oracle.errhp);

			if (OCI_SUCCESS != err)
			{
				zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
				ret = ZBX_DB_DOWN;
			}
		}
	}

	zbx_free(connect);

	if (ZBX_DB_OK != ret)
		zbx_db_close();
#elif defined(HAVE_POSTGRESQL)
	if (0 != port)
		cport = zbx_dsprintf(cport, "%d", port);

	conn = PQsetdbLogin(host, cport, NULL, NULL, dbname, user, password);

	zbx_free(cport);

	/* check to see that the backend connection was successfully made */
	if (CONNECTION_OK != PQstatus(conn))
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, PQerrorMessage(conn));
		ret = ZBX_DB_DOWN;
	}
	else
	{
		result = DBselect("select oid from pg_type where typname='bytea'");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_BYTEAOID = atoi(row[0]);
		DBfree_result(result);
	}

#ifdef HAVE_FUNCTION_PQSERVERVERSION
	ZBX_PG_SVERSION = PQserverVersion(conn);
	zabbix_log(LOG_LEVEL_DEBUG, "PostgreSQL Server version: %d", ZBX_PG_SVERSION);
#endif

	if (80100 <= ZBX_PG_SVERSION)
	{
		/* disable "nonstandard use of \' in a string literal" warning */
		DBexecute("set escape_string_warning to off");

		result = DBselect("show standard_conforming_strings");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_ESCAPE_BACKSLASH = (0 == strcmp(row[0], "off"));
		DBfree_result(result);
	}

	if (90000 <= ZBX_PG_SVERSION)
	{
		/* change the output format for values of type bytea from hex (the default) to escape */
		DBexecute("set bytea_output=escape");
	}
#elif defined(HAVE_SQLITE3)
#ifdef HAVE_FUNCTION_SQLITE3_OPEN_V2
	if (SQLITE_OK != sqlite3_open_v2(dbname, &conn, SQLITE_OPEN_READWRITE, NULL))
#else
	if (SQLITE_OK != sqlite3_open(dbname, &conn))
#endif
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, sqlite3_errmsg(conn));
		sqlite3_close(conn);
		ret = ZBX_DB_DOWN;
	}
	else
	{
		char	*p, *path;

		/* do not return SQLITE_BUSY immediately, wait for N ms */
		sqlite3_busy_timeout(conn, SEC_PER_MIN * 1000);

		path = strdup(dbname);
		if (NULL != (p = strrchr(path, '/')))
			*++p = '\0';
		else
			*path = '\0';

		DBexecute("PRAGMA synchronous = 0");	/* OFF */
		DBexecute("PRAGMA temp_store = 2");	/* MEMORY */
		DBexecute("PRAGMA temp_store_directory = '%s'", path);

		zbx_free(path);
	}
#endif	/* HAVE_SQLITE3 */

	txn_init = 0;

	return ret;
}
// coverity[ +free : arg-0 ]
int putenv_wrapper(char * var)
{
    return putenv(var);
}
Esempio n. 16
0
/*
 * pg_perm_setlocale
 *
 * This is identical to the libc function setlocale(), with the addition
 * that if the operation is successful, the corresponding LC_XXX environment
 * variable is set to match.  By setting the environment variable, we ensure
 * that any subsequent use of setlocale(..., "") will preserve the settings
 * made through this routine.  Of course, LC_ALL must also be unset to fully
 * ensure that, but that has to be done elsewhere after all the individual
 * LC_XXX variables have been set correctly.  (Thank you Perl for making this
 * kluge necessary.)
 */
char *
pg_perm_setlocale(int category, const char *locale)
{
	char	   *result;
	const char *envvar;
	char	   *envbuf;

#ifndef WIN32
	result = setlocale(category, locale);
#else

	/*
	 * On Windows, setlocale(LC_MESSAGES) does not work, so just assume that
	 * the given value is good and set it in the environment variables. We
	 * must ignore attempts to set to "", which means "keep using the old
	 * environment value".
	 */
#ifdef LC_MESSAGES
	if (category == LC_MESSAGES)
	{
		result = (char *) locale;
		if (locale == NULL || locale[0] == '\0')
			return result;
	}
	else
#endif
		result = setlocale(category, locale);
#endif   /* WIN32 */

	if (result == NULL)
		return result;			/* fall out immediately on failure */

	switch (category)
	{
		case LC_COLLATE:
			envvar = "LC_COLLATE";
			envbuf = lc_collate_envbuf;
			break;
		case LC_CTYPE:
			envvar = "LC_CTYPE";
			envbuf = lc_ctype_envbuf;
			break;
#ifdef LC_MESSAGES
		case LC_MESSAGES:
			envvar = "LC_MESSAGES";
			envbuf = lc_messages_envbuf;
#ifdef WIN32
			result = IsoLocaleName(locale);
			if (result == NULL)
				result = (char *) locale;
#endif   /* WIN32 */
			break;
#endif   /* LC_MESSAGES */
		case LC_MONETARY:
			envvar = "LC_MONETARY";
			envbuf = lc_monetary_envbuf;
			break;
		case LC_NUMERIC:
			envvar = "LC_NUMERIC";
			envbuf = lc_numeric_envbuf;
			break;
		case LC_TIME:
			envvar = "LC_TIME";
			envbuf = lc_time_envbuf;
			break;
		default:
			elog(FATAL, "unrecognized LC category: %d", category);
			envvar = NULL;		/* keep compiler quiet */
			envbuf = NULL;
			return NULL;
	}

	snprintf(envbuf, LC_ENV_BUFSIZE - 1, "%s=%s", envvar, result);

	if (putenv(envbuf))
		return NULL;

	return result;
}
int main(int argc, char** argv)
{
    const char* progname = basename(strdup(argv[0]));
    if (argc <= 1)
        return usage(progname);

    // special case -- if the first arg is "--init.d", then we just build symlinks
    if (strcmp(argv[1], "--init.d") == 0)
    {
        std::list<char*> ns_args;
        for (int i = 1; i < argc; ++i)
            ns_args.push_back(argv[i]);
        int ret = create_symlinks_and_metadata(progname, ns_args);
        return ret;
    }

    // Search **backwards** from the end of the commandline for --
    //     from end to 1st -- is the environment args (env_args)
    //     up to 2nd -- is the with namespace args (ns_args)
    //     rest is the command args (exec_args)
    // This also means you need to push to **front**, not **back**.
    std::list<char*> env_args, ns_args, exec_args;
    int i = argc - 1; // start at 1 since 0 is progname
    while (i > 0 && strcmp(argv[i], "--") != 0)
        env_args.push_front(argv[i--]);
    i--; // skip --
    while (i > 0 && strcmp(argv[i], "--") != 0)
        ns_args.push_front(argv[i--]);
    if (ns_args.size() == 0) // must at least have mount name
        return usage(progname);
    i--; // skip --
    while (i > 0)
        exec_args.push_front(argv[i--]);
    exec_args.push_back(NULL); // execvp requires final argument be NULL

    // detach from our parent's namespace
    CHECK(unshare(CLONE_NEWNS) == 0, "%s: unshare failed: %m\n", progname);

    // umount the old /with (this mount is now private for us)
    // the MNT_DETACH is needed if some joker set getcwd() to /with.
    int ret = umount2(WITH_MOUNTPOINT, MNT_DETACH);
    CHECK(ret >= 0, "%s: umount2 tmpfs " WITH_MOUNTPOINT " failed: %m\n", progname);

    // after the -- is mount_name target1=src1 target2=src2 -- env
    char* mount_name = ns_args.front();
    assert(mount_name);
    ret = mount(mount_name, "/with", "tmpfs", 0, NULL);
    CHECK(ret >= 0, "%s: mount tmpfs " WITH_MOUNTPOINT " failed: %m\n", progname);

    // build out the symlinks from the namespace
    ret = create_symlinks_and_metadata(progname, ns_args);
    if (ret != 0)  // CHECKs are performed in the function
        return ret;

    // write env metadata
    FILE* fd = fopen(WITH_MOUNTPOINT "/.env", "w");
    CHECK(fd >= 0, "%s: unable to write env metadata: %m\n%s\n", progname, WITH_MOUNTPOINT "/.env");
    for (std::list<char*>::const_iterator it = env_args.begin(), end = env_args.end(); it != end; ++it)
        fprintf(fd, "%s\n", *it);
    fclose(fd);

    // drop setuid
    int uid = getuid(), gid = getgid();
    CHECK(setresuid(uid, uid, uid) >= 0 && setresgid(gid, gid, gid) >= 0,
        "%s: setresuid/setresgid failed: %m\n", progname);

    // now that we've dropped privileges, install the environment
    // that was passed on the commandline.
    clearenv();
    for (std::list<char*>::const_iterator it = env_args.begin(), end = env_args.end(); it != end; ++it)
    {
        char* env_var = *it;
        assert(env_var);
        putenv(env_var);
    }

    // we need to copy exec_args to a vector so it's laid out like an array
    std::vector<char*> exec_args_as_array(exec_args.begin(), exec_args.end());
    CHECK(execvp(exec_args_as_array[0], &exec_args_as_array[0]) != -1, "%s: cannot exec %s: %m\n", progname, exec_args_as_array[0]);
    return 1;
}
int
main(int argc, char *argv[])
{
    netsnmp_session session, *ss;
    netsnmp_pdu    *pdu, *response;
    oid             name[MAX_OID_LEN];
    size_t          name_length;
    int             arg;
    int             status;
    char           *trap = NULL;
    char           *prognam;
    int             exitval = 0;
#ifndef NETSNMP_DISABLE_SNMPV1
    char           *specific = NULL, *description = NULL, *agent = NULL;
    in_addr_t      *pdu_in_addr_t;
#endif

    prognam = strrchr(argv[0], '/');
    if (prognam)
        prognam++;
    else
        prognam = argv[0];

    putenv(strdup("POSIXLY_CORRECT=1"));

    if (strcmp(prognam, "snmpinform") == 0)
        inform = 1;
    switch (arg = snmp_parse_args(argc, argv, &session, "C:", optProc)) {
    case -2:
        exit(0);
    case -1:
        usage();
        exit(1);
    default:
        break;
    }

    SOCK_STARTUP;

    session.callback = snmp_input;
    session.callback_magic = NULL;

    if (session.version == SNMP_VERSION_3 && !inform) {
        /*
         * for traps, we use ourselves as the authoritative engine
         * which is really stupid since command line apps don't have a
         * notion of a persistent engine.  Hence, our boots and time
         * values are probably always really wacked with respect to what
         * a manager would like to see.
         * 
         * The following should be enough to:
         * 
         * 1) prevent the library from doing discovery for engineid & time.
         * 2) use our engineid instead of the remote engineid for
         * authoritative & privacy related operations.
         * 3) The remote engine must be configured with users for our engineID.
         * 
         * -- Wes 
         */

        /*
         * setup the engineID based on IP addr.  Need a different
         * algorthim here.  This will cause problems with agents on the
         * same machine sending traps. 
         */
        setup_engineID(NULL, NULL);

        /*
         * pick our own engineID 
         */
        if (session.securityEngineIDLen == 0 ||
            session.securityEngineID == NULL) {
            session.securityEngineID =
                snmpv3_generate_engineID(&session.securityEngineIDLen);
        }
        if (session.contextEngineIDLen == 0 ||
            session.contextEngineID == NULL) {
            session.contextEngineID =
                snmpv3_generate_engineID(&session.contextEngineIDLen);
        }

        /*
         * set boots and time, which will cause problems if this
         * machine ever reboots and a remote trap receiver has cached our
         * boots and time...  I'll cause a not-in-time-window report to
         * be sent back to this machine. 
         */
        if (session.engineBoots == 0)
            session.engineBoots = 1;
        if (session.engineTime == 0)    /* not really correct, */
            session.engineTime = get_uptime();  /* but it'll work. Sort of. */
    }

    ss = snmp_add(&session,
                  netsnmp_transport_open_client("snmptrap", session.peername),
                  NULL, NULL);
    if (ss == NULL) {
        /*
         * diagnose netsnmp_transport_open_client and snmp_add errors with
         * the input netsnmp_session pointer
         */
        snmp_sess_perror("snmptrap", &session);
        SOCK_CLEANUP;
        exit(1);
    }

#ifndef NETSNMP_DISABLE_SNMPV1
    if (session.version == SNMP_VERSION_1) {
        if (inform) {
            fprintf(stderr, "Cannot send INFORM as SNMPv1 PDU\n");
            exit(1);
        }
        pdu = snmp_pdu_create(SNMP_MSG_TRAP);
        pdu_in_addr_t = (in_addr_t *) pdu->agent_addr;
        if (arg == argc) {
            fprintf(stderr, "No enterprise oid\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        if (argv[arg][0] == 0) {
            pdu->enterprise = (oid *) malloc(sizeof(objid_enterprise));
            memcpy(pdu->enterprise, objid_enterprise,
                   sizeof(objid_enterprise));
            pdu->enterprise_length =
                sizeof(objid_enterprise) / sizeof(oid);
        } else {
            name_length = MAX_OID_LEN;
            if (!snmp_parse_oid(argv[arg], name, &name_length)) {
                snmp_perror(argv[arg]);
                usage();
                SOCK_CLEANUP;
                exit(1);
            }
            pdu->enterprise = (oid *) malloc(name_length * sizeof(oid));
            memcpy(pdu->enterprise, name, name_length * sizeof(oid));
            pdu->enterprise_length = name_length;
        }
        if (++arg >= argc) {
            fprintf(stderr, "Missing agent parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        agent = argv[arg];
        if (agent != NULL && strlen(agent) != 0) {
            *pdu_in_addr_t = parse_address(agent);
        } else {
            *pdu_in_addr_t = get_myaddr();
        }
        if (++arg == argc) {
            fprintf(stderr, "Missing generic-trap parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        trap = argv[arg];
        pdu->trap_type = atoi(trap);
        if (++arg == argc) {
            fprintf(stderr, "Missing specific-trap parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        specific = argv[arg];
        pdu->specific_type = atoi(specific);
        if (++arg == argc) {
            fprintf(stderr, "Missing uptime parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        description = argv[arg];
        if (description == NULL || *description == 0)
            pdu->time = get_uptime();
        else
            pdu->time = atol(description);
    } else
#endif
    {
        long            sysuptime;
        char            csysuptime[20];

        pdu = snmp_pdu_create(inform ? SNMP_MSG_INFORM : SNMP_MSG_TRAP2);
        if (arg == argc) {
            fprintf(stderr, "Missing up-time parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        trap = argv[arg];
        if (*trap == 0) {
            sysuptime = get_uptime();
            sprintf(csysuptime, "%ld", sysuptime);
            trap = csysuptime;
        }
        snmp_add_var(pdu, objid_sysuptime,
                     sizeof(objid_sysuptime) / sizeof(oid), 't', trap);
        if (++arg == argc) {
            fprintf(stderr, "Missing trap-oid parameter\n");
            usage();
            SOCK_CLEANUP;
            exit(1);
        }
        if (snmp_add_var
            (pdu, objid_snmptrap, sizeof(objid_snmptrap) / sizeof(oid),
             'o', argv[arg]) != 0) {
            snmp_perror(argv[arg]);
            SOCK_CLEANUP;
            exit(1);
        }
    }
    arg++;

    while (arg < argc) {
        arg += 3;
        if (arg > argc) {
            fprintf(stderr, "%s: Missing type/value for variable\n",
                    argv[arg - 3]);
            SOCK_CLEANUP;
            exit(1);
        }
        name_length = MAX_OID_LEN;
        if (!snmp_parse_oid(argv[arg - 3], name, &name_length)) {
            snmp_perror(argv[arg - 3]);
            SOCK_CLEANUP;
            exit(1);
        }
        if (snmp_add_var
            (pdu, name, name_length, argv[arg - 2][0],
             argv[arg - 1]) != 0) {
            snmp_perror(argv[arg - 3]);
            SOCK_CLEANUP;
            exit(1);
        }
    }

    if (inform)
        status = snmp_synch_response(ss, pdu, &response);
    else
        status = snmp_send(ss, pdu) == 0;
    if (status) {
        snmp_sess_perror(inform ? "snmpinform" : "snmptrap", ss);
        if (!inform)
            snmp_free_pdu(pdu);
        exitval = 1;
    } else if (inform)
        snmp_free_pdu(response);

    snmp_close(ss);
    snmp_shutdown("snmpapp");
    SOCK_CLEANUP;
    return exitval;
}
Esempio n. 19
0
PyObject *
visit_frontend_Launch(PyObject *self, PyObject *args)
{
    char *visitProgram = NULL, *visitProgramWithArgs = NULL,
         *LIBPATH = NULL, *VISITPLUGINDIR = NULL;
    int i, slen = 0;
    PyCFunction func = NULL;
#if defined(_WIN32)
    static char *visitProgramDefault = "visit.exe";
    static const char *moduleFile = "/visitmodule.pyd";
#else
    static char *visitProgramDefault = "visit";
    static const char *moduleFile = "/visitmodule.so";
#endif
#if defined(__APPLE__)
    int length;
    char *envcommand = NULL, *VISITHOME = NULL;
#endif

    /* Return in the unlikely event that moduleState is NULL. */
    if(moduleState == NULL)
    {
#ifdef DEBUG_PRINT
        fprintf(stderr, "moduleState is NULL!\n");
#endif
        return NULL;
    }

    if (!PyArg_ParseTuple(args, "s", &visitProgram))
    {
        visitProgram = visitProgramDefault;
        PyErr_Clear();
    }

#ifdef DEBUG_PRINT
    fprintf(stderr, "visitProgram = %s\n", visitProgram);
#endif

    /* Decorate visitProgram with any arguments we have added. */
    slen = strlen(visitProgram) + 1;
    for(i = 0; moduleState->arguments[i] != NULL; i++)
        slen += strlen(moduleState->arguments[i]) + 1 + 1;
    visitProgramWithArgs = (char *)malloc(slen);
    strcpy(visitProgramWithArgs, visitProgram);
    slen = strlen(visitProgramWithArgs);
    for(i = 0; moduleState->arguments[i] != NULL; i++)
    {
        sprintf(&visitProgramWithArgs[slen], " %s", moduleState->arguments[i]);
        slen += (strlen(moduleState->arguments[i]) + 1);
    }
#ifdef DEBUG_PRINT
    fprintf(stderr, "visitProgramWithArgs = %s\n", visitProgramWithArgs);
#endif

    /* Read the LIBPATH that would be used by the specified VisIt program
     * so we know where to look for visitmodule.so
     */
    ReadVisItEnvironment(visitProgramWithArgs, &LIBPATH, &VISITPLUGINDIR);
    free(visitProgramWithArgs);
    visitProgramWithArgs = NULL;
    if(LIBPATH == 0)
    {
#ifdef DEBUG_PRINT
        fprintf(stderr, "LIBPATH = NULL\n");
#endif
        return NULL;
    }
#ifdef DEBUG_PRINT
    else
    {
        fprintf(stderr, "LIBPATH = %s\n", LIBPATH);
    }
#endif
    if(VISITPLUGINDIR == 0)
    {
#ifdef DEBUG_PRINT
        fprintf(stderr, "VISITPLUGINDIR = NULL\n");
#endif
        return NULL;
    }
#ifdef DEBUG_PRINT
    else
    {
        fprintf(stderr, "VISITPLUGINDIR = %s\n", VISITPLUGINDIR);
    }
#endif

#if defined(__APPLE__)
    /* use LIBPATH but truncate the "/lib" */
    length=strlen(LIBPATH) - 4;
    VISITHOME=(char *)malloc(length);
    strncpy(VISITHOME, LIBPATH, length);
#ifdef DEBUG_PRINT
    fprintf(stderr, "VISITHOME = %s\n", VISITHOME);
#endif
    envcommand = (char*)malloc(
      strlen("DYLD_LIBRARY_PATH=") + strlen(VISITHOME) + strlen("/lib:") +
      strlen(VISITHOME) + strlen("/plugins/operators:") +
      strlen(VISITHOME) + strlen("/plugins/plots") + 1);
    sprintf(envcommand, 
      "DYLD_LIBRARY_PATH=%s/lib:%s/plugins/operators:%s/plugins/plots",
       VISITHOME, VISITHOME, VISITHOME);
#ifdef DEBUG_PRINT
    fprintf(stderr, "envcommand = %s\n", envcommand);
#endif
    putenv(envcommand);
    free(VISITHOME);
    free(envcommand);
#else
    /* UNIX */

    /* Set the plugin dir */
    putenv(VISITPLUGINDIR);
#endif

    /* Save off the name of the module file that we will have to load
     * in order to access functions from the VisIt module.
     */
    if(moduleState->moduleFile != NULL)
    {
        free(moduleState->moduleFile);
        moduleState->moduleFile = NULL;
    }
    moduleState->moduleFile = (char*)malloc(strlen(LIBPATH) + 
        strlen(moduleFile) + 1);
    sprintf(moduleState->moduleFile, "%s%s", LIBPATH, moduleFile);
    free(LIBPATH);
#ifdef DEBUG_PRINT
    fprintf(stderr, "moduleFile = %s\n", moduleState->moduleFile);
#endif

    if(moduleState->moduleLibrary == NULL)
    {
        void *init = NULL;
#ifdef DEBUG_PRINT
        fprintf(stderr, "Getting initvisit2 function.\n");
#endif
        /* First try to get the initvisit2 function from the module since
         * it is a little more likely to do what we want if the user
         * has issued "from visit import *".
         */
        if((init = GetDynamicFunction("initvisit2")) == NULL)
        {
#ifdef DEBUG_PRINT
            fprintf(stderr, "Getting initvisit function.\n");
#endif
            init = GetDynamicFunction("initvisit");
        }
        if(init != NULL)
        {
            /* Initialize the VisIt module. This will overwrite this
             * VisIt module's functions with functions from the new
             * VisIt module, allowing us to pick up its interface.
             */
#ifdef DEBUG_PRINT
            fprintf(stderr, "Calling initvisit function.\n");
#endif      
            ((void(*)(void))init)();
        }
#ifdef DEBUG_PRINT
        else
        {
            fprintf(stderr, "Could not get initvisit function.\n");
        }
#endif      

        /* Call the SetDebugLevel function in the loaded library. */
        if(moduleState->moduleDebugLevel > 0)
        {
            func = (PyCFunction)GetDynamicFunction("visit_SetDebugLevel");
            if(func != NULL)
            {
                PyObject *obj = NULL, *debugLevel = NULL, *tuple = NULL;
                /* Create an argument tuple. */
                tuple = PyTuple_New(1);
                debugLevel = PyInt_FromLong(moduleState->moduleDebugLevel);
                PyTuple_SET_ITEM(tuple, 0, debugLevel);
#ifdef DEBUG_PRINT
                fprintf(stderr, "Calling SetDebugLevel function.\n");
#endif 
                obj = (func)(self, tuple);
                Py_DECREF(tuple);
                if(obj != NULL)
                {
                    Py_DECREF(obj);
                }
#ifdef DEBUG_PRINT
                else
                {
                    fprintf(stderr, "SetDebugLevel function returned NULL.\n");
                }
#endif 
            }
        }

        /* Call functions to set the arguments that the user provided. */
        if(moduleState->arguments[0] != NULL)
        {
            func = (PyCFunction)GetDynamicFunction("visit_AddArgument");
            if(func != NULL)
            {
                int i = 0;
                while(moduleState->arguments[i] != NULL)
                {
                    PyObject *obj = NULL, *a = NULL, *tuple = NULL;
                    tuple = PyTuple_New(1);
                    a = PyString_FromString(moduleState->arguments[i]);
                    PyTuple_SET_ITEM(tuple, 0, a);
#ifdef DEBUG_PRINT
                    fprintf(stderr, "Calling AddArgument function.\n");
#endif 
                    obj = (func)(self, tuple);
                    Py_DECREF(tuple);
                    if(obj != NULL)
                    {
                        Py_DECREF(obj);
                    }
#ifdef DEBUG_PRINT
                    else
                    {
                        fprintf(stderr, "AddArgument function returned NULL.\n");
                    }
#endif 
                    ++i;
                }
            }
        }
    }

    /* Call the launch function in the loaded library. */
    func = (PyCFunction)GetDynamicFunction("visit_Launch");
    if(func != NULL)
    {
#ifdef DEBUG_PRINT
        fprintf(stderr, "Calling Launch function.\n");
#endif
        /* Since we've been able to call the initvisit function in
         * the dynamically loaded module if we've made it here, we won't
         * be in this module any more since its methods will be replaced
         * by those from the new VisIt module. Therefore, we should be
         * able to free memory that we've allocated.
         */
        cleanupvisit();

        /* Call the new VisIt module's Launch method. */
        return (func)(self, args);
    }

#ifdef DEBUG_PRINT
    fprintf(stderr, "Could not call Launch function.\n");
#endif 

    return PyInt_FromLong(0);
}
Esempio n. 20
0
void
threadmain(int argc, char **argv)
{
	int p[2], fd[3], pid[2];
	char *a[4], *devdraw;
	
	ARGBEGIN{}ARGEND

	if(argc != 1)
		usage();
		
	// Make sure we don't kill our parent whilst killing
	// our children.
	setsid();

	if(pipe(p) < 0)
		sysfatal("pipe: %r");
	
	fd[0] = dup(p[0], -1);
	fd[1] = dup(p[0], -1);
	fd[2] = dup(2, -1);
	
	a[0] = "rc";
	a[1] = "-c";
	a[2] = argv[0];
	a[3] = nil;

	if((pid[0] = threadspawn(fd, a[0], a)) < 0)
		sysfatal("threadspawn: %r");

	fd[0] = dup(p[1], -1);
	fd[1] = dup(p[1], -1);
	fd[2] = dup(2, -1);

	putenv("NOLIBTHREADDAEMONIZE", "1");
	devdraw = getenv("DEVDRAW");
	if(devdraw == nil)
		devdraw = "devdraw";
	if((pid[1] = threadspawnl(fd, devdraw, devdraw, "(devdraw)", nil)) < 0)
		sysfatal("threadspawnl: %r");

	close(p[0]);
	close(p[1]);

	recvp(threadwaitchan());

	postnote(PNGROUP, pid[0], "hangup");
	postnote(PNGROUP, pid[1], "hangup");
	//recvp(threadwaitchan());

	threadexitsall("");

/*
	if ((pid = fork()) < 0)
		sysfatal("fork: %r");

	switch(pid){
	case 0:
		close(p[0]);
		dup(p[1], 0);
		dup(p[1], 1);

		a[0] = "rc";
		a[1] = "-c";
		a[2] = argv[0];
		a[3] = nil;

		if(exec("rc", a) < 0)
			sysfatal("execl: %r");

	default:
		close(p[1]);
		dup(p[0], 0);
		dup(p[0], 1);

		putenv("NOLIBTHREADDAEMONIZE", "1");
		devdraw = getenv("DEVDRAW");
		if(devdraw == nil)
			devdraw = "devdraw";

		if(execl(devdraw, devdraw, "(devdraw)", nil) < 0)
			sysfatal("execl: %r");
	}

	exits(0);
*/
}
Esempio n. 21
0
int
main (int argc, char *argv[])
{
    int result = 0;
    int ret;
    char *err_msg = NULL;
    sqlite3 *db_handle;
    void *cache = spatialite_alloc_connection ();
    void *priv_data = rl2_alloc_private ();
    char *old_SPATIALITE_SECURITY_ENV = NULL;

    if (argc > 1 || argv[0] == NULL)
	argc = 1;		/* silencing stupid compiler warnings */

    old_SPATIALITE_SECURITY_ENV = getenv ("SPATIALITE_SECURITY");
#ifdef _WIN32
    putenv ("SPATIALITE_SECURITY=relaxed");
#else /* not WIN32 */
    setenv ("SPATIALITE_SECURITY", "relaxed", 1);
#endif

/* opening and initializing the "memory" test DB */
    ret = sqlite3_open_v2 (":memory:", &db_handle,
			   SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "sqlite3_open_v2() error: %s\n",
		   sqlite3_errmsg (db_handle));
	  return -1;
      }
    spatialite_init_ex (db_handle, cache, 0);
    rl2_init (db_handle, priv_data, 0);
    ret =
	sqlite3_exec (db_handle, "SELECT InitSpatialMetadata(1)", NULL, NULL,
		      &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -2;
      }
    ret =
	sqlite3_exec (db_handle, "SELECT CreateRasterCoveragesTable()", NULL,
		      NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "CreateRasterCoveragesTable() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -3;
      }

/* SRTM NILE-DOUBLE (GRID) tests */
    ret = -100;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT8, TILE_256, &ret))
	return ret;
    ret = -120;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT8, TILE_1024, &ret))
	return ret;
    ret = -140;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT8, TILE_256, &ret))
	return ret;
    ret = -160;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT8, TILE_1024, &ret))
	return ret;
    ret = -180;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT16, TILE_256, &ret))
	return ret;
    ret = -200;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT16, TILE_1024, &ret))
	return ret;
    ret = -220;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT16, TILE_256, &ret))
	return ret;
    ret = -240;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT16, TILE_1024, &ret))
	return ret;
    ret = -260;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT32, TILE_256, &ret))
	return ret;
    ret = -280;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT32, TILE_1024, &ret))
	return ret;
    ret = -300;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT32, TILE_256, &ret))
	return ret;
    ret = -320;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT32, TILE_1024, &ret))
	return ret;
    ret = -340;
    if (!test_coverage (db_handle, RL2_SAMPLE_FLOAT, TILE_256, &ret))
	return ret;
    ret = -360;
    if (!test_coverage (db_handle, RL2_SAMPLE_FLOAT, TILE_1024, &ret))
	return ret;
    ret = -380;
    if (!test_coverage (db_handle, RL2_SAMPLE_DOUBLE, TILE_256, &ret))
	return ret;
    ret = -400;
    if (!test_coverage (db_handle, RL2_SAMPLE_DOUBLE, TILE_1024, &ret))
	return ret;

/* closing the DB */
    sqlite3_close (db_handle);
    spatialite_cleanup_ex (cache);
    rl2_cleanup_private (priv_data);
    spatialite_shutdown ();
    if (old_SPATIALITE_SECURITY_ENV)
      {
#ifdef _WIN32
	  char *env = sqlite3_mprintf ("SPATIALITE_SECURITY=%s",
				       old_SPATIALITE_SECURITY_ENV);
	  putenv (env);
	  sqlite3_free (env);
#else /* not WIN32 */
	  setenv ("SPATIALITE_SECURITY", old_SPATIALITE_SECURITY_ENV, 1);
#endif
      }
    else
      {
#ifdef _WIN32
	  putenv ("SPATIALITE_SECURITY=");
#else /* not WIN32 */
	  unsetenv ("SPATIALITE_SECURITY");
#endif
      }
    return result;
}
Esempio n. 22
0
static void process_exec(PROCESS_REC *rec, const char *cmd)
{
	const char *shell_args[4] = { "/bin/sh", "-c", NULL, NULL };
        char **args;
	int in[2], out[2];
        int n;

	if (pipe(in) == -1)
                return;
	if (pipe(out) == -1)
		return;

	shell_args[2] = cmd;
	rec->pid = fork();
	if (rec->pid == -1) {
                /* error */
		close(in[0]); close(in[1]);
                close(out[0]); close(out[1]);
		return;
	}

	if (rec->pid != 0) {
		/* parent process */
                GIOChannel *outio = g_io_channel_unix_new(in[1]);

		rec->in = g_io_channel_unix_new(out[0]);
		rec->out = net_sendbuffer_create(outio, 0);

                close(out[1]);
		close(in[0]);
		pidwait_add(rec->pid);
                return;
	}

	/* child process, try to clean up everything */
	setsid();
	setuid(getuid());
	setgid(getgid());
	signal(SIGINT, SIG_IGN);
	signal(SIGQUIT, SIG_DFL);

	putenv("TERM=tty");

	/* set stdin, stdout and stderr */
        dup2(in[0], STDIN_FILENO);
        dup2(out[1], STDOUT_FILENO);
	dup2(out[1], STDERR_FILENO);

        /* don't let child see our files */
	for (n = 3; n < 256; n++)
                close(n);

	if (rec->shell) {
		execvp(shell_args[0], (char **) shell_args);

		fprintf(stderr, "Exec: /bin/sh: %s\n", g_strerror(errno));
	} else {
		args = g_strsplit(cmd, " ", -1);
                execvp(args[0], args);

		fprintf(stderr, "Exec: %s: %s\n", args[0], g_strerror(errno));
	}

	_exit(-1);
}
Esempio n. 23
0
int main (int argc, char *argv[])
{
    int i;
    int result;                 /* CA result */
    OutputT format = plain;     /* User specified format */
    RequestT request = get;     /* User specified request type */
    int isArray = 0;            /* Flag for array operation */
    int enumAsString = 0;       /* Force ENUM values to be strings */

    int count = 1;
    int opt;                    /* getopt() current option */
    chtype dbrType = DBR_STRING;
    char *pend;
    EpicsStr *sbuf;
    double *dbuf;
    char *cbuf = 0;
    char *ebuf = 0;
    void *pbuf;
    int len = 0;
    int waitStatus;
    struct dbr_gr_enum bufGrEnum;

    int nPvs;                   /* Number of PVs */
    pv* pvs;                /* Array of PV structures */

    LINE_BUFFER(stdout);        /* Configure stdout buffering */
    putenv("POSIXLY_CORRECT="); /* Behave correct on GNU getopt systems */

    while ((opt = getopt(argc, argv, ":cnlhatsS#:w:p:F:")) != -1) {
        switch (opt) {
        case 'h':               /* Print usage */
            usage();
            return 0;
        case 'n':               /* Force interpret ENUM as index number */
            enumAsNr = 1;
            enumAsString = 0;
            break;
        case 's':               /* Force interpret ENUM as menu string */
            enumAsString = 1;
            enumAsNr = 0;
            break;
        case 'S':               /* Treat char array as (long) string */
            charArrAsStr = 1;
            isArray = 0;
            break;
        case 't':               /* Select terse output format */
            format = terse;
            break;
        case 'l':               /* Select long output format */
            format = all;
            break;
        case 'a':               /* Select array mode */
            isArray = 1;
            charArrAsStr = 0;
            break;
        case 'c':               /* Select put_callback mode */
            request = callback;
            break;
        case 'w':               /* Set CA timeout value */
            if(epicsScanDouble(optarg, &caTimeout) != 1)
            {
                fprintf(stderr, "'%s' is not a valid timeout value "
                        "- ignored. ('caput -h' for help.)\n", optarg);
                caTimeout = DEFAULT_TIMEOUT;
            }
            break;
        case '#':               /* Array count */
            if (sscanf(optarg,"%d", &count) != 1)
            {
                fprintf(stderr, "'%s' is not a valid array element count "
                        "- ignored. ('caput -h' for help.)\n", optarg);
                count = 0;
            }
            break;
        case 'p':               /* CA priority */
            if (sscanf(optarg,"%u", &caPriority) != 1)
            {
                fprintf(stderr, "'%s' is not a valid CA priority "
                        "- ignored. ('caget -h' for help.)\n", optarg);
                caPriority = DEFAULT_CA_PRIORITY;
            }
            if (caPriority > CA_PRIORITY_MAX) caPriority = CA_PRIORITY_MAX;
            break;
        case 'F':               /* Store this for output and tool_lib formatting */
            fieldSeparator = (char) *optarg;
            break;
        case '?':
            fprintf(stderr,
                    "Unrecognized option: '-%c'. ('caput -h' for help.)\n",
                    optopt);
            return 1;
        case ':':
            fprintf(stderr,
                    "Option '-%c' requires an argument. ('caput -h' for help.)\n",
                    optopt);
            return 1;
        default :
            usage();
            return 1;
        }
    }

    nPvs = argc - optind;       /* Remaining arg list are PV names and values */

    if (nPvs < 1) {
        fprintf(stderr, "No pv name specified. ('caput -h' for help.)\n");
        return 1;
    }
    if (nPvs == 1) {
        fprintf(stderr, "No value specified. ('caput -h' for help.)\n");
        return 1;
    }

    nPvs = 1;                   /* One PV - the rest is value(s) */

    epId = epicsEventCreate(epicsEventEmpty);  /* Create empty EPICS event (semaphore) */

                                /* Start up Channel Access */

    result = ca_context_create(ca_enable_preemptive_callback);
    if (result != ECA_NORMAL) {
        fprintf(stderr, "CA error %s occurred while trying "
                "to start channel access.\n", ca_message(result));
        return 1;
    }
                                /* Allocate PV structure array */

    pvs = calloc (nPvs, sizeof(pv));
    if (!pvs) {
        fprintf(stderr, "Memory allocation for channel structure failed.\n");
        return 1;
    }
                                /* Connect channels */

    pvs[0].name = argv[optind] ;   /* Copy PV name from command line */

    result = connect_pvs(pvs, nPvs); /* If the connection fails, we're done */
    if (result) {
        ca_context_destroy();
        return result;
    }

                                /* Get values from command line */
    optind++;

    if (isArray) {
        optind++;               /* In case of array skip first value (nr
                                 * of elements) - actual number of values is used */
        count = argc - optind;

    } else {                    /* Concatenate the remaining line to one string
                                 * (sucks but is compatible to the former version) */
        for (i = optind; i < argc; i++) {
            len += strlen(argv[i]);
            len++;
        }
        cbuf = calloc(len, sizeof(char));
        if (!cbuf) {
            fprintf(stderr, "Memory allocation failed.\n");
            return 1;
        }
        strcpy(cbuf, argv[optind]);

        if (argc > optind+1) {
            for (i = optind + 1; i < argc; i++) {
                strcat(cbuf, " ");
                strcat(cbuf, argv[i]); 
            }
        }

        if ((argc - optind) >= 1)
            count = 1;
        argv[optind] = cbuf;
    }

    sbuf = calloc (count, sizeof(EpicsStr));
    dbuf = calloc (count, sizeof(double));
    if(!sbuf || !dbuf) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

                                /*  ENUM? Special treatment */

    if (ca_field_type(pvs[0].chid) == DBR_ENUM) {

                                /* Get the ENUM strings */

        result = ca_array_get (DBR_GR_ENUM, 1, pvs[0].chid, &bufGrEnum);
        result = ca_pend_io(caTimeout);
        if (result == ECA_TIMEOUT) {
            fprintf(stderr, "Read operation timed out: ENUM data was not read.\n");
            return 1;
        }

        if (enumAsNr) {         /* Interpret values as numbers */

            for (i = 0; i < count; ++i) {
                dbuf[i] = epicsStrtod(*(argv+optind+i), &pend);
                if (*(argv+optind+i) == pend) { /* Conversion didn't work */
                    fprintf(stderr, "Enum index value '%s' is not a number.\n",
                            *(argv+optind+i));
                    return 1;
                }
                if (dbuf[i] >= bufGrEnum.no_str) {
                    fprintf(stderr, "Warning: enum index value '%s' may be too large.\n",
                            *(argv+optind+i));
                }
            }
            dbrType = DBR_DOUBLE;

        } else {                /* Interpret values as strings */

            for (i = 0; i < count; ++i) {
                epicsStrnRawFromEscaped(sbuf[i], sizeof(EpicsStr), *(argv+optind+i), sizeof(EpicsStr));
                *( sbuf[i]+sizeof(EpicsStr)-1 ) = '\0';
                dbrType = DBR_STRING;

                                /* Compare to ENUM strings */
                for (len = 0; len < bufGrEnum.no_str; len++)
                    if (!strcmp(sbuf[i], bufGrEnum.strs[len]))
                        break;

                if (len >= bufGrEnum.no_str) {
                                         /* Not a string? Try as number */
                    dbuf[i] = epicsStrtod(sbuf[i], &pend);
                    if (sbuf[i] == pend || enumAsString) {
                        fprintf(stderr, "Enum string value '%s' invalid.\n", sbuf[i]);
                        return 1;
                    }
                    if (dbuf[i] >= bufGrEnum.no_str) {
                        fprintf(stderr, "Warning: enum index value '%s' may be too large.\n", sbuf[i]);
                    }
                    dbrType = DBR_DOUBLE;
                }
            }
        }

    } else {                    /* Not an ENUM */

        if (charArrAsStr) {
            dbrType = DBR_CHAR;
            ebuf = calloc(len, sizeof(char));
            if(!ebuf) {
                fprintf(stderr, "Memory allocation failed\n");
                return 1;
            }
            count = epicsStrnRawFromEscaped(ebuf, len, cbuf, len-1) + 1;
        } else {
            for (i = 0; i < count; ++i) {
                epicsStrnRawFromEscaped(sbuf[i], sizeof(EpicsStr), *(argv+optind+i), sizeof(EpicsStr));
                *( sbuf[i]+sizeof(EpicsStr)-1 ) = '\0';
            }
            dbrType = DBR_STRING;
        }
    }

                                /* Read and print old data */
    if (format != terse) {
        printf("Old : ");
        result = caget(pvs, nPvs, format, 0, 0);
    }

                                /* Write new data */
    if (dbrType == DBR_STRING) pbuf = sbuf;
    else if (dbrType == DBR_CHAR) pbuf = ebuf;
    else pbuf = dbuf;

    if (request == callback) {
        /* Use callback version of put */
        pvs[0].status = ECA_NORMAL;   /* All ok at the moment */
        result = ca_array_put_callback (
            dbrType, count, pvs[0].chid, pbuf, put_event_handler, (void *) pvs);
    } else {
        /* Use standard put with defined timeout */
        result = ca_array_put (dbrType, count, pvs[0].chid, pbuf);
    }
    result = ca_pend_io(caTimeout);
    if (result == ECA_TIMEOUT) {
        fprintf(stderr, "Write operation timed out: Data was not written.\n");
        return 1;
    }
    if (request == callback) {   /* Also wait for callbacks */
        waitStatus = epicsEventWaitWithTimeout( epId, caTimeout );
        if (waitStatus)
            fprintf(stderr, "Write callback operation timed out\n");

        /* retrieve status from callback */
        result = pvs[0].status;
    }

    if (result != ECA_NORMAL) {
        fprintf(stderr, "Error occured writing data.\n");
        return 1;
    }

                                /* Read and print new data */
    if (format != terse)
        printf("New : ");

    result = caget(pvs, nPvs, format, 0, 0);

                                /* Shut down Channel Access */
    ca_context_destroy();

    return result;
}
Esempio n. 24
0
int main(int ac, char *av[])
{
  int i, ret, verbose = 0, output_thumbs = 0;

  // don't use fixed size buffers in real apps!
  char outfn[1024], thumbfn[1024];

  LibRaw RawProcessor;
  RawProcessor.imgdata.params.custom_camera_strings = customCameras;
  if (ac < 2)
  {
    printf("simple_dcraw - LibRaw %s sample. Emulates dcraw [-D] [-T] [-v] [-e] [-E]\n"
           " %d cameras supported\n"
           "Usage: %s [-D] [-T] [-v] [-e] raw-files....\n"
           "\t-4 - 16-bit mode\n"
           "\t-L - list supported cameras and exit\n"
           "\t-v - verbose output\n"
           "\t-T - output TIFF files instead of .pgm/ppm\n"
           "\t-e - extract thumbnails (same as dcraw -e in separate run)\n",
           LibRaw::version(), LibRaw::cameraCount(), av[0]);
    return 0;
  }

  putenv((char *)"TZ=UTC"); // dcraw compatibility, affects TIFF datestamp field

#define P1 RawProcessor.imgdata.idata
#define S RawProcessor.imgdata.sizes
#define C RawProcessor.imgdata.color
#define T RawProcessor.imgdata.thumbnail
#define P2 RawProcessor.imgdata.other
#define OUT RawProcessor.imgdata.params

  for (i = 1; i < ac; i++)
  {
    if (av[i][0] == '-')
    {
      if (av[i][1] == 'T' && av[i][2] == 0)
        OUT.output_tiff = 1;
      if (av[i][1] == 'v' && av[i][2] == 0)
        verbose++;
      if (av[i][1] == 'e' && av[i][2] == 0)
        output_thumbs++;
      if (av[i][1] == '4' && av[i][2] == 0)
        OUT.output_bps = 16;
      if (av[i][1] == 'C' && av[i][2] == 0)
        RawProcessor.set_progress_handler(my_progress_callback, NULL);
      if (av[i][1] == 'L' && av[i][2] == 0)
      {
        const char **clist = LibRaw::cameraList();
        const char **cc = clist;
        while (*cc)
        {
          printf("%s\n", *cc);
          cc++;
        }

        exit(0);
      }
      continue;
    }

    if (verbose)
      printf("Processing file %s\n", av[i]);

    if ((ret = RawProcessor.open_file(av[i])) != LIBRAW_SUCCESS)
    {
      fprintf(stderr, "Cannot open_file %s: %s\n", av[i], libraw_strerror(ret));
      continue; // no recycle b/c open file will recycle itself
    }

    if (!output_thumbs) // No unpack for thumb extraction
      if ((ret = RawProcessor.unpack()) != LIBRAW_SUCCESS)
      {
        fprintf(stderr, "Cannot unpack %s: %s\n", av[i], libraw_strerror(ret));
        continue;
      }

    // thumbnail unpacking and output in the middle of main
    // image processing - for test purposes!
    if (output_thumbs)
    {
      if ((ret = RawProcessor.unpack_thumb()) != LIBRAW_SUCCESS)
      {
        fprintf(stderr, "Cannot unpack_thumb %s: %s\n", av[i], libraw_strerror(ret));
        if (LIBRAW_FATAL_ERROR(ret))
          continue; // skip to next file
      }
      else
      {
        snprintf(thumbfn, sizeof(thumbfn), "%s.%s", av[i],
                 T.tformat == LIBRAW_THUMBNAIL_JPEG ? "thumb.jpg" : "thumb.ppm");

        if (verbose)
          printf("Writing thumbnail file %s\n", thumbfn);
        if (LIBRAW_SUCCESS != (ret = RawProcessor.dcraw_thumb_writer(thumbfn)))
        {
          fprintf(stderr, "Cannot write %s: %s\n", thumbfn, libraw_strerror(ret));
          if (LIBRAW_FATAL_ERROR(ret))
            continue;
        }
      }
      continue;
    }

    ret = RawProcessor.dcraw_process();

    if (LIBRAW_SUCCESS != ret)
    {
      fprintf(stderr, "Cannot do postpocessing on %s: %s\n", av[i], libraw_strerror(ret));
      if (LIBRAW_FATAL_ERROR(ret))
        continue;
    }
    snprintf(outfn, sizeof(outfn), "%s.%s", av[i], OUT.output_tiff ? "tiff" : (P1.colors > 1 ? "ppm" : "pgm"));

    if (verbose)
      printf("Writing file %s\n", outfn);

    if (LIBRAW_SUCCESS != (ret = RawProcessor.dcraw_ppm_tiff_writer(outfn)))
      fprintf(stderr, "Cannot write %s: %s\n", outfn, libraw_strerror(ret));

    RawProcessor.recycle(); // just for show this call
  }
  return 0;
}
Esempio n. 25
0
OWPL_RESULT
owplInit
(
	const int asyncCallbackMode,
	short udpPort,
	short tcpPort,
	short tlsPort,
	const char* szBindToAddr,
	const int bUserSequentialPorts
)
{
	int return_code;
	short useUdp = (udpPort == -1 ? 0 : 1);
	short useTcp = (tcpPort == -1 ? 0 : 1);
	short useTls = (tlsPort == -1 ? 0 : 1);
	const char* ptime;

	return_code = owplAdapterInitialize();
	if (return_code != 0)
	{
		owplLogError("owplAdapterInitialize failed");
		return OWPL_RESULT_FAILURE;
	}
	return_code = owplAdapterNortelInitialize("nortel");
	if (return_code != 0)
	{
		owplLogError("owplAdapterNortelInitialize failed");
		return OWPL_RESULT_FAILURE;
	}

	phcb = (phCallbacks_t * ) malloc(sizeof(phCallbacks_t));
	memset(phcb, 0, sizeof(phCallbacks_t));

	phcfg.asyncmode = asyncCallbackMode;

	return_code = owplInitOwsl(useUdp, useTcp, useTls);
	if (return_code != 0)
	{
		owplLogError("owplInitOwsl failed");
		return OWPL_RESULT_FAILURE;
	}

	osip_trace_initialize_func(OSIP_INFO3, owplOsipLogFunction);

	return_code = eXosip_init(0, 0, udpPort, tcpPort, tlsPort);
	if (return_code != 0)
	{
		owplLogError("eXosip_init failed");
		return OWPL_RESULT_FAILURE;
	}

	{

		const char version[] = stringize(VOXOXVERSION);//VOXOX - CJC - 2009.06.27 
		// VOXOX CHANGE by ASV 06-27-2009: modified the code to be compatible with GCC
		char ua[50] = "VoxOx "; // We need to define he size to make sure strcat has enough space to copy version in ua
		strcat(ua, version);//VOXOX - CJC - 2009.06.27 
		// VOXOX CHANGE by ASV - end
		eXosip_set_user_agent(ua);
	}

	ph_avcodec_init();
	ph_calls_init();

#ifdef FORCE_VAD
/* HACK for test */
#ifdef EMBED
	phcfg.vad = VAD_VALID_MASK | (500 & VAD_THRESHOLD_MASK);
#else
	phcfg.vad = VAD_VALID_MASK | (1000 & VAD_THRESHOLD_MASK);
#endif
#endif

#ifdef FORCE_CNG
  /* HACK for test */
  phcfg.cng = 1;
#endif

	ph_media_init(phcfg.plugin_path);

	ph_vlines_init();

	ph_payloads_init();

	if (!phcfg.audio_dev || phcfg.audio_dev[0] == '\0')
	{
		// Set default audio device if no one has been set before
		owplAudioSetConfigString(0);
	}
#if 0	
	ptime = getenv("EXOSIP_FORCE_PTIME");
	if (!ptime || !*ptime)
	{
		putenv("EXOSIP_FORCE_PTIME=20");
	}
#endif	
	/* register callbacks? */
	eXosip_set_mode(EVENT_MODE);

	if (!phcfg.asyncmode)
	{
		phWaitTimeout = 1;
	}
	else 
	{
		phWaitTimeout = 500;
	}

	if (phcfg.asyncmode)
	{
		osip_thread_create(20000, ph_api_thread, 0);
	}

	pthread_mutex_init(&ph_media_stop_mutex, NULL);

	phIsInitialized = 1;

	owplLogDebug("owplInit finished");

	return OWPL_RESULT_SUCCESS;
}
Esempio n. 26
0
static void
test_inserts(int level)
{
    static bool first = TRUE;

    int ch;
    int limit;
    int row = 1;
    int col;
    int row2, col2;
    int length;
    wchar_t buffer[BUFSIZ];
    WINDOW *look = 0;
    WINDOW *work = 0;
    WINDOW *show = 0;
    int margin = (2 * MY_TABSIZE) - 1;
    Options option = ((m_opt ? oMove : oDefault)
		      | ((w_opt || (level > 0)) ? oWindow : oDefault));

    if (first) {
	static char cmd[80];
	setlocale(LC_ALL, "");

	putenv(strcpy(cmd, "TABSIZE=8"));

	initscr();
	(void) cbreak();	/* take input chars one at a time, no wait for \n */
	(void) noecho();	/* don't echo input */
	keypad(stdscr, TRUE);
    }

    limit = LINES - 5;
    if (level > 0) {
	look = newwin(limit, COLS - (2 * (level - 1)), 0, level - 1);
	work = newwin(limit - 2, COLS - (2 * level), 1, level);
	show = newwin(4, COLS, limit + 1, 0);
	box(look, 0, 0);
	wnoutrefresh(look);
	limit -= 2;
    } else {
	work = stdscr;
	show = derwin(stdscr, 4, COLS, limit + 1, 0);
    }
    keypad(work, TRUE);

    for (col = margin + 1; col < COLS; col += MY_TABSIZE)
	MvWVLine(work, row, col, '.', limit - 2);

    MvWVLine(work, row, margin, ACS_VLINE, limit - 2);
    MvWVLine(work, row, margin + 1, ACS_VLINE, limit - 2);
    limit /= 2;

    MvWAddStr(work, 1, 2, "String");
    MvWAddStr(work, limit + 1, 2, "Chars");
    wnoutrefresh(work);

    buffer[length = 0] = '\0';
    legend(show, level, option, buffer, length);
    wnoutrefresh(show);

    doupdate();

    /*
     * Show the characters inserted in color, to distinguish from those that
     * are shifted.
     */
    if (has_colors()) {
	start_color();
	init_pair(1, COLOR_WHITE, COLOR_BLUE);
	wbkgdset(work, COLOR_PAIR(1) | ' ');
    }

    while ((ch = read_linedata(work)) != ERR && !isQUIT(ch)) {
	wmove(work, row, margin + 1);
	switch (ch) {
	case key_RECUR:
	    test_inserts(level + 1);

	    touchwin(look);
	    touchwin(work);
	    touchwin(show);

	    wnoutrefresh(look);
	    wnoutrefresh(work);
	    wnoutrefresh(show);

	    doupdate();
	    break;
	case key_NEWLINE:
	    if (row < limit) {
		++row;
		/* put the whole string in, all at once */
		col2 = margin + 1;
		switch (option) {
		case oDefault:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    if (move(row, col2) != ERR) {
				InsNStr(buffer + col, LEN(col));
			    }
			}
		    } else {
			if (move(row, col2) != ERR) {
			    InsStr(buffer);
			}
		    }
		    break;
		case oMove:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    MvInsNStr(row, col2, buffer + col, LEN(col));
			}
		    } else {
			MvInsStr(row, col2, buffer);
		    }
		    break;
		case oWindow:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    if (wmove(work, row, col2) != ERR) {
				WInsNStr(work, buffer + col, LEN(col));
			    }
			}
		    } else {
			if (wmove(work, row, col2) != ERR) {
			    WInsStr(work, buffer);
			}
		    }
		    break;
		case oMoveWindow:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    MvWInsNStr(work, row, col2, buffer + col, LEN(col));
			}
		    } else {
			MvWInsStr(work, row, col2, buffer);
		    }
		    break;
		}

		/* do the corresponding single-character insertion */
		row2 = limit + row;
		for (col = 0; col < length; ++col) {
		    col2 = ColOf(buffer, col, margin);
		    switch (option) {
		    case oDefault:
			if (move(row2, col2) != ERR) {
			    InsCh((chtype) buffer[col]);
			}
			break;
		    case oMove:
			MvInsCh(row2, col2, (chtype) buffer[col]);
			break;
		    case oWindow:
			if (wmove(work, row2, col2) != ERR) {
			    WInsCh(work, (chtype) buffer[col]);
			}
			break;
		    case oMoveWindow:
			MvWInsCh(work, row2, col2, (chtype) buffer[col]);
			break;
		    }
		}
	    } else {
		beep();
	    }
	    break;
	default:
	    buffer[length++] = ch;
	    buffer[length] = '\0';

	    /* put the string in, one character at a time */
	    col = ColOf(buffer, length - 1, margin);
	    switch (option) {
	    case oDefault:
		if (move(row, col) != ERR) {
		    InsStr(buffer + length - 1);
		}
		break;
	    case oMove:
		MvInsStr(row, col, buffer + length - 1);
		break;
	    case oWindow:
		if (wmove(work, row, col) != ERR) {
		    WInsStr(work, buffer + length - 1);
		}
		break;
	    case oMoveWindow:
		MvWInsStr(work, row, col, buffer + length - 1);
		break;
	    }

	    /* do the corresponding single-character insertion */
	    switch (option) {
	    case oDefault:
		if (move(limit + row, col) != ERR) {
		    InsCh((chtype) ch);
		}
		break;
	    case oMove:
		MvInsCh(limit + row, col, (chtype) ch);
		break;
	    case oWindow:
		if (wmove(work, limit + row, col) != ERR) {
		    WInsCh(work, (chtype) ch);
		}
		break;
	    case oMoveWindow:
		MvWInsCh(work, limit + row, col, (chtype) ch);
		break;
	    }

	    wnoutrefresh(work);

	    legend(show, level, option, buffer, length);
	    wnoutrefresh(show);

	    doupdate();
	    break;
	}
    }
    if (level > 0) {
	delwin(show);
	delwin(work);
	delwin(look);
    }
}
Esempio n. 27
0
void nostdinc() {
	putenv("INCLUDE=");		// Windows
	putenv("INCLUDE");		// POSIX
	//assert(!getenv("INCLUDE"));
	add_to_argv("-X");
}
Esempio n. 28
0
/**
 * Reads and parses the file request lines received from the client. 
 * @param req: location where this method writes the requested 
 *             filename or directory.
 * @param buff: buffer where the HTTP request is stored.
 * @param response: instance of Struct HTTP_Response which this method will
 *				    populate based on the HTTP request in buff.
 */
void ExtractFileRequest(char *req, char *buff, HTTP_Response *response ) {

	int lastPos = (int)(strchr(buff, '\n') - buff) - 1; //Newline is \r\n
	                                                      
	/* We should now have the ending position to get the following line:
	 * "GET / HTTP/1.0"
	 * So split it based on space delimeter to get URL path 
	 * and HTTP version.
	 */

	//printf("entire buffer: %s\nLast pos: %d\n", buff, lastPos);
	//printf("End of first line position: %d\n", lastPos);

	char *tempBuff = malloc(strlen(buff));
	strcpy(tempBuff, buff);

	char *split, *savePtr;
	int i = 0;
	int total = 0;
	while (total < lastPos)
	{
		if (total == 0)
		{
			split = strtok_r(tempBuff, " ", &savePtr);
		}
		else
		{
			split = strtok_r(NULL, " ", &savePtr);
		}
		int size = strlen(split);
		
		switch(i)
		{
			case 0: //Method (GET, POST, HEAD...)
				response->HTTP_Type = malloc(size + 1);
				strcpy(response -> HTTP_Type, split);
				break;
			case 1: //File content path
				strcpy(req, split);
				break;
			case 2: //HTTP Protocol (ex HTTP/1.1)
				
				/* There is no space after the version number, 
				 * only a newline character. So split again. */
				split = strtok(split, "\r\n");
				size = strlen(split);
				response->versionNum = malloc(size + 1);
				strcpy(response -> versionNum, split);
				break;
		}
		total += size + 1; //+1 to account for space
		i++;	
		printf("Split string: %s, size: %d\n", split, size); 
	}
	// Find the Accept: ... line in the get response
	strcpy(tempBuff, buff);

	split = strstr(tempBuff, "Accept: ");
	split = split + strlen("Accept: ");  //Should put us right after Accept: statement
	char *content_type = strtok(split, "\n");
	
	/* If content_type only contains one element, strtok will return NULL.
	 * If content_type has multiple elements (seperated by commas), strtok will 
	 * null terminate the first comma, so content_type will point to only the first element */	 
	strtok(content_type, ",");
	
	printf("Content-type: %s\n", content_type);
	response -> contentType = malloc(strlen(content_type) + 1);
	strcpy(response -> contentType, content_type);

	char *result = "200";
	response -> resultCode = malloc(strlen(result) + 1);
    strcpy(response -> resultCode, result);

	char *stat = "OK";	
	response -> status = malloc(strlen(stat) + 1);
	strcpy(response -> status, stat);

	/*
	 * Check if content requested (req) contains any user variables
	 * GET request contains data in content URL,
	 * POST containst data at the end of the buffer
	 */
	
	char *t = NULL;
	char *userVarStart = NULL;
    if (strcmp(response -> HTTP_Type, "POST") == 0)
	{
		//Print buffer for debug
		printf("Header:\n%s\n\n", buff);

		// Check if POST request with data AFTER the header
		printf("POST Request. Checking for user data\n");
		t = strstr(buff, "\r\n\r\n"); //CRLF is new line
	}
	else if ((t = strchr(req, '?')) != NULL)
	{
		// GET request with data in URL
		printf("GET Request. Checking for user data\n");
		*t = '\0'; //NULL '?' so file request is seperated from the user vars
		t++;
	}
	
	if (t != NULL)
	{
		userVarStart = malloc(strlen(t) + 14);
		sprintf(userVarStart, "QUERY_STRING=%s", t);
		printf("User data: %s\nFile: %s\n\n", userVarStart, req);

		// Add the user variables to QUERY_STRING environment variable
	    putenv(userVarStart); 
	}
		
}
Esempio n. 29
0
GenericAgentConfig *CheckOpts(int argc, char **argv)
{
    extern char *optarg;
    char ld_library_path[CF_BUFSIZE];
    int optindex = 0;
    int c;
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_SERVER);

    while ((c = getopt_long(argc, argv, "dvIKf:D:N:VSxLFMhA", OPTIONS, &optindex)) != EOF)
    {
        switch ((char) c)
        {
        case 'f':

            if (optarg && (strlen(optarg) < 5))
            {
                CfOut(OUTPUT_LEVEL_ERROR, "", " -f used but argument \"%s\" incorrect", optarg);
                exit(EXIT_FAILURE);
            }

            GenericAgentConfigSetInputFile(config, GetWorkDir(), optarg);
            MINUSF = true;
            break;

        case 'd':
            config->debug_mode = true;
            NO_FORK = true;

        case 'K':
            IGNORELOCK = true;
            break;

        case 'D':
            config->heap_soft = StringSetFromString(optarg, ',');
            break;

        case 'N':
            config->heap_negated = StringSetFromString(optarg, ',');
            break;

        case 'I':
            INFORM = true;
            break;

        case 'v':
            VERBOSE = true;
            NO_FORK = true;
            break;

        case 'F':
            NO_FORK = true;
            break;

        case 'L':
            CfOut(OUTPUT_LEVEL_VERBOSE, "", "Setting LD_LIBRARY_PATH=%s\n", optarg);
            snprintf(ld_library_path, CF_BUFSIZE - 1, "LD_LIBRARY_PATH=%s", optarg);
            putenv(ld_library_path);
            break;

        case 'V':
            PrintVersion();
            exit(0);

        case 'h':
            Syntax("cf-serverd", OPTIONS, HINTS, ID, true);
            exit(0);

        case 'M':
            ManPage("cf-serverd - CFEngine's server agent", OPTIONS, HINTS, ID);
            exit(0);

        case 'x':
            CfOut(OUTPUT_LEVEL_ERROR, "", "Self-diagnostic functionality is retired.");
            exit(0);
        case 'A':
#ifdef HAVE_AVAHI_CLIENT_CLIENT_H
#ifdef HAVE_AVAHI_COMMON_ADDRESS_H
            printf("Generating Avahi configuration file.\n");
            if (GenerateAvahiConfig("/etc/avahi/services/cfengine-hub.service") != 0)
            {
                exit(1);
            }
            cf_popen("/etc/init.d/avahi-daemon restart", "r", true);
            printf("Avahi configuration file generated successfuly.\n");
            exit(0);
#else
            printf("This option can only be used when avahi-daemon and libavahi are installed on the machine.\n");
#endif
#endif

        default:
            Syntax("cf-serverd", OPTIONS, HINTS, ID, true);
            exit(1);

        }
    }

    if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
    {
        Log(LOG_LEVEL_ERR, "Too many arguments");
        exit(EXIT_FAILURE);
    }

    return config;
}
Esempio n. 30
0
int start_command(struct child_process *cmd)
{
	int need_in, need_out, need_err;
	int fdin[2], fdout[2], fderr[2];
	int failed_errno = failed_errno;

	/*
	 * In case of errors we must keep the promise to close FDs
	 * that have been passed in via ->in and ->out.
	 */

	need_in = !cmd->no_stdin && cmd->in < 0;
	if (need_in) {
		if (pipe(fdin) < 0) {
			failed_errno = errno;
			if (cmd->out > 0)
				close(cmd->out);
			goto fail_pipe;
		}
		cmd->in = fdin[1];
	}

	need_out = !cmd->no_stdout
		&& !cmd->stdout_to_stderr
		&& cmd->out < 0;
	if (need_out) {
		if (pipe(fdout) < 0) {
			failed_errno = errno;
			if (need_in)
				close_pair(fdin);
			else if (cmd->in)
				close(cmd->in);
			goto fail_pipe;
		}
		cmd->out = fdout[0];
	}

	need_err = !cmd->no_stderr && cmd->err < 0;
	if (need_err) {
		if (pipe(fderr) < 0) {
			failed_errno = errno;
			if (need_in)
				close_pair(fdin);
			else if (cmd->in)
				close(cmd->in);
			if (need_out)
				close_pair(fdout);
			else if (cmd->out)
				close(cmd->out);
fail_pipe:
			error("cannot create pipe for %s: %s",
				cmd->argv[0], strerror(failed_errno));
			errno = failed_errno;
			return -1;
		}
		cmd->err = fderr[0];
	}

	trace_argv_printf(cmd->argv, "trace: run_command:");
	fflush(NULL);

#ifndef WIN32
{
	int notify_pipe[2];
	if (pipe(notify_pipe))
		notify_pipe[0] = notify_pipe[1] = -1;

	cmd->pid = fork();
	if (!cmd->pid) {
		/*
		 * Redirect the channel to write syscall error messages to
		 * before redirecting the process's stderr so that all die()
		 * in subsequent call paths use the parent's stderr.
		 */
		if (cmd->no_stderr || need_err) {
			child_err = dup(2);
			set_cloexec(child_err);
		}
		set_die_routine(die_child);
		set_error_routine(error_child);

		close(notify_pipe[0]);
		set_cloexec(notify_pipe[1]);
		child_notifier = notify_pipe[1];
		atexit(notify_parent);

		if (cmd->no_stdin)
			dup_devnull(0);
		else if (need_in) {
			dup2(fdin[0], 0);
			close_pair(fdin);
		} else if (cmd->in) {
			dup2(cmd->in, 0);
			close(cmd->in);
		}

		if (cmd->no_stderr)
			dup_devnull(2);
		else if (need_err) {
			dup2(fderr[1], 2);
			close_pair(fderr);
		} else if (cmd->err > 1) {
			dup2(cmd->err, 2);
			close(cmd->err);
		}

		if (cmd->no_stdout)
			dup_devnull(1);
		else if (cmd->stdout_to_stderr)
			dup2(2, 1);
		else if (need_out) {
			dup2(fdout[1], 1);
			close_pair(fdout);
		} else if (cmd->out > 1) {
			dup2(cmd->out, 1);
			close(cmd->out);
		}

		if (cmd->dir && chdir(cmd->dir))
			die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
			    cmd->dir);
		if (cmd->env) {
			for (; *cmd->env; cmd->env++) {
				if (strchr(*cmd->env, '='))
					putenv((char *)*cmd->env);
				else
					unsetenv(*cmd->env);
			}
		}
		if (cmd->git_cmd) {
			execv_git_cmd(cmd->argv);
		} else if (cmd->use_shell) {
			execv_shell_cmd(cmd->argv);
		} else {
			sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
		}
		if (errno == ENOENT) {
			if (!cmd->silent_exec_failure)
				error("cannot run %s: %s", cmd->argv[0],
					strerror(ENOENT));
			exit(127);
		} else {
			die_errno("cannot exec '%s'", cmd->argv[0]);
		}
	}
	if (cmd->pid < 0)
		error("cannot fork() for %s: %s", cmd->argv[0],
			strerror(failed_errno = errno));
	else if (cmd->clean_on_exit)
		mark_child_for_cleanup(cmd->pid);

	/*
	 * Wait for child's execvp. If the execvp succeeds (or if fork()
	 * failed), EOF is seen immediately by the parent. Otherwise, the
	 * child process sends a single byte.
	 * Note that use of this infrastructure is completely advisory,
	 * therefore, we keep error checks minimal.
	 */
	close(notify_pipe[1]);
	if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
		/*
		 * At this point we know that fork() succeeded, but execvp()
		 * failed. Errors have been reported to our stderr.
		 */
		wait_or_whine(cmd->pid, cmd->argv[0]);
		failed_errno = errno;
		cmd->pid = -1;
	}
	close(notify_pipe[0]);

}
#else
{
	int fhin = 0, fhout = 1, fherr = 2;
	const char **sargv = cmd->argv;
	char **env = environ;

	if (cmd->no_stdin)
		fhin = open("/dev/null", O_RDWR);
	else if (need_in)
		fhin = dup(fdin[0]);
	else if (cmd->in)
		fhin = dup(cmd->in);

	if (cmd->no_stderr)
		fherr = open("/dev/null", O_RDWR);
	else if (need_err)
		fherr = dup(fderr[1]);
	else if (cmd->err > 2)
		fherr = dup(cmd->err);

	if (cmd->no_stdout)
		fhout = open("/dev/null", O_RDWR);
	else if (cmd->stdout_to_stderr)
		fhout = dup(fherr);
	else if (need_out)
		fhout = dup(fdout[1]);
	else if (cmd->out > 1)
		fhout = dup(cmd->out);

	if (cmd->env)
		env = make_augmented_environ(cmd->env);

	if (cmd->git_cmd) {
		cmd->argv = prepare_git_cmd(cmd->argv);
	} else if (cmd->use_shell) {
		cmd->argv = prepare_shell_cmd(cmd->argv);
	}

	cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
				  fhin, fhout, fherr);
	failed_errno = errno;
	if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
		error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
	if (cmd->clean_on_exit && cmd->pid >= 0)
		mark_child_for_cleanup(cmd->pid);

	if (cmd->env)
		free_environ(env);
	if (cmd->git_cmd)
		free(cmd->argv);

	cmd->argv = sargv;
	if (fhin != 0)
		close(fhin);
	if (fhout != 1)
		close(fhout);
	if (fherr != 2)
		close(fherr);
}
#endif

	if (cmd->pid < 0) {
		if (need_in)
			close_pair(fdin);
		else if (cmd->in)
			close(cmd->in);
		if (need_out)
			close_pair(fdout);
		else if (cmd->out)
			close(cmd->out);
		if (need_err)
			close_pair(fderr);
		else if (cmd->err)
			close(cmd->err);
		errno = failed_errno;
		return -1;
	}

	if (need_in)
		close(fdin[0]);
	else if (cmd->in)
		close(cmd->in);

	if (need_out)
		close(fdout[1]);
	else if (cmd->out)
		close(cmd->out);

	if (need_err)
		close(fderr[1]);
	else if (cmd->err)
		close(cmd->err);

	return 0;
}