static void *
basic_thread(void *arg)
{
	struct cond_wait cw;
	struct event_base *base = arg;
	struct event ev;
	int i = 0;

	assert(pthread_mutex_init(&cw.lock, NULL) == 0);
	assert(pthread_cond_init(&cw.cond, NULL) == 0);

	evtimer_assign(&ev, base, basic_timeout, &cw);
	for (i = 0; i < 100; i++) {
		struct timeval tv;
		evutil_timerclear(&tv);
		assert(evtimer_add(&ev, &tv) == 0);

		assert(pthread_mutex_lock(&cw.lock) == 0);
		assert(pthread_cond_wait(&cw.cond, &cw.lock) == 0);
		assert(pthread_mutex_unlock(&cw.lock) == 0);

		assert(pthread_mutex_lock(&count_lock) == 0);
		++count;
		assert(pthread_mutex_unlock(&count_lock) == 0);
	}

	/* exit the loop only if all threads fired all timeouts */
	assert(pthread_mutex_lock(&count_lock) == 0);
	if (count >= NUM_THREADS * 100)
		event_base_loopexit(base, NULL);
	assert(pthread_mutex_unlock(&count_lock) == 0);

	assert(pthread_cond_destroy(&cw.cond) == 0);
	assert(pthread_mutex_destroy(&cw.lock) == 0);

	return (NULL);
}
Exemple #2
0
int 
main(int argc, char **argv)
{
	struct event timeout;
	struct timeval tv;
	struct event_base *base;
	int flags;

	event_is_persistent = 1;
	flags = EV_PERSIST;

	base = event_base_new();
	
	event_assign(&timeout, base, -1, flags, timeout_cb, (void *)&timeout);
	
	evutil_timerclear(&tv);
	
	tv.tv_sec = 2;
	event_add(&timeout, &tv);
	evutil_gettimeofday(&lasttime, NULL);
	event_base_dispatch(base);

	return (0);
}
Exemple #3
0
int
master_ready(Conn *conn, char *data, int datalen)
{
    WThread *wt = g_runtime->wthread;
    //int ret;
    int lastlogver, lastlogline;
    //int lastret;

    commitlog_read(wt->clog, &lastlogver, &lastlogline);
    DINFO("=======lastlogver: %d, lastlogline: %d\n", lastlogver, lastlogline);
    //DNOTE("=======lastlogver: %d, lastlogline: %d\n", lastlogver, lastlogline);
    //写本地commitlog
    //commitlog_write(wt->clog, g_runtime->synclog->version, g_runtime->synclog->index_pos, 
        //data, datalen);

    int newlogver, newlogline;

    //commitlog_read(wt->clog, &newlogver, &newlogline);
    newlogver = g_runtime->synclog->version;
    newlogline = g_runtime->synclog->index_pos;

    //DNOTE("=======newlogver: %d, newlogline: %d\n", newlogver, newlogline);
    DINFO("=======newlogver: %d, newlogline: %d\n", newlogver, newlogline);
    //DNOTE("in synclog version: %d, logline: %d\n", g_runtime->synclog->version,   g_runtime->synclog->index_pos);
    DINFO("in synclog version: %d, logline: %d\n", g_runtime->synclog->version,   g_runtime->synclog->index_pos);
    /* 
    int dlen = wt->clog->len + sizeof(char);
    char *buffer = conn_write_buffer(conn, dlen); 
    
    ret = pack(buffer, 0, "$4cC", dlen, CMD_WRITE, wt->clog->len, wt->clog->data); 
    */
    BackupInfo *binfo = wt->backup_info;
    BackupItem *bitem  = binfo->item;
    
    //保存客户端命令
    pack(binfo->cltcmd, 0, "ii", newlogver, newlogline);
    memcpy(binfo->cltcmd+sizeof(int)*2, data, datalen);
    binfo->cmdlen = datalen + sizeof(int)*2;

    //binfo->done = 0;
    binfo->succ = 0;
    
    DINFO("state: %d, succ: %d\n", wt->state, binfo->succ);
    //系统不可用
    if (wt->state == STATE_NOCONN) {
        conn_send_buffer_reply(conn, MEMLINK_ERR_NOWRITE, NULL, 0); 
        return 0;
    }
    
    //while (binfo->timer_send == TRUE) {
    //}

    binfo->ctlconn = conn;
    DINFO("need send comand to all backup\n");
    while (bitem) {
        if(bitem->state == STATE_ALLREADY) {
            Conn *conn = (Conn *)bitem->mbconn;
            //DNOTE("-------------------wlen: %d, wpos: %d\n", conn->wlen, conn->wpos);
            DINFO("-------------------wlen: %d, wpos: %d\n", conn->wlen, conn->wpos);
            char *buffer = conn_write_buffer(conn, 2048);
            int  count;
            int  ret;
            
            DINFO("clog->len: %d\n", wt->clog->len);
            //count = pack(buffer, 0, "$4ciiiC:4", CMD_WRITE, lastlogver, lastlogline, wt->clog->state, wt->clog->len , wt->clog->data);
            count = pack(buffer, 0, "$4ciiiC:4", CMD_WRITE, lastlogver, lastlogline, wt->clog->state, binfo->cmdlen, binfo->cltcmd);
            int lastver, lastline, lastret, logver, logline;
            
            unpack(buffer+sizeof(int)+sizeof(char), 0, "iii", &lastver, &lastline, &lastret);
            DINFO("lastver: %d, lastline: %d, lastret: %d\n", lastver, lastline,
                lastret);

            unpack(buffer+sizeof(int)*5+sizeof(char), 0, "ii", &logver, &logline);
            DINFO("unpack logver: %d, logline: %d\n", logver, logline);
            conn->wlen = count;
            
            DINFO("change event to write\n");
            //DNOTE("change event to write\n");
            ret = change_event((Conn *)bitem->mbconn, EV_WRITE | EV_PERSIST, 0, 0);
            /*
            if (ret < 0) {
                DERROR("change_event error: %d, %s:%d\n", ret, bitem->ip, bitem->write_port);
                Conn *conn = (Conn *)bitem->mbconn;
                conn->destroy((Conn *)bitem->mbconn);
                binfo->succ_conns--;
            }
            */
        }
        bitem = bitem->next;
    }
    
    DINFO("=======add timer check event\n");
    struct timeval tm;
    evtimer_set(&binfo->timer_check_evt, mb_data_timeout, conn);
    evutil_timerclear(&tm);
    tm.tv_sec = 1;
    event_base_set(wt->base, &binfo->timer_check_evt);
    event_add(&binfo->timer_check_evt, &tm);

    return 0;
}
Exemple #4
0
/* Thread: httpd */
void
httpd_stream_file(struct evhttp_request *req, int id)
{
  struct media_file_info *mfi;
  struct stream_ctx *st;
  void (*stream_cb)(int fd, short event, void *arg);
  struct stat sb;
  struct timeval tv;
  struct evhttp_connection *evcon;
  struct evkeyvalq *input_headers;
  struct evkeyvalq *output_headers;
  const char *param;
  const char *param_end;
  const char *ua;
  const char *client_codecs;
  char buf[64];
  int64_t offset;
  int64_t end_offset;
  off_t pos;
  int transcode;
  int ret;

  offset = 0;
  end_offset = 0;

  input_headers = evhttp_request_get_input_headers(req);

  param = evhttp_find_header(input_headers, "Range");
  if (param)
    {
      DPRINTF(E_DBG, L_HTTPD, "Found Range header: %s\n", param);

      /* Start offset */
      ret = safe_atoi64(param + strlen("bytes="), &offset);
      if (ret < 0)
	{
	  DPRINTF(E_LOG, L_HTTPD, "Invalid start offset, will stream whole file (%s)\n", param);
	  offset = 0;
	}
      /* End offset, if any */
      else
	{
	  param_end = strchr(param, '-');
	  if (param_end && (strlen(param_end) > 1))
	    {
	      ret = safe_atoi64(param_end + 1, &end_offset);
	      if (ret < 0)
		{
		  DPRINTF(E_LOG, L_HTTPD, "Invalid end offset, will stream to end of file (%s)\n", param);
		  end_offset = 0;
		}

	      if (end_offset < offset)
		{
		  DPRINTF(E_LOG, L_HTTPD, "End offset < start offset, will stream to end of file (%" PRIi64 " < %" PRIi64 ")\n", end_offset, offset);
		  end_offset = 0;
		}
	    }
	}
    }

  mfi = db_file_fetch_byid(id);
  if (!mfi)
    {
      DPRINTF(E_LOG, L_HTTPD, "Item %d not found\n", id);

      evhttp_send_error(req, HTTP_NOTFOUND, "Not Found");
      return;
    }

  if (mfi->data_kind != DATA_KIND_FILE)
    {
      evhttp_send_error(req, 500, "Cannot stream radio station");

      goto out_free_mfi;
    }

  st = (struct stream_ctx *)malloc(sizeof(struct stream_ctx));
  if (!st)
    {
      DPRINTF(E_LOG, L_HTTPD, "Out of memory for struct stream_ctx\n");

      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");

      goto out_free_mfi;
    }
  memset(st, 0, sizeof(struct stream_ctx));
  st->fd = -1;

  ua = evhttp_find_header(input_headers, "User-Agent");
  client_codecs = evhttp_find_header(input_headers, "Accept-Codecs");

  transcode = transcode_needed(ua, client_codecs, mfi->codectype);

  output_headers = evhttp_request_get_output_headers(req);

  if (transcode)
    {
      DPRINTF(E_INFO, L_HTTPD, "Preparing to transcode %s\n", mfi->path);

      stream_cb = stream_chunk_xcode_cb;

      st->xcode = transcode_setup(mfi, XCODE_PCM16_HEADER, &st->size);
      if (!st->xcode)
	{
	  DPRINTF(E_WARN, L_HTTPD, "Transcoding setup failed, aborting streaming\n");

	  evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");

	  goto out_free_st;
	}

      if (!evhttp_find_header(output_headers, "Content-Type"))
	evhttp_add_header(output_headers, "Content-Type", "audio/wav");
    }
  else
    {
      /* Stream the raw file */
      DPRINTF(E_INFO, L_HTTPD, "Preparing to stream %s\n", mfi->path);

      st->buf = (uint8_t *)malloc(STREAM_CHUNK_SIZE);
      if (!st->buf)
	{
	  DPRINTF(E_LOG, L_HTTPD, "Out of memory for raw streaming buffer\n");

	  evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");

	  goto out_free_st;
	}

      stream_cb = stream_chunk_raw_cb;

      st->fd = open(mfi->path, O_RDONLY);
      if (st->fd < 0)
	{
	  DPRINTF(E_LOG, L_HTTPD, "Could not open %s: %s\n", mfi->path, strerror(errno));

	  evhttp_send_error(req, HTTP_NOTFOUND, "Not Found");

	  goto out_cleanup;
	}

      ret = stat(mfi->path, &sb);
      if (ret < 0)
	{
	  DPRINTF(E_LOG, L_HTTPD, "Could not stat() %s: %s\n", mfi->path, strerror(errno));

	  evhttp_send_error(req, HTTP_NOTFOUND, "Not Found");

	  goto out_cleanup;
	}
      st->size = sb.st_size;

      pos = lseek(st->fd, offset, SEEK_SET);
      if (pos == (off_t) -1)
	{
	  DPRINTF(E_LOG, L_HTTPD, "Could not seek into %s: %s\n", mfi->path, strerror(errno));

	  evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request");

	  goto out_cleanup;
	}
      st->offset = offset;
      st->end_offset = end_offset;

      /* Content-Type for video files is different than for audio files
       * and overrides whatever may have been set previously, like
       * application/x-dmap-tagged when we're speaking DAAP.
       */
      if (mfi->has_video)
	{
	  /* Front Row and others expect video/<type> */
	  ret = snprintf(buf, sizeof(buf), "video/%s", mfi->type);
	  if ((ret < 0) || (ret >= sizeof(buf)))
	    DPRINTF(E_LOG, L_HTTPD, "Content-Type too large for buffer, dropping\n");
	  else
	    {
	      evhttp_remove_header(output_headers, "Content-Type");
	      evhttp_add_header(output_headers, "Content-Type", buf);
	    }
	}
      /* If no Content-Type has been set and we're streaming audio, add a proper
       * Content-Type for the file we're streaming. Remember DAAP streams audio
       * with application/x-dmap-tagged as the Content-Type (ugh!).
       */
      else if (!evhttp_find_header(output_headers, "Content-Type") && mfi->type)
	{
	  ret = snprintf(buf, sizeof(buf), "audio/%s", mfi->type);
	  if ((ret < 0) || (ret >= sizeof(buf)))
	    DPRINTF(E_LOG, L_HTTPD, "Content-Type too large for buffer, dropping\n");
	  else
	    evhttp_add_header(output_headers, "Content-Type", buf);
	}
    }

  st->evbuf = evbuffer_new();
  if (!st->evbuf)
    {
      DPRINTF(E_LOG, L_HTTPD, "Could not allocate an evbuffer for streaming\n");

      evhttp_clear_headers(output_headers);
      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");

      goto out_cleanup;
    }

  ret = evbuffer_expand(st->evbuf, STREAM_CHUNK_SIZE);
  if (ret != 0)
    {
      DPRINTF(E_LOG, L_HTTPD, "Could not expand evbuffer for streaming\n");

      evhttp_clear_headers(output_headers);
      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");

      goto out_cleanup;
    }

  st->ev = event_new(evbase_httpd, -1, EV_TIMEOUT, stream_cb, st);
  evutil_timerclear(&tv);
  if (!st->ev || (event_add(st->ev, &tv) < 0))
    {
      DPRINTF(E_LOG, L_HTTPD, "Could not add one-shot event for streaming\n");

      evhttp_clear_headers(output_headers);
      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");

      goto out_cleanup;
    }

  st->id = mfi->id;
  st->start_offset = offset;
  st->stream_size = st->size;
  st->req = req;

  if ((offset == 0) && (end_offset == 0))
    {
      /* If we are not decoding, send the Content-Length. We don't do
       * that if we are decoding because we can only guesstimate the
       * size in this case and the error margin is unknown and variable.
       */
      if (!transcode)
	{
	  ret = snprintf(buf, sizeof(buf), "%" PRIi64, (int64_t)st->size);
	  if ((ret < 0) || (ret >= sizeof(buf)))
	    DPRINTF(E_LOG, L_HTTPD, "Content-Length too large for buffer, dropping\n");
	  else
	    evhttp_add_header(output_headers, "Content-Length", buf);
	}

      evhttp_send_reply_start(req, HTTP_OK, "OK");
    }
  else
    {
      if (offset > 0)
	st->stream_size -= offset;
      if (end_offset > 0)
	st->stream_size -= (st->size - end_offset);

      DPRINTF(E_DBG, L_HTTPD, "Stream request with range %" PRIi64 "-%" PRIi64 "\n", offset, end_offset);

      ret = snprintf(buf, sizeof(buf), "bytes %" PRIi64 "-%" PRIi64 "/%" PRIi64,
		     offset, (end_offset) ? end_offset : (int64_t)st->size, (int64_t)st->size);
      if ((ret < 0) || (ret >= sizeof(buf)))
	DPRINTF(E_LOG, L_HTTPD, "Content-Range too large for buffer, dropping\n");
      else
	evhttp_add_header(output_headers, "Content-Range", buf);

      ret = snprintf(buf, sizeof(buf), "%" PRIi64, ((end_offset) ? end_offset + 1 : (int64_t)st->size) - offset);
      if ((ret < 0) || (ret >= sizeof(buf)))
	DPRINTF(E_LOG, L_HTTPD, "Content-Length too large for buffer, dropping\n");
      else
	evhttp_add_header(output_headers, "Content-Length", buf);

      evhttp_send_reply_start(req, 206, "Partial Content");
    }

#ifdef HAVE_POSIX_FADVISE
  if (!transcode)
    {
      /* Hint the OS */
      posix_fadvise(st->fd, st->start_offset, st->stream_size, POSIX_FADV_WILLNEED);
      posix_fadvise(st->fd, st->start_offset, st->stream_size, POSIX_FADV_SEQUENTIAL);
      posix_fadvise(st->fd, st->start_offset, st->stream_size, POSIX_FADV_NOREUSE);
    }
#endif

  evcon = evhttp_request_get_connection(req);

  evhttp_connection_set_closecb(evcon, stream_fail_cb, st);

  DPRINTF(E_INFO, L_HTTPD, "Kicking off streaming for %s\n", mfi->path);

  free_mfi(mfi, 0);

  return;

 out_cleanup:
  if (st->evbuf)
    evbuffer_free(st->evbuf);
  if (st->xcode)
    transcode_cleanup(st->xcode);
  if (st->buf)
    free(st->buf);
  if (st->fd > 0)
    close(st->fd);
 out_free_st:
  free(st);
 out_free_mfi:
  free_mfi(mfi, 0);
}
Exemple #5
0
static void
stream_chunk_xcode_cb(int fd, short event, void *arg)
{
  struct stream_ctx *st;
  struct timeval tv;
  int xcoded;
  int ret;
  int dummy;

  st = (struct stream_ctx *)arg;

  xcoded = transcode(st->evbuf, STREAM_CHUNK_SIZE, st->xcode, &dummy);
  if (xcoded <= 0)
    {
      if (xcoded == 0)
	DPRINTF(E_LOG, L_HTTPD, "Done streaming transcoded file id %d\n", st->id);
      else
	DPRINTF(E_LOG, L_HTTPD, "Transcoding error, file id %d\n", st->id);

      stream_end(st, 0);
      return;
    }

  DPRINTF(E_DBG, L_HTTPD, "Got %d bytes from transcode; streaming file id %d\n", xcoded, st->id);

  /* Consume transcoded data until we meet start_offset */
  if (st->start_offset > st->offset)
    {
      ret = st->start_offset - st->offset;

      if (ret < xcoded)
	{
	  evbuffer_drain(st->evbuf, ret);
	  st->offset += ret;

	  ret = xcoded - ret;
	}
      else
	{
	  evbuffer_drain(st->evbuf, xcoded);
	  st->offset += xcoded;

	  goto consume;
	}
    }
  else
    ret = xcoded;

#ifdef HAVE_LIBEVENT2_OLD
  evhttp_send_reply_chunk(st->req, st->evbuf);

  struct evhttp_connection *evcon = evhttp_request_get_connection(st->req);
  struct bufferevent *bufev = evhttp_connection_get_bufferevent(evcon);

  g_st = st; // Can't pass st to callback so use global - limits libevent 2.0 to a single stream
  bufev->writecb = stream_chunk_resched_cb_wrapper;
#else
  evhttp_send_reply_chunk_with_cb(st->req, st->evbuf, stream_chunk_resched_cb, st);
#endif

  st->offset += ret;

  stream_up_playcount(st);

  return;

 consume: /* reschedule immediately - consume up to start_offset */
  evutil_timerclear(&tv);
  ret = event_add(st->ev, &tv);
  if (ret < 0)
    {
      DPRINTF(E_LOG, L_HTTPD, "Could not re-add one-shot event for streaming (xcode)\n");

      stream_end(st, 0);
      return;
    }
}
Exemple #6
0
int
bufferevent_init_common(struct bufferevent_private *bufev_private,
    struct event_base *base,
    const struct bufferevent_ops *ops,
    enum bufferevent_options options)
{
	struct bufferevent *bufev = &bufev_private->bev;

