private static async Task CopyStreams(Stream source, Stream destination, SendFileInfo info, CopyStreamState state)
        {
            var buffer = new byte[info.BufferSize];
            int bytesRead;
            var lastProgessCalled = false;

            while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, info.CancellationToken)) > 0)
            {
                await destination.WriteAsync(buffer, 0, bytesRead, info.CancellationToken);

                lastProgessCalled = false;
                if (state != null)
                {
                    state.Pos += bytesRead;
                    if (info.Progress != null && (state.Pos >= state.NextPos))
                    {
                        state.NextPos = await info.Progress.Invoke(state.Pos);

                        lastProgessCalled = true;
                    }
                }
            }

            if (state != null && info.Progress != null && !lastProgessCalled)
            {
                await info.Progress.Invoke(state.Pos);
            }
        }
        private Quest BuildSendFileQuest(SendFileInfo info)
        {
            Quest quest = null;

            switch (info.actionType)
            {
            case FileTokenType.P2P:
                quest = new Quest("sendfile");
                quest.Param("to", info.xid);
                break;

            case FileTokenType.Group:
                quest = new Quest("sendgroupfile");
                quest.Param("gid", info.xid);
                break;

            case FileTokenType.Room:
                quest = new Quest("sendroomfile");
                quest.Param("rid", info.xid);
                break;
            }

            quest.Param("pid", pid);
            quest.Param("from", uid);
            quest.Param("token", info.token);
            quest.Param("mtype", info.mtype);
            quest.Param("mid", MidGenerator.Gen());

            quest.Param("file", info.fileContent);
            quest.Param("attrs", BuildFileAttrs(info));

            return(quest);
        }
