예제 #1
0
        public HomeModule()
        {
            Get["/"] = x => View["Index", RequestContextListModel.Instance];

            Get["/details/{guid}"] = x =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                return(Response.AsText(JsonConvert.SerializeObject(context), "text/json"));
            };

            Get["/download/cert"] = x =>
            {
                var cert = CertificateHelper.GetCertificateFromStore();
                var pem  = CertificateHelper.ConvertToPem(cert);

                return(Response.AsText(pem).AsAttachment($"{AppConfig.RootCertificateName}.cer", "application/x-x509-ca-cert"));
            };

            Get["/download/request/raw/{guid}"] = x =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                if (context?.RequestData.RequestBody != null)
                {
                    return(Response.FromStream(new MemoryStream(context.RequestData.RequestBody), "application/binary").AsAttachment(guid + "-request.bin"));
                }
                return(new NotFoundResponse());
            };

            Get["/download/request/decoded/{guid}", true] = async(x, ct) =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                if (context == null)
                {
                    return(new NotFoundResponse());
                }
                if (context.RequestData.RawDecodedRequestBody == null)
                {
                    context.RequestData.RawDecodedRequestBody = await Protoc.DecodeRaw(context.RequestData.RequestBody);
                }
                return(Response.AsText(context.RequestData.RawDecodedRequestBody).AsAttachment(guid + "-request.txt", "text/plain"));
            };


            Get["/download/response/raw/{guid}"] = x =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                if (context?.ResponseData.ResponseBody != null)
                {
                    return(Response.FromStream(new MemoryStream(context.ResponseData.ResponseBody), "application/binary").AsAttachment(guid + "-response.bin"));
                }
                return(new NotFoundResponse());
            };

            Get["/download/rawsignature/{guid}"] = x =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                if (context?.RequestData.RequestBody != null)
                {
                    return(Response.FromStream(new MemoryStream(context.RequestData.RawEncryptedSignature), "application/binary").AsAttachment(guid + "-rawsignature.bin"));
                }
                return(new NotFoundResponse());
            };


            Get["/download/decryptedrawsignature/{guid}"] = x =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                if (context?.RequestData.RequestBody != null)
                {
                    return(Response.FromStream(new MemoryStream(context.RequestData.RawDecryptedSignature), "application/binary").AsAttachment(guid + "-decryptedsignature.bin"));
                }
                return(new NotFoundResponse());
            };

            Get["/download/response/decoded/{guid}", true] = async(x, ct) =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                if (context == null)
                {
                    return(new NotFoundResponse());
                }
                if (context.ResponseData.RawDecodedResponseBody == null)
                {
                    context.ResponseData.RawDecodedResponseBody = await Protoc.DecodeRaw(context.ResponseData.ResponseBody);
                }

                return(Response.AsText(context.ResponseData.RawDecodedResponseBody).AsAttachment(guid + "-response.txt", "text/plain"));
            };

            Get["/download/json/{guid}"] = x =>
            {
                var guid    = (string)x.guid;
                var context = GetRequestContext(guid);
                if (context != null)
                {
                    return(Response.AsText(JsonConvert.SerializeObject(context, Formatting.Indented)).AsAttachment(guid + ".json", "application/json"));
                }
                return(new NotFoundResponse());
            };

            Get["/session/{session}"] = x =>
            {
                var fileName = (string)x.session;
                if (fileName == "live")
                {
                    var liveContext =
                        ContextCache.RawContexts.Values.Where(r => r.IsLive)
                        .OrderBy(c => c.RequestTime).Select(RequestContextListModel.FromRawContext);
                    return(Response.AsText(JsonConvert.SerializeObject(liveContext), "text/json"));
                }
                var sessionDump = RawDumpReader.GetSession(fileName);
                if (sessionDump != null)
                {
                    foreach (var rawContext in sessionDump.Where(r => r != null))
                    {
                        ContextCache.RawContexts.TryAdd(rawContext.Guid, rawContext);
                    }
                    var list = sessionDump.Where(r => r != null).Select(RequestContextListModel.FromRawContext).ToList();
                    return(Response.AsText(JsonConvert.SerializeObject(list), "text/json"));
                }
                return(new NotFoundResponse());
            };

            Post["/details/signature/{guid}"] = x =>
            {
                try
                {
                    var guid    = (string)x.guid;
                    var context = GetRequestContext(guid);

                    var post    = this.Bind <DecryptedSignature>();
                    var trimmed = post.Bytes.Substring(1);
                    trimmed = trimmed.Substring(0, trimmed.Length - 1);
                    var res = trimmed.Split(',');
                    var arr = new byte[res.Length];
                    arr = res.Select(byte.Parse).ToArray();
                    context.RequestData.RawDecryptedSignature = arr;

                    var signature = Signature.Parser.ParseFrom(arr);
                    context.RequestData.DecryptedSignature = signature;
                    return(Response.AsText(JsonConvert.SerializeObject(new { success = true, signature = signature }), "text/json"));
                }
                catch (Exception ex)
                {
                    return(Response.AsText(JsonConvert.SerializeObject(new { success = false, exception = ex }), "text/json"));
                }
            };
        }
