Beispiel #1
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="s"></param>
 public HttpServer(Server s)
 {
     this.s = s;
     s.Connect += new ClientEvent (ClientConnect);
     //handlers.Add (new FallbackHandler ());
     HttpServer.singletonServer = this;
 }
        public bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url);
            if (request.Url.StartsWith (SERVICE_URI)) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Service protocol.");
                try {
                    string commandParams = request.Url.Substring (SERVICE_URI.Length);
                    string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                    string serviceName = commandParamsArray [0];

                    Object service = serviceLocator.GetService (serviceName);
                    byte[] result = null;
                    string methodName = commandParamsArray [1];

                    if (request.Method == "GET") {
                        string[] methodParams = null;
                        if (commandParamsArray.Length > 2) {
                            methodParams = new string[commandParamsArray.Length - 2];
                            for (int i = 2; i < commandParamsArray.Length; i++) {
                                methodParams [i - 2] = commandParamsArray [i];
                            }
                        }
                        result = getInvocationManager (request.Method).InvokeService (service, methodName, methodParams);
                    } else if (request.Method == "POST") {
                        string queryString = null;
                        if (request.QueryString != null && request.QueryString.Length > "json=".Length) {
                            //queryString = ServiceURIHandler.UrlDecode(request.QueryString.Substring("json=".Length));
                            queryString = request.QueryString.Substring ("json=".Length);
                        }
                        result = getInvocationManager (request.Method).InvokeService (service, methodName, queryString);
                    }

                    response.RawContent = result;
                    if (response.RawContent == null) {
                        response.Content = "null";
                        /* SERVICES COULD SEND NULL OBJETS.
                        SystemLogger.Log(SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler...");
                        return false;
                        */
                    }
                    response.ContentType = "application/json";
                    return true;
                } catch (Exception e) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e);
                    response.Content = "Malformed request.";
                    return false;
                }
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Non service protocol. Continue to next handler...");
                return false;
            }
        }
        public bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url);
            if (request.Url.StartsWith (REMOTE_RESOURCE_URI)) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Remote resource protocol.");
                try {
                    string commandParams = request.Url.Substring (REMOTE_RESOURCE_URI.Length);
                    string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                    if (commandParamsArray.Length > 0) {
                        string ioServiceName = commandParamsArray [0];

                        Object unityIOService = serviceLocator.GetService (UNITY_IO_SERVICE_NAME);
                        if (unityIOService != null && ioServiceName != null) {
                            IIo io = (IIo)unityIOService;
                            string parameters = commandParams.Substring (ioServiceName.Length + 1);

                            IORequest ioRequest = new IORequest ();
                            ioRequest.Content = parameters;
                            IOResponse ioResponse = io.InvokeService (ioRequest, ioServiceName);
                            if (ioResponse != null) {
                                response.ContentType = ioResponse.ContentType;
                                response.RawContent = ioResponse.ContentBinary;
                            }
                        }
                    }

                    if (response.RawContent == null) {
                        response.Content = "No content available.";
                        SystemLogger.Log (SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler...");
                        return false;
                    }

                    return true;
                } catch (Exception e) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e);
                    response.Content = "Malformed request.";
                    return false;
                }
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Non remote resource protocol. Continue to next handler...");
                return false;
            }
        }
 public bool Process(HttpServer server, HttpRequest req, HttpResponse resp)
 {
     //server.RequestSession(req);
     StringBuilder sb = new StringBuilder ();
     sb.Append ("<h3>Session</h3>");
     sb.Append ("<p>ID: " + req.Session.ID + "<br>User: "******"<h3>Header</h3>");
     sb.Append ("Method: " + req.Method + "; URL: '" + req.Url + "'; HTTP version " + req.HttpVersion + "<p>");
     foreach (DictionaryEntry ide in req.Header)
         sb.Append (" " + ide.Key + ": " + ide.Value + "<br>");
     sb.Append ("<h3>Cookies</h3>");
     foreach (DictionaryEntry ide in req.Cookies)
         sb.Append (" " + ide.Key + ": " + ide.Value + "<br>");
     sb.Append ("<h3>Query</h3>");
     foreach (DictionaryEntry ide in req.Query)
         sb.Append (" " + ide.Key + ": " + ide.Value + "<br>");
     sb.Append ("<h3>Content</h3>");
     sb.Append (req.Content);
     resp.Content = sb.ToString ();
     return true;
 }
        public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            if (request.Url.StartsWith (DOCUMENTS_URI)) {
                SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## " + this.GetType () + " -> " + request.Url);

                string requestUrl = request.Url;
                if(request.QueryString!=null && request.QueryString.Length>0) {
                    requestUrl = request.Page;
                    SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## " + this.GetType () + " -> removing req params -> " + requestUrl);
                }

                string escapedUrl = Uri.UnescapeDataString(requestUrl);
                // url should be escaped to reach the real filesystem path for the requested file.
                string resourcePath = escapedUrl.Substring (DOCUMENTS_URI.Length);

                // Getting mime type
                string ext = Path.GetExtension (resourcePath.ToLower());
                string mime = (string)MimeTypes [ext];
                if (mime == null)
                    mime = "application/octet-stream";
                response.ContentType = mime;

                // Getting Root Directory for Files in this platform.
                IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance ().GetService ("file");
                DirectoryData rootDir = fileSystemService.GetDirectoryRoot ();
                resourcePath = Path.Combine (rootDir.FullName, resourcePath);

                // Get Resources as Binary Data and Write them to the server response
                response.RawContent = IPhoneUtils.GetInstance ().GetResourceAsBinary (resourcePath, false);
                SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## " + this.GetType () + " -> file extension: " + ext + ", mimetype: " + mime + ", binary data length: " + response.RawContent.Length);

                return true;

            } else {
                return base.Process (server, request, response);
            }
        }
        /// <summary>
        /// Process the specified server, request and response. Overrides CORE ServiceURIHandler superclass
        /// </summary>
        /// <param name="server">Server.</param>
        /// <param name="request">Request.</param>
        /// <param name="response">Response.</param>
        public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            bool isServiceProtocol = request.Url.StartsWith (ServiceURIHandler.SERVICE_URI);

            /* TO BE REMOVED - 5.0.6 [AMOB-30]
            bool isManagedService = IPhoneServiceLocator.consumeManagedService (request.Url);
            SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## Managed Service? " + isManagedService);
            */

            if (isServiceProtocol) {

                /* TO BE REMOVED - 5.0.6 [AMOB-30]
                if(isManagedService) return base.Process (server, request, response);

                SystemLogger.Log (SystemLogger.Module .PLATFORM, "**** WARNING: Anonymous service call, not managed by Appverse !!!");
                return false;
                */

                return base.Process (server, request, response);
            }

            SystemLogger.Log (SystemLogger.Module .PLATFORM, "Non service protocol. Continue to next handler...");
            return false;
        }
        public virtual bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            if (this.appSource == ApplicationSource.FILE) {   // RESOURCES ARE SERVED FROM FILESYSTEM.

                string fn = server.GetFilename (request);
                if (!File.Exists (fn)) {
                    response.ReturnCode = 404;
                    response.Content = "File not found.";
                    SystemLogger.Log (SystemLogger.Module .CORE, "# ResourceHandler. Error getting response content for [" + fn + "]: File Not Found");
                    return true;
                }

                string ext = Path.GetExtension (fn);
                string mime = (string)MimeTypes [ext];
                if (mime == null)
                    mime = "application/octet-stream";
                response.ContentType = mime;

                try {   // Only perform substitutions on HTML files

                    //if (substitute && (mime.StartsWith("text/html"))) //(mime.Substring(0, 5) == "text/")
                    if (mime.StartsWith ("text/html")) { //(mime.Substring(0, 5) == "text/")
                        // Mime type 'text' is substituted
                        response.Content = GetContentFromStreamReader (fn);
                        /*
                        // Do substitutions
                        Regex regex = new Regex(@"\<\%(?<tag>[^>]+)\>");
                        lock (this)
                        {
                            req = request;
                            response.Content = regex.Replace(response.Content, new MatchEvaluator(RegexMatch));
                        }
                        */
                    } else {
                        response.RawContent = GetRawContentFromFileStream (fn);
                    }
                } catch (Exception e) {
                    response.ReturnCode = 500;
                    response.Content = "Error reading file: " + e;
                    SystemLogger.Log (SystemLogger.Module .CORE, "# ResourceHandler. Error getting response content for [" + fn + "]", e);
                    return true;
                }

            } else if (this.appSource == ApplicationSource.DB_FILE) {   // RESOURCES ARE SERVED FROM A PRE_BUILD "DB" FILE.
                // TODO get resources from DB file.

            } else if (this.appSource == ApplicationSource.DB_EMBEDDED) {   // RESOURCES ARE SERVED FROM A PRE_BUILD "DB" FILE.
                // TODO get resources from embedded DB file.

            }

            return true;
        }
