Beispiel #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="destination"></param>
 /// <param name="data">max size 10000</param>
 public async Task SendDatagram(
     string destination,
     byte[] data
     )
 {
     try
     {
         if (string.IsNullOrWhiteSpace(destination))
         {
             throw new ArgumentNullException(
                       MyNameof.GetLocalVarName(() => destination));
         }
         if (data == null)
         {
             throw new ArgumentNullException(
                       MyNameof.GetLocalVarName(() => data));
         }
         if (data.Length <= 0 || data.Length > 10000)
         {
             throw new ArgumentOutOfRangeException(
                       MyNameof.GetLocalVarName(() => data)
                       + "." + MyNameof.GetLocalVarName(() => data.Length),
                       "data length should be 0 < length <= 10000");
         }
         if (_samStream == null)
         {
             throw new InvalidOperationException(
                       this.MyNameOfProperty(e => e._samStream)
                       );
         }
         if (!_samStream.CanWrite)
         {
             throw new InvalidOperationException(
                       "_samStream can't write"
                       );
         }
         var writeBuffer = SamBridgeCommandBuilder.DatagramSend(
             destination,
             data
             );
         await WriteBuffer(writeBuffer).ConfigureAwait(false);
     }
     catch (EnumException <SendDatagramExcs> )
     {
         throw;
     }
     catch (Exception exc)
     {
         throw new EnumException <SendDatagramExcs>(
                   SendDatagramExcs.UnknownError,
                   innerException: exc
                   );
     }
 }
Beispiel #2
0
        private async Task <SamSession> CreateSession(
            string id,
            CancellationToken cancellationToken,
            string destinationPrivateKey = null,
            string i2CpOptions           = null
            )
        {
            try
            {
                if (id == null)
                {
                    throw new ArgumentNullException("id");
                }
                if (!_samStream.CanWrite)
                {
                    throw new EnumException <SamHelperExcs>(
                              SamHelperExcs.NetStreamCannotWrite,
                              tag: _samStream
                              );
                }
                var sessionCreateTask
                    = _samReader.SessionStatusReceived
                      .FirstAsync().ToTask(cancellationToken);
                var writeBuffer = SamBridgeCommandBuilder.SessionCreate(
                    SamBridgeCommandBuilder.SessionStyle.Datagram,
                    id,
                    destinationPrivateKey,
                    i2CpOptions
                    );
                await WriteBuffer(writeBuffer).ConfigureAwait(false);

                SessionStatusReceivedArgs sessionStatusReply = null;
                try
                {
                    sessionStatusReply = await sessionCreateTask.ConfigureAwait(false);

                    if (sessionStatusReply == null)
                    {
                        throw new ArgumentNullException(
                                  MyNameof.GetLocalVarName(() => sessionStatusReply));
                    }
                }
                catch (OperationCanceledException)
                {
                    throw new EnumException <ECreateSessionErrorCodes>(
                              ECreateSessionErrorCodes.CreateSessionTimeout
                              );
                }
                if (
                    sessionStatusReply.SessionStatusResult
                    == SamBridgeMessages.SESSION_STATUS_OK
                    )
                {
                    _log.Trace(
                        string.Format(
                            "Session created {0}",
                            sessionStatusReply.DestinationWithPrivateKey
                            .Substring(0, 20)
                            )
                        );
                    return(new SamSession
                    {
                        PrivateKey
                            = sessionStatusReply.DestinationWithPrivateKey,
                        SessionId = id,
                        SessionStyle = SamBridgeCommandBuilder.SessionStyle.Datagram
                    });
                }
                if (
                    sessionStatusReply.SessionStatusResult
                    == SamBridgeMessages.SESSION_STATUS_DUPLICATE_ID
                    )
                {
                    throw new EnumException <ECreateSessionErrorCodes>(
                              ECreateSessionErrorCodes.DuplicatedId,
                              tag: sessionStatusReply
                              );
                }
                if (
                    sessionStatusReply.SessionStatusResult
                    == SamBridgeMessages.SESSION_STATUS_DUPLICATE_DEST
                    )
                {
                    throw new EnumException <ECreateSessionErrorCodes>(
                              ECreateSessionErrorCodes.DuplicatedDest,
                              tag: sessionStatusReply
                              );
                }
                if (
                    sessionStatusReply.SessionStatusResult
                    == SamBridgeMessages.SESSION_STATUS_INVALID_KEY
                    )
                {
                    throw new EnumException <ECreateSessionErrorCodes>(
                              ECreateSessionErrorCodes.InvalidKey,
                              tag: sessionStatusReply
                              );
                }
                if (
                    sessionStatusReply.SessionStatusResult
                    == SamBridgeMessages.SESSION_STATUS_I2P_ERROR
                    )
                {
                    throw new EnumException <ECreateSessionErrorCodes>(
                              ECreateSessionErrorCodes.I2PError,
                              message: sessionStatusReply.Message,
                              tag: sessionStatusReply
                              );
                }
                else
                {
                    _log.Error(
                        "CreateSession unknown error '{0}'",
                        sessionStatusReply.WriteObjectToJson()
                        );
                    throw new EnumException <ECreateSessionErrorCodes>(
                              ECreateSessionErrorCodes.UnknownError,
                              tag: sessionStatusReply
                              );
                }
            }
            catch (EnumException <ECreateSessionErrorCodes> )
            {
                throw;
            }
            catch (Exception exc)
            {
                throw new EnumException <ECreateSessionErrorCodes>(
                          ECreateSessionErrorCodes.UnknownError,
                          innerException: exc
                          );
            }
        }
