Exemplo n.º 1
0
int ast_jb_get_when_to_wakeup(struct ast_channel *c0, struct ast_channel *c1, int time_left)
{
	struct ast_jb *jb0 = ast_channel_jb(c0);
	struct ast_jb *jb1 = ast_channel_jb(c1);
	int c0_use_jb = ast_test_flag(jb0, JB_USE);
	int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
	int c1_use_jb = ast_test_flag(jb1, JB_USE);
	int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
	int wait, wait0, wait1;
	struct timeval tv_now;

	if (time_left == 0) {
		/* No time left - the bridge will be retried */
		/* TODO: Test disable this */
		/*return 0;*/
	}

	if (time_left < 0) {
		time_left = INT_MAX;
	}

	gettimeofday(&tv_now, NULL);

	wait0 = (c0_use_jb && c0_jb_is_created) ? jb0->next - get_now(jb0, &tv_now) : time_left;
	wait1 = (c1_use_jb && c1_jb_is_created) ? jb1->next - get_now(jb1, &tv_now) : time_left;

	wait = wait0 < wait1 ? wait0 : wait1;
	wait = wait < time_left ? wait : time_left;

	if (wait == INT_MAX) {
		wait = -1;
	} else if (wait < 1) {
		/* don't let wait=0, because this can cause the pbx thread to loop without any sleeping at all */
		wait = 1;
	}

	return wait;
}
Exemplo n.º 2
0
MoonAppRecord *
MoonAppDatabase::CreateAppRecord (const Uri *origin)
{
	char *install_dir, *uid;
	MoonAppRecord *app;
	const char *domain;
	
	if (origin == NULL || !(domain = origin->GetHost ()))
		domain = "localhost";
	
	int seed = (int)(get_now () >> 32);
#if !HAVE_RAND_R
	srand (seed);
#endif
	do {
#if HAVE_RAND_R
		int r = rand_r (&seed);
#else
		int r = rand ();
#endif

		uid = g_strdup_printf ("%u.%s", r, domain);
		install_dir = g_build_filename (base_dir, uid, NULL);
		if (g_mkdir_with_parents (install_dir, 0777) == 0)
			break;
		
		g_free (install_dir);
		g_free (uid);
		
		if (errno != EEXIST) {
			// EEXIST is the only error we can recover from...
			return NULL;
		}
	} while (true);
	
	app = new MoonAppRecord ();
	app->origin = g_strdup (origin->GetOriginalString ());
	app->mtime = time (NULL);
	app->uid = uid;
	
	if (!AddAppRecord (app)) {
		RemoveDir (install_dir);
		delete app;
		return NULL;
	}
	
	g_free (install_dir);
	
	return app;
}
/*
 * Check whether we need to rotate.
 * Possible reasons are:
 * - No log file open (ROTATE_NEW)
 * - User forces us to rotate (ROTATE_FORCE)
 * - Our log file size is already bigger than the
 *   allowed maximum (ROTATE_SIZE)
 * - The next log time interval expired (ROTATE_TIME)
 *
 * When size and time constraints are both given,
 * it suffices that one of them is fulfilled.
 */
static void checkRotate(rotate_config_t *config, rotate_status_t *status)
{
    if (status->current.fd == NULL) {
        status->rotateReason = ROTATE_NEW;
    }
    else if (config->sRotation) {
        apr_finfo_t finfo;
        apr_off_t current_size = -1;

        if (apr_file_info_get(&finfo, APR_FINFO_SIZE, status->current.fd) == APR_SUCCESS) {
            current_size = finfo.size;
        }

        if (current_size > config->sRotation) {
            status->rotateReason = ROTATE_SIZE;
        }
        else if (config->tRotation) {
            if (get_now(config) >= status->tLogEnd) {
                status->rotateReason = ROTATE_TIME;
            }
        }
    }
    else if (config->tRotation) {
        if (get_now(config) >= status->tLogEnd) {
            status->rotateReason = ROTATE_TIME;
        }
    }
    else {
        fprintf(stderr, "No rotation time or size specified\n");
        exit(2);
    }

    if (status->rotateReason != ROTATE_NONE && config->verbose) {
        fprintf(stderr, "File rotation needed, reason: %s\n", ROTATE_REASONS[status->rotateReason]);
    }
}
Exemplo n.º 4
0
void TournamentSR::spawn_player(Player *p) {
    if (!server) {
        TimesOfPlayer *top = get_times_of_player(p);
        if (top) {
            if (!top->running) {
                top->running = true;
            } else {
                if (top->finished) {
                    top->finished = false;
                    gametime_t now;
                    get_now(now);
                    ms_t d_ms = diff_ms(top->start_time, now);
                    GTransportTime *race = new GTransportTime;
                    race->id = p->state.id;
                    race->ms = static_cast<sr_milliseconds_t>(d_ms);
                    race->to_net();
                    add_state_response(GPSRoundFinished, GTransportTimeLen, race);
                }
            }
            get_now(top->start_time);
        }
    }
    Tournament::spawn_player(p);
}
Exemplo n.º 5
0
char*ndpi_find_lru_cache_str(struct ndpi_LruCache *cache, char *key) {
  if(cache->hash_size == 0)
    return(0);
  else {
    u_int32_t hash_val =  lru_hash_string(key);
    u_int32_t hash_id = hash_val % cache->hash_size;
    struct ndpi_LruCacheEntry *head, *prev = NULL;
    char *ret_val = NULL;
    time_t now = get_now();

    if(unlikely(traceLRU))
      printf("%s(%s)", __FUNCTION__, key);

    // validate_unit_len(cache, hash_id);
    cache->num_cache_find++;
    head = cache->hash[hash_id];
        
    while(head != NULL) {
      if(strcmp(head->u.str.key, key) == 0) {
	if(head->u.str.expire_time < now) {
	  /* The node has expired */
	  if(prev == NULL)
	    cache->hash[hash_id] = head->next;
	  else
	    prev->next = head->next;

	  free_lru_cache_entry(cache, head);
	  ndpi_free(head);
#ifdef FULL_STATS
	  cache->mem_size -= sizeof(struct ndpi_LruCacheEntry);
#endif
	  ret_val = NULL;
	  cache->current_hash_size[hash_id]--;
	} else
	  ret_val = head->u.str.value;
	break;
      } else {
	prev = head;
	head = head->next;
      }
    }

    if(ret_val == NULL) cache->num_cache_misses++;
    // validate_unit_len(cache, hash_id);

    return(ret_val);
  }
}
Exemplo n.º 6
0
void handle_request_stats(struct evhttp_request *req, void *arg){
	global_data * global = (global_data *) arg;

	struct evbuffer *evb;
	evb = evbuffer_new();

	evbuffer_add_printf(evb, "Uptime:   %u<br />\n", (get_now() - global->stats.starttime));
	evbuffer_add_printf(evb, "Requests: %u<br />\n", global->stats.requests);
//	evbuffer_add_printf(evb, "Games:    %u<br />\n", global->stats.games);
	evbuffer_add_printf(evb, "Moves:    %u<br />\n", global->stats.moves);
	evbuffer_add_printf(evb, "Cpu Time: %u s<br />\n", global->stats.cputime/1000);

	evhttp_send_reply(req, HTTP_OK, "OK", evb);

	evbuffer_free(evb);
}
Exemplo n.º 7
0
void main_loop(void)
{
        int n;
        struct timer *timer;
        int delay;

        while (num_pollfds > 1 || heap_len(timers) > 1
               || pollfds[0].events & POLLOUT) {
                if (heap_empty(timers)) {
                        timer = NULL;
                        delay = -1;
                } else {
                        timer = heap_peek(timers);
                        delay = (timer->time - get_now()) * 1000;
                }
                
                if (timer && delay <= 0)
                        n = 0;
                else
                        n = poll(pollfds, num_pollfds, delay);

                if (!n) {
                        timer = heap_extract_min(timers);
                        timer->func(timer->data);
                        free(timer);
                        goto cont;
                }

                for (int i = 0; i < num_pollfds && n; i++) {
                        if (pollfds[i].revents) {
                                event_handlers[i]->func(event_handlers[i]->data);
                                n--;

                                /* We may have just deleted this id.
                                 * Try it again in case it's a new
                                 * one. */
                                i--;
                        }
                }

        cont:
                maybe_dequeue();                
        }
}
Exemplo n.º 8
0
struct ndpi_LruCacheEntry* lru_allocCacheStringNode(struct ndpi_LruCache *cache, char *key, char *value, u_int32_t timeout) {
  struct ndpi_LruCacheEntry *node = (struct ndpi_LruCacheEntry*)ndpi_calloc(1, sizeof(struct ndpi_LruCacheEntry));

  if(unlikely(traceLRU))
    printf("%s(key=%s, value=%s)", __FUNCTION__, key, value);

  if(node == NULL)
    printf("ERROR: Not enough memory?");
  else {
    node->numeric_node = 0;
    node->u.str.key = ndpi_strdup(key), node->u.str.value = ndpi_strdup(value);
    node->u.str.expire_time = (timeout == 0) ? 0 : (compute_timeout(timeout) + get_now());

#ifdef FULL_STATS
    cache->mem_size += sizeof(struct ndpi_LruCacheEntry) + strlen(key) + strlen(value);
    //printf("%s(key=%s, value=%s) [memory: %u]", __FUNCTION__, key, value, cache->mem_size);
#endif
  }