Beispiel #8
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns>
        /// A <see cref="System.Boolean"/>
        /// </returns>
        protected bool openSocketListener(NSDictionary settings)
        {
            bool socketOpened = false;

            try {

                int defaultIPCPort = AppDelegate.GetIPCDefaultPort (settings);
                #if DEBUG
                log ("Opening Listener on port " + defaultIPCPort + "...");
                #endif
                if (httpServer == null) {
                    httpServer = new HttpServer (new Server (defaultIPCPort));
                }
                socketOpened = true;

                #if DEBUG
                log ("Listener OPENED on port: " + httpServer.Server.Port);
                #endif
                // Adding Resource Handler.
                IPhoneResourceHandler resourceHandler = new IPhoneResourceHandler (ApplicationSource.FILE);
                //resourceHandler.Substitute = false;
                httpServer.Handlers.Add (resourceHandler);

                // Adding Service URI Handler.
                httpServer.Handlers.Add (new IPhoneServiceURIHandler (IPhoneServiceLocator.GetInstance ()));

                // Adding Remote Resource Handler.
                httpServer.Handlers.Add (new RemoteResourceHandler (IPhoneServiceLocator.GetInstance ()));

            } catch (Exception ex) {
                #if DEBUG
                log ("Cannot open internal server socket: " + ex.Message);
                #endif
            }

            return socketOpened;
        }
