Пример #1
0
/**
 * Migemoオブジェクトを作成する。作成に成功するとオブジェクトが戻り値として
 * 返り、失敗するとNULLが返る。dictで指定したファイルがmigemo-dict辞書として
 * オブジェクト作成時に読み込まれる。辞書と同じディレクトリに:
 *
 *  <dl>
 *  <dt>roma2hira.dat</dt>
 *	<dd>ローマ字→平仮名変換表 </dd>
 *  <dt>hira2kata.dat</dt>
 *	<dd>平仮名→カタカナ変換表 </dd>
 *  <dt>han2zen.dat</dt>
 *	<dd>半角→全角変換表 </dd>
 *  </dl>
 *
 * という名前のファイルが存在すれば、存在したものだけが読み込まれる。dictに
 * NULLを指定した場合には、辞書を含めていかなるファイルも読み込まれない。
 * ファイルはオブジェクト作成後にもmigemo_load()関数を使用することで追加読み
 * 込みができる。
 * @param dict migemo-dict辞書のパス。NULLの時は辞書を読み込まない。
 * @returns 作成されたMigemoオブジェクト
 */
    EXPORTS migemo* MIGEMO_CALLTYPE
migemo_open(const char* dict)
{
    migemo *obj;

    /* migemoオブジェクトと各メンバを構築 */
    if (!(obj = (migemo*)calloc(1, sizeof(migemo))))
	return obj;
    obj->enable = 0;
    obj->mtree = mnode_open(NULL);
    obj->charset = CHARSET_NONE;
    obj->rx = rxgen_open();
    obj->roma2hira =	romaji_open();
    obj->hira2kata =	romaji_open();
    obj->han2zen =	romaji_open();
    obj->zen2han =	romaji_open();
    if (!obj->rx || !obj->roma2hira || !obj->hira2kata || !obj->han2zen
	    || !obj->zen2han)
    {
	migemo_close(obj);
	return obj = NULL;
    }

    /* デフォルトmigemo辞書が指定されていたらローマ字とカタカナ辞書も探す */
    if (dict)
    {
#ifndef _MAX_PATH
# define _MAX_PATH 1024 /* いい加減な数値 */
#endif
	char dir[_MAX_PATH];
	char roma_dict[_MAX_PATH];
	char kata_dict[_MAX_PATH];
	char h2z_dict[_MAX_PATH];
	char z2h_dict[_MAX_PATH];
	const char *tmp;
	mtree_p mtree;

	filename_directory(dir, dict);
	tmp = strlen(dir) ? dir : ".";
	dircat(roma_dict, tmp, DICT_ROMA2HIRA);
	dircat(kata_dict, tmp, DICT_HIRA2KATA);
	dircat(h2z_dict,  tmp, DICT_HAN2ZEN);
	dircat(z2h_dict,  tmp, DICT_ZEN2HAN);

	mtree = load_mtree_dictionary2(obj, dict);
	if (mtree)
	{
	    obj->mtree = mtree;
	    obj->enable = 1;
	    romaji_load(obj->roma2hira, roma_dict);
	    romaji_load(obj->hira2kata, kata_dict);
	    romaji_load(obj->han2zen, h2z_dict);
	    romaji_load(obj->zen2han, z2h_dict);
	}
    }
    return obj;
}
Пример #2
0
StatInfo::StatInfo( const char *param_dirpath,
					const char *param_filename )
{
	this->filename = strnewp( param_filename );
	this->dirpath = make_dirpath( param_dirpath );
	fullpath = dircat( param_dirpath, param_filename );
	stat_file( fullpath );
}
Пример #3
0
int main(int argc, char **argv, char **envp) {
  char *c;
  progname = basename(argv[0]);
  c = stringcat(dircat(dirname(argv[0]),dirname(getreadlink(argv[0]))),basename(argv[0]));
  if (0 == strcmp(c,argv[0])) {
    fprintf(stderr,"%s: executes itself\n", argv[0]);
    exit(1);
  }
  argv[0] = c;
  execve(argv[0],argv,envp);
  perror(argv[0]);
  exit(1);
  }