Beispiel #3
0
        //ECreateInstanceErrCodes
        public static async Task <SamHelper> CreateInstance(
            SamHelperSettings settings,
            CancellationToken cancellationToken
            )
        {
            if (settings == null)
            {
                throw new ArgumentNullException(
                          MyNameof.GetLocalVarName(() => settings));
            }
            if (cancellationToken == null)
            {
                throw new ArgumentNullException(
                          MyNameof.GetLocalVarName(() => cancellationToken));
            }
            settings.CheckMe();
            var result = new SamHelper();

            result._samTcpClient = new TcpClient();
            try
            {
                await result._samTcpClient.ConnectAsync(
                    settings.SamServerAddress,
                    settings.SamServerPort
                    ).ThrowIfCancelled(cancellationToken).ConfigureAwait(false);
            }
            catch (TimeoutException timeExc)
            {
                throw new EnumException <ECreateInstanceErrCodes>(
                          ECreateInstanceErrCodes.ConnectTcpTimeout,
                          innerException: timeExc
                          );
            }
            catch (Exception exc)
            {
                throw new EnumException <ECreateInstanceErrCodes>(
                          ECreateInstanceErrCodes.ConnectTcp,
                          innerException: exc
                          );
            }
            try
            {
                result._samStream = result._samTcpClient.GetStream();
                try
                {
                    if (!result._samStream.CanWrite)
                    {
                        throw new EnumException <SamHelperExcs>(
                                  SamHelperExcs.NetStreamCannotWrite
                                  );
                    }
                    if (!result._samStream.CanRead)
                    {
                        throw new EnumException <SamHelperExcs>(
                                  SamHelperExcs.NetStreamCannotRead
                                  );
                    }

                    result._samReader = new SamReader(result._samStream);
                    result._subscriptions.Add(
                        result._samReader.IoExceptionThrown.ObserveOn(TaskPoolScheduler.Default).Subscribe(
                            i => result.IoExceptionThrown.OnNext(null)
                            )
                        );
                    result._subscriptions.Add(
                        result._samReader.DatagramDataReceived.ObserveOn(TaskPoolScheduler.Default).Subscribe(
                            result.SamReaderOnDatagramDataReceived
                            )
                        );
                    /*******************/
                    HelloReplyReceivedArgs helloAnswer;
                    try
                    {
                        var writeBuffer     = SamBridgeCommandBuilder.HelloReply();
                        var helloAnswerTask =
                            result._samReader.HelloReplyReceived
                            .FirstAsync()
                            .ToTask(cancellationToken);
                        await result.WriteBuffer(writeBuffer).ConfigureAwait(false);

                        helloAnswer = await helloAnswerTask.ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        //timeout
                        result._samTcpClient.Close();
                        throw new EnumException <ECreateInstanceErrCodes>(
                                  ECreateInstanceErrCodes.HelloReplyTimeoutExceed
                                  );
                    }
                    if (!helloAnswer.Ok)
                    {
                        result._samTcpClient.Close();
                        throw new EnumException <ECreateInstanceErrCodes>(
                                  ECreateInstanceErrCodes.HelloReplyError,
                                  tag: helloAnswer
                                  );
                    }
                    result._stateHelper.SetInitializedState();
                    try
                    {
                        var sessionName = settings.SessionId ??
                                          Guid.NewGuid().ToString().Replace("-", "").Substring(0, 15);
                        result._samSession = await result.CreateSession(
                            sessionName,
                            cancellationToken,
                            settings.SessionPrivateKeys,
                            settings.I2CpOptions
                            ).ConfigureAwait(false);
                    }
                    catch (EnumException <ECreateSessionErrorCodes> createSessionExc)
                    {
                        throw new EnumException <ECreateInstanceErrCodes>(
                                  ECreateInstanceErrCodes.CreateSessionError,
                                  innerException: createSessionExc
                                  );
                    }
                    return(result);
                }
                catch
                {
                    result._samStream.Close();
                    throw;
                }
            }
            catch
            {
                result._samTcpClient.Close();
                throw;
            }
        }