Example #1
0
        private DreamMessage GetFile(DreamContext context)
        {
            DreamMessage message;

            string[] parts    = context.GetSuffixes(UriPathFormat.Decoded);
            string   filename = _resourcesPath;

            foreach (string part in parts)
            {
                if (part.EqualsInvariant(".."))
                {
                    _log.WarnFormat("attempted to access file outside of target folder: {0}", string.Join("/", parts));
                    throw new DreamBadRequestException("paths cannot contain '..'");
                }
                filename = Path.Combine(filename, part);
            }
            try {
                message = DreamMessage.FromFile(filename, context.Verb == Verb.HEAD);
            } catch (FileNotFoundException e) {
                message = DreamMessage.NotFound("resource not found: " + String.Join("/", context.GetSuffixes(UriPathFormat.Decoded)));
            } catch (Exception e) {
                message = DreamMessage.BadRequest("invalid path");
            }
            return(message);
        }
Example #2
0
        public void UploadFile()
        {
            // Acquire ADMIN permissions
            Plug p = Utils.BuildPlugForAdmin();

            // Create a random page
            string       id   = null;
            string       path = null;
            DreamMessage msg  = PageUtils.CreateRandomPage(p, out id, out path);

            // Create a file
            string fileName = FileUtils.CreateRamdomFile(null);

            msg      = DreamMessage.FromFile(fileName);
            fileName = XUri.DoubleEncode(System.IO.Path.GetFileName(fileName));

            // Upload file to page
            msg = p.At("pages", id, "files", "=" + fileName).Put(msg);

            // Assert file upload returned 200 OK HTTP status
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "PUT request failed");

            // Delete the page
            PageUtils.DeletePageByID(p, id, true);
        }
Example #3
0
        public Yield TestCreateRetrieveHeadDelete(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            string filename = Path.GetTempFileName();

            using (Stream s = File.OpenWrite(filename)) {
                byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS);
                s.Write(data, 0, data.Length);
            }
            _log.Debug("created file");

            // add a file
            Storage.AtPath(TEST_FILE_URI).Put(DreamMessage.FromFile(filename, false));
            File.Delete(filename);
            _log.Debug("put file");

            // get file and compare contents
            DreamMessage headResponse = Storage.AtPath(TEST_FILE_URI).Invoke(Verb.HEAD, DreamMessage.Ok());

            Assert.AreEqual(TEST_CONTENTS.Length, headResponse.ContentLength);
            _log.Debug("got content length");

            // delete file
            Storage.AtPath(TEST_FILE_URI).Delete();
            _log.Debug("deleted file");
            response.Return(DreamMessage.Ok());
            yield break;
        }
Example #4
0
            public Yield TestCreateRetrieveDelete(DreamContext context, DreamMessage request, Result <DreamMessage> response)
            {
                string filename = Path.GetTempFileName();

                using (Stream s = File.OpenWrite(filename)) {
                    byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS);
                    s.Write(data, 0, data.Length);
                }
                _log.Debug("created file");

                // add a file
                Plug cross = Plug.New(_crossServiceUri);

                _log.DebugFormat("cross service path storage path: {0}", cross.Uri);
                cross.AtPath(TEST_FILE_URI).Put(DreamMessage.FromFile(filename, false));
                File.Delete(filename);
                _log.Debug("put file");

                // get file and compare contents
                string contents = cross.AtPath(TEST_FILE_URI).Get().ToText();

                Assert.AreEqual(TEST_CONTENTS, contents);
                _log.Debug("got file");

                // delete file
                cross.AtPath(TEST_FILE_URI).Delete();
                _log.Debug("deleted file");
                response.Return(DreamMessage.Ok());
                yield break;
            }
