/* feed a command to the system to be started in background. No fancy argument processing, just pass to shell or equiv. Return 1 on success, 0 on failure. */ int start_background_program(const char *cmd) { char buf[1024]; # ifdef WIN32 int res; STARTUPINFO si; PROCESS_INFORMATION pi; strmcpy(buf,cmd,1023); buf[1023] = 0; memset((void *)&si,0,sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); res = CreateProcess(NULL,buf,NULL,NULL, 0,DETACHED_PROCESS,NULL,NULL,&si,&pi); if ( res ) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { warn("Failed to start process %s",cmd); } return res; # else strmcpy(buf,cmd,sizeof(buf)-strlen(buf)-1); strcat(buf," &"); # endif return ! system(buf); }
/** * ArgTokenize * * Tokenizes a string (i.e. splits it into arguments). ArgFree must * eventually be called on the returned string. * * @param Data the string */ const char *ArgTokenize(const char *Data) { char *Copy; size_t LengthData, Size; if (Data == NULL) { return NULL; } LengthData = strlen(Data); Size = LengthData + 2; Copy = (char *)malloc(Size); if (AllocFailed(Copy)) { return NULL; } strmcpy(Copy, Data, Size); Copy[LengthData + 1] = '\0'; for (unsigned int i = 0; i < LengthData; i++) { if (Copy[i] == ' ' && Copy[i + 1] != ' ' && Copy[i + 1] != '\0') { Copy[i] = '\0'; if (i > 0 && Copy[i + 1] == ':') { break; } } } return Copy; }
/*-------------------------------------------------------------------------*/ int make_dir(char *path) { int i; char tmp_path1[MAXPATH], tmp_path2[MAXPATH], length, mkdir_error; if (path[0] == '\0') { return -1; } strmcpy(tmp_path1, path, sizeof(tmp_path1)); cat_separator(tmp_path1); length = strlen(tmp_path1); strncpy(tmp_path2, tmp_path1, 3); i = 3; while (i < length) { if (tmp_path1[i] == '\\') { tmp_path2[i] = '\0'; if (!dir_exists(tmp_path2)) { mkdir_error = mkdir(tmp_path2); if (mkdir_error) { path[i] = '\0'; return mkdir_error; } } } tmp_path2[i] = tmp_path1[i]; i++; } return 0; }
void serversay(int save, int from_server, const char *format, ...) { Window *old_target_window = target_window; char servername[200]; int len = 0; char *out = NULL; if (get_int_var(OV_VAR)) target_window = get_window_by_name("OPER_VIEW"); if (window_display && format) { va_list args; va_start (args, format); vsnprintf(putbuf, LARGE_BIG_BUFFER_SIZE, format, args); va_end(args); strmcpy(servername, convert_output_format(get_string_var(SERVER_PROMPT_VAR), "%s", ov_server(from_server)?ov_server(from_server):empty_string), 79); len = strlen(putbuf); out = alloca(strlen(servername)+len+5); len = strlen(servername); strcpy(out, servername); out[len] = ' '; out[len+1] = 0; strcat(out, putbuf); if (*out) put_echo(out); } target_window = old_target_window; if (save && out) add_last_type(&last_servermsg[0], MAX_LAST_MSG, NULL, NULL, NULL, out); }
/* This windows version is loosely based on the example Creating a Child Process with Redirected Input and Output from the MSDN Library. See that example for all the comments explaining what's going on. In fact it's (a) easier than that, since instead of saving, setting and inheriting handles, we can put the pipes into the startup info of the CreateProcess call. (Thanks to somebody on Usenet, no thanks to Microsoft!); (b) harder, because we need to pass back C-style file descriptors, not Windows handles. Hence the mystic call to _open_osfhandle. */ int start_background_program_with_io(const char *cmd,int *childin, int *childout) { int res; char buf[1024]; STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES sa; HANDLE tochildr, tochildw, tochildw2, fromchildr, fromchildr2, fromchildw; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; if ( ! CreatePipe(&fromchildr,&fromchildw,&sa,0 ) ) { perror("couldn't create pipe"); return 0; } DuplicateHandle(GetCurrentProcess(), fromchildr,GetCurrentProcess(),&fromchildr2,0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(fromchildr); if ( ! CreatePipe(&tochildr,&tochildw,&sa,0 ) ) { perror("couldn't create pipe"); return 0; } DuplicateHandle(GetCurrentProcess(), tochildw,GetCurrentProcess(),&tochildw2,0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(tochildw); strmcpy(buf,cmd,1023); buf[1023] = 0; memset((void *)&si,0,sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESTDHANDLES; si.hStdOutput = fromchildw; si.hStdInput = tochildr; si.hStdError = 0; res = CreateProcess(NULL,buf,NULL,NULL, TRUE,DETACHED_PROCESS,NULL,NULL,&si,&pi); if ( res ) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { warn("Failed to start process %s",cmd); } /* I think the mingw has the wrong type for _open_osfhandle ? */ *childin = _open_osfhandle((int)tochildw2,_O_WRONLY); *childout = _open_osfhandle((int)fromchildr2,_O_RDONLY); /* do we, as in unix, close our versions of the handles we don't want? */ if ( 1 ) { CloseHandle(tochildr); CloseHandle(fromchildw); } return res; }
/** * GetChannelModes * * Returns the channel's modes. */ RESULT<const char *> CChannel::GetChannelModes(void) { int i; size_t Size; char *NewTempModes; char ModeString[2]; int ModeType; if (m_TempModes != NULL) { RETURN(const char *, m_TempModes); } Size = m_Modes.GetLength() + 1024; m_TempModes = (char *)malloc(Size); if (AllocFailed(m_TempModes)) { THROW(const char *, Generic_OutOfMemory, "malloc() failed."); } strmcpy(m_TempModes, "+", Size); for (i = 0; i < m_Modes.GetLength(); i++) { ModeType = GetOwner()->RequiresParameter(m_Modes[i].Mode); if (m_Modes[i].Mode != '\0' && ModeType != 3) { ModeString[0] = m_Modes[i].Mode; ModeString[1] = '\0'; strmcat(m_TempModes, ModeString, Size); } } for (i = 0; i < m_Modes.GetLength(); i++) { ModeType = GetOwner()->RequiresParameter(m_Modes[i].Mode); if (m_Modes[i].Mode != '\0' && m_Modes[i].Parameter && ModeType != 3) { strmcat(m_TempModes, " ", Size); if (strlen(m_TempModes) + strlen(m_Modes[i].Parameter) > Size) { Size += strlen(m_Modes[i].Parameter) + 1024; NewTempModes = (char *)realloc(m_TempModes, Size); if (AllocFailed(NewTempModes)) { free(m_TempModes); m_TempModes = NULL; THROW(const char *, Generic_OutOfMemory, "urealloc() failed."); } m_TempModes = NewTempModes; } strmcat(m_TempModes, m_Modes[i].Parameter, Size); }
string substr(const char *src, unsigned start, unsigned length) { string dest; if(length == ~0u) { //copy entire string dest.reserve(strlen(src + start) + 1); strcpy(dest(), src + start); } else { //copy partial string dest.reserve(length + 1); strmcpy(dest(), src + start, length + 1); } return dest; }
/* this function takes a string and parses it as an address. It returns 0 for an Internet address, 1 for a Unix address. For Internet addresses, the host name and port are placed in the given variables (the string had better be long enough); for Unix, the file name is copied to the given variable. */ static int parse_address(const char *address, char *ret_host, unsigned short *ret_port, char *ret_file, size_t n) { if ( strchr(address,':') ) { /* grrr */ if ( address[0] == ':' ) { strcpy(ret_host,"localhost"); sscanf(address,":%hu",ret_port); } else { sscanf(address,"%[^:]:%hu",ret_host,ret_port); } return 0; } else { if ( ret_file) strmcpy(ret_file,address,n); return 1; } }
serializer System::serialize() { serializer s(serialize_size); unsigned signature = 0x31545342, version = Info::SerializerVersion; char hash[64], description[512], profile[16]; memcpy(&hash, (const char*)cartridge.sha256(), 64); memset(&description, 0, sizeof description); memset(&profile, 0, sizeof profile); strmcpy(profile, Info::Profile, sizeof profile); s.integer(signature); s.integer(version); s.array(hash); s.array(description); s.array(profile); serialize_all(s); return s; }
char *ov_server(int server) { char *c; char *d; static char tmpstr[61]; char *string = get_server_itsname(server); if (!string || !*string) string = get_server_name(server); if (!string || !*string) return empty_string; strmcpy(tmpstr, string, 60); if (!(c = strrchr(tmpstr,'.'))) return(string); *c = 0; if (!(d = strrchr(tmpstr, '.'))) d = ++c; /* Extract domain */ d++; return(d); }
void main() { char s[80], t[80]; int m; int repeat, ri; void strmcpy(char *s, char *t, int m); scanf("%d", &repeat); getchar(); for(ri = 1; ri <= repeat; ri++){ gets(t); scanf("%d", &m); getchar(); if(strlen(t) < m) printf("error input"); else{ strmcpy(s, t, m); puts(s); } } }
/*-------------------------------------------------------------------------*/ void build_filename(char *dest_filename, const char *src_filename, const char *filepattern) { char drive[MAXDRIVE], dir[MAXDIR], filename_file[MAXFILE], filename_ext[MAXEXT], filepattern_file[MAXFILE], filepattern_ext[MAXEXT], tmp_filename[MAXFILE], tmp_ext[MAXEXT]; _splitpath(src_filename, drive, dir, filename_file, filename_ext); _splitpath(filepattern, drive, dir, filepattern_file, filepattern_ext); build_name(tmp_filename, filename_file, filepattern_file); build_name(tmp_ext, filename_ext, filepattern_ext); strmcpy(dest_filename, drive, MAXPATH); strmcat(dest_filename, dir, MAXPATH); strmcat(dest_filename, tmp_filename, MAXPATH); strmcat(dest_filename, tmp_ext, MAXPATH); }
/** * ArgTokenize2 * * Tokenizes a string and returns it. * * @param String the string */ tokendata_t ArgTokenize2(const char *String) { tokendata_t tokens; register unsigned int a = 1; size_t Len = min(strlen(String), sizeof(tokens.String) - 1); memset(tokens.String, 0, sizeof(tokens.String)); strmcpy(tokens.String, String, sizeof(tokens.String)); tokens.Pointers[0] = 0; for (unsigned int i = 0; i < Len; i++) { if (String[i] == ' ' && String[i + 1] != ' ') { if (String[i + 1] == '\0') { tokens.String[i] = '\0'; continue; } tokens.Pointers[a] = i + 1; tokens.String[i] = '\0'; a++; if (a >= 32) { break; } if (String[i + 1] == ':') { tokens.Pointers[a - 1]++; break; } } } tokens.Count = a; return tokens; }
/** * SaltFromHash * * Returns the salt value for a hash (or NULL if there is none). * * @param Hash the hash value */ const char *SaltFromHash(const char *Hash) { static char *Salt = NULL; const char *HashSign; HashSign = strchr(Hash, '$'); if (HashSign == NULL) { return NULL; } free(Salt); Salt = (char *)malloc(HashSign - Hash + 1); if (AllocFailed(Salt)) { g_Bouncer->Fatal(); } strmcpy(Salt, Hash, HashSign - Hash + 1); return Salt; }
void ui_add_console_line(const char* txt) { strmcpy(console_scrollback[console_scrollback_pos], txt, MAX_CONSOLE_INPUT); console_scrollback_pos = (console_scrollback_pos + 1) % CONSOLE_SCROLLBACK; printf("> %s\n", txt); }
///////////////////////////////////////////////////////////////////////////////////// // Print out full alignment in HHR format ///////////////////////////////////////////////////////////////////////////////////// void FullAlignment::PrintHHR(std::stringstream& out, Hit& hit, const char showconf, const char showcons, const char showdssp, const char showpred, const int aliwidth, const int maxseq) { const int NLEN = 14; //Length of name field in front of multiple alignment int h = 0; //counts position (column) in alignment int hh = 0; //points to column at start of present output block of alignment int k; //counts sequences in query and template short unsigned int* lq = new short unsigned int[maxseq]; // lq[k] counts index of residue from query sequence k to be printed next; short unsigned int* lt = new short unsigned int[maxseq]; // lt[k] counts index of residue from template sequence k to be printed next; char namestr[NAMELEN]; //name of sequence int iq = hit.i1; // match state counter for query HMM (displayed in consensus line) int jt = hit.j1; // match state counter for template HMM (displayed in consensus line) for (k = 0; k < qa->n; k++) lq[k] = qa->l[k][hit.i1]; for (k = 0; k < ta->n; k++) lt[k] = ta->l[k][hit.j1]; char line[LINELEN]; while (hh < ta->pos - 1) // print alignment block { // Print query secondary structure sequences for (k = 0; k < qa->n; k++) { if (!(k == qa->nss_dssp || k == qa->nsa_dssp || k == qa->nss_pred || k == qa->nss_conf)) continue; if (k == qa->nsa_dssp) continue; if (k == qa->nss_dssp && !showdssp) continue; if ((k == qa->nss_pred || k == qa->nss_conf) && !showpred) continue; if (k == qa->nss_conf && !showconf) continue; strmcpy(namestr, qa->sname[k], NAMELEN - 1); strcut(namestr); sprintf(line, "Q %-*.*s ", NLEN, NLEN, namestr); out << line; if (k == qa->nss_pred && qa->nss_conf >= 0) for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) { sprintf(line, "%1c", qa->s[qa->nss_conf][h] <= '6' && qa->s[qa->nss_conf][h] >= '0' ? qa->s[k][h] + 32 : qa->s[k][h]); out << line; } else for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) { sprintf(line, "%1c", qa->s[k][h]); out << line; } out << std::endl; } // Print query sequences for (k = 0; k < qa->n; k++) { if (k == qa->nss_dssp || k == qa->nsa_dssp || k == qa->nss_pred || k == qa->nss_conf || k == qa->ncons) continue; strmcpy(namestr, qa->sname[k], NAMELEN - 1); strcut(namestr); sprintf(line, "Q %-*.*s %4i ", NLEN, NLEN, namestr, lq[k]); out << line; for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) { sprintf(line, "%1c", qa->s[k][h]); out << line; lq[k] += WordChr(qa->s[k][h]); } //WordChr() returns 1 if a-z or A-Z; 0 otherwise sprintf(line, " %4i (%i)\n", lq[k] - 1, qa->l[k][qa->L + 1]); out << line; } // Print query consensus sequence if (showcons && qa->ncons >= 0) { k = qa->ncons; strmcpy(namestr, qa->sname[k], NAMELEN - 1); strcut(namestr); sprintf(line, "Q %-*.*s %4i ", NLEN, NLEN, namestr, iq); out << line; for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) { if (qa->s[k][h] == 'x') qa->s[k][h] = '~'; if (qa->s[k][h] != '-' && qa->s[k][h] != '.') iq++; sprintf(line, "%1c", qa->s[k][h]); out << line; } sprintf(line, " %4i (%i)\n", iq - 1, qa->L); out << line; } // Print symbols representing the score sprintf(line, " %*.*s ", NLEN, NLEN, " "); out << line; for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) { sprintf(line, "%1c", symbol[h]); out << line; } out << std::endl; // Print template consensus sequence if (showcons && ta->ncons >= 0) { k = ta->ncons; strmcpy(namestr, ta->sname[k], NAMELEN - 1); strcut(namestr); sprintf(line, "T %-*.*s %4i ", NLEN, NLEN, namestr, jt); out << line; for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) { if (ta->s[k][h] == 'x') ta->s[k][h] = '~'; if (ta->s[k][h] != '-' && ta->s[k][h] != '.') jt++; sprintf(line, "%1c", ta->s[k][h]); out << line; } sprintf(line, " %4i (%i)\n", jt - 1, ta->L); out << line; } // Print template sequences for (k = 0; k < ta->n; k++) { if (k == ta->nss_dssp || k == ta->nsa_dssp || k == ta->nss_pred || k == ta->nss_conf || k == ta->ncons) continue; strmcpy(namestr, ta->sname[k], NAMELEN - 1); strcut(namestr); sprintf(line, "T %-*.*s %4i ", NLEN, NLEN, namestr, lt[k]); out << line; for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) { sprintf(line, "%1c", ta->s[k][h]); out << line; lt[k] += WordChr(ta->s[k][h]); } //WordChr() returns 1 if a-z or A-Z; 0 otherwise sprintf(line, " %4i (%i)\n", lt[k] - 1, ta->l[k][ta->L + 1]); out << line; } // Print template secondary structure sequences for (k = 0; k < ta->n; k++) { if (!(k == ta->nss_dssp || k == ta->nss_pred || k == ta->nss_conf)) continue; if (k == ta->nsa_dssp) continue; if (k == ta->nss_dssp && !showdssp) continue; if ((k == ta->nss_pred || k == ta->nss_conf) && !showpred) continue; if (k == ta->nss_conf && !showconf) continue; strmcpy(namestr, ta->sname[k], NAMELEN - 1); strcut(namestr); sprintf(line, "T %-*.*s ", NLEN, NLEN, namestr); out << line; if (k == ta->nss_pred && ta->nss_conf >= 0) for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) { sprintf(line, "%1c", ta->s[ta->nss_conf][h] <= '6' && ta->s[ta->nss_conf][h] >= '0' ? ta->s[k][h] + 32 : ta->s[k][h]); out << line; } else for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) { sprintf(line, "%1c", ta->s[k][h]); out << line; } out << std::endl; } // Print alignment confidence values (posterior probabilities)? if (posterior[0] != '\0') { sprintf(line, "%-*.*s ", NLEN, NLEN, "Confidence "); out << line; for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) { sprintf(line, "%1c", posterior[h]); out << line; } out << std::endl; } hh = h; out << std::endl << std::endl; } delete [] lq; delete [] lt; }
extern char *BX_extract2(const char *start, int firstword, int lastword) { /* If firstword or lastword is negative, then we take those values from the end of the string */ char *mark; char *mark2; char *booya = NULL; /* If firstword is EOS, then the user wants the last word */ if (firstword == EOS) { mark = (char *)start + strlen(start); mark = move_word_rel(start, &mark, -1); #ifndef NO_CHEATING /* * Really. the only case where firstword == EOS is * when the user wants $~, in which case we really * dont need to do all the following crud. Of * course, if there ever comes a time that the * user would want to start from the EOS (when??) * we couldnt make this assumption. */ return m_strdup(mark); #endif } /* SOS is used when the user does $-n, all leading spaces * are retained */ else if (firstword == SOS) mark = (char *)start; /* If the firstword is positive, move to that word */ else if (firstword >= 0) { move_to_abs_word(start, &mark, firstword); if (!*mark) return m_strdup(empty_string); } /* Otherwise, move to the firstwords from the end */ else { mark = (char *)start + strlen((char *)start); move_word_rel(start, &mark, firstword); } #ifndef STRIP_EXTRANEOUS_SPACES /* IF the user did something like this: * $n- $n-m * then include any leading spaces on the 'n'th word. * this is the "old" behavior that we are attempting * to emulate here. */ #ifndef NO_CHEATING if (lastword == EOS || (lastword > firstword)) #else if (((lastword == EOS) && (firstword != EOS)) || (lastword > firstword)) #endif { while (mark > start && my_isspace(mark[-1])) mark--; if (mark > start) mark++; } #endif /* * When we find the last word, we need to move to the * END of the word, so that word 3 to 3, would include * all of word 3, so we sindex to the space after the word */ if (lastword == EOS) mark2 = mark + strlen(mark); else { if (lastword >= 0) move_to_abs_word(start, &mark2, lastword+1); else { mark2 = (char *)start + strlen(start); move_word_rel(start, &mark2, lastword); } while (mark2 > start && my_isspace(mark2[-1])) mark2--; } /* * If the end is before the string, then there is nothing * to extract (this is perfectly legal, btw) */ if (mark2 < mark) booya = m_strdup(empty_string); else { #if 0 /* Otherwise, copy off the string we just isolated */ char tmp; tmp = *mark2; *mark2 = '\0'; booya = m_strdup(mark); *mark2 = tmp; #endif booya = new_malloc(mark2 - mark + 1); strmcpy(booya, mark, (mark2 - mark)); } return booya; }
/*-------------------------------------------------------------------------*/ static int CopyTree(const char *src_pathname, const char *src_filename, const char *dest_pathname, const char *dest_filename) { char filepattern[MAXPATH], new_src_pathname[MAXPATH], new_dest_pathname[MAXPATH], src_path_filename[MAXPATH], dest_path_filename[MAXPATH], tmp_filename[MAXFILE + MAXEXT], tmp_pathname[MAXPATH]; struct ffblk fileblock; int fileattrib, done; /* copy files in subdirectories */ strmcpy(filepattern, src_pathname, sizeof(filepattern)); strmcat(filepattern, src_filename, sizeof(filepattern)); done = findfirst(filepattern, &fileblock, FA_DIREC); while (!done) { if (fileblock.ff_attrib == FA_DIREC && strcmp(fileblock.ff_name, ".") != 0 && strcmp(fileblock.ff_name, "..") != 0) { /* build source pathname */ strmcpy(new_src_pathname, src_pathname, sizeof(new_src_pathname)); strmcat(new_src_pathname, fileblock.ff_name, sizeof(new_src_pathname)); strmcat(new_src_pathname, DIR_SEPARATOR, sizeof(new_src_pathname)); /* build destination pathname */ strmcpy(new_dest_pathname, dest_pathname, sizeof(new_dest_pathname)); strmcat(new_dest_pathname, fileblock.ff_name, sizeof(new_dest_pathname)); strmcat(new_dest_pathname, DIR_SEPARATOR, sizeof(new_dest_pathname)); if (!CopyTree(new_src_pathname, "*.*", new_dest_pathname, "*.*")) return 0; } done = findnext(&fileblock); } fileattrib = FA_RDONLY+FA_ARCH+FA_HIDDEN+FA_SYSTEM; /* find first source file */ strmcpy(filepattern, src_pathname, sizeof(filepattern)); strmcat(filepattern, src_filename, sizeof(filepattern)); done = findfirst(filepattern, &fileblock, fileattrib); /* check if destination directory must be created */ if (!dir_exists(dest_pathname)) { strmcpy(tmp_pathname, dest_pathname, sizeof(tmp_pathname)); if (makedir(tmp_pathname) != 0) { #ifdef USE_KITTEN error(1,28,"Unable to create directory"); #else error("Unable to create directory"); #endif return 0; } } /* copy files */ while (!done) { /* build source filename including path */ strmcpy(src_path_filename, src_pathname, sizeof(src_path_filename)); strmcat(src_path_filename, fileblock.ff_name, sizeof(src_path_filename)); /* build destination filename including path */ strmcpy(dest_path_filename, dest_pathname, sizeof(dest_path_filename)); build_filename(tmp_filename, fileblock.ff_name, dest_filename); strmcat(dest_path_filename, tmp_filename, sizeof(dest_path_filename)); if (!xcopy_file(src_path_filename, dest_path_filename)) return 0; done = findnext(&fileblock); } return 1; }
static char *parse_args (char *argv[], int argc, char **envp) { int ac; int add_servers = 0; char *channel = NULL; char *ptr; *nickname = 0; *password = 0; if ((ptr = getenv("NAPNICK"))) strmcpy(nickname, ptr, NICKNAME_LEN); if ((ptr = getenv("NAPPASS"))) strmcpy(password, ptr, NICKNAME_LEN); if ((ptr = getenv("NAP_HOST")) || (ptr = getenv("NAPHOST"))) malloc_strcpy(&LocalHostName, ptr); for ( ac = 1; ac < argc; ac++ ) { if (argv[ac][0] == '-') { switch (argv[ac][1]) { case 'r': /* Load list of servers from this file */ { char *what = empty_string; if (argv[ac][2]) what = &argv[ac][2]; else if (argv[ac+1] && argv[ac+1][0] != '-') { what = argv[ac+1]; ac++; } else fprintf(stderr, "Missing argumenT to -r\n"); if (*what) { add_servers = 1; malloc_strcpy(&ircservers_file, what); } break; } case 'a': /* add server, not replace */ { add_servers = 1; if (argv[ac][2]) fprintf(stderr, "Ignoring junk after -a\n"); break; } case 'H': { char *what = empty_string; if (argv[ac][2]) what = &(argv[ac][2]); else if (argv[ac+1] && argv[ac+1][0] != '-') { what = argv[ac+1]; ac++; } else { fprintf(stderr, "Specify a hostname\n"); exit(1); } malloc_strcpy(&LocalHostName, what); break; } case 'S': { if (argv[ac][2]) { char *what; what = &argv[ac][2]; starting_server = my_atol(what); } else { ac++; starting_server = my_atol(argv[ac]); } break; } case 'n': { char *what = empty_string; if (argv[ac][2]) what = &(argv[ac][2]); else if (argv[ac+1] && argv[ac+1][0] != '-') { what = argv[ac+1]; ac++; } else { fprintf(stderr,"Missing argument for -n\n"); exit(1); } strmcpy(nickname, what, NICKNAME_LEN); break; } case 'p': { char *pass = NULL; if ((pass = getpass("Enter Password :"******"%s %s\n", nap_version, internal_version); exit(1); #if defined(WINNT) || defined(EMX) case 's': setup_autoexec(); exit(1); #endif default: fprintf(stderr, "Unknown flag: %s\n",argv[ac]); case 'h': fprintf(stderr, "%s", switch_help); #if defined(WINNT) || defined(EMX) fprintf(stderr, "%s", switch_help_w); #endif exit(1); } /* End of switch */ } else { if (!strchr(argv[ac], '.')) strmcpy(nickname, argv[ac], NICKNAME_LEN); else build_server_list(argv[ac]); } } if ((ptr = getenv("NAPLIB"))) irc_lib = m_opendup("/", ptr, "/", NULL); else { char *s; if ((s = expand_twiddle(NAPLIB))) irc_lib = s; else malloc_strcpy(&irc_lib, NAPLIB); } if ((ptr = getenv("NAPPATH"))) malloc_strcpy(&irc_path, ptr); else { #ifdef NAPPATH malloc_strcpy(&irc_path, NAPPATH); #else #ifdef WINNT malloc_strcpy(&irc_path, ".:~/TekNap:"); #else malloc_strcpy(&irc_path, ".:~/.TekNap:"); #endif irc_path = m_opendup(irc_lib, "/", "script", NULL); #endif } if (LocalHostName) { struct hostent *hp; printf("Your hostname appears to be [%s]\n", LocalHostName); memset((void *)&LocalHostAddr, 0, sizeof(LocalHostAddr)); if ((hp = gethostbyname(LocalHostName))) memcpy((void *)&LocalHostAddr.sin_addr, hp->h_addr, sizeof(struct in_addr)); } if (!check_nickname(nickname)) { fprintf(stderr, "\n Invalid Nickname\n"); exit(1); } set_string_var(LOAD_PATH_VAR, irc_path); new_free(&irc_path); if ((ptr = getenv("HOME"))) malloc_strcpy(&my_path, ptr); if (!my_path || !*my_path) #ifdef WINNT { malloc_strcpy(&my_path, "//c/TekNap/"); bsd_setenv("HOME", "//c/TekNap", 1); } if (access("//c/TekNap", F_OK) != 0) { fprintf(stderr, "Directory doesn't exist, creating //c/TekNap\n"); mkdir("//c/TekNap", S_IWUSR|S_IRUSR|S_IXUSR); } #else malloc_strcpy(&my_path, "/"); #endif #if defined(WINNT) || defined(__EMX__) convert_unix(my_path); #endif if (!bircrc_file) malloc_sprintf(&bircrc_file, "%s%s", my_path, IRCRC_NAME); if ((ptr = getenv("NAPPORT"))) nap_port = my_atol(ptr); if ((ptr = getenv("NAPSERVER"))) build_server_list(ptr); #ifdef DEFAULT_SERVER { if (!read_server_list()) { ptr = LOCAL_COPY(DEFAULT_SERVER); build_server_list(ptr); } } #endif return (channel); }
/** * ParseLineArgV * * Parses and processes a line which was sent by the server. * * @param argc number of tokens * @param argv the tokens */ bool CIRCConnection::ParseLineArgV(int argc, const char **argv) { CChannel *Channel; CClientConnection *Client; m_LastResponse = g_CurrentTime; if (argc < 2) { return true; } const char *Reply = argv[0]; const char *Raw = argv[1]; char *Nick = ::NickFromHostmask(Reply); int iRaw = atoi(Raw); bool b_Me = false; if (m_CurrentNick != NULL && Nick != NULL && strcasecmp(Nick, m_CurrentNick) == 0) { b_Me = true; } free(Nick); Client = GetOwner()->GetClientConnectionMultiplexer(); // HASH values CHashCompare hashRaw(argv[1]); static CHashCompare hashPrivmsg("PRIVMSG"); static CHashCompare hashNotice("NOTICE"); static CHashCompare hashJoin("JOIN"); static CHashCompare hashPart("PART"); static CHashCompare hashKick("KICK"); static CHashCompare hashNick("NICK"); static CHashCompare hashQuit("QUIT"); static CHashCompare hashMode("MODE"); static CHashCompare hashTopic("TOPIC"); static CHashCompare hashPong("PONG"); // END of HASH values if (argc > 3 && iRaw == 433) { bool ReturnValue = ModuleEvent(argc, argv); if (ReturnValue) { if (GetCurrentNick() == NULL) { WriteLine("NICK :%s_", argv[3]); } if (m_NickCatchTimer == NULL) { m_NickCatchTimer = new CTimer(30, false, NickCatchTimer, this); } } return ReturnValue; } else if (argc > 3 && hashRaw == hashPrivmsg && Client == NULL) { const char *Host; const char *Dest = argv[2]; char *Nick = ::NickFromHostmask(Reply); Channel = GetChannel(Dest); if (Channel != NULL) { CNick *User = Channel->GetNames()->Get(Nick); if (User != NULL) { User->SetIdleSince(g_CurrentTime); } Channel->AddBacklogLine(argv[0], argv[3]); } if (!ModuleEvent(argc, argv)) { free(Nick); return false; } /* don't log ctcp requests */ if (argv[3][0] != '\1' && argv[3][strlen(argv[3]) - 1] != '\1' && Dest != NULL && Nick != NULL && m_CurrentNick != NULL && strcasecmp(Dest, m_CurrentNick) == 0 && strcasecmp(Nick, m_CurrentNick) != 0) { char *Dup; char *Delim; Dup = strdup(Reply); if (AllocFailed(Dup)) { free(Nick); return true; } Delim = strchr(Dup, '!'); if (Delim != NULL) { *Delim = '\0'; Host = Delim + 1; } GetOwner()->Log("%s (%s): %s", Dup, Delim ? Host : "<unknown host>", argv[3]); free(Dup); } free(Nick); UpdateHostHelper(Reply); return true; } else if (argc > 3 && hashRaw == hashPrivmsg && Client != NULL) { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->AddBacklogLine(argv[0], argv[3]); } } else if (argc > 3 && hashRaw == hashNotice && Client == NULL) { const char *Dest = argv[2]; char *Nick; if (!ModuleEvent(argc, argv)) { return false; } Nick = ::NickFromHostmask(Reply); /* don't log ctcp replies */ if (argv[3][0] != '\1' && argv[3][strlen(argv[3]) - 1] != '\1' && Dest != NULL && Nick != NULL && m_CurrentNick != NULL && strcasecmp(Dest, m_CurrentNick) == 0 && strcasecmp(Nick, m_CurrentNick) != 0) { GetOwner()->Log("%s (notice): %s", Reply, argv[3]); } free(Nick); return true; } else if (argc > 2 && hashRaw == hashJoin) { if (b_Me) { AddChannel(argv[2]); /* GetOwner() can be NULL if AddChannel failed */ if (GetOwner() != NULL && Client == NULL) { WriteLine("MODE %s", argv[2]); } } Channel = GetChannel(argv[2]); if (Channel != NULL) { Nick = NickFromHostmask(Reply); if (AllocFailed(Nick)) { return false; } Channel->AddUser(Nick, '\0'); free(Nick); } UpdateHostHelper(Reply); } else if (argc > 2 && hashRaw == hashPart) { bool bRet = ModuleEvent(argc, argv); if (b_Me) { RemoveChannel(argv[2]); } else { Channel = GetChannel(argv[2]); if (Channel != NULL) { Nick = ::NickFromHostmask(Reply); if (AllocFailed(Nick)) { return false; } Channel->RemoveUser(Nick); free(Nick); } } UpdateHostHelper(Reply); return bRet; } else if (argc > 3 && hashRaw == hashKick) { bool bRet = ModuleEvent(argc, argv); if (m_CurrentNick != NULL && strcasecmp(argv[3], m_CurrentNick) == 0) { RemoveChannel(argv[2]); if (Client == NULL) { char *Dup = strdup(Reply); if (AllocFailed(Dup)) { return bRet; } char *Delim = strchr(Dup, '!'); const char *Host = NULL; if (Delim) { *Delim = '\0'; Host = Delim + 1; } GetOwner()->Log("%s (%s) kicked you from %s (%s)", Dup, Delim ? Host : "<unknown host>", argv[2], argc > 4 ? argv[4] : ""); free(Dup); } } else { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->RemoveUser(argv[3]); } } UpdateHostHelper(Reply); return bRet; } else if (argc > 2 && iRaw == 1) { if (Client != NULL) { if (strcmp(Client->GetNick(), argv[2]) != 0) { Client->WriteLine(":%s!%s NICK :%s", Client->GetNick(), m_Site ? m_Site : "*****@*****.**", argv[2]); } } free(m_CurrentNick); m_CurrentNick = strdup(argv[2]); free(m_Server); m_Server = strdup(Reply); } else if (argc > 2 && hashRaw == hashNick) { if (b_Me) { free(m_CurrentNick); m_CurrentNick = strdup(argv[2]); } Nick = NickFromHostmask(argv[0]); int i = 0; if (!b_Me && GetOwner()->GetClientConnectionMultiplexer() == NULL) { const char *AwayNick = GetOwner()->GetAwayNick(); if (AwayNick != NULL && strcasecmp(AwayNick, Nick) == 0) { WriteLine("NICK %s", AwayNick); } } while (hash_t<CChannel *> *ChannelHash = m_Channels->Iterate(i++)) { ChannelHash->Value->RenameUser(Nick, argv[2]); } free(Nick); } else if (argc > 1 && hashRaw == hashQuit) { bool bRet = ModuleEvent(argc, argv); Nick = NickFromHostmask(argv[0]); int i = 0; while (hash_t<CChannel *> *ChannelHash = m_Channels->Iterate(i++)) { ChannelHash->Value->RemoveUser(Nick); } free(Nick); return bRet; } else if (argc > 1 && (iRaw == 422 || iRaw == 376)) { int DelayJoin = GetOwner()->GetDelayJoin(); if (m_State != State_Connected) { const CVector<CModule *> *Modules = g_Bouncer->GetModules(); for (int i = 0; i < Modules->GetLength(); i++) { (*Modules)[i]->ServerLogon(GetOwner()->GetUsername()); } const char *ClientNick; if (Client != NULL) { ClientNick = Client->GetNick(); if (strcmp(m_CurrentNick, ClientNick) != 0) { Client->ChangeNick(m_CurrentNick); } } GetOwner()->Log("You were successfully connected to an IRC server."); g_Bouncer->Log("User %s connected to an IRC server.", GetOwner()->GetUsername()); } if (DelayJoin == 1) { m_DelayJoinTimer = g_Bouncer->CreateTimer(5, false, DelayJoinTimer, this); } else if (DelayJoin == 0) { JoinChannels(); } if (Client == NULL) { bool AppendTS = (GetOwner()->GetConfig()->ReadInteger("user.ts") != 0); const char *AwayReason = GetOwner()->GetAwayText(); if (AwayReason != NULL) { WriteLine(AppendTS ? "AWAY :%s (Away since the dawn of time)" : "AWAY :%s", AwayReason); } } const char *AutoModes = GetOwner()->GetAutoModes(); const char *DropModes = GetOwner()->GetDropModes(); if (AutoModes != NULL) { WriteLine("MODE %s +%s", GetCurrentNick(), AutoModes); } if (DropModes != NULL && Client == NULL) { WriteLine("MODE %s -%s", GetCurrentNick(), DropModes); } m_State = State_Connected; } else if (argc > 1 && strcasecmp(Reply, "ERROR") == 0) { if (strstr(Raw, "throttle") != NULL) { GetOwner()->ScheduleReconnect(120); } else { GetOwner()->ScheduleReconnect(5); } if (GetCurrentNick() != NULL && GetSite() != NULL) { g_Bouncer->LogUser(GetUser(), "Error received for user %s [%s!%s]: %s", GetOwner()->GetUsername(), GetCurrentNick(), GetSite(), argv[1]); } else { g_Bouncer->LogUser(GetUser(), "Error received for user %s: %s", GetOwner()->GetUsername(), argv[1]); } } else if (argc > 3 && iRaw == 465) { if (GetCurrentNick() != NULL && GetSite() != NULL) { g_Bouncer->LogUser(GetUser(), "G/K-line reason for user %s [%s!%s]: %s", GetOwner()->GetUsername(), GetCurrentNick(), GetSite(), argv[3]); } else { g_Bouncer->LogUser(GetUser(), "G/K-line reason for user %s: %s", GetOwner()->GetUsername(), argv[3]); } } else if (argc > 5 && iRaw == 351) { free(m_ServerVersion); m_ServerVersion = strdup(argv[3]); free(m_ServerFeat); m_ServerFeat = strdup(argv[5]); } else if (argc > 3 && iRaw == 5) { for (int i = 3; i < argc - 1; i++) { char *Dup = strdup(argv[i]); if (AllocFailed(Dup)) { return false; } char *Eq = strchr(Dup, '='); if (strcasecmp(Dup, "NAMESX") == 0) { WriteLine("PROTOCTL NAMESX"); } char *Value; if (Eq) { *Eq = '\0'; Value = strdup(++Eq); } else { Value = strdup(""); } m_ISupport->Add(Dup, Value); free(Dup); } } else if (argc > 4 && iRaw == 324) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->ClearModes(); Channel->ParseModeChange(argv[0], argv[4], argc - 5, &argv[5]); Channel->SetModesValid(true); } } else if (argc > 3 && hashRaw == hashMode) { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->ParseModeChange(argv[0], argv[3], argc - 4, &argv[4]); } else if (strcmp(m_CurrentNick, argv[2]) == 0) { bool Flip = true, WasNull; const char *Modes = argv[3]; size_t Length = strlen(Modes) + 1; if (m_Usermodes != NULL) { Length += strlen(m_Usermodes); } WasNull = (m_Usermodes != NULL) ? false : true; m_Usermodes = (char *)realloc(m_Usermodes, Length); if (AllocFailed(m_Usermodes)) { return false; } if (WasNull) { m_Usermodes[0] = '\0'; } while (*Modes != '\0') { if (*Modes == '+') { Flip = true; } else if (*Modes == '-') { Flip = false; } else { if (Flip) { size_t Position = strlen(m_Usermodes); m_Usermodes[Position] = *Modes; m_Usermodes[Position + 1] = '\0'; } else { char *CurrentModes = m_Usermodes; size_t a = 0; while (*CurrentModes != '\0') { *CurrentModes = m_Usermodes[a]; if (*CurrentModes != *Modes) { CurrentModes++; } a++; } } } Modes++; } } UpdateHostHelper(Reply); } else if (argc > 4 && iRaw == 329) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetCreationTime(atoi(argv[4])); } } else if (argc > 4 && iRaw == 332) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetTopic(argv[4]); } } else if (argc > 5 && iRaw == 333) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetTopicNick(argv[4]); Channel->SetTopicStamp(atoi(argv[5])); } } else if (argc > 3 && iRaw == 331) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetNoTopic(); } } else if (argc > 3 && hashRaw == hashTopic) { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->SetTopic(argv[3]); Channel->SetTopicStamp(g_CurrentTime); Channel->SetTopicNick(argv[0]); } UpdateHostHelper(Reply); } else if (argc > 5 && iRaw == 353) { Channel = GetChannel(argv[4]); if (Channel != NULL) { const char *nicks; const char **nickv; nicks = ArgTokenize(argv[5]); if (AllocFailed(nicks)) { return false; } nickv = ArgToArray(nicks); if (AllocFailed(nickv)) { ArgFree(nicks); return false; } int nickc = ArgCount(nicks); for (int i = 0; i < nickc; i++) { char *Nick = strdup(nickv[i]); char *BaseNick = Nick; if (AllocFailed(Nick)) { ArgFree(nicks); return false; } StrTrim(Nick, ' '); while (IsNickPrefix(*Nick)) { Nick++; } char *Modes = NULL; if (BaseNick != Nick) { Modes = (char *)malloc(Nick - BaseNick + 1); if (!AllocFailed(Modes)) { strmcpy(Modes, BaseNick, Nick - BaseNick + 1); } } Channel->AddUser(Nick, Modes); free(BaseNick); free(Modes); } ArgFreeArray(nickv); ArgFree(nicks); } } else if (argc > 3 && iRaw == 366) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetHasNames(); } } else if (argc > 9 && iRaw == 352) { const char *Ident = argv[4]; const char *Host = argv[5]; const char *Server = argv[6]; const char *Nick = argv[7]; const char *Realname = argv[9]; char *Mask; int rc = asprintf(&Mask, "%s!%s@%s", Nick, Ident, Host); if (!RcFailed(rc)) { UpdateHostHelper(Mask); UpdateWhoHelper(Nick, Realname, Server); free(Mask); } } else if (argc > 6 && iRaw == 367) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->GetBanlist()->SetBan(argv[4], argv[5], atoi(argv[6])); } } else if (argc > 3 && iRaw == 368) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetHasBans(); } } else if (argc > 3 && iRaw == 396) { free(m_Site); m_Site = strdup(argv[3]); if (AllocFailed(m_Site)) {} } else if (argc > 3 && hashRaw == hashPong && m_Server != NULL && strcasecmp(argv[2], m_Server) == 0 && m_EatPong) { m_EatPong = false; return false; } else if (argc > 3 && iRaw == 421) { m_FloodControl->Unplug(); return false; } if (GetOwner() != NULL) { return ModuleEvent(argc, argv); } else { return true; } }
/* * extract is a simpler version of extract2, it is used when we dont * want special treatment of "firstword" if it is negative. This is * typically used by the word/list functions, which also dont care if * we strip out or leave in any whitespace, we just do what is the * fastest. */ extern char *BX_extract(char *start, int firstword, int lastword) { /* * firstword and lastword must be zero. If they are not, * then they are assumed to be invalid However, please note * that taking word set (-1,3) is valid and contains the * words 0, 1, 2, 3. But word set (-1, -1) is an empty_string. */ char *mark; char *mark2; char *booya = NULL; /* * before we do anything, we strip off leading and trailing * spaces. * * ITS OK TO TAKE OUT SPACES HERE, AS THE USER SHOULDNT EXPECT * THAT THE WORD FUNCTIONS WOULD RETAIN ANY SPACES. (That is * to say that since the word/list functions dont pay attention * to the whitespace anyhow, noone should have any problem with * those ops removing bothersome whitespace when needed.) */ while (my_isspace(*start)) start++; remove_trailing_spaces(start); if (firstword == EOS) { mark = start + strlen(start); mark = move_word_rel(start, &mark, -1); } /* If the firstword is positive, move to that word */ else if (firstword >= 0) move_to_abs_word(start, &mark, firstword); /* Its negative. Hold off right now. */ else mark = start; /* When we find the last word, we need to move to the END of the word, so that word 3 to 3, would include all of word 3, so we sindex to the space after the word */ /* EOS is a #define meaning "end of string" */ if (lastword == EOS) mark2 = start + strlen(start); else { if (lastword >= 0) move_to_abs_word(start, &mark2, lastword+1); else /* its negative -- thats not valid */ return m_strdup(empty_string); while (mark2 > start && my_isspace(mark2[-1])) mark2--; } /* Ok.. now if we get to here, then lastword is positive, so * we sanity check firstword. */ if (firstword < 0) firstword = 0; if (firstword > lastword) /* this works even if fw was < 0 */ return m_strdup(empty_string); /* If the end is before the string, then there is nothing * to extract (this is perfectly legal, btw) */ #if 0 booya = NULL; #endif if (mark2 < mark) return m_strdup(empty_string); booya = new_malloc(mark2 - mark + 1); strmcpy(booya, mark, (mark2 - mark)); #if 0 malloc_strcpy(&booya, empty_string); else {
///////////////////////////////////////////////////////////////////////////////////// //// MAIN PROGRAM ///////////////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { char* argv_conf[MAXOPT]; // Input arguments from .hhdefaults file (first=1: argv_conf[0] is not used) int argc_conf; // Number of arguments in argv_conf strcpy(par.infile, ""); strcpy(par.outfile, ""); strcpy(par.alnfile, ""); //Default parameter settings par.nseqdis = MAXSEQ - 1; // maximum number of sequences to be written par.showcons = 0; par.cons = 1; par.Ndiff = 0; par.max_seqid = 100; par.coverage = 0; par.pc_hhm_context_engine.pca = 0.0; // no amino acid pseudocounts par.pc_hhm_nocontext_a = 0.0; // no amino acid pseudocounts par.gapb = 0.0; // no transition pseudocounts // Make command line input globally available par.argv = argv; par.argc = argc; RemovePathAndExtension(program_name, argv[0]); // Enable changing verbose mode before defaults file and command line are processed int v = 2; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-def")) par.readdefaultsfile = 1; else if (strcmp(argv[i], "-v") == 0) { v = atoi(argv[i + 1]); } } par.v = Log::from_int(v); Log::reporting_level() = par.v; par.SetDefaultPaths(); // Read .hhdefaults file? if (par.readdefaultsfile) { // Process default otpions from .hhconfig file ReadDefaultsFile(argc_conf, argv_conf); ProcessArguments(argc_conf, argv_conf); } // Process command line options (they override defaults from .hhdefaults file) ProcessArguments(argc, argv); Alignment* qali = new Alignment(MAXSEQ, par.maxres); HMM* q = new HMM(MAXSEQDIS, par.maxres); //Create a HMM with maximum of par.maxres match states // q is only available after maxres is known, so we had to move this here for (int i = 1; i <= argc - 1; i++) { if (!strcmp(argv[i], "-name") && (i < argc - 1)) { strmcpy(q->name, argv[++i], NAMELEN - 1); //copy longname to name... strmcpy(q->longname, argv[i], DESCLEN - 1); //copy full name to longname } } // Check command line input and default values if (!*par.infile) { help(); HH_LOG(ERROR) << "Input file is missing!" << std::endl; exit(4); } // Get basename RemoveExtension(q->file, par.infile); //Get basename of infile (w/o extension): // Outfile not given? Name it basename.hhm if (!*par.outfile && !*par.alnfile) { RemoveExtension(par.outfile, par.infile); strcat(par.outfile, ".seq"); } // Prepare CS pseudocounts lib if (!par.nocontxt && *par.clusterfile) { InitializePseudocountsEngine(par, context_lib, crf, pc_hhm_context_engine, pc_hhm_context_mode, pc_prefilter_context_engine, pc_prefilter_context_mode); } // Set substitution matrix; adjust to query aa distribution if par.pcm==3 SetSubstitutionMatrix(par.matrix, pb, P, R, S, Sim); // Read input file (HMM, HHM, or alignment format), and add pseudocounts etc. char input_format = 0; ReadQueryFile(par, par.infile, input_format, par.wg, q, qali, pb, S, Sim); // Same code as in PrepareQueryHMM(par.infile,input_format,q,qali), except that we add SS prediction // Add Pseudocounts, if no HMMER input if (input_format == 0) { // Transform transition freqs to lin space if not already done q->AddTransitionPseudocounts(par.gapd, par.gape, par.gapf, par.gapg, par.gaph, par.gapi, par.gapb, par.gapb); // Comput substitution matrix pseudocounts if (par.nocontxt) { // Generate an amino acid frequency matrix from f[i][a] with full pseudocount admixture (tau=1) -> g[i][a] q->PreparePseudocounts(R); // Add amino acid pseudocounts to query: p[i][a] = (1-tau)*f[i][a] + tau*g[i][a] q->AddAminoAcidPseudocounts(par.pc_hhm_nocontext_mode, par.pc_hhm_nocontext_a, par.pc_hhm_nocontext_b, par.pc_hhm_nocontext_c); } else { // Add full context specific pseudocounts to query q->AddContextSpecificPseudocounts(pc_hhm_context_engine, pc_hhm_context_mode); } } else { q->AddAminoAcidPseudocounts(0, par.pc_hhm_nocontext_a, par.pc_hhm_nocontext_b, par.pc_hhm_nocontext_c); } q->CalculateAminoAcidBackground(pb); if (par.columnscore == 5 && !q->divided_by_local_bg_freqs) q->DivideBySqrtOfLocalBackgroundFreqs( par.half_window_size_local_aa_bg_freqs, pb); // Write consensus sequence to sequence file // Consensus sequence is calculated in hhalignment.C, Alignment::FrequenciesAndTransitions() if (*par.outfile) { FILE* outf = NULL; if (strcmp(par.outfile, "stdout")) { outf = fopen(par.outfile, "a"); if (!outf) OpenFileError(par.outfile, __FILE__, __LINE__, __func__); } else outf = stdout; // OLD //// ">name_consensus" -> ">name consensus" //strsubst(q->sname[q->nfirst],"_consensus"," consensus"); //fprintf(outf,">%s\n%s\n",q->sname[q->nfirst],q->seq[q->nfirst]+1); // NEW (long header needed for NR30cons database) fprintf(outf, ">%s\n%s\n", q->longname, q->seq[q->nfirst] + 1); fclose(outf); } // Print A3M/A2M/FASTA output alignment if (*par.alnfile) { HalfAlignment qa; int n = imin(q->n_display, par.nseqdis + (q->nss_dssp >= 0) + (q->nss_pred >= 0) + (q->nss_conf >= 0) + (q->ncons >= 0)); qa.Set(q->name, q->seq, q->sname, n, q->L, q->nss_dssp, q->nss_pred, q->nss_conf, q->nsa_dssp, q->ncons); if (par.outformat == 1) qa.BuildFASTA(); else if (par.outformat == 2) qa.BuildA2M(); else if (par.outformat == 3) qa.BuildA3M(); if (qali->readCommentLine) qa.Print(par.alnfile, par.append, qali->longname); // print alignment to outfile else qa.Print(par.alnfile, par.append); // print alignment to outfile } delete qali; delete q; DeletePseudocountsEngine(context_lib, crf, pc_hhm_context_engine, pc_hhm_context_mode, pc_prefilter_context_engine, pc_prefilter_context_mode); }
/** * JoinChannels * * Joins the channels which the user should be in (according to * the configuration file). */ void CIRCConnection::JoinChannels(void) { size_t Size; const char *Channels; if (m_DelayJoinTimer) { m_DelayJoinTimer->Destroy(); m_DelayJoinTimer = NULL; } Channels = GetOwner()->GetConfigChannels(); if (Channels != NULL && Channels[0] != '\0') { char *DupChannels, *newChanList, *Channel, *ChanList = NULL; CKeyring *Keyring; DupChannels = strdup(Channels); if (AllocFailed(DupChannels)) { return; } Channel = strtok(DupChannels, ","); Keyring = GetOwner()->GetKeyring(); while (Channel != NULL && Channel[0] != '\0') { const char *Key = Keyring->GetKey(Channel); if (Key != NULL) { WriteLine("JOIN %s %s", Channel, Key); } else { if (ChanList == NULL || strlen(ChanList) > 400) { if (ChanList != NULL) { WriteLine("JOIN %s", ChanList); free(ChanList); } Size = strlen(Channel) + 1; ChanList = (char *)malloc(Size); if (AllocFailed(ChanList)) { free(DupChannels); return; } strmcpy(ChanList, Channel, Size); } else { Size = strlen(ChanList) + 1 + strlen(Channel) + 2; newChanList = (char *)realloc(ChanList, Size); if (AllocFailed(newChanList)) { continue; } ChanList = newChanList; strmcat(ChanList, ",", Size); strmcat(ChanList, Channel, Size); } } Channel = strtok(NULL, ","); } if (ChanList != NULL) { WriteLine("JOIN %s", ChanList); free(ChanList); } free(DupChannels); } }
/*-------------------------------------------------------------------------*/ void xcopy_files(const char *src_pathname, const char *src_filename, const char *dest_pathname, const char *dest_filename) { char filepattern[MAXPATH], new_src_pathname[MAXPATH], new_dest_pathname[MAXPATH], src_path_filename[MAXPATH], dest_path_filename[MAXPATH], tmp_filename[MAXFILE + MAXEXT], tmp_pathname[MAXPATH]; struct ffblk fileblock; int fileattrib, done; if (switch_emptydir || switch_subdir || switch_tree) { /* copy files in subdirectories too */ strmcpy(filepattern, src_pathname, sizeof(filepattern)); strmcat(filepattern, "*.*", sizeof(filepattern)); done = findfirst(filepattern, &fileblock, FA_DIREC); while (!done) { if ((fileblock.ff_attrib & FA_DIREC) != 0 && strcmp(fileblock.ff_name, ".") != 0 && strcmp(fileblock.ff_name, "..") != 0) { /* build source pathname */ strmcpy(new_src_pathname, src_pathname, sizeof(new_src_pathname)); strmcat(new_src_pathname, fileblock.ff_name, sizeof(new_src_pathname)); strmcat(new_src_pathname, DIR_SEPARATOR, sizeof(new_src_pathname)); /* build destination pathname */ strmcpy(new_dest_pathname, dest_pathname, sizeof(new_dest_pathname)); strmcat(new_dest_pathname, fileblock.ff_name, sizeof(new_dest_pathname)); strmcat(new_dest_pathname, DIR_SEPARATOR, sizeof(new_dest_pathname)); xcopy_files(new_src_pathname, src_filename, new_dest_pathname, dest_filename); } done = findnext(&fileblock); } } fileattrib = FA_RDONLY + FA_ARCH; if (switch_hidden) { /* replace hidden and system files too */ fileattrib = fileattrib + FA_HIDDEN + FA_SYSTEM; } /* find first source file */ strmcpy(filepattern, src_pathname, sizeof(filepattern)); strmcat(filepattern, src_filename, sizeof(filepattern)); done = findfirst(filepattern, &fileblock, fileattrib); if (!done) { file_found = -1; } /* check if destination directory must be created */ if ((!done || switch_emptydir) && !dir_exists(dest_pathname)) { strmcpy(tmp_pathname, dest_pathname, sizeof(tmp_pathname)); if (make_dir(tmp_pathname) != 0) { printf("%s %s\n", catgets(cat, 1, 20, "Unable to create directory"), tmp_pathname); if (switch_continue) { return; } else { catclose(cat); exit(4); } } } /* check, if only directory tree should be created */ if (switch_tree) { return; } /* copy files */ while (!done) { /* check, if copied files should have archive attribute set */ if ((switch_archive == 0 && switch_archive_reset == 0) || fileblock.ff_attrib & FA_ARCH) { /* build source filename including path */ strmcpy(src_path_filename, src_pathname, sizeof(src_path_filename)); strmcat(src_path_filename, fileblock.ff_name, sizeof(src_path_filename)); /* build destination filename including path */ strmcpy(dest_path_filename, dest_pathname, sizeof(dest_path_filename)); build_filename(tmp_filename, fileblock.ff_name, dest_filename); strmcat(dest_path_filename, tmp_filename, sizeof(dest_path_filename)); xcopy_file(src_path_filename, dest_path_filename); } done = findnext(&fileblock); } }
/*-------------------------------------------------------------------------*/ int main(int argc, const char **argv) { int fileargc, switchargc; char *fileargv[255], *switchargv[255], env_prompt[MAXSWITCH], tmp_switch[MAXSWITCH] = "", src_pathname[MYMAXPATH] = "", src_filename[MAXFILE + MAXEXT] = "", dest_pathname[MYMAXPATH] = "", dest_filename[MAXFILE + MAXEXT] = "", *ptr, ch; int i, length; THEDATE dt; #ifdef __WATCOMC__ struct dostime_t tm; #else struct time tm; #endif cat = catopen ("xcopy", 0); /* initialize kitten */ classify_args(argc, argv, &fileargc, fileargv, &switchargc, switchargv); if (fileargc < 1 || switchargv[0] == "?") { print_help(); catclose(cat); exit(4); } if (fileargc > 2) { printf("%s\n",catgets(cat, 1, 1, "Invalid number of parameters")); catclose(cat); exit(4); } /* activate termination function */ /* (writes no. of copied files at exit) */ atexit(exit_fn); /* read environment variable COPYCMD to set confirmation switch */ strmcpy(env_prompt, getenv("COPYCMD"), sizeof(env_prompt)); if (env_prompt[0] != '\0') { strupr(env_prompt); if (strcmp(env_prompt, "/Y") == 0) /* overwrite existing file(s) */ switch_confirm = 0; else if (strcmp(env_prompt, "/N") == 0) /* skip existing file(s) */ switch_confirm = 1; else /* ask for confirmation */ switch_confirm = 2; } /* get switches */ for (i = 0; i < switchargc; i++) { strmcpy(tmp_switch, switchargv[i], sizeof(tmp_switch)); strupr(tmp_switch); if (strcmp(tmp_switch, "A") == 0) switch_archive = -1; else if (strcmp(tmp_switch, "C") == 0) switch_continue = -1; else if (strcmp(tmp_switch, "D") == 0) switch_date = -1; else if (strncmp(tmp_switch, "D:", 2) == 0) { if (strtodate(tmp_switch+2, &dt) != 0 || !datevalid(&dt)) { printf("%s\n",catgets(cat, 1, 2, "Invalid date")); catclose(cat); exit(4); } #ifdef __WATCOMC__ memset((void *)&tm, 0, sizeof(struct dostime_t)); /* tm.tm_hour = 0; tm.tm_min = 0; tm.tm_sec = 0; tm.tm_hund = 0; */ #else memset((void *)&tm, 0, sizeof(struct time)); /* tm.ti_hour = 0; tm.ti_min = 0; tm.ti_sec = 0; tm.ti_hund = 0; */ #endif switch_date = dostounix(&dt, &tm); } else if (strcmp(tmp_switch, "E") == 0) switch_emptydir = -1; else if (strcmp(tmp_switch, "F") == 0) switch_fullnames = -1; else if (strcmp(tmp_switch, "H") == 0) switch_hidden = -1; else if (strcmp(tmp_switch, "I") == 0) switch_intodir = -1; else if (strcmp(tmp_switch, "L") == 0) switch_listmode = -1; else if (strcmp(tmp_switch, "M") == 0) switch_archive_reset = -1; else if (strcmp(tmp_switch, "N") == 0) switch_confirm = 1; else if (strcmp(tmp_switch, "P") == 0) switch_prompt = -1; else if (strcmp(tmp_switch, "Q") == 0) switch_quiet = -1; else if (strcmp(tmp_switch, "R") == 0) switch_readonly = -1; else if (strcmp(tmp_switch, "S") == 0) switch_subdir = -1; else if (strcmp(tmp_switch, "T") == 0) switch_tree = -1; else if (strcmp(tmp_switch, "V") == 0) { switch_verify = -1; bak_verify = getverify(); setverify(1); } else if (strcmp(tmp_switch, "W") == 0) switch_wait = -1; else if (strcmp(tmp_switch, "Y") == 0) switch_confirm = 0; else if (strcmp(tmp_switch, "-Y") == 0) switch_confirm = 2; else { printf("%s - %s\n", catgets(cat, 1, 3, "Invalid switch"), switchargv[i]); catclose(cat); exit(4); } } /* get source pathname (with trailing backspace) and filename/-pattern */ length = strlen(fileargv[0]); if (length > (MAXPATH - 1)) { printf("%s\n", catgets(cat, 1, 4, "Source path too long")); catclose(cat); exit(4); } _fullpath(src_pathname, fileargv[0], MYMAXPATH); if (src_pathname[0] == '\0') { printf("%s\n", catgets(cat, 1, 5, "Invalid source drive specification")); catclose(cat); exit(4); } /* check source path */ if (!dir_exists(src_pathname)) { /* source path contains a filename/-pattern -> separate it */ ptr = strrchr(src_pathname, *DIR_SEPARATOR); ptr++; strmcpy(src_filename, ptr, sizeof(src_filename)); *ptr = '\0'; if (!dir_exists(src_pathname)) { printf("%s - %s\n", catgets(cat, 1, 6, "Source path not found"), src_pathname); catclose(cat); exit(4); } } else { /* source is a directory -> filepattern = "*.*" */ strmcpy(src_filename, "*.*", sizeof(src_filename)); } cat_separator(src_pathname); length = strlen(src_pathname); if (length > (MAXDRIVE - 1 + MAXDIR - 1)) { printf("%s\n", catgets(cat, 1, 7, "Source path too long")); catclose(cat); exit(4); } /* get destination pathname (with trailing backspace) and */ /* filename/-pattern */ if (fileargc < 2) { /* no destination path specified -> use current */ getcwd(dest_pathname, MAXPATH); strmcpy(dest_filename, "*.*", sizeof(dest_filename)); } else { /* destination path specified */ length = strlen(fileargv[1]); if (length > (MAXPATH - 1)) { printf("%s\n", catgets(cat, 1, 8, "Destination path too long")); catclose(cat); exit(4); } _fullpath(dest_pathname, fileargv[1], MYMAXPATH); if (dest_pathname[0] == '\0') { printf("%s\n", catgets(cat, 1, 9, "Invalid destination drive specification")); catclose(cat); exit(4); } /* check destination path */ if (fileargv[1][length - 1] != *DIR_SEPARATOR && !dir_exists(dest_pathname)) { ptr = strrchr(dest_pathname, *DIR_SEPARATOR); ptr++; strmcpy(dest_filename, ptr, sizeof(dest_filename)); *ptr = '\0'; if ((ptr = strchr(dest_filename, '*')) == NULL && (ptr = strchr(dest_filename, '?')) == NULL) { /* last destination entry is not a filepattern -> does it specify */ /* a file or directory? */ if (((ptr = strchr(src_filename, '*')) == NULL && (ptr = strchr(src_filename, '?')) == NULL) || !switch_intodir) { /* source is a single file or switch /I was not specified -> ask */ /* user if destination should be a file or a directory */ printf("%s %s %s\n", catgets(cat, 1, 10, "Does"), dest_filename, catgets(cat, 1, 11, "specify a file name")); ch = confirm( catgets(cat, 1, 12, "or directory name on the target"), catgets(cat, 1, 13, "File"), catgets(cat, 1, 14, "Directory"), NULL, NULL); switch (ch) { case 1: /* 'F' */ /* file */ switch_file = -1; break; case 2: /* 'D' */ /* directory */ switch_intodir = -1; break; } } if (switch_intodir) { /* destination is a directory -> filepattern = "*.*" */ strmcat(dest_pathname, dest_filename, sizeof(dest_pathname)); strmcpy(dest_filename, "*.*", sizeof(dest_filename)); } } } else { /* destination is a directory -> filepattern = "*.*" */ strmcpy(dest_filename, "*.*", sizeof(dest_filename)); } } cat_separator(dest_pathname); length = strlen(dest_pathname); if (length > (MAXDRIVE - 1 + MAXDIR - 1)) { printf("%s\n",catgets(cat, 1, 15, "Destination path too long")); catclose(cat); exit(4); } /* check for cyclic path */ if ((switch_emptydir || switch_subdir) && cyclic_path(src_pathname, dest_pathname)) { printf("%s\n",catgets(cat, 1, 16, "Cannot perform a cyclic copy")); catclose(cat); exit(4); } /* get destination drive (1 = A, 2 = B, 3 = C, ...) */ dest_drive = toupper(dest_pathname[0]) - 64; if (switch_wait) { printf("%s\n",catgets(cat, 1, 17, "Press enter to continue...")); (void)getchar(); /* getch(); would need conio.h */ fflush(stdin); } xcopy_files(src_pathname, src_filename, dest_pathname, dest_filename); if (!file_found) { printf("%s - %s\n",catgets(cat, 1, 18, "File not found"), src_filename); catclose(cat); exit(1); } catclose(cat); return 0; }
/*-------------------------------------------------------------------------*/ void xcopy_file(const char *src_filename, const char *dest_filename) { int dest_file_exists; int fileattrib; struct stat src_statbuf; struct stat dest_statbuf; struct dfree disktable; unsigned long free_diskspace; char ch; char msg_prompt[255]; if (switch_prompt) { /* ask for confirmation to create file */ ch = confirm(dest_filename, catgets(cat, 3, 2, "Yes"), catgets(cat, 3, 3, "No"), NULL, NULL); if (ch == 2 /* 'N' */) { /* no -> skip file */ return; } } /* check if source and destination file are equal */ if (stricmp(src_filename, dest_filename) == 0) { printf("%s - %s\n", catgets(cat, 1, 21, "File cannot be copied onto itself"), src_filename); catclose(cat); exit(4); } /* check source file for read permission */ /* (only usefull under an OS with the ability to deny read access) */ if (access(src_filename, R_OK) != 0) { printf("%s - %s\n", catgets(cat, 1, 22, "Read access denied"), src_filename); if (switch_continue) { return; } else { catclose(cat); exit(5); } } /* get info of source and destination file */ stat((char *)src_filename, &src_statbuf); dest_file_exists = !stat((char *)dest_filename, &dest_statbuf); /* get amount of free disk space in destination drive */ getdfree(dest_drive, &disktable); free_diskspace = (unsigned long) disktable.df_avail * disktable.df_sclus * disktable.df_bsec; if (dest_file_exists) { if (switch_date) { if (switch_date < 0) { /* check, that only newer files are copied */ if (src_statbuf.st_mtime <= dest_statbuf.st_mtime) { return; } } else { /* check, that only files changed on or after the specified date */ /* are copied */ if (src_statbuf.st_mtime < switch_date) { return; } } } switch (switch_confirm) { case 1: /* skip file */ return; case 2: /* ask for confirmation to overwrite file */ strmcpy(msg_prompt, catgets(cat, 3, 1, "Overwrite"), sizeof(msg_prompt)); strmcat(msg_prompt, " ", sizeof(msg_prompt)); strmcat(msg_prompt, dest_filename, sizeof(msg_prompt)); ch = confirm(msg_prompt, catgets(cat, 3, 2, "Yes"), catgets(cat, 3, 3, "No"), catgets(cat, 3, 4, "Overwrite all"), catgets(cat, 3, 5, "Skip all")); switch (ch) { case 2: /* 'N' */ /* no -> skip file */ return; case 3: /* 'O' */ /* overwrite all -> set confirm switch */ switch_confirm = 0; break; case 4: /* 'S' */ /* skip all -> set confirm switch */ switch_confirm = 1; return; } break; } /* check free space on destination disk */ /* *** was wrong, was: "if (src... > free... - dest...) ..." */ if ( (src_statbuf.st_size > dest_statbuf.st_size) && ((src_statbuf.st_size - dest_statbuf.st_size) > free_diskspace) ) { printf("%s - %s\n", catgets(cat, 1, 23, "Insufficient disk space in destination path"), dest_filename); catclose(cat); exit(39); } /* get file attribute from destination file */ fileattrib = _chmod(dest_filename, 0); /* check destination file for write permission */ if ((fileattrib & (64 ^ FA_RDONLY)) != 0) { if (!switch_readonly) { printf("%s - %s\n", catgets(cat, 1, 24, "Write access denied"), dest_filename); if (switch_continue) { return; } else { catclose(cat); exit(5); } } /* check, if file copying should be simulated */ if (!switch_listmode) { /* remove readonly attribute from destination file */ fileattrib = fileattrib ^ FA_RDONLY; _chmod(dest_filename, 1, fileattrib); } } } else { /* check free space on destination disk */ if (src_statbuf.st_size > free_diskspace) { printf("%s - %s\n", catgets(cat, 1, 25, "Insufficient disk space in destination path"), dest_filename); catclose(cat); exit(39); } } if (!switch_quiet) { printf("%s %s", catgets(cat, 1, 26, "Copying"), src_filename); if (switch_fullnames) { printf(" -> %s\n", dest_filename); } else { printf("\n"); } } /* check, if file copying should be simulated */ if (!switch_listmode) { copy_file(src_filename, dest_filename, switch_continue); if (switch_archive_reset) { /* remove archive attribute from source file */ fileattrib = _chmod(src_filename, 0); _chmod(src_filename, 1, fileattrib ^ FA_ARCH); } } file_counter++; }
char * pathcpy(char *dst, char const *src) { return strmcpy(dst, src, PATH_MAX); }
/* * update_input: does varying amount of updating on the input line depending * upon the position of the cursor and the update flag. If the cursor has * move toward one of the edge boundaries on the screen, update_cursor() * flips the input line to the next (previous) line of text. The update flag * may be: * * NO_UPDATE - only do the above bounds checking. * * UPDATE_JUST_CURSOR - do bounds checking and position cursor where is should * be. * * UPDATE_FROM_CURSOR - does all of the above, and makes sure everything from * the cursor to the right edge of the screen is current (by redrawing it). * * UPDATE_ALL - redraws the entire line */ void update_input(int update) { int old_start; static int co = 0, li = 0; char *ptr; int len, free_it = 1, cnt, ansi_count, max; char *prompt; cursor_to_input(); if (current_screen->promptlist) prompt = current_screen->promptlist->prompt; else prompt = input_prompt; if (prompt) { if (update != NO_UPDATE) { char *inp_ptr = NULL; int args_used; if (is_process(get_target_by_refnum(0))) { ptr = (char *) get_prompt_by_refnum(0); free_it = 0; } else if (!get_int_var(DISPLAY_ANSI_VAR)) ptr = expand_alias(stripansicodes(prompt), empty_str, &args_used, NULL); else ptr = expand_alias(prompt, empty_str, &args_used, NULL); if (*ptr && ((my_strnicmp(ptr, "Password:"******"Operator Password:"******"Server Password:", 16) == 0))) term_echo(0); else term_echo(1); len = strlen(ptr); if (strncmp(ptr, current_screen->input_buffer, len) || !len) { malloc_strcpy(&inp_ptr, INPUT_BUFFER + MIN_POS); strmcpy(INPUT_BUFFER, ptr, INPUT_BUFFER_SIZE); THIS_POS += (len - MIN_POS); MIN_POS = strlen(ptr); ADD_TO_INPUT(inp_ptr); new_free(&inp_ptr); update = UPDATE_ALL; } if (free_it) new_free(&ptr); } } else term_echo(1); if ((li != term_rows) || (co != term_cols)) { /* resized? Keep it simple and reset everything */ input_line = term_rows - 1; zone = term_cols - (WIDTH * 2) + 4; lower_mark = WIDTH; upper_mark = term_cols - WIDTH; cursor = current_screen->buffer_min_pos; current_screen->buffer_pos = current_screen->buffer_min_pos; str_start = 0; li = term_rows; co = term_cols; } old_start = str_start; ansi_count = count_ansi(current_screen->input_buffer, zone); if (old_ansi != ansi_count || current_screen->buffer_pos - ansi_count > zone) { lower_mark = WIDTH; upper_mark = term_cols - WIDTH; str_start = 0; } ansi_count = count_ansi(&(current_screen->input_buffer[str_start]), zone); while ((current_screen->buffer_pos - ansi_count < lower_mark) && lower_mark > WIDTH) { upper_mark = lower_mark - ansi_count; lower_mark -= (zone + ansi_count); str_start -= (zone + ansi_count); if (str_start < zone) { str_start = 0; ansi_count = count_ansi(&(current_screen->input_buffer[str_start]), zone); lower_mark -= ansi_count; upper_mark -= ansi_count; } } while (current_screen->buffer_pos - ansi_count >= upper_mark) { lower_mark = upper_mark + ansi_count; upper_mark += zone + ansi_count; str_start += zone + ansi_count; if (ansi_count) ansi_count = 0; } /* we need to count ansi characters again, this time in the part of the string we are gonna display in a few moments */ ansi_count = count_ansi(&(current_screen->input_buffer[str_start]), zone); old_ansi = count_ansi(current_screen->input_buffer, zone); /* we need to substract number of ansi characters from cursor position since those are not visible, otherwise we'd display cursor * in wrong place */ cursor = current_screen->buffer_pos - str_start - ansi_count; if ((old_start != str_start) || (update == UPDATE_ALL)) { term_move_cursor(0, input_line); if ((str_start == 0) && (MIN_POS > 0)) { int echo; echo = term_echo(1); if (MIN_POS > (term_cols - WIDTH)) len = term_cols - WIDTH - 1 /* + ansi_count */ ; else len = MIN_POS; cnt = /* term_puts */ safe_puts(&(INPUT_BUFFER[str_start]), len); term_echo(echo); cnt += /* term_puts */ safe_puts(&(current_screen->input_buffer[ str_start + len]), term_cols - len + ansi_count); } else cnt = /* term_puts */ safe_puts(&(INPUT_BUFFER[str_start]), term_cols); term_clear_to_eol(); term_move_cursor(cursor, input_line); } else if (update == UPDATE_FROM_CURSOR) { term_move_cursor(cursor, input_line); cnt = cursor; max = term_cols - (current_screen->buffer_pos - str_start) + ansi_count; if ((len = strlen(&(THIS_CHAR))) > max) len = max; cnt += /* term_puts */ safe_puts(&(THIS_CHAR), len); term_clear_to_eol(); term_move_cursor(cursor, input_line); } else if (update == UPDATE_JUST_CURSOR) term_move_cursor(cursor, input_line); term_flush(); }
/* * set_input: sets the input buffer to the given string, discarding whatever * was in the input buffer before */ void set_input(char *str) { strmcpy(INPUT_BUFFER + MIN_POS, str, INPUT_BUFFER_SIZE - MIN_POS); THIS_POS = strlen(INPUT_BUFFER); }
/** * UtilSaltedMd5 * * Computes the MD5 hash of a given string and returns * a string representation of the hash. * * @param String the string which should be hashed * @param Salt the salt value * @param BrokenAlgo whether to use the broken algorithm */ const char *UtilMd5(const char *String, const char *Salt, bool BrokenAlgo) { #ifdef HAVE_LIBSSL MD5_CTX context; #else /* HAVE_LIBSSL */ sMD5_CTX context; #endif /* HAVE_LIBSSL */ broken_sMD5_CTX broken_context; unsigned char digest[16]; char *StringAndSalt, *StringPtr; static char *SaltAndResult = NULL; int rc; free(SaltAndResult); if (Salt != NULL) { rc = asprintf(&StringAndSalt, "%s%s", String, Salt); } else { rc = asprintf(&StringAndSalt, "%s", String); } if (RcFailed(rc)) { g_Bouncer->Fatal(); } if (!BrokenAlgo) { #ifdef HAVE_LIBSSL MD5_Init(&context); MD5_Update(&context, (unsigned char *)StringAndSalt, strlen(StringAndSalt)); MD5_Final(digest, &context); #else /* HAVE_LIBSSL */ MD5Init(&context); MD5Update(&context, (unsigned char *)StringAndSalt, strlen(StringAndSalt)); MD5Final(digest, &context); #endif /* HAVE_LIBSSL */ } else { broken_MD5Init(&broken_context); broken_MD5Update(&broken_context, (unsigned char *)StringAndSalt, strlen(StringAndSalt)); broken_MD5Final(digest, &broken_context); } free(StringAndSalt); if (Salt != NULL) { SaltAndResult = (char *)malloc(strlen(Salt) + 50); if (AllocFailed(SaltAndResult)) { g_Bouncer->Fatal(); } strmcpy(SaltAndResult, Salt, strlen(Salt) + 50); strmcat(SaltAndResult, "$", strlen(Salt) + 50); StringPtr = SaltAndResult + strlen(SaltAndResult); } else { StringPtr = SaltAndResult = (char *)malloc(50); if (AllocFailed(SaltAndResult)) { g_Bouncer->Fatal(); } } for (int i = 0; i < 16; i++) { /* TODO: don't use sprintf */ sprintf(StringPtr + i * 2, "%02x", digest[i]); } return SaltAndResult; }