Exemplo n.º 1
0
static void rpc_listen_event(int /*epoll*/, epoll_event &ev) {
    RPCTask *t = rpc_get_task_from_event(ev);
    if (NULL == t) {
        ZLOG(LOG_WARN, "Fail to get task from event.");
        return ;
    }

    if (ev.events & (EPOLLIN | EPOLLPRI) ) {
        // accept a new link
        int fd = tcp_accept(t->fd, true/*async*/, NULL/*&client*/);
        if (fd >= 0) {
            RPCServiceHandle *s = t->service;
            RPCTask *new_task = rpc_build_task(s, fd, RPC_EL_FD_IO);
            if (NULL == new_task) {
                ZLOG(LOG_WARN, "Fail to build task for I/O fd. [link: %u] [max: %u]",
                     s->link_count - 1, s->link_max);
                close(fd);
            } else {
                rpc_do_op_rec(new_task->op_next, new_task);
            }
        } else {
            ZLOG(LOG_WARN, "Accept return %d: errno = %d(%s)", fd, errno, ZSTRERR(errno).c_str() );
        }
    } else {
        ZLOG(LOG_FATAL, "Listen socket(%d) error. stop the service now. errno = %d (%s)",
             t->fd, errno, ZSTRERR(errno).c_str() );
        rpc_set_service_flags(t->service, RPC_FLAG_EXIT);
    }
}
Exemplo n.º 2
0
/**
 * Load configuration file.
 * @param[in] path Configuration file location.
 * @param[in,out] zconf Parsed configuration storage.
 * @return True on success.
 */
bool zconfig_load(const char *path, zconfig_t *zconf)
{
    if (NULL == path) {
        ZLOG(LOG_ERR, "config: configuration file not specified");
        return false;
    }

    bool loaded = false;
    config_t config;
    config_init(&config);

    if (!config_read_file(&config, path)) {
        ZLOG(LOG_ERR, "config: failed to parse %s (error: %s at %d line)",
             path, config_error_text(&config), config_error_line(&config));
        goto end;
    }

    const config_setting_t *root = config_root_setting(&config);

    if (!zconfig_load_sections(root, zconf)) {
        zconfig_destroy(zconf);
    } else {
        loaded = true;
    }

    end:
    config_destroy(&config);

    return loaded;
}
Exemplo n.º 3
0
/*
 * Records the time in sv and  returns its index in sv
 * Note that the first time this routine is called on a sv that was just
 * constructed via NaClPerfCounterCtor(), it will return 1, but that
 * is actually the SECOND sample.
 */
int NaClPerfCounterMark(struct NaClPerfCounter *sv, const char *ev_name)
{
  if((NULL == sv) || (NULL == ev_name))
  {
    ZLOG(LOG_ERROR, "NaClPerfCounterMark received null args");
    return -1;
  }
  if(sv->samples >= NACL_MAX_PERF_COUNTER_SAMPLES)
  {
    ZLOG(LOG_ERROR, "NaClPerfCounterMark going beyond buffer size");
    return -1;
  }
  /* busy loop until we succeed, damn it */
  while(0 != NaClGetTimeOfDay(&(sv->sample_list[sv->samples])))
    ;

  /*
   * This relies upon memset() inside NaClPerfCounterCtor() for
   * correctness
   */

  NACL_ASSERT_IS_ARRAY(sv->sample_names[sv->samples]);

  strncpy(sv->sample_names[sv->samples], ev_name, LAST_IDX(sv->sample_names[sv->samples]));
  /* Being explicit about string termination */
  sv->sample_names[sv->samples][LAST_IDX(sv->sample_names[sv->samples])] = '\0';

  return (sv->samples)++;
}
Exemplo n.º 4
0
static void rpc_io_event(int /*epoll*/, epoll_event &ev) {
    RPCTask *t = rpc_get_task_from_event(ev);
    if (NULL == t) {
        ZLOG(LOG_WARN, "Fail to get task from event.");
        return ;
    }

    if (ev.events & (EPOLLERR | EPOLLHUP) ) {
        ZLOG(LOG_DEBUG, "Client %d exit.", t->fd);
        if (RPC_OP_CLOSE != t->op_next) {
            // ERR(CPU) --> END(CPU) --> CLOSE(IO)
            t->op_next = RPC_OP_ERR;
        }
    }

    if ( (RPC_OP_READ == t->op_next) && !(ev.events & (EPOLLIN | EPOLLPRI) ) ) {
        ZLOG(LOG_WARN, "EPOLLIN (%d) expected. but event [%d] occured.", EPOLLIN, ev.events);
        t->op_next = RPC_OP_ERR;
    }

    if ( (RPC_OP_WRITE == t->op_next) && !(ev.events & EPOLLOUT) ) {
        ZLOG(LOG_WARN, "EPOLLOUT (%d) expected. but event [%d] occured.", EPOLLOUT, ev.events);
        t->op_next = RPC_OP_ERR;
    }

    if (RPC_CPU_BIND == g_rpc_op_type[rpc_do_op(t->op_next, t)]) {
        rpc_do_op_rec(t->op_next, t);
    }
}
Exemplo n.º 5
0
static void* rpc_worker_thread_main(void *arg_) {
    rpc_worker_thread_arg_t *arg = (rpc_worker_thread_arg_t*)(arg_);
    if (NULL == arg) {
        ZLOG(LOG_FATAL, "NULL thread argument.");
        assert(0);
    }

    RPCServiceHandle *service = arg->service;
    if (NULL == service) {
        ZLOG(LOG_FATAL, "NULL service in worker thread.");
        assert(0);
    }

    RPCServiceHandle::task_queue_t *task_queue = service->task_queue[arg->thread_id];
    while (! (service->flags & RPC_FLAG_FORCE_EXIT) ) {
        RPCTask* task = NULL;
        if (task_queue->dequeue(&task) ) {
            if (task->type == RPC_EL_FD_END_FLAG) {
                break;
            }

            rpc_do_op_rec(task->op_next, task);
        }

        if (task_queue->isEmpty() ) {
            zsleep_ms(RPC_WORKER_IDLE_WAIT_MS);
        }
    }

    return NULL;
}
Exemplo n.º 6
0
int sample_http_server_op_err(RPCTask *t) {
    ZLOG(LOG_INFO, "err");
    ZLOG(LOG_WARN, "http server error. [fd: %d]",
        t->fd);
    
    return RPC_OP_END;
}
Exemplo n.º 7
0
static void rpc_unknown_event(int /*epoll*/, epoll_event &ev) {
    RPCTask *t = rpc_get_task_from_event(ev);
    if (NULL == t) {
        ZLOG(LOG_WARN, "Fail to get task from event.");
        return ;
    }

    ZLOG(LOG_WARN, "Unknown fd/task type. [fd: %d] [type: %d]",
         t->fd, int(t->type) );
}
Exemplo n.º 8
0
/**
 * Load interfaces section.
 * @param[in] option Option name.
 * @param[in,out] array Resulting array.
 * @return <0 - error. 0 - success. >0 - not found.
 */