示例#3
0
        private void p_UserChannelCreated(object sender, ChannelCreatedEventArgs e)
        {
            e.CanDisposeChannel = false;
            SendFileInfo info = (SendFileInfo)e.Data;

            ServerClient otherClient;

            lock (fClients)
                fClients.TryGetValue(info.To, out otherClient);

            if (otherClient == null)
            {
                return;
            }

            var otherRemotingClient = RemotingClient.GetFromRemoteObject(otherClient.fClient);

            using (var otherChannel = otherRemotingClient.CreateUserChannel(info))
            {
                UnlimitedThreadPool.Run
                (
                    delegate
                {
                    try
                    {
                        while (true)
                        {
                            int b = otherChannel.ReadByte();
                            if (b == -1)
                            {
                                e.Channel.Dispose();
                                return;
                            }

                            e.Channel.WriteByte((byte)b);
                            e.Channel.Flush();
                        }
                    }
                    catch
                    {
                        otherChannel.Dispose();
                        e.Channel.Dispose();
                    }
                }
                );

                byte[] buffer = new byte[8 * 1024];
                while (true)
                {
                    int read = e.Channel.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                    {
                        return;
                    }

                    otherChannel.Write(buffer, 0, read);
                    otherChannel.Flush();
                }
            }
        }
        private string BuildFileAttrs(SendFileInfo info)
        {
            string fileMD5 = GetMD5(info.fileContent, false);
            string sign    = GetMD5(fileMD5 + ":" + info.token, false);

            StringBuilder sb = new StringBuilder();

            sb.Append("{\"sign\":\"");
            sb.Append(sign);
            sb.Append("\"");

            if (info.filename != null && info.filename.Length > 0)
            {
                sb.Append(",\"filename\":\"");
                sb.Append(info.filename);
                sb.Append("\"");

                if (info.fileExtension == null || info.fileExtension.Length == 0)
                {
                    info.fileExtension = ExtraFileExtension(info.filename);
                }
            }

            if (info.fileExtension != null && info.fileExtension.Length > 0)
            {
                sb.Append(",\"ext\":\"");
                sb.Append(info.fileExtension);
                sb.Append("\"");
            }

            sb.Append("}");

            return(sb.ToString());
        }
        public MultipartBoundary(SendFileInfo fileInfo)
        {
            _fileInfo = fileInfo;
            Boundary  = Guid.NewGuid();

            Postfix = GetPostFix();
        }
        private string BuildFileAttrs(SendFileInfo info)
        {
            string fileMD5 = GetMD5(info.fileContent, false);
            string sign    = GetMD5(fileMD5 + ":" + info.token, false);

            if (info.rtmAttrs == null)
            {
                info.rtmAttrs = new Dictionary <string, object>();
            }

            Dictionary <string, object> rtmAttrs = info.rtmAttrs;

            rtmAttrs.Add("sign", sign);

            if (info.filename != null && info.filename.Length > 0)
            {
                rtmAttrs.Add("filename", info.filename);

                if (info.fileExtension == null || info.fileExtension.Length == 0)
                {
                    info.fileExtension = ExtraFileExtension(info.filename);
                }
            }
            if (info.fileExtension != null && info.fileExtension.Length > 0)
            {
                rtmAttrs.Add("ext", info.fileExtension);
            }

            Dictionary <string, object> fileAttrs = new Dictionary <string, object>();

            fileAttrs.Add("rtm", rtmAttrs);

            if (info.userAttrs == null || info.userAttrs.Length == 0)
            {
                fileAttrs.Add("custom", "");
            }
            else
            {
                try
                {
                    Dictionary <string, object> userDict = Json.ParseObject(info.userAttrs);
                    if (userDict != null)
                    {
                        fileAttrs.Add("custom", userDict);
                    }
                    else
                    {
                        fileAttrs.Add("custom", info.userAttrs);
                    }
                }
                catch (JsonException)
                {
                    fileAttrs.Add("custom", info.userAttrs);
                }
            }

            return(Json.ToString(fileAttrs));
        }
 /// <inheritdoc/>
 async Task<AmazonNode> IAmazonFiles.Overwrite(string id, Func<Stream> streamCreator, CancellationToken? token, Func<long, long> progress)
 {
     var url = string.Format("{0}nodes/{1}/content", await GetContentUrl().ConfigureAwait(false), id);
     var file = new SendFileInfo
     {
         StreamOpener = streamCreator,
         FileName = id,
         FormName = "content",
         CancellationToken = token,
         Progress = progress
     };
     return await http.SendFile<AmazonNode>(HttpMethod.Put, url, file).ConfigureAwait(false);
 }
        private int SendFileWithoutClient(SendFileInfo info, bool originalEndpoint)
        {
            string fileGateEndpoint;

            if (originalEndpoint)
            {
                fileGateEndpoint = info.endpoint;
            }
            else
            {
                if (ConvertIPv4EndpointToIPv6IPPort(info.endpoint, out string ipv6, out int port))
                {
                    fileGateEndpoint = ipv6 + ":" + port;
                }
示例#9
0
        public static void Send(string FilePath, string TargetIP, string TargetPort, string PassPhrase)
        {
            Aes myr = Aes.Create();

            PoshMove.Utils.SetUpSymmetric(myr, PassPhrase);
            ICryptoTransform transform = myr.CreateEncryptor();

            IPAddress  remoteEP     = IPAddress.Parse(TargetIP);
            IPEndPoint endpoint     = new IPEndPoint(remoteEP, int.Parse(TargetPort));
            Socket     senderSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            Console.WriteLine("Sending metadata to: " + remoteEP.ToString());
            senderSocket.Connect(endpoint);
            NetworkStream ns  = new NetworkStream(senderSocket);
            CryptoStream  cs  = new CryptoStream(ns, transform, CryptoStreamMode.Write);
            FileInfo      fi  = new FileInfo(FilePath);
            SendFileInfo  sfi = new SendFileInfo()
            {
                FileName = fi.Name,
                length   = fi.Length
            };
            XmlSerializer serializer = new XmlSerializer(typeof(SendFileInfo));

            serializer.Serialize(cs, sfi);
            cs.FlushFinalBlock();
            senderSocket.Close();

            senderSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            senderSocket.SendBufferSize = 65536;
            Console.WriteLine("SendBuffer Size " + senderSocket.SendBufferSize);
            Console.WriteLine("Sending file to: " + remoteEP.ToString() + " " + fi.Length + " bytes");
            senderSocket.Connect(endpoint);
            ns = new NetworkStream(senderSocket);
            FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
            //CryptoStream csfile = new CryptoStream(ns, transform, CryptoStreamMode.Write);
            //GZipStream gsz = new GZipStream(csfile, CompressionLevel.Optimal);
            //LZ4Stream gsz = new LZ4Stream(csfile, LZ4StreamMode.Compress, LZ4StreamFlags.Default, 1024 * 1024);
            Stopwatch sw = new Stopwatch();

            sw.Start();
            fs.CopyTo(ns, 8192);

            senderSocket.Close();
            sw.Stop();
            double kbps = (fs.Length / 1000) / (sw.Elapsed.TotalSeconds);

            Console.WriteLine("Copy finished in " + sw.ElapsedMilliseconds + " at " + kbps + " kbps.  Total Bytes / Bytes on Wire: " + fs.Length);
        }
示例#10
0
        private void p_UserChannelCreated(object sender, ChannelCreatedEventArgs e)
        {
            Invoke
            (
                new Action
                (
                    delegate
            {
                SendFileInfo sendFileInfo = (SendFileInfo)e.Data;

                using (var dialog = new SaveFileDialog())
                {
                    dialog.FileName = sendFileInfo.FileName;
                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    FormTransferFile form = null;
                    FileStream fileStream = null;
                    try
                    {
                        fileStream = File.Create(dialog.FileName);
                        form       = new FormTransferFile(sendFileInfo, fileStream, e.Channel, false);
                        form.Show();

                        e.CanDisposeChannel = false;
                    }
                    catch (Exception exception)
                    {
                        if (fileStream != null)
                        {
                            fileStream.Dispose();
                        }

                        if (form != null)
                        {
                            form.Dispose();
                        }

                        MessageBox.Show(exception.Message);
                    }
                }
            }
                )
            );
        }
示例#11
0
        private void listUsers_DragDrop(object sender, DragEventArgs e)
        {
            string selectedUser = listUsers.SelectedItem.ToString();
            int    pos          = selectedUser.LastIndexOf(" - ");

            if (pos > 0)
            {
                selectedUser = selectedUser.Substring(0, pos);
            }

            string filePath = ((string[])e.Data.GetData("FileDrop"))[0];


            FileStream       fileStream = null;
            Stream           sendStream = null;
            FormTransferFile form       = null;

            try
            {
                fileStream = File.OpenRead(filePath);
                SendFileInfo sendFileInfo = new SendFileInfo(selectedUser, Path.GetFileName(filePath), fileStream.Length);

                sendStream = fConnection.CreateUserChannel(sendFileInfo);
                form       = new FormTransferFile(sendFileInfo, fileStream, sendStream, true);

                form.Show();
            }
            catch (Exception exception)
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }

                if (sendStream != null)
                {
                    sendStream.Dispose();
                }

                if (form != null)
                {
                    form.Dispose();
                }

                MessageBox.Show(exception.Message);
            }
        }
