clsync-synchandler-so.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include <stdlib.h>
  2. #include <errno.h>
  3. // Required header:
  4. #include <clsync/compilerflags.h>
  5. #include <clsync/clsync.h>
  6. // Optional headers:
  7. #include <clsync/configuration.h>
  8. #include <clsync/error.h>
  9. #include <clsync/ctx.h>
  10. struct ctx *ctx_p = NULL;
  11. struct indexes *indexes_p = NULL;
  12. char **argv = NULL;
  13. size_t argv_size = 0;
  14. // Optional function, you can erase it.
  15. int clsyncapi_init(struct ctx *_ctx_p, struct indexes *_indexes_p) {
  16. debug(1, "Hello world! API version is %i", clsyncapi_getapiversion());
  17. ctx_p = _ctx_p;
  18. indexes_p = _indexes_p;
  19. if(ctx_p->destdir == NULL) {
  20. errno = EINVAL;
  21. error("destination-dir is not set.");
  22. return EINVAL;
  23. }
  24. if(ctx_p->flags[THREADING]) {
  25. errno = EINVAL;
  26. error("this handler is not pthread-safe.");
  27. return EINVAL;
  28. }
  29. argv_size = ALLOC_PORTION;
  30. argv = malloc(argv_size * sizeof(char *));
  31. argv[0] = "/bin/cp";
  32. argv[1] = "-pf";
  33. return 0;
  34. }
  35. int clsyncapi_sync(int n, api_eventinfo_t *ei) {
  36. debug(1, "clsyncapi_sync(): n == %i", n, ei->path);
  37. if(n+4 > argv_size) { // "/bin/cp" + "-pf" + n paths + ctx_p->destdir + NULL --> n+4
  38. argv_size = n+4 + ALLOC_PORTION;
  39. argv = realloc(argv, argv_size * sizeof(char *));
  40. }
  41. int argv_i=2;
  42. int ei_i=0;
  43. while(ei_i < n) {
  44. if(ei[ei_i].path_len > 0) {
  45. debug(1, "ei[%i].path == \"%s\" (len == %i, type_o == %i, type_n == %i)",
  46. ei_i, ei[ei_i].path, ei[ei_i].path_len, ei[ei_i].objtype_old, ei[ei_i].objtype_new);
  47. argv[argv_i++] = (char *)ei[ei_i].path;
  48. }
  49. ei_i++;
  50. }
  51. if(argv_i == 2) {
  52. debug(1, "Nothing to sync.");
  53. return 0;
  54. }
  55. argv[argv_i++] = ctx_p->destdir;
  56. argv[argv_i++] = NULL;
  57. // Forking
  58. int pid = clsyncapi_fork(ctx_p);
  59. switch(pid) {
  60. case -1:
  61. error("Cannot fork().");
  62. return errno;
  63. case 0:
  64. chdir(ctx_p->watchdir);
  65. execvp(argv[0], (char *const *)argv);
  66. return errno;
  67. }
  68. int status;
  69. if(waitpid(pid, &status, 0) != pid) {
  70. error("Cannot waitid().");
  71. return errno;
  72. }
  73. // Return
  74. int exitcode = WEXITSTATUS(status);
  75. debug(1, "Execution completed with exitcode %i.", exitcode);
  76. return exitcode;
  77. }
  78. // Optional function, you can erase it.
  79. int clsyncapi_deinit() {
  80. debug(1, "Goodbye cruel world!");
  81. if(argv != NULL)
  82. free(argv);
  83. return 0;
  84. }