/**
 * ido_location_menu_item_set_timezone:
 * @timezone: timezone identifier (eg: "America/Chicago")
 *
 * Set this location's timezone. This will be used to show the location's
 * current time in menuitem's right-justified secondary label.
 */
void
ido_location_menu_item_set_timezone (IdoLocationMenuItem   * self,
                                     const char            * timezone)
{
  priv_t * p;

  g_return_if_fail (IDO_IS_LOCATION_MENU_ITEM (self));
  p = self->priv;

  g_free (p->timezone);
  p->timezone = g_strdup (timezone);
  update_timestamp (self);
}
Exemple #2
0
/**
 * gst_adapter_flush:
 * @adapter: a #GstAdapter
 * @flush: the number of bytes to flush
 *
 * Flushes the first @flush bytes in the @adapter. The caller must ensure that
 * at least this many bytes are available.
 *
 * See also: gst_adapter_peek().
 */
static void
gst_adapter_flush_unchecked (GstAdapter * adapter, guint flush)
{
    GstBuffer *cur;
    guint size;
    GstAdapterPrivate *priv;
    GSList *g;

    GST_LOG_OBJECT (adapter, "flushing %u bytes", flush);

    priv = adapter->priv;

    /* clear state */
    adapter->size -= flush;
    adapter->assembled_len = 0;

    /* take skip into account */
    flush += adapter->skip;
    /* distance is always at least the amount of skipped bytes */
    priv->distance -= adapter->skip;

    g = adapter->buflist;
    cur = g->data;
    size = GST_BUFFER_SIZE (cur);
    while (flush >= size) {
        /* can skip whole buffer */
        GST_LOG_OBJECT (adapter, "flushing out head buffer");
        priv->distance += size;
        flush -= size;

        gst_buffer_unref (cur);
        g = g_slist_delete_link (g, g);

        if (G_UNLIKELY (g == NULL)) {
            GST_LOG_OBJECT (adapter, "adapter empty now");
            adapter->buflist_end = NULL;
            break;
        }
        /* there is a new head buffer, update the timestamp */
        cur = g->data;
        update_timestamp (adapter, cur);
        size = GST_BUFFER_SIZE (cur);
    }
    adapter->buflist = g;
    /* account for the remaining bytes */
    adapter->skip = flush;
    adapter->priv->distance += flush;
    /* invalidate scan position */
    priv->scan_offset = 0;
    priv->scan_entry = NULL;
}
Exemple #3
0
void recoder::add_enc_packet(const uint8_t *data, const uint16_t len)
{
    size_t tmp_rank;

    guard g(m_lock);

    /* don't add packets when we have enough, and try to stop encoder
     * from sending more packets
     */
    if (this->is_complete()) {
        send_ack_packet();
        return;
    }

    if (curr_state() == STATE_DONE)
        return;

    CHECK_EQ(len, this->payload_size()) << "Recoder " << m_coder
                                        << ": Encoded data is too short:"
                                        << len << " < " << this->payload_size();

    /* keep track of changes in rank */
    tmp_rank = this->rank();

    this->decode(const_cast<uint8_t *>(data));

    /* check if rank improved */
    if (this->rank() == tmp_rank)
        inc("non-innovative recoded packets");

    update_timestamp();

    if (this->last_symbol_is_systematic()) {
        inc("systematic packets added");
        send_systematic_packet(data, len);
        m_budget--;
    } else {
        inc("encoded packets added");
    }

    /* signal state machine if generation is complete */
    if (this->is_complete()) {
        send_ack_packet();
        dispatch_event(EVENT_COMPLETE);
    } else {
        dispatch_event(EVENT_RX);
    }

    VLOG(LOG_PKT) << "Recoder " << m_coder << ": Added encoded packet";
}
Exemple #4
0
static void revoke_eviction(UINT32 const page_idx)
{
	ASSERT(cached_pmt_timestamps[page_idx] == EVICTED_TIMESTAMP);
	ASSERT(merge_buf_size > 0);
	// find the evicted page in merge buf
	UINT8 sp_i;
	for (sp_i = 0; sp_i < merge_buf_size; sp_i++)
		if (merged_page_idxes[sp_i] == page_idx) break;
	ASSERT(sp_i != merge_buf_size);
	// remove the evicted page from merge buf
	merge_buf_size--;
	merged_page_idxes[sp_i] = merged_page_idxes[merge_buf_size];
	// change timestamp to normal
	update_timestamp(page_idx);
}
Exemple #5
0
/* execute rundll32 on the wine.inf file if necessary */
static void update_wineprefix( int force )
{
    const char *config_dir = wine_get_config_dir();
    char *inf_path = get_wine_inf_path();
    int fd;
    struct stat st;

    if (!inf_path)
    {
        WINE_MESSAGE( "wine: failed to update %s, wine.inf not found\n", config_dir );
        return;
    }
    if ((fd = open( inf_path, O_RDONLY )) == -1)
    {
        WINE_MESSAGE( "wine: failed to update %s with %s: %s\n",
                      config_dir, inf_path, strerror(errno) );
        goto done;
    }
    fstat( fd, &st );
    close( fd );

    if (update_timestamp( config_dir, st.st_mtime ) || force)
    {
        HANDLE process;
        DWORD count = 0;

        if ((process = start_rundll32( inf_path, FALSE )))
        {
            HWND hwnd = show_wait_window();
            for (;;)
            {
                MSG msg;
                DWORD res = MsgWaitForMultipleObjects( 1, &process, FALSE, INFINITE, QS_ALLINPUT );
                if (res == WAIT_OBJECT_0)
                {
                    CloseHandle( process );
                    if (count++ || !(process = start_rundll32( inf_path, TRUE ))) break;
                }
                else while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageW( &msg );
            }
            DestroyWindow( hwnd );
        }
        WINE_MESSAGE( "wine: configuration in '%s' has been updated.\n", config_dir );
    }

done:
    HeapFree( GetProcessHeap(), 0, inf_path );
}
/*
 * Returns true if the user successfully authenticates, false if not
 * or -1 on error.
 */