	if (!bufev->input) {
		if ((bufev->input = evbuffer_new()) == NULL)
			return -1;
	}

	if (!bufev->output) {
		if ((bufev->output = evbuffer_new()) == NULL) {
			evbuffer_free(bufev->input);
			return -1;
		}
	}

	bufev_private->refcnt = 1;
	bufev->ev_base = base;

	/* Disable timeouts. */
	evutil_timerclear(&bufev->timeout_read);
	evutil_timerclear(&bufev->timeout_write);

	bufev->be_ops = ops;

	_bufferevent_ratelim_init(bufev_private);

	/*
	 * Set to EV_WRITE so that using bufferevent_write is going to
	 * trigger a callback.  Reading needs to be explicitly enabled
	 * because otherwise no data will be available.
	 */
	bufev->enabled = EV_WRITE;

#ifndef _EVENT_DISABLE_THREAD_SUPPORT
	if (options & BEV_OPT_THREADSAFE) {
		if (bufferevent_enable_locking(bufev, NULL) < 0) {
			/* cleanup */
			evbuffer_free(bufev->input);
			evbuffer_free(bufev->output);
			bufev->input = NULL;
			bufev->output = NULL;
			return -1;
		}
	}
#endif
	if ((options & (BEV_OPT_DEFER_CALLBACKS|BEV_OPT_UNLOCK_CALLBACKS))
	    == BEV_OPT_UNLOCK_CALLBACKS) {
		event_warnx("UNLOCK_CALLBACKS requires DEFER_CALLBACKS");
		return -1;
	}
	if (options & BEV_OPT_DEFER_CALLBACKS) {
		if (options & BEV_OPT_UNLOCK_CALLBACKS)
			event_deferred_cb_init(&bufev_private->deferred,
			    bufferevent_run_deferred_callbacks_unlocked,
			    bufev_private);
		else
			event_deferred_cb_init(&bufev_private->deferred,
			    bufferevent_run_deferred_callbacks_locked,
			    bufev_private);
	}