示例#12
0
        public static void Receive(string TargetPath, string ListenPort, string PassPhrase)
        {
            Aes myr = Aes.Create();

            PoshMove.Utils.SetUpSymmetric(myr, PassPhrase);
            ICryptoTransform transform = myr.CreateDecryptor();


            IPAddress  localhost     = IPAddress.Any;
            IPEndPoint localEP       = new IPEndPoint(localhost, int.Parse(ListenPort));
            Socket     receiveSocket = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            receiveSocket.Bind(localEP);
            receiveSocket.Listen(1);

            Socket    handler = receiveSocket.Accept();
            Stopwatch sw      = new Stopwatch();

            sw.Start();
            NetworkStream ns           = new NetworkStream(handler);
            CryptoStream  cs           = new CryptoStream(ns, transform, CryptoStreamMode.Read);
            XmlSerializer deserializer = new XmlSerializer(typeof(SendFileInfo));
            SendFileInfo  sfi          = (SendFileInfo)deserializer.Deserialize(cs);

            Console.WriteLine("Receiving: " + sfi.FileName + "@" + sfi.length.ToString() + " bytes");

            handler = receiveSocket.Accept();
            ns      = new NetworkStream(handler);
            //CryptoStream csFile = new CryptoStream(ns, transform, CryptoStreamMode.Read);
            //GZipStream gsz = new GZipStream(csFile, CompressionMode.Decompress);
            //LZ4Stream gsz = new LZ4Stream(cs, LZ4StreamMode.Decompress);
            var        targetPath = Path.Combine(TargetPath, sfi.FileName);
            FileStream fs         = new FileStream(targetPath, FileMode.OpenOrCreate, FileAccess.Write);

            ns.CopyTo(fs, 8192);
            fs.Flush();
            sw.Stop();
            double kbps = (fs.Length / 1000) / (sw.Elapsed.TotalSeconds);

            fs.Close();
            Console.WriteLine("Copy finished in " + sw.Elapsed.TotalSeconds + " seconds at " + kbps + " kbps");
        }
        private int SendFileWithClient(SendFileInfo info, TCPClient client)
        {
            UpdateTimeout(ref info.remainTimeout, ref info.lastActionTimestamp);
            if (info.remainTimeout <= 0)
            {
                return(fpnn.ErrorCode.FPNN_EC_CORE_TIMEOUT);
            }

            long  messageId = 0;
            Quest quest     = BuildSendFileQuest(out messageId, info);
            bool  success   = client.SendQuest(quest, (Answer answer, int errorCode) => {
                if (errorCode == fpnn.ErrorCode.FPNN_EC_OK)
                {
                    try
                    {
                        //-- long mtime = answer.Want<long>("mtime");
                        info.callback(messageId, fpnn.ErrorCode.FPNN_EC_OK);

                        RTMControlCenter.ActiveFileGateClient(info.endpoint, client);
                        return;
                    }
                    catch (Exception)
                    {
                        errorCode = fpnn.ErrorCode.FPNN_EC_CORE_INVALID_PACKAGE;
                    }
                }

                info.callback(0, errorCode);
            }, info.remainTimeout);

            if (success)
            {
                return(fpnn.ErrorCode.FPNN_EC_OK);
            }
            else
            {
                return(fpnn.ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION);
            }
        }
