예제 #1
0
        internal static void DeleteDirectoryNoThrow(string path, bool recursive)
        {
            int retryCount;
            int retryTimeOut;

            // Try parse will set the out parameter to 0 if the string passed in is null, or is outside the range of an int.
            if (!int.TryParse(Environment.GetEnvironmentVariable("MSBUILDDIRECTORYDELETERETRYCOUNT"), out retryCount))
            {
                retryCount = 0;
            }

            if (!int.TryParse(Environment.GetEnvironmentVariable("MSBUILDDIRECTORYDELETRETRYTIMEOUT"), out retryTimeOut))
            {
                retryTimeOut = 0;
            }

            retryCount   = retryCount < 1 ? 2 : retryCount;
            retryTimeOut = retryTimeOut < 1 ? 500 : retryTimeOut;

            for (int i = 0; i < retryCount; i++)
            {
                try
                {
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, recursive);
                        break;
                    }
                }
                catch (Exception ex) when(ExceptionHandling.IsIoRelatedException(ex))
                {
                }

                if (i + 1 < retryCount) // should not wait for the final iteration since we not gonna check anyway
                {
                    Thread.Sleep(retryTimeOut);
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Creates a file with unique temporary file name with a given extension in the specified folder.
        /// File is guaranteed to be unique.
        /// Extension may have an initial period.
        /// If folder is null, the temporary folder will be used.
        /// Caller must delete it when finished.
        /// May throw IOException.
        /// </summary>
        internal static string GetTemporaryFile(string directory, string extension)
        {
            ErrorUtilities.VerifyThrowArgumentLengthIfNotNull(directory, "directory");
            ErrorUtilities.VerifyThrowArgumentLength(extension, "extension");

            if (extension[0] != '.')
            {
                extension = '.' + extension;
            }

            string file = null;

            try
            {
                directory = directory ?? Path.GetTempPath();

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                file = Path.Combine(directory, "tmp" + Guid.NewGuid().ToString("N") + extension);

                ErrorUtilities.VerifyThrow(!File.Exists(file), "Guid should be unique");

                File.WriteAllText(file, String.Empty);
            }
            catch (Exception ex)
            {
                if (ExceptionHandling.NotExpectedException(ex))
                {
                    throw;
                }

                throw new IOException(ResourceUtilities.FormatResourceString("Shared.FailedCreatingTempFile", ex.Message), ex);
            }

            return(file);
        }
        internal static FileInfo GetFileInfoNoThrow(string filePath)
        {
            FileInfo info;

            filePath = AttemptToShortenPath(filePath);
            try
            {
                info = new FileInfo(filePath);
            }
            catch (Exception exception)
            {
                if (ExceptionHandling.NotExpectedException(exception))
                {
                    throw;
                }
                return(null);
            }
            if (info.Exists)
            {
                return(info);
            }
            return(null);
        }
예제 #4
0
            internal static string GetItemSpecModifier(string currentDirectory, string itemSpec, string definingProjectEscaped, string modifier, ref string fullPath)
            {
                ErrorUtilities.VerifyThrow(itemSpec != null, "Need item-spec to modify.");
                ErrorUtilities.VerifyThrow(modifier != null, "Need modifier to apply to item-spec.");

                string modifiedItemSpec = null;

                try
                {
                    if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.FullPath, StringComparison.OrdinalIgnoreCase))
                    {
                        if (fullPath != null)
                        {
                            return(fullPath);
                        }

                        if (currentDirectory == null)
                        {
                            currentDirectory = String.Empty;
                        }

                        modifiedItemSpec = GetFullPath(itemSpec, currentDirectory);
                        fullPath         = modifiedItemSpec;

                        ThrowForUrl(modifiedItemSpec, itemSpec, currentDirectory);
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.RootDir, StringComparison.OrdinalIgnoreCase))
                    {
                        GetItemSpecModifier(currentDirectory, itemSpec, definingProjectEscaped, ItemSpecModifiers.FullPath, ref fullPath);

                        modifiedItemSpec = Path.GetPathRoot(fullPath);

                        if (!EndsWithSlash(modifiedItemSpec))
                        {
                            ErrorUtilities.VerifyThrow(FileUtilitiesRegex.StartsWithUncPattern(modifiedItemSpec),
                                                       "Only UNC shares should be missing trailing slashes.");

                            // restore/append trailing slash if Path.GetPathRoot() has either removed it, or failed to add it
                            // (this happens with UNC shares)
                            modifiedItemSpec += Path.DirectorySeparatorChar;
                        }
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.Filename, StringComparison.OrdinalIgnoreCase))
                    {
                        // if the item-spec is a root directory, it can have no filename
                        if (IsRootDirectory(itemSpec))
                        {
                            // NOTE: this is to prevent Path.GetFileNameWithoutExtension() from treating server and share elements
                            // in a UNC file-spec as filenames e.g. \\server, \\server\share
                            modifiedItemSpec = String.Empty;
                        }
                        else
                        {
                            // Fix path to avoid problem with Path.GetFileNameWithoutExtension when backslashes in itemSpec on Unix
                            modifiedItemSpec = Path.GetFileNameWithoutExtension(FixFilePath(itemSpec));
                        }
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.Extension, StringComparison.OrdinalIgnoreCase))
                    {
                        // if the item-spec is a root directory, it can have no extension
                        if (IsRootDirectory(itemSpec))
                        {
                            // NOTE: this is to prevent Path.GetExtension() from treating server and share elements in a UNC
                            // file-spec as filenames e.g. \\server.ext, \\server\share.ext
                            modifiedItemSpec = String.Empty;
                        }
                        else
                        {
                            modifiedItemSpec = Path.GetExtension(itemSpec);
                        }
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.RelativeDir, StringComparison.OrdinalIgnoreCase))
                    {
                        modifiedItemSpec = GetDirectory(itemSpec);
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.Directory, StringComparison.OrdinalIgnoreCase))
                    {
                        GetItemSpecModifier(currentDirectory, itemSpec, definingProjectEscaped, ItemSpecModifiers.FullPath, ref fullPath);

                        modifiedItemSpec = GetDirectory(fullPath);

                        if (NativeMethodsShared.IsWindows)
                        {
                            int length = -1;
                            if (FileUtilitiesRegex.StartsWithDrivePattern(modifiedItemSpec))
                            {
                                length = 2;
                            }
                            else
                            {
                                length = FileUtilitiesRegex.StartsWithUncPatternMatchLength(modifiedItemSpec);
                            }

                            if (length != -1)
                            {
                                ErrorUtilities.VerifyThrow((modifiedItemSpec.Length > length) && IsSlash(modifiedItemSpec[length]),
                                                           "Root directory must have a trailing slash.");

                                modifiedItemSpec = modifiedItemSpec.Substring(length + 1);
                            }
                        }
                        else
                        {
                            ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(modifiedItemSpec) && IsSlash(modifiedItemSpec[0]),
                                                       "Expected a full non-windows path rooted at '/'.");

                            // A full unix path is always rooted at
                            // `/`, and a root-relative path is the
                            // rest of the string.
                            modifiedItemSpec = modifiedItemSpec.Substring(1);
                        }
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.RecursiveDir, StringComparison.OrdinalIgnoreCase))
                    {
                        // only the BuildItem class can compute this modifier -- so leave empty
                        modifiedItemSpec = String.Empty;
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.Identity, StringComparison.OrdinalIgnoreCase))
                    {
                        modifiedItemSpec = itemSpec;
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.ModifiedTime, StringComparison.OrdinalIgnoreCase))
                    {
                        // About to go out to the filesystem.  This means data is leaving the engine, so need
                        // to unescape first.
                        string unescapedItemSpec = EscapingUtilities.UnescapeAll(itemSpec);

                        FileInfo info = FileUtilities.GetFileInfoNoThrow(unescapedItemSpec);

                        if (info != null)
                        {
                            modifiedItemSpec = info.LastWriteTime.ToString(FileTimeFormat, null);
                        }
                        else
                        {
                            // File does not exist, or path is a directory
                            modifiedItemSpec = String.Empty;
                        }
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.CreatedTime, StringComparison.OrdinalIgnoreCase))
                    {
                        // About to go out to the filesystem.  This means data is leaving the engine, so need
                        // to unescape first.
                        string unescapedItemSpec = EscapingUtilities.UnescapeAll(itemSpec);

                        if (FileSystems.Default.FileExists(unescapedItemSpec))
                        {
                            modifiedItemSpec = File.GetCreationTime(unescapedItemSpec).ToString(FileTimeFormat, null);
                        }
                        else
                        {
                            // File does not exist, or path is a directory
                            modifiedItemSpec = String.Empty;
                        }
                    }
                    else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.AccessedTime, StringComparison.OrdinalIgnoreCase))
                    {
                        // About to go out to the filesystem.  This means data is leaving the engine, so need
                        // to unescape first.
                        string unescapedItemSpec = EscapingUtilities.UnescapeAll(itemSpec);

                        if (FileSystems.Default.FileExists(unescapedItemSpec))
                        {
                            modifiedItemSpec = File.GetLastAccessTime(unescapedItemSpec).ToString(FileTimeFormat, null);
                        }
                        else
                        {
                            // File does not exist, or path is a directory
                            modifiedItemSpec = String.Empty;
                        }
                    }
                    else if (IsDefiningProjectModifier(modifier))
                    {
                        if (String.IsNullOrEmpty(definingProjectEscaped))
                        {
                            // We have nothing to work with, but that's sometimes OK -- so just return String.Empty
                            modifiedItemSpec = String.Empty;
                        }
                        else
                        {
                            if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.DefiningProjectDirectory, StringComparison.OrdinalIgnoreCase))
                            {
                                // ItemSpecModifiers.Directory does not contain the root directory
                                modifiedItemSpec = Path.Combine
                                                   (
                                    GetItemSpecModifier(currentDirectory, definingProjectEscaped, null, ItemSpecModifiers.RootDir),
                                    GetItemSpecModifier(currentDirectory, definingProjectEscaped, null, ItemSpecModifiers.Directory)
                                                   );
                            }
                            else
                            {
                                string additionalModifier = null;

                                if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.DefiningProjectFullPath, StringComparison.OrdinalIgnoreCase))
                                {
                                    additionalModifier = ItemSpecModifiers.FullPath;
                                }
                                else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.DefiningProjectName, StringComparison.OrdinalIgnoreCase))
                                {
                                    additionalModifier = ItemSpecModifiers.Filename;
                                }
                                else if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.DefiningProjectExtension, StringComparison.OrdinalIgnoreCase))
                                {
                                    additionalModifier = ItemSpecModifiers.Extension;
                                }
                                else
                                {
                                    ErrorUtilities.ThrowInternalError("\"{0}\" is not a valid item-spec modifier.", modifier);
                                }

                                modifiedItemSpec = GetItemSpecModifier(currentDirectory, definingProjectEscaped, null, additionalModifier);
                            }
                        }
                    }
                    else
                    {
                        ErrorUtilities.ThrowInternalError("\"{0}\" is not a valid item-spec modifier.", modifier);
                    }
                }
                catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e))
                {
                    ErrorUtilities.VerifyThrowInvalidOperation(false, "Shared.InvalidFilespecForTransform", modifier, itemSpec, e.Message);
                }

                return(modifiedItemSpec);
            }
