Пример #1
0
        public static void Main(string[] args)
        {
            ParserResult <Options> options = Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(o =>
            {
                Logger.LogInfo($"Using server config: {o.ConfigPath}");
                Logger.LogInfo($"Using http profile: {o.ProfilePath}");
                Logger.LogInfo($"Debug Logging: {o.Debug.ToString()}");

                if (o.Debug)
                {
                    Logger.Debug = true;
                }

                string configString       = File.ReadAllText(o.ConfigPath);
                State.ServerConfiguration = JsonConvert.DeserializeObject <ServerConfiguration>(configString);


                string profileString = File.ReadAllText(o.ProfilePath);
                JsonSerializerSettings jsonSettings = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                };

                TransportProfile profile = JsonConvert.DeserializeObject <TransportProfile>(profileString, jsonSettings);

                // Flesh out the agent profile so we can serialize it and register it with Faction
                profile.Agent.Hosts = State.ServerConfiguration.Hosts;
                profile.Agent.URLs  = profile.Server.URLs;
                profile.Agent.ServerMessageConfig = profile.Server.MessageConfig;

                State.Profile = profile;
            });

            CreateWebHostBuilder().Build().Run();
        }
Пример #2
0
        public static void Setup()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <HyperwayOutboundComponent>().AsSelf();
            builder.RegisterType <TransmissionRequestBuilder>().AsSelf();
            builder.RegisterType <NoSbdhParser>().As <IContentDetector>();

            // Lookup module registration
            builder.RegisterModule(new ModeModule());               // Configuration
            builder.RegisterModule(new CertificateModule());        // Keystore
            builder.RegisterModule(new LookupModule());
            builder.RegisterModule(new TransmissionModule());
            builder.RegisterModule(new As2OutboundModule());
            builder.RegisterModule(new TimestampModule());
            builder.RegisterModule(new PersisterModule());



            // Manual registration
            builder.RegisterType <SMimeMessageFactory>().AsSelf().InstancePerLifetimeScope();
            //

            builder.RegisterType <LookupClient>().AsSelf();
            builder.RegisterType <BusdoxLocator>().As <IMetadataLocator>();
            builder.RegisterType <MultiReader>().As <IMetadataReader>();
            builder.RegisterType <DifiCertificateValidator>().As <ICertificateValidator>();

            builder.RegisterType <IMetadataProvider>().AsSelf();


            builder.RegisterType <MessageSenderFactory>().AsSelf();
            builder.RegisterType <NoopStatisticsService>().As <IStatisticsService>();
            builder.RegisterType <DefaultTransmissionVerifier>().As <ITransmissionVerifier>();
            builder.RegisterType <TransmissionRequestBuilder>().AsSelf();

            builder.RegisterType <Mx.Peppol.Lookup.Provider.DefaultProvider>().As <IMetadataProvider>();

            builder.Register(
                (c) =>
            {
                var config = c.Resolve <Mode>();
                return(config.Defaults.Transports.Where(x => x.Enabled).OrderBy(x => x.Weight)
                       .Select(x => TransportProfile.Of(x.Profile)).ToList());
            }).Keyed <List <TransportProfile> >("prioritized")
            .As <List <TransportProfile> >();
            // prioritized

            builder.RegisterType <Bdxr201605Reader>()
            .Keyed <Bdxr201605Reader>("reader-protocols")
            .As <IMetadataReader>();
            builder.RegisterType <BusdoxReader>()
            .Keyed <BusdoxReader>("reader-protocols")
            .As <IMetadataReader>();


            Container = builder.Build();

            CryptographyContext.Register(() => Container.Resolve <HyperwaySecureMimeContext>());
        }
