Пример #1
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);
        }
Пример #2
0
        private void ApplyDiff(ulong id)
        {
            // change log - who / not

            // read file uid

                // if exists locally
                    // if integrated mark as so
                    // else mark as changed, run history diff, and use last note

                // if doesnt exist
                    // add file as a temp
                    // user does - add to storage, to add it

                // if remote doesnt have any record of local file, ignore

            ChangeCount[id] = 0;

            OpStorage storage = Storages.GetStorage(id);

            if (storage == null)
            {
                FailedDiffs.Add(id);
                return;
            }

            string path = Storages.GetFilePath(storage);

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

            try
            {
                using (TaggedStream filex = new TaggedStream(path, Core.GuiProtocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, storage.File.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Storages.Protocol, FileAccess.Read);

                    ulong remoteUID = 0;
                    FolderNode currentFolder = RootFolder;
                    bool readingProject = false;

                    G2Header header = null;

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

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                // if new UID
                                if (remoteUID == folder.UID)
                                    continue;

                                remoteUID = folder.UID;

                                // check scope
                                bool ignore = false;
                                if (folder.Scope.Count > 0 && !Trust.IsInScope(folder.Scope, UserID, ProjectID))
                                    ignore = true;

                                bool added = false;

                                while (!added)
                                {
                                    if (currentFolder.Details.UID == folder.ParentUID)
                                    {
                                        // if folder exists with UID
                                        if (currentFolder.Folders.ContainsKey(remoteUID))
                                            currentFolder = currentFolder.Folders[remoteUID];

                                        // else add folder as temp, mark as changed
                                        else
                                        {
                                            if (ignore) // temp so traverse works, but not saved in structure
                                            {
                                                currentFolder = new FolderNode(this, folder, currentFolder, false);
                                                break;
                                            }
                                            else
                                                currentFolder = currentFolder.AddFolderInfo(folder, true);
                                        }

                                        bool found = false;

                                        currentFolder.Archived.LockReading(delegate()
                                        {
                                            foreach (StorageFolder archive in currentFolder.Archived)
                                                if (Storages.ItemDiff(archive, folder) == StorageActions.None)
                                                    if (archive.Date == folder.Date)
                                                    {
                                                        found = true;
                                                        break;
                                                    }
                                        });

                                        if (!found)
                                        {
                                            currentFolder.Changes[id] = folder;
                                            currentFolder.UpdateOverlay();
                                        }

                                        // diff file properties, if different, add as change
                                        /*if (currentFolder.Temp || Storages.ItemDiff(currentFolder.Details, folder) != StorageActions.None)
                                        {
                                            currentFolder.Changes[id] = folder;
                                            currentFolder.UpdateOverlay();
                                        }*/

                                        added = true;
                                    }
                                    else if (currentFolder.Parent.GetType() == typeof(FolderNode))
                                        currentFolder = (FolderNode)currentFolder.Parent;
                                    else
                                        break;
                                }
                            }

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

                                // if new UID
                                if (remoteUID == file.UID)
                                    continue;

                                remoteUID = file.UID;

                                // check scope
                                if (file.Scope.Count > 0 && !Trust.IsInScope(file.Scope, UserID, ProjectID))
                                    continue;

                                FileItem currentFile = null;

                                // if file exists with UID
                                if (currentFolder.Files.ContainsKey(remoteUID))
                                    currentFile = currentFolder.Files[remoteUID];

                                // else add file as temp, mark as changed
                                else
                                    currentFile = currentFolder.AddFileInfo(file, true);

                                // if file is integrated, still add, so that reject functions

                                // true if file doesnt exist in local file history
                                // if it does exist and file is newer than latest, true

                                bool found = false;

                                currentFile.Archived.LockReading(delegate()
                                {
                                    foreach (StorageFile archive in currentFile.Archived)
                                        if (Storages.ItemDiff(archive, file) == StorageActions.None)
                                            if (archive.Date == file.Date)
                                            {
                                                found = true;
                                                break;
                                            }
                                });

                                if (!found)
                                    currentFile.Changes[id] = file;
                            }
                        }
                    }
                }
            }
            catch
            {
                FailedDiffs.Add(id);
            }
        }