	bufev_private->options = options;

	evbuffer_set_parent(bufev->input, bufev);
	evbuffer_set_parent(bufev->output, bufev);

	return 0;
}
static void  
timeout_cb(int fd, short event, void *arg)  
{  
	struct timeval tv;  
	struct event *timeout = arg;
  	printf("calling back\n");

	char command[1024];
    char shellbuf[1024];
	
	char* str_pipeerr = "something error...\n";
	char* str_nouser = "******";
	
	if(renew_req()==1)
	{
		struct RuntimeSTAT* maxusrStat;
		//getSTAT(maxusr,maxusrStat);
		FILE* fd_shell;
		sprintf(command,"ls %s/%s",PATH_SHM,maxusr);
		fd_shell = popen(command,"r");
    	if(fd_shell <= 0)
    	{
       	 	printf(str_pipeerr);
    	}
    	fgets(shellbuf,1023,fd_shell);

    	int len = strlen(shellbuf);
    	if(len <= 0)
    	{
       		printf(str_nouser);
    	}
    	shellbuf[len-1]=0;
    	char* fname = strrchr(shellbuf,'/');
    	fname++;

    	maxusrStat = (struct RuntimeSTAT*)SHM_get(fname,sizeof(struct RuntimeSTAT));
		if(maxusrStat == NULL)
    	{
        	printf(str_pipeerr);
    	}
		struct RuntimeSTAT* minusrStat;
		//getSTAT(minusr,minusrStat);
		sprintf(command,"ls %s/%s",PATH_SHM,minusr);
		fd_shell = popen(command,"r");
    	if(fd_shell <= 0)
    	{
       	 	printf(str_pipeerr);
    	}
    	fgets(shellbuf,1023,fd_shell);

    	len = strlen(shellbuf);
    	if(len <= 0)
    	{
        	printf(str_nouser);
    	}
    	shellbuf[len-1]=0;
    	fname = strrchr(shellbuf,'/');
    	fname++;

    	minusrStat = (struct RuntimeSTAT*)SHM_get(fname,sizeof(struct RuntimeSTAT));
		if(minusrStat == NULL)
    	{
        	printf(str_pipeerr);
    	}
		int cut_off = maxusrStat->cacheLimit/10;
		printf("old maxusr ssd %d,cut off = %d\n",maxusrStat->cacheLimit,cut_off);
		maxusrStat->cacheLimit = maxusrStat->cacheLimit - cut_off;
		printf("new maxusr ssd %d\n",maxusrStat->cacheLimit);
		printf("old minusr ssd %d,cut off = %d\n",minusrStat->cacheLimit,cut_off);
		minusrStat->cacheLimit = minusrStat->cacheLimit + cut_off;
		printf("new minusr ssd %d\n",minusrStat->cacheLimit);
	}
	
	printf("End of adjustment.\n");
	evutil_timerclear(&tv);  
	tv.tv_sec = TIME_INTERVAL;  
	//重新注册event  
	event_add(timeout, &tv);  
} 
int main (int argc, char *argv[])
{
    gchar *in_dir;
    GList *tmp;
    struct evhttp_uri *uri;
    struct timeval tv;

    log_level = LOG_debug;

    event_set_mem_functions (g_malloc, g_realloc, g_free);
    // init SSL libraries
    CRYPTO_set_mem_functions (g_malloc0, g_realloc, g_free);
    ENGINE_load_builtin_engines ();
    ENGINE_register_all_complete ();
    ERR_load_crypto_strings ();
    OpenSSL_add_all_algorithms ();

    SSL_load_error_strings ();
    SSL_library_init ();
    if (!RAND_poll ()) {
        fprintf(stderr, "RAND_poll() failed.\n");
        return 1;
    }
    g_random_set_seed (time (NULL));

    in_dir = g_dir_make_tmp (NULL, NULL);
    g_assert (in_dir);

    app = g_new0 (Application, 1);
    app->files_count = 10;
    app->evbase = event_base_new ();
	app->dns_base = evdns_base_new (app->evbase, 1);

        app->conf = conf_create ();
        conf_add_boolean (app->conf, "log.use_syslog", TRUE);
        
        conf_add_uint (app->conf, "auth.ttl", 85800);
        
        conf_add_int (app->conf, "pool.writers", 2);
        conf_add_int (app->conf, "pool.readers", 2);
        conf_add_int (app->conf, "pool.operations", 4);
        conf_add_uint (app->conf, "pool.max_requests_per_pool", 100);

        conf_add_int (app->conf, "connection.timeout", 20);
        conf_add_int (app->conf, "connection.retries", -1);

        conf_add_uint (app->conf, "filesystem.dir_cache_max_time", 5);
        conf_add_boolean (app->conf, "filesystem.cache_enabled", TRUE);
        conf_add_string (app->conf, "filesystem.cache_dir", "/tmp/hydrafs");
        conf_add_string (app->conf, "filesystem.cache_dir_max_size", "1Gb");

        conf_add_boolean (app->conf, "statistics.enabled", TRUE);
        conf_add_int (app->conf, "statistics.port", 8011);

    conf_add_string (app->conf, "auth.user", "test:tester");
    conf_add_string (app->conf, "auth.key", "testing");
    uri = evhttp_uri_parse ("https://10.0.0.104:8080/auth/v1.0");
    
    app->ssl_ctx = SSL_CTX_new (TLSv1_client_method ());
    
    app->stats = hfs_stats_srv_create (app);
    app->auth_client = auth_client_create (app, uri);

    app->http = http_client_create (app);

    // start server
     start_srv (app->evbase, in_dir);

    app->timeout = evtimer_new (app->evbase, on_output_timer, NULL);

    evutil_timerclear(&tv);
    tv.tv_sec = 0;
    tv.tv_usec = 500;
    event_add (app->timeout, &tv);

    event_base_dispatch (app->evbase);

    evhttp_uri_free (uri);
    event_del (app->timeout);
    event_free (app->timeout);

    evhttp_free (app->http_srv);
    auth_client_destroy (app->auth_client);

    evdns_base_free (app->dns_base, 0);
    event_base_free (app->evbase);

    conf_destroy (app->conf);
    g_free (app);

    return 0;
}
Exemple #9
0
CNetTimer::CNetTimer(mw_net_timer_sink* sink)
: m_sink(sink)
{
	evutil_timerclear(&m_tv);
}
Exemple #10
0
void client_init(void)
{
	struct event timeout;
	struct timeval tv;
	int i, socket_fd, retry = 0;
	char c = MIN_CHAR;
	
	/* Initialize libevent. */
	event_init();
	
	/* allocate space for the test string */
	if ((test_vars.string_test = malloc(sizeof(char) * test_vars.string_length + 1)) == NULL)
		err(1, "malloc");
	
	/* create test string */
	for (i = 0; i < test_vars.string_length; i++) {
		if (c > MAX_CHAR)
			c = MIN_CHAR;
		else
			c++;
		
		test_vars.string_test[i] = c;
	}
	
	/* set currently open connections to 0 */
	test_vars.open_conns = 0;
	
	/* create as many sockets as needed */
	for (i = 0; i < test_vars.conns; i++) {
		socket_fd = get_socket(i);
		
		if (socket_fd == ERROR) {
			if (retry < MAX_CONNECT_ERRORS) {
				retry++;
				i--;
				usleep(1000);
			}
			else
				err(1, "get_socket");
		}
		else {
			/* setup write events */
			event_set(&srv_stats[i].ev_write, srv_stats[i].fd_server,
					  EV_WRITE|EV_PERSIST, on_write, &srv_stats[i]);
			event_add(&srv_stats[i].ev_write, NULL);
			
			/* setup read events */
			event_set(&srv_stats[i].ev_read, srv_stats[i].fd_server,
					  EV_READ|EV_PERSIST, on_read, &srv_stats[i]);
			event_add(&srv_stats[i].ev_read, NULL);
			
			test_vars.open_conns++;
			retry = 0;
		}

		usleep(1);
	}
	
	/* create a timer event for writing stats to disk */
	evtimer_set(&timeout, event_timer, &timeout);
	evutil_timerclear(&tv);
	tv.tv_usec = 0;
	event_add(&timeout, &tv);
	
	/* Start the libevent event loop. */
	event_dispatch();
	
	write_stats();
}
Exemple #11
0
/*---------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
	struct xio_session	*session;
	char			url[256];
	struct session_data	session_data;
	int			i = 0;
	struct event		timeout;
	struct event		xio_event;
	struct timeval		tv;
	struct xio_poll_params  poll_params;
	struct xio_session_params params;

	if (argc < 3) {
		printf("Usage: %s <host> <port> <transport:optional>\n",
		       argv[0]);
		exit(1);
	}
	memset(&session_data, 0, sizeof(session_data));
	memset(&params, 0, sizeof(params));

	/* initialize library */
	xio_init();

	/* create thread context for the client */
	session_data.ctx = xio_context_create(NULL, 0, -1);

	/* get poll parameters for libevent */
	xio_context_get_poll_params(session_data.ctx, &poll_params);

	/* create url to connect to */
	if (argc > 3)
		sprintf(url, "%s://%s:%s", argv[3], argv[1], argv[2]);
	else
		sprintf(url, "rdma://%s:%s", argv[1], argv[2]);
	params.type		= XIO_SESSION_CLIENT;
	params.ses_ops		= &ses_ops;
	params.user_context	= &session_data;
	params.uri		= url;

	session = xio_session_create(&params);

	/* connect the session  */
	session_data.conn = xio_connect(session, session_data.ctx,
					0, NULL, &session_data);

	/* create "hello world" message */
	for (i = 0; i < QUEUE_DEPTH; i++) {
		memset(&session_data.req[i], 0, sizeof(session_data.req[i]));
		/* header */
		session_data.req[i].out.header.iov_base =
			strdup("hello world header request");
		session_data.req[i].out.header.iov_len =
			strlen(session_data.req[i].out.header.iov_base) + 1;
		/* iovec[0]*/
		session_data.req[i].out.sgl_type	   = XIO_SGL_TYPE_IOV;
		session_data.req[i].out.data_iov.max_nents = XIO_IOVLEN;

		session_data.req[i].out.data_iov.sglist[0].iov_base =
			strdup("hello world iovec request");
		session_data.req[i].out.data_iov.sglist[0].iov_len =
			strlen(session_data.req[i].out.data_iov.sglist[0].iov_base) + 1;
		session_data.req[i].out.data_iov.nents = 1;
	}
	/* send first message */
	for (i = 0; i < QUEUE_DEPTH; i++) {
		xio_send_request(session_data.conn, &session_data.req[i]);
		session_data.nsent++;
	}

	/* Initialize the event library */
	session_data.evbase = event_base_new();

	/* Initialize one timer event */
	event_assign(&timeout, session_data.evbase, -1,
		     EV_PERSIST, timeout_cb, (void *)&timeout);

	evutil_timerclear(&tv);
	tv.tv_sec = 2;
	event_add(&timeout, &tv);

	event_assign(&xio_event, session_data.evbase, poll_params.fd,
		     EV_READ|EV_PERSIST, xio_event_handler,
		     (void *)&poll_params);

	/* Add it to the active events, without a timeout */
	event_add(&xio_event, NULL);

	event_base_dispatch(session_data.evbase);

	fprintf(stdout, "exit signaled\n");

	event_base_free(session_data.evbase);

	/* free the message */
	for (i = 0; i < QUEUE_DEPTH; i++) {
		free(session_data.req[i].out.header.iov_base);
		free(session_data.req[i].out.data_iov.sglist[0].iov_base);
	}

	/* free the context */
	xio_context_destroy(session_data.ctx);

	xio_shutdown();

	printf("good bye\n");
	return 0;
}
Exemple #12
0
int NFCNet::InitClientNet()
{
    std::string strIP = mstrIP;
    int nPort = mnPort;

    struct sockaddr_in addr;
    struct bufferevent *bev = NULL;

#if NF_PLATFORM == NF_PLATFORM_WIN
    WSADATA wsa_data;
    WSAStartup(0x0201, &wsa_data);
#endif

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(nPort);

    if (inet_pton(AF_INET, strIP.c_str(), &addr.sin_addr) <= 0)
    {
        printf("inet_pton");
        return -1;
    }

    base = event_base_new();
    if (base == NULL)
    {
        printf("event_base_new ");
        return -1;
    }

    bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
    if (bev == NULL)
    {
        printf("bufferevent_socket_new ");
        return -1;
    }

    int bRet = bufferevent_socket_connect(bev, (struct sockaddr *)&addr, sizeof(addr));
    if (0 != bRet)
    {
        //int nError = GetLastError();
        printf("bufferevent_socket_connect error");
        return -1;
    }

    int sockfd = bufferevent_getfd(bev);
    NetObject* pObject = new NetObject(this, 0, addr, bev);
    if (!AddNetObject(0, pObject))
    {
        assert(0);
        return -1;
    }

    mbServer = false;

    bufferevent_setcb(bev, conn_readcb, conn_writecb, conn_eventcb, (void*)pObject);
    bufferevent_enable(bev, EV_READ|EV_WRITE);

    ev = evtimer_new(base, time_cb, (void*)pObject);
    evutil_timerclear(&tv);
    tv.tv_sec = 10; //间隔
    tv.tv_usec = 0;

    evtimer_add(ev, &tv);

    event_set_log_callback(&NFCNet::log_cb);
    //event_base_loop(base, EVLOOP_ONCE|EVLOOP_NONBLOCK);

    return sockfd;
}
Exemple #13
0
int gp_send_idle() {
	static int gp_dst=0;
	int activ=0;
	
	do {
		gp_dst++;
		if( gp_dst > gp_cfg.max_dev_n ) { gp_dst=0; return 0; }
//	fprintf(stderr, "Check gp_send_idle for %d (%d)\n",gp_dst,devices[gp_dst].timeout_count );
		if(devices[gp_dst].timeout_count > gp_cfg.max_timeout_count) {
			if( devices[gp_dst].activ > 0)
//			if ( gp_dst == 5  ) 
				{
				fprintf(stderr, "Disabled dev %d (%d)\n", gp_dst, devices[gp_dst].timeout_count);
				syslog(LOG_ERR, "Disabled dev %d (%d)\n", gp_dst, devices[gp_dst].timeout_count);
				}
			devices[gp_dst].activ=activ=0;
			continue;
		}
		activ=1;
	} while( activ == 0 );
//	if ( gp_dst == 5  ) 
//	fprintf(stderr, "Run gp_send_idle for %d (%d)\n",gp_dst,devices[gp_dst].timeout_count );
	
/*	cmd_send_t z = {
		.cmd_n = 0x06,
		.set_timeout = 50,
		.polling = 1,
		.data_len = 0
	};*/
	
//return 0;
//	return ad_get_cid(AD_Q_SHORT, gp_dst, &cb_get_poll_result);
	cmd_send_t z = {
		.queue = AD_Q_SHORT,
		.ev_handler = &cb_get_poll_result,
		.target_n = AD_TARGET_GET_CID,
		.cmd_n = 0x04,
		.set_timeout = 150,
		.polling = 1,
		.data_len = 5,
		.cmd_buff = { 0x00, 0xD0, 6, 0x00, 0x0C }
	};
	
	z.dst=gp_dst;
	return gp_send(&z);
}