Пример #3
0
        public IPotentiallySigned <ServiceMetadata> ParseServiceMetadata(FetcherResponse fetcherResponse)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(fetcherResponse.InputStream);
                var o = ClassFactory.FromXmlStream(fetcherResponse.InputStream);

                X509Certificate signer = null;
                if (o is SignedServiceMetadata)
                {
                    signer = XmldsigVerifier.Verify(doc);
                }

                ServiceInformationType serviceInformation = ((tns.ServiceMetadata)o).ServiceInformation;

                List <ProcessMetadata <Endpoint> > processMetadatas = new List <ProcessMetadata <Endpoint> >();
                foreach (ProcessType processType in serviceInformation.ProcessList.Process)
                {
                    List <Endpoint> endpoints = new List <Endpoint>();
                    foreach (EndpointType endpointType in processType.ServiceEndpointList.Endpoint)
                    {
                        endpoints.Add(
                            Endpoint.Of(
                                TransportProfile.Of(endpointType.TransportProfile),
                                new Uri(endpointType.EndpointURI),
                                this.CertificateInstance(endpointType.Certificate.Data)));
                    }

                    processMetadatas.Add(
                        ProcessMetadata <Endpoint> .Of(
                            ProcessIdentifier.Of(
                                processType.ProcessIdentifier.PrimitiveValue,
                                Scheme.Of(processType.ProcessIdentifier.Scheme)),
                            endpoints));
                }

                return(Signed <ServiceMetadata> .Of(
                           ServiceMetadata.Of(

                               ParticipantIdentifier.Of(
                                   serviceInformation.ParticipantIdentifier.PrimitiveValue,
                                   Scheme.Of(serviceInformation.ParticipantIdentifier.Scheme)),

                               DocumentTypeIdentifier.Of(
                                   serviceInformation.DocumentIdentifier.PrimitiveValue,
                                   Scheme.Of(serviceInformation.DocumentIdentifier.Scheme)),

                               processMetadatas),
                           signer));
            }
            catch (Exception e) when(e is CertificateException | e is IOException)
            {
                throw new Exception(e.Message, e);
            }
        }
Пример #4
0
        /// <summary>
        /// Fetch identifier used in named annotation for the implementation of requested transport profile.
        /// </summary>
        public string GetSender(TransportProfile transportProfile)
        {
            if (!this.prioritizedTransportProfiles.Any(x => x.Equals(transportProfile)))
            {
                throw new HyperwayTransmissionException(
                          $"Transport protocol '{transportProfile.Identifier}' not supported.");
            }

            return(this.configMap.Where(x => x.Key.Equals(transportProfile)).Select(x => x.Value.Sender).First());
        }
Пример #5
0
        public static SMimeDigestMethod FindByTransportProfile(TransportProfile transportProfile)
        {
            foreach (SMimeDigestMethod digestMethod in Values())
            {
                if (digestMethod.transportProfile.Equals(transportProfile))
                {
                    return(digestMethod);
                }
            }

            throw new ArgumentException($"Digest method for transport profile '{transportProfile}' not known.");
        }
Пример #6
0
        public MessageSenderFactory(IComponentContext injector, Mode config)
        {
            this.injector = injector;

            this.configMap = config.Defaults.Transports.Where(x => x.Enabled).OrderBy(x => x.Weight)
                             .ToDictionary(t => TransportProfile.Of(t.Profile), x => x);

            this.prioritizedTransportProfiles = config.Defaults.Transports.Where(x => x.Enabled).OrderBy(x => x.Weight)
                                                .Select(x => TransportProfile.Of(x.Profile)).ToList();

            // Logging list of prioritized transport profiles supported.
            Logger.Info("Prioritized list of transport profiles:");
            this.prioritizedTransportProfiles.ForEach(tp => Logger.InfoFormat("=> {0}", tp.Identifier));
        }
Пример #7
0
 SMimeDigestMethod(
     string[] identifier,
     string method,
     string algorithm,
     Asn1Object oid,
     DigestMethod digestMethod,
     TransportProfile transportProfile)
 {
     this.identifier       = identifier;
     this.method           = method;
     this.algorithm        = algorithm;
     this.oid              = oid;
     this.digestMethod     = digestMethod;
     this.transportProfile = transportProfile;
 }