static int
check_user_interactive(int validated, int mode, struct passwd *auth_pw)
{
    int status, rval = true;
    debug_decl(check_user_interactive, SUDO_DEBUG_AUTH)

    /* Always need a password when -k was specified with the command. */
    if (ISSET(mode, MODE_IGNORE_TICKET))
	SET(validated, FLAG_CHECK_USER);

    if (build_timestamp(auth_pw) == -1) {
	rval = -1;
	goto done;
    }

    status = timestamp_status(auth_pw);

    if (status != TS_CURRENT || ISSET(validated, FLAG_CHECK_USER)) {
	char *prompt;
	bool lectured;

	/* Bail out if we are non-interactive and a password is required */
	if (ISSET(mode, MODE_NONINTERACTIVE)) {
	    validated |= FLAG_NON_INTERACTIVE;
	    log_auth_failure(validated, 0);
	    rval = -1;
	    goto done;
	}

	/* XXX - should not lecture if askpass helper is being used. */
	lectured = display_lecture(status);

	/* Expand any escapes in the prompt. */
	prompt = expand_prompt(user_prompt ? user_prompt : def_passprompt,
	    auth_pw->pw_name);

	rval = verify_user(auth_pw, prompt, validated);
	if (rval == true && lectured)
	    set_lectured();
	efree(prompt);
    }
    /* Only update timestamp if user was validated. */
    if (rval == true && ISSET(validated, VALIDATE_OK) &&
	!ISSET(mode, MODE_IGNORE_TICKET) && status != TS_ERROR)
	update_timestamp(auth_pw);
done:
    debug_return_bool(rval);
}
Exemple #7
0
static UINT32 get_page(UINT32 const pmt_idx)
{
	ASSERT(pmt_idx < PMT_SUB_PAGES);

	/* shortcuts for consecutive access of the same pmt_idx */
	if (last_pmt_idx == pmt_idx) return last_page_idx;

	UINT32 page_idx = mem_search_equ_sram(cached_pmt_idxes,
					       sizeof(UINT32),
					       NUM_PC_SUB_PAGES, pmt_idx);
	if (page_idx >= NUM_PC_SUB_PAGES) return NULL_PAGE_IDX;

	last_pmt_idx = pmt_idx;
	last_page_idx = page_idx;

	UINT32 timestamp = cached_pmt_timestamps[page_idx];
	if (timestamp == EVICTED_TIMESTAMP)
		revoke_eviction(page_idx);
	else if (timestamp < NULL_TIMESTAMP)
		update_timestamp(page_idx);

	return page_idx;
}
Exemple #8
0
/**
 * gst_adapter_push:
 * @adapter: a #GstAdapter
 * @buf: a #GstBuffer to add to queue in the adapter
 *
 * Adds the data from @buf to the data stored inside @adapter and takes
 * ownership of the buffer.
 */
