SmbFile.cs 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755
  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.Collections.Generic;
  19. using System.IO;
  20. using System.Net;
  21. using System.Text;
  22. using SharpCifs.Dcerpc;
  23. using SharpCifs.Dcerpc.Msrpc;
  24. using SharpCifs.Netbios;
  25. using SharpCifs.Util;
  26. using SharpCifs.Util.Sharpen;
  27. namespace SharpCifs.Smb
  28. {
  29. /// <summary>This class represents a resource on an SMB network.</summary>
  30. /// <remarks>
  31. /// This class represents a resource on an SMB network. Mainly these
  32. /// resources are files and directories however an <code>SmbFile</code>
  33. /// may also refer to servers and workgroups. If the resource is a file or
  34. /// directory the methods of <code>SmbFile</code> follow the behavior of
  35. /// the well known
  36. /// <see cref="FilePath">Sharpen.FilePath</see>
  37. /// class. One fundamental difference
  38. /// is the usage of a URL scheme [1] to specify the target file or
  39. /// directory. SmbFile URLs have the following syntax:
  40. /// <blockquote><pre>
  41. /// smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?[param=value[param2=value2[...]]]
  42. /// </pre></blockquote>
  43. /// This example:
  44. /// <blockquote><pre>
  45. /// smb://storage15/public/foo.txt
  46. /// </pre></blockquote>
  47. /// would reference the file <code>foo.txt</code> in the share
  48. /// <code>public</code> on the server <code>storage15</code>. In addition
  49. /// to referencing files and directories, jCIFS can also address servers,
  50. /// and workgroups.
  51. /// <p>
  52. /// <font color="#800000"><i>Important: all SMB URLs that represent
  53. /// workgroups, servers, shares, or directories require a trailing slash '/'.
  54. /// </i></font>
  55. /// <p>
  56. /// When using the <tt>java.net.URL</tt> class with
  57. /// 'smb://' URLs it is necessary to first call the static
  58. /// <tt>jcifs.Config.registerSmbURLHandler();</tt> method. This is required
  59. /// to register the SMB protocol handler.
  60. /// <p>
  61. /// The userinfo component of the SMB URL (<tt>domain;user:pass</tt>) must
  62. /// be URL encoded if it contains reserved characters. According to RFC 2396
  63. /// these characters are non US-ASCII characters and most meta characters
  64. /// however jCIFS will work correctly with anything but '@' which is used
  65. /// to delimit the userinfo component from the server and '%' which is the
  66. /// URL escape character itself.
  67. /// <p>
  68. /// The server
  69. /// component may a traditional NetBIOS name, a DNS name, or IP
  70. /// address. These name resolution mechanisms and their resolution order
  71. /// can be changed (See <a href="../../../resolver.html">Setting Name
  72. /// Resolution Properties</a>). The servername and path components are
  73. /// not case sensitive but the domain, username, and password components
  74. /// are. It is also likely that properties must be specified for jcifs
  75. /// to function (See <a href="../../overview-summary.html#scp">Setting
  76. /// JCIFS Properties</a>). Here are some examples of SMB URLs with brief
  77. /// descriptions of what they do:
  78. /// <p>[1] This URL scheme is based largely on the <i>SMB
  79. /// Filesharing URL Scheme</i> IETF draft.
  80. /// <p><table border="1" cellpadding="3" cellspacing="0" width="100%">
  81. /// <tr bgcolor="#ccccff">
  82. /// <td colspan="2"><b>SMB URL Examples</b></td>
  83. /// <tr><td width="20%"><b>URL</b></td><td><b>Description</b></td></tr>
  84. /// <tr><td width="20%"><code>smb://users-nyc;miallen:mypass@angus/tmp/</code></td><td>
  85. /// This URL references a share called <code>tmp</code> on the server
  86. /// <code>angus</code> as user <code>miallen</code> who's password is
  87. /// <code>mypass</code>.
  88. /// </td></tr>
  89. /// <tr><td width="20%">
  90. /// <code>smb://Administrator:P%40ss@msmith1/c/WINDOWS/Desktop/foo.txt</code></td><td>
  91. /// A relativly sophisticated example that references a file
  92. /// <code>msmith1</code>'s desktop as user <code>Administrator</code>. Notice the '@' is URL encoded with the '%40' hexcode escape.
  93. /// </td></tr>
  94. /// <tr><td width="20%"><code>smb://angus/</code></td><td>
  95. /// This references only a server. The behavior of some methods is different
  96. /// in this context(e.g. you cannot <code>delete</code> a server) however
  97. /// as you might expect the <code>list</code> method will list the available
  98. /// shares on this server.
  99. /// </td></tr>
  100. /// <tr><td width="20%"><code>smb://myworkgroup/</code></td><td>
  101. /// This syntactically is identical to the above example. However if
  102. /// <code>myworkgroup</code> happends to be a workgroup(which is indeed
  103. /// suggested by the name) the <code>list</code> method will return
  104. /// a list of servers that have registered themselves as members of
  105. /// <code>myworkgroup</code>.
  106. /// </td></tr>
  107. /// <tr><td width="20%"><code>smb://</code></td><td>
  108. /// Just as <code>smb://server/</code> lists shares and
  109. /// <code>smb://workgroup/</code> lists servers, the <code>smb://</code>
  110. /// URL lists all available workgroups on a netbios LAN. Again,
  111. /// in this context many methods are not valid and return default
  112. /// values(e.g. <code>isHidden</code> will always return false).
  113. /// </td></tr>
  114. /// <tr><td width="20%"><code>smb://angus.foo.net/d/jcifs/pipes.doc</code></td><td>
  115. /// The server name may also be a DNS name as it is in this example. See
  116. /// <a href="../../../resolver.html">Setting Name Resolution Properties</a>
  117. /// for details.
  118. /// </td></tr>
  119. /// <tr><td width="20%"><code>smb://192.168.1.15/ADMIN$/</code></td><td>
  120. /// The server name may also be an IP address. See &lt;a
  121. /// href="../../../resolver.html"&gt;Setting Name Resolution Properties</a>
  122. /// for details.
  123. /// </td></tr>
  124. /// <tr><td width="20%">
  125. /// <code>smb://domain;username:password@server/share/path/to/file.txt</code></td><td>
  126. /// A prototypical example that uses all the fields.
  127. /// </td></tr>
  128. /// <tr><td width="20%"><code>smb://myworkgroup/angus/ &lt;-- ILLEGAL </code></td><td>
  129. /// Despite the hierarchial relationship between workgroups, servers, and
  130. /// filesystems this example is not valid.
  131. /// </td></tr>
  132. /// <tr><td width="20%">
  133. /// <code>smb://server/share/path/to/dir &lt;-- ILLEGAL </code></td><td>
  134. /// URLs that represent workgroups, servers, shares, or directories require a trailing slash '/'.
  135. /// </td></tr>
  136. /// <tr><td width="20%">
  137. /// <code>smb://MYGROUP/?SERVER=192.168.10.15</code></td><td>
  138. /// SMB URLs support some query string parameters. In this example
  139. /// the <code>SERVER</code> parameter is used to override the
  140. /// server name service lookup to contact the server 192.168.10.15
  141. /// (presumably known to be a master
  142. /// browser) for the server list in workgroup <code>MYGROUP</code>.
  143. /// </td></tr>
  144. /// </table>
  145. /// <p>A second constructor argument may be specified to augment the URL
  146. /// for better programmatic control when processing many files under
  147. /// a common base. This is slightly different from the corresponding
  148. /// <code>java.io.File</code> usage; a '/' at the beginning of the second
  149. /// parameter will still use the server component of the first parameter. The
  150. /// examples below illustrate the resulting URLs when this second contructor
  151. /// argument is used.
  152. /// <p><table border="1" cellpadding="3" cellspacing="0" width="100%">
  153. /// <tr bgcolor="#ccccff">
  154. /// <td colspan="3">
  155. /// <b>Examples Of SMB URLs When Augmented With A Second Constructor Parameter</b></td>
  156. /// <tr><td width="20%">
  157. /// <b>First Parameter</b></td><td><b>Second Parameter</b></td><td><b>Result</b></td></tr>
  158. /// <tr><td width="20%"><code>
  159. /// smb://host/share/a/b/
  160. /// </code></td><td width="20%"><code>
  161. /// c/d/
  162. /// </code></td><td><code>
  163. /// smb://host/share/a/b/c/d/
  164. /// </code></td></tr>
  165. /// <tr><td width="20%"><code>
  166. /// smb://host/share/foo/bar/
  167. /// </code></td><td width="20%"><code>
  168. /// /share2/zig/zag
  169. /// </code></td><td><code>
  170. /// smb://host/share2/zig/zag
  171. /// </code></td></tr>
  172. /// <tr><td width="20%"><code>
  173. /// smb://host/share/foo/bar/
  174. /// </code></td><td width="20%"><code>
  175. /// ../zip/
  176. /// </code></td><td><code>
  177. /// smb://host/share/foo/zip/
  178. /// </code></td></tr>
  179. /// <tr><td width="20%"><code>
  180. /// smb://host/share/zig/zag
  181. /// </code></td><td width="20%"><code>
  182. /// smb://foo/bar/
  183. /// </code></td><td><code>
  184. /// smb://foo/bar/
  185. /// </code></td></tr>
  186. /// <tr><td width="20%"><code>
  187. /// smb://host/share/foo/
  188. /// </code></td><td width="20%"><code>
  189. /// ../.././.././../foo/
  190. /// </code></td><td><code>
  191. /// smb://host/foo/
  192. /// </code></td></tr>
  193. /// <tr><td width="20%"><code>
  194. /// smb://host/share/zig/zag
  195. /// </code></td><td width="20%"><code>
  196. /// /
  197. /// </code></td><td><code>
  198. /// smb://host/
  199. /// </code></td></tr>
  200. /// <tr><td width="20%"><code>
  201. /// smb://server/
  202. /// </code></td><td width="20%"><code>
  203. /// ../
  204. /// </code></td><td><code>
  205. /// smb://server/
  206. /// </code></td></tr>
  207. /// <tr><td width="20%"><code>
  208. /// smb://
  209. /// </code></td><td width="20%"><code>
  210. /// myworkgroup/
  211. /// </code></td><td><code>
  212. /// smb://myworkgroup/
  213. /// </code></td></tr>
  214. /// <tr><td width="20%"><code>
  215. /// smb://myworkgroup/
  216. /// </code></td><td width="20%"><code>
  217. /// angus/
  218. /// </code></td><td><code>
  219. /// smb://myworkgroup/angus/ &lt;-- ILLEGAL<br />(But if you first create an <tt>SmbFile</tt> with 'smb://workgroup/' and use and use it as the first parameter to a constructor that accepts it with a second <tt>String</tt> parameter jCIFS will factor out the 'workgroup'.)
  220. /// </code></td></tr>
  221. /// </table>
  222. /// <p>Instances of the <code>SmbFile</code> class are immutable; that is,
  223. /// once created, the abstract pathname represented by an SmbFile object
  224. /// will never change.
  225. /// </remarks>
  226. /// <seealso cref="FilePath">Sharpen.FilePath</seealso>
  227. public class SmbFile : UrlConnection
  228. {
  229. internal const int ORdonly = 0x01;
  230. internal const int OWronly = 0x02;
  231. internal const int ORdwr = 0x03;
  232. internal const int OAppend = 0x04;
  233. internal const int OCreat = 0x0010;
  234. internal const int OExcl = 0x0020;
  235. internal const int OTrunc = 0x0040;
  236. /// <summary>
  237. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  238. /// other SMB clients (including other threads making calls into jCIFS)
  239. /// will not be permitted to access the target file and will receive "The
  240. /// file is being accessed by another process" message.
  241. /// </summary>
  242. /// <remarks>
  243. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  244. /// other SMB clients (including other threads making calls into jCIFS)
  245. /// will not be permitted to access the target file and will receive "The
  246. /// file is being accessed by another process" message.
  247. /// </remarks>
  248. public const int FileNoShare = 0x00;
  249. /// <summary>
  250. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  251. /// other SMB clients will be permitted to read from the target file while
  252. /// this file is open.
  253. /// </summary>
  254. /// <remarks>
  255. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  256. /// other SMB clients will be permitted to read from the target file while
  257. /// this file is open. This constant may be logically OR'd with other share
  258. /// access flags.
  259. /// </remarks>
  260. public const int FileShareRead = 0x01;
  261. /// <summary>
  262. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  263. /// other SMB clients will be permitted to write to the target file while
  264. /// this file is open.
  265. /// </summary>
  266. /// <remarks>
  267. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  268. /// other SMB clients will be permitted to write to the target file while
  269. /// this file is open. This constant may be logically OR'd with other share
  270. /// access flags.
  271. /// </remarks>
  272. public const int FileShareWrite = 0x02;
  273. /// <summary>
  274. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  275. /// other SMB clients will be permitted to delete the target file while
  276. /// this file is open.
  277. /// </summary>
  278. /// <remarks>
  279. /// When specified as the <tt>shareAccess</tt> constructor parameter,
  280. /// other SMB clients will be permitted to delete the target file while
  281. /// this file is open. This constant may be logically OR'd with other share
  282. /// access flags.
  283. /// </remarks>
  284. public const int FileShareDelete = 0x04;
  285. /// <summary>
  286. /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
  287. /// with <tt>setAttributes()</tt> will be read-only
  288. /// </summary>
  289. public const int AttrReadonly = 0x01;
  290. /// <summary>
  291. /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
  292. /// with <tt>setAttributes()</tt> will be hidden
  293. /// </summary>
  294. public const int AttrHidden = 0x02;
  295. /// <summary>
  296. /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
  297. /// with <tt>setAttributes()</tt> will be a system file
  298. /// </summary>
  299. public const int AttrSystem = 0x04;
  300. /// <summary>
  301. /// A file with this bit on as returned by <tt>getAttributes()</tt> is
  302. /// a volume
  303. /// </summary>
  304. public const int AttrVolume = 0x08;
  305. /// <summary>
  306. /// A file with this bit on as returned by <tt>getAttributes()</tt> is
  307. /// a directory
  308. /// </summary>
  309. public const int AttrDirectory = 0x10;
  310. /// <summary>
  311. /// A file with this bit on as returned by <tt>getAttributes()</tt> or set
  312. /// with <tt>setAttributes()</tt> is an archived file
  313. /// </summary>
  314. public const int AttrArchive = 0x20;
  315. internal const int AttrCompressed = 0x800;
  316. internal const int AttrNormal = 0x080;
  317. internal const int AttrTemporary = 0x100;
  318. internal const int AttrGetMask = 0x7FFF;
  319. internal const int AttrSetMask = 0x30A7;
  320. internal const int DefaultAttrExpirationPeriod = 5000;
  321. internal static readonly int HashDot = ".".GetHashCode();
  322. internal static readonly int HashDotDot = "..".GetHashCode();
  323. //internal static LogStream log = LogStream.GetInstance();
  324. public LogStream Log
  325. {
  326. get { return LogStream.GetInstance(); }
  327. }
  328. internal static long AttrExpirationPeriod;
  329. internal static bool IgnoreCopyToException;
  330. static SmbFile()
  331. {
  332. // Open Function Encoding
  333. // create if the file does not exist
  334. // fail if the file exists
  335. // truncate if the file exists
  336. // share access
  337. // file attribute encoding
  338. // extended file attribute encoding(others same as above)
  339. /*try
  340. {
  341. Sharpen.Runtime.GetType("jcifs.Config");
  342. }
  343. catch (TypeLoadException cnfe)
  344. {
  345. Sharpen.Runtime.PrintStackTrace(cnfe);
  346. }*/
  347. AttrExpirationPeriod = Config.GetLong("jcifs.smb.client.attrExpirationPeriod", DefaultAttrExpirationPeriod
  348. );
  349. IgnoreCopyToException = Config.GetBoolean("jcifs.smb.client.ignoreCopyToException"
  350. , true);
  351. Dfs = new Dfs();
  352. }
  353. /// <summary>
  354. /// Returned by
  355. /// <see cref="GetType()">GetType()</see>
  356. /// if the resource this <tt>SmbFile</tt>
  357. /// represents is a regular file or directory.
  358. /// </summary>
  359. public const int TypeFilesystem = 0x01;
  360. /// <summary>
  361. /// Returned by
  362. /// <see cref="GetType()">GetType()</see>
  363. /// if the resource this <tt>SmbFile</tt>
  364. /// represents is a workgroup.
  365. /// </summary>
  366. public const int TypeWorkgroup = 0x02;
  367. /// <summary>
  368. /// Returned by
  369. /// <see cref="GetType()">GetType()</see>
  370. /// if the resource this <tt>SmbFile</tt>
  371. /// represents is a server.
  372. /// </summary>
  373. public const int TypeServer = 0x04;
  374. /// <summary>
  375. /// Returned by
  376. /// <see cref="GetType()">GetType()</see>
  377. /// if the resource this <tt>SmbFile</tt>
  378. /// represents is a share.
  379. /// </summary>
  380. public const int TypeShare = 0x08;
  381. /// <summary>
  382. /// Returned by
  383. /// <see cref="GetType()">GetType()</see>
  384. /// if the resource this <tt>SmbFile</tt>
  385. /// represents is a named pipe.
  386. /// </summary>
  387. public const int TypeNamedPipe = 0x10;
  388. /// <summary>
  389. /// Returned by
  390. /// <see cref="GetType()">GetType()</see>
  391. /// if the resource this <tt>SmbFile</tt>
  392. /// represents is a printer.
  393. /// </summary>
  394. public const int TypePrinter = 0x20;
  395. /// <summary>
  396. /// Returned by
  397. /// <see cref="GetType()">GetType()</see>
  398. /// if the resource this <tt>SmbFile</tt>
  399. /// represents is a communications device.
  400. /// </summary>
  401. public const int TypeComm = 0x40;
  402. private string _canon;
  403. private string _share;
  404. private long _createTime;
  405. private long _lastModified;
  406. private int _attributes;
  407. private long _attrExpiration;
  408. private long _size;
  409. private long _sizeExpiration;
  410. private bool _isExists;
  411. private int _shareAccess = FileShareRead | FileShareWrite | FileShareDelete;
  412. private bool _enableDfs = Config.GetBoolean("jcifs.smb.client.enabledfs", false);
  413. private SmbComBlankResponse _blankResp;
  414. private DfsReferral _dfsReferral;
  415. protected internal static Dfs Dfs;
  416. internal NtlmPasswordAuthentication Auth;
  417. internal SmbTree Tree;
  418. internal string Unc;
  419. internal int Fid;
  420. internal int Type;
  421. internal bool Opened;
  422. internal int TreeNum;
  423. public bool EnableDfs
  424. {
  425. get { return _enableDfs; }
  426. set { _enableDfs = value; }
  427. }
  428. /// <summary>
  429. /// Constructs an SmbFile representing a resource on an SMB network such as
  430. /// a file or directory.
  431. /// </summary>
  432. /// <remarks>
  433. /// Constructs an SmbFile representing a resource on an SMB network such as
  434. /// a file or directory. See the description and examples of smb URLs above.
  435. /// </remarks>
  436. /// <param name="url">A URL string</param>
  437. /// <exception cref="System.UriFormatException">
  438. /// If the <code>parent</code> and <code>child</code> parameters
  439. /// do not follow the prescribed syntax
  440. /// </exception>
  441. public SmbFile(string url)
  442. : this(new Uri(url))
  443. {
  444. }
  445. /// <summary>
  446. /// Constructs an SmbFile representing a resource on an SMB network such
  447. /// as a file or directory.
  448. /// </summary>
  449. /// <remarks>
  450. /// Constructs an SmbFile representing a resource on an SMB network such
  451. /// as a file or directory. The second parameter is a relative path from
  452. /// the <code>parent SmbFile</code>. See the description above for examples
  453. /// of using the second <code>name</code> parameter.
  454. /// </remarks>
  455. /// <param name="context">A base <code>SmbFile</code></param>
  456. /// <param name="name">A path string relative to the <code>parent</code> paremeter</param>
  457. /// <exception cref="System.UriFormatException">
  458. /// If the <code>parent</code> and <code>child</code> parameters
  459. /// do not follow the prescribed syntax
  460. /// </exception>
  461. /// <exception cref="UnknownHostException">If the server or workgroup of the <tt>context</tt> file cannot be determined
  462. /// </exception>
  463. public SmbFile(SmbFile context, string name)
  464. : this(context.IsWorkgroup0
  465. () ? new Uri("smb://" + name) : new Uri(context.Url.AbsoluteUri + name),
  466. context.Auth)
  467. {
  468. this._enableDfs = context.EnableDfs;
  469. if (!context.IsWorkgroup0())
  470. {
  471. Addresses = context.Addresses;
  472. if (context._share != null)
  473. {
  474. Tree = context.Tree;
  475. _dfsReferral = context._dfsReferral;
  476. }
  477. }
  478. }
  479. /// <summary>
  480. /// Constructs an SmbFile representing a resource on an SMB network such
  481. /// as a file or directory.
  482. /// </summary>
  483. /// <remarks>
  484. /// Constructs an SmbFile representing a resource on an SMB network such
  485. /// as a file or directory. The second parameter is a relative path from
  486. /// the <code>parent</code>. See the description above for examples of
  487. /// using the second <code>chile</code> parameter.
  488. /// </remarks>
  489. /// <param name="context">A URL string</param>
  490. /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
  491. /// <exception cref="System.UriFormatException">
  492. /// If the <code>context</code> and <code>name</code> parameters
  493. /// do not follow the prescribed syntax
  494. /// </exception>
  495. /*public SmbFile(string context, string name)
  496. : this(new Uri(new Uri(null, context), name))
  497. {
  498. }*/
  499. public SmbFile(string context, string name)
  500. : this(new Uri(context + name))
  501. {
  502. }
  503. /// <summary>
  504. /// Constructs an SmbFile representing a resource on an SMB network such
  505. /// as a file or directory.
  506. /// </summary>
  507. /// <remarks>
  508. /// Constructs an SmbFile representing a resource on an SMB network such
  509. /// as a file or directory.
  510. /// </remarks>
  511. /// <param name="url">A URL string</param>
  512. /// <param name="auth">The credentials the client should use for authentication</param>
  513. /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
  514. /// </exception>
  515. public SmbFile(string url, NtlmPasswordAuthentication auth)
  516. : this(new Uri(url, UriKind.RelativeOrAbsolute),
  517. auth)
  518. {
  519. }
  520. /// <summary>Constructs an SmbFile representing a file on an SMB network.</summary>
  521. /// <remarks>
  522. /// Constructs an SmbFile representing a file on an SMB network. The
  523. /// <tt>shareAccess</tt> parameter controls what permissions other
  524. /// clients have when trying to access the same file while this instance
  525. /// is still open. This value is either <tt>FILE_NO_SHARE</tt> or any
  526. /// combination of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>,
  527. /// and <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
  528. /// </remarks>
  529. /// <param name="url">A URL string</param>
  530. /// <param name="auth">The credentials the client should use for authentication</param>
  531. /// <param name="shareAccess">Specifies what access other clients have while this file is open.
  532. /// </param>
  533. /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
  534. /// </exception>
  535. public SmbFile(string url, NtlmPasswordAuthentication auth, int shareAccess)
  536. : this
  537. (new Uri(url), auth)
  538. {
  539. // Initially null; set by getUncPath; dir must end with '/'
  540. // Can be null
  541. // For getDfsPath() and getServerWithDfs()
  542. // Cannot be null
  543. // Initially null
  544. // Initially null; set by getUncPath; never ends with '/'
  545. // Initially 0; set by open()
  546. if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
  547. 0)
  548. {
  549. throw new RuntimeException("Illegal shareAccess parameter");
  550. }
  551. this._shareAccess = shareAccess;
  552. }
  553. /// <summary>
  554. /// Constructs an SmbFile representing a resource on an SMB network such
  555. /// as a file or directory.
  556. /// </summary>
  557. /// <remarks>
  558. /// Constructs an SmbFile representing a resource on an SMB network such
  559. /// as a file or directory. The second parameter is a relative path from
  560. /// the <code>context</code>. See the description above for examples of
  561. /// using the second <code>name</code> parameter.
  562. /// </remarks>
  563. /// <param name="context">A URL string</param>
  564. /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
  565. /// <param name="auth">The credentials the client should use for authentication</param>
  566. /// <exception cref="System.UriFormatException">
  567. /// If the <code>context</code> and <code>name</code> parameters
  568. /// do not follow the prescribed syntax
  569. /// </exception>
  570. public SmbFile(string context, string name, NtlmPasswordAuthentication auth)
  571. : this
  572. (new Uri(context + name)
  573. , auth)
  574. {
  575. }
  576. /// <summary>
  577. /// Constructs an SmbFile representing a resource on an SMB network such
  578. /// as a file or directory.
  579. /// </summary>
  580. /// <remarks>
  581. /// Constructs an SmbFile representing a resource on an SMB network such
  582. /// as a file or directory. The second parameter is a relative path from
  583. /// the <code>context</code>. See the description above for examples of
  584. /// using the second <code>name</code> parameter. The <tt>shareAccess</tt>
  585. /// parameter controls what permissions other clients have when trying
  586. /// to access the same file while this instance is still open. This
  587. /// value is either <tt>FILE_NO_SHARE</tt> or any combination
  588. /// of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and
  589. /// <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
  590. /// </remarks>
  591. /// <param name="context">A URL string</param>
  592. /// <param name="name">A path string relative to the <code>context</code> paremeter</param>
  593. /// <param name="auth">The credentials the client should use for authentication</param>
  594. /// <param name="shareAccess">Specifies what access other clients have while this file is open.
  595. /// </param>
  596. /// <exception cref="System.UriFormatException">
  597. /// If the <code>context</code> and <code>name</code> parameters
  598. /// do not follow the prescribed syntax
  599. /// </exception>
  600. public SmbFile(string context, string name, NtlmPasswordAuthentication auth, int
  601. shareAccess)
  602. : this(new Uri(context + name), auth)
  603. {
  604. if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
  605. 0)
  606. {
  607. throw new RuntimeException("Illegal shareAccess parameter");
  608. }
  609. this._shareAccess = shareAccess;
  610. }
  611. /// <summary>
  612. /// Constructs an SmbFile representing a resource on an SMB network such
  613. /// as a file or directory.
  614. /// </summary>
  615. /// <remarks>
  616. /// Constructs an SmbFile representing a resource on an SMB network such
  617. /// as a file or directory. The second parameter is a relative path from
  618. /// the <code>context</code>. See the description above for examples of
  619. /// using the second <code>name</code> parameter. The <tt>shareAccess</tt>
  620. /// parameter controls what permissions other clients have when trying
  621. /// to access the same file while this instance is still open. This
  622. /// value is either <tt>FILE_NO_SHARE</tt> or any combination
  623. /// of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and
  624. /// <tt>FILE_SHARE_DELETE</tt> logically OR'd together.
  625. /// </remarks>
  626. /// <param name="context">A base <code>SmbFile</code></param>
  627. /// <param name="name">A path string relative to the <code>context</code> file path</param>
  628. /// <param name="shareAccess">Specifies what access other clients have while this file is open.
  629. /// </param>
  630. /// <exception cref="System.UriFormatException">
  631. /// If the <code>context</code> and <code>name</code> parameters
  632. /// do not follow the prescribed syntax
  633. /// </exception>
  634. /// <exception cref="UnknownHostException"></exception>
  635. public SmbFile(SmbFile context, string name, int shareAccess)
  636. : this(context.IsWorkgroup0() ? new Uri("smb://" + name) : new Uri(
  637. context.Url.AbsoluteUri + name), context.Auth)
  638. {
  639. if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
  640. 0)
  641. {
  642. throw new RuntimeException("Illegal shareAccess parameter");
  643. }
  644. if (!context.IsWorkgroup0())
  645. {
  646. this.Addresses = context.Addresses;
  647. if (context._share != null || context.Tree != null)
  648. {
  649. Tree = context.Tree;
  650. _dfsReferral = context._dfsReferral;
  651. }
  652. }
  653. this._shareAccess = shareAccess;
  654. this._enableDfs = context.EnableDfs;
  655. }
  656. /// <summary>
  657. /// Constructs an SmbFile representing a resource on an SMB network such
  658. /// as a file or directory from a <tt>URL</tt> object.
  659. /// </summary>
  660. /// <remarks>
  661. /// Constructs an SmbFile representing a resource on an SMB network such
  662. /// as a file or directory from a <tt>URL</tt> object.
  663. /// </remarks>
  664. /// <param name="url">The URL of the target resource</param>
  665. protected SmbFile(Uri url)
  666. : this(url, new NtlmPasswordAuthentication(url.GetUserInfo
  667. ()))
  668. {
  669. }
  670. /// <summary>
  671. /// Constructs an SmbFile representing a resource on an SMB network such
  672. /// as a file or directory from a <tt>URL</tt> object and an
  673. /// <tt>NtlmPasswordAuthentication</tt> object.
  674. /// </summary>
  675. /// <remarks>
  676. /// Constructs an SmbFile representing a resource on an SMB network such
  677. /// as a file or directory from a <tt>URL</tt> object and an
  678. /// <tt>NtlmPasswordAuthentication</tt> object.
  679. /// </remarks>
  680. /// <param name="url">The URL of the target resource</param>
  681. /// <param name="auth">The credentials the client should use for authentication</param>
  682. public SmbFile(Uri url, NtlmPasswordAuthentication auth)
  683. {
  684. this.Auth = auth ?? new NtlmPasswordAuthentication(url.GetUserInfo());
  685. Url = url;
  686. GetUncPath0();
  687. }
  688. /// <exception cref="System.UriFormatException"></exception>
  689. /// <exception cref="UnknownHostException"></exception>
  690. /*internal SmbFile(Jcifs.Smb.SmbFile context, string name, int type, int attributes
  691. , long createTime, long lastModified, long size)
  692. : this(context.IsWorkgroup0() ?
  693. new Uri(null, "smb://" + name + "/") : new Uri(context.url,
  694. name + ((attributes & ATTR_DIRECTORY) > 0 ? "/" : string.Empty)))*/
  695. internal SmbFile(SmbFile context, string name, int type, int attributes
  696. , long createTime, long lastModified, long size)
  697. : this(context.IsWorkgroup0() ?
  698. new Uri("smb://" + name + "/") : new Uri(context.Url.AbsoluteUri +
  699. name + ((attributes & AttrDirectory) > 0 ? "/" : string.Empty)))
  700. {
  701. Auth = context.Auth;
  702. if (context._share != null)
  703. {
  704. Tree = context.Tree;
  705. _dfsReferral = context._dfsReferral;
  706. }
  707. int last = name.Length - 1;
  708. if (name[last] == '/')
  709. {
  710. name = Runtime.Substring(name, 0, last);
  711. }
  712. if (context._share == null)
  713. {
  714. Unc = "\\";
  715. }
  716. else
  717. {
  718. if (context.Unc.Equals("\\"))
  719. {
  720. Unc = '\\' + name;
  721. }
  722. else
  723. {
  724. Unc = context.Unc + '\\' + name;
  725. }
  726. }
  727. if (!context.IsWorkgroup0())
  728. {
  729. Addresses = context.Addresses;
  730. }
  731. this._enableDfs = context.EnableDfs;
  732. this.Type = type;
  733. this._attributes = attributes;
  734. this._createTime = createTime;
  735. this._lastModified = lastModified;
  736. this._size = size;
  737. _isExists = true;
  738. _attrExpiration = _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
  739. }
  740. private SmbComBlankResponse Blank_resp()
  741. {
  742. if (_blankResp == null)
  743. {
  744. _blankResp = new SmbComBlankResponse();
  745. }
  746. return _blankResp;
  747. }
  748. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  749. internal virtual void ResolveDfs(ServerMessageBlock request)
  750. {
  751. if (!_enableDfs)
  752. {
  753. Connect0();
  754. return;
  755. }
  756. if (request is SmbComClose)
  757. {
  758. return;
  759. }
  760. Connect0();
  761. DfsReferral dr = Dfs.Resolve(Tree.Session.transport.TconHostName, Tree.Share, Unc
  762. , Auth);
  763. if (dr != null)
  764. {
  765. string service = null;
  766. if (request != null)
  767. {
  768. switch (request.Command)
  769. {
  770. case ServerMessageBlock.SmbComTransaction:
  771. case ServerMessageBlock.SmbComTransaction2:
  772. {
  773. switch (((SmbComTransaction)request).SubCommand & 0xFF)
  774. {
  775. case SmbComTransaction.Trans2GetDfsReferral:
  776. {
  777. break;
  778. }
  779. default:
  780. {
  781. service = "A:";
  782. break;
  783. }
  784. }
  785. break;
  786. }
  787. default:
  788. {
  789. service = "A:";
  790. break;
  791. }
  792. }
  793. }
  794. DfsReferral start = dr;
  795. SmbException se = null;
  796. do
  797. {
  798. try
  799. {
  800. if (Log.Level >= 2)
  801. {
  802. Log.WriteLine("DFS redirect: " + dr);
  803. }
  804. UniAddress addr = UniAddress.GetByName(dr.Server);
  805. SmbTransport trans = SmbTransport.GetSmbTransport(addr, Url.Port);
  806. trans.Connect();
  807. Tree = trans.GetSmbSession(Auth).GetSmbTree(dr.Share, service);
  808. if (dr != start && dr.Key != null)
  809. {
  810. dr.Map.Put(dr.Key, dr);
  811. }
  812. se = null;
  813. break;
  814. }
  815. catch (IOException ioe)
  816. {
  817. if (ioe is SmbException)
  818. {
  819. se = (SmbException)ioe;
  820. }
  821. else
  822. {
  823. se = new SmbException(dr.Server, ioe);
  824. }
  825. }
  826. dr = dr.Next;
  827. }
  828. while (dr != start);
  829. if (se != null)
  830. {
  831. throw se;
  832. }
  833. if (Log.Level >= 3)
  834. {
  835. Log.WriteLine(dr);
  836. }
  837. _dfsReferral = dr;
  838. if (dr.PathConsumed < 0)
  839. {
  840. dr.PathConsumed = 0;
  841. }
  842. else
  843. {
  844. if (dr.PathConsumed > Unc.Length)
  845. {
  846. dr.PathConsumed = Unc.Length;
  847. }
  848. }
  849. string dunc = Runtime.Substring(Unc, dr.PathConsumed);
  850. if (dunc.Equals(string.Empty))
  851. {
  852. dunc = "\\";
  853. }
  854. if (!dr.Path.Equals(string.Empty))
  855. {
  856. dunc = "\\" + dr.Path + dunc;
  857. }
  858. Unc = dunc;
  859. if (request != null && request.Path != null && request.Path.EndsWith("\\") && dunc
  860. .EndsWith("\\") == false)
  861. {
  862. dunc += "\\";
  863. }
  864. if (request != null)
  865. {
  866. request.Path = dunc;
  867. request.Flags2 |= SmbConstants.Flags2ResolvePathsInDfs;
  868. }
  869. }
  870. else
  871. {
  872. if (Tree.InDomainDfs && !(request is NtTransQuerySecurityDesc) && !(request is SmbComClose
  873. ) && !(request is SmbComFindClose2))
  874. {
  875. throw new SmbException(NtStatus.NtStatusNotFound, false);
  876. }
  877. if (request != null)
  878. {
  879. request.Flags2 &= ~SmbConstants.Flags2ResolvePathsInDfs;
  880. }
  881. }
  882. }
  883. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  884. internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
  885. )
  886. {
  887. for (; ; )
  888. {
  889. ResolveDfs(request);
  890. try
  891. {
  892. Tree.Send(request, response);
  893. break;
  894. }
  895. catch (DfsReferral dre)
  896. {
  897. if (dre.ResolveHashes)
  898. {
  899. throw;
  900. }
  901. request.Reset();
  902. }
  903. }
  904. }
  905. internal static string QueryLookup(string query, string param)
  906. {
  907. char[] instr = query.ToCharArray();
  908. int i;
  909. int ch;
  910. int st;
  911. int eq;
  912. st = eq = 0;
  913. for (i = 0; i < instr.Length; i++)
  914. {
  915. ch = instr[i];
  916. if (ch == '&')
  917. {
  918. if (eq > st)
  919. {
  920. string p = new string(instr, st, eq - st);
  921. if (Runtime.EqualsIgnoreCase(p, param))
  922. {
  923. eq++;
  924. return new string(instr, eq, i - eq);
  925. }
  926. }
  927. st = i + 1;
  928. }
  929. else
  930. {
  931. if (ch == '=')
  932. {
  933. eq = i;
  934. }
  935. }
  936. }
  937. if (eq > st)
  938. {
  939. string p = new string(instr, st, eq - st);
  940. if (Runtime.EqualsIgnoreCase(p, param))
  941. {
  942. eq++;
  943. return new string(instr, eq, instr.Length - eq);
  944. }
  945. }
  946. return null;
  947. }
  948. internal UniAddress[] Addresses;
  949. internal int AddressIndex;
  950. /// <exception cref="UnknownHostException"></exception>
  951. internal virtual UniAddress GetAddress()
  952. {
  953. if (AddressIndex == 0)
  954. {
  955. return GetFirstAddress();
  956. }
  957. return Addresses[AddressIndex - 1];
  958. }
  959. /// <exception cref="UnknownHostException"></exception>
  960. internal virtual UniAddress GetFirstAddress()
  961. {
  962. AddressIndex = 0;
  963. string host = Url.GetHost();
  964. string path = Url.AbsolutePath;
  965. string query = Url.GetQuery();
  966. if (Addresses != null && Addresses.Length > 0)
  967. {
  968. return GetNextAddress();
  969. }
  970. if (query != null)
  971. {
  972. string server = QueryLookup(query, "server");
  973. if (!string.IsNullOrEmpty(server))
  974. {
  975. Addresses = new UniAddress[1];
  976. Addresses[0] = UniAddress.GetByName(server);
  977. return GetNextAddress();
  978. }
  979. string address = QueryLookup(query, "address");
  980. if (!string.IsNullOrEmpty(address))
  981. {
  982. byte[] ip = Extensions.GetAddressByName(address).GetAddressBytes();
  983. Addresses = new UniAddress[1];
  984. //addresses[0] = new UniAddress(IPAddress.Parse(host, ip));
  985. Addresses[0] = new UniAddress(IPAddress.Parse(host));
  986. return GetNextAddress();
  987. }
  988. }
  989. if (host.Length == 0)
  990. {
  991. try
  992. {
  993. NbtAddress addr = NbtAddress.GetByName(NbtAddress.MasterBrowserName, 0x01, null);
  994. Addresses = new UniAddress[1];
  995. Addresses[0] = UniAddress.GetByName(addr.GetHostAddress());
  996. }
  997. catch (UnknownHostException uhe)
  998. {
  999. NtlmPasswordAuthentication.InitDefaults();
  1000. if (NtlmPasswordAuthentication.DefaultDomain.Equals("?"))
  1001. {
  1002. throw;
  1003. }
  1004. Addresses = UniAddress.GetAllByName(NtlmPasswordAuthentication.DefaultDomain, true
  1005. );
  1006. }
  1007. }
  1008. else
  1009. {
  1010. if (path.Length == 0 || path.Equals("/"))
  1011. {
  1012. Addresses = UniAddress.GetAllByName(host, true);
  1013. }
  1014. else
  1015. {
  1016. Addresses = UniAddress.GetAllByName(host, false);
  1017. }
  1018. }
  1019. return GetNextAddress();
  1020. }
  1021. internal virtual UniAddress GetNextAddress()
  1022. {
  1023. UniAddress addr = null;
  1024. if (AddressIndex < Addresses.Length)
  1025. {
  1026. addr = Addresses[AddressIndex++];
  1027. }
  1028. return addr;
  1029. }
  1030. internal virtual bool HasNextAddress()
  1031. {
  1032. return AddressIndex < Addresses.Length;
  1033. }
  1034. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1035. internal virtual void Connect0()
  1036. {
  1037. try
  1038. {
  1039. Connect();
  1040. }
  1041. catch (UnknownHostException uhe)
  1042. {
  1043. throw new SmbException("Failed to connect to server", uhe);
  1044. }
  1045. catch (SmbException se)
  1046. {
  1047. throw;
  1048. }
  1049. catch (IOException ioe)
  1050. {
  1051. throw new SmbException("Failed to connect to server", ioe);
  1052. }
  1053. }
  1054. /// <exception cref="System.IO.IOException"></exception>
  1055. internal virtual void DoConnect()
  1056. {
  1057. SmbTransport trans;
  1058. UniAddress addr;
  1059. addr = GetAddress();
  1060. if (Tree != null && Tree.Session.transport.Address.Equals(addr))
  1061. {
  1062. trans = Tree.Session.transport;
  1063. }
  1064. else
  1065. {
  1066. trans = SmbTransport.GetSmbTransport(addr, Url.Port);
  1067. Tree = trans.GetSmbSession(Auth).GetSmbTree(_share, null);
  1068. }
  1069. string hostName = GetServerWithDfs();
  1070. if (_enableDfs)
  1071. {
  1072. Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null;
  1073. }
  1074. if (Tree.InDomainDfs)
  1075. {
  1076. Tree.ConnectionState = 2;
  1077. }
  1078. try
  1079. {
  1080. if (Log.Level >= 3)
  1081. {
  1082. Log.WriteLine("doConnect: " + addr);
  1083. }
  1084. Tree.TreeConnect(null, null);
  1085. }
  1086. catch (SmbAuthException sae)
  1087. {
  1088. NtlmPasswordAuthentication a;
  1089. SmbSession ssn;
  1090. if (_share == null)
  1091. {
  1092. // IPC$ - try "anonymous" credentials
  1093. ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Null);
  1094. Tree = ssn.GetSmbTree(null, null);
  1095. Tree.TreeConnect(null, null);
  1096. }
  1097. else
  1098. {
  1099. if ((a = NtlmAuthenticator.RequestNtlmPasswordAuthentication(Url.ToString(), sae)
  1100. ) != null)
  1101. {
  1102. Auth = a;
  1103. ssn = trans.GetSmbSession(Auth);
  1104. Tree = ssn.GetSmbTree(_share, null);
  1105. Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null;
  1106. if (Tree.InDomainDfs)
  1107. {
  1108. Tree.ConnectionState = 2;
  1109. }
  1110. Tree.TreeConnect(null, null);
  1111. }
  1112. else
  1113. {
  1114. if (Log.Level >= 1 && HasNextAddress())
  1115. {
  1116. Runtime.PrintStackTrace(sae, Log);
  1117. }
  1118. throw;
  1119. }
  1120. }
  1121. }
  1122. }
  1123. /// <summary>It is not necessary to call this method directly.</summary>
  1124. /// <remarks>
  1125. /// It is not necessary to call this method directly. This is the
  1126. /// <tt>URLConnection</tt> implementation of <tt>connect()</tt>.
  1127. /// </remarks>
  1128. /// <exception cref="System.IO.IOException"></exception>
  1129. public void Connect()
  1130. {
  1131. SmbTransport trans;
  1132. SmbSession ssn;
  1133. UniAddress addr;
  1134. if (IsConnected())
  1135. {
  1136. return;
  1137. }
  1138. GetUncPath0();
  1139. GetFirstAddress();
  1140. for (; ; )
  1141. {
  1142. try
  1143. {
  1144. DoConnect();
  1145. return;
  1146. }
  1147. catch (SmbAuthException sae)
  1148. {
  1149. throw;
  1150. }
  1151. catch (SmbException se)
  1152. {
  1153. // Prevents account lockout on servers with multiple IPs
  1154. if (GetNextAddress() == null)
  1155. {
  1156. throw;
  1157. }
  1158. else
  1159. {
  1160. RemoveCurrentAddress();
  1161. }
  1162. if (Log.Level >= 3)
  1163. {
  1164. Runtime.PrintStackTrace(se, Log);
  1165. }
  1166. }
  1167. }
  1168. }
  1169. internal virtual bool IsConnected()
  1170. {
  1171. return Tree != null && Tree.ConnectionState == 2;
  1172. }
  1173. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1174. internal virtual int Open0(int flags, int access, int attrs, int options)
  1175. {
  1176. int f;
  1177. Connect0();
  1178. if (Log.Level >= 3)
  1179. {
  1180. Log.WriteLine("open0: " + Unc);
  1181. }
  1182. if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs))
  1183. {
  1184. SmbComNtCreateAndXResponse response = new SmbComNtCreateAndXResponse();
  1185. SmbComNtCreateAndX request = new SmbComNtCreateAndX(Unc, flags, access, _shareAccess
  1186. , attrs, options, null);
  1187. if (this is SmbNamedPipe)
  1188. {
  1189. request.Flags0 |= 0x16;
  1190. request.DesiredAccess |= 0x20000;
  1191. response.IsExtended = true;
  1192. }
  1193. Send(request, response);
  1194. f = response.Fid;
  1195. _attributes = response.ExtFileAttributes & AttrGetMask;
  1196. _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
  1197. _isExists = true;
  1198. }
  1199. else
  1200. {
  1201. SmbComOpenAndXResponse response = new SmbComOpenAndXResponse();
  1202. Send(new SmbComOpenAndX(Unc, access, flags, null), response);
  1203. f = response.Fid;
  1204. }
  1205. return f;
  1206. }
  1207. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1208. internal virtual void Open(int flags, int access, int attrs, int options)
  1209. {
  1210. if (IsOpen())
  1211. {
  1212. return;
  1213. }
  1214. Fid = Open0(flags, access, attrs, options);
  1215. Opened = true;
  1216. TreeNum = Tree.TreeNum;
  1217. }
  1218. internal virtual bool IsOpen()
  1219. {
  1220. bool ans = Opened && IsConnected() && TreeNum == Tree.TreeNum;
  1221. return ans;
  1222. }
  1223. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1224. internal virtual void Close(int f, long lastWriteTime)
  1225. {
  1226. if (Log.Level >= 3)
  1227. {
  1228. Log.WriteLine("close: " + f);
  1229. }
  1230. Send(new SmbComClose(f, lastWriteTime), Blank_resp());
  1231. }
  1232. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1233. internal virtual void Close(long lastWriteTime)
  1234. {
  1235. if (IsOpen() == false)
  1236. {
  1237. return;
  1238. }
  1239. Close(Fid, lastWriteTime);
  1240. Opened = false;
  1241. }
  1242. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1243. internal virtual void Close()
  1244. {
  1245. Close(0L);
  1246. }
  1247. /// <summary>
  1248. /// Returns the <tt>NtlmPasswordAuthentication</tt> object used as
  1249. /// credentials with this file or pipe.
  1250. /// </summary>
  1251. /// <remarks>
  1252. /// Returns the <tt>NtlmPasswordAuthentication</tt> object used as
  1253. /// credentials with this file or pipe. This can be used to retrieve the
  1254. /// username for example:
  1255. /// <tt>
  1256. /// String username = f.getPrincipal().getName();
  1257. /// </tt>
  1258. /// The <tt>Principal</tt> object returned will never be <tt>null</tt>
  1259. /// however the username can be <tt>null</tt> indication anonymous
  1260. /// credentials were used (e.g. some IPC$ services).
  1261. /// </remarks>
  1262. public virtual Principal GetPrincipal()
  1263. {
  1264. return Auth;
  1265. }
  1266. /// <summary>Returns the last component of the target URL.</summary>
  1267. /// <remarks>
  1268. /// Returns the last component of the target URL. This will
  1269. /// effectively be the name of the file or directory represented by this
  1270. /// <code>SmbFile</code> or in the case of URLs that only specify a server
  1271. /// or workgroup, the server or workgroup will be returned. The name of
  1272. /// the root URL <code>smb://</code> is also <code>smb://</code>. If this
  1273. /// <tt>SmbFile</tt> refers to a workgroup, server, share, or directory,
  1274. /// the name will include a trailing slash '/' so that composing new
  1275. /// <tt>SmbFile</tt>s will maintain the trailing slash requirement.
  1276. /// </remarks>
  1277. /// <returns>
  1278. /// The last component of the URL associated with this SMB
  1279. /// resource or <code>smb://</code> if the resource is <code>smb://</code>
  1280. /// itself.
  1281. /// </returns>
  1282. public virtual string GetName()
  1283. {
  1284. GetUncPath0();
  1285. if (_canon.Length > 1)
  1286. {
  1287. int i = _canon.Length - 2;
  1288. while (_canon[i] != '/')
  1289. {
  1290. i--;
  1291. }
  1292. return Runtime.Substring(_canon, i + 1);
  1293. }
  1294. if (_share != null)
  1295. {
  1296. return _share + '/';
  1297. }
  1298. if (Url.GetHost().Length > 0)
  1299. {
  1300. return Url.GetHost() + '/';
  1301. }
  1302. return "smb://";
  1303. }
  1304. /// <summary>
  1305. /// Everything but the last component of the URL representing this SMB
  1306. /// resource is effectivly it's parent.
  1307. /// </summary>
  1308. /// <remarks>
  1309. /// Everything but the last component of the URL representing this SMB
  1310. /// resource is effectivly it's parent. The root URL <code>smb://</code>
  1311. /// does not have a parent. In this case <code>smb://</code> is returned.
  1312. /// </remarks>
  1313. /// <returns>
  1314. /// The parent directory of this SMB resource or
  1315. /// <code>smb://</code> if the resource refers to the root of the URL
  1316. /// hierarchy which incedentally is also <code>smb://</code>.
  1317. /// </returns>
  1318. public virtual string GetParent()
  1319. {
  1320. string str = Url.Authority;
  1321. if (str.Length > 0)
  1322. {
  1323. StringBuilder sb = new StringBuilder("smb://");
  1324. sb.Append(str);
  1325. GetUncPath0();
  1326. if (_canon.Length > 1)
  1327. {
  1328. sb.Append(_canon);
  1329. }
  1330. else
  1331. {
  1332. sb.Append('/');
  1333. }
  1334. str = sb.ToString();
  1335. int i = str.Length - 2;
  1336. while (str[i] != '/')
  1337. {
  1338. i--;
  1339. }
  1340. return Runtime.Substring(str, 0, i + 1);
  1341. }
  1342. return "smb://";
  1343. }
  1344. /// <summary>Returns the full uncanonicalized URL of this SMB resource.</summary>
  1345. /// <remarks>
  1346. /// Returns the full uncanonicalized URL of this SMB resource. An
  1347. /// <code>SmbFile</code> constructed with the result of this method will
  1348. /// result in an <code>SmbFile</code> that is equal to the original.
  1349. /// </remarks>
  1350. /// <returns>The uncanonicalized full URL of this SMB resource.</returns>
  1351. public virtual string GetPath()
  1352. {
  1353. return Url.ToString();
  1354. }
  1355. internal virtual string GetUncPath0()
  1356. {
  1357. if (Unc == null)
  1358. {
  1359. char[] instr = Url.LocalPath.ToCharArray();
  1360. char[] outstr = new char[instr.Length];
  1361. int length = instr.Length;
  1362. int i;
  1363. int o;
  1364. int state;
  1365. state = 0;
  1366. o = 0;
  1367. for (i = 0; i < length; i++)
  1368. {
  1369. switch (state)
  1370. {
  1371. case 0:
  1372. {
  1373. if (instr[i] != '/')
  1374. {
  1375. return null;
  1376. }
  1377. outstr[o++] = instr[i];
  1378. state = 1;
  1379. break;
  1380. }
  1381. case 1:
  1382. {
  1383. if (instr[i] == '/')
  1384. {
  1385. break;
  1386. }
  1387. if (instr[i] == '.' && ((i + 1) >= length || instr[i + 1] == '/'))
  1388. {
  1389. i++;
  1390. break;
  1391. }
  1392. if ((i + 1) < length && instr[i] == '.' && instr[i + 1] == '.' && ((i + 2) >= length
  1393. || instr[i + 2] == '/'))
  1394. {
  1395. i += 2;
  1396. if (o == 1)
  1397. {
  1398. break;
  1399. }
  1400. do
  1401. {
  1402. o--;
  1403. }
  1404. while (o > 1 && outstr[o - 1] != '/');
  1405. break;
  1406. }
  1407. state = 2;
  1408. goto case 2;
  1409. }
  1410. case 2:
  1411. {
  1412. if (instr[i] == '/')
  1413. {
  1414. state = 1;
  1415. }
  1416. outstr[o++] = instr[i];
  1417. break;
  1418. }
  1419. }
  1420. }
  1421. _canon = new string(outstr, 0, o);
  1422. if (o > 1)
  1423. {
  1424. o--;
  1425. i = _canon.IndexOf('/', 1);
  1426. if (i < 0)
  1427. {
  1428. _share = Runtime.Substring(_canon, 1);
  1429. Unc = "\\";
  1430. }
  1431. else
  1432. {
  1433. if (i == o)
  1434. {
  1435. _share = Runtime.Substring(_canon, 1, i);
  1436. Unc = "\\";
  1437. }
  1438. else
  1439. {
  1440. _share = Runtime.Substring(_canon, 1, i);
  1441. Unc = Runtime.Substring(_canon, i, outstr[o] == '/' ? o : o + 1);
  1442. Unc = Unc.Replace('/', '\\');
  1443. }
  1444. }
  1445. }
  1446. else
  1447. {
  1448. _share = null;
  1449. Unc = "\\";
  1450. }
  1451. }
  1452. return Unc;
  1453. }
  1454. /// <summary>Retuns the Windows UNC style path with backslashs intead of forward slashes.
  1455. /// </summary>
  1456. /// <remarks>Retuns the Windows UNC style path with backslashs intead of forward slashes.
  1457. /// </remarks>
  1458. /// <returns>The UNC path.</returns>
  1459. public virtual string GetUncPath()
  1460. {
  1461. GetUncPath0();
  1462. if (_share == null)
  1463. {
  1464. return "\\\\" + Url.GetHost();
  1465. }
  1466. return "\\\\" + Url.GetHost() + _canon.Replace('/', '\\');
  1467. }
  1468. /// <summary>
  1469. /// Returns the full URL of this SMB resource with '.' and '..' components
  1470. /// factored out.
  1471. /// </summary>
  1472. /// <remarks>
  1473. /// Returns the full URL of this SMB resource with '.' and '..' components
  1474. /// factored out. An <code>SmbFile</code> constructed with the result of
  1475. /// this method will result in an <code>SmbFile</code> that is equal to
  1476. /// the original.
  1477. /// </remarks>
  1478. /// <returns>The canonicalized URL of this SMB resource.</returns>
  1479. public virtual string GetCanonicalPath()
  1480. {
  1481. string str = Url.Authority;
  1482. GetUncPath0();
  1483. if (str.Length > 0)
  1484. {
  1485. return "smb://" + Url.Authority + _canon;
  1486. }
  1487. return "smb://";
  1488. }
  1489. /// <summary>Retrieves the share associated with this SMB resource.</summary>
  1490. /// <remarks>
  1491. /// Retrieves the share associated with this SMB resource. In
  1492. /// the case of <code>smb://</code>, <code>smb://workgroup/</code>,
  1493. /// and <code>smb://server/</code> URLs which do not specify a share,
  1494. /// <code>null</code> will be returned.
  1495. /// </remarks>
  1496. /// <returns>The share component or <code>null</code> if there is no share</returns>
  1497. public virtual string GetShare()
  1498. {
  1499. return _share;
  1500. }
  1501. internal virtual string GetServerWithDfs()
  1502. {
  1503. if (_dfsReferral != null)
  1504. {
  1505. return _dfsReferral.Server;
  1506. }
  1507. return GetServer();
  1508. }
  1509. /// <summary>Retrieve the hostname of the server for this SMB resource.</summary>
  1510. /// <remarks>
  1511. /// Retrieve the hostname of the server for this SMB resource. If this
  1512. /// <code>SmbFile</code> references a workgroup, the name of the workgroup
  1513. /// is returned. If this <code>SmbFile</code> refers to the root of this
  1514. /// SMB network hierarchy, <code>null</code> is returned.
  1515. /// </remarks>
  1516. /// <returns>
  1517. /// The server or workgroup name or <code>null</code> if this
  1518. /// <code>SmbFile</code> refers to the root <code>smb://</code> resource.
  1519. /// </returns>
  1520. public virtual string GetServer()
  1521. {
  1522. string str = Url.GetHost();
  1523. if (str.Length == 0)
  1524. {
  1525. return null;
  1526. }
  1527. return str;
  1528. }
  1529. /// <summary>Returns type of of object this <tt>SmbFile</tt> represents.</summary>
  1530. /// <remarks>Returns type of of object this <tt>SmbFile</tt> represents.</remarks>
  1531. /// <returns>
  1532. /// <tt>TYPE_FILESYSTEM, TYPE_WORKGROUP, TYPE_SERVER, TYPE_SHARE,
  1533. /// TYPE_PRINTER, TYPE_NAMED_PIPE</tt>, or <tt>TYPE_COMM</tt>.
  1534. /// </returns>
  1535. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1536. public new virtual int GetType()
  1537. {
  1538. if (Type == 0)
  1539. {
  1540. if (GetUncPath0().Length > 1)
  1541. {
  1542. Type = TypeFilesystem;
  1543. }
  1544. else
  1545. {
  1546. if (_share != null)
  1547. {
  1548. // treeConnect good enough to test service type
  1549. Connect0();
  1550. if (_share.Equals("IPC$"))
  1551. {
  1552. Type = TypeNamedPipe;
  1553. }
  1554. else
  1555. {
  1556. if (Tree.Service.Equals("LPT1:"))
  1557. {
  1558. Type = TypePrinter;
  1559. }
  1560. else
  1561. {
  1562. if (Tree.Service.Equals("COMM"))
  1563. {
  1564. Type = TypeComm;
  1565. }
  1566. else
  1567. {
  1568. Type = TypeShare;
  1569. }
  1570. }
  1571. }
  1572. }
  1573. else
  1574. {
  1575. if (string.IsNullOrEmpty(Url.Authority))
  1576. {
  1577. Type = TypeWorkgroup;
  1578. }
  1579. else
  1580. {
  1581. UniAddress addr;
  1582. try
  1583. {
  1584. addr = GetAddress();
  1585. }
  1586. catch (UnknownHostException uhe)
  1587. {
  1588. throw new SmbException(Url.ToString(), uhe);
  1589. }
  1590. if (addr.GetAddress() is NbtAddress)
  1591. {
  1592. int code = ((NbtAddress)addr.GetAddress()).GetNameType();
  1593. if (code == 0x1d || code == 0x1b)
  1594. {
  1595. Type = TypeWorkgroup;
  1596. return Type;
  1597. }
  1598. }
  1599. Type = TypeServer;
  1600. }
  1601. }
  1602. }
  1603. }
  1604. return Type;
  1605. }
  1606. /// <exception cref="UnknownHostException"></exception>
  1607. internal virtual bool IsWorkgroup0()
  1608. {
  1609. if (Type == TypeWorkgroup || Url.GetHost().Length == 0)
  1610. {
  1611. Type = TypeWorkgroup;
  1612. return true;
  1613. }
  1614. GetUncPath0();
  1615. if (_share == null)
  1616. {
  1617. UniAddress addr = GetAddress();
  1618. if (addr.GetAddress() is NbtAddress)
  1619. {
  1620. int code = ((NbtAddress)addr.GetAddress()).GetNameType();
  1621. if (code == 0x1d || code == 0x1b)
  1622. {
  1623. Type = TypeWorkgroup;
  1624. return true;
  1625. }
  1626. }
  1627. Type = TypeServer;
  1628. }
  1629. return false;
  1630. }
  1631. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1632. internal virtual IInfo QueryPath(string path, int infoLevel)
  1633. {
  1634. Connect0();
  1635. if (Log.Level >= 3)
  1636. {
  1637. Log.WriteLine("queryPath: " + path);
  1638. }
  1639. if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs))
  1640. {
  1641. Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse
  1642. (infoLevel);
  1643. Send(new Trans2QueryPathInformation(path, infoLevel), response);
  1644. return response.Info;
  1645. }
  1646. else
  1647. {
  1648. SmbComQueryInformationResponse response = new SmbComQueryInformationResponse(Tree
  1649. .Session.transport.Server.ServerTimeZone * 1000 * 60L);
  1650. Send(new SmbComQueryInformation(path), response);
  1651. return response;
  1652. }
  1653. }
  1654. /// <summary>Tests to see if the SMB resource exists.</summary>
  1655. /// <remarks>
  1656. /// Tests to see if the SMB resource exists. If the resource refers
  1657. /// only to a server, this method determines if the server exists on the
  1658. /// network and is advertising SMB services. If this resource refers to
  1659. /// a workgroup, this method determines if the workgroup name is valid on
  1660. /// the local SMB network. If this <code>SmbFile</code> refers to the root
  1661. /// <code>smb://</code> resource <code>true</code> is always returned. If
  1662. /// this <code>SmbFile</code> is a traditional file or directory, it will
  1663. /// be queried for on the specified server as expected.
  1664. /// </remarks>
  1665. /// <returns>
  1666. /// <code>true</code> if the resource exists or is alive or
  1667. /// <code>false</code> otherwise
  1668. /// </returns>
  1669. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1670. public virtual bool Exists()
  1671. {
  1672. if (_attrExpiration > Runtime.CurrentTimeMillis())
  1673. {
  1674. return _isExists;
  1675. }
  1676. _attributes = AttrReadonly | AttrDirectory;
  1677. _createTime = 0L;
  1678. _lastModified = 0L;
  1679. _isExists = false;
  1680. try
  1681. {
  1682. if (Url.GetHost().Length == 0)
  1683. {
  1684. }
  1685. else
  1686. {
  1687. if (_share == null)
  1688. {
  1689. if (GetType() == TypeWorkgroup)
  1690. {
  1691. UniAddress.GetByName(Url.GetHost(), true);
  1692. }
  1693. else
  1694. {
  1695. UniAddress.GetByName(Url.GetHost()).GetHostName();
  1696. }
  1697. }
  1698. else
  1699. {
  1700. if (GetUncPath0().Length == 1 || Runtime.EqualsIgnoreCase(_share, "IPC$"))
  1701. {
  1702. Connect0();
  1703. }
  1704. else
  1705. {
  1706. // treeConnect is good enough
  1707. IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
  1708. );
  1709. _attributes = info.GetAttributes();
  1710. _createTime = info.GetCreateTime();
  1711. _lastModified = info.GetLastWriteTime();
  1712. }
  1713. }
  1714. }
  1715. _isExists = true;
  1716. }
  1717. catch (UnknownHostException)
  1718. {
  1719. }
  1720. catch (SmbException se)
  1721. {
  1722. switch (se.GetNtStatus())
  1723. {
  1724. case NtStatus.NtStatusNoSuchFile:
  1725. case NtStatus.NtStatusObjectNameInvalid:
  1726. case NtStatus.NtStatusObjectNameNotFound:
  1727. case NtStatus.NtStatusObjectPathNotFound:
  1728. {
  1729. break;
  1730. }
  1731. default:
  1732. {
  1733. throw;
  1734. }
  1735. }
  1736. }
  1737. _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
  1738. return _isExists;
  1739. }
  1740. /// <summary>
  1741. /// Tests to see if the file this <code>SmbFile</code> represents can be
  1742. /// read.
  1743. /// </summary>
  1744. /// <remarks>
  1745. /// Tests to see if the file this <code>SmbFile</code> represents can be
  1746. /// read. Because any file, directory, or other resource can be read if it
  1747. /// exists, this method simply calls the <code>exists</code> method.
  1748. /// </remarks>
  1749. /// <returns><code>true</code> if the file is read-only</returns>
  1750. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1751. public virtual bool CanRead()
  1752. {
  1753. if (GetType() == TypeNamedPipe)
  1754. {
  1755. // try opening the pipe for reading?
  1756. return true;
  1757. }
  1758. return Exists();
  1759. }
  1760. // try opening and catch sharing violation?
  1761. /// <summary>
  1762. /// Tests to see if the file this <code>SmbFile</code> represents
  1763. /// exists and is not marked read-only.
  1764. /// </summary>
  1765. /// <remarks>
  1766. /// Tests to see if the file this <code>SmbFile</code> represents
  1767. /// exists and is not marked read-only. By default, resources are
  1768. /// considered to be read-only and therefore for <code>smb://</code>,
  1769. /// <code>smb://workgroup/</code>, and <code>smb://server/</code> resources
  1770. /// will be read-only.
  1771. /// </remarks>
  1772. /// <returns>
  1773. /// <code>true</code> if the resource exists is not marked
  1774. /// read-only
  1775. /// </returns>
  1776. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1777. public virtual bool CanWrite()
  1778. {
  1779. if (GetType() == TypeNamedPipe)
  1780. {
  1781. // try opening the pipe for writing?
  1782. return true;
  1783. }
  1784. return Exists() && (_attributes & AttrReadonly) == 0;
  1785. }
  1786. /// <summary>Tests to see if the file this <code>SmbFile</code> represents is a directory.
  1787. /// </summary>
  1788. /// <remarks>Tests to see if the file this <code>SmbFile</code> represents is a directory.
  1789. /// </remarks>
  1790. /// <returns><code>true</code> if this <code>SmbFile</code> is a directory</returns>
  1791. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1792. public virtual bool IsDirectory()
  1793. {
  1794. if (GetUncPath0().Length == 1)
  1795. {
  1796. return true;
  1797. }
  1798. if (!Exists())
  1799. {
  1800. return false;
  1801. }
  1802. return (_attributes & AttrDirectory) == AttrDirectory;
  1803. }
  1804. /// <summary>Tests to see if the file this <code>SmbFile</code> represents is not a directory.
  1805. /// </summary>
  1806. /// <remarks>Tests to see if the file this <code>SmbFile</code> represents is not a directory.
  1807. /// </remarks>
  1808. /// <returns><code>true</code> if this <code>SmbFile</code> is not a directory</returns>
  1809. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1810. public virtual bool IsFile()
  1811. {
  1812. if (GetUncPath0().Length == 1)
  1813. {
  1814. return false;
  1815. }
  1816. Exists();
  1817. return (_attributes & AttrDirectory) == 0;
  1818. }
  1819. /// <summary>
  1820. /// Tests to see if the file this SmbFile represents is marked as
  1821. /// hidden.
  1822. /// </summary>
  1823. /// <remarks>
  1824. /// Tests to see if the file this SmbFile represents is marked as
  1825. /// hidden. This method will also return true for shares with names that
  1826. /// end with '$' such as <code>IPC$</code> or <code>C$</code>.
  1827. /// </remarks>
  1828. /// <returns><code>true</code> if the <code>SmbFile</code> is marked as being hidden</returns>
  1829. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1830. public virtual bool IsHidden()
  1831. {
  1832. if (_share == null)
  1833. {
  1834. return false;
  1835. }
  1836. if (GetUncPath0().Length == 1)
  1837. {
  1838. if (_share.EndsWith("$"))
  1839. {
  1840. return true;
  1841. }
  1842. return false;
  1843. }
  1844. Exists();
  1845. return (_attributes & AttrHidden) == AttrHidden;
  1846. }
  1847. /// <summary>
  1848. /// If the path of this <code>SmbFile</code> falls within a DFS volume,
  1849. /// this method will return the referral path to which it maps.
  1850. /// </summary>
  1851. /// <remarks>
  1852. /// If the path of this <code>SmbFile</code> falls within a DFS volume,
  1853. /// this method will return the referral path to which it maps. Otherwise
  1854. /// <code>null</code> is returned.
  1855. /// </remarks>
  1856. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1857. public virtual string GetDfsPath()
  1858. {
  1859. ResolveDfs(null);
  1860. if (_dfsReferral == null)
  1861. {
  1862. return null;
  1863. }
  1864. string path = "smb:/" + _dfsReferral.Server + "/" + _dfsReferral.Share + Unc;
  1865. path = path.Replace('\\', '/');
  1866. if (IsDirectory())
  1867. {
  1868. path += '/';
  1869. }
  1870. return path;
  1871. }
  1872. /// <summary>Retrieve the time this <code>SmbFile</code> was created.</summary>
  1873. /// <remarks>
  1874. /// Retrieve the time this <code>SmbFile</code> was created. The value
  1875. /// returned is suitable for constructing a
  1876. /// <see cref="System.DateTime">System.DateTime</see>
  1877. /// object
  1878. /// (i.e. seconds since Epoch 1970). Times should be the same as those
  1879. /// reported using the properties dialog of the Windows Explorer program.
  1880. /// For Win95/98/Me this is actually the last write time. It is currently
  1881. /// not possible to retrieve the create time from files on these systems.
  1882. /// </remarks>
  1883. /// <returns>
  1884. /// The number of milliseconds since the 00:00:00 GMT, January 1,
  1885. /// 1970 as a <code>long</code> value
  1886. /// </returns>
  1887. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1888. public virtual long CreateTime()
  1889. {
  1890. if (GetUncPath0().Length > 1)
  1891. {
  1892. Exists();
  1893. return _createTime;
  1894. }
  1895. return 0L;
  1896. }
  1897. /// <summary>
  1898. /// Retrieve the last time the file represented by this
  1899. /// <code>SmbFile</code> was modified.
  1900. /// </summary>
  1901. /// <remarks>
  1902. /// Retrieve the last time the file represented by this
  1903. /// <code>SmbFile</code> was modified. The value returned is suitable for
  1904. /// constructing a
  1905. /// <see cref="System.DateTime">System.DateTime</see>
  1906. /// object (i.e. seconds since Epoch
  1907. /// 1970). Times should be the same as those reported using the properties
  1908. /// dialog of the Windows Explorer program.
  1909. /// </remarks>
  1910. /// <returns>
  1911. /// The number of milliseconds since the 00:00:00 GMT, January 1,
  1912. /// 1970 as a <code>long</code> value
  1913. /// </returns>
  1914. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1915. public virtual long LastModified()
  1916. {
  1917. if (GetUncPath0().Length > 1)
  1918. {
  1919. Exists();
  1920. return _lastModified;
  1921. }
  1922. return 0L;
  1923. }
  1924. /// <summary>List the contents of this SMB resource.</summary>
  1925. /// <remarks>
  1926. /// List the contents of this SMB resource. The list returned by this
  1927. /// method will be;
  1928. /// <ul>
  1929. /// <li> files and directories contained within this resource if the
  1930. /// resource is a normal disk file directory,
  1931. /// <li> all available NetBIOS workgroups or domains if this resource is
  1932. /// the top level URL <code>smb://</code>,
  1933. /// <li> all servers registered as members of a NetBIOS workgroup if this
  1934. /// resource refers to a workgroup in a <code>smb://workgroup/</code> URL,
  1935. /// <li> all browseable shares of a server including printers, IPC
  1936. /// services, or disk volumes if this resource is a server URL in the form
  1937. /// <code>smb://server/</code>,
  1938. /// <li> or <code>null</code> if the resource cannot be resolved.
  1939. /// </ul>
  1940. /// </remarks>
  1941. /// <returns>
  1942. /// A <code>String[]</code> array of files and directories,
  1943. /// workgroups, servers, or shares depending on the context of the
  1944. /// resource URL
  1945. /// </returns>
  1946. /// <exception cref="SmbException"></exception>
  1947. public virtual string[] List()
  1948. {
  1949. return List("*", AttrDirectory | AttrHidden | AttrSystem, null, null);
  1950. }
  1951. /// <summary>List the contents of this SMB resource.</summary>
  1952. /// <remarks>
  1953. /// List the contents of this SMB resource. The list returned will be
  1954. /// identical to the list returned by the parameterless <code>list()</code>
  1955. /// method minus filenames filtered by the specified filter.
  1956. /// </remarks>
  1957. /// <param name="filter">a filename filter to exclude filenames from the results</param>
  1958. /// <exception cref="SmbException"># @return An array of filenames</exception>
  1959. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  1960. public virtual string[] List(ISmbFilenameFilter filter)
  1961. {
  1962. return List("*", AttrDirectory | AttrHidden | AttrSystem, filter, null);
  1963. }
  1964. /// <summary>
  1965. /// List the contents of this SMB resource as an array of
  1966. /// <code>SmbFile</code> objects.
  1967. /// </summary>
  1968. /// <remarks>
  1969. /// List the contents of this SMB resource as an array of
  1970. /// <code>SmbFile</code> objects. This method is much more efficient than
  1971. /// the regular <code>list</code> method when querying attributes of each
  1972. /// file in the result set.
  1973. /// <p>
  1974. /// The list of <code>SmbFile</code>s returned by this method will be;
  1975. /// <ul>
  1976. /// <li> files and directories contained within this resource if the
  1977. /// resource is a normal disk file directory,
  1978. /// <li> all available NetBIOS workgroups or domains if this resource is
  1979. /// the top level URL <code>smb://</code>,
  1980. /// <li> all servers registered as members of a NetBIOS workgroup if this
  1981. /// resource refers to a workgroup in a <code>smb://workgroup/</code> URL,
  1982. /// <li> all browseable shares of a server including printers, IPC
  1983. /// services, or disk volumes if this resource is a server URL in the form
  1984. /// <code>smb://server/</code>,
  1985. /// <li> or <code>null</code> if the resource cannot be resolved.
  1986. /// </ul>
  1987. /// </remarks>
  1988. /// <returns>
  1989. /// An array of <code>SmbFile</code> objects representing file
  1990. /// and directories, workgroups, servers, or shares depending on the context
  1991. /// of the resource URL
  1992. /// </returns>
  1993. /// <exception cref="SmbException"></exception>
  1994. public virtual SmbFile[] ListFiles()
  1995. {
  1996. return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null);
  1997. }
  1998. /// <summary>
  1999. /// The CIFS protocol provides for DOS "wildcards" to be used as
  2000. /// a performance enhancement.
  2001. /// </summary>
  2002. /// <remarks>
  2003. /// The CIFS protocol provides for DOS "wildcards" to be used as
  2004. /// a performance enhancement. The client does not have to filter
  2005. /// the names and the server does not have to return all directory
  2006. /// entries.
  2007. /// <p>
  2008. /// The wildcard expression may consist of two special meta
  2009. /// characters in addition to the normal filename characters. The '*'
  2010. /// character matches any number of characters in part of a name. If
  2011. /// the expression begins with one or more '?'s then exactly that
  2012. /// many characters will be matched whereas if it ends with '?'s
  2013. /// it will match that many characters <i>or less</i>.
  2014. /// <p>
  2015. /// Wildcard expressions will not filter workgroup names or server names.
  2016. /// <blockquote><pre>
  2017. /// winnt&gt; ls c?o
  2018. /// clock.avi -rw-- 82944 Mon Oct 14 1996 1:38 AM
  2019. /// Cookies drw-- 0 Fri Nov 13 1998 9:42 PM
  2020. /// 2 items in 5ms
  2021. /// </pre></blockquote>
  2022. /// </remarks>
  2023. /// <param name="wildcard">a wildcard expression</param>
  2024. /// <exception cref="SmbException">SmbException</exception>
  2025. /// <returns>
  2026. /// An array of <code>SmbFile</code> objects representing file
  2027. /// and directories, workgroups, servers, or shares depending on the context
  2028. /// of the resource URL
  2029. /// </returns>
  2030. /// <exception cref="SmbException"></exception>
  2031. public virtual SmbFile[] ListFiles(string wildcard)
  2032. {
  2033. return ListFiles(wildcard, AttrDirectory | AttrHidden | AttrSystem, null, null
  2034. );
  2035. }
  2036. /// <summary>List the contents of this SMB resource.</summary>
  2037. /// <remarks>
  2038. /// List the contents of this SMB resource. The list returned will be
  2039. /// identical to the list returned by the parameterless <code>listFiles()</code>
  2040. /// method minus files filtered by the specified filename filter.
  2041. /// </remarks>
  2042. /// <param name="filter">a filter to exclude files from the results</param>
  2043. /// <returns>An array of <tt>SmbFile</tt> objects</returns>
  2044. /// <exception cref="SmbException">SmbException</exception>
  2045. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2046. public virtual SmbFile[] ListFiles(ISmbFilenameFilter filter)
  2047. {
  2048. return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, filter, null);
  2049. }
  2050. /// <summary>List the contents of this SMB resource.</summary>
  2051. /// <remarks>
  2052. /// List the contents of this SMB resource. The list returned will be
  2053. /// identical to the list returned by the parameterless <code>listFiles()</code>
  2054. /// method minus filenames filtered by the specified filter.
  2055. /// </remarks>
  2056. /// <param name="filter">a file filter to exclude files from the results</param>
  2057. /// <returns>An array of <tt>SmbFile</tt> objects</returns>
  2058. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2059. public virtual SmbFile[] ListFiles(ISmbFileFilter filter)
  2060. {
  2061. return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, filter);
  2062. }
  2063. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2064. internal virtual string[] List(string wildcard, int searchAttributes, ISmbFilenameFilter
  2065. fnf, ISmbFileFilter ff)
  2066. {
  2067. List<object> list = new List<object>();
  2068. DoEnum(list, false, wildcard, searchAttributes, fnf, ff);
  2069. return Collections.ToArray<string>(list); //Collections.ToArray<string>(list);
  2070. }
  2071. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2072. internal virtual SmbFile[] ListFiles(string wildcard, int searchAttributes
  2073. , ISmbFilenameFilter fnf, ISmbFileFilter ff)
  2074. {
  2075. List<object> list = new List<object>();
  2076. DoEnum(list, true, wildcard, searchAttributes, fnf, ff);
  2077. return Collections.ToArray<SmbFile>(list); //Collections.ToArray<SmbFile>(list);
  2078. }
  2079. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2080. internal virtual void DoEnum(List<object> list, bool files, string wildcard, int searchAttributes
  2081. , ISmbFilenameFilter fnf, ISmbFileFilter ff)
  2082. {
  2083. if (ff != null && ff is DosFileFilter)
  2084. {
  2085. DosFileFilter dff = (DosFileFilter)ff;
  2086. if (dff.Wildcard != null)
  2087. {
  2088. wildcard = dff.Wildcard;
  2089. }
  2090. searchAttributes = dff.Attributes;
  2091. }
  2092. try
  2093. {
  2094. int hostlen = Url.GetHost() != null ? Url.GetHost().Length : 0;
  2095. if (hostlen == 0 || GetType() == TypeWorkgroup)
  2096. {
  2097. DoNetServerEnum(list, files, wildcard, searchAttributes, fnf, ff);
  2098. }
  2099. else
  2100. {
  2101. if (_share == null)
  2102. {
  2103. DoShareEnum(list, files, wildcard, searchAttributes, fnf, ff);
  2104. }
  2105. else
  2106. {
  2107. DoFindFirstNext(list, files, wildcard, searchAttributes, fnf, ff);
  2108. }
  2109. }
  2110. }
  2111. catch (UnknownHostException uhe)
  2112. {
  2113. throw new SmbException(Url.ToString(), uhe);
  2114. }
  2115. catch (UriFormatException mue)
  2116. {
  2117. throw new SmbException(Url.ToString(), mue);
  2118. }
  2119. }
  2120. private void RemoveCurrentAddress()
  2121. {
  2122. if (AddressIndex >= 1)
  2123. {
  2124. UniAddress[] aux = new UniAddress[Addresses.Length - 1];
  2125. Array.Copy(Addresses, 1, aux, 0, Addresses.Length - 1);
  2126. Addresses = aux;
  2127. AddressIndex--;
  2128. }
  2129. }
  2130. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2131. /// <exception cref="UnknownHostException"></exception>
  2132. /// <exception cref="System.UriFormatException"></exception>
  2133. internal virtual void DoShareEnum(List<object> list, bool files, string wildcard, int
  2134. searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
  2135. {
  2136. string p = Url.AbsolutePath;
  2137. IOException last = null;
  2138. IFileEntry[] entries;
  2139. UniAddress addr;
  2140. IFileEntry e;
  2141. Hashtable map;
  2142. if (p.LastIndexOf('/') != (p.Length - 1))
  2143. {
  2144. throw new SmbException(Url + " directory must end with '/'");
  2145. }
  2146. if (GetType() != TypeServer)
  2147. {
  2148. throw new SmbException("The requested list operations is invalid: " + Url);
  2149. }
  2150. map = new Hashtable();
  2151. if (_enableDfs && Dfs.IsTrustedDomain(GetServer(), Auth))
  2152. {
  2153. try
  2154. {
  2155. entries = DoDfsRootEnum();
  2156. for (int ei = 0; ei < entries.Length; ei++)
  2157. {
  2158. e = entries[ei];
  2159. if (map.ContainsKey(e) == false)
  2160. {
  2161. map.Put(e, e);
  2162. }
  2163. }
  2164. }
  2165. catch (IOException ioe)
  2166. {
  2167. if (Log.Level >= 4)
  2168. {
  2169. Runtime.PrintStackTrace(ioe, Log);
  2170. }
  2171. }
  2172. }
  2173. addr = GetFirstAddress();
  2174. while (addr != null)
  2175. {
  2176. try
  2177. {
  2178. last = null;
  2179. DoConnect();
  2180. try
  2181. {
  2182. entries = DoMsrpcShareEnum();
  2183. }
  2184. catch (IOException ioe)
  2185. {
  2186. if (Log.Level >= 3)
  2187. {
  2188. Runtime.PrintStackTrace(ioe, Log);
  2189. }
  2190. entries = DoNetShareEnum();
  2191. }
  2192. for (int ei = 0; ei < entries.Length; ei++)
  2193. {
  2194. e = entries[ei];
  2195. if (map.ContainsKey(e) == false)
  2196. {
  2197. map.Put(e, e);
  2198. }
  2199. }
  2200. break;
  2201. }
  2202. catch (IOException ioe)
  2203. {
  2204. if (Log.Level >= 3)
  2205. {
  2206. Runtime.PrintStackTrace(ioe, Log);
  2207. }
  2208. last = ioe;
  2209. if (!(ioe is SmbAuthException))
  2210. {
  2211. RemoveCurrentAddress();
  2212. addr = GetNextAddress();
  2213. }
  2214. else
  2215. {
  2216. break;
  2217. }
  2218. }
  2219. }
  2220. if (last != null && map.Count == 0)
  2221. {
  2222. if (last is SmbException == false)
  2223. {
  2224. throw new SmbException(Url.ToString(), last);
  2225. }
  2226. throw (SmbException)last;
  2227. }
  2228. //Iterator iter = map.Keys.Iterator();
  2229. //while (iter.HasNext())
  2230. foreach (var item in map.Keys)
  2231. {
  2232. e = (IFileEntry)item;
  2233. string name = e.GetName();
  2234. if (fnf != null && fnf.Accept(this, name) == false)
  2235. {
  2236. continue;
  2237. }
  2238. if (name.Length > 0)
  2239. {
  2240. // if !files we don't need to create SmbFiles here
  2241. SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly
  2242. | AttrDirectory, 0L, 0L, 0L);
  2243. if (ff != null && ff.Accept(f) == false)
  2244. {
  2245. continue;
  2246. }
  2247. if (files)
  2248. {
  2249. list.Add(f);
  2250. }
  2251. else
  2252. {
  2253. list.Add(name);
  2254. }
  2255. }
  2256. }
  2257. }
  2258. /// <exception cref="System.IO.IOException"></exception>
  2259. internal virtual IFileEntry[] DoDfsRootEnum()
  2260. {
  2261. MsrpcDfsRootEnum rpc;
  2262. DcerpcHandle handle = null;
  2263. IFileEntry[] entries;
  2264. handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\netdfs]"
  2265. , Auth);
  2266. try
  2267. {
  2268. rpc = new MsrpcDfsRootEnum(GetServer());
  2269. handle.Sendrecv(rpc);
  2270. if (rpc.Retval != 0)
  2271. {
  2272. throw new SmbException(rpc.Retval, true);
  2273. }
  2274. return rpc.GetEntries();
  2275. }
  2276. finally
  2277. {
  2278. try
  2279. {
  2280. handle.Close();
  2281. }
  2282. catch (IOException ioe)
  2283. {
  2284. if (Log.Level >= 4)
  2285. {
  2286. Runtime.PrintStackTrace(ioe, Log);
  2287. }
  2288. }
  2289. }
  2290. }
  2291. /// <exception cref="System.IO.IOException"></exception>
  2292. internal virtual IFileEntry[] DoMsrpcShareEnum()
  2293. {
  2294. MsrpcShareEnum rpc;
  2295. DcerpcHandle handle;
  2296. rpc = new MsrpcShareEnum(Url.GetHost());
  2297. handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\srvsvc]"
  2298. , Auth);
  2299. try
  2300. {
  2301. handle.Sendrecv(rpc);
  2302. if (rpc.Retval != 0)
  2303. {
  2304. throw new SmbException(rpc.Retval, true);
  2305. }
  2306. return rpc.GetEntries();
  2307. }
  2308. finally
  2309. {
  2310. try
  2311. {
  2312. handle.Close();
  2313. }
  2314. catch (IOException ioe)
  2315. {
  2316. if (Log.Level >= 4)
  2317. {
  2318. Runtime.PrintStackTrace(ioe, Log);
  2319. }
  2320. }
  2321. }
  2322. }
  2323. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2324. internal virtual IFileEntry[] DoNetShareEnum()
  2325. {
  2326. SmbComTransaction req = new NetShareEnum();
  2327. SmbComTransactionResponse resp = new NetShareEnumResponse();
  2328. Send(req, resp);
  2329. if (resp.Status != WinError.ErrorSuccess)
  2330. {
  2331. throw new SmbException(resp.Status, true);
  2332. }
  2333. return resp.Results;
  2334. }
  2335. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2336. /// <exception cref="UnknownHostException"></exception>
  2337. /// <exception cref="System.UriFormatException"></exception>
  2338. internal virtual void DoNetServerEnum(List<object> list, bool files, string wildcard
  2339. , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
  2340. {
  2341. int listType = Url.GetHost().Length == 0 ? 0 : GetType();
  2342. SmbComTransaction req;
  2343. SmbComTransactionResponse resp;
  2344. if (listType == 0)
  2345. {
  2346. Connect0();
  2347. req = new NetServerEnum2(Tree.Session.transport.Server.OemDomainName, NetServerEnum2
  2348. .SvTypeDomainEnum);
  2349. resp = new NetServerEnum2Response();
  2350. }
  2351. else
  2352. {
  2353. if (listType == TypeWorkgroup)
  2354. {
  2355. req = new NetServerEnum2(Url.GetHost(), NetServerEnum2.SvTypeAll);
  2356. resp = new NetServerEnum2Response();
  2357. }
  2358. else
  2359. {
  2360. throw new SmbException("The requested list operations is invalid: " + Url);
  2361. }
  2362. }
  2363. bool more;
  2364. do
  2365. {
  2366. int n;
  2367. Send(req, resp);
  2368. if (resp.Status != WinError.ErrorSuccess && resp.Status != WinError.ErrorMoreData)
  2369. {
  2370. throw new SmbException(resp.Status, true);
  2371. }
  2372. more = resp.Status == WinError.ErrorMoreData;
  2373. n = more ? resp.NumEntries - 1 : resp.NumEntries;
  2374. for (int i = 0; i < n; i++)
  2375. {
  2376. IFileEntry e = resp.Results[i];
  2377. string name = e.GetName();
  2378. if (fnf != null && fnf.Accept(this, name) == false)
  2379. {
  2380. continue;
  2381. }
  2382. if (name.Length > 0)
  2383. {
  2384. // if !files we don't need to create SmbFiles here
  2385. SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly
  2386. | AttrDirectory, 0L, 0L, 0L);
  2387. if (ff != null && ff.Accept(f) == false)
  2388. {
  2389. continue;
  2390. }
  2391. if (files)
  2392. {
  2393. list.Add(f);
  2394. }
  2395. else
  2396. {
  2397. list.Add(name);
  2398. }
  2399. }
  2400. }
  2401. if (GetType() != TypeWorkgroup)
  2402. {
  2403. break;
  2404. }
  2405. req.SubCommand = unchecked(SmbComTransaction.NetServerEnum3);
  2406. req.Reset(0, ((NetServerEnum2Response)resp).LastName);
  2407. resp.Reset();
  2408. }
  2409. while (more);
  2410. }
  2411. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2412. /// <exception cref="UnknownHostException"></exception>
  2413. /// <exception cref="System.UriFormatException"></exception>
  2414. internal virtual void DoFindFirstNext(List<object> list, bool files, string wildcard
  2415. , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
  2416. {
  2417. SmbComTransaction req;
  2418. Trans2FindFirst2Response resp;
  2419. int sid;
  2420. string path = GetUncPath0();
  2421. string p = Url.AbsolutePath;
  2422. if (p.LastIndexOf('/') != (p.Length - 1))
  2423. {
  2424. throw new SmbException(Url + " directory must end with '/'");
  2425. }
  2426. req = new Trans2FindFirst2(path, wildcard, searchAttributes);
  2427. resp = new Trans2FindFirst2Response();
  2428. if (Log.Level >= 3)
  2429. {
  2430. Log.WriteLine("doFindFirstNext: " + req.Path);
  2431. }
  2432. Send(req, resp);
  2433. sid = resp.Sid;
  2434. req = new Trans2FindNext2(sid, resp.ResumeKey, resp.LastName);
  2435. resp.SubCommand = SmbComTransaction.Trans2FindNext2;
  2436. for (; ; )
  2437. {
  2438. for (int i = 0; i < resp.NumEntries; i++)
  2439. {
  2440. IFileEntry e = resp.Results[i];
  2441. string name = e.GetName();
  2442. if (name.Length < 3)
  2443. {
  2444. int h = name.GetHashCode();
  2445. if (h == HashDot || h == HashDotDot)
  2446. {
  2447. if (name.Equals(".") || name.Equals(".."))
  2448. {
  2449. continue;
  2450. }
  2451. }
  2452. }
  2453. if (fnf != null && fnf.Accept(this, name) == false)
  2454. {
  2455. continue;
  2456. }
  2457. if (name.Length > 0)
  2458. {
  2459. SmbFile f = new SmbFile(this, name, TypeFilesystem, e.GetAttributes
  2460. (), e.CreateTime(), e.LastModified(), e.Length());
  2461. if (ff != null && ff.Accept(f) == false)
  2462. {
  2463. continue;
  2464. }
  2465. if (files)
  2466. {
  2467. list.Add(f);
  2468. }
  2469. else
  2470. {
  2471. list.Add(name);
  2472. }
  2473. }
  2474. }
  2475. if (resp.IsEndOfSearch || resp.NumEntries == 0)
  2476. {
  2477. break;
  2478. }
  2479. req.Reset(resp.ResumeKey, resp.LastName);
  2480. resp.Reset();
  2481. Send(req, resp);
  2482. }
  2483. try
  2484. {
  2485. Send(new SmbComFindClose2(sid), Blank_resp());
  2486. }
  2487. catch (SmbException se)
  2488. {
  2489. if (Log.Level >= 4)
  2490. {
  2491. Runtime.PrintStackTrace(se, Log);
  2492. }
  2493. }
  2494. }
  2495. /// <summary>
  2496. /// Changes the name of the file this <code>SmbFile</code> represents to the name
  2497. /// designated by the <code>SmbFile</code> argument.
  2498. /// </summary>
  2499. /// <remarks>
  2500. /// Changes the name of the file this <code>SmbFile</code> represents to the name
  2501. /// designated by the <code>SmbFile</code> argument.
  2502. /// <p/>
  2503. /// <i>Remember: <code>SmbFile</code>s are immutible and therefore
  2504. /// the path associated with this <code>SmbFile</code> object will not
  2505. /// change). To access the renamed file it is necessary to construct a
  2506. /// new <tt>SmbFile</tt></i>.
  2507. /// </remarks>
  2508. /// <param name="dest">An <code>SmbFile</code> that represents the new pathname</param>
  2509. /// <exception cref="System.ArgumentNullException">If the <code>dest</code> argument is <code>null</code>
  2510. /// </exception>
  2511. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2512. public virtual void RenameTo(SmbFile dest)
  2513. {
  2514. if (GetUncPath0().Length == 1 || dest.GetUncPath0().Length == 1)
  2515. {
  2516. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  2517. }
  2518. ResolveDfs(null);
  2519. dest.ResolveDfs(null);
  2520. if (!Tree.Equals(dest.Tree))
  2521. {
  2522. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  2523. }
  2524. if (Log.Level >= 3)
  2525. {
  2526. Log.WriteLine("renameTo: " + Unc + " -> " + dest.Unc);
  2527. }
  2528. _attrExpiration = _sizeExpiration = 0;
  2529. dest._attrExpiration = 0;
  2530. Send(new SmbComRename(Unc, dest.Unc), Blank_resp());
  2531. }
  2532. internal class WriterThread : Thread
  2533. {
  2534. internal byte[] B;
  2535. internal int N;
  2536. internal long Off;
  2537. internal bool Ready;
  2538. internal SmbFile Dest;
  2539. internal SmbException E;
  2540. internal bool UseNtSmbs;
  2541. internal SmbComWriteAndX Reqx;
  2542. internal SmbComWrite Req;
  2543. internal ServerMessageBlock Resp;
  2544. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2545. public WriterThread(SmbFile enclosing)
  2546. : base("JCIFS-WriterThread")
  2547. {
  2548. this._enclosing = enclosing;
  2549. UseNtSmbs = this._enclosing.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs);
  2550. if (UseNtSmbs)
  2551. {
  2552. Reqx = new SmbComWriteAndX();
  2553. Resp = new SmbComWriteAndXResponse();
  2554. }
  2555. else
  2556. {
  2557. Req = new SmbComWrite();
  2558. Resp = new SmbComWriteResponse();
  2559. }
  2560. Ready = false;
  2561. }
  2562. internal virtual void Write(byte[] b, int n, SmbFile dest, long off)
  2563. {
  2564. lock (this)
  2565. {
  2566. this.B = b;
  2567. this.N = n;
  2568. this.Dest = dest;
  2569. this.Off = off;
  2570. Ready = false;
  2571. Runtime.Notify(this);
  2572. }
  2573. }
  2574. public override void Run()
  2575. {
  2576. lock (this)
  2577. {
  2578. try
  2579. {
  2580. for (; ; )
  2581. {
  2582. Runtime.Notify(this);
  2583. Ready = true;
  2584. while (Ready)
  2585. {
  2586. Runtime.Wait(this);
  2587. }
  2588. if (N == -1)
  2589. {
  2590. return;
  2591. }
  2592. if (UseNtSmbs)
  2593. {
  2594. Reqx.SetParam(Dest.Fid, Off, N, B, 0, N);
  2595. Dest.Send(Reqx, Resp);
  2596. }
  2597. else
  2598. {
  2599. Req.SetParam(Dest.Fid, Off, N, B, 0, N);
  2600. Dest.Send(Req, Resp);
  2601. }
  2602. }
  2603. }
  2604. catch (SmbException e)
  2605. {
  2606. this.E = e;
  2607. }
  2608. catch (Exception x)
  2609. {
  2610. E = new SmbException("WriterThread", x);
  2611. }
  2612. Runtime.Notify(this);
  2613. }
  2614. }
  2615. private readonly SmbFile _enclosing;
  2616. }
  2617. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2618. internal virtual void CopyTo0(SmbFile dest, byte[][] b, int bsize, WriterThread
  2619. w, SmbComReadAndX req, SmbComReadAndXResponse resp)
  2620. {
  2621. int i;
  2622. if (_attrExpiration < Runtime.CurrentTimeMillis())
  2623. {
  2624. _attributes = AttrReadonly | AttrDirectory;
  2625. _createTime = 0L;
  2626. _lastModified = 0L;
  2627. _isExists = false;
  2628. IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
  2629. );
  2630. _attributes = info.GetAttributes();
  2631. _createTime = info.GetCreateTime();
  2632. _lastModified = info.GetLastWriteTime();
  2633. _isExists = true;
  2634. _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
  2635. }
  2636. if (IsDirectory())
  2637. {
  2638. SmbFile[] files;
  2639. SmbFile ndest;
  2640. string path = dest.GetUncPath0();
  2641. if (path.Length > 1)
  2642. {
  2643. try
  2644. {
  2645. dest.Mkdir();
  2646. dest.SetPathInformation(_attributes, _createTime, _lastModified);
  2647. }
  2648. catch (SmbException se)
  2649. {
  2650. if (se.GetNtStatus() != NtStatus.NtStatusAccessDenied && se.GetNtStatus() != NtStatus
  2651. .NtStatusObjectNameCollision)
  2652. {
  2653. throw;
  2654. }
  2655. }
  2656. }
  2657. files = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null);
  2658. try
  2659. {
  2660. for (i = 0; i < files.Length; i++)
  2661. {
  2662. ndest = new SmbFile(dest, files[i].GetName(), files[i].Type, files[i]._attributes,
  2663. files[i]._createTime, files[i]._lastModified, files[i]._size);
  2664. files[i].CopyTo0(ndest, b, bsize, w, req, resp);
  2665. }
  2666. }
  2667. catch (UnknownHostException uhe)
  2668. {
  2669. throw new SmbException(Url.ToString(), uhe);
  2670. }
  2671. catch (UriFormatException mue)
  2672. {
  2673. throw new SmbException(Url.ToString(), mue);
  2674. }
  2675. }
  2676. else
  2677. {
  2678. long off;
  2679. try
  2680. {
  2681. Open(ORdonly, 0, AttrNormal, 0);
  2682. try
  2683. {
  2684. dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData |
  2685. SmbConstants.FileWriteAttributes, _attributes, 0);
  2686. }
  2687. catch (SmbAuthException sae)
  2688. {
  2689. if ((dest._attributes & AttrReadonly) != 0)
  2690. {
  2691. dest.SetPathInformation(dest._attributes & ~AttrReadonly, 0L, 0L);
  2692. dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData |
  2693. SmbConstants.FileWriteAttributes, _attributes, 0);
  2694. }
  2695. else
  2696. {
  2697. throw;
  2698. }
  2699. }
  2700. i = 0;
  2701. off = 0L;
  2702. for (; ; )
  2703. {
  2704. req.SetParam(Fid, off, bsize);
  2705. resp.SetParam(b[i], 0);
  2706. Send(req, resp);
  2707. lock (w)
  2708. {
  2709. if (w.E != null)
  2710. {
  2711. throw w.E;
  2712. }
  2713. while (!w.Ready)
  2714. {
  2715. try
  2716. {
  2717. Runtime.Wait(w);
  2718. }
  2719. catch (Exception ie)
  2720. {
  2721. throw new SmbException(dest.Url.ToString(), ie);
  2722. }
  2723. }
  2724. if (w.E != null)
  2725. {
  2726. throw w.E;
  2727. }
  2728. if (resp.DataLength <= 0)
  2729. {
  2730. break;
  2731. }
  2732. w.Write(b[i], resp.DataLength, dest, off);
  2733. }
  2734. i = i == 1 ? 0 : 1;
  2735. off += resp.DataLength;
  2736. }
  2737. dest.Send(new Trans2SetFileInformation(dest.Fid, _attributes, _createTime, _lastModified
  2738. ), new Trans2SetFileInformationResponse());
  2739. dest.Close(0L);
  2740. }
  2741. catch (SmbException se)
  2742. {
  2743. if (IgnoreCopyToException == false)
  2744. {
  2745. throw new SmbException("Failed to copy file from [" + ToString() + "] to ["
  2746. + dest + "]", se);
  2747. }
  2748. if (Log.Level > 1)
  2749. {
  2750. Runtime.PrintStackTrace(se, Log);
  2751. }
  2752. }
  2753. finally
  2754. {
  2755. Close();
  2756. }
  2757. }
  2758. }
  2759. /// <summary>
  2760. /// This method will copy the file or directory represented by this
  2761. /// <tt>SmbFile</tt> and it's sub-contents to the location specified by the
  2762. /// <tt>dest</tt> parameter.
  2763. /// </summary>
  2764. /// <remarks>
  2765. /// This method will copy the file or directory represented by this
  2766. /// <tt>SmbFile</tt> and it's sub-contents to the location specified by the
  2767. /// <tt>dest</tt> parameter. This file and the destination file do not
  2768. /// need to be on the same host. This operation does not copy extended
  2769. /// file attibutes such as ACLs but it does copy regular attributes as
  2770. /// well as create and last write times. This method is almost twice as
  2771. /// efficient as manually copying as it employs an additional write
  2772. /// thread to read and write data concurrently.
  2773. /// <p/>
  2774. /// It is not possible (nor meaningful) to copy entire workgroups or
  2775. /// servers.
  2776. /// </remarks>
  2777. /// <param name="dest">the destination file or directory</param>
  2778. /// <exception cref="SmbException">SmbException</exception>
  2779. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2780. public virtual void CopyTo(SmbFile dest)
  2781. {
  2782. SmbComReadAndX req;
  2783. SmbComReadAndXResponse resp;
  2784. WriterThread w;
  2785. int bsize;
  2786. byte[][] b;
  2787. if (_share == null || dest._share == null)
  2788. {
  2789. throw new SmbException("Invalid operation for workgroups or servers");
  2790. }
  2791. req = new SmbComReadAndX();
  2792. resp = new SmbComReadAndXResponse();
  2793. Connect0();
  2794. dest.Connect0();
  2795. ResolveDfs(null);
  2796. try
  2797. {
  2798. if (GetAddress().Equals(dest.GetAddress()) && _canon.RegionMatches(true, 0, dest._canon
  2799. , 0, Math.Min(_canon.Length, dest._canon.Length)))
  2800. {
  2801. throw new SmbException("Source and destination paths overlap.");
  2802. }
  2803. }
  2804. catch (UnknownHostException)
  2805. {
  2806. }
  2807. w = new WriterThread(this);
  2808. w.SetDaemon(true);
  2809. w.Start();
  2810. SmbTransport t1 = Tree.Session.transport;
  2811. SmbTransport t2 = dest.Tree.Session.transport;
  2812. if (t1.SndBufSize < t2.SndBufSize)
  2813. {
  2814. t2.SndBufSize = t1.SndBufSize;
  2815. }
  2816. else
  2817. {
  2818. t1.SndBufSize = t2.SndBufSize;
  2819. }
  2820. bsize = Math.Min(t1.RcvBufSize - 70, t1.SndBufSize - 70);
  2821. b = new[] { new byte[bsize], new byte[bsize] };
  2822. try
  2823. {
  2824. CopyTo0(dest, b, bsize, w, req, resp);
  2825. }
  2826. finally
  2827. {
  2828. w.Write(null, -1, null, 0);
  2829. }
  2830. }
  2831. /// <summary>
  2832. /// This method will delete the file or directory specified by this
  2833. /// <code>SmbFile</code>.
  2834. /// </summary>
  2835. /// <remarks>
  2836. /// This method will delete the file or directory specified by this
  2837. /// <code>SmbFile</code>. If the target is a directory, the contents of
  2838. /// the directory will be deleted as well. If a file within the directory or
  2839. /// it's sub-directories is marked read-only, the read-only status will
  2840. /// be removed and the file will be deleted.
  2841. /// </remarks>
  2842. /// <exception cref="SmbException">SmbException</exception>
  2843. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2844. public virtual void Delete()
  2845. {
  2846. Exists();
  2847. GetUncPath0();
  2848. Delete(Unc);
  2849. }
  2850. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2851. internal virtual void Delete(string fileName)
  2852. {
  2853. if (GetUncPath0().Length == 1)
  2854. {
  2855. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  2856. }
  2857. if (Runtime.CurrentTimeMillis() > _attrExpiration)
  2858. {
  2859. _attributes = AttrReadonly | AttrDirectory;
  2860. _createTime = 0L;
  2861. _lastModified = 0L;
  2862. _isExists = false;
  2863. IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
  2864. );
  2865. _attributes = info.GetAttributes();
  2866. _createTime = info.GetCreateTime();
  2867. _lastModified = info.GetLastWriteTime();
  2868. _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
  2869. _isExists = true;
  2870. }
  2871. if ((_attributes & AttrReadonly) != 0)
  2872. {
  2873. SetReadWrite();
  2874. }
  2875. if (Log.Level >= 3)
  2876. {
  2877. Log.WriteLine("delete: " + fileName);
  2878. }
  2879. if ((_attributes & AttrDirectory) != 0)
  2880. {
  2881. try
  2882. {
  2883. SmbFile[] l = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null
  2884. );
  2885. for (int i = 0; i < l.Length; i++)
  2886. {
  2887. l[i].Delete();
  2888. }
  2889. }
  2890. catch (SmbException se)
  2891. {
  2892. if (se.GetNtStatus() != NtStatus.NtStatusNoSuchFile)
  2893. {
  2894. throw;
  2895. }
  2896. }
  2897. Send(new SmbComDeleteDirectory(fileName), Blank_resp());
  2898. }
  2899. else
  2900. {
  2901. Send(new SmbComDelete(fileName), Blank_resp());
  2902. }
  2903. _attrExpiration = _sizeExpiration = 0;
  2904. }
  2905. /// <summary>Returns the length of this <tt>SmbFile</tt> in bytes.</summary>
  2906. /// <remarks>
  2907. /// Returns the length of this <tt>SmbFile</tt> in bytes. If this object
  2908. /// is a <tt>TYPE_SHARE</tt> the total capacity of the disk shared in
  2909. /// bytes is returned. If this object is a directory or a type other than
  2910. /// <tt>TYPE_SHARE</tt>, 0L is returned.
  2911. /// </remarks>
  2912. /// <returns>
  2913. /// The length of the file in bytes or 0 if this
  2914. /// <code>SmbFile</code> is not a file.
  2915. /// </returns>
  2916. /// <exception cref="SmbException">SmbException</exception>
  2917. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2918. public virtual long Length()
  2919. {
  2920. if (_sizeExpiration > Runtime.CurrentTimeMillis())
  2921. {
  2922. return _size;
  2923. }
  2924. if (GetType() == TypeShare)
  2925. {
  2926. Trans2QueryFsInformationResponse response;
  2927. int level = Trans2QueryFsInformationResponse.SMB_INFO_ALLOCATION;
  2928. response = new Trans2QueryFsInformationResponse(level);
  2929. Send(new Trans2QueryFsInformation(level), response);
  2930. _size = response.Info.GetCapacity();
  2931. }
  2932. else
  2933. {
  2934. if (GetUncPath0().Length > 1 && Type != TypeNamedPipe)
  2935. {
  2936. IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO
  2937. );
  2938. _size = info.GetSize();
  2939. }
  2940. else
  2941. {
  2942. _size = 0L;
  2943. }
  2944. }
  2945. _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
  2946. return _size;
  2947. }
  2948. /// <summary>
  2949. /// This method returns the free disk space in bytes of the drive this share
  2950. /// represents or the drive on which the directory or file resides.
  2951. /// </summary>
  2952. /// <remarks>
  2953. /// This method returns the free disk space in bytes of the drive this share
  2954. /// represents or the drive on which the directory or file resides. Objects
  2955. /// other than <tt>TYPE_SHARE</tt> or <tt>TYPE_FILESYSTEM</tt> will result
  2956. /// in 0L being returned.
  2957. /// </remarks>
  2958. /// <returns>
  2959. /// the free disk space in bytes of the drive on which this file or
  2960. /// directory resides
  2961. /// </returns>
  2962. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2963. public virtual long GetDiskFreeSpace()
  2964. {
  2965. if (GetType() == TypeShare || Type == TypeFilesystem)
  2966. {
  2967. int level = Trans2QueryFsInformationResponse.SmbFsFullSizeInformation;
  2968. try
  2969. {
  2970. return QueryFsInformation(level);
  2971. }
  2972. catch (SmbException ex)
  2973. {
  2974. switch (ex.GetNtStatus())
  2975. {
  2976. case NtStatus.NtStatusInvalidInfoClass:
  2977. case NtStatus.NtStatusUnsuccessful:
  2978. {
  2979. // NetApp Filer
  2980. // SMB_FS_FULL_SIZE_INFORMATION not supported by the server.
  2981. level = Trans2QueryFsInformationResponse.SMB_INFO_ALLOCATION;
  2982. return QueryFsInformation(level);
  2983. }
  2984. }
  2985. throw;
  2986. }
  2987. }
  2988. return 0L;
  2989. }
  2990. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  2991. private long QueryFsInformation(int level)
  2992. {
  2993. Trans2QueryFsInformationResponse response;
  2994. response = new Trans2QueryFsInformationResponse(level);
  2995. Send(new Trans2QueryFsInformation(level), response);
  2996. if (Type == TypeShare)
  2997. {
  2998. _size = response.Info.GetCapacity();
  2999. _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod;
  3000. }
  3001. return response.Info.GetFree();
  3002. }
  3003. /// <summary>
  3004. /// Creates a directory with the path specified by this
  3005. /// <code>SmbFile</code>.
  3006. /// </summary>
  3007. /// <remarks>
  3008. /// Creates a directory with the path specified by this
  3009. /// <code>SmbFile</code>. For this method to be successful, the target
  3010. /// must not already exist. This method will fail when
  3011. /// used with <code>smb://</code>, <code>smb://workgroup/</code>,
  3012. /// <code>smb://server/</code>, or <code>smb://server/share/</code> URLs
  3013. /// because workgroups, servers, and shares cannot be dynamically created
  3014. /// (although in the future it may be possible to create shares).
  3015. /// </remarks>
  3016. /// <exception cref="SmbException">SmbException</exception>
  3017. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3018. public virtual void Mkdir()
  3019. {
  3020. string path = GetUncPath0();
  3021. if (path.Length == 1)
  3022. {
  3023. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  3024. }
  3025. if (Log.Level >= 3)
  3026. {
  3027. Log.WriteLine("mkdir: " + path);
  3028. }
  3029. Send(new SmbComCreateDirectory(path), Blank_resp());
  3030. _attrExpiration = _sizeExpiration = 0;
  3031. }
  3032. /// <summary>
  3033. /// Creates a directory with the path specified by this <tt>SmbFile</tt>
  3034. /// and any parent directories that do not exist.
  3035. /// </summary>
  3036. /// <remarks>
  3037. /// Creates a directory with the path specified by this <tt>SmbFile</tt>
  3038. /// and any parent directories that do not exist. This method will fail
  3039. /// when used with <code>smb://</code>, <code>smb://workgroup/</code>,
  3040. /// <code>smb://server/</code>, or <code>smb://server/share/</code> URLs
  3041. /// because workgroups, servers, and shares cannot be dynamically created
  3042. /// (although in the future it may be possible to create shares).
  3043. /// </remarks>
  3044. /// <exception cref="SmbException">SmbException</exception>
  3045. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3046. public virtual void Mkdirs()
  3047. {
  3048. SmbFile parent;
  3049. try
  3050. {
  3051. parent = new SmbFile(GetParent(), Auth);
  3052. }
  3053. catch (IOException)
  3054. {
  3055. return;
  3056. }
  3057. if (parent.Exists() == false)
  3058. {
  3059. parent.Mkdirs();
  3060. }
  3061. Mkdir();
  3062. }
  3063. /// <summary>Create a new file but fail if it already exists.</summary>
  3064. /// <remarks>
  3065. /// Create a new file but fail if it already exists. The check for
  3066. /// existance of the file and it's creation are an atomic operation with
  3067. /// respect to other filesystem activities.
  3068. /// </remarks>
  3069. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3070. public virtual void CreateNewFile()
  3071. {
  3072. if (GetUncPath0().Length == 1)
  3073. {
  3074. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  3075. }
  3076. Close(Open0(ORdwr | OCreat | OExcl, 0, AttrNormal, 0), 0L);
  3077. }
  3078. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3079. internal virtual void SetPathInformation(int attrs, long ctime, long mtime)
  3080. {
  3081. int f;
  3082. int dir;
  3083. Exists();
  3084. dir = _attributes & AttrDirectory;
  3085. f = Open0(ORdonly, SmbConstants.FileWriteAttributes, dir, dir != 0 ? 0x0001
  3086. : 0x0040);
  3087. Send(new Trans2SetFileInformation(f, attrs | dir, ctime, mtime), new Trans2SetFileInformationResponse
  3088. ());
  3089. Close(f, 0L);
  3090. _attrExpiration = 0;
  3091. }
  3092. /// <summary>Set the create time of the file.</summary>
  3093. /// <remarks>
  3094. /// Set the create time of the file. The time is specified as milliseconds
  3095. /// from Jan 1, 1970 which is the same as that which is returned by the
  3096. /// <tt>createTime()</tt> method.
  3097. /// <p/>
  3098. /// This method does not apply to workgroups, servers, or shares.
  3099. /// </remarks>
  3100. /// <param name="time">the create time as milliseconds since Jan 1, 1970</param>
  3101. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3102. public virtual void SetCreateTime(long time)
  3103. {
  3104. if (GetUncPath0().Length == 1)
  3105. {
  3106. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  3107. }
  3108. SetPathInformation(0, time, 0L);
  3109. }
  3110. /// <summary>Set the last modified time of the file.</summary>
  3111. /// <remarks>
  3112. /// Set the last modified time of the file. The time is specified as milliseconds
  3113. /// from Jan 1, 1970 which is the same as that which is returned by the
  3114. /// <tt>lastModified()</tt>, <tt>getLastModified()</tt>, and <tt>getDate()</tt> methods.
  3115. /// <p/>
  3116. /// This method does not apply to workgroups, servers, or shares.
  3117. /// </remarks>
  3118. /// <param name="time">the last modified time as milliseconds since Jan 1, 1970</param>
  3119. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3120. public virtual void SetLastModified(long time)
  3121. {
  3122. if (GetUncPath0().Length == 1)
  3123. {
  3124. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  3125. }
  3126. SetPathInformation(0, 0L, time);
  3127. }
  3128. /// <summary>Return the attributes of this file.</summary>
  3129. /// <remarks>
  3130. /// Return the attributes of this file. Attributes are represented as a
  3131. /// bitset that must be masked with <tt>ATTR_*</tt> constants to determine
  3132. /// if they are set or unset. The value returned is suitable for use with
  3133. /// the <tt>setAttributes()</tt> method.
  3134. /// </remarks>
  3135. /// <returns>the <tt>ATTR_*</tt> attributes associated with this file</returns>
  3136. /// <exception cref="SmbException">SmbException</exception>
  3137. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3138. public virtual int GetAttributes()
  3139. {
  3140. if (GetUncPath0().Length == 1)
  3141. {
  3142. return 0;
  3143. }
  3144. Exists();
  3145. return _attributes & AttrGetMask;
  3146. }
  3147. /// <summary>Set the attributes of this file.</summary>
  3148. /// <remarks>
  3149. /// Set the attributes of this file. Attributes are composed into a
  3150. /// bitset by bitwise ORing the <tt>ATTR_*</tt> constants. Setting the
  3151. /// value returned by <tt>getAttributes</tt> will result in both files
  3152. /// having the same attributes.
  3153. /// </remarks>
  3154. /// <exception cref="SmbException">SmbException</exception>
  3155. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3156. public virtual void SetAttributes(int attrs)
  3157. {
  3158. if (GetUncPath0().Length == 1)
  3159. {
  3160. throw new SmbException("Invalid operation for workgroups, servers, or shares");
  3161. }
  3162. SetPathInformation(attrs & AttrSetMask, 0L, 0L);
  3163. }
  3164. /// <summary>Make this file read-only.</summary>
  3165. /// <remarks>
  3166. /// Make this file read-only. This is shorthand for <tt>setAttributes(
  3167. /// getAttributes() | ATTR_READ_ONLY )</tt>.
  3168. /// </remarks>
  3169. /// <exception cref="SmbException">SmbException</exception>
  3170. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  3171. public virtual void SetReadOnly()
  3172. {
  3173. SetAttributes(GetAttributes() | AttrReadonly);
  3174. }
  3175. /// <summary>Turn off the read-only attribute of this file.</summary>
  3176. /// <remarks>
  3177. /// Turn off the read-only attribute of this file. This is shorthand for
  3178. /// <tt>setAttributes( getAttributes() & ~ATTR_READONLY )</tt>.
  3179. /// </remarks>
  3180. /// <exception cref="SmbException">SmbException</exception>
  3181. /// <exception cref="SmbException"></exception>
  3182. public virtual void SetReadWrite()
  3183. {
  3184. SetAttributes(GetAttributes() & ~AttrReadonly);
  3185. }
  3186. /// <summary>
  3187. /// Returns a
  3188. /// <see cref="System.Uri">System.Uri</see>
  3189. /// for this <code>SmbFile</code>. The
  3190. /// <code>URL</code> may be used as any other <code>URL</code> might to
  3191. /// access an SMB resource. Currently only retrieving data and information
  3192. /// is supported (i.e. no <tt>doOutput</tt>).
  3193. /// </summary>
  3194. /// <returns>
  3195. /// A new <code>
  3196. /// <see cref="System.Uri">System.Uri</see>
  3197. /// </code> for this <code>SmbFile</code>
  3198. /// </returns>
  3199. /// <exception cref="System.UriFormatException">System.UriFormatException</exception>
  3200. [Obsolete(@"Use getURL() instead")]
  3201. public virtual Uri ToUrl()
  3202. {
  3203. return Url;
  3204. }
  3205. /// <summary>
  3206. /// Computes a hashCode for this file based on the URL string and IP
  3207. /// address if the server.
  3208. /// </summary>
  3209. /// <remarks>
  3210. /// Computes a hashCode for this file based on the URL string and IP
  3211. /// address if the server. The hashing function uses the hashcode of the
  3212. /// server address, the canonical representation of the URL, and does not
  3213. /// compare authentication information. In essance, two
  3214. /// <code>SmbFile</code> objects that refer to
  3215. /// the same file should generate the same hashcode provided it is possible
  3216. /// to make such a determination.
  3217. /// </remarks>
  3218. /// <returns>A hashcode for this abstract file</returns>
  3219. /// <exception cref="SmbException">SmbException</exception>
  3220. public override int GetHashCode()
  3221. {
  3222. int hash;
  3223. try
  3224. {
  3225. hash = GetAddress().GetHashCode();
  3226. }
  3227. catch (UnknownHostException)
  3228. {
  3229. hash = GetServer().ToUpper().GetHashCode();
  3230. }
  3231. GetUncPath0();
  3232. return hash + _canon.ToUpper().GetHashCode();
  3233. }
  3234. protected internal virtual bool PathNamesPossiblyEqual(string path1, string path2
  3235. )
  3236. {
  3237. int p1;
  3238. int p2;
  3239. int l1;
  3240. int l2;
  3241. // if unsure return this method returns true
  3242. p1 = path1.LastIndexOf('/');
  3243. p2 = path2.LastIndexOf('/');
  3244. l1 = path1.Length - p1;
  3245. l2 = path2.Length - p2;
  3246. // anything with dots voids comparison
  3247. if (l1 > 1 && path1[p1 + 1] == '.')
  3248. {
  3249. return true;
  3250. }
  3251. if (l2 > 1 && path2[p2 + 1] == '.')
  3252. {
  3253. return true;
  3254. }
  3255. return l1 == l2 && path1.RegionMatches(true, p1, path2, p2, l1);
  3256. }
  3257. /// <summary>Tests to see if two <code>SmbFile</code> objects are equal.</summary>
  3258. /// <remarks>
  3259. /// Tests to see if two <code>SmbFile</code> objects are equal. Two
  3260. /// SmbFile objects are equal when they reference the same SMB
  3261. /// resource. More specifically, two <code>SmbFile</code> objects are
  3262. /// equals if their server IP addresses are equal and the canonicalized
  3263. /// representation of their URLs, minus authentication parameters, are
  3264. /// case insensitivly and lexographically equal.
  3265. /// <p/>
  3266. /// For example, assuming the server <code>angus</code> resolves to the
  3267. /// <code>192.168.1.15</code> IP address, the below URLs would result in
  3268. /// <code>SmbFile</code>s that are equal.
  3269. /// <p><blockquote><pre>
  3270. /// smb://192.168.1.15/share/DIR/foo.txt
  3271. /// smb://angus/share/data/../dir/foo.txt
  3272. /// </pre></blockquote>
  3273. /// </remarks>
  3274. /// <param name="obj">Another <code>SmbFile</code> object to compare for equality</param>
  3275. /// <returns>
  3276. /// <code>true</code> if the two objects refer to the same SMB resource
  3277. /// and <code>false</code> otherwise
  3278. /// </returns>
  3279. /// <exception cref="SmbException">SmbException</exception>
  3280. public override bool Equals(object obj)
  3281. {
  3282. if (obj is SmbFile)
  3283. {
  3284. SmbFile f = (SmbFile)obj;
  3285. bool ret;
  3286. if (this == f)
  3287. {
  3288. return true;
  3289. }
  3290. if (PathNamesPossiblyEqual(Url.AbsolutePath, f.Url.AbsolutePath))
  3291. {
  3292. GetUncPath0();
  3293. f.GetUncPath0();
  3294. if (Runtime.EqualsIgnoreCase(_canon, f._canon))
  3295. {
  3296. try
  3297. {
  3298. ret = GetAddress().Equals(f.GetAddress());
  3299. }
  3300. catch (UnknownHostException)
  3301. {
  3302. ret = Runtime.EqualsIgnoreCase(GetServer(), f.GetServer());
  3303. }
  3304. return ret;
  3305. }
  3306. }
  3307. }
  3308. return false;
  3309. }
  3310. /// <summary>Returns the string representation of this SmbFile object.</summary>
  3311. /// <remarks>
  3312. /// Returns the string representation of this SmbFile object. This will
  3313. /// be the same as the URL used to construct this <code>SmbFile</code>.
  3314. /// This method will return the same value
  3315. /// as <code>getPath</code>.
  3316. /// </remarks>
  3317. /// <returns>The original URL representation of this SMB resource</returns>
  3318. /// <exception cref="SmbException">SmbException</exception>
  3319. public override string ToString()
  3320. {
  3321. return Url.ToString();
  3322. }
  3323. /// <summary>This URLConnection method just returns the result of <tt>length()</tt>.</summary>
  3324. /// <remarks>This URLConnection method just returns the result of <tt>length()</tt>.</remarks>
  3325. /// <returns>the length of this file or 0 if it refers to a directory</returns>
  3326. public int GetContentLength()
  3327. {
  3328. try
  3329. {
  3330. return (int)(Length() & unchecked(0xFFFFFFFFL));
  3331. }
  3332. catch (SmbException)
  3333. {
  3334. }
  3335. return 0;
  3336. }
  3337. /// <summary>This URLConnection method just returns the result of <tt>lastModified</tt>.
  3338. /// </summary>
  3339. /// <remarks>This URLConnection method just returns the result of <tt>lastModified</tt>.
  3340. /// </remarks>
  3341. /// <returns>the last modified data as milliseconds since Jan 1, 1970</returns>
  3342. public long GetDate()
  3343. {
  3344. try
  3345. {
  3346. return LastModified();
  3347. }
  3348. catch (SmbException)
  3349. {
  3350. }
  3351. return 0L;
  3352. }
  3353. /// <summary>This URLConnection method just returns the result of <tt>lastModified</tt>.
  3354. /// </summary>
  3355. /// <remarks>This URLConnection method just returns the result of <tt>lastModified</tt>.
  3356. /// </remarks>
  3357. /// <returns>the last modified data as milliseconds since Jan 1, 1970</returns>
  3358. public long GetLastModified()
  3359. {
  3360. try
  3361. {
  3362. return LastModified();
  3363. }
  3364. catch (SmbException)
  3365. {
  3366. }
  3367. return 0L;
  3368. }
  3369. /// <summary>This URLConnection method just returns a new <tt>SmbFileInputStream</tt> created with this file.
  3370. /// </summary>
  3371. /// <remarks>This URLConnection method just returns a new <tt>SmbFileInputStream</tt> created with this file.
  3372. /// </remarks>
  3373. /// <exception cref="System.IO.IOException">thrown by <tt>SmbFileInputStream</tt> constructor
  3374. /// </exception>
  3375. public InputStream GetInputStream()
  3376. {
  3377. return new SmbFileInputStream(this);
  3378. }
  3379. /// <summary>This URLConnection method just returns a new <tt>SmbFileOutputStream</tt> created with this file.
  3380. /// </summary>
  3381. /// <remarks>This URLConnection method just returns a new <tt>SmbFileOutputStream</tt> created with this file.
  3382. /// </remarks>
  3383. /// <exception cref="System.IO.IOException">thrown by <tt>SmbFileOutputStream</tt> constructor
  3384. /// </exception>
  3385. public OutputStream GetOutputStream()
  3386. {
  3387. return new SmbFileOutputStream(this);
  3388. }
  3389. /// <exception cref="System.IO.IOException"></exception>
  3390. private void ProcessAces(Ace[] aces, bool resolveSids)
  3391. {
  3392. string server = GetServerWithDfs();
  3393. int ai;
  3394. if (resolveSids)
  3395. {
  3396. Sid[] sids = new Sid[aces.Length];
  3397. string[] names = null;
  3398. for (ai = 0; ai < aces.Length; ai++)
  3399. {
  3400. sids[ai] = aces[ai].Sid;
  3401. }
  3402. for (int off = 0; off < sids.Length; off += 64)
  3403. {
  3404. int len = sids.Length - off;
  3405. if (len > 64)
  3406. {
  3407. len = 64;
  3408. }
  3409. Sid.ResolveSids(server, Auth, sids, off, len);
  3410. }
  3411. }
  3412. else
  3413. {
  3414. for (ai = 0; ai < aces.Length; ai++)
  3415. {
  3416. aces[ai].Sid.OriginServer = server;
  3417. aces[ai].Sid.OriginAuth = Auth;
  3418. }
  3419. }
  3420. }
  3421. /// <summary>
  3422. /// Return an array of Access Control Entry (ACE) objects representing
  3423. /// the security descriptor associated with this file or directory.
  3424. /// </summary>
  3425. /// <remarks>
  3426. /// Return an array of Access Control Entry (ACE) objects representing
  3427. /// the security descriptor associated with this file or directory.
  3428. /// If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned.
  3429. /// </remarks>
  3430. /// <param name="resolveSids">
  3431. /// Attempt to resolve the SIDs within each ACE form
  3432. /// their numeric representation to their corresponding account names.
  3433. /// </param>
  3434. /// <exception cref="System.IO.IOException"></exception>
  3435. public virtual Ace[] GetSecurity(bool resolveSids)
  3436. {
  3437. int f;
  3438. Ace[] aces;
  3439. f = Open0(ORdonly, SmbConstants.ReadControl, 0, IsDirectory() ? 1 : 0);
  3440. NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x04);
  3441. NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(
  3442. );
  3443. try
  3444. {
  3445. Send(request, response);
  3446. }
  3447. finally
  3448. {
  3449. Close(f, 0L);
  3450. }
  3451. aces = response.SecurityDescriptor.Aces;
  3452. if (aces != null)
  3453. {
  3454. ProcessAces(aces, resolveSids);
  3455. }
  3456. return aces;
  3457. }
  3458. /// <summary>
  3459. /// Return an array of Access Control Entry (ACE) objects representing
  3460. /// the share permissions on the share exporting this file or directory.
  3461. /// </summary>
  3462. /// <remarks>
  3463. /// Return an array of Access Control Entry (ACE) objects representing
  3464. /// the share permissions on the share exporting this file or directory.
  3465. /// If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned.
  3466. /// <p>
  3467. /// Note that this is different from calling <tt>getSecurity</tt> on a
  3468. /// share. There are actually two different ACLs for shares - the ACL on
  3469. /// the share and the ACL on the folder being shared.
  3470. /// Go to <i>Computer Management</i>
  3471. /// &gt; <i>System Tools</i> &gt; <i>Shared Folders</i> &gt <i>Shares</i> and
  3472. /// look at the <i>Properties</i> for a share. You will see two tabs - one
  3473. /// for "Share Permissions" and another for "Security". These correspond to
  3474. /// the ACLs returned by <tt>getShareSecurity</tt> and <tt>getSecurity</tt>
  3475. /// respectively.
  3476. /// </remarks>
  3477. /// <param name="resolveSids">
  3478. /// Attempt to resolve the SIDs within each ACE form
  3479. /// their numeric representation to their corresponding account names.
  3480. /// </param>
  3481. /// <exception cref="System.IO.IOException"></exception>
  3482. public virtual Ace[] GetShareSecurity(bool resolveSids)
  3483. {
  3484. string p = Url.AbsolutePath;
  3485. MsrpcShareGetInfo rpc;
  3486. DcerpcHandle handle;
  3487. Ace[] aces;
  3488. ResolveDfs(null);
  3489. string server = GetServerWithDfs();
  3490. rpc = new MsrpcShareGetInfo(server, Tree.Share);
  3491. handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", Auth);
  3492. try
  3493. {
  3494. handle.Sendrecv(rpc);
  3495. if (rpc.Retval != 0)
  3496. {
  3497. throw new SmbException(rpc.Retval, true);
  3498. }
  3499. aces = rpc.GetSecurity();
  3500. if (aces != null)
  3501. {
  3502. ProcessAces(aces, resolveSids);
  3503. }
  3504. }
  3505. finally
  3506. {
  3507. try
  3508. {
  3509. handle.Close();
  3510. }
  3511. catch (IOException ioe)
  3512. {
  3513. if (Log.Level >= 1)
  3514. {
  3515. Runtime.PrintStackTrace(ioe, Log);
  3516. }
  3517. }
  3518. }
  3519. return aces;
  3520. }
  3521. /// <summary>
  3522. /// Return an array of Access Control Entry (ACE) objects representing
  3523. /// the security descriptor associated with this file or directory.
  3524. /// </summary>
  3525. /// <remarks>
  3526. /// Return an array of Access Control Entry (ACE) objects representing
  3527. /// the security descriptor associated with this file or directory.
  3528. /// <p>
  3529. /// Initially, the SIDs within each ACE will not be resolved however when
  3530. /// <tt>getType()</tt>, <tt>getDomainName()</tt>, <tt>getAccountName()</tt>,
  3531. /// or <tt>toString()</tt> is called, the names will attempt to be
  3532. /// resolved. If the names cannot be resolved (e.g. due to temporary
  3533. /// network failure), the said methods will return default values (usually
  3534. /// <tt>S-X-Y-Z</tt> strings of fragments of).
  3535. /// <p>
  3536. /// Alternatively <tt>getSecurity(true)</tt> may be used to resolve all
  3537. /// SIDs together and detect network failures.
  3538. /// </remarks>
  3539. /// <exception cref="System.IO.IOException"></exception>
  3540. public virtual Ace[] GetSecurity()
  3541. {
  3542. return GetSecurity(false);
  3543. }
  3544. }
  3545. }