int zcfg_load_interfaces(const config_setting_t *option, UT_array *array)
{
    utarray_init(array, &ut_zif_pair_icd);

    if (!option) {
        return 1;
    }

    if (CONFIG_TYPE_LIST != option->type) {
        return -1;
    }

    u_int count = (u_int) config_setting_length(option);

    for (u_int i = 0; i < count; i++) {
        zifpair_t if_pair;
        const char *str;
        config_setting_t *entry = config_setting_get_elem(option, i);

        if (!config_setting_lookup_string(entry, ZCFG_LAN, &str)) {
            ZLOG(LOG_ERR, "config:%s:%s: invalid or missing 'lan' property", option->parent->name, option->name);
            goto fail;
        }
        strncpy(if_pair.lan, str, sizeof(if_pair.lan));

        if (!config_setting_lookup_string(entry, ZCFG_WAN, &str)) {
            ZLOG(LOG_ERR, "config:%s:%s: invalid or missing 'wan' property", option->parent->name, option->name);
            goto fail;
        }
        strncpy(if_pair.wan, str, sizeof(if_pair.wan));

        int affinity = 0;
        if (!config_setting_lookup_int(entry, ZCFG_AFFINITY, &affinity)) {
            ZLOG(LOG_ERR, "config:%s:%s: invalid or missing 'affinity' property", option->parent->name, option->name);
            goto fail;
        }
        if ((affinity < 0) || affinity >= UINT16_MAX) {
            ZLOG(LOG_ERR, "config:%s:%s: invalid 'affinity' value", option->parent->name, option->name);
            goto fail;
        }
        if_pair.affinity = (uint16_t) affinity;

        utarray_push_back(array, &if_pair);
    }

    return 0;

    fail:
    utarray_done(array);
    return -1;
}
Exemplo n.º 9
0
static int rpc_do_op(int op, RPCTask *task) {
    if (op >= RPC_OP_LIMIT) {
        ZLOG(LOG_WARN, "rcp_op error. [op: %d] >= [limit: %d]",
             op, RPC_OP_LIMIT);
        task->op_next = RPC_OP_ERR;
        return RPC_OP_ERR;
    }

    task->op_prev = task->op_next;
    int op_next = (task->service->service_op[op])(task);

    if (task->op_prev == RPC_OP_SCHED && op_next >= RPC_OP_LIMIT) {
        // the return value of RPC_OP_SCHED is a encoded task queue id
        int target_queue_id = rpc_decode_queue_id_for_op_sched(op_next);
        if (target_queue_id < 0 || (uint32_t)target_queue_id >= task->service->calc_thread) {
            ZLOG(LOG_FATAL, "Incorrect target queue id: [%d], should in [0, %u)",
                 target_queue_id, task->service->calc_thread);
            op_next = RPC_OP_ERR;
            task->op_next = op_next;
        }

        op_next = RPC_OP_NOOP;
        task->op_next = RPC_OP_CALC;
        rpc_unpoll_task(task->service, task);
        task->service->task_queue[target_queue_id]->enqueue(task);
    } else {
        if (op_next >= RPC_OP_LIMIT || op_next < 0) {
            ZLOG(LOG_FATAL, "Incorrect op_next returned from op function. "
                 "set op_next = OP_RPC_ERR, [op: %d] [ret_op: %d] [limit: %d]",
                 op, op_next, RPC_OP_LIMIT);
            op_next = RPC_OP_ERR;
        }

        task->op_next = op_next;

        if (rpc_switch_op_polling_stat(task->op_prev, op_next, task) ) {
            ZLOG(LOG_FATAL, "Fail to switch polling stat. set op_next as RPC_OP_ERR. "
                 "[fd: %d] [prev: %d] [next: %d]",
                 task->fd, task->op_prev, op_next);

            rpc_unpoll_task(task->service, task);
            op_next = RPC_OP_ERR;
        }
        task->op_next = op_next;
    }

    return op_next;
}
Exemplo n.º 10
0
void NaClPerfCounterCtor(struct NaClPerfCounter *sv, const char *app_name)
{
  if(NULL == sv)
  {
    ZLOG(LOG_ERROR, "NaClPerfCounterStart received null pointer");
    return;
  };

  memset(sv, 0, sizeof(struct NaClPerfCounter));

  if(NULL == app_name)
  {
    app_name = "__unknown_app__";
  }

  NACL_ASSERT_IS_ARRAY(sv->app_name);
  strncpy(sv->app_name, app_name, LAST_IDX(sv->app_name));

  /* Being explicit about string termination */
  sv->app_name[LAST_IDX(sv->app_name)] = '\0';

  strncpy(sv->sample_names[0], "__start__", LAST_IDX(sv->sample_names[0]));

  while(0 != NaClGetTimeOfDay(&sv->sample_list[sv->samples]))
  {
    /* repeat until we get a sample */
  }

  sv->samples++;
}
Exemplo n.º 11
0
RPCServiceHandle * create_sample_http_service(int listen_fd, int thread_num) {
    ZLOG(LOG_INFO, "create");
    RPCServiceHandle *s = new RPCServiceHandle;
    s->listen_socket    = listen_fd;
    s->epoll_fd         = -1;
    memset(s->service_op, 0, sizeof(s->service_op) );
    s->link_count       = 0;
    s->link_max         = 102400;
    s->calc_thread      = thread_num;
    s->task_queue_size  = 102400;
        
    s->task_pool        = NULL;
    s->task_queue       = NULL;
    s->calc_thread_id   = NULL;
    s->calc_thread_arg  = NULL;
    s->flags            = 0;
    s->d                = NULL;

    s->service_op[RPC_OP_ERR] = sample_http_server_op_err;
    s->service_op[RPC_OP_BEGIN] = sample_http_server_op_begin;
    s->service_op[RPC_OP_READ] = sample_http_server_op_read;
    s->service_op[RPC_OP_SCHED] = sample_http_server_op_sched;
    s->service_op[RPC_OP_CALC] = sample_http_server_op_calc;
    s->service_op[RPC_OP_WRITE] = sample_http_server_op_write;
    s->service_op[RPC_OP_END] = sample_http_server_op_end;
    s->service_op[RPC_OP_CLOSE] = sample_http_server_op_close;

    return s;
}
Exemplo n.º 12
0
/* TODO(d'b): rework "-t" and update the function */
static void OutputReport(char *r)
{
    char *p = NULL;
    int size = strlen(r);

#define REPORT(p) ZLOGIF(write(report_handle, p, size) != size, \
  "report write error %d: %s", errno, strerror(errno))

    switch(report_mode)
    {
    case 3: /* unix socket */
        p = g_strdup_printf("0x%06x%s", size, r);
        size = strlen(p);
        REPORT(p);
        g_free(p);
        break;
    case 0: /* stdout */
        REPORT(r);
        break;
    case 1: /* syslog */
        ZLOGS(LOG_ERROR, "%s", r);
        break;
    default:
        ZLOG(LOG_ERROR, "invalid report mode %d", report_mode);
        break;
    }
