/// <summary> /// Starts DNS transaction processing. /// </summary> public void Start() { // Send parallel query to DNS server(s). foreach (string server in Dns_Client.DnsServers) { try{ if (Net_Utils.IsIPAddress(server)) { IPAddress ip = IPAddress.Parse(server); if (ip.AddressFamily == AddressFamily.InterNetwork) { m_pOwner.m_pIPv4Socket.SendTo(m_pQuery, new IPEndPoint(ip, 53)); } else if (ip.AddressFamily == AddressFamily.InterNetworkV6) { m_pOwner.m_pIPv6Socket.SendTo(m_pQuery, new IPEndPoint(ip, 53)); } } } catch { } } m_pTimeoutTimer.Start(); }
/// <summary> /// Stores body decoded-data to the specified file. Note: This method is available for single part entities only. /// </summary> /// <param name="fileName">File name with path, where to store body data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>fileName</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="InvalidOperationException">Is raised when this method is called for multipart entity.</exception> public void DataToFile(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (fileName == string.Empty) { throw new ArgumentException("Argument 'fileName' value must be specified."); } if (this.Body == null) { throw new InvalidOperationException("Mime entity body has been not set yet."); } if (!(this.Body is MIME_b_SinglepartBase)) { throw new InvalidOperationException("This method is available only for single part entities, not for multipart."); } MIME_b_SinglepartBase body = (MIME_b_SinglepartBase)this.Body; using (Stream fs = File.Create(fileName)){ using (Stream dataStream = body.GetDataStream()){ Net_Utils.StreamCopy(dataStream, fs, 64000); } } }
/// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> public override void Write(byte[] buffer, int offset, int count) { if (m_IsDisposed) { throw new ObjectDisposedException("SmartStream"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } // We need switch to temporary file. if (m_pStream is MemoryStream && (m_pStream.Position + count) > m_MaxMemSize) { FileStream fs = new FileStream(Path.GetTempPath() + "ls-" + Guid.NewGuid().ToString().Replace("-", "") + ".tmp", FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 32000, FileOptions.DeleteOnClose); m_pStream.Position = 0; Net_Utils.StreamCopy(m_pStream, fs, 8000); // m_pStream.Close(); m_pStream = null; m_pStream.Dispose(); m_pStream = fs; } m_pStream.Write(buffer, offset, count); }
/// <summary> /// Does STUN transaction. Returns transaction response or null if transaction failed. /// </summary> /// <param name="request">STUN message.</param> /// <param name="socket">Socket to use for send/receive.</param> /// <param name="remoteEndPoint">Remote end point.</param> /// <param name="timeout">Timeout in milli seconds.</param> /// <returns>Returns transaction response or null if transaction failed.</returns> private static STUN_Message DoTransaction(STUN_Message request, Socket socket, IPEndPoint remoteEndPoint, int timeout) { byte[] requestBytes = request.ToByteData(); DateTime startTime = DateTime.Now; // Retransmit with 500 ms. while (startTime.AddMilliseconds(timeout) > DateTime.Now) { try{ socket.SendTo(requestBytes, remoteEndPoint); // We got response. if (socket.Poll(500 * 1000, SelectMode.SelectRead)) { byte[] receiveBuffer = new byte[512]; socket.Receive(receiveBuffer); // Parse message STUN_Message response = new STUN_Message(); response.Parse(receiveBuffer); // Check that transaction ID matches or not response what we want. if (Net_Utils.CompareArray(request.TransactionID, response.TransactionID)) { return(response); } } } catch { } } return(null); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_Text retVal = null; if (owner.ContentType != null) { retVal = new MIME_b_Text(owner.ContentType.TypeWithSubtype); } else { retVal = new MIME_b_Text(defaultContentType.TypeWithSubtype); } Net_Utils.StreamCopy(stream, retVal.EncodedStream, stream.LineBufferSize); retVal.SetModified(false); return(retVal); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_Application retVal = null; if (owner.ContentType != null) { retVal = new MIME_b_Application(owner.ContentType.TypeWithSubtype); } else { retVal = new MIME_b_Application(defaultContentType.TypeWithSubtype); } Net_Utils.StreamCopy(stream, retVal.EncodedStream, 32000); return(retVal); }
/// <summary> /// Sets body encoded data from specified stream. /// </summary> /// <param name="contentTransferEncoding">Content-Transfer-Encoding in what encoding <b>stream</b> data is.</param> /// <param name="stream">Stream data to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentTransferEncoding</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="InvalidOperationException">Is raised when this method is accessed and this body is not bounded to any entity.</exception> public void SetEncodedData(string contentTransferEncoding, Stream stream) { if (contentTransferEncoding == null) { throw new ArgumentNullException("contentTransferEncoding"); } if (contentTransferEncoding == string.Empty) { throw new ArgumentException("Argument 'contentTransferEncoding' value must be specified."); } if (stream == null) { throw new ArgumentNullException("stream"); } if (this.Entity == null) { throw new InvalidOperationException("Body must be bounded to some entity first."); } // Owner entity has no content-type or has different content-type, just add/overwrite it. if (this.Entity.ContentType == null || !string.Equals(this.Entity.ContentType.TypeWithSubtype, this.MediaType, StringComparison.InvariantCultureIgnoreCase)) { this.Entity.ContentType = new MIME_h_ContentType(this.MediaType); } this.Entity.ContentTransferEncoding = contentTransferEncoding; m_pEncodedDataStream.SetLength(0); Net_Utils.StreamCopy(stream, m_pEncodedDataStream, 84000); m_IsModified = true; }
/// <summary> /// Gets if this proxy server is responsible for specified route. /// </summary> /// <param name="uri">Route value to check.</param> /// <returns>Returns trues if server route, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> internal bool IsLocalRoute(SIP_Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } // Not a route. if (uri.User != null) { return(false); } // Consider any IP address as local route, because if server behind NAT we can't do IP check. if (Net_Utils.IsIPAddress(uri.Host)) { return(true); } else { foreach (IPBindInfo bind in m_pStack.BindInfo) { if (uri.Host.ToLower() == bind.HostName.ToLower()) { return(true); } } } return(false); }
/// <summary> /// Sets body encoded data from specified stream. /// </summary> /// <param name="contentTransferEncoding">Content-Transfer-Encoding in what encoding <b>stream</b> data is.</param> /// <param name="stream">Stream data to add.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentTransferEncoding</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the argumennts has invalid value.</exception> public void SetEncodedData(string contentTransferEncoding, Stream stream) { if (contentTransferEncoding == null) { throw new ArgumentNullException("contentTransferEncoding"); } if (contentTransferEncoding == string.Empty) { throw new ArgumentException("Argument 'contentTransferEncoding' value must be specified."); } if (stream == null) { throw new ArgumentNullException("stream"); } m_pEncodedDataStream.SetLength(0); Net_Utils.StreamCopy(stream, m_pEncodedDataStream, 32000); // If body won't end with CRLF, add CRLF. if (m_pEncodedDataStream.Length >= 2) { m_pEncodedDataStream.Position = m_pEncodedDataStream.Length - 2; } if (m_pEncodedDataStream.ReadByte() != '\r' && m_pEncodedDataStream.ReadByte() != '\n') { m_pEncodedDataStream.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2); } this.Entity.ContentTransferEncoding = contentTransferEncoding; m_IsModified = true; }
/// <summary> /// Multicast constructor. /// </summary> /// <param name="ip">Multicast IP address.</param> /// <param name="dataPort">RTP data port.</param> /// <param name="controlPort">RTP control port. Usualy this is <b>dataPort</b> + 1.</param> /// <param name="ttl">RTP control port. Usualy this is <b>dataPort</b> + 1.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid values.</exception> public RTP_Address(IPAddress ip, int dataPort, int controlPort, int ttl) { if (ip == null) { throw new ArgumentNullException("ip"); } if (!Net_Utils.IsMulticastAddress(ip)) { throw new ArgumentException("Argument 'ip' is not multicast ip address."); } if (dataPort < IPEndPoint.MinPort || dataPort > IPEndPoint.MaxPort) { throw new ArgumentException("Argument 'dataPort' value must be between '" + IPEndPoint.MinPort + "' and '" + IPEndPoint.MaxPort + "'."); } if (controlPort < IPEndPoint.MinPort || controlPort > IPEndPoint.MaxPort) { throw new ArgumentException("Argument 'controlPort' value must be between '" + IPEndPoint.MinPort + "' and '" + IPEndPoint.MaxPort + "'."); } if (dataPort == controlPort) { throw new ArgumentException("Arguments 'dataPort' and 'controlPort' values must be different."); } if (ttl < 0 || ttl > 255) { throw new ArgumentException("Argument 'ttl' value must be between '0' and '255'."); } m_pIP = ip; m_DataPort = dataPort; m_ControlPort = controlPort; m_TTL = ttl; m_pRtpEP = new IPEndPoint(ip, dataPort); m_pRtcpEP = new IPEndPoint(ip, controlPort); }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } string mediaType = null; try { mediaType = owner.ContentType.TypeWithSubtype; } catch { mediaType = "unparsable/unparsable"; } MIME_b_Unknown retVal = new MIME_b_Unknown(mediaType); Net_Utils.StreamCopy(stream, retVal.EncodedStream, 32000); return(retVal); }
/// <summary> /// Resolves local IP to public IP using STUN. /// </summary> /// <param name="stunServer">STUN server.</param> /// <param name="port">STUN server port. Default port is 3478.</param> /// <param name="localIP">Local IP address.</param> /// <returns>Returns public IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stunServer</b> or <b>localIP</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="IOException">Is raised when no connection to STUN server.</exception> public static IPAddress GetPublicIP(string stunServer, int port, IPAddress localIP) { if (stunServer == null) { throw new ArgumentNullException("stunServer"); } if (stunServer == "") { throw new ArgumentException("Argument 'stunServer' value must be specified."); } if (port < 1) { throw new ArgumentException("Invalid argument 'port' value."); } if (localIP == null) { throw new ArgumentNullException("localIP"); } if (!Net_Utils.IsPrivateIP(localIP)) { return(localIP); } STUN_Result result = Query(stunServer, port, Net_Utils.CreateSocket(new IPEndPoint(localIP, 0), ProtocolType.Udp)); if (result.PublicEndPoint != null) { return(result.PublicEndPoint.Address); } else { throw new IOException("Failed to STUN public IP address. STUN server name is invalid or firewall blocks STUN."); } }
/// <summary> /// Gets attachment stream. /// </summary> /// <returns>Returns attachment stream.</returns> internal Stream GetStream() { if (m_pStream == null) { m_pStream = File.OpenRead(m_FileName); } if (m_ZipCompress) { #if NET20 || NET35 || NET40 throw new InvalidOperationException("Not supported lower framework version than 4.5."); #else MemoryStreamEx retVal = new MemoryStreamEx(); using (ZipArchive archive = new ZipArchive(retVal, ZipArchiveMode.Create)){ ZipArchiveEntry entry = archive.CreateEntry(m_Name, CompressionLevel.Optimal); using (Stream zipStream = entry.Open()){ Net_Utils.StreamCopy(m_pStream, zipStream, 64000); } } retVal.Position = 0; CloseStream(); return(retVal); #endif } return(m_pStream); }
/// <summary> /// Gets attachment stream. /// </summary> /// <returns>Returns attachment stream.</returns> internal Stream GetStream() { if (m_pStream == null) { m_pStream = File.OpenRead(m_FileName); } if (m_ZipCompress) { MemoryStreamEx retVal = new MemoryStreamEx(); using (ZipArchive archive = new ZipArchive(retVal, ZipArchiveMode.Create)){ ZipArchiveEntry entry = archive.CreateEntry(m_Name, CompressionLevel.Optimal); using (Stream zipStream = entry.Open()){ Net_Utils.StreamCopy(m_pStream, zipStream, 64000); } } retVal.Position = 0; CloseStream(); return(retVal); } return(m_pStream); }
/// <summary> /// Starts receiving data. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this calss is disposed and this method is accessed.</exception> public void Start() { if(m_IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(m_IsRunning){ return; } m_IsRunning = true; // Move processing to thread pool. ThreadPool.QueueUserWorkItem(delegate(object state){ try{ m_pEventArgs = new UDP_e_PacketReceived(); m_pBuffer = new byte[m_BufferSize]; if(Net_Utils.IsIoCompletionPortsSupported()){ m_pSocketArgs = new SocketAsyncEventArgs(); m_pSocketArgs.SetBuffer(m_pBuffer,0,m_BufferSize); m_pSocketArgs.RemoteEndPoint = new IPEndPoint(m_pSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any,0); m_pSocketArgs.Completed += delegate(object s1,SocketAsyncEventArgs e1){ if(m_IsDisposed){ return; } try{ if(m_pSocketArgs.SocketError == SocketError.Success){ OnPacketReceived(m_pBuffer,m_pSocketArgs.BytesTransferred,(IPEndPoint)m_pSocketArgs.RemoteEndPoint); } else{ OnError(new Exception("Socket error '" + m_pSocketArgs.SocketError + "'.")); } IOCompletionReceive(); } catch(Exception x){ OnError(x); } }; IOCompletionReceive(); } else{ EndPoint rtpRemoteEP = new IPEndPoint(m_pSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any,0); m_pSocket.BeginReceiveFrom( m_pBuffer, 0, m_BufferSize, SocketFlags.None, ref rtpRemoteEP, new AsyncCallback(this.AsyncSocketReceive), null ); } } catch(Exception x){ OnError(x); } }); }
protected virtual Task OnStart() { var capabilities = String.Join(" ", Capabilities); var hostName = Net_Utils.GetLocalHostName(Server.HostName); return(Stream.WriteLineAsync($"* OK <{hostName}> Kooboo Imap server ready.")); }
/// <summary> /// Starts accpeting connections. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this calss is disposed and this method is accessed.</exception> public void Start() { if (m_IsDisposed) { throw new ObjectDisposedException(this.GetType().Name); } if (m_IsRunning) { return; } m_IsRunning = true; // Move processing to thread pool. ThreadPool.QueueUserWorkItem(delegate(object state) { try { if (Net_Utils.IsSocketAsyncSupported()) { m_pSocketArgs = new SocketAsyncEventArgs(); m_pSocketArgs.Completed += delegate(object s1, SocketAsyncEventArgs e1) { if (m_IsDisposed) { return; } try { if (m_pSocketArgs.SocketError == SocketError.Success) { OnConnectionAccepted(m_pSocketArgs.AcceptSocket); } else { OnError(new Exception("Socket error '" + m_pSocketArgs.SocketError + "'.")); } IOCompletionAccept(); } catch (Exception x) { OnError(x); } }; IOCompletionAccept(); } else { m_pSocket.BeginAccept(new AsyncCallback(this.AsyncSocketAccept), null); } } catch (Exception x) { OnError(x); } }); }
/// <summary> /// Returns DIGEST-MD5 "digest-challenge" string. /// </summary> /// <returns>Returns DIGEST-MD5 "digest-challenge" string.</returns> public string ToChallenge() { /* RFC 2831 2.1.1. * The server starts by sending a challenge. The data encoded in the * challenge contains a string formatted according to the rules for a * "digest-challenge" defined as follows: * * digest-challenge = * 1#( realm | nonce | qop-options | stale | maxbuf | charset * algorithm | cipher-opts | auth-param ) * * realm = "realm" "=" <"> realm-value <"> * realm-value = qdstr-val * nonce = "nonce" "=" <"> nonce-value <"> * nonce-value = qdstr-val * qop-options = "qop" "=" <"> qop-list <"> * qop-list = 1#qop-value * qop-value = "auth" | "auth-int" | "auth-conf" | token * stale = "stale" "=" "true" * maxbuf = "maxbuf" "=" maxbuf-value * maxbuf-value = 1*DIGIT * charset = "charset" "=" "utf-8" * algorithm = "algorithm" "=" "md5-sess" * cipher-opts = "cipher" "=" <"> 1#cipher-value <"> * cipher-value = "3des" | "des" | "rc4-40" | "rc4" | "rc4-56" | token * auth-param = token "=" ( token | quoted-string ) */ StringBuilder retVal = new StringBuilder(); retVal.Append("realm=\"" + Net_Utils.ArrayToString(this.Realm, ",") + "\""); retVal.Append(",nonce=\"" + this.Nonce + "\""); if (this.QopOptions != null) { retVal.Append(",qop=\"" + Net_Utils.ArrayToString(this.QopOptions, ",") + "\""); } if (this.Stale) { retVal.Append(",stale=true"); } if (this.Maxbuf > 0) { retVal.Append(",maxbuf=" + this.Maxbuf); } if (!string.IsNullOrEmpty(this.Charset)) { retVal.Append(",charset=" + this.Charset); } retVal.Append(",algorithm=" + this.Algorithm); if (!string.IsNullOrEmpty(this.CipherOpts)) { retVal.Append(",cipher-opts=\"" + this.CipherOpts + "\""); } //if(!string.IsNullOrEmpty(this.AuthParam)){ // retVal.Append("auth-param=\"" + this.AuthParam + "\""); //} return(retVal.ToString()); }
/// <summary> /// This method is called when REGISTER has finished. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pRegisterSender_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { m_pFlow = e.ClientTransaction.Flow; if (e.Response.StatusCodeType == SIP_StatusCodeType.Success) { SetState(SIP_UA_RegistrationState.Registered); OnRegistered(); m_pFlow.SendKeepAlives = true; } else { SetState(SIP_UA_RegistrationState.Error); OnError(e); } // REMOVE ME: if (this.AutoFixContact && (m_pContact is SIP_Uri)) { // If Via: received or rport paramter won't match to our sent-by, use received and rport to construct new contact value. SIP_Uri cContact = ((SIP_Uri)m_pContact); IPAddress cContactIP = Net_Utils.IsIPAddress(cContact.Host) ? IPAddress.Parse(cContact.Host) : null; SIP_t_ViaParm via = e.Response.Via.GetTopMostValue(); if (via != null && cContactIP != null) { IPEndPoint ep = new IPEndPoint(via.Received != null ? via.Received : cContactIP, via.RPort > 0 ? via.RPort : cContact.Port); if (!cContactIP.Equals(ep.Address) || cContact.Port != via.RPort) { // Unregister old contact. BeginUnregister(false); // Fix contact. cContact.Host = ep.Address.ToString(); cContact.Port = ep.Port; m_pRegisterSender.Dispose(); m_pRegisterSender = null; BeginRegister(m_AutoRefresh); return; } } } if (m_AutoRefresh) { // Set registration refresh timer. m_pTimer.Enabled = true; } m_pRegisterSender.Dispose(); m_pRegisterSender = null; }
/// <summary> /// Sets item decoded value. Value will be encoded as needed and stored to item.Value property. /// </summary> /// <param name="value"></param> public void SetDecodedValue(string value) { /* RFC 2426 vCrad 5. Differences From vCard v2.1 * The QUOTED-PRINTABLE inline encoding has been eliminated. * Only the "B" encoding of [RFC 2047] is an allowed value for * the ENCODING parameter. * * The CRLF character sequence in a text type value is specified * with the backslash character sequence "\n" or "\N". * * Any COMMA or SEMICOLON in a text type value must be backslash escaped. */ // Remove encoding and charset parameters string newParmString = ""; string[] parameters = m_Parameters.ToLower().Split(';'); foreach (string parameter in parameters) { string[] name_value = parameter.Split('='); if (name_value[0] == "encoding" || name_value[0] == "charset") { } else if (parameter.Length > 0) { newParmString += parameter + ";"; } } if (m_pCard.Version.StartsWith("3")) { // Add encoding parameter if (!Net_Utils.IsAscii(value)) { newParmString += "CHARSET=utf-8"; } this.ParametersString = newParmString; this.Value = vCard_Utils.Encode(m_pCard.Version, m_pCard.Charset, value); } else { if (NeedEncode(value)) { // Add encoding parameter newParmString += "ENCODING=QUOTED-PRINTABLE;CHARSET=" + m_pCard.Charset.WebName; this.ParametersString = newParmString; this.Value = vCard_Utils.Encode(m_pCard.Version, m_pCard.Charset, value); } else { this.ParametersString = newParmString; this.Value = value; } } }
/// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> internal protected override void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset) { if (stream == null) { throw new ArgumentNullException("stream"); } Net_Utils.StreamCopy(GetEncodedDataStream(), stream, 32000); }
/// <summary> /// Starts DNS transaction processing. /// </summary> /// <exception cref="InvalidOperationException">Is raised when this method is called in invalid transaction state.</exception> public void Start() { if (this.State != DNS_ClientTransactionState.WaitingForStart) { throw new InvalidOperationException("DNS_ClientTransaction.Start may be called only in 'WaitingForStart' transaction state."); } SetState(DNS_ClientTransactionState.Active); // Move processing to thread pool. ThreadPool.QueueUserWorkItem(delegate(object state){ try{ // Use DNS cache if allowed. if (Dns_Client.UseDnsCache) { DnsServerResponse response = m_pOwner.Cache.GetFromCache(m_QName, (int)m_QType); if (response != null) { m_pResponse = response; SetState(DNS_ClientTransactionState.Completed); Dispose(); return; } } byte[] buffer = new byte[1400]; int count = CreateQuery(buffer, m_ID, m_QName, m_QType, 1); // Send parallel query to DNS server(s). foreach (string server in Dns_Client.DnsServers) { if (Net_Utils.IsIPAddress(server)) { IPAddress ip = IPAddress.Parse(server); m_pOwner.Send(ip, buffer, count); } } m_pTimeoutTimer.Start(); } catch { // Check if we have bad unicode qname. try{ System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping(); ldn.GetAscii(m_QName); } catch { m_pResponse = new DnsServerResponse(true, m_ID, DNS_RCode.NAME_ERROR, new List <DNS_rr>(), new List <DNS_rr>(), new List <DNS_rr>()); } SetState(DNS_ClientTransactionState.Completed); } }); }
/* * /// <summary> * /// Parses SMTP mailbox from the specified string. * /// </summary> * /// <param name="value">Mailbox string.</param> * /// <returns>Returns parsed SMTP mailbox.</returns> * /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> * public static SMTP_t_Mailbox Parse(string value) * { * if(value == null){ * throw new ArgumentNullException("value"); * } * * return Parse(new ABNF_Reader(value)); * } * * /// <summary> * /// Parses SMTP mailbox from the specified reader. * /// </summary> * /// <param name="reader">Source reader.</param> * /// <returns>Returns parsed SMTP mailbox.</returns> * /// <exception cref="ArgumentNullException">Is raised when <b>reader</b> is null reference.</exception> * public static SMTP_t_Mailbox Parse(ABNF_Reader reader) * { * if(reader == null){ * throw new ArgumentNullException("reader"); * } * * // TODO: * * return null; * } */ #endregion #region override method ToString /// <summary> /// Returns mailbox as string. /// </summary> /// <returns>Returns mailbox as string.</returns> public override string ToString() { if (MIME_Reader.IsDotAtom(m_LocalPart)) { return(m_LocalPart + "@" + (Net_Utils.IsIPAddress(m_Domain) ? "[" + m_Domain + "]" : m_Domain)); } else { return(TextUtils.QuoteString(m_LocalPart) + "@" + (Net_Utils.IsIPAddress(m_Domain) ? "[" + m_Domain + "]" : m_Domain)); } }
/// <summary> /// Stores body decoded-data to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> public void DataToStream(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } using (Stream dataStream = GetDataStream()){ Net_Utils.StreamCopy(dataStream, stream, 64000); } }
/// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> protected internal override void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset) { if (stream == null) { throw new ArgumentNullException("stream"); } Net_Utils.StreamCopy(GetEncodedDataStream(), stream, Workaround.Definitions.MaxStreamLineLength); }
/// <summary> /// Sets body data from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="transferEncoding">Specifies content-transfer-encoding to use to encode data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>transferEncoding</b> is null reference.</exception> public void SetData(Stream stream, string transferEncoding) { if (stream == null) { throw new ArgumentNullException("stream"); } if (transferEncoding == null) { throw new ArgumentNullException("transferEncoding"); } if (transferEncoding == MIME_TransferEncodings.QuotedPrintable) { using (MemoryStream mem_stream = new MemoryStream()) { QuotedPrintableStream encoder = new QuotedPrintableStream(new SmartStream(mem_stream, false), FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, Workaround.Definitions.MaxStreamLineLength); encoder.Flush(); mem_stream.Position = 0; SetEncodedData(transferEncoding, mem_stream); } } else if (transferEncoding == MIME_TransferEncodings.Base64) { using (MemoryStream mem_stream = new MemoryStream()) { Base64Stream encoder = new Base64Stream(mem_stream, false, true, FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, Workaround.Definitions.MaxStreamLineLength); encoder.Finish(); mem_stream.Position = 0; SetEncodedData(transferEncoding, mem_stream); } } else if (transferEncoding == MIME_TransferEncodings.Binary) { SetEncodedData(transferEncoding, stream); } else if (transferEncoding == MIME_TransferEncodings.EightBit) { SetEncodedData(transferEncoding, stream); } else if (transferEncoding == MIME_TransferEncodings.SevenBit) { SetEncodedData(transferEncoding, stream); } else { throw new NotSupportedException("Not supported Content-Transfer-Encoding '" + transferEncoding + "'."); } }
/// <summary> /// Sets item decoded value. Value will be encoded as needed and stored to item.Value property. /// Also property item.ParametersString is updated to reflect right encoding(always base64, required by rfc) and charset (utf-8). /// </summary> /// <param name="value"></param> public void SetDecodedValue(string value) { /* RFC 2426 vCrad 5. Differences From vCard v2.1 * The QUOTED-PRINTABLE inline encoding has been eliminated. * Only the "B" encoding of [RFC 2047] is an allowed value for * the ENCODING parameter. * * The CRLF character sequence in a text type value is specified * with the backslash character sequence "\n" or "\N". * * Any COMMA or SEMICOLON in a text type value must be backslash escaped. */ // FIX ME: this must be done with structured fields //value = value.Replace("\r\n","\n").Replace("\n","\\n"); //value = TextUtils.EscapeString(value,new char[]{',',';'}); bool needEncode = false; if (!Net_Utils.IsAscii(value)) { needEncode = true; } if (needEncode) { // Remove encoding and charset parameters string newParmString = ""; string[] parameters = m_Parameters.ToLower().Split(';'); foreach (string parameter in parameters) { string[] name_value = parameter.Split('='); if (name_value[0] == "encoding" || name_value[0] == "charset") { } else if (parameter.Length > 0) { newParmString += parameter + ";"; } } // Add encoding parameter newParmString += "ENCODING=b;CHARSET=utf-8"; this.ParametersString = newParmString; this.Value = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)); } else { this.Value = value; } }
/// <summary> /// Sets body data from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="transferEncoding">Specifies content-transfer-encoding to use to encode data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>transferEncoding</b> is null reference.</exception> /// <exception cref="InvalidOperationException">Is raised when this method is accessed and this body is not bounded to any entity.</exception> public void SetData(Stream stream, string transferEncoding) { if (stream == null) { throw new ArgumentNullException("stream"); } if (transferEncoding == null) { throw new ArgumentNullException("transferEncoding"); } if (String2.Equals(transferEncoding, MIME_TransferEncodings.QuotedPrintable, StringComparison2.InvariantCultureIgnoreCase)) { using (MemoryStreamEx fs = new MemoryStreamEx()) { QuotedPrintableStream encoder = new QuotedPrintableStream(new SmartStream(fs, false), FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, 84000); encoder.Flush(); fs.Position = 0; SetEncodedData(transferEncoding, fs); } } else if (String2.Equals(transferEncoding, MIME_TransferEncodings.Base64, StringComparison2.InvariantCultureIgnoreCase)) { using (MemoryStreamEx fs = new MemoryStreamEx()) { Base64Stream encoder = new Base64Stream(fs, false, true, FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, 84000); encoder.Finish(); fs.Position = 0; SetEncodedData(transferEncoding, fs); } } else if (String2.Equals(transferEncoding, MIME_TransferEncodings.Binary, StringComparison2.InvariantCultureIgnoreCase)) { SetEncodedData(transferEncoding, stream); } else if (String2.Equals(transferEncoding, MIME_TransferEncodings.EightBit, StringComparison2.InvariantCultureIgnoreCase)) { SetEncodedData(transferEncoding, stream); } else if (String2.Equals(transferEncoding, MIME_TransferEncodings.SevenBit, StringComparison2.InvariantCultureIgnoreCase)) { SetEncodedData(transferEncoding, stream); } else { throw new NotSupportedException("Not supported Content-Transfer-Encoding '" + transferEncoding + "'."); } }
/// <summary> /// Sets body data from the specified stream. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="transferEncoding">Specifies content-transfer-encoding to use to encode data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>transferEncoding</b> is null reference.</exception> public void SetData(Stream stream, string transferEncoding) { if (stream == null) { throw new ArgumentNullException("stream"); } if (transferEncoding == null) { throw new ArgumentNullException("transferEncoding"); } if (transferEncoding == MIME_TransferEncodings.QuotedPrintable) { using (FileStream fs = File.Create(Path.GetTempFileName())){ QuotedPrintableStream encoder = new QuotedPrintableStream(new SmartStream(fs, false), FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, 32000); encoder.Flush(); fs.Position = 0; SetEncodedData(transferEncoding, fs); } } else if (transferEncoding == MIME_TransferEncodings.Base64) { using (FileStream fs = File.Create(Path.GetTempFileName())){ Base64Stream encoder = new Base64Stream(fs, false, true, FileAccess.ReadWrite); Net_Utils.StreamCopy(stream, encoder, 32000); encoder.Finish(); fs.Position = 0; SetEncodedData(transferEncoding, fs); } } else if (transferEncoding == MIME_TransferEncodings.Binary) { SetEncodedData(transferEncoding, stream); } else if (transferEncoding == MIME_TransferEncodings.EightBit) { SetEncodedData(transferEncoding, stream); } else if (transferEncoding == MIME_TransferEncodings.SevenBit) { SetEncodedData(transferEncoding, stream); } else { throw new NotSupportedException("Not supported Content-Transfer-Encoding '" + transferEncoding + "'."); } }
/// <summary> /// Stores body decoded-data to the specified file. /// </summary> /// <param name="fileName">File name with path, where to store body data.</param> /// <exception cref="ArgumentNullException">Is raised when <b>fileName</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void DataToFile(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (fileName == string.Empty) { throw new ArgumentException("Argument 'fileName' value must be specified."); } using (Stream fs = File.Create(fileName)){ using (Stream dataStream = GetDataStream()){ Net_Utils.StreamCopy(dataStream, fs, 64000); } } }