wsdef.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #ifndef HV_WS_DEF_H_
  2. #define HV_WS_DEF_H_
  3. #include "hexport.h"
  4. #include <stdbool.h>
  5. #include <stdlib.h> // import rand
  6. #define SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version"
  7. #define SEC_WEBSOCKET_KEY "Sec-WebSocket-Key"
  8. #define SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept"
  9. enum ws_opcode {
  10. WS_OPCODE_CONTINUE = 0x0,
  11. WS_OPCODE_TEXT = 0x1,
  12. WS_OPCODE_BINARY = 0x2,
  13. WS_OPCODE_CLOSE = 0x8,
  14. WS_OPCODE_PING = 0x9,
  15. WS_OPCODE_PONG = 0xA,
  16. };
  17. BEGIN_EXTERN_C
  18. // Sec-WebSocket-Key => Sec-WebSocket-Accept
  19. HV_EXPORT void ws_encode_key(const char* key, char accept[]);
  20. // fix-header[2] + var-length[2/8] + mask[4] + data[data_len]
  21. HV_EXPORT int ws_calc_frame_size(int data_len, bool has_mask DEFAULT(false));
  22. HV_EXPORT int ws_build_frame(
  23. char* out,
  24. const char* data,
  25. int data_len,
  26. const char mask[4],
  27. bool has_mask DEFAULT(false),
  28. enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT),
  29. bool fin DEFAULT(true));
  30. static inline int ws_client_build_frame(
  31. char* out,
  32. const char* data,
  33. int data_len,
  34. /* const char mask[4] */
  35. /* bool has_mask = true */
  36. enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT),
  37. bool fin DEFAULT(true)) {
  38. char mask[4];
  39. *(int*)mask = rand();
  40. return ws_build_frame(out, data, data_len, mask, true, opcode, fin);
  41. }
  42. static inline int ws_server_build_frame(
  43. char* out,
  44. const char* data,
  45. int data_len,
  46. /* const char mask[4] */
  47. /* bool has_mask = false */
  48. enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT),
  49. bool fin DEFAULT(true)) {
  50. char mask[4] = {0};
  51. return ws_build_frame(out, data, data_len, mask, false, opcode, fin);
  52. }
  53. END_EXTERN_C
  54. #endif // HV_WS_DEF_H_