AdminLog.c 11 KB

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