semaphore::~semaphore() { if (sem_destroy(&sem) == -1) { // Destructor, so can't throw log_errno("failed to destroy semaphore: %1% (%2%)"); } }
static void wake_up_server () { int w = 1; debug ("Waking up the server"); if (write(wake_up_pipe[1], &w, sizeof(w)) < 0) log_errno ("Can't wake up the server: (write() failed)", errno); }
int wds_open() { // Create the structure for connecting to the forwarded 9999 port sockaddr_in addr; createTcpSocket(addr, DEFAULT_WDS_PORT); // Create our socket int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd < 0) { log_errno("Failed to create file descriptor"); return -1; } // Connect to the remote wds server thread if (connect(fd, (sockaddr*)&addr, sizeof(addr)) < 0) { log_errno("Failed to connect to remote debug server"); return -1; } return fd; }
// read file data // // returns positive number of bytes read, or negative error number // static int read_file(file_t *fp, char *retbuf, int len, int *readflag, charset_t outcset) { (void) outcset; File *file = (File*)fp; if (file != NULL) { int sockfd = file->sockfd; int rv = CBM_ERROR_OK; retbuf[0] = file->lastbyte; ssize_t n = read(sockfd, file->has_lastbyte ? retbuf+1 : retbuf, file->has_lastbyte ? len - 1 : len); #ifdef DEBUG_READ log_debug("Read %ld bytes from socket fd=%d\n", n, sockfd); #endif if (n < 0) { // error condition if (errno != EAGAIN && errno != EWOULDBLOCK) { // error reading from socket rv = errno_to_error(errno); log_errno("Error reading from socket!\n"); return -rv; } // no data available, not in error, just non-blocking len = 0; } else if (n > 0) { // got some real data // what's in the buffer? len = n + (file->has_lastbyte ? 1 : 0); // NOTE: this probably belongs into an option, or // make it different defaults for read only and read/write files // keep one for EOF handling (note: len here always >= 1) //len--; //file->lastbyte = retbuf[len]; //file->has_lastbyte = 1; file->has_lastbyte = 0; } else if (n == 0) { // got an EOF *readflag = READFLAG_EOF; len = file->has_lastbyte ? 1 : 0; retbuf[0] = file->lastbyte; } return len; } return -CBM_ERROR_FAULT; }
void VBBM::loadVersion2(IDBDataFile* in) { int vbbmEntries; int nFiles; int i; VBBMEntry entry; if (in->read((char *) &vbbmEntries, 4) != 4) { log_errno("VBBM::load()"); throw runtime_error("VBBM::load(): Failed to read entry number"); } if (in->read((char *) &nFiles, 4) != 4) { log_errno("VBBM::load()"); throw runtime_error("VBBM::load(): Failed to read file number"); } // Need to make clear() truncate the files section if (vbbm->nFiles > nFiles) vbbm->nFiles = nFiles; clear(); while (vbbm->nFiles < nFiles) growVBBM(true); // this allocates one file, doesn't grow the main storage growForLoad(vbbmEntries); const int nfileSize = sizeof(VBFileMetadata) * nFiles; if (in->read((char *)files, nfileSize) != nfileSize) { log_errno("VBBM::load()"); throw runtime_error("VBBM::load(): Failed to load vb file meta data"); } for (i = 0; i < vbbmEntries; i++) { if (in->read((char *)&entry, sizeof(entry)) != sizeof(entry)) { log_errno("VBBM::load()"); throw runtime_error("VBBM::load(): Failed to load entry"); } insert(entry.lbid, entry.verID, entry.vbOID, entry.vbFBO, true); } }
int CSocket::setListening() { int e = ::listen(this->sockfd_, 1); // TODO: change 1 to the corresponding constant if(e == -1) { e = errno; log_errno(e); return -1; } return 0; }
int CSocket::bind() { int e = ::bind(this->sockfd_, this->ai_addr_, sizeof(*this->ai_addr_)); if(e != 0) { e = errno; log_errno(e); return -1; } return 0; }
static void clients_cleanup () { int i, rc; for (i = 0; i < CLIENTS_MAX; i++) { clients[i].socket = -1; rc = pthread_mutex_destroy (&clients[i].events_mtx); if (rc != 0) log_errno ("Can't destroy events mutex", rc); } }
semaphore_fd::~semaphore_fd() { for (int i = 0; i < 2; i++) if (pipe_fds[i] != -1) { if (close(pipe_fds[i]) == -1) { // Can't throw, because this is a destructor log_errno("failed to close pipe: %1% (%2%)"); } } }
int CSocket::close() { int retval = -1; if(this->sockfd_ != -1) retval = ::close(this->sockfd_); if(retval == -1) { int e = errno; log_errno(e); } return retval; }
int single_instance_init(SingleInstanceFunc func, const char *str) { on_dupe = func; path = g_build_filename(g_get_home_dir(), "." PACKAGE, "fifo", NULL); /* If we can open the program FIFO in write-only mode then we must have a reader process already running. We send it a one-byte junk message to wake it up and quit. */ if ((fifo = open(path, O_WRONLY | O_NONBLOCK)) > 0) { write(fifo, str, 1); close(fifo); return TRUE; } /* The FIFO can be left over from a previous instance if the program crashes or is killed */ if (g_file_test(path, G_FILE_TEST_EXISTS)) { g_debug("Program FIFO exists but is not opened on " "read-only side, deleting\n"); single_instance_cleanup(); } /* Otherwise, create a read-only FIFO and poll for input */ fifo = 0; if (mkfifo(path, S_IRUSR | S_IWUSR)) { log_errno("Failed to create program FIFO"); return FALSE; } if ((fifo = open(path, O_RDONLY | O_NONBLOCK)) == -1) { log_errno("Failed to open FIFO for reading"); return FALSE; } /* Setup the polling function */ g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 1000, (GSourceFunc)check_dupe, NULL, NULL); return FALSE; }
// free disk space in bytes, < 0 on errors // If per-user quotas are being used, the reported value may be less than // the total number of free bytes on a disk. signed long long os_free_disk_space (const char *path) { BOOL res; signed long long total, free_bytes_to_caller; res = GetDiskFreeSpaceEx(path, (PULARGE_INTEGER)&free_bytes_to_caller, NULL, NULL); if (res) { total = free_bytes_to_caller; } else { log_errno("Unable to get free disk space for '%s'", path); total = -GetLastError(); } return total; }
void VBBM::loadVersion1(IDBDataFile* in) { int vbbmEntries, i; VBBMEntry entry; clear(); if (in->read((char *) &vbbmEntries, 4) != 4) { log_errno("VBBM::load()"); throw runtime_error("VBBM::load(): Failed to read entry number"); } for (i = 0; i < vbbmEntries; i++) { if (in->read((char *)&entry, sizeof(entry)) != sizeof(entry)) { log_errno("VBBM::load()"); throw runtime_error("VBBM::load(): Failed to load entry"); } insert(entry.lbid, entry.verID, entry.vbOID, entry.vbFBO, true); //confirmChanges(); addVBFileIfNotExists(entry.vbOID); } /* This will load the saved file data from 2.2, but it is not compatible with * 3.0+. If enabled, take out the addVBFile..() call above */ #if 0 int dummy, nFiles; in.read((char *) &nFiles, 4); cout << "got nfiles = " << nFiles << endl; in.read((char *) &dummy, 4); // an unused var in 3.0+ while (vbbm->nFiles < nFiles) growVBBM(true); // this allocates one file, doesn't grow the main storage in.read((char *) files, sizeof(VBFileMetadata) * nFiles); for (i = 0; i < nFiles; i++) cout << "file " << i << ": oid=" << files[i].OID << " size=" << files[i].fileSize << " offset=" << files[i].nextOffset << endl; #endif }
void destroy_conf (conf_t conf) { /* Destroys the configuration [conf]. */ assert (conf != NULL); if (conf->payload) { assert (conf->num_payload > 0); free (conf->payload); } if ((errno = pthread_cond_destroy (&conf->cond_done)) != 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to destroy condition"); } if ((errno = pthread_mutex_destroy (&conf->mutex)) != 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to destroy mutex"); } munge_ctx_destroy (conf->ctx); free (conf->tids); free (conf); return; }
int CSocket::getSockFd() { if(this->sockfd_ != -1) throw std::logic_error("Trying to getSockFd, but this->sockfd_ != -1"); int e; this->sockfd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(this->sockfd_ == -1) { e = errno; log_errno(e); return -1; } return 0; }
void output_msg (const char *format, ...) { /* Outputs the current time followed by the [format] string * to stdout in a thread-safe manner. */ time_t t; struct tm tm; struct tm *tm_ptr; char buf[256]; char *p = buf; int len = sizeof (buf); int n; va_list vargs; if (g_got_quiet) { return; } if (!format) { return; } if (time (&t) == ((time_t) -1)) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to query current time"); } #if HAVE_LOCALTIME_R tm_ptr = localtime_r (&t, &tm); #else /* !HAVE_LOCALTIME_R */ tm_ptr = localtime (&t); #endif /* !HAVE_LOCALTIME_R */ if (tm_ptr != NULL) { n = strftime (p, len, "%Y-%m-%d %H:%M:%S ", tm_ptr); if ((n <= 0) || (n >= len)) { log_err (EMUNGE_SNAFU, LOG_ERR, "Exceeded buffer while writing timestamp"); } p += n; len -= n; } va_start (vargs, format); n = vsnprintf (p, len, format, vargs); va_end (vargs); if ((n < 0) || (n >= len)) { buf[sizeof (buf) - 2] = '+'; buf[sizeof (buf) - 1] = '\0'; /* technically redundant */ } printf ("%s\n", buf); return; }
int red_socket_geterrno(struct bufferevent *buffev) { int error; int pseudo_errno; socklen_t optlen = sizeof(pseudo_errno); int fd = bufferevent_getfd(buffev); error = getsockopt(fd, SOL_SOCKET, SO_ERROR, &pseudo_errno, &optlen); if (error) { log_errno(LOG_ERR, "getsockopt(fd=%d)", fd); return -1; } return pseudo_errno; }
int red_socket_geterrno(struct bufferevent *buffev) { int error; int pseudo_errno; socklen_t optlen = sizeof(pseudo_errno); assert(EVENT_FD(&buffev->ev_read) == EVENT_FD(&buffev->ev_write)); error = getsockopt(EVENT_FD(&buffev->ev_read), SOL_SOCKET, SO_ERROR, &pseudo_errno, &optlen); if (error) { log_errno(LOG_ERR, "getsockopt"); return -1; } return pseudo_errno; }
int apply_tcp_fastopen(int fd) { #ifdef TCP_FASTOPEN #ifdef __APPLE__ int opt = 1; #else int opt = 5; #endif int rc = setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &opt, sizeof(opt)); if (rc == -1) log_errno(LOG_ERR, "setsockopt"); return rc; #else return -1; #endif }
int red_is_socket_connected_ok(struct bufferevent *buffev) { int pseudo_errno = red_socket_geterrno(buffev); if (pseudo_errno == -1) { return 0; } else if (pseudo_errno) { errno = pseudo_errno; log_errno(LOG_NOTICE, "connect"); return 0; } else { return 1; } }
struct bufferevent* red_connect_relay2(struct sockaddr_in *addr, evbuffercb writecb, everrorcb errorcb, void *cbarg, const struct timeval *timeout_write) { struct bufferevent *retval = NULL; int on = 1; int relay_fd = -1; int error; relay_fd = socket(AF_INET, SOCK_STREAM, 0); if (relay_fd == -1) { log_errno(LOG_ERR, "socket"); goto fail; } error = fcntl_nonblock(relay_fd); if (error) { log_errno(LOG_ERR, "fcntl"); goto fail; } error = setsockopt(relay_fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)); if (error) { log_errno(LOG_WARNING, "setsockopt"); goto fail; } error = connect(relay_fd, (struct sockaddr*)addr, sizeof(*addr)); if (error && errno != EINPROGRESS) { log_errno(LOG_NOTICE, "connect"); goto fail; } retval = bufferevent_new(relay_fd, NULL, writecb, errorcb, cbarg); if (!retval) { log_errno(LOG_ERR, "bufferevent_new"); goto fail; } bufferevent_set_timeouts(retval, NULL, timeout_write); error = bufferevent_enable(retval, EV_WRITE); // we wait for connection... if (error) { log_errno(LOG_ERR, "bufferevent_enable"); goto fail; } return retval; fail: if (relay_fd != -1) redsocks_close(relay_fd); if (retval) bufferevent_free(retval); return NULL; }
/** * check a path, making sure it's a directory */ int os_path_is_dir(const char *name) { struct stat sbuf; int isdir = 1; log_info("checking dir with name %s\n",name); if (lstat(name, &sbuf) < 0) { log_errno("Error stat'ing dir"); isdir = 0; } else { if (!S_ISDIR(sbuf.st_mode)) { isdir = 0; log_error("Error trying to open a directory as file\n"); } } return isdir; }
static void disable_core_dumps (void) { /* Disable creation of core dump files. */ #ifdef NDEBUG struct rlimit limit; limit.rlim_cur = 0; limit.rlim_max = 0; if (setrlimit (RLIMIT_CORE, &limit) < 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to disable core dumps"); } #endif /* NDEBUG */ return; }
/** * Sets a system error-message as the first error-message for the current thread * based on the current value of "errno" and a higher-level error-message. */ void log_serror( const char* const fmt, /**< The higher-level message format */ ...) /**< Arguments referenced by the format */ { va_list args; log_errno(); va_start(args, fmt); if (EAGAIN == log_vadd(fmt, args)) { va_end(args); va_start(args, fmt); (void)log_vadd(fmt, args); } va_end(args); }
int compare_packet(int fd, const char *inbuffer, const char *mask, const int inbuflen, int curpos) { char buffer[8192]; ssize_t cnt = 0; int err = 0; cnt = read_packet(fd, buffer, sizeof(buffer)); if (cnt < 0) { log_errno("Error reading from socket at line %d\n", curpos); err = 2; } else { if (inbuflen > 0) { // only check data when we actually expect something if (cnt == inbuflen) { // expected length if (mask == NULL) { if (memcmp(inbuffer, buffer, inbuflen)) { log_error("Detected mismatch at line %d\n", curpos); err = 1; } } else { for (int i = 0; i < inbuflen; i++) { if ((inbuffer[i] ^ buffer[i]) & mask[i]) { log_error("Detected mismatch at line %d\n", curpos); err = 1; } } } } else { // length mismatch log_error("Detected mismatch at line %d\n", curpos); err = 1; } } // print data lines if (trace || err) { log_hexdump2(buffer, cnt, 0, "Rxd : "); } if (err) { log_hexdump2(inbuffer, inbuflen, 0, "Expect: "); } } return err; }
/** * check a path, making sure it's something readable, not a directory */ int os_path_is_file(const char *name) { struct stat sbuf; int isfile = 1; log_debug("checking file with name %s\n",name); if (lstat(name, &sbuf) < 0) { log_errno("Error stat'ing file"); // note we still return 1, as open may succeed - e.g. for // save where the file does not exist in the first place } else { if (S_ISDIR(sbuf.st_mode)) { isfile = 0; log_error("Error trying to open a directory as file\n"); } } return isfile; }
void files_init () { #ifdef HAVE_LIBMAGIC assert (cookie == NULL); cookie = magic_open (MAGIC_SYMLINK | MAGIC_MIME | MAGIC_ERROR | MAGIC_NO_CHECK_COMPRESS | MAGIC_NO_CHECK_ELF | MAGIC_NO_CHECK_TAR | MAGIC_NO_CHECK_TOKENS | MAGIC_NO_CHECK_FORTRAN | MAGIC_NO_CHECK_TROFF); if (cookie == NULL) log_errno ("Error allocating magic cookie", errno); else if (magic_load (cookie, NULL) != 0) { logit ("Error loading magic database: %s", magic_error (cookie)); magic_close (cookie); cookie = NULL; } #endif }
static void daemonize_fini (int fd) { /* Completes the daemonization of the process, * where 'fd' is the file descriptor returned by daemonize_init(). */ int dev_null; /* Ensure process does not keep a directory in use. * Avoid relative pathnames from this point on! */ if (chdir ("/") < 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to change to root directory"); } /* Discard data to/from stdin, stdout, and stderr. */ if ((dev_null = open ("/dev/null", O_RDWR)) < 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to open \"/dev/null\""); } if (dup2 (dev_null, STDIN_FILENO) < 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to dup \"/dev/null\" onto stdin"); } if (dup2 (dev_null, STDOUT_FILENO) < 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to dup \"/dev/null\" onto stdout"); } if (dup2 (dev_null, STDERR_FILENO) < 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to dup \"/dev/null\" onto stderr"); } if (close (dev_null) < 0) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to close \"/dev/null\""); } /* Clear the fd used by log_err() to return status back to the parent. */ log_set_err_pipe (-1); /* * Signal grandparent process to terminate. */ if ((fd >= 0) && (close (fd) < 0)) { log_errno (EMUNGE_SNAFU, LOG_ERR, "Failed to close write-pipe in grandchild process"); } return; }
/* * reads data from the tcp conection. * any error is fatal and the connection is closed. * (And a read of zero bytes is a half closed stream => error.) */ static int readtcp( register SVCXPRT *xprt, char* buf, register int len) { register int sock = xprt->xp_sock; #ifdef FD_SETSIZE fd_set mask; fd_set readfds; FD_ZERO(&mask); FD_SET(sock, &mask); #else register int mask = 1 << sock; int readfds; #endif /* def FD_SETSIZE */ do { int status; struct timeval timeout = wait_per_try; readfds = mask; status = select(sock+1, &readfds, NULL, NULL, &timeout); if (status <= 0) { if (status == 0) { log_add("readtcp(): select() timeout on socket %d", sock); } else { if (errno == EINTR) continue; log_errno(); log_add("readtcp(): select() error on socket %d", sock); } goto fatal_err; } #ifdef FD_SETSIZE } while (!FD_ISSET(sock, &readfds)); #else } while (readfds != mask);
static void *locked_read_add (struct tags_cache *c, const char *file, const int tags_sel, const int client_id, DBT *key, DBT *serialized_cache_rec) { int ret; struct file_tags *tags = NULL; assert (c->db != NULL); ret = c->db->get (c->db, NULL, key, serialized_cache_rec, 0); if (ret && ret != DB_NOTFOUND) log_errno ("Cache DB get error", ret); /* If this entry is already present in the cache, we have 3 options: * we must read different tags (TAGS_*) or the tags are outdated * or this is an immediate tags read (client_id == -1) */ if (ret == 0) { struct cache_record rec; if (cache_record_deserialize (&rec, serialized_cache_rec->data, serialized_cache_rec->size, 0)) { time_t curr_mtime = get_mtime (file); if (rec.mod_time != curr_mtime) { debug ("Tags in the cache are outdated"); tags_free (rec.tags); /* remove them and reread tags */ } else if ((rec.tags->filled & tags_sel) == tags_sel && client_id == -1) { debug ("Tags are in the cache."); return rec.tags; } else { debug ("Tags in the cache are not what we want"); tags = rec.tags; /* read additional tags */ } } } tags = read_missing_tags (file, tags, tags_sel); tags_cache_add (c, file, key, tags); return tags; }