コード例 #1
0
int tlsio_schannel_send(CONCRETE_IO_HANDLE tls_io, const void* buffer, size_t size, ON_SEND_COMPLETE on_send_complete, void* callback_context)
{
    int result;

    while (size > 0)
    {
        size_t to_send = 16 * 1024;
        if (to_send > size)
        {
            to_send = size;
        }

        if (send_chunk(tls_io, buffer, to_send, (to_send == size) ? on_send_complete : NULL, callback_context) != 0)
        {
            break;
        }

        size -= to_send;
        buffer = ((const unsigned char*)buffer) + to_send;
    }

    if (size > 0)
    {
        result = __LINE__;
    }
    else
    {
        result = 0;
    }

    return result;
}
コード例 #2
0
static int internal_send(TLS_IO_INSTANCE* tls_io_instance, const void* buffer, size_t size, ON_SEND_COMPLETE on_send_complete, void* callback_context)
{
    int result;

    while (size > 0)
    {
        size_t to_send = 16 * 1024;
        if (to_send > size)
        {
            to_send = size;
        }

        if (send_chunk(tls_io_instance, buffer, to_send, (to_send == size) ? on_send_complete : NULL, callback_context) != 0)
        {
            break;
        }

        size -= to_send;
        buffer = ((const unsigned char*)buffer) + to_send;
    }

    if (size > 0)
    {
        LogError("send_chunk failed");
        result = __FAILURE__;
    }
    else
    {
        result = 0;
    }

    return result;
}
コード例 #3
0
ファイル: smoke_downstream.c プロジェクト: Bagarre/RProxy
static void
badchunk_transfer_cb(evhtp_request_t * req, void * arg) {
    /* Start the chunk */
    evhtp_send_reply_chunk_start(req, EVHTP_RES_OK);

    /* Send a few chunks with a bogus GET in the middle */
    send_chunk(req, "DATA", "%d\r\n", strlen("DATA"));
    send_chunk(req, "GET /index.html HTTP/1.1", "", 0);
    send_chunk(req, "MOREDATA", "%d\r\n", strlen("DATA"));

    /* Flush the connection */
    bufferevent_flush(req->conn->bev, EV_WRITE, BEV_FLUSH);

    /* Close the chunk */
    evhtp_send_reply_chunk_end(req);
}
コード例 #4
0
ファイル: proto.c プロジェクト: libguestfs/libguestfs
/* Also check if the library sends us a cancellation message. */
int
send_file_write (const void *buf, size_t len)
{
  guestfs_chunk chunk;
  int cancel;

  if (len > GUESTFS_MAX_CHUNK_SIZE) {
    fprintf (stderr, "guestfsd: send_file_write: len (%zu) > GUESTFS_MAX_CHUNK_SIZE (%d)\n",
             len, GUESTFS_MAX_CHUNK_SIZE);
    return -1;
  }

  cancel = check_for_library_cancellation ();

  if (cancel) {
    chunk.cancel = 1;
    chunk.data.data_len = 0;
    chunk.data.data_val = NULL;
  } else {
    chunk.cancel = 0;
    chunk.data.data_len = len;
    chunk.data.data_val = (char *) buf;
  }

  if (send_chunk (&chunk) == -1)
    return -1;

  if (cancel) return -2;
  return 0;
}
コード例 #5
0
ファイル: netplay.c プロジェクト: AbelFlos/RetroArch
// Grab our own input state and send this over the network.
static bool get_self_input_state(netplay_t *handle)
{
   unsigned i;
   struct delta_frame *ptr = &handle->buffer[handle->self_ptr];

   uint32_t state = 0;
   if (handle->frame_count > 0) // First frame we always give zero input since relying on input from first frame screws up when we use -F 0.
   {
      retro_input_state_t cb = handle->cbs.state_cb;
      for (i = 0; i < RARCH_FIRST_META_KEY; i++)
      {
         int16_t tmp = cb(g_settings.input.netplay_client_swap_input ? 0 : !handle->port,
               RETRO_DEVICE_JOYPAD, 0, i);
         state |= tmp ? 1 << i : 0;
      }
   }

   memmove(handle->packet_buffer, handle->packet_buffer + 2,
         sizeof (handle->packet_buffer) - 2 * sizeof(uint32_t));
   handle->packet_buffer[(UDP_FRAME_PACKETS - 1) * 2] = htonl(handle->frame_count); 
   handle->packet_buffer[(UDP_FRAME_PACKETS - 1) * 2 + 1] = htonl(state);

   if (!send_chunk(handle))
   {
      warn_hangup();
      handle->has_connection = false;
      return false;
   }

   ptr->self_state = state;
   handle->self_ptr = NEXT_PTR(handle->self_ptr);
   return true;
}
コード例 #6
0
ファイル: proto.c プロジェクト: libguestfs/libguestfs
int
send_file_end (int cancel)
{
  guestfs_chunk chunk;

  chunk.cancel = cancel;
  chunk.data.data_len = 0;
  chunk.data.data_val = NULL;
  return send_chunk (&chunk);
}
コード例 #7
0
ファイル: process-game.c プロジェクト: yorickvP/craftd
static void chunkradiusload(const void *T, void *ctx)
{
  // Send full chunk
  const int sizex = 16, sizey = 128, sizez = 16;
  
  struct PL_entry *player = (void *)ctx;
  chunk_coord coord = *(chunk_coord *)T;
  
  send_prechunk(player, coord.x, coord.z, true);
  send_chunk(player, coord.x, 0, coord.z, sizex, sizey, sizez);
}
コード例 #8
0
ファイル: utils.c プロジェクト: bigdinotech/crops
void send_args(int sock_fd, char *params[]) {
  int  i, j, num_chunks;
  msg_chunk *new_chunk, *tail_chunk, *head_chunk ;

  /* send all params in chunks of 20 chars*/
  for(i = 0; i < KEY_ARR_SZ; i++) {
    if (params[i] != NULL) {
      new_chunk = calloc(1, sizeof(msg_chunk));
      head_chunk = new_chunk;
      tail_chunk = new_chunk;
      num_chunks =  ceil((double) strlen(params[i]) /
        (sizeof((*new_chunk).arg)-1));

      for(j = 0; j < num_chunks; j++) {
        (*tail_chunk).op_code = i;
        if (j != 0) {
          strncpy((*tail_chunk).arg, params[i]+(j*sizeof((*tail_chunk).arg)-j),
            sizeof((*tail_chunk).arg)-1);
        } else {
          strncpy((*tail_chunk).arg, params[i], sizeof((*tail_chunk).arg)-1);
        }

        /* was this the last chunk*/
        if ((j+1) != num_chunks) {
          new_chunk = calloc(1, sizeof(msg_chunk));
          tail_chunk->next = new_chunk;
          tail_chunk = new_chunk;
        }
      }
      /* this param is ready - send head chunk*/
      send_chunk(sock_fd, head_chunk);
    }
  }

  /* we are done with all params. Send EOM as an individual chunk*/
  new_chunk = calloc(1, sizeof(msg_chunk));
  (*new_chunk).op_code = -1;
  strcpy((*new_chunk).arg, MSG_TERM);
  send_chunk(sock_fd, new_chunk);
}
コード例 #9
0
ファイル: netplay.c プロジェクト: carriercomm/RetroArch
static int poll_input(netplay_t *netplay, bool block)
{
    int max_fd        = (netplay->fd > netplay->udp_fd ?
                         netplay->fd : netplay->udp_fd) + 1;
    struct timeval tv = {0};
    tv.tv_sec         = 0;
    tv.tv_usec        = block ? (RETRY_MS * 1000) : 0;

    do
    {
        fd_set fds;
        /* select() does not take pointer to const struct timeval.
         * Technically possible for select() to modify tmp_tv, so
         * we go paranoia mode. */
        struct timeval tmp_tv = tv;

        netplay->timeout_cnt++;

        FD_ZERO(&fds);
        FD_SET(netplay->udp_fd, &fds);
        FD_SET(netplay->fd, &fds);

        if (socket_select(max_fd, &fds, NULL, NULL, &tmp_tv) < 0)
            return -1;

        /* Somewhat hacky,
         * but we aren't using the TCP connection for anything useful atm. */
        if (FD_ISSET(netplay->fd, &fds) && !netplay_get_cmd(netplay))
            return -1;

        if (FD_ISSET(netplay->udp_fd, &fds))
            return 1;

        if (!block)
            continue;

        if (!send_chunk(netplay))
        {
            warn_hangup();
            netplay->has_connection = false;
            return -1;
        }

        RARCH_LOG("Network is stalling, resending packet... Count %u of %d ...\n",
                  netplay->timeout_cnt, MAX_RETRIES);
    } while ((netplay->timeout_cnt < MAX_RETRIES) && block);

    if (block)
        return -1;
    return 0;
}
コード例 #10
0
ファイル: netplay.c プロジェクト: AbelFlos/RetroArch
static int poll_input(netplay_t *handle, bool block)
{
   int max_fd = (handle->fd > handle->udp_fd ? handle->fd : handle->udp_fd) + 1;

   struct timeval tv = {0};
   tv.tv_sec = 0;
   tv.tv_usec = block ? (RETRY_MS * 1000) : 0;

   do
   { 
      handle->timeout_cnt++;

      // select() does not take pointer to const struct timeval.
      // Technically possible for select() to modify tmp_tv, so we go paranoia mode.
      struct timeval tmp_tv = tv;

      fd_set fds;
      FD_ZERO(&fds);
      FD_SET(handle->udp_fd, &fds);
      FD_SET(handle->fd, &fds);

      if (select(max_fd, &fds, NULL, NULL, &tmp_tv) < 0)
         return -1;

      // Somewhat hacky,
      // but we aren't using the TCP connection for anything useful atm.
      if (FD_ISSET(handle->fd, &fds) && !netplay_get_cmd(handle))
         return -1; 

      if (FD_ISSET(handle->udp_fd, &fds))
         return 1;

      if (block && !send_chunk(handle))
      {
         warn_hangup();
         handle->has_connection = false;
         return -1;
      }

      if (block)
      {
         RARCH_LOG("Network is stalling, resending packet... Count %u of %d ...\n",
               handle->timeout_cnt, MAX_RETRIES);
      }
   } while ((handle->timeout_cnt < MAX_RETRIES) && block);

   if (block)
      return -1;
   return 0;
}
コード例 #11
0
ファイル: smoke_downstream.c プロジェクト: Bagarre/RProxy
static void
badchunk_length_cb(evhtp_request_t * req, void * arg) {
    evbuf_t * buf = evbuffer_new();
    evbuf_t * output;

    /* Start the chunk */
    evhtp_send_reply_chunk_start(req, EVHTP_RES_OK);

    /* Send some data */
    send_chunk(req, "SUCCESS", "%d\r\n", strlen("SUCCESS"));

    /* Close the chunk */
    evhtp_send_reply_chunk_end(req);
    evbuffer_free(buf);
}
コード例 #12
0
ファイル: netplay-4.c プロジェクト: flaviommedeiros/cprojects
/**
 * get_self_input_state:
 * @netplay              : pointer to netplay object
 *
 * Grab our own input state and send this over the network.
 *
 * Returns: true (1) if successful, otherwise false (0).
 **/
