mask.ipp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_WEBSOCKET_DETAIL_MASK_IPP
  10. #define BOOST_BEAST_WEBSOCKET_DETAIL_MASK_IPP
  11. #include <boost/beast/websocket/detail/mask.hpp>
  12. namespace boost {
  13. namespace beast {
  14. namespace websocket {
  15. namespace detail {
  16. void
  17. prepare_key(prepared_key& prepared, std::uint32_t key)
  18. {
  19. prepared[0] = (key >> 0) & 0xff;
  20. prepared[1] = (key >> 8) & 0xff;
  21. prepared[2] = (key >> 16) & 0xff;
  22. prepared[3] = (key >> 24) & 0xff;
  23. }
  24. inline
  25. void
  26. rol(prepared_key& v, std::size_t n)
  27. {
  28. auto v0 = v;
  29. for(std::size_t i = 0; i < v.size(); ++i )
  30. v[i] = v0[(i + n) % v.size()];
  31. }
  32. // Apply mask in place
  33. //
  34. void
  35. mask_inplace(net::mutable_buffer const& b, prepared_key& key)
  36. {
  37. auto n = b.size();
  38. auto const mask = key; // avoid aliasing
  39. auto p = static_cast<unsigned char*>(b.data());
  40. while(n >= 4)
  41. {
  42. for(int i = 0; i < 4; ++i)
  43. p[i] ^= mask[i];
  44. p += 4;
  45. n -= 4;
  46. }
  47. if(n > 0)
  48. {
  49. for(std::size_t i = 0; i < n; ++i)
  50. p[i] ^= mask[i];
  51. rol(key, n);
  52. }
  53. }
  54. } // detail
  55. } // websocket
  56. } // beast
  57. } // boost
  58. #endif