int main(int argc, char* argv[], char *envp[]) { // If you use execvp() without a fork, it'll take over the main system. // This is why you need to fork a process, then call execvp() list<char**> arguments; list<char*> connectors; // Grabs host name char* login; char host[127]; login = getlogin(); if (gethostname(host, 127) != 0) { perror("failed to gethostname"); exit(EXIT_FAILURE); } string command = ""; printInfo(login, host); cout << "$ "; while (getline(cin, command)) { while (command.length() == 0) { printInfo(login, host); cout << "$ "; getline(cin,command); } char* cstrcmd = '\0'; list<char*> tokens; list<char*> data; cstrcmd = new char[command.size() + 1]; // This data is universal. It will be used until deallocated. strcpy(cstrcmd, command.c_str()); data.push_back(cstrcmd); // This is to hold locations of the data to deallocate later tokens = parse(cstrcmd); /*if (isDblConnector(tokens.back())) { tokens.pop_back(); cout << "Terminated without command -- ignoring leading connector." << endl; }*/ while (isDblConnector(tokens.back())) { // If the stupid user ended with a connector list<char*> tmpCmds; cout << "> "; getline(cin, command); cstrcmd = new char[command.size() + 1]; strcpy(cstrcmd, command.c_str()); data.push_back(cstrcmd); tmpCmds = parse(cstrcmd); while (!tmpCmds.empty()) { tokens.push_back(tmpCmds.front()); tmpCmds.pop_front(); } } // Creating the two argument and connector lists int last; // There definitely has to be a better way to do this. char* cmd[128][256]; // cmd is a list of pointers to the beginning of each token of the // universal data int n = 0; for (int i = 0; !tokens.empty(); ++i) { cutEndSpaces(tokens.front()); if (isQuoteBegin(tokens.front())) { // Quote parsing trim(tokens.front()); while (!isQuoteEnd(tokens.front())) { // Input clause should prevent infinite loop cmd[n][i] = tokens.front(); tokens.pop_front(); ++i; } truncate(tokens.front()); // Cuts off the quotation mark if (isAttached(tokens.front())) { // Same clause as below truncate(tokens.front()); // This one should cut off the semicolon cmd[n][i] = tokens.front(); tokens.front() = new char[1]; data.push_back(tokens.front()); strcpy(tokens.front(), ";\0"); tokens.push_front(NULL); // Phony Value } else { cmd[n][i] = tokens.front(); // Throws it into the list } ++i; } else if (isComment(tokens.front())) break; else if (isConnector(tokens.front())) { if (isAttached(tokens.front())) { // Pesky semicolons being attached... truncate(tokens.front()); // Cuts out the semicolon, leaves rest of stack cmd[n][i] = tokens.front(); tokens.front() = new char[1]; data.push_back(tokens.front()); strcpy(tokens.front(), ";\0"); ++i; // Progressing to the next value of cmd } cmd[n][i] = '\0'; // Null terminating cmd arguments.push_back(cmd[n]); // If we ran into a connector, means we have a full argument. connectors.push_back(tokens.front()); ++n; i = -1; // Reset argc } else if (isTestBegin(tokens.front()) && i == 0) { // Essentially converting "[" to "test" cmd[n][0] = new char[4]; strcpy(cmd[n][0], "test"); data.push_back(cmd[n][0]); // potential glibc tokens.pop_front(); // Killing "[" from tokens. for (i = 1; !isTestEnd(tokens.front()); ++i) { cmd[n][i] = tokens.front(); tokens.pop_front(); } } else { cmd[n][i] = tokens.front(); // Assigns cmd[i] to pointer at tokens.front(). // Tokens contains cstrings } tokens.pop_front(); // Should take care of "]" last = i; } if (cmd[n][0] != '\0') { // Push in the last argument cmd[n][last + 1] = '\0'; arguments.push_back(cmd[n]); } Connector* head = NULL; head = buildTree(arguments, connectors); head->run(); while (!connectors.empty()) connectors.pop_front(); while (!arguments.empty()) arguments.pop_front(); // If, for some reason, these two are not empty. while (!data.empty()) { delete[] data.front(); // This deallocates the entire command string. data.pop_front(); } head->destroyBranch(head); printInfo(login, host); cout << "$ "; } return 0; }
EditLine::EditLine(const QString &text) : QString( text ) { if ( at(length()-1)=='\n' ) truncate(length()-1); forward = -1; }
DBOP * dbop3_open(const char *path, int mode, int perm, int flags) { int rc, rw = 0; char *errmsg = 0; DBOP *dbop; sqlite3 *db3; const char *tblname; int cache_size = 0; STRBUF *sql = strbuf_open_tempbuf(); char buf[1024]; /* * When the path is NULL string and private, temporary file is used. * The database will be removed when the session is closed. */ if (path == NULL) { path = ""; tblname = "temp"; } else { /* * In case of creation. */ if (mode == 1) (void)truncate(path, 0); tblname = "db"; } /* * setup arguments. */ switch (mode) { case 0: rw = SQLITE_OPEN_READONLY; break; case 1: rw = SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; break; case 2: rw = SQLITE_OPEN_READWRITE; break; default: assert(0); } /* * When the forth argument is NULL, sqlite3_vfs is used. */ rc = sqlite3_open_v2(path, &db3, rw, NULL); if (rc != SQLITE_OK) die("sqlite3_open_v2 failed. (rc = %d)", rc); dbop = (DBOP *)check_calloc(sizeof(DBOP), 1); strlimcpy(dbop->dbname, path, sizeof(dbop->dbname)); dbop->sb = strbuf_open(0); dbop->db3 = db3; dbop->openflags = flags; dbop->perm = (mode == 1) ? perm : 0; dbop->mode = mode; dbop->lastdat = NULL; dbop->lastflag = NULL; dbop->lastsize = 0; dbop->sortout = NULL; dbop->sortin = NULL; dbop->stmt = NULL; dbop->tblname = check_strdup(tblname); /* * Maximum file size is DBOP_PAGESIZE * 2147483646. * if DBOP_PAGESIZE == 8192 then maximum file size is 17592186028032 (17T). */ snprintf(buf, sizeof(buf), "pragma page_size=%d", DBOP_PAGESIZE); rc = sqlite3_exec(dbop->db3, buf, NULL, NULL, &errmsg); if (rc != SQLITE_OK) die("pragma page_size error: %s", errmsg); /* * create table (GTAGS, GRTAGS, GSYMS, GPATH). */ if (mode == 1) { /* drop table */ strbuf_clear(sql); strbuf_puts(sql, "drop table "); strbuf_puts(sql, dbop->tblname); rc = sqlite3_exec(dbop->db3, strbuf_value(sql), NULL, NULL, &errmsg); if (rc != SQLITE_OK) { /* ignore */ } /* create table */ strbuf_clear(sql); strbuf_puts(sql, "create table "); strbuf_puts(sql, dbop->tblname); strbuf_puts(sql, " (key text, dat text, extra text"); if (!(flags & DBOP_DUP)) strbuf_puts(sql, ", primary key(key)"); strbuf_putc(sql, ')'); rc = sqlite3_exec(dbop->db3, strbuf_value(sql), NULL, NULL, &errmsg); if (rc != SQLITE_OK) die("create table error: %s", errmsg); } /* rc = sqlite3_exec(dbop->db3, "pragma synchronous=off", NULL, NULL, &errmsg); if (rc != SQLITE_OK) die("pragma synchronous=off error: %s", errmsg); */ /* * Decide cache size. * See libutil/gparam.h for the details. */ cache_size = GTAGSCACHE; if (getenv("GTAGSCACHE") != NULL) cache_size = atoi(getenv("GTAGSCACHE")); if (cache_size < GTAGSMINCACHE) cache_size = GTAGSMINCACHE; cache_size = (cache_size + DBOP_PAGESIZE - 1) / DBOP_PAGESIZE; snprintf(buf, sizeof(buf), "pragma cache_size=%d", cache_size); rc = sqlite3_exec(dbop->db3, buf, NULL, NULL, &errmsg); if (rc != SQLITE_OK) die("pragma cache_size error: %s", errmsg); sqlite3_exec(dbop->db3, "pragma journal_mode=memory", NULL, NULL, &errmsg); if (rc != SQLITE_OK) die("pragma journal_mode=memory error: %s", errmsg); sqlite3_exec(dbop->db3, "pragma synchronous=off", NULL, NULL, &errmsg); if (rc != SQLITE_OK) die("pragma synchronous=off error: %s", errmsg); rc = sqlite3_exec(dbop->db3, "begin transaction", NULL, NULL, &errmsg); if (rc != SQLITE_OK) die("begin transaction error: %s", errmsg); strbuf_release_tempbuf(sql); return dbop; }
void UnistdTruncate(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs) { ReturnValue->Val->Integer = truncate(Param[0]->Val->Pointer, Param[1]->Val->Integer); }
static int local_truncate(FsContext *ctx, const char *path, off_t size) { return truncate(rpath(ctx, path), size); }
static void start_looper_processes() { unsigned int i, file_size; /* we want at least two pages for each processor. the */ /* child for any one processor will write to the first of his two */ /* pages, and the second page will be a buffer in case there is page */ /* prefetching. if your system pre-fetches more than a single page, */ /* well, you'll have to modify this or live with it :( raj 4/95 */ file_size = ((netlib_get_page_size() * PAGES_PER_CHILD) * lib_num_loc_cpus); #ifndef WIN32 /* we we are not using WINDOWS NT (or 95 actually :), then we want */ /* to create a memory mapped region so we can see all the counting */ /* rates of the loopers */ /* could we just use an anonymous memory region for this? it is */ /* possible that using a mmap()'ed "real" file, while convenient for */ /* debugging, could result in some filesystem activity - like */ /* metadata updates? raj 4/96 */ lib_idle_fd = open("/tmp/netperf_cpu",O_RDWR | O_CREAT | O_EXCL); if (lib_idle_fd == -1) { fprintf(where,"create_looper: file creation; errno %d\n",errno); fflush(where); exit(1); } if (chmod("/tmp/netperf_cpu",0644) == -1) { fprintf(where,"create_looper: chmod; errno %d\n",errno); fflush(where); exit(1); } /* with the file descriptor in place, lets be sure that the file is */ /* large enough. */ if (truncate("/tmp/netperf_cpu",file_size) == -1) { fprintf(where,"create_looper: truncate: errno %d\n",errno); fflush(where); exit(1); } /* the file should be large enough now, so we can mmap it */ /* if the system does not have MAP_VARIABLE, just define it to */ /* be zero. it is only used/needed on HP-UX (?) raj 4/95 */ #ifndef MAP_VARIABLE #define MAP_VARIABLE 0x0000 #endif /* MAP_VARIABLE */ #ifndef MAP_FILE #define MAP_FILE 0x0000 #endif /* MAP_FILE */ if ((lib_base_pointer = (long *)mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED | MAP_VARIABLE, lib_idle_fd, 0)) == (long *)-1) { fprintf(where,"create_looper: mmap: errno %d\n",errno); fflush(where); exit(1); } if (debug > 1) { fprintf(where,"num CPUs %d, file_size %d, lib_base_pointer %p\n", lib_num_loc_cpus, file_size, lib_base_pointer); fflush(where); } /* we should have a valid base pointer. lets fork */ for (i = 0; i < (unsigned int)lib_num_loc_cpus; i++) { switch (lib_idle_pids[i] = fork()) { case -1: perror("netperf: fork"); exit(1); case 0: /* we are the child. we could decide to exec some separate */ /* program, but that doesn't really seem worthwhile - raj 4/95 */ signal(SIGTERM, SIG_DFL); sit_and_spin(i); /* we should never really get here, but if we do, just exit(0) */ exit(0); break; default: /* we must be the parent */ lib_idle_address[i] = (uint64_t *) ((char *)lib_base_pointer + (netlib_get_page_size() * PAGES_PER_CHILD * i)); if (debug) { fprintf(where,"lib_idle_address[%d] is %p\n", i, lib_idle_address[i]); fflush(where); } } } #else /* we are compiled -DWIN32 */ if ((lib_base_pointer = malloc(file_size)) == NULL) { fprintf(where, "create_looper_process could not malloc %d bytes\n", file_size); fflush(where); exit(1); } /* now, create all the threads */ for(i = 0; i < (unsigned int)lib_num_loc_cpus; i++) { long place_holder; if ((lib_idle_pids[i] = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)sit_and_spin, (LPVOID)(ULONG_PTR)i, 0, &place_holder)) == NULL ) { fprintf(where, "create_looper_process: CreateThread failed\n"); fflush(where); /* I wonder if I need to look for other threads to kill? */ exit(1); } lib_idle_address[i] = (long *) ((char *)lib_base_pointer + (netlib_get_page_size() * PAGES_PER_CHILD * i)); if (debug) { fprintf(where,"lib_idle_address[%d] is %p\n", i, lib_idle_address[i]); fflush(where); } } #endif /* WIN32 */ /* we need to have the looper processes settled-in before we do */ /* anything with them, so lets sleep for say 30 seconds. raj 4/95 */ sleep(30); }
void TrimErrorFile( void ) { int f1, f2; int deleteBytes; char buf[BUFSIZ]; char *p; int n; off_t status; struct stat statb; /* * convert user-specified units of 1Kb to bytes... * put an upper cap of 200Kb on the file... */ if (errorLogSize < 1024) errorLogSize *= 1024; if (errorLogSize > (200*1024) ) { errorLogSize = 200*1024; LogError(ReadCatalog( MC_LOG_SET,MC_LOG_MAX_LOGFILE,MC_DEF_LOG_MAX_LOGFILE)); } if ( errorLogFile && errorLogFile[0] && (stat(errorLogFile, &statb) == 0) && (statb.st_size > errorLogSize) ) { deleteBytes = (statb.st_size - errorLogSize) + (errorLogSize / 4); Debug("TrimErrorLog(): discarding oldest %d bytes from logfile %s\n", deleteBytes, errorLogFile); /* * get two pointers to the file... */ if ( (f1 = open(errorLogFile, O_RDWR)) < 0 || (f2 = open(errorLogFile, O_RDWR)) < 0 ) { Debug("TrimErrorLog(): Cannot open file %s, error number = %d\n", errorLogFile, errno); return; } /* * position read pointer to the first full line after the trim * point... */ if ( (status = lseek(f2, deleteBytes, SEEK_SET)) < 0 ) { Debug("TrimErrorLog(): Cannot lseek() in file %s, error number = %d\n", errorLogFile, errno); return; } n = read(f2, buf, BUFSIZ); if ( (p = strchr(buf,'\n')) != NULL ) { p++; n -= p - buf; deleteBytes += p - buf; } else { p = buf; } /* * shift bytes to be saved to the beginning of the file... */ write (f1, p, n); while ( (n = read(f2, buf, BUFSIZ)) > 0 ) write(f1, buf, n); /* * truncate file to new length and close file pointers... */ truncate(errorLogFile, statb.st_size - deleteBytes); close(f1); close(f2); } }
/* Compress the file with the number of divisions indicated by the input * parameter. Pad out to a full byte with zeros at the end of each chunk to * compress in the case that the compressed chunk has a bit count that is not * divisible by 8. */ int HuffmanEncoder::CompressFileWithPadding(int divisions, const string& filename) { /* Stat the file. */ struct stat s; int fd = open(filename.c_str(), O_RDONLY); if (fstat(fd,&s) < 0) { printf("Couldn't stat file, exiting.\n"); exit(1); } close(fd); uint64_t fileLength = (uint64_t)s.st_size; if (mpirank == 0) printf("File length: %ld\n", fileLength); ndivisions = (uint32_t)divisions; offsets = new uint64_t[ndivisions]; chunkLengths = new uint64_t[ndivisions]; chunks = new vector<char>[ndivisions]; compressedChunks = new vector<bool>[ndivisions]; newLengths = new uint64_t[ndivisions]; newOffsets = new uint64_t[ndivisions]; chunksPerProc = new int[p]; memset(chunksPerProc, 0, sizeof(int)*p); if (mpirank == 0) printf("%d: Setting offsets\n", mpirank); int rank = 0; for (unsigned int i = 0; i < ndivisions; i++) { offsets[i] = i*(fileLength/ndivisions); if (i == ndivisions-1) { chunkLengths[i] = fileLength - (ndivisions-1)*(fileLength/ndivisions); printf("Setting chunk %d's length to %ld\n", i, chunkLengths[i]); } else { chunkLengths[i] = fileLength/ndivisions; printf("Setting chunk %d's length to %ld\n", i, chunkLengths[i]); } if (rank % p == mpirank) { printf("%d: Assigned chunk #%d\n", mpirank, i); myChunks.push_back(i); } chunksPerProc[rank%p]++; rank++; } if (mpirank == 0) { printf("Chunks per proc: \n"); for (int i = 0; i < p; i++) { printf("proc #%d: %d, ", i, chunksPerProc[i]); } printf("\n"); } uint64_t myFreqMap[256] = {0}, globalFreqMap[256] = {0}; memset(myFreqMap, 0, 256*sizeof(uint64_t)); memset(globalFreqMap, 0, 256*sizeof(uint64_t)); for (auto it = myChunks.begin(); it != myChunks.end(); it++) { int i = *it; printf("%d: Reading chunk %d from file at offset %ld with chunk size %ld\n", mpirank, i, offsets[i], chunkLengths[i]); chunks[i] = readFile(filename, chunkLengths[i], offsets[i]); HuffmanEncoder::frequencyMapFromText(chunks[i], myFreqMap); } int err = MPI_Allreduce(myFreqMap, globalFreqMap, 256, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); if (err) { printf("Problem with MPI all reduce. Exiting...\n"); exit(1); } HuffmanTree *coding_tree = HuffmanEncoder::huffmanTreeFromFrequencyMap(globalFreqMap); vector<string> encoder = HuffmanEncoder::huffmanEncodingMapFromTree(coding_tree); for (auto it = myChunks.begin(); it != myChunks.end(); it++) { compressedChunks[*it] = HuffmanEncoder::toBinary(chunks[*it], encoder); newLengths[*it] = (uint64_t)ceil((double)compressedChunks[*it].size()/8); newLengths[*it] += sizeof(size_t); newOffsets[*it] = 0; } metadataOffset = calculateMetaDataSize(encoder); if (mpirank == 0) { printf("0: Metadata offset: %d\n", metadataOffset); } string output_file_name = filename + ".hez"; if (mpirank == 0) { int fd = creat(output_file_name.c_str(), 0664); if (fd < 0) { printf("%d: Couldn't create output file %s\n", mpirank, output_file_name.c_str()); exit(1); } close(fd); } HuffmanEncoder::CalculateOffsets(); if (mpirank == 0) { /* Last rank knows how big the final file is, so it will take care of * allocating it. Here, offset is the total length of the compressed * file. */ uint64_t compressedSize = metadataOffset; for (unsigned int i = 0; i < ndivisions; i++) { compressedSize += newLengths[i]; } err = truncate(output_file_name.c_str(), compressedSize); if (err) { printf("Issue with truncate. Error: %s\n", strerror(errno)); return (1); } } /* Make sure file is truncated first. */ MPI_Barrier(MPI_COMM_WORLD); FILE *output_file = fopen(output_file_name.c_str(), "r+"); if(output_file == NULL) { printf("%d: Couldn't open output_file %s!!!\n", mpirank, output_file_name.c_str()); exit(1); } if (mpirank == 0) { printf("%d: Writing metadata!\n", mpirank); CompressedFile::WriteMetadataToFile(output_file, encoder); } //printf("%d: Writing my chunk to the file!\n", mpirank); for (auto it = myChunks.begin(); it != myChunks.end(); it++) { CompressedFile::WriteToFile(output_file, compressedChunks[*it], newOffsets[*it]); printf("%d: Wrote chunk %d to the file at offset %ld!\n", mpirank, *it, newOffsets[*it]); } fclose(output_file); return 0; }
void mqueue_start() { char message_buffer[MQUEUE_BUFFER_SIZE]; from_client = mq_open(MQUEUE_SERVER, O_RDONLY | O_EXCL | O_CREAT, S_IRUSR | S_IWUSR, NULL); to_client = mq_open(MQUEUE_CLIENT, O_WRONLY | O_EXCL | O_CREAT, S_IWUSR | S_IRUSR, NULL); if(from_client == -1 || to_client == -1) { log_error("Failed to open administration interface, mq_open failed"); master_stop(); } log_info("Apricot admin interface opened"); for(;;) { /* receive a message from the client administration interface */ if(mq_receive(from_client, message_buffer, MQUEUE_BUFFER_SIZE, NULL) == -1) { log_error("mq_receive failed : %s", strerror(errno)); continue; } /* process interface request */ if(!strcasecmp(message_buffer, MQUEUE_SEND_LOG)) { FILE * log_file = log_file = fopen(conf.log_file, "r"); if(!log_file) { strcpy(message_buffer, MQUEUE_FAIL); send(to_client, message_buffer); } else { while(fgets(message_buffer, MQUEUE_BUFFER_SIZE-1, log_file)) { send(to_client, message_buffer); } fclose(log_file); strcpy(message_buffer, MQUEUE_OK); send(to_client, message_buffer); } } else if(!strcasecmp(message_buffer, MQUEUE_TRUNCATE_LOG)) { /* to preserve log consistency */ log_lock(); truncate(conf.log_file, 0); log_unlock(); strcpy(message_buffer, MQUEUE_OK); send(to_client, message_buffer); } else if(!strcasecmp(message_buffer, MQUEUE_STOP_SERVER)) { log_info("Apricot stop asked by admin interface"); master_stop(); exit(EXIT_SUCCESS); } else if(!strcasecmp(message_buffer, MQUEUE_RESIZE_POOL)) { log_info("Pool resize asked by admin interface"); /* receive a message from the client administration interface */ if(mq_receive(from_client, message_buffer, MQUEUE_BUFFER_SIZE, NULL) == -1) { log_error("mq_receive failed to receive new pool size : %s", strerror(errno)); continue; } int new_size; if(sscanf(message_buffer, "%i", &new_size) != 1 || new_size <= 0) { log_error("invalid pool size %i received from admin interface", new_size); strcpy(message_buffer, MQUEUE_FAIL); send(to_client, message_buffer); continue; } pool_resize(new_size); strcpy(message_buffer, MQUEUE_OK); send(to_client, message_buffer); } else { strcpy(message_buffer, MQUEUE_FAIL); send(to_client, message_buffer); } } }
int wtruncate(const OsPath& pathname, off_t length) { return truncate(OsString(pathname).c_str(), length); }
/* Decompress the file with the number of divisions indicated by file. * Bytes are oadded out to a full byte with zeros at the end of each chunk * in the case that the compressed chunk has a bit count that is not * divisible by 8. */ int HuffmanEncoder::DecompressFileWithPadding(const string& filename) { struct stat s; int fd = open(filename.c_str(), O_RDONLY); if (fstat(fd,&s) < 0) { printf("Couldn't stat file, exiting.\n"); exit(1); } close(fd); FILE *inputFile = fopen(filename.c_str(), "r"); vector<string>* huffmanMap; CompressedFile::ReadMetadataFromFile(inputFile, &huffmanMap); chunkLengths = new uint64_t[ndivisions]; chunks = new vector<char>[ndivisions]; compressedChunks = new vector<bool>[ndivisions]; newLengths = new uint64_t[ndivisions]; newOffsets = new uint64_t[ndivisions]; decompressedChunks = new string[ndivisions]; chunksPerProc = new int[p]; memset(chunksPerProc, 0, sizeof(int)*p); int rank = 0; for (unsigned int i = 0; i < ndivisions; i++) { if (rank % p == mpirank) { myChunks.push_back(i); } chunksPerProc[rank]++; rank++; } /****************************************************************************************/ for (auto it = myChunks.begin(); it != myChunks.end(); it++) { compressedChunks[*it] = CompressedFile::ReadFromFile(inputFile, offsets[*it]); printf("%d: Read chunk %d at offset %ld, decoding...\n", mpirank, *it, offsets[*it]); decompressedChunks[*it] = HuffmanEncoder::decodeBits(compressedChunks[*it], *huffmanMap); printf("%d: Finished decoding chunk %d\n", mpirank, *it); newLengths[*it] = decompressedChunks[*it].size(); } fclose(inputFile); /* Delete .hez extension */ string output_filename = filename.substr(0, filename.size()-4); if (mpirank == 0) { int fd = creat(output_filename.c_str(), 0664); if (fd < 0) { printf("%d: Couldn't create output file %s\n", mpirank, output_filename.c_str()); exit(1); } close(fd); } metadataOffset = 0; HuffmanEncoder::CalculateOffsets(); if (mpirank == p-1) { /* Last rank knows how big the final file is, so it will take care of * allocating it. Here, offset is the total length of the uncompressed * file. */ uint64_t uncompressedSize = 0; for (unsigned int i = 0; i < ndivisions; i++) { uncompressedSize += newLengths[i]; } int err = truncate(output_filename.c_str(), uncompressedSize); if (err) { printf("Issue with truncate. Error: %s\n", strerror(errno)); exit (1); } } /* Make sure file is truncated first. */ MPI_Barrier(MPI_COMM_WORLD); FILE *outputFile = fopen(output_filename.c_str(), "r+"); //printf("Decompressing %s to %s\n", filename.c_str(), output_filename.c_str()); /* Adjust so we write at the beginning of the chunk, not the end */ //printf("%d: My length to write: %ld, my offset: %ld\n", mpirank, lengthToWrite, offset); for (auto it = myChunks.begin(); it != myChunks.end(); it++) { fseek(outputFile, newOffsets[*it], 0); fwrite(decompressedChunks[*it].c_str(), 1, newLengths[*it], outputFile); printf("%d: Wrote chunk %d to the file at offset %ld!\n", mpirank, *it, newOffsets[*it]); } fclose(outputFile); return 0; }
void DescriptionManager::configurationUpdated() { MaxNumberOfDescriptions = m_configuration->deprecatedApi()->readNumEntry("General", "NumberOfDescriptions"); truncate(); }
/*! \brief Create version file Create version file based on the current file attributes. \param path Complete file path \param dentry Dentry of the file \param with_size Whether version file should be enlarged to the size of the current file */ int32_t version_create_file_with_attr(char *path, internal_dentry dentry, volume vol, string * orgpath) { fattr *sa; zfs_fh fh; int32_t r; sa = &dentry->fh->version_orig_attr; // make sure we have correct attributes of the file if (orgpath) { local_getattr_path_ns(sa, orgpath); } else memcpy(sa, &dentry->fh->attr, sizeof(fattr)); dentry->fh->version_fd = creat(path, GET_MODE(sa->mode)); dentry->fh->version_path = xstrdup(path); if (lchown(path, map_uid_zfs2node(sa->uid), map_gid_zfs2node(sa->gid)) != 0) RETURN_INT(errno); version_set_time(dentry->fh); if (orgpath) { if (truncate(path, sa->size) != 0) RETURN_INT(errno); } acquire_dentry(dentry->parent); r = ZFS_OK; if (r == ZFS_OK) { internal_dentry ndentry; zfs_fh master_fh; // , tmp_fh; string name; metadata meta; fattr attr; string spath; char *p; zfs_fh_undefine(master_fh); p = strrchr(path, '/'); if (p) p++; else p = path; xmkstring(&name, p); xmkstring(&spath, path); r = local_getattr_path_ns(&attr, &spath); free(spath.str); fh.sid = dentry->fh->local_fh.sid; fh.vid = dentry->fh->local_fh.vid; fh.dev = attr.dev; fh.ino = attr.ino; meta.flags = METADATA_COMPLETE; meta.modetype = GET_MODETYPE(attr.mode, attr.type); meta.uid = attr.uid; meta.gid = attr.gid; lookup_metadata(vol, &fh, &meta, true); set_attr_version(&attr, &meta); ndentry = internal_dentry_create_ns(&fh, &master_fh, vol, dentry->parent, &name, sa, &meta, LEVEL_UNLOCKED); if (INTERNAL_FH_HAS_LOCAL_PATH(dentry->fh)) { if (vol->master != this_node) { if (!add_journal_entry(vol, dentry->parent->fh->journal, &dentry->parent->fh->local_fh, &ndentry->fh->local_fh, &ndentry->fh->meta.master_fh, ndentry->fh->meta.master_version, &name, JOURNAL_OPERATION_ADD)) { MARK_VOLUME_DELETE(vol); } } if (!inc_local_version(vol, dentry->parent->fh)) MARK_VOLUME_DELETE(vol); } dentry->version_dentry = ndentry; release_dentry(ndentry); free(name.str); } release_dentry(dentry->parent); RETURN_INT(ZFS_OK); }
// Map an already open file void *FXMemMap::map(FXlong off,FXival len){ if(isOpen()){ // Get file size FXlong filesize=size(); if(0<=filesize){ #ifdef WIN32 // Map whole file if(len==-1) len=filesize-off; // Set access flags DWORD prot=0; if(access&ReadOnly){ prot=PAGE_READONLY; } if(access&WriteOnly){ prot=PAGE_READWRITE; } DWORD flag=0; if(access&ReadOnly){ flag=FILE_MAP_READ; } if(access&WriteOnly){ flag=FILE_MAP_WRITE; } // Now map it FXInputHandle hnd=::CreateFileMapping(handle(),NULL,prot,0,len,NULL); if(hnd!=NULL){ FXuchar* ptr=(FXuchar*)::MapViewOfFile(hnd,flag,0,off,len); if(ptr!=NULL){ maphandle=hnd; mapbase=ptr; maplength=len; mapoffset=off; mapposition=off; return mapbase; } ::CloseHandle(hnd); } #else // Map whole file if(len==-1) len=filesize-off; // Trying to map region larger than the file if(filesize<off+len){ if(access&WriteOnly){ truncate(off+len); // Extends the file if writing } else{ len=filesize-off; // Map smaller region when reading } } // Set access flags FXint prot=PROT_NONE; if(access&ReadOnly){ prot|=PROT_READ; } if(access&WriteOnly){ prot|=PROT_WRITE|PROT_READ; } if(access&Executable){ prot|=PROT_EXEC; } // Now map it FXuchar* ptr=(FXuchar*)::mmap(NULL,len,prot,MAP_SHARED,handle(),off); if(ptr!=MAP_FAILED){ mapbase=ptr; maplength=len; mapoffset=off; mapposition=off; return mapbase; } #endif } } return NULL; }
int main(int argc, char *argv[]) { char filename[] = "/tmp/textfile"; char key[18], value[512], *str; unsigned int i, j, size, max = 10; int fd, err; size = getpagesize(); printf("System uses a page size of %d bytes\n\n", size); fd = creat(filename, 0644); err = ftruncate(fd, 0); memset(value, 0, sizeof(value)); for (i = 0; i < (size / sizeof(value)); i++) err = write(fd, value, sizeof(value)); close(fd); sprintf(key, "11:11:11:11:11:11"); str = textfile_get(filename, key); err = truncate(filename, 0); sprintf(key, "00:00:00:00:00:00"); if (textfile_del(filename, key) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); memset(value, 0, sizeof(value)); if (textfile_put(filename, key, value) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); str = textfile_get(filename, key); if (!str) fprintf(stderr, "No value for %s\n", key); else free(str); snprintf(value, sizeof(value), "Test"); if (textfile_put(filename, key, value) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); if (textfile_put(filename, key, value) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); if (textfile_put(filename, key, value) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); if (textfile_del(filename, key) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); str = textfile_get(filename, key); if (str) { fprintf(stderr, "Found value for %s\n", key); free(str); } for (i = 1; i < max + 1; i++) { sprintf(key, "00:00:00:00:00:%02X", i); memset(value, 0, sizeof(value)); for (j = 0; j < i; j++) value[j] = 'x'; printf("%s %s\n", key, value); if (textfile_put(filename, key, value) < 0) { fprintf(stderr, "%s (%d)\n", strerror(errno), errno); break; } str = textfile_get(filename, key); if (!str) fprintf(stderr, "No value for %s\n", key); else free(str); } sprintf(key, "00:00:00:00:00:%02X", max); memset(value, 0, sizeof(value)); for (j = 0; j < max; j++) value[j] = 'y'; if (textfile_put(filename, key, value) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); sprintf(key, "00:00:00:00:00:%02X", 1); memset(value, 0, sizeof(value)); for (j = 0; j < max; j++) value[j] = 'z'; if (textfile_put(filename, key, value) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); printf("\n"); for (i = 1; i < max + 1; i++) { sprintf(key, "00:00:00:00:00:%02X", i); str = textfile_get(filename, key); if (str) { printf("%s %s\n", key, str); free(str); } } sprintf(key, "00:00:00:00:00:%02X", 2); if (textfile_del(filename, key) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); sprintf(key, "00:00:00:00:00:%02X", max - 3); if (textfile_del(filename, key) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); printf("\n"); textfile_foreach(filename, print_entry, NULL); sprintf(key, "00:00:00:00:00:%02X", 1); if (textfile_del(filename, key) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); sprintf(key, "00:00:00:00:00:%02X", max); if (textfile_del(filename, key) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); sprintf(key, "00:00:00:00:00:%02X", max + 1); if (textfile_del(filename, key) < 0) fprintf(stderr, "%s (%d)\n", strerror(errno), errno); printf("\n"); textfile_foreach(filename, print_entry, NULL); return 0; }
int main (int argc, char *argv[]) { int i, n, fd, c; unsigned long chunk_size[2]; int rank, noProcessors, done; int error; off_t offset; char **chunk_buf; char *read_buf; struct stat stat_buf; ssize_t ret; char *filename = "/mnt/lustre/write_disjoint"; int numloops = 1000; int random = 0; error = MPI_Init(&argc, &argv); if (error != MPI_SUCCESS) rprintf(-1, -1, "MPI_Init failed: %d\n", error); /* Parse command line options */ while ((c = getopt(argc, argv, "f:n:")) != EOF) { switch (c) { case 'f': filename = optarg; break; case 'n': numloops = strtoul(optarg, NULL, 0); break; } } MPI_Comm_size(MPI_COMM_WORLD, &noProcessors); MPI_Comm_rank(MPI_COMM_WORLD, &rank); chunk_buf = malloc(noProcessors * sizeof(chunk_buf[0])); for (i=0; i < noProcessors; i++) { chunk_buf[i] = malloc(CHUNK_MAX_SIZE); memset(chunk_buf[i], 'A'+ i, CHUNK_MAX_SIZE); } read_buf = malloc(noProcessors * CHUNK_MAX_SIZE); if (rank == 0) { fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666); if (fd < 0) rprintf(rank, -1, "open() returned %s\n", strerror(errno)); } MPI_Barrier(MPI_COMM_WORLD); fd = open(filename, O_RDWR); if (fd < 0) rprintf(rank, -1, "open() returned %s\n", strerror(errno)); for (n = 0; n < numloops; n++) { /* reset the environment */ if (rank == 0) { ret = truncate(filename, 0); if (ret != 0) rprintf(rank, n, "truncate() returned %s\n", strerror(errno) ); random = rand(); } MPI_Bcast(&random, 1, MPI_INT, 0, MPI_COMM_WORLD); CHUNK_SIZE(n) = random % CHUNK_MAX_SIZE; if (n % 1000 == 0 && rank == 0) printf("loop %d: chunk_size %lu\n", n, CHUNK_SIZE(n)); if (stat(filename, &stat_buf) < 0) rprintf(rank, n, "error stating %s: %s\n", filename, strerror(errno)); if (stat_buf.st_size != 0) rprintf(rank, n, "filesize = %lu. " "Should be zero after truncate\n", stat_buf.st_size); MPI_Barrier(MPI_COMM_WORLD); /* Do the race */ offset = rank * CHUNK_SIZE(n); lseek(fd, offset, SEEK_SET); done = 0; do { ret = write(fd, chunk_buf[rank] + done, CHUNK_SIZE(n) - done); if (ret < 0 && errno != EINTR) rprintf(rank, n, "write() returned %s\n", strerror(errno)); if (ret > 0) done += ret; } while (done != CHUNK_SIZE(n)); MPI_Barrier(MPI_COMM_WORLD); /* Check the result */ if (stat(filename, &stat_buf) < 0) rprintf(rank, n, "error stating %s: %s\n", filename, strerror(errno)); if (stat_buf.st_size != CHUNK_SIZE(n) * noProcessors) { if (n > 0) printf("loop %d: chunk_size %lu, " "file size was %lu\n", n - 1, CHUNK_SIZE(n - 1), CHUNK_SIZE(n - 1) *noProcessors); rprintf(rank, n, "invalid file size %lu" " instead of %lu = %lu * %u\n", (unsigned long)stat_buf.st_size, CHUNK_SIZE(n) * noProcessors, CHUNK_SIZE(n), noProcessors); } if (rank == 0) { if (lseek(fd, 0, SEEK_SET) < 0) rprintf(rank, n, "error seeking to 0: %s\n", strerror(errno)); done = 0; do { ret = read(fd, read_buf + done, CHUNK_SIZE(n) * noProcessors - done); if (ret < 0) rprintf(rank, n, "read returned %s\n", strerror(errno)); done += ret; } while (done != CHUNK_SIZE(n) * noProcessors); for (i = 0; i < noProcessors; i++) { char command[4096]; int j; if (!memcmp(read_buf + (i * CHUNK_SIZE(n)), chunk_buf[i], CHUNK_SIZE(n))) continue; /* print out previous chunk sizes */ if (n > 0) printf("loop %d: chunk_size %lu\n", n - 1, CHUNK_SIZE(n - 1)); printf("loop %d: chunk %d corrupted " "with chunk_size %lu, page_size %d\n", n, i, CHUNK_SIZE(n), getpagesize()); printf("ranks:\tpage boundry\tchunk boundry\t" "page boundry\n"); for (j = 1 ; j < noProcessors; j++) { int b = j * CHUNK_SIZE(n); printf("%c -> %c:\t%d\t%d\t%d\n", 'A' + j - 1, 'A' + j, b & ~(getpagesize()-1), b, (b + getpagesize()) & ~(getpagesize()-1)); } sprintf(command, "od -Ad -a %s", filename); ret = system(command); rprintf(0, n, "data check error - exiting\n"); } } MPI_Barrier(MPI_COMM_WORLD); } printf("Finished after %d loops\n", n); MPI_Finalize(); return 0; }
// Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool FontInfoTable::DeSerialize(TFile* fp) { truncate(0); return this->DeSerializeClasses(fp); }
struct blk * div(struct blk *ddivd,struct blk *ddivr) { int divsign,remsign,offset,divcarry = 0; int carry, dig = 0,magic,d = 0,dd; long c,td,cc; struct blk *ps; register struct blk *p,*divd,*divr; rem = 0; p = salloc(0); if(length(ddivr) == 0){ pushp(ddivr); printf("divide by 0\n"); return NULL; } divsign = remsign = 0; divr = ddivr; fsfile(divr); if(sbackc(divr) == -1){ divr = copy(ddivr,length(ddivr)); chsign(divr); divsign = ~divsign; } divd = copy(ddivd,length(ddivd)); fsfile(divd); if(sfbeg(divd) == 0 && sbackc(divd) == -1){ chsign(divd); divsign = ~divsign; remsign = ~remsign; } offset = length(divd) - length(divr); if(offset < 0)goto ddone; seekc(p,offset+1); sputc(divd,0); magic = 0; fsfile(divr); c = sbackc(divr); if(c<10)magic++; c = c*100 + (sfbeg(divr)?0:sbackc(divr)); if(magic>0){ c = (c*100 +(sfbeg(divr)?0:sbackc(divr)))*2; c /= 25; } while(offset >= 0){ fsfile(divd); td = sbackc(divd)*100; dd = sfbeg(divd)?0:sbackc(divd); td = (td+dd)*100; dd = sfbeg(divd)?0:sbackc(divd); td = td+dd; cc = c; if(offset == 0)td += 1; else cc += 1; if(magic != 0)td = td<<3; dig = td/cc; rewind(divr); rewind(divxyz); carry = 0; while(sfeof(divr) == 0){ d = sgetc(divr)*dig+carry; carry = d / 100; salterc(divxyz,d%100); } salterc(divxyz,carry); rewind(divxyz); seekc(divd,offset); carry = 0; while(sfeof(divd) == 0){ d = slookc(divd); d = d-(sfeof(divxyz)?0:sgetc(divxyz))-carry; carry = 0; if(d < 0){ d += 100; carry = 1; } salterc(divd,d); } divcarry = carry; sbackc(p); salterc(p,dig); sbackc(p); if(--offset >= 0){ if(d > 0){ sbackc(divd); dd=sbackc(divd); salterc(divd,dd+100); } divd->wt--; } } if(divcarry != 0){ salterc(p,dig-1); salterc(divd,-1); ps = add(divr,divd); release(divd); divd = ps; } rewind(p); divcarry = 0; while(sfeof(p) == 0){ d = slookc(p)+divcarry; divcarry = 0; if(d >= 100){ d -= 100; divcarry = 1; } salterc(p,d); } if(divcarry != 0)salterc(p,divcarry); fsfile(p); while(sfbeg(p) == 0){ if(sbackc(p) == 0)truncate(p); else break; } if(divsign < 0)chsign(p); fsfile(divd); while(sfbeg(divd) == 0){ if(sbackc(divd) == 0)truncate(divd); else break; } ddone: if(remsign<0)chsign(divd); if(divr != ddivr)release(divr); rem = divd; return(p); }
int voice_get_message(char *name, char *timestr, int save) { vaheader_t header; char line_i[MODEM_BUFFER_LEN + 1]; char line_o[MODEM_BUFFER_LEN + 1]; int byte_i; int byte_o; int result; int havedle; int savetimeout; int fd; savetimeout = xstrtol(timestr, 90); if (save) log(L_INFO, "Recording \"%s\" (%d secs)...\n", name, savetimeout); else log(L_INFO, "Waiting %d secs for input...\n", savetimeout); if (!voice_set_compression(setup.modem.compression)) { log(L_ERROR, "Can't set voice audio compressen.\n"); return(VOICE_ACTION_ERROR); } if (save) { if ((fd = open(name, O_WRONLY|O_CREAT|O_TRUNC, S_IWUSR|S_IWGRP|S_IWOTH)) == -1) { log(L_ERROR, "Can't create \"%s\".\n", name); return(VOICE_ACTION_ERROR); } truncate(name, 0); voice_set_header(&header); if (!header_put(fd, &header)) { log(L_ERROR, "Can't write vbox audio header.\n"); voice_close_or_unlink(fd, name); return(VOICE_ACTION_ERROR); } } else fd = -1; if (modem_get_nocarrier_state()) { if (save) voice_close_or_unlink(fd, name); return(VOICE_ACTION_LOCALHANGUP); } if (modem_command("AT+VRX", "CONNECT") == 0) { log(L_ERROR, "Can't start record mode.\n"); if (save) voice_close_or_unlink(fd, name); return(VOICE_ACTION_ERROR); } sequencestatus = ST_NO_INPUT; voicestatus = VOICE_ACTION_OK; havedle = FALSE; modem_set_timeout(savetimeout); while (voicestatus == VOICE_ACTION_OK) { byte_o = 0; byte_i = 0; result = 0; while ((byte_o < MODEM_BUFFER_LEN) && (voicestatus == VOICE_ACTION_OK)) { if ((result = modem_raw_read(line_i, 1)) == 1) { byte_i++; if (havedle) { switch (*line_i) { case DLE: line_o[byte_o++] = DLE; break; case ETX: log(L_DEBUG, "Found sequence \"<DLE><ETX>\" (remote hangup)...\n"); voicestatus = VOICE_ACTION_REMOTEHANGUP; break; default: voice_handle_touchtone_dle(*line_i); break; } havedle = FALSE; } else { if (*line_i != DLE) { line_o[byte_o++] = *line_i; } else havedle = TRUE; } } else break; } if (byte_o > 0) { if (save) { log(L_JUNK, "Record: <DATA %d incoming; %d outgoing>\n", byte_i, byte_o); write(fd, line_o, byte_o); } else log(L_JUNK, "Wait: <DATA %d incoming>\n", byte_i); } if ((result != 1) || (modem_get_timeout())) { if (!modem_get_timeout()) { log(L_ERROR, "Can't read incoming data (%s).\n", strerror(errno)); voicestatus = VOICE_ACTION_ERROR; } else voicestatus = VOICE_ACTION_TIMEOUT; } if ((result == 1) && (ctrl_ishere(setup.spool, CTRL_NAME_SUSPEND))) { log(L_INFO, "Control file \"%s\" exists - suspending call...\n", CTRL_NAME_SUSPEND); if (!ctrl_remove(setup.spool, CTRL_NAME_SUSPEND)) { log(L_WARN, "Can't remove control file \"%s\"!\n", CTRL_NAME_SUSPEND); } log(L_JUNK, "Sending \"<DLE><DC4>\"...\n"); printstring(line_o, "%c%c", DLE, DC4); printstring(line_i, "%c%c", DLE, ETX); modem_raw_write(line_o, strlen(line_o)); modem_wait_sequence(line_i); if (modem_command("", "VCON")>0) { #ifdef VBOX_SUSPEND_VALUE printstring(line_o, "AT+S%d", VBOX_SUSPEND_VALUE); #else printstring(line_o, "AT+S"); #endif if (modem_command(line_o, "OK") <= 0) { log(L_WARN, "Can't suspend call\n"); } else { log(L_INFO, "Call suspended\n"); voicestatus = VOICE_ACTION_REMOTEHANGUP; } } } if ((voicestatus == VOICE_ACTION_OK) || (voicestatus == VOICE_ACTION_TIMEOUT)) { if ((index(touchtones, '#')) && (index(touchtones, '*'))) { log(L_DEBUG, "Touchtone sequence \"%s\" found.\n", touchtones); if (breaklist_search(touchtones)) { log(L_INFO, "Sequence \"%s\" found in breaklist...\n", touchtones); voicestatus = VOICE_ACTION_TOUCHTONES; } else { log(L_DEBUG, "Sequence \"%s\" not in breaklist (ignored)...\n", touchtones); *touchtones = '\0'; } } } } modem_set_timeout(0); if (save) { voice_close_or_unlink(fd, NULL); permissions_set(name, setup.users.uid, setup.users.gid, S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH, setup.users.umask); } if ((voicestatus == VOICE_ACTION_REMOTEHANGUP) || (modem_get_nocarrier_state())) { /* * Remote hangup: Modem should response with the sequence * NO CARRIER. */ modem_command("", "NO CARRIER"); } else { /* * Local hangup: send <DLE><DC4> to the modem and read the * response <DLE><ETX> and VCON. */ printstring(line_o, "%c%c", DLE, DC4); printstring(line_i, "%c%c", DLE, ETX); log(L_JUNK, "Sending \"<DLE><DC4>\"...\n"); modem_raw_write(line_o, strlen(line_o)); modem_get_sequence(line_i); modem_command("", "VCON"); } if (modem_get_nocarrier_state()) voicestatus = VOICE_ACTION_REMOTEHANGUP; return(voicestatus); }
void executeTruncate(char* filename, int size) { truncate(filename, size); }
int main(int argc, char **argv) { int x = 0; char *args[10]; setuid(2); signal(SIGCHLD, sigchld); do_signals(); x += getpid(); x += getppid(); x += getuid(); x += getgid(); x += setsid(); x += seteuid(); x += setegid(); lseek(0, 0, -1); kill(0, 0); signal(99, 0); signal(SIGINT, int_handler); signal(SIGSEGV, segv_handler); // *(int *) 0 = 0; pipe(0); munmap(0, 0); mincore(0, 0); shmget(0); shmat(0); line = __LINE__; poll(-1, 0, 0); signal(SIGSEGV, SIG_IGN); // ppoll(-1, -1, -1, 0); signal(SIGSEGV, SIG_DFL); sched_yield(); readv(-1, 0, 0, 0); writev(-1, 0, 0, 0); msync(0, 0, 0); fsync(-1); fdatasync(-1); semget(0, 0, 0); semctl(0, 0, 0); uselib(NULL); pivot_root(0, 0); personality(-1); setfsuid(-1); flock(-1, 0); shmdt(0, 0, 0); times(0); mremap(0, 0, 0, 0, 0); madvise(0, 0, 0); fchown(-1, 0, 0); lchown(0, 0, 0); setreuid(); setregid(); link("/nonexistant", "/also-nonexistant"); do_slow(); symlink("/nothing", "/"); rename("/", "/"); mkdir("/junk/stuff////0", 0777); geteuid(); getsid(); getpgid(); getresuid(); getresgid(); getpgid(); ptrace(-1, 0, 0, 0); semop(0, 0, 0); capget(0, 0); line = __LINE__; gettimeofday(0, 0); settimeofday(0, 0); dup(-1); dup2(-1, -1); shmctl(0, 0, 0, 0); execve("/bin/nothing", "/bin/nothing", 0); alarm(9999); bind(0, 0, 0); socket(0, 0, 0); accept(0, 0, 0); listen(0); shutdown(0); getsockname(0, 0, 0); getpeername(0, 0, 0); truncate(0, 0); ftruncate(0, 0); line = __LINE__; if (vfork() == 0) exit(0); line = __LINE__; x = opendir("/", 0, 0); line = __LINE__; readdir(x, 0, 0); line = __LINE__; closedir(x); line = __LINE__; chroot("/"); line = __LINE__; sigaction(0, 0, 0); line = __LINE__; sigprocmask(0, 0, 0); x += open("/nothing", 0); x += chdir("/nothing"); x += mknod("/nothing/nothing", 0); x += ioctl(); execve("/nothing", NULL, NULL); line = __LINE__; x += close(-2); line = __LINE__; if (fork() == 0) exit(0); line = __LINE__; clone(clone_func, 0, 0, 0); line = __LINE__; brk(0); sbrk(0); line = __LINE__; mmap(0, 0, 0, 0, 0); line = __LINE__; uname(0); line = __LINE__; getcwd(0, 0); line = __LINE__; iopl(3); ioperm(0, 0, 0); mount(0, 0, 0, 0, 0); umount(0, 0); umount(0, 0, 0); swapon(0, 0); swapoff(0); sethostname(0); line = __LINE__; time(NULL); unlink("/nothing"); line = __LINE__; rmdir("/nothing"); chmod(0, 0); line = __LINE__; # if defined(__i386) || defined(__amd64) modify_ldt(0); # endif stat("/doing-nice", 0); nice(0); args[0] = "/bin/df"; args[1] = "-l"; args[2] = NULL; close(1); open("/dev/null", O_WRONLY); /***********************************************/ /* Some syscalls arent available direct */ /* from libc, so get them here. We mostly */ /* care about the ones which have caused */ /* implementation difficulty and kernel */ /* crashes - eventually we can be complete. */ /***********************************************/ line = __LINE__; open("/system-dependent-syscalls-follow", 0); line = __LINE__; if (fork() == 0) exit(0); {int status; while (wait(&status) >= 0) ; } sigaltstack(0, 0); /*vm86(0, 0);*/ /***********************************************/ /* Some syscalls arent directly accessible, */ /* e.g. legacy. */ /***********************************************/ #if defined(__x86_64__) trace(__LINE__, "x64 syscalls"); syscall(174, 0, 0, 0); // create_module syscall(176, 0, 0, 0); // delete_module syscall(178, 0, 0, 0); // query_module #else trace(__LINE__, "x32 syscalls"); syscall(0, 0, 0, 0); // restart_syscall syscall(34, 0, 0, 0); // nice syscall(59, 0, 0, 0); // oldolduname syscall(109, 0, 0, 0); // olduname if (fork() == 0) syscall(1, 0, 0, 0); // exit #endif line = __LINE__; execve("/bin/df", args, NULL); fprintf(stderr, "Error: should not get here -- %s\n", strerror(errno)); exit(1); }
bool operator()(GLushort i1, GLushort i2) { // Is this so horribly naive that it's completely unrealistic? return distanceSqr(m_eye, truncate(m_positions[i1])) > distanceSqr(m_eye, truncate(m_positions[i2])); }
/*! * \brief Output all-class information to file. * \param snapshot [in] Snapshot instance. * \param rank [out] Sorted-class information. * \return Value is zero, if process is succeed.<br /> * Value is error number a.k.a. "errno", if process is failure. */ int TClassContainer::afterTakeSnapShot(TSnapShotContainer *snapshot, TSorter<THeapDelta> **rank) { /* Sanity check. */ if (unlikely(snapshot == NULL || rank == NULL)) { return 0; } /* Copy header. */ TSnapShotFileHeader hdr; memcpy(&hdr, (const void *)snapshot->getHeader(), sizeof(TSnapShotFileHeader)); /* If java heap usage alert is enable. */ if (conf->getHeapAlertThreshold() > 0) { jlong usage = hdr.newAreaSize + hdr.oldAreaSize; if (usage > conf->getHeapAlertThreshold()) { /* Raise alert. */ logger->printWarnMsg( "ALERT: Java heap usage exceeded the threshold (%ld MB)", usage / 1024 / 1024); /* If need send trap. */ if (conf->SnmpSend()->get()) { if (unlikely(!sendMemoryUsageAlertTrap(pSender, ALERT_JAVA_HEAP, hdr.snapShotTime, usage, jvmInfo->getMaxMemory()))) { logger->printWarnMsg("SNMP trap send failed!"); } } } } /* If metaspace usage alert is enable. */ if ((conf->MetaspaceThreshold()->get() > 0) && ((conf->MetaspaceThreshold()->get() * 1024 * 1024) < hdr.metaspaceUsage)) { const char *label = jvmInfo->isAfterCR6964458() ? "Metaspace" : "PermGen"; /* Raise alert. */ logger->printWarnMsg("ALERT: %s usage exceeded the threshold (%ld MB)", label, hdr.metaspaceUsage / 1024 / 1024); /* If need send trap. */ if (conf->SnmpSend()->get()) { if (unlikely(!sendMemoryUsageAlertTrap( pSender, ALERT_METASPACE, hdr.snapShotTime, hdr.metaspaceUsage, hdr.metaspaceCapacity))) { logger->printWarnMsg("SNMP trap send failed!"); } } } /* Class map used snapshot output. */ TClassMap *workClsMap = NULL; /* Get class container's spin lock. */ spinLockWait(&lockval); { try { workClsMap = new TClassMap(*this->classMap); } catch (...) { workClsMap = NULL; } } /* Release class container's spin lock. */ spinLockRelease(&lockval); if (unlikely(workClsMap == NULL)) { int raisedErrNum = errno; logger->printWarnMsgWithErrno("Couldn't allocate working memory!"); return raisedErrNum; } /* Allocate return array. */ jlong rankCnt = workClsMap->size(); rankCnt = (rankCnt < conf->RankLevel()->get()) ? rankCnt : conf->RankLevel()->get(); /* Make controller to sort. */ register TRankOrder order = conf->Order()->get(); TSorter<THeapDelta> *sortArray; try { sortArray = new TSorter<THeapDelta>( rankCnt, (TComparator)((order == DELTA) ? &HeapDeltaCmp : &HeapUsageCmp)); } catch (...) { int raisedErrNum = errno; logger->printWarnMsgWithErrno("Couldn't allocate working memory!"); delete workClsMap; return raisedErrNum; } /* Open file and seek EOF. */ int fd = open(conf->FileName()->get(), O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); /* If failure open file. */ if (unlikely(fd < 0)) { int raisedErrNum = errno; logger->printWarnMsgWithErrno("Could not open %s", conf->FileName()->get()); delete sortArray; delete workClsMap; return raisedErrNum; } off_t oldFileOffset = -1; try { /* Move position to EOF. */ oldFileOffset = lseek(fd, 0, SEEK_END); /* If failure seek. */ if (unlikely(oldFileOffset < 0)) { throw 1; } /* Frist, Output each classes information. Secondly output header. */ if (unlikely(lseek(fd, sizeof(TSnapShotFileHeader) - sizeof(char[80]) + hdr.gcCauseLen, SEEK_CUR) < 0)) { throw 1; } } catch (...) { int raisedErrNum = errno; logger->printWarnMsg("Could not write snapshot"); close(fd); delete sortArray; delete workClsMap; return raisedErrNum; } /* Output class information. */ THeapDelta result; jlong numEntries = 0L; int raiseErrorCode = 0; register jlong AlertThreshold = conf->getAlertThreshold(); /* Loop each class. */ for (TClassMap::iterator it = workClsMap->begin(); it != workClsMap->end(); ++it) { TObjectData *objData = (*it).second; TClassCounter *cur = snapshot->findClass(objData); /* If don't registed class yet. */ if (unlikely(cur == NULL)) { cur = snapshot->pushNewClass(objData); if (unlikely(cur == NULL)) { raiseErrorCode = errno; logger->printWarnMsgWithErrno("Couldn't allocate working memory!"); delete sortArray; sortArray = NULL; break; } } /* Calculate uasge and delta size. */ result.usage = cur->counter->total_size; result.delta = cur->counter->total_size - objData->oldTotalSize; result.tag = objData->tag; objData->oldTotalSize = result.usage; /* If do output class. */ if (!conf->ReduceSnapShot()->get() || (result.usage > 0)) { /* Output class-information. */ if (likely(raiseErrorCode == 0)) { raiseErrorCode = writeClassData(fd, objData, cur); } numEntries++; } /* Ranking sort. */ sortArray->push(result); /* If alert is enable. */ if (AlertThreshold > 0) { /* Variable for send trap. */ int sendFlag = 0; /* If size is bigger more limit size. */ if ((order == DELTA) && (AlertThreshold <= result.delta)) { /* Raise alert. */ logger->printWarnMsg( "ALERT(DELTA): \"%s\" exceeded the threshold (%ld bytes)", objData->className, result.delta); /* Set need send trap flag. */ sendFlag = 1; } else if ((order == USAGE) && (AlertThreshold <= result.usage)) { /* Raise alert. */ logger->printWarnMsg( "ALERT(USAGE): \"%s\" exceeded the threshold (%ld bytes)", objData->className, result.usage); /* Set need send trap flag. */ sendFlag = 1; } /* If need send trap. */ if (conf->SnmpSend()->get() && sendFlag != 0) { if (unlikely(!sendHeapAlertTrap(pSender, result, objData->className, cur->counter->count))) { logger->printWarnMsg("Send SNMP trap failed!"); } } } } delete workClsMap; /* Set output entry count. */ hdr.size = numEntries; /* Stored error number to avoid overwriting by "truncate" and etc.. */ int raisedErrNum = 0; try { /* If already failed in processing to write snapshot. */ if (unlikely(raiseErrorCode != 0)) { errno = raiseErrorCode; raisedErrNum = raiseErrorCode; throw 1; } /* If fail seeking to header position. */ if (unlikely(lseek(fd, oldFileOffset, SEEK_SET) < 0)) { raisedErrNum = errno; throw 2; } raisedErrNum = writeHeader(fd, hdr); /* If failed to write a snapshot header. */ if (unlikely(raisedErrNum != 0)) { throw 3; } } catch (...) { ; /* Failed to write file. */ } /* Clean up. */ if (unlikely(close(fd) != 0 && raisedErrNum == 0)) { errno = raisedErrNum; logger->printWarnMsgWithErrno("Could not write snapshot"); } /* If need rollback snapshot. */ if (unlikely(raisedErrNum != 0)) { if (unlikely(truncate(conf->FileName()->get(), oldFileOffset) < 0)) { logger->printWarnMsgWithErrno("Could not rollback snapshot"); } } /* Cleanup. */ (*rank) = sortArray; return raisedErrNum; }
template<class T> inline void BasicArray<T>::clear() { truncate(0); // Throws }
Npfcall* diod_setattr (Npfid *fid, u32 valid, u32 mode, u32 uid, u32 gid, u64 size, u64 atime_sec, u64 atime_nsec, u64 mtime_sec, u64 mtime_nsec) { Npfcall *ret; Fid *f = fid->aux; int ctime_updated = 0; if ((f->flags & DIOD_FID_FLAGS_ROFS)) { np_uerror (EROFS); goto error_quiet; } if ((valid & P9_ATTR_MODE)) { /* N.B. derefs symlinks */ if (chmod (path_s (f->path), mode) < 0) { np_uerror(errno); goto error_quiet; } ctime_updated = 1; } if ((valid & P9_ATTR_UID) || (valid & P9_ATTR_GID)) { if (lchown (path_s (f->path), (valid & P9_ATTR_UID) ? uid : -1, (valid & P9_ATTR_GID) ? gid : -1) < 0){ np_uerror(errno); goto error_quiet; } ctime_updated = 1; } if ((valid & P9_ATTR_SIZE)) { if (truncate (path_s (f->path), size) < 0) { np_uerror(errno); goto error_quiet; } ctime_updated = 1; } if ((valid & P9_ATTR_ATIME) || (valid & P9_ATTR_MTIME)) { #if HAVE_UTIMENSAT struct timespec ts[2]; if (!(valid & P9_ATTR_ATIME)) { ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_OMIT; } else if (!(valid & P9_ATTR_ATIME_SET)) { ts[0].tv_sec = 0; ts[0].tv_nsec = UTIME_NOW; } else { ts[0].tv_sec = atime_sec; ts[0].tv_nsec = atime_nsec; } if (!(valid & P9_ATTR_MTIME)) { ts[1].tv_sec = 0; ts[1].tv_nsec = UTIME_OMIT; } else if (!(valid & P9_ATTR_MTIME_SET)) { ts[1].tv_sec = 0; ts[1].tv_nsec = UTIME_NOW; } else { ts[1].tv_sec = mtime_sec; ts[1].tv_nsec = mtime_nsec; } if (utimensat(-1, path_s (f->path), ts, AT_SYMLINK_NOFOLLOW) < 0) { np_uerror(errno); goto error_quiet; } #else /* HAVE_UTIMENSAT */ struct timeval tv[2], now, *tvp; struct stat sb; if ((valid & P9_ATTR_ATIME) && !(valid & P9_ATTR_ATIME_SET) && (valid & P9_ATTR_MTIME) && !(valid & P9_ATTR_MTIME_SET)) { tvp = NULL; /* set both to now */ } else { if (lstat(path_s (f->path), &sb) < 0) { np_uerror (errno); goto error_quiet; } if (gettimeofday (&now, NULL) < 0) { np_uerror (errno); goto error_quiet; } if (!(valid & P9_ATTR_ATIME)) { tv[0].tv_sec = sb.st_atim.tv_sec; tv[0].tv_usec = sb.st_atim.tv_nsec / 1000; } else if (!(valid & P9_ATTR_ATIME_SET)) { tv[0].tv_sec = now.tv_sec; tv[0].tv_usec = now.tv_usec; } else { tv[0].tv_sec = atime_sec; tv[0].tv_usec = atime_nsec / 1000; } if (!(valid & P9_ATTR_MTIME)) { tv[1].tv_sec = sb.st_mtim.tv_sec; tv[1].tv_usec = sb.st_mtim.tv_nsec / 1000; } else if (!(valid & P9_ATTR_MTIME_SET)) { tv[1].tv_sec = now.tv_sec; tv[1].tv_usec = now.tv_usec; } else { tv[1].tv_sec = mtime_sec; tv[1].tv_usec = mtime_nsec / 1000; } tvp = tv; } if (utimes (path_s (f->path), tvp) < 0) { np_uerror(errno); goto error_quiet; } #endif /* HAVE_UTIMENSAT */ ctime_updated = 1; } if ((valid & P9_ATTR_CTIME) && !ctime_updated) { if (lchown (path_s (f->path), -1, -1) < 0) { np_uerror (errno); goto error_quiet; } } if (!(ret = np_create_rsetattr())) { np_uerror (ENOMEM); goto error; } return ret; error: errn (np_rerror (), "diod_setattr %s@%s:%s (valid=0x%x)", fid->user->uname, np_conn_get_client_id (fid->conn), path_s (f->path), valid); error_quiet: return NULL; }
/* * clear instream */ static int clear_file(const char *name) { return (truncate(name, 0)); }
void V1_minix_truncate(struct inode * inode) { truncate(inode); }
void DescriptionManager::configurationUpdated() { MaxNumberOfDescriptions = Application::instance()->configuration()->deprecatedApi()->readNumEntry("General", "NumberOfDescriptions"); truncate(); }
/* * === FUNCTION ============================================================= * Name: start_next_ad * Description: Styr muxar, ad och anropar omvandlingar samt anropar bussen * för att skicka data. Det här kan ses som * sensorenhetens huvudprogram då alla * andra funktioner anropas härifrån. * ============================================================================ */ void start_next_ad() { unsigned char state=control_mux(); if (state==1){ //left_front klar if(maze_mode==1 && auto_mode==1){ header = 0xC1; //Skicka till // styr&pc med E-flagga } else if(maze_mode == 0 && auto_mode==1){ //linjeläge header = 0x91; //Skicka till pc } else { header = 0x80; } data=dist_left_front; req_sending(); } else if (state==2){ //left_back klar if(maze_mode==1 && auto_mode==1){ header = 0xC5; //Skicka till styr&pc med E-flagga } else if(maze_mode == 0 && auto_mode==1){ //linjeläge header = 0x95; //Skicka till pc } else { header = 0x84; } data= dist_left_back; req_sending(); } else if (state==3){ //right_front klar if(maze_mode==1 && auto_mode==1){ header = 0xC9; //Skicka till styr&pc med E-flagga } else if(maze_mode == 0 && auto_mode==1){ //linjeläge header = 0x99; //Skicka till pc } else if(auto_mode == 0) { header = 0x88; } data= dist_right_front; req_sending(); } else if (state==4){ //right_back klar if(maze_mode==1 && auto_mode==1){ header = 0xCD; //Skicka till styr&pc med E-flagga } else if(maze_mode == 0 && auto_mode==1){ //linjeläge header = 0x9D; //Skicka till pc } else { header = 0x8C; } data= dist_right_back; req_sending(); } else if(state==5){ //front klar if(display_ctr == 10){ data_to_display(dist_right_front,0x00); data_to_display(dist_left_front,0x01); data_to_display(dist_right_back,0x02); data_to_display(dist_left_back,0x03); data_to_display(dist_front,0x04); if(maze_mode == 1){ data_to_display(// (get_next_special_command()/16+100),// 0x05); } else{ data_to_display(// get_next_special_command()/16,0x05); } display_ctr = 0; } display_ctr++; } else if(state==6){ header=0x4D; data=dist_right_short | 0x80; req_sending(); } else if(state==7){ header=0x4D; data=dist_left_short | 0xC0; req_sending(); } else if(state==8){ //linjesensor 0-7 pågår create_line_array(truncate(ADCH), 1); } else if(state==9){ //linjesensor 8-10 pågår create_line_array(truncate(ADCH), 2); } if (count==17){ //alla linjesensorer omvandlade if (maze_mode==0 && auto_mode==1){ //kod som kollar om banan är s**t data=calculate_diff(line_array_1, line_array_2); if(data==0x60){ //bana s**t? header=0xC3; //skicka till styr och dator //med stopp-kod, D-flagga satt } else { header=0x51; //Skicka till styr med A- och //E-flagga } req_sending(); //inga linjer? byt till maze_mode=1 om väggar finns if(line_array_1==0 && line_array_2==0) { decide_maze_mode(1); } } else if(maze_mode==1 && auto_mode==1){ int temp = markning(find_ones(line_array_1)); generate_special_command(temp); int temp2 = search_for_crossroad(); if(temp2==1){ send_special_command(get_next_special_command() | 0x01); //Resetar next_special_command generate_special_command(4); } else if(temp2==2){ send_special_command(get_next_special_command() | 0x02); //Resetar next_special_command generate_special_command(4); } else if(temp2==3 && (get_next_special_command()==0x10)) { generate_special_command(4); } else if(temp2==4){ //vanlig 90 högersväng header=0xC3; if(duplicate==1){ data=0x00; duplicate=0; } else { duplicate=1; data=0x40; } req_sending(); } else if(temp2==5){ //vanlig 90 vänstersväng header=0xC3; if(duplicate==1){ data=0x00; duplicate=0; } else { duplicate=1; data=0x50; } req_sending(); } //linjer? byt till maze_mode=0 om inga väggar finns if(line_array_1!=0 || line_array_2!=0) { decide_maze_mode(0); } } create_line_array(0,0); //Nollställ } else if (count<17){ count++; ADCSRA |= (1<<ADSC); //starta nästa omvandling } }
int main(int argc, char *argv[]) { bool newrc, already; int rcfirst = 0; /* first message to print (from .rc) */ int rcback = 0; /* amount to back off of rcfirst */ int firstmsg = 0, nextmsg = 0, lastmsg = 0; int blast = 0; struct stat buf; /* stat to check access of bounds */ FILE *bounds; char *cp; #ifdef UNBUFFERED setbuf(stdout, NULL); #endif setlocale(LC_ALL, ""); time(&t); if (setuid(uid = getuid()) != 0) err(1, "setuid failed"); ruptible = (signal(SIGINT, SIG_IGN) == SIG_DFL); if (ruptible) signal(SIGINT, SIG_DFL); argc--, argv++; while (argc > 0) { if (isdigit(argv[0][0])) { /* starting message # */ rcfirst = atoi(argv[0]); } else if (isdigit(argv[0][1])) { /* backward offset */ rcback = atoi( &( argv[0][1] ) ); } else { ptr = *argv; while (*ptr) switch (*ptr++) { case '-': break; case 'c': if (uid != SUPERUSER && uid != DAEMON) errx(1, "only the super-user can use the c flag"); clean = YES; break; case 'f': /* silently */ hush = YES; break; case 'h': /* headers only */ hdrs = YES; break; case 'l': /* local msgs only */ locomode = YES; break; case 'o': /* option to save last message */ lastcmd = YES; break; case 'p': /* pipe thru 'more' during long msgs */ use_pager = YES; break; case 'q': /* query only */ qopt = YES; break; case 's': /* sending TO msgs */ send_msg = YES; break; default: usage(); } } argc--, argv++; } /* * determine current message bounds */ snprintf(fname, sizeof(fname), "%s/%s", _PATH_MSGS, BOUNDS); /* * Test access rights to the bounds file * This can be a little tricky. if(send_msg), then * we will create it. We assume that if(send_msg), * then you have write permission there. * Else, it better be there, or we bail. */ if (send_msg != YES) { if (stat(fname, &buf) < 0) { if (hush != YES) { err(errno, "%s", fname); } else { exit(1); } } } bounds = fopen(fname, "r"); if (bounds != NULL) { fscanf(bounds, "%d %d\n", &firstmsg, &lastmsg); fclose(bounds); blast = lastmsg; /* save upper bound */ } if (clean) keep = t - (rcback? rcback : NDAYS) DAYS; if (clean || bounds == NULL) { /* relocate message bounds */ struct dirent *dp; struct stat stbuf; bool seenany = NO; DIR *dirp; dirp = opendir(_PATH_MSGS); if (dirp == NULL) err(errno, "%s", _PATH_MSGS); firstmsg = 32767; lastmsg = 0; for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)){ cp = dp->d_name; int i = 0; if (dp->d_ino == 0) continue; if (dp->d_namlen == 0) continue; if (clean) snprintf(inbuf, sizeof(inbuf), "%s/%s", _PATH_MSGS, cp); while (isdigit(*cp)) i = i * 10 + *cp++ - '0'; if (*cp) continue; /* not a message! */ if (clean) { if (stat(inbuf, &stbuf) != 0) continue; if (stbuf.st_mtime < keep && stbuf.st_mode&S_IWRITE) { unlink(inbuf); continue; } } if (i > lastmsg) lastmsg = i; if (i < firstmsg) firstmsg = i; seenany = YES; } closedir(dirp); if (!seenany) { if (blast != 0) /* never lower the upper bound! */ lastmsg = blast; firstmsg = lastmsg + 1; } else if (blast > lastmsg) lastmsg = blast; if (!send_msg) { bounds = fopen(fname, "w"); if (bounds == NULL) err(errno, "%s", fname); chmod(fname, CMODE); fprintf(bounds, "%d %d\n", firstmsg, lastmsg); fclose(bounds); } } if (send_msg) { /* * Send mode - place msgs in _PATH_MSGS */ bounds = fopen(fname, "w"); if (bounds == NULL) err(errno, "%s", fname); nextmsg = lastmsg + 1; snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, nextmsg); newmsg = fopen(fname, "w"); if (newmsg == NULL) err(errno, "%s", fname); chmod(fname, CMODE); fprintf(bounds, "%d %d\n", firstmsg, nextmsg); fclose(bounds); sending = YES; if (ruptible) signal(SIGINT, onintr); if (isatty(fileno(stdin))) { ptr = getpwuid(uid)->pw_name; printf("Message %d:\nFrom %s %sSubject: ", nextmsg, ptr, ctime(&t)); fflush(stdout); fgets(inbuf, sizeof inbuf, stdin); putchar('\n'); fflush(stdout); fprintf(newmsg, "From %s %sSubject: %s\n", ptr, ctime(&t), inbuf); blankline = seensubj = YES; } else blankline = seensubj = NO; for (;;) { fgets(inbuf, sizeof inbuf, stdin); if (feof(stdin) || ferror(stdin)) break; blankline = (blankline || (inbuf[0] == '\n')); seensubj = (seensubj || (!blankline && (strncmp(inbuf, "Subj", 4) == 0))); fputs(inbuf, newmsg); } #ifdef OBJECT if (!seensubj) { printf("NOTICE: Messages should have a Subject field!\n"); #ifdef REJECT unlink(fname); #endif exit(1); } #endif exit(ferror(stdin)); } if (clean) exit(0); /* * prepare to display messages */ totty = (isatty(fileno(stdout)) != 0); use_pager = use_pager && totty; if ((cp = getenv("HOME")) == NULL || *cp == '\0') { fprintf(stderr, "Error, no home directory!\n"); exit(1); } snprintf(fname, sizeof(fname), "%s/%s", cp, MSGSRC); msgsrc = fopen(fname, "r"); if (msgsrc) { newrc = NO; fscanf(msgsrc, "%d\n", &nextmsg); fclose(msgsrc); if (nextmsg > lastmsg+1) { printf("Warning: bounds have been reset (%d, %d)\n", firstmsg, lastmsg); truncate(fname, (off_t)0); newrc = YES; } else if (!rcfirst) rcfirst = nextmsg - rcback; } else newrc = YES; msgsrc = fopen(fname, "r+"); if (msgsrc == NULL) msgsrc = fopen(fname, "w"); if (msgsrc == NULL) err(errno, "%s", fname); if (rcfirst) { if (rcfirst > lastmsg+1) { printf("Warning: the last message is number %d.\n", lastmsg); rcfirst = nextmsg; } if (rcfirst > firstmsg) firstmsg = rcfirst; /* don't set below first msg */ } if (newrc) { nextmsg = firstmsg; rewind(msgsrc); fprintf(msgsrc, "%d\n", nextmsg); fflush(msgsrc); } #ifdef V7 if (totty) { struct winsize win; if (ioctl(fileno(stdout), TIOCGWINSZ, &win) != -1) Lpp = win.ws_row; if (Lpp <= 0) { if (tgetent(inbuf, getenv("TERM")) <= 0 || (Lpp = tgetnum("li")) <= 0) { Lpp = NLINES; } } } #endif Lpp -= 6; /* for headers, etc. */ already = NO; prevmsg = firstmsg; printing = YES; if (ruptible) signal(SIGINT, onintr); /* * Main program loop */ for (msg = firstmsg; msg <= lastmsg; msg++) { snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, msg); newmsg = fopen(fname, "r"); if (newmsg == NULL) continue; gfrsub(newmsg); /* get From and Subject fields */ if (locomode && !local) { fclose(newmsg); continue; } if (qopt) { /* This has to be located here */ printf("There are new messages.\n"); exit(0); } if (already && !hdrs) putchar('\n'); /* * Print header */ if (totty) signal(SIGTSTP, onsusp); (void) setjmp(tstpbuf); already = YES; nlines = 2; if (seenfrom) { printf("Message %d:\nFrom %s %s", msg, from, date); nlines++; } if (seensubj) { printf("Subject: %s", subj); nlines++; } else { if (seenfrom) { putchar('\n'); nlines++; } while (nlines < 6 && fgets(inbuf, sizeof inbuf, newmsg) && inbuf[0] != '\n') { fputs(inbuf, stdout); nlines++; } } lct = linecnt(newmsg); if (lct) printf("(%d%sline%s) ", lct, seensubj? " " : " more ", (lct == 1) ? "" : "s"); if (hdrs) { printf("\n-----\n"); fclose(newmsg); continue; } /* * Ask user for command */ if (totty) ask(lct? MORE : (msg==lastmsg? NOMORE : NEXT)); else inbuf[0] = 'y'; if (totty) signal(SIGTSTP, SIG_DFL); cmnd: in = inbuf; switch (*in) { case 'x': /* FALLTHROUGH */ case 'X': exit(0); /* NOTREACHED */ case 'q': /* FALLTHROUGH */ case 'Q': quitit = YES; printf("--Postponed--\n"); exit(0); /* NOTREACHED */ case 'n': /* FALLTHROUGH */ case 'N': if (msg >= nextmsg) sep = "Flushed"; prevmsg = msg; break; case 'p': /* FALLTHROUGH */ case 'P': use_pager = (*in++ == 'p'); /* FALLTHROUGH */ case '\n': /* FALLTHROUGH */ case 'y': default: if (*in == '-') { msg = prevmsg-1; sep = "replay"; break; } if (isdigit(*in)) { msg = next(in); sep = in; break; } prmesg(nlines + lct + (seensubj? 1 : 0)); prevmsg = msg; } printf("--%s--\n", sep); sep = "-"; if (msg >= nextmsg) { nextmsg = msg + 1; rewind(msgsrc); fprintf(msgsrc, "%d\n", nextmsg); fflush(msgsrc); } if (newmsg) fclose(newmsg); if (quitit) break; } /* * Make sure .rc file gets updated */ if (--msg >= nextmsg) { nextmsg = msg + 1; rewind(msgsrc); fprintf(msgsrc, "%d\n", nextmsg); fflush(msgsrc); } if (already && !quitit && lastcmd && totty) { /* * save or reply to last message? */ msg = prevmsg; ask(NOMORE); if (inbuf[0] == '-' || isdigit(inbuf[0])) goto cmnd; } if (!(already || hush || qopt)) printf("No new messages.\n"); exit(0); /* NOTREACHED */ }