示例#14
0
        /// <summary>
        /// 读取配置文件
        /// </summary>
        private void ReadConfig()
        {
            //读取配置文件
            string   path       = AppDomain.CurrentDomain.BaseDirectory;
            string   strIniFile = path + Constant.FILENAME_CONFIG;
            IniFiles ini        = new IniFiles(strIniFile);

            txtIP.Text       = ini.ReadString(iniSession, "ip", "");
            txtPort.Text     = ini.ReadString(iniSession, "port", "");
            txtFolder.Text   = ini.ReadString(iniSession, "folder", "");
            txtFile.Text     = ini.ReadString(iniSession, "file", "");
            rdBtnUDP.Checked = ini.ReadBool(iniSession, "udp", true);
            rdBtnTCP.Checked = ini.ReadBool(iniSession, "tcp", false);

            finished      = ini.ReadBool(iniSession, "finished", false);
            completeBytes = ini.ReadLong(iniSession, "completeBytes", 0);
            totalBytes    = ini.ReadLong(iniSession, "totalBytes", 0);
            milliseconds  = ini.ReadLong(iniSession, "milliseconds", 0);
            buffersize    = ini.ReadInteger(iniSession, "buffersize", Constant.EXDATA_SIZE);
            interval      = ini.ReadInteger(iniSession, "interval", 0);

            chkShowLog.Checked    = ini.ReadBool(iniSession, "showlog", true);
            rdBtnNothing.Checked  = ini.ReadBool(iniSession, "nothing", true);
            rdBtnExitApp.Checked  = ini.ReadBool(iniSession, "exitapp", false);
            rdBtnShutdown.Checked = ini.ReadBool(iniSession, "shutdown", false);

            //读取上传文件信息
            string strSendInfo = path + Constant.FILENAME_SENDINFO;

            if (File.Exists(strSendInfo))
            {
                sendFileInfo = (SendFileInfo)FileUtils.DeserializeFile(strSendInfo, typeof(SendFileInfo));
            }
            else
            {
                sendFileInfo = new SendFileInfo();
            }
        }