void
gst_adapter_push (GstAdapter * adapter, GstBuffer * buf)
{
    guint size;

    g_return_if_fail (GST_IS_ADAPTER (adapter));
    g_return_if_fail (GST_IS_BUFFER (buf));

    size = GST_BUFFER_SIZE (buf);
    adapter->size += size;

    /* Note: merging buffers at this point is premature. */
    if (G_UNLIKELY (adapter->buflist == NULL)) {
        GST_LOG_OBJECT (adapter, "pushing first %u bytes", size);
        adapter->buflist = adapter->buflist_end = g_slist_append (NULL, buf);
        update_timestamp (adapter, buf);
    } else {
        /* Otherwise append to the end, and advance our end pointer */
        GST_LOG_OBJECT (adapter, "pushing %u bytes at end, size now %u", size,
                        adapter->size);
        adapter->buflist_end = g_slist_append (adapter->buflist_end, buf);
        adapter->buflist_end = g_slist_next (adapter->buflist_end);
    }
}
Exemple #9
0
void encoder::add_plain_packet(const uint8_t *data, const uint16_t len)
{
    uint8_t *buf;
    size_t size = this->symbol_size();

    CHECK_LE(len, size - LEN_SIZE) << "Encoder " << m_coder
                                   << ": Plain packet is too long: "
                                   << len << " > " << size - LEN_SIZE;

    guard g(m_lock);

    /* make sure encoder is in a state to accept plain packets */
    if (curr_state() != STATE_WAIT)
        return;

    buf = get_symbol_buffer(m_plain_pkt_count);
    *reinterpret_cast<uint16_t *>(buf) = len;
    memcpy(buf + LEN_SIZE, data, len);

    /* Copy data into encoder storage */
    sak::mutable_storage symbol(buf, this->symbol_size());
    this->set_symbol(m_plain_pkt_count++, symbol);

    update_timestamp();
    inc("plain packets added");
    VLOG(LOG_PKT) << "Encoder " << m_coder << ": Added plain packet";

    if (is_full()) {
        inc("generations");
        dispatch_event(EVENT_FULL);
    } else if (this->rank() > FLAGS_encoder_threshold*this->symbols() &&
               semaphore_count() > 0) {
        m_budget += recoder_credit(m_e1, m_e2, m_e3);
        send_encoded_credit();
    }
}
Exemple #10
0
/*
 * Returns true if the user successfully authenticates, false if not
 * or -1 on error.
 */