Beispiel #9
0
 public override void WillTerminate(UIApplication application)
 {
     #if DEBUG
     log ("WillTerminate");
     #endif
     // Close Listener.
     if (httpServer != null) {
         httpServer.Close ();
         httpServer = null;
     }
     #if DEBUG
     log ("Internal Server Socket closed.");
     #endif
 }
Beispiel #10
0
        public override void DidEnterBackground(UIApplication application)
        {
            #if DEBUG
            log ("DidEnterBackground");
            #endif

            if(disableThumbnails) {
                // security reasons; the splash screen is shown when application enters in background (hiding sensitive data)
                // it will be dismissed on "WillEnterForeground" method
                UIInterfaceOrientation orientation =  UIApplication.SharedApplication.StatusBarOrientation;
                this.ShowSplashScreen(orientation);
            }
            using (var pool = new NSAutoreleasePool ()) {
                Thread thread = new Thread (NotifyEnterBackground as ThreadStart);
                thread.Priority = ThreadPriority.BelowNormal;
                thread.Start ();

            }

            if (httpServer != null) {
                httpServer.Close ();
                httpServer = null;
            }
        }
Beispiel #11
0
        /// <summary>
        /// 
        /// Closing Opened SocketListener
        /// </summary>
        private void closeOpenedSocketListener()
        {
            if (httpServer != null) {
                httpServer.Close ();
                httpServer = null;
                firstTimeOpening = true;
                socketOpened = false;

                #if DEBUG
                log ("Internal Server Socket closed.");
                #endif
            }
        }