static bool get_self_input_state(netplay_t *netplay)
{
   uint32_t state          = 0;
   struct delta_frame *ptr = &netplay->buffer[netplay->self_ptr];
   driver_t *driver        = driver_get_ptr();
   settings_t *settings    = config_get_ptr();

   if (!driver->block_libretro_input && netplay->frame_count > 0)
   {
      unsigned i;

      /* First frame we always give zero input since relying on 
       * input from first frame screws up when we use -F 0. */
      retro_input_state_t cb = netplay->cbs.state_cb;
      for (i = 0; i < RARCH_FIRST_CUSTOM_BIND; i++)
      {
         int16_t tmp = cb(settings->input.netplay_client_swap_input ?
               0 : !netplay->port,
               RETRO_DEVICE_JOYPAD, 0, i);
         state |= tmp ? 1 << i : 0;
      }

      for (i = RARCH_FIRST_CUSTOM_BIND; i < RARCH_FIRST_META_KEY; i++)
      {
         int16_t tmp = cb(settings->input.netplay_client_swap_input ?
               0 : !netplay->port,
               RETRO_DEVICE_ANALOG, 0, i);
         state |= tmp ? 1 << i : 0;
      }
   }

   memmove(netplay->packet_buffer, netplay->packet_buffer + 2,
         sizeof (netplay->packet_buffer) - 2 * sizeof(uint32_t));
   netplay->packet_buffer[(UDP_FRAME_PACKETS - 1) * 2] = htonl(netplay->frame_count); 
   netplay->packet_buffer[(UDP_FRAME_PACKETS - 1) * 2 + 1] = htonl(state);

   if (!send_chunk(netplay))
   {
      warn_hangup();
      netplay->has_connection = false;
      return false;
   }

   ptr->self_state = state;
   netplay->self_ptr = NEXT_PTR(netplay->self_ptr);
   return true;
}
コード例 #13
0
ファイル: api.c プロジェクト: merbanan/libsigrok
static void send_data(struct sr_dev_inst *sdi, struct libusb_transfer *buf[], uint64_t samples)
{
	int i = 0;
	uint64_t send = 0;
	uint32_t chunk;

	while (send < samples) {
		chunk = MIN(samples - send, (uint64_t)(buf[i]->actual_length / NUM_CHANNELS));
		send += chunk;
		send_chunk(sdi, buf[i]->buffer, chunk);

		/*
		 * Everything in this transfer was either copied to the buffer
		 * or sent to the session bus.
		 */
		g_free(buf[i]->buffer);
		libusb_free_transfer(buf[i]);
		i++;
	}
}
コード例 #14
0
ファイル: send.c プロジェクト: matildah/mimocat
/* loops, copying data from the fdfrom file descriptor and calls send_chunk
   on each chunk of data */