int
check_user(int validated, int mode)
{
    struct passwd *auth_pw;
    char *timestampdir = NULL;
    char *timestampfile = NULL;
    char *prompt;
    struct stat sb;
    int status, rval = true;
    debug_decl(check_user, SUDO_DEBUG_AUTH)

    /*
     * Init authentication system regardless of whether we need a password.
     * Required for proper PAM session support.
     */
    auth_pw = get_authpw();
    if (sudo_auth_init(auth_pw) == -1) {
	rval = -1;
	goto done;
    }

    /*
     * Don't prompt for the root passwd or if the user is exempt.
     * If the user is not changing uid/gid, no need for a password.
     */
    if (!def_authenticate || user_uid == 0 || user_is_exempt())
	goto done;
    if (user_uid == runas_pw->pw_uid &&
	(!runas_gr || user_in_group(sudo_user.pw, runas_gr->gr_name))) {
#ifdef HAVE_SELINUX
	if (user_role == NULL && user_type == NULL)
#endif
#ifdef HAVE_PRIV_SET
	if (runas_privs == NULL && runas_limitprivs == NULL)
#endif
	    goto done;
    }

    /* Always need a password when -k was specified with the command. */
    if (ISSET(mode, MODE_IGNORE_TICKET))
	SET(validated, FLAG_CHECK_USER);

    /* Stash the tty's ctime for tty ticket comparison. */
    if (def_tty_tickets && user_ttypath && stat(user_ttypath, &sb) == 0) {
	tty_info.dev = sb.st_dev;
	tty_info.ino = sb.st_ino;
	tty_info.rdev = sb.st_rdev;
	if (tty_is_devpts(user_ttypath))
	    ctim_get(&sb, &tty_info.ctime);
    }

    if (build_timestamp(&timestampdir, &timestampfile) == -1) {
	rval = -1;
	goto done;
    }

    status = timestamp_status(timestampdir, timestampfile, user_name,
	TS_MAKE_DIRS);

    if (status != TS_CURRENT || ISSET(validated, FLAG_CHECK_USER)) {
	/* Bail out if we are non-interactive and a password is required */
	if (ISSET(mode, MODE_NONINTERACTIVE)) {
	    validated |= FLAG_NON_INTERACTIVE;
	    log_auth_failure(validated, 0);
	    rval = -1;
	    goto done;
	}

	/* XXX - should not lecture if askpass helper is being used. */
	lecture(status);

	/* Expand any escapes in the prompt. */
	prompt = expand_prompt(user_prompt ? user_prompt : def_passprompt,
	    user_name, user_shost);

	rval = verify_user(auth_pw, prompt, validated);
    }
    /* Only update timestamp if user was validated. */
    if (rval == true && ISSET(validated, VALIDATE_OK) &&
	!ISSET(mode, MODE_IGNORE_TICKET) && status != TS_ERROR)
	update_timestamp(timestampdir, timestampfile);
    efree(timestampdir);
    efree(timestampfile);

done:
    sudo_auth_cleanup(auth_pw);
    sudo_pw_delref(auth_pw);

    debug_return_bool(rval);
}
Exemple #11
0
int main(int argc, char *argv[])
{
	unsigned long sleep_time;
	double read_interval;
	
	start_time = time(0);
	memset(&rtiming, 0, sizeof(rtiming));
	rtiming.rt_variance.v_min = FLT_MAX;

	/*
	 * Early initialization before reading config
	 */
	conf_init_pre();
	parse_args_pre(argc, argv);

	/*
	 * Reading the configuration file */
	configfile_read();

	/*
	 * Late initialization after reading config
	 */
	if (parse_args_post(argc, argv))
		return 1;
	conf_init_post();

	module_init();

	read_interval = cfg_read_interval;
	sleep_time = cfg_getint(cfg, "sleep_time");

	if (((double) sleep_time / 1000000.0f) > read_interval)
		sleep_time = (unsigned long) (read_interval * 1000000.0f);

	DBG("Entering mainloop...");

	do {
		/*
		 * E  := Elapsed time
		 * NR := Next Read
		 * LR := Last Read
		 * RI := Read Interval
		 * ST := Sleep Time
		 * C  := Correction
		 */
		timestamp_t e, ri, tmp;
		unsigned long st;

		float_to_timestamp(&ri, read_interval);

		/*
		 * NR := NOW
		 */
		update_timestamp(&rtiming.rt_next_read);
		
		for (;;) {
			output_pre();

			/*
			 * E := NOW
			 */
			update_timestamp(&e);

			/*
			 * IF NR <= E THEN
			 */
			if (timestamp_le(&rtiming.rt_next_read, &e)) {
				timestamp_t c;

				/*
				 * C :=  (NR - E)
				 */
				timestamp_sub(&c, &rtiming.rt_next_read, &e);

				//calc_variance(&c, &ri);

				/*
				 * LR := E
				 */
				copy_timestamp(&rtiming.rt_last_read, &e);

				/*
				 * NR := E + RI + C
				 */
				timestamp_add(&rtiming.rt_next_read, &e, &ri);
				timestamp_add(&rtiming.rt_next_read,
				       &rtiming.rt_next_read, &c);


				reset_update_flags();
				input_read();
				free_unused_elements();
				output_draw();
				output_post();
			}

			if (do_quit)
				exit(0);

			/*
			 * ST := Configured ST
			 */
			st = sleep_time;

			/*
			 * IF (NR - E) < ST THEN
			 */
			timestamp_sub(&tmp, &rtiming.rt_next_read, &e);

			if (tmp.tv_sec < 0)
				continue;

			if (tmp.tv_sec == 0 && tmp.tv_usec < st) {
				if (tmp.tv_usec < 0)
					continue;
				/*
				 * ST := (NR - E)
				 */
				st = tmp.tv_usec;
			}
			
			/*
			 * SLEEP(ST)
			 */
			usleep(st);
		}
	} while (0);

	return 0; /* buddha says i'll never be reached */
}
Exemple #12
0
static bool process_packet(tc_user_t *u, unsigned char *frame) 
{
    bool                    result;
    uint16_t                size_ip, size_tcp, tot_len, cont_len;
    uint32_t                h_ack, h_last_ack;
    tc_ip_header_t         *ip_header;
    tc_tcp_header_t        *tcp_header;
    ip_port_pair_mapping_t *test;

    ip_header  = (tc_ip_header_t *) (frame + ETHERNET_HDR_LEN);
    size_ip    = ip_header->ihl << 2;
    tcp_header = (tc_tcp_header_t *) ((char *) ip_header + size_ip);
    size_tcp = tcp_header->doff << 2;
    tot_len  = ntohs(ip_header->tot_len);
    cont_len = tot_len - size_tcp - size_ip;

    if (u->dst_port == 0) {
        test = get_test_pair(&(clt_settings.transfer), 
                ip_header->daddr, tcp_header->dest);
        if (test == NULL) {
            tc_log_info(LOG_NOTICE, 0, " test null:%u", 
                    ntohs(tcp_header->dest));
            tc_log_trace(LOG_WARN, 0, TO_BAKEND_FLAG, ip_header, tcp_header);
            return false;
        }
        u->dst_addr = test->target_ip;
        u->dst_port = test->target_port;
#if (GRYPHON_PCAP_SEND)
        u->src_mac       = test->src_mac;
        u->dst_mac       = test->dst_mac;
#endif
    }

    if (u->state.last_ack_recorded) {
        if (u->state.status < SEND_REQ && (u->state.status & SYN_CONFIRM)) {
            h_ack = ntohl(tcp_header->ack_seq);
            h_last_ack = ntohl(u->history_last_ack_seq);
            if (after(h_ack, h_last_ack)) {
                tc_log_debug1(LOG_DEBUG, 0, "server resp first, wait, p:%u", 
                        ntohs(u->src_port));
                u->state.resp_waiting = 1;
                return false;
            }
        }

    }

    ip_header->saddr = u->src_addr;
    tcp_header->source = u->src_port;
    u->history_last_ack_seq = tcp_header->ack_seq;
    u->state.last_ack_recorded = 1;
    tcp_header->ack_seq = u->exp_ack_seq;
    ip_header->daddr = u->dst_addr;
    tcp_header->dest = u->dst_port;

    tc_log_debug2(LOG_DEBUG, 0, "set ack seq:%u, p:%u",
            ntohl(u->exp_ack_seq), ntohs(u->src_port));

    packs_sent_cnt++;
    if (tcp_header->syn) {
        syn_sent_cnt++;
#if (!GRYPHON_SINGLE)
        if (!send_router_info(u, CLIENT_ADD)) {
            return false;
        }
#endif
        u->state.last_ack_recorded = 0;
        u->state.status  |= SYN_SENT;
    } else if (tcp_header->fin) {
        fin_sent_cnt++;
        u->state.status  |= CLIENT_FIN;
    } else if (tcp_header->rst) {
        rst_sent_cnt++;
        u->state.status  |= CLIENT_FIN;
        tc_log_debug1(LOG_DEBUG, 0, "a reset packet to back:%u",
                ntohs(u->src_port));
    }

    if (cont_len > 0) {
        cont_sent_cnt++;
        u->state.status |= SEND_REQ;
    }
    if (u->state.timestamped) {
        update_timestamp(u, tcp_header);
    }

    tcp_header->check = 0;
    tcp_header->check = tcpcsum((unsigned char *) ip_header,
            (unsigned short *) tcp_header, (int) (tot_len - size_ip));
#if (GRYPHON_PCAP_SEND)
    ip_header->check = 0;
    ip_header->check = csum((unsigned short *) ip_header,size_ip);
#endif
    tc_log_debug_trace(LOG_DEBUG, 0, TO_BAKEND_FLAG, ip_header, tcp_header);

#if (!GRYPHON_PCAP_SEND)
    result = tc_raw_socket_send(tc_raw_socket_out, ip_header, tot_len,
            ip_header->daddr);
#else
    fill_frame((struct ethernet_hdr *) frame, u->src_mac, u->dst_mac);
    result = tc_pcap_send(frame, tot_len + ETHERNET_HDR_LEN);
#endif

    if (result == TC_OK) {
        u->last_sent_time = tc_time();
        return true;
    } else {
        tc_log_info(LOG_ERR, 0, "send to back error,tot_len is:%d,cont_len:%d",
                tot_len,cont_len);
#if (!TCPCOPY_PCAP_SEND)
        tc_raw_socket_out = TC_INVALID_SOCKET;
#endif
        tc_over = SIGRTMAX;
        return false;
    }
}
Exemple #13
0
timer::timer(std::string name, time_callback callback, int interval, bool repeat, unsigned long timestamp):name_(name), callback_(callback), repeat_(repeat), update_(false)
{
	set_interval(interval);
	set_timestamp(timestamp);
	update_timestamp();
}
Exemple #14
0
int main(int argc, char *argv[])
{
	unsigned long sleep_time;
	double read_interval;
	

	start_time = time(0);

	parse_args_pre(argc, argv);
	configfile_read();
	parse_args_post(argc, argv);

	conf_init();
	module_init();

	read_interval = cfg_read_interval;
	sleep_time = cfg_getint(cfg, "sleep_time");

	if (((double) sleep_time / 1000000.0f) > read_interval)
		sleep_time = (unsigned long) (read_interval * 1000000.0f);

	// pipe_start();

	if (cfg_getbool(cfg, "daemon")) {
		init_syslog();
		daemonize();
		write_pidfile();
	}

	drop_privs();

	do {
		/*
		 * E  := Elapsed time
		 * NR := Next Read
		 * LR := Last Read
		 * RI := Read Interval
		 * ST := Sleep Time
		 * C  := Correction
		 */
		timestamp_t e, ri, tmp;
		unsigned long st;

		float_to_timestamp(&ri, read_interval);

		/*
		 * NR := NOW
		 */
		update_timestamp(&rtiming.rt_next_read);
		
		for (;;) {
			output_pre();

			/*
			 * read the chucka chucka pipe
			 */
			// pipe_handle();

			/*
			 * E := NOW
			 */
			update_timestamp(&e);

			/*
			 * IF NR <= E THEN
			 */
			if (timestamp_le(&rtiming.rt_next_read, &e)) {
				timestamp_t c;

				/*
				 * C :=  (NR - E)
				 */
				timestamp_sub(&c, &rtiming.rt_next_read, &e);

				//calc_variance(&c, &ri);

				/*
				 * LR := E
				 */
				copy_timestamp(&rtiming.rt_last_read, &e);

				/*
				 * NR := E + RI + C
				 */
				timestamp_add(&rtiming.rt_next_read, &e, &ri);
				timestamp_add(&rtiming.rt_next_read,
				       &rtiming.rt_next_read, &c);


				reset_update_flags();
				input_read();
				free_unused_elements();
				output_draw();
				output_post();
			}

			if (do_quit)
				exit(0);

			/*
			 * ST := Configured ST
			 */
			st = sleep_time;

			/*
			 * IF (NR - E) < ST THEN
			 */
			timestamp_sub(&tmp, &rtiming.rt_next_read, &e);

			if (tmp.tv_sec < 0)
				continue;

			if (tmp.tv_sec == 0 && tmp.tv_usec < st) {
				if (tmp.tv_usec < 0)
					continue;
				/*
				 * ST := (NR - E)
				 */
				st = tmp.tv_usec;
			}
			
			/*
			 * SLEEP(ST)
			 */
			usleep(st);
		}
	} while (0);

	return 0; /* buddha says i'll never be reached */
}
Exemple #15
0
/*
 * serve - handle one HTTP request/response transaction
 */
