public override void handleGETRequest(HttpProcessor p) { BasicEventTimer bet = new BasicEventTimer(); bet.Start("GET " + p.requestedPage); try { p.tcpClient.NoDelay = true; string pageLower = p.requestedPage.ToLower(); if (pageLower == "json") { p.writeFailure("405 Method Not Allowed", "json API requests must use the POST method"); } else if (p.requestedPage.StartsWith("WebSocketClientProxy/")) { WebSocketProxy.HandleWebSocketClientProxyRequest(p); } else if (p.requestedPage.StartsWith("WebSocketHostProxy/")) { WebSocketProxy.HandleWebSocketHostProxyResponse(p); } //else if (p.requestedPage == "windowskeycodes") //{ // p.writeSuccess(); // p.outputStream.Write("<table><thead><tr><th>KeyCode</th><th>Name</th></tr></thead><tbody>"); // HashSet<int> addedKeyCodes = new HashSet<int>(); // foreach (int keyCode in ((IEnumerable<int>)Enum.GetValues(typeof(System.Windows.Forms.Keys)))) // { // p.outputStream.Write("<tr><td>" + keyCode + "</td><td>" + (System.Windows.Forms.Keys)keyCode + "</td></tr>"); // } // p.outputStream.Write("</tbody></table>"); //} else { #region www DirectoryInfo WWWDirectory = new DirectoryInfo(ServiceWrapper.settings.GetWWWDirectoryBase()); string wwwDirectoryBase = WWWDirectory.FullName.Replace('\\', '/').TrimEnd('/') + '/'; FileInfo fi = null; if (p.requestedPage == "") { fi = GetDefaultFile(wwwDirectoryBase); } else { try { fi = new FileInfo(wwwDirectoryBase + p.requestedPage); } catch { fi = GetDefaultFile(wwwDirectoryBase); } } string targetFilePath = fi.FullName.Replace('\\', '/'); if (!targetFilePath.StartsWith(wwwDirectoryBase) || targetFilePath.Contains("../")) { p.writeFailure("400 Bad Request"); return; } if (webpackProxy != null) { // Handle hot module reload provided by webpack dev server. switch (fi.Extension.ToLower()) { case ".js": case ".map": case ".css": case ".json": bet.Start("Proxy Start"); webpackProxy.Proxy(p); bet.Start("Proxy End"); return; } } if (!fi.Exists) { fi = GetDefaultFile(wwwDirectoryBase); if (!fi.Exists) { p.writeFailure(); return; } } if ((fi.Extension == ".html" || fi.Extension == ".htm") && fi.Length < 256000) { bet.Start("Write HTML"); string html = File.ReadAllText(fi.FullName); try { //html = html.Replace("%%REMOTEIP%%", p.RemoteIPAddressStr); html = html.Replace("%%SYSTEM_NAME%%", "SHRD"); html = html.Replace("%%APP_VERSION%%", AppVersion.VersionNumber); html = html.Replace("%%APPPATH%%", "/"); } catch (Exception ex) { Logger.Debug(ex); } p.writeSuccess(Mime.GetMimeType(fi.Extension)); p.outputStream.Write(html); p.outputStream.Flush(); } else { bet.Start("Write Response"); if (fi.LastWriteTimeUtc.ToString("R") == p.GetHeaderValue("if-modified-since")) { p.writeSuccess(Mime.GetMimeType(fi.Extension), -1, "304 Not Modified"); return; } using (FileStream fs = fi.OpenRead()) { p.writeSuccess(Mime.GetMimeType(fi.Extension), fi.Length, additionalHeaders: GetCacheLastModifiedHeaders(TimeSpan.FromHours(1), fi.LastWriteTimeUtc)); p.outputStream.Flush(); fs.CopyTo(p.tcpStream); p.tcpStream.Flush(); } } #endregion } } finally { bet.Stop(); //Logger.Info(bet.ToString("\r\n")); } }
public override void handleGETRequest(HttpProcessor p) { BasicEventTimer bet = new BasicEventTimer(); bet.Start("GET " + p.requestedPage); try { string pageLower = p.requestedPage.ToLower(); if (pageLower == "json") { p.writeFailure("405 Method Not Allowed", "json API requests must use the POST method"); } else if (pageLower == "broadlinkcommands.json") { if (File.Exists(ServiceWrapper.BroadLinkCommandsFile)) { byte[] content = File.ReadAllBytes(ServiceWrapper.BroadLinkCommandsFile); p.writeSuccess("application/json", content.Length); p.outputStream.Flush(); p.tcpStream.Write(content, 0, content.Length); } else { p.writeFailure(); } } else if (pageLower == "itachcommands.json") { if (File.Exists(ServiceWrapper.iTachCommandsFile)) { byte[] content = File.ReadAllBytes(ServiceWrapper.iTachCommandsFile); p.writeSuccess("application/json", content.Length); p.outputStream.Flush(); p.tcpStream.Write(content, 0, content.Length); } else { p.writeFailure(); } } else if (pageLower == "downloadconfiguration") { string filename = "HotkeyAutomationConfig_" + Environment.MachineName + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".zip"; List <KeyValuePair <string, string> > additionalHeaders = new List <KeyValuePair <string, string> >(); additionalHeaders.Add(new KeyValuePair <string, string>("Content-Disposition", "attachment; filename=\"" + filename + "\"")); p.writeSuccess("application/zip", additionalHeaders: additionalHeaders); p.outputStream.Flush(); ConfigurationIO.WriteToStream(p.tcpStream); } else { #region www DirectoryInfo WWWDirectory = new DirectoryInfo(ServiceWrapper.config.GetWWWDirectoryBase()); string wwwDirectoryBase = WWWDirectory.FullName.Replace('\\', '/').TrimEnd('/') + '/'; FileInfo fi = null; if (p.requestedPage == "") { fi = GetDefaultFile(wwwDirectoryBase); } else { try { fi = new FileInfo(wwwDirectoryBase + p.requestedPage); } catch { fi = GetDefaultFile(wwwDirectoryBase); } } string targetFilePath = fi.FullName.Replace('\\', '/'); if (!targetFilePath.StartsWith(wwwDirectoryBase) || targetFilePath.Contains("../")) { p.writeFailure("400 Bad Request"); return; } if (webpackProxy != null) { // Handle hot module reload provided by webpack dev server. switch (fi.Extension.ToLower()) { case ".js": case ".map": case ".css": case ".json": bet.Start("Proxy Start"); webpackProxy.Proxy(p); bet.Start("Proxy End"); return; } } if (!fi.Exists) { fi = GetDefaultFile(wwwDirectoryBase); if (!fi.Exists) { p.writeFailure(); return; } } if ((fi.Extension == ".html" || fi.Extension == ".htm") && fi.Length < 256000) { bet.Start("Write HTML"); string html = File.ReadAllText(fi.FullName); try { html = html.Replace("%%SYSTEM_NAME%%", ServiceWrapper.config.systemName); html = html.Replace("%%APP_VERSION%%", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); html = html.Replace("%%APPPATH%%", "/"); } catch (Exception ex) { Logger.Debug(ex); } p.writeSuccess(Mime.GetMimeType(fi.Extension)); p.outputStream.Write(html); p.outputStream.Flush(); } else { bet.Start("Write Response"); if (fi.LastWriteTimeUtc.ToString("R") == p.GetHeaderValue("if-modified-since")) { p.writeSuccess(Mime.GetMimeType(fi.Extension), -1, "304 Not Modified"); return; } using (FileStream fs = fi.OpenRead()) { p.writeSuccess(Mime.GetMimeType(fi.Extension), fi.Length, additionalHeaders: GetCacheLastModifiedHeaders(TimeSpan.FromHours(1), fi.LastWriteTimeUtc)); p.outputStream.Flush(); fs.CopyTo(p.tcpStream); p.tcpStream.Flush(); } } #endregion } } finally { bet.Stop(); //Logger.Info(bet.ToString("\r\n")); } }
/// <summary> /// Checks for duplicates, adds the event to the database, and runs all enabled filters against it, within a single transaction. /// </summary> /// <param name="ev">The event to run filters against.</param> /// <returns>A BasicEventTimer containing timing data.</returns> public BasicEventTimer AddEventAndRunEnabledFilters(Event ev) { BasicEventTimer bet = new BasicEventTimer(); if (ev == null) { throw new ArgumentNullException("ev", "FilterEngine.AddEventAndRunEnabledFilters was given a null event."); } try { bet.Start("Begin Transaction"); db.LockedTransaction(() => { try { bet.Start("Dupe Check"); // If our response is not received by the client, they will most likely submit again, causing a duplicate to be received. // Check for duplicate submissions. List <Event> events = db.GetEventsByDate(ev.Date, ev.Date); bool anyDupe = events.Any(existing => { if (existing.Date == ev.Date && existing.EventType == ev.EventType && existing.SubType == ev.SubType && existing.Message == ev.Message && existing.GetTagCount() == ev.GetTagCount()) { // All else is the same. Compare tags. List <Tag> existingTags = existing.GetAllTags(); existingTags.Sort(CompareTags); List <Tag> newTags = ev.GetAllTags(); newTags.Sort(CompareTags); for (int i = 0; i < existingTags.Count; i++) { if (existingTags[i].Key != newTags[i].Key || existingTags[i].Value != newTags[i].Value) { return(false); } } return(true); } return(false); }); // Skip adding the event if it is a duplicate. if (anyDupe) { bet.Start("Duplicate Found"); return; } // Add the event to the database bet.Start("Insert"); db.AddEvent(ev); if (Settings.data.verboseSubmitLogging) { Util.SubmitLog(ProjectName, "Event " + ev.EventId + " Inserted"); } // Run Filters bet.Start("Filter"); RunEnabledFiltersAgainstEvent(ev, true); bet.Start("Commit Transaction"); } catch { bet.Start("Rollback Transaction"); } }); bet.Stop(); } catch (Exception ex) { bet.Stop(); throw new FilterException(bet, "An exception was thrown while adding and filtering a new event.", ex); } return(bet); }
/// <summary> /// Attempts to capture a screenshot of the current desktop. /// </summary> /// <returns></returns> private Screenshot CaptureScreenshot(int x, int y, int width, int height) { BasicEventTimer bet = new BasicEventTimer("0.000"); bet.Start("Setup"); if (!CreateCaptureHandleIfNecessary()) { return(null); } NativeMethods.BITMAPINFO bmpInfo = new NativeMethods.BITMAPINFO(); using (AutoDisposeHandle bmp = AutoDisposeHandle.Create(NativeMethods.CreateCompatibleBitmap(deviceContext, 1, 1), h => NativeMethods.DeleteObject(h))) { bmpInfo.bmiHeader.biSize = Marshal.SizeOf(typeof(NativeMethods.BITMAPINFOHEADER)); if (0 == NativeMethods.GetDIBits(deviceContext, bmp, 0, 1, null, ref bmpInfo, NativeMethods.DIB_Color_Mode.DIB_RGB_COLORS)) { Win32Helper.ThrowLastWin32Error(); } bmpInfo.bmiHeader.biSize = Marshal.SizeOf(typeof(NativeMethods.BITMAPINFO)); if (0 == NativeMethods.GetDIBits(deviceContext, bmp, 0, 1, null, ref bmpInfo, NativeMethods.DIB_Color_Mode.DIB_RGB_COLORS)) { Win32Helper.ThrowLastWin32Error(); } } bmpInfo.bmiHeader.biWidth = width; bmpInfo.bmiHeader.biHeight = -height; bmpInfo.bmiHeader.biSizeImage = 0; // Create memory device context. When done, delete it. using (AutoDisposeHandle dc = AutoDisposeHandle.Create(NativeMethods.CreateCompatibleDC(IntPtr.Zero), h => NativeMethods.DeleteDC(h))) { if (dc == null) { Win32Helper.ThrowLastWin32Error("Failed to create memory device context"); } // Create "DIB Section" (a Bitmap, more or less). When done, delete it. IntPtr ppvBits = new IntPtr(); using (AutoDisposeHandle newDib = AutoDisposeHandle.Create(NativeMethods.CreateDIBSection(dc, ref bmpInfo, 0U, out ppvBits, IntPtr.Zero, 0U), h => NativeMethods.DeleteObject(h))) //using (AutoDisposeHandle newDib = AutoDisposeHandle.Create(NativeMethods.CreateCompatibleBitmap(deviceContext, width, height), h => NativeMethods.DeleteObject(h))) { if (newDib == null) { Win32Helper.ThrowLastWin32Error("Failed to create DIB Section"); } // Assign new DIB Section to our memory device context. When done, put back the old DIB Section. using (AutoDisposeHandle oldDib = AutoDisposeHandle.Create(NativeMethods.SelectObject(dc, newDib), h => NativeMethods.SelectObject(dc, h))) { if (oldDib == null) { Win32Helper.ThrowLastWin32Error("Failed to assign new DIB Section to memory device context"); } bet.Start("BitBlt"); // Copy data from the screen to our memory device context if (!NativeMethods.BitBlt(dc, 0, 0, width, height, deviceContext, x, y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt)) { Logger.Debug("BitBlt failed with error code: " + Win32Helper.GetLastWin32Error()); ClearCaptureHandle(); DesktopManager.ShouldReassociate = true; } else { bet.Start("new Screenshot/Copy bits"); Screenshot screenshot = new Screenshot(width, height, bmpInfo.bmiHeader.biBitCount); Marshal.Copy(ppvBits, screenshot.Buffer, 0, screenshot.Buffer.Length); bet.Stop(); //Logger.Info(bet.ToString(Environment.NewLine)); return(screenshot); } } } } return(null); }