Example #5
0
        public Yield GetFileHandler(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            string suffixPath = string.Join("" + Path.DirectorySeparatorChar, context.GetSuffixes(UriPathFormat.Decoded));
            string filename   = Path.Combine(_path, suffixPath);

            if (Directory.Exists(filename))
            {
                XDoc   ret     = new XDoc("files");
                string pattern = context.GetParam("pattern", "");
                AddDirectories(new DirectoryInfo(filename), pattern, ret);
                AddFiles(new DirectoryInfo(filename), pattern, ret);
                response.Return(DreamMessage.Ok(ret));
                yield break;
            }

            DreamMessage message;

            try {
                message = DreamMessage.FromFile(filename, StringUtil.EqualsInvariant(context.Verb, "HEAD"));
            } catch (FileNotFoundException) {
                message = DreamMessage.NotFound("file not found");
            } catch (Exception) {
                message = DreamMessage.BadRequest("invalid path");
            }

            // open file and stream it to the requester
            response.Return(message);
        }
Example #6
0
            public Yield TestCreateForCrossService(DreamContext context, DreamMessage request, Result <DreamMessage> response)
            {
                string filename = Path.GetTempFileName();

                using (Stream s = File.OpenWrite(filename)) {
                    byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS);
                    s.Write(data, 0, data.Length);
                }
                _log.Debug("created file");

                // derive shared storage path
                Plug sharedStorage = Plug.New(Storage.Uri.WithoutLastSegment().At(TEST_SHARED_PATH));

                _log.DebugFormat("shared storage: {0}", sharedStorage.Uri);

                // add a file
                sharedStorage.AtPath(TEST_FILE_URI).Put(DreamMessage.FromFile(filename, false));
                File.Delete(filename);
                _log.Debug("put file");

                // get file and compare contents
                string contents = sharedStorage.AtPath(TEST_FILE_URI).Get().ToText();

                Assert.AreEqual(TEST_CONTENTS, contents);
                _log.Debug("got file");
                response.Return(DreamMessage.Ok());
                yield break;
            }
Example #7
0
        public void Bug_MT8962_PostPageContentsWithFile()
        {
            Plug adminPlug = Utils.BuildPlugForAdmin();

            // Create random contributor
            string       username = null;
            string       userid   = null;
            DreamMessage msg      = UserUtils.CreateRandomUser(adminPlug, "Contributor", "password", out userid, out username);

            // Login as user
            Plug userPlug = Utils.BuildPlugForUser(username);

            // Create a page
            string page_id;
            string page_path;

            msg = PageUtils.CreateRandomPage(userPlug, out page_id, out page_path);

            // Create a file
            string fileName = FileUtils.CreateRamdomFile(null);

            msg      = DreamMessage.FromFile(fileName);
            fileName = "foo.jpg";

            // Upload file to page
            msg = userPlug.At("pages", page_id, "files", "=" + fileName).Put(msg);
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "PUT request failed");

            // update the page
            XDoc pageContents = new XDoc("content");

            pageContents.Attr("type", "application/x.deki-text");
            pageContents.Attr("unsafe", "false");
            pageContents.Start("body");
            pageContents.Start("img");
            pageContents.Attr("class", "internal default");
            pageContents.Attr("src.path", "//");
            pageContents.Attr("src.filename", fileName);
            pageContents.End(); //img
            pageContents.End(); //body

            msg = userPlug.At("pages", page_id, "contents")
                  .With("edittime", "now")
                  .With("redirects", 0)
                  .With("reltopath", page_path)
                  .Post(pageContents);
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "page creation failed!");

            msg = userPlug.At("pages", page_id, "contents")
                  .With("mode", "view")
                  .Get();

            string contents  = msg.AsDocument()["/content/body"].Contents;
            XDoc   imgDoc    = XDocFactory.From(contents, MimeType.XML);
            XUri   imgSrcUri = XUri.TryParse(imgDoc["@src"].AsText);

            Assert.IsNotNull(imgSrcUri, "img src uri is invalid!");
        }
Example #8
0
        public void TestSendFolder_Fail()
        {
            string foldername = Path.GetTempPath();

            DreamMessage folderMsg = DreamMessage.FromFile(foldername, false);

            // add a file
            _storage.At(_fileUri).Put(folderMsg);

            // delete file (should never happen)
            _storage.At(_fileUri).Delete();
        }