void mainloop(int fdfrom, FD_ARRAY *fd)
{
    ssize_t read_bytes;
    uint8_t buf [BLOCKSIZE];

    while (1)
    {
        read_bytes = read(fdfrom, &buf, BLOCKSIZE);
        if (read_bytes == -1)
        {
            perror("read error");
        }
        
        if (read_bytes == 0)
        {
            break;
        }
        send_chunk(fd, buf, read_bytes);
    }
}
コード例 #15
0
ファイル: server.c プロジェクト: gorakhargosh/bjoern
static void
ev_io_on_write(struct ev_loop* mainloop, ev_io* watcher, const int events)
{
    GIL_LOCK(0);

    Request* request = ADDR_FROM_MEMBER(watcher, Request, ev_watcher);
    assert(request->current_chunk);

    if(send_chunk(request))
        goto notfinished;

    if(request->iterable) {
        PyObject* next_chunk;
        DBG_REQ(request, "Getting next iterable chunk.");
        next_chunk = wsgi_iterable_get_next_chunk(request);
        if(next_chunk == NULL) {
            if(PyErr_Occurred()) {
                /* Internal server error. */
                PyErr_Print();
                set_error(request, HTTP_SERVER_ERROR);
                goto notfinished;
            }
            DBG_REQ(request, "Iterable exhausted");
            goto bye;
        }
        request->current_chunk = next_chunk;
        assert(request->current_chunk_p == 0);
        goto notfinished;
    }

bye:
    DBG_REQ(request, "Done");

    /* Everything done, bye client! */
    ev_io_stop(mainloop, &request->ev_watcher);
    close(request->client_fd);
    Request_free(request);

notfinished:
    GIL_UNLOCK(0);
}
コード例 #16
0
ファイル: responser.c プロジェクト: lazyplus/641proj3
int responser_packet(bt_responser_t * res, int peer, data_packet_t * packet){
    // WHOHAS
    if(packet->header.packet_type == 0){
        int i = 0, j;
        for(; i<packet->header.packet_len - packet->header.header_len; i+=SHA1_HASH_SIZE * 2){
            for(j=0; j<res->chunk_cnt; ++j){
                if(strncmp(packet->data + i, res->chunks[j].hash, SHA1_HASH_SIZE * 2) == 0){
                    send_ihave(res, peer, packet->data + i);
                }
            }
        }
    }else
    // GET
    if(packet->header.packet_type == 2){
        int i;
        for(i=0; i<res->chunk_cnt; ++i){
            if(strncmp(packet->data, res->chunks[i].hash, SHA1_HASH_SIZE * 2) == 0){
                send_chunk(res, peer, res->chunks[i].id);
                break;
            }
        }
    }
    return 0;
}
コード例 #17
0
ファイル: server.c プロジェクト: liveck/bjoern
/* XXX too many gotos */
static void
ev_io_on_write(struct ev_loop* mainloop, ev_io* watcher, const int events)
{
  Request* request = REQUEST_FROM_WATCHER(watcher);

  GIL_LOCK(0);

  if(request->state.use_sendfile) {
    /* sendfile */
    if(request->current_chunk) {
      /* current_chunk contains the HTTP headers */
      if(send_chunk(request))
        goto out;
      assert(!request->current_chunk_p);
      /* abuse current_chunk_p to store the file fd */
      request->current_chunk_p = PyObject_AsFileDescriptor(request->iterable);
      goto out;
    }
    if(do_sendfile(request))
      goto out;
  } else {
    /* iterable */
    if(send_chunk(request))
      goto out;

    if(request->iterator) {
      PyObject* next_chunk;
      next_chunk = wsgi_iterable_get_next_chunk(request);
      if(next_chunk) {
        if(request->state.chunked_response) {
          request->current_chunk = wrap_http_chunk_cruft_around(next_chunk);
          Py_DECREF(next_chunk);
        } else {
          request->current_chunk = next_chunk;
        }
        assert(request->current_chunk_p == 0);
        goto out;
      } else {
        if(PyErr_Occurred()) {
          PyErr_Print();
          /* We can't do anything graceful here because at least one
           * chunk is already sent... just close the connection */
          DBG_REQ(request, "Exception in iterator, can not recover");
          ev_io_stop(mainloop, &request->ev_watcher);
          close(request->client_fd);
          Request_free(request);
          goto out;
        }
        Py_CLEAR(request->iterator);
      }
    }

    if(request->state.chunked_response) {
      /* We have to send a terminating empty chunk + \r\n */
      request->current_chunk = PyString_FromString("0\r\n\r\n");
      assert(request->current_chunk_p == 0);
      request->state.chunked_response = false;
      goto out;
    }
  }

  ev_io_stop(mainloop, &request->ev_watcher);
  if(request->state.keep_alive) {
    DBG_REQ(request, "done, keep-alive");
    Request_clean(request);
    Request_reset(request);
    ev_io_init(&request->ev_watcher, &ev_io_on_read,
               request->client_fd, EV_READ);
    ev_io_start(mainloop, &request->ev_watcher);
  } else {
    DBG_REQ(request, "done, close");
    close(request->client_fd);
    Request_free(request);
  }

out:
  GIL_UNLOCK(0);
}
コード例 #18
0
ファイル: api.c プロジェクト: bvanheu/libsigrok-ad
/*
 * Called by libusb (as triggered by handle_event()) when a transfer comes in.
 * Only channel data comes in asynchronously, and all transfers for this are
 * queued up beforehand, so this just needs to chuck the incoming data onto
 * the libsigrok session bus.
 */