예제 #5
0
        private static NamedPipeClientStream TryConnectToProcess(string pipeName, int?nodeProcessId, int timeout, Handshake handshake)
        {
            NamedPipeClientStream nodeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous
#if FEATURE_PIPEOPTIONS_CURRENTUSERONLY
                                                                         | PipeOptions.CurrentUserOnly
#endif
                                                                         );

            CommunicationsUtilities.Trace("Attempting connect to PID {0} with pipe {1} with timeout {2} ms", nodeProcessId.HasValue ? nodeProcessId.Value.ToString() : pipeName, pipeName, timeout);

            try
            {
                nodeStream.Connect(timeout);

#if !FEATURE_PIPEOPTIONS_CURRENTUSERONLY
                if (NativeMethodsShared.IsWindows && !NativeMethodsShared.IsMono)
                {
                    // Verify that the owner of the pipe is us.  This prevents a security hole where a remote node has
                    // been faked up with ACLs that would let us attach to it.  It could then issue fake build requests back to
                    // us, potentially causing us to execute builds that do harmful or unexpected things.  The pipe owner can
                    // only be set to the user's own SID by a normal, unprivileged process.  The conditions where a faked up
                    // remote node could set the owner to something else would also let it change owners on other objects, so
                    // this would be a security flaw upstream of us.
                    ValidateRemotePipeSecurityOnWindows(nodeStream);
                }
#endif

                int[] handshakeComponents = handshake.RetrieveHandshakeComponents();
                for (int i = 0; i < handshakeComponents.Length; i++)
                {
                    CommunicationsUtilities.Trace("Writing handshake part {0} to pipe {1}", i, pipeName);
                    nodeStream.WriteIntForHandshake(handshakeComponents[i]);
                }

                // This indicates that we have finished all the parts of our handshake; hopefully the endpoint has as well.
                nodeStream.WriteEndOfHandshakeSignal();

                CommunicationsUtilities.Trace("Reading handshake from pipe {0}", pipeName);

#if NETCOREAPP2_1 || MONO
                nodeStream.ReadEndOfHandshakeSignal(true, timeout);
#else
                nodeStream.ReadEndOfHandshakeSignal(true);
#endif

                // We got a connection.
                CommunicationsUtilities.Trace("Successfully connected to pipe {0}...!", pipeName);
                return(nodeStream);
            }
            catch (Exception e) when(!ExceptionHandling.IsCriticalException(e))
            {
                // Can be:
                // UnauthorizedAccessException -- Couldn't connect, might not be a node.
                // IOException -- Couldn't connect, already in use.
                // TimeoutException -- Couldn't connect, might not be a node.
                // InvalidOperationException – Couldn’t connect, probably a different build
                CommunicationsUtilities.Trace("Failed to connect to pipe {0}. {1}", pipeName, e.Message.TrimEnd());

                // If we don't close any stream, we might hang up the child
                nodeStream?.Dispose();
            }

            return(null);
        }