void serve(int to_client_fd)
{
	char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], version[MAXLINE];
	char filename[MAXLINE], hostname[MAXLINE];
	char port[10];
	rio_t rio_to_client;
	rio_t rio_to_server;
	int to_server_fd;

	/* Read request line and headers */
	Rio_readinitb(&rio_to_client, to_client_fd);
	Rio_readlineb(&rio_to_client, buf, MAXLINE);
	sscanf(buf, "%s %s %s", method, uri, version);

	/* if not GET method, ignore it */
	if (strcasecmp(method, "GET")) {
		return;
	}

	/* Parse URI from GET request */
	parse_uri(uri, hostname, port, filename);
	// strange display error in csapp page
	if (strcasecmp(hostname, "csapp.cs.cmu.edu") == 0) {
		return;
	}

	sprintf(buf, "%s %s %s\r\n", "GET", filename, "HTTP/1.0");

	/* search content in cache list */
	struct cache_block* ptr = search_cache(head, uri);

	/* cache found, directly send to client */
	if (ptr) {
		// add the number of existing threads reading
		add_reading_cnt(ptr);
		// send cache to client
		Rio_writen(to_client_fd, ptr->file, ptr->size);
		// subtract the number of existing threads reading
		sub_reading_cnt(ptr);
		// update timestamp and reorder LRU list
		update_timestamp(head, ptr);

		return;
	}

	/* cache not found, connect with server */
	to_server_fd = Open_clientfd(hostname, port);
	Rio_readinitb(&rio_to_server, to_server_fd);
	// send request line: GET HTTP/1.0
	Rio_writen(to_server_fd, buf, strlen(buf));
	// send host to server
	sprintf(buf, "Host: %s\r\n", hostname);
	Rio_writen(to_server_fd, buf, strlen(buf));

	
	/* read http headers from client and write to server */
	Rio_readlineb(&rio_to_client, buf, MAXLINE);
	while (strncmp(buf, "\r\n", MAXLINE) != 0) {
		if (strstr(buf, "User-Agent"))
			strncpy(buf, user_agent_hdr, MAXLINE);
		else if (strstr(buf, "Connection"))
			strncpy(buf, "Connection: close\r\n", MAXLINE);
		else if (strstr(buf, "Proxy-Connection"))
			strncpy(buf, "Proxy-Connection: close\r\n", MAXLINE);
		else if (strstr(buf, "Host")) {
			// ignore, because we already sent one
			Rio_readlineb(&rio_to_client, buf, MAXLINE);
			continue;
		}
		Rio_writen(to_server_fd, buf, strlen(buf));
		Rio_readlineb(&rio_to_client, buf, MAXLINE);
	}
	/* terminates request headers */
	Rio_writen(to_server_fd, "\r\n", 2);


	/* read http response from server and write to client */
	memset(buf, 0, MAXLINE);
	Rio_readlineb(&rio_to_server, buf, MAXLINE);
	int content_len = 0;
	
	while (strncmp(buf, "\r\n", MAXLINE) != 0) {
		char* ptr = strstr(buf, "Content-length");
		if (ptr) {
			content_len = atoi(ptr + 16);
		}
		//printf("write2: %s\n", uri);
		//printf("fd: %d\n", to_client_fd);
		//printf("%d: %s\n", strlen(buf), buf);
		Rio_writen(to_client_fd, buf, strlen(buf));
		memset(buf, 0, MAXLINE);
		Rio_readlineb(&rio_to_server, buf, MAXLINE);
	}
	/* terminates response headers */
	Rio_writen(to_client_fd, "\r\n", 2);

	int size = 0;
	int need_cache = 0;
	/* shall we cache it? */
	if (content_len < MAX_OBJECT_SIZE)
		need_cache = 1;

	/* init a new cache block */
	struct cache_block* blk = (struct cache_block*) 
								malloc(sizeof(struct cache_block));
	init_cache(blk);
	strncpy(blk->uri, uri, MAXLINE);

	if (content_len > 0)
		blk->file = (char*) malloc(sizeof(char) * content_len);
	else
		blk->file = (char*) malloc(sizeof(char) * MAX_OBJECT_SIZE);

	memset(buf, 0, MAXLINE);
	int total_size = 0;
	char* headptr = blk->file;

	/* read response contents and write to client */
	while ((size = Rio_readnb(&rio_to_server, buf, MAXLINE)) > 0) {
		total_size += size;
		if (total_size > MAX_OBJECT_SIZE)
			need_cache = 0;
		if (need_cache) {
			memcpy(headptr, buf, size);
			headptr += size;
		}
		//printf("write3: %s\n", uri);
		Rio_writen(to_client_fd, buf, size);
		memset(buf, 0, MAXLINE);
	}

	/* add cache block */
	if (need_cache) {
		blk->size = total_size;
		// resize block
		blk->file = (char*) realloc(blk->file, blk->size);
		// size overflow, need to evict using LRU
		if (blk->size + cache_size > MAX_CACHE_SIZE)
			evict_cache(head, blk->size);
		// add it
		add_cache(head, blk);
	}
	/* prevent memory leakage */
	else {
		free_cache_node(blk);
	}

	Close(to_server_fd);
	return;
}
void countdown_clock::update_team(int new_timestamp)
{
	int time_passed = update_timestamp(new_timestamp);
	team_.set_countdown_time(std::max<int>(0, team_.countdown_time() - time_passed));
}
Exemple #17
0
static uint32_t flv_merge_stream(FILE * in, FILE * out,uint64_t timestamp,uint32_t lastsize)
{
	static char buf[65536000];

	struct flvbodytag flvbodytag;

	int pos;

	flv_skip_header(in);//skip the header

	// skip to video content and start reading

	do{
		fread(&flvbodytag,sizeof flvbodytag,1,in);
		fseek(in,UI24(flvbodytag.tag_data_size),SEEK_CUR);
	}while(flvbodytag.tag_type != 18);

	if( lastsize  ){
		fread(&flvbodytag,sizeof flvbodytag,1,in);
		fseek(in,UI24(flvbodytag.tag_data_size),SEEK_CUR);

		fread(&flvbodytag,sizeof flvbodytag,1,in);
		fseek(in,UI24(flvbodytag.tag_data_size),SEEK_CUR);

		pos = ftell(in);
	}

	//开始读咯
	//还要步步更新 timestamp
	if( fread(&flvbodytag,sizeof flvbodytag,1,in) ==1 )
	{
		flvbodytag.prv_tag_size = htonl(lastsize);

		// update timestamp
		update_timestamp(&flvbodytag,timestamp);
		// write tag
		fwrite(&flvbodytag,sizeof flvbodytag,1,out);

		// write tag data
		fread(buf, 1, UI24(flvbodytag.tag_data_size), in);
		fwrite(buf, 1, UI24(flvbodytag.tag_data_size), out);
	}else
		return 0;

	//开始读咯
	//还要步步更新 timestamp
	while( fread(&flvbodytag,sizeof flvbodytag,1,in) ==1 )
	{
		// update timestamp
		update_timestamp(&flvbodytag,timestamp);
		// write tag
		fwrite(&flvbodytag,sizeof flvbodytag,1,out);


		// write tag data
		fread(buf, 1, UI24(flvbodytag.tag_data_size), in);
		fwrite(buf, 1, UI24(flvbodytag.tag_data_size), out);
	}

	return ntohl(flvbodytag.prv_tag_size);
}
Exemple #18
0
void
shuffle(peer_t *peers, uint16_t numpeers, char *coop)
{
	peer_timestamp_t	*list;
	int			i;

#ifdef	DEBUG
	fprintf(stderr, "shuffle:coop %s\n", coop);
#endif

	if ((list = (peer_timestamp_t *)malloc(
			numpeers * sizeof(peer_timestamp_t))) == NULL) {
		/*
		 * if this fails, just do a random shuffle
		 */
		random_shuffle(peers, numpeers);

		/*
		 * need to touch all the timestamps in the download timestamps
		 * table
		 */

		return;
	}

	for (i = 0 ; i < numpeers ; ++i) {
		memcpy(&list[i].peer, &peers[i], sizeof(list[i].peer));
		list[i].timestamp = lookup_timestamp(list[i].peer.ip,
			&list[i].coop);
	}

	if (numpeers > 1) {

#ifdef	DEBUG
		fprintf(stderr, "shuffle:before sort\n");

		for (i = 0 ; i < numpeers ; ++i) {
			struct in_addr	in;

			in.s_addr = list[i].peer.ip;
	
			fprintf(stderr,
				"\thost %s : state %c : timestamp %lld : coop %s\n",
				inet_ntoa(in),
				(list[i].peer.state == DOWNLOADING ? 'd' : 'r'),
				list[i].timestamp, list[i].coop);
		}
#endif

		mycoop = coop;

		/*
		 * sort the list by timestamps
		 */
		qsort(list, numpeers, sizeof(peer_timestamp_t),
			timestamp_compare);

#ifdef	DEBUG
		fprintf(stderr, "shuffle:after sort\n");

		for (i = 0 ; i < numpeers ; ++i) {
			struct in_addr	in;

			in.s_addr = list[i].peer.ip;
	
			fprintf(stderr,
				"\thost %s : state %c : timestamp %lld : coop %s\n",
				inet_ntoa(in),
				(list[i].peer.state == DOWNLOADING ? 'd' : 'r'),
				list[i].timestamp, list[i].coop);
		}
#endif

		/*
		 * now copy the sorted list back into peers
		 */
		for (i = 0 ; i < numpeers ; ++i) {
			memcpy(&peers[i], &list[i].peer, sizeof(peers[i]));
		}

		/*
		 * update the timestamp on only the first entry in the new list
		 */ 
		update_timestamp(peers[0].ip);
	}

	free(list);
	return;
}