static void receive_transfer(struct libusb_transfer *transfer)
{
	struct sr_datafeed_packet packet;
	struct sr_dev_inst *sdi;
	struct dev_context *devc;
	int num_samples, pre;

	sdi = transfer->user_data;
	devc = sdi->priv;
	sr_spew("receive_transfer(): status %d received %d bytes.",
		   transfer->status, transfer->actual_length);

	if (transfer->actual_length == 0)
		/* Nothing to send to the bus. */
		return;

	num_samples = transfer->actual_length / 2;

	sr_spew("Got %d-%d/%d samples in frame.", devc->samp_received + 1,
		   devc->samp_received + num_samples, devc->framesize);

	/*
	 * The device always sends a full frame, but the beginning of the frame
	 * doesn't represent the trigger point. The offset at which the trigger
	 * happened came in with the capture state, so we need to start sending
	 * from there up the session bus. The samples in the frame buffer
	 * before that trigger point came after the end of the device's frame
	 * buffer was reached, and it wrapped around to overwrite up until the
	 * trigger point.
	 */
	if (devc->samp_received < devc->trigger_offset) {
		/* Trigger point not yet reached. */
		if (devc->samp_received + num_samples < devc->trigger_offset) {
			/* The entire chunk is before the trigger point. */
			memcpy(devc->framebuf + devc->samp_buffered * 2,
					transfer->buffer, num_samples * 2);
			devc->samp_buffered += num_samples;
		} else {
			/*
			 * This chunk hits or overruns the trigger point.
			 * Store the part before the trigger fired, and
			 * send the rest up to the session bus.
			 */
			pre = devc->trigger_offset - devc->samp_received;
			memcpy(devc->framebuf + devc->samp_buffered * 2,
					transfer->buffer, pre * 2);
			devc->samp_buffered += pre;

			/* The rest of this chunk starts with the trigger point. */
			sr_dbg("Reached trigger point, %d samples buffered.",
				   devc->samp_buffered);

			/* Avoid the corner case where the chunk ended at
			 * exactly the trigger point. */
			if (num_samples > pre)
				send_chunk(sdi, transfer->buffer + pre * 2,
						num_samples - pre);
		}
	} else {
		/* Already past the trigger point, just send it all out. */
		send_chunk(sdi, transfer->buffer,
				num_samples);
	}

	devc->samp_received += num_samples;

	/* Everything in this transfer was either copied to the buffer or
	 * sent to the session bus. */
	g_free(transfer->buffer);
	libusb_free_transfer(transfer);

	if (devc->samp_received >= devc->framesize) {
		/* That was the last chunk in this frame. Send the buffered
		 * pre-trigger samples out now, in one big chunk. */
		sr_dbg("End of frame, sending %d pre-trigger buffered samples.",
			   devc->samp_buffered);
		send_chunk(sdi, devc->framebuf, devc->samp_buffered);

		/* Mark the end of this frame. */
		packet.type = SR_DF_FRAME_END;
		sr_session_send(devc->cb_data, &packet);

		if (devc->limit_frames && ++devc->num_frames == devc->limit_frames) {
			/* Terminate session */
			devc->dev_state = STOPPING;
		} else {
			devc->dev_state = NEW_CAPTURE;
		}
	}
}
コード例 #19
0
ファイル: httpstreaming.c プロジェクト: uitv/itvencoder
/**
 * httpserver_dispatcher:
 * @data: RequestData type pointer
 * @user_data: httpstreaming type pointer
 *
 * Process http request.
 *
 * Returns: positive value if have not completed the processing, for example live streaming.
 *      0 if have completed the processing.
 */