#undef REPORT
}
Exemplo n.º 13
0
/**
 * Load uint16 array.
 * @param[in] option Configuration option.
 * @param[in,out] array Resulting array.
 * @return <0 - error. 0 - success. >0 - not found.
 */
static int zcfg_load_uint16_array(const config_setting_t *option, UT_array *array)
{
    utarray_init(array, &ut_uint16_icd);

    if (!option) {
        return 1;
    }

    if (CONFIG_TYPE_ARRAY != option->type) {
        return -1;
    }

    int count = config_setting_length(option);

    for (int i = 0; i < count; i++) {
        int item = config_setting_get_int_elem(option, i);

        if ((item < 0) || (item > UINT16_MAX)) {
            ZLOG(LOG_ERR, "config:%s:%s: invalid port: %d", option->parent->name, option->name, item);
            utarray_done(array);
            return -1;
        }

        uint16_t port = (uint16_t) item;
        utarray_push_back(array, &port);
    }

    if (utarray_len(array)) {
        utarray_sort(array, uint16_cmp);
    }

    return 0;
}
Exemplo n.º 14
0
/**
 * Load client rules list.
 * @param[in] option Configuration option.
 * @param[in,out] rules Resulting rules.
 * @return <0 - error. 0 - success. >0 - not found.
 */
static int zcfg_load_client_rules(const config_setting_t *option, zclient_rules_t *rules)
{
    zclient_rules_init(rules);

    if (!option) {
        return 1;
    }

    if (CONFIG_TYPE_LIST != option->type) {
        return -1;
    }

    int count = config_setting_length(option);

    zclient_rule_parser_t *rule_parser = zclient_rule_parser_new();

    for (int i = 0; i < count; i++) {
        const char *str = config_setting_get_string_elem(option, i);
        if (!zclient_rule_parse(rule_parser, rules, str)) {
            ZLOG(LOG_ERR, "config:%s:%s: invalid client rule: %s", option->parent->name, option->name, str);
            zclient_rule_parser_free(rule_parser);
            return -1;
        }
    }

    zclient_rule_parser_free(rule_parser);
    return 0;
}
Exemplo n.º 15
0
/// \sa ZBlackBerry::Device_Client::Write
bool ZBlackBerryServer::Handler_DeviceFinished::Write(const ZStreamW& w)
	{
	if (!fOpen)
		{
		if (ZLOG(s, eDebug + 2, "ZBlackBerryServer::Handler_DeviceFinished"))
			s << "Write false, return false";

		w.WriteBool(false);
		return false;
		}

	if (ZLOG(s, eDebug + 2, "ZBlackBerryServer::Handler_DeviceFinished"))
		s << "Write nothing, return true";

	return true;
	}
