Rest.cs 22 KB

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