Exemple #1
0
        public static void DecryptTagFile(string source, string destination, byte[] key, OpCore core)
        {
            int bufferSize = 4096;

            byte[] buffer = new byte[4096]; // needs to be 4k to packet stream break/resume work

            string     tempPath = (core != null) ? core.GetTempPath() : destination;
            G2Protocol protocol = (core != null) ? core.Network.Protocol : new G2Protocol();

            using (FileStream tempFile = new FileStream(tempPath, FileMode.Create))
                using (TaggedStream encFile = new TaggedStream(source, protocol))
                    using (IVCryptoStream stream = IVCryptoStream.Load(encFile, key))
                    {
                        int read = bufferSize;
                        while (read == bufferSize)
                        {
                            read = stream.Read(buffer, 0, bufferSize);
                            tempFile.Write(buffer, 0, read);
                        }
                    }

            // move to official path
            if (core == null)
            {
                return;
            }

            File.Copy(tempPath, destination, true);
            File.Delete(tempPath);
        }
Exemple #2
0
        private ProfileTemplate GetTemplate(ulong id)
        {
            OpProfile profile = Profiles.GetProfile(id);

            if (profile == null)
            {
                return(null);
            }

            ProfileTemplate template = new ProfileTemplate(false, true);

            template.User     = Core.GetName(id);;
            template.FilePath = Profiles.GetFilePath(profile);
            template.FileKey  = profile.File.Header.FileKey;

            if (!profile.Loaded)
            {
                Profiles.LoadProfile(profile.UserID);
            }

            try
            {
                using (TaggedStream stream = new TaggedStream(template.FilePath, Core.GuiProtocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(stream, template.FileKey))
                    {
                        int    buffSize  = 4096;
                        byte[] buffer    = new byte[4096];
                        long   bytesLeft = profile.EmbeddedStart;
                        while (bytesLeft > 0)
                        {
                            int readSize = (bytesLeft > (long)buffSize) ? buffSize : (int)bytesLeft;
                            int read     = crypto.Read(buffer, 0, readSize);
                            bytesLeft -= (long)read;
                        }

                        foreach (ProfileAttachment attach in profile.Attached)
                        {
                            if (attach.Name.StartsWith("template"))
                            {
                                byte[] html = new byte[attach.Size];
                                crypto.Read(html, 0, (int)attach.Size);

                                template.Html = UTF8Encoding.UTF8.GetString(html);
                                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                                template.Hash = sha1.ComputeHash(html);

                                break;
                            }
                        }
                    }
            }
            catch
            {
                return(null);
            }

            return(template);
        }
Exemple #3
0
        public void CollectionDownloadFinished(object[] args)
        {
            ShareCollection collection = args[0] as ShareCollection;
            ushort          client     = (ushort)args[1];

            collection.Files.LockWriting(() =>
            {
                foreach (SharedFile file in collection.Files.Where(c => c.ClientID == client).ToArray())
                {
                    collection.Files.Remove(file);
                }
            });

            try
            {
                string finalpath = GetPublicPath(collection);

                using (TaggedStream tagged = new TaggedStream(finalpath, Network.Protocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(tagged, collection.Key))
                    {
                        PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                        G2Header root = null;

                        collection.Files.LockWriting(() =>
                        {
                            while (stream.ReadPacket(ref root))
                            {
                                if (root.Name == SharePacket.File)
                                {
                                    SharedFile file = SharedFile.Decode(root, client);

                                    // dont add dupes from diff client ids
                                    if (collection.Files.Any(f => f.Size == file.Size && Utilities.MemCompare(f.Hash, file.Hash)))
                                    {
                                        continue;
                                    }

                                    file.FileID = OpTransfer.GetFileID(ServiceID, file.Hash, file.Size);
                                    collection.Files.SafeAdd(file);
                                }
                            }
                        });
                    }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Mail", "Error loading local mail " + ex.Message);
            }

            collection.Status = collection.Files.SafeCount + " Files Shared";

            Core.RunInGuiThread(GuiCollectionUpdate, collection.UserID);
        }
Exemple #4
0
        public void LoadProfile(ulong id)
        {
            OpProfile profile = GetProfile(id);

            if (profile == null)
            {
                return;
            }

            try
            {
                string path = GetFilePath(profile);

                if (!File.Exists(path))
                {
                    return;
                }

                profile.Attached = new List <ProfileAttachment>();

                using (TaggedStream file = new TaggedStream(path, Network.Protocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(file, profile.File.Header.FileKey))
                    {
                        PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                        G2Header root = null;

                        while (stream.ReadPacket(ref root))
                        {
                            if (root.Name == ProfilePacket.Attachment)
                            {
                                ProfileAttachment packet = ProfileAttachment.Decode(root);

                                if (packet == null)
                                {
                                    continue;
                                }

                                profile.Attached.Add(packet);
                            }
                        }
                    }

                profile.Loaded = true;
            }
            catch (Exception ex)
            {
                Network.UpdateLog("Profile", "Error loading file " + ex.Message);
            }
        }
Exemple #5
0
        private void UnloadHeaderFile(string path, byte[] key)
        {
            try
            {
                if (!File.Exists(path))
                {
                    return;
                }

                using (TaggedStream filex = new TaggedStream(path, Network.Protocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
                    {
                        PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                        G2Header header = null;

                        while (stream.ReadPacket(ref header))
                        {
                            if (header.Name == StoragePacket.File)
                            {
                                StorageFile packet = StorageFile.Decode(header);

                                if (packet == null)
                                {
                                    continue;
                                }

                                OpFile commonFile = null;
                                if (!FileMap.SafeTryGetValue(packet.HashID, out commonFile))
                                {
                                    continue;
                                }

                                commonFile.DeRef();
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
            }
        }
Exemple #6
0
        private void Cache_FileAquired(OpVersionedFile file)
        {
            if (file.UserID != Network.Local.UserID)
            {
                return;
            }

            // only we can open the buddly list stored on the network
            byte[] key = Core.User.Settings.KeyPair.Decrypt(file.Header.FileKey, false);

            using (TaggedStream tagged = new TaggedStream(Cache.GetFilePath(file.Header), Network.Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(tagged, key))
                {
                    BuddyList.SafeClear();

                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header root = null;

                    while (stream.ReadPacket(ref root))
                    {
                        if (root.Name == BuddyPacket.Buddy)
                        {
                            OpBuddy buddy = OpBuddy.Decode(root);
                            ulong   id    = Utilities.KeytoID(buddy.Key);

                            Core.IndexKey(id, ref buddy.Key);
                            Core.IndexName(id, buddy.Name);

                            if (buddy.Ignored)
                            {
                                IgnoreList.SafeAdd(id, buddy);
                            }
                            else
                            {
                                BuddyList.SafeAdd(id, buddy);
                            }
                        }
                    }
                }

            Core.RunInGuiThread(GuiUpdate);
        }
Exemple #7
0
        public static void ExtractAttachedFile(string source, byte[] key, long fileStart, long[] attachments, int index, string destination)
        {
            using (TaggedStream tagged = new TaggedStream(source, new G2Protocol()))
                using (IVCryptoStream crypto = IVCryptoStream.Load(tagged, key))
                {
                    // get past packet section of file
                    const int buffSize = 4096;
                    byte[]    buffer   = new byte[4096];

                    long bytesLeft = fileStart;
                    while (bytesLeft > 0)
                    {
                        int readSize = (bytesLeft > buffSize) ? buffSize : (int)bytesLeft;
                        int read     = crypto.Read(buffer, 0, readSize);
                        bytesLeft -= read;
                    }

                    // setup write file
                    using (FileStream outstream = new FileStream(destination, FileMode.Create, FileAccess.Write))
                    {
                        // read files, write the right one :P
                        for (int i = 0; i < attachments.Length; i++)
                        {
                            bytesLeft = attachments[i];

                            while (bytesLeft > 0)
                            {
                                int readSize = (bytesLeft > buffSize) ? buffSize : (int)bytesLeft;
                                int read     = crypto.Read(buffer, 0, readSize);
                                bytesLeft -= read;

                                if (i == index)
                                {
                                    outstream.Write(buffer, 0, read);
                                }
                            }
                        }
                    }
                }
        }
Exemple #8
0
        private void ShowMessage(OpPost post, OpPost parent)
        {
            if (parent == null)
            {
                parent = post;
            }

            string responseTo = "";

            if (parent != post)
            {
                responseTo = "Response to ";
            }

            // header
            string content = responseTo + "<b><font size=2>" + parent.Info.Subject + @"</font></b> posted by " +
                             Core.GetName(post.Header.SourceID) + @" at " +
                             Utilities.FormatTime(post.Header.Time) + @"<br>";

            // edit time
            if (post.Header.EditTime > post.Header.Time)
            {
                content += "Edited at " + Utilities.FormatTime(post.Header.EditTime) + "<br>";
            }

            // attached files
            if (post.Attached.Count > 1)
            {
                string attachHtml = "";

                for (int i = 0; i < post.Attached.Count; i++)
                {
                    if (post.Attached[i].Name == "body")
                    {
                        continue;
                    }

                    attachHtml += "<a href='http://attach/" + i.ToString() + "'>" + post.Attached[i].Name + "</a> (" + Utilities.ByteSizetoString(post.Attached[i].Size) + "), ";
                }

                attachHtml = attachHtml.TrimEnd(new char[] { ' ', ',' });

                content += "<b>Attachments: </b> " + attachHtml;
            }

            content += "<br>";

            // actions
            string actions = "";

            if (!post.Header.Archived)
            {
                actions += @" <a href='http://reply'>Reply</a>";
            }

            if (post.Header.SourceID == Core.UserID)
            {
                if (!post.Header.Archived)
                {
                    actions += @", <a href='http://edit'>Edit</a>";
                }

                if (post == parent)
                {
                    if (post.Header.Archived)
                    {
                        actions += @", <a href='http://restore'>Restore</a>";
                    }
                    else
                    {
                        actions += @", <a href='http://archive'>Remove</a>";
                    }
                }
            }

            content += "<b>Actions: </b>" + actions.Trim(',', ' ');

            SetHeader(content);


            // body

            try
            {
                using (TaggedStream stream = new TaggedStream(Boards.GetPostPath(post.Header), Core.GuiProtocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(stream, post.Header.FileKey))
                    {
                        int    buffSize  = 4096;
                        byte[] buffer    = new byte[4096];
                        long   bytesLeft = post.Header.FileStart;
                        while (bytesLeft > 0)
                        {
                            int readSize = (bytesLeft > (long)buffSize) ? buffSize : (int)bytesLeft;
                            int read     = crypto.Read(buffer, 0, readSize);
                            bytesLeft -= (long)read;
                        }

                        // load file
                        foreach (PostFile file in post.Attached)
                        {
                            if (file.Name == "body")
                            {
                                byte[] msgBytes = new byte[file.Size];
                                crypto.Read(msgBytes, 0, (int)file.Size);

                                UTF8Encoding utf = new UTF8Encoding();

                                PostBody.Clear();
                                PostBody.SelectionFont  = new Font("Tahoma", 9.75f);
                                PostBody.SelectionColor = Color.Black;

                                if (post.Info.Format == TextFormat.RTF)
                                {
                                    PostBody.Rtf = utf.GetString(msgBytes);
                                }
                                else
                                {
                                    PostBody.Text = utf.GetString(msgBytes);
                                }

                                PostBody.DetectLinksDefault();
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error Opening Post: " + ex.Message);
            }
        }
Exemple #9
0
        private void LoadHeaderFile(string path, OpStorage storage, bool reload, bool working)
        {
            try
            {
                if (!File.Exists(path))
                {
                    return;
                }

                bool cached = Network.Routing.InCacheArea(storage.UserID);
                bool local  = false;

                byte[] key = working ? LocalFileKey : storage.File.Header.FileKey;

                using (TaggedStream filex = new TaggedStream(path, Network.Protocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
                    {
                        PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                        G2Header header = null;

                        ulong currentUID = 0;

                        while (stream.ReadPacket(ref header))
                        {
                            if (!working && header.Name == StoragePacket.Root)
                            {
                                StorageRoot packet = StorageRoot.Decode(header);

                                local = Core.UserID == storage.UserID ||
                                        GetHigherRegion(Core.UserID, packet.ProjectID).Contains(storage.UserID) ||
                                        Trust.GetDownlinkIDs(Core.UserID, packet.ProjectID, 1).Contains(storage.UserID);
                            }

                            if (header.Name == StoragePacket.File)
                            {
                                StorageFile packet = StorageFile.Decode(header);

                                if (packet == null)
                                {
                                    continue;
                                }

                                bool historyFile = true;
                                if (packet.UID != currentUID)
                                {
                                    historyFile = false;
                                    currentUID  = packet.UID;
                                }

                                OpFile file = null;
                                if (!FileMap.SafeTryGetValue(packet.HashID, out file))
                                {
                                    file = new OpFile(packet);
                                    FileMap.SafeAdd(packet.HashID, file);
                                }

                                InternalFileMap.SafeAdd(packet.InternalHashID, file);

                                if (!reload)
                                {
                                    file.References++;
                                }

                                if (!working) // if one ref is public, then whole file is marked public
                                {
                                    file.Working = false;
                                }

                                if (packet.HashID == 0 || packet.InternalHash == null)
                                {
                                    Debug.Assert(false);
                                    continue;
                                }

                                string filepath = GetFilePath(packet.HashID);
                                file.Downloaded = File.Exists(filepath);

                                if (Loading && file.Downloaded && !ReferencedPaths.Contains(filepath))
                                {
                                    ReferencedPaths.Add(filepath);
                                }

                                if (!file.Downloaded)
                                {
                                    // if in local range only store latest
                                    if (local && !historyFile)
                                    {
                                        DownloadFile(storage.UserID, packet);
                                    }

                                    // if storage is in cache range, download all files
                                    else if (Network.Established && cached)
                                    {
                                        DownloadFile(storage.UserID, packet);
                                    }
                                }

                                // on link update, if in local range, get latest files
                                // (handled by location update, when it sees a new version of storage component is available)
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
            }
        }
Exemple #10
0
        public void SaveLocal(uint project)
        {
            try
            {
                string tempPath = Core.GetTempPath();
                byte[] key      = Utilities.GenerateKey(Core.StrongRndGen, 256);

                using (IVCryptoStream stream = IVCryptoStream.Save(tempPath, key))
                {
                    // write loaded projects
                    WorkingStorage working = null;
                    if (Working.ContainsKey(project))
                    {
                        working = Working[project];
                    }

                    if (working != null)
                    {
                        Protocol.WriteToFile(new StorageRoot(working.ProjectID), stream);
                        working.WriteWorkingFile(stream, working.RootFolder, true);

                        working.Modified = false;

                        try { File.Delete(GetWorkingPath(project)); }
                        catch { }
                    }

                    // open old file and copy entries, except for working
                    OpStorage local = GetStorage(Core.UserID);

                    if (local != null)
                    {
                        string oldPath = GetFilePath(local);

                        if (File.Exists(oldPath))
                        {
                            using (TaggedStream file = new TaggedStream(oldPath, Network.Protocol))
                                using (IVCryptoStream crypto = IVCryptoStream.Load(file, local.File.Header.FileKey))
                                {
                                    PacketStream oldStream = new PacketStream(crypto, Protocol, FileAccess.Read);
                                    bool         write     = false;
                                    G2Header     g2header  = null;

                                    while (oldStream.ReadPacket(ref g2header))
                                    {
                                        if (g2header.Name == StoragePacket.Root)
                                        {
                                            StorageRoot root = StorageRoot.Decode(g2header);

                                            write = (root.ProjectID != project);
                                        }

                                        //copy packet right to new file
                                        if (write) //crit test
                                        {
                                            stream.Write(g2header.Data, g2header.PacketPos, g2header.PacketSize);
                                        }
                                    }
                                }
                        }
                    }

                    stream.WriteByte(0); // signal last packet

                    stream.FlushFinalBlock();
                }

                SavingLocal = true; // prevents auto-integrate from re-calling saveLocal
                OpVersionedFile vfile = Cache.UpdateLocal(tempPath, key, BitConverter.GetBytes(Core.TimeNow.ToUniversalTime().ToBinary()));
                SavingLocal = false;

                Store.PublishDirect(Core.Trust.GetLocsAbove(), Core.UserID, ServiceID, FileTypeCache, vfile.SignedHeader);
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error updating local " + ex.Message);
            }

            if (StorageUpdate != null)
            {
                Core.RunInGuiThread(StorageUpdate, GetStorage(Core.UserID));
            }
        }
Exemple #11
0
        private void ShowMessage(LocalMail message)
        {
            if (message == null)
            {
                SetHeader("");
                MessageBody.Clear();

                return;
            }


            string content = "<b><font size=2>" + message.Info.Subject + "</font></b> from " +
                             Core.GetName(message.Header.SourceID) + ", sent " +
                             Utilities.FormatTime(message.Info.Date) + @"<br> 
                              <b>To:</b> " + Mail.GetNames(message.To) + "<br>";

            if (message.CC.Count > 0)
            {
                content += "<b>CC:</b> " + Mail.GetNames(message.CC) + "<br>";
            }

            if (message.Attached.Count > 1)
            {
                string attachHtml = "";

                for (int i = 0; i < message.Attached.Count; i++)
                {
                    if (message.Attached[i].Name == "body")
                    {
                        continue;
                    }

                    attachHtml += "<a href='http://attach/" + i.ToString() + "'>" + message.Attached[i].Name + "</a> (" + Utilities.ByteSizetoString(message.Attached[i].Size) + "), ";
                }

                attachHtml = attachHtml.TrimEnd(new char[] { ' ', ',' });

                content += "<b>Attachments: </b> " + attachHtml;
            }

            content += "<br>";

            string actions = "";

            if (message.Header.TargetID == Core.UserID)
            {
                actions += @"<a href='http://reply" + "'>Reply</a>";
            }

            actions += @", <a href='http://forward'>Forward</a>";
            actions += @", <a href='http://delete'>Delete</a>";

            content += "<b>Actions: </b>" + actions.Trim(',', ' ');

            SetHeader(content);

            // body

            try
            {
                using (TaggedStream stream = new TaggedStream(Mail.GetLocalPath(message.Header), Core.GuiProtocol))
                    using (CryptoStream crypto = IVCryptoStream.Load(stream, message.Header.LocalKey))
                    {
                        int    buffSize  = 4096;
                        byte[] buffer    = new byte[4096];
                        long   bytesLeft = message.Header.FileStart;
                        while (bytesLeft > 0)
                        {
                            int readSize = (bytesLeft > buffSize) ? buffSize : (int)bytesLeft;
                            int read     = crypto.Read(buffer, 0, readSize);
                            bytesLeft -= read;
                        }

                        // load file
                        foreach (MailFile file in message.Attached)
                        {
                            if (file.Name == "body")
                            {
                                byte[] msgBytes = new byte[file.Size];
                                crypto.Read(msgBytes, 0, (int)file.Size);

                                UTF8Encoding utf = new UTF8Encoding();

                                MessageBody.Clear();
                                MessageBody.SelectionFont  = new Font("Tahoma", 9.75f);
                                MessageBody.SelectionColor = Color.Black;

                                if (message.Info.Format == TextFormat.RTF)
                                {
                                    MessageBody.Rtf = utf.GetString(msgBytes);
                                }
                                else
                                {
                                    MessageBody.Text = utf.GetString(msgBytes);
                                }

                                MessageBody.DetectLinksDefault();
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error Opening Mail: " + ex.Message);
            }

            if (message.Header.Read == false)
            {
                message.Header.Read = true;

                Mail.SaveMailbox = true;

                if (MessageView.SelectedNodes.Count > 0)
                {
                    ((MessageNode)MessageView.SelectedNodes[0]).UpdateRow();
                }
            }
        }
Exemple #12
0
        private static string LoadProfile(ProfileService service, OpProfile profile, string tempPath, Dictionary <string, string> textFields, Dictionary <string, string> fileFields)
        {
            string template = null;

            textFields.Clear();
            textFields["local_help"] = (profile.UserID == service.Core.UserID) ? "<font size=2>Right-click or click <a href='http://edit'>here</a> to Edit</font>" : "";

            if (fileFields != null)
            {
                fileFields.Clear();
            }

            if (!profile.Loaded)
            {
                service.LoadProfile(profile.UserID);
            }

            try
            {
                using (TaggedStream stream = new TaggedStream(service.GetFilePath(profile), service.Core.GuiProtocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(stream, profile.File.Header.FileKey))
                    {
                        int    buffSize  = 4096;
                        byte[] buffer    = new byte[4096];
                        long   bytesLeft = profile.EmbeddedStart;
                        while (bytesLeft > 0)
                        {
                            int readSize = (bytesLeft > (long)buffSize) ? buffSize : (int)bytesLeft;
                            int read     = crypto.Read(buffer, 0, readSize);
                            bytesLeft -= (long)read;
                        }

                        // load file
                        foreach (ProfileAttachment attached in profile.Attached)
                        {
                            if (attached.Name.StartsWith("template"))
                            {
                                byte[] html = new byte[attached.Size];
                                crypto.Read(html, 0, (int)attached.Size);

                                UTF8Encoding utf = new UTF8Encoding();
                                template = utf.GetString(html);
                            }

                            else if (attached.Name.StartsWith("fields"))
                            {
                                byte[] data = new byte[attached.Size];
                                crypto.Read(data, 0, (int)attached.Size);

                                int          start = 0, length = data.Length;
                                G2ReadResult streamStatus = G2ReadResult.PACKET_GOOD;

                                while (streamStatus == G2ReadResult.PACKET_GOOD)
                                {
                                    G2ReceivedPacket packet = new G2ReceivedPacket();
                                    packet.Root = new G2Header(data);

                                    streamStatus = G2Protocol.ReadNextPacket(packet.Root, ref start, ref length);

                                    if (streamStatus != G2ReadResult.PACKET_GOOD)
                                    {
                                        break;
                                    }

                                    if (packet.Root.Name == ProfilePacket.Field)
                                    {
                                        ProfileField field = ProfileField.Decode(packet.Root);

                                        if (field.Value == null)
                                        {
                                            continue;
                                        }

                                        if (field.FieldType == ProfileFieldType.Text)
                                        {
                                            textFields[field.Name] = UTF8Encoding.UTF8.GetString(field.Value);
                                        }
                                        else if (field.FieldType == ProfileFieldType.File && fileFields != null)
                                        {
                                            fileFields[field.Name] = UTF8Encoding.UTF8.GetString(field.Value);
                                        }
                                    }
                                }
                            }

                            else if (attached.Name.StartsWith("file=") && fileFields != null)
                            {
                                string name = attached.Name.Substring(5);

                                try
                                {
                                    string fileKey = null;
                                    foreach (string key in fileFields.Keys)
                                    {
                                        if (name == fileFields[key])
                                        {
                                            fileKey = key;
                                            break;
                                        }
                                    }

                                    fileFields[fileKey] = tempPath + Path.DirectorySeparatorChar + name;

                                    using (FileStream extract = new FileStream(fileFields[fileKey], FileMode.CreateNew, FileAccess.Write))
                                    {
                                        long   remaining = attached.Size;
                                        byte[] buff      = new byte[2096];

                                        while (remaining > 0)
                                        {
                                            int read = (remaining > 2096) ? 2096 : (int)remaining;
                                            remaining -= read;

                                            crypto.Read(buff, 0, read);
                                            extract.Write(buff, 0, read);
                                        }
                                    }
                                }
                                catch
                                { }
                            }
                        }
                    }
            }
            catch (Exception)
            {
            }

            return(template);
        }
Exemple #13
0
        internal void CollectionDownloadFinished(string path, object[] args)
        {
            ShareCollection collection = args[0] as ShareCollection;
            ushort client = (ushort) args[1];

            collection.Files.LockWriting(() =>
            {
                foreach (SharedFile file in collection.Files.Where(c => c.ClientID == client).ToArray())
                    collection.Files.Remove(file);
            });

            try
            {
                string finalpath = GetPublicPath(collection);

                File.Delete(finalpath);
                File.Copy(path, finalpath);

                using (TaggedStream tagged = new TaggedStream(finalpath, Network.Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(tagged, collection.Key))
                {
                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header root = null;

                    collection.Files.LockWriting(() =>
                    {
                        while (stream.ReadPacket(ref root))
                            if (root.Name == SharingPacket.File)
                            {
                                SharedFile file = SharedFile.Decode(root, client);

                                // dont add dupes from diff client ids
                                if (collection.Files.Any(f => f.Size == file.Size && Utilities.MemCompare(f.Hash, file.Hash)))
                                    continue;

                                file.FileID = OpTransfer.GetFileID(ServiceID, file.Hash, file.Size);
                                collection.Files.SafeAdd(file);
                            }
                    });
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Mail", "Error loading local mail " + ex.Message);
            }

            collection.Status = collection.Files.SafeCount + " Files Shared";

            Core.RunInGuiThread(GuiCollectionUpdate, collection.UserID);
        }
Exemple #14
0
        void OpenFiles()
        {
            SharedFile file = null;

            // while files on open list
            while (OpenQueue.Count > 0 && !KillThreads)
            {
                lock (OpenQueue)
                {
                    file = OpenQueue.First.Value;
                    OpenQueue.RemoveFirst();
                }

                try
                {
                    if(!Directory.Exists(DownloadPath))
                        Directory.CreateDirectory(DownloadPath);

                    string finalpath = DownloadPath + file.Name;

                    int i = 1;
                    while(File.Exists(finalpath))
                        finalpath = DownloadPath + "(" + (i++) + ") " + file.Name;

                    // decrypt file to temp dir
                    file.FileStatus = "Unsecuring...";

                    string tempPath = Core.GetTempPath();

                    using (FileStream tempFile = new FileStream(tempPath, FileMode.CreateNew))
                    using (TaggedStream encFile = new TaggedStream(GetFilePath(file), Network.Protocol))
                    using (IVCryptoStream stream = IVCryptoStream.Load(encFile, file.FileKey))
                    {
                        int read = OpenBufferSize;
                        while (read == OpenBufferSize)
                        {
                            read = stream.Read(OpenBuffer, 0, OpenBufferSize);
                            tempFile.Write(OpenBuffer, 0, read);
                        }
                    }

                    // move to official path
                    File.Move(tempPath, finalpath);

                    file.SystemPath = finalpath;

                    file.FileStatus = "File in Downloads Folder";

                    Process.Start(finalpath);

                    Core.RunInCoreAsync(() => SaveHeaders());
                }
                catch (Exception ex)
                {
                    Network.UpdateLog("Sharing", "Error: " + ex.Message);
                }
            }

            OpenFilesHandle = null;
        }
Exemple #15
0
        public void LoadPlan(ulong id)
        {
            if (Core.InvokeRequired)
            {
                Core.RunInCoreBlocked(delegate() { LoadPlan(id); });
                return;
            }

            OpPlan plan = GetPlan(id, false);

            if (plan == null)
            {
                return;
            }

            // if local plan file not created yet
            if (plan.File.Header == null)
            {
                if (plan.UserID == Core.UserID)
                {
                    plan.Init();
                }

                return;
            }

            try
            {
                string path = Cache.GetFilePath(plan.File.Header);

                if (!File.Exists(path))
                {
                    return;
                }

                plan.Init();

                List <int> myjobs = new List <int>();

                using (TaggedStream file = new TaggedStream(path, Network.Protocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(file, plan.File.Header.FileKey))
                    {
                        PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                        G2Header root = null;

                        while (stream.ReadPacket(ref root))
                        {
                            if (root.Name == PlanPacket.Block)
                            {
                                PlanBlock block = PlanBlock.Decode(root);

                                if (block != null)
                                {
                                    plan.AddBlock(block);
                                }
                            }

                            if (root.Name == PlanPacket.Goal)
                            {
                                PlanGoal goal = PlanGoal.Decode(root);

                                if (goal != null)
                                {
                                    plan.AddGoal(goal);
                                }
                            }

                            if (root.Name == PlanPacket.Item)
                            {
                                PlanItem item = PlanItem.Decode(root);

                                if (item != null)
                                {
                                    plan.AddItem(item);
                                }
                            }
                        }
                    }

                plan.Loaded = true;


                // check if we have tasks for this person, that those jobs still exist
                //crit do check with plan items, make sure goal exists for them

                /*List<PlanTask> removeList = new List<PlanTask>();
                 * bool update = false;
                 *
                 * foreach(List<PlanTask> tasklist in LocalPlan.TaskMap.Values)
                 * {
                 *  removeList.Clear();
                 *
                 *  foreach (PlanTask task in tasklist)
                 *      if(task.Assigner == id)
                 *          if(!myjobs.Contains(task.Unique))
                 *              removeList.Add(task);
                 *
                 *  foreach(PlanTask task in removeList)
                 *      tasklist.Remove(task);
                 *
                 *  if (removeList.Count > 0)
                 *      update = true;
                 * }
                 *
                 * if (update)
                 *  SaveLocal();*/
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Plan", "Error loading plan " + ex.Message);
            }
        }
Exemple #16
0
        public void Load(LoadModeType loadMode)
        {
            RijndaelManaged Password = new RijndaelManaged();

            Password.Key = PasswordKey;

            byte[] iv   = new byte[16];
            byte[] salt = new byte[4];

            OpCore lookup = null;

            if (Core != null)
            {
                lookup = Core.Context.Lookup;
            }

            try
            {
                using (TaggedStream file = new TaggedStream(ProfilePath, Protocol, ProcessSplash)) // tagged with splash
                {
                    // first 16 bytes IV, next 4 bytes is salt
                    file.Read(iv, 0, 16);
                    file.Read(salt, 0, 4);
                    Password.IV = iv;

                    using (CryptoStream crypto = new CryptoStream(file, Password.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                        G2Header root = null;
                        while (stream.ReadPacket(ref root))
                        {
                            if (loadMode == LoadModeType.Settings)
                            {
                                if (root.Name == IdentityPacket.OperationSettings)
                                {
                                    Settings = SettingsPacket.Decode(root);
                                }

                                if (root.Name == IdentityPacket.UserInfo && Core != null &&
                                    (Core.Sim == null || !Core.Sim.Internet.FreshStart))
                                {
                                    Core.IndexInfo(UserInfo.Decode(root));
                                }

                                // save icon to identity file because only root node saves icon/splash to link file
                                // to minimize link file size, but allow user to set custom icon/splash if there are not overrides
                                if (root.Name == IdentityPacket.Icon)
                                {
                                    OpIcon = IconPacket.Decode(root).OpIcon;
                                }
                            }

                            if (lookup != null && (loadMode == LoadModeType.AllCaches || loadMode == LoadModeType.LookupCache))
                            {
                                if (root.Name == IdentityPacket.LookupCachedIP)
                                {
                                    lookup.Network.Cache.AddSavedContact(CachedIP.Decode(root));
                                }

                                if (root.Name == IdentityPacket.LookupCachedWeb)
                                {
                                    lookup.Network.Cache.AddWebCache(WebCache.Decode(root));
                                }
                            }

                            if (loadMode == LoadModeType.AllCaches)
                            {
                                if (root.Name == IdentityPacket.OpCachedIP)
                                {
                                    Core.Network.Cache.AddSavedContact(CachedIP.Decode(root));
                                }

                                if (root.Name == IdentityPacket.OpCachedWeb)
                                {
                                    Core.Network.Cache.AddWebCache(WebCache.Decode(root));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }