wsdef.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "wsdef.h"
  2. #include <string.h>
  3. #include "sha1.h"
  4. #include "base64.h"
  5. #include "websocket_parser.h"
  6. // base64_encode( SHA1(key + magic) )
  7. void ws_encode_key(const char* key, char accept[]) {
  8. char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9. unsigned char digest[20] = {0};
  10. HV_SHA1_CTX ctx;
  11. HV_SHA1Init(&ctx);
  12. HV_SHA1Update(&ctx, (unsigned char*)key, (uint32_t)strlen(key));
  13. HV_SHA1Update(&ctx, (unsigned char*)magic, (uint32_t)strlen(magic));
  14. HV_SHA1Final(digest, &ctx);
  15. hv_base64_encode(digest, 20, accept);
  16. }
  17. // fix-header[2] + var-length[2/8] + mask[4] + data[data_len]
  18. int ws_calc_frame_size(int data_len, bool has_mask) {
  19. int size = data_len + 2;
  20. if (data_len >=126) {
  21. if (data_len > 0xFFFF) {
  22. size += 8;
  23. } else {
  24. size += 2;
  25. }
  26. }
  27. if (has_mask) size += 4;
  28. return size;
  29. }
  30. int ws_build_frame(
  31. char* out,
  32. const char* data, int data_len,
  33. const char mask[4], bool has_mask,
  34. enum ws_opcode opcode,
  35. bool fin) {
  36. int flags = opcode;
  37. if (fin) flags |= WS_FIN;
  38. if (has_mask) flags |= WS_HAS_MASK;
  39. return (int)websocket_build_frame(out, (websocket_flags)flags, mask, data, data_len);
  40. }