snac.c 2.3 KB

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