Add support for SSLKEYLOGFILE to server tool.

Mirrors the same functionality that is present in the client tool.

Tested by connecting the client with the server tool, verified that the
generated keylogs are identical.

Change-Id: Ic40b0ecb920383e01d7706574faf11fdb5c3fc7a
Reviewed-on: https://boringssl-review.googlesource.com/20244
Reviewed-by: Steven Valdez <svaldez@google.com>
Commit-Queue: Steven Valdez <svaldez@google.com>
CQ-Verified: CQ bot account: commit-bot@chromium.org <commit-bot@chromium.org>
diff --git a/tool/server.cc b/tool/server.cc
index 4cc183b..1d64933 100644
--- a/tool/server.cc
+++ b/tool/server.cc
@@ -160,6 +160,13 @@
   }
 }
 
+static FILE *g_keylog_file = nullptr;
+
+static void KeyLogCallback(const SSL *ssl, const char *line) {
+  fprintf(g_keylog_file, "%s\n", line);
+  fflush(g_keylog_file);
+}
+
 bool Server(const std::vector<std::string> &args) {
   if (!InitSocketLibrary()) {
     return false;
@@ -174,6 +181,16 @@
 
   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
 
+  const char *keylog_file = getenv("SSLKEYLOGFILE");
+  if (keylog_file) {
+    g_keylog_file = fopen(keylog_file, "a");
+    if (g_keylog_file == nullptr) {
+      perror("fopen");
+      return false;
+    }
+    SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
+  }
+
   // Server authentication is required.
   if (args_map.count("-key") != 0) {
     std::string key = args_map["-key"];