1
0

wsdef.h 2.1 KB

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