static GstClockTime
httpstreaming_dispatcher (gpointer data, gpointer user_data)
{
        RequestData *request_data = data;
        HTTPStreaming *httpstreaming = (HTTPStreaming *)user_data;
        gchar *buf;
        int i = 0, j, ret;
        Encoder *encoder;
        EncoderOutput *encoder_output;
        Channel *channel;
        RequestDataUserData *request_user_data;
        GstClockTime ret_clock_time;

        channel = get_channel (httpstreaming, request_data);
        switch (request_data->status) {
        case HTTP_REQUEST:
                GST_DEBUG ("new request arrived, socket is %d, uri is %s", request_data->sock, request_data->uri);
                encoder_output = get_encoder_output (httpstreaming, request_data);
                if (encoder_output == NULL) {
                        buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
                        httpserver_write (request_data->sock, buf, strlen (buf));
                        g_free (buf);
                        return 0;
                } else if ((request_data->parameters[0] == '\0') || (request_data->parameters[0] == 'b')) {
                        /* default operator is play, ?bitrate= */
                        GST_ERROR ("Play %s.", request_data->uri);
                        request_user_data = (RequestDataUserData *)g_malloc (sizeof (RequestDataUserData));//FIXME
                        if (request_user_data == NULL) {
                                GST_ERROR ("Internal Server Error, g_malloc for request_user_data failure.");
                                buf = g_strdup_printf (http_500, PACKAGE_NAME, PACKAGE_VERSION);
                                httpserver_write (request_data->sock, buf, strlen (buf));
                                g_free (buf);
                                return 0;
                        }

                        if (*(encoder_output->head_addr) == *(encoder_output->tail_addr)) {
                                GST_DEBUG ("%s unready.", request_data->uri);
                                buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
                                httpserver_write (request_data->sock, buf, strlen (buf));
                                g_free (buf);
                                return 0;
                        }

                        /* let send_chunk send new chunk. */
                        encoder = get_encoder (request_data->uri, httpstreaming->itvencoder->channel_array);
                        request_user_data->encoder = encoder;
                        request_user_data->chunk_size = 0;
                        request_user_data->send_count = 2;
                        request_user_data->chunk_size_str = g_strdup ("");
                        request_user_data->chunk_size_str_len = 0;
                        request_user_data->encoder_output = encoder_output;
                        request_user_data->current_rap_addr = *(encoder_output->last_rap_addr);
                        request_user_data->current_send_position = *(encoder_output->last_rap_addr) + 12;
                        request_user_data->channel_age = channel->age;
                        request_data->user_data = request_user_data;
                        request_data->bytes_send = 0;
                        buf = g_strdup_printf (http_chunked, PACKAGE_NAME, PACKAGE_VERSION);
                        httpserver_write (request_data->sock, buf, strlen (buf));
                        g_free (buf);
                        return gst_clock_get_time (httpstreaming->httpserver->system_clock) + GST_MSECOND;
                } else {
                        buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
                        httpserver_write (request_data->sock, buf, strlen (buf));
                        g_free (buf);
                        return 0;
                }
                break;
        case HTTP_CONTINUE:
                request_user_data = request_data->user_data;
                if ((request_user_data->channel_age != channel->age) ||
                    (*(channel->output->state) != GST_STATE_PLAYING)) {
                        g_free (request_data->user_data);
                        request_data->user_data = NULL;
                        return 0;
                }
                encoder_output = request_user_data->encoder_output;
                if (request_user_data->current_send_position == *(encoder_output->tail_addr)) {
                        /* no more stream, wait 10ms */
                        GST_DEBUG ("current:%llu == tail:%llu", request_user_data->current_send_position, encoder_output->tail_addr);
						return gst_clock_get_time (httpstreaming->httpserver->system_clock) + 500 * GST_MSECOND + g_random_int_range (1, 1000000);
                }
                ret_clock_time = send_chunk (encoder_output, request_data);
                if (ret_clock_time != GST_CLOCK_TIME_NONE)
                {
                        return ret_clock_time + gst_clock_get_time (httpstreaming->httpserver->system_clock);
                }
                else
                {
                        return GST_CLOCK_TIME_NONE;
                }
        case HTTP_FINISH:
                g_free (request_data->user_data);
                request_data->user_data = NULL;
                return 0;
        default:
                GST_ERROR ("Unknown status %d", request_data->status);
                buf = g_strdup_printf (http_400, PACKAGE_NAME, PACKAGE_VERSION);
                httpserver_write (request_data->sock, buf, strlen (buf));
                g_free (buf);
                return 0;
        }
}
コード例 #20
0
ファイル: tuple_server.c プロジェクト: ChrisX34/stuff
/**
 * Handle GETs and READs, both blocking and non-blocking.
 */
