UniAddress.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. // This code is derived from jcifs smb client library <jcifs at samba dot org>
  2. // Ported by J. Arturo <webmaster at komodosoft dot net>
  3. //
  4. // This library is free software; you can redistribute it and/or
  5. // modify it under the terms of the GNU Lesser General Public
  6. // License as published by the Free Software Foundation; either
  7. // version 2.1 of the License, or (at your option) any later version.
  8. //
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. // Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public
  15. // License along with this library; if not, write to the Free Software
  16. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. using System;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Net;
  21. using SharpCifs.Netbios;
  22. using SharpCifs.Util;
  23. using SharpCifs.Util.Sharpen;
  24. using Extensions = SharpCifs.Util.Sharpen.Extensions;
  25. namespace SharpCifs
  26. {
  27. /// <summary>
  28. /// <p>Under normal conditions it is not necessary to use
  29. /// this class to use jCIFS properly.
  30. /// </summary>
  31. /// <remarks>
  32. /// <p>Under normal conditions it is not necessary to use
  33. /// this class to use jCIFS properly. Name resolusion is
  34. /// handled internally to the <code>jcifs.smb</code> package.
  35. /// <p>
  36. /// This class is a wrapper for both
  37. /// <see cref="Jcifs.Netbios.NbtAddress">Jcifs.Netbios.NbtAddress</see>
  38. /// and
  39. /// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
  40. /// . The name resolution mechanisms
  41. /// used will systematically query all available configured resolution
  42. /// services including WINS, broadcasts, DNS, and LMHOSTS. See
  43. /// <a href="../../resolver.html">Setting Name Resolution Properties</a>
  44. /// and the <code>jcifs.resolveOrder</code> property. Changing
  45. /// jCIFS name resolution properties can greatly affect the behavior of
  46. /// the client and may be necessary for proper operation.
  47. /// <p>
  48. /// This class should be used in favor of <tt>InetAddress</tt> to resolve
  49. /// hostnames on LANs and WANs that support a mixture of NetBIOS/WINS and
  50. /// DNS resolvable hosts.
  51. /// </remarks>
  52. public class UniAddress
  53. {
  54. private const int ResolverWins = 0;
  55. private const int ResolverBcast = 1;
  56. private const int ResolverDns = 2;
  57. private const int ResolverLmhosts = 3;
  58. private static int[] _resolveOrder;
  59. private static IPAddress _baddr;
  60. private static LogStream _log = LogStream.GetInstance();
  61. static UniAddress()
  62. {
  63. string ro = Config.GetProperty("jcifs.resolveOrder");
  64. IPAddress nbns = NbtAddress.GetWinsAddress();
  65. try
  66. {
  67. _baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName
  68. ("255.255.255.255"));
  69. }
  70. catch (UnknownHostException)
  71. {
  72. }
  73. if (string.IsNullOrEmpty(ro))
  74. {
  75. if (nbns == null)
  76. {
  77. _resolveOrder = new int[3];
  78. _resolveOrder[0] = ResolverLmhosts;
  79. _resolveOrder[1] = ResolverDns;
  80. _resolveOrder[2] = ResolverBcast;
  81. }
  82. else
  83. {
  84. _resolveOrder = new int[4];
  85. _resolveOrder[0] = ResolverLmhosts;
  86. _resolveOrder[1] = ResolverWins;
  87. _resolveOrder[2] = ResolverDns;
  88. _resolveOrder[3] = ResolverBcast;
  89. }
  90. }
  91. else
  92. {
  93. int[] tmp = new int[4];
  94. StringTokenizer st = new StringTokenizer(ro, ",");
  95. int i = 0;
  96. while (st.HasMoreTokens())
  97. {
  98. string s = st.NextToken().Trim();
  99. if (Runtime.EqualsIgnoreCase(s, "LMHOSTS"))
  100. {
  101. tmp[i++] = ResolverLmhosts;
  102. }
  103. else
  104. {
  105. if (Runtime.EqualsIgnoreCase(s, "WINS"))
  106. {
  107. if (nbns == null)
  108. {
  109. if (_log.Level > 1)
  110. {
  111. _log.WriteLine("UniAddress resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
  112. );
  113. }
  114. continue;
  115. }
  116. tmp[i++] = ResolverWins;
  117. }
  118. else
  119. {
  120. if (Runtime.EqualsIgnoreCase(s, "BCAST"))
  121. {
  122. tmp[i++] = ResolverBcast;
  123. }
  124. else
  125. {
  126. if (Runtime.EqualsIgnoreCase(s, "DNS"))
  127. {
  128. tmp[i++] = ResolverDns;
  129. }
  130. else
  131. {
  132. if (_log.Level > 1)
  133. {
  134. _log.WriteLine("unknown resolver method: " + s);
  135. }
  136. }
  137. }
  138. }
  139. }
  140. }
  141. _resolveOrder = new int[i];
  142. Array.Copy(tmp, 0, _resolveOrder, 0, i);
  143. }
  144. }
  145. internal class Sem
  146. {
  147. internal Sem(int count)
  148. {
  149. this.Count = count;
  150. }
  151. internal int Count;
  152. }
  153. internal class QueryThread : Thread
  154. {
  155. internal Sem Sem;
  156. internal string Host;
  157. internal string Scope;
  158. internal int Type;
  159. internal NbtAddress[] Ans;
  160. internal IPAddress Svr;
  161. internal UnknownHostException Uhe;
  162. internal QueryThread(Sem sem, string host, int type, string scope, IPAddress
  163. svr) : base("JCIFS-QueryThread: " + host)
  164. {
  165. this.Sem = sem;
  166. this.Host = host;
  167. this.Type = type;
  168. this.Scope = scope;
  169. this.Svr = svr;
  170. }
  171. public override void Run()
  172. {
  173. try
  174. {
  175. //Ans = new [] { NbtAddress.GetByName(Host, Type, Scope, Svr) };
  176. Ans = NbtAddress.GetAllByName(Host, Type, Scope, Svr);
  177. }
  178. catch (UnknownHostException uhe)
  179. {
  180. this.Uhe = uhe;
  181. }
  182. catch (Exception ex)
  183. {
  184. Uhe = new UnknownHostException(ex.Message);
  185. }
  186. finally
  187. {
  188. lock (Sem)
  189. {
  190. Sem.Count--;
  191. Runtime.Notify(Sem);
  192. }
  193. }
  194. }
  195. }
  196. /// <exception cref="UnknownHostException"></exception>
  197. internal static NbtAddress[] LookupServerOrWorkgroup(string name, IPAddress svr)
  198. {
  199. Sem sem = new Sem(2);
  200. int type = NbtAddress.IsWins(svr) ? unchecked(0x1b) : unchecked(0x1d);
  201. QueryThread q1X = new QueryThread(sem, name, type, null, svr
  202. );
  203. QueryThread q20 = new QueryThread(sem, name, unchecked(0x20), null, svr);
  204. q1X.SetDaemon(true);
  205. q20.SetDaemon(true);
  206. try
  207. {
  208. lock (sem)
  209. {
  210. q1X.Start();
  211. q20.Start();
  212. while (sem.Count > 0 && q1X.Ans == null && q20.Ans == null)
  213. {
  214. Runtime.Wait(sem);
  215. }
  216. }
  217. }
  218. catch (Exception)
  219. {
  220. throw new UnknownHostException(name);
  221. }
  222. if (q1X.Ans != null)
  223. {
  224. return q1X.Ans;
  225. }
  226. if (q20.Ans != null)
  227. {
  228. return q20.Ans;
  229. }
  230. throw q1X.Uhe;
  231. }
  232. /// <summary>Determines the address of a host given it's host name.</summary>
  233. /// <remarks>
  234. /// Determines the address of a host given it's host name. The name can be a
  235. /// machine name like "jcifs.samba.org", or an IP address like "192.168.1.15".
  236. /// </remarks>
  237. /// <param name="hostname">NetBIOS or DNS hostname to resolve</param>
  238. /// <exception cref="UnknownHostException">if there is an error resolving the name
  239. /// </exception>
  240. public static UniAddress GetByName(string hostname)
  241. {
  242. return GetByName(hostname, false);
  243. }
  244. internal static bool IsDotQuadIp(string hostname)
  245. {
  246. if (char.IsDigit(hostname[0]))
  247. {
  248. int i;
  249. int len;
  250. int dots;
  251. char[] data;
  252. i = dots = 0;
  253. len = hostname.Length;
  254. data = hostname.ToCharArray();
  255. while (i < len && char.IsDigit(data[i++]))
  256. {
  257. if (i == len && dots == 3)
  258. {
  259. // probably an IP address
  260. return true;
  261. }
  262. if (i < len && data[i] == '.')
  263. {
  264. dots++;
  265. i++;
  266. }
  267. }
  268. }
  269. return false;
  270. }
  271. internal static bool IsAllDigits(string hostname)
  272. {
  273. for (int i = 0; i < hostname.Length; i++)
  274. {
  275. if (char.IsDigit(hostname[i]) == false)
  276. {
  277. return false;
  278. }
  279. }
  280. return true;
  281. }
  282. /// <summary>Lookup <tt>hostname</tt> and return it's <tt>UniAddress</tt>.</summary>
  283. /// <remarks>
  284. /// Lookup <tt>hostname</tt> and return it's <tt>UniAddress</tt>. If the
  285. /// <tt>possibleNTDomainOrWorkgroup</tt> parameter is <tt>true</tt> an
  286. /// addtional name query will be performed to locate a master browser.
  287. /// </remarks>
  288. /// <exception cref="UnknownHostException"></exception>
  289. public static UniAddress GetByName(string hostname, bool possibleNtDomainOrWorkgroup
  290. )
  291. {
  292. UniAddress[] addrs = GetAllByName(hostname, possibleNtDomainOrWorkgroup
  293. );
  294. return addrs[0];
  295. }
  296. /// <exception cref="UnknownHostException"></exception>
  297. public static UniAddress[] GetAllByName(string hostname, bool possibleNtDomainOrWorkgroup
  298. )
  299. {
  300. object addr;
  301. int i;
  302. if (string.IsNullOrEmpty(hostname))
  303. {
  304. throw new UnknownHostException();
  305. }
  306. if (IsDotQuadIp(hostname))
  307. {
  308. UniAddress[] addrs = new UniAddress[1];
  309. addrs[0] = new UniAddress(NbtAddress.GetByName(hostname));
  310. return addrs;
  311. }
  312. for (i = 0; i < _resolveOrder.Length; i++)
  313. {
  314. try
  315. {
  316. switch (_resolveOrder[i])
  317. {
  318. case ResolverLmhosts:
  319. {
  320. if ((addr = Lmhosts.GetByName(hostname)) == null)
  321. {
  322. continue;
  323. }
  324. break;
  325. }
  326. case ResolverWins:
  327. {
  328. if (hostname == NbtAddress.MasterBrowserName || hostname.Length > 15)
  329. {
  330. // invalid netbios name
  331. continue;
  332. }
  333. if (possibleNtDomainOrWorkgroup)
  334. {
  335. addr = LookupServerOrWorkgroup(hostname, NbtAddress.GetWinsAddress());
  336. }
  337. else
  338. {
  339. addr = NbtAddress.GetByName(hostname, unchecked(0x20), null, NbtAddress.GetWinsAddress
  340. ());
  341. }
  342. break;
  343. }
  344. case ResolverBcast:
  345. {
  346. if (hostname.Length > 15)
  347. {
  348. // invalid netbios name
  349. continue;
  350. }
  351. try
  352. {
  353. if (possibleNtDomainOrWorkgroup)
  354. {
  355. NbtAddress[] iaddrs = LookupServerOrWorkgroup(hostname, _baddr);
  356. UniAddress[] addrs = new UniAddress[iaddrs.Length];
  357. for (int ii = 0; ii < iaddrs.Length; ii++)
  358. {
  359. addrs[ii] = new UniAddress(iaddrs[ii]);
  360. }
  361. return addrs;
  362. }
  363. else
  364. {
  365. addr = NbtAddress.GetByName(hostname, unchecked(0x20), null, _baddr);
  366. }
  367. }
  368. catch (Exception ex)
  369. {
  370. if (i == _resolveOrder.Length - 1)
  371. {
  372. throw ex;
  373. }
  374. else
  375. {
  376. continue;
  377. }
  378. }
  379. break;
  380. }
  381. case ResolverDns:
  382. {
  383. if (IsAllDigits(hostname))
  384. {
  385. throw new UnknownHostException(hostname);
  386. }
  387. IPAddress[] iaddrs = Extensions.GetAddressesByName(hostname);
  388. if (iaddrs == null || iaddrs.Length == 0)
  389. {
  390. continue;
  391. }
  392. return iaddrs.Select(iaddr => new UniAddress(iaddr)).ToArray();
  393. }
  394. default:
  395. {
  396. // Success
  397. throw new UnknownHostException(hostname);
  398. }
  399. }
  400. UniAddress[] addrs1 = new UniAddress[1];
  401. addrs1[0] = new UniAddress(addr);
  402. return addrs1;
  403. }
  404. catch (IOException)
  405. {
  406. }
  407. }
  408. // Success
  409. // Failure
  410. throw new UnknownHostException(hostname);
  411. }
  412. internal object Addr;
  413. internal string CalledName;
  414. /// <summary>
  415. /// Create a <tt>UniAddress</tt> by wrapping an <tt>InetAddress</tt> or
  416. /// <tt>NbtAddress</tt>.
  417. /// </summary>
  418. /// <remarks>
  419. /// Create a <tt>UniAddress</tt> by wrapping an <tt>InetAddress</tt> or
  420. /// <tt>NbtAddress</tt>.
  421. /// </remarks>
  422. public UniAddress(object addr)
  423. {
  424. if (addr == null)
  425. {
  426. throw new ArgumentException();
  427. }
  428. this.Addr = addr;
  429. }
  430. /// <summary>Return the IP address of this address as a 32 bit integer.</summary>
  431. /// <remarks>Return the IP address of this address as a 32 bit integer.</remarks>
  432. public override int GetHashCode()
  433. {
  434. return Addr.GetHashCode();
  435. }
  436. /// <summary>Compare two addresses for equality.</summary>
  437. /// <remarks>
  438. /// Compare two addresses for equality. Two <tt>UniAddress</tt>s are equal
  439. /// if they are both <tt>UniAddress</tt>' and refer to the same IP address.
  440. /// </remarks>
  441. public override bool Equals(object obj)
  442. {
  443. return obj is UniAddress && Addr.Equals(((UniAddress)obj).Addr);
  444. }
  445. /// <summary>Guess first called name to try for session establishment.</summary>
  446. /// <remarks>
  447. /// Guess first called name to try for session establishment. This
  448. /// method is used exclusively by the <tt>jcifs.smb</tt> package.
  449. /// </remarks>
  450. public virtual string FirstCalledName()
  451. {
  452. if (Addr is NbtAddress)
  453. {
  454. return ((NbtAddress)Addr).FirstCalledName();
  455. }
  456. CalledName = ((IPAddress) Addr).GetHostAddress();
  457. if (IsDotQuadIp(CalledName))
  458. {
  459. CalledName = NbtAddress.SmbserverName;
  460. }
  461. else
  462. {
  463. int i = CalledName.IndexOf('.');
  464. if (i > 1 && i < 15)
  465. {
  466. CalledName = Runtime.Substring(CalledName, 0, i).ToUpper();
  467. }
  468. else
  469. {
  470. if (CalledName.Length > 15)
  471. {
  472. CalledName = NbtAddress.SmbserverName;
  473. }
  474. else
  475. {
  476. CalledName = CalledName.ToUpper();
  477. }
  478. }
  479. }
  480. return CalledName;
  481. }
  482. /// <summary>Guess next called name to try for session establishment.</summary>
  483. /// <remarks>
  484. /// Guess next called name to try for session establishment. This
  485. /// method is used exclusively by the <tt>jcifs.smb</tt> package.
  486. /// </remarks>
  487. public virtual string NextCalledName()
  488. {
  489. if (Addr is NbtAddress)
  490. {
  491. return ((NbtAddress)Addr).NextCalledName();
  492. }
  493. if (CalledName != NbtAddress.SmbserverName)
  494. {
  495. CalledName = NbtAddress.SmbserverName;
  496. return CalledName;
  497. }
  498. return null;
  499. }
  500. /// <summary>Return the underlying <tt>NbtAddress</tt> or <tt>InetAddress</tt>.</summary>
  501. /// <remarks>Return the underlying <tt>NbtAddress</tt> or <tt>InetAddress</tt>.</remarks>
  502. public virtual object GetAddress()
  503. {
  504. return Addr;
  505. }
  506. /// <summary>Return the hostname of this address such as "MYCOMPUTER".</summary>
  507. /// <remarks>Return the hostname of this address such as "MYCOMPUTER".</remarks>
  508. public virtual string GetHostName()
  509. {
  510. if (Addr is NbtAddress)
  511. {
  512. return ((NbtAddress)Addr).GetHostName();
  513. }
  514. return ((IPAddress) Addr).GetHostAddress();
  515. }
  516. /// <summary>Return the IP address as text such as "192.168.1.15".</summary>
  517. /// <remarks>Return the IP address as text such as "192.168.1.15".</remarks>
  518. public virtual string GetHostAddress()
  519. {
  520. if (Addr is NbtAddress)
  521. {
  522. return ((NbtAddress)Addr).GetHostAddress();
  523. }
  524. return ((IPAddress)Addr).GetHostAddress();
  525. }
  526. public virtual IPAddress GetHostIpAddress()
  527. {
  528. return (IPAddress) Addr;
  529. }
  530. /// <summary>
  531. /// Return the a text representation of this address such as
  532. /// <tt>MYCOMPUTER/192.168.1.15</tt>.
  533. /// </summary>
  534. /// <remarks>
  535. /// Return the a text representation of this address such as
  536. /// <tt>MYCOMPUTER/192.168.1.15</tt>.
  537. /// </remarks>
  538. public override string ToString()
  539. {
  540. return Addr.ToString();
  541. }
  542. }
  543. }