diff options
Diffstat (limited to 'cs/src')
92 files changed, 26709 insertions, 26709 deletions
diff --git a/cs/src/Glacier2/AssemblyInfo.cs b/cs/src/Glacier2/AssemblyInfo.cs index 5a809b6b21e..89bb510277e 100755 --- a/cs/src/Glacier2/AssemblyInfo.cs +++ b/cs/src/Glacier2/AssemblyInfo.cs @@ -20,6 +20,6 @@ using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Glacier2 for C#")] [assembly: AssemblyCopyright("Copyright (c) 2003-2007, ZeroC, Inc.")] [assembly: AssemblyTrademark("Ice")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.51")] [assembly: AssemblyDelaySign(false)] diff --git a/cs/src/Ice/Acceptor.cs b/cs/src/Ice/Acceptor.cs index c8334f62189..20148ebd419 100755 --- a/cs/src/Ice/Acceptor.cs +++ b/cs/src/Ice/Acceptor.cs @@ -14,12 +14,12 @@ namespace IceInternal public interface Acceptor { - Socket fd(); - void close(); - void listen(); - Transceiver accept(int timeout); - void connectToSelf(); - string ToString(); + Socket fd(); + void close(); + void listen(); + Transceiver accept(int timeout); + void connectToSelf(); + string ToString(); } } diff --git a/cs/src/Ice/Application.cs b/cs/src/Ice/Application.cs index 59b4520f42d..869b2c3e9db 100755 --- a/cs/src/Ice/Application.cs +++ b/cs/src/Ice/Application.cs @@ -17,514 +17,514 @@ namespace Ice public abstract class Application { - public abstract int run(string[] args); - - // - // Override this method to provide a custom application interrupt - // hook. You must call callbackOnInterrupt for this method - // to be called. Note that the interruptCallback can be called - // concurrently with any other thread (including main) in your - // application--take appropriate concurrency precautions. - // - public virtual void interruptCallback(int sig) - { - } - - public Application() - { + public abstract int run(string[] args); + + // + // Override this method to provide a custom application interrupt + // hook. You must call callbackOnInterrupt for this method + // to be called. Note that the interruptCallback can be called + // concurrently with any other thread (including main) in your + // application--take appropriate concurrency precautions. + // + public virtual void interruptCallback(int sig) + { + } + + public Application() + { #if !__MonoCS__ - bool rc = SetConsoleCtrlHandler(_handler, true); - Debug.Assert(rc); + bool rc = SetConsoleCtrlHandler(_handler, true); + Debug.Assert(rc); #endif - } - - // - // This main() must be called by the global Main(). main() - // initializes the Communicator, calls run(), and destroys - // the Communicator upon return from run(). It thereby handles - // all exceptions properly, i.e., error messages are printed - // if exceptions propagate to main(), and the Communicator is - // always destroyed, regardless of exceptions. - // - public int main(string[] args) - { - return main(args, new InitializationData()); - } - - public int main(string[] args, string configFile) - { - InitializationData initData = new InitializationData(); - if(configFile != null) - { - try - { - initData.properties = Util.createProperties(); - initData.properties.load(configFile); - } - catch(Ice.Exception ex) - { - Console.Error.WriteLine(_appName + ": " + ex); - return 1; - } - catch(System.Exception ex) - { - Console.Error.WriteLine(_appName + ": unknown exception: " + ex); - return 1; - } - } - return main(args, initData); - } - - [Obsolete("This method has been deprecated.")] - public int main(string[] args, string configFile, Logger logger) - { - InitializationData initData = new InitializationData(); - if(configFile != null) - { - try - { - initData.properties = Util.createProperties(); - initData.properties.load(configFile); - } - catch(Ice.Exception ex) - { - Console.Error.WriteLine(_appName + ": " + ex); - return 1; - } - catch(System.Exception ex) - { - Console.Error.WriteLine(_appName + ": unknown exception: " + ex); - return 1; - } - } - initData.logger = logger; - return main(args, initData); - } - - public int main(string[] args, InitializationData initData) - { - if(_communicator != null) - { - Console.Error.WriteLine(_appName + ": only one instance of the Application class can be used"); - return 1; - } - int status = 0; - - try - { - _communicator = Util.initialize(ref args, initData); - _application = this; - - Properties props = _communicator.getProperties(); - _nohup = props.getPropertyAsInt("Ice.Nohup") != 0; - _appName = props.getPropertyWithDefault("Ice.ProgramName", _appName); - - // - // The default is to destroy when a signal is received. - // - destroyOnInterrupt(); - - status = run(args); - } - catch(Ice.Exception ex) - { - Console.Error.WriteLine(_appName + ": " + ex); - status = 1; - } - catch(System.Exception ex) - { - Console.Error.WriteLine(_appName + ": unknown exception: " + ex); - status = 1; - } - - // - // Don't want any new interrupt. And at this point - // (post-run), it would not make sense to release a held - // signal to run shutdown or destroy. - // - ignoreInterrupt(); - - Monitor.Enter(sync); - while(_callbackInProgress) - { - Monitor.Wait(sync); - } - if(_destroyed) - { - _communicator = null; - } - else - { - _destroyed = true; - // - // _communicator != 0 means that it will be destroyed - // next; _destroyed == true ensures that any - // remaining callback won't do anything - // - } - _application = null; - Monitor.Exit(sync); - - if(_communicator != null) - { - try - { - _communicator.destroy(); - } - catch(Ice.Exception ex) - { - Console.Error.WriteLine(_appName + ": " + ex); - status = 1; - } - catch(System.Exception ex) - { - Console.Error.WriteLine(_appName + ": unknown exception: " + ex); - status = 1; - } - _communicator = null; - } - return status; - } - - // - // Return the application name. - // - public static string appName() - { - return _appName; - } - - // - // One limitation of this class is that there can only be one - // Application instance, with one global Communicator, accessible - // with this communicator() operation. This limitiation is due to - // how the signal handling functions below operate. If you require - // multiple Communicators, then you cannot use this Application - // framework class. - // - public static Communicator communicator() - { - return _communicator; - } - - public static void destroyOnInterrupt() - { - Monitor.Enter(sync); - if(_callback == _holdCallback) - { - _callback = _destroyCallback; - _released = true; - Monitor.Pulse(sync); - } - else - { - _callback = _destroyCallback; - } - Monitor.Exit(sync); - } - - public static void shutdownOnInterrupt() - { - Monitor.Enter(sync); - if(_callback == _holdCallback) - { - _callback = _shutdownCallback; - _released = true; - Monitor.Pulse(sync); - } - else - { - _callback = _shutdownCallback; - } - Monitor.Exit(sync); - } - - public static void ignoreInterrupt() - { - Monitor.Enter(sync); - if(_callback == _holdCallback) - { - _callback = null; - _released = true; - Monitor.Pulse(sync); - } - else - { - _callback = null; - } - Monitor.Exit(sync); - } - - public static void callbackOnInterrupt() - { - Monitor.Enter(sync); - if(_callback == _holdCallback) - { - _released = true; - _callback = _userCallback; - Monitor.Pulse(sync); - } - else - { - _callback = _userCallback; - } - Monitor.Exit(sync); - } - - public static void holdInterrupt() - { - Monitor.Enter(sync); - if(_callback != _holdCallback) - { - _previousCallback = _callback; - _callback = _holdCallback; - _released = false; - } - // else, we were already holding signals - Monitor.Exit(sync); - } - - public static void releaseInterrupt() - { - Monitor.Enter(sync); - if(_callback == _holdCallback) - { - _callback = _previousCallback; - _released = true; - Monitor.Pulse(sync); - } - // Else nothing to release. - Monitor.Exit(sync); - } - - public static bool interrupted() - { - Monitor.Enter(sync); - bool rc = _interrupted; - Monitor.Exit(sync); - return rc; - } + } + + // + // This main() must be called by the global Main(). main() + // initializes the Communicator, calls run(), and destroys + // the Communicator upon return from run(). It thereby handles + // all exceptions properly, i.e., error messages are printed + // if exceptions propagate to main(), and the Communicator is + // always destroyed, regardless of exceptions. + // + public int main(string[] args) + { + return main(args, new InitializationData()); + } + + public int main(string[] args, string configFile) + { + InitializationData initData = new InitializationData(); + if(configFile != null) + { + try + { + initData.properties = Util.createProperties(); + initData.properties.load(configFile); + } + catch(Ice.Exception ex) + { + Console.Error.WriteLine(_appName + ": " + ex); + return 1; + } + catch(System.Exception ex) + { + Console.Error.WriteLine(_appName + ": unknown exception: " + ex); + return 1; + } + } + return main(args, initData); + } + + [Obsolete("This method has been deprecated.")] + public int main(string[] args, string configFile, Logger logger) + { + InitializationData initData = new InitializationData(); + if(configFile != null) + { + try + { + initData.properties = Util.createProperties(); + initData.properties.load(configFile); + } + catch(Ice.Exception ex) + { + Console.Error.WriteLine(_appName + ": " + ex); + return 1; + } + catch(System.Exception ex) + { + Console.Error.WriteLine(_appName + ": unknown exception: " + ex); + return 1; + } + } + initData.logger = logger; + return main(args, initData); + } + + public int main(string[] args, InitializationData initData) + { + if(_communicator != null) + { + Console.Error.WriteLine(_appName + ": only one instance of the Application class can be used"); + return 1; + } + int status = 0; + + try + { + _communicator = Util.initialize(ref args, initData); + _application = this; + + Properties props = _communicator.getProperties(); + _nohup = props.getPropertyAsInt("Ice.Nohup") != 0; + _appName = props.getPropertyWithDefault("Ice.ProgramName", _appName); + + // + // The default is to destroy when a signal is received. + // + destroyOnInterrupt(); + + status = run(args); + } + catch(Ice.Exception ex) + { + Console.Error.WriteLine(_appName + ": " + ex); + status = 1; + } + catch(System.Exception ex) + { + Console.Error.WriteLine(_appName + ": unknown exception: " + ex); + status = 1; + } + + // + // Don't want any new interrupt. And at this point + // (post-run), it would not make sense to release a held + // signal to run shutdown or destroy. + // + ignoreInterrupt(); + + Monitor.Enter(sync); + while(_callbackInProgress) + { + Monitor.Wait(sync); + } + if(_destroyed) + { + _communicator = null; + } + else + { + _destroyed = true; + // + // _communicator != 0 means that it will be destroyed + // next; _destroyed == true ensures that any + // remaining callback won't do anything + // + } + _application = null; + Monitor.Exit(sync); + + if(_communicator != null) + { + try + { + _communicator.destroy(); + } + catch(Ice.Exception ex) + { + Console.Error.WriteLine(_appName + ": " + ex); + status = 1; + } + catch(System.Exception ex) + { + Console.Error.WriteLine(_appName + ": unknown exception: " + ex); + status = 1; + } + _communicator = null; + } + return status; + } + + // + // Return the application name. + // + public static string appName() + { + return _appName; + } + + // + // One limitation of this class is that there can only be one + // Application instance, with one global Communicator, accessible + // with this communicator() operation. This limitiation is due to + // how the signal handling functions below operate. If you require + // multiple Communicators, then you cannot use this Application + // framework class. + // + public static Communicator communicator() + { + return _communicator; + } + + public static void destroyOnInterrupt() + { + Monitor.Enter(sync); + if(_callback == _holdCallback) + { + _callback = _destroyCallback; + _released = true; + Monitor.Pulse(sync); + } + else + { + _callback = _destroyCallback; + } + Monitor.Exit(sync); + } + + public static void shutdownOnInterrupt() + { + Monitor.Enter(sync); + if(_callback == _holdCallback) + { + _callback = _shutdownCallback; + _released = true; + Monitor.Pulse(sync); + } + else + { + _callback = _shutdownCallback; + } + Monitor.Exit(sync); + } + + public static void ignoreInterrupt() + { + Monitor.Enter(sync); + if(_callback == _holdCallback) + { + _callback = null; + _released = true; + Monitor.Pulse(sync); + } + else + { + _callback = null; + } + Monitor.Exit(sync); + } + + public static void callbackOnInterrupt() + { + Monitor.Enter(sync); + if(_callback == _holdCallback) + { + _released = true; + _callback = _userCallback; + Monitor.Pulse(sync); + } + else + { + _callback = _userCallback; + } + Monitor.Exit(sync); + } + + public static void holdInterrupt() + { + Monitor.Enter(sync); + if(_callback != _holdCallback) + { + _previousCallback = _callback; + _callback = _holdCallback; + _released = false; + } + // else, we were already holding signals + Monitor.Exit(sync); + } + + public static void releaseInterrupt() + { + Monitor.Enter(sync); + if(_callback == _holdCallback) + { + _callback = _previousCallback; + _released = true; + Monitor.Pulse(sync); + } + // Else nothing to release. + Monitor.Exit(sync); + } + + public static bool interrupted() + { + Monitor.Enter(sync); + bool rc = _interrupted; + Monitor.Exit(sync); + return rc; + } #if !__MonoCS__ - // - // First-level handler - // - private static Boolean HandlerRoutine(int sig) - { - Monitor.Enter(sync); - Callback callback = _callback; - Monitor.Exit(sync); - if(callback != null) - { - try - { - callback(sig); - } - catch(System.Exception) - { - Debug.Assert(false); - } - } - return true; - } + // + // First-level handler + // + private static Boolean HandlerRoutine(int sig) + { + Monitor.Enter(sync); + Callback callback = _callback; + Monitor.Exit(sync); + if(callback != null) + { + try + { + callback(sig); + } + catch(System.Exception) + { + Debug.Assert(false); + } + } + return true; + } #endif - // - // The callbacks to be invoked from the handler. - // - private static void holdInterruptCallback(int sig) - { - bool destroyed; - Callback callback; - Monitor.Enter(sync); - while(!_released) - { - Monitor.Wait(sync); - } - - destroyed = _destroyed; - callback = _callback; - Monitor.Exit(sync); - - // - // If not being destroyed by main thread call callback. - // - if(!destroyed && callback != null) - { - callback(sig); - } - } - - // - // The callbacks to be invoked from the handler. - // - private static void destroyOnInterruptCallback(int sig) - { - bool ignore = false; - Monitor.Enter(sync); - if(_destroyed) - { - // - // Being destroyed by main thread - // - ignore = true; - } - else if(_nohup && sig == SIGHUP) - { - ignore = true; - } - else - { - _callbackInProgress = true; - _interrupted = true; - _destroyed = true; - } - Monitor.Exit(sync); - - if(ignore) - { - return; - } - - try - { - _communicator.destroy(); - } - catch(System.Exception ex) - { - Console.Error.WriteLine(_appName + ": while destroying in response to signal: " + ex); - } - - Monitor.Enter(sync); - _callbackInProgress = false; - Monitor.Pulse(sync); - Monitor.Exit(sync); - } - - private static void shutdownOnInterruptCallback(int sig) - { - bool ignore = false; - Monitor.Enter(sync); - if(_destroyed) - { - // - // Being destroyed by main thread - // - ignore = true; - } - else if(_nohup && sig == SIGHUP) - { - ignore = true; - } - else - { - _callbackInProgress = true; - _interrupted = true; - } - Monitor.Exit(sync); - - if(ignore) - { - return; - } - - try - { - _communicator.shutdown(); - } - catch(System.Exception ex) - { - Console.Error.WriteLine(_appName + ": while shutting down in response to signal: " + ex); - } - - Monitor.Enter(sync); - _callbackInProgress = false; - Monitor.Pulse(sync); - Monitor.Exit(sync); - } - - private static void userCallbackOnInterruptCallback(int sig) - { - bool ignore = false; - Monitor.Enter(sync); - if(_destroyed) - { - // - // Being destroyed by main thread - // - ignore = true; - } - else if(_nohup && sig == SIGHUP) - { - ignore = true; - } - else - { - _callbackInProgress = true; - _interrupted = true; - } - Monitor.Exit(sync); - - if(ignore) - { - return; - } - - try - { - if(_application != null) - { - _application.interruptCallback(sig); - } - } - catch(System.Exception ex) - { - Console.Error.WriteLine(_appName + ": while interrupting in response to signal: " + ex); - } - - Monitor.Enter(sync); - _callbackInProgress = false; - Monitor.Pulse(sync); - Monitor.Exit(sync); - } + // + // The callbacks to be invoked from the handler. + // + private static void holdInterruptCallback(int sig) + { + bool destroyed; + Callback callback; + Monitor.Enter(sync); + while(!_released) + { + Monitor.Wait(sync); + } + + destroyed = _destroyed; + callback = _callback; + Monitor.Exit(sync); + + // + // If not being destroyed by main thread call callback. + // + if(!destroyed && callback != null) + { + callback(sig); + } + } + + // + // The callbacks to be invoked from the handler. + // + private static void destroyOnInterruptCallback(int sig) + { + bool ignore = false; + Monitor.Enter(sync); + if(_destroyed) + { + // + // Being destroyed by main thread + // + ignore = true; + } + else if(_nohup && sig == SIGHUP) + { + ignore = true; + } + else + { + _callbackInProgress = true; + _interrupted = true; + _destroyed = true; + } + Monitor.Exit(sync); + + if(ignore) + { + return; + } + + try + { + _communicator.destroy(); + } + catch(System.Exception ex) + { + Console.Error.WriteLine(_appName + ": while destroying in response to signal: " + ex); + } + + Monitor.Enter(sync); + _callbackInProgress = false; + Monitor.Pulse(sync); + Monitor.Exit(sync); + } + + private static void shutdownOnInterruptCallback(int sig) + { + bool ignore = false; + Monitor.Enter(sync); + if(_destroyed) + { + // + // Being destroyed by main thread + // + ignore = true; + } + else if(_nohup && sig == SIGHUP) + { + ignore = true; + } + else + { + _callbackInProgress = true; + _interrupted = true; + } + Monitor.Exit(sync); + + if(ignore) + { + return; + } + + try + { + _communicator.shutdown(); + } + catch(System.Exception ex) + { + Console.Error.WriteLine(_appName + ": while shutting down in response to signal: " + ex); + } + + Monitor.Enter(sync); + _callbackInProgress = false; + Monitor.Pulse(sync); + Monitor.Exit(sync); + } + + private static void userCallbackOnInterruptCallback(int sig) + { + bool ignore = false; + Monitor.Enter(sync); + if(_destroyed) + { + // + // Being destroyed by main thread + // + ignore = true; + } + else if(_nohup && sig == SIGHUP) + { + ignore = true; + } + else + { + _callbackInProgress = true; + _interrupted = true; + } + Monitor.Exit(sync); + + if(ignore) + { + return; + } + + try + { + if(_application != null) + { + _application.interruptCallback(sig); + } + } + catch(System.Exception ex) + { + Console.Error.WriteLine(_appName + ": while interrupting in response to signal: " + ex); + } + + Monitor.Enter(sync); + _callbackInProgress = false; + Monitor.Pulse(sync); + Monitor.Exit(sync); + } #if !__MonoCS__ - public delegate void ControlEventHandler(int consoleEvent); - [DllImport("kernel32.dll")] - private static extern Boolean SetConsoleCtrlHandler(Application.EventHandler eh, Boolean add); + public delegate void ControlEventHandler(int consoleEvent); + [DllImport("kernel32.dll")] + private static extern Boolean SetConsoleCtrlHandler(Application.EventHandler eh, Boolean add); #endif - private static readonly object sync = typeof(Application); + private static readonly object sync = typeof(Application); - private const int SIGHUP = 5; // CTRL_LOGOFF_EVENT, from wincon.h + private const int SIGHUP = 5; // CTRL_LOGOFF_EVENT, from wincon.h - private static bool _callbackInProgress = false; - private static bool _destroyed = false; - private static bool _interrupted = false; - private static bool _released = false; - private static bool _nohup = false; + private static bool _callbackInProgress = false; + private static bool _destroyed = false; + private static bool _interrupted = false; + private static bool _released = false; + private static bool _nohup = false; - private delegate Boolean EventHandler(int sig); + private delegate Boolean EventHandler(int sig); #if !__MonoCS__ - private static readonly Application.EventHandler _handler - = new Application.EventHandler(HandlerRoutine); // First-level handler + private static readonly Application.EventHandler _handler + = new Application.EventHandler(HandlerRoutine); // First-level handler #endif - private delegate void Callback(int sig); - private static readonly Callback _destroyCallback = new Callback(destroyOnInterruptCallback); - private static readonly Callback _shutdownCallback = new Callback(shutdownOnInterruptCallback); - private static readonly Callback _holdCallback = new Callback(holdInterruptCallback); - private static readonly Callback _userCallback = new Callback(userCallbackOnInterruptCallback); - - private static Callback _callback = null; // Current callback - private static Callback _previousCallback; // Remembers prev. callback when signals are held - - // - // We use FriendlyName instead of Process.GetCurrentProcess().ProcessName because the latter - // is terribly slow. (It takes around 1 second!) - // - private static string _appName = AppDomain.CurrentDomain.FriendlyName; - private static Communicator _communicator; - private static Application _application; + private delegate void Callback(int sig); + private static readonly Callback _destroyCallback = new Callback(destroyOnInterruptCallback); + private static readonly Callback _shutdownCallback = new Callback(shutdownOnInterruptCallback); + private static readonly Callback _holdCallback = new Callback(holdInterruptCallback); + private static readonly Callback _userCallback = new Callback(userCallbackOnInterruptCallback); + + private static Callback _callback = null; // Current callback + private static Callback _previousCallback; // Remembers prev. callback when signals are held + + // + // We use FriendlyName instead of Process.GetCurrentProcess().ProcessName because the latter + // is terribly slow. (It takes around 1 second!) + // + private static string _appName = AppDomain.CurrentDomain.FriendlyName; + private static Communicator _communicator; + private static Application _application; } } diff --git a/cs/src/Ice/Arrays.cs b/cs/src/Ice/Arrays.cs index b7d2b3b4756..ecba0e893aa 100644 --- a/cs/src/Ice/Arrays.cs +++ b/cs/src/Ice/Arrays.cs @@ -14,85 +14,85 @@ namespace IceUtil public sealed class Arrays { - public static bool Equals(object[] arr1, object[] arr2) + public static bool Equals(object[] arr1, object[] arr2) { - if(object.ReferenceEquals(arr1, arr2)) - { - return true; - } + if(object.ReferenceEquals(arr1, arr2)) + { + return true; + } - if(arr1.Length == arr2.Length) - { - for(int i = 0; i < arr1.Length; i++) - { - if(!arr1[i].Equals(arr2[i])) - { - return false; - } - } + if(arr1.Length == arr2.Length) + { + for(int i = 0; i < arr1.Length; i++) + { + if(!arr1[i].Equals(arr2[i])) + { + return false; + } + } - return true; - } + return true; + } - return false; - } + return false; + } - public static void Sort(ref ArrayList array, IComparer comparator) + public static void Sort(ref ArrayList array, IComparer comparator) { - // - // This Sort method implements the merge sort algorithm - // which is a stable sort (unlike the Sort method of the - // System.Collections.ArrayList which is unstable). - // - Sort1(ref array, 0, array.Count, comparator); - } + // + // This Sort method implements the merge sort algorithm + // which is a stable sort (unlike the Sort method of the + // System.Collections.ArrayList which is unstable). + // + Sort1(ref array, 0, array.Count, comparator); + } - private static void Sort1(ref ArrayList array, int begin, int end, IComparer comparator) + private static void Sort1(ref ArrayList array, int begin, int end, IComparer comparator) { - int mid; - if(end - begin <= 1) - { - return; - } + int mid; + if(end - begin <= 1) + { + return; + } - mid = (begin + end) / 2; - Sort1(ref array, begin, mid, comparator); - Sort1(ref array, mid, end, comparator); - Merge(ref array, begin, mid, end, comparator); - } + mid = (begin + end) / 2; + Sort1(ref array, begin, mid, comparator); + Sort1(ref array, mid, end, comparator); + Merge(ref array, begin, mid, end, comparator); + } - private static void Merge(ref ArrayList array, int begin, int mid, int end, IComparer comparator) + private static void Merge(ref ArrayList array, int begin, int mid, int end, IComparer comparator) { - int i = begin; - int j = mid; - int k = 0; + int i = begin; + int j = mid; + int k = 0; - object[] tmp = new object[end - begin]; - while(i < mid && j < end) - { - if(comparator.Compare(array[i], array[j]) <= 0) - { - tmp[k++] = array[i++]; - } - else - { - tmp[k++] = array[j++]; - } - } + object[] tmp = new object[end - begin]; + while(i < mid && j < end) + { + if(comparator.Compare(array[i], array[j]) <= 0) + { + tmp[k++] = array[i++]; + } + else + { + tmp[k++] = array[j++]; + } + } - while(i < mid) - { - tmp[k++] = array[i++]; - } - while(j < end) - { - tmp[k++] = array[j++]; - } - for(i = 0; i < (end - begin); ++i) - { - array[begin + i] = tmp[i]; - } - } + while(i < mid) + { + tmp[k++] = array[i++]; + } + while(j < end) + { + tmp[k++] = array[j++]; + } + for(i = 0; i < (end - begin); ++i) + { + array[begin + i] = tmp[i]; + } + } } } diff --git a/cs/src/Ice/AssemblyInfo.cs b/cs/src/Ice/AssemblyInfo.cs index 9f652ce2b71..3fdccaa2698 100755 --- a/cs/src/Ice/AssemblyInfo.cs +++ b/cs/src/Ice/AssemblyInfo.cs @@ -20,6 +20,6 @@ using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Ice for C#")] [assembly: AssemblyCopyright("Copyright (c) 2003-2007, ZeroC, Inc.")] [assembly: AssemblyTrademark("Ice")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.51")] [assembly: AssemblyDelaySign(false)] diff --git a/cs/src/Ice/AssemblyUtil.cs b/cs/src/Ice/AssemblyUtil.cs index dec8ecce16e..7342d2d9108 100755 --- a/cs/src/Ice/AssemblyUtil.cs +++ b/cs/src/Ice/AssemblyUtil.cs @@ -22,7 +22,7 @@ namespace IceInternal public enum Platform { Windows, NonWindows }; static AssemblyUtil() - { + { PlatformID id = Environment.OSVersion.Platform; if( id == PlatformID.Win32NT || id == PlatformID.Win32S @@ -36,151 +36,151 @@ namespace IceInternal platform_ = Platform.NonWindows; } - if(System.Type.GetType("Mono.Runtime") != null) - { - runtime_ = Runtime.Mono; - } - else - { - runtime_ = Runtime.DotNET; - } - System.Version v = System.Environment.Version; - runtimeMajor_ = v.Major; - runtimeMinor_ = v.Minor; - runtimeBuild_ = v.Build; - runtimeRevision_ = v.Revision; - } - - public static Type findType(string csharpId) - { - loadAssemblies(); // Lazy initialization - - lock(_mutex) - { - Type t = (Type)_typeTable[csharpId]; - if(t != null) - { - return t; - } - foreach(Assembly a in _loadedAssemblies.Values) - { - if((t = a.GetType(csharpId)) != null) - { - _typeTable[csharpId] = t; - return t; - } - } - } - return null; - } - - public static Type[] findTypesWithPrefix(string prefix) - { - IceUtil.LinkedList l = new IceUtil.LinkedList(); - - loadAssemblies(); // Lazy initialization - - lock(_mutex) - { - foreach(Assembly a in _loadedAssemblies.Values) - { - Type[] types = a.GetTypes(); - foreach(Type t in types) - { - if(t.AssemblyQualifiedName.IndexOf(prefix) == 0) - { - l.Add(t); - } - } - } - } - - Type[] result = new Type[l.Count]; + if(System.Type.GetType("Mono.Runtime") != null) + { + runtime_ = Runtime.Mono; + } + else + { + runtime_ = Runtime.DotNET; + } + System.Version v = System.Environment.Version; + runtimeMajor_ = v.Major; + runtimeMinor_ = v.Minor; + runtimeBuild_ = v.Build; + runtimeRevision_ = v.Revision; + } + + public static Type findType(string csharpId) + { + loadAssemblies(); // Lazy initialization + + lock(_mutex) + { + Type t = (Type)_typeTable[csharpId]; + if(t != null) + { + return t; + } + foreach(Assembly a in _loadedAssemblies.Values) + { + if((t = a.GetType(csharpId)) != null) + { + _typeTable[csharpId] = t; + return t; + } + } + } + return null; + } + + public static Type[] findTypesWithPrefix(string prefix) + { + IceUtil.LinkedList l = new IceUtil.LinkedList(); + + loadAssemblies(); // Lazy initialization + + lock(_mutex) + { + foreach(Assembly a in _loadedAssemblies.Values) + { + Type[] types = a.GetTypes(); + foreach(Type t in types) + { + if(t.AssemblyQualifiedName.IndexOf(prefix) == 0) + { + l.Add(t); + } + } + } + } + + Type[] result = new Type[l.Count]; if(l.Count > 0) { l.CopyTo(result, 0); } - return result; - } - - public static object createInstance(Type t) - { - ConstructorInfo[] constructors = t.GetConstructors(); - - if(constructors.Length == 0) - { - return null; - } - - ParameterInfo[] firstConstructor = constructors[0].GetParameters(); - - int paramCount = firstConstructor.Length; - Type[] constructor = new Type[paramCount]; - for(int i = 0; i < paramCount; i++) - { - constructor[i] = firstConstructor[i].ParameterType; - } - - return t.GetConstructor(constructor).Invoke(new object[]{}); - } - - // - // Make sure that all assemblies that are referenced by this process - // are actually loaded. This is necessary so we can use reflection - // on any type in any assembly (because the type we are after will - // most likely not be in the current assembly and, worse, may be - // in an assembly that has not been loaded yet. (Type.GetType() - // is no good because it looks only in the calling object's assembly - // and mscorlib.dll.) - // - private static void loadAssemblies() - { - lock(_mutex) - { - if(!_assembliesLoaded) - { - Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); - foreach(Assembly a in assemblies) - { - _loadedAssemblies[a.FullName] = a; - } - foreach(Assembly a in assemblies) - { - loadReferencedAssemblies(a); - } - _assembliesLoaded = true; - } - } - } - - private static void loadReferencedAssemblies(Assembly a) - { - AssemblyName[] names = a.GetReferencedAssemblies(); - foreach(AssemblyName name in names) - { - if(!_loadedAssemblies.Contains(name.FullName)) - { - Assembly ra = Assembly.Load(name); - _loadedAssemblies[ra.FullName] = ra; - loadReferencedAssemblies(ra); - } - } - } - - private static bool _assembliesLoaded = false; - private static Hashtable _loadedAssemblies = new Hashtable(); // <string, Assembly> pairs. - private static Hashtable _typeTable = new Hashtable(); // <type name, Type> pairs. - private static Mutex _mutex = new Mutex(); - - public readonly static Runtime runtime_; // Either DotNET or Mono - // - // Versioning is: Major.Minor.Build.Revision. (Yes, really. It is not Major.Minor.Revision.Build, as - // one might expect.) If a part of a version number (such as revision) is not defined, it is -1. - // - public readonly static int runtimeMajor_; - public readonly static int runtimeMinor_; - public readonly static int runtimeBuild_; - public readonly static int runtimeRevision_; + return result; + } + + public static object createInstance(Type t) + { + ConstructorInfo[] constructors = t.GetConstructors(); + + if(constructors.Length == 0) + { + return null; + } + + ParameterInfo[] firstConstructor = constructors[0].GetParameters(); + + int paramCount = firstConstructor.Length; + Type[] constructor = new Type[paramCount]; + for(int i = 0; i < paramCount; i++) + { + constructor[i] = firstConstructor[i].ParameterType; + } + + return t.GetConstructor(constructor).Invoke(new object[]{}); + } + + // + // Make sure that all assemblies that are referenced by this process + // are actually loaded. This is necessary so we can use reflection + // on any type in any assembly (because the type we are after will + // most likely not be in the current assembly and, worse, may be + // in an assembly that has not been loaded yet. (Type.GetType() + // is no good because it looks only in the calling object's assembly + // and mscorlib.dll.) + // + private static void loadAssemblies() + { + lock(_mutex) + { + if(!_assembliesLoaded) + { + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach(Assembly a in assemblies) + { + _loadedAssemblies[a.FullName] = a; + } + foreach(Assembly a in assemblies) + { + loadReferencedAssemblies(a); + } + _assembliesLoaded = true; + } + } + } + + private static void loadReferencedAssemblies(Assembly a) + { + AssemblyName[] names = a.GetReferencedAssemblies(); + foreach(AssemblyName name in names) + { + if(!_loadedAssemblies.Contains(name.FullName)) + { + Assembly ra = Assembly.Load(name); + _loadedAssemblies[ra.FullName] = ra; + loadReferencedAssemblies(ra); + } + } + } + + private static bool _assembliesLoaded = false; + private static Hashtable _loadedAssemblies = new Hashtable(); // <string, Assembly> pairs. + private static Hashtable _typeTable = new Hashtable(); // <type name, Type> pairs. + private static Mutex _mutex = new Mutex(); + + public readonly static Runtime runtime_; // Either DotNET or Mono + // + // Versioning is: Major.Minor.Build.Revision. (Yes, really. It is not Major.Minor.Revision.Build, as + // one might expect.) If a part of a version number (such as revision) is not defined, it is -1. + // + public readonly static int runtimeMajor_; + public readonly static int runtimeMinor_; + public readonly static int runtimeBuild_; + public readonly static int runtimeRevision_; public readonly static Platform platform_; } diff --git a/cs/src/Ice/BasicInputStream.cs b/cs/src/Ice/BasicInputStream.cs index 45b2b6dc9ba..0a26dfb4339 100644 --- a/cs/src/Ice/BasicInputStream.cs +++ b/cs/src/Ice/BasicInputStream.cs @@ -11,12 +11,12 @@ namespace IceInternal { public class BasicInputStream : BasicStream { - public BasicInputStream(Instance instance, Ice.InputStream inStream) + public BasicInputStream(Instance instance, Ice.InputStream inStream) : base(instance) - { - in_ = inStream; - } + { + in_ = inStream; + } - public Ice.InputStream in_; + public Ice.InputStream in_; } } diff --git a/cs/src/Ice/BasicOutputStream.cs b/cs/src/Ice/BasicOutputStream.cs index db8f353f1cd..7c512f633bd 100644 --- a/cs/src/Ice/BasicOutputStream.cs +++ b/cs/src/Ice/BasicOutputStream.cs @@ -12,12 +12,12 @@ namespace IceInternal public class BasicOutputStream : BasicStream { - public BasicOutputStream(Instance instance, Ice.OutputStream outStream) + public BasicOutputStream(Instance instance, Ice.OutputStream outStream) : base(instance) - { - out_ = outStream; - } + { + out_ = outStream; + } - public Ice.OutputStream out_; + public Ice.OutputStream out_; } } diff --git a/cs/src/Ice/BasicStream.cs b/cs/src/Ice/BasicStream.cs index be766ecf375..7d8f3398f8e 100755 --- a/cs/src/Ice/BasicStream.cs +++ b/cs/src/Ice/BasicStream.cs @@ -39,1008 +39,1008 @@ namespace IceInternal { _bzlibInstalled = false; } - catch(System.EntryPointNotFoundException) - { + catch(System.EntryPointNotFoundException) + { _bzlibInstalled = false; - } - } - - public BasicStream(IceInternal.Instance instance) - { - initialize(instance, false); - } - - public BasicStream(IceInternal.Instance instance, bool unlimited) - { - initialize(instance, unlimited); - } - - private void initialize(IceInternal.Instance instance, bool unlimited) - { - instance_ = instance; - _unlimited = unlimited; - allocate(1500); - _capacity = _buf.capacity(); - _limit = 0; - Debug.Assert(_buf.limit() == _capacity); - - _readEncapsStack = null; - _writeEncapsStack = null; - _readEncapsCache = null; - _writeEncapsCache = null; - - _traceSlicing = -1; - - _sliceObjects = true; - - _messageSizeMax = instance_.messageSizeMax(); // Cached for efficiency. - - _seqDataStack = null; - _objectList = null; - } - - // - // This function allows this object to be reused, rather than - // reallocated. - // - public virtual void reset() - { - _limit = 0; - _buf.limit(_capacity); - _buf.position(0); - - if(_readEncapsStack != null) - { - Debug.Assert(_readEncapsStack.next == null); - _readEncapsStack.next = _readEncapsCache; - _readEncapsCache = _readEncapsStack; - _readEncapsStack = null; - _readEncapsCache.reset(); - } - - if(_objectList != null) - { - _objectList.Clear(); - } - } - - public virtual IceInternal.Instance instance() - { - return instance_; - } - - public virtual void swap(BasicStream other) - { - Debug.Assert(instance_ == other.instance_); - - ByteBuffer tmpBuf = other._buf; - other._buf = _buf; - _buf = tmpBuf; - - int tmpCapacity = other._capacity; - other._capacity = _capacity; - _capacity = tmpCapacity; - - int tmpLimit = other._limit; - other._limit = _limit; - _limit = tmpLimit; - - ReadEncaps tmpRead = other._readEncapsStack; - other._readEncapsStack = _readEncapsStack; - _readEncapsStack = tmpRead; - - tmpRead = other._readEncapsCache; - other._readEncapsCache = _readEncapsCache; - _readEncapsCache = tmpRead; - - WriteEncaps tmpWrite = other._writeEncapsStack; - other._writeEncapsStack = _writeEncapsStack; - _writeEncapsStack = tmpWrite; - - tmpWrite = other._writeEncapsCache; - other._writeEncapsCache = _writeEncapsCache; - _writeEncapsCache = tmpWrite; - - int tmpReadSlice = other._readSlice; - other._readSlice = _readSlice; - _readSlice = tmpReadSlice; - - int tmpWriteSlice = other._writeSlice; - other._writeSlice = _writeSlice; - _writeSlice = tmpWriteSlice; - - SeqData tmpSeqDataStack = other._seqDataStack; - other._seqDataStack = _seqDataStack; - _seqDataStack = tmpSeqDataStack; - - ArrayList tmpObjectList = other._objectList; - other._objectList = _objectList; - _objectList = tmpObjectList; - - bool tmpUnlimited = other._unlimited; - other._unlimited = _unlimited; - _unlimited = tmpUnlimited; - } - - public virtual void resize(int total, bool reading) - { - if(!_unlimited && total > _messageSizeMax) - { - throw new Ice.MemoryLimitException("Message size > Ice.MessageSizeMax"); - } - if(total > _capacity) - { - int cap2 = _capacity << 1; - int newCapacity = cap2 > total ? cap2 : total; - _buf.limit(_limit); - reallocate(newCapacity); - _capacity = _buf.capacity(); - } - // - // If this stream is used for reading, then we want to set - // the buffer's limit to the new total size. If this - // buffer is used for writing, then we must set the - // buffer's limit to the buffer's capacity. - // - if(reading) - { - _buf.limit(total); - } - else - { - _buf.limit(_capacity); - } - _buf.position(total); - _limit = total; - } - - public virtual ByteBuffer prepareRead() - { - return _buf; - } - - public virtual ByteBuffer prepareWrite() - { - _buf.limit(_limit); - _buf.position(0); - return _buf; - } - - // - // startSeq() and endSeq() sanity-check sequence sizes during - // unmarshaling and prevent malicious messages with incorrect - // sequence sizes from causing the receiver to use up all - // available memory by allocating sequences with an impossibly - // large number of elements. - // - // The code generator inserts calls to startSeq() and endSeq() - // around the code to unmarshal a sequence. startSeq() is - // called immediately after reading the sequence size, and - // endSeq() is called after reading the final element of a - // sequence. - // - // For sequences that contain constructed types that, in turn, - // contain sequences, the code generator also inserts a call - // to endElement() after unmarshaling each element. - // - // startSeq() is passed the unmarshaled element count, plus - // the minimum size (in bytes) occupied by the sequence's - // element type. numElements * minSize is the smallest - // possible number of bytes that the sequence will occupy on - // the wire. - // - // Every time startSeq() is called, it pushes the element - // count and the minimum size on a stack. Every time endSeq() - // is called, it pops the stack. - // - // For an ordinary sequence (one that does not (recursively) - // contain nested sequences), numElements * minSize must be - // less than the number of bytes remaining in the stream. - // - // For a sequence that is nested within some other sequence, - // there must be enough bytes remaining in the stream for this - // sequence (numElements + minSize), plus the sum of the bytes - // required by the remaining elements of all the enclosing - // sequences. - // - // For the enclosing sequences, numElements - 1 is the number - // of elements for which unmarshaling has not started - // yet. (The call to endElement() in the generated code - // decrements that number whenever a sequence element is - // unmarshaled.) - // - // For sequence that variable-length elements, checkSeq() is - // called whenever an element is unmarshaled. checkSeq() also - // checks whether the stream has a sufficient number of bytes - // remaining. This means that, for messages with bogus - // sequence sizes, unmarshaling is aborted at the earliest - // possible point. - // - - public void startSeq(int numElements, int minSize) - { - if(numElements == 0) // Optimization to avoid pushing a useless stack frame. - { - return; - } - - // - // Push the current sequence details on the stack. - // - SeqData sd = new SeqData(numElements, minSize); - sd.previous = _seqDataStack; - _seqDataStack = sd; - - int bytesLeft = _buf.remaining(); - if(_seqDataStack.previous == null) // Outermost sequence - { - // - // The sequence must fit within the message. - // - if(numElements * minSize > bytesLeft) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - else // Nested sequence - { - checkSeq(bytesLeft); - } - } - - // - // Check, given the number of elements requested for this - // sequence, that this sequence, plus the sum of the sizes of - // the remaining number of elements of all enclosing - // sequences, would still fit within the message. - // - public void checkSeq() - { - checkSeq(_buf.remaining()); - } - - public void checkSeq(int bytesLeft) - { - int size = 0; - SeqData sd = _seqDataStack; - do - { - size += (sd.numElements - 1) * sd.minSize; - sd = sd.previous; - } - while(sd != null); - - if(size > bytesLeft) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void checkFixedSeq(int numElements, int elemSize) - { - int bytesLeft = _buf.remaining(); - if(_seqDataStack == null) // Outermost sequence - { - // - // The sequence must fit within the message. - // - if(numElements * elemSize > bytesLeft) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - else // Nested sequence - { - checkSeq(bytesLeft - numElements * elemSize); - } - } - - public void endElement() - { - Debug.Assert(_seqDataStack != null); - --_seqDataStack.numElements; - } - - public void endSeq(int sz) - { - if(sz == 0) // Pop only if something was pushed previously. - { - return; - } - - // - // Pop the sequence stack. - // - SeqData oldSeqData = _seqDataStack; - Debug.Assert(oldSeqData != null); - _seqDataStack = oldSeqData.previous; - } - - public virtual void startWriteEncaps() - { - { - WriteEncaps curr = _writeEncapsCache; - if(curr != null) - { - curr.reset(); - _writeEncapsCache = _writeEncapsCache.next; - } - else - { - curr = new WriteEncaps(); - } - curr.next = _writeEncapsStack; - _writeEncapsStack = curr; - } - - _writeEncapsStack.start = _buf.position(); - writeInt(0); // Placeholder for the encapsulation length. - writeByte(Protocol.encodingMajor); - writeByte(Protocol.encodingMinor); - } - - public virtual void endWriteEncaps() - { - Debug.Assert(_writeEncapsStack != null); - int start = _writeEncapsStack.start; - int sz = _buf.position() - start; // Size includes size and version. - _buf.putInt(start, sz); - - WriteEncaps curr = _writeEncapsStack; - _writeEncapsStack = curr.next; - curr.next = _writeEncapsCache; - _writeEncapsCache = curr; - _writeEncapsCache.reset(); - } - - public virtual void startReadEncaps() - { - { - ReadEncaps curr = _readEncapsCache; - if(curr != null) - { - curr.reset(); - _readEncapsCache = _readEncapsCache.next; - } - else - { - curr = new ReadEncaps(); - } - curr.next = _readEncapsStack; - _readEncapsStack = curr; - } - - _readEncapsStack.start = _buf.position(); - - // - // I don't use readSize() and writeSize() for - // encapsulations, because when creating an encapsulation, - // I must know in advance how many bytes the size - // information will require in the data stream. If I use - // an Int, it is always 4 bytes. For - // readSize()/writeSize(), it could be 1 or 5 bytes. - // - int sz = readInt(); - if(sz < 0) - { - throw new Ice.NegativeSizeException(); - } - - if(sz - 4 > _buf.limit()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - _readEncapsStack.sz = sz; - - byte eMajor = readByte(); - byte eMinor = readByte(); - if(eMajor != Protocol.encodingMajor || eMinor > Protocol.encodingMinor) - { - Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); - e.badMajor = eMajor < 0 ? eMajor + 256 : eMajor; - e.badMinor = eMinor < 0 ? eMinor + 256 : eMinor; - e.major = Protocol.encodingMajor; - e.minor = Protocol.encodingMinor; - throw e; - } - _readEncapsStack.encodingMajor = eMajor; - _readEncapsStack.encodingMinor = eMinor; - } - - public virtual void endReadEncaps() - { - Debug.Assert(_readEncapsStack != null); - int start = _readEncapsStack.start; - int sz = _readEncapsStack.sz; - try - { - _buf.position(start + sz); - } - catch(ArgumentOutOfRangeException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - - ReadEncaps curr = _readEncapsStack; - _readEncapsStack = curr.next; - curr.next = _readEncapsCache; - _readEncapsCache = curr; - _readEncapsCache.reset(); - } - - public virtual void checkReadEncaps() - { - Debug.Assert(_readEncapsStack != null); - int start = _readEncapsStack.start; - int sz = _readEncapsStack.sz; - if(_buf.position() != start + sz) - { - throw new Ice.EncapsulationException(); - } - } - - public virtual int getReadEncapsSize() - { - Debug.Assert(_readEncapsStack != null); - return _readEncapsStack.sz - 6; - } - - public virtual void skipEncaps() - { - int sz = readInt(); - if(sz < 0) - { - throw new Ice.NegativeSizeException(); - } - try - { - _buf.position(_buf.position() + sz - 4); - } - catch(ArgumentOutOfRangeException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void startWriteSlice() - { - writeInt(0); // Placeholder for the slice length. - _writeSlice = _buf.position(); - } - - public virtual void endWriteSlice() - { - int sz = _buf.position() - _writeSlice + 4; - _buf.putInt(_writeSlice - 4, sz); - } - - public virtual void startReadSlice() - { - int sz = readInt(); - if(sz < 0) - { - throw new Ice.NegativeSizeException(); - } - _readSlice = _buf.position(); - } - - public virtual void endReadSlice() - { - } - - public virtual void skipSlice() - { - int sz = readInt(); - if(sz < 0) - { - throw new Ice.NegativeSizeException(); - } - try - { - _buf.position(_buf.position() + sz - 4); - } - catch(ArgumentOutOfRangeException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeSize(int v) - { - if(v > 254) - { - expand(5); - _buf.put((byte)255); - _buf.putInt(v); - } - else - { - expand(1); - _buf.put((byte)v); - } - } - - public virtual int readSize() - { - try - { - // - // COMPILERFIX: for some reasons _buf.get() doesn't work here on MacOS X with Mono; + } + } + + public BasicStream(IceInternal.Instance instance) + { + initialize(instance, false); + } + + public BasicStream(IceInternal.Instance instance, bool unlimited) + { + initialize(instance, unlimited); + } + + private void initialize(IceInternal.Instance instance, bool unlimited) + { + instance_ = instance; + _unlimited = unlimited; + allocate(1500); + _capacity = _buf.capacity(); + _limit = 0; + Debug.Assert(_buf.limit() == _capacity); + + _readEncapsStack = null; + _writeEncapsStack = null; + _readEncapsCache = null; + _writeEncapsCache = null; + + _traceSlicing = -1; + + _sliceObjects = true; + + _messageSizeMax = instance_.messageSizeMax(); // Cached for efficiency. + + _seqDataStack = null; + _objectList = null; + } + + // + // This function allows this object to be reused, rather than + // reallocated. + // + public virtual void reset() + { + _limit = 0; + _buf.limit(_capacity); + _buf.position(0); + + if(_readEncapsStack != null) + { + Debug.Assert(_readEncapsStack.next == null); + _readEncapsStack.next = _readEncapsCache; + _readEncapsCache = _readEncapsStack; + _readEncapsStack = null; + _readEncapsCache.reset(); + } + + if(_objectList != null) + { + _objectList.Clear(); + } + } + + public virtual IceInternal.Instance instance() + { + return instance_; + } + + public virtual void swap(BasicStream other) + { + Debug.Assert(instance_ == other.instance_); + + ByteBuffer tmpBuf = other._buf; + other._buf = _buf; + _buf = tmpBuf; + + int tmpCapacity = other._capacity; + other._capacity = _capacity; + _capacity = tmpCapacity; + + int tmpLimit = other._limit; + other._limit = _limit; + _limit = tmpLimit; + + ReadEncaps tmpRead = other._readEncapsStack; + other._readEncapsStack = _readEncapsStack; + _readEncapsStack = tmpRead; + + tmpRead = other._readEncapsCache; + other._readEncapsCache = _readEncapsCache; + _readEncapsCache = tmpRead; + + WriteEncaps tmpWrite = other._writeEncapsStack; + other._writeEncapsStack = _writeEncapsStack; + _writeEncapsStack = tmpWrite; + + tmpWrite = other._writeEncapsCache; + other._writeEncapsCache = _writeEncapsCache; + _writeEncapsCache = tmpWrite; + + int tmpReadSlice = other._readSlice; + other._readSlice = _readSlice; + _readSlice = tmpReadSlice; + + int tmpWriteSlice = other._writeSlice; + other._writeSlice = _writeSlice; + _writeSlice = tmpWriteSlice; + + SeqData tmpSeqDataStack = other._seqDataStack; + other._seqDataStack = _seqDataStack; + _seqDataStack = tmpSeqDataStack; + + ArrayList tmpObjectList = other._objectList; + other._objectList = _objectList; + _objectList = tmpObjectList; + + bool tmpUnlimited = other._unlimited; + other._unlimited = _unlimited; + _unlimited = tmpUnlimited; + } + + public virtual void resize(int total, bool reading) + { + if(!_unlimited && total > _messageSizeMax) + { + throw new Ice.MemoryLimitException("Message size > Ice.MessageSizeMax"); + } + if(total > _capacity) + { + int cap2 = _capacity << 1; + int newCapacity = cap2 > total ? cap2 : total; + _buf.limit(_limit); + reallocate(newCapacity); + _capacity = _buf.capacity(); + } + // + // If this stream is used for reading, then we want to set + // the buffer's limit to the new total size. If this + // buffer is used for writing, then we must set the + // buffer's limit to the buffer's capacity. + // + if(reading) + { + _buf.limit(total); + } + else + { + _buf.limit(_capacity); + } + _buf.position(total); + _limit = total; + } + + public virtual ByteBuffer prepareRead() + { + return _buf; + } + + public virtual ByteBuffer prepareWrite() + { + _buf.limit(_limit); + _buf.position(0); + return _buf; + } + + // + // startSeq() and endSeq() sanity-check sequence sizes during + // unmarshaling and prevent malicious messages with incorrect + // sequence sizes from causing the receiver to use up all + // available memory by allocating sequences with an impossibly + // large number of elements. + // + // The code generator inserts calls to startSeq() and endSeq() + // around the code to unmarshal a sequence. startSeq() is + // called immediately after reading the sequence size, and + // endSeq() is called after reading the final element of a + // sequence. + // + // For sequences that contain constructed types that, in turn, + // contain sequences, the code generator also inserts a call + // to endElement() after unmarshaling each element. + // + // startSeq() is passed the unmarshaled element count, plus + // the minimum size (in bytes) occupied by the sequence's + // element type. numElements * minSize is the smallest + // possible number of bytes that the sequence will occupy on + // the wire. + // + // Every time startSeq() is called, it pushes the element + // count and the minimum size on a stack. Every time endSeq() + // is called, it pops the stack. + // + // For an ordinary sequence (one that does not (recursively) + // contain nested sequences), numElements * minSize must be + // less than the number of bytes remaining in the stream. + // + // For a sequence that is nested within some other sequence, + // there must be enough bytes remaining in the stream for this + // sequence (numElements + minSize), plus the sum of the bytes + // required by the remaining elements of all the enclosing + // sequences. + // + // For the enclosing sequences, numElements - 1 is the number + // of elements for which unmarshaling has not started + // yet. (The call to endElement() in the generated code + // decrements that number whenever a sequence element is + // unmarshaled.) + // + // For sequence that variable-length elements, checkSeq() is + // called whenever an element is unmarshaled. checkSeq() also + // checks whether the stream has a sufficient number of bytes + // remaining. This means that, for messages with bogus + // sequence sizes, unmarshaling is aborted at the earliest + // possible point. + // + + public void startSeq(int numElements, int minSize) + { + if(numElements == 0) // Optimization to avoid pushing a useless stack frame. + { + return; + } + + // + // Push the current sequence details on the stack. + // + SeqData sd = new SeqData(numElements, minSize); + sd.previous = _seqDataStack; + _seqDataStack = sd; + + int bytesLeft = _buf.remaining(); + if(_seqDataStack.previous == null) // Outermost sequence + { + // + // The sequence must fit within the message. + // + if(numElements * minSize > bytesLeft) + { + throw new Ice.UnmarshalOutOfBoundsException(); + } + } + else // Nested sequence + { + checkSeq(bytesLeft); + } + } + + // + // Check, given the number of elements requested for this + // sequence, that this sequence, plus the sum of the sizes of + // the remaining number of elements of all enclosing + // sequences, would still fit within the message. + // + public void checkSeq() + { + checkSeq(_buf.remaining()); + } + + public void checkSeq(int bytesLeft) + { + int size = 0; + SeqData sd = _seqDataStack; + do + { + size += (sd.numElements - 1) * sd.minSize; + sd = sd.previous; + } + while(sd != null); + + if(size > bytesLeft) + { + throw new Ice.UnmarshalOutOfBoundsException(); + } + } + + public void checkFixedSeq(int numElements, int elemSize) + { + int bytesLeft = _buf.remaining(); + if(_seqDataStack == null) // Outermost sequence + { + // + // The sequence must fit within the message. // - //byte b = _buf.get(); - byte b = readByte(); - if(b == 255) - { - int v = _buf.getInt(); - if(v < 0) - { - throw new Ice.NegativeSizeException(); - } - return v; - } - else - { - return (int) (b < 0 ? b + 256 : b); - } - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeTypeId(string id) - { - object o = _writeEncapsStack.typeIdMap[id]; - if(o != null) - { - writeBool(true); - writeSize((int)o); - } - else - { - int index = ++_writeEncapsStack.typeIdIndex; - _writeEncapsStack.typeIdMap[id] = index; - writeBool(false); - writeString(id); - } - } - - public virtual string readTypeId() - { - string id; - int index; - bool isIndex = readBool(); - if(isIndex) - { - index = readSize(); - id = (string)_readEncapsStack.typeIdMap[index]; - if(id == null) - { - throw new Ice.UnmarshalOutOfBoundsException("Missing type ID"); - } - } - else - { - id = readString(); - index = ++_readEncapsStack.typeIdIndex; - _readEncapsStack.typeIdMap[index] = id; - } - return id; - } - - public virtual void writeBlob(byte[] v) - { + if(numElements * elemSize > bytesLeft) + { + throw new Ice.UnmarshalOutOfBoundsException(); + } + } + else // Nested sequence + { + checkSeq(bytesLeft - numElements * elemSize); + } + } + + public void endElement() + { + Debug.Assert(_seqDataStack != null); + --_seqDataStack.numElements; + } + + public void endSeq(int sz) + { + if(sz == 0) // Pop only if something was pushed previously. + { + return; + } + + // + // Pop the sequence stack. + // + SeqData oldSeqData = _seqDataStack; + Debug.Assert(oldSeqData != null); + _seqDataStack = oldSeqData.previous; + } + + public virtual void startWriteEncaps() + { + { + WriteEncaps curr = _writeEncapsCache; + if(curr != null) + { + curr.reset(); + _writeEncapsCache = _writeEncapsCache.next; + } + else + { + curr = new WriteEncaps(); + } + curr.next = _writeEncapsStack; + _writeEncapsStack = curr; + } + + _writeEncapsStack.start = _buf.position(); + writeInt(0); // Placeholder for the encapsulation length. + writeByte(Protocol.encodingMajor); + writeByte(Protocol.encodingMinor); + } + + public virtual void endWriteEncaps() + { + Debug.Assert(_writeEncapsStack != null); + int start = _writeEncapsStack.start; + int sz = _buf.position() - start; // Size includes size and version. + _buf.putInt(start, sz); + + WriteEncaps curr = _writeEncapsStack; + _writeEncapsStack = curr.next; + curr.next = _writeEncapsCache; + _writeEncapsCache = curr; + _writeEncapsCache.reset(); + } + + public virtual void startReadEncaps() + { + { + ReadEncaps curr = _readEncapsCache; + if(curr != null) + { + curr.reset(); + _readEncapsCache = _readEncapsCache.next; + } + else + { + curr = new ReadEncaps(); + } + curr.next = _readEncapsStack; + _readEncapsStack = curr; + } + + _readEncapsStack.start = _buf.position(); + + // + // I don't use readSize() and writeSize() for + // encapsulations, because when creating an encapsulation, + // I must know in advance how many bytes the size + // information will require in the data stream. If I use + // an Int, it is always 4 bytes. For + // readSize()/writeSize(), it could be 1 or 5 bytes. + // + int sz = readInt(); + if(sz < 0) + { + throw new Ice.NegativeSizeException(); + } + + if(sz - 4 > _buf.limit()) + { + throw new Ice.UnmarshalOutOfBoundsException(); + } + _readEncapsStack.sz = sz; + + byte eMajor = readByte(); + byte eMinor = readByte(); + if(eMajor != Protocol.encodingMajor || eMinor > Protocol.encodingMinor) + { + Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); + e.badMajor = eMajor < 0 ? eMajor + 256 : eMajor; + e.badMinor = eMinor < 0 ? eMinor + 256 : eMinor; + e.major = Protocol.encodingMajor; + e.minor = Protocol.encodingMinor; + throw e; + } + _readEncapsStack.encodingMajor = eMajor; + _readEncapsStack.encodingMinor = eMinor; + } + + public virtual void endReadEncaps() + { + Debug.Assert(_readEncapsStack != null); + int start = _readEncapsStack.start; + int sz = _readEncapsStack.sz; + try + { + _buf.position(start + sz); + } + catch(ArgumentOutOfRangeException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + + ReadEncaps curr = _readEncapsStack; + _readEncapsStack = curr.next; + curr.next = _readEncapsCache; + _readEncapsCache = curr; + _readEncapsCache.reset(); + } + + public virtual void checkReadEncaps() + { + Debug.Assert(_readEncapsStack != null); + int start = _readEncapsStack.start; + int sz = _readEncapsStack.sz; + if(_buf.position() != start + sz) + { + throw new Ice.EncapsulationException(); + } + } + + public virtual int getReadEncapsSize() + { + Debug.Assert(_readEncapsStack != null); + return _readEncapsStack.sz - 6; + } + + public virtual void skipEncaps() + { + int sz = readInt(); + if(sz < 0) + { + throw new Ice.NegativeSizeException(); + } + try + { + _buf.position(_buf.position() + sz - 4); + } + catch(ArgumentOutOfRangeException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void startWriteSlice() + { + writeInt(0); // Placeholder for the slice length. + _writeSlice = _buf.position(); + } + + public virtual void endWriteSlice() + { + int sz = _buf.position() - _writeSlice + 4; + _buf.putInt(_writeSlice - 4, sz); + } + + public virtual void startReadSlice() + { + int sz = readInt(); + if(sz < 0) + { + throw new Ice.NegativeSizeException(); + } + _readSlice = _buf.position(); + } + + public virtual void endReadSlice() + { + } + + public virtual void skipSlice() + { + int sz = readInt(); + if(sz < 0) + { + throw new Ice.NegativeSizeException(); + } + try + { + _buf.position(_buf.position() + sz - 4); + } + catch(ArgumentOutOfRangeException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeSize(int v) + { + if(v > 254) + { + expand(5); + _buf.put((byte)255); + _buf.putInt(v); + } + else + { + expand(1); + _buf.put((byte)v); + } + } + + public virtual int readSize() + { + try + { + // + // COMPILERFIX: for some reasons _buf.get() doesn't work here on MacOS X with Mono; + // + //byte b = _buf.get(); + byte b = readByte(); + if(b == 255) + { + int v = _buf.getInt(); + if(v < 0) + { + throw new Ice.NegativeSizeException(); + } + return v; + } + else + { + return (int) (b < 0 ? b + 256 : b); + } + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeTypeId(string id) + { + object o = _writeEncapsStack.typeIdMap[id]; + if(o != null) + { + writeBool(true); + writeSize((int)o); + } + else + { + int index = ++_writeEncapsStack.typeIdIndex; + _writeEncapsStack.typeIdMap[id] = index; + writeBool(false); + writeString(id); + } + } + + public virtual string readTypeId() + { + string id; + int index; + bool isIndex = readBool(); + if(isIndex) + { + index = readSize(); + id = (string)_readEncapsStack.typeIdMap[index]; + if(id == null) + { + throw new Ice.UnmarshalOutOfBoundsException("Missing type ID"); + } + } + else + { + id = readString(); + index = ++_readEncapsStack.typeIdIndex; + _readEncapsStack.typeIdMap[index] = id; + } + return id; + } + + public virtual void writeBlob(byte[] v) + { if(v == null) { return; } - expand(v.Length); - _buf.put(v); - } - - public virtual void readBlob(byte[] v) - { - try - { - _buf.get(v); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual byte[] readBlob(int sz) - { - byte[] v = new byte[sz]; - try - { - _buf.get(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeByte(byte v) - { - expand(1); - _buf.put(v); - } - - public virtual void writeByteSeq(byte[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length); - _buf.put(v); - } - } - - public virtual byte readByte() - { - try - { - return _buf.get(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual byte[] readByteSeq() - { - try - { - int sz = readSize(); - checkFixedSeq(sz, 1); - byte[] v = new byte[sz]; - _buf.get(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeBool(bool v) - { - expand(1); - _buf.put(v ? (byte)1 : (byte)0); - } - - public virtual void writeBoolSeq(bool[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length); - _buf.putBoolSeq(v); - } - } - - public virtual bool readBool() - { - try - { - return _buf.get() == 1; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual bool[] readBoolSeq() - { - try - { - int sz = readSize(); - checkFixedSeq(sz, 1); - bool[] v = new bool[sz]; - _buf.getBoolSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeShort(short v) - { - expand(2); - _buf.putShort(v); - } - - public virtual void writeShortSeq(short[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 2); - _buf.putShortSeq(v); - } - } - - public virtual short readShort() - { - try - { - return _buf.getShort(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual short[] readShortSeq() - { - try - { - int sz = readSize(); - checkFixedSeq(sz, 2); - short[] v = new short[sz]; - _buf.getShortSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeInt(int v) - { - expand(4); - _buf.putInt(v); - } - - public virtual void writeIntSeq(int[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 4); - _buf.putIntSeq(v); - } - } - - public virtual int readInt() - { - try - { - return _buf.getInt(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual int[] readIntSeq() - { - try - { - int sz = readSize(); - checkFixedSeq(sz, 4); - int[] v = new int[sz]; - _buf.getIntSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeLong(long v) - { - expand(8); - _buf.putLong(v); - } - - public virtual void writeLongSeq(long[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 8); - _buf.putLongSeq(v); - } - } - - public virtual long readLong() - { - try - { - return _buf.getLong(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual long[] readLongSeq() - { - try - { - int sz = readSize(); - checkFixedSeq(sz, 8); - long[] v = new long[sz]; - _buf.getLongSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeFloat(float v) - { - expand(4); - _buf.putFloat(v); - } - - public virtual void writeFloatSeq(float[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 4); - _buf.putFloatSeq(v); - } - } - - public virtual float readFloat() - { - try - { - return _buf.getFloat(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual float[] readFloatSeq() - { - try - { - int sz = readSize(); - checkFixedSeq(sz, 4); - float[] v = new float[sz]; - _buf.getFloatSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual void writeDouble(double v) - { - expand(8); - _buf.putDouble(v); - } - - public virtual void writeDoubleSeq(double[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - expand(v.Length * 8); - _buf.putDoubleSeq(v); - } - } - - public virtual double readDouble() - { - try - { - return _buf.getDouble(); - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - public virtual double[] readDoubleSeq() - { - try - { - int sz = readSize(); - checkFixedSeq(sz, 8); - double[] v = new double[sz]; - _buf.getDoubleSeq(v); - return v; - } - catch(InvalidOperationException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(ex); - } - } - - private static System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); + expand(v.Length); + _buf.put(v); + } + + public virtual void readBlob(byte[] v) + { + try + { + _buf.get(v); + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual byte[] readBlob(int sz) + { + byte[] v = new byte[sz]; + try + { + _buf.get(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeByte(byte v) + { + expand(1); + _buf.put(v); + } + + public virtual void writeByteSeq(byte[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length); + _buf.put(v); + } + } + + public virtual byte readByte() + { + try + { + return _buf.get(); + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual byte[] readByteSeq() + { + try + { + int sz = readSize(); + checkFixedSeq(sz, 1); + byte[] v = new byte[sz]; + _buf.get(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeBool(bool v) + { + expand(1); + _buf.put(v ? (byte)1 : (byte)0); + } + + public virtual void writeBoolSeq(bool[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length); + _buf.putBoolSeq(v); + } + } + + public virtual bool readBool() + { + try + { + return _buf.get() == 1; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual bool[] readBoolSeq() + { + try + { + int sz = readSize(); + checkFixedSeq(sz, 1); + bool[] v = new bool[sz]; + _buf.getBoolSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeShort(short v) + { + expand(2); + _buf.putShort(v); + } + + public virtual void writeShortSeq(short[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 2); + _buf.putShortSeq(v); + } + } + + public virtual short readShort() + { + try + { + return _buf.getShort(); + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual short[] readShortSeq() + { + try + { + int sz = readSize(); + checkFixedSeq(sz, 2); + short[] v = new short[sz]; + _buf.getShortSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeInt(int v) + { + expand(4); + _buf.putInt(v); + } + + public virtual void writeIntSeq(int[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 4); + _buf.putIntSeq(v); + } + } + + public virtual int readInt() + { + try + { + return _buf.getInt(); + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual int[] readIntSeq() + { + try + { + int sz = readSize(); + checkFixedSeq(sz, 4); + int[] v = new int[sz]; + _buf.getIntSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeLong(long v) + { + expand(8); + _buf.putLong(v); + } + + public virtual void writeLongSeq(long[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 8); + _buf.putLongSeq(v); + } + } + + public virtual long readLong() + { + try + { + return _buf.getLong(); + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual long[] readLongSeq() + { + try + { + int sz = readSize(); + checkFixedSeq(sz, 8); + long[] v = new long[sz]; + _buf.getLongSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeFloat(float v) + { + expand(4); + _buf.putFloat(v); + } + + public virtual void writeFloatSeq(float[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 4); + _buf.putFloatSeq(v); + } + } + + public virtual float readFloat() + { + try + { + return _buf.getFloat(); + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual float[] readFloatSeq() + { + try + { + int sz = readSize(); + checkFixedSeq(sz, 4); + float[] v = new float[sz]; + _buf.getFloatSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual void writeDouble(double v) + { + expand(8); + _buf.putDouble(v); + } + + public virtual void writeDoubleSeq(double[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + expand(v.Length * 8); + _buf.putDoubleSeq(v); + } + } + + public virtual double readDouble() + { + try + { + return _buf.getDouble(); + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + public virtual double[] readDoubleSeq() + { + try + { + int sz = readSize(); + checkFixedSeq(sz, 8); + double[] v = new double[sz]; + _buf.getDoubleSeq(v); + return v; + } + catch(InvalidOperationException ex) + { + throw new Ice.UnmarshalOutOfBoundsException(ex); + } + } + + private static System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true); - public virtual void writeString(string v) - { - if(v == null || v.Length == 0) - { - writeSize(0); - return; - } - byte[] arr = utf8.GetBytes(v); - writeSize(arr.Length); - expand(arr.Length); - _buf.put(arr); - } - - public virtual void writeStringSeq(string[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.Length); - for(int i = 0; i < v.Length; i++) - { - writeString(v[i]); - } - } - } - - public virtual string readString() - { - int len = readSize(); - - if(len == 0) - { - return ""; - } - + public virtual void writeString(string v) + { + if(v == null || v.Length == 0) + { + writeSize(0); + return; + } + byte[] arr = utf8.GetBytes(v); + writeSize(arr.Length); + expand(arr.Length); + _buf.put(arr); + } + + public virtual void writeStringSeq(string[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.Length); + for(int i = 0; i < v.Length; i++) + { + writeString(v[i]); + } + } + } + + public virtual string readString() + { + int len = readSize(); + + if(len == 0) + { + return ""; + } + try { // @@ -1067,467 +1067,467 @@ namespace IceInternal Debug.Assert(false); return ""; } - } - - public virtual string[] readStringSeq() - { - int sz = readSize(); - startSeq(sz, 1); - string[] v = new string[sz]; - for(int i = 0; i < sz; i++) - { - v[i] = readString(); - checkSeq(); - endElement(); - } - endSeq(sz); - return v; - } - - public virtual void writeProxy(Ice.ObjectPrx v) - { - instance_.proxyFactory().proxyToStream(v, this); - } - - public virtual Ice.ObjectPrx readProxy() - { - return instance_.proxyFactory().streamToProxy(this); - } - - public virtual void writeObject(Ice.Object v) - { - if(_writeEncapsStack == null) // Lazy initialization - { - _writeEncapsStack = _writeEncapsCache; - if(_writeEncapsStack != null) - { - _writeEncapsCache = _writeEncapsCache.next; - } - else - { - _writeEncapsStack = new WriteEncaps(); - } - } - - if(_writeEncapsStack.toBeMarshaledMap == null) // Lazy initialization - { - _writeEncapsStack.toBeMarshaledMap = new Hashtable(); - _writeEncapsStack.marshaledMap = new Hashtable(); - _writeEncapsStack.typeIdMap = new Hashtable(); - } - if(v != null) - { - // - // Look for this instance in the to-be-marshaled map. - // - object p = _writeEncapsStack.toBeMarshaledMap[v]; - if(p == null) - { - // - // Didn't find it, try the marshaled map next. - // - object q = _writeEncapsStack.marshaledMap[v]; - if(q == null) - { - // - // We haven't seen this instance previously, - // create a new index, and insert it into the - // to-be-marshaled map. - // - q = ++_writeEncapsStack.writeIndex; - _writeEncapsStack.toBeMarshaledMap[v] = q; - } - p = q; - } - writeInt(-((int)p)); - } - else - { - writeInt(0); // Write null reference - } - } - - public virtual void readObject(IceInternal.Patcher patcher) - { - Ice.Object v = null; - - if(_readEncapsStack == null) // Lazy initialization - { - _readEncapsStack = _readEncapsCache; - if(_readEncapsStack != null) - { - _readEncapsCache = _readEncapsCache.next; - } - else - { - _readEncapsStack = new ReadEncaps(); - } - } - - if(_readEncapsStack.patchMap == null) // Lazy initialization - { - _readEncapsStack.patchMap = new Hashtable(); - _readEncapsStack.unmarshaledMap = new Hashtable(); - _readEncapsStack.typeIdMap = new Hashtable(); - } - - int index = readInt(); - - if(index == 0) - { - patcher.patch(null); - return; - } - - if(index < 0 && patcher != null) - { - int i = -index; - IceUtil.LinkedList patchlist = (IceUtil.LinkedList)_readEncapsStack.patchMap[i]; - if(patchlist == null) - { - // - // We have no outstanding instances to be patched - // for this index, so make a new entry in the - // patch map. - // - patchlist = new IceUtil.LinkedList(); - _readEncapsStack.patchMap[i] = patchlist; - } - // - // Append a patcher for this instance and see if we - // can patch the instance. (The instance may have been - // unmarshaled previously.) - // - patchlist.Add(patcher); - patchReferences(null, i); - return; - } - - string mostDerivedId = readTypeId(); - string id = string.Copy(mostDerivedId); - - while(true) - { - // - // If we slice all the way down to Ice::Object, we throw - // because Ice::Object is abstract. - // - if(id == Ice.ObjectImpl.ice_staticId()) - { + } + + public virtual string[] readStringSeq() + { + int sz = readSize(); + startSeq(sz, 1); + string[] v = new string[sz]; + for(int i = 0; i < sz; i++) + { + v[i] = readString(); + checkSeq(); + endElement(); + } + endSeq(sz); + return v; + } + + public virtual void writeProxy(Ice.ObjectPrx v) + { + instance_.proxyFactory().proxyToStream(v, this); + } + + public virtual Ice.ObjectPrx readProxy() + { + return instance_.proxyFactory().streamToProxy(this); + } + + public virtual void writeObject(Ice.Object v) + { + if(_writeEncapsStack == null) // Lazy initialization + { + _writeEncapsStack = _writeEncapsCache; + if(_writeEncapsStack != null) + { + _writeEncapsCache = _writeEncapsCache.next; + } + else + { + _writeEncapsStack = new WriteEncaps(); + } + } + + if(_writeEncapsStack.toBeMarshaledMap == null) // Lazy initialization + { + _writeEncapsStack.toBeMarshaledMap = new Hashtable(); + _writeEncapsStack.marshaledMap = new Hashtable(); + _writeEncapsStack.typeIdMap = new Hashtable(); + } + if(v != null) + { + // + // Look for this instance in the to-be-marshaled map. + // + object p = _writeEncapsStack.toBeMarshaledMap[v]; + if(p == null) + { + // + // Didn't find it, try the marshaled map next. + // + object q = _writeEncapsStack.marshaledMap[v]; + if(q == null) + { + // + // We haven't seen this instance previously, + // create a new index, and insert it into the + // to-be-marshaled map. + // + q = ++_writeEncapsStack.writeIndex; + _writeEncapsStack.toBeMarshaledMap[v] = q; + } + p = q; + } + writeInt(-((int)p)); + } + else + { + writeInt(0); // Write null reference + } + } + + public virtual void readObject(IceInternal.Patcher patcher) + { + Ice.Object v = null; + + if(_readEncapsStack == null) // Lazy initialization + { + _readEncapsStack = _readEncapsCache; + if(_readEncapsStack != null) + { + _readEncapsCache = _readEncapsCache.next; + } + else + { + _readEncapsStack = new ReadEncaps(); + } + } + + if(_readEncapsStack.patchMap == null) // Lazy initialization + { + _readEncapsStack.patchMap = new Hashtable(); + _readEncapsStack.unmarshaledMap = new Hashtable(); + _readEncapsStack.typeIdMap = new Hashtable(); + } + + int index = readInt(); + + if(index == 0) + { + patcher.patch(null); + return; + } + + if(index < 0 && patcher != null) + { + int i = -index; + IceUtil.LinkedList patchlist = (IceUtil.LinkedList)_readEncapsStack.patchMap[i]; + if(patchlist == null) + { + // + // We have no outstanding instances to be patched + // for this index, so make a new entry in the + // patch map. + // + patchlist = new IceUtil.LinkedList(); + _readEncapsStack.patchMap[i] = patchlist; + } + // + // Append a patcher for this instance and see if we + // can patch the instance. (The instance may have been + // unmarshaled previously.) + // + patchlist.Add(patcher); + patchReferences(null, i); + return; + } + + string mostDerivedId = readTypeId(); + string id = string.Copy(mostDerivedId); + + while(true) + { + // + // If we slice all the way down to Ice::Object, we throw + // because Ice::Object is abstract. + // + if(id == Ice.ObjectImpl.ice_staticId()) + { Ice.NoObjectFactoryException ex = new Ice.NoObjectFactoryException("class sliced to Ice.Object, which is abstract"); ex.type = mostDerivedId; throw ex; - } - - // - // Try to find a factory registered for the specific - // type. - // - Ice.ObjectFactory userFactory = instance_.servantFactoryManager().find(id); - if(userFactory != null) - { - v = userFactory.create(id); - } - - // - // If that fails, invoke the default factory if one - // has been registered. - // - if(v == null) - { - userFactory = instance_.servantFactoryManager().find(""); - if(userFactory != null) - { - v = userFactory.create(id); - } - } - - // - // Last chance: check whether the class is - // non-abstract and dynamically instantiate it using - // reflection. - // - if(v == null) - { - userFactory = loadObjectFactory(id); - if(userFactory != null) - { - v = userFactory.create(id); - } - } - - if(v == null) - { - if(_sliceObjects) - { - // - // Performance sensitive, so we use lazy - // initialization for tracing. - // - if(_traceSlicing == -1) - { - _traceSlicing = instance_.traceLevels().slicing; - _slicingCat = instance_.traceLevels().slicingCat; - } - if(_traceSlicing > 0) - { - TraceUtil.traceSlicing("class", id, _slicingCat, instance_.initializationData().logger); - } - skipSlice(); // Slice off this derived part -- we don't understand it. - id = readTypeId(); // Read next id for next iteration. - continue; - } - else - { - Ice.NoObjectFactoryException ex = new Ice.NoObjectFactoryException(); - ex.type = id; - throw ex; - } - } - - int i = index; - _readEncapsStack.unmarshaledMap[i] = v; - - // - // Record each object instance so that - // readPendingObjects can invoke ice_postUnmarshal - // after all objects have been unmarshaled. - // - if(_objectList == null) - { - _objectList = new ArrayList(); - } - _objectList.Add(v); - - v.read__(this, false); - patchReferences(i, null); - return; - } - } - - public virtual void writeUserException(Ice.UserException v) - { - writeBool(v.usesClasses__()); - v.write__(this); - if(v.usesClasses__()) - { - writePendingObjects(); - } - } - - public virtual void throwException() - { - bool usesClasses = readBool(); - - string id = readString(); - - for(;;) - { - // - // Look for a factory for this ID. - // - UserExceptionFactory factory = getUserExceptionFactory(id); - - if(factory != null) - { - // - // Got factory -- get the factory to instantiate - // the exception, initialize the exception - // members, and throw the exception. - // - try - { - factory.createAndThrow(); - } - catch(Ice.UserException ex) - { - ex.read__(this, false); - if(usesClasses) - { - readPendingObjects(); - } - throw ex; - } - } - else - { - // - // Performance sensitive, so we use lazy - // initialization for tracing. - // - if(_traceSlicing == -1) - { - _traceSlicing = instance_.traceLevels().slicing; - _slicingCat = instance_.traceLevels().slicingCat; - } - if(_traceSlicing > 0) - { - TraceUtil.traceSlicing("exception", id, _slicingCat, instance_.initializationData().logger); - } - skipSlice(); // Slice off what we don't understand. - id = readString(); // Read type id for next slice. - } - } - - // - // The only way out of the loop above is to find an - // exception for which the receiver has a factory. If this - // does not happen, sender and receiver disagree about the - // Slice definitions they use. In that case, the receiver - // will eventually fail to read another type ID and throw - // a MarshalException. - // - } - - public virtual void writePendingObjects() - { - if(_writeEncapsStack != null && _writeEncapsStack.toBeMarshaledMap != null) - { - while(_writeEncapsStack.toBeMarshaledMap.Count > 0) - { - Hashtable savedMap = new Hashtable(_writeEncapsStack.toBeMarshaledMap); - writeSize(savedMap.Count); - foreach(DictionaryEntry e in savedMap) - { - // - // Add an instance from the old - // to-be-marshaled map to the marshaled map - // and then ask the instance to marshal - // itself. Any new class instances that are - // triggered by the classes marshaled are - // added to toBeMarshaledMap. - // - _writeEncapsStack.marshaledMap[e.Key] = e.Value; - writeInstance((Ice.Object)e.Key, (int)e.Value); - } - - // - // We have marshaled all the instances for this - // pass, substract what we have marshaled from the - // toBeMarshaledMap. - // - foreach(DictionaryEntry e in savedMap) - { - _writeEncapsStack.toBeMarshaledMap.Remove(e.Key); - } - } - } - writeSize(0); // Zero marker indicates end of sequence of sequences of instances. - } - - public virtual void readPendingObjects() - { - int num; - do - { - num = readSize(); - for(int k = num; k > 0; --k) - { - readObject(null); - } - } - while(num > 0); - - // - // Iterate over unmarshaledMap and invoke - // ice_postUnmarshal on each object. We must do this - // after all objects in this encapsulation have been - // unmarshaled in order to ensure that any object data - // members have been properly patched. - // - if(_objectList != null) - { - foreach(Ice.Object obj in _objectList) - { - try - { - obj.ice_postUnmarshal(); - } - catch(System.Exception ex) - { - instance_.initializationData().logger.warning("exception raised by ice_postUnmarshal::\n" + ex); - } - } - } - } - - public void - sliceObjects(bool b) - { - _sliceObjects = b; - } - - internal virtual void writeInstance(Ice.Object v, int index) - { - writeInt(index); - try - { - v.ice_preMarshal(); - } - catch(System.Exception ex) - { - instance_.initializationData().logger.warning("exception raised by ice_preMarshal::\n" + ex); - } - v.write__(this); - } - - internal virtual void patchReferences(object instanceIndex, object patchIndex) - { - // - // Called whenever we have unmarshaled a new instance or - // an index. The instanceIndex is the index of the - // instance just unmarshaled and patchIndex is the index - // just unmarshaled. (Exactly one of the two parameters - // must be null.) Patch any pointers in the patch map with - // the new address. - // - Debug.Assert( ((object)instanceIndex != null && (object)patchIndex == null) - || ((object)instanceIndex == null && (object)patchIndex != null)); - - IceUtil.LinkedList patchlist; - Ice.Object v; - if((object)instanceIndex != null) - { - // - // We have just unmarshaled an instance -- check if - // something needs patching for that instance. - // - patchlist = (IceUtil.LinkedList)_readEncapsStack.patchMap[instanceIndex]; - if(patchlist == null) - { - return; // We don't have anything to patch for the instance just unmarshaled. - } - v = (Ice.Object)_readEncapsStack.unmarshaledMap[instanceIndex]; - patchIndex = instanceIndex; - } - else - { - // - // We have just unmarshaled an index -- check if we - // have unmarshaled the instance for that index yet. - // - v = (Ice.Object)_readEncapsStack.unmarshaledMap[patchIndex]; - if(v == null) - { - return; // We haven't unmarshaled the instance for this index yet. - } - patchlist = (IceUtil.LinkedList)_readEncapsStack.patchMap[patchIndex]; - } - Debug.Assert(patchlist != null && patchlist.Count > 0); - Debug.Assert(v != null); - - // - // Patch all references that refer to the instance. - // - foreach(IceInternal.Patcher patcher in patchlist) - { - try - { - patcher.patch(v); - } - catch(InvalidCastException ex) - { + } + + // + // Try to find a factory registered for the specific + // type. + // + Ice.ObjectFactory userFactory = instance_.servantFactoryManager().find(id); + if(userFactory != null) + { + v = userFactory.create(id); + } + + // + // If that fails, invoke the default factory if one + // has been registered. + // + if(v == null) + { + userFactory = instance_.servantFactoryManager().find(""); + if(userFactory != null) + { + v = userFactory.create(id); + } + } + + // + // Last chance: check whether the class is + // non-abstract and dynamically instantiate it using + // reflection. + // + if(v == null) + { + userFactory = loadObjectFactory(id); + if(userFactory != null) + { + v = userFactory.create(id); + } + } + + if(v == null) + { + if(_sliceObjects) + { + // + // Performance sensitive, so we use lazy + // initialization for tracing. + // + if(_traceSlicing == -1) + { + _traceSlicing = instance_.traceLevels().slicing; + _slicingCat = instance_.traceLevels().slicingCat; + } + if(_traceSlicing > 0) + { + TraceUtil.traceSlicing("class", id, _slicingCat, instance_.initializationData().logger); + } + skipSlice(); // Slice off this derived part -- we don't understand it. + id = readTypeId(); // Read next id for next iteration. + continue; + } + else + { + Ice.NoObjectFactoryException ex = new Ice.NoObjectFactoryException(); + ex.type = id; + throw ex; + } + } + + int i = index; + _readEncapsStack.unmarshaledMap[i] = v; + + // + // Record each object instance so that + // readPendingObjects can invoke ice_postUnmarshal + // after all objects have been unmarshaled. + // + if(_objectList == null) + { + _objectList = new ArrayList(); + } + _objectList.Add(v); + + v.read__(this, false); + patchReferences(i, null); + return; + } + } + + public virtual void writeUserException(Ice.UserException v) + { + writeBool(v.usesClasses__()); + v.write__(this); + if(v.usesClasses__()) + { + writePendingObjects(); + } + } + + public virtual void throwException() + { + bool usesClasses = readBool(); + + string id = readString(); + + for(;;) + { + // + // Look for a factory for this ID. + // + UserExceptionFactory factory = getUserExceptionFactory(id); + + if(factory != null) + { + // + // Got factory -- get the factory to instantiate + // the exception, initialize the exception + // members, and throw the exception. + // + try + { + factory.createAndThrow(); + } + catch(Ice.UserException ex) + { + ex.read__(this, false); + if(usesClasses) + { + readPendingObjects(); + } + throw ex; + } + } + else + { + // + // Performance sensitive, so we use lazy + // initialization for tracing. + // + if(_traceSlicing == -1) + { + _traceSlicing = instance_.traceLevels().slicing; + _slicingCat = instance_.traceLevels().slicingCat; + } + if(_traceSlicing > 0) + { + TraceUtil.traceSlicing("exception", id, _slicingCat, instance_.initializationData().logger); + } + skipSlice(); // Slice off what we don't understand. + id = readString(); // Read type id for next slice. + } + } + + // + // The only way out of the loop above is to find an + // exception for which the receiver has a factory. If this + // does not happen, sender and receiver disagree about the + // Slice definitions they use. In that case, the receiver + // will eventually fail to read another type ID and throw + // a MarshalException. + // + } + + public virtual void writePendingObjects() + { + if(_writeEncapsStack != null && _writeEncapsStack.toBeMarshaledMap != null) + { + while(_writeEncapsStack.toBeMarshaledMap.Count > 0) + { + Hashtable savedMap = new Hashtable(_writeEncapsStack.toBeMarshaledMap); + writeSize(savedMap.Count); + foreach(DictionaryEntry e in savedMap) + { + // + // Add an instance from the old + // to-be-marshaled map to the marshaled map + // and then ask the instance to marshal + // itself. Any new class instances that are + // triggered by the classes marshaled are + // added to toBeMarshaledMap. + // + _writeEncapsStack.marshaledMap[e.Key] = e.Value; + writeInstance((Ice.Object)e.Key, (int)e.Value); + } + + // + // We have marshaled all the instances for this + // pass, substract what we have marshaled from the + // toBeMarshaledMap. + // + foreach(DictionaryEntry e in savedMap) + { + _writeEncapsStack.toBeMarshaledMap.Remove(e.Key); + } + } + } + writeSize(0); // Zero marker indicates end of sequence of sequences of instances. + } + + public virtual void readPendingObjects() + { + int num; + do + { + num = readSize(); + for(int k = num; k > 0; --k) + { + readObject(null); + } + } + while(num > 0); + + // + // Iterate over unmarshaledMap and invoke + // ice_postUnmarshal on each object. We must do this + // after all objects in this encapsulation have been + // unmarshaled in order to ensure that any object data + // members have been properly patched. + // + if(_objectList != null) + { + foreach(Ice.Object obj in _objectList) + { + try + { + obj.ice_postUnmarshal(); + } + catch(System.Exception ex) + { + instance_.initializationData().logger.warning("exception raised by ice_postUnmarshal::\n" + ex); + } + } + } + } + + public void + sliceObjects(bool b) + { + _sliceObjects = b; + } + + internal virtual void writeInstance(Ice.Object v, int index) + { + writeInt(index); + try + { + v.ice_preMarshal(); + } + catch(System.Exception ex) + { + instance_.initializationData().logger.warning("exception raised by ice_preMarshal::\n" + ex); + } + v.write__(this); + } + + internal virtual void patchReferences(object instanceIndex, object patchIndex) + { + // + // Called whenever we have unmarshaled a new instance or + // an index. The instanceIndex is the index of the + // instance just unmarshaled and patchIndex is the index + // just unmarshaled. (Exactly one of the two parameters + // must be null.) Patch any pointers in the patch map with + // the new address. + // + Debug.Assert( ((object)instanceIndex != null && (object)patchIndex == null) + || ((object)instanceIndex == null && (object)patchIndex != null)); + + IceUtil.LinkedList patchlist; + Ice.Object v; + if((object)instanceIndex != null) + { + // + // We have just unmarshaled an instance -- check if + // something needs patching for that instance. + // + patchlist = (IceUtil.LinkedList)_readEncapsStack.patchMap[instanceIndex]; + if(patchlist == null) + { + return; // We don't have anything to patch for the instance just unmarshaled. + } + v = (Ice.Object)_readEncapsStack.unmarshaledMap[instanceIndex]; + patchIndex = instanceIndex; + } + else + { + // + // We have just unmarshaled an index -- check if we + // have unmarshaled the instance for that index yet. + // + v = (Ice.Object)_readEncapsStack.unmarshaledMap[patchIndex]; + if(v == null) + { + return; // We haven't unmarshaled the instance for this index yet. + } + patchlist = (IceUtil.LinkedList)_readEncapsStack.patchMap[patchIndex]; + } + Debug.Assert(patchlist != null && patchlist.Count > 0); + Debug.Assert(v != null); + + // + // Patch all references that refer to the instance. + // + foreach(IceInternal.Patcher patcher in patchlist) + { + try + { + patcher.patch(v); + } + catch(InvalidCastException ex) + { // // TODO: Fix this (also for C++ and Java): // NoObjectFactoryException is misleading because @@ -1535,19 +1535,19 @@ namespace IceInternal // with what is expected. This really should be a // MarshalException. // - Ice.NoObjectFactoryException nof = new Ice.NoObjectFactoryException(ex); - nof.type = patcher.type(); - throw nof; - } - } - - // - // Clear out the patch map for that index -- there is - // nothing left to patch for that index for the time - // being. - // - _readEncapsStack.patchMap.Remove(patchIndex); - } + Ice.NoObjectFactoryException nof = new Ice.NoObjectFactoryException(ex); + nof.type = patcher.type(); + throw nof; + } + } + + // + // Clear out the patch map for that index -- there is + // nothing left to patch for that index for the time + // being. + // + _readEncapsStack.patchMap.Remove(patchIndex); + } static string getBZ2Error(int error) { @@ -1640,7 +1640,7 @@ namespace IceInternal byte[] compressed = new byte[compressedLen]; int rc = BZ2_bzBuffToBuffCompress(compressed, ref compressedLen, uncompressed, uncompressedLen, - compressionLevel, 0, 0); + compressionLevel, 0, 0); if(rc == BZ_OUTBUFF_FULL) { cstream = null; @@ -1652,11 +1652,11 @@ namespace IceInternal ex.reason = getBZ2Error(rc); throw ex; } - - // - // Don't bother if the compressed data is larger than the - // uncompressed data. - // + + // + // Don't bother if the compressed data is larger than the + // uncompressed data. + // if(compressedLen >= uncompressedLen) { return false; @@ -1726,328 +1726,328 @@ namespace IceInternal ucStream._buf.put(uncompressed, 0, uncompressedLen); return ucStream; } - - internal virtual int pos() - { - return _buf.position(); - } - - internal virtual void pos(int n) - { - _buf.position(n); - } - - public virtual int size() - { - return _limit; - } - - virtual internal bool isEmpty() - { - return _limit == 0; - } - - private void expand(int size) - { - if(_buf.position() == _limit) - { - int oldLimit = _limit; - _limit += size; - if(!_unlimited && _limit > _messageSizeMax) - { - throw new Ice.MemoryLimitException("Message larger than Ice.MessageSizeMax"); - } - if(_limit > _capacity) - { - int cap2 = _capacity << 1; - int newCapacity = cap2 > _limit ? cap2 : _limit; - _buf.limit(oldLimit); - int pos = _buf.position(); - reallocate(newCapacity); - _capacity = _buf.capacity(); - _buf.limit(_capacity); - _buf.position(pos); - } - } - } - - private sealed class DynamicObjectFactory : Ice.LocalObjectImpl, Ice.ObjectFactory - { - internal DynamicObjectFactory(Type c) - { - _class = c; - } - - public Ice.Object create(string type) - { - try - { - return (Ice.Object)AssemblyUtil.createInstance(_class); - } - catch(Exception ex) - { - throw new Ice.SyscallException(ex); - } - } - - public void destroy() - { - } - - private Type _class; - } - - private Ice.ObjectFactory loadObjectFactory(string id) - { - Ice.ObjectFactory factory = null; - - try - { - Type c = AssemblyUtil.findType(typeToClass(id)); - if(c == null) - { - return null; - } - // - // Ensure the class is instantiable. - // - if(!c.IsAbstract && !c.IsInterface) - { - Ice.ObjectFactory dynamicFactory = new DynamicObjectFactory(c); - // - // We will try to install the dynamic factory, but - // another thread may install a factory first. - // - while(factory == null) - { - try - { - instance_.servantFactoryManager().add(dynamicFactory, id); - factory = dynamicFactory; - } - catch(Ice.AlreadyRegisteredException) - { - // - // Another thread already installed the - // factory, so try to obtain it. It's - // possible (but unlikely) that the - // factory will have already been removed, - // in which case the return value will be - // null and the while loop will attempt to - // install the dynamic factory again. - // - factory = instance_.servantFactoryManager().find(id); - } - } - } - } - catch(Exception ex) - { - Ice.NoObjectFactoryException e = new Ice.NoObjectFactoryException(ex); - e.type = id; - throw e; - } - - return factory; - } - - private sealed class DynamicUserExceptionFactory : Ice.LocalObjectImpl, UserExceptionFactory - { - internal DynamicUserExceptionFactory(Type c) - { - _class = c; - } - - public void createAndThrow() - { - try - { - throw (Ice.UserException)AssemblyUtil.createInstance(_class); - } - catch(Ice.UserException) - { - throw; - } - catch(Exception ex) - { - throw new Ice.SyscallException(ex); - } - } - - public void destroy() - { - } - - private Type _class; - } - - private UserExceptionFactory getUserExceptionFactory(string id) - { - UserExceptionFactory factory = null; - - lock(_exceptionFactories) - { - factory = (UserExceptionFactory)_exceptionFactories[id]; - if(factory == null) - { - try - { - Type c = AssemblyUtil.findType(typeToClass(id)); - if(c == null) - { - return null; - } - // - // Ensure the class is instantiable. - // - Debug.Assert(!c.IsAbstract && !c.IsInterface); - factory = new DynamicUserExceptionFactory(c); - _exceptionFactories[id] = factory; - } - catch(Exception ex) - { - throw new Ice.UnknownUserException(ex); - } - } - } - return factory; - } - - private static string typeToClass(string id) - { - if(!id.StartsWith("::")) - { - throw new Ice.MarshalException("type ID does not start with `::'"); - } - return id.Substring(2).Replace("::", "."); - } + + internal virtual int pos() + { + return _buf.position(); + } + + internal virtual void pos(int n) + { + _buf.position(n); + } + + public virtual int size() + { + return _limit; + } + + virtual internal bool isEmpty() + { + return _limit == 0; + } + + private void expand(int size) + { + if(_buf.position() == _limit) + { + int oldLimit = _limit; + _limit += size; + if(!_unlimited && _limit > _messageSizeMax) + { + throw new Ice.MemoryLimitException("Message larger than Ice.MessageSizeMax"); + } + if(_limit > _capacity) + { + int cap2 = _capacity << 1; + int newCapacity = cap2 > _limit ? cap2 : _limit; + _buf.limit(oldLimit); + int pos = _buf.position(); + reallocate(newCapacity); + _capacity = _buf.capacity(); + _buf.limit(_capacity); + _buf.position(pos); + } + } + } + + private sealed class DynamicObjectFactory : Ice.LocalObjectImpl, Ice.ObjectFactory + { + internal DynamicObjectFactory(Type c) + { + _class = c; + } + + public Ice.Object create(string type) + { + try + { + return (Ice.Object)AssemblyUtil.createInstance(_class); + } + catch(Exception ex) + { + throw new Ice.SyscallException(ex); + } + } + + public void destroy() + { + } + + private Type _class; + } + + private Ice.ObjectFactory loadObjectFactory(string id) + { + Ice.ObjectFactory factory = null; + + try + { + Type c = AssemblyUtil.findType(typeToClass(id)); + if(c == null) + { + return null; + } + // + // Ensure the class is instantiable. + // + if(!c.IsAbstract && !c.IsInterface) + { + Ice.ObjectFactory dynamicFactory = new DynamicObjectFactory(c); + // + // We will try to install the dynamic factory, but + // another thread may install a factory first. + // + while(factory == null) + { + try + { + instance_.servantFactoryManager().add(dynamicFactory, id); + factory = dynamicFactory; + } + catch(Ice.AlreadyRegisteredException) + { + // + // Another thread already installed the + // factory, so try to obtain it. It's + // possible (but unlikely) that the + // factory will have already been removed, + // in which case the return value will be + // null and the while loop will attempt to + // install the dynamic factory again. + // + factory = instance_.servantFactoryManager().find(id); + } + } + } + } + catch(Exception ex) + { + Ice.NoObjectFactoryException e = new Ice.NoObjectFactoryException(ex); + e.type = id; + throw e; + } + + return factory; + } + + private sealed class DynamicUserExceptionFactory : Ice.LocalObjectImpl, UserExceptionFactory + { + internal DynamicUserExceptionFactory(Type c) + { + _class = c; + } + + public void createAndThrow() + { + try + { + throw (Ice.UserException)AssemblyUtil.createInstance(_class); + } + catch(Ice.UserException) + { + throw; + } + catch(Exception ex) + { + throw new Ice.SyscallException(ex); + } + } + + public void destroy() + { + } + + private Type _class; + } + + private UserExceptionFactory getUserExceptionFactory(string id) + { + UserExceptionFactory factory = null; + + lock(_exceptionFactories) + { + factory = (UserExceptionFactory)_exceptionFactories[id]; + if(factory == null) + { + try + { + Type c = AssemblyUtil.findType(typeToClass(id)); + if(c == null) + { + return null; + } + // + // Ensure the class is instantiable. + // + Debug.Assert(!c.IsAbstract && !c.IsInterface); + factory = new DynamicUserExceptionFactory(c); + _exceptionFactories[id] = factory; + } + catch(Exception ex) + { + throw new Ice.UnknownUserException(ex); + } + } + } + return factory; + } + + private static string typeToClass(string id) + { + if(!id.StartsWith("::")) + { + throw new Ice.MarshalException("type ID does not start with `::'"); + } + return id.Substring(2).Replace("::", "."); + } private void allocate(int size) { ByteBuffer buf = null; - try - { - buf = ByteBuffer.allocate(size); - } - catch(System.OutOfMemoryException ex) - { - Ice.MarshalException e = new Ice.MarshalException(ex); - e.reason = "OutOfMemoryException occurred while allocating a ByteBuffer"; - throw e; - } - buf.order(ByteBuffer.ByteOrder.LITTLE_ENDIAN); + try + { + buf = ByteBuffer.allocate(size); + } + catch(System.OutOfMemoryException ex) + { + Ice.MarshalException e = new Ice.MarshalException(ex); + e.reason = "OutOfMemoryException occurred while allocating a ByteBuffer"; + throw e; + } + buf.order(ByteBuffer.ByteOrder.LITTLE_ENDIAN); _buf = buf; } - private void reallocate(int size) - { - // - // Limit the buffer size to MessageSizeMax - // - if(!_unlimited) - { - size = size > _messageSizeMax ? _messageSizeMax : size; - } - - ByteBuffer old = _buf; - Debug.Assert(old != null); - - allocate(size); - Debug.Assert(_buf != null); - - old.position(0); - _buf.put(old); - } - - private IceInternal.Instance instance_; - private ByteBuffer _buf; - private int _capacity; // Cache capacity to avoid excessive method calls. - private int _limit; // Cache limit to avoid excessive method calls. - private byte[] _stringBytes; // Reusable array for reading strings. - - private sealed class ReadEncaps - { - internal int start; - internal int sz; - - internal byte encodingMajor; - internal byte encodingMinor; - - internal Hashtable patchMap; - internal Hashtable unmarshaledMap; - internal int typeIdIndex; - internal Hashtable typeIdMap; - internal ReadEncaps next; - - internal void reset() - { - if(patchMap != null) - { - patchMap.Clear(); - unmarshaledMap.Clear(); - typeIdIndex = 0; - typeIdMap.Clear(); - } - } - } - - private sealed class WriteEncaps - { - internal int start; - - internal int writeIndex; - internal Hashtable toBeMarshaledMap; - internal Hashtable marshaledMap; - internal int typeIdIndex; - internal Hashtable typeIdMap; - internal WriteEncaps next; - - internal void reset() - { - if(toBeMarshaledMap != null) - { - writeIndex = 0; - toBeMarshaledMap.Clear(); - marshaledMap.Clear(); - typeIdIndex = 0; - typeIdMap.Clear(); - } - } - } - - private ReadEncaps _readEncapsStack; - private WriteEncaps _writeEncapsStack; - private ReadEncaps _readEncapsCache; - private WriteEncaps _writeEncapsCache; - - private int _readSlice; - private int _writeSlice; - - private int _traceSlicing; - private string _slicingCat; - - private bool _sliceObjects; - - private int _messageSizeMax; - private bool _unlimited; - - private sealed class SeqData - { - public SeqData(int numElements, int minSize) - { - this.numElements = numElements; - this.minSize = minSize; - } - - public int numElements; - public int minSize; - public SeqData previous; - } - SeqData _seqDataStack; - - private ArrayList _objectList; - - private static Hashtable _exceptionFactories = new Hashtable(); // <type name, factory> pairs. + private void reallocate(int size) + { + // + // Limit the buffer size to MessageSizeMax + // + if(!_unlimited) + { + size = size > _messageSizeMax ? _messageSizeMax : size; + } + + ByteBuffer old = _buf; + Debug.Assert(old != null); + + allocate(size); + Debug.Assert(_buf != null); + + old.position(0); + _buf.put(old); + } + + private IceInternal.Instance instance_; + private ByteBuffer _buf; + private int _capacity; // Cache capacity to avoid excessive method calls. + private int _limit; // Cache limit to avoid excessive method calls. + private byte[] _stringBytes; // Reusable array for reading strings. + + private sealed class ReadEncaps + { + internal int start; + internal int sz; + + internal byte encodingMajor; + internal byte encodingMinor; + + internal Hashtable patchMap; + internal Hashtable unmarshaledMap; + internal int typeIdIndex; + internal Hashtable typeIdMap; + internal ReadEncaps next; + + internal void reset() + { + if(patchMap != null) + { + patchMap.Clear(); + unmarshaledMap.Clear(); + typeIdIndex = 0; + typeIdMap.Clear(); + } + } + } + + private sealed class WriteEncaps + { + internal int start; + + internal int writeIndex; + internal Hashtable toBeMarshaledMap; + internal Hashtable marshaledMap; + internal int typeIdIndex; + internal Hashtable typeIdMap; + internal WriteEncaps next; + + internal void reset() + { + if(toBeMarshaledMap != null) + { + writeIndex = 0; + toBeMarshaledMap.Clear(); + marshaledMap.Clear(); + typeIdIndex = 0; + typeIdMap.Clear(); + } + } + } + + private ReadEncaps _readEncapsStack; + private WriteEncaps _writeEncapsStack; + private ReadEncaps _readEncapsCache; + private WriteEncaps _writeEncapsCache; + + private int _readSlice; + private int _writeSlice; + + private int _traceSlicing; + private string _slicingCat; + + private bool _sliceObjects; + + private int _messageSizeMax; + private bool _unlimited; + + private sealed class SeqData + { + public SeqData(int numElements, int minSize) + { + this.numElements = numElements; + this.minSize = minSize; + } + + public int numElements; + public int minSize; + public SeqData previous; + } + SeqData _seqDataStack; + + private ArrayList _objectList; + + private static Hashtable _exceptionFactories = new Hashtable(); // <type name, factory> pairs. private static bool _bzlibInstalled; diff --git a/cs/src/Ice/ByteBuffer.cs b/cs/src/Ice/ByteBuffer.cs index 05183efe0df..e711da08742 100755 --- a/cs/src/Ice/ByteBuffer.cs +++ b/cs/src/Ice/ByteBuffer.cs @@ -14,714 +14,714 @@ namespace IceInternal public class ByteBuffer { - public ByteBuffer() - { - _order = ByteOrder.BIG_ENDIAN; - } - - public enum ByteOrder { BIG_ENDIAN, LITTLE_ENDIAN }; - - public static ByteOrder nativeOrder() - { - return NO._o; - } - - public ByteOrder order() - { - return _order; - } - - public ByteBuffer order(ByteOrder bo) - { - _order = bo; - return this; - } - - public static ByteBuffer allocate(int capacity) - { - if(capacity < 0) - { - throw new ArgumentOutOfRangeException("capacity", capacity, "capacity must be non-negative"); - } - ByteBuffer ret = new ByteBuffer(); - ret._position = 0; - ret._limit = capacity; - ret._capacity = capacity; - ret._bytes = new byte[capacity]; - return ret; - } - - public int position() - { - return _position; - } - - public ByteBuffer position(int pos) - { - if(pos < 0) - { - throw new ArgumentOutOfRangeException("pos", pos, "position must be non-negative"); - } - if(pos > _limit) - { - throw new ArgumentOutOfRangeException("pos", pos, "position must be less than limit"); - } - _position = pos; - return this; - } - - public int limit() - { - return _limit; - } - - public ByteBuffer limit(int newLimit) - { - if(newLimit < 0) - { - throw new ArgumentOutOfRangeException("newLimit", newLimit, "limit must be non-negative"); - } - if(newLimit > _capacity) - { - throw new ArgumentOutOfRangeException("newLimit", newLimit, "limit must be less than capacity"); - } - _limit = newLimit; - return this; - } - - public void clear() - { - _position = 0; - _limit = _capacity; - } - - public int remaining() - { - return _limit - _position; - } - - public bool hasRemaining() - { - return _position < _limit; - } - - public int capacity() - { - return _capacity; - } - - public byte[] toArray() - { - int len = remaining(); - byte[] rc = new byte[len]; - Buffer.BlockCopy(_bytes, 0, rc, 0, len); - return rc; - } - - public ByteBuffer put(ByteBuffer buf) - { - int len = buf.remaining(); - checkOverflow(len); - Buffer.BlockCopy(buf._bytes, buf._position, _bytes, _position, len); - _position += len; - return this; - } - - public byte get() - { - checkUnderflow(1); - return Buffer.GetByte(_bytes, _position++); - } - - public ByteBuffer get(byte[] b) - { - return get(b, 0, Buffer.ByteLength(b)); - } - - public ByteBuffer get(byte[] b, int offset, int length) - { - if(offset < 0) - { - throw new ArgumentOutOfRangeException("offset", offset, "offset must be non-negative"); - } - if(offset + length > Buffer.ByteLength(b)) - { - throw new ArgumentOutOfRangeException("length", length, - "insufficient room beyond given offset in destination array"); - } - checkUnderflow(length); - Buffer.BlockCopy(_bytes, _position, b, offset, length); - _position += length; - return this; - } - - public ByteBuffer put(byte b) - { - checkOverflow(1); - Buffer.SetByte(_bytes, _position++, b); - return this; - } - - public ByteBuffer put(byte[] b) - { - return put(b, 0, Buffer.ByteLength(b)); - } - - public ByteBuffer put(byte[]b, int offset, int length) - { - if(offset < 0) - { - throw new ArgumentOutOfRangeException("offset", offset, "offset must be non-negative"); - } - if(offset + length > Buffer.ByteLength(b)) - { - throw new ArgumentOutOfRangeException("length", length, - "insufficient data beyond given offset in source array"); - } - checkOverflow(length); - Buffer.BlockCopy(b, offset, _bytes, _position, length); - _position += length; - return this; - } - - public bool getBool() - { - return get() == 1; - } - - public void getBoolSeq(bool[] seq) - { - int len = Buffer.ByteLength(seq); - checkUnderflow(len); - Buffer.BlockCopy(_bytes, _position, seq, 0, len); - _position += len; - } - - public ByteBuffer putBool(bool b) - { - return put(b ? (byte)1 : (byte)0); - } - - public ByteBuffer putBoolSeq(bool[] seq) - { - int len = Buffer.ByteLength(seq); - checkOverflow(len); - Buffer.BlockCopy(seq, 0, _bytes, _position, len); - _position += len; - return this; - } - - public unsafe short getShort() - { - checkUnderflow(2); - short ret; - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - ret = *((short*)p); - } - } - else - { - byte* p = (byte*)&ret; - *p++ = Buffer.GetByte(_bytes, _position + 1); - *p = Buffer.GetByte(_bytes, _position); - } - _position += 2; - return ret; - } - - public unsafe void getShortSeq(short[] seq) - { - int len = Buffer.ByteLength(seq); - checkUnderflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(_bytes, _position, seq, 0, len); - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - fixed(short* p = &seq[i]) - { - int index = i * 2; - byte* q = (byte*)p; - *q++ = Buffer.GetByte(_bytes, _position + index + 1); - *q = Buffer.GetByte(_bytes, _position + index); - } - }; - } - _position += len; - } - - public unsafe ByteBuffer putShort(short val) - { - checkOverflow(2); - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - *((short*)p) = val; - } - _position += 2; - } - else - { - byte* p = (byte*)&val; - Buffer.SetByte(_bytes, _position++, *(p + 1)); - Buffer.SetByte(_bytes, _position++, *p); - } - return this; - } - - public unsafe ByteBuffer putShortSeq(short[] seq) - { - int len = Buffer.ByteLength(seq); - checkOverflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(seq, 0, _bytes, _position, len); - _position += len; - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - int index = i * 2; - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); - } - } - return this; - } - - public unsafe int getInt() - { - checkUnderflow(4); - int ret; - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - ret = *((int*)p); - } - } - else - { - byte* p = (byte*)&ret; - *p++ = Buffer.GetByte(_bytes, _position + 3); - *p++ = Buffer.GetByte(_bytes, _position + 2); - *p++ = Buffer.GetByte(_bytes, _position + 1); - *p = Buffer.GetByte(_bytes, _position); - } - _position += 4; - return ret; - } - - public unsafe void getIntSeq(int[] seq) - { - int len = Buffer.ByteLength(seq); - checkUnderflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(_bytes, _position, seq, 0, len); - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - fixed(int* p = &seq[i]) - { - int index = i * 4; - byte* q = (byte*)p; - *q++ = Buffer.GetByte(_bytes, _position + index + 3); - *q++ = Buffer.GetByte(_bytes, _position + index + 2); - *q++ = Buffer.GetByte(_bytes, _position + index + 1); - *q = Buffer.GetByte(_bytes, _position + index); - } - } - } - _position += len; - } - - public ByteBuffer putInt(int val) - { - putInt(_position, val); - _position += 4; - return this; - } - - public unsafe ByteBuffer putInt(int pos, int val) - { - if(pos < 0) - { - throw new ArgumentOutOfRangeException("pos", pos, "position must be non-negative"); - } - if(pos + 4 > _limit) - { - throw new ArgumentOutOfRangeException("pos", pos, "position must be less than limit - 4"); - } - if(NO._o == _order) - { - fixed(byte* p = &_bytes[pos]) - { - *((int*)p) = val; - } - } - else - { - byte* p = (byte*)&val; - Buffer.SetByte(_bytes, pos, *(p + 3)); - Buffer.SetByte(_bytes, pos + 1, *(p + 2)); - Buffer.SetByte(_bytes, pos + 2, *(p + 1)); - Buffer.SetByte(_bytes, pos + 3, *p); - } - return this; - } - - public ByteBuffer putIntSeq(int[] seq) - { - int len = Buffer.ByteLength(seq); - checkOverflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(seq, 0, _bytes, _position, len); - _position += len; - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - int index = i * 4; - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); - } - } - return this; - } - - public unsafe long getLong() - { - checkUnderflow(8); - long ret; - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - ret = *((long*)p); - } - } - else - { - byte* p = (byte*)&ret; - *p++ = Buffer.GetByte(_bytes, _position + 7); - *p++ = Buffer.GetByte(_bytes, _position + 6); - *p++ = Buffer.GetByte(_bytes, _position + 5); - *p++ = Buffer.GetByte(_bytes, _position + 4); - *p++ = Buffer.GetByte(_bytes, _position + 3); - *p++ = Buffer.GetByte(_bytes, _position + 2); - *p++ = Buffer.GetByte(_bytes, _position + 1); - *p = Buffer.GetByte(_bytes, _position); - } - _position += 8; - return ret; - } - - public unsafe void getLongSeq(long[] seq) - { - int len = Buffer.ByteLength(seq); - checkUnderflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(_bytes, _position, seq, 0, len); - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - fixed(long* p = &seq[i]) - { - int index = i * 8; - byte* q = (byte*)p; - *q++ = Buffer.GetByte(_bytes, _position + index + 7); - *q++ = Buffer.GetByte(_bytes, _position + index + 6); - *q++ = Buffer.GetByte(_bytes, _position + index + 5); - *q++ = Buffer.GetByte(_bytes, _position + index + 4); - *q++ = Buffer.GetByte(_bytes, _position + index + 3); - *q++ = Buffer.GetByte(_bytes, _position + index + 2); - *q++ = Buffer.GetByte(_bytes, _position + index + 1); - *q = Buffer.GetByte(_bytes, _position + index); - } - } - } - _position += len; - } - - public unsafe ByteBuffer putLong(long val) - { - checkOverflow(8); - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - *((long*)p) = val; - } - _position += 8; - } - else - { - byte* p = (byte*)&val; - Buffer.SetByte(_bytes, _position++, *(p + 7)); - Buffer.SetByte(_bytes, _position++, *(p + 6)); - Buffer.SetByte(_bytes, _position++, *(p + 5)); - Buffer.SetByte(_bytes, _position++, *(p + 4)); - Buffer.SetByte(_bytes, _position++, *(p + 3)); - Buffer.SetByte(_bytes, _position++, *(p + 2)); - Buffer.SetByte(_bytes, _position++, *(p + 1)); - Buffer.SetByte(_bytes, _position++, *p); - } - return this; - } - - public ByteBuffer putLongSeq(long[] seq) - { - int len = Buffer.ByteLength(seq); - checkOverflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(seq, 0, _bytes, _position, len); - _position += len; - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - int index = i * 8; - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 7)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 6)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 5)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 4)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); - } - } - return this; - } - - public unsafe float getFloat() - { - checkUnderflow(4); - float ret; - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - ret = *((float*)p); - } - } - else - { - byte* p = (byte*)&ret; - *p++ = Buffer.GetByte(_bytes, _position + 3); - *p++ = Buffer.GetByte(_bytes, _position + 2); - *p++ = Buffer.GetByte(_bytes, _position + 1); - *p = Buffer.GetByte(_bytes, _position); - } - _position += 4; - return ret; - } - - public unsafe void getFloatSeq(float[] seq) - { - int len = Buffer.ByteLength(seq); - checkUnderflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(_bytes, _position, seq, 0, len); - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - fixed(float* p = &seq[i]) - { - int index = i * 4; - byte* q = (byte*)p; - *q++ = Buffer.GetByte(_bytes, _position + index + 3); - *q++ = Buffer.GetByte(_bytes, _position + index + 2); - *q++ = Buffer.GetByte(_bytes, _position + index + 1); - *q = Buffer.GetByte(_bytes, _position + index); - } - } - } - _position += len; - } - - public unsafe ByteBuffer putFloat(float val) - { - checkOverflow(4); - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - *((float*)p) = val; - } - _position += 4; - } - else - { - byte* p = (byte*)&val; - Buffer.SetByte(_bytes, _position++, *(p + 3)); - Buffer.SetByte(_bytes, _position++, *(p + 2)); - Buffer.SetByte(_bytes, _position++, *(p + 1)); - Buffer.SetByte(_bytes, _position++, *p); - } - return this; - } - - public ByteBuffer putFloatSeq(float[] seq) - { - int len = Buffer.ByteLength(seq); - checkOverflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(seq, 0, _bytes, _position, len); - _position += len; - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - int index = i * 4; - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); - } - } - return this; - } - - public unsafe double getDouble() - { - checkUnderflow(8); - double ret; - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - ret = *((double*)p); - } - } - else - { - byte* p = (byte*)&ret; - *p++ = Buffer.GetByte(_bytes, _position + 7); - *p++ = Buffer.GetByte(_bytes, _position + 6); - *p++ = Buffer.GetByte(_bytes, _position + 5); - *p++ = Buffer.GetByte(_bytes, _position + 4); - *p++ = Buffer.GetByte(_bytes, _position + 3); - *p++ = Buffer.GetByte(_bytes, _position + 2); - *p++ = Buffer.GetByte(_bytes, _position + 1); - *p = Buffer.GetByte(_bytes, _position); - } - _position += 8; - return ret; - } - - public unsafe void getDoubleSeq(double[] seq) - { - int len = Buffer.ByteLength(seq); - checkUnderflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(_bytes, _position, seq, 0, len); - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - fixed(double* p = &seq[i]) - { - int index = i * 8; - byte* q = (byte*)p; - *q++ = Buffer.GetByte(_bytes, _position + index + 7); - *q++ = Buffer.GetByte(_bytes, _position + index + 6); - *q++ = Buffer.GetByte(_bytes, _position + index + 5); - *q++ = Buffer.GetByte(_bytes, _position + index + 4); - *q++ = Buffer.GetByte(_bytes, _position + index + 3); - *q++ = Buffer.GetByte(_bytes, _position + index + 2); - *q++ = Buffer.GetByte(_bytes, _position + index + 1); - *q = Buffer.GetByte(_bytes, _position + index); - } - } - } - _position += len; - } - - public unsafe ByteBuffer putDouble(double val) - { - checkOverflow(8); - if(NO._o == _order) - { - fixed(byte* p = &_bytes[_position]) - { - *((double*)p) = val; - } - _position += 8; - } - else - { - byte* p = (byte*)&val; - Buffer.SetByte(_bytes, _position++, *(p + 7)); - Buffer.SetByte(_bytes, _position++, *(p + 6)); - Buffer.SetByte(_bytes, _position++, *(p + 5)); - Buffer.SetByte(_bytes, _position++, *(p + 4)); - Buffer.SetByte(_bytes, _position++, *(p + 3)); - Buffer.SetByte(_bytes, _position++, *(p + 2)); - Buffer.SetByte(_bytes, _position++, *(p + 1)); - Buffer.SetByte(_bytes, _position++, *p); - } - return this; - } - - public ByteBuffer putDoubleSeq(double[] seq) - { - int len = Buffer.ByteLength(seq); - checkOverflow(len); - if(NO._o == _order) - { - Buffer.BlockCopy(seq, 0, _bytes, _position, len); - _position += len; - } - else - { - for(int i = 0; i < seq.Length; ++i) - { - int index = i * 8; - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 7)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 6)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 5)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 4)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); - Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); - } - } - return this; - } - - public byte[] rawBytes() - { - return _bytes; - } + public ByteBuffer() + { + _order = ByteOrder.BIG_ENDIAN; + } + + public enum ByteOrder { BIG_ENDIAN, LITTLE_ENDIAN }; + + public static ByteOrder nativeOrder() + { + return NO._o; + } + + public ByteOrder order() + { + return _order; + } + + public ByteBuffer order(ByteOrder bo) + { + _order = bo; + return this; + } + + public static ByteBuffer allocate(int capacity) + { + if(capacity < 0) + { + throw new ArgumentOutOfRangeException("capacity", capacity, "capacity must be non-negative"); + } + ByteBuffer ret = new ByteBuffer(); + ret._position = 0; + ret._limit = capacity; + ret._capacity = capacity; + ret._bytes = new byte[capacity]; + return ret; + } + + public int position() + { + return _position; + } + + public ByteBuffer position(int pos) + { + if(pos < 0) + { + throw new ArgumentOutOfRangeException("pos", pos, "position must be non-negative"); + } + if(pos > _limit) + { + throw new ArgumentOutOfRangeException("pos", pos, "position must be less than limit"); + } + _position = pos; + return this; + } + + public int limit() + { + return _limit; + } + + public ByteBuffer limit(int newLimit) + { + if(newLimit < 0) + { + throw new ArgumentOutOfRangeException("newLimit", newLimit, "limit must be non-negative"); + } + if(newLimit > _capacity) + { + throw new ArgumentOutOfRangeException("newLimit", newLimit, "limit must be less than capacity"); + } + _limit = newLimit; + return this; + } + + public void clear() + { + _position = 0; + _limit = _capacity; + } + + public int remaining() + { + return _limit - _position; + } + + public bool hasRemaining() + { + return _position < _limit; + } + + public int capacity() + { + return _capacity; + } + + public byte[] toArray() + { + int len = remaining(); + byte[] rc = new byte[len]; + Buffer.BlockCopy(_bytes, 0, rc, 0, len); + return rc; + } + + public ByteBuffer put(ByteBuffer buf) + { + int len = buf.remaining(); + checkOverflow(len); + Buffer.BlockCopy(buf._bytes, buf._position, _bytes, _position, len); + _position += len; + return this; + } + + public byte get() + { + checkUnderflow(1); + return Buffer.GetByte(_bytes, _position++); + } + + public ByteBuffer get(byte[] b) + { + return get(b, 0, Buffer.ByteLength(b)); + } + + public ByteBuffer get(byte[] b, int offset, int length) + { + if(offset < 0) + { + throw new ArgumentOutOfRangeException("offset", offset, "offset must be non-negative"); + } + if(offset + length > Buffer.ByteLength(b)) + { + throw new ArgumentOutOfRangeException("length", length, + "insufficient room beyond given offset in destination array"); + } + checkUnderflow(length); + Buffer.BlockCopy(_bytes, _position, b, offset, length); + _position += length; + return this; + } + + public ByteBuffer put(byte b) + { + checkOverflow(1); + Buffer.SetByte(_bytes, _position++, b); + return this; + } + + public ByteBuffer put(byte[] b) + { + return put(b, 0, Buffer.ByteLength(b)); + } + + public ByteBuffer put(byte[]b, int offset, int length) + { + if(offset < 0) + { + throw new ArgumentOutOfRangeException("offset", offset, "offset must be non-negative"); + } + if(offset + length > Buffer.ByteLength(b)) + { + throw new ArgumentOutOfRangeException("length", length, + "insufficient data beyond given offset in source array"); + } + checkOverflow(length); + Buffer.BlockCopy(b, offset, _bytes, _position, length); + _position += length; + return this; + } + + public bool getBool() + { + return get() == 1; + } + + public void getBoolSeq(bool[] seq) + { + int len = Buffer.ByteLength(seq); + checkUnderflow(len); + Buffer.BlockCopy(_bytes, _position, seq, 0, len); + _position += len; + } + + public ByteBuffer putBool(bool b) + { + return put(b ? (byte)1 : (byte)0); + } + + public ByteBuffer putBoolSeq(bool[] seq) + { + int len = Buffer.ByteLength(seq); + checkOverflow(len); + Buffer.BlockCopy(seq, 0, _bytes, _position, len); + _position += len; + return this; + } + + public unsafe short getShort() + { + checkUnderflow(2); + short ret; + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + ret = *((short*)p); + } + } + else + { + byte* p = (byte*)&ret; + *p++ = Buffer.GetByte(_bytes, _position + 1); + *p = Buffer.GetByte(_bytes, _position); + } + _position += 2; + return ret; + } + + public unsafe void getShortSeq(short[] seq) + { + int len = Buffer.ByteLength(seq); + checkUnderflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(_bytes, _position, seq, 0, len); + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + fixed(short* p = &seq[i]) + { + int index = i * 2; + byte* q = (byte*)p; + *q++ = Buffer.GetByte(_bytes, _position + index + 1); + *q = Buffer.GetByte(_bytes, _position + index); + } + }; + } + _position += len; + } + + public unsafe ByteBuffer putShort(short val) + { + checkOverflow(2); + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + *((short*)p) = val; + } + _position += 2; + } + else + { + byte* p = (byte*)&val; + Buffer.SetByte(_bytes, _position++, *(p + 1)); + Buffer.SetByte(_bytes, _position++, *p); + } + return this; + } + + public unsafe ByteBuffer putShortSeq(short[] seq) + { + int len = Buffer.ByteLength(seq); + checkOverflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(seq, 0, _bytes, _position, len); + _position += len; + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + int index = i * 2; + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); + } + } + return this; + } + + public unsafe int getInt() + { + checkUnderflow(4); + int ret; + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + ret = *((int*)p); + } + } + else + { + byte* p = (byte*)&ret; + *p++ = Buffer.GetByte(_bytes, _position + 3); + *p++ = Buffer.GetByte(_bytes, _position + 2); + *p++ = Buffer.GetByte(_bytes, _position + 1); + *p = Buffer.GetByte(_bytes, _position); + } + _position += 4; + return ret; + } + + public unsafe void getIntSeq(int[] seq) + { + int len = Buffer.ByteLength(seq); + checkUnderflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(_bytes, _position, seq, 0, len); + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + fixed(int* p = &seq[i]) + { + int index = i * 4; + byte* q = (byte*)p; + *q++ = Buffer.GetByte(_bytes, _position + index + 3); + *q++ = Buffer.GetByte(_bytes, _position + index + 2); + *q++ = Buffer.GetByte(_bytes, _position + index + 1); + *q = Buffer.GetByte(_bytes, _position + index); + } + } + } + _position += len; + } + + public ByteBuffer putInt(int val) + { + putInt(_position, val); + _position += 4; + return this; + } + + public unsafe ByteBuffer putInt(int pos, int val) + { + if(pos < 0) + { + throw new ArgumentOutOfRangeException("pos", pos, "position must be non-negative"); + } + if(pos + 4 > _limit) + { + throw new ArgumentOutOfRangeException("pos", pos, "position must be less than limit - 4"); + } + if(NO._o == _order) + { + fixed(byte* p = &_bytes[pos]) + { + *((int*)p) = val; + } + } + else + { + byte* p = (byte*)&val; + Buffer.SetByte(_bytes, pos, *(p + 3)); + Buffer.SetByte(_bytes, pos + 1, *(p + 2)); + Buffer.SetByte(_bytes, pos + 2, *(p + 1)); + Buffer.SetByte(_bytes, pos + 3, *p); + } + return this; + } + + public ByteBuffer putIntSeq(int[] seq) + { + int len = Buffer.ByteLength(seq); + checkOverflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(seq, 0, _bytes, _position, len); + _position += len; + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + int index = i * 4; + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); + } + } + return this; + } + + public unsafe long getLong() + { + checkUnderflow(8); + long ret; + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + ret = *((long*)p); + } + } + else + { + byte* p = (byte*)&ret; + *p++ = Buffer.GetByte(_bytes, _position + 7); + *p++ = Buffer.GetByte(_bytes, _position + 6); + *p++ = Buffer.GetByte(_bytes, _position + 5); + *p++ = Buffer.GetByte(_bytes, _position + 4); + *p++ = Buffer.GetByte(_bytes, _position + 3); + *p++ = Buffer.GetByte(_bytes, _position + 2); + *p++ = Buffer.GetByte(_bytes, _position + 1); + *p = Buffer.GetByte(_bytes, _position); + } + _position += 8; + return ret; + } + + public unsafe void getLongSeq(long[] seq) + { + int len = Buffer.ByteLength(seq); + checkUnderflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(_bytes, _position, seq, 0, len); + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + fixed(long* p = &seq[i]) + { + int index = i * 8; + byte* q = (byte*)p; + *q++ = Buffer.GetByte(_bytes, _position + index + 7); + *q++ = Buffer.GetByte(_bytes, _position + index + 6); + *q++ = Buffer.GetByte(_bytes, _position + index + 5); + *q++ = Buffer.GetByte(_bytes, _position + index + 4); + *q++ = Buffer.GetByte(_bytes, _position + index + 3); + *q++ = Buffer.GetByte(_bytes, _position + index + 2); + *q++ = Buffer.GetByte(_bytes, _position + index + 1); + *q = Buffer.GetByte(_bytes, _position + index); + } + } + } + _position += len; + } + + public unsafe ByteBuffer putLong(long val) + { + checkOverflow(8); + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + *((long*)p) = val; + } + _position += 8; + } + else + { + byte* p = (byte*)&val; + Buffer.SetByte(_bytes, _position++, *(p + 7)); + Buffer.SetByte(_bytes, _position++, *(p + 6)); + Buffer.SetByte(_bytes, _position++, *(p + 5)); + Buffer.SetByte(_bytes, _position++, *(p + 4)); + Buffer.SetByte(_bytes, _position++, *(p + 3)); + Buffer.SetByte(_bytes, _position++, *(p + 2)); + Buffer.SetByte(_bytes, _position++, *(p + 1)); + Buffer.SetByte(_bytes, _position++, *p); + } + return this; + } + + public ByteBuffer putLongSeq(long[] seq) + { + int len = Buffer.ByteLength(seq); + checkOverflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(seq, 0, _bytes, _position, len); + _position += len; + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + int index = i * 8; + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 7)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 6)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 5)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 4)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); + } + } + return this; + } + + public unsafe float getFloat() + { + checkUnderflow(4); + float ret; + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + ret = *((float*)p); + } + } + else + { + byte* p = (byte*)&ret; + *p++ = Buffer.GetByte(_bytes, _position + 3); + *p++ = Buffer.GetByte(_bytes, _position + 2); + *p++ = Buffer.GetByte(_bytes, _position + 1); + *p = Buffer.GetByte(_bytes, _position); + } + _position += 4; + return ret; + } + + public unsafe void getFloatSeq(float[] seq) + { + int len = Buffer.ByteLength(seq); + checkUnderflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(_bytes, _position, seq, 0, len); + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + fixed(float* p = &seq[i]) + { + int index = i * 4; + byte* q = (byte*)p; + *q++ = Buffer.GetByte(_bytes, _position + index + 3); + *q++ = Buffer.GetByte(_bytes, _position + index + 2); + *q++ = Buffer.GetByte(_bytes, _position + index + 1); + *q = Buffer.GetByte(_bytes, _position + index); + } + } + } + _position += len; + } + + public unsafe ByteBuffer putFloat(float val) + { + checkOverflow(4); + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + *((float*)p) = val; + } + _position += 4; + } + else + { + byte* p = (byte*)&val; + Buffer.SetByte(_bytes, _position++, *(p + 3)); + Buffer.SetByte(_bytes, _position++, *(p + 2)); + Buffer.SetByte(_bytes, _position++, *(p + 1)); + Buffer.SetByte(_bytes, _position++, *p); + } + return this; + } + + public ByteBuffer putFloatSeq(float[] seq) + { + int len = Buffer.ByteLength(seq); + checkOverflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(seq, 0, _bytes, _position, len); + _position += len; + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + int index = i * 4; + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); + } + } + return this; + } + + public unsafe double getDouble() + { + checkUnderflow(8); + double ret; + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + ret = *((double*)p); + } + } + else + { + byte* p = (byte*)&ret; + *p++ = Buffer.GetByte(_bytes, _position + 7); + *p++ = Buffer.GetByte(_bytes, _position + 6); + *p++ = Buffer.GetByte(_bytes, _position + 5); + *p++ = Buffer.GetByte(_bytes, _position + 4); + *p++ = Buffer.GetByte(_bytes, _position + 3); + *p++ = Buffer.GetByte(_bytes, _position + 2); + *p++ = Buffer.GetByte(_bytes, _position + 1); + *p = Buffer.GetByte(_bytes, _position); + } + _position += 8; + return ret; + } + + public unsafe void getDoubleSeq(double[] seq) + { + int len = Buffer.ByteLength(seq); + checkUnderflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(_bytes, _position, seq, 0, len); + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + fixed(double* p = &seq[i]) + { + int index = i * 8; + byte* q = (byte*)p; + *q++ = Buffer.GetByte(_bytes, _position + index + 7); + *q++ = Buffer.GetByte(_bytes, _position + index + 6); + *q++ = Buffer.GetByte(_bytes, _position + index + 5); + *q++ = Buffer.GetByte(_bytes, _position + index + 4); + *q++ = Buffer.GetByte(_bytes, _position + index + 3); + *q++ = Buffer.GetByte(_bytes, _position + index + 2); + *q++ = Buffer.GetByte(_bytes, _position + index + 1); + *q = Buffer.GetByte(_bytes, _position + index); + } + } + } + _position += len; + } + + public unsafe ByteBuffer putDouble(double val) + { + checkOverflow(8); + if(NO._o == _order) + { + fixed(byte* p = &_bytes[_position]) + { + *((double*)p) = val; + } + _position += 8; + } + else + { + byte* p = (byte*)&val; + Buffer.SetByte(_bytes, _position++, *(p + 7)); + Buffer.SetByte(_bytes, _position++, *(p + 6)); + Buffer.SetByte(_bytes, _position++, *(p + 5)); + Buffer.SetByte(_bytes, _position++, *(p + 4)); + Buffer.SetByte(_bytes, _position++, *(p + 3)); + Buffer.SetByte(_bytes, _position++, *(p + 2)); + Buffer.SetByte(_bytes, _position++, *(p + 1)); + Buffer.SetByte(_bytes, _position++, *p); + } + return this; + } + + public ByteBuffer putDoubleSeq(double[] seq) + { + int len = Buffer.ByteLength(seq); + checkOverflow(len); + if(NO._o == _order) + { + Buffer.BlockCopy(seq, 0, _bytes, _position, len); + _position += len; + } + else + { + for(int i = 0; i < seq.Length; ++i) + { + int index = i * 8; + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 7)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 6)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 5)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 4)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 3)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 2)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index + 1)); + Buffer.SetByte(_bytes, _position++, Buffer.GetByte(seq, index)); + } + } + return this; + } + + public byte[] rawBytes() + { + return _bytes; + } public byte[] rawBytes(int offset, int len) { @@ -734,37 +734,37 @@ namespace IceInternal return rc; } - private void checkUnderflow(int size) - { - if(_position + size > _limit) - { - throw new InvalidOperationException("buffer underflow"); - } - } - - private void checkOverflow(int size) - { - if(_position + size > _limit) - { - throw new InvalidOperationException("buffer overflow"); - } - } - - private int _position; - private int _limit; - private int _capacity; - private byte[] _bytes; - private ByteOrder _order; - - private class NO // Native Order - { - static NO() - { - byte[] b = BitConverter.GetBytes((int)1); - _o = b[0] == 1 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; - } - internal static readonly ByteOrder _o; - } + private void checkUnderflow(int size) + { + if(_position + size > _limit) + { + throw new InvalidOperationException("buffer underflow"); + } + } + + private void checkOverflow(int size) + { + if(_position + size > _limit) + { + throw new InvalidOperationException("buffer overflow"); + } + } + + private int _position; + private int _limit; + private int _capacity; + private byte[] _bytes; + private ByteOrder _order; + + private class NO // Native Order + { + static NO() + { + byte[] b = BitConverter.GetBytes((int)1); + _o = b[0] == 1 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; + } + internal static readonly ByteOrder _o; + } } } diff --git a/cs/src/Ice/CommunicatorI.cs b/cs/src/Ice/CommunicatorI.cs index e54fb2463a6..9b9a104df76 100755 --- a/cs/src/Ice/CommunicatorI.cs +++ b/cs/src/Ice/CommunicatorI.cs @@ -9,197 +9,197 @@ namespace Ice { - + sealed class CommunicatorI : LocalObjectImpl, Communicator { - public void destroy() - { - instance_.destroy(); + public void destroy() + { + instance_.destroy(); lock(this) { destroyed_ = true; } - } - - public void shutdown() - { - instance_.objectAdapterFactory().shutdown(); - } - - public void waitForShutdown() - { - instance_.objectAdapterFactory().waitForShutdown(); - } - - public bool isShutdown() - { - return instance_.objectAdapterFactory().isShutdown(); - } - - public Ice.ObjectPrx stringToProxy(string s) - { - return instance_.proxyFactory().stringToProxy(s); - } - - public string proxyToString(Ice.ObjectPrx proxy) - { - return instance_.proxyFactory().proxyToString(proxy); - } - - public Ice.ObjectPrx propertyToProxy(string s) - { - return instance_.proxyFactory().propertyToProxy(s); - } - - public Ice.Identity stringToIdentity(string s) - { - return instance_.stringToIdentity(s); - } - - public string identityToString(Ice.Identity ident) - { - return instance_.identityToString(ident); - } - - public ObjectAdapter createObjectAdapter(string name) - { - return instance_.objectAdapterFactory().createObjectAdapter(name, "", null); - } - - public ObjectAdapter createObjectAdapterWithEndpoints(string name, string endpoints) - { - return instance_.objectAdapterFactory().createObjectAdapter(name, endpoints, null); - } - - public ObjectAdapter createObjectAdapterWithRouter(string name, RouterPrx router) - { - return instance_.objectAdapterFactory().createObjectAdapter(name, "", router); - } - - public void addObjectFactory(ObjectFactory factory, string id) - { - instance_.servantFactoryManager().add(factory, id); - } - - public ObjectFactory findObjectFactory(string id) - { - return instance_.servantFactoryManager().find(id); - } - - public Properties getProperties() - { - return instance_.initializationData().properties; - } - - public Logger getLogger() - { - return instance_.initializationData().logger; - } - - public Stats getStats() - { - return instance_.initializationData().stats; - } - - public RouterPrx getDefaultRouter() - { - return instance_.referenceFactory().getDefaultRouter(); - } - - public void setDefaultRouter(RouterPrx router) - { - instance_.referenceFactory().setDefaultRouter(router); - } - - public LocatorPrx getDefaultLocator() - { - return instance_.referenceFactory().getDefaultLocator(); - } - - public void setDefaultLocator(LocatorPrx locator) - { - instance_.referenceFactory().setDefaultLocator(locator); - } - - public Ice.Context getDefaultContext() - { - return instance_.getDefaultContext(); - } - - public void setDefaultContext(Ice.Context ctx) - { - instance_.setDefaultContext(ctx); - } - - public ImplicitContext getImplicitContext() - { - return instance_.getImplicitContext(); - } - - public PluginManager getPluginManager() - { - return instance_.pluginManager(); - } - - public void flushBatchRequests() - { - instance_.flushBatchRequests(); - } - - internal CommunicatorI(InitializationData initData) - { - instance_ = new IceInternal.Instance(this, initData); - } - + } + + public void shutdown() + { + instance_.objectAdapterFactory().shutdown(); + } + + public void waitForShutdown() + { + instance_.objectAdapterFactory().waitForShutdown(); + } + + public bool isShutdown() + { + return instance_.objectAdapterFactory().isShutdown(); + } + + public Ice.ObjectPrx stringToProxy(string s) + { + return instance_.proxyFactory().stringToProxy(s); + } + + public string proxyToString(Ice.ObjectPrx proxy) + { + return instance_.proxyFactory().proxyToString(proxy); + } + + public Ice.ObjectPrx propertyToProxy(string s) + { + return instance_.proxyFactory().propertyToProxy(s); + } + + public Ice.Identity stringToIdentity(string s) + { + return instance_.stringToIdentity(s); + } + + public string identityToString(Ice.Identity ident) + { + return instance_.identityToString(ident); + } + + public ObjectAdapter createObjectAdapter(string name) + { + return instance_.objectAdapterFactory().createObjectAdapter(name, "", null); + } + + public ObjectAdapter createObjectAdapterWithEndpoints(string name, string endpoints) + { + return instance_.objectAdapterFactory().createObjectAdapter(name, endpoints, null); + } + + public ObjectAdapter createObjectAdapterWithRouter(string name, RouterPrx router) + { + return instance_.objectAdapterFactory().createObjectAdapter(name, "", router); + } + + public void addObjectFactory(ObjectFactory factory, string id) + { + instance_.servantFactoryManager().add(factory, id); + } + + public ObjectFactory findObjectFactory(string id) + { + return instance_.servantFactoryManager().find(id); + } + + public Properties getProperties() + { + return instance_.initializationData().properties; + } + + public Logger getLogger() + { + return instance_.initializationData().logger; + } + + public Stats getStats() + { + return instance_.initializationData().stats; + } + + public RouterPrx getDefaultRouter() + { + return instance_.referenceFactory().getDefaultRouter(); + } + + public void setDefaultRouter(RouterPrx router) + { + instance_.referenceFactory().setDefaultRouter(router); + } + + public LocatorPrx getDefaultLocator() + { + return instance_.referenceFactory().getDefaultLocator(); + } + + public void setDefaultLocator(LocatorPrx locator) + { + instance_.referenceFactory().setDefaultLocator(locator); + } + + public Ice.Context getDefaultContext() + { + return instance_.getDefaultContext(); + } + + public void setDefaultContext(Ice.Context ctx) + { + instance_.setDefaultContext(ctx); + } + + public ImplicitContext getImplicitContext() + { + return instance_.getImplicitContext(); + } + + public PluginManager getPluginManager() + { + return instance_.pluginManager(); + } + + public void flushBatchRequests() + { + instance_.flushBatchRequests(); + } + + internal CommunicatorI(InitializationData initData) + { + instance_ = new IceInternal.Instance(this, initData); + } + #if DEBUG - ~CommunicatorI() - { - lock(this) - { - if(!destroyed_) - { - if(!System.Environment.HasShutdownStarted) - { - instance_.initializationData().logger.warning( - "Ice::Communicator::destroy() has not been called"); - } - else - { - System.Console.Error.WriteLine("Ice::Communicator::destroy() has not been called"); - } - } - } - } + ~CommunicatorI() + { + lock(this) + { + if(!destroyed_) + { + if(!System.Environment.HasShutdownStarted) + { + instance_.initializationData().logger.warning( + "Ice::Communicator::destroy() has not been called"); + } + else + { + System.Console.Error.WriteLine("Ice::Communicator::destroy() has not been called"); + } + } + } + } #endif - // - // Certain initialization tasks need to be completed after the - // constructor. - // - internal void finishSetup(ref string[] args) - { - try - { - instance_.finishSetup(ref args); - } - catch(System.Exception) - { - instance_.destroy(); + // + // Certain initialization tasks need to be completed after the + // constructor. + // + internal void finishSetup(ref string[] args) + { + try + { + instance_.finishSetup(ref args); + } + catch(System.Exception) + { + instance_.destroy(); destroyed_ = true; - throw; - } - } - - // - // For use by Util.getInstance() - // - internal IceInternal.Instance getInstance() - { - return instance_; - } - - private IceInternal.Instance instance_; - private bool destroyed_ = false; + throw; + } + } + + // + // For use by Util.getInstance() + // + internal IceInternal.Instance getInstance() + { + return instance_; + } + + private IceInternal.Instance instance_; + private bool destroyed_ = false; } } diff --git a/cs/src/Ice/ConnectionFactory.cs b/cs/src/Ice/ConnectionFactory.cs index 2e212df012b..df5bceec03d 100644 --- a/cs/src/Ice/ConnectionFactory.cs +++ b/cs/src/Ice/ConnectionFactory.cs @@ -17,88 +17,88 @@ namespace IceInternal public sealed class OutgoingConnectionFactory { - public void destroy() - { - lock(this) - { - if(_destroyed) - { - return; - } - - foreach(LinkedList connections in _connections.Values) - { - foreach(Ice.ConnectionI c in connections) - { - c.destroy(Ice.ConnectionI.CommunicatorDestroyed); - } - } + public void destroy() + { + lock(this) + { + if(_destroyed) + { + return; + } + + foreach(LinkedList connections in _connections.Values) + { + foreach(Ice.ConnectionI c in connections) + { + c.destroy(Ice.ConnectionI.CommunicatorDestroyed); + } + } - _destroyed = true; - System.Threading.Monitor.PulseAll(this); - } - } - - public void waitUntilFinished() - { - Hashtable connections; - - lock(this) - { - // - // First we wait until the factory is destroyed. We also - // wait until there are no pending connections - // anymore. Only then we can be sure the _connections - // contains all connections. - // - while(!_destroyed || _pending.Count != 0) - { - System.Threading.Monitor.Wait(this); - } - - // - // We want to wait until all connections are finished - // outside the thread synchronization. - // - // We set _connections to null because our destructor must not - // invoke methods on member objects. - // - connections = _connections; - _connections = null; - } - - // - // Now we wait for the destruction of each connection to be - // finished. - // - foreach(LinkedList cl in connections.Values) - { - foreach(Ice.ConnectionI c in cl) - { - c.waitUntilFinished(); - } - } - } - - public Ice.ConnectionI create(EndpointI[] endpts, bool hasMore, bool threadPerConnection, out bool compress) - { - Debug.Assert(endpts.Length > 0); - EndpointI[] endpoints = new EndpointI[endpts.Length]; + _destroyed = true; + System.Threading.Monitor.PulseAll(this); + } + } + + public void waitUntilFinished() + { + Hashtable connections; + + lock(this) + { + // + // First we wait until the factory is destroyed. We also + // wait until there are no pending connections + // anymore. Only then we can be sure the _connections + // contains all connections. + // + while(!_destroyed || _pending.Count != 0) + { + System.Threading.Monitor.Wait(this); + } + + // + // We want to wait until all connections are finished + // outside the thread synchronization. + // + // We set _connections to null because our destructor must not + // invoke methods on member objects. + // + connections = _connections; + _connections = null; + } + + // + // Now we wait for the destruction of each connection to be + // finished. + // + foreach(LinkedList cl in connections.Values) + { + foreach(Ice.ConnectionI c in cl) + { + c.waitUntilFinished(); + } + } + } + + public Ice.ConnectionI create(EndpointI[] endpts, bool hasMore, bool threadPerConnection, out bool compress) + { + Debug.Assert(endpts.Length > 0); + EndpointI[] endpoints = new EndpointI[endpts.Length]; - for(int i = 0; i < endpoints.Length; ++i) - { - endpoints[i] = endpts[i]; - } - DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); - + for(int i = 0; i < endpoints.Length; ++i) + { + endpoints[i] = endpts[i]; + } + DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); + compress = false; - lock(this) - { - if(_destroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } + lock(this) + { + if(_destroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } // // TODO: Remove when we no longer support SSL for .NET 1.1. @@ -113,72 +113,72 @@ namespace IceInternal } } - // - // Reap connections for which destruction has completed. - // - ArrayList removeList = new ArrayList(); - foreach(DictionaryEntry e in _connections) - { - LinkedList cl = (LinkedList)e.Value; - LinkedList.Enumerator q = (LinkedList.Enumerator)cl.GetEnumerator(); - while(q.MoveNext()) - { - if(((Ice.ConnectionI)q.Current).isFinished()) - { - q.Remove(); - } - } - if(cl.Count == 0) - { - removeList.Add(e.Key); - } - } - foreach(object o in removeList) - { - _connections.Remove(o); - } + // + // Reap connections for which destruction has completed. + // + ArrayList removeList = new ArrayList(); + foreach(DictionaryEntry e in _connections) + { + LinkedList cl = (LinkedList)e.Value; + LinkedList.Enumerator q = (LinkedList.Enumerator)cl.GetEnumerator(); + while(q.MoveNext()) + { + if(((Ice.ConnectionI)q.Current).isFinished()) + { + q.Remove(); + } + } + if(cl.Count == 0) + { + removeList.Add(e.Key); + } + } + foreach(object o in removeList) + { + _connections.Remove(o); + } - // - // Modify endpoints with overrides. - // - for(int i = 0; i < endpoints.Length; i++) - { - if(defaultsAndOverrides.overrideTimeout) - { - endpoints[i] = endpoints[i].timeout(defaultsAndOverrides.overrideTimeoutValue); - } + // + // Modify endpoints with overrides. + // + for(int i = 0; i < endpoints.Length; i++) + { + if(defaultsAndOverrides.overrideTimeout) + { + endpoints[i] = endpoints[i].timeout(defaultsAndOverrides.overrideTimeoutValue); + } - // - // The Connection object does not take the - // compression flag of endpoints into account, but - // instead gets the information about whether - // messages should be compressed or not from other - // sources. In order to allow connection sharing - // for endpoints that differ in the value of the - // compression flag only, we always set the - // compression flag to false here in this - // connection factory. - // - endpoints[i] = endpoints[i].compress(false); - } - - // - // Search for existing connections. - // - for(int i = 0; i < endpoints.Length; i++) - { - LinkedList connectionList = (LinkedList)_connections[endpoints[i]]; - if(connectionList != null) - { - foreach(Ice.ConnectionI conn in connectionList) - { + // + // The Connection object does not take the + // compression flag of endpoints into account, but + // instead gets the information about whether + // messages should be compressed or not from other + // sources. In order to allow connection sharing + // for endpoints that differ in the value of the + // compression flag only, we always set the + // compression flag to false here in this + // connection factory. + // + endpoints[i] = endpoints[i].compress(false); + } + + // + // Search for existing connections. + // + for(int i = 0; i < endpoints.Length; i++) + { + LinkedList connectionList = (LinkedList)_connections[endpoints[i]]; + if(connectionList != null) + { + foreach(Ice.ConnectionI conn in connectionList) + { // // Don't return connections for which destruction has // been initiated. The connection must also match the // requested thread-per-connection setting. // - if(!conn.isDestroyed() && conn.threadPerConnection() == threadPerConnection) - { + if(!conn.isDestroyed() && conn.threadPerConnection() == threadPerConnection) + { if(defaultsAndOverrides.overrideCompress) { compress = defaultsAndOverrides.overrideCompressValue; @@ -187,56 +187,56 @@ namespace IceInternal { compress = endpts[i].compress(); } - return conn; - } - } - } - } - - // - // If some other thread is currently trying to establish a - // connection to any of our endpoints, we wait until this - // thread is finished. - // - bool searchAgain = false; - while(!_destroyed) - { - int i; - for(i = 0; i < endpoints.Length; i++) - { - if(_pending.Contains(endpoints[i])) - { - break; - } - } - - if(i == endpoints.Length) - { - break; - } - - searchAgain = true; - - System.Threading.Monitor.Wait(this); - } - - if(_destroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - // - // Search for existing connections again if we waited - // above, as new connections might have been added in the - // meantime. - // - if(searchAgain) - { - for(int i = 0; i < endpoints.Length; i++) - { - LinkedList connectionList = (LinkedList)_connections[endpoints[i]]; - if(connectionList != null) - { + return conn; + } + } + } + } + + // + // If some other thread is currently trying to establish a + // connection to any of our endpoints, we wait until this + // thread is finished. + // + bool searchAgain = false; + while(!_destroyed) + { + int i; + for(i = 0; i < endpoints.Length; i++) + { + if(_pending.Contains(endpoints[i])) + { + break; + } + } + + if(i == endpoints.Length) + { + break; + } + + searchAgain = true; + + System.Threading.Monitor.Wait(this); + } + + if(_destroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + // + // Search for existing connections again if we waited + // above, as new connections might have been added in the + // meantime. + // + if(searchAgain) + { + for(int i = 0; i < endpoints.Length; i++) + { + LinkedList connectionList = (LinkedList)_connections[endpoints[i]]; + if(connectionList != null) + { foreach(Ice.ConnectionI conn in connectionList) { // @@ -257,55 +257,55 @@ namespace IceInternal return conn; } } - } - } - } - - // - // No connection to any of our endpoints exists yet, - // so we will try to create one. To avoid that other - // threads try to create connections to the same - // endpoints, we add our endpoints to _pending. - // - foreach(EndpointI e in endpoints) - { - _pending.Add(e); - } - } - - Ice.ConnectionI connection = null; - Ice.LocalException exception = null; - - for(int i = 0; i < endpoints.Length; i++) - { - EndpointI endpoint = endpoints[i]; - - try - { - Transceiver transceiver = endpoint.clientTransceiver(); - if(transceiver == null) - { - Connector connector = endpoint.connector(); - Debug.Assert(connector != null); + } + } + } + + // + // No connection to any of our endpoints exists yet, + // so we will try to create one. To avoid that other + // threads try to create connections to the same + // endpoints, we add our endpoints to _pending. + // + foreach(EndpointI e in endpoints) + { + _pending.Add(e); + } + } + + Ice.ConnectionI connection = null; + Ice.LocalException exception = null; + + for(int i = 0; i < endpoints.Length; i++) + { + EndpointI endpoint = endpoints[i]; + + try + { + Transceiver transceiver = endpoint.clientTransceiver(); + if(transceiver == null) + { + Connector connector = endpoint.connector(); + Debug.Assert(connector != null); - int timeout; - if(defaultsAndOverrides.overrideConnectTimeout) - { - timeout = defaultsAndOverrides.overrideConnectTimeoutValue; - } - // It is not necessary to check for overrideTimeout, - // the endpoint has already been modified with this - // override, if set. - else - { - timeout = endpoint.timeout(); - } + int timeout; + if(defaultsAndOverrides.overrideConnectTimeout) + { + timeout = defaultsAndOverrides.overrideConnectTimeoutValue; + } + // It is not necessary to check for overrideTimeout, + // the endpoint has already been modified with this + // override, if set. + else + { + timeout = endpoint.timeout(); + } - transceiver = connector.connect(timeout); - Debug.Assert(transceiver != null); - } - connection = new Ice.ConnectionI(instance_, transceiver, endpoint, null, threadPerConnection); - connection.validate(); + transceiver = connector.connect(timeout); + Debug.Assert(transceiver != null); + } + connection = new Ice.ConnectionI(instance_, transceiver, endpoint, null, threadPerConnection); + connection.validate(); if(defaultsAndOverrides.overrideCompress) { @@ -315,974 +315,974 @@ namespace IceInternal { compress = endpoint.compress(); } - break; - } - catch(Ice.LocalException ex) - { - exception = ex; + break; + } + catch(Ice.LocalException ex) + { + exception = ex; - // - // If a connection object was constructed, then validate() - // must have raised the exception. - // - if(connection != null) - { - connection.waitUntilFinished(); // We must call waitUntilFinished() for cleanup. - connection = null; - } - } - - TraceLevels traceLevels = instance_.traceLevels(); - if(traceLevels.retry >= 2) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("connection to endpoint failed"); - if(hasMore || i < endpoints.Length - 1) - { - s.Append(", trying next endpoint\n"); - } - else - { - s.Append(" and no more endpoints to try\n"); - } - s.Append(exception); - instance_.initializationData().logger.trace(traceLevels.retryCat, s.ToString()); - } - } - - lock(this) - { - // - // Signal other threads that we are done with trying to - // establish connections to our endpoints. - // - for(int i = 0; i < endpoints.Length; i++) - { - _pending.Remove(endpoints[i]); - } - System.Threading.Monitor.PulseAll(this); - - if(connection == null) - { - Debug.Assert(exception != null); - throw exception; - } - else - { - LinkedList connectionList = (LinkedList)_connections[connection.endpoint()]; - if(connectionList == null) - { - connectionList = new LinkedList(); - _connections[connection.endpoint()] = connectionList; - } - connectionList.Add(connection); - - if(_destroyed) - { - connection.destroy(Ice.ConnectionI.CommunicatorDestroyed); - throw new Ice.CommunicatorDestroyedException(); - } - else - { - connection.activate(); - } - } - } - - Debug.Assert(connection != null); - return connection; - } - - public void setRouterInfo(IceInternal.RouterInfo routerInfo) - { - lock(this) - { - if(_destroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - Debug.Assert(routerInfo != null); - // - // Search for connections to the router's client proxy - // endpoints, and update the object adapter for such - // connections, so that callbacks from the router can be - // received over such connections. - // - Ice.ObjectAdapter adapter = routerInfo.getAdapter(); - DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); - EndpointI[] endpoints = routerInfo.getClientEndpoints(); - for(int i = 0; i < endpoints.Length; i++) - { - EndpointI endpoint = endpoints[i]; + // + // If a connection object was constructed, then validate() + // must have raised the exception. + // + if(connection != null) + { + connection.waitUntilFinished(); // We must call waitUntilFinished() for cleanup. + connection = null; + } + } + + TraceLevels traceLevels = instance_.traceLevels(); + if(traceLevels.retry >= 2) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("connection to endpoint failed"); + if(hasMore || i < endpoints.Length - 1) + { + s.Append(", trying next endpoint\n"); + } + else + { + s.Append(" and no more endpoints to try\n"); + } + s.Append(exception); + instance_.initializationData().logger.trace(traceLevels.retryCat, s.ToString()); + } + } + + lock(this) + { + // + // Signal other threads that we are done with trying to + // establish connections to our endpoints. + // + for(int i = 0; i < endpoints.Length; i++) + { + _pending.Remove(endpoints[i]); + } + System.Threading.Monitor.PulseAll(this); + + if(connection == null) + { + Debug.Assert(exception != null); + throw exception; + } + else + { + LinkedList connectionList = (LinkedList)_connections[connection.endpoint()]; + if(connectionList == null) + { + connectionList = new LinkedList(); + _connections[connection.endpoint()] = connectionList; + } + connectionList.Add(connection); + + if(_destroyed) + { + connection.destroy(Ice.ConnectionI.CommunicatorDestroyed); + throw new Ice.CommunicatorDestroyedException(); + } + else + { + connection.activate(); + } + } + } + + Debug.Assert(connection != null); + return connection; + } + + public void setRouterInfo(IceInternal.RouterInfo routerInfo) + { + lock(this) + { + if(_destroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + Debug.Assert(routerInfo != null); + // + // Search for connections to the router's client proxy + // endpoints, and update the object adapter for such + // connections, so that callbacks from the router can be + // received over such connections. + // + Ice.ObjectAdapter adapter = routerInfo.getAdapter(); + DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); + EndpointI[] endpoints = routerInfo.getClientEndpoints(); + for(int i = 0; i < endpoints.Length; i++) + { + EndpointI endpoint = endpoints[i]; - // - // Modify endpoints with overrides. - // - if(defaultsAndOverrides.overrideTimeout) - { - endpoint = endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue); - } + // + // Modify endpoints with overrides. + // + if(defaultsAndOverrides.overrideTimeout) + { + endpoint = endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue); + } - // - // The Ice.ConnectionI object does not take the compression flag of - // endpoints into account, but instead gets the information - // about whether messages should be compressed or not from - // other sources. In order to allow connection sharing for - // endpoints that differ in the value of the compression flag - // only, we always set the compression flag to false here in - // this connection factory. - // - endpoint = endpoint.compress(false); - - LinkedList connectionList = (LinkedList)_connections[endpoints[i]]; - if(connectionList != null) - { - foreach(Ice.ConnectionI connection in connectionList) - { - try - { - connection.setAdapter(adapter); - } - catch(Ice.LocalException) - { - // - // Ignore, the connection is being closed or closed. - // - } - } - } - } - } - } + // + // The Ice.ConnectionI object does not take the compression flag of + // endpoints into account, but instead gets the information + // about whether messages should be compressed or not from + // other sources. In order to allow connection sharing for + // endpoints that differ in the value of the compression flag + // only, we always set the compression flag to false here in + // this connection factory. + // + endpoint = endpoint.compress(false); + + LinkedList connectionList = (LinkedList)_connections[endpoints[i]]; + if(connectionList != null) + { + foreach(Ice.ConnectionI connection in connectionList) + { + try + { + connection.setAdapter(adapter); + } + catch(Ice.LocalException) + { + // + // Ignore, the connection is being closed or closed. + // + } + } + } + } + } + } - public void removeAdapter(Ice.ObjectAdapter adapter) - { - lock(this) - { - if(_destroyed) - { - return; - } - - foreach(LinkedList connectionList in _connections.Values) - { - foreach(Ice.ConnectionI connection in connectionList) - { - if(connection.getAdapter() == adapter) - { - try - { - connection.setAdapter(null); - } - catch(Ice.LocalException) - { - // - // Ignore, the connection is being closed or closed. - // - } - } - } - } - } - } - - public void flushBatchRequests() - { - LinkedList c = new LinkedList(); - - lock(this) - { - foreach(LinkedList connectionList in _connections.Values) - { - foreach(Ice.ConnectionI conn in connectionList) - { - c.Add(conn); - } - } - } - - foreach(Ice.ConnectionI conn in c) - { - try - { - conn.flushBatchRequests(); - } - catch(Ice.LocalException) - { - // Ignore. - } - } - } - - // - // Only for use by Instance. - // - internal OutgoingConnectionFactory(Instance instance) - { - instance_ = instance; - _destroyed = false; - _connections = new Hashtable(); - _pending = new Set(); - } - - private readonly Instance instance_; - private bool _destroyed; - private Hashtable _connections; - private Set _pending; + public void removeAdapter(Ice.ObjectAdapter adapter) + { + lock(this) + { + if(_destroyed) + { + return; + } + + foreach(LinkedList connectionList in _connections.Values) + { + foreach(Ice.ConnectionI connection in connectionList) + { + if(connection.getAdapter() == adapter) + { + try + { + connection.setAdapter(null); + } + catch(Ice.LocalException) + { + // + // Ignore, the connection is being closed or closed. + // + } + } + } + } + } + } + + public void flushBatchRequests() + { + LinkedList c = new LinkedList(); + + lock(this) + { + foreach(LinkedList connectionList in _connections.Values) + { + foreach(Ice.ConnectionI conn in connectionList) + { + c.Add(conn); + } + } + } + + foreach(Ice.ConnectionI conn in c) + { + try + { + conn.flushBatchRequests(); + } + catch(Ice.LocalException) + { + // Ignore. + } + } + } + + // + // Only for use by Instance. + // + internal OutgoingConnectionFactory(Instance instance) + { + instance_ = instance; + _destroyed = false; + _connections = new Hashtable(); + _pending = new Set(); + } + + private readonly Instance instance_; + private bool _destroyed; + private Hashtable _connections; + private Set _pending; } public sealed class IncomingConnectionFactory : EventHandler { - public void activate() - { - lock(this) - { - setState(StateActive); - } - } - - public void hold() - { - lock(this) - { - setState(StateHolding); - } - } - - public void destroy() - { - lock(this) - { - setState(StateClosed); - } - } - - public void waitUntilHolding() - { - LinkedList connections; - - lock(this) - { - // - // First we wait until the connection factory itself is in - // holding state. - // - while(_state < StateHolding) - { - System.Threading.Monitor.Wait(this); - } - - // - // We want to wait until all connections are in holding state - // outside the thread synchronization. - // - connections = (LinkedList)_connections.Clone(); - } - - // - // Now we wait until each connection is in holding state. - // - foreach(Ice.ConnectionI connection in connections) - { - connection.waitUntilHolding(); - } - } - - public void waitUntilFinished() - { - Thread threadPerIncomingConnectionFactory = null; - LinkedList connections; - - lock(this) - { - // - // First we wait until the factory is destroyed. If we are using - // an acceptor, we also wait for it to be closed. - // - while(_state != StateClosed || _acceptor != null) - { - System.Threading.Monitor.Wait(this); - } + public void activate() + { + lock(this) + { + setState(StateActive); + } + } + + public void hold() + { + lock(this) + { + setState(StateHolding); + } + } + + public void destroy() + { + lock(this) + { + setState(StateClosed); + } + } + + public void waitUntilHolding() + { + LinkedList connections; + + lock(this) + { + // + // First we wait until the connection factory itself is in + // holding state. + // + while(_state < StateHolding) + { + System.Threading.Monitor.Wait(this); + } + + // + // We want to wait until all connections are in holding state + // outside the thread synchronization. + // + connections = (LinkedList)_connections.Clone(); + } + + // + // Now we wait until each connection is in holding state. + // + foreach(Ice.ConnectionI connection in connections) + { + connection.waitUntilHolding(); + } + } + + public void waitUntilFinished() + { + Thread threadPerIncomingConnectionFactory = null; + LinkedList connections; + + lock(this) + { + // + // First we wait until the factory is destroyed. If we are using + // an acceptor, we also wait for it to be closed. + // + while(_state != StateClosed || _acceptor != null) + { + System.Threading.Monitor.Wait(this); + } - threadPerIncomingConnectionFactory = _threadPerIncomingConnectionFactory; - _threadPerIncomingConnectionFactory = null; + threadPerIncomingConnectionFactory = _threadPerIncomingConnectionFactory; + _threadPerIncomingConnectionFactory = null; // // Clear the OA. See bug 1673 for the details of why this is necessary. // _adapter = null; - // - // We want to wait until all connections are finished - // outside the thread synchronization. - // - // We set _connections to null because our destructor must not - // invoke methods on member objects. - // - connections = _connections; - _connections = null; - } + // + // We want to wait until all connections are finished + // outside the thread synchronization. + // + // We set _connections to null because our destructor must not + // invoke methods on member objects. + // + connections = _connections; + _connections = null; + } - if(threadPerIncomingConnectionFactory != null) - { - threadPerIncomingConnectionFactory.Join(); - } + if(threadPerIncomingConnectionFactory != null) + { + threadPerIncomingConnectionFactory.Join(); + } - // - // Now we wait until the destruction of each connection is finished. - // - if(connections != null) - { - foreach(Ice.ConnectionI connection in connections) - { - connection.waitUntilFinished(); - } - } - } - - public EndpointI endpoint() - { - // No mutex protection necessary, _endpoint is immutable. - return _endpoint; - } - - public bool equivalent(EndpointI endp) - { - if(_transceiver != null) - { - return endp.equivalent(_transceiver); - } - - Debug.Assert(_acceptor != null); - return endp.equivalent(_acceptor); - } - - public Ice.ConnectionI[] connections() - { - lock(this) - { - LinkedList connections = new LinkedList(); - - // - // Only copy connections which have not been destroyed. - // - foreach(Ice.ConnectionI connection in _connections) - { - if(!connection.isDestroyed()) - { - connections.Add(connection); - } - } - Ice.ConnectionI[] arr = new Ice.ConnectionI[connections.Count]; - if(arr.Length != 0) - { - connections.CopyTo(arr, 0); - } - return arr; - } - } - - public void flushBatchRequests() - { - // - // connections() is synchronized, so no need to synchronize here. - // - foreach(Ice.ConnectionI connection in connections()) - { - try - { - connection.flushBatchRequests(); - } - catch(Ice.LocalException) - { - // Ignore. - } - } - } - - // - // Operations from EventHandler. - // - - public override bool datagram() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - return _endpoint.datagram(); - } - - public override bool readable() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - return false; - } - - public override void read(BasicStream unused) - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - Debug.Assert(false); // Must not be called. - } - - public override void message(BasicStream unused, ThreadPool threadPool) - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + // + // Now we wait until the destruction of each connection is finished. + // + if(connections != null) + { + foreach(Ice.ConnectionI connection in connections) + { + connection.waitUntilFinished(); + } + } + } + + public EndpointI endpoint() + { + // No mutex protection necessary, _endpoint is immutable. + return _endpoint; + } + + public bool equivalent(EndpointI endp) + { + if(_transceiver != null) + { + return endp.equivalent(_transceiver); + } + + Debug.Assert(_acceptor != null); + return endp.equivalent(_acceptor); + } + + public Ice.ConnectionI[] connections() + { + lock(this) + { + LinkedList connections = new LinkedList(); + + // + // Only copy connections which have not been destroyed. + // + foreach(Ice.ConnectionI connection in _connections) + { + if(!connection.isDestroyed()) + { + connections.Add(connection); + } + } + Ice.ConnectionI[] arr = new Ice.ConnectionI[connections.Count]; + if(arr.Length != 0) + { + connections.CopyTo(arr, 0); + } + return arr; + } + } + + public void flushBatchRequests() + { + // + // connections() is synchronized, so no need to synchronize here. + // + foreach(Ice.ConnectionI connection in connections()) + { + try + { + connection.flushBatchRequests(); + } + catch(Ice.LocalException) + { + // Ignore. + } + } + } + + // + // Operations from EventHandler. + // + + public override bool datagram() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + return _endpoint.datagram(); + } + + public override bool readable() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + return false; + } + + public override void read(BasicStream unused) + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + Debug.Assert(false); // Must not be called. + } + + public override void message(BasicStream unused, ThreadPool threadPool) + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - Ice.ConnectionI connection = null; - - lock(this) - { - try - { - if(_state != StateActive) - { - Thread.Sleep(0); - return; - } - - // - // Reap connections for which destruction has completed. - // - LinkedList.Enumerator p = (LinkedList.Enumerator)_connections.GetEnumerator(); - while(p.MoveNext()) - { - Ice.ConnectionI con = (Ice.ConnectionI)p.Current; - if(con.isFinished()) - { - p.Remove(); - } - } - - // - // Now accept a new connection. - // - Transceiver transceiver; - try - { - transceiver = _acceptor.accept(0); - } - catch(Ice.TimeoutException) - { - // Ignore timeouts. - return; - } - catch(Ice.LocalException ex) - { - // Warn about other Ice local exceptions. - if(_warn) - { - warning(ex); - } - return; - } - - Debug.Assert(transceiver != null); + Ice.ConnectionI connection = null; + + lock(this) + { + try + { + if(_state != StateActive) + { + Thread.Sleep(0); + return; + } + + // + // Reap connections for which destruction has completed. + // + LinkedList.Enumerator p = (LinkedList.Enumerator)_connections.GetEnumerator(); + while(p.MoveNext()) + { + Ice.ConnectionI con = (Ice.ConnectionI)p.Current; + if(con.isFinished()) + { + p.Remove(); + } + } + + // + // Now accept a new connection. + // + Transceiver transceiver; + try + { + transceiver = _acceptor.accept(0); + } + catch(Ice.TimeoutException) + { + // Ignore timeouts. + return; + } + catch(Ice.LocalException ex) + { + // Warn about other Ice local exceptions. + if(_warn) + { + warning(ex); + } + return; + } + + Debug.Assert(transceiver != null); - try - { - connection = new Ice.ConnectionI(instance_, transceiver, _endpoint, _adapter, + try + { + connection = new Ice.ConnectionI(instance_, transceiver, _endpoint, _adapter, _threadPerConnection); - } - catch(Ice.LocalException) - { - return; - } - - _connections.Add(connection); - } - finally - { - // - // This makes sure that we promote a follower before - // we leave the scope of the mutex above, but after we - // call accept() (if we call it). - // - threadPool.promoteFollower(); - } - } - - Debug.Assert(connection != null); - - // - // We validate and activate outside the thread - // synchronization, to not block the factory. - // - try - { - connection.validate(); - } - catch(Ice.LocalException) - { - lock(this) - { - connection.waitUntilFinished(); // We must call waitUntilFinished() for cleanup. - LinkedList.Enumerator p = (LinkedList.Enumerator)_connections.GetEnumerator(); - while(p.MoveNext()) - { - if((Ice.ConnectionI)p.Current == connection) - { - p.Remove(); - break; - } - } - return; - } - } - - connection.activate(); - } - - public override void finished(ThreadPool threadPool) - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + } + catch(Ice.LocalException) + { + return; + } + + _connections.Add(connection); + } + finally + { + // + // This makes sure that we promote a follower before + // we leave the scope of the mutex above, but after we + // call accept() (if we call it). + // + threadPool.promoteFollower(); + } + } + + Debug.Assert(connection != null); + + // + // We validate and activate outside the thread + // synchronization, to not block the factory. + // + try + { + connection.validate(); + } + catch(Ice.LocalException) + { + lock(this) + { + connection.waitUntilFinished(); // We must call waitUntilFinished() for cleanup. + LinkedList.Enumerator p = (LinkedList.Enumerator)_connections.GetEnumerator(); + while(p.MoveNext()) + { + if((Ice.ConnectionI)p.Current == connection) + { + p.Remove(); + break; + } + } + return; + } + } + + connection.activate(); + } + + public override void finished(ThreadPool threadPool) + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - lock(this) - { - threadPool.promoteFollower(); + lock(this) + { + threadPool.promoteFollower(); Debug.Assert(threadPool == ((Ice.ObjectAdapterI)_adapter).getThreadPool()); - - --_finishedCount; + + --_finishedCount; - if(_finishedCount == 0 && _state == StateClosed) - { - _acceptor.close(); - _acceptor = null; - System.Threading.Monitor.PulseAll(this); - } - } - } - - public override void exception(Ice.LocalException ex) - { - Debug.Assert(false); // Must not be called. - } - - public override string ToString() - { - if(_transceiver != null) - { - return _transceiver.ToString(); - } - - Debug.Assert(_acceptor != null); - return _acceptor.ToString(); - } - - public IncomingConnectionFactory(Instance instance, EndpointI endpoint, Ice.ObjectAdapter adapter, - string adapterName) - : base(instance) - { - _endpoint = endpoint; - _adapter = adapter; - _registeredWithPool = false; - _finishedCount = 0; - _warn = - instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Connections") > 0 ? true : false; - _connections = new LinkedList(); - _state = StateHolding; - - DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); + if(_finishedCount == 0 && _state == StateClosed) + { + _acceptor.close(); + _acceptor = null; + System.Threading.Monitor.PulseAll(this); + } + } + } + + public override void exception(Ice.LocalException ex) + { + Debug.Assert(false); // Must not be called. + } + + public override string ToString() + { + if(_transceiver != null) + { + return _transceiver.ToString(); + } + + Debug.Assert(_acceptor != null); + return _acceptor.ToString(); + } + + public IncomingConnectionFactory(Instance instance, EndpointI endpoint, Ice.ObjectAdapter adapter, + string adapterName) + : base(instance) + { + _endpoint = endpoint; + _adapter = adapter; + _registeredWithPool = false; + _finishedCount = 0; + _warn = + instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Connections") > 0 ? true : false; + _connections = new LinkedList(); + _state = StateHolding; + + DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); - if(defaultsAndOverrides.overrideTimeout) - { - _endpoint = _endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue); - } + if(defaultsAndOverrides.overrideTimeout) + { + _endpoint = _endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue); + } - if(defaultsAndOverrides.overrideCompress) - { - _endpoint = _endpoint.compress(defaultsAndOverrides.overrideCompressValue); - } + if(defaultsAndOverrides.overrideCompress) + { + _endpoint = _endpoint.compress(defaultsAndOverrides.overrideCompressValue); + } Ice.ObjectAdapterI adapterImpl = (Ice.ObjectAdapterI)_adapter; _threadPerConnection = adapterImpl.getThreadPerConnection(); - EndpointI h = _endpoint; - _transceiver = _endpoint.serverTransceiver(ref h); + EndpointI h = _endpoint; + _transceiver = _endpoint.serverTransceiver(ref h); - try - { - if(_transceiver != null) - { - _endpoint = h; - - Ice.ConnectionI connection = null; - - try - { - connection = new Ice.ConnectionI(instance_, _transceiver, _endpoint, _adapter, + try + { + if(_transceiver != null) + { + _endpoint = h; + + Ice.ConnectionI connection = null; + + try + { + connection = new Ice.ConnectionI(instance_, _transceiver, _endpoint, _adapter, _threadPerConnection); - connection.validate(); - } - catch(Ice.LocalException) - { - // - // If a connection object was constructed, then - // validate() must have raised the exception. - // - if(connection != null) - { - connection.waitUntilFinished(); // We must call waitUntilFinished() for cleanup. - } - - return; - } - - _connections.Add(connection); - } - else - { - h = _endpoint; - _acceptor = _endpoint.acceptor(ref h, adapterName); - _endpoint = h; - Debug.Assert(_acceptor != null); - _acceptor.listen(); + connection.validate(); + } + catch(Ice.LocalException) + { + // + // If a connection object was constructed, then + // validate() must have raised the exception. + // + if(connection != null) + { + connection.waitUntilFinished(); // We must call waitUntilFinished() for cleanup. + } + + return; + } + + _connections.Add(connection); + } + else + { + h = _endpoint; + _acceptor = _endpoint.acceptor(ref h, adapterName); + _endpoint = h; + Debug.Assert(_acceptor != null); + _acceptor.listen(); - if(_threadPerConnection) - { - try - { - // - // If we are in thread per connection mode, we also use - // one thread per incoming connection factory, that - // accepts new connections on this endpoint. - // - _threadPerIncomingConnectionFactory = - new Thread(new ThreadStart(ThreadPerIncomingConnectionFactory)); + if(_threadPerConnection) + { + try + { + // + // If we are in thread per connection mode, we also use + // one thread per incoming connection factory, that + // accepts new connections on this endpoint. + // + _threadPerIncomingConnectionFactory = + new Thread(new ThreadStart(ThreadPerIncomingConnectionFactory)); _threadPerIncomingConnectionFactory.IsBackground = true; - _threadPerIncomingConnectionFactory.Start(); - } - catch(System.Exception ex) - { - instance_.initializationData().logger.error( - "cannot create thread for incoming connection factory:\n" + ex); - throw; - } - } - } - } - catch(Ice.LocalException) - { - // - // Clean up for finalizer. - // - - if(_acceptor != null) - { - try - { - _acceptor.close(); - } - catch(Ice.LocalException) - { - // Here we ignore any exceptions in close(). - } - } + _threadPerIncomingConnectionFactory.Start(); + } + catch(System.Exception ex) + { + instance_.initializationData().logger.error( + "cannot create thread for incoming connection factory:\n" + ex); + throw; + } + } + } + } + catch(Ice.LocalException) + { + // + // Clean up for finalizer. + // + + if(_acceptor != null) + { + try + { + _acceptor.close(); + } + catch(Ice.LocalException) + { + // Here we ignore any exceptions in close(). + } + } - lock(this) - { - _state = StateClosed; - _acceptor = null; - _connections = null; - _threadPerIncomingConnectionFactory = null; - } + lock(this) + { + _state = StateClosed; + _acceptor = null; + _connections = null; + _threadPerIncomingConnectionFactory = null; + } - throw; - } - catch(System.Exception ex) - { - // - // Clean up for finalizer. - // - - if(_acceptor != null) - { - try - { - _acceptor.close(); - } - catch(Ice.LocalException) - { - // Here we ignore any exceptions in close(). - } - } + throw; + } + catch(System.Exception ex) + { + // + // Clean up for finalizer. + // + + if(_acceptor != null) + { + try + { + _acceptor.close(); + } + catch(Ice.LocalException) + { + // Here we ignore any exceptions in close(). + } + } - lock(this) - { - _state = StateClosed; - _acceptor = null; - _connections = null; - _threadPerIncomingConnectionFactory = null; - } + lock(this) + { + _state = StateClosed; + _acceptor = null; + _connections = null; + _threadPerIncomingConnectionFactory = null; + } - throw new Ice.SyscallException(ex); - } - } - - private const int StateActive = 0; - private const int StateHolding = 1; - private const int StateClosed = 2; - - private void setState(int state) - { - if(_state == state) // Don't switch twice. - { - return; - } - - switch (state) - { - case StateActive: - { - if(_state != StateHolding) // Can only switch from holding to active. - { - return; - } - if(!_threadPerConnection && _acceptor != null) - { - registerWithPool(); - } - - foreach(Ice.ConnectionI connection in _connections) - { - connection.activate(); - } - break; - } - - case StateHolding: - { - if(_state != StateActive) // Can only switch from active to holding. - { - return; - } - if(!_threadPerConnection && _acceptor != null) - { - unregisterWithPool(); - } - - foreach(Ice.ConnectionI connection in _connections) - { - connection.hold(); - } - break; - } - - case StateClosed: - { - if(_acceptor != null) - { - if(_threadPerConnection) - { - // - // If we are in thread per connection mode, we connect - // to our own acceptor, which unblocks our thread per - // incoming connection factory stuck in accept(). - // - _acceptor.connectToSelf(); - } - else - { - // - // Otherwise we first must make sure that we are - // registered, then we unregister, and let finished() - // do the close. - // - registerWithPool(); - unregisterWithPool(); - } - } - - foreach(Ice.ConnectionI connection in _connections) - { - connection.destroy(Ice.ConnectionI.ObjectAdapterDeactivated); - } - break; - } - } - - _state = state; - System.Threading.Monitor.PulseAll(this); - } + throw new Ice.SyscallException(ex); + } + } + + private const int StateActive = 0; + private const int StateHolding = 1; + private const int StateClosed = 2; + + private void setState(int state) + { + if(_state == state) // Don't switch twice. + { + return; + } + + switch (state) + { + case StateActive: + { + if(_state != StateHolding) // Can only switch from holding to active. + { + return; + } + if(!_threadPerConnection && _acceptor != null) + { + registerWithPool(); + } + + foreach(Ice.ConnectionI connection in _connections) + { + connection.activate(); + } + break; + } + + case StateHolding: + { + if(_state != StateActive) // Can only switch from active to holding. + { + return; + } + if(!_threadPerConnection && _acceptor != null) + { + unregisterWithPool(); + } + + foreach(Ice.ConnectionI connection in _connections) + { + connection.hold(); + } + break; + } + + case StateClosed: + { + if(_acceptor != null) + { + if(_threadPerConnection) + { + // + // If we are in thread per connection mode, we connect + // to our own acceptor, which unblocks our thread per + // incoming connection factory stuck in accept(). + // + _acceptor.connectToSelf(); + } + else + { + // + // Otherwise we first must make sure that we are + // registered, then we unregister, and let finished() + // do the close. + // + registerWithPool(); + unregisterWithPool(); + } + } + + foreach(Ice.ConnectionI connection in _connections) + { + connection.destroy(Ice.ConnectionI.ObjectAdapterDeactivated); + } + break; + } + } + + _state = state; + System.Threading.Monitor.PulseAll(this); + } - private void registerWithPool() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - Debug.Assert(_acceptor != null); + private void registerWithPool() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + Debug.Assert(_acceptor != null); - if(!_registeredWithPool) - { - ((Ice.ObjectAdapterI) _adapter).getThreadPool().register(_acceptor.fd(), this); - _registeredWithPool = true; - } - } - - private void unregisterWithPool() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - Debug.Assert(_acceptor != null); + if(!_registeredWithPool) + { + ((Ice.ObjectAdapterI) _adapter).getThreadPool().register(_acceptor.fd(), this); + _registeredWithPool = true; + } + } + + private void unregisterWithPool() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + Debug.Assert(_acceptor != null); - if(_registeredWithPool) - { - ((Ice.ObjectAdapterI) _adapter).getThreadPool().unregister(_acceptor.fd()); - _registeredWithPool = false; - ++_finishedCount; // For each unregistration, finished() is called once. - } - } - - private void warning(Ice.LocalException ex) - { - instance_.initializationData().logger.warning("connection exception:\n" + ex + '\n' + _acceptor.ToString()); - } + if(_registeredWithPool) + { + ((Ice.ObjectAdapterI) _adapter).getThreadPool().unregister(_acceptor.fd()); + _registeredWithPool = false; + ++_finishedCount; // For each unregistration, finished() is called once. + } + } + + private void warning(Ice.LocalException ex) + { + instance_.initializationData().logger.warning("connection exception:\n" + ex + '\n' + _acceptor.ToString()); + } - private void run() - { - Debug.Assert(_acceptor != null); + private void run() + { + Debug.Assert(_acceptor != null); - while(true) - { - // - // We must accept new connections outside the thread - // synchronization, because we use blocking accept. - // - Transceiver transceiver = null; - try - { - transceiver = _acceptor.accept(-1); - } - catch(Ice.TimeoutException) - { - // Ignore timeouts. - } - catch(Ice.LocalException ex) - { - // Warn about other Ice local exceptions. - if(_warn) - { - warning(ex); - } - } + while(true) + { + // + // We must accept new connections outside the thread + // synchronization, because we use blocking accept. + // + Transceiver transceiver = null; + try + { + transceiver = _acceptor.accept(-1); + } + catch(Ice.TimeoutException) + { + // Ignore timeouts. + } + catch(Ice.LocalException ex) + { + // Warn about other Ice local exceptions. + if(_warn) + { + warning(ex); + } + } - Ice.ConnectionI connection = null; + Ice.ConnectionI connection = null; - lock(this) - { - while(_state == StateHolding) - { - Monitor.Wait(this); - } + lock(this) + { + while(_state == StateHolding) + { + Monitor.Wait(this); + } - if(_state == StateClosed) - { - if(transceiver != null) - { - try - { - transceiver.close(); - } - catch(Ice.LocalException) - { - // Here we ignore any exceptions in close(). - } - } + if(_state == StateClosed) + { + if(transceiver != null) + { + try + { + transceiver.close(); + } + catch(Ice.LocalException) + { + // Here we ignore any exceptions in close(). + } + } - try - { - _acceptor.close(); - } - catch(Ice.LocalException) - { - _acceptor = null; - Monitor.PulseAll(this); - throw; - } + try + { + _acceptor.close(); + } + catch(Ice.LocalException) + { + _acceptor = null; + Monitor.PulseAll(this); + throw; + } - _acceptor = null; - Monitor.PulseAll(this); - return; - } + _acceptor = null; + Monitor.PulseAll(this); + return; + } - Debug.Assert(_state == StateActive); + Debug.Assert(_state == StateActive); - // - // Reap connections for which destruction has completed. - // - LinkedList.Enumerator p = (LinkedList.Enumerator)_connections.GetEnumerator(); - while(p.MoveNext()) - { - Ice.ConnectionI con = (Ice.ConnectionI)p.Current; - if(con.isFinished()) - { - p.Remove(); - } - } + // + // Reap connections for which destruction has completed. + // + LinkedList.Enumerator p = (LinkedList.Enumerator)_connections.GetEnumerator(); + while(p.MoveNext()) + { + Ice.ConnectionI con = (Ice.ConnectionI)p.Current; + if(con.isFinished()) + { + p.Remove(); + } + } - // - // Create a connection object for the connection. - // - if(transceiver != null) - { - try - { - connection = new Ice.ConnectionI(instance_, transceiver, _endpoint, _adapter, + // + // Create a connection object for the connection. + // + if(transceiver != null) + { + try + { + connection = new Ice.ConnectionI(instance_, transceiver, _endpoint, _adapter, _threadPerConnection); - } - catch(Ice.LocalException) - { - return; - } + } + catch(Ice.LocalException) + { + return; + } - _connections.Add(connection); - } - } + _connections.Add(connection); + } + } - // - // In thread per connection mode, the connection's thread - // will take care of connection validation and activation - // (for non-datagram connections). We don't want to block - // this thread waiting until validation is complete, - // because in contrast to thread pool mode, it is the only - // thread that can accept connections with this factory's - // acceptor. Therefore we don't call validate() and - // activate() from the connection factory in thread per - // connection mode. - // - } - } + // + // In thread per connection mode, the connection's thread + // will take care of connection validation and activation + // (for non-datagram connections). We don't want to block + // this thread waiting until validation is complete, + // because in contrast to thread pool mode, it is the only + // thread that can accept connections with this factory's + // acceptor. Therefore we don't call validate() and + // activate() from the connection factory in thread per + // connection mode. + // + } + } - public void ThreadPerIncomingConnectionFactory() - { - try - { - run(); - } - catch(Ice.Exception ex) - { - instance_.initializationData().logger.error("exception in thread per incoming connection factory:\n" + - ToString() + ex.ToString()); - } - catch(System.Exception ex) - { - instance_.initializationData().logger.error( - "system exception in thread per incoming connection factory:\n" + ToString() + - ex.ToString()); - } - } + public void ThreadPerIncomingConnectionFactory() + { + try + { + run(); + } + catch(Ice.Exception ex) + { + instance_.initializationData().logger.error("exception in thread per incoming connection factory:\n" + + ToString() + ex.ToString()); + } + catch(System.Exception ex) + { + instance_.initializationData().logger.error( + "system exception in thread per incoming connection factory:\n" + ToString() + + ex.ToString()); + } + } - private Thread _threadPerIncomingConnectionFactory; + private Thread _threadPerIncomingConnectionFactory; - private Acceptor _acceptor; - private readonly Transceiver _transceiver; - private EndpointI _endpoint; - - private Ice.ObjectAdapter _adapter; - - private bool _registeredWithPool; - private int _finishedCount; - - private readonly bool _warn; - - private LinkedList _connections; - - private int _state; + private Acceptor _acceptor; + private readonly Transceiver _transceiver; + private EndpointI _endpoint; + + private Ice.ObjectAdapter _adapter; + + private bool _registeredWithPool; + private int _finishedCount; + + private readonly bool _warn; + + private LinkedList _connections; + + private int _state; private bool _threadPerConnection; } diff --git a/cs/src/Ice/ConnectionI.cs b/cs/src/Ice/ConnectionI.cs index 002fbdf907c..f70f3345fb4 100755 --- a/cs/src/Ice/ConnectionI.cs +++ b/cs/src/Ice/ConnectionI.cs @@ -26,2518 +26,2518 @@ namespace Ice return MemberwiseClone(); } - public void validate() - { - if(!endpoint().datagram()) // Datagram connections are always implicitly validated. - { - bool active; - - lock(this) - { - if(_thread != null && _thread != Thread.CurrentThread) - { - // - // In thread per connection mode, this connection's thread - // will take care of connection validation. Therefore all we - // have to do here is to wait until this thread has completed - // validation. - // - while(_state == StateNotValidated) - { - Monitor.Wait(this); - } - - if(_state >= StateClosing) - { - Debug.Assert(_exception != null); - throw _exception; - } - - return; - } - - Debug.Assert(_state == StateNotValidated || _state == StateClosed); - if(_state == StateClosed) - { - Debug.Assert(_exception != null); - throw _exception; - } - - if(_adapter != null) - { - active = true; // The server side has the active role for connection validation. - } - else - { - active = false; // The client side has the passive role for connection validation. - } - } - - try - { - int timeout; - IceInternal.DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); - if(defaultsAndOverrides.overrideConnectTimeout) - { - timeout = defaultsAndOverrides.overrideConnectTimeoutValue; - } - else - { - timeout = _endpoint.timeout(); - } - - if(active) - { - lock(_sendMutex) - { - if(_transceiver == null) // Has the transceiver already been closed? - { - Debug.Assert(_exception != null); - throw _exception; // The exception is immutable at this point. - } - - IceInternal.BasicStream os = new IceInternal.BasicStream(instance_); - os.writeBlob(IceInternal.Protocol.magic); - os.writeByte(IceInternal.Protocol.protocolMajor); - os.writeByte(IceInternal.Protocol.protocolMinor); - os.writeByte(IceInternal.Protocol.encodingMajor); - os.writeByte(IceInternal.Protocol.encodingMinor); - os.writeByte(IceInternal.Protocol.validateConnectionMsg); - os.writeByte((byte)0); // Compression status (always zero for validate connection). - os.writeInt(IceInternal.Protocol.headerSize); // Message size. - IceInternal.TraceUtil.traceHeader("sending validate connection", os, _logger, _traceLevels); - try - { - _transceiver.initialize(timeout); - _transceiver.write(os, timeout); - } - catch(TimeoutException) - { - throw new ConnectTimeoutException("Connect timed out after " + timeout + " msec"); - } - } - } - else - { - IceInternal.BasicStream ins = new IceInternal.BasicStream(instance_); - ins.resize(IceInternal.Protocol.headerSize, true); - ins.pos(0); - try - { + public void validate() + { + if(!endpoint().datagram()) // Datagram connections are always implicitly validated. + { + bool active; + + lock(this) + { + if(_thread != null && _thread != Thread.CurrentThread) + { + // + // In thread per connection mode, this connection's thread + // will take care of connection validation. Therefore all we + // have to do here is to wait until this thread has completed + // validation. + // + while(_state == StateNotValidated) + { + Monitor.Wait(this); + } + + if(_state >= StateClosing) + { + Debug.Assert(_exception != null); + throw _exception; + } + + return; + } + + Debug.Assert(_state == StateNotValidated || _state == StateClosed); + if(_state == StateClosed) + { + Debug.Assert(_exception != null); + throw _exception; + } + + if(_adapter != null) + { + active = true; // The server side has the active role for connection validation. + } + else + { + active = false; // The client side has the passive role for connection validation. + } + } + + try + { + int timeout; + IceInternal.DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides(); + if(defaultsAndOverrides.overrideConnectTimeout) + { + timeout = defaultsAndOverrides.overrideConnectTimeoutValue; + } + else + { + timeout = _endpoint.timeout(); + } + + if(active) + { + lock(_sendMutex) + { + if(_transceiver == null) // Has the transceiver already been closed? + { + Debug.Assert(_exception != null); + throw _exception; // The exception is immutable at this point. + } + + IceInternal.BasicStream os = new IceInternal.BasicStream(instance_); + os.writeBlob(IceInternal.Protocol.magic); + os.writeByte(IceInternal.Protocol.protocolMajor); + os.writeByte(IceInternal.Protocol.protocolMinor); + os.writeByte(IceInternal.Protocol.encodingMajor); + os.writeByte(IceInternal.Protocol.encodingMinor); + os.writeByte(IceInternal.Protocol.validateConnectionMsg); + os.writeByte((byte)0); // Compression status (always zero for validate connection). + os.writeInt(IceInternal.Protocol.headerSize); // Message size. + IceInternal.TraceUtil.traceHeader("sending validate connection", os, _logger, _traceLevels); + try + { + _transceiver.initialize(timeout); + _transceiver.write(os, timeout); + } + catch(TimeoutException) + { + throw new ConnectTimeoutException("Connect timed out after " + timeout + " msec"); + } + } + } + else + { + IceInternal.BasicStream ins = new IceInternal.BasicStream(instance_); + ins.resize(IceInternal.Protocol.headerSize, true); + ins.pos(0); + try + { _transceiver.initialize(timeout); - _transceiver.read(ins, timeout); - } - catch(TimeoutException) - { - throw new ConnectTimeoutException("Connect timed out after " + timeout + " msec"); - } - Debug.Assert(ins.pos() == IceInternal.Protocol.headerSize); - ins.pos(0); - byte[] m = ins.readBlob(4); - if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] || - m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3]) - { - BadMagicException ex = new BadMagicException(); - ex.badMagic = m; - throw ex; - } - byte pMajor = ins.readByte(); - byte pMinor = ins.readByte(); - if(pMajor != IceInternal.Protocol.protocolMajor) - { - UnsupportedProtocolException e = new UnsupportedProtocolException(); - e.badMajor = pMajor < 0 ? pMajor + 255 : pMajor; - e.badMinor = pMinor < 0 ? pMinor + 255 : pMinor; - e.major = IceInternal.Protocol.protocolMajor; - e.minor = IceInternal.Protocol.protocolMinor; - throw e; - } - byte eMajor = ins.readByte(); - byte eMinor = ins.readByte(); - if(eMajor != IceInternal.Protocol.encodingMajor) - { - UnsupportedEncodingException e = new UnsupportedEncodingException(); - e.badMajor = eMajor < 0 ? eMajor + 255 : eMajor; - e.badMinor = eMinor < 0 ? eMinor + 255 : eMinor; - e.major = IceInternal.Protocol.encodingMajor; - e.minor = IceInternal.Protocol.encodingMinor; - throw e; - } - byte messageType = ins.readByte(); - if(messageType != IceInternal.Protocol.validateConnectionMsg) - { - throw new ConnectionNotValidatedException(); - } - ins.readByte(); // Ignore compression status for validate connection. - int size = ins.readInt(); - if(size != IceInternal.Protocol.headerSize) - { - throw new IllegalMessageSizeException(); - } - IceInternal.TraceUtil.traceHeader("received validate connection", ins, _logger, _traceLevels); - } - } - catch(LocalException ex) - { - lock(this) - { - setState(StateClosed, ex); - Debug.Assert(_exception != null); - throw _exception; - } - } - } - - lock(this) - { - if(_acmTimeout > 0) - { - _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; - } - - // - // We start out in holding state. - // - setState(StateHolding); - } - } - - public void activate() - { - lock(this) - { - while(_state == StateNotValidated) - { - Monitor.Wait(this); - } - - setState(StateActive); - } - } - - public void hold() - { - lock(this) - { - while(_state == StateNotValidated) - { - Monitor.Wait(this); - } - - setState(StateHolding); - } - } - - // DestructionReason. - public const int ObjectAdapterDeactivated = 0; - public const int CommunicatorDestroyed = 1; - - public void destroy(int reason) - { - lock(this) - { - switch(reason) - { - case ObjectAdapterDeactivated: - { - setState(StateClosing, new ObjectAdapterDeactivatedException()); - break; - } - - case CommunicatorDestroyed: - { - setState(StateClosing, new CommunicatorDestroyedException()); - break; - } - } - } - } - - public void close(bool force) - { - lock(this) - { - if(force) - { - setState(StateClosed, new ForcedCloseConnectionException()); - } - else - { - // - // If we do a graceful shutdown, then we wait until all - // outstanding requests have been completed. Otherwise, - // the CloseConnectionException will cause all outstanding - // requests to be retried, regardless of whether the - // server has processed them or not. - // - while(_requests.Count != 0 || _asyncRequests.Count != 0) - { - Monitor.Wait(this); - } - - setState(StateClosing, new CloseConnectionException()); - } - } - } - - public bool isDestroyed() - { - lock(this) - { - return _state >= StateClosing; - } - } - - public bool isFinished() - { - Thread threadPerConnection; - - // - // We can use TryEnter here, because as long as there are still - // threads operating in this connection object, connection - // destruction is considered as not yet finished. - // - if(!Monitor.TryEnter(this)) - { - return false; - } - - try - { - if(_transceiver != null || _dispatchCount != 0 || (_thread != null && _thread.IsAlive)) - { - return false; - } - - Debug.Assert(_state == StateClosed); - - threadPerConnection = _thread; - _thread = null; - } - finally - { - Monitor.Exit(this); - } - - if(threadPerConnection != null) - { - threadPerConnection.Join(); - } - - return true; - } - - public void throwException() - { - lock(this) - { - if(_exception != null) - { - Debug.Assert(_state >= StateClosing); - throw _exception; - } - } - } - - public void waitUntilHolding() - { - lock(this) - { - while(_state < StateHolding || _dispatchCount > 0) - { - Monitor.Wait(this); - } - } - } - - public void waitUntilFinished() - { - Thread threadPerConnection; - - lock(this) - { - // - // We wait indefinitely until connection closing has been - // initiated. We also wait indefinitely until all outstanding - // requests are completed. Otherwise we couldn't guarantee - // that there are no outstanding calls when deactivate() is - // called on the servant locators. - // - while(_state < StateClosing || _dispatchCount > 0) - { - Monitor.Wait(this); - } - - // - // Now we must wait until close() has been called on the - // transceiver. - // - while(_transceiver != null) - { - if(_state != StateClosed && _endpoint.timeout() >= 0) - { - long absoluteWaitTime = _stateTime + _endpoint.timeout(); - int waitTime = (int)(absoluteWaitTime - System.DateTime.Now.Ticks / 10000); - - if(waitTime > 0) - { - // - // We must wait a bit longer until we close - // this connection. - // - Monitor.Wait(this, waitTime); - if(System.DateTime.Now.Ticks / 10000 >= absoluteWaitTime) - { - setState(StateClosed, new CloseTimeoutException()); - } - } - else - { - // - // We already waited long enough, so let's - // close this connection! - // - setState(StateClosed, new CloseTimeoutException()); - } - - // - // No return here, we must still wait until - // close() is called on the _transceiver. - // - } - else - { - Monitor.Wait(this); - } - } - - Debug.Assert(_state == StateClosed); - - threadPerConnection = _thread; - _thread = null; + _transceiver.read(ins, timeout); + } + catch(TimeoutException) + { + throw new ConnectTimeoutException("Connect timed out after " + timeout + " msec"); + } + Debug.Assert(ins.pos() == IceInternal.Protocol.headerSize); + ins.pos(0); + byte[] m = ins.readBlob(4); + if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] || + m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3]) + { + BadMagicException ex = new BadMagicException(); + ex.badMagic = m; + throw ex; + } + byte pMajor = ins.readByte(); + byte pMinor = ins.readByte(); + if(pMajor != IceInternal.Protocol.protocolMajor) + { + UnsupportedProtocolException e = new UnsupportedProtocolException(); + e.badMajor = pMajor < 0 ? pMajor + 255 : pMajor; + e.badMinor = pMinor < 0 ? pMinor + 255 : pMinor; + e.major = IceInternal.Protocol.protocolMajor; + e.minor = IceInternal.Protocol.protocolMinor; + throw e; + } + byte eMajor = ins.readByte(); + byte eMinor = ins.readByte(); + if(eMajor != IceInternal.Protocol.encodingMajor) + { + UnsupportedEncodingException e = new UnsupportedEncodingException(); + e.badMajor = eMajor < 0 ? eMajor + 255 : eMajor; + e.badMinor = eMinor < 0 ? eMinor + 255 : eMinor; + e.major = IceInternal.Protocol.encodingMajor; + e.minor = IceInternal.Protocol.encodingMinor; + throw e; + } + byte messageType = ins.readByte(); + if(messageType != IceInternal.Protocol.validateConnectionMsg) + { + throw new ConnectionNotValidatedException(); + } + ins.readByte(); // Ignore compression status for validate connection. + int size = ins.readInt(); + if(size != IceInternal.Protocol.headerSize) + { + throw new IllegalMessageSizeException(); + } + IceInternal.TraceUtil.traceHeader("received validate connection", ins, _logger, _traceLevels); + } + } + catch(LocalException ex) + { + lock(this) + { + setState(StateClosed, ex); + Debug.Assert(_exception != null); + throw _exception; + } + } + } + + lock(this) + { + if(_acmTimeout > 0) + { + _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; + } + + // + // We start out in holding state. + // + setState(StateHolding); + } + } + + public void activate() + { + lock(this) + { + while(_state == StateNotValidated) + { + Monitor.Wait(this); + } + + setState(StateActive); + } + } + + public void hold() + { + lock(this) + { + while(_state == StateNotValidated) + { + Monitor.Wait(this); + } + + setState(StateHolding); + } + } + + // DestructionReason. + public const int ObjectAdapterDeactivated = 0; + public const int CommunicatorDestroyed = 1; + + public void destroy(int reason) + { + lock(this) + { + switch(reason) + { + case ObjectAdapterDeactivated: + { + setState(StateClosing, new ObjectAdapterDeactivatedException()); + break; + } + + case CommunicatorDestroyed: + { + setState(StateClosing, new CommunicatorDestroyedException()); + break; + } + } + } + } + + public void close(bool force) + { + lock(this) + { + if(force) + { + setState(StateClosed, new ForcedCloseConnectionException()); + } + else + { + // + // If we do a graceful shutdown, then we wait until all + // outstanding requests have been completed. Otherwise, + // the CloseConnectionException will cause all outstanding + // requests to be retried, regardless of whether the + // server has processed them or not. + // + while(_requests.Count != 0 || _asyncRequests.Count != 0) + { + Monitor.Wait(this); + } + + setState(StateClosing, new CloseConnectionException()); + } + } + } + + public bool isDestroyed() + { + lock(this) + { + return _state >= StateClosing; + } + } + + public bool isFinished() + { + Thread threadPerConnection; + + // + // We can use TryEnter here, because as long as there are still + // threads operating in this connection object, connection + // destruction is considered as not yet finished. + // + if(!Monitor.TryEnter(this)) + { + return false; + } + + try + { + if(_transceiver != null || _dispatchCount != 0 || (_thread != null && _thread.IsAlive)) + { + return false; + } + + Debug.Assert(_state == StateClosed); + + threadPerConnection = _thread; + _thread = null; + } + finally + { + Monitor.Exit(this); + } + + if(threadPerConnection != null) + { + threadPerConnection.Join(); + } + + return true; + } + + public void throwException() + { + lock(this) + { + if(_exception != null) + { + Debug.Assert(_state >= StateClosing); + throw _exception; + } + } + } + + public void waitUntilHolding() + { + lock(this) + { + while(_state < StateHolding || _dispatchCount > 0) + { + Monitor.Wait(this); + } + } + } + + public void waitUntilFinished() + { + Thread threadPerConnection; + + lock(this) + { + // + // We wait indefinitely until connection closing has been + // initiated. We also wait indefinitely until all outstanding + // requests are completed. Otherwise we couldn't guarantee + // that there are no outstanding calls when deactivate() is + // called on the servant locators. + // + while(_state < StateClosing || _dispatchCount > 0) + { + Monitor.Wait(this); + } + + // + // Now we must wait until close() has been called on the + // transceiver. + // + while(_transceiver != null) + { + if(_state != StateClosed && _endpoint.timeout() >= 0) + { + long absoluteWaitTime = _stateTime + _endpoint.timeout(); + int waitTime = (int)(absoluteWaitTime - System.DateTime.Now.Ticks / 10000); + + if(waitTime > 0) + { + // + // We must wait a bit longer until we close + // this connection. + // + Monitor.Wait(this, waitTime); + if(System.DateTime.Now.Ticks / 10000 >= absoluteWaitTime) + { + setState(StateClosed, new CloseTimeoutException()); + } + } + else + { + // + // We already waited long enough, so let's + // close this connection! + // + setState(StateClosed, new CloseTimeoutException()); + } + + // + // No return here, we must still wait until + // close() is called on the _transceiver. + // + } + else + { + Monitor.Wait(this); + } + } + + Debug.Assert(_state == StateClosed); + + threadPerConnection = _thread; + _thread = null; // // Clear the OA. See bug 1673 for the details of why this is necessary. // _adapter = null; - } - - if(threadPerConnection != null) - { - threadPerConnection.Join(); - } - } - - public void monitor() - { - if(!Monitor.TryEnter(this)) - { - return; - } - - try - { - if(_state != StateActive) - { - return; - } - - // - // Check for timed out async requests. - // - foreach(IceInternal.OutgoingAsync og in _asyncRequests.Values) - { - if(og.timedOut__()) - { - setState(StateClosed, new TimeoutException()); - return; - } - } - - // - // Active connection management for idle connections. - // - // - if(_acmTimeout > 0 && - _requests.Count == 0 && _asyncRequests.Count == 0 && - !_batchStreamInUse && _batchStream.isEmpty() && - _dispatchCount == 0) - { - if(System.DateTime.Now.Ticks / 10000 >= _acmAbsoluteTimeoutMillis) - { - setState(StateClosing, new ConnectionTimeoutException()); - return; - } - } - } - finally - { - Monitor.Exit(this); - } - } - - private IceInternal.BasicStream doCompress(IceInternal.BasicStream uncompressed, bool compress) - { - if(_compressionSupported) - { - if(compress && uncompressed.size() >= 100) - { - // - // Do compression. - // - IceInternal.BasicStream cstream = null; - if(uncompressed.compress(ref cstream, IceInternal.Protocol.headerSize, _compressionLevel)) - { - // - // Set compression status. - // - cstream.pos(9); - cstream.writeByte((byte)2); - - // - // Write the size of the compressed stream into the header. - // - cstream.pos(10); - cstream.writeInt(cstream.size()); - - // - // Write the compression status and size of the compressed stream into the header of the - // uncompressed stream -- we need this to trace requests correctly. - // - uncompressed.pos(9); - uncompressed.writeByte((byte)2); - uncompressed.writeInt(cstream.size()); - - return cstream; - } - } - } - - uncompressed.pos(9); - uncompressed.writeByte((byte)((_compressionSupported && compress) ? 1 : 0)); - - // - // Not compressed, fill in the message size. - // - uncompressed.pos(10); - uncompressed.writeInt(uncompressed.size()); - - return uncompressed; - } - - /* - private class MessageInfo - { - MessageInfo(IceInternal.BasicStream stream) - { - this.stream = stream; - } - - IceInternal.BasicStream stream; - bool destroyStream; - int invokeNum; - int requestId; - byte compress; - IceInternal.ServantManager servantManager; - ObjectAdapter adapter; - IceInternal.OutgoingAsync outAsync; - } + } + + if(threadPerConnection != null) + { + threadPerConnection.Join(); + } + } + + public void monitor() + { + if(!Monitor.TryEnter(this)) + { + return; + } + + try + { + if(_state != StateActive) + { + return; + } + + // + // Check for timed out async requests. + // + foreach(IceInternal.OutgoingAsync og in _asyncRequests.Values) + { + if(og.timedOut__()) + { + setState(StateClosed, new TimeoutException()); + return; + } + } + + // + // Active connection management for idle connections. + // + // + if(_acmTimeout > 0 && + _requests.Count == 0 && _asyncRequests.Count == 0 && + !_batchStreamInUse && _batchStream.isEmpty() && + _dispatchCount == 0) + { + if(System.DateTime.Now.Ticks / 10000 >= _acmAbsoluteTimeoutMillis) + { + setState(StateClosing, new ConnectionTimeoutException()); + return; + } + } + } + finally + { + Monitor.Exit(this); + } + } + + private IceInternal.BasicStream doCompress(IceInternal.BasicStream uncompressed, bool compress) + { + if(_compressionSupported) + { + if(compress && uncompressed.size() >= 100) + { + // + // Do compression. + // + IceInternal.BasicStream cstream = null; + if(uncompressed.compress(ref cstream, IceInternal.Protocol.headerSize, _compressionLevel)) + { + // + // Set compression status. + // + cstream.pos(9); + cstream.writeByte((byte)2); + + // + // Write the size of the compressed stream into the header. + // + cstream.pos(10); + cstream.writeInt(cstream.size()); + + // + // Write the compression status and size of the compressed stream into the header of the + // uncompressed stream -- we need this to trace requests correctly. + // + uncompressed.pos(9); + uncompressed.writeByte((byte)2); + uncompressed.writeInt(cstream.size()); + + return cstream; + } + } + } + + uncompressed.pos(9); + uncompressed.writeByte((byte)((_compressionSupported && compress) ? 1 : 0)); + + // + // Not compressed, fill in the message size. + // + uncompressed.pos(10); + uncompressed.writeInt(uncompressed.size()); + + return uncompressed; + } + + /* + private class MessageInfo + { + MessageInfo(IceInternal.BasicStream stream) + { + this.stream = stream; + } + + IceInternal.BasicStream stream; + bool destroyStream; + int invokeNum; + int requestId; + byte compress; + IceInternal.ServantManager servantManager; + ObjectAdapter adapter; + IceInternal.OutgoingAsync outAsync; + } */ - public void sendRequest(IceInternal.BasicStream os, IceInternal.Outgoing og, bool compress) - { - int requestId = 0; - IceInternal.BasicStream stream = null; - - lock(this) - { - Debug.Assert(!(og != null && _endpoint.datagram())); // Twoway requests cannot be datagrams. - - if(_exception != null) - { - // - // If the connection is closed before we even have a chance - // to send our request, we always try to send the request - // again. - // - throw new IceInternal.LocalExceptionWrapper(_exception, true); - } - - Debug.Assert(_state > StateNotValidated); - Debug.Assert(_state < StateClosing); - - // - // Only add to the request map if this is a twoway call. - // - if(og != null) - { - // - // Create a new unique request ID. - // - requestId = _nextRequestId++; - if(requestId <= 0) - { - _nextRequestId = 1; - requestId = _nextRequestId++; - } - - // - // Fill in the request ID. - // - os.pos(IceInternal.Protocol.headerSize); - os.writeInt(requestId); - - // - // Add to the requests map. - // - _requests[requestId] = og; - } - - stream = doCompress(os, _overrideCompress ? _overrideCompressValue : compress); - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; - } - } - - try - { - lock(_sendMutex) - { - if(_transceiver == null) // Has the transceiver already been closed? - { - Debug.Assert(_exception != null); - throw _exception; // The exception is immutable at this point. - } - - // - // Send the request. - // - IceInternal.TraceUtil.traceRequest("sending request", os, _logger, _traceLevels); - _transceiver.write(stream, _endpoint.timeout()); - } - } - catch(LocalException ex) - { - lock(this) - { - setState(StateClosed, ex); - Debug.Assert(_exception != null); - - if(og != null) - { - // - // If the request has already been removed from - // the request map, we are out of luck. It would - // mean that finished() has been called already, - // and therefore the exception has been set using - // the Outgoing::finished() callback. In this - // case, we cannot throw the exception here, - // because we must not both raise an exception and - // have Outgoing::finished() called with an - // exception. This means that in some rare cases, - // a request will not be retried even though it - // could. But I honestly don't know how I could - // avoid this, without a very elaborate and - // complex design, which would be bad for - // performance. - // - IceInternal.Outgoing o = (IceInternal.Outgoing)_requests[requestId]; - _requests.Remove(requestId); - if(o != null) - { - Debug.Assert(o == og); - throw _exception; - } - } - else - { - throw _exception; - } - } - } - } - - public void sendAsyncRequest(IceInternal.BasicStream os, IceInternal.OutgoingAsync og, bool compress) - { - int requestId = 0; - IceInternal.BasicStream stream = null; - - lock(this) - { - Debug.Assert(!_endpoint.datagram()); // Twoway requests cannot be datagrams, and async implies twoway. - - if(_exception != null) - { - // - // If the connection is closed before we even have a chance - // to send our request, we always try to send the request - // again. - // - throw new IceInternal.LocalExceptionWrapper(_exception, true); - } - - Debug.Assert(_state > StateNotValidated); - Debug.Assert(_state < StateClosing); - - // - // Create a new unique request ID. - // - requestId = _nextRequestId++; - if(requestId <= 0) - { - _nextRequestId = 1; - requestId = _nextRequestId++; - } - - // - // Fill in the request ID. - // - os.pos(IceInternal.Protocol.headerSize); - os.writeInt(requestId); - - // - // Add to the async requests map. - // - _asyncRequests[requestId] = og; - - stream = doCompress(os, _overrideCompress ? _overrideCompressValue : compress); - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; - } - } - - try - { - lock(_sendMutex) - { - if(_transceiver == null) // Has the transceiver already been closed? - { - Debug.Assert(_exception != null); - throw _exception; // The exception is imuutable at this point. - } - - // - // Send the request. - // - IceInternal.TraceUtil.traceRequest("sending asynchronous request", os, _logger, _traceLevels); - _transceiver.write(stream, _endpoint.timeout()); - } - } - catch(LocalException ex) - { - lock(this) - { - setState(StateClosed, ex); - Debug.Assert(_exception != null); - - // - // If the request has already been removed from the - // async request map, we are out of luck. It would - // mean that finished() has been called already, and - // therefore the exception has been set using the - // OutgoingAsync::finished__() callback. In this case, - // we cannot throw the exception here, because we must - // not both raise an exception and have - // OutgoingAsync::finished__() called with an - // exception. This means that in some rare cases, a - // request will not be retried even though it - // could. But I honestly don't know how I could avoid - // this, without a very elaborate and complex design, - // which would be bad for performance. - // - IceInternal.OutgoingAsync o = (IceInternal.OutgoingAsync)_asyncRequests[requestId]; - _asyncRequests.Remove(requestId); - if(o != null) - { - Debug.Assert(o == og); - throw _exception; - } - } - } - } - - public void prepareBatchRequest(IceInternal.BasicStream os) - { - lock(this) - { - // - // Wait if flushing is currently in progress. - // - while(_batchStreamInUse && _exception == null) - { - Monitor.Wait(this); - } - - if(_exception != null) - { - throw _exception; - } - - Debug.Assert(_state > StateNotValidated); - Debug.Assert(_state < StateClosing); - - if(_batchStream.isEmpty()) - { - try - { - _batchStream.writeBlob(IceInternal.Protocol.requestBatchHdr); - } - catch(LocalException ex) - { - setState(StateClosed, ex); - throw; - } - } - - _batchStreamInUse = true; - _batchMarker = _batchStream.size(); - _batchStream.swap(os); - - // - // The batch stream now belongs to the caller, until - // finishBatchRequest() or abortBatchRequest() is called. - // - } - } - - public void finishBatchRequest(IceInternal.BasicStream os, bool compress) - { - bool autoflush = false; - byte[] lastRequest = null; - - lock(this) - { - // - // Get the batch stream back. - // - _batchStream.swap(os); - - if(_batchAutoFlush) - { - lock(_sendMutex) - { - if(_transceiver == null) - { - Debug.Assert(_exception != null); - throw _exception; // The exception is immutable at this point. - } - // - // Throw memory limit exception if the first - // message added causes us to go over - // limit. Otherwise put aside the marshalled - // message that caused limit to be exceeded and - // rollback stream to the marker. - // - try - { - _transceiver.checkSendSize(_batchStream, instance_.messageSizeMax()); - } - catch(Ice.LocalException ex) - { - if(_batchRequestNum == 0) - { - resetBatch(true); - throw ex; - } - int requestSize = _batchStream.size() - _batchMarker; - lastRequest = new byte[requestSize]; - Buffer.BlockCopy(_batchStream.prepareRead().rawBytes(), _batchMarker, lastRequest, 0, - requestSize); - _batchStream.resize(_batchMarker, false); - autoflush = true; - } - } - } - if(!autoflush) - { - // - // Increment the number of requests in the batch. - // - ++_batchRequestNum; - - // - // We compress the whole batch if there is at least - // one compressed message. - // - if(compress) - { - _batchRequestCompress = true; - } - - // - // Notify about the batch stream not being in use anymore. - // - Debug.Assert(_batchStreamInUse); - _batchStreamInUse = false; - Monitor.PulseAll(this); - } - } - - if(autoflush) - { - // - // We have to keep _batchStreamInUse set until after we insert the - // saved marshalled data into a new stream. - // - flushBatchRequestsInternal(true); - - lock(this) - { - // - // Throw memory limit exception if the message that caused us to go over - // limit causes us to exceed the limit by itself. - // - if(IceInternal.Protocol.requestBatchHdr.Length + lastRequest.Length > instance_.messageSizeMax()) - { - resetBatch(true); - throw new MemoryLimitException(); - } - - // - // Start a new batch with the last message that caused us to - // go over the limit. - // - try - { - _batchStream.writeBlob(IceInternal.Protocol.requestBatchHdr); - _batchStream.writeBlob(lastRequest); - } - catch(LocalException ex) - { - setState(StateClosed, ex); - throw; - } - - if(compress) - { - _batchRequestCompress = true; - } - - // - // Notify that the batch stream not in use anymore. - // - ++_batchRequestNum; - _batchStreamInUse = false; - Monitor.PulseAll(this); - } - } - } - - public void abortBatchRequest() - { - lock(this) - { - // - // Reset the batch stream. We cannot save old requests - // in the batch stream, as they might be corrupted due to - // incomplete marshaling. - // - resetBatch(true); - } - } - - public void flushBatchRequests() - { - flushBatchRequestsInternal(false); - } - - private void flushBatchRequestsInternal(bool ignoreInUse) - { - IceInternal.BasicStream stream = null; - - lock(this) - { - if(!ignoreInUse) - { - while(_batchStreamInUse && _exception == null) - { - Monitor.Wait(this); - } - } - - if(_exception != null) - { - throw _exception; - } - - if(_batchStream.isEmpty()) - { - return; // Nothing to do. - } - - Debug.Assert(_state > StateNotValidated); - Debug.Assert(_state < StateClosing); - - // - // Fill in the message size. - // - _batchStream.pos(10); - _batchStream.writeInt(_batchStream.size()); - - // - // Fill in the number of requests in the batch. - // - _batchStream.writeInt(_batchRequestNum); - - stream = doCompress(_batchStream, _overrideCompress ? _overrideCompressValue : _batchRequestCompress); - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; - } - - // - // Prevent that new batch requests are added while we are - // flushing. - // - _batchStreamInUse = true; - } - - try - { - lock(_sendMutex) - { - if(_transceiver == null) // Has the transceiver already been closed? - { - Debug.Assert(_exception != null); - throw _exception; // The exception is immutable at this point. - } - - // - // Send the batch request. - // - IceInternal.TraceUtil.traceBatchRequest("sending batch request", _batchStream, _logger, - _traceLevels); - _transceiver.write(stream, _endpoint.timeout()); - } - } - catch(LocalException ex) - { - lock(this) - { - setState(StateClosed, ex); - Debug.Assert(_exception != null); - - // - // Since batch requests area all oneways (or datarams), we - // must report the exception to the caller. - // - throw _exception; - } - } - - lock(this) - { - // - // Reset the batch stream, and notify that flushing is over. - // - resetBatch(!ignoreInUse); - } - } - - - private void resetBatch(bool resetInUse) - { - _batchStream = new IceInternal.BasicStream(instance_, _batchAutoFlush); - _batchRequestNum = 0; - _batchRequestCompress = false; - - // - // Notify about the batch stream not being in use - // anymore. - // - if(resetInUse) - { - Debug.Assert(_batchStreamInUse); - _batchStreamInUse = false; - Monitor.PulseAll(this); - } - } - - public void sendResponse(IceInternal.BasicStream os, byte compress) - { - IceInternal.BasicStream stream = null; - try - { - lock(_sendMutex) - { - if(_transceiver == null) // Has the transceiver already been closed? - { - Debug.Assert(_exception != null); - throw _exception; // The exception is immutable at this point. - } - - stream = doCompress(os, compress != 0); - - // - // Send the reply. - // - IceInternal.TraceUtil.traceReply("sending reply", os, _logger, _traceLevels); - _transceiver.write(stream, _endpoint.timeout()); - } - } - catch(LocalException ex) - { - lock(this) - { - setState(StateClosed, ex); - } - } - - lock(this) - { - Debug.Assert(_state > StateNotValidated); - - try - { - if(--_dispatchCount == 0) - { - Monitor.PulseAll(this); - } - - if(_state == StateClosing && _dispatchCount == 0) - { - initiateShutdown(); - } - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; - } - } - catch(LocalException ex) - { - setState(StateClosed, ex); - } - } - } - - public void sendNoResponse() - { - lock(this) - { - Debug.Assert(_state > StateNotValidated); - - try - { - if(--_dispatchCount == 0) - { - Monitor.PulseAll(this); - } - - if(_state == StateClosing && _dispatchCount == 0) - { - initiateShutdown(); - } - } - catch(LocalException ex) - { - setState(StateClosed, ex); - } - } - } - - public IceInternal.EndpointI endpoint() - { - // No mutex protection necessary, _endpoint is immutable. - return _endpoint; - } + public void sendRequest(IceInternal.BasicStream os, IceInternal.Outgoing og, bool compress) + { + int requestId = 0; + IceInternal.BasicStream stream = null; + + lock(this) + { + Debug.Assert(!(og != null && _endpoint.datagram())); // Twoway requests cannot be datagrams. + + if(_exception != null) + { + // + // If the connection is closed before we even have a chance + // to send our request, we always try to send the request + // again. + // + throw new IceInternal.LocalExceptionWrapper(_exception, true); + } + + Debug.Assert(_state > StateNotValidated); + Debug.Assert(_state < StateClosing); + + // + // Only add to the request map if this is a twoway call. + // + if(og != null) + { + // + // Create a new unique request ID. + // + requestId = _nextRequestId++; + if(requestId <= 0) + { + _nextRequestId = 1; + requestId = _nextRequestId++; + } + + // + // Fill in the request ID. + // + os.pos(IceInternal.Protocol.headerSize); + os.writeInt(requestId); + + // + // Add to the requests map. + // + _requests[requestId] = og; + } + + stream = doCompress(os, _overrideCompress ? _overrideCompressValue : compress); + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; + } + } + + try + { + lock(_sendMutex) + { + if(_transceiver == null) // Has the transceiver already been closed? + { + Debug.Assert(_exception != null); + throw _exception; // The exception is immutable at this point. + } + + // + // Send the request. + // + IceInternal.TraceUtil.traceRequest("sending request", os, _logger, _traceLevels); + _transceiver.write(stream, _endpoint.timeout()); + } + } + catch(LocalException ex) + { + lock(this) + { + setState(StateClosed, ex); + Debug.Assert(_exception != null); + + if(og != null) + { + // + // If the request has already been removed from + // the request map, we are out of luck. It would + // mean that finished() has been called already, + // and therefore the exception has been set using + // the Outgoing::finished() callback. In this + // case, we cannot throw the exception here, + // because we must not both raise an exception and + // have Outgoing::finished() called with an + // exception. This means that in some rare cases, + // a request will not be retried even though it + // could. But I honestly don't know how I could + // avoid this, without a very elaborate and + // complex design, which would be bad for + // performance. + // + IceInternal.Outgoing o = (IceInternal.Outgoing)_requests[requestId]; + _requests.Remove(requestId); + if(o != null) + { + Debug.Assert(o == og); + throw _exception; + } + } + else + { + throw _exception; + } + } + } + } + + public void sendAsyncRequest(IceInternal.BasicStream os, IceInternal.OutgoingAsync og, bool compress) + { + int requestId = 0; + IceInternal.BasicStream stream = null; + + lock(this) + { + Debug.Assert(!_endpoint.datagram()); // Twoway requests cannot be datagrams, and async implies twoway. + + if(_exception != null) + { + // + // If the connection is closed before we even have a chance + // to send our request, we always try to send the request + // again. + // + throw new IceInternal.LocalExceptionWrapper(_exception, true); + } + + Debug.Assert(_state > StateNotValidated); + Debug.Assert(_state < StateClosing); + + // + // Create a new unique request ID. + // + requestId = _nextRequestId++; + if(requestId <= 0) + { + _nextRequestId = 1; + requestId = _nextRequestId++; + } + + // + // Fill in the request ID. + // + os.pos(IceInternal.Protocol.headerSize); + os.writeInt(requestId); + + // + // Add to the async requests map. + // + _asyncRequests[requestId] = og; + + stream = doCompress(os, _overrideCompress ? _overrideCompressValue : compress); + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; + } + } + + try + { + lock(_sendMutex) + { + if(_transceiver == null) // Has the transceiver already been closed? + { + Debug.Assert(_exception != null); + throw _exception; // The exception is imuutable at this point. + } + + // + // Send the request. + // + IceInternal.TraceUtil.traceRequest("sending asynchronous request", os, _logger, _traceLevels); + _transceiver.write(stream, _endpoint.timeout()); + } + } + catch(LocalException ex) + { + lock(this) + { + setState(StateClosed, ex); + Debug.Assert(_exception != null); + + // + // If the request has already been removed from the + // async request map, we are out of luck. It would + // mean that finished() has been called already, and + // therefore the exception has been set using the + // OutgoingAsync::finished__() callback. In this case, + // we cannot throw the exception here, because we must + // not both raise an exception and have + // OutgoingAsync::finished__() called with an + // exception. This means that in some rare cases, a + // request will not be retried even though it + // could. But I honestly don't know how I could avoid + // this, without a very elaborate and complex design, + // which would be bad for performance. + // + IceInternal.OutgoingAsync o = (IceInternal.OutgoingAsync)_asyncRequests[requestId]; + _asyncRequests.Remove(requestId); + if(o != null) + { + Debug.Assert(o == og); + throw _exception; + } + } + } + } + + public void prepareBatchRequest(IceInternal.BasicStream os) + { + lock(this) + { + // + // Wait if flushing is currently in progress. + // + while(_batchStreamInUse && _exception == null) + { + Monitor.Wait(this); + } + + if(_exception != null) + { + throw _exception; + } + + Debug.Assert(_state > StateNotValidated); + Debug.Assert(_state < StateClosing); + + if(_batchStream.isEmpty()) + { + try + { + _batchStream.writeBlob(IceInternal.Protocol.requestBatchHdr); + } + catch(LocalException ex) + { + setState(StateClosed, ex); + throw; + } + } + + _batchStreamInUse = true; + _batchMarker = _batchStream.size(); + _batchStream.swap(os); + + // + // The batch stream now belongs to the caller, until + // finishBatchRequest() or abortBatchRequest() is called. + // + } + } + + public void finishBatchRequest(IceInternal.BasicStream os, bool compress) + { + bool autoflush = false; + byte[] lastRequest = null; + + lock(this) + { + // + // Get the batch stream back. + // + _batchStream.swap(os); + + if(_batchAutoFlush) + { + lock(_sendMutex) + { + if(_transceiver == null) + { + Debug.Assert(_exception != null); + throw _exception; // The exception is immutable at this point. + } + // + // Throw memory limit exception if the first + // message added causes us to go over + // limit. Otherwise put aside the marshalled + // message that caused limit to be exceeded and + // rollback stream to the marker. + // + try + { + _transceiver.checkSendSize(_batchStream, instance_.messageSizeMax()); + } + catch(Ice.LocalException ex) + { + if(_batchRequestNum == 0) + { + resetBatch(true); + throw ex; + } + int requestSize = _batchStream.size() - _batchMarker; + lastRequest = new byte[requestSize]; + Buffer.BlockCopy(_batchStream.prepareRead().rawBytes(), _batchMarker, lastRequest, 0, + requestSize); + _batchStream.resize(_batchMarker, false); + autoflush = true; + } + } + } + if(!autoflush) + { + // + // Increment the number of requests in the batch. + // + ++_batchRequestNum; + + // + // We compress the whole batch if there is at least + // one compressed message. + // + if(compress) + { + _batchRequestCompress = true; + } + + // + // Notify about the batch stream not being in use anymore. + // + Debug.Assert(_batchStreamInUse); + _batchStreamInUse = false; + Monitor.PulseAll(this); + } + } + + if(autoflush) + { + // + // We have to keep _batchStreamInUse set until after we insert the + // saved marshalled data into a new stream. + // + flushBatchRequestsInternal(true); + + lock(this) + { + // + // Throw memory limit exception if the message that caused us to go over + // limit causes us to exceed the limit by itself. + // + if(IceInternal.Protocol.requestBatchHdr.Length + lastRequest.Length > instance_.messageSizeMax()) + { + resetBatch(true); + throw new MemoryLimitException(); + } + + // + // Start a new batch with the last message that caused us to + // go over the limit. + // + try + { + _batchStream.writeBlob(IceInternal.Protocol.requestBatchHdr); + _batchStream.writeBlob(lastRequest); + } + catch(LocalException ex) + { + setState(StateClosed, ex); + throw; + } + + if(compress) + { + _batchRequestCompress = true; + } + + // + // Notify that the batch stream not in use anymore. + // + ++_batchRequestNum; + _batchStreamInUse = false; + Monitor.PulseAll(this); + } + } + } + + public void abortBatchRequest() + { + lock(this) + { + // + // Reset the batch stream. We cannot save old requests + // in the batch stream, as they might be corrupted due to + // incomplete marshaling. + // + resetBatch(true); + } + } + + public void flushBatchRequests() + { + flushBatchRequestsInternal(false); + } + + private void flushBatchRequestsInternal(bool ignoreInUse) + { + IceInternal.BasicStream stream = null; + + lock(this) + { + if(!ignoreInUse) + { + while(_batchStreamInUse && _exception == null) + { + Monitor.Wait(this); + } + } + + if(_exception != null) + { + throw _exception; + } + + if(_batchStream.isEmpty()) + { + return; // Nothing to do. + } + + Debug.Assert(_state > StateNotValidated); + Debug.Assert(_state < StateClosing); + + // + // Fill in the message size. + // + _batchStream.pos(10); + _batchStream.writeInt(_batchStream.size()); + + // + // Fill in the number of requests in the batch. + // + _batchStream.writeInt(_batchRequestNum); + + stream = doCompress(_batchStream, _overrideCompress ? _overrideCompressValue : _batchRequestCompress); + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; + } + + // + // Prevent that new batch requests are added while we are + // flushing. + // + _batchStreamInUse = true; + } + + try + { + lock(_sendMutex) + { + if(_transceiver == null) // Has the transceiver already been closed? + { + Debug.Assert(_exception != null); + throw _exception; // The exception is immutable at this point. + } + + // + // Send the batch request. + // + IceInternal.TraceUtil.traceBatchRequest("sending batch request", _batchStream, _logger, + _traceLevels); + _transceiver.write(stream, _endpoint.timeout()); + } + } + catch(LocalException ex) + { + lock(this) + { + setState(StateClosed, ex); + Debug.Assert(_exception != null); + + // + // Since batch requests area all oneways (or datarams), we + // must report the exception to the caller. + // + throw _exception; + } + } + + lock(this) + { + // + // Reset the batch stream, and notify that flushing is over. + // + resetBatch(!ignoreInUse); + } + } + + + private void resetBatch(bool resetInUse) + { + _batchStream = new IceInternal.BasicStream(instance_, _batchAutoFlush); + _batchRequestNum = 0; + _batchRequestCompress = false; + + // + // Notify about the batch stream not being in use + // anymore. + // + if(resetInUse) + { + Debug.Assert(_batchStreamInUse); + _batchStreamInUse = false; + Monitor.PulseAll(this); + } + } + + public void sendResponse(IceInternal.BasicStream os, byte compress) + { + IceInternal.BasicStream stream = null; + try + { + lock(_sendMutex) + { + if(_transceiver == null) // Has the transceiver already been closed? + { + Debug.Assert(_exception != null); + throw _exception; // The exception is immutable at this point. + } + + stream = doCompress(os, compress != 0); + + // + // Send the reply. + // + IceInternal.TraceUtil.traceReply("sending reply", os, _logger, _traceLevels); + _transceiver.write(stream, _endpoint.timeout()); + } + } + catch(LocalException ex) + { + lock(this) + { + setState(StateClosed, ex); + } + } + + lock(this) + { + Debug.Assert(_state > StateNotValidated); + + try + { + if(--_dispatchCount == 0) + { + Monitor.PulseAll(this); + } + + if(_state == StateClosing && _dispatchCount == 0) + { + initiateShutdown(); + } + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; + } + } + catch(LocalException ex) + { + setState(StateClosed, ex); + } + } + } + + public void sendNoResponse() + { + lock(this) + { + Debug.Assert(_state > StateNotValidated); + + try + { + if(--_dispatchCount == 0) + { + Monitor.PulseAll(this); + } + + if(_state == StateClosing && _dispatchCount == 0) + { + initiateShutdown(); + } + } + catch(LocalException ex) + { + setState(StateClosed, ex); + } + } + } + + public IceInternal.EndpointI endpoint() + { + // No mutex protection necessary, _endpoint is immutable. + return _endpoint; + } public bool threadPerConnection() { return _threadPerConnection; // No mutex protection necessary, _threadPerConnection is immutable. } - public void setAdapter(ObjectAdapter adapter) - { - lock(this) - { - if(_exception != null) - { - throw _exception; - } - - Debug.Assert(_state < StateClosing); - - _adapter = adapter; - - if(_adapter != null) - { - _servantManager = ((ObjectAdapterI) _adapter).getServantManager(); - if(_servantManager == null) - { - _adapter = null; - } - } - else - { - _servantManager = null; - } - - // - // We never change the thread pool with which we were - // initially registered, even if we add or remove an - // object adapter. - // - } - } - - public ObjectAdapter getAdapter() - { - lock(this) - { - return _adapter; - } - } - - public ObjectPrx createProxy(Identity ident) - { - // - // Create a reference and return a reverse proxy for this - // reference. - // - ConnectionI[] connections = new ConnectionI[1]; - connections[0] = this; - IceInternal.Reference @ref = instance_.referenceFactory().create( - ident, instance_.getDefaultContext(), "", IceInternal.Reference.Mode.ModeTwoway, - connections); - return instance_.proxyFactory().referenceToProxy(@ref); - } - - // - // Operations from EventHandler - // - - public override bool datagram() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - return _endpoint.datagram(); // No mutex protection necessary, _endpoint is immutable. - } - - public override bool readable() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - return true; - } - - public override void read(IceInternal.BasicStream stream) - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - - _transceiver.read(stream, 0); - - // - // Updating _acmAbsoluteTimeoutMillis is too expensive here, - // because we would have to acquire a lock just for this - // purpose. Instead, we update _acmAbsoluteTimeoutMillis in - // message(). - // - } - - public override void message(IceInternal.BasicStream stream, IceInternal.ThreadPool threadPool) - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - - byte compress = 0; - int requestId = 0; - int invokeNum = 0; - IceInternal.ServantManager servantManager = null; - ObjectAdapter adapter = null; - IceInternal.OutgoingAsync outAsync = null; - - lock(this) - { - // - // We must promote with the synchronization, otherwise - // there could be various race conditions with close - // connection messages and other messages. - // - threadPool.promoteFollower(); - - if(_state != StateClosed) - { - parseMessage(ref stream, ref invokeNum, ref requestId, ref compress, ref servantManager, - ref adapter, ref outAsync); - } - - // - // parseMessage() can close the connection, so we must check - // for closed state again. - // - if(_state == StateClosed) - { - return; - } - } - - // - // Asynchronous replies must be handled outside the thread - // synchronization, so that nested calls are possible. - // - if(outAsync != null) - { - outAsync.finished__(stream); - } - - // - // Method invocation (or multiple invocations for batch messages) - // must be done outside the thread synchronization, so that nested - // calls are possible. - // - invokeAll(stream, invokeNum, requestId, compress, servantManager, adapter); - } - - public override void finished(IceInternal.ThreadPool threadPool) - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - - threadPool.promoteFollower(); - - LocalException exception = null; - - Hashtable requests = null; - Hashtable asyncRequests = null; - - lock(this) - { - --_finishedCount; - if(_finishedCount == 0 && _state == StateClosed) - { - // - // We must make sure that nobody is sending when we - // close the transeiver. - // - lock(_sendMutex) - { - try - { - _transceiver.close(); - } - catch(LocalException ex) - { - exception = ex; - } - - _transceiver = null; - Monitor.PulseAll(this); - } - } - - if(_state == StateClosed || _state == StateClosing) - { - requests = _requests; - _requests = new Hashtable(); - - asyncRequests = _asyncRequests; - _asyncRequests = new Hashtable(); - } - } - - if(requests != null) - { - foreach(IceInternal.Outgoing og in requests.Values) - { - og.finished(_exception); // The exception is immutable at this point. - } - } - - if(asyncRequests != null) - { - foreach(IceInternal.OutgoingAsync og in asyncRequests.Values) - { - og.finished__(_exception); // The exception is immutable at this point. - } - } - - if(exception != null) - { - throw exception; - } - } - - public override void exception(LocalException ex) - { - lock(this) - { - setState(StateClosed, ex); - } - } - - public void invokeException(LocalException ex, int invokeNum) - { - // - // Fatal exception while invoking a request. Since sendResponse/sendNoResponse isn't - // called in case of a fatal exception we decrement _dispatchCount here. - // - - lock(this) - { - setState(StateClosed, ex); - - if(invokeNum > 0) - { - Debug.Assert(_dispatchCount > 0); - _dispatchCount -= invokeNum; - Debug.Assert(_dispatchCount >= 0); - if(_dispatchCount == 0) - { - Monitor.PulseAll(this); - } - } - } - } - - public string type() - { - return _type; // No mutex lock, _type is immutable. - } - - public int timeout() - { - return _endpoint.timeout(); // No mutex protection necessary, _endpoint is immutable. - } - - public string ice_toString_() - { - return ToString(); - } - - public override string ToString() - { - return _desc; // No mutex lock, _desc is immutable. - } - - // - // Only used by the SSL plug-in. - // - // The external party has to synchronize the connection, since the - // connection is the object that protects the transceiver. - // - public IceInternal.Transceiver - getTransceiver() - { - return _transceiver; - } - - static ConnectionI() - { - _compressionSupported = IceInternal.BasicStream.compressible(); - } - - internal ConnectionI(IceInternal.Instance instance, IceInternal.Transceiver transceiver, - IceInternal.EndpointI endpoint, ObjectAdapter adapter, bool threadPerConnection) - : base(instance) - { + public void setAdapter(ObjectAdapter adapter) + { + lock(this) + { + if(_exception != null) + { + throw _exception; + } + + Debug.Assert(_state < StateClosing); + + _adapter = adapter; + + if(_adapter != null) + { + _servantManager = ((ObjectAdapterI) _adapter).getServantManager(); + if(_servantManager == null) + { + _adapter = null; + } + } + else + { + _servantManager = null; + } + + // + // We never change the thread pool with which we were + // initially registered, even if we add or remove an + // object adapter. + // + } + } + + public ObjectAdapter getAdapter() + { + lock(this) + { + return _adapter; + } + } + + public ObjectPrx createProxy(Identity ident) + { + // + // Create a reference and return a reverse proxy for this + // reference. + // + ConnectionI[] connections = new ConnectionI[1]; + connections[0] = this; + IceInternal.Reference @ref = instance_.referenceFactory().create( + ident, instance_.getDefaultContext(), "", IceInternal.Reference.Mode.ModeTwoway, + connections); + return instance_.proxyFactory().referenceToProxy(@ref); + } + + // + // Operations from EventHandler + // + + public override bool datagram() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + return _endpoint.datagram(); // No mutex protection necessary, _endpoint is immutable. + } + + public override bool readable() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + return true; + } + + public override void read(IceInternal.BasicStream stream) + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + + _transceiver.read(stream, 0); + + // + // Updating _acmAbsoluteTimeoutMillis is too expensive here, + // because we would have to acquire a lock just for this + // purpose. Instead, we update _acmAbsoluteTimeoutMillis in + // message(). + // + } + + public override void message(IceInternal.BasicStream stream, IceInternal.ThreadPool threadPool) + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + + byte compress = 0; + int requestId = 0; + int invokeNum = 0; + IceInternal.ServantManager servantManager = null; + ObjectAdapter adapter = null; + IceInternal.OutgoingAsync outAsync = null; + + lock(this) + { + // + // We must promote with the synchronization, otherwise + // there could be various race conditions with close + // connection messages and other messages. + // + threadPool.promoteFollower(); + + if(_state != StateClosed) + { + parseMessage(ref stream, ref invokeNum, ref requestId, ref compress, ref servantManager, + ref adapter, ref outAsync); + } + + // + // parseMessage() can close the connection, so we must check + // for closed state again. + // + if(_state == StateClosed) + { + return; + } + } + + // + // Asynchronous replies must be handled outside the thread + // synchronization, so that nested calls are possible. + // + if(outAsync != null) + { + outAsync.finished__(stream); + } + + // + // Method invocation (or multiple invocations for batch messages) + // must be done outside the thread synchronization, so that nested + // calls are possible. + // + invokeAll(stream, invokeNum, requestId, compress, servantManager, adapter); + } + + public override void finished(IceInternal.ThreadPool threadPool) + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + + threadPool.promoteFollower(); + + LocalException exception = null; + + Hashtable requests = null; + Hashtable asyncRequests = null; + + lock(this) + { + --_finishedCount; + if(_finishedCount == 0 && _state == StateClosed) + { + // + // We must make sure that nobody is sending when we + // close the transeiver. + // + lock(_sendMutex) + { + try + { + _transceiver.close(); + } + catch(LocalException ex) + { + exception = ex; + } + + _transceiver = null; + Monitor.PulseAll(this); + } + } + + if(_state == StateClosed || _state == StateClosing) + { + requests = _requests; + _requests = new Hashtable(); + + asyncRequests = _asyncRequests; + _asyncRequests = new Hashtable(); + } + } + + if(requests != null) + { + foreach(IceInternal.Outgoing og in requests.Values) + { + og.finished(_exception); // The exception is immutable at this point. + } + } + + if(asyncRequests != null) + { + foreach(IceInternal.OutgoingAsync og in asyncRequests.Values) + { + og.finished__(_exception); // The exception is immutable at this point. + } + } + + if(exception != null) + { + throw exception; + } + } + + public override void exception(LocalException ex) + { + lock(this) + { + setState(StateClosed, ex); + } + } + + public void invokeException(LocalException ex, int invokeNum) + { + // + // Fatal exception while invoking a request. Since sendResponse/sendNoResponse isn't + // called in case of a fatal exception we decrement _dispatchCount here. + // + + lock(this) + { + setState(StateClosed, ex); + + if(invokeNum > 0) + { + Debug.Assert(_dispatchCount > 0); + _dispatchCount -= invokeNum; + Debug.Assert(_dispatchCount >= 0); + if(_dispatchCount == 0) + { + Monitor.PulseAll(this); + } + } + } + } + + public string type() + { + return _type; // No mutex lock, _type is immutable. + } + + public int timeout() + { + return _endpoint.timeout(); // No mutex protection necessary, _endpoint is immutable. + } + + public string ice_toString_() + { + return ToString(); + } + + public override string ToString() + { + return _desc; // No mutex lock, _desc is immutable. + } + + // + // Only used by the SSL plug-in. + // + // The external party has to synchronize the connection, since the + // connection is the object that protects the transceiver. + // + public IceInternal.Transceiver + getTransceiver() + { + return _transceiver; + } + + static ConnectionI() + { + _compressionSupported = IceInternal.BasicStream.compressible(); + } + + internal ConnectionI(IceInternal.Instance instance, IceInternal.Transceiver transceiver, + IceInternal.EndpointI endpoint, ObjectAdapter adapter, bool threadPerConnection) + : base(instance) + { _threadPerConnection = threadPerConnection; - _transceiver = transceiver; - _desc = transceiver.ToString(); - _type = transceiver.type(); - _endpoint = endpoint; - _adapter = adapter; - _logger = instance.initializationData().logger; // Cached for better performance. - _traceLevels = instance.traceLevels(); // Cached for better performance. - _registeredWithPool = false; - _finishedCount = 0; - _warn = instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Connections") > 0; - _cacheBuffers = instance_.initializationData().properties.getPropertyAsIntWithDefault( - "Ice.CacheMessageBuffers", 1) == 1; - _acmAbsoluteTimeoutMillis = 0; - _nextRequestId = 1; - _batchAutoFlush = instance_.initializationData().properties.getPropertyAsIntWithDefault( + _transceiver = transceiver; + _desc = transceiver.ToString(); + _type = transceiver.type(); + _endpoint = endpoint; + _adapter = adapter; + _logger = instance.initializationData().logger; // Cached for better performance. + _traceLevels = instance.traceLevels(); // Cached for better performance. + _registeredWithPool = false; + _finishedCount = 0; + _warn = instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Connections") > 0; + _cacheBuffers = instance_.initializationData().properties.getPropertyAsIntWithDefault( + "Ice.CacheMessageBuffers", 1) == 1; + _acmAbsoluteTimeoutMillis = 0; + _nextRequestId = 1; + _batchAutoFlush = instance_.initializationData().properties.getPropertyAsIntWithDefault( "Ice.BatchAutoFlush", 1) > 0; - _batchStream = new IceInternal.BasicStream(instance, _batchAutoFlush); - _batchStreamInUse = false; - _batchRequestNum = 0; - _batchRequestCompress = false; - _dispatchCount = 0; - _state = StateNotValidated; - _stateTime = System.DateTime.Now.Ticks / 10000; - - if(_endpoint.datagram()) - { - _acmTimeout = 0; - } - else - { - if(_adapter != null) - { - _acmTimeout = instance_.serverACM(); - } - else - { - _acmTimeout = instance_.clientACM(); - } - } - - _compressionLevel = - instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Compression.Level", 1); - if(_compressionLevel < 1) - { - _compressionLevel = 1; - } - else if(_compressionLevel > 9) - { - _compressionLevel = 9; - } - - ObjectAdapterI adapterImpl = _adapter as ObjectAdapterI; - if(adapterImpl != null) - { - _servantManager = adapterImpl.getServantManager(); - } - - try - { - if(!threadPerConnection) - { - // - // Only set _threadPool if we really need it, i.e., if we are - // not in thread per connection mode. Thread pools have lazy - // initialization in Instance, and we don't want them to be - // created if they are not needed. - // - if(adapterImpl != null) - { - _threadPool = adapterImpl.getThreadPool(); - } - else - { - _threadPool = instance.clientThreadPool(); - } - } - else - { - // - // If we are in thread per connection mode, create the thread - // for this connection. - // - _thread = new Thread(new ThreadStart(RunThreadPerConnection)); + _batchStream = new IceInternal.BasicStream(instance, _batchAutoFlush); + _batchStreamInUse = false; + _batchRequestNum = 0; + _batchRequestCompress = false; + _dispatchCount = 0; + _state = StateNotValidated; + _stateTime = System.DateTime.Now.Ticks / 10000; + + if(_endpoint.datagram()) + { + _acmTimeout = 0; + } + else + { + if(_adapter != null) + { + _acmTimeout = instance_.serverACM(); + } + else + { + _acmTimeout = instance_.clientACM(); + } + } + + _compressionLevel = + instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Compression.Level", 1); + if(_compressionLevel < 1) + { + _compressionLevel = 1; + } + else if(_compressionLevel > 9) + { + _compressionLevel = 9; + } + + ObjectAdapterI adapterImpl = _adapter as ObjectAdapterI; + if(adapterImpl != null) + { + _servantManager = adapterImpl.getServantManager(); + } + + try + { + if(!threadPerConnection) + { + // + // Only set _threadPool if we really need it, i.e., if we are + // not in thread per connection mode. Thread pools have lazy + // initialization in Instance, and we don't want them to be + // created if they are not needed. + // + if(adapterImpl != null) + { + _threadPool = adapterImpl.getThreadPool(); + } + else + { + _threadPool = instance.clientThreadPool(); + } + } + else + { + // + // If we are in thread per connection mode, create the thread + // for this connection. + // + _thread = new Thread(new ThreadStart(RunThreadPerConnection)); _thread.IsBackground = true; - _thread.Start(); - } - } - catch(System.Exception ex) - { - if(threadPerConnection) - { - _logger.error("cannot create thread for connection:\n" + ex); - } - - try - { - _transceiver.close(); - } - catch(LocalException) - { - // Here we ignore any exceptions in close(). - } - - throw new Ice.SyscallException(ex); - } - - _overrideCompress = instance_.defaultsAndOverrides().overrideCompress; - _overrideCompressValue = instance_.defaultsAndOverrides().overrideCompressValue; - } - - private const int StateNotValidated = 0; - private const int StateActive = 1; - private const int StateHolding = 2; - private const int StateClosing = 3; - private const int StateClosed = 4; - - private void setState(int state, LocalException ex) - { - // - // If setState() is called with an exception, then only closed - // and closing states are permissible. - // - Debug.Assert(state == StateClosing || state == StateClosed); - - if(_state == state) // Don't switch twice. - { - return; - } - - if(_exception == null) - { - // - // If we are in closed state, an exception must be set. - // - Debug.Assert(_state != StateClosed); - - _exception = ex; - - if(_warn) - { - // - // We don't warn if we are not validated. - // - if(_state > StateNotValidated) - { - // - // Don't warn about certain expected exceptions. - // - if(!(_exception is CloseConnectionException || - _exception is ForcedCloseConnectionException || - _exception is ConnectionTimeoutException || - _exception is CommunicatorDestroyedException || - _exception is ObjectAdapterDeactivatedException || - (_exception is ConnectionLostException && _state == StateClosing))) - { - warning("connection exception", _exception); - } - } - } - } - - // - // We must set the new state before we notify requests of any - // exceptions. Otherwise new requests may retry on a - // connection that is not yet marked as closed or closing. - // - setState(state); - } - - private void setState(int state) - { - // - // We don't want to send close connection messages if the endpoint - // only supports oneway transmission from client to server. - // - if(_endpoint.datagram() && state == StateClosing) - { - state = StateClosed; - } - - // - // Skip graceful shutdown if we are destroyed before validation. - // - if(_state == StateNotValidated && state == StateClosing) - { - state = StateClosed; - } - - if(_state == state) // Don't switch twice. - { - return; - } - - switch(state) - { - case StateNotValidated: - { - Debug.Assert(false); - break; - } - - case StateActive: - { - // - // Can only switch from holding or not validated to - // active. - // - if(_state != StateHolding && _state != StateNotValidated) - { - return; - } - if(!_threadPerConnection) - { - registerWithPool(); - } - break; - } - - case StateHolding: - { - // - // Can only switch from active or not validated to - // holding. - // - if(_state != StateActive && _state != StateNotValidated) - { - return; - } - if(!_threadPerConnection) - { - unregisterWithPool(); - } - break; - } - - case StateClosing: - { - // - // Can't change back from closed. - // - if(_state == StateClosed) - { - return; - } - if(!_threadPerConnection) - { - registerWithPool(); // We need to continue to read in closing state. - } - break; - } - - case StateClosed: - { - if(_threadPerConnection) - { - // - // If we are in thread per connection mode, we - // shutdown both for reading and writing. This will - // unblock any read call with an exception. The thread - // per connection then closes the transceiver. - // - _transceiver.shutdownReadWrite(); - } - else if(_state == StateNotValidated) - { - // - // If we change from not validated, we can close right - // away. - // - Debug.Assert(!_registeredWithPool); - - // - // We must make sure that nobidy is sending when we - // close the transceiver. - // - lock(_sendMutex) - { - try - { - _transceiver.close(); - } - catch(LocalException) - { - // Here we ignore any exceptions in close(). - } - - _transceiver = null; - //Monitor.PulseAll(); // We notify already below. - } - } - else - { - // - // Otherwise we first must make sure that we are - // registered, then we unregister, and let finished() - // do the close. - // - registerWithPool(); - unregisterWithPool(); - - // - // We must prevent any further writes when _state == StateClosed. - // However, functions such as sendResponse cannot acquire the main - // mutex in order to check _state. Therefore we shut down the write - // end of the transceiver, which causes subsequent write attempts - // to fail with an exception. - // - _transceiver.shutdownWrite(); - } - break; - } - } - - // - // We only register with the connection monitor if our new state - // is StateActive. Otherwise we unregister with the connection - // monitor, but only if we were registered before, i.e., if our - // old state was StateActive. - // - IceInternal.ConnectionMonitor connectionMonitor = instance_.connectionMonitor(); - if(connectionMonitor != null) - { - if(state == StateActive) - { - connectionMonitor.add(this); - } - else if(_state == StateActive) - { - connectionMonitor.remove(this); - } - } - - _state = state; - _stateTime = System.DateTime.Now.Ticks / 10000; - - Monitor.PulseAll(this); - - if(_state == StateClosing && _dispatchCount == 0) - { - try - { - initiateShutdown(); - } - catch(LocalException ex) - { - setState(StateClosed, ex); - } - } - } - - private void initiateShutdown() - { - Debug.Assert(_state == StateClosing); - Debug.Assert(_dispatchCount == 0); - - if(!_endpoint.datagram()) - { - lock(_sendMutex) - { - // - // Before we shut down, we send a close connection - // message. - // - IceInternal.BasicStream os = new IceInternal.BasicStream(instance_); - os.writeBlob(IceInternal.Protocol.magic); - os.writeByte(IceInternal.Protocol.protocolMajor); - os.writeByte(IceInternal.Protocol.protocolMinor); - os.writeByte(IceInternal.Protocol.encodingMajor); - os.writeByte(IceInternal.Protocol.encodingMinor); - os.writeByte(IceInternal.Protocol.closeConnectionMsg); - os.writeByte(_compressionSupported ? (byte)1 : (byte)0); - os.writeInt(IceInternal.Protocol.headerSize); // Message size. - - // - // Send the message. - // - IceInternal.TraceUtil.traceHeader("sending close connection", os, _logger, _traceLevels); - _transceiver.write(os, _endpoint.timeout()); - // - // The CloseConnection message should be sufficient. Closing the write - // end of the socket is probably an artifact of how things were done - // in IIOP. In fact, shutting down the write end of the socket causes - // problems on Windows by preventing the peer from using the socket. - // For example, the peer is no longer able to continue writing a large - // message after the socket is shutdown. - // - //_transceiver.shutdown(); - } - } - } - - private void registerWithPool() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - - if(!_registeredWithPool) - { - _threadPool.register(_transceiver.fd(), this); - _registeredWithPool = true; - } - } - - private void unregisterWithPool() - { - Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. - - if(_registeredWithPool) - { - _threadPool.unregister(_transceiver.fd()); - _registeredWithPool = false; - ++_finishedCount; // For each unregistration, finished() is called once. - } - } - - private void warning(string msg, System.Exception ex) - { - _logger.warning(msg + ":\n" + ex + "\n" + _transceiver.ToString()); - } - - private void parseMessage(ref IceInternal.BasicStream stream, ref int invokeNum, ref int requestId, - ref byte compress, ref IceInternal.ServantManager servantManager, - ref ObjectAdapter adapter, ref IceInternal.OutgoingAsync outAsync) - { - Debug.Assert(_state > StateNotValidated && _state < StateClosed); - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; - } - - try - { - // - // We don't need to check magic and version here. This has - // already been done by the ThreadPool or ThreadPerConnection, - // which provides us with the stream. - // - Debug.Assert(stream.pos() == stream.size()); - stream.pos(8); - byte messageType = stream.readByte(); - compress = stream.readByte(); - if(compress == (byte)2) - { - if(_compressionSupported) - { - IceInternal.BasicStream uncompressedStream - = stream.uncompress(IceInternal.Protocol.headerSize); - stream = uncompressedStream; - } - else - { - FeatureNotSupportedException ex = new FeatureNotSupportedException(); - ex.unsupportedFeature = "Cannot uncompress compressed message: bzip2 DLL not found"; - throw ex; - } - } - stream.pos(IceInternal.Protocol.headerSize); - - switch(messageType) - { - case IceInternal.Protocol.closeConnectionMsg: - { - IceInternal.TraceUtil.traceHeader("received close connection", stream, _logger, - _traceLevels); - if(_endpoint.datagram()) - { - if(_warn) - { - _logger.warning("ignoring close connection message for datagram connection:\n" - + _desc); - } - } - else - { - setState(StateClosed, new CloseConnectionException()); - } - break; - } - case IceInternal.Protocol.requestMsg: - { - if(_state == StateClosing) - { - IceInternal.TraceUtil.traceRequest("received request during closing\n" - + "(ignored by server, client will retry)", - stream, _logger, _traceLevels); - } - else - { - IceInternal.TraceUtil.traceRequest("received request", stream, _logger, _traceLevels); - requestId = stream.readInt(); - invokeNum = 1; - servantManager = _servantManager; - adapter = _adapter; - ++_dispatchCount; - } - break; - } - - case IceInternal.Protocol.requestBatchMsg: - { - if(_state == StateClosing) - { - IceInternal.TraceUtil.traceBatchRequest("received batch request during closing\n" - + "(ignored by server, client will retry)", - stream, _logger, _traceLevels); - } - else - { - IceInternal.TraceUtil.traceBatchRequest("received batch request", stream, _logger, - _traceLevels); - invokeNum = stream.readInt(); - if(invokeNum < 0) - { - invokeNum = 0; - throw new NegativeSizeException(); - } - servantManager = _servantManager; - adapter = _adapter; - _dispatchCount += invokeNum; - } - break; - } - - case IceInternal.Protocol.replyMsg: - { - IceInternal.TraceUtil.traceReply("received reply", stream, _logger, _traceLevels); - - requestId = stream.readInt(); - - IceInternal.Outgoing og = (IceInternal.Outgoing)_requests[requestId]; - _requests.Remove(requestId); - if(og != null) - { - og.finished(stream); - } - else - { - outAsync = (IceInternal.OutgoingAsync)_asyncRequests[requestId]; - _asyncRequests.Remove(requestId); - if(outAsync == null) - { - throw new UnknownRequestIdException(); - } - } - break; - } - - case IceInternal.Protocol.validateConnectionMsg: - { - IceInternal.TraceUtil.traceHeader("received validate connection", stream, _logger, - _traceLevels); - if(_warn) - { - _logger.warning("ignoring unexpected validate connection message:\n" + _desc); - } - break; - } - - default: - { - IceInternal.TraceUtil.traceHeader("received unknown message\n" + - "(invalid, closing connection)", - stream, _logger, _traceLevels); - throw new UnknownMessageException(); - } - } - } - catch(LocalException ex) - { - if(_endpoint.datagram()) - { - if(_warn) - { - _logger.warning("datagram connection exception:\n" + ex.ToString() + "\n" + _desc); - } - } - else - { - setState(StateClosed, ex); - } - } - } - - private void invokeAll(IceInternal.BasicStream stream, int invokeNum, int requestId, byte compress, - IceInternal.ServantManager servantManager, ObjectAdapter adapter) - { - // - // Note: In contrast to other private or protected methods, this - // operation must be called *without* the mutex locked. - // - - IceInternal.Incoming inc = null; - try - { - while(invokeNum > 0) - { - // - // Prepare the invocation. - // - bool response = !_endpoint.datagram() && requestId != 0; - inc = getIncoming(adapter, response, compress, requestId); - IceInternal.BasicStream ins = inc.istr(); - stream.swap(ins); - IceInternal.BasicStream os = inc.ostr(); - - // - // Prepare the response if necessary. - // - if(response) - { - Debug.Assert(invokeNum == 1); // No further invocations if a response is expected. - os.writeBlob(IceInternal.Protocol.replyHdr); - - // - // Add the request ID. - // - os.writeInt(requestId); - } - - inc.invoke(servantManager); - - // - // If there are more invocations, we need the stream back. - // - if(--invokeNum > 0) - { - stream.swap(ins); - } - - reclaimIncoming(inc); - inc = null; - } - } - catch(LocalException ex) - { - invokeException(ex, invokeNum); - } - finally - { - if(inc != null) - { - reclaimIncoming(inc); - } - } - } - - private void run() - { - // - // For non-datagram connections, the thread-per-connection must - // validate and activate this connection, and not in the - // connection factory. Please see the comments in the connection - // factory for details. - // - if(!_endpoint.datagram()) - { - try - { - validate(); - } - catch(LocalException) - { - lock(this) - { - Debug.Assert(_state == StateClosed); - - // - // We must make sure that nobody is sending when we close - // the transceiver. - // - lock(_sendMutex) - { - if(_transceiver != null) - { - try - { - _transceiver.close(); - } - catch(LocalException) - { - // Here we ignore any exceptions in close(). - } - - _transceiver = null; - } - Monitor.PulseAll(this); - return; - } - } - } - - activate(); - } - - bool warnUdp = instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; - - bool closed = false; - - IceInternal.BasicStream stream = new IceInternal.BasicStream(instance_); - - while(!closed) - { - // - // We must accept new connections outside the thread - // synchronization, because we use blocking accept. - // - - try - { - try - { - stream.resize(IceInternal.Protocol.headerSize, true); - stream.pos(0); - _transceiver.read(stream, -1); - - int pos = stream.pos(); - if(pos < IceInternal.Protocol.headerSize) - { - // - // This situation is possible for small UDP packets. - // - throw new IllegalMessageSizeException(); - } - stream.pos(0); - byte[] m = stream.readBlob(4); - if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] || - m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3]) - { - BadMagicException ex = new BadMagicException(); - ex.badMagic = m; - throw ex; - } - byte pMajor = stream.readByte(); - byte pMinor = stream.readByte(); - if(pMajor != IceInternal.Protocol.protocolMajor) - { - UnsupportedProtocolException e = new UnsupportedProtocolException(); - e.badMajor = pMajor < 0 ? pMajor + 255 : pMajor; - e.badMinor = pMinor < 0 ? pMinor + 255 : pMinor; - e.major = IceInternal.Protocol.protocolMajor; - e.minor = IceInternal.Protocol.protocolMinor; - throw e; - } - byte eMajor = stream.readByte(); - byte eMinor = stream.readByte(); - if(eMajor != IceInternal.Protocol.encodingMajor) - { - UnsupportedEncodingException e = new UnsupportedEncodingException(); - e.badMajor = eMajor < 0 ? eMajor + 255 : eMajor; - e.badMinor = eMinor < 0 ? eMinor + 255 : eMinor; - e.major = IceInternal.Protocol.encodingMajor; - e.minor = IceInternal.Protocol.encodingMinor; - throw e; - } - stream.readByte(); // Skip message type. - stream.readByte(); // Skip compression flag. - int size = stream.readInt(); - if(size < IceInternal.Protocol.headerSize) - { - throw new IllegalMessageSizeException(); - } - if(size > instance_.messageSizeMax()) - { - throw new MemoryLimitException(); - } - if(size > stream.size()) - { - stream.resize(size, true); - } - stream.pos(pos); - - if(pos != stream.size()) - { - if(_endpoint.datagram()) - { - if(warnUdp) - { - _logger.warning("DatagramLimitException: maximum size of " + pos + " exceeded"); - } - throw new DatagramLimitException(); - } - else - { - _transceiver.read(stream, -1); - Debug.Assert(stream.pos() == stream.size()); - } - } - } - catch(DatagramLimitException) // Expected. - { - continue; - } - catch(SocketException ex) // Expected. - { - exception(ex); - } - catch(LocalException ex) - { - if(_endpoint.datagram()) - { - if(_warn) - { - warning("datagram connection exception:", ex); - } - continue; - } - else - { - exception(ex); - } - } - - byte compress = 0; - int requestId = 0; - int invokeNum = 0; - IceInternal.ServantManager servantManager = null; - ObjectAdapter adapter = null; - IceInternal.OutgoingAsync outAsync = null; - - LocalException localEx = null; - - Hashtable requests = null; - Hashtable asyncRequests = null; - - lock(this) - { - while(_state == StateHolding) - { - Monitor.Wait(this); - } - - if(_state != StateClosed) - { - parseMessage(ref stream, ref invokeNum, ref requestId, ref compress, ref servantManager, - ref adapter, ref outAsync); - } - - // - // parseMessage() can close the connection, so we must check - // for closed state again. - // - if(_state == StateClosed) - { - // - // We must make sure that nobody is sending when we close - // the transceiver. - // - lock(_sendMutex) - { - try - { - _transceiver.close(); - } - catch(LocalException ex) - { - localEx = ex; - } - - _transceiver = null; - Monitor.PulseAll(this); - - // - // We cannot simply return here. We have to make sure - // that all requests (regular and async) are notified - // about the closed connection below. - // - closed = true; - } - } - - if(_state == StateClosed || _state == StateClosing) - { - requests = _requests; - _requests = new Hashtable(); - - asyncRequests = _asyncRequests; - _asyncRequests = new Hashtable(); - } - } - - // - // Asynchronous replies must be handled outside the thread - // synchronization, so that nested calls are possible. - // - if(outAsync != null) - { - outAsync.finished__(stream); - } - - // - // Method invocation (or multiple invocations for batch messages) - // must be done outside the thread synchronization, so that nested - // calls are possible. - // - invokeAll(stream, invokeNum, requestId, compress, servantManager, adapter); - - if(requests != null) - { - foreach(IceInternal.Outgoing og in requests.Values) - { - og.finished(_exception); // The exception is immutable at this point. - } - } - - if(asyncRequests != null) - { - foreach(IceInternal.OutgoingAsync og in asyncRequests.Values) - { - og.finished__(_exception); // The exception is immutable at this point. - } - } - - if(localEx != null) - { - Debug.Assert(closed); - throw localEx; - } - } - finally - { - stream.reset(); - } - } - } - - public void RunThreadPerConnection() - { - if(instance_.initializationData().threadHook != null) - { - instance_.initializationData().threadHook.start(); - } - - try - { - run(); - } - catch(Exception ex) - { - _logger.error("exception in thread per connection:\n" + ToString() + "\n" + ex.ToString()); - } - catch(System.Exception ex) - { - _logger.error("system exception in thread per connection:\n" + ToString() + "\n" + - ex.ToString()); - } - finally - { - if(instance_.initializationData().threadHook != null) - { - instance_.initializationData().threadHook.stop(); - } - } - } - - private IceInternal.Incoming getIncoming(ObjectAdapter adapter, bool response, byte compress, int requestId) - { - IceInternal.Incoming inc = null; - - if(_cacheBuffers) - { - lock(_incomingCacheMutex) - { - if(_incomingCache == null) - { - inc = new IceInternal.Incoming(instance_, this, adapter, response, compress, requestId); - } - else - { - inc = _incomingCache; - _incomingCache = _incomingCache.next; - inc.reset(instance_, this, adapter, response, compress, requestId); - inc.next = null; - } - } - } - else - { - inc = new IceInternal.Incoming(instance_, this, adapter, response, compress, requestId); - } - - return inc; - } - - private void reclaimIncoming(IceInternal.Incoming inc) - { - if(_cacheBuffers) - { - lock(_incomingCacheMutex) - { - inc.next = _incomingCache; - _incomingCache = inc; - // - // Clear references to Ice objects as soon as possible. - // - _incomingCache.reclaim(); - } - } - } - - public IceInternal.Outgoing getOutgoing(IceInternal.Reference reference, string operation, OperationMode mode, - Context context, bool compress) - { - IceInternal.Outgoing outg = null; - - if(_cacheBuffers) - { - lock(_outgoingCacheMutex) - { - if(_outgoingCache == null) - { - outg = new IceInternal.Outgoing(this, reference, operation, mode, context, compress); - } - else - { - outg = _outgoingCache; - _outgoingCache = _outgoingCache.next; - outg.reset(reference, operation, mode, context, compress); - outg.next = null; - } - } - } - else - { - outg = new IceInternal.Outgoing(this, reference, operation, mode, context, compress); - } - - return outg; - } - - public void reclaimOutgoing(IceInternal.Outgoing outg) - { - if(_cacheBuffers) - { - // - // Clear references to Ice objects as soon as possible. - // - outg.reclaim(); - - lock(_outgoingCacheMutex) - { - outg.next = _outgoingCache; - _outgoingCache = outg; - } - } - } - - private Thread _thread; + _thread.Start(); + } + } + catch(System.Exception ex) + { + if(threadPerConnection) + { + _logger.error("cannot create thread for connection:\n" + ex); + } + + try + { + _transceiver.close(); + } + catch(LocalException) + { + // Here we ignore any exceptions in close(). + } + + throw new Ice.SyscallException(ex); + } + + _overrideCompress = instance_.defaultsAndOverrides().overrideCompress; + _overrideCompressValue = instance_.defaultsAndOverrides().overrideCompressValue; + } + + private const int StateNotValidated = 0; + private const int StateActive = 1; + private const int StateHolding = 2; + private const int StateClosing = 3; + private const int StateClosed = 4; + + private void setState(int state, LocalException ex) + { + // + // If setState() is called with an exception, then only closed + // and closing states are permissible. + // + Debug.Assert(state == StateClosing || state == StateClosed); + + if(_state == state) // Don't switch twice. + { + return; + } + + if(_exception == null) + { + // + // If we are in closed state, an exception must be set. + // + Debug.Assert(_state != StateClosed); + + _exception = ex; + + if(_warn) + { + // + // We don't warn if we are not validated. + // + if(_state > StateNotValidated) + { + // + // Don't warn about certain expected exceptions. + // + if(!(_exception is CloseConnectionException || + _exception is ForcedCloseConnectionException || + _exception is ConnectionTimeoutException || + _exception is CommunicatorDestroyedException || + _exception is ObjectAdapterDeactivatedException || + (_exception is ConnectionLostException && _state == StateClosing))) + { + warning("connection exception", _exception); + } + } + } + } + + // + // We must set the new state before we notify requests of any + // exceptions. Otherwise new requests may retry on a + // connection that is not yet marked as closed or closing. + // + setState(state); + } + + private void setState(int state) + { + // + // We don't want to send close connection messages if the endpoint + // only supports oneway transmission from client to server. + // + if(_endpoint.datagram() && state == StateClosing) + { + state = StateClosed; + } + + // + // Skip graceful shutdown if we are destroyed before validation. + // + if(_state == StateNotValidated && state == StateClosing) + { + state = StateClosed; + } + + if(_state == state) // Don't switch twice. + { + return; + } + + switch(state) + { + case StateNotValidated: + { + Debug.Assert(false); + break; + } + + case StateActive: + { + // + // Can only switch from holding or not validated to + // active. + // + if(_state != StateHolding && _state != StateNotValidated) + { + return; + } + if(!_threadPerConnection) + { + registerWithPool(); + } + break; + } + + case StateHolding: + { + // + // Can only switch from active or not validated to + // holding. + // + if(_state != StateActive && _state != StateNotValidated) + { + return; + } + if(!_threadPerConnection) + { + unregisterWithPool(); + } + break; + } + + case StateClosing: + { + // + // Can't change back from closed. + // + if(_state == StateClosed) + { + return; + } + if(!_threadPerConnection) + { + registerWithPool(); // We need to continue to read in closing state. + } + break; + } + + case StateClosed: + { + if(_threadPerConnection) + { + // + // If we are in thread per connection mode, we + // shutdown both for reading and writing. This will + // unblock any read call with an exception. The thread + // per connection then closes the transceiver. + // + _transceiver.shutdownReadWrite(); + } + else if(_state == StateNotValidated) + { + // + // If we change from not validated, we can close right + // away. + // + Debug.Assert(!_registeredWithPool); + + // + // We must make sure that nobidy is sending when we + // close the transceiver. + // + lock(_sendMutex) + { + try + { + _transceiver.close(); + } + catch(LocalException) + { + // Here we ignore any exceptions in close(). + } + + _transceiver = null; + //Monitor.PulseAll(); // We notify already below. + } + } + else + { + // + // Otherwise we first must make sure that we are + // registered, then we unregister, and let finished() + // do the close. + // + registerWithPool(); + unregisterWithPool(); + + // + // We must prevent any further writes when _state == StateClosed. + // However, functions such as sendResponse cannot acquire the main + // mutex in order to check _state. Therefore we shut down the write + // end of the transceiver, which causes subsequent write attempts + // to fail with an exception. + // + _transceiver.shutdownWrite(); + } + break; + } + } + + // + // We only register with the connection monitor if our new state + // is StateActive. Otherwise we unregister with the connection + // monitor, but only if we were registered before, i.e., if our + // old state was StateActive. + // + IceInternal.ConnectionMonitor connectionMonitor = instance_.connectionMonitor(); + if(connectionMonitor != null) + { + if(state == StateActive) + { + connectionMonitor.add(this); + } + else if(_state == StateActive) + { + connectionMonitor.remove(this); + } + } + + _state = state; + _stateTime = System.DateTime.Now.Ticks / 10000; + + Monitor.PulseAll(this); + + if(_state == StateClosing && _dispatchCount == 0) + { + try + { + initiateShutdown(); + } + catch(LocalException ex) + { + setState(StateClosed, ex); + } + } + } + + private void initiateShutdown() + { + Debug.Assert(_state == StateClosing); + Debug.Assert(_dispatchCount == 0); + + if(!_endpoint.datagram()) + { + lock(_sendMutex) + { + // + // Before we shut down, we send a close connection + // message. + // + IceInternal.BasicStream os = new IceInternal.BasicStream(instance_); + os.writeBlob(IceInternal.Protocol.magic); + os.writeByte(IceInternal.Protocol.protocolMajor); + os.writeByte(IceInternal.Protocol.protocolMinor); + os.writeByte(IceInternal.Protocol.encodingMajor); + os.writeByte(IceInternal.Protocol.encodingMinor); + os.writeByte(IceInternal.Protocol.closeConnectionMsg); + os.writeByte(_compressionSupported ? (byte)1 : (byte)0); + os.writeInt(IceInternal.Protocol.headerSize); // Message size. + + // + // Send the message. + // + IceInternal.TraceUtil.traceHeader("sending close connection", os, _logger, _traceLevels); + _transceiver.write(os, _endpoint.timeout()); + // + // The CloseConnection message should be sufficient. Closing the write + // end of the socket is probably an artifact of how things were done + // in IIOP. In fact, shutting down the write end of the socket causes + // problems on Windows by preventing the peer from using the socket. + // For example, the peer is no longer able to continue writing a large + // message after the socket is shutdown. + // + //_transceiver.shutdown(); + } + } + } + + private void registerWithPool() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + + if(!_registeredWithPool) + { + _threadPool.register(_transceiver.fd(), this); + _registeredWithPool = true; + } + } + + private void unregisterWithPool() + { + Debug.Assert(!_threadPerConnection); // Only for use with a thread pool. + + if(_registeredWithPool) + { + _threadPool.unregister(_transceiver.fd()); + _registeredWithPool = false; + ++_finishedCount; // For each unregistration, finished() is called once. + } + } + + private void warning(string msg, System.Exception ex) + { + _logger.warning(msg + ":\n" + ex + "\n" + _transceiver.ToString()); + } + + private void parseMessage(ref IceInternal.BasicStream stream, ref int invokeNum, ref int requestId, + ref byte compress, ref IceInternal.ServantManager servantManager, + ref ObjectAdapter adapter, ref IceInternal.OutgoingAsync outAsync) + { + Debug.Assert(_state > StateNotValidated && _state < StateClosed); + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + _acmTimeout * 1000; + } + + try + { + // + // We don't need to check magic and version here. This has + // already been done by the ThreadPool or ThreadPerConnection, + // which provides us with the stream. + // + Debug.Assert(stream.pos() == stream.size()); + stream.pos(8); + byte messageType = stream.readByte(); + compress = stream.readByte(); + if(compress == (byte)2) + { + if(_compressionSupported) + { + IceInternal.BasicStream uncompressedStream + = stream.uncompress(IceInternal.Protocol.headerSize); + stream = uncompressedStream; + } + else + { + FeatureNotSupportedException ex = new FeatureNotSupportedException(); + ex.unsupportedFeature = "Cannot uncompress compressed message: bzip2 DLL not found"; + throw ex; + } + } + stream.pos(IceInternal.Protocol.headerSize); + + switch(messageType) + { + case IceInternal.Protocol.closeConnectionMsg: + { + IceInternal.TraceUtil.traceHeader("received close connection", stream, _logger, + _traceLevels); + if(_endpoint.datagram()) + { + if(_warn) + { + _logger.warning("ignoring close connection message for datagram connection:\n" + + _desc); + } + } + else + { + setState(StateClosed, new CloseConnectionException()); + } + break; + } + case IceInternal.Protocol.requestMsg: + { + if(_state == StateClosing) + { + IceInternal.TraceUtil.traceRequest("received request during closing\n" + + "(ignored by server, client will retry)", + stream, _logger, _traceLevels); + } + else + { + IceInternal.TraceUtil.traceRequest("received request", stream, _logger, _traceLevels); + requestId = stream.readInt(); + invokeNum = 1; + servantManager = _servantManager; + adapter = _adapter; + ++_dispatchCount; + } + break; + } + + case IceInternal.Protocol.requestBatchMsg: + { + if(_state == StateClosing) + { + IceInternal.TraceUtil.traceBatchRequest("received batch request during closing\n" + + "(ignored by server, client will retry)", + stream, _logger, _traceLevels); + } + else + { + IceInternal.TraceUtil.traceBatchRequest("received batch request", stream, _logger, + _traceLevels); + invokeNum = stream.readInt(); + if(invokeNum < 0) + { + invokeNum = 0; + throw new NegativeSizeException(); + } + servantManager = _servantManager; + adapter = _adapter; + _dispatchCount += invokeNum; + } + break; + } + + case IceInternal.Protocol.replyMsg: + { + IceInternal.TraceUtil.traceReply("received reply", stream, _logger, _traceLevels); + + requestId = stream.readInt(); + + IceInternal.Outgoing og = (IceInternal.Outgoing)_requests[requestId]; + _requests.Remove(requestId); + if(og != null) + { + og.finished(stream); + } + else + { + outAsync = (IceInternal.OutgoingAsync)_asyncRequests[requestId]; + _asyncRequests.Remove(requestId); + if(outAsync == null) + { + throw new UnknownRequestIdException(); + } + } + break; + } + + case IceInternal.Protocol.validateConnectionMsg: + { + IceInternal.TraceUtil.traceHeader("received validate connection", stream, _logger, + _traceLevels); + if(_warn) + { + _logger.warning("ignoring unexpected validate connection message:\n" + _desc); + } + break; + } + + default: + { + IceInternal.TraceUtil.traceHeader("received unknown message\n" + + "(invalid, closing connection)", + stream, _logger, _traceLevels); + throw new UnknownMessageException(); + } + } + } + catch(LocalException ex) + { + if(_endpoint.datagram()) + { + if(_warn) + { + _logger.warning("datagram connection exception:\n" + ex.ToString() + "\n" + _desc); + } + } + else + { + setState(StateClosed, ex); + } + } + } + + private void invokeAll(IceInternal.BasicStream stream, int invokeNum, int requestId, byte compress, + IceInternal.ServantManager servantManager, ObjectAdapter adapter) + { + // + // Note: In contrast to other private or protected methods, this + // operation must be called *without* the mutex locked. + // + + IceInternal.Incoming inc = null; + try + { + while(invokeNum > 0) + { + // + // Prepare the invocation. + // + bool response = !_endpoint.datagram() && requestId != 0; + inc = getIncoming(adapter, response, compress, requestId); + IceInternal.BasicStream ins = inc.istr(); + stream.swap(ins); + IceInternal.BasicStream os = inc.ostr(); + + // + // Prepare the response if necessary. + // + if(response) + { + Debug.Assert(invokeNum == 1); // No further invocations if a response is expected. + os.writeBlob(IceInternal.Protocol.replyHdr); + + // + // Add the request ID. + // + os.writeInt(requestId); + } + + inc.invoke(servantManager); + + // + // If there are more invocations, we need the stream back. + // + if(--invokeNum > 0) + { + stream.swap(ins); + } + + reclaimIncoming(inc); + inc = null; + } + } + catch(LocalException ex) + { + invokeException(ex, invokeNum); + } + finally + { + if(inc != null) + { + reclaimIncoming(inc); + } + } + } + + private void run() + { + // + // For non-datagram connections, the thread-per-connection must + // validate and activate this connection, and not in the + // connection factory. Please see the comments in the connection + // factory for details. + // + if(!_endpoint.datagram()) + { + try + { + validate(); + } + catch(LocalException) + { + lock(this) + { + Debug.Assert(_state == StateClosed); + + // + // We must make sure that nobody is sending when we close + // the transceiver. + // + lock(_sendMutex) + { + if(_transceiver != null) + { + try + { + _transceiver.close(); + } + catch(LocalException) + { + // Here we ignore any exceptions in close(). + } + + _transceiver = null; + } + Monitor.PulseAll(this); + return; + } + } + } + + activate(); + } + + bool warnUdp = instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; + + bool closed = false; + + IceInternal.BasicStream stream = new IceInternal.BasicStream(instance_); + + while(!closed) + { + // + // We must accept new connections outside the thread + // synchronization, because we use blocking accept. + // + + try + { + try + { + stream.resize(IceInternal.Protocol.headerSize, true); + stream.pos(0); + _transceiver.read(stream, -1); + + int pos = stream.pos(); + if(pos < IceInternal.Protocol.headerSize) + { + // + // This situation is possible for small UDP packets. + // + throw new IllegalMessageSizeException(); + } + stream.pos(0); + byte[] m = stream.readBlob(4); + if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] || + m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3]) + { + BadMagicException ex = new BadMagicException(); + ex.badMagic = m; + throw ex; + } + byte pMajor = stream.readByte(); + byte pMinor = stream.readByte(); + if(pMajor != IceInternal.Protocol.protocolMajor) + { + UnsupportedProtocolException e = new UnsupportedProtocolException(); + e.badMajor = pMajor < 0 ? pMajor + 255 : pMajor; + e.badMinor = pMinor < 0 ? pMinor + 255 : pMinor; + e.major = IceInternal.Protocol.protocolMajor; + e.minor = IceInternal.Protocol.protocolMinor; + throw e; + } + byte eMajor = stream.readByte(); + byte eMinor = stream.readByte(); + if(eMajor != IceInternal.Protocol.encodingMajor) + { + UnsupportedEncodingException e = new UnsupportedEncodingException(); + e.badMajor = eMajor < 0 ? eMajor + 255 : eMajor; + e.badMinor = eMinor < 0 ? eMinor + 255 : eMinor; + e.major = IceInternal.Protocol.encodingMajor; + e.minor = IceInternal.Protocol.encodingMinor; + throw e; + } + stream.readByte(); // Skip message type. + stream.readByte(); // Skip compression flag. + int size = stream.readInt(); + if(size < IceInternal.Protocol.headerSize) + { + throw new IllegalMessageSizeException(); + } + if(size > instance_.messageSizeMax()) + { + throw new MemoryLimitException(); + } + if(size > stream.size()) + { + stream.resize(size, true); + } + stream.pos(pos); + + if(pos != stream.size()) + { + if(_endpoint.datagram()) + { + if(warnUdp) + { + _logger.warning("DatagramLimitException: maximum size of " + pos + " exceeded"); + } + throw new DatagramLimitException(); + } + else + { + _transceiver.read(stream, -1); + Debug.Assert(stream.pos() == stream.size()); + } + } + } + catch(DatagramLimitException) // Expected. + { + continue; + } + catch(SocketException ex) // Expected. + { + exception(ex); + } + catch(LocalException ex) + { + if(_endpoint.datagram()) + { + if(_warn) + { + warning("datagram connection exception:", ex); + } + continue; + } + else + { + exception(ex); + } + } + + byte compress = 0; + int requestId = 0; + int invokeNum = 0; + IceInternal.ServantManager servantManager = null; + ObjectAdapter adapter = null; + IceInternal.OutgoingAsync outAsync = null; + + LocalException localEx = null; + + Hashtable requests = null; + Hashtable asyncRequests = null; + + lock(this) + { + while(_state == StateHolding) + { + Monitor.Wait(this); + } + + if(_state != StateClosed) + { + parseMessage(ref stream, ref invokeNum, ref requestId, ref compress, ref servantManager, + ref adapter, ref outAsync); + } + + // + // parseMessage() can close the connection, so we must check + // for closed state again. + // + if(_state == StateClosed) + { + // + // We must make sure that nobody is sending when we close + // the transceiver. + // + lock(_sendMutex) + { + try + { + _transceiver.close(); + } + catch(LocalException ex) + { + localEx = ex; + } + + _transceiver = null; + Monitor.PulseAll(this); + + // + // We cannot simply return here. We have to make sure + // that all requests (regular and async) are notified + // about the closed connection below. + // + closed = true; + } + } + + if(_state == StateClosed || _state == StateClosing) + { + requests = _requests; + _requests = new Hashtable(); + + asyncRequests = _asyncRequests; + _asyncRequests = new Hashtable(); + } + } + + // + // Asynchronous replies must be handled outside the thread + // synchronization, so that nested calls are possible. + // + if(outAsync != null) + { + outAsync.finished__(stream); + } + + // + // Method invocation (or multiple invocations for batch messages) + // must be done outside the thread synchronization, so that nested + // calls are possible. + // + invokeAll(stream, invokeNum, requestId, compress, servantManager, adapter); + + if(requests != null) + { + foreach(IceInternal.Outgoing og in requests.Values) + { + og.finished(_exception); // The exception is immutable at this point. + } + } + + if(asyncRequests != null) + { + foreach(IceInternal.OutgoingAsync og in asyncRequests.Values) + { + og.finished__(_exception); // The exception is immutable at this point. + } + } + + if(localEx != null) + { + Debug.Assert(closed); + throw localEx; + } + } + finally + { + stream.reset(); + } + } + } + + public void RunThreadPerConnection() + { + if(instance_.initializationData().threadHook != null) + { + instance_.initializationData().threadHook.start(); + } + + try + { + run(); + } + catch(Exception ex) + { + _logger.error("exception in thread per connection:\n" + ToString() + "\n" + ex.ToString()); + } + catch(System.Exception ex) + { + _logger.error("system exception in thread per connection:\n" + ToString() + "\n" + + ex.ToString()); + } + finally + { + if(instance_.initializationData().threadHook != null) + { + instance_.initializationData().threadHook.stop(); + } + } + } + + private IceInternal.Incoming getIncoming(ObjectAdapter adapter, bool response, byte compress, int requestId) + { + IceInternal.Incoming inc = null; + + if(_cacheBuffers) + { + lock(_incomingCacheMutex) + { + if(_incomingCache == null) + { + inc = new IceInternal.Incoming(instance_, this, adapter, response, compress, requestId); + } + else + { + inc = _incomingCache; + _incomingCache = _incomingCache.next; + inc.reset(instance_, this, adapter, response, compress, requestId); + inc.next = null; + } + } + } + else + { + inc = new IceInternal.Incoming(instance_, this, adapter, response, compress, requestId); + } + + return inc; + } + + private void reclaimIncoming(IceInternal.Incoming inc) + { + if(_cacheBuffers) + { + lock(_incomingCacheMutex) + { + inc.next = _incomingCache; + _incomingCache = inc; + // + // Clear references to Ice objects as soon as possible. + // + _incomingCache.reclaim(); + } + } + } + + public IceInternal.Outgoing getOutgoing(IceInternal.Reference reference, string operation, OperationMode mode, + Context context, bool compress) + { + IceInternal.Outgoing outg = null; + + if(_cacheBuffers) + { + lock(_outgoingCacheMutex) + { + if(_outgoingCache == null) + { + outg = new IceInternal.Outgoing(this, reference, operation, mode, context, compress); + } + else + { + outg = _outgoingCache; + _outgoingCache = _outgoingCache.next; + outg.reset(reference, operation, mode, context, compress); + outg.next = null; + } + } + } + else + { + outg = new IceInternal.Outgoing(this, reference, operation, mode, context, compress); + } + + return outg; + } + + public void reclaimOutgoing(IceInternal.Outgoing outg) + { + if(_cacheBuffers) + { + // + // Clear references to Ice objects as soon as possible. + // + outg.reclaim(); + + lock(_outgoingCacheMutex) + { + outg.next = _outgoingCache; + _outgoingCache = outg; + } + } + } + + private Thread _thread; private bool _threadPerConnection; - private IceInternal.Transceiver _transceiver; - private string _desc; - private string _type; - private IceInternal.EndpointI _endpoint; - - private ObjectAdapter _adapter; - private IceInternal.ServantManager _servantManager; - - private Logger _logger; - private IceInternal.TraceLevels _traceLevels; - - private bool _registeredWithPool; - private int _finishedCount; - private IceInternal.ThreadPool _threadPool; - - private bool _warn; - - private int _acmTimeout; - private long _acmAbsoluteTimeoutMillis; - - private int _compressionLevel; - - private int _nextRequestId; - private Hashtable _requests = new Hashtable(); - private Hashtable _asyncRequests = new Hashtable(); - - private LocalException _exception; - - private bool _batchAutoFlush; - private IceInternal.BasicStream _batchStream; - private bool _batchStreamInUse; - private int _batchRequestNum; - private bool _batchRequestCompress; - private int _batchMarker; - - private int _dispatchCount; - - private int _state; // The current state. - private long _stateTime; // The last time when the state was changed. - - // - // We have a separate mutex for sending, so that we don't block - // the whole connection when we do a blocking send. - // - private object _sendMutex = new object(); - - private IceInternal.Incoming _incomingCache; - private object _incomingCacheMutex = new object(); - - private IceInternal.Outgoing _outgoingCache; - private object _outgoingCacheMutex = new object(); - - private static bool _compressionSupported; - - private bool _overrideCompress; - private bool _overrideCompressValue; - private bool _cacheBuffers; + private IceInternal.Transceiver _transceiver; + private string _desc; + private string _type; + private IceInternal.EndpointI _endpoint; + + private ObjectAdapter _adapter; + private IceInternal.ServantManager _servantManager; + + private Logger _logger; + private IceInternal.TraceLevels _traceLevels; + + private bool _registeredWithPool; + private int _finishedCount; + private IceInternal.ThreadPool _threadPool; + + private bool _warn; + + private int _acmTimeout; + private long _acmAbsoluteTimeoutMillis; + + private int _compressionLevel; + + private int _nextRequestId; + private Hashtable _requests = new Hashtable(); + private Hashtable _asyncRequests = new Hashtable(); + + private LocalException _exception; + + private bool _batchAutoFlush; + private IceInternal.BasicStream _batchStream; + private bool _batchStreamInUse; + private int _batchRequestNum; + private bool _batchRequestCompress; + private int _batchMarker; + + private int _dispatchCount; + + private int _state; // The current state. + private long _stateTime; // The last time when the state was changed. + + // + // We have a separate mutex for sending, so that we don't block + // the whole connection when we do a blocking send. + // + private object _sendMutex = new object(); + + private IceInternal.Incoming _incomingCache; + private object _incomingCacheMutex = new object(); + + private IceInternal.Outgoing _outgoingCache; + private object _outgoingCacheMutex = new object(); + + private static bool _compressionSupported; + + private bool _overrideCompress; + private bool _overrideCompressValue; + private bool _cacheBuffers; } } diff --git a/cs/src/Ice/ConnectionMonitor.cs b/cs/src/Ice/ConnectionMonitor.cs index e0280c77b2d..6aa99ae6f77 100755 --- a/cs/src/Ice/ConnectionMonitor.cs +++ b/cs/src/Ice/ConnectionMonitor.cs @@ -16,134 +16,134 @@ namespace IceInternal public sealed class ConnectionMonitor { - public void destroy() - { - lock(this) - { - Debug.Assert(instance_ != null); - - instance_ = null; - _connections = null; - - System.Threading.Monitor.Pulse(this); - } - - while(true) - { - _thread.Join(); - break; - } - } - - public void add(Ice.ConnectionI connection) - { - lock(this) - { - Debug.Assert(instance_ != null); - _connections.Add(connection); - } - } - - public void remove(Ice.ConnectionI connection) - { - lock(this) - { - Debug.Assert(instance_ != null); - _connections.Remove(connection); - } - } - - // - // Only for use by Instance. - // - internal ConnectionMonitor(Instance instance, int interval) - { - Debug.Assert(interval > 0); + public void destroy() + { + lock(this) + { + Debug.Assert(instance_ != null); + + instance_ = null; + _connections = null; + + System.Threading.Monitor.Pulse(this); + } + + while(true) + { + _thread.Join(); + break; + } + } + + public void add(Ice.ConnectionI connection) + { + lock(this) + { + Debug.Assert(instance_ != null); + _connections.Add(connection); + } + } + + public void remove(Ice.ConnectionI connection) + { + lock(this) + { + Debug.Assert(instance_ != null); + _connections.Remove(connection); + } + } + + // + // Only for use by Instance. + // + internal ConnectionMonitor(Instance instance, int interval) + { + Debug.Assert(interval > 0); - instance_ = instance; - _interval = interval * 1000; - _connections = new Set(); - - string threadName = instance_.initializationData().properties.getProperty("Ice.ProgramName"); - if(threadName.Length > 0) - { - threadName += "-"; - } + instance_ = instance; + _interval = interval * 1000; + _connections = new Set(); + + string threadName = instance_.initializationData().properties.getProperty("Ice.ProgramName"); + if(threadName.Length > 0) + { + threadName += "-"; + } - _thread = new Thread(new ThreadStart(Run)); + _thread = new Thread(new ThreadStart(Run)); _thread.IsBackground = true; - _thread.Name = threadName + "Ice.ConnectionMonitor"; - _thread.Start(); - } - - public void Run() - { - Set connections = new Set(); - - while(true) - { - lock(this) - { - if(instance_ != null) - { - System.Threading.Monitor.Wait(this, _interval); - } - - if(instance_ == null) - { - return; - } - - connections.Clear(); - foreach(Ice.ConnectionI connection in _connections) - { - connections.Add(connection); - } - } - - // - // Monitor connections outside the thread synchronization, - // so that connections can be added or removed during - // monitoring. - // - foreach(Ice.ConnectionI connection in connections) - { - try - { - connection.monitor(); - } - catch(Ice.LocalException ex) - { - lock(this) - { - if(instance_ == null) - { - return; - } - instance_.initializationData().logger.error("exception in connection monitor thread " + _thread.Name + - "::\n" + ex); - } - } - catch(System.Exception ex) - { - lock(this) - { - if(instance_ == null) - { - return; - } - instance_.initializationData().logger.error("unknown exception in connection monitor thread " + - _thread.Name + ":\n" + ex); - } - } - } - } - } - - private Instance instance_; - private readonly int _interval; - private Set _connections; - private Thread _thread; + _thread.Name = threadName + "Ice.ConnectionMonitor"; + _thread.Start(); + } + + public void Run() + { + Set connections = new Set(); + + while(true) + { + lock(this) + { + if(instance_ != null) + { + System.Threading.Monitor.Wait(this, _interval); + } + + if(instance_ == null) + { + return; + } + + connections.Clear(); + foreach(Ice.ConnectionI connection in _connections) + { + connections.Add(connection); + } + } + + // + // Monitor connections outside the thread synchronization, + // so that connections can be added or removed during + // monitoring. + // + foreach(Ice.ConnectionI connection in connections) + { + try + { + connection.monitor(); + } + catch(Ice.LocalException ex) + { + lock(this) + { + if(instance_ == null) + { + return; + } + instance_.initializationData().logger.error("exception in connection monitor thread " + _thread.Name + + "::\n" + ex); + } + } + catch(System.Exception ex) + { + lock(this) + { + if(instance_ == null) + { + return; + } + instance_.initializationData().logger.error("unknown exception in connection monitor thread " + + _thread.Name + ":\n" + ex); + } + } + } + } + } + + private Instance instance_; + private readonly int _interval; + private Set _connections; + private Thread _thread; } } diff --git a/cs/src/Ice/Connector.cs b/cs/src/Ice/Connector.cs index b13738191f5..8e3565301f2 100755 --- a/cs/src/Ice/Connector.cs +++ b/cs/src/Ice/Connector.cs @@ -12,7 +12,7 @@ namespace IceInternal public interface Connector { - Transceiver connect(int timeout); + Transceiver connect(int timeout); } } diff --git a/cs/src/Ice/DefaultsAndOverrides.cs b/cs/src/Ice/DefaultsAndOverrides.cs index efbf69e80bd..d7413dbf24d 100755 --- a/cs/src/Ice/DefaultsAndOverrides.cs +++ b/cs/src/Ice/DefaultsAndOverrides.cs @@ -14,75 +14,75 @@ namespace IceInternal public sealed class DefaultsAndOverrides { - internal DefaultsAndOverrides(Ice.Properties properties) - { - string val; - - defaultProtocol = properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp"); - - val = properties.getProperty("Ice.Default.Host"); - if(val.Length != 0) - { - defaultHost = val; - } - - val = properties.getProperty("Ice.Override.Timeout"); - if(val.Length > 0) - { - overrideTimeout = true; - overrideTimeoutValue = properties.getPropertyAsInt("Ice.Override.Timeout"); - } - else - { - overrideTimeout = false; - overrideTimeoutValue = -1; - } - - val = properties.getProperty("Ice.Override.ConnectTimeout"); - if(val.Length > 0) - { - overrideConnectTimeout = true; - overrideConnectTimeoutValue = properties.getPropertyAsInt("Ice.Override.ConnectTimeout"); - } - else - { - overrideConnectTimeout = false; - overrideConnectTimeoutValue = -1; - } + internal DefaultsAndOverrides(Ice.Properties properties) + { + string val; + + defaultProtocol = properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp"); + + val = properties.getProperty("Ice.Default.Host"); + if(val.Length != 0) + { + defaultHost = val; + } + + val = properties.getProperty("Ice.Override.Timeout"); + if(val.Length > 0) + { + overrideTimeout = true; + overrideTimeoutValue = properties.getPropertyAsInt("Ice.Override.Timeout"); + } + else + { + overrideTimeout = false; + overrideTimeoutValue = -1; + } + + val = properties.getProperty("Ice.Override.ConnectTimeout"); + if(val.Length > 0) + { + overrideConnectTimeout = true; + overrideConnectTimeoutValue = properties.getPropertyAsInt("Ice.Override.ConnectTimeout"); + } + else + { + overrideConnectTimeout = false; + overrideConnectTimeoutValue = -1; + } - val = properties.getProperty("Ice.Override.Compress"); - if(val.Length > 0) - { - overrideCompress = true; - overrideCompressValue = properties.getPropertyAsInt("Ice.Override.Compress") != 0; - if(!BasicStream.compressible() && overrideCompressValue) - { - Console.Error.WriteLine("warning: libbz2 not installed, Ice.Override.Compress ignored"); - overrideCompressValue = false; - } - } - else - { - overrideCompress = !BasicStream.compressible(); - overrideCompressValue = false; - } + val = properties.getProperty("Ice.Override.Compress"); + if(val.Length > 0) + { + overrideCompress = true; + overrideCompressValue = properties.getPropertyAsInt("Ice.Override.Compress") != 0; + if(!BasicStream.compressible() && overrideCompressValue) + { + Console.Error.WriteLine("warning: libbz2 not installed, Ice.Override.Compress ignored"); + overrideCompressValue = false; + } + } + else + { + overrideCompress = !BasicStream.compressible(); + overrideCompressValue = false; + } - val = properties.getProperty("Ice.Override.Secure"); - if(val.Length > 0) - { - overrideSecure = true; - overrideSecureValue = properties.getPropertyAsInt("Ice.Override.Secure") > 0; - } - else - { - overrideSecure = false; - overrideSecureValue = false; - } + val = properties.getProperty("Ice.Override.Secure"); + if(val.Length > 0) + { + overrideSecure = true; + overrideSecureValue = properties.getPropertyAsInt("Ice.Override.Secure") > 0; + } + else + { + overrideSecure = false; + overrideSecureValue = false; + } - defaultCollocationOptimization = - properties.getPropertyAsIntWithDefault("Ice.Default.CollocationOptimization", 1) > 0; + defaultCollocationOptimization = + properties.getPropertyAsIntWithDefault("Ice.Default.CollocationOptimization", 1) > 0; - val = properties.getPropertyWithDefault("Ice.Default.EndpointSelection", "Random"); + val = properties.getPropertyWithDefault("Ice.Default.EndpointSelection", "Random"); if(val.Equals("Random")) { defaultEndpointSelection = Ice.EndpointSelectionType.Random; @@ -98,26 +98,26 @@ namespace IceInternal throw ex; } - defaultLocatorCacheTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1); + defaultLocatorCacheTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1); - defaultPreferSecure = properties.getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0; - } - - public string defaultHost; - public string defaultProtocol; - public bool defaultCollocationOptimization; + defaultPreferSecure = properties.getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0; + } + + public string defaultHost; + public string defaultProtocol; + public bool defaultCollocationOptimization; public Ice.EndpointSelectionType defaultEndpointSelection; - public int defaultLocatorCacheTimeout; - public bool defaultPreferSecure; - - public bool overrideTimeout; - public int overrideTimeoutValue; - public bool overrideConnectTimeout; - public int overrideConnectTimeoutValue; - public bool overrideCompress; - public bool overrideCompressValue; - public bool overrideSecure; - public bool overrideSecureValue; + public int defaultLocatorCacheTimeout; + public bool defaultPreferSecure; + + public bool overrideTimeout; + public int overrideTimeoutValue; + public bool overrideConnectTimeout; + public int overrideConnectTimeoutValue; + public bool overrideCompress; + public bool overrideCompressValue; + public bool overrideSecure; + public bool overrideSecureValue; } } diff --git a/cs/src/Ice/Direct.cs b/cs/src/Ice/Direct.cs index f3a50b338b0..6e14126da1c 100755 --- a/cs/src/Ice/Direct.cs +++ b/cs/src/Ice/Direct.cs @@ -14,104 +14,104 @@ namespace IceInternal public sealed class Direct { - public Direct(Ice.Current current) - { - _current = current; - - Ice.ObjectAdapterI adapter = (Ice.ObjectAdapterI)_current.adapter; - Debug.Assert(adapter != null); - - // - // Must call incDirectCount() first, because it checks for - // adapter deactivation, and prevents deactivation completion - // until decDirectCount() is called. This is important, - // because getServantManager() may not be called afer - // deactivation completion. - // - adapter.incDirectCount(); - - ServantManager servantManager = adapter.getServantManager(); - Debug.Assert(servantManager != null); - - try - { - _servant = servantManager.findServant(_current.id, current.facet); - if(_servant == null) - { - _locator = servantManager.findServantLocator(_current.id.category); - if(_locator == null && _current.id.category.Length > 0) - { - _locator = servantManager.findServantLocator(""); - } - if(_locator != null) - { - _servant = _locator.locate(_current, out _cookie); - } - } - if(_servant == null) - { - if(servantManager != null && servantManager.hasServant(_current.id)) - { - Ice.FacetNotExistException ex = new Ice.FacetNotExistException(); - ex.id = _current.id; - ex.facet = _current.facet; - ex.operation = _current.operation; - throw ex; - } - else - { - Ice.ObjectNotExistException ex = new Ice.ObjectNotExistException(); - ex.id = _current.id; - ex.facet = _current.facet; - ex.operation = _current.operation; - throw ex; - } - } - } - catch(System.Exception) - { - try - { - if(_locator != null && _servant != null) - { - _locator.finished(_current, _servant, _cookie); - } - throw; - } - finally - { - adapter.decDirectCount(); - } - } - } - - public void destroy() - { - Ice.ObjectAdapterI adapter = (Ice.ObjectAdapterI)_current.adapter; - Debug.Assert(adapter != null); - - try - { - if(_locator != null && _servant != null) - { - _locator.finished(_current, _servant, _cookie); - } - } - finally - { - adapter.decDirectCount(); - } - } - - public Ice.Object servant() - { - return _servant; - } - - private Ice.Current _current; - private Ice.Object _servant; - private Ice.ServantLocator _locator; - private Ice.LocalObject _cookie; + public Direct(Ice.Current current) + { + _current = current; + + Ice.ObjectAdapterI adapter = (Ice.ObjectAdapterI)_current.adapter; + Debug.Assert(adapter != null); + + // + // Must call incDirectCount() first, because it checks for + // adapter deactivation, and prevents deactivation completion + // until decDirectCount() is called. This is important, + // because getServantManager() may not be called afer + // deactivation completion. + // + adapter.incDirectCount(); + + ServantManager servantManager = adapter.getServantManager(); + Debug.Assert(servantManager != null); + + try + { + _servant = servantManager.findServant(_current.id, current.facet); + if(_servant == null) + { + _locator = servantManager.findServantLocator(_current.id.category); + if(_locator == null && _current.id.category.Length > 0) + { + _locator = servantManager.findServantLocator(""); + } + if(_locator != null) + { + _servant = _locator.locate(_current, out _cookie); + } + } + if(_servant == null) + { + if(servantManager != null && servantManager.hasServant(_current.id)) + { + Ice.FacetNotExistException ex = new Ice.FacetNotExistException(); + ex.id = _current.id; + ex.facet = _current.facet; + ex.operation = _current.operation; + throw ex; + } + else + { + Ice.ObjectNotExistException ex = new Ice.ObjectNotExistException(); + ex.id = _current.id; + ex.facet = _current.facet; + ex.operation = _current.operation; + throw ex; + } + } + } + catch(System.Exception) + { + try + { + if(_locator != null && _servant != null) + { + _locator.finished(_current, _servant, _cookie); + } + throw; + } + finally + { + adapter.decDirectCount(); + } + } + } + + public void destroy() + { + Ice.ObjectAdapterI adapter = (Ice.ObjectAdapterI)_current.adapter; + Debug.Assert(adapter != null); + + try + { + if(_locator != null && _servant != null) + { + _locator.finished(_current, _servant, _cookie); + } + } + finally + { + adapter.decDirectCount(); + } + } + + public Ice.Object servant() + { + return _servant; + } + + private Ice.Current _current; + private Ice.Object _servant; + private Ice.ServantLocator _locator; + private Ice.LocalObject _cookie; } } diff --git a/cs/src/Ice/EndpointFactory.cs b/cs/src/Ice/EndpointFactory.cs index 5613e44f712..5c04622e4d2 100755 --- a/cs/src/Ice/EndpointFactory.cs +++ b/cs/src/Ice/EndpointFactory.cs @@ -12,11 +12,11 @@ namespace IceInternal public interface EndpointFactory { - short type(); - string protocol(); - EndpointI create(string str); - EndpointI read(BasicStream s); - void destroy(); + short type(); + string protocol(); + EndpointI create(string str); + EndpointI read(BasicStream s); + void destroy(); } } diff --git a/cs/src/Ice/EndpointFactoryManager.cs b/cs/src/Ice/EndpointFactoryManager.cs index 324eebbd39a..541489b848a 100755 --- a/cs/src/Ice/EndpointFactoryManager.cs +++ b/cs/src/Ice/EndpointFactoryManager.cs @@ -16,111 +16,111 @@ namespace IceInternal public sealed class EndpointFactoryManager { - internal EndpointFactoryManager(Instance instance) - { - instance_ = instance; - _factories = new ArrayList(); - } - - public void add(EndpointFactory factory) - { - lock(this) - { - for(int i = 0; i < _factories.Count; i++) - { - EndpointFactory f = (EndpointFactory)_factories[i]; - if(f.type() == factory.type()) - { - Debug.Assert(false); - } - } - _factories.Add(factory); - } - } - - public EndpointFactory get(short type) - { - lock(this) - { - for(int i = 0; i < _factories.Count; i++) - { - EndpointFactory f = (EndpointFactory)_factories[i]; - if(f.type() == type) - { - return f; - } - } - return null; - } - } - - public EndpointI create(string str) - { - lock(this) - { - string s = str.Trim(); - if(s.Length == 0) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = str; - throw e; - } - - Regex p = new Regex("([ \t\n\r]+)|$"); - Match m = p.Match(s); - Debug.Assert(m.Success); - - string protocol = s.Substring(0, m.Index); - - if(protocol.Equals("default")) - { - protocol = instance_.defaultsAndOverrides().defaultProtocol; - } - - for(int i = 0; i < _factories.Count; i++) - { - EndpointFactory f = (EndpointFactory)_factories[i]; - if(f.protocol().Equals(protocol)) - { - return f.create(s.Substring(m.Index + m.Length)); - } - } - - return null; - } - } - - public EndpointI read(BasicStream s) - { - lock(this) - { - short type = s.readShort(); - - for(int i = 0; i < _factories.Count; i++) - { - EndpointFactory f = (EndpointFactory)_factories[i]; - if(f.type() == type) - { - return f.read(s); - } - } - - return new UnknownEndpointI(type, s); - } - } - - internal void destroy() - { - for(int i = 0; i < _factories.Count; i++) - { - EndpointFactory f = (EndpointFactory)_factories[i]; - f.destroy(); - } - _factories.Clear(); - } - - private readonly Instance instance_; - private readonly ArrayList _factories; + internal EndpointFactoryManager(Instance instance) + { + instance_ = instance; + _factories = new ArrayList(); + } + + public void add(EndpointFactory factory) + { + lock(this) + { + for(int i = 0; i < _factories.Count; i++) + { + EndpointFactory f = (EndpointFactory)_factories[i]; + if(f.type() == factory.type()) + { + Debug.Assert(false); + } + } + _factories.Add(factory); + } + } + + public EndpointFactory get(short type) + { + lock(this) + { + for(int i = 0; i < _factories.Count; i++) + { + EndpointFactory f = (EndpointFactory)_factories[i]; + if(f.type() == type) + { + return f; + } + } + return null; + } + } + + public EndpointI create(string str) + { + lock(this) + { + string s = str.Trim(); + if(s.Length == 0) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = str; + throw e; + } + + Regex p = new Regex("([ \t\n\r]+)|$"); + Match m = p.Match(s); + Debug.Assert(m.Success); + + string protocol = s.Substring(0, m.Index); + + if(protocol.Equals("default")) + { + protocol = instance_.defaultsAndOverrides().defaultProtocol; + } + + for(int i = 0; i < _factories.Count; i++) + { + EndpointFactory f = (EndpointFactory)_factories[i]; + if(f.protocol().Equals(protocol)) + { + return f.create(s.Substring(m.Index + m.Length)); + } + } + + return null; + } + } + + public EndpointI read(BasicStream s) + { + lock(this) + { + short type = s.readShort(); + + for(int i = 0; i < _factories.Count; i++) + { + EndpointFactory f = (EndpointFactory)_factories[i]; + if(f.type() == type) + { + return f.read(s); + } + } + + return new UnknownEndpointI(type, s); + } + } + + internal void destroy() + { + for(int i = 0; i < _factories.Count; i++) + { + EndpointFactory f = (EndpointFactory)_factories[i]; + f.destroy(); + } + _factories.Clear(); + } + + private readonly Instance instance_; + private readonly ArrayList _factories; } } diff --git a/cs/src/Ice/EndpointI.cs b/cs/src/Ice/EndpointI.cs index d16396a5f4f..271d41b696f 100755 --- a/cs/src/Ice/EndpointI.cs +++ b/cs/src/Ice/EndpointI.cs @@ -24,102 +24,102 @@ namespace IceInternal return MemberwiseClone(); } - public override string ToString() + public override string ToString() { - return ice_toString_(); - } - - public abstract string ice_toString_(); - public abstract int CompareTo(object obj); - - // - // Marshal the endpoint. - // - public abstract void streamWrite(BasicStream s); - - // - // Return the endpoint type. - // - public abstract short type(); - - // - // Return the timeout for the endpoint in milliseconds. 0 means - // non-blocking, -1 means no timeout. - // - public abstract int timeout(); - - // - // Return a new endpoint with a different timeout value, provided - // that timeouts are supported by the endpoint. Otherwise the same - // endpoint is returned. - // - public abstract EndpointI timeout(int t); - - // - // Return a new endpoint with a different connection id. - // - public abstract EndpointI connectionId(string connectionId); - - // - // Return true if the endpoints support bzip2 compress, or false - // otherwise. - // - public abstract bool compress(); - - // - // Return a new endpoint with a different compression value, - // provided that compression is supported by the - // endpoint. Otherwise the same endpoint is returned. - // - public abstract EndpointI compress(bool co); - - // - // Return true if the endpoint is datagram-based. - // - public abstract bool datagram(); - - // - // Return true if the endpoint is secure. - // - public abstract bool secure(); - - // - // Return true if the endpoint type is unknown. - // - public abstract bool unknown(); - - // - // Return a client side transceiver for this endpoint, or null if a - // transceiver can only be created by a connector. - // - public abstract Transceiver clientTransceiver(); - - // - // Return a server side transceiver for this endpoint, or null if a - // transceiver can only be created by an acceptor. In case a - // transceiver is created, this operation also returns a new - // "effective" endpoint, which might differ from this endpoint, - // for example, if a dynamic port number is assigned. - // - public abstract Transceiver serverTransceiver(ref EndpointI endpoint); - - // - // Return a connector for this endpoint, or null if no connector - // is available. - // - public abstract Connector connector(); - - // - // Return an acceptor for this endpoint, or null if no acceptors - // is available. In case an acceptor is created, this operation - // also returns a new "effective" endpoint, which might differ - // from this endpoint, for example, if a dynamic port number is - // assigned. - // - public abstract Acceptor acceptor(ref EndpointI endpoint, string adapterName); - - // - // Expand endpoint out in to separate endpoints for each local + return ice_toString_(); + } + + public abstract string ice_toString_(); + public abstract int CompareTo(object obj); + + // + // Marshal the endpoint. + // + public abstract void streamWrite(BasicStream s); + + // + // Return the endpoint type. + // + public abstract short type(); + + // + // Return the timeout for the endpoint in milliseconds. 0 means + // non-blocking, -1 means no timeout. + // + public abstract int timeout(); + + // + // Return a new endpoint with a different timeout value, provided + // that timeouts are supported by the endpoint. Otherwise the same + // endpoint is returned. + // + public abstract EndpointI timeout(int t); + + // + // Return a new endpoint with a different connection id. + // + public abstract EndpointI connectionId(string connectionId); + + // + // Return true if the endpoints support bzip2 compress, or false + // otherwise. + // + public abstract bool compress(); + + // + // Return a new endpoint with a different compression value, + // provided that compression is supported by the + // endpoint. Otherwise the same endpoint is returned. + // + public abstract EndpointI compress(bool co); + + // + // Return true if the endpoint is datagram-based. + // + public abstract bool datagram(); + + // + // Return true if the endpoint is secure. + // + public abstract bool secure(); + + // + // Return true if the endpoint type is unknown. + // + public abstract bool unknown(); + + // + // Return a client side transceiver for this endpoint, or null if a + // transceiver can only be created by a connector. + // + public abstract Transceiver clientTransceiver(); + + // + // Return a server side transceiver for this endpoint, or null if a + // transceiver can only be created by an acceptor. In case a + // transceiver is created, this operation also returns a new + // "effective" endpoint, which might differ from this endpoint, + // for example, if a dynamic port number is assigned. + // + public abstract Transceiver serverTransceiver(ref EndpointI endpoint); + + // + // Return a connector for this endpoint, or null if no connector + // is available. + // + public abstract Connector connector(); + + // + // Return an acceptor for this endpoint, or null if no acceptors + // is available. In case an acceptor is created, this operation + // also returns a new "effective" endpoint, which might differ + // from this endpoint, for example, if a dynamic port number is + // assigned. + // + public abstract Acceptor acceptor(ref EndpointI endpoint, string adapterName); + + // + // Expand endpoint out in to separate endpoints for each local // host if endpoint was configured with no host set. // public abstract ArrayList expand(bool server); @@ -128,14 +128,14 @@ namespace IceInternal // Return whether the endpoint should be published in proxies // created by the Object Adapter. // - public abstract bool publish(); + public abstract bool publish(); - // - // Check whether the endpoint is equivalent to a specific - // Transceiver or Acceptor. - // - public abstract bool equivalent(Transceiver transceiver); - public abstract bool equivalent(Acceptor acceptor); + // + // Check whether the endpoint is equivalent to a specific + // Transceiver or Acceptor. + // + public abstract bool equivalent(Transceiver transceiver); + public abstract bool equivalent(Acceptor acceptor); // // Returns true if the endpoint's transport requires thread-per-connection. diff --git a/cs/src/Ice/EventHandler.cs b/cs/src/Ice/EventHandler.cs index c5b4491ee11..089d7837c46 100755 --- a/cs/src/Ice/EventHandler.cs +++ b/cs/src/Ice/EventHandler.cs @@ -14,61 +14,61 @@ namespace IceInternal public abstract class EventHandler { - // - // Return true if the handler is for a datagram transport, false otherwise. - // - abstract public bool datagram(); - - // - // Return true if read() must be called before calling message(). - // - abstract public bool readable(); - - // - // Read data via the event handler. May only be called if - // readable() returns true. - // - abstract public void read(BasicStream istr); - - // - // A complete message has been received. - // - abstract public void message(BasicStream stream, ThreadPool threadPool); - - // - // Will be called if the event handler is finally - // unregistered. (Calling unregister() does not unregister - // immediately.) - // - abstract public void finished(ThreadPool threadPool); - - // - // Propagate an exception to the event handler. - // - abstract public void exception(Ice.LocalException ex); - - // - // Get a textual representation of the event handler. - // - public abstract override string ToString(); - + // + // Return true if the handler is for a datagram transport, false otherwise. + // + abstract public bool datagram(); + + // + // Return true if read() must be called before calling message(). + // + abstract public bool readable(); + + // + // Read data via the event handler. May only be called if + // readable() returns true. + // + abstract public void read(BasicStream istr); + + // + // A complete message has been received. + // + abstract public void message(BasicStream stream, ThreadPool threadPool); + + // + // Will be called if the event handler is finally + // unregistered. (Calling unregister() does not unregister + // immediately.) + // + abstract public void finished(ThreadPool threadPool); + + // + // Propagate an exception to the event handler. + // + abstract public void exception(Ice.LocalException ex); + + // + // Get a textual representation of the event handler. + // + public abstract override string ToString(); + public Instance instance() { return instance_; } - protected internal EventHandler(Instance instance) - { - instance_ = instance; - stream_ = new BasicStream(instance); - } + protected internal EventHandler(Instance instance) + { + instance_ = instance; + stream_ = new BasicStream(instance); + } - protected internal Instance instance_; - - // - // The stream_ data member is for use by ThreadPool only. - // - internal BasicStream stream_; + protected internal Instance instance_; + + // + // The stream_ data member is for use by ThreadPool only. + // + internal BasicStream stream_; } } diff --git a/cs/src/Ice/Exception.cs b/cs/src/Ice/Exception.cs index 758d30995fd..a22e8b3ee83 100755 --- a/cs/src/Ice/Exception.cs +++ b/cs/src/Ice/Exception.cs @@ -18,40 +18,40 @@ namespace Ice public Exception(string msg) : base(msg) {} public Exception(System.Exception ex) : base(_dflt, ex) {} public Exception(string msg, System.Exception ex) : base(msg, ex) {} - public override string ToString() - { - // - // This prints the exception Java style. That is outmost - // exception, Caused by: to the innermost exception. The - // stack trace is not nicely indented as with Java, but - // without string parsing (perhaps tokenize on "\n") it - // doesn't appear to be possible to reformat it. - // - System.IO.StringWriter sw = new System.IO.StringWriter(); - IceUtil.OutputBase op = new IceUtil.OutputBase(sw); - op.setUseTab(false); - op.print(GetType().FullName); - op.print(": "); - op.print(Message); - op.inc(); - IceInternal.ValueWriter.write(this, op); - sw.Write("\n"); - sw.Write(StackTrace); - - System.Exception curr = InnerException; - while(curr != null) - { - sw.Write("\nCaused by: "); - sw.Write(curr.GetType().FullName); - sw.Write(": "); - sw.Write(curr.Message); - sw.Write("\n"); - sw.Write(curr.StackTrace); - curr = curr.InnerException; - } - - return sw.ToString(); - } + public override string ToString() + { + // + // This prints the exception Java style. That is outmost + // exception, Caused by: to the innermost exception. The + // stack trace is not nicely indented as with Java, but + // without string parsing (perhaps tokenize on "\n") it + // doesn't appear to be possible to reformat it. + // + System.IO.StringWriter sw = new System.IO.StringWriter(); + IceUtil.OutputBase op = new IceUtil.OutputBase(sw); + op.setUseTab(false); + op.print(GetType().FullName); + op.print(": "); + op.print(Message); + op.inc(); + IceInternal.ValueWriter.write(this, op); + sw.Write("\n"); + sw.Write(StackTrace); + + System.Exception curr = InnerException; + while(curr != null) + { + sw.Write("\nCaused by: "); + sw.Write(curr.GetType().FullName); + sw.Write(": "); + sw.Write(curr.Message); + sw.Write("\n"); + sw.Write(curr.StackTrace); + curr = curr.InnerException; + } + + return sw.ToString(); + } private static readonly string _dflt = "Ice.Exception"; } @@ -74,20 +74,20 @@ namespace Ice public abstract void write__(IceInternal.BasicStream os__); public abstract void read__(IceInternal.BasicStream is__, bool rid__); - public virtual void write__(Ice.OutputStream outS__) - { - Debug.Assert(false); - } + public virtual void write__(Ice.OutputStream outS__) + { + Debug.Assert(false); + } - public virtual void read__(Ice.InputStream inS__, bool rid__) - { - Debug.Assert(false); - } + public virtual void read__(Ice.InputStream inS__, bool rid__) + { + Debug.Assert(false); + } - public virtual bool usesClasses__() - { - return false; - } + public virtual bool usesClasses__() + { + return false; + } } } @@ -100,19 +100,19 @@ namespace IceInternal public LocalExceptionWrapper(Ice.LocalException ex, bool retry) { _ex = ex; - _retry = retry; + _retry = retry; } - public LocalExceptionWrapper(LocalExceptionWrapper ex) - { - _ex = ex.get(); - _retry = ex._retry; - } + public LocalExceptionWrapper(LocalExceptionWrapper ex) + { + _ex = ex.get(); + _retry = ex._retry; + } - public Ice.LocalException get() - { - return _ex; - } + public Ice.LocalException get() + { + return _ex; + } // // If true, always repeat the request. Don't take retry settings @@ -126,9 +126,9 @@ namespace IceInternal { return _retry; } - + private Ice.LocalException _ex; - private bool _retry; + private bool _retry; } } diff --git a/cs/src/Ice/ImplicitContextI.cs b/cs/src/Ice/ImplicitContextI.cs index 4aeb8867474..e97d76c2f24 100644 --- a/cs/src/Ice/ImplicitContextI.cs +++ b/cs/src/Ice/ImplicitContextI.cs @@ -17,413 +17,413 @@ namespace Ice // public abstract class ImplicitContextI : LocalObjectImpl, ImplicitContext { - public static ImplicitContextI create(string kind) - { - if(kind.Equals("None") || kind.Equals("")) - { - return null; - } - else if(kind.Equals("Shared")) - { - return new SharedImplicitContext(); - } - else if(kind.Equals("SharedWithoutLocking")) - { - return new SharedImplicitContextWithoutLocking(); - } - else if(kind.Equals("PerThread")) - { - return new PerThreadImplicitContext(); - } - else - { - throw new Ice.InitializationException( - "'" + kind + "' is not a valid value for Ice.ImplicitContext"); - } - } - - public abstract Context getContext(); - public abstract void setContext(Context newContext); - public abstract string get(string key); - public abstract string getWithDefault(string key, string defaultValue); - public abstract void set(string key, string value); - public abstract void remove(string key); + public static ImplicitContextI create(string kind) + { + if(kind.Equals("None") || kind.Equals("")) + { + return null; + } + else if(kind.Equals("Shared")) + { + return new SharedImplicitContext(); + } + else if(kind.Equals("SharedWithoutLocking")) + { + return new SharedImplicitContextWithoutLocking(); + } + else if(kind.Equals("PerThread")) + { + return new PerThreadImplicitContext(); + } + else + { + throw new Ice.InitializationException( + "'" + kind + "' is not a valid value for Ice.ImplicitContext"); + } + } + + public abstract Context getContext(); + public abstract void setContext(Context newContext); + public abstract string get(string key); + public abstract string getWithDefault(string key, string defaultValue); + public abstract void set(string key, string value); + public abstract void remove(string key); - abstract public void write(Context prxContext, IceInternal.BasicStream os); - abstract internal Context combine(Context prxContext); + abstract public void write(Context prxContext, IceInternal.BasicStream os); + abstract internal Context combine(Context prxContext); } - + internal class SharedImplicitContextWithoutLocking : ImplicitContextI { - public override Context getContext() - { - return (Context)_context.Clone(); - } - - public override void setContext(Context context) - { - if(context != null && context.Count != 0) - { - _context = (Context)context.Clone(); - } - else - { - _context.Clear(); - } - } - - public override string get(string key) - { - if(key == null) - { - key = ""; - } - - string val = _context[key]; - if(val == null) - { - throw new NotSetException(key); - } - else - { - return val; - } - } - - public override string getWithDefault(string key, string dflt) - { - if(key == null) - { - key = ""; - } - if(dflt == null) - { - dflt = ""; - } - - string val = _context[key]; - return val == null ? dflt : val; - } - - public override void set(string key, string value) - { - if(key == null) - { - key = ""; - } - if(value == null) - { - value = ""; - } - - _context[key] = value; - } - - public override void remove(string key) - { - if(key == null) - { - key = ""; - } - - if(_context.Contains(key)) - { - _context.Remove(key); - } - else - { - throw new NotSetException(key); - } - } - - public override void write(Context prxContext, IceInternal.BasicStream os) - { - if(prxContext.Count == 0) - { - ContextHelper.write(os, _context); - } - else if(_context.Count == 0) - { - ContextHelper.write(os, prxContext); - } - else - { - ContextHelper.write(os, combine(prxContext)); - } - } - - internal override Context combine(Context prxContext) - { - Context combined = (Context)prxContext.Clone(); - combined.AddRange(_context); - return combined; - } - - protected Context _context = new Context(); + public override Context getContext() + { + return (Context)_context.Clone(); + } + + public override void setContext(Context context) + { + if(context != null && context.Count != 0) + { + _context = (Context)context.Clone(); + } + else + { + _context.Clear(); + } + } + + public override string get(string key) + { + if(key == null) + { + key = ""; + } + + string val = _context[key]; + if(val == null) + { + throw new NotSetException(key); + } + else + { + return val; + } + } + + public override string getWithDefault(string key, string dflt) + { + if(key == null) + { + key = ""; + } + if(dflt == null) + { + dflt = ""; + } + + string val = _context[key]; + return val == null ? dflt : val; + } + + public override void set(string key, string value) + { + if(key == null) + { + key = ""; + } + if(value == null) + { + value = ""; + } + + _context[key] = value; + } + + public override void remove(string key) + { + if(key == null) + { + key = ""; + } + + if(_context.Contains(key)) + { + _context.Remove(key); + } + else + { + throw new NotSetException(key); + } + } + + public override void write(Context prxContext, IceInternal.BasicStream os) + { + if(prxContext.Count == 0) + { + ContextHelper.write(os, _context); + } + else if(_context.Count == 0) + { + ContextHelper.write(os, prxContext); + } + else + { + ContextHelper.write(os, combine(prxContext)); + } + } + + internal override Context combine(Context prxContext) + { + Context combined = (Context)prxContext.Clone(); + combined.AddRange(_context); + return combined; + } + + protected Context _context = new Context(); } - + internal class SharedImplicitContext : SharedImplicitContextWithoutLocking { - public override Context getContext() - { - lock(this) - { - return base.getContext(); - } - } - - public override void setContext(Context context) - { - lock(this) - { - base.setContext(context); - } - } - - public override string get(string key) - { - lock(this) - { - return base.get(key); - } - } - - public override string getWithDefault(string key, string dflt) - { - lock(this) - { - return base.getWithDefault(key, dflt); - } - } - - public override void set(string key, string value) - { - lock(this) - { - base.set(key, value); - } - } - - public override void remove(string key) - { - lock(this) - { - base.remove(key); - } - } - - public override void write(Context prxContext, IceInternal.BasicStream os) - { - if(prxContext.Count == 0) - { - lock(this) - { - ContextHelper.write(os, _context); - } - } - else - { - Context ctx = null; - lock(this) - { - ctx = _context.Count == 0 ? prxContext : base.combine(prxContext); - } - ContextHelper.write(os, ctx); - } - } + public override Context getContext() + { + lock(this) + { + return base.getContext(); + } + } + + public override void setContext(Context context) + { + lock(this) + { + base.setContext(context); + } + } + + public override string get(string key) + { + lock(this) + { + return base.get(key); + } + } + + public override string getWithDefault(string key, string dflt) + { + lock(this) + { + return base.getWithDefault(key, dflt); + } + } + + public override void set(string key, string value) + { + lock(this) + { + base.set(key, value); + } + } + + public override void remove(string key) + { + lock(this) + { + base.remove(key); + } + } + + public override void write(Context prxContext, IceInternal.BasicStream os) + { + if(prxContext.Count == 0) + { + lock(this) + { + ContextHelper.write(os, _context); + } + } + else + { + Context ctx = null; + lock(this) + { + ctx = _context.Count == 0 ? prxContext : base.combine(prxContext); + } + ContextHelper.write(os, ctx); + } + } - internal override Context combine(Context prxContext) - { - lock(this) - { - return base.combine(prxContext); - } - } + internal override Context combine(Context prxContext) + { + lock(this) + { + return base.combine(prxContext); + } + } } internal class PerThreadImplicitContext : ImplicitContextI { - public override Context getContext() - { - Context threadContext = null; - lock(this) - { - threadContext = (Context)_map[Thread.CurrentThread]; - } + public override Context getContext() + { + Context threadContext = null; + lock(this) + { + threadContext = (Context)_map[Thread.CurrentThread]; + } - if(threadContext == null) - { - threadContext = new Context(); - } - return threadContext; - } + if(threadContext == null) + { + threadContext = new Context(); + } + return threadContext; + } - public override void setContext(Context context) - { - if(context == null || context.Count == 0) - { - lock(this) - { - _map.Remove(Thread.CurrentThread); - } - } - else - { - Context threadContext = (Context)context.Clone(); - - lock(this) - { - _map.Add(Thread.CurrentThread, threadContext); - } - } - } + public override void setContext(Context context) + { + if(context == null || context.Count == 0) + { + lock(this) + { + _map.Remove(Thread.CurrentThread); + } + } + else + { + Context threadContext = (Context)context.Clone(); + + lock(this) + { + _map.Add(Thread.CurrentThread, threadContext); + } + } + } - public override string get(string key) - { - if(key == null) - { - key = ""; - } + public override string get(string key) + { + if(key == null) + { + key = ""; + } - Context threadContext = null; - lock(this) - { - threadContext = (Context)_map[Thread.CurrentThread]; - } + Context threadContext = null; + lock(this) + { + threadContext = (Context)_map[Thread.CurrentThread]; + } - if(threadContext == null) - { - throw new NotSetException(key); - } - string val = threadContext[key]; - if(val == null) - { - throw new NotSetException(key); - } - return val; - } + if(threadContext == null) + { + throw new NotSetException(key); + } + string val = threadContext[key]; + if(val == null) + { + throw new NotSetException(key); + } + return val; + } - public override string getWithDefault(string key, string dflt) - { - if(key == null) - { - key = ""; - } - if(dflt == null) - { - dflt = ""; - } + public override string getWithDefault(string key, string dflt) + { + if(key == null) + { + key = ""; + } + if(dflt == null) + { + dflt = ""; + } - Context threadContext = null; - lock(this) - { - threadContext = (Context)_map[Thread.CurrentThread]; - } + Context threadContext = null; + lock(this) + { + threadContext = (Context)_map[Thread.CurrentThread]; + } - if(threadContext == null) - { - return dflt; - } - string val = threadContext[key]; - if(val == null) - { - return dflt; - } - return val; - } + if(threadContext == null) + { + return dflt; + } + string val = threadContext[key]; + if(val == null) + { + return dflt; + } + return val; + } - public override void set(string key, string value) - { - if(key == null) - { - key = ""; - } - if(value == null) - { - value = ""; - } + public override void set(string key, string value) + { + if(key == null) + { + key = ""; + } + if(value == null) + { + value = ""; + } - Thread currentThread = Thread.CurrentThread; - - Context threadContext = null; - lock(this) - { - threadContext = (Context)_map[currentThread]; - } - - if(threadContext == null) - { - threadContext = new Context(); - lock(this) - { - _map.Add(currentThread, threadContext); - } - } - - threadContext[key] = value; - } + Thread currentThread = Thread.CurrentThread; + + Context threadContext = null; + lock(this) + { + threadContext = (Context)_map[currentThread]; + } + + if(threadContext == null) + { + threadContext = new Context(); + lock(this) + { + _map.Add(currentThread, threadContext); + } + } + + threadContext[key] = value; + } - public override void remove(string key) - { - if(key == null) - { - key = ""; - } + public override void remove(string key) + { + if(key == null) + { + key = ""; + } - Context threadContext = null; - lock(this) - { - threadContext = (Context)_map[Thread.CurrentThread]; - } + Context threadContext = null; + lock(this) + { + threadContext = (Context)_map[Thread.CurrentThread]; + } - if(threadContext == null || !threadContext.Contains(key)) - { - throw new NotSetException(key); - } - threadContext.Remove(key); - } + if(threadContext == null || !threadContext.Contains(key)) + { + throw new NotSetException(key); + } + threadContext.Remove(key); + } - public override void write(Context prxContext, IceInternal.BasicStream os) - { - Context threadContext = null; - lock(this) - { - threadContext = (Context)_map[Thread.CurrentThread]; - } - - if(threadContext == null || threadContext.Count == 0) - { - ContextHelper.write(os, prxContext); - } - else if(prxContext.Count == 0) - { - ContextHelper.write(os, threadContext); - } - else - { - Context combined = (Context)prxContext.Clone(); - combined.AddRange(threadContext); - ContextHelper.write(os, combined); - } - } + public override void write(Context prxContext, IceInternal.BasicStream os) + { + Context threadContext = null; + lock(this) + { + threadContext = (Context)_map[Thread.CurrentThread]; + } + + if(threadContext == null || threadContext.Count == 0) + { + ContextHelper.write(os, prxContext); + } + else if(prxContext.Count == 0) + { + ContextHelper.write(os, threadContext); + } + else + { + Context combined = (Context)prxContext.Clone(); + combined.AddRange(threadContext); + ContextHelper.write(os, combined); + } + } - internal override Context combine(Context prxContext) - { - Context threadContext = null; - lock(this) - { - threadContext = (Context)_map[Thread.CurrentThread]; - } + internal override Context combine(Context prxContext) + { + Context threadContext = null; + lock(this) + { + threadContext = (Context)_map[Thread.CurrentThread]; + } - Context combined = (Context)prxContext.Clone(); - combined.AddRange(threadContext); - return combined; - } + Context combined = (Context)prxContext.Clone(); + combined.AddRange(threadContext); + return combined; + } - // - // map Thread -> Context - // - private Hashtable _map = new Hashtable(); + // + // map Thread -> Context + // + private Hashtable _map = new Hashtable(); } } diff --git a/cs/src/Ice/Incoming.cs b/cs/src/Ice/Incoming.cs index 03b39760b6a..c0ccbdc5fcc 100755 --- a/cs/src/Ice/Incoming.cs +++ b/cs/src/Ice/Incoming.cs @@ -16,160 +16,160 @@ namespace IceInternal public class IncomingBase { - protected internal IncomingBase(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, - bool response, byte compress, int requestId) - { - response_ = response; - compress_ = compress; - os_ = new BasicStream(instance); - connection_ = connection; - - current_ = new Ice.Current(); - current_.id = new Ice.Identity(); - current_.adapter = adapter; - current_.con = connection; - current_.requestId = requestId; - - cookie_ = null; - } - - protected internal IncomingBase(IncomingBase inc) // Adopts the argument. It must not be used afterwards. - { - current_ = inc.current_; - - servant_ = inc.servant_; - inc.servant_ = null; - - locator_ = inc.locator_; - inc.locator_ = null; - - cookie_ = inc.cookie_; - inc.cookie_ = null; - - response_ = inc.response_; - inc.response_ = false; - - compress_ = inc.compress_; - inc.compress_ = 0; - - os_ = inc.os_; - inc.os_ = null; - - connection_ = inc.connection_; - inc.connection_ = null; - } - - // - // These functions allow this object to be reused, rather than reallocated. - // - public virtual void reset(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, - bool response, byte compress, int requestId) - { + protected internal IncomingBase(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, + bool response, byte compress, int requestId) + { + response_ = response; + compress_ = compress; + os_ = new BasicStream(instance); + connection_ = connection; + + current_ = new Ice.Current(); + current_.id = new Ice.Identity(); + current_.adapter = adapter; + current_.con = connection; + current_.requestId = requestId; + + cookie_ = null; + } + + protected internal IncomingBase(IncomingBase inc) // Adopts the argument. It must not be used afterwards. + { + current_ = inc.current_; + + servant_ = inc.servant_; + inc.servant_ = null; + + locator_ = inc.locator_; + inc.locator_ = null; + + cookie_ = inc.cookie_; + inc.cookie_ = null; + + response_ = inc.response_; + inc.response_ = false; + + compress_ = inc.compress_; + inc.compress_ = 0; + + os_ = inc.os_; + inc.os_ = null; + + connection_ = inc.connection_; + inc.connection_ = null; + } + + // + // These functions allow this object to be reused, rather than reallocated. + // + public virtual void reset(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, + bool response, byte compress, int requestId) + { // // Don't recycle the Current object, because servants may keep a reference to it. // - current_ = new Ice.Current(); - current_.id = new Ice.Identity(); - current_.adapter = adapter; - current_.con = connection; - current_.requestId = requestId; - - Debug.Assert(cookie_ == null); - - response_ = response; - - compress_ = compress; - - if(os_ == null) - { - os_ = new BasicStream(instance); - } - - connection_ = connection; - } - - public virtual void reclaim() - { - servant_ = null; - - locator_ = null; - - cookie_ = null; - - if(os_ != null) - { - os_.reset(); - } - } - - protected internal void warning__(System.Exception ex) - { - Debug.Assert(os_ != null); - - using(StringWriter sw = new StringWriter()) - { - IceUtil.OutputBase output = new IceUtil.OutputBase(sw); - output.setUseTab(false); - output.print("dispatch exception:"); - output.print("\nidentity: " + os_.instance().identityToString(current_.id)); - output.print("\nfacet: " + IceUtil.StringUtil.escapeString(current_.facet, "")); - output.print("\noperation: " + current_.operation); - output.print("\n"); - output.print(ex.ToString()); - os_.instance().initializationData().logger.warning(sw.ToString()); - } - } - - protected internal void handleException__(System.Exception exc) + current_ = new Ice.Current(); + current_.id = new Ice.Identity(); + current_.adapter = adapter; + current_.con = connection; + current_.requestId = requestId; + + Debug.Assert(cookie_ == null); + + response_ = response; + + compress_ = compress; + + if(os_ == null) + { + os_ = new BasicStream(instance); + } + + connection_ = connection; + } + + public virtual void reclaim() + { + servant_ = null; + + locator_ = null; + + cookie_ = null; + + if(os_ != null) + { + os_.reset(); + } + } + + protected internal void warning__(System.Exception ex) + { + Debug.Assert(os_ != null); + + using(StringWriter sw = new StringWriter()) + { + IceUtil.OutputBase output = new IceUtil.OutputBase(sw); + output.setUseTab(false); + output.print("dispatch exception:"); + output.print("\nidentity: " + os_.instance().identityToString(current_.id)); + output.print("\nfacet: " + IceUtil.StringUtil.escapeString(current_.facet, "")); + output.print("\noperation: " + current_.operation); + output.print("\n"); + output.print(ex.ToString()); + os_.instance().initializationData().logger.warning(sw.ToString()); + } + } + + protected internal void handleException__(System.Exception exc) { - try - { - throw exc; - } - catch(Ice.RequestFailedException ex) - { - if(ex.id == null) - { - ex.id = current_.id; - } - - if(ex.facet == null) - { - ex.facet = current_.facet; - } - - if(ex.operation == null || ex.operation.Length == 0) - { - ex.operation = current_.operation; - } - - if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Dispatch", 1) > 1) - { - warning__(ex); - } - - if(response_) - { - os_.endWriteEncaps(); - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - if(ex is Ice.ObjectNotExistException) - { - os_.writeByte((byte)DispatchStatus.DispatchObjectNotExist); - } - else if(ex is Ice.FacetNotExistException) - { - os_.writeByte((byte)DispatchStatus.DispatchFacetNotExist); - } - else if(ex is Ice.OperationNotExistException) - { - os_.writeByte((byte)DispatchStatus.DispatchOperationNotExist); - } - else - { - Debug.Assert(false); - } - ex.id.write__(os_); + try + { + throw exc; + } + catch(Ice.RequestFailedException ex) + { + if(ex.id == null) + { + ex.id = current_.id; + } + + if(ex.facet == null) + { + ex.facet = current_.facet; + } + + if(ex.operation == null || ex.operation.Length == 0) + { + ex.operation = current_.operation; + } + + if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Dispatch", 1) > 1) + { + warning__(ex); + } + + if(response_) + { + os_.endWriteEncaps(); + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + if(ex is Ice.ObjectNotExistException) + { + os_.writeByte((byte)DispatchStatus.DispatchObjectNotExist); + } + else if(ex is Ice.FacetNotExistException) + { + os_.writeByte((byte)DispatchStatus.DispatchFacetNotExist); + } + else if(ex is Ice.OperationNotExistException) + { + os_.writeByte((byte)DispatchStatus.DispatchOperationNotExist); + } + else + { + Debug.Assert(false); + } + ex.id.write__(os_); // // For compatibility with the old FacetPath. @@ -184,211 +184,211 @@ namespace IceInternal os_.writeStringSeq(facetPath2); } - os_.writeString(ex.operation); - - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - - return; - } - catch(Ice.UnknownLocalException ex) - { - if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - - if(response_) - { - os_.endWriteEncaps(); - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - os_.writeByte((byte)DispatchStatus.DispatchUnknownLocalException); - os_.writeString(ex.unknown); - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - - return; - } - catch(Ice.UnknownUserException ex) - { - if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - - if(response_) - { - os_.endWriteEncaps(); - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - os_.writeByte((byte)DispatchStatus.DispatchUnknownUserException); - os_.writeString(ex.unknown); - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - - return; - } - catch(Ice.UnknownException ex) - { - if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - - if(response_) - { - os_.endWriteEncaps(); - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - os_.writeByte((byte)DispatchStatus.DispatchUnknownException); - os_.writeString(ex.unknown); - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - - return; - } - catch(Ice.LocalException ex) - { - if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - - if(response_) - { - os_.endWriteEncaps(); - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - os_.writeByte((byte)DispatchStatus.DispatchUnknownLocalException); - os_.writeString(ex.ToString()); - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - - return; - } - - catch(Ice.UserException ex) - { - if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - - if(response_) - { - os_.endWriteEncaps(); - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - os_.writeByte((byte)DispatchStatus.DispatchUnknownUserException); - os_.writeString(ex.ToString()); - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - - return; - } - - catch(System.Exception ex) - { - if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Dispatch", 1) > 0) - { - warning__(ex); - } - - if(response_) - { - os_.endWriteEncaps(); - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - os_.writeByte((byte) DispatchStatus.DispatchUnknownException); - os_.writeString(ex.ToString()); - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - - return; - } - } - - protected internal Ice.Current current_; - protected internal Ice.Object servant_; - protected internal Ice.ServantLocator locator_; - protected internal Ice.LocalObject cookie_; - - protected internal bool response_; - protected internal byte compress_; - - protected internal BasicStream os_; - - protected Ice.ConnectionI connection_; + os_.writeString(ex.operation); + + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + + return; + } + catch(Ice.UnknownLocalException ex) + { + if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Dispatch", 1) > 0) + { + warning__(ex); + } + + if(response_) + { + os_.endWriteEncaps(); + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + os_.writeByte((byte)DispatchStatus.DispatchUnknownLocalException); + os_.writeString(ex.unknown); + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + + return; + } + catch(Ice.UnknownUserException ex) + { + if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Dispatch", 1) > 0) + { + warning__(ex); + } + + if(response_) + { + os_.endWriteEncaps(); + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + os_.writeByte((byte)DispatchStatus.DispatchUnknownUserException); + os_.writeString(ex.unknown); + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + + return; + } + catch(Ice.UnknownException ex) + { + if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Dispatch", 1) > 0) + { + warning__(ex); + } + + if(response_) + { + os_.endWriteEncaps(); + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + os_.writeByte((byte)DispatchStatus.DispatchUnknownException); + os_.writeString(ex.unknown); + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + + return; + } + catch(Ice.LocalException ex) + { + if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Dispatch", 1) > 0) + { + warning__(ex); + } + + if(response_) + { + os_.endWriteEncaps(); + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + os_.writeByte((byte)DispatchStatus.DispatchUnknownLocalException); + os_.writeString(ex.ToString()); + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + + return; + } + + catch(Ice.UserException ex) + { + if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Dispatch", 1) > 0) + { + warning__(ex); + } + + if(response_) + { + os_.endWriteEncaps(); + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + os_.writeByte((byte)DispatchStatus.DispatchUnknownUserException); + os_.writeString(ex.ToString()); + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + + return; + } + + catch(System.Exception ex) + { + if(os_.instance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Dispatch", 1) > 0) + { + warning__(ex); + } + + if(response_) + { + os_.endWriteEncaps(); + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + os_.writeByte((byte) DispatchStatus.DispatchUnknownException); + os_.writeString(ex.ToString()); + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + + return; + } + } + + protected internal Ice.Current current_; + protected internal Ice.Object servant_; + protected internal Ice.ServantLocator locator_; + protected internal Ice.LocalObject cookie_; + + protected internal bool response_; + protected internal byte compress_; + + protected internal BasicStream os_; + + protected Ice.ConnectionI connection_; } - + sealed public class Incoming : IncomingBase { - public Incoming(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, - bool response, byte compress, int requestId) - : base(instance, connection, adapter, response, compress, requestId) - { - _is = new BasicStream(instance); - } - - // - // These functions allow this object to be reused, rather than reallocated. - // - public override void reset(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, - bool response, byte compress, int requestId) - { - if(_is == null) - { - _is = new BasicStream(instance); - } - - base.reset(instance, connection, adapter, response, compress, requestId); - } - - public override void reclaim() - { - if(_is != null) - { - _is.reset(); - } - - base.reclaim(); - } - - public void invoke(ServantManager servantManager) - { - // - // Read the current. - // - current_.id.read__(_is); + public Incoming(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, + bool response, byte compress, int requestId) + : base(instance, connection, adapter, response, compress, requestId) + { + _is = new BasicStream(instance); + } + + // + // These functions allow this object to be reused, rather than reallocated. + // + public override void reset(Instance instance, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, + bool response, byte compress, int requestId) + { + if(_is == null) + { + _is = new BasicStream(instance); + } + + base.reset(instance, connection, adapter, response, compress, requestId); + } + + public override void reclaim() + { + if(_is != null) + { + _is.reset(); + } + + base.reclaim(); + } + + public void invoke(ServantManager servantManager) + { + // + // Read the current. + // + current_.id.read__(_is); // // For compatibility with the old FacetPath. @@ -407,124 +407,124 @@ namespace IceInternal current_.facet = ""; } - current_.operation = _is.readString(); - current_.mode = (Ice.OperationMode)(int)_is.readByte(); - int sz = _is.readSize(); - while(sz-- > 0) - { - string first = _is.readString(); - string second = _is.readString(); - if(current_.ctx == null) - { - current_.ctx = new Ice.Context(); - } - current_.ctx[first] = second; - } - - _is.startReadEncaps(); - - if(response_) - { - Debug.Assert(os_.size() == Protocol.headerSize + 4); // Dispatch status position. - os_.writeByte((byte)0); - os_.startWriteEncaps(); - } - - // Initialize status to some value, to keep the compiler happy. - DispatchStatus status = DispatchStatus.DispatchOK; - - // - // Don't put the code above into the try block below. Exceptions - // in the code above are considered fatal, and must propagate to - // the caller of this operation. - // - - try - { - try - { - if(servantManager != null) - { - servant_ = servantManager.findServant(current_.id, current_.facet); - if(servant_ == null) - { - locator_ = servantManager.findServantLocator(current_.id.category); - if(locator_ == null && current_.id.category.Length > 0) - { - locator_ = servantManager.findServantLocator(""); - } - if(locator_ != null) - { - servant_ = locator_.locate(current_, out cookie_); - } - } - } - if(servant_ == null) - { - if(servantManager != null && servantManager.hasServant(current_.id)) - { - status = DispatchStatus.DispatchFacetNotExist; - } - else - { - status = DispatchStatus.DispatchObjectNotExist; - } - } - else - { - status = servant_.dispatch__(this, current_); - } - } - finally - { - if(locator_ != null && servant_ != null && status != DispatchStatus.DispatchAsync) - { - locator_.finished(current_, servant_, cookie_); - } - } - } - catch(System.Exception ex) - { - _is.endReadEncaps(); - handleException__(ex); - return; - } - - // - // Don't put the code below into the try block above. Exceptions - // in the code below are considered fatal, and must propagate to - // the caller of this operation. - // - - _is.endReadEncaps(); - - // - // DispatchAsync is "pseudo dispatch status", used internally - // only to indicate async dispatch. - // - if(status == DispatchStatus.DispatchAsync) - { - // - // If this was an asynchronous dispatch, we're done - // here. - // - return; - } - - if(response_) - { - os_.endWriteEncaps(); - - if(status != DispatchStatus.DispatchOK && status != DispatchStatus.DispatchUserException) - { - Debug.Assert(status == DispatchStatus.DispatchObjectNotExist || - status == DispatchStatus.DispatchFacetNotExist || - status == DispatchStatus.DispatchOperationNotExist); - - os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. - os_.writeByte((byte)status); - - current_.id.write__(os_); + current_.operation = _is.readString(); + current_.mode = (Ice.OperationMode)(int)_is.readByte(); + int sz = _is.readSize(); + while(sz-- > 0) + { + string first = _is.readString(); + string second = _is.readString(); + if(current_.ctx == null) + { + current_.ctx = new Ice.Context(); + } + current_.ctx[first] = second; + } + + _is.startReadEncaps(); + + if(response_) + { + Debug.Assert(os_.size() == Protocol.headerSize + 4); // Dispatch status position. + os_.writeByte((byte)0); + os_.startWriteEncaps(); + } + + // Initialize status to some value, to keep the compiler happy. + DispatchStatus status = DispatchStatus.DispatchOK; + + // + // Don't put the code above into the try block below. Exceptions + // in the code above are considered fatal, and must propagate to + // the caller of this operation. + // + + try + { + try + { + if(servantManager != null) + { + servant_ = servantManager.findServant(current_.id, current_.facet); + if(servant_ == null) + { + locator_ = servantManager.findServantLocator(current_.id.category); + if(locator_ == null && current_.id.category.Length > 0) + { + locator_ = servantManager.findServantLocator(""); + } + if(locator_ != null) + { + servant_ = locator_.locate(current_, out cookie_); + } + } + } + if(servant_ == null) + { + if(servantManager != null && servantManager.hasServant(current_.id)) + { + status = DispatchStatus.DispatchFacetNotExist; + } + else + { + status = DispatchStatus.DispatchObjectNotExist; + } + } + else + { + status = servant_.dispatch__(this, current_); + } + } + finally + { + if(locator_ != null && servant_ != null && status != DispatchStatus.DispatchAsync) + { + locator_.finished(current_, servant_, cookie_); + } + } + } + catch(System.Exception ex) + { + _is.endReadEncaps(); + handleException__(ex); + return; + } + + // + // Don't put the code below into the try block above. Exceptions + // in the code below are considered fatal, and must propagate to + // the caller of this operation. + // + + _is.endReadEncaps(); + + // + // DispatchAsync is "pseudo dispatch status", used internally + // only to indicate async dispatch. + // + if(status == DispatchStatus.DispatchAsync) + { + // + // If this was an asynchronous dispatch, we're done + // here. + // + return; + } + + if(response_) + { + os_.endWriteEncaps(); + + if(status != DispatchStatus.DispatchOK && status != DispatchStatus.DispatchUserException) + { + Debug.Assert(status == DispatchStatus.DispatchObjectNotExist || + status == DispatchStatus.DispatchFacetNotExist || + status == DispatchStatus.DispatchOperationNotExist); + + os_.resize(Protocol.headerSize + 4, false); // Dispatch status position. + os_.writeByte((byte)status); + + current_.id.write__(os_); // // For compatibility with the old FacetPath. @@ -539,37 +539,37 @@ namespace IceInternal os_.writeStringSeq(facetPath2); } - os_.writeString(current_.operation); - } - else - { - int save = os_.pos(); - os_.pos(Protocol.headerSize + 4); // Dispatch status position. - os_.writeByte((byte)status); - os_.pos(save); - } - - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - } - - public BasicStream istr() - { - return _is; - } - - public BasicStream ostr() - { - return os_; - } - - public Incoming next; // For use by Connection. - - private BasicStream _is; + os_.writeString(current_.operation); + } + else + { + int save = os_.pos(); + os_.pos(Protocol.headerSize + 4); // Dispatch status position. + os_.writeByte((byte)status); + os_.pos(save); + } + + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + } + + public BasicStream istr() + { + return _is; + } + + public BasicStream ostr() + { + return os_; + } + + public Incoming next; // For use by Connection. + + private BasicStream _is; } } diff --git a/cs/src/Ice/IncomingAsync.cs b/cs/src/Ice/IncomingAsync.cs index c77e4f4851e..e0b150f5546 100755 --- a/cs/src/Ice/IncomingAsync.cs +++ b/cs/src/Ice/IncomingAsync.cs @@ -21,82 +21,82 @@ namespace IceInternal protected void response__(bool ok) { - try - { - if(!servantLocatorFinished__()) - { - return; - } + try + { + if(!servantLocatorFinished__()) + { + return; + } - if(response_) - { - os_.endWriteEncaps(); - - int save = os_.pos(); - os_.pos(Protocol.headerSize + 4); // Dispatch status position. - - if(ok) - { - os_.writeByte((byte)DispatchStatus.DispatchOK); - } - else - { - os_.writeByte((byte)DispatchStatus.DispatchUserException); - } - - os_.pos(save); + if(response_) + { + os_.endWriteEncaps(); + + int save = os_.pos(); + os_.pos(Protocol.headerSize + 4); // Dispatch status position. + + if(ok) + { + os_.writeByte((byte)DispatchStatus.DispatchOK); + } + else + { + os_.writeByte((byte)DispatchStatus.DispatchUserException); + } + + os_.pos(save); - connection_.sendResponse(os_, compress_); - } - else - { - connection_.sendNoResponse(); - } - } - catch(Ice.LocalException ex) - { - connection_.invokeException(ex, 1); - } + connection_.sendResponse(os_, compress_); + } + else + { + connection_.sendNoResponse(); + } + } + catch(Ice.LocalException ex) + { + connection_.invokeException(ex, 1); + } } - + protected internal void exception__(System.Exception exc) { - try - { - if(!servantLocatorFinished__()) - { - return; - } + try + { + if(!servantLocatorFinished__()) + { + return; + } - handleException__(exc); - } - catch(Ice.LocalException ex) - { - connection_.invokeException(ex, 1); - } + handleException__(exc); + } + catch(Ice.LocalException ex) + { + connection_.invokeException(ex, 1); + } } - + protected internal BasicStream os__() { return os_; } - private bool servantLocatorFinished__() - { - try - { - if(locator_ != null && servant_ != null) - { - locator_.finished(current_, servant_, cookie_); - } - return true; - } - catch(System.Exception ex) - { - handleException__(ex); - return false; - } - } + private bool servantLocatorFinished__() + { + try + { + if(locator_ != null && servant_ != null) + { + locator_.finished(current_, servant_, cookie_); + } + return true; + } + catch(System.Exception ex) + { + handleException__(ex); + return false; + } + } } } @@ -115,24 +115,24 @@ namespace Ice : base(inc) { } - + public void ice_response(bool ok, byte[] outParams) { - try - { - os__().writeBlob(outParams); - } - catch(Ice.LocalException ex) - { - exception__(ex); - return; - } - response__(ok); - } - + try + { + os__().writeBlob(outParams); + } + catch(Ice.LocalException ex) + { + exception__(ex); + return; + } + response__(ok); + } + public void ice_exception(System.Exception ex) { - exception__(ex); + exception__(ex); } } } diff --git a/cs/src/Ice/InputStream.cs b/cs/src/Ice/InputStream.cs index 33d23e9cbfb..792c200f80c 100644 --- a/cs/src/Ice/InputStream.cs +++ b/cs/src/Ice/InputStream.cs @@ -11,53 +11,53 @@ namespace Ice { public interface InputStream { - Communicator communicator(); + Communicator communicator(); - void sliceObjects(bool slice); + void sliceObjects(bool slice); - bool readBool(); - bool[] readBoolSeq(); + bool readBool(); + bool[] readBoolSeq(); - byte readByte(); - byte[] readByteSeq(); + byte readByte(); + byte[] readByteSeq(); - short readShort(); - short[] readShortSeq(); + short readShort(); + short[] readShortSeq(); - int readInt(); - int[] readIntSeq(); + int readInt(); + int[] readIntSeq(); - long readLong(); - long[] readLongSeq(); + long readLong(); + long[] readLongSeq(); - float readFloat(); - float[] readFloatSeq(); + float readFloat(); + float[] readFloatSeq(); - double readDouble(); - double[] readDoubleSeq(); + double readDouble(); + double[] readDoubleSeq(); - string readString(); - string[] readStringSeq(); + string readString(); + string[] readStringSeq(); - int readSize(); + int readSize(); - ObjectPrx readProxy(); + ObjectPrx readProxy(); - void readObject(ReadObjectCallback cb); + void readObject(ReadObjectCallback cb); - string readTypeId(); + string readTypeId(); - void throwException(); + void throwException(); - void startSlice(); - void endSlice(); - void skipSlice(); + void startSlice(); + void endSlice(); + void skipSlice(); - void startEncapsulation(); - void endEncapsulation(); + void startEncapsulation(); + void endEncapsulation(); - void readPendingObjects(); + void readPendingObjects(); - void destroy(); + void destroy(); } } diff --git a/cs/src/Ice/InputStreamI.cs b/cs/src/Ice/InputStreamI.cs index ea1e19142a6..21ff63d94fa 100644 --- a/cs/src/Ice/InputStreamI.cs +++ b/cs/src/Ice/InputStreamI.cs @@ -11,192 +11,192 @@ namespace Ice { public class InputStreamI : InputStream { - public InputStreamI(Communicator communicator, byte[] data) - { - _communicator = communicator; - - _is = new IceInternal.BasicInputStream(Util.getInstance(communicator), this); - _is.resize(data.Length, true); - IceInternal.ByteBuffer buf = _is.prepareRead(); - buf.position(0); - buf.put(data); - buf.position(0); - } - - public Communicator communicator() - { - return _communicator; - } - - public void sliceObjects(bool slice) - { - _is.sliceObjects(slice); - } - - public bool readBool() - { - return _is.readBool(); - } - - public bool[] readBoolSeq() - { - return _is.readBoolSeq(); - } - - public byte readByte() - { - return _is.readByte(); - } - - public byte[] readByteSeq() - { - return _is.readByteSeq(); - } - - public short readShort() - { - return _is.readShort(); - } - - public short[] readShortSeq() - { - return _is.readShortSeq(); - } - - public int readInt() - { - return _is.readInt(); - } - - public int[] readIntSeq() - { - return _is.readIntSeq(); - } - - public long readLong() - { - return _is.readLong(); - } - - public long[] readLongSeq() - { - return _is.readLongSeq(); - } - - public float readFloat() - { - return _is.readFloat(); - } - - public float[] readFloatSeq() - { - return _is.readFloatSeq(); - } - - public double readDouble() - { - return _is.readDouble(); - } - - public double[] readDoubleSeq() - { - return _is.readDoubleSeq(); - } - - public string readString() - { - return _is.readString(); - } - - public string[] readStringSeq() - { - return _is.readStringSeq(); - } - - public int readSize() - { - return _is.readSize(); - } - - public ObjectPrx readProxy() - { - return _is.readProxy(); - } - - private class Patcher : IceInternal.Patcher - { - public Patcher(ReadObjectCallback cb) - { - _cb = cb; - } - - public override void patch(Ice.Object v) - { - _cb.invoke(v); - } - - public override string type() - { - return "unknown"; - } - - ReadObjectCallback _cb; - } - - public void readObject(ReadObjectCallback cb) - { - _is.readObject(new Patcher(cb)); - } - - public string readTypeId() - { - return _is.readTypeId(); - } - - public void throwException() - { - _is.throwException(); - } - - public void startSlice() - { - _is.startReadSlice(); - } - - public void endSlice() - { - _is.endReadSlice(); - } - - public void skipSlice() - { - _is.skipSlice(); - } - - public void startEncapsulation() - { - _is.startReadEncaps(); - } - - public void endEncapsulation() - { - _is.endReadEncaps(); - } - - public void readPendingObjects() - { - _is.readPendingObjects(); - } - - public void destroy() - { - if(_is != null) - { - _is = null; - } - } - - private Communicator _communicator; - private IceInternal.BasicInputStream _is; + public InputStreamI(Communicator communicator, byte[] data) + { + _communicator = communicator; + + _is = new IceInternal.BasicInputStream(Util.getInstance(communicator), this); + _is.resize(data.Length, true); + IceInternal.ByteBuffer buf = _is.prepareRead(); + buf.position(0); + buf.put(data); + buf.position(0); + } + + public Communicator communicator() + { + return _communicator; + } + + public void sliceObjects(bool slice) + { + _is.sliceObjects(slice); + } + + public bool readBool() + { + return _is.readBool(); + } + + public bool[] readBoolSeq() + { + return _is.readBoolSeq(); + } + + public byte readByte() + { + return _is.readByte(); + } + + public byte[] readByteSeq() + { + return _is.readByteSeq(); + } + + public short readShort() + { + return _is.readShort(); + } + + public short[] readShortSeq() + { + return _is.readShortSeq(); + } + + public int readInt() + { + return _is.readInt(); + } + + public int[] readIntSeq() + { + return _is.readIntSeq(); + } + + public long readLong() + { + return _is.readLong(); + } + + public long[] readLongSeq() + { + return _is.readLongSeq(); + } + + public float readFloat() + { + return _is.readFloat(); + } + + public float[] readFloatSeq() + { + return _is.readFloatSeq(); + } + + public double readDouble() + { + return _is.readDouble(); + } + + public double[] readDoubleSeq() + { + return _is.readDoubleSeq(); + } + + public string readString() + { + return _is.readString(); + } + + public string[] readStringSeq() + { + return _is.readStringSeq(); + } + + public int readSize() + { + return _is.readSize(); + } + + public ObjectPrx readProxy() + { + return _is.readProxy(); + } + + private class Patcher : IceInternal.Patcher + { + public Patcher(ReadObjectCallback cb) + { + _cb = cb; + } + + public override void patch(Ice.Object v) + { + _cb.invoke(v); + } + + public override string type() + { + return "unknown"; + } + + ReadObjectCallback _cb; + } + + public void readObject(ReadObjectCallback cb) + { + _is.readObject(new Patcher(cb)); + } + + public string readTypeId() + { + return _is.readTypeId(); + } + + public void throwException() + { + _is.throwException(); + } + + public void startSlice() + { + _is.startReadSlice(); + } + + public void endSlice() + { + _is.endReadSlice(); + } + + public void skipSlice() + { + _is.skipSlice(); + } + + public void startEncapsulation() + { + _is.startReadEncaps(); + } + + public void endEncapsulation() + { + _is.endReadEncaps(); + } + + public void readPendingObjects() + { + _is.readPendingObjects(); + } + + public void destroy() + { + if(_is != null) + { + _is = null; + } + } + + private Communicator _communicator; + private IceInternal.BasicInputStream _is; } } diff --git a/cs/src/Ice/Instance.cs b/cs/src/Ice/Instance.cs index 072952951db..c066024d5bd 100755 --- a/cs/src/Ice/Instance.cs +++ b/cs/src/Ice/Instance.cs @@ -14,283 +14,283 @@ namespace IceInternal public sealed class Instance { - public bool destroyed() - { - return _state == StateDestroyed; - } + public bool destroyed() + { + return _state == StateDestroyed; + } - public Ice.InitializationData initializationData() - { - // - // No check for destruction. It must be possible to access the - // initialization data after destruction. - // - // No mutex lock, immutable. - // - return _initData; - } - - public TraceLevels traceLevels() - { - // No mutex lock, immutable. - return _traceLevels; - } - - public DefaultsAndOverrides defaultsAndOverrides() - { - // No mutex lock, immutable. - return _defaultsAndOverrides; - } - - public RouterManager routerManager() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _routerManager; - } - } - - public LocatorManager locatorManager() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _locatorManager; - } - } - - public ReferenceFactory referenceFactory() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _referenceFactory; - } - } - - public ProxyFactory proxyFactory() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _proxyFactory; - } - } - - public OutgoingConnectionFactory outgoingConnectionFactory() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _outgoingConnectionFactory; - } - } - - public ConnectionMonitor connectionMonitor() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _connectionMonitor; - } - } - - public ObjectFactoryManager servantFactoryManager() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _servantFactoryManager; - } - } - - public ObjectAdapterFactory objectAdapterFactory() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _objectAdapterFactory; - } - } - - public ThreadPool clientThreadPool() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - if(_clientThreadPool == null) // Lazy initialization. - { - _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0); - } - - return _clientThreadPool; - } - } - - public ThreadPool serverThreadPool() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - if(_serverThreadPool == null) - // Lazy initialization. - { - int timeout = _initData.properties.getPropertyAsInt("Ice.ServerIdleTime"); - _serverThreadPool = new ThreadPool(this, "Ice.ThreadPool.Server", timeout); - } - - return _serverThreadPool; - } - } + public Ice.InitializationData initializationData() + { + // + // No check for destruction. It must be possible to access the + // initialization data after destruction. + // + // No mutex lock, immutable. + // + return _initData; + } + + public TraceLevels traceLevels() + { + // No mutex lock, immutable. + return _traceLevels; + } + + public DefaultsAndOverrides defaultsAndOverrides() + { + // No mutex lock, immutable. + return _defaultsAndOverrides; + } + + public RouterManager routerManager() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _routerManager; + } + } + + public LocatorManager locatorManager() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _locatorManager; + } + } + + public ReferenceFactory referenceFactory() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _referenceFactory; + } + } + + public ProxyFactory proxyFactory() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _proxyFactory; + } + } + + public OutgoingConnectionFactory outgoingConnectionFactory() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _outgoingConnectionFactory; + } + } + + public ConnectionMonitor connectionMonitor() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _connectionMonitor; + } + } + + public ObjectFactoryManager servantFactoryManager() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _servantFactoryManager; + } + } + + public ObjectAdapterFactory objectAdapterFactory() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _objectAdapterFactory; + } + } + + public ThreadPool clientThreadPool() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + if(_clientThreadPool == null) // Lazy initialization. + { + _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0); + } + + return _clientThreadPool; + } + } + + public ThreadPool serverThreadPool() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + if(_serverThreadPool == null) + // Lazy initialization. + { + int timeout = _initData.properties.getPropertyAsInt("Ice.ServerIdleTime"); + _serverThreadPool = new ThreadPool(this, "Ice.ThreadPool.Server", timeout); + } + + return _serverThreadPool; + } + } - public bool threadPerConnection() - { - // No mutex lock, immutable. - return _threadPerConnection; - } + public bool threadPerConnection() + { + // No mutex lock, immutable. + return _threadPerConnection; + } - public EndpointFactoryManager endpointFactoryManager() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _endpointFactoryManager; - } - } - - public Ice.PluginManager pluginManager() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return _pluginManager; - } - } - - public int messageSizeMax() - { - // No mutex lock, immutable. - return _messageSizeMax; - } - - public int clientACM() - { - // No mutex lock, immutable. - return _clientACM; - } - - public int serverACM() - { - // No mutex lock, immutable. - return _serverACM; - } - - public void setDefaultContext(Ice.Context ctx) - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - if(ctx == null || ctx.Count == 0) - { - _defaultContext = _emptyContext; - } - else - { - _defaultContext = (Ice.Context)ctx.Clone(); - } - } - } + public EndpointFactoryManager endpointFactoryManager() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _endpointFactoryManager; + } + } + + public Ice.PluginManager pluginManager() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return _pluginManager; + } + } + + public int messageSizeMax() + { + // No mutex lock, immutable. + return _messageSizeMax; + } + + public int clientACM() + { + // No mutex lock, immutable. + return _clientACM; + } + + public int serverACM() + { + // No mutex lock, immutable. + return _serverACM; + } + + public void setDefaultContext(Ice.Context ctx) + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + if(ctx == null || ctx.Count == 0) + { + _defaultContext = _emptyContext; + } + else + { + _defaultContext = (Ice.Context)ctx.Clone(); + } + } + } - public Ice.Context getDefaultContext() - { - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - return (Ice.Context)_defaultContext.Clone(); - } - } + public Ice.Context getDefaultContext() + { + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + return (Ice.Context)_defaultContext.Clone(); + } + } - public Ice.ImplicitContextI getImplicitContext() - { - return _implicitContext; - } + public Ice.ImplicitContextI getImplicitContext() + { + return _implicitContext; + } - public void flushBatchRequests() - { - OutgoingConnectionFactory connectionFactory; - ObjectAdapterFactory adapterFactory; - - lock(this) - { - if(_state == StateDestroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - connectionFactory = _outgoingConnectionFactory; - adapterFactory = _objectAdapterFactory; - } - - connectionFactory.flushBatchRequests(); - adapterFactory.flushBatchRequests(); - } + public void flushBatchRequests() + { + OutgoingConnectionFactory connectionFactory; + ObjectAdapterFactory adapterFactory; + + lock(this) + { + if(_state == StateDestroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + + connectionFactory = _outgoingConnectionFactory; + adapterFactory = _objectAdapterFactory; + } + + connectionFactory.flushBatchRequests(); + adapterFactory.flushBatchRequests(); + } public Ice.Identity stringToIdentity(string s) { @@ -301,385 +301,385 @@ namespace IceInternal { return Ice.Util.identityToString(ident); } - - // - // Only for use by Ice.CommunicatorI - // - public Instance(Ice.Communicator communicator, Ice.InitializationData initData) - { - _state = StateActive; - _initData = initData; - - try - { - if(_initData.properties == null) - { - _initData.properties = Ice.Util.createProperties(); - } + + // + // Only for use by Ice.CommunicatorI + // + public Instance(Ice.Communicator communicator, Ice.InitializationData initData) + { + _state = StateActive; + _initData = initData; + + try + { + if(_initData.properties == null) + { + _initData.properties = Ice.Util.createProperties(); + } - lock(_staticLock) - { - if(!_oneOffDone) - { - string stdOut = _initData.properties.getProperty("Ice.StdOut"); - string stdErr = _initData.properties.getProperty("Ice.StdErr"); - - System.IO.StreamWriter outStream = null; - - if(stdOut.Length > 0) - { - try - { - outStream = System.IO.File.AppendText(stdOut); - } - catch(System.IO.IOException ex) - { - Ice.FileException fe = new Ice.FileException(ex); - fe.path = stdOut; - throw fe; - } - outStream.AutoFlush = true; - System.Console.Out.Close(); - System.Console.SetOut(outStream); - } - if(stdErr.Length > 0) - { - if(stdErr.Equals(stdOut)) - { - System.Console.SetError(outStream); - } - else - { - System.IO.StreamWriter errStream = null; - try - { - errStream = System.IO.File.AppendText(stdErr); - } - catch(System.IO.IOException ex) - { - Ice.FileException fe = new Ice.FileException(ex); - fe.path = stdErr; - throw fe; - } - errStream.AutoFlush = true; - System.Console.Error.Close(); - System.Console.SetError(errStream); - } - } + lock(_staticLock) + { + if(!_oneOffDone) + { + string stdOut = _initData.properties.getProperty("Ice.StdOut"); + string stdErr = _initData.properties.getProperty("Ice.StdErr"); + + System.IO.StreamWriter outStream = null; + + if(stdOut.Length > 0) + { + try + { + outStream = System.IO.File.AppendText(stdOut); + } + catch(System.IO.IOException ex) + { + Ice.FileException fe = new Ice.FileException(ex); + fe.path = stdOut; + throw fe; + } + outStream.AutoFlush = true; + System.Console.Out.Close(); + System.Console.SetOut(outStream); + } + if(stdErr.Length > 0) + { + if(stdErr.Equals(stdOut)) + { + System.Console.SetError(outStream); + } + else + { + System.IO.StreamWriter errStream = null; + try + { + errStream = System.IO.File.AppendText(stdErr); + } + catch(System.IO.IOException ex) + { + Ice.FileException fe = new Ice.FileException(ex); + fe.path = stdErr; + throw fe; + } + errStream.AutoFlush = true; + System.Console.Error.Close(); + System.Console.SetError(errStream); + } + } - _oneOffDone = true; - } - } - - if(_initData.logger == null) - { - if(_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0) - { - _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName")); - } - else - { - _initData.logger = Ice.Util.getProcessLogger(); - } - } - - _traceLevels = new TraceLevels(_initData.properties); - - _defaultsAndOverrides = new DefaultsAndOverrides(_initData.properties); - - { - const int defaultMessageSizeMax = 1024; - int num = - _initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax); - if(num < 1) - { - _messageSizeMax = defaultMessageSizeMax * 1024; // Ignore stupid values. - } - else if(num > 0x7fffffff / 1024) - { - _messageSizeMax = 0x7fffffff; - } - else - { - _messageSizeMax = num * 1024; // Property is in kilobytes, _messageSizeMax in bytes - } - } - - // - // Client ACM enabled by default. Server ACM disabled by default. - // - _clientACM = _initData.properties.getPropertyAsIntWithDefault("Ice.ACM.Client", 60); - _serverACM = _initData.properties.getPropertyAsInt("Ice.ACM.Server"); + _oneOffDone = true; + } + } + + if(_initData.logger == null) + { + if(_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0) + { + _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName")); + } + else + { + _initData.logger = Ice.Util.getProcessLogger(); + } + } + + _traceLevels = new TraceLevels(_initData.properties); + + _defaultsAndOverrides = new DefaultsAndOverrides(_initData.properties); + + { + const int defaultMessageSizeMax = 1024; + int num = + _initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax); + if(num < 1) + { + _messageSizeMax = defaultMessageSizeMax * 1024; // Ignore stupid values. + } + else if(num > 0x7fffffff / 1024) + { + _messageSizeMax = 0x7fffffff; + } + else + { + _messageSizeMax = num * 1024; // Property is in kilobytes, _messageSizeMax in bytes + } + } + + // + // Client ACM enabled by default. Server ACM disabled by default. + // + _clientACM = _initData.properties.getPropertyAsIntWithDefault("Ice.ACM.Client", 60); + _serverACM = _initData.properties.getPropertyAsInt("Ice.ACM.Server"); - _implicitContext = Ice.ImplicitContextI.create(_initData.properties.getProperty("Ice.ImplicitContext")); + _implicitContext = Ice.ImplicitContextI.create(_initData.properties.getProperty("Ice.ImplicitContext")); - _threadPerConnection = _initData.properties.getPropertyAsInt("Ice.ThreadPerConnection") > 0; + _threadPerConnection = _initData.properties.getPropertyAsInt("Ice.ThreadPerConnection") > 0; - _routerManager = new RouterManager(); - - _locatorManager = new LocatorManager(); - - _referenceFactory = new ReferenceFactory(this, communicator); - - _proxyFactory = new ProxyFactory(this); - - _endpointFactoryManager = new EndpointFactoryManager(this); - EndpointFactory tcpEndpointFactory = new TcpEndpointFactory(this); - _endpointFactoryManager.add(tcpEndpointFactory); - EndpointFactory udpEndpointFactory = new UdpEndpointFactory(this); - _endpointFactoryManager.add(udpEndpointFactory); - - _pluginManager = new Ice.PluginManagerI(communicator); + _routerManager = new RouterManager(); + + _locatorManager = new LocatorManager(); + + _referenceFactory = new ReferenceFactory(this, communicator); + + _proxyFactory = new ProxyFactory(this); + + _endpointFactoryManager = new EndpointFactoryManager(this); + EndpointFactory tcpEndpointFactory = new TcpEndpointFactory(this); + _endpointFactoryManager.add(tcpEndpointFactory); + EndpointFactory udpEndpointFactory = new UdpEndpointFactory(this); + _endpointFactoryManager.add(udpEndpointFactory); + + _pluginManager = new Ice.PluginManagerI(communicator); - _defaultContext = _emptyContext; - - _outgoingConnectionFactory = new OutgoingConnectionFactory(this); - - _servantFactoryManager = new ObjectFactoryManager(); - - _objectAdapterFactory = new ObjectAdapterFactory(this, communicator); - } - catch(Ice.LocalException) - { - destroy(); - throw; - } - } - - public void finishSetup(ref string[] args) - { - // - // Load plug-ins. - // - Ice.PluginManagerI pluginManagerImpl = (Ice.PluginManagerI)_pluginManager; - pluginManagerImpl.loadPlugins(ref args); - Ice.Logger logger = pluginManagerImpl.getLogger(); - if(logger != null) - { - _initData.logger = logger; - } - - // - // Get default router and locator proxies. Don't move this - // initialization before the plug-in initialization!!! The proxies - // might depend on endpoint factories to be installed by plug-ins. - // - _referenceFactory.setDefaultRouter(Ice.RouterPrxHelper.uncheckedCast( - _proxyFactory.propertyToProxy("Ice.Default.Router"))); - - _referenceFactory.setDefaultLocator(Ice.LocatorPrxHelper.uncheckedCast( - _proxyFactory.propertyToProxy("Ice.Default.Locator"))); - - // - // Show process id if requested (but only once). - // - lock(this) - { - if(!_printProcessIdDone && _initData.properties.getPropertyAsInt("Ice.PrintProcessId") > 0) - { - using(Process p = Process.GetCurrentProcess()) - { - System.Console.WriteLine(p.Id); - } - _printProcessIdDone = true; - } - } + _defaultContext = _emptyContext; + + _outgoingConnectionFactory = new OutgoingConnectionFactory(this); + + _servantFactoryManager = new ObjectFactoryManager(); + + _objectAdapterFactory = new ObjectAdapterFactory(this, communicator); + } + catch(Ice.LocalException) + { + destroy(); + throw; + } + } + + public void finishSetup(ref string[] args) + { + // + // Load plug-ins. + // + Ice.PluginManagerI pluginManagerImpl = (Ice.PluginManagerI)_pluginManager; + pluginManagerImpl.loadPlugins(ref args); + Ice.Logger logger = pluginManagerImpl.getLogger(); + if(logger != null) + { + _initData.logger = logger; + } + + // + // Get default router and locator proxies. Don't move this + // initialization before the plug-in initialization!!! The proxies + // might depend on endpoint factories to be installed by plug-ins. + // + _referenceFactory.setDefaultRouter(Ice.RouterPrxHelper.uncheckedCast( + _proxyFactory.propertyToProxy("Ice.Default.Router"))); + + _referenceFactory.setDefaultLocator(Ice.LocatorPrxHelper.uncheckedCast( + _proxyFactory.propertyToProxy("Ice.Default.Locator"))); + + // + // Show process id if requested (but only once). + // + lock(this) + { + if(!_printProcessIdDone && _initData.properties.getPropertyAsInt("Ice.PrintProcessId") > 0) + { + using(Process p = Process.GetCurrentProcess()) + { + System.Console.WriteLine(p.Id); + } + _printProcessIdDone = true; + } + } - // - // Start connection monitor if necessary. - // - int interval = 0; - if(_clientACM > 0 && _serverACM > 0) - { - if(_clientACM < _serverACM) - { - interval = _clientACM; - } - else - { - interval = _serverACM; - } - } - else if(_clientACM > 0) - { - interval = _clientACM; - } - else if(_serverACM > 0) - { - interval = _serverACM; - } - interval = _initData.properties.getPropertyAsIntWithDefault("Ice.MonitorConnections", interval); - if(interval > 0) - { - _connectionMonitor = new ConnectionMonitor(this, interval); - } - - // - // Thread pool initialization is now lazy initialization in - // clientThreadPool() and serverThreadPool(). - // - } - - // - // Only for use by Ice.CommunicatorI - // - public bool destroy() - { - lock(this) - { - // - // If the _state is not StateActive then the instance is - // either being destroyed, or has already been destroyed. - // - if(_state != StateActive) - { - return false; - } - - // - // We cannot set state to StateDestroyed otherwise instance - // methods called during the destroy process (such as - // outgoingConnectionFactory() from - // ObjectAdapterI::deactivate() will cause an exception. - // - _state = StateDestroyInProgress; - } - - if(_objectAdapterFactory != null) - { - _objectAdapterFactory.shutdown(); - } - - if(_outgoingConnectionFactory != null) - { - _outgoingConnectionFactory.destroy(); - } - - if(_objectAdapterFactory != null) - { - _objectAdapterFactory.destroy(); - } - - if(_outgoingConnectionFactory != null) - { - _outgoingConnectionFactory.waitUntilFinished(); - } - - ThreadPool serverThreadPool = null; - ThreadPool clientThreadPool = null; - - lock(this) - { - _objectAdapterFactory = null; - - _outgoingConnectionFactory = null; - - if(_connectionMonitor != null) - { - _connectionMonitor.destroy(); - _connectionMonitor = null; - } - - if(_serverThreadPool != null) - { - _serverThreadPool.destroy(); - serverThreadPool = _serverThreadPool; - _serverThreadPool = null; - } - - if(_clientThreadPool != null) - { - _clientThreadPool.destroy(); - clientThreadPool = _clientThreadPool; - _clientThreadPool = null; - } - - if(_servantFactoryManager != null) - { - _servantFactoryManager.destroy(); - _servantFactoryManager = null; - } - - if(_referenceFactory != null) - { - _referenceFactory.destroy(); - _referenceFactory = null; - } - - // No destroy function defined. - // _proxyFactory.destroy(); - _proxyFactory = null; - - if(_routerManager != null) - { - _routerManager.destroy(); - _routerManager = null; - } - - if(_locatorManager != null) - { - _locatorManager.destroy(); - _locatorManager = null; - } - - if(_endpointFactoryManager != null) - { - _endpointFactoryManager.destroy(); - _endpointFactoryManager = null; - } - - if(_pluginManager != null) - { - _pluginManager.destroy(); - _pluginManager = null; - } - - _state = StateDestroyed; - } - - // - // Join with the thread pool threads outside the - // synchronization. - // - if(clientThreadPool != null) - { - clientThreadPool.joinWithAllThreads(); - } - if(serverThreadPool != null) - { - serverThreadPool.joinWithAllThreads(); - } + // + // Start connection monitor if necessary. + // + int interval = 0; + if(_clientACM > 0 && _serverACM > 0) + { + if(_clientACM < _serverACM) + { + interval = _clientACM; + } + else + { + interval = _serverACM; + } + } + else if(_clientACM > 0) + { + interval = _clientACM; + } + else if(_serverACM > 0) + { + interval = _serverACM; + } + interval = _initData.properties.getPropertyAsIntWithDefault("Ice.MonitorConnections", interval); + if(interval > 0) + { + _connectionMonitor = new ConnectionMonitor(this, interval); + } + + // + // Thread pool initialization is now lazy initialization in + // clientThreadPool() and serverThreadPool(). + // + } + + // + // Only for use by Ice.CommunicatorI + // + public bool destroy() + { + lock(this) + { + // + // If the _state is not StateActive then the instance is + // either being destroyed, or has already been destroyed. + // + if(_state != StateActive) + { + return false; + } + + // + // We cannot set state to StateDestroyed otherwise instance + // methods called during the destroy process (such as + // outgoingConnectionFactory() from + // ObjectAdapterI::deactivate() will cause an exception. + // + _state = StateDestroyInProgress; + } + + if(_objectAdapterFactory != null) + { + _objectAdapterFactory.shutdown(); + } + + if(_outgoingConnectionFactory != null) + { + _outgoingConnectionFactory.destroy(); + } + + if(_objectAdapterFactory != null) + { + _objectAdapterFactory.destroy(); + } + + if(_outgoingConnectionFactory != null) + { + _outgoingConnectionFactory.waitUntilFinished(); + } + + ThreadPool serverThreadPool = null; + ThreadPool clientThreadPool = null; + + lock(this) + { + _objectAdapterFactory = null; + + _outgoingConnectionFactory = null; + + if(_connectionMonitor != null) + { + _connectionMonitor.destroy(); + _connectionMonitor = null; + } + + if(_serverThreadPool != null) + { + _serverThreadPool.destroy(); + serverThreadPool = _serverThreadPool; + _serverThreadPool = null; + } + + if(_clientThreadPool != null) + { + _clientThreadPool.destroy(); + clientThreadPool = _clientThreadPool; + _clientThreadPool = null; + } + + if(_servantFactoryManager != null) + { + _servantFactoryManager.destroy(); + _servantFactoryManager = null; + } + + if(_referenceFactory != null) + { + _referenceFactory.destroy(); + _referenceFactory = null; + } + + // No destroy function defined. + // _proxyFactory.destroy(); + _proxyFactory = null; + + if(_routerManager != null) + { + _routerManager.destroy(); + _routerManager = null; + } + + if(_locatorManager != null) + { + _locatorManager.destroy(); + _locatorManager = null; + } + + if(_endpointFactoryManager != null) + { + _endpointFactoryManager.destroy(); + _endpointFactoryManager = null; + } + + if(_pluginManager != null) + { + _pluginManager.destroy(); + _pluginManager = null; + } + + _state = StateDestroyed; + } + + // + // Join with the thread pool threads outside the + // synchronization. + // + if(clientThreadPool != null) + { + clientThreadPool.joinWithAllThreads(); + } + if(serverThreadPool != null) + { + serverThreadPool.joinWithAllThreads(); + } - return true; - } - - private const int StateActive = 0; - private const int StateDestroyInProgress = 1; - private const int StateDestroyed = 2; - private int _state; - private Ice.InitializationData _initData; // Immutable, not reset by destroy(). - private TraceLevels _traceLevels; // Immutable, not reset by destroy(). - private DefaultsAndOverrides _defaultsAndOverrides; // Immutable, not reset by destroy(). - private int _messageSizeMax; // Immutable, not reset by destroy(). - private int _clientACM; // Immutable, not reset by destroy(). - private int _serverACM; // Immutable, not reset by destroy(). - private Ice.ImplicitContextI _implicitContext; // Immutable - private RouterManager _routerManager; - private LocatorManager _locatorManager; - private ReferenceFactory _referenceFactory; - private ProxyFactory _proxyFactory; - private OutgoingConnectionFactory _outgoingConnectionFactory; - private ConnectionMonitor _connectionMonitor; - private ObjectFactoryManager _servantFactoryManager; - private ObjectAdapterFactory _objectAdapterFactory; - private ThreadPool _clientThreadPool; - private ThreadPool _serverThreadPool; - private bool _threadPerConnection; - private EndpointFactoryManager _endpointFactoryManager; - private Ice.PluginManager _pluginManager; + return true; + } + + private const int StateActive = 0; + private const int StateDestroyInProgress = 1; + private const int StateDestroyed = 2; + private int _state; + private Ice.InitializationData _initData; // Immutable, not reset by destroy(). + private TraceLevels _traceLevels; // Immutable, not reset by destroy(). + private DefaultsAndOverrides _defaultsAndOverrides; // Immutable, not reset by destroy(). + private int _messageSizeMax; // Immutable, not reset by destroy(). + private int _clientACM; // Immutable, not reset by destroy(). + private int _serverACM; // Immutable, not reset by destroy(). + private Ice.ImplicitContextI _implicitContext; // Immutable + private RouterManager _routerManager; + private LocatorManager _locatorManager; + private ReferenceFactory _referenceFactory; + private ProxyFactory _proxyFactory; + private OutgoingConnectionFactory _outgoingConnectionFactory; + private ConnectionMonitor _connectionMonitor; + private ObjectFactoryManager _servantFactoryManager; + private ObjectAdapterFactory _objectAdapterFactory; + private ThreadPool _clientThreadPool; + private ThreadPool _serverThreadPool; + private bool _threadPerConnection; + private EndpointFactoryManager _endpointFactoryManager; + private Ice.PluginManager _pluginManager; private Ice.Context _defaultContext; - private static Ice.Context _emptyContext = new Ice.Context(); - private static bool _printProcessIdDone = false; + private static Ice.Context _emptyContext = new Ice.Context(); + private static bool _printProcessIdDone = false; private static bool _oneOffDone = false; private static System.Object _staticLock = new System.Object(); diff --git a/cs/src/Ice/LinkedList.cs b/cs/src/Ice/LinkedList.cs index ae665f4c7df..5304109d6b7 100755 --- a/cs/src/Ice/LinkedList.cs +++ b/cs/src/Ice/LinkedList.cs @@ -15,258 +15,258 @@ namespace IceUtil public class LinkedList : ICollection, ICloneable { - public LinkedList() - { - _head = null; - _tail = null; - _count = 0; - } + public LinkedList() + { + _head = null; + _tail = null; + _count = 0; + } - public int Count - { - get - { - return _count; - } - } + public int Count + { + get + { + return _count; + } + } - public bool IsSynchronized - { - get - { - return false; - } - } + public bool IsSynchronized + { + get + { + return false; + } + } - public object SyncRoot - { - get - { - return this; - } - } + public object SyncRoot + { + get + { + return this; + } + } - public void CopyTo(Array array, int index) - { - // - // Check preconditions. - // - if(array == null) - { - throw new ArgumentNullException("array", "array parameter must not be null"); - } - if(index < 0) - { - throw new ArgumentOutOfRangeException("index", _count, "index must not be less than zero"); - } - if(index >= array.Length) - { - throw new ArgumentException("index out of bounds for array", "index"); - } - if(array.Length - index > _count) - { - throw new ArgumentException("insufficient room in array", "array"); - } - if(array.Rank != 1) - { - throw new ArgumentException("array must be one-dimensional", "array"); - } + public void CopyTo(Array array, int index) + { + // + // Check preconditions. + // + if(array == null) + { + throw new ArgumentNullException("array", "array parameter must not be null"); + } + if(index < 0) + { + throw new ArgumentOutOfRangeException("index", _count, "index must not be less than zero"); + } + if(index >= array.Length) + { + throw new ArgumentException("index out of bounds for array", "index"); + } + if(array.Length - index > _count) + { + throw new ArgumentException("insufficient room in array", "array"); + } + if(array.Rank != 1) + { + throw new ArgumentException("array must be one-dimensional", "array"); + } - // - // Copy the elements. - // - Node n = _head; - while(n != null) - { - array.SetValue(n.val, index++); - n = (Node)n.next; - } - } + // + // Copy the elements. + // + Node n = _head; + while(n != null) + { + array.SetValue(n.val, index++); + n = (Node)n.next; + } + } - public IEnumerator GetEnumerator() - { - return new Enumerator(this); - } + public IEnumerator GetEnumerator() + { + return new Enumerator(this); + } - public object Clone() - { - LinkedList l = new LinkedList(); - Node cursor = _head; - while(cursor != null) - { - l.Add(cursor.val); - cursor = cursor.next; - } - return l; - } + public object Clone() + { + LinkedList l = new LinkedList(); + Node cursor = _head; + while(cursor != null) + { + l.Add(cursor.val); + cursor = cursor.next; + } + return l; + } - public void Add(object value) - { - Node n = new Node(); - n.val = value; - if(_tail == null) - { - n.prev = null; - n.next = null; - _head = n; - _tail = n; - } - else - { - n.prev = _tail; - n.next = null; - _tail.next = n; - _tail = n; - } - _count++; - } + public void Add(object value) + { + Node n = new Node(); + n.val = value; + if(_tail == null) + { + n.prev = null; + n.next = null; + _head = n; + _tail = n; + } + else + { + n.prev = _tail; + n.next = null; + _tail.next = n; + _tail = n; + } + _count++; + } - public void AddFirst(object value) - { - Node n = new Node(); - n.val = value; - if(_head == null) - { - n.prev = null; - n.next = null; - _head = n; - _tail = n; - } - else - { - n.prev = null; - n.next = _head; - _head.prev = n; - _head = n; - } - _count++; - } + public void AddFirst(object value) + { + Node n = new Node(); + n.val = value; + if(_head == null) + { + n.prev = null; + n.next = null; + _head = n; + _tail = n; + } + else + { + n.prev = null; + n.next = _head; + _head.prev = n; + _head = n; + } + _count++; + } - private void Remove(Node n) - { - Debug.Assert(n != null); - Debug.Assert(_count != 0); - - if(n.prev != null) - { - n.prev.next = n.next; - } - else - { - _head = n.next; - } - if(n.next != null) - { - n.next.prev = n.prev; - } - else - { - _tail = n.prev; - } - _count--; - } + private void Remove(Node n) + { + Debug.Assert(n != null); + Debug.Assert(_count != 0); + + if(n.prev != null) + { + n.prev.next = n.next; + } + else + { + _head = n.next; + } + if(n.next != null) + { + n.next.prev = n.prev; + } + else + { + _tail = n.prev; + } + _count--; + } - internal class Node - { - internal Node next; - internal Node prev; - internal object val; - } + internal class Node + { + internal Node next; + internal Node prev; + internal object val; + } - private Node _head; - private Node _tail; - private int _count; + private Node _head; + private Node _tail; + private int _count; - public class Enumerator : IEnumerator - { - internal Enumerator(LinkedList list) - { - _list = list; - _current = null; - _movePrev = null; - _moveNext = null; - _removed = false; - } + public class Enumerator : IEnumerator + { + internal Enumerator(LinkedList list) + { + _list = list; + _current = null; + _movePrev = null; + _moveNext = null; + _removed = false; + } - public void Reset() - { - _current = null; - _movePrev = null; - _moveNext = null; - _removed = false; - } + public void Reset() + { + _current = null; + _movePrev = null; + _moveNext = null; + _removed = false; + } - public object Current - { - get - { - if(_current == null) - { - throw new InvalidOperationException("iterator not positioned on an element"); - } - return _current.val; - } - } + public object Current + { + get + { + if(_current == null) + { + throw new InvalidOperationException("iterator not positioned on an element"); + } + return _current.val; + } + } - public bool MoveNext() - { - if(_removed) - { - _current = _moveNext; - _moveNext = null; - _movePrev = null; - _removed = false; - } - else - { - if(_current == _list._tail) // Make sure the iterator "sticks" if on last element. - { - return false; - } - _current = _current == null ? _list._head : _current.next; - } - return _current != null; - } + public bool MoveNext() + { + if(_removed) + { + _current = _moveNext; + _moveNext = null; + _movePrev = null; + _removed = false; + } + else + { + if(_current == _list._tail) // Make sure the iterator "sticks" if on last element. + { + return false; + } + _current = _current == null ? _list._head : _current.next; + } + return _current != null; + } - public bool MovePrev() - { - if(_removed) - { - _current = _movePrev; - _movePrev = null; - _moveNext = null; - _removed = false; - } - else - { - if(_current == _list._head) // Make sure the iterator "sticks" if on first element. - { - return false; - } - _current = _current == null ? _list._tail : _current.prev; - } - return _current != null; - } + public bool MovePrev() + { + if(_removed) + { + _current = _movePrev; + _movePrev = null; + _moveNext = null; + _removed = false; + } + else + { + if(_current == _list._head) // Make sure the iterator "sticks" if on first element. + { + return false; + } + _current = _current == null ? _list._tail : _current.prev; + } + return _current != null; + } - public void Remove() - { - if(_current == null) - { - throw new InvalidOperationException("iterator is not positioned on an element"); - } - _removed = true; - _moveNext = _current.next; // Remember where to move next for call to MoveNext(). - _movePrev = _current.prev; // Remember where to move next for call to MovePrev(). - _list.Remove(_current); - _current = null; - } + public void Remove() + { + if(_current == null) + { + throw new InvalidOperationException("iterator is not positioned on an element"); + } + _removed = true; + _moveNext = _current.next; // Remember where to move next for call to MoveNext(). + _movePrev = _current.prev; // Remember where to move next for call to MovePrev(). + _list.Remove(_current); + _current = null; + } - private LinkedList _list; // The list we are iterating over. - private Node _current; // Current iterator position. - private Node _moveNext; // Remembers node that preceded a removed element. - private Node _movePrev; // Remembers node that followed a removed element. - private bool _removed; // True after a call to Remove(), false otherwise. - } + private LinkedList _list; // The list we are iterating over. + private Node _current; // Current iterator position. + private Node _moveNext; // Remembers node that preceded a removed element. + private Node _movePrev; // Remembers node that followed a removed element. + private bool _removed; // True after a call to Remove(), false otherwise. + } } } diff --git a/cs/src/Ice/LocatorInfo.cs b/cs/src/Ice/LocatorInfo.cs index 9db3a357c11..9fe258c7290 100755 --- a/cs/src/Ice/LocatorInfo.cs +++ b/cs/src/Ice/LocatorInfo.cs @@ -15,135 +15,135 @@ namespace IceInternal public sealed class LocatorInfo { - internal LocatorInfo(Ice.LocatorPrx locator, LocatorTable table) - { - _locator = locator; - _table = table; - } - - public void destroy() - { - lock(this) - { - _locatorRegistry = null; - _table.clear(); - } - } - - public override bool Equals(object obj) - { - if(object.ReferenceEquals(this, obj)) - { - return true; - } + internal LocatorInfo(Ice.LocatorPrx locator, LocatorTable table) + { + _locator = locator; + _table = table; + } + + public void destroy() + { + lock(this) + { + _locatorRegistry = null; + _table.clear(); + } + } + + public override bool Equals(object obj) + { + if(object.ReferenceEquals(this, obj)) + { + return true; + } - LocatorInfo rhs = obj as LocatorInfo; - return rhs == null ? false : _locator.Equals(rhs._locator); - } + LocatorInfo rhs = obj as LocatorInfo; + return rhs == null ? false : _locator.Equals(rhs._locator); + } - public override int GetHashCode() - { - return _locator.GetHashCode(); - } - - public Ice.LocatorPrx getLocator() - { - // - // No synchronization necessary, _locator is immutable. - // - return _locator; - } + public override int GetHashCode() + { + return _locator.GetHashCode(); + } + + public Ice.LocatorPrx getLocator() + { + // + // No synchronization necessary, _locator is immutable. + // + return _locator; + } - public Ice.LocatorRegistryPrx getLocatorRegistry() - { - lock(this) - { - if(_locatorRegistry == null) // Lazy initialization - { - _locatorRegistry = _locator.getRegistry(); - - // - // The locator registry can't be located. - // - _locatorRegistry = Ice.LocatorRegistryPrxHelper.uncheckedCast(_locatorRegistry.ice_locator(null)); - } - - return _locatorRegistry; - } - } + public Ice.LocatorRegistryPrx getLocatorRegistry() + { + lock(this) + { + if(_locatorRegistry == null) // Lazy initialization + { + _locatorRegistry = _locator.getRegistry(); + + // + // The locator registry can't be located. + // + _locatorRegistry = Ice.LocatorRegistryPrxHelper.uncheckedCast(_locatorRegistry.ice_locator(null)); + } + + return _locatorRegistry; + } + } - public EndpointI[] getEndpoints(IndirectReference @ref, int ttl, out bool cached) - { - Debug.Assert(@ref.getEndpoints().Length == 0); - - EndpointI[] endpoints = null; - Ice.ObjectPrx obj = null; - cached = true; + public EndpointI[] getEndpoints(IndirectReference @ref, int ttl, out bool cached) + { + Debug.Assert(@ref.getEndpoints().Length == 0); + + EndpointI[] endpoints = null; + Ice.ObjectPrx obj = null; + cached = true; string adapterId = @ref.getAdapterId(); Ice.Identity identity = @ref.getIdentity(); - - try - { - if(adapterId.Length > 0) - { - endpoints = _table.getAdapterEndpoints(adapterId, ttl); - if(endpoints == null) - { - cached = false; - - if(@ref.getInstance().traceLevels().location >= 1) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("searching for adapter by id\n"); - s.Append("adapter = " + adapterId); - @ref.getInstance().initializationData().logger.trace( - @ref.getInstance().traceLevels().locationCat, s.ToString()); - } + + try + { + if(adapterId.Length > 0) + { + endpoints = _table.getAdapterEndpoints(adapterId, ttl); + if(endpoints == null) + { + cached = false; + + if(@ref.getInstance().traceLevels().location >= 1) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("searching for adapter by id\n"); + s.Append("adapter = " + adapterId); + @ref.getInstance().initializationData().logger.trace( + @ref.getInstance().traceLevels().locationCat, s.ToString()); + } - // - // Search the adapter in the location service if we didn't - // find it in the cache. - // - obj = _locator.findAdapterById(adapterId); - if(obj != null) - { - endpoints = ((Ice.ObjectPrxHelperBase)obj).reference__().getEndpoints(); - - if(endpoints != null && endpoints.Length > 0) - { - _table.addAdapterEndpoints(adapterId, endpoints); - } - } - } - } - else - { - bool objectCached = true; - obj = _table.getProxy(identity, ttl); - if(obj == null) - { - objectCached = false; - - if(@ref.getInstance().traceLevels().location >= 1) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("searching for object by id\n"); - s.Append("object = " + @ref.getInstance().identityToString(identity)); - @ref.getInstance().initializationData().logger.trace( - @ref.getInstance().traceLevels().locationCat, s.ToString()); - } + // + // Search the adapter in the location service if we didn't + // find it in the cache. + // + obj = _locator.findAdapterById(adapterId); + if(obj != null) + { + endpoints = ((Ice.ObjectPrxHelperBase)obj).reference__().getEndpoints(); + + if(endpoints != null && endpoints.Length > 0) + { + _table.addAdapterEndpoints(adapterId, endpoints); + } + } + } + } + else + { + bool objectCached = true; + obj = _table.getProxy(identity, ttl); + if(obj == null) + { + objectCached = false; + + if(@ref.getInstance().traceLevels().location >= 1) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("searching for object by id\n"); + s.Append("object = " + @ref.getInstance().identityToString(identity)); + @ref.getInstance().initializationData().logger.trace( + @ref.getInstance().traceLevels().locationCat, s.ToString()); + } - obj = _locator.findObjectById(identity); - } - - bool endpointsCached = true; - if(obj != null) - { + obj = _locator.findObjectById(identity); + } + + bool endpointsCached = true; + if(obj != null) + { Reference r = ((Ice.ObjectPrxHelperBase)obj).reference__(); if(r is DirectReference) { DirectReference odr = (DirectReference)r; - endpointsCached = false; + endpointsCached = false; endpoints = odr.getEndpoints(); } else @@ -155,114 +155,114 @@ namespace IceInternal } } } - - if(!objectCached && endpoints != null && endpoints.Length > 0) - { - _table.addProxy(identity, obj); - } + + if(!objectCached && endpoints != null && endpoints.Length > 0) + { + _table.addProxy(identity, obj); + } - cached = objectCached || endpointsCached; - } - } - catch(Ice.AdapterNotFoundException ex) - { - if(@ref.getInstance().traceLevels().location >= 1) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("adapter not found\n"); - s.Append("adapter = " + adapterId); - @ref.getInstance().initializationData().logger.trace( - @ref.getInstance().traceLevels().locationCat, s.ToString()); - } + cached = objectCached || endpointsCached; + } + } + catch(Ice.AdapterNotFoundException ex) + { + if(@ref.getInstance().traceLevels().location >= 1) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("adapter not found\n"); + s.Append("adapter = " + adapterId); + @ref.getInstance().initializationData().logger.trace( + @ref.getInstance().traceLevels().locationCat, s.ToString()); + } - Ice.NotRegisteredException e = new Ice.NotRegisteredException(ex); - e.kindOfObject = "object adapter"; - e.id = adapterId; - throw e; - } - catch(Ice.ObjectNotFoundException ex) - { - if(@ref.getInstance().traceLevels().location >= 1) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("object not found\n"); - s.Append("object = " + @ref.getInstance().identityToString(identity)); - @ref.getInstance().initializationData().logger.trace( - @ref.getInstance().traceLevels().locationCat, s.ToString()); - } + Ice.NotRegisteredException e = new Ice.NotRegisteredException(ex); + e.kindOfObject = "object adapter"; + e.id = adapterId; + throw e; + } + catch(Ice.ObjectNotFoundException ex) + { + if(@ref.getInstance().traceLevels().location >= 1) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("object not found\n"); + s.Append("object = " + @ref.getInstance().identityToString(identity)); + @ref.getInstance().initializationData().logger.trace( + @ref.getInstance().traceLevels().locationCat, s.ToString()); + } - Ice.NotRegisteredException e = new Ice.NotRegisteredException(ex); - e.kindOfObject = "object"; - e.id = @ref.getInstance().identityToString(identity); - throw e; - } - catch(Ice.NotRegisteredException) - { - throw; - } - catch(Ice.LocalException ex) - { - if(@ref.getInstance().traceLevels().location >= 1) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("couldn't contact the locator to retrieve adapter endpoints\n"); - if(adapterId.Length > 0) - { - s.Append("adapter = " + adapterId + "\n"); - } - else - { - s.Append("object = " + @ref.getInstance().identityToString(identity) + "\n"); - } - s.Append("reason = " + ex); - @ref.getInstance().initializationData().logger.trace( - @ref.getInstance().traceLevels().locationCat, s.ToString()); - } - } - - if(@ref.getInstance().traceLevels().location >= 1) - { - if(endpoints != null && endpoints.Length > 0) - { - if(cached) - { - trace("found endpoints in locator table", @ref, endpoints); - } - else - { - trace("retrieved endpoints from locator, adding to locator table", @ref, endpoints); - } - } - else - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("no endpoints configured for "); - if(adapterId.Length > 0) - { - s.Append("adapter\n"); - s.Append("adapter = " + adapterId); - } - else - { - s.Append("object\n"); - s.Append("object = " + @ref.getInstance().identityToString(identity)); - } - @ref.getInstance().initializationData().logger.trace( - @ref.getInstance().traceLevels().locationCat, s.ToString()); - } - } - - return endpoints == null ? new EndpointI[0] : endpoints; - } - - public void clearObjectCache(IndirectReference rf) - { - if(rf.getAdapterId().Length == 0 && rf.getEndpoints().Length == 0) - { - Ice.ObjectPrx obj = _table.removeProxy(rf.getIdentity()); - if(obj != null) - { - if(((Ice.ObjectPrxHelperBase)obj).reference__() is IndirectReference) + Ice.NotRegisteredException e = new Ice.NotRegisteredException(ex); + e.kindOfObject = "object"; + e.id = @ref.getInstance().identityToString(identity); + throw e; + } + catch(Ice.NotRegisteredException) + { + throw; + } + catch(Ice.LocalException ex) + { + if(@ref.getInstance().traceLevels().location >= 1) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("couldn't contact the locator to retrieve adapter endpoints\n"); + if(adapterId.Length > 0) + { + s.Append("adapter = " + adapterId + "\n"); + } + else + { + s.Append("object = " + @ref.getInstance().identityToString(identity) + "\n"); + } + s.Append("reason = " + ex); + @ref.getInstance().initializationData().logger.trace( + @ref.getInstance().traceLevels().locationCat, s.ToString()); + } + } + + if(@ref.getInstance().traceLevels().location >= 1) + { + if(endpoints != null && endpoints.Length > 0) + { + if(cached) + { + trace("found endpoints in locator table", @ref, endpoints); + } + else + { + trace("retrieved endpoints from locator, adding to locator table", @ref, endpoints); + } + } + else + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("no endpoints configured for "); + if(adapterId.Length > 0) + { + s.Append("adapter\n"); + s.Append("adapter = " + adapterId); + } + else + { + s.Append("object\n"); + s.Append("object = " + @ref.getInstance().identityToString(identity)); + } + @ref.getInstance().initializationData().logger.trace( + @ref.getInstance().traceLevels().locationCat, s.ToString()); + } + } + + return endpoints == null ? new EndpointI[0] : endpoints; + } + + public void clearObjectCache(IndirectReference rf) + { + if(rf.getAdapterId().Length == 0 && rf.getEndpoints().Length == 0) + { + Ice.ObjectPrx obj = _table.removeProxy(rf.getIdentity()); + if(obj != null) + { + if(((Ice.ObjectPrxHelperBase)obj).reference__() is IndirectReference) { IndirectReference oir = (IndirectReference)((Ice.ObjectPrxHelperBase)obj).reference__(); if(oir.getAdapterId().Length > 0) @@ -278,27 +278,27 @@ namespace IceInternal rf, ((Ice.ObjectPrxHelperBase)obj).reference__().getEndpoints()); } } - } - } - } - - public void clearCache(IndirectReference rf) - { - if(rf.getAdapterId().Length > 0) - { - EndpointI[] endpoints = _table.removeAdapterEndpoints(rf.getAdapterId()); - - if(endpoints != null && rf.getInstance().traceLevels().location >= 2) - { - trace("removed endpoints from locator table\n", rf, endpoints); - } - } - else - { - Ice.ObjectPrx obj = _table.removeProxy(rf.getIdentity()); - if(obj != null) - { - if(((Ice.ObjectPrxHelperBase)obj).reference__() is IndirectReference) + } + } + } + + public void clearCache(IndirectReference rf) + { + if(rf.getAdapterId().Length > 0) + { + EndpointI[] endpoints = _table.removeAdapterEndpoints(rf.getAdapterId()); + + if(endpoints != null && rf.getInstance().traceLevels().location >= 2) + { + trace("removed endpoints from locator table\n", rf, endpoints); + } + } + else + { + Ice.ObjectPrx obj = _table.removeProxy(rf.getIdentity()); + if(obj != null) + { + if(((Ice.ObjectPrxHelperBase)obj).reference__() is IndirectReference) { IndirectReference oir = (IndirectReference)((Ice.ObjectPrxHelperBase)obj).reference__(); if(oir.getAdapterId().Length > 0) @@ -314,40 +314,40 @@ namespace IceInternal rf, ((Ice.ObjectPrxHelperBase)obj).reference__().getEndpoints()); } } - } - } - } - - private void trace(string msg, IndirectReference r, EndpointI[] endpoints) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append(msg + "\n"); - if(r.getAdapterId().Length > 0) - { - s.Append("adapter = " + r.getAdapterId() + "\n"); - } - else - { - s.Append("object = " + r.getInstance().identityToString(r.getIdentity()) + "\n"); - } - - s.Append("endpoints = "); - int sz = endpoints.Length; - for (int i = 0; i < sz; i++) - { - s.Append(endpoints[i].ToString()); - if(i + 1 < sz) - { - s.Append(":"); - } - } - - r.getInstance().initializationData().logger.trace(r.getInstance().traceLevels().locationCat, s.ToString()); - } - - private readonly Ice.LocatorPrx _locator; - private Ice.LocatorRegistryPrx _locatorRegistry; - private readonly LocatorTable _table; + } + } + } + + private void trace(string msg, IndirectReference r, EndpointI[] endpoints) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append(msg + "\n"); + if(r.getAdapterId().Length > 0) + { + s.Append("adapter = " + r.getAdapterId() + "\n"); + } + else + { + s.Append("object = " + r.getInstance().identityToString(r.getIdentity()) + "\n"); + } + + s.Append("endpoints = "); + int sz = endpoints.Length; + for (int i = 0; i < sz; i++) + { + s.Append(endpoints[i].ToString()); + if(i + 1 < sz) + { + s.Append(":"); + } + } + + r.getInstance().initializationData().logger.trace(r.getInstance().traceLevels().locationCat, s.ToString()); + } + + private readonly Ice.LocatorPrx _locator; + private Ice.LocatorRegistryPrx _locatorRegistry; + private readonly LocatorTable _table; } public sealed class LocatorManager @@ -357,7 +357,7 @@ namespace IceInternal _table = new Hashtable(); _locatorTables = new Hashtable(); } - + internal void destroy() { lock(this) @@ -370,7 +370,7 @@ namespace IceInternal _locatorTables.Clear(); } } - + // // Returns locator info for a given locator. Automatically creates // the locator info if it doesn't exist yet. @@ -381,16 +381,16 @@ namespace IceInternal { return null; } - + // // The locator can't be located. // Ice.LocatorPrx locator = Ice.LocatorPrxHelper.uncheckedCast(loc.ice_locator(null)); - + // // TODO: reap unused locator info objects? // - + lock(this) { LocatorInfo info = (LocatorInfo)_table[locator]; @@ -407,15 +407,15 @@ namespace IceInternal table = new LocatorTable(); _locatorTables[locator.ice_getIdentity()] = table; } - + info = new LocatorInfo(locator, table); _table[locator] = info; } - + return info; } } - + private Hashtable _table; private Hashtable _locatorTables; } @@ -427,7 +427,7 @@ namespace IceInternal _adapterEndpointsTable = new Hashtable(); _objectTable = new Hashtable(); } - + internal void clear() { lock(this) @@ -436,25 +436,25 @@ namespace IceInternal _objectTable.Clear(); } } - + internal IceInternal.EndpointI[] getAdapterEndpoints(string adapter, int ttl) { - if(ttl == 0) // Locator cache disabled. - { - return null; - } + if(ttl == 0) // Locator cache disabled. + { + return null; + } lock(this) { - EndpointTableEntry entry = (EndpointTableEntry)_adapterEndpointsTable[adapter]; - if(entry != null && checkTTL(entry.time, ttl)) - { - return entry.endpoints; - } - return null; + EndpointTableEntry entry = (EndpointTableEntry)_adapterEndpointsTable[adapter]; + if(entry != null && checkTTL(entry.time, ttl)) + { + return entry.endpoints; + } + return null; } } - + internal void addAdapterEndpoints(string adapter, IceInternal.EndpointI[] endpoints) { lock(this) @@ -462,7 +462,7 @@ namespace IceInternal _adapterEndpointsTable[adapter] = new EndpointTableEntry(System.DateTime.Now.Ticks / 10000, endpoints); } } - + internal IceInternal.EndpointI[] removeAdapterEndpoints(string adapter) { lock(this) @@ -472,25 +472,25 @@ namespace IceInternal return entry != null ? entry.endpoints : null; } } - + internal Ice.ObjectPrx getProxy(Ice.Identity id, int ttl) { - if(ttl == 0) // Locator cache disabled. - { - return null; - } + if(ttl == 0) // Locator cache disabled. + { + return null; + } lock(this) { ProxyTableEntry entry = (ProxyTableEntry)_objectTable[id]; - if(entry != null && checkTTL(entry.time, ttl)) - { - return entry.proxy; - } - return null; + if(entry != null && checkTTL(entry.time, ttl)) + { + return entry.proxy; + } + return null; } } - + internal void addProxy(Ice.Identity id, Ice.ObjectPrx proxy) { lock(this) @@ -498,7 +498,7 @@ namespace IceInternal _objectTable[id] = new ProxyTableEntry(System.DateTime.Now.Ticks / 10000, proxy); } } - + internal Ice.ObjectPrx removeProxy(Ice.Identity id) { lock(this) @@ -508,43 +508,43 @@ namespace IceInternal return entry != null ? entry.proxy : null; } } - - private bool checkTTL(long time, int ttl) + + private bool checkTTL(long time, int ttl) { - Debug.Assert(ttl != 0); - if(ttl < 0) // TTL = infinite - { - return true; - } - else - { - return System.DateTime.Now.Ticks / 10000 - time <= ((long)ttl * 1000); - } - } - - sealed private class EndpointTableEntry + Debug.Assert(ttl != 0); + if(ttl < 0) // TTL = infinite + { + return true; + } + else + { + return System.DateTime.Now.Ticks / 10000 - time <= ((long)ttl * 1000); + } + } + + sealed private class EndpointTableEntry { - public EndpointTableEntry(long time, IceInternal.EndpointI[] endpoints) - { - this.time = time; - this.endpoints = endpoints; - } + public EndpointTableEntry(long time, IceInternal.EndpointI[] endpoints) + { + this.time = time; + this.endpoints = endpoints; + } - public long time; - public IceInternal.EndpointI[] endpoints; - } + public long time; + public IceInternal.EndpointI[] endpoints; + } - sealed private class ProxyTableEntry + sealed private class ProxyTableEntry { - public ProxyTableEntry(long time, Ice.ObjectPrx proxy) - { - this.time = time; - this.proxy = proxy; - } + public ProxyTableEntry(long time, Ice.ObjectPrx proxy) + { + this.time = time; + this.proxy = proxy; + } - public long time; - public Ice.ObjectPrx proxy; - } + public long time; + public Ice.ObjectPrx proxy; + } private Hashtable _adapterEndpointsTable; private Hashtable _objectTable; diff --git a/cs/src/Ice/LoggerI.cs b/cs/src/Ice/LoggerI.cs index f673d9fc238..a482bc13f3f 100755 --- a/cs/src/Ice/LoggerI.cs +++ b/cs/src/Ice/LoggerI.cs @@ -14,78 +14,78 @@ namespace Ice public sealed class LoggerI : LocalObjectImpl, Logger { - public LoggerI(string prefix) - { - if(prefix.Length > 0) - { - _prefix = prefix + ": "; - } - - _date = "G"; - } - - public void print(string message) - { - lock(_globalMutex) - { - System.Console.Error.WriteLine(message); - } - } + public LoggerI(string prefix) + { + if(prefix.Length > 0) + { + _prefix = prefix + ": "; + } + + _date = "G"; + } + + public void print(string message) + { + lock(_globalMutex) + { + System.Console.Error.WriteLine(message); + } + } - public void trace(string category, string message) - { - System.Text.StringBuilder s = new System.Text.StringBuilder("[ "); - s.Append(System.DateTime.Now.ToString(_date, DateTimeFormatInfo.InvariantInfo)); - s.Append(' '); - s.Append(_prefix); - s.Append(category); - s.Append(": "); - s.Append(message); - s.Append(" ]"); - s.Replace("\n", "\n "); + public void trace(string category, string message) + { + System.Text.StringBuilder s = new System.Text.StringBuilder("[ "); + s.Append(System.DateTime.Now.ToString(_date, DateTimeFormatInfo.InvariantInfo)); + s.Append(' '); + s.Append(_prefix); + s.Append(category); + s.Append(": "); + s.Append(message); + s.Append(" ]"); + s.Replace("\n", "\n "); - lock(_globalMutex) - { - System.Console.Error.WriteLine(s.ToString()); - } - } - - public void warning(string message) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append(System.DateTime.Now.ToString(_date, DateTimeFormatInfo.InvariantInfo)); - s.Append(' '); - s.Append(_prefix); - s.Append("warning: "); - s.Append(message); + lock(_globalMutex) + { + System.Console.Error.WriteLine(s.ToString()); + } + } + + public void warning(string message) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append(System.DateTime.Now.ToString(_date, DateTimeFormatInfo.InvariantInfo)); + s.Append(' '); + s.Append(_prefix); + s.Append("warning: "); + s.Append(message); - lock(_globalMutex) - { - System.Console.Error.WriteLine(s.ToString()); - } - } - - public void error(string message) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append(System.DateTime.Now.ToString(_date, DateTimeFormatInfo.InvariantInfo)); - s.Append(' '); - s.Append(_prefix); - s.Append("error: "); - s.Append(message); + lock(_globalMutex) + { + System.Console.Error.WriteLine(s.ToString()); + } + } + + public void error(string message) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append(System.DateTime.Now.ToString(_date, DateTimeFormatInfo.InvariantInfo)); + s.Append(' '); + s.Append(_prefix); + s.Append("error: "); + s.Append(message); - lock(_globalMutex) - { - System.Console.Error.WriteLine(s.ToString()); - } - } - - internal string _prefix = ""; - internal static object _globalMutex; - internal string _date = null; - static LoggerI() - { - _globalMutex = new object(); - } + lock(_globalMutex) + { + System.Console.Error.WriteLine(s.ToString()); + } + } + + internal string _prefix = ""; + internal static object _globalMutex; + internal string _date = null; + static LoggerI() + { + _globalMutex = new object(); + } } } diff --git a/cs/src/Ice/Network.cs b/cs/src/Ice/Network.cs index 283d54e9d62..b3f7cb32b8e 100755 --- a/cs/src/Ice/Network.cs +++ b/cs/src/Ice/Network.cs @@ -21,724 +21,724 @@ namespace IceInternal public sealed class Network { - // - // Magic numbers taken from winsock2.h - // - const int WSAEINTR = 10004; - const int WSAEFAULT = 10014; - const int WSAEINVAL = 10022; - const int WSAEWOULDBLOCK = 10035; - const int WSAEINPROGRESS = 10036; // Deprecated in winsock2, but still used by Mono Beta 1 - const int WSAEMSGSIZE = 10040; - const int WSAENETDOWN = 10050; - const int WSAENETUNREACH = 10051; - const int WSAENETRESET = 10052; - const int WSAECONNABORTED = 10053; - const int WSAECONNRESET = 10054; - const int WSAENOBUFS = 10055; - const int WSAENOTCONN = 10057; - const int WSAESHUTDOWN = 10058; - const int WSAETIMEDOUT = 10060; - const int WSAECONNREFUSED = 10061; - const int WSAEHOSTUNREACH = 10065; - const int WSATRY_AGAIN = 11002; - - public static bool interrupted(Win32Exception ex) - { - return ex.NativeErrorCode == WSAEINTR; - } - - public static bool acceptInterrupted(Win32Exception ex) - { - if(interrupted(ex)) - { - return true; - } - int error = ex.NativeErrorCode; - return error == WSAECONNABORTED || - error == WSAECONNRESET || - error == WSAETIMEDOUT; - } - - public static bool noBuffers(Win32Exception ex) - { - int error = ex.NativeErrorCode; - return error == WSAENOBUFS || - error == WSAEFAULT; - } - - public static bool wouldBlock(Win32Exception ex) - { - return ex.NativeErrorCode == WSAEWOULDBLOCK; - } - - public static bool connectFailed(Win32Exception ex) - { - int error = ex.NativeErrorCode; - return error == WSAECONNREFUSED || - error == WSAETIMEDOUT || - error == WSAENETUNREACH || - error == WSAEHOSTUNREACH || - error == WSAECONNRESET || - error == WSAESHUTDOWN || - error == WSAECONNABORTED || - error == WSAENETDOWN; - } - - public static bool connectInProgress(Win32Exception ex) - { - int error = ex.NativeErrorCode; - return error == WSAEWOULDBLOCK || - error == WSAEINPROGRESS; - } - - public static bool connectionLost(Win32Exception ex) - { - int error = ex.NativeErrorCode; - return error == WSAECONNRESET || - error == WSAESHUTDOWN || - error == WSAECONNABORTED || - error == WSAENETDOWN || - error == WSAENETRESET; - } - - public static bool connectionLost(System.IO.IOException ex) - { - string msg = ex.Message.ToLower(); - return msg.IndexOf("connection was forcibly closed") >= 0 || - msg.IndexOf("remote party has closed the transport stream") >= 0 || - msg.IndexOf("established connection was aborted") >= 0 || - msg.IndexOf("received an unexpected eof or 0 bytes from the transport stream") >= 0; - } - - public static bool connectionRefused(Win32Exception ex) - { - return ex.NativeErrorCode == WSAECONNREFUSED; - } - - public static bool notConnected(Win32Exception ex) - { - // BUGFIX: WSAEINVAL because shutdown() under MacOS returns EINVAL if the server side is gone. - return ex.NativeErrorCode == WSAENOTCONN || ex.NativeErrorCode == WSAEINVAL; - } - - public static bool recvTruncated(Win32Exception ex) - { - return ex.NativeErrorCode == WSAEMSGSIZE; - } - - public static bool timeout(System.IO.IOException ex) - { - return ex.Message.IndexOf("period of time") >= 0; - } - - public static Socket createSocket(bool udp) - { - Socket socket; - - try - { - if(udp) - { - socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - } - else - { - socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - } - } - catch(SocketException ex) - { - throw new Ice.SocketException("Cannot create socket", ex); - } - - if(!udp) - { - try - { - setTcpNoDelay(socket); - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); - } - catch(SocketException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot set socket options", ex); - } - } - return socket; - } - - public static void closeSocketNoThrow(Socket socket) - { - if(socket == null) - { - return; - } - try - { - socket.Close(); - } - catch(SocketException) - { - // Ignore - } - } - - public static void closeSocket(Socket socket) - { - if(socket == null) - { - return; - } - try - { - socket.Close(); - } - catch(SocketException ex) - { - throw new Ice.SocketException("Cannot close socket", ex); - } - } - - public static void setBlock(Socket socket, bool block) - { - try - { - socket.Blocking = block; - } - catch(SocketException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException(ex); - } - } - - public static void setTcpNoDelay(Socket socket) - { - try - { - socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); - } - catch(System.Exception ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot set NoDelay option", ex); - } - } - - public static void setKeepAlive(Socket socket) - { - try - { - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); - } - catch(System.Exception ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot set KeepAlive option", ex); - } - } - - public static void setSendBufferSize(Socket socket, int sz) - { - try - { - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, sz); - } - catch(SocketException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot set send buffer size", ex); - } - } - - public static int getSendBufferSize(Socket socket) - { - int sz; - try - { - sz = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); - } - catch(SocketException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot read send buffer size", ex); - } - return sz; - } - - public static void setRecvBufferSize(Socket socket, int sz) - { - try - { - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, sz); - } - catch(SocketException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot set receive buffer size", ex); - } - } - - public static int getRecvBufferSize(Socket socket) - { - int sz = 0; - try - { - sz = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); - } - catch(SocketException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot read receive buffer size", ex); - } - return sz; - } - - public static IPEndPoint doBind(Socket socket, EndPoint addr) - { - try - { - // - // Don't set ReuseAddress on Win32 -- it allows two processes to bind to the same port! - // - //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); - socket.Bind(addr); - return (IPEndPoint)socket.LocalEndPoint; - } - catch(SocketException ex) - { - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot bind", ex); - } - } - - public static void doListen(Socket socket, int backlog) - { - repeatListen: - - try - { - socket.Listen(backlog); - } - catch(SocketException ex) - { - if(interrupted(ex)) - { - goto repeatListen; - } - - closeSocketNoThrow(socket); - throw new Ice.SocketException("Cannot listen", ex); - } - } - - public static void doConnect(Socket socket, EndPoint addr, int timeout) - { - // - // MONO workaround for - // http://bugzilla.zeroc.com/bugzilla/show_bug.cgi?id=1647. - // - // It would have been nice to be able to get rid of the 2 - // implementations of doConnect() and only use - // doConnectAsync() however, with .NET doConnectAsync() - // doesn't work with the TCP transport. In particular, - // the test/Ice/timeout test fails in the connect timeout - // test because the client hangs in the Receive() call - // waiting for the connection validation (for some reasons - // Receive blocks even though the socket is - // non-blocking...) - // - if(AssemblyUtil.runtime_ == AssemblyUtil.Runtime.Mono) - { - doConnectAsync(socket, addr, timeout); - return; - } + // + // Magic numbers taken from winsock2.h + // + const int WSAEINTR = 10004; + const int WSAEFAULT = 10014; + const int WSAEINVAL = 10022; + const int WSAEWOULDBLOCK = 10035; + const int WSAEINPROGRESS = 10036; // Deprecated in winsock2, but still used by Mono Beta 1 + const int WSAEMSGSIZE = 10040; + const int WSAENETDOWN = 10050; + const int WSAENETUNREACH = 10051; + const int WSAENETRESET = 10052; + const int WSAECONNABORTED = 10053; + const int WSAECONNRESET = 10054; + const int WSAENOBUFS = 10055; + const int WSAENOTCONN = 10057; + const int WSAESHUTDOWN = 10058; + const int WSAETIMEDOUT = 10060; + const int WSAECONNREFUSED = 10061; + const int WSAEHOSTUNREACH = 10065; + const int WSATRY_AGAIN = 11002; + + public static bool interrupted(Win32Exception ex) + { + return ex.NativeErrorCode == WSAEINTR; + } + + public static bool acceptInterrupted(Win32Exception ex) + { + if(interrupted(ex)) + { + return true; + } + int error = ex.NativeErrorCode; + return error == WSAECONNABORTED || + error == WSAECONNRESET || + error == WSAETIMEDOUT; + } + + public static bool noBuffers(Win32Exception ex) + { + int error = ex.NativeErrorCode; + return error == WSAENOBUFS || + error == WSAEFAULT; + } + + public static bool wouldBlock(Win32Exception ex) + { + return ex.NativeErrorCode == WSAEWOULDBLOCK; + } + + public static bool connectFailed(Win32Exception ex) + { + int error = ex.NativeErrorCode; + return error == WSAECONNREFUSED || + error == WSAETIMEDOUT || + error == WSAENETUNREACH || + error == WSAEHOSTUNREACH || + error == WSAECONNRESET || + error == WSAESHUTDOWN || + error == WSAECONNABORTED || + error == WSAENETDOWN; + } + + public static bool connectInProgress(Win32Exception ex) + { + int error = ex.NativeErrorCode; + return error == WSAEWOULDBLOCK || + error == WSAEINPROGRESS; + } + + public static bool connectionLost(Win32Exception ex) + { + int error = ex.NativeErrorCode; + return error == WSAECONNRESET || + error == WSAESHUTDOWN || + error == WSAECONNABORTED || + error == WSAENETDOWN || + error == WSAENETRESET; + } + + public static bool connectionLost(System.IO.IOException ex) + { + string msg = ex.Message.ToLower(); + return msg.IndexOf("connection was forcibly closed") >= 0 || + msg.IndexOf("remote party has closed the transport stream") >= 0 || + msg.IndexOf("established connection was aborted") >= 0 || + msg.IndexOf("received an unexpected eof or 0 bytes from the transport stream") >= 0; + } + + public static bool connectionRefused(Win32Exception ex) + { + return ex.NativeErrorCode == WSAECONNREFUSED; + } + + public static bool notConnected(Win32Exception ex) + { + // BUGFIX: WSAEINVAL because shutdown() under MacOS returns EINVAL if the server side is gone. + return ex.NativeErrorCode == WSAENOTCONN || ex.NativeErrorCode == WSAEINVAL; + } + + public static bool recvTruncated(Win32Exception ex) + { + return ex.NativeErrorCode == WSAEMSGSIZE; + } + + public static bool timeout(System.IO.IOException ex) + { + return ex.Message.IndexOf("period of time") >= 0; + } + + public static Socket createSocket(bool udp) + { + Socket socket; + + try + { + if(udp) + { + socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + } + else + { + socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + } + } + catch(SocketException ex) + { + throw new Ice.SocketException("Cannot create socket", ex); + } + + if(!udp) + { + try + { + setTcpNoDelay(socket); + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); + } + catch(SocketException ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot set socket options", ex); + } + } + return socket; + } + + public static void closeSocketNoThrow(Socket socket) + { + if(socket == null) + { + return; + } + try + { + socket.Close(); + } + catch(SocketException) + { + // Ignore + } + } + + public static void closeSocket(Socket socket) + { + if(socket == null) + { + return; + } + try + { + socket.Close(); + } + catch(SocketException ex) + { + throw new Ice.SocketException("Cannot close socket", ex); + } + } + + public static void setBlock(Socket socket, bool block) + { + try + { + socket.Blocking = block; + } + catch(SocketException ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException(ex); + } + } + + public static void setTcpNoDelay(Socket socket) + { + try + { + socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); + } + catch(System.Exception ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot set NoDelay option", ex); + } + } + + public static void setKeepAlive(Socket socket) + { + try + { + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); + } + catch(System.Exception ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot set KeepAlive option", ex); + } + } + + public static void setSendBufferSize(Socket socket, int sz) + { + try + { + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, sz); + } + catch(SocketException ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot set send buffer size", ex); + } + } + + public static int getSendBufferSize(Socket socket) + { + int sz; + try + { + sz = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); + } + catch(SocketException ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot read send buffer size", ex); + } + return sz; + } + + public static void setRecvBufferSize(Socket socket, int sz) + { + try + { + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, sz); + } + catch(SocketException ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot set receive buffer size", ex); + } + } + + public static int getRecvBufferSize(Socket socket) + { + int sz = 0; + try + { + sz = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); + } + catch(SocketException ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot read receive buffer size", ex); + } + return sz; + } + + public static IPEndPoint doBind(Socket socket, EndPoint addr) + { + try + { + // + // Don't set ReuseAddress on Win32 -- it allows two processes to bind to the same port! + // + //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); + socket.Bind(addr); + return (IPEndPoint)socket.LocalEndPoint; + } + catch(SocketException ex) + { + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot bind", ex); + } + } + + public static void doListen(Socket socket, int backlog) + { + repeatListen: + + try + { + socket.Listen(backlog); + } + catch(SocketException ex) + { + if(interrupted(ex)) + { + goto repeatListen; + } + + closeSocketNoThrow(socket); + throw new Ice.SocketException("Cannot listen", ex); + } + } + + public static void doConnect(Socket socket, EndPoint addr, int timeout) + { + // + // MONO workaround for + // http://bugzilla.zeroc.com/bugzilla/show_bug.cgi?id=1647. + // + // It would have been nice to be able to get rid of the 2 + // implementations of doConnect() and only use + // doConnectAsync() however, with .NET doConnectAsync() + // doesn't work with the TCP transport. In particular, + // the test/Ice/timeout test fails in the connect timeout + // test because the client hangs in the Receive() call + // waiting for the connection validation (for some reasons + // Receive blocks even though the socket is + // non-blocking...) + // + if(AssemblyUtil.runtime_ == AssemblyUtil.Runtime.Mono) + { + doConnectAsync(socket, addr, timeout); + return; + } // // Set larger send buffer size to avoid performance problems on // WIN32. // - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) - { - setSendBufferSize(socket, 64 * 1024); - } - - repeatConnect: - try - { - socket.Connect(addr); - } - catch(SocketException ex) - { - if(interrupted(ex)) - { - goto repeatConnect; - } - - if(!connectInProgress(ex)) - { - closeSocketNoThrow(socket); - // - // Check for connectionRefused, and connectFailed - // here. - // - if(connectionRefused(ex)) - { - throw new Ice.ConnectionRefusedException("Connect refused", ex); - } - else if(connectFailed(ex)) - { - throw new Ice.ConnectFailedException("Connection failed", ex); - } - else - { - throw new Ice.SocketException(ex); - } - } - - repeatSelect: - bool ready; - bool error; - try - { - ArrayList writeList = new ArrayList(); - writeList.Add(socket); - ArrayList errorList = new ArrayList(); - errorList.Add(socket); - doSelect(null, writeList, errorList, timeout); - ready = writeList.Count != 0; - error = errorList.Count != 0; - - // - // As with C++ we need to get the SO_ERROR error - // to determine whether the connect has actually - // failed. - // - int val = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); - if(val > 0) - { - closeSocketNoThrow(socket); - - // - // Create a Win32Exception out of this error value. Check the for refused, and - // failed. Otherwise its a plain old socket exception. - // - Win32Exception sockEx = new Win32Exception(val); - if(connectionRefused(sockEx)) - { - throw new Ice.ConnectionRefusedException("Connect refused", sockEx); - } - else if(connectFailed(sockEx)) - { - throw new Ice.ConnectFailedException("Connect failed", sockEx); - } - else - { - throw new Ice.SocketException(sockEx); - } - } - - Debug.Assert(!(ready && error)); - } - catch(SocketException e) - { - if(interrupted(e)) - { - goto repeatSelect; - } - - closeSocketNoThrow(socket); - throw new Ice.SocketException(e); - } - - if(error || !ready) - { - closeSocketNoThrow(socket); - - // - // If GetSocketOption didn't return an error and we've failed then we cannot - // distinguish between connect failed and connection refused. - // - if(error) - { - throw new Ice.ConnectFailedException("Connect failed"); - } - else - { - throw new Ice.ConnectTimeoutException("Connect timed out after " + timeout + " msec"); - } - } - } - } - - internal class AsyncConnectInfo - { - internal AsyncConnectInfo(Socket fd) - { - this.fd = fd; - this.ex = null; - this.done = false; - } - - internal Socket fd; - volatile internal Exception ex; - volatile internal bool done; - } - - private static void asyncConnectCallback(IAsyncResult ar) - { - AsyncConnectInfo info = (AsyncConnectInfo)ar.AsyncState; - lock(info) - { - try - { - info.fd.EndConnect(ar); - } - catch(Exception ex) - { - info.ex = ex; - } - finally - { - info.done = true; - Monitor.Pulse(info); - } - } - } - - public static void doConnectAsync(Socket socket, EndPoint addr, int timeout) - { + if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) + { + setSendBufferSize(socket, 64 * 1024); + } + + repeatConnect: + try + { + socket.Connect(addr); + } + catch(SocketException ex) + { + if(interrupted(ex)) + { + goto repeatConnect; + } + + if(!connectInProgress(ex)) + { + closeSocketNoThrow(socket); + // + // Check for connectionRefused, and connectFailed + // here. + // + if(connectionRefused(ex)) + { + throw new Ice.ConnectionRefusedException("Connect refused", ex); + } + else if(connectFailed(ex)) + { + throw new Ice.ConnectFailedException("Connection failed", ex); + } + else + { + throw new Ice.SocketException(ex); + } + } + + repeatSelect: + bool ready; + bool error; + try + { + ArrayList writeList = new ArrayList(); + writeList.Add(socket); + ArrayList errorList = new ArrayList(); + errorList.Add(socket); + doSelect(null, writeList, errorList, timeout); + ready = writeList.Count != 0; + error = errorList.Count != 0; + + // + // As with C++ we need to get the SO_ERROR error + // to determine whether the connect has actually + // failed. + // + int val = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); + if(val > 0) + { + closeSocketNoThrow(socket); + + // + // Create a Win32Exception out of this error value. Check the for refused, and + // failed. Otherwise its a plain old socket exception. + // + Win32Exception sockEx = new Win32Exception(val); + if(connectionRefused(sockEx)) + { + throw new Ice.ConnectionRefusedException("Connect refused", sockEx); + } + else if(connectFailed(sockEx)) + { + throw new Ice.ConnectFailedException("Connect failed", sockEx); + } + else + { + throw new Ice.SocketException(sockEx); + } + } + + Debug.Assert(!(ready && error)); + } + catch(SocketException e) + { + if(interrupted(e)) + { + goto repeatSelect; + } + + closeSocketNoThrow(socket); + throw new Ice.SocketException(e); + } + + if(error || !ready) + { + closeSocketNoThrow(socket); + + // + // If GetSocketOption didn't return an error and we've failed then we cannot + // distinguish between connect failed and connection refused. + // + if(error) + { + throw new Ice.ConnectFailedException("Connect failed"); + } + else + { + throw new Ice.ConnectTimeoutException("Connect timed out after " + timeout + " msec"); + } + } + } + } + + internal class AsyncConnectInfo + { + internal AsyncConnectInfo(Socket fd) + { + this.fd = fd; + this.ex = null; + this.done = false; + } + + internal Socket fd; + volatile internal Exception ex; + volatile internal bool done; + } + + private static void asyncConnectCallback(IAsyncResult ar) + { + AsyncConnectInfo info = (AsyncConnectInfo)ar.AsyncState; + lock(info) + { + try + { + info.fd.EndConnect(ar); + } + catch(Exception ex) + { + info.ex = ex; + } + finally + { + info.done = true; + Monitor.Pulse(info); + } + } + } + + public static void doConnectAsync(Socket socket, EndPoint addr, int timeout) + { // // Set larger send buffer size to avoid performance problems on // WIN32. // - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) - { - setSendBufferSize(socket, 64 * 1024); - } - - repeatConnect: - try - { - AsyncConnectInfo info = new AsyncConnectInfo(socket); - /* IAsyncResult ar = */ socket.BeginConnect(addr, new AsyncCallback(asyncConnectCallback), info); - lock(info) - { - if(!info.done) - { - if(!Monitor.Wait(info, timeout == -1 ? Timeout.Infinite : timeout)) - { - throw new Ice.ConnectTimeoutException("Connect timed out after " + timeout + " msec"); - } - } - if(info.ex != null) - { - throw info.ex; - } - } - } - catch(SocketException ex) - { - if(interrupted(ex)) - { - goto repeatConnect; - } - - closeSocketNoThrow(socket); - - // - // Check for connectionRefused, and connectFailed - // here. - // - if(connectionRefused(ex)) - { - throw new Ice.ConnectionRefusedException("Connect refused", ex); - } - else if(connectFailed(ex)) - { - throw new Ice.ConnectFailedException("Connection failed", ex); - } - else - { - throw new Ice.SocketException(ex); - } - } - } - - public static Socket doAccept(Socket socket, int timeout) - { - Socket ret = null; - - repeatAccept: - try - { - ret = socket.Accept(); - } - catch(SocketException ex) - { - if(acceptInterrupted(ex)) - { - goto repeatAccept; - } - if(wouldBlock(ex)) - { - repeatSelect: - ArrayList readList = new ArrayList(); - readList.Add(socket); - try - { - doSelect(readList, null, null, timeout); - } - catch(Win32Exception we) - { - if(interrupted(we)) - { - goto repeatSelect; - } - throw new Ice.SocketException("select failed", we); - } - catch(System.Exception se) - { - throw new Ice.SocketException("select failed", se); - } - - if(readList.Count == 0) - { - throw new Ice.TimeoutException(); - } - - goto repeatAccept; - } - } - - setTcpNoDelay(ret); - setKeepAlive(ret); - setSendBufferSize(ret, 64 * 1024); - - return ret; - } - - private static ArrayList copyList(IList list) - { - if(list == null) - { - return null; - } - return new ArrayList(list); - } - - private static void overwriteList(ArrayList from, IList to) - { - if(from != null && to != null) - { - to.Clear(); - foreach(object o in from) - { - to.Add(o); - } - } - } - - public enum PollMode { Read, Write, Error }; - - public static bool doPoll(Socket s, int timeout, PollMode mode) - { - // - // Poll() wants microseconds, so we need to deal with overflow. - // - while((timeout > System.Int32.MaxValue / 1000)) - { - if(s.Poll((System.Int32.MaxValue / 1000) * 1000, (SelectMode)mode)) - { - return true; - } - timeout -= System.Int32.MaxValue / 1000; - } - return s.Poll(timeout * 1000, (SelectMode)mode); - } - - public static void doSelect(IList checkRead, IList checkWrite, IList checkError, int milliSeconds) - { - ArrayList cr = null; - ArrayList cw = null; - ArrayList ce = null; - - if(milliSeconds < 0) - { - // - // Socket.Select() returns immediately if the timeout is < 0 (instead - // of blocking indefinitely), so we have to emulate a blocking select here. - // (Using Int32.MaxValue isn't good enough because that's only about 35 minutes.) - // - do { - cr = copyList(checkRead); - cw = copyList(checkWrite); - ce = copyList(checkError); - try - { - Socket.Select(cr, cw, ce, System.Int32.MaxValue); - } - catch(SocketException e) - { - if(interrupted(e)) - { - continue; - } - throw new Ice.SocketException(e); - } - } - while((cr == null || cr.Count == 0) && - (cw == null || cw.Count == 0) && - (ce == null || ce.Count == 0)); - overwriteList(cr, checkRead); - overwriteList(cw, checkWrite); - overwriteList(ce, checkError); - } - else - { - // - // Select() wants microseconds, so we need to deal with overflow. - // - while((milliSeconds > System.Int32.MaxValue / 1000) && - ((cr == null) || cr.Count == 0) && - ((cw == null) || cw.Count == 0) && - ((ce == null) || ce.Count == 0)) - { - cr = copyList(checkRead); - cw = copyList(checkWrite); - ce = copyList(checkError); - try - { - Socket.Select(cr, cw, ce, (System.Int32.MaxValue / 1000) * 1000); - } - catch(SocketException e) - { - if(interrupted(e)) - { - continue; - } - throw new Ice.SocketException(e); - } - milliSeconds -= System.Int32.MaxValue / 1000; - } - if(cr == null && cw == null && ce == null) - { - Socket.Select(checkRead, checkWrite, checkError, milliSeconds * 1000); - } - overwriteList(cr, checkRead); - overwriteList(cw, checkWrite); - overwriteList(ce, checkError); - } - } - - public static IPEndPoint getAddress(string host, int port) - { - int retry = 5; - - repeatGetHostByName: - try - { + if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) + { + setSendBufferSize(socket, 64 * 1024); + } + + repeatConnect: + try + { + AsyncConnectInfo info = new AsyncConnectInfo(socket); + /* IAsyncResult ar = */ socket.BeginConnect(addr, new AsyncCallback(asyncConnectCallback), info); + lock(info) + { + if(!info.done) + { + if(!Monitor.Wait(info, timeout == -1 ? Timeout.Infinite : timeout)) + { + throw new Ice.ConnectTimeoutException("Connect timed out after " + timeout + " msec"); + } + } + if(info.ex != null) + { + throw info.ex; + } + } + } + catch(SocketException ex) + { + if(interrupted(ex)) + { + goto repeatConnect; + } + + closeSocketNoThrow(socket); + + // + // Check for connectionRefused, and connectFailed + // here. + // + if(connectionRefused(ex)) + { + throw new Ice.ConnectionRefusedException("Connect refused", ex); + } + else if(connectFailed(ex)) + { + throw new Ice.ConnectFailedException("Connection failed", ex); + } + else + { + throw new Ice.SocketException(ex); + } + } + } + + public static Socket doAccept(Socket socket, int timeout) + { + Socket ret = null; + + repeatAccept: + try + { + ret = socket.Accept(); + } + catch(SocketException ex) + { + if(acceptInterrupted(ex)) + { + goto repeatAccept; + } + if(wouldBlock(ex)) + { + repeatSelect: + ArrayList readList = new ArrayList(); + readList.Add(socket); + try + { + doSelect(readList, null, null, timeout); + } + catch(Win32Exception we) + { + if(interrupted(we)) + { + goto repeatSelect; + } + throw new Ice.SocketException("select failed", we); + } + catch(System.Exception se) + { + throw new Ice.SocketException("select failed", se); + } + + if(readList.Count == 0) + { + throw new Ice.TimeoutException(); + } + + goto repeatAccept; + } + } + + setTcpNoDelay(ret); + setKeepAlive(ret); + setSendBufferSize(ret, 64 * 1024); + + return ret; + } + + private static ArrayList copyList(IList list) + { + if(list == null) + { + return null; + } + return new ArrayList(list); + } + + private static void overwriteList(ArrayList from, IList to) + { + if(from != null && to != null) + { + to.Clear(); + foreach(object o in from) + { + to.Add(o); + } + } + } + + public enum PollMode { Read, Write, Error }; + + public static bool doPoll(Socket s, int timeout, PollMode mode) + { + // + // Poll() wants microseconds, so we need to deal with overflow. + // + while((timeout > System.Int32.MaxValue / 1000)) + { + if(s.Poll((System.Int32.MaxValue / 1000) * 1000, (SelectMode)mode)) + { + return true; + } + timeout -= System.Int32.MaxValue / 1000; + } + return s.Poll(timeout * 1000, (SelectMode)mode); + } + + public static void doSelect(IList checkRead, IList checkWrite, IList checkError, int milliSeconds) + { + ArrayList cr = null; + ArrayList cw = null; + ArrayList ce = null; + + if(milliSeconds < 0) + { + // + // Socket.Select() returns immediately if the timeout is < 0 (instead + // of blocking indefinitely), so we have to emulate a blocking select here. + // (Using Int32.MaxValue isn't good enough because that's only about 35 minutes.) + // + do { + cr = copyList(checkRead); + cw = copyList(checkWrite); + ce = copyList(checkError); + try + { + Socket.Select(cr, cw, ce, System.Int32.MaxValue); + } + catch(SocketException e) + { + if(interrupted(e)) + { + continue; + } + throw new Ice.SocketException(e); + } + } + while((cr == null || cr.Count == 0) && + (cw == null || cw.Count == 0) && + (ce == null || ce.Count == 0)); + overwriteList(cr, checkRead); + overwriteList(cw, checkWrite); + overwriteList(ce, checkError); + } + else + { + // + // Select() wants microseconds, so we need to deal with overflow. + // + while((milliSeconds > System.Int32.MaxValue / 1000) && + ((cr == null) || cr.Count == 0) && + ((cw == null) || cw.Count == 0) && + ((ce == null) || ce.Count == 0)) + { + cr = copyList(checkRead); + cw = copyList(checkWrite); + ce = copyList(checkError); + try + { + Socket.Select(cr, cw, ce, (System.Int32.MaxValue / 1000) * 1000); + } + catch(SocketException e) + { + if(interrupted(e)) + { + continue; + } + throw new Ice.SocketException(e); + } + milliSeconds -= System.Int32.MaxValue / 1000; + } + if(cr == null && cw == null && ce == null) + { + Socket.Select(checkRead, checkWrite, checkError, milliSeconds * 1000); + } + overwriteList(cr, checkRead); + overwriteList(cw, checkWrite); + overwriteList(ce, checkError); + } + } + + public static IPEndPoint getAddress(string host, int port) + { + int retry = 5; + + repeatGetHostByName: + try + { try { return new IPEndPoint(IPAddress.Parse(host), port); @@ -746,276 +746,276 @@ namespace IceInternal catch (FormatException) { } - IPHostEntry e = Dns.GetHostEntry(host); - for(int i = 0; i < e.AddressList.Length; ++i) - { - if(e.AddressList[i].AddressFamily != AddressFamily.InterNetworkV6) - { - return new IPEndPoint(e.AddressList[i], port); - } - } - } - catch(Win32Exception ex) - { - if(ex.NativeErrorCode == WSATRY_AGAIN && --retry >= 0) - { - goto repeatGetHostByName; - } - Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); - e.host = host; - throw e; - } - catch(System.Exception ex) - { - Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); - e.host = host; - throw e; - } - - // - // No InterNetworkV4 address available. - // - Ice.DNSException dns = new Ice.DNSException("no IPv4 addresses found "); - dns.host = host; - throw dns; - } - - public static string getNumericHost(string hostname) - { - int retry = 5; - - repeatGetHostByName: - try - { - IPHostEntry e = Dns.GetHostEntry(hostname); - for(int i = 0; i < e.AddressList.Length; ++i) - { - if(e.AddressList[i].AddressFamily != AddressFamily.InterNetworkV6) - { - return e.AddressList[i].ToString(); - } - } - } - catch(Win32Exception ex) - { - if(ex.NativeErrorCode == WSATRY_AGAIN && --retry >= 0) - { - goto repeatGetHostByName; - } - Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); - e.host = hostname; - throw e; - } - catch(System.Exception ex) - { - Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); - e.host = hostname; - throw e; - } - - // - // No InterNetworkV4 address available. - // - Ice.DNSException dns = new Ice.DNSException("no IPv4 addresses found"); - dns.host = hostname; - throw dns; - } - - public static string[] getLocalHosts() - { - ArrayList hosts; - - int retry = 5; - - repeatGetHostByName: - try - { - IPHostEntry e = Dns.GetHostEntry(Dns.GetHostName()); - hosts = new ArrayList(); - for(int i = 0; i < e.AddressList.Length; ++i) - { - if(e.AddressList[i].AddressFamily != AddressFamily.InterNetworkV6) - { - hosts.Add(e.AddressList[i].ToString()); - } - } - hosts.Add(IPAddress.Loopback.ToString()); - } - catch(Win32Exception ex) - { - if(ex.NativeErrorCode == WSATRY_AGAIN && --retry >= 0) - { - goto repeatGetHostByName; - } - Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); - e.host = "0.0.0.0"; - throw e; - } - catch(System.Exception ex) - { - Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); - e.host = "0.0.0.0"; - throw e; - } - - return (string[])hosts.ToArray(typeof(string)); - } - - public sealed class SocketPair - { - public Socket source; - public Socket sink; - - public SocketPair() - { - sink = createSocket(false); - Socket listener = createSocket(false); - - doBind(listener, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0)); - doListen(listener, 1); - doConnect(sink, listener.LocalEndPoint, 1000); - try - { - source = doAccept(listener, -1); - } - catch(Ice.SocketException) - { - try - { - sink.Close(); - } - catch(System.Exception) - { - // ignore - } - throw; - } - finally - { - try - { - listener.Close(); - } - catch(System.Exception) - { - } - } - } - } - - public static SocketPair createPipe() - { - return new SocketPair(); - } - - [StructLayout(LayoutKind.Sequential)] - private struct in_addr - { - [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] - public byte[] sin_addr; - } - - [StructLayout(LayoutKind.Sequential)] - private struct sockaddr - { - public short sin_family; - public ushort sin_port; - public in_addr sin_addr; - [MarshalAs(UnmanagedType.ByValArray, SizeConst=8)] - public byte[] sin_zero; - } - - [DllImport("wsock32.dll")] - private static extern int getsockname(IntPtr s, ref sockaddr name, ref int namelen); - - [DllImport("wsock32.dll")] - private static extern int getpeername(IntPtr s, ref sockaddr name, ref int namelen); - - [DllImport("ws2_32.dll")] - private static extern IntPtr inet_ntoa(in_addr a); - - [DllImport("ws2_32.dll")] - private static extern ushort ntohs(ushort netshort); - - public static string fdToString(Socket socket) - { - if(socket == null) - { - return "<closed>"; - } - - // - // .Net BUG: The LocalEndPoint and RemoteEndPoint properties - // are null for a socket that was connected in non-blocking - // mode. The only way to make this work is to step down to - // the native API and use platform invoke :-( - // - IPEndPoint localEndpoint; - IPEndPoint remoteEndpoint; - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) - { - sockaddr addr = new sockaddr(); - int addrLen = 16; - - if(getsockname(socket.Handle, ref addr, ref addrLen) != 0) - { - throw new Ice.SyscallException("getsockname call failed"); - } - string ip = Marshal.PtrToStringAnsi(inet_ntoa(addr.sin_addr)); - int port = ntohs(addr.sin_port); - localEndpoint = new IPEndPoint(IPAddress.Parse(ip), port); - - remoteEndpoint = null; - if(getpeername(socket.Handle, ref addr, ref addrLen) == 0) - { - ip = Marshal.PtrToStringAnsi(inet_ntoa(addr.sin_addr)); - port = ntohs(addr.sin_port); - remoteEndpoint = new IPEndPoint(IPAddress.Parse(ip), port); - } - } - else - { - try - { - localEndpoint = (IPEndPoint)socket.LocalEndPoint; - } - catch(SocketException ex) - { - throw new Ice.SocketException(ex); - } - - try - { - remoteEndpoint = (IPEndPoint)socket.RemoteEndPoint; - } - catch(SocketException) - { - remoteEndpoint = null; - } - } - - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("local address = " + localEndpoint.Address); - s.Append(":" + localEndpoint.Port); - - if(remoteEndpoint == null) - { - s.Append("\nremote address = <not connected>"); - } - else - { - s.Append("\nremote address = " + IPAddress.Parse(remoteEndpoint.Address.ToString())); - s.Append(":" + remoteEndpoint.Port.ToString()); - } - - return s.ToString(); - } - - public static string - addrToString(EndPoint addr) - { - return addr.ToString(); - } + IPHostEntry e = Dns.GetHostEntry(host); + for(int i = 0; i < e.AddressList.Length; ++i) + { + if(e.AddressList[i].AddressFamily != AddressFamily.InterNetworkV6) + { + return new IPEndPoint(e.AddressList[i], port); + } + } + } + catch(Win32Exception ex) + { + if(ex.NativeErrorCode == WSATRY_AGAIN && --retry >= 0) + { + goto repeatGetHostByName; + } + Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); + e.host = host; + throw e; + } + catch(System.Exception ex) + { + Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); + e.host = host; + throw e; + } + + // + // No InterNetworkV4 address available. + // + Ice.DNSException dns = new Ice.DNSException("no IPv4 addresses found "); + dns.host = host; + throw dns; + } + + public static string getNumericHost(string hostname) + { + int retry = 5; + + repeatGetHostByName: + try + { + IPHostEntry e = Dns.GetHostEntry(hostname); + for(int i = 0; i < e.AddressList.Length; ++i) + { + if(e.AddressList[i].AddressFamily != AddressFamily.InterNetworkV6) + { + return e.AddressList[i].ToString(); + } + } + } + catch(Win32Exception ex) + { + if(ex.NativeErrorCode == WSATRY_AGAIN && --retry >= 0) + { + goto repeatGetHostByName; + } + Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); + e.host = hostname; + throw e; + } + catch(System.Exception ex) + { + Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); + e.host = hostname; + throw e; + } + + // + // No InterNetworkV4 address available. + // + Ice.DNSException dns = new Ice.DNSException("no IPv4 addresses found"); + dns.host = hostname; + throw dns; + } + + public static string[] getLocalHosts() + { + ArrayList hosts; + + int retry = 5; + + repeatGetHostByName: + try + { + IPHostEntry e = Dns.GetHostEntry(Dns.GetHostName()); + hosts = new ArrayList(); + for(int i = 0; i < e.AddressList.Length; ++i) + { + if(e.AddressList[i].AddressFamily != AddressFamily.InterNetworkV6) + { + hosts.Add(e.AddressList[i].ToString()); + } + } + hosts.Add(IPAddress.Loopback.ToString()); + } + catch(Win32Exception ex) + { + if(ex.NativeErrorCode == WSATRY_AGAIN && --retry >= 0) + { + goto repeatGetHostByName; + } + Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); + e.host = "0.0.0.0"; + throw e; + } + catch(System.Exception ex) + { + Ice.DNSException e = new Ice.DNSException("address lookup failed", ex); + e.host = "0.0.0.0"; + throw e; + } + + return (string[])hosts.ToArray(typeof(string)); + } + + public sealed class SocketPair + { + public Socket source; + public Socket sink; + + public SocketPair() + { + sink = createSocket(false); + Socket listener = createSocket(false); + + doBind(listener, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0)); + doListen(listener, 1); + doConnect(sink, listener.LocalEndPoint, 1000); + try + { + source = doAccept(listener, -1); + } + catch(Ice.SocketException) + { + try + { + sink.Close(); + } + catch(System.Exception) + { + // ignore + } + throw; + } + finally + { + try + { + listener.Close(); + } + catch(System.Exception) + { + } + } + } + } + + public static SocketPair createPipe() + { + return new SocketPair(); + } + + [StructLayout(LayoutKind.Sequential)] + private struct in_addr + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] + public byte[] sin_addr; + } + + [StructLayout(LayoutKind.Sequential)] + private struct sockaddr + { + public short sin_family; + public ushort sin_port; + public in_addr sin_addr; + [MarshalAs(UnmanagedType.ByValArray, SizeConst=8)] + public byte[] sin_zero; + } + + [DllImport("wsock32.dll")] + private static extern int getsockname(IntPtr s, ref sockaddr name, ref int namelen); + + [DllImport("wsock32.dll")] + private static extern int getpeername(IntPtr s, ref sockaddr name, ref int namelen); + + [DllImport("ws2_32.dll")] + private static extern IntPtr inet_ntoa(in_addr a); + + [DllImport("ws2_32.dll")] + private static extern ushort ntohs(ushort netshort); + + public static string fdToString(Socket socket) + { + if(socket == null) + { + return "<closed>"; + } + + // + // .Net BUG: The LocalEndPoint and RemoteEndPoint properties + // are null for a socket that was connected in non-blocking + // mode. The only way to make this work is to step down to + // the native API and use platform invoke :-( + // + IPEndPoint localEndpoint; + IPEndPoint remoteEndpoint; + if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) + { + sockaddr addr = new sockaddr(); + int addrLen = 16; + + if(getsockname(socket.Handle, ref addr, ref addrLen) != 0) + { + throw new Ice.SyscallException("getsockname call failed"); + } + string ip = Marshal.PtrToStringAnsi(inet_ntoa(addr.sin_addr)); + int port = ntohs(addr.sin_port); + localEndpoint = new IPEndPoint(IPAddress.Parse(ip), port); + + remoteEndpoint = null; + if(getpeername(socket.Handle, ref addr, ref addrLen) == 0) + { + ip = Marshal.PtrToStringAnsi(inet_ntoa(addr.sin_addr)); + port = ntohs(addr.sin_port); + remoteEndpoint = new IPEndPoint(IPAddress.Parse(ip), port); + } + } + else + { + try + { + localEndpoint = (IPEndPoint)socket.LocalEndPoint; + } + catch(SocketException ex) + { + throw new Ice.SocketException(ex); + } + + try + { + remoteEndpoint = (IPEndPoint)socket.RemoteEndPoint; + } + catch(SocketException) + { + remoteEndpoint = null; + } + } + + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("local address = " + localEndpoint.Address); + s.Append(":" + localEndpoint.Port); + + if(remoteEndpoint == null) + { + s.Append("\nremote address = <not connected>"); + } + else + { + s.Append("\nremote address = " + IPAddress.Parse(remoteEndpoint.Address.ToString())); + s.Append(":" + remoteEndpoint.Port.ToString()); + } + + return s.ToString(); + } + + public static string + addrToString(EndPoint addr) + { + return addr.ToString(); + } } } diff --git a/cs/src/Ice/Object.cs b/cs/src/Ice/Object.cs index 8a14b62c3eb..9ce79d814a0 100755 --- a/cs/src/Ice/Object.cs +++ b/cs/src/Ice/Object.cs @@ -33,30 +33,30 @@ namespace Ice public interface Object : System.ICloneable { - int ice_hash(); + int ice_hash(); bool ice_isA(string s); - bool ice_isA(string s, Current current); + bool ice_isA(string s, Current current); void ice_ping(); - void ice_ping(Current current); + void ice_ping(Current current); string[] ice_ids(); - string[] ice_ids(Current current); + string[] ice_ids(Current current); string ice_id(); - string ice_id(Current current); + string ice_id(Current current); - void ice_preMarshal(); - void ice_postUnmarshal(); + void ice_preMarshal(); + void ice_postUnmarshal(); - IceInternal.DispatchStatus dispatch__(IceInternal.Incoming inc, Current current); + IceInternal.DispatchStatus dispatch__(IceInternal.Incoming inc, Current current); - void write__(IceInternal.BasicStream os__); - void read__(IceInternal.BasicStream is__, bool rid__); + void write__(IceInternal.BasicStream os__); + void read__(IceInternal.BasicStream is__, bool rid__); - void write__(OutputStream outS__); - void read__(InputStream inS__, bool rid__); + void write__(OutputStream outS__); + void read__(InputStream inS__, bool rid__); } public abstract class ObjectImpl : Object @@ -76,7 +76,7 @@ namespace Ice } public static readonly string[] ids__ = new string[] { "::Ice::Object" }; - + public virtual bool ice_isA(string s) { return s.Equals(ids__[0]); @@ -86,7 +86,7 @@ namespace Ice { return s.Equals(ids__[0]); } - + public static IceInternal.DispatchStatus ice_isA___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) { @@ -97,7 +97,7 @@ namespace Ice os__.writeBool(__ret); return IceInternal.DispatchStatus.DispatchOK; } - + public virtual void ice_ping() { // Nothing to do. @@ -107,14 +107,14 @@ namespace Ice { // Nothing to do. } - + public static IceInternal.DispatchStatus ice_ping___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) { __obj.ice_ping(__current); return IceInternal.DispatchStatus.DispatchOK; } - + public virtual string[] ice_ids() { return ids__; @@ -124,7 +124,7 @@ namespace Ice { return ids__; } - + public static IceInternal.DispatchStatus ice_ids___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) { @@ -132,7 +132,7 @@ namespace Ice os__.writeStringSeq(__obj.ice_ids(__current)); return IceInternal.DispatchStatus.DispatchOK; } - + public virtual string ice_id() { return ids__[0]; @@ -142,7 +142,7 @@ namespace Ice { return ids__[0]; } - + public static IceInternal.DispatchStatus ice_id___(Ice.Object __obj, IceInternal.Incoming inS__, Current __current) { @@ -151,12 +151,12 @@ namespace Ice os__.writeString(__ret); return IceInternal.DispatchStatus.DispatchOK; } - + public static string ice_staticId() { return ids__[0]; } - + public virtual void ice_preMarshal() { } @@ -169,7 +169,7 @@ namespace Ice { "ice_id", "ice_ids", "ice_isA", "ice_ping" }; - + public virtual IceInternal.DispatchStatus dispatch__(IceInternal.Incoming inc, Current current) { int pos = System.Array.BinarySearch(all__, current.operation); @@ -177,7 +177,7 @@ namespace Ice { return IceInternal.DispatchStatus.DispatchOperationNotExist; } - + switch(pos) { case 0: @@ -197,11 +197,11 @@ namespace Ice return ice_ping___(this, inc, current); } } - + Debug.Assert(false); return IceInternal.DispatchStatus.DispatchOperationNotExist; } - + public virtual void write__(IceInternal.BasicStream os__) { os__.writeTypeId(ice_staticId()); @@ -209,7 +209,7 @@ namespace Ice os__.writeSize(0); // For compatibility with the old AFM. os__.endWriteSlice(); } - + public virtual void read__(IceInternal.BasicStream is__, bool rid__) { @@ -217,89 +217,89 @@ namespace Ice { /* string myId = */ is__.readTypeId(); } - + is__.startReadSlice(); - + // For compatibility with the old AFM. int sz = is__.readSize(); if(sz != 0) { throw new MarshalException(); } - + is__.endReadSlice(); } - public virtual void write__(OutputStream outS__) - { - outS__.writeTypeId(ice_staticId()); - outS__.startSlice(); - outS__.writeSize(0); // For compatibility with the old AFM. - outS__.endSlice(); - } - - public virtual void read__(InputStream inS__, bool rid__) - { - if(rid__) - { - /* string myId = */ inS__.readTypeId(); - } - - inS__.startSlice(); - - // For compatibility with the old AFM. - int sz = inS__.readSize(); - if(sz != 0) - { - throw new MarshalException(); - } - - inS__.endSlice(); - } - - private static string - operationModeToString(OperationMode mode) - { - if(mode == Ice.OperationMode.Normal) - { - return "::Ice::Normal"; - } - if(mode == Ice.OperationMode.Nonmutating) - { - return "::Ice::Nonmutating"; - } - - if(mode == Ice.OperationMode.Idempotent) - { - return "::Ice::Idempotent"; - } - - return "???"; - } - - protected static void - checkMode__(OperationMode expected, OperationMode received) - { - if(expected != received) - { - if(expected == OperationMode.Idempotent - && received == OperationMode.Nonmutating) - { - // - // Fine: typically an old client still using the - // deprecated nonmutating keyword - // - } - else - { - Ice.MarshalException ex = new Ice.MarshalException(); - ex.reason = "unexpected operation mode. expected = " - + operationModeToString(expected) + " received = " - + operationModeToString(received); - throw ex; - } - } - } + public virtual void write__(OutputStream outS__) + { + outS__.writeTypeId(ice_staticId()); + outS__.startSlice(); + outS__.writeSize(0); // For compatibility with the old AFM. + outS__.endSlice(); + } + + public virtual void read__(InputStream inS__, bool rid__) + { + if(rid__) + { + /* string myId = */ inS__.readTypeId(); + } + + inS__.startSlice(); + + // For compatibility with the old AFM. + int sz = inS__.readSize(); + if(sz != 0) + { + throw new MarshalException(); + } + + inS__.endSlice(); + } + + private static string + operationModeToString(OperationMode mode) + { + if(mode == Ice.OperationMode.Normal) + { + return "::Ice::Normal"; + } + if(mode == Ice.OperationMode.Nonmutating) + { + return "::Ice::Nonmutating"; + } + + if(mode == Ice.OperationMode.Idempotent) + { + return "::Ice::Idempotent"; + } + + return "???"; + } + + protected static void + checkMode__(OperationMode expected, OperationMode received) + { + if(expected != received) + { + if(expected == OperationMode.Idempotent + && received == OperationMode.Nonmutating) + { + // + // Fine: typically an old client still using the + // deprecated nonmutating keyword + // + } + else + { + Ice.MarshalException ex = new Ice.MarshalException(); + ex.reason = "unexpected operation mode. expected = " + + operationModeToString(expected) + " received = " + + operationModeToString(received); + throw ex; + } + } + } public static Ice.Current defaultCurrent = new Ice.Current(); } @@ -307,7 +307,7 @@ namespace Ice { // Returns true if ok, false if user exception. public abstract bool ice_invoke(byte[] inParams, out byte[] outParams, Current current); - + public override IceInternal.DispatchStatus dispatch__(IceInternal.Incoming inc, Current current) { byte[] inParams; @@ -333,7 +333,7 @@ namespace Ice public abstract class BlobjectAsync : Ice.ObjectImpl { public abstract void ice_invoke_async(AMD_Object_ice_invoke cb, byte[] inParams, Current current); - + public override IceInternal.DispatchStatus dispatch__(IceInternal.Incoming inc, Current current) { byte[] inParams; diff --git a/cs/src/Ice/ObjectAdapterFactory.cs b/cs/src/Ice/ObjectAdapterFactory.cs index d305d338d3d..2a4d18512f4 100755 --- a/cs/src/Ice/ObjectAdapterFactory.cs +++ b/cs/src/Ice/ObjectAdapterFactory.cs @@ -16,231 +16,231 @@ namespace IceInternal public sealed class ObjectAdapterFactory { - public void shutdown() - { - Hashtable adapters; - - lock(this) - { - // - // Ignore shutdown requests if the object adapter factory has - // already been shut down. - // - if(instance_ == null) - { - return; - } - - adapters = _adapters; - - instance_ = null; - _communicator = null; - - System.Threading.Monitor.PulseAll(this); - } - - // - // Deactivate outside the thread synchronization, to avoid - // deadlocks. - // - foreach(Ice.ObjectAdapter adapter in adapters.Values) - { - adapter.deactivate(); - } - } - - public void waitForShutdown() - { - lock(this) - { - // - // First we wait for the shutdown of the factory itself. - // - while(instance_ != null) - { - System.Threading.Monitor.Wait(this); - } - - // - // If some other thread is currently shutting down, we wait - // until this thread is finished. - // - while(_waitForShutdown) - { - System.Threading.Monitor.Wait(this); - } - _waitForShutdown = true; - } - - // - // Now we wait for deactivation of each object adapter. - // - if(_adapters != null) - { - foreach(Ice.ObjectAdapter adapter in _adapters.Values) - { - adapter.waitForDeactivate(); - } - } - - lock(this) - { - // - // Signal that waiting is complete. - // - _waitForShutdown = false; - System.Threading.Monitor.PulseAll(this); - } - } - - public bool isShutdown() - { - lock(this) - { - return instance_ == null; - } - } - - public void destroy() - { - // - // First wait for shutdown to finish. - // - waitForShutdown(); - - Hashtable adapters; - - lock(this) - { - adapters = _adapters; - - // - // We set _adapters to null because our destructor must not - // invoke methods on member objects. - // - _adapters = null; - } - - foreach(Ice.ObjectAdapter adapter in adapters.Values) - { - adapter.destroy(); - } - } - - public Ice.ObjectAdapter createObjectAdapter(string name, string endpoints, Ice.RouterPrx router) - { - lock(this) - { - if(instance_ == null) - { - throw new Ice.ObjectAdapterDeactivatedException(); - } - - Ice.ObjectAdapter adapter = (Ice.ObjectAdapter)_adapters[name]; - if(adapter != null) - { - Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); - ex.kindOfObject = "object adapter"; - ex.id = name; - throw ex; - } - - if(name.Length == 0 && (endpoints.Length != 0 || router != null)) - { - Ice.InitializationException ex = new Ice.InitializationException(); - ex.reason = "Cannot configure endpoints or router with nameless object adapter"; - throw ex; - } - - if(name.Length == 0) - { - string uuid = Ice.Util.generateUUID(); - adapter = new Ice.ObjectAdapterI(instance_, _communicator, this, uuid, "", null, true); - _adapters[uuid] = adapter; - } - else - { - adapter = new Ice.ObjectAdapterI(instance_, _communicator, this, name, endpoints, router, false); - _adapters[name] = adapter; - } - return adapter; - } - } - - public Ice.ObjectAdapter findObjectAdapter(Ice.ObjectPrx proxy) - { - lock(this) - { - if(instance_ == null) - { - return null; - } - - IEnumerator i = _adapters.Values.GetEnumerator(); - while(i.MoveNext()) - { - Ice.ObjectAdapterI adapter = (Ice.ObjectAdapterI)i.Current; - try - { - if(adapter.isLocal(proxy)) - { - return adapter; - } - } - catch(Ice.ObjectAdapterDeactivatedException) - { - // Ignore. - } - } - - return null; - } - } - - public void removeObjectAdapter(string name) - { - lock(this) - { - if(_waitForShutdown || _adapters == null) - { - return; - } - - _adapters.Remove(name); - } - } - - public void flushBatchRequests() - { - LinkedList a = new LinkedList(); - lock(this) - { - foreach(Ice.ObjectAdapterI adapter in _adapters.Values) - { - a.Add(adapter); - } - } - foreach(Ice.ObjectAdapterI adapter in a) - { - adapter.flushBatchRequests(); - } - } - - // - // Only for use by Instance. - // - internal ObjectAdapterFactory(Instance instance, Ice.Communicator communicator) - { - instance_ = instance; - _communicator = communicator; - _adapters = new Hashtable(); - _waitForShutdown = false; - } - - private Instance instance_; - private Ice.Communicator _communicator; - private Hashtable _adapters; - private bool _waitForShutdown; + public void shutdown() + { + Hashtable adapters; + + lock(this) + { + // + // Ignore shutdown requests if the object adapter factory has + // already been shut down. + // + if(instance_ == null) + { + return; + } + + adapters = _adapters; + + instance_ = null; + _communicator = null; + + System.Threading.Monitor.PulseAll(this); + } + + // + // Deactivate outside the thread synchronization, to avoid + // deadlocks. + // + foreach(Ice.ObjectAdapter adapter in adapters.Values) + { + adapter.deactivate(); + } + } + + public void waitForShutdown() + { + lock(this) + { + // + // First we wait for the shutdown of the factory itself. + // + while(instance_ != null) + { + System.Threading.Monitor.Wait(this); + } + + // + // If some other thread is currently shutting down, we wait + // until this thread is finished. + // + while(_waitForShutdown) + { + System.Threading.Monitor.Wait(this); + } + _waitForShutdown = true; + } + + // + // Now we wait for deactivation of each object adapter. + // + if(_adapters != null) + { + foreach(Ice.ObjectAdapter adapter in _adapters.Values) + { + adapter.waitForDeactivate(); + } + } + + lock(this) + { + // + // Signal that waiting is complete. + // + _waitForShutdown = false; + System.Threading.Monitor.PulseAll(this); + } + } + + public bool isShutdown() + { + lock(this) + { + return instance_ == null; + } + } + + public void destroy() + { + // + // First wait for shutdown to finish. + // + waitForShutdown(); + + Hashtable adapters; + + lock(this) + { + adapters = _adapters; + + // + // We set _adapters to null because our destructor must not + // invoke methods on member objects. + // + _adapters = null; + } + + foreach(Ice.ObjectAdapter adapter in adapters.Values) + { + adapter.destroy(); + } + } + + public Ice.ObjectAdapter createObjectAdapter(string name, string endpoints, Ice.RouterPrx router) + { + lock(this) + { + if(instance_ == null) + { + throw new Ice.ObjectAdapterDeactivatedException(); + } + + Ice.ObjectAdapter adapter = (Ice.ObjectAdapter)_adapters[name]; + if(adapter != null) + { + Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); + ex.kindOfObject = "object adapter"; + ex.id = name; + throw ex; + } + + if(name.Length == 0 && (endpoints.Length != 0 || router != null)) + { + Ice.InitializationException ex = new Ice.InitializationException(); + ex.reason = "Cannot configure endpoints or router with nameless object adapter"; + throw ex; + } + + if(name.Length == 0) + { + string uuid = Ice.Util.generateUUID(); + adapter = new Ice.ObjectAdapterI(instance_, _communicator, this, uuid, "", null, true); + _adapters[uuid] = adapter; + } + else + { + adapter = new Ice.ObjectAdapterI(instance_, _communicator, this, name, endpoints, router, false); + _adapters[name] = adapter; + } + return adapter; + } + } + + public Ice.ObjectAdapter findObjectAdapter(Ice.ObjectPrx proxy) + { + lock(this) + { + if(instance_ == null) + { + return null; + } + + IEnumerator i = _adapters.Values.GetEnumerator(); + while(i.MoveNext()) + { + Ice.ObjectAdapterI adapter = (Ice.ObjectAdapterI)i.Current; + try + { + if(adapter.isLocal(proxy)) + { + return adapter; + } + } + catch(Ice.ObjectAdapterDeactivatedException) + { + // Ignore. + } + } + + return null; + } + } + + public void removeObjectAdapter(string name) + { + lock(this) + { + if(_waitForShutdown || _adapters == null) + { + return; + } + + _adapters.Remove(name); + } + } + + public void flushBatchRequests() + { + LinkedList a = new LinkedList(); + lock(this) + { + foreach(Ice.ObjectAdapterI adapter in _adapters.Values) + { + a.Add(adapter); + } + } + foreach(Ice.ObjectAdapterI adapter in a) + { + adapter.flushBatchRequests(); + } + } + + // + // Only for use by Instance. + // + internal ObjectAdapterFactory(Instance instance, Ice.Communicator communicator) + { + instance_ = instance; + _communicator = communicator; + _adapters = new Hashtable(); + _waitForShutdown = false; + } + + private Instance instance_; + private Ice.Communicator _communicator; + private Hashtable _adapters; + private bool _waitForShutdown; } } diff --git a/cs/src/Ice/ObjectAdapterI.cs b/cs/src/Ice/ObjectAdapterI.cs index cb7d25c71dc..11e461c1162 100755 --- a/cs/src/Ice/ObjectAdapterI.cs +++ b/cs/src/Ice/ObjectAdapterI.cs @@ -15,711 +15,711 @@ namespace Ice public sealed class ObjectAdapterI : LocalObjectImpl, ObjectAdapter { - public string getName() - { - // - // No mutex lock necessary, _name is immutable. - // - return _noConfig ? "" : _name; - } - - public Communicator getCommunicator() - { - lock(this) - { - checkForDeactivation(); - - return _communicator; - } - } - - public void activate() - { - IceInternal.LocatorInfo locatorInfo = null; - bool registerProcess = false; - bool printAdapterReady = false; - - lock(this) - { - checkForDeactivation(); - - // - // If the one off initializations of the adapter are already - // done, we just need to activate the incoming connection - // factories and we're done. - // - if(_activateOneOffDone) - { - foreach(IceInternal.IncomingConnectionFactory icf in _incomingConnectionFactories) - { - icf.activate(); - } - return; - } - - // - // One off initializations of the adapter: update the locator - // registry and print the "adapter ready" message. We set the - // _waitForActivate flag to prevent deactivation from other - // threads while these one off initializations are done. - // - _waitForActivate = true; - - locatorInfo = _locatorInfo; - if(!_noConfig) - { - Properties properties = instance_.initializationData().properties; - // - // DEPRECATED PROPERTY: Remove extra code in future release. - // - registerProcess = properties.getPropertyAsIntWithDefault( - _propertyPrefix + _name + ".RegisterProcess", - properties.getPropertyAsInt(_name + ".RegisterProcess")) > 0; - printAdapterReady = properties.getPropertyAsInt("Ice.PrintAdapterReady") > 0; - } - } - - try - { - Ice.Identity dummy = new Ice.Identity(); - dummy.name = "dummy"; - updateLocatorRegistry(locatorInfo, createDirectProxy(dummy), registerProcess); - } - catch(Ice.LocalException ex) - { - // - // If we couldn't update the locator registry, we let the - // exception go through and don't activate the adapter to - // allow to user code to retry activating the adapter - // later. - // - lock(this) - { - _waitForActivate = false; - System.Threading.Monitor.PulseAll(this); - } - throw ex; - } - - if(printAdapterReady) - { - System.Console.Out.WriteLine(_name + " ready"); - } - - lock(this) - { - Debug.Assert(!_deactivated); // Not possible if _waitForActivate = true; - - // - // Signal threads waiting for the activation. - // - _waitForActivate = false; - System.Threading.Monitor.PulseAll(this); - - _activateOneOffDone = true; - - foreach(IceInternal.IncomingConnectionFactory icf in _incomingConnectionFactories) - { - icf.activate(); - } - } - } - - public void hold() - { - lock(this) - { - checkForDeactivation(); - - int sz = _incomingConnectionFactories.Count; - for(int i = 0; i < sz; ++i) - { - IceInternal.IncomingConnectionFactory factory = - (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[i]; - factory.hold(); - } - } - } - - public void waitForHold() - { - lock(this) - { - checkForDeactivation(); - - int sz = _incomingConnectionFactories.Count; - for(int i = 0; i < sz; ++i) - { - IceInternal.IncomingConnectionFactory factory = - (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[i]; - factory.waitUntilHolding(); - } - } - } - - public void deactivate() - { - IceInternal.OutgoingConnectionFactory outgoingConnectionFactory; - ArrayList incomingConnectionFactories; - IceInternal.LocatorInfo locatorInfo; - - lock(this) - { - // - // Ignore deactivation requests if the object adapter has - // already been deactivated. - // - if(_deactivated) - { - return; - } - - // - // - // Wait for activation to complete. This is necessary to not - // get out of order locator updates. - // - while(_waitForActivate) - { - System.Threading.Monitor.Wait(this); - } - - if(_routerInfo != null) - { - // - // Remove entry from the router manager. - // - instance_.routerManager().erase(_routerInfo.getRouter()); - - // - // Clear this object adapter with the router. - // - _routerInfo.setAdapter(null); - } - - incomingConnectionFactories = new ArrayList(_incomingConnectionFactories); - outgoingConnectionFactory = instance_.outgoingConnectionFactory(); - locatorInfo = _locatorInfo; - - _deactivated = true; - - System.Threading.Monitor.PulseAll(this); - } - - try - { - updateLocatorRegistry(locatorInfo, null, false); - } - catch(Ice.LocalException) - { - // - // We can't throw exceptions in deactivate so we ignore - // failures to update the locator registry. - // - } - - // - // Must be called outside the thread synchronization, because - // Connection::destroy() might block when sending a CloseConnection - // message. - // - int sz = incomingConnectionFactories.Count; - for(int i = 0; i < sz; ++i) - { - IceInternal.IncomingConnectionFactory factory = - (IceInternal.IncomingConnectionFactory)incomingConnectionFactories[i]; - factory.destroy(); - } - - // - // Must be called outside the thread synchronization, because - // changing the object adapter might block if there are still - // requests being dispatched. - // - outgoingConnectionFactory.removeAdapter(this); - } - - public void waitForDeactivate() - { - IceInternal.IncomingConnectionFactory[] incomingConnectionFactories = null; - lock(this) - { - if(_destroyed) - { - return; - } - - // - // Wait for deactivation of the adapter itself, and - // for the return of all direct method calls using this - // adapter. - // - while(!_deactivated || _directCount > 0) - { - System.Threading.Monitor.Wait(this); - } - - incomingConnectionFactories = - (IceInternal.IncomingConnectionFactory[])_incomingConnectionFactories.ToArray( - typeof(IceInternal.IncomingConnectionFactory)); - } - - // - // Now we wait for until all incoming connection factories are - // finished. - // - for(int i = 0; i < incomingConnectionFactories.Length; ++i) - { - incomingConnectionFactories[i].waitUntilFinished(); - } - } - - public bool isDeactivated() - { - lock(this) - { - return _deactivated; - } - } - - public void destroy() - { - lock(this) - { - // - // Another thread is in the process of destroying the object - // adapter. Wait for it to finish. - // - while(_destroying) - { - System.Threading.Monitor.Wait(this); - } - - // - // Object adpater is already destroyed. - // - if(_destroyed) - { - return; - } - - _destroying = true; - } - - // - // Deactivate and wait for completion. - // - deactivate(); - waitForDeactivate(); - - // - // Now it's also time to clean up our servants and servant - // locators. - // - _servantManager.destroy(); - - // - // Destroy the thread pool. - // - if(_threadPool != null) - { - _threadPool.destroy(); - _threadPool.joinWithAllThreads(); - } - - IceInternal.ObjectAdapterFactory objectAdapterFactory; - - lock(this) - { - // - // Signal that destroying is complete. - // - _destroying = false; - _destroyed = true; - System.Threading.Monitor.PulseAll(this); - - // - // We're done, now we can throw away all incoming connection - // factories. - // - // We set _incomingConnectionFactories to null because the finalizer - // must not invoke methods on objects. - // - _incomingConnectionFactories = null; - - // - // Remove object references (some of them cyclic). - // - instance_ = null; - _threadPool = null; - _communicator = null; - _incomingConnectionFactories = null; - _routerEndpoints = null; - _routerInfo = null; - _publishedEndpoints = null; - _locatorInfo = null; - - objectAdapterFactory = _objectAdapterFactory; - _objectAdapterFactory = null; - } - - if(objectAdapterFactory != null) - { - objectAdapterFactory.removeObjectAdapter(_name); - } - } - - public ObjectPrx add(Ice.Object obj, Identity ident) - { - return addFacet(obj, ident, ""); - } - - public ObjectPrx addFacet(Ice.Object obj, Identity ident, string facet) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - // - // Create a copy of the Identity argument, in case the caller - // reuses it. - // - Identity id = new Identity(); - id.category = ident.category; - id.name = ident.name; - - _servantManager.addServant(obj, id, facet); - - return newProxy(id, facet); - } - } - - public ObjectPrx addWithUUID(Ice.Object obj) - { - return addFacetWithUUID(obj, ""); - } - - public ObjectPrx addFacetWithUUID(Ice.Object obj, string facet) - { - Identity ident = new Identity(); - ident.category = ""; - ident.name = Util.generateUUID(); - - return addFacet(obj, ident, facet); - } - - public Ice.Object remove(Identity ident) - { - return removeFacet(ident, ""); - } - - public Ice.Object removeFacet(Identity ident, string facet) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - return _servantManager.removeServant(ident, facet); - } - } - - public FacetMap removeAllFacets(Identity ident) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - return _servantManager.removeAllFacets(ident); - } - } - - public Ice.Object find(Identity ident) - { - return findFacet(ident, ""); - } - - public Ice.Object findFacet(Identity ident, string facet) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - return _servantManager.findServant(ident, facet); - } - } - - public FacetMap findAllFacets(Identity ident) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - return _servantManager.findAllFacets(ident); - } - } - - public Ice.Object findByProxy(ObjectPrx proxy) - { - lock(this) - { - checkForDeactivation(); - - IceInternal.Reference @ref = ((ObjectPrxHelperBase)proxy).reference__(); - return findFacet(@ref.getIdentity(), @ref.getFacet()); - } - } - - public void addServantLocator(ServantLocator locator, string prefix) - { - lock(this) - { - checkForDeactivation(); - - _servantManager.addServantLocator(locator, prefix); - } - } - - public ServantLocator findServantLocator(string prefix) - { - lock(this) - { - checkForDeactivation(); - - return _servantManager.findServantLocator(prefix); - } - } - - public ObjectPrx createProxy(Identity ident) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - return newProxy(ident, ""); - } - } - - public ObjectPrx createDirectProxy(Identity ident) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - return newDirectProxy(ident, ""); - } - } - - public ObjectPrx createIndirectProxy(Identity ident) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - return newIndirectProxy(ident, "", _id); - } - } - - public ObjectPrx createReverseProxy(Identity ident) - { - lock(this) - { - checkForDeactivation(); - checkIdentity(ident); - - // - // Get all incoming connections for this object adapter. - // - ArrayList connections = new ArrayList(); - int sz = _incomingConnectionFactories.Count; - for(int i = 0; i < sz; ++i) - { - IceInternal.IncomingConnectionFactory factory - = (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[i]; - ConnectionI[] cons = factory.connections(); - for(int j = 0; j < cons.Length; j++) - { - connections.Add(cons[j]); - } - } - - // - // Create a reference and return a reverse proxy for this - // reference. - // - ConnectionI[] arr = new ConnectionI[connections.Count]; - if(arr.Length != 0) - { - connections.CopyTo(arr, 0); - } + public string getName() + { + // + // No mutex lock necessary, _name is immutable. + // + return _noConfig ? "" : _name; + } + + public Communicator getCommunicator() + { + lock(this) + { + checkForDeactivation(); + + return _communicator; + } + } + + public void activate() + { + IceInternal.LocatorInfo locatorInfo = null; + bool registerProcess = false; + bool printAdapterReady = false; + + lock(this) + { + checkForDeactivation(); + + // + // If the one off initializations of the adapter are already + // done, we just need to activate the incoming connection + // factories and we're done. + // + if(_activateOneOffDone) + { + foreach(IceInternal.IncomingConnectionFactory icf in _incomingConnectionFactories) + { + icf.activate(); + } + return; + } + + // + // One off initializations of the adapter: update the locator + // registry and print the "adapter ready" message. We set the + // _waitForActivate flag to prevent deactivation from other + // threads while these one off initializations are done. + // + _waitForActivate = true; + + locatorInfo = _locatorInfo; + if(!_noConfig) + { + Properties properties = instance_.initializationData().properties; + // + // DEPRECATED PROPERTY: Remove extra code in future release. + // + registerProcess = properties.getPropertyAsIntWithDefault( + _propertyPrefix + _name + ".RegisterProcess", + properties.getPropertyAsInt(_name + ".RegisterProcess")) > 0; + printAdapterReady = properties.getPropertyAsInt("Ice.PrintAdapterReady") > 0; + } + } + + try + { + Ice.Identity dummy = new Ice.Identity(); + dummy.name = "dummy"; + updateLocatorRegistry(locatorInfo, createDirectProxy(dummy), registerProcess); + } + catch(Ice.LocalException ex) + { + // + // If we couldn't update the locator registry, we let the + // exception go through and don't activate the adapter to + // allow to user code to retry activating the adapter + // later. + // + lock(this) + { + _waitForActivate = false; + System.Threading.Monitor.PulseAll(this); + } + throw ex; + } + + if(printAdapterReady) + { + System.Console.Out.WriteLine(_name + " ready"); + } + + lock(this) + { + Debug.Assert(!_deactivated); // Not possible if _waitForActivate = true; + + // + // Signal threads waiting for the activation. + // + _waitForActivate = false; + System.Threading.Monitor.PulseAll(this); + + _activateOneOffDone = true; + + foreach(IceInternal.IncomingConnectionFactory icf in _incomingConnectionFactories) + { + icf.activate(); + } + } + } + + public void hold() + { + lock(this) + { + checkForDeactivation(); + + int sz = _incomingConnectionFactories.Count; + for(int i = 0; i < sz; ++i) + { + IceInternal.IncomingConnectionFactory factory = + (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[i]; + factory.hold(); + } + } + } + + public void waitForHold() + { + lock(this) + { + checkForDeactivation(); + + int sz = _incomingConnectionFactories.Count; + for(int i = 0; i < sz; ++i) + { + IceInternal.IncomingConnectionFactory factory = + (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[i]; + factory.waitUntilHolding(); + } + } + } + + public void deactivate() + { + IceInternal.OutgoingConnectionFactory outgoingConnectionFactory; + ArrayList incomingConnectionFactories; + IceInternal.LocatorInfo locatorInfo; + + lock(this) + { + // + // Ignore deactivation requests if the object adapter has + // already been deactivated. + // + if(_deactivated) + { + return; + } + + // + // + // Wait for activation to complete. This is necessary to not + // get out of order locator updates. + // + while(_waitForActivate) + { + System.Threading.Monitor.Wait(this); + } + + if(_routerInfo != null) + { + // + // Remove entry from the router manager. + // + instance_.routerManager().erase(_routerInfo.getRouter()); + + // + // Clear this object adapter with the router. + // + _routerInfo.setAdapter(null); + } + + incomingConnectionFactories = new ArrayList(_incomingConnectionFactories); + outgoingConnectionFactory = instance_.outgoingConnectionFactory(); + locatorInfo = _locatorInfo; + + _deactivated = true; + + System.Threading.Monitor.PulseAll(this); + } + + try + { + updateLocatorRegistry(locatorInfo, null, false); + } + catch(Ice.LocalException) + { + // + // We can't throw exceptions in deactivate so we ignore + // failures to update the locator registry. + // + } + + // + // Must be called outside the thread synchronization, because + // Connection::destroy() might block when sending a CloseConnection + // message. + // + int sz = incomingConnectionFactories.Count; + for(int i = 0; i < sz; ++i) + { + IceInternal.IncomingConnectionFactory factory = + (IceInternal.IncomingConnectionFactory)incomingConnectionFactories[i]; + factory.destroy(); + } + + // + // Must be called outside the thread synchronization, because + // changing the object adapter might block if there are still + // requests being dispatched. + // + outgoingConnectionFactory.removeAdapter(this); + } + + public void waitForDeactivate() + { + IceInternal.IncomingConnectionFactory[] incomingConnectionFactories = null; + lock(this) + { + if(_destroyed) + { + return; + } + + // + // Wait for deactivation of the adapter itself, and + // for the return of all direct method calls using this + // adapter. + // + while(!_deactivated || _directCount > 0) + { + System.Threading.Monitor.Wait(this); + } + + incomingConnectionFactories = + (IceInternal.IncomingConnectionFactory[])_incomingConnectionFactories.ToArray( + typeof(IceInternal.IncomingConnectionFactory)); + } + + // + // Now we wait for until all incoming connection factories are + // finished. + // + for(int i = 0; i < incomingConnectionFactories.Length; ++i) + { + incomingConnectionFactories[i].waitUntilFinished(); + } + } + + public bool isDeactivated() + { + lock(this) + { + return _deactivated; + } + } + + public void destroy() + { + lock(this) + { + // + // Another thread is in the process of destroying the object + // adapter. Wait for it to finish. + // + while(_destroying) + { + System.Threading.Monitor.Wait(this); + } + + // + // Object adpater is already destroyed. + // + if(_destroyed) + { + return; + } + + _destroying = true; + } + + // + // Deactivate and wait for completion. + // + deactivate(); + waitForDeactivate(); + + // + // Now it's also time to clean up our servants and servant + // locators. + // + _servantManager.destroy(); + + // + // Destroy the thread pool. + // + if(_threadPool != null) + { + _threadPool.destroy(); + _threadPool.joinWithAllThreads(); + } + + IceInternal.ObjectAdapterFactory objectAdapterFactory; + + lock(this) + { + // + // Signal that destroying is complete. + // + _destroying = false; + _destroyed = true; + System.Threading.Monitor.PulseAll(this); + + // + // We're done, now we can throw away all incoming connection + // factories. + // + // We set _incomingConnectionFactories to null because the finalizer + // must not invoke methods on objects. + // + _incomingConnectionFactories = null; + + // + // Remove object references (some of them cyclic). + // + instance_ = null; + _threadPool = null; + _communicator = null; + _incomingConnectionFactories = null; + _routerEndpoints = null; + _routerInfo = null; + _publishedEndpoints = null; + _locatorInfo = null; + + objectAdapterFactory = _objectAdapterFactory; + _objectAdapterFactory = null; + } + + if(objectAdapterFactory != null) + { + objectAdapterFactory.removeObjectAdapter(_name); + } + } + + public ObjectPrx add(Ice.Object obj, Identity ident) + { + return addFacet(obj, ident, ""); + } + + public ObjectPrx addFacet(Ice.Object obj, Identity ident, string facet) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + // + // Create a copy of the Identity argument, in case the caller + // reuses it. + // + Identity id = new Identity(); + id.category = ident.category; + id.name = ident.name; + + _servantManager.addServant(obj, id, facet); + + return newProxy(id, facet); + } + } + + public ObjectPrx addWithUUID(Ice.Object obj) + { + return addFacetWithUUID(obj, ""); + } + + public ObjectPrx addFacetWithUUID(Ice.Object obj, string facet) + { + Identity ident = new Identity(); + ident.category = ""; + ident.name = Util.generateUUID(); + + return addFacet(obj, ident, facet); + } + + public Ice.Object remove(Identity ident) + { + return removeFacet(ident, ""); + } + + public Ice.Object removeFacet(Identity ident, string facet) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + return _servantManager.removeServant(ident, facet); + } + } + + public FacetMap removeAllFacets(Identity ident) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + return _servantManager.removeAllFacets(ident); + } + } + + public Ice.Object find(Identity ident) + { + return findFacet(ident, ""); + } + + public Ice.Object findFacet(Identity ident, string facet) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + return _servantManager.findServant(ident, facet); + } + } + + public FacetMap findAllFacets(Identity ident) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + return _servantManager.findAllFacets(ident); + } + } + + public Ice.Object findByProxy(ObjectPrx proxy) + { + lock(this) + { + checkForDeactivation(); + + IceInternal.Reference @ref = ((ObjectPrxHelperBase)proxy).reference__(); + return findFacet(@ref.getIdentity(), @ref.getFacet()); + } + } + + public void addServantLocator(ServantLocator locator, string prefix) + { + lock(this) + { + checkForDeactivation(); + + _servantManager.addServantLocator(locator, prefix); + } + } + + public ServantLocator findServantLocator(string prefix) + { + lock(this) + { + checkForDeactivation(); + + return _servantManager.findServantLocator(prefix); + } + } + + public ObjectPrx createProxy(Identity ident) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + return newProxy(ident, ""); + } + } + + public ObjectPrx createDirectProxy(Identity ident) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + return newDirectProxy(ident, ""); + } + } + + public ObjectPrx createIndirectProxy(Identity ident) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + return newIndirectProxy(ident, "", _id); + } + } + + public ObjectPrx createReverseProxy(Identity ident) + { + lock(this) + { + checkForDeactivation(); + checkIdentity(ident); + + // + // Get all incoming connections for this object adapter. + // + ArrayList connections = new ArrayList(); + int sz = _incomingConnectionFactories.Count; + for(int i = 0; i < sz; ++i) + { + IceInternal.IncomingConnectionFactory factory + = (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[i]; + ConnectionI[] cons = factory.connections(); + for(int j = 0; j < cons.Length; j++) + { + connections.Add(cons[j]); + } + } + + // + // Create a reference and return a reverse proxy for this + // reference. + // + ConnectionI[] arr = new ConnectionI[connections.Count]; + if(arr.Length != 0) + { + connections.CopyTo(arr, 0); + } IceInternal.Reference @ref = instance_.referenceFactory().create( - ident, instance_.getDefaultContext(), "", IceInternal.Reference.Mode.ModeTwoway, - arr); - return instance_.proxyFactory().referenceToProxy(@ref); - } - } - - public void setLocator(LocatorPrx locator) - { - lock(this) - { - checkForDeactivation(); - - _locatorInfo = instance_.locatorManager().get(locator); - } - } - - public bool isLocal(ObjectPrx proxy) - { - IceInternal.Reference r = ((ObjectPrxHelperBase)proxy).reference__(); - IceInternal.EndpointI[] endpoints; - - try - { - IceInternal.IndirectReference ir = (IceInternal.IndirectReference)r; - if(ir.getAdapterId().Length != 0) - { - // - // Proxy is local if the reference adapter id matches this - // adapter name. - // - return ir.getAdapterId().Equals(_id); - } - IceInternal.LocatorInfo info = ir.getLocatorInfo(); - if(info != null) - { - bool isCached; - endpoints = info.getEndpoints(ir, ir.getLocatorCacheTimeout(), out isCached); - } - else - { - return false; - } - } - catch(InvalidCastException) - { - endpoints = r.getEndpoints(); - } - - lock(this) - { - checkForDeactivation(); - - // - // Proxies which have at least one endpoint in common with the - // endpoints used by this object adapter's incoming connection - // factories are considered local. - // - for(int i = 0; i < endpoints.Length; ++i) - { - int sz = _incomingConnectionFactories.Count; - for(int j = 0; j < sz; j++) - { - IceInternal.IncomingConnectionFactory factory - = (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[j]; - if(factory.equivalent(endpoints[i])) - { - return true; - } - } - } - - // - // Proxies which have at least one endpoint in common with the - // router's server proxy endpoints (if any), are also considered - // local. - // - if(_routerInfo != null && _routerInfo.getRouter().Equals(proxy.ice_getRouter())) - { - for(int i = 0; i < endpoints.Length; ++i) - { - if(_routerEndpoints.BinarySearch(endpoints[i]) >= 0) // _routerEndpoints is sorted. - { - return true; - } - } - } - - return false; - } - } - - public void flushBatchRequests() - { - ArrayList f; - lock(this) - { - f = new ArrayList(_incomingConnectionFactories); - } - - foreach(IceInternal.IncomingConnectionFactory factory in f) - { - factory.flushBatchRequests(); - } - } - - public void incDirectCount() - { - lock(this) - { - checkForDeactivation(); - - Debug.Assert(_directCount >= 0); - ++_directCount; - } - } - - public void decDirectCount() - { - lock(this) - { - // Not check for deactivation here! - - Debug.Assert(instance_ != null); // Must not be called after destroy(). - - Debug.Assert(_directCount > 0); - if(--_directCount == 0) - { - System.Threading.Monitor.PulseAll(this); - } - } - } - - public IceInternal.ThreadPool getThreadPool() - { - // No mutex lock necessary, _threadPool and instance_ are - // immutable after creation until they are removed in - // destroy(). - - // Not check for deactivation here! - - Debug.Assert(instance_ != null); // Must not be called after destroy(). - - if(_threadPool != null) - { - return _threadPool; - } - else - { - return instance_.serverThreadPool(); - } - - } - - public IceInternal.ServantManager getServantManager() - { - // - // No mutex lock necessary, _servantManager is immutable. - // - return _servantManager; - } + ident, instance_.getDefaultContext(), "", IceInternal.Reference.Mode.ModeTwoway, + arr); + return instance_.proxyFactory().referenceToProxy(@ref); + } + } + + public void setLocator(LocatorPrx locator) + { + lock(this) + { + checkForDeactivation(); + + _locatorInfo = instance_.locatorManager().get(locator); + } + } + + public bool isLocal(ObjectPrx proxy) + { + IceInternal.Reference r = ((ObjectPrxHelperBase)proxy).reference__(); + IceInternal.EndpointI[] endpoints; + + try + { + IceInternal.IndirectReference ir = (IceInternal.IndirectReference)r; + if(ir.getAdapterId().Length != 0) + { + // + // Proxy is local if the reference adapter id matches this + // adapter name. + // + return ir.getAdapterId().Equals(_id); + } + IceInternal.LocatorInfo info = ir.getLocatorInfo(); + if(info != null) + { + bool isCached; + endpoints = info.getEndpoints(ir, ir.getLocatorCacheTimeout(), out isCached); + } + else + { + return false; + } + } + catch(InvalidCastException) + { + endpoints = r.getEndpoints(); + } + + lock(this) + { + checkForDeactivation(); + + // + // Proxies which have at least one endpoint in common with the + // endpoints used by this object adapter's incoming connection + // factories are considered local. + // + for(int i = 0; i < endpoints.Length; ++i) + { + int sz = _incomingConnectionFactories.Count; + for(int j = 0; j < sz; j++) + { + IceInternal.IncomingConnectionFactory factory + = (IceInternal.IncomingConnectionFactory)_incomingConnectionFactories[j]; + if(factory.equivalent(endpoints[i])) + { + return true; + } + } + } + + // + // Proxies which have at least one endpoint in common with the + // router's server proxy endpoints (if any), are also considered + // local. + // + if(_routerInfo != null && _routerInfo.getRouter().Equals(proxy.ice_getRouter())) + { + for(int i = 0; i < endpoints.Length; ++i) + { + if(_routerEndpoints.BinarySearch(endpoints[i]) >= 0) // _routerEndpoints is sorted. + { + return true; + } + } + } + + return false; + } + } + + public void flushBatchRequests() + { + ArrayList f; + lock(this) + { + f = new ArrayList(_incomingConnectionFactories); + } + + foreach(IceInternal.IncomingConnectionFactory factory in f) + { + factory.flushBatchRequests(); + } + } + + public void incDirectCount() + { + lock(this) + { + checkForDeactivation(); + + Debug.Assert(_directCount >= 0); + ++_directCount; + } + } + + public void decDirectCount() + { + lock(this) + { + // Not check for deactivation here! + + Debug.Assert(instance_ != null); // Must not be called after destroy(). + + Debug.Assert(_directCount > 0); + if(--_directCount == 0) + { + System.Threading.Monitor.PulseAll(this); + } + } + } + + public IceInternal.ThreadPool getThreadPool() + { + // No mutex lock necessary, _threadPool and instance_ are + // immutable after creation until they are removed in + // destroy(). + + // Not check for deactivation here! + + Debug.Assert(instance_ != null); // Must not be called after destroy(). + + if(_threadPool != null) + { + return _threadPool; + } + else + { + return instance_.serverThreadPool(); + } + + } + + public IceInternal.ServantManager getServantManager() + { + // + // No mutex lock necessary, _servantManager is immutable. + // + return _servantManager; + } public bool getThreadPerConnection() { @@ -729,78 +729,78 @@ namespace Ice return _threadPerConnection; } - // - // Only for use by IceInternal.ObjectAdapterFactory - // - public ObjectAdapterI(IceInternal.Instance instance, Communicator communicator, - IceInternal.ObjectAdapterFactory objectAdapterFactory, string name, - string endpointInfo, RouterPrx router, bool noConfig) - { - _deactivated = false; - instance_ = instance; - _communicator = communicator; - _objectAdapterFactory = objectAdapterFactory; - _servantManager = new IceInternal.ServantManager(instance, name); - _activateOneOffDone = false; - _name = name; - _incomingConnectionFactories = new ArrayList(); - _publishedEndpoints = new ArrayList(); - _routerEndpoints = new ArrayList(); - _routerInfo = null; - _directCount = 0; - _waitForActivate = false; - _noConfig = noConfig; - - if(_noConfig) - { - return; - } - - // - // DEPRECATED PROPERTIES: Remove extra code in future release. - // - - // - // Make sure named adapter has configuration. - // - Properties properties = instance_.initializationData().properties; - string[] oldProps = filterProperties(_name + "."); - if(endpointInfo.Length == 0 && router == null) - { - string[] props = filterProperties(_propertyPrefix + _name + "."); - if(props.Length == 0 && oldProps.Length == 0) - { - // - // These need to be set to prevent warnings/asserts in the destructor. - // - _deactivated = true; - instance_ = null; - _communicator = null; - _incomingConnectionFactories = null; - - InitializationException ex = new InitializationException(); - ex.reason = "object adapter \"" + _name + "\" requires configuration."; - throw ex; - } - } - - if(oldProps.Length != 0) - { - string message = "The following properties have been deprecated, please prepend \"Ice.OA.\":"; - for(int i = 0; i < oldProps.Length; ++i) - { - message += "\n " + oldProps[i]; - } - instance_.initializationData().logger.warning(message); - } - - _id = properties.getPropertyWithDefault(_propertyPrefix + _name + ".AdapterId", - properties.getProperty(_name + ".AdapterId")); - _replicaGroupId = properties.getPropertyWithDefault(_propertyPrefix + _name + ".ReplicaGroupId", - properties.getProperty(_name + ".ReplicaGroupId")); - - try - { + // + // Only for use by IceInternal.ObjectAdapterFactory + // + public ObjectAdapterI(IceInternal.Instance instance, Communicator communicator, + IceInternal.ObjectAdapterFactory objectAdapterFactory, string name, + string endpointInfo, RouterPrx router, bool noConfig) + { + _deactivated = false; + instance_ = instance; + _communicator = communicator; + _objectAdapterFactory = objectAdapterFactory; + _servantManager = new IceInternal.ServantManager(instance, name); + _activateOneOffDone = false; + _name = name; + _incomingConnectionFactories = new ArrayList(); + _publishedEndpoints = new ArrayList(); + _routerEndpoints = new ArrayList(); + _routerInfo = null; + _directCount = 0; + _waitForActivate = false; + _noConfig = noConfig; + + if(_noConfig) + { + return; + } + + // + // DEPRECATED PROPERTIES: Remove extra code in future release. + // + + // + // Make sure named adapter has configuration. + // + Properties properties = instance_.initializationData().properties; + string[] oldProps = filterProperties(_name + "."); + if(endpointInfo.Length == 0 && router == null) + { + string[] props = filterProperties(_propertyPrefix + _name + "."); + if(props.Length == 0 && oldProps.Length == 0) + { + // + // These need to be set to prevent warnings/asserts in the destructor. + // + _deactivated = true; + instance_ = null; + _communicator = null; + _incomingConnectionFactories = null; + + InitializationException ex = new InitializationException(); + ex.reason = "object adapter \"" + _name + "\" requires configuration."; + throw ex; + } + } + + if(oldProps.Length != 0) + { + string message = "The following properties have been deprecated, please prepend \"Ice.OA.\":"; + for(int i = 0; i < oldProps.Length; ++i) + { + message += "\n " + oldProps[i]; + } + instance_.initializationData().logger.warning(message); + } + + _id = properties.getPropertyWithDefault(_propertyPrefix + _name + ".AdapterId", + properties.getProperty(_name + ".AdapterId")); + _replicaGroupId = properties.getPropertyWithDefault(_propertyPrefix + _name + ".ReplicaGroupId", + properties.getProperty(_name + ".ReplicaGroupId")); + + try + { _threadPerConnection = properties.getPropertyAsInt(_propertyPrefix + _name + ".ThreadPerConnection") > 0; @@ -841,96 +841,96 @@ namespace Ice } } - if(router == null) - { - router = RouterPrxHelper.uncheckedCast( - instance_.proxyFactory().propertyToProxy(_propertyPrefix + _name + ".Router")); - if(router == null) - { - router = RouterPrxHelper.uncheckedCast( - instance_.proxyFactory().propertyToProxy(_name + ".Router")); - } - } - if(router != null) - { - _routerInfo = instance_.routerManager().get(router); - if(_routerInfo != null) - { + if(router == null) + { + router = RouterPrxHelper.uncheckedCast( + instance_.proxyFactory().propertyToProxy(_propertyPrefix + _name + ".Router")); + if(router == null) + { + router = RouterPrxHelper.uncheckedCast( + instance_.proxyFactory().propertyToProxy(_name + ".Router")); + } + } + if(router != null) + { + _routerInfo = instance_.routerManager().get(router); + if(_routerInfo != null) + { // // Make sure this router is not already registered with another adapter. // if(_routerInfo.getAdapter() != null) { - Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); - ex.kindOfObject = "object adapter with router"; - ex.id = instance_.identityToString(router.ice_getIdentity()); - throw ex; + Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); + ex.kindOfObject = "object adapter with router"; + ex.id = instance_.identityToString(router.ice_getIdentity()); + throw ex; } - // - // Add the router's server proxy endpoints to this object - // adapter. - // - IceInternal.EndpointI[] endpoints = _routerInfo.getServerEndpoints(); - for(int i = 0; i < endpoints.Length; ++i) - { - _routerEndpoints.Add(endpoints[i]); - } - _routerEndpoints.Sort(); // Must be sorted. - - // - // Remove duplicate endpoints, so we have a list of unique endpoints. - // - for(int i = 0; i < _routerEndpoints.Count-1;) - { - System.Object o1 = _routerEndpoints[i]; - System.Object o2 = _routerEndpoints[i + 1]; - if(o1.Equals(o2)) - { - _routerEndpoints.RemoveAt(i); - } - else - { - ++i; - } - } - - // - // Associate this object adapter with the router. This way, - // new outgoing connections to the router's client proxy will - // use this object adapter for callbacks. - // - _routerInfo.setAdapter(this); - - // - // Also modify all existing outgoing connections to the - // router's client proxy to use this object adapter for - // callbacks. - // - instance_.outgoingConnectionFactory().setRouterInfo(_routerInfo); - } - } - else - { - // - // Parse the endpoints, but don't store them in the adapter. - // The connection factory might change it, for example, to - // fill in the real port number. - // - ArrayList endpoints; - if(endpointInfo.Length == 0) - { - endpoints = parseEndpoints(properties.getPropertyWithDefault( - _propertyPrefix + _name + ".Endpoints", - properties.getProperty(_name + ".Endpoints"))); - } - else - { - endpoints = parseEndpoints(endpointInfo); - } - for(int i = 0; i < endpoints.Count; ++i) - { - IceInternal.EndpointI endp = (IceInternal.EndpointI)endpoints[i]; + // + // Add the router's server proxy endpoints to this object + // adapter. + // + IceInternal.EndpointI[] endpoints = _routerInfo.getServerEndpoints(); + for(int i = 0; i < endpoints.Length; ++i) + { + _routerEndpoints.Add(endpoints[i]); + } + _routerEndpoints.Sort(); // Must be sorted. + + // + // Remove duplicate endpoints, so we have a list of unique endpoints. + // + for(int i = 0; i < _routerEndpoints.Count-1;) + { + System.Object o1 = _routerEndpoints[i]; + System.Object o2 = _routerEndpoints[i + 1]; + if(o1.Equals(o2)) + { + _routerEndpoints.RemoveAt(i); + } + else + { + ++i; + } + } + + // + // Associate this object adapter with the router. This way, + // new outgoing connections to the router's client proxy will + // use this object adapter for callbacks. + // + _routerInfo.setAdapter(this); + + // + // Also modify all existing outgoing connections to the + // router's client proxy to use this object adapter for + // callbacks. + // + instance_.outgoingConnectionFactory().setRouterInfo(_routerInfo); + } + } + else + { + // + // Parse the endpoints, but don't store them in the adapter. + // The connection factory might change it, for example, to + // fill in the real port number. + // + ArrayList endpoints; + if(endpointInfo.Length == 0) + { + endpoints = parseEndpoints(properties.getPropertyWithDefault( + _propertyPrefix + _name + ".Endpoints", + properties.getProperty(_name + ".Endpoints"))); + } + else + { + endpoints = parseEndpoints(endpointInfo); + } + for(int i = 0; i < endpoints.Count; ++i) + { + IceInternal.EndpointI endp = (IceInternal.EndpointI)endpoints[i]; // // TODO: Remove when we no longer support SSL for .NET 1.1. // @@ -940,356 +940,356 @@ namespace Ice ex.unsupportedFeature = "endpoint requires thread-per-connection:\n" + endp.ToString(); throw ex; } - _incomingConnectionFactories.Add( - new IceInternal.IncomingConnectionFactory(instance, endp, this, _name)); - } - if(endpoints.Count == 0) - { - IceInternal.TraceLevels tl = instance_.traceLevels(); - if(tl.network >= 2) - { - instance_.initializationData().logger.trace(tl.networkCat, - "created adapter `" + _name + "' without endpoints"); - } - } - - // - // Parse published endpoints. If set, these are used in proxies - // instead of the connection factory endpoints. - // - string endpts = properties.getPropertyWithDefault(_propertyPrefix + _name + ".PublishedEndpoints", - properties.getProperty(_name + ".PublishedEndpoints")); - _publishedEndpoints = parseEndpoints(endpts); - if(_publishedEndpoints.Count == 0) - { - foreach(IceInternal.IncomingConnectionFactory factory in _incomingConnectionFactories) - { - _publishedEndpoints.Add(factory.endpoint()); - } - } - - // - // Filter out any endpoints that are not meant to be published. - // - ArrayList tmp = new ArrayList(); - foreach(IceInternal.EndpointI endpoint in _publishedEndpoints) - { - if(endpoint.publish()) - { - tmp.Add(endpoint); - } - } - _publishedEndpoints = tmp; - } - - string locatorProperty = _propertyPrefix + _name + ".Locator"; - if(properties.getProperty(locatorProperty).Length > 0) - { - setLocator(LocatorPrxHelper.uncheckedCast( - instance_.proxyFactory().propertyToProxy(locatorProperty))); - } - else if(properties.getProperty(_name + ".Locator").Length > 0) - { - setLocator(LocatorPrxHelper.uncheckedCast( - instance_.proxyFactory().propertyToProxy(_name + ".Locator"))); - } - else - { - setLocator(instance_.referenceFactory().getDefaultLocator()); - } - } - catch(LocalException) - { - destroy(); - throw; - } - } - + _incomingConnectionFactories.Add( + new IceInternal.IncomingConnectionFactory(instance, endp, this, _name)); + } + if(endpoints.Count == 0) + { + IceInternal.TraceLevels tl = instance_.traceLevels(); + if(tl.network >= 2) + { + instance_.initializationData().logger.trace(tl.networkCat, + "created adapter `" + _name + "' without endpoints"); + } + } + + // + // Parse published endpoints. If set, these are used in proxies + // instead of the connection factory endpoints. + // + string endpts = properties.getPropertyWithDefault(_propertyPrefix + _name + ".PublishedEndpoints", + properties.getProperty(_name + ".PublishedEndpoints")); + _publishedEndpoints = parseEndpoints(endpts); + if(_publishedEndpoints.Count == 0) + { + foreach(IceInternal.IncomingConnectionFactory factory in _incomingConnectionFactories) + { + _publishedEndpoints.Add(factory.endpoint()); + } + } + + // + // Filter out any endpoints that are not meant to be published. + // + ArrayList tmp = new ArrayList(); + foreach(IceInternal.EndpointI endpoint in _publishedEndpoints) + { + if(endpoint.publish()) + { + tmp.Add(endpoint); + } + } + _publishedEndpoints = tmp; + } + + string locatorProperty = _propertyPrefix + _name + ".Locator"; + if(properties.getProperty(locatorProperty).Length > 0) + { + setLocator(LocatorPrxHelper.uncheckedCast( + instance_.proxyFactory().propertyToProxy(locatorProperty))); + } + else if(properties.getProperty(_name + ".Locator").Length > 0) + { + setLocator(LocatorPrxHelper.uncheckedCast( + instance_.proxyFactory().propertyToProxy(_name + ".Locator"))); + } + else + { + setLocator(instance_.referenceFactory().getDefaultLocator()); + } + } + catch(LocalException) + { + destroy(); + throw; + } + } + #if DEBUG ~ObjectAdapterI() { lock(this) { - if(!_deactivated) - { + if(!_deactivated) + { string msg = "object adapter `" + getName() + "' has not been deactivated"; - if(!Environment.HasShutdownStarted) - { - instance_.initializationData().logger.warning(msg); - } - else - { - Console.Error.WriteLine(msg); - } - } - else if(instance_ != null) - { + if(!Environment.HasShutdownStarted) + { + instance_.initializationData().logger.warning(msg); + } + else + { + Console.Error.WriteLine(msg); + } + } + else if(instance_ != null) + { string msg = "object adapter `" + getName() + "' deactivation had not been waited for"; - if(!Environment.HasShutdownStarted) - { - instance_.initializationData().logger.warning(msg); - } - else - { - Console.Error.WriteLine(msg); - } - } + if(!Environment.HasShutdownStarted) + { + instance_.initializationData().logger.warning(msg); + } + else + { + Console.Error.WriteLine(msg); + } + } } } #endif - private ObjectPrx newProxy(Identity ident, string facet) - { - if(_id.Length == 0) - { - return newDirectProxy(ident, facet); - } - else if(_replicaGroupId.Length == 0) - { - return newIndirectProxy(ident, facet, _id); - } - else - { - return newIndirectProxy(ident, facet, _replicaGroupId); - } - } - - private ObjectPrx newDirectProxy(Identity ident, string facet) - { - IceInternal.EndpointI[] endpoints; - - // - // Use the published endpoints, otherwise use the endpoints from all - // incoming connection factories. - // - int sz = _publishedEndpoints.Count; - endpoints = new IceInternal.EndpointI[sz + _routerEndpoints.Count]; - for(int i = 0; i < sz; ++i) - { - endpoints[i] = (IceInternal.EndpointI)_publishedEndpoints[i]; - } - - // - // Now we also add the endpoints of the router's server proxy, if - // any. This way, object references created by this object adapter - // will also point to the router's server proxy endpoints. - // - for(int i = 0; i < _routerEndpoints.Count; ++i) - { - endpoints[sz + i] = (IceInternal.EndpointI)_routerEndpoints[i]; - } - - // - // Create a reference and return a proxy for this reference. - // - IceInternal.Reference reference = - instance_.referenceFactory().create(ident, instance_.getDefaultContext(), facet, - IceInternal.Reference.Mode.ModeTwoway, false, - instance_.defaultsAndOverrides().defaultPreferSecure, endpoints, - null, - instance_.defaultsAndOverrides().defaultCollocationOptimization, + private ObjectPrx newProxy(Identity ident, string facet) + { + if(_id.Length == 0) + { + return newDirectProxy(ident, facet); + } + else if(_replicaGroupId.Length == 0) + { + return newIndirectProxy(ident, facet, _id); + } + else + { + return newIndirectProxy(ident, facet, _replicaGroupId); + } + } + + private ObjectPrx newDirectProxy(Identity ident, string facet) + { + IceInternal.EndpointI[] endpoints; + + // + // Use the published endpoints, otherwise use the endpoints from all + // incoming connection factories. + // + int sz = _publishedEndpoints.Count; + endpoints = new IceInternal.EndpointI[sz + _routerEndpoints.Count]; + for(int i = 0; i < sz; ++i) + { + endpoints[i] = (IceInternal.EndpointI)_publishedEndpoints[i]; + } + + // + // Now we also add the endpoints of the router's server proxy, if + // any. This way, object references created by this object adapter + // will also point to the router's server proxy endpoints. + // + for(int i = 0; i < _routerEndpoints.Count; ++i) + { + endpoints[sz + i] = (IceInternal.EndpointI)_routerEndpoints[i]; + } + + // + // Create a reference and return a proxy for this reference. + // + IceInternal.Reference reference = + instance_.referenceFactory().create(ident, instance_.getDefaultContext(), facet, + IceInternal.Reference.Mode.ModeTwoway, false, + instance_.defaultsAndOverrides().defaultPreferSecure, endpoints, + null, + instance_.defaultsAndOverrides().defaultCollocationOptimization, true, instance_.defaultsAndOverrides().defaultEndpointSelection, instance_.threadPerConnection()); - return instance_.proxyFactory().referenceToProxy(reference); - } - - private ObjectPrx newIndirectProxy(Identity ident, string facet, string id) - { - // - // Create a reference with the adapter id and return a - // proxy for the reference. - // - IceInternal.Reference reference = - instance_.referenceFactory().create(ident, instance_.getDefaultContext(), facet, - IceInternal.Reference.Mode.ModeTwoway, - false, instance_.defaultsAndOverrides().defaultPreferSecure, id, - null, _locatorInfo, - instance_.defaultsAndOverrides().defaultCollocationOptimization, + return instance_.proxyFactory().referenceToProxy(reference); + } + + private ObjectPrx newIndirectProxy(Identity ident, string facet, string id) + { + // + // Create a reference with the adapter id and return a + // proxy for the reference. + // + IceInternal.Reference reference = + instance_.referenceFactory().create(ident, instance_.getDefaultContext(), facet, + IceInternal.Reference.Mode.ModeTwoway, + false, instance_.defaultsAndOverrides().defaultPreferSecure, id, + null, _locatorInfo, + instance_.defaultsAndOverrides().defaultCollocationOptimization, true, instance_.defaultsAndOverrides().defaultEndpointSelection, instance_.threadPerConnection(), - instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); - return instance_.proxyFactory().referenceToProxy(reference); - } - - private void checkForDeactivation() - { - if(_deactivated) - { - ObjectAdapterDeactivatedException ex = new ObjectAdapterDeactivatedException(); - ex.name = getName(); - throw ex; - } - } - - private static void checkIdentity(Identity ident) - { - if(ident.name == null || ident.name.Length == 0) - { - IllegalIdentityException e = new IllegalIdentityException(); - e.id.name = ident.name; - e.id.category = ident.category; - throw e; - } - if(ident.category == null) - { - ident.category = ""; - } - } - - private ArrayList parseEndpoints(string endpts) - { - endpts = endpts.ToLower(); - - int beg; - int end = 0; - - string delim = " \t\n\r"; - - ArrayList endpoints = new ArrayList(); - while(end < endpts.Length) - { - beg = IceUtil.StringUtil.findFirstNotOf(endpts, delim, end); - if(beg == -1) - { - break; - } - - end = endpts.IndexOf((System.Char) ':', beg); - if(end == -1) - { - end = endpts.Length; - } - - if(end == beg) - { - ++end; - continue; - } - - string s = endpts.Substring(beg, (end) - (beg)); - IceInternal.EndpointI endp = instance_.endpointFactoryManager().create(s); - if(endp == null) - { - if(IceInternal.AssemblyUtil.runtime_ == IceInternal.AssemblyUtil.Runtime.Mono && - s.StartsWith("ssl")) - { + instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); + return instance_.proxyFactory().referenceToProxy(reference); + } + + private void checkForDeactivation() + { + if(_deactivated) + { + ObjectAdapterDeactivatedException ex = new ObjectAdapterDeactivatedException(); + ex.name = getName(); + throw ex; + } + } + + private static void checkIdentity(Identity ident) + { + if(ident.name == null || ident.name.Length == 0) + { + IllegalIdentityException e = new IllegalIdentityException(); + e.id.name = ident.name; + e.id.category = ident.category; + throw e; + } + if(ident.category == null) + { + ident.category = ""; + } + } + + private ArrayList parseEndpoints(string endpts) + { + endpts = endpts.ToLower(); + + int beg; + int end = 0; + + string delim = " \t\n\r"; + + ArrayList endpoints = new ArrayList(); + while(end < endpts.Length) + { + beg = IceUtil.StringUtil.findFirstNotOf(endpts, delim, end); + if(beg == -1) + { + break; + } + + end = endpts.IndexOf((System.Char) ':', beg); + if(end == -1) + { + end = endpts.Length; + } + + if(end == beg) + { + ++end; + continue; + } + + string s = endpts.Substring(beg, (end) - (beg)); + IceInternal.EndpointI endp = instance_.endpointFactoryManager().create(s); + if(endp == null) + { + if(IceInternal.AssemblyUtil.runtime_ == IceInternal.AssemblyUtil.Runtime.Mono && + s.StartsWith("ssl")) + { instance_.initializationData().logger.warning( "SSL endpoint `" + s + "' ignored: IceSSL is not supported with Mono"); ++end; continue; - } - Ice.EndpointParseException e2 = new Ice.EndpointParseException(); - e2.str = s; - throw e2; - } - ArrayList endps = endp.expand(true); - endpoints.AddRange(endps); - - ++end; - } - - return endpoints; - } - - private void updateLocatorRegistry(IceInternal.LocatorInfo locatorInfo, ObjectPrx proxy, bool registerProcess) - { - if(!registerProcess && _id.Length == 0) - { - return; // Nothing to update. - } - - // - // We must get and call on the locator registry outside the - // thread synchronization to avoid deadlocks. (we can't make - // remote calls within the OA synchronization because the - // remote call will indirectly call isLocal() on this OA with - // the OA factory locked). - // - // TODO: This might throw if we can't connect to the - // locator. Shall we raise a special exception for the - // activate operation instead of a non obvious network - // exception? - // - LocatorRegistryPrx locatorRegistry = locatorInfo != null ? locatorInfo.getLocatorRegistry() : null; - string serverId = ""; - if(registerProcess) - { - Debug.Assert(instance_ != null); - serverId = instance_.initializationData().properties.getProperty("Ice.ServerId"); - - if(locatorRegistry == null) - { - instance_.initializationData().logger.warning( - "object adapter `" + getName() + "' cannot register the process without a locator registry"); - } - else if(serverId.Length == 0) - { - instance_.initializationData().logger.warning( - "object adapter `" + getName() + - "' cannot register the process without a value for Ice.ServerId"); - } - } - - if(locatorRegistry == null) - { - return; - } - - if(_id.Length > 0) - { - try - { - if(_replicaGroupId.Length == 0) - { - locatorRegistry.setAdapterDirectProxy(_id, proxy); - } - else - { - locatorRegistry.setReplicatedAdapterDirectProxy(_id, _replicaGroupId, proxy); - } - } - catch(AdapterNotFoundException) - { - NotRegisteredException ex1 = new NotRegisteredException(); - ex1.kindOfObject = "object adapter"; - ex1.id = _id; - throw ex1; - } - catch(InvalidReplicaGroupIdException) - { - NotRegisteredException ex1 = new NotRegisteredException(); - ex1.kindOfObject = "replica group"; - ex1.id = _replicaGroupId; - throw ex1; - } - catch(AdapterAlreadyActiveException) - { - ObjectAdapterIdInUseException ex1 = new ObjectAdapterIdInUseException(); - ex1.id = _id; - throw ex1; - } - } - - if(registerProcess && serverId.Length > 0) - { - try - { - Process servant = new ProcessI(_communicator); - Ice.ObjectPrx process = createDirectProxy(addWithUUID(servant).ice_getIdentity()); - locatorRegistry.setServerProcessProxy(serverId, ProcessPrxHelper.uncheckedCast(process)); - } - catch(ServerNotFoundException) - { - NotRegisteredException ex1 = new NotRegisteredException(); - ex1.id = serverId; - ex1.kindOfObject = "server"; - throw ex1; - } - } - } - - static private readonly string[] _suffixes = - { + } + Ice.EndpointParseException e2 = new Ice.EndpointParseException(); + e2.str = s; + throw e2; + } + ArrayList endps = endp.expand(true); + endpoints.AddRange(endps); + + ++end; + } + + return endpoints; + } + + private void updateLocatorRegistry(IceInternal.LocatorInfo locatorInfo, ObjectPrx proxy, bool registerProcess) + { + if(!registerProcess && _id.Length == 0) + { + return; // Nothing to update. + } + + // + // We must get and call on the locator registry outside the + // thread synchronization to avoid deadlocks. (we can't make + // remote calls within the OA synchronization because the + // remote call will indirectly call isLocal() on this OA with + // the OA factory locked). + // + // TODO: This might throw if we can't connect to the + // locator. Shall we raise a special exception for the + // activate operation instead of a non obvious network + // exception? + // + LocatorRegistryPrx locatorRegistry = locatorInfo != null ? locatorInfo.getLocatorRegistry() : null; + string serverId = ""; + if(registerProcess) + { + Debug.Assert(instance_ != null); + serverId = instance_.initializationData().properties.getProperty("Ice.ServerId"); + + if(locatorRegistry == null) + { + instance_.initializationData().logger.warning( + "object adapter `" + getName() + "' cannot register the process without a locator registry"); + } + else if(serverId.Length == 0) + { + instance_.initializationData().logger.warning( + "object adapter `" + getName() + + "' cannot register the process without a value for Ice.ServerId"); + } + } + + if(locatorRegistry == null) + { + return; + } + + if(_id.Length > 0) + { + try + { + if(_replicaGroupId.Length == 0) + { + locatorRegistry.setAdapterDirectProxy(_id, proxy); + } + else + { + locatorRegistry.setReplicatedAdapterDirectProxy(_id, _replicaGroupId, proxy); + } + } + catch(AdapterNotFoundException) + { + NotRegisteredException ex1 = new NotRegisteredException(); + ex1.kindOfObject = "object adapter"; + ex1.id = _id; + throw ex1; + } + catch(InvalidReplicaGroupIdException) + { + NotRegisteredException ex1 = new NotRegisteredException(); + ex1.kindOfObject = "replica group"; + ex1.id = _replicaGroupId; + throw ex1; + } + catch(AdapterAlreadyActiveException) + { + ObjectAdapterIdInUseException ex1 = new ObjectAdapterIdInUseException(); + ex1.id = _id; + throw ex1; + } + } + + if(registerProcess && serverId.Length > 0) + { + try + { + Process servant = new ProcessI(_communicator); + Ice.ObjectPrx process = createDirectProxy(addWithUUID(servant).ice_getIdentity()); + locatorRegistry.setServerProcessProxy(serverId, ProcessPrxHelper.uncheckedCast(process)); + } + catch(ServerNotFoundException) + { + NotRegisteredException ex1 = new NotRegisteredException(); + ex1.id = serverId; + ex1.kindOfObject = "server"; + throw ex1; + } + } + } + + static private readonly string[] _suffixes = + { "AdapterId", "Endpoints", "Locator", @@ -1301,78 +1301,78 @@ namespace Ice "ThreadPool.SizeMax", "ThreadPool.SizeWarn", "ThreadPool.StackSize" - }; - - private string[] - filterProperties(string prefix) - { - ArrayList propertySet = new ArrayList(); - PropertyDict props = instance_.initializationData().properties.getPropertiesForPrefix(prefix); - for(int i = 0; i < _suffixes.Length; ++i) - { - if(props.Contains(prefix + _suffixes[i])) - { - propertySet.Add(prefix + _suffixes[i]); - } - } - - return (string[])propertySet.ToArray(typeof(string)); - } - - private sealed class ProcessI : ProcessDisp_ - { - public ProcessI(Communicator communicator) - { - _communicator = communicator; - } - - public override void shutdown(Ice.Current current) - { - _communicator.shutdown(); - } - - public override void writeMessage(string message, int fd, Ice.Current current) - { - switch(fd) - { - case 1: - { - System.Console.Out.WriteLine(message); - break; - } - case 2: - { - System.Console.Error.WriteLine(message); - break; - } - } - } - - - private Communicator _communicator; - } - - private bool _deactivated; - private IceInternal.Instance instance_; - private Communicator _communicator; - private IceInternal.ObjectAdapterFactory _objectAdapterFactory; - private IceInternal.ThreadPool _threadPool; - private IceInternal.ServantManager _servantManager; - private bool _activateOneOffDone; - private readonly string _name; - private readonly string _id; - private readonly string _replicaGroupId; - private ArrayList _incomingConnectionFactories; - private ArrayList _routerEndpoints; - private IceInternal.RouterInfo _routerInfo; - private ArrayList _publishedEndpoints; - private IceInternal.LocatorInfo _locatorInfo; - private int _directCount; - private bool _waitForActivate; - private bool _destroying; - private bool _destroyed; - private bool _noConfig; + }; + + private string[] + filterProperties(string prefix) + { + ArrayList propertySet = new ArrayList(); + PropertyDict props = instance_.initializationData().properties.getPropertiesForPrefix(prefix); + for(int i = 0; i < _suffixes.Length; ++i) + { + if(props.Contains(prefix + _suffixes[i])) + { + propertySet.Add(prefix + _suffixes[i]); + } + } + + return (string[])propertySet.ToArray(typeof(string)); + } + + private sealed class ProcessI : ProcessDisp_ + { + public ProcessI(Communicator communicator) + { + _communicator = communicator; + } + + public override void shutdown(Ice.Current current) + { + _communicator.shutdown(); + } + + public override void writeMessage(string message, int fd, Ice.Current current) + { + switch(fd) + { + case 1: + { + System.Console.Out.WriteLine(message); + break; + } + case 2: + { + System.Console.Error.WriteLine(message); + break; + } + } + } + + + private Communicator _communicator; + } + + private bool _deactivated; + private IceInternal.Instance instance_; + private Communicator _communicator; + private IceInternal.ObjectAdapterFactory _objectAdapterFactory; + private IceInternal.ThreadPool _threadPool; + private IceInternal.ServantManager _servantManager; + private bool _activateOneOffDone; + private readonly string _name; + private readonly string _id; + private readonly string _replicaGroupId; + private ArrayList _incomingConnectionFactories; + private ArrayList _routerEndpoints; + private IceInternal.RouterInfo _routerInfo; + private ArrayList _publishedEndpoints; + private IceInternal.LocatorInfo _locatorInfo; + private int _directCount; + private bool _waitForActivate; + private bool _destroying; + private bool _destroyed; + private bool _noConfig; private bool _threadPerConnection; - static private string _propertyPrefix = "Ice.OA."; + static private string _propertyPrefix = "Ice.OA."; } } diff --git a/cs/src/Ice/ObjectFactoryManager.cs b/cs/src/Ice/ObjectFactoryManager.cs index 9b66bad471f..7f686f7b957 100755 --- a/cs/src/Ice/ObjectFactoryManager.cs +++ b/cs/src/Ice/ObjectFactoryManager.cs @@ -14,73 +14,73 @@ namespace IceInternal public sealed class ObjectFactoryManager { - public void add(Ice.ObjectFactory factory, string id) - { - lock(this) - { - object o = _factoryMap[id]; - if(o != null) - { - Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); - ex.id = id; - ex.kindOfObject = "object factory"; - throw ex; - } - _factoryMap[id] = factory; - } - } - - public void remove(string id) - { - object o = null; - lock(this) - { - o = _factoryMap[id]; - if(o == null) - { - Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); - ex.id = id; - ex.kindOfObject = "object factory"; - throw ex; - } - _factoryMap.Remove(id); - } - ((Ice.ObjectFactory)o).destroy(); - } - - public Ice.ObjectFactory find(string id) - { - lock(this) - { - return (Ice.ObjectFactory)_factoryMap[id]; - } - } - - // - // Only for use by Instance - // - internal ObjectFactoryManager() - { - _factoryMap = new Hashtable(); - } - - internal void destroy() - { - Hashtable oldMap = null; + public void add(Ice.ObjectFactory factory, string id) + { + lock(this) + { + object o = _factoryMap[id]; + if(o != null) + { + Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); + ex.id = id; + ex.kindOfObject = "object factory"; + throw ex; + } + _factoryMap[id] = factory; + } + } + + public void remove(string id) + { + object o = null; + lock(this) + { + o = _factoryMap[id]; + if(o == null) + { + Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); + ex.id = id; + ex.kindOfObject = "object factory"; + throw ex; + } + _factoryMap.Remove(id); + } + ((Ice.ObjectFactory)o).destroy(); + } + + public Ice.ObjectFactory find(string id) + { + lock(this) + { + return (Ice.ObjectFactory)_factoryMap[id]; + } + } + + // + // Only for use by Instance + // + internal ObjectFactoryManager() + { + _factoryMap = new Hashtable(); + } + + internal void destroy() + { + Hashtable oldMap = null; - lock(this) - { - oldMap = _factoryMap; - _factoryMap = new Hashtable(); - } + lock(this) + { + oldMap = _factoryMap; + _factoryMap = new Hashtable(); + } - foreach(Ice.ObjectFactory factory in oldMap.Values) - { - factory.destroy(); - } - } - - private Hashtable _factoryMap; + foreach(Ice.ObjectFactory factory in oldMap.Values) + { + factory.destroy(); + } + } + + private Hashtable _factoryMap; } } diff --git a/cs/src/Ice/ObjectReader.cs b/cs/src/Ice/ObjectReader.cs index d22b69fbd74..c96d280ae25 100644 --- a/cs/src/Ice/ObjectReader.cs +++ b/cs/src/Ice/ObjectReader.cs @@ -13,17 +13,17 @@ namespace Ice { public abstract class ObjectReader : ObjectImpl { - public abstract void read(InputStream inStream, bool rid); + public abstract void read(InputStream inStream, bool rid); - public override void write__(IceInternal.BasicStream os) - { - Debug.Assert(false); - } + public override void write__(IceInternal.BasicStream os) + { + Debug.Assert(false); + } - public override void read__(IceInternal.BasicStream istr, bool rid) - { - IceInternal.BasicInputStream bis = (IceInternal.BasicInputStream)istr; - read(bis.in_, rid); - } + public override void read__(IceInternal.BasicStream istr, bool rid) + { + IceInternal.BasicInputStream bis = (IceInternal.BasicInputStream)istr; + read(bis.in_, rid); + } } } diff --git a/cs/src/Ice/ObjectWriter.cs b/cs/src/Ice/ObjectWriter.cs index 41c8cd2d160..29991d4a5f7 100644 --- a/cs/src/Ice/ObjectWriter.cs +++ b/cs/src/Ice/ObjectWriter.cs @@ -13,18 +13,18 @@ namespace Ice { public abstract class ObjectWriter : ObjectImpl { - public abstract void write(OutputStream outStream); + public abstract void write(OutputStream outStream); - public override void write__(IceInternal.BasicStream os) - { - IceInternal.BasicOutputStream bos = (IceInternal.BasicOutputStream)os; - write(bos.out_); - } + public override void write__(IceInternal.BasicStream os) + { + IceInternal.BasicOutputStream bos = (IceInternal.BasicOutputStream)os; + write(bos.out_); + } - public override void read__(IceInternal.BasicStream istr, bool rid) - { - Debug.Assert(false); - } + public override void read__(IceInternal.BasicStream istr, bool rid) + { + Debug.Assert(false); + } } } diff --git a/cs/src/Ice/Options.cs b/cs/src/Ice/Options.cs index 8519d487a82..2256ae90937 100644 --- a/cs/src/Ice/Options.cs +++ b/cs/src/Ice/Options.cs @@ -14,392 +14,392 @@ namespace IceUtil { public sealed class Options { - public sealed class BadQuote : System.ApplicationException - { - public BadQuote(string message) : base(message) - { - } - } + public sealed class BadQuote : System.ApplicationException + { + public BadQuote(string message) : base(message) + { + } + } - enum State { Normal, DoubleQuote, SingleQuote, ANSIQuote }; + enum State { Normal, DoubleQuote, SingleQuote, ANSIQuote }; - static public string[] - split(string line) + static public string[] + split(string line) { - string IFS = " \t\n"; - - string l = line.Trim(); - if(l.Length == 0) - { - return new string[0]; - } + string IFS = " \t\n"; + + string l = line.Trim(); + if(l.Length == 0) + { + return new string[0]; + } - State state = State.Normal; + State state = State.Normal; - string arg = ""; - ArrayList vec = new ArrayList(); - - for(int i = 0; i < l.Length; ++i) - { - char c = l[i]; - switch(state) - { - case State.Normal: - { - switch(c) - { - case '\\': - { - // - // Ignore a backslash at the end of the string, - // and strip backslash-newline pairs. If a - // backslash is followed by a space, single quote, - // double quote, or dollar sign, we drop the backslash - // and write the space, single quote, double quote, - // or dollar sign. This is necessary to allow quotes - // to be escaped. Dropping the backslash preceding a - // space deviates from bash quoting rules, but is - // necessary so we don't drop backslashes from Windows - // path names.) - // - if(i < l.Length - 1 && l[++i] != '\n') - { - switch(l[i]) - { - case ' ': - case '$': - case '\'': - case '"': - { - arg += l[i]; - break; - } - default: - { - arg += '\\'; - arg += l[i]; + string arg = ""; + ArrayList vec = new ArrayList(); + + for(int i = 0; i < l.Length; ++i) + { + char c = l[i]; + switch(state) + { + case State.Normal: + { + switch(c) + { + case '\\': + { + // + // Ignore a backslash at the end of the string, + // and strip backslash-newline pairs. If a + // backslash is followed by a space, single quote, + // double quote, or dollar sign, we drop the backslash + // and write the space, single quote, double quote, + // or dollar sign. This is necessary to allow quotes + // to be escaped. Dropping the backslash preceding a + // space deviates from bash quoting rules, but is + // necessary so we don't drop backslashes from Windows + // path names.) + // + if(i < l.Length - 1 && l[++i] != '\n') + { + switch(l[i]) + { + case ' ': + case '$': + case '\'': + case '"': + { + arg += l[i]; + break; + } + default: + { + arg += '\\'; + arg += l[i]; break; - } - } - } - break; - } - case '\'': - { - state = State.SingleQuote; - break; - } - case '"': - { - state = State.DoubleQuote; - break; - } - case '$': - { - if(i < l.Length - 1 && l[i + 1] == '\'') - { - state = State.ANSIQuote; // Bash uses $'<text>' to allow ANSI escape sequences - // within <text>. - ++i; - } - else - { - arg += '$'; - } - break; - } - default: - { - if(IFS.IndexOf(l[i]) != -1) - { - vec.Add(arg); - arg = ""; - - // - // Move to start of next argument. - // - while(++i < l.Length && IFS.IndexOf(l[i]) != -1) - { - ; - } - --i; - } - else - { - arg += l[i]; - } - break; - } - } - break; - } - case State.DoubleQuote: - { - // - // Within double quotes, only backslash retains its special - // meaning, and only if followed by double quote, backslash, - // or newline. If not followed by one of these characters, - // both the backslash and the character are preserved. - // - if(c == '\\' && i < l.Length - 1) - { - switch(c = l[++i]) - { - case '"': - case '\\': - case '\n': - { - arg += c; - break; - } - default: - { - arg += '\\'; - arg += c; - break; - } - } - } - else if(c == '"') // End of double-quote mode. - { - state = State.Normal; - } - else - { - arg += c; // Everything else is taken literally. - } - break; - } - case State.SingleQuote: - { - if(c == '\'') // End of single-quote mode. - { - state = State.Normal; - } - else - { - arg += c; // Everything else is taken literally. - } - break; - } - case State.ANSIQuote: - { - switch(c) - { - case '\\': - { - if(i == l.Length - 1) - { - break; - } - switch(c = l[++i]) - { - // - // Single-letter escape sequences. - // - case 'a': - { - arg += '\a'; - break; - } - case 'b': - { - arg += '\b'; - break; - } - case 'f': - { - arg += '\f'; - break; - } - case 'n': - { - arg += '\n'; - break; - } - case 'r': - { - arg += '\r'; - break; - } - case 't': - { - arg += '\t'; - break; - } - case 'v': - { - arg += '\v'; - break; - } - case '\\': - { - arg += '\\'; - break; - } - case '\'': - { - arg += '\''; - break; - } - case 'e': // Not ANSI-C, but used by bash. - { - arg += '\u001B'; - break; - } + } + } + } + break; + } + case '\'': + { + state = State.SingleQuote; + break; + } + case '"': + { + state = State.DoubleQuote; + break; + } + case '$': + { + if(i < l.Length - 1 && l[i + 1] == '\'') + { + state = State.ANSIQuote; // Bash uses $'<text>' to allow ANSI escape sequences + // within <text>. + ++i; + } + else + { + arg += '$'; + } + break; + } + default: + { + if(IFS.IndexOf(l[i]) != -1) + { + vec.Add(arg); + arg = ""; + + // + // Move to start of next argument. + // + while(++i < l.Length && IFS.IndexOf(l[i]) != -1) + { + ; + } + --i; + } + else + { + arg += l[i]; + } + break; + } + } + break; + } + case State.DoubleQuote: + { + // + // Within double quotes, only backslash retains its special + // meaning, and only if followed by double quote, backslash, + // or newline. If not followed by one of these characters, + // both the backslash and the character are preserved. + // + if(c == '\\' && i < l.Length - 1) + { + switch(c = l[++i]) + { + case '"': + case '\\': + case '\n': + { + arg += c; + break; + } + default: + { + arg += '\\'; + arg += c; + break; + } + } + } + else if(c == '"') // End of double-quote mode. + { + state = State.Normal; + } + else + { + arg += c; // Everything else is taken literally. + } + break; + } + case State.SingleQuote: + { + if(c == '\'') // End of single-quote mode. + { + state = State.Normal; + } + else + { + arg += c; // Everything else is taken literally. + } + break; + } + case State.ANSIQuote: + { + switch(c) + { + case '\\': + { + if(i == l.Length - 1) + { + break; + } + switch(c = l[++i]) + { + // + // Single-letter escape sequences. + // + case 'a': + { + arg += '\a'; + break; + } + case 'b': + { + arg += '\b'; + break; + } + case 'f': + { + arg += '\f'; + break; + } + case 'n': + { + arg += '\n'; + break; + } + case 'r': + { + arg += '\r'; + break; + } + case 't': + { + arg += '\t'; + break; + } + case 'v': + { + arg += '\v'; + break; + } + case '\\': + { + arg += '\\'; + break; + } + case '\'': + { + arg += '\''; + break; + } + case 'e': // Not ANSI-C, but used by bash. + { + arg += '\u001B'; + break; + } - // - // Process up to three octal digits. - // - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - { - const string octalDigits = "01234567"; - short s = 0; - int j; - for(j = i; j < i + 3 && j < l.Length && octalDigits.IndexOf(c = l[j]) != -1; ++j) - { - s = (short)(s * 8 + c - '0'); - } - i = j - 1; - arg += (char)s; - break; - } + // + // Process up to three octal digits. + // + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + { + const string octalDigits = "01234567"; + short s = 0; + int j; + for(j = i; j < i + 3 && j < l.Length && octalDigits.IndexOf(c = l[j]) != -1; ++j) + { + s = (short)(s * 8 + c - '0'); + } + i = j - 1; + arg += (char)s; + break; + } - // - // Process up to two hex digits. - // - case 'x': - { - const string hexDigits = "0123456789abcdefABCDEF"; - if(i < l.Length - 1 && hexDigits.IndexOf(l[i + 1]) == -1) - { - arg += '\\'; - arg += 'x'; - break; - } + // + // Process up to two hex digits. + // + case 'x': + { + const string hexDigits = "0123456789abcdefABCDEF"; + if(i < l.Length - 1 && hexDigits.IndexOf(l[i + 1]) == -1) + { + arg += '\\'; + arg += 'x'; + break; + } - short s = 0; - int j; - for(j = i + 1; - j < i + 3 && j < l.Length && hexDigits.IndexOf(c = l[j]) != -1; - ++j) - { - s *= 16; - if(char.IsDigit(c)) - { - s += (short)(c - '0'); - } - else if(char.IsLower(c)) - { - s += (short)(c - 'a' + 10); - } - else - { - s += (short)(c - 'A' + 10); - } - } - i = j - 1; - arg += (char)s; - break; - } + short s = 0; + int j; + for(j = i + 1; + j < i + 3 && j < l.Length && hexDigits.IndexOf(c = l[j]) != -1; + ++j) + { + s *= 16; + if(char.IsDigit(c)) + { + s += (short)(c - '0'); + } + else if(char.IsLower(c)) + { + s += (short)(c - 'a' + 10); + } + else + { + s += (short)(c - 'A' + 10); + } + } + i = j - 1; + arg += (char)s; + break; + } - // - // Process control-chars. - // - case 'c': - { - c = l[++i]; - if((char.ToUpper(c) >= 'A' && char.ToUpper(c) <= 'Z') || - c == '@' || - (c >= '[' && c <= '_')) + // + // Process control-chars. + // + case 'c': + { + c = l[++i]; + if((char.ToUpper(c) >= 'A' && char.ToUpper(c) <= 'Z') || + c == '@' || + (c >= '[' && c <= '_')) + { + arg += (char)(char.ToUpper(c) - '@'); + } + else { - arg += (char)(char.ToUpper(c) - '@'); - } - else - { - // - // Bash does not define what should happen if a \c - // is not followed by a recognized control character. - // We simply treat this case like other unrecognized - // escape sequences, that is, we preserve the escape - // sequence unchanged. - // - arg += '\\'; - arg += 'c'; - arg += c; - } - break; - } + // + // Bash does not define what should happen if a \c + // is not followed by a recognized control character. + // We simply treat this case like other unrecognized + // escape sequences, that is, we preserve the escape + // sequence unchanged. + // + arg += '\\'; + arg += 'c'; + arg += c; + } + break; + } - // - // If inside an ANSI-quoted string, a backslash isn't followed by - // one of the recognized characters, both the backslash and the - // character are preserved. - // - default: - { - arg += '\\'; - arg += c; - break; - } - } - break; - } - case '\'': // End of ANSI-quote mode. - { - state = State.Normal; - break; - } - default: - { - arg += c; // Everything else is taken literally. - break; - } - } - break; - } - default: - { - Debug.Assert(false); - break; - } - } - } - - switch(state) - { - case State.Normal: - { - vec.Add(arg); - break; - } - case State.SingleQuote: - { - throw new BadQuote("missing closing single quote"); - } - case State.DoubleQuote: - { - throw new BadQuote("missing closing double quote"); - } + // + // If inside an ANSI-quoted string, a backslash isn't followed by + // one of the recognized characters, both the backslash and the + // character are preserved. + // + default: + { + arg += '\\'; + arg += c; + break; + } + } + break; + } + case '\'': // End of ANSI-quote mode. + { + state = State.Normal; + break; + } + default: + { + arg += c; // Everything else is taken literally. + break; + } + } + break; + } + default: + { + Debug.Assert(false); + break; + } + } + } + + switch(state) + { + case State.Normal: + { + vec.Add(arg); + break; + } + case State.SingleQuote: + { + throw new BadQuote("missing closing single quote"); + } + case State.DoubleQuote: + { + throw new BadQuote("missing closing double quote"); + } case State.ANSIQuote: { throw new BadQuote("unterminated $' quote"); } - default: - { - Debug.Assert(false); - break; - } - } - - return (string[])vec.ToArray(typeof(string)); - } + default: + { + Debug.Assert(false); + break; + } + } + + return (string[])vec.ToArray(typeof(string)); + } } } diff --git a/cs/src/Ice/Outgoing.cs b/cs/src/Ice/Outgoing.cs index 1df78505b1d..1fe3b23531c 100755 --- a/cs/src/Ice/Outgoing.cs +++ b/cs/src/Ice/Outgoing.cs @@ -15,285 +15,285 @@ namespace IceInternal public class Outgoing { - public Outgoing(Ice.ConnectionI connection, Reference r, string operation, Ice.OperationMode mode, - Ice.Context context, bool compress) - { - _connection = connection; - _reference = r; - _state = StateUnsent; - _is = new BasicStream(r.getInstance()); - _os = new BasicStream(r.getInstance()); - _compress = compress; - - writeHeader(operation, mode, context); - } + public Outgoing(Ice.ConnectionI connection, Reference r, string operation, Ice.OperationMode mode, + Ice.Context context, bool compress) + { + _connection = connection; + _reference = r; + _state = StateUnsent; + _is = new BasicStream(r.getInstance()); + _os = new BasicStream(r.getInstance()); + _compress = compress; + + writeHeader(operation, mode, context); + } - // - // These functions allow this object to be reused, rather than reallocated. - // - public void reset(Reference r, string operation, Ice.OperationMode mode, Ice.Context context, bool compress) - { - _reference = r; - _state = StateUnsent; - _exception = null; - _compress = compress; - - writeHeader(operation, mode, context); - } + // + // These functions allow this object to be reused, rather than reallocated. + // + public void reset(Reference r, string operation, Ice.OperationMode mode, Ice.Context context, bool compress) + { + _reference = r; + _state = StateUnsent; + _exception = null; + _compress = compress; + + writeHeader(operation, mode, context); + } - public void reclaim() - { - _is.reset(); - _os.reset(); - } - - // Returns true if ok, false if user exception. - public bool invoke() - { - Debug.Assert(_state == StateUnsent); + public void reclaim() + { + _is.reset(); + _os.reset(); + } + + // Returns true if ok, false if user exception. + public bool invoke() + { + Debug.Assert(_state == StateUnsent); - _os.endWriteEncaps(); - - switch(_reference.getMode()) - { - case Reference.Mode.ModeTwoway: - { - // - // We let all exceptions raised by sending directly - // propagate to the caller, because they can be - // retried without violating "at-most-once". In case - // of such exceptions, the connection object does not - // call back on this object, so we don't need to lock - // the mutex, keep track of state, or save exceptions. - // - _connection.sendRequest(_os, this, _compress); + _os.endWriteEncaps(); + + switch(_reference.getMode()) + { + case Reference.Mode.ModeTwoway: + { + // + // We let all exceptions raised by sending directly + // propagate to the caller, because they can be + // retried without violating "at-most-once". In case + // of such exceptions, the connection object does not + // call back on this object, so we don't need to lock + // the mutex, keep track of state, or save exceptions. + // + _connection.sendRequest(_os, this, _compress); - // - // Wait until the request has completed, or until the - // request times out. - // + // + // Wait until the request has completed, or until the + // request times out. + // - bool timedOut = false; - - lock(this) - { - // - // It's possible that the request has already - // completed, due to a regular response, or because of - // an exception. So we only change the state to "in - // progress" if it is still "unsent". - // - if(_state == StateUnsent) - { - _state = StateInProgress; - } + bool timedOut = false; + + lock(this) + { + // + // It's possible that the request has already + // completed, due to a regular response, or because of + // an exception. So we only change the state to "in + // progress" if it is still "unsent". + // + if(_state == StateUnsent) + { + _state = StateInProgress; + } - int timeout = _connection.timeout(); - while(_state == StateInProgress && !timedOut) - { - if(timeout >= 0) - { - System.Threading.Monitor.Wait(this, timeout); - - if(_state == StateInProgress) - { - timedOut = true; - } - } - else - { - System.Threading.Monitor.Wait(this); - } - } - } - - if(timedOut) - { - // - // Must be called outside the synchronization of - // this object - // - _connection.exception(new Ice.TimeoutException()); + int timeout = _connection.timeout(); + while(_state == StateInProgress && !timedOut) + { + if(timeout >= 0) + { + System.Threading.Monitor.Wait(this, timeout); + + if(_state == StateInProgress) + { + timedOut = true; + } + } + else + { + System.Threading.Monitor.Wait(this); + } + } + } + + if(timedOut) + { + // + // Must be called outside the synchronization of + // this object + // + _connection.exception(new Ice.TimeoutException()); - // - // We must wait until the exception set above has - // propagated to this Outgoing object. - // - lock(this) - { - while(_state == StateInProgress) - { - System.Threading.Monitor.Wait(this); - } - } - } - - if(_exception != null) - { - // - // A CloseConnectionException indicates graceful - // server shutdown, and is therefore always repeatable - // without violating "at-most-once". That's because by - // sending a close connection message, the server - // guarantees that all outstanding requests can safely - // be repeated. - // - // An ObjectNotExistException can always be retried as - // well without violating "at-most-once". - // - if(_exception is Ice.CloseConnectionException || _exception is Ice.ObjectNotExistException) - { - throw _exception; - } - - // - // Throw the exception wrapped in a LocalExceptionWrapper, to - // indicate that the request cannot be resent without - // potentially violating the "at-most-once" principle. - // - throw new LocalExceptionWrapper(_exception, false); - } - - if(_state == StateUserException) - { - return false; - } - - Debug.Assert(_state == StateOK); - break; - } - - case Reference.Mode.ModeOneway: - case Reference.Mode.ModeDatagram: - { - // - // For oneway and datagram requests, the - // connection object never calls back on this - // object. Therefore we don't need to lock the - // mutex or save exceptions. We simply let all - // exceptions from sending propagate to the - // caller, because such exceptions can be retried - // without violating "at-most-once". - // - _state = StateInProgress; - _connection.sendRequest(_os, null, _compress); - break; - } - - case Reference.Mode.ModeBatchOneway: - case Reference.Mode.ModeBatchDatagram: - { - // - // For batch oneways and datagrams, the same rules - // as for regular oneways and datagrams (see - // comment above) apply. - // - _state = StateInProgress; - _connection.finishBatchRequest(_os, _compress); - break; - } - } - - return true; - } - - public void abort(Ice.LocalException ex) - { - Debug.Assert(_state == StateUnsent); - - // - // If we didn't finish a batch oneway or datagram request, - // we must notify the connection about that we give up - // ownership of the batch stream. - // - if(_reference.getMode() == Reference.Mode.ModeBatchOneway || + // + // We must wait until the exception set above has + // propagated to this Outgoing object. + // + lock(this) + { + while(_state == StateInProgress) + { + System.Threading.Monitor.Wait(this); + } + } + } + + if(_exception != null) + { + // + // A CloseConnectionException indicates graceful + // server shutdown, and is therefore always repeatable + // without violating "at-most-once". That's because by + // sending a close connection message, the server + // guarantees that all outstanding requests can safely + // be repeated. + // + // An ObjectNotExistException can always be retried as + // well without violating "at-most-once". + // + if(_exception is Ice.CloseConnectionException || _exception is Ice.ObjectNotExistException) + { + throw _exception; + } + + // + // Throw the exception wrapped in a LocalExceptionWrapper, to + // indicate that the request cannot be resent without + // potentially violating the "at-most-once" principle. + // + throw new LocalExceptionWrapper(_exception, false); + } + + if(_state == StateUserException) + { + return false; + } + + Debug.Assert(_state == StateOK); + break; + } + + case Reference.Mode.ModeOneway: + case Reference.Mode.ModeDatagram: + { + // + // For oneway and datagram requests, the + // connection object never calls back on this + // object. Therefore we don't need to lock the + // mutex or save exceptions. We simply let all + // exceptions from sending propagate to the + // caller, because such exceptions can be retried + // without violating "at-most-once". + // + _state = StateInProgress; + _connection.sendRequest(_os, null, _compress); + break; + } + + case Reference.Mode.ModeBatchOneway: + case Reference.Mode.ModeBatchDatagram: + { + // + // For batch oneways and datagrams, the same rules + // as for regular oneways and datagrams (see + // comment above) apply. + // + _state = StateInProgress; + _connection.finishBatchRequest(_os, _compress); + break; + } + } + + return true; + } + + public void abort(Ice.LocalException ex) + { + Debug.Assert(_state == StateUnsent); + + // + // If we didn't finish a batch oneway or datagram request, + // we must notify the connection about that we give up + // ownership of the batch stream. + // + if(_reference.getMode() == Reference.Mode.ModeBatchOneway || _reference.getMode() == Reference.Mode.ModeBatchDatagram) - { - _connection.abortBatchRequest(); + { + _connection.abortBatchRequest(); - // - // If we abort a batch requests, we cannot retry, - // because not only the batch request that caused the - // problem will be aborted, but all other requests in - // the batch as well. - // - throw new LocalExceptionWrapper(ex, false); - } - - throw ex; - } + // + // If we abort a batch requests, we cannot retry, + // because not only the batch request that caused the + // problem will be aborted, but all other requests in + // the batch as well. + // + throw new LocalExceptionWrapper(ex, false); + } + + throw ex; + } - public void finished(BasicStream istr) - { - lock(this) - { - Debug.Assert(_reference.getMode() == Reference.Mode.ModeTwoway); // Can only be called for twoways. + public void finished(BasicStream istr) + { + lock(this) + { + Debug.Assert(_reference.getMode() == Reference.Mode.ModeTwoway); // Can only be called for twoways. - Debug.Assert(_state <= StateInProgress); + Debug.Assert(_state <= StateInProgress); - _is.swap(istr); - DispatchStatus status = (DispatchStatus)_is.readByte(); + _is.swap(istr); + DispatchStatus status = (DispatchStatus)_is.readByte(); - switch(status) - { - case DispatchStatus.DispatchOK: - { - // - // Input and output parameters are always sent in an - // encapsulation, which makes it possible to forward - // oneway requests as blobs. - // - _is.startReadEncaps(); - _state = StateOK; // The state must be set last, in case there is an exception. - break; - } - - case DispatchStatus.DispatchUserException: - { - // - // Input and output parameters are always sent in an - // encapsulation, which makes it possible to forward - // oneway requests as blobs. - // - _is.startReadEncaps(); - _state = StateUserException; // The state must be set last, in case there is an exception. - break; - } - - case DispatchStatus.DispatchObjectNotExist: - case DispatchStatus.DispatchFacetNotExist: - case DispatchStatus.DispatchOperationNotExist: - { - Ice.RequestFailedException ex = null; - switch(status) - { - case DispatchStatus.DispatchObjectNotExist: - { - ex = new Ice.ObjectNotExistException(); - break; - } - - case DispatchStatus.DispatchFacetNotExist: - { - ex = new Ice.FacetNotExistException(); - break; - } - - case DispatchStatus.DispatchOperationNotExist: - { - ex = new Ice.OperationNotExistException(); - break; - } - - default: - { - Debug.Assert(false); - break; - } - } - - ex.id = new Ice.Identity(); - ex.id.read__(_is); + switch(status) + { + case DispatchStatus.DispatchOK: + { + // + // Input and output parameters are always sent in an + // encapsulation, which makes it possible to forward + // oneway requests as blobs. + // + _is.startReadEncaps(); + _state = StateOK; // The state must be set last, in case there is an exception. + break; + } + + case DispatchStatus.DispatchUserException: + { + // + // Input and output parameters are always sent in an + // encapsulation, which makes it possible to forward + // oneway requests as blobs. + // + _is.startReadEncaps(); + _state = StateUserException; // The state must be set last, in case there is an exception. + break; + } + + case DispatchStatus.DispatchObjectNotExist: + case DispatchStatus.DispatchFacetNotExist: + case DispatchStatus.DispatchOperationNotExist: + { + Ice.RequestFailedException ex = null; + switch(status) + { + case DispatchStatus.DispatchObjectNotExist: + { + ex = new Ice.ObjectNotExistException(); + break; + } + + case DispatchStatus.DispatchFacetNotExist: + { + ex = new Ice.FacetNotExistException(); + break; + } + + case DispatchStatus.DispatchOperationNotExist: + { + ex = new Ice.OperationNotExistException(); + break; + } + + default: + { + Debug.Assert(false); + break; + } + } + + ex.id = new Ice.Identity(); + ex.id.read__(_is); // // For compatibility with the old FacetPath. @@ -312,187 +312,187 @@ namespace IceInternal ex.facet = ""; } - ex.operation = _is.readString(); - _exception = ex; + ex.operation = _is.readString(); + _exception = ex; _state = StateLocalException; // The state must be set last, in case there is an exception. - break; - } - - case DispatchStatus.DispatchUnknownException: - case DispatchStatus.DispatchUnknownLocalException: - case DispatchStatus.DispatchUnknownUserException: - { - Ice.UnknownException ex = null; - switch(status) - { - case DispatchStatus.DispatchUnknownException: - { - ex = new Ice.UnknownException(); - break; - } - - case DispatchStatus.DispatchUnknownLocalException: - { - ex = new Ice.UnknownLocalException(); - break; - } - - case DispatchStatus.DispatchUnknownUserException: - { - ex = new Ice.UnknownUserException(); - break; - } - - default: - { - Debug.Assert(false); - break; - } - } - - ex.unknown = _is.readString(); - _exception = ex; + break; + } + + case DispatchStatus.DispatchUnknownException: + case DispatchStatus.DispatchUnknownLocalException: + case DispatchStatus.DispatchUnknownUserException: + { + Ice.UnknownException ex = null; + switch(status) + { + case DispatchStatus.DispatchUnknownException: + { + ex = new Ice.UnknownException(); + break; + } + + case DispatchStatus.DispatchUnknownLocalException: + { + ex = new Ice.UnknownLocalException(); + break; + } + + case DispatchStatus.DispatchUnknownUserException: + { + ex = new Ice.UnknownUserException(); + break; + } + + default: + { + Debug.Assert(false); + break; + } + } + + ex.unknown = _is.readString(); + _exception = ex; _state = StateLocalException; // The state must be set last, in case there is an exception. - break; - } - - default: - { - _exception = new Ice.UnknownReplyStatusException(); + break; + } + + default: + { + _exception = new Ice.UnknownReplyStatusException(); _state = StateLocalException; - break; - } - } + break; + } + } - System.Threading.Monitor.Pulse(this); - } - } - - public void finished(Ice.LocalException ex) - { - lock(this) - { - Debug.Assert(_reference.getMode() == Reference.Mode.ModeTwoway); // Can only be called for twoways. - - Debug.Assert(_state <= StateInProgress); + System.Threading.Monitor.Pulse(this); + } + } + + public void finished(Ice.LocalException ex) + { + lock(this) + { + Debug.Assert(_reference.getMode() == Reference.Mode.ModeTwoway); // Can only be called for twoways. + + Debug.Assert(_state <= StateInProgress); - _state = StateLocalException; - _exception = ex; - System.Threading.Monitor.Pulse(this); - } - } - - public BasicStream istr() - { - return _is; - } - - public BasicStream ostr() - { - return _os; - } - - private void writeHeader(string operation, Ice.OperationMode mode, Ice.Context context) - { - switch(_reference.getMode()) - { - case Reference.Mode.ModeTwoway: - case Reference.Mode.ModeOneway: - case Reference.Mode.ModeDatagram: - { - _os.writeBlob(IceInternal.Protocol.requestHdr); - break; - } - - case Reference.Mode.ModeBatchOneway: - case Reference.Mode.ModeBatchDatagram: - { - _connection.prepareBatchRequest(_os); - break; - } - } + _state = StateLocalException; + _exception = ex; + System.Threading.Monitor.Pulse(this); + } + } + + public BasicStream istr() + { + return _is; + } + + public BasicStream ostr() + { + return _os; + } + + private void writeHeader(string operation, Ice.OperationMode mode, Ice.Context context) + { + switch(_reference.getMode()) + { + case Reference.Mode.ModeTwoway: + case Reference.Mode.ModeOneway: + case Reference.Mode.ModeDatagram: + { + _os.writeBlob(IceInternal.Protocol.requestHdr); + break; + } + + case Reference.Mode.ModeBatchOneway: + case Reference.Mode.ModeBatchDatagram: + { + _connection.prepareBatchRequest(_os); + break; + } + } - try - { - _reference.getIdentity().write__(_os); + try + { + _reference.getIdentity().write__(_os); - // - // For compatibility with the old FacetPath. - // - string facet = _reference.getFacet(); - if(facet == null || facet.Length == 0) - { - _os.writeStringSeq(null); - } - else - { - string[] facetPath = { facet }; - _os.writeStringSeq(facetPath); - } + // + // For compatibility with the old FacetPath. + // + string facet = _reference.getFacet(); + if(facet == null || facet.Length == 0) + { + _os.writeStringSeq(null); + } + else + { + string[] facetPath = { facet }; + _os.writeStringSeq(facetPath); + } - _os.writeString(operation); + _os.writeString(operation); - _os.writeByte((byte)mode); + _os.writeByte((byte)mode); - if(context != null) - { - // - // Explicit context - // - Ice.ContextHelper.write(_os, context); - } - else - { - // - // Implicit context - // - Ice.ImplicitContextI implicitContext = - _reference.getInstance().getImplicitContext(); - - Ice.Context prxContext = _reference.getContext(); - - if(implicitContext == null) - { - Ice.ContextHelper.write(_os, prxContext); - } - else - { - implicitContext.write(prxContext, _os); - } - } - - // - // Input and output parameters are always sent in an - // encapsulation, which makes it possible to forward requests as - // blobs. - // - _os.startWriteEncaps(); - } - catch(Ice.LocalException ex) - { - abort(ex); - } - } - - private Ice.ConnectionI _connection; - private Reference _reference; - private Ice.LocalException _exception; - - private const int StateUnsent = 0; - private const int StateInProgress = 1; - private const int StateOK = 2; - private const int StateUserException = 3; - private const int StateLocalException = 4; - private int _state; - - private BasicStream _is; - private BasicStream _os; + if(context != null) + { + // + // Explicit context + // + Ice.ContextHelper.write(_os, context); + } + else + { + // + // Implicit context + // + Ice.ImplicitContextI implicitContext = + _reference.getInstance().getImplicitContext(); + + Ice.Context prxContext = _reference.getContext(); + + if(implicitContext == null) + { + Ice.ContextHelper.write(_os, prxContext); + } + else + { + implicitContext.write(prxContext, _os); + } + } + + // + // Input and output parameters are always sent in an + // encapsulation, which makes it possible to forward requests as + // blobs. + // + _os.startWriteEncaps(); + } + catch(Ice.LocalException ex) + { + abort(ex); + } + } + + private Ice.ConnectionI _connection; + private Reference _reference; + private Ice.LocalException _exception; + + private const int StateUnsent = 0; + private const int StateInProgress = 1; + private const int StateOK = 2; + private const int StateUserException = 3; + private const int StateLocalException = 4; + private int _state; + + private BasicStream _is; + private BasicStream _os; - private bool _compress; // Immutable after construction - - public Outgoing next; // For use by Ice.ObjectDelM_ + private bool _compress; // Immutable after construction + + public Outgoing next; // For use by Ice.ObjectDelM_ } } diff --git a/cs/src/Ice/OutgoingAsync.cs b/cs/src/Ice/OutgoingAsync.cs index 01d7b42c374..e7ec99cd0b5 100755 --- a/cs/src/Ice/OutgoingAsync.cs +++ b/cs/src/Ice/OutgoingAsync.cs @@ -18,19 +18,19 @@ namespace IceInternal public abstract class OutgoingAsync { public abstract void ice_exception(Ice.Exception ex); - + public void finished__(BasicStream istr) { lock(_monitor) { DispatchStatus status; - + try { is__.swap(istr); - + status = (DispatchStatus)is__.readByte(); - + switch(status) { case DispatchStatus.DispatchOK: @@ -39,7 +39,7 @@ namespace IceInternal is__.startReadEncaps(); break; } - + case DispatchStatus.DispatchObjectNotExist: case DispatchStatus.DispatchFacetNotExist: case DispatchStatus.DispatchOperationNotExist: @@ -75,13 +75,13 @@ namespace IceInternal ex = new Ice.ObjectNotExistException(); break; } - + case DispatchStatus.DispatchFacetNotExist: { ex = new Ice.FacetNotExistException(); break; } - + case DispatchStatus.DispatchOperationNotExist: { ex = new Ice.OperationNotExistException(); @@ -100,7 +100,7 @@ namespace IceInternal ex.operation = operation; throw ex; } - + case DispatchStatus.DispatchUnknownException: case DispatchStatus.DispatchUnknownLocalException: case DispatchStatus.DispatchUnknownUserException: @@ -146,9 +146,9 @@ namespace IceInternal finished__(ex); return; } - + Debug.Assert(status == DispatchStatus.DispatchOK || status == DispatchStatus.DispatchUserException); - + try { response__(status == DispatchStatus.DispatchOK); @@ -163,7 +163,7 @@ namespace IceInternal } } } - + public void finished__(Ice.LocalException exc) { lock(_monitor) @@ -180,24 +180,24 @@ namespace IceInternal // be repeated. Otherwise, we can also retry if the // operation mode is Nonmutating or Idempotent. // - // An ObjectNotExistException can always be retried as - // well without violating "at-most-once". - // + // An ObjectNotExistException can always be retried as + // well without violating "at-most-once". + // if(_mode == Ice.OperationMode.Nonmutating || _mode == Ice.OperationMode.Idempotent || exc is Ice.CloseConnectionException || exc is Ice.ObjectNotExistException) { try { - _cnt = ((Ice.ObjectPrxHelperBase)_proxy).handleException__(_delegate, exc, _cnt); - send__(); - return; + _cnt = ((Ice.ObjectPrxHelperBase)_proxy).handleException__(_delegate, exc, _cnt); + send__(); + return; } catch(Ice.LocalException) { } } } - + try { ice_exception(exc); @@ -212,15 +212,15 @@ namespace IceInternal } } } - + public bool timedOut__() { - long absoluteTimeoutMillis; + long absoluteTimeoutMillis; lock(_timeoutMutex) // MONO bug: Should be WaitOne(), but that's broken under Mono 1.0 for Linux. - { - absoluteTimeoutMillis = _absoluteTimeoutMillis; - } + { + absoluteTimeoutMillis = _absoluteTimeoutMillis; + } if(absoluteTimeoutMillis > 0) { @@ -247,24 +247,24 @@ namespace IceInternal Monitor.Wait(_monitor); } - // - // Can't call sync via a oneway proxy. - // - ((Ice.ObjectPrxHelperBase)prx).checkTwowayOnly__(operation); + // + // Can't call sync via a oneway proxy. + // + ((Ice.ObjectPrxHelperBase)prx).checkTwowayOnly__(operation); - _proxy = prx; + _proxy = prx; _delegate = null; _cnt = 0; _mode = mode; - Reference rf = ((Ice.ObjectPrxHelperBase)prx).reference__(); + Reference rf = ((Ice.ObjectPrxHelperBase)prx).reference__(); Debug.Assert(is__ == null); is__ = new BasicStream(rf.getInstance()); Debug.Assert(os__ == null); os__ = new BasicStream(rf.getInstance()); - os__.writeBlob(IceInternal.Protocol.requestHdr); - + os__.writeBlob(IceInternal.Protocol.requestHdr); + rf.getIdentity().write__(os__); // @@ -286,32 +286,32 @@ namespace IceInternal os__.writeByte((byte)mode); if(context != null) - { - // - // Explicit context - // - Ice.ContextHelper.write(os__, context); - } - else - { - // - // Implicit context - // - Ice.ImplicitContextI implicitContext = - rf.getInstance().getImplicitContext(); - - Ice.Context prxContext = rf.getContext(); - - if(implicitContext == null) - { - Ice.ContextHelper.write(os__, prxContext); - } - else - { - implicitContext.write(prxContext, os__); - } - } - + { + // + // Explicit context + // + Ice.ContextHelper.write(os__, context); + } + else + { + // + // Implicit context + // + Ice.ImplicitContextI implicitContext = + rf.getInstance().getImplicitContext(); + + Ice.Context prxContext = rf.getContext(); + + if(implicitContext == null) + { + Ice.ContextHelper.write(os__, prxContext); + } + else + { + implicitContext.write(prxContext, os__); + } + } + os__.startWriteEncaps(); } catch(Ice.LocalException) @@ -321,7 +321,7 @@ namespace IceInternal } } } - + protected void send__() { lock(_monitor) @@ -330,27 +330,27 @@ namespace IceInternal { while(true) { - bool comp; + bool comp; _delegate = ((Ice.ObjectPrxHelperBase)_proxy).getDelegate__(); - Ice.ConnectionI con = _delegate.getConnection__(out comp); + Ice.ConnectionI con = _delegate.getConnection__(out comp); // MONO bug: Should be WaitOne(), but that's broken under Mono 1.0 for Linux. - lock(_timeoutMutex) - { - if(con.timeout() >= 0) - { - _absoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + con.timeout(); - } - else - { - _absoluteTimeoutMillis = 0; - } - } - + lock(_timeoutMutex) + { + if(con.timeout() >= 0) + { + _absoluteTimeoutMillis = System.DateTime.Now.Ticks / 10000 + con.timeout(); + } + else + { + _absoluteTimeoutMillis = 0; + } + } + try { con.sendAsyncRequest(os__, this, comp); - + // // Don't do anything after sendAsyncRequest() returned // without an exception. I such case, there will be @@ -360,13 +360,13 @@ namespace IceInternal // return; } - catch(LocalExceptionWrapper ex) - { - ((Ice.ObjectPrxHelperBase)_proxy).handleExceptionWrapper__(_delegate, ex); - } + catch(LocalExceptionWrapper ex) + { + ((Ice.ObjectPrxHelperBase)_proxy).handleExceptionWrapper__(_delegate, ex); + } catch(Ice.LocalException ex) { - _cnt = ((Ice.ObjectPrxHelperBase)_proxy).handleException__(_delegate, ex, _cnt); + _cnt = ((Ice.ObjectPrxHelperBase)_proxy).handleException__(_delegate, ex, _cnt); } } } @@ -381,25 +381,25 @@ namespace IceInternal private void warning(System.Exception ex) { - if(os__ != null) // Don't print anything if cleanup() was already called. - { - Reference rf = ((Ice.ObjectPrxHelperBase)_proxy).reference__(); - if(rf.getInstance().initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.AMICallback", 1) > 0) - { - rf.getInstance().initializationData().logger.warning("exception raised by AMI callback:\n" + ex); - } - } + if(os__ != null) // Don't print anything if cleanup() was already called. + { + Reference rf = ((Ice.ObjectPrxHelperBase)_proxy).reference__(); + if(rf.getInstance().initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.AMICallback", 1) > 0) + { + rf.getInstance().initializationData().logger.warning("exception raised by AMI callback:\n" + ex); + } + } } private void cleanup() { - is__ = null; - os__ = null; + is__ = null; + os__ = null; Monitor.Pulse(_monitor); } - + protected BasicStream is__; protected BasicStream os__; @@ -451,8 +451,8 @@ namespace Ice } catch(LocalException ex) { - finished__(ex); - return; + finished__(ex); + return; } ice_response(ok, outParams); } diff --git a/cs/src/Ice/OutputBase.cs b/cs/src/Ice/OutputBase.cs index d9a3697874b..68923169481 100755 --- a/cs/src/Ice/OutputBase.cs +++ b/cs/src/Ice/OutputBase.cs @@ -19,166 +19,166 @@ public class OutputBase public OutputBase() { - out_ = null; - pos_ = 0; - indent_ = 0; - indentSize_ = 4; - useTab_ = true; - indentSave_ = new Stack(); - separator_ = true; + out_ = null; + pos_ = 0; + indent_ = 0; + indentSize_ = 4; + useTab_ = true; + indentSave_ = new Stack(); + separator_ = true; } public OutputBase(TextWriter writer) { - out_ = writer; - pos_ = 0; - indent_ = 0; - indentSize_ = 4; - useTab_ = true; - indentSave_ = new Stack(); - separator_ = true; + out_ = writer; + pos_ = 0; + indent_ = 0; + indentSize_ = 4; + useTab_ = true; + indentSave_ = new Stack(); + separator_ = true; } public OutputBase(string s) { - out_ = new StreamWriter(s); - pos_ = 0; - indent_ = 0; - indentSize_ = 4; - useTab_ = true; - indentSave_ = new Stack(); - separator_ = true; + out_ = new StreamWriter(s); + pos_ = 0; + indent_ = 0; + indentSize_ = 4; + useTab_ = true; + indentSave_ = new Stack(); + separator_ = true; } virtual public void setIndent(int indentSize) { - indentSize_ = indentSize; + indentSize_ = indentSize; } virtual public void setUseTab(bool useTab) { - useTab_ = useTab; + useTab_ = useTab; } public virtual void open(string s) { - try - { - out_ = new StreamWriter(s); - } - catch(IOException) - { - } + try + { + out_ = new StreamWriter(s); + } + catch(IOException) + { + } } public virtual void print(string s) { - char[] arr = s.ToCharArray(); - for(int i = 0; i < arr.Length; i++) - { - if(arr[i] == '\n') - { - pos_ = 0; - } - else - { - } - } - - out_.Write(s); + char[] arr = s.ToCharArray(); + for(int i = 0; i < arr.Length; i++) + { + if(arr[i] == '\n') + { + pos_ = 0; + } + else + { + } + } + + out_.Write(s); } public virtual void inc() { - indent_ += indentSize_; + indent_ += indentSize_; } public virtual void dec() { - Debug.Assert(indent_ >= indentSize_); - indent_ -= indentSize_; + Debug.Assert(indent_ >= indentSize_); + indent_ -= indentSize_; } public virtual void useCurrentPosAsIndent() { - indentSave_.Push(indent_); - indent_ = pos_; + indentSave_.Push(indent_); + indent_ = pos_; } public virtual void zeroIndent() { - indentSave_.Push(indent_); - indent_ = 0; + indentSave_.Push(indent_); + indent_ = 0; } public virtual void restoreIndent() { - Debug.Assert(indentSave_.Count != 0); - indent_ = (int)indentSave_.Pop(); + Debug.Assert(indentSave_.Count != 0); + indent_ = (int)indentSave_.Pop(); } public virtual void nl() { - out_.WriteLine(); - pos_ = 0; - separator_ = true; - - int indent = indent_; - - if(useTab_) - { - while(indent >= 8) - { - indent -= 8; - out_.Write('\t'); - pos_ += 8; - } - } - else - { - while(indent >= indentSize_) - { - indent -= indentSize_; - out_.Write(" "); - pos_ += indentSize_; - } - } - - while(indent > 0) - { - --indent; - out_.Write(" "); - ++pos_; - } - - out_.Flush(); + out_.WriteLine(); + pos_ = 0; + separator_ = true; + + int indent = indent_; + + if(useTab_) + { + while(indent >= 8) + { + indent -= 8; + out_.Write('\t'); + pos_ += 8; + } + } + else + { + while(indent >= indentSize_) + { + indent -= indentSize_; + out_.Write(" "); + pos_ += indentSize_; + } + } + + while(indent > 0) + { + --indent; + out_.Write(" "); + ++pos_; + } + + out_.Flush(); } public virtual void sp() { - if(separator_) - { - out_.WriteLine(); - } + if(separator_) + { + out_.WriteLine(); + } } public virtual bool valid() { - return out_ != null; + return out_ != null; } protected internal TextWriter out_; diff --git a/cs/src/Ice/OutputStream.cs b/cs/src/Ice/OutputStream.cs index b76949371d6..efd6bdca19b 100644 --- a/cs/src/Ice/OutputStream.cs +++ b/cs/src/Ice/OutputStream.cs @@ -11,51 +11,51 @@ namespace Ice { public interface OutputStream { - Communicator communicator(); + Communicator communicator(); - void writeBool(bool v); - void writeBoolSeq(bool[] v); + void writeBool(bool v); + void writeBoolSeq(bool[] v); - void writeByte(byte v); - void writeByteSeq(byte[] v); + void writeByte(byte v); + void writeByteSeq(byte[] v); - void writeShort(short v); - void writeShortSeq(short[] v); + void writeShort(short v); + void writeShortSeq(short[] v); - void writeInt(int v); - void writeIntSeq(int[] v); + void writeInt(int v); + void writeIntSeq(int[] v); - void writeLong(long v); - void writeLongSeq(long[] v); + void writeLong(long v); + void writeLongSeq(long[] v); - void writeFloat(float v); - void writeFloatSeq(float[] v); + void writeFloat(float v); + void writeFloatSeq(float[] v); - void writeDouble(double v); - void writeDoubleSeq(double[] v); + void writeDouble(double v); + void writeDoubleSeq(double[] v); - void writeString(string v); - void writeStringSeq(string[] v); + void writeString(string v); + void writeStringSeq(string[] v); - void writeSize(int sz); + void writeSize(int sz); - void writeProxy(ObjectPrx v); + void writeProxy(ObjectPrx v); - void writeObject(Ice.Object v); + void writeObject(Ice.Object v); - void writeTypeId(string id); + void writeTypeId(string id); - void writeException(UserException ex); + void writeException(UserException ex); - void startSlice(); - void endSlice(); + void startSlice(); + void endSlice(); - void startEncapsulation(); - void endEncapsulation(); + void startEncapsulation(); + void endEncapsulation(); - void writePendingObjects(); + void writePendingObjects(); - byte[] finished(); - void destroy(); + byte[] finished(); + void destroy(); } } diff --git a/cs/src/Ice/OutputStreamI.cs b/cs/src/Ice/OutputStreamI.cs index 9cb2c57298e..1286c68495e 100644 --- a/cs/src/Ice/OutputStreamI.cs +++ b/cs/src/Ice/OutputStreamI.cs @@ -11,165 +11,165 @@ namespace Ice { public class OutputStreamI : OutputStream { - public OutputStreamI(Communicator communicator) - { - _communicator = communicator; - _os = new IceInternal.BasicOutputStream(Util.getInstance(communicator), this); - } - - public Communicator communicator() - { - return _communicator; - } - - public void writeBool(bool v) - { - _os.writeBool(v); - } - - public void writeBoolSeq(bool[] v) - { - _os.writeBoolSeq(v); - } - - public void writeByte(byte v) - { - _os.writeByte(v); - } - - public void writeByteSeq(byte[] v) - { - _os.writeByteSeq(v); - } - - public void writeShort(short v) - { - _os.writeShort(v); - } - - public void writeShortSeq(short[] v) - { - _os.writeShortSeq(v); - } - - public void writeInt(int v) - { - _os.writeInt(v); - } - - public void writeIntSeq(int[] v) - { - _os.writeIntSeq(v); - } - - public void writeLong(long v) - { - _os.writeLong(v); - } - - public void writeLongSeq(long[] v) - { - _os.writeLongSeq(v); - } - - public void writeFloat(float v) - { - _os.writeFloat(v); - } - - public void writeFloatSeq(float[] v) - { - _os.writeFloatSeq(v); - } - - public void writeDouble(double v) - { - _os.writeDouble(v); - } - - public void writeDoubleSeq(double[] v) - { - _os.writeDoubleSeq(v); - } - - public void writeString(string v) - { - _os.writeString(v); - } - - public void writeStringSeq(string[] v) - { - _os.writeStringSeq(v); - } - - public void writeSize(int sz) - { - _os.writeSize(sz); - } - - public void writeProxy(ObjectPrx v) - { - _os.writeProxy(v); - } - - public void writeObject(Ice.Object v) - { - _os.writeObject(v); - } - - public void writeTypeId(string id) - { - _os.writeTypeId(id); - } - - public void writeException(UserException v) - { - _os.writeUserException(v); - } - - public void startSlice() - { - _os.startWriteSlice(); - } - - public void endSlice() - { - _os.endWriteSlice(); - } - - public void startEncapsulation() - { - _os.startWriteEncaps(); - } - - public void endEncapsulation() - { - _os.endWriteEncaps(); - } - - public void writePendingObjects() - { - _os.writePendingObjects(); - } - - public byte[] finished() - { - IceInternal.ByteBuffer buf = _os.prepareWrite(); - byte[] result = new byte[buf.limit()]; - buf.get(result); - - return result; - } - - public void destroy() - { - if(_os != null) - { - _os = null; - } - } - - private Communicator _communicator; - private IceInternal.BasicOutputStream _os; + public OutputStreamI(Communicator communicator) + { + _communicator = communicator; + _os = new IceInternal.BasicOutputStream(Util.getInstance(communicator), this); + } + + public Communicator communicator() + { + return _communicator; + } + + public void writeBool(bool v) + { + _os.writeBool(v); + } + + public void writeBoolSeq(bool[] v) + { + _os.writeBoolSeq(v); + } + + public void writeByte(byte v) + { + _os.writeByte(v); + } + + public void writeByteSeq(byte[] v) + { + _os.writeByteSeq(v); + } + + public void writeShort(short v) + { + _os.writeShort(v); + } + + public void writeShortSeq(short[] v) + { + _os.writeShortSeq(v); + } + + public void writeInt(int v) + { + _os.writeInt(v); + } + + public void writeIntSeq(int[] v) + { + _os.writeIntSeq(v); + } + + public void writeLong(long v) + { + _os.writeLong(v); + } + + public void writeLongSeq(long[] v) + { + _os.writeLongSeq(v); + } + + public void writeFloat(float v) + { + _os.writeFloat(v); + } + + public void writeFloatSeq(float[] v) + { + _os.writeFloatSeq(v); + } + + public void writeDouble(double v) + { + _os.writeDouble(v); + } + + public void writeDoubleSeq(double[] v) + { + _os.writeDoubleSeq(v); + } + + public void writeString(string v) + { + _os.writeString(v); + } + + public void writeStringSeq(string[] v) + { + _os.writeStringSeq(v); + } + + public void writeSize(int sz) + { + _os.writeSize(sz); + } + + public void writeProxy(ObjectPrx v) + { + _os.writeProxy(v); + } + + public void writeObject(Ice.Object v) + { + _os.writeObject(v); + } + + public void writeTypeId(string id) + { + _os.writeTypeId(id); + } + + public void writeException(UserException v) + { + _os.writeUserException(v); + } + + public void startSlice() + { + _os.startWriteSlice(); + } + + public void endSlice() + { + _os.endWriteSlice(); + } + + public void startEncapsulation() + { + _os.startWriteEncaps(); + } + + public void endEncapsulation() + { + _os.endWriteEncaps(); + } + + public void writePendingObjects() + { + _os.writePendingObjects(); + } + + public byte[] finished() + { + IceInternal.ByteBuffer buf = _os.prepareWrite(); + byte[] result = new byte[buf.limit()]; + buf.get(result); + + return result; + } + + public void destroy() + { + if(_os != null) + { + _os = null; + } + } + + private Communicator _communicator; + private IceInternal.BasicOutputStream _os; } } diff --git a/cs/src/Ice/Patcher.cs b/cs/src/Ice/Patcher.cs index 4e3d64d2fad..b2aab24e934 100755 --- a/cs/src/Ice/Patcher.cs +++ b/cs/src/Ice/Patcher.cs @@ -24,7 +24,7 @@ namespace IceInternal type_ = type; } - public abstract void patch(Ice.Object v); + public abstract void patch(Ice.Object v); public virtual string type() { @@ -32,57 +32,57 @@ namespace IceInternal return type_.FullName; } - public virtual void invoke(Ice.Object v) - { - patch(v); - } + public virtual void invoke(Ice.Object v) + { + patch(v); + } protected System.Type type_; } public sealed class ParamPatcher : Patcher { - public ParamPatcher(System.Type type, string expectedSliceType) : base(type) - { - _expectedSliceType = expectedSliceType; - } + public ParamPatcher(System.Type type, string expectedSliceType) : base(type) + { + _expectedSliceType = expectedSliceType; + } - public override void patch(Ice.Object v) - { + public override void patch(Ice.Object v) + { Debug.Assert(type_ != null); - if(v != null && !type_.IsInstanceOfType(v)) - { - Ice.UnexpectedObjectException ex = new Ice.UnexpectedObjectException( - "unexpected class instance of type `" + v.ice_id() - + "'; expected instance of type '" + _expectedSliceType + "'"); - ex.type = v.ice_id(); - ex.expectedType = _expectedSliceType; - } - value = v; - } + if(v != null && !type_.IsInstanceOfType(v)) + { + Ice.UnexpectedObjectException ex = new Ice.UnexpectedObjectException( + "unexpected class instance of type `" + v.ice_id() + + "'; expected instance of type '" + _expectedSliceType + "'"); + ex.type = v.ice_id(); + ex.expectedType = _expectedSliceType; + } + value = v; + } - public Ice.Object value; - private string _expectedSliceType; + public Ice.Object value; + private string _expectedSliceType; } public sealed class SequencePatcher : Patcher { - public SequencePatcher(ICollection seq, System.Type type, int index) : base(type) - { - _seq = seq; - _index = index; - } + public SequencePatcher(ICollection seq, System.Type type, int index) : base(type) + { + _seq = seq; + _index = index; + } private static object dummyObject = new object(); - public override void patch(Ice.Object v) - { - Debug.Assert(type_ != null); - if(v != null && !type_.IsInstanceOfType(v)) - { - throw new System.InvalidCastException("expected element of type " + type() + - " but received " + v.GetType().FullName); - } + public override void patch(Ice.Object v) + { + Debug.Assert(type_ != null); + if(v != null && !type_.IsInstanceOfType(v)) + { + throw new System.InvalidCastException("expected element of type " + type() + + " but received " + v.GetType().FullName); + } try { @@ -96,36 +96,36 @@ namespace IceInternal } } - // - // Ugly work-around for broken CollectionBase implementation: - // - // CollectionBase provides implementations of the IList.Add method - // and indexer. However, stupidly, these implementations do not permit - // null to be added or assigned even though, according to the doc, this should work. - // (Attempts to put a null into the collection raise ArgumentNullException.) - // That's why the above code grows the sequence by adding a dummy object. - // - // Furthermore, CollectionBase.Add and the indexer are (incorrectly) non-virtual so, - // when we treat _seq as an IList, we always dispatch into the CollectionBase - // implementation, not into the implementation of the generated sequence type. - // This makes it impossible to assign v to a sequence element if v is null. - // - // The ugly work-around is to use reflection to ensure that we get the - // actual run-time type of the generated sequence, and then - // use dynamic invocation to make sure that we dispatch to the generated indexer, - // instead of the broken indexer provided by CollectionBase. - // - if(v == null) - { - object[] ov = new object[2]; - ov[0] = _index; - ov[1] = null; - _seq.GetType().GetProperty("Item").GetSetMethod().Invoke(_seq, ov); - } - else - { - ((IList)_seq)[_index] = v; - } + // + // Ugly work-around for broken CollectionBase implementation: + // + // CollectionBase provides implementations of the IList.Add method + // and indexer. However, stupidly, these implementations do not permit + // null to be added or assigned even though, according to the doc, this should work. + // (Attempts to put a null into the collection raise ArgumentNullException.) + // That's why the above code grows the sequence by adding a dummy object. + // + // Furthermore, CollectionBase.Add and the indexer are (incorrectly) non-virtual so, + // when we treat _seq as an IList, we always dispatch into the CollectionBase + // implementation, not into the implementation of the generated sequence type. + // This makes it impossible to assign v to a sequence element if v is null. + // + // The ugly work-around is to use reflection to ensure that we get the + // actual run-time type of the generated sequence, and then + // use dynamic invocation to make sure that we dispatch to the generated indexer, + // instead of the broken indexer provided by CollectionBase. + // + if(v == null) + { + object[] ov = new object[2]; + ov[0] = _index; + ov[1] = null; + _seq.GetType().GetProperty("Item").GetSetMethod().Invoke(_seq, ov); + } + else + { + ((IList)_seq)[_index] = v; + } } else { @@ -136,9 +136,9 @@ namespace IceInternal { throw new Ice.MarshalException("Unexpected failure during patching", ex); } - } + } - private ICollection _seq; - private int _index; + private ICollection _seq; + private int _index; } } diff --git a/cs/src/Ice/PluginManagerI.cs b/cs/src/Ice/PluginManagerI.cs index f5e34a2aa59..95a032f4eb8 100755 --- a/cs/src/Ice/PluginManagerI.cs +++ b/cs/src/Ice/PluginManagerI.cs @@ -79,7 +79,7 @@ namespace Ice { throw new CommunicatorDestroyedException(); } - + Plugin p = (Plugin)_plugins[name]; if(p != null) { @@ -100,7 +100,7 @@ namespace Ice { throw new CommunicatorDestroyedException(); } - + if(_plugins.Contains(name)) { AlreadyRegisteredException ex = new AlreadyRegisteredException(); @@ -122,13 +122,13 @@ namespace Ice { plugin.destroy(); } - - _logger = null; + + _logger = null; _communicator = null; } } } - + public PluginManagerI(Communicator communicator) { _communicator = communicator; @@ -140,7 +140,7 @@ namespace Ice public void loadPlugins(ref string[] cmdArgs) { Debug.Assert(_communicator != null); - + // // Load and initialize the plug-ins defined in the property set // with the prefix "Ice.Plugin.". These properties should @@ -206,14 +206,14 @@ namespace Ice loadPlugin(name, val, ref cmdArgs, false); } - // - // Check for a Logger Plugin - // - string loggerStr = properties.getProperty("Ice.LoggerPlugin"); - if(loggerStr.Length != 0) - { - loadPlugin("Logger", loggerStr, ref cmdArgs, true); - } + // + // Check for a Logger Plugin + // + string loggerStr = properties.getProperty("Ice.LoggerPlugin"); + if(loggerStr.Length != 0) + { + loadPlugin("Logger", loggerStr, ref cmdArgs, true); + } // // An application can set Ice.InitPlugins=0 if it wants to postpone @@ -225,7 +225,7 @@ namespace Ice initializePlugins(); } } - + private void loadPlugin(string name, string pluginSpec, ref string[] cmdArgs, bool isLogger) { Debug.Assert(_communicator != null); @@ -243,16 +243,16 @@ namespace Ice int start = pluginSpec.IndexOf(':'); if(start != -1) { - // - // Skip drive letter, if any. - // - if(pluginSpec.Length > 3 && - start == 1 && - System.Char.IsLetter(pluginSpec[0]) && - (pluginSpec[2] == '\\' || pluginSpec[2] == '/')) - { - start = pluginSpec.IndexOf(':', 3); - } + // + // Skip drive letter, if any. + // + if(pluginSpec.Length > 3 && + start == 1 && + System.Char.IsLetter(pluginSpec[0]) && + (pluginSpec[2] == '\\' || pluginSpec[2] == '/')) + { + start = pluginSpec.IndexOf(':', 3); + } // // Find the whitespace. @@ -273,7 +273,7 @@ namespace Ice args = pluginSpec.Substring(pos).Trim().Split(delims, pos); } } - + // // Convert command-line options into properties. First // we convert the options from the plug-in @@ -283,7 +283,7 @@ namespace Ice Properties properties = _communicator.getProperties(); args = properties.parseCommandLineOptions(name, args); cmdArgs = properties.parseCommandLineOptions(name, cmdArgs); - + // // Retrieve the assembly name and the type. // @@ -295,7 +295,7 @@ namespace Ice e.reason = err + "invalid entry point format"; throw e; } - + System.Reflection.Assembly pluginAssembly = null; string assemblyName = entryPoint.Substring(0, sepPos); try @@ -330,14 +330,14 @@ namespace Ice e.reason = err + "unable to load assembly: '" + assemblyName + "': " + ex.ToString(); throw e; } - - // - // Instantiate the class. - // - PluginFactory pluginFactory = null; - LoggerFactory loggerFactory = null; - string className = entryPoint.Substring(sepPos + 1); - System.Type c = pluginAssembly.GetType(className); + + // + // Instantiate the class. + // + PluginFactory pluginFactory = null; + LoggerFactory loggerFactory = null; + string className = entryPoint.Substring(sepPos + 1); + System.Type c = pluginAssembly.GetType(className); if(c == null) { PluginInitializationException e = new PluginInitializationException(); @@ -345,118 +345,118 @@ namespace Ice throw e; } - try - { - if(isLogger) - { - loggerFactory = (LoggerFactory)IceInternal.AssemblyUtil.createInstance(c); - if(loggerFactory == null) - { - PluginInitializationException e = new PluginInitializationException(); - e.reason = err + "Can't find constructor for '" + className + "'"; - throw e; - } - } - else - { - pluginFactory = (PluginFactory)IceInternal.AssemblyUtil.createInstance(c); - if(pluginFactory == null) - { - PluginInitializationException e = new PluginInitializationException(); - e.reason = err + "Can't find constructor for '" + className + "'"; - throw e; - } - } - } - catch(System.InvalidCastException ex) - { - PluginInitializationException e = new PluginInitializationException(ex); - e.reason = err + "InvalidCastException to " + (isLogger ? "Ice.LoggerFactory" : "Ice.PluginFactory"); - throw e; - } - catch(System.UnauthorizedAccessException ex) - { - PluginInitializationException e = new PluginInitializationException(ex); - e.reason = err + "UnauthorizedAccessException: " + ex.ToString(); - throw e; - } - catch(System.Exception ex) - { - PluginInitializationException e = new PluginInitializationException(ex); - e.reason = err + "System.Exception: " + ex.ToString(); - throw e; - } - - // - // Invoke the factory. - // - if(isLogger) - { - try - { - _logger = loggerFactory.create(_communicator, args); - } - catch(PluginInitializationException ex) - { - ex.reason = err + ex.reason; - throw ex; - } - catch(System.Exception ex) - { - PluginInitializationException e = new PluginInitializationException(ex); - e.reason = err + "System.Exception in factory.create: " + ex.ToString(); - throw e; - } - - if(_logger == null) - { - PluginInitializationException ex = new PluginInitializationException(); - ex.reason = err + "factory.create returned null logger"; - throw ex; - } - } - else - { - Plugin plugin = null; - try - { - plugin = pluginFactory.create(_communicator, name, args); - } - catch(PluginInitializationException ex) - { - ex.reason = err + ex.reason; - throw ex; - } - catch(System.Exception ex) - { - PluginInitializationException e = new PluginInitializationException(ex); - e.reason = err + "System.Exception in factory.create: " + ex.ToString(); - throw e; - } - - if(plugin == null) - { - PluginInitializationException ex = new PluginInitializationException(); - ex.reason = err + "factory.create returned null plug-in"; - throw ex; - } + try + { + if(isLogger) + { + loggerFactory = (LoggerFactory)IceInternal.AssemblyUtil.createInstance(c); + if(loggerFactory == null) + { + PluginInitializationException e = new PluginInitializationException(); + e.reason = err + "Can't find constructor for '" + className + "'"; + throw e; + } + } + else + { + pluginFactory = (PluginFactory)IceInternal.AssemblyUtil.createInstance(c); + if(pluginFactory == null) + { + PluginInitializationException e = new PluginInitializationException(); + e.reason = err + "Can't find constructor for '" + className + "'"; + throw e; + } + } + } + catch(System.InvalidCastException ex) + { + PluginInitializationException e = new PluginInitializationException(ex); + e.reason = err + "InvalidCastException to " + (isLogger ? "Ice.LoggerFactory" : "Ice.PluginFactory"); + throw e; + } + catch(System.UnauthorizedAccessException ex) + { + PluginInitializationException e = new PluginInitializationException(ex); + e.reason = err + "UnauthorizedAccessException: " + ex.ToString(); + throw e; + } + catch(System.Exception ex) + { + PluginInitializationException e = new PluginInitializationException(ex); + e.reason = err + "System.Exception: " + ex.ToString(); + throw e; + } + + // + // Invoke the factory. + // + if(isLogger) + { + try + { + _logger = loggerFactory.create(_communicator, args); + } + catch(PluginInitializationException ex) + { + ex.reason = err + ex.reason; + throw ex; + } + catch(System.Exception ex) + { + PluginInitializationException e = new PluginInitializationException(ex); + e.reason = err + "System.Exception in factory.create: " + ex.ToString(); + throw e; + } + + if(_logger == null) + { + PluginInitializationException ex = new PluginInitializationException(); + ex.reason = err + "factory.create returned null logger"; + throw ex; + } + } + else + { + Plugin plugin = null; + try + { + plugin = pluginFactory.create(_communicator, name, args); + } + catch(PluginInitializationException ex) + { + ex.reason = err + ex.reason; + throw ex; + } + catch(System.Exception ex) + { + PluginInitializationException e = new PluginInitializationException(ex); + e.reason = err + "System.Exception in factory.create: " + ex.ToString(); + throw e; + } + + if(plugin == null) + { + PluginInitializationException ex = new PluginInitializationException(); + ex.reason = err + "factory.create returned null plug-in"; + throw ex; + } - _plugins[name] = plugin; - _initOrder.Add(plugin); - } - } + _plugins[name] = plugin; + _initOrder.Add(plugin); + } + } - public Logger - getLogger() - { - return _logger; - } - - private Communicator _communicator; - private Hashtable _plugins; - private ArrayList _initOrder; - private Logger _logger = null; - private bool _initialized; - private static bool _sslWarnOnce = false; + public Logger + getLogger() + { + return _logger; + } + + private Communicator _communicator; + private Hashtable _plugins; + private ArrayList _initOrder; + private Logger _logger = null; + private bool _initialized; + private static bool _sslWarnOnce = false; } } diff --git a/cs/src/Ice/PropertiesI.cs b/cs/src/Ice/PropertiesI.cs index 49c370c0b1f..8a4f9403f2c 100755 --- a/cs/src/Ice/PropertiesI.cs +++ b/cs/src/Ice/PropertiesI.cs @@ -15,372 +15,372 @@ namespace Ice { sealed class PropertiesI : LocalObjectImpl, Properties { - public string getProperty(string key) - { - lock(this) - { - string result = _properties[key]; - if(result == null) - { - result = ""; - } - return result; - } - } - - public string getPropertyWithDefault(string key, string val) - { - lock(this) - { - string result = _properties[key]; - if(result == null) - { - result = val; - } - return result; - } - } - - public int getPropertyAsInt(string key) - { - return getPropertyAsIntWithDefault(key, 0); - } - - public int getPropertyAsIntWithDefault(string key, int val) - { - lock(this) - { - string result = _properties[key]; - if(result == null) - { - return val; - } - try - { - return System.Int32.Parse(result); - } - catch(System.FormatException) - { - return val; - } - } - } - - public Ice.PropertyDict getPropertiesForPrefix(string prefix) - { - lock(this) - { - Ice.PropertyDict result = new Ice.PropertyDict(); + public string getProperty(string key) + { + lock(this) + { + string result = _properties[key]; + if(result == null) + { + result = ""; + } + return result; + } + } + + public string getPropertyWithDefault(string key, string val) + { + lock(this) + { + string result = _properties[key]; + if(result == null) + { + result = val; + } + return result; + } + } + + public int getPropertyAsInt(string key) + { + return getPropertyAsIntWithDefault(key, 0); + } + + public int getPropertyAsIntWithDefault(string key, int val) + { + lock(this) + { + string result = _properties[key]; + if(result == null) + { + return val; + } + try + { + return System.Int32.Parse(result); + } + catch(System.FormatException) + { + return val; + } + } + } + + public Ice.PropertyDict getPropertiesForPrefix(string prefix) + { + lock(this) + { + Ice.PropertyDict result = new Ice.PropertyDict(); - foreach(string s in _properties.Keys) - { - if(prefix.Length == 0 || s.StartsWith(prefix)) - { - result[s] = _properties[s]; - } - } - return result; - } - } - - public void setProperty(string key, string val) - { - if(key == null || key.Length == 0) - { - return; - } + foreach(string s in _properties.Keys) + { + if(prefix.Length == 0 || s.StartsWith(prefix)) + { + result[s] = _properties[s]; + } + } + return result; + } + } + + public void setProperty(string key, string val) + { + if(key == null || key.Length == 0) + { + return; + } - // - // Check if the property is legal. - // - Logger logger = Ice.Util.getProcessLogger(); - int dotPos = key.IndexOf('.'); - if(dotPos != -1) - { - string prefix = key.Substring(0, dotPos); - for(int i = 0; IceInternal.PropertyNames.validProps[i] != null; ++i) - { - string pattern = IceInternal.PropertyNames.validProps[i][0]; - dotPos = pattern.IndexOf('.'); - Debug.Assert(dotPos != -1); - string propPrefix = pattern.Substring(1, dotPos - 2); - if(!propPrefix.Equals(prefix)) - { - continue; - } + // + // Check if the property is legal. + // + Logger logger = Ice.Util.getProcessLogger(); + int dotPos = key.IndexOf('.'); + if(dotPos != -1) + { + string prefix = key.Substring(0, dotPos); + for(int i = 0; IceInternal.PropertyNames.validProps[i] != null; ++i) + { + string pattern = IceInternal.PropertyNames.validProps[i][0]; + dotPos = pattern.IndexOf('.'); + Debug.Assert(dotPos != -1); + string propPrefix = pattern.Substring(1, dotPos - 2); + if(!propPrefix.Equals(prefix)) + { + continue; + } - bool found = false; - for(int j = 0; IceInternal.PropertyNames.validProps[i][j] != null && !found; ++j) - { - Regex r = new Regex(IceInternal.PropertyNames.validProps[i][j]); - Match m = r.Match(key); - found = m.Success; - } - if(!found) - { - logger.warning("unknown property: " + key); - } - } - } + bool found = false; + for(int j = 0; IceInternal.PropertyNames.validProps[i][j] != null && !found; ++j) + { + Regex r = new Regex(IceInternal.PropertyNames.validProps[i][j]); + Match m = r.Match(key); + found = m.Success; + } + if(!found) + { + logger.warning("unknown property: " + key); + } + } + } - lock(this) - { - // - // - // Set or clear the property. - // - if(val != null && val.Length > 0) - { - _properties[key] = val; - } - else - { - _properties.Remove(key); - } - } - } - - public string[] getCommandLineOptions() - { - lock(this) - { - string[] result = new string[_properties.Count]; + lock(this) + { + // + // + // Set or clear the property. + // + if(val != null && val.Length > 0) + { + _properties[key] = val; + } + else + { + _properties.Remove(key); + } + } + } + + public string[] getCommandLineOptions() + { + lock(this) + { + string[] result = new string[_properties.Count]; int i = 0; - foreach(DictionaryEntry entry in _properties) - { - result[i++] = "--" + entry.Key + "=" + entry.Value; - } - return result; - } - } + foreach(DictionaryEntry entry in _properties) + { + result[i++] = "--" + entry.Key + "=" + entry.Value; + } + return result; + } + } - public string[] parseCommandLineOptions(string pfx, string[] options) - { - if(pfx.Length > 0 && pfx[pfx.Length - 1] != '.') - { - pfx += '.'; - } - pfx = "--" + pfx; + public string[] parseCommandLineOptions(string pfx, string[] options) + { + if(pfx.Length > 0 && pfx[pfx.Length - 1] != '.') + { + pfx += '.'; + } + pfx = "--" + pfx; - ArrayList result = new ArrayList(); - for(int i = 0; i < options.Length; i++) - { - string opt = options[i]; - if(opt.StartsWith(pfx)) - { - if(opt.IndexOf('=') == -1) - { - opt += "=1"; - } + ArrayList result = new ArrayList(); + for(int i = 0; i < options.Length; i++) + { + string opt = options[i]; + if(opt.StartsWith(pfx)) + { + if(opt.IndexOf('=') == -1) + { + opt += "=1"; + } - parseLine(opt.Substring(2)); - } - else - { - result.Add(opt); - } - } - string[] arr = new string[result.Count]; - if(arr.Length != 0) - { - result.CopyTo(arr); - } - return arr; - } - - public string[] parseIceCommandLineOptions(string[] options) - { - string[] args = options; - for(int i = 0; IceInternal.PropertyNames.clPropNames[i] != null; ++i) - { - args = parseCommandLineOptions(IceInternal.PropertyNames.clPropNames[i], args); - } - return args; - } - - public void load(string file) - { - try - { - using(System.IO.StreamReader sr = new System.IO.StreamReader(file)) - { - parse(sr); - } - } - catch(System.IO.IOException ex) - { - Ice.FileException fe = new Ice.FileException(ex); - fe.path = file; - throw fe; - } - } - - public Properties ice_clone_() - { - lock(this) - { - return new PropertiesI(this); - } - } - - internal PropertiesI(PropertiesI p) - { - _properties = (PropertyDict)p._properties.Clone(); - } + parseLine(opt.Substring(2)); + } + else + { + result.Add(opt); + } + } + string[] arr = new string[result.Count]; + if(arr.Length != 0) + { + result.CopyTo(arr); + } + return arr; + } + + public string[] parseIceCommandLineOptions(string[] options) + { + string[] args = options; + for(int i = 0; IceInternal.PropertyNames.clPropNames[i] != null; ++i) + { + args = parseCommandLineOptions(IceInternal.PropertyNames.clPropNames[i], args); + } + return args; + } + + public void load(string file) + { + try + { + using(System.IO.StreamReader sr = new System.IO.StreamReader(file)) + { + parse(sr); + } + } + catch(System.IO.IOException ex) + { + Ice.FileException fe = new Ice.FileException(ex); + fe.path = file; + throw fe; + } + } + + public Properties ice_clone_() + { + lock(this) + { + return new PropertiesI(this); + } + } + + internal PropertiesI(PropertiesI p) + { + _properties = (PropertyDict)p._properties.Clone(); + } - internal PropertiesI() - { - _properties = new PropertyDict(); - } - - internal PropertiesI(ref string[] args, Properties defaults) - { - if(defaults == null) - { - _properties = new PropertyDict(); - } - else - { - _properties = defaults.getPropertiesForPrefix(""); - } - - if(_properties["Ice.ProgramName"] == null) - { - setProperty("Ice.ProgramName", System.AppDomain.CurrentDomain.FriendlyName); - } + internal PropertiesI() + { + _properties = new PropertyDict(); + } + + internal PropertiesI(ref string[] args, Properties defaults) + { + if(defaults == null) + { + _properties = new PropertyDict(); + } + else + { + _properties = defaults.getPropertiesForPrefix(""); + } + + if(_properties["Ice.ProgramName"] == null) + { + setProperty("Ice.ProgramName", System.AppDomain.CurrentDomain.FriendlyName); + } - bool loadConfigFiles = false; + bool loadConfigFiles = false; - for(int i = 0; i < args.Length; i++) - { - if(args[i].StartsWith("--Ice.Config")) - { - string line = args[i]; - if(line.IndexOf('=') == -1) - { - line += "=1"; - } - parseLine(line.Substring(2)); - loadConfigFiles = true; + for(int i = 0; i < args.Length; i++) + { + if(args[i].StartsWith("--Ice.Config")) + { + string line = args[i]; + if(line.IndexOf('=') == -1) + { + line += "=1"; + } + parseLine(line.Substring(2)); + loadConfigFiles = true; - string[] arr = new string[args.Length - 1]; - System.Array.Copy(args, 0, arr, 0, i); - if(i < args.Length - 1) - { - System.Array.Copy(args, i + 1, arr, i, args.Length - i - 1); - } - args = arr; - } - } + string[] arr = new string[args.Length - 1]; + System.Array.Copy(args, 0, arr, 0, i); + if(i < args.Length - 1) + { + System.Array.Copy(args, i + 1, arr, i, args.Length - i - 1); + } + args = arr; + } + } - if(!loadConfigFiles) - { - // - // If Ice.Config is not set, load from ICE_CONFIG (if set) - // - loadConfigFiles = (_properties["Ice.Config"] == null); - } - - if(loadConfigFiles) - { - loadConfig(); - } - - args = parseIceCommandLineOptions(args); - } - - private void parse(System.IO.StreamReader input) - { - try - { - string line; - while((line = input.ReadLine()) != null) - { - parseLine(line); - } - } - catch(System.IO.IOException ex) - { - SyscallException se = new SyscallException(ex); - throw se; - } - } - - private void parseLine(string line) - { - string s = line; - - int hash = s.IndexOf('#'); - if(hash == 0) - { - return; // ignore comment lines - } - else if(hash != - 1) - { - s = s.Substring(0, (hash) - (0)); - } - - s = s.Trim(); - - char[] arr = s.ToCharArray(); - int end = -1; - for(int i = 0; i < arr.Length; i++) - { - if(arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\r' || arr[i] == '\n' || arr[i] == '=') - { - end = i; - break; - } - } - if(end == -1) - { - return; - } - - string key = s.Substring(0, end); - - end = s.IndexOf('=', end); - if(end == -1) - { - return; - } - ++end; - - string val = ""; - if(end < s.Length) - { - val = s.Substring(end).Trim(); - } - - setProperty(key, val); - } - - private void loadConfig() - { - string val = getProperty("Ice.Config"); - - if(val.Length == 0 || val.Equals("1")) - { - string s = System.Environment.GetEnvironmentVariable("ICE_CONFIG"); - if(s != null && s.Length != 0) - { - val = s; - } - } - - if(val.Length > 0) - { - char[] separator = { ',' }; - string[] files = val.Split(separator); - for(int i = 0; i < files.Length; i++) - { - load(files[i]); - } - } - - setProperty("Ice.Config", val); - } - - private Ice.PropertyDict _properties; + if(!loadConfigFiles) + { + // + // If Ice.Config is not set, load from ICE_CONFIG (if set) + // + loadConfigFiles = (_properties["Ice.Config"] == null); + } + + if(loadConfigFiles) + { + loadConfig(); + } + + args = parseIceCommandLineOptions(args); + } + + private void parse(System.IO.StreamReader input) + { + try + { + string line; + while((line = input.ReadLine()) != null) + { + parseLine(line); + } + } + catch(System.IO.IOException ex) + { + SyscallException se = new SyscallException(ex); + throw se; + } + } + + private void parseLine(string line) + { + string s = line; + + int hash = s.IndexOf('#'); + if(hash == 0) + { + return; // ignore comment lines + } + else if(hash != - 1) + { + s = s.Substring(0, (hash) - (0)); + } + + s = s.Trim(); + + char[] arr = s.ToCharArray(); + int end = -1; + for(int i = 0; i < arr.Length; i++) + { + if(arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\r' || arr[i] == '\n' || arr[i] == '=') + { + end = i; + break; + } + } + if(end == -1) + { + return; + } + + string key = s.Substring(0, end); + + end = s.IndexOf('=', end); + if(end == -1) + { + return; + } + ++end; + + string val = ""; + if(end < s.Length) + { + val = s.Substring(end).Trim(); + } + + setProperty(key, val); + } + + private void loadConfig() + { + string val = getProperty("Ice.Config"); + + if(val.Length == 0 || val.Equals("1")) + { + string s = System.Environment.GetEnvironmentVariable("ICE_CONFIG"); + if(s != null && s.Length != 0) + { + val = s; + } + } + + if(val.Length > 0) + { + char[] separator = { ',' }; + string[] files = val.Split(separator); + for(int i = 0; i < files.Length; i++) + { + load(files[i]); + } + } + + setProperty("Ice.Config", val); + } + + private Ice.PropertyDict _properties; } } diff --git a/cs/src/Ice/Protocol.cs b/cs/src/Ice/Protocol.cs index ad82b545b71..8b17cc5eb82 100755 --- a/cs/src/Ice/Protocol.cs +++ b/cs/src/Ice/Protocol.cs @@ -12,78 +12,78 @@ namespace IceInternal sealed class Protocol { - // - // Size of the Ice protocol header - // - // Magic number (4 bytes) - // Protocol version major (Byte) - // Protocol version minor (Byte) - // Encoding version major (Byte) - // Encoding version minor (Byte) - // Message type (Byte) - // Compression status (Byte) - // Message size (Int) - // - internal const int headerSize = 14; - - // - // The magic number at the front of each message - // - internal static readonly byte[] magic - = new byte[] { (byte)0x49, (byte)0x63, (byte)0x65, (byte)0x50 }; // 'I', 'c', 'e', 'P' - - // - // The current Ice protocol and encoding version - // - internal const byte protocolMajor = 1; - internal const byte protocolMinor = 0; - internal const byte encodingMajor = 1; - internal const byte encodingMinor = 0; - - // - // The Ice protocol message types - // - internal const byte requestMsg = 0; - internal const byte requestBatchMsg = 1; - internal const byte replyMsg = 2; - internal const byte validateConnectionMsg = 3; - internal const byte closeConnectionMsg = 4; + // + // Size of the Ice protocol header + // + // Magic number (4 bytes) + // Protocol version major (Byte) + // Protocol version minor (Byte) + // Encoding version major (Byte) + // Encoding version minor (Byte) + // Message type (Byte) + // Compression status (Byte) + // Message size (Int) + // + internal const int headerSize = 14; + + // + // The magic number at the front of each message + // + internal static readonly byte[] magic + = new byte[] { (byte)0x49, (byte)0x63, (byte)0x65, (byte)0x50 }; // 'I', 'c', 'e', 'P' + + // + // The current Ice protocol and encoding version + // + internal const byte protocolMajor = 1; + internal const byte protocolMinor = 0; + internal const byte encodingMajor = 1; + internal const byte encodingMinor = 0; + + // + // The Ice protocol message types + // + internal const byte requestMsg = 0; + internal const byte requestBatchMsg = 1; + internal const byte replyMsg = 2; + internal const byte validateConnectionMsg = 3; + internal const byte closeConnectionMsg = 4; - internal static readonly byte[] requestHdr = new byte[] - { - IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], - IceInternal.Protocol.magic[3], - IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, - IceInternal.Protocol.encodingMajor, IceInternal.Protocol.encodingMinor, - IceInternal.Protocol.requestMsg, - (byte)0, // Compression status. - (byte)0, (byte)0, (byte)0, (byte)0, // Message size (placeholder). - (byte)0, (byte)0, (byte)0, (byte)0 // Request ID (placeholder). - }; + internal static readonly byte[] requestHdr = new byte[] + { + IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], + IceInternal.Protocol.magic[3], + IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, + IceInternal.Protocol.encodingMajor, IceInternal.Protocol.encodingMinor, + IceInternal.Protocol.requestMsg, + (byte)0, // Compression status. + (byte)0, (byte)0, (byte)0, (byte)0, // Message size (placeholder). + (byte)0, (byte)0, (byte)0, (byte)0 // Request ID (placeholder). + }; - internal static readonly byte[] requestBatchHdr = new byte[] - { - IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], - IceInternal.Protocol.magic[3], - IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, - IceInternal.Protocol.encodingMajor, IceInternal.Protocol.encodingMinor, - IceInternal.Protocol.requestBatchMsg, - (byte)0, // Compression status. - (byte)0, (byte)0, (byte)0, (byte)0, // Message size (placeholder). - (byte)0, (byte)0, (byte)0, (byte)0 // Number of requests in batch (placeholder). - }; - - internal static readonly byte[] replyHdr = new byte[] - { - IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], - IceInternal.Protocol.magic[3], - IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, - IceInternal.Protocol.encodingMajor, IceInternal.Protocol.encodingMinor, - IceInternal.Protocol.replyMsg, - (byte)0, // Compression status. - (byte)0, (byte)0, (byte)0, (byte)0 // Message size (placeholder). - }; - + internal static readonly byte[] requestBatchHdr = new byte[] + { + IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], + IceInternal.Protocol.magic[3], + IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, + IceInternal.Protocol.encodingMajor, IceInternal.Protocol.encodingMinor, + IceInternal.Protocol.requestBatchMsg, + (byte)0, // Compression status. + (byte)0, (byte)0, (byte)0, (byte)0, // Message size (placeholder). + (byte)0, (byte)0, (byte)0, (byte)0 // Number of requests in batch (placeholder). + }; + + internal static readonly byte[] replyHdr = new byte[] + { + IceInternal.Protocol.magic[0], IceInternal.Protocol.magic[1], IceInternal.Protocol.magic[2], + IceInternal.Protocol.magic[3], + IceInternal.Protocol.protocolMajor, IceInternal.Protocol.protocolMinor, + IceInternal.Protocol.encodingMajor, IceInternal.Protocol.encodingMinor, + IceInternal.Protocol.replyMsg, + (byte)0, // Compression status. + (byte)0, (byte)0, (byte)0, (byte)0 // Message size (placeholder). + }; + } } diff --git a/cs/src/Ice/ProtocolPluginFacade.cs b/cs/src/Ice/ProtocolPluginFacade.cs index 1d2df8bd1ae..1da53a9c0cb 100644 --- a/cs/src/Ice/ProtocolPluginFacade.cs +++ b/cs/src/Ice/ProtocolPluginFacade.cs @@ -11,77 +11,77 @@ namespace IceInternal { public interface ProtocolPluginFacade { - // - // Get the Communicator instance with which this facade is - // associated. - // - Ice.Communicator getCommunicator(); + // + // Get the Communicator instance with which this facade is + // associated. + // + Ice.Communicator getCommunicator(); - // - // Get the default hostname to be used in endpoints. - // - string getDefaultHost(); + // + // Get the default hostname to be used in endpoints. + // + string getDefaultHost(); - // - // Get the network trace level and category name. - // - int getNetworkTraceLevel(); - string getNetworkTraceCategory(); + // + // Get the network trace level and category name. + // + int getNetworkTraceLevel(); + string getNetworkTraceCategory(); - // - // Register an EndpointFactory. - // - void addEndpointFactory(EndpointFactory factory); + // + // Register an EndpointFactory. + // + void addEndpointFactory(EndpointFactory factory); } public sealed class ProtocolPluginFacadeI : ProtocolPluginFacade { - public - ProtocolPluginFacadeI(Ice.Communicator communicator) - { - _communicator = communicator; - _instance = Ice.Util.getInstance(communicator); - } + public + ProtocolPluginFacadeI(Ice.Communicator communicator) + { + _communicator = communicator; + _instance = Ice.Util.getInstance(communicator); + } - // - // Get the Communicator instance with which this facade is - // associated. - // - public Ice.Communicator getCommunicator() - { - return _communicator; - } + // + // Get the Communicator instance with which this facade is + // associated. + // + public Ice.Communicator getCommunicator() + { + return _communicator; + } - // - // Get the default hostname to be used in endpoints. - // - public string getDefaultHost() - { - return _instance.defaultsAndOverrides().defaultHost; - } + // + // Get the default hostname to be used in endpoints. + // + public string getDefaultHost() + { + return _instance.defaultsAndOverrides().defaultHost; + } - // - // Get the network trace level and category name. - // - public int getNetworkTraceLevel() - { - return _instance.traceLevels().network; - } + // + // Get the network trace level and category name. + // + public int getNetworkTraceLevel() + { + return _instance.traceLevels().network; + } - public string getNetworkTraceCategory() - { - return _instance.traceLevels().networkCat; - } + public string getNetworkTraceCategory() + { + return _instance.traceLevels().networkCat; + } - // - // Register an EndpointFactory. - // - public void addEndpointFactory(EndpointFactory factory) - { - _instance.endpointFactoryManager().add(factory); - } + // + // Register an EndpointFactory. + // + public void addEndpointFactory(EndpointFactory factory) + { + _instance.endpointFactoryManager().add(factory); + } - private Instance _instance; - private Ice.Communicator _communicator; + private Instance _instance; + private Ice.Communicator _communicator; } } diff --git a/cs/src/Ice/Proxy.cs b/cs/src/Ice/Proxy.cs index a00b4ef77de..cb09b746f65 100644 --- a/cs/src/Ice/Proxy.cs +++ b/cs/src/Ice/Proxy.cs @@ -16,15 +16,15 @@ namespace Ice { public interface ObjectPrx { - [Obsolete("This method is deprecated, use ice_getHash instead.")] + [Obsolete("This method is deprecated, use ice_getHash instead.")] int ice_hash(); int ice_getHash(); - [Obsolete("This method is deprecated, use ice_getCommunicator instead.")] - Communicator ice_communicator(); - Communicator ice_getCommunicator(); + [Obsolete("This method is deprecated, use ice_getCommunicator instead.")] + Communicator ice_communicator(); + Communicator ice_getCommunicator(); - string ice_toString(); + string ice_toString(); bool ice_isA(string id__); bool ice_isA(string id__, Context context__); @@ -48,54 +48,54 @@ namespace Ice Context context); Identity ice_getIdentity(); - [Obsolete("This method is deprecated, use ice_identity instead.")] + [Obsolete("This method is deprecated, use ice_identity instead.")] ObjectPrx ice_newIdentity(Identity newIdentity); ObjectPrx ice_identity(Identity newIdentity); - + Context ice_getContext(); - [Obsolete("This method is deprecated, use ice_context instead.")] + [Obsolete("This method is deprecated, use ice_context instead.")] ObjectPrx ice_newContext(Context newContext); ObjectPrx ice_context(Context newContext); ObjectPrx ice_defaultContext(); - + string ice_getFacet(); - [Obsolete("This method is deprecated, use ice_facet instead.")] + [Obsolete("This method is deprecated, use ice_facet instead.")] ObjectPrx ice_newFacet(string newFacet); ObjectPrx ice_facet(string newFacet); string ice_getAdapterId(); - [Obsolete("This method is deprecated, use ice_adapterId instead.")] + [Obsolete("This method is deprecated, use ice_adapterId instead.")] ObjectPrx ice_newAdapterId(string newAdapterId); ObjectPrx ice_adapterId(string newAdapterId); - Endpoint[] ice_getEndpoints(); - [Obsolete("This method is deprecated, use ice_endpoints instead.")] + Endpoint[] ice_getEndpoints(); + [Obsolete("This method is deprecated, use ice_endpoints instead.")] ObjectPrx ice_newEndpoints(Endpoint[] newEndpoints); ObjectPrx ice_endpoints(Endpoint[] newEndpoints); - int ice_getLocatorCacheTimeout(); - ObjectPrx ice_locatorCacheTimeout(int timeout); - - bool ice_isConnectionCached(); - ObjectPrx ice_connectionCached(bool newCache); + int ice_getLocatorCacheTimeout(); + ObjectPrx ice_locatorCacheTimeout(int timeout); + + bool ice_isConnectionCached(); + ObjectPrx ice_connectionCached(bool newCache); - EndpointSelectionType ice_getEndpointSelection(); - ObjectPrx ice_endpointSelection(EndpointSelectionType newType); + EndpointSelectionType ice_getEndpointSelection(); + ObjectPrx ice_endpointSelection(EndpointSelectionType newType); - bool ice_isSecure(); + bool ice_isSecure(); ObjectPrx ice_secure(bool b); - bool ice_isPreferSecure(); + bool ice_isPreferSecure(); ObjectPrx ice_preferSecure(bool b); - Ice.RouterPrx ice_getRouter(); + Ice.RouterPrx ice_getRouter(); ObjectPrx ice_router(Ice.RouterPrx router); - Ice.LocatorPrx ice_getLocator(); + Ice.LocatorPrx ice_getLocator(); ObjectPrx ice_locator(Ice.LocatorPrx locator); - bool ice_isCollocationOptimized(); - [Obsolete("This method is deprecated, use ice_collocationOptimized instead.")] + bool ice_isCollocationOptimized(); + [Obsolete("This method is deprecated, use ice_collocationOptimized instead.")] ObjectPrx ice_collocationOptimization(bool b); ObjectPrx ice_collocationOptimized(bool b); @@ -117,7 +117,7 @@ namespace Ice bool ice_isThreadPerConnection(); ObjectPrx ice_threadPerConnection(bool tpc); - [Obsolete("This method is deprecated, use ice_getConnection instead.")] + [Obsolete("This method is deprecated, use ice_getConnection instead.")] Connection ice_connection(); Connection ice_getConnection(); Connection ice_getCachedConnection(); @@ -141,41 +141,41 @@ namespace Ice } public Communicator ice_communicator() - { - return ice_getCommunicator(); - } + { + return ice_getCommunicator(); + } public Communicator ice_getCommunicator() - { - return _reference.getCommunicator(); - } + { + return _reference.getCommunicator(); + } - public override string ToString() - { - return _reference.ToString(); - } + public override string ToString() + { + return _reference.ToString(); + } - public string ice_toString() - { - return ToString(); - } + public string ice_toString() + { + return ToString(); + } public bool ice_isA(string id__) { return ice_isA(id__, null, false); } - public bool ice_isA(string id__, Context context__) + public bool ice_isA(string id__, Context context__) { - return ice_isA(id__, context__, true); - } + return ice_isA(id__, context__, true); + } private bool ice_isA(string id__, Context context__, bool explicitContext__) { - if(explicitContext__ && context__ == null) - { - context__ = emptyContext_; - } + if(explicitContext__ && context__ == null) + { + context__ = emptyContext_; + } int cnt__ = 0; while(true) @@ -203,17 +203,17 @@ namespace Ice ice_ping(null, false); } - public void ice_ping(Context context__) + public void ice_ping(Context context__) { ice_ping(context__, true); } private void ice_ping(Context context__, bool explicitContext__) { - if(explicitContext__ && context__ == null) - { - context__ = emptyContext_; - } + if(explicitContext__ && context__ == null) + { + context__ = emptyContext_; + } int cnt__ = 0; while(true) @@ -228,7 +228,7 @@ namespace Ice } catch(IceInternal.LocalExceptionWrapper ex__) { - cnt__ = handleExceptionWrapperRelaxed__(del__, ex__, cnt__); + cnt__ = handleExceptionWrapperRelaxed__(del__, ex__, cnt__); } catch(LocalException ex__) { @@ -242,17 +242,17 @@ namespace Ice return ice_ids(null, false); } - public string[] ice_ids(Context context__) + public string[] ice_ids(Context context__) { - return ice_ids(context__, true); - } + return ice_ids(context__, true); + } private string[] ice_ids(Context context__, bool explicitContext__) { - if(explicitContext__ && context__ == null) - { - context__ = emptyContext_; - } + if(explicitContext__ && context__ == null) + { + context__ = emptyContext_; + } int cnt__ = 0; while(true) { @@ -265,7 +265,7 @@ namespace Ice } catch(IceInternal.LocalExceptionWrapper ex__) { - cnt__ = handleExceptionWrapperRelaxed__(del__, ex__, cnt__); + cnt__ = handleExceptionWrapperRelaxed__(del__, ex__, cnt__); } catch(LocalException ex__) { @@ -279,17 +279,17 @@ namespace Ice return ice_id(null, false); } - public string ice_id(Context context__) + public string ice_id(Context context__) { - return ice_id(context__, true); - } + return ice_id(context__, true); + } private string ice_id(Context context__, bool explicitContext__) { - if(explicitContext__ && context__ == null) - { - context__ = emptyContext_; - } + if(explicitContext__ && context__ == null) + { + context__ = emptyContext_; + } int cnt__ = 0; while(true) { @@ -302,7 +302,7 @@ namespace Ice } catch(IceInternal.LocalExceptionWrapper ex__) { - cnt__ = handleExceptionWrapperRelaxed__(del__, ex__, cnt__); + cnt__ = handleExceptionWrapperRelaxed__(del__, ex__, cnt__); } catch(LocalException ex__) { @@ -316,19 +316,19 @@ namespace Ice return ice_invoke(operation, mode, inParams, out outParams, null, false); } - public bool ice_invoke(string operation, OperationMode mode, byte[] inParams, out byte[] outParams, + public bool ice_invoke(string operation, OperationMode mode, byte[] inParams, out byte[] outParams, Context context) { - return ice_invoke(operation, mode, inParams, out outParams, context, true); - } - + return ice_invoke(operation, mode, inParams, out outParams, context, true); + } + private bool ice_invoke(string operation, OperationMode mode, byte[] inParams, out byte[] outParams, - Context context, bool explicitContext) + Context context, bool explicitContext) { - if(explicitContext && context == null) - { - context = emptyContext_; - } + if(explicitContext && context == null) + { + context = emptyContext_; + } int cnt__ = 0; while(true) @@ -364,12 +364,12 @@ namespace Ice } public void ice_invoke_async(AMI_Object_ice_invoke cb, string operation, OperationMode mode, byte[] inParams, - Context context) + Context context) { - if(context == null) - { - context = emptyContext_; - } + if(context == null) + { + context = emptyContext_; + } checkTwowayOnly__("ice_invoke_async"); cb.invoke__(this, operation, mode, inParams, context); } @@ -381,10 +381,10 @@ namespace Ice public ObjectPrx ice_identity(Identity newIdentity) { - if(newIdentity.name.Equals("")) - { - throw new IllegalIdentityException(); - } + if(newIdentity.name.Equals("")) + { + throw new IllegalIdentityException(); + } if(newIdentity.Equals(_reference.getIdentity())) { return this; @@ -399,8 +399,8 @@ namespace Ice public ObjectPrx ice_newIdentity(Identity newIdentity) { - return ice_identity(newIdentity); - } + return ice_identity(newIdentity); + } public Context ice_getContext() { @@ -416,15 +416,15 @@ namespace Ice public ObjectPrx ice_newContext(Context newContext) { - return ice_context(newContext); - } + return ice_context(newContext); + } - public ObjectPrx ice_defaultContext() - { + public ObjectPrx ice_defaultContext() + { ObjectPrxHelperBase proxy = new ObjectPrxHelperBase(); proxy.setup(_reference.defaultContext()); return proxy; - } + } public string ice_getFacet() { @@ -452,8 +452,8 @@ namespace Ice public ObjectPrx ice_newFacet(string newFacet) { - return ice_facet(newFacet); - } + return ice_facet(newFacet); + } public string ice_getAdapterId() { @@ -481,8 +481,8 @@ namespace Ice public ObjectPrx ice_newAdapterId(string newAdapterId) { - return ice_adapterId(newAdapterId); - } + return ice_adapterId(newAdapterId); + } public Endpoint[] ice_getEndpoints() { @@ -498,8 +498,8 @@ namespace Ice else { ObjectPrxHelperBase proxy = new ObjectPrxHelperBase(); - ArrayList arr = ArrayList.Adapter(newEndpoints); - IceInternal.EndpointI[] endpts = (IceInternal.EndpointI[])arr.ToArray(typeof(IceInternal.EndpointI)); + ArrayList arr = ArrayList.Adapter(newEndpoints); + IceInternal.EndpointI[] endpts = (IceInternal.EndpointI[])arr.ToArray(typeof(IceInternal.EndpointI)); proxy.setup(_reference.changeEndpoints(endpts)); return proxy; } @@ -507,8 +507,8 @@ namespace Ice public ObjectPrx ice_newEndpoints(Endpoint[] newEndpoints) { - return ice_endpoints(newEndpoints); - } + return ice_endpoints(newEndpoints); + } public int ice_getLocatorCacheTimeout() { @@ -607,8 +607,8 @@ namespace Ice public Ice.RouterPrx ice_getRouter() { - IceInternal.RouterInfo ri = _reference.getRouterInfo(); - return ri != null ? ri.getRouter() : null; + IceInternal.RouterInfo ri = _reference.getRouterInfo(); + return ri != null ? ri.getRouter() : null; } public ObjectPrx ice_router(RouterPrx router) @@ -628,8 +628,8 @@ namespace Ice public Ice.LocatorPrx ice_getLocator() { - IceInternal.LocatorInfo li = _reference.getLocatorInfo(); - return li != null ? li.getLocator() : null; + IceInternal.LocatorInfo li = _reference.getLocatorInfo(); + return li != null ? li.getLocator() : null; } public ObjectPrx ice_locator(LocatorPrx locator) @@ -654,8 +654,8 @@ namespace Ice public ObjectPrx ice_collocationOptimization(bool b) { - return ice_collocationOptimized(b); - } + return ice_collocationOptimized(b); + } public ObjectPrx ice_collocationOptimized(bool b) { @@ -796,7 +796,7 @@ namespace Ice } } - public ObjectPrx ice_connectionId(string connectionId) + public ObjectPrx ice_connectionId(string connectionId) { IceInternal.Reference @ref = _reference.changeConnectionId(connectionId); if(@ref.Equals(_reference)) @@ -833,8 +833,8 @@ namespace Ice public Connection ice_connection() { - return ice_getConnection(); - } + return ice_getConnection(); + } public Connection ice_getConnection() { @@ -845,7 +845,7 @@ namespace Ice try { del__ = getDelegate__(); - bool comp; + bool comp; return del__.getConnection__(out comp); } catch(LocalException ex__) @@ -858,23 +858,23 @@ namespace Ice public Connection ice_getCachedConnection() { ObjectDel_ del__ = null; - lock(this) - { - del__ = _delegate; - } + lock(this) + { + del__ = _delegate; + } if(del__ != null) { try { - bool comp; + bool comp; return del__.getConnection__(out comp); } catch(CollocationOptimizationException) { } } - return null; + return null; } public override bool Equals(object r) @@ -927,27 +927,27 @@ namespace Ice _reference = @ref; - if(_reference.getCacheConnection()) - { - // - // The _delegate attribute is only used if "cache connection" - // is enabled. If it's not enabled, we don't keep track of the - // delegate -- a new delegate is created for each invocations. - // - - if(delegateD != null) - { - ObjectDelD_ @delegate = createDelegateD__(); - @delegate.copyFrom__(delegateD); - _delegate = @delegate; - } - else if(delegateM != null) - { - ObjectDelM_ @delegate = createDelegateM__(); - @delegate.copyFrom__(delegateM); - _delegate = @delegate; - } - } + if(_reference.getCacheConnection()) + { + // + // The _delegate attribute is only used if "cache connection" + // is enabled. If it's not enabled, we don't keep track of the + // delegate -- a new delegate is created for each invocations. + // + + if(delegateD != null) + { + ObjectDelD_ @delegate = createDelegateD__(); + @delegate.copyFrom__(delegateD); + _delegate = @delegate; + } + else if(delegateM != null) + { + ObjectDelM_ @delegate = createDelegateM__(); + @delegate.copyFrom__(delegateM); + _delegate = @delegate; + } + } } public int handleException__(ObjectDel_ @delegate, LocalException ex, int cnt) @@ -964,16 +964,16 @@ namespace Ice } IceInternal.ProxyFactory proxyFactory; - try - { - proxyFactory = _reference.getInstance().proxyFactory(); - } - catch(CommunicatorDestroyedException) - { - // - // The communicator is already destroyed, so we cannot - // retry. - // + try + { + proxyFactory = _reference.getInstance().proxyFactory(); + } + catch(CommunicatorDestroyedException) + { + // + // The communicator is already destroyed, so we cannot + // retry. + // throw ex; } @@ -1036,51 +1036,51 @@ namespace Ice { if(_delegate != null) { - return _delegate; - } - - ObjectDel_ @delegate = null; - if(_reference.getCollocationOptimization()) - { - ObjectAdapter adapter = _reference.getInstance().objectAdapterFactory().findObjectAdapter(this); - if(adapter != null) - { - ObjectDelD_ d = createDelegateD__(); - d.setup(_reference, adapter); - @delegate = d; - } - } - - if(@delegate == null) - { - ObjectDelM_ d = createDelegateM__(); - d.setup(_reference); - @delegate = d; - - // - // If this proxy is for a non-local object, and we are - // using a router, then add this proxy to the router info - // object. - // - IceInternal.RouterInfo ri = _reference.getRouterInfo(); - if(ri != null) - { - ri.addProxy(this); - } - } - - if(_reference.getCacheConnection()) - { - // - // The _delegate attribute is only used if "cache connection" - // is enabled. If it's not enabled, we don't keep track of the - // delegate -- a new delegate is created for each invocations. - // - _delegate = @delegate; - } - - return @delegate; - } + return _delegate; + } + + ObjectDel_ @delegate = null; + if(_reference.getCollocationOptimization()) + { + ObjectAdapter adapter = _reference.getInstance().objectAdapterFactory().findObjectAdapter(this); + if(adapter != null) + { + ObjectDelD_ d = createDelegateD__(); + d.setup(_reference, adapter); + @delegate = d; + } + } + + if(@delegate == null) + { + ObjectDelM_ d = createDelegateM__(); + d.setup(_reference); + @delegate = d; + + // + // If this proxy is for a non-local object, and we are + // using a router, then add this proxy to the router info + // object. + // + IceInternal.RouterInfo ri = _reference.getRouterInfo(); + if(ri != null) + { + ri.addProxy(this); + } + } + + if(_reference.getCacheConnection()) + { + // + // The _delegate attribute is only used if "cache connection" + // is enabled. If it's not enabled, we don't keep track of the + // delegate -- a new delegate is created for each invocations. + // + _delegate = @delegate; + } + + return @delegate; + } } protected virtual ObjectDelM_ createDelegateM__() @@ -1109,7 +1109,7 @@ namespace Ice _reference = @ref; } - protected static Ice.Context emptyContext_ = new Ice.Context(); + protected static Ice.Context emptyContext_ = new Ice.Context(); private IceInternal.Reference _reference; private ObjectDel_ _delegate; } @@ -1189,12 +1189,12 @@ namespace Ice public interface ObjectDel_ { - bool ice_isA(string id, Ice.Context context); - void ice_ping(Ice.Context context); - string[] ice_ids(Ice.Context context); - string ice_id(Ice.Context context); - bool ice_invoke(string operation, Ice.OperationMode mode, byte[] inParams, out byte[] outParams, - Ice.Context context); + bool ice_isA(string id, Ice.Context context); + void ice_ping(Ice.Context context); + string[] ice_ids(Ice.Context context); + string ice_id(Ice.Context context); + bool ice_invoke(string operation, Ice.OperationMode mode, byte[] inParams, out byte[] outParams, + Ice.Context context); ConnectionI getConnection__(out bool compress); } @@ -1218,7 +1218,7 @@ namespace Ice } } } - + public virtual void ice_ping(Ice.Context context__) { Current current__ = new Current(); @@ -1237,7 +1237,7 @@ namespace Ice } } } - + public virtual string[] ice_ids(Ice.Context context__) { Current current__ = new Current(); @@ -1255,7 +1255,7 @@ namespace Ice } } } - + public virtual string ice_id(Ice.Context context__) { Current current__ = new Current(); @@ -1273,13 +1273,13 @@ namespace Ice } } } - + public virtual bool ice_invoke(string operation, Ice.OperationMode mode, byte[] inParams, out byte[] outParams, Ice.Context context) { throw new CollocationOptimizationException(); } - + public virtual ConnectionI getConnection__(out bool compress) { throw new CollocationOptimizationException(); @@ -1294,24 +1294,24 @@ namespace Ice // No need to synchronize "from", as the delegate is immutable // after creation. // - + // // No need to synchronize, as this operation is only called // upon initialization. // - + Debug.Assert(reference__ == null); Debug.Assert(adapter__ == null); - + reference__ = from.reference__; adapter__ = from.adapter__; } - + protected internal IceInternal.Reference reference__; protected internal Ice.ObjectAdapter adapter__; - + protected internal void initCurrent__(ref Current current, string op, Ice.OperationMode mode, - Ice.Context context) + Ice.Context context) { current.adapter = adapter__; current.id = reference__.getIdentity(); @@ -1319,48 +1319,48 @@ namespace Ice current.operation = op; current.mode = mode; - if(context != null) - { - current.ctx = context; - } - else - { - // - // Implicit context - // - ImplicitContextI implicitContext = - reference__.getInstance().getImplicitContext(); - - Context prxContext = reference__.getContext(); - - if(implicitContext == null) - { - current.ctx = (Context)prxContext.Clone(); - } - else - { - current.ctx = implicitContext.combine(prxContext); - } - } - - current.requestId = -1; - } - + if(context != null) + { + current.ctx = context; + } + else + { + // + // Implicit context + // + ImplicitContextI implicitContext = + reference__.getInstance().getImplicitContext(); + + Context prxContext = reference__.getContext(); + + if(implicitContext == null) + { + current.ctx = (Context)prxContext.Clone(); + } + else + { + current.ctx = implicitContext.combine(prxContext); + } + } + + current.requestId = -1; + } + public virtual void setup(IceInternal.Reference rf, Ice.ObjectAdapter adapter) { // // No need to synchronize, as this operation is only called // upon initialization. // - + Debug.Assert(reference__ == null); Debug.Assert(adapter__ == null); - + reference__ = rf; adapter__ = adapter; } } - + public class ObjectDelM_ : ObjectDel_ { public virtual bool ice_isA(string id__, Ice.Context context__) @@ -1368,156 +1368,156 @@ namespace Ice IceInternal.Outgoing og__ = getOutgoing("ice_isA", OperationMode.Nonmutating, context__); try { - try - { - IceInternal.BasicStream os__ = og__.ostr(); - os__.writeString(id__); - } - catch(LocalException ex__) - { - og__.abort(ex__); - } - bool ok__ = og__.invoke(); - try - { - IceInternal.BasicStream is__ = og__.istr(); - if(!ok__) - { - try - { - is__.throwException(); - } - catch(UserException) - { - throw new UnknownUserException(); - } - } - return is__.readBool(); - } - catch(LocalException ex__) - { - throw new IceInternal.LocalExceptionWrapper(ex__, false); - } + try + { + IceInternal.BasicStream os__ = og__.ostr(); + os__.writeString(id__); + } + catch(LocalException ex__) + { + og__.abort(ex__); + } + bool ok__ = og__.invoke(); + try + { + IceInternal.BasicStream is__ = og__.istr(); + if(!ok__) + { + try + { + is__.throwException(); + } + catch(UserException) + { + throw new UnknownUserException(); + } + } + return is__.readBool(); + } + catch(LocalException ex__) + { + throw new IceInternal.LocalExceptionWrapper(ex__, false); + } } finally { reclaimOutgoing(og__); } } - + public virtual void ice_ping(Ice.Context context__) { IceInternal.Outgoing og__ = getOutgoing("ice_ping", OperationMode.Nonmutating, context__); try { - bool ok__ = og__.invoke(); - try - { - IceInternal.BasicStream is__ = og__.istr(); - if(!ok__) - { - try - { - is__.throwException(); - } - catch(UserException) - { - throw new UnknownUserException(); - } - } - } - catch(LocalException ex__) - { - throw new IceInternal.LocalExceptionWrapper(ex__, false); - } + bool ok__ = og__.invoke(); + try + { + IceInternal.BasicStream is__ = og__.istr(); + if(!ok__) + { + try + { + is__.throwException(); + } + catch(UserException) + { + throw new UnknownUserException(); + } + } + } + catch(LocalException ex__) + { + throw new IceInternal.LocalExceptionWrapper(ex__, false); + } } finally { reclaimOutgoing(og__); } } - + public virtual string[] ice_ids(Ice.Context context__) { IceInternal.Outgoing og__ = getOutgoing("ice_ids", OperationMode.Nonmutating, context__); try { - bool ok__ = og__.invoke(); - try - { - IceInternal.BasicStream is__ = og__.istr(); - if(!ok__) - { - try - { - is__.throwException(); - } - catch(UserException) - { - throw new UnknownUserException(); - } - } - return is__.readStringSeq(); - } - catch(LocalException ex__) - { - throw new IceInternal.LocalExceptionWrapper(ex__, false); - } + bool ok__ = og__.invoke(); + try + { + IceInternal.BasicStream is__ = og__.istr(); + if(!ok__) + { + try + { + is__.throwException(); + } + catch(UserException) + { + throw new UnknownUserException(); + } + } + return is__.readStringSeq(); + } + catch(LocalException ex__) + { + throw new IceInternal.LocalExceptionWrapper(ex__, false); + } } finally { reclaimOutgoing(og__); } } - + public virtual string ice_id(Ice.Context context__) { IceInternal.Outgoing og__ = getOutgoing("ice_id", OperationMode.Nonmutating, context__); try { - bool ok__ = og__.invoke(); - try - { - IceInternal.BasicStream is__ = og__.istr(); - if(!ok__) - { - try - { - is__.throwException(); - } - catch(UserException) - { - throw new UnknownUserException(); - } - } - return is__.readString(); - } - catch(LocalException ex__) - { - throw new IceInternal.LocalExceptionWrapper(ex__, false); - } + bool ok__ = og__.invoke(); + try + { + IceInternal.BasicStream is__ = og__.istr(); + if(!ok__) + { + try + { + is__.throwException(); + } + catch(UserException) + { + throw new UnknownUserException(); + } + } + return is__.readString(); + } + catch(LocalException ex__) + { + throw new IceInternal.LocalExceptionWrapper(ex__, false); + } } finally { reclaimOutgoing(og__); } } - + public virtual bool ice_invoke(string operation, OperationMode mode, byte[] inParams, out byte[] outParams, Ice.Context context__) { IceInternal.Outgoing og__ = getOutgoing(operation, mode, context__); try { - try - { - IceInternal.BasicStream os__ = og__.ostr(); - os__.writeBlob(inParams); - } - catch(LocalException ex__) - { - og__.abort(ex__); - } + try + { + IceInternal.BasicStream os__ = og__.ostr(); + os__.writeBlob(inParams); + } + catch(LocalException ex__) + { + og__.abort(ex__); + } bool ok = og__.invoke(); outParams = null; if(reference__.getMode() == IceInternal.Reference.Mode.ModeTwoway) @@ -1540,13 +1540,13 @@ namespace Ice reclaimOutgoing(og__); } } - + public virtual ConnectionI getConnection__(out bool compress) { - compress = compress__; + compress = compress__; return connection__; } - + // // Only for use by ObjectPrx // @@ -1556,20 +1556,20 @@ namespace Ice // No need to synchronize "from", as the delegate is immutable // after creation. // - + // // No need to synchronize, as this operation is only called // upon initialization. // - + Debug.Assert(reference__ == null); Debug.Assert(connection__ == null); - + reference__ = from.reference__; connection__ = from.connection__; - compress__ = from.compress__; + compress__ = from.compress__; } - + protected IceInternal.Reference reference__; protected ConnectionI connection__; protected bool compress__; @@ -1580,22 +1580,22 @@ namespace Ice // No need to synchronize, as this operation is only called // upon initialization. // - + Debug.Assert(reference__ == null); Debug.Assert(connection__ == null); - + reference__ = rf; connection__ = reference__.getConnection(out compress__); } - + protected IceInternal.Outgoing getOutgoing(string operation, OperationMode mode, Ice.Context context) { - return connection__.getOutgoing(reference__, operation, mode, context, compress__); + return connection__.getOutgoing(reference__, operation, mode, context, compress__); } protected void reclaimOutgoing(IceInternal.Outgoing outg) { - connection__.reclaimOutgoing(outg); + connection__.reclaimOutgoing(outg); } } } diff --git a/cs/src/Ice/ProxyFactory.cs b/cs/src/Ice/ProxyFactory.cs index c213347902b..63c49fbe880 100755 --- a/cs/src/Ice/ProxyFactory.cs +++ b/cs/src/Ice/ProxyFactory.cs @@ -14,119 +14,119 @@ namespace IceInternal public sealed class ProxyFactory { - public Ice.ObjectPrx stringToProxy(string str) - { - Reference r = instance_.referenceFactory().create(str); - return referenceToProxy(r); - } - - public string proxyToString(Ice.ObjectPrx proxy) - { - if(proxy != null) - { - Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase) proxy; - return h.reference__().ToString(); - } - else - { - return ""; - } - } - - public Ice.ObjectPrx propertyToProxy(string prefix) - { - Reference r = instance_.referenceFactory().createFromProperties(prefix); - return referenceToProxy(r); - } - - public Ice.ObjectPrx streamToProxy(BasicStream s) - { - Ice.Identity ident = new Ice.Identity(); - ident.read__(s); - - Reference r = instance_.referenceFactory().create(ident, s); - return referenceToProxy(r); - } - - public Ice.ObjectPrx referenceToProxy(Reference r) - { - if(r != null) - { - Ice.ObjectPrxHelperBase proxy = new Ice.ObjectPrxHelperBase(); - proxy.setup(r); - return proxy; - } - else - { - return null; - } - } - - public void proxyToStream(Ice.ObjectPrx proxy, BasicStream s) - { - if(proxy != null) - { - Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase)proxy; - Reference r = h.reference__(); - r.getIdentity().write__(s); - r.streamWrite(s); - } - else - { - Ice.Identity ident = new Ice.Identity(); - ident.name = ""; - ident.category = ""; - ident.write__(s); - } - } - - public int checkRetryAfterException(Ice.LocalException ex, Reference @ref, int cnt) - { - TraceLevels traceLevels = instance_.traceLevels(); - Ice.Logger logger = instance_.initializationData().logger; + public Ice.ObjectPrx stringToProxy(string str) + { + Reference r = instance_.referenceFactory().create(str); + return referenceToProxy(r); + } + + public string proxyToString(Ice.ObjectPrx proxy) + { + if(proxy != null) + { + Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase) proxy; + return h.reference__().ToString(); + } + else + { + return ""; + } + } + + public Ice.ObjectPrx propertyToProxy(string prefix) + { + Reference r = instance_.referenceFactory().createFromProperties(prefix); + return referenceToProxy(r); + } + + public Ice.ObjectPrx streamToProxy(BasicStream s) + { + Ice.Identity ident = new Ice.Identity(); + ident.read__(s); + + Reference r = instance_.referenceFactory().create(ident, s); + return referenceToProxy(r); + } + + public Ice.ObjectPrx referenceToProxy(Reference r) + { + if(r != null) + { + Ice.ObjectPrxHelperBase proxy = new Ice.ObjectPrxHelperBase(); + proxy.setup(r); + return proxy; + } + else + { + return null; + } + } + + public void proxyToStream(Ice.ObjectPrx proxy, BasicStream s) + { + if(proxy != null) + { + Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase)proxy; + Reference r = h.reference__(); + r.getIdentity().write__(s); + r.streamWrite(s); + } + else + { + Ice.Identity ident = new Ice.Identity(); + ident.name = ""; + ident.category = ""; + ident.write__(s); + } + } + + public int checkRetryAfterException(Ice.LocalException ex, Reference @ref, int cnt) + { + TraceLevels traceLevels = instance_.traceLevels(); + Ice.Logger logger = instance_.initializationData().logger; - if(ex is Ice.ObjectNotExistException) - { - Ice.ObjectNotExistException one = (Ice.ObjectNotExistException)ex; + if(ex is Ice.ObjectNotExistException) + { + Ice.ObjectNotExistException one = (Ice.ObjectNotExistException)ex; - LocatorInfo li = @ref.getLocatorInfo(); - if(li != null) - { - // - // We retry ObjectNotExistException if the reference is - // indirect. - // - li.clearObjectCache((IndirectReference)@ref); - } - else if(@ref.getRouterInfo() != null && one.operation.Equals("ice_add_proxy")) - { - // - // If we have a router, an ObjectNotExistException with an - // operation name "ice_add_proxy" indicates to the client - // that the router isn't aware of the proxy (for example, - // because it was evicted by the router). In this case, we - // must *always* retry, so that the missing proxy is added - // to the router. - // - if(traceLevels.retry >= 1) - { - string s = "retrying operation call to add proxy to router\n" + ex; - logger.trace(traceLevels.retryCat, s); - } - return cnt; // We must always retry, so we don't look at the retry count. - } - else - { - // - // For all other cases, we don't retry ObjectNotExistException. - // - throw ex; - } - } - else if(ex is Ice.RequestFailedException) - { - throw ex; - } + LocatorInfo li = @ref.getLocatorInfo(); + if(li != null) + { + // + // We retry ObjectNotExistException if the reference is + // indirect. + // + li.clearObjectCache((IndirectReference)@ref); + } + else if(@ref.getRouterInfo() != null && one.operation.Equals("ice_add_proxy")) + { + // + // If we have a router, an ObjectNotExistException with an + // operation name "ice_add_proxy" indicates to the client + // that the router isn't aware of the proxy (for example, + // because it was evicted by the router). In this case, we + // must *always* retry, so that the missing proxy is added + // to the router. + // + if(traceLevels.retry >= 1) + { + string s = "retrying operation call to add proxy to router\n" + ex; + logger.trace(traceLevels.retryCat, s); + } + return cnt; // We must always retry, so we don't look at the retry count. + } + else + { + // + // For all other cases, we don't retry ObjectNotExistException. + // + throw ex; + } + } + else if(ex is Ice.RequestFailedException) + { + throw ex; + } // // There is no point in retrying an operation that resulted in a @@ -149,98 +149,98 @@ namespace IceInternal // of the batched requests were accepted, when in reality only the // last few are actually sent. // - if(ex is Ice.MarshalException) - { - throw ex; - } + if(ex is Ice.MarshalException) + { + throw ex; + } - ++cnt; - Debug.Assert(cnt > 0); + ++cnt; + Debug.Assert(cnt > 0); - if(cnt > _retryIntervals.Length) - { - if(traceLevels.retry >= 1) - { - string s = "cannot retry operation call because retry limit has been exceeded\n" + ex; - logger.trace(traceLevels.retryCat, s); - } - throw ex; - } + if(cnt > _retryIntervals.Length) + { + if(traceLevels.retry >= 1) + { + string s = "cannot retry operation call because retry limit has been exceeded\n" + ex; + logger.trace(traceLevels.retryCat, s); + } + throw ex; + } - int interval = _retryIntervals[cnt - 1]; + int interval = _retryIntervals[cnt - 1]; - if(traceLevels.retry >= 1) - { - string s = "retrying operation call"; - if(interval > 0) - { - s += " in " + interval + "ms"; - } - s += " because of exception\n" + ex; - logger.trace(traceLevels.retryCat, s); - } + if(traceLevels.retry >= 1) + { + string s = "retrying operation call"; + if(interval > 0) + { + s += " in " + interval + "ms"; + } + s += " because of exception\n" + ex; + logger.trace(traceLevels.retryCat, s); + } - if(interval > 0) - { - // - // Sleep before retrying. - // - System.Threading.Thread.Sleep(interval); - } + if(interval > 0) + { + // + // Sleep before retrying. + // + System.Threading.Thread.Sleep(interval); + } - return cnt; - } + return cnt; + } - // - // Only for use by Instance - // - internal ProxyFactory(Instance instance) - { - instance_ = instance; - - string str = instance_.initializationData().properties.getPropertyWithDefault("Ice.RetryIntervals", "0"); - - char[] separators = { ' ', '\t', '\n', '\r' }; - string[] arr = str.Trim().Split(separators); - - if(arr.Length > 0) - { - _retryIntervals = new int[arr.Length]; - - for (int i = 0; i < arr.Length; i++) - { - int v; - - try - { - v = System.Int32.Parse(arr[i]); - } - catch(System.FormatException) - { - v = 0; - } - - // - // If -1 is the first value, no retry and wait intervals. - // - if(i == 0 && v == -1) - { - _retryIntervals = new int[0]; - break; - } - - _retryIntervals[i] = v > 0?v:0; - } - } - else - { - _retryIntervals = new int[1]; - _retryIntervals[0] = 0; - } - } - - private Instance instance_; - private int[] _retryIntervals; + // + // Only for use by Instance + // + internal ProxyFactory(Instance instance) + { + instance_ = instance; + + string str = instance_.initializationData().properties.getPropertyWithDefault("Ice.RetryIntervals", "0"); + + char[] separators = { ' ', '\t', '\n', '\r' }; + string[] arr = str.Trim().Split(separators); + + if(arr.Length > 0) + { + _retryIntervals = new int[arr.Length]; + + for (int i = 0; i < arr.Length; i++) + { + int v; + + try + { + v = System.Int32.Parse(arr[i]); + } + catch(System.FormatException) + { + v = 0; + } + + // + // If -1 is the first value, no retry and wait intervals. + // + if(i == 0 && v == -1) + { + _retryIntervals = new int[0]; + break; + } + + _retryIntervals[i] = v > 0?v:0; + } + } + else + { + _retryIntervals = new int[1]; + _retryIntervals[0] = 0; + } + } + + private Instance instance_; + private int[] _retryIntervals; } } diff --git a/cs/src/Ice/ProxyIdentityKey.cs b/cs/src/Ice/ProxyIdentityKey.cs index 58129cbfb57..819e386deda 100755 --- a/cs/src/Ice/ProxyIdentityKey.cs +++ b/cs/src/Ice/ProxyIdentityKey.cs @@ -20,25 +20,25 @@ namespace Ice public class ProxyIdentityKey : System.Collections.IEqualityComparer, System.Collections.IComparer { - public int GetHashCode(object obj) - { + public int GetHashCode(object obj) + { return ((Ice.ObjectPrx)obj).ice_getIdentity().GetHashCode(); - } + } - public new bool Equals(object obj1, object obj2) - { - try - { - return Compare(obj1, obj2) == 0; - } - catch(System.Exception) - { - return false; - } - } + public new bool Equals(object obj1, object obj2) + { + try + { + return Compare(obj1, obj2) == 0; + } + catch(System.Exception) + { + return false; + } + } - public int Compare(object obj1, object obj2) - { + public int Compare(object obj1, object obj2) + { if(obj1 == null) { return obj2 == null ? 0 : -1; @@ -57,39 +57,39 @@ namespace Ice { throw new System.ArgumentException("Argument must be derived from Ice.ObjectPrx", "o2"); } - Ice.Identity i1 = ((Ice.ObjectPrx)obj1).ice_getIdentity(); - Ice.Identity i2 = ((Ice.ObjectPrx)obj2).ice_getIdentity(); - int comp = string.Compare(i1.name, i2.name, false, CultureInfo.InvariantCulture); - if(comp != 0) - { - return comp; - } - return string.Compare(i1.category, i2.category, false, CultureInfo.InvariantCulture); + Ice.Identity i1 = ((Ice.ObjectPrx)obj1).ice_getIdentity(); + Ice.Identity i2 = ((Ice.ObjectPrx)obj2).ice_getIdentity(); + int comp = string.Compare(i1.name, i2.name, false, CultureInfo.InvariantCulture); + if(comp != 0) + { + return comp; + } + return string.Compare(i1.category, i2.category, false, CultureInfo.InvariantCulture); } - } + } } public class ProxyIdentityFacetKey : System.Collections.IEqualityComparer, System.Collections.IComparer { - public int GetHashCode(object obj) - { - Ice.ObjectPrx o = (Ice.ObjectPrx)obj; - Ice.Identity identity = o.ice_getIdentity(); - string facet = o.ice_getFacet(); - return 5 * identity.GetHashCode() + facet.GetHashCode(); - } + public int GetHashCode(object obj) + { + Ice.ObjectPrx o = (Ice.ObjectPrx)obj; + Ice.Identity identity = o.ice_getIdentity(); + string facet = o.ice_getFacet(); + return 5 * identity.GetHashCode() + facet.GetHashCode(); + } - public new bool Equals(object obj1, object obj2) - { - try - { - return Compare(obj1, obj2) == 0; - } - catch(System.Exception) - { - return false; - } - } + public new bool Equals(object obj1, object obj2) + { + try + { + return Compare(obj1, obj2) == 0; + } + catch(System.Exception) + { + return false; + } + } public int Compare(object obj1, object obj2) { diff --git a/cs/src/Ice/Reference.cs b/cs/src/Ice/Reference.cs index 7a4561641f0..009ca814d62 100755 --- a/cs/src/Ice/Reference.cs +++ b/cs/src/Ice/Reference.cs @@ -16,878 +16,878 @@ namespace IceInternal { public abstract class Reference : ICloneable { - public enum Mode { - ModeTwoway, - ModeOneway, - ModeBatchOneway, - ModeDatagram, - ModeBatchDatagram, - ModeLast=ModeBatchDatagram - }; - - public Mode getMode() - { - return mode_; - } - - public Ice.Identity getIdentity() - { - return identity_; - } - - public string getFacet() - { - return facet_; - } - - public Instance getInstance() - { - return instance_; - } - - public Ice.Context getContext() - { - return context_; - } - - public Reference defaultContext() - { - Reference r = instance_.referenceFactory().copy(this); - r.context_ = instance_.getDefaultContext(); - return r; - } - - public Ice.Communicator getCommunicator() - { - return communicator_; - } - - public virtual RouterInfo getRouterInfo() - { - return null; - } - - public virtual LocatorInfo getLocatorInfo() - { - return null; - } - - public abstract bool getSecure(); - public abstract bool getPreferSecure(); - public abstract string getAdapterId(); - public abstract EndpointI[] getEndpoints(); - public abstract bool getCollocationOptimization(); - public abstract int getLocatorCacheTimeout(); - public abstract bool getCacheConnection(); - public abstract Ice.EndpointSelectionType getEndpointSelection(); + public enum Mode { + ModeTwoway, + ModeOneway, + ModeBatchOneway, + ModeDatagram, + ModeBatchDatagram, + ModeLast=ModeBatchDatagram + }; + + public Mode getMode() + { + return mode_; + } + + public Ice.Identity getIdentity() + { + return identity_; + } + + public string getFacet() + { + return facet_; + } + + public Instance getInstance() + { + return instance_; + } + + public Ice.Context getContext() + { + return context_; + } + + public Reference defaultContext() + { + Reference r = instance_.referenceFactory().copy(this); + r.context_ = instance_.getDefaultContext(); + return r; + } + + public Ice.Communicator getCommunicator() + { + return communicator_; + } + + public virtual RouterInfo getRouterInfo() + { + return null; + } + + public virtual LocatorInfo getLocatorInfo() + { + return null; + } + + public abstract bool getSecure(); + public abstract bool getPreferSecure(); + public abstract string getAdapterId(); + public abstract EndpointI[] getEndpoints(); + public abstract bool getCollocationOptimization(); + public abstract int getLocatorCacheTimeout(); + public abstract bool getCacheConnection(); + public abstract Ice.EndpointSelectionType getEndpointSelection(); public abstract bool getThreadPerConnection(); - // - // The change* methods (here and in derived classes) create - // a new reference based on the existing one, with the - // corresponding value changed. - // - public Reference changeContext(Ice.Context newContext) - { - if(newContext == null) - { - newContext = _emptyContext; - } - Reference r = instance_.referenceFactory().copy(this); - if(newContext.Count == 0) - { - r.context_ = _emptyContext; - } - else - { - r.context_ = (Ice.Context)newContext.Clone(); - } - return r; - } - - public Reference changeMode(Mode newMode) - { - if(newMode == mode_) - { - return this; - } - Reference r = instance_.referenceFactory().copy(this); - r.mode_ = newMode; - return r; - } - - public Reference changeIdentity(Ice.Identity newIdentity) - { - if(newIdentity.Equals(identity_)) - { - return this; - } - Reference r = instance_.referenceFactory().copy(this); - r.identity_ = newIdentity; // Identity is a value type, therefore a copy of newIdentity is made. - return r; - } - - public Reference changeFacet(string newFacet) - { - if(newFacet.Equals(facet_)) - { - return this; - } - Reference r = instance_.referenceFactory().copy(this); - r.facet_ = newFacet; - return r; - } - - public abstract Reference changeSecure(bool newSecure); - public abstract Reference changePreferSecure(bool newPreferSecure); - public abstract Reference changeRouter(Ice.RouterPrx newRouter); - public abstract Reference changeLocator(Ice.LocatorPrx newLocator); - public abstract Reference changeCompress(bool newCompress); - public abstract Reference changeTimeout(int newTimeout); - public abstract Reference changeConnectionId(string connectionId); - public abstract Reference changeCollocationOptimization(bool newCollocationOptimization); - public abstract Reference changeAdapterId(string newAdapterId); - public abstract Reference changeEndpoints(EndpointI[] newEndpoints); - public abstract Reference changeLocatorCacheTimeout(int newTimeout); - public abstract Reference changeCacheConnection(bool newCache); - public abstract Reference changeEndpointSelection(Ice.EndpointSelectionType newType); - public abstract Reference changeThreadPerConnection(bool newTpc); - - public override int GetHashCode() - { - lock(this) - { - if(hashInitialized_) - { - return hashValue_; - } - - int h = (int)mode_; - - int sz = identity_.name.Length; - for(int i = 0; i < sz; i++) - { - h = 5 * h + (int)identity_.name[i]; - } - - sz = identity_.category.Length; - for(int i = 0; i < sz; i++) - { - h = 5 * h + (int)identity_.category[i]; - } - - h = 5 * h + context_.GetHashCode(); - - sz = facet_.Length; - for(int i = 0; i < sz; i++) - { - h = 5 * h + (int)facet_[i]; - } - - h = 5 * h + (getSecure() ? 1 : 0); - - hashValue_ = h; - hashInitialized_ = true; - - return h; - } - } - - // - // Marshal the reference. - // - public virtual void streamWrite(BasicStream s) - { - // - // Don't write the identity here. Operations calling streamWrite - // write the identity. - // - - // - // For compatibility with the old FacetPath. - // - if(facet_.Length == 0) - { - s.writeStringSeq(null); - } - else - { - string[] facetPath = { facet_ }; - s.writeStringSeq(facetPath); - } - - s.writeByte((byte)mode_); - - s.writeBool(getSecure()); - - // Derived class writes the remainder of the reference. - } - - // - // Convert the reference to its string form. - // - public override string ToString() - { - // - // WARNING: Certain features, such as proxy validation in Glacier2, - // depend on the format of proxy strings. Changes to toString() and - // methods called to generate parts of the reference string could break - // these features. Please review for all features that depend on the - // format of proxyToString() before changing this and related code. - // - StringBuilder s = new StringBuilder(); - - // - // If the encoded identity string contains characters which - // the reference parser uses as separators, then we enclose - // the identity string in quotes. - // - string id = instance_.identityToString(identity_); - if(IceUtil.StringUtil.findFirstOf(id, " \t\n\r:@") != -1) - { - s.Append('"'); - s.Append(id); - s.Append('"'); - } - else - { - s.Append(id); - } - - if(facet_.Length > 0) - { - // - // If the encoded facet string contains characters which - // the reference parser uses as separators, then we enclose - // the facet string in quotes. - // - s.Append(" -f "); - string fs = IceUtil.StringUtil.escapeString(facet_, ""); - if(IceUtil.StringUtil.findFirstOf(fs, " \t\n\r:@") != -1) - { - s.Append('"'); - s.Append(fs); - s.Append('"'); - } - else - { - s.Append(fs); - } - } - - switch(mode_) - { - case Mode.ModeTwoway: - { - s.Append(" -t"); - break; - } - - case Mode.ModeOneway: - { - s.Append(" -o"); - break; - } - - case Mode.ModeBatchOneway: - { - s.Append(" -O"); - break; - } - - case Mode.ModeDatagram: - { - s.Append(" -d"); - break; - } - - case Mode.ModeBatchDatagram: - { - s.Append(" -D"); - break; - } - } - - if(getSecure()) - { - s.Append(" -s"); - } - - return s.ToString(); - - // Derived class writes the remainder of the string. - } - - public abstract Ice.ConnectionI getConnection(out bool comp); - - public override bool Equals(object obj) - { - // - // Note: if(this == obj) and type test are performed by each non-abstract derived class. - // - - Reference r = (Reference)obj; // Guaranteed to succeed. - - if(mode_ != r.mode_) - { - return false; - } - - if(!identity_.Equals(r.identity_)) - { - return false; - } - - if(!context_.Equals(r.context_)) - { - return false; - } - - if(!facet_.Equals(r.facet_)) - { - return false; - } - - return true; - } - - public Object Clone() - { - // - // A member-wise copy is safe because the members are immutable. - // - return MemberwiseClone(); - } - - private Instance instance_; - private Ice.Communicator communicator_; - private Mode mode_; - private Ice.Identity identity_; - private Ice.Context context_; - private static Ice.Context _emptyContext = new Ice.Context(); - private string facet_; - - protected int hashValue_; - protected bool hashInitialized_; - - protected Reference(Instance inst, - Ice.Communicator com, - Ice.Identity ident, - Ice.Context ctx, - string fac, - Mode md) - { - // - // Validate string arguments. - // - Debug.Assert(ident.name != null); - Debug.Assert(ident.category != null); - Debug.Assert(fac != null); - - instance_ = inst; - communicator_ = com; - mode_ = md; - identity_ = ident; - context_ = ctx == null ? _emptyContext : ctx; - facet_ = fac; - hashInitialized_ = false; - } - - protected static System.Random rand_ = new System.Random(unchecked((int)System.DateTime.Now.Ticks)); + // + // The change* methods (here and in derived classes) create + // a new reference based on the existing one, with the + // corresponding value changed. + // + public Reference changeContext(Ice.Context newContext) + { + if(newContext == null) + { + newContext = _emptyContext; + } + Reference r = instance_.referenceFactory().copy(this); + if(newContext.Count == 0) + { + r.context_ = _emptyContext; + } + else + { + r.context_ = (Ice.Context)newContext.Clone(); + } + return r; + } + + public Reference changeMode(Mode newMode) + { + if(newMode == mode_) + { + return this; + } + Reference r = instance_.referenceFactory().copy(this); + r.mode_ = newMode; + return r; + } + + public Reference changeIdentity(Ice.Identity newIdentity) + { + if(newIdentity.Equals(identity_)) + { + return this; + } + Reference r = instance_.referenceFactory().copy(this); + r.identity_ = newIdentity; // Identity is a value type, therefore a copy of newIdentity is made. + return r; + } + + public Reference changeFacet(string newFacet) + { + if(newFacet.Equals(facet_)) + { + return this; + } + Reference r = instance_.referenceFactory().copy(this); + r.facet_ = newFacet; + return r; + } + + public abstract Reference changeSecure(bool newSecure); + public abstract Reference changePreferSecure(bool newPreferSecure); + public abstract Reference changeRouter(Ice.RouterPrx newRouter); + public abstract Reference changeLocator(Ice.LocatorPrx newLocator); + public abstract Reference changeCompress(bool newCompress); + public abstract Reference changeTimeout(int newTimeout); + public abstract Reference changeConnectionId(string connectionId); + public abstract Reference changeCollocationOptimization(bool newCollocationOptimization); + public abstract Reference changeAdapterId(string newAdapterId); + public abstract Reference changeEndpoints(EndpointI[] newEndpoints); + public abstract Reference changeLocatorCacheTimeout(int newTimeout); + public abstract Reference changeCacheConnection(bool newCache); + public abstract Reference changeEndpointSelection(Ice.EndpointSelectionType newType); + public abstract Reference changeThreadPerConnection(bool newTpc); + + public override int GetHashCode() + { + lock(this) + { + if(hashInitialized_) + { + return hashValue_; + } + + int h = (int)mode_; + + int sz = identity_.name.Length; + for(int i = 0; i < sz; i++) + { + h = 5 * h + (int)identity_.name[i]; + } + + sz = identity_.category.Length; + for(int i = 0; i < sz; i++) + { + h = 5 * h + (int)identity_.category[i]; + } + + h = 5 * h + context_.GetHashCode(); + + sz = facet_.Length; + for(int i = 0; i < sz; i++) + { + h = 5 * h + (int)facet_[i]; + } + + h = 5 * h + (getSecure() ? 1 : 0); + + hashValue_ = h; + hashInitialized_ = true; + + return h; + } + } + + // + // Marshal the reference. + // + public virtual void streamWrite(BasicStream s) + { + // + // Don't write the identity here. Operations calling streamWrite + // write the identity. + // + + // + // For compatibility with the old FacetPath. + // + if(facet_.Length == 0) + { + s.writeStringSeq(null); + } + else + { + string[] facetPath = { facet_ }; + s.writeStringSeq(facetPath); + } + + s.writeByte((byte)mode_); + + s.writeBool(getSecure()); + + // Derived class writes the remainder of the reference. + } + + // + // Convert the reference to its string form. + // + public override string ToString() + { + // + // WARNING: Certain features, such as proxy validation in Glacier2, + // depend on the format of proxy strings. Changes to toString() and + // methods called to generate parts of the reference string could break + // these features. Please review for all features that depend on the + // format of proxyToString() before changing this and related code. + // + StringBuilder s = new StringBuilder(); + + // + // If the encoded identity string contains characters which + // the reference parser uses as separators, then we enclose + // the identity string in quotes. + // + string id = instance_.identityToString(identity_); + if(IceUtil.StringUtil.findFirstOf(id, " \t\n\r:@") != -1) + { + s.Append('"'); + s.Append(id); + s.Append('"'); + } + else + { + s.Append(id); + } + + if(facet_.Length > 0) + { + // + // If the encoded facet string contains characters which + // the reference parser uses as separators, then we enclose + // the facet string in quotes. + // + s.Append(" -f "); + string fs = IceUtil.StringUtil.escapeString(facet_, ""); + if(IceUtil.StringUtil.findFirstOf(fs, " \t\n\r:@") != -1) + { + s.Append('"'); + s.Append(fs); + s.Append('"'); + } + else + { + s.Append(fs); + } + } + + switch(mode_) + { + case Mode.ModeTwoway: + { + s.Append(" -t"); + break; + } + + case Mode.ModeOneway: + { + s.Append(" -o"); + break; + } + + case Mode.ModeBatchOneway: + { + s.Append(" -O"); + break; + } + + case Mode.ModeDatagram: + { + s.Append(" -d"); + break; + } + + case Mode.ModeBatchDatagram: + { + s.Append(" -D"); + break; + } + } + + if(getSecure()) + { + s.Append(" -s"); + } + + return s.ToString(); + + // Derived class writes the remainder of the string. + } + + public abstract Ice.ConnectionI getConnection(out bool comp); + + public override bool Equals(object obj) + { + // + // Note: if(this == obj) and type test are performed by each non-abstract derived class. + // + + Reference r = (Reference)obj; // Guaranteed to succeed. + + if(mode_ != r.mode_) + { + return false; + } + + if(!identity_.Equals(r.identity_)) + { + return false; + } + + if(!context_.Equals(r.context_)) + { + return false; + } + + if(!facet_.Equals(r.facet_)) + { + return false; + } + + return true; + } + + public Object Clone() + { + // + // A member-wise copy is safe because the members are immutable. + // + return MemberwiseClone(); + } + + private Instance instance_; + private Ice.Communicator communicator_; + private Mode mode_; + private Ice.Identity identity_; + private Ice.Context context_; + private static Ice.Context _emptyContext = new Ice.Context(); + private string facet_; + + protected int hashValue_; + protected bool hashInitialized_; + + protected Reference(Instance inst, + Ice.Communicator com, + Ice.Identity ident, + Ice.Context ctx, + string fac, + Mode md) + { + // + // Validate string arguments. + // + Debug.Assert(ident.name != null); + Debug.Assert(ident.category != null); + Debug.Assert(fac != null); + + instance_ = inst; + communicator_ = com; + mode_ = md; + identity_ = ident; + context_ = ctx == null ? _emptyContext : ctx; + facet_ = fac; + hashInitialized_ = false; + } + + protected static System.Random rand_ = new System.Random(unchecked((int)System.DateTime.Now.Ticks)); } public class FixedReference : Reference { - public FixedReference(Instance inst, - Ice.Communicator com, - Ice.Identity ident, - Ice.Context ctx, - string fs, - Reference.Mode md, - Ice.ConnectionI[] fixedConns) - : base(inst, com, ident, ctx, fs, md) - { - _fixedConnections = fixedConns; - } - - public Ice.ConnectionI[] getFixedConnections() - { - return _fixedConnections; - } - - public override bool getSecure() - { - return false; - } - - public override bool getPreferSecure() - { - return false; - } - - public override string getAdapterId() - { - return ""; - } - - public override EndpointI[] getEndpoints() - { - return new EndpointI[0]; - } - - public override bool getCollocationOptimization() - { - return false; - } - - public override int getLocatorCacheTimeout() - { - return 0; - } - - public override bool getCacheConnection() - { - return false; - } - - public override Ice.EndpointSelectionType getEndpointSelection() - { - return Ice.EndpointSelectionType.Random; - } + public FixedReference(Instance inst, + Ice.Communicator com, + Ice.Identity ident, + Ice.Context ctx, + string fs, + Reference.Mode md, + Ice.ConnectionI[] fixedConns) + : base(inst, com, ident, ctx, fs, md) + { + _fixedConnections = fixedConns; + } + + public Ice.ConnectionI[] getFixedConnections() + { + return _fixedConnections; + } + + public override bool getSecure() + { + return false; + } + + public override bool getPreferSecure() + { + return false; + } + + public override string getAdapterId() + { + return ""; + } + + public override EndpointI[] getEndpoints() + { + return new EndpointI[0]; + } + + public override bool getCollocationOptimization() + { + return false; + } + + public override int getLocatorCacheTimeout() + { + return 0; + } + + public override bool getCacheConnection() + { + return false; + } + + public override Ice.EndpointSelectionType getEndpointSelection() + { + return Ice.EndpointSelectionType.Random; + } public override bool getThreadPerConnection() { return false; } - public override Reference changeSecure(bool sec) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeSecure(bool sec) + { + throw new Ice.FixedProxyException(); + } - public override Reference changePreferSecure(bool prefSec) - { - throw new Ice.FixedProxyException(); - } + public override Reference changePreferSecure(bool prefSec) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeRouter(Ice.RouterPrx newRouter) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeRouter(Ice.RouterPrx newRouter) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeLocator(Ice.LocatorPrx newLocator) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeLocator(Ice.LocatorPrx newLocator) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeCompress(bool newCompress) - { - // TODO: FixedReferences should probably have a _compress flag, - // that gets its default from the fixed connection this reference - // refers to. This should be changable with changeCompress(). - throw new Ice.FixedProxyException(); - } + public override Reference changeCompress(bool newCompress) + { + // TODO: FixedReferences should probably have a _compress flag, + // that gets its default from the fixed connection this reference + // refers to. This should be changable with changeCompress(). + throw new Ice.FixedProxyException(); + } - public override Reference changeTimeout(int newTimeout) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeTimeout(int newTimeout) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeConnectionId(string connectionId) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeConnectionId(string connectionId) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeCollocationOptimization(bool newCollocationOptimization) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeCollocationOptimization(bool newCollocationOptimization) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeAdapterId(string newAdapterId) + public override Reference changeAdapterId(string newAdapterId) { - throw new Ice.FixedProxyException(); - } + throw new Ice.FixedProxyException(); + } - public override Reference changeEndpoints(EndpointI[] newEndpoints) + public override Reference changeEndpoints(EndpointI[] newEndpoints) { - throw new Ice.FixedProxyException(); - } + throw new Ice.FixedProxyException(); + } - public override Reference changeLocatorCacheTimeout(int newTimeout) + public override Reference changeLocatorCacheTimeout(int newTimeout) { - throw new Ice.FixedProxyException(); - } + throw new Ice.FixedProxyException(); + } - public override Reference changeCacheConnection(bool newCache) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeCacheConnection(bool newCache) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeEndpointSelection(Ice.EndpointSelectionType newType) - { - throw new Ice.FixedProxyException(); - } + public override Reference changeEndpointSelection(Ice.EndpointSelectionType newType) + { + throw new Ice.FixedProxyException(); + } + + public override Reference changeThreadPerConnection(bool newTpc) + { + throw new Ice.FixedProxyException(); + } - public override Reference changeThreadPerConnection(bool newTpc) + public override void streamWrite(BasicStream s) { throw new Ice.FixedProxyException(); } - public override void streamWrite(BasicStream s) - { - throw new Ice.FixedProxyException(); - } - - public override string ToString() - { - throw new Ice.FixedProxyException(); - } - - public override Ice.ConnectionI getConnection(out bool compress) - { - Ice.ConnectionI[] filteredConns = filterConnections(_fixedConnections); - if(filteredConns.Length == 0) - { - Ice.NoEndpointException ex = new Ice.NoEndpointException(); - ex.proxy = ""; // No stringified representation for fixed proxies. - throw ex; - } - - Ice.ConnectionI connection = filteredConns[0]; - Debug.Assert(connection != null); - connection.throwException(); // Throw in case our connection is already destroyed. - compress = connection.endpoint().compress(); - - return connection; - } - - public override bool Equals(object obj) - { - if(object.ReferenceEquals(this, obj)) - { - return true; - } - if(!(obj is FixedReference)) - { - return false; - } - FixedReference rhs = (FixedReference)obj; - if(!base.Equals(rhs)) - { - return false; - } - return IceUtil.Arrays.Equals(_fixedConnections, rhs._fixedConnections); - } + public override string ToString() + { + throw new Ice.FixedProxyException(); + } + + public override Ice.ConnectionI getConnection(out bool compress) + { + Ice.ConnectionI[] filteredConns = filterConnections(_fixedConnections); + if(filteredConns.Length == 0) + { + Ice.NoEndpointException ex = new Ice.NoEndpointException(); + ex.proxy = ""; // No stringified representation for fixed proxies. + throw ex; + } + + Ice.ConnectionI connection = filteredConns[0]; + Debug.Assert(connection != null); + connection.throwException(); // Throw in case our connection is already destroyed. + compress = connection.endpoint().compress(); + + return connection; + } + + public override bool Equals(object obj) + { + if(object.ReferenceEquals(this, obj)) + { + return true; + } + if(!(obj is FixedReference)) + { + return false; + } + FixedReference rhs = (FixedReference)obj; + if(!base.Equals(rhs)) + { + return false; + } + return IceUtil.Arrays.Equals(_fixedConnections, rhs._fixedConnections); + } // // If we override Equals, we must also override GetHashCode. // - public override int GetHashCode() - { + public override int GetHashCode() + { return base.GetHashCode(); } - // - // Filter connections based on criteria from this reference. - // - public Ice.ConnectionI[] - filterConnections(Ice.ConnectionI[] allConnections) - { - ArrayList connections = new ArrayList(); - - switch(getMode()) - { - case Reference.Mode.ModeTwoway: - case Reference.Mode.ModeOneway: - case Reference.Mode.ModeBatchOneway: - { - // - // Filter out datagram endpoints. - // - for(int i = 0; i < allConnections.Length; ++i) - { - if(!allConnections[i].endpoint().datagram()) - { - connections.Add(allConnections[i]); - } - } - - break; - } - - case Reference.Mode.ModeDatagram: - case Reference.Mode.ModeBatchDatagram: - { - // - // Filter out non-datagram endpoints. - // - for(int i = 0; i < allConnections.Length; ++i) - { - if(allConnections[i].endpoint().datagram()) - { - connections.Add(allConnections[i]); - } - } - - break; - } - } - - // - // Randomize the order of connections. - // - for(int i = 0; i < connections.Count - 2; ++i) - { - int r = rand_.Next(connections.Count - i) + i; - Debug.Assert(r >= i && r < connections.Count); - if(r != i) - { - object tmp = connections[i]; - connections[i] = connections[r]; - connections[r] = tmp; - } - } - - // - // If a secure connection is requested or secure overrides is set, - // remove all non-secure endpoints. Otherwise if preferSecure is set - // make secure endpoints prefered. By default make non-secure - // endpoints preferred over secure endpoints. - // - DefaultsAndOverrides overrides = getInstance().defaultsAndOverrides(); - if(overrides.overrideSecure ? overrides.overrideSecureValue : getSecure()) - { - ArrayList tmp = new ArrayList(); - foreach(Ice.ConnectionI connection in connections) - { - if(connection.endpoint().secure()) - { - tmp.Add(connection); - } - } - connections = tmp; - } - else if(getPreferSecure()) - { - IceUtil.Arrays.Sort(ref connections, _preferSecureConnectionComparator); - } - else - { - IceUtil.Arrays.Sort(ref connections, _preferNonSecureConnectionComparator); - } - - Ice.ConnectionI[] arr = new Ice.ConnectionI[connections.Count]; - if(arr.Length != 0) - { - connections.CopyTo(arr); - } - return arr; - } - - private class ConnectionComparator : IComparer - { - public ConnectionComparator(bool preferSecure) - { - _preferSecure = preferSecure; - } - - public int Compare(object l, object r) - { - Ice.ConnectionI lc = (Ice.ConnectionI)l; - Ice.ConnectionI rc = (Ice.ConnectionI)r; - bool ls = lc.endpoint().secure(); - bool rs = rc.endpoint().secure(); - if((ls && rs) || (!ls && !rs)) - { - return 0; - } - else if(!ls && rs) - { - if(_preferSecure) - { - return 1; - } - else - { - return -1; - } - } - else - { - if(_preferSecure) - { - return -1; - } - else - { - return 1; - } - } - } - - private bool _preferSecure; - } - - private static ConnectionComparator _preferNonSecureConnectionComparator = new ConnectionComparator(false); - private static ConnectionComparator _preferSecureConnectionComparator = new ConnectionComparator(true); - private Ice.ConnectionI[] _fixedConnections; + // + // Filter connections based on criteria from this reference. + // + public Ice.ConnectionI[] + filterConnections(Ice.ConnectionI[] allConnections) + { + ArrayList connections = new ArrayList(); + + switch(getMode()) + { + case Reference.Mode.ModeTwoway: + case Reference.Mode.ModeOneway: + case Reference.Mode.ModeBatchOneway: + { + // + // Filter out datagram endpoints. + // + for(int i = 0; i < allConnections.Length; ++i) + { + if(!allConnections[i].endpoint().datagram()) + { + connections.Add(allConnections[i]); + } + } + + break; + } + + case Reference.Mode.ModeDatagram: + case Reference.Mode.ModeBatchDatagram: + { + // + // Filter out non-datagram endpoints. + // + for(int i = 0; i < allConnections.Length; ++i) + { + if(allConnections[i].endpoint().datagram()) + { + connections.Add(allConnections[i]); + } + } + + break; + } + } + + // + // Randomize the order of connections. + // + for(int i = 0; i < connections.Count - 2; ++i) + { + int r = rand_.Next(connections.Count - i) + i; + Debug.Assert(r >= i && r < connections.Count); + if(r != i) + { + object tmp = connections[i]; + connections[i] = connections[r]; + connections[r] = tmp; + } + } + + // + // If a secure connection is requested or secure overrides is set, + // remove all non-secure endpoints. Otherwise if preferSecure is set + // make secure endpoints prefered. By default make non-secure + // endpoints preferred over secure endpoints. + // + DefaultsAndOverrides overrides = getInstance().defaultsAndOverrides(); + if(overrides.overrideSecure ? overrides.overrideSecureValue : getSecure()) + { + ArrayList tmp = new ArrayList(); + foreach(Ice.ConnectionI connection in connections) + { + if(connection.endpoint().secure()) + { + tmp.Add(connection); + } + } + connections = tmp; + } + else if(getPreferSecure()) + { + IceUtil.Arrays.Sort(ref connections, _preferSecureConnectionComparator); + } + else + { + IceUtil.Arrays.Sort(ref connections, _preferNonSecureConnectionComparator); + } + + Ice.ConnectionI[] arr = new Ice.ConnectionI[connections.Count]; + if(arr.Length != 0) + { + connections.CopyTo(arr); + } + return arr; + } + + private class ConnectionComparator : IComparer + { + public ConnectionComparator(bool preferSecure) + { + _preferSecure = preferSecure; + } + + public int Compare(object l, object r) + { + Ice.ConnectionI lc = (Ice.ConnectionI)l; + Ice.ConnectionI rc = (Ice.ConnectionI)r; + bool ls = lc.endpoint().secure(); + bool rs = rc.endpoint().secure(); + if((ls && rs) || (!ls && !rs)) + { + return 0; + } + else if(!ls && rs) + { + if(_preferSecure) + { + return 1; + } + else + { + return -1; + } + } + else + { + if(_preferSecure) + { + return -1; + } + else + { + return 1; + } + } + } + + private bool _preferSecure; + } + + private static ConnectionComparator _preferNonSecureConnectionComparator = new ConnectionComparator(false); + private static ConnectionComparator _preferSecureConnectionComparator = new ConnectionComparator(true); + private Ice.ConnectionI[] _fixedConnections; } public abstract class RoutableReference : Reference { - public override RouterInfo getRouterInfo() - { - return _routerInfo; - } - - public EndpointI[] getRoutedEndpoints() - { - if(_routerInfo != null) - { - // - // If we route, we send everything to the router's client - // proxy endpoints. - // - return _routerInfo.getClientEndpoints(); - } - return new EndpointI[0]; - } - - public override bool getSecure() - { - return _secure; - } - - public override bool getPreferSecure() - { - return _preferSecure; - } - - public override bool getCollocationOptimization() - { - return _collocationOptimization; - } - - public override bool getCacheConnection() - { - return _cacheConnection; - } - - public override Ice.EndpointSelectionType getEndpointSelection() - { - return _endpointSelection; - } + public override RouterInfo getRouterInfo() + { + return _routerInfo; + } + + public EndpointI[] getRoutedEndpoints() + { + if(_routerInfo != null) + { + // + // If we route, we send everything to the router's client + // proxy endpoints. + // + return _routerInfo.getClientEndpoints(); + } + return new EndpointI[0]; + } + + public override bool getSecure() + { + return _secure; + } + + public override bool getPreferSecure() + { + return _preferSecure; + } + + public override bool getCollocationOptimization() + { + return _collocationOptimization; + } + + public override bool getCacheConnection() + { + return _cacheConnection; + } + + public override Ice.EndpointSelectionType getEndpointSelection() + { + return _endpointSelection; + } public override bool getThreadPerConnection() { return _threadPerConnection; } - public override Reference changeSecure(bool newSecure) - { - if(newSecure == _secure) - { - return this; - } - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r._secure = newSecure; - return r; - } - - public override Reference changePreferSecure(bool newPreferSecure) - { - if(newPreferSecure == _preferSecure) - { - return this; - } - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r._preferSecure = newPreferSecure; - return r; - } - - public override Reference changeRouter(Ice.RouterPrx newRouter) - { - RouterInfo newRouterInfo = getInstance().routerManager().get(newRouter); - if(newRouterInfo != null && _routerInfo != null && newRouterInfo.Equals(_routerInfo)) - { - return this; - } - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r._routerInfo = newRouterInfo; - return r; - } - - public override Reference changeCollocationOptimization(bool newCollocationOptimization) - { - if(newCollocationOptimization == _collocationOptimization) - { - return this; - } - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r._collocationOptimization = newCollocationOptimization; - return r; - } - - public override Reference changeCompress(bool newCompress) - { - if(overrideCompress_ && compress_ == newCompress) - { - return this; - } - - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r.compress_ = newCompress; - r.overrideCompress_ = true; - return r; - } - - public override Reference changeTimeout(int newTimeout) - { - if(overrideTimeout_ && timeout_ == newTimeout) - { - return this; - } - - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r.timeout_ = newTimeout; - r.overrideTimeout_ = true; - return r; - } - - public override Reference changeConnectionId(string id) - { - if(connectionId_.Equals(id)) - { - return this; - } - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r.connectionId_ = id; - return r; - } - - public override Reference changeCacheConnection(bool newCache) - { - if(newCache == _cacheConnection) - { - return this; - } - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r._cacheConnection = newCache; - return r; - } - - public override Reference changeEndpointSelection(Ice.EndpointSelectionType newType) - { - if(newType == _endpointSelection) - { - return this; - } - RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); - r._endpointSelection = newType; - return r; - } - - public override Reference changeThreadPerConnection(bool newTpc) + public override Reference changeSecure(bool newSecure) + { + if(newSecure == _secure) + { + return this; + } + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r._secure = newSecure; + return r; + } + + public override Reference changePreferSecure(bool newPreferSecure) + { + if(newPreferSecure == _preferSecure) + { + return this; + } + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r._preferSecure = newPreferSecure; + return r; + } + + public override Reference changeRouter(Ice.RouterPrx newRouter) + { + RouterInfo newRouterInfo = getInstance().routerManager().get(newRouter); + if(newRouterInfo != null && _routerInfo != null && newRouterInfo.Equals(_routerInfo)) + { + return this; + } + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r._routerInfo = newRouterInfo; + return r; + } + + public override Reference changeCollocationOptimization(bool newCollocationOptimization) + { + if(newCollocationOptimization == _collocationOptimization) + { + return this; + } + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r._collocationOptimization = newCollocationOptimization; + return r; + } + + public override Reference changeCompress(bool newCompress) + { + if(overrideCompress_ && compress_ == newCompress) + { + return this; + } + + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r.compress_ = newCompress; + r.overrideCompress_ = true; + return r; + } + + public override Reference changeTimeout(int newTimeout) + { + if(overrideTimeout_ && timeout_ == newTimeout) + { + return this; + } + + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r.timeout_ = newTimeout; + r.overrideTimeout_ = true; + return r; + } + + public override Reference changeConnectionId(string id) + { + if(connectionId_.Equals(id)) + { + return this; + } + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r.connectionId_ = id; + return r; + } + + public override Reference changeCacheConnection(bool newCache) + { + if(newCache == _cacheConnection) + { + return this; + } + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r._cacheConnection = newCache; + return r; + } + + public override Reference changeEndpointSelection(Ice.EndpointSelectionType newType) + { + if(newType == _endpointSelection) + { + return this; + } + RoutableReference r = (RoutableReference)getInstance().referenceFactory().copy(this); + r._endpointSelection = newType; + return r; + } + + public override Reference changeThreadPerConnection(bool newTpc) { if(newTpc == _threadPerConnection) { @@ -898,817 +898,817 @@ namespace IceInternal return r; } - public override bool Equals(object obj) - { - // - // Note: if(this == obj) and type test are performed by each non-abstract derived class. - // - - if(!base.Equals(obj)) - { - return false; - } - RoutableReference rhs = (RoutableReference)obj; // Guaranteed to succeed. - if(_secure != rhs._secure) - { - return false; - } - if(_preferSecure != rhs._preferSecure) - { - return false; - } - if(_collocationOptimization != rhs._collocationOptimization) - { - return false; - } - if(_cacheConnection != rhs._cacheConnection) - { - return false; - } - if(_endpointSelection != rhs._endpointSelection) - { - return false; - } - if(overrideCompress_ != rhs.overrideCompress_) - { - return false; - } - if(overrideCompress_ && compress_ != rhs.compress_) - { - return false; - } - if(overrideTimeout_ != rhs.overrideTimeout_) - { - return false; - } - if(overrideTimeout_ && timeout_ != rhs.timeout_) - { - return false; - } - if(!connectionId_.Equals(rhs.connectionId_)) - { - return false; - } + public override bool Equals(object obj) + { + // + // Note: if(this == obj) and type test are performed by each non-abstract derived class. + // + + if(!base.Equals(obj)) + { + return false; + } + RoutableReference rhs = (RoutableReference)obj; // Guaranteed to succeed. + if(_secure != rhs._secure) + { + return false; + } + if(_preferSecure != rhs._preferSecure) + { + return false; + } + if(_collocationOptimization != rhs._collocationOptimization) + { + return false; + } + if(_cacheConnection != rhs._cacheConnection) + { + return false; + } + if(_endpointSelection != rhs._endpointSelection) + { + return false; + } + if(overrideCompress_ != rhs.overrideCompress_) + { + return false; + } + if(overrideCompress_ && compress_ != rhs.compress_) + { + return false; + } + if(overrideTimeout_ != rhs.overrideTimeout_) + { + return false; + } + if(overrideTimeout_ && timeout_ != rhs.timeout_) + { + return false; + } + if(!connectionId_.Equals(rhs.connectionId_)) + { + return false; + } if(_threadPerConnection != rhs._threadPerConnection) { return false; } - return _routerInfo == null ? rhs._routerInfo == null : _routerInfo.Equals(rhs._routerInfo); - } + return _routerInfo == null ? rhs._routerInfo == null : _routerInfo.Equals(rhs._routerInfo); + } // // If we override Equals, we must also override GetHashCode. // - public override int GetHashCode() - { + public override int GetHashCode() + { return base.GetHashCode(); } - protected RoutableReference(Instance inst, - Ice.Communicator com, - Ice.Identity ident, - Ice.Context ctx, - string fac, - Reference.Mode md, - bool sec, - bool prefSec, - RouterInfo rtrInfo, - bool collocationOpt, + protected RoutableReference(Instance inst, + Ice.Communicator com, + Ice.Identity ident, + Ice.Context ctx, + string fac, + Reference.Mode md, + bool sec, + bool prefSec, + RouterInfo rtrInfo, + bool collocationOpt, bool cacheConnection, Ice.EndpointSelectionType endpointSelection, bool threadPerConnection) - : base(inst, com, ident, ctx, fac, md) - { - _secure = sec; - _preferSecure = prefSec; - _routerInfo = rtrInfo; - _collocationOptimization = collocationOpt; - _cacheConnection = cacheConnection; - _endpointSelection = endpointSelection; - overrideCompress_ = false; - compress_ = false; - overrideTimeout_ = false; - timeout_ = -1; + : base(inst, com, ident, ctx, fac, md) + { + _secure = sec; + _preferSecure = prefSec; + _routerInfo = rtrInfo; + _collocationOptimization = collocationOpt; + _cacheConnection = cacheConnection; + _endpointSelection = endpointSelection; + overrideCompress_ = false; + compress_ = false; + overrideTimeout_ = false; + timeout_ = -1; _threadPerConnection = threadPerConnection; - } - - protected void applyOverrides(ref EndpointI[] endpts) - { - for(int i = 0; i < endpts.Length; ++i) - { - endpts[i] = endpts[i].connectionId(connectionId_); - if(overrideCompress_) - { - endpts[i] = endpts[i].compress(compress_); - } - if(overrideTimeout_) - { - endpts[i] = endpts[i].timeout(timeout_); - } - } - } - - protected Ice.ConnectionI createConnection(EndpointI[] allEndpoints, out bool comp) - { - ArrayList endpoints = new ArrayList(); - - // - // Filter out unknown endpoints. - // - for(int i = 0; i < allEndpoints.Length; i++) - { - if(!allEndpoints[i].unknown()) - { - endpoints.Add(allEndpoints[i]); - } - } - - // - // Filter out endpoints according to the mode of the reference. - // - switch(getMode()) - { - case Reference.Mode.ModeTwoway: - case Reference.Mode.ModeOneway: - case Reference.Mode.ModeBatchOneway: - { - // - // Filter out datagram endpoints. - // - ArrayList tmp = new ArrayList(); - foreach(EndpointI endpoint in endpoints) - { - if(!endpoint.datagram()) - { - tmp.Add(endpoint); - } - } - endpoints = tmp; - break; - } - - case Reference.Mode.ModeDatagram: - case Reference.Mode.ModeBatchDatagram: - { - // - // Filter out non-datagram endpoints. - // - ArrayList tmp = new ArrayList(); - foreach(EndpointI endpoint in endpoints) - { - if(endpoint.datagram()) - { - tmp.Add(endpoint); - } - } - endpoints = tmp; - break; - } - } - - // - // Sort the endpoints according to the endpoint selection type. - // - switch(getEndpointSelection()) - { - case Ice.EndpointSelectionType.Random: - { - for(int i = 0; i < endpoints.Count - 2; ++i) - { - int r = rand_.Next(endpoints.Count - i) + i; - Debug.Assert(r >= i && r < endpoints.Count); - if(r != i) - { - object tmp = endpoints[i]; - endpoints[i] = endpoints[r]; - endpoints[r] = tmp; - } - } - break; - } - case Ice.EndpointSelectionType.Ordered: - { - // Nothing to do. - break; - } - default: - { - Debug.Assert(false); - break; - } - } - - // - // If a secure connection is requested or secure overrides - // is set, remove all non-secure endpoints. Otherwise make - // non-secure endpoints preferred over secure endpoints by - // partitioning the endpoint vector, so that non-secure - // endpoints come first. - // - DefaultsAndOverrides overrides = getInstance().defaultsAndOverrides(); - if(overrides.overrideSecure ? overrides.overrideSecureValue : getSecure()) - { - ArrayList tmp = new ArrayList(); - foreach(EndpointI endpoint in endpoints) - { - if(endpoint.secure()) - { - tmp.Add(endpoint); - } - } - endpoints = tmp; - } - else if(getPreferSecure()) - { - IceUtil.Arrays.Sort(ref endpoints, _preferSecureEndpointComparator); - } - else - { - IceUtil.Arrays.Sort(ref endpoints, _preferNonSecureEndpointComparator); - } - - if(endpoints.Count == 0) - { - Ice.NoEndpointException ex = new Ice.NoEndpointException(); - ex.proxy = ToString(); - throw ex; - } - - // - // Finally, create the connection. - // - OutgoingConnectionFactory factory = getInstance().outgoingConnectionFactory(); - if(getCacheConnection() || endpoints.Count == 1) - { - // - // Get an existing connection or create one if there's no - // existing connection to one of the given endpoints. - // - EndpointI[] arr = new EndpointI[endpoints.Count]; - endpoints.CopyTo(arr); - return factory.create(arr, false, _threadPerConnection, out comp); - } - else - { - // - // Go through the list of endpoints and try to create the - // connection until it succeeds. This is different from just - // calling create() with the given endpoints since this might - // create a new connection even if there's an existing - // connection for one of the endpoints. - // - Ice.LocalException exception = null; - EndpointI[] endpoint = new EndpointI[1]; - - foreach(EndpointI e in endpoints) - { - try - { - endpoint[0] = e; - return factory.create(endpoint, e != endpoints[endpoints.Count - 1], _threadPerConnection, + } + + protected void applyOverrides(ref EndpointI[] endpts) + { + for(int i = 0; i < endpts.Length; ++i) + { + endpts[i] = endpts[i].connectionId(connectionId_); + if(overrideCompress_) + { + endpts[i] = endpts[i].compress(compress_); + } + if(overrideTimeout_) + { + endpts[i] = endpts[i].timeout(timeout_); + } + } + } + + protected Ice.ConnectionI createConnection(EndpointI[] allEndpoints, out bool comp) + { + ArrayList endpoints = new ArrayList(); + + // + // Filter out unknown endpoints. + // + for(int i = 0; i < allEndpoints.Length; i++) + { + if(!allEndpoints[i].unknown()) + { + endpoints.Add(allEndpoints[i]); + } + } + + // + // Filter out endpoints according to the mode of the reference. + // + switch(getMode()) + { + case Reference.Mode.ModeTwoway: + case Reference.Mode.ModeOneway: + case Reference.Mode.ModeBatchOneway: + { + // + // Filter out datagram endpoints. + // + ArrayList tmp = new ArrayList(); + foreach(EndpointI endpoint in endpoints) + { + if(!endpoint.datagram()) + { + tmp.Add(endpoint); + } + } + endpoints = tmp; + break; + } + + case Reference.Mode.ModeDatagram: + case Reference.Mode.ModeBatchDatagram: + { + // + // Filter out non-datagram endpoints. + // + ArrayList tmp = new ArrayList(); + foreach(EndpointI endpoint in endpoints) + { + if(endpoint.datagram()) + { + tmp.Add(endpoint); + } + } + endpoints = tmp; + break; + } + } + + // + // Sort the endpoints according to the endpoint selection type. + // + switch(getEndpointSelection()) + { + case Ice.EndpointSelectionType.Random: + { + for(int i = 0; i < endpoints.Count - 2; ++i) + { + int r = rand_.Next(endpoints.Count - i) + i; + Debug.Assert(r >= i && r < endpoints.Count); + if(r != i) + { + object tmp = endpoints[i]; + endpoints[i] = endpoints[r]; + endpoints[r] = tmp; + } + } + break; + } + case Ice.EndpointSelectionType.Ordered: + { + // Nothing to do. + break; + } + default: + { + Debug.Assert(false); + break; + } + } + + // + // If a secure connection is requested or secure overrides + // is set, remove all non-secure endpoints. Otherwise make + // non-secure endpoints preferred over secure endpoints by + // partitioning the endpoint vector, so that non-secure + // endpoints come first. + // + DefaultsAndOverrides overrides = getInstance().defaultsAndOverrides(); + if(overrides.overrideSecure ? overrides.overrideSecureValue : getSecure()) + { + ArrayList tmp = new ArrayList(); + foreach(EndpointI endpoint in endpoints) + { + if(endpoint.secure()) + { + tmp.Add(endpoint); + } + } + endpoints = tmp; + } + else if(getPreferSecure()) + { + IceUtil.Arrays.Sort(ref endpoints, _preferSecureEndpointComparator); + } + else + { + IceUtil.Arrays.Sort(ref endpoints, _preferNonSecureEndpointComparator); + } + + if(endpoints.Count == 0) + { + Ice.NoEndpointException ex = new Ice.NoEndpointException(); + ex.proxy = ToString(); + throw ex; + } + + // + // Finally, create the connection. + // + OutgoingConnectionFactory factory = getInstance().outgoingConnectionFactory(); + if(getCacheConnection() || endpoints.Count == 1) + { + // + // Get an existing connection or create one if there's no + // existing connection to one of the given endpoints. + // + EndpointI[] arr = new EndpointI[endpoints.Count]; + endpoints.CopyTo(arr); + return factory.create(arr, false, _threadPerConnection, out comp); + } + else + { + // + // Go through the list of endpoints and try to create the + // connection until it succeeds. This is different from just + // calling create() with the given endpoints since this might + // create a new connection even if there's an existing + // connection for one of the endpoints. + // + Ice.LocalException exception = null; + EndpointI[] endpoint = new EndpointI[1]; + + foreach(EndpointI e in endpoints) + { + try + { + endpoint[0] = e; + return factory.create(endpoint, e != endpoints[endpoints.Count - 1], _threadPerConnection, out comp); - } - catch(Ice.LocalException ex) - { - exception = ex; - } - } - - Debug.Assert(exception != null); - throw exception; - } - } - - private class EndpointComparator : IComparer - { - public EndpointComparator(bool preferSecure) - { - _preferSecure = preferSecure; - } - - public int Compare(object l, object r) - { - IceInternal.EndpointI le = (IceInternal.EndpointI)l; - IceInternal.EndpointI re = (IceInternal.EndpointI)r; - bool ls = le.secure(); - bool rs = re.secure(); - if((ls && rs) || (!ls && !rs)) - { - return 0; - } - else if(!ls && rs) - { - if(_preferSecure) - { - return 1; - } - else - { - return -1; - } - } - else - { - if(_preferSecure) - { - return -1; - } - else - { - return 1; - } - } - } - - private bool _preferSecure; - } - - private static EndpointComparator _preferNonSecureEndpointComparator = new EndpointComparator(false); - private static EndpointComparator _preferSecureEndpointComparator = new EndpointComparator(true); - - private bool _secure; - private bool _preferSecure; - private RouterInfo _routerInfo; // Null if no router is used. - private bool _collocationOptimization; - private bool _cacheConnection; - private Ice.EndpointSelectionType _endpointSelection; - private string connectionId_ = ""; - private bool overrideCompress_; - private bool compress_; - private bool overrideTimeout_; - private int timeout_; - private bool _threadPerConnection; + } + catch(Ice.LocalException ex) + { + exception = ex; + } + } + + Debug.Assert(exception != null); + throw exception; + } + } + + private class EndpointComparator : IComparer + { + public EndpointComparator(bool preferSecure) + { + _preferSecure = preferSecure; + } + + public int Compare(object l, object r) + { + IceInternal.EndpointI le = (IceInternal.EndpointI)l; + IceInternal.EndpointI re = (IceInternal.EndpointI)r; + bool ls = le.secure(); + bool rs = re.secure(); + if((ls && rs) || (!ls && !rs)) + { + return 0; + } + else if(!ls && rs) + { + if(_preferSecure) + { + return 1; + } + else + { + return -1; + } + } + else + { + if(_preferSecure) + { + return -1; + } + else + { + return 1; + } + } + } + + private bool _preferSecure; + } + + private static EndpointComparator _preferNonSecureEndpointComparator = new EndpointComparator(false); + private static EndpointComparator _preferSecureEndpointComparator = new EndpointComparator(true); + + private bool _secure; + private bool _preferSecure; + private RouterInfo _routerInfo; // Null if no router is used. + private bool _collocationOptimization; + private bool _cacheConnection; + private Ice.EndpointSelectionType _endpointSelection; + private string connectionId_ = ""; + private bool overrideCompress_; + private bool compress_; + private bool overrideTimeout_; + private int timeout_; + private bool _threadPerConnection; } public class DirectReference : RoutableReference { - public DirectReference(Instance inst, - Ice.Communicator com, - Ice.Identity ident, - Ice.Context ctx, - string fs, - Reference.Mode md, - bool sec, - bool prefSec, - EndpointI[] endpts, - RouterInfo rtrInfo, - bool collocationOpt, + public DirectReference(Instance inst, + Ice.Communicator com, + Ice.Identity ident, + Ice.Context ctx, + string fs, + Reference.Mode md, + bool sec, + bool prefSec, + EndpointI[] endpts, + RouterInfo rtrInfo, + bool collocationOpt, bool cacheConnection, Ice.EndpointSelectionType endpointSelection, bool threadPerConnection) - : base(inst, com, ident, ctx, fs, md, sec, prefSec, rtrInfo, collocationOpt, cacheConnection, + : base(inst, com, ident, ctx, fs, md, sec, prefSec, rtrInfo, collocationOpt, cacheConnection, endpointSelection, threadPerConnection) - { - _endpoints = endpts; - } - - public override string getAdapterId() - { - return ""; - } - - public override EndpointI[] getEndpoints() - { - return _endpoints; - } - - public override int getLocatorCacheTimeout() - { - return 0; - } - - public override Reference changeLocator(Ice.LocatorPrx newLocator) - { - return this; - } - - public override Reference changeCompress(bool newCompress) - { - DirectReference r = (DirectReference)base.changeCompress(newCompress); - if(r != this) // Also override the compress flag on the endpoints if it was updated. - { - EndpointI[] newEndpoints = new EndpointI[_endpoints.Length]; - for(int i = 0; i < _endpoints.Length; i++) - { - newEndpoints[i] = _endpoints[i].compress(newCompress); - } - r._endpoints = newEndpoints; - } - return r; - } - - public override Reference changeTimeout(int newTimeout) - { - DirectReference r = (DirectReference)base.changeTimeout(newTimeout); - if(r != this) // Also override the timeout on the endpoints if it was updated. - { - EndpointI[] newEndpoints = new EndpointI[_endpoints.Length]; - for(int i = 0; i < _endpoints.Length; i++) - { - newEndpoints[i] = _endpoints[i].timeout(newTimeout); - } - r._endpoints = newEndpoints; - } - return r; - } - - public override Reference changeConnectionId(string connectionId) - { - DirectReference r = (DirectReference)base.changeConnectionId(connectionId); - if(r != this) // Also override the connection id on the endpoints if it was updated. - { - EndpointI[] newEndpoints = new EndpointI[_endpoints.Length]; - for(int i = 0; i < _endpoints.Length; i++) - { - newEndpoints[i] = _endpoints[i].connectionId(connectionId); - } - r._endpoints = newEndpoints; - } - return r; - } - - public override Reference changeAdapterId(string newAdapterId) - { - if(newAdapterId == null || newAdapterId.Length == 0) - { - return this; - } - LocatorInfo locatorInfo = - getInstance().locatorManager().get(getInstance().referenceFactory().getDefaultLocator()); - return getInstance().referenceFactory().create( - getIdentity(), getContext(), getFacet(), getMode(), getSecure(), getPreferSecure(), newAdapterId, - getRouterInfo(), locatorInfo, getCollocationOptimization(), getCacheConnection(), + { + _endpoints = endpts; + } + + public override string getAdapterId() + { + return ""; + } + + public override EndpointI[] getEndpoints() + { + return _endpoints; + } + + public override int getLocatorCacheTimeout() + { + return 0; + } + + public override Reference changeLocator(Ice.LocatorPrx newLocator) + { + return this; + } + + public override Reference changeCompress(bool newCompress) + { + DirectReference r = (DirectReference)base.changeCompress(newCompress); + if(r != this) // Also override the compress flag on the endpoints if it was updated. + { + EndpointI[] newEndpoints = new EndpointI[_endpoints.Length]; + for(int i = 0; i < _endpoints.Length; i++) + { + newEndpoints[i] = _endpoints[i].compress(newCompress); + } + r._endpoints = newEndpoints; + } + return r; + } + + public override Reference changeTimeout(int newTimeout) + { + DirectReference r = (DirectReference)base.changeTimeout(newTimeout); + if(r != this) // Also override the timeout on the endpoints if it was updated. + { + EndpointI[] newEndpoints = new EndpointI[_endpoints.Length]; + for(int i = 0; i < _endpoints.Length; i++) + { + newEndpoints[i] = _endpoints[i].timeout(newTimeout); + } + r._endpoints = newEndpoints; + } + return r; + } + + public override Reference changeConnectionId(string connectionId) + { + DirectReference r = (DirectReference)base.changeConnectionId(connectionId); + if(r != this) // Also override the connection id on the endpoints if it was updated. + { + EndpointI[] newEndpoints = new EndpointI[_endpoints.Length]; + for(int i = 0; i < _endpoints.Length; i++) + { + newEndpoints[i] = _endpoints[i].connectionId(connectionId); + } + r._endpoints = newEndpoints; + } + return r; + } + + public override Reference changeAdapterId(string newAdapterId) + { + if(newAdapterId == null || newAdapterId.Length == 0) + { + return this; + } + LocatorInfo locatorInfo = + getInstance().locatorManager().get(getInstance().referenceFactory().getDefaultLocator()); + return getInstance().referenceFactory().create( + getIdentity(), getContext(), getFacet(), getMode(), getSecure(), getPreferSecure(), newAdapterId, + getRouterInfo(), locatorInfo, getCollocationOptimization(), getCacheConnection(), getEndpointSelection(), getThreadPerConnection(), getLocatorCacheTimeout()); - } - - public override Reference changeEndpoints(EndpointI[] newEndpoints) - { - if(Array.Equals(newEndpoints, _endpoints)) - { - return this; - } - DirectReference r = (DirectReference)getInstance().referenceFactory().copy(this); - r._endpoints = newEndpoints; - r.applyOverrides(ref r._endpoints); - return r; - } - - public override Reference changeLocatorCacheTimeout(int newTimeout) - { - return this; - } - - public override void streamWrite(BasicStream s) - { - base.streamWrite(s); - - s.writeSize(_endpoints.Length); - if(_endpoints.Length > 0) - { - for(int i = 0; i < _endpoints.Length; i++) - { - _endpoints[i].streamWrite(s); - } - } - else - { - s.writeString(""); // Adapter id. - } - } - - public override string ToString() - { - // - // WARNING: Certain features, such as proxy validation in Glacier2, - // depend on the format of proxy strings. Changes to toString() and - // methods called to generate parts of the reference string could break - // these features. Please review for all features that depend on the - // format of proxyToString() before changing this and related code. - // - StringBuilder s = new StringBuilder(); - s.Append(base.ToString()); - - for(int i = 0; i < _endpoints.Length; i++) - { - string endp = _endpoints[i].ToString(); - if(endp != null && endp.Length > 0) - { - s.Append(':'); - s.Append(endp); - } - } - return s.ToString(); - } - - public override Ice.ConnectionI getConnection(out bool comp) - { - EndpointI[] endpts = base.getRoutedEndpoints(); - applyOverrides(ref endpts); - - if(endpts.Length == 0) - { - endpts = _endpoints; // Endpoint overrides are already applied on these endpoints. - } - - Ice.ConnectionI connection = createConnection(endpts, out comp); - - // - // If we have a router, set the object adapter for this router - // (if any) to the new connection, so that callbacks from the - // router can be received over this new connection. - // - if(getRouterInfo() != null) - { - connection.setAdapter(getRouterInfo().getAdapter()); - } - - Debug.Assert(connection != null); - return connection; - } - - public override bool Equals(object obj) - { - if(Object.ReferenceEquals(this, obj)) - { - return true; - } - if(!(obj is DirectReference)) - { - return false; - } - DirectReference rhs = (DirectReference)obj; - if(!base.Equals(rhs)) - { - return false; - } - return IceUtil.Arrays.Equals(_endpoints, rhs._endpoints); - } + } + + public override Reference changeEndpoints(EndpointI[] newEndpoints) + { + if(Array.Equals(newEndpoints, _endpoints)) + { + return this; + } + DirectReference r = (DirectReference)getInstance().referenceFactory().copy(this); + r._endpoints = newEndpoints; + r.applyOverrides(ref r._endpoints); + return r; + } + + public override Reference changeLocatorCacheTimeout(int newTimeout) + { + return this; + } + + public override void streamWrite(BasicStream s) + { + base.streamWrite(s); + + s.writeSize(_endpoints.Length); + if(_endpoints.Length > 0) + { + for(int i = 0; i < _endpoints.Length; i++) + { + _endpoints[i].streamWrite(s); + } + } + else + { + s.writeString(""); // Adapter id. + } + } + + public override string ToString() + { + // + // WARNING: Certain features, such as proxy validation in Glacier2, + // depend on the format of proxy strings. Changes to toString() and + // methods called to generate parts of the reference string could break + // these features. Please review for all features that depend on the + // format of proxyToString() before changing this and related code. + // + StringBuilder s = new StringBuilder(); + s.Append(base.ToString()); + + for(int i = 0; i < _endpoints.Length; i++) + { + string endp = _endpoints[i].ToString(); + if(endp != null && endp.Length > 0) + { + s.Append(':'); + s.Append(endp); + } + } + return s.ToString(); + } + + public override Ice.ConnectionI getConnection(out bool comp) + { + EndpointI[] endpts = base.getRoutedEndpoints(); + applyOverrides(ref endpts); + + if(endpts.Length == 0) + { + endpts = _endpoints; // Endpoint overrides are already applied on these endpoints. + } + + Ice.ConnectionI connection = createConnection(endpts, out comp); + + // + // If we have a router, set the object adapter for this router + // (if any) to the new connection, so that callbacks from the + // router can be received over this new connection. + // + if(getRouterInfo() != null) + { + connection.setAdapter(getRouterInfo().getAdapter()); + } + + Debug.Assert(connection != null); + return connection; + } + + public override bool Equals(object obj) + { + if(Object.ReferenceEquals(this, obj)) + { + return true; + } + if(!(obj is DirectReference)) + { + return false; + } + DirectReference rhs = (DirectReference)obj; + if(!base.Equals(rhs)) + { + return false; + } + return IceUtil.Arrays.Equals(_endpoints, rhs._endpoints); + } // // If we override Equals, we must also override GetHashCode. // - public override int GetHashCode() - { + public override int GetHashCode() + { return base.GetHashCode(); } - private EndpointI[] _endpoints; + private EndpointI[] _endpoints; } public class IndirectReference : RoutableReference { - public IndirectReference(Instance inst, - Ice.Communicator com, - Ice.Identity ident, - Ice.Context ctx, - string fs, - Reference.Mode md, - bool sec, - bool prefSec, - string adptid, - RouterInfo rtrInfo, - LocatorInfo locInfo, - bool collocationOpt, + public IndirectReference(Instance inst, + Ice.Communicator com, + Ice.Identity ident, + Ice.Context ctx, + string fs, + Reference.Mode md, + bool sec, + bool prefSec, + string adptid, + RouterInfo rtrInfo, + LocatorInfo locInfo, + bool collocationOpt, bool cacheConnection, Ice.EndpointSelectionType endpointSelection, bool threadPerConnection, - int locatorCacheTimeout) - : base(inst, com, ident, ctx, fs, md, sec, prefSec, rtrInfo, collocationOpt, cacheConnection, + int locatorCacheTimeout) + : base(inst, com, ident, ctx, fs, md, sec, prefSec, rtrInfo, collocationOpt, cacheConnection, endpointSelection, threadPerConnection) - { - adapterId_ = adptid; - locatorInfo_ = locInfo; - locatorCacheTimeout_ = locatorCacheTimeout; - } - - public override LocatorInfo getLocatorInfo() - { - return locatorInfo_; - } - - public override string getAdapterId() - { - return adapterId_; - } - - public override EndpointI[] getEndpoints() - { - return new EndpointI[0]; - } - - public override int getLocatorCacheTimeout() - { - return locatorCacheTimeout_; - } - - public override Reference changeLocator(Ice.LocatorPrx newLocator) - { - LocatorInfo newLocatorInfo = getInstance().locatorManager().get(newLocator); - if(locatorInfo_ != null && newLocatorInfo != null && newLocatorInfo.Equals(locatorInfo_)) - { - return this; - } - IndirectReference r = (IndirectReference)getInstance().referenceFactory().copy(this); - r.locatorInfo_ = newLocatorInfo; - return r; - } - - public override Reference changeAdapterId(string newAdapterId) - { - if(adapterId_.Equals(newAdapterId)) - { - return this; - } - IndirectReference r = (IndirectReference)getInstance().referenceFactory().copy(this); - r.adapterId_ = newAdapterId; - return r; - } - - public override Reference changeEndpoints(EndpointI[] newEndpoints) - { - if(newEndpoints == null || newEndpoints.Length == 0) - { - return this; - } - return getInstance().referenceFactory().create( - getIdentity(), getContext(), getFacet(), getMode(), getSecure(), getPreferSecure(), newEndpoints, - getRouterInfo(), getCollocationOptimization(), getCacheConnection(), getEndpointSelection(), + { + adapterId_ = adptid; + locatorInfo_ = locInfo; + locatorCacheTimeout_ = locatorCacheTimeout; + } + + public override LocatorInfo getLocatorInfo() + { + return locatorInfo_; + } + + public override string getAdapterId() + { + return adapterId_; + } + + public override EndpointI[] getEndpoints() + { + return new EndpointI[0]; + } + + public override int getLocatorCacheTimeout() + { + return locatorCacheTimeout_; + } + + public override Reference changeLocator(Ice.LocatorPrx newLocator) + { + LocatorInfo newLocatorInfo = getInstance().locatorManager().get(newLocator); + if(locatorInfo_ != null && newLocatorInfo != null && newLocatorInfo.Equals(locatorInfo_)) + { + return this; + } + IndirectReference r = (IndirectReference)getInstance().referenceFactory().copy(this); + r.locatorInfo_ = newLocatorInfo; + return r; + } + + public override Reference changeAdapterId(string newAdapterId) + { + if(adapterId_.Equals(newAdapterId)) + { + return this; + } + IndirectReference r = (IndirectReference)getInstance().referenceFactory().copy(this); + r.adapterId_ = newAdapterId; + return r; + } + + public override Reference changeEndpoints(EndpointI[] newEndpoints) + { + if(newEndpoints == null || newEndpoints.Length == 0) + { + return this; + } + return getInstance().referenceFactory().create( + getIdentity(), getContext(), getFacet(), getMode(), getSecure(), getPreferSecure(), newEndpoints, + getRouterInfo(), getCollocationOptimization(), getCacheConnection(), getEndpointSelection(), getThreadPerConnection()); - } - - public override Reference changeLocatorCacheTimeout(int newTimeout) - { - if(newTimeout == locatorCacheTimeout_) - { - return this; - } - IndirectReference r = (IndirectReference)getInstance().referenceFactory().copy(this); - r.locatorCacheTimeout_ = newTimeout; - return r; - } - - public override void streamWrite(BasicStream s) - { - base.streamWrite(s); - - s.writeSize(0); - s.writeString(adapterId_); - } - - public override string ToString() - { - // - // WARNING: Certain features, such as proxy validation in Glacier2, - // depend on the format of proxy strings. Changes to toString() and - // methods called to generate parts of the reference string could break - // these features. Please review for all features that depend on the - // format of proxyToString() before changing this and related code. - // - string result = base.ToString(); - - if(adapterId_.Length == 0) - { - return result; - } - - StringBuilder s = new StringBuilder(); - s.Append(result); - s.Append(" @ "); - - // - // If the encoded adapter id string contains characters which - // the reference parser uses as separators, then we enclose - // the adapter id string in quotes. - // - string a = IceUtil.StringUtil.escapeString(adapterId_, null); - if(IceUtil.StringUtil.findFirstOf(a, " \t\n\r") != -1) - { - s.Append('"'); - s.Append(a); - s.Append('"'); - } - else - { - s.Append(a); - } - return s.ToString(); - } - - public override Ice.ConnectionI getConnection(out bool comp) - { - Ice.ConnectionI connection; - - while(true) - { - EndpointI[] endpts = base.getRoutedEndpoints(); - bool cached = false; - if(endpts.Length == 0 && locatorInfo_ != null) - { - endpts = locatorInfo_.getEndpoints(this, locatorCacheTimeout_, out cached); - } - - applyOverrides(ref endpts); - - try - { - connection = createConnection(endpts, out comp); - Debug.Assert(connection != null); - } - catch(Ice.NoEndpointException ex) - { - throw ex; // No need to retry if there's no endpoints. - } - catch(Ice.LocalException ex) - { - if(getRouterInfo() == null) - { - Debug.Assert(locatorInfo_ != null); - locatorInfo_.clearCache(this); - - if(cached) - { - TraceLevels traceLevels = getInstance().traceLevels(); - - if(traceLevels.retry >= 2) - { - String s = "connection to cached endpoints failed\n" + - "removing endpoints from cache and trying one more time\n" + ex; - getInstance().initializationData().logger.trace(traceLevels.retryCat, s); - } - - continue; - } - } - - throw; - } - - break; - } - - // - // If we have a router, set the object adapter for this router - // (if any) to the new connection, so that callbacks from the - // router can be received over this new connection. - // - if(getRouterInfo() != null) - { - connection.setAdapter(getRouterInfo().getAdapter()); - } - - Debug.Assert(connection != null); - return connection; - } - - public override bool Equals(object obj) - { - if(object.ReferenceEquals(this, obj)) - { - return true; - } - if(!(obj is IndirectReference)) - { - return false; - } - IndirectReference rhs = (IndirectReference)obj; - if(!base.Equals(rhs)) - { - return false; - } - if(!adapterId_.Equals(rhs.adapterId_)) - { - return false; - } - if(locatorInfo_ == null ? rhs.locatorInfo_ != null : !locatorInfo_.Equals(rhs.locatorInfo_)) - { - return false; - } - return locatorCacheTimeout_ == rhs.locatorCacheTimeout_; - } + } + + public override Reference changeLocatorCacheTimeout(int newTimeout) + { + if(newTimeout == locatorCacheTimeout_) + { + return this; + } + IndirectReference r = (IndirectReference)getInstance().referenceFactory().copy(this); + r.locatorCacheTimeout_ = newTimeout; + return r; + } + + public override void streamWrite(BasicStream s) + { + base.streamWrite(s); + + s.writeSize(0); + s.writeString(adapterId_); + } + + public override string ToString() + { + // + // WARNING: Certain features, such as proxy validation in Glacier2, + // depend on the format of proxy strings. Changes to toString() and + // methods called to generate parts of the reference string could break + // these features. Please review for all features that depend on the + // format of proxyToString() before changing this and related code. + // + string result = base.ToString(); + + if(adapterId_.Length == 0) + { + return result; + } + + StringBuilder s = new StringBuilder(); + s.Append(result); + s.Append(" @ "); + + // + // If the encoded adapter id string contains characters which + // the reference parser uses as separators, then we enclose + // the adapter id string in quotes. + // + string a = IceUtil.StringUtil.escapeString(adapterId_, null); + if(IceUtil.StringUtil.findFirstOf(a, " \t\n\r") != -1) + { + s.Append('"'); + s.Append(a); + s.Append('"'); + } + else + { + s.Append(a); + } + return s.ToString(); + } + + public override Ice.ConnectionI getConnection(out bool comp) + { + Ice.ConnectionI connection; + + while(true) + { + EndpointI[] endpts = base.getRoutedEndpoints(); + bool cached = false; + if(endpts.Length == 0 && locatorInfo_ != null) + { + endpts = locatorInfo_.getEndpoints(this, locatorCacheTimeout_, out cached); + } + + applyOverrides(ref endpts); + + try + { + connection = createConnection(endpts, out comp); + Debug.Assert(connection != null); + } + catch(Ice.NoEndpointException ex) + { + throw ex; // No need to retry if there's no endpoints. + } + catch(Ice.LocalException ex) + { + if(getRouterInfo() == null) + { + Debug.Assert(locatorInfo_ != null); + locatorInfo_.clearCache(this); + + if(cached) + { + TraceLevels traceLevels = getInstance().traceLevels(); + + if(traceLevels.retry >= 2) + { + String s = "connection to cached endpoints failed\n" + + "removing endpoints from cache and trying one more time\n" + ex; + getInstance().initializationData().logger.trace(traceLevels.retryCat, s); + } + + continue; + } + } + + throw; + } + + break; + } + + // + // If we have a router, set the object adapter for this router + // (if any) to the new connection, so that callbacks from the + // router can be received over this new connection. + // + if(getRouterInfo() != null) + { + connection.setAdapter(getRouterInfo().getAdapter()); + } + + Debug.Assert(connection != null); + return connection; + } + + public override bool Equals(object obj) + { + if(object.ReferenceEquals(this, obj)) + { + return true; + } + if(!(obj is IndirectReference)) + { + return false; + } + IndirectReference rhs = (IndirectReference)obj; + if(!base.Equals(rhs)) + { + return false; + } + if(!adapterId_.Equals(rhs.adapterId_)) + { + return false; + } + if(locatorInfo_ == null ? rhs.locatorInfo_ != null : !locatorInfo_.Equals(rhs.locatorInfo_)) + { + return false; + } + return locatorCacheTimeout_ == rhs.locatorCacheTimeout_; + } // // If we override Equals, we must also override GetHashCode. // - public override int GetHashCode() - { - lock(this) - { - if(base.hashInitialized_) - { - return hashValue_; - } - base.GetHashCode(); // Initializes hashValue_. - int sz = adapterId_.Length; // Add hash of adapter ID to base hash. - for(int i = 0; i < sz; i++) - { - hashValue_ = 5 * hashValue_ + (int)adapterId_[i]; - } - return hashValue_; - } - } - - private string adapterId_; - private LocatorInfo locatorInfo_; - private int locatorCacheTimeout_; + public override int GetHashCode() + { + lock(this) + { + if(base.hashInitialized_) + { + return hashValue_; + } + base.GetHashCode(); // Initializes hashValue_. + int sz = adapterId_.Length; // Add hash of adapter ID to base hash. + for(int i = 0; i < sz; i++) + { + hashValue_ = 5 * hashValue_ + (int)adapterId_[i]; + } + return hashValue_; + } + } + + private string adapterId_; + private LocatorInfo locatorInfo_; + private int locatorCacheTimeout_; } } diff --git a/cs/src/Ice/ReferenceFactory.cs b/cs/src/Ice/ReferenceFactory.cs index f85bb4d568e..1b6c7b35b50 100755 --- a/cs/src/Ice/ReferenceFactory.cs +++ b/cs/src/Ice/ReferenceFactory.cs @@ -15,518 +15,518 @@ namespace IceInternal public class ReferenceFactory { - public Reference - create(Ice.Identity ident, - Ice.Context context, - string facet, - Reference.Mode mode, - bool secure, - bool preferSecure, - EndpointI[] endpoints, - RouterInfo routerInfo, - bool collocationOptimization, + public Reference + create(Ice.Identity ident, + Ice.Context context, + string facet, + Reference.Mode mode, + bool secure, + bool preferSecure, + EndpointI[] endpoints, + RouterInfo routerInfo, + bool collocationOptimization, bool cacheConnection, Ice.EndpointSelectionType endpointSelection, bool threadPerConnection) - { - lock(this) - { - if(instance_ == null) - { - throw new Ice.CommunicatorDestroyedException(); - } - - if(ident.name.Length == 0 && ident.category.Length == 0) - { - return null; - } - - // - // Create new reference - // - DirectReference @ref = new DirectReference(instance_, _communicator, ident, context, facet, mode, - secure, preferSecure, endpoints, routerInfo, - collocationOptimization, cacheConnection, endpointSelection, + { + lock(this) + { + if(instance_ == null) + { + throw new Ice.CommunicatorDestroyedException(); + } + + if(ident.name.Length == 0 && ident.category.Length == 0) + { + return null; + } + + // + // Create new reference + // + DirectReference @ref = new DirectReference(instance_, _communicator, ident, context, facet, mode, + secure, preferSecure, endpoints, routerInfo, + collocationOptimization, cacheConnection, endpointSelection, threadPerConnection); - return updateCache(@ref); - } - } - - public Reference create(Ice.Identity ident, - Ice.Context context, - string facet, - Reference.Mode mode, - bool secure, - bool preferSecure, - string adapterId, - RouterInfo routerInfo, - LocatorInfo locatorInfo, - bool collocationOptimization, + return updateCache(@ref); + } + } + + public Reference create(Ice.Identity ident, + Ice.Context context, + string facet, + Reference.Mode mode, + bool secure, + bool preferSecure, + string adapterId, + RouterInfo routerInfo, + LocatorInfo locatorInfo, + bool collocationOptimization, bool cacheConnection, Ice.EndpointSelectionType endpointSelection, bool threadPerConnection, - int locatorCacheTimeout) - { - lock(this) - { - if(instance_ == null) - { - throw new Ice.CommunicatorDestroyedException(); - } - - if(ident.name.Length == 0 && ident.category.Length == 0) - { - return null; - } - - // - // Create new reference - // - IndirectReference @ref = new IndirectReference(instance_, _communicator, ident, context, facet, mode, - secure, preferSecure, adapterId, routerInfo, locatorInfo, - collocationOptimization, cacheConnection, + int locatorCacheTimeout) + { + lock(this) + { + if(instance_ == null) + { + throw new Ice.CommunicatorDestroyedException(); + } + + if(ident.name.Length == 0 && ident.category.Length == 0) + { + return null; + } + + // + // Create new reference + // + IndirectReference @ref = new IndirectReference(instance_, _communicator, ident, context, facet, mode, + secure, preferSecure, adapterId, routerInfo, locatorInfo, + collocationOptimization, cacheConnection, endpointSelection, threadPerConnection, locatorCacheTimeout); - return updateCache(@ref); - } - } - - public Reference create(Ice.Identity ident, - Ice.Context context, - string facet, - Reference.Mode mode, - Ice.ConnectionI[] fixedConnections) - { - lock(this) - { - if(instance_ == null) - { - throw new Ice.CommunicatorDestroyedException(); - } - - if(ident.name.Length == 0 && ident.category.Length == 0) - { - return null; - } - - // - // Create new reference - // - FixedReference @ref = - new FixedReference(instance_, _communicator, ident, context, facet, mode, fixedConnections); - return updateCache(@ref); - } - } - - public Reference copy(Reference r) - { - lock(this) - { - if(instance_ == null) - { - throw new Ice.CommunicatorDestroyedException(); - } - - Ice.Identity ident = r.getIdentity(); - if(ident.name.Length == 0 && ident.category.Length == 0) - { - return null; - } - return (Reference)r.Clone(); - } - } - - public Reference create(string s) - { - if(s.Length == 0) - { - return null; - } - - const string delim = " \t\n\r"; - - int beg; - int end = 0; - - beg = IceUtil.StringUtil.findFirstNotOf(s, delim, end); - if(beg == -1) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - - // - // Extract the identity, which may be enclosed in single - // or double quotation marks. - // - string idstr = null; - end = IceUtil.StringUtil.checkQuote(s, beg); - if(end == -1) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - else if(end == 0) - { - end = IceUtil.StringUtil.findFirstOf(s, delim + ":@", beg); - if(end == -1) - { - end = s.Length; - } - idstr = s.Substring(beg, end - beg); - } - else - { - beg++; // Skip leading quote - idstr = s.Substring(beg, end - beg); - end++; // Skip trailing quote - } - - if(beg == end) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - - // - // Parsing the identity may raise IdentityParseException. - // - Ice.Identity ident = instance_.stringToIdentity(idstr); - - if(ident.name.Length == 0) - { - // - // An identity with an empty name and a non-empty - // category is illegal. - // - if(ident.category.Length > 0) - { - Ice.IllegalIdentityException e = new Ice.IllegalIdentityException(); - e.id = ident; - throw e; - } - // - // Treat a stringified proxy containing two double - // quotes ("") the same as an empty string, i.e., - // a null proxy, but only if nothing follows the - // quotes. - // - else if(IceUtil.StringUtil.findFirstNotOf(s, delim, end) != -1) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - else - { - return null; - } - } - - string facet = ""; - Reference.Mode mode = Reference.Mode.ModeTwoway; - bool secure = false; - string adapter = ""; - - while(true) - { - beg = IceUtil.StringUtil.findFirstNotOf(s, delim, end); - if(beg == -1) - { - break; - } - - if(s[beg] == ':' || s[beg] == '@') - { - break; - } - - end = IceUtil.StringUtil.findFirstOf(s, delim + ":@", beg); - if(end == -1) - { - end = s.Length; - } - - if(beg == end) - { - break; - } - - string option = s.Substring(beg, end - beg); - if(option.Length != 2 || option[0] != '-') - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - - // - // Check for the presence of an option argument. The - // argument may be enclosed in single or double - // quotation marks. - // - string argument = null; - int argumentBeg = IceUtil.StringUtil.findFirstNotOf(s, delim, end); - if(argumentBeg != -1) - { - char ch = s[argumentBeg]; - if(ch != '@' && ch != ':' && ch != '-') - { - beg = argumentBeg; - end = IceUtil.StringUtil.checkQuote(s, beg); - if(end == -1) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - else if(end == 0) - { - end = IceUtil.StringUtil.findFirstOf(s, delim + ":@", beg); - if(end == -1) - { - end = s.Length; - } - argument = s.Substring(beg, end - beg); - } - else - { - beg++; // Skip leading quote - argument = s.Substring(beg, end - beg); - end++; // Skip trailing quote - } - } - } - - // - // If any new options are added here, - // IceInternal::Reference::toString() and its derived classes must be updated as well. - // - switch(option[1]) - { - case 'f': - { - if(argument == null) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - - string token; - if(!IceUtil.StringUtil.unescapeString(argument, 0, argument.Length, out token)) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } + return updateCache(@ref); + } + } + + public Reference create(Ice.Identity ident, + Ice.Context context, + string facet, + Reference.Mode mode, + Ice.ConnectionI[] fixedConnections) + { + lock(this) + { + if(instance_ == null) + { + throw new Ice.CommunicatorDestroyedException(); + } + + if(ident.name.Length == 0 && ident.category.Length == 0) + { + return null; + } + + // + // Create new reference + // + FixedReference @ref = + new FixedReference(instance_, _communicator, ident, context, facet, mode, fixedConnections); + return updateCache(@ref); + } + } + + public Reference copy(Reference r) + { + lock(this) + { + if(instance_ == null) + { + throw new Ice.CommunicatorDestroyedException(); + } + + Ice.Identity ident = r.getIdentity(); + if(ident.name.Length == 0 && ident.category.Length == 0) + { + return null; + } + return (Reference)r.Clone(); + } + } + + public Reference create(string s) + { + if(s.Length == 0) + { + return null; + } + + const string delim = " \t\n\r"; + + int beg; + int end = 0; + + beg = IceUtil.StringUtil.findFirstNotOf(s, delim, end); + if(beg == -1) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + + // + // Extract the identity, which may be enclosed in single + // or double quotation marks. + // + string idstr = null; + end = IceUtil.StringUtil.checkQuote(s, beg); + if(end == -1) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + else if(end == 0) + { + end = IceUtil.StringUtil.findFirstOf(s, delim + ":@", beg); + if(end == -1) + { + end = s.Length; + } + idstr = s.Substring(beg, end - beg); + } + else + { + beg++; // Skip leading quote + idstr = s.Substring(beg, end - beg); + end++; // Skip trailing quote + } + + if(beg == end) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + + // + // Parsing the identity may raise IdentityParseException. + // + Ice.Identity ident = instance_.stringToIdentity(idstr); + + if(ident.name.Length == 0) + { + // + // An identity with an empty name and a non-empty + // category is illegal. + // + if(ident.category.Length > 0) + { + Ice.IllegalIdentityException e = new Ice.IllegalIdentityException(); + e.id = ident; + throw e; + } + // + // Treat a stringified proxy containing two double + // quotes ("") the same as an empty string, i.e., + // a null proxy, but only if nothing follows the + // quotes. + // + else if(IceUtil.StringUtil.findFirstNotOf(s, delim, end) != -1) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + else + { + return null; + } + } + + string facet = ""; + Reference.Mode mode = Reference.Mode.ModeTwoway; + bool secure = false; + string adapter = ""; + + while(true) + { + beg = IceUtil.StringUtil.findFirstNotOf(s, delim, end); + if(beg == -1) + { + break; + } + + if(s[beg] == ':' || s[beg] == '@') + { + break; + } + + end = IceUtil.StringUtil.findFirstOf(s, delim + ":@", beg); + if(end == -1) + { + end = s.Length; + } + + if(beg == end) + { + break; + } + + string option = s.Substring(beg, end - beg); + if(option.Length != 2 || option[0] != '-') + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + + // + // Check for the presence of an option argument. The + // argument may be enclosed in single or double + // quotation marks. + // + string argument = null; + int argumentBeg = IceUtil.StringUtil.findFirstNotOf(s, delim, end); + if(argumentBeg != -1) + { + char ch = s[argumentBeg]; + if(ch != '@' && ch != ':' && ch != '-') + { + beg = argumentBeg; + end = IceUtil.StringUtil.checkQuote(s, beg); + if(end == -1) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + else if(end == 0) + { + end = IceUtil.StringUtil.findFirstOf(s, delim + ":@", beg); + if(end == -1) + { + end = s.Length; + } + argument = s.Substring(beg, end - beg); + } + else + { + beg++; // Skip leading quote + argument = s.Substring(beg, end - beg); + end++; // Skip trailing quote + } + } + } + + // + // If any new options are added here, + // IceInternal::Reference::toString() and its derived classes must be updated as well. + // + switch(option[1]) + { + case 'f': + { + if(argument == null) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + + string token; + if(!IceUtil.StringUtil.unescapeString(argument, 0, argument.Length, out token)) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } facet = token; - break; - } - - case 't': - { - if(argument != null) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - mode = Reference.Mode.ModeTwoway; - break; - } - - case 'o': - { - if(argument != null) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - mode = Reference.Mode.ModeOneway; - break; - } - - case 'O': - { - if(argument != null) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - mode = Reference.Mode.ModeBatchOneway; - break; - } - - case 'd': - { - if(argument != null) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - mode = Reference.Mode.ModeDatagram; - break; - } - - case 'D': - { - if(argument != null) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - mode = Reference.Mode.ModeBatchDatagram; - break; - } - - case 's': - { - if(argument != null) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - secure = true; - break; - } - - default: - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - } - } - - RouterInfo routerInfo = instance_.routerManager().get(getDefaultRouter()); - LocatorInfo locatorInfo = instance_.locatorManager().get(getDefaultLocator()); - - if(beg == -1) - { - return create(ident, instance_.getDefaultContext(), facet, mode, secure, - instance_.defaultsAndOverrides().defaultPreferSecure, "", - routerInfo, locatorInfo, instance_.defaultsAndOverrides().defaultCollocationOptimization, - true, instance_.defaultsAndOverrides().defaultEndpointSelection, + break; + } + + case 't': + { + if(argument != null) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + mode = Reference.Mode.ModeTwoway; + break; + } + + case 'o': + { + if(argument != null) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + mode = Reference.Mode.ModeOneway; + break; + } + + case 'O': + { + if(argument != null) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + mode = Reference.Mode.ModeBatchOneway; + break; + } + + case 'd': + { + if(argument != null) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + mode = Reference.Mode.ModeDatagram; + break; + } + + case 'D': + { + if(argument != null) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + mode = Reference.Mode.ModeBatchDatagram; + break; + } + + case 's': + { + if(argument != null) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + secure = true; + break; + } + + default: + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + } + } + + RouterInfo routerInfo = instance_.routerManager().get(getDefaultRouter()); + LocatorInfo locatorInfo = instance_.locatorManager().get(getDefaultLocator()); + + if(beg == -1) + { + return create(ident, instance_.getDefaultContext(), facet, mode, secure, + instance_.defaultsAndOverrides().defaultPreferSecure, "", + routerInfo, locatorInfo, instance_.defaultsAndOverrides().defaultCollocationOptimization, + true, instance_.defaultsAndOverrides().defaultEndpointSelection, instance_.threadPerConnection(), - instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); - } - - ArrayList endpoints = new ArrayList(); - - if(s[beg] == ':') - { - ArrayList unknownEndpoints = new ArrayList(); - end = beg; - - while(end < s.Length && s[end] == ':') - { - beg = end + 1; - - end = s.IndexOf(':', beg); - if(end == -1) - { - end = s.Length; - } - - string es = s.Substring(beg, end - beg); - EndpointI endp = instance_.endpointFactoryManager().create(es); - if(endp != null) - { - ArrayList endps = endp.expand(false); - endpoints.AddRange(endps); - } - else - { - unknownEndpoints.Add(es); - } - } - if(endpoints.Count == 0) - { - Ice.EndpointParseException e2 = new Ice.EndpointParseException(); - e2.str = s; - throw e2; - } - else if(unknownEndpoints.Count != 0 && - instance_.initializationData().properties.getPropertyAsIntWithDefault( - "Ice.Warn.Endpoints", 1) > 0) - { - string msg = "Proxy contains unknown endpoints:"; - int sz = unknownEndpoints.Count; - for(int idx = 0; idx < sz; ++idx) - { - msg += " `" + (string)unknownEndpoints[idx] + "'"; - } - instance_.initializationData().logger.warning(msg); - } - - EndpointI[] ep = (EndpointI[])endpoints.ToArray(typeof(EndpointI)); - return create(ident, instance_.getDefaultContext(), facet, mode, secure, - instance_.defaultsAndOverrides().defaultPreferSecure, ep, routerInfo, - instance_.defaultsAndOverrides().defaultCollocationOptimization, true, + instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); + } + + ArrayList endpoints = new ArrayList(); + + if(s[beg] == ':') + { + ArrayList unknownEndpoints = new ArrayList(); + end = beg; + + while(end < s.Length && s[end] == ':') + { + beg = end + 1; + + end = s.IndexOf(':', beg); + if(end == -1) + { + end = s.Length; + } + + string es = s.Substring(beg, end - beg); + EndpointI endp = instance_.endpointFactoryManager().create(es); + if(endp != null) + { + ArrayList endps = endp.expand(false); + endpoints.AddRange(endps); + } + else + { + unknownEndpoints.Add(es); + } + } + if(endpoints.Count == 0) + { + Ice.EndpointParseException e2 = new Ice.EndpointParseException(); + e2.str = s; + throw e2; + } + else if(unknownEndpoints.Count != 0 && + instance_.initializationData().properties.getPropertyAsIntWithDefault( + "Ice.Warn.Endpoints", 1) > 0) + { + string msg = "Proxy contains unknown endpoints:"; + int sz = unknownEndpoints.Count; + for(int idx = 0; idx < sz; ++idx) + { + msg += " `" + (string)unknownEndpoints[idx] + "'"; + } + instance_.initializationData().logger.warning(msg); + } + + EndpointI[] ep = (EndpointI[])endpoints.ToArray(typeof(EndpointI)); + return create(ident, instance_.getDefaultContext(), facet, mode, secure, + instance_.defaultsAndOverrides().defaultPreferSecure, ep, routerInfo, + instance_.defaultsAndOverrides().defaultCollocationOptimization, true, instance_.defaultsAndOverrides().defaultEndpointSelection, instance_.threadPerConnection()); - } - else if(s[beg] == '@') - { - beg = IceUtil.StringUtil.findFirstNotOf(s, delim, beg + 1); - if(beg == -1) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - - end = IceUtil.StringUtil.checkQuote(s, beg); - if(end == -1) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - else if(end == 0) - { - end = IceUtil.StringUtil.findFirstOf(s, delim, beg); - if(end == -1) - { - end = s.Length; - } - } - else - { - beg++; // Skip leading quote - } - - if(!IceUtil.StringUtil.unescapeString(s, beg, end, out adapter) || adapter.Length == 0) - { - Ice.ProxyParseException e = new Ice.ProxyParseException(); - e.str = s; - throw e; - } - return create(ident, instance_.getDefaultContext(), facet, mode, secure, - instance_.defaultsAndOverrides().defaultPreferSecure, adapter, - routerInfo, locatorInfo, instance_.defaultsAndOverrides().defaultCollocationOptimization, + } + else if(s[beg] == '@') + { + beg = IceUtil.StringUtil.findFirstNotOf(s, delim, beg + 1); + if(beg == -1) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + + end = IceUtil.StringUtil.checkQuote(s, beg); + if(end == -1) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + else if(end == 0) + { + end = IceUtil.StringUtil.findFirstOf(s, delim, beg); + if(end == -1) + { + end = s.Length; + } + } + else + { + beg++; // Skip leading quote + } + + if(!IceUtil.StringUtil.unescapeString(s, beg, end, out adapter) || adapter.Length == 0) + { + Ice.ProxyParseException e = new Ice.ProxyParseException(); + e.str = s; + throw e; + } + return create(ident, instance_.getDefaultContext(), facet, mode, secure, + instance_.defaultsAndOverrides().defaultPreferSecure, adapter, + routerInfo, locatorInfo, instance_.defaultsAndOverrides().defaultCollocationOptimization, true, instance_.defaultsAndOverrides().defaultEndpointSelection, instance_.threadPerConnection(), - instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); - } + instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); + } - Ice.ProxyParseException ex = new Ice.ProxyParseException(); - ex.str = s; - throw ex; - } + Ice.ProxyParseException ex = new Ice.ProxyParseException(); + ex.str = s; + throw ex; + } - public Reference createFromProperties(string propertyPrefix) - { + public Reference createFromProperties(string propertyPrefix) + { Ice.Properties properties = instance_.initializationData().properties; Reference @ref = create(properties.getProperty(propertyPrefix)); @@ -598,164 +598,164 @@ namespace IceInternal } return @ref; - } - - public Reference create(Ice.Identity ident, BasicStream s) - { - // - // Don't read the identity here. Operations calling this - // constructor read the identity, and pass it as a parameter. - // - - if(ident.name.Length == 0 && ident.category.Length == 0) - { - return null; - } - - // - // For compatibility with the old FacetPath. - // - string[] facetPath = s.readStringSeq(); - string facet; - if(facetPath.Length > 0) - { - if(facetPath.Length > 1) - { - throw new Ice.ProxyUnmarshalException(); - } - facet = facetPath[0]; - } - else - { - facet = ""; - } - - int mode = (int)s.readByte(); - if(mode < 0 || mode > (int)Reference.Mode.ModeLast) - { - throw new Ice.ProxyUnmarshalException(); - } - - bool secure = s.readBool(); - - EndpointI[] endpoints; - string adapterId = ""; - - RouterInfo routerInfo = instance_.routerManager().get(getDefaultRouter()); - LocatorInfo locatorInfo = instance_.locatorManager().get(getDefaultLocator()); - - int sz = s.readSize(); - if(sz > 0) - { - endpoints = new EndpointI[sz]; - for(int i = 0; i < sz; i++) - { - endpoints[i] = instance_.endpointFactoryManager().read(s); - } - return create(ident, instance_.getDefaultContext(), facet, (Reference.Mode)mode, - secure, instance_.defaultsAndOverrides().defaultPreferSecure, endpoints, routerInfo, - instance_.defaultsAndOverrides().defaultCollocationOptimization, true, + } + + public Reference create(Ice.Identity ident, BasicStream s) + { + // + // Don't read the identity here. Operations calling this + // constructor read the identity, and pass it as a parameter. + // + + if(ident.name.Length == 0 && ident.category.Length == 0) + { + return null; + } + + // + // For compatibility with the old FacetPath. + // + string[] facetPath = s.readStringSeq(); + string facet; + if(facetPath.Length > 0) + { + if(facetPath.Length > 1) + { + throw new Ice.ProxyUnmarshalException(); + } + facet = facetPath[0]; + } + else + { + facet = ""; + } + + int mode = (int)s.readByte(); + if(mode < 0 || mode > (int)Reference.Mode.ModeLast) + { + throw new Ice.ProxyUnmarshalException(); + } + + bool secure = s.readBool(); + + EndpointI[] endpoints; + string adapterId = ""; + + RouterInfo routerInfo = instance_.routerManager().get(getDefaultRouter()); + LocatorInfo locatorInfo = instance_.locatorManager().get(getDefaultLocator()); + + int sz = s.readSize(); + if(sz > 0) + { + endpoints = new EndpointI[sz]; + for(int i = 0; i < sz; i++) + { + endpoints[i] = instance_.endpointFactoryManager().read(s); + } + return create(ident, instance_.getDefaultContext(), facet, (Reference.Mode)mode, + secure, instance_.defaultsAndOverrides().defaultPreferSecure, endpoints, routerInfo, + instance_.defaultsAndOverrides().defaultCollocationOptimization, true, instance_.defaultsAndOverrides().defaultEndpointSelection, instance_.threadPerConnection()); - } - else - { - endpoints = new EndpointI[0]; - adapterId = s.readString(); - return create(ident, instance_.getDefaultContext(), facet, (Reference.Mode)mode, - secure, instance_.defaultsAndOverrides().defaultPreferSecure, adapterId, - routerInfo, locatorInfo, - instance_.defaultsAndOverrides().defaultCollocationOptimization, true, + } + else + { + endpoints = new EndpointI[0]; + adapterId = s.readString(); + return create(ident, instance_.getDefaultContext(), facet, (Reference.Mode)mode, + secure, instance_.defaultsAndOverrides().defaultPreferSecure, adapterId, + routerInfo, locatorInfo, + instance_.defaultsAndOverrides().defaultCollocationOptimization, true, instance_.defaultsAndOverrides().defaultEndpointSelection, instance_.threadPerConnection(), - instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); - } - } - - public void setDefaultRouter(Ice.RouterPrx defaultRouter) - { - lock(this) - { - _defaultRouter = defaultRouter; - } - } - - public Ice.RouterPrx getDefaultRouter() - { - lock(this) - { - return _defaultRouter; - } - } - - public void setDefaultLocator(Ice.LocatorPrx defaultLocator) - { - lock(this) - { - _defaultLocator = defaultLocator; - } - } - - public Ice.LocatorPrx getDefaultLocator() - { - lock(this) - { - return _defaultLocator; - } - } - - // - // Only for use by Instance - // - internal ReferenceFactory(Instance instance, Ice.Communicator communicator) - { - instance_ = instance; - _communicator = communicator; - } - - internal void destroy() - { - lock(this) - { - if(instance_ == null) - { - throw new Ice.CommunicatorDestroyedException(); - } - - instance_ = null; - _defaultRouter = null; - _defaultLocator = null; - _references.Clear(); - } - } - - private Reference updateCache(Reference @ref) - { - // - // If we already have an equivalent reference, use such equivalent - // reference. Otherwise add the new reference to the reference - // set. - // - WeakReference w = new WeakReference(@ref); - WeakReference val = (WeakReference)_references[w]; - if(val != null) - { - Reference r = (Reference)val.Target; - if(r != null && r.Equals(@ref)) - { - return r; - } - } - _references[w] = w; - - return @ref; - } - - private Instance instance_; - private Ice.Communicator _communicator; - private Ice.RouterPrx _defaultRouter; - private Ice.LocatorPrx _defaultLocator; - private Hashtable _references = new Hashtable(); + instance_.defaultsAndOverrides().defaultLocatorCacheTimeout); + } + } + + public void setDefaultRouter(Ice.RouterPrx defaultRouter) + { + lock(this) + { + _defaultRouter = defaultRouter; + } + } + + public Ice.RouterPrx getDefaultRouter() + { + lock(this) + { + return _defaultRouter; + } + } + + public void setDefaultLocator(Ice.LocatorPrx defaultLocator) + { + lock(this) + { + _defaultLocator = defaultLocator; + } + } + + public Ice.LocatorPrx getDefaultLocator() + { + lock(this) + { + return _defaultLocator; + } + } + + // + // Only for use by Instance + // + internal ReferenceFactory(Instance instance, Ice.Communicator communicator) + { + instance_ = instance; + _communicator = communicator; + } + + internal void destroy() + { + lock(this) + { + if(instance_ == null) + { + throw new Ice.CommunicatorDestroyedException(); + } + + instance_ = null; + _defaultRouter = null; + _defaultLocator = null; + _references.Clear(); + } + } + + private Reference updateCache(Reference @ref) + { + // + // If we already have an equivalent reference, use such equivalent + // reference. Otherwise add the new reference to the reference + // set. + // + WeakReference w = new WeakReference(@ref); + WeakReference val = (WeakReference)_references[w]; + if(val != null) + { + Reference r = (Reference)val.Target; + if(r != null && r.Equals(@ref)) + { + return r; + } + } + _references[w] = w; + + return @ref; + } + + private Instance instance_; + private Ice.Communicator _communicator; + private Ice.RouterPrx _defaultRouter; + private Ice.LocatorPrx _defaultLocator; + private Hashtable _references = new Hashtable(); } } diff --git a/cs/src/Ice/RouterInfo.cs b/cs/src/Ice/RouterInfo.cs index 0addf260a22..1ee95536bdc 100755 --- a/cs/src/Ice/RouterInfo.cs +++ b/cs/src/Ice/RouterInfo.cs @@ -16,157 +16,157 @@ namespace IceInternal public sealed class RouterInfo { - internal RouterInfo(Ice.RouterPrx router) - { - _router = router; - - Debug.Assert(_router != null); - } - - public void destroy() - { - lock(this) - { - _clientEndpoints = new EndpointI[0]; - _serverEndpoints = new EndpointI[0]; - _adapter = null; - _identities.Clear(); - } - } - - public override bool Equals(System.Object obj) - { - if(object.ReferenceEquals(this, obj)) - { - return true; - } - - RouterInfo rhs = obj as RouterInfo; - return rhs == null ? false : _router.Equals(rhs._router); - } - - public override int GetHashCode() - { - return _router.GetHashCode(); - } - - public Ice.RouterPrx getRouter() - { - // - // No mutex lock necessary, _router is immutable. - // - return _router; - } - - public EndpointI[] getClientEndpoints() - { - lock(this) - { - if(_clientEndpoints == null) // Lazy initialization. - { - Ice.ObjectPrx clientProxy = _router.getClientProxy(); - if(clientProxy == null) - { - // - // Use router endpoints if getClientProxy returns nil. - // - _clientEndpoints = ((Ice.ObjectPrxHelperBase)_router).reference__().getEndpoints(); - } - else - { - clientProxy = clientProxy.ice_router(null); // The client proxy cannot be routed. - - // - // In order to avoid creating a new connection to - // the router, we must use the same timeout as the - // already existing connection. - // - try - { - clientProxy = clientProxy.ice_timeout(_router.ice_getConnection().timeout()); - } - catch(Ice.CollocationOptimizationException) - { - // Ignore - collocated router. - } - - _clientEndpoints = ((Ice.ObjectPrxHelperBase)clientProxy).reference__().getEndpoints(); - } - } - - return _clientEndpoints; - } - } - - public EndpointI[] getServerEndpoints() - { - if(_serverEndpoints == null) // Lazy initialization. - { - Ice.ObjectPrx serverProxy = _router.getServerProxy(); - if(serverProxy == null) - { - throw new Ice.NoEndpointException(); - } - - serverProxy = serverProxy.ice_router(null); // The server proxy cannot be routed. - _serverEndpoints = ((Ice.ObjectPrxHelperBase)serverProxy).reference__().getEndpoints(); - } - - return _serverEndpoints; - } - - public void addProxy(Ice.ObjectPrx proxy) - { - Debug.Assert(proxy != null); - - lock(this) - { - if(!_identities.Contains(proxy.ice_getIdentity())) - { - // - // Only add the proxy to the router if it's not already in our local map. - // - Ice.ObjectPrx[] proxies = new Ice.ObjectPrx[1]; - proxies[0] = proxy; - Ice.ObjectPrx[] evictedProxies = _router.addProxies(proxies); - - // - // If we successfully added the proxy to the router, we add it to our local map. - // - _identities.Add(proxy.ice_getIdentity()); - - // - // We also must remove whatever proxies the router evicted. - // - for(int i = 0; i < evictedProxies.Length; ++i) - { - _identities.Remove(evictedProxies[i].ice_getIdentity()); - } - } - } - } - - public void setAdapter(Ice.ObjectAdapter adapter) - { - lock(this) - { - _adapter = adapter; - } - } - - public Ice.ObjectAdapter getAdapter() - { - lock(this) - { - return _adapter; - } - } - - private readonly Ice.RouterPrx _router; - private EndpointI[] _clientEndpoints; - private EndpointI[] _serverEndpoints; - private IceUtil.Set _identities = new IceUtil.Set(); - private Ice.ObjectAdapter _adapter; + internal RouterInfo(Ice.RouterPrx router) + { + _router = router; + + Debug.Assert(_router != null); + } + + public void destroy() + { + lock(this) + { + _clientEndpoints = new EndpointI[0]; + _serverEndpoints = new EndpointI[0]; + _adapter = null; + _identities.Clear(); + } + } + + public override bool Equals(System.Object obj) + { + if(object.ReferenceEquals(this, obj)) + { + return true; + } + + RouterInfo rhs = obj as RouterInfo; + return rhs == null ? false : _router.Equals(rhs._router); + } + + public override int GetHashCode() + { + return _router.GetHashCode(); + } + + public Ice.RouterPrx getRouter() + { + // + // No mutex lock necessary, _router is immutable. + // + return _router; + } + + public EndpointI[] getClientEndpoints() + { + lock(this) + { + if(_clientEndpoints == null) // Lazy initialization. + { + Ice.ObjectPrx clientProxy = _router.getClientProxy(); + if(clientProxy == null) + { + // + // Use router endpoints if getClientProxy returns nil. + // + _clientEndpoints = ((Ice.ObjectPrxHelperBase)_router).reference__().getEndpoints(); + } + else + { + clientProxy = clientProxy.ice_router(null); // The client proxy cannot be routed. + + // + // In order to avoid creating a new connection to + // the router, we must use the same timeout as the + // already existing connection. + // + try + { + clientProxy = clientProxy.ice_timeout(_router.ice_getConnection().timeout()); + } + catch(Ice.CollocationOptimizationException) + { + // Ignore - collocated router. + } + + _clientEndpoints = ((Ice.ObjectPrxHelperBase)clientProxy).reference__().getEndpoints(); + } + } + + return _clientEndpoints; + } + } + + public EndpointI[] getServerEndpoints() + { + if(_serverEndpoints == null) // Lazy initialization. + { + Ice.ObjectPrx serverProxy = _router.getServerProxy(); + if(serverProxy == null) + { + throw new Ice.NoEndpointException(); + } + + serverProxy = serverProxy.ice_router(null); // The server proxy cannot be routed. + _serverEndpoints = ((Ice.ObjectPrxHelperBase)serverProxy).reference__().getEndpoints(); + } + + return _serverEndpoints; + } + + public void addProxy(Ice.ObjectPrx proxy) + { + Debug.Assert(proxy != null); + + lock(this) + { + if(!_identities.Contains(proxy.ice_getIdentity())) + { + // + // Only add the proxy to the router if it's not already in our local map. + // + Ice.ObjectPrx[] proxies = new Ice.ObjectPrx[1]; + proxies[0] = proxy; + Ice.ObjectPrx[] evictedProxies = _router.addProxies(proxies); + + // + // If we successfully added the proxy to the router, we add it to our local map. + // + _identities.Add(proxy.ice_getIdentity()); + + // + // We also must remove whatever proxies the router evicted. + // + for(int i = 0; i < evictedProxies.Length; ++i) + { + _identities.Remove(evictedProxies[i].ice_getIdentity()); + } + } + } + } + + public void setAdapter(Ice.ObjectAdapter adapter) + { + lock(this) + { + _adapter = adapter; + } + } + + public Ice.ObjectAdapter getAdapter() + { + lock(this) + { + return _adapter; + } + } + + private readonly Ice.RouterPrx _router; + private EndpointI[] _clientEndpoints; + private EndpointI[] _serverEndpoints; + private IceUtil.Set _identities = new IceUtil.Set(); + private Ice.ObjectAdapter _adapter; } public sealed class RouterManager @@ -175,7 +175,7 @@ namespace IceInternal { _table = new Hashtable(); } - + internal void destroy() { lock(this) @@ -187,7 +187,7 @@ namespace IceInternal _table.Clear(); } } - + // // Returns router info for a given router. Automatically creates // the router info if it doesn't exist yet. @@ -198,9 +198,9 @@ namespace IceInternal { return null; } - + Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(rtr.ice_router(null)); // The router cannot be routed. - + lock(this) { RouterInfo info = (RouterInfo)_table[router]; @@ -209,7 +209,7 @@ namespace IceInternal info = new RouterInfo(router); _table[router] = info; } - + return info; } } @@ -220,22 +220,22 @@ namespace IceInternal // public RouterInfo erase(Ice.RouterPrx rtr) { - RouterInfo info = null; + RouterInfo info = null; if(rtr == null) { - Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(rtr.ice_router(null)); // The router cannot be routed. - lock(this) - { - info = (RouterInfo)_table[router]; - if(info != null) - { - _table.Remove(router); - } - } - } - return info; + Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(rtr.ice_router(null)); // The router cannot be routed. + lock(this) + { + info = (RouterInfo)_table[router]; + if(info != null) + { + _table.Remove(router); + } + } + } + return info; } - + private Hashtable _table; } diff --git a/cs/src/Ice/ServantManager.cs b/cs/src/Ice/ServantManager.cs index 266f153894c..510883593f4 100755 --- a/cs/src/Ice/ServantManager.cs +++ b/cs/src/Ice/ServantManager.cs @@ -17,22 +17,22 @@ public sealed class ServantManager { public void addServant(Ice.Object servant, Ice.Identity ident, string facet) { - lock(this) - { - Debug.Assert(instance_ != null); // Must not be called after destruction. - - if(facet == null) - { - facet = ""; - } + lock(this) + { + Debug.Assert(instance_ != null); // Must not be called after destruction. + + if(facet == null) + { + facet = ""; + } - Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; - if(m == null) - { - _servantMapMap[ident] = (m = new Ice.FacetMap()); - } - else - { + Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; + if(m == null) + { + _servantMapMap[ident] = (m = new Ice.FacetMap()); + } + else + { if(m.Contains(facet)) { Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); @@ -44,171 +44,171 @@ public sealed class ServantManager } throw ex; } - } - - m[facet] = servant; - } + } + + m[facet] = servant; + } } public Ice.Object removeServant(Ice.Identity ident, string facet) { - lock(this) - { - Debug.Assert(instance_ != null); // Must not be called after destruction. - - if(facet == null) - { - facet = ""; - } + lock(this) + { + Debug.Assert(instance_ != null); // Must not be called after destruction. + + if(facet == null) + { + facet = ""; + } - Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; - Ice.Object obj = null; - if(m == null || !m.Contains(facet)) - { - Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); - ex.id = Ice.Util.identityToString(ident); - ex.kindOfObject = "servant"; - if(facet.Length > 0) - { - ex.id += " -f " + IceUtil.StringUtil.escapeString(facet, ""); - } - throw ex; - } - obj = m[facet]; - m.Remove(facet); - - if(m.Count == 0) - { - _servantMapMap.Remove(ident); - } - return obj; - } + Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; + Ice.Object obj = null; + if(m == null || !m.Contains(facet)) + { + Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); + ex.id = Ice.Util.identityToString(ident); + ex.kindOfObject = "servant"; + if(facet.Length > 0) + { + ex.id += " -f " + IceUtil.StringUtil.escapeString(facet, ""); + } + throw ex; + } + obj = m[facet]; + m.Remove(facet); + + if(m.Count == 0) + { + _servantMapMap.Remove(ident); + } + return obj; + } } public Ice.FacetMap removeAllFacets(Ice.Identity ident) { lock(this) - { - Debug.Assert(instance_ != null); + { + Debug.Assert(instance_ != null); - Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; - if(m == null) - { - Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); - ex.id = Ice.Util.identityToString(ident); - ex.kindOfObject = "servant"; - throw ex; - } - _servantMapMap.Remove(ident); + Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; + if(m == null) + { + Ice.NotRegisteredException ex = new Ice.NotRegisteredException(); + ex.id = Ice.Util.identityToString(ident); + ex.kindOfObject = "servant"; + throw ex; + } + _servantMapMap.Remove(ident); - return m; - } + return m; + } } public Ice.Object findServant(Ice.Identity ident, string facet) { - lock(this) - { - // - // This assert is not valid if the adapter dispatch incoming - // requests from bidir connections. This method might be called if - // requests are received over the bidir connection after the - // adapter was deactivated. - // - //Debug.Assert(instance_ != null); // Must not be called after destruction. - - if(facet == null) - { - facet = ""; - } + lock(this) + { + // + // This assert is not valid if the adapter dispatch incoming + // requests from bidir connections. This method might be called if + // requests are received over the bidir connection after the + // adapter was deactivated. + // + //Debug.Assert(instance_ != null); // Must not be called after destruction. + + if(facet == null) + { + facet = ""; + } - Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; - Ice.Object obj = null; - if(m != null) - { - obj = m[facet]; - } + Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; + Ice.Object obj = null; + if(m != null) + { + obj = m[facet]; + } - return obj; - } + return obj; + } } public Ice.FacetMap findAllFacets(Ice.Identity ident) { lock(this) - { - Debug.Assert(instance_ != null); // Must not be called after destruction. + { + Debug.Assert(instance_ != null); // Must not be called after destruction. - Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; - if(m != null) - { - return (Ice.FacetMap)m.Clone(); - } + Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; + if(m != null) + { + return (Ice.FacetMap)m.Clone(); + } - return new Ice.FacetMap(); - } + return new Ice.FacetMap(); + } } public bool hasServant(Ice.Identity ident) { lock(this) - { - // - // This assert is not valid if the adapter dispatch incoming - // requests from bidir connections. This method might be called if - // requests are received over the bidir connection after the - // adapter was deactivated. - // - // - //Debug.Assert(instance_ != null); // Must not be called after destruction. + { + // + // This assert is not valid if the adapter dispatch incoming + // requests from bidir connections. This method might be called if + // requests are received over the bidir connection after the + // adapter was deactivated. + // + // + //Debug.Assert(instance_ != null); // Must not be called after destruction. - Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; - if(m == null) - { - return false; - } - else - { - Debug.Assert(m.Count != 0); - return true; - } - } + Ice.FacetMap m = (Ice.FacetMap)_servantMapMap[ident]; + if(m == null) + { + return false; + } + else + { + Debug.Assert(m.Count != 0); + return true; + } + } } public void addServantLocator(Ice.ServantLocator locator, string category) { - lock(this) - { - Debug.Assert(instance_ != null); // Must not be called after destruction. - - Ice.ServantLocator l = (Ice.ServantLocator)_locatorMap[category]; - if(l != null) - { - Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); - ex.id = IceUtil.StringUtil.escapeString(category, ""); - ex.kindOfObject = "servant locator"; - throw ex; - } - - _locatorMap[category] = locator; - } + lock(this) + { + Debug.Assert(instance_ != null); // Must not be called after destruction. + + Ice.ServantLocator l = (Ice.ServantLocator)_locatorMap[category]; + if(l != null) + { + Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); + ex.id = IceUtil.StringUtil.escapeString(category, ""); + ex.kindOfObject = "servant locator"; + throw ex; + } + + _locatorMap[category] = locator; + } } public Ice.ServantLocator findServantLocator(string category) { - lock(this) - { - // - // This assert is not valid if the adapter dispatch incoming - // requests from bidir connections. This method might be called if - // requests are received over the bidir connection after the - // adapter was deactivated. - // - // - //Debug.Assert(instance_ != null); // Must not be called after destruction. - - return (Ice.ServantLocator)_locatorMap[category]; - } + lock(this) + { + // + // This assert is not valid if the adapter dispatch incoming + // requests from bidir connections. This method might be called if + // requests are received over the bidir connection after the + // adapter was deactivated. + // + // + //Debug.Assert(instance_ != null); // Must not be called after destruction. + + return (Ice.ServantLocator)_locatorMap[category]; + } } // @@ -216,22 +216,22 @@ public sealed class ServantManager // public ServantManager(Instance instance, string adapterName) { - instance_ = instance; - _adapterName = adapterName; + instance_ = instance; + _adapterName = adapterName; } /* ~ServantManager() { - // - // Don't check whether destroy() has been called. It might have - // not been called if the associated object adapter was not - // properly deactivated. - // - //lock(this) - //{ - //IceUtil.Assert.FinalizerAssert(instance_ == null); - //} + // + // Don't check whether destroy() has been called. It might have + // not been called if the associated object adapter was not + // properly deactivated. + // + //lock(this) + //{ + //IceUtil.Assert.FinalizerAssert(instance_ == null); + //} } */ @@ -240,31 +240,31 @@ public sealed class ServantManager // public void destroy() { - lock(this) - { - Debug.Assert(instance_ != null); // Must not be called after destruction. - - _servantMapMap.Clear(); - - foreach(DictionaryEntry p in _locatorMap) - { - Ice.ServantLocator locator = (Ice.ServantLocator)p.Value; - try - { - locator.deactivate((string)p.Key); - } - catch(System.Exception ex) - { - string s = "exception during locator deactivation:\n" + "object adapter: `" - + _adapterName + "'\n" + "locator category: `" + p.Key + "'\n" + ex; - instance_.initializationData().logger.error(s); - } - } - - _locatorMap.Clear(); + lock(this) + { + Debug.Assert(instance_ != null); // Must not be called after destruction. + + _servantMapMap.Clear(); + + foreach(DictionaryEntry p in _locatorMap) + { + Ice.ServantLocator locator = (Ice.ServantLocator)p.Value; + try + { + locator.deactivate((string)p.Key); + } + catch(System.Exception ex) + { + string s = "exception during locator deactivation:\n" + "object adapter: `" + + _adapterName + "'\n" + "locator category: `" + p.Key + "'\n" + ex; + instance_.initializationData().logger.error(s); + } + } + + _locatorMap.Clear(); - instance_ = null; - } + instance_ = null; + } } private Instance instance_; diff --git a/cs/src/Ice/Set.cs b/cs/src/Ice/Set.cs index 9b5a167ae48..063e3d3d2ee 100755 --- a/cs/src/Ice/Set.cs +++ b/cs/src/Ice/Set.cs @@ -15,348 +15,348 @@ namespace IceUtil { public class Set : ICollection, ICloneable { - public Set() - : this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR) - { - } - - public Set(int capacity) - : this(capacity, DEFAULT_LOAD_FACTOR) - { - } - - public Set(int capacity, double loadFactor) - { - if(loadFactor <= 0) - { - throw new ArgumentOutOfRangeException("loadFactor", loadFactor, "load factor must be greater than 0.0"); - } - if(loadFactor > 1) - { - throw new ArgumentOutOfRangeException("loadfactor", loadFactor, - "load factor must not be greater than 1.0"); - } - if(capacity > MAXIMUM_CAPACITY) - { - _capacity = MAXIMUM_CAPACITY; - } - else if(capacity < 1) - { - _capacity = 2; - } - else - { - int c = 1; - while(c < capacity) - { - c *= 2; - } - _capacity = c; - } - _loadFactor = loadFactor; - _count = 0; - _table = new Entry[_capacity]; - } - - public int Count - { - get - { - return _count; - } - } - - public bool IsSynchronized - { - get - { - return false; - } - } - - public object SyncRoot - { - get - { - return this; - } - } - - public void CopyTo(Array array, int index) - { - // - // Check preconditions. - // - if(array == null) - { - throw new ArgumentNullException("array", "array parameter must not be null"); - } - if(index < 0) - { - throw new ArgumentOutOfRangeException("index", _count, "index must not be less than zero"); - } - if(index >= array.Length) - { - throw new ArgumentException("index out of bounds for array", "index"); - } - if(array.Length - index > _count) - { - throw new ArgumentException("insufficient room in array", "array"); - } - if(array.Rank != 1) - { - throw new ArgumentException("array must be one-dimensional", "array"); - } - - // - // Copy the elements. - // - foreach(Entry e in _table) - { - Entry cursor = e; - while(cursor != null) - { - array.SetValue(cursor.value, index++); - cursor = cursor.next; - } - } - } - - public IEnumerator GetEnumerator() - { - return new SetEnumerator(this); - } - - public object Clone() - { - Set newSet = new Set(_capacity, _loadFactor); - foreach(object o in this) - { - newSet.Add(o); - } - return newSet; - } - - public bool Add(object value) - { - if(value == null) - { - throw new ArgumentNullException("value", "value parameter must not be null"); - } - int hash = System.Math.Abs(value.GetHashCode()); - Entry e = FindEntry(hash % _capacity, value); - if(e != null) - { - return false; - } - if(_count >= _capacity * _loadFactor) - { - if(_capacity == MAXIMUM_CAPACITY) - { - throw new OutOfMemoryException("set exceeded maximum capacity of " + MAXIMUM_CAPACITY); - } - _capacity *= 2; - Resize(); - } - AddEntry(hash % _capacity, value); - return true; - } - - public bool Remove(object value) - { - if(value == null) - { - throw new ArgumentNullException("value", "value parameter must not be null"); - } - int hash = System.Math.Abs(value.GetHashCode()) % _capacity; - return RemoveEntry(hash, value); - } - - public void Clear() - { - _table = new Entry[_capacity]; - _count = 0; - } - - public bool Contains(object value) - { - if(value == null) - { - throw new ArgumentNullException("value", "value parameter must not be null"); - } - int hash = System.Math.Abs(value.GetHashCode()) % _capacity; - return FindEntry(hash, value) != null; - } - - private Entry FindEntry(int hash, object value) - { - Entry cursor = _table[hash]; - while(cursor != null) - { - if(object.ReferenceEquals(value, cursor.value) || value.Equals(cursor.value)) - { - return cursor; - } - cursor = cursor.next; - } - return null; - } - - private void Resize() - { - Entry[] newTable = new Entry[_capacity]; - foreach(Entry e in _table) - { - Entry cursor = e; - while(cursor != null) - { - int hash = System.Math.Abs(cursor.value.GetHashCode()) % _capacity; - newTable[hash] = new Entry(cursor.value, newTable[hash]); - cursor = cursor.next; - } - } - _table = newTable; - } - - private void AddEntry(int hash, object value) - { - _table[hash] = new Entry(value, _table[hash]); - _count++; - } - - private bool RemoveEntry(int hash, object value) - { - Entry prev = null; - Entry cursor = _table[hash]; - while(cursor != null) - { - if(object.ReferenceEquals(value, cursor.value) || value.Equals(cursor.value)) - { - if(prev == null) - { - _table[hash] = cursor.next; - } - else - { - prev.next = cursor.next; - } - _count--; - return true; - } - prev = cursor; - cursor = cursor.next; - } - return false; - } - - internal class Entry - { - internal - Entry() : this(null, null) - { - } - - internal - Entry(object value, Entry nextEntry) - { - this.value = value; - next = nextEntry; - } - internal object value; - internal Entry next; - } - - private const int DEFAULT_CAPACITY = 64; // Must be power of 2 - private const int MAXIMUM_CAPACITY = 2 << 29; // Must be power of 2 - private const double DEFAULT_LOAD_FACTOR = 0.8; // Must be >= 0 - private readonly double _loadFactor; // Selected load factor - private int _capacity; // Current capacity - private int _count; // Number of entries in the table - private Entry[] _table; // Resized as necessary; number of elements is a power of 2 - - public class SetEnumerator : IEnumerator - { - internal SetEnumerator(Set theSet) - { - _set = theSet; - _index = 0; - _current = null; - } - - public void Reset() - { - _index = 0; - _current = null; - } - - public object Current - { - get - { - if(_current == null) - { - throw new InvalidOperationException("iterator not positioned on an element"); - } - return _current.value; - } - } - - public bool MoveNext() - { - Debug.Assert(_index <= _set._table.Length); - - if(_index == _set._table.Length) // Make sure the iterator "sticks" if on last element. - { - return false; - } - - if(_current == null || _current.next == null) // If at start of iteration, or after Remove(), - { // or at end of an overflow chain... - if(_current != null) // _current is at the end of an overflow chain. - { - _index++; // Start search for non-empty bucket in next array slot. - } - while(_index < _set._table.Length && _set._table[_index] == null) // Find non-empty bucket. - { - _index++; - } - if(_index < _set._table.Length) - { - _prev = null; - _current = _set._table[_index]; // Point _current at first entry in non-empty bucket. - } - } - else // _current points at an entry with a successor. - { - _prev = _current; - _current = _current.next; - } - - return _index < _set._table.Length; - } - - public void Remove() - { - if(_current == null) - { - throw new InvalidOperationException("iterator is not positioned on an element"); - } - if(_prev == null) - { - _set._table[_index] = _current.next; - } - else - { - _prev.next = _current.next; - } - _set._count--; - } - - private Set _set; // The set we are iterating over. - private int _index; // Current index into table. - private Entry _current; // Current element. - private Entry _prev; // Element preceding current element (if any). - } + public Set() + : this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR) + { + } + + public Set(int capacity) + : this(capacity, DEFAULT_LOAD_FACTOR) + { + } + + public Set(int capacity, double loadFactor) + { + if(loadFactor <= 0) + { + throw new ArgumentOutOfRangeException("loadFactor", loadFactor, "load factor must be greater than 0.0"); + } + if(loadFactor > 1) + { + throw new ArgumentOutOfRangeException("loadfactor", loadFactor, + "load factor must not be greater than 1.0"); + } + if(capacity > MAXIMUM_CAPACITY) + { + _capacity = MAXIMUM_CAPACITY; + } + else if(capacity < 1) + { + _capacity = 2; + } + else + { + int c = 1; + while(c < capacity) + { + c *= 2; + } + _capacity = c; + } + _loadFactor = loadFactor; + _count = 0; + _table = new Entry[_capacity]; + } + + public int Count + { + get + { + return _count; + } + } + + public bool IsSynchronized + { + get + { + return false; + } + } + + public object SyncRoot + { + get + { + return this; + } + } + + public void CopyTo(Array array, int index) + { + // + // Check preconditions. + // + if(array == null) + { + throw new ArgumentNullException("array", "array parameter must not be null"); + } + if(index < 0) + { + throw new ArgumentOutOfRangeException("index", _count, "index must not be less than zero"); + } + if(index >= array.Length) + { + throw new ArgumentException("index out of bounds for array", "index"); + } + if(array.Length - index > _count) + { + throw new ArgumentException("insufficient room in array", "array"); + } + if(array.Rank != 1) + { + throw new ArgumentException("array must be one-dimensional", "array"); + } + + // + // Copy the elements. + // + foreach(Entry e in _table) + { + Entry cursor = e; + while(cursor != null) + { + array.SetValue(cursor.value, index++); + cursor = cursor.next; + } + } + } + + public IEnumerator GetEnumerator() + { + return new SetEnumerator(this); + } + + public object Clone() + { + Set newSet = new Set(_capacity, _loadFactor); + foreach(object o in this) + { + newSet.Add(o); + } + return newSet; + } + + public bool Add(object value) + { + if(value == null) + { + throw new ArgumentNullException("value", "value parameter must not be null"); + } + int hash = System.Math.Abs(value.GetHashCode()); + Entry e = FindEntry(hash % _capacity, value); + if(e != null) + { + return false; + } + if(_count >= _capacity * _loadFactor) + { + if(_capacity == MAXIMUM_CAPACITY) + { + throw new OutOfMemoryException("set exceeded maximum capacity of " + MAXIMUM_CAPACITY); + } + _capacity *= 2; + Resize(); + } + AddEntry(hash % _capacity, value); + return true; + } + + public bool Remove(object value) + { + if(value == null) + { + throw new ArgumentNullException("value", "value parameter must not be null"); + } + int hash = System.Math.Abs(value.GetHashCode()) % _capacity; + return RemoveEntry(hash, value); + } + + public void Clear() + { + _table = new Entry[_capacity]; + _count = 0; + } + + public bool Contains(object value) + { + if(value == null) + { + throw new ArgumentNullException("value", "value parameter must not be null"); + } + int hash = System.Math.Abs(value.GetHashCode()) % _capacity; + return FindEntry(hash, value) != null; + } + + private Entry FindEntry(int hash, object value) + { + Entry cursor = _table[hash]; + while(cursor != null) + { + if(object.ReferenceEquals(value, cursor.value) || value.Equals(cursor.value)) + { + return cursor; + } + cursor = cursor.next; + } + return null; + } + + private void Resize() + { + Entry[] newTable = new Entry[_capacity]; + foreach(Entry e in _table) + { + Entry cursor = e; + while(cursor != null) + { + int hash = System.Math.Abs(cursor.value.GetHashCode()) % _capacity; + newTable[hash] = new Entry(cursor.value, newTable[hash]); + cursor = cursor.next; + } + } + _table = newTable; + } + + private void AddEntry(int hash, object value) + { + _table[hash] = new Entry(value, _table[hash]); + _count++; + } + + private bool RemoveEntry(int hash, object value) + { + Entry prev = null; + Entry cursor = _table[hash]; + while(cursor != null) + { + if(object.ReferenceEquals(value, cursor.value) || value.Equals(cursor.value)) + { + if(prev == null) + { + _table[hash] = cursor.next; + } + else + { + prev.next = cursor.next; + } + _count--; + return true; + } + prev = cursor; + cursor = cursor.next; + } + return false; + } + + internal class Entry + { + internal + Entry() : this(null, null) + { + } + + internal + Entry(object value, Entry nextEntry) + { + this.value = value; + next = nextEntry; + } + internal object value; + internal Entry next; + } + + private const int DEFAULT_CAPACITY = 64; // Must be power of 2 + private const int MAXIMUM_CAPACITY = 2 << 29; // Must be power of 2 + private const double DEFAULT_LOAD_FACTOR = 0.8; // Must be >= 0 + private readonly double _loadFactor; // Selected load factor + private int _capacity; // Current capacity + private int _count; // Number of entries in the table + private Entry[] _table; // Resized as necessary; number of elements is a power of 2 + + public class SetEnumerator : IEnumerator + { + internal SetEnumerator(Set theSet) + { + _set = theSet; + _index = 0; + _current = null; + } + + public void Reset() + { + _index = 0; + _current = null; + } + + public object Current + { + get + { + if(_current == null) + { + throw new InvalidOperationException("iterator not positioned on an element"); + } + return _current.value; + } + } + + public bool MoveNext() + { + Debug.Assert(_index <= _set._table.Length); + + if(_index == _set._table.Length) // Make sure the iterator "sticks" if on last element. + { + return false; + } + + if(_current == null || _current.next == null) // If at start of iteration, or after Remove(), + { // or at end of an overflow chain... + if(_current != null) // _current is at the end of an overflow chain. + { + _index++; // Start search for non-empty bucket in next array slot. + } + while(_index < _set._table.Length && _set._table[_index] == null) // Find non-empty bucket. + { + _index++; + } + if(_index < _set._table.Length) + { + _prev = null; + _current = _set._table[_index]; // Point _current at first entry in non-empty bucket. + } + } + else // _current points at an entry with a successor. + { + _prev = _current; + _current = _current.next; + } + + return _index < _set._table.Length; + } + + public void Remove() + { + if(_current == null) + { + throw new InvalidOperationException("iterator is not positioned on an element"); + } + if(_prev == null) + { + _set._table[_index] = _current.next; + } + else + { + _prev.next = _current.next; + } + _set._count--; + } + + private Set _set; // The set we are iterating over. + private int _index; // Current index into table. + private Entry _current; // Current element. + private Entry _prev; // Element preceding current element (if any). + } } } diff --git a/cs/src/Ice/StringUtil.cs b/cs/src/Ice/StringUtil.cs index 80377b40761..b5dae389ca8 100755 --- a/cs/src/Ice/StringUtil.cs +++ b/cs/src/Ice/StringUtil.cs @@ -15,381 +15,381 @@ namespace IceUtil public sealed class StringUtil { - // - // Return the index of the first character in str to - // appear in match, starting from 0. Returns -1 if none is - // found. - // - public static int findFirstOf(string str, string match) - { - return findFirstOf(str, match, 0); - } - - // - // Return the index of the first character in str to - // appear in match, starting from start. Returns -1 if none is - // found. - // - public static int findFirstOf(string str, string match, int start) - { - int len = str.Length; - for(int i = start; i < len; i++) - { - char ch = str[i]; - if(match.IndexOf((char) ch) != -1) - { - return i; - } - } - - return -1; - } - - // - // Return the index of the first character in str which does - // not appear in match, starting from 0. Returns -1 if none is - // found. - // - public static int findFirstNotOf(string str, string match) - { - return findFirstNotOf(str, match, 0); - } - - // - // Return the index of the first character in str which does - // not appear in match, starting from start. Returns -1 if none is - // found. - // - public static int findFirstNotOf(string str, string match, int start) - { - int len = str.Length; - for(int i = start; i < len; i++) - { - char ch = str[i]; - if(match.IndexOf((char) ch) == -1) - { - return i; - } - } - - return -1; - } - - // - // Write the byte b as an escape sequence if it isn't a printable ASCII - // character and append the escape sequence to sb. Additional characters - // that should be escaped can be passed in special. If b is any of these - // characters, b is preceded by a backslash in sb. - // - private static void encodeChar(byte b, StringBuilder sb, string special) - { - switch((char)b) - { - case '\\': - { - sb.Append("\\\\"); - break; - } - - case '\'': - { - sb.Append("\\'"); - break; - } - - case '"': - { - sb.Append("\\\""); - break; - } - - case '\b': - { - sb.Append("\\b"); - break; - } - - case '\f': - { - sb.Append("\\f"); - break; - } - - case '\n': - { - sb.Append("\\n"); - break; - } - - case '\r': - { - sb.Append("\\r"); - break; - } - - case '\t': - { - sb.Append("\\t"); - break; - } - - default: - { - if(!(b >= 32 && b <= 126)) - { - sb.Append('\\'); - string octal = System.Convert.ToString(b, 8); - // - // Add leading zeroes so that we avoid problems during - // decoding. For example, consider the encoded string - // \0013 (i.e., a character with value 1 followed by - // the character '3'). If the leading zeroes were omitted, - // the result would be incorrectly interpreted by the - // decoder as a single character with value 11. - // - for(int j = octal.Length; j < 3; j++) - { - sb.Append('0'); - } - sb.Append(octal); - } - else if(special != null && special.IndexOf((char)b) != -1) - { - sb.Append('\\'); - sb.Append((char)b); - } - else - { - sb.Append((char)b); - } - } - break; - } - } - + // + // Return the index of the first character in str to + // appear in match, starting from 0. Returns -1 if none is + // found. + // + public static int findFirstOf(string str, string match) + { + return findFirstOf(str, match, 0); + } + + // + // Return the index of the first character in str to + // appear in match, starting from start. Returns -1 if none is + // found. + // + public static int findFirstOf(string str, string match, int start) + { + int len = str.Length; + for(int i = start; i < len; i++) + { + char ch = str[i]; + if(match.IndexOf((char) ch) != -1) + { + return i; + } + } + + return -1; + } + + // + // Return the index of the first character in str which does + // not appear in match, starting from 0. Returns -1 if none is + // found. + // + public static int findFirstNotOf(string str, string match) + { + return findFirstNotOf(str, match, 0); + } + + // + // Return the index of the first character in str which does + // not appear in match, starting from start. Returns -1 if none is + // found. + // + public static int findFirstNotOf(string str, string match, int start) + { + int len = str.Length; + for(int i = start; i < len; i++) + { + char ch = str[i]; + if(match.IndexOf((char) ch) == -1) + { + return i; + } + } + + return -1; + } + + // + // Write the byte b as an escape sequence if it isn't a printable ASCII + // character and append the escape sequence to sb. Additional characters + // that should be escaped can be passed in special. If b is any of these + // characters, b is preceded by a backslash in sb. + // + private static void encodeChar(byte b, StringBuilder sb, string special) + { + switch((char)b) + { + case '\\': + { + sb.Append("\\\\"); + break; + } + + case '\'': + { + sb.Append("\\'"); + break; + } + + case '"': + { + sb.Append("\\\""); + break; + } + + case '\b': + { + sb.Append("\\b"); + break; + } + + case '\f': + { + sb.Append("\\f"); + break; + } + + case '\n': + { + sb.Append("\\n"); + break; + } + + case '\r': + { + sb.Append("\\r"); + break; + } + + case '\t': + { + sb.Append("\\t"); + break; + } + + default: + { + if(!(b >= 32 && b <= 126)) + { + sb.Append('\\'); + string octal = System.Convert.ToString(b, 8); + // + // Add leading zeroes so that we avoid problems during + // decoding. For example, consider the encoded string + // \0013 (i.e., a character with value 1 followed by + // the character '3'). If the leading zeroes were omitted, + // the result would be incorrectly interpreted by the + // decoder as a single character with value 11. + // + for(int j = octal.Length; j < 3; j++) + { + sb.Append('0'); + } + sb.Append(octal); + } + else if(special != null && special.IndexOf((char)b) != -1) + { + sb.Append('\\'); + sb.Append((char)b); + } + else + { + sb.Append((char)b); + } + } + break; + } + } + // // Add escape sequences (such as "\n", or "\007") to make a string // readable in ASCII. Any characters that appear in special are - // prefixed with a backslash in the returned string. + // prefixed with a backslash in the returned string. // - public static string escapeString(string s, string special) - { - if(special != null) - { - for(int i = 0; i < special.Length; ++i) - { - if((int)special[i] < 32 || (int)special[i] > 126) - { - throw new System.ArgumentException("special characters must be in ASCII range 32-126", "special"); - } - } - } + public static string escapeString(string s, string special) + { + if(special != null) + { + for(int i = 0; i < special.Length; ++i) + { + if((int)special[i] < 32 || (int)special[i] > 126) + { + throw new System.ArgumentException("special characters must be in ASCII range 32-126", "special"); + } + } + } - UTF8Encoding utf8 = new UTF8Encoding(); - byte[] bytes = utf8.GetBytes(s); + UTF8Encoding utf8 = new UTF8Encoding(); + byte[] bytes = utf8.GetBytes(s); - StringBuilder result = new StringBuilder(bytes.Length); - for(int i = 0; i < bytes.Length; i++) - { - encodeChar(bytes[i], result, special); - } - - return result.ToString(); - } - - private static char checkChar(char c) - { - if(!(c >= 32 && c <= 126)) - { - throw new System.ArgumentException("illegal input character"); - } - return c; - } + StringBuilder result = new StringBuilder(bytes.Length); + for(int i = 0; i < bytes.Length; i++) + { + encodeChar(bytes[i], result, special); + } + + return result.ToString(); + } + + private static char checkChar(char c) + { + if(!(c >= 32 && c <= 126)) + { + throw new System.ArgumentException("illegal input character"); + } + return c; + } - // - // Decode the character or escape sequence starting at start and return it. - // end marks the one-past-the-end position of the substring to be scanned. - // nextStart is set to the index of the first character following the decoded - // character or escape sequence. - // - private static char decodeChar(string s, int start, int end, out int nextStart) - { - Debug.Assert(start >= 0); - Debug.Assert(start < end); - Debug.Assert(end <= s.Length); + // + // Decode the character or escape sequence starting at start and return it. + // end marks the one-past-the-end position of the substring to be scanned. + // nextStart is set to the index of the first character following the decoded + // character or escape sequence. + // + private static char decodeChar(string s, int start, int end, out int nextStart) + { + Debug.Assert(start >= 0); + Debug.Assert(start < end); + Debug.Assert(end <= s.Length); - char c; + char c; - if(s[start] != '\\') - { - c = checkChar(s[start++]); - } - else - { - if(start + 1 == end) - { - throw new System.ArgumentException("trailing backslash in argument"); - } - switch(s[++start]) - { - case '\\': - case '\'': - case '"': - { - c = s[start++]; - break; - } - case 'b': - { - ++start; - c = '\b'; - break; - } - case 'f': - { - ++start; - c = '\f'; - break; - } - case 'n': - { - ++start; - c = '\n'; - break; - } - case 'r': - { - ++start; - c = '\r'; - break; - } - case 't': - { - ++start; - c = '\t'; - break; - } - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - { - int oct = 0; - for(int j = 0; j < 3 && start < end; ++j) - { - int charVal = s[start++] - '0'; - if(charVal < 0 || charVal > 7) - { - --start; - break; - } - oct = oct * 8 + charVal; - } - if(oct > 255) - { - throw new System.ArgumentException("octal value out of range", "s"); - } - c = System.Convert.ToChar(oct); - break; - } - default: - { - c = checkChar(s[start++]); - break; - } - } - } - nextStart = start; - return c; - } + if(s[start] != '\\') + { + c = checkChar(s[start++]); + } + else + { + if(start + 1 == end) + { + throw new System.ArgumentException("trailing backslash in argument"); + } + switch(s[++start]) + { + case '\\': + case '\'': + case '"': + { + c = s[start++]; + break; + } + case 'b': + { + ++start; + c = '\b'; + break; + } + case 'f': + { + ++start; + c = '\f'; + break; + } + case 'n': + { + ++start; + c = '\n'; + break; + } + case 'r': + { + ++start; + c = '\r'; + break; + } + case 't': + { + ++start; + c = '\t'; + break; + } + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + { + int oct = 0; + for(int j = 0; j < 3 && start < end; ++j) + { + int charVal = s[start++] - '0'; + if(charVal < 0 || charVal > 7) + { + --start; + break; + } + oct = oct * 8 + charVal; + } + if(oct > 255) + { + throw new System.ArgumentException("octal value out of range", "s"); + } + c = System.Convert.ToChar(oct); + break; + } + default: + { + c = checkChar(s[start++]); + break; + } + } + } + nextStart = start; + return c; + } - // - // Remove escape sequences from s and append the result to sb. - // Return true if successful, false otherwise. - // - private static void decodeString(string s, int start, int end, StringBuilder sb) - { - while(start < end) - { - sb.Append(decodeChar(s, start, end, out start)); - } - } + // + // Remove escape sequences from s and append the result to sb. + // Return true if successful, false otherwise. + // + private static void decodeString(string s, int start, int end, StringBuilder sb) + { + while(start < end) + { + sb.Append(decodeChar(s, start, end, out start)); + } + } // // Remove escape sequences added by escapeString. // - public static bool unescapeString(string s, int start, int end, out string result) - { - if(start < 0) - { - throw new System.ArgumentException("start offset must be >= 0", "start"); - } - if(end > s.Length) - { - throw new System.ArgumentException("end offset must be <= s.Length", "end"); - } - if(start > end) - { - throw new System.ArgumentException("start offset must be <= end offset"); - } - - result = null; - try - { - StringBuilder sb = new StringBuilder(); - decodeString(s, start, end, sb); - string decodedString = sb.ToString(); + public static bool unescapeString(string s, int start, int end, out string result) + { + if(start < 0) + { + throw new System.ArgumentException("start offset must be >= 0", "start"); + } + if(end > s.Length) + { + throw new System.ArgumentException("end offset must be <= s.Length", "end"); + } + if(start > end) + { + throw new System.ArgumentException("start offset must be <= end offset"); + } + + result = null; + try + { + StringBuilder sb = new StringBuilder(); + decodeString(s, start, end, sb); + string decodedString = sb.ToString(); - byte[] arr = new byte[decodedString.Length]; - for(int i = 0; i < arr.Length; ++i) - { - arr[i] = (byte)decodedString[i]; - } + byte[] arr = new byte[decodedString.Length]; + for(int i = 0; i < arr.Length; ++i) + { + arr[i] = (byte)decodedString[i]; + } - UTF8Encoding utf8 = new UTF8Encoding(false, true); - result = utf8.GetString(arr); - return true; - } - catch(System.Exception) - { - return false; - } - } + UTF8Encoding utf8 = new UTF8Encoding(false, true); + result = utf8.GetString(arr); + return true; + } + catch(System.Exception) + { + return false; + } + } - public static int checkQuote(string s) - { - return checkQuote(s, 0); - } - - // - // If a single or double quotation mark is found at the start position, - // then the position of the matching closing quote is returned. If no - // quotation mark is found at the start position, then 0 is returned. - // If no matching closing quote is found, then -1 is returned. - // - public static int checkQuote(string s, int start) - { - char quoteChar = s[start]; - if(quoteChar == '"' || quoteChar == '\'') - { - start++; - int len = s.Length; - int pos; - while(start < len && (pos = s.IndexOf(quoteChar, start)) != -1) - { - if(s[pos - 1] != '\\') - { - return pos; - } - start = pos + 1; - } - return -1; // Unmatched quote - } - return 0; // Not quoted - } + public static int checkQuote(string s) + { + return checkQuote(s, 0); + } + + // + // If a single or double quotation mark is found at the start position, + // then the position of the matching closing quote is returned. If no + // quotation mark is found at the start position, then 0 is returned. + // If no matching closing quote is found, then -1 is returned. + // + public static int checkQuote(string s, int start) + { + char quoteChar = s[start]; + if(quoteChar == '"' || quoteChar == '\'') + { + start++; + int len = s.Length; + int pos; + while(start < len && (pos = s.IndexOf(quoteChar, start)) != -1) + { + if(s[pos - 1] != '\\') + { + return pos; + } + start = pos + 1; + } + return -1; // Unmatched quote + } + return 0; // Not quoted + } } } diff --git a/cs/src/Ice/SysLoggerI.cs b/cs/src/Ice/SysLoggerI.cs index de1865f73be..b5d22a35232 100755 --- a/cs/src/Ice/SysLoggerI.cs +++ b/cs/src/Ice/SysLoggerI.cs @@ -14,92 +14,92 @@ namespace Ice public sealed class SysLoggerI : LocalObjectImpl, Logger { - public SysLoggerI(string ident) - { - _ident = ident; - - // - // Open a datagram socket to communicate with the localhost - // syslog daemon. - // - try - { - _host = IceInternal.Network.getAddress(System.Net.Dns.GetHostName(), _port).Address; - _socket = new UdpClient(); - _socket.Connect(_host, _port); - } - catch(System.Exception ex) - { - throw new Ice.DNSException(ex); - } - } - - public void print(string message) - { - log(LOG_INFO, message); - } + public SysLoggerI(string ident) + { + _ident = ident; + + // + // Open a datagram socket to communicate with the localhost + // syslog daemon. + // + try + { + _host = IceInternal.Network.getAddress(System.Net.Dns.GetHostName(), _port).Address; + _socket = new UdpClient(); + _socket.Connect(_host, _port); + } + catch(System.Exception ex) + { + throw new Ice.DNSException(ex); + } + } + + public void print(string message) + { + log(LOG_INFO, message); + } - public void trace(string category, string message) - { - log(LOG_INFO, category + ": " + message); - } - - public void warning(string message) - { - log(LOG_WARNING, message); - } - - public void error(string message) - { - log(LOG_ERR, message); - } - - private void log(int severity, string message) - { - try - { - // - // Create a syslog message as defined by the RFC 3164: - // <PRI>HEADER MSG. PRI is the priority and is calculated - // from the facility and the severity. We don't specify - // the HEADER. MSG contains the identifier followed by a - // colon character and the message. - // - - int priority = (LOG_USER << 3) | severity; - - string msg = '<' + priority + '>' + _ident + ": " + message; - - byte[] buf = new byte[msg.Length]; - for(int i = 0; i < msg.Length; i++) - { - buf[i] = (byte)msg[i]; - } - _socket.Send(buf, buf.Length); - } - catch(System.IO.IOException ex) - { - Ice.SocketException se = new Ice.SocketException(ex); - throw se; - } - } - - private string _ident; - private UdpClient _socket; - private System.Net.IPAddress _host; - private static int _port = 514; - - // - // Syslog facilities facilities (as defined in syslog.h) - // - private static readonly int LOG_USER = 1; - - // - // Syslog priorities (as defined in syslog.h) - // - private static readonly int LOG_ERR = 3; - private static readonly int LOG_WARNING = 4; - private static readonly int LOG_INFO = 6; + public void trace(string category, string message) + { + log(LOG_INFO, category + ": " + message); + } + + public void warning(string message) + { + log(LOG_WARNING, message); + } + + public void error(string message) + { + log(LOG_ERR, message); + } + + private void log(int severity, string message) + { + try + { + // + // Create a syslog message as defined by the RFC 3164: + // <PRI>HEADER MSG. PRI is the priority and is calculated + // from the facility and the severity. We don't specify + // the HEADER. MSG contains the identifier followed by a + // colon character and the message. + // + + int priority = (LOG_USER << 3) | severity; + + string msg = '<' + priority + '>' + _ident + ": " + message; + + byte[] buf = new byte[msg.Length]; + for(int i = 0; i < msg.Length; i++) + { + buf[i] = (byte)msg[i]; + } + _socket.Send(buf, buf.Length); + } + catch(System.IO.IOException ex) + { + Ice.SocketException se = new Ice.SocketException(ex); + throw se; + } + } + + private string _ident; + private UdpClient _socket; + private System.Net.IPAddress _host; + private static int _port = 514; + + // + // Syslog facilities facilities (as defined in syslog.h) + // + private static readonly int LOG_USER = 1; + + // + // Syslog priorities (as defined in syslog.h) + // + private static readonly int LOG_ERR = 3; + private static readonly int LOG_WARNING = 4; + private static readonly int LOG_INFO = 6; } } diff --git a/cs/src/Ice/TcpAcceptor.cs b/cs/src/Ice/TcpAcceptor.cs index e4f19ef8481..e646327a668 100755 --- a/cs/src/Ice/TcpAcceptor.cs +++ b/cs/src/Ice/TcpAcceptor.cs @@ -17,125 +17,125 @@ namespace IceInternal class TcpAcceptor : Acceptor { - public virtual Socket fd() - { - return _fd; - } - - public virtual void close() - { + public virtual Socket fd() + { + return _fd; + } + + public virtual void close() + { Socket fd; - lock(this) - { - fd = _fd; - _fd = null; - } - if(fd != null) - { - if(_traceLevels.network >= 1) - { - string s = "stopping to accept tcp connections at " + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - try - { - fd.Close(); - } - catch(System.Exception) - { - // Ignore. - } - } - } - - public virtual void listen() - { - Network.doListen(_fd, _backlog); - - if(_traceLevels.network >= 1) - { - string s = "accepting tcp connections at " + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - } - - public virtual Transceiver accept(int timeout) - { - Socket fd = Network.doAccept(_fd, timeout); - Network.setBlock(fd, false); + lock(this) + { + fd = _fd; + _fd = null; + } + if(fd != null) + { + if(_traceLevels.network >= 1) + { + string s = "stopping to accept tcp connections at " + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + try + { + fd.Close(); + } + catch(System.Exception) + { + // Ignore. + } + } + } + + public virtual void listen() + { + Network.doListen(_fd, _backlog); + + if(_traceLevels.network >= 1) + { + string s = "accepting tcp connections at " + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + } + + public virtual Transceiver accept(int timeout) + { + Socket fd = Network.doAccept(_fd, timeout); + Network.setBlock(fd, false); - if(_traceLevels.network >= 1) - { - string s = "accepted tcp connection\n" + Network.fdToString(fd); - _logger.trace(_traceLevels.networkCat, s); - } - - return new TcpTransceiver(instance_, fd); - } + if(_traceLevels.network >= 1) + { + string s = "accepted tcp connection\n" + Network.fdToString(fd); + _logger.trace(_traceLevels.networkCat, s); + } + + return new TcpTransceiver(instance_, fd); + } - public virtual void connectToSelf() - { - Socket fd = Network.createSocket(false); - Network.setBlock(fd, false); - Network.doConnect(fd, _addr, -1); - Network.closeSocket(fd); - } + public virtual void connectToSelf() + { + Socket fd = Network.createSocket(false); + Network.setBlock(fd, false); + Network.doConnect(fd, _addr, -1); + Network.closeSocket(fd); + } - public override string ToString() - { - return Network.addrToString(_addr); - } - - internal bool equivalent(string host, int port) - { - EndPoint addr = Network.getAddress(host, port); - return addr.Equals(_addr); - } - - internal virtual int effectivePort() - { - return _addr.Port; - } - - internal - TcpAcceptor(Instance instance, string host, int port) - { - instance_ = instance; - _traceLevels = instance.traceLevels(); - _logger = instance.initializationData().logger; - _backlog = 0; - - if(_backlog <= 0) - { - _backlog = 5; - } - - try - { - _fd = Network.createSocket(false); - Network.setBlock(_fd, false); - _addr = Network.getAddress(host, port); - if(_traceLevels.network >= 2) - { - string s = "attempting to bind to tcp socket " + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - _addr = Network.doBind(_fd, _addr); - } - catch(System.Exception) - { - _fd = null; - throw; - } - } - - private Instance instance_; - private TraceLevels _traceLevels; - private Ice.Logger _logger; - private Socket _fd; - private int _backlog; - private IPEndPoint _addr; + public override string ToString() + { + return Network.addrToString(_addr); + } + + internal bool equivalent(string host, int port) + { + EndPoint addr = Network.getAddress(host, port); + return addr.Equals(_addr); + } + + internal virtual int effectivePort() + { + return _addr.Port; + } + + internal + TcpAcceptor(Instance instance, string host, int port) + { + instance_ = instance; + _traceLevels = instance.traceLevels(); + _logger = instance.initializationData().logger; + _backlog = 0; + + if(_backlog <= 0) + { + _backlog = 5; + } + + try + { + _fd = Network.createSocket(false); + Network.setBlock(_fd, false); + _addr = Network.getAddress(host, port); + if(_traceLevels.network >= 2) + { + string s = "attempting to bind to tcp socket " + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + _addr = Network.doBind(_fd, _addr); + } + catch(System.Exception) + { + _fd = null; + throw; + } + } + + private Instance instance_; + private TraceLevels _traceLevels; + private Ice.Logger _logger; + private Socket _fd; + private int _backlog; + private IPEndPoint _addr; } } diff --git a/cs/src/Ice/TcpConnector.cs b/cs/src/Ice/TcpConnector.cs index e2a8c98b17a..2ee3d622888 100755 --- a/cs/src/Ice/TcpConnector.cs +++ b/cs/src/Ice/TcpConnector.cs @@ -15,48 +15,48 @@ namespace IceInternal sealed class TcpConnector : Connector { - public Transceiver connect(int timeout) - { - if(_traceLevels.network >= 2) - { - string s = "trying to establish tcp connection to " + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - Socket fd = Network.createSocket(false); - Network.setBlock(fd, false); - Network.doConnect(fd, _addr, timeout); - - if(_traceLevels.network >= 1) - { - string s = "tcp connection established\n" + Network.fdToString(fd); - _logger.trace(_traceLevels.networkCat, s); - } - - return new TcpTransceiver(instance_, fd); - } - - public override string ToString() - { - return Network.addrToString(_addr); - } - - // - // Only for use by TcpEndpoint - // - internal TcpConnector(Instance instance, string host, int port) - { - instance_ = instance; - _traceLevels = instance.traceLevels(); - _logger = instance.initializationData().logger; - - _addr = Network.getAddress(host, port); - } - - private Instance instance_; - private TraceLevels _traceLevels; - private Ice.Logger _logger; - private IPEndPoint _addr; + public Transceiver connect(int timeout) + { + if(_traceLevels.network >= 2) + { + string s = "trying to establish tcp connection to " + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + Socket fd = Network.createSocket(false); + Network.setBlock(fd, false); + Network.doConnect(fd, _addr, timeout); + + if(_traceLevels.network >= 1) + { + string s = "tcp connection established\n" + Network.fdToString(fd); + _logger.trace(_traceLevels.networkCat, s); + } + + return new TcpTransceiver(instance_, fd); + } + + public override string ToString() + { + return Network.addrToString(_addr); + } + + // + // Only for use by TcpEndpoint + // + internal TcpConnector(Instance instance, string host, int port) + { + instance_ = instance; + _traceLevels = instance.traceLevels(); + _logger = instance.initializationData().logger; + + _addr = Network.getAddress(host, port); + } + + private Instance instance_; + private TraceLevels _traceLevels; + private Ice.Logger _logger; + private IPEndPoint _addr; } } diff --git a/cs/src/Ice/TcpEndpointI.cs b/cs/src/Ice/TcpEndpointI.cs index f0963693640..be5f9a8068a 100755 --- a/cs/src/Ice/TcpEndpointI.cs +++ b/cs/src/Ice/TcpEndpointI.cs @@ -15,566 +15,566 @@ namespace IceInternal sealed class TcpEndpointI : EndpointI { - internal const short TYPE = 1; - - public TcpEndpointI(Instance instance, string ho, int po, int ti, string conId, bool co, bool pub) - { - instance_ = instance; - _host = ho; - _port = po; - _timeout = ti; - _connectionId = conId; - _compress = co; - _publish = pub; - calcHashValue(); - } - - public TcpEndpointI(Instance instance, string str) - { - instance_ = instance; - _host = null; - _port = 0; - _timeout = -1; - _compress = false; - _publish = true; - - char[] separators = { ' ', '\t', '\n', '\r' }; - string[] arr = str.Split(separators); - - int i = 0; - while(i < arr.Length) - { - if(arr[i].Length == 0) - { - i++; - continue; - } - - string option = arr[i++]; - if(option.Length != 2 || option[0] != '-') - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "tcp " + str; - throw e; - } - - string argument = null; - if(i < arr.Length && arr[i][0] != '-') - { - argument = arr[i++]; - } - - switch(option[1]) - { - case 'h': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "tcp " + str; - throw e; - } - - _host = argument; - break; - } - - case 'p': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "tcp " + str; - throw e; - } - - try - { - _port = System.Int32.Parse(argument); - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "tcp " + str; - throw e; - } + internal const short TYPE = 1; + + public TcpEndpointI(Instance instance, string ho, int po, int ti, string conId, bool co, bool pub) + { + instance_ = instance; + _host = ho; + _port = po; + _timeout = ti; + _connectionId = conId; + _compress = co; + _publish = pub; + calcHashValue(); + } + + public TcpEndpointI(Instance instance, string str) + { + instance_ = instance; + _host = null; + _port = 0; + _timeout = -1; + _compress = false; + _publish = true; + + char[] separators = { ' ', '\t', '\n', '\r' }; + string[] arr = str.Split(separators); + + int i = 0; + while(i < arr.Length) + { + if(arr[i].Length == 0) + { + i++; + continue; + } + + string option = arr[i++]; + if(option.Length != 2 || option[0] != '-') + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "tcp " + str; + throw e; + } + + string argument = null; + if(i < arr.Length && arr[i][0] != '-') + { + argument = arr[i++]; + } + + switch(option[1]) + { + case 'h': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "tcp " + str; + throw e; + } + + _host = argument; + break; + } + + case 'p': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "tcp " + str; + throw e; + } + + try + { + _port = System.Int32.Parse(argument); + } + catch(System.FormatException ex) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(ex); + e.str = "tcp " + str; + throw e; + } - if(_port < 0 || _port > 65535) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "tcp " + str; - throw e; - } - - break; - } - - case 't': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "tcp " + str; - throw e; - } - - try - { - _timeout = System.Int32.Parse(argument); - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "tcp " + str; - throw e; - } - - break; - } - - case 'z': - { - if(argument != null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "tcp " + str; - throw e; - } - - _compress = true; - break; - } - - default: - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "tcp " + str; - throw e; - } - } - } - } - - public TcpEndpointI(BasicStream s) - { - instance_ = s.instance(); - s.startReadEncaps(); - _host = s.readString(); - _port = s.readInt(); - _timeout = s.readInt(); - _compress = s.readBool(); - s.endReadEncaps(); - _publish = true; - calcHashValue(); - } - - // - // Marshal the endpoint - // - public override void streamWrite(BasicStream s) - { - s.writeShort(TYPE); - s.startWriteEncaps(); - s.writeString(_host); - s.writeInt(_port); - s.writeInt(_timeout); - s.writeBool(_compress); - s.endWriteEncaps(); - } - - // - // Convert the endpoint to its string form - // - public override string ice_toString_() - { - // - // WARNING: Certain features, such as proxy validation in Glacier2, - // depend on the format of proxy strings. Changes to toString() and - // methods called to generate parts of the reference string could break - // these features. Please review for all features that depend on the - // format of proxyToString() before changing this and related code. - // - string s = "tcp -h " + _host + " -p " + _port; - if(_timeout != -1) - { - s += " -t " + _timeout; - } - if(_compress) - { - s += " -z"; - } - return s; - } - - // - // Return the endpoint type - // - public override short type() - { - return TYPE; - } - - // - // Return the timeout for the endpoint in milliseconds. 0 means - // non-blocking, -1 means no timeout. - // - public override int timeout() - { - return _timeout; - } - - // - // Return a new endpoint with a different timeout value, provided - // that timeouts are supported by the endpoint. Otherwise the same - // endpoint is returned. - // - public override EndpointI timeout(int timeout) - { - if(timeout == _timeout) - { - return this; - } - else - { - return new TcpEndpointI(instance_, _host, _port, timeout, _connectionId, _compress, _publish); - } - } + if(_port < 0 || _port > 65535) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "tcp " + str; + throw e; + } + + break; + } + + case 't': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "tcp " + str; + throw e; + } + + try + { + _timeout = System.Int32.Parse(argument); + } + catch(System.FormatException ex) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(ex); + e.str = "tcp " + str; + throw e; + } + + break; + } + + case 'z': + { + if(argument != null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "tcp " + str; + throw e; + } + + _compress = true; + break; + } + + default: + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "tcp " + str; + throw e; + } + } + } + } + + public TcpEndpointI(BasicStream s) + { + instance_ = s.instance(); + s.startReadEncaps(); + _host = s.readString(); + _port = s.readInt(); + _timeout = s.readInt(); + _compress = s.readBool(); + s.endReadEncaps(); + _publish = true; + calcHashValue(); + } + + // + // Marshal the endpoint + // + public override void streamWrite(BasicStream s) + { + s.writeShort(TYPE); + s.startWriteEncaps(); + s.writeString(_host); + s.writeInt(_port); + s.writeInt(_timeout); + s.writeBool(_compress); + s.endWriteEncaps(); + } + + // + // Convert the endpoint to its string form + // + public override string ice_toString_() + { + // + // WARNING: Certain features, such as proxy validation in Glacier2, + // depend on the format of proxy strings. Changes to toString() and + // methods called to generate parts of the reference string could break + // these features. Please review for all features that depend on the + // format of proxyToString() before changing this and related code. + // + string s = "tcp -h " + _host + " -p " + _port; + if(_timeout != -1) + { + s += " -t " + _timeout; + } + if(_compress) + { + s += " -z"; + } + return s; + } + + // + // Return the endpoint type + // + public override short type() + { + return TYPE; + } + + // + // Return the timeout for the endpoint in milliseconds. 0 means + // non-blocking, -1 means no timeout. + // + public override int timeout() + { + return _timeout; + } + + // + // Return a new endpoint with a different timeout value, provided + // that timeouts are supported by the endpoint. Otherwise the same + // endpoint is returned. + // + public override EndpointI timeout(int timeout) + { + if(timeout == _timeout) + { + return this; + } + else + { + return new TcpEndpointI(instance_, _host, _port, timeout, _connectionId, _compress, _publish); + } + } - // - // Return a new endpoint with a different connection id. - // - public override EndpointI connectionId(string connectionId) - { - if(connectionId == _connectionId) - { - return this; - } - else - { - return new TcpEndpointI(instance_, _host, _port, _timeout, connectionId, _compress, _publish); - } - } - - // - // Return true if the endpoints support bzip2 compress, or false - // otherwise. - // - public override bool compress() - { - return _compress; - } - - // - // Return a new endpoint with a different compression value, - // provided that compression is supported by the - // endpoint. Otherwise the same endpoint is returned. - // - public override EndpointI compress(bool compress) - { - if(compress == _compress) - { - return this; - } - else - { - return new TcpEndpointI(instance_, _host, _port, _timeout, _connectionId, compress, _publish); - } - } - - // - // Return true if the endpoint is datagram-based. - // - public override bool datagram() - { - return false; - } - - // - // Return true if the endpoint is secure. - // - public override bool secure() - { - return false; - } - - // - // Return true if the endpoint type is unknown. - // - public override bool unknown() - { - return false; - } - - // - // Return a client side transceiver for this endpoint, or null if a - // transceiver can only be created by a connector. - // - public override Transceiver clientTransceiver() - { - return null; - } - - // - // Return a server side transceiver for this endpoint, or null if a - // transceiver can only be created by an acceptor. In case a - // transceiver is created, this operation also returns a new - // "effective" endpoint, which might differ from this endpoint, - // for example, if a dynamic port number is assigned. - // - public override Transceiver serverTransceiver(ref EndpointI endpoint) - { - endpoint = this; - return null; - } - - // - // Return a connector for this endpoint, or null if no connector - // is available. - // - public override Connector connector() - { - return new TcpConnector(instance_, _host, _port); - } - - // - // Return an acceptor for this endpoint, or null if no acceptors - // is available. In case an acceptor is created, this operation - // also returns a new "effective" endpoint, which might differ - // from this endpoint, for example, if a dynamic port number is - // assigned. - // - public override Acceptor acceptor(ref EndpointI endpoint, string adapterName) - { - TcpAcceptor p = new TcpAcceptor(instance_, _host, _port); - endpoint = new TcpEndpointI(instance_, _host, p.effectivePort(), _timeout, _connectionId, - _compress, _publish); - return p; - } + // + // Return a new endpoint with a different connection id. + // + public override EndpointI connectionId(string connectionId) + { + if(connectionId == _connectionId) + { + return this; + } + else + { + return new TcpEndpointI(instance_, _host, _port, _timeout, connectionId, _compress, _publish); + } + } + + // + // Return true if the endpoints support bzip2 compress, or false + // otherwise. + // + public override bool compress() + { + return _compress; + } + + // + // Return a new endpoint with a different compression value, + // provided that compression is supported by the + // endpoint. Otherwise the same endpoint is returned. + // + public override EndpointI compress(bool compress) + { + if(compress == _compress) + { + return this; + } + else + { + return new TcpEndpointI(instance_, _host, _port, _timeout, _connectionId, compress, _publish); + } + } + + // + // Return true if the endpoint is datagram-based. + // + public override bool datagram() + { + return false; + } + + // + // Return true if the endpoint is secure. + // + public override bool secure() + { + return false; + } + + // + // Return true if the endpoint type is unknown. + // + public override bool unknown() + { + return false; + } + + // + // Return a client side transceiver for this endpoint, or null if a + // transceiver can only be created by a connector. + // + public override Transceiver clientTransceiver() + { + return null; + } + + // + // Return a server side transceiver for this endpoint, or null if a + // transceiver can only be created by an acceptor. In case a + // transceiver is created, this operation also returns a new + // "effective" endpoint, which might differ from this endpoint, + // for example, if a dynamic port number is assigned. + // + public override Transceiver serverTransceiver(ref EndpointI endpoint) + { + endpoint = this; + return null; + } + + // + // Return a connector for this endpoint, or null if no connector + // is available. + // + public override Connector connector() + { + return new TcpConnector(instance_, _host, _port); + } + + // + // Return an acceptor for this endpoint, or null if no acceptors + // is available. In case an acceptor is created, this operation + // also returns a new "effective" endpoint, which might differ + // from this endpoint, for example, if a dynamic port number is + // assigned. + // + public override Acceptor acceptor(ref EndpointI endpoint, string adapterName) + { + TcpAcceptor p = new TcpAcceptor(instance_, _host, _port); + endpoint = new TcpEndpointI(instance_, _host, p.effectivePort(), _timeout, _connectionId, + _compress, _publish); + return p; + } - // - // Expand endpoint out in to separate endpoints for each local - // host if endpoint was configured with no host set. This - // only applies for ObjectAdapter endpoints. - // - public override ArrayList - expand(bool server) - { - if(_host == null) - { - _host = instance_.defaultsAndOverrides().defaultHost; - if(_host == null) - { - if(server) - { - _host = "0.0.0.0"; - } - else - { - _host = "127.0.0.1"; - } - } - } - else if(_host.Equals("*")) - { - _host = "0.0.0.0"; - } - - ArrayList endps = new ArrayList(); - if(_host.Equals("0.0.0.0")) - { - string[] hosts = Network.getLocalHosts(); - for(int i = 0; i < hosts.Length; ++i) - { - endps.Add(new TcpEndpointI(instance_, hosts[i], _port, _timeout, _connectionId, _compress, - hosts.Length == 1 || !hosts[i].Equals("127.0.0.1"))); - } - } - else - { - calcHashValue(); - endps.Add(this); - } - return endps; - } - - // - // Return whether endpoint should be published in proxies - // created by Object Adapter. - // - public override bool - publish() - { - return _publish; - } - - // - // Check whether the endpoint is equivalent to a specific - // Transceiver or Acceptor - // - public override bool equivalent(Transceiver transceiver) - { - return false; - } - - public override bool equivalent(Acceptor acceptor) - { - TcpAcceptor tcpAcceptor = null; - try - { - tcpAcceptor = (TcpAcceptor)acceptor; - } - catch(System.InvalidCastException) - { - return false; - } - return tcpAcceptor.equivalent(_host, _port); - } + // + // Expand endpoint out in to separate endpoints for each local + // host if endpoint was configured with no host set. This + // only applies for ObjectAdapter endpoints. + // + public override ArrayList + expand(bool server) + { + if(_host == null) + { + _host = instance_.defaultsAndOverrides().defaultHost; + if(_host == null) + { + if(server) + { + _host = "0.0.0.0"; + } + else + { + _host = "127.0.0.1"; + } + } + } + else if(_host.Equals("*")) + { + _host = "0.0.0.0"; + } + + ArrayList endps = new ArrayList(); + if(_host.Equals("0.0.0.0")) + { + string[] hosts = Network.getLocalHosts(); + for(int i = 0; i < hosts.Length; ++i) + { + endps.Add(new TcpEndpointI(instance_, hosts[i], _port, _timeout, _connectionId, _compress, + hosts.Length == 1 || !hosts[i].Equals("127.0.0.1"))); + } + } + else + { + calcHashValue(); + endps.Add(this); + } + return endps; + } + + // + // Return whether endpoint should be published in proxies + // created by Object Adapter. + // + public override bool + publish() + { + return _publish; + } + + // + // Check whether the endpoint is equivalent to a specific + // Transceiver or Acceptor + // + public override bool equivalent(Transceiver transceiver) + { + return false; + } + + public override bool equivalent(Acceptor acceptor) + { + TcpAcceptor tcpAcceptor = null; + try + { + tcpAcceptor = (TcpAcceptor)acceptor; + } + catch(System.InvalidCastException) + { + return false; + } + return tcpAcceptor.equivalent(_host, _port); + } public override bool requiresThreadPerConnection() { return false; } - public override int GetHashCode() - { - return _hashCode; - } - - // - // Compare endpoints for sorting purposes - // - public override bool Equals(object obj) - { - return CompareTo(obj) == 0; - } - - public override int CompareTo(object obj) - { - TcpEndpointI p = null; - - try - { - p = (TcpEndpointI)obj; - } - catch(System.InvalidCastException) - { - return 1; - } - - if(this == p) - { - return 0; - } - - if(_port < p._port) - { - return -1; - } - else if(p._port < _port) - { - return 1; - } - - if(_timeout < p._timeout) - { - return -1; - } - else if(p._timeout < _timeout) - { - return 1; - } + public override int GetHashCode() + { + return _hashCode; + } + + // + // Compare endpoints for sorting purposes + // + public override bool Equals(object obj) + { + return CompareTo(obj) == 0; + } + + public override int CompareTo(object obj) + { + TcpEndpointI p = null; + + try + { + p = (TcpEndpointI)obj; + } + catch(System.InvalidCastException) + { + return 1; + } + + if(this == p) + { + return 0; + } + + if(_port < p._port) + { + return -1; + } + else if(p._port < _port) + { + return 1; + } + + if(_timeout < p._timeout) + { + return -1; + } + else if(p._timeout < _timeout) + { + return 1; + } - if(!_connectionId.Equals(p._connectionId)) - { - return _connectionId.CompareTo(p._connectionId); - } - - if(!_compress && p._compress) - { - return -1; - } - else if(!p._compress && _compress) - { - return 1; - } - - if(!_host.Equals(p._host)) - { - // - // We do the most time-consuming part of the comparison last. - // - System.Net.IPEndPoint laddr = null; - try - { - laddr = Network.getAddress(_host, _port); - } - catch(Ice.DNSException) - { - } - - System.Net.IPEndPoint raddr = null; - try - { - raddr = Network.getAddress(p._host, p._port); - } - catch(Ice.DNSException) - { - } - - if(laddr == null && raddr != null) - { - return -1; - } - else if(raddr == null && laddr != null) - { - return 1; - } - else if(laddr != null && raddr != null) - { - byte[] larr = laddr.Address.GetAddressBytes(); - byte[] rarr = raddr.Address.GetAddressBytes(); - Debug.Assert(larr.Length == rarr.Length); - for(int i = 0; i < larr.Length; i++) - { - if(larr[i] < rarr[i]) - { - return -1; - } - else if(rarr[i] < larr[i]) - { - return 1; - } - } - } - } - - return 0; - } - - private void calcHashValue() - { - try - { - _hashCode = Network.getNumericHost(_host).GetHashCode(); - } - catch(Ice.DNSException) - { - _hashCode = _host.GetHashCode(); - } - _hashCode = 5 * _hashCode + _port; - _hashCode = 5 * _hashCode + _timeout; - _hashCode = 5 * _hashCode + _connectionId.GetHashCode(); - _hashCode = 5 * _hashCode + (_compress? 1 : 0); - } - - private Instance instance_; - private string _host; - private int _port; - private int _timeout; - private string _connectionId = ""; - private bool _compress; - private bool _publish; - private int _hashCode; + if(!_connectionId.Equals(p._connectionId)) + { + return _connectionId.CompareTo(p._connectionId); + } + + if(!_compress && p._compress) + { + return -1; + } + else if(!p._compress && _compress) + { + return 1; + } + + if(!_host.Equals(p._host)) + { + // + // We do the most time-consuming part of the comparison last. + // + System.Net.IPEndPoint laddr = null; + try + { + laddr = Network.getAddress(_host, _port); + } + catch(Ice.DNSException) + { + } + + System.Net.IPEndPoint raddr = null; + try + { + raddr = Network.getAddress(p._host, p._port); + } + catch(Ice.DNSException) + { + } + + if(laddr == null && raddr != null) + { + return -1; + } + else if(raddr == null && laddr != null) + { + return 1; + } + else if(laddr != null && raddr != null) + { + byte[] larr = laddr.Address.GetAddressBytes(); + byte[] rarr = raddr.Address.GetAddressBytes(); + Debug.Assert(larr.Length == rarr.Length); + for(int i = 0; i < larr.Length; i++) + { + if(larr[i] < rarr[i]) + { + return -1; + } + else if(rarr[i] < larr[i]) + { + return 1; + } + } + } + } + + return 0; + } + + private void calcHashValue() + { + try + { + _hashCode = Network.getNumericHost(_host).GetHashCode(); + } + catch(Ice.DNSException) + { + _hashCode = _host.GetHashCode(); + } + _hashCode = 5 * _hashCode + _port; + _hashCode = 5 * _hashCode + _timeout; + _hashCode = 5 * _hashCode + _connectionId.GetHashCode(); + _hashCode = 5 * _hashCode + (_compress? 1 : 0); + } + + private Instance instance_; + private string _host; + private int _port; + private int _timeout; + private string _connectionId = ""; + private bool _compress; + private bool _publish; + private int _hashCode; } sealed class TcpEndpointFactory : EndpointFactory @@ -583,32 +583,32 @@ namespace IceInternal { instance_ = instance; } - + public short type() { return TcpEndpointI.TYPE; } - + public string protocol() { return "tcp"; } - + public EndpointI create(string str) { return new TcpEndpointI(instance_, str); } - + public EndpointI read(BasicStream s) { return new TcpEndpointI(s); } - + public void destroy() { instance_ = null; } - + private Instance instance_; } diff --git a/cs/src/Ice/TcpTransceiver.cs b/cs/src/Ice/TcpTransceiver.cs index 87299b370ff..dbfdb76127d 100755 --- a/cs/src/Ice/TcpTransceiver.cs +++ b/cs/src/Ice/TcpTransceiver.cs @@ -17,246 +17,246 @@ namespace IceInternal sealed class TcpTransceiver : Transceiver { - public Socket fd() - { - Debug.Assert(_fd != null); - return _fd; - } - - public void close() - { - if(_traceLevels.network >= 1) - { - string s = "closing tcp connection\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - lock(this) - { - Debug.Assert(_fd != null); - try - { - _fd.Close(); - } - catch(System.IO.IOException ex) - { - throw new Ice.SocketException(ex); - } - finally - { - _fd = null; - } - } - } + public Socket fd() + { + Debug.Assert(_fd != null); + return _fd; + } + + public void close() + { + if(_traceLevels.network >= 1) + { + string s = "closing tcp connection\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + lock(this) + { + Debug.Assert(_fd != null); + try + { + _fd.Close(); + } + catch(System.IO.IOException ex) + { + throw new Ice.SocketException(ex); + } + finally + { + _fd = null; + } + } + } - public void shutdownWrite() - { - if(_traceLevels.network >= 2) - { - string s = "shutting down tcp connection for writing\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - Debug.Assert(_fd != null); - try - { - _fd.Shutdown(SocketShutdown.Send); - } - catch(SocketException ex) - { - if(Network.notConnected(ex)) - { - return; - } - throw new Ice.SocketException(ex); - } - } + public void shutdownWrite() + { + if(_traceLevels.network >= 2) + { + string s = "shutting down tcp connection for writing\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + Debug.Assert(_fd != null); + try + { + _fd.Shutdown(SocketShutdown.Send); + } + catch(SocketException ex) + { + if(Network.notConnected(ex)) + { + return; + } + throw new Ice.SocketException(ex); + } + } - public void shutdownReadWrite() - { - if(_traceLevels.network >= 2) - { - string s = "shutting down tcp connection for reading and writing\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - Debug.Assert(_fd != null); - try - { - _fd.Shutdown(SocketShutdown.Both); - } - catch(SocketException ex) - { - if(Network.notConnected(ex)) - { - return; - } - throw new Ice.SocketException(ex); - } - } + public void shutdownReadWrite() + { + if(_traceLevels.network >= 2) + { + string s = "shutting down tcp connection for reading and writing\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + Debug.Assert(_fd != null); + try + { + _fd.Shutdown(SocketShutdown.Both); + } + catch(SocketException ex) + { + if(Network.notConnected(ex)) + { + return; + } + throw new Ice.SocketException(ex); + } + } - public void write(BasicStream stream, int timeout) - { - Debug.Assert(_fd != null); + public void write(BasicStream stream, int timeout) + { + Debug.Assert(_fd != null); - ByteBuffer buf = stream.prepareWrite(); - int remaining = buf.remaining(); - int position = buf.position(); - try - { - while(remaining > 0) - { - int ret; - try - { - // - // Try to send first. Most of the time, this will work and - // avoids the cost of calling Poll(). - // - ret = _fd.Send(buf.rawBytes(), position, remaining, SocketFlags.None); - Debug.Assert(ret != 0); - } - catch(Win32Exception e) - { - if(Network.wouldBlock(e)) - { - if(timeout == 0) - { - throw new Ice.TimeoutException(); - } - ret = 0; - } - else - { - throw; - } - } - if(ret == 0) - { - // - // The first attempt to write would have blocked, - // so wait for the socket to become writable now. - // - if(!Network.doPoll(_fd, timeout, Network.PollMode.Write)) - { - throw new Ice.TimeoutException(); - } - ret = _fd.Send(buf.rawBytes(), position, remaining, SocketFlags.None); - Debug.Assert(ret != 0); - } + ByteBuffer buf = stream.prepareWrite(); + int remaining = buf.remaining(); + int position = buf.position(); + try + { + while(remaining > 0) + { + int ret; + try + { + // + // Try to send first. Most of the time, this will work and + // avoids the cost of calling Poll(). + // + ret = _fd.Send(buf.rawBytes(), position, remaining, SocketFlags.None); + Debug.Assert(ret != 0); + } + catch(Win32Exception e) + { + if(Network.wouldBlock(e)) + { + if(timeout == 0) + { + throw new Ice.TimeoutException(); + } + ret = 0; + } + else + { + throw; + } + } + if(ret == 0) + { + // + // The first attempt to write would have blocked, + // so wait for the socket to become writable now. + // + if(!Network.doPoll(_fd, timeout, Network.PollMode.Write)) + { + throw new Ice.TimeoutException(); + } + ret = _fd.Send(buf.rawBytes(), position, remaining, SocketFlags.None); + Debug.Assert(ret != 0); + } - if(_traceLevels.network >= 3) - { - string s = "sent " + ret + " of " + remaining + " bytes via tcp\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - if(_stats != null) - { - _stats.bytesSent(type(), ret); - } + if(_traceLevels.network >= 3) + { + string s = "sent " + ret + " of " + remaining + " bytes via tcp\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + if(_stats != null) + { + _stats.bytesSent(type(), ret); + } - remaining -= ret; - buf.position(position += ret); - } - } - catch(SocketException ex) - { - if(Network.connectionLost(ex)) - { - throw new Ice.ConnectionLostException(ex); - } - if(Network.wouldBlock(ex)) - { - throw new Ice.TimeoutException(); - } - throw new Ice.SocketException(ex); - } - catch(Ice.LocalException) - { - throw; - } - catch(System.Exception ex) - { - throw new Ice.SyscallException(ex); - } - } - - public void read(BasicStream stream, int timeout) - { - Debug.Assert(_fd != null); + remaining -= ret; + buf.position(position += ret); + } + } + catch(SocketException ex) + { + if(Network.connectionLost(ex)) + { + throw new Ice.ConnectionLostException(ex); + } + if(Network.wouldBlock(ex)) + { + throw new Ice.TimeoutException(); + } + throw new Ice.SocketException(ex); + } + catch(Ice.LocalException) + { + throw; + } + catch(System.Exception ex) + { + throw new Ice.SyscallException(ex); + } + } + + public void read(BasicStream stream, int timeout) + { + Debug.Assert(_fd != null); - ByteBuffer buf = stream.prepareRead(); - int remaining = buf.remaining(); - int position = buf.position(); - - try - { - while(remaining > 0) - { - int ret; - try - { - // - // Try to receive first. Much of the time, this will work and we - // avoid the cost of calling Poll(). - // - ret = _fd.Receive(buf.rawBytes(), position, remaining, SocketFlags.None); - if(ret == 0) - { - throw new Ice.ConnectionLostException(); - } - } - catch(Win32Exception e) - { - if(Network.wouldBlock(e)) - { - if(!Network.doPoll(_fd, timeout, Network.PollMode.Read)) - { - throw new Ice.TimeoutException(); - } - continue; - } - throw; - } - if(_traceLevels.network >= 3) - { - string s = "received " + ret + " of " + remaining + " bytes via tcp\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - if(_stats != null) - { - _stats.bytesReceived(type(), ret); - } - remaining -= ret; - buf.position(position += ret); - } - } - catch(SocketException ex) - { - if(Network.connectionLost(ex)) - { - throw new Ice.ConnectionLostException(ex); - } - if(Network.wouldBlock(ex)) - { - throw new Ice.TimeoutException(); - } - throw new Ice.SocketException(ex); - } - catch(Ice.LocalException) - { - throw; - } - catch(System.Exception ex) - { - throw new Ice.SyscallException(ex); - } - } + ByteBuffer buf = stream.prepareRead(); + int remaining = buf.remaining(); + int position = buf.position(); + + try + { + while(remaining > 0) + { + int ret; + try + { + // + // Try to receive first. Much of the time, this will work and we + // avoid the cost of calling Poll(). + // + ret = _fd.Receive(buf.rawBytes(), position, remaining, SocketFlags.None); + if(ret == 0) + { + throw new Ice.ConnectionLostException(); + } + } + catch(Win32Exception e) + { + if(Network.wouldBlock(e)) + { + if(!Network.doPoll(_fd, timeout, Network.PollMode.Read)) + { + throw new Ice.TimeoutException(); + } + continue; + } + throw; + } + if(_traceLevels.network >= 3) + { + string s = "received " + ret + " of " + remaining + " bytes via tcp\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + if(_stats != null) + { + _stats.bytesReceived(type(), ret); + } + remaining -= ret; + buf.position(position += ret); + } + } + catch(SocketException ex) + { + if(Network.connectionLost(ex)) + { + throw new Ice.ConnectionLostException(ex); + } + if(Network.wouldBlock(ex)) + { + throw new Ice.TimeoutException(); + } + throw new Ice.SocketException(ex); + } + catch(Ice.LocalException) + { + throw; + } + catch(System.Exception ex) + { + throw new Ice.SyscallException(ex); + } + } - public string type() - { - return "tcp"; - } + public string type() + { + return "tcp"; + } public void initialize(int timeout) { @@ -270,28 +270,28 @@ namespace IceInternal } } - public override string ToString() - { - return _desc; - } + public override string ToString() + { + return _desc; + } - // - // Only for use by TcpConnector, TcpAcceptor - // - internal TcpTransceiver(Instance instance, Socket fd) - { - _fd = fd; - _traceLevels = instance.traceLevels(); - _logger = instance.initializationData().logger; - _stats = instance.initializationData().stats; - _desc = Network.fdToString(_fd); - } - - private Socket _fd; - private TraceLevels _traceLevels; - private Ice.Logger _logger; - private Ice.Stats _stats; - private string _desc; + // + // Only for use by TcpConnector, TcpAcceptor + // + internal TcpTransceiver(Instance instance, Socket fd) + { + _fd = fd; + _traceLevels = instance.traceLevels(); + _logger = instance.initializationData().logger; + _stats = instance.initializationData().stats; + _desc = Network.fdToString(_fd); + } + + private Socket _fd; + private TraceLevels _traceLevels; + private Ice.Logger _logger; + private Ice.Stats _stats; + private string _desc; } } diff --git a/cs/src/Ice/ThreadPool.cs b/cs/src/Ice/ThreadPool.cs index acf2703f3c3..d803ff6bf18 100755 --- a/cs/src/Ice/ThreadPool.cs +++ b/cs/src/Ice/ThreadPool.cs @@ -31,872 +31,872 @@ namespace IceInternal public sealed class ThreadPool { - public ThreadPool(Instance instance, string prefix, int timeout) - { - instance_ = instance; - _destroyed = false; - _prefix = prefix; - _timeout = timeout; - size_ = 0; - sizeMax_ = 0; - sizeWarn_ = 0; - threadIndex_ = 0; - running_ = 0; - inUse_ = 0; - load_ = 1.0; - promote_ = true; - warnUdp_ = instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; - - string programName = instance_.initializationData().properties.getProperty("Ice.ProgramName"); - if(programName.Length > 0) - { - _programNamePrefix = programName + "-"; - } - else - { - _programNamePrefix = ""; - } - - Network.SocketPair pair = Network.createPipe(); - _fdIntrRead = pair.source; - _fdIntrWrite = pair.sink; - Network.setBlock(_fdIntrRead, false); - - // - // We use just one thread as the default. This is the fastest - // possible setting, still allows one level of nesting, and - // doesn't require to make the servants thread safe. - // - int size = instance_.initializationData().properties.getPropertyAsIntWithDefault(_prefix + ".Size", 1); - if(size < 1) - { - string s = _prefix + ".Size < 1; Size adjusted to 1"; - instance_.initializationData().logger.warning(s); - size = 1; - } - - int sizeMax = - instance_.initializationData().properties.getPropertyAsIntWithDefault(_prefix + ".SizeMax", size); - if(sizeMax < size) - { - string s = _prefix + ".SizeMax < " + _prefix + ".Size; SizeMax adjusted to Size (" + size + ")"; - instance_.initializationData().logger.warning(s); - sizeMax = size; - } - - int sizeWarn = instance_.initializationData().properties.getPropertyAsIntWithDefault(_prefix + ".SizeWarn", - sizeMax * 80 / 100); - if(sizeWarn > sizeMax) - { - string s = _prefix + ".SizeWarn > " + _prefix + ".SizeMax; adjusted SizeWarn to SizeMax (" - + sizeMax + ")"; - instance_.initializationData().logger.warning(s); - sizeWarn = sizeMax; - } - - size_ = size; - sizeMax_ = sizeMax; - sizeWarn_ = sizeWarn; - - try - { - threads_ = new ArrayList(); - for(int i = 0; i < size_; ++i) - { - EventHandlerThread thread = new EventHandlerThread(this, _programNamePrefix + _prefix + "-" + - threadIndex_++); - threads_.Add(thread); - thread.Start(); - ++running_; - } - } - catch(System.Exception ex) - { - string s = "cannot create thread for `" + _prefix + "':\n" + ex; - instance_.initializationData().logger.error(s); - - destroy(); - joinWithAllThreads(); - throw; - } - } - - public void destroy() - { - lock(this) - { - #if TRACE_SHUTDOWN - trace("destroy"); - #endif - - Debug.Assert(!_destroyed); - Debug.Assert(_handlerMap.Count == 0); - Debug.Assert(_changes.Count == 0); - _destroyed = true; - setInterrupt(); - } - } - - public void register(Socket fd, EventHandler handler) - { - lock(this) - { - #if TRACE_REGISTRATION - trace("adding handler of type " + handler.GetType().FullName + " for channel " + fd.Handle); - #endif - Debug.Assert(!_destroyed); - _changes.Add(new FdHandlerPair(fd, handler)); - setInterrupt(); - } - } - - public void unregister(Socket fd) - { - lock(this) - { - #if TRACE_REGISTRATION - #if TRACE_STACK_TRACE - try - { - throw new System.Exception(); - } - catch(System.Exception ex) - { - trace("removing handler for channel " + fd.Handle + "\n" + ex); - } - #else - trace("removing handler for channel " + fd.Handle); - #endif - #endif - - Debug.Assert(!_destroyed); - _changes.Add(new FdHandlerPair(fd, null)); - setInterrupt(); - } - } - - public void promoteFollower() - { - if(sizeMax_ > 1) - { - lock(this) - { - Debug.Assert(!promote_); - promote_ = true; - System.Threading.Monitor.Pulse(this); - - if(!_destroyed) - { - Debug.Assert(inUse_ >= 0); - ++inUse_; - - if(inUse_ == sizeWarn_) - { - string s = "thread pool `" + _prefix + "' is running low on threads\n" - + "Size=" + size_ + ", " + "SizeMax=" + sizeMax_ + ", " - + "SizeWarn=" + sizeWarn_; - instance_.initializationData().logger.warning(s); - } - - Debug.Assert(inUse_ <= running_); - if(inUse_ < sizeMax_ && inUse_ == running_) - { - try - { - EventHandlerThread thread = new EventHandlerThread(this, _programNamePrefix + - _prefix + "-" + threadIndex_++); - threads_.Add(thread); - thread.Start(); - ++running_; - } - catch(System.Exception ex) - { - string s = "cannot create thread for `" + _prefix + "':\n" + ex; - instance_.initializationData().logger.error(s); - } - } - } - } - } - } - - public void joinWithAllThreads() - { - // - // threads_ is immutable after destroy() has been called, - // therefore no synchronization is needed. (Synchronization - // wouldn't be possible here anyway, because otherwise the - // other threads would never terminate.) - // - Debug.Assert(_destroyed); - foreach(EventHandlerThread thread in threads_) - { - while(true) - { - thread.Join(); - break; - } - } - // - // Close the socket pair. - // - try - { - Network.closeSocket(_fdIntrWrite); - Network.closeSocket(_fdIntrRead); - } - catch(System.Exception) - { - } - } - - public string prefix() - { - return _prefix; - } - - private void clearInterrupt() - { - #if TRACE_INTERRUPT - trace("clearInterrupt"); - #if TRACE_STACK_TRACE - try - { - throw new System.Exception(); - } - catch(System.Exception ex) - { - Console.Error.WriteLine(ex); - } - #endif - #endif - - repeat: - try - { - _fdIntrRead.Receive(_intrBuf); - } - catch(SocketException ex) - { - #if TRACE_INTERRUPT - trace("clearInterrupt, handling exception"); - #endif - if(Network.interrupted(ex)) - { - goto repeat; - } - throw new Ice.SocketException("Could not read from interrupt socket", ex); - } - } - - private void setInterrupt() - { - #if TRACE_INTERRUPT - trace("setInterrupt()"); - #if TRACE_STACK_TRACE - try - { - throw new System.Exception(); - } - catch(System.Exception ex) - { - Console.Error.WriteLine(ex); - } - #endif - #endif - - repeat: - try - { - _fdIntrWrite.Send(_intrBuf); - } - catch(SocketException ex) - { - #if TRACE_INTERRUPT - trace("setInterrupt, handling exception"); - #endif - if(Network.interrupted(ex)) - { - goto repeat; - } - throw new Ice.SocketException("Could not write to interrupt socket", ex); - } - } - - private static byte[] _intrBuf = new byte[1]; - - // - // Each thread supplies a BasicStream, to avoid creating excessive - // garbage. - // - private bool run(BasicStream stream) - { - if(sizeMax_ > 1) - { - lock(this) - { - while(!promote_) - { - System.Threading.Monitor.Wait(this); - } - - promote_ = false; - } - - #if TRACE_THREAD - trace("thread " + System.Threading.Thread.CurrentThread.Name + " has the lock"); - #endif - } - - while(true) - { - #if TRACE_REGISTRATION - trace("selecting on " + (_handlerMap.Count + 1) + " channels: "); - trace(_fdIntrRead.Handle.ToString()); - foreach(Socket socket in _handlerMap.Keys) - { - trace(", " + socket.Handle); - } - #endif - - ArrayList readList = new ArrayList(_handlerMap.Count + 1); - readList.Add(_fdIntrRead); - readList.AddRange(_handlerMap.Keys); - - Network.doSelect(readList, null, null, _timeout > 0 ? _timeout * 1000 : -1); - - EventHandler handler = null; - bool finished = false; - bool shutdown = false; - - lock(this) - { - if(readList.Count == 0) // We initiate a shutdown if there is a thread pool timeout. - { - #if TRACE_SELECT - trace("timeout"); - #endif - - Debug.Assert(_timeout > 0); - _timeout = 0; - shutdown = true; - } - else - { - if(readList.Contains(_fdIntrRead)) - { - #if TRACE_SELECT || TRACE_INTERRUPT - trace("detected interrupt"); - #endif - - // - // There are two possibilities for an interrupt: - // - // 1. The thread pool has been destroyed. - // - // 2. An event handler was registered or unregistered. - // - - // - // Thread pool destroyed? - // - if(_destroyed) - { - #if TRACE_SHUTDOWN - trace("destroyed, thread id = " + System.Threading.Thread.CurrentThread.Name); - #endif - - // - // Don't clear the interrupt fd if - // destroyed, so that the other threads - // exit as well. - // - return true; - } - - // - // Remove the interrupt channel from the - // readList. - // - readList.Remove(_fdIntrRead); - - clearInterrupt(); - - // - // An event handler must have been registered - // or unregistered. - // - Debug.Assert(_changes.Count != 0); - LinkedList.Enumerator first = (LinkedList.Enumerator)_changes.GetEnumerator(); - first.MoveNext(); - FdHandlerPair change = (FdHandlerPair)first.Current; - first.Remove(); - if(change.handler != null) // Addition if handler is set. - { - _handlerMap[change.fd] = change.handler; - - #if TRACE_REGISTRATION - trace("added handler (" + change.handler.GetType().FullName + ") for fd " - + change.fd.Handle); - #endif - - continue; - } - else // Removal if handler is not set. - { - handler = (EventHandler)_handlerMap[change.fd]; - _handlerMap.Remove(change.fd); - finished = true; - - #if TRACE_REGISTRATION - trace("removed handler (" + handler.GetType().FullName + ") for fd " - + change.fd.Handle); - #endif - - // Don't continue; we have to call - // finished() on the event handler below, - // outside the thread synchronization. - } - } - else - { - Socket fd = (Socket)readList[0]; - #if TRACE_SELECT - trace("found a readable socket: " + fd.Handle); - #endif - handler = (EventHandler)_handlerMap[fd]; - - if(handler == null) - { - #if TRACE_SELECT - trace("socket " + fd.Handle + " not registered with " + _prefix); - #endif - - continue; - } - } - } - } - - // - // Now we are outside the thread synchronization. - // - - if(shutdown) - { - #if TRACE_SHUTDOWN - trace("shutdown detected"); - #endif - - // - // Initiate server shutdown. - // - ObjectAdapterFactory factory; - try - { - factory = instance_.objectAdapterFactory(); - } - catch(Ice.CommunicatorDestroyedException) - { - continue; - } - - promoteFollower(); - factory.shutdown(); - - // - // No "continue", because we want shutdown to be done in - // its own thread from this pool. Therefore we called - // promoteFollower(); - // - } - else - { - Debug.Assert(handler != null); - - if(finished) - { - // - // Notify a handler about it's removal from - // the thread pool. - // - try - { - handler.finished(this); - } - catch(Ice.LocalException ex) - { - string s = "exception in `" + _prefix + "' while calling finished():\n" - + ex + "\n" + handler.ToString(); - instance_.initializationData().logger.error(s); - } - - // - // No "continue", because we want finished() to be - // called in its own thread from this pool. Note - // that this means that finished() must call - // promoteFollower(). - // - } - else - { - // - // If the handler is "readable", try to read a - // message. - // - try - { - if(handler.readable()) - { - try - { - read(handler); - } - catch(Ice.TimeoutException) // Expected. - { - continue; - } - catch(Ice.DatagramLimitException) // Expected. - { - continue; - } - catch(Ice.SocketException ex) - { - #if TRACE_EXCEPTION - trace("informing handler (" + handler.GetType().FullName + ") about " - + ex.GetType().FullName + " exception " + ex); - #endif - - handler.exception(ex); - continue; - } - catch(Ice.LocalException ex) - { - if(handler.datagram()) - { - if(instance_.initializationData().properties.getPropertyAsInt( - "Ice.Warn.Connections") > 0) - { - instance_.initializationData().logger.warning( - "datagram connection exception:\n" + ex + - handler.ToString()); - } - } - else - { - #if TRACE_EXCEPTION - trace("informing handler (" + handler.GetType().FullName + ") about " - + ex.GetType().FullName + " exception " + ex); - #endif - - handler.exception(ex); - } - continue; - } - - stream.swap(handler.stream_); - Debug.Assert(stream.pos() == stream.size()); - } - - // - // Provide a new message to the handler. - // - try - { - handler.message(stream, this); - } - catch(Ice.LocalException ex) - { - string s = "exception in `" + _prefix + "' while calling message():\n" + ex; - instance_.initializationData().logger.error(s); - } - - // - // No "continue", because we want message() to - // be called in its own thread from this - // pool. Note that this means that message() - // must call promoteFollower(). - // - } - finally - { - stream.reset(); - } - } - } - - if(sizeMax_ > 1) - { - lock(this) - { - if(!_destroyed) - { - // - // First we reap threads that have been - // destroyed before. - // - int sz = threads_.Count; - Debug.Assert(running_ <= sz); - if(running_ < sz) - { - ArrayList liveThreads = new ArrayList(); - foreach(EventHandlerThread thread in threads_) - { - if(!thread.IsAlive()) - { - thread.Join(); - } - else - { - liveThreads.Add(thread); - } - } - threads_ = liveThreads; - } - - // - // Now we check if this thread can be destroyed, based - // on a load factor. - // - - // - // The load factor jumps immediately to the number of - // threads that are currently in use, but decays - // exponentially if the number of threads in use is - // smaller than the load factor. This reflects that we - // create threads immediately when they are needed, - // but want the number of threads to slowly decline to - // the configured minimum. - // - double inUse = (double)inUse_; - if(load_ < inUse) - { - load_ = inUse; - } - else - { - double loadFactor = 0.05; // TODO: Configurable? - double oneMinusLoadFactor = 1 - loadFactor; - load_ = load_ * oneMinusLoadFactor + inUse * loadFactor; - } - - if(running_ > size_) - { - int load = (int)(load_ + 0.5); - - // - // We add one to the load factor because on - // additional thread is needed for select(). - // - if(load + 1 < running_) - { - Debug.Assert(inUse_ > 0); - --inUse_; - - Debug.Assert(running_ > 0); - --running_; - - return false; - } - } - - Debug.Assert(inUse_ > 0); - --inUse_; - } - - while(!promote_) - { - System.Threading.Monitor.Wait(this); - } - - promote_ = false; - } - - #if TRACE_THREAD - trace("thread " + System.Threading.Thread.CurrentThread.Name + " has the lock"); - #endif - } - } - } - - private void read(EventHandler handler) - { - BasicStream stream = handler.stream_; - - if(stream.size() == 0) - { - stream.resize(Protocol.headerSize, true); - stream.pos(0); - } - - if(stream.pos() != stream.size()) - { - handler.read(stream); - Debug.Assert(stream.pos() == stream.size()); - } - - int pos = stream.pos(); - if(pos < Protocol.headerSize) - { - // - // This situation is possible for small UDP packets. - // - throw new Ice.IllegalMessageSizeException(); - } - stream.pos(0); - byte[] m = new byte[4]; - m[0] = stream.readByte(); - m[1] = stream.readByte(); - m[2] = stream.readByte(); - m[3] = stream.readByte(); - if(m[0] != Protocol.magic[0] || m[1] != Protocol.magic[1] || - m[2] != Protocol.magic[2] || m[3] != Protocol.magic[3]) - { - Ice.BadMagicException ex = new Ice.BadMagicException(); - ex.badMagic = m; - throw ex; - } - - byte pMajor = stream.readByte(); - byte pMinor = stream.readByte(); - if(pMajor != Protocol.protocolMajor || pMinor > Protocol.protocolMinor) - { - Ice.UnsupportedProtocolException e = new Ice.UnsupportedProtocolException(); - e.badMajor = pMajor < 0 ? pMajor + 255 : pMajor; - e.badMinor = pMinor < 0 ? pMinor + 255 : pMinor; - e.major = Protocol.protocolMajor; - e.minor = Protocol.protocolMinor; - throw e; - } - - byte eMajor = stream.readByte(); - byte eMinor = stream.readByte(); - if(eMajor != Protocol.encodingMajor || eMinor > Protocol.encodingMinor) - { - Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); - e.badMajor = eMajor < 0 ? eMajor + 255 : eMajor; - e.badMinor = eMinor < 0 ? eMinor + 255 : eMinor; - e.major = Protocol.encodingMajor; - e.minor = Protocol.encodingMinor; - throw e; - } - - stream.readByte(); // Message type. - stream.readByte(); // Compression status. - int size = stream.readInt(); - if(size < Protocol.headerSize) - { - throw new Ice.IllegalMessageSizeException(); - } - if(size > instance_.messageSizeMax()) - { - throw new Ice.MemoryLimitException(); - } - if(size > stream.size()) - { - stream.resize(size, true); - } - stream.pos(pos); - - if(stream.pos() != stream.size()) - { - if(handler.datagram()) - { - if(warnUdp_) - { - instance_.initializationData().logger.warning("DatagramLimitException: maximum size of " + - stream.pos() + " exceeded"); - } - stream.pos(0); - stream.resize(0, true); - throw new Ice.DatagramLimitException(); - } - else - { - handler.read(stream); - Debug.Assert(stream.pos() == stream.size()); - } - } - } - + public ThreadPool(Instance instance, string prefix, int timeout) + { + instance_ = instance; + _destroyed = false; + _prefix = prefix; + _timeout = timeout; + size_ = 0; + sizeMax_ = 0; + sizeWarn_ = 0; + threadIndex_ = 0; + running_ = 0; + inUse_ = 0; + load_ = 1.0; + promote_ = true; + warnUdp_ = instance_.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; + + string programName = instance_.initializationData().properties.getProperty("Ice.ProgramName"); + if(programName.Length > 0) + { + _programNamePrefix = programName + "-"; + } + else + { + _programNamePrefix = ""; + } + + Network.SocketPair pair = Network.createPipe(); + _fdIntrRead = pair.source; + _fdIntrWrite = pair.sink; + Network.setBlock(_fdIntrRead, false); + + // + // We use just one thread as the default. This is the fastest + // possible setting, still allows one level of nesting, and + // doesn't require to make the servants thread safe. + // + int size = instance_.initializationData().properties.getPropertyAsIntWithDefault(_prefix + ".Size", 1); + if(size < 1) + { + string s = _prefix + ".Size < 1; Size adjusted to 1"; + instance_.initializationData().logger.warning(s); + size = 1; + } + + int sizeMax = + instance_.initializationData().properties.getPropertyAsIntWithDefault(_prefix + ".SizeMax", size); + if(sizeMax < size) + { + string s = _prefix + ".SizeMax < " + _prefix + ".Size; SizeMax adjusted to Size (" + size + ")"; + instance_.initializationData().logger.warning(s); + sizeMax = size; + } + + int sizeWarn = instance_.initializationData().properties.getPropertyAsIntWithDefault(_prefix + ".SizeWarn", + sizeMax * 80 / 100); + if(sizeWarn > sizeMax) + { + string s = _prefix + ".SizeWarn > " + _prefix + ".SizeMax; adjusted SizeWarn to SizeMax (" + + sizeMax + ")"; + instance_.initializationData().logger.warning(s); + sizeWarn = sizeMax; + } + + size_ = size; + sizeMax_ = sizeMax; + sizeWarn_ = sizeWarn; + + try + { + threads_ = new ArrayList(); + for(int i = 0; i < size_; ++i) + { + EventHandlerThread thread = new EventHandlerThread(this, _programNamePrefix + _prefix + "-" + + threadIndex_++); + threads_.Add(thread); + thread.Start(); + ++running_; + } + } + catch(System.Exception ex) + { + string s = "cannot create thread for `" + _prefix + "':\n" + ex; + instance_.initializationData().logger.error(s); + + destroy(); + joinWithAllThreads(); + throw; + } + } + + public void destroy() + { + lock(this) + { + #if TRACE_SHUTDOWN + trace("destroy"); + #endif + + Debug.Assert(!_destroyed); + Debug.Assert(_handlerMap.Count == 0); + Debug.Assert(_changes.Count == 0); + _destroyed = true; + setInterrupt(); + } + } + + public void register(Socket fd, EventHandler handler) + { + lock(this) + { + #if TRACE_REGISTRATION + trace("adding handler of type " + handler.GetType().FullName + " for channel " + fd.Handle); + #endif + Debug.Assert(!_destroyed); + _changes.Add(new FdHandlerPair(fd, handler)); + setInterrupt(); + } + } + + public void unregister(Socket fd) + { + lock(this) + { + #if TRACE_REGISTRATION + #if TRACE_STACK_TRACE + try + { + throw new System.Exception(); + } + catch(System.Exception ex) + { + trace("removing handler for channel " + fd.Handle + "\n" + ex); + } + #else + trace("removing handler for channel " + fd.Handle); + #endif + #endif + + Debug.Assert(!_destroyed); + _changes.Add(new FdHandlerPair(fd, null)); + setInterrupt(); + } + } + + public void promoteFollower() + { + if(sizeMax_ > 1) + { + lock(this) + { + Debug.Assert(!promote_); + promote_ = true; + System.Threading.Monitor.Pulse(this); + + if(!_destroyed) + { + Debug.Assert(inUse_ >= 0); + ++inUse_; + + if(inUse_ == sizeWarn_) + { + string s = "thread pool `" + _prefix + "' is running low on threads\n" + + "Size=" + size_ + ", " + "SizeMax=" + sizeMax_ + ", " + + "SizeWarn=" + sizeWarn_; + instance_.initializationData().logger.warning(s); + } + + Debug.Assert(inUse_ <= running_); + if(inUse_ < sizeMax_ && inUse_ == running_) + { + try + { + EventHandlerThread thread = new EventHandlerThread(this, _programNamePrefix + + _prefix + "-" + threadIndex_++); + threads_.Add(thread); + thread.Start(); + ++running_; + } + catch(System.Exception ex) + { + string s = "cannot create thread for `" + _prefix + "':\n" + ex; + instance_.initializationData().logger.error(s); + } + } + } + } + } + } + + public void joinWithAllThreads() + { + // + // threads_ is immutable after destroy() has been called, + // therefore no synchronization is needed. (Synchronization + // wouldn't be possible here anyway, because otherwise the + // other threads would never terminate.) + // + Debug.Assert(_destroyed); + foreach(EventHandlerThread thread in threads_) + { + while(true) + { + thread.Join(); + break; + } + } + // + // Close the socket pair. + // + try + { + Network.closeSocket(_fdIntrWrite); + Network.closeSocket(_fdIntrRead); + } + catch(System.Exception) + { + } + } + + public string prefix() + { + return _prefix; + } + + private void clearInterrupt() + { + #if TRACE_INTERRUPT + trace("clearInterrupt"); + #if TRACE_STACK_TRACE + try + { + throw new System.Exception(); + } + catch(System.Exception ex) + { + Console.Error.WriteLine(ex); + } + #endif + #endif + + repeat: + try + { + _fdIntrRead.Receive(_intrBuf); + } + catch(SocketException ex) + { + #if TRACE_INTERRUPT + trace("clearInterrupt, handling exception"); + #endif + if(Network.interrupted(ex)) + { + goto repeat; + } + throw new Ice.SocketException("Could not read from interrupt socket", ex); + } + } + + private void setInterrupt() + { + #if TRACE_INTERRUPT + trace("setInterrupt()"); + #if TRACE_STACK_TRACE + try + { + throw new System.Exception(); + } + catch(System.Exception ex) + { + Console.Error.WriteLine(ex); + } + #endif + #endif + + repeat: + try + { + _fdIntrWrite.Send(_intrBuf); + } + catch(SocketException ex) + { + #if TRACE_INTERRUPT + trace("setInterrupt, handling exception"); + #endif + if(Network.interrupted(ex)) + { + goto repeat; + } + throw new Ice.SocketException("Could not write to interrupt socket", ex); + } + } + + private static byte[] _intrBuf = new byte[1]; + + // + // Each thread supplies a BasicStream, to avoid creating excessive + // garbage. + // + private bool run(BasicStream stream) + { + if(sizeMax_ > 1) + { + lock(this) + { + while(!promote_) + { + System.Threading.Monitor.Wait(this); + } + + promote_ = false; + } + + #if TRACE_THREAD + trace("thread " + System.Threading.Thread.CurrentThread.Name + " has the lock"); + #endif + } + + while(true) + { + #if TRACE_REGISTRATION + trace("selecting on " + (_handlerMap.Count + 1) + " channels: "); + trace(_fdIntrRead.Handle.ToString()); + foreach(Socket socket in _handlerMap.Keys) + { + trace(", " + socket.Handle); + } + #endif + + ArrayList readList = new ArrayList(_handlerMap.Count + 1); + readList.Add(_fdIntrRead); + readList.AddRange(_handlerMap.Keys); + + Network.doSelect(readList, null, null, _timeout > 0 ? _timeout * 1000 : -1); + + EventHandler handler = null; + bool finished = false; + bool shutdown = false; + + lock(this) + { + if(readList.Count == 0) // We initiate a shutdown if there is a thread pool timeout. + { + #if TRACE_SELECT + trace("timeout"); + #endif + + Debug.Assert(_timeout > 0); + _timeout = 0; + shutdown = true; + } + else + { + if(readList.Contains(_fdIntrRead)) + { + #if TRACE_SELECT || TRACE_INTERRUPT + trace("detected interrupt"); + #endif + + // + // There are two possibilities for an interrupt: + // + // 1. The thread pool has been destroyed. + // + // 2. An event handler was registered or unregistered. + // + + // + // Thread pool destroyed? + // + if(_destroyed) + { + #if TRACE_SHUTDOWN + trace("destroyed, thread id = " + System.Threading.Thread.CurrentThread.Name); + #endif + + // + // Don't clear the interrupt fd if + // destroyed, so that the other threads + // exit as well. + // + return true; + } + + // + // Remove the interrupt channel from the + // readList. + // + readList.Remove(_fdIntrRead); + + clearInterrupt(); + + // + // An event handler must have been registered + // or unregistered. + // + Debug.Assert(_changes.Count != 0); + LinkedList.Enumerator first = (LinkedList.Enumerator)_changes.GetEnumerator(); + first.MoveNext(); + FdHandlerPair change = (FdHandlerPair)first.Current; + first.Remove(); + if(change.handler != null) // Addition if handler is set. + { + _handlerMap[change.fd] = change.handler; + + #if TRACE_REGISTRATION + trace("added handler (" + change.handler.GetType().FullName + ") for fd " + + change.fd.Handle); + #endif + + continue; + } + else // Removal if handler is not set. + { + handler = (EventHandler)_handlerMap[change.fd]; + _handlerMap.Remove(change.fd); + finished = true; + + #if TRACE_REGISTRATION + trace("removed handler (" + handler.GetType().FullName + ") for fd " + + change.fd.Handle); + #endif + + // Don't continue; we have to call + // finished() on the event handler below, + // outside the thread synchronization. + } + } + else + { + Socket fd = (Socket)readList[0]; + #if TRACE_SELECT + trace("found a readable socket: " + fd.Handle); + #endif + handler = (EventHandler)_handlerMap[fd]; + + if(handler == null) + { + #if TRACE_SELECT + trace("socket " + fd.Handle + " not registered with " + _prefix); + #endif + + continue; + } + } + } + } + + // + // Now we are outside the thread synchronization. + // + + if(shutdown) + { + #if TRACE_SHUTDOWN + trace("shutdown detected"); + #endif + + // + // Initiate server shutdown. + // + ObjectAdapterFactory factory; + try + { + factory = instance_.objectAdapterFactory(); + } + catch(Ice.CommunicatorDestroyedException) + { + continue; + } + + promoteFollower(); + factory.shutdown(); + + // + // No "continue", because we want shutdown to be done in + // its own thread from this pool. Therefore we called + // promoteFollower(); + // + } + else + { + Debug.Assert(handler != null); + + if(finished) + { + // + // Notify a handler about it's removal from + // the thread pool. + // + try + { + handler.finished(this); + } + catch(Ice.LocalException ex) + { + string s = "exception in `" + _prefix + "' while calling finished():\n" + + ex + "\n" + handler.ToString(); + instance_.initializationData().logger.error(s); + } + + // + // No "continue", because we want finished() to be + // called in its own thread from this pool. Note + // that this means that finished() must call + // promoteFollower(). + // + } + else + { + // + // If the handler is "readable", try to read a + // message. + // + try + { + if(handler.readable()) + { + try + { + read(handler); + } + catch(Ice.TimeoutException) // Expected. + { + continue; + } + catch(Ice.DatagramLimitException) // Expected. + { + continue; + } + catch(Ice.SocketException ex) + { + #if TRACE_EXCEPTION + trace("informing handler (" + handler.GetType().FullName + ") about " + + ex.GetType().FullName + " exception " + ex); + #endif + + handler.exception(ex); + continue; + } + catch(Ice.LocalException ex) + { + if(handler.datagram()) + { + if(instance_.initializationData().properties.getPropertyAsInt( + "Ice.Warn.Connections") > 0) + { + instance_.initializationData().logger.warning( + "datagram connection exception:\n" + ex + + handler.ToString()); + } + } + else + { + #if TRACE_EXCEPTION + trace("informing handler (" + handler.GetType().FullName + ") about " + + ex.GetType().FullName + " exception " + ex); + #endif + + handler.exception(ex); + } + continue; + } + + stream.swap(handler.stream_); + Debug.Assert(stream.pos() == stream.size()); + } + + // + // Provide a new message to the handler. + // + try + { + handler.message(stream, this); + } + catch(Ice.LocalException ex) + { + string s = "exception in `" + _prefix + "' while calling message():\n" + ex; + instance_.initializationData().logger.error(s); + } + + // + // No "continue", because we want message() to + // be called in its own thread from this + // pool. Note that this means that message() + // must call promoteFollower(). + // + } + finally + { + stream.reset(); + } + } + } + + if(sizeMax_ > 1) + { + lock(this) + { + if(!_destroyed) + { + // + // First we reap threads that have been + // destroyed before. + // + int sz = threads_.Count; + Debug.Assert(running_ <= sz); + if(running_ < sz) + { + ArrayList liveThreads = new ArrayList(); + foreach(EventHandlerThread thread in threads_) + { + if(!thread.IsAlive()) + { + thread.Join(); + } + else + { + liveThreads.Add(thread); + } + } + threads_ = liveThreads; + } + + // + // Now we check if this thread can be destroyed, based + // on a load factor. + // + + // + // The load factor jumps immediately to the number of + // threads that are currently in use, but decays + // exponentially if the number of threads in use is + // smaller than the load factor. This reflects that we + // create threads immediately when they are needed, + // but want the number of threads to slowly decline to + // the configured minimum. + // + double inUse = (double)inUse_; + if(load_ < inUse) + { + load_ = inUse; + } + else + { + double loadFactor = 0.05; // TODO: Configurable? + double oneMinusLoadFactor = 1 - loadFactor; + load_ = load_ * oneMinusLoadFactor + inUse * loadFactor; + } + + if(running_ > size_) + { + int load = (int)(load_ + 0.5); + + // + // We add one to the load factor because on + // additional thread is needed for select(). + // + if(load + 1 < running_) + { + Debug.Assert(inUse_ > 0); + --inUse_; + + Debug.Assert(running_ > 0); + --running_; + + return false; + } + } + + Debug.Assert(inUse_ > 0); + --inUse_; + } + + while(!promote_) + { + System.Threading.Monitor.Wait(this); + } + + promote_ = false; + } + + #if TRACE_THREAD + trace("thread " + System.Threading.Thread.CurrentThread.Name + " has the lock"); + #endif + } + } + } + + private void read(EventHandler handler) + { + BasicStream stream = handler.stream_; + + if(stream.size() == 0) + { + stream.resize(Protocol.headerSize, true); + stream.pos(0); + } + + if(stream.pos() != stream.size()) + { + handler.read(stream); + Debug.Assert(stream.pos() == stream.size()); + } + + int pos = stream.pos(); + if(pos < Protocol.headerSize) + { + // + // This situation is possible for small UDP packets. + // + throw new Ice.IllegalMessageSizeException(); + } + stream.pos(0); + byte[] m = new byte[4]; + m[0] = stream.readByte(); + m[1] = stream.readByte(); + m[2] = stream.readByte(); + m[3] = stream.readByte(); + if(m[0] != Protocol.magic[0] || m[1] != Protocol.magic[1] || + m[2] != Protocol.magic[2] || m[3] != Protocol.magic[3]) + { + Ice.BadMagicException ex = new Ice.BadMagicException(); + ex.badMagic = m; + throw ex; + } + + byte pMajor = stream.readByte(); + byte pMinor = stream.readByte(); + if(pMajor != Protocol.protocolMajor || pMinor > Protocol.protocolMinor) + { + Ice.UnsupportedProtocolException e = new Ice.UnsupportedProtocolException(); + e.badMajor = pMajor < 0 ? pMajor + 255 : pMajor; + e.badMinor = pMinor < 0 ? pMinor + 255 : pMinor; + e.major = Protocol.protocolMajor; + e.minor = Protocol.protocolMinor; + throw e; + } + + byte eMajor = stream.readByte(); + byte eMinor = stream.readByte(); + if(eMajor != Protocol.encodingMajor || eMinor > Protocol.encodingMinor) + { + Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); + e.badMajor = eMajor < 0 ? eMajor + 255 : eMajor; + e.badMinor = eMinor < 0 ? eMinor + 255 : eMinor; + e.major = Protocol.encodingMajor; + e.minor = Protocol.encodingMinor; + throw e; + } + + stream.readByte(); // Message type. + stream.readByte(); // Compression status. + int size = stream.readInt(); + if(size < Protocol.headerSize) + { + throw new Ice.IllegalMessageSizeException(); + } + if(size > instance_.messageSizeMax()) + { + throw new Ice.MemoryLimitException(); + } + if(size > stream.size()) + { + stream.resize(size, true); + } + stream.pos(pos); + + if(stream.pos() != stream.size()) + { + if(handler.datagram()) + { + if(warnUdp_) + { + instance_.initializationData().logger.warning("DatagramLimitException: maximum size of " + + stream.pos() + " exceeded"); + } + stream.pos(0); + stream.resize(0, true); + throw new Ice.DatagramLimitException(); + } + else + { + handler.read(stream); + Debug.Assert(stream.pos() == stream.size()); + } + } + } + /* * Commented out because it is unused. * - private void selectNonBlocking() - { - while(true) - { - #if TRACE_SELECT - trace("non-blocking select on " + _handlerMap.Count + " sockets, thread id = " - + System.Threading.Thread.CurrentThread.Name); - #endif - - ArrayList readList = new ArrayList(_handlerMap.Count + 1); - readList.Add(_fdIntrRead); - readList.AddRange(_handlerMap.Keys); - Network.doSelect(readList, null, null, 0); - - #if TRACE_SELECT - if(readList.Count > 0) - { - trace("after selectNow, there are " + readList.Count + " sockets:"); - foreach(Socket socket in readList) - { - trace(" " + socket); - } - } - #endif - - break; - } - } + private void selectNonBlocking() + { + while(true) + { + #if TRACE_SELECT + trace("non-blocking select on " + _handlerMap.Count + " sockets, thread id = " + + System.Threading.Thread.CurrentThread.Name); + #endif + + ArrayList readList = new ArrayList(_handlerMap.Count + 1); + readList.Add(_fdIntrRead); + readList.AddRange(_handlerMap.Keys); + Network.doSelect(readList, null, null, 0); + + #if TRACE_SELECT + if(readList.Count > 0) + { + trace("after selectNow, there are " + readList.Count + " sockets:"); + foreach(Socket socket in readList) + { + trace(" " + socket); + } + } + #endif + + break; + } + } */ - + /* * Commented out because it is unused. * - private void trace(string msg) - { - System.Console.Error.WriteLine(_prefix + "(" + System.Threading.Thread.CurrentThread.Name + "): " + msg); - } + private void trace(string msg) + { + System.Console.Error.WriteLine(_prefix + "(" + System.Threading.Thread.CurrentThread.Name + "): " + msg); + } */ - - private sealed class FdHandlerPair - { - internal Socket fd; - internal EventHandler handler; - - internal FdHandlerPair(Socket fd, EventHandler handler) - { - this.fd = fd; - this.handler = handler; - } - } - - private Instance instance_; - private bool _destroyed; - private readonly string _prefix; - private readonly string _programNamePrefix; - - private Socket _fdIntrRead; - private Socket _fdIntrWrite; - - private IceUtil.LinkedList _changes = new IceUtil.LinkedList(); - - private Hashtable _handlerMap = new Hashtable(); - - private int _timeout; - - private sealed class EventHandlerThread - { - private ThreadPool thread_Pool; - - internal EventHandlerThread(ThreadPool threadPool, string name) - : base() - { - thread_Pool = threadPool; + + private sealed class FdHandlerPair + { + internal Socket fd; + internal EventHandler handler; + + internal FdHandlerPair(Socket fd, EventHandler handler) + { + this.fd = fd; + this.handler = handler; + } + } + + private Instance instance_; + private bool _destroyed; + private readonly string _prefix; + private readonly string _programNamePrefix; + + private Socket _fdIntrRead; + private Socket _fdIntrWrite; + + private IceUtil.LinkedList _changes = new IceUtil.LinkedList(); + + private Hashtable _handlerMap = new Hashtable(); + + private int _timeout; + + private sealed class EventHandlerThread + { + private ThreadPool thread_Pool; + + internal EventHandlerThread(ThreadPool threadPool, string name) + : base() + { + thread_Pool = threadPool; name_ = name; - } + } public bool IsAlive() { @@ -916,75 +916,75 @@ namespace IceInternal thread_.Start(); } - public void Run() - { - if(thread_Pool.instance_.initializationData().threadHook != null) - { - thread_Pool.instance_.initializationData().threadHook.start(); - } - - BasicStream stream = new BasicStream(thread_Pool.instance_); - - bool promote; - - try - { - promote = thread_Pool.run(stream); - } - catch(Ice.LocalException ex) - { - string s = "exception in `" + thread_Pool._prefix + "' thread " + thread_.Name + ":\n" + ex; - thread_Pool.instance_.initializationData().logger.error(s); - promote = true; - } - catch(System.Exception ex) - { - string s = "unknown exception in `" + thread_Pool._prefix + "' thread " + thread_.Name + ":\n" + ex; - thread_Pool.instance_.initializationData().logger.error(s); - promote = true; - } - - if(promote && thread_Pool.sizeMax_ > 1) - { - // - // Promote a follower, but w/o modifying inUse_ or - // creating new threads. - // - lock(thread_Pool) - { - Debug.Assert(!thread_Pool.promote_); - thread_Pool.promote_ = true; - System.Threading.Monitor.Pulse(thread_Pool); - } - } - - if(thread_Pool.instance_.initializationData().threadHook != null) - { - thread_Pool.instance_.initializationData().threadHook.stop(); - } - - #if TRACE_THREAD - thread_Pool.trace("run() terminated"); - #endif - } + public void Run() + { + if(thread_Pool.instance_.initializationData().threadHook != null) + { + thread_Pool.instance_.initializationData().threadHook.start(); + } + + BasicStream stream = new BasicStream(thread_Pool.instance_); + + bool promote; + + try + { + promote = thread_Pool.run(stream); + } + catch(Ice.LocalException ex) + { + string s = "exception in `" + thread_Pool._prefix + "' thread " + thread_.Name + ":\n" + ex; + thread_Pool.instance_.initializationData().logger.error(s); + promote = true; + } + catch(System.Exception ex) + { + string s = "unknown exception in `" + thread_Pool._prefix + "' thread " + thread_.Name + ":\n" + ex; + thread_Pool.instance_.initializationData().logger.error(s); + promote = true; + } + + if(promote && thread_Pool.sizeMax_ > 1) + { + // + // Promote a follower, but w/o modifying inUse_ or + // creating new threads. + // + lock(thread_Pool) + { + Debug.Assert(!thread_Pool.promote_); + thread_Pool.promote_ = true; + System.Threading.Monitor.Pulse(thread_Pool); + } + } + + if(thread_Pool.instance_.initializationData().threadHook != null) + { + thread_Pool.instance_.initializationData().threadHook.stop(); + } + + #if TRACE_THREAD + thread_Pool.trace("run() terminated"); + #endif + } private string name_; private Thread thread_; - } - - private readonly int size_; // Number of threads that are pre-created. - private readonly int sizeMax_; // Maximum number of threads. - private readonly int sizeWarn_; // If inUse_ reaches sizeWarn_, a "low on threads" warning will be printed. - - private ArrayList threads_; // All threads, running or not. - private int threadIndex_; // For assigning thread names. - private int running_; // Number of running threads. - private int inUse_; // Number of threads that are currently in use. - private double load_; // Current load in number of threads. - - private bool promote_; - - private readonly bool warnUdp_; + } + + private readonly int size_; // Number of threads that are pre-created. + private readonly int sizeMax_; // Maximum number of threads. + private readonly int sizeWarn_; // If inUse_ reaches sizeWarn_, a "low on threads" warning will be printed. + + private ArrayList threads_; // All threads, running or not. + private int threadIndex_; // For assigning thread names. + private int running_; // Number of running threads. + private int inUse_; // Number of threads that are currently in use. + private double load_; // Current load in number of threads. + + private bool promote_; + + private readonly bool warnUdp_; } } diff --git a/cs/src/Ice/TieBase.cs b/cs/src/Ice/TieBase.cs index 4de567266b3..400476d687a 100644 --- a/cs/src/Ice/TieBase.cs +++ b/cs/src/Ice/TieBase.cs @@ -12,8 +12,8 @@ namespace Ice public interface TieBase { - object ice_delegate(); - void ice_delegate(object o); + object ice_delegate(); + void ice_delegate(object o); } } diff --git a/cs/src/Ice/TraceLevels.cs b/cs/src/Ice/TraceLevels.cs index 7432c4afda8..28d3a3b72ef 100755 --- a/cs/src/Ice/TraceLevels.cs +++ b/cs/src/Ice/TraceLevels.cs @@ -12,33 +12,33 @@ namespace IceInternal public sealed class TraceLevels { - internal TraceLevels(Ice.Properties properties) - { - networkCat = "Network"; - protocolCat = "Protocol"; - retryCat = "Retry"; - locationCat = "Location"; - slicingCat = "Slicing"; - - string keyBase = "Ice.Trace."; - - network = properties.getPropertyAsInt(keyBase + networkCat); - protocol = properties.getPropertyAsInt(keyBase + protocolCat); - retry = properties.getPropertyAsInt(keyBase + retryCat); - location = properties.getPropertyAsInt(keyBase + locationCat); - slicing = properties.getPropertyAsInt(keyBase + slicingCat); - } - - public readonly int network; - public readonly string networkCat; - public readonly int protocol; - public readonly string protocolCat; - public readonly int retry; - public readonly string retryCat; - public readonly int location; - public readonly string locationCat; - public readonly int slicing; - public readonly string slicingCat; + internal TraceLevels(Ice.Properties properties) + { + networkCat = "Network"; + protocolCat = "Protocol"; + retryCat = "Retry"; + locationCat = "Location"; + slicingCat = "Slicing"; + + string keyBase = "Ice.Trace."; + + network = properties.getPropertyAsInt(keyBase + networkCat); + protocol = properties.getPropertyAsInt(keyBase + protocolCat); + retry = properties.getPropertyAsInt(keyBase + retryCat); + location = properties.getPropertyAsInt(keyBase + locationCat); + slicing = properties.getPropertyAsInt(keyBase + slicingCat); + } + + public readonly int network; + public readonly string networkCat; + public readonly int protocol; + public readonly string protocolCat; + public readonly int retry; + public readonly string retryCat; + public readonly int location; + public readonly string locationCat; + public readonly int slicing; + public readonly string slicingCat; } } diff --git a/cs/src/Ice/TraceUtil.cs b/cs/src/Ice/TraceUtil.cs index 89eb4b291f1..1532ae7f534 100755 --- a/cs/src/Ice/TraceUtil.cs +++ b/cs/src/Ice/TraceUtil.cs @@ -16,458 +16,458 @@ namespace IceInternal sealed class TraceUtil { - internal static void traceHeader(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) - { - if(tl.protocol >= 1) - { - int p = str.pos(); - str.pos(0); - - using(System.IO.StringWriter s = new System.IO.StringWriter()) - { - s.Write(heading); - printHeader(s, str); - - logger.trace(tl.protocolCat, s.ToString()); - } - str.pos(p); - } - } - - internal static void traceRequest(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) - { - if(tl.protocol >= 1) - { - int p = str.pos(); - str.pos(0); - - using(System.IO.StringWriter s = new System.IO.StringWriter()) - { - s.Write(heading); - printHeader(s, str); - - int requestId = str.readInt(); - s.Write("\nrequest id = " + requestId); - if(requestId == 0) - { - s.Write(" (oneway)"); - } - - printRequestHeader(s, str); - - logger.trace(tl.protocolCat, s.ToString()); - } - str.pos(p); - } - } - - internal static void traceBatchRequest(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) - { - if(tl.protocol >= 1) - { - int p = str.pos(); - str.pos(0); - - using(System.IO.StringWriter s = new System.IO.StringWriter()) - { - s.Write(heading); - printHeader(s, str); - - int batchRequestNum = str.readInt(); - s.Write("\nnumber of requests = " + batchRequestNum); - - for(int i = 0; i < batchRequestNum; ++i) - { - s.Write("\nrequest #" + i + ':'); - printRequestHeader(s, str); - str.skipEncaps(); - } - - logger.trace(tl.protocolCat, s.ToString()); - } - str.pos(p); - } - } - - internal static void traceReply(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) - { - if(tl.protocol >= 1) - { - int p = str.pos(); - str.pos(0); - - using(System.IO.StringWriter s = new System.IO.StringWriter()) - { - s.Write(heading); - printHeader(s, str); - - int requestId = str.readInt(); - s.Write("\nrequest id = " + requestId); - - byte status = str.readByte(); - s.Write("\nreply status = " + (int)status + ' '); - - switch((DispatchStatus)status) - { - case DispatchStatus.DispatchOK: - { - s.Write("(ok)"); - break; - } - - case DispatchStatus.DispatchUserException: - { - s.Write("(user exception)"); - break; - } - - case DispatchStatus.DispatchObjectNotExist: - case DispatchStatus.DispatchFacetNotExist: - case DispatchStatus.DispatchOperationNotExist: - { - switch((DispatchStatus)status) - { - case DispatchStatus.DispatchObjectNotExist: - { - s.Write("(object not exist)"); - break; - } - - case DispatchStatus.DispatchFacetNotExist: - { - s.Write("(facet not exist)"); - break; - } - - case DispatchStatus.DispatchOperationNotExist: - { - s.Write("(operation not exist)"); - break; - } - - default: - { - Debug.Assert(false); - break; - } - } - - printIdentityFacetOperation(s, str); - break; - } - - case DispatchStatus.DispatchUnknownException: - case DispatchStatus.DispatchUnknownLocalException: - case DispatchStatus.DispatchUnknownUserException: - { - switch((DispatchStatus)status) - { - case DispatchStatus.DispatchUnknownException: - { - s.Write("(unknown exception)"); - break; - } - - case DispatchStatus.DispatchUnknownLocalException: - { - s.Write("(unknown local exception)"); - break; - } - - case DispatchStatus.DispatchUnknownUserException: - { - s.Write("(unknown user exception)"); - break; - } - - default: - { - Debug.Assert(false); - break; - } - } - - string unknown = str.readString(); - s.Write("\nunknown = " + unknown); - break; - } - - default: - { - s.Write("(unknown)"); - break; - } - - } - - logger.trace(tl.protocolCat, s.ToString()); - } - str.pos(p); - } - } - - private static Set slicingIds; - - internal static void traceSlicing(string kind, string typeId, string slicingCat, Ice.Logger logger) - { - lock(typeof(IceInternal.TraceUtil)) - { - if(slicingIds.Add(typeId)) - { - using(System.IO.StringWriter s = new System.IO.StringWriter()) - { - s.Write("unknown " + kind + " type `" + typeId + "'"); - logger.trace(slicingCat, s.ToString()); - } - } - } - } - - public static void dumpStream(BasicStream stream) - { - int pos = stream.pos(); - stream.pos(0); - - byte[] data = new byte[stream.size()]; - stream.readBlob(data); - dumpOctets(data); - - stream.pos(pos); - } - - public static void dumpOctets(byte[] data) - { - const int inc = 8; - - for(int i = 0; i < data.Length; i += inc) - { - for(int j = i; j - i < inc; j++) - { - if(j < data.Length) - { - int n = (int)data[j]; - if(n < 0) - { - n += 256; - } - string s; - if(n < 10) - { - s = " " + n; - } - else if(n < 100) - { - s = " " + n; - } - else - { - s = "" + n; - } - System.Console.Out.Write(s + " "); - } - else - { - System.Console.Out.Write(" "); - } - } - - System.Console.Out.Write('"'); - - for(int j = i; j < data.Length && j - i < inc; j++) - { - // TODO: this needs fixing - if(data[j] >= (byte)32 && data[j] < (byte)127) - { - System.Console.Out.Write((char) data[j]); - } - else - { - System.Console.Out.Write('.'); - } - } - - System.Console.Out.WriteLine('"'); - } - } - - private static void printIdentityFacetOperation(System.IO.StringWriter o, BasicStream stream) - { - try - { - Ice.Identity identity = new Ice.Identity(); - identity.read__(stream); - o.Write("\nidentity = " + stream.instance().identityToString(identity)); - - string[] facet = stream.readStringSeq(); - o.Write("\nfacet = "); - if(facet.Length > 0) - { - o.Write(IceUtil.StringUtil.escapeString(facet[0], "")); - } - - string operation = stream.readString(); - o.Write("\noperation = " + operation); - } - catch(System.IO.IOException) - { - Debug.Assert(false); - } - } - - private static void printRequestHeader(System.IO.StringWriter o, BasicStream stream) - { - printIdentityFacetOperation(o, stream); - - try - { - byte mode = stream.readByte(); - o.Write("\nmode = " + (int)mode + ' '); - switch((Ice.OperationMode)mode) - { - case Ice.OperationMode.Normal: - { - o.Write("(normal)"); - break; - } - - case Ice.OperationMode.Nonmutating: - { - o.Write("(nonmutating)"); - break; - } - - case Ice.OperationMode.Idempotent: - { - o.Write("(idempotent)"); - break; - } - - default: - { - o.Write("(unknown)"); - break; - } - } - - int sz = stream.readSize(); - o.Write("\ncontext = "); - while(sz-- > 0) - { - string key = stream.readString(); - string val = stream.readString(); - o.Write(key + '/' + val); - if(sz > 0) - { - o.Write(", "); - } - } - } - catch(System.IO.IOException) - { - Debug.Assert(false); - } - } - - private static void printHeader(System.IO.StringWriter o, BasicStream stream) - { - try - { - stream.readByte(); // Don't bother printing the magic number - stream.readByte(); - stream.readByte(); - stream.readByte(); - - /* byte pMajor = */ stream.readByte(); - /* byte pMinor = */ stream.readByte(); - //o.Write("\nprotocol version = " + (int)pMajor + "." + (int)pMinor); - - /* byte eMajor = */ stream.readByte(); - /* byte eMinor = */ stream.readByte(); - //o.Write("\nencoding version = " + (int)eMajor + "." + (int)eMinor); - - byte type = stream.readByte(); - o.Write("\nmessage type = " + (int)type + ' '); - switch(type) - { - case Protocol.requestMsg: - { - o.Write("(request)"); - break; - } - - case Protocol.requestBatchMsg: - { - o.Write("(batch request)"); - break; - } - - case Protocol.replyMsg: - { - o.Write("(reply)"); - break; - } - - case Protocol.closeConnectionMsg: - { - o.Write("(close connection)"); - break; - } - - case Protocol.validateConnectionMsg: - { - o.Write("(validate connection)"); - break; - } - - default: - { - o.Write("(unknown)"); - break; - } - } - - byte compress = stream.readByte(); - o.Write("\ncompression status = " + (int)compress + ' '); - switch(compress) - { - case (byte)0: - { - o.Write("(not compressed; do not compress response, if any)"); - break; - } - - case (byte)1: - { - o.Write("(not compressed; compress response, if any)"); - break; - } - - case (byte)2: - { - o.Write("(compressed; compress response, if any)"); - break; - } - - default: - { - o.Write("(unknown)"); - break; - } - } - - int size = stream.readInt(); - o.Write("\nmessage size = " + size); - } - catch(System.IO.IOException) - { - Debug.Assert(false); - } - } + internal static void traceHeader(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) + { + if(tl.protocol >= 1) + { + int p = str.pos(); + str.pos(0); + + using(System.IO.StringWriter s = new System.IO.StringWriter()) + { + s.Write(heading); + printHeader(s, str); + + logger.trace(tl.protocolCat, s.ToString()); + } + str.pos(p); + } + } + + internal static void traceRequest(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) + { + if(tl.protocol >= 1) + { + int p = str.pos(); + str.pos(0); + + using(System.IO.StringWriter s = new System.IO.StringWriter()) + { + s.Write(heading); + printHeader(s, str); + + int requestId = str.readInt(); + s.Write("\nrequest id = " + requestId); + if(requestId == 0) + { + s.Write(" (oneway)"); + } + + printRequestHeader(s, str); + + logger.trace(tl.protocolCat, s.ToString()); + } + str.pos(p); + } + } + + internal static void traceBatchRequest(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) + { + if(tl.protocol >= 1) + { + int p = str.pos(); + str.pos(0); + + using(System.IO.StringWriter s = new System.IO.StringWriter()) + { + s.Write(heading); + printHeader(s, str); + + int batchRequestNum = str.readInt(); + s.Write("\nnumber of requests = " + batchRequestNum); + + for(int i = 0; i < batchRequestNum; ++i) + { + s.Write("\nrequest #" + i + ':'); + printRequestHeader(s, str); + str.skipEncaps(); + } + + logger.trace(tl.protocolCat, s.ToString()); + } + str.pos(p); + } + } + + internal static void traceReply(string heading, BasicStream str, Ice.Logger logger, TraceLevels tl) + { + if(tl.protocol >= 1) + { + int p = str.pos(); + str.pos(0); + + using(System.IO.StringWriter s = new System.IO.StringWriter()) + { + s.Write(heading); + printHeader(s, str); + + int requestId = str.readInt(); + s.Write("\nrequest id = " + requestId); + + byte status = str.readByte(); + s.Write("\nreply status = " + (int)status + ' '); + + switch((DispatchStatus)status) + { + case DispatchStatus.DispatchOK: + { + s.Write("(ok)"); + break; + } + + case DispatchStatus.DispatchUserException: + { + s.Write("(user exception)"); + break; + } + + case DispatchStatus.DispatchObjectNotExist: + case DispatchStatus.DispatchFacetNotExist: + case DispatchStatus.DispatchOperationNotExist: + { + switch((DispatchStatus)status) + { + case DispatchStatus.DispatchObjectNotExist: + { + s.Write("(object not exist)"); + break; + } + + case DispatchStatus.DispatchFacetNotExist: + { + s.Write("(facet not exist)"); + break; + } + + case DispatchStatus.DispatchOperationNotExist: + { + s.Write("(operation not exist)"); + break; + } + + default: + { + Debug.Assert(false); + break; + } + } + + printIdentityFacetOperation(s, str); + break; + } + + case DispatchStatus.DispatchUnknownException: + case DispatchStatus.DispatchUnknownLocalException: + case DispatchStatus.DispatchUnknownUserException: + { + switch((DispatchStatus)status) + { + case DispatchStatus.DispatchUnknownException: + { + s.Write("(unknown exception)"); + break; + } + + case DispatchStatus.DispatchUnknownLocalException: + { + s.Write("(unknown local exception)"); + break; + } + + case DispatchStatus.DispatchUnknownUserException: + { + s.Write("(unknown user exception)"); + break; + } + + default: + { + Debug.Assert(false); + break; + } + } + + string unknown = str.readString(); + s.Write("\nunknown = " + unknown); + break; + } + + default: + { + s.Write("(unknown)"); + break; + } + + } + + logger.trace(tl.protocolCat, s.ToString()); + } + str.pos(p); + } + } + + private static Set slicingIds; + + internal static void traceSlicing(string kind, string typeId, string slicingCat, Ice.Logger logger) + { + lock(typeof(IceInternal.TraceUtil)) + { + if(slicingIds.Add(typeId)) + { + using(System.IO.StringWriter s = new System.IO.StringWriter()) + { + s.Write("unknown " + kind + " type `" + typeId + "'"); + logger.trace(slicingCat, s.ToString()); + } + } + } + } + + public static void dumpStream(BasicStream stream) + { + int pos = stream.pos(); + stream.pos(0); + + byte[] data = new byte[stream.size()]; + stream.readBlob(data); + dumpOctets(data); + + stream.pos(pos); + } + + public static void dumpOctets(byte[] data) + { + const int inc = 8; + + for(int i = 0; i < data.Length; i += inc) + { + for(int j = i; j - i < inc; j++) + { + if(j < data.Length) + { + int n = (int)data[j]; + if(n < 0) + { + n += 256; + } + string s; + if(n < 10) + { + s = " " + n; + } + else if(n < 100) + { + s = " " + n; + } + else + { + s = "" + n; + } + System.Console.Out.Write(s + " "); + } + else + { + System.Console.Out.Write(" "); + } + } + + System.Console.Out.Write('"'); + + for(int j = i; j < data.Length && j - i < inc; j++) + { + // TODO: this needs fixing + if(data[j] >= (byte)32 && data[j] < (byte)127) + { + System.Console.Out.Write((char) data[j]); + } + else + { + System.Console.Out.Write('.'); + } + } + + System.Console.Out.WriteLine('"'); + } + } + + private static void printIdentityFacetOperation(System.IO.StringWriter o, BasicStream stream) + { + try + { + Ice.Identity identity = new Ice.Identity(); + identity.read__(stream); + o.Write("\nidentity = " + stream.instance().identityToString(identity)); + + string[] facet = stream.readStringSeq(); + o.Write("\nfacet = "); + if(facet.Length > 0) + { + o.Write(IceUtil.StringUtil.escapeString(facet[0], "")); + } + + string operation = stream.readString(); + o.Write("\noperation = " + operation); + } + catch(System.IO.IOException) + { + Debug.Assert(false); + } + } + + private static void printRequestHeader(System.IO.StringWriter o, BasicStream stream) + { + printIdentityFacetOperation(o, stream); + + try + { + byte mode = stream.readByte(); + o.Write("\nmode = " + (int)mode + ' '); + switch((Ice.OperationMode)mode) + { + case Ice.OperationMode.Normal: + { + o.Write("(normal)"); + break; + } + + case Ice.OperationMode.Nonmutating: + { + o.Write("(nonmutating)"); + break; + } + + case Ice.OperationMode.Idempotent: + { + o.Write("(idempotent)"); + break; + } + + default: + { + o.Write("(unknown)"); + break; + } + } + + int sz = stream.readSize(); + o.Write("\ncontext = "); + while(sz-- > 0) + { + string key = stream.readString(); + string val = stream.readString(); + o.Write(key + '/' + val); + if(sz > 0) + { + o.Write(", "); + } + } + } + catch(System.IO.IOException) + { + Debug.Assert(false); + } + } + + private static void printHeader(System.IO.StringWriter o, BasicStream stream) + { + try + { + stream.readByte(); // Don't bother printing the magic number + stream.readByte(); + stream.readByte(); + stream.readByte(); + + /* byte pMajor = */ stream.readByte(); + /* byte pMinor = */ stream.readByte(); + //o.Write("\nprotocol version = " + (int)pMajor + "." + (int)pMinor); + + /* byte eMajor = */ stream.readByte(); + /* byte eMinor = */ stream.readByte(); + //o.Write("\nencoding version = " + (int)eMajor + "." + (int)eMinor); + + byte type = stream.readByte(); + o.Write("\nmessage type = " + (int)type + ' '); + switch(type) + { + case Protocol.requestMsg: + { + o.Write("(request)"); + break; + } + + case Protocol.requestBatchMsg: + { + o.Write("(batch request)"); + break; + } + + case Protocol.replyMsg: + { + o.Write("(reply)"); + break; + } + + case Protocol.closeConnectionMsg: + { + o.Write("(close connection)"); + break; + } + + case Protocol.validateConnectionMsg: + { + o.Write("(validate connection)"); + break; + } + + default: + { + o.Write("(unknown)"); + break; + } + } + + byte compress = stream.readByte(); + o.Write("\ncompression status = " + (int)compress + ' '); + switch(compress) + { + case (byte)0: + { + o.Write("(not compressed; do not compress response, if any)"); + break; + } + + case (byte)1: + { + o.Write("(not compressed; compress response, if any)"); + break; + } + + case (byte)2: + { + o.Write("(compressed; compress response, if any)"); + break; + } + + default: + { + o.Write("(unknown)"); + break; + } + } + + int size = stream.readInt(); + o.Write("\nmessage size = " + size); + } + catch(System.IO.IOException) + { + Debug.Assert(false); + } + } - static TraceUtil() - { - slicingIds = new Set(); - } + static TraceUtil() + { + slicingIds = new Set(); + } } } diff --git a/cs/src/Ice/Transceiver.cs b/cs/src/Ice/Transceiver.cs index ee30a9cfbca..17437890810 100755 --- a/cs/src/Ice/Transceiver.cs +++ b/cs/src/Ice/Transceiver.cs @@ -12,15 +12,15 @@ namespace IceInternal public interface Transceiver { - System.Net.Sockets.Socket fd(); - void close(); - void shutdownWrite(); - void shutdownReadWrite(); - void write(BasicStream stream, int timeout); - void read(BasicStream stream, int timeout); - string type(); + System.Net.Sockets.Socket fd(); + void close(); + void shutdownWrite(); + void shutdownReadWrite(); + void write(BasicStream stream, int timeout); + void read(BasicStream stream, int timeout); + string type(); void initialize(int timeout); - void checkSendSize(BasicStream stream, int messageSizeMax); + void checkSendSize(BasicStream stream, int messageSizeMax); } } diff --git a/cs/src/Ice/UdpEndpointI.cs b/cs/src/Ice/UdpEndpointI.cs index c7bd3347a43..043ca36e4ba 100755 --- a/cs/src/Ice/UdpEndpointI.cs +++ b/cs/src/Ice/UdpEndpointI.cs @@ -15,490 +15,490 @@ namespace IceInternal sealed class UdpEndpointI : EndpointI { - internal const short TYPE = 3; - - public UdpEndpointI(Instance instance, string ho, int po, bool conn, string conId, bool co, bool pub) - { - instance_ = instance; - _host = ho; - _port = po; - _protocolMajor = Protocol.protocolMajor; - _protocolMinor = Protocol.protocolMinor; - _encodingMajor = Protocol.encodingMajor; - _encodingMinor = Protocol.encodingMinor; - _connect = conn; - _connectionId = conId; - _compress = co; - _publish = pub; - calcHashValue(); - } - - public UdpEndpointI(Instance instance, string str) - { - instance_ = instance; - _host = null; - _port = 0; - _protocolMajor = Protocol.protocolMajor; - _protocolMinor = Protocol.protocolMinor; - _encodingMajor = Protocol.encodingMajor; - _encodingMinor = Protocol.encodingMinor; - _connect = false; - _compress = false; - _publish = true; - - char[] splitChars = { ' ', '\t', '\n', '\r' }; - string[] arr = str.Split(splitChars); - - int i = 0; - while(i < arr.Length) - { - if(arr[i].Length == 0) - { - i++; - continue; - } - - string option = arr[i++]; - if(option.Length != 2 || option[0] != '-') - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - string argument = null; - if(i < arr.Length && arr[i][0] != '-') - { - argument = arr[i++]; - } - - switch(option[1]) - { - case 'v': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - int pos = argument.IndexOf((System.Char) '.'); - if(pos == -1) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - string majStr = argument.Substring(0, (pos) - (0)); - string minStr = argument.Substring(pos + 1, (argument.Length) - (pos + 1)); - int majVersion; - int minVersion; - try - { - majVersion = System.Int32.Parse(majStr); - minVersion = System.Int32.Parse(minStr); - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "udp " + str; - throw e; - } - - if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - if(majVersion != Protocol.protocolMajor) - { - Ice.UnsupportedProtocolException e = new Ice.UnsupportedProtocolException(); - e.badMajor = majVersion < 0?majVersion + 255:majVersion; - e.badMinor = minVersion < 0?minVersion + 255:minVersion; - e.major = Protocol.protocolMajor; - e.minor = Protocol.protocolMinor; - throw e; - } - - _protocolMajor = (byte)majVersion; - _protocolMinor = (byte)minVersion; - - break; - } - - case 'e': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - int pos = argument.IndexOf((System.Char) '.'); - if(pos == -1) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - string majStr = argument.Substring(0, (pos) - (0)); - string minStr = argument.Substring(pos + 1, (argument.Length) - (pos + 1)); - int majVersion; - int minVersion; - try - { - majVersion = System.Int32.Parse(majStr); - minVersion = System.Int32.Parse(minStr); - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "udp " + str; - throw e; - } - - if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - if(majVersion != Protocol.encodingMajor) - { - Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); - e.badMajor = majVersion < 0?majVersion + 255:majVersion; - e.badMinor = minVersion < 0?minVersion + 255:minVersion; - e.major = Protocol.encodingMajor; - e.minor = Protocol.encodingMinor; - throw e; - } - - _encodingMajor = (byte)majVersion; - _encodingMinor = (byte)minVersion; - - break; - } - - case 'h': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - _host = argument; - break; - } - - case 'p': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - try - { - _port = System.Int32.Parse(argument); - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "udp " + str; - throw e; - } + internal const short TYPE = 3; + + public UdpEndpointI(Instance instance, string ho, int po, bool conn, string conId, bool co, bool pub) + { + instance_ = instance; + _host = ho; + _port = po; + _protocolMajor = Protocol.protocolMajor; + _protocolMinor = Protocol.protocolMinor; + _encodingMajor = Protocol.encodingMajor; + _encodingMinor = Protocol.encodingMinor; + _connect = conn; + _connectionId = conId; + _compress = co; + _publish = pub; + calcHashValue(); + } + + public UdpEndpointI(Instance instance, string str) + { + instance_ = instance; + _host = null; + _port = 0; + _protocolMajor = Protocol.protocolMajor; + _protocolMinor = Protocol.protocolMinor; + _encodingMajor = Protocol.encodingMajor; + _encodingMinor = Protocol.encodingMinor; + _connect = false; + _compress = false; + _publish = true; + + char[] splitChars = { ' ', '\t', '\n', '\r' }; + string[] arr = str.Split(splitChars); + + int i = 0; + while(i < arr.Length) + { + if(arr[i].Length == 0) + { + i++; + continue; + } + + string option = arr[i++]; + if(option.Length != 2 || option[0] != '-') + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + string argument = null; + if(i < arr.Length && arr[i][0] != '-') + { + argument = arr[i++]; + } + + switch(option[1]) + { + case 'v': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + int pos = argument.IndexOf((System.Char) '.'); + if(pos == -1) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + string majStr = argument.Substring(0, (pos) - (0)); + string minStr = argument.Substring(pos + 1, (argument.Length) - (pos + 1)); + int majVersion; + int minVersion; + try + { + majVersion = System.Int32.Parse(majStr); + minVersion = System.Int32.Parse(minStr); + } + catch(System.FormatException ex) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(ex); + e.str = "udp " + str; + throw e; + } + + if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + if(majVersion != Protocol.protocolMajor) + { + Ice.UnsupportedProtocolException e = new Ice.UnsupportedProtocolException(); + e.badMajor = majVersion < 0?majVersion + 255:majVersion; + e.badMinor = minVersion < 0?minVersion + 255:minVersion; + e.major = Protocol.protocolMajor; + e.minor = Protocol.protocolMinor; + throw e; + } + + _protocolMajor = (byte)majVersion; + _protocolMinor = (byte)minVersion; + + break; + } + + case 'e': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + int pos = argument.IndexOf((System.Char) '.'); + if(pos == -1) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + string majStr = argument.Substring(0, (pos) - (0)); + string minStr = argument.Substring(pos + 1, (argument.Length) - (pos + 1)); + int majVersion; + int minVersion; + try + { + majVersion = System.Int32.Parse(majStr); + minVersion = System.Int32.Parse(minStr); + } + catch(System.FormatException ex) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(ex); + e.str = "udp " + str; + throw e; + } + + if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + if(majVersion != Protocol.encodingMajor) + { + Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); + e.badMajor = majVersion < 0?majVersion + 255:majVersion; + e.badMinor = minVersion < 0?minVersion + 255:minVersion; + e.major = Protocol.encodingMajor; + e.minor = Protocol.encodingMinor; + throw e; + } + + _encodingMajor = (byte)majVersion; + _encodingMinor = (byte)minVersion; + + break; + } + + case 'h': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + _host = argument; + break; + } + + case 'p': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + try + { + _port = System.Int32.Parse(argument); + } + catch(System.FormatException ex) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(ex); + e.str = "udp " + str; + throw e; + } - if(_port < 0 || _port > 65535) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - break; - } - - case 'c': - { - if(argument != null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - _connect = true; - break; - } - - case 'z': - { - if(argument != null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - - _compress = true; - break; - } - - default: - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "udp " + str; - throw e; - } - } - } - } - - public UdpEndpointI(BasicStream s) - { - instance_ = s.instance(); - s.startReadEncaps(); - _host = s.readString(); - _port = s.readInt(); - _protocolMajor = s.readByte(); - _protocolMinor = s.readByte(); - _encodingMajor = s.readByte(); - _encodingMinor = s.readByte(); - if(_protocolMajor != Protocol.protocolMajor) - { - Ice.UnsupportedProtocolException e = new Ice.UnsupportedProtocolException(); - e.badMajor = _protocolMajor < 0?_protocolMajor + 255:_protocolMajor; - e.badMinor = _protocolMinor < 0?_protocolMinor + 255:_protocolMinor; - e.major = Protocol.protocolMajor; - e.minor = Protocol.protocolMinor; - throw e; - } - if(_encodingMajor != Protocol.encodingMajor) - { - Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); - e.badMajor = _encodingMajor < 0?_encodingMajor + 255:_encodingMajor; - e.badMinor = _encodingMinor < 0?_encodingMinor + 255:_encodingMinor; - e.major = Protocol.encodingMajor; - e.minor = Protocol.encodingMinor; - throw e; - } - // Not transmitted. - //_connect = s.readBool(); - _connect = false; - _compress = s.readBool(); - s.endReadEncaps(); - _publish = true; - calcHashValue(); - } - - // - // Marshal the endpoint - // - public override void streamWrite(BasicStream s) - { - s.writeShort(TYPE); - s.startWriteEncaps(); - s.writeString(_host); - s.writeInt(_port); - s.writeByte(_protocolMajor); - s.writeByte(_protocolMinor); - s.writeByte(_encodingMajor); - s.writeByte(_encodingMinor); - // Not transmitted. - //s.writeBool(_connect); - s.writeBool(_compress); - s.endWriteEncaps(); - } - - // - // Convert the endpoint to its string form - // - public override string ice_toString_() - { - // - // WARNING: Certain features, such as proxy validation in Glacier2, - // depend on the format of proxy strings. Changes to toString() and - // methods called to generate parts of the reference string could break - // these features. Please review for all features that depend on the - // format of proxyToString() before changing this and related code. - // - string s = "udp"; + if(_port < 0 || _port > 65535) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + break; + } + + case 'c': + { + if(argument != null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + _connect = true; + break; + } + + case 'z': + { + if(argument != null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + + _compress = true; + break; + } + + default: + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "udp " + str; + throw e; + } + } + } + } + + public UdpEndpointI(BasicStream s) + { + instance_ = s.instance(); + s.startReadEncaps(); + _host = s.readString(); + _port = s.readInt(); + _protocolMajor = s.readByte(); + _protocolMinor = s.readByte(); + _encodingMajor = s.readByte(); + _encodingMinor = s.readByte(); + if(_protocolMajor != Protocol.protocolMajor) + { + Ice.UnsupportedProtocolException e = new Ice.UnsupportedProtocolException(); + e.badMajor = _protocolMajor < 0?_protocolMajor + 255:_protocolMajor; + e.badMinor = _protocolMinor < 0?_protocolMinor + 255:_protocolMinor; + e.major = Protocol.protocolMajor; + e.minor = Protocol.protocolMinor; + throw e; + } + if(_encodingMajor != Protocol.encodingMajor) + { + Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException(); + e.badMajor = _encodingMajor < 0?_encodingMajor + 255:_encodingMajor; + e.badMinor = _encodingMinor < 0?_encodingMinor + 255:_encodingMinor; + e.major = Protocol.encodingMajor; + e.minor = Protocol.encodingMinor; + throw e; + } + // Not transmitted. + //_connect = s.readBool(); + _connect = false; + _compress = s.readBool(); + s.endReadEncaps(); + _publish = true; + calcHashValue(); + } + + // + // Marshal the endpoint + // + public override void streamWrite(BasicStream s) + { + s.writeShort(TYPE); + s.startWriteEncaps(); + s.writeString(_host); + s.writeInt(_port); + s.writeByte(_protocolMajor); + s.writeByte(_protocolMinor); + s.writeByte(_encodingMajor); + s.writeByte(_encodingMinor); + // Not transmitted. + //s.writeBool(_connect); + s.writeBool(_compress); + s.endWriteEncaps(); + } + + // + // Convert the endpoint to its string form + // + public override string ice_toString_() + { + // + // WARNING: Certain features, such as proxy validation in Glacier2, + // depend on the format of proxy strings. Changes to toString() and + // methods called to generate parts of the reference string could break + // these features. Please review for all features that depend on the + // format of proxyToString() before changing this and related code. + // + string s = "udp"; - if((int)_protocolMajor != 1 || (int)_protocolMinor != 0) - { - s += " -v " + (_protocolMajor < 0 ? (int)_protocolMajor + 255 : _protocolMajor); - s += "." + (_protocolMinor < 0 ? (int)_protocolMinor + 255 : _protocolMinor); - } + if((int)_protocolMajor != 1 || (int)_protocolMinor != 0) + { + s += " -v " + (_protocolMajor < 0 ? (int)_protocolMajor + 255 : _protocolMajor); + s += "." + (_protocolMinor < 0 ? (int)_protocolMinor + 255 : _protocolMinor); + } - if((int)_encodingMajor != 1 || (int)_encodingMinor != 0) - { - s += " -e " + (_encodingMajor < 0 ? (int)_encodingMajor + 255 : _encodingMajor); - s += "." + (_encodingMinor < 0 ? (int)_encodingMinor + 255 : _encodingMinor); - } + if((int)_encodingMajor != 1 || (int)_encodingMinor != 0) + { + s += " -e " + (_encodingMajor < 0 ? (int)_encodingMajor + 255 : _encodingMajor); + s += "." + (_encodingMinor < 0 ? (int)_encodingMinor + 255 : _encodingMinor); + } - s += " -h " + _host + " -p " + _port; + s += " -h " + _host + " -p " + _port; - if(_connect) - { - s += " -c"; - } + if(_connect) + { + s += " -c"; + } - if(_compress) - { - s += " -z"; - } + if(_compress) + { + s += " -z"; + } - return s; - } - - // - // Return the endpoint type - // - public override short type() - { - return TYPE; - } - - // - // Return the timeout for the endpoint in milliseconds. 0 means - // non-blocking, -1 means no timeout. - // - public override int timeout() - { - return -1; - } - - // - // Return true if the endpoints support bzip2 compress, or false - // otherwise. - // - public override bool compress() - { - return _compress; - } - - // - // Return a new endpoint with a different compression value, - // provided that compression is supported by the - // endpoint. Otherwise the same endpoint is returned. - // - public override EndpointI compress(bool compress) - { - if(compress == _compress) - { - return this; - } - else - { - return new UdpEndpointI(instance_, _host, _port, _connect, _connectionId, compress, _publish); - } - } + return s; + } + + // + // Return the endpoint type + // + public override short type() + { + return TYPE; + } + + // + // Return the timeout for the endpoint in milliseconds. 0 means + // non-blocking, -1 means no timeout. + // + public override int timeout() + { + return -1; + } + + // + // Return true if the endpoints support bzip2 compress, or false + // otherwise. + // + public override bool compress() + { + return _compress; + } + + // + // Return a new endpoint with a different compression value, + // provided that compression is supported by the + // endpoint. Otherwise the same endpoint is returned. + // + public override EndpointI compress(bool compress) + { + if(compress == _compress) + { + return this; + } + else + { + return new UdpEndpointI(instance_, _host, _port, _connect, _connectionId, compress, _publish); + } + } - // - // Return a new endpoint with a different connection id. - // - public override EndpointI connectionId(string connectionId) - { - if(connectionId == _connectionId) - { - return this; - } - else - { - return new UdpEndpointI(instance_, _host, _port, _connect, connectionId, _compress, _publish); - } - } - - // - // Return a new endpoint with a different timeout value, provided - // that timeouts are supported by the endpoint. Otherwise the same - // endpoint is returned. - // - public override EndpointI timeout(int timeout) - { - return this; - } - - // - // Return true if the endpoint is datagram-based. - // - public override bool datagram() - { - return true; - } - - // - // Return true if the endpoint is secure. - // - public override bool secure() - { - return false; - } - - // - // Return true if the endpoint type is unknown. - // - public override bool unknown() - { - return false; - } - - // - // Return a client side transceiver for this endpoint, or null if a - // transceiver can only be created by a connector. - // - public override Transceiver clientTransceiver() - { - return new UdpTransceiver(instance_, _host, _port); - } - - // - // Return a server side transceiver for this endpoint, or null if a - // transceiver can only be created by an acceptor. In case a - // transceiver is created, this operation also returns a new - // "effective" endpoint, which might differ from this endpoint, - // for example, if a dynamic port number is assigned. - // - public override Transceiver serverTransceiver(ref EndpointI endpoint) - { - UdpTransceiver p = new UdpTransceiver(instance_, _host, _port, _connect); - endpoint = new UdpEndpointI(instance_, _host, p.effectivePort(), _connect, _connectionId, _compress, - _publish); - return p; - } - - // - // Return a connector for this endpoint, or null if no connector - // is available. - // - public override Connector connector() - { - return null; - } - - // - // Return an acceptor for this endpoint, or null if no acceptors - // is available. In case an acceptor is created, this operation - // also returns a new "effective" endpoint, which might differ - // from this endpoint, for example, if a dynamic port number is - // assigned. - // - public override Acceptor acceptor(ref EndpointI endpoint, string adapterName) - { - endpoint = this; - return null; - } + // + // Return a new endpoint with a different connection id. + // + public override EndpointI connectionId(string connectionId) + { + if(connectionId == _connectionId) + { + return this; + } + else + { + return new UdpEndpointI(instance_, _host, _port, _connect, connectionId, _compress, _publish); + } + } + + // + // Return a new endpoint with a different timeout value, provided + // that timeouts are supported by the endpoint. Otherwise the same + // endpoint is returned. + // + public override EndpointI timeout(int timeout) + { + return this; + } + + // + // Return true if the endpoint is datagram-based. + // + public override bool datagram() + { + return true; + } + + // + // Return true if the endpoint is secure. + // + public override bool secure() + { + return false; + } + + // + // Return true if the endpoint type is unknown. + // + public override bool unknown() + { + return false; + } + + // + // Return a client side transceiver for this endpoint, or null if a + // transceiver can only be created by a connector. + // + public override Transceiver clientTransceiver() + { + return new UdpTransceiver(instance_, _host, _port); + } + + // + // Return a server side transceiver for this endpoint, or null if a + // transceiver can only be created by an acceptor. In case a + // transceiver is created, this operation also returns a new + // "effective" endpoint, which might differ from this endpoint, + // for example, if a dynamic port number is assigned. + // + public override Transceiver serverTransceiver(ref EndpointI endpoint) + { + UdpTransceiver p = new UdpTransceiver(instance_, _host, _port, _connect); + endpoint = new UdpEndpointI(instance_, _host, p.effectivePort(), _connect, _connectionId, _compress, + _publish); + return p; + } + + // + // Return a connector for this endpoint, or null if no connector + // is available. + // + public override Connector connector() + { + return null; + } + + // + // Return an acceptor for this endpoint, or null if no acceptors + // is available. In case an acceptor is created, this operation + // also returns a new "effective" endpoint, which might differ + // from this endpoint, for example, if a dynamic port number is + // assigned. + // + public override Acceptor acceptor(ref EndpointI endpoint, string adapterName) + { + endpoint = this; + return null; + } // // Expand endpoint out in to separate endpoints for each local @@ -508,26 +508,26 @@ namespace IceInternal public override ArrayList expand(bool server) { - if(_host == null) - { - _host = instance_.defaultsAndOverrides().defaultHost; - if(_host == null) - { - if(server) - { + if(_host == null) + { + _host = instance_.defaultsAndOverrides().defaultHost; + if(_host == null) + { + if(server) + { _host = "0.0.0.0"; - } - else - { + } + else + { _host = "127.0.0.1"; - } - } - } - else if(_host.Equals("*")) - { - _host = "0.0.0.0"; - } - + } + } + } + else if(_host.Equals("*")) + { + _host = "0.0.0.0"; + } + ArrayList endps = new ArrayList(); if(_host.Equals("0.0.0.0")) { @@ -540,7 +540,7 @@ namespace IceInternal } else { - calcHashValue(); + calcHashValue(); endps.Add(this); } return endps; @@ -555,189 +555,189 @@ namespace IceInternal { return _publish; } - - // - // Check whether the endpoint is equivalent to a specific - // Transceiver or Acceptor - // - public override bool equivalent(Transceiver transceiver) - { - UdpTransceiver udpTransceiver = null; - try - { - udpTransceiver = (UdpTransceiver) transceiver; - } - catch(System.InvalidCastException) - { - return false; - } - return udpTransceiver.equivalent(_host, _port); - } - - public override bool equivalent(Acceptor acceptor) - { - return false; - } + + // + // Check whether the endpoint is equivalent to a specific + // Transceiver or Acceptor + // + public override bool equivalent(Transceiver transceiver) + { + UdpTransceiver udpTransceiver = null; + try + { + udpTransceiver = (UdpTransceiver) transceiver; + } + catch(System.InvalidCastException) + { + return false; + } + return udpTransceiver.equivalent(_host, _port); + } + + public override bool equivalent(Acceptor acceptor) + { + return false; + } public override bool requiresThreadPerConnection() { return false; } - public override int GetHashCode() - { - return _hashCode; - } - - // - // Compare endpoints for sorting purposes - // - public override bool Equals(object obj) - { - return CompareTo(obj) == 0; - } - - public override int CompareTo(object obj) - { - UdpEndpointI p = null; - - try - { - p = (UdpEndpointI) obj; - } - catch(System.InvalidCastException) - { - return 1; - } - - if(this == p) - { - return 0; - } - - if(_port < p._port) - { - return -1; - } - else if(p._port < _port) - { - return 1; - } - - if(!_connect && p._connect) - { - return -1; - } - else if(!p._connect && _connect) - { - return 1; - } - - if(!_connectionId.Equals(p._connectionId)) - { - return _connectionId.CompareTo(p._connectionId); - } + public override int GetHashCode() + { + return _hashCode; + } + + // + // Compare endpoints for sorting purposes + // + public override bool Equals(object obj) + { + return CompareTo(obj) == 0; + } + + public override int CompareTo(object obj) + { + UdpEndpointI p = null; + + try + { + p = (UdpEndpointI) obj; + } + catch(System.InvalidCastException) + { + return 1; + } + + if(this == p) + { + return 0; + } + + if(_port < p._port) + { + return -1; + } + else if(p._port < _port) + { + return 1; + } + + if(!_connect && p._connect) + { + return -1; + } + else if(!p._connect && _connect) + { + return 1; + } + + if(!_connectionId.Equals(p._connectionId)) + { + return _connectionId.CompareTo(p._connectionId); + } - if(!_compress && p._compress) - { - return -1; - } - else if(!p._compress && _compress) - { - return 1; - } - - if(_protocolMajor < p._protocolMajor) - { - return -1; - } - else if(p._protocolMajor < _protocolMajor) - { - return 1; - } - - if(_protocolMinor < p._protocolMinor) - { - return -1; - } - else if(p._protocolMinor < _protocolMinor) - { - return 1; - } - - if(_encodingMajor < p._encodingMajor) - { - return -1; - } - else if(p._encodingMajor < _encodingMajor) - { - return 1; - } - - if(_encodingMinor < p._encodingMinor) - { - return -1; - } - else if(p._encodingMinor < _encodingMinor) - { - return 1; - } - - if(!_host.Equals(p._host)) - { - // - // We do the most time-consuming part of the comparison last. - // - System.Net.IPEndPoint laddr = null; - try - { - laddr = Network.getAddress(_host, _port); - } - catch(Ice.DNSException) - { - } - - System.Net.IPEndPoint raddr = null; - try - { - raddr = Network.getAddress(p._host, p._port); - } - catch(Ice.DNSException) - { - } - - if(laddr == null && raddr != null) - { - return -1; - } - else if(raddr == null && laddr != null) - { - return 1; - } - else if(laddr != null && raddr != null) - { - byte[] larr = laddr.Address.GetAddressBytes(); - byte[] rarr = raddr.Address.GetAddressBytes(); - Debug.Assert(larr.Length == rarr.Length); - for(int i = 0; i < larr.Length; i++) - { - if(larr[i] < rarr[i]) - { - return -1; - } - else if(rarr[i] < larr[i]) - { - return 1; - } - } - } - } - - return 0; - } - - private void calcHashValue() - { + if(!_compress && p._compress) + { + return -1; + } + else if(!p._compress && _compress) + { + return 1; + } + + if(_protocolMajor < p._protocolMajor) + { + return -1; + } + else if(p._protocolMajor < _protocolMajor) + { + return 1; + } + + if(_protocolMinor < p._protocolMinor) + { + return -1; + } + else if(p._protocolMinor < _protocolMinor) + { + return 1; + } + + if(_encodingMajor < p._encodingMajor) + { + return -1; + } + else if(p._encodingMajor < _encodingMajor) + { + return 1; + } + + if(_encodingMinor < p._encodingMinor) + { + return -1; + } + else if(p._encodingMinor < _encodingMinor) + { + return 1; + } + + if(!_host.Equals(p._host)) + { + // + // We do the most time-consuming part of the comparison last. + // + System.Net.IPEndPoint laddr = null; + try + { + laddr = Network.getAddress(_host, _port); + } + catch(Ice.DNSException) + { + } + + System.Net.IPEndPoint raddr = null; + try + { + raddr = Network.getAddress(p._host, p._port); + } + catch(Ice.DNSException) + { + } + + if(laddr == null && raddr != null) + { + return -1; + } + else if(raddr == null && laddr != null) + { + return 1; + } + else if(laddr != null && raddr != null) + { + byte[] larr = laddr.Address.GetAddressBytes(); + byte[] rarr = raddr.Address.GetAddressBytes(); + Debug.Assert(larr.Length == rarr.Length); + for(int i = 0; i < larr.Length; i++) + { + if(larr[i] < rarr[i]) + { + return -1; + } + else if(rarr[i] < larr[i]) + { + return 1; + } + } + } + } + + return 0; + } + + private void calcHashValue() + { try { _hashCode = Network.getNumericHost(_host).GetHashCode(); @@ -746,24 +746,24 @@ namespace IceInternal { _hashCode = _host.GetHashCode(); } - _hashCode = 5 * _hashCode + _port; - _hashCode = 5 * _hashCode + (_connect?1:0); - _hashCode = 5 * _hashCode + _connectionId.GetHashCode(); - _hashCode = 5 * _hashCode + (_compress?1:0); - } - - private Instance instance_; - private string _host; - private int _port; - private byte _protocolMajor; - private byte _protocolMinor; - private byte _encodingMajor; - private byte _encodingMinor; - private bool _connect; - private string _connectionId = ""; - private bool _compress; - private bool _publish; - private int _hashCode; + _hashCode = 5 * _hashCode + _port; + _hashCode = 5 * _hashCode + (_connect?1:0); + _hashCode = 5 * _hashCode + _connectionId.GetHashCode(); + _hashCode = 5 * _hashCode + (_compress?1:0); + } + + private Instance instance_; + private string _host; + private int _port; + private byte _protocolMajor; + private byte _protocolMinor; + private byte _encodingMajor; + private byte _encodingMinor; + private bool _connect; + private string _connectionId = ""; + private bool _compress; + private bool _publish; + private int _hashCode; } sealed class UdpEndpointFactory : EndpointFactory @@ -772,32 +772,32 @@ namespace IceInternal { instance_ = instance; } - + public short type() { return UdpEndpointI.TYPE; } - + public string protocol() { return "udp"; } - + public EndpointI create(string str) { return new UdpEndpointI(instance_, str); } - + public EndpointI read(BasicStream s) { return new UdpEndpointI(s); } - + public void destroy() { instance_ = null; } - + private Instance instance_; } diff --git a/cs/src/Ice/UdpTransceiver.cs b/cs/src/Ice/UdpTransceiver.cs index ac183d5f0a0..a1ed731ff4f 100755 --- a/cs/src/Ice/UdpTransceiver.cs +++ b/cs/src/Ice/UdpTransceiver.cs @@ -19,403 +19,403 @@ namespace IceInternal sealed class UdpTransceiver : Transceiver { - public Socket fd() - { - Debug.Assert(_fd != null); - return _fd; - } - - public void close() - { - lock(this) - { - if(_traceLevels.network >= 1) - { - string s = "closing udp connection\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - if(_fd != null) - { - try - { - _fd.Close(); - } - catch(System.IO.IOException) - { - } - _fd = null; - } - } - } - - public void shutdownWrite() - { - } - - public void shutdownReadWrite() - { - if(_traceLevels.network >= 2) - { - string s = "shutting down udp connection for reading and writing\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - // - // Set a flag and then shutdown the socket in order to wake a thread that is - // blocked in read(). - // - lock(_shutdownReadWriteMutex) - { - _shutdownReadWrite = true; - - Debug.Assert(_fd != null); - try - { - _fd.Shutdown(SocketShutdown.Both); - } - catch(SocketException ex) - { - if(Network.notConnected(ex)) - { - return; - } - throw new Ice.SocketException(ex); - } - - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) - { - // - // On Windows, shutting down the socket doesn't unblock a call to - // receive or select. Setting an event wakes up the thread in - // read(). - // - _shutdownReadWriteEvent.Set(); - } - } - } - - public void write(BasicStream stream, int timeout) - { - Debug.Assert(_fd != null); - - ByteBuffer buf = stream.prepareWrite(); - - Debug.Assert(buf.position() == 0); - int packetSize = System.Math.Min(_maxPacketSize, _sndSize - _udpOverhead); - if(packetSize < buf.limit()) - { - // - // We don't log a warning here because the client gets an exception anyway. - // - throw new Ice.DatagramLimitException(); - } - - try - { - int remaining = buf.remaining(); - int ret; - try - { - ret = _fd.Send(buf.rawBytes(), 0, remaining, SocketFlags.None); - } - catch(Win32Exception e) - { - if(Network.wouldBlock(e)) - { - if(timeout == 0) - { - throw new Ice.TimeoutException(); - } - ret = 0; - } - else - { - throw; - } - } - if(ret == 0) - { - if(!Network.doPoll(_fd, timeout, Network.PollMode.Write)) - { - throw new Ice.TimeoutException(); - } - ret = _fd.Send(buf.rawBytes(), 0, remaining, SocketFlags.None); - } - if(ret != remaining) - { - throw new Ice.DatagramLimitException(); - } - - if(_traceLevels.network >= 3) - { - string s = "sent " + ret + " bytes via udp\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - if(_stats != null) - { - _stats.bytesSent(type(), ret); - } - - buf.position(remaining); - } - catch(SocketException ex) - { - throw new Ice.SocketException(ex); - } - catch(Ice.LocalException) - { - throw; - } - catch(System.Exception ex) - { - throw new Ice.SyscallException(ex); - } - } - - public void read(BasicStream stream, int timeout) - { - Debug.Assert(stream.pos() == 0); - - int packetSize = System.Math.Min(_maxPacketSize, _rcvSize - _udpOverhead); - if(packetSize < stream.size()) - { - // - // We log a warning here because this is the server side -- without the - // the warning, there would only be silence. - // - if(_warn) - { - _logger.warning("DatagramLimitException: maximum size of " + packetSize + " exceeded"); - } - throw new Ice.DatagramLimitException(); - } - stream.resize(packetSize, true); - ByteBuffer buf = stream.prepareRead(); - buf.position(0); - - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.NonWindows) - { - - repeat: - - // - // Check the shutdown flag. - // - lock(_shutdownReadWriteMutex) - { - if(_shutdownReadWrite) - { - throw new Ice.ConnectionLostException(); - } - } - - try - { - int ret; - if(_connect) - { - // - // If we must connect, then we connect to the first peer that - // sends us a packet. - // - EndPoint peerAddr = new IPEndPoint(IPAddress.Any, 0); - ret = _fd.ReceiveFrom(buf.rawBytes(), 0, buf.limit(), SocketFlags.None, ref peerAddr); - - Network.doConnect(_fd, peerAddr, -1); - _connect = false; // We're connected now - - if(_traceLevels.network >= 1) - { - string s = "connected udp socket\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - } - else - { - Debug.Assert(_fd != null); - ret = _fd.Receive(buf.rawBytes(), 0, buf.limit(), SocketFlags.None); - } - - if(_traceLevels.network >= 3) - { - string s = "received " + ret + " bytes via udp\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - if(_stats != null) - { - _stats.bytesReceived(type(), ret); - } - - stream.resize(ret, true); - } - catch(Win32Exception e) - { - if(Network.interrupted(e)) - { - goto repeat; - } - - if(Network.wouldBlock(e)) - { - repeatPoll: - try - { - Network.doPoll(_fd, -1, Network.PollMode.Read); - } - catch(Win32Exception we) - { - if(Network.interrupted(we)) - { - goto repeatPoll; - } - throw new Ice.SocketException("poll failed", we); - } - catch(System.Exception se) - { - throw new Ice.SyscallException("poll failed", se); - } - - goto repeat; - } - - if(Network.recvTruncated(e)) - { - if(_warn) - { - _logger.warning("DatagramLimitException: maximum size of " + packetSize + " exceeded"); - } - throw new Ice.DatagramLimitException(); - } - - if(Network.connectionLost(e)) - { - throw new Ice.ConnectionLostException(); - } - - if(Network.connectionRefused(e)) - { - throw new Ice.ConnectionRefusedException(); - } - - throw new Ice.SocketException(e); - } - catch(Ice.LocalException) - { - throw; - } - catch(System.Exception e) - { - throw new Ice.SyscallException(e); - } - } - else - { - // - // On Windows, we use asynchronous I/O to properly handle a call to - // shutdownReadWrite. After calling BeginReceiveFrom, we wait for - // the receive to complete or for the _shutdownReadWriteEvent to be - // signaled. - // - - WaitHandle[] handles = new WaitHandle[2]; - handles[0] = _shutdownReadWriteEvent; - - EndPoint peerAddr = new IPEndPoint(IPAddress.Any, 0); - - // - // Check the shutdown flag. - // - lock(_shutdownReadWriteMutex) - { - if(_shutdownReadWrite) - { - throw new Ice.ConnectionLostException(); - } - } - - try - { - IAsyncResult ar = _fd.BeginReceiveFrom(buf.rawBytes(), 0, buf.limit(), SocketFlags.None, - ref peerAddr, null, null); - handles[1] = ar.AsyncWaitHandle; - int num = WaitHandle.WaitAny(handles); - if(num == 0) - { - // - // shutdownReadWrite was called. - // - throw new Ice.ConnectionLostException(); - } - else - { - int ret = _fd.EndReceiveFrom(ar, ref peerAddr); - - if(_connect) - { - // - // If we must connect, then we connect to the first peer that - // sends us a packet. - // - Network.doConnect(_fd, peerAddr, -1); - _connect = false; // We're connected now - - if(_traceLevels.network >= 1) - { - string s = "connected udp socket\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - } - - if(_traceLevels.network >= 3) - { - string s = "received " + ret + " bytes via udp\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - - if(_stats != null) - { - _stats.bytesReceived(type(), ret); - } - - stream.resize(ret, true); - } - } - catch(Win32Exception e) - { - if(Network.recvTruncated(e)) - { - if(_warn) - { - _logger.warning("DatagramLimitException: maximum size of " + packetSize + " exceeded"); - } - throw new Ice.DatagramLimitException(); - } - - if(Network.connectionLost(e)) - { - throw new Ice.ConnectionLostException(); - } - - if(Network.connectionRefused(e)) - { - throw new Ice.ConnectionRefusedException(); - } - - throw new Ice.SocketException(e); - } - catch(Ice.LocalException) - { - throw; - } - catch(System.Exception e) - { - throw new Ice.SyscallException(e); - } - } - } + public Socket fd() + { + Debug.Assert(_fd != null); + return _fd; + } + + public void close() + { + lock(this) + { + if(_traceLevels.network >= 1) + { + string s = "closing udp connection\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + if(_fd != null) + { + try + { + _fd.Close(); + } + catch(System.IO.IOException) + { + } + _fd = null; + } + } + } + + public void shutdownWrite() + { + } + + public void shutdownReadWrite() + { + if(_traceLevels.network >= 2) + { + string s = "shutting down udp connection for reading and writing\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + // + // Set a flag and then shutdown the socket in order to wake a thread that is + // blocked in read(). + // + lock(_shutdownReadWriteMutex) + { + _shutdownReadWrite = true; + + Debug.Assert(_fd != null); + try + { + _fd.Shutdown(SocketShutdown.Both); + } + catch(SocketException ex) + { + if(Network.notConnected(ex)) + { + return; + } + throw new Ice.SocketException(ex); + } + + if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) + { + // + // On Windows, shutting down the socket doesn't unblock a call to + // receive or select. Setting an event wakes up the thread in + // read(). + // + _shutdownReadWriteEvent.Set(); + } + } + } + + public void write(BasicStream stream, int timeout) + { + Debug.Assert(_fd != null); + + ByteBuffer buf = stream.prepareWrite(); + + Debug.Assert(buf.position() == 0); + int packetSize = System.Math.Min(_maxPacketSize, _sndSize - _udpOverhead); + if(packetSize < buf.limit()) + { + // + // We don't log a warning here because the client gets an exception anyway. + // + throw new Ice.DatagramLimitException(); + } + + try + { + int remaining = buf.remaining(); + int ret; + try + { + ret = _fd.Send(buf.rawBytes(), 0, remaining, SocketFlags.None); + } + catch(Win32Exception e) + { + if(Network.wouldBlock(e)) + { + if(timeout == 0) + { + throw new Ice.TimeoutException(); + } + ret = 0; + } + else + { + throw; + } + } + if(ret == 0) + { + if(!Network.doPoll(_fd, timeout, Network.PollMode.Write)) + { + throw new Ice.TimeoutException(); + } + ret = _fd.Send(buf.rawBytes(), 0, remaining, SocketFlags.None); + } + if(ret != remaining) + { + throw new Ice.DatagramLimitException(); + } + + if(_traceLevels.network >= 3) + { + string s = "sent " + ret + " bytes via udp\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + if(_stats != null) + { + _stats.bytesSent(type(), ret); + } + + buf.position(remaining); + } + catch(SocketException ex) + { + throw new Ice.SocketException(ex); + } + catch(Ice.LocalException) + { + throw; + } + catch(System.Exception ex) + { + throw new Ice.SyscallException(ex); + } + } + + public void read(BasicStream stream, int timeout) + { + Debug.Assert(stream.pos() == 0); + + int packetSize = System.Math.Min(_maxPacketSize, _rcvSize - _udpOverhead); + if(packetSize < stream.size()) + { + // + // We log a warning here because this is the server side -- without the + // the warning, there would only be silence. + // + if(_warn) + { + _logger.warning("DatagramLimitException: maximum size of " + packetSize + " exceeded"); + } + throw new Ice.DatagramLimitException(); + } + stream.resize(packetSize, true); + ByteBuffer buf = stream.prepareRead(); + buf.position(0); + + if(AssemblyUtil.platform_ == AssemblyUtil.Platform.NonWindows) + { + + repeat: + + // + // Check the shutdown flag. + // + lock(_shutdownReadWriteMutex) + { + if(_shutdownReadWrite) + { + throw new Ice.ConnectionLostException(); + } + } + + try + { + int ret; + if(_connect) + { + // + // If we must connect, then we connect to the first peer that + // sends us a packet. + // + EndPoint peerAddr = new IPEndPoint(IPAddress.Any, 0); + ret = _fd.ReceiveFrom(buf.rawBytes(), 0, buf.limit(), SocketFlags.None, ref peerAddr); + + Network.doConnect(_fd, peerAddr, -1); + _connect = false; // We're connected now + + if(_traceLevels.network >= 1) + { + string s = "connected udp socket\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + } + else + { + Debug.Assert(_fd != null); + ret = _fd.Receive(buf.rawBytes(), 0, buf.limit(), SocketFlags.None); + } + + if(_traceLevels.network >= 3) + { + string s = "received " + ret + " bytes via udp\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + if(_stats != null) + { + _stats.bytesReceived(type(), ret); + } + + stream.resize(ret, true); + } + catch(Win32Exception e) + { + if(Network.interrupted(e)) + { + goto repeat; + } + + if(Network.wouldBlock(e)) + { + repeatPoll: + try + { + Network.doPoll(_fd, -1, Network.PollMode.Read); + } + catch(Win32Exception we) + { + if(Network.interrupted(we)) + { + goto repeatPoll; + } + throw new Ice.SocketException("poll failed", we); + } + catch(System.Exception se) + { + throw new Ice.SyscallException("poll failed", se); + } + + goto repeat; + } + + if(Network.recvTruncated(e)) + { + if(_warn) + { + _logger.warning("DatagramLimitException: maximum size of " + packetSize + " exceeded"); + } + throw new Ice.DatagramLimitException(); + } + + if(Network.connectionLost(e)) + { + throw new Ice.ConnectionLostException(); + } + + if(Network.connectionRefused(e)) + { + throw new Ice.ConnectionRefusedException(); + } + + throw new Ice.SocketException(e); + } + catch(Ice.LocalException) + { + throw; + } + catch(System.Exception e) + { + throw new Ice.SyscallException(e); + } + } + else + { + // + // On Windows, we use asynchronous I/O to properly handle a call to + // shutdownReadWrite. After calling BeginReceiveFrom, we wait for + // the receive to complete or for the _shutdownReadWriteEvent to be + // signaled. + // + + WaitHandle[] handles = new WaitHandle[2]; + handles[0] = _shutdownReadWriteEvent; + + EndPoint peerAddr = new IPEndPoint(IPAddress.Any, 0); + + // + // Check the shutdown flag. + // + lock(_shutdownReadWriteMutex) + { + if(_shutdownReadWrite) + { + throw new Ice.ConnectionLostException(); + } + } + + try + { + IAsyncResult ar = _fd.BeginReceiveFrom(buf.rawBytes(), 0, buf.limit(), SocketFlags.None, + ref peerAddr, null, null); + handles[1] = ar.AsyncWaitHandle; + int num = WaitHandle.WaitAny(handles); + if(num == 0) + { + // + // shutdownReadWrite was called. + // + throw new Ice.ConnectionLostException(); + } + else + { + int ret = _fd.EndReceiveFrom(ar, ref peerAddr); + + if(_connect) + { + // + // If we must connect, then we connect to the first peer that + // sends us a packet. + // + Network.doConnect(_fd, peerAddr, -1); + _connect = false; // We're connected now + + if(_traceLevels.network >= 1) + { + string s = "connected udp socket\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + } + + if(_traceLevels.network >= 3) + { + string s = "received " + ret + " bytes via udp\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + + if(_stats != null) + { + _stats.bytesReceived(type(), ret); + } + + stream.resize(ret, true); + } + } + catch(Win32Exception e) + { + if(Network.recvTruncated(e)) + { + if(_warn) + { + _logger.warning("DatagramLimitException: maximum size of " + packetSize + " exceeded"); + } + throw new Ice.DatagramLimitException(); + } + + if(Network.connectionLost(e)) + { + throw new Ice.ConnectionLostException(); + } + + if(Network.connectionRefused(e)) + { + throw new Ice.ConnectionRefusedException(); + } + + throw new Ice.SocketException(e); + } + catch(Ice.LocalException) + { + throw; + } + catch(System.Exception e) + { + throw new Ice.SyscallException(e); + } + } + } public string type() { @@ -439,183 +439,183 @@ namespace IceInternal } } - public override string ToString() - { - return Network.fdToString(_fd); - } - - public bool equivalent(string host, int port) - { - IPEndPoint addr = ((IPEndPoint)Network.getAddress(host, port)); - return addr.Equals(_addr); - } - - public int effectivePort() - { - return _addr.Port; - } - - // - // Only for use by UdpEndpoint - // - internal UdpTransceiver(Instance instance, string host, int port) - { - _traceLevels = instance.traceLevels(); - _logger = instance.initializationData().logger; - _stats = instance.initializationData().stats; - _connect = true; - _warn = instance.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; - - try - { - _fd = Network.createSocket(true); - setBufSize(instance); - Network.setBlock(_fd, false); - _addr = Network.getAddress(host, port); - Network.doConnect(_fd, _addr, -1); - _connect = false; // We're connected now - - if(_traceLevels.network >= 1) - { - string s = "starting to send udp packets\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - } - catch(Ice.LocalException) - { - _fd = null; - throw; - } - } - - // - // Only for use by UdpEndpoint - // - internal UdpTransceiver(Instance instance, string host, int port, bool connect) - { - _traceLevels = instance.traceLevels(); - _logger = instance.initializationData().logger; - _stats = instance.initializationData().stats; - _connect = connect; - _warn = instance.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; - _shutdownReadWrite = false; - - try - { - _fd = Network.createSocket(true); - setBufSize(instance); - Network.setBlock(_fd, false); - _addr = Network.getAddress(host, port); - if(_traceLevels.network >= 2) - { - string s = "attempting to bind to udp socket " + Network.addrToString(_addr); - _logger.trace(_traceLevels.networkCat, s); - } - _addr = Network.doBind(_fd, _addr); - - if(_traceLevels.network >= 1) - { - string s = "starting to receive udp packets\n" + ToString(); - _logger.trace(_traceLevels.networkCat, s); - } - } - catch(Ice.LocalException) - { - _fd = null; - throw; - } - } - - private void setBufSize(Instance instance) - { - lock(this) - { - Debug.Assert(_fd != null); - - for (int i = 0; i < 2; ++i) - { - string direction; - string prop; - int dfltSize; - if(i == 0) - { - direction = "receive"; - prop = "Ice.UDP.RcvSize"; - dfltSize = Network.getRecvBufferSize(_fd); - _rcvSize = dfltSize; - } - else - { - direction = "send"; - prop = "Ice.UDP.SndSize"; - dfltSize = Network.getSendBufferSize(_fd); - _sndSize = dfltSize; - } - - // - // Get property for buffer size and check for sanity. - // - int sizeRequested = - instance.initializationData().properties.getPropertyAsIntWithDefault(prop, dfltSize); - if(sizeRequested < _udpOverhead) - { - _logger.warning("Invalid " + prop + " value of " + sizeRequested + " adjusted to " + dfltSize); - sizeRequested = dfltSize; - } - - if(sizeRequested != dfltSize) - { - // - // Try to set the buffer size. The kernel will silently adjust - // the size to an acceptable value. Then read the size back to - // get the size that was actually set. - // - int sizeSet; - if(i == 0) - { - Network.setRecvBufferSize(_fd, sizeRequested); - _rcvSize = Network.getRecvBufferSize(_fd); - sizeSet = _rcvSize; - } - else - { - Network.setSendBufferSize(_fd, sizeRequested); - _sndSize = Network.getSendBufferSize(_fd); - sizeSet = _sndSize; - } - - // - // Warn if the size that was set is less than the requested size. - // - if(sizeSet < sizeRequested) - { - _logger.warning("UDP " + direction + " buffer size: requested size of " + sizeRequested + - " adjusted to " + sizeSet); - } - } - } - } - } - - private TraceLevels _traceLevels; - private Ice.Logger _logger; - private Ice.Stats _stats; - private bool _connect; - private readonly bool _warn; - private int _rcvSize; - private int _sndSize; - private Socket _fd; - private IPEndPoint _addr; - - // - // The maximum IP datagram size is 65535. Subtract 20 bytes for the IP header and 8 bytes for the UDP header - // to get the maximum payload. - // - private const int _udpOverhead = 20 + 8; - private static readonly int _maxPacketSize = 65535 - _udpOverhead; - - private bool _shutdownReadWrite; - private object _shutdownReadWriteMutex = new object(); - private AutoResetEvent _shutdownReadWriteEvent = new AutoResetEvent(false); + public override string ToString() + { + return Network.fdToString(_fd); + } + + public bool equivalent(string host, int port) + { + IPEndPoint addr = ((IPEndPoint)Network.getAddress(host, port)); + return addr.Equals(_addr); + } + + public int effectivePort() + { + return _addr.Port; + } + + // + // Only for use by UdpEndpoint + // + internal UdpTransceiver(Instance instance, string host, int port) + { + _traceLevels = instance.traceLevels(); + _logger = instance.initializationData().logger; + _stats = instance.initializationData().stats; + _connect = true; + _warn = instance.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; + + try + { + _fd = Network.createSocket(true); + setBufSize(instance); + Network.setBlock(_fd, false); + _addr = Network.getAddress(host, port); + Network.doConnect(_fd, _addr, -1); + _connect = false; // We're connected now + + if(_traceLevels.network >= 1) + { + string s = "starting to send udp packets\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + } + catch(Ice.LocalException) + { + _fd = null; + throw; + } + } + + // + // Only for use by UdpEndpoint + // + internal UdpTransceiver(Instance instance, string host, int port, bool connect) + { + _traceLevels = instance.traceLevels(); + _logger = instance.initializationData().logger; + _stats = instance.initializationData().stats; + _connect = connect; + _warn = instance.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; + _shutdownReadWrite = false; + + try + { + _fd = Network.createSocket(true); + setBufSize(instance); + Network.setBlock(_fd, false); + _addr = Network.getAddress(host, port); + if(_traceLevels.network >= 2) + { + string s = "attempting to bind to udp socket " + Network.addrToString(_addr); + _logger.trace(_traceLevels.networkCat, s); + } + _addr = Network.doBind(_fd, _addr); + + if(_traceLevels.network >= 1) + { + string s = "starting to receive udp packets\n" + ToString(); + _logger.trace(_traceLevels.networkCat, s); + } + } + catch(Ice.LocalException) + { + _fd = null; + throw; + } + } + + private void setBufSize(Instance instance) + { + lock(this) + { + Debug.Assert(_fd != null); + + for (int i = 0; i < 2; ++i) + { + string direction; + string prop; + int dfltSize; + if(i == 0) + { + direction = "receive"; + prop = "Ice.UDP.RcvSize"; + dfltSize = Network.getRecvBufferSize(_fd); + _rcvSize = dfltSize; + } + else + { + direction = "send"; + prop = "Ice.UDP.SndSize"; + dfltSize = Network.getSendBufferSize(_fd); + _sndSize = dfltSize; + } + + // + // Get property for buffer size and check for sanity. + // + int sizeRequested = + instance.initializationData().properties.getPropertyAsIntWithDefault(prop, dfltSize); + if(sizeRequested < _udpOverhead) + { + _logger.warning("Invalid " + prop + " value of " + sizeRequested + " adjusted to " + dfltSize); + sizeRequested = dfltSize; + } + + if(sizeRequested != dfltSize) + { + // + // Try to set the buffer size. The kernel will silently adjust + // the size to an acceptable value. Then read the size back to + // get the size that was actually set. + // + int sizeSet; + if(i == 0) + { + Network.setRecvBufferSize(_fd, sizeRequested); + _rcvSize = Network.getRecvBufferSize(_fd); + sizeSet = _rcvSize; + } + else + { + Network.setSendBufferSize(_fd, sizeRequested); + _sndSize = Network.getSendBufferSize(_fd); + sizeSet = _sndSize; + } + + // + // Warn if the size that was set is less than the requested size. + // + if(sizeSet < sizeRequested) + { + _logger.warning("UDP " + direction + " buffer size: requested size of " + sizeRequested + + " adjusted to " + sizeSet); + } + } + } + } + } + + private TraceLevels _traceLevels; + private Ice.Logger _logger; + private Ice.Stats _stats; + private bool _connect; + private readonly bool _warn; + private int _rcvSize; + private int _sndSize; + private Socket _fd; + private IPEndPoint _addr; + + // + // The maximum IP datagram size is 65535. Subtract 20 bytes for the IP header and 8 bytes for the UDP header + // to get the maximum payload. + // + private const int _udpOverhead = 20 + 8; + private static readonly int _maxPacketSize = 65535 - _udpOverhead; + + private bool _shutdownReadWrite; + private object _shutdownReadWriteMutex = new object(); + private AutoResetEvent _shutdownReadWriteEvent = new AutoResetEvent(false); } } diff --git a/cs/src/Ice/UnknownEndpointI.cs b/cs/src/Ice/UnknownEndpointI.cs index 96dff4394ca..b841c992df0 100755 --- a/cs/src/Ice/UnknownEndpointI.cs +++ b/cs/src/Ice/UnknownEndpointI.cs @@ -14,157 +14,157 @@ namespace IceInternal sealed class UnknownEndpointI : EndpointI { - public UnknownEndpointI(short type, BasicStream s) - { - _type = type; - s.startReadEncaps(); - int sz = s.getReadEncapsSize(); - _rawBytes = new byte[sz]; - s.readBlob(_rawBytes); - s.endReadEncaps(); - calcHashValue(); - } - - // - // Marshal the endpoint - // - public override void streamWrite(BasicStream s) - { - s.writeShort(_type); - s.startWriteEncaps(); - s.writeBlob(_rawBytes); - s.endWriteEncaps(); - } - - // - // Convert the endpoint to its string form - // - public override string ice_toString_() - { - return ""; - } - - // - // Return the endpoint type - // - public override short type() - { - return _type; - } - - // - // Return the timeout for the endpoint in milliseconds. 0 means - // non-blocking, -1 means no timeout. - // - public override int timeout() - { - return -1; - } - - // - // Return a new endpoint with a different timeout value, provided - // that timeouts are supported by the endpoint. Otherwise the same - // endpoint is returned. - // - public override EndpointI timeout(int t) - { - return this; - } + public UnknownEndpointI(short type, BasicStream s) + { + _type = type; + s.startReadEncaps(); + int sz = s.getReadEncapsSize(); + _rawBytes = new byte[sz]; + s.readBlob(_rawBytes); + s.endReadEncaps(); + calcHashValue(); + } + + // + // Marshal the endpoint + // + public override void streamWrite(BasicStream s) + { + s.writeShort(_type); + s.startWriteEncaps(); + s.writeBlob(_rawBytes); + s.endWriteEncaps(); + } + + // + // Convert the endpoint to its string form + // + public override string ice_toString_() + { + return ""; + } + + // + // Return the endpoint type + // + public override short type() + { + return _type; + } + + // + // Return the timeout for the endpoint in milliseconds. 0 means + // non-blocking, -1 means no timeout. + // + public override int timeout() + { + return -1; + } + + // + // Return a new endpoint with a different timeout value, provided + // that timeouts are supported by the endpoint. Otherwise the same + // endpoint is returned. + // + public override EndpointI timeout(int t) + { + return this; + } - // - // Return a new endpoint with a different connection id. - // - public override EndpointI connectionId(string id) - { - return this; - } - - // - // Return true if the endpoints support bzip2 compress, or false - // otherwise. - // - public override bool compress() - { - return false; - } - - // - // Return a new endpoint with a different compression value, - // provided that compression is supported by the - // endpoint. Otherwise the same endpoint is returned. - // - public override EndpointI compress(bool compress) - { - return this; - } - - // - // Return true if the endpoint is datagram-based. - // - public override bool datagram() - { - return false; - } - - // - // Return true if the endpoint is secure. - // - public override bool secure() - { - return false; - } - - // - // Return true if the endpoint type is unknown. - // - public override bool unknown() - { - return true; - } - - // - // Return a client side transceiver for this endpoint, or null if a - // transceiver can only be created by a connector. - // - public override Transceiver clientTransceiver() - { - return null; - } - - // - // Return a server side transceiver for this endpoint, or null if a - // transceiver can only be created by an acceptor. In case a - // transceiver is created, this operation also returns a new - // "effective" endpoint, which might differ from this endpoint, - // for example, if a dynamic port number is assigned. - // - public override Transceiver serverTransceiver(ref EndpointI endpoint) - { - endpoint = null; - return null; - } - - // - // Return a connector for this endpoint, or null if no connector - // is available. - // - public override Connector connector() - { - return null; - } - - // - // Return an acceptor for this endpoint, or null if no acceptors - // is available. In case an acceptor is created, this operation - // also returns a new "effective" endpoint, which might differ - // from this endpoint, for example, if a dynamic port number is - // assigned. - // - public override Acceptor acceptor(ref EndpointI endpoint, string adapterName) - { - endpoint = null; - return null; - } + // + // Return a new endpoint with a different connection id. + // + public override EndpointI connectionId(string id) + { + return this; + } + + // + // Return true if the endpoints support bzip2 compress, or false + // otherwise. + // + public override bool compress() + { + return false; + } + + // + // Return a new endpoint with a different compression value, + // provided that compression is supported by the + // endpoint. Otherwise the same endpoint is returned. + // + public override EndpointI compress(bool compress) + { + return this; + } + + // + // Return true if the endpoint is datagram-based. + // + public override bool datagram() + { + return false; + } + + // + // Return true if the endpoint is secure. + // + public override bool secure() + { + return false; + } + + // + // Return true if the endpoint type is unknown. + // + public override bool unknown() + { + return true; + } + + // + // Return a client side transceiver for this endpoint, or null if a + // transceiver can only be created by a connector. + // + public override Transceiver clientTransceiver() + { + return null; + } + + // + // Return a server side transceiver for this endpoint, or null if a + // transceiver can only be created by an acceptor. In case a + // transceiver is created, this operation also returns a new + // "effective" endpoint, which might differ from this endpoint, + // for example, if a dynamic port number is assigned. + // + public override Transceiver serverTransceiver(ref EndpointI endpoint) + { + endpoint = null; + return null; + } + + // + // Return a connector for this endpoint, or null if no connector + // is available. + // + public override Connector connector() + { + return null; + } + + // + // Return an acceptor for this endpoint, or null if no acceptors + // is available. In case an acceptor is created, this operation + // also returns a new "effective" endpoint, which might differ + // from this endpoint, for example, if a dynamic port number is + // assigned. + // + public override Acceptor acceptor(ref EndpointI endpoint, string adapterName) + { + endpoint = null; + return null; + } // // Expand endpoint out in to separate endpoints for each local @@ -186,101 +186,101 @@ namespace IceInternal { return false; } - - // - // Check whether the endpoint is equivalent to a specific - // Transceiver or Acceptor - // - public override bool equivalent(Transceiver transceiver) - { - return false; - } - - public override bool equivalent(Acceptor acceptor) - { - return false; - } + + // + // Check whether the endpoint is equivalent to a specific + // Transceiver or Acceptor + // + public override bool equivalent(Transceiver transceiver) + { + return false; + } + + public override bool equivalent(Acceptor acceptor) + { + return false; + } public override bool requiresThreadPerConnection() { return false; } - public override int GetHashCode() - { - return _hashCode; - } - - // - // Compare endpoints for sorting purposes - // - public override bool Equals(System.Object obj) - { - return CompareTo(obj) == 0; - } - - public override int CompareTo(System.Object obj) - { - UnknownEndpointI p = null; - - try - { - p = (UnknownEndpointI) obj; - } - catch(System.InvalidCastException) - { - return 1; - } - - if(this == p) - { - return 0; - } - - if(_type < p._type) - { - return -1; - } - else if(p._type < _type) - { - return 1; - } - - if(_rawBytes.Length < p._rawBytes.Length) - { - return -1; - } - else if(p._rawBytes.Length < _rawBytes.Length) - { - return 1; - } - for(int i = 0; i < _rawBytes.Length; i++) - { - if(_rawBytes[i] < p._rawBytes[i]) - { - return -1; - } - else if(p._rawBytes[i] < _rawBytes[i]) - { - return 1; - } - } - - return 0; - } - - private void calcHashValue() - { - _hashCode = _type; - for(int i = 0; i < _rawBytes.Length; i++) - { - _hashCode = 5 * _hashCode + _rawBytes[i]; - } - } - - private short _type; - private byte[] _rawBytes; - private int _hashCode; + public override int GetHashCode() + { + return _hashCode; + } + + // + // Compare endpoints for sorting purposes + // + public override bool Equals(System.Object obj) + { + return CompareTo(obj) == 0; + } + + public override int CompareTo(System.Object obj) + { + UnknownEndpointI p = null; + + try + { + p = (UnknownEndpointI) obj; + } + catch(System.InvalidCastException) + { + return 1; + } + + if(this == p) + { + return 0; + } + + if(_type < p._type) + { + return -1; + } + else if(p._type < _type) + { + return 1; + } + + if(_rawBytes.Length < p._rawBytes.Length) + { + return -1; + } + else if(p._rawBytes.Length < _rawBytes.Length) + { + return 1; + } + for(int i = 0; i < _rawBytes.Length; i++) + { + if(_rawBytes[i] < p._rawBytes[i]) + { + return -1; + } + else if(p._rawBytes[i] < _rawBytes[i]) + { + return 1; + } + } + + return 0; + } + + private void calcHashValue() + { + _hashCode = _type; + for(int i = 0; i < _rawBytes.Length; i++) + { + _hashCode = 5 * _hashCode + _rawBytes[i]; + } + } + + private short _type; + private byte[] _rawBytes; + private int _hashCode; } } diff --git a/cs/src/Ice/UserExceptionFactory.cs b/cs/src/Ice/UserExceptionFactory.cs index 44d857bc16b..f10524bbb3f 100755 --- a/cs/src/Ice/UserExceptionFactory.cs +++ b/cs/src/Ice/UserExceptionFactory.cs @@ -12,8 +12,8 @@ namespace IceInternal public interface UserExceptionFactory { - void createAndThrow(); - void destroy(); + void createAndThrow(); + void destroy(); } } diff --git a/cs/src/Ice/Util.cs b/cs/src/Ice/Util.cs index 3f11df349bc..80f72a6a9cb 100755 --- a/cs/src/Ice/Util.cs +++ b/cs/src/Ice/Util.cs @@ -27,399 +27,399 @@ namespace Ice public class InitializationData : ICloneable { public System.Object Clone() - { - // - // A member-wise copy is safe because the members are immutable. - // - return MemberwiseClone(); - } + { + // + // A member-wise copy is safe because the members are immutable. + // + return MemberwiseClone(); + } public Properties properties; - public Logger logger; - public Stats stats; - public ThreadNotification threadHook; + public Logger logger; + public Stats stats; + public ThreadNotification threadHook; } public sealed class Util { - public static Properties createProperties() - { - return new PropertiesI(); - } - - public static Properties createProperties(ref string[] args) - { - return new PropertiesI(ref args, null); - } - - public static Properties createProperties(ref string[] args, Properties defaults) - { - return new PropertiesI(ref args, defaults); - } - - public static Communicator initialize(ref string[] args) - { - return initialize(ref args, null); - } - - public static Communicator initialize(ref string[] args, InitializationData initData) - { - if(initData == null) - { - initData = new InitializationData(); - } - else - { - initData = (InitializationData)initData.Clone(); - } - - initData.properties = createProperties(ref args, initData.properties); - - CommunicatorI result = new CommunicatorI(initData); - result.finishSetup(ref args); - return result; - } - - public static Communicator initialize(InitializationData initData) - { - if(initData == null) - { - initData = new InitializationData(); - } - else - { - initData = (InitializationData)initData.Clone(); - } - - CommunicatorI result = new CommunicatorI(initData); - string[] args = new string[0]; - result.finishSetup(ref args); - return result; - } - - public static Communicator initialize() - { - return initialize(null); - } - - [Obsolete("This method is deprecated, use initialize instead.")] - public static Communicator initializeWithLogger(ref string[] args, Logger logger) - { - InitializationData initData = new InitializationData(); - initData.logger = logger; - return initialize(ref args, initData); - } - - [Obsolete("This method is deprecated, use initialize instead.")] - public static Communicator initializeWithProperties(ref string[] args, Properties properties) - { - InitializationData initData = new InitializationData(); - initData.properties = properties; - return initialize(ref args, initData); - } - - [Obsolete("This method is deprecated, use initialize instead.")] - public static Communicator initializeWithPropertiesAndLogger(ref string[] args, Properties properties, - Ice.Logger logger) - { - InitializationData initData = new InitializationData(); - initData.properties = properties; - initData.logger = logger; - return initialize(ref args, initData); - } - - public static IceInternal.Instance getInstance(Communicator communicator) - { - CommunicatorI p = (CommunicatorI) communicator; - return p.getInstance(); - } - - public static IceInternal.ProtocolPluginFacade getProtocolPluginFacade(Communicator communicator) - { - return new IceInternal.ProtocolPluginFacadeI(communicator); - } - - public static Identity stringToIdentity(string s) - { - Identity ident = new Identity(); - - // - // Find unescaped separator. - // - int slash = -1, pos = 0; - while((pos = s.IndexOf((System.Char) '/', pos)) != -1) - { - if(pos == 0 || s[pos - 1] != '\\') - { - if(slash == -1) - { - slash = pos; - } - else - { - // - // Extra unescaped slash found. - // - IdentityParseException ex = new IdentityParseException(); - ex.str = s; - throw ex; - } - } - pos++; - } - - if(slash == -1) - { - if(!IceUtil.StringUtil.unescapeString(s, 0, s.Length, out ident.name)) - { - IdentityParseException ex = new IdentityParseException(); - ex.str = s; - throw ex; - } - ident.category = ""; - } - else - { - if(!IceUtil.StringUtil.unescapeString(s, 0, slash, out ident.category)) - { - IdentityParseException ex = new IdentityParseException(); - ex.str = s; - throw ex; - } - if(slash + 1 < s.Length) - { - if(!IceUtil.StringUtil.unescapeString(s, slash + 1, s.Length, out ident.name)) - { - IdentityParseException ex = new IdentityParseException(); - ex.str = s; - throw ex; - } - } - else - { - ident.name = ""; - } - } - - return ident; - } - - public static string identityToString(Identity ident) - { - if(ident.category.Length == 0) - { - return IceUtil.StringUtil.escapeString(ident.name, "/"); - } - else - { - return IceUtil.StringUtil.escapeString(ident.category, "/") + '/' + IceUtil.StringUtil.escapeString(ident.name, "/"); - } - } - - [StructLayout(LayoutKind.Sequential)] - private struct UUID - { - public ulong Data1; - public ushort Data2; - public ushort Data3; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst=8)] - public string Data4; - } - - [DllImport("rpcrt4.dll")] - private static extern int UuidCreate(ref UUID uuid); - - [DllImport("rpcrt4.dll")] - private static extern int UuidToString(ref UUID uuid, ref System.IntPtr str); - - [DllImport("rpcrt4.dll")] - private static extern int RpcStringFree(ref System.IntPtr str); - - private const int RPC_S_OK = 0; - private const int RPC_S_OUT_OF_MEMORY = 14; - private const int RPC_S_UUID_LOCAL_ONLY = 1824; - - public static string generateUUID() - { - if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) - { - // - // Under Windows, with both .NET and Mono, there is no /dev/urandom. - // - int rc; - UUID uuid = new UUID(); - rc = UuidCreate(ref uuid); - if(rc != RPC_S_OK && rc != RPC_S_UUID_LOCAL_ONLY) - { - Ice.SyscallException ex = new Ice.SyscallException("UuidCreate() failed"); - ex.error = rc; - throw ex; - } - System.IntPtr str = new System.IntPtr(); - rc = UuidToString(ref uuid, ref str); - switch(rc) - { - case RPC_S_OK: - { - break; - } - case RPC_S_OUT_OF_MEMORY: - { - throw new Ice.MemoryLimitException("No memory for UUID string"); - } - default: - { - Ice.SyscallException ex = new Ice.SyscallException("UuidToString() failed"); - ex.error = rc; - throw ex; - } - } - string result; - try - { - result = Marshal.PtrToStringAnsi(str); - } - catch(System.Exception ex) - { - throw new Ice.SyscallException(ex); - } - if((rc = RpcStringFree(ref str)) != RPC_S_OK) - { - Ice.SyscallException ex = new Ice.SyscallException("Cannot deallocate UUID"); - ex.error = rc; - throw ex; - } - return result; - } - else - { - // - // On Linux, /dev/random, even when used in blocking mode, sometimes - // fails or returns fewer bytes. - // Maybe we should use a combination of version 4 UUIDs (with /dev/random), - // and version 1 UUIDs (MAC address + time), when /dev/random is exhausted? - // - FileStream f = File.OpenRead("/dev/urandom"); - - const int uuidSize = 16; - byte[] buf = new byte[uuidSize]; - - // - // Limit the number of attempts to 20 reads to avoid an infinite loop. - // - int reads = 0; - int index = 0; - while(reads < 20 && index != uuidSize) - { - int bytesRead = f.Read(buf, index, uuidSize - index); - index += bytesRead; - reads++; - } - f.Close(); - if(index != uuidSize) - { - throw new System.ApplicationException("generateUUID(): could not get 16 random bytes"); - } - - // - // Adjust the bits that say "version 4" UUUID - // - buf[6] &= 0x0F; - buf[6] |= (4 << 4); - buf[8] &= 0x3F; - buf[8] |= 0x80; - - StringBuilder sb = new StringBuilder(); - for(int i = 0; i < 4; ++i) - { - sb.AppendFormat("{0:X2}", buf[i]); - } - sb.Append("-"); - for(int i = 4; i < 6; ++i) - { - sb.AppendFormat("{0:X2}", buf[i]); - } - sb.Append("-"); - for(int i = 6; i < 8; ++i) - { - sb.AppendFormat("{0:X2}", buf[i]); - } - sb.Append("-"); - for(int i = 8; i < 10; ++i) - { - sb.AppendFormat("{0:X2}", buf[i]); - } - sb.Append("-"); - for(int i = 10; i < 16; ++i) - { - sb.AppendFormat("{0:X2}", buf[i]); - } - return sb.ToString(); - } - } - - - public static int - proxyIdentityCompare(ObjectPrx lhs, ObjectPrx rhs) - { - if(lhs == null && rhs == null) - { - return 0; - } - else if(lhs == null && rhs != null) - { - return -1; - } - else if(lhs != null && rhs == null) - { - return 1; - } - else - { - Identity lhsIdentity = lhs.ice_getIdentity(); - Identity rhsIdentity = rhs.ice_getIdentity(); - int n; - n = string.Compare(lhsIdentity.name, rhsIdentity.name, false, CultureInfo.InvariantCulture); - if(n != 0) - { - return n; - } - return string.Compare(lhsIdentity.category, rhsIdentity.category, false, CultureInfo.InvariantCulture); - } - } - - public static int proxyIdentityAndFacetCompare(ObjectPrx lhs, ObjectPrx rhs) - { - if(lhs == null && rhs == null) - { - return 0; - } - else if(lhs == null && rhs != null) - { - return -1; - } - else if(lhs != null && rhs == null) - { - return 1; - } - else - { - Identity lhsIdentity = lhs.ice_getIdentity(); - Identity rhsIdentity = rhs.ice_getIdentity(); - int n; - n = string.Compare(lhsIdentity.name, rhsIdentity.name, false, CultureInfo.InvariantCulture); - if(n != 0) - { - return n; - } - n = string.Compare(lhsIdentity.category, rhsIdentity.category, false, CultureInfo.InvariantCulture); + public static Properties createProperties() + { + return new PropertiesI(); + } + + public static Properties createProperties(ref string[] args) + { + return new PropertiesI(ref args, null); + } + + public static Properties createProperties(ref string[] args, Properties defaults) + { + return new PropertiesI(ref args, defaults); + } + + public static Communicator initialize(ref string[] args) + { + return initialize(ref args, null); + } + + public static Communicator initialize(ref string[] args, InitializationData initData) + { + if(initData == null) + { + initData = new InitializationData(); + } + else + { + initData = (InitializationData)initData.Clone(); + } + + initData.properties = createProperties(ref args, initData.properties); + + CommunicatorI result = new CommunicatorI(initData); + result.finishSetup(ref args); + return result; + } + + public static Communicator initialize(InitializationData initData) + { + if(initData == null) + { + initData = new InitializationData(); + } + else + { + initData = (InitializationData)initData.Clone(); + } + + CommunicatorI result = new CommunicatorI(initData); + string[] args = new string[0]; + result.finishSetup(ref args); + return result; + } + + public static Communicator initialize() + { + return initialize(null); + } + + [Obsolete("This method is deprecated, use initialize instead.")] + public static Communicator initializeWithLogger(ref string[] args, Logger logger) + { + InitializationData initData = new InitializationData(); + initData.logger = logger; + return initialize(ref args, initData); + } + + [Obsolete("This method is deprecated, use initialize instead.")] + public static Communicator initializeWithProperties(ref string[] args, Properties properties) + { + InitializationData initData = new InitializationData(); + initData.properties = properties; + return initialize(ref args, initData); + } + + [Obsolete("This method is deprecated, use initialize instead.")] + public static Communicator initializeWithPropertiesAndLogger(ref string[] args, Properties properties, + Ice.Logger logger) + { + InitializationData initData = new InitializationData(); + initData.properties = properties; + initData.logger = logger; + return initialize(ref args, initData); + } + + public static IceInternal.Instance getInstance(Communicator communicator) + { + CommunicatorI p = (CommunicatorI) communicator; + return p.getInstance(); + } + + public static IceInternal.ProtocolPluginFacade getProtocolPluginFacade(Communicator communicator) + { + return new IceInternal.ProtocolPluginFacadeI(communicator); + } + + public static Identity stringToIdentity(string s) + { + Identity ident = new Identity(); + + // + // Find unescaped separator. + // + int slash = -1, pos = 0; + while((pos = s.IndexOf((System.Char) '/', pos)) != -1) + { + if(pos == 0 || s[pos - 1] != '\\') + { + if(slash == -1) + { + slash = pos; + } + else + { + // + // Extra unescaped slash found. + // + IdentityParseException ex = new IdentityParseException(); + ex.str = s; + throw ex; + } + } + pos++; + } + + if(slash == -1) + { + if(!IceUtil.StringUtil.unescapeString(s, 0, s.Length, out ident.name)) + { + IdentityParseException ex = new IdentityParseException(); + ex.str = s; + throw ex; + } + ident.category = ""; + } + else + { + if(!IceUtil.StringUtil.unescapeString(s, 0, slash, out ident.category)) + { + IdentityParseException ex = new IdentityParseException(); + ex.str = s; + throw ex; + } + if(slash + 1 < s.Length) + { + if(!IceUtil.StringUtil.unescapeString(s, slash + 1, s.Length, out ident.name)) + { + IdentityParseException ex = new IdentityParseException(); + ex.str = s; + throw ex; + } + } + else + { + ident.name = ""; + } + } + + return ident; + } + + public static string identityToString(Identity ident) + { + if(ident.category.Length == 0) + { + return IceUtil.StringUtil.escapeString(ident.name, "/"); + } + else + { + return IceUtil.StringUtil.escapeString(ident.category, "/") + '/' + IceUtil.StringUtil.escapeString(ident.name, "/"); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct UUID + { + public ulong Data1; + public ushort Data2; + public ushort Data3; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst=8)] + public string Data4; + } + + [DllImport("rpcrt4.dll")] + private static extern int UuidCreate(ref UUID uuid); + + [DllImport("rpcrt4.dll")] + private static extern int UuidToString(ref UUID uuid, ref System.IntPtr str); + + [DllImport("rpcrt4.dll")] + private static extern int RpcStringFree(ref System.IntPtr str); + + private const int RPC_S_OK = 0; + private const int RPC_S_OUT_OF_MEMORY = 14; + private const int RPC_S_UUID_LOCAL_ONLY = 1824; + + public static string generateUUID() + { + if(AssemblyUtil.platform_ == AssemblyUtil.Platform.Windows) + { + // + // Under Windows, with both .NET and Mono, there is no /dev/urandom. + // + int rc; + UUID uuid = new UUID(); + rc = UuidCreate(ref uuid); + if(rc != RPC_S_OK && rc != RPC_S_UUID_LOCAL_ONLY) + { + Ice.SyscallException ex = new Ice.SyscallException("UuidCreate() failed"); + ex.error = rc; + throw ex; + } + System.IntPtr str = new System.IntPtr(); + rc = UuidToString(ref uuid, ref str); + switch(rc) + { + case RPC_S_OK: + { + break; + } + case RPC_S_OUT_OF_MEMORY: + { + throw new Ice.MemoryLimitException("No memory for UUID string"); + } + default: + { + Ice.SyscallException ex = new Ice.SyscallException("UuidToString() failed"); + ex.error = rc; + throw ex; + } + } + string result; + try + { + result = Marshal.PtrToStringAnsi(str); + } + catch(System.Exception ex) + { + throw new Ice.SyscallException(ex); + } + if((rc = RpcStringFree(ref str)) != RPC_S_OK) + { + Ice.SyscallException ex = new Ice.SyscallException("Cannot deallocate UUID"); + ex.error = rc; + throw ex; + } + return result; + } + else + { + // + // On Linux, /dev/random, even when used in blocking mode, sometimes + // fails or returns fewer bytes. + // Maybe we should use a combination of version 4 UUIDs (with /dev/random), + // and version 1 UUIDs (MAC address + time), when /dev/random is exhausted? + // + FileStream f = File.OpenRead("/dev/urandom"); + + const int uuidSize = 16; + byte[] buf = new byte[uuidSize]; + + // + // Limit the number of attempts to 20 reads to avoid an infinite loop. + // + int reads = 0; + int index = 0; + while(reads < 20 && index != uuidSize) + { + int bytesRead = f.Read(buf, index, uuidSize - index); + index += bytesRead; + reads++; + } + f.Close(); + if(index != uuidSize) + { + throw new System.ApplicationException("generateUUID(): could not get 16 random bytes"); + } + + // + // Adjust the bits that say "version 4" UUUID + // + buf[6] &= 0x0F; + buf[6] |= (4 << 4); + buf[8] &= 0x3F; + buf[8] |= 0x80; + + StringBuilder sb = new StringBuilder(); + for(int i = 0; i < 4; ++i) + { + sb.AppendFormat("{0:X2}", buf[i]); + } + sb.Append("-"); + for(int i = 4; i < 6; ++i) + { + sb.AppendFormat("{0:X2}", buf[i]); + } + sb.Append("-"); + for(int i = 6; i < 8; ++i) + { + sb.AppendFormat("{0:X2}", buf[i]); + } + sb.Append("-"); + for(int i = 8; i < 10; ++i) + { + sb.AppendFormat("{0:X2}", buf[i]); + } + sb.Append("-"); + for(int i = 10; i < 16; ++i) + { + sb.AppendFormat("{0:X2}", buf[i]); + } + return sb.ToString(); + } + } + + + public static int + proxyIdentityCompare(ObjectPrx lhs, ObjectPrx rhs) + { + if(lhs == null && rhs == null) + { + return 0; + } + else if(lhs == null && rhs != null) + { + return -1; + } + else if(lhs != null && rhs == null) + { + return 1; + } + else + { + Identity lhsIdentity = lhs.ice_getIdentity(); + Identity rhsIdentity = rhs.ice_getIdentity(); + int n; + n = string.Compare(lhsIdentity.name, rhsIdentity.name, false, CultureInfo.InvariantCulture); + if(n != 0) + { + return n; + } + return string.Compare(lhsIdentity.category, rhsIdentity.category, false, CultureInfo.InvariantCulture); + } + } + + public static int proxyIdentityAndFacetCompare(ObjectPrx lhs, ObjectPrx rhs) + { + if(lhs == null && rhs == null) + { + return 0; + } + else if(lhs == null && rhs != null) + { + return -1; + } + else if(lhs != null && rhs == null) + { + return 1; + } + else + { + Identity lhsIdentity = lhs.ice_getIdentity(); + Identity rhsIdentity = rhs.ice_getIdentity(); + int n; + n = string.Compare(lhsIdentity.name, rhsIdentity.name, false, CultureInfo.InvariantCulture); + if(n != 0) + { + return n; + } + n = string.Compare(lhsIdentity.category, rhsIdentity.category, false, CultureInfo.InvariantCulture); if(n != 0) - { - return n; - } + { + return n; + } - string lhsFacet = lhs.ice_getFacet(); - string rhsFacet = rhs.ice_getFacet(); + string lhsFacet = lhs.ice_getFacet(); + string rhsFacet = rhs.ice_getFacet(); if(lhsFacet == null && rhsFacet == null) { return 0; @@ -436,8 +436,8 @@ namespace Ice { return string.Compare(lhsFacet, rhsFacet, false, CultureInfo.InvariantCulture); } - } - } + } + } public static InputStream createInputStream(Communicator communicator, byte[] bytes) { @@ -449,27 +449,27 @@ namespace Ice return new OutputStreamI(communicator); } - public static Logger getProcessLogger() - { - lock(_processLoggerMutex) - { - if(_processLogger == null) - { - _processLogger = new LoggerI(System.AppDomain.CurrentDomain.FriendlyName); - } - return _processLogger; - } - } - - public static void setProcessLogger(Logger logger) - { - lock(_processLoggerMutex) - { - _processLogger = logger; - } - } - - private static object _processLoggerMutex = new object(); - private static Logger _processLogger = null; + public static Logger getProcessLogger() + { + lock(_processLoggerMutex) + { + if(_processLogger == null) + { + _processLogger = new LoggerI(System.AppDomain.CurrentDomain.FriendlyName); + } + return _processLogger; + } + } + + public static void setProcessLogger(Logger logger) + { + lock(_processLoggerMutex) + { + _processLogger = logger; + } + } + + private static object _processLoggerMutex = new object(); + private static Logger _processLogger = null; } } diff --git a/cs/src/Ice/ValueWriter.cs b/cs/src/Ice/ValueWriter.cs index 0b1076340cd..625cfbf18a9 100755 --- a/cs/src/Ice/ValueWriter.cs +++ b/cs/src/Ice/ValueWriter.cs @@ -17,137 +17,137 @@ namespace IceInternal public sealed class ValueWriter { - public static void write(object obj, OutputBase output) - { - writeValue(null, obj, null, output); - } - - private static void writeValue(string name, object val, Hashtable objectTable, OutputBase output) - { - if(val == null) - { - writeName(name, output); - output.print("(null)"); - } - else - { - System.Type c = val.GetType(); - if(c.Equals(typeof(byte)) || c.Equals(typeof(short)) || c.Equals(typeof(int)) || - c.Equals(typeof(long)) || c.Equals(typeof(double)) || c.Equals(typeof(float)) || - c.Equals(typeof(bool))) - { - writeName(name, output); - output.print(val.ToString()); - } - else if(c.Equals(typeof(string))) - { - writeName(name, output); - output.print("\""); - output.print(val.ToString()); - output.print("\""); - } - else if(val is CollectionBase) - { - int n = 0; - IEnumerator i = ((CollectionBase)val).GetEnumerator(); - while(i.MoveNext()) - { - string elem = (name != null ? name : ""); - elem += "[" + n++ + "]"; - writeValue(elem, i.Current, objectTable, output); - } - } - else if(val is DictionaryBase) - { - foreach(DictionaryEntry entry in (Hashtable)val) - { - string elem = name != null ? name + "." : ""; - writeValue(elem + "key", entry.Key, objectTable, output); - writeValue(elem + "value", entry.Value, objectTable, output); - } - } - else if(val is Ice.ObjectPrxHelperBase) - { - writeName(name, output); - Ice.ObjectPrxHelperBase proxy = (Ice.ObjectPrxHelperBase)val; - output.print(proxy.reference__().ToString()); - } - else if(val is Ice.Object) - { - // - // Check for recursion. - // - if(objectTable != null && objectTable.Contains(val)) - { - writeName(name, output); - output.print("(recursive)"); - } - else - { - if(objectTable == null) - { - objectTable = new Hashtable(); - } - objectTable[val] = null; - writeFields(name, val, c, objectTable, output); - } - } - else if(c.IsEnum) - { - writeName(name, output); - output.print(val.ToString()); - } - else - { - // - // Must be struct. - // - writeFields(name, val, c, objectTable, output); - } - } - } - - private static void writeFields(string name, object obj, System.Type c, Hashtable objectTable, - OutputBase output) - { - if(!c.Equals(typeof(object))) - { - // - // Write the superclass first. - // - writeFields(name, obj, c.BaseType, objectTable, output); - - // - // Write the declared fields of the given class. - // - FieldInfo[] fields = - c.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); + public static void write(object obj, OutputBase output) + { + writeValue(null, obj, null, output); + } + + private static void writeValue(string name, object val, Hashtable objectTable, OutputBase output) + { + if(val == null) + { + writeName(name, output); + output.print("(null)"); + } + else + { + System.Type c = val.GetType(); + if(c.Equals(typeof(byte)) || c.Equals(typeof(short)) || c.Equals(typeof(int)) || + c.Equals(typeof(long)) || c.Equals(typeof(double)) || c.Equals(typeof(float)) || + c.Equals(typeof(bool))) + { + writeName(name, output); + output.print(val.ToString()); + } + else if(c.Equals(typeof(string))) + { + writeName(name, output); + output.print("\""); + output.print(val.ToString()); + output.print("\""); + } + else if(val is CollectionBase) + { + int n = 0; + IEnumerator i = ((CollectionBase)val).GetEnumerator(); + while(i.MoveNext()) + { + string elem = (name != null ? name : ""); + elem += "[" + n++ + "]"; + writeValue(elem, i.Current, objectTable, output); + } + } + else if(val is DictionaryBase) + { + foreach(DictionaryEntry entry in (Hashtable)val) + { + string elem = name != null ? name + "." : ""; + writeValue(elem + "key", entry.Key, objectTable, output); + writeValue(elem + "value", entry.Value, objectTable, output); + } + } + else if(val is Ice.ObjectPrxHelperBase) + { + writeName(name, output); + Ice.ObjectPrxHelperBase proxy = (Ice.ObjectPrxHelperBase)val; + output.print(proxy.reference__().ToString()); + } + else if(val is Ice.Object) + { + // + // Check for recursion. + // + if(objectTable != null && objectTable.Contains(val)) + { + writeName(name, output); + output.print("(recursive)"); + } + else + { + if(objectTable == null) + { + objectTable = new Hashtable(); + } + objectTable[val] = null; + writeFields(name, val, c, objectTable, output); + } + } + else if(c.IsEnum) + { + writeName(name, output); + output.print(val.ToString()); + } + else + { + // + // Must be struct. + // + writeFields(name, val, c, objectTable, output); + } + } + } + + private static void writeFields(string name, object obj, System.Type c, Hashtable objectTable, + OutputBase output) + { + if(!c.Equals(typeof(object))) + { + // + // Write the superclass first. + // + writeFields(name, obj, c.BaseType, objectTable, output); + + // + // Write the declared fields of the given class. + // + FieldInfo[] fields = + c.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); - for(int i = 0; i < fields.Length; i++) - { - string fieldName = (name != null ? name + '.' + fields[i].Name : fields[i].Name); - - try - { - object val = fields[i].GetValue(obj); - writeValue(fieldName, val, objectTable, output); - } - catch(System.UnauthorizedAccessException) - { - Debug.Assert(false); - } - } - } - } - - private static void writeName(string name, OutputBase output) - { - if(name != null) - { - output.nl(); - output.print(name + " = "); - } - } + for(int i = 0; i < fields.Length; i++) + { + string fieldName = (name != null ? name + '.' + fields[i].Name : fields[i].Name); + + try + { + object val = fields[i].GetValue(obj); + writeValue(fieldName, val, objectTable, output); + } + catch(System.UnauthorizedAccessException) + { + Debug.Assert(false); + } + } + } + } + + private static void writeName(string name, OutputBase output) + { + if(name != null) + { + output.nl(); + output.print(name + " = "); + } + } } } diff --git a/cs/src/Ice/XMLOutput.cs b/cs/src/Ice/XMLOutput.cs index 557e123b927..7a57537f451 100755 --- a/cs/src/Ice/XMLOutput.cs +++ b/cs/src/Ice/XMLOutput.cs @@ -17,273 +17,273 @@ using System.Diagnostics; public class XMLOutput : OutputBase { public XMLOutput() - : base() + : base() { - elementStack_ = new Stack(); - se_ = false; - text_ = false; - sgml_ = false; - escape_ = false; + elementStack_ = new Stack(); + se_ = false; + text_ = false; + sgml_ = false; + escape_ = false; } public XMLOutput(StreamWriter writer) - : base(writer) + : base(writer) { - elementStack_ = new Stack(); - se_ = false; - text_ = false; - sgml_ = false; - escape_ = false; + elementStack_ = new Stack(); + se_ = false; + text_ = false; + sgml_ = false; + escape_ = false; } public XMLOutput(string s) - : base(s) + : base(s) { - elementStack_ = new Stack(); - se_ = false; - text_ = false; - sgml_ = false; - escape_ = false; + elementStack_ = new Stack(); + se_ = false; + text_ = false; + sgml_ = false; + escape_ = false; } virtual public void setSGML(bool sgml) { - sgml_ = true; + sgml_ = true; } public override void print(string s) { - if(se_) - { - out_.Write(">"); - se_ = false; - } - text_ = true; - - if(escape_) - { - string escaped = escape(s); - base.print(escaped); - } - else - { - base.print(s); - } + if(se_) + { + out_.Write(">"); + se_ = false; + } + text_ = true; + + if(escape_) + { + string escaped = escape(s); + base.print(escaped); + } + else + { + base.print(s); + } } public virtual XMLOutput write(string s) { - print(s); - return this; + print(s); + return this; } public override void nl() { - if(se_) - { - se_ = false; - out_.Write(">"); - } - base.nl(); + if(se_) + { + se_ = false; + out_.Write(">"); + } + base.nl(); } public virtual XMLOutput se(string element) { - nl(); - - // - // If we're not in SGML mode the output of the '>' character is - // deferred until either the end-element (in which case a /> is - // emitted) or until something is displayed. - // - if(escape_) - { - out_.Write('<'); - out_.Write(escape(element)); - } - else - { - out_.Write('<'); - out_.Write(element); - } - se_ = true; - text_ = false; - - int pos = element.IndexOf(' '); - if (pos == - 1) - { - pos = element.IndexOf('\t'); - } - if (pos == - 1) - { - elementStack_.Push(element); - } - else - { - elementStack_.Push(element.Substring(0, pos - 1)); - } - - ++pos_; // TODO: ??? - inc(); - separator_ = false; - return this; + nl(); + + // + // If we're not in SGML mode the output of the '>' character is + // deferred until either the end-element (in which case a /> is + // emitted) or until something is displayed. + // + if(escape_) + { + out_.Write('<'); + out_.Write(escape(element)); + } + else + { + out_.Write('<'); + out_.Write(element); + } + se_ = true; + text_ = false; + + int pos = element.IndexOf(' '); + if (pos == - 1) + { + pos = element.IndexOf('\t'); + } + if (pos == - 1) + { + elementStack_.Push(element); + } + else + { + elementStack_.Push(element.Substring(0, pos - 1)); + } + + ++pos_; // TODO: ??? + inc(); + separator_ = false; + return this; } public virtual XMLOutput ee() { - string element = (string)elementStack_.Pop(); + string element = (string)elementStack_.Pop(); - dec(); - if(se_) - { - // - // SGML (docbook) doesn't support <foo/> - // - if(sgml_) - { - out_.Write("></"); - out_.Write(element); - out_.Write(">"); - } - else - { - out_.Write("/>"); - } - } - else - { - if(!text_) - { - nl(); - } - out_.Write("</"); - out_.Write(element); - out_.Write(">"); - } - --pos_; // TODO: ??? + dec(); + if(se_) + { + // + // SGML (docbook) doesn't support <foo/> + // + if(sgml_) + { + out_.Write("></"); + out_.Write(element); + out_.Write(">"); + } + else + { + out_.Write("/>"); + } + } + else + { + if(!text_) + { + nl(); + } + out_.Write("</"); + out_.Write(element); + out_.Write(">"); + } + --pos_; // TODO: ??? - se_ = false; - text_ = false; - return this; + se_ = false; + text_ = false; + return this; } public virtual XMLOutput attr(string name, string val) { - // - // Precondition: Attributes can only be attached to elements. - // - Debug.Assert(se_); - out_.Write(" "); - out_.Write(name); - out_.Write("=\""); - out_.Write(escape(val)); - out_.Write("\""); - return this; + // + // Precondition: Attributes can only be attached to elements. + // + Debug.Assert(se_); + out_.Write(" "); + out_.Write(name); + out_.Write("=\""); + out_.Write(escape(val)); + out_.Write("\""); + return this; } public virtual XMLOutput startEscapes() { - escape_ = true; - return this; + escape_ = true; + return this; } public virtual XMLOutput endEscapes() { - escape_ = false; - return this; + escape_ = false; + return this; } public virtual string currentElement() { - if(elementStack_.Count > 0) - { - return (string)elementStack_.Peek(); - } - else - { - return ""; - } + if(elementStack_.Count > 0) + { + return (string)elementStack_.Peek(); + } + else + { + return ""; + } } private string escape(string input) { - string v = input; - - // - // Find out whether there is a reserved character to avoid - // conversion if not necessary. - // - string allReserved = "<>'\"&"; - bool hasReserved = false; - char[] arr = input.ToCharArray(); - for(int i = 0; i < arr.Length; i++) - { - if(allReserved.IndexOf((char)arr[i]) != - 1) - { - hasReserved = true; - break; - } - } - if(hasReserved) - { - int index; + string v = input; + + // + // Find out whether there is a reserved character to avoid + // conversion if not necessary. + // + string allReserved = "<>'\"&"; + bool hasReserved = false; + char[] arr = input.ToCharArray(); + for(int i = 0; i < arr.Length; i++) + { + if(allReserved.IndexOf((char)arr[i]) != - 1) + { + hasReserved = true; + break; + } + } + if(hasReserved) + { + int index; - // - // First convert all & to & - // - index = v.IndexOf('&'); - if(index != - 1) - { - v = v.Insert(index, "amp;"); - } - - // - // Next convert remaining reserved characters. - // - index = v.IndexOf('>'); - if(index != - 1) - { - string tmp = v.Substring(0, index); - tmp += ">"; - tmp += v.Substring(index + 1); - v = tmp; - } - index = v.IndexOf('<'); - if(index != -1) - { - string tmp = v.Substring(0, index); - tmp += "<"; - tmp += v.Substring(index + 1); - v = tmp; - } - index = v.IndexOf('\''); - if(index != -1) - { - string tmp = v.Substring(0, index); - tmp += "'"; - tmp += v.Substring(index + 1); - v = tmp; - } - index = v.IndexOf('"'); - if(index != -1) - { - string tmp = v.Substring(0, index); - tmp += """; - tmp += v.Substring(index + 1); - } - } - return v; + // + // First convert all & to & + // + index = v.IndexOf('&'); + if(index != - 1) + { + v = v.Insert(index, "amp;"); + } + + // + // Next convert remaining reserved characters. + // + index = v.IndexOf('>'); + if(index != - 1) + { + string tmp = v.Substring(0, index); + tmp += ">"; + tmp += v.Substring(index + 1); + v = tmp; + } + index = v.IndexOf('<'); + if(index != -1) + { + string tmp = v.Substring(0, index); + tmp += "<"; + tmp += v.Substring(index + 1); + v = tmp; + } + index = v.IndexOf('\''); + if(index != -1) + { + string tmp = v.Substring(0, index); + tmp += "'"; + tmp += v.Substring(index + 1); + v = tmp; + } + index = v.IndexOf('"'); + if(index != -1) + { + string tmp = v.Substring(0, index); + tmp += """; + tmp += v.Substring(index + 1); + } + } + return v; } private Stack elementStack_; diff --git a/cs/src/IceBox/AssemblyInfo.cs b/cs/src/IceBox/AssemblyInfo.cs index 0c889e35d80..33ad09e8ea4 100755 --- a/cs/src/IceBox/AssemblyInfo.cs +++ b/cs/src/IceBox/AssemblyInfo.cs @@ -20,6 +20,6 @@ using System.Runtime.CompilerServices; [assembly: AssemblyProduct("IceBox for C#")] [assembly: AssemblyCopyright("Copyright (c) 2003-2007, ZeroC, Inc.")] [assembly: AssemblyTrademark("Ice")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.51")] [assembly: AssemblyDelaySign(false)] diff --git a/cs/src/IceBox/Server.cs b/cs/src/IceBox/Server.cs index 56d97844767..72ebcaf5373 100644 --- a/cs/src/IceBox/Server.cs +++ b/cs/src/IceBox/Server.cs @@ -22,29 +22,29 @@ public class Server : Ice.Application public override int run(string[] args) { - for(int i = 0; i < args.Length; ++i) - { - if(args[i].Equals("-h") || args[i].Equals("--help")) - { - usage(); - return 0; - } - else if(!args[i].StartsWith("--")) - { - Console.Error.WriteLine("Server: unknown option `" + args[i] + "'"); - usage(); - return 1; - } - } + for(int i = 0; i < args.Length; ++i) + { + if(args[i].Equals("-h") || args[i].Equals("--help")) + { + usage(); + return 0; + } + else if(!args[i].StartsWith("--")) + { + Console.Error.WriteLine("Server: unknown option `" + args[i] + "'"); + usage(); + return 1; + } + } - ServiceManagerI serviceManagerImpl = new ServiceManagerI(args); - return serviceManagerImpl.run(); + ServiceManagerI serviceManagerImpl = new ServiceManagerI(args); + return serviceManagerImpl.run(); } public static void Main(string[] args) { - Server server = new Server(); - int status = server.main(args); + Server server = new Server(); + int status = server.main(args); if(status != 0) { System.Environment.Exit(status); diff --git a/cs/src/IceBox/ServiceManagerI.cs b/cs/src/IceBox/ServiceManagerI.cs index 034df0888ba..90260d49bc4 100644 --- a/cs/src/IceBox/ServiceManagerI.cs +++ b/cs/src/IceBox/ServiceManagerI.cs @@ -18,588 +18,588 @@ class ServiceManagerI : IceBox.ServiceManagerDisp_ { public ServiceManagerI(string[] args) { - _logger = Ice.Application.communicator().getLogger(); - _argv = args; + _logger = Ice.Application.communicator().getLogger(); + _argv = args; } public override Ice.SliceChecksumDict getSliceChecksums(Ice.Current current) { - return Ice.SliceChecksums.checksums; + return Ice.SliceChecksums.checksums; } public override void startService(string name, Ice.Current current) { lock(this) - { - // - // Search would be more efficient if services were contained in - // a map, but order is required for shutdown. - // - for(int i = 0; i < _services.Count; ++i) - { - ServiceInfo info = (ServiceInfo)_services[i]; - if(info.name.Equals(name)) - { - if(info.active) - { - throw new IceBox.AlreadyStartedException(); - } - - try - { - info.service.start(info.name, info.communicator == null ? Ice.Application.communicator() - : info.communicator, info.args); - info.active = true; - _services[i] = info; - } - catch(Exception e) - { - _logger.warning("ServiceManager: exception in start for service " + info.name + "\n" + - e.ToString()); - } - - return; - } - } - - throw new IceBox.NoSuchServiceException(); - } + { + // + // Search would be more efficient if services were contained in + // a map, but order is required for shutdown. + // + for(int i = 0; i < _services.Count; ++i) + { + ServiceInfo info = (ServiceInfo)_services[i]; + if(info.name.Equals(name)) + { + if(info.active) + { + throw new IceBox.AlreadyStartedException(); + } + + try + { + info.service.start(info.name, info.communicator == null ? Ice.Application.communicator() + : info.communicator, info.args); + info.active = true; + _services[i] = info; + } + catch(Exception e) + { + _logger.warning("ServiceManager: exception in start for service " + info.name + "\n" + + e.ToString()); + } + + return; + } + } + + throw new IceBox.NoSuchServiceException(); + } } public override void stopService(string name, Ice.Current current) { lock(this) - { - // - // Search would be more efficient if services were contained in - // a map, but order is required for shutdown. - // - for(int i = 0; i < _services.Count; ++i) - { - ServiceInfo info = (ServiceInfo)_services[i]; - if(info.name.Equals(name)) - { - if(!info.active) - { - throw new IceBox.AlreadyStoppedException(); - } - - try - { - info.service.stop(); - info.active = false; - _services[i] = info; - } - catch(Exception e) - { - _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + - e.ToString()); - } - - return; - } - } - - throw new IceBox.NoSuchServiceException(); - } + { + // + // Search would be more efficient if services were contained in + // a map, but order is required for shutdown. + // + for(int i = 0; i < _services.Count; ++i) + { + ServiceInfo info = (ServiceInfo)_services[i]; + if(info.name.Equals(name)) + { + if(!info.active) + { + throw new IceBox.AlreadyStoppedException(); + } + + try + { + info.service.stop(); + info.active = false; + _services[i] = info; + } + catch(Exception e) + { + _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + + e.ToString()); + } + + return; + } + } + + throw new IceBox.NoSuchServiceException(); + } } public override void shutdown(Ice.Current current) { - Ice.Application.communicator().shutdown(); + Ice.Application.communicator().shutdown(); } public int run() { - try - { - // - // Create an object adapter. Services probably should NOT share - // this object adapter, as the endpoint(s) for this object adapter - // will most likely need to be firewalled for security reasons. - // - Ice.ObjectAdapter adapter = Ice.Application.communicator().createObjectAdapter("IceBox.ServiceManager"); - - Ice.Properties properties = Ice.Application.communicator().getProperties(); - - Ice.Identity identity = new Ice.Identity(); - identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox"); - identity.name = "ServiceManager"; - adapter.add(this, identity); - - // - // Parse the IceBox.LoadOrder property. - // - string order = properties.getProperty("IceBox.LoadOrder"); - string[] loadOrder = null; - if(order.Length > 0) - { - char[] seperators = { ',', '\t', ' ' }; - loadOrder = order.Trim().Split(seperators); - } - - // - // Load and start the services defined in the property set - // with the prefix "IceBox.Service.". These properties should - // have the following format: - // - // IceBox.Service.Foo=Package.Foo [args] - // - // We load the services specified in IceBox.LoadOrder first, - // then load any remaining services. - // - string prefix = "IceBox.Service."; - Ice.PropertyDict services = properties.getPropertiesForPrefix(prefix); - if(loadOrder != null) - { - for(int i = 0; i < loadOrder.Length; ++i) - { - if(loadOrder[i].Length > 0) - { - string key = prefix + loadOrder[i]; - string value = services[key]; - if(value == null) - { - IceBox.FailureException ex = new IceBox.FailureException(); - ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'"; - throw ex; - } - load(loadOrder[i], value); - services.Remove(key); - } - } - } - - foreach(DictionaryEntry entry in services) - { - string name = ((string)entry.Key).Substring(prefix.Length); - string value = (string)entry.Value; - load(name, value); - } - - // - // We may want to notify external scripts that the services - // have started. This is done by defining the property: - // - // IceBox.PrintServicesReady=bundleName - // - // Where bundleName is whatever you choose to call this set of - // services. It will be echoed back as "bundleName ready". - // - // This must be done after start() has been invoked on the - // services. - // - string bundleName = properties.getProperty("IceBox.PrintServicesReady"); - if(bundleName.Length > 0) - { - Console.Out.WriteLine(bundleName + " ready"); - } - - // - // Don't move after the adapter activation. This allows - // applications to wait for the service manager to be - // reachable before sending a signal to shutdown the - // IceBox. - // - Ice.Application.shutdownOnInterrupt(); - - // - // Start request dispatching after we've started the services. - // - try - { - adapter.activate(); - } - catch(Ice.ObjectAdapterDeactivatedException) - { - // - // Expected if the communicator has been shutdown. - // - } - - Ice.Application.communicator().waitForShutdown(); - // XXX: - //Ice.Application.defaultInterrupt(); - - // - // Invoke stop() on the services. - // - stopAll(); - } - catch(IceBox.FailureException ex) - { - _logger.error(ex.ToString()); - stopAll(); - return 1; - } - catch(Ice.LocalException ex) - { - _logger.error("ServiceManager: " + ex.ToString()); - stopAll(); - return 1; - } - catch(Exception ex) - { - _logger.error("ServiceManager: unknown exception\n" + ex.ToString()); - stopAll(); - return 1; - } - - return 0; + try + { + // + // Create an object adapter. Services probably should NOT share + // this object adapter, as the endpoint(s) for this object adapter + // will most likely need to be firewalled for security reasons. + // + Ice.ObjectAdapter adapter = Ice.Application.communicator().createObjectAdapter("IceBox.ServiceManager"); + + Ice.Properties properties = Ice.Application.communicator().getProperties(); + + Ice.Identity identity = new Ice.Identity(); + identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox"); + identity.name = "ServiceManager"; + adapter.add(this, identity); + + // + // Parse the IceBox.LoadOrder property. + // + string order = properties.getProperty("IceBox.LoadOrder"); + string[] loadOrder = null; + if(order.Length > 0) + { + char[] seperators = { ',', '\t', ' ' }; + loadOrder = order.Trim().Split(seperators); + } + + // + // Load and start the services defined in the property set + // with the prefix "IceBox.Service.". These properties should + // have the following format: + // + // IceBox.Service.Foo=Package.Foo [args] + // + // We load the services specified in IceBox.LoadOrder first, + // then load any remaining services. + // + string prefix = "IceBox.Service."; + Ice.PropertyDict services = properties.getPropertiesForPrefix(prefix); + if(loadOrder != null) + { + for(int i = 0; i < loadOrder.Length; ++i) + { + if(loadOrder[i].Length > 0) + { + string key = prefix + loadOrder[i]; + string value = services[key]; + if(value == null) + { + IceBox.FailureException ex = new IceBox.FailureException(); + ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'"; + throw ex; + } + load(loadOrder[i], value); + services.Remove(key); + } + } + } + + foreach(DictionaryEntry entry in services) + { + string name = ((string)entry.Key).Substring(prefix.Length); + string value = (string)entry.Value; + load(name, value); + } + + // + // We may want to notify external scripts that the services + // have started. This is done by defining the property: + // + // IceBox.PrintServicesReady=bundleName + // + // Where bundleName is whatever you choose to call this set of + // services. It will be echoed back as "bundleName ready". + // + // This must be done after start() has been invoked on the + // services. + // + string bundleName = properties.getProperty("IceBox.PrintServicesReady"); + if(bundleName.Length > 0) + { + Console.Out.WriteLine(bundleName + " ready"); + } + + // + // Don't move after the adapter activation. This allows + // applications to wait for the service manager to be + // reachable before sending a signal to shutdown the + // IceBox. + // + Ice.Application.shutdownOnInterrupt(); + + // + // Start request dispatching after we've started the services. + // + try + { + adapter.activate(); + } + catch(Ice.ObjectAdapterDeactivatedException) + { + // + // Expected if the communicator has been shutdown. + // + } + + Ice.Application.communicator().waitForShutdown(); + // XXX: + //Ice.Application.defaultInterrupt(); + + // + // Invoke stop() on the services. + // + stopAll(); + } + catch(IceBox.FailureException ex) + { + _logger.error(ex.ToString()); + stopAll(); + return 1; + } + catch(Ice.LocalException ex) + { + _logger.error("ServiceManager: " + ex.ToString()); + stopAll(); + return 1; + } + catch(Exception ex) + { + _logger.error("ServiceManager: unknown exception\n" + ex.ToString()); + stopAll(); + return 1; + } + + return 0; } private void load(string name, string value) { - // - // Separate the entry point from the arguments. - // - string entryPoint = value; - string[] args = new string[0]; - int start = value.IndexOf(':'); - if(start != -1) - { - // - // Find the whitespace. - // - int pos = value.IndexOf(' ', start); - if(pos == -1) - { - pos = value.IndexOf('\t', start); - } - if(pos == -1) - { - pos = value.IndexOf('\n', start); - } - if(pos != -1) - { - entryPoint = value.Substring(0, pos); - try - { - args = IceUtil.Options.split(value.Substring(pos)); - } - catch(IceUtil.Options.BadQuote ex) - { - IceBox.FailureException e = new IceBox.FailureException(); - e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.ToString(); - throw e; - } - } - } - - startService(name, entryPoint, args); + // + // Separate the entry point from the arguments. + // + string entryPoint = value; + string[] args = new string[0]; + int start = value.IndexOf(':'); + if(start != -1) + { + // + // Find the whitespace. + // + int pos = value.IndexOf(' ', start); + if(pos == -1) + { + pos = value.IndexOf('\t', start); + } + if(pos == -1) + { + pos = value.IndexOf('\n', start); + } + if(pos != -1) + { + entryPoint = value.Substring(0, pos); + try + { + args = IceUtil.Options.split(value.Substring(pos)); + } + catch(IceUtil.Options.BadQuote ex) + { + IceBox.FailureException e = new IceBox.FailureException(); + e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.ToString(); + throw e; + } + } + } + + startService(name, entryPoint, args); } private void startService(string service, string entryPoint, string[] args) { lock(this) - { - // - // Create the service property set from the service arguments - // and the server arguments. The service property set will be - // used to create a new communicator, or will be added to the - // shared communicator, depending on the value of the - // IceBox.UseSharedCommunicator property. - // - ArrayList l = new ArrayList(); - for(int j = 0; j < args.Length; j++) - { - l.Add(args[j]); - } - for(int j = 0; j < _argv.Length; j++) - { - if(_argv[j].StartsWith("--" + service + ".")) - { - l.Add(_argv[j]); - } - } - - // - // Instantiate the class. - // - ServiceInfo info = new ServiceInfo(); - info.name = service; - info.args = (string[])l.ToArray(typeof(string)); - - // - // Retrieve the assembly name and the type. - // - string err = "ServiceManager: unable to load service '" + entryPoint + "': "; - int sepPos = entryPoint.IndexOf(':'); - if (sepPos == -1) - { - IceBox.FailureException e = new IceBox.FailureException(); - e.reason = err + "invalid entry point format: " + entryPoint; - throw e; - } - - System.Reflection.Assembly serviceAssembly = null; - string assemblyName = entryPoint.Substring(0, sepPos); - try - { - if (System.IO.File.Exists(assemblyName)) - { - serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName); - } - else - { - serviceAssembly = System.Reflection.Assembly.Load(assemblyName); - } - } - catch(System.Exception ex) - { - IceBox.FailureException e = new IceBox.FailureException(ex); - e.reason = err + "unable to load assembly: " + assemblyName; - throw e; - } - - // - // Instantiate the class. - // - string className = entryPoint.Substring(sepPos + 1); - System.Type c = serviceAssembly.GetType(className); - if(c == null) - { - IceBox.FailureException e = new IceBox.FailureException(); - e.reason = err + "GetType failed for '" + className + "'"; - throw e; - } - - try - { - info.service = (IceBox.Service)IceInternal.AssemblyUtil.createInstance(c); - if(info.service == null) - { - IceBox.FailureException e = new IceBox.FailureException(); - e.reason = err + "Can't find constructor for '" + className + "'"; - throw e; - } - } - catch(System.InvalidCastException ex) - { - IceBox.FailureException e = new IceBox.FailureException(ex); - e.reason = err + "InvalidCastException to Ice.PluginFactory"; - throw e; - } - catch(System.UnauthorizedAccessException ex) - { - IceBox.FailureException e = new IceBox.FailureException(ex); - e.reason = err + "UnauthorizedAccessException"; - throw e; - } - catch(System.Exception ex) - { - IceBox.FailureException e = new IceBox.FailureException(ex); - e.reason = err + "System.Exception"; - throw e; - } - - // - // Invoke Service::start(). - // - try - { - // - // If Ice.UseSharedCommunicator.<name> is defined, create a - // communicator for the service. The communicator inherits - // from the shared communicator properties. If it's not - // defined, add the service properties to the shared - // commnunicator property set. - // - Ice.Properties properties = Ice.Application.communicator().getProperties(); - if(properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) - { - Ice.Properties serviceProperties = Ice.Util.createProperties(ref info.args, properties); - - // - // Erase properties in 'properties' - // - Ice.PropertyDict allProps = properties.getPropertiesForPrefix(""); - foreach(string key in allProps.Keys) - { - if(serviceProperties.getProperty(key).Length == 0) - { - properties.setProperty(key, ""); - } - } - - // - // Put all serviceProperties into 'properties' - // - properties.parseCommandLineOptions("", serviceProperties.getCommandLineOptions()); - - // - // Parse <service>.* command line options - // (the Ice command line options were parse by the createProperties above) - // - info.args = properties.parseCommandLineOptions(service, info.args); - } - else - { - string name = properties.getProperty("Ice.ProgramName"); - Ice.Properties serviceProperties; - if(properties.getPropertyAsInt("IceBox.InheritContainerProperties") > 0) - { - serviceProperties = Ice.Util.createProperties(ref info.args, properties); - } - else - { - serviceProperties = Ice.Util.createProperties(ref info.args); - } - - if(name.Equals(serviceProperties.getProperty("Ice.ProgramName"))) - { - // - // If the service did not set its own program-name, and - // the icebox program-name != service, append the service name to the - // program name. - // - if(!name.Equals(service)) - { - name = name.Length == 0 ? service : name + "-" + service; - } - serviceProperties.setProperty("Ice.ProgramName", name); - } - - // - // Parse <service>.* command line options. - // (the Ice command line options were parsed by the createProperties above) - // - info.args = serviceProperties.parseCommandLineOptions(service, info.args); - - Ice.InitializationData initData = new Ice.InitializationData(); - initData.properties = serviceProperties; - info.communicator = Ice.Util.initialize(ref info.args, initData); - } - - Ice.Communicator communicator = info.communicator != null ? info.communicator : - Ice.Application.communicator(); - - try - { - info.service.start(service, communicator, info.args); - info.active = true; - } - catch(Exception) - { - if(info.communicator != null) - { - try - { - info.communicator.shutdown(); - info.communicator.waitForShutdown(); - } - catch(Ice.CommunicatorDestroyedException) - { - // - // Ignore, the service might have already destroyed - // the communicator for its own reasons. - // - } - catch(Exception e) - { - _logger.warning("ServiceManager: exception in shutting down communicator for service " - + service + "\n" + e.ToString()); - } - - try - { - info.communicator.destroy(); - } - catch(Exception e) - { - _logger.warning("ServiceManager: exception in destroying communciator for service" - + service + "\n" + e.ToString()); - } - } - throw; - } - - _services.Add(info); - } - catch(IceBox.FailureException) - { - throw; - } - catch(Exception ex) - { - IceBox.FailureException e = new IceBox.FailureException(ex); - e.reason = "ServiceManager: exception while starting service " + service + ": " + ex; - throw e; - } - } + { + // + // Create the service property set from the service arguments + // and the server arguments. The service property set will be + // used to create a new communicator, or will be added to the + // shared communicator, depending on the value of the + // IceBox.UseSharedCommunicator property. + // + ArrayList l = new ArrayList(); + for(int j = 0; j < args.Length; j++) + { + l.Add(args[j]); + } + for(int j = 0; j < _argv.Length; j++) + { + if(_argv[j].StartsWith("--" + service + ".")) + { + l.Add(_argv[j]); + } + } + + // + // Instantiate the class. + // + ServiceInfo info = new ServiceInfo(); + info.name = service; + info.args = (string[])l.ToArray(typeof(string)); + + // + // Retrieve the assembly name and the type. + // + string err = "ServiceManager: unable to load service '" + entryPoint + "': "; + int sepPos = entryPoint.IndexOf(':'); + if (sepPos == -1) + { + IceBox.FailureException e = new IceBox.FailureException(); + e.reason = err + "invalid entry point format: " + entryPoint; + throw e; + } + + System.Reflection.Assembly serviceAssembly = null; + string assemblyName = entryPoint.Substring(0, sepPos); + try + { + if (System.IO.File.Exists(assemblyName)) + { + serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName); + } + else + { + serviceAssembly = System.Reflection.Assembly.Load(assemblyName); + } + } + catch(System.Exception ex) + { + IceBox.FailureException e = new IceBox.FailureException(ex); + e.reason = err + "unable to load assembly: " + assemblyName; + throw e; + } + + // + // Instantiate the class. + // + string className = entryPoint.Substring(sepPos + 1); + System.Type c = serviceAssembly.GetType(className); + if(c == null) + { + IceBox.FailureException e = new IceBox.FailureException(); + e.reason = err + "GetType failed for '" + className + "'"; + throw e; + } + + try + { + info.service = (IceBox.Service)IceInternal.AssemblyUtil.createInstance(c); + if(info.service == null) + { + IceBox.FailureException e = new IceBox.FailureException(); + e.reason = err + "Can't find constructor for '" + className + "'"; + throw e; + } + } + catch(System.InvalidCastException ex) + { + IceBox.FailureException e = new IceBox.FailureException(ex); + e.reason = err + "InvalidCastException to Ice.PluginFactory"; + throw e; + } + catch(System.UnauthorizedAccessException ex) + { + IceBox.FailureException e = new IceBox.FailureException(ex); + e.reason = err + "UnauthorizedAccessException"; + throw e; + } + catch(System.Exception ex) + { + IceBox.FailureException e = new IceBox.FailureException(ex); + e.reason = err + "System.Exception"; + throw e; + } + + // + // Invoke Service::start(). + // + try + { + // + // If Ice.UseSharedCommunicator.<name> is defined, create a + // communicator for the service. The communicator inherits + // from the shared communicator properties. If it's not + // defined, add the service properties to the shared + // commnunicator property set. + // + Ice.Properties properties = Ice.Application.communicator().getProperties(); + if(properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) + { + Ice.Properties serviceProperties = Ice.Util.createProperties(ref info.args, properties); + + // + // Erase properties in 'properties' + // + Ice.PropertyDict allProps = properties.getPropertiesForPrefix(""); + foreach(string key in allProps.Keys) + { + if(serviceProperties.getProperty(key).Length == 0) + { + properties.setProperty(key, ""); + } + } + + // + // Put all serviceProperties into 'properties' + // + properties.parseCommandLineOptions("", serviceProperties.getCommandLineOptions()); + + // + // Parse <service>.* command line options + // (the Ice command line options were parse by the createProperties above) + // + info.args = properties.parseCommandLineOptions(service, info.args); + } + else + { + string name = properties.getProperty("Ice.ProgramName"); + Ice.Properties serviceProperties; + if(properties.getPropertyAsInt("IceBox.InheritContainerProperties") > 0) + { + serviceProperties = Ice.Util.createProperties(ref info.args, properties); + } + else + { + serviceProperties = Ice.Util.createProperties(ref info.args); + } + + if(name.Equals(serviceProperties.getProperty("Ice.ProgramName"))) + { + // + // If the service did not set its own program-name, and + // the icebox program-name != service, append the service name to the + // program name. + // + if(!name.Equals(service)) + { + name = name.Length == 0 ? service : name + "-" + service; + } + serviceProperties.setProperty("Ice.ProgramName", name); + } + + // + // Parse <service>.* command line options. + // (the Ice command line options were parsed by the createProperties above) + // + info.args = serviceProperties.parseCommandLineOptions(service, info.args); + + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = serviceProperties; + info.communicator = Ice.Util.initialize(ref info.args, initData); + } + + Ice.Communicator communicator = info.communicator != null ? info.communicator : + Ice.Application.communicator(); + + try + { + info.service.start(service, communicator, info.args); + info.active = true; + } + catch(Exception) + { + if(info.communicator != null) + { + try + { + info.communicator.shutdown(); + info.communicator.waitForShutdown(); + } + catch(Ice.CommunicatorDestroyedException) + { + // + // Ignore, the service might have already destroyed + // the communicator for its own reasons. + // + } + catch(Exception e) + { + _logger.warning("ServiceManager: exception in shutting down communicator for service " + + service + "\n" + e.ToString()); + } + + try + { + info.communicator.destroy(); + } + catch(Exception e) + { + _logger.warning("ServiceManager: exception in destroying communciator for service" + + service + "\n" + e.ToString()); + } + } + throw; + } + + _services.Add(info); + } + catch(IceBox.FailureException) + { + throw; + } + catch(Exception ex) + { + IceBox.FailureException e = new IceBox.FailureException(ex); + e.reason = "ServiceManager: exception while starting service " + service + ": " + ex; + throw e; + } + } } private void stopAll() { lock(this) - { - // - // First, for each service, we call stop on the service and flush its database environment to - // the disk. Services are stopped in the reverse order of which they were started. - // - _services.Reverse(); - foreach(ServiceInfo info in _services) - { - try - { - info.service.stop(); - } - catch(Exception e) - { - _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + e.ToString()); - } - - if(info.communicator != null) - { - try - { - info.communicator.shutdown(); - info.communicator.waitForShutdown(); - } - catch(Ice.CommunicatorDestroyedException) - { - // - // Ignore, the service might have already destroyed - // the communicator for its own reasons. - // - } - catch(Exception e) - { - _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + - e.ToString()); - } - - try - { - info.communicator.destroy(); - } - catch(Exception e) - { - _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + - e.ToString()); - } - } - } - - _services.Clear(); - } + { + // + // First, for each service, we call stop on the service and flush its database environment to + // the disk. Services are stopped in the reverse order of which they were started. + // + _services.Reverse(); + foreach(ServiceInfo info in _services) + { + try + { + info.service.stop(); + } + catch(Exception e) + { + _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + e.ToString()); + } + + if(info.communicator != null) + { + try + { + info.communicator.shutdown(); + info.communicator.waitForShutdown(); + } + catch(Ice.CommunicatorDestroyedException) + { + // + // Ignore, the service might have already destroyed + // the communicator for its own reasons. + // + } + catch(Exception e) + { + _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + + e.ToString()); + } + + try + { + info.communicator.destroy(); + } + catch(Exception e) + { + _logger.warning("ServiceManager: exception in stop for service " + info.name + "\n" + + e.ToString()); + } + } + } + + _services.Clear(); + } } struct ServiceInfo { public string name; public IceBox.Service service; - public Ice.Communicator communicator; - public bool active; - public string[] args; + public Ice.Communicator communicator; + public bool active; + public string[] args; } private Ice.Logger _logger; diff --git a/cs/src/IceGrid/AssemblyInfo.cs b/cs/src/IceGrid/AssemblyInfo.cs index 7aa597b813e..158dc9832e7 100755 --- a/cs/src/IceGrid/AssemblyInfo.cs +++ b/cs/src/IceGrid/AssemblyInfo.cs @@ -20,6 +20,6 @@ using System.Runtime.CompilerServices; [assembly: AssemblyProduct("IceGrid for C#")] [assembly: AssemblyCopyright("Copyright (c) 2003-2007, ZeroC, Inc.")] [assembly: AssemblyTrademark("Ice")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.51")] [assembly: AssemblyDelaySign(false)] diff --git a/cs/src/IcePatch2/AssemblyInfo.cs b/cs/src/IcePatch2/AssemblyInfo.cs index 8b446ddbec4..198c598dda5 100755 --- a/cs/src/IcePatch2/AssemblyInfo.cs +++ b/cs/src/IcePatch2/AssemblyInfo.cs @@ -20,6 +20,6 @@ using System.Runtime.CompilerServices; [assembly: AssemblyProduct("IcePatch2 for C#")] [assembly: AssemblyCopyright("Copyright (c) 2003-2007, ZeroC, Inc.")] [assembly: AssemblyTrademark("Ice")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.51")] [assembly: AssemblyDelaySign(false)] diff --git a/cs/src/IceSSL/AcceptorI.cs b/cs/src/IceSSL/AcceptorI.cs index 1a4b011da28..2ce09404d5b 100755 --- a/cs/src/IceSSL/AcceptorI.cs +++ b/cs/src/IceSSL/AcceptorI.cs @@ -19,159 +19,159 @@ namespace IceSSL class AcceptorI : IceInternal.Acceptor { - public virtual Socket fd() - { - return fd_; - } - - public virtual void close() - { + public virtual Socket fd() + { + return fd_; + } + + public virtual void close() + { Socket fd; - lock(this) - { - fd = fd_; - fd_ = null; - } - if(fd != null) - { - if(instance_.networkTraceLevel() >= 1) - { - string s = "stopping to accept ssl connections at " + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - - try - { - fd.Close(); - } - catch(System.Exception) - { - // Ignore. - } - } - } - - public virtual void listen() - { - IceInternal.Network.doListen(fd_, backlog_); - - if(instance_.networkTraceLevel() >= 1) - { - string s = "accepting ssl connections at " + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - } - - public virtual IceInternal.Transceiver accept(int timeout) - { - Debug.Assert(timeout == -1); // Always called with -1 for thread-per-connection. + lock(this) + { + fd = fd_; + fd_ = null; + } + if(fd != null) + { + if(instance_.networkTraceLevel() >= 1) + { + string s = "stopping to accept ssl connections at " + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + + try + { + fd.Close(); + } + catch(System.Exception) + { + // Ignore. + } + } + } + + public virtual void listen() + { + IceInternal.Network.doListen(fd_, backlog_); + + if(instance_.networkTraceLevel() >= 1) + { + string s = "accepting ssl connections at " + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + } + + public virtual IceInternal.Transceiver accept(int timeout) + { + Debug.Assert(timeout == -1); // Always called with -1 for thread-per-connection. - // - // The plugin may not be fully initialized. - // - if(!instance_.initialized()) - { - Ice.PluginInitializationException ex = new Ice.PluginInitializationException(); - ex.reason = "IceSSL: plugin is not initialized"; - throw ex; - } + // + // The plugin may not be fully initialized. + // + if(!instance_.initialized()) + { + Ice.PluginInitializationException ex = new Ice.PluginInitializationException(); + ex.reason = "IceSSL: plugin is not initialized"; + throw ex; + } - Socket fd = IceInternal.Network.doAccept(fd_, timeout); - IceInternal.Network.setBlock(fd, true); // SSL requires a blocking socket. + Socket fd = IceInternal.Network.doAccept(fd_, timeout); + IceInternal.Network.setBlock(fd, true); // SSL requires a blocking socket. - if(instance_.networkTraceLevel() >= 1) - { - string s = "attempting to accept ssl connection\n" + IceInternal.Network.fdToString(fd); - logger_.trace(instance_.networkTraceCategory(), s); - } + if(instance_.networkTraceLevel() >= 1) + { + string s = "attempting to accept ssl connection\n" + IceInternal.Network.fdToString(fd); + logger_.trace(instance_.networkTraceCategory(), s); + } - return new TransceiverI(instance_, fd, adapterName_); - } + return new TransceiverI(instance_, fd, adapterName_); + } - public virtual void connectToSelf() - { - Socket fd = IceInternal.Network.createSocket(false); - IceInternal.Network.setBlock(fd, false); - IceInternal.Network.doConnect(fd, addr_, -1); - IceInternal.Network.closeSocket(fd); - } + public virtual void connectToSelf() + { + Socket fd = IceInternal.Network.createSocket(false); + IceInternal.Network.setBlock(fd, false); + IceInternal.Network.doConnect(fd, addr_, -1); + IceInternal.Network.closeSocket(fd); + } - public override string ToString() - { - return IceInternal.Network.addrToString(addr_); - } - - internal bool equivalent(string host, int port) - { - EndPoint addr = IceInternal.Network.getAddress(host, port); - return addr.Equals(addr_); - } + public override string ToString() + { + return IceInternal.Network.addrToString(addr_); + } + + internal bool equivalent(string host, int port) + { + EndPoint addr = IceInternal.Network.getAddress(host, port); + return addr.Equals(addr_); + } - internal virtual int effectivePort() - { - return addr_.Port; - } + internal virtual int effectivePort() + { + return addr_.Port; + } - internal - AcceptorI(Instance instance, string adapterName, string host, int port) - { - instance_ = instance; - adapterName_ = adapterName; - logger_ = instance.communicator().getLogger(); - backlog_ = 0; + internal + AcceptorI(Instance instance, string adapterName, string host, int port) + { + instance_ = instance; + adapterName_ = adapterName; + logger_ = instance.communicator().getLogger(); + backlog_ = 0; - // - // .NET requires that a certificate be supplied. - // - X509Certificate2Collection certs = instance.certs(); - if(certs.Count == 0) - { - Ice.SecurityException ex = new Ice.SecurityException(); - ex.reason = "IceSSL: certificate required for server endpoint"; - throw ex; - } + // + // .NET requires that a certificate be supplied. + // + X509Certificate2Collection certs = instance.certs(); + if(certs.Count == 0) + { + Ice.SecurityException ex = new Ice.SecurityException(); + ex.reason = "IceSSL: certificate required for server endpoint"; + throw ex; + } - if(backlog_ <= 0) - { - backlog_ = 5; - } - - try - { - fd_ = IceInternal.Network.createSocket(false); - IceInternal.Network.setBlock(fd_, false); - addr_ = IceInternal.Network.getAddress(host, port); - if(instance_.networkTraceLevel() >= 2) - { - string s = "attempting to bind to ssl socket " + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - addr_ = IceInternal.Network.doBind(fd_, addr_); - } - catch(System.Exception) - { - fd_ = null; - throw; - } - } - + if(backlog_ <= 0) + { + backlog_ = 5; + } + + try + { + fd_ = IceInternal.Network.createSocket(false); + IceInternal.Network.setBlock(fd_, false); + addr_ = IceInternal.Network.getAddress(host, port); + if(instance_.networkTraceLevel() >= 2) + { + string s = "attempting to bind to ssl socket " + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + addr_ = IceInternal.Network.doBind(fd_, addr_); + } + catch(System.Exception) + { + fd_ = null; + throw; + } + } + #if DEBUG - ~AcceptorI() - { - /* - lock(this) - { - IceUtil.Assert.FinalizerAssert(fd_ == null); - } - */ - } + ~AcceptorI() + { + /* + lock(this) + { + IceUtil.Assert.FinalizerAssert(fd_ == null); + } + */ + } #endif - private Instance instance_; - private string adapterName_; - private Ice.Logger logger_; - private Socket fd_; - private int backlog_; - private IPEndPoint addr_; + private Instance instance_; + private string adapterName_; + private Ice.Logger logger_; + private Socket fd_; + private int backlog_; + private IPEndPoint addr_; } } diff --git a/cs/src/IceSSL/AssemblyInfo.cs b/cs/src/IceSSL/AssemblyInfo.cs index 00dc3c97433..d1657993242 100755 --- a/cs/src/IceSSL/AssemblyInfo.cs +++ b/cs/src/IceSSL/AssemblyInfo.cs @@ -20,6 +20,6 @@ using System.Runtime.CompilerServices; [assembly: AssemblyProduct("IceSSL for C#")] [assembly: AssemblyCopyright("Copyright (c) 2003-2007, ZeroC, Inc.")] [assembly: AssemblyTrademark("Ice")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.51")] [assembly: AssemblyDelaySign(false)] diff --git a/cs/src/IceSSL/ConnectorI.cs b/cs/src/IceSSL/ConnectorI.cs index 2f063b52692..31b586cc3c3 100755 --- a/cs/src/IceSSL/ConnectorI.cs +++ b/cs/src/IceSSL/ConnectorI.cs @@ -20,261 +20,261 @@ namespace IceSSL sealed class ConnectorI : IceInternal.Connector { - public IceInternal.Transceiver connect(int timeout) - { - // - // The plugin may not be fully initialized. - // - if(!instance_.initialized()) - { - Ice.PluginInitializationException ex = new Ice.PluginInitializationException(); - ex.reason = "IceSSL: plugin is not initialized"; - throw ex; - } + public IceInternal.Transceiver connect(int timeout) + { + // + // The plugin may not be fully initialized. + // + if(!instance_.initialized()) + { + Ice.PluginInitializationException ex = new Ice.PluginInitializationException(); + ex.reason = "IceSSL: plugin is not initialized"; + throw ex; + } - if(instance_.networkTraceLevel() >= 2) - { - string s = "trying to establish ssl connection to " + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } + if(instance_.networkTraceLevel() >= 2) + { + string s = "trying to establish ssl connection to " + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } - Socket fd = IceInternal.Network.createSocket(false); - IceInternal.Network.setBlock(fd, true); - IceInternal.Network.doConnectAsync(fd, addr_, timeout); + Socket fd = IceInternal.Network.createSocket(false); + IceInternal.Network.setBlock(fd, true); + IceInternal.Network.doConnectAsync(fd, addr_, timeout); - SslStream stream = null; - ConnectionInfo connInfo = null; - try - { - // - // Create an SslStream. - // - NetworkStream ns = new NetworkStream(fd, true); - ConnectorValidationCallback cb = new ConnectorValidationCallback(this); - stream = new SslStream(ns, false, new RemoteCertificateValidationCallback(cb.validate), null); + SslStream stream = null; + ConnectionInfo connInfo = null; + try + { + // + // Create an SslStream. + // + NetworkStream ns = new NetworkStream(fd, true); + ConnectorValidationCallback cb = new ConnectorValidationCallback(this); + stream = new SslStream(ns, false, new RemoteCertificateValidationCallback(cb.validate), null); - // - // Start the validation process and wait for it to complete. - // - AuthInfo info = new AuthInfo(); - info.stream = stream; - info.done = false; - stream.BeginAuthenticateAsClient(host_, instance_.certs(), instance_.protocols(), - instance_.checkCRL(), - new AsyncCallback(authCallback), info); - lock(info) - { - if(!info.done) - { - if(!Monitor.Wait(info, timeout == -1 ? Timeout.Infinite : timeout)) - { - throw new Ice.ConnectTimeoutException("SSL authentication timed out after " + timeout + - " msec"); - } - } - if(info.ex != null) - { - throw info.ex; - } - } + // + // Start the validation process and wait for it to complete. + // + AuthInfo info = new AuthInfo(); + info.stream = stream; + info.done = false; + stream.BeginAuthenticateAsClient(host_, instance_.certs(), instance_.protocols(), + instance_.checkCRL(), + new AsyncCallback(authCallback), info); + lock(info) + { + if(!info.done) + { + if(!Monitor.Wait(info, timeout == -1 ? Timeout.Infinite : timeout)) + { + throw new Ice.ConnectTimeoutException("SSL authentication timed out after " + timeout + + " msec"); + } + } + if(info.ex != null) + { + throw info.ex; + } + } - connInfo = Util.populateConnectionInfo(stream, fd, cb.certs, "", false); - instance_.verifyPeer(connInfo, fd, false); - } - catch(Ice.LocalException ex) - { - if(stream != null) - { - stream.Close(); - } - else - { - IceInternal.Network.closeSocketNoThrow(fd); - } + connInfo = Util.populateConnectionInfo(stream, fd, cb.certs, "", false); + instance_.verifyPeer(connInfo, fd, false); + } + catch(Ice.LocalException ex) + { + if(stream != null) + { + stream.Close(); + } + else + { + IceInternal.Network.closeSocketNoThrow(fd); + } - throw ex; - } - catch(IOException ex) - { - if(stream != null) - { - stream.Close(); - } - else - { - IceInternal.Network.closeSocketNoThrow(fd); - } + throw ex; + } + catch(IOException ex) + { + if(stream != null) + { + stream.Close(); + } + else + { + IceInternal.Network.closeSocketNoThrow(fd); + } - if(IceInternal.Network.connectionLost(ex)) - { - throw new Ice.ConnectionLostException(ex); - } - throw new Ice.SyscallException(ex); - } - catch(AuthenticationException ex) - { - if(stream != null) - { - stream.Close(); - } - else - { - IceInternal.Network.closeSocketNoThrow(fd); - } + if(IceInternal.Network.connectionLost(ex)) + { + throw new Ice.ConnectionLostException(ex); + } + throw new Ice.SyscallException(ex); + } + catch(AuthenticationException ex) + { + if(stream != null) + { + stream.Close(); + } + else + { + IceInternal.Network.closeSocketNoThrow(fd); + } - Ice.SecurityException e = new Ice.SecurityException(ex); - e.reason = ex.Message; - throw e; - } - catch(Exception ex) - { - if(stream != null) - { - stream.Close(); - } - else - { - IceInternal.Network.closeSocketNoThrow(fd); - } + Ice.SecurityException e = new Ice.SecurityException(ex); + e.reason = ex.Message; + throw e; + } + catch(Exception ex) + { + if(stream != null) + { + stream.Close(); + } + else + { + IceInternal.Network.closeSocketNoThrow(fd); + } - throw new Ice.SyscallException(ex); - } + throw new Ice.SyscallException(ex); + } - if(instance_.networkTraceLevel() >= 1) - { - string s = "ssl connection established\n" + IceInternal.Network.fdToString(fd); - logger_.trace(instance_.networkTraceCategory(), s); - } + if(instance_.networkTraceLevel() >= 1) + { + string s = "ssl connection established\n" + IceInternal.Network.fdToString(fd); + logger_.trace(instance_.networkTraceCategory(), s); + } - if(instance_.securityTraceLevel() >= 1) - { - instance_.traceStream(stream, IceInternal.Network.fdToString(fd)); - } + if(instance_.securityTraceLevel() >= 1) + { + instance_.traceStream(stream, IceInternal.Network.fdToString(fd)); + } - return new TransceiverI(instance_, fd, stream, connInfo); - } + return new TransceiverI(instance_, fd, stream, connInfo); + } - public override string ToString() - { - return IceInternal.Network.addrToString(addr_); - } + public override string ToString() + { + return IceInternal.Network.addrToString(addr_); + } - // - // Only for use by EndpointI. - // - internal ConnectorI(Instance instance, string host, int port) - { - instance_ = instance; - host_ = host; - logger_ = instance.communicator().getLogger(); - addr_ = IceInternal.Network.getAddress(host, port); - } + // + // Only for use by EndpointI. + // + internal ConnectorI(Instance instance, string host, int port) + { + instance_ = instance; + host_ = host; + logger_ = instance.communicator().getLogger(); + addr_ = IceInternal.Network.getAddress(host, port); + } - private class AuthInfo - { - internal SslStream stream; - volatile internal Exception ex; - volatile internal bool done; - } + private class AuthInfo + { + internal SslStream stream; + volatile internal Exception ex; + volatile internal bool done; + } - private static void authCallback(IAsyncResult ar) - { - AuthInfo info = (AuthInfo)ar.AsyncState; - lock(info) - { - try - { - info.stream.EndAuthenticateAsClient(ar); - } - catch(Exception ex) - { - info.ex = ex; - } - finally - { - info.done = true; - Monitor.Pulse(info); - } - } - } + private static void authCallback(IAsyncResult ar) + { + AuthInfo info = (AuthInfo)ar.AsyncState; + lock(info) + { + try + { + info.stream.EndAuthenticateAsClient(ar); + } + catch(Exception ex) + { + info.ex = ex; + } + finally + { + info.done = true; + Monitor.Pulse(info); + } + } + } - internal bool validate(object sender, X509Certificate certificate, X509Chain chain, - SslPolicyErrors sslPolicyErrors) - { - string message = ""; - int errors = (int)sslPolicyErrors; - if((errors & (int)SslPolicyErrors.RemoteCertificateNameMismatch) > 0) - { - if(!instance_.checkCertName()) - { - errors ^= (int)SslPolicyErrors.RemoteCertificateNameMismatch; - message = message + "\nremote certificate name mismatch (ignored)"; - } - else - { - if(instance_.securityTraceLevel() >= 1) - { - logger_.trace(instance_.securityTraceCategory(), - "SSL certificate validation failed - remote certificate name mismatch"); - } - return false; - } - } + internal bool validate(object sender, X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + string message = ""; + int errors = (int)sslPolicyErrors; + if((errors & (int)SslPolicyErrors.RemoteCertificateNameMismatch) > 0) + { + if(!instance_.checkCertName()) + { + errors ^= (int)SslPolicyErrors.RemoteCertificateNameMismatch; + message = message + "\nremote certificate name mismatch (ignored)"; + } + else + { + if(instance_.securityTraceLevel() >= 1) + { + logger_.trace(instance_.securityTraceCategory(), + "SSL certificate validation failed - remote certificate name mismatch"); + } + return false; + } + } - // - // The RemoteCertificateNotAvailable case does not appear to be possible - // for an outgoing connection. Since .NET requires an authenticated - // connection, the remote peer closes the socket if it does not have a - // certificate to provide. - // + // + // The RemoteCertificateNotAvailable case does not appear to be possible + // for an outgoing connection. Since .NET requires an authenticated + // connection, the remote peer closes the socket if it does not have a + // certificate to provide. + // - if(errors > 0) - { - if(instance_.securityTraceLevel() >= 1) - { - logger_.trace(instance_.securityTraceCategory(), "SSL certificate validation failed"); - } - return false; - } + if(errors > 0) + { + if(instance_.securityTraceLevel() >= 1) + { + logger_.trace(instance_.securityTraceCategory(), "SSL certificate validation failed"); + } + return false; + } - return true; - } + return true; + } - private Instance instance_; - private string host_; - private Ice.Logger logger_; - private IPEndPoint addr_; + private Instance instance_; + private string host_; + private Ice.Logger logger_; + private IPEndPoint addr_; } internal class ConnectorValidationCallback { - internal ConnectorValidationCallback(ConnectorI connector) - { - connector_ = connector; - certs = null; - } + internal ConnectorValidationCallback(ConnectorI connector) + { + connector_ = connector; + certs = null; + } - internal bool validate(object sender, X509Certificate certificate, X509Chain chain, - SslPolicyErrors sslPolicyErrors) - { - // - // The certificate chain is not available via SslStream, and it is destroyed - // after this callback returns, so we keep a reference to each of the - // certificates. - // - if(chain != null) - { - certs = new X509Certificate2[chain.ChainElements.Count]; - int i = 0; - foreach(X509ChainElement e in chain.ChainElements) - { - certs[i++] = e.Certificate; - } - } - return connector_.validate(sender, certificate, chain, sslPolicyErrors); - } + internal bool validate(object sender, X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + // + // The certificate chain is not available via SslStream, and it is destroyed + // after this callback returns, so we keep a reference to each of the + // certificates. + // + if(chain != null) + { + certs = new X509Certificate2[chain.ChainElements.Count]; + int i = 0; + foreach(X509ChainElement e in chain.ChainElements) + { + certs[i++] = e.Certificate; + } + } + return connector_.validate(sender, certificate, chain, sslPolicyErrors); + } - private ConnectorI connector_; - internal X509Certificate2[] certs; + private ConnectorI connector_; + internal X509Certificate2[] certs; } } diff --git a/cs/src/IceSSL/EndpointI.cs b/cs/src/IceSSL/EndpointI.cs index 2e0e7c2c3b8..bd5b8148e68 100755 --- a/cs/src/IceSSL/EndpointI.cs +++ b/cs/src/IceSSL/EndpointI.cs @@ -14,597 +14,597 @@ namespace IceSSL sealed class EndpointI : IceInternal.EndpointI { - internal const short TYPE = 2; - - internal EndpointI(Instance instance, string ho, int po, int ti, string conId, bool co, bool pub) - { - instance_ = instance; - host_ = ho; - port_ = po; - timeout_ = ti; - connectionId_ = conId; - compress_ = co; - publish_ = pub; - calcHashValue(); - } - - internal EndpointI(Instance instance, string str) - { - instance_ = instance; - host_ = null; - port_ = 0; - timeout_ = -1; - compress_ = false; - publish_ = true; - - char[] separators = { ' ', '\t', '\n', '\r' }; - string[] arr = str.Split(separators); - - int i = 0; - while(i < arr.Length) - { - if(arr[i].Length == 0) - { - i++; - continue; - } - - string option = arr[i++]; - if(option.Length != 2 || option[0] != '-') - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "ssl " + str; - throw e; - } - - string argument = null; - if(i < arr.Length && arr[i][0] != '-') - { - argument = arr[i++]; - } - - switch(option[1]) - { - case 'h': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "ssl " + str; - throw e; - } - - host_ = argument; - break; - } - - case 'p': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "ssl " + str; - throw e; - } - - try - { - port_ = System.Int32.Parse(argument); - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "ssl " + str; - throw e; - } - - if(port_ < 0 || port_ > 65535) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "ssl " + str; - throw e; - } - - break; - } - - case 't': - { - if(argument == null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "ssl " + str; - throw e; - } - - try - { - timeout_ = System.Int32.Parse(argument); - } - catch(System.FormatException ex) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(ex); - e.str = "ssl " + str; - throw e; - } - - break; - } - - case 'z': - { - if(argument != null) - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "ssl " + str; - throw e; - } - - compress_ = true; - break; - } - - default: - { - Ice.EndpointParseException e = new Ice.EndpointParseException(); - e.str = "ssl " + str; - throw e; - } - } - } - } - - internal EndpointI(Instance instance, IceInternal.BasicStream s) - { - instance_ = instance; - s.startReadEncaps(); - host_ = s.readString(); - port_ = s.readInt(); - timeout_ = s.readInt(); - compress_ = s.readBool(); - s.endReadEncaps(); - publish_ = true; - calcHashValue(); - } - - // - // Marshal the endpoint. - // - public override void streamWrite(IceInternal.BasicStream s) - { - s.writeShort(TYPE); - s.startWriteEncaps(); - s.writeString(host_); - s.writeInt(port_); - s.writeInt(timeout_); - s.writeBool(compress_); - s.endWriteEncaps(); - } - - // - // Convert the endpoint to its string form. - // - public override string ice_toString_() - { - // - // WARNING: Certain features, such as proxy validation in Glacier2, - // depend on the format of proxy strings. Changes to toString() and - // methods called to generate parts of the reference string could break - // these features. Please review for all features that depend on the - // format of proxyToString() before changing this and related code. - // - string s = "ssl -h " + host_ + " -p " + port_; - if(timeout_ != -1) - { - s += " -t " + timeout_; - } - if(compress_) - { - s += " -z"; - } - return s; - } - - // - // Return the endpoint type. - // - public override short type() - { - return TYPE; - } - - // - // Return the timeout for the endpoint in milliseconds. 0 means - // non-blocking, -1 means no timeout. - // - public override int timeout() - { - return timeout_; - } - - // - // Return a new endpoint with a different timeout value, provided - // that timeouts are supported by the endpoint. Otherwise the same - // endpoint is returned. - // - public override IceInternal.EndpointI timeout(int timeout) - { - if(timeout == timeout_) - { - return this; - } - else - { - return new EndpointI(instance_, host_, port_, timeout, connectionId_, compress_, publish_); - } - } - - // - // Return a new endpoint with a different connection id. - // - public override IceInternal.EndpointI connectionId(string connectionId) - { - if(connectionId == connectionId_) - { - return this; - } - else - { - return new EndpointI(instance_, host_, port_, timeout_, connectionId, compress_, publish_); - } - } - - // - // Return true if the endpoints support bzip2 compress, or false - // otherwise. - // - public override bool compress() - { - return compress_; - } - - // - // Return a new endpoint with a different compression value, - // provided that compression is supported by the - // endpoint. Otherwise the same endpoint is returned. - // - public override IceInternal.EndpointI compress(bool compress) - { - if(compress == compress_) - { - return this; - } - else - { - return new EndpointI(instance_, host_, port_, timeout_, connectionId_, compress, publish_); - } - } - - // - // Return true if the endpoint is datagram-based. - // - public override bool datagram() - { - return false; - } - - // - // Return true if the endpoint is secure. - // - public override bool secure() - { - return true; - } - - // - // Return true if the endpoint type is unknown. - // - public override bool unknown() - { - return false; - } - - // - // Return a client side transceiver for this endpoint, or null if a - // transceiver can only be created by a connector. - // - public override IceInternal.Transceiver clientTransceiver() - { - return null; - } - - // - // Return a server side transceiver for this endpoint, or null if a - // transceiver can only be created by an acceptor. In case a - // transceiver is created, this operation also returns a new - // "effective" endpoint, which might differ from this endpoint, - // for example, if a dynamic port number is assigned. - // - public override IceInternal.Transceiver serverTransceiver(ref IceInternal.EndpointI endpoint) - { - endpoint = this; - return null; - } - - // - // Return a connector for this endpoint, or null if no connector - // is available. - // - public override IceInternal.Connector connector() - { - return new ConnectorI(instance_, host_, port_); - } - - // - // Return an acceptor for this endpoint, or null if no acceptor - // is available. In case an acceptor is created, this operation - // also returns a new "effective" endpoint, which might differ - // from this endpoint, for example, if a dynamic port number is - // assigned. - // - public override IceInternal.Acceptor acceptor(ref IceInternal.EndpointI endpoint, string adapterName) - { - AcceptorI p = new AcceptorI(instance_, adapterName, host_, port_); - endpoint = new EndpointI(instance_, host_, p.effectivePort(), timeout_, connectionId_, compress_, publish_); - return p; - } - - // - // Expand endpoint out in to separate endpoints for each local - // host if endpoint was configured with no host set. This - // only applies for ObjectAdapter endpoints. - // - public override ArrayList expand(bool server) - { - if(host_ == null) - { - host_ = instance_.defaultHost(); - if(host_ == null) - { - if(server) - { - host_ = "0.0.0.0"; - } - else - { - host_ = "127.0.0.1"; - } - } - } - else if(host_.Equals("*")) - { - host_ = "0.0.0.0"; - } - - ArrayList endps = new ArrayList(); - if(host_.Equals("0.0.0.0")) - { - string[] hosts = IceInternal.Network.getLocalHosts(); - for(int i = 0; i < hosts.Length; ++i) - { - endps.Add(new EndpointI(instance_, hosts[i], port_, timeout_, connectionId_, compress_, - hosts.Length == 1 || !hosts[i].Equals("127.0.0.1"))); - } - } - else - { - calcHashValue(); - endps.Add(this); - } - return endps; - } - - // - // Return whether endpoint should be published in proxies - // created by Object Adapter. - // - public override bool publish() - { - return publish_; - } - - // - // Check whether the endpoint is equivalent to a specific - // Transceiver or Acceptor - // - public override bool equivalent(IceInternal.Transceiver transceiver) - { - return false; - } - - public override bool equivalent(IceInternal.Acceptor acceptor) - { - AcceptorI sslAcceptor = null; - try - { - sslAcceptor = (AcceptorI)acceptor; - } - catch(System.InvalidCastException) - { - return false; - } - return sslAcceptor.equivalent(host_, port_); - } + internal const short TYPE = 2; + + internal EndpointI(Instance instance, string ho, int po, int ti, string conId, bool co, bool pub) + { + instance_ = instance; + host_ = ho; + port_ = po; + timeout_ = ti; + connectionId_ = conId; + compress_ = co; + publish_ = pub; + calcHashValue(); + } + + internal EndpointI(Instance instance, string str) + { + instance_ = instance; + host_ = null; + port_ = 0; + timeout_ = -1; + compress_ = false; + publish_ = true; + + char[] separators = { ' ', '\t', '\n', '\r' }; + string[] arr = str.Split(separators); + + int i = 0; + while(i < arr.Length) + { + if(arr[i].Length == 0) + { + i++; + continue; + } + + string option = arr[i++]; + if(option.Length != 2 || option[0] != '-') + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "ssl " + str; + throw e; + } + + string argument = null; + if(i < arr.Length && arr[i][0] != '-') + { + argument = arr[i++]; + } + + switch(option[1]) + { + case 'h': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "ssl " + str; + throw e; + } + + host_ = argument; + break; + } + + case 'p': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "ssl " + str; + throw e; + } + + try + { + port_ = System.Int32.Parse(argument); + } + catch(System.FormatException ex) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(ex); + e.str = "ssl " + str; + throw e; + } + + if(port_ < 0 || port_ > 65535) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "ssl " + str; + throw e; + } + + break; + } + + case 't': + { + if(argument == null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "ssl " + str; + throw e; + } + + try + { + timeout_ = System.Int32.Parse(argument); + } + catch(System.FormatException ex) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(ex); + e.str = "ssl " + str; + throw e; + } + + break; + } + + case 'z': + { + if(argument != null) + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "ssl " + str; + throw e; + } + + compress_ = true; + break; + } + + default: + { + Ice.EndpointParseException e = new Ice.EndpointParseException(); + e.str = "ssl " + str; + throw e; + } + } + } + } + + internal EndpointI(Instance instance, IceInternal.BasicStream s) + { + instance_ = instance; + s.startReadEncaps(); + host_ = s.readString(); + port_ = s.readInt(); + timeout_ = s.readInt(); + compress_ = s.readBool(); + s.endReadEncaps(); + publish_ = true; + calcHashValue(); + } + + // + // Marshal the endpoint. + // + public override void streamWrite(IceInternal.BasicStream s) + { + s.writeShort(TYPE); + s.startWriteEncaps(); + s.writeString(host_); + s.writeInt(port_); + s.writeInt(timeout_); + s.writeBool(compress_); + s.endWriteEncaps(); + } + + // + // Convert the endpoint to its string form. + // + public override string ice_toString_() + { + // + // WARNING: Certain features, such as proxy validation in Glacier2, + // depend on the format of proxy strings. Changes to toString() and + // methods called to generate parts of the reference string could break + // these features. Please review for all features that depend on the + // format of proxyToString() before changing this and related code. + // + string s = "ssl -h " + host_ + " -p " + port_; + if(timeout_ != -1) + { + s += " -t " + timeout_; + } + if(compress_) + { + s += " -z"; + } + return s; + } + + // + // Return the endpoint type. + // + public override short type() + { + return TYPE; + } + + // + // Return the timeout for the endpoint in milliseconds. 0 means + // non-blocking, -1 means no timeout. + // + public override int timeout() + { + return timeout_; + } + + // + // Return a new endpoint with a different timeout value, provided + // that timeouts are supported by the endpoint. Otherwise the same + // endpoint is returned. + // + public override IceInternal.EndpointI timeout(int timeout) + { + if(timeout == timeout_) + { + return this; + } + else + { + return new EndpointI(instance_, host_, port_, timeout, connectionId_, compress_, publish_); + } + } + + // + // Return a new endpoint with a different connection id. + // + public override IceInternal.EndpointI connectionId(string connectionId) + { + if(connectionId == connectionId_) + { + return this; + } + else + { + return new EndpointI(instance_, host_, port_, timeout_, connectionId, compress_, publish_); + } + } + + // + // Return true if the endpoints support bzip2 compress, or false + // otherwise. + // + public override bool compress() + { + return compress_; + } + + // + // Return a new endpoint with a different compression value, + // provided that compression is supported by the + // endpoint. Otherwise the same endpoint is returned. + // + public override IceInternal.EndpointI compress(bool compress) + { + if(compress == compress_) + { + return this; + } + else + { + return new EndpointI(instance_, host_, port_, timeout_, connectionId_, compress, publish_); + } + } + + // + // Return true if the endpoint is datagram-based. + // + public override bool datagram() + { + return false; + } + + // + // Return true if the endpoint is secure. + // + public override bool secure() + { + return true; + } + + // + // Return true if the endpoint type is unknown. + // + public override bool unknown() + { + return false; + } + + // + // Return a client side transceiver for this endpoint, or null if a + // transceiver can only be created by a connector. + // + public override IceInternal.Transceiver clientTransceiver() + { + return null; + } + + // + // Return a server side transceiver for this endpoint, or null if a + // transceiver can only be created by an acceptor. In case a + // transceiver is created, this operation also returns a new + // "effective" endpoint, which might differ from this endpoint, + // for example, if a dynamic port number is assigned. + // + public override IceInternal.Transceiver serverTransceiver(ref IceInternal.EndpointI endpoint) + { + endpoint = this; + return null; + } + + // + // Return a connector for this endpoint, or null if no connector + // is available. + // + public override IceInternal.Connector connector() + { + return new ConnectorI(instance_, host_, port_); + } + + // + // Return an acceptor for this endpoint, or null if no acceptor + // is available. In case an acceptor is created, this operation + // also returns a new "effective" endpoint, which might differ + // from this endpoint, for example, if a dynamic port number is + // assigned. + // + public override IceInternal.Acceptor acceptor(ref IceInternal.EndpointI endpoint, string adapterName) + { + AcceptorI p = new AcceptorI(instance_, adapterName, host_, port_); + endpoint = new EndpointI(instance_, host_, p.effectivePort(), timeout_, connectionId_, compress_, publish_); + return p; + } + + // + // Expand endpoint out in to separate endpoints for each local + // host if endpoint was configured with no host set. This + // only applies for ObjectAdapter endpoints. + // + public override ArrayList expand(bool server) + { + if(host_ == null) + { + host_ = instance_.defaultHost(); + if(host_ == null) + { + if(server) + { + host_ = "0.0.0.0"; + } + else + { + host_ = "127.0.0.1"; + } + } + } + else if(host_.Equals("*")) + { + host_ = "0.0.0.0"; + } + + ArrayList endps = new ArrayList(); + if(host_.Equals("0.0.0.0")) + { + string[] hosts = IceInternal.Network.getLocalHosts(); + for(int i = 0; i < hosts.Length; ++i) + { + endps.Add(new EndpointI(instance_, hosts[i], port_, timeout_, connectionId_, compress_, + hosts.Length == 1 || !hosts[i].Equals("127.0.0.1"))); + } + } + else + { + calcHashValue(); + endps.Add(this); + } + return endps; + } + + // + // Return whether endpoint should be published in proxies + // created by Object Adapter. + // + public override bool publish() + { + return publish_; + } + + // + // Check whether the endpoint is equivalent to a specific + // Transceiver or Acceptor + // + public override bool equivalent(IceInternal.Transceiver transceiver) + { + return false; + } + + public override bool equivalent(IceInternal.Acceptor acceptor) + { + AcceptorI sslAcceptor = null; + try + { + sslAcceptor = (AcceptorI)acceptor; + } + catch(System.InvalidCastException) + { + return false; + } + return sslAcceptor.equivalent(host_, port_); + } public override bool requiresThreadPerConnection() { return true; } - public override int GetHashCode() - { - return hashCode_; - } - - // - // Compare endpoints for sorting purposes - // - public override bool Equals(object obj) - { - return CompareTo(obj) == 0; - } - - public override int CompareTo(object obj) - { - EndpointI p = null; - - try - { - p = (EndpointI)obj; - } - catch(System.InvalidCastException) - { - return 1; - } - - if(this == p) - { - return 0; - } - - if(port_ < p.port_) - { - return -1; - } - else if(p.port_ < port_) - { - return 1; - } - - if(timeout_ < p.timeout_) - { - return -1; - } - else if(p.timeout_ < timeout_) - { - return 1; - } - - if(!connectionId_.Equals(p.connectionId_)) - { - return connectionId_.CompareTo(p.connectionId_); - } - - if(!compress_ && p.compress_) - { - return -1; - } - else if(!p.compress_ && compress_) - { - return 1; - } - - if(!host_.Equals(p.host_)) - { - // - // We do the most time-consuming part of the comparison last. - // - System.Net.IPEndPoint laddr = null; - try - { - laddr = IceInternal.Network.getAddress(host_, port_); - } - catch(Ice.DNSException) - { - } - - System.Net.IPEndPoint raddr = null; - try - { - raddr = IceInternal.Network.getAddress(p.host_, p.port_); - } - catch(Ice.DNSException) - { - } - - if(laddr == null && raddr != null) - { - return -1; - } - else if(raddr == null && laddr != null) - { - return 1; - } - else if(laddr != null && raddr != null) - { - byte[] larr = laddr.Address.GetAddressBytes(); - byte[] rarr = raddr.Address.GetAddressBytes(); - Debug.Assert(larr.Length == rarr.Length); - for(int i = 0; i < larr.Length; i++) - { - if(larr[i] < rarr[i]) - { - return -1; - } - else if(rarr[i] < larr[i]) - { - return 1; - } - } - } - } - - return 0; - } - - private void calcHashValue() - { - try - { - hashCode_ = IceInternal.Network.getNumericHost(host_).GetHashCode(); - } - catch(Ice.DNSException) - { - hashCode_ = host_.GetHashCode(); - } - hashCode_ = 5 * hashCode_ + port_; - hashCode_ = 5 * hashCode_ + timeout_; - hashCode_ = 5 * hashCode_ + connectionId_.GetHashCode(); - hashCode_ = 5 * hashCode_ + (compress_? 1 : 0); - } - - private Instance instance_; - private string host_; - private int port_; - private int timeout_; - private string connectionId_ = ""; - private bool compress_; - private bool publish_; - private int hashCode_; + public override int GetHashCode() + { + return hashCode_; + } + + // + // Compare endpoints for sorting purposes + // + public override bool Equals(object obj) + { + return CompareTo(obj) == 0; + } + + public override int CompareTo(object obj) + { + EndpointI p = null; + + try + { + p = (EndpointI)obj; + } + catch(System.InvalidCastException) + { + return 1; + } + + if(this == p) + { + return 0; + } + + if(port_ < p.port_) + { + return -1; + } + else if(p.port_ < port_) + { + return 1; + } + + if(timeout_ < p.timeout_) + { + return -1; + } + else if(p.timeout_ < timeout_) + { + return 1; + } + + if(!connectionId_.Equals(p.connectionId_)) + { + return connectionId_.CompareTo(p.connectionId_); + } + + if(!compress_ && p.compress_) + { + return -1; + } + else if(!p.compress_ && compress_) + { + return 1; + } + + if(!host_.Equals(p.host_)) + { + // + // We do the most time-consuming part of the comparison last. + // + System.Net.IPEndPoint laddr = null; + try + { + laddr = IceInternal.Network.getAddress(host_, port_); + } + catch(Ice.DNSException) + { + } + + System.Net.IPEndPoint raddr = null; + try + { + raddr = IceInternal.Network.getAddress(p.host_, p.port_); + } + catch(Ice.DNSException) + { + } + + if(laddr == null && raddr != null) + { + return -1; + } + else if(raddr == null && laddr != null) + { + return 1; + } + else if(laddr != null && raddr != null) + { + byte[] larr = laddr.Address.GetAddressBytes(); + byte[] rarr = raddr.Address.GetAddressBytes(); + Debug.Assert(larr.Length == rarr.Length); + for(int i = 0; i < larr.Length; i++) + { + if(larr[i] < rarr[i]) + { + return -1; + } + else if(rarr[i] < larr[i]) + { + return 1; + } + } + } + } + + return 0; + } + + private void calcHashValue() + { + try + { + hashCode_ = IceInternal.Network.getNumericHost(host_).GetHashCode(); + } + catch(Ice.DNSException) + { + hashCode_ = host_.GetHashCode(); + } + hashCode_ = 5 * hashCode_ + port_; + hashCode_ = 5 * hashCode_ + timeout_; + hashCode_ = 5 * hashCode_ + connectionId_.GetHashCode(); + hashCode_ = 5 * hashCode_ + (compress_? 1 : 0); + } + + private Instance instance_; + private string host_; + private int port_; + private int timeout_; + private string connectionId_ = ""; + private bool compress_; + private bool publish_; + private int hashCode_; } internal sealed class EndpointFactoryI : IceInternal.EndpointFactory { - internal EndpointFactoryI(Instance instance) - { - instance_ = instance; - } - - public short type() - { - return EndpointI.TYPE; - } - - public string protocol() - { - return "ssl"; - } - - public IceInternal.EndpointI create(string str) - { - return new EndpointI(instance_, str); - } - - public IceInternal.EndpointI read(IceInternal.BasicStream s) - { - return new EndpointI(instance_, s); - } - - public void destroy() - { - instance_ = null; - } - - private Instance instance_; + internal EndpointFactoryI(Instance instance) + { + instance_ = instance; + } + + public short type() + { + return EndpointI.TYPE; + } + + public string protocol() + { + return "ssl"; + } + + public IceInternal.EndpointI create(string str) + { + return new EndpointI(instance_, str); + } + + public IceInternal.EndpointI read(IceInternal.BasicStream s) + { + return new EndpointI(instance_, s); + } + + public void destroy() + { + instance_ = null; + } + + private Instance instance_; } } diff --git a/cs/src/IceSSL/Instance.cs b/cs/src/IceSSL/Instance.cs index 6c90980db4f..5b82fdf1392 100644 --- a/cs/src/IceSSL/Instance.cs +++ b/cs/src/IceSSL/Instance.cs @@ -18,730 +18,730 @@ namespace IceSSL internal class Instance { - internal Instance(Ice.Communicator communicator) - { - logger_ = communicator.getLogger(); - facade_ = Ice.Util.getProtocolPluginFacade(communicator); - securityTraceLevel_ = communicator.getProperties().getPropertyAsIntWithDefault("IceSSL.Trace.Security", 0); - securityTraceCategory_ = "Security"; - initialized_ = false; - trustManager_ = new TrustManager(communicator); - - // - // Register the endpoint factory. We have to do this now, rather than - // in initialize, because the communicator may need to interpret - // proxies before the plugin is fully initialized. - // - facade_.addEndpointFactory(new EndpointFactoryI(this)); - } - - internal void initialize() - { - if(initialized_) - { - return; - } - - const string prefix = "IceSSL."; - Ice.Properties properties = communicator().getProperties(); - - // - // Check for a default directory. We look in this directory for - // files mentioned in the configuration. - // - defaultDir_ = properties.getProperty(prefix + "DefaultDir"); - - // - // Process IceSSL.ImportCert.* properties. - // - Ice.PropertyDict certs = properties.getPropertiesForPrefix(prefix + "ImportCert."); - foreach(DictionaryEntry entry in certs) - { - string name = (string)entry.Key; - string val = (string)entry.Value; - if(val.Length > 0) - { - importCertificate(name, val); - } - } - - // - // Select protocols. - // - protocols_ = parseProtocols(prefix + "Protocols"); - - // - // CheckCertName determines whether we compare the name in a peer's - // certificate against its hostname. - // - checkCertName_ = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0; - - // - // VerifyDepthMax establishes the maximum length of a peer's certificate - // chain, including the peer's certificate. A value of 0 means there is - // no maximum. - // - verifyDepthMax_ = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 2); - - // - // CheckCRL determines whether the certificate revocation list is checked. - // - checkCRL_ = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0) > 0; - - // - // If the user hasn't supplied a certificate collection, we need to examine - // the property settings. - // - if(certs_ == null) - { - // - // If IceSSL.CertFile is defined, load a certificate from a file and - // add it to the collection. - // - // TODO: tracing? - certs_ = new X509Certificate2Collection(); - string certFile = properties.getProperty(prefix + "CertFile"); - string password = properties.getProperty(prefix + "Password"); - if(certFile.Length > 0) - { - if(!checkPath(ref certFile)) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: certificate file not found: " + certFile; - throw e; - } - try - { - X509Certificate2 cert = new X509Certificate2(certFile, password); - certs_.Add(cert); - } - catch(CryptographicException ex) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); - e.reason = "IceSSL: error while attempting to load certificate from " + certFile; - throw e; - } - } - - // - // If IceSSL.FindCert.* properties are defined, add the selected certificates - // to the collection. - // - // TODO: tracing? - const string findPrefix = prefix + "FindCert."; - Ice.PropertyDict certProps = properties.getPropertiesForPrefix(findPrefix); - if(certProps.Count > 0) - { - foreach(DictionaryEntry entry in certProps) - { - string name = (string)entry.Key; - string val = (string)entry.Value; - if(val.Length > 0) - { - string storeSpec = name.Substring(findPrefix.Length); - X509Certificate2Collection coll = findCertificates(name, storeSpec, val); - certs_.AddRange(coll); - } - } - if(certs_.Count == 0) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: no certificates found"; - throw e; - } - } - } - - initialized_ = true; - } - - internal void setCertificates(X509Certificate2Collection certs) - { - if(initialized_) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: plugin is already initialized"; - throw e; - } - - certs_ = certs; - } - - internal void setCertificateVerifier(CertificateVerifier verifier) - { - verifier_ = verifier; - } - - internal Ice.Communicator communicator() - { - return facade_.getCommunicator(); - } - - internal string defaultHost() - { - return facade_.getDefaultHost(); - } - - internal int networkTraceLevel() - { - return facade_.getNetworkTraceLevel(); - } - - internal string networkTraceCategory() - { - return facade_.getNetworkTraceCategory(); - } - - internal int securityTraceLevel() - { - return securityTraceLevel_; - } - - internal string securityTraceCategory() - { - return securityTraceCategory_; - } - - internal CertificateVerifier certificateVerifier() - { - return verifier_; - } - - internal bool initialized() - { - return initialized_; - } - - internal X509Certificate2Collection certs() - { - return certs_; - } - - internal SslProtocols protocols() - { - return protocols_; - } - - internal bool checkCRL() - { - return checkCRL_; - } - - internal bool checkCertName() - { - return checkCertName_; - } - - internal void traceStream(System.Net.Security.SslStream stream, string connInfo) - { - System.Text.StringBuilder s = new System.Text.StringBuilder(); - s.Append("SSL connection summary"); - if(connInfo.Length > 0) - { - s.Append("\n"); - s.Append(connInfo); - } - s.Append("\nauthenticated = " + (stream.IsAuthenticated ? "yes" : "no")); - s.Append("\nencrypted = " + (stream.IsEncrypted ? "yes" : "no")); - s.Append("\nsigned = " + (stream.IsSigned ? "yes" : "no")); - s.Append("\nmutually authenticated = " + (stream.IsMutuallyAuthenticated ? "yes" : "no")); - s.Append("\nhash algorithm = " + stream.HashAlgorithm + "/" + stream.HashStrength); - s.Append("\ncipher algorithm = " + stream.CipherAlgorithm + "/" + stream.CipherStrength); - s.Append("\nkey exchange algorithm = " + stream.KeyExchangeAlgorithm + "/" + stream.KeyExchangeStrength); - s.Append("\nprotocol = " + stream.SslProtocol); - communicator().getLogger().trace(securityTraceCategory_, s.ToString()); - } - - internal void verifyPeer(ConnectionInfo info, System.Net.Sockets.Socket fd, bool incoming) - { - if(verifyDepthMax_ > 0 && info.certs != null && info.certs.Length > verifyDepthMax_) - { - string msg = (incoming ? "incoming" : "outgoing") + " connection rejected:\n" + - "length of peer's certificate chain (" + info.certs.Length + ") exceeds maximum of " + - verifyDepthMax_ + "\n" + - IceInternal.Network.fdToString(fd); - if(securityTraceLevel_ >= 1) - { - logger_.trace(securityTraceCategory_, msg); - } - Ice.SecurityException ex = new Ice.SecurityException(); - ex.reason = msg; - throw ex; - } - - if(!trustManager_.verify(info)) - { - string msg = (incoming ? "incoming" : "outgoing") + " connection rejected by trust manager\n" + - IceInternal.Network.fdToString(fd); - if(securityTraceLevel_ >= 1) - { - logger_.trace(securityTraceCategory_, msg); - } - - Ice.SecurityException ex = new Ice.SecurityException(); - ex.reason = "IceSSL: " + msg; - throw ex; - } - - if(verifier_ != null && !verifier_.verify(info)) - { - string msg = (incoming ? "incoming" : "outgoing") + " connection rejected by certificate verifier\n" + - IceInternal.Network.fdToString(fd); - if(securityTraceLevel_ >= 1) - { - logger_.trace(securityTraceCategory_, msg); - } - - Ice.SecurityException ex = new Ice.SecurityException(); - ex.reason = "IceSSL: " + msg; - throw ex; - } - } - - // - // Parse a string of the form "location.name" into two parts. - // - internal void parseStore(string prop, string store, ref StoreLocation loc, ref StoreName name, ref string sname) - { - int pos = store.IndexOf('.'); - if(pos == -1) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: property `" + prop + "' has invalid format"; - throw e; - } - - string sloc = store.Substring(0, pos).ToLower(); - if(sloc.Equals("currentuser")) - { - loc = StoreLocation.CurrentUser; - } - else if(sloc.Equals("localmachine")) - { - loc = StoreLocation.LocalMachine; - } - else - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unknown store location `" + sloc + "' in " + prop; - throw e; - } - - sname = store.Substring(pos + 1); - if(sname.Length == 0) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: invalid store name in " + prop; - throw e; - } - - // - // Try to convert the name into the StoreName enumeration. - // - try - { - name = (StoreName)Enum.Parse(typeof(StoreName), sname, true); - sname = null; - } - catch(ArgumentException) - { - // Ignore - assume the user is selecting a non-standard store. - } - } - - private bool checkPath(ref string path) - { - if(File.Exists(path)) - { - return true; - } - - if(defaultDir_.Length > 0) - { - string s = defaultDir_ + Path.DirectorySeparatorChar + path; - if(File.Exists(s)) - { - path = s; - return true; - } - } - - return false; - } - - private void importCertificate(string propName, string propValue) - { - // - // Expecting a property of the following form: - // - // IceSSL.ImportCert.<location>.<name>=<file>[;password] - // - const string prefix = "IceSSL.ImportCert."; - StoreLocation loc = 0; - StoreName name = 0; - string sname = null; - parseStore(propName, propName.Substring(prefix.Length), ref loc, ref name, ref sname); - - // - // Extract the filename and password. Either or both can be quoted. - // - string[] arr = splitString(propValue, ';'); - if(arr == null) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unmatched quote in `" + propValue + "'"; - throw e; - } - if(arr.Length == 0) - { - return; - } - string file = arr[0]; - string password = null; - if(arr.Length > 1) - { - password = arr[1]; - } - - // - // Open the X509 certificate store. - // - X509Store store = null; - try - { - if(sname != null) - { - store = new X509Store(sname, loc); - } - else - { - store = new X509Store(name, loc); - } - store.Open(OpenFlags.ReadWrite); - } - catch(Exception ex) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); - e.reason = "IceSSL: failure while opening store specified by " + propName; - throw e; - } - - if(!checkPath(ref file)) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: certificate file not found:\n" + file; - throw e; - } - - // - // Add the certificate to the store. - // - try - { - X509Certificate2 cert; - if(password != null) - { - cert = new X509Certificate2(file, password); - } - else - { - cert = new X509Certificate2(file); - } - store.Add(cert); - } - catch(Exception ex) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); - e.reason = "IceSSL: failure while adding certificate file:\n" + file; - throw e; - } - finally - { - store.Close(); - } - } - - // - // Split strings using a delimiter. Quotes are supported. - // Returns null for an unmatched quote. - // - private string[] splitString(string str, char delim) - { - ArrayList l = new ArrayList(); - char[] arr = new char[str.Length]; - int pos = 0; - - while(pos < str.Length) - { - int n = 0; - char quoteChar = '\0'; - if(str[pos] == '"' || str[pos] == '\'') - { - quoteChar = str[pos]; - ++pos; - } - bool trim = true; - while(pos < str.Length) - { - if(quoteChar != '\0' && str[pos] == '\\' && pos + 1 < str.Length && str[pos + 1] == quoteChar) - { - ++pos; - } - else if(quoteChar != '\0' && str[pos] == quoteChar) - { - trim = false; - ++pos; - quoteChar = '\0'; - break; - } - else if(str[pos] == delim) - { - if(quoteChar == '\0') - { - ++pos; - break; - } - } - if(pos < str.Length) - { - arr[n++] = str[pos++]; - } - } - if(quoteChar != '\0') - { - return null; // Unmatched quote. - } - if(n > 0) - { - string s = new string(arr, 0, n); - if(trim) - { - s = s.Trim(); - } - if(s.Length > 0) - { - l.Add(s); - } - } - } - - return (string[])l.ToArray(typeof(string)); - } - - private SslProtocols parseProtocols(string property) - { - SslProtocols result = SslProtocols.Default; - string val = communicator().getProperties().getProperty(property); - if(val.Length > 0) - { - char[] delim = new char[] {',', ' '}; - string[] arr = val.Split(delim, StringSplitOptions.RemoveEmptyEntries); - if(arr.Length > 0) - { - result = 0; - for(int i = 0; i < arr.Length; ++i) - { - string s = arr[i].ToLower(); - if(s.Equals("ssl3") || s.Equals("sslv3")) - { - result |= SslProtocols.Ssl3; - } - else if(s.Equals("tls") || s.Equals("tls1") || s.Equals("tlsv1")) - { - result |= SslProtocols.Tls; - } - else - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unrecognized protocol `" + s + "'"; - throw e; - } - } - } - } - return result; - } - - private X509Certificate2Collection findCertificates(string prop, string storeSpec, string value) - { - StoreLocation storeLoc = 0; - StoreName storeName = 0; - string storeNameStr = null; - parseStore(prop, storeSpec, ref storeLoc, ref storeName, ref storeNameStr); - - // - // Open the X509 certificate store. - // - X509Store store = null; - try - { - if(storeNameStr != null) - { - store = new X509Store(storeNameStr, storeLoc); - } - else - { - store = new X509Store(storeName, storeLoc); - } - store.Open(OpenFlags.ReadOnly); - } - catch(Exception ex) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); - e.reason = "IceSSL: failure while opening store specified by " + prop; - throw e; - } - - // - // Start with all of the certificates in the collection and filter as necessary. - // - // - If the value is "*", return all certificates. - // - Otherwise, search using key:value pairs. The following keys are supported: - // - // Issuer - // IssuerDN - // Serial - // Subject - // SubjectDN - // SubjectKeyId - // Thumbprint - // - // A value must be enclosed in single or double quotes if it contains whitespace. - // - X509Certificate2Collection result = new X509Certificate2Collection(); - result.AddRange(store.Certificates); - try - { - if(value != "*") - { - int start = 0; - int pos; - while((pos = value.IndexOf(':', start)) != -1) - { - // - // Parse the X509FindType. - // - string field = value.Substring(start, pos - start).Trim().ToLower(); - X509FindType findType; - if(field.Equals("subject")) - { - findType = X509FindType.FindBySubjectName; - } - else if(field.Equals("subjectdn")) - { - findType = X509FindType.FindBySubjectDistinguishedName; - } - else if(field.Equals("issuer")) - { - findType = X509FindType.FindByIssuerName; - } - else if(field.Equals("issuerdn")) - { - findType = X509FindType.FindByIssuerDistinguishedName; - } - else if(field.Equals("thumbprint")) - { - findType = X509FindType.FindByThumbprint; - } - else if(field.Equals("subjectkeyid")) - { - findType = X509FindType.FindBySubjectKeyIdentifier; - } - else if(field.Equals("serial")) - { - findType = X509FindType.FindBySerialNumber; - } - else - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unknown key in `" + value + "'"; - throw e; - } - - // - // Parse the argument. - // - start = pos + 1; - while(start < value.Length && (value[start] == ' ' || value[start] == '\t')) - { - ++start; - } - if(start == value.Length) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: missing argument in `" + value + "'"; - throw e; - } - - string arg; - if(value[start] == '"' || value[start] == '\'') - { - int end = start; - ++end; - while(end < value.Length) - { - if(value[end] == value[start] && value[end - 1] != '\\') - { - break; - } - ++end; - } - if(end == value.Length || value[end] != value[start]) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unmatched quote in `" + value + "'"; - throw e; - } - ++start; - arg = value.Substring(start, end - start); - start = end + 1; - } - else - { - char[] ws = new char[] { ' ', '\t' }; - int end = value.IndexOfAny(ws, start); - if(end == -1) - { - arg = value.Substring(start); - start = value.Length; - } - else - { - arg = value.Substring(start, end - start); - start = end + 1; - } - } - - // - // Execute the query. - // - // TODO: allow user to specify a value for validOnly? - // - bool validOnly = false; - result = result.Find(findType, arg, validOnly); - } - } - } - finally - { - store.Close(); - } - - return result; - } - - private Ice.Logger logger_; - private IceInternal.ProtocolPluginFacade facade_; - private int securityTraceLevel_; - private string securityTraceCategory_; - private bool initialized_; - private string defaultDir_; - private SslProtocols protocols_; - private bool checkCertName_; - private int verifyDepthMax_; - private bool checkCRL_; - private X509Certificate2Collection certs_; - private CertificateVerifier verifier_; - private TrustManager trustManager_; + internal Instance(Ice.Communicator communicator) + { + logger_ = communicator.getLogger(); + facade_ = Ice.Util.getProtocolPluginFacade(communicator); + securityTraceLevel_ = communicator.getProperties().getPropertyAsIntWithDefault("IceSSL.Trace.Security", 0); + securityTraceCategory_ = "Security"; + initialized_ = false; + trustManager_ = new TrustManager(communicator); + + // + // Register the endpoint factory. We have to do this now, rather than + // in initialize, because the communicator may need to interpret + // proxies before the plugin is fully initialized. + // + facade_.addEndpointFactory(new EndpointFactoryI(this)); + } + + internal void initialize() + { + if(initialized_) + { + return; + } + + const string prefix = "IceSSL."; + Ice.Properties properties = communicator().getProperties(); + + // + // Check for a default directory. We look in this directory for + // files mentioned in the configuration. + // + defaultDir_ = properties.getProperty(prefix + "DefaultDir"); + + // + // Process IceSSL.ImportCert.* properties. + // + Ice.PropertyDict certs = properties.getPropertiesForPrefix(prefix + "ImportCert."); + foreach(DictionaryEntry entry in certs) + { + string name = (string)entry.Key; + string val = (string)entry.Value; + if(val.Length > 0) + { + importCertificate(name, val); + } + } + + // + // Select protocols. + // + protocols_ = parseProtocols(prefix + "Protocols"); + + // + // CheckCertName determines whether we compare the name in a peer's + // certificate against its hostname. + // + checkCertName_ = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0; + + // + // VerifyDepthMax establishes the maximum length of a peer's certificate + // chain, including the peer's certificate. A value of 0 means there is + // no maximum. + // + verifyDepthMax_ = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 2); + + // + // CheckCRL determines whether the certificate revocation list is checked. + // + checkCRL_ = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0) > 0; + + // + // If the user hasn't supplied a certificate collection, we need to examine + // the property settings. + // + if(certs_ == null) + { + // + // If IceSSL.CertFile is defined, load a certificate from a file and + // add it to the collection. + // + // TODO: tracing? + certs_ = new X509Certificate2Collection(); + string certFile = properties.getProperty(prefix + "CertFile"); + string password = properties.getProperty(prefix + "Password"); + if(certFile.Length > 0) + { + if(!checkPath(ref certFile)) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: certificate file not found: " + certFile; + throw e; + } + try + { + X509Certificate2 cert = new X509Certificate2(certFile, password); + certs_.Add(cert); + } + catch(CryptographicException ex) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); + e.reason = "IceSSL: error while attempting to load certificate from " + certFile; + throw e; + } + } + + // + // If IceSSL.FindCert.* properties are defined, add the selected certificates + // to the collection. + // + // TODO: tracing? + const string findPrefix = prefix + "FindCert."; + Ice.PropertyDict certProps = properties.getPropertiesForPrefix(findPrefix); + if(certProps.Count > 0) + { + foreach(DictionaryEntry entry in certProps) + { + string name = (string)entry.Key; + string val = (string)entry.Value; + if(val.Length > 0) + { + string storeSpec = name.Substring(findPrefix.Length); + X509Certificate2Collection coll = findCertificates(name, storeSpec, val); + certs_.AddRange(coll); + } + } + if(certs_.Count == 0) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: no certificates found"; + throw e; + } + } + } + + initialized_ = true; + } + + internal void setCertificates(X509Certificate2Collection certs) + { + if(initialized_) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: plugin is already initialized"; + throw e; + } + + certs_ = certs; + } + + internal void setCertificateVerifier(CertificateVerifier verifier) + { + verifier_ = verifier; + } + + internal Ice.Communicator communicator() + { + return facade_.getCommunicator(); + } + + internal string defaultHost() + { + return facade_.getDefaultHost(); + } + + internal int networkTraceLevel() + { + return facade_.getNetworkTraceLevel(); + } + + internal string networkTraceCategory() + { + return facade_.getNetworkTraceCategory(); + } + + internal int securityTraceLevel() + { + return securityTraceLevel_; + } + + internal string securityTraceCategory() + { + return securityTraceCategory_; + } + + internal CertificateVerifier certificateVerifier() + { + return verifier_; + } + + internal bool initialized() + { + return initialized_; + } + + internal X509Certificate2Collection certs() + { + return certs_; + } + + internal SslProtocols protocols() + { + return protocols_; + } + + internal bool checkCRL() + { + return checkCRL_; + } + + internal bool checkCertName() + { + return checkCertName_; + } + + internal void traceStream(System.Net.Security.SslStream stream, string connInfo) + { + System.Text.StringBuilder s = new System.Text.StringBuilder(); + s.Append("SSL connection summary"); + if(connInfo.Length > 0) + { + s.Append("\n"); + s.Append(connInfo); + } + s.Append("\nauthenticated = " + (stream.IsAuthenticated ? "yes" : "no")); + s.Append("\nencrypted = " + (stream.IsEncrypted ? "yes" : "no")); + s.Append("\nsigned = " + (stream.IsSigned ? "yes" : "no")); + s.Append("\nmutually authenticated = " + (stream.IsMutuallyAuthenticated ? "yes" : "no")); + s.Append("\nhash algorithm = " + stream.HashAlgorithm + "/" + stream.HashStrength); + s.Append("\ncipher algorithm = " + stream.CipherAlgorithm + "/" + stream.CipherStrength); + s.Append("\nkey exchange algorithm = " + stream.KeyExchangeAlgorithm + "/" + stream.KeyExchangeStrength); + s.Append("\nprotocol = " + stream.SslProtocol); + communicator().getLogger().trace(securityTraceCategory_, s.ToString()); + } + + internal void verifyPeer(ConnectionInfo info, System.Net.Sockets.Socket fd, bool incoming) + { + if(verifyDepthMax_ > 0 && info.certs != null && info.certs.Length > verifyDepthMax_) + { + string msg = (incoming ? "incoming" : "outgoing") + " connection rejected:\n" + + "length of peer's certificate chain (" + info.certs.Length + ") exceeds maximum of " + + verifyDepthMax_ + "\n" + + IceInternal.Network.fdToString(fd); + if(securityTraceLevel_ >= 1) + { + logger_.trace(securityTraceCategory_, msg); + } + Ice.SecurityException ex = new Ice.SecurityException(); + ex.reason = msg; + throw ex; + } + + if(!trustManager_.verify(info)) + { + string msg = (incoming ? "incoming" : "outgoing") + " connection rejected by trust manager\n" + + IceInternal.Network.fdToString(fd); + if(securityTraceLevel_ >= 1) + { + logger_.trace(securityTraceCategory_, msg); + } + + Ice.SecurityException ex = new Ice.SecurityException(); + ex.reason = "IceSSL: " + msg; + throw ex; + } + + if(verifier_ != null && !verifier_.verify(info)) + { + string msg = (incoming ? "incoming" : "outgoing") + " connection rejected by certificate verifier\n" + + IceInternal.Network.fdToString(fd); + if(securityTraceLevel_ >= 1) + { + logger_.trace(securityTraceCategory_, msg); + } + + Ice.SecurityException ex = new Ice.SecurityException(); + ex.reason = "IceSSL: " + msg; + throw ex; + } + } + + // + // Parse a string of the form "location.name" into two parts. + // + internal void parseStore(string prop, string store, ref StoreLocation loc, ref StoreName name, ref string sname) + { + int pos = store.IndexOf('.'); + if(pos == -1) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: property `" + prop + "' has invalid format"; + throw e; + } + + string sloc = store.Substring(0, pos).ToLower(); + if(sloc.Equals("currentuser")) + { + loc = StoreLocation.CurrentUser; + } + else if(sloc.Equals("localmachine")) + { + loc = StoreLocation.LocalMachine; + } + else + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: unknown store location `" + sloc + "' in " + prop; + throw e; + } + + sname = store.Substring(pos + 1); + if(sname.Length == 0) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: invalid store name in " + prop; + throw e; + } + + // + // Try to convert the name into the StoreName enumeration. + // + try + { + name = (StoreName)Enum.Parse(typeof(StoreName), sname, true); + sname = null; + } + catch(ArgumentException) + { + // Ignore - assume the user is selecting a non-standard store. + } + } + + private bool checkPath(ref string path) + { + if(File.Exists(path)) + { + return true; + } + + if(defaultDir_.Length > 0) + { + string s = defaultDir_ + Path.DirectorySeparatorChar + path; + if(File.Exists(s)) + { + path = s; + return true; + } + } + + return false; + } + + private void importCertificate(string propName, string propValue) + { + // + // Expecting a property of the following form: + // + // IceSSL.ImportCert.<location>.<name>=<file>[;password] + // + const string prefix = "IceSSL.ImportCert."; + StoreLocation loc = 0; + StoreName name = 0; + string sname = null; + parseStore(propName, propName.Substring(prefix.Length), ref loc, ref name, ref sname); + + // + // Extract the filename and password. Either or both can be quoted. + // + string[] arr = splitString(propValue, ';'); + if(arr == null) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: unmatched quote in `" + propValue + "'"; + throw e; + } + if(arr.Length == 0) + { + return; + } + string file = arr[0]; + string password = null; + if(arr.Length > 1) + { + password = arr[1]; + } + + // + // Open the X509 certificate store. + // + X509Store store = null; + try + { + if(sname != null) + { + store = new X509Store(sname, loc); + } + else + { + store = new X509Store(name, loc); + } + store.Open(OpenFlags.ReadWrite); + } + catch(Exception ex) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); + e.reason = "IceSSL: failure while opening store specified by " + propName; + throw e; + } + + if(!checkPath(ref file)) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: certificate file not found:\n" + file; + throw e; + } + + // + // Add the certificate to the store. + // + try + { + X509Certificate2 cert; + if(password != null) + { + cert = new X509Certificate2(file, password); + } + else + { + cert = new X509Certificate2(file); + } + store.Add(cert); + } + catch(Exception ex) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); + e.reason = "IceSSL: failure while adding certificate file:\n" + file; + throw e; + } + finally + { + store.Close(); + } + } + + // + // Split strings using a delimiter. Quotes are supported. + // Returns null for an unmatched quote. + // + private string[] splitString(string str, char delim) + { + ArrayList l = new ArrayList(); + char[] arr = new char[str.Length]; + int pos = 0; + + while(pos < str.Length) + { + int n = 0; + char quoteChar = '\0'; + if(str[pos] == '"' || str[pos] == '\'') + { + quoteChar = str[pos]; + ++pos; + } + bool trim = true; + while(pos < str.Length) + { + if(quoteChar != '\0' && str[pos] == '\\' && pos + 1 < str.Length && str[pos + 1] == quoteChar) + { + ++pos; + } + else if(quoteChar != '\0' && str[pos] == quoteChar) + { + trim = false; + ++pos; + quoteChar = '\0'; + break; + } + else if(str[pos] == delim) + { + if(quoteChar == '\0') + { + ++pos; + break; + } + } + if(pos < str.Length) + { + arr[n++] = str[pos++]; + } + } + if(quoteChar != '\0') + { + return null; // Unmatched quote. + } + if(n > 0) + { + string s = new string(arr, 0, n); + if(trim) + { + s = s.Trim(); + } + if(s.Length > 0) + { + l.Add(s); + } + } + } + + return (string[])l.ToArray(typeof(string)); + } + + private SslProtocols parseProtocols(string property) + { + SslProtocols result = SslProtocols.Default; + string val = communicator().getProperties().getProperty(property); + if(val.Length > 0) + { + char[] delim = new char[] {',', ' '}; + string[] arr = val.Split(delim, StringSplitOptions.RemoveEmptyEntries); + if(arr.Length > 0) + { + result = 0; + for(int i = 0; i < arr.Length; ++i) + { + string s = arr[i].ToLower(); + if(s.Equals("ssl3") || s.Equals("sslv3")) + { + result |= SslProtocols.Ssl3; + } + else if(s.Equals("tls") || s.Equals("tls1") || s.Equals("tlsv1")) + { + result |= SslProtocols.Tls; + } + else + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: unrecognized protocol `" + s + "'"; + throw e; + } + } + } + } + return result; + } + + private X509Certificate2Collection findCertificates(string prop, string storeSpec, string value) + { + StoreLocation storeLoc = 0; + StoreName storeName = 0; + string storeNameStr = null; + parseStore(prop, storeSpec, ref storeLoc, ref storeName, ref storeNameStr); + + // + // Open the X509 certificate store. + // + X509Store store = null; + try + { + if(storeNameStr != null) + { + store = new X509Store(storeNameStr, storeLoc); + } + else + { + store = new X509Store(storeName, storeLoc); + } + store.Open(OpenFlags.ReadOnly); + } + catch(Exception ex) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex); + e.reason = "IceSSL: failure while opening store specified by " + prop; + throw e; + } + + // + // Start with all of the certificates in the collection and filter as necessary. + // + // - If the value is "*", return all certificates. + // - Otherwise, search using key:value pairs. The following keys are supported: + // + // Issuer + // IssuerDN + // Serial + // Subject + // SubjectDN + // SubjectKeyId + // Thumbprint + // + // A value must be enclosed in single or double quotes if it contains whitespace. + // + X509Certificate2Collection result = new X509Certificate2Collection(); + result.AddRange(store.Certificates); + try + { + if(value != "*") + { + int start = 0; + int pos; + while((pos = value.IndexOf(':', start)) != -1) + { + // + // Parse the X509FindType. + // + string field = value.Substring(start, pos - start).Trim().ToLower(); + X509FindType findType; + if(field.Equals("subject")) + { + findType = X509FindType.FindBySubjectName; + } + else if(field.Equals("subjectdn")) + { + findType = X509FindType.FindBySubjectDistinguishedName; + } + else if(field.Equals("issuer")) + { + findType = X509FindType.FindByIssuerName; + } + else if(field.Equals("issuerdn")) + { + findType = X509FindType.FindByIssuerDistinguishedName; + } + else if(field.Equals("thumbprint")) + { + findType = X509FindType.FindByThumbprint; + } + else if(field.Equals("subjectkeyid")) + { + findType = X509FindType.FindBySubjectKeyIdentifier; + } + else if(field.Equals("serial")) + { + findType = X509FindType.FindBySerialNumber; + } + else + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: unknown key in `" + value + "'"; + throw e; + } + + // + // Parse the argument. + // + start = pos + 1; + while(start < value.Length && (value[start] == ' ' || value[start] == '\t')) + { + ++start; + } + if(start == value.Length) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: missing argument in `" + value + "'"; + throw e; + } + + string arg; + if(value[start] == '"' || value[start] == '\'') + { + int end = start; + ++end; + while(end < value.Length) + { + if(value[end] == value[start] && value[end - 1] != '\\') + { + break; + } + ++end; + } + if(end == value.Length || value[end] != value[start]) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: unmatched quote in `" + value + "'"; + throw e; + } + ++start; + arg = value.Substring(start, end - start); + start = end + 1; + } + else + { + char[] ws = new char[] { ' ', '\t' }; + int end = value.IndexOfAny(ws, start); + if(end == -1) + { + arg = value.Substring(start); + start = value.Length; + } + else + { + arg = value.Substring(start, end - start); + start = end + 1; + } + } + + // + // Execute the query. + // + // TODO: allow user to specify a value for validOnly? + // + bool validOnly = false; + result = result.Find(findType, arg, validOnly); + } + } + } + finally + { + store.Close(); + } + + return result; + } + + private Ice.Logger logger_; + private IceInternal.ProtocolPluginFacade facade_; + private int securityTraceLevel_; + private string securityTraceCategory_; + private bool initialized_; + private string defaultDir_; + private SslProtocols protocols_; + private bool checkCertName_; + private int verifyDepthMax_; + private bool checkCRL_; + private X509Certificate2Collection certs_; + private CertificateVerifier verifier_; + private TrustManager trustManager_; } } diff --git a/cs/src/IceSSL/Plugin.cs b/cs/src/IceSSL/Plugin.cs index 853996a2f1e..1e0346b05c7 100755 --- a/cs/src/IceSSL/Plugin.cs +++ b/cs/src/IceSSL/Plugin.cs @@ -17,41 +17,41 @@ namespace IceSSL // public interface CertificateVerifier { - // - // Return true to allow a connection using the provided certificate - // information, or false to reject the connection. - // - bool verify(ConnectionInfo info); + // + // Return true to allow a connection using the provided certificate + // information, or false to reject the connection. + // + bool verify(ConnectionInfo info); } abstract public class Plugin : Ice.LocalObjectImpl, Ice.Plugin { - // - // From Ice.Plugin. - // - abstract public void initialize(); + // + // From Ice.Plugin. + // + abstract public void initialize(); - // - // Specify the certificates to use for SSL connections. This - // must be done before the plugin is initialized, therefore - // the application must define the property Ice.InitPlugins=0, - // set the certificates, and finally invoke initializePlugins - // on the PluginManager. - // - // When the application supplies its own certificates, the - // plugin skips its normal property-based configuration. - // - abstract public void setCertificates(X509Certificate2Collection certs); + // + // Specify the certificates to use for SSL connections. This + // must be done before the plugin is initialized, therefore + // the application must define the property Ice.InitPlugins=0, + // set the certificates, and finally invoke initializePlugins + // on the PluginManager. + // + // When the application supplies its own certificates, the + // plugin skips its normal property-based configuration. + // + abstract public void setCertificates(X509Certificate2Collection certs); - // - // Establish the certificate verifier object. This should be - // done before any connections are established. - // - abstract public void setCertificateVerifier(CertificateVerifier verifier); + // + // Establish the certificate verifier object. This should be + // done before any connections are established. + // + abstract public void setCertificateVerifier(CertificateVerifier verifier); - // - // This method is for internal use. - // - abstract public void destroy(); + // + // This method is for internal use. + // + abstract public void destroy(); } } diff --git a/cs/src/IceSSL/PluginI.cs b/cs/src/IceSSL/PluginI.cs index d2b3502fddd..498385066ba 100755 --- a/cs/src/IceSSL/PluginI.cs +++ b/cs/src/IceSSL/PluginI.cs @@ -13,41 +13,41 @@ namespace IceSSL { public sealed class PluginFactory : Ice.PluginFactory { - public Ice.Plugin - create(Ice.Communicator communicator, string name, string[] args) - { - return new PluginI(communicator); - } + public Ice.Plugin + create(Ice.Communicator communicator, string name, string[] args) + { + return new PluginI(communicator); + } } public sealed class PluginI : Plugin { - public - PluginI(Ice.Communicator communicator) - { - instance_ = new Instance(communicator); - } - - public override void initialize() - { - instance_.initialize(); - } - - public override void - destroy() - { - } - - public override void setCertificates(X509Certificate2Collection certs) - { - instance_.setCertificates(certs); - } - - public override void setCertificateVerifier(CertificateVerifier verifier) - { - instance_.setCertificateVerifier(verifier); - } - - private Instance instance_; + public + PluginI(Ice.Communicator communicator) + { + instance_ = new Instance(communicator); + } + + public override void initialize() + { + instance_.initialize(); + } + + public override void + destroy() + { + } + + public override void setCertificates(X509Certificate2Collection certs) + { + instance_.setCertificates(certs); + } + + public override void setCertificateVerifier(CertificateVerifier verifier) + { + instance_.setCertificateVerifier(verifier); + } + + private Instance instance_; } } diff --git a/cs/src/IceSSL/RFC2253.cs b/cs/src/IceSSL/RFC2253.cs index 1a90bf5143c..9f1570d106c 100755 --- a/cs/src/IceSSL/RFC2253.cs +++ b/cs/src/IceSSL/RFC2253.cs @@ -21,480 +21,480 @@ namespace IceSSL internal class ParseException : System.Exception { internal ParseException() - { - } + { + } internal ParseException(string reason) - { - this.reason = reason; - } + { + this.reason = reason; + } internal string ice_name() - { - return "RFC2253::ParseException"; - } + { + return "RFC2253::ParseException"; + } internal string reason; } internal struct RDNPair - { - internal string key; - internal string value; - }; + { + internal string key; + internal string value; + }; - internal static ArrayList - parse(string data) - { - ArrayList results = new ArrayList(); - ArrayList current = new ArrayList(); - int pos = 0; - while(pos < data.Length) - { - current.Add(parseNameComponent(data, ref pos)); - eatWhite(data, ref pos); - if(pos < data.Length && data[pos] == ',') - { - ++pos; - } - else if(pos < data.Length && data[pos] == ';') - { - ++pos; - results.Add(current); - current = new ArrayList(); - } - else if(pos < data.Length) - { - throw new ParseException("expected ',' or ';' at `" + data.Substring(pos) + "'"); - } - } - if(current.Count > 0) - { - results.Add(current); - } + internal static ArrayList + parse(string data) + { + ArrayList results = new ArrayList(); + ArrayList current = new ArrayList(); + int pos = 0; + while(pos < data.Length) + { + current.Add(parseNameComponent(data, ref pos)); + eatWhite(data, ref pos); + if(pos < data.Length && data[pos] == ',') + { + ++pos; + } + else if(pos < data.Length && data[pos] == ';') + { + ++pos; + results.Add(current); + current = new ArrayList(); + } + else if(pos < data.Length) + { + throw new ParseException("expected ',' or ';' at `" + data.Substring(pos) + "'"); + } + } + if(current.Count > 0) + { + results.Add(current); + } - return results; - } + return results; + } - internal static ArrayList - parseStrict(string data) - { - ArrayList results = new ArrayList(); - int pos = 0; - while(pos < data.Length) - { - results.Add(parseNameComponent(data, ref pos)); - eatWhite(data, ref pos); - if(pos < data.Length && - (data[pos] == ',' || data[pos] == ';')) - { - ++pos; - } - else if(pos < data.Length) - { - throw new ParseException("expected ',' or ';' at `" + data.Substring(pos) + "'"); - } - } - return results; - } - - public static string - unescape(string data) - { - if(data.Length == 0) - { - return data; - } + internal static ArrayList + parseStrict(string data) + { + ArrayList results = new ArrayList(); + int pos = 0; + while(pos < data.Length) + { + results.Add(parseNameComponent(data, ref pos)); + eatWhite(data, ref pos); + if(pos < data.Length && + (data[pos] == ',' || data[pos] == ';')) + { + ++pos; + } + else if(pos < data.Length) + { + throw new ParseException("expected ',' or ';' at `" + data.Substring(pos) + "'"); + } + } + return results; + } + + public static string + unescape(string data) + { + if(data.Length == 0) + { + return data; + } - if(data[0] == '"') - { - if(data[data.Length - 1] != '"') - { - throw new ParseException("unescape: missing \""); - } - // - // Return the string without quotes. - // - return data.Substring(1, data.Length - 2); - } - - // - // Unescape the entire string. - // - string result = ""; - if(data[0] == '#') - { - int pos = 1; - while(pos < data.Length) - { - result += unescapeHex(data, pos); - pos += 2; - } - } - else - { - int pos = 0; - while (pos < data.Length) - { - if(data[pos] != '\\') - { - result += data[pos]; - ++pos; - } - else - { - ++pos; - if(pos >= data.Length) - { - throw new ParseException("unescape: invalid escape sequence"); - } - if(special.IndexOf(data[pos]) != -1 || data[pos] != '\\' || data[pos] != '"') - { - result += data[pos]; - ++pos; - } - else - { - result += unescapeHex(data, pos); - pos += 2; - } - } - } - } - return result; - } - - private static int - hexToInt(char v) - { - if(v >= '0' && v <= '9') - { - return v - '0'; - } - if(v >= 'a' && v <= 'f') - { - return 10 + (v - 'a'); - } - if(v >= 'A' && v <= 'F') - { - return 10 + (v - 'A'); - } - throw new ParseException("unescape: invalid hex pair"); - } - - private static char - unescapeHex(string data, int pos) - { - Debug.Assert(pos < data.Length); - if(pos + 2 >= data.Length) - { - throw new ParseException("unescape: invalid hex pair"); - } - return (char)(hexToInt(data[pos]) * 16 + hexToInt(data[pos + 1])); - } + if(data[0] == '"') + { + if(data[data.Length - 1] != '"') + { + throw new ParseException("unescape: missing \""); + } + // + // Return the string without quotes. + // + return data.Substring(1, data.Length - 2); + } + + // + // Unescape the entire string. + // + string result = ""; + if(data[0] == '#') + { + int pos = 1; + while(pos < data.Length) + { + result += unescapeHex(data, pos); + pos += 2; + } + } + else + { + int pos = 0; + while (pos < data.Length) + { + if(data[pos] != '\\') + { + result += data[pos]; + ++pos; + } + else + { + ++pos; + if(pos >= data.Length) + { + throw new ParseException("unescape: invalid escape sequence"); + } + if(special.IndexOf(data[pos]) != -1 || data[pos] != '\\' || data[pos] != '"') + { + result += data[pos]; + ++pos; + } + else + { + result += unescapeHex(data, pos); + pos += 2; + } + } + } + } + return result; + } + + private static int + hexToInt(char v) + { + if(v >= '0' && v <= '9') + { + return v - '0'; + } + if(v >= 'a' && v <= 'f') + { + return 10 + (v - 'a'); + } + if(v >= 'A' && v <= 'F') + { + return 10 + (v - 'A'); + } + throw new ParseException("unescape: invalid hex pair"); + } + + private static char + unescapeHex(string data, int pos) + { + Debug.Assert(pos < data.Length); + if(pos + 2 >= data.Length) + { + throw new ParseException("unescape: invalid hex pair"); + } + return (char)(hexToInt(data[pos]) * 16 + hexToInt(data[pos + 1])); + } - private static RDNPair - parseNameComponent(string data, ref int pos) - { - RDNPair result = parseAttributeTypeAndValue(data, ref pos); - while(pos < data.Length) - { - eatWhite(data, ref pos); - if(pos < data.Length && data[pos] == '+') - { - ++pos; - } - else - { - break; - } - RDNPair p = parseAttributeTypeAndValue(data, ref pos); - result.value += "+"; - result.value += p.key; - result.value += '='; - result.value += p.value; - } - return result; - } + private static RDNPair + parseNameComponent(string data, ref int pos) + { + RDNPair result = parseAttributeTypeAndValue(data, ref pos); + while(pos < data.Length) + { + eatWhite(data, ref pos); + if(pos < data.Length && data[pos] == '+') + { + ++pos; + } + else + { + break; + } + RDNPair p = parseAttributeTypeAndValue(data, ref pos); + result.value += "+"; + result.value += p.key; + result.value += '='; + result.value += p.value; + } + return result; + } - private static RDNPair - parseAttributeTypeAndValue(string data, ref int pos) - { - RDNPair p = new RDNPair(); - p.key = parseAttributeType(data, ref pos); - eatWhite(data, ref pos); - if(pos >= data.Length) - { - throw new ParseException("invalid attribute type/value pair (unexpected end of data)"); - } - if(data[pos] != '=') - { - throw new ParseException("invalid attribute type/value pair (missing =). remainder: " + - data.Substring(pos)); - } - ++pos; - p.value = parseAttributeValue(data, ref pos); - return p; - } + private static RDNPair + parseAttributeTypeAndValue(string data, ref int pos) + { + RDNPair p = new RDNPair(); + p.key = parseAttributeType(data, ref pos); + eatWhite(data, ref pos); + if(pos >= data.Length) + { + throw new ParseException("invalid attribute type/value pair (unexpected end of data)"); + } + if(data[pos] != '=') + { + throw new ParseException("invalid attribute type/value pair (missing =). remainder: " + + data.Substring(pos)); + } + ++pos; + p.value = parseAttributeValue(data, ref pos); + return p; + } - private static string - parseAttributeType(string data, ref int pos) - { - eatWhite(data, ref pos); - if(pos >= data.Length) - { - throw new ParseException("invalid attribute type (expected end of data)"); - } + private static string + parseAttributeType(string data, ref int pos) + { + eatWhite(data, ref pos); + if(pos >= data.Length) + { + throw new ParseException("invalid attribute type (expected end of data)"); + } - string result = ""; + string result = ""; - // - // RFC 1779. - // <key> ::= 1*( <keychar> ) | "OID." <oid> | "oid." <oid> - // <oid> ::= <digitstring> | <digitstring> "." <oid> - // RFC 2253: - // attributeType = (ALPHA 1*keychar) | oid - // keychar = ALPHA | DIGIT | "-" - // oid = 1*DIGIT *("." 1*DIGIT) - // - // In section 4 of RFC 2253 the document says: - // Implementations MUST allow an oid in the attribute type to be - // prefixed by one of the character strings "oid." or "OID.". - // - // Here we must also check for "oid." and "OID." before parsing - // according to the ALPHA KEYCHAR* rule. - // - // First the OID case. - // - if(Char.IsDigit(data[pos]) || - (data.Length - pos >= 4 && (data.Substring(pos, 4) == "oid." || - data.Substring(pos, 4) == "OID."))) - { - if(!Char.IsDigit(data[pos])) - { - result += data.Substring(pos, 4); - pos += 4; - } + // + // RFC 1779. + // <key> ::= 1*( <keychar> ) | "OID." <oid> | "oid." <oid> + // <oid> ::= <digitstring> | <digitstring> "." <oid> + // RFC 2253: + // attributeType = (ALPHA 1*keychar) | oid + // keychar = ALPHA | DIGIT | "-" + // oid = 1*DIGIT *("." 1*DIGIT) + // + // In section 4 of RFC 2253 the document says: + // Implementations MUST allow an oid in the attribute type to be + // prefixed by one of the character strings "oid." or "OID.". + // + // Here we must also check for "oid." and "OID." before parsing + // according to the ALPHA KEYCHAR* rule. + // + // First the OID case. + // + if(Char.IsDigit(data[pos]) || + (data.Length - pos >= 4 && (data.Substring(pos, 4) == "oid." || + data.Substring(pos, 4) == "OID."))) + { + if(!Char.IsDigit(data[pos])) + { + result += data.Substring(pos, 4); + pos += 4; + } - while(true) - { - // 1*DIGIT - while(pos < data.Length && Char.IsDigit(data[pos])) - { - result += data[pos]; - ++pos; - } - // "." 1*DIGIT - if(pos < data.Length && data[pos] == '.') - { - result += data[pos]; - ++pos; - // 1*DIGIT must follow "." - if(pos < data.Length && !Char.IsDigit(data[pos])) - { - throw new ParseException("invalid attribute type (expected end of data)"); - } - } - else - { - break; - } - } - } - else if(Char.IsUpper(data[pos]) || - Char.IsLower(data[pos])) - { - // - // The grammar is wrong in this case. It should be ALPHA - // KEYCHAR* otherwise it will not accept "O" as a valid - // attribute type. - // - result += data[pos]; - ++pos; - // 1* KEYCHAR - while(pos < data.Length && - (Char.IsDigit(data[pos]) || - Char.IsUpper(data[pos]) || - Char.IsLower(data[pos]) || - data[pos] == '-')) - { - result += data[pos]; - ++pos; - } - } - else - { - throw new ParseException("invalid attribute type"); - } - return result; - } + while(true) + { + // 1*DIGIT + while(pos < data.Length && Char.IsDigit(data[pos])) + { + result += data[pos]; + ++pos; + } + // "." 1*DIGIT + if(pos < data.Length && data[pos] == '.') + { + result += data[pos]; + ++pos; + // 1*DIGIT must follow "." + if(pos < data.Length && !Char.IsDigit(data[pos])) + { + throw new ParseException("invalid attribute type (expected end of data)"); + } + } + else + { + break; + } + } + } + else if(Char.IsUpper(data[pos]) || + Char.IsLower(data[pos])) + { + // + // The grammar is wrong in this case. It should be ALPHA + // KEYCHAR* otherwise it will not accept "O" as a valid + // attribute type. + // + result += data[pos]; + ++pos; + // 1* KEYCHAR + while(pos < data.Length && + (Char.IsDigit(data[pos]) || + Char.IsUpper(data[pos]) || + Char.IsLower(data[pos]) || + data[pos] == '-')) + { + result += data[pos]; + ++pos; + } + } + else + { + throw new ParseException("invalid attribute type"); + } + return result; + } - private static string - parseAttributeValue(string data, ref int pos) - { - eatWhite(data, ref pos); - string result = ""; - if(pos >= data.Length) - { - return result; - } + private static string + parseAttributeValue(string data, ref int pos) + { + eatWhite(data, ref pos); + string result = ""; + if(pos >= data.Length) + { + return result; + } - // - // RFC 2253 - // # hexstring - // - if(data[pos] == '#') - { - result += data[pos]; - ++pos; - while(true) - { - string h = parseHexPair(data, ref pos, true); - if(h.Length == 0) - { - break; - } - result += h; - } - } - // - // RFC 2253 - // QUOTATION *( quotechar | pair ) QUOTATION ; only from v2 - // quotechar = <any character except "\" or QUOTATION > - // - else if(data[pos] == '"') - { - result += data[pos]; - ++pos; - while(true) - { - if(pos >= data.Length) - { - throw new ParseException("invalid attribute value (unexpected end of data)"); - } - // final terminating " - if(data[pos] == '"') - { - result += data[pos]; - ++pos; - break; - } - // any character except '\' - else if(data[pos] != '\\') - { - result += data[pos]; - ++pos; - } - // pair '\' - else - { - result += parsePair(data, ref pos); - } - } - } - // - // RFC 2253 - // * (stringchar | pair) - // stringchar = <any character except one of special, "\" or QUOTATION > - // - else - { - while(pos < data.Length) - { - if(data[pos] == '\\') - { - result += parsePair(data, ref pos); - } - else if(special.IndexOf(data[pos]) == -1 && data[pos] != '"') - { - result += data[pos]; - ++pos; - } - else - { - break; - } - } - } - return result; - } + // + // RFC 2253 + // # hexstring + // + if(data[pos] == '#') + { + result += data[pos]; + ++pos; + while(true) + { + string h = parseHexPair(data, ref pos, true); + if(h.Length == 0) + { + break; + } + result += h; + } + } + // + // RFC 2253 + // QUOTATION *( quotechar | pair ) QUOTATION ; only from v2 + // quotechar = <any character except "\" or QUOTATION > + // + else if(data[pos] == '"') + { + result += data[pos]; + ++pos; + while(true) + { + if(pos >= data.Length) + { + throw new ParseException("invalid attribute value (unexpected end of data)"); + } + // final terminating " + if(data[pos] == '"') + { + result += data[pos]; + ++pos; + break; + } + // any character except '\' + else if(data[pos] != '\\') + { + result += data[pos]; + ++pos; + } + // pair '\' + else + { + result += parsePair(data, ref pos); + } + } + } + // + // RFC 2253 + // * (stringchar | pair) + // stringchar = <any character except one of special, "\" or QUOTATION > + // + else + { + while(pos < data.Length) + { + if(data[pos] == '\\') + { + result += parsePair(data, ref pos); + } + else if(special.IndexOf(data[pos]) == -1 && data[pos] != '"') + { + result += data[pos]; + ++pos; + } + else + { + break; + } + } + } + return result; + } - // - // RFC2253: - // pair = "\" ( special | "\" | QUOTATION | hexpair ) - // - private static string - parsePair(string data, ref int pos) - { - string result = ""; + // + // RFC2253: + // pair = "\" ( special | "\" | QUOTATION | hexpair ) + // + private static string + parsePair(string data, ref int pos) + { + string result = ""; - Debug.Assert(data[pos] == '\\'); - result += data[pos]; - ++pos; + Debug.Assert(data[pos] == '\\'); + result += data[pos]; + ++pos; - if(pos >= data.Length) - { - throw new ParseException("invalid escape format (unexpected end of data)"); - } + if(pos >= data.Length) + { + throw new ParseException("invalid escape format (unexpected end of data)"); + } - if(special.IndexOf(data[pos]) != -1 || data[pos] != '\\' || - data[pos] != '"') - { - result += data[pos]; - ++pos; - return result; - } - return parseHexPair(data, ref pos, false); - } + if(special.IndexOf(data[pos]) != -1 || data[pos] != '\\' || + data[pos] != '"') + { + result += data[pos]; + ++pos; + return result; + } + return parseHexPair(data, ref pos, false); + } - // - // RFC 2253 - // hexpair = hexchar hexchar - // - private static string - parseHexPair(string data, ref int pos, bool allowEmpty) - { - string result = ""; - if(pos < data.Length && hexvalid.IndexOf(data[pos]) != -1) - { - result += data[pos]; - ++pos; - } - if(pos < data.Length && hexvalid.IndexOf(data[pos]) != -1) - { - result += data[pos]; - ++pos; - } - if(result.Length != 2) - { - if(allowEmpty && result.Length == 0) - { - return result; - } - throw new ParseException("invalid hex format"); - } - return result; - } + // + // RFC 2253 + // hexpair = hexchar hexchar + // + private static string + parseHexPair(string data, ref int pos, bool allowEmpty) + { + string result = ""; + if(pos < data.Length && hexvalid.IndexOf(data[pos]) != -1) + { + result += data[pos]; + ++pos; + } + if(pos < data.Length && hexvalid.IndexOf(data[pos]) != -1) + { + result += data[pos]; + ++pos; + } + if(result.Length != 2) + { + if(allowEmpty && result.Length == 0) + { + return result; + } + throw new ParseException("invalid hex format"); + } + return result; + } - // - // RFC 2253: - // - // Implementations MUST allow for space (' ' ASCII 32) characters to be - // present between name-component and ',', between attributeTypeAndValue - // and '+', between attributeType and '=', and between '=' and - // attributeValue. These space characters are ignored when parsing. - // - private static void - eatWhite(string data, ref int pos) - { - while(pos < data.Length && data[pos] == ' ') - { - ++pos; - } - } + // + // RFC 2253: + // + // Implementations MUST allow for space (' ' ASCII 32) characters to be + // present between name-component and ',', between attributeTypeAndValue + // and '+', between attributeType and '=', and between '=' and + // attributeValue. These space characters are ignored when parsing. + // + private static void + eatWhite(string data, ref int pos) + { + while(pos < data.Length && data[pos] == ' ') + { + ++pos; + } + } - private static string special = ",=+<>#;"; - private static string hexvalid = "0123456789abcdefABCDEF"; + private static string special = ",=+<>#;"; + private static string hexvalid = "0123456789abcdefABCDEF"; } } diff --git a/cs/src/IceSSL/TransceiverI.cs b/cs/src/IceSSL/TransceiverI.cs index d7d18a636bd..e87ab78494f 100755 --- a/cs/src/IceSSL/TransceiverI.cs +++ b/cs/src/IceSSL/TransceiverI.cs @@ -21,25 +21,25 @@ namespace IceSSL sealed class TransceiverI : IceInternal.Transceiver { - public Socket fd() - { - Debug.Assert(fd_ != null); - return fd_; - } - - public void close() - { - if(instance_.networkTraceLevel() >= 1) - { - string s = "closing ssl connection\n" + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - - lock(this) - { - Debug.Assert(fd_ != null); - try - { + public Socket fd() + { + Debug.Assert(fd_ != null); + return fd_; + } + + public void close() + { + if(instance_.networkTraceLevel() >= 1) + { + string s = "closing ssl connection\n" + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + + lock(this) + { + Debug.Assert(fd_ != null); + try + { if(stream_ != null) { // @@ -51,229 +51,229 @@ namespace IceSSL { fd_.Close(); } - } - catch(IOException ex) - { - throw new Ice.SocketException(ex); - } - finally - { - fd_ = null; - stream_ = null; - } - } - } - - public void shutdownWrite() - { - if(instance_.networkTraceLevel() >= 2) - { - string s = "shutting down ssl connection for writing\n" + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - - Debug.Assert(fd_ != null); - try - { - fd_.Shutdown(SocketShutdown.Send); - } - catch(SocketException ex) - { - if(IceInternal.Network.notConnected(ex)) - { - return; - } - throw new Ice.SocketException(ex); - } - } - - public void shutdownReadWrite() - { - if(instance_.networkTraceLevel() >= 2) - { - string s = "shutting down ssl connection for reading and writing\n" + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - - Debug.Assert(fd_ != null); - try - { - fd_.Shutdown(SocketShutdown.Both); - } - catch(SocketException ex) - { - if(IceInternal.Network.notConnected(ex)) - { - return; - } - throw new Ice.SocketException(ex); - } - } - - public void write(IceInternal.BasicStream stream, int timeout) - { - Debug.Assert(fd_ != null); - - IceInternal.ByteBuffer buf = stream.prepareWrite(); - int remaining = buf.remaining(); - int position = buf.position(); - try - { - if(timeout == -1) - { - stream_.Write(buf.rawBytes(), position, remaining); - } - else - { - // - // We have to use an asynchronous write to support a timeout. - // - IAsyncResult ar = stream_.BeginWrite(buf.rawBytes(), position, remaining, null, null); - if(!ar.AsyncWaitHandle.WaitOne(timeout, false)) - { - throw new Ice.TimeoutException(); - } - stream_.EndWrite(ar); - } - if(instance_.networkTraceLevel() >= 3) - { - string s = "sent " + remaining + " of " + remaining + " bytes via ssl\n" + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - if(stats_ != null) - { - stats_.bytesSent(type(), remaining); - } - buf.position(position + remaining); - } - catch(IOException ex) - { - if(IceInternal.Network.connectionLost(ex)) - { - throw new Ice.ConnectionLostException(ex); - } - if(IceInternal.Network.timeout(ex)) - { - throw new Ice.TimeoutException(); - } - throw new Ice.SocketException(ex); - } - catch(SocketException ex) // TODO: Necessary? - { - if(IceInternal.Network.connectionLost(ex)) - { - throw new Ice.ConnectionLostException(ex); - } - if(IceInternal.Network.wouldBlock(ex)) - { - throw new Ice.TimeoutException(); - } - throw new Ice.SocketException(ex); - } - catch(Ice.LocalException) - { - throw; - } - catch(Exception ex) - { - throw new Ice.SyscallException(ex); - } - } - - public void read(IceInternal.BasicStream stream, int timeout) - { - Debug.Assert(fd_ != null); - - IceInternal.ByteBuffer buf = stream.prepareRead(); - int remaining = buf.remaining(); - int position = buf.position(); - - try - { - int ret = 0; - while(remaining > 0) - { - if(timeout == -1) - { - ret = stream_.Read(buf.rawBytes(), position, remaining); - if(ret == 0) - { - // - // Try to read again; if zero is returned, the connection is lost. - // - ret = stream_.Read(buf.rawBytes(), position, remaining); - if(ret == 0) - { - throw new Ice.ConnectionLostException(); - } - } - } - else - { - // - // We have to use an asynchronous read to support a timeout. - // - IAsyncResult ar = stream_.BeginRead(buf.rawBytes(), position, remaining, null, null); - if(!ar.AsyncWaitHandle.WaitOne(timeout, false)) - { - throw new Ice.TimeoutException(); - } - ret = stream_.EndRead(ar); - } - if(instance_.networkTraceLevel() >= 3) - { - string s = "received " + ret + " of " + remaining + " bytes via ssl\n" + ToString(); - logger_.trace(instance_.networkTraceCategory(), s); - } - if(stats_ != null) - { - stats_.bytesReceived(type(), ret); - } - remaining -= ret; - buf.position(position += ret); - } - } - catch(IOException ex) - { - if(IceInternal.Network.connectionLost(ex)) - { - throw new Ice.ConnectionLostException(ex); - } - if(IceInternal.Network.timeout(ex)) - { - throw new Ice.TimeoutException(); - } - throw new Ice.SocketException(ex); - } - catch(SocketException ex) // TODO: Necessary? - { - if(IceInternal.Network.connectionLost(ex)) - { - throw new Ice.ConnectionLostException(ex); - } - if(IceInternal.Network.wouldBlock(ex)) - { - throw new Ice.TimeoutException(); - } - throw new Ice.SocketException(ex); - } - catch(Ice.LocalException) - { - throw; - } - catch(Exception ex) - { - throw new Ice.SyscallException(ex); - } - } - - public string type() - { - return "ssl"; - } - - public void initialize(int timeout) - { + } + catch(IOException ex) + { + throw new Ice.SocketException(ex); + } + finally + { + fd_ = null; + stream_ = null; + } + } + } + + public void shutdownWrite() + { + if(instance_.networkTraceLevel() >= 2) + { + string s = "shutting down ssl connection for writing\n" + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + + Debug.Assert(fd_ != null); + try + { + fd_.Shutdown(SocketShutdown.Send); + } + catch(SocketException ex) + { + if(IceInternal.Network.notConnected(ex)) + { + return; + } + throw new Ice.SocketException(ex); + } + } + + public void shutdownReadWrite() + { + if(instance_.networkTraceLevel() >= 2) + { + string s = "shutting down ssl connection for reading and writing\n" + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + + Debug.Assert(fd_ != null); + try + { + fd_.Shutdown(SocketShutdown.Both); + } + catch(SocketException ex) + { + if(IceInternal.Network.notConnected(ex)) + { + return; + } + throw new Ice.SocketException(ex); + } + } + + public void write(IceInternal.BasicStream stream, int timeout) + { + Debug.Assert(fd_ != null); + + IceInternal.ByteBuffer buf = stream.prepareWrite(); + int remaining = buf.remaining(); + int position = buf.position(); + try + { + if(timeout == -1) + { + stream_.Write(buf.rawBytes(), position, remaining); + } + else + { + // + // We have to use an asynchronous write to support a timeout. + // + IAsyncResult ar = stream_.BeginWrite(buf.rawBytes(), position, remaining, null, null); + if(!ar.AsyncWaitHandle.WaitOne(timeout, false)) + { + throw new Ice.TimeoutException(); + } + stream_.EndWrite(ar); + } + if(instance_.networkTraceLevel() >= 3) + { + string s = "sent " + remaining + " of " + remaining + " bytes via ssl\n" + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + if(stats_ != null) + { + stats_.bytesSent(type(), remaining); + } + buf.position(position + remaining); + } + catch(IOException ex) + { + if(IceInternal.Network.connectionLost(ex)) + { + throw new Ice.ConnectionLostException(ex); + } + if(IceInternal.Network.timeout(ex)) + { + throw new Ice.TimeoutException(); + } + throw new Ice.SocketException(ex); + } + catch(SocketException ex) // TODO: Necessary? + { + if(IceInternal.Network.connectionLost(ex)) + { + throw new Ice.ConnectionLostException(ex); + } + if(IceInternal.Network.wouldBlock(ex)) + { + throw new Ice.TimeoutException(); + } + throw new Ice.SocketException(ex); + } + catch(Ice.LocalException) + { + throw; + } + catch(Exception ex) + { + throw new Ice.SyscallException(ex); + } + } + + public void read(IceInternal.BasicStream stream, int timeout) + { + Debug.Assert(fd_ != null); + + IceInternal.ByteBuffer buf = stream.prepareRead(); + int remaining = buf.remaining(); + int position = buf.position(); + + try + { + int ret = 0; + while(remaining > 0) + { + if(timeout == -1) + { + ret = stream_.Read(buf.rawBytes(), position, remaining); + if(ret == 0) + { + // + // Try to read again; if zero is returned, the connection is lost. + // + ret = stream_.Read(buf.rawBytes(), position, remaining); + if(ret == 0) + { + throw new Ice.ConnectionLostException(); + } + } + } + else + { + // + // We have to use an asynchronous read to support a timeout. + // + IAsyncResult ar = stream_.BeginRead(buf.rawBytes(), position, remaining, null, null); + if(!ar.AsyncWaitHandle.WaitOne(timeout, false)) + { + throw new Ice.TimeoutException(); + } + ret = stream_.EndRead(ar); + } + if(instance_.networkTraceLevel() >= 3) + { + string s = "received " + ret + " of " + remaining + " bytes via ssl\n" + ToString(); + logger_.trace(instance_.networkTraceCategory(), s); + } + if(stats_ != null) + { + stats_.bytesReceived(type(), ret); + } + remaining -= ret; + buf.position(position += ret); + } + } + catch(IOException ex) + { + if(IceInternal.Network.connectionLost(ex)) + { + throw new Ice.ConnectionLostException(ex); + } + if(IceInternal.Network.timeout(ex)) + { + throw new Ice.TimeoutException(); + } + throw new Ice.SocketException(ex); + } + catch(SocketException ex) // TODO: Necessary? + { + if(IceInternal.Network.connectionLost(ex)) + { + throw new Ice.ConnectionLostException(ex); + } + if(IceInternal.Network.wouldBlock(ex)) + { + throw new Ice.TimeoutException(); + } + throw new Ice.SocketException(ex); + } + catch(Ice.LocalException) + { + throw; + } + catch(Exception ex) + { + throw new Ice.SyscallException(ex); + } + } + + public string type() + { + return "ssl"; + } + + public void initialize(int timeout) + { if(stream_ == null) { try @@ -356,40 +356,40 @@ namespace IceSSL instance_.traceStream(stream_, IceInternal.Network.fdToString(fd_)); } } - } - - public void checkSendSize(IceInternal.BasicStream stream, int messageSizeMax) - { - if(stream.size() > messageSizeMax) - { - throw new Ice.MemoryLimitException(); - } - } - - public override string ToString() - { - return desc_; - } - - public ConnectionInfo getConnectionInfo() - { - return info_; - } - - // - // Only for use by ConnectorI. - // - internal TransceiverI(Instance instance, Socket fd, SslStream stream, ConnectionInfo info) - { - instance_ = instance; - fd_ = fd; - stream_ = stream; - info_ = info; - logger_ = instance.communicator().getLogger(); - stats_ = instance.communicator().getStats(); - desc_ = IceInternal.Network.fdToString(fd_); + } + + public void checkSendSize(IceInternal.BasicStream stream, int messageSizeMax) + { + if(stream.size() > messageSizeMax) + { + throw new Ice.MemoryLimitException(); + } + } + + public override string ToString() + { + return desc_; + } + + public ConnectionInfo getConnectionInfo() + { + return info_; + } + + // + // Only for use by ConnectorI. + // + internal TransceiverI(Instance instance, Socket fd, SslStream stream, ConnectionInfo info) + { + instance_ = instance; + fd_ = fd; + stream_ = stream; + info_ = info; + logger_ = instance.communicator().getLogger(); + stats_ = instance.communicator().getStats(); + desc_ = IceInternal.Network.fdToString(fd_); verifyPeer_ = 0; - } + } // // Only for use by AcceptorI. @@ -412,125 +412,125 @@ namespace IceSSL } #if DEBUG - ~TransceiverI() - { - /* - lock(this) - { - IceUtil.Assert.FinalizerAssert(fd_ == null); - } - */ - } + ~TransceiverI() + { + /* + lock(this) + { + IceUtil.Assert.FinalizerAssert(fd_ == null); + } + */ + } #endif - internal bool validate(object sender, X509Certificate certificate, X509Chain chain, - SslPolicyErrors sslPolicyErrors) - { - string message = ""; - int errors = (int)sslPolicyErrors; - if((errors & (int)SslPolicyErrors.RemoteCertificateNotAvailable) > 0) - { - if(verifyPeer_ > 1) - { - if(instance_.securityTraceLevel() >= 1) - { - logger_.trace(instance_.securityTraceCategory(), - "SSL certificate validation failed - client certificate not provided"); - } - return false; - } - errors ^= (int)SslPolicyErrors.RemoteCertificateNotAvailable; - message = message + "\nremote certificate not provided (ignored)"; - } - - if((errors & (int)SslPolicyErrors.RemoteCertificateNameMismatch) > 0) - { - // - // This condition is not expected in a server. - // - Debug.Assert(false); - } - - if(errors > 0) - { - if(instance_.securityTraceLevel() >= 1) - { - logger_.trace(instance_.securityTraceCategory(), "SSL certificate validation failed"); - } - return false; - } - - return true; - } - - private class AuthInfo - { - internal SslStream stream; - volatile internal Exception ex; - volatile internal bool done; - } - - private static void authCallback(IAsyncResult ar) - { - AuthInfo info = (AuthInfo)ar.AsyncState; - lock(info) - { - try - { - info.stream.EndAuthenticateAsServer(ar); - } - catch(Exception ex) - { - info.ex = ex; - } - finally - { - info.done = true; - Monitor.Pulse(info); - } - } - } - - private Instance instance_; - private Socket fd_; - private SslStream stream_; - private ConnectionInfo info_; - private string adapterName_; - private Ice.Logger logger_; - private Ice.Stats stats_; - private string desc_; + internal bool validate(object sender, X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + string message = ""; + int errors = (int)sslPolicyErrors; + if((errors & (int)SslPolicyErrors.RemoteCertificateNotAvailable) > 0) + { + if(verifyPeer_ > 1) + { + if(instance_.securityTraceLevel() >= 1) + { + logger_.trace(instance_.securityTraceCategory(), + "SSL certificate validation failed - client certificate not provided"); + } + return false; + } + errors ^= (int)SslPolicyErrors.RemoteCertificateNotAvailable; + message = message + "\nremote certificate not provided (ignored)"; + } + + if((errors & (int)SslPolicyErrors.RemoteCertificateNameMismatch) > 0) + { + // + // This condition is not expected in a server. + // + Debug.Assert(false); + } + + if(errors > 0) + { + if(instance_.securityTraceLevel() >= 1) + { + logger_.trace(instance_.securityTraceCategory(), "SSL certificate validation failed"); + } + return false; + } + + return true; + } + + private class AuthInfo + { + internal SslStream stream; + volatile internal Exception ex; + volatile internal bool done; + } + + private static void authCallback(IAsyncResult ar) + { + AuthInfo info = (AuthInfo)ar.AsyncState; + lock(info) + { + try + { + info.stream.EndAuthenticateAsServer(ar); + } + catch(Exception ex) + { + info.ex = ex; + } + finally + { + info.done = true; + Monitor.Pulse(info); + } + } + } + + private Instance instance_; + private Socket fd_; + private SslStream stream_; + private ConnectionInfo info_; + private string adapterName_; + private Ice.Logger logger_; + private Ice.Stats stats_; + private string desc_; private int verifyPeer_; } internal class TransceiverValidationCallback { - internal TransceiverValidationCallback(TransceiverI transceiver) - { - transceiver_ = transceiver; - certs = null; - } - - internal bool validate(object sender, X509Certificate certificate, X509Chain chain, - SslPolicyErrors sslPolicyErrors) - { - // - // The certificate chain is not available via SslStream, and it is destroyed - // after this callback returns, so we keep a reference to each of the - // certificates. - // - if(chain != null) - { - certs = new X509Certificate2[chain.ChainElements.Count]; - int i = 0; - foreach(X509ChainElement e in chain.ChainElements) - { - certs[i++] = e.Certificate; - } - } - return transceiver_.validate(sender, certificate, chain, sslPolicyErrors); - } - - private TransceiverI transceiver_; - internal X509Certificate2[] certs; + internal TransceiverValidationCallback(TransceiverI transceiver) + { + transceiver_ = transceiver; + certs = null; + } + + internal bool validate(object sender, X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + // + // The certificate chain is not available via SslStream, and it is destroyed + // after this callback returns, so we keep a reference to each of the + // certificates. + // + if(chain != null) + { + certs = new X509Certificate2[chain.ChainElements.Count]; + int i = 0; + foreach(X509ChainElement e in chain.ChainElements) + { + certs[i++] = e.Certificate; + } + } + return transceiver_.validate(sender, certificate, chain, sslPolicyErrors); + } + + private TransceiverI transceiver_; + internal X509Certificate2[] certs; } } diff --git a/cs/src/IceSSL/TrustManager.cs b/cs/src/IceSSL/TrustManager.cs index 9e14e6c68b9..699d6a194b7 100755 --- a/cs/src/IceSSL/TrustManager.cs +++ b/cs/src/IceSSL/TrustManager.cs @@ -18,108 +18,108 @@ namespace IceSSL { internal TrustManager(Ice.Communicator communicator) { - Debug.Assert(communicator != null); - communicator_ = communicator; - Ice.Properties properties = communicator.getProperties(); - traceLevel_ = properties.getPropertyAsInt("IceSSL.Trace.Security"); - string key = null; - try - { - key = "IceSSL.TrustOnly"; - all_ = parse(properties.getProperty(key)); - key = "IceSSL.TrustOnly.Client"; - client_ = parse(properties.getProperty(key)); - key = "IceSSL.TrustOnly.Server"; - allServer_ = parse(properties.getProperty(key)); - Ice.PropertyDict dict = properties.getPropertiesForPrefix("IceSSL.TrustOnly.Server."); + Debug.Assert(communicator != null); + communicator_ = communicator; + Ice.Properties properties = communicator.getProperties(); + traceLevel_ = properties.getPropertyAsInt("IceSSL.Trace.Security"); + string key = null; + try + { + key = "IceSSL.TrustOnly"; + all_ = parse(properties.getProperty(key)); + key = "IceSSL.TrustOnly.Client"; + client_ = parse(properties.getProperty(key)); + key = "IceSSL.TrustOnly.Server"; + allServer_ = parse(properties.getProperty(key)); + Ice.PropertyDict dict = properties.getPropertiesForPrefix("IceSSL.TrustOnly.Server."); foreach (DictionaryEntry entry in dict) { - string dkey = (string)entry.Key; - string dname = dkey.Substring("IceSSL.TrustOnly.Server.".Length); + string dkey = (string)entry.Key; + string dname = dkey.Substring("IceSSL.TrustOnly.Server.".Length); server_[dname] = parse((string)entry.Value); - } - } - catch(RFC2253.ParseException e) - { - Ice.PluginInitializationException ex = new Ice.PluginInitializationException(); - ex.reason = "IceSSL: invalid property " + key + ":\n" + e.reason; - throw ex; - } + } + } + catch(RFC2253.ParseException e) + { + Ice.PluginInitializationException ex = new Ice.PluginInitializationException(); + ex.reason = "IceSSL: invalid property " + key + ":\n" + e.reason; + throw ex; + } } internal bool verify(ConnectionInfo info) { - ArrayList trustset = new ArrayList(); - if(all_.Count != 0) - { - trustset.Add(all_); - } + ArrayList trustset = new ArrayList(); + if(all_.Count != 0) + { + trustset.Add(all_); + } - if(info.incoming) - { - if(allServer_.Count != 0) - { - trustset.Add(allServer_); - } - if(info.adapterName.Length > 0) - { + if(info.incoming) + { + if(allServer_.Count != 0) + { + trustset.Add(allServer_); + } + if(info.adapterName.Length > 0) + { ArrayList p = (ArrayList)server_[info.adapterName]; - if(p != null) - { - trustset.Add(p); - } - } - } - else - { - if(client_.Count != 0) - { - trustset.Add(client_); - } - } + if(p != null) + { + trustset.Add(p); + } + } + } + else + { + if(client_.Count != 0) + { + trustset.Add(client_); + } + } - // - // If there is nothing to match against, then we accept the cert. - // - if(trustset.Count == 0) - { - return true; - } + // + // If there is nothing to match against, then we accept the cert. + // + if(trustset.Count == 0) + { + return true; + } - // - // If there is no certificate then we match false. - // - if(info.certs.Length != 0) - { - X500DistinguishedName subjectDN = info.certs[0].SubjectName; + // + // If there is no certificate then we match false. + // + if(info.certs.Length != 0) + { + X500DistinguishedName subjectDN = info.certs[0].SubjectName; string subjectName = subjectDN.Name; Debug.Assert(subjectName != null); - try - { - // - // Decompose the subject DN into the RDNs. - // - if(traceLevel_ > 0) - { - if(info.incoming) - { - communicator_.getLogger().trace("Security", "trust manager evaluating client:\n" + - "subject = " + subjectName + "\n" + - "adapter = " + info.adapterName + "\n" + - "local addr = " + IceInternal.Network.addrToString(info.localAddr) + "\n" + - "remote addr = " + IceInternal.Network.addrToString(info.remoteAddr)); - } - else - { - communicator_.getLogger().trace("Security", "trust manager evaluating server:\n" + - "subject = " + subjectName + "\n" + - "local addr = " + IceInternal.Network.addrToString(info.localAddr) + "\n" + - "remote addr = " + IceInternal.Network.addrToString(info.remoteAddr)); - } - } + try + { + // + // Decompose the subject DN into the RDNs. + // + if(traceLevel_ > 0) + { + if(info.incoming) + { + communicator_.getLogger().trace("Security", "trust manager evaluating client:\n" + + "subject = " + subjectName + "\n" + + "adapter = " + info.adapterName + "\n" + + "local addr = " + IceInternal.Network.addrToString(info.localAddr) + "\n" + + "remote addr = " + IceInternal.Network.addrToString(info.remoteAddr)); + } + else + { + communicator_.getLogger().trace("Security", "trust manager evaluating server:\n" + + "subject = " + subjectName + "\n" + + "local addr = " + IceInternal.Network.addrToString(info.localAddr) + "\n" + + "remote addr = " + IceInternal.Network.addrToString(info.remoteAddr)); + } + } - ArrayList dn = RFC2253.parseStrict(subjectName); + ArrayList dn = RFC2253.parseStrict(subjectName); // // Unescape the DN. Note that this isn't done in @@ -133,11 +133,11 @@ namespace IceSSL dn[i] = p; } - // - // Try matching against everything in the trust set. - // + // + // Try matching against everything in the trust set. + // foreach(ArrayList matchSet in trustset) - { + { if(traceLevel_ > 0)
{
string s = "trust manager matching PDNs:\n";
@@ -149,7 +149,7 @@ namespace IceSSL s += ';';
}
addSemi = true;
- bool addComma = false;
+ bool addComma = false;
foreach(RFC2253.RDNPair rdn in rdnSet)
{
if(addComma)
@@ -168,16 +168,16 @@ namespace IceSSL {
return true;
}
- } - } - catch(RFC2253.ParseException e) - { - communicator_.getLogger().warning( - "IceSSL: unable to parse certificate DN `" + subjectName + "'\nreason: " + e.reason); - } - } + } + } + catch(RFC2253.ParseException e) + { + communicator_.getLogger().warning( + "IceSSL: unable to parse certificate DN `" + subjectName + "'\nreason: " + e.reason); + } + } - return false; + return false; } private bool @@ -185,44 +185,44 @@ namespace IceSSL { foreach(ArrayList item in matchSet) { - if(matchRDNs(item, subject)) - { - return true; - } - } - return false; + if(matchRDNs(item, subject)) + { + return true; + } + } + return false; } private bool matchRDNs(ArrayList match, ArrayList subject) { - foreach(RFC2253.RDNPair matchRDN in match) - { + foreach(RFC2253.RDNPair matchRDN in match) + { bool found = false; foreach(RFC2253.RDNPair subjectRDN in subject) - { - if(matchRDN.key.Equals(subjectRDN.key)) - { - found = true; - if(!matchRDN.value.Equals(subjectRDN.value)) - { - return false; - } - } - } - if(!found) - { - return false; - } - } - return true; + { + if(matchRDN.key.Equals(subjectRDN.key)) + { + found = true; + if(!matchRDN.value.Equals(subjectRDN.value)) + { + return false; + } + } + } + if(!found) + { + return false; + } + } + return true; } // Note that unlike the C++ & Java implementation this returns unescaped data. ArrayList parse(string value) { - // + // // As with the Java implementation, the DN that comes from // the X500DistinguishedName does not necessarily match // the user's input form. Therefore we need to normalize the @@ -230,11 +230,11 @@ namespace IceSSL // ArrayList l = RFC2253.parse(value); for(int i = 0; i < l.Count; ++i) - { - ArrayList dn = (ArrayList)l[i]; + { + ArrayList dn = (ArrayList)l[i]; for(int j = 0; j < dn.Count; ++j) - { - RFC2253.RDNPair pair = (RFC2253.RDNPair)dn[j]; + { + RFC2253.RDNPair pair = (RFC2253.RDNPair)dn[j]; // Normalize the RDN key. if (pair.key == "emailAddress") { @@ -249,7 +249,7 @@ namespace IceSSL dn[j] = pair; } } - return l; + return l; } private Ice.Communicator communicator_; diff --git a/cs/src/IceSSL/Util.cs b/cs/src/IceSSL/Util.cs index 2ea9c74495f..2e566565a34 100755 --- a/cs/src/IceSSL/Util.cs +++ b/cs/src/IceSSL/Util.cs @@ -20,190 +20,190 @@ namespace IceSSL // public sealed class ConnectionInfo { - // - // The certificate chain. This may be null if the peer did not - // supply a certificate. The peer's certificate (if any) is the - // first one in the chain. - // - public System.Security.Cryptography.X509Certificates.X509Certificate2[] certs; - - // - // The name of the negotiated cipher. - // - public string cipher; - - // - // The local TCP/IP host & port. - // - public System.Net.IPEndPoint localAddr; - - // - // The remote TCP/IP host & port. - // - public System.Net.IPEndPoint remoteAddr; - - // - // If the connection is incoming this bool is true, false - // otherwise. - // - public bool incoming; - - // - // The name of the object adapter that hosts this endpoint, if - // any. - // - public string adapterName; + // + // The certificate chain. This may be null if the peer did not + // supply a certificate. The peer's certificate (if any) is the + // first one in the chain. + // + public System.Security.Cryptography.X509Certificates.X509Certificate2[] certs; + + // + // The name of the negotiated cipher. + // + public string cipher; + + // + // The local TCP/IP host & port. + // + public System.Net.IPEndPoint localAddr; + + // + // The remote TCP/IP host & port. + // + public System.Net.IPEndPoint remoteAddr; + + // + // If the connection is incoming this bool is true, false + // otherwise. + // + public bool incoming; + + // + // The name of the object adapter that hosts this endpoint, if + // any. + // + public string adapterName; } public class ConnectionInvalidException : Ice.LocalException { - #region Slice data members - - public string reason; - - #endregion - - #region Constructors - - private static readonly string _dflt = "ConnectionInvalidException"; - - public ConnectionInvalidException() : base(_dflt) - { - } - - public ConnectionInvalidException(string m__) : base(m__) - { - } - - public ConnectionInvalidException(System.Exception ex__) : base(_dflt, ex__) - { - } - - public ConnectionInvalidException(string m__, System.Exception ex__) : base(m__, ex__) - { - } - - #endregion - - #region Object members - - public override int GetHashCode() - { - int h__ = 0; - if((object)reason != null) - { - h__ = 5 * h__ + reason.GetHashCode(); - } - return h__; - } - - public override bool Equals(object other__) - { - if(other__ == null) - { - return false; - } - if(object.ReferenceEquals(this, other__)) - { - return true; - } - if(!(other__ is ConnectionInvalidException)) - { - return false; - } - if(reason == null) - { - if(((ConnectionInvalidException)other__).reason != null) - { - return false; - } - } - else - { - if(!reason.Equals(((ConnectionInvalidException)other__).reason)) - { - return false; - } - } - return true; - } - - #endregion - - #region Comparison members - - public static bool operator==(ConnectionInvalidException lhs__, ConnectionInvalidException rhs__) - { - return Equals(lhs__, rhs__); - } - - public static bool operator!=(ConnectionInvalidException lhs__, ConnectionInvalidException rhs__) - { - return !Equals(lhs__, rhs__); - } - - #endregion + #region Slice data members + + public string reason; + + #endregion + + #region Constructors + + private static readonly string _dflt = "ConnectionInvalidException"; + + public ConnectionInvalidException() : base(_dflt) + { + } + + public ConnectionInvalidException(string m__) : base(m__) + { + } + + public ConnectionInvalidException(System.Exception ex__) : base(_dflt, ex__) + { + } + + public ConnectionInvalidException(string m__, System.Exception ex__) : base(m__, ex__) + { + } + + #endregion + + #region Object members + + public override int GetHashCode() + { + int h__ = 0; + if((object)reason != null) + { + h__ = 5 * h__ + reason.GetHashCode(); + } + return h__; + } + + public override bool Equals(object other__) + { + if(other__ == null) + { + return false; + } + if(object.ReferenceEquals(this, other__)) + { + return true; + } + if(!(other__ is ConnectionInvalidException)) + { + return false; + } + if(reason == null) + { + if(((ConnectionInvalidException)other__).reason != null) + { + return false; + } + } + else + { + if(!reason.Equals(((ConnectionInvalidException)other__).reason)) + { + return false; + } + } + return true; + } + + #endregion + + #region Comparison members + + public static bool operator==(ConnectionInvalidException lhs__, ConnectionInvalidException rhs__) + { + return Equals(lhs__, rhs__); + } + + public static bool operator!=(ConnectionInvalidException lhs__, ConnectionInvalidException rhs__) + { + return !Equals(lhs__, rhs__); + } + + #endregion } public sealed class Util { - public static ConnectionInfo getConnectionInfo(Ice.Connection connection) - { - Ice.ConnectionI con = (Ice.ConnectionI)connection; - Debug.Assert(con != null); - - // - // Lock the connection directly. This is done because the only - // thing that prevents the transceiver from being closed during - // the duration of the invocation is the connection. - // - lock(con) - { - IceInternal.Transceiver transceiver = con.getTransceiver(); - if(transceiver == null) - { - ConnectionInvalidException ex = new ConnectionInvalidException(); - ex.reason = "connection closed"; - throw ex; - } - - try - { - TransceiverI sslTransceiver = (TransceiverI)transceiver; - return sslTransceiver.getConnectionInfo(); - } - catch(InvalidCastException) - { - ConnectionInvalidException e = new ConnectionInvalidException(); - e.reason = "not ssl connection"; - throw e; - } - } - } - - public static X509Certificate2 createCertificate(string certPEM) - { - char[] chars = certPEM.ToCharArray(); - byte[] bytes = new byte[chars.Length]; - for(int i = 0; i < chars.Length; ++i) - { - bytes[i] = (byte)chars[i]; - } - return new X509Certificate2(bytes); - } - - internal static ConnectionInfo - populateConnectionInfo(System.Net.Security.SslStream stream, System.Net.Sockets.Socket fd, - X509Certificate2[] certs, string adapterName, bool incoming) - { - ConnectionInfo info = new ConnectionInfo(); - info.certs = certs; - info.cipher = stream.CipherAlgorithm.ToString(); - info.localAddr = (System.Net.IPEndPoint)fd.LocalEndPoint; - info.remoteAddr = (System.Net.IPEndPoint)fd.RemoteEndPoint; - info.incoming = incoming; - info.adapterName = adapterName; - return info; - } + public static ConnectionInfo getConnectionInfo(Ice.Connection connection) + { + Ice.ConnectionI con = (Ice.ConnectionI)connection; + Debug.Assert(con != null); + + // + // Lock the connection directly. This is done because the only + // thing that prevents the transceiver from being closed during + // the duration of the invocation is the connection. + // + lock(con) + { + IceInternal.Transceiver transceiver = con.getTransceiver(); + if(transceiver == null) + { + ConnectionInvalidException ex = new ConnectionInvalidException(); + ex.reason = "connection closed"; + throw ex; + } + + try + { + TransceiverI sslTransceiver = (TransceiverI)transceiver; + return sslTransceiver.getConnectionInfo(); + } + catch(InvalidCastException) + { + ConnectionInvalidException e = new ConnectionInvalidException(); + e.reason = "not ssl connection"; + throw e; + } + } + } + + public static X509Certificate2 createCertificate(string certPEM) + { + char[] chars = certPEM.ToCharArray(); + byte[] bytes = new byte[chars.Length]; + for(int i = 0; i < chars.Length; ++i) + { + bytes[i] = (byte)chars[i]; + } + return new X509Certificate2(bytes); + } + + internal static ConnectionInfo + populateConnectionInfo(System.Net.Security.SslStream stream, System.Net.Sockets.Socket fd, + X509Certificate2[] certs, string adapterName, bool incoming) + { + ConnectionInfo info = new ConnectionInfo(); + info.certs = certs; + info.cipher = stream.CipherAlgorithm.ToString(); + info.localAddr = (System.Net.IPEndPoint)fd.LocalEndPoint; + info.remoteAddr = (System.Net.IPEndPoint)fd.RemoteEndPoint; + info.incoming = incoming; + info.adapterName = adapterName; + return info; + } } } diff --git a/cs/src/IceStorm/AssemblyInfo.cs b/cs/src/IceStorm/AssemblyInfo.cs index eb1e978bda8..a8ba8bdaa77 100755 --- a/cs/src/IceStorm/AssemblyInfo.cs +++ b/cs/src/IceStorm/AssemblyInfo.cs @@ -20,6 +20,6 @@ using System.Runtime.CompilerServices; [assembly: AssemblyProduct("IceStorm for C#")] [assembly: AssemblyCopyright("Copyright (c) 2003-2007, ZeroC, Inc.")] [assembly: AssemblyTrademark("Ice")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.2.51")] [assembly: AssemblyDelaySign(false)] |