Пример #1
0
        public static void HandleUploadFullfillment(Payload inbound, Payload outbound)
        {
            var context     = new SmartShareContext();
            var queryResult = from s in context.Storage
                              where s.FileHash.Contains(inbound.Status)
                              select s;

            //File GUID not found in database.

            if (queryResult.Count() == 0)
            {
                outbound.Status = Core.Config.ServerError;
            }

            //GUID found.
            else
            {
                var updatedFile = queryResult.First();
                updatedFile.TimeCreated  = DateTime.Now;
                updatedFile.TimeExpiring = updatedFile.TimeCreated + inbound.TimeLeft;
                context.Storage.Update(updatedFile);
                context.SaveChanges();
                Core.Util.WriteBase64StringToFile(
                    inbound.Base64FileData,
                    Server.Config.StorageRoot + updatedFile.FileHash
                    );
                outbound.Status = Core.Config.ServerSuccess;
            }
        }
Пример #2
0
        static void HandleDownload(NetworkStream stream, FileRequestInfo requestInfo)
        {
            var context = new SmartShareContext();
            var file    = context.UploadedFiles.First(x => x.Name == requestInfo.FileName);

            if (file == null)
            {
                stream.Write(new byte[] { FAIL_BYTE });
                return;
            }

            if (!(file.Password == requestInfo.Password))
            {
                stream.Write(new byte[] { FAIL_BYTE });
                return;
            }

            if (file.DownloadsExceeded() || file.IsExpired())
            {
                stream.Write(new byte[] { FAIL_BYTE });
                stream.Close();
                file.Delete(context);
                return;
            }

            stream.Write(new byte[] { ACK_BYTE });
            file.DownloadCount++;
            context.UploadedFiles.Update(file);
            context.SaveChanges();

            var connection = context.Database.GetDbConnection();

            if (connection is NpgsqlConnection)
            {
                var conn = (NpgsqlConnection)connection;
                conn.Open();
                var blobManager = new NpgsqlLargeObjectManager(conn);
                using (var transaction = connection.BeginTransaction())
                {
                    var blobStream = blobManager.OpenRead(file.BlobOid);
                    blobStream.CopyTo(stream);
                    transaction.Commit();
                }
                conn.Close();
                Console.WriteLine("Download successful.");
            }
            else
            {
                throw new NotSupportedException("Unsupported database adapter.");
            }
        }
Пример #3
0
        public static void HandleDownloadRequest(Payload inbound, Payload outbound)
        {
            var context     = new SmartShareContext();
            var queryResult = from s in context.Storage
                              where s.Filename.Contains(inbound.Filename)
                              select s;

            //File doesn't exist or user doesn't have correct password.
            if (queryResult.Count() == 0 || queryResult.First().Password != inbound.Password)
            {
                outbound.Status = Core.Config.ServerError;
            }

            //File exists and user has correct password.
            else
            {
                var fileRecord = queryResult.First();
                //File hasn't expired or reached max downloads.
                //Return file and update downloads left.
                if (fileRecord.TimeExpiring > DateTime.Now &&
                    fileRecord.DownloadsRemaining != 0)
                {
                    outbound.Base64FileData = Core.Util.FileToBase64String(
                        Server.Config.StorageRoot + fileRecord.FileHash
                        );
                    outbound.Status = Core.Config.ServerSuccess;

                    if (fileRecord.DownloadsRemaining != Core.Config.OptionUnlimitedDownload)
                    {
                        fileRecord.DownloadsRemaining--;
                    }

                    context.Storage.Update(fileRecord);
                }

                //File has expired or reache max downloads.
                //Delete file and update record.
                else
                {
                    outbound.Status = Core.Config.ServerError;
                    File.Delete(Server.Config.StorageRoot + fileRecord.FileHash);
                    context.Storage.Remove(fileRecord);
                }

                context.SaveChanges();
            }
        }
