util.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdarg.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include "libb64/cencode.h"
  10. #include "libb64/cdecode.h"
  11. #include "util.h"
  12. extern void sha512_compress(uint64_t state[8], const uint8_t block[128]);
  13. extern int logfd;
  14. char* strip(char* input, size_t sz) {
  15. char* clean = malloc(sz);
  16. int i = 0;
  17. while (*input) {
  18. if (*input == '\n') { input++; }
  19. if (!(strncmp(input, "�", 3))) { input += 3; }
  20. *clean = *input;
  21. clean++; input++; i++;
  22. }
  23. input -= i;
  24. return (clean-i);
  25. }
  26. //Libb64 interface functions
  27. void b64encode(char* input, char* output, size_t sz) {
  28. base64_encodestate s;
  29. char* clean;
  30. char* c = output;
  31. int cnt = 0;
  32. base64_init_encodestate(&s);
  33. cnt = base64_encode_block(input, strlen(input), c, &s);
  34. c += cnt;
  35. cnt = base64_encode_blockend(c, &s);
  36. c += cnt;
  37. *c = '\0';
  38. clean = strip(output, b64max(sz));
  39. snprintf(output, sz, "%s", clean);
  40. #if DO_FREE
  41. free(clean);
  42. #endif
  43. }
  44. void b64decode(char* input, char* output, size_t sz) {
  45. char* c = output;
  46. int cnt = 0;
  47. base64_decodestate s;
  48. base64_init_decodestate(&s);
  49. cnt = base64_decode_block(input, strlen(input), c, &s);
  50. c += cnt;
  51. *c = 0;
  52. }
  53. //End libb64 interface functions
  54. char* read_file(char* path, size_t sz, size_t nmemb) {
  55. if ((sz*nmemb) > MAXLEN_FILE) { return NULL; }
  56. if (access(path, F_OK) == -1) { return NULL; }
  57. FILE* fp = fopen(path, "r");
  58. if (!fp) { return NULL; }
  59. char* buf = malloc(MAXLEN_FILE); memset(buf, 0, MAXLEN_FILE);
  60. if (!buf) { return NULL; }
  61. fread(buf, sz, nmemb, fp);
  62. if (ferror(fp)) { return NULL; }
  63. return buf;
  64. }
  65. void logs(char* msg, ...) {
  66. va_list ap;
  67. char buf[MAXLEN_LOG]; memset(buf, 0, MAXLEN_LOG);
  68. va_start(ap, msg);
  69. vsprintf(buf, msg, ap);
  70. va_end(ap);
  71. if (getenv("DEBUG")) {
  72. printf("%s\n", buf);
  73. }
  74. write(logfd, buf, MAXLEN_LOG);
  75. write(logfd, "\n", 1);
  76. }