snac.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 grunfink - MIT license */
  3. #define XS_IMPLEMENTATION
  4. #include "xs.h"
  5. #include "xs_io.h"
  6. #include "xs_encdec.h"
  7. #include "xs_json.h"
  8. #include "xs_curl.h"
  9. #include "xs_openssl.h"
  10. #include "xs_socket.h"
  11. #include "xs_httpd.h"
  12. #include "snac.h"
  13. #include <sys/time.h>
  14. d_char *srv_basedir = NULL;
  15. d_char *srv_config = NULL;
  16. d_char *srv_baseurl = NULL;
  17. int srv_running = 0;
  18. int dbglevel = 0;
  19. d_char *xs_time(char *fmt, int local)
  20. /* returns a d_char with a formated time */
  21. {
  22. time_t t = time(NULL);
  23. struct tm tm;
  24. char tmp[64];
  25. if (local)
  26. localtime_r(&t, &tm);
  27. else
  28. gmtime_r(&t, &tm);
  29. strftime(tmp, sizeof(tmp), fmt, &tm);
  30. return xs_str_new(tmp);
  31. }
  32. d_char *tid(int offset)
  33. /* returns a time-based Id */
  34. {
  35. struct timeval tv;
  36. struct timezone tz;
  37. gettimeofday(&tv, &tz);
  38. return xs_fmt("%10d.%06d", tv.tv_sec + offset, tv.tv_usec);
  39. }
  40. void srv_debug(int level, d_char *str)
  41. /* logs a debug message */
  42. {
  43. xs *msg = str;
  44. if (dbglevel >= level) {
  45. xs *tm = xs_local_time("%H:%M:%S");
  46. fprintf(stderr, "%s %s\n", tm, msg);
  47. }
  48. }
  49. int validate_uid(char *uid)
  50. /* returns if uid is a valid identifier */
  51. {
  52. while (*uid) {
  53. if (!(isalnum(*uid) || *uid == '_'))
  54. return 0;
  55. uid++;
  56. }
  57. return 1;
  58. }
  59. void snac_debug(snac *snac, int level, d_char *str)
  60. /* prints a user debugging information */
  61. {
  62. xs *msg = str;
  63. if (dbglevel >= level) {
  64. xs *tm = xs_local_time("%H:%M:%S");
  65. fprintf(stderr, "%s [%s] %s\n", tm, snac->uid, msg);
  66. }
  67. }
  68. d_char *hash_password(char *uid, char *passwd, char *nonce)
  69. /* hashes a password */
  70. {
  71. xs *d_nonce = NULL;
  72. xs *combi;
  73. xs *hash;
  74. if (nonce == NULL)
  75. nonce = d_nonce = xs_fmt("%08x", random());
  76. combi = xs_fmt("%s:%s:%s", nonce, uid, passwd);
  77. hash = xs_sha1_hex(combi, strlen(combi));
  78. return xs_fmt("%s:%s", nonce, hash);
  79. }
  80. int check_password(char *uid, char *passwd, char *hash)
  81. /* checks a password */
  82. {
  83. int ret = 0;
  84. xs *spl = xs_split_n(hash, ":", 1);
  85. if (xs_list_len(spl) == 2) {
  86. xs *n_hash = hash_password(uid, passwd, xs_list_get(spl, 0));
  87. ret = (strcmp(hash, n_hash) == 0);
  88. }
  89. return ret;
  90. }