Пример #4
0
        public static void HandleUploadRequest(Payload inbound, Payload outbound)
        {
            var context     = new SmartShareContext();
            var queryResult = from s in context.Storage
                              where s.Filename.Contains(inbound.Filename)
                              select s;

            if (queryResult.Count() == 0)
            {
                //File doesn't exist, add initial entry.
                var newFile = new StorageModel();
                newFile.Filename           = inbound.Filename;
                newFile.FileHash           = Guid.NewGuid().ToString();
                newFile.DownloadsRemaining = (inbound.DownloadsLeft > 0)
                    ? inbound.DownloadsLeft
                    : Core.Config.DefaultDownloadLimit;
                newFile.Password = inbound.Password;
                //newFile.TimeCreated and newFile.TimeExpiring will be added
                //upon file receipt.
                context.Storage.Add(newFile);
                context.SaveChanges();

                //Prepare authorization response.
                outbound.Status = newFile.FileHash;
                if (inbound.TimeLeft < Core.Config.MinLifetime)
                {
                    outbound.TimeLeft = Core.Config.DefaultLifetime;
                }

                else if (inbound.TimeLeft > Core.Config.MaxLifetime)
                {
                    outbound.TimeLeft = Core.Config.MaxLifetime;
                }

                else
                {
                    outbound.TimeLeft = inbound.TimeLeft;
                }
            }

            else
            {
                outbound.Status = Core.Config.ServerError;
            }
        }
Пример #5
0
        public static bool SaveToDb(FileRequest request)
        {
            File file = MapFileRequestToFileEntity(request);

            using (var context = new SmartShareContext())
            {
                try
                {
                    context.Files.Add(file);
                    context.SaveChanges();
                    return(true);
                }
                catch (Exception)
                {
                    Console.WriteLine("File Already Exist, Please try a Different Filename to Upload");
                    return(false);
                }
            }
        }