Пример #8
0
 private static void GenerateClientForProfile(
     ClassBuilder factory,
     DependencyInjectionDescriptor descriptor,
     TransportProfile profile)
 {
     factory
     .AddMethod("ConfigureClient" + profile.Name)
     .SetPrivate()
     .SetStatic()
     .SetReturnType(TypeNames.IServiceCollection)
     .AddParameter(_parentServices, x => x.SetType(TypeNames.IServiceProvider))
     .AddParameter(
         _strategy,
         x => x.SetType(TypeNames.ExecutionStrategy)
         .SetDefault(TypeNames.ExecutionStrategy + "." + "NetworkOnly"))
     .AddCode(GenerateInternalMethodBody(descriptor, profile));
 }
Пример #9
0
 public As2InboundMetadata(
     TransmissionIdentifier transmissionIdentifier,
     Header header,
     Timestamp timestamp,
     TransportProfile transportProfile,
     Digest digest,
     X509Certificate certificate,
     byte[] primaryReceipt)
 {
     this.transmissionIdentifier = transmissionIdentifier;
     this.header           = header;
     this.timestamp        = this.timestamp.Date;
     this.transportProfile = transportProfile;
     this.digest           = digest;
     this.receipt          = Receipt.Of("message/disposition-notification", primaryReceipt);
     this.receipts         = new List <Receipt>();
     this.receipts.Add(this.receipt);
     if (timestamp.GetReceipt() != null)
     {
         this.receipts.Add(timestamp.GetReceipt());
     }
     this.certificate = certificate;
 }
Пример #10
0
        public IPotentiallySigned <ServiceMetadata> ParseServiceMetadata(FetcherResponse fetcherResponse)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(fetcherResponse.InputStream);
                var o = ClassFactory.FromXmlElement(doc.DocumentElement);

                Xml.Busdox.tns.ServiceMetadata serviceMetadata = o as Xml.Busdox.tns.ServiceMetadata;
                X509Certificate signer = null;
                if (o is SignedServiceMetadata)
                {
                    signer          = XmldsigVerifier.Verify(doc);
                    serviceMetadata = ((SignedServiceMetadata)o).ServiceMetadata;
                }

                if (serviceMetadata == null)
                {
                    throw new LookupException("ServiceMetadata element not found");
                }


                ServiceInformationType serviceInformation = serviceMetadata.ServiceInformation;

                List <ProcessMetadata <Endpoint> > processMetadatas = new List <ProcessMetadata <Endpoint> >();
                foreach (ProcessType processType in serviceInformation.ProcessList.Process)
                {
                    List <Endpoint> endpoints = new List <Endpoint>();
                    foreach (EndpointType endpointType in processType.ServiceEndpointList.Endpoint)
                    {
                        var certificate = this.CertificateInstance(Convert.FromBase64String(endpointType.Certificate));
                        var endpointUri = new Uri(endpointType.EndpointReference.Address.PrimitiveValue);
                        var profile     = TransportProfile.Of(endpointType.TransportProfile);
                        endpoints.Add(Endpoint.Of(profile, endpointUri, certificate));
                    }

                    processMetadatas.Add(
                        ProcessMetadata <Endpoint> .Of(
                            ProcessIdentifier.Of(
                                processType.ProcessIdentifier.PrimitiveValue,
                                Scheme.Of(processType.ProcessIdentifier.Scheme)),
                            endpoints));
                }

                return(Signed <ServiceMetadata> .Of(
                           ServiceMetadata.Of(

                               ParticipantIdentifier.Of(
                                   serviceInformation.ParticipantIdentifier.PrimitiveValue,
                                   Scheme.Of(serviceInformation.ParticipantIdentifier.Scheme)),

                               DocumentTypeIdentifier.Of(
                                   serviceInformation.DocumentIdentifier.PrimitiveValue,
                                   Scheme.Of(serviceInformation.DocumentIdentifier.Scheme)),

                               processMetadatas),
                           signer));
            }
            catch (Exception e) when(e is CertificateException | e is IOException)
            {
                throw new Exception(e.Message, e);
            }
        }