Exemplo n.º 16
0
int sample_http_server_op_write(RPCTask *t) {
    ZLOG(LOG_INFO, "write");
    HttpRR *h = (HttpRR*)t->dptr;

    char out[8192];
    uint32_t len = snprintf(out, sizeof(out),
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/html\r\n"
        "Content-Length: %u\r\n"
        "\r\n"
        "URI: %s",
        5 + h->resp_length, h->buf + h->resp);
    
    ssize_t w = write(t->fd, out + h->wpos, len - h->wpos);
    if (w == 0) {
        return RPC_OP_WRITE;
    } else if (w < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
            return RPC_OP_WRITE;
        }
        return RPC_OP_END;
    } else {
        h->wpos += w;
        if (h->wpos >= len) {
            return RPC_OP_END;
        }
        return RPC_OP_WRITE;
    }
}
Exemplo n.º 17
0
int rpc_encode_queue_id_for_op_sched(int queue_id) {
    if (queue_id < 0) {
        ZLOG(LOG_WARN, "Incorrect queue id, should >=0. [id: %d]", queue_id);
        return RPC_OP_ERR;
    }

    return RPC_OP_LIMIT + queue_id;
}
Exemplo n.º 18
0
int sample_http_server_op_calc(RPCTask *t) {
    ZLOG(LOG_INFO, "calc");
    HttpRR *h = (HttpRR*)t->dptr;
    h->resp = h->uri;
    h->resp_length = strlen(h->buf + h->uri);

    return RPC_OP_WRITE;
}
Exemplo n.º 19
0
Arquivo: trap.c Projeto: Abioy/zerovm
int32_t TrapHandler(struct NaClApp *nap, uint32_t args)
{
  uint64_t *sargs;
  int retcode = 0;
  int i;

  assert(nap != NULL);
  assert(nap->manifest != NULL);

  /*
   * translate address from user space to system
   * note: cannot set "trap error"
   */
  sargs = (uint64_t*)NaClUserToSys(nap, (uintptr_t)args);
  i = FunctionIndexById(*sargs);
  ZLOGS(LOG_DEBUG, "%s called", function[i]);
  ZTrace("untrusted code");

  switch(*sargs)
  {
    case TrapFork:
      if(Daemon(nap) == 0)
      {
        SyscallZTrace(5, function[5]);
        ZVMExitHandle(nap, 0);
      }
      break;
    case TrapExit:
      ZVMExitHandle(nap, (int32_t)sargs[2]);
      break;
    case TrapRead:
      retcode = ZVMReadHandle(nap,
          (int)sargs[2], (char*)sargs[3], (int32_t)sargs[4], sargs[5]);
      break;
    case TrapWrite:
      retcode = ZVMWriteHandle(nap,
          (int)sargs[2], (char*)sargs[3], (int32_t)sargs[4], sargs[5]);
      break;
    case TrapJail:
      retcode = ZVMJailHandle(nap, (uint32_t)sargs[2], (int32_t)sargs[3]);
      break;
    case TrapUnjail:
      retcode = ZVMUnjailHandle(nap, (uint32_t)sargs[2], (int32_t)sargs[3]);
      break;
    default:
      retcode = -EPERM;
      ZLOG(LOG_ERROR, "function %ld is not supported", *sargs);
      break;
  }

  /* report, ztrace and return */
  FastReport();
  ZLOGS(LOG_DEBUG, "%s returned %d", function[i], retcode);
  SyscallZTrace(i, function[i], sargs[2], sargs[3], sargs[4], sargs[5], retcode);
  return retcode;
}
Exemplo n.º 20
0
/*
 * NaClAllocatePow2AlignedMemory is for allocating a large amount of
 * memory of mem_sz bytes that must be address aligned, so that
 * log_alignment low-order address bits must be zero.
 *
 * Returns the aligned region on success, or NULL on failure.
 */
static void *NaClAllocatePow2AlignedMemory(size_t mem_sz, size_t log_alignment)
{
  uintptr_t pow2align;
  size_t request_sz;
  void *mem_ptr;
  uintptr_t orig_addr;
  uintptr_t rounded_addr;
  size_t extra;

  pow2align = ((uintptr_t)1) << log_alignment;
  request_sz = mem_sz + pow2align;
  ZLOGS(LOG_INSANE, "%25s %016lx", " Ask:", request_sz);

  /* d'b: try to get the fixed address r15 (user base register) */
  /*
   * WARNING: mmap can overwrite the zerovm dynamically linked code.
   * to prevent it the code should be linked statically
   */
  mem_ptr = mmap(R15_CONST, request_sz, PROT_NONE, ABSOLUTE_MMAP, -1, (off_t)0);
  if(MAP_FAILED == mem_ptr)
  {
    ZLOG(LOG_ERROR, "the base register absolute address allocation failed!"
        " trying to allocate user space in NOT DETERMINISTIC WAY");
    mem_ptr = mmap(NULL, request_sz, PROT_NONE, RELATIVE_MMAP, -1, (off_t)0);
    ZLOGFAIL(MAP_FAILED == mem_ptr, ENOMEM, FAILED_MSG);
  }

  orig_addr = (uintptr_t)mem_ptr;
  ZLOGS(LOG_INSANE, "%25s %016lx", "orig memory at", orig_addr);

  rounded_addr = (orig_addr + (pow2align - 1)) & ~(pow2align - 1);
  extra = rounded_addr - orig_addr;
  if(0 != extra)
  {
    ZLOGS(LOG_INSANE, "%25s %016lx, %016lx", "Freeing front:", orig_addr, extra);
    ZLOGFAIL(-1 == munmap((void *)orig_addr, extra), errno, "munmap front failed");
  }

  extra = pow2align - extra;
  if(0 != extra)
  {
    ZLOGS(LOG_INSANE, "%25s %016lx, %016lx", "Freeing tail:", rounded_addr + mem_sz, extra);
    ZLOGFAIL(-1 == munmap((void *)(rounded_addr + mem_sz), extra), errno, "munmap tail failed");
  }

  ZLOGS(LOG_INSANE, "%25s %016lx", "Aligned memory:", rounded_addr);

  /*
   * we could also mmap again at rounded_addr w/o MAP_NORESERVE etc to
   * ensure that we have the memory, but that's better done in another
   * utility function.  the semantics here is no paging space
   * reserved, as in Windows MEM_RESERVE without MEM_COMMIT.
   */

  return (void *)rounded_addr;
}
Exemplo n.º 21
0
int sample_http_server_op_end(RPCTask *t) {
    ZLOG(LOG_INFO, "end");
    HttpRR *h = (HttpRR*)t->dptr;
    delete h;

    t->dn = 0;
    t->dptr = NULL;

    return RPC_OP_CLOSE;
}
Exemplo n.º 22
0
int sample_http_server_op_begin(RPCTask *t) {
    ZLOG(LOG_INFO, "begin");
    if (t->dn || t->dptr) {
        ZLOG(LOG_WARN, "Not null task. [dn: %lu] [dptr: %p]", t->dn, t->dptr);
    }

    HttpRR *h = new HttpRR;
    h->pos = 0;
    h->uri = 0;
    h->host = 0;
    h->resp = 0;
    h->resp_length = 0;
    h->wpos = 0;
    h->buf[0] = 0;
    h->buf[sizeof(h->buf) - 1] = 0;
    
    t->dn = sizeof(HttpRR);
    t->dptr = h;

    return RPC_OP_READ;
}
Exemplo n.º 23
0
/*
 * "One Ring" syscall main routine. the nacl syscalls replacement.
 * "args" is an array of syscall name and its arguments
 * note: since nacl patch two 1st arguments if they are pointers, arg[1] are not used
 * todo(d'b): check how nacl decide to patch arguments.
 */
