File size: 109,501 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using System.Management.Automation.Tracing;
using System.Reflection;
using System.Threading;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
#if NOT_USED
/// <summary>
/// This represents that a remote data is incorrectly encoded.
/// </summary>
public class RemotingEncodingException : RuntimeException
{
#region Constructors
/// <summary>
/// </summary>
public RemotingEncodingException()
: base()
{
}
/// <summary>
/// </summary>
/// <param name="message"></param>
public RemotingEncodingException(string message)
: base (message)
{
}
/// <summary>
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public RemotingEncodingException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorRecord"></param>
public RemotingEncodingException(string message, Exception innerException, ErrorRecord errorRecord)
: base(message, innerException, errorRecord)
{
}
#endregion Constructors
}
#endif // NOT_USED
/// <summary>
/// Constants used by hosts in remoting.
/// </summary>
internal static class RemotingConstants
{
internal static readonly Version HostVersion = PSVersionInfo.PSVersion;
internal static readonly Version ProtocolVersion_2_0 = new(2, 0); // Window 7 RC
internal static readonly Version ProtocolVersion_2_1 = new(2, 1); // Window 7 RTM
internal static readonly Version ProtocolVersion_2_2 = new(2, 2); // Window 8 RTM
internal static readonly Version ProtocolVersion_2_3 = new(2, 3); // Window 10 RTM
internal static readonly Version ProtocolVersion_2_4 = new(2, 4); // PowerShell 7.6
// Minor will be incremented for each change in PSRP client/server stack and new versions will be
// forked on early major release/drop changes history.
// 2.101 to 2.102 - Disconnect support as of M2
// 2.102 to 2.103 - Key exchange protocol changes in M3
// 2.103 to 2.2 - Final ship protocol version value, no change to protocol
// 2.2 to 2.3 - Enabling informational stream
// 2.3 to 2.4 - Deprecate the 'Session_Key' exchange. The following messages are obsolete when both server and client are v2.4+:
// - PUBLIC_KEY
// - PUBLIC_KEY_REQUEST
// - ENCRYPTED_SESSION_KEY
// The padding algorithm 'RSAEncryptionPadding.Pkcs1' used in the 'Session_Key' exchange is NOT secure, and therefore,
// PSRP needs to be used on top of a secure transport and the 'Session_Key' doesn't add any extra security.
// So, we decided to deprecate the 'Session_Key' exchange in PSRP and skip encryption and decryption for 'SecureString'
// objects. Instead, we require the transport to be secure for secure data transfer between PSRP clients and servers.
internal static readonly Version ProtocolVersionCurrent = new(2, 4);
internal static readonly Version ProtocolVersion = ProtocolVersionCurrent;
// Used by remoting commands to add remoting specific note properties.
internal static readonly string ComputerNameNoteProperty = "PSComputerName";
internal static readonly string RunspaceIdNoteProperty = "RunspaceId";
internal static readonly string ShowComputerNameNoteProperty = "PSShowComputerName";
internal static readonly string SourceJobInstanceId = "PSSourceJobInstanceId";
internal static readonly string EventObject = "PSEventObject";
// used by Custom Shell related cmdlets.
internal const string PSSessionConfigurationNoun = "PSSessionConfiguration";
internal const string PSRemotingNoun = "PSRemoting";
internal const string PSPluginDLLName = "pwrshplugin.dll";
internal const string DefaultShellName = "Microsoft.PowerShell";
internal const string MaxIdleTimeoutMS = "2147483647";
}
/// <summary>
/// String constants used for names of properties that are for storing
/// remoting message fields in a PSObject property bag.
/// </summary>
internal static class RemoteDataNameStrings
{
internal const string Destination = "Destination";
internal const string RemotingTargetInterface = "RemotingTargetInterface";
internal const string ClientRunspacePoolId = "ClientRunspacePoolId";
internal const string ClientPowerShellId = "ClientPowerShellId";
internal const string Action = "Action";
internal const string DataType = "DataType";
// used by negotiation algorithm to figure out client's timezone.
internal const string TimeZone = "TimeZone";
internal const string SenderInfoPreferenceVariable = "PSSenderInfo";
// used by negotiation algorithm to figure out if the negotiation
// request (from client) must comply.
internal const string MustComply = "MustComply";
// used by negotiation algorithm. Server sends this information back
// to client to let client know if the negotiation succeeded.
internal const string IsNegotiationSucceeded = "IsNegotiationSucceeded";
#region Host Related Strings
internal const string CallId = "ci";
internal const string MethodId = "mi";
internal const string MethodParameters = "mp";
internal const string MethodReturnValue = "mr";
internal const string MethodException = "me";
internal const string PS_STARTUP_PROTOCOL_VERSION_NAME = "protocolversion";
internal const string PublicKeyAsXml = "PublicKeyAsXml";
internal const string PSVersion = "PSVersion";
internal const string SerializationVersion = "SerializationVersion";
internal const string MethodArrayElementType = "mat";
internal const string MethodArrayLengths = "mal";
internal const string MethodArrayElements = "mae";
internal const string ObjectType = "T";
internal const string ObjectValue = "V";
#endregion
#region Command discovery pipeline
internal const string DiscoveryName = "Name";
internal const string DiscoveryType = "CommandType";
internal const string DiscoveryModule = "Namespace";
internal const string DiscoveryFullyQualifiedModule = "FullyQualifiedModule";
internal const string DiscoveryArgumentList = "ArgumentList";
internal const string DiscoveryCount = "Count";
#endregion
#region PowerShell
internal const string PSInvocationSettings = "PSInvocationSettings";
internal const string ApartmentState = "ApartmentState";
internal const string RemoteStreamOptions = "RemoteStreamOptions";
internal const string AddToHistory = "AddToHistory";
internal const string PowerShell = "PowerShell";
internal const string IsNested = "IsNested";
internal const string HistoryString = "History";
internal const string RedirectShellErrorOutputPipe = "RedirectShellErrorOutputPipe";
internal const string Commands = "Cmds";
internal const string ExtraCommands = "ExtraCmds";
internal const string CommandText = "Cmd";
internal const string IsScript = "IsScript";
internal const string UseLocalScopeNullable = "UseLocalScope";
internal const string MergeUnclaimedPreviousCommandResults = "MergePreviousResults";
internal const string MergeMyResult = "MergeMyResult";
internal const string MergeToResult = "MergeToResult";
internal const string MergeError = "MergeError";
internal const string MergeWarning = "MergeWarning";
internal const string MergeVerbose = "MergeVerbose";
internal const string MergeDebug = "MergeDebug";
internal const string MergeInformation = "MergeInformation";
internal const string Parameters = "Args";
internal const string ParameterName = "N";
internal const string ParameterValue = "V";
internal const string NoInput = "NoInput";
#endregion PowerShell
#region StateInfo
/// <summary>
/// Name of property when Exception is serialized as error record.
/// </summary>
internal const string ExceptionAsErrorRecord = "ExceptionAsErrorRecord";
/// <summary>
/// Property used for encoding state of pipeline when serializing PipelineStateInfo.
/// </summary>
internal const string PipelineState = "PipelineState";
/// <summary>
/// Property used for encoding state of runspace when serializing RunspaceStateInfo.
/// </summary>
internal const string RunspaceState = "RunspaceState";
#endregion StateInfo
#region PSEventArgs
/// <summary>
/// Properties used for serialization of PSEventArgs.
/// </summary>
internal const string PSEventArgsComputerName = "PSEventArgs.ComputerName";
internal const string PSEventArgsRunspaceId = "PSEventArgs.RunspaceId";
internal const string PSEventArgsEventIdentifier = "PSEventArgs.EventIdentifier";
internal const string PSEventArgsSourceIdentifier = "PSEventArgs.SourceIdentifier";
internal const string PSEventArgsTimeGenerated = "PSEventArgs.TimeGenerated";
internal const string PSEventArgsSender = "PSEventArgs.Sender";
internal const string PSEventArgsSourceArgs = "PSEventArgs.SourceArgs";
internal const string PSEventArgsMessageData = "PSEventArgs.MessageData";
#endregion PSEventArgs
#region RunspacePool
internal const string MinRunspaces = "MinRunspaces";
internal const string MaxRunspaces = "MaxRunspaces";
internal const string ThreadOptions = "PSThreadOptions";
internal const string HostInfo = "HostInfo";
internal const string RunspacePoolOperationResponse = "SetMinMaxRunspacesResponse";
internal const string AvailableRunspaces = "AvailableRunspaces";
internal const string PublicKey = "PublicKey";
internal const string EncryptedSessionKey = "EncryptedSessionKey";
internal const string ApplicationArguments = "ApplicationArguments";
internal const string ApplicationPrivateData = "ApplicationPrivateData";
#endregion RunspacePool
#region ProgressRecord
internal const string ProgressRecord_Activity = "Activity";
internal const string ProgressRecord_ActivityId = "ActivityId";
internal const string ProgressRecord_CurrentOperation = "CurrentOperation";
internal const string ProgressRecord_ParentActivityId = "ParentActivityId";
internal const string ProgressRecord_PercentComplete = "PercentComplete";
internal const string ProgressRecord_Type = "Type";
internal const string ProgressRecord_SecondsRemaining = "SecondsRemaining";
internal const string ProgressRecord_StatusDescription = "StatusDescription";
#endregion
}
/// <summary>
/// The destination of the remote message.
/// </summary>
[Flags]
internal enum RemotingDestination : uint
{
InvalidDestination = 0x0,
Client = 0x1,
Server = 0x2,
Listener = 0x4,
}
/// <summary>
/// The layer the remoting message is being communicated between.
/// </summary>
/// <remarks>
/// Please keep in sync with RemotingTargetInterface from
/// C:\e\win7_powershell\admin\monad\nttargets\assemblies\logging\ETW\Manifests\Microsoft-Windows-PowerShell-Instrumentation.man
/// </remarks>
internal enum RemotingTargetInterface : int
{
InvalidTargetInterface = 0,
Session = 1,
RunspacePool = 2,
PowerShell = 3,
}
/// <summary>
/// The type of the remoting message.
/// </summary>
/// <remarks>
/// Please keep in sync with RemotingDataType from
/// C:\e\win7_powershell\admin\monad\nttargets\assemblies\logging\ETW\Manifests\Microsoft-Windows-PowerShell-Instrumentation.man
/// </remarks>
internal enum RemotingDataType : uint
{
InvalidDataType = 0,
/// <summary>
/// This data type is used when an Exception derived from IContainsErrorRecord
/// is caught on server and is sent to client. This exception gets
/// serialized as an error record. On the client this data type is deserialized in
/// to an ErrorRecord.
///
/// ErrorRecord on the client has an instance of RemoteException as exception.
/// </summary>
ExceptionAsErrorRecord = 1,
// Session messages
SessionCapability = 0x00010002,
CloseSession = 0x00010003,
CreateRunspacePool = 0x00010004,
PublicKey = 0x00010005,
EncryptedSessionKey = 0x00010006,
PublicKeyRequest = 0x00010007,
ConnectRunspacePool = 0x00010008,
// Runspace Pool messages
SetMaxRunspaces = 0x00021002,
SetMinRunspaces = 0x00021003,
RunspacePoolOperationResponse = 0x00021004,
RunspacePoolStateInfo = 0x00021005,
CreatePowerShell = 0x00021006,
AvailableRunspaces = 0x00021007,
PSEventArgs = 0x00021008,
ApplicationPrivateData = 0x00021009,
GetCommandMetadata = 0x0002100A,
RunspacePoolInitData = 0x0002100B,
ResetRunspaceState = 0x0002100C,
// Runspace host messages
RemoteHostCallUsingRunspaceHost = 0x00021100,
RemoteRunspaceHostResponseData = 0x00021101,
// PowerShell messages
PowerShellInput = 0x00041002,
PowerShellInputEnd = 0x00041003,
PowerShellOutput = 0x00041004,
PowerShellErrorRecord = 0x00041005,
PowerShellStateInfo = 0x00041006,
PowerShellDebug = 0x00041007,
PowerShellVerbose = 0x00041008,
PowerShellWarning = 0x00041009,
PowerShellProgress = 0x00041010,
PowerShellInformationStream = 0x00041011,
StopPowerShell = 0x00041012,
// PowerShell host messages
RemoteHostCallUsingPowerShellHost = 0x00041100,
RemotePowerShellHostResponseData = 0x00041101,
}
/// <summary>
/// Converts C# types to PSObject properties for embedding in PSObjects transported across the wire.
/// </summary>
internal static class RemotingEncoder
{
#region NotePropertyHelpers
internal delegate T ValueGetterDelegate<T>();
internal static void AddNoteProperty<T>(PSObject pso, string propertyName, ValueGetterDelegate<T> valueGetter)
{
T value = default(T);
try
{
value = valueGetter();
}
catch (Exception e)
{
Dbg.Assert(false, "Internal code shouldn't throw exceptions during serialization");
PSEtwLog.LogAnalyticWarning(
PSEventId.Serializer_PropertyGetterFailed, PSOpcode.Exception, PSTask.Serialization,
PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic,
propertyName,
valueGetter.Target == null ? string.Empty : valueGetter.Target.GetType().FullName,
e.ToString(),
e.InnerException == null ? string.Empty : e.InnerException.ToString());
}
try
{
pso.Properties.Add(new PSNoteProperty(propertyName, value));
}
catch (ExtendedTypeSystemException)
{
// Member already exists, just make sure the value is the same.
var existingValue = pso.Properties[propertyName].Value;
Diagnostics.Assert(object.Equals(existingValue, value),
"Property already exists but new value differs.");
}
}
internal static PSObject CreateEmptyPSObject()
{
PSObject pso = new PSObject();
// we don't care about serializing/deserializing TypeNames in remoting objects/messages
// so we just omit TypeNames info to lower packet size and improve performance
pso.InternalTypeNames = ConsolidatedString.Empty;
return pso;
}
private static PSNoteProperty CreateHostInfoProperty(HostInfo hostInfo)
{
return new PSNoteProperty(
RemoteDataNameStrings.HostInfo,
RemoteHostEncoder.EncodeObject(hostInfo));
}
#endregion NotePropertyHelpers
#region RunspacePool related
/// <summary>
/// This method generates a Remoting data structure handler message for
/// creating a RunspacePool on the server.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the clientRunspacePool.</param>
/// <param name="minRunspaces">minRunspaces for the RunspacePool
/// to be created at the server</param>
/// <param name="maxRunspaces">maxRunspaces for the RunspacePool
/// to be created at the server</param>
/// <param name="runspacePool">Local runspace pool.</param>
/// <param name="host">host for the runspacepool at the client end
/// from this host, information will be extracted and sent to
/// server</param>
/// <param name="applicationArguments">
/// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/>
/// </param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | S | Session | CRPID | 0 | CreateRuns | minRunspaces, | InvalidDataType |
/// | | | | | pacePool | maxRunspaces, | |
/// | | | | | | threadOptions, | |
/// | | | | | | apartmentState,| |
/// | | | | | | hostInfo | |
/// | | | | | | appParameters | |
/// --------------------------------------------------------------------------------------
///
///
internal static RemoteDataObject GenerateCreateRunspacePool(
Guid clientRunspacePoolId,
int minRunspaces,
int maxRunspaces,
RemoteRunspacePoolInternal runspacePool,
PSHost host,
PSPrimitiveDictionary applicationArguments)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MinRunspaces, minRunspaces));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MaxRunspaces, maxRunspaces));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ThreadOptions, runspacePool.ThreadOptions));
ApartmentState poolState = runspacePool.ApartmentState;
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ApartmentState, poolState));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ApplicationArguments, applicationArguments));
// a runspace's host info always needs to be cached. This is because
// at a later point in time, a powershell may choose to use the
// runspace's host and may require that it uses cached Raw UI properties
dataAsPSObject.Properties.Add(CreateHostInfoProperty(new HostInfo(host)));
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.CreateRunspacePool,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method generates a Remoting data structure handler message for
/// creating a RunspacePool on the server.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the clientRunspacePool.</param>
/// <param name="minRunspaces">minRunspaces for the RunspacePool
/// to be created at the server</param>
/// <param name="maxRunspaces">maxRunspaces for the RunspacePool
/// to be created at the server</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | ConnectRun | minRunspaces, | InvalidDataType |
/// | | | | | spacePool | maxRunspaces, | |
/// | | | | | | | |
/// --------------------------------------------------------------------------------------
///
///
internal static RemoteDataObject GenerateConnectRunspacePool(
Guid clientRunspacePoolId,
int minRunspaces,
int maxRunspaces)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
int propertyCount = 0;
if (minRunspaces != -1)
{
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MinRunspaces, minRunspaces));
propertyCount++;
}
if (maxRunspaces != -1)
{
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MaxRunspaces, maxRunspaces));
propertyCount++;
}
if (propertyCount > 0)
{
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.ConnectRunspacePool,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
else
{
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.ConnectRunspacePool,
clientRunspacePoolId,
Guid.Empty,
string.Empty);
}
}
/// <summary>
/// Generates a response message to ConnectRunspace that includes
/// sufficient information to construction client RunspacePool state.
/// </summary>
/// <param name="runspacePoolId">Id of the clientRunspacePool.</param>
/// <param name="minRunspaces">minRunspaces for the RunspacePool
/// to be created at the server</param>
/// <param name="maxRunspaces">maxRunspaces for the RunspacePool
/// to be created at the server</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C | Runspace | CRPID | 0 | RunspacePo | minRunspaces, | InvalidDataType |
/// | | | | | olInitData | maxRunspaces, | |
/// | | | | | | | |
/// --------------------------------------------------------------------------------------
///
///
internal static RemoteDataObject GenerateRunspacePoolInitData(
Guid runspacePoolId,
int minRunspaces,
int maxRunspaces)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MinRunspaces, minRunspaces));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MaxRunspaces, maxRunspaces));
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.RunspacePoolInitData,
runspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method generates a Remoting data structure handler message for
/// modifying the maxrunspaces of the specified runspace pool on the server.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the clientRunspacePool.</param>
/// <param name="maxRunspaces">new value of maxRunspaces for the
/// specified RunspacePool </param>
/// <param name="callId">Call id of the call at client.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | SetMax | maxRunspaces | InvalidDataType |
/// | | Pool | | | Runspaces | | |
/// | | | | | | | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GenerateSetMaxRunspaces(Guid clientRunspacePoolId,
int maxRunspaces, long callId)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MaxRunspaces, maxRunspaces));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, callId));
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.SetMaxRunspaces,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method generates a Remoting data structure handler message for
/// modifying the maxrunspaces of the specified runspace pool on the server.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the clientRunspacePool.</param>
/// <param name="minRunspaces">new value of minRunspaces for the
/// specified RunspacePool </param>
/// <param name="callId">Call id of the call at client.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | SetMin | minRunspaces | InvalidDataType |
/// | | Pool | | | Runspaces | | |
/// | | | | | | | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GenerateSetMinRunspaces(Guid clientRunspacePoolId,
int minRunspaces, long callId)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MinRunspaces, minRunspaces));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, callId));
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.SetMinRunspaces,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method generates a Remoting data structure handler message for
/// that contains a response to SetMaxRunspaces or SetMinRunspaces.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the clientRunspacePool.</param>
/// <param name="callId">Call id of the call at client.</param>
/// <param name="response">Response to the call.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | SetMax | maxRunspaces | InvalidDataType |
/// | | Pool | | | Runspaces | | |
/// | | | | | | | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GenerateRunspacePoolOperationResponse(Guid clientRunspacePoolId,
object response, long callId)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.RunspacePoolOperationResponse, response));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, callId));
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.RunspacePoolOperationResponse,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method generates a Remoting data structure handler message for
/// getting the available runspaces on the server.
/// </summary>
/// <param name="clientRunspacePoolId">guid of the runspace pool on which
/// this needs to be queried</param>
/// <param name="callId">Call id of the call at the client.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------
/// | D | TI | RPID | PID | Data | Type |
/// ---------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | null |GetAvailableRunspaces |
/// | | Pool | | | | |
/// --------------------------------------------------------------------------
internal static RemoteDataObject GenerateGetAvailableRunspaces(Guid clientRunspacePoolId,
long callId)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, callId));
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.AvailableRunspaces,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method generates a remoting data structure handler message for
/// transferring a roles public key to the other side.
/// </summary>
/// <param name="runspacePoolId">Runspace pool id.</param>
/// <param name="publicKey">Public key to send across.</param>
/// <param name="destination">destination that this message is
/// targeted to</param>
/// <returns>Data structure message.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------
/// | D | TI | RPID | PID | Data | Type |
/// ---------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | public | PublicKey |
/// | | Pool | | | key | |
/// --------------------------------------------------------------------------
internal static RemoteDataObject GenerateMyPublicKey(Guid runspacePoolId,
string publicKey, RemotingDestination destination)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PublicKey, publicKey));
return RemoteDataObject.CreateFrom(destination,
RemotingDataType.PublicKey,
runspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method generates a remoting data structure handler message for
/// requesting a public key from the client to the server.
/// </summary>
/// <param name="runspacePoolId">Runspace pool id.</param>
/// <returns>Data structure message.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------
/// | D | TI | RPID | PID | Data | Type |
/// ---------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | | PublicKeyRequest |
/// | | Pool | | | | |
/// --------------------------------------------------------------------------
internal static RemoteDataObject GeneratePublicKeyRequest(Guid runspacePoolId)
{
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.PublicKeyRequest,
runspacePoolId,
Guid.Empty,
string.Empty);
}
/// <summary>
/// This method generates a remoting data structure handler message for
/// sending an encrypted session key to the client.
/// </summary>
/// <param name="runspacePoolId">Runspace pool id.</param>
/// <param name="encryptedSessionKey">Encrypted session key.</param>
/// <returns>Data structure message.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------
/// | D | TI | RPID | PID | Data | Type |
/// ---------------------------------------------------------------------------
/// | S | Runspace | CRPID | 0 | encrypted | EncryptedSessionKey |
/// | | Pool | | | session key | |
/// --------------------------------------------------------------------------
internal static RemoteDataObject GenerateEncryptedSessionKeyResponse(Guid runspacePoolId,
string encryptedSessionKey)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.EncryptedSessionKey,
encryptedSessionKey));
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.EncryptedSessionKey,
runspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This methods generates a Remoting data structure handler message for
/// creating a command discovery pipeline on the server.
/// </summary>
/// <param name="shell">The client remote powershell from which the
/// message needs to be generated.
/// The data is extracted from parameters of the first command named "Get-Command".
/// </param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// -------------------------------------------------------------------------
/// | D | TI | RPID | PID | Data | Type |
/// --------------------------------------------------------------------------
/// | S | Runspace | CRPID | CPID | name, | GetCommandMetadata |
/// | | Pool | | | commandType, | |
/// | | | | | module,FQM, | |
/// | | | | | argumentList | |
/// --------------------------------------------------------------------------
///
internal static RemoteDataObject GenerateGetCommandMetadata(ClientRemotePowerShell shell)
{
Command getCommand = null;
foreach (Command c in shell.PowerShell.Commands.Commands)
{
if (c.CommandText.Equals("Get-Command", StringComparison.OrdinalIgnoreCase))
{
getCommand = c;
break;
}
}
Dbg.Assert(getCommand != null, "Whoever sets PowerShell.IsGetCommandMetadataSpecialPipeline needs to make sure Get-Command is present");
string[] name = null;
CommandTypes commandTypes = CommandTypes.Alias | CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration;
string[] module = null;
ModuleSpecification[] fullyQualifiedModule = null;
object[] argumentList = null;
foreach (CommandParameter p in getCommand.Parameters)
{
if (p.Name.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
name = (string[])LanguagePrimitives.ConvertTo(p.Value, typeof(string[]), CultureInfo.InvariantCulture);
}
else if (p.Name.Equals("CommandType", StringComparison.OrdinalIgnoreCase))
{
commandTypes = (CommandTypes)LanguagePrimitives.ConvertTo(p.Value, typeof(CommandTypes), CultureInfo.InvariantCulture);
}
else if (p.Name.Equals("Module", StringComparison.OrdinalIgnoreCase))
{
module = (string[])LanguagePrimitives.ConvertTo(p.Value, typeof(string[]), CultureInfo.InvariantCulture);
}
else if (p.Name.Equals("FullyQualifiedModule", StringComparison.OrdinalIgnoreCase))
{
fullyQualifiedModule = (ModuleSpecification[])LanguagePrimitives.ConvertTo(p.Value, typeof(ModuleSpecification[]), CultureInfo.InvariantCulture);
}
else if (p.Name.Equals("ArgumentList", StringComparison.OrdinalIgnoreCase))
{
argumentList = (object[])LanguagePrimitives.ConvertTo(p.Value, typeof(object[]), CultureInfo.InvariantCulture);
}
}
RunspacePool rsPool = shell.PowerShell.GetRunspaceConnection() as RunspacePool;
Dbg.Assert(rsPool != null, "Runspacepool cannot be null for a CreatePowerShell request");
Guid clientRunspacePoolId = rsPool.InstanceId;
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.DiscoveryName, name));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.DiscoveryType, commandTypes));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.DiscoveryModule, module));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.DiscoveryFullyQualifiedModule, fullyQualifiedModule));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.DiscoveryArgumentList, argumentList));
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.GetCommandMetadata,
clientRunspacePoolId,
shell.InstanceId,
dataAsPSObject);
}
/// <summary>
/// This methods generates a Remoting data structure handler message for
/// creating a PowerShell on the server.
/// </summary>
/// <param name="shell">The client remote powershell from which the
/// create powershell message needs to be generated</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// -------------------------------------------------------------------------
/// | D | TI | RPID | PID | Data | Type |
/// --------------------------------------------------------------------------
/// | S | Runspace | CRPID | CPID | serialized | CreatePowerShell |
/// | | Pool | | | powershell, | |
/// | | | | | noInput, | |
/// | | | | | hostInfo, | |
/// | | | | | invocationset | |
/// | | | | | tings, stream | |
/// | | | | | options | |
/// --------------------------------------------------------------------------
///
internal static RemoteDataObject GenerateCreatePowerShell(ClientRemotePowerShell shell)
{
PowerShell powerShell = shell.PowerShell;
PSInvocationSettings settings = shell.Settings;
PSObject dataAsPSObject = CreateEmptyPSObject();
Guid clientRunspacePoolId = Guid.Empty;
HostInfo hostInfo;
PSNoteProperty hostInfoProperty;
RunspacePool rsPool = powerShell.GetRunspaceConnection() as RunspacePool;
Dbg.Assert(rsPool != null, "Runspacepool cannot be null for a CreatePowerShell request");
clientRunspacePoolId = rsPool.InstanceId;
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PowerShell, powerShell.ToPSObjectForRemoting()));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.NoInput, shell.NoInput));
if (settings == null)
{
hostInfo = new HostInfo(null);
hostInfo.UseRunspaceHost = true;
ApartmentState passedApartmentState = rsPool.ApartmentState;
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ApartmentState, passedApartmentState));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.RemoteStreamOptions, RemoteStreamOptions.AddInvocationInfo));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.AddToHistory, false));
}
else
{
hostInfo = new HostInfo(settings.Host);
if (settings.Host == null)
{
hostInfo.UseRunspaceHost = true;
}
ApartmentState passedApartmentState = settings.ApartmentState;
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ApartmentState, passedApartmentState));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.RemoteStreamOptions, settings.RemoteStreamOptions));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.AddToHistory, settings.AddToHistory));
}
hostInfoProperty = CreateHostInfoProperty(hostInfo);
dataAsPSObject.Properties.Add(hostInfoProperty);
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.IsNested, shell.PowerShell.IsNested));
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.CreatePowerShell,
clientRunspacePoolId,
shell.InstanceId,
dataAsPSObject);
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting
/// application private data from server to client.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the client RunspacePool.</param>
/// <param name="applicationPrivateData">Application private data.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C | Runspace | CRPID | -1 | Data | appl. private | PSPrimitive |
/// | | Pool | | | | data | Dictionary|
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GenerateApplicationPrivateData(
Guid clientRunspacePoolId,
PSPrimitiveDictionary applicationPrivateData)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ApplicationPrivateData, applicationPrivateData));
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.ApplicationPrivateData,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a state
/// information from server to client.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the client RunspacePool.</param>
/// <param name="stateInfo">State information object.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C | Runspace | CRPID | -1 | Data | RunspacePool | RunspacePoolState |
/// | | Pool | | | | StateInfo | Info |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GenerateRunspacePoolStateInfo(
Guid clientRunspacePoolId,
RunspacePoolStateInfo stateInfo)
{
// BUGBUG: This object creation needs to be relooked
PSObject dataAsPSObject = CreateEmptyPSObject();
// Add State Property
PSNoteProperty stateProperty =
new PSNoteProperty(RemoteDataNameStrings.RunspaceState,
(int)(stateInfo.State));
dataAsPSObject.Properties.Add(stateProperty);
// Add Reason property
if (stateInfo.Reason != null)
{
PSNoteProperty exceptionProperty = GetExceptionProperty(
exception: stateInfo.Reason,
errorId: "RemoteRunspaceStateInfoReason",
category: ErrorCategory.NotSpecified);
dataAsPSObject.Properties.Add(exceptionProperty);
}
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.RunspacePoolStateInfo,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a PowerShell
/// event from server to client.
/// </summary>
/// <param name="clientRunspacePoolId">Id of the client RunspacePool.</param>
/// <param name="e">PowerShell event.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C | Runspace | CRPID | -1 | Data | RunspacePool | PSEventArgs |
/// | | Pool | | | | StateInfo | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePSEventArgs(Guid clientRunspacePoolId, PSEventArgs e)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsEventIdentifier, e.EventIdentifier));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsSourceIdentifier, e.SourceIdentifier));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsTimeGenerated, e.TimeGenerated));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsSender, e.Sender));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsSourceArgs, e.SourceArgs));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsMessageData, e.MessageData));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsComputerName, e.ComputerName));
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PSEventArgsRunspaceId, e.RunspaceId));
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.PSEventArgs,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// This method creates a remoting data structure handler message to instruct the server to reset
/// the single runspace on the server.
/// </summary>
/// <param name="clientRunspacePoolId"></param>
/// <param name="callId">Caller Id.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------------
/// | S | Runspace | CRPID | -1 | Reset server | None | ResetRunspaceState |
/// | | Pool | | | runspace state | | |
/// ---------------------------------------------------------------------------------------------
internal static RemoteDataObject GenerateResetRunspaceState(Guid clientRunspacePoolId, long callId)
{
PSObject dataAsPSObject = CreateEmptyPSObject();
dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, callId));
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.ResetRunspaceState,
clientRunspacePoolId,
Guid.Empty,
dataAsPSObject);
}
/// <summary>
/// Returns the PS remoting protocol version associated with the provided.
/// </summary>
/// <param name="rsPool">RunspacePool.</param>
/// <returns>PS remoting protocol version.</returns>
internal static Version GetPSRemotingProtocolVersion(RunspacePool rsPool)
{
return (rsPool != null && rsPool.RemoteRunspacePoolInternal != null) ?
rsPool.RemoteRunspacePoolInternal.PSRemotingProtocolVersion : null;
}
#endregion RunspacePool related
#region PowerShell related
/// <summary>
/// This method creates a remoting data structure handler message for sending a powershell
/// input data from the client to the server.
/// </summary>
/// <param name="data">Input data to send.</param>
/// <param name="clientRemoteRunspacePoolId">Client runspace pool id.</param>
/// <param name="clientPowerShellId">Client powershell id.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | S |PowerShell | CRPID | CPID | Data | input data | PowerShellInput |
/// | | | | | | | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellInput(object data, Guid clientRemoteRunspacePoolId,
Guid clientPowerShellId)
{
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.PowerShellInput,
clientRemoteRunspacePoolId,
clientPowerShellId,
data);
}
/// <summary>
/// This method creates a remoting data structure handler message for signalling
/// end of input data for powershell.
/// </summary>
/// <param name="clientRemoteRunspacePoolId">Client runspace pool id.</param>
/// <param name="clientPowerShellId">Client powershell id.</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | S |PowerShell | CRPID | CPID | Data | bool. | PowerShellInputEnd |
/// | | | | | | TrueString | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellInputEnd(Guid clientRemoteRunspacePoolId,
Guid clientPowerShellId)
{
return RemoteDataObject.CreateFrom(RemotingDestination.Server,
RemotingDataType.PowerShellInputEnd,
clientRemoteRunspacePoolId,
clientPowerShellId,
null);
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a
/// powershell output data from server to client.
/// </summary>
/// <param name="data">Data to be sent.</param>
/// <param name="clientPowerShellId">id of client powershell
/// to which this information need to be delivered</param>
/// <param name="clientRunspacePoolId">id of client runspacepool
/// associated with this powershell</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C |PowerShell | CRPID | CPID | Data | data to send | PowerShellOutput |
/// | | | | | | | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellOutput(PSObject data, Guid clientPowerShellId,
Guid clientRunspacePoolId)
{
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.PowerShellOutput,
clientRunspacePoolId,
clientPowerShellId,
data);
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a
/// powershell informational message (debug/verbose/warning/progress)from
/// server to client.
/// </summary>
/// <param name="data">Data to be sent.</param>
/// <param name="clientPowerShellId">id of client powershell
/// to which this information need to be delivered</param>
/// <param name="clientRunspacePoolId">id of client runspacepool
/// associated with this powershell</param>
/// <param name="dataType">data type of this informational
/// message</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C |PowerShell | CRPID | CPID | Data | data to send | DataType - debug, |
/// | | | | | | | verbose, warning |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellInformational(object data,
Guid clientRunspacePoolId, Guid clientPowerShellId, RemotingDataType dataType)
{
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
dataType,
clientRunspacePoolId,
clientPowerShellId,
PSObject.AsPSObject(data));
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a
/// powershell progress message from
/// server to client.
/// </summary>
/// <param name="progressRecord">Progress record to send.</param>
/// <param name="clientPowerShellId">id of client powershell
/// to which this information need to be delivered</param>
/// <param name="clientRunspacePoolId">id of client runspacepool
/// associated with this powershell</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C |PowerShell | CRPID | CPID | Data | progress | PowerShellProgress |
/// | | | | | | message | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellInformational(ProgressRecord progressRecord,
Guid clientRunspacePoolId, Guid clientPowerShellId)
{
if (progressRecord == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(progressRecord));
}
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.PowerShellProgress,
clientRunspacePoolId,
clientPowerShellId,
progressRecord.ToPSObjectForRemoting());
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a
/// powershell information stream message from
/// server to client.
/// </summary>
/// <param name="informationRecord">Information record to send.</param>
/// <param name="clientPowerShellId">id of client powershell
/// to which this information need to be delivered</param>
/// <param name="clientRunspacePoolId">id of client runspacepool
/// associated with this powershell</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// -----------------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// -----------------------------------------------------------------------------------------------
/// | C |PowerShell | CRPID | CPID | Data | information | PowerShellInformationStream |
/// | | | | | | message | |
/// -----------------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellInformational(InformationRecord informationRecord,
Guid clientRunspacePoolId, Guid clientPowerShellId)
{
if (informationRecord == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(informationRecord));
}
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.PowerShellInformationStream,
clientRunspacePoolId,
clientPowerShellId,
informationRecord.ToPSObjectForRemoting());
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a
/// powershell error record from server to client.
/// </summary>
/// <param name="errorRecord">Error record to be sent.</param>
/// <param name="clientPowerShellId">id of client powershell
/// to which this information need to be delivered</param>
/// <param name="clientRunspacePoolId">id of client runspacepool
/// associated with this powershell</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C |PowerShell | CRPID | CPID | Data | error record | PowerShellError |
/// | | | | | | to send | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellError(object errorRecord,
Guid clientRunspacePoolId, Guid clientPowerShellId)
{
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.PowerShellErrorRecord,
clientRunspacePoolId,
clientPowerShellId,
PSObject.AsPSObject(errorRecord));
}
/// <summary>
/// This method creates a remoting data structure handler message for transporting a
/// powershell state information from server to client.
/// </summary>
/// <param name="stateInfo">State information object.</param>
/// <param name="clientPowerShellId">id of client powershell
/// to which this information need to be delivered</param>
/// <param name="clientRunspacePoolId">id of client runspacepool
/// associated with this powershell</param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C |PowerShell | CRPID | CPID | Data | PSInvocation | PowerShellStateInfo |
/// | | | | | | StateInfo | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateInfo stateInfo,
Guid clientPowerShellId, Guid clientRunspacePoolId)
{
// Encode Pipeline StateInfo as PSObject
PSObject dataAsPSObject = CreateEmptyPSObject();
// Convert the state to int and add as property
PSNoteProperty stateProperty = new PSNoteProperty(
RemoteDataNameStrings.PipelineState, (int)(stateInfo.State));
dataAsPSObject.Properties.Add(stateProperty);
// Add exception property
if (stateInfo.Reason != null)
{
PSNoteProperty exceptionProperty = GetExceptionProperty(
exception: stateInfo.Reason,
errorId: "RemotePSInvocationStateInfoReason",
category: ErrorCategory.NotSpecified);
dataAsPSObject.Properties.Add(exceptionProperty);
}
return RemoteDataObject.CreateFrom(RemotingDestination.Client,
RemotingDataType.PowerShellStateInfo,
clientRunspacePoolId,
clientPowerShellId,
dataAsPSObject);
}
#endregion PowerShell related
#region Exception
/// <summary>
/// Gets the error record from exception of type IContainsErrorRecord.
/// </summary>
/// <param name="exception"></param>
/// <returns>
/// ErrorRecord if exception is of type IContainsErrorRecord
/// Null if exception is not of type IContainsErrorRecord
/// </returns>
internal static ErrorRecord GetErrorRecordFromException(Exception exception)
{
Dbg.Assert(exception != null, "Caller should validate the data");
ErrorRecord er = null;
IContainsErrorRecord cer = exception as IContainsErrorRecord;
if (cer != null)
{
er = cer.ErrorRecord;
// Exception inside the error record is ParentContainsErrorRecordException which
// doesn't have stack trace. Replace it with top level exception.
er = new ErrorRecord(er, exception);
}
return er;
}
/// <summary>
/// Gets a Note Property for the exception.
/// </summary>
/// <remarks>
/// If <paramref name="exception"/> is of not type IContainsErrorRecord, a new ErrorRecord is created.
/// </remarks>
/// <param name="exception"></param>
/// <param name="errorId">ErrorId to use if exception is not of type IContainsErrorRecord.</param>
/// <param name="category">ErrorCategory to use if exception is not of type IContainsErrorRecord.</param>
/// <returns></returns>
private static PSNoteProperty GetExceptionProperty(Exception exception, string errorId, ErrorCategory category)
{
Dbg.Assert(exception != null, "Caller should validate the data");
ErrorRecord er = GetErrorRecordFromException(exception) ??
new ErrorRecord(exception, errorId, category, null);
return new PSNoteProperty(RemoteDataNameStrings.ExceptionAsErrorRecord, er);
}
#endregion Exception
#region Session related
/// <summary>
/// This method creates a remoting data structure handler message for transporting a session
/// capability message. Should be used by client.
/// </summary>
/// <param name="capability">RemoteSession capability object to encode.</param>
/// <param name="runspacePoolId"></param>
/// <returns>Data structure handler message encoded as RemoteDataObject.</returns>
/// The message format is as under for this message
/// --------------------------------------------------------------------------------------
/// | D | TI | RPID | PID | Action | Data | Type |
/// --------------------------------------------------------------------------------------
/// | C | Session | RPID | Empty | Data | session | SessionCapability |
/// | / | | | | | capability | |
/// | S | | | | | | |
/// --------------------------------------------------------------------------------------
internal static RemoteDataObject GenerateClientSessionCapability(RemoteSessionCapability capability,
Guid runspacePoolId)
{
PSObject temp = GenerateSessionCapability(capability);
return RemoteDataObject.CreateFrom(capability.RemotingDestination,
RemotingDataType.SessionCapability, runspacePoolId, Guid.Empty, temp);
}
internal static RemoteDataObject GenerateServerSessionCapability(RemoteSessionCapability capability,
Guid runspacePoolId)
{
PSObject temp = GenerateSessionCapability(capability);
return RemoteDataObject.CreateFrom(capability.RemotingDestination,
RemotingDataType.SessionCapability, runspacePoolId, Guid.Empty, temp);
}
private static PSObject GenerateSessionCapability(RemoteSessionCapability capability)
{
PSObject temp = CreateEmptyPSObject();
temp.Properties.Add(
new PSNoteProperty(RemoteDataNameStrings.PS_STARTUP_PROTOCOL_VERSION_NAME, capability.ProtocolVersion));
temp.Properties.Add(
new PSNoteProperty(RemoteDataNameStrings.PSVersion, capability.PSVersion));
temp.Properties.Add(
new PSNoteProperty(RemoteDataNameStrings.SerializationVersion, capability.SerializationVersion));
return temp;
}
#endregion Session related
}
/// <summary>
/// Converts fields of PSObjects containing remoting messages to C# types.
/// </summary>
internal static class RemotingDecoder
{
private static T ConvertPropertyValueTo<T>(string propertyName, object propertyValue)
{
if (propertyName == null) // comes from internal caller
{
throw PSTraceSource.NewArgumentNullException(nameof(propertyName));
}
if (typeof(T).IsEnum)
{
if (propertyValue is string)
{
try
{
string stringValue = (string)propertyValue;
T value = (T)Enum.Parse(typeof(T), stringValue, true);
return value;
}
catch (ArgumentException)
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.CantCastPropertyToExpectedType,
propertyName,
typeof(T).FullName,
propertyValue.GetType().FullName);
}
}
try
{
Type underlyingType = Enum.GetUnderlyingType(typeof(T));
object underlyingValue = LanguagePrimitives.ConvertTo(propertyValue, underlyingType, CultureInfo.InvariantCulture);
T value = (T)underlyingValue;
return value;
}
catch (InvalidCastException)
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.CantCastPropertyToExpectedType,
propertyName,
typeof(T).FullName,
propertyValue.GetType().FullName);
}
}
else if (typeof(T).Equals(typeof(PSObject)))
{
if (propertyValue == null)
{
return default(T); // => "return null" for PSObject
}
else
{
return (T)(object)PSObject.AsPSObject(propertyValue);
}
}
else if (propertyValue == null)
{
if (!typeof(T).IsValueType)
{
return default(T);
}
if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
return default(T);
}
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.CantCastPropertyToExpectedType,
propertyName,
typeof(T).FullName,
propertyValue != null ? propertyValue.GetType().FullName : "null");
}
else if (propertyValue is T)
{
return (T)(propertyValue);
}
else if (propertyValue is PSObject)
{
PSObject psObject = (PSObject)propertyValue;
return ConvertPropertyValueTo<T>(propertyName, psObject.BaseObject);
}
else if ((propertyValue is Hashtable) && (typeof(T).Equals(typeof(PSPrimitiveDictionary))))
{
// rehydration of PSPrimitiveDictionary might not work when CreateRunspacePool message is received
// (there is no runspace and so no type table at this point) so try converting manually
try
{
return (T)(object)(new PSPrimitiveDictionary((Hashtable)propertyValue));
}
catch (ArgumentException)
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.CantCastPropertyToExpectedType,
propertyName,
typeof(T).FullName,
propertyValue != null ? propertyValue.GetType().FullName : "null");
}
}
else
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.CantCastPropertyToExpectedType,
propertyName,
typeof(T).FullName,
propertyValue.GetType().FullName);
}
}
private static PSPropertyInfo GetProperty(PSObject psObject, string propertyName)
{
if (psObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(psObject));
}
if (propertyName == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(propertyName));
}
PSPropertyInfo property = psObject.Properties[propertyName];
if (property == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.MissingProperty, propertyName);
}
return property;
}
internal static T GetPropertyValue<T>(PSObject psObject, string propertyName)
{
if (psObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(psObject));
}
if (propertyName == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(propertyName));
}
PSPropertyInfo property = GetProperty(psObject, propertyName);
object propertyValue = property.Value;
return ConvertPropertyValueTo<T>(propertyName, propertyValue);
}
internal static IEnumerable<T> EnumerateListProperty<T>(PSObject psObject, string propertyName)
{
if (psObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(psObject));
}
if (propertyName == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(propertyName));
}
IEnumerable e = GetPropertyValue<IEnumerable>(psObject, propertyName);
if (e != null)
{
foreach (object o in e)
{
yield return ConvertPropertyValueTo<T>(propertyName, o);
}
}
}
internal static IEnumerable<KeyValuePair<TKey, TValue>> EnumerateHashtableProperty<TKey, TValue>(PSObject psObject, string propertyName)
{
if (psObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(psObject));
}
if (propertyName == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(propertyName));
}
Hashtable h = GetPropertyValue<Hashtable>(psObject, propertyName);
if (h != null)
{
foreach (DictionaryEntry e in h)
{
TKey key = ConvertPropertyValueTo<TKey>(propertyName, e.Key);
TValue value = ConvertPropertyValueTo<TValue>(propertyName, e.Value);
yield return new KeyValuePair<TKey, TValue>(key, value);
}
}
}
/// <summary>
/// Decode and obtain the RunspacePool state info from the
/// data object specified.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>RunspacePoolStateInfo.</returns>
internal static RunspacePoolStateInfo GetRunspacePoolStateInfo(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
RunspacePoolState state = GetPropertyValue<RunspacePoolState>(dataAsPSObject, RemoteDataNameStrings.RunspaceState);
Exception reason = GetExceptionFromStateInfoObject(dataAsPSObject);
return new RunspacePoolStateInfo(state, reason);
}
/// <summary>
/// Decode and obtain the application private data from the
/// data object specified.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>Application private data.</returns>
internal static PSPrimitiveDictionary GetApplicationPrivateData(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
return GetPropertyValue<PSPrimitiveDictionary>(dataAsPSObject, RemoteDataNameStrings.ApplicationPrivateData);
}
/// <summary>
/// Gets the public key from the encoded message.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>Public key as string.</returns>
internal static string GetPublicKey(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
return GetPropertyValue<string>(dataAsPSObject, RemoteDataNameStrings.PublicKey);
}
/// <summary>
/// Gets the encrypted session key from the encoded message.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>Encrypted session key as string.</returns>
internal static string GetEncryptedSessionKey(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
return GetPropertyValue<string>(dataAsPSObject, RemoteDataNameStrings.EncryptedSessionKey);
}
/// <summary>
/// Decode and obtain the RunspacePool state info from the
/// data object specified.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>RunspacePoolStateInfo.</returns>
internal static PSEventArgs GetPSEventArgs(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
int eventIdentifier = GetPropertyValue<int>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsEventIdentifier);
string sourceIdentifier = GetPropertyValue<string>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsSourceIdentifier);
object sender = GetPropertyValue<object>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsSender);
object messageData = GetPropertyValue<object>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsMessageData);
string computerName = GetPropertyValue<string>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsComputerName);
Guid runspaceId = GetPropertyValue<Guid>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsRunspaceId);
var sourceArgs = new List<object>();
foreach (object argument in RemotingDecoder.EnumerateListProperty<object>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsSourceArgs))
{
sourceArgs.Add(argument);
}
PSEventArgs eventArgs = new PSEventArgs(
computerName,
runspaceId,
eventIdentifier,
sourceIdentifier,
sender,
sourceArgs.ToArray(),
messageData == null ? null : PSObject.AsPSObject(messageData));
eventArgs.TimeGenerated = GetPropertyValue<DateTime>(dataAsPSObject, RemoteDataNameStrings.PSEventArgsTimeGenerated);
return eventArgs;
}
/// <summary>
/// Decode and obtain the minimum runspaces to create in the
/// runspace pool from the data object specified.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>Minimum runspaces.</returns>
internal static int GetMinRunspaces(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
return GetPropertyValue<int>(dataAsPSObject, RemoteDataNameStrings.MinRunspaces);
}
/// <summary>
/// Decode and obtain the maximum runspaces to create in the
/// runspace pool from the data object specified.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>Maximum runspaces.</returns>
internal static int GetMaxRunspaces(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
return GetPropertyValue<int>(dataAsPSObject, RemoteDataNameStrings.MaxRunspaces);
}
/// <summary>
/// Decode and obtain the thread options for the runspaces in the
/// runspace pool from the data object specified.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>Thread options.</returns>
internal static PSPrimitiveDictionary GetApplicationArguments(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
// rehydration might not work yet (there is no type table before a runspace is created)
// so try to cast ApplicationArguments to PSPrimitiveDictionary manually
return GetPropertyValue<PSPrimitiveDictionary>(dataAsPSObject, RemoteDataNameStrings.ApplicationArguments);
}
/// <summary>
/// Generates RunspacePoolInitInfo object from a received PSObject.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>RunspacePoolInitInfo generated.</returns>
internal static RunspacePoolInitInfo GetRunspacePoolInitInfo(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
int maxRS = GetPropertyValue<int>(dataAsPSObject, RemoteDataNameStrings.MaxRunspaces);
int minRS = GetPropertyValue<int>(dataAsPSObject, RemoteDataNameStrings.MinRunspaces);
return new RunspacePoolInitInfo(minRS, maxRS);
}
/// <summary>
/// Decode and obtain the thread options for the runspaces in the
/// runspace pool from the data object specified.
/// </summary>
/// <param name="dataAsPSObject">Data object to decode.</param>
/// <returns>Thread options.</returns>
internal static PSThreadOptions GetThreadOptions(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
return GetPropertyValue<PSThreadOptions>(dataAsPSObject, RemoteDataNameStrings.ThreadOptions);
}
/// <summary>
/// Decode and obtain the host info for the host
/// associated with the runspace pool.
/// </summary>
/// <param name="dataAsPSObject">DataAsPSObject object to decode.</param>
/// <returns>Host information.</returns>
internal static HostInfo GetHostInfo(PSObject dataAsPSObject)
{
if (dataAsPSObject == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject));
}
PSObject propertyValue = GetPropertyValue<PSObject>(dataAsPSObject, RemoteDataNameStrings.HostInfo);
return RemoteHostEncoder.DecodeObject(propertyValue, typeof(HostInfo)) as HostInfo;
}
/// <summary>
/// Gets the exception if any from the serialized state info object.
/// </summary>
/// <param name="stateInfo"></param>
/// <returns></returns>
private static Exception GetExceptionFromStateInfoObject(PSObject stateInfo)
{
// Check if exception is encoded as errorrecord
PSPropertyInfo property = stateInfo.Properties[RemoteDataNameStrings.ExceptionAsErrorRecord];
if (property != null && property.Value != null)
{
return GetExceptionFromSerializedErrorRecord(property.Value);
}
// Exception is not present and return null.
return null;
}
/// <summary>
/// Get the exception from serialized error record.
/// </summary>
/// <param name="serializedErrorRecord"></param>
/// <returns></returns>
internal static Exception GetExceptionFromSerializedErrorRecord(object serializedErrorRecord)
{
ErrorRecord er = ErrorRecord.FromPSObjectForRemoting(PSObject.AsPSObject(serializedErrorRecord));
if (er == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.DecodingErrorForErrorRecord);
}
else
{
return er.Exception;
}
}
/// <summary>
/// Gets the output from the message.
/// </summary>
/// <param name="data">Object to decode.</param>
/// <returns>Output object.</returns>
/// <remarks>the current implementation does nothing,
/// however this method is there in place as the
/// packaging of output data may change in the future</remarks>
internal static object GetPowerShellOutput(object data)
{
return data;
}
/// <summary>
/// Gets the PSInvocationStateInfo from the data.
/// </summary>
/// <param name="data">Object to decode.</param>
/// <returns>PSInvocationInfo.</returns>
internal static PSInvocationStateInfo GetPowerShellStateInfo(object data)
{
if (data is not PSObject dataAsPSObject)
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.DecodingErrorForPowerShellStateInfo);
}
PSInvocationState state = GetPropertyValue<PSInvocationState>(dataAsPSObject, RemoteDataNameStrings.PipelineState);
Exception reason = GetExceptionFromStateInfoObject(dataAsPSObject);
return new PSInvocationStateInfo(state, reason);
}
/// <summary>
/// Gets the ErrorRecord from the message.
/// </summary>
/// <param name="data">Data to decode.</param>
/// <returns>Error record.</returns>
internal static ErrorRecord GetPowerShellError(object data)
{
if (data == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(data));
}
PSObject dataAsPSObject = data as PSObject;
ErrorRecord errorRecord = ErrorRecord.FromPSObjectForRemoting(dataAsPSObject);
return errorRecord;
}
/// <summary>
/// Gets the WarningRecord from the message.
/// </summary>
internal static WarningRecord GetPowerShellWarning(object data)
{
if (data == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(data));
}
return new WarningRecord((PSObject)data);
}
/// <summary>
/// Gets the VerboseRecord from the message.
/// </summary>
internal static VerboseRecord GetPowerShellVerbose(object data)
{
if (data == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(data));
}
return new VerboseRecord((PSObject)data);
}
/// <summary>
/// Gets the DebugRecord from the message.
/// </summary>
internal static DebugRecord GetPowerShellDebug(object data)
{
if (data == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(data));
}
return new DebugRecord((PSObject)data);
}
/// <summary>
/// Gets the ProgressRecord from the message.
/// </summary>
internal static ProgressRecord GetPowerShellProgress(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
if (dataAsPSObject == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
return ProgressRecord.FromPSObjectForRemoting(dataAsPSObject);
}
/// <summary>
/// Gets the InformationRecord from the message.
/// </summary>
internal static InformationRecord GetPowerShellInformation(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
if (dataAsPSObject == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
return InformationRecord.FromPSObjectForRemoting(dataAsPSObject);
}
/// <summary>
/// Gets the PowerShell object from the specified data.
/// </summary>
/// <param name="data">Data to decode.</param>
/// <returns>Deserialized PowerShell object.</returns>
internal static PowerShell GetPowerShell(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
if (dataAsPSObject == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
PSObject powerShellAsPSObject = GetPropertyValue<PSObject>(dataAsPSObject, RemoteDataNameStrings.PowerShell);
return PowerShell.FromPSObjectForRemoting(powerShellAsPSObject);
}
/// <summary>
/// Gets the PowerShell object from the specified data.
/// </summary>
/// <param name="data">Data to decode.</param>
/// <returns>Deserialized PowerShell object.</returns>
internal static PowerShell GetCommandDiscoveryPipeline(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
if (dataAsPSObject == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
CommandTypes commandType = GetPropertyValue<CommandTypes>(dataAsPSObject, RemoteDataNameStrings.DiscoveryType);
string[] name;
if (GetPropertyValue<PSObject>(dataAsPSObject, RemoteDataNameStrings.DiscoveryName) != null)
{
IEnumerable<string> tmp = EnumerateListProperty<string>(dataAsPSObject, RemoteDataNameStrings.DiscoveryName);
name = new List<string>(tmp).ToArray();
}
else
{
name = new string[] { "*" };
}
string[] module;
if (GetPropertyValue<PSObject>(dataAsPSObject, RemoteDataNameStrings.DiscoveryModule) != null)
{
IEnumerable<string> tmp = EnumerateListProperty<string>(dataAsPSObject, RemoteDataNameStrings.DiscoveryModule);
module = new List<string>(tmp).ToArray();
}
else
{
module = new string[] { string.Empty };
}
ModuleSpecification[] fullyQualifiedName = null;
if (DeserializingTypeConverter.GetPropertyValue<PSObject>(dataAsPSObject,
RemoteDataNameStrings.DiscoveryFullyQualifiedModule,
DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk) != null)
{
IEnumerable<ModuleSpecification> tmp = EnumerateListProperty<ModuleSpecification>(dataAsPSObject, RemoteDataNameStrings.DiscoveryFullyQualifiedModule);
fullyQualifiedName = new List<ModuleSpecification>(tmp).ToArray();
}
object[] argumentList;
if (GetPropertyValue<PSObject>(dataAsPSObject, RemoteDataNameStrings.DiscoveryArgumentList) != null)
{
IEnumerable<object> tmp = EnumerateListProperty<object>(dataAsPSObject, RemoteDataNameStrings.DiscoveryArgumentList);
argumentList = new List<object>(tmp).ToArray();
}
else
{
argumentList = null;
}
PowerShell powerShell = PowerShell.Create();
powerShell.AddCommand("Get-Command");
powerShell.AddParameter("Name", name);
powerShell.AddParameter("CommandType", commandType);
if (fullyQualifiedName != null)
{
powerShell.AddParameter("FullyQualifiedModule", fullyQualifiedName);
}
else
{
powerShell.AddParameter("Module", module);
}
powerShell.AddParameter("ArgumentList", argumentList);
return powerShell;
}
/// <summary>
/// Gets the NoInput setting from the specified data.
/// </summary>
/// <param name="data">Data to decode.</param>
/// <returns><see langword="true"/> if there is no pipeline input; <see langword="false"/> otherwise.</returns>
internal static bool GetNoInput(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
if (dataAsPSObject == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
return GetPropertyValue<bool>(dataAsPSObject, RemoteDataNameStrings.NoInput);
}
/// <summary>
/// Gets the AddToHistory setting from the specified data.
/// </summary>
/// <param name="data">Data to decode.</param>
/// <returns><see langword="true"/> if there is addToHistory data; <see langword="false"/> otherwise.</returns>
internal static bool GetAddToHistory(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
if (dataAsPSObject == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
return GetPropertyValue<bool>(dataAsPSObject, RemoteDataNameStrings.AddToHistory);
}
/// <summary>
/// Gets the IsNested setting from the specified data.
/// </summary>
/// <param name="data">Data to decode.</param>
/// <returns><see langword="true"/> if there is IsNested data; <see langword="false"/> otherwise.</returns>
internal static bool GetIsNested(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
if (dataAsPSObject == null)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
return GetPropertyValue<bool>(dataAsPSObject, RemoteDataNameStrings.IsNested);
}
/// <summary>
/// Gets the invocation settings information from the message.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
internal static ApartmentState GetApartmentState(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
return GetPropertyValue<ApartmentState>(dataAsPSObject, RemoteDataNameStrings.ApartmentState);
}
/// <summary>
/// Gets the stream options from the message.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
internal static RemoteStreamOptions GetRemoteStreamOptions(object data)
{
PSObject dataAsPSObject = PSObject.AsPSObject(data);
return GetPropertyValue<RemoteStreamOptions>(dataAsPSObject, RemoteDataNameStrings.RemoteStreamOptions);
}
/// <summary>
/// Decodes a RemoteSessionCapability object.
/// </summary>
/// <param name="data">Data to decode.</param>
/// <returns>RemoteSessionCapability object.</returns>
internal static RemoteSessionCapability GetSessionCapability(object data)
{
if (data is not PSObject dataAsPSObject)
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
}
Version protocolVersion = GetPropertyValue<Version>(dataAsPSObject, RemoteDataNameStrings.PS_STARTUP_PROTOCOL_VERSION_NAME);
Version psVersion = GetPropertyValue<Version>(dataAsPSObject, RemoteDataNameStrings.PSVersion);
Version serializationVersion = GetPropertyValue<Version>(dataAsPSObject,
RemoteDataNameStrings.SerializationVersion);
RemoteSessionCapability result = new RemoteSessionCapability(
RemotingDestination.InvalidDestination,
protocolVersion, psVersion, serializationVersion);
return result;
}
/// <summary>
/// Checks if the server supports batch invocation.
/// </summary>
/// <param name="runspace">Runspace instance.</param>
/// <returns>True if batch invocation is supported, false if not.</returns>
internal static bool ServerSupportsBatchInvocation(Runspace runspace)
{
if (runspace == null || runspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen)
{
return false;
}
return (runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersion_2_2);
}
}
}
|