/super_clnt/open.c

https://github.com/blackav/ejudge · C · 72 lines · 45 code · 14 blank · 13 comment · 7 complexity · b96c647440c926126ecca21739636e71 MD5 · raw file

  1. /* -*- mode: c -*- */
  2. /* Copyright (C) 2004-2016 Alexander Chernov <cher@ejudge.ru> */
  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. #include "ejudge/super_clnt.h"
  15. #include "ejudge/super_proto.h"
  16. #include "ejudge/errlog.h"
  17. #include "ejudge/sock_op.h"
  18. #include "ejudge/osdeps.h"
  19. #include <stdio.h>
  20. #include <signal.h>
  21. #include <unistd.h>
  22. #include <sys/types.h>
  23. #include <sys/socket.h>
  24. #include <sys/un.h>
  25. int
  26. super_clnt_open(const unsigned char *socket_path)
  27. {
  28. struct sockaddr_un addr;
  29. int fd = -1;
  30. int code = -SSERV_UNKNOWN_ERROR;
  31. signal(SIGPIPE, SIG_IGN);
  32. if (!socket_path) return -SSERV_ERR_BAD_SOCKET_NAME;
  33. addr.sun_family = AF_UNIX;
  34. snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
  35. if (strcmp(socket_path, addr.sun_path)!=0) return -SSERV_ERR_BAD_SOCKET_NAME;
  36. if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
  37. err("super_clnt_open: socket() failed: %s", os_ErrorMsg());
  38. code = -SSERV_ERR_SYSTEM_ERROR;
  39. goto failure;
  40. }
  41. if (sock_op_enable_creds(fd) < 0) {
  42. code = -SSERV_ERR_SYSTEM_ERROR;
  43. goto failure;
  44. }
  45. if (connect(fd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
  46. err("super_clnt_open: connect() failed: %s", os_ErrorMsg());
  47. code = -SSERV_ERR_CONNECT_FAILED;
  48. goto failure;
  49. }
  50. if (sock_op_put_creds(fd) < 0) {
  51. code = -SSERV_ERR_WRITE_TO_SERVER;
  52. goto failure;
  53. }
  54. return fd;
  55. failure:
  56. if (fd >= 0) close(fd);
  57. return code;
  58. }