Exemple #1
0
boolean
fsysdep_sync (openfile_t e, const char *zmsg)
{
#if FSYNC_ON_CLOSE
  int o;
#endif

#if USE_STDIO
  if (fflush (e) == EOF)
    {
      ulog (LOG_ERROR, "%s: fflush: %s", zmsg, strerror (errno));
      return FALSE;
    }
#endif

#if FSYNC_ON_CLOSE
#if USE_STDIO
  o = fileno (e);
#else
  o = e;
#endif

  if (fsync (o) < 0)
    {
      ulog (LOG_ERROR, "%s: fsync: %s", zmsg, strerror (errno));
      return FALSE;
    }
#endif

  return TRUE;
}
Exemple #2
0
static void dump_status(struct uplink *uplink) {
	const char *status = "unknown";
	if (uplink->fd == -1) {
		status = "offline";
	} else {
		switch (uplink->auth_status) {
			case AUTHENTICATED:
				status = "online";
				break;
			case SENT:
			case NOT_STARTED:
				status = "connecting";
				break;
			case FAILED:
				status = "bad-auth";
				break;
		}
	}
	ulog(LLOG_DEBUG, "Dump status %s\n", status);
	if (!uplink->status_file)
		return;
	FILE *sf = fopen(uplink->status_file, "w");
	if (!sf) {
		ulog(LLOG_ERROR, "Couldn't dump current uplink status to file %s: %s\n", uplink->status_file, strerror(errno));
		return;
	}
	fprintf(sf, "%s\t%llu\n", status, (unsigned long long)time(NULL));
	if (fclose(sf) == EOF)
		ulog(LLOG_WARN, "Error closing status file %s/%p: %s\n", uplink->status_file, (void *)sf, strerror(errno));
}
static int netlink_send(int s, struct cn_msg *msg)
{
    struct nlmsghdr *nlh;
    unsigned int size;
    int err;
    char buf[128];
    struct cn_msg *m;

    size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len);

    nlh = (struct nlmsghdr *)buf;
    nlh->nlmsg_seq = seq++;
    nlh->nlmsg_pid = getpid();
    nlh->nlmsg_type = NLMSG_DONE;
    nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh));
    nlh->nlmsg_flags = 0;

    m = NLMSG_DATA(nlh);
#if 0
    ulog("%s: [%08x.%08x] len=%u, seq=%u, ack=%u.\n",
         __func__, msg->id.idx, msg->id.val, msg->len, msg->seq, msg->ack);