int32_t TrapHandler(struct NaClApp *nap, uint32_t args)
{
  uint64_t *sys_args;
  int retcode = 0;

  assert(nap != NULL);
  assert(nap->system_manifest != NULL);

  /*
   * translate address from user space to system
   * note: cannot set "trap error"
   */
  sys_args = (uint64_t*)NaClUserToSys(nap, (uintptr_t) args);
  ZLOGS(LOG_DEBUG, "%s called", FunctionNameById(sys_args[0]));

  switch(*sys_args)
  {
    case TrapExit:
      retcode = ZVMExitHandle(nap, (int32_t) sys_args[2]);
      break;
    case TrapRead:
      retcode = ZVMReadHandle(nap,
          (int)sys_args[2], (char*)sys_args[3], (int32_t)sys_args[4], sys_args[5]);
      break;
    case TrapWrite:
      retcode = ZVMWriteHandle(nap,
          (int)sys_args[2], (char*)sys_args[3], (int32_t)sys_args[4], sys_args[5]);
      break;
    case TrapSyscallback:
      retcode = ZVMSyscallback(nap, (int32_t)sys_args[2]);
      break;
    case TrapChannels:
      retcode = ZVMChannels(nap, (struct ZVMChannel*)sys_args[2]);
      break;
    case TrapChannelName:
      retcode = ZVMChannelName(nap, (struct ZVMChannel*)sys_args[2], (int32_t)sys_args[3]);
      break;
    case TrapHeapEnd:
      retcode = ZVMHeapEnd(nap);
      break;
    case TrapHeapPtr:
      retcode = ZVMHeapPtr(nap);
      break;
    default:
      retcode = -EPERM;
      ZLOG(LOG_ERROR, "function %ld is not supported", *sys_args);
      break;
  }

  ZLOGS(LOG_DEBUG, "%s returned %d", FunctionNameById(sys_args[0]), retcode);
  return retcode;
}
Exemplo n.º 24
0
/**
 * Authenticate and set client info.
 * @param[in] session Client session.
 * @return Zero on success.
 */