static void
handle_get_read(struct context *ctx,
		struct tuple *s, int remove, int blocking)
{
	struct ttuple *p;
	int clientnr = ctx - client_list;

#if 0
	GETLOG;
	LOGPRINTF("%s(%d) wants a tuple:", ctx->peername, ctx->id);
	LOGTUPLE(s);
	YIELDLOG;
#endif
	while (1) {
		status_list[clientnr]='a';
		GETACCESS;
		for (p = first_message; p != NULL; p = p->next) {
			if (tuples_match(p->tuple, s)) {
				if (remove) {
					remove_message_from_space(p);
				}
				YIELDACCESS;
				GETLOG;
				LOGPRINTF("%s(%d) %s a tuple:", ctx->peername, ctx->id, (remove)?"gets":"reads");
				LOGTUPLE(p->tuple);
				YIELDLOG;
				if (send_tuple(ctx, p->tuple)) {
					PRINTF("send_tuple failed\n");
					/* Assume the client died while blocked.
					 * If the tuple was removed, put it back.
					 * Otherwise just kill this thread.
					 */
					LOGPRINTF("send_tuple failed\n");
					LOGTUPLE(s);
					DBGPRINTF("remove=%d\n", remove);
					if (remove) {
						add_tuple_to_space(p->tuple);
						destroy_tuple(s);
						return;
					}
				}
				if (remove) {
					destroy_tuple(p->tuple);
				}
				destroy_tuple(s);
				return;
			}
		}

#if 0
		GETLOG;
		LOGPRINTF("Socket %d couldn't find a match for ", ctx->sock);
		LOGTUPLE(s);
		YIELDLOG;
#endif

		YIELDACCESS;
		if (blocking) {
			/* wait for a tuple that might match */
#ifdef USE_SEMA
			num_blocked++;
			if (sem_wait(&blocked_sem))
                          perror("sem_wait");
#else
			status_list[clientnr]='m';
			if (pthread_mutex_lock(&blocked_mutex))
				perror("mutex_lock");
			status_list[clientnr]='b';
			if (pthread_cond_wait(&blocked_cond, &blocked_mutex))
				perror("cond_wait");
			status_list[clientnr]='u';
			if (pthread_mutex_unlock(&blocked_mutex))
				perror("mutex_unlock");
#endif
		}
		else {
			/* don't wait, return a failure code */
			int ack = -1;
			if (send_chunk(ctx, (char *) &ack, sizeof(int)))
			{
				perror("Cannot send -1 return code");
			}
			return;
		}
	}
}
コード例 #21
0
ファイル: server.c プロジェクト: SongJLG/johan-doc
static void io_write(Request* request)
{
  //GIL_LOCK(0);

  if(request->state.use_sendfile) {
	dprint("发送文件给客户端");
    /* sendfile */
    if(request->current_chunk && send_chunk(request))
      goto out;
    /* abuse current_chunk_p to store the file fd */
    request->current_chunk_p = PyObject_AsFileDescriptor(request->iterable);
    if(do_sendfile(request))
      goto out;
  } else {
    dprint("发送字符");
    /* iterable */
	if(send_chunk(request)){
	  dprint("一次发送即完成");
	  //uv_close((uv_handle_t*) &request->ev_watcher, _http_uv__on_close__cb);
      goto out;
	}

    if(request->iterator) {
      PyObject* next_chunk;
	  dprint("request迭代");
      next_chunk = wsgi_iterable_get_next_chunk(request);
      if(next_chunk) {
		dprint("下一块chunk发送");
        if(request->state.chunked_response) {
          request->current_chunk = wrap_http_chunk_cruft_around(next_chunk);
          Py_DECREF(next_chunk);
        } else {
          request->current_chunk = next_chunk;
        }
        assert(request->current_chunk_p == 0);
		//io_write(request);
        goto out;
      } else {
        if(PyErr_Occurred()) {
		  uv_err_t err;
		  dprint("迭代出错");
          PyErr_Print();
          DBG_REQ(request, "Exception in iterator, can not recover");
		  uv_close((uv_handle_t*) request->ev_watcher, on_close);
		  Request_free(request);
		  err = uv_last_error(loop);
		  UVERR(err, "uv_write error on next chunk");
		  ASSERT(0);
          goto out;
        }
		dprint("没有下一块chunk");
        Py_CLEAR(request->iterator);
      }
    }

    if(request->state.chunked_response) {
      dprint("如果是chunked_response 发送收尾数据,并置空chunked_response");
      /* We have to send a terminating empty chunk + \r\n */
      request->current_chunk = PyString_FromString("0\r\n\r\n");
      assert(request->current_chunk_p == 0);
	  //io_write(request);
      request->state.chunked_response = false;
      goto out;
    }
  }
  dprint("响应完成");
  if(request->state.keep_alive) {
    DBG_REQ(request, "done, keep-alive");
    Request_clean(request);
    Request_reset(request);
  } else {
	dprint("done not keep alive");
	uv_close((uv_handle_t*) request->ev_watcher, on_close);
	Request_free(request);
  }

out:
  dprint("本次字符发送结束");
  //GIL_UNLOCK(0);
  return;
}
コード例 #22
0
ファイル: uefisign.c プロジェクト: 2asoft/freebsd
static void
sign(X509 *cert, EVP_PKEY *key, int pipefd)
{
	PKCS7 *pkcs7;
	BIO *bio, *out;
	const EVP_MD *md;
	PKCS7_SIGNER_INFO *info;
	void *digest, *signature;
	size_t digest_len, signature_len;
	int ok;

	assert(cert != NULL);
	assert(key != NULL);

	receive_chunk(&digest, &digest_len, pipefd);

	bio = BIO_new_mem_buf(digest, digest_len);
	if (bio == NULL) {
		ERR_print_errors_fp(stderr);
		errx(1, "BIO_new_mem_buf(3) failed");
	}

	pkcs7 = PKCS7_sign(NULL, NULL, NULL, bio, PKCS7_BINARY | PKCS7_PARTIAL);
	if (pkcs7 == NULL) {
		ERR_print_errors_fp(stderr);
		errx(1, "PKCS7_sign(3) failed");
	}

	md = EVP_get_digestbyname(DIGEST);
	if (md == NULL) {
		ERR_print_errors_fp(stderr);
		errx(1, "EVP_get_digestbyname(\"%s\") failed", DIGEST);
	}

	info = PKCS7_sign_add_signer(pkcs7, cert, key, md, 0);
	if (info == NULL) {
		ERR_print_errors_fp(stderr);
		errx(1, "PKCS7_sign_add_signer(3) failed");
	}

	/*
	 * XXX: All the signed binaries seem to have this, but where is it
	 *      described in the spec?
	 */
	PKCS7_add_signed_attribute(info, NID_pkcs9_contentType,
	    V_ASN1_OBJECT, OBJ_txt2obj("1.3.6.1.4.1.311.2.1.4", 1));

	magic(pkcs7, digest, digest_len);

#if 0
	out = BIO_new(BIO_s_file());
	BIO_set_fp(out, stdout, BIO_NOCLOSE);
	PKCS7_print_ctx(out, pkcs7, 0, NULL);

	i2d_PKCS7_bio(out, pkcs7);
#endif

	out = BIO_new(BIO_s_mem());
	if (out == NULL) {
		ERR_print_errors_fp(stderr);
		errx(1, "BIO_new(3) failed");
	}

	ok = i2d_PKCS7_bio(out, pkcs7);
	if (ok == 0) {
		ERR_print_errors_fp(stderr);
		errx(1, "i2d_PKCS7_bio(3) failed");
	}

	signature_len = BIO_get_mem_data(out, &signature);
	if (signature_len <= 0) {
		ERR_print_errors_fp(stderr);
		errx(1, "BIO_get_mem_data(3) failed");
	}

	(void)BIO_set_close(out, BIO_NOCLOSE);
	BIO_free(out);

	send_chunk(signature, signature_len, pipefd);
}
コード例 #23
0
ファイル: httpstreaming.c プロジェクト: wxtry/gstreamill
static GstClockTime http_continue_process (HTTPStreaming *httpstreaming, RequestData *request_data)
{
        HTTPStreamingPrivateData *priv_data;
        EncoderOutput *encoder_output;
        GstClock *system_clock = httpstreaming->httpserver->system_clock;
        gint ret;

        priv_data = request_data->priv_data;
        encoder_output = priv_data->encoder_output;
        if (priv_data->buf != NULL) {
                ret = write (request_data->sock,
                             priv_data->buf + priv_data->send_position,
                             priv_data->buf_size - priv_data->send_position);
                /* send complete or send error */
                if ((ret + priv_data->send_position == priv_data->buf_size) ||
                    ((ret == -1) && (errno != EAGAIN))) {
                        if ((ret == -1) && (errno != EAGAIN)) {
                                GST_ERROR ("Write sock error: %s", g_strerror (errno));
                        }
                        g_free (priv_data->buf);
                        priv_data->buf = NULL;
                        /* progressive play? continue */
                        if (is_http_progress_play_url (request_data)) {
                                priv_data->send_position = *(encoder_output->last_rap_addr) + 12;
                                priv_data->buf = NULL;
                                return gst_clock_get_time (system_clock);
                        }
                        if (encoder_output != NULL) {
                                gstreamill_unaccess (httpstreaming->gstreamill, request_data->uri);
                        }
                        if (priv_data->job != NULL) {
                                g_object_unref (priv_data->job);
                        }
                        g_free (priv_data);
                        request_data->priv_data = NULL;
                        return 0;

                } else if ((ret > 0) || ((ret == -1) && (errno == EAGAIN))) {
                        /* send not completed or socket block, resend late */
                        priv_data->send_position += ret > 0? ret : 0;
                        return ret > 0? 10 * GST_MSECOND + g_random_int_range (1, 1000000) : GST_CLOCK_TIME_NONE;
                }
        }
        if ((priv_data->livejob_age != priv_data->job->age) ||
            (*(priv_data->job->output->state) != JOB_STATE_PLAYING)) {
                if (priv_data->encoder_output != NULL) {
                        gstreamill_unaccess (httpstreaming->gstreamill, request_data->uri);
                }
                if (priv_data->job != NULL) {
                        g_object_unref (priv_data->job);
                }
                g_free (request_data->priv_data);
                request_data->priv_data = NULL;
                return 0;
        }
        if (priv_data->send_position == *(encoder_output->tail_addr)) {
                /* no more stream, wait 10ms */
                GST_DEBUG ("current:%lu == tail:%lu", priv_data->send_position, *(encoder_output->tail_addr));
                return gst_clock_get_time (system_clock) + 500 * GST_MSECOND + g_random_int_range (1, 1000000);
        }
        return send_chunk (encoder_output, request_data) + gst_clock_get_time (system_clock);
}
コード例 #24
0
ファイル: netplay.c プロジェクト: carriercomm/RetroArch
/**
 * get_self_input_state:
 * @netplay              : pointer to netplay object
 *
 * Grab our own input state and send this over the network.
 *
 * Returns: true (1) if successful, otherwise false (0).
 **/