  return(node);
}
Exemplo n.º 9
0
void init(void)
{
        struct timespec timespec;

        queue = queue_new();

        if (0 > clock_getres(CLOCK_MONOTONIC, &timespec)) die();

        /* 5 ms resolution should be _plenty_ */
        if (timespec.tv_sec || timespec.tv_nsec > 5000000) die();

        start_time = 0;
        start_time = get_now();
        
        if (timers) die();

        timers = heap_new(timer_cmp, offsetof(struct timer, heap_loc));

        max_pollfds = 128;
        num_pollfds = 0;
        myallocn(pollfds, max_pollfds);
        myallocn(event_handlers, max_pollfds);
}
Exemplo n.º 10
0
void TournamentSR::draw_score() {
    Player *me = get_me();
    if (!(me->state.server_state.flags & PlayerServerFlagSpectating)) {
        TimesOfPlayer *top = get_times_of_player(me);
        if (top) {
            subsystem.set_color(0.75f, 0.75f, 1.0f, 0.75f);

            if (!game_over) {
                get_now(now_for_drawing);
            }
            ms_t d_ms = diff_ms(top->start_time, now_for_drawing);
            float diff = round(d_ms / 10.0f) / 100.0f;

            char *pb;
            int len;
            int x;
            int view_width = subsystem.get_view_width();
            Tileset *ts = resources.get_tileset("numbers");
            int tile_width = ts->get_tile(0)->get_tilegraphic()->get_width();
            int number_width = tile_width - 13;
            int i = static_cast<int>(floor(diff));
            int m = static_cast<int>((diff - i) * 100);

            /* first part */
            sprintf(buffer, "%d", i);
            len = strlen(buffer);
            x = view_width / 2 - (len * number_width) - number_width / 2;
            pb = buffer;
            while (*pb) {
                subsystem.draw_tile(ts->get_tile(*pb - '0'), x, 5);
                x += number_width;
                pb++;
            }

            /* draw dot */
            subsystem.draw_tile(ts->get_tile(11), x, 5);
            x += number_width;

            /* second part */
            sprintf(buffer, "%02d", m);
            pb = buffer;
            while (*pb) {
                subsystem.draw_tile(ts->get_tile(*pb - '0'), x, 5);
                x += number_width;
                pb++;
            }

            /* reset */
            subsystem.reset_color();

            /* draw best & last lap */
            size_t sz = top->times.size();
            Font *f = resources.get_font("big");

            const TimesOfPlayer& lead = times_of_players[0];
            if (lead.times.size()) {
                subsystem.set_color(0.25f, 1.0f, 0.25f, 1.0f);
                subsystem.draw_text(f, 5, 5, "lead:");
                sprintf(buffer, "%.2f (%s)", lead.best, lead.player->get_player_name().c_str());
                subsystem.draw_text(f, 45, 5, buffer);
                subsystem.reset_color();
            }

            subsystem.draw_text(f, 5, 20, "lap:");
            sprintf(buffer, "%d", static_cast<int>(sz + 1));
            subsystem.draw_text(f, 45, 20, buffer);

            if (sz) {
                subsystem.draw_text(f, 5, 35, "best:");
                sprintf(buffer, "%.2f", top->best);
                subsystem.draw_text(f, 45, 35, buffer);

                subsystem.draw_text(f, 5, 50, "last:");
                sprintf(buffer, "%.2f", top->last);
                subsystem.draw_text(f, 45, 50, buffer);
            }
        }
    }
}
Exemplo n.º 11
0
 /**
  * Updates the time stamp, setting it to the current clock.
  */
 void update() {
   last = get_now();
 }
