read.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. /* $Id: read.c,v 1.14 2001/04/30 16:02:07 kilobug Exp $ */
  2. #include "net_private.h"
  3. static gboolean net_check_type(int fd, net_type_t wanted)
  4. {
  5. unsigned char c = 42;
  6. if (read(fd, &c, 1) != 1)
  7. c = net_type_none;
  8. #ifdef __DEBUG_NETLIB__
  9. fprintf(stderr, "Reading type: %#x (wanted: %#x)\n", c, wanted);
  10. #endif
  11. if (c != wanted)
  12. {
  13. net_error(c, wanted);
  14. return FALSE;
  15. }
  16. return TRUE;
  17. }
  18. static gboolean read_data(int fd, void *buf, int sz)
  19. {
  20. int i;
  21. char *p = buf;
  22. while (sz > 0)
  23. {
  24. i = read(fd, p, sz);
  25. if (i <= -1)
  26. return FALSE;
  27. p += i;
  28. sz -= i;
  29. }
  30. return TRUE;
  31. }
  32. char *net_get_string(int fd)
  33. {
  34. int sz;
  35. char *s;
  36. if (!net_check_type(fd, net_type_str))
  37. return NULL;
  38. read_data(fd, &sz, 4);
  39. sz = g_ntohl(sz);
  40. if (sz < 0)
  41. {
  42. net_error(net_type_none, net_type_str);
  43. return NULL;
  44. }
  45. if (sz == 0)
  46. return g_strdup("");
  47. s = g_malloc(sz + 1);
  48. if (!read_data(fd, s, sz))
  49. {
  50. g_free(s);
  51. net_error(net_type_none, net_type_str);
  52. return NULL;
  53. }
  54. s[sz] = 0;
  55. #ifdef __DEBUG_NETLIB__
  56. fprintf(stderr, "Reading string: %s\n", s);
  57. #endif
  58. return s;
  59. }
  60. int net_get_int(int fd)
  61. {
  62. int l;
  63. if (!net_check_type(fd, net_type_int))
  64. return -1;
  65. if (!read_data(fd, &l, 4))
  66. {
  67. net_error(net_type_none, net_type_int);
  68. return -1;
  69. }
  70. #ifdef __DEBUG_NETLIB__
  71. fprintf(stderr, "Reading int: %d\n", g_ntohl(l));
  72. #endif
  73. return g_ntohl(l);
  74. }
  75. gboolean net_get_flag(int fd)
  76. {
  77. return net_get_char(fd);
  78. }
  79. char net_get_char(int fd)
  80. {
  81. char c;
  82. if (!net_check_type(fd, net_type_char))
  83. return FALSE;
  84. if (read(fd, &c, 1) != 1)
  85. {
  86. net_error(net_type_none, net_type_char);
  87. return 0;
  88. }
  89. #ifdef __DEBUG_NETLIB__
  90. fprintf(stderr, "Reading char: %d\n", c);
  91. #endif
  92. return c;
  93. }
  94. float net_get_float(int fd)
  95. {
  96. float f;
  97. if (!net_check_type(fd, net_type_float))
  98. return 1;
  99. if (!read_data(fd, &f, 4))
  100. {
  101. net_error(net_type_none, net_type_float);
  102. return 1;
  103. }
  104. #ifdef __DEBUG_NETLIB__
  105. fprintf(stderr, "Reading float: %f\n", f);
  106. #endif
  107. return f;
  108. }