Rest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. /// Supported authentication schemes
  46. /// </summary>
  47. public const string AS_BASIC = "Basic"; // simple user/password verification
  48. public const string AS_DIGEST = "Digest"; // password safe authentication
  49. /// Supported Digest algorithms
  50. public const string Digest_MD5 = "MD5"; // assumed default if omitted
  51. public const string Digest_MD5Sess = "MD5-sess"; // session-span - not good for REST?
  52. public const string Qop_Auth = "auth"; // authentication only
  53. public const string Qop_Int = "auth-int"; // TODO
  54. /// <summary>
  55. /// These values have a single value for the whole
  56. /// domain and lifetime of the plugin handler. We
  57. /// make them static for ease of reference within
  58. /// the assembly. These are initialized by the
  59. /// RestHandler class during start-up.
  60. /// </summary>
  61. internal static IRestHandler Plugin = null;
  62. internal static OpenSimBase main = null;
  63. internal static CommunicationsManager Comms = null;
  64. internal static IInventoryServices InventoryServices = null;
  65. internal static IUserService UserServices = null;
  66. internal static IAvatarService AvatarServices = null;
  67. internal static AssetCache AssetServices = null;
  68. internal static string Prefix = null;
  69. internal static IConfig Config = null;
  70. internal static string GodKey = null;
  71. internal static bool Authenticate = true;
  72. internal static bool Secure = true;
  73. internal static bool ExtendedEscape = true;
  74. internal static bool DumpAsset = false;
  75. internal static bool Fill = false;
  76. internal static bool FlushEnabled = true;
  77. internal static string Realm = "OpenSim REST";
  78. internal static string Scheme = AS_BASIC;
  79. internal static int DumpLineSize = 32; // Should be a multiple of 16 or (possibly) 4
  80. /// <summary>
  81. /// HTTP requires that status information be generated for PUT
  82. /// and POST opertaions. This is in support of that. The
  83. /// operation verb gets substituted into the first string,
  84. /// and the completion code is inserted into the tail. The
  85. /// strings are put here to encourage consistency.
  86. /// </summary>
  87. internal static string statusHead = "<html><body><title>{0} status</title><break>";
  88. internal static string statusTail = "</body></html>";
  89. internal static Dictionary<int,string> HttpStatusDesc;
  90. static Rest()
  91. {
  92. HttpStatusDesc = new Dictionary<int,string>();
  93. if (HttpStatusCodeArray.Length != HttpStatusDescArray.Length)
  94. {
  95. Log.ErrorFormat("{0} HTTP Status Code and Description arrays do not match");
  96. throw new Exception("HTTP Status array discrepancy");
  97. }
  98. // Repackage the data into something more tractable. The sparse
  99. // nature of HTTP return codes makes an array a bad choice.
  100. for (int i=0; i<HttpStatusCodeArray.Length; i++)
  101. {
  102. HttpStatusDesc.Add(HttpStatusCodeArray[i], HttpStatusDescArray[i]);
  103. }
  104. }
  105. internal static int CreationDate
  106. {
  107. get { return (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; }
  108. }
  109. internal static string MsgId
  110. {
  111. get { return Plugin.MsgId; }
  112. }
  113. internal static string RequestId
  114. {
  115. get { return Plugin.RequestId; }
  116. }
  117. internal static Encoding Encoding = Encoding.UTF8;
  118. /// <summary>
  119. /// Version control for REST implementation. This
  120. /// refers to the overall infrastructure represented
  121. /// by the following classes
  122. /// RequestData
  123. /// RequestInventoryPlugin
  124. /// Rest
  125. /// It does no describe implementation classes such as
  126. /// RestInventoryServices, which may morph much more
  127. /// often. Such classes ARE dependent upon this however
  128. /// and should check it in their Initialize method.
  129. /// </summary>
  130. public static readonly float Version = 1.0F;
  131. public const string Name = "REST 1.0";
  132. /// <summary>
  133. /// Currently defined HTTP methods.
  134. /// Only GET and HEAD are required to be
  135. /// supported by all servers. See Respond
  136. /// to see how these are handled.
  137. /// </summary>
  138. // REST AGENT 1.0 interpretations
  139. public const string GET = "get"; // information retrieval - server state unchanged
  140. public const string HEAD = "head"; // same as get except only the headers are returned.
  141. public const string POST = "post"; // Replace the URI designated resource with the entity.
  142. public const string PUT = "put"; // Add the entity to the context represented by the URI
  143. public const string DELETE = "delete"; // Remove the URI designated resource from the server.
  144. public const string OPTIONS = "options"; //
  145. public const string TRACE = "trace"; //
  146. public const string CONNECT = "connect"; //
  147. // Define this in one place...
  148. public const string UrlPathSeparator = "/";
  149. public const string UrlMethodSeparator = ":";
  150. // Redirection qualifications
  151. public const bool PERMANENT = false;
  152. public const bool TEMPORARY = true;
  153. // Constant arrays used by String.Split
  154. public static readonly char C_SPACE = ' ';
  155. public static readonly char C_SLASH = '/';
  156. public static readonly char C_PATHSEP = '/';
  157. public static readonly char C_COLON = ':';
  158. public static readonly char C_PLUS = '+';
  159. public static readonly char C_PERIOD = '.';
  160. public static readonly char C_COMMA = ',';
  161. public static readonly char C_DQUOTE = '"';
  162. public static readonly string CS_SPACE = " ";
  163. public static readonly string CS_SLASH = "/";
  164. public static readonly string CS_PATHSEP = "/";
  165. public static readonly string CS_COLON = ":";
  166. public static readonly string CS_PLUS = "+";
  167. public static readonly string CS_PERIOD = ".";
  168. public static readonly string CS_COMMA = ",";
  169. public static readonly string CS_DQUOTE = "\"";
  170. public static readonly char[] CA_SPACE = { C_SPACE };
  171. public static readonly char[] CA_SLASH = { C_SLASH };
  172. public static readonly char[] CA_PATHSEP = { C_PATHSEP };
  173. public static readonly char[] CA_COLON = { C_COLON };
  174. public static readonly char[] CA_PERIOD = { C_PERIOD };
  175. public static readonly char[] CA_PLUS = { C_PLUS };
  176. public static readonly char[] CA_COMMA = { C_COMMA };
  177. public static readonly char[] CA_DQUOTE = { C_DQUOTE };
  178. // HTTP Code Values (in value order)
  179. public const int HttpStatusCodeContinue = 100;
  180. public const int HttpStatusCodeSwitchingProtocols = 101;
  181. public const int HttpStatusCodeOK = 200;
  182. public const int HttpStatusCodeCreated = 201;
  183. public const int HttpStatusCodeAccepted = 202;
  184. public const int HttpStatusCodeNonAuthoritative = 203;
  185. public const int HttpStatusCodeNoContent = 204;
  186. public const int HttpStatusCodeResetContent = 205;
  187. public const int HttpStatusCodePartialContent = 206;
  188. public const int HttpStatusCodeMultipleChoices = 300;
  189. public const int HttpStatusCodePermanentRedirect = 301;
  190. public const int HttpStatusCodeFound = 302;
  191. public const int HttpStatusCodeSeeOther = 303;
  192. public const int HttpStatusCodeNotModified = 304;
  193. public const int HttpStatusCodeUseProxy = 305;
  194. public const int HttpStatusCodeReserved306 = 306;
  195. public const int HttpStatusCodeTemporaryRedirect = 307;
  196. public const int HttpStatusCodeBadRequest = 400;
  197. public const int HttpStatusCodeNotAuthorized = 401;
  198. public const int HttpStatusCodePaymentRequired = 402;
  199. public const int HttpStatusCodeForbidden = 403;
  200. public const int HttpStatusCodeNotFound = 404;
  201. public const int HttpStatusCodeMethodNotAllowed = 405;
  202. public const int HttpStatusCodeNotAcceptable = 406;
  203. public const int HttpStatusCodeProxyAuthenticate = 407;
  204. public const int HttpStatusCodeTimeOut = 408;
  205. public const int HttpStatusCodeConflict = 409;
  206. public const int HttpStatusCodeGone = 410;
  207. public const int HttpStatusCodeLengthRequired = 411;
  208. public const int HttpStatusCodePreconditionFailed = 412;
  209. public const int HttpStatusCodeEntityTooLarge = 413;
  210. public const int HttpStatusCodeUriTooLarge = 414;
  211. public const int HttpStatusCodeUnsupportedMedia = 415;
  212. public const int HttpStatusCodeRangeNotSatsified = 416;
  213. public const int HttpStatusCodeExpectationFailed = 417;
  214. public const int HttpStatusCodeServerError = 500;
  215. public const int HttpStatusCodeNotImplemented = 501;
  216. public const int HttpStatusCodeBadGateway = 502;
  217. public const int HttpStatusCodeServiceUnavailable = 503;
  218. public const int HttpStatusCodeGatewayTimeout = 504;
  219. public const int HttpStatusCodeHttpVersionError = 505;
  220. public static readonly int[] HttpStatusCodeArray = {
  221. HttpStatusCodeContinue,
  222. HttpStatusCodeSwitchingProtocols,
  223. HttpStatusCodeOK,
  224. HttpStatusCodeCreated,
  225. HttpStatusCodeAccepted,
  226. HttpStatusCodeNonAuthoritative,
  227. HttpStatusCodeNoContent,
  228. HttpStatusCodeResetContent,
  229. HttpStatusCodePartialContent,
  230. HttpStatusCodeMultipleChoices,
  231. HttpStatusCodePermanentRedirect,
  232. HttpStatusCodeFound,
  233. HttpStatusCodeSeeOther,
  234. HttpStatusCodeNotModified,
  235. HttpStatusCodeUseProxy,
  236. HttpStatusCodeReserved306,
  237. HttpStatusCodeTemporaryRedirect,
  238. HttpStatusCodeBadRequest,
  239. HttpStatusCodeNotAuthorized,
  240. HttpStatusCodePaymentRequired,
  241. HttpStatusCodeForbidden,
  242. HttpStatusCodeNotFound,
  243. HttpStatusCodeMethodNotAllowed,
  244. HttpStatusCodeNotAcceptable,
  245. HttpStatusCodeProxyAuthenticate,
  246. HttpStatusCodeTimeOut,
  247. HttpStatusCodeConflict,
  248. HttpStatusCodeGone,
  249. HttpStatusCodeLengthRequired,
  250. HttpStatusCodePreconditionFailed,
  251. HttpStatusCodeEntityTooLarge,
  252. HttpStatusCodeUriTooLarge,
  253. HttpStatusCodeUnsupportedMedia,
  254. HttpStatusCodeRangeNotSatsified,
  255. HttpStatusCodeExpectationFailed,
  256. HttpStatusCodeServerError,
  257. HttpStatusCodeNotImplemented,
  258. HttpStatusCodeBadGateway,
  259. HttpStatusCodeServiceUnavailable,
  260. HttpStatusCodeGatewayTimeout,
  261. HttpStatusCodeHttpVersionError
  262. };
  263. // HTTP Status Descriptions (in status code order)
  264. // This array must be kept strictly consistent with respect
  265. // to the status code array above.
  266. public static readonly string[] HttpStatusDescArray = {
  267. "Continue Request",
  268. "Switching Protocols",
  269. "OK",
  270. "CREATED",
  271. "ACCEPTED",
  272. "NON-AUTHORITATIVE INFORMATION",
  273. "NO CONTENT",
  274. "RESET CONTENT",
  275. "PARTIAL CONTENT",
  276. "MULTIPLE CHOICES",
  277. "PERMANENT REDIRECT",
  278. "FOUND",
  279. "SEE OTHER",
  280. "NOT MODIFIED",
  281. "USE PROXY",
  282. "RESERVED CODE 306",
  283. "TEMPORARY REDIRECT",
  284. "BAD REQUEST",
  285. "NOT AUTHORIZED",
  286. "PAYMENT REQUIRED",
  287. "FORBIDDEN",
  288. "NOT FOUND",
  289. "METHOD NOT ALLOWED",
  290. "NOT ACCEPTABLE",
  291. "PROXY AUTHENTICATION REQUIRED",
  292. "TIMEOUT",
  293. "CONFLICT",
  294. "GONE",
  295. "LENGTH REQUIRED",
  296. "PRECONDITION FAILED",
  297. "ENTITY TOO LARGE",
  298. "URI TOO LARGE",
  299. "UNSUPPORTED MEDIA",
  300. "RANGE NOT SATISFIED",
  301. "EXPECTATION FAILED",
  302. "SERVER ERROR",
  303. "NOT IMPLEMENTED",
  304. "BAD GATEWAY",
  305. "SERVICE UNAVAILABLE",
  306. "GATEWAY TIMEOUT",
  307. "HTTP VERSION NOT SUPPORTED"
  308. };
  309. // HTTP Headers
  310. public const string HttpHeaderAccept = "Accept";
  311. public const string HttpHeaderAcceptCharset = "Accept-Charset";
  312. public const string HttpHeaderAcceptEncoding = "Accept-Encoding";
  313. public const string HttpHeaderAcceptLanguage = "Accept-Language";
  314. public const string HttpHeaderAcceptRanges = "Accept-Ranges";
  315. public const string HttpHeaderAge = "Age";
  316. public const string HttpHeaderAllow = "Allow";
  317. public const string HttpHeaderAuthorization = "Authorization";
  318. public const string HttpHeaderCacheControl = "Cache-Control";
  319. public const string HttpHeaderConnection = "Connection";
  320. public const string HttpHeaderContentEncoding = "Content-Encoding";
  321. public const string HttpHeaderContentLanguage = "Content-Language";
  322. public const string HttpHeaderContentLength = "Content-Length";
  323. public const string HttpHeaderContentLocation = "Content-Location";
  324. public const string HttpHeaderContentMD5 = "Content-MD5";
  325. public const string HttpHeaderContentRange = "Content-Range";
  326. public const string HttpHeaderContentType = "Content-Type";
  327. public const string HttpHeaderDate = "Date";
  328. public const string HttpHeaderETag = "ETag";
  329. public const string HttpHeaderExpect = "Expect";
  330. public const string HttpHeaderExpires = "Expires";
  331. public const string HttpHeaderFrom = "From";
  332. public const string HttpHeaderHost = "Host";
  333. public const string HttpHeaderIfMatch = "If-Match";
  334. public const string HttpHeaderIfModifiedSince = "If-Modified-Since";
  335. public const string HttpHeaderIfNoneMatch = "If-None-Match";
  336. public const string HttpHeaderIfRange = "If-Range";
  337. public const string HttpHeaderIfUnmodifiedSince = "If-Unmodified-Since";
  338. public const string HttpHeaderLastModified = "Last-Modified";
  339. public const string HttpHeaderLocation = "Location";
  340. public const string HttpHeaderMaxForwards = "Max-Forwards";
  341. public const string HttpHeaderPragma = "Pragma";
  342. public const string HttpHeaderProxyAuthenticate = "Proxy-Authenticate";
  343. public const string HttpHeaderProxyAuthorization = "Proxy-Authorization";
  344. public const string HttpHeaderRange = "Range";
  345. public const string HttpHeaderReferer = "Referer";
  346. public const string HttpHeaderRetryAfter = "Retry-After";
  347. public const string HttpHeaderServer = "Server";
  348. public const string HttpHeaderTE = "TE";
  349. public const string HttpHeaderTrailer = "Trailer";
  350. public const string HttpHeaderTransferEncoding = "Transfer-Encoding";
  351. public const string HttpHeaderUpgrade = "Upgrade";
  352. public const string HttpHeaderUserAgent = "User-Agent";
  353. public const string HttpHeaderVary = "Vary";
  354. public const string HttpHeaderVia = "Via";
  355. public const string HttpHeaderWarning = "Warning";
  356. public const string HttpHeaderWWWAuthenticate = "WWW-Authenticate";
  357. /// Utility routines
  358. public static string StringToBase64(string str)
  359. {
  360. try
  361. {
  362. byte[] encData_byte = new byte[str.Length];
  363. encData_byte = Encoding.UTF8.GetBytes(str);
  364. return Convert.ToBase64String(encData_byte);
  365. }
  366. catch
  367. {
  368. return String.Empty;
  369. }
  370. }
  371. public static string Base64ToString(string str)
  372. {
  373. UTF8Encoding encoder = new UTF8Encoding();
  374. Decoder utf8Decode = encoder.GetDecoder();
  375. try
  376. {
  377. byte[] todecode_byte = Convert.FromBase64String(str);
  378. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  379. char[] decoded_char = new char[charCount];
  380. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  381. return new String(decoded_char);
  382. }
  383. catch
  384. {
  385. return String.Empty;
  386. }
  387. }
  388. private const string hvals = "0123456789abcdef";
  389. public static int Hex2Int(string hex)
  390. {
  391. int val = 0;
  392. int sum = 0;
  393. string tmp = null;
  394. if (hex != null)
  395. {
  396. tmp = hex.ToLower();
  397. for (int i = 0; i < tmp.Length; i++)
  398. {
  399. val = hvals.IndexOf(tmp[i]);
  400. if (val == -1)
  401. break;
  402. sum *= 16;
  403. sum += val;
  404. }
  405. }
  406. return sum;
  407. }
  408. // Nonce management
  409. public static string NonceGenerator()
  410. {
  411. return StringToBase64(CreationDate + Guid.NewGuid().ToString());
  412. }
  413. // Dump the specified data stream
  414. public static void Dump(byte[] data)
  415. {
  416. char[] buffer = new char[Rest.DumpLineSize];
  417. int cc = 0;
  418. for (int i = 0; i < data.Length; i++)
  419. {
  420. if (i % Rest.DumpLineSize == 0) Console.Write("\n{0}: ",i.ToString("d8"));
  421. if (i % 4 == 0) Console.Write(" ");
  422. Console.Write("{0}",data[i].ToString("x2"));
  423. if (data[i] < 127 && data[i] > 31)
  424. buffer[i % Rest.DumpLineSize] = (char) data[i];
  425. else
  426. buffer[i % Rest.DumpLineSize] = '.';
  427. cc++;
  428. if (i != 0 && (i + 1) % Rest.DumpLineSize == 0)
  429. {
  430. Console.Write(" |"+(new String(buffer))+"|");
  431. cc = 0;
  432. }
  433. }
  434. // Finish off any incomplete line
  435. if (cc != 0)
  436. {
  437. for (int i = cc ; i < Rest.DumpLineSize; i++)
  438. {
  439. if (i % 4 == 0) Console.Write(" ");
  440. Console.Write(" ");
  441. buffer[i % Rest.DumpLineSize] = ' ';
  442. }
  443. Console.WriteLine(" |"+(new String(buffer))+"|");
  444. }
  445. else
  446. {
  447. Console.Write("\n");
  448. }
  449. }
  450. }
  451. // Local exception type
  452. public class RestException : Exception
  453. {
  454. internal int statusCode;
  455. internal string statusDesc;
  456. internal string httpmethod;
  457. internal string httppath;
  458. public RestException(string msg) : base(msg)
  459. {
  460. }
  461. }
  462. }