Пример #4
0
// Note: caller must deallocate return value w/ delete []
char *
GridUniverseLogic::scratchFilePath(gman_node_t *gman_node)
{
	MyString filename;
	filename.formatstr("%s%p.%d",scratch_prefix,
					gman_node,daemonCore->getpid());
	char *prefix = temp_dir_path();
	ASSERT(prefix);
		// note: dircat allocates with new char[]
	char *finalpath = dircat(prefix,filename.Value());
	free(prefix);
	return finalpath;
}
Пример #5
0
StatInfo::StatInfo( const char* dirpath, const char* filename, 
					time_t time_access, time_t time_create, 
					time_t time_modify, filesize_t fsize,
					bool is_dir, bool is_symlink )
{
	this->dirpath = strnewp( dirpath );
	this->filename = strnewp( filename );
	fullpath = dircat( dirpath, filename );
	si_error = SIGood;
	si_errno = 0;
	access_time = time_access;
	modify_time = time_modify;
	create_time = time_create;
	valid = false;
	file_size = fsize;
	m_isDirectory = is_dir;
	m_isSymlink = is_symlink;
}
Пример #6
0
MyString
which(const MyString &strFilename, const MyString &strAdditionalSearchDirs)
{
	MyString strPath = getenv( EnvGetName( ENV_PATH ) );
	dprintf( D_FULLDEBUG, "Path: %s\n", strPath.Value());

	char path_delim[3];
	sprintf( path_delim, "%c", PATH_DELIM_CHAR );
	StringList listDirectoriesInPath( strPath.Value(), path_delim );

#ifdef WIN32
	int iLength = strFilename.Length();
	if (!strcasecmp(strFilename.Substr(iLength - 4, iLength - 1).Value(), ".dll"))
	{	// if the filename ends in ".dll"
		
		// in order to mimic the behavior of LoadLibrary
		// we need to artificially insert some other stuff in the search path

		/* from MSDN LoadLibrary
			1.) The directory from which the application loaded. 
			2.) The current directory. 
				Windows XP: If HKLM\System\CurrentControlSet\Control\SessionManager\SafeDllSearchMode is 1, the current directory is the last directory searched. The default value is 0. 

			3.) The Windows system directory. Use the GetSystemDirectory function to get the path of this directory. 
				Windows NT/2000/XP: The wname of this directory is System32. 

			4.) Windows NT/2000/XP: The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System. 
			5.) The Windows directory. Use the GetWindowsDirectory function to get the path of this directory. 
			6.) The directories that are listed in the PATH environment variable. 
		*/

		listDirectoriesInPath.rewind();
		listDirectoriesInPath.next();

		// #5
		char psNewDir[MAX_PATH];
		if (GetWindowsDirectory(psNewDir, MAX_PATH) > 0)
			listDirectoriesInPath.insert(psNewDir);
		else
			dprintf( D_FULLDEBUG, "GetWindowsDirectory() failed, err=%d\n", GetLastError());

		listDirectoriesInPath.rewind();
		listDirectoriesInPath.next();

		// #4 
		strcat(psNewDir, "\\System");
		listDirectoriesInPath.insert(psNewDir);

		listDirectoriesInPath.rewind();
		listDirectoriesInPath.next();

		// #3
		if (GetSystemDirectory(psNewDir, MAX_PATH) > 0)
			listDirectoriesInPath.insert(psNewDir);
		else
			dprintf( D_FULLDEBUG, "GetSystemDirectory() failed, err=%d\n", GetLastError());

		listDirectoriesInPath.rewind();
		listDirectoriesInPath.next();

		// #2
		if (_getcwd(psNewDir, MAX_PATH))
			listDirectoriesInPath.insert(psNewDir);
		else
			dprintf( D_FULLDEBUG, "_getcwd() failed, err=%d\n", errno);

		// #1  had better be covered by the user passing in strAdditionalSearchDirs
	}
#endif

	listDirectoriesInPath.rewind();
	listDirectoriesInPath.next();

	// add additional dirs if specified
	if( strAdditionalSearchDirs != "" ) {
		// path_delim was set above
		StringList listAdditionalSearchDirs( strAdditionalSearchDirs.Value(), path_delim );
		listDirectoriesInPath.create_union(listAdditionalSearchDirs, false);
	}
	
	listDirectoriesInPath.rewind();

	const char *psDir;
	while( (psDir = listDirectoriesInPath.next()) )
	{
		dprintf( D_FULLDEBUG, "Checking dir: %s\n", psDir );

		char *psFullDir = dircat(psDir, strFilename.Value());
		MyString strFullDir = psFullDir;
		delete [] psFullDir;

		StatInfo info(strFullDir.Value());
		if( info.Error() == SIGood ) {
			return strFullDir;
		}
	}
	return "";
}
Пример #7
0
void
Init() {
  char * tmp = param( "CRED_SUPER_USERS" );
  if( tmp ) {
    super_users.initializeFromString( tmp );
    free( tmp );
  } else {
#if defined(WIN32)
    super_users.initializeFromString("Administrator");
#else
    super_users.initializeFromString("root");
#endif
  }

  char * spool = param ("SPOOL");

  tmp = param ( "CRED_STORE_DIR" );
  if ( tmp ) {
    cred_store_dir = tmp;
  } else {
    cred_store_dir = dircat (spool, "cred");
  } 
  if ( spool != NULL ) {
	  free (spool);
  }

  tmp = param ( "CRED_INDEX_FILE" );
  if (tmp ) {
    cred_index_file = tmp;
  } else {
    cred_index_file = dircat (cred_store_dir, "cred-index");
  }

  // default 1 hr
  default_cred_expire_threshold = param_integer ("DEFAULT_CRED_EXPIRE_THRESHOLD", 3600);

	// default 1 minute
	CheckCredentials_interval =
		param_integer (
			"CRED_CHECK_INTERVAL",		// param name
			DEF_CRED_CHECK_INTERVAL		// default value, seconds
	  );

  struct stat stat_buff;
  if (stat (cred_store_dir, &stat_buff)) {
    dprintf (D_ALWAYS, "ERROR: Cred store directory %s does not exist\n", cred_store_dir);
    DC_Exit (1 );
  }

  if (stat (cred_index_file, &stat_buff)) {
    dprintf (D_ALWAYS, "Creating credential index file %s\n", cred_index_file);
    priv_state priv = set_root_priv();
    int fd = safe_open_wrapper_follow(cred_index_file, O_WRONLY | O_CREAT | O_TRUNC, 0600);
    if (fd != -1) {
      close (fd);
      set_priv (priv);
    } else {
      dprintf (D_ALWAYS, "ERROR: Unable to create credential index file %s\n", cred_index_file);
      set_priv (priv);
      DC_Exit (1 );
    }
  } else {
    if ((stat_buff.st_mode & (S_IRWXG | S_IRWXO)) ||
	(stat_buff.st_uid != getuid())) {
      dprintf (D_ALWAYS, "ERROR: Invalid ownership / permissions on credential index file %s\n", 
	       cred_index_file);
      DC_Exit (1 );
    }
  }

}
Пример #8
0
int 
store_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) {
  void * data = NULL;
  int rtnVal = FALSE;
  int rc;
  char * temp_file_name = NULL;
  bool found_cred;
  CredentialWrapper * temp_cred = NULL;
  int data_size = -1;
  classad::ClassAd * _classad = NULL;
  classad::ClassAd classad;
  std::string classad_cstr;
  char * classad_str = NULL;
  classad::ClassAdParser parser;
  ReliSock * socket = (ReliSock*)stream;
  const char * user = NULL;

  CredentialWrapper * cred_wrapper = NULL;

  if (!socket->triedAuthentication()) { 
    CondorError errstack;
    if( ! SecMan::authenticate_sock(socket, WRITE, &errstack) ) {
      dprintf (D_ALWAYS, "Unable to authenticate, qutting\n");
      goto EXIT;
    }
  }

  user = socket->getFullyQualifiedUser();
  dprintf (D_FULLDEBUG, "Request by: %s, %s\n", socket->getOwner(), user);

  socket->decode();

  if (!socket->code (classad_str)) {
    dprintf (D_ALWAYS, "Error receiving credential metadata\n"); 
    goto EXIT;
  }

  classad_cstr = classad_str;
  free (classad_str);

  _classad = parser.ParseClassAd(classad_cstr);
  if (!_classad) {
	  dprintf (D_ALWAYS, "Error: invalid credential metadata %s\n", classad_cstr.c_str());
	  goto EXIT;
  }

  classad = *_classad;
  delete _classad;
  
 
  
  int type;
  if (!classad.EvaluateAttrInt ("Type", type)) {
    dprintf (D_ALWAYS, "Missing Type attribute in classad!\n");
    goto EXIT;
  }


  if (type == X509_CREDENTIAL_TYPE) {
	cred_wrapper = new X509CredentialWrapper (classad);
    dprintf (D_ALWAYS, "Name=%s Size=%d\n", 
			 cred_wrapper->cred->GetName(), 
			 cred_wrapper->cred->GetDataSize());

  } else {
	  dprintf (D_ALWAYS, "Unsupported credential type %d\n", type);
	  goto EXIT;
  }

  cred_wrapper->cred->SetOrigOwner (socket->getOwner()); // original remote uname
  cred_wrapper->cred->SetOwner (user);                   // mapped uname

  // Receive credential data
  data_size = cred_wrapper->cred->GetDataSize();
  if (data_size > MAX_CRED_DATA_SIZE) {
	  dprintf (D_ALWAYS, "ERROR: Credential data size %d > maximum allowed (%d)\n", data_size, MAX_CRED_DATA_SIZE);
	  goto EXIT;
  }

  data = malloc (data_size);
  if (data == NULL) {
	  EXCEPT("Out of memory. Aborting.");
  }
  if (!socket->code_bytes(data,data_size)) {
    dprintf (D_ALWAYS, "Error receiving credential data\n");
    goto EXIT;
  }
  cred_wrapper->cred->SetData (data, data_size);
  

  // Check whether credential under this name already exists
  found_cred=false;
  credentials.Rewind();
  while (credentials.Next(temp_cred)) {
	  if ((strcmp(cred_wrapper->cred->GetName(), 
				  temp_cred->cred->GetName()) == 0) && 
		  (strcmp(cred_wrapper->cred->GetOwner(), 
				  temp_cred->cred->GetOwner()) == 0)) {
		  found_cred=true;
		  break; // found it
	  }
  }

  if (found_cred) {
	  dprintf (D_ALWAYS, "Credential %s for owner %s already exists!\n", 
			   cred_wrapper->cred->GetName(), 
			   cred_wrapper->cred->GetOwner());
	  socket->encode();
	  int rcred=CREDD_ERROR_CREDENTIAL_ALREADY_EXISTS;
	  socket->code(rcred);
	  goto EXIT;
  }

  
  // Write data to a file
  temp_file_name = dircat (cred_store_dir, "credXXXXXX");
  condor_mkstemp (temp_file_name);
  cred_wrapper->SetStorageName (temp_file_name);
  
  init_user_id_from_FQN (user);
  if (!StoreData(temp_file_name,data,data_size)) {
    socket->encode();
    int rcred = CREDD_UNABLE_TO_STORE;
    socket->code(rcred);
    goto EXIT;
  }

  ((X509CredentialWrapper*)cred_wrapper)->cred->SetRealExpirationTime (
			   x509_proxy_expiration_time(temp_file_name));

  // Write metadata to a file
  credentials.Append (cred_wrapper);
  SaveCredentialList();

  // Write response to the client
  socket->encode();
  rc = CREDD_SUCCESS;
  socket->code(rc);

  dprintf( D_ALWAYS, "Credential name %s owner %s successfully stored\n",
			 cred_wrapper->cred->GetName(), cred_wrapper->cred->GetOwner() );

  if (type == X509_CREDENTIAL_TYPE) {
	((X509Credential*)cred_wrapper->cred)->display( D_FULLDEBUG );
  }
  rtnVal = TRUE;

EXIT:
  if ( data != NULL ) {
	  free (data);
  }
  if ( temp_file_name != NULL ) {
	  delete [] temp_file_name;
  }
  if ( cred_wrapper != NULL) {
	  delete cred_wrapper;
  }
  return rtnVal;
}
Пример #9
0
void
do_process_request(const ClassAd *inputAd, ClassAd *resultAd, const int req_number, 
				   const char *iwd, const char *stdio_iwd)
{
		// Check for inputAd
	if ( !inputAd ) {
		handle_process_request_error("No input ad",req_number,resultAd);
		return;
	}

		// Map the CMD specified in the input via the config file.
	MyString UnmappedJobName,JobName;
	if (inputAd->LookupString(ATTR_JOB_CMD,UnmappedJobName) == 0 ) {
			// no CMD specified.
		handle_process_request_error("No CMD specified",req_number,resultAd);
		return;
	}
	char *auth_commands = param("SOAPSHELL_AUTHORIZED_COMMANDS");
	StringList auth_list(auth_commands,",");
	if ( auth_commands ) free(auth_commands);
		// Each command needs four tuples; anything else is a misconfiguration
	if ( auth_list.number() % 4 != 0 ) {
		handle_process_request_error("Service is misconfigured: SOAPSHELL_AUTHORIZED_COMMANDS malformed",req_number,resultAd);
		return;
	}

	if ( auth_list.contains_anycase(UnmappedJobName.Value()) == TRUE ) {
		JobName = auth_list.next();
	}
	if ( JobName.IsEmpty() ) {
			// the CMD not authorized
		handle_process_request_error("Requested CMD not authorized via SOAPSHELL_AUTHORIZED_COMMANDS",req_number,resultAd);
		return;
	}

		// handle command line arguments.
	ArgList args;
	args.SetArgV1SyntaxToCurrentPlatform();
	args.AppendArg(JobName.Value());	// set argv[0] to command
	char *soapshell_args = auth_list.next();
	if ( soapshell_args && strcmp(soapshell_args,"*") ) {
		if(!args.AppendArgsV1RawOrV2Quoted(soapshell_args,NULL)) {
			dprintf( D_ALWAYS, "ERROR: SOAPSHELL_ARGS config macro invalid\n" );
		}
	} else if(!args.AppendArgsFromClassAd(inputAd,NULL)) {
		handle_process_request_error("Failed to setup CMD arguments",req_number,resultAd);
		return;
	}
		
		// handle the environment.
	Env job_env;
	char *env_str = auth_list.next();
	if ( env_str && strcmp(env_str,"*") ) {
		if(!job_env.MergeFromV1RawOrV2Quoted(env_str,NULL) ) {
			dprintf(D_ALWAYS,"ERROR: SOAPSHELL_ENVIRONMENT config macro invalid\n");
		}
	} else if(!job_env.MergeFrom(inputAd,NULL)) {
		// bad environment string in job ad!
		handle_process_request_error("Request has faulty environment string",req_number,resultAd);
		return;
	}

		// Write input files into iwd (we will write stdin later)
	if ( !write_input_files(inputAd, iwd) ) {
		// failed to write input files
		handle_process_request_error("Failed to write input files",req_number,resultAd);
		return;
	}

		// handle stdin, stdout, and stderr redirection
	const char* jobstdin_ = dircat(stdio_iwd,"stdin");
	MyString jobstdin(jobstdin_);
	const char* jobstdout_ = dircat(stdio_iwd,"stdout");
	MyString jobstdout(jobstdout_);
	const char* jobstderr_ = dircat(stdio_iwd,"stderr");
	MyString jobstderr(jobstderr_);
	delete [] jobstdin_;
	delete [] jobstdout_;
	delete [] jobstderr_;
	int flags = O_WRONLY | O_CREAT | O_TRUNC | O_APPEND | O_LARGEFILE;
		// write stdin file is needed
	{
		char *input = NULL;
		unsigned char *output = NULL;
		int output_length = 0;
		int fd = -1;
		inputAd->LookupString(ATTR_JOB_INPUT,&input);
		if ( input ) {
			// Caller needs to free *output if non-NULL
			condor_base64_decode(input,&output,&output_length);
			if ( output ) {
				fd = safe_open_wrapper_follow( jobstdin.Value(), flags, 0666 );
				if ( fd > -1 ) {
					write(fd,output,output_length);
					close(fd);
				}
				free(output);
			}
			free(input);
			if ( fd < 0 ) {
				handle_process_request_error("Failed to write stdin",req_number,resultAd);
				return;
			}
		}
	}
	int fds[3]; 
		// initialize these to -2 to mean they're not specified.
		// -1 will be treated as an error.
	fds[0] = -2; fds[1] = -2; fds[2] = -2;	
	fds[0] = safe_open_wrapper_follow( jobstdin.Value(), O_RDONLY | O_LARGEFILE ); // stdin	
	fds[1] = safe_open_wrapper_follow( jobstdout.Value(), flags, 0666 );	// stdout
	fds[2] = safe_open_wrapper_follow( jobstderr.Value(), flags, 0666 );	// stderr
	/* Bail out if we couldn't open stdout/err files correctly */
	if( fds[1]==-1 || fds[2]==-1 ) {
		/* only close ones that had been opened correctly */
		for ( int i = 0; i <= 2; i++ ) {
			if ( fds[i] >= 0 ) {
				daemonCore->Close_FD ( fds[i] );
			}
		}
		handle_process_request_error("Failed to write stdout/err files",req_number,resultAd);
		return;
	}

		// Print what we are about to do to the log
	MyString args_string;
	args.GetArgsStringForDisplay(&args_string,1);
	dprintf( D_ALWAYS, "About to exec %s %s\n", JobName.Value(),
				 args_string.Value() );

		// Spawn a process, baby!!!
	int JobPid = daemonCore->Create_Process( JobName.Value(),	// executable
		                                     args,				// args
		                                     PRIV_UNKNOWN,		// priv_state - TODO
		                                     0,					// reaper id - TODO
		                                     FALSE,				// want_command_port
		                                     &job_env,			// job environment
		                                     iwd,				// job iwd
		                                     NULL,				// family_info - TODO
		                                     NULL,				// sock_inherit_list
		                                     fds				// stdio redirection
										);

		// NOTE: Create_Process() saves the errno for us if it is an
		// "interesting" error.
	char const *create_process_error = NULL;
	if(JobPid == FALSE && errno) create_process_error = strerror(errno);

		// now close the descriptors in fds array.  our child has inherited
		// them already, so we should close them so we do not leak descriptors.
	for ( int i = 0; i <= 2; i++ ) {
		if ( fds[i] >= 0 ) {
			daemonCore->Close_FD ( fds[i] );
		}
	}

	if ( JobPid == FALSE ) {
		JobPid = -1;
		MyString errormsg;
		errormsg.formatstr("Create_Process failed %s",create_process_error ? create_process_error : "");
		handle_process_request_error(errormsg.Value(),req_number,resultAd);
		return;
	}


	dprintf(D_ALWAYS,"Create_Process succeeded, pid=%d\n",JobPid);

		// TODO - For now, just deal w/ one at a time. :(
		// So for now just wait for the child to exit.
#ifdef WIN32
#error This service does not yet work on Windows
#else
	{
		int exit_status;
		pid_t pid;
		for (;;) {
			pid = wait(&exit_status);
			dprintf(D_FULLDEBUG,"WAIT returned %d, errno=%d\n",pid,errno);
			if (pid == JobPid ) break;
			if (pid == -1 && errno != EINTR) {
				EXCEPT("waitpid failed errno=%d",errno);
			}
		}
		if ( WIFEXITED(exit_status) ) {
			int status = WEXITSTATUS(exit_status);
			resultAd->Assign("EXIT_STATUS",status);
		}		
	}
#endif

		// Job has completed, exit status is in the ad.  Now put
		// the output files into the result ad.
	stash_output_file(resultAd, jobstdout.Value(), ATTR_JOB_OUTPUT);
	stash_output_file(resultAd, jobstderr.Value(), ATTR_JOB_ERROR);

}