static bool get_self_input_state(netplay_t *netplay)
{
    uint32_t state[UDP_WORDS_PER_FRAME - 1] = {0};
    struct delta_frame *ptr                 = &netplay->buffer[netplay->self_ptr];
    settings_t *settings                    = config_get_ptr();

    if (!input_driver_ctl(RARCH_INPUT_CTL_IS_LIBRETRO_INPUT_BLOCKED, NULL)
            && netplay->frame_count > 0)
    {
        unsigned i;

        /* First frame we always give zero input since relying on
         * input from first frame screws up when we use -F 0. */
        retro_input_state_t cb = netplay->cbs.state_cb;
        for (i = 0; i < RARCH_FIRST_CUSTOM_BIND; i++)
        {
            int16_t tmp = cb(settings->input.netplay_client_swap_input ?
                             0 : !netplay->port,
                             RETRO_DEVICE_JOYPAD, 0, i);
            state[0] |= tmp ? 1 << i : 0;
        }

        for (i = 0; i < 2; i++)
        {
            int16_t tmp_x = cb(settings->input.netplay_client_swap_input ?
                               0 : !netplay->port,
                               RETRO_DEVICE_ANALOG, i, 0);
            int16_t tmp_y = cb(settings->input.netplay_client_swap_input ?
                               0 : !netplay->port,
                               RETRO_DEVICE_ANALOG, i, 1);
            state[1 + i] = (uint16_t)tmp_x | (((uint16_t)tmp_y) << 16);
        }
    }

    /* Here we construct the payload format:
     * frame {
     *    uint32_t frame_number
     *    uint32_t RETRO_DEVICE_JOYPAD state (top 16 bits zero)
     *    uint32_t ANALOG state[0]
     *    uint32_t ANALOG state[1]
     * }
     *
     * payload {
     *    ; To compat packet losses, send input in a sliding window
     *    frame redundancy_frames[UDP_FRAME_PACKETS];
     * }
     */
    memmove(netplay->packet_buffer, netplay->packet_buffer + UDP_WORDS_PER_FRAME,
            sizeof (netplay->packet_buffer) - UDP_WORDS_PER_FRAME * sizeof(uint32_t));
    netplay->packet_buffer[(UDP_FRAME_PACKETS - 1) * UDP_WORDS_PER_FRAME] = htonl(netplay->frame_count);
    netplay->packet_buffer[(UDP_FRAME_PACKETS - 1) * UDP_WORDS_PER_FRAME + 1] = htonl(state[0]);
    netplay->packet_buffer[(UDP_FRAME_PACKETS - 1) * UDP_WORDS_PER_FRAME + 2] = htonl(state[1]);
    netplay->packet_buffer[(UDP_FRAME_PACKETS - 1) * UDP_WORDS_PER_FRAME + 3] = htonl(state[2]);

    if (!send_chunk(netplay))
    {
        warn_hangup();
        netplay->has_connection = false;
        return false;
    }

    memcpy(ptr->self_state, state, sizeof(state));
    netplay->self_ptr = NEXT_PTR(netplay->self_ptr);
    return true;
}
コード例 #25
0
ファイル: wav.c プロジェクト: anatol/libsigrok
static int process_buffer(struct sr_input *in)
{
	struct context *inc;
	struct sr_datafeed_packet packet;
	struct sr_datafeed_meta meta;
	struct sr_config *src;
	int offset, chunk_samples, total_samples, processed, max_chunk_samples;
	int num_samples, i;
	char channelname[8];

	inc = in->priv;
	if (!inc->started) {
		for (i = 0; i < inc->num_channels; i++) {
			snprintf(channelname, 8, "CH%d", i + 1);
			sr_channel_new(in->sdi, i, SR_CHANNEL_ANALOG, TRUE, channelname);
		}

		std_session_send_df_header(in->sdi, LOG_PREFIX);

		packet.type = SR_DF_META;
		packet.payload = &meta;
		src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(inc->samplerate));
		meta.config = g_slist_append(NULL, src);
		sr_session_send(in->sdi, &packet);
		sr_config_free(src);

		inc->started = TRUE;
	}

	if (!inc->found_data) {
		/* Skip past size of 'fmt ' chunk. */
		i = 20 + RL32(in->buf->str + 16);
		offset = find_data_chunk(in->buf, i);
		if (offset < 0) {
			if (in->buf->len > MAX_DATA_CHUNK_OFFSET) {
				sr_err("Couldn't find data chunk.");
				return SR_ERR;
			}
		}
		inc->found_data = TRUE;
	} else
		offset = 0;

	/* Round off up to the last channels * unitsize boundary. */
	chunk_samples = (in->buf->len - offset) / inc->num_channels / inc->unitsize;
	max_chunk_samples = CHUNK_SIZE / inc->num_channels / inc->unitsize;
	processed = 0;
	total_samples = chunk_samples;
	while (processed < total_samples) {
		if (chunk_samples > max_chunk_samples)
			num_samples = max_chunk_samples;
		else
			num_samples = chunk_samples;
		send_chunk(in, offset, num_samples);
		offset += num_samples * inc->unitsize;
		chunk_samples -= num_samples;
		processed += num_samples;
	}

	if ((unsigned int)offset < in->buf->len) {
		/*
		 * The incoming buffer wasn't processed completely. Stash
		 * the leftover data for next time.
		 */
		g_string_erase(in->buf, 0, offset);
	} else
		g_string_truncate(in->buf, 0);

	return SR_OK;
}
コード例 #26
0
ファイル: child.c プロジェクト: jaredmcneill/freebsd
static void
send_digest(const struct executable *x, int pipefd)
{

    send_chunk(x->x_digest, x->x_digest_len, pipefd);
}