Beispiel #12
0
        /// <summary>
        /// Open Socket listener on specific port
        /// </summary>
        protected void openSocketListener(int port)
        {
            try {

                #if DEBUG
                log ("[2] Opening Listener on port " + port + "...");
                #endif
                if (httpServer == null) {
                    httpServer = new HttpServer (new Server (port));
                }
                socketOpened = true;

                #if DEBUG
                log ("[2] Listener OPENED on port: " + httpServer.Server.Port);
                #endif

                // Adding Resource Handler.
                IPhoneResourceHandler resourceHandler = new IPhoneResourceHandler (ApplicationSource.FILE);
                //resourceHandler.Substitute = false;
                httpServer.Handlers.Add (resourceHandler);
                httpServer.Handlers.Add (new RemoteResourceHandler (IPhoneServiceLocator.GetInstance ()));

            } catch (Exception ex) {
                #if DEBUG
                log ("[2] Cannot open internal server socket: " + ex.Message);
                #endif
                if(ex.GetType() == typeof(System.Net.Sockets.SocketException)) {
                    System.Net.Sockets.SocketException socketException = ex as System.Net.Sockets.SocketException;
                    //log ("[2] Socket exception: " + socketException.SocketErrorCode);
                    if (socketException.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse) {
                        #if DEBUG
                        log ("[2] Address already in use; trying with next port...");
                        #endif
                        this.openSocketListener (port + 1);
                    }
                }
            }
        }
        public virtual bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url);
            if (request.Url.StartsWith (SERVICE_URI)) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Service protocol.");

                bool asyncmode = true;  // PLATFORM won't have anymore the sync mode for services.
                int serviceUriLength = SERVICE_URI.Length;

                if(response.Header == null) {
                    response.Header = new Hashtable();
                }

                // Adding Header Cache-Control to "no-cache" to force no caching service requests
                string cacheControlHeader = DEFAULT_CACHE_CONTROL;

                response.ContentType = "application/json";
                IInvocationManager invocationManager = getInvocationManager (request.Method);

                try {
                    string commandParams = request.Url.Substring (serviceUriLength);
                    string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                    string serviceName = commandParamsArray [0];

                    Object service = serviceLocator.GetService (serviceName);
                    byte[] result = null;
                    string methodName = commandParamsArray [1];

                    if (request.Method == "GET" && !asyncmode) {
                        string[] methodParams = null;
                        if (commandParamsArray.Length > 2) {
                            methodParams = new string[commandParamsArray.Length - 2];
                            for (int i = 2; i < commandParamsArray.Length; i++) {
                                methodParams [i - 2] = commandParamsArray [i];
                            }
                        }

                        // Process result synchronously
                        result = this.ProcessGETResult(invocationManager, service, methodName, methodParams);
                    } else if (request.Method == "POST") {
                        if (asyncmode){
                            // Process result asynchronously
                            this.ProcessAsyncPOSTResult(invocationManager, service, methodName, request.QueryString);
                        } else {
                            // Process result synchronously
                            result = this.ProcessPOSTResult(invocationManager, service, methodName, request.QueryString);
                        }
                    }

                    if(asyncmode) {
                        // Return acknowledge
                        response.Content = "{\"result\":\"Processed\"}";
                    } else {
                        response.RawContent = result;
                        if (response.RawContent == null) {
                            response.Content = "null";
                            /* SERVICES COULD SEND NULL OBJETS.
                                SystemLogger.Log(SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler...");
                                return false;
                                */
                        }
                    }

                } catch (Exception e) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e);
                    response.Content = "{\"result\":\"Malformed request\"}";
                }

                if(invocationManager.CacheControlHeader()!=null) {
                    cacheControlHeader = invocationManager.CacheControlHeader();
                }

                if(response.Header.ContainsKey(CACHE_CONTROL_HEADER)) {
                    response.Header[CACHE_CONTROL_HEADER] = cacheControlHeader;
                    SystemLogger.Log (SystemLogger.Module .CORE, "Updated Caching-Control header on response: " + cacheControlHeader);
                } else {
                    response.Header.Add(CACHE_CONTROL_HEADER, cacheControlHeader);
                    SystemLogger.Log (SystemLogger.Module .CORE, "Added Caching-Control header to response: " + cacheControlHeader);
                }

                return true;
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Non service protocol. Continue to next handler...");
                return false;
            }
        }