示例#15
0
        public FormTransferFile(SendFileInfo sendFileInfo, FileStream fileStream, Stream sendOrReceiveStream, bool mustSend)
        {
            InitializeComponent();

            fSendFileInfo        = sendFileInfo;
            fFileStream          = fileStream;
            fSendOrReceiveStream = sendOrReceiveStream;
            fMustSend            = mustSend;

            if (mustSend)
            {
                Text = "Waiting response to send " + sendFileInfo.FileName;
            }
            else
            {
                Text = "Receiving " + sendFileInfo.FileName;
            }

            fMaximum             = progressBar1.Width;
            fFileLength          = sendFileInfo.Length;
            progressBar1.Maximum = fMaximum;

            Disposed += new EventHandler(p_Disposed);
        }
示例#16
0
        /// <inheritdoc/>
        async Task<AmazonNode> IAmazonFiles.UploadNew(FileUpload fileUpload)
        {
            var url = string.Format("{0}nodes", await GetContentUrl().ConfigureAwait(false));
            if (fileUpload.AllowDuplicate)
            {
                url += "?suppress=deduplication";
            }

            var obj = new NewChild { name = fileUpload.FileName, parents = new string[] { fileUpload.ParentId }, kind = "FILE" };
            var meta = JsonConvert.SerializeObject(obj);

            var file = new SendFileInfo
            {
                StreamOpener = fileUpload.StreamOpener,
                FileName = fileUpload.FileName,
                FormName = "content",
                CancellationToken = fileUpload.CancellationToken,
                BufferSize = fileUpload.BufferSize,
                Progress = fileUpload.Progress,
                Parameters = new Dictionary<string, string>
                    {
                        { "metadata", meta }
                    }
            };
            return await http.SendFile<AmazonNode>(HttpMethod.Post, url, file).ConfigureAwait(false);
        }
        /// <summary>
        /// Uploads file
        /// </summary>
        /// <typeparam name="TResult">Result type</typeparam>
        /// <param name="method">HTTP method</param>
        /// <param name="url">URL for request</param>
        /// <param name="fileInfo">File upload parameters. Input stream must support Length</param>
        /// <returns>Async result object</returns>
        public async Task <TResult> SendFile <TResult>(HttpMethod method, string url, SendFileInfo fileInfo)
        {
            var result = default(TResult);
            await Retry.Do(
                RetryTimes,
                RetryDelay,
                async() =>
            {
                var client = await GetHttpClient(url);
                try
                {
                    client.Method = method.ToString();
                    client.AllowWriteStreamBuffering = false;

                    var boundry        = Guid.NewGuid().ToString();
                    client.ContentType = $"multipart/form-data; boundary={fileInfo.MultipartBoundary.Boundary}";
                    client.SendChunked = false;

                    using (var input = fileInfo.StreamOpener())
                    {
                        var preFix  = fileInfo.MultipartBoundary.GetPrefix(input);
                        var postFix = fileInfo.MultipartBoundary.Postfix;

                        client.ContentLength = preFix.Length + input.Length + postFix.Length;

                        fileInfo.CancellationToken.ThrowIfCancellationRequested();

                        using (var output = await client.GetRequestStreamAsync())
                        {
                            var state = new CopyStreamState();

                            await CopyStreams(preFix, output, fileInfo, null);
                            await CopyStreams(input, output, fileInfo, state);

                            await CopyStreams(postFix, output, fileInfo, null);
                        }
                    }
                    using (var response = (HttpWebResponse)await client.GetResponseAsync())
                    {
                        if (!response.IsSuccessStatusCode())
                        {
                            return(await LogBadResponse(response));
                        }

                        result = await response.ReadAsAsync <TResult>();
                    }
                    return(true);
                }
                catch (Exception)
                {
                    client.Abort();
                    throw;
                }
            },
                FileSendExceptionProcessor);

            return(result);
        }