Exemplo n.º 12
0
void
TimeManager::SourceTick ()
{
#if PUT_TIME_MANAGER_TO_SLEEP
	// we need to do this because we might have had a shorter timeout due to putting the time manager to sleep
	source->SetTimerFrequency (current_timeout);
#endif

	TimeManagerOp current_flags = flags;

#if PUT_TIME_MANAGER_TO_SLEEP
	flags = (TimeManagerOp)0;
#endif

	if (current_flags & TIME_MANAGER_TICK_CALL) {
		STARTTICKTIMER (tm_tick_call, "TimeManager::Tick - Call");
		InvokeTickCalls ();
		ENDTICKTIMER (tm_tick_call, "TimeManager::Tick - Call");
	}

	if (current_flags & TIME_MANAGER_UPDATE_CLOCKS) {
		STARTTICKTIMER (tick_update_clocks, "TimeManager::Tick - UpdateClocks");
		current_global_time = source->GetNow();
		current_global_time_usec = current_global_time / 10;

		bool need_another_tick = root_clock->UpdateFromParentTime (GetCurrentTime());

		if (need_another_tick)
			NeedClockTick ();
	
		// ... then cause all clocks to raise the events they've queued up
		root_clock->RaiseAccumulatedEvents ();
		
		applier->Apply ();
		applier->Flush ();
	
		root_clock->RaiseAccumulatedCompleted ();

#if CLOCK_DEBUG
		if (need_another_tick)
			ListClocks ();
#endif
		ENDTICKTIMER (tick_update_clocks, "TimeManager::Tick - UpdateClocks");
	}

	if (current_flags & TIME_MANAGER_UPDATE_INPUT) {
		STARTTICKTIMER (tick_input, "TimeManager::Tick - Input");
		Emit (UpdateInputEvent);
		ENDTICKTIMER (tick_input, "TimeManager::Tick - Input");
	}

	if (current_flags & TIME_MANAGER_RENDER) {
		// fprintf (stderr, "rendering\n"); fflush (stderr);
		STARTTICKTIMER (tick_render, "TimeManager::Tick - Render");
		rendering_args->SetRenderingTime (get_now());
		rendering_args->ref (); // to keep Emit from destroying the object
		Emit (RenderEvent, rendering_args);
		ENDTICKTIMER (tick_render, "TimeManager::Tick - Render");
	}

	last_global_time = current_global_time;

#if PUT_TIME_MANAGER_TO_SLEEP
	if (flags == 0 && source_tick_pending) {
		Stop ();
	}
#endif
}
int main (int argc, const char * const argv[])
{
    char buf[BUFSIZE];
    apr_size_t nRead, nWrite;
    apr_file_t *f_stdin;
    apr_file_t *f_stdout;
    apr_getopt_t *opt;
    apr_status_t rv;
    char c;
    const char *opt_arg;
    const char *err = NULL;
#if APR_FILES_AS_SOCKETS
    apr_pollfd_t pollfd = { 0 };
    apr_status_t pollret = APR_SUCCESS;
    int polltimeout;
#endif

    apr_app_initialize(&argc, &argv, NULL);
    atexit(apr_terminate);

    memset(&config, 0, sizeof config);
    memset(&status, 0, sizeof status);
    status.rotateReason = ROTATE_NONE;

    apr_pool_create(&status.pool, NULL);
    apr_getopt_init(&opt, status.pool, argc, argv);
#if APR_FILES_AS_SOCKETS
    while ((rv = apr_getopt(opt, "lL:p:ftvecn:", &c, &opt_arg)) == APR_SUCCESS) {
#else
    while ((rv = apr_getopt(opt, "lL:p:ftven:", &c, &opt_arg)) == APR_SUCCESS) {
#endif
        switch (c) {
        case 'l':
            config.use_localtime = 1;
            break;
        case 'L':
            config.linkfile = opt_arg;
            break;
        case 'p':
            config.postrotate_prog = opt_arg;
            break;
        case 'f':
            config.force_open = 1;
            break;
        case 't':
            config.truncate = 1;
            break;
        case 'v':
            config.verbose = 1;
            break;
        case 'e':
            config.echo = 1;
            break;
#if APR_FILES_AS_SOCKETS
        case 'c':
            config.create_empty = 1;
            break;
#endif
        case 'n':
            config.num_files = atoi(opt_arg);
            status.fileNum = -1;
            break;
        }
    }

    if (rv != APR_EOF) {
        usage(argv[0], NULL /* specific error message already issued */ );
    }

    /*
     * After the initial flags we need 2 to 4 arguments,
     * the file name, either the rotation interval time or size
     * or both of them, and optionally the UTC offset.
     */
    if ((argc - opt->ind < 2) || (argc - opt->ind > 4) ) {
        usage(argv[0], "Incorrect number of arguments");
    }

    config.szLogRoot = argv[opt->ind++];

    /* Read in the remaining flags, namely time, size and UTC offset. */
    for(; opt->ind < argc; opt->ind++) {
        if ((err = get_time_or_size(&config, argv[opt->ind],
                                    opt->ind < argc - 1 ? 0 : 1)) != NULL) {
            usage(argv[0], err);
        }
    }

    config.use_strftime = (strchr(config.szLogRoot, '%') != NULL);

    if (config.use_strftime && config.num_files > 0) { 
        fprintf(stderr, "Cannot use -n with %% in filename\n");
        exit(1);
    }

    if (status.fileNum == -1 && config.num_files < 1) { 
        fprintf(stderr, "Invalid -n argument\n");
        exit(1);
    }

    if (apr_file_open_stdin(&f_stdin, status.pool) != APR_SUCCESS) {
        fprintf(stderr, "Unable to open stdin\n");
        exit(1);
    }

    if (apr_file_open_stdout(&f_stdout, status.pool) != APR_SUCCESS) {
        fprintf(stderr, "Unable to open stdout\n");
        exit(1);
    }

    /*
     * Write out result of config parsing if verbose is set.
     */
    if (config.verbose) {
        dumpConfig(&config);
    }

#if APR_FILES_AS_SOCKETS
    if (config.create_empty && config.tRotation) {
        pollfd.p = status.pool;
        pollfd.desc_type = APR_POLL_FILE;
        pollfd.reqevents = APR_POLLIN;
        pollfd.desc.f = f_stdin;
    }
#endif

    /*
     * Immediately open the logfile as we start, if we were forced
     * to do so via '-f'.
     */
    if (config.force_open) {
        doRotate(&config, &status);
    }

    for (;;) {
        nRead = sizeof(buf);
#if APR_FILES_AS_SOCKETS
        if (config.create_empty && config.tRotation) {
            polltimeout = status.tLogEnd ? status.tLogEnd - get_now(&config) : config.tRotation;
            if (polltimeout <= 0) {
                pollret = APR_TIMEUP;
            }
            else {
                pollret = apr_poll(&pollfd, 1, &pollret, apr_time_from_sec(polltimeout));
            }
        }
        if (pollret == APR_SUCCESS) {
            rv = apr_file_read(f_stdin, buf, &nRead);
            if (APR_STATUS_IS_EOF(rv)) {
                break;
            }
            else if (rv != APR_SUCCESS) {
                exit(3);
            }
        }
        else if (pollret == APR_TIMEUP) {
            *buf = 0;
            nRead = 0;
        }
        else {
            fprintf(stderr, "Unable to poll stdin\n");
            exit(5);
        }
#else /* APR_FILES_AS_SOCKETS */
        rv = apr_file_read(f_stdin, buf, &nRead);
        if (APR_STATUS_IS_EOF(rv)) {
            break;
        }
        else if (rv != APR_SUCCESS) {
            exit(3);
        }
#endif /* APR_FILES_AS_SOCKETS */
        checkRotate(&config, &status);
        if (status.rotateReason != ROTATE_NONE) {
            doRotate(&config, &status);
        }

        nWrite = nRead;
        rv = apr_file_write_full(status.current.fd, buf, nWrite, &nWrite);
        if (nWrite != nRead) {
            apr_off_t cur_offset;

            cur_offset = 0;
            if (apr_file_seek(status.current.fd, APR_CUR, &cur_offset) != APR_SUCCESS) {
                cur_offset = -1;
            }
            status.nMessCount++;
            apr_snprintf(status.errbuf, sizeof status.errbuf,
                         "Error %d writing to log file at offset %" APR_OFF_T_FMT ". "
                         "%10d messages lost (%pm)\n",
                         rv, cur_offset, status.nMessCount, &rv);

            truncate_and_write_error(&status);
        }
        else {
            status.nMessCount++;
        }
        if (config.echo) {
            if (apr_file_write_full(f_stdout, buf, nRead, &nWrite)) {
                fprintf(stderr, "Unable to write to stdout\n");
                exit(4);
            }
        }
    }

    return 0; /* reached only at stdin EOF. */
}
/*
 * Open a new log file, and if successful
 * also close the old one.
 *
 * The timestamp for the calculation of the file
 * name of the new log file will be the actual millisecond
 * timestamp, except when a regular rotation based on a time
 * interval is configured and the previous interval
 * is over. Then the timestamp is the starting time
 * of the actual interval.
 */
static void doRotate(rotate_config_t *config, rotate_status_t *status)
{

    int now = get_now(config);
    int tLogStart;
    apr_status_t rv;
    struct logfile newlog;
    int thisLogNum = -1;

    status->rotateReason = ROTATE_NONE;

    if (config->tRotation) {
        int tLogEnd;
        tLogStart = (now / config->tRotation) * config->tRotation;
        tLogEnd = tLogStart + config->tRotation;
        /*
         * Check if rotation was forced and the last rotation
         * interval is not yet over. Use the value of now instead
         * of the time interval boundary for the file name then.
         */
        if (tLogStart < status->tLogEnd) {
            tLogStart = now;
        }
        status->tLogEnd = tLogEnd;
    }
    else {
        tLogStart = now;
    }

    if (config->use_strftime) {
        apr_time_t tNow = apr_time_from_sec(tLogStart);
        apr_time_exp_t e;
        apr_size_t rs;

        apr_time_exp_gmt(&e, tNow);
        apr_strftime(newlog.name, &rs, sizeof(newlog.name), config->szLogRoot, &e);
    }
    else {
        if (config->truncate) {
            apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot);
        }
        else if (config->num_files > 0) { 
            if (status->fileNum == -1 || status->fileNum == (config->num_files - 1)) {
                thisLogNum = 0;
                apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot);
            }
            else { 
                thisLogNum = status->fileNum + 1;
                apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%d", config->szLogRoot, thisLogNum);
            }
        }
        else {
            apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%010d", config->szLogRoot,
                         tLogStart);
        }
    }
    apr_pool_create(&newlog.pool, status->pool);
    if (config->verbose) {
        fprintf(stderr, "Opening file %s\n", newlog.name);
    }
    rv = apr_file_open(&newlog.fd, newlog.name, APR_WRITE | APR_CREATE | APR_APPEND
                       | (config->truncate || (config->num_files > 0 && status->current.fd) ? APR_TRUNCATE : 0), 
                       APR_OS_DEFAULT, newlog.pool);
    if (rv == APR_SUCCESS) {
        /* Handle post-rotate processing. */
        post_rotate(newlog.pool, &newlog, config, status);

        status->fileNum = thisLogNum;
        /* Close out old (previously 'current') logfile, if any. */
        if (status->current.fd) {
            close_logfile(config, &status->current);
        }

        /* New log file is now 'current'. */
        status->current = newlog;
    }
    else {
        char error[120];

        apr_strerror(rv, error, sizeof error);

        /* Uh-oh. Failed to open the new log file. Try to clear
         * the previous log file, note the lost log entries,
         * and keep on truckin'. */
        if (status->current.fd == NULL) {
            fprintf(stderr, "Could not open log file '%s' (%s)\n", newlog.name, error);
            exit(2);
        }

        /* Throw away new state; it isn't going to be used. */
        apr_pool_destroy(newlog.pool);

        /* Try to keep this error message constant length
         * in case it occurs several times. */
        apr_snprintf(status->errbuf, sizeof status->errbuf,
                     "Resetting log file due to error opening "
                     "new log file, %10d messages lost: %-25.25s\n",
                     status->nMessCount, error);

        truncate_and_write_error(status);
    }

    status->nMessCount = 0;
}
int main(int argc, char**argv)
{

			//Iterator
		  int i;

		  //Port number
		  int port;

		  //Host file
		  string hostfile;

		  //count of messages to be sent
			int count;

			//Delivery queue
			map<Key,DM*> delivery_queue;

			//Delivered Messages
			vector<Key> delivered_queue;

			//Map to store Hostname to IP address
			map<string,string> host_to_id;

			//Map to store Hostname to id
			map<string,int> hostname_to_id;

			//Map to maintain retransmission info
			map<string,bool> host_retransmit_info;

			//buffer to hold a recieved message
			char *mesg = (char *)malloc(sizeof(AckMessage));

			if(argc < 7)
			{
				kprintf("Usage: ");
				kprintf("proj2 -p port -h hostfile -c count");
				exit(EXIT_FAILURE);
			}

		  for(i=0;i<argc;i++)
		  {
					 string arg = argv[i];
					 if(arg == "-p")
					 {					 			
					 			if(argv[i+1])
								{
									string temp = argv[i+1];
									port = atoi(temp.c_str());
									if(port == 0 || port <=1024)
									{
										kprintf("Invalid port. Please specify a port greater than 1024");
										exit(EXIT_FAILURE);
									}
									i = i + 1;
								}
								else
								{
									kprintf("Please specify port number");
									exit(EXIT_FAILURE);
								}
					 }

					 if(arg == "-h")
					 {	
					 			if(argv[i+1])
								{
									hostfile = argv[i+1];
									i = i + 1;
								}
								else
								{
									kprintf("Please specify host file");
									exit(EXIT_FAILURE);
								}
					 }

					 if(arg == "-c")
					 {
					 			if(argv[i+1])
								{
									string temp = argv[i+1];
									count = atoi(temp.c_str());
									i = i + 1;
									if(count < 0)
									{
										kprintf("Number of messages to be multicast must be greater than zero");
										exit(EXIT_FAILURE);
									}
								}
								else
								{
									kprintf("Please specify number of messages to be multicast");
									exit(EXIT_FAILURE);
								}
					 }

		  }

			kprintf("Port: ",port);
			kprintf("Hostfile: ",hostfile);
			kprintf("Count: ",count);
	
			ifstream hostfile_stream(hostfile.c_str());
		
			string hostname;

			int host_id = 0;

			if(hostfile_stream.is_open())
			{
				while(hostfile_stream.good())
				{		
						getline(hostfile_stream,hostname);		
						if(!hostname.empty())
						{							
							hostname_to_id[hostname] = host_id++;
						
							//Get IP address
							struct hostent *hp;
							hp = gethostbyname(hostname.c_str());
		
							if(!hp)
							{
								kprintf(" not found ",hostname);
								exit(EXIT_FAILURE);			
							}
					
							if((inet_ntoa(*(struct in_addr *)hp->h_addr_list[0])))
							{
									  string s_local(inet_ntoa(*(struct in_addr *)hp->h_addr_list[0]));
	
										kprintf(s_local.c_str());
										
										if(s_local.find("127") != 0)
										{
											host_to_id[hostname] = s_local;
											host_retransmit_info[s_local] = false;
										}
										else
										{
											host_to_id[hostname] = string(inet_ntoa(*(struct in_addr *)hp->h_addr_list[1]));
											host_retransmit_info[string(inet_ntoa(*(struct in_addr *)hp->h_addr_list[1]))] = false;
										}
							}
							else
							{
									host_to_id[hostname] = string(inet_ntoa(*(struct in_addr *)hp->h_addr_list[1]));
									host_retransmit_info[string(inet_ntoa(*(struct in_addr *)hp->h_addr_list[1]))] = false;
							}
							kprintf(hostname.c_str());
	
						}
				}			
				hostfile_stream.close();
			}
			else
			{
				kprintf("Unable to read host file");
				exit(EXIT_FAILURE);
			}

			kprintf("Size is: ",host_to_id.at("xinu01.cs.purdue.edu"));

			//get my hostname
			char myhostname[HOSTNAME_LEN];
			gethostname(myhostname,HOSTNAME_LEN);

			string myhostname_str(myhostname);

			host_retransmit_info[host_to_id[myhostname_str]] = true;

			//Iterator for sending messages		
			int iter=0;

			//Seq numbers to be maintained throughout
			int max_last_proposed_seq_num=0;
			int last_proposed_seq_num = 0;

			//Socket variables
			int sockfd,n;
			struct sockaddr_in servaddr,cliaddr;
			socklen_t lensock;
		
			sockfd = socket(AF_INET,SOCK_DGRAM,0);

			if(sockfd == -1)
			{
				kprintf("Could not create socket");
				exit(EXIT_FAILURE);
			}

			bzero(&servaddr,sizeof(servaddr));
			servaddr.sin_family = AF_INET;
			servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
			servaddr.sin_port=htons(port);
			
			int bval = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
			
			if(bval==-1)
			{
				kprintf("Bind failed\n");
				exit(EXIT_FAILURE);
			}
			
			//Multiset to maintain all the sequence numbers recieved in Acks
			multiset<int> ackmultiset;


			//infinite loop for the protocol
			while(1)
			{
					//Send message to all other hosts/processes only if iter<count
					if(iter<count)
					{
						DataMessage *init_dm = (DataMessage *)malloc(sizeof(DataMessage));
						init_dm->type = TYPE_DM;
						init_dm->sender = hostname_to_id[myhostname_str];
					
						//Get sender ID
						kprintf("Sender ID: ",init_dm->sender);

						init_dm->msg_id = iter;
						init_dm->data = iter;
					
						host_network(init_dm);

						for(map<string,string>::iterator it	=	host_to_id.begin();it	!= host_to_id.end();++it)
						{
							if(host_retransmit_info[it->second.c_str()] == false)
							{
								cliaddr.sin_family = AF_INET;
								cliaddr.sin_addr.s_addr = inet_addr(it->second.c_str());
								cliaddr.sin_port = htons(port);
								int rval = sendto(sockfd,init_dm,sizeof(DataMessage),0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));								
								kprintf("Sent message ",it->second.c_str());
							}
						}					
						
						network_host(init_dm);

						Key current_srch_key (last_proposed_seq_num,hostname_to_id[myhostname_str]);								
				
						//Add the sent message to your queue if it does not already exist
						if(delivery_queue.find(current_srch_key) == delivery_queue.end())
						{
							DM* sent_msg = (DM*)malloc(sizeof(DM));
							sent_msg->deliverable = false;
							sent_msg->seq_num = ++max_last_proposed_seq_num;
							sent_msg->data_msg = init_dm;
							Key current_key (sent_msg->seq_num,hostname_to_id[myhostname_str]);								
							last_proposed_seq_num = max_last_proposed_seq_num;	
							//Add the sent message to your queue
							delivery_queue[current_key] = sent_msg;
							kprintf("Inserted in delivery queue",current_key.seq);
						}
					}

					//Start Recieving messages here
					//start ack timer
					 struct timeval time_ack,time_curr_ack;                            
					 get_now(&time_ack);

					 while(time_to_seconds(&time_ack,get_now(&time_curr_ack)) <= UDP_RETRANSMIT_TIMER)
					 {
					 			
								socklen_t lensock = sizeof(cliaddr);                            
					      if((n = recvfrom(sockfd,mesg,sizeof(AckMessage),MSG_DONTWAIT,(struct sockaddr *)&cliaddr,&lensock)) > 0)
								{
									
									//Get the type by converting from network to host
									uint32_t* recv_type = (uint32_t*)malloc(sizeof(uint32_t));
									memcpy(recv_type,mesg,sizeof(uint32_t));
									int type = *recv_type;
									type = ntohl(type);
			
									kprintf("Recieved Type",type);

									if(type == TYPE_ACK)
									{
												AckMessage* ack_mesg = (AckMessage*)mesg;
												network_host(ack_mesg);
												
												int sender = hostname_to_id[myhostname_str];
												if(ack_mesg->receiver == sender && iter == ack_mesg->msg_id)
												{
													//Mark Ack recieved
													string ip = string(inet_ntoa(cliaddr.sin_addr));
													
													if(host_retransmit_info.find(ip) != host_retransmit_info.end())
													{
														host_retransmit_info[ip] = true;
														kprintf("Marked true for ip ",ip.c_str());
													}
												}
												ackmultiset.insert(ack_mesg->proposed_seq);
									}
									else if(type == TYPE_DM)
									{
										//Check if it is delivered
										DataMessage* dm_mesg = (DataMessage*) mesg;

										network_host(dm_mesg);

										int msg_id = dm_mesg->msg_id;
										int sender = dm_mesg->sender;
										bool delivered = false;

										for(vector<Key>:: iterator it=delivered_queue.begin();it!=delivered_queue.end();++it)
										{
											if((*it).seq == msg_id && (*it).pid == sender)
											{
												delivered = true;
											}
										}
										
										//Check if in ready queue
										bool inreadyqueue = false;

										for(map<Key,DM*>:: iterator it=delivery_queue.begin();it!=delivery_queue.end();it++)
										{
											if((it->second)->data_msg->msg_id == msg_id && (it->second)->data_msg->sender == sender)
												inreadyqueue = true;
										}

										//if not in ready queue or delivered
										if(delivered == false && inreadyqueue == false)
										{
												//Send Ack
												AckMessage* ack_mesg = (AckMessage*)malloc(sizeof(AckMessage));
												ack_mesg->type = TYPE_ACK;
												ack_mesg->sender = hostname_to_id[myhostname_str];
												ack_mesg->msg_id = msg_id;
												ack_mesg->proposed_seq = ++max_last_proposed_seq_num;
												ack_mesg->receiver = sender;
														
												host_network(ack_mesg);		

												//Send ack to the sender
												string ip = string(inet_ntoa(cliaddr.sin_addr));
												cliaddr.sin_family = AF_INET;
												cliaddr.sin_addr.s_addr = inet_addr(ip.c_str());
												cliaddr.sin_port = htons(port);
												int rval = sendto(sockfd,ack_mesg,sizeof(AckMessage),0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));								
												kprintf("Sent Ack to ",ip.c_str());
			
												//Store in Queue ********************
												string current_hostname;

												for(map<string,string>:: iterator it=host_to_id.begin(); it!=host_to_id.end(); it++)
												{
													if((it->second).compare(ip) == 0)
														current_hostname = it->first;
												}
												
												DataMessage *init_dm = (DataMessage *)malloc(sizeof(DataMessage));
												init_dm->type = TYPE_DM;
												init_dm->sender = hostname_to_id[current_hostname];
												init_dm->msg_id = msg_id;
												init_dm->data = dm_mesg->data;											

											
												DM* sent_msg = (DM*)malloc(sizeof(DM));
												sent_msg->deliverable = false;
												sent_msg->seq_num = max_last_proposed_seq_num;
												sent_msg->data_msg = init_dm;
												Key current_key (sent_msg->seq_num,hostname_to_id[current_hostname]);								
												last_proposed_seq_num = max_last_proposed_seq_num;

												//Add the sent message to your queue
												delivery_queue[current_key] = sent_msg;
												kprintf("Inserted in delivery queue",current_key.seq);
										}
									}
									else if(type == TYPE_SEQ_MSG)
									{
												SeqMessage* seq_mesg = (SeqMessage*)mesg;	
												
												network_host(seq_mesg);

												int msg_id = seq_mesg->msg_id;
												int sender = seq_mesg->sender;

												//Search in delivery queue for the corresponding message
												for(map<Key,DM*>:: iterator it=delivery_queue.begin();it!=delivery_queue.end();it++)
												{
													if((it->second)->data_msg->msg_id == msg_id && (it->second)->data_msg->sender == sender)
														{
															(it->second)->deliverable = true;
															(it->second)->seq_num = seq_mesg->final_seq;
														}
												}
												max_last_proposed_seq_num = seq_mesg->final_seq;
												deliver_messages(&delivery_queue,&delivered_queue,hostname_to_id[myhostname_str]);
												kprintf("Got final seq message", seq_mesg->msg_id);

									}						
								}

					 }
												 

					//go for next message
					if(check(host_retransmit_info))
					{
													kprintf("After check");

													//Get the maximum sequence number recieved
													int max = *(ackmultiset.rbegin());

													kprintf("Max is",max);

													//Update the max proposed seq num for next message
													if(max_last_proposed_seq_num < max)
														max_last_proposed_seq_num = max;

													//Build the final seq message
													SeqMessage* final_seq_msg = (SeqMessage *)malloc(sizeof(SeqMessage));
													final_seq_msg->type = TYPE_SEQ_MSG;
													final_seq_msg->sender = hostname_to_id[myhostname_str];
													final_seq_msg->msg_id = iter;
													final_seq_msg->final_seq = max;

													host_network(final_seq_msg);

													//send it to everyone
													for(map<string,string>::iterator it	=	host_to_id.begin();it	!= host_to_id.end();++it)
													{
															if(myhostname_str.compare(it->first) !=0)
															{
																cliaddr.sin_family = AF_INET;
																cliaddr.sin_addr.s_addr = inet_addr(it->second.c_str());
																cliaddr.sin_port = htons(port);
																int rval = sendto(sockfd,final_seq_msg,sizeof(SeqMessage),0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));								
																kprintf("Sent final sequence message ",it->second.c_str());
															}
													}
													
												int msg_id_srch = iter;
												int sender = hostname_to_id[myhostname_str];

												//update the message in delivery queue with the final sequence number
												for(map<Key,DM*>:: iterator it = delivery_queue.begin();it != delivery_queue.end();++it)
												{
														if(it->second->data_msg->sender == sender && it->second->data_msg->msg_id == msg_id_srch)
														{

															//Prepare new message
															DM* updatedDM = (DM*)malloc(sizeof(DM));	
															updatedDM->data_msg = it->second->data_msg;
															updatedDM->deliverable = true;
															updatedDM->seq_num = max;
														
															//erase the old msg
															delivery_queue.erase(it);
															
															//Prepare new key
															Key updated_key(max,sender);

															//Update queue
															delivery_queue[updated_key] = updatedDM;

															kprintf("Found the message and marked deliverable and updated sequence number too",updatedDM->seq_num);

														}
												}
												
					//deliver messages
					deliver_messages(&delivery_queue,&delivered_queue,hostname_to_id[myhostname_str]);
		
					iter++;	
					//Reinitialize for new message
					host_retransmit_info = reinit(host_retransmit_info,host_to_id[myhostname_str]);

					//Reinitialize ack multiset
					ackmultiset = reinit_set(ackmultiset);
				}
	

				
			}

}
Exemplo n.º 16
0
void*
capture_multiple_images (void* data)
{
	capture_multiple_images_data_t* cmid = (capture_multiple_images_data_t *) data;
	std::list<Magick::Image> image_list;
	pid_t pid = getpid ();
	gint64 start, previous, current, elapsed, next;
	const gint64 ticks_in_ms = 10000;
	const gchar *tmp_dir = g_get_tmp_dir ();
	gchar *pid_dir = g_strdup_printf ("%i", pid);
	gchar *image_dir = g_build_filename (tmp_dir, "moonlight-test-harness", pid_dir, NULL);
	gchar **image_paths = (gchar **) g_malloc0 (sizeof (gchar *) * (cmid->count + 1));
	gchar **image_files = (gchar **) g_malloc0 (sizeof (gchar *) * (cmid->count + 1));
	
	LOG_CAPTURE ("Moonlight harness: Capture %i screenshots, initial delay: %i ms, interval: %i ms, width: %i, height: %i\n", cmid->count, cmid->initial_delay, cmid->interval, cmid->width, cmid->height);
	
	usleep (cmid->initial_delay * 1000);

	g_mkdir_with_parents (image_dir, 0700);

	ScreenCaptureData sc (cmid->x, cmid->y, cmid->width, cmid->height);
	
	start = get_now () / ticks_in_ms;
	for (int i = 0; i < cmid->count; i++) {
		image_files [i] = g_strdup_printf ("multilayered-image-%03i.png", i);
		image_paths [i] = g_build_filename (image_dir, image_files [i], NULL);

		// printf (" Capturing screenshot #%2i into %s", i + 1, image_paths [i]);
		previous = get_now () / ticks_in_ms;
		
		sc.Capture (image_paths [i]);
		
		current = get_now () / ticks_in_ms;
		elapsed = current - start;
		next = (start + cmid->interval * (i + 1)) - current;
		if (next <= 0) {
			next = cmid->interval;
			if (current - previous > cmid->interval)
				printf ("\nMoonlight harness: Screen capture can't capture fast enough. Interval %" G_GINT64_FORMAT " ms, time spent taking screenshot: %" G_GINT64_FORMAT " ms\n", (gint64) cmid->interval, (gint64) current - previous);
		}
		
		LOG_CAPTURE (" Done in %4" G_GINT64_FORMAT " ms, elapsed: %4" G_GINT64_FORMAT " ms, sleeping %4" G_GINT64_FORMAT " ms\n", current - previous, elapsed, next);
		
		usleep (next * 1000);
	}
	try {
		for (int i = 0; i < cmid->count; i++) {
			Magick::Image image;
			image.read (image_paths [i]);
			image_list.push_front (image);
		}
		Magick::writeImages (image_list.begin (), image_list.end (), cmid->image_path);
	} catch (Magick::Exception & error) {
		// Don't crash if imagemagick freaks out
		printf ("Moonlight harness: ImageMagick threw an exception: %s\n", error.what ());
	}
	// Cleanup after us
	for (int i = 0; i < cmid->count; i++) {
		unlink (image_paths [i]);
	}
	rmdir (image_dir);	
	g_strfreev (image_paths);
	g_strfreev (image_files);
	g_free (pid_dir);
	g_free (image_dir);
	
	capture_multiple_images_data_free (cmid);
	shutdown_manager_wait_decrement ();

	LOG_CAPTURE ("Moonlight harness: Capture %i screenshots [Done]\n", cmid->count);

	return NULL;
}
Exemplo n.º 17
0
int ast_jb_put(struct ast_channel *chan, struct ast_frame *f)
{
	struct ast_jb *jb = ast_channel_jb(chan);
	const struct ast_jb_impl *jbimpl = jb->impl;
	void *jbobj = jb->jbobj;
	struct ast_frame *frr;
	long now = 0;

	if (!ast_test_flag(jb, JB_USE))
		return -1;

	if (f->frametype != AST_FRAME_VOICE) {
		if (f->frametype == AST_FRAME_DTMF && ast_test_flag(jb, JB_CREATED)) {
			jb_framelog("JB_PUT {now=%ld}: Received DTMF frame. Force resynching jb...\n", now);
			jbimpl->force_resync(jbobj);
		}

		return -1;
	}

	/* We consider an enabled jitterbuffer should receive frames with valid timing info. */
	if (!ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO) || f->len < 2 || f->ts < 0) {
		ast_log(LOG_WARNING, "%s received frame with invalid timing info: "
			"has_timing_info=%d, len=%ld, ts=%ld, src=%s\n",
			ast_channel_name(chan), ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO), f->len, f->ts, f->src);
		return -1;
	}

	frr = ast_frdup(f);

	if (!frr) {
		ast_log(LOG_ERROR, "Failed to isolate frame for the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
		return -1;
	}

	if (!ast_test_flag(jb, JB_CREATED)) {
		if (create_jb(chan, frr)) {
			ast_frfree(frr);
			/* Disable the jitterbuffer */
			ast_clear_flag(jb, JB_USE);
			return -1;
		}

		ast_set_flag(jb, JB_CREATED);
		return 0;
	} else {
		now = get_now(jb, NULL);
		if (jbimpl->put(jbobj, frr, now) != AST_JB_IMPL_OK) {
			jb_framelog("JB_PUT {now=%ld}: Dropped frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);
			ast_frfree(frr);
			/*return -1;*/
			/* TODO: Check this fix - should return 0 here, because the dropped frame shouldn't
			   be delivered at all */
			return 0;
		}

		jb->next = jbimpl->next(jbobj);

		jb_framelog("JB_PUT {now=%ld}: Queued frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);

		return 0;
	}
}
Exemplo n.º 18
0
void Client::idle() throw (Exception) {
    /* process net io */
    bool queue_empty = true;
    do {
        ServerEvent evt;
        {
            Scope<Mutex> lock(mtx);
            if (server_events.empty()) {
                break;
            }
            evt = server_events.front();
            server_events.pop();
            queue_empty = server_events.empty();
        }
        switch (evt.event) {
            case EventTypeStatus:
            {
                std::string msg(evt.data, evt.sz);
                subsystem << msg << std::endl;
                break;
            }

            case EventTypeAccessDenied:
            {
                stop_thread();
                exception_msg.assign(evt.data, evt.sz);
                throw_exception = true;
                break;
            }

            case EventTypeLogin:
            {
                sevt_login(evt);
                break;
            }

            case EventTypeLogout:
            {
                stop_thread();
                logged_in = false;
                conn = 0;
                exception_msg.assign(evt.data, evt.sz);
                throw_exception = true;
                break;
            }

            case EventTypeData:
                sevt_data(evt);
                break;
        }
        if (evt.data) {
            delete[] evt.data;
        }
    } while (!queue_empty && !throw_exception);

    /* have to throw an exception? */
    if (throw_exception) {
        throw ClientException(exception_msg);
    }

    /* interpolate movements */
    get_now(now);
    ns_t diff = diff_ns(last, now);

    last = now;

    if (tournament) {
        tournament->update_states(diff);
        if (conn) {
            tournament->set_ping_time(conn->ping_time);
            Tournament::StateResponses& responses = tournament->get_state_responses();
            size_t sz = responses.size();
            {
                Scope<Mutex> lock(mtx);
                for (size_t i = 0; i < sz; i++) {
                    StateResponse *resp = responses[i];
                    if (resp->action == GPCTextMessage) {
                        std::string msg(reinterpret_cast<const char *>(resp->data), resp->len);
                        add_text_msg(msg);
                    } else {
                        stacked_send_data(conn, factory.get_tournament_id(), resp->action, 0, resp->len, resp->data);
                    }
                }
                flush_stacked_send_data(conn, 0);
            }
        }
        tournament->delete_responses();

        /* send player position (unreliable) */
        updatecnt += diff;
        bool player_force = false;
        if (me && me->force_broadcast) {
            player_force = true;
            me->force_broadcast = false;
            me->state.client_server_state.flags |= PlayerClientServerFlagForceBroadcast;
        }
        if (updatecnt >= UpdatePeriod || force_send || player_force) {
            updatecnt = 0;
            if (conn && me && tournament->is_ready()) {
                GPlayerClientServerState state;
                state = me->state.client_server_state;
                state.to_net();
                {
                    Scope<Mutex> lock(mtx);
                    send_data(conn, factory.get_tournament_id(), GPSUpdatePlayerClientServerState, 0, GPlayerClientServerStateLen, &state);
                }
                me->state.client_server_state.flags &= ~PlayerClientServerFlagForceBroadcast;
            }
        }
    }

    /* interpolate messages */
    for (TextMessages::iterator it = text_messages.begin();
        it != text_messages.end(); it++)
    {
        TextMessage *cmsg = *it;
        cmsg->duration += (diff / 1000000.0f);
        if (cmsg->duration > text_message_duration) {
            cmsg->delete_me = true;
        }
    }
    text_messages.erase(std::remove_if(text_messages.begin(),
        text_messages.end(), erase_element<TextMessage>),
        text_messages.end());

    /* player in options or in chatbox? */
    if (me) {
        if (get_stack_count()) {
            me->state.client_server_state.flags |= PlayerClientServerFlagWriting;
        } else {
            me->state.client_server_state.flags &= ~PlayerClientServerFlagWriting;
        }
    }

    /* draw map */
    if (tournament) {
        tournament->draw();
    }

    /* draw messages */
    Font *font = resources.get_font("normal");
    int view_height = subsystem.get_view_height();
    int font_height = font->get_font_height();
    int y = view_height - font_height - 5;
    for (TextMessages::reverse_iterator it = text_messages.rbegin();
        it != text_messages.rend(); it++)
    {
        TextMessage *cmsg = *it;
        float alpha = 1.0f;
        if (cmsg->duration > text_message_fade_out_at) {
            alpha = static_cast<float>((text_message_duration - cmsg->duration) / (text_message_duration - text_message_fade_out_at));
        }

        subsystem.set_color(0.75f, 0.75f, 1.0f, alpha);
        subsystem.draw_text(font, 5, y, cmsg->text);
        alpha *= 0.9f;
        y -= font_height;
    }
    subsystem.reset_color();

    /* draw file transfer status */
    if (fhnd) {
        Font *big = resources.get_font("big");
        int percent = 100 - static_cast<int>(100.0f / static_cast<float>(total_xfer_sz) * remaining_xfer_sz);
        sprintf(buffer, "transferring %s (%d%%)", xfer_filename.c_str(), percent);
        int tw = big->get_text_width(buffer);
        subsystem.draw_text(big, subsystem.get_view_width() / 2 - tw / 2, view_height - 30, buffer);
    }
}
Exemplo n.º 19
0
static int create_jb(struct ast_channel *chan, struct ast_frame *frr)
{
	struct ast_jb *jb = ast_channel_jb(chan);
	struct ast_jb_conf *jbconf = &jb->conf;
	const struct ast_jb_impl *jbimpl = jb->impl;
	void *jbobj;
	struct ast_channel *bridged;
	long now;
	char logfile_pathname[20 + AST_JB_IMPL_NAME_SIZE + 2*AST_CHANNEL_NAME + 1];
	char name1[AST_CHANNEL_NAME], name2[AST_CHANNEL_NAME], *tmp;
	int res;

	jbobj = jb->jbobj = jbimpl->create(jbconf, jbconf->resync_threshold);
	if (!jbobj) {
		ast_log(LOG_WARNING, "Failed to create jitterbuffer on channel '%s'\n", ast_channel_name(chan));
		return -1;
	}

	now = get_now(jb, NULL);
	res = jbimpl->put_first(jbobj, frr, now);

	/* The result of putting the first frame should not differ from OK. However, its possible
	   some implementations (i.e. adaptive's when resynch_threshold is specified) to drop it. */
	if (res != AST_JB_IMPL_OK) {
		ast_log(LOG_WARNING, "Failed to put first frame in the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
		/*
		jbimpl->destroy(jbobj);
		return -1;
		*/
	}

	/* Init next */
	jb->next = jbimpl->next(jbobj);

	/* Init last format for a first time. */
	ast_format_copy(&jb->last_format, &frr->subclass.format);

	/* Create a frame log file */
	if (ast_test_flag(jbconf, AST_JB_LOG)) {
		char safe_logfile[30] = "/tmp/logfile-XXXXXX";
		int safe_fd;
		snprintf(name2, sizeof(name2), "%s", ast_channel_name(chan));
		if ((tmp = strchr(name2, '/'))) {
			*tmp = '#';
		}

		bridged = ast_bridged_channel(chan);
		/* We should always have bridged chan if a jitterbuffer is in use */
		ast_assert(bridged != NULL);

		snprintf(name1, sizeof(name1), "%s", ast_channel_name(bridged));
		if ((tmp = strchr(name1, '/'))) {
			*tmp = '#';
		}

		snprintf(logfile_pathname, sizeof(logfile_pathname),
			"/tmp/ast_%s_jb_%s--%s.log", jbimpl->name, name1, name2);
		unlink(logfile_pathname);
		safe_fd = mkstemp(safe_logfile);
		if (safe_fd < 0 || link(safe_logfile, logfile_pathname) || unlink(safe_logfile) || !(jb->logfile = fdopen(safe_fd, "w+b"))) {
			ast_log(LOG_ERROR, "Failed to create frame log file with pathname '%s': %s\n", logfile_pathname, strerror(errno));
			jb->logfile = NULL;
			if (safe_fd > -1) {
				close(safe_fd);
			}
		}

		if (res == AST_JB_IMPL_OK) {
			jb_framelog("JB_PUT_FIRST {now=%ld}: Queued frame with ts=%ld and len=%ld\n",
				now, frr->ts, frr->len);
		} else {
			jb_framelog("JB_PUT_FIRST {now=%ld}: Dropped frame with ts=%ld and len=%ld\n",
				now, frr->ts, frr->len);
		}
	}

	ast_verb(3, "%s jitterbuffer created on channel %s\n", jbimpl->name, ast_channel_name(chan));

	/* Free the frame if it has not been queued in the jb */
	if (res != AST_JB_IMPL_OK) {
		ast_frfree(frr);
	}

	return 0;
}
Exemplo n.º 20
0
// <@$M_{t1}$@> module
void acq () {
  uint myt = FAI_ticket();
  while(get_now()!=myt){};
  hold_lock();
}
Exemplo n.º 21
0
void benchcore(const char *host,const int port,const char *req) {
    int     rlen;
    char    buf[1500], readflag;
    int     s,i, success;
    struct  sigaction sa;
    ull     start, end;
    long    recv_byte;
    FILE*   f;

    /* setup alarm signal handler */
    sa.sa_handler=alarm_handler;
    sa.sa_flags=0;
    if(sigaction(SIGALRM,&sa,NULL))
        exit(3);
    alarm(benchtime);

    rlen=strlen(req);
    f=fdopen(mypipe[1],"w"); /* open pipe to write data*/

    while(1) {
        if(timerexpired) {
            if(failed>0) {
                failed--;
            }
            break;
        }
        start     = get_now();
        recv_byte = 0;
        success   = 0;
        readflag  = 0;
        s=Socket(host,port);
        if(s<0) {
            failed++;
            goto writelog;
        }
        if(rlen!=write(s,req,rlen)) {
            failed++;
            close(s);
            goto writelog;
        }
        if(http10==0)
            if(shutdown(s,1)) {
                failed++;
                close(s);
                goto writelog;
            }
        if(force==0) {
            /* read all available data from socket */
            do {
                if(timerexpired) break;
                i = read(s,buf,1500);
                /* fprintf(stderr,"%s\n", buf);  */
                if(i < 0) {
                    failed++;
                    close(s);
                    goto writelog;
                } else {
                    if(i==0) break;
                    else {
                        if (!readflag) {
                            readflag = 1;
                            buf[8] = 0;
                            if(!strcmp(buf, HTTP_HEADER)) {
                                if(buf[9] < '4') {
                                    success = 1;
                                }
                            }
                        }
                        bytes+=i;
                        recv_byte += i;
                    }
                }
            } while(1);
        }
        if(close(s)) {
            failed++;
            goto writelog;
        }
        speed++;
writelog: {
            end = get_now();
            /* Ignore error caused by signal. */
            if (!timerexpired) 
                fprintf(f, "%d %ld %d\n", success, recv_byte, (int)(end - start));
        }
    }
    fprintf(f, "-1 0 0\n");
    fclose(f);
}
Exemplo n.º 22
0
Arquivo: main.cpp Projeto: SanHot/snet
void callback(const HttpRequest* req, HttpResponse* res) {
    Buffer content;
    ServerInfo svr_info;
    StatementsInfo smt_info;

    if (req->path() == "/") {
            res->setStatusCode(HttpResponse::HTTP_OK);
            res->setContentType(CONTEXT_TYPE_HTML);
            res->addHeader("Server", JOINTCOM_FLAG);
            char date[128] = {0};
            get_now(date);
            res->setBody("<html><head><title>JOINTCOM</title></head>"
                                 "<body><h1>Welcom to JOINTCOM</h1>Now is " + std::string(date) +
                         "</body></html>");
    }
    else if (readUrlConfig(req->method(), req->path(), svr_info, smt_info) != -1) {
        if (req->method() == HTTP_GET || req->method() == HTTP_DELETE) {
            if(smt_info.param_count > 0) {
                //固定参数
                //固定参数需匹配参数数量,不匹配时返回404
                if(smt_info.param_count != req->query_param().size()) {
                    res->setHttp404Status("Query-Param error!");
                    return;
                }
                auto it = req->query_param().begin();
                for (int i = 0; i < smt_info.param_count; i++) {
                    auto n = smt_info.sql.find_first_of('?');
                    if (n != std::string::npos) {
                        smt_info.sql.replace(n, 1, it->first);
                        it++;
                    }
                }
            }
            else if (smt_info.param_count == 0 && req->query_param().size() > 0) {
                //自由参数
                auto it = req->query_param().begin();
                std::string temp = " where ";
                for (int i = 0; i < req->query_param().size(); i++) {
                    temp += "[";
                    temp += it->first;
                    temp += "] = '";
                    temp += it->second;
                    temp += "'";
                    if (i != req->query_param().size() - 1) {
                        temp += " and ";
                        it++;
                    }
                }
                smt_info.sql += temp;
            }
            else if(smt_info.param_count == 0 && req->query_param().size() == 0 && req->method() == HTTP_DELETE) {
                //删除方法的参数不允许参数为0, 返回404
                res->setHttp404Status("Delete-Param error!");
                return;
            }
        }
        else if(req->method() == HTTP_POST) {
            std::string body = req->body();
            std::string sql = "";
            std::vector<std::string> vec = split_string(body, "\n");
            for(auto it = vec.begin(); it != vec.end(); it++) {
                std::string val = *it;
                if(val == "") continue;
                std::string temp = smt_info.sql;
                auto n = temp.find_first_of('?');
                if (n != std::string::npos)
                    temp.replace(n, 1, val.c_str());
                else {
                    res->setHttp404Status("Config-Sql error!");
                    return;
                }
                sql += temp + "\n";
            }
            smt_info.sql = sql;
        }

        std::string content_type(CONTEXT_TYPE_PLAIN);
        int ret = db_odbc_exec(svr_info, smt_info, &content, content_type);
        if (ret == -1) {
            res->setHttp404Status(content.buffer());
            return;
        }
        res->setStatusCode(HttpResponse::HTTP_OK);
        res->setContentType(content_type);
        res->addHeader("Server", JOINTCOM_FLAG);
        res->setBody(content.buffer());
    }
    else {
            res->setHttp404Status();
    }
}
Exemplo n.º 23
0
void log_event_now(const char *log_name, const char *event) {
    log_event(log_name, get_now(), event);
}
Exemplo n.º 24
0
TimeSpan
SystemTimeSource::GetNow ()
{
	return get_now ();
}
Exemplo n.º 25
0
int ndpi_add_to_lru_cache_str_timeout(struct ndpi_LruCache *cache,
				     char *key, char *value,
				     u_int32_t timeout) {
  if(cache->hash_size == 0)
    return(0);
  else {
    u_int32_t hash_val =  lru_hash_string(key);
    u_int32_t hash_id = hash_val % cache->hash_size;
    struct ndpi_LruCacheEntry *node;
    u_int8_t node_already_existing = 0;
    int rc = 0;

    if(unlikely(traceLRU))
      printf("%s(key=%s, value=%s)", __FUNCTION__, key, value);

    // validate_unit_len(cache, hash_id);
    cache->num_cache_add++;

    /* [1] Add to hash */
    if(cache->hash[hash_id] == NULL) {
      if((node = lru_allocCacheStringNode(cache, key, value, timeout)) == NULL) {
	rc = -1;
	goto ret_add_to_lru_cache;
      }

      cache->hash[hash_id] = node;
      cache->current_hash_size[hash_id]++;
    } else {
      /* Check if the element exists */
      struct ndpi_LruCacheEntry *head = cache->hash[hash_id];

      while(head != NULL) {
	if(strcmp(head->u.str.key, key) == 0) {
	  /* Duplicated key found */
	  node = head;
	  if(node->u.str.value) {
#ifdef FULL_STATS
	    cache->mem_size -= strlen(node->u.str.value);
#endif
	    ndpi_free(node->u.str.value);
	  }

	  node->u.str.value = ndpi_strdup(value); /* Overwrite old value */
#ifdef FULL_STATS
	  cache->mem_size += strlen(value);
#endif

	  node->u.str.expire_time = (timeout == 0) ? 0 : (compute_timeout(timeout) + get_now());
	  node_already_existing = 1;
	  break;
	} else
	  head = head->next;
      }

      if(!node_already_existing) {
	if((node = lru_allocCacheStringNode(cache, key, value, timeout)) == NULL) {
	  rc = -2;
	  goto ret_add_to_lru_cache;
	}

	node->next = cache->hash[hash_id];
	cache->hash[hash_id] = node;
	cache->current_hash_size[hash_id]++;
      }
    }

    trim_subhash(cache, hash_id);

    // validate_unit_len(cache, hash_id);

  ret_add_to_lru_cache:
    return(rc);
  }
}
Exemplo n.º 26
0
/*! \brief Handle connection coming data and timeout of timers.
 *
 */
static void
_cons_supp_event_loop(mb_rt_t *rt) {
    struct _cons_supp_runtime *cmb_rt = (struct _cons_supp_runtime *)rt;
    struct _cons_supp_IO_man *io_man =
	(struct _cons_supp_IO_man *)cmb_rt->io_man;
    mb_timer_man_t *timer_man = (mb_timer_man_t *)cmb_rt->timer_man;
    redraw_man_t *rdman;
    mb_tman_t *tman = tman_timer_man_get_tman(timer_man);
    mb_timeval_t now, tmo;
    struct timeval tv;
    fd_set rfds, wfds;
    int nfds = 0;
    int r, r1,i;

    rdman = mb_runtime_rdman(rt);
    rdman_redraw_all(rdman);
    
    _cons_supp_handle_cons_event(cmb_rt);

    while(1) {
	FD_ZERO(&rfds);
	FD_ZERO(&wfds);
        for(i = 0; i < io_man->n_monitor; i++) {
	    if(io_man->monitors[i].type == MB_IO_R ||
	       io_man->monitors[i].type == MB_IO_RW) {
		FD_SET(io_man->monitors[i].fd, &rfds);
		nfds = MB_MAX(nfds, io_man->monitors[i].fd + 1);
	    }
	    if(io_man->monitors[i].type == MB_IO_W ||
	       io_man->monitors[i].type == MB_IO_RW) {
		FD_SET(io_man->monitors[i].fd, &wfds);
		nfds = MB_MAX(nfds, io_man->monitors[i].fd + 1);
	    }
        }

	get_now(&now);
	r = mb_tman_next_timeout(tman, &now, &tmo);

	if(r == 0) {
	    tv.tv_sec = MB_TIMEVAL_SEC(&tmo);
	    tv.tv_usec = MB_TIMEVAL_USEC(&tmo);
	    r1 = select(nfds, &rfds, NULL, NULL, &tv);
	} else
	    r1 = select(nfds, &rfds, NULL, NULL, NULL);

	if(r1 == -1) {
	    perror("select");
	    break;
	}

	if(r1 == 0) {
	    get_now(&now);
	    mb_tman_handle_timeout(tman, &now);
	    rdman_redraw_changed(rdman);
	} else {
            for(i = 0; i < io_man->n_monitor; i++) {
	        if(io_man->monitors[i].type == MB_IO_R ||
		   io_man->monitors[i].type == MB_IO_RW) {
		    if(FD_ISSET(io_man->monitors[i].fd, &rfds))
		    	io_man->monitors[i].cb(i, io_man->monitors[i].fd,
					       MB_IO_R,
					       io_man->monitors[i].data);
		}
		if(io_man->monitors[i].type == MB_IO_W ||
		   io_man->monitors[i].type == MB_IO_RW) {
		    if(FD_ISSET(io_man->monitors[i].fd, &wfds))
			io_man->monitors[i].cb(i, io_man->monitors[i].fd,
					       MB_IO_W,
					       io_man->monitors[i].data);
		}
            }
	}
    }
}
Exemplo n.º 27
0
int main(int argc, char **argv) {
  char *username = NULL;
  int rc;
  char buf[BUFSIZE];
  int nRead, nWrite;
  time_t now;

  pthread_attr_t *tha = NULL;
  pthread_t tid;

  char *m_cmd = strrchr(argv[0], '/');

  if(m_cmd == NULL) {
    m_cmd = argv[0];
  } else {
    m_cmd++;
  }
  
  while(argc >= 1) {
    if(strcmp(*argv,"-o") == 0) {
      if (--argc >= 1) {
	m_file_name = *(++argv);
      }
    } else if(strcmp(*argv,"-u") == 0) {
      if (--argc >= 1) {
	username = *(++argv);
      }
    } else if(strcmp(*argv,"-s") == 0) {
      if (--argc >= 1) {
	m_tRotation = atoi(*(++argv));
      } 
    } else if(strcmp(*argv,"-t") == 0) {
      if (--argc >= 1) {
	m_offset = atoi(*(++argv));
	m_offset = m_offset * 3600;
	m_offset_enabled = 1;
      } 
    } else if(strcmp(*argv,"-g") == 0) {
      if (--argc >= 1) {
	m_generations = atoi(*(++argv));
      } 
    } else if(strcmp(*argv,"-b") == 0) {
      if (--argc >= 1) {
	m_limit = atoi(*(++argv));
      } 
    } else if(strcmp(*argv,"-z") == 0) {
      m_compress = 1;
    } else if(strcmp(*argv,"-p") == 0) {
      m_stdout = 1;
    } else if(strcmp(*argv,"-f") == 0) {
      m_force_rotation = 1;
    } else if(strcmp(*argv,"-h") == 0) {
      usage(m_cmd, 0);
    } else if(strcmp(*argv,"--help") == 0) {
      usage(m_cmd, 0);
    } else if(strcmp(*argv,"-?") == 0) {
      usage(m_cmd, 0);
    } else if(strcmp(*argv,"--man") == 0) {
      usage(m_cmd, 1);
    }

    argc--;
    argv++;
  }

  if(m_file_name == NULL) usage(m_cmd, 0);
  if(m_limit < (1024 * 1024)) usage(m_cmd, 0);

  if(username && getuid() == 0) {
    struct passwd *pwd = getpwnam(username);
    uid_t uid, gid;
    if(pwd == NULL) {
      fprintf(stderr,"[%s]: ERROR, unknown user id %s\n", m_cmd, username);
      exit(1);
    }
    uid = pwd->pw_uid;
    gid = pwd->pw_gid;
    setgid(gid);
    setuid(uid);
    if(getuid() != uid) {
      fprintf(stderr,"[%s]: ERROR, setuid failed (%s,%d)\n", m_cmd, username, uid);
      exit(1);
    }
    if(getgid() != gid) {
      fprintf(stderr,"[%s]: ERROR, setgid failed (%d)\n", m_cmd, gid);
      exit(1);
    }
  }
  
  /* set next rotation time */
  now = get_now();
  m_tLogEnd = ((now / m_tRotation) * m_tRotation) + m_tRotation;
  /* open file */
  m_nLogFD = openFile(m_cmd, m_file_name);
  if(m_nLogFD < 0) {
    /* startup did not success */
    exit(2);
  }

  if(m_force_rotation) {
    qs_csInitLock();
    pthread_create(&tid, tha, forcedRotationThread, NULL);
  }

  for(;;) {
    nRead = read(0, buf, sizeof buf);
    if(nRead == 0) exit(3);
    if(nRead < 0) if(errno != EINTR) exit(4);
    if(m_force_rotation) {
      qs_csLock();
    }
    m_counter += nRead;
    now = get_now();
    /* write data if we have a file handle (else continue but drop log data,
       re-try to open the file at next rotation time) */
    if(m_nLogFD >= 0) {
      do {
	nWrite = write(m_nLogFD, buf, nRead);
	if(m_stdout) {
	  printf("%.*s", nRead, buf);
	}
      } while (nWrite < 0 && errno == EINTR);
    }
    if(nWrite != nRead) {
      m_messages++;
      if(m_nLogFD >= 0) {
	char msg[HUGE_STR];
	snprintf(msg, sizeof(msg), "ERROR while writing to file, %ld messages lost\n", m_messages);
	/* error while writing data, try to delete the old file and continue ... */
	rc = ftruncate(m_nLogFD, 0);
	rc = write(m_nLogFD, msg, strlen(msg));
      }
    } else {
      m_messages++;
    }
    if((now > m_tLogEnd) || (m_counter > m_limit)) {
      /* rotate! */
      rotate(m_cmd, now, m_file_name, &m_messages);
    }
    if(m_force_rotation) {
      qs_csUnLock();
    }
  }
  return 0;
}
Exemplo n.º 28
0
int main(int argc, char **argv){
	unsigned int i;
	char * ptr;

	unsigned int numthreads;

	global_data * global = new global_data;

	global->stats.starttime = get_now();

//2 queues
	global->request  = new tqueue<request_t>();
	global->response = new tqueue<request_t>();

//thread stuff
	pthread_t thread[MAX_THREADS];
	thread_data_t threaddata[MAX_THREADS];

//http server stuff
	struct evhttp *http;
	struct event updateEvent;


//notification fds
	int fds[2];

	srand(time(NULL));

	//defaults
	char port_def[] = "80";
	char hostname_def[] = "0.0.0.0";
	char threads_def[] = "3";
	char static_source_def[] = "pentagoo/";

	//Argument Pointers
	char *port_arg = port_def;
	char *hostname_arg = hostname_def;
	char *threads_arg = threads_def;
	char *static_source = static_source_def;


//Parse command line options
	for (i = 1; i < (unsigned int)argc; i++) {
		ptr = argv[i];
		if(strcmp(ptr, "--help") == 0){
			printf("Usage:\n"
				"\t--help        Show this help\n"
				"\t-l            Location for the web frontend [%s]\n"
				"\t-p            Port Number [%s]\n"
				"\t-h            Hostname [%s]\n"
				"\t-t            Number of threads [%s]\n\n",
				static_source_def, port_def, hostname_def, threads_def);
			exit(255);
		}else if (strcmp(ptr, "-p") == 0)
			port_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-h") == 0)
			hostname_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-t") == 0)
			threads_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-l") == 0)
			static_source = ptr = argv[++i];
	}


	global->static_source = static_source;

	numthreads = atoi(threads_arg);
	if(numthreads < 1)
		numthreads = 1;

	if(numthreads > MAX_THREADS){
		printf("Invalid number of threads '%s', setting to max threads %i\n", threads_arg, MAX_THREADS);
		numthreads = MAX_THREADS;
	}

//initialize update notification pipe
	socketpair(AF_UNIX, SOCK_STREAM, 0, fds);

	global->pushfd = fds[0];
	global->popfd = fds[1];


	printf("Starting %u computation threads\n", numthreads);

	for(i = 0; i < numthreads; i++){
		threaddata[i].threadid = i;
		threaddata[i].state = 1;
		threaddata[i].global = global;
		
		pthread_create(&thread[i], NULL, (void* (*)(void*)) requestRunner, (void*) &threaddata[i]);
	}


//init the event lib
	event_init();


	printf("Listening on %s:%s\n", hostname_arg, port_arg);

//start the http server
	http = evhttp_start(hostname_arg, atoi(port_arg));
	if(http == NULL) {
		printf("Couldn't start server on %s:%s\n", hostname_arg, port_arg);
		return 1;
	}


//Register a callback for requests
	evhttp_set_gencb(http, handle_http_static, global); //the generic catch all callback, used to serve static files
	evhttp_set_cb(http, "/ai",              handle_request_ai,       global); //my nice url
	evhttp_set_cb(http, "/pentagoo_ai.php", handle_request_ai,       global); //hijack the pentagoo url

	evhttp_set_cb(http, "/stats",    handle_request_stats,    global);

	event_set(& updateEvent, global->popfd, EV_READ|EV_PERSIST, handle_queue_response, global);
	event_add(& updateEvent, 0);


	printf("Starting event loop\n");

	event_dispatch();


	printf("Exiting\n");

	global->request->nonblock();
	for(i = 0; i < numthreads; i++)
		pthread_join(thread[i], NULL);

	return 0;
}
Exemplo n.º 29
0
#include <unistd.h>
#include <assert.h>
#include <sys/time.h>

volatile unsigned int AmSession::session_num = 0;
AmMutex AmSession::session_num_mut;
volatile unsigned int AmSession::max_session_num = 0;
volatile unsigned long long AmSession::avg_session_num = 0;

struct timeval get_now() {
  struct timeval res;
  gettimeofday(&res, NULL);
  return res;
}
struct timeval avg_last_timestamp = get_now();
struct timeval avg_first_timestamp = avg_last_timestamp;

// AmSession methods

AmSession::AmSession(AmSipDialog* p_dlg)
  : AmEventQueue(this), dlg(p_dlg),
    input(NULL), output(NULL),
    sess_stopped(false),
    m_dtmfDetector(this), m_dtmfEventQueue(&m_dtmfDetector),
    m_dtmfDetectionEnabled(true),
    accept_early_session(false),
    rtp_interface(-1),
    refresh_method(REFRESH_UPDATE_FB_REINV),
    processing_status(SESSION_PROCESSING_EVENTS)
#ifdef WITH_ZRTP
Exemplo n.º 30
0
int main( int argc, char *argv[] )
{
	PGconn *conn;
	const char *value;
	bool integer_datetimes;
	PGresult *res;
	uint64_t tmp;
	uint64_t param1;
	const char *values[1] = { (const char *)&param1 };
	int lengths[1] = { sizeof( param1 ) };
	int binary[1] = { 1 };
	struct timespec now;
	
	if( argc != 2 ) {
		fprintf( stderr, "usage: testpgsql <Pg conn info>\n" );
		return 1;
	}
	
	conn = PQconnectdb( argv[1] );
	if( PQstatus( conn ) != CONNECTION_OK ) {
		fprintf( stderr, "Connection to database failed: %s",
			PQerrorMessage( conn ) );
		PQfinish( conn );
		return 1;
	}
	
	value = PQparameterStatus( conn, "integer_datetimes" );
	if( value == NULL ) {
		fprintf( stderr, "PQ param integer_datetimes empty?\n" );
		PQfinish( conn );
		return 1;
	}
	
	integer_datetimes = strcmp( value, "on" ) == 0 ? true : false;
	printf( "integer_datetimes: %s\n", integer_datetimes ? "true" : "false" );

	now = get_now( );
	tmp = ( (uint64_t)now.tv_sec - POSTGRES_EPOCH_DATE ) * 1000000;
	tmp += now.tv_nsec / 1000;
	param1 = htobe64( tmp );
		
	res = PQexecParams( conn, "SELECT now(),$1::timestamp",
		1, NULL, values, lengths, binary, 1 );
	
	if( PQresultStatus( res ) != PGRES_TUPLES_OK ) {
		fprintf( stderr, "select error: %s\n", PQerrorMessage( conn ) );
		PQclear( res );
		PQfinish( conn );
		return 1;
	}
	
	if( PQntuples( res ) == 0 ) {
		PQclear( res );
		PQfinish( conn );
		return 1;
	}
	
	if( PQntuples( res ) > 1 ) {
		fprintf( stderr, "Expecting exactly one tuple as result." );
		PQclear( res );
		PQfinish( conn );
		return 1;
	}
		
	/* Since PostgreSQL 8.4 int64 representation should be the default
	 * unless changed at compilation time
	 */
	if( integer_datetimes ) {
		char *data_db;
		char *data_select;
		struct timespec time_db;
		struct timespec time_select;
		uint64_t t_db;
		uint64_t t_select;
		
		data_db = PQgetvalue( res, 0, 0 );
		
		t_db = be64toh( *( (uint64_t *)data_db ) );
		
		time_db.tv_sec = POSTGRES_EPOCH_DATE + t_db / 1000000;
		time_db.tv_nsec = ( t_db % 1000000 ) * 1000;

		data_select = PQgetvalue( res, 0, 1 );
		
		t_select = be64toh( *( (uint64_t *)data_select ) );
		
		time_select.tv_sec = POSTGRES_EPOCH_DATE + t_select / 1000000;
		time_select.tv_nsec = ( t_select % 1000000 ) * 1000;

		now = get_now( );
				
		printf( "now passed as param: %lu.%lu, now from database: %lu.%lu, now computed: %lu.%lu\n",
			time_select.tv_sec, time_select.tv_nsec, time_db.tv_sec, time_db.tv_nsec, now.tv_sec, now.tv_nsec );
	} else {
		/* doubles have no standard network representation! */
		fprintf( stderr, "Not supporting dates as doubles!\n" );
		PQclear( res );
		PQfinish( conn );
		return 1;
	}

	value = PQparameterStatus( conn, "client_encoding" );
	if( value == NULL ) {
		fprintf( stderr, "PQ param client_encoding empty?\n" );
		PQfinish( conn );
		return 1;
	}
	
	printf( "integer_datetimes: %s\n", value );

	PQfinish( conn );
	
	return 0;
}