diff Core/HttpServer/MongooseServer.cpp @ 409:63f707278fc8 lua-scripting

lua filtering of incoming http requests
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 03 May 2013 12:23:02 +0200
parents bdd72233b105
children 26290b46056b
line wrap: on
line diff
--- a/Core/HttpServer/MongooseServer.cpp	Thu May 02 16:51:40 2013 +0200
+++ b/Core/HttpServer/MongooseServer.cpp	Fri May 03 12:23:02 2013 +0200
@@ -454,6 +454,37 @@
   }
 
 
+  static std::string GetAuthenticatedUsername(const HttpHandler::Arguments& headers)
+  {
+    HttpHandler::Arguments::const_iterator auth = headers.find("authorization");
+
+    if (auth == headers.end())
+    {
+      return "";
+    }
+
+    std::string s = auth->second;
+    if (s.substr(0, 6) != "Basic ")
+    {
+      return "";
+    }
+
+    std::string b64 = s.substr(6);
+    std::string decoded = Toolbox::DecodeBase64(b64);
+    size_t semicolons = decoded.find(':');
+
+    if (semicolons == std::string::npos)
+    {
+      // Bad-formatted request
+      return "";
+    }
+    else
+    {
+      return decoded.substr(0, semicolons);
+    }
+  }
+
+
 
   static void* Callback(enum mg_event event,
                         struct mg_connection *connection,
@@ -511,6 +542,28 @@
         return (void*) "";
       }
 
+
+      // Apply the filter, if it is installed
+      const IIncomingHttpRequestFilter *filter = that->GetIncomingHttpRequestFilter();
+      if (filter != NULL)
+      {
+        std::string username = GetAuthenticatedUsername(headers);
+
+        char remoteIp[24];
+        sprintf(remoteIp, "%d.%d.%d.%d", 
+                reinterpret_cast<const uint8_t*>(&request->remote_ip) [3], 
+                reinterpret_cast<const uint8_t*>(&request->remote_ip) [2], 
+                reinterpret_cast<const uint8_t*>(&request->remote_ip) [1], 
+                reinterpret_cast<const uint8_t*>(&request->remote_ip) [0]);
+
+        if (!filter->IsAllowed(method, request->uri, remoteIp, username.c_str()))
+        {
+          SendUnauthorized(output);
+          return (void*) "";
+        }
+      }
+
+
       std::string postData;
 
       if (method == Orthanc_HttpMethod_Get)
@@ -737,6 +790,11 @@
     remoteAllowed_ = allowed;
   }
 
+  void MongooseServer::SetIncomingHttpRequestFilter(IIncomingHttpRequestFilter& filter)
+  {
+    Stop();
+    filter_ = &filter;
+  }
 
   bool MongooseServer::IsValidBasicHttpAuthentication(const std::string& basic) const
   {