コード例 #1
0
        string EP_show_reason(IHttpRequestResponse req)
        {
            string result = "";
            string prefix = "url=";

            try
            {
                string reason = "No url found";

                if (!string.IsNullOrEmpty(req.QueryString))
                {
                    int startIndex = req.QueryString.IndexOf(prefix);
                    if (startIndex > -1)
                    {
                        Uri url = new Uri(System.Net.WebUtility.UrlDecode(req.QueryString.Substring(startIndex + prefix.Length)));
                        isBlockedFullFlow(url, out reason);
                    }
                }

                result = AndroidApp.Properties.Resources.BlockedPage.Replace("{0}", reasonToHTML(reason));
            }
            catch (Exception ex)
            {
                result = stringHTML(ex.ToString(), "Error");
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #2
0
        string EP_echo(IHttpRequestResponse req)
        {
            string result = "";

            try
            {
                string headers = "";
                foreach (var key in req.Headers.Keys)
                {
                    headers += $"{key}: {req.Headers[key]}\r\n";
                }

                string sentBody = readReqBodyAsString(req);

                result =
                    AndroidApp.Properties.Resources.Echo
                    .Replace("{0}", headers)
                    .Replace("{1}", sentBody)
                    .Replace("{2}", req.Method)
                    .Replace("{3}", req.Path)
                ;
            }
            catch (Exception ex)
            {
                result = stringHTML(ex.ToString(), "Error");
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #3
0
        async Task SendResponseAsync(IHttpRequestResponse request, HttpSender httpSender)
        {
            try
            {
                if (request.RequestType == RequestType.TCP)
                {
                    string path = request.Path;
                    string responseContentType = ContentHTML;
                    string responseBody        = $"<html>\r\n<body>Unknown Path:\r\n{path}</body>\r\n</html>";


                    if (path.StartsWith("/echo"))
                    {
                        responseContentType = ContentHTML;
                        responseBody        = EP_echo(request);
                    }
                    else if (path.StartsWith("/history"))
                    {
                        responseContentType = ContentHTML;
                        responseBody        = EP_domainHistory(request);
                    }
                    else if (path.StartsWith("/check"))
                    {
                        responseContentType = ContentJSON;
                        responseBody        = EP_checkDomain(request);
                    }
                    else if (path.StartsWith("/reason"))
                    {
                        responseContentType = ContentHTML;
                        responseBody        = EP_show_reason(request);
                    }

                    var response = new HttpResponse
                    {
                        StatusCode     = (int)HttpStatusCode.OK,
                        ResponseReason = HttpStatusCode.OK.ToString(),
                        Headers        = new Dictionary <string, string>
                        {
                            { "Date", DateTime.UtcNow.ToString("r") },
                            { "Content-Type", responseContentType },
                            { "Connection", "close" }
                        },
                        Body = new MemoryStream(Encoding.UTF8.GetBytes(responseBody))
                    };

                    AndroidBridge.d(TAG, "[RESP-SEND] \"" + request.Path + "\" IP: " + ipString(request.RemoteIpEndPoint));

                    await httpSender.SendTcpResponseAsync(request, response).ConfigureAwait(false);

                    request.TcpClient.Close(); // Force close!

                    AndroidBridge.d(TAG, "[END] \"" + request.Path + "\" IP: " + ipString(request.RemoteIpEndPoint));
                }
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex.ToString());
            }
        }
コード例 #4
0
 public static void AppendLinePublic(string relativePath, string line)
 {
     try
     {
         File.AppendAllLines(AndroidBridge.GetAbsulotePath(relativePath, isPublic: true), new[] { line });
     }
     catch (Exception ex)
     {
         AndroidBridge.e(TAG, ex);
     }
 }
コード例 #5
0
 public void Stop()
 {
     try
     {
         AndroidBridge.d(TAG, "Closing server");
         cancellationTokenSource?.Cancel();
         myServerInstance?.Dispose();
         myListener?.Stop();
     }
     catch (Exception ex)
     {
         AndroidBridge.e(TAG, ex.ToString());
     }
 }
コード例 #6
0
        string EP_domainHistory(IHttpRequestResponse req)
        {
            string result = "";

            try
            {
                string body = String.Join("<br />", domainHistory);
                result = stringHTML(body: body);
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #7
0
        public static TaskResult SetPassword(string newPass)
        {
            TaskResult result = TaskResult.Fail("Init");

            try
            {
                newPass = get256Hash(newPass);
                File.WriteAllText(Filenames.MASTER_PASSWORD.getAppPrivate(), newPass);
                result = TaskResult.Success("Master password saved");
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex);
                result = TaskResult.Fail(ex.ToString());
            }
            return(result);
        }
コード例 #8
0
        string stringHTML(string body = "", string title = "")
        {
            string result = "";

            try
            {
                result =
                    AndroidApp.Properties.Resources.EmptyHTML
                    .Replace("{title}", title)
                    .Replace("{body}", body)
                ;
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #9
0
        public static string ReadAssetAsString(Context ctx, string tag, string asset_name)
        {
            string result = "";

            try
            {
                using (Stream s = ctx.Assets.Open(asset_name))
                {
                    StreamReader reader = new StreamReader(s);
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                AndroidBridge.e(tag, ex);
            }
            return(result);
        }
コード例 #10
0
 public static async Task onlyUnlockedAsync(Func <Task> callback)
 {
     try
     {
         var isLocked = TimeLock.isLocked();
         if (isLocked)
         {
             AndroidBridge.ToastIt(isLocked.eventReason);
         }
         else
         {
             await callback();
         }
     }
     catch (Exception ex)
     {
         AndroidBridge.e(TAG, ex);
     }
 }
コード例 #11
0
        string readReqBodyAsString(IHttpRequestResponse req)
        {
            string result = "";

            try
            {
                if (req.Body != null && req.Body.Length > 0)
                {
                    StreamReader reader = new StreamReader(req.Body);
                    req.Body.Position = 0;
                    result            = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #12
0
        public static string domainCategoryResult(bool block)
        {
            string result = "";

            try
            {
                int myCategory = block ? Category_Blocked : Category_Allowed;

                var jsonObject = new JObject();
                jsonObject["categories"] = new JArray(new[] { new JValue(myCategory) });
                jsonObject["resultCode"] = new JValue(0);

                result = jsonObject.ToString();
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #13
0
        public static TaskResult ComparePass(string checkPass)
        {
            TaskResult result = TaskResult.Fail("Init");

            try
            {
                checkPass = get256Hash(checkPass);
                string currentPass         = File.ReadAllText(Filenames.MASTER_PASSWORD.getAppPrivate());
                bool   arePasswordHashSame = checkPass.Equals(currentPass);

                result             = new TaskResult();
                result.success     = arePasswordHashSame;
                result.eventReason = "Are password same? " + arePasswordHashSame;
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex);
                result = TaskResult.Fail(ex.ToString());
            }
            return(result);
        }
コード例 #14
0
        public void Start(int port)
        {
            try
            {
                myListener = new TcpListener(IPAddress.Loopback, port)
                {
                    ExclusiveAddressUse = false
                };

                var httpSender = new HttpSender();

                cancellationTokenSource = new CancellationTokenSource();

                myServerInstance = myListener.ToHttpListenerObservable(cancellationTokenSource.Token)
                                   .Do(r =>
                {
                    AndroidBridge.d(TAG, "[START] \"" + r.Path + "\" IP: " + ipString(r.RemoteIpEndPoint));
                })
                                   // Send reply to browser
                                   .Select(r => Observable.FromAsync(() => SendResponseAsync(r, httpSender)))
                                   .Concat()
                                   .Subscribe(r =>
                {
                    //Console.WriteLine("Reply sent.");
                },
                                              ex =>
                {
                    AndroidBridge.e(TAG, ex.ToString());
                },
                                              () =>
                {
                    AndroidBridge.d(TAG, "Server completed");
                });
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex.ToString());
            }
        }
コード例 #15
0
        string EP_checkDomain(IHttpRequestResponse req)
        {
            string result = "";

            try
            {
                var    reqJSON = readReqBodyAsString(req);
                string domain  = SpinResultHelper.getDomainName(reqJSON).Trim(new char[] { ' ', '"' });
                domainHistory.Add(domain);

                string reason = "";
                bool   block  = isBlockedFullFlow(new Uri(domain), out reason);


                if (block)
                {
                    try
                    {
                        File.AppendAllLines(Filenames.BLOCK_LOG.getAppPublic(), new[] {
                            string.Format("[{0}] {1} {2}", DateTime.Now, domain, reason)
                        });
                    }
                    catch (Exception ex)
                    {
                        AndroidBridge.e(TAG, ex);
                    }
                }

                result = SpinResultHelper.domainCategoryResult(block);
            }
            catch (Exception ex)
            {
                result = "{\"error\":\"0\"}".Replace("0", ex.ToString());
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #16
0
        private static string ForceLockDate(DateTime date)
        {
            string result = "";

            try
            {
                string unlockPath = Filenames.LOCK_DATE.getAppPrivate();

                AndroidBridge.d(TAG, "(*) Locking until '" + date.ToString() + "'");
                if (File.Exists(unlockPath))
                {
                    File.Delete(unlockPath);
                }
                File.WriteAllText(unlockPath, date.ToString());

                result = "Sucess! Locked to " + date.ToString();
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex);
                result = ex.ToString();
            }
            return(result);
        }
コード例 #17
0
        public void StartFlow()
        {
            try
            {
                // Reload policies:
                FilteringObjects.httpPolicy.reloadPolicy(File.ReadAllText(Filenames.HTTP_POLICY.getAppPrivate()));
                FilteringObjects.timePolicy.reloadPolicy(File.ReadAllText(Filenames.TIME_POLICY.getAppPrivate()));

                if (!AndroidBridge.isForegroundServiceUp())
                {
                    AndroidBridge.OnForgroundServiceStart = () =>
                    {
                        AndroidBridge.d(TAG, "Starting filtering flow");
                        myHTTPServer.StartHttpServer();
                        StartPeriodicTasks();
                    };

                    AndroidBridge.OnForgroundServiceStop = () =>
                    {
                        AndroidBridge.d(TAG, "Stopping filtering flow");
                        StopPeriodicTasks();
                        myHTTPServer.StopHTTPServer();
                    };

                    AndroidBridge.StartForgroundService();
                }
                else
                {
                    AndroidBridge.ToastIt("Service already up!");
                }
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex);
            }
        }
コード例 #18
0
        public void scheduleRepeated()
        {
            TimeSpan WIFI_PERIOD = (FilteringObjects.isFiltering && FilteringObjects.isInWifiBlockZone) ?
                                   WIFI_PERIOD_BLOCKED : WIFI_PERIOD_ALLOWED;

            int taskID = AndroidBridge.scheduleJob(WIFI_PERIOD, WIFI_PERIOD + TimeSpan.FromSeconds(10), null,
                                                   (finishFunc) => {
                if (AndroidBridge.isForegroundServiceUp())
                {
                    AndroidBridge.StartWifiScanning();
                    scheduleRepeated();
                }
                finishFunc(false);
            },
                                                   () => AndroidBridge.isForegroundServiceUp(),
                                                   null,
                                                   () => false
                                                   );

            if (taskID < 0)
            {
                AndroidBridge.e(TAG, "Failed to schedule job.");
            }
        }
コード例 #19
0
        public static string getDomainName(string jsonBody)
        {
            string result = "";

            try
            {
                var jsonObject = JObject.Parse(jsonBody);
                var version    = jsonObject["v"].ToString();
                if (version == "1")
                {
                    var domainName = jsonObject["domainName"];
                    result = domainName.ToString();
                }
                else
                {
                    throw new Exception("Unknown Version of domain request");
                }
            }
            catch (Exception ex)
            {
                AndroidBridge.e(TAG, ex.ToString());
            }
            return(result);
        }
コード例 #20
0
        public static void WifiCheckerCallback(List <string> wifiLists, TimeSpan?timeSinceLastScan, Exception callbackEx)
        {
            string reason         = "init";
            bool   shouldLogDebug = false;

            if (callbackEx != null)
            {
                // Dont even check, bad zone:
                FilteringObjects.isInWifiBlockZone = true;

                reason         = "callback with exepction.";
                shouldLogDebug = true;
            }
            else
            {
                TimeSpan actualTime = (timeSinceLastScan ?? TimeSpan.FromDays(1));
                if (actualTime > FilteringServiceFlow.WIFI_PERIOD_BLOCKED)
                {
                    // Dont even check, bad zone:
                    FilteringObjects.isInWifiBlockZone = true;

                    reason         = "results are old, wifi off? (Time: " + actualTime + ")";
                    shouldLogDebug = true;
                }
                else
                {
                    bool inBadZoneResult = true;
                    try
                    {
                        if (!File.Exists(Filenames.WIFI_POLICY.getAppPrivate()))
                        {
                            File.WriteAllText(Filenames.WIFI_POLICY.getAppPrivate(), "");
                        }

                        IEnumerable <string> currentRules = File.ReadAllLines(Filenames.WIFI_POLICY.getAppPrivate());
                        List <string>        newRules     = new List <string>();

                        //TODO Reason what wifi blocked.

                        inBadZoneResult = CheckBlacklistedWifiStandard.WifiHelper.fastBlockZoneCheck(wifiLists, currentRules, out newRules,
                                                                                                     (log) => { /* AndroidBridge.d(TAG, "[CheckBlacklistedWifi] " + log);*/ }, out reason
                                                                                                     );

                        File.WriteAllLines(Filenames.WIFI_POLICY.getAppPrivate(), newRules);
                    }
                    catch (Exception ex2)
                    {
                        AndroidBridge.e(TAG, ex2);
                        inBadZoneResult = false; // allow in case of exceptions...

                        reason = "Exception processing Wifi Algo";
                    }

                    if (!showReason && FilteringObjects.isInWifiBlockZone != inBadZoneResult)
                    {
                        AndroidBridge.ToastIt("Changing blackzone to: " + inBadZoneResult);
                    }

                    FilteringObjects.isInWifiBlockZone = inBadZoneResult;
                }
            }

            reason = "[Blockzone? " + FilteringObjects.isInWifiBlockZone + "] " + reason;

            if (showReason)
            {
                AndroidBridge.ToastIt(reason);
                showReason = false; // Reset it until user mark it again.
            }

            if (shouldLogDebug)
            {
                if (callbackEx != null)
                {
                    reason += "\nCallback Exception:\n" + callbackEx.ToString();
                }
                AndroidBridge.d(TAG, reason);
            }
        }