1
0

wsdef.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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] = {0};
  55. int i = 0;
  56. int imask = rand();
  57. for (i = 0; i < 4; i++) {
  58. mask[i] = (imask >> (8 * i)) & 0xff;
  59. }
  60. return ws_build_frame(out, data, data_len, mask, true, opcode, fin);
  61. }
  62. HV_INLINE int ws_server_build_frame(
  63. char* out,
  64. const char* data,
  65. int data_len,
  66. /* const char mask[4] */
  67. /* bool has_mask = false */
  68. enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT),
  69. bool fin DEFAULT(true)) {
  70. char mask[4] = {0};
  71. return ws_build_frame(out, data, data_len, mask, false, opcode, fin);
  72. }
  73. END_EXTERN_C
  74. #endif // HV_WS_DEF_H_