Example #9
0
        private DreamMessage GetFile(string filename)
        {
            DreamMessage message;

            try {
                message = DreamMessage.FromFile(filename);
            } catch (FileNotFoundException e) {
                message = DreamMessage.NotFound("file not found");
            } catch (Exception e) {
                message = DreamMessage.BadRequest("invalid path");
            }
            return(message);
        }
Example #10
0
        public void Cannot_clone_a_filestream_message()
        {
            var file = Path.GetTempFileName();
            var text = "blah";

            File.WriteAllText(file, text);
            var m = DreamMessage.FromFile(file);

            m.Headers.Add("baz", "blah");
            try {
                var m2 = m.Clone();
                Assert.Fail("clone worked");
            } catch (InvalidOperationException) {
                return;
            }
        }
Example #11
0
        public void Can_mock_a_request_with_a_stream_body()
        {
            var tmp     = Path.GetTempFileName();
            var payload = "blahblah";

            File.WriteAllText(tmp, payload);
            var message = DreamMessage.FromFile(tmp);
            var uri     = new XUri("http://mock/post/stream");

            MockPlug.Setup(uri).Verb("POST")
            .WithMessage(m => m.ToText() == payload)
            .ExpectAtLeastOneCall();
            var response = Plug.New(uri).Post(message, new Result <DreamMessage>()).Wait();

            response.AssertSuccess();
            MockPlug.VerifyAll(1.Seconds());
        }
Example #12
0
        private DreamMessage GetDreamMessage(XUri uri)
        {
            // create a dream message from a file or from text entered by the user
            DreamMessage msg = null;

            if (useFileRadioButton.Checked)
            {
                msg = DreamMessage.FromFile(filepathTextBox.Text);
            }
            else
            {
                MimeType mimeType = MimeType.TEXT;
                MimeType.TryParse(mimeTypeComboBox.Text, out mimeType);
                msg = DreamMessage.Ok(mimeType, messageContentTextBox.Text);
            }
            msg.Cookies.AddRange(_cookies.Fetch(uri));
            return(msg);
        }
Example #13
0
        public static DreamMessage UploadFile(Plug p, string pageid, string description, out string fileid, string filename)
        {
            DreamMessage msg = DreamMessage.FromFile(filename);

            filename = XUri.DoubleEncode(System.IO.Path.GetFileName(filename));
            if (string.IsNullOrEmpty(description))
            {
                msg = p.At("pages", pageid, "files", "=" + filename).Put(msg);
            }
            else
            {
                msg = p.At("pages", pageid, "files", "=" + filename).With("description", description).Put(msg);
            }
            Assert.AreEqual(DreamStatus.Ok, msg.Status);
            fileid = msg.ToDocument()["@id"].AsText;
            Assert.IsFalse(string.IsNullOrEmpty(fileid));

            return(msg);
        }
Example #14
0
        public void TestSendFile()
        {
            string filename = Path.GetTempFileName();

            using (Stream s = File.OpenWrite(filename)) {
                byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS);
                s.Write(data, 0, data.Length);
            }

            // add a file
            _storage.At(_fileUri).Put(DreamMessage.FromFile(filename, false));
            File.Delete(filename);

            // get file and compare contents
            string contents = _storage.At(_fileUri).Get().ToText();

            Assert.AreEqual(TEST_CONTENTS, contents);

            // delete file
            _storage.At(_fileUri).Delete();
        }
