public void Run() { BS = new BlindSocket(); BP = new BlindPacket(); BS.ConnectWithECDH(BlindNetConst.ServerIP, BlindNetConst.WebDevicePort); while (true) { try { BP = BS.CryptoReceive();// 아이디에 따른 장치제어 결과 받아옴 } catch { break; } BP.data = BlindNetUtil.ByteTrimEndNull(BP.data); string ReceiveByteToStringGender = Encoding.Default.GetString(BP.data);// 변환 바이트 -> string = default,GetString | string -> 바이트 = utf8,GetBytes //11 : USB,CAM 차단 | 10: USB만 차단 | 01: 웹캠만 차단 | 00 : 모두허용 DeviceToggle(ReceiveByteToStringGender); Thread.Sleep(1000); } }
public async Task <bool> DownloadDir(ListViewItem item) { form.label_fName.Text = "(압축중)" + form.selected.FullPath + "\\" + item.Text; form.label_fName.Update(); uint id = (uint)item.Tag; socket.CryptoSend(BitConverter.GetBytes(id), PacketType.DocDirDownload); BlindPacket packet = await Task.Run(() => { return(socket.CryptoReceive()); }); if (packet.header == PacketType.Fail) { return(false); } form.label_fName.Text = form.selected.FullPath + "\\" + item.Text; form.label_fName.Update(); string fileName = dPath + item.Text + ".zip"; byte[] data = null; bool recvMode = false; do { packet = socket.CryptoReceive(recvMode); if (packet.header == PacketType.Disconnect) { return(false); } data = BlindNetUtil.MergeArray <byte>(data, packet.data); form.progressBar.PerformStep(); if (form.progressBar.Value < form.progressBar.Maximum) { form.progressBar.Value += 1; } form.progressBar.Value -= 1; form.label_percent.Text = (form.progressBar.Value * 100 / form.progressBar.Maximum) + "%"; form.label_percent.Update(); recvMode = true; } while (packet.header == PacketType.Sending); data = BlindNetUtil.ByteTrimEndNull(data); FileInfo file = new FileInfo(fileName); int tmp = 1; while (file.Exists) { file = new FileInfo(file.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(fileName) + "(" + tmp++ + ")" + file.Extension); } FileStream fs = file.OpenWrite(); fs.Write(data, 0, data.Length); fs.Close(); return(true); }
public void UpdateDir(TreeNode node) { form.listview_File.BeginUpdate(); form.listview_File.Items.Clear(); node.Nodes.Clear(); socket.CryptoSend(BitConverter.GetBytes(((Directory_Info)(node.Tag)).id), PacketType.DocDirInfo); while (true) { BlindPacket packet = socket.CryptoReceive(); if (packet.header == PacketType.EOF) { break; } Directory_Info dir = BlindNetUtil.ByteToStruct <Directory_Info>(BlindNetUtil.ByteTrimEndNull(packet.data)); TreeNode subNode = new TreeNode(); subNode.Tag = dir; subNode.Text = dir.name; subNode.ImageIndex = 0; subNode.SelectedImageIndex = 0; node.Nodes.Add(subNode); ListViewItem item = new ListViewItem(); item.Text = dir.name; item.SubItems.Add(dir.modDate); item.SubItems.Add(string.Empty); item.Tag = dir.id; item.ImageIndex = 0; form.listview_File.Items.Add(item); } while (true) { BlindPacket packet = socket.CryptoReceive(); if (packet.header == PacketType.EOF) { break; } File_Info file = BlindNetUtil.ByteToStruct <File_Info>(BlindNetUtil.ByteTrimEndNull(packet.data)); ListViewItem item = new ListViewItem(); item.Text = file.name; item.ImageIndex = 1; item.SubItems.Add(file.modDate); item.SubItems.Add(file.type); item.SubItems.Add(ConvertSize(file.size)); item.Tag = file.id; form.listview_File.Items.Add(item); } form.listview_File.EndUpdate(); }
public void Run() { connection = new MySqlConnection("Server = " + BlindNetConst.DatabaseIP + "; Port = 3306; Database = document_center; Uid = root; Pwd = kit2020"); mainSocket = new BlindServerScoket(BlindNetConst.ServerIP, BlindNetConst.OPENNERPORT); mainSocket.BindListen(); while (true) { BlindSocket client = mainSocket.AcceptWithECDH(); IPEndPoint iep = (IPEndPoint)(client.socket.RemoteEndPoint); Console.WriteLine("Accepted {0} : {1}", iep.Address, iep.Port); if (client == null) { continue; } byte[] data = BlindNetUtil.ByteTrimEndNull(client.CryptoReceiveMsg()); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); string ext = GetExt(BitConverter.ToUInt32(tmp, 0)); if (ext == null) { client.CryptoSend(null, PacketType.Disconnect); continue; } client.CryptoSend(Encoding.UTF8.GetBytes(ext), PacketType.Info); data = BlindNetUtil.ByteTrimEndNull(client.CryptoReceiveMsg()); tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); int encryptDate = BitConverter.ToInt32(tmp, 0); byte[] key, iv; if (!GetSpecifyKeyPair(out key, out iv, encryptDate)) { client.CryptoSend(null, PacketType.Disconnect); continue; } client.CryptoSend(key, PacketType.Info); client.CryptoSend(iv, PacketType.Info); byte[] latestKey, latestIv; if (!GetLatestKeyPair(out latestKey, out latestIv)) { client.CryptoSend(null, PacketType.Disconnect); continue; } client.CryptoSend(latestKey, PacketType.Info); client.CryptoSend(latestIv, PacketType.Info); client.Close(); } }
private void MainForm_Shown(object sender, EventArgs e) { VPNClass = new VPN_Class(); //클라이언트 cid 서버로부터 받아오기 //ClientID = "test1"; string SendMsg = ClientID + "," + isInner; //아이디 + 내부 외부 보내서 외부면 vpn로그남김 (isInner bool형. 디버그했을때 실질적인 값 : true -> "True" | false -> "False") byte[] SendStringToByteGender = Encoding.UTF8.GetBytes(SendMsg); // String -> bytes 변환 mainSocket.CryptoSend(SendStringToByteGender, PacketType.Response); //서버로 클라이언트 id 보냄 blindClientCidPacket = mainSocket.CryptoReceive(); // 서버로부터 cid받아옴 byte[] data = BlindNetUtil.ByteTrimEndNull(blindClientCidPacket.data); // 넑값 지움 byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); uint ClintCID = BitConverter.ToUInt32(tmp, 0); if (ClintCID == 0) //서버에서 아이디를 조회못했을때 0반환 { MessageBox.Show("서버로부터 id를 받지 못하였거나 등록되지 않은 아이디입니다." + Environment.NewLine + "\t 관리자에게 문의하십시요."); mainSocket.Close(); Application.Exit(); return; } //각 기능 객체 및 Task 생성 TaskScheduler scheduler = TaskScheduler.Default; token = new CancellationTokenSource(); documentCenter = new Doc_Center(document_Center, isInner); documentCenter.Run(); document_Center.docCenter = documentCenter; _ChatMain = new ChatMain(ClintCID); _ChatMain.Dock = DockStyle.Fill; MainControlPanel.Controls.Add(_ChatMain); //Func chat = new BlindChat(ClintCID, ref _ChatMain, this); tChat = Task.Factory.StartNew(() => chat.Run(), token.Token, TaskCreationOptions.LongRunning, scheduler); //ScreenLocking lockForm = new LockForm(isInner, ClientID); lockForm.connect(); MessageBox.Show("락 연결!"); deviceDriver = new DeviceDriverHelper(); tDeviceDriver = Task.Factory.StartNew(() => deviceDriver.Run(), token.Token, TaskCreationOptions.LongRunning, scheduler); }
public bool AddDir(TreeNode node, string name) { Directory_Info dir = new Directory_Info(); dir.id = 0; dir.parent_id = ((Directory_Info)(node.Parent.Tag)).id; dir.name = name; socket.CryptoSend(BlindNetUtil.StructToByte(dir), PacketType.DocAddDir); BlindPacket packet = socket.CryptoReceive(); if (packet.header != PacketType.OK) { return(false); } node.Tag = BlindNetUtil.ByteToStruct <Directory_Info>(BlindNetUtil.ByteTrimEndNull(packet.data)); return(true); }
public void UpdateRoot() { form.treeview_Dir.Nodes.Clear(); socket.CryptoSend(null, PacketType.DocRefresh); while (true) { BlindPacket packet = socket.CryptoReceive(); if (packet.header == PacketType.EOF) { break; } Directory_Info dir = BlindNetUtil.ByteToStruct <Directory_Info>(BlindNetUtil.ByteTrimEndNull(packet.data)); TreeNode node = new TreeNode(); node.Tag = dir; node.Text = dir.name; node.ImageIndex = 0; node.SelectedImageIndex = 0; form.treeview_Dir.Nodes.Add(node); } }
static void Main(string[] args) { Console.WriteLine("Well Come to Console \r\n\r\n"); if (!BlindNetUtil.IsConnectedInternet()) { Console.WriteLine("There is no internet connection"); Environment.Exit(0); } bool result = MainSocket.ConnectWithECDH(BlindNetConst.ServerIP, BlindNetConst.WebInterlockPort); if (!result) { Console.WriteLine("Main socket connection failed."); Environment.Exit(0); } Console.WriteLine("Main Server Connection. (Server IP : " + BlindNetConst.ServerIP + ")\r\n"); while (true) { //받기 -> 명령문 실행 -> 결과(Result) 스트링 전송) MainPacket = MainSocket.CryptoReceive(); //타입 + 아이디 + 비번 정보 받음 Console.Write("Server Message Receive Waiting"); //MainPacket.data = BlindNetUtil.ByteTrimEndNull(MainPacket.data); // ReceiveByteToStringGenderText = Encoding.Default.GetString(BlindNetUtil.ByteTrimEndNull(MainPacket.data)); //변환해서 ㅓㄶ음 Console.WriteLine("Receive Message : " + ReceiveByteToStringGenderText); if (CMD_Instruction(ReceiveByteToStringGenderText)) // 명령문 전달해서 실행 { Result = "true"; } else { Result = "false"; } MainSocket.CryptoSend(Encoding.UTF8.GetBytes(Result), PacketType.Response); // 결과 전송 Console.WriteLine("Send Message | Instruction Result = " + Result + "\r\n"); } }
public async Task <TreeNode> UploadDirAsync(TreeNode node, string path) { Directory_Info dir = new Directory_Info(); dir.id = 0; dir.parent_id = ((Directory_Info)node.Tag).id; dir.name = Path.GetFileName(path); socket.CryptoSend(BlindNetUtil.StructToByte(dir), PacketType.DocAddDir); BlindPacket packet = await Task.Run(() => socket.CryptoReceive()); if (packet.header == PacketType.Fail) { return(null); } Directory_Info newDir = BlindNetUtil.ByteToStruct <Directory_Info>(BlindNetUtil.ByteTrimEndNull(packet.data)); TreeNode newNode = new TreeNode(); newNode.Tag = newDir; newNode.Text = newDir.name; newNode.ImageIndex = 0; newNode.SelectedImageIndex = 0; form.progressBar.PerformStep(); if (form.progressBar.Value < form.progressBar.Maximum) { form.progressBar.Value += 1; } form.progressBar.Value -= 1; form.label_percent.Text = (form.progressBar.Value * 100 / form.progressBar.Maximum) + "%"; #if DEBUG form.label_percent.Text = form.progressBar.Value.ToString(); #endif form.label_percent.Update(); return(newNode); }
static void onEchoReader(IAsyncResult ar) { //웹에서 보낸 데이터 처리 // 받은 데이터의 길이를 확인합니다. int receiveLength = ClientStream.EndRead(ar); // 데이터 6 = close() 데이터 0보다 작거나 같은것 = 홈페이지 끈경우 if (receiveLength <= 0 || receiveLength == 6) { Console.WriteLine("(WebSocket)Connection Close"); ClientStream.Close(); return; } BitArray maskingCheck = new BitArray(new byte[] { ReadBuffer[1] });//마스킹 관련 int receivedSize = (int)ReadBuffer[1]; byte[] mask = new byte[] { ReadBuffer[2], ReadBuffer[3], ReadBuffer[4], ReadBuffer[5] }; receivedSize -= 128; //if (maskingCheck.Get(0)) //{ // Console.WriteLine("마스킹 되어 있습니다."); // receivedSize -= 128; // 마스킹으로 인해 추가된 값을 빼 줍니다. //} //else //{ // Console.WriteLine("마스킹 되어 있지 않습니다."); //} //데이터 길이 비트 : receivedSize | 데이터 길이 : receivedLength // 받은 메시지를 디코딩해 줍니다. byte[] decodedByte = new byte[receivedSize]; for (int _i = 0; _i < receivedSize; _i++) { int curIndex = _i + 6; decodedByte[_i] = (byte)(ReadBuffer[curIndex] ^ mask[_i % 4]); } // 받은 메시지를 출력합니다. //string newMessage = Encoding.UTF8.GetString( ReadBuffer, 6, receiveLength - 6 ); string newMessage = Encoding.UTF8.GetString(decodedByte, 0, receivedSize); string value = "\u0003�"; //페이지이동할때 발생 if (newMessage.ToString() == value.ToString()) { ClientStream.Close(); //페이지 이동하면 뒤지게끔 Console.WriteLine("(WebSocket)Connection Close"); return; } Console.WriteLine(string.Format("(WebSocket)Receive Message : {0}", newMessage)); string SendMsg = "false"; byte[] sendMessage; string Instruction = ""; bool InstructionResult = false; string[] MessageSort = new string[10]; // 받아온 것 분류하기 위한 스트링 배열 Enumerable.Repeat("NULL", 10); /* 메시지 "," 순서 * 계정 생성 : 방식, cid, 아이디, 비밀번호, 이름, 직급, 휴대폰 번호, 이메일, 부서, 성별 * 계정 생성,삭제 : 방식,아이디 */ for (int count = 0; count <= 9; count++) // 스트링 배열에 순차적으로 ,을 구분하여 0~9까지 결과를 배열에 넣음 { try { if (newMessage.Split(',')[count].ToString() != "") { MessageSort[count] = newMessage.Split(',')[count].ToString(); } } catch { MessageSort[3] = "1234"; break; } } Instruction = MessageSort[0] + " " + MessageSort[2] + " " + MessageSort[3]; InstructionResult = CMD_Instruction(Instruction); SUBBS.CryptoSend(Encoding.UTF8.GetBytes(Instruction), PacketType.Response); //타입 + 아이디 + 비번 정보 보냄 Console.WriteLine("(VpnSocket)Send Instruction"); SUBBP = SUBBS.CryptoReceive(); // VPN 서버에서 실행된 결과 메시지 받음 ( true / false) string VpnServerReceiveMsg = Encoding.Default.GetString(BlindNetUtil.ByteTrimEndNull(SUBBP.data)); // 결과 메시지 변환후 저장 Console.WriteLine("(VpnSocket)Receive Message : " + VpnServerReceiveMsg); if (InstructionResult == true && VpnServerReceiveMsg == "true") { if (MessageSort[0] == "Create") { SendMsg = "CreateSuccess," + MessageSort[1]; } if (MessageSort[0] == "Modify") { SendMsg = "ModifySuccess," + MessageSort[1]; } if (MessageSort[0] == "Delete") { SendMsg = "DeleteSuccess," + MessageSort[1]; } } else { SendMsg = "Fail," + MessageSort[1]; } // 보낼 메시지 만들기 sendMessage = Encoding.UTF8.GetBytes(SendMsg); List <byte> sendByteList = new List <byte>(); // 첫 데이터의 정보를 만들어 추가합니다. BitArray firstInfor = new BitArray( new bool[] { true // FIN , false // RSV1 , false // RSV2 , false // RSV3 // opcode (0x01: 텍스트) , false , false , false , true } ); byte[] inforByte = new byte[1]; firstInfor.CopyTo(inforByte, 0); sendByteList.Add(inforByte[0]); // 문자열의 길이를 추가합니다. sendByteList.Add((byte)sendMessage.Length); // 실제 데이터를 추가합니다. sendByteList.AddRange(sendMessage); // 만든 메시지 보내기 ClientStream.Write(sendByteList.ToArray(), 0, sendByteList.Count); Console.WriteLine("(WebSocket)Web Send Message : " + SendMsg + "\r\n"); // 또 다음 메시지를 받을 수 있도록 대기 합니다. //ClientStream.BeginRead(ReadBuffer, 0, ReadBuffer.Length, onEchoReader, null); ClientStream.Close(); //페이지 이동하면 뒤지게끔 Console.WriteLine("(WebSocket)Connection Close"); //TClient.Close(); // 페이지이동하면 뒤지게끔 }
public void Run() { socket = _Main.socket_docCenter.AcceptWithECDH(); socket.socket.NoDelay = true; logger = new Logger(uid, ((IPEndPoint)(socket.socket.RemoteEndPoint)).Address.ToString(), LogService.DocumentCenter); logger.Log(LogRank.INFO, "Connected to document center."); isInner = BitConverter.ToBoolean(socket.CryptoReceiveMsg(), 0); connection = new MySqlConnection("Server = " + BlindNetConst.DatabaseIP + "; Port = 3306; Database = document_center; Uid = root; Pwd = kit2020"); try { connection.Open(); } catch (Exception ex) { Console.WriteLine("ERROR : [UID : " + uid + "] " + ex.Message); socket.CryptoSend(null, PacketType.Fail); return; } socket.CryptoSend(null, PacketType.OK); while (true) { //try //{ BlindPacket packet = socket.CryptoReceive(); if (packet.header != PacketType.Disconnect) { packet.data = BlindNetUtil.ByteTrimEndNull(packet.data); } switch (packet.header) { case PacketType.DocRefresh: UpdateRoot(); break; case PacketType.DocDirInfo: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); UpdateDir(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocAddDir: AddDir(BlindNetUtil.ByteToStruct <Directory_Info>(packet.data)); break; case PacketType.DocRemoveDir: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); RemoveDir(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocRemoveFile: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); RemoveFile(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocChngNameDir: ChangeNameDir(BlindNetUtil.ByteToStruct <Directory_Info>(packet.data)); break; case PacketType.DocFileUpload: FileUpload(BlindNetUtil.ByteToStruct <Directory_Info>(packet.data)); break; case PacketType.DocFileDownload: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); FileDownload(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocDirDownload: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); DirDownload(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocGetFileSize: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); GetFileSize(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocGetDirSize: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); GetDirSize(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocRenameFile: { byte[] data = BlindNetUtil.ByteTrimEndNull(packet.data); byte[] tmp = new byte[4]; Array.Copy(data, 0, tmp, 0, data.Length); RenameFile(BitConverter.ToUInt32(tmp, 0)); break; } case PacketType.DocMoveFile: MoveFile(BlindNetUtil.ByteToStruct <SrcDstInfo>(packet.data)); break; case PacketType.DocMoveDir: MoveDir(BlindNetUtil.ByteToStruct <SrcDstInfo>(packet.data)); break; case PacketType.DocCopyFile: CopyFile(BlindNetUtil.ByteToStruct <SrcDstInfo>(packet.data)); break; case PacketType.DocCopyDir: CopyDir(BlindNetUtil.ByteToStruct <SrcDstInfo>(packet.data)); break; case PacketType.Disconnect: logger.Log(LogRank.INFO, "Disconnected from document center"); return; } //} //catch (Exception ex) //{ // Console.WriteLine("ERROR : [UID : " + uid + "] " + ex.Message); // return; //} } }