wsdef.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. #define SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol"
  10. #define SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions"
  11. #define WS_SERVER_MIN_FRAME_SIZE 2
  12. // 1000 1001 0000 0000
  13. #define WS_SERVER_PING_FRAME "\211\0"
  14. // 1000 1010 0000 0000
  15. #define WS_SERVER_PONG_FRAME "\212\0"
  16. #define WS_CLIENT_MIN_FRAME_SIZE 6
  17. // 1000 1001 1000 0000
  18. #define WS_CLIENT_PING_FRAME "\211\200WSWS"
  19. // 1000 1010 1000 0000
  20. #define WS_CLIENT_PONG_FRAME "\212\200WSWS"
  21. enum ws_session_type {
  22. WS_CLIENT,
  23. WS_SERVER,
  24. };
  25. enum ws_opcode {
  26. WS_OPCODE_CONTINUE = 0x0,
  27. WS_OPCODE_TEXT = 0x1,
  28. WS_OPCODE_BINARY = 0x2,
  29. WS_OPCODE_CLOSE = 0x8,
  30. WS_OPCODE_PING = 0x9,
  31. WS_OPCODE_PONG = 0xA,
  32. };
  33. BEGIN_EXTERN_C
  34. // Sec-WebSocket-Key => Sec-WebSocket-Accept
  35. HV_EXPORT void ws_encode_key(const char* key, char accept[]);
  36. // fix-header[2] + var-length[2/8] + mask[4] + data[data_len]
  37. HV_EXPORT int ws_calc_frame_size(int data_len, bool has_mask DEFAULT(false));
  38. HV_EXPORT int ws_build_frame(
  39. char* out,
  40. const char* data,
  41. int data_len,
  42. const char mask[4],
  43. bool has_mask DEFAULT(false),
  44. enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT),
  45. bool fin DEFAULT(true));
  46. HV_INLINE int ws_client_build_frame(
  47. char* out,
  48. const char* data,
  49. int data_len,
  50. /* const char mask[4] */
  51. /* bool has_mask = true */
  52. enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT),
  53. bool fin DEFAULT(true)) {
  54. char mask[4];
  55. *(int*)mask = rand();
  56. return ws_build_frame(out, data, data_len, mask, true, opcode, fin);
  57. }
  58. HV_INLINE int ws_server_build_frame(
  59. char* out,
  60. const char* data,
  61. int data_len,
  62. /* const char mask[4] */
  63. /* bool has_mask = false */
  64. enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT),
  65. bool fin DEFAULT(true)) {
  66. char mask[4] = {0};
  67. return ws_build_frame(out, data, data_len, mask, false, opcode, fin);
  68. }
  69. END_EXTERN_C
  70. #endif // HV_WS_DEF_H_