getrandom.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (C) 2016 Etienne Champetier <champetier.etienne@gmail.com>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. */
  14. #define _GNU_SOURCE
  15. #include <errno.h>
  16. #include <linux/random.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <sys/syscall.h>
  21. #include <unistd.h>
  22. #define ERROR_EXIT(fmt, ...) do { \
  23. fprintf(stderr, fmt, ## __VA_ARGS__); \
  24. return EXIT_FAILURE; \
  25. } while (0)
  26. static int usage(char *name)
  27. {
  28. fprintf(stderr, "Usage: %s <nb>\n", name);
  29. fprintf(stderr, " => return <nb> bytes from getrandom()\n");
  30. return EXIT_FAILURE;
  31. }
  32. int main(int argc, char *argv[])
  33. {
  34. if (argc != 2)
  35. return usage(argv[0]);
  36. if (isatty(STDOUT_FILENO))
  37. ERROR_EXIT("Not outputting random to a tty\n");
  38. int nbtot = atoi(argv[1]);
  39. if (nbtot < 1)
  40. ERROR_EXIT("Invalid <nb> param (must be > 0)\n");
  41. char buf[256];
  42. int len = sizeof(buf);
  43. while (nbtot > 0) {
  44. if (nbtot <= sizeof(buf))
  45. len = nbtot;
  46. if (syscall(SYS_getrandom, buf, len, 0) == -1)
  47. ERROR_EXIT("getrandom() failed: %m\n");
  48. if (write(STDOUT_FILENO, buf, len) != len)
  49. ERROR_EXIT("write() failed: %m\n");
  50. nbtot -= sizeof(buf);
  51. }
  52. return 0;
  53. }