예제 #2
0
        public object Any(Protoc request)
        {
            var tmpId = (Request as IHasStringId)?.Id?.Replace("|", "").Replace(".", "") ?? Guid.NewGuid().ToString();
            var files = request.Files ?? new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(request.ProtoUrl))
            {
                var fileName = request.ProtoUrl.EndsWith(".proto")
                    ? request.ProtoUrl.LastRightPart('/')
                    : "services.proto";
                files[fileName] = request.ProtoUrl.GetStringFromUrl();
            }

            if (Request.Files.Length > 0)
            {
                foreach (var httpFile in Request.Files)
                {
                    var fileName = httpFile.FileName ?? httpFile.Name;
                    if (!fileName.EndsWith(".proto") && !fileName.EndsWith(".zip"))
                    {
                        throw new ArgumentException($"Unsupported file '{fileName}'. Only .proto or .zip files supported.");
                    }

                    if (fileName.EndsWith(".zip"))
                    {
                        var tmpZipPath = Path.GetTempFileName();
                        var tmpDir     = Path.Combine(Path.GetTempPath(), "protoc-api", tmpId);
                        httpFile.SaveTo(tmpZipPath);

                        ZipFile.ExtractToDirectory(tmpZipPath, tmpDir);

                        var tmpDirInfo      = new DirectoryInfo(tmpDir);
                        var hasProtoRootDir = tmpDirInfo.GetFiles("*.proto").Length > 0;
                        var fsZipDir        = !hasProtoRootDir && tmpDirInfo.GetDirectories().Length == 1
                            ? new FileSystemVirtualFiles(tmpDirInfo.GetDirectories()[0].FullName)
                            : new FileSystemVirtualFiles(tmpDirInfo.FullName);

                        foreach (var file in fsZipDir.GetAllFiles().Where(x => x.Extension == "proto"))
                        {
                            files[file.VirtualPath] = file.ReadAllText();
                        }
                    }
                    else
                    {
                        files[fileName] = httpFile.InputStream.ReadToEnd();
                    }
                }
            }

            if (files.IsEmpty())
            {
                throw new ArgumentNullException(nameof(request.Files));
            }

            var tmpPath = Path.Combine(ProtocConfig.TempDirectory, tmpId);
            var outPath = Path.Combine(tmpPath, "out");

            try { Directory.CreateDirectory(outPath); } catch {}

            var fs = new FileSystemVirtualFiles(tmpPath);

            fs.WriteFiles(files);

            var langOptions = ProtocConfig.Languages[request.Lang];
            var args        = StringBuilderCache.Allocate();

            var outArgs = "";

            if (!langOptions.OutModifiers.IsEmpty())
            {
                foreach (var modifier in langOptions.OutModifiers)
                {
                    if (outArgs.Length > 0)
                    {
                        outArgs += ",";
                    }
                    outArgs += modifier;
                }
                if (outArgs.Length > 0)
                {
                    outArgs += ":";
                }
            }

            var grpcOut = "";

            if (langOptions.GrpcOutModifiers != null)
            {
                grpcOut = " --grpc_out=";
                for (var i = 0; i < langOptions.GrpcOutModifiers.Length; i++)
                {
                    if (i > 0)
                    {
                        grpcOut += ",";
                    }

                    var modifier = langOptions.GrpcOutModifiers[i];
                    grpcOut += modifier;
                }

                if (langOptions.GrpcOutModifiers.Length > 0)
                {
                    grpcOut += ":";
                }
                grpcOut += "out";
            }

            args.AppendFormat($"-I . -I \"{ProtocConfig.ProtoIncludeDirectory}\" --{langOptions.Lang}_out={outArgs}out{grpcOut}");

            if (!langOptions.GrpcWebModifiers.IsEmpty())
            {
                var webArgs = "";
                foreach (var modifier in langOptions.GrpcWebModifiers)
                {
                    if (webArgs.Length > 0)
                    {
                        webArgs += ",";
                    }
                    webArgs += modifier;
                }
                if (webArgs.Length > 0)
                {
                    webArgs += ":";
                }
                args.AppendFormat($" --grpc-web_out={webArgs}out");
            }

            if (!langOptions.Args.IsEmpty())
            {
                foreach (var arg in langOptions.Args)
                {
                    args.Append($" {arg}");
                }
            }

            if (!langOptions.IndividuallyPerFile)
            {
                foreach (var entry in files)
                {
                    args.Append($" {entry.Key}");
                }

                exec(tmpPath, StringBuilderCache.ReturnAndFree(args));
            }
            else
            {
                var argsBase = StringBuilderCache.ReturnAndFree(args);
                foreach (var entry in files)
                {
                    exec(tmpPath, $"{argsBase} {entry.Key}");
                }
            }

            var serviceName = files.Count == 1 ? files.Keys.First() : "grpc";
            var archiveUrl  = Request.ResolveAbsoluteUrl(new GetArchive {
                RequestId = tmpId, FileName = $"{serviceName}.{langOptions.Lang}.zip"
            }.ToGetUrl());

            if (Request.QueryString["zip"] != null)
            {
                return(new HttpResult(new ProtocResponse {
                    ArchiveUrl = archiveUrl
                })
                {
                    Location = archiveUrl
                });
            }

            var response = new ProtocResponse {
                GeneratedFiles = new Dictionary <string, string>(),
                ArchiveUrl     = archiveUrl,
            };

            var fsOut    = new FileSystemVirtualFiles(Path.Combine(tmpPath, "out"));
            var genFiles = fsOut.GetAllFiles();

            foreach (var virtualFile in genFiles)
            {
                response.Lang = request.Lang;
                response.GeneratedFiles[virtualFile.VirtualPath] = virtualFile.GetTextContentsAsMemory().ToString();
            }

            return(response);
        }