예제 #6
0
 internal static bool NotExpectedFunctionException(Exception e)
 {
     return(!(e is InvalidCastException) && !(e is ArgumentNullException) && (!(e is FormatException) && !(e is InvalidOperationException)) && ExceptionHandling.NotExpectedReflectionException(e));
 }
예제 #7
0
 internal static bool NotExpectedSerializationException(Exception e)
 {
     return(!(e is SerializationException) && ExceptionHandling.NotExpectedReflectionException(e));
 }
예제 #8
0
 internal static bool NotExpectedReflectionException(Exception e)
 {
     return(!(e is TypeLoadException) && !(e is MethodAccessException) && (!(e is MissingMethodException) && !(e is MemberAccessException)) && (!(e is BadImageFormatException) && !(e is ReflectionTypeLoadException) && (!(e is CustomAttributeFormatException) && !(e is TargetParameterCountException))) && (!(e is InvalidCastException) && !(e is AmbiguousMatchException) && (!(e is InvalidFilterCriteriaException) && !(e is TargetException)) && (!(e is MissingFieldException) && ExceptionHandling.NotExpectedException(e))));
 }
예제 #9
0
 internal static bool NotExpectedIoOrXmlException(Exception e)
 {
     return(!ExceptionHandling.IsXmlException(e) && ExceptionHandling.NotExpectedException(e));
 }