#endif
    memcpy(m, msg, sizeof(*m) + msg->len);

    err = send(s, nlh, size, 0);
    if (err == -1)
        ulog("Failed to send: %s [%d].\n",
             strerror(errno), errno);

    return err;
}
Exemple #4
0
void* UThread::startThread(void* ptr)
{
	UThread* thread = (UThread *) ptr;

	ulog(ULOG_INFO,"starting thread %s",thread->mThreadName?thread->mThreadName:"");
	//进行子类的向下虚拟调用
    thread->handleRun();
    ulog(ULOG_INFO,"thread ended %s",thread->mThreadName?thread->mThreadName:"");
    return (void *)1;
}
Exemple #5
0
boolean
fcopy_open_file (FILE *efrom, const char *zto, boolean fpublic, boolean fmkdirs, boolean fsignals)
{
  FILE *eto;
  char ab[8192];
  size_t c;

  eto = esysdep_fopen (zto, fpublic, FALSE, fmkdirs);
  if (eto == NULL)
    return FALSE;

  while ((c = fread (ab, sizeof (char), sizeof ab, efrom)) != 0)
    {
      if (fwrite (ab, sizeof (char), (size_t) c, eto) != c)
	{
	  ulog (LOG_ERROR, "fwrite: %s", strerror (errno));
	  (void) fclose (eto);
	  (void) remove (zto);
	  return FALSE;
	}
      if (fsignals && FGOT_SIGNAL ())
	{
	  /* Log the signal.  */
	  ulog (LOG_ERROR, (const char *) NULL);
	  (void) fclose (eto);
	  (void) remove (zto);
	  return FALSE;
	}
    }

  if (! fsysdep_sync (eto, zto))
    {
      (void) fclose (eto);
      (void) remove (zto);
      return FALSE;
    }

  if (fclose (eto) != 0)
    {
      ulog (LOG_ERROR, "fclose: %s", strerror (errno));
      (void) remove (zto);
      return FALSE;
    }

  if (ferror (efrom))
    {
      ulog (LOG_ERROR, "fread: %s", strerror (errno));
      (void) remove (zto);
      return FALSE;
    }

  return TRUE;
}
Exemple #6
0
void readQueryFromClient(aeEventLoop *el, int fd, httpClient *c) {
    char buf[CCACHE_IOBUF_LEN];
    int nread;
    nread = read(fd, buf, CCACHE_IOBUF_LEN);
    if (nread == -1) {
        if (errno == EAGAIN) { /* try again */
            nread = 0;
        } else {
            ulog(CCACHE_VERBOSE, "Reading from client: %s",strerror(errno));
            freeClient(c);
            return;
        }
    } else if (nread == 0) {
        ulog(CCACHE_VERBOSE, "End of client request");
        freeClient(c);
        return;
    }
    if (nread>0) {
        printf("Read Request: %.2lf \n", (double)(clock()));
        c->lastinteraction = time(NULL);
        listMoveNodeToTail(el->clients,c->elNode);
        /* NOTICE: nread or nread-1 */
        switch(requestParse(c->req,buf,buf+nread)){
        case parse_not_completed:
            break;
        case parse_completed:
        {            
            int handle_result = requestHandle(c->req,c->rep,el->cache,c);
            if(handle_result == HANDLER_BLOCK){
                blockClient(el,c);
            }
            else {
                if (_installWriteEvent(el, c) != CCACHE_OK) return;
                printf("Install Write: %.2lf\n", (double)(clock()));
                /* For HANDLE_OK there is nothing to do */
                if(handle_result == HANDLER_ERR) requestHandleError(c->req,c->rep);
            }
                break;
        }
        case parse_error:
            if (_installWriteEvent(el, c) != CCACHE_OK) {
                return;
            }
            requestHandleError(c->req,c->rep);
            break;
        default:
            break;
        };
    }
}
Exemple #7
0
void nodelib_version(void)
{
  ulog(ULOG_INFO, "NODElib version information\n");
  ulog(ULOG_INFO, "---------------------------\n");
  ulog(ULOG_INFO, "     USER : %s\n", NODELIB_USER);
  ulog(ULOG_INFO, "     HOST : %s\n", NODELIB_HOST);
  ulog(ULOG_INFO, "     DATE : %s\n", NODELIB_DATE);
  ulog(ULOG_INFO, "    UNAME : %s\n", NODELIB_UNAME);
  ulog(ULOG_INFO, "  VERSION : %s\n", NODELIB_VERSION);
  ulog(ULOG_INFO, " COMPILER : %s\n", NODELIB_COMPILER);
  ulog(ULOG_INFO, "COPYRIGHT : %s\n", NODELIB_COPYRIGHT);
}
Exemple #8
0
void sendReplyToClient(aeEventLoop *el, int fd, httpClient *c) {
    int nwritten = 0;

    CCACHE_NOTUSED(el);    
    if(c->rep) {
        sds obuf = replyToBuffer(c->rep);
        int towrite = sdslen(obuf) - c->bufpos;
        nwritten = write(fd, obuf+c->bufpos,towrite);
        /* Content */
        if (nwritten == -1) {
            if (errno == EAGAIN) {
                nwritten = 0;
            } else {
                ulog(CCACHE_VERBOSE,
                     "Error writing to client: %s", strerror(errno));
                freeClient(c);
                return;
            }
        }
        c->lastinteraction = time(NULL);
        listMoveNodeToTail(el->clients,c->elNode);
        if(nwritten<towrite) {
            c->bufpos += nwritten;
        }
        else {
#ifdef AE_MAX_CLIENT_IDLE_TIME
            resetClient(c);
#else
            freeClient(c);
#endif
            aeModifyFileEvent(el,c->fd,AE_READABLE,c);
            printf("Send Reply: %.2lf\n", (double)(clock()));
        }
    }
}
Exemple #9
0
static jint tagThreads(ThreadModule * threadModule, jvmtiEnv * jvmti, jlong beginTag) {
	jthread * threads;
	jvmtiError err;
	int i;

	err = (*jvmti)->GetAllThreads(jvmti, &threadModule->threadCount, &threads);
	CHECK_ERROR_AND_RETURN(jvmti, err, "get all thread error", JNI_ERR);

	threadModule->threadInfos = calloc(threadModule->threadCount, sizeof(ThreadInfo));
	for (i = 0; i < threadModule->threadCount; i++) {
		jvmtiThreadInfo aInfo;

		int tag = beginTag + i;

		err = (*jvmti)->GetThreadInfo(jvmti, threads[i], &aInfo);
		print_if_error(jvmti, err, "get thread info error");
		if (err == JVMTI_ERROR_NONE) {
			(*jvmti)->SetTag(jvmti, threads[i], tag);
			threadModule->threadInfos[i].name = strdup(aInfo.name);
#ifdef DEBUG
			ulog("tag thread: %s to %d\n", threadModule->threadInfos[i].name, tag);
#endif
			deallocate(jvmti, aInfo.name);
		}
	}

	deallocate(jvmti, threads);
	return JNI_OK;
}
Exemple #10
0
static int netlink_send(int s, struct cn_msg *msg)
{
	struct nlmsghdr *nlh;
	unsigned int size;
	int err;
	char buf[CONNECTOR_MAX_MSG_SIZE];
	struct cn_msg *m;

	size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len);

	nlh = (struct nlmsghdr *)buf;
	nlh->nlmsg_seq = seq++;
	nlh->nlmsg_pid = getpid();
	nlh->nlmsg_type = NLMSG_DONE;
	nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh));
	nlh->nlmsg_flags = 0;

	m = NLMSG_DATA(nlh);
	memcpy(m, msg, sizeof(*m) + msg->len);

	err = send(s, nlh, size, 0);
	if (err == -1)
		ulog(LOG_ERR, "Failed to send: %s [%d].\n", strerror(errno), errno);

	return err;
}
Exemple #11
0
void sensor_server() {
    struct SensorService service;    
    sensorservice_initialize(&service);

    RegisterAs("SensorServer");

    // Create the thing sending us sensor messages.
    Create(HIGH, sensor_notifier);

    tid_t stream = CreateStream("SensorServerStream");

    int tid;
    SensorServerMessage msg, rply;
    for(;;) {
        Receive(&tid, (char *) &msg, sizeof(msg));

        switch(msg.type) {
            case SENSOR_EVENT_REQUEST:
                rply.type = SENSOR_EVENT_RESPONSE;
                Reply(tid, (char *) &rply, sizeof(rply));

                sensorservice_process_data(&service, msg.data);

                publish(&service, stream);
                break;
            default:
                ulog("Invalid SensorServer Request");
        }
    }

    Exit();
}
Exemple #12
0
void xalloc_report(void)
{
  XALLOC_REC *rec;
  HASH_NODE *node = NULL;
  int index = 0, i;
  char line[LEN], *l;

  struct info
  { int pos; char *fmt; int offset;
  } pinfo[] =  { {  8, "%d",   offsetof(XALLOC_REC, id) },
                 { 24, "%s",   offsetof(XALLOC_REC, file) },
                 { 32, "%d",   offsetof(XALLOC_REC, line) },
                 { 48, "%s",   offsetof(XALLOC_REC, name) },
                 { 64, "0x%x", offsetof(XALLOC_REC, ptr) },
                 {  0, "%d",   offsetof(XALLOC_REC, size) }};
  

  ulog(ULOG_INFO, "xalloc-report: ");
  if(!xalloc_initialized) {
    ulog(ULOG_INFO, "nothing to report.\n");
    return;
  }
  ulog(ULOG_INFO, "\n-------------\n");
  ulog(ULOG_INFO, "\ttotal xmalloc()  & xcalloc()   : %d\n",
          xalloc_numalloc);
  ulog(ULOG_INFO, "\ttotal xrealloc() & xrecalloc() : %d\n",
          xalloc_numrealloc);
  ulog(ULOG_INFO, "\ttotal xfree()    & xcfree()    : %d\n\n",
          xalloc_numfree);
  if(hash_iterate(xalloc_hash, &index, &node)) {
    node = NULL, index = 0;
    ulog(ULOG_INFO, "ID\tFILE\t\tLINE\tSOURCE\t\tADDRESS\t\tSIZE\n");
    ulog(ULOG_INFO, "--\t----\t\t----\t------\t\t-------\t\t----\n");
    while((rec = hash_iterate(xalloc_hash, &index, &node)) != NULL) {
      l = line;
      for(i = 0; i < sizeof(pinfo) / sizeof(struct info); i++) {
	sprintf(l, pinfo[i].fmt, *(int *)((char *)rec + pinfo[i].offset));
        l = l + strlen(l);
        while(l < line + pinfo[i].pos) *l++ = ' ';
      }
      ulog(ULOG_INFO, "%s\n", line);
    }
  }
  ulog(ULOG_INFO, "\n\n");
}
Exemple #13
0
char *
zsysdep_local_file (const char *zfile, const char *zpubdir, boolean *pfbadname)
{
  const char *zdir;

  if (pfbadname != NULL)
    *pfbadname = FALSE;

  if (*zfile == '/')
    return zbufcpy (zfile);

  if (*zfile != '~')
    zdir = zpubdir;
  else
    {
      if (zfile[1] == '\0')
	return zbufcpy (zpubdir);

      if (zfile[1] == '/')
	{
	  zdir = zpubdir;
	  zfile += 2;
	}
      else
	{
	  size_t cuserlen;
	  char *zcopy;
	  struct passwd *q;

	  ++zfile;
	  cuserlen = strcspn ((char *) zfile, "/");
	  zcopy = zbufalc (cuserlen + 1);
	  memcpy (zcopy, zfile, cuserlen);
	  zcopy[cuserlen] = '\0';
      
	  q = getpwnam (zcopy);
	  if (q == NULL)
	    {
	      ulog (LOG_ERROR, "User %s not found", zcopy);
	      ubuffree (zcopy);
	      if (pfbadname != NULL)
		*pfbadname = TRUE;
	      return NULL;
	    }
	  ubuffree (zcopy);

	  if (zfile[cuserlen] == '\0')
	    return zbufcpy (q->pw_dir);

	  zdir = q->pw_dir;
	  zfile += cuserlen + 1;
	}
    }

  return zsysdep_in_dir (zdir, zfile);
}
Exemple #14
0
JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM *vm, char *options, void *reserved) {
	jint rc;
	jvmtiEnv *jvmti;
	JNIEnv *jniEnv;
	jvmtiError err;


	char * optionType;
	char * otherOption = NULL;

	/* Get JVMTI environment */
	jvmti = NULL;
	rc = (*vm)->GetEnv(vm, (void **) &jvmti, JVMTI_VERSION);
	if (rc != JNI_OK) {
		ulog("ERROR: Unable to create jvmtiEnv, error=%d\n", rc);
		return JNI_ERR;
	}
	if (jvmti == NULL) {
		ulog("ERROR: No jvmtiEnv* returned from GetEnv\n");
		return JNI_ERR;
	}
	/////////////jni/////////////
	rc = (*vm)->GetEnv(vm, (void **) &jniEnv, JNI_VERSION_1_2);
	if (rc != JNI_OK) {
		ulog("ERROR: Unable to create jnienv, error=%d\n", rc);
		return JNI_ERR;
	}
	if (jvmti == NULL) {
		ulog("ERROR: No jnienv* returned from GetEnv\n");
		return JNI_ERR;
	}
	////////////////////////////
#ifdef DEBUG
	ulog("options: %s\n", options);
#endif

	parseOption(options, &optionType, &otherOption);

#ifdef DEBUG
	ulog("optionType:%s, otherOption: %s\n", optionType, otherOption==NULL?"":otherOption);
#endif


	if (strcmp(optionType, DUMP_REFER) == 0) {
		rc = printReferAction(jvmti, jniEnv, otherOption);
	} else if (strcmp(optionType, DUMP_ROOT) == 0) {
		rc = printRootReferAction(jvmti, otherOption);
	} else {
		rc = JNI_ERR;
		ulog("ERROR: invalid options\n");
	}

	err = (*jvmti)->DisposeEnvironment(jvmti);
	CHECK_ERROR_AND_RETURN(jvmti, err, "DisposeEnvironment error", JNI_ERR);

	return rc;
}
Exemple #15
0
static void train_reserved_node_reserved(int index, DisplayData *data, track_node *node) {
//    ulog("Train widget got reserved event for index %d, train %d, node %s", index, data->id, node->name);
    unsigned int j;
    for (j = 0; j < MAX_RESERVED_NODES; ++j) {
        if (data->reserved_nodes[j] == 0) {
            data->reserved_nodes[j] = node;
            return;
        }
    }
    ulog("ERROR: Train widget: Reserved more than MAX_RESERVED_NODES");
}
Exemple #16
0
bool fork_task(struct loop *loop, const char *program, char **argv, const char *name, int *output, pid_t *pid) {
	int pipes[2];
	if (pipe(pipes) == -1) {
		ulog(LLOG_ERROR, "Couldn't create %s pipes: %s\n", name, strerror(errno));
		return false;
	}
	pid_t new_pid = loop_fork(loop);
	if (new_pid == -1) {
		ulog(LLOG_ERROR, "Couldn't create new %s process: %s\n", name, strerror(errno));
		if (close(pipes[0]) == -1)
			ulog(LLOG_ERROR, "Failed to close %s read pipe: %s\n", name, strerror(errno));
		if (close(pipes[1]) == -1)
			ulog(LLOG_ERROR, "Failed to close %s write pipe: %s\n", name, strerror(errno));
		return false;
	}
	if (new_pid == 0) { // We are the child now.
		sanity(close(pipes[0]) != -1, "Failed to close %s read pipe in child: %s\n", name, strerror(errno));
		sanity(dup2(pipes[1], 1) != -1, "Failed to assign stdout of %s: %s\n", name, strerror(errno));
		sanity(close(pipes[1]) != -1, "Failed to close copy of %s write pipe: %s\n", name, strerror(errno));
		execv(program, argv);
		sanity(false, "Failed to execute %s (%s): %s\n", name, program, strerror(errno));
	} else {
		if (close(pipes[1]) == -1)
			ulog(LLOG_ERROR, "Couldn't close %s write pipe: %s\n", name, strerror(errno));
		ulog(LLOG_DEBUG, "Task %s (%s) started with FD %d and PID %d\n", name, program, pipes[0], (int) new_pid);
		*output = pipes[0];
		*pid = new_pid;
	}
	return true;
}
Exemple #17
0
/**
 * Logs a system error.
 *
 * This function is thread-safe.
 */
