pex.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2014-2018 K. Lange
  5. *
  6. * pex - Packet EXchange client library
  7. *
  8. * Provides a friendly interface to the "Packet Exchange"
  9. * functionality provided by the packetfs kernel module.
  10. */
  11. #include <alloca.h>
  12. #include <assert.h>
  13. #include <stdint.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include <sys/ioctl.h>
  19. #include <toaru/pex.h>
  20. size_t pex_send(FILE * sock, unsigned int rcpt, size_t size, char * blob) {
  21. assert(size <= MAX_PACKET_SIZE);
  22. pex_header_t * broadcast = malloc(sizeof(pex_header_t) + size);
  23. broadcast->target = rcpt;
  24. memcpy(broadcast->data, blob, size);
  25. size_t out = write(fileno(sock), broadcast, sizeof(pex_header_t) + size);
  26. free(broadcast);
  27. return out;
  28. }
  29. size_t pex_broadcast(FILE * sock, size_t size, char * blob) {
  30. return pex_send(sock, 0, size, blob);
  31. }
  32. size_t pex_listen(FILE * sock, pex_packet_t * packet) {
  33. return read(fileno(sock), packet, PACKET_SIZE);
  34. }
  35. size_t pex_reply(FILE * sock, size_t size, char * blob) {
  36. return write(fileno(sock), blob, size);
  37. }
  38. size_t pex_recv(FILE * sock, char * blob) {
  39. memset(blob, 0, MAX_PACKET_SIZE);
  40. return read(fileno(sock), blob, MAX_PACKET_SIZE);
  41. }
  42. FILE * pex_connect(char * target) {
  43. char tmp[100];
  44. sprintf(tmp, "/dev/pex/%s", target);
  45. FILE * out = fopen(tmp, "r+");
  46. if (out) {
  47. setbuf(out, NULL);
  48. }
  49. return out;
  50. }
  51. FILE * pex_bind(char * target) {
  52. char tmp[100];
  53. sprintf(tmp, "/dev/pex/%s", target);
  54. FILE * out = fopen(tmp, "a+");
  55. if (out) {
  56. setbuf(out, NULL);
  57. }
  58. return out;
  59. }
  60. size_t pex_query(FILE * sock) {
  61. return ioctl(fileno(sock), IOCTL_PACKETFS_QUEUED, NULL);
  62. }