Пример #6
0
        public static bool SaveTextToDb(FileRequest requestObj)
        {
            DownloadFile filerequest = mapTextRequestToTextEntity(requestObj);

            using (SmartShareContext context = new SmartShareContext())
            {
                try
                {
                    context.FilesIn.Add(filerequest);
                    context.SaveChanges();
                    return(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    return(false);
                }
            }
        }
Пример #7
0
        public static void HandleInfoRequest(Payload inbound, Payload outbound)
        {
            var context     = new SmartShareContext();
            var queryResult = from s in context.Storage
                              where s.Filename.Contains(inbound.Filename)
                              select s;

            //File not found or incorrect password provided.
            if (queryResult.Count() == 0 || queryResult.First().Password != inbound.Password)
            {
                outbound.Status = Core.Config.ServerError;
            }

            //File found and correct password provided.
            else
            {
                var fileRecord = queryResult.First();

                //File not expired or over download limit.
                //Return file info.
                if (fileRecord.TimeExpiring > DateTime.Now &&
                    fileRecord.DownloadsRemaining != 0)
                {
                    outbound.TimeCreated   = fileRecord.TimeCreated;
                    outbound.TimeLeft      = fileRecord.TimeExpiring - DateTime.Now;
                    outbound.DownloadsLeft = fileRecord.DownloadsRemaining;
                    outbound.Status        = Core.Config.ServerSuccess;
                }

                //File expired or over download limit.
                //Delete file.
                else
                {
                    outbound.Status = Core.Config.ServerError;
                    File.Delete(Server.Config.StorageRoot + fileRecord.FileHash);
                    context.Storage.Remove(fileRecord);
                    context.SaveChanges();
                }
            }
        }
Пример #8
0
        private static void HandleView(NetworkStream stream, FileRequestInfo requestInfo)
        {
            var context = new SmartShareContext();
            var file    = context.UploadedFiles.First(x => x.Name == requestInfo.FileName);

            if (!(file.Password == requestInfo.Password))
            {
                return;
            }

            if (file.DownloadsExceeded() || file.IsExpired())
            {
                stream.Close();
                file.Delete(context);
                return;
            }

            var view = file.CreateView();
            var responseSerializer = new XmlSerializer(typeof(FileView));

            responseSerializer.Serialize(stream, view);
        }
Пример #9
0
        static void HandleClient(TcpClient client)
        {
            using (var stream = client.GetStream())
            {
                var payloadSerializer = new XmlSerializer(typeof(Payload));
                var inbound           = (Payload)payloadSerializer.Deserialize(stream);
                var outbound          = new Payload();
                var context           = new SmartShareContext();

                //Client requested upload authorization.
                if (inbound.Status == Core.Config.RequestUpload)
                {
                    HandleUploadRequest(inbound, outbound);
                }

                //Client requested download.
                else if (inbound.Status == Core.Config.RequestDownload)
                {
                    HandleDownloadRequest(inbound, outbound);
                }

                //Client requested file info.
                else if (inbound.Status == Core.Config.RequestInfo)
                {
                    HandleInfoRequest(inbound, outbound);
                }

                //Client passed authorization. Create file and update record.
                else
                {
                    HandleUploadFullfillment(inbound, outbound);
                }

                //Send response to client.
                payloadSerializer.Serialize(stream, outbound);
                client.Close();
            }
        }
Пример #10
0
        private static String ViewDB(FileRequest request)
        {
            File file = MapFileRequestToFileEntity(request);

            using (var context = new SmartShareContext())
            {
                try
                {
                    var Dbfiles = context.Files;

                    var FileView = (from f in Dbfiles
                                    where f.FileName == file.FileName
                                    select f).First();

                    return(FileView.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }

                return("File Does Not Exist");
            }
        }
Пример #11
0
        static void Main(string[] args)
        {
            XmlSerializer fromClientDeserialize = new XmlSerializer(typeof(ClientToServerDTO));

            ClientToServerDTO fromClientDTO = new ClientToServerDTO();

            IPEndPoint ingress = new IPEndPoint(0, 1234);

            SmartShareContext DBContext = new SmartShareContext();

            TcpListener mainSocket = new TcpListener(ingress);

            mainSocket.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            mainSocket.Start();

            while (true)
            {
                try
                {
                    TcpClient clientConnection = mainSocket.AcceptTcpClient();
                    Console.WriteLine("Connection Received");

                    Task.Run(() =>
                    {
                        SmartShareContext dbContext = new SmartShareContext();
                        DbSet <SmartShareFile> smartShareFileTable = dbContext.SmartShareFileTable;
                        SmartShareFile newDataEntry = new SmartShareFile();

                        using (NetworkStream stream = clientConnection.GetStream())
                        {
                            fromClientDTO = (ClientToServerDTO)fromClientDeserialize.Deserialize(stream);

                            bool exists = (from i in smartShareFileTable where i.Filename == fromClientDTO.Filename select i).Any();

                            if (fromClientDTO.UserAction == UserAction.upload)
                            {
                                if (!exists)
                                {
                                    newDataEntry.Filename         = fromClientDTO.Filename;
                                    newDataEntry.Password         = fromClientDTO.Password;
                                    newDataEntry.MaximumDownloads = fromClientDTO.MaxDown;
                                    newDataEntry.Expiration       = fromClientDTO.Expiration;
                                    newDataEntry.DownloadCount    = 0;
                                    newDataEntry.FileData         = fromClientDTO.FileData;

                                    dbContext.Add(newDataEntry);
                                    dbContext.SaveChanges();
                                }
                            }

                            if (fromClientDTO.UserAction == UserAction.download || fromClientDTO.UserAction == UserAction.view)
                            {
                                XmlSerializer toClientSerialize = new XmlSerializer(typeof(ServerToClientDTO));
                                ServerToClientDTO toClientDTO   = new ServerToClientDTO();


                                if (exists)
                                {
                                    SmartShareFile fetchedDownload = (from i in smartShareFileTable
                                                                      where i.Filename == fromClientDTO.Filename
                                                                      select i).First();

                                    if (fetchedDownload.Password == fromClientDTO.Password && DateTime.Parse(fetchedDownload.Expiration) > DateTime.Now && fetchedDownload.DownloadCount < fetchedDownload.MaximumDownloads)
                                    {
                                        toClientDTO.Filename   = fetchedDownload.Filename;
                                        toClientDTO.MaxDown    = fetchedDownload.MaximumDownloads;
                                        toClientDTO.DownCount  = ++fetchedDownload.DownloadCount;
                                        toClientDTO.Expiration = fetchedDownload.Expiration;
                                        toClientDTO.FileData   = fetchedDownload.FileData;
                                        toClientDTO.Created    = fetchedDownload.Created;

                                        if (fromClientDTO.UserAction != UserAction.view)
                                        {
                                            dbContext.Update(fetchedDownload);
                                            dbContext.SaveChanges();
                                        }

                                        --toClientDTO.DownCount;

                                        toClientSerialize.Serialize(stream, toClientDTO);
                                    }
                                    else if (DateTime.Parse(fetchedDownload.Expiration) <= DateTime.Now || fetchedDownload.MaximumDownloads <= fetchedDownload.DownloadCount)
                                    {
                                        dbContext.SmartShareFileTable.Remove(fetchedDownload);
                                        dbContext.SaveChanges();
                                    }
                                }
                            }
                        }

                        dbContext.Dispose();
                    });
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Пример #12
0
        private static bool CheckDb(FileRequest request)
        {
            File file = MapFileRequestToFileEntity(request);

            using (var context = new SmartShareContext())
            {
                try
                {
                    var Dbfiles = context.Files;

                    var findFile = (from f in Dbfiles
                                    where f.FileName == file.FileName
                                    select f).Any();

                    var ifdownloadReached = (from f in Dbfiles
                                             where f.TotalDownload == f.MaxDownload
                                             select f).Any();

                    var isExpired = (from f in Dbfiles
                                     where DateTime.Compare(f.Expiration, DateTime.Now) < 0
                                     select f).Any();

                    var isPassword = (from f in Dbfiles
                                      where f.Password.Equals(file.Password)
                                      select f).Any();

                    if (isExpired || ifdownloadReached)
                    {
                        var todelete = (from f in Dbfiles
                                        where f.FileName.Equals(file.FileName)
                                        select f).First();

                        Dbfiles.Remove(todelete);
                        context.SaveChanges();

                        return(false);
                    }

                    if (!isPassword)
                    {
                        return(false);
                    }

                    if (findFile)
                    {
                        var increasetotal = (from f in Dbfiles
                                             where f.FileName == file.FileName
                                             select f).FirstOrDefault();

                        increasetotal.TotalDownload++;
                        context.Files.Update(increasetotal);
                        context.SaveChanges();

                        return(true);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    return(false);
                }

                return(false);
            }
        }
Пример #13
0
        static void HandleUpload(NetworkStream stream, FileRequestInfo requestInfo)
        {
            var context    = new SmartShareContext();
            var connection = context.Database.GetDbConnection();

            // check if file already exists, and if that file is expired we can delete it and continue the upload.
            try
            {
                var possibleFile = context.UploadedFiles.First(x => x.Name == requestInfo.FileName);
                if (possibleFile != null)
                {
                    if (possibleFile.DownloadsExceeded() || possibleFile.IsExpired())
                    {
                        possibleFile.Delete(context);
                    }
                    else
                    {
                        return;
                    }
                }
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine("File table is empty");
            }

            stream.Write(new byte[1] {
                ACK_BYTE
            });                                     // let client know we're ready to receive

            if (connection is NpgsqlConnection)
            {
                var  blobManager = new NpgsqlLargeObjectManager((NpgsqlConnection)connection);
                uint oid;
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    oid = blobManager.Create();
                    using (var blobStream = blobManager.OpenReadWrite(oid))
                    {
                        stream.CopyTo(blobStream);
                    }

                    transaction.Commit();
                }

                stream.Close();
                connection.Close();

                Console.WriteLine("Upload successful.");

                var uploadedFile = new UploadedFile(requestInfo, oid);

                context.Add(uploadedFile);
                context.SaveChanges();
            }
            else
            {
                throw new NotSupportedException("Unsupported database adapter");
            }
        }