static void mlist_onClientConnect(ClientWebRequest request) { try { engine.NtfyConnection(request); } catch (Exception er) { MemoryStream errstream = new MemoryStream(); StreamWriter mwriter = new StreamWriter(errstream); mwriter.Write("<html><head><title>An error has occured</title></head><body><pre><h2>Whoops! We've had a 500 Internal Server Error! To the embarassment of the developer, the full error is shown below</h2><hr />"+er.ToString()+"</pre></body></html>"); mwriter.Flush(); errstream.Position = 0; ClientHttpResponse response = new ClientHttpResponse(); response.len = errstream.Length; response.StatusCode = "500 Internal Server Error"; response.ContentType = "text/html"; response.WriteHeader(request.stream); response.WriteStream(errstream, request.stream, 16384); try { request.stream.Dispose(); }catch(Exception err) { } } }
public static void ProcessRequest(ClientWebRequest equest) { lock(syncobj) { if(db == null) { db = new PubKeyDatabase("default",File.Open("OpenNetDB_client",FileMode.OpenOrCreate)); } if(db.Length == 0) { db.AddPublicKey(db.GenPublicPrivateKey(2048)); db.GetPublicKeyOnly(db[0]); } Uri url = new Uri("http:/"+equest.UnsanitizedRelativeURI.Replace("idw.local.ids","127.0.0.1")); if(!drivers.ContainsKey(url.Host)) { Console.WriteLine("Connecting to "+url.Host); HttpWebRequest request = HttpWebRequest.Create("http://"+url.Host+"/OpenNetProvider") as HttpWebRequest; request.AllowWriteStreamBuffering = false; Stream receiver = new TrashyStream(request.GetResponse().GetResponseStream()); BinaryReader mreader = new BinaryReader(receiver); byte[] guid = mreader.ReadBytes(16); Console.WriteLine(BitConverter.ToString(guid)); request = HttpWebRequest.Create("http://"+url.Host+"/OpenNetProvider") as HttpWebRequest; request.Method = "POST"; request.ContentLength = 9999999999; request.AllowWriteStreamBuffering = false; Stream sender = new TrashyStream(request.GetRequestStream()); BinaryWriter mwriter = new BinaryWriter(sender); mwriter.Write(guid); mwriter.Flush(); byte[] theirpubkey = mreader.ReadBytes(mreader.ReadInt32()); Stream dbStr = File.Open("keyDB.db", FileMode.OpenOrCreate); byte[] ourpublickey = db.GetPublicKeyOnly(db[0]); byte[] ourprivatekey = db[0]; mwriter.Write(ourpublickey.Length); mwriter.Write(ourpublickey); mwriter.Flush(); db.AddPublicKey(theirpubkey); Stream securedStream = new TrashyStream(db.CreateAuthenticatedStream(ourprivatekey, new DualStream(sender, receiver), 32)); Console.WriteLine("Secure stream negotiated"); driver = new OpenNetProtocolDriver(securedStream); drivers.Add(url.Host,driver); Console.WriteLine("Driver initialized"); } mvent.Reset(); currentRequest = equest; currentURL = url; driver = drivers[url.Host]; drivers[url.Host].onConnectionEstablished += HandleonConnectionEstablished; drivers[url.Host].OpenStream(); mvent.WaitOne(); } }
public string CurrentDirectory(string queryStringValue, ClientWebRequest request) { Dictionary<string,string> querystring = request.QueryString; if(!querystring.ContainsKey(queryStringValue)) { querystring.Add(queryStringValue,Path.GetPathRoot(Environment.CurrentDirectory)); } return querystring[queryStringValue]; }
public string loginstatus(ClientWebRequest request) { if (request.QueryString.ContainsKey("sessionID")) { string sesid = request.QueryString["sessionID"]; if (!sessions.ContainsKey(request.QueryString["sessionID"])) { sessions.Add(sesid, new SessionInformation()); } SessionInformation session = sessions[sesid]; if(request.Method == "POST") { Dictionary<string,string> formdata = request.Form; Stream fstr = File.Open(formdata["username"],FileMode.OpenOrCreate); try { session.fs = new IndexedFS(new Filesystem(fstr,formdata["pswd"],1024*1024,1024*1024*512)); //return "Authorization success!"; session.UserName = formdata["username"]; bool dirsetup = false; foreach(string et in session.fs.Directories) { if(et == formdata["username"]) { dirsetup = true; } } if(!dirsetup) { session.fs.CreateDirectory(formdata["username"]); } session.fs.Commit(); }catch(Exception er) { fstr.Close(); return "Invalid password"; } } if(session.fs !=null) { ClientHttpResponse response = new ClientHttpResponse(); request.ContinueProcessing = false; response.Redirect("profile.html?sessionID="+request.QueryString["sessionID"],false,request.stream); } return sesid; } else { return ""; } }
public void onRequest(ClientWebRequest request) { if(request.Method == "GET") { //Initiate session ClientHttpResponse response = new ClientHttpResponse(); response.ContentType = "text/html"; response.len = 1024*1024*300; response.StatusCode = "200 OK"; response.WriteHeader(request.stream); ClientSession session = new ClientSession(); session.sessionID = Guid.NewGuid(); TrashyStream garbage = new TrashyStream(request.stream); session.writer = garbage; BinaryWriter mwriter = new BinaryWriter(garbage); mwriter.Write(session.sessionID.ToByteArray()); mwriter.Flush(); lock(ClientSession.sessions) { ClientSession.sessions.Add(session.sessionID,session); } session.WaitHandle.WaitOne(); }else { try { TrashyStream reader = new TrashyStream(request.stream); BinaryReader mreader = new BinaryReader(reader); ClientSession currentSession = ClientSession.sessions[new Guid(mreader.ReadBytes(16))]; currentSession.reader = reader; BinaryWriter mwriter = new BinaryWriter(currentSession.writer); byte[] ourprivatekey = db[0]; byte[] ourpubkey = db.GetPublicKeyOnly(ourprivatekey); mwriter.Write(ourpubkey.Length); mwriter.Write(ourpubkey); mwriter.Flush(); byte[] theirpubkey = mreader.ReadBytes(mreader.ReadInt32()); if(!db.IsKeyTrusted(theirpubkey)) { db.AddPublicKey(theirpubkey); db.Commit(); } currentSession.securedStream = new TrashyStream(db.CreateAuthenticatedStream(ourprivatekey,new DualStream(currentSession.writer,currentSession.reader),32)); Console.WriteLine("Secure stream negotiated"); currentSession.pubKey = BitConverter.ToString(theirpubkey); OpenNetProtocolDriver driver = new OpenNetProtocolDriver(currentSession); }catch(Exception er) { Console.WriteLine(er); } } }
public string applicationManager(ClientWebRequest request) { if(request.QueryString.ContainsKey("action")) { if(request.QueryString["action"] == "terminate") { ConfigManager.TerminateApplication(request.QueryString["id"]); } if(request.QueryString["action"] == "startup") { ConfigManager.setStartup(request.QueryString["id"]); } } StringBuilder mbuilder = new StringBuilder(); mbuilder.AppendLine("<h2>Web applications</h2><hr />"); mbuilder.AppendLine("<table border=\"1\" inst_id=\"maintable\">"); foreach(string et in ConfigManager.GetApplications()) { mbuilder.AppendLine("<tr><td inst_id=\"appname\">"+et+"</td></tr>"); } mbuilder.AppendLine("</table>"); return mbuilder.ToString(); }
public void ParseHTMLDocument(ref string HTML, ClientWebRequest request) { HTML = Link(HTML); mtype = GetType(); StringBuilder mbuilder = new StringBuilder(); int offset = 0; while (offset < HTML.Length) { int idex = HTML.IndexOf("<$server=", offset); if (idex > -1) { string sbstr = HTML.Substring(idex,HTML.IndexOf(">",idex)-idex+1); //TODO: Implement this string name = sbstr.Substring(sbstr.IndexOf("=")+1,sbstr.IndexOf("(")-sbstr.IndexOf("=")-1); object[] args; if (sbstr.Contains("()")) { args = new string[0]; } else { string argstr = sbstr.Substring(sbstr.IndexOf("(") + 1, sbstr.IndexOf(")") - sbstr.IndexOf("(") - 1); args = argstr.Split(','); } object[] realargs = new object[args.Length + 1]; for (int i = 0; i < args.Length; i++) { realargs[i] = args[i]; } realargs[realargs.Length - 1] = request; HTML = HTML.Replace(sbstr, InvokeMethod(name,realargs)); offset = idex + 1; } else { break; } } }
public string UserName(ClientWebRequest request) { SessionInformation session = sessions[request.QueryString["sessionID"]]; return session.UserName; }
public void NtfyConnection(ClientWebRequest request) { string appname; if(request.UnsanitizedRelativeURI.Length>5) { int el; if(request.UnsanitizedRelativeURI.IndexOf("/",request.UnsanitizedRelativeURI.IndexOf("/")+1) <0) { el = request.UnsanitizedRelativeURI.Length-(request.UnsanitizedRelativeURI.IndexOf("/")+1); }else { el = request.UnsanitizedRelativeURI.IndexOf("/",request.UnsanitizedRelativeURI.IndexOf("/")+1)-1; } appname = request.UnsanitizedRelativeURI.Substring(request.UnsanitizedRelativeURI.IndexOf("/")+1,el); }else { ClientHttpResponse response = new ClientHttpResponse(); response.Redirect(startupApplication,true,request.stream); request.ContinueProcessing = false; return; } doRequest: if(request.ProxyConnection) { OpenNetProxySvc.ProxyHandler.ProcessRequest(request); }else { if(instances.ContainsKey(appname)) { try { instances[appname].ntfyRequest(request); if(request.UnmanagedConnection) { Console.WriteLine("Unmanaged connection found"); return; } }catch(RemotingException er) { Console.WriteLine("Remoting instance for "+appname+" has died. Respawning application...."); lock(instances) { AppDomain.Unload(domains[appname]); instances.Remove(appname); domains.Remove(appname); } goto doRequest; } }else { //Search for application bool isfound = false; foreach(string et in Directory.GetDirectories(Environment.CurrentDirectory)) { string it = et.Replace("\\","/"); string ix = it.Substring(it.LastIndexOf("/")+1); if(ix == appname) { isfound = true; } } if(!isfound) { StreamWriter mwriter = new StreamWriter(request.stream); mwriter.WriteLine("<html>"); mwriter.WriteLine("<head>"); mwriter.WriteLine("<title>Application not found</title>"); mwriter.WriteLine("</head>"); mwriter.WriteLine("<body>"); mwriter.WriteLine("<h1>Unable to locate application "+appname+"</h1><hr />The application you are looking for does not exist on this server."); mwriter.WriteLine("</body>"); mwriter.WriteLine("</html>"); mwriter.Flush(); }else { Stream mstr = File.Open(Environment.CurrentDirectory+"\\"+appname+"\\"+appname+".dll",FileMode.Open); byte[] buffer = new byte[mstr.Length]; mstr.Read(buffer,0,buffer.Length); mstr.Close(); LoadApplication(buffer,appname); goto doRequest; } } } byte[] mbuffer = new byte[16384]; int total = 0; try { if(request.ExpectedContentLength>0) { while(true) { int count = request.stream.Read(mbuffer,0,mbuffer.Length); total+=count; if(count <=0 || total>=request.ExpectedContentLength) { break; } } } }catch(Exception er) { } request.stream.Dispose(); }
public string ProfilePicture(ClientWebRequest request) { SessionInformation session = sessions[request.QueryString["sessionID"]]; if(request.QueryString.ContainsKey("GetProfilePic")) { foreach(string et in session.fs.OpenDir(request.QueryString["GetProfilePic"]).Files) { if(et == "pic") { Bitmap tmap = new Bitmap(32,32); Graphics aix = Graphics.FromImage(tmap); Bitmap amage = new Bitmap(session.fs.OpenDir(request.QueryString["GetProfilePic"]).OpenFile("pic")); aix.DrawImage(amage,new Rectangle(0,0,32,32)); aix.Dispose(); amage.Dispose(); MemoryStream ystream = new MemoryStream(); tmap.Save(ystream,System.Drawing.Imaging.ImageFormat.Jpeg); ystream.Position = 0; tmap.Dispose(); ClientHttpResponse _response = new ClientHttpResponse(); _response.len = ystream.Length; _response.ContentType = "image/jpg"; _response.WriteHeader(request.stream); _response.WriteStream(ystream,request.stream,16384); } } Bitmap mmap = new Bitmap(32,32); Graphics mfix = Graphics.FromImage(mmap); mfix.DrawLine(Pens.Red,new Point(0,0),new Point(32,32)); mfix.DrawLine(Pens.Red,new Point(0,32),new Point(32,0)); mfix.Dispose(); MemoryStream mstream = new MemoryStream(); mmap.Save(mstream,System.Drawing.Imaging.ImageFormat.Jpeg); mmap.Dispose(); mstream.Position = 0; ClientHttpResponse response = new ClientHttpResponse(); response.len = mstream.Length; response.ContentType = "image/jpg"; response.WriteHeader(request.stream); response.WriteStream(mstream,request.stream,16384); request.ContinueProcessing = false; return ""; } return "profile.html?GetProfilePic="+session.UserName+"&sessionID="+request.QueryString["sessionID"]; }
public string sessionKey(ClientWebRequest request) { if (!request.QueryString.ContainsKey("sessionID")) { Guid msession = Guid.NewGuid(); sessions.Add(msession.ToString(), new SessionInformation()); return msession.ToString(); } else { return request.QueryString["sessionID"]; } }
public void onclientconnect(object sender) { Stream mstream = sender as Stream; if(resetConnections) { try { mstream.Dispose(); }catch(Exception) { } } try { //Parse web request BinaryReader mreader = new BinaryReader(mstream); List<string> headers = new List<string>(); while (true) { string txt = ReadLine(mreader); if (txt.Length < 2) { break; } headers.Add(txt); } ClientWebRequest mreq = new ClientWebRequest(mstream, headers); using (mreq.stream) { if (onClientConnect != null) { onClientConnect.Invoke(mreq); } } } catch (Exception) { } }
public string downloadTable(ClientWebRequest request) { if(request.QueryString.ContainsKey("action")) { if(request.QueryString["action"] == "pause") { Download.downloads[Convert.ToInt32(request.QueryString["inst"])].Pause(); } if(request.QueryString["action"] == "resume") { Download.downloads[Convert.ToInt32(request.QueryString["inst"])].Resume(); } if(request.QueryString["action"] == "abort") { Download.downloads[Convert.ToInt32(request.QueryString["inst"])].Abort(); } return ""; } if(request.QueryString.ContainsKey("downloadFile")) { Stream fstr = File.Open(request.QueryString["downloadFile"],FileMode.Open,FileAccess.Read,FileShare.ReadWrite); ClientHttpResponse response = new ClientHttpResponse(); response.StatusCode = "200 OK"; response.ContentType = ConfigManager.getMimeType(request.QueryString["downloadFile"]); response.len = fstr.Length; response.AddHeader("Content-Disposition: attachment; filename=\""+Path.GetFileName(request.QueryString["downloadFile"])+"\""); response.WriteHeader(request.stream); request.ContinueProcessing = false; try { Download mload = new Download(request.QueryString["downloadFile"],fstr,request.stream,fstr.Length); mload.Begin(); }catch(Exception er) { } return ""; } try { statusUpdateEvent.WaitOne(5000); statusUpdateEvent.Reset(); }catch(Exception) { } StringBuilder mbuilder = new StringBuilder(); mbuilder.AppendLine("<table border=\"1\" inst_id=\"maintable\">"); mbuilder.AppendLine("<tr><td><b><u>Connection name</u></b></td><td><b><u>Progress</u></b></td><td><b><u>Status</u></b></td></tr>"); try { int i = 0; lock(Download.downloads) { foreach(Download et in Download.downloads) { string progress = "<div style=\"width:"+((int)(((float)et._progress/(float)et._size)*100f)).ToString()+"%;background-color:Green;\">PROGRESS</div>"; string actions = ""; if(et.paused) { actions = "PAUSED"; }else { actions = "IN PROGRESS"; } if(et.haserror) { actions = "ERROR"; } mbuilder.AppendLine("<tr dlID=\""+i.ToString()+"\"><td>"+et.name+"</td><td style=\"background-color:Red;\">"+progress+"</td><td inst_id=\"status\">"+actions+"</td></tr>"); i++; } mbuilder.AppendLine("</table>"); } }catch(Exception) { } return mbuilder.ToString(); }
public void ntfyRequest(ClientWebRequest request) { VM.GetType().GetMethod("onRequest").Invoke(VM,new object[] {request}); }
public void onRequest(ClientWebRequest request) { try { if(request.UnsanitizedRelativeURI.Contains("transparent.png")) { if(transparentBitmap == null) { Bitmap mmap = new Bitmap(4,4); Graphics mfix = Graphics.FromImage(mmap); mfix.Clear(Color.FromArgb(106,0,0,255)); mfix.Dispose(); MemoryStream mstream = new MemoryStream(); mmap.Save(mstream,ImageFormat.Png); mstream.Position = 0; transparentBitmap = mstream.ToArray(); mstream.Dispose(); mmap.Dispose(); } ClientHttpResponse response = new ClientHttpResponse(); response.ContentType = "image/png"; response.len = transparentBitmap.Length; response.StatusCode = "200 OK"; response.WriteHeader(request.stream); request.stream.Write(transparentBitmap,0,transparentBitmap.Length); } if(request.UnsanitizedRelativeURI.Contains("backgroundImg.jpg")) { if(bitmapData == null) { Bitmap mmap = new Bitmap(1024,1024); Graphics mfix = Graphics.FromImage(mmap); mfix.Clear(Color.Black); mfix.FillRectangle(new LinearGradientBrush(new Point(0,0),new Point(0,512),Color.Blue,Color.Black),new Rectangle(0,0,1024,512)); mfix.DrawString("OpenServer 2012 - Administration Console\nApplication startup time: "+DateTime.Now.ToString(),new Font(FontFamily.GenericMonospace,24),Brushes.White,new Point(0,0)); mfix.Dispose(); MemoryStream mstream = new MemoryStream(); mmap.Save(mstream,ImageFormat.Jpeg); mstream.Position = 0; bitmapData = mstream.ToArray(); mstream.Dispose(); } ClientHttpResponse response = new ClientHttpResponse(); response.ContentType = "image/jpeg"; response.len = bitmapData.Length; response.StatusCode = "200 OK"; response.WriteHeader(request.stream); request.stream.Write(bitmapData,0,bitmapData.Length); request.stream.Flush(); return; } string path = Environment.CurrentDirectory+request.UnsanitizedRelativeURI.Replace("/",Path.DirectorySeparatorChar.ToString()); if(path.IndexOf("?")>1) { path = path.Substring(0,path.IndexOf("?")); } if(File.Exists(path)) { using(Stream fstr = File.Open(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)) { string mimetype; string str = path.Substring(path.LastIndexOf(".")); if(engine.mimetypes.ContainsKey(str)) { mimetype = engine.mimetypes[str]; }else { mimetype = "application/octet-stream"; } if(mimetype == "text/html") { StreamReader mreader = new StreamReader(fstr); string httext = mreader.ReadToEnd(); reqManager.ParseHTMLDocument(ref httext,request); MemoryStream mstream = new MemoryStream(); StreamWriter mwriter = new StreamWriter(mstream); mwriter.Write(httext); mwriter.Flush(); mstream.Position = 0; if(request.ContinueProcessing) { ClientHttpResponse response = new ClientHttpResponse(); response.ContentType = mimetype; response.len = mstream.Length; response.StatusCode = "200 OK"; response.WriteHeader(request.stream); response.WriteStream(mstream,request.stream,16384); }else { return; } }else { ClientHttpResponse response = new ClientHttpResponse(); response.ContentType = mimetype; response.len = fstr.Length; response.StatusCode = "200 OK"; response.WriteHeader(request.stream); response.WriteStream(fstr,request.stream,16384); } } }else { ClientHttpResponse response = new ClientHttpResponse(); response.ContentType = "text/html"; response.len = notfoundpage.Length; response.StatusCode = "404 Not Found"; response.WriteHeader(request.stream); request.stream.Write(notfoundpage,0,notfoundpage.Length); request.stream.Flush(); } }catch(Exception er) { Console.WriteLine(er); } }
public string securePage(ClientWebRequest request) { SessionInformation session = sessions[sessionKey(request)]; if(!session.isAdminAuthenticated) { ClientHttpResponse response = new ClientHttpResponse(); response.Redirect("index.htm?sessionID="+sessionKey(request),false,request.stream); request.ContinueProcessing = false; } return ""; }
public string loginstatus(ClientWebRequest request) { if (request.QueryString.ContainsKey("sessionID")) { string sesid = request.QueryString["sessionID"]; if (!sessions.ContainsKey(request.QueryString["sessionID"])) { sessions.Add(sesid, new SessionInformation()); } SessionInformation session = sessions[sesid]; if(request.Method == "POST") { Dictionary<string,string> formdata = request.Form; try { using(Stream fstr = File.Open(Environment.CurrentDirectory+"\\admin",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite)) { Filesystem msys = new Filesystem(fstr,formdata["pswd"],16384,1024*1024*5); msys.Dispose(); session.isAdminAuthenticated = true; } }catch(Exception er) { return "Login failure"; } } if(session.isAdminAuthenticated) { ClientHttpResponse response = new ClientHttpResponse(); response.Redirect("serverAdmin.htm?sessionID="+request.QueryString["sessionID"],false,request.stream); request.ContinueProcessing = false; } return ""; } else { return ""; } }
public string fileList(string queryStringValue,ClientWebRequest request) { Dictionary<string,string> querystring = request.QueryString; if(!querystring.ContainsKey(queryStringValue)) { querystring.Add(queryStringValue,Path.GetPathRoot(Environment.CurrentDirectory)); } StringBuilder retval = new StringBuilder(); retval.Append("<tr><td><b><u>File name</b></u></td><td><b><u>Last modified</u></b></td></tr>"); foreach(string et in Directory.GetFileSystemEntries(querystring[queryStringValue])) { retval.Append("<tr fullname=\""+et+"\" isdirectory=\""+Directory.Exists(et).ToString()+"\"><td>"+Path.GetFileName(et)+"</td><td>"+Directory.GetLastWriteTime(et)+"</td></tr>"); } return retval.ToString(); }
void thetar(object sender) { try { ParallelSocket msock = sender as ParallelSocket; XStream mstream = new XStream(msock); List<string> headers = new List<string>(); BinaryReader mreader = new BinaryReader(mstream); int count = mreader.ReadInt32(); for (int i = 0; i < count; i++) { headers.Add(mreader.ReadString()); } //Create a new ClientWebRequest. Note that WE will be the server for this remoting object //as it is created on our end. So unlike most reuqests, we'll have a really complex route //Execution route: server->Protocol driver->Server->Application ClientWebRequest request = new ClientWebRequest(mstream, headers); request.SecureConnection = true; request.SecurityIdentifier = _session.pubKey; //Inject the request into the server execution framework NetProvider.instance._engine.NtfyConnection(request); } catch (Exception er) { Console.WriteLine(er); } }
public string backgroundURL(ClientWebRequest request) { SessionInformation session = sessions[sessionKey(request)]; return session.profileImgUrl; }