#pragma pack(push,1)
#pragma pack(pop)

//void gp_receiv(uint8_t* in, int nread) {
// short event=4;
int mydev=-1;

int err=0;
void gp_receiv(int fd, short event, void *arg) {
	int nread=0;
//	int last=0;
	struct timeval tv;
 	
 	gettimeofday(&tv,NULL);
 	uint32_t current_time=tv2ms(tv);
 	uint32_t expect_time=tv2ms(gp_cfg.timeout);
 	uint32_t delta = current_time -  send_mess.sent_time;
 	uint32_t delta2 = current_time -  receiv_mess.last_read;
/*	if (send_mess.dev == 1 ) 
	fprintf(stderr, "Got  event (%d): 0x%X, %u.%06u (%u ms), sent time %u ms, current timeout: %u ms, delta: %u ms (%u ms)\n",
		send_mess.dev,
		event,
		tv.tv_sec,tv.tv_usec,
		current_time,
		send_mess.sent_time,
		expect_time,
		delta, delta2
		);*/
//	char buf[PORT_READ_BUF_LENGTH];
	

//	memset(buf, 0, sizeof(buf));
				
//	if ( event_del(&send_mess.ev_timeout) < 0) syslog(LOG_ERR, "event_del (send_mess.ev_timeout): %m");
//	event_set(&evsocket, sockfd, EV_READ|EV_PERSIST, socket_read, (void*)&evsocket);
//	if ( event_del(&gp_cfg.evport) < 0) syslog(LOG_ERR, "event_del (send_mess.ev_timeout): %m");

/*	if( (event & EV_WRITE) != 0 ) {
//		gp_put_cmd();
		return;
	}*/
/*	evutil_timerclear(&gp_cfg.timeout);
	gp_cfg.timeout.tv_usec = gp_cfg.gp_timeout * 1000;
 	if ( event_add(&gp_cfg.evport, &gp_cfg.timeout) < 0) syslog(LOG_ERR, "event_add.send_mess.ev_timeout setup: %m");*/
	
	if( (event & EV_READ) == 0 ) {
		gp_reconnect(0);
// HACK - we check real timeout, not timer
//		if( current_time >= expect_time ) {	 	
//				} else if(gp_cfg.timeout.tv_sec > 0) {
/*		if ( send_mess.dev == 5 ) 
		fprintf(stderr, "dev=%d,  delta by sent = %d, delta by read = %d, count = %d\n",
			send_mess.dev,delta, delta2, devices[send_mess.dev].timeout_count );*/
	 	if( delta >=  gp_cfg.gp_timeout) {
			if( send_mess.is_expected > 0 ) {
				send_mess.is_expected=0;
				devices[send_mess.dev].timeout_count++;
//				if ( send_mess.dev == 1 ) fprintf(stderr, "inc %d dev=%d\n", devices[send_mess.dev].timeout_count, send_mess.dev);
				if( gp_cfg.polling == 0 ) {
//				if( send_mess.dev == 1 ) {
//					send_mess.target=0;
					uint32_t delta3=current_time - devices[send_mess.dev].last_read;
					fprintf(stderr, "Timeout (%d) for read for %d (cmd=%d, delta=%u)\n", devices[send_mess.dev].timeout_count,
						send_mess.dev, send_mess.target, delta3);
					syslog(LOG_ERR, "Timeout (%d) for read for %d (cmd=%d, delta=%u)",   devices[send_mess.dev].timeout_count,
						send_mess.dev, send_mess.target, delta3);
				}
			}
		}	 	
//		if( current_time >= expect_time + gp_cfg.gp_timeout) {
//	 	if( current_time - receiv_mess.last_read >  gp_cfg.gp_timeout) {
	 	if( delta >=  gp_cfg.gp_timeout) {
// /*	 		if ( send_mess.dev == 5 ) 
// 				fprintf(stderr, "Runed gp_put_cmd!\n");*/
			if( gp_put_cmd() > 0 ||  gp_send_idle() > 0) return;
	 	}
		evutil_timerclear(&gp_cfg.timeout);
		gp_cfg.timeout.tv_usec = gp_cfg.gp_timeout * 1000;
		if ( event_add(&gp_cfg.evport, &gp_cfg.timeout) < 0) syslog(LOG_ERR, "event_add.send_mess.ev_timeout setup: %m");
		return;
	}

// HACK Read (EV_READ)
	evutil_timerclear(&gp_cfg.timeout);
	gp_cfg.timeout.tv_usec = gp_cfg.gp_timeout * 1000;
 	if ( event_add(&gp_cfg.evport, &gp_cfg.timeout) < 0) syslog(LOG_ERR, "event_add.send_mess.ev_timeout setup: %m");

// 	fprintf(stderr, "Set last read %lu \n",current_time);
	devices[send_mess.dev].last_read=receiv_mess.last_read=current_time;
//	gp_cfg.last_dev=send_mess.dev;
	send_mess.is_expected=0;
// TODO after check crc
	if( gp_cfg.polling == 1 && devices[send_mess.dev].activ==0) {
		syslog(LOG_ERR,"Found dev: '%d'\n",send_mess.dev);
	}
	devices[send_mess.dev].activ=1; 
	devices[send_mess.dev].timeout_count=0;
	if (devices[send_mess.dev].is_inited == 0) {
		gp_dev_init(send_mess.dev);
	}
// HACK	
//	mydev=send_mess.dst;
// First chunk of data. 
	if( receiv_buf_p == 0 ) {
		receiv_buf_p = receiv_mess.buf;
		receiv_mess.len=0;
	}
	nread = read(fd, receiv_buf_p, GP_PORT_READ_BUF_LENGTH - 1 - receiv_mess.len);
	
	
//	if( debug >= 5 || (debug >= 4 && gp_cfg.polling == 0) ||  receiv_mess.src != 7) {
	if( debug >= 9 || (debug >= 8 && gp_cfg.polling == 0) ) {
		print_buff("port received: ", receiv_buf_p, nread);
	}
// 	dprint(DL5, "read %d bytes, ev=%x\n", nread, event);
	
	if (nread < 0) { /* EOF */
		syslog(LOG_CRIT, "read: %m");
		gp_close();
		// daemon_exit(1); // never exit on error!
	} else if (nread == 0) {
	 	zprintf(1, "port unexpectedly closed\n");
	 	ad_soft_reset(AD_Q_SHORT,send_mess.dev);
		gp_close();
//		gp_reconnect(0);
//		if(err++  > 10 ) exit(102);
		return;
	} else if (nread > 0) {
		// right trim buffer
		receiv_buf_p[nread] = '\0';
		if( receiv_mess.fl_begin !=  GP_INIT) {
			syslog(LOG_ERR, "Begin flag not found");
			gp_reconnect(0);
//			gp_close();
			return;
		}		
		uint8_t* p=memchr(receiv_buf_p, GP_END,nread);
		if ( p != 0 ) {
			receiv_buf_p=0;
//			*p='\0'; 
			int l = p - &receiv_mess.id_ctrl; // buff. length  for crc		
//	fprintf(stderr, "l = %d bytes\n", l);
//			l = memcpy_unesc(receiv_mess.cmd_buff,receiv_mess.cmd_buff,l);
			l = memcpy_unesc(&receiv_mess.id_ctrl,&receiv_mess.id_ctrl,l);
	
//	fprintf(stderr, "l = %d bytes\n", l);
			if ( crc8_xor(&receiv_mess.id_ctrl,l) > 0 ) {
				int crc=crc8_xor(&receiv_mess.id_ctrl,l-1);
				fprintf(stderr, "crc8 error for %d (cmd=%d, crc=x0%02x) \n", send_mess.dev, send_mess.target, crc);
				syslog(LOG_ERR, "crc8 error for %d (cmd=%d, crc=x0%02x) \n", send_mess.dev, send_mess.target, crc);
				if( debug < 9 ) 
					print_buff("port received (crc error): ", receiv_mess.buf, nread+receiv_mess.len);
//				exit(222);
				return;
			}
// Check error!!!
			if( send_mess.dev !=  receiv_mess.src ) {
				zprintf(2, "device error: got %d, expect %d\n", receiv_mess.src, send_mess.dev);
//				exit(222);				
				return;
			} else {
				receiv_mess.dev=receiv_mess.src;
			}
			if( receiv_mess.cmd_n == GP_REPLY ) {
//				syslog(LOG_ERR, "Got ask(0x%02X) for %d (cmd=%d)\n",receiv_mess.replay, send_mess.dev, send_mess.target);
				if( receiv_mess.replay == GP_REPLY_ACK ) {
					receiv_mess.cmd_n=receiv_mess.was_cmd_n;
//					fprintf(stderr, "Got ACK for (0x%02X) \n", receiv_mess.was_cmd_n);
					process_port_input(PROC_REPLY_ACK);
				} else if ( receiv_mess.replay == GP_REPLY_NACK ) {
					receiv_mess.cmd_n=receiv_mess.was_cmd_n;
					zprintf(2, "Got NACK for (0x%02X) \n", receiv_mess.was_cmd_n);
//					process_port_input(PROC_REPLY_NACK);
				} else {
					receiv_mess.cmd_n=receiv_mess.bad_cmd_n;
					zprintf(2, "Got  EEPROM/RTC error (%d)\n",receiv_mess.replay );
//					process_port_input(PROC_REPLY_EEPROM_ERR);
				}				
			} else {
				receiv_mess.len=l-(3+1);
				if( process_port_input(PROC_REPLY_ACK) > 0 ) return;
			}
		} else {
			receiv_mess.len +=nread;
			receiv_buf_p+=nread;
			return;
		}
//			dprint(DL2, "port recvd: '%.*s'\n", nread, buf);
/*			if(debug >= DL2) {
				char buf2[PORT_READ_BUF_LENGTH];
				char* p=strncpy(buf2,buf,PORT_READ_BUF_LENGTH);
				while( (p=strchr(p,'\r')) > 0 ) *p='$';
				p=buf2;
				while( (p=strchr(buf2,'\n')) >0 ) *p='&';
				dprint(DL2, "port recvd: '%s'\n", buf2);
			}*/
	}
//	fprintf(stderr, "Sending new cmd\n");
	gp_put_cmd();
// 	if ( gp_put_cmd() == 0 && event_add(&gp_cfg.evport, &gp_cfg.timeout) < 0) 
// 		syslog(LOG_ERR, "event_add.send_mess.ev_timeout setup: %m");

// exit(0);	f
// fprintf(stderr, "gp_receiv ok \n");
}