Example #15
0
        public void FileUploadAndPropertyUpdate()
        {
            Plug p = Utils.BuildPlugForAdmin();

            string       id       = null;
            string       path     = null;
            DreamMessage msg      = PageUtils.CreateRandomPage(p, out id, out path);
            string       filepath = FileUtils.CreateRamdomFile(null);
            string       fileName = System.IO.Path.GetFileName(filepath);

            fileName = "properties";

            //Upload file via PUT: pages/{id}/files/{filename}
            msg = p.At("pages", id, "files", "=" + XUri.DoubleEncode(fileName)).PutAsync(DreamMessage.FromFile(filepath)).Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "Initial upload failed");

            string fileid = msg.ToDocument()["@id"].AsText;

            //Upload another rev of file via PUT:files/{fileid}/{filename}
            msg = p.At("files", fileid, "=" + XUri.DoubleEncode(fileName)).PutAsync(DreamMessage.FromFile(filepath)).Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "upload via PUT:files/{fileid}/{filename} failed");
            Assert.AreEqual("file", msg.ToDocument().Name, "File upload did not return a file xml");

            //Create a property 'foo' on the file
            msg = p.At("files", fileid, "properties").WithHeader("slug", "foo").PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, "foo content")).Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "Property foo set via POST:files/{id}/properties failed");
            Assert.AreEqual("property", msg.ToDocument().Name, "property upload did not return property xml");
            string propEtag = msg.ToDocument()["@etag"].AsText;

            //Update property 'foo' using the batch feature
            string newPropertyContent = "Some new content";
            XDoc   propDoc            = new XDoc("properties")
                                        .Start("property").Attr("name", "foo").Attr("etag", propEtag)
                                        .Start("contents").Attr("type", MimeType.TEXT_UTF8.ToString()).Value(newPropertyContent).End()
                                        .End();

            msg = p.At("files", fileid, "properties").PutAsync(propDoc).Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "batch property call failed");
            Assert.AreEqual("properties", msg.ToDocument().Name, "batch property upload did not return properties xml");
        }
Example #16
0
        public Yield GetFileOrFolderListing(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            bool   head = StringUtil.EqualsInvariant(context.Verb, "HEAD");
            string path = GetPath(context);

            DreamMessage result;

            if (File.Exists(path))
            {
                // dealing with a file request
                TouchMeta(path);

                // check if request contains a 'if-modified-since' header
                var lastmodified = File.GetLastWriteTime(path);
                if (request.CheckCacheRevalidation(lastmodified) && (lastmodified.Year >= 1900))
                {
                    response.Return(DreamMessage.NotModified());
                    yield break;
                }

                // retrieve file
                try {
                    result = DreamMessage.FromFile(path, head);
                } catch (FileNotFoundException) {
                    result = DreamMessage.NotFound("file not found");
                } catch (Exception) {
                    result = DreamMessage.BadRequest("invalid path");
                }

                // add caching headers if file was found
                if (!head && result.IsSuccessful)
                {
                    // add caching information; this will avoid unnecessary data transfers by user-agents with caches
                    result.SetCacheMustRevalidate(lastmodified);
                }
            }
            else if (Directory.Exists(path))
            {
                // dealing with a directory request
                if (head)
                {
                    // HEAD for a directory doesn't really mean anything, so we just return ok, to indicate that it exists
                    result = DreamMessage.Ok();
                }
                else
                {
                    var doc = new XDoc("files");

                    // list directory contents
                    var directories = Directory.GetDirectories(path);
                    foreach (var dir in directories)
                    {
                        if (dir.EndsWithInvariantIgnoreCase(META))
                        {
                            continue;
                        }
                        doc.Start("folder")
                        .Elem("name", Path.GetFileName(dir))
                        .End();
                    }
                    foreach (var filepath in Directory.GetFiles(path))
                    {
                        var file = new FileInfo(filepath);
                        doc.Start("file")
                        .Elem("name", file.Name)
                        .Elem("size", file.Length)
                        .Elem("date.created", file.CreationTimeUtc)
                        .Elem("date.modified", file.LastWriteTimeUtc);
                        var entry = SyncMeta(filepath);
                        if (entry != null)
                        {
                            doc.Elem("date.expire", entry.When);
                            doc.Elem("date.ttl", entry.TTL);
                        }
                        doc.End();
                    }
                    result = DreamMessage.Ok(doc);
                }
            }
            else
            {
                // nothin here
                result = DreamMessage.NotFound("no such file or folder");
            }

            response.Return(result);
            yield break;
        }