Rest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. *
  27. */
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Text;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Servers;
  34. using OpenSim.Framework.Communications;
  35. using OpenSim.Framework.Communications.Cache;
  36. using Nini.Config;
  37. namespace OpenSim.ApplicationPlugins.Rest.Inventory
  38. {
  39. public class Rest
  40. {
  41. internal static readonly log4net.ILog Log =
  42. log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. internal static bool DEBUG = Log.IsDebugEnabled;
  44. /// <summary>
  45. /// These values have a single value for the whole
  46. /// domain and lifetime of the plugin handler. We
  47. /// make them static for ease of reference within
  48. /// the assembly. These are initialized by the
  49. /// RestHandler class during start-up.
  50. /// </summary>
  51. internal static RestHandler Plugin = null;
  52. internal static OpenSimBase main = null;
  53. internal static CommunicationsManager Comms = null;
  54. internal static IInventoryServices InventoryServices = null;
  55. internal static IUserService UserServices = null;
  56. internal static AssetCache AssetServices = null;
  57. internal static string Prefix = null;
  58. internal static IConfig Config = null;
  59. internal static string GodKey = null;
  60. internal static bool Authenticate = true;
  61. internal static bool Secure = true;
  62. internal static bool ExtendedEscape = true;
  63. internal static bool DumpAsset = false;
  64. internal static string Realm = "REST";
  65. internal static Dictionary<string,string> Domains = new Dictionary<string,string>();
  66. internal static int CreationDate = (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
  67. internal static int DumpLineSize = 32; // Should be a multiple of 16 or (possibly) 4
  68. internal static string MsgId
  69. {
  70. get { return Plugin.MsgId; }
  71. }
  72. internal static string RequestId
  73. {
  74. get { return Plugin.RequestId; }
  75. }
  76. internal static Encoding Encoding = Encoding.UTF8;
  77. /// <summary>
  78. /// Version control for REST implementation. This
  79. /// refers to the overall infrastructure represented
  80. /// by the following classes
  81. /// RequestData
  82. /// RequestInventoryPlugin
  83. /// Rest
  84. /// It does no describe implementation classes such as
  85. /// RestInventoryServices, which may morph much more
  86. /// often. Such classes ARE dependent upon this however
  87. /// and should check it in their Initialize method.
  88. /// </summary>
  89. public static readonly float Version = 1.0F;
  90. public const string Name = "REST 1.0";
  91. /// <summary>
  92. /// Currently defined HTTP methods.
  93. /// Only GET and HEAD are required to be
  94. /// supported by all servers. See Respond
  95. /// to see how these are handled.
  96. /// </summary>
  97. // REST AGENT 1.0 interpretations
  98. public const string GET = "get"; // information retrieval - server state unchanged
  99. public const string HEAD = "head"; // same as get except only the headers are returned.
  100. public const string POST = "post"; // Replace the URI designated resource with the entity.
  101. public const string PUT = "put"; // Add the entity to the context represented by the URI
  102. public const string DELETE = "delete"; // Remove the URI designated resource from the server.
  103. public const string OPTIONS = "options"; //
  104. public const string TRACE = "trace"; //
  105. public const string CONNECT = "connect"; //
  106. // Define this in one place...
  107. public const string UrlPathSeparator = "/";
  108. public const string UrlMethodSeparator = ":";
  109. // Redirection qualifications
  110. public const bool PERMANENT = false;
  111. public const bool TEMPORARY = true;
  112. // Constant arrays used by String.Split
  113. public static readonly char C_SPACE = ' ';
  114. public static readonly char C_SLASH = '/';
  115. public static readonly char C_PATHSEP = '/';
  116. public static readonly char C_COLON = ':';
  117. public static readonly char C_PLUS = '+';
  118. public static readonly char C_PERIOD = '.';
  119. public static readonly char C_COMMA = ',';
  120. public static readonly char C_DQUOTE = '"';
  121. public static readonly string CS_SPACE = " ";
  122. public static readonly string CS_SLASH = "/";
  123. public static readonly string CS_PATHSEP = "/";
  124. public static readonly string CS_COLON = ":";
  125. public static readonly string CS_PLUS = "+";
  126. public static readonly string CS_PERIOD = ".";
  127. public static readonly string CS_COMMA = ",";
  128. public static readonly string CS_DQUOTE = "\"";
  129. public static readonly char[] CA_SPACE = { C_SPACE };
  130. public static readonly char[] CA_SLASH = { C_SLASH };
  131. public static readonly char[] CA_PATHSEP = { C_PATHSEP };
  132. public static readonly char[] CA_COLON = { C_COLON };
  133. public static readonly char[] CA_PERIOD = { C_PERIOD };
  134. public static readonly char[] CA_PLUS = { C_PLUS };
  135. public static readonly char[] CA_COMMA = { C_COMMA };
  136. public static readonly char[] CA_DQUOTE = { C_DQUOTE };
  137. // HTTP Code Values (in value order)
  138. public const int HttpStatusCodeContinue = 100;
  139. public const int HttpStatusCodeSwitchingProtocols = 101;
  140. public const int HttpStatusCodeOK = 200;
  141. public const int HttpStatusCodeCreated = 201;
  142. public const int HttpStatusCodeAccepted = 202;
  143. public const int HttpStatusCodeNonAuthoritative = 203;
  144. public const int HttpStatusCodeNoContent = 204;
  145. public const int HttpStatusCodeResetContent = 205;
  146. public const int HttpStatusCodePartialContent = 206;
  147. public const int HttpStatusCodeMultipleChoices = 300;
  148. public const int HttpStatusCodePermanentRedirect = 301;
  149. public const int HttpStatusCodeFound = 302;
  150. public const int HttpStatusCodeSeeOther = 303;
  151. public const int HttpStatusCodeNotModified = 304;
  152. public const int HttpStatusCodeUseProxy = 305;
  153. public const int HttpStatusCodeReserved306 = 306;
  154. public const int HttpStatusCodeTemporaryRedirect = 307;
  155. public const int HttpStatusCodeBadRequest = 400;
  156. public const int HttpStatusCodeNotAuthorized = 401;
  157. public const int HttpStatusCodePaymentRequired = 402;
  158. public const int HttpStatusCodeForbidden = 403;
  159. public const int HttpStatusCodeNotFound = 404;
  160. public const int HttpStatusCodeMethodNotAllowed = 405;
  161. public const int HttpStatusCodeNotAcceptable = 406;
  162. public const int HttpStatusCodeProxyAuthenticate = 407;
  163. public const int HttpStatusCodeTimeOut = 408;
  164. public const int HttpStatusCodeConflict = 409;
  165. public const int HttpStatusCodeGone = 410;
  166. public const int HttpStatusCodeLengthRequired = 411;
  167. public const int HttpStatusCodePreconditionFailed = 412;
  168. public const int HttpStatusCodeEntityTooLarge = 413;
  169. public const int HttpStatusCodeUriTooLarge = 414;
  170. public const int HttpStatusCodeUnsupportedMedia = 415;
  171. public const int HttpStatusCodeRangeNotSatsified = 416;
  172. public const int HttpStatusCodeExpectationFailed = 417;
  173. public const int HttpStatusCodeServerError = 500;
  174. public const int HttpStatusCodeNotImplemented = 501;
  175. public const int HttpStatusCodeBadGateway = 502;
  176. public const int HttpStatusCodeServiceUnavailable = 503;
  177. public const int HttpStatusCodeGatewayTimeout = 504;
  178. public const int HttpStatusCodeHttpVersionError = 505;
  179. // HTTP Status Descriptions (in status code order)
  180. public const string HttpStatusDescContinue = "Continue Request"; // 100
  181. public const string HttpStatusDescSwitchingProtocols = "Switching Protocols"; // 101
  182. public const string HttpStatusDescOK = "OK";
  183. public const string HttpStatusDescCreated = "CREATED";
  184. public const string HttpStatusDescAccepted = "ACCEPTED";
  185. public const string HttpStatusDescNonAuthoritative = "NON-AUTHORITATIVE INFORMATION";
  186. public const string HttpStatusDescNoContent = "NO CONTENT";
  187. public const string HttpStatusDescResetContent = "RESET CONTENT";
  188. public const string HttpStatusDescPartialContent = "PARTIAL CONTENT";
  189. public const string HttpStatusDescMultipleChoices = "MULTIPLE CHOICES";
  190. public const string HttpStatusDescPermanentRedirect = "PERMANENT REDIRECT";
  191. public const string HttpStatusDescFound = "FOUND";
  192. public const string HttpStatusDescSeeOther = "SEE OTHER";
  193. public const string HttpStatusDescNotModified = "NOT MODIFIED";
  194. public const string HttpStatusDescUseProxy = "USE PROXY";
  195. public const string HttpStatusDescReserved306 = "RESERVED CODE 306";
  196. public const string HttpStatusDescTemporaryRedirect = "TEMPORARY REDIRECT";
  197. public const string HttpStatusDescBadRequest = "BAD REQUEST";
  198. public const string HttpStatusDescNotAuthorized = "NOT AUTHORIZED";
  199. public const string HttpStatusDescPaymentRequired = "PAYMENT REQUIRED";
  200. public const string HttpStatusDescForbidden = "FORBIDDEN";
  201. public const string HttpStatusDescNotFound = "NOT FOUND";
  202. public const string HttpStatusDescMethodNotAllowed = "METHOD NOT ALLOWED";
  203. public const string HttpStatusDescNotAcceptable = "NOT ACCEPTABLE";
  204. public const string HttpStatusDescProxyAuthenticate = "PROXY AUTHENTICATION REQUIRED";
  205. public const string HttpStatusDescTimeOut = "TIMEOUT";
  206. public const string HttpStatusDescConflict = "CONFLICT";
  207. public const string HttpStatusDescGone = "GONE";
  208. public const string HttpStatusDescLengthRequired = "LENGTH REQUIRED";
  209. public const string HttpStatusDescPreconditionFailed = "PRECONDITION FAILED";
  210. public const string HttpStatusDescEntityTooLarge = "ENTITY TOO LARGE";
  211. public const string HttpStatusDescUriTooLarge = "URI TOO LARGE";
  212. public const string HttpStatusDescUnsupportedMedia = "UNSUPPORTED MEDIA";
  213. public const string HttpStatusDescRangeNotSatisfied = "RANGE NOT SATISFIED";
  214. public const string HttpStatusDescExpectationFailed = "EXPECTATION FAILED";
  215. public const string HttpStatusDescServerError = "SERVER ERROR";
  216. public const string HttpStatusDescNotImplemented = "NOT IMPLEMENTED";
  217. public const string HttpStatusDescBadGateway = "BAD GATEWAY";
  218. public const string HttpStatusDescServiceUnavailable = "SERVICE UNAVAILABLE";
  219. public const string HttpStatusDescGatewayTimeout = "GATEWAY TIMEOUT";
  220. public const string HttpStatusDescHttpVersionError = "HTTP VERSION NOT SUPPORTED";
  221. // HTTP Headers
  222. public const string HttpHeaderAccept = "Accept";
  223. public const string HttpHeaderAcceptCharset = "Accept-Charset";
  224. public const string HttpHeaderAcceptEncoding = "Accept-Encoding";
  225. public const string HttpHeaderAcceptLanguage = "Accept-Language";
  226. public const string HttpHeaderAcceptRanges = "Accept-Ranges";
  227. public const string HttpHeaderAge = "Age";
  228. public const string HttpHeaderAllow = "Allow";
  229. public const string HttpHeaderAuthorization = "Authorization";
  230. public const string HttpHeaderCacheControl = "Cache-Control";
  231. public const string HttpHeaderConnection = "Connection";
  232. public const string HttpHeaderContentEncoding = "Content-Encoding";
  233. public const string HttpHeaderContentLanguage = "Content-Language";
  234. public const string HttpHeaderContentLength = "Content-Length";
  235. public const string HttpHeaderContentLocation = "Content-Location";
  236. public const string HttpHeaderContentMD5 = "Content-MD5";
  237. public const string HttpHeaderContentRange = "Content-Range";
  238. public const string HttpHeaderContentType = "Content-Type";
  239. public const string HttpHeaderDate = "Date";
  240. public const string HttpHeaderETag = "ETag";
  241. public const string HttpHeaderExpect = "Expect";
  242. public const string HttpHeaderExpires = "Expires";
  243. public const string HttpHeaderFrom = "From";
  244. public const string HttpHeaderHost = "Host";
  245. public const string HttpHeaderIfMatch = "If-Match";
  246. public const string HttpHeaderIfModifiedSince = "If-Modified-Since";
  247. public const string HttpHeaderIfNoneMatch = "If-None-Match";
  248. public const string HttpHeaderIfRange = "If-Range";
  249. public const string HttpHeaderIfUnmodifiedSince = "If-Unmodified-Since";
  250. public const string HttpHeaderLastModified = "Last-Modified";
  251. public const string HttpHeaderLocation = "Location";
  252. public const string HttpHeaderMaxForwards = "Max-Forwards";
  253. public const string HttpHeaderPragma = "Pragma";
  254. public const string HttpHeaderProxyAuthenticate = "Proxy-Authenticate";
  255. public const string HttpHeaderProxyAuthorization = "Proxy-Authorization";
  256. public const string HttpHeaderRange = "Range";
  257. public const string HttpHeaderReferer = "Referer";
  258. public const string HttpHeaderRetryAfter = "Retry-After";
  259. public const string HttpHeaderServer = "Server";
  260. public const string HttpHeaderTE = "TE";
  261. public const string HttpHeaderTrailer = "Trailer";
  262. public const string HttpHeaderTransferEncoding = "Transfer-Encoding";
  263. public const string HttpHeaderUpgrade = "Upgrade";
  264. public const string HttpHeaderUserAgent = "User-Agent";
  265. public const string HttpHeaderVary = "Vary";
  266. public const string HttpHeaderVia = "Via";
  267. public const string HttpHeaderWarning = "Warning";
  268. public const string HttpHeaderWWWAuthenticate = "WWW-Authenticate";
  269. /// <summary>
  270. /// Supported authentication schemes
  271. /// </summary>
  272. public const string AS_BASIC = "Basic";
  273. public const string AS_DIGEST = "Digest";
  274. /// Supported Digest algorithms
  275. public const string Digest_MD5 = "MD5"; // assumedd efault if omitted
  276. public const string Digest_MD5Sess = "MD5-sess";
  277. public const string Qop_Auth = "auth";
  278. public const string Qop_Int = "auth-int";
  279. /// Utility routines
  280. public static string StringToBase64(string str)
  281. {
  282. try
  283. {
  284. byte[] encData_byte = new byte[str.Length];
  285. encData_byte = Encoding.UTF8.GetBytes(str);
  286. return Convert.ToBase64String(encData_byte);
  287. }
  288. catch
  289. {
  290. return String.Empty;
  291. }
  292. }
  293. public static string Base64ToString(string str)
  294. {
  295. UTF8Encoding encoder = new UTF8Encoding();
  296. Decoder utf8Decode = encoder.GetDecoder();
  297. try
  298. {
  299. byte[] todecode_byte = Convert.FromBase64String(str);
  300. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  301. char[] decoded_char = new char[charCount];
  302. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  303. return new String(decoded_char);
  304. }
  305. catch
  306. {
  307. return String.Empty;
  308. }
  309. }
  310. private const string hvals = "0123456789abcdef";
  311. public static int Hex2Int(string hex)
  312. {
  313. int val = 0;
  314. int sum = 0;
  315. string tmp = null;
  316. if (hex != null)
  317. {
  318. tmp = hex.ToLower();
  319. for (int i = 0; i < tmp.Length; i++)
  320. {
  321. val = hvals.IndexOf(tmp[i]);
  322. if (val == -1)
  323. break;
  324. sum *= 16;
  325. sum += val;
  326. }
  327. }
  328. return sum;
  329. }
  330. public static string Int2Hex8(int val)
  331. {
  332. string res = String.Empty;
  333. for (int i = 0; i < 8; i++)
  334. {
  335. res = (val % 16) + res;
  336. val = val / 16;
  337. }
  338. return res;
  339. }
  340. public static string ToHex32(int val)
  341. {
  342. return String.Empty;
  343. }
  344. public static string ToHex32(string val)
  345. {
  346. return String.Empty;
  347. }
  348. // Nonce management
  349. public static string NonceGenerator()
  350. {
  351. return StringToBase64(Guid.NewGuid().ToString());
  352. }
  353. // Dump he specified data stream;
  354. public static void Dump(byte[] data)
  355. {
  356. char[] buffer = new char[Rest.DumpLineSize];
  357. int cc = 0;
  358. for (int i = 0; i < data.Length; i++)
  359. {
  360. if (i % Rest.DumpLineSize == 0) Console.Write("\n{0}: ",i.ToString("d8"));
  361. if (i % 4 == 0) Console.Write(" ");
  362. // if (i%16 == 0) Console.Write(" ");
  363. Console.Write("{0}",data[i].ToString("x2"));
  364. if (data[i] < 127 && data[i] > 31)
  365. buffer[i % Rest.DumpLineSize] = (char) data[i];
  366. else
  367. buffer[i % Rest.DumpLineSize] = '.';
  368. cc++;
  369. if (i != 0 && (i + 1) % Rest.DumpLineSize == 0)
  370. {
  371. Console.Write(" |"+(new String(buffer))+"|");
  372. cc = 0;
  373. }
  374. }
  375. // Finish off any incomplete line
  376. if (cc != 0)
  377. {
  378. for (int i = cc ; i < Rest.DumpLineSize; i++)
  379. {
  380. if (i % 4 == 0) Console.Write(" ");
  381. // if (i%16 == 0) Console.Write(" ");
  382. Console.Write(" ");
  383. buffer[i % Rest.DumpLineSize] = ' ';
  384. }
  385. Console.WriteLine(" |"+(new String(buffer))+"|");
  386. }
  387. else
  388. {
  389. Console.Write("\n");
  390. }
  391. }
  392. }
  393. // Local exception type
  394. public class RestException : Exception
  395. {
  396. internal int statusCode;
  397. internal string statusDesc;
  398. internal string httpmethod;
  399. internal string httppath;
  400. public RestException(string msg) : base(msg)
  401. {
  402. }
  403. }
  404. }