Пример #3
0
        private void Cache_FileAquired(OpVersionedFile cachefile)
        {
            try
            {
                // get link directly, even if in unloaded state we need the same reference
                OpTrust trust = null;
                TrustMap.SafeTryGetValue(cachefile.UserID, out trust);

                if (trust == null)
                {
                    trust = new OpTrust(cachefile);
                    TrustMap.SafeAdd(cachefile.UserID, trust);
                }
                else
                    trust.File = cachefile;

                // clean roots, if link has loopID, remove loop node entirely, it will be recreated if needed later
                ProjectRoots.LockReading(delegate()
                {
                    foreach (uint project in ProjectRoots.Keys)
                    {
                        OpLink link = trust.GetLink(project);

                        if (link == null)
                            continue;

                        ThreadedList<OpLink> roots = ProjectRoots[project];

                        roots.SafeRemove(link);

                        // remove loop node
                        if (link.LoopRoot != null)
                            roots.LockReading(delegate()
                            {
                                foreach (OpLink root in roots)
                                    if (root.UserID == link.LoopRoot.UserID)
                                    {
                                        roots.SafeRemove(root); // root is a loop node

                                        // remove associations with loop node
                                        foreach (OpLink downlink in root.Downlinks)
                                            downlink.LoopRoot = null;

                                        break;
                                    }
                            });
                    }
                });

                trust.Reset();

                // load data from link file
                string inheritName = null;
                string inheritOp = null;
                Bitmap inheritIcon = null;
                byte[] inheritSplash = null;

                using (TaggedStream file = new TaggedStream(Cache.GetFilePath(cachefile.Header), Network.Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(file, cachefile.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header packetRoot = null;

                    while (stream.ReadPacket(ref packetRoot))
                    {
                        if (packetRoot.Name == DataPacket.SignedData)
                        {
                            SignedData signed = SignedData.Decode(packetRoot);
                            G2Header embedded = new G2Header(signed.Data);

                            // figure out data contained
                            if (G2Protocol.ReadPacket(embedded))
                            {
                                if (embedded.Name == TrustPacket.ProjectData)
                                {
                                    ProjectData project = ProjectData.Decode(embedded);
                                    Process_ProjectData(trust, signed, project);

                                    if (project.ID == 0)
                                    {
                                        inheritName = project.UserName;
                                        inheritOp = project.Name;
                                    }
                                }

                                else if (embedded.Name == TrustPacket.LinkData)
                                    Process_LinkData(trust, signed, LinkData.Decode(embedded));
                            }
                        }

                        else if (packetRoot.Name == TrustPacket.WebCache)
                            Network.Cache.AddWebCache(WebCache.Decode(packetRoot));

                        else if (packetRoot.Name == TrustPacket.Icon)
                            inheritIcon = IconPacket.Decode(packetRoot).OpIcon;

                        else if (packetRoot.Name == TrustPacket.Splash)
                        {
                            LargeDataPacket splash = LargeDataPacket.Decode(packetRoot);

                            if (splash.Size > 0)
                                inheritSplash = LargeDataPacket.Read(splash, stream, TrustPacket.Splash);
                        }
                    }
                }

                // set new header
                trust.Loaded = true;

                // set as root if node has no uplinks
                foreach (OpLink link in trust.Links.Values)
                    if (link.Uplink == null)
                        AddRoot(link);
                    // if uplink is unknown - process link data will search for the unknown parent

                // if loop created, create new loop node with unique ID, assign all nodes in loop the ID and add as downlinks
                foreach (OpLink link in trust.Links.Values)
                    if (IsLooped(link))
                    {
                        uint project = link.Project;

                        OpLink loop = new OpTrust(project, (ulong)Core.RndGen.Next()).GetLink(project);
                        loop.IsLoopRoot = true;

                        List<ulong> uplinks = GetUnconfirmedUplinkIDs(trust.UserID, project);
                        uplinks.Add(trust.UserID);

                        foreach (ulong uplink in uplinks)
                        {
                            OpLink member = GetLink(uplink, project);

                            if (member == null)
                                continue;

                            member.LoopRoot = loop;

                            loop.Downlinks.Add(member);
                            loop.Confirmed.Add(member.UserID); //needed for getlowers
                        }

                        AddRoot(loop);
                    }

                trust.CheckRequestVersions();

                if (LinkUpdate != null)
                    LinkUpdate.Invoke(trust);

                if (Core.NewsWorthy(trust.UserID, 0, false))
                    Core.MakeNews(ServiceIDs.Trust, "Trust updated by " + Core.GetName(trust.UserID), trust.UserID, 0, true);

                // update subs
                if (Network.Established)
                {
                    List<LocationData> locations = new List<LocationData>();

                    ProjectRoots.LockReading(delegate()
                    {
                        foreach (uint project in ProjectRoots.Keys)
                            if (Core.UserID == trust.UserID || IsHigher(trust.UserID, project))
                                GetLocsBelow(Core.UserID, project, locations);
                    });

                    Store.PublishDirect(locations, trust.UserID, ServiceID, 0, cachefile.SignedHeader);
                }

                // inherit local settings
                if(Core.UserID == trust.UserID)
                {
                    if (inheritName != null)
                        Core.User.Settings.UserName = inheritName;
                }

                // inherit settings from highest node, first node in loop
                if (IsInheritNode(trust.UserID))
                {
                    if (inheritOp != null)
                        Core.User.Settings.Operation = inheritOp;

                    if (inheritIcon != null)
                    {
                        Core.User.OpIcon = inheritIcon;
                        Core.User.IconUpdate();
                    }

                    if (inheritSplash != null)
                        Core.User.OpSplash = (Bitmap)Bitmap.FromStream(new MemoryStream(inheritSplash));
                    else
                        Core.User.OpSplash = null;
                }

                // update interface node
                Core.RunInGuiThread(GuiUpdate, trust.UserID);

                foreach (OpLink link in trust.Links.Values)
                    foreach (OpLink downlink in link.Downlinks)
                        Core.RunInGuiThread(GuiUpdate, downlink.UserID);

            }
            catch (Exception ex)
            {
                Network.UpdateLog("Link", "Error loading file " + ex.Message);
            }
        }
Пример #4
0
        private void LoadHeader(string path, byte[] key)
        {
            try
            {
                using (TaggedStream filex = new TaggedStream(path, Core.GuiProtocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
                {
                    PacketStream stream = new PacketStream(crypto, Storages.Protocol, FileAccess.Read);

                    FolderNode currentFolder = RootFolder;
                    bool readingProject = false;

                    G2Header header = null;

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

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        // show archived if selected, only add top uid, not copies

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                bool added = false;

                                while (!added)
                                {
                                    if (currentFolder.Details.UID == folder.ParentUID)
                                    {
                                        currentFolder = currentFolder.AddFolderInfo(folder, false);

                                        // re-select on re-load
                                        if (SelectedFolder != null && currentFolder.Details.UID == SelectedFolder.Details.UID)
                                        {
                                            currentFolder.Selected = true;
                                            SelectedFolder = currentFolder;
                                        }

                                        added = true;
                                    }
                                    else if (currentFolder.Parent.GetType() == typeof(FolderNode))
                                        currentFolder = (FolderNode)currentFolder.Parent;
                                    else
                                        break;
                                }

                                if (!added)
                                {
                                    Debug.Assert(false);
                                    throw new Exception("Error loading CFS");
                                }
                            }

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

                                currentFolder.AddFileInfo(file, false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
            }
        }
Пример #5
0
        private void RescanDiff(ulong id)
        {
            /*
             * see if uid exists in rescan map
            if file
                add to changes
            if folder
                add temp if uid doesnt exist
                set inTarget[uid], add further uids if recurse set
             */

            OpStorage storage = Storages.GetStorage(id);

            if (storage == null)
                return;

            string path = Storages.GetFilePath(storage);

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

            try
            {
                using (TaggedStream filex = new TaggedStream(path, Core.GuiProtocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, storage.File.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Storages.Protocol, FileAccess.Read);

                    ulong remoteUID = 0;
                    FolderNode currentFolder = RootFolder;
                    bool readingProject = false;

                    G2Header header = null;

                    List<ulong> Recursing = new List<ulong>();

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

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                // if new UID
                                if (remoteUID == folder.UID)
                                    continue;

                                remoteUID = folder.UID;

                                if (RescanFolderMap.ContainsKey(remoteUID))
                                    if (RescanFolderMap[remoteUID].Recurse)
                                        Recursing.Add(remoteUID);

                                if (Recursing.Count > 0 || RescanFolderMap.ContainsKey(remoteUID))
                                {
                                    bool added = false;

                                    while (!added)
                                    {
                                        if (currentFolder.Details.UID == folder.ParentUID)
                                        {
                                            // if folder exists with UID
                                            if (currentFolder.Folders.ContainsKey(remoteUID))
                                                currentFolder = currentFolder.Folders[remoteUID];

                                            // else add folder as temp, mark as changed
                                            else
                                                currentFolder = currentFolder.AddFolderInfo(folder, true);

                                            // diff file properties, if different, add as change
                                            if (currentFolder.Temp || Storages.ItemDiff(currentFolder.Details, folder) != StorageActions.None)
                                            {
                                                currentFolder.Changes[id] = folder;
                                                currentFolder.UpdateOverlay();
                                            }

                                            added = true;
                                        }
                                        else if (currentFolder.Parent.GetType() == typeof(FolderNode))
                                        {
                                            // if current folder id equals recurse marker stop recursing
                                            if (Recursing.Contains(currentFolder.Details.UID))
                                                Recursing.Remove(currentFolder.Details.UID);

                                            currentFolder = (FolderNode)currentFolder.Parent;
                                        }
                                        else
                                            break;
                                    }
                                }
                            }

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

                                // if new UID
                                if (remoteUID == file.UID)
                                    continue;

                                remoteUID = file.UID;

                                if (Recursing.Count > 0 /*|| RescanFileMap.ContainsKey(remoteUID)*/)
                                {
                                    FileItem currentFile = null;

                                    // if file exists with UID
                                    if (currentFolder.Files.ContainsKey(remoteUID))
                                        currentFile = currentFolder.Files[remoteUID];

                                    // else add file as temp, mark as changed
                                    else
                                        currentFile = currentFolder.AddFileInfo(file, true);

                                    //crit check if file is integrated

                                    if (currentFile.Temp || Storages.ItemDiff(currentFile.Details, file) != StorageActions.None)
                                        currentFile.Changes[id] = file;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
Пример #6
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);
            }
        }
Пример #7
0
        public string GetPostTitle(OpPost post)
        {
            // loads info when first demanded, cached afterwards
            if (post.Info == null)
                try
                {
                    string path = GetPostPath(post.Header);
                    if (!File.Exists(path))
                        return "";

                    post.Attached = new List<PostFile>();

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

                        G2Header root = null;

                        while (stream.ReadPacket(ref root))
                        {
                            if (root.Name == BoardPacket.PostInfo)
                                post.Info = PostInfo.Decode(root);

                            else if (root.Name == BoardPacket.PostFile)
                                post.Attached.Add(PostFile.Decode(root));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Network.UpdateLog("Board", "Could not load post " + post.Header.SourceID.ToString() + ": " + ex.Message);
                }

            if (post.Info == null)
                return "";

            if (post.Header.ParentID == 0)
                return post.Info.Subject;
            else
                return post.Info.Quip;
        }
Пример #8
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();
            }
        }
Пример #9
0
        private void LoadWorking()
        {
            OpStorage local = Storages.GetStorage(Core.UserID);

            if (local == null)
                return;

            // load working
            try
            {
                string path = Storages.GetWorkingPath(ProjectID);
                byte[] key = Storages.LocalFileKey;

                if (File.Exists(path)) // use locally committed storage file
                {
                    Modified = true; // working file present on startup, meaning there are changes lingering to be committed
                }
                else
                {
                    path = Storages.GetFilePath(local);

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

                    key = local.File.Header.FileKey;
                }

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

                    G2Header header = null;
                    bool readingProject = false;

                    LocalFolder CurrentFolder = RootFolder;
                    string CurrentPath = RootPath;

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

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                bool added = false;

                                while (!added)
                                {
                                    if (CurrentFolder.Info.UID == folder.ParentUID)
                                    {
                                        // tracked, so need to add multiple folders (archives) with same UIDs
                                        CurrentFolder = CurrentFolder.AddFolderInfo(folder);

                                        added = true;
                                    }
                                    else if (CurrentFolder.Parent == null) // error
                                        break;
                                    else if (CurrentFolder.Parent.GetType() == typeof(LocalFolder))
                                        CurrentFolder = CurrentFolder.Parent;
                                    else
                                        break;
                                }

                                if (!added)
                                {
                                    Debug.Assert(false);
                                    throw new Exception("Error loading CFS");
                                }
                            }

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

                                CurrentFolder.AddFileInfo(file);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading headers " + ex.Message);
            }
        }
Пример #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));
        }
Пример #11
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;
            }
        }