zrad_status_t zradius_session_auth(zscope_t *scope, zsession_t *session)
{
    zrad_status_t ret;
    VALUE_PAIR *reply_attrs = NULL;
    char reply_msg[PW_MAX_MSG_SIZE] = {0};

    zclient_rules_t rules;
    zclient_rules_init(&rules);

    zrad_auth_req_t req;
    zrad_auth_prepare(scope, session, &req);

    ret = zrad_auth_request(scope->radh, &req, &reply_attrs, reply_msg);
    if (unlikely(ZRAD_OK != ret)) {
        str_rtrim(reply_msg);
        ZLOG(LOG_ERR, "%s: Session authentication failed for %s (code: %s, msg: %s)",
             scope->cfg->name, session->ip_str, zrad_decode_state(ret), reply_msg);
        goto end;
    }

    zrad_auth_parse(session, reply_attrs, &rules);

    if (unlikely(!rules.have.user_id || !rules.have.login)) {
        ZLOG(LOG_ERR, "%s: Session authentication failed for %s (login or user_id not found)",
             scope->cfg->name, session->ip_str);
        ret = ZRAD_OTHER;
        goto end;
    }

    zscope_session_rules_apply(scope, session, &rules);
    zrad_auth_log(scope, session, reply_attrs);

    end:
    zclient_rules_destroy(&rules);
    if (likely(reply_attrs)) rc_avpair_free(reply_attrs);

    return ret;
}
Exemplo n.º 25
0
void ZopfliCalculateEntropy(const size_t* count, size_t n, zfloat* bitlengths) {
  size_t sum = 0;
  size_t i;
  zfloat log2sum;
  for (i = 0; i < n; ++i) {
    sum += count[i];
  }
  log2sum = (sum == 0 ? ZLOG(n) : ZLOG(sum)) * ZOPFLI_INVLOG2;
  for (i = 0; i < n; ++i) {
    /* When the count of the symbol is 0, but its cost is requested anyway, it
    means the symbol will appear at least once anyway, so give it the cost as if
    its count is 1.*/
    if (count[i] == 0) bitlengths[i] = log2sum;
    else bitlengths[i] = log2sum - ZLOG(count[i]) * ZOPFLI_INVLOG2;
    /* Depending on compiler and architecture, the above subtraction of two
    floating point numbers may give a negative result very close to zero
    instead of zero (e.g. -5.973954e-17 with gcc 4.1.2 on Ubuntu 11.4). Clamp
    it to zero. These floating point imprecisions do not affect the cost model
    significantly so this is ok. */
    if (bitlengths[i] < 0 && bitlengths[i] > ZOPFLI_CLOSENEGATIVE) bitlengths[i] = 0;
    assert(bitlengths[i] >= 0);
  }
}
Exemplo n.º 26
0
/**
 * Load subnet array.
 * @param[in] cfg Config section.
 * @param[in] option Option name.
 * @param[in,out] array Resulting array.
 * @return <0 - error. 0 - success. >0 - not found.
 */
static int zcfg_load_subnet_list(const config_setting_t *option, zsubnet_group_t *array)
{
    utarray_init(array, &ut_ip_range_icd);

    if (!option) {
        return 1;
    }

    if (CONFIG_TYPE_LIST != option->type) {
        return -1;
    }

    int count = config_setting_length(option);

    for (int i = 0; i < count; i++) {
        ip_range_t range;
        char ip_str[INET_ADDRSTRLEN];
        const char *item = config_setting_get_string_elem(option, i);
        const char *cidr_pos = strchr(item, '/');

        // search CIDR, and make sure, that ip part is not bigger than buffer size
        if (cidr_pos && (((size_t) (cidr_pos - item) < sizeof(ip_str)))) {
            strncpy(ip_str, item, cidr_pos - item);
            ip_str[cidr_pos - item] = '\0';

            struct in_addr ip_addr;
            if (0 < inet_pton(AF_INET, ip_str, &ip_addr)) {
                uint8_t cidr = 0;
                if ((0 == str_to_u8(cidr_pos + 1, &cidr)) && (cidr <= CIDR_MAX)) {
                    range.ip_start = ntohl(ip_addr.s_addr);
                    range.ip_end = IP_RANGE_END(range.ip_start, cidr);
                    utarray_push_back(array, &range);
                    continue;
                }
            }
        }

        // error handler
        ZLOG(LOG_ERR, "config:%s:%s: invalid subnet: %s", option->parent->name, option->name, item);
        utarray_done(array);
        return -1;
    }

    if (count) {
        utarray_sort(array, ip_range_cmp);
    }

    return 0;
}
Exemplo n.º 27
0
/**
 * @param[in] root Root section of config.
 * @param[in] zconf Config handle.
 * @return True on success.
 */