Пример #11
0
        private static ICode GenerateInternalMethodBody(
            CSharpSyntaxGeneratorSettings settings,
            DependencyInjectionDescriptor descriptor,
            TransportProfile profile)
        {
            var rootNamespace = descriptor.ClientDescriptor.RuntimeType.Namespace;

            var hasSubscriptions =
                descriptor.Operations.OfType <SubscriptionOperationDescriptor>().Any();
            var hasQueries =
                descriptor.Operations.OfType <QueryOperationDescriptor>().Any();
            var hasMutations =
                descriptor.Operations.OfType <MutationOperationDescriptor>().Any();

            CodeBlockBuilder body = CodeBlockBuilder
                                    .New()
                                    .AddCode(CreateBaseCode(settings));

            var generatedConnections = new HashSet <TransportType>();

            if (hasSubscriptions)
            {
                generatedConnections.Add(profile.Subscription);
                body.AddCode(
                    RegisterConnection(profile.Subscription, descriptor.Name));
            }

            if (hasQueries && !generatedConnections.Contains(profile.Query))
            {
                generatedConnections.Add(profile.Query);
                body.AddCode(RegisterConnection(profile.Query, descriptor.Name));
            }

            if (hasMutations && !generatedConnections.Contains(profile.Mutation))
            {
                generatedConnections.Add(profile.Mutation);
                body.AddCode(RegisterConnection(profile.Mutation, descriptor.Name));
            }

            body.AddEmptyLine();

            foreach (var typeDescriptor in descriptor.TypeDescriptors
                     .OfType <INamedTypeDescriptor>())
            {
                if (typeDescriptor.Kind == TypeKind.Entity && !typeDescriptor.IsInterface())
                {
                    INamedTypeDescriptor namedTypeDescriptor =
                        (INamedTypeDescriptor)typeDescriptor.NamedType();
                    NameString className = namedTypeDescriptor.ExtractMapperName();

                    var interfaceName =
                        TypeNames.IEntityMapper.WithGeneric(
                            namedTypeDescriptor.ExtractType().ToString(),
                            $"{rootNamespace}.{typeDescriptor.RuntimeType.Name}");

                    body.AddMethodCall()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(interfaceName)
                    .AddGeneric($"{CreateStateNamespace(rootNamespace)}.{className}")
                    .AddArgument(_services);
                }
            }

            body.AddEmptyLine();

            foreach (var enumType in descriptor.EnumTypeDescriptor)
            {
                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric(CreateEnumParserName($"{rootNamespace}.{enumType.Name}"))
                .AddArgument(_services);
            }

            foreach (var serializer in _serializers)
            {
                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric(serializer)
                .AddArgument(_services);
            }

            RuntimeTypeInfo stringTypeInfo = new RuntimeTypeInfo(TypeNames.String);

            foreach (var scalar in descriptor.TypeDescriptors.OfType <ScalarTypeDescriptor>())
            {
                if (scalar.RuntimeType.Equals(stringTypeInfo) &&
                    scalar.SerializationType.Equals(stringTypeInfo) &&
                    !BuiltInScalarNames.IsBuiltInScalar(scalar.Name))
                {
                    body.AddMethodCall()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(TypeNames.ISerializer)
                    .AddArgument(_services)
                    .AddArgument(MethodCallBuilder
                                 .Inline()
                                 .SetNew()
                                 .SetMethodName(TypeNames.StringSerializer)
                                 .AddArgument(scalar.Name.AsStringToken()));
                }
            }

            foreach (var inputTypeDescriptor in descriptor.TypeDescriptors
                     .Where(x => x.Kind is TypeKind.Input))
            {
                var formatter =
                    CreateInputValueFormatter(
                        (InputObjectTypeDescriptor)inputTypeDescriptor.NamedType());

                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric($"{rootNamespace}.{formatter}")
                .AddArgument(_services);
            }

            body.AddCode(RegisterSerializerResolver());

            body.AddEmptyLine();

            foreach (var operation in descriptor.Operations)
            {
                if (!(operation.ResultTypeReference is InterfaceTypeDescriptor typeDescriptor))
                {
                    continue;
                }

                TransportType operationKind = operation switch
                {
                    SubscriptionOperationDescriptor => profile.Subscription,
                    QueryOperationDescriptor => profile.Query,
                    MutationOperationDescriptor => profile.Mutation,
                    _ => throw ThrowHelper.DependencyInjection_InvalidOperationKind(operation)
                };

                string connectionKind = operationKind switch
                {
                    TransportType.Http => TypeNames.IHttpConnection,
                    TransportType.WebSocket => TypeNames.IWebSocketConnection,
                    TransportType.InMemory => TypeNames.IInMemoryConnection,
                    { } v => throw ThrowHelper.DependencyInjection_InvalidTransportType(v)
                };

                string operationName          = operation.Name;
                string fullName               = operation.RuntimeType.ToString();
                string operationInterfaceName = operation.InterfaceType.ToString();
                string resultInterface        = typeDescriptor.RuntimeType.ToString();

                // The factories are generated based on the concrete result type, which is the
                // only implementee of the result type interface.

                var factoryName =
                    CreateResultFactoryName(
                        typeDescriptor.ImplementedBy.First().RuntimeType.Name);

                var builderName = CreateResultBuilderName(operationName);
                body.AddCode(
                    RegisterOperation(
                        settings,
                        connectionKind,
                        fullName,
                        operationInterfaceName,
                        resultInterface,
                        $"{CreateStateNamespace(operation.RuntimeType.Namespace)}.{factoryName}",
                        $"{CreateStateNamespace(operation.RuntimeType.Namespace)}.{builderName}"));
            }

            if (settings.IsStoreEnabled())
            {
                body.AddCode(
                    MethodCallBuilder
                    .New()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(TypeNames.IEntityIdSerializer)
                    .AddGeneric(descriptor.EntityIdFactoryDescriptor.Type.ToString())
                    .AddArgument(_services));
            }

            body.AddCode(
                MethodCallBuilder
                .New()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(descriptor.ClientDescriptor.RuntimeType.ToString())
                .AddArgument(_services));

            body.AddCode(
                MethodCallBuilder
                .New()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(descriptor.ClientDescriptor.InterfaceType.ToString())
                .AddArgument(_services)
                .AddArgument(LambdaBuilder
                             .New()
                             .AddArgument(_sp)
                             .SetCode(MethodCallBuilder
                                      .Inline()
                                      .SetMethodName(TypeNames.GetRequiredService)
                                      .AddGeneric(descriptor.ClientDescriptor.RuntimeType.ToString())
                                      .AddArgument(_sp))));

            body.AddLine($"return {_services};");

            return(body);
        }