Пример #12
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);
            }
        }
Пример #13
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);
            }
        }
Пример #14
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);
        }
Пример #15
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;
        }
Пример #16
0
        public bool RefreshHigherChanges(ulong id)
        {
            // first remove changes from this id
            RemoveHigherChanges(RootFolder, id);

            bool save = false;

            OpStorage storage = Storages.GetStorage(id);

            if (storage == null)
                return save;

            // this is the first step in auto-integration
            // go through this id's storage file, and add any changes or updates to our own system
            string path = Storages.GetFilePath(storage);

            if (!File.Exists(path))
                return save;

            try
            {
                using (TaggedStream filex = new TaggedStream(path, Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, storage.File.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                    ulong currentUID = 0;
                    LocalFolder currentFolder = RootFolder;
                    LocalFile currentFile = null;
                    bool ignoreCurrent = false;
                    bool readingProject = false;

                    G2Header header = null;

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

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder readFolder = StorageFolder.Decode(header);

                                // if new uid
                                if (currentUID != readFolder.UID)
                                {
                                    // if only 1 entry in changes for previous file, remove it, its probably a dupe of local
                                    // and integration needs more than one file to happen
                                    if (currentFolder.HigherChanges.ContainsKey(id) && currentFolder.HigherChanges[id].Count == 1)
                                        currentFolder.HigherChanges.Remove(id);

                                    // set new id
                                    currentUID = readFolder.UID;

                                    // check scope
                                    ignoreCurrent = false;
                                    if (readFolder.Scope.Count > 0 && !Core.Trust.IsInScope(readFolder.Scope, Core.UserID, ProjectID))
                                        ignoreCurrent = true;

                                    bool added = false;

                                    while (!added)
                                    {
                                        if (currentFolder.Info.UID == readFolder.ParentUID)
                                        {
                                            LocalFolder subFolder = null;
                                            if (currentFolder.Folders.SafeTryGetValue(currentUID, out subFolder))
                                                currentFolder = subFolder;

                                            else
                                            {
                                                // if ignoring, add folder so we can traverse id's file, but dont save changes to local storage mapping
                                                if (ignoreCurrent)
                                                {
                                                    currentFolder = new LocalFolder(currentFolder, readFolder);
                                                    break;
                                                }

                                                // check for conflicting name
                                                currentFolder.Folders.LockReading(delegate()
                                                {
                                                    foreach (LocalFolder subfolder in currentFolder.Folders.Values)
                                                        if (!subfolder.Info.IsFlagged(StorageFlags.Archived) && subfolder.Info.Name == readFolder.Name)
                                                            subfolder.Info.Name = subfolder.Info.Name + ".fix";
                                                });

                                                // if not found, create folder
                                                currentFolder = currentFolder.AddFolderInfo(readFolder);
                                                save = true;
                                            }

                                            added = true;
                                        }

                                        else if (currentFolder.Parent == null)
                                            break; // error, couldn't find parent of folder that was read

                                        else if (currentFolder.Parent.GetType() == typeof(LocalFolder))
                                            currentFolder = currentFolder.Parent;

                                        else
                                            break;
                                    }
                                }

                                // if file does not equal null
                                if (currentFolder != null && !ignoreCurrent)
                                {
                                    // log change if file newer than ours
                                    // if if not in higher's history
                                    // or if file integrated by higher by a node we would have inherited from

                                    // we look for our own file in higher changes, if there then we can auto integrate

                                    if (readFolder.Date >= currentFolder.Info.Date)
                                        if (readFolder.IntegratedID == 0 ||
                                            readFolder.IntegratedID == Core.UserID ||
                                            Core.Trust.IsAdjacent(readFolder.IntegratedID, ProjectID))
                                            currentFolder.AddHigherChange(id, readFolder);
                                }

                            }

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

                                // if new uid
                                if (currentUID != readFile.UID)
                                {
                                    // if only 1 entry in changes for previous file, remove it, its probably a dupe of local
                                    // and integration needs more than one file to happen
                                    if (currentFile != null && currentFile.HigherChanges.ContainsKey(id) && currentFile.HigherChanges[id].Count == 1)
                                        currentFile.HigherChanges.Remove(id);

                                    // set new id
                                    currentUID = readFile.UID;

                                    currentFile = null;

                                    // check scope
                                    ignoreCurrent = false;
                                    if (readFile.Scope.Count > 0 && !Core.Trust.IsInScope(readFile.Scope, Core.UserID, ProjectID))
                                    {
                                        ignoreCurrent = true;
                                        continue;
                                    }

                                    // if file exists with UID, else add file as temp, mark as changed
                                    if (!currentFolder.Files.SafeTryGetValue(currentUID, out currentFile))
                                    {
                                        // check for conflicting name
                                        currentFolder.Files.LockReading(delegate()
                                        {
                                            foreach (LocalFile checkFile in currentFolder.Files.Values)
                                                if (!checkFile.Info.IsFlagged(StorageFlags.Archived) && checkFile.Info.Name == readFile.Name)
                                                    checkFile.Info.Name = checkFile.Info.Name + ".fix";
                                        });

                                        currentFile = currentFolder.AddFileInfo(readFile);
                                        save = true;

                                        if (!Storages.FileExists(currentFile.Info))
                                            Storages.DownloadFile(id, currentFile.Info);
                                    }
                                }

                                // if file does not equal null
                                if (currentFile != null && !ignoreCurrent)
                                {
                                    if (readFile.Date >= currentFile.Info.Date)
                                        if (readFile.IntegratedID == 0 ||
                                            readFile.IntegratedID == Core.UserID ||
                                            Core.Trust.IsAdjacent(readFile.IntegratedID, ProjectID))
                                            currentFile.AddHigherChange(id, readFile);
                                }

                            }
                        }
                    }
                }
            }
            catch
            {

            }

            return save;
        }
Пример #17
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);
        }
Пример #18
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;
        }