예제 #10
0
 internal static bool IsIoRelatedException(Exception e)
 {
     return(!ExceptionHandling.NotExpectedException(e));
 }
예제 #11
0
 internal static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
 {
     ExceptionHandling.DumpExceptionToFile((Exception)e.ExceptionObject);
 }
            internal static string GetItemSpecModifier(string currentDirectory, string itemSpec, string modifier, ref CopyOnWriteDictionary <string, string> cachedModifiers)
            {
                ErrorUtilities.VerifyThrow(itemSpec != null, "Need item-spec to modify.");
                ErrorUtilities.VerifyThrow(modifier != null, "Need modifier to apply to item-spec.");
                string fullPath = null;

                if (cachedModifiers != null)
                {
                    cachedModifiers.TryGetValue(modifier, out fullPath);
                }
                if (fullPath == null)
                {
                    bool flag = true;
                    try
                    {
                        if (string.Compare(modifier, "FullPath", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            if (currentDirectory == null)
                            {
                                currentDirectory = string.Empty;
                            }
                            fullPath = FileUtilities.GetFullPath(itemSpec, currentDirectory);
                            ThrowForUrl(fullPath, itemSpec, currentDirectory);
                        }
                        else if (string.Compare(modifier, "RootDir", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            string str2;
                            if (currentDirectory == null)
                            {
                                currentDirectory = string.Empty;
                            }
                            if ((cachedModifiers == null) || !cachedModifiers.TryGetValue("FullPath", out str2))
                            {
                                str2 = FileUtilities.GetFullPath(itemSpec, currentDirectory);
                                ThrowForUrl(str2, itemSpec, currentDirectory);
                            }
                            fullPath = Path.GetPathRoot(str2);
                            if (!FileUtilities.EndsWithSlash(fullPath))
                            {
                                ErrorUtilities.VerifyThrow(FileUtilitiesRegex.UNCPattern.IsMatch(fullPath), "Only UNC shares should be missing trailing slashes.");
                                fullPath = fullPath + Path.DirectorySeparatorChar;
                            }
                        }
                        else if (string.Compare(modifier, "Filename", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            if (Path.GetDirectoryName(itemSpec) == null)
                            {
                                fullPath = string.Empty;
                            }
                            else
                            {
                                fullPath = Path.GetFileNameWithoutExtension(itemSpec);
                            }
                        }
                        else if (string.Compare(modifier, "Extension", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            if (Path.GetDirectoryName(itemSpec) == null)
                            {
                                fullPath = string.Empty;
                            }
                            else
                            {
                                fullPath = Path.GetExtension(itemSpec);
                            }
                        }
                        else if (string.Compare(modifier, "RelativeDir", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            fullPath = FileUtilities.GetDirectory(itemSpec);
                        }
                        else if (string.Compare(modifier, "Directory", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            string str3;
                            if (currentDirectory == null)
                            {
                                currentDirectory = string.Empty;
                            }
                            if ((cachedModifiers == null) || !cachedModifiers.TryGetValue("FullPath", out str3))
                            {
                                str3 = FileUtilities.GetFullPath(itemSpec, currentDirectory);
                                ThrowForUrl(str3, itemSpec, currentDirectory);
                            }
                            fullPath = FileUtilities.GetDirectory(str3);
                            Match match = FileUtilitiesRegex.DrivePattern.Match(fullPath);
                            if (!match.Success)
                            {
                                match = FileUtilitiesRegex.UNCPattern.Match(fullPath);
                            }
                            if (match.Success)
                            {
                                ErrorUtilities.VerifyThrow((fullPath.Length > match.Length) && FileUtilities.IsSlash(fullPath[match.Length]), "Root directory must have a trailing slash.");
                                fullPath = fullPath.Substring(match.Length + 1);
                            }
                        }
                        else if (string.Compare(modifier, "RecursiveDir", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            fullPath = string.Empty;
                        }
                        else if (string.Compare(modifier, "Identity", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            flag     = cachedModifiers != null;
                            fullPath = itemSpec;
                        }
                        else if (string.Compare(modifier, "ModifiedTime", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            flag = false;
                            FileInfo fileInfoNoThrow = FileUtilities.GetFileInfoNoThrow(EscapingUtilities.UnescapeAll(itemSpec));
                            if (fileInfoNoThrow != null)
                            {
                                fullPath = fileInfoNoThrow.LastWriteTime.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'.'fffffff", null);
                            }
                            else
                            {
                                fullPath = string.Empty;
                            }
                        }
                        else if (string.Compare(modifier, "CreatedTime", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            flag = false;
                            string path = EscapingUtilities.UnescapeAll(itemSpec);
                            if (File.Exists(path))
                            {
                                fullPath = File.GetCreationTime(path).ToString("yyyy'-'MM'-'dd HH':'mm':'ss'.'fffffff", null);
                            }
                            else
                            {
                                fullPath = string.Empty;
                            }
                        }
                        else if (string.Compare(modifier, "AccessedTime", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            flag = false;
                            string str6 = EscapingUtilities.UnescapeAll(itemSpec);
                            if (File.Exists(str6))
                            {
                                fullPath = File.GetLastAccessTime(str6).ToString("yyyy'-'MM'-'dd HH':'mm':'ss'.'fffffff", null);
                            }
                            else
                            {
                                fullPath = string.Empty;
                            }
                        }
                        else
                        {
                            ErrorUtilities.VerifyThrow(false, "\"{0}\" is not a valid item-spec modifier.", modifier);
                        }
                    }
                    catch (Exception exception)
                    {
                        if (ExceptionHandling.NotExpectedException(exception))
                        {
                            throw;
                        }
                        ErrorUtilities.VerifyThrowInvalidOperation(false, "Shared.InvalidFilespecForTransform", modifier, itemSpec, exception.Message);
                    }
                    ErrorUtilities.VerifyThrow(fullPath != null, "The item-spec modifier \"{0}\" was not evaluated.", modifier);
                    if (flag)
                    {
                        if (cachedModifiers == null)
                        {
                            cachedModifiers = new CopyOnWriteDictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                        }
                        cachedModifiers[modifier] = fullPath;
                    }
                }
                return(fullPath);
            }