AdminLog.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. // needed for String_vprintf()
  16. #include <stdarg.h>
  17. #include "admin/Admin.h"
  18. #include "admin/AdminLog.h"
  19. #include "benc/Dict.h"
  20. #include "benc/String.h"
  21. #include "crypto/random/Random.h"
  22. #include "io/Writer.h"
  23. #include "memory/BufferAllocator.h"
  24. #include "util/log/Log.h"
  25. #include "util/log/Log_impl.h"
  26. #include "util/Hex.h"
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <time.h>
  30. #include <stdbool.h>
  31. #define MAX_SUBSCRIPTIONS 64
  32. #define FILE_NAME_COUNT 32
  33. struct Subscription
  34. {
  35. /** The log level to match against, all higher levels will also be matched. */
  36. enum Log_Level level;
  37. /**
  38. * true if the file name is the internal name
  39. * which can be compared using a pointer equality check
  40. */
  41. bool internalName : 1;
  42. /** The line number within the file or 0 to match all lines. */
  43. int lineNum : 31;
  44. /** The name of the file to match against or null to match any file. */
  45. const char* file;
  46. /** The transaction ID of the message which solicited this stream of logs. */
  47. String* txid;
  48. /** A hopefully unique (random) number identifying this stream. */
  49. uint8_t streamId[8];
  50. /** An allocator which will live during the lifecycle of the Subscription */
  51. struct Allocator* alloc;
  52. };
  53. struct AdminLog
  54. {
  55. struct Log pub;
  56. struct Subscription subscriptions[MAX_SUBSCRIPTIONS];
  57. uint32_t subscriptionCount;
  58. const char* fileNames[FILE_NAME_COUNT];
  59. struct Admin* admin;
  60. struct Allocator* alloc;
  61. struct Random* rand;
  62. };
  63. static inline const char* getShortName(const char* fullFilePath)
  64. {
  65. const char* out = CString_strrchr(fullFilePath, '/');
  66. if (out) {
  67. return out + 1;
  68. }
  69. return fullFilePath;
  70. }
  71. static inline bool isMatch(struct Subscription* subscription,
  72. struct AdminLog* logger,
  73. enum Log_Level logLevel,
  74. const char* file,
  75. int line)
  76. {
  77. if (subscription->file) {
  78. if (subscription->internalName) {
  79. if (file != subscription->file) {
  80. return false;
  81. }
  82. } else {
  83. const char* shortFileName = getShortName(file);
  84. if (CString_strcmp(shortFileName, subscription->file)) {
  85. return false;
  86. }
  87. // It's the same name but so we'll swap the name for the internal name and then
  88. // it can be compared quickly with a pointer comparison.
  89. subscription->file = shortFileName;
  90. subscription->internalName = true;
  91. for (int i = 0; i < FILE_NAME_COUNT; i++) {
  92. if (logger->fileNames[i] == shortFileName) {
  93. break;
  94. }
  95. if (logger->fileNames[i] == NULL) {
  96. logger->fileNames[i] = shortFileName;
  97. logger->fileNames[(i + 1) % FILE_NAME_COUNT] = NULL;
  98. break;
  99. }
  100. }
  101. }
  102. }
  103. if (logLevel < subscription->level) {
  104. return false;
  105. }
  106. if (subscription->lineNum && line != subscription->lineNum) {
  107. return false;
  108. }
  109. return true;
  110. }
  111. static Dict* makeLogMessage(struct Subscription* subscription,
  112. struct AdminLog* logger,
  113. enum Log_Level logLevel,
  114. const char* fullFilePath,
  115. uint32_t line,
  116. const char* format,
  117. va_list vaArgs,
  118. struct Allocator* alloc)
  119. {
  120. time_t now;
  121. time(&now);
  122. Dict* out = Dict_new(alloc);
  123. char* buff = Allocator_malloc(alloc, 20);
  124. Hex_encode((uint8_t*)buff, 20, subscription->streamId, 8);
  125. Dict_putString(out, String_new("streamId", alloc), String_new(buff, alloc), alloc);
  126. Dict_putInt(out, String_new("time", alloc), now, alloc);
  127. Dict_putString(out,
  128. String_new("level", alloc),
  129. String_new(Log_nameForLevel(logLevel), alloc),
  130. alloc);
  131. const char* shortName = getShortName(fullFilePath);
  132. Dict_putString(out, String_new("file", alloc), String_new((char*)shortName, alloc), alloc);
  133. Dict_putInt(out, String_new("line", alloc), line, alloc);
  134. String* message = String_vprintf(alloc, format, vaArgs);
  135. // Strip all of the annoying \n marks in the log entries.
  136. if (message->len > 0 && message->bytes[message->len - 1] == '\n') {
  137. message->len--;
  138. }
  139. Dict_putString(out, String_new("message", alloc), message, alloc);
  140. return out;
  141. }
  142. static void removeSubscription(struct AdminLog* log, struct Subscription* sub)
  143. {
  144. Allocator_free(sub->alloc);
  145. log->subscriptionCount--;
  146. if (log->subscriptionCount == 0 || sub == &log->subscriptions[log->subscriptionCount]) {
  147. return;
  148. }
  149. Bits_memcpyConst(sub,
  150. &log->subscriptions[log->subscriptionCount],
  151. sizeof(struct Subscription));
  152. }
  153. static void doLog(struct Log* genericLog,
  154. enum Log_Level logLevel,
  155. const char* fullFilePath,
  156. int line,
  157. const char* format,
  158. va_list args)
  159. {
  160. struct AdminLog* log = (struct AdminLog*) genericLog;
  161. Dict* message = NULL;
  162. #define ALLOC_BUFFER_SZ 4096
  163. uint8_t allocBuffer[ALLOC_BUFFER_SZ];
  164. for (int i = 0; i < (int)log->subscriptionCount; i++) {
  165. if (isMatch(&log->subscriptions[i], log, logLevel, fullFilePath, line)) {
  166. if (!message) {
  167. struct Allocator* alloc = BufferAllocator_new(allocBuffer, ALLOC_BUFFER_SZ);
  168. message = makeLogMessage(&log->subscriptions[i],
  169. log,
  170. logLevel,
  171. fullFilePath,
  172. line,
  173. format,
  174. args,
  175. alloc);
  176. }
  177. int ret = Admin_sendMessage(message, log->subscriptions[i].txid, log->admin);
  178. if (ret) {
  179. removeSubscription(log, &log->subscriptions[i]);
  180. }
  181. }
  182. }
  183. }
  184. static void subscribe(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  185. {
  186. struct AdminLog* log = (struct AdminLog*) vcontext;
  187. String* levelName = Dict_getString(args, String_CONST("level"));
  188. enum Log_Level level = (levelName) ? Log_levelForName(levelName->bytes) : Log_Level_DEBUG;
  189. int64_t* lineNumPtr = Dict_getInt(args, String_CONST("line"));
  190. String* fileStr = Dict_getString(args, String_CONST("file"));
  191. const char* file = (fileStr && fileStr->len > 0) ? fileStr->bytes : NULL;
  192. char* error = "2+2=5";
  193. if (level == Log_Level_INVALID) {
  194. level = Log_Level_KEYS;
  195. }
  196. if (lineNumPtr && *lineNumPtr < 0) {
  197. error = "Invalid line number, must be positive or 0 to signify any line is acceptable.";
  198. } else if (log->subscriptionCount >= MAX_SUBSCRIPTIONS) {
  199. error = "Max subscription count reached.";
  200. } else {
  201. struct Subscription* sub = &log->subscriptions[log->subscriptionCount];
  202. sub->level = level;
  203. sub->alloc = Allocator_child(log->alloc);
  204. if (file) {
  205. int i;
  206. for (i = 0; i < FILE_NAME_COUNT; i++) {
  207. if (log->fileNames[i] && !CString_strcmp(log->fileNames[i], file)) {
  208. file = log->fileNames[i];
  209. sub->internalName = true;
  210. break;
  211. }
  212. }
  213. if (i == FILE_NAME_COUNT) {
  214. file = String_new(file, sub->alloc)->bytes;
  215. sub->internalName = false;
  216. }
  217. }
  218. sub->file = file;
  219. sub->lineNum = (lineNumPtr) ? *lineNumPtr : 0;
  220. sub->txid = String_clone(txid, sub->alloc);
  221. Random_bytes(log->rand, (uint8_t*) sub->streamId, 8);
  222. uint8_t streamIdHex[20];
  223. Hex_encode(streamIdHex, 20, sub->streamId, 8);
  224. Dict response = Dict_CONST(
  225. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  226. String_CONST("streamId"), String_OBJ(String_CONST((char*)streamIdHex)), NULL
  227. ));
  228. Admin_sendMessage(&response, txid, log->admin);
  229. log->subscriptionCount++;
  230. return;
  231. }
  232. Dict response = Dict_CONST(
  233. String_CONST("error"), String_OBJ(String_CONST(error)), NULL
  234. );
  235. Admin_sendMessage(&response, txid, log->admin);
  236. }
  237. static void unsubscribe(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  238. {
  239. struct AdminLog* log = (struct AdminLog*) vcontext;
  240. String* streamIdHex = Dict_getString(args, String_CONST("streamId"));
  241. uint8_t streamId[8];
  242. char* error = NULL;
  243. if (streamIdHex->len != 16 || Hex_decode(streamId, 8, (uint8_t*)streamIdHex->bytes, 16) != 8) {
  244. error = "Invalid streamId.";
  245. } else {
  246. error = "No such subscription.";
  247. for (int i = 0; i < (int)log->subscriptionCount; i++) {
  248. if (!Bits_memcmp(streamId, log->subscriptions[i].streamId, 8)) {
  249. removeSubscription(log, &log->subscriptions[i]);
  250. error = "none";
  251. break;
  252. }
  253. }
  254. }
  255. Dict response = Dict_CONST(
  256. String_CONST("error"), String_OBJ(String_CONST(error)), NULL
  257. );
  258. Admin_sendMessage(&response, txid, log->admin);
  259. }
  260. struct Log* AdminLog_registerNew(struct Admin* admin, struct Allocator* alloc, struct Random* rand)
  261. {
  262. struct AdminLog* log = Allocator_clone(alloc, (&(struct AdminLog) {
  263. .pub = {
  264. .print = doLog
  265. },
  266. .admin = admin,
  267. .alloc = alloc,
  268. .rand = rand
  269. }));
  270. Admin_registerFunction("AdminLog_subscribe", subscribe, log, true,
  271. ((struct Admin_FunctionArg[]) {
  272. { .name = "level", .required = 0, .type = "String" },
  273. { .name = "line", .required = 0, .type = "Int" },
  274. { .name = "file", .required = 0, .type = "String" }
  275. }), admin);
  276. Admin_registerFunction("AdminLog_unsubscribe", unsubscribe, log, true,
  277. ((struct Admin_FunctionArg[]) {
  278. { .name = "streamId", .required = 1, .type = "String" }
  279. }), admin);
  280. return &log->pub;
  281. }