keygen-noise.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * keygen-noise.c: Unix implementation of get_heavy_noise() from cmdgen.c.
  3. */
  4. #include <stdio.h>
  5. #include <errno.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include "putty.h"
  9. char *get_random_data(int len, const char *device)
  10. {
  11. char *buf = snewn(len, char);
  12. int fd;
  13. int ngot, ret;
  14. if (!device) {
  15. static const char *const default_devices[] = {
  16. "/dev/urandom", "/dev/random"
  17. };
  18. size_t i;
  19. for (i = 0; i < lenof(default_devices); i++) {
  20. if (access(default_devices[i], R_OK) == 0) {
  21. device = default_devices[i];
  22. break;
  23. }
  24. }
  25. if (!device) {
  26. sfree(buf);
  27. fprintf(stderr, "puttygen: cannot find a readable "
  28. "random number source; use --random-device\n");
  29. return NULL;
  30. }
  31. }
  32. fd = open(device, O_RDONLY);
  33. if (fd < 0) {
  34. sfree(buf);
  35. fprintf(stderr, "puttygen: %s: open: %s\n",
  36. device, strerror(errno));
  37. return NULL;
  38. }
  39. ngot = 0;
  40. while (ngot < len) {
  41. ret = read(fd, buf+ngot, len-ngot);
  42. if (ret < 0) {
  43. close(fd);
  44. sfree(buf);
  45. fprintf(stderr, "puttygen: %s: read: %s\n",
  46. device, strerror(errno));
  47. return NULL;
  48. }
  49. ngot += ret;
  50. }
  51. close(fd);
  52. return buf;
  53. }