random.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <sys/random.h>
  15. #include <sys/param.h>
  16. #include <assert.h>
  17. #include <errno.h>
  18. #include <string.h>
  19. #include "esp_system.h"
  20. #include "esp_log.h"
  21. static const char *TAG = "RANDOM";
  22. ssize_t getrandom(void *buf, size_t buflen, unsigned int flags)
  23. {
  24. // Flags are ignored because:
  25. // - esp_random is non-blocking so it works for both blocking and non-blocking calls,
  26. // - don't have opportunity so set som other source of entropy.
  27. ESP_LOGD(TAG, "getrandom(buf=0x%x, buflen=%d, flags=%u)", (int) buf, buflen, flags);
  28. if (buf == NULL) {
  29. errno = EFAULT;
  30. ESP_LOGD(TAG, "getrandom returns -1 (EFAULT)");
  31. return -1;
  32. }
  33. uint8_t *dst = (uint8_t *) buf;
  34. ssize_t ret = 0;
  35. while (ret < buflen) {
  36. const uint32_t random = esp_random();
  37. const int needed = buflen - ret;
  38. const int copy_len = MIN(sizeof(random), needed);
  39. memcpy(dst + ret, &random, copy_len);
  40. ret += copy_len;
  41. }
  42. ESP_LOGD(TAG, "getrandom returns %d", ret);
  43. return ret;
  44. }