Пример #12
0
        private static ICode GenerateClientServiceProviderFactory(
            DependencyInjectionDescriptor descriptor)
        {
            CodeBlockBuilder codeBuilder = CodeBlockBuilder.New();

            if (descriptor.TransportProfiles.Count == 1)
            {
                return(codeBuilder
                       .AddCode(
                           MethodCallBuilder
                           .New()
                           .SetMethodName("ConfigureClient" + descriptor.TransportProfiles[0].Name)
                           .AddArgument(_sp)
                           .AddArgument(_serviceCollection)
                           .AddArgument(_strategy))
                       .AddEmptyLine()
                       .AddCode(MethodCallBuilder
                                .New()
                                .SetReturn()
                                .SetNew()
                                .SetMethodName("ClientServiceProvider")
                                .SetWrapArguments()
                                .AddArgument(MethodCallBuilder
                                             .Inline()
                                             .SetMethodName(TypeNames.BuildServiceProvider)
                                             .AddArgument(_serviceCollection))));
            }

            IfBuilder ifProfile = IfBuilder.New();

            var enumName = CreateProfileEnumReference(descriptor);

            for (var index = 0; index < descriptor.TransportProfiles.Count; index++)
            {
                TransportProfile profile   = descriptor.TransportProfiles[index];
                IfBuilder        currentIf = ifProfile;
                if (index != 0)
                {
                    currentIf = IfBuilder.New();
                    ifProfile.AddIfElse(currentIf);
                }

                currentIf
                .SetCondition($"{_profile} == {enumName}.{profile.Name}")
                .AddCode(
                    MethodCallBuilder
                    .New()
                    .SetMethodName("ConfigureClient" + profile.Name)
                    .AddArgument(_sp)
                    .AddArgument(_serviceCollection)
                    .AddArgument(_strategy));
            }

            return(codeBuilder
                   .AddCode(ifProfile)
                   .AddEmptyLine()
                   .AddCode(MethodCallBuilder
                            .New()
                            .SetReturn()
                            .SetNew()
                            .SetMethodName("ClientServiceProvider")
                            .SetWrapArguments()
                            .AddArgument(MethodCallBuilder
                                         .Inline()
                                         .SetMethodName(TypeNames.BuildServiceProvider)
                                         .AddArgument(_serviceCollection))));
        }
