klish.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <getopt.h>
  12. #include <sys/socket.h>
  13. #include <sys/un.h>
  14. #include <faux/faux.h>
  15. #include <faux/str.h>
  16. #include <faux/msg.h>
  17. #include <klish/ktp.h>
  18. #include <klish/ktp_session.h>
  19. #include "private.h"
  20. static bool_t stdout_cb(ktp_session_t *ktp, const char *line, size_t len,
  21. void *user_data);
  22. static bool_t stderr_cb(ktp_session_t *ktp, const char *line, size_t len,
  23. void *user_data);
  24. int main(int argc, char **argv)
  25. {
  26. int retval = -1;
  27. struct options *opts = NULL;
  28. int unix_sock = -1;
  29. ktp_session_t *ktp = NULL;
  30. // Parse command line options
  31. opts = opts_init();
  32. if (opts_parse(argc, argv, opts)) {
  33. fprintf(stderr, "Error: Can't parse command line options\n");
  34. goto err;
  35. }
  36. // Connect to server
  37. unix_sock = ktp_connect_unix(opts->unix_socket_path);
  38. if (unix_sock < 0) {
  39. fprintf(stderr, "Error: Can't connect to server\n");
  40. goto err;
  41. }
  42. ktp = ktp_session_new(unix_sock);
  43. assert(ktp);
  44. if (!ktp) {
  45. fprintf(stderr, "Error: Can't create klish session\n");
  46. goto err;
  47. }
  48. ktp_session_set_stdout_cb(ktp, stdout_cb, NULL);
  49. ktp_session_set_stderr_cb(ktp, stderr_cb, NULL);
  50. {
  51. faux_error_t *error = faux_error_new();
  52. int retcode = -1;
  53. if (ktp_session_req_cmd(ktp, opts->line, &retcode, error)) {
  54. fprintf(stderr, "Retcode: %d\n", retcode);
  55. } else {
  56. fprintf(stderr, "Error:\n");
  57. faux_error_fshow(error, stderr);
  58. }
  59. faux_error_free(error);
  60. }
  61. retval = 0;
  62. err:
  63. ktp_session_free(ktp);
  64. ktp_disconnect(unix_sock);
  65. opts_free(opts);
  66. return retval;
  67. }
  68. static bool_t stdout_cb(ktp_session_t *ktp, const char *line, size_t len,
  69. void *user_data)
  70. {
  71. if (write(STDOUT_FILENO, line, len) < 0)
  72. return BOOL_FALSE;
  73. ktp = ktp;
  74. user_data = user_data;
  75. return BOOL_TRUE;
  76. }
  77. static bool_t stderr_cb(ktp_session_t *ktp, const char *line, size_t len,
  78. void *user_data)
  79. {
  80. if (write(STDERR_FILENO, line, len) < 0)
  81. return BOOL_FALSE;
  82. ktp = ktp;
  83. user_data = user_data;
  84. return BOOL_TRUE;
  85. }