Esempio n. 1
0
mongo_packet *
test_mongo_wire_generate_reply (gboolean valid, gint32 nreturn,
                                gboolean with_docs)
{
  mongo_reply_packet_header rh;
  mongo_packet_header h;
  mongo_packet *p;
  guint8 *data;
  gint data_size = sizeof (mongo_reply_packet_header);
  bson *b1 = NULL, *b2 = NULL;

  p = mongo_wire_packet_new ();

  h.opcode = (valid) ? GINT32_TO_LE (1) : GINT32_TO_LE (42);
  h.id = GINT32_TO_LE (1984);
  h.resp_to = GINT32_TO_LE (42);
  if (with_docs)
    {
      b1 = test_bson_generate_full ();
      b2 = test_bson_generate_full ();
      data_size += bson_size (b1) + bson_size (b2);
    }
  h.length = GINT32_TO_LE (sizeof (mongo_packet_header) + data_size);

  mongo_wire_packet_set_header (p, &h);

  data = g_try_malloc (data_size);

  rh.flags = 0;
  rh.cursor_id = GINT64_TO_LE ((gint64)12345);
  rh.start = 0;
  rh.returned = GINT32_TO_LE (nreturn);

  memcpy (data, &rh, sizeof (mongo_reply_packet_header));
  if (with_docs)
    {
      memcpy (data + sizeof (mongo_reply_packet_header),
              bson_data (b1), bson_size (b1));
      memcpy (data + sizeof (mongo_reply_packet_header) + bson_size (b1),
              bson_data (b2), bson_size (b2));
    }

  mongo_wire_packet_set_data (p, data, data_size);
  g_free (data);
  bson_free (b1);
  bson_free (b2);

  return p;
}
Esempio n. 2
0
mongo_packet *
mongo_packet_recv (mongo_connection *conn)
{
  mongo_packet *p;
  guint8 *data;
  guint32 size;
  mongo_packet_header h;

  if (!conn)
    {
      errno = ENOTCONN;
      return NULL;
    }

  if (conn->fd < 0)
    {
      errno = EBADF;
      return NULL;
    }

  memset (&h, 0, sizeof (h));
  if (recv (conn->fd, &h, sizeof (mongo_packet_header), MSG_NOSIGNAL) !=
      sizeof (mongo_packet_header))
    {
      return NULL;
    }

  h.length = GINT32_FROM_LE (h.length);
  h.id = GINT32_FROM_LE (h.id);
  h.resp_to = GINT32_FROM_LE (h.resp_to);
  h.opcode = GINT32_FROM_LE (h.opcode);

  p = mongo_wire_packet_new ();

  if (!mongo_wire_packet_set_header_raw (p, &h))
    {
      int e = errno;

      mongo_wire_packet_free (p);
      errno = e;
      return NULL;
    }

  size = h.length - sizeof (mongo_packet_header);
  data = g_new0 (guint8, size);
  if ((guint32)recv (conn->fd, data, size, MSG_NOSIGNAL) != size)
    {
      int e = errno;

      g_free (data);
      mongo_wire_packet_free (p);
      errno = e;
      return NULL;
    }

  if (!mongo_wire_packet_set_data (p, data, size))
    {
      int e = errno;

      g_free (data);
      mongo_wire_packet_free (p);
      errno = e;
      return NULL;
    }

  g_free (data);

  return p;
}