You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.2 KiB

11 years ago
11 years ago
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include "utils.h"
  5. #define INT_DIGITS 19 /* enough for 64 bit integer */
  6. char *itoa(int i) {
  7. /* Room for INT_DIGITS digits, - and '\0' */
  8. static char buf[INT_DIGITS + 2];
  9. char *p = buf + INT_DIGITS + 1; /* points to terminating '\0' */
  10. if (i >= 0) {
  11. do {
  12. *--p = '0' + (i % 10);
  13. i /= 10;
  14. } while (i != 0);
  15. return p;
  16. }
  17. else { /* i < 0 */
  18. do {
  19. *--p = '0' - (i % 10);
  20. i /= 10;
  21. } while (i != 0);
  22. *--p = '-';
  23. }
  24. return p;
  25. }
  26. void FATAL(const char *msg) {
  27. fprintf(stderr, "%s", msg);
  28. exit(-1);
  29. }
  30. void usage() {
  31. printf("usage:\n\n");
  32. printf(" ss -s server_host -p server_port -l local_port -k password\n");
  33. printf(" [-m encrypt_method] [-f pid_file] [-t timeout] [-c config_file]\n");
  34. printf("\n");
  35. printf("options:\n\n");
  36. printf(" encrypt_method: table, rc4\n");
  37. printf(" pid_file: valid path to the pid file\n");
  38. printf(" timeout: socket timeout in senconds\n");
  39. printf(" config_file: json format config file\n");
  40. printf("\n\n");
  41. }
  42. void demonize(const char* path) {
  43. /* Our process ID and Session ID */
  44. pid_t pid, sid;
  45. /* Fork off the parent process */
  46. pid = fork();
  47. if (pid < 0) {
  48. exit(EXIT_FAILURE);
  49. }
  50. /* If we got a good PID, then
  51. we can exit the parent process. */
  52. if (pid > 0) {
  53. FILE *file = fopen(path, "w");
  54. if (file == NULL) FATAL("Invalid pid file\n");
  55. fprintf(file, "%d", pid);
  56. fclose(file);
  57. exit(EXIT_SUCCESS);
  58. }
  59. /* Change the file mode mask */
  60. umask(0);
  61. /* Open any logs here */
  62. /* Create a new SID for the child process */
  63. sid = setsid();
  64. if (sid < 0) {
  65. /* Log the failure */
  66. exit(EXIT_FAILURE);
  67. }
  68. /* Change the current working directory */
  69. if ((chdir("/")) < 0) {
  70. /* Log the failure */
  71. exit(EXIT_FAILURE);
  72. }
  73. /* Close out the standard file descriptors */
  74. close(STDIN_FILENO);
  75. close(STDOUT_FILENO);
  76. close(STDERR_FILENO);
  77. }