void wildcard_expander_t::expand_trailing_slash(const wcstring &base_dir, const wcstring &prefix) { if (interrupted()) { return; } if (!(flags & EXPAND_FOR_COMPLETIONS)) { // Trailing slash and not accepting incomplete, e.g. `echo /xyz/`. Insert this file if it // exists. if (waccess(base_dir, F_OK) == 0) { this->add_expansion_result(base_dir); } } else { // Trailing slashes and accepting incomplete, e.g. `echo /xyz/<tab>`. Everything is added. DIR *dir = open_dir(base_dir); if (dir) { wcstring next; while (wreaddir(dir, next) && !interrupted()) { if (!next.empty() && next.at(0) != L'.') { this->try_add_completion_result(base_dir + next, next, L"", prefix); } } closedir(dir); } } }
void QLClient::listen() { IO::QuakeLink::RequestFormat rf = _config->gzip ? (_config->native ? IO::QuakeLink::rfGZNative : IO::QuakeLink::rfGZXML) : (_config->native ? IO::QuakeLink::rfNative : IO::QuakeLink::rfXML); // activate socket timeout if keepAlive was requested if ( _config->options & IO::QuakeLink::opKeepAlive ) { if ( _sock ) { _sock->setTimeout(60); } else { SEISCOMP_ERROR("%sinstance not initialized", _logPrefix.c_str()); return; } } while ( !interrupted() ) { // determine start time of request Core::Time from; string filter = _config->filter; if ( _backLog > 0 ) { Core::Time minTime = Core::Time::GMT() - Core::TimeSpan(_backLog); from = lastUpdate(); if ( !from.valid() || from < minTime ) from = minTime; if ( !filter.empty() ) filter += " AND "; filter += "UPDATED > " + from.toString(IO::QuakeLink::RequestTimeFormat); } // start request try { select(from.valid(), Core::Time(), Core::Time(), rf, filter); } catch ( Core::GeneralException& e) { if ( interrupted() ) break; SEISCOMP_DEBUG("%sselect exception: %s", _logPrefix.c_str(), e.what()); } _sock->close(); // clears interrupt flag SEISCOMP_WARNING("%sQuakeLink connection closed, trying to reconnect " "in 5s", _logPrefix.c_str()); for ( int i = 0; i < 50; ++i ) { usleep(100000); // 100ms if ( interrupted() ) break; } } if ( interrupted() ) SEISCOMP_INFO("%sQuakeLink connection interrupted", _logPrefix.c_str()); _sock->close(); }
void HttpGetFiles::run() { QRegExp rx("file=(.*)"); m_status = Running; QStringList::iterator iter; for (iter = m_fileList.begin(); iter != m_fileList.end(); ++iter) { QString source(*iter); if (rx.indexIn(source, 0) != -1) { QString destination(m_destinationPath); destination += "/" + rx.cap(1); HttpGet* reply(new HttpGet(m_connection, source, destination)); m_replies.append(reply); connect(this, SIGNAL(interrupted()), this, SLOT(interrupt())); connect(reply, SIGNAL(finished()), this, SLOT(replyFinished())); connect(reply, SIGNAL(copyProgress()), this, SLOT(copyProgress())); } } QList<HttpGet*> replies(m_replies); QList<HttpGet*>::iterator reply; for (reply = replies.begin(); reply != replies.end(); ++reply) { (*reply)->run(); } }
static ssize_t net_send(Connection* c, const void* d, size_t size) { size_t sendsize = 0; while(size > sendsize) { #ifdef WIN32 ssize_t n = TEMP_FAILURE_RETRY(send(c->fd, (const char*)d + sendsize, size - sendsize, 0)); #else ssize_t n = TEMP_FAILURE_RETRY(send(c->fd, (uint8_t*)d + sendsize, size - sendsize, 0)); #endif if (n == 0) { return SOCKET_ERROR; } if (n == SOCKET_ERROR) { if (interrupted()) { continue; } if (wouldblock()) { /* on ET mode, MUST send EAGAIN return */ return sendsize; } return SOCKET_ERROR; } sendsize += n; c->send_bytes += n; } return sendsize; }
/* dump all references to stdout */ retvalue references_dump(void) { struct cursor *cursor; retvalue result, r; const char *found_to, *found_by; r = table_newglobalcursor(rdb_references, &cursor); if (!RET_IS_OK(r)) return r; result = RET_OK; while (cursor_nexttemp(rdb_references, cursor, &found_to, &found_by)) { if (fputs(found_by, stdout) == EOF || putchar(' ') == EOF || puts(found_to) == EOF) { result = RET_ERROR; break; } result = RET_OK; if (interrupted()) { result = RET_ERROR_INTERRUPTED; break; } } r = cursor_close(rdb_references, cursor); RET_ENDUPDATE(result, r); return result; }
void WatcherRunner::start() { // Set worker performance counters to an initial state. Watcher::resetWorkerCounters(0); // Enter the watch loop. do { if (use_worker_ && !watch(Watcher::getWorker())) { if (Watcher::fatesBound()) { // A signal has interrupted the watcher. break; } // The watcher failed, create a worker. createWorker(); } // Loop over every managed extension and check sanity. std::vector<std::string> failing_extensions; for (const auto& extension : Watcher::extensions()) { if (!watch(*extension.second)) { if (!createExtension(extension.first)) { failing_extensions.push_back(extension.first); } } } // If any extension creations failed, stop managing them. for (const auto& failed_extension : failing_extensions) { Watcher::removeExtensionPath(failed_extension); } pauseMilli(getWorkerLimit(INTERVAL) * 1000); } while (!interrupted() && ok()); }
static int simple_fence(int sdir, int ch, int ofence) { int count = 1; /* Assmue that we're sitting at one end of the fence */ int c; /* scan for fence */ while (InDirection(sdir) && !interrupted()) { c = CurrentChar(); if (c == ch) { ++count; } else if (c == ofence) { if (--count <= 0) break; } } /* if count is zero, we have a match, move the sucker */ if (count <= 0) { if (!doingopcmd || doingsweep) sweephack = TRUE; else if (sdir == FORWARD) forwchar(TRUE,1); curwp->w_flag |= WFMOVE; return TRUE; } return FALSE; }
void SchedulerRunner::start() { // Start the counter at the second. auto i = osquery::getUnixTime(); for (; (timeout_ == 0) || (i <= timeout_); ++i) { Config::get().scheduledQueries( ([&i](const std::string& name, const ScheduledQuery& query) { if (query.splayed_interval > 0 && i % query.splayed_interval == 0) { TablePlugin::kCacheInterval = query.splayed_interval; TablePlugin::kCacheStep = i; launchQuery(name, query); } })); // Configuration decorators run on 60 second intervals only. if ((i % 60) == 0) { runDecorators(DECORATE_INTERVAL, i); } if (FLAGS_schedule_reload > 0 && (i % FLAGS_schedule_reload) == 0) { if (FLAGS_schedule_reload_sql) { SQLiteDBManager::resetPrimary(); } resetDatabase(); } // GLog is not re-entrant, so logs must be flushed in a dedicated thread. if ((i % 3) == 0) { relayStatusLogs(true); } // Put the thread into an interruptible sleep without a config instance. pauseMilli(interval_ * 1000); if (interrupted()) { break; } } }
void wildcard_expander_t::expand_intermediate_segment(const wcstring &base_dir, DIR *base_dir_fp, const wcstring &wc_segment, const wchar_t *wc_remainder, const wcstring &prefix) { wcstring name_str; while (!interrupted() && wreaddir_for_dirs(base_dir_fp, &name_str)) { // Note that it's critical we ignore leading dots here, else we may descend into . and .. if (!wildcard_match(name_str, wc_segment, true)) { // Doesn't match the wildcard for this segment, skip it. continue; } wcstring full_path = base_dir + name_str; struct stat buf; if (0 != wstat(full_path, &buf) || !S_ISDIR(buf.st_mode)) { // We either can't stat it, or we did but it's not a directory. continue; } const file_id_t file_id = file_id_t::from_stat(buf); if (!this->visited_files.insert(file_id).second) { // Symlink loop! This directory was already visited, so skip it. continue; } // We made it through. Perform normal wildcard expansion on this new directory, starting at // our tail_wc, which includes the ANY_STRING_RECURSIVE guy. full_path.push_back(L'/'); this->expand(full_path, wc_remainder, prefix + wc_segment + L'/'); // Now remove the visited file. This is for #2414: only directories "beneath" us should be // considered visited. this->visited_files.erase(file_id); } }
static int Xerror(Display *d, XErrorEvent *error) { X_UNLOCK; if (getenv("X11VNC_PRINT_XERROR")) { fprintf(stderr, "Xerror: major_opcode: %d minor_opcode: %d error_code: %d\n", error->request_code, error->minor_code, error->error_code); } if (xshm_opcode > 0 && error->request_code == xshm_opcode) { if (error->minor_code == X_ShmAttach) { char *dstr = DisplayString(dpy); fprintf(stderr, "\nX11 MIT Shared Memory Attach failed:\n"); fprintf(stderr, " Is your DISPLAY=%s on a remote machine?\n", dstr); if (strstr(dstr, "localhost:")) { fprintf(stderr, " Note: DISPLAY=localhost:N suggests a SSH X11 redir to a remote machine.\n"); } else if (dstr[0] != ':') { fprintf(stderr, " Note: DISPLAY=hostname:N suggests a remote display.\n"); } fprintf(stderr, " Suggestion, use: x11vnc -display :0 ... for local display :0\n\n"); } } interrupted(0); if (d) {} /* unused vars warning: */ return (*Xerror_def)(d, error); }
void FPGACamToolApp::run() { log("FPGACamToolApp running", Logger::LOGLEVEL_DEBUG); Array2D array(Core::argc, Core::argv); while( !interrupted() ) { if ( Array2D::status == Array2D::CLEAR || Array2D::status == Array2D::COMPLETE ) { Array2D::status = Array2D::PENDING; Lock tx_lock(tx_mav_mutex); mavlink_msg_data_transmission_handshake_pack(system_id(), component_id, &tx_mav_msg, DATA_TYPE_RAW_IMAGE, 0, 0, 0, 0, 0, 0); AppLayer<mavlink_message_t>::send(tx_mav_msg); } Array2D::display(); usleep(10000); } { Lock tx_lock(tx_mav_mutex); mavlink_msg_data_transmission_handshake_pack(system_id(), component_id, &tx_mav_msg, 0, 0, 0, 0, 0, 0, 0); AppLayer<mavlink_message_t>::send(tx_mav_msg); } log("FPGACamToolApp stop running", Logger::LOGLEVEL_DEBUG); }
static int comment_fence(int sdir) { MARK comstartpos; int found = FALSE; int s = FALSE; int first = TRUE; comstartpos.l = null_ptr; while (!found) { if (!first && CurrentChar() == '/') { /* is it a comment-end? */ if (PrevCharIs('*')) { if (sdir == FORWARD) { found = TRUE; break; } else if (comstartpos.l != null_ptr) { DOT = comstartpos; found = TRUE; break; } else { return FALSE; } } /* is it a comment start? */ if (sdir == REVERSE && NextCharIs('*')) { /* remember where we are */ comstartpos = DOT; } } s = InDirection(sdir); if (s == FALSE) { if (comstartpos.l != null_ptr) { DOT = comstartpos; found = TRUE; break; } return FALSE; } if (interrupted()) return FALSE; first = FALSE; } /* if found, move the sucker */ if (found && !first) { if (!doingopcmd || doingsweep) sweephack = TRUE; else if (sdir == FORWARD) forwchar(TRUE,1); curwp->w_flag |= WFMOVE; return TRUE; } return FALSE; }
virtual void start() override { while (!interrupted()) { if (!writeTextFile(kMultiThreadPermissionPath, "test")) { throw std::runtime_error("Cannot write " + kMultiThreadPermissionPath); } ticks++; } }
static int Xerror(Display *d, XErrorEvent *error) { X_UNLOCK; interrupted(0); if (d) {} /* unused vars warning: */ return (*Xerror_def)(d, error); }
void TLSLogForwarderRunner::start() { while (!interrupted()) { check(); // Cool off and time wait the configured period. pauseMilli(FLAGS_logger_tls_period * 1000); } }
void BufferedLogForwarder::start() { while (!interrupted()) { check(); // Cool off and time wait the configured period. pauseMilli(log_period_); } }
static int XIOerr(Display *d) { X_UNLOCK; interrupted(-1); if (d) {} /* unused vars warning: */ return (*XIOerr_def)(d); }
void HttpReply::interrupt() { m_interrupt = true; QLOG_TRACE() << "HttpReply interrupted" << m_connection->hostname(); m_networkReply->abort(); m_status = Interrupted; interrupted(); finished(); }
/* create dirname and any '/'-separated part of it */ retvalue dirs_make_recursive(const char *directory) { retvalue r, result; if (interrupted()) { return RET_ERROR_INTERRUPTED; } r = dirs_make_parent(directory); result = dirs_create(directory); RET_UPDATE(result, r); return result; }
void WatcherWatcherRunner::start() { while (!interrupted()) { if (isLauncherProcessDead(*watcher_)) { // Watcher died, the worker must follow. VLOG(1) << "osqueryd worker (" << PlatformProcess::getCurrentProcess()->pid() << ") detected killed watcher (" << watcher_->pid() << ")"; // The watcher watcher is a thread. Do not join services after removing. Initializer::requestShutdown(); break; } pauseMilli(getWorkerLimit(INTERVAL) * 1000); } }
void TLSConfigRefreshRunner::start() { while (!interrupted()) { // Cool off and time wait the configured period. // Apply this interruption initially as at t=0 the config was read. pauseMilli(FLAGS_config_tls_refresh * 1000); // Since the pause occurs before the logic, we need to check for an // interruption request. if (interrupted()) { return; } // Access the configuration. auto plugin = Registry::get("config", "tls"); if (plugin != nullptr) { auto config_plugin = std::dynamic_pointer_cast<ConfigPlugin>(plugin); // The config instance knows the TLS plugin is selected. std::map<std::string, std::string> config; if (config_plugin->genConfig(config)) { Config::getInstance().update(config); } } } }
void MemoryMap::addVariableWithRules(const Variable *var) { Instance inst(var->toInstance(_vmem, BaseType::trLexical, _knowSrc)); while (!interrupted()) { if (inst.isValid()) addVarInstance(inst); if (inst.isList()) { inst = inst.listNext(); checkOperationProgress(); } else break; } }
void start() override { PlatformFile file(kMultiThreadPermissionPath, PF_OPEN_EXISTING | PF_READ | PF_NONBLOCK); auto file_fd = file.nativeHandle(); struct pollfd fds[1]; while (!interrupted()) { std::memset(fds, 0, sizeof(fds)); fds[0].fd = file_fd; result = poll(fds, 1, 1); if (result == 0) { ticks++; } } }
static bbc_status_t remote_crc(serial_h com, bool wildcards, bool directories) { bbc_status_t result = BBC_OK ; char name[MAXLINELEN] ; if ( filespec(name, MAXLINELEN, wildcards, directories) == 0 ) return BBC_OK ; if ( wildcards ) { filelist *files ; if ( (result = getfilenames(com, name, &files, directories)) == BBC_SYNC ) { result = BBC_OK ; while ( files && !interrupted(true) ) { filelist *next = files->next ; if ( (result = retrieve_crc(com, files)) != BBC_OK ) { printf("Error retrieving CRC of %s, skipping\n", files->name) ; free(files) ; files = next ; break ; } free(files) ; files = next ; } while ( files ) { filelist *next = files->next ; printf("Skipping file %s because of previous error\n", files->name) ; free(files) ; files = next ; } } } else { filelist file ; strcpy(file.name, name) ; if ( (result = retrieve_crc(com, &file)) != BBC_OK ) printf("Error retrieving CRC for %s\n", name) ; } return result ; }
static int attribute_cntl_a_sequences(void) { BUFFER *bp = curbp; LINE *pastline; C_NUM offset; /* offset in cur line of place to attribute */ int count; #if EFFICIENCY_HACK AREGION *orig_attribs = bp->b_attribs; AREGION *new_attribs; #endif if ((pastline = setup_region()) == 0) return FALSE; while (DOT.l != pastline) { if (interrupted()) return FALSE; while (DOT.o < llength(DOT.l)) { if (CharAtDot() == CONTROL_A) { offset = decode_attribute(lvalue(DOT.l), (size_t) llength(DOT.l), (size_t) DOT.o, &count); if (offset > DOT.o) { #if EFFICIENCY_HACK new_attribs = bp->b_attribs; bp->b_attribs = orig_attribs; ldel_bytes((B_COUNT) (offset - DOT.o), FALSE); bp->b_attribs = new_attribs; #else ldel_bytes((B_COUNT) (offset - DOT.o), FALSE); #endif } set_mark_after(count, len_record_sep(bp)); if (apply_attribute()) (void) attributeregion(); } else { DOT.o += BytesAt(DOT.l, DOT.o); } } DOT.l = lforw(DOT.l); DOT.o = 0; } return TRUE; }
nullmsg* Connection::receive() { //粘包 nullmsg* newmsg = handle_socket_buffer(&this->recv_buffer); if (newmsg) { return newmsg; } while(1) { int size = this->recv_buffer.size - this->recv_buffer.current; assert(size >= 0); if (size == 0) { size = 960; this->recv_buffer.resize(size); } ssize_t n = TEMP_FAILURE_RETRY(recv(this->fd, &this->recv_buffer.data[this->recv_buffer.current], size, 0)); if (n == 0) // The return value will be 0 when the peer has performed an orderly shutdown. { //error_log("Connection lost:%d,%s\n", errno, strerror(errno)); this->disable(); return NULL; } else if (n == SOCKET_ERROR) { if (interrupted()) { continue; } if (wouldblock()) { /* on ET mode, MUST recv EAGAIN return */ return NULL; } //CCLOG("Connection error:%d,%s\n", errno, strerror(errno)); this->disable(); return NULL; } this->recv_bytes += n; this->recv_buffer.current += n; newmsg = handle_socket_buffer(&this->recv_buffer); if (newmsg) { return newmsg; } } return NULL; }
// Given a start point as an absolute path, for any directory that has exactly one non-hidden // entity in it which is itself a directory, return that. The result is a relative path. For // example, if start_point is '/usr' we may return 'local/bin/'. // // The result does not have a leading slash, but does have a trailing slash if non-empty. wcstring descend_unique_hierarchy(const wcstring &start_point) { assert(!start_point.empty() && start_point.at(0) == L'/'); wcstring unique_hierarchy; wcstring abs_unique_hierarchy = start_point; bool stop_descent = false; DIR *dir; while (!stop_descent && (dir = wopendir(abs_unique_hierarchy))) { // We keep track of the single unique_entry entry. If we get more than one, it's not // unique and we stop the descent. wcstring unique_entry; bool child_is_dir; wcstring child_entry; while (wreaddir_resolving(dir, abs_unique_hierarchy, child_entry, &child_is_dir)) { if (child_entry.empty() || child_entry.at(0) == L'.') { continue; // either hidden, or . and .. entries -- skip them } else if (child_is_dir && unique_entry.empty()) { unique_entry = child_entry; // first candidate } else { // We either have two or more candidates, or the child is not a directory. We're // done. stop_descent = true; break; } } // We stop if we got two or more entries; also stop if we got zero or were interrupted if (unique_entry.empty() || interrupted()) { stop_descent = true; } if (!stop_descent) { // We have an entry in the unique hierarchy! append_path_component(unique_hierarchy, unique_entry); unique_hierarchy.push_back(L'/'); append_path_component(abs_unique_hierarchy, unique_entry); abs_unique_hierarchy.push_back(L'/'); } closedir(dir); } return unique_hierarchy; }
/* callback for each registered file */ retvalue files_foreach(per_file_action action, void *privdata) { retvalue result, r; struct cursor *cursor; const char *filekey, *checksum; r = table_newglobalcursor(rdb_checksums, &cursor); if (!RET_IS_OK(r)) return r; result = RET_NOTHING; while (cursor_nexttemp(rdb_checksums, cursor, &filekey, &checksum)) { if (interrupted()) { RET_UPDATE(result, RET_ERROR_INTERRUPTED); break; } r = action(privdata, filekey); RET_UPDATE(result, r); } r = cursor_close(rdb_checksums, cursor); RET_ENDUPDATE(result, r); return result; }
void TypeRuleEngine::checkRules(int from) { operationStarted(); _rulesChecked = 0; // Full or partial check? if (from <= 0) { from = 0; _hits.fill(0, _rules.size()); _rulesPerType.clear(); for (int i = 0; i < _activeRules.size(); ++i) delete _activeRules[i]; _activeRules.clear(); _rulesToCheck = _rules.size(); } else { _hits.resize(_rules.size()); _rulesToCheck = _rules.size() - from; } if (!_symbols->factory().symbolsAvailable() || _rules.isEmpty()) return; forceOperationProgress(); OsSpecs specs(&_symbols->memSpecs()); // Checking the rules from last to first assures that rules in the // _activeRules hash are processes first to last. That way, if multiple // rules match the same instance, the first rule takes precedence. for (int i = _rules.size() - 1; !interrupted() && i >= from; --i) { ++_rulesChecked; checkOperationProgress(); checkRule(_rules[i], i, &specs); } operationStopped(); operationProgress(); shellEndl(); }
void Runner::runRenderer(string sceneData, UIprogressEvent* e) { QString cd = QDir::currentPath(); string path = cd.toLocal8Bit().constData(); path += "/.temp.scene"; ofstream file(path.c_str()); file<<sceneData; handler = e; currentWorker = new Worker(path, threads, blocks, handler); QThread* thread = new QThread(); currentWorker->moveToThread(thread); connect(thread, SIGNAL(started()), currentWorker, SLOT(Render())); connect(currentWorker, SIGNAL(imageReady(UIimage*)), this, SLOT(setImage(UIimage*))); connect(currentWorker, SIGNAL(renderComplete()), this, SLOT(done())); connect(currentWorker, SIGNAL(renderInvalid()), this, SLOT(invalid())); connect(currentWorker, SIGNAL(renderInterrupted()), this, SLOT(interrupted())); thread->start(); }