void nplSerror(
    const char* fmt,    /**< The message format */
    ...)                /**< Arguments referenced by the format */
{
    va_list     args;

    va_start(args, fmt);
    lock();
    ulog(LOG_ERR, "%s", strerror(errno));
    vulog(LOG_ERR, fmt, args);
    unlock();
    va_end(args);
}
Exemple #18
0
void xfree(void *ptr)
{
  if(ptr) {
    /* Move the pointer back to its real origin. */
    ptr = ((char *)ptr - xalloc_magic);

    /* Remove from the running total, and free it. */
    xalloc_total_used -= *((size_t *)ptr);
    free(ptr);
  }
  else
    ulog(ULOG_WARN, "xfree: passed a NULL pointer.");
}
Exemple #19
0
long
csysdep_size (const char *zfile)
{
  struct stat s;

  if (stat ((char *) zfile, &s) < 0)
    {
      if (errno == ENOENT)
	return -1;
      ulog (LOG_ERROR, "stat (%s): %s", zfile, strerror (errno));
      return -2;
    }

  return s.st_size;
}
Exemple #20
0
void __xcfree(char *file, int line, void *ptr)
{
  XALLOC_REC *rec, srch;
  
  if(!xalloc_initialized)
    xalloc_init();
  if(ptr) {
    srch.ptr = ptr;
    if((rec = hash_search(xalloc_hash, &srch)) == NULL) {
      ulog(ULOG_INFO, "(%s, %d): xcfree: attempted to free bad pointer.\n",
	   file, line);
      return;
    }
    hash_delete(xalloc_hash, rec);
    xar_destroy(rec);
  }
  else {
    ulog(ULOG_INFO, "(%s, %d): xfree: attempted to free NULL pointer.\n",
	 file, line);
    return;
  }
  xalloc_numfree++;
  xcfree(ptr);
}
Exemple #21
0
boolean
fcopy_file (const char *zfrom, const char *zto, boolean fpublic, boolean fmkdirs, boolean fsignals)
{
  FILE *efrom;
  boolean fret;

  efrom = fopen (zfrom, BINREAD);
  if (efrom == NULL)
    {
      ulog (LOG_ERROR, "fopen (%s): %s", zfrom, strerror (errno));
      return FALSE;
    }

  fret = fcopy_open_file (efrom, zto, fpublic, fmkdirs, fsignals);
  (void) fclose (efrom);
  return fret;
}
Exemple #22
0
DSM_ISUBSET *dsm_isubset(DATASET *dset, unsigned *index, unsigned len)
{
  DSM_ISUBSET *isubset;
  unsigned sz;
 
  sz = dataset_size(dset);
  if(len == 0 || len > sz) {
    ulog(ULOG_ERROR, "DSM_ISUBSET: parameters failed sanity check."
	 "%t(%d == 0 || %d > %d).", len, len, sz);
    return(NULL);
  }
  isubset = xmalloc(sizeof(DSM_ISUBSET));
  isubset->dset = dset;
  isubset->index = index;
  isubset->len = len;
  return(isubset);
}
Exemple #23
0
int userlog(char *param)
{
    char	*prname, *prpid, *grade, *msg;
    static char	lfn[PATH_MAX], token[14];
    int		rc;

    lfn[0] = '\0';
    strncpy(token, strtok(param, ","), 14);
    strncpy(token, strtok(NULL, ","), 14);
    snprintf(lfn, PATH_MAX, "%s/log/%s", getenv("FTND_ROOT"), token);
    prname = strtok(NULL, ",");
    prpid  = strtok(NULL, ",");
    grade  = strtok(NULL, ",");
    msg    = xstrcpy(cldecode(strtok(NULL, ";")));
    rc = ulog(lfn, grade, prname, prpid, msg);
    free(msg);
    return rc;
}
Exemple #24
0
void _masterProcessStatus() {
    /* Check if status is expired */
    unsigned long now = time(NULL);
    if(next_master_refresh_time < now) {
        objSds *value = dictFetchValue(master_cache,statusQuery);
        if(value) {
            sds oldptr = value->ptr;
            /* Re-asign the value */
            value->ptr = _masterGetStatus();
            sdsfree(oldptr);
            next_master_refresh_time = now + MASTER_STATUS_REFRESH_PERIOD;
        }
        else {
            ulog(CCACHE_WARNING,"master cache %s not found",statusQuery);
            next_master_refresh_time = now + MASTER_STATUS_REFRESH_PERIOD*1000;
        }
    }
}
Exemple #25
0
void *xmalloc(size_t size)
{
  size_t *ptr;

  /* Make room to keep the size. */ 
  size += xalloc_magic;

  /* Get the memory. */
  if(!(ptr = malloc(size)))
    ulog(ULOG_FATAL, "xmalloc: failed to get %ld bytes.", (long)size);

  /* Assign the size of the segment, and keep a running total. */
  *ptr = size;
  xalloc_total_used += size;

  /* Reset the pointer to the user memory. */
  ptr = (size_t *)((char *)ptr + xalloc_magic);  
  return(ptr);
}
Exemple #26
0
/*
 * Logs the currently-accumulated log-messages and resets the message-list for
 * the current thread.
 *
 * This function is thread-safe.
 */
