//--------------------------------------------------------------------------- const char * Job::GetJobstateJobTag() { if ( !_jobTag ) { MyString jobTagName = MultiLogFiles::loadValueFromSubFile( _cmdFile, _directory, JOB_TAG_NAME ); if ( jobTagName == "" ) { jobTagName = PEGASUS_SITE; } else { // Remove double-quotes int begin = jobTagName[0] == '\"' ? 1 : 0; int last = jobTagName.Length() - 1; int end = jobTagName[last] == '\"' ? last - 1 : last; jobTagName = jobTagName.Substr( begin, end ); } MyString tmpJobTag = MultiLogFiles::loadValueFromSubFile( _cmdFile, _directory, jobTagName.Value() ); if ( tmpJobTag == "" ) { tmpJobTag = "-"; } else { // Remove double-quotes int begin = tmpJobTag[0] == '\"' ? 1 : 0; int last = tmpJobTag.Length() - 1; int end = tmpJobTag[last] == '\"' ? last - 1 : last; tmpJobTag = tmpJobTag.Substr( begin, end ); } _jobTag = strnewp( tmpJobTag.Value() ); } return _jobTag; }
// Remove/replace characters from the string so it can be used as an attribute name // it changes the string that is passed to it. first leading an trailing spaces // are removed, then Characters that are invalid in compatible classads // (basically anthing but [a-zA-Z0-9_]) is replaced with chReplace. // if chReplace is 0, then invalid characters are removed. // if compact is true, then multiple consecutive runs of chReplace // are changed to a single instance. // return value is the length of the resulting string. // int cleanStringForUseAsAttr(MyString &str, char chReplace/*=0*/, bool compact/*=true*/) { // have 0 mean 'remove' since we can't actually use it as a replacement char // we'll actually implement it by replacing invalid chars with spaces, // and then compacting to remove all of the spaces. if (0 == chReplace) { chReplace = ' '; compact = true; } // trim the input and replace invalid chars with chReplace str.trim(); for (int ii = 0; ii < str.Length(); ++ii) { char ch = str[ii]; if (ch == '_' || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) continue; str.setChar(ii,chReplace); } // if compact, convert runs of chReplace with a single instance, // unless chReplace is ' ', then remove them entirely. if (compact) { if (chReplace == ' ') str.replaceString(" ",""); else { MyString tmp; tmp += chReplace; tmp += chReplace; str.replaceString(tmp.Value(), tmp.Value()+1); } } str.trim(); return str.Length(); }
// +, += (concatenation - takes a MyString or a c style string) MyString MyString::operator+ (const MyString & aMyString) { // Get the total length of the two strings and create a MyString to return int totalLen = this->Length() + aMyString.Length(); MyString toReturn(totalLen + 1); // Ensure that the MyString has a length toReturn._length = totalLen; // Add the null character toReturn._string[totalLen] = '\0'; // The current position in relativity to the total int currentPos = 0; // Take the values from this for (int i = 0; i < this->Length(); i++) { toReturn._string[currentPos] = this->_string[i]; currentPos++; } // Take the values from aMyString for (int i = 0; i < aMyString.Length(); i++) { toReturn[currentPos] = aMyString[i]; currentPos++; } return toReturn; }
void MapFile::PerformSubstitution(ExtArray<MyString> & groups, const MyString pattern, MyString & output) { for (int index = 0; index < pattern.Length(); index++) { if ('\\' == pattern[index]) { index++; if (index < pattern.Length()) { if ('1' <= pattern[index] && '9' >= pattern[index]) { int match = pattern[index] - '0'; if (groups.getlast() >= match) { output += groups[match]; continue; } } output += '\\'; } } output += pattern[index]; } }
void AvailStats::checkpoint() { // Checkpoint our state to disk by serializing to a string // and writing the string to disk. It's not very efficient // to create this string each time, but it shouldn't be too big // (under 1KB), so I don't think it's worth worrying too much // about efficiency. if( ckpt_filename.Length() ) { FILE *fp = safe_fopen_wrapper_follow(tmp_ckpt_filename.Value(), "w"); if( fp ) { MyString state = serialize(); if( (int)fwrite(state.Value(), sizeof(char), state.Length(), fp) == state.Length() ) { fclose(fp); if ( rotate_file(tmp_ckpt_filename.Value(), ckpt_filename.Value()) < 0 ) { dprintf( D_ALWAYS, "AvailStats::checkpoint() failed to rotate " "%s to %s\n", tmp_ckpt_filename.Value(), ckpt_filename.Value() ); } } else { fclose(fp); } } } }
void append_arg(char const *arg,MyString &result) { if(result.Length()) { result += " "; } ASSERT(arg); if(!*arg) { result += "''"; //empty arg } while(*arg) { switch(*arg) { case ' ': case '\t': case '\n': case '\r': case '\'': if(result.Length() && result[result.Length()-1] == '\'') { //combine preceeding quoted section with this one, //so we do not introduce a repeated quote. result.setChar(result.Length()-1,'\0'); } else { result += '\''; } if(*arg == '\'') { result += '\''; //repeat the quote to escape it } result += *(arg++); result += '\''; break; default: result += *(arg++); } } }
int parseMyProxyArgument (const char * arg, char * & user, char * & host, int & port) { MyString strArg (arg); int at_idx = strArg.FindChar ((int)'@'); int colon_idx = strArg.FindChar ((int)':', at_idx+1); if (at_idx != -1) { MyString _user = strArg.Substr (0, at_idx-1); user = strdup(_user.Value()); } if (colon_idx == -1) { MyString _host = strArg.Substr (at_idx+1, strArg.Length()-1); host = strdup(_host.Value()); } else { MyString _host = strArg.Substr (at_idx+1, colon_idx-1); host = strdup(_host.Value()); MyString _port = strArg.Substr (colon_idx+1, strArg.Length()-1); port = atoi(_port.Value()); } return TRUE; }
condor_sockaddr convert_hostname_to_ipaddr(const MyString& fullname) { MyString hostname; MyString default_domain; bool truncated = false; if (param(default_domain, "DEFAULT_DOMAIN_NAME")) { MyString dotted_domain = "."; dotted_domain += default_domain; int pos = fullname.find(dotted_domain.Value()); if (pos != -1) { truncated = true; hostname = fullname.Substr(0, pos - 1); } } if (!truncated) hostname = fullname; // detects if hostname is IPv6 // // hostname is NODNS coded address // // for example, // it could be 127-0-0-1 (127.0.0.1) as IPv4 address // it could be fe80-3577--1234 ( fe80:3577::1234) as IPv6 address // // it is IPv6 address // 1) if there are 7 '-' // 2) if there are '--' which means compaction of zeroes in IPv6 adress char target_char; bool ipv6 = false; if (hostname.find("--") != -1) ipv6 = true; else { int dash_count = 0; for (int i = 0; i < hostname.Length(); ++i) if (hostname[i] == '-') ++dash_count; if (dash_count == 7) ipv6 = true; } if (ipv6) target_char = ':'; else target_char ='.'; // converts hostname to IP address string for (int i = 0; i < hostname.Length(); ++i) { if (hostname[i] == '-') hostname.setChar(i, target_char); } condor_sockaddr ret; ret.from_ip_string(hostname); return ret; }
int main(int, char* argv[]) { MyString err; // dup FD 0 since well will later replace FD 0 with the job's stdin // int sock_fd = dup(0); if (sock_fd == -1) { err.sprintf("dup error on FD 0: %s", strerror(errno)); full_write(0, err.Value(), err.Length() + 1); exit(1); } // set up an Env object that we'll use for the job. we'll initialize // it with the environment that Condor sends us then merge on top of // that the environment that glexec prepared for us // Env env; char* env_buf = read_env(sock_fd); MyString merge_err; if (!env.MergeFromV2Raw(env_buf, &merge_err)) { err.sprintf("Env::MergeFromV2Raw error: %s", merge_err.Value()); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } env.MergeFrom(environ); delete[] env_buf; // now receive an FD on our stdin (which is a UNIX domain socket) // that we'll use as the job's stdin // int job_fd = read_fd(sock_fd); if (dup2(job_fd, 0) == -1) { err.sprintf("dup2 to FD 0 error: %s", strerror(errno)); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } close(job_fd); if (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1) { err.sprintf("fcntl error setting close-on-exec: %s", strerror(errno)); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } // now we can exec the job. for arguments, we shift this wrappers // arguments by one. similarly, the job's executable path is taken // as our argv[1] // char** envp = env.getStringArray(); execve(argv[1], &argv[1], envp); err.sprintf("execve error: %s", strerror(errno)); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); }
// Given an offset count that points to a delimiter, this function returns the // previous delimiter offset position. // If clusterId and procId is specified, it will not return the immediately // previous delimiter, but the nearest previous delimiter that matches static long findPrevDelimiter(FILE *fd, char* filename, long currOffset) { MyString buf; char *owner; long prevOffset = -1, completionDate = -1; int clusterId = -1, procId = -1; fseek(fd, currOffset, SEEK_SET); buf.readLine(fd); owner = (char *) malloc(buf.Length() * sizeof(char)); // Current format of the delimiter: // *** ProcId = a ClusterId = b Owner = "cde" CompletionDate = f // For the moment, owner and completionDate are just parsed in, reserved for future functionalities. sscanf(buf.Value(), "%*s %*s %*s %ld %*s %*s %d %*s %*s %d %*s %*s %s %*s %*s %ld", &prevOffset, &clusterId, &procId, owner, &completionDate); if (prevOffset == -1 && clusterId == -1 && procId == -1) { fprintf(stderr, "Error: (%s) is an incompatible history file, please run condor_convert_history.\n", filename); free(owner); exit(1); } // If clusterId.procId is specified if (cluster != -1 || proc != -1) { // Ok if only clusterId specified while (clusterId != cluster || (proc != -1 && procId != proc)) { if (prevOffset == 0) { // no match free(owner); return -1; } // Find previous delimiter + summary fseek(fd, prevOffset, SEEK_SET); buf.readLine(fd); owner = (char *) realloc (owner, buf.Length() * sizeof(char)); sscanf(buf.Value(), "%*s %*s %*s %ld %*s %*s %d %*s %*s %d %*s %*s %s %*s %*s %ld", &prevOffset, &clusterId, &procId, owner, &completionDate); } } free(owner); return prevOffset; }
//! Gets the writer password required by the quill++ // daemon to access the database static MyString getWritePassword(const char *write_passwd_fname, const char *host, const char *port, const char *db, const char *dbuser) { FILE *fp = NULL; MyString passwd; int len; MyString prefix; MyString msbuf; const char *buf; bool found = FALSE; // prefix is for the prefix of the entry in the .pgpass // it is in the format of the following: // host:port:db:user:password prefix.sprintf("%s:%s:%s:%s:", host, port, db, dbuser); len = prefix.Length(); fp = safe_fopen_wrapper(write_passwd_fname, "r"); if(fp == NULL) { EXCEPT("Unable to open password file %s\n", write_passwd_fname); } //dprintf(D_ALWAYS, "prefix: %s\n", prefix); while(msbuf.readLine(fp)) { msbuf.chomp(); buf = msbuf.Value(); //fprintf(stderr, "line: %s\n", buf); // check if the entry matches the prefix if (strncmp(buf, prefix.Value(), len) == 0) { // extract the password passwd = msbuf.Substr(len, msbuf.Length()); found = TRUE; break; } } fclose(fp); if (!found) { EXCEPT("Unable to find password from file %s\n", write_passwd_fname); } return passwd; }
CheckEvents::check_event_result_t CheckEvents::CheckAllJobs(MyString &errorMsg) { check_event_result_t result = EVENT_OKAY; errorMsg = ""; const int MAX_MSG_LEN = 1024; bool msgFull = false; // message length has hit max CondorID id; JobInfo *info = NULL; jobHash.startIterations(); while ( jobHash.iterate(id, info) != 0 ) { // Put a limit on the maximum message length so we don't // have a chance of ending up with a ridiculously large // MyString... if ( !msgFull && (errorMsg.Length() > MAX_MSG_LEN) ) { errorMsg += " ..."; msgFull = true; } MyString idStr("BAD EVENT: job "); idStr.formatstr_cat("(%d.%d.%d)", id._cluster, id._proc, id._subproc); MyString tmpMsg; CheckJobFinal(idStr, id, info, tmpMsg, result); if ( tmpMsg != "" && !msgFull ) { if ( errorMsg != "" ) errorMsg += "; "; errorMsg += tmpMsg; } } return result; }
// Insert // Takes two arguments // An int – the index in this MyString // at which to insert the new chars // A MyString containing the chars to be inserted void MyString::Insert(const MyString & aMyString, int index) { int lengthOfAMyString = aMyString.Length(); int newCapacity = _length + lengthOfAMyString; _capacity = newCapacity; char *tempStr = new char[_capacity + 1]; for(int i = 0; i < index; i++) { tempStr[i] = _string[i]; } tempStr[index] = '\0'; strcat(tempStr, aMyString._cstr()); for(int i = 0; i <= _length - index; i++) { tempStr[index + lengthOfAMyString + i] = _string[index + i]; } _length = _capacity; delete [] _string; _string = tempStr; }
bool privsep_get_switchboard_response(FILE* err_fp, MyString *response) { // first read everything off the error pipe and close // the error pipe // MyString err; while (err.readLine(err_fp, true)) { } fclose(err_fp); // if this is passed in, assume the caller will handle any // error propagation, and we just succeed. if (response) { *response = err; return true; } // if there was something there, print it out here (since no one captured // the error message) and return false to indicate something went wrong. if (err.Length() != 0) { dprintf(D_ALWAYS, "privsep_get_switchboard_response: error received: %s", err.Value()); return false; } // otherwise, indicate that everything's fine // return true; }
// Replace // Takes three arguments // An int – the index of the char in thisMyString // to begin replacing at. // An int – the number of chars to replace // And a MyString containg the replacement string // throws an exception if startIndex >= Length // throws an exception if startIndex + numChars > Length() // throws an exception if aMyString.Length() < numChars void MyString::Replace(int startIndex, int numChars, const MyString & aMyString) { // Exception check if (startIndex >= this->Length()) { throw "!Access Violation!"; } // Exception check if (startIndex + numChars > this->Length()) { throw "!Access Violation!"; } // Exception check if (aMyString.Length() < numChars) { throw "!Access Violation!"; } //for loop for index of this string for (int i = startIndex; i < startIndex + numChars; i++) { //for loop for proper index of aMyString for (int j = 0; j < numChars; j++) { this->_string[i] = aMyString[j]; } } }
// Look up an IP attribute in an ad, optionally fall back to an alternate bool getIpAddr( const char *ad_type, const ClassAd *ad, const char *attrname, const char *attrold, MyString &ip ) { MyString tmp; // get the IP and port of the startd if ( !adLookup( ad_type, ad, attrname, attrold, tmp, true ) ) { return false; } // If no valid string, do our own thing.. char* host; if ( ( tmp.Length() == 0 ) || (host = getHostFromAddr(tmp.Value())) == NULL ) { dprintf (D_ALWAYS, "%sAd: Invalid IP address in classAd\n", ad_type ); return false; } ip = host; free(host); return true; }
MyString convert_ipaddr_to_hostname(const condor_sockaddr& addr) { MyString ret; MyString default_domain; if (!param(default_domain, "DEFAULT_DOMAIN_NAME")) { dprintf(D_HOSTNAME, "NO_DNS: DEFAULT_DOMAIN_NAME must be defined in your " "top-level config file\n"); return ret; } ret = addr.to_ip_string(); for (int i = 0; i < ret.Length(); ++i) { if (ret[i] == '.' || ret[i] == ':') ret.setChar(i, '-'); } ret += "."; ret += default_domain; // Hostnames can't begin with -, as per RFC 1123 // ipv6 zero-compression could cause this, esp. for the loopback addr if (ret[0] == '-') { ret = "0" + ret; } return ret; }
bool Regex::match(const MyString & string, ExtArray<MyString> * groups) { if ( ! this->isInitialized() ) { return false; } int group_count; pcre_fullinfo(re, NULL, PCRE_INFO_CAPTURECOUNT, &group_count); int oveccount = 3 * (group_count + 1); // +1 for the string itself int * ovector = (int *) malloc(oveccount * sizeof(int)); if (!ovector) { // XXX: EXCEPTing sucks EXCEPT("No memory to allocate data for re match"); } int rc = pcre_exec(re, NULL, string.Value(), string.Length(), 0, // Index in string from which to start matching options, ovector, oveccount); if (NULL != groups) { for (int i = 0; i < rc; i++) { (*groups)[i] = string.Substr(ovector[i * 2], ovector[i * 2 + 1] - 1); } } free(ovector); return rc > 0; }
TEST(MyString, DefaultConstructor) { const MyString s; EXPECT_STREQ(NULL, s.c_string()); EXPECT_EQ(0u, s.Length()); }
bool VirshType::findCkptConfigAndSuspendFile(MyString &vmconfig, MyString &suspendfile) { if( m_transfer_intermediate_files.isEmpty() ) { return false; } vmconfig = ""; suspendfile = ""; MyString tmpconfig; MyString tmpsuspendfile; if( filelist_contains_file( XEN_CONFIG_FILE_NAME, &m_transfer_intermediate_files, true) ) { // There is a vm config file for checkpointed files tmpconfig.formatstr("%s%c%s",m_workingpath.Value(), DIR_DELIM_CHAR, XEN_CONFIG_FILE_NAME); } MyString tmp_name; makeNameofSuspendfile(tmp_name); if( filelist_contains_file(tmp_name.Value(), &m_transfer_intermediate_files, true) ) { // There is a suspend file that was created during vacate tmpsuspendfile = tmp_name; if( check_vm_read_access_file(tmpsuspendfile.Value(), true) == false) { return false; } } if( (tmpconfig.Length() > 0) && (tmpsuspendfile.Length() > 0 )) { // check if the timestamp of suspend file is same to // that of writable disk files // If timestamp differs between suspend file and writable disk file, // it means that there was a crash. // So we need to restart this VM job from the beginning. if( checkCkptSuspendFile(tmpsuspendfile.Value()) ) { vmconfig = tmpconfig; suspendfile = tmpsuspendfile; return true; } } return false; }
static char* read_env(int sock_fd) { MyString err; int bytes; int env_len; bytes = full_read(0, &env_len, sizeof(env_len)); if (bytes != sizeof(env_len)) { if (bytes == -1) { err.sprintf("read error getting env size: %s", strerror(errno)); } else { err.sprintf("short read of env size: %d of %lu bytes", bytes, sizeof(env_len)); } full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } if (env_len <= 0) { err.sprintf("invalid env size %d read from stdin", env_len); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } char* env_buf = new char[env_len]; if (env_buf == NULL) { err.sprintf("failure to allocate %d bytes", env_len); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } bytes = full_read(0, env_buf, env_len); if (bytes != env_len) { if (bytes == -1) { err.sprintf("read error getting env: %s", strerror(errno)); } else { err.sprintf("short read of env: %d of %d bytes", bytes, env_len); } full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } return env_buf; }
static pid_t privsep_launch_switchboard(const char* op, FILE*& in_fp, FILE*& err_fp) { ASSERT(switchboard_path != NULL); ASSERT(switchboard_file != NULL); // create the pipes for communication with the switchboard // int child_in_fd; int child_err_fd; if (!privsep_create_pipes(in_fp, child_in_fd, err_fp, child_err_fd)) { return 0; } pid_t switchboard_pid = fork(); if (switchboard_pid == -1) { dprintf(D_ALWAYS, "privsep_launch_switchboard: fork error: %s (%d)\n", strerror(errno), errno); return 0; } // in the parent, we just return back to the caller so they can // start sending commands to the switchboard's input pipe; but // make sure to close the clients sides of our pipes first // if (switchboard_pid != 0) { close(child_in_fd); close(child_err_fd); return switchboard_pid; } // in the child, we need to exec the switchboard binary with the // appropriate arguments // close(fileno(in_fp)); close(fileno(err_fp)); MyString cmd; ArgList arg_list; privsep_get_switchboard_command(op, child_in_fd, child_err_fd, cmd, arg_list); execv(cmd.Value(), arg_list.GetStringArray()); // exec failed; tell our parent using the error pipe that something // went wrong before exiting // MyString err; err.sprintf("exec error on %s: %s (%d)\n", cmd.Value(), strerror(errno), errno); write_error_code = write(child_err_fd, err.Value(), err.Length()); _exit(1); }
float ClassAdCollection::GetClassAdRank(ClassAd* Ad, const MyString& RankExpr) { if (RankExpr.Length()==0) return 0.0; AttrList RankingAd; RankingAd.AssignExpr( ATTR_RANK, RankExpr.Value() ); float Rank; if (!RankingAd.EvalFloat(ATTR_RANK,Ad,Rank)) Rank=0.0; return Rank; }
// copy constructor // initializes this MyString to a deep copy of the original MyString::MyString(const MyString & original) { this->_capacity = original.CurrentCapacity(); this->_length = original.Length(); this->_string = new char[this->_capacity + 1]; strcpy(_string, original._cstr()); //strcpy_s(_string, _capacity + 1, original._cstr()); //_string[_length + 1] = '\0'; }
void addConstraint( const char *constraint ) { if ( global_constraint.Length() > 0 ) { global_constraint += " || ("; } else { global_constraint += "("; } global_constraint += constraint; global_constraint += ")"; }
// Find // Takes a myString argument // Returns the index (int) // where the argument MyString was found // in this MyString. If it is not found, then returns -1. int MyString::Find(const MyString & aMyString) const { // Get the furthest back that I need to check int maxLength = this->Length() - aMyString.Length(); // Check if the first character is equals // If so, check the rest of the characters // If not, move on for (int i = 0; i <= maxLength; i++) { if ((*this)[i] == aMyString[0]) { if (this->SubStr(i, aMyString.Length()) == aMyString) { return i; } } } return -1; }
static int read_fd(int sock_fd) { MyString err; int bytes; int flag; bytes = full_read(0, &flag, sizeof(flag)); if (bytes != sizeof(flag)) { if (bytes == -1) { err.sprintf("read error getting flag: %s", strerror(errno)); } else { err.sprintf("short read of flag: %d of %lu bytes", bytes, sizeof(flag)); } full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } int fd; if (flag) { fd = fdpass_recv(sock_fd); if (fd == -1) { err.sprintf("fdpass_recv failed\n"); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } } else { fd = open("/dev/null", O_RDONLY); if (fd == -1) { err.sprintf("error opening /dev/null: %s", strerror(errno)); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } } return fd; }
int operator==(const char *S1, const MyString& S2) { if ((!S2.Data || !S2.Length()) && (!S1 || !strlen(S1))) { return 1; } if (!S2.Data || !S1) { return 0; } if (strcmp(S2.Data,S1)==0) { return 1; } return 0; }
bool Env::SetEnv( const MyString & var, const MyString & val ) { if( var.Length() == 0 ) { return false; } bool ret = (_envTable->insert( var, val ) == 0); ASSERT( ret ); #if defined(WIN32) m_sorted_varnames.erase(var.Value()); m_sorted_varnames.insert(var.Value()); #endif return true; }
void VMGahp::printAllReqsWithResult() { char *one_result = NULL; MyString output; m_result_list.rewind(); while( (one_result = m_result_list.next()) != NULL ) { output = one_result; output += "\n"; write_to_daemoncore_pipe(vmgahp_stdout_pipe, output.Value(), output.Length()); m_result_list.deleteCurrent(); } }