Пример #13
0
 /// <summary>
 /// Fetch MessageSender implementing from provided transport profile.
 /// </summary>
 public IMessageSender GetMessageSender(TransportProfile transportProfile)
 {
     return(this.injector.ResolveKeyed <IMessageSender>(this.GetSender(transportProfile)));
 }
Пример #14
0
        private ITransmissionResponse Perform(ITransmissionMessage transmissionMessage, Trace root)
        {
            this.transmissionVerifier.Verify(transmissionMessage.GetHeader(), Direction.OUT);

            ITransmissionRequest transmissionRequest;

            if (transmissionMessage is ITransmissionRequest)
            {
                transmissionRequest = (ITransmissionRequest)transmissionMessage;
            }
            else
            {
                // Perform lookup using header.
                Trace lookupSpan = root.Child();
                lookupSpan.Record(Annotations.ServiceName("Fetch endpoint information"));
                lookupSpan.Record(Annotations.ClientSend());
                try
                {
                    var endpoint = this.lookupService.Lookup(transmissionMessage.GetHeader(), lookupSpan);
                    lookupSpan.Record(
                        Annotations.Tag("transport profile", endpoint.TransportProfile.Identifier));
                    transmissionRequest = new DefaultTransmissionRequest(transmissionMessage, endpoint);
                }
                catch (HyperwayTransmissionException e)
                {
                    lookupSpan.Record(Annotations.Tag("exception", e.Message));
                    throw;
                }
                finally
                {
                    lookupSpan.Record(Annotations.ClientRecv());
                }
            }

            Trace span = root.Child();

            span.Record(Annotations.ServiceName("send message"));
            span.Record(Annotations.ClientSend());

            // Span span = tracer.newChild(root.context()).name("send message").start();
            ITransmissionResponse transmissionResponse;

            try
            {
                TransportProfile transportProfile = transmissionRequest.GetEndpoint().TransportProfile;
                IMessageSender   messageSender    = this.messageSenderFactory.GetMessageSender(transportProfile);
                transmissionResponse = messageSender.Send(transmissionRequest, span);
            }
            catch (HyperwayTransmissionException e)
            {
                span.Record(Annotations.Tag("exception", e.Message));
                throw;
            }
            finally
            {
                span.Record(Annotations.ClientRecv());
            }

            this.statisticsService.Persist(transmissionRequest, transmissionResponse, root);

            return(transmissionResponse);
        }