void nplLog(
    const int   level)  /**< The level at which to log the messages.  One of
                          *  LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, or
                          *  LOG_DEBUG; otherwise, the behavior is undefined. */
{
    List*   list = getList();

    if (NULL != list && NULL != list->last) {
        static const unsigned       allPrioritiesMask = 
            LOG_MASK(LOG_ERR) |
            LOG_MASK(LOG_WARNING) |
            LOG_MASK(LOG_NOTICE) | 
            LOG_MASK(LOG_INFO) |
            LOG_MASK(LOG_DEBUG);
        const int                   priorityMask = LOG_MASK(level);

        lock();

        if ((priorityMask & allPrioritiesMask) == 0) {
            nplError("nplLog(): Invalid logging-level (%d)", level);
        }
        else if (getulogmask() & priorityMask) {
            const Message*     msg;

            for (msg = list->first; NULL != msg; msg = msg->next) {
                /*
                 * NB: The message is not printed using "ulog(level,
                 * msg->string)" because "msg->string" might have formatting
                 * characters in it (e.g., "%") from, for example, a call to
                 * "s_prod_info()" with a dangerous product-identifier.
                 */
                ulog(level, "%s", msg->string);

                if (msg == list->last)
                    break;
            }                       /* message loop */
        }                           /* messages should be printed */

        unlock();
        nplClear();
    }                               /* have messages */
}
Exemple #27
0
void *__xrealloc(char *file, int line, void * ptr, size_t size)
{
  XALLOC_REC *rec, srch;
  
  if(!xalloc_initialized)
    xalloc_init();
  if(ptr) {
    srch.ptr = ptr;
    if((rec = hash_search(xalloc_hash, &srch)) == NULL) {
      ulog(ULOG_INFO, "(%s, %d): xrealloc: attempted to realloc "
	   "from bad pointer.\n", file, line);
      return(NULL);
    }
    hash_delete(xalloc_hash, rec);
    xar_destroy(rec);
  }
  ptr = xrealloc(ptr, size);
  xalloc_numrealloc++, xalloc_id++;
  rec = xar_create(file, line, xalloc_id, xrealloc_name, ptr, size);
  hash_insert(xalloc_hash, rec);
  return(ptr);
}
Exemple #28
0
void *xrealloc(void *old_ptr, size_t size)
{
  size_t *new_ptr;

  /* If the old pointer is NULL then just do a standard malloc. */
  if(!old_ptr)
    return(xmalloc(size));

  /* If the new size request is zero then just free the old memory. */
  if(!size) {
    xfree(old_ptr);
    return(NULL);
  }

  /* Get back the pointer that was returned by either malloc() or realloc() */
  old_ptr = ((char *)old_ptr - xalloc_magic);

  /* Remove the old segment from the running total. */
  xalloc_total_used -= *((size_t *)old_ptr);

  /* Make room to keep the size. */
  size += xalloc_magic;

  /* Update the running total. */
  xalloc_total_used += size;

  /* Get the memory. */
  if(!(new_ptr = realloc(old_ptr, size)))
    ulog(ULOG_FATAL, "xrealloc: failed to get %ld bytes.", (long)size);

  /* Assign the size of the segment, and keep a running total. */
  *new_ptr = size;

  /* Reset the pointer to the user memory. */
  new_ptr = (size_t *)((char *)new_ptr + xalloc_magic);
  return((void *)new_ptr);
}
Exemple #29
0
boolean
fsysdep_in_directory (const char *zfile, const char *zdir, boolean fcheck, boolean freadable, const char *zuser)
{
  size_t c;
  char *zcopy, *zslash;
  struct stat s;

  if (*zfile != '/')
    return FALSE;
  c = strlen (zdir);
  if (c > 0 && zdir[c - 1] == '/')
    c--;
  if (strncmp (zfile, zdir, c) != 0
      || (zfile[c] != '/' && zfile[c] != '\0'))
    return FALSE;
  if (strstr (zfile + c, "/../") != NULL)
    return FALSE;

  /* If we're not checking access, get out now.  */
  if (! fcheck)
    return TRUE;

  zcopy = zbufcpy (zfile);

  /* Start checking directories after zdir.  Otherwise, we would
     require that all directories down to /usr/spool/uucppublic be
     publically searchable; they probably are but it should not be a
     requirement.  */
  zslash = zcopy + c;
  do
    {
      char b;
      struct stat shold;

      b = *zslash;
      *zslash = '\0';

      shold = s;
      if (stat (zcopy, &s) != 0)
	{
	  if (errno != ENOENT)
	    {
	      ulog (LOG_ERROR, "stat (%s): %s", zcopy, strerror (errno));
	      ubuffree (zcopy);
	      return FALSE;
	    }

	  /* If this is the top directory, any problems will be caught
	     later when we try to open it.  */
	  if (zslash == zcopy + c)
	    {
	      ubuffree (zcopy);
	      return TRUE;
	    }

	  /* Go back and check the last directory for read or write
	     access.  */
	  s = shold;
	  break;
	}

      /* If this is not a directory, get out of the loop.  */
      if (! S_ISDIR (s.st_mode))
	break;

      /* Make sure the directory is searchable.  */
      if (! fsuser_access (&s, X_OK, zuser))
	{
	  ulog (LOG_ERROR, "%s: %s", zcopy, strerror (EACCES));
	  ubuffree (zcopy);
	  return FALSE;
	}

      /* If we've reached the end of the string, get out.  */
      if (b == '\0')
	break;

      *zslash = b;
    }
  while ((zslash = strchr (zslash + 1, '/')) != NULL);

  /* At this point s holds a stat on the last component of the path.
     We must check it for readability or writeability.  */
  if (! fsuser_access (&s, freadable ? R_OK : W_OK, zuser))
    {
      ulog (LOG_ERROR, "%s: %s", zcopy, strerror (EACCES));
      ubuffree (zcopy);
      return FALSE;
    }

  ubuffree (zcopy);
  return TRUE;
}
Exemple #30
0
void upnp_service::map_port( uint16_t local_port )
{
  std::string port = fc::variant(local_port).as_string();

  my->map_port_complete = my->upnp_thread.async( [=]() {
      const char * multicastif = 0;
      const char * minissdpdpath = 0;
      struct UPNPDev * devlist = 0;
      char lanaddr[64];
      
      /* miniupnpc 1.6 */
      int error = 0;
      devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);

      struct UPNPUrls urls;
      memset( &urls, 0, sizeof(urls) );
      struct IGDdatas data;
      memset( &data, 0, sizeof(data) );
      int r;
      
      r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));

      bool port_mapping_added = false;
      bool port_mapping_added_successfully = false;

       if (r == 1)
       {
           if (true) //  TODO  config this ?  fDiscover) 
           {
               char externalIPAddress[40];
               r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
               if(r != UPNPCOMMAND_SUCCESS)
                   wlog("UPnP: GetExternalIPAddress() returned ${code}", ("code", r));
               else
               {
                   if(externalIPAddress[0])
                   {
                       ulog("UPnP: ExternalIPAddress = ${address}", ("address", externalIPAddress));
                       my->external_ip = fc::ip::address( std::string(externalIPAddress) );
                       // AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
                   }
                   else
                       wlog("UPnP: GetExternalIPAddress failed.");
               }
           }
       
           std::string strDesc = "BitShares 0.0"; // TODO  + FormatFullVersion();
       
     //      try 
           {
               while(!my->done)  // TODO provide way to exit cleanly
               {
                   /* miniupnpc 1.6 */
                   r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
                                       port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
       
                   port_mapping_added = true;
                   if(r!=UPNPCOMMAND_SUCCESS)
                       wlog("AddPortMapping(${port}, ${port}, ${addr}) failed with code ${code} (${string})",
                            ("port", port)("addr", lanaddr)("code", r)("string", strupnperror(r)));
                   else
                   {
                       if (!port_mapping_added_successfully)
                         ulog("UPnP Port Mapping successful");
                       port_mapping_added_successfully = true;

                       my->mapped_port = local_port;
                   }
       
                   fc::usleep( fc::seconds(60*20) ); // Refresh every 20 minutes
               }
           }
     //      catch (boost::thread_interrupted)
           {
               if( port_mapping_added )
               {
                 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
                 ilog("UPNP_DeletePortMapping() returned : ${r}", ("r",r));
                 freeUPNPDevlist(devlist); devlist = 0;
                 FreeUPNPUrls(&urls);
               }
      //         throw;
           }
       } else {
           //printf("No valid UPnP IGDs found\n");
           wlog("No valid UPnP IGDs found");
           freeUPNPDevlist(devlist); devlist = 0;
           if (r != 0)
           {
               FreeUPNPUrls(&urls);
           }
       }
  }, "upnp::map_port" );
}