bool zconfig_load_sections(const config_setting_t *root, zconfig_t *zconf)
{
    // global section
    config_setting_t *section = config_setting_get_member(root, ZCFG_SECTION_GLOBAL);
    if (!section) {
        ZLOG(LOG_ERR, "config: %s section not found", ZCFG_SECTION_GLOBAL);
        return false;
    }
    if (0 != zconfig_global_load(section, zconf)) {
        ZLOG(LOG_ERR, "config: failed to load %s section", ZCFG_SECTION_GLOBAL);
        return false;
    }

    // all other sections parse as scopes
    u_int sections_count = (u_int) config_setting_length(root);

    // global section + minimum one scope section
    if (sections_count < 2) {
        ZLOG(LOG_ERR, "config: no scopes found");
        return false;
    }

    utarray_init(&zconf->scopes, &ut_ptr_icd);
    for (u_int i = 0; i < sections_count; i++) {
        section = config_setting_get_elem(root, i);

        if (!config_setting_is_group(section)) {
            continue;
        }
        if (0 == strcmp(section->name, ZCFG_SECTION_GLOBAL)) {
            continue;
        }

        for (size_t j = 0; j < utarray_len(&zconf->scopes); j++) {
            zconfig_scope_t *sc = *(zconfig_scope_t **) utarray_eltptr(&zconf->scopes, j);
            if (0 == strcasecmp(sc->name, section->name)) {
                ZLOG(LOG_ERR, "config: duplicate scope %s", section->name);
                return false;
            }
        }

        zconfig_scope_t *scope = malloc(sizeof(*scope));
        if (0 == zconfig_scope_load(section, scope)) {
            utarray_push_back(&zconf->scopes, &scope);
            ZLOG(LOG_DEBUG, "config: loaded scope %s", scope->name);
        } else {
            zconfig_scope_destroy(scope);
            free(scope);
            ZLOG(LOG_ERR, "config: failed to load scope %s", section->name);
            return false;
        }
    }

    return true;
}
Exemplo n.º 28
0
/* get internal i/o information from channels counters */
static int GetChannelsAccounting(const struct NaClApp *nap, char *buf, int size)
{
  int64_t network_stats[IOLimitsCount] = {0};
  int64_t local_stats[IOLimitsCount] = {0};
  int i;

  assert(nap != NULL);
  assert(nap->system_manifest != NULL);
  assert(buf != NULL);
  assert(size != 0);

  /* gather all channels statistics */
  for(i = 0; i < nap->system_manifest->channels_count; ++i)
  {
    struct ChannelDesc *channel = &nap->system_manifest->channels[i];
    int64_t *stats = NULL;
    int j;

    /* select proper stats array */
    switch(channel->source)
    {
      case ChannelRegular:
      case ChannelCharacter:
      case ChannelFIFO:
        stats = local_stats;
        break;
      case ChannelTCP:
        stats = network_stats;
        break;
      default:
        ZLOG(LOG_ERR, "'%s': source type '%s' not supported",
            channel->name, StringizeChannelSourceType(channel->source));
        buf = DEFAULT_ACCOUNTING;
        return sizeof DEFAULT_ACCOUNTING;
    }

    for(j = 0; j < IOLimitsCount; ++j)
      stats[j] += channel->counters[j];
  }

  /* construct the accounting statistics string */
  return g_snprintf(buf, size, "%ld %ld %ld %ld %ld %ld %ld %ld",
      local_stats[GetsLimit], local_stats[GetSizeLimit],
      local_stats[PutsLimit], local_stats[PutSizeLimit],
      network_stats[GetsLimit], network_stats[GetSizeLimit],
      network_stats[PutsLimit], network_stats[PutSizeLimit]);
}
Exemplo n.º 29
0
static void rpc_do_op_rec(int op, RPCTask *task) {
    int op_next = op;
    int err_cnt = 0;
    do {
        op_next = rpc_do_op(op_next, task);
        if (task->op_prev == RPC_OP_ERR && task->op_next == RPC_OP_ERR) {
            ++err_cnt;
        }

        if (err_cnt >= ERR_RECHECK_COUNT) {
            err_cnt = 0;
            ZLOG(LOG_WARN, "Recursively call RPC_OP_ERR for %d times now! sleep 3 seconds.",
                 ERR_RECHECK_COUNT);
            zsleep_sec(3);
        }
    } while (RPC_OP_NOOP != op_next && RPC_CPU_BIND == g_rpc_op_type[op_next]);
}
Exemplo n.º 30
0
static int rpc_poll_task(RPCServiceHandle *service, RPCTask *task, int events) {
    epoll_event ev;
    ev.events = events;
    ev.data.ptr = task;

    int r = (task->events) ?
            epoll_ctl(service->epoll_fd, EPOLL_CTL_MOD, task->fd, &ev)
            : epoll_ctl(service->epoll_fd, EPOLL_CTL_ADD, task->fd, &ev);

    if (0 == r) {
        task->events |= events;
    } else {
        ZLOG(LOG_WARN, "Fail to poll task. [efd: %d], [fd: %d], [events: %d] [errno: %d, %s]",
             service->epoll_fd, task->fd, events, errno, ZSTRERR(errno).c_str() );
    }

    return r;
}