TdsParser.cs 517 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373
  1. //------------------------------------------------------------------------------
  2. // <copyright file="TdsParser.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Data.Common;
  12. using System.Data.ProviderBase;
  13. using System.Data.Sql;
  14. using System.Data.SqlTypes;
  15. using System.Diagnostics;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Runtime.CompilerServices;
  19. using System.Runtime.InteropServices;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using System.Xml;
  24. using MSS = Microsoft.SqlServer.Server;
  25. // The TdsParser Object controls reading/writing to the netlib, parsing the tds,
  26. // and surfacing objects to the user.
  27. sealed internal class TdsParser {
  28. private static int _objectTypeCount; // Bid counter
  29. internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
  30. static Task completedTask;
  31. static Task CompletedTask {
  32. get {
  33. if (completedTask == null) {
  34. completedTask = Task.FromResult<object>(null);
  35. }
  36. return completedTask;
  37. }
  38. }
  39. internal int ObjectID {
  40. get {
  41. return _objectID;
  42. }
  43. }
  44. // ReliabilitySection Usage:
  45. //
  46. // #if DEBUG
  47. // TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  48. //
  49. // RuntimeHelpers.PrepareConstrainedRegions();
  50. // try {
  51. // tdsReliabilitySection.Start();
  52. // #else
  53. // {
  54. // #endif //DEBUG
  55. //
  56. // // code that requires reliability
  57. //
  58. // }
  59. // #if DEBUG
  60. // finally {
  61. // tdsReliabilitySection.Stop();
  62. // }
  63. // #endif //DEBUG
  64. internal struct ReliabilitySection {
  65. #if DEBUG
  66. // do not allocate TLS data in RETAIL bits
  67. [ThreadStatic]
  68. private static int s_reliabilityCount; // initialized to 0 by CLR
  69. private bool m_started; // initialized to false (not started) by CLR
  70. #endif //DEBUG
  71. [Conditional("DEBUG")]
  72. internal void Start() {
  73. #if DEBUG
  74. Debug.Assert(!m_started);
  75. RuntimeHelpers.PrepareConstrainedRegions();
  76. try {
  77. }
  78. finally {
  79. ++s_reliabilityCount;
  80. m_started = true;
  81. }
  82. #endif //DEBUG
  83. }
  84. [Conditional("DEBUG")]
  85. internal void Stop() {
  86. #if DEBUG
  87. // cannot assert m_started - ThreadAbortException can be raised before Start is called
  88. if (m_started) {
  89. Debug.Assert(s_reliabilityCount > 0);
  90. RuntimeHelpers.PrepareConstrainedRegions();
  91. try {
  92. }
  93. finally {
  94. --s_reliabilityCount;
  95. m_started = false;
  96. }
  97. }
  98. #endif //DEBUG
  99. }
  100. // you need to setup for a thread abort somewhere before you call this method
  101. [Conditional("DEBUG")]
  102. internal static void Assert(string message) {
  103. #if DEBUG
  104. Debug.Assert(s_reliabilityCount > 0, message);
  105. #endif //DEBUG
  106. }
  107. }
  108. // Default state object for parser
  109. internal TdsParserStateObject _physicalStateObj = null; // Default stateObj and connection for Dbnetlib and non-MARS SNI.
  110. // Also, default logical stateObj and connection for MARS over SNI.
  111. internal TdsParserStateObject _pMarsPhysicalConObj = null; // With MARS enabled, cached physical stateObj and connection.
  112. // Must keep this around - especially for callbacks on pre-MARS
  113. // ReadAsync which will return if physical connection broken!
  114. //
  115. // Per Instance TDS Parser variables
  116. //
  117. // Constants
  118. const int constBinBufferSize = 4096; // Size of the buffer used to read input parameter of type Stream
  119. const int constTextBufferSize = 4096; // Size of the buffer (in chars) user to read input parameter of type TextReader
  120. // State variables
  121. internal TdsParserState _state = TdsParserState.Closed; // status flag for connection
  122. private string _server = ""; // name of server that the parser connects to
  123. internal volatile bool _fResetConnection = false; // flag to denote whether we are needing to call sp_reset
  124. internal volatile bool _fPreserveTransaction = false; // flag to denote whether we need to preserve the transaction when reseting
  125. private SqlCollation _defaultCollation; // default collation from the server
  126. private int _defaultCodePage;
  127. private int _defaultLCID;
  128. internal Encoding _defaultEncoding = null; // for sql character data
  129. private static EncryptionOptions _sniSupportedEncryptionOption = SNILoadHandle.SingletonInstance.Options;
  130. private EncryptionOptions _encryptionOption = _sniSupportedEncryptionOption;
  131. private SqlInternalTransaction _currentTransaction;
  132. private SqlInternalTransaction _pendingTransaction; // pending transaction for Yukon and beyond.
  133. // SQLHOT 483
  134. // need to hold on to the transaction id if distributed transaction merely rolls back without defecting.
  135. private long _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
  136. // This counter is used for the entire connection to track the open result count for all
  137. // operations not under a transaction.
  138. private int _nonTransactedOpenResultCount = 0;
  139. // Connection reference
  140. private SqlInternalConnectionTds _connHandler;
  141. // Async/Mars variables
  142. private bool _fMARS = false;
  143. internal bool _loginWithFailover = false; // set to true while connect in failover mode so parser state object can adjust its logic
  144. internal AutoResetEvent _resetConnectionEvent = null; // Used to serialize executes and call reset on first execute only.
  145. internal TdsParserSessionPool _sessionPool = null; // initialized only when we're a MARS parser.
  146. // Version variables
  147. private bool _isShiloh = false; // set to true if we connect to a 8.0 server (SQL 2000) or later
  148. private bool _isShilohSP1 = false; // set to true if speaking to Shiloh SP1 or later
  149. private bool _isYukon = false; // set to true if speaking to Yukon or later
  150. private bool _isKatmai = false;
  151. private bool _isDenali = false;
  152. private byte[] _sniSpnBuffer = null;
  153. //
  154. // SqlStatistics
  155. private SqlStatistics _statistics = null;
  156. private bool _statisticsIsInTransaction = false;
  157. //
  158. // STATIC TDS Parser variables
  159. //
  160. // NIC address caching
  161. private static byte[] s_nicAddress; // cache the NIC address from the registry
  162. // SSPI variables
  163. private static bool s_fSSPILoaded = false; // bool to indicate whether library has been loaded
  164. private volatile static UInt32 s_maxSSPILength = 0; // variable to hold max SSPI data size, keep for token from server
  165. // ADAL variables
  166. private static bool s_fADALLoaded = false; // bool to indicate whether ADAL library has been loaded
  167. // textptr sequence
  168. private static readonly byte[] s_longDataHeader = { 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
  169. private static object s_tdsParserLock = new object();
  170. // Various other statics
  171. private const int ATTENTION_TIMEOUT = 5000; // internal attention timeout, in ticks
  172. // XML metadata substitue sequence
  173. private static readonly byte[] s_xmlMetadataSubstituteSequence = { 0xe7, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00 };
  174. // size of Guid (e.g. _clientConnectionId, ActivityId.Id)
  175. private const int GUID_SIZE = 16;
  176. // NOTE: You must take the internal connection's _parserLock before modifying this
  177. internal bool _asyncWrite = false;
  178. // TCE supported flag, used to determine if new TDS fields are present. This is
  179. // useful when talking to downlevel/uplevel server.
  180. private bool _serverSupportsColumnEncryption = false;
  181. /// <summary>
  182. /// Get or set if column encryption is supported by the server.
  183. /// </summary>
  184. internal bool IsColumnEncryptionSupported {
  185. get {
  186. return _serverSupportsColumnEncryption;
  187. }
  188. set {
  189. _serverSupportsColumnEncryption = value;
  190. }
  191. }
  192. internal TdsParser(bool MARS, bool fAsynchronous) {
  193. _fMARS = MARS; // may change during Connect to pre Yukon servers
  194. _physicalStateObj = new TdsParserStateObject(this);
  195. }
  196. internal SqlInternalConnectionTds Connection {
  197. get {
  198. return _connHandler;
  199. }
  200. }
  201. internal SqlInternalTransaction CurrentTransaction {
  202. get {
  203. return _currentTransaction;
  204. }
  205. set {
  206. Debug.Assert(value == _currentTransaction
  207. || null == _currentTransaction
  208. || null == value
  209. || (null != _currentTransaction && !_currentTransaction.IsLocal), "attempting to change current transaction?");
  210. // If there is currently a transaction active, we don't want to
  211. // change it; this can occur when there is a delegated transaction
  212. // and the user attempts to do an API begin transaction; in these
  213. // cases, it's safe to ignore the set.
  214. if ((null == _currentTransaction && null != value)
  215. ||(null != _currentTransaction && null == value)) {
  216. _currentTransaction = value;
  217. }
  218. }
  219. }
  220. internal int DefaultLCID {
  221. get {
  222. return _defaultLCID;
  223. }
  224. }
  225. internal EncryptionOptions EncryptionOptions {
  226. get {
  227. return _encryptionOption;
  228. }
  229. set {
  230. _encryptionOption = value;
  231. }
  232. }
  233. internal bool IsYukonOrNewer {
  234. get {
  235. return _isYukon;
  236. }
  237. }
  238. internal bool IsKatmaiOrNewer {
  239. get {
  240. return _isKatmai;
  241. }
  242. }
  243. internal bool MARSOn {
  244. get {
  245. return _fMARS;
  246. }
  247. }
  248. internal SqlInternalTransaction PendingTransaction {
  249. get {
  250. return _pendingTransaction;
  251. }
  252. set {
  253. Debug.Assert (null != value, "setting a non-null PendingTransaction?");
  254. _pendingTransaction = value;
  255. }
  256. }
  257. internal string Server {
  258. get {
  259. return _server;
  260. }
  261. }
  262. internal TdsParserState State {
  263. get {
  264. return _state;
  265. }
  266. set {
  267. _state = value;
  268. }
  269. }
  270. internal SqlStatistics Statistics {
  271. get {
  272. return _statistics;
  273. }
  274. set {
  275. _statistics = value;
  276. }
  277. }
  278. private bool IncludeTraceHeader {
  279. get {
  280. return (_isDenali && Bid.TraceOn && Bid.IsOn(ActivityCorrelator.CorrelationTracePoints));
  281. }
  282. }
  283. internal int IncrementNonTransactedOpenResultCount() {
  284. // IMPORTANT - this increments the connection wide open result count for all
  285. // operations not under a transaction! Do not call if you intend to modify the
  286. // count for a transaction!
  287. Debug.Assert(_nonTransactedOpenResultCount >= 0, "Unexpected result count state");
  288. int result = Interlocked.Increment(ref _nonTransactedOpenResultCount);
  289. return result;
  290. }
  291. internal void DecrementNonTransactedOpenResultCount() {
  292. // IMPORTANT - this decrements the connection wide open result count for all
  293. // operations not under a transaction! Do not call if you intend to modify the
  294. // count for a transaction!
  295. Interlocked.Decrement(ref _nonTransactedOpenResultCount);
  296. Debug.Assert(_nonTransactedOpenResultCount >= 0, "Unexpected result count state");
  297. }
  298. internal void ProcessPendingAck(TdsParserStateObject stateObj) {
  299. if (stateObj._attentionSent) {
  300. ProcessAttention(stateObj);
  301. }
  302. }
  303. internal void Connect(ServerInfo serverInfo,
  304. SqlInternalConnectionTds connHandler,
  305. bool ignoreSniOpenTimeout,
  306. long timerExpire,
  307. bool encrypt,
  308. bool trustServerCert,
  309. bool integratedSecurity,
  310. bool withFailover,
  311. bool isFirstTransparentAttempt,
  312. SqlAuthenticationMethod authType) {
  313. if (_state != TdsParserState.Closed) {
  314. Debug.Assert(false, "TdsParser.Connect called on non-closed connection!");
  315. return;
  316. }
  317. _connHandler = connHandler;
  318. _loginWithFailover = withFailover;
  319. UInt32 sniStatus = SNILoadHandle.SingletonInstance.SNIStatus;
  320. if (sniStatus != TdsEnums.SNI_SUCCESS) {
  321. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  322. _physicalStateObj.Dispose();
  323. ThrowExceptionAndWarning(_physicalStateObj);
  324. Debug.Assert(false, "SNI returned status != success, but no error thrown?");
  325. }
  326. //Create LocalDB instance if necessary
  327. if (connHandler.ConnectionOptions.LocalDBInstance != null)
  328. LocalDBAPI.CreateLocalDBInstance(connHandler.ConnectionOptions.LocalDBInstance);
  329. if (integratedSecurity || authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated) {
  330. LoadSSPILibrary();
  331. // now allocate proper length of buffer
  332. _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength];
  333. Bid.Trace("<sc.TdsParser.Connect|SEC> SSPI or Active Directory Authentication Library for SQL Server based integrated authentication\n");
  334. }
  335. else {
  336. _sniSpnBuffer = null;
  337. if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) {
  338. Bid.Trace("<sc.TdsParser.Connect|SEC> Active Directory Password authentication\n");
  339. }
  340. else if (authType == SqlAuthenticationMethod.SqlPassword) {
  341. Bid.Trace("<sc.TdsParser.Connect|SEC> SQL Password authentication\n");
  342. }
  343. else{
  344. Bid.Trace("<sc.TdsParser.Connect|SEC> SQL authentication\n");
  345. }
  346. }
  347. byte[] instanceName = null;
  348. Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point.");
  349. _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin);
  350. _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection);
  351. bool fParallel = _connHandler.ConnectionOptions.MultiSubnetFailover;
  352. TransparentNetworkResolutionState transparentNetworkResolutionState;
  353. if(_connHandler.ConnectionOptions.TransparentNetworkIPResolution)
  354. {
  355. if(isFirstTransparentAttempt)
  356. transparentNetworkResolutionState = TransparentNetworkResolutionState.SequentialMode;
  357. else
  358. transparentNetworkResolutionState = TransparentNetworkResolutionState.ParallelMode;
  359. }
  360. else
  361. transparentNetworkResolutionState = TransparentNetworkResolutionState.DisabledMode;
  362. int totalTimeout = _connHandler.ConnectionOptions.ConnectTimeout;
  363. _physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire,
  364. out instanceName, _sniSpnBuffer, false, true, fParallel, transparentNetworkResolutionState, totalTimeout);
  365. if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) {
  366. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  367. // Since connect failed, free the unmanaged connection memory.
  368. // HOWEVER - only free this after the netlib error was processed - if you
  369. // don't, the memory for the connection object might not be accurate and thus
  370. // a bad error could be returned (as it was when it was freed to early for me).
  371. _physicalStateObj.Dispose();
  372. Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Login failure\n");
  373. ThrowExceptionAndWarning(_physicalStateObj);
  374. Debug.Assert(false, "SNI returned status != success, but no error thrown?");
  375. }
  376. _server = serverInfo.ResolvedServerName;
  377. if (null != connHandler.PoolGroupProviderInfo) {
  378. // If we are pooling, check to see if we were processing an
  379. // alias which has changed, which means we need to clean out
  380. // the pool. See Webdata 104293.
  381. // This should not apply to routing, as it is not an alias change, routed connection
  382. // should still use VNN of AlwaysOn cluster as server for pooling purposes.
  383. connHandler.PoolGroupProviderInfo.AliasCheck(serverInfo.PreRoutingServerName==null ?
  384. serverInfo.ResolvedServerName: serverInfo.PreRoutingServerName);
  385. }
  386. _state = TdsParserState.OpenNotLoggedIn;
  387. _physicalStateObj.SniContext = SniContext.Snix_PreLoginBeforeSuccessfullWrite; // SQL BU DT 376766
  388. _physicalStateObj.TimeoutTime = timerExpire;
  389. bool marsCapable = false;
  390. _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection);
  391. _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
  392. UInt32 result = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId);
  393. Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
  394. //
  395. Bid.Trace("<sc.TdsParser.Connect|SEC> Sending prelogin handshake\n");
  396. SendPreLoginHandshake(instanceName, encrypt);
  397. _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
  398. _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake);
  399. _physicalStateObj.SniContext = SniContext.Snix_PreLogin;
  400. Bid.Trace("<sc.TdsParser.Connect|SEC> Consuming prelogin handshake\n");
  401. PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, out marsCapable,
  402. out _connHandler._fedAuthRequired);
  403. if (status == PreLoginHandshakeStatus.InstanceFailure) {
  404. Bid.Trace("<sc.TdsParser.Connect|SEC> Prelogin handshake unsuccessful. Reattempting prelogin handshake\n");
  405. _physicalStateObj.Dispose(); // Close previous connection
  406. // On Instance failure re-connect and flush SNI named instance cache.
  407. _physicalStateObj.SniContext=SniContext.Snix_Connect;
  408. _physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire, out instanceName, _sniSpnBuffer, true, true, fParallel, transparentNetworkResolutionState, totalTimeout);
  409. if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) {
  410. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  411. Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Login failure\n");
  412. ThrowExceptionAndWarning(_physicalStateObj);
  413. }
  414. UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId);
  415. Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
  416. Bid.Trace("<sc.TdsParser.Connect|SEC> Sending prelogin handshake\n");
  417. SendPreLoginHandshake(instanceName, encrypt);
  418. status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, out marsCapable,
  419. out _connHandler._fedAuthRequired);
  420. // Don't need to check for Sphinx failure, since we've already consumed
  421. // one pre-login packet and know we are connecting to Shiloh.
  422. if (status == PreLoginHandshakeStatus.InstanceFailure) {
  423. Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Prelogin handshake unsuccessful. Login failure\n");
  424. throw SQL.InstanceFailure();
  425. }
  426. }
  427. Bid.Trace("<sc.TdsParser.Connect|SEC> Prelogin handshake successful\n");
  428. if (_fMARS && marsCapable) {
  429. // if user explictly disables mars or mars not supported, don't create the session pool
  430. _sessionPool = new TdsParserSessionPool(this);
  431. }
  432. else {
  433. _fMARS = false;
  434. }
  435. if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword || (authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated && _connHandler._fedAuthRequired)) {
  436. Debug.Assert(!integratedSecurity, "The legacy Integrated Security connection string option cannot be true when using Active Directory Authentication Library for SQL Server Based workflows.");
  437. LoadADALLibrary();
  438. if (Bid.AdvancedOn) {
  439. Bid.Trace("<sc.TdsParser.Connect|SEC> Active directory authentication.Loaded Active Directory Authentication Library for SQL Server\n");
  440. }
  441. }
  442. return;
  443. }
  444. internal void RemoveEncryption() {
  445. Debug.Assert(_encryptionOption == EncryptionOptions.LOGIN, "Invalid encryption option state");
  446. UInt32 error = 0;
  447. // Remove SSL (Encryption) SNI provider since we only wanted to encrypt login.
  448. error = SNINativeMethodWrapper.SNIRemoveProvider(_physicalStateObj.Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV);
  449. if (error != TdsEnums.SNI_SUCCESS) {
  450. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  451. ThrowExceptionAndWarning(_physicalStateObj);
  452. }
  453. // create a new packet encryption changes the internal packet size Bug# 228403
  454. try {} // EmptyTry/Finally to avoid FXCop violation
  455. finally {
  456. _physicalStateObj.ClearAllWritePackets();
  457. }
  458. }
  459. internal void EnableMars() {
  460. if (_fMARS) {
  461. // Cache physical stateObj and connection.
  462. _pMarsPhysicalConObj = _physicalStateObj;
  463. UInt32 error = 0;
  464. UInt32 info = 0;
  465. // Add SMUX (MARS) SNI provider.
  466. error = SNINativeMethodWrapper.SNIAddProvider(_pMarsPhysicalConObj.Handle, SNINativeMethodWrapper.ProviderEnum.SMUX_PROV, ref info);
  467. if (error != TdsEnums.SNI_SUCCESS) {
  468. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  469. ThrowExceptionAndWarning(_physicalStateObj);
  470. }
  471. // HACK HACK HACK - for Async only
  472. // Have to post read to intialize MARS - will get callback on this when connection goes
  473. // down or is closed.
  474. IntPtr temp = IntPtr.Zero;
  475. RuntimeHelpers.PrepareConstrainedRegions();
  476. try {} finally {
  477. _pMarsPhysicalConObj.IncrementPendingCallbacks();
  478. error = SNINativeMethodWrapper.SNIReadAsync(_pMarsPhysicalConObj.Handle, ref temp);
  479. if (temp != IntPtr.Zero) {
  480. // Be sure to release packet, otherwise it will be leaked by native.
  481. SNINativeMethodWrapper.SNIPacketRelease(temp);
  482. }
  483. }
  484. Debug.Assert(IntPtr.Zero == temp, "unexpected syncReadPacket without corresponding SNIPacketRelease");
  485. if (TdsEnums.SNI_SUCCESS_IO_PENDING != error) {
  486. Debug.Assert(TdsEnums.SNI_SUCCESS != error, "Unexpected successfull read async on physical connection before enabling MARS!");
  487. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  488. ThrowExceptionAndWarning(_physicalStateObj);
  489. }
  490. _physicalStateObj = CreateSession(); // Create and open default MARS stateObj and connection.
  491. }
  492. }
  493. internal TdsParserStateObject CreateSession() {
  494. TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true);
  495. if (Bid.AdvancedOn) {
  496. Bid.Trace("<sc.TdsParser.CreateSession|ADV> %d# created session %d\n", ObjectID, session.ObjectID);
  497. }
  498. return session;
  499. }
  500. internal TdsParserStateObject GetSession(object owner) {
  501. TdsParserStateObject session = null;
  502. //
  503. if (MARSOn) {
  504. session = _sessionPool.GetSession(owner);
  505. Debug.Assert(!session._pendingData, "pending data on a pooled MARS session");
  506. if (Bid.AdvancedOn) {
  507. Bid.Trace("<sc.TdsParser.GetSession|ADV> %d# getting session %d from pool\n", ObjectID, session.ObjectID);
  508. }
  509. }
  510. else {
  511. session = _physicalStateObj;
  512. if (Bid.AdvancedOn) {
  513. Bid.Trace("<sc.TdsParser.GetSession|ADV> %d# getting physical session %d\n", ObjectID, session.ObjectID);
  514. }
  515. }
  516. Debug.Assert(session._outputPacketNumber==1, "The packet number is expected to be 1");
  517. return session;
  518. }
  519. internal void PutSession(TdsParserStateObject session) {
  520. session.AssertStateIsClean();
  521. if (MARSOn) {
  522. // This will take care of disposing if the parser is closed
  523. _sessionPool.PutSession(session);
  524. }
  525. else if ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken)) {
  526. // Parser is closed\broken - dispose the stateObj
  527. Debug.Assert(session == _physicalStateObj, "MARS is off, but session to close is not the _physicalStateObj");
  528. _physicalStateObj.SniContext = SniContext.Snix_Close;
  529. #if DEBUG
  530. _physicalStateObj.InvalidateDebugOnlyCopyOfSniContext();
  531. #endif
  532. _physicalStateObj.Dispose();
  533. }
  534. else {
  535. // Non-MARS, and session is ok - remove its owner
  536. _physicalStateObj.Owner = null;
  537. }
  538. }
  539. // This is called from a ThreadAbort - ensure that it can be run from a CER Catch
  540. internal void BestEffortCleanup() {
  541. _state = TdsParserState.Broken;
  542. var stateObj = _physicalStateObj;
  543. if (stateObj != null) {
  544. var stateObjHandle = stateObj.Handle;
  545. if (stateObjHandle != null) {
  546. stateObjHandle.Dispose();
  547. }
  548. }
  549. if (_fMARS) {
  550. var sessionPool = _sessionPool;
  551. if (sessionPool != null) {
  552. sessionPool.BestEffortCleanup();
  553. }
  554. var marsStateObj = _pMarsPhysicalConObj;
  555. if (marsStateObj != null) {
  556. var marsStateObjHandle = marsStateObj.Handle;
  557. if (marsStateObjHandle != null) {
  558. marsStateObjHandle.Dispose();
  559. }
  560. }
  561. }
  562. }
  563. private void SendPreLoginHandshake(byte[] instanceName, bool encrypt) {
  564. // PreLoginHandshake buffer consists of:
  565. // 1) Standard header, with type = MT_PRELOGIN
  566. // 2) Consecutive 5 bytes for each option, (1 byte length, 2 byte offset, 2 byte payload length)
  567. // 3) Consecutive data blocks for each option
  568. // NOTE: packet data needs to be big endian - not the standard little endian used by
  569. // the rest of the parser.
  570. _physicalStateObj._outputMessageType = TdsEnums.MT_PRELOGIN;
  571. // Initialize option offset into payload buffer
  572. // 5 bytes for each option (1 byte length, 2 byte offset, 2 byte payload length)
  573. int offset = (int)PreLoginOptions.NUMOPT * 5 + 1;
  574. byte[] payload = new byte[(int)PreLoginOptions.NUMOPT * 5 + TdsEnums.MAX_PRELOGIN_PAYLOAD_LENGTH];
  575. int payloadLength = 0;
  576. //
  577. for (int option = (int)PreLoginOptions.VERSION; option < (int)PreLoginOptions.NUMOPT; option++) {
  578. int optionDataSize = 0;
  579. // Fill in the option
  580. _physicalStateObj.WriteByte((byte)option);
  581. // Fill in the offset of the option data
  582. _physicalStateObj.WriteByte((byte)((offset & 0xff00) >> 8)); // send upper order byte
  583. _physicalStateObj.WriteByte((byte)(offset & 0x00ff)); // send lower order byte
  584. switch (option) {
  585. case (int)PreLoginOptions.VERSION:
  586. Version systemDataVersion = ADP.GetAssemblyVersion();
  587. // Major and minor
  588. payload[payloadLength++] = (byte)(systemDataVersion.Major & 0xff);
  589. payload[payloadLength++] = (byte)(systemDataVersion.Minor & 0xff);
  590. // Build (Big Endian)
  591. payload[payloadLength++] = (byte)((systemDataVersion.Build & 0xff00) >> 8);
  592. payload[payloadLength++] = (byte)(systemDataVersion.Build & 0xff);
  593. // Sub-build (Little Endian)
  594. payload[payloadLength++] = (byte)(systemDataVersion.Revision & 0xff);
  595. payload[payloadLength++] = (byte)((systemDataVersion.Revision & 0xff00) >> 8);
  596. offset += 6;
  597. optionDataSize = 6;
  598. break;
  599. case (int)PreLoginOptions.ENCRYPT:
  600. if (_encryptionOption == EncryptionOptions.NOT_SUP) {
  601. // If OS doesn't support encryption, inform server not supported.
  602. payload[payloadLength] = (byte)EncryptionOptions.NOT_SUP;
  603. }
  604. else {
  605. // Else, inform server of user request.
  606. if (encrypt) {
  607. payload[payloadLength] = (byte)EncryptionOptions.ON;
  608. _encryptionOption = EncryptionOptions.ON;
  609. }
  610. else {
  611. payload[payloadLength] = (byte)EncryptionOptions.OFF;
  612. _encryptionOption = EncryptionOptions.OFF;
  613. }
  614. }
  615. payloadLength += 1;
  616. offset += 1;
  617. optionDataSize = 1;
  618. break;
  619. case (int)PreLoginOptions.INSTANCE:
  620. int i = 0;
  621. while (instanceName[i] != 0) {
  622. payload[payloadLength] = instanceName[i];
  623. payloadLength++;
  624. i++;
  625. }
  626. payload[payloadLength] = 0; // null terminate
  627. payloadLength++;
  628. i++;
  629. offset += i;
  630. optionDataSize = i;
  631. break;
  632. case (int)PreLoginOptions.THREADID:
  633. Int32 threadID = TdsParserStaticMethods.GetCurrentThreadIdForTdsLoginOnly();
  634. payload[payloadLength++] = (byte)((0xff000000 & threadID) >> 24);
  635. payload[payloadLength++] = (byte)((0x00ff0000 & threadID) >> 16);
  636. payload[payloadLength++] = (byte)((0x0000ff00 & threadID) >> 8);
  637. payload[payloadLength++] = (byte)(0x000000ff & threadID);
  638. offset += 4;
  639. optionDataSize = 4;
  640. break;
  641. case (int)PreLoginOptions.MARS:
  642. payload[payloadLength++] = (byte)(_fMARS ? 1 : 0);
  643. offset += 1;
  644. optionDataSize += 1;
  645. break;
  646. case (int)PreLoginOptions.TRACEID:
  647. byte[] connectionIdBytes = _connHandler._clientConnectionId.ToByteArray();
  648. Debug.Assert(GUID_SIZE == connectionIdBytes.Length);
  649. Buffer.BlockCopy(connectionIdBytes, 0, payload, payloadLength, GUID_SIZE);
  650. payloadLength += GUID_SIZE;
  651. offset += GUID_SIZE;
  652. optionDataSize = GUID_SIZE;
  653. ActivityCorrelator.ActivityId actId = ActivityCorrelator.Next();
  654. connectionIdBytes = actId.Id.ToByteArray();
  655. Buffer.BlockCopy(connectionIdBytes, 0, payload, payloadLength, GUID_SIZE);
  656. payloadLength += GUID_SIZE;
  657. payload[payloadLength++] = (byte)(0x000000ff & actId.Sequence);
  658. payload[payloadLength++] = (byte)((0x0000ff00 & actId.Sequence) >> 8);
  659. payload[payloadLength++] = (byte)((0x00ff0000 & actId.Sequence) >> 16);
  660. payload[payloadLength++] = (byte)((0xff000000 & actId.Sequence) >> 24);
  661. int actIdSize = GUID_SIZE + sizeof(UInt32);
  662. offset += actIdSize;
  663. optionDataSize += actIdSize;
  664. Bid.Trace("<sc.TdsParser.SendPreLoginHandshake|INFO> ClientConnectionID %ls, ActivityID %ls\n", _connHandler._clientConnectionId.ToString(), actId.ToString());
  665. break;
  666. case (int)PreLoginOptions.FEDAUTHREQUIRED:
  667. payload[payloadLength++] = 0x01;
  668. offset += 1;
  669. optionDataSize += 1;
  670. break;
  671. default:
  672. Debug.Assert(false, "UNKNOWN option in SendPreLoginHandshake");
  673. break;
  674. }
  675. // Write data length
  676. _physicalStateObj.WriteByte((byte)((optionDataSize & 0xff00) >> 8));
  677. _physicalStateObj.WriteByte((byte)(optionDataSize & 0x00ff));
  678. }
  679. // Write out last option - to let server know the second part of packet completed
  680. _physicalStateObj.WriteByte((byte)PreLoginOptions.LASTOPT);
  681. // Write out payload
  682. _physicalStateObj.WriteByteArray(payload, payloadLength, 0);
  683. // Flush packet
  684. _physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
  685. }
  686. private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod authType, bool encrypt, bool trustServerCert, bool integratedSecurity, out bool marsCapable, out bool fedAuthRequired) {
  687. // Assign default values
  688. marsCapable = _fMARS;
  689. fedAuthRequired = false;
  690. bool isYukonOrLater = false;
  691. //
  692. Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  693. bool result = _physicalStateObj.TryReadNetworkPacket();
  694. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  695. if (_physicalStateObj._inBytesRead == 0) {
  696. // If the server did not respond then something has gone wrong and we need to close the connection
  697. _physicalStateObj.AddError(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.PreloginError(), "", 0));
  698. _physicalStateObj.Dispose();
  699. ThrowExceptionAndWarning(_physicalStateObj);
  700. }
  701. // SEC
  702. byte[] payload = new byte[_physicalStateObj._inBytesRead - _physicalStateObj._inBytesUsed - _physicalStateObj._inputHeaderLen];
  703. Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  704. result = _physicalStateObj.TryReadByteArray(payload, 0, payload.Length);
  705. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  706. if (payload[0] == 0xaa) {
  707. // If the first byte is 0xAA, we are connecting to a 6.5 or earlier server, which
  708. // is not supported. SQL BU DT 296425
  709. throw SQL.InvalidSQLServerVersionUnknown();
  710. }
  711. int offset = 0;
  712. int payloadOffset = 0;
  713. int payloadLength = 0;
  714. int option = payload[offset++];
  715. while (option != (byte)PreLoginOptions.LASTOPT) {
  716. switch (option) {
  717. case (int)PreLoginOptions.VERSION:
  718. payloadOffset = payload[offset++] << 8 | payload[offset++];
  719. payloadLength = payload[offset++] << 8 | payload[offset++];
  720. byte majorVersion = payload[payloadOffset];
  721. byte minorVersion = payload[payloadOffset + 1];
  722. int level = (payload[payloadOffset + 2] << 8) |
  723. payload[payloadOffset + 3];
  724. isYukonOrLater = majorVersion >= 9;
  725. if (!isYukonOrLater) {
  726. marsCapable = false; // If pre-Yukon, MARS not supported.
  727. }
  728. break;
  729. case (int)PreLoginOptions.ENCRYPT:
  730. payloadOffset = payload[offset++] << 8 | payload[offset++];
  731. payloadLength = payload[offset++] << 8 | payload[offset++];
  732. EncryptionOptions serverOption = (EncryptionOptions)payload[payloadOffset];
  733. /* internal enum EncryptionOptions {
  734. OFF,
  735. ON,
  736. NOT_SUP,
  737. REQ,
  738. LOGIN
  739. } */
  740. switch (_encryptionOption) {
  741. case (EncryptionOptions.ON):
  742. if (serverOption == EncryptionOptions.NOT_SUP) {
  743. _physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByServer(), "", 0));
  744. _physicalStateObj.Dispose();
  745. ThrowExceptionAndWarning(_physicalStateObj);
  746. }
  747. break;
  748. case (EncryptionOptions.OFF):
  749. if (serverOption == EncryptionOptions.OFF) {
  750. // Only encrypt login.
  751. _encryptionOption = EncryptionOptions.LOGIN;
  752. }
  753. else if (serverOption == EncryptionOptions.REQ) {
  754. // Encrypt all.
  755. _encryptionOption = EncryptionOptions.ON;
  756. }
  757. break;
  758. case (EncryptionOptions.NOT_SUP):
  759. if (serverOption == EncryptionOptions.REQ) {
  760. _physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByClient(), "", 0));
  761. _physicalStateObj.Dispose();
  762. ThrowExceptionAndWarning(_physicalStateObj);
  763. }
  764. break;
  765. default:
  766. Debug.Assert(false, "Invalid client encryption option detected");
  767. break;
  768. }
  769. if (_encryptionOption == EncryptionOptions.ON ||
  770. _encryptionOption == EncryptionOptions.LOGIN) {
  771. UInt32 error = 0;
  772. // If we're using legacy server certificate validation behavior (Authentication keyword not provided and not using access token), then validate if
  773. // Encrypt=true and Trust Sever Certificate = false.
  774. // If using Authentication keyword or access token, validate if Trust Server Certificate=false.
  775. bool shouldValidateServerCert = (encrypt && !trustServerCert) || ((authType != SqlAuthenticationMethod.NotSpecified || _connHandler._accessTokenInBytes != null) && !trustServerCert);
  776. UInt32 info = (shouldValidateServerCert ? TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE : 0)
  777. | (isYukonOrLater ? TdsEnums.SNI_SSL_USE_SCHANNEL_CACHE : 0);
  778. if (encrypt && !integratedSecurity) {
  779. // optimization: in case of SQL Authentication and encryption, set SNI_SSL_IGNORE_CHANNEL_BINDINGS to let SNI
  780. // know that it does not need to allocate/retrieve the Channel Bindings from the SSL context.
  781. info |= TdsEnums.SNI_SSL_IGNORE_CHANNEL_BINDINGS;
  782. }
  783. // Add SSL (Encryption) SNI provider.
  784. error = SNINativeMethodWrapper.SNIAddProvider(_physicalStateObj.Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV, ref info);
  785. if (error != TdsEnums.SNI_SUCCESS) {
  786. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  787. ThrowExceptionAndWarning(_physicalStateObj);
  788. }
  789. // in the case where an async connection is made, encryption is used and Windows Authentication is used,
  790. // wait for SSL handshake to complete, so that the SSL context is fully negotiated before we try to use its
  791. // Channel Bindings as part of the Windows Authentication context build (SSL handshake must complete
  792. // before calling SNISecGenClientContext).
  793. error = SNINativeMethodWrapper.SNIWaitForSSLHandshakeToComplete(_physicalStateObj.Handle, _physicalStateObj.GetTimeoutRemaining());
  794. if (error != TdsEnums.SNI_SUCCESS)
  795. {
  796. _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
  797. ThrowExceptionAndWarning(_physicalStateObj);
  798. }
  799. // create a new packet encryption changes the internal packet size Bug# 228403
  800. try {} // EmptyTry/Finally to avoid FXCop violation
  801. finally {
  802. _physicalStateObj.ClearAllWritePackets();
  803. }
  804. }
  805. break;
  806. case (int)PreLoginOptions.INSTANCE:
  807. payloadOffset = payload[offset++] << 8 | payload[offset++];
  808. payloadLength = payload[offset++] << 8 | payload[offset++];
  809. byte ERROR_INST = 0x1;
  810. byte instanceResult = payload[payloadOffset];
  811. if (instanceResult == ERROR_INST) {
  812. // Check if server says ERROR_INST. That either means the cached info
  813. // we used to connect is not valid or we connected to a named instance
  814. // listening on default params.
  815. return PreLoginHandshakeStatus.InstanceFailure;
  816. }
  817. break;
  818. case (int)PreLoginOptions.THREADID:
  819. // DO NOTHING FOR THREADID
  820. offset += 4;
  821. break;
  822. case (int)PreLoginOptions.MARS:
  823. payloadOffset = payload[offset++] << 8 | payload[offset++];
  824. payloadLength = payload[offset++] << 8 | payload[offset++];
  825. marsCapable = (payload[payloadOffset] == 0 ? false : true);
  826. Debug.Assert(payload[payloadOffset] == 0 || payload[payloadOffset] == 1, "Value for Mars PreLoginHandshake option not equal to 1 or 0!");
  827. break;
  828. case (int)PreLoginOptions.TRACEID:
  829. // DO NOTHING FOR TRACEID
  830. offset += 4;
  831. break;
  832. case (int)PreLoginOptions.FEDAUTHREQUIRED:
  833. payloadOffset = payload[offset++] << 8 | payload[offset++];
  834. payloadLength = payload[offset++] << 8 | payload[offset++];
  835. // Only 0x00 and 0x01 are accepted values from the server.
  836. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) {
  837. Bid.Trace("<sc.TdsParser.ConsumePreLoginHandshake|ERR> %d#, Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was %d.\n", ObjectID, (int)payload[payloadOffset]);
  838. throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]);
  839. }
  840. // We must NOT use the response for the FEDAUTHREQUIRED PreLogin option, if the connection string option
  841. // was not using the new Authentication keyword or in other words, if Authentication=NotSpecified
  842. // Or AccessToken is not null, mean token based authentication is used.
  843. if ((_connHandler.ConnectionOptions != null
  844. && _connHandler.ConnectionOptions.Authentication != SqlAuthenticationMethod.NotSpecified)
  845. || _connHandler._accessTokenInBytes != null)
  846. {
  847. fedAuthRequired = payload[payloadOffset] == 0x01 ? true : false;
  848. }
  849. break;
  850. default:
  851. Debug.Assert(false, "UNKNOWN option in ConsumePreLoginHandshake, option:" + option);
  852. // DO NOTHING FOR THESE UNKNOWN OPTIONS
  853. offset += 4;
  854. break;
  855. }
  856. if (offset < payload.Length) {
  857. option = payload[offset++];
  858. }
  859. else {
  860. break;
  861. }
  862. }
  863. return PreLoginHandshakeStatus.Successful;
  864. }
  865. internal void Deactivate(bool connectionIsDoomed) {
  866. // Called when the connection that owns us is deactivated.
  867. if (Bid.AdvancedOn) {
  868. Bid.Trace("<sc.TdsParser.Deactivate|ADV> %d# deactivating\n", ObjectID);
  869. }
  870. if (Bid.IsOn(Bid.ApiGroup.StateDump)) {
  871. Bid.Trace("<sc.TdsParser.Deactivate|STATE> %d#, %ls\n", ObjectID, TraceString());
  872. }
  873. if (MARSOn) {
  874. _sessionPool.Deactivate();
  875. }
  876. Debug.Assert(connectionIsDoomed || null == _pendingTransaction, "pending transaction at disconnect?");
  877. if (!connectionIsDoomed && null != _physicalStateObj) {
  878. if (_physicalStateObj._pendingData) {
  879. DrainData(_physicalStateObj);
  880. }
  881. if (_physicalStateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount for all pending operations.
  882. _physicalStateObj.DecrementOpenResultCount();
  883. }
  884. }
  885. // Any active, non-distributed transaction must be rolled back. We
  886. // need to wait for distributed transactions to be completed by the
  887. // transaction manager -- we don't want to automatically roll them
  888. // back.
  889. //
  890. // Note that when there is a transaction delegated to this connection,
  891. // we will defer the deactivation of this connection until the
  892. // transaction manager completes the transaction.
  893. SqlInternalTransaction currentTransaction = CurrentTransaction;
  894. if (null != currentTransaction && currentTransaction.HasParentTransaction) {
  895. currentTransaction.CloseFromConnection();
  896. Debug.Assert(null == CurrentTransaction, "rollback didn't clear current transaction?");
  897. }
  898. Statistics = null; // must come after CleanWire or we won't count the stuff that happens there...
  899. }
  900. // Used to close the connection and then free the memory allocated for the netlib connection.
  901. internal void Disconnect() {
  902. if (null != _sessionPool) {
  903. // MARSOn may be true, but _sessionPool not yet created
  904. _sessionPool.Dispose();
  905. }
  906. // Can close the connection if its open or broken
  907. if (_state != TdsParserState.Closed) {
  908. //benign assert - the user could close the connection before consuming all the data
  909. //Debug.Assert(_physicalStateObj._inBytesUsed == _physicalStateObj._inBytesRead && _physicalStateObj._outBytesUsed == _physicalStateObj._inputHeaderLen, "TDSParser closed with data not fully sent or consumed.");
  910. _state = TdsParserState.Closed;
  911. try {
  912. // If the _physicalStateObj has an owner, we will delay the disposal until the owner is finished with it
  913. if (!_physicalStateObj.HasOwner) {
  914. _physicalStateObj.SniContext = SniContext.Snix_Close;
  915. #if DEBUG
  916. _physicalStateObj.InvalidateDebugOnlyCopyOfSniContext();
  917. #endif
  918. _physicalStateObj.Dispose();
  919. }
  920. else {
  921. // Remove the "initial" callback (this will allow the stateObj to be GC collected if need be)
  922. _physicalStateObj.DecrementPendingCallbacks(false);
  923. }
  924. // Not allocated until MARS is actually enabled in SNI.
  925. if (null != _pMarsPhysicalConObj) {
  926. _pMarsPhysicalConObj.Dispose();
  927. }
  928. }
  929. finally {
  930. _pMarsPhysicalConObj = null;
  931. }
  932. }
  933. }
  934. // Fires a single InfoMessageEvent
  935. private void FireInfoMessageEvent(SqlConnection connection, TdsParserStateObject stateObj, SqlError error) {
  936. string serverVersion = null;
  937. Debug.Assert(connection != null && _connHandler.Connection == connection);
  938. if (_state == TdsParserState.OpenLoggedIn) {
  939. serverVersion = _connHandler.ServerVersion;
  940. }
  941. SqlErrorCollection sqlErs = new SqlErrorCollection();
  942. sqlErs.Add(error);
  943. SqlException exc = SqlException.CreateException(sqlErs, serverVersion, _connHandler);
  944. bool notified;
  945. connection.OnInfoMessage(new SqlInfoMessageEventArgs(exc), out notified);
  946. if (notified) {
  947. // observable side-effects, no retry
  948. stateObj._syncOverAsync = true;
  949. }
  950. return;
  951. }
  952. internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) {
  953. Debug.Assert(_currentTransaction != null && _currentTransaction == internalTransaction, "disconnecting different transaction");
  954. if (_currentTransaction != null && _currentTransaction == internalTransaction) {
  955. _currentTransaction = null;
  956. }
  957. }
  958. internal void RollbackOrphanedAPITransactions() {
  959. // Any active, non-distributed transaction must be rolled back.
  960. SqlInternalTransaction currentTransaction = CurrentTransaction;
  961. if (null != currentTransaction && currentTransaction.HasParentTransaction && currentTransaction.IsOrphaned) {
  962. currentTransaction.CloseFromConnection();
  963. Debug.Assert(null == CurrentTransaction, "rollback didn't clear current transaction?");
  964. }
  965. }
  966. internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool callerHasConnectionLock = false, bool asyncClose = false) {
  967. Debug.Assert(!callerHasConnectionLock || _connHandler._parserLock.ThreadMayHaveLock(), "Caller claims to have lock, but connection lock is not taken");
  968. SqlException exception = null;
  969. bool breakConnection;
  970. // This function should only be called when there was an error or warning. If there aren't any
  971. // errors, the handler will be called for the warning(s). If there was an error, the warning(s) will
  972. // be copied to the end of the error collection so that the user may see all the errors and also the
  973. // warnings that occurred.
  974. // can be deleted)
  975. SqlErrorCollection temp = stateObj.GetFullErrorAndWarningCollection(out breakConnection);
  976. Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!");
  977. if (temp.Count == 0)
  978. {
  979. Bid.Trace("<sc.TdsParser.ThrowExceptionAndWarning|ERR> Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock %d#\n", ObjectID);
  980. }
  981. Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!");
  982. // Don't break the connection if it is already closed
  983. breakConnection &= (TdsParserState.Closed != _state);
  984. if (breakConnection) {
  985. if ((_state == TdsParserState.OpenNotLoggedIn) && (_connHandler.ConnectionOptions.TransparentNetworkIPResolution || _connHandler.ConnectionOptions.MultiSubnetFailover || _loginWithFailover) && (temp.Count == 1) && ((temp[0].Number == TdsEnums.TIMEOUT_EXPIRED) || (temp[0].Number == TdsEnums.SNI_WAIT_TIMEOUT))) {
  986. // DevDiv2 Bug 459546: With "MultiSubnetFailover=yes" in the Connection String, SQLClient incorrectly throws a Timeout using shorter time slice (3-4 seconds), not honoring the actual 'Connect Timeout'
  987. // http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/459546
  988. // For Multisubnet Failover we slice the timeout to make reconnecting faster (with the assumption that the server will not failover instantaneously)
  989. // However, when timeout occurs we need to not doom the internal connection and also to mark the TdsParser as closed such that the login will be will retried
  990. breakConnection = false;
  991. Disconnect();
  992. }
  993. else {
  994. _state = TdsParserState.Broken;
  995. }
  996. }
  997. Debug.Assert(temp != null, "TdsParser::ThrowExceptionAndWarning: 0 errors in collection");
  998. if (temp != null && temp.Count > 0) {
  999. // Construct the exception now that we've collected all the errors
  1000. string serverVersion = null;
  1001. if (_state == TdsParserState.OpenLoggedIn) {
  1002. serverVersion = _connHandler.ServerVersion;
  1003. }
  1004. exception = SqlException.CreateException(temp, serverVersion, _connHandler);
  1005. if (exception.Procedure == TdsEnums.INIT_ADAL_PACKAGE || exception.Procedure == TdsEnums.INIT_SSPI_PACKAGE) {
  1006. exception._doNotReconnect = true;
  1007. }
  1008. }
  1009. // call OnError outside of _ErrorCollectionLock to avoid deadlock
  1010. if (exception != null) {
  1011. if (breakConnection) {
  1012. // report exception to pending async operation
  1013. // before OnConnectionClosed overrides the exception
  1014. // due to connection close notification through references
  1015. var taskSource = stateObj._networkPacketTaskSource;
  1016. if (taskSource != null) {
  1017. taskSource.TrySetException(ADP.ExceptionWithStackTrace(exception));
  1018. }
  1019. }
  1020. if (asyncClose) {
  1021. // Wait until we have the parser lock, then try to close
  1022. var connHandler = _connHandler;
  1023. Action<Action> wrapCloseAction = closeAction => {
  1024. Task.Factory.StartNew(() => {
  1025. connHandler._parserLock.Wait(canReleaseFromAnyThread: false);
  1026. connHandler.ThreadHasParserLockForClose = true;
  1027. try {
  1028. closeAction();
  1029. }
  1030. finally {
  1031. connHandler.ThreadHasParserLockForClose = false;
  1032. connHandler._parserLock.Release();
  1033. }
  1034. });
  1035. };
  1036. _connHandler.OnError(exception, breakConnection, wrapCloseAction);
  1037. }
  1038. else {
  1039. // Let close know that we already have the _parserLock
  1040. bool threadAlreadyHadParserLockForClose = _connHandler.ThreadHasParserLockForClose;
  1041. if (callerHasConnectionLock) {
  1042. _connHandler.ThreadHasParserLockForClose = true;
  1043. }
  1044. try {
  1045. // the following handler will throw an exception or generate a warning event
  1046. _connHandler.OnError(exception, breakConnection);
  1047. }
  1048. finally {
  1049. if (callerHasConnectionLock) {
  1050. _connHandler.ThreadHasParserLockForClose = threadAlreadyHadParserLockForClose;
  1051. }
  1052. }
  1053. }
  1054. }
  1055. }
  1056. internal SqlError ProcessSNIError(TdsParserStateObject stateObj) {
  1057. #if DEBUG
  1058. // There is an exception here for MARS as its possible that another thread has closed the connection just as we see an error
  1059. Debug.Assert(SniContext.Undefined!=stateObj.DebugOnlyCopyOfSniContext || ((_fMARS) && ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))), "SniContext must not be None");
  1060. #endif
  1061. SNINativeMethodWrapper.SNI_Error sniError = new SNINativeMethodWrapper.SNI_Error();
  1062. SNINativeMethodWrapper.SNIGetLastError(sniError);
  1063. if (sniError.sniError != 0) {
  1064. // handle special SNI error codes that are converted into exception which is not a SqlException.
  1065. switch (sniError.sniError) {
  1066. case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs:
  1067. // Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported.
  1068. throw SQL.MultiSubnetFailoverWithMoreThan64IPs();
  1069. case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified:
  1070. // Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported.
  1071. throw SQL.MultiSubnetFailoverWithInstanceSpecified();
  1072. case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol:
  1073. // Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol.
  1074. throw SQL.MultiSubnetFailoverWithNonTcpProtocol();
  1075. // continue building SqlError instance
  1076. }
  1077. }
  1078. // error.errorMessage is null terminated with garbage beyond that, since fixed length
  1079. string errorMessage;
  1080. int MessageLength = Array.IndexOf(sniError.errorMessage, '\0');
  1081. if (MessageLength == -1) {
  1082. errorMessage = String.Empty; // If we don't see the expected null return nothing.
  1083. } else {
  1084. errorMessage = new String(sniError.errorMessage, 0, MessageLength);
  1085. }
  1086. // Format SNI errors and add Context Information
  1087. //
  1088. // General syntax is:
  1089. // <sqlclient message>
  1090. // (provider:<SNIx provider>, error: <SNIx error code> - <SNIx error message>)
  1091. //
  1092. // errorMessage | sniError |
  1093. // -------------------------------------------
  1094. // ==null | x | must never happen
  1095. // !=null | != 0 | retrieve corresponding errorMessage from resources
  1096. // !=null | == 0 | replace text left of errorMessage
  1097. //
  1098. Debug.Assert(!ADP.IsEmpty(errorMessage),"Empty error message received from SNI");
  1099. string sqlContextInfo = Res.GetString(Enum.GetName(typeof(SniContext), stateObj.SniContext));
  1100. string providerRid = String.Format((IFormatProvider)null,"SNI_PN{0}", (int)sniError.provider);
  1101. string providerName = Res.GetString(providerRid);
  1102. Debug.Assert(!ADP.IsEmpty(providerName), String.Format((IFormatProvider)null,"invalid providerResourceId '{0}'", providerRid));
  1103. uint win32ErrorCode = sniError.nativeError;
  1104. if (sniError.sniError == 0) {
  1105. // Provider error. The message from provider is preceeded with non-localizable info from SNI
  1106. // strip provider info from SNI
  1107. //
  1108. int iColon = errorMessage.IndexOf(':');
  1109. Debug.Assert(0<=iColon, "':' character missing in sni errorMessage");
  1110. Debug.Assert(errorMessage.Length>iColon+1 && errorMessage[iColon+1]==' ', "Expecting a space after the ':' character");
  1111. // extract the message excluding the colon and trailing cr/lf chars
  1112. if (0<=iColon) {
  1113. int len = errorMessage.Length;
  1114. len -=2; // exclude "\r\n" sequence
  1115. iColon+=2; // skip over ": " sequence
  1116. len-=iColon;
  1117. /*
  1118. The error message should come back in the following format: "TCP Provider: MESSAGE TEXT"
  1119. Fix Bug 370686, if the message is recieved on a Win9x OS, the error message will not contain MESSAGE TEXT
  1120. per Bug: 269574. If we get a errormessage with no message text, just return the entire message otherwise
  1121. return just the message text.
  1122. */
  1123. if (len > 0) {
  1124. errorMessage = errorMessage.Substring(iColon, len);
  1125. }
  1126. }
  1127. }
  1128. else {
  1129. // SNI error. Replace the entire message
  1130. //
  1131. errorMessage = SQL.GetSNIErrorMessage((int)sniError.sniError);
  1132. // If its a LocalDB error, then nativeError actually contains a LocalDB-specific error code, not a win32 error code
  1133. if (sniError.sniError == (int)SNINativeMethodWrapper.SniSpecialErrors.LocalDBErrorCode) {
  1134. errorMessage += LocalDBAPI.GetLocalDBMessage((int)sniError.nativeError);
  1135. win32ErrorCode = 0;
  1136. }
  1137. }
  1138. errorMessage = String.Format((IFormatProvider)null, "{0} (provider: {1}, error: {2} - {3})",
  1139. sqlContextInfo, providerName, (int)sniError.sniError, errorMessage);
  1140. return new SqlError((int)sniError.nativeError, 0x00, TdsEnums.FATAL_ERROR_CLASS,
  1141. _server, errorMessage, sniError.function, (int)sniError.lineNumber, win32ErrorCode);
  1142. }
  1143. internal void CheckResetConnection(TdsParserStateObject stateObj) {
  1144. if (_fResetConnection && !stateObj._fResetConnectionSent) {
  1145. Debug.Assert(stateObj._outputPacketNumber == 1 || stateObj._outputPacketNumber == 2, "In ResetConnection logic unexpectedly!");
  1146. try {
  1147. if (_fMARS && !stateObj._fResetEventOwned) {
  1148. // If using Async & MARS and we do not own ResetEvent - grab it. We need to not grab lock here
  1149. // for case where multiple packets are sent to server from one execute.
  1150. stateObj._fResetEventOwned = _resetConnectionEvent.WaitOne(stateObj.GetTimeoutRemaining(), false);
  1151. if (stateObj._fResetEventOwned) {
  1152. if (stateObj.TimeoutHasExpired) {
  1153. // We didn't timeout on the WaitOne, but we timed out by the time we decremented stateObj._timeRemaining.
  1154. stateObj._fResetEventOwned = !_resetConnectionEvent.Set();
  1155. stateObj.TimeoutTime = 0;
  1156. }
  1157. }
  1158. if (!stateObj._fResetEventOwned) {
  1159. // We timed out waiting for ResetEvent. Throw timeout exception and reset
  1160. // the buffer. Nothing else to do since we did not actually send anything
  1161. // to the server.
  1162. stateObj.ResetBuffer();
  1163. Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point.");
  1164. stateObj.AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _server, _connHandler.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
  1165. Debug.Assert(_connHandler._parserLock.ThreadMayHaveLock(), "Thread is writing without taking the connection lock");
  1166. ThrowExceptionAndWarning(stateObj, callerHasConnectionLock: true);
  1167. }
  1168. }
  1169. if (_fResetConnection) {
  1170. // Check again to see if we need to send reset.
  1171. Debug.Assert(!stateObj._fResetConnectionSent, "Unexpected state for sending reset connection");
  1172. Debug.Assert(_isShiloh, "TdsParser.cs: Error! _fResetConnection true when not going against Shiloh or later!");
  1173. if (_fPreserveTransaction) {
  1174. // if we are reseting, set bit in header by or'ing with other value
  1175. stateObj._outBuff[1] = (Byte)(stateObj._outBuff[1] | TdsEnums.ST_RESET_CONNECTION_PRESERVE_TRANSACTION);
  1176. }
  1177. else {
  1178. // if we are reseting, set bit in header by or'ing with other value
  1179. stateObj._outBuff[1] = (Byte)(stateObj._outBuff[1] | TdsEnums.ST_RESET_CONNECTION);
  1180. }
  1181. if (!_fMARS) {
  1182. _fResetConnection = false; // If not MARS, can turn off flag now.
  1183. _fPreserveTransaction = false;
  1184. }
  1185. else {
  1186. stateObj._fResetConnectionSent = true; // Otherwise set flag so we don't resend on multiple packet execute.
  1187. }
  1188. }
  1189. else if (_fMARS && stateObj._fResetEventOwned) {
  1190. Debug.Assert(!stateObj._fResetConnectionSent, "Unexpected state on WritePacket ResetConnection");
  1191. // Otherwise if Yukon and we grabbed the event, free it. Another execute grabbed the event and
  1192. // took care of sending the reset.
  1193. stateObj._fResetEventOwned = !_resetConnectionEvent.Set();
  1194. Debug.Assert(!stateObj._fResetEventOwned, "Invalid AutoResetEvent state!");
  1195. }
  1196. }
  1197. catch (Exception) {
  1198. if (_fMARS && stateObj._fResetEventOwned) {
  1199. // If exception thrown, and we are on Yukon and own the event, release it!
  1200. stateObj._fResetConnectionSent = false;
  1201. stateObj._fResetEventOwned = !_resetConnectionEvent.Set();
  1202. Debug.Assert(!stateObj._fResetEventOwned, "Invalid AutoResetEvent state!");
  1203. }
  1204. throw;
  1205. }
  1206. }
  1207. #if DEBUG
  1208. else {
  1209. Debug.Assert(!_fResetConnection ||
  1210. (_fResetConnection && stateObj._fResetConnectionSent && stateObj._fResetEventOwned),
  1211. "Unexpected state on else ResetConnection block in WritePacket");
  1212. }
  1213. #endif
  1214. }
  1215. //
  1216. // Takes a 16 bit short and writes it.
  1217. //
  1218. internal byte[] SerializeShort(int v, TdsParserStateObject stateObj) {
  1219. if (null == stateObj._bShortBytes) {
  1220. stateObj._bShortBytes = new byte[2];
  1221. }
  1222. else {
  1223. Debug.Assert(2 == stateObj._bShortBytes.Length);
  1224. }
  1225. byte[] bytes = stateObj._bShortBytes;
  1226. int current = 0;
  1227. bytes[current++] = (byte)(v & 0xff);
  1228. bytes[current++] = (byte)((v >> 8) & 0xff);
  1229. return bytes;
  1230. }
  1231. internal void WriteShort(int v, TdsParserStateObject stateObj) {
  1232. ReliabilitySection.Assert("unreliable call to WriteShort"); // you need to setup for a thread abort somewhere before you call this method
  1233. if ((stateObj._outBytesUsed + 2) > stateObj._outBuff.Length) {
  1234. // if all of the short doesn't fit into the buffer
  1235. stateObj.WriteByte((byte)(v & 0xff));
  1236. stateObj.WriteByte((byte)((v >> 8) & 0xff));
  1237. }
  1238. else {
  1239. // all of the short fits into the buffer
  1240. stateObj._outBuff[stateObj._outBytesUsed] = (byte)(v & 0xff);
  1241. stateObj._outBuff[stateObj._outBytesUsed + 1] = (byte)((v >> 8) & 0xff);
  1242. stateObj._outBytesUsed += 2;
  1243. }
  1244. }
  1245. internal void WriteUnsignedShort(ushort us, TdsParserStateObject stateObj) {
  1246. WriteShort((short)us, stateObj);
  1247. }
  1248. //
  1249. // Takes a long and writes out an unsigned int
  1250. //
  1251. internal byte[] SerializeUnsignedInt(uint i, TdsParserStateObject stateObj) {
  1252. return SerializeInt((int)i, stateObj);
  1253. }
  1254. internal void WriteUnsignedInt(uint i, TdsParserStateObject stateObj) {
  1255. WriteInt((int)i, stateObj);
  1256. }
  1257. //
  1258. // Takes an int and writes it as an int.
  1259. //
  1260. internal byte[] SerializeInt(int v, TdsParserStateObject stateObj) {
  1261. if (null == stateObj._bIntBytes) {
  1262. stateObj._bIntBytes = new byte[4];
  1263. }
  1264. else {
  1265. Debug.Assert (4 == stateObj._bIntBytes.Length);
  1266. }
  1267. int current = 0;
  1268. byte[] bytes = stateObj._bIntBytes;
  1269. bytes[current++] = (byte)(v & 0xff);
  1270. bytes[current++] = (byte)((v >> 8) & 0xff);
  1271. bytes[current++] = (byte)((v >> 16) & 0xff);
  1272. bytes[current++] = (byte)((v >> 24) & 0xff);
  1273. return bytes;
  1274. }
  1275. internal void WriteInt(int v, TdsParserStateObject stateObj) {
  1276. ReliabilitySection.Assert("unreliable call to WriteInt"); // you need to setup for a thread abort somewhere before you call this method
  1277. if ((stateObj._outBytesUsed + 4) > stateObj._outBuff.Length) {
  1278. // if all of the int doesn't fit into the buffer
  1279. for (int shiftValue = 0; shiftValue < sizeof(int) * 8; shiftValue += 8) {
  1280. stateObj.WriteByte((byte)((v >> shiftValue) & 0xff));
  1281. }
  1282. }
  1283. else {
  1284. // all of the int fits into the buffer
  1285. // NOTE: We don't use a loop here for performance
  1286. stateObj._outBuff[stateObj._outBytesUsed] = (byte)(v & 0xff);
  1287. stateObj._outBuff[stateObj._outBytesUsed + 1] = (byte)((v >> 8) & 0xff);
  1288. stateObj._outBuff[stateObj._outBytesUsed + 2] = (byte)((v >> 16) & 0xff);
  1289. stateObj._outBuff[stateObj._outBytesUsed + 3] = (byte)((v >> 24) & 0xff);
  1290. stateObj._outBytesUsed += 4;
  1291. }
  1292. }
  1293. //
  1294. // Takes a float and writes it as a 32 bit float.
  1295. //
  1296. internal byte[] SerializeFloat(float v) {
  1297. if (Single.IsInfinity(v) || Single.IsNaN(v)) {
  1298. throw ADP.ParameterValueOutOfRange(v.ToString());
  1299. }
  1300. return BitConverter.GetBytes(v);
  1301. }
  1302. internal void WriteFloat(float v, TdsParserStateObject stateObj) {
  1303. byte[] bytes = BitConverter.GetBytes(v);
  1304. stateObj.WriteByteArray(bytes, bytes.Length, 0);
  1305. }
  1306. //
  1307. // Takes a long and writes it as a long.
  1308. //
  1309. internal byte[] SerializeLong(long v, TdsParserStateObject stateObj) {
  1310. int current = 0;
  1311. if (null == stateObj._bLongBytes) {
  1312. stateObj._bLongBytes = new byte[8];
  1313. }
  1314. byte[] bytes = stateObj._bLongBytes;
  1315. Debug.Assert (8 == bytes.Length, "Cached buffer has wrong size");
  1316. bytes[current++] = (byte)(v & 0xff);
  1317. bytes[current++] = (byte)((v >> 8) & 0xff);
  1318. bytes[current++] = (byte)((v >> 16) & 0xff);
  1319. bytes[current++] = (byte)((v >> 24) & 0xff);
  1320. bytes[current++] = (byte)((v >> 32) & 0xff);
  1321. bytes[current++] = (byte)((v >> 40) & 0xff);
  1322. bytes[current++] = (byte)((v >> 48) & 0xff);
  1323. bytes[current++] = (byte)((v >> 56) & 0xff);
  1324. return bytes;
  1325. }
  1326. internal void WriteLong(long v, TdsParserStateObject stateObj) {
  1327. ReliabilitySection.Assert("unreliable call to WriteLong"); // you need to setup for a thread abort somewhere before you call this method
  1328. if ((stateObj._outBytesUsed + 8) > stateObj._outBuff.Length) {
  1329. // if all of the long doesn't fit into the buffer
  1330. for (int shiftValue = 0; shiftValue < sizeof(long) * 8; shiftValue += 8) {
  1331. stateObj.WriteByte((byte)((v >> shiftValue) & 0xff));
  1332. }
  1333. }
  1334. else {
  1335. // all of the long fits into the buffer
  1336. // NOTE: We don't use a loop here for performance
  1337. stateObj._outBuff[stateObj._outBytesUsed] = (byte)(v & 0xff);
  1338. stateObj._outBuff[stateObj._outBytesUsed + 1] = (byte)((v >> 8) & 0xff);
  1339. stateObj._outBuff[stateObj._outBytesUsed + 2] = (byte)((v >> 16) & 0xff);
  1340. stateObj._outBuff[stateObj._outBytesUsed + 3] = (byte)((v >> 24) & 0xff);
  1341. stateObj._outBuff[stateObj._outBytesUsed + 4] = (byte)((v >> 32) & 0xff);
  1342. stateObj._outBuff[stateObj._outBytesUsed + 5] = (byte)((v >> 40) & 0xff);
  1343. stateObj._outBuff[stateObj._outBytesUsed + 6] = (byte)((v >> 48) & 0xff);
  1344. stateObj._outBuff[stateObj._outBytesUsed + 7] = (byte)((v >> 56) & 0xff);
  1345. stateObj._outBytesUsed += 8;
  1346. }
  1347. }
  1348. //
  1349. // Takes a long and writes part of it
  1350. //
  1351. internal byte[] SerializePartialLong(long v, int length) {
  1352. Debug.Assert(length <= 8, "Length specified is longer than the size of a long");
  1353. Debug.Assert(length >= 0, "Length should not be negative");
  1354. byte[] bytes = new byte[length];
  1355. // all of the long fits into the buffer
  1356. for (int index = 0; index < length; index++) {
  1357. bytes[index] = (byte)((v >> (index * 8)) & 0xff);
  1358. }
  1359. return bytes;
  1360. }
  1361. internal void WritePartialLong(long v, int length, TdsParserStateObject stateObj) {
  1362. ReliabilitySection.Assert("unreliable call to WritePartialLong"); // you need to setup for a thread abort somewhere before you call this method
  1363. Debug.Assert(length <= 8, "Length specified is longer than the size of a long");
  1364. Debug.Assert(length >= 0, "Length should not be negative");
  1365. if ((stateObj._outBytesUsed + length) > stateObj._outBuff.Length) {
  1366. // if all of the long doesn't fit into the buffer
  1367. for (int shiftValue = 0; shiftValue < length * 8; shiftValue += 8) {
  1368. stateObj.WriteByte((byte)((v >> shiftValue) & 0xff));
  1369. }
  1370. }
  1371. else {
  1372. // all of the long fits into the buffer
  1373. for (int index = 0; index < length; index++) {
  1374. stateObj._outBuff[stateObj._outBytesUsed + index] = (byte)((v >> (index * 8)) & 0xff);
  1375. }
  1376. stateObj._outBytesUsed += length;
  1377. }
  1378. }
  1379. //
  1380. // Takes a ulong and writes it as a ulong.
  1381. //
  1382. internal void WriteUnsignedLong(ulong uv, TdsParserStateObject stateObj) {
  1383. WriteLong((long)uv, stateObj);
  1384. }
  1385. //
  1386. // Takes a double and writes it as a 64 bit double.
  1387. //
  1388. internal byte[] SerializeDouble(double v) {
  1389. if (Double.IsInfinity(v) || Double.IsNaN(v)) {
  1390. throw ADP.ParameterValueOutOfRange(v.ToString());
  1391. }
  1392. return BitConverter.GetBytes(v);
  1393. }
  1394. internal void WriteDouble(double v, TdsParserStateObject stateObj) {
  1395. byte[] bytes = BitConverter.GetBytes(v);
  1396. stateObj.WriteByteArray(bytes, bytes.Length, 0);
  1397. }
  1398. internal void PrepareResetConnection(bool preserveTransaction) {
  1399. // Set flag to reset connection upon next use - only for use on shiloh!
  1400. _fResetConnection = true;
  1401. _fPreserveTransaction = preserveTransaction;
  1402. }
  1403. internal bool RunReliably(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) {
  1404. RuntimeHelpers.PrepareConstrainedRegions();
  1405. try {
  1406. #if DEBUG
  1407. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1408. RuntimeHelpers.PrepareConstrainedRegions();
  1409. try {
  1410. tdsReliabilitySection.Start();
  1411. #endif //DEBUG
  1412. return Run(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj);
  1413. #if DEBUG
  1414. }
  1415. finally {
  1416. tdsReliabilitySection.Stop();
  1417. }
  1418. #endif //DEBUG
  1419. }
  1420. catch (OutOfMemoryException) {
  1421. _connHandler.DoomThisConnection();
  1422. throw;
  1423. }
  1424. catch (StackOverflowException) {
  1425. _connHandler.DoomThisConnection();
  1426. throw;
  1427. }
  1428. catch (ThreadAbortException) {
  1429. _connHandler.DoomThisConnection();
  1430. throw;
  1431. }
  1432. }
  1433. internal bool Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) {
  1434. bool syncOverAsync = stateObj._syncOverAsync;
  1435. try
  1436. {
  1437. stateObj._syncOverAsync = true;
  1438. bool dataReady;
  1439. bool result = TryRun(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj, out dataReady);
  1440. Debug.Assert(result == true, "Should never return false when _syncOverAsync is set");
  1441. return dataReady;
  1442. }
  1443. finally
  1444. {
  1445. stateObj._syncOverAsync = syncOverAsync;
  1446. }
  1447. }
  1448. /// <summary>
  1449. /// Checks if the given token is a valid TDS token
  1450. /// </summary>
  1451. /// <param name="token">Token to check</param>
  1452. /// <returns>True if the token is a valid TDS token, otherwise false</returns>
  1453. internal static bool IsValidTdsToken(byte token) {
  1454. return (
  1455. token == TdsEnums.SQLERROR ||
  1456. token == TdsEnums.SQLINFO ||
  1457. token == TdsEnums.SQLLOGINACK ||
  1458. token == TdsEnums.SQLENVCHANGE ||
  1459. token == TdsEnums.SQLRETURNVALUE ||
  1460. token == TdsEnums.SQLRETURNSTATUS ||
  1461. token == TdsEnums.SQLCOLNAME ||
  1462. token == TdsEnums.SQLCOLFMT ||
  1463. token == TdsEnums.SQLCOLMETADATA ||
  1464. token == TdsEnums.SQLALTMETADATA ||
  1465. token == TdsEnums.SQLTABNAME ||
  1466. token == TdsEnums.SQLCOLINFO ||
  1467. token == TdsEnums.SQLORDER ||
  1468. token == TdsEnums.SQLALTROW ||
  1469. token == TdsEnums.SQLROW ||
  1470. token == TdsEnums.SQLNBCROW ||
  1471. token == TdsEnums.SQLDONE ||
  1472. token == TdsEnums.SQLDONEPROC ||
  1473. token == TdsEnums.SQLDONEINPROC ||
  1474. token == TdsEnums.SQLROWCRC ||
  1475. token == TdsEnums.SQLSECLEVEL ||
  1476. token == TdsEnums.SQLPROCID ||
  1477. token == TdsEnums.SQLOFFSET ||
  1478. token == TdsEnums.SQLSSPI ||
  1479. token == TdsEnums.SQLFEATUREEXTACK ||
  1480. token == TdsEnums.SQLSESSIONSTATE ||
  1481. token == TdsEnums.SQLFEDAUTHINFO);
  1482. }
  1483. // Main parse loop for the top-level tds tokens, calls back into the I*Handler interfaces
  1484. internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, out bool dataReady) {
  1485. ReliabilitySection.Assert("unreliable call to Run"); // you need to setup for a thread abort somewhere before you call this method
  1486. Debug.Assert((SniContext.Undefined != stateObj.SniContext) && // SniContext must not be Undefined
  1487. ((stateObj._attentionSent) || ((SniContext.Snix_Execute != stateObj.SniContext) && (SniContext.Snix_SendRows != stateObj.SniContext))), // SniContext should not be Execute or SendRows unless attention was sent (and, therefore, we are looking for an ACK)
  1488. String.Format("Unexpected SniContext on call to TryRun; SniContext={0}", stateObj.SniContext));
  1489. if (TdsParserState.Broken == State || TdsParserState.Closed == State ) {
  1490. dataReady = true;
  1491. return true; // Just in case this is called in a loop, expecting data to be returned.
  1492. }
  1493. dataReady = false;
  1494. do {
  1495. // If there is data ready, but we didn't exit the loop, then something is wrong
  1496. Debug.Assert(!dataReady, "dataReady not expected - did we forget to skip the row?");
  1497. if (stateObj._internalTimeout) {
  1498. runBehavior = RunBehavior.Attention;
  1499. }
  1500. if (TdsParserState.Broken == State || TdsParserState.Closed == State)
  1501. break; // jump out of the loop if the state is already broken or closed.
  1502. if (!stateObj._accumulateInfoEvents && (stateObj._pendingInfoEvents != null)) {
  1503. if (RunBehavior.Clean != (RunBehavior.Clean & runBehavior)) {
  1504. SqlConnection connection = null;
  1505. if (_connHandler != null)
  1506. connection = _connHandler.Connection; // SqlInternalConnection holds the user connection object as a weak ref
  1507. // We are omitting checks for error.Class in the code below (see processing of INFO) since we know (and assert) that error class
  1508. // error.Class < TdsEnums.MIN_ERROR_CLASS for info message.
  1509. // Also we know that TdsEnums.MIN_ERROR_CLASS<TdsEnums.MAX_USER_CORRECTABLE_ERROR_CLASS
  1510. if ((connection != null) && connection.FireInfoMessageEventOnUserErrors)
  1511. {
  1512. foreach (SqlError error in stateObj._pendingInfoEvents)
  1513. FireInfoMessageEvent(connection, stateObj, error);
  1514. }
  1515. else
  1516. foreach (SqlError error in stateObj._pendingInfoEvents)
  1517. stateObj.AddWarning(error);
  1518. }
  1519. stateObj._pendingInfoEvents=null;
  1520. }
  1521. byte token;
  1522. if (!stateObj.TryReadByte(out token)) {
  1523. return false;
  1524. }
  1525. if (!IsValidTdsToken(token)) {
  1526. Debug.Assert(false, String.Format((IFormatProvider)null, "unexpected token; token = {0,-2:X2}", token));
  1527. _state = TdsParserState.Broken;
  1528. _connHandler.BreakConnection();
  1529. Bid.Trace("<sc.TdsParser.Run|ERR> Potential multi-threaded misuse of connection, unexpected TDS token found %d#\n", ObjectID);
  1530. throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443
  1531. }
  1532. int tokenLength;
  1533. if (!TryGetTokenLength(token, stateObj, out tokenLength)) {
  1534. return false;
  1535. }
  1536. switch (token) {
  1537. case TdsEnums.SQLERROR:
  1538. case TdsEnums.SQLINFO:
  1539. {
  1540. if (token == TdsEnums.SQLERROR) {
  1541. stateObj._errorTokenReceived = true; // Keep track of the fact error token was received - for Done processing.
  1542. }
  1543. SqlError error;
  1544. if (!TryProcessError(token, stateObj, out error)) {
  1545. return false;
  1546. }
  1547. if (token == TdsEnums.SQLINFO && stateObj._accumulateInfoEvents)
  1548. {
  1549. Debug.Assert(error.Class < TdsEnums.MIN_ERROR_CLASS, "INFO with class > TdsEnums.MIN_ERROR_CLASS");
  1550. if (stateObj._pendingInfoEvents == null)
  1551. stateObj._pendingInfoEvents = new List<SqlError>();
  1552. stateObj._pendingInfoEvents.Add(error);
  1553. stateObj._syncOverAsync = true;
  1554. break;
  1555. }
  1556. if (RunBehavior.Clean != (RunBehavior.Clean & runBehavior)) {
  1557. // If FireInfoMessageEventOnUserErrors is true, we have to fire event without waiting.
  1558. // Otherwise we can go ahead and add it to errors/warnings collection.
  1559. SqlConnection connection = null;
  1560. if (_connHandler != null)
  1561. connection = _connHandler.Connection; // SqlInternalConnection holds the user connection object as a weak ref
  1562. if ((connection != null) &&
  1563. (connection.FireInfoMessageEventOnUserErrors == true) &&
  1564. (error.Class <= TdsEnums.MAX_USER_CORRECTABLE_ERROR_CLASS)) {
  1565. // Fire SqlInfoMessage here
  1566. FireInfoMessageEvent(connection, stateObj, error);
  1567. }
  1568. else {
  1569. // insert error/info into the appropriate exception - warning if info, exception if error
  1570. if (error.Class < TdsEnums.MIN_ERROR_CLASS) {
  1571. stateObj.AddWarning(error);
  1572. }
  1573. else if (error.Class < TdsEnums.FATAL_ERROR_CLASS) {
  1574. // VSTFDEVDIV 479643: continue results processing for all non-fatal errors (<20)
  1575. stateObj.AddError(error);
  1576. // Add it to collection - but do NOT change run behavior UNLESS
  1577. // we are in an ExecuteReader call - at which time we will be throwing
  1578. // anyways so we need to consume all errors. This is not the case
  1579. // if we have already given out a reader. If we have already given out
  1580. // a reader we need to throw the error but not halt further processing. We used to
  1581. // halt processing and that was a bug preventing the user from
  1582. // processing subsequent results.
  1583. if (null != dataStream) { // Webdata 104560
  1584. if (!dataStream.IsInitialized) {
  1585. runBehavior = RunBehavior.UntilDone;
  1586. }
  1587. }
  1588. }
  1589. else {
  1590. stateObj.AddError(error);
  1591. // Else we have a fatal error and we need to change the behavior
  1592. // since we want the complete error information in the exception.
  1593. // Besides - no further results will be received.
  1594. runBehavior = RunBehavior.UntilDone;
  1595. }
  1596. }
  1597. }
  1598. else if (error.Class >= TdsEnums.FATAL_ERROR_CLASS) {
  1599. stateObj.AddError(error);
  1600. }
  1601. break;
  1602. }
  1603. case TdsEnums.SQLCOLINFO:
  1604. {
  1605. if (null != dataStream) {
  1606. _SqlMetaDataSet metaDataSet;
  1607. if (!TryProcessColInfo(dataStream.MetaData, dataStream, stateObj, out metaDataSet)) {
  1608. return false;
  1609. }
  1610. if (!dataStream.TrySetMetaData(metaDataSet, false)) {
  1611. return false;
  1612. }
  1613. dataStream.BrowseModeInfoConsumed = true;
  1614. }
  1615. else { // no dataStream
  1616. if (!stateObj.TrySkipBytes(tokenLength)) {
  1617. return false;
  1618. }
  1619. }
  1620. break;
  1621. }
  1622. case TdsEnums.SQLDONE:
  1623. case TdsEnums.SQLDONEPROC:
  1624. case TdsEnums.SQLDONEINPROC:
  1625. {
  1626. // RunBehavior can be modified - see SQL BU DT 269516 & 290090
  1627. if (!TryProcessDone(cmdHandler, dataStream, ref runBehavior, stateObj)) {
  1628. return false;
  1629. }
  1630. if ((token == TdsEnums.SQLDONEPROC) && (cmdHandler != null)) {
  1631. // If the current parse/read is for the results of describe parameter encryption RPC requests,
  1632. // call a different handler which will update the describe parameter encryption RPC structures
  1633. // with the results, instead of the actual user RPC requests.
  1634. if (cmdHandler.IsDescribeParameterEncryptionRPCCurrentlyInProgress) {
  1635. cmdHandler.OnDoneDescribeParameterEncryptionProc(stateObj);
  1636. }
  1637. else {
  1638. cmdHandler.OnDoneProc();
  1639. }
  1640. }
  1641. break;
  1642. }
  1643. case TdsEnums.SQLORDER:
  1644. {
  1645. // don't do anything with the order token so read off the pipe
  1646. if (!stateObj.TrySkipBytes(tokenLength)) {
  1647. return false;
  1648. }
  1649. break;
  1650. }
  1651. case TdsEnums.SQLALTMETADATA:
  1652. {
  1653. stateObj.CloneCleanupAltMetaDataSetArray();
  1654. if (stateObj._cleanupAltMetaDataSetArray == null) {
  1655. // create object on demand (lazy creation)
  1656. stateObj._cleanupAltMetaDataSetArray = new _SqlMetaDataSetCollection();
  1657. }
  1658. _SqlMetaDataSet cleanupAltMetaDataSet;
  1659. if (!TryProcessAltMetaData(tokenLength, stateObj, out cleanupAltMetaDataSet)) {
  1660. return false;
  1661. }
  1662. stateObj._cleanupAltMetaDataSetArray.SetAltMetaData(cleanupAltMetaDataSet);
  1663. if (null != dataStream) {
  1664. byte metadataConsumedByte;
  1665. if (!stateObj.TryPeekByte(out metadataConsumedByte)) {
  1666. return false;
  1667. }
  1668. if (!dataStream.TrySetAltMetaDataSet(cleanupAltMetaDataSet, (TdsEnums.SQLALTMETADATA != metadataConsumedByte))) {
  1669. return false;
  1670. }
  1671. }
  1672. break;
  1673. }
  1674. case TdsEnums.SQLALTROW:
  1675. {
  1676. if (!stateObj.TryStartNewRow(isNullCompressed:false)) { // altrows are not currently null compressed
  1677. return false;
  1678. }
  1679. // read will call run until dataReady. Must not read any data if returnimmetiately set
  1680. if (RunBehavior.ReturnImmediately != (RunBehavior.ReturnImmediately & runBehavior)) {
  1681. ushort altRowId;
  1682. if (!stateObj.TryReadUInt16(out altRowId)) { // get altRowId
  1683. return false;
  1684. }
  1685. if (!TrySkipRow(stateObj._cleanupAltMetaDataSetArray.GetAltMetaData(altRowId), stateObj)) { // skip altRow
  1686. return false;
  1687. }
  1688. }
  1689. else {
  1690. dataReady = true;
  1691. }
  1692. break;
  1693. }
  1694. case TdsEnums.SQLENVCHANGE:
  1695. {
  1696. // ENVCHANGE must be processed synchronously (since it can modify the state of many objects)
  1697. stateObj._syncOverAsync = true;
  1698. SqlEnvChange[] env;
  1699. if (!TryProcessEnvChange(tokenLength, stateObj, out env)) {
  1700. return false;
  1701. }
  1702. for (int ii = 0; ii < env.Length; ii++) {
  1703. if (env[ii] != null && !this.Connection.IgnoreEnvChange) {
  1704. switch (env[ii].type) {
  1705. case TdsEnums.ENV_BEGINTRAN:
  1706. case TdsEnums.ENV_ENLISTDTC:
  1707. // When we get notification from the server of a new
  1708. // transaction, we move any pending transaction over to
  1709. // the current transaction, then we store the token in it.
  1710. // if there isn't a pending transaction, then it's either
  1711. // a TSQL transaction or a distributed transaction.
  1712. Debug.Assert(null == _currentTransaction, "non-null current transaction with an ENV Change");
  1713. _currentTransaction = _pendingTransaction;
  1714. _pendingTransaction = null;
  1715. if (null != _currentTransaction) {
  1716. _currentTransaction.TransactionId = env[ii].newLongValue; // this is defined as a ULongLong in the server and in the TDS Spec.
  1717. }
  1718. else {
  1719. TransactionType transactionType = (TdsEnums.ENV_BEGINTRAN == env[ii].type) ? TransactionType.LocalFromTSQL : TransactionType.Distributed;
  1720. _currentTransaction = new SqlInternalTransaction(_connHandler, transactionType, null, env[ii].newLongValue);
  1721. }
  1722. if (null != _statistics && !_statisticsIsInTransaction) {
  1723. _statistics.SafeIncrement(ref _statistics._transactions);
  1724. }
  1725. _statisticsIsInTransaction = true;
  1726. _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
  1727. break;
  1728. case TdsEnums.ENV_DEFECTDTC:
  1729. case TdsEnums.ENV_TRANSACTIONENDED:
  1730. case TdsEnums.ENV_COMMITTRAN:
  1731. // SQLHOT 483
  1732. // Must clear the retain id if the server-side transaction ends by anything other
  1733. // than rollback.
  1734. _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
  1735. goto case TdsEnums.ENV_ROLLBACKTRAN;
  1736. case TdsEnums.ENV_ROLLBACKTRAN:
  1737. // When we get notification of a completed transaction
  1738. // we null out the current transaction.
  1739. if (null != _currentTransaction) {
  1740. #if DEBUG
  1741. // Check null for case where Begin and Rollback obtained in the same message.
  1742. if (SqlInternalTransaction.NullTransactionId != _currentTransaction.TransactionId) {
  1743. Debug.Assert(_currentTransaction.TransactionId != env[ii].newLongValue, "transaction id's are not equal!");
  1744. }
  1745. #endif
  1746. if (TdsEnums.ENV_COMMITTRAN == env[ii].type) {
  1747. _currentTransaction.Completed(TransactionState.Committed);
  1748. }
  1749. else if (TdsEnums.ENV_ROLLBACKTRAN == env[ii].type) {
  1750. // Hold onto transaction id if distributed tran is rolled back. This must
  1751. // be sent to the server on subsequent executions even though the transaction
  1752. // is considered to be rolled back.
  1753. if (_currentTransaction.IsDistributed && _currentTransaction.IsActive) {
  1754. _retainedTransactionId = env[ii].oldLongValue;
  1755. }
  1756. _currentTransaction.Completed(TransactionState.Aborted);
  1757. }
  1758. else {
  1759. //
  1760. _currentTransaction.Completed(TransactionState.Unknown);
  1761. }
  1762. _currentTransaction = null;
  1763. }
  1764. _statisticsIsInTransaction = false;
  1765. break;
  1766. default:
  1767. _connHandler.OnEnvChange(env[ii]);
  1768. break;
  1769. }
  1770. }
  1771. }
  1772. break;
  1773. }
  1774. case TdsEnums.SQLLOGINACK:
  1775. {
  1776. Bid.Trace("<sc.TdsParser.TryRun|SEC> Received login acknowledgement token\n");
  1777. SqlLoginAck ack;
  1778. if (!TryProcessLoginAck(stateObj, out ack)) {
  1779. return false;
  1780. }
  1781. _connHandler.OnLoginAck(ack);
  1782. break;
  1783. }
  1784. case TdsEnums.SQLFEATUREEXTACK:
  1785. {
  1786. if (!TryProcessFeatureExtAck(stateObj)) {
  1787. return false;
  1788. }
  1789. break;
  1790. }
  1791. case TdsEnums.SQLFEDAUTHINFO:
  1792. {
  1793. _connHandler._federatedAuthenticationInfoReceived = true;
  1794. SqlFedAuthInfo info;
  1795. Bid.Trace("<sc.TdsParser.TryRun|SEC> Received federated authentication info token\n");
  1796. if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) {
  1797. return false;
  1798. }
  1799. _connHandler.OnFedAuthInfo(info);
  1800. break;
  1801. }
  1802. case TdsEnums.SQLSESSIONSTATE:
  1803. {
  1804. if (!TryProcessSessionState(stateObj, tokenLength, _connHandler._currentSessionData)) {
  1805. return false;
  1806. }
  1807. break;
  1808. }
  1809. case TdsEnums.SQLCOLMETADATA:
  1810. {
  1811. if (tokenLength != TdsEnums.VARNULL) {
  1812. _SqlMetaDataSet metadata;
  1813. if (!TryProcessMetaData(tokenLength, stateObj, out metadata,
  1814. cmdHandler != null ? cmdHandler.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting)) {
  1815. return false;
  1816. }
  1817. stateObj._cleanupMetaData = metadata;
  1818. }
  1819. else {
  1820. if (cmdHandler != null) {
  1821. stateObj._cleanupMetaData = cmdHandler.MetaData;
  1822. }
  1823. }
  1824. if (null != dataStream) {
  1825. byte peekedToken;
  1826. if (!stateObj.TryPeekByte(out peekedToken)) { // temporarily cache next byte
  1827. return false;
  1828. }
  1829. if (!dataStream.TrySetMetaData(stateObj._cleanupMetaData, (TdsEnums.SQLTABNAME == peekedToken || TdsEnums.SQLCOLINFO == peekedToken))) {
  1830. return false;
  1831. }
  1832. }
  1833. else if (null != bulkCopyHandler) {
  1834. bulkCopyHandler.SetMetaData(stateObj._cleanupMetaData);
  1835. }
  1836. break;
  1837. }
  1838. case TdsEnums.SQLROW:
  1839. case TdsEnums.SQLNBCROW:
  1840. {
  1841. Debug.Assert(stateObj._cleanupMetaData != null, "Reading a row, but the metadata is null");
  1842. if (token == TdsEnums.SQLNBCROW) {
  1843. if (!stateObj.TryStartNewRow(isNullCompressed: true, nullBitmapColumnsCount: stateObj._cleanupMetaData.Length)) {
  1844. return false;
  1845. }
  1846. }
  1847. else {
  1848. if (!stateObj.TryStartNewRow(isNullCompressed:false)) {
  1849. return false;
  1850. }
  1851. }
  1852. if (null != bulkCopyHandler) {
  1853. //
  1854. if (!TryProcessRow(stateObj._cleanupMetaData, bulkCopyHandler.CreateRowBuffer(), bulkCopyHandler.CreateIndexMap(), stateObj)) {
  1855. return false;
  1856. }
  1857. }
  1858. else if (RunBehavior.ReturnImmediately != (RunBehavior.ReturnImmediately & runBehavior)) {
  1859. if (!TrySkipRow(stateObj._cleanupMetaData, stateObj)) { // skip rows
  1860. return false;
  1861. }
  1862. }
  1863. else {
  1864. dataReady = true;
  1865. }
  1866. if (_statistics != null) {
  1867. _statistics.WaitForDoneAfterRow = true;
  1868. }
  1869. break;
  1870. }
  1871. case TdsEnums.SQLRETURNSTATUS:
  1872. int status;
  1873. if (!stateObj.TryReadInt32(out status)) {
  1874. return false;
  1875. }
  1876. if (cmdHandler != null) {
  1877. cmdHandler.OnReturnStatus(status);
  1878. }
  1879. break;
  1880. case TdsEnums.SQLRETURNVALUE:
  1881. {
  1882. SqlReturnValue returnValue;
  1883. if (!TryProcessReturnValue(tokenLength, stateObj, out returnValue,
  1884. cmdHandler != null ? cmdHandler.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting)) {
  1885. return false;
  1886. }
  1887. if (cmdHandler != null) {
  1888. cmdHandler.OnReturnValue(returnValue, stateObj);
  1889. }
  1890. break;
  1891. }
  1892. case TdsEnums.SQLSSPI:
  1893. {
  1894. // token length is length of SSPI data - call ProcessSSPI with it
  1895. Debug.Assert(stateObj._syncOverAsync, "ProcessSSPI does not support retry, do not attempt asynchronously");
  1896. stateObj._syncOverAsync = true;
  1897. ProcessSSPI(tokenLength);
  1898. break;
  1899. }
  1900. case TdsEnums.SQLTABNAME:
  1901. {
  1902. if (null != dataStream) {
  1903. MultiPartTableName[] tableNames;
  1904. if (!TryProcessTableName(tokenLength, stateObj, out tableNames)) {
  1905. return false;
  1906. }
  1907. dataStream.TableNames = tableNames;
  1908. }
  1909. else {
  1910. if (!stateObj.TrySkipBytes(tokenLength)) {
  1911. return false;
  1912. }
  1913. }
  1914. break;
  1915. }
  1916. default:
  1917. Debug.Assert(false, "Unhandled token: " + token.ToString(CultureInfo.InvariantCulture));
  1918. break;
  1919. }
  1920. Debug.Assert(stateObj._pendingData || !dataReady, "dataReady is set, but there is no pending data");
  1921. }
  1922. // Loop while data pending & runbehavior not return immediately, OR
  1923. // if in attention case, loop while no more pending data & attention has not yet been
  1924. // received.
  1925. while ((stateObj._pendingData &&
  1926. (RunBehavior.ReturnImmediately != (RunBehavior.ReturnImmediately & runBehavior))) ||
  1927. (!stateObj._pendingData && stateObj._attentionSent && !stateObj._attentionReceived));
  1928. #if DEBUG
  1929. if ((stateObj._pendingData) && (!dataReady)) {
  1930. byte token;
  1931. if (!stateObj.TryPeekByte(out token)) {
  1932. return false;
  1933. }
  1934. Debug.Assert(IsValidTdsToken(token), string.Format("DataReady is false, but next token is not valid: {0,-2:X2}", token));
  1935. }
  1936. #endif
  1937. if (!stateObj._pendingData) {
  1938. if (null != CurrentTransaction) {
  1939. CurrentTransaction.Activate();
  1940. }
  1941. }
  1942. // if we recieved an attention (but this thread didn't send it) then
  1943. // we throw an Operation Cancelled error
  1944. if (stateObj._attentionReceived) {
  1945. // Dev11 #344723: SqlClient stress hang System_Data!Tcp::ReadSync via a call to SqlDataReader::Close
  1946. // Spin until SendAttention has cleared _attentionSending, this prevents a race condition between receiving the attention ACK and setting _attentionSent
  1947. SpinWait.SpinUntil(() => !stateObj._attentionSending);
  1948. Debug.Assert(stateObj._attentionSent, "Attention ACK has been received without attention sent");
  1949. if (stateObj._attentionSent) {
  1950. // Reset attention state.
  1951. stateObj._attentionSent = false;
  1952. stateObj._attentionReceived = false;
  1953. if (RunBehavior.Clean != (RunBehavior.Clean & runBehavior) && !stateObj._internalTimeout) {
  1954. // Add attention error to collection - if not RunBehavior.Clean!
  1955. stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.OperationCancelled(), "", 0));
  1956. }
  1957. }
  1958. }
  1959. if (stateObj.HasErrorOrWarning) {
  1960. ThrowExceptionAndWarning(stateObj);
  1961. }
  1962. return true;
  1963. }
  1964. private bool TryProcessEnvChange(int tokenLength, TdsParserStateObject stateObj, out SqlEnvChange[] sqlEnvChange) {
  1965. // There could be multiple environment change messages following this token.
  1966. byte byteLength;
  1967. int processedLength = 0;
  1968. int nvalues = 0;
  1969. SqlEnvChange[] envarray = new SqlEnvChange[3]; // Why is this hardcoded to 3?
  1970. sqlEnvChange = null;
  1971. while (tokenLength > processedLength) {
  1972. if (nvalues >= envarray.Length) {
  1973. // This is a rare path. Most of the time we will have 1 or 2 envchange data streams.
  1974. SqlEnvChange[] newenvarray = new SqlEnvChange[envarray.Length + 3];
  1975. for (int ii = 0; ii < envarray.Length; ii++)
  1976. newenvarray[ii] = envarray[ii];
  1977. envarray = newenvarray;
  1978. }
  1979. SqlEnvChange env = new SqlEnvChange();
  1980. if (!stateObj.TryReadByte(out env.type)) {
  1981. return false;
  1982. }
  1983. envarray[nvalues] = env;
  1984. nvalues++;
  1985. switch (env.type) {
  1986. case TdsEnums.ENV_DATABASE:
  1987. case TdsEnums.ENV_LANG:
  1988. if (!TryReadTwoStringFields(env, stateObj)) {
  1989. return false;
  1990. }
  1991. break;
  1992. case TdsEnums.ENV_CHARSET:
  1993. // we copied this behavior directly from luxor - see charset envchange
  1994. // section from sqlctokn.c
  1995. Debug.Assert(!_isShiloh, "Received ENV_CHARSET on non 7.0 server!");
  1996. if (!TryReadTwoStringFields(env, stateObj)) {
  1997. return false;
  1998. }
  1999. if (env.newValue == TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_STRING) {
  2000. _defaultCodePage = TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_VALUE;
  2001. _defaultEncoding = System.Text.Encoding.GetEncoding(_defaultCodePage);
  2002. }
  2003. else {
  2004. Debug.Assert(env.newValue.Length > TdsEnums.CHARSET_CODE_PAGE_OFFSET, "TdsParser.ProcessEnvChange(): charset value received with length <=10");
  2005. string stringCodePage = env.newValue.Substring(TdsEnums.CHARSET_CODE_PAGE_OFFSET);
  2006. _defaultCodePage = Int32.Parse(stringCodePage, NumberStyles.Integer, CultureInfo.InvariantCulture);
  2007. _defaultEncoding = System.Text.Encoding.GetEncoding(_defaultCodePage);
  2008. }
  2009. break;
  2010. case TdsEnums.ENV_PACKETSIZE:
  2011. // take care of packet size right here
  2012. Debug.Assert(stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2013. if (!TryReadTwoStringFields(env, stateObj)) {
  2014. // Changing packet size does not support retry, should not pend"
  2015. throw SQL.SynchronousCallMayNotPend();
  2016. }
  2017. // Only set on physical state object - this should only occur on LoginAck prior
  2018. // to MARS initialization!
  2019. Int32 packetSize = Int32.Parse(env.newValue, NumberStyles.Integer, CultureInfo.InvariantCulture);
  2020. if (_physicalStateObj.SetPacketSize(packetSize)) {
  2021. // If packet size changed, we need to release our SNIPackets since
  2022. // those are tied to packet size of connection.
  2023. _physicalStateObj.ClearAllWritePackets();
  2024. // Update SNI ConsumerInfo value to be resulting packet size
  2025. UInt32 unsignedPacketSize = (UInt32) packetSize;
  2026. UInt32 result = SNINativeMethodWrapper.SNISetInfo(_physicalStateObj.Handle, SNINativeMethodWrapper.QTypes.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize);
  2027. Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SNISetInfo");
  2028. }
  2029. break;
  2030. case TdsEnums.ENV_LOCALEID:
  2031. //
  2032. if (!TryReadTwoStringFields(env, stateObj)) {
  2033. return false;
  2034. }
  2035. _defaultLCID = Int32.Parse(env.newValue, NumberStyles.Integer, CultureInfo.InvariantCulture);
  2036. break;
  2037. case TdsEnums.ENV_COMPFLAGS:
  2038. if (!TryReadTwoStringFields(env, stateObj)) {
  2039. return false;
  2040. }
  2041. break;
  2042. case TdsEnums.ENV_COLLATION:
  2043. Debug.Assert(env.newLength == 5 || env.newLength == 0, "Improper length in new collation!");
  2044. if (!stateObj.TryReadByte(out byteLength)) {
  2045. return false;
  2046. }
  2047. env.newLength = byteLength;
  2048. if (env.newLength == 5) {
  2049. if (!TryProcessCollation(stateObj, out env.newCollation)) {
  2050. return false;
  2051. }
  2052. // give the parser the new collation values in case parameters don't specify one
  2053. _defaultCollation = env.newCollation;
  2054. int newCodePage = GetCodePage(env.newCollation, stateObj);
  2055. if (newCodePage != _defaultCodePage) {
  2056. _defaultCodePage = newCodePage;
  2057. _defaultEncoding = System.Text.Encoding.GetEncoding(_defaultCodePage);
  2058. }
  2059. _defaultLCID = env.newCollation.LCID;
  2060. }
  2061. if (!stateObj.TryReadByte(out byteLength)) {
  2062. return false;
  2063. }
  2064. env.oldLength = byteLength;
  2065. Debug.Assert(env.oldLength == 5 || env.oldLength == 0, "Improper length in old collation!");
  2066. if (env.oldLength == 5) {
  2067. if (!TryProcessCollation(stateObj, out env.oldCollation)) {
  2068. return false;
  2069. }
  2070. }
  2071. env.length = 3 + env.newLength + env.oldLength;
  2072. break;
  2073. case TdsEnums.ENV_BEGINTRAN:
  2074. case TdsEnums.ENV_COMMITTRAN:
  2075. case TdsEnums.ENV_ROLLBACKTRAN:
  2076. case TdsEnums.ENV_ENLISTDTC:
  2077. case TdsEnums.ENV_DEFECTDTC:
  2078. case TdsEnums.ENV_TRANSACTIONENDED:
  2079. Debug.Assert(_isYukon, "Received new ENVCHANGE transaction/DTC token on pre 9.0 server!");
  2080. if (!stateObj.TryReadByte(out byteLength)) {
  2081. return false;
  2082. }
  2083. env.newLength = byteLength;
  2084. Debug.Assert(env.newLength == 0 || env.newLength == 8, "Improper length for new transaction id!");
  2085. if (env.newLength > 0) {
  2086. if (!stateObj.TryReadInt64(out env.newLongValue)) {
  2087. return false;
  2088. }
  2089. Debug.Assert(env.newLongValue != SqlInternalTransaction.NullTransactionId, "New transaction id is null?"); // the server guarantees that zero is an invalid transaction id.
  2090. }
  2091. else {
  2092. env.newLongValue = SqlInternalTransaction.NullTransactionId; // the server guarantees that zero is an invalid transaction id.
  2093. }
  2094. if (!stateObj.TryReadByte(out byteLength)) {
  2095. return false;
  2096. }
  2097. env.oldLength = byteLength;
  2098. Debug.Assert(env.oldLength == 0 || env.oldLength == 8, "Improper length for old transaction id!");
  2099. if (env.oldLength > 0) {
  2100. if (!stateObj.TryReadInt64(out env.oldLongValue)) {
  2101. return false;
  2102. }
  2103. Debug.Assert(env.oldLongValue != SqlInternalTransaction.NullTransactionId, "Old transaction id is null?"); // the server guarantees that zero is an invalid transaction id.
  2104. }
  2105. else {
  2106. env.oldLongValue = SqlInternalTransaction.NullTransactionId; // the server guarantees that zero is an invalid transaction id.
  2107. }
  2108. // env.length includes 1 byte type token
  2109. env.length = 3 + env.newLength + env.oldLength;
  2110. break;
  2111. case TdsEnums.ENV_LOGSHIPNODE:
  2112. // env.newBinValue is secondary node, env.oldBinValue is witness node
  2113. // comes before LoginAck so we can't assert this
  2114. if (!TryReadTwoStringFields(env, stateObj)) {
  2115. return false;
  2116. }
  2117. break;
  2118. case TdsEnums.ENV_PROMOTETRANSACTION:
  2119. Debug.Assert(_isYukon, "Received new ENVCHANGE tokens on pre 9.0 server!");
  2120. if (!stateObj.TryReadInt32(out env.newLength)) { // new value has 4 byte length
  2121. return false;
  2122. }
  2123. env.newBinValue = new byte[env.newLength];
  2124. if (!stateObj.TryReadByteArray(env.newBinValue, 0, env.newLength)) { // read new value with 4 byte length
  2125. return false;
  2126. }
  2127. if (!stateObj.TryReadByte(out byteLength)) {
  2128. return false;
  2129. }
  2130. env.oldLength = byteLength;
  2131. Debug.Assert(0 == env.oldLength, "old length should be zero");
  2132. // env.length includes 1 byte for type token
  2133. env.length = 5 + env.newLength;
  2134. break;
  2135. case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
  2136. case TdsEnums.ENV_SPRESETCONNECTIONACK:
  2137. //
  2138. Debug.Assert(_isYukon, "Received new ENVCHANGE tokens on pre 9.0 server!");
  2139. if (!TryReadTwoBinaryFields(env, stateObj)) {
  2140. return false;
  2141. }
  2142. break;
  2143. case TdsEnums.ENV_USERINSTANCE:
  2144. Debug.Assert(!_isYukon, "Received ENV_USERINSTANCE on non 9.0 server!");
  2145. if (!TryReadTwoStringFields(env, stateObj)) {
  2146. return false;
  2147. }
  2148. break;
  2149. case TdsEnums.ENV_ROUTING:
  2150. ushort newLength;
  2151. if (!stateObj.TryReadUInt16(out newLength)) {
  2152. return false;
  2153. }
  2154. env.newLength = newLength;
  2155. byte protocol;
  2156. if (!stateObj.TryReadByte(out protocol)) {
  2157. return false;
  2158. }
  2159. ushort port;
  2160. if (!stateObj.TryReadUInt16(out port)) {
  2161. return false;
  2162. }
  2163. UInt16 serverLen;
  2164. if (!stateObj.TryReadUInt16(out serverLen)) {
  2165. return false;
  2166. }
  2167. string serverName;
  2168. if (!stateObj.TryReadString(serverLen, out serverName)) {
  2169. return false;
  2170. }
  2171. env.newRoutingInfo = new RoutingInfo(protocol, port, serverName);
  2172. UInt16 oldLength;
  2173. if (!stateObj.TryReadUInt16(out oldLength)) {
  2174. return false;
  2175. }
  2176. if (!stateObj.TrySkipBytes(oldLength)) {
  2177. return false;
  2178. }
  2179. env.length = env.newLength + oldLength + 5; // 5=2*sizeof(UInt16)+sizeof(byte) [token+newLength+oldLength]
  2180. break;
  2181. default:
  2182. Debug.Assert(false, "Unknown environment change token: " + env.type);
  2183. break;
  2184. }
  2185. processedLength += env.length;
  2186. }
  2187. sqlEnvChange = envarray;
  2188. return true;
  2189. }
  2190. private bool TryReadTwoBinaryFields(SqlEnvChange env, TdsParserStateObject stateObj) {
  2191. // Used by ProcessEnvChangeToken
  2192. byte byteLength;
  2193. if (!stateObj.TryReadByte(out byteLength)) {
  2194. return false;
  2195. }
  2196. env.newLength = byteLength;
  2197. env.newBinValue = new byte[env.newLength];
  2198. if (!stateObj.TryReadByteArray(env.newBinValue, 0, env.newLength)) {
  2199. return false;
  2200. }
  2201. if (!stateObj.TryReadByte(out byteLength)) {
  2202. return false;
  2203. }
  2204. env.oldLength = byteLength;
  2205. env.oldBinValue = new byte[env.oldLength];
  2206. if (!stateObj.TryReadByteArray(env.oldBinValue, 0, env.oldLength)) {
  2207. return false;
  2208. }
  2209. // env.length includes 1 byte type token
  2210. env.length = 3 + env.newLength + env.oldLength;
  2211. return true;
  2212. }
  2213. private bool TryReadTwoStringFields(SqlEnvChange env, TdsParserStateObject stateObj) {
  2214. // Used by ProcessEnvChangeToken
  2215. byte newLength, oldLength;
  2216. string newValue, oldValue;
  2217. if (!stateObj.TryReadByte(out newLength)) {
  2218. return false;
  2219. }
  2220. if (!stateObj.TryReadString(newLength, out newValue)) {
  2221. return false;
  2222. }
  2223. if (!stateObj.TryReadByte(out oldLength)) {
  2224. return false;
  2225. }
  2226. if (!stateObj.TryReadString(oldLength, out oldValue)) {
  2227. return false;
  2228. }
  2229. env.newLength = newLength;
  2230. env.newValue = newValue;
  2231. env.oldLength = oldLength;
  2232. env.oldValue = oldValue;
  2233. // env.length includes 1 byte type token
  2234. env.length = 3 + env.newLength * 2 + env.oldLength * 2;
  2235. return true;
  2236. }
  2237. private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavior run, TdsParserStateObject stateObj) {
  2238. ushort curCmd;
  2239. ushort status;
  2240. int count;
  2241. // Can't retry TryProcessDone
  2242. stateObj._syncOverAsync = true;
  2243. // status
  2244. // command
  2245. // rowcount (valid only if DONE_COUNT bit is set)
  2246. if (!stateObj.TryReadUInt16(out status)) {
  2247. return false;
  2248. }
  2249. if (!stateObj.TryReadUInt16(out curCmd)) {
  2250. return false;
  2251. }
  2252. if (_isYukon) {
  2253. long longCount;
  2254. if (!stateObj.TryReadInt64(out longCount)) {
  2255. return false;
  2256. }
  2257. count = (int) longCount;
  2258. }
  2259. else {
  2260. if (!stateObj.TryReadInt32(out count)) {
  2261. return false;
  2262. }
  2263. // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server
  2264. // In that case we still have to read another 4 bytes
  2265. // But don't try to read beyond the TDS stream in this case, because it generates errors if login failed.
  2266. if ( _state == TdsParserState.OpenNotLoggedIn) {
  2267. // Login incomplete, if we are reading from Yukon we need to read another int
  2268. if (stateObj._inBytesRead > stateObj._inBytesUsed) {
  2269. byte b;
  2270. if (!stateObj.TryPeekByte(out b)) {
  2271. return false;
  2272. }
  2273. if (b == 0) {
  2274. // This is an invalid token value
  2275. if (!stateObj.TryReadInt32(out count)) {
  2276. return false;
  2277. }
  2278. }
  2279. }
  2280. }
  2281. }
  2282. // We get a done token with the attention bit set
  2283. if (TdsEnums.DONE_ATTN == (status & TdsEnums.DONE_ATTN)) {
  2284. Debug.Assert(TdsEnums.DONE_MORE != (status & TdsEnums.DONE_MORE),"Not expecting DONE_MORE when receiving DONE_ATTN");
  2285. Debug.Assert(stateObj._attentionSent, "Received attention done without sending one!");
  2286. stateObj._attentionReceived = true;
  2287. Debug.Assert(stateObj._inBytesUsed == stateObj._inBytesRead && stateObj._inBytesPacket == 0, "DONE_ATTN received with more data left on wire");
  2288. }
  2289. if ((null != cmd) && (TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT))) {
  2290. if (curCmd != TdsEnums.SELECT) {
  2291. if (cmd.IsDescribeParameterEncryptionRPCCurrentlyInProgress) {
  2292. // The below line is used only for debug asserts and not exposed publicly or impacts functionality otherwise.
  2293. cmd.RowsAffectedByDescribeParameterEncryption = count;
  2294. }
  2295. else {
  2296. cmd.InternalRecordsAffected = count;
  2297. }
  2298. }
  2299. // Skip the bogus DONE counts sent by the server
  2300. if (stateObj._receivedColMetaData || (curCmd != TdsEnums.SELECT)) {
  2301. cmd.OnStatementCompleted(count);
  2302. }
  2303. }
  2304. stateObj._receivedColMetaData = false;
  2305. // Surface exception for DONE_ERROR in the case we did not receive an error token
  2306. // in the stream, but an error occurred. In these cases, we throw a general server error. The
  2307. // situations where this can occur are: an invalid buffer received from client, login error
  2308. // and the server refused our connection, and the case where we are trying to log in but
  2309. // the server has reached its max connection limit. Bottom line, we need to throw general
  2310. // error in the cases where we did not receive a error token along with the DONE_ERROR.
  2311. if ((TdsEnums.DONE_ERROR == (TdsEnums.DONE_ERROR & status)) && stateObj.ErrorCount == 0 &&
  2312. stateObj._errorTokenReceived == false && (RunBehavior.Clean != (RunBehavior.Clean & run))) {
  2313. stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0));
  2314. if (null != reader) { // SQL BU DT 269516
  2315. if (!reader.IsInitialized) {
  2316. run = RunBehavior.UntilDone;
  2317. }
  2318. }
  2319. }
  2320. // Similar to above, only with a more severe error. In this case, if we received
  2321. // the done_srverror, this exception will be added to the collection regardless.
  2322. // MDAC #93896. Also, per Ashwin, the server will always break the connection in this case.
  2323. if ((TdsEnums.DONE_SRVERROR == (TdsEnums.DONE_SRVERROR & status)) && (RunBehavior.Clean != (RunBehavior.Clean & run))) {
  2324. stateObj.AddError(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0));
  2325. if (null != reader) { // SQL BU DT 269516
  2326. if (!reader.IsInitialized) {
  2327. run = RunBehavior.UntilDone;
  2328. }
  2329. }
  2330. }
  2331. ProcessSqlStatistics(curCmd, status, count);
  2332. // stop if the DONE_MORE bit isn't set (see above for attention handling)
  2333. if (TdsEnums.DONE_MORE != (status & TdsEnums.DONE_MORE)) {
  2334. stateObj._errorTokenReceived = false;
  2335. if (stateObj._inBytesUsed >= stateObj._inBytesRead) {
  2336. stateObj._pendingData = false;
  2337. }
  2338. }
  2339. // _pendingData set by e.g. 'TdsExecuteSQLBatch'
  2340. // _hasOpenResult always set to true by 'WriteMarsHeader'
  2341. //
  2342. if (!stateObj._pendingData && stateObj._hasOpenResult) {
  2343. /*
  2344. Debug.Assert(!((sqlTransaction != null && _distributedTransaction != null) ||
  2345. (_userStartedLocalTransaction != null && _distributedTransaction != null))
  2346. , "ProcessDone - have both distributed and local transactions not null!");
  2347. */ // WebData 112722
  2348. stateObj.DecrementOpenResultCount();
  2349. }
  2350. return true;
  2351. }
  2352. private void ProcessSqlStatistics(ushort curCmd, ushort status, int count) {
  2353. // SqlStatistics bookkeeping stuff
  2354. //
  2355. if (null != _statistics) {
  2356. // any done after row(s) counts as a resultset
  2357. if (_statistics.WaitForDoneAfterRow) {
  2358. _statistics.SafeIncrement(ref _statistics._sumResultSets);
  2359. _statistics.WaitForDoneAfterRow = false;
  2360. }
  2361. // clear row count DONE_COUNT flag is not set
  2362. if (!(TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT))) {
  2363. count = 0;
  2364. }
  2365. switch (curCmd) {
  2366. case TdsEnums.INSERT:
  2367. case TdsEnums.DELETE:
  2368. case TdsEnums.UPDATE:
  2369. case TdsEnums.MERGE:
  2370. _statistics.SafeIncrement(ref _statistics._iduCount);
  2371. _statistics.SafeAdd(ref _statistics._iduRows, count);
  2372. if (!_statisticsIsInTransaction) {
  2373. _statistics.SafeIncrement(ref _statistics._transactions);
  2374. }
  2375. break;
  2376. case TdsEnums.SELECT:
  2377. _statistics.SafeIncrement(ref _statistics._selectCount);
  2378. _statistics.SafeAdd(ref _statistics._selectRows, count);
  2379. break;
  2380. case TdsEnums.BEGINXACT:
  2381. if (!_statisticsIsInTransaction) {
  2382. _statistics.SafeIncrement(ref _statistics._transactions);
  2383. }
  2384. _statisticsIsInTransaction = true;
  2385. break;
  2386. case TdsEnums.OPENCURSOR:
  2387. _statistics.SafeIncrement(ref _statistics._cursorOpens);
  2388. break;
  2389. case TdsEnums.ABORT:
  2390. _statisticsIsInTransaction = false;
  2391. break;
  2392. case TdsEnums.ENDXACT:
  2393. _statisticsIsInTransaction = false;
  2394. break;
  2395. } // switch
  2396. }
  2397. else {
  2398. switch (curCmd) {
  2399. case TdsEnums.BEGINXACT:
  2400. _statisticsIsInTransaction = true;
  2401. break;
  2402. case TdsEnums.ABORT:
  2403. case TdsEnums.ENDXACT:
  2404. _statisticsIsInTransaction = false;
  2405. break;
  2406. }
  2407. }
  2408. }
  2409. private bool TryProcessFeatureExtAck(TdsParserStateObject stateObj) {
  2410. // read feature ID
  2411. byte featureId;
  2412. do {
  2413. if (!stateObj.TryReadByte(out featureId)) {
  2414. return false;
  2415. }
  2416. if (featureId != TdsEnums.FEATUREEXT_TERMINATOR) {
  2417. UInt32 dataLen;
  2418. if (!stateObj.TryReadUInt32(out dataLen)) {
  2419. return false;
  2420. }
  2421. byte[] data = new byte[dataLen];
  2422. if (dataLen > 0) {
  2423. if (!stateObj.TryReadByteArray(data, 0, checked ((int)dataLen))) {
  2424. return false;
  2425. }
  2426. }
  2427. _connHandler.OnFeatureExtAck(featureId, data);
  2428. }
  2429. } while (featureId != TdsEnums.FEATUREEXT_TERMINATOR);
  2430. // Check if column encryption was on and feature wasn't acknowledged.
  2431. if (_connHandler.ConnectionOptions.ColumnEncryptionSetting == SqlConnectionColumnEncryptionSetting.Enabled && !IsColumnEncryptionSupported) {
  2432. throw SQL.TceNotSupported ();
  2433. }
  2434. return true;
  2435. }
  2436. private bool TryProcessSessionState(TdsParserStateObject stateObj, int length, SessionData sdata) {
  2437. if (length < 5) {
  2438. throw SQL.ParsingErrorLength(ParsingErrorState.SessionStateLengthTooShort, length);
  2439. }
  2440. UInt32 seqNum;
  2441. if (!stateObj.TryReadUInt32(out seqNum)) {
  2442. return false;
  2443. }
  2444. if (seqNum == UInt32.MaxValue) {
  2445. _connHandler.DoNotPoolThisConnection();
  2446. }
  2447. byte status;
  2448. if (!stateObj.TryReadByte(out status)) {
  2449. return false;
  2450. }
  2451. if (status > 1) {
  2452. throw SQL.ParsingErrorStatus(ParsingErrorState.SessionStateInvalidStatus, status);
  2453. }
  2454. bool recoverable = status != 0;
  2455. length -= 5;
  2456. while (length > 0) {
  2457. byte stateId;
  2458. if (!stateObj.TryReadByte(out stateId)) {
  2459. return false;
  2460. }
  2461. int stateLen;
  2462. byte stateLenByte;
  2463. if (!stateObj.TryReadByte(out stateLenByte)) {
  2464. return false;
  2465. }
  2466. if (stateLenByte < 0xFF) {
  2467. stateLen = stateLenByte;
  2468. }
  2469. else {
  2470. if (!stateObj.TryReadInt32(out stateLen)) {
  2471. return false;
  2472. }
  2473. }
  2474. byte[] buffer = null;
  2475. lock (sdata._delta) {
  2476. if (sdata._delta[stateId] == null) {
  2477. buffer = new byte[stateLen];
  2478. sdata._delta[stateId] = new SessionStateRecord { _version = seqNum, _dataLength = stateLen, _data = buffer, _recoverable = recoverable };
  2479. sdata._deltaDirty = true;
  2480. if (!recoverable) {
  2481. checked { sdata._unrecoverableStatesCount++; }
  2482. }
  2483. }
  2484. else {
  2485. if (sdata._delta[stateId]._version <= seqNum) {
  2486. SessionStateRecord sv = sdata._delta[stateId];
  2487. sv._version = seqNum;
  2488. sv._dataLength = stateLen;
  2489. if (sv._recoverable != recoverable) {
  2490. if (recoverable) {
  2491. Debug.Assert(sdata._unrecoverableStatesCount > 0, "Unrecoverable states count >0");
  2492. sdata._unrecoverableStatesCount--;
  2493. }
  2494. else {
  2495. checked { sdata._unrecoverableStatesCount++; }
  2496. }
  2497. sv._recoverable = recoverable;
  2498. }
  2499. buffer = sv._data;
  2500. if (buffer.Length < stateLen) {
  2501. buffer = new byte[stateLen];
  2502. sv._data = buffer;
  2503. }
  2504. }
  2505. }
  2506. }
  2507. if (buffer != null) {
  2508. if (!stateObj.TryReadByteArray(buffer, 0, stateLen)) {
  2509. return false;
  2510. }
  2511. }
  2512. else {
  2513. if (!stateObj.TrySkipBytes(stateLen))
  2514. return false;
  2515. }
  2516. if (stateLenByte < 0xFF) {
  2517. length -= 2 + stateLen;
  2518. }
  2519. else {
  2520. length -= 6 + stateLen;
  2521. }
  2522. }
  2523. sdata.AssertUnrecoverableStateCountIsCorrect();
  2524. return true;
  2525. }
  2526. private bool TryProcessLoginAck(TdsParserStateObject stateObj, out SqlLoginAck sqlLoginAck) {
  2527. SqlLoginAck a = new SqlLoginAck();
  2528. sqlLoginAck = null;
  2529. // read past interface type and version
  2530. if (!stateObj.TrySkipBytes(1)) {
  2531. return false;
  2532. }
  2533. byte[] b = new byte[TdsEnums.VERSION_SIZE];
  2534. if (!stateObj.TryReadByteArray(b, 0, b.Length)) {
  2535. return false;
  2536. }
  2537. a.tdsVersion = (UInt32)((((((b[0]<<8)|b[1])<<8)|b[2])<<8)|b[3]); // bytes are in motorola order (high byte first)
  2538. UInt32 majorMinor = a.tdsVersion & 0xff00ffff;
  2539. UInt32 increment = (a.tdsVersion >> 16) & 0xff;
  2540. // Server responds:
  2541. // 0x07000000 -> Sphinx // Notice server response format is different for bwd compat
  2542. // 0x07010000 -> Shiloh RTM // Notice server response format is different for bwd compat
  2543. // 0x71000001 -> Shiloh SP1
  2544. // 0x72xx0002 -> Yukon RTM
  2545. // information provided by S. Ashwin
  2546. switch (majorMinor) {
  2547. case TdsEnums.SPHINXORSHILOH_MAJOR<<24|TdsEnums.DEFAULT_MINOR: // Sphinx & Shiloh RTM
  2548. // note that sphinx and shiloh_rtm can only be distinguished by the increment
  2549. switch (increment) {
  2550. case TdsEnums.SHILOH_INCREMENT:
  2551. _isShiloh = true;
  2552. break;
  2553. case TdsEnums.SPHINX_INCREMENT:
  2554. // no flag will be set
  2555. break;
  2556. default:
  2557. throw SQL.InvalidTDSVersion();
  2558. }
  2559. break;
  2560. case TdsEnums.SHILOHSP1_MAJOR<<24|TdsEnums.SHILOHSP1_MINOR: // Shiloh SP1
  2561. if (increment != TdsEnums.SHILOHSP1_INCREMENT) { throw SQL.InvalidTDSVersion(); }
  2562. _isShilohSP1 = true;
  2563. break;
  2564. case TdsEnums.YUKON_MAJOR<<24|TdsEnums.YUKON_RTM_MINOR: // Yukon
  2565. if (increment != TdsEnums.YUKON_INCREMENT) { throw SQL.InvalidTDSVersion(); }
  2566. _isYukon = true;
  2567. break;
  2568. case TdsEnums.KATMAI_MAJOR<<24|TdsEnums.KATMAI_MINOR:
  2569. if (increment != TdsEnums.KATMAI_INCREMENT) { throw SQL.InvalidTDSVersion(); }
  2570. _isKatmai = true;
  2571. break;
  2572. case TdsEnums.DENALI_MAJOR << 24|TdsEnums.DENALI_MINOR:
  2573. if (increment != TdsEnums.DENALI_INCREMENT) { throw SQL.InvalidTDSVersion(); }
  2574. _isDenali = true;
  2575. break;
  2576. default:
  2577. throw SQL.InvalidTDSVersion();
  2578. }
  2579. _isKatmai |= _isDenali;
  2580. _isYukon |= _isKatmai;
  2581. _isShilohSP1 |= _isYukon; // includes all lower versions
  2582. _isShiloh |= _isShilohSP1; //
  2583. a.isVersion8 = _isShiloh;
  2584. stateObj._outBytesUsed = stateObj._outputHeaderLen;
  2585. byte len;
  2586. if (!stateObj.TryReadByte(out len)) {
  2587. return false;
  2588. }
  2589. if (!stateObj.TryReadString(len, out a.programName)) {
  2590. return false;
  2591. }
  2592. if (!stateObj.TryReadByte(out a.majorVersion)) {
  2593. return false;
  2594. }
  2595. if (!stateObj.TryReadByte(out a.minorVersion)) {
  2596. return false;
  2597. }
  2598. byte buildNumHi, buildNumLo;
  2599. if (!stateObj.TryReadByte(out buildNumHi)) {
  2600. return false;
  2601. }
  2602. if (!stateObj.TryReadByte(out buildNumLo)) {
  2603. return false;
  2604. }
  2605. a.buildNum = (short)((buildNumHi << 8) + buildNumLo);
  2606. Debug.Assert(_state == TdsParserState.OpenNotLoggedIn, "ProcessLoginAck called with state not TdsParserState.OpenNotLoggedIn");
  2607. _state = TdsParserState.OpenLoggedIn;
  2608. if (_isYukon) {
  2609. if (_fMARS) {
  2610. _resetConnectionEvent = new AutoResetEvent(true);
  2611. }
  2612. }
  2613. // Fail if SSE UserInstance and we have not received this info.
  2614. if ( _connHandler.ConnectionOptions.UserInstance &&
  2615. ADP.IsEmpty(_connHandler.InstanceName)) {
  2616. stateObj.AddError(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, Server, SQLMessage.UserInstanceFailure(), "", 0));
  2617. ThrowExceptionAndWarning(stateObj);
  2618. }
  2619. sqlLoginAck = a;
  2620. return true;
  2621. }
  2622. private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, out SqlFedAuthInfo sqlFedAuthInfo) {
  2623. sqlFedAuthInfo = null;
  2624. SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo();
  2625. // Skip reading token length, since it has already been read in caller
  2626. if (Bid.AdvancedOn) {
  2627. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo> FEDAUTHINFO token stream length = {0}\n", tokenLen);
  2628. }
  2629. if (tokenLen < sizeof(uint)) {
  2630. // the token must at least contain a DWORD indicating the number of info IDs
  2631. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> FEDAUTHINFO token stream length too short for CountOfInfoIDs.\n");
  2632. throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen);
  2633. }
  2634. // read how many FedAuthInfo options there are
  2635. uint optionsCount;
  2636. if (!stateObj.TryReadUInt32(out optionsCount)) {
  2637. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.\n");
  2638. throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds);
  2639. }
  2640. tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount
  2641. if (Bid.AdvancedOn) {
  2642. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo> CountOfInfoIDs = {0}\n", optionsCount.ToString(CultureInfo.InvariantCulture));
  2643. }
  2644. if (tokenLen > 0) {
  2645. // read the rest of the token
  2646. byte[] tokenData = new byte[tokenLen];
  2647. int totalRead = 0;
  2648. bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead);
  2649. if (Bid.AdvancedOn) {
  2650. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo> Read rest of FEDAUTHINFO token stream: {0}\n", BitConverter.ToString(tokenData, 0, totalRead));
  2651. }
  2652. if (!successfulRead || totalRead != tokenLen) {
  2653. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}\n", tokenLen, totalRead);
  2654. throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream);
  2655. }
  2656. // each FedAuthInfoOpt is 9 bytes:
  2657. // 1 byte for FedAuthInfoID
  2658. // 4 bytes for FedAuthInfoDataLen
  2659. // 4 bytes for FedAuthInfoDataOffset
  2660. // So this is the index in tokenData for the i-th option
  2661. const uint optionSize = 9;
  2662. // the total number of bytes for all FedAuthInfoOpts together
  2663. uint totalOptionsSize = checked(optionsCount * optionSize);
  2664. for (uint i = 0; i < optionsCount; i++) {
  2665. uint currentOptionOffset = checked(i * optionSize);
  2666. byte id = tokenData[currentOptionOffset];
  2667. uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1)));
  2668. uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5)));
  2669. if (Bid.AdvancedOn) {
  2670. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo> FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}\n", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture));
  2671. }
  2672. // offset is measured from optCount, so subtract to make offset measured
  2673. // from the beginning of tokenData
  2674. checked {
  2675. dataOffset -= sizeof(uint);
  2676. }
  2677. // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw
  2678. if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) {
  2679. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> FedAuthInfoDataOffset points to an invalid location.\n");
  2680. throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset));
  2681. }
  2682. // try to read data and throw if the arguments are bad, meaning the server sent us a bad token
  2683. string data;
  2684. try {
  2685. data = System.Text.Encoding.Unicode.GetString(tokenData, checked((int)dataOffset), checked((int)dataLen));
  2686. }
  2687. catch (ArgumentOutOfRangeException e) {
  2688. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> Failed to read FedAuthInfoData.\n");
  2689. throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e);
  2690. }
  2691. catch (ArgumentException e) {
  2692. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> FedAuthInfoData is not in unicode format.\n");
  2693. throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e);
  2694. }
  2695. if (Bid.AdvancedOn) {
  2696. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo> FedAuthInfoData: {0}\n", data);
  2697. }
  2698. // store data in tempFedAuthInfo
  2699. switch ((TdsEnums.FedAuthInfoId)id) {
  2700. case TdsEnums.FedAuthInfoId.Spn:
  2701. tempFedAuthInfo.spn = data;
  2702. break;
  2703. case TdsEnums.FedAuthInfoId.Stsurl:
  2704. tempFedAuthInfo.stsurl = data;
  2705. break;
  2706. default:
  2707. if (Bid.AdvancedOn) {
  2708. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo> Ignoring unknown federated authentication info option: {0}\n", id);
  2709. }
  2710. break;
  2711. }
  2712. }
  2713. }
  2714. else {
  2715. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> FEDAUTHINFO token stream is not long enough to contain the data it claims to.\n");
  2716. throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen);
  2717. }
  2718. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo> Processed FEDAUTHINFO token stream: {0}\n", tempFedAuthInfo.ToString());
  2719. if (String.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || String.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) {
  2720. // We should be receiving both stsurl and spn
  2721. Bid.Trace("<sc.TdsParser.TryProcessFedAuthInfo|ERR> FEDAUTHINFO token stream does not contain both STSURL and SPN.\n");
  2722. throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn);
  2723. }
  2724. sqlFedAuthInfo = tempFedAuthInfo;
  2725. return true;
  2726. }
  2727. internal bool TryProcessError(byte token, TdsParserStateObject stateObj, out SqlError error) {
  2728. ushort shortLen;
  2729. byte byteLen;
  2730. int number;
  2731. byte state;
  2732. byte errorClass;
  2733. error = null;
  2734. if (!stateObj.TryReadInt32(out number)) {
  2735. return false;
  2736. }
  2737. if (!stateObj.TryReadByte(out state)) {
  2738. return false;
  2739. }
  2740. if (!stateObj.TryReadByte(out errorClass)) {
  2741. return false;
  2742. }
  2743. Debug.Assert(((errorClass >= TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLERROR) ||
  2744. ((errorClass < TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLINFO), "class and token don't match!");
  2745. if (!stateObj.TryReadUInt16(out shortLen)) {
  2746. return false;
  2747. }
  2748. string message;
  2749. if (!stateObj.TryReadString(shortLen, out message)) {
  2750. return false;
  2751. }
  2752. if (!stateObj.TryReadByte(out byteLen)) {
  2753. return false;
  2754. }
  2755. string server;
  2756. // MDAC bug #49307 - server sometimes does not send over server field! In those cases
  2757. // we will use our locally cached value.
  2758. if (byteLen == 0) {
  2759. server = _server;
  2760. }
  2761. else {
  2762. if (!stateObj.TryReadString(byteLen, out server)) {
  2763. return false;
  2764. }
  2765. }
  2766. if (!stateObj.TryReadByte(out byteLen)) {
  2767. return false;
  2768. }
  2769. string procedure;
  2770. if (!stateObj.TryReadString(byteLen, out procedure)) {
  2771. return false;
  2772. }
  2773. int line;
  2774. if (_isYukon) {
  2775. if (!stateObj.TryReadInt32(out line)) {
  2776. return false;
  2777. }
  2778. }
  2779. else {
  2780. ushort shortLine;
  2781. if (!stateObj.TryReadUInt16(out shortLine)) {
  2782. return false;
  2783. }
  2784. line = shortLine;
  2785. // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server
  2786. // In that case we still have to read another 2 bytes
  2787. if ( _state == TdsParserState.OpenNotLoggedIn) {
  2788. // Login incomplete
  2789. byte b;
  2790. if (!stateObj.TryPeekByte(out b)) {
  2791. return false;
  2792. }
  2793. if (b == 0) {
  2794. // This is an invalid token value
  2795. ushort value;
  2796. if (!stateObj.TryReadUInt16(out value)) {
  2797. return false;
  2798. }
  2799. line = (line << 16) + value;
  2800. }
  2801. }
  2802. }
  2803. error = new SqlError(number, state, errorClass, _server, message, procedure, line);
  2804. return true;
  2805. }
  2806. internal bool TryProcessReturnValue(int length,
  2807. TdsParserStateObject stateObj,
  2808. out SqlReturnValue returnValue,
  2809. SqlCommandColumnEncryptionSetting columnEncryptionSetting) {
  2810. returnValue = null;
  2811. SqlReturnValue rec = new SqlReturnValue();
  2812. rec.length = length; // In Yukon this length is -1
  2813. if (_isYukon) {
  2814. if (!stateObj.TryReadUInt16(out rec.parmIndex)) {
  2815. return false;
  2816. }
  2817. }
  2818. byte len;
  2819. if (!stateObj.TryReadByte(out len)) { // Length of parameter name
  2820. return false;
  2821. }
  2822. rec.parameter = null;
  2823. if (len > 0) {
  2824. if (!stateObj.TryReadString(len, out rec.parameter)) {
  2825. return false;
  2826. }
  2827. }
  2828. // read status and ignore
  2829. byte ignored;
  2830. if (!stateObj.TryReadByte(out ignored)) {
  2831. return false;
  2832. }
  2833. UInt32 userType;
  2834. // read user type - 4 bytes Yukon, 2 backwards
  2835. if (IsYukonOrNewer) {
  2836. if (!stateObj.TryReadUInt32(out userType)) {
  2837. return false;
  2838. }
  2839. }
  2840. else {
  2841. ushort userTypeShort;
  2842. if (!stateObj.TryReadUInt16(out userTypeShort)) {
  2843. return false;
  2844. }
  2845. userType = userTypeShort;
  2846. }
  2847. // Read off the flags.
  2848. // The first byte is ignored since it doesn't contain any interesting information.
  2849. byte flags;
  2850. if (!stateObj.TryReadByte(out flags)) {
  2851. return false;
  2852. }
  2853. if (!stateObj.TryReadByte(out flags)) {
  2854. return false;
  2855. }
  2856. // Check if the column is encrypted.
  2857. if (_serverSupportsColumnEncryption) {
  2858. rec.isEncrypted = (TdsEnums.IsEncrypted == (flags & TdsEnums.IsEncrypted));
  2859. }
  2860. // read the type
  2861. byte tdsType;
  2862. if (!stateObj.TryReadByte(out tdsType)) {
  2863. return false;
  2864. }
  2865. // read the MaxLen
  2866. // For xml datatpyes, there is no tokenLength
  2867. int tdsLen;
  2868. if (tdsType == TdsEnums.SQLXMLTYPE) {
  2869. tdsLen = TdsEnums.SQL_USHORTVARMAXLEN;
  2870. }
  2871. else if (IsVarTimeTds(tdsType))
  2872. tdsLen = 0; // placeholder until we read the scale, just make sure it's not SQL_USHORTVARMAXLEN
  2873. else if (tdsType == TdsEnums.SQLDATE) {
  2874. tdsLen = 3;
  2875. }
  2876. else {
  2877. if (!TryGetTokenLength(tdsType, stateObj, out tdsLen)) {
  2878. return false;
  2879. }
  2880. }
  2881. rec.metaType = MetaType.GetSqlDataType(tdsType, userType, tdsLen);
  2882. rec.type = rec.metaType.SqlDbType;
  2883. // always use the nullable type for parameters if Shiloh or later
  2884. // Sphinx sometimes sends fixed length return values
  2885. if (_isShiloh) {
  2886. rec.tdsType = rec.metaType.NullableType;
  2887. rec.isNullable = true;
  2888. if (tdsLen == TdsEnums.SQL_USHORTVARMAXLEN) {
  2889. Debug.Assert(_isYukon, "plp data from pre-Yukon server");
  2890. rec.metaType = MetaType.GetMaxMetaTypeFromMetaType(rec.metaType);
  2891. }
  2892. }
  2893. else { // For sphinx, keep the fixed type if that is what is returned
  2894. if (rec.metaType.NullableType == tdsType)
  2895. rec.isNullable = true;
  2896. rec.tdsType = (byte)tdsType;
  2897. }
  2898. if (rec.type == SqlDbType.Decimal) {
  2899. if (!stateObj.TryReadByte(out rec.precision)) {
  2900. return false;
  2901. }
  2902. if (!stateObj.TryReadByte(out rec.scale)) {
  2903. return false;
  2904. }
  2905. }
  2906. if (rec.metaType.IsVarTime) {
  2907. if (!stateObj.TryReadByte(out rec.scale)) {
  2908. return false;
  2909. }
  2910. }
  2911. if (tdsType == TdsEnums.SQLUDT) {
  2912. if (!TryProcessUDTMetaData((SqlMetaDataPriv) rec, stateObj)) {
  2913. return false;
  2914. }
  2915. }
  2916. if (rec.type == SqlDbType.Xml) {
  2917. // Read schema info
  2918. byte schemapresent;
  2919. if (!stateObj.TryReadByte(out schemapresent)) {
  2920. return false;
  2921. }
  2922. if ((schemapresent & 1) != 0) {
  2923. if (!stateObj.TryReadByte(out len)) {
  2924. return false;
  2925. }
  2926. if (len != 0) {
  2927. if (!stateObj.TryReadString(len, out rec.xmlSchemaCollectionDatabase)) {
  2928. return false;
  2929. }
  2930. }
  2931. if (!stateObj.TryReadByte(out len)) {
  2932. return false;
  2933. }
  2934. if (len != 0) {
  2935. if (!stateObj.TryReadString(len, out rec.xmlSchemaCollectionOwningSchema)) {
  2936. return false;
  2937. }
  2938. }
  2939. short slen;
  2940. if (!stateObj.TryReadInt16(out slen)) {
  2941. return false;
  2942. }
  2943. if (slen != 0) {
  2944. if (!stateObj.TryReadString(slen, out rec.xmlSchemaCollectionName)) {
  2945. return false;
  2946. }
  2947. }
  2948. }
  2949. }
  2950. else if (_isShiloh && rec.metaType.IsCharType) {
  2951. // read the collation for 8.x servers
  2952. if (!TryProcessCollation(stateObj, out rec.collation)) {
  2953. return false;
  2954. }
  2955. int codePage = GetCodePage(rec.collation, stateObj);
  2956. // if the column lcid is the same as the default, use the default encoder
  2957. if (codePage == _defaultCodePage) {
  2958. rec.codePage = _defaultCodePage;
  2959. rec.encoding = _defaultEncoding;
  2960. }
  2961. else {
  2962. rec.codePage = codePage;
  2963. rec.encoding = System.Text.Encoding.GetEncoding(rec.codePage);
  2964. }
  2965. }
  2966. // For encrypted parameters, read the unencrypted type and encryption information.
  2967. if (_serverSupportsColumnEncryption && rec.isEncrypted) {
  2968. if (!TryProcessTceCryptoMetadata(stateObj, rec, cipherTable: null, columnEncryptionSetting: columnEncryptionSetting, isReturnValue: true)) {
  2969. return false;
  2970. }
  2971. }
  2972. // for now we coerce return values into a SQLVariant, not good...
  2973. bool isNull = false;
  2974. ulong valLen;
  2975. if (!TryProcessColumnHeaderNoNBC(rec, stateObj, out isNull, out valLen)) {
  2976. return false;
  2977. }
  2978. // always read as sql types
  2979. Debug.Assert(valLen < (ulong)(Int32.MaxValue), "ProcessReturnValue received data size > 2Gb");
  2980. int intlen = valLen > (ulong)(Int32.MaxValue) ? Int32.MaxValue : (int)valLen;
  2981. if (rec.metaType.IsPlp) {
  2982. intlen = Int32.MaxValue; // If plp data, read it all
  2983. }
  2984. if (isNull) {
  2985. GetNullSqlValue(rec.value, rec, SqlCommandColumnEncryptionSetting.Disabled, _connHandler);
  2986. }
  2987. else {
  2988. // We should never do any decryption here, so pass disabled as the command encryption override.
  2989. // We only read the binary value and decryption will be performed by OnReturnValue().
  2990. if (!TryReadSqlValue(rec.value, rec, intlen, stateObj, SqlCommandColumnEncryptionSetting.Disabled, columnName:null /*Not used*/)) {
  2991. return false;
  2992. }
  2993. }
  2994. returnValue = rec;
  2995. return true;
  2996. }
  2997. internal bool TryProcessTceCryptoMetadata (TdsParserStateObject stateObj,
  2998. SqlMetaDataPriv col,
  2999. SqlTceCipherInfoTable? cipherTable,
  3000. SqlCommandColumnEncryptionSetting columnEncryptionSetting,
  3001. bool isReturnValue) {
  3002. Debug.Assert(isReturnValue == (cipherTable == null), "Ciphertable is not set iff this is a return value");
  3003. // Read the ordinal into cipher table
  3004. ushort index = 0;
  3005. UInt32 userType;
  3006. // For return values there is not cipher table and no ordinal.
  3007. if (cipherTable.HasValue) {
  3008. if (!stateObj.TryReadUInt16(out index)) {
  3009. return false;
  3010. }
  3011. // validate the index (ordinal passed)
  3012. if (index >= cipherTable.Value.Size) {
  3013. Bid.Trace("<sc.TdsParser.TryProcessTceCryptoMetadata|TCE> Incorrect ordinal received %d, max tab size: %d\n", index, cipherTable.Value.Size);
  3014. throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index);
  3015. }
  3016. }
  3017. // Read the user type
  3018. if (!stateObj.TryReadUInt32(out userType)) {
  3019. return false;
  3020. }
  3021. // Read the base TypeInfo
  3022. col.baseTI = new SqlMetaDataPriv();
  3023. if (!TryProcessTypeInfo(stateObj, col.baseTI, userType)) {
  3024. return false;
  3025. }
  3026. // Read the cipher algorithm Id
  3027. byte cipherAlgorithmId;
  3028. if (!stateObj.TryReadByte(out cipherAlgorithmId)) {
  3029. return false;
  3030. }
  3031. string cipherAlgorithmName = null;
  3032. if (TdsEnums.CustomCipherAlgorithmId == cipherAlgorithmId) {
  3033. // Custom encryption algorithm, read the name
  3034. byte nameSize;
  3035. if (!stateObj.TryReadByte(out nameSize)) {
  3036. return false;
  3037. }
  3038. if (!stateObj.TryReadString(nameSize, out cipherAlgorithmName)) {
  3039. return false;
  3040. }
  3041. }
  3042. // Read Encryption Type.
  3043. byte encryptionType;
  3044. if (!stateObj.TryReadByte(out encryptionType)) {
  3045. return false;
  3046. }
  3047. // Read Normalization Rule Version.
  3048. byte normalizationRuleVersion;
  3049. if (!stateObj.TryReadByte(out normalizationRuleVersion)) {
  3050. return false;
  3051. }
  3052. Debug.Assert(col.cipherMD == null, "col.cipherMD should be null in TryProcessTceCryptoMetadata.");
  3053. // Check if TCE is enable and if it is set the crypto MD for the column.
  3054. // TCE is enabled if the command is set to enabled or to resultset only and this is not a return value
  3055. // or if it is set to use connection setting and the connection has TCE enabled.
  3056. if ((columnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled ||
  3057. (columnEncryptionSetting == SqlCommandColumnEncryptionSetting.ResultSetOnly && !isReturnValue)) ||
  3058. (columnEncryptionSetting == SqlCommandColumnEncryptionSetting.UseConnectionSetting &&
  3059. _connHandler != null && _connHandler.ConnectionOptions != null &&
  3060. _connHandler.ConnectionOptions.ColumnEncryptionSetting == SqlConnectionColumnEncryptionSetting.Enabled)) {
  3061. col.cipherMD = new SqlCipherMetadata(cipherTable.HasValue ? (SqlTceCipherInfoEntry?)cipherTable.Value[index] : null,
  3062. index,
  3063. cipherAlgorithmId: cipherAlgorithmId,
  3064. cipherAlgorithmName: cipherAlgorithmName,
  3065. encryptionType: encryptionType,
  3066. normalizationRuleVersion: normalizationRuleVersion);
  3067. }
  3068. else {
  3069. // If TCE is disabled mark the MD as not encrypted.
  3070. col.isEncrypted = false;
  3071. }
  3072. return true;
  3073. }
  3074. internal bool TryProcessCollation(TdsParserStateObject stateObj, out SqlCollation collation) {
  3075. SqlCollation newCollation = new SqlCollation();
  3076. if (!stateObj.TryReadUInt32(out newCollation.info)) {
  3077. collation = null;
  3078. return false;
  3079. }
  3080. if (!stateObj.TryReadByte(out newCollation.sortId)) {
  3081. collation = null;
  3082. return false;
  3083. }
  3084. collation = newCollation;
  3085. return true;
  3086. }
  3087. private void WriteCollation(SqlCollation collation, TdsParserStateObject stateObj) {
  3088. if (collation == null) {
  3089. _physicalStateObj.WriteByte(0);
  3090. }
  3091. else {
  3092. _physicalStateObj.WriteByte(sizeof(UInt32)+sizeof(byte));
  3093. WriteUnsignedInt(collation.info, _physicalStateObj);
  3094. _physicalStateObj.WriteByte(collation.sortId);
  3095. }
  3096. }
  3097. internal int GetCodePage(SqlCollation collation, TdsParserStateObject stateObj) {
  3098. int codePage = 0;
  3099. if (0 != collation.sortId) {
  3100. codePage = TdsEnums.CODE_PAGE_FROM_SORT_ID[collation.sortId];
  3101. Debug.Assert(0 != codePage, "GetCodePage accessed codepage array and produced 0!, sortID =" + ((Byte)(collation.sortId)).ToString((IFormatProvider)null));
  3102. }
  3103. else {
  3104. int cultureId = collation.LCID;
  3105. bool success = false;
  3106. try {
  3107. codePage = CultureInfo.GetCultureInfo(cultureId).TextInfo.ANSICodePage;
  3108. // SqlHot 50001398: CodePage can be zero, but we should defer such errors until
  3109. // we actually MUST use the code page (i.e. don't error if no ANSI data is sent).
  3110. success = true;
  3111. }
  3112. catch (ArgumentException e) {
  3113. ADP.TraceExceptionWithoutRethrow(e);
  3114. }
  3115. // If we failed, it is quite possible this is because certain culture id's
  3116. // were removed in Win2k and beyond, however Sql Server still supports them.
  3117. // There is a workaround for the culture id's listed below, which is to mask
  3118. // off the sort id (the leading 1). If that fails, or we have a culture id
  3119. // other than the special cases below, we throw an error and throw away the
  3120. // rest of the results. For additional info, see MDAC 65963.
  3121. // SqlHot 50001398: Sometimes GetCultureInfo will return CodePage 0 instead of throwing.
  3122. // treat this as an error also, and switch into the special-case logic.
  3123. if (!success || codePage == 0) {
  3124. CultureInfo ci = null;
  3125. switch (cultureId) {
  3126. case 0x10404: // zh-TW
  3127. case 0x10804: // zh-CN
  3128. case 0x10c04: // zh-HK
  3129. case 0x11004: // zh-SG
  3130. case 0x11404: // zh-MO
  3131. case 0x10411: // ja-JP
  3132. case 0x10412: // ko-KR
  3133. // If one of the following special cases, mask out sortId and
  3134. // retry.
  3135. cultureId = cultureId & 0x03fff;
  3136. try {
  3137. ci = new CultureInfo(cultureId);
  3138. success = true;
  3139. }
  3140. catch (ArgumentException e) {
  3141. ADP.TraceExceptionWithoutRethrow(e);
  3142. }
  3143. break;
  3144. case 0x827: // Non-supported Lithuanian code page, map it to supported Lithuanian.
  3145. try {
  3146. ci = new CultureInfo(0x427);
  3147. success = true;
  3148. }
  3149. catch (ArgumentException e) {
  3150. ADP.TraceExceptionWithoutRethrow(e);
  3151. }
  3152. break;
  3153. default:
  3154. break;
  3155. }
  3156. // I don't believe we should still be in failure case, but just in case.
  3157. if (!success) {
  3158. ThrowUnsupportedCollationEncountered(stateObj);
  3159. }
  3160. if (null != ci) {
  3161. codePage = ci.TextInfo.ANSICodePage;
  3162. }
  3163. }
  3164. }
  3165. return codePage;
  3166. }
  3167. internal void DrainData(TdsParserStateObject stateObj) {
  3168. RuntimeHelpers.PrepareConstrainedRegions();
  3169. try {
  3170. #if DEBUG
  3171. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  3172. RuntimeHelpers.PrepareConstrainedRegions();
  3173. try {
  3174. tdsReliabilitySection.Start();
  3175. #else
  3176. {
  3177. #endif //DEBUG
  3178. try {
  3179. SqlDataReader.SharedState sharedState = stateObj._readerState;
  3180. if (sharedState != null && sharedState._dataReady) {
  3181. var metadata = stateObj._cleanupMetaData;
  3182. if (stateObj._partialHeaderBytesRead > 0) {
  3183. if (!stateObj.TryProcessHeader()) {
  3184. throw SQL.SynchronousCallMayNotPend();
  3185. }
  3186. }
  3187. if (0 == sharedState._nextColumnHeaderToRead) {
  3188. // i. user called read but didn't fetch anything
  3189. if (!stateObj.Parser.TrySkipRow(stateObj._cleanupMetaData, stateObj)) {
  3190. throw SQL.SynchronousCallMayNotPend();
  3191. }
  3192. }
  3193. else {
  3194. // iia. if we still have bytes left from a partially read column, skip
  3195. if (sharedState._nextColumnDataToRead < sharedState._nextColumnHeaderToRead) {
  3196. if ((sharedState._nextColumnHeaderToRead > 0) && (metadata[sharedState._nextColumnHeaderToRead - 1].metaType.IsPlp)) {
  3197. if (stateObj._longlen != 0) {
  3198. ulong ignored;
  3199. if (!TrySkipPlpValue(UInt64.MaxValue, stateObj, out ignored)) {
  3200. throw SQL.SynchronousCallMayNotPend();
  3201. }
  3202. }
  3203. }
  3204. else if (0 < sharedState._columnDataBytesRemaining) {
  3205. if (!stateObj.TrySkipLongBytes(sharedState._columnDataBytesRemaining)) {
  3206. throw SQL.SynchronousCallMayNotPend();
  3207. }
  3208. }
  3209. }
  3210. // iib.
  3211. // now read the remaining values off the wire for this row
  3212. if (!stateObj.Parser.TrySkipRow(metadata, sharedState._nextColumnHeaderToRead, stateObj)) {
  3213. throw SQL.SynchronousCallMayNotPend();
  3214. }
  3215. }
  3216. }
  3217. Run(RunBehavior.Clean, null, null, null, stateObj);
  3218. }
  3219. catch {
  3220. _connHandler.DoomThisConnection();
  3221. throw;
  3222. }
  3223. }
  3224. #if DEBUG
  3225. finally {
  3226. tdsReliabilitySection.Stop();
  3227. }
  3228. #endif //DEBUG
  3229. }
  3230. catch (System.OutOfMemoryException) {
  3231. _connHandler.DoomThisConnection();
  3232. throw;
  3233. }
  3234. catch (System.StackOverflowException) {
  3235. _connHandler.DoomThisConnection();
  3236. throw;
  3237. }
  3238. catch (System.Threading.ThreadAbortException) {
  3239. _connHandler.DoomThisConnection();
  3240. throw;
  3241. }
  3242. }
  3243. internal void ThrowUnsupportedCollationEncountered(TdsParserStateObject stateObj) {
  3244. stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.CultureIdError(), "", 0));
  3245. if (null != stateObj) {
  3246. DrainData(stateObj);
  3247. stateObj._pendingData = false;
  3248. }
  3249. ThrowExceptionAndWarning(stateObj);
  3250. }
  3251. internal bool TryProcessAltMetaData(int cColumns, TdsParserStateObject stateObj, out _SqlMetaDataSet metaData) {
  3252. Debug.Assert(cColumns > 0, "should have at least 1 column in altMetaData!");
  3253. metaData = null;
  3254. _SqlMetaDataSet altMetaDataSet = new _SqlMetaDataSet(cColumns, null);
  3255. int[] indexMap = new int[cColumns];
  3256. if (!stateObj.TryReadUInt16(out altMetaDataSet.id)) {
  3257. return false;
  3258. }
  3259. byte byCols;
  3260. if (!stateObj.TryReadByte(out byCols)) {
  3261. return false;
  3262. }
  3263. while (byCols > 0) {
  3264. if (!stateObj.TrySkipBytes(2)) { // ignore ColNum ...
  3265. return false;
  3266. }
  3267. byCols--;
  3268. }
  3269. // pass 1, read the meta data off the wire
  3270. for (int i = 0; i < cColumns; i++) {
  3271. // internal meta data class
  3272. _SqlMetaData col = altMetaDataSet[i];
  3273. if (!stateObj.TryReadByte(out col.op)) {
  3274. return false;
  3275. }
  3276. if (!stateObj.TryReadUInt16(out col.operand)) {
  3277. return false;
  3278. }
  3279. // TCE is not applicable to AltMetadata.
  3280. if (!TryCommonProcessMetaData(stateObj, col, null, fColMD: false, columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Disabled)) {
  3281. return false;
  3282. }
  3283. if (ADP.IsEmpty(col.column)) {
  3284. // create column name from op
  3285. switch (col.op) {
  3286. case TdsEnums.AOPAVG:
  3287. col.column = "avg";
  3288. break;
  3289. case TdsEnums.AOPCNT:
  3290. col.column = "cnt";
  3291. break;
  3292. case TdsEnums.AOPCNTB:
  3293. col.column = "cntb";
  3294. break;
  3295. case TdsEnums.AOPMAX:
  3296. col.column = "max";
  3297. break;
  3298. case TdsEnums.AOPMIN:
  3299. col.column = "min";
  3300. break;
  3301. case TdsEnums.AOPSUM:
  3302. col.column = "sum";
  3303. break;
  3304. case TdsEnums.AOPANY:
  3305. col.column = "any";
  3306. break;
  3307. case TdsEnums.AOPNOOP:
  3308. col.column = "noop";
  3309. break;
  3310. case TdsEnums.AOPSTDEV:
  3311. col.column = "stdev";
  3312. break;
  3313. case TdsEnums.AOPSTDEVP:
  3314. col.column = "stdevp";
  3315. break;
  3316. case TdsEnums.AOPVAR:
  3317. col.column = "var";
  3318. break;
  3319. case TdsEnums.AOPVARP:
  3320. col.column = "varp";
  3321. break;
  3322. }
  3323. }
  3324. indexMap[i] = i;
  3325. }
  3326. altMetaDataSet.indexMap = indexMap;
  3327. altMetaDataSet.visibleColumns = cColumns;
  3328. metaData = altMetaDataSet;
  3329. return true;
  3330. }
  3331. /// <summary>
  3332. /// <para> Parses the TDS message to read single CIPHER_INFO entry.</para>
  3333. /// </summary>
  3334. internal bool TryReadCipherInfoEntry (TdsParserStateObject stateObj, out SqlTceCipherInfoEntry entry) {
  3335. byte cekValueCount = 0;
  3336. entry = new SqlTceCipherInfoEntry(ordinal: 0);
  3337. // Read the DB ID
  3338. int dbId;
  3339. if (!stateObj.TryReadInt32(out dbId)) {
  3340. return false;
  3341. }
  3342. // Read the keyID
  3343. int keyId;
  3344. if (!stateObj.TryReadInt32(out keyId)) {
  3345. return false;
  3346. }
  3347. // Read the key version
  3348. int keyVersion;
  3349. if (!stateObj.TryReadInt32(out keyVersion)) {
  3350. return false;
  3351. }
  3352. // Read the key MD Version
  3353. byte[] keyMDVersion = new byte[8];
  3354. if (!stateObj.TryReadByteArray(keyMDVersion, 0, 8)) {
  3355. return false;
  3356. }
  3357. // Read the value count
  3358. if (!stateObj.TryReadByte (out cekValueCount)) {
  3359. return false;
  3360. }
  3361. for (int i = 0; i < cekValueCount; i++) {
  3362. // Read individual CEK values
  3363. byte[] encryptedCek;
  3364. string keyPath;
  3365. string keyStoreName;
  3366. byte algorithmLength;
  3367. string algorithmName;
  3368. ushort shortValue;
  3369. byte byteValue;
  3370. int length;
  3371. // Read the length of encrypted CEK
  3372. if (!stateObj.TryReadUInt16 (out shortValue)) {
  3373. return false;
  3374. }
  3375. length = shortValue;
  3376. encryptedCek = new byte[length];
  3377. // Read the actual encrypted CEK
  3378. if (!stateObj.TryReadByteArray (encryptedCek, 0, length)) {
  3379. return false;
  3380. }
  3381. // Read the length of key store name
  3382. if (!stateObj.TryReadByte (out byteValue)) {
  3383. return false;
  3384. }
  3385. length = byteValue;
  3386. // And read the key store name now
  3387. if (!stateObj.TryReadString(length, out keyStoreName)) {
  3388. return false;
  3389. }
  3390. // Read the length of key Path
  3391. if (!stateObj.TryReadUInt16 (out shortValue)) {
  3392. return false;
  3393. }
  3394. length = shortValue;
  3395. // Read the key path string
  3396. if (!stateObj.TryReadString(length, out keyPath)) {
  3397. return false;
  3398. }
  3399. // Read the length of the string carrying the encryption algo
  3400. if (!stateObj.TryReadByte(out algorithmLength)) {
  3401. return false;
  3402. }
  3403. length = (int)algorithmLength;
  3404. // Read the string carrying the encryption algo (eg. RSA_PKCS_OAEP)
  3405. if (!stateObj.TryReadString(length, out algorithmName)) {
  3406. return false;
  3407. }
  3408. // Add this encrypted CEK blob to our list of encrypted values for the CEK
  3409. entry.Add(encryptedCek,
  3410. databaseId: dbId,
  3411. cekId: keyId,
  3412. cekVersion: keyVersion,
  3413. cekMdVersion: keyMDVersion,
  3414. keyPath: keyPath,
  3415. keyStoreName: keyStoreName,
  3416. algorithmName: algorithmName);
  3417. }
  3418. return true;
  3419. }
  3420. /// <summary>
  3421. /// <para> Parses the TDS message to read a single CIPHER_INFO table.</para>
  3422. /// </summary>
  3423. internal bool TryProcessCipherInfoTable (TdsParserStateObject stateObj, out SqlTceCipherInfoTable? cipherTable) {
  3424. // Read count
  3425. short tableSize = 0;
  3426. cipherTable = null;
  3427. if (!stateObj.TryReadInt16(out tableSize)) {
  3428. return false;
  3429. }
  3430. if (0 != tableSize) {
  3431. SqlTceCipherInfoTable tempTable = new SqlTceCipherInfoTable(tableSize);
  3432. // Read individual entries
  3433. for (int i = 0; i < tableSize; i++) {
  3434. SqlTceCipherInfoEntry entry;
  3435. if (!TryReadCipherInfoEntry (stateObj, out entry)) {
  3436. return false;
  3437. }
  3438. tempTable[i] = entry;
  3439. }
  3440. cipherTable = tempTable;
  3441. }
  3442. return true;
  3443. }
  3444. internal bool TryProcessMetaData(int cColumns, TdsParserStateObject stateObj, out _SqlMetaDataSet metaData, SqlCommandColumnEncryptionSetting columnEncryptionSetting) {
  3445. Debug.Assert(cColumns > 0, "should have at least 1 column in metadata!");
  3446. // Read the cipher info table first
  3447. SqlTceCipherInfoTable? cipherTable = null;
  3448. if (_serverSupportsColumnEncryption) {
  3449. if (!TryProcessCipherInfoTable (stateObj, out cipherTable)) {
  3450. metaData = null;
  3451. return false;
  3452. }
  3453. }
  3454. // Read the ColumnData fields
  3455. _SqlMetaDataSet newMetaData = new _SqlMetaDataSet(cColumns, cipherTable);
  3456. for (int i = 0; i < cColumns; i++) {
  3457. if (!TryCommonProcessMetaData(stateObj, newMetaData[i], cipherTable, fColMD: true, columnEncryptionSetting: columnEncryptionSetting)) {
  3458. metaData = null;
  3459. return false;
  3460. }
  3461. }
  3462. // DEVNOTE: cipherTable is discarded at this point since its no longer needed.
  3463. metaData = newMetaData;
  3464. return true;
  3465. }
  3466. private bool IsVarTimeTds(byte tdsType) {
  3467. return tdsType == TdsEnums.SQLTIME || tdsType == TdsEnums.SQLDATETIME2 || tdsType == TdsEnums.SQLDATETIMEOFFSET;
  3468. }
  3469. private bool TryProcessTypeInfo (TdsParserStateObject stateObj, SqlMetaDataPriv col, UInt32 userType) {
  3470. byte byteLen;
  3471. byte tdsType;
  3472. if (!stateObj.TryReadByte(out tdsType)) {
  3473. return false;
  3474. }
  3475. if (tdsType == TdsEnums.SQLXMLTYPE)
  3476. col.length = TdsEnums.SQL_USHORTVARMAXLEN; //Use the same length as other plp datatypes
  3477. else if (IsVarTimeTds(tdsType))
  3478. col.length = 0; // placeholder until we read the scale, just make sure it's not SQL_USHORTVARMAXLEN
  3479. else if (tdsType == TdsEnums.SQLDATE) {
  3480. col.length = 3;
  3481. }
  3482. else {
  3483. if (!TryGetTokenLength(tdsType, stateObj, out col.length)) {
  3484. return false;
  3485. }
  3486. }
  3487. col.metaType = MetaType.GetSqlDataType(tdsType, userType, col.length);
  3488. col.type = col.metaType.SqlDbType;
  3489. // If sphinx, do not change to nullable type
  3490. if (_isShiloh)
  3491. col.tdsType = (col.isNullable ? col.metaType.NullableType : col.metaType.TDSType);
  3492. else
  3493. col.tdsType = tdsType;
  3494. if (_isYukon) {
  3495. if (TdsEnums.SQLUDT == tdsType) {
  3496. if (!TryProcessUDTMetaData((SqlMetaDataPriv) col, stateObj)) {
  3497. return false;
  3498. }
  3499. }
  3500. if (col.length == TdsEnums.SQL_USHORTVARMAXLEN) {
  3501. Debug.Assert(tdsType == TdsEnums.SQLXMLTYPE ||
  3502. tdsType == TdsEnums.SQLBIGVARCHAR ||
  3503. tdsType == TdsEnums.SQLBIGVARBINARY ||
  3504. tdsType == TdsEnums.SQLNVARCHAR ||
  3505. tdsType == TdsEnums.SQLUDT,
  3506. "Invalid streaming datatype");
  3507. col.metaType = MetaType.GetMaxMetaTypeFromMetaType(col.metaType);
  3508. Debug.Assert(col.metaType.IsLong, "Max datatype not IsLong");
  3509. col.length = Int32.MaxValue;
  3510. if (tdsType == TdsEnums.SQLXMLTYPE) {
  3511. byte schemapresent;
  3512. if (!stateObj.TryReadByte(out schemapresent)) {
  3513. return false;
  3514. }
  3515. if ((schemapresent & 1) != 0) {
  3516. if (!stateObj.TryReadByte(out byteLen)) {
  3517. return false;
  3518. }
  3519. if (byteLen != 0) {
  3520. if (!stateObj.TryReadString(byteLen, out col.xmlSchemaCollectionDatabase)) {
  3521. return false;
  3522. }
  3523. }
  3524. if (!stateObj.TryReadByte(out byteLen)) {
  3525. return false;
  3526. }
  3527. if (byteLen != 0) {
  3528. if (!stateObj.TryReadString(byteLen, out col.xmlSchemaCollectionOwningSchema)) {
  3529. return false;
  3530. }
  3531. }
  3532. short shortLen;
  3533. if (!stateObj.TryReadInt16(out shortLen)) {
  3534. return false;
  3535. }
  3536. if (byteLen != 0) {
  3537. if (!stateObj.TryReadString(shortLen, out col.xmlSchemaCollectionName)) {
  3538. return false;
  3539. }
  3540. }
  3541. }
  3542. }
  3543. }
  3544. }
  3545. if (col.type == SqlDbType.Decimal) {
  3546. if (!stateObj.TryReadByte(out col.precision)) {
  3547. return false;
  3548. }
  3549. if (!stateObj.TryReadByte(out col.scale)) {
  3550. return false;
  3551. }
  3552. }
  3553. if (col.metaType.IsVarTime) {
  3554. if (!stateObj.TryReadByte(out col.scale)) {
  3555. return false;
  3556. }
  3557. Debug.Assert(0 <= col.scale && col.scale <= 7);
  3558. // calculate actual column length here
  3559. //
  3560. switch (col.metaType.SqlDbType)
  3561. {
  3562. case SqlDbType.Time:
  3563. col.length = MetaType.GetTimeSizeFromScale(col.scale);
  3564. break;
  3565. case SqlDbType.DateTime2:
  3566. // Date in number of days (3 bytes) + time
  3567. col.length = 3 + MetaType.GetTimeSizeFromScale(col.scale);
  3568. break;
  3569. case SqlDbType.DateTimeOffset:
  3570. // Date in days (3 bytes) + offset in minutes (2 bytes) + time
  3571. col.length = 5 + MetaType.GetTimeSizeFromScale(col.scale);
  3572. break;
  3573. default:
  3574. Debug.Assert(false, "Unknown VariableTime type!");
  3575. break;
  3576. }
  3577. }
  3578. // read the collation for 7.x servers
  3579. if (_isShiloh && col.metaType.IsCharType && (tdsType != TdsEnums.SQLXMLTYPE)) {
  3580. if (!TryProcessCollation(stateObj, out col.collation)) {
  3581. return false;
  3582. }
  3583. int codePage = GetCodePage(col.collation, stateObj);
  3584. if (codePage == _defaultCodePage) {
  3585. col.codePage = _defaultCodePage;
  3586. col.encoding = _defaultEncoding;
  3587. }
  3588. else {
  3589. col.codePage = codePage;
  3590. col.encoding = System.Text.Encoding.GetEncoding(col.codePage);
  3591. }
  3592. }
  3593. return true;
  3594. }
  3595. private bool TryCommonProcessMetaData(TdsParserStateObject stateObj, _SqlMetaData col, SqlTceCipherInfoTable? cipherTable, bool fColMD, SqlCommandColumnEncryptionSetting columnEncryptionSetting) {
  3596. byte byteLen;
  3597. UInt32 userType;
  3598. // read user type - 4 bytes Yukon, 2 backwards
  3599. if (IsYukonOrNewer) {
  3600. if (!stateObj.TryReadUInt32(out userType)) {
  3601. return false;
  3602. }
  3603. }
  3604. else {
  3605. ushort userTypeShort;
  3606. if (!stateObj.TryReadUInt16(out userTypeShort)) {
  3607. return false;
  3608. }
  3609. userType = userTypeShort;
  3610. }
  3611. // read flags and set appropriate flags in structure
  3612. byte flags;
  3613. if (!stateObj.TryReadByte(out flags)) {
  3614. return false;
  3615. }
  3616. col.updatability = (byte)((flags & TdsEnums.Updatability) >> 2);
  3617. col.isNullable = (TdsEnums.Nullable == (flags & TdsEnums.Nullable));
  3618. col.isIdentity = (TdsEnums.Identity == (flags & TdsEnums.Identity));
  3619. // read second byte of column metadata flags
  3620. if (!stateObj.TryReadByte(out flags)) {
  3621. return false;
  3622. }
  3623. col.isColumnSet = (TdsEnums.IsColumnSet == (flags & TdsEnums.IsColumnSet));
  3624. if (fColMD && _serverSupportsColumnEncryption) {
  3625. col.isEncrypted = (TdsEnums.IsEncrypted == (flags & TdsEnums.IsEncrypted));
  3626. }
  3627. // Read TypeInfo
  3628. if (!TryProcessTypeInfo (stateObj, col, userType)) {
  3629. return false;
  3630. }
  3631. // Read tablename if present
  3632. if (col.metaType.IsLong && !col.metaType.IsPlp) {
  3633. if (_isYukon) {
  3634. int unusedLen = 0xFFFF; //We ignore this value
  3635. if (!TryProcessOneTable(stateObj, ref unusedLen, out col.multiPartTableName)) {
  3636. return false;
  3637. }
  3638. } else {
  3639. ushort shortLen;
  3640. if (!stateObj.TryReadUInt16(out shortLen)) {
  3641. return false;
  3642. }
  3643. string tableName;
  3644. if (!stateObj.TryReadString(shortLen, out tableName)) {
  3645. return false;
  3646. }
  3647. // with Sql2000 this is returned as an unquoted mix of catalog.owner.table
  3648. // all of which may contain "." and unable to parse correctly from the string alone
  3649. // example "select * from pubs..[A.B.C.D.E]" AND only when * will contain a image/text/ntext column
  3650. // by delay parsing from execute to SqlDataReader.GetSchemaTable to enable more scenarios
  3651. col.multiPartTableName = new MultiPartTableName(tableName);
  3652. }
  3653. }
  3654. // Read the TCE column cryptoinfo
  3655. if (fColMD && _serverSupportsColumnEncryption && col.isEncrypted) {
  3656. // If the column is encrypted, we should have a valid cipherTable
  3657. if (cipherTable.HasValue && !TryProcessTceCryptoMetadata (stateObj, col, cipherTable.Value, columnEncryptionSetting, isReturnValue: false)) {
  3658. return false;
  3659. }
  3660. }
  3661. // Read the column name
  3662. if (!stateObj.TryReadByte(out byteLen)) {
  3663. return false;
  3664. }
  3665. if (!stateObj.TryReadString(byteLen, out col.column)) {
  3666. return false;
  3667. }
  3668. // We get too many DONE COUNTs from the server, causing too meany StatementCompleted event firings.
  3669. // We only need to fire this event when we actually have a meta data stream with 0 or more rows.
  3670. stateObj._receivedColMetaData = true;
  3671. return true;
  3672. }
  3673. private bool TryProcessUDTMetaData(SqlMetaDataPriv metaData, TdsParserStateObject stateObj) {
  3674. ushort shortLength;
  3675. byte byteLength;
  3676. if (!stateObj.TryReadUInt16(out shortLength)) { // max byte size
  3677. return false;
  3678. }
  3679. metaData.length = shortLength;
  3680. // database name
  3681. if (!stateObj.TryReadByte(out byteLength)) {
  3682. return false;
  3683. }
  3684. if (byteLength != 0) {
  3685. if (!stateObj.TryReadString(byteLength, out metaData.udtDatabaseName)) {
  3686. return false;
  3687. }
  3688. }
  3689. // schema name
  3690. if (!stateObj.TryReadByte(out byteLength)) {
  3691. return false;
  3692. }
  3693. if (byteLength != 0) {
  3694. if (!stateObj.TryReadString(byteLength, out metaData.udtSchemaName)) {
  3695. return false;
  3696. }
  3697. }
  3698. // type name
  3699. if (!stateObj.TryReadByte(out byteLength)) {
  3700. return false;
  3701. }
  3702. if (byteLength != 0) {
  3703. if (!stateObj.TryReadString(byteLength, out metaData.udtTypeName)) {
  3704. return false;
  3705. }
  3706. }
  3707. if (!stateObj.TryReadUInt16(out shortLength)) {
  3708. return false;
  3709. }
  3710. if (shortLength != 0) {
  3711. if (!stateObj.TryReadString(shortLength, out metaData.udtAssemblyQualifiedName)) {
  3712. return false;
  3713. }
  3714. }
  3715. return true;
  3716. }
  3717. private void WriteUDTMetaData(object value, string database, string schema, string type,
  3718. TdsParserStateObject stateObj) {
  3719. // database
  3720. if (ADP.IsEmpty(database)) {
  3721. stateObj.WriteByte(0);
  3722. }
  3723. else {
  3724. stateObj.WriteByte((byte)database.Length);
  3725. WriteString(database, stateObj);
  3726. }
  3727. // schema
  3728. if (ADP.IsEmpty(schema)) {
  3729. stateObj.WriteByte(0);
  3730. }
  3731. else {
  3732. stateObj.WriteByte((byte)schema.Length);
  3733. WriteString(schema, stateObj);
  3734. }
  3735. // type
  3736. if (ADP.IsEmpty(type)) {
  3737. stateObj.WriteByte(0);
  3738. }
  3739. else {
  3740. stateObj.WriteByte((byte)type.Length);
  3741. WriteString(type, stateObj);
  3742. }
  3743. }
  3744. internal bool TryProcessTableName(int length, TdsParserStateObject stateObj, out MultiPartTableName[] multiPartTableNames) {
  3745. int tablesAdded = 0;
  3746. MultiPartTableName[] tables = new MultiPartTableName[1];
  3747. MultiPartTableName mpt;
  3748. while (length > 0) {
  3749. //
  3750. if (!TryProcessOneTable(stateObj, ref length, out mpt)) {
  3751. multiPartTableNames = null;
  3752. return false;
  3753. }
  3754. if (tablesAdded == 0) {
  3755. tables[tablesAdded] = mpt;
  3756. }
  3757. else {
  3758. MultiPartTableName[] newTables = new MultiPartTableName[tables.Length + 1];
  3759. Array.Copy(tables, 0, newTables, 0, tables.Length);
  3760. newTables[tables.Length] = mpt;
  3761. tables = newTables;
  3762. }
  3763. tablesAdded++;
  3764. }
  3765. multiPartTableNames = tables;
  3766. return true;
  3767. }
  3768. private bool TryProcessOneTable(TdsParserStateObject stateObj, ref int length, out MultiPartTableName multiPartTableName) {
  3769. ushort tableLen;
  3770. MultiPartTableName mpt;
  3771. string value;
  3772. multiPartTableName = default(MultiPartTableName);
  3773. if (_isShilohSP1) {
  3774. mpt = new MultiPartTableName();
  3775. byte nParts;
  3776. // Find out how many parts in the TDS stream
  3777. if (!stateObj.TryReadByte(out nParts)) {
  3778. return false;
  3779. }
  3780. length--;
  3781. if (nParts == 4) {
  3782. if (!stateObj.TryReadUInt16(out tableLen)) {
  3783. return false;
  3784. }
  3785. length -= 2;
  3786. if (!stateObj.TryReadString(tableLen, out value)) {
  3787. return false;
  3788. }
  3789. mpt.ServerName = value;
  3790. nParts--;
  3791. length -= (tableLen * 2); // wide bytes
  3792. }
  3793. if (nParts == 3) {
  3794. if (!stateObj.TryReadUInt16(out tableLen)) {
  3795. return false;
  3796. }
  3797. length -= 2;
  3798. if (!stateObj.TryReadString(tableLen, out value)) {
  3799. return false;
  3800. }
  3801. mpt.CatalogName = value;
  3802. length -= (tableLen * 2); // wide bytes
  3803. nParts--;
  3804. }
  3805. if (nParts == 2) {
  3806. if (!stateObj.TryReadUInt16(out tableLen)) {
  3807. return false;
  3808. }
  3809. length -= 2;
  3810. if (!stateObj.TryReadString(tableLen, out value)) {
  3811. return false;
  3812. }
  3813. mpt.SchemaName = value;
  3814. length -= (tableLen * 2); // wide bytes
  3815. nParts--;
  3816. }
  3817. if (nParts == 1) {
  3818. if (!stateObj.TryReadUInt16(out tableLen)) {
  3819. return false;
  3820. }
  3821. length -= 2;
  3822. if (!stateObj.TryReadString(tableLen, out value)) {
  3823. return false;
  3824. }
  3825. mpt.TableName = value;
  3826. length -= (tableLen * 2); // wide bytes
  3827. nParts--;
  3828. }
  3829. Debug.Assert(nParts == 0 , "ProcessTableName:Unidentified parts in the table name token stream!");
  3830. }
  3831. else {
  3832. if (!stateObj.TryReadUInt16(out tableLen)) {
  3833. return false;
  3834. }
  3835. length -= 2;
  3836. if (!stateObj.TryReadString(tableLen, out value)) {
  3837. return false;
  3838. }
  3839. string tableName = value;
  3840. length -= (tableLen * 2); // wide bytes
  3841. mpt = new MultiPartTableName(MultipartIdentifier.ParseMultipartIdentifier(tableName, "[\"", "]\"", Res.SQL_TDSParserTableName, false));
  3842. }
  3843. multiPartTableName = mpt;
  3844. return true;
  3845. }
  3846. // augments current metadata with table and key information
  3847. private bool TryProcessColInfo(_SqlMetaDataSet columns, SqlDataReader reader, TdsParserStateObject stateObj, out _SqlMetaDataSet metaData) {
  3848. Debug.Assert(columns != null && columns.Length > 0, "no metadata available!");
  3849. metaData = null;
  3850. for (int i = 0; i < columns.Length; i++) {
  3851. _SqlMetaData col = columns[i];
  3852. byte ignored;
  3853. if (!stateObj.TryReadByte(out ignored)) { // colnum, ignore
  3854. return false;
  3855. }
  3856. if (!stateObj.TryReadByte(out col.tableNum)) {
  3857. return false;
  3858. }
  3859. // interpret status
  3860. byte status;
  3861. if (!stateObj.TryReadByte(out status)) {
  3862. return false;
  3863. }
  3864. col.isDifferentName = (TdsEnums.SQLDifferentName == (status & TdsEnums.SQLDifferentName));
  3865. col.isExpression = (TdsEnums.SQLExpression == (status & TdsEnums.SQLExpression));
  3866. col.isKey = (TdsEnums.SQLKey == (status & TdsEnums.SQLKey));
  3867. col.isHidden = (TdsEnums.SQLHidden == (status & TdsEnums.SQLHidden));
  3868. // read off the base table name if it is different than the select list column name
  3869. if (col.isDifferentName) {
  3870. byte len;
  3871. if (!stateObj.TryReadByte(out len)) {
  3872. return false;
  3873. }
  3874. if (!stateObj.TryReadString(len, out col.baseColumn)) {
  3875. return false;
  3876. }
  3877. }
  3878. // Fixup column name - only if result of a table - that is if it was not the result of
  3879. // an expression.
  3880. if ((reader.TableNames != null) && (col.tableNum > 0)) {
  3881. Debug.Assert(reader.TableNames.Length >= col.tableNum, "invalid tableNames array!");
  3882. col.multiPartTableName = reader.TableNames[col.tableNum - 1];
  3883. }
  3884. // MDAC 60109: expressions are readonly
  3885. if (col.isExpression) {
  3886. col.updatability = 0;
  3887. }
  3888. }
  3889. // set the metadata so that the stream knows some metadata info has changed
  3890. metaData = columns;
  3891. return true;
  3892. }
  3893. // takes care of any per data header information:
  3894. // for long columns, reads off textptrs, reads length, check nullability
  3895. // for other columns, reads length, checks nullability
  3896. // returns length and nullability
  3897. internal bool TryProcessColumnHeader(SqlMetaDataPriv col, TdsParserStateObject stateObj, int columnOrdinal, out bool isNull, out ulong length) {
  3898. // query NBC row information first
  3899. if (stateObj.IsNullCompressionBitSet(columnOrdinal)) {
  3900. isNull = true;
  3901. // column information is not present in TDS if null compression bit is set, return now
  3902. length = 0;
  3903. return true;
  3904. }
  3905. return TryProcessColumnHeaderNoNBC(col, stateObj, out isNull, out length);
  3906. }
  3907. private bool TryProcessColumnHeaderNoNBC(SqlMetaDataPriv col, TdsParserStateObject stateObj, out bool isNull, out ulong length) {
  3908. if (col.metaType.IsLong && !col.metaType.IsPlp) {
  3909. //
  3910. // we don't care about TextPtrs, simply go after the data after it
  3911. //
  3912. byte textPtrLen;
  3913. if (!stateObj.TryReadByte(out textPtrLen)) {
  3914. isNull = false;
  3915. length = 0;
  3916. return false;
  3917. }
  3918. if (0 != textPtrLen) {
  3919. // read past text pointer
  3920. if (!stateObj.TrySkipBytes(textPtrLen)) {
  3921. isNull = false;
  3922. length = 0;
  3923. return false;
  3924. }
  3925. // read past timestamp
  3926. if (!stateObj.TrySkipBytes(TdsEnums.TEXT_TIME_STAMP_LEN)) {
  3927. isNull = false;
  3928. length = 0;
  3929. return false;
  3930. }
  3931. isNull = false;
  3932. return TryGetDataLength(col, stateObj, out length);
  3933. }
  3934. else {
  3935. isNull = true;
  3936. length = 0;
  3937. return true;
  3938. }
  3939. }
  3940. else {
  3941. // non-blob columns
  3942. ulong longlen;
  3943. if (!TryGetDataLength(col, stateObj, out longlen)) {
  3944. isNull = false;
  3945. length = 0;
  3946. return false;
  3947. }
  3948. isNull = IsNull(col.metaType, longlen);
  3949. length = (isNull ? 0 : longlen);
  3950. return true;
  3951. }
  3952. }
  3953. // assumes that the current position is at the start of an altrow!
  3954. internal bool TryGetAltRowId(TdsParserStateObject stateObj, out int id) {
  3955. byte token;
  3956. if (!stateObj.TryReadByte(out token)) { // skip over ALTROW token
  3957. id = 0;
  3958. return false;
  3959. }
  3960. Debug.Assert((token == TdsEnums.SQLALTROW), "");
  3961. // Start a fresh row - disable NBC since Alt Rows are never compressed
  3962. if (!stateObj.TryStartNewRow(isNullCompressed: false)) {
  3963. id = 0;
  3964. return false;
  3965. }
  3966. ushort shortId;
  3967. if (!stateObj.TryReadUInt16(out shortId)) {
  3968. id = 0;
  3969. return false;
  3970. }
  3971. id = shortId;
  3972. return true;
  3973. }
  3974. // Used internally by BulkCopy only
  3975. private bool TryProcessRow(_SqlMetaDataSet columns, object[] buffer, int[] map, TdsParserStateObject stateObj) {
  3976. SqlBuffer data = new SqlBuffer();
  3977. for (int i = 0; i < columns.Length; i++) {
  3978. _SqlMetaData md = columns[i];
  3979. Debug.Assert(md != null, "_SqlMetaData should not be null for column " + i.ToString(CultureInfo.InvariantCulture));
  3980. bool isNull;
  3981. ulong len;
  3982. if (!TryProcessColumnHeader(md, stateObj, i, out isNull, out len)) {
  3983. return false;
  3984. }
  3985. if (isNull) {
  3986. GetNullSqlValue(data, md, SqlCommandColumnEncryptionSetting.Disabled /*Column Encryption Disabled for Bulk Copy*/, _connHandler);
  3987. buffer[map[i]] = data.SqlValue;
  3988. }
  3989. else {
  3990. // We only read up to 2Gb. Throw if data is larger. Very large data
  3991. // should be read in chunks in sequential read mode
  3992. // For Plp columns, we may have gotten only the length of the first chunk
  3993. if (!TryReadSqlValue(data, md, md.metaType.IsPlp ? (Int32.MaxValue) : (int)len, stateObj,
  3994. SqlCommandColumnEncryptionSetting.Disabled /*Column Encryption Disabled for Bulk Copy*/,
  3995. md.column)) {
  3996. return false;
  3997. }
  3998. buffer[map[i]] = data.SqlValue;
  3999. if (stateObj._longlen != 0) {
  4000. throw new SqlTruncateException(Res.GetString(Res.SqlMisc_TruncationMaxDataMessage));
  4001. }
  4002. }
  4003. data.Clear();
  4004. }
  4005. return true;
  4006. }
  4007. /// <summary>
  4008. /// Determines if a column value should be transparently decrypted (based on SqlCommand and Connection String settings).
  4009. /// </summary>
  4010. /// <returns>true if the value should be transparently decrypted, false otherwise</returns>
  4011. internal static bool ShouldHonorTceForRead (SqlCommandColumnEncryptionSetting columnEncryptionSetting,
  4012. SqlInternalConnectionTds connection) {
  4013. // Command leve setting trumps all
  4014. switch (columnEncryptionSetting) {
  4015. case SqlCommandColumnEncryptionSetting.Disabled:
  4016. return false;
  4017. case SqlCommandColumnEncryptionSetting.Enabled:
  4018. return true;
  4019. case SqlCommandColumnEncryptionSetting.ResultSetOnly:
  4020. return true;
  4021. default:
  4022. // Check connection level setting!
  4023. Debug.Assert(SqlCommandColumnEncryptionSetting.UseConnectionSetting == columnEncryptionSetting,
  4024. "Unexpected value for command level override");
  4025. return (connection != null && connection.ConnectionOptions != null &&
  4026. connection.ConnectionOptions.ColumnEncryptionSetting == SqlConnectionColumnEncryptionSetting.Enabled);
  4027. }
  4028. }
  4029. internal static object GetNullSqlValue(
  4030. SqlBuffer nullVal,
  4031. SqlMetaDataPriv md,
  4032. SqlCommandColumnEncryptionSetting columnEncryptionSetting,
  4033. SqlInternalConnectionTds connection) {
  4034. SqlDbType type = md.type;
  4035. if (type == SqlDbType.VarBinary && // if its a varbinary
  4036. md.isEncrypted &&// and encrypted
  4037. ShouldHonorTceForRead(columnEncryptionSetting, connection)){
  4038. type = md.baseTI.type; // the use the actual (plaintext) type
  4039. }
  4040. switch (type) {
  4041. case SqlDbType.Real:
  4042. nullVal.SetToNullOfType(SqlBuffer.StorageType.Single);
  4043. break;
  4044. case SqlDbType.Float:
  4045. nullVal.SetToNullOfType(SqlBuffer.StorageType.Double);
  4046. break;
  4047. case SqlDbType.Udt:
  4048. case SqlDbType.Binary:
  4049. case SqlDbType.VarBinary:
  4050. case SqlDbType.Image:
  4051. nullVal.SqlBinary = SqlBinary.Null;
  4052. break;
  4053. case SqlDbType.UniqueIdentifier:
  4054. nullVal.SqlGuid = SqlGuid.Null;
  4055. break;
  4056. case SqlDbType.Bit:
  4057. nullVal.SetToNullOfType(SqlBuffer.StorageType.Boolean);
  4058. break;
  4059. case SqlDbType.TinyInt:
  4060. nullVal.SetToNullOfType(SqlBuffer.StorageType.Byte);
  4061. break;
  4062. case SqlDbType.SmallInt:
  4063. nullVal.SetToNullOfType(SqlBuffer.StorageType.Int16);
  4064. break;
  4065. case SqlDbType.Int:
  4066. nullVal.SetToNullOfType(SqlBuffer.StorageType.Int32);
  4067. break;
  4068. case SqlDbType.BigInt:
  4069. nullVal.SetToNullOfType(SqlBuffer.StorageType.Int64);
  4070. break;
  4071. case SqlDbType.Char:
  4072. case SqlDbType.VarChar:
  4073. case SqlDbType.NChar:
  4074. case SqlDbType.NVarChar:
  4075. case SqlDbType.Text:
  4076. case SqlDbType.NText:
  4077. nullVal.SetToNullOfType(SqlBuffer.StorageType.String);
  4078. break;
  4079. case SqlDbType.Decimal:
  4080. nullVal.SetToNullOfType(SqlBuffer.StorageType.Decimal);
  4081. break;
  4082. case SqlDbType.DateTime:
  4083. case SqlDbType.SmallDateTime:
  4084. nullVal.SetToNullOfType(SqlBuffer.StorageType.DateTime);
  4085. break;
  4086. case SqlDbType.Money:
  4087. case SqlDbType.SmallMoney:
  4088. nullVal.SetToNullOfType(SqlBuffer.StorageType.Money);
  4089. break;
  4090. case SqlDbType.Variant:
  4091. // DBNull.Value will have to work here
  4092. nullVal.SetToNullOfType(SqlBuffer.StorageType.Empty);
  4093. break;
  4094. case SqlDbType.Xml:
  4095. nullVal.SqlCachedBuffer = SqlCachedBuffer.Null;
  4096. break;
  4097. case SqlDbType.Date:
  4098. nullVal.SetToNullOfType(SqlBuffer.StorageType.Date);
  4099. break;
  4100. case SqlDbType.Time:
  4101. nullVal.SetToNullOfType(SqlBuffer.StorageType.Time);
  4102. break;
  4103. case SqlDbType.DateTime2:
  4104. nullVal.SetToNullOfType(SqlBuffer.StorageType.DateTime2);
  4105. break;
  4106. case SqlDbType.DateTimeOffset:
  4107. nullVal.SetToNullOfType(SqlBuffer.StorageType.DateTimeOffset);
  4108. break;
  4109. case SqlDbType.Timestamp:
  4110. // Dev10 Bug #479607 - this should have been the same as SqlDbType.Binary, but it's a rejected breaking change
  4111. // Dev10 Bug #752790 - don't assert when it does happen
  4112. break;
  4113. default:
  4114. Debug.Assert(false, "unknown null sqlType!" + md.type.ToString());
  4115. break;
  4116. }
  4117. return nullVal;
  4118. }
  4119. internal bool TrySkipRow(_SqlMetaDataSet columns, TdsParserStateObject stateObj) {
  4120. return TrySkipRow(columns, 0, stateObj);
  4121. }
  4122. internal bool TrySkipRow(_SqlMetaDataSet columns, int startCol, TdsParserStateObject stateObj) {
  4123. for (int i = startCol; i < columns.Length; i++) {
  4124. _SqlMetaData md = columns[i];
  4125. if (!TrySkipValue(md, i, stateObj)) {
  4126. return false;
  4127. }
  4128. }
  4129. return true;
  4130. }
  4131. /// <summary>
  4132. /// This method skips bytes of a single column value from the media. It supports NBCROW and handles all types of values, including PLP and long
  4133. /// </summary>
  4134. internal bool TrySkipValue(SqlMetaDataPriv md, int columnOrdinal, TdsParserStateObject stateObj) {
  4135. if (stateObj.IsNullCompressionBitSet(columnOrdinal)) {
  4136. return true;
  4137. }
  4138. if (md.metaType.IsPlp) {
  4139. ulong ignored;
  4140. if (!TrySkipPlpValue(UInt64.MaxValue, stateObj, out ignored)) {
  4141. return false;
  4142. }
  4143. }
  4144. else if (md.metaType.IsLong) {
  4145. Debug.Assert(!md.metaType.IsPlp, "Plp types must be handled using SkipPlpValue");
  4146. byte textPtrLen;
  4147. if (!stateObj.TryReadByte(out textPtrLen)) {
  4148. return false;
  4149. }
  4150. if (0 != textPtrLen) {
  4151. if (!stateObj.TrySkipBytes(textPtrLen + TdsEnums.TEXT_TIME_STAMP_LEN)) {
  4152. return false;
  4153. }
  4154. int length;
  4155. if (!TryGetTokenLength(md.tdsType, stateObj, out length)) {
  4156. return false;
  4157. }
  4158. if (!stateObj.TrySkipBytes(length)) {
  4159. return false;
  4160. }
  4161. }
  4162. }
  4163. else {
  4164. int length;
  4165. if (!TryGetTokenLength(md.tdsType, stateObj, out length)) {
  4166. return false;
  4167. }
  4168. // if false, no value to skip - it's null
  4169. if (!IsNull(md.metaType, (ulong)length)) {
  4170. if (!stateObj.TrySkipBytes(length)) {
  4171. return false;
  4172. }
  4173. }
  4174. }
  4175. return true;
  4176. }
  4177. private bool IsNull(MetaType mt, ulong length) {
  4178. // null bin and char types have a length of -1 to represent null
  4179. if (mt.IsPlp) {
  4180. return (TdsEnums.SQL_PLP_NULL == length);
  4181. }
  4182. // HOTFIX #50000415: for image/text, 0xFFFF is the length, not representing null
  4183. if ((TdsEnums.VARNULL == length) && !mt.IsLong) {
  4184. return true;
  4185. }
  4186. // other types have a length of 0 to represent null
  4187. // long and non-PLP types will always return false because these types are either char or binary
  4188. // this is expected since for long and non-plp types isnull is checked based on textptr field and not the length
  4189. return ((TdsEnums.FIXEDNULL == length) && !mt.IsCharType && !mt.IsBinType);
  4190. }
  4191. private bool TryReadSqlStringValue(SqlBuffer value, byte type, int length, Encoding encoding, bool isPlp, TdsParserStateObject stateObj) {
  4192. switch (type) {
  4193. case TdsEnums.SQLCHAR:
  4194. case TdsEnums.SQLBIGCHAR:
  4195. case TdsEnums.SQLVARCHAR:
  4196. case TdsEnums.SQLBIGVARCHAR:
  4197. case TdsEnums.SQLTEXT:
  4198. // If bigvarchar(max), we only read the first chunk here,
  4199. // expecting the caller to read the rest
  4200. if (encoding == null) {
  4201. // if hitting 7.0 server, encoding will be null in metadata for columns or return values since
  4202. // 7.0 has no support for multiple code pages in data - single code page support only
  4203. encoding = _defaultEncoding;
  4204. }
  4205. string stringValue;
  4206. if (!stateObj.TryReadStringWithEncoding(length, encoding, isPlp, out stringValue)) {
  4207. return false;
  4208. }
  4209. value.SetToString(stringValue);
  4210. break;
  4211. case TdsEnums.SQLNCHAR:
  4212. case TdsEnums.SQLNVARCHAR:
  4213. case TdsEnums.SQLNTEXT:
  4214. {
  4215. String s = null;
  4216. if (isPlp) {
  4217. char[] cc = null;
  4218. if (!TryReadPlpUnicodeChars(ref cc, 0, length >> 1, stateObj, out length)) {
  4219. return false;
  4220. }
  4221. if (length > 0) {
  4222. s = new String(cc, 0, length);
  4223. }
  4224. else {
  4225. s = ADP.StrEmpty;
  4226. }
  4227. }
  4228. else {
  4229. if (!stateObj.TryReadString(length >> 1, out s)) {
  4230. return false;
  4231. }
  4232. }
  4233. value.SetToString(s);
  4234. break;
  4235. }
  4236. default:
  4237. Debug.Assert(false, "Unknown tds type for SqlString!" + type.ToString(CultureInfo.InvariantCulture));
  4238. break;
  4239. }
  4240. return true;
  4241. }
  4242. /// <summary>
  4243. /// Deserializes the unencrypted bytes into a value based on the target type info.
  4244. /// </summary>
  4245. internal bool DeserializeUnencryptedValue (SqlBuffer value, byte[] unencryptedBytes, SqlMetaDataPriv md, TdsParserStateObject stateObj, byte normalizationVersion) {
  4246. if (normalizationVersion != 0x01) {
  4247. throw SQL.UnsupportedNormalizationVersion(normalizationVersion);
  4248. }
  4249. byte tdsType = md.baseTI.tdsType;
  4250. int length = unencryptedBytes.Length;
  4251. // For normalized types, the length and scale of the actual type might be different than the value's.
  4252. int denormalizedLength = md.baseTI.length;
  4253. byte denormalizedScale = md.baseTI.scale;
  4254. Debug.Assert (false == md.baseTI.isEncrypted, "Double encryption detected");
  4255. switch (tdsType) {
  4256. // We normalize to allow conversion across data types. All data types below are serialized into a BIGINT.
  4257. case TdsEnums.SQLBIT:
  4258. case TdsEnums.SQLBITN:
  4259. case TdsEnums.SQLINTN:
  4260. case TdsEnums.SQLINT1:
  4261. case TdsEnums.SQLINT2:
  4262. case TdsEnums.SQLINT4:
  4263. case TdsEnums.SQLINT8:
  4264. Debug.Assert(length == 8, "invalid length for SqlInt64 type!");
  4265. byte byteValue;
  4266. long longValue;
  4267. if (unencryptedBytes.Length != 8) {
  4268. return false;
  4269. }
  4270. longValue = BitConverter.ToInt64(unencryptedBytes, 0);
  4271. if (tdsType == TdsEnums.SQLBIT ||
  4272. tdsType == TdsEnums.SQLBITN) {
  4273. value.Boolean = (longValue != 0);
  4274. break;
  4275. }
  4276. if (tdsType == TdsEnums.SQLINT1 || denormalizedLength == 1)
  4277. value.Byte = (byte)longValue;
  4278. else if (tdsType == TdsEnums.SQLINT2 || denormalizedLength == 2)
  4279. value.Int16 = (Int16)longValue;
  4280. else if (tdsType == TdsEnums.SQLINT4 || denormalizedLength == 4)
  4281. value.Int32 = (Int32)longValue;
  4282. else
  4283. value.Int64 = longValue;
  4284. break;
  4285. case TdsEnums.SQLFLTN:
  4286. if (length == 4) {
  4287. goto case TdsEnums.SQLFLT4;
  4288. }
  4289. else {
  4290. goto case TdsEnums.SQLFLT8;
  4291. }
  4292. case TdsEnums.SQLFLT4:
  4293. Debug.Assert(length == 4, "invalid length for SqlSingle type!");
  4294. float singleValue;
  4295. if (unencryptedBytes.Length != 4) {
  4296. return false;
  4297. }
  4298. singleValue = BitConverter.ToSingle(unencryptedBytes, 0);
  4299. value.Single = singleValue;
  4300. break;
  4301. case TdsEnums.SQLFLT8:
  4302. double doubleValue;
  4303. if (unencryptedBytes.Length != 8) {
  4304. return false;
  4305. }
  4306. doubleValue = BitConverter.ToDouble(unencryptedBytes, 0);
  4307. value.Double = doubleValue;
  4308. break;
  4309. // We normalize to allow conversion across data types. SMALLMONEY is serialized into a MONEY.
  4310. case TdsEnums.SQLMONEYN:
  4311. case TdsEnums.SQLMONEY4:
  4312. case TdsEnums.SQLMONEY:
  4313. {
  4314. int mid;
  4315. uint lo;
  4316. if (unencryptedBytes.Length != 8) {
  4317. return false;
  4318. }
  4319. mid = BitConverter.ToInt32(unencryptedBytes, 0);
  4320. lo = BitConverter.ToUInt32(unencryptedBytes, 4);
  4321. long l = (((long)mid) << 0x20) + ((long)lo);
  4322. value.SetToMoney(l);
  4323. break;
  4324. }
  4325. case TdsEnums.SQLDATETIMN:
  4326. if (length == 4) {
  4327. goto case TdsEnums.SQLDATETIM4;
  4328. }
  4329. else {
  4330. goto case TdsEnums.SQLDATETIME;
  4331. }
  4332. case TdsEnums.SQLDATETIM4:
  4333. ushort daypartShort, timepartShort;
  4334. if (unencryptedBytes.Length != 4) {
  4335. return false;
  4336. }
  4337. daypartShort = (UInt16)((unencryptedBytes[1] << 8) + unencryptedBytes[0]);
  4338. timepartShort = (UInt16)((unencryptedBytes[3] << 8) + unencryptedBytes[2]);
  4339. value.SetToDateTime(daypartShort, timepartShort * SqlDateTime.SQLTicksPerMinute);
  4340. break;
  4341. case TdsEnums.SQLDATETIME:
  4342. int daypart;
  4343. uint timepart;
  4344. if (unencryptedBytes.Length != 8) {
  4345. return false;
  4346. }
  4347. daypart = BitConverter.ToInt32(unencryptedBytes, 0);
  4348. timepart = BitConverter.ToUInt32(unencryptedBytes, 4);
  4349. value.SetToDateTime(daypart, (int)timepart);
  4350. break;
  4351. case TdsEnums.SQLUNIQUEID:
  4352. {
  4353. Debug.Assert(length == 16, "invalid length for SqlGuid type!");
  4354. value.SqlGuid = new SqlGuid(unencryptedBytes, true); // doesn't copy the byte array
  4355. break;
  4356. }
  4357. case TdsEnums.SQLBINARY:
  4358. case TdsEnums.SQLBIGBINARY:
  4359. case TdsEnums.SQLBIGVARBINARY:
  4360. case TdsEnums.SQLVARBINARY:
  4361. case TdsEnums.SQLIMAGE:
  4362. {
  4363. // Note: Better not come here with plp data!!
  4364. Debug.Assert(length <= TdsEnums.MAXSIZE, "Plp data decryption attempted");
  4365. // If this is a fixed length type, pad with zeros to get to the fixed length size.
  4366. if (tdsType == TdsEnums.SQLBINARY || tdsType == TdsEnums.SQLBIGBINARY) {
  4367. byte[] bytes = new byte[md.baseTI.length];
  4368. Buffer.BlockCopy(unencryptedBytes, 0, bytes, 0, unencryptedBytes.Length);
  4369. unencryptedBytes = bytes;
  4370. }
  4371. value.SqlBinary = new SqlBinary(unencryptedBytes, true); // doesn't copy the byte array
  4372. break;
  4373. }
  4374. case TdsEnums.SQLDECIMALN:
  4375. case TdsEnums.SQLNUMERICN:
  4376. // Check the sign from the first byte.
  4377. int index = 0;
  4378. byteValue = unencryptedBytes[index++];
  4379. bool fPositive = (1 == byteValue);
  4380. // Now read the 4 next integers which contain the actual value.
  4381. length = checked((int)length-1);
  4382. int[] bits = new int[4];
  4383. int decLength = length>>2;
  4384. for (int i = 0; i < decLength; i++) {
  4385. // up to 16 bytes of data following the sign byte
  4386. bits[i] = BitConverter.ToInt32(unencryptedBytes, index);
  4387. index += 4;
  4388. }
  4389. value.SetToDecimal (md.baseTI.precision, md.baseTI.scale, fPositive, bits);
  4390. break;
  4391. case TdsEnums.SQLCHAR:
  4392. case TdsEnums.SQLBIGCHAR:
  4393. case TdsEnums.SQLVARCHAR:
  4394. case TdsEnums.SQLBIGVARCHAR:
  4395. case TdsEnums.SQLTEXT:
  4396. {
  4397. System.Text.Encoding encoding = md.baseTI.encoding;
  4398. if (null == encoding) {
  4399. encoding = _defaultEncoding;
  4400. }
  4401. if (null == encoding) {
  4402. ThrowUnsupportedCollationEncountered(stateObj);
  4403. }
  4404. string strValue = encoding.GetString(unencryptedBytes, 0, length);
  4405. // If this is a fixed length type, pad with spaces to get to the fixed length size.
  4406. if (tdsType == TdsEnums.SQLCHAR || tdsType == TdsEnums.SQLBIGCHAR) {
  4407. strValue = strValue.PadRight(md.baseTI.length);
  4408. }
  4409. value.SetToString(strValue);
  4410. break;
  4411. }
  4412. case TdsEnums.SQLNCHAR:
  4413. case TdsEnums.SQLNVARCHAR:
  4414. case TdsEnums.SQLNTEXT:
  4415. {
  4416. string strValue = System.Text.Encoding.Unicode.GetString(unencryptedBytes, 0, length);
  4417. // If this is a fixed length type, pad with spaces to get to the fixed length size.
  4418. if (tdsType == TdsEnums.SQLNCHAR) {
  4419. strValue = strValue.PadRight(md.baseTI.length / ADP.CharSize);
  4420. }
  4421. value.SetToString(strValue);
  4422. break;
  4423. }
  4424. case TdsEnums.SQLDATE:
  4425. Debug.Assert(length == 3, "invalid length for date type!");
  4426. value.SetToDate(unencryptedBytes);
  4427. break;
  4428. case TdsEnums.SQLTIME:
  4429. // We normalize to maximum precision to allow conversion across different precisions.
  4430. Debug.Assert(length == 5, "invalid length for time type!");
  4431. value.SetToTime(unencryptedBytes, length, TdsEnums.MAX_TIME_SCALE, denormalizedScale);
  4432. break;
  4433. case TdsEnums.SQLDATETIME2:
  4434. // We normalize to maximum precision to allow conversion across different precisions.
  4435. Debug.Assert(length == 8, "invalid length for datetime2 type!");
  4436. value.SetToDateTime2(unencryptedBytes, length, TdsEnums.MAX_TIME_SCALE, denormalizedScale);
  4437. break;
  4438. case TdsEnums.SQLDATETIMEOFFSET:
  4439. // We normalize to maximum precision to allow conversion across different precisions.
  4440. Debug.Assert(length == 10, "invalid length for datetimeoffset type!");
  4441. value.SetToDateTimeOffset(unencryptedBytes, length, TdsEnums.MAX_TIME_SCALE, denormalizedScale);
  4442. break;
  4443. default:
  4444. MetaType metaType = md.baseTI.metaType;
  4445. // If we don't have a metatype already, construct one to get the proper type name.
  4446. if (metaType == null) {
  4447. metaType = MetaType.GetSqlDataType(tdsType, userType:0, length:length);
  4448. }
  4449. throw SQL.UnsupportedDatatypeEncryption(metaType.TypeName);
  4450. }
  4451. return true;
  4452. }
  4453. internal bool TryReadSqlValue(SqlBuffer value,
  4454. SqlMetaDataPriv md,
  4455. int length,
  4456. TdsParserStateObject stateObj,
  4457. SqlCommandColumnEncryptionSetting columnEncryptionOverride,
  4458. string columnName) {
  4459. bool isPlp = md.metaType.IsPlp;
  4460. byte tdsType = md.tdsType;
  4461. Debug.Assert(isPlp || !IsNull(md.metaType, (ulong)length), "null value should not get here!");
  4462. if (isPlp) {
  4463. // We must read the column value completely, no matter what length is passed in
  4464. length = Int32.MaxValue;
  4465. }
  4466. //DEVNOTE: When modifying the following routines (for deserialization) please pay attention to
  4467. // deserialization code in DecryptWithKey () method and modify it accordingly.
  4468. switch (tdsType) {
  4469. case TdsEnums.SQLDECIMALN:
  4470. case TdsEnums.SQLNUMERICN:
  4471. if (!TryReadSqlDecimal(value, length, md.precision, md.scale, stateObj)) {
  4472. return false;
  4473. }
  4474. break;
  4475. case TdsEnums.SQLUDT:
  4476. case TdsEnums.SQLBINARY:
  4477. case TdsEnums.SQLBIGBINARY:
  4478. case TdsEnums.SQLBIGVARBINARY:
  4479. case TdsEnums.SQLVARBINARY:
  4480. case TdsEnums.SQLIMAGE:
  4481. byte[] b = null;
  4482. // If varbinary(max), we only read the first chunk here, expecting the caller to read the rest
  4483. if (isPlp) {
  4484. // If we are given -1 for length, then we read the entire value,
  4485. // otherwise only the requested amount, usually first chunk.
  4486. int ignored;
  4487. if (!stateObj.TryReadPlpBytes(ref b, 0, length, out ignored)) {
  4488. return false;
  4489. }
  4490. }
  4491. else {
  4492. //Debug.Assert(length > 0 && length < (long)(Int32.MaxValue), "Bad length for column");
  4493. b = new byte[length];
  4494. if (!stateObj.TryReadByteArray(b, 0, length)) {
  4495. return false;
  4496. }
  4497. }
  4498. if (md.isEncrypted
  4499. && ((columnEncryptionOverride == SqlCommandColumnEncryptionSetting.Enabled
  4500. || columnEncryptionOverride == SqlCommandColumnEncryptionSetting.ResultSetOnly)
  4501. || (columnEncryptionOverride == SqlCommandColumnEncryptionSetting.UseConnectionSetting
  4502. && _connHandler != null && _connHandler.ConnectionOptions != null
  4503. && _connHandler.ConnectionOptions.ColumnEncryptionSetting == SqlConnectionColumnEncryptionSetting.Enabled))) {
  4504. try {
  4505. // CipherInfo is present, decrypt and read
  4506. byte[] unencryptedBytes = SqlSecurityUtility.DecryptWithKey(b, md.cipherMD, _connHandler.ConnectionOptions.DataSource);
  4507. if (unencryptedBytes != null) {
  4508. DeserializeUnencryptedValue(value, unencryptedBytes, md, stateObj, md.NormalizationRuleVersion);
  4509. }
  4510. }
  4511. catch (Exception e) {
  4512. throw SQL.ColumnDecryptionFailed(columnName, null, e);
  4513. }
  4514. }
  4515. else {
  4516. value.SqlBinary = new SqlBinary(b, true); // doesn't copy the byte array
  4517. }
  4518. break;
  4519. case TdsEnums.SQLCHAR:
  4520. case TdsEnums.SQLBIGCHAR:
  4521. case TdsEnums.SQLVARCHAR:
  4522. case TdsEnums.SQLBIGVARCHAR:
  4523. case TdsEnums.SQLTEXT:
  4524. case TdsEnums.SQLNCHAR:
  4525. case TdsEnums.SQLNVARCHAR:
  4526. case TdsEnums.SQLNTEXT:
  4527. if (!TryReadSqlStringValue(value, tdsType, length, md.encoding, isPlp, stateObj)) {
  4528. return false;
  4529. }
  4530. break;
  4531. case TdsEnums.SQLXMLTYPE:
  4532. // We store SqlCachedBuffer here, so that we can return either SqlBinary, SqlString or SqlXmlReader.
  4533. SqlCachedBuffer sqlBuf;
  4534. if (!SqlCachedBuffer.TryCreate(md, this, stateObj, out sqlBuf)) {
  4535. return false;
  4536. }
  4537. value.SqlCachedBuffer = sqlBuf;
  4538. break;
  4539. case TdsEnums.SQLDATE:
  4540. case TdsEnums.SQLTIME:
  4541. case TdsEnums.SQLDATETIME2:
  4542. case TdsEnums.SQLDATETIMEOFFSET:
  4543. if (!TryReadSqlDateTime(value, tdsType, length, md.scale, stateObj)) {
  4544. return false;
  4545. }
  4546. break;
  4547. default:
  4548. Debug.Assert(!isPlp, "ReadSqlValue calling ReadSqlValueInternal with plp data");
  4549. if (!TryReadSqlValueInternal(value, tdsType, length, stateObj)) {
  4550. return false;
  4551. }
  4552. break;
  4553. }
  4554. Debug.Assert((stateObj._longlen == 0) && (stateObj._longlenleft == 0), "ReadSqlValue did not read plp field completely, longlen =" + stateObj._longlen.ToString((IFormatProvider)null) + ",longlenleft=" + stateObj._longlenleft.ToString((IFormatProvider)null));
  4555. return true;
  4556. }
  4557. private bool TryReadSqlDateTime(SqlBuffer value, byte tdsType, int length, byte scale, TdsParserStateObject stateObj) {
  4558. byte[] datetimeBuffer = new byte[length];
  4559. if (!stateObj.TryReadByteArray(datetimeBuffer, 0, length)) {
  4560. return false;
  4561. }
  4562. switch (tdsType) {
  4563. case TdsEnums.SQLDATE:
  4564. Debug.Assert(length == 3, "invalid length for date type!");
  4565. value.SetToDate(datetimeBuffer);
  4566. break;
  4567. case TdsEnums.SQLTIME:
  4568. Debug.Assert(3 <= length && length <= 5, "invalid length for time type!");
  4569. value.SetToTime(datetimeBuffer, length, scale, scale);
  4570. break;
  4571. case TdsEnums.SQLDATETIME2:
  4572. Debug.Assert(6 <= length && length <= 8, "invalid length for datetime2 type!");
  4573. value.SetToDateTime2(datetimeBuffer, length, scale, scale);
  4574. break;
  4575. case TdsEnums.SQLDATETIMEOFFSET:
  4576. Debug.Assert(8 <= length && length <= 10, "invalid length for datetimeoffset type!");
  4577. value.SetToDateTimeOffset(datetimeBuffer, length, scale, scale);
  4578. break;
  4579. default:
  4580. Debug.Assert(false, "ReadSqlDateTime is called with the wrong tdsType");
  4581. break;
  4582. }
  4583. return true;
  4584. }
  4585. internal bool TryReadSqlValueInternal(SqlBuffer value, byte tdsType, int length, TdsParserStateObject stateObj) {
  4586. switch (tdsType) {
  4587. case TdsEnums.SQLBIT:
  4588. case TdsEnums.SQLBITN:
  4589. Debug.Assert(length == 1, "invalid length for SqlBoolean type!");
  4590. byte byteValue;
  4591. if (!stateObj.TryReadByte(out byteValue)) {
  4592. return false;
  4593. }
  4594. value.Boolean = (byteValue != 0);
  4595. break;
  4596. case TdsEnums.SQLINTN:
  4597. if (length == 1) {
  4598. goto case TdsEnums.SQLINT1;
  4599. }
  4600. else if (length == 2) {
  4601. goto case TdsEnums.SQLINT2;
  4602. }
  4603. else if (length == 4) {
  4604. goto case TdsEnums.SQLINT4;
  4605. }
  4606. else {
  4607. goto case TdsEnums.SQLINT8;
  4608. }
  4609. case TdsEnums.SQLINT1:
  4610. Debug.Assert(length == 1, "invalid length for SqlByte type!");
  4611. if (!stateObj.TryReadByte(out byteValue)) {
  4612. return false;
  4613. }
  4614. value.Byte = byteValue;
  4615. break;
  4616. case TdsEnums.SQLINT2:
  4617. Debug.Assert(length == 2, "invalid length for SqlInt16 type!");
  4618. short shortValue;
  4619. if (!stateObj.TryReadInt16(out shortValue)) {
  4620. return false;
  4621. }
  4622. value.Int16 = shortValue;
  4623. break;
  4624. case TdsEnums.SQLINT4:
  4625. Debug.Assert(length == 4, "invalid length for SqlInt32 type!");
  4626. int intValue;
  4627. if (!stateObj.TryReadInt32(out intValue)) {
  4628. return false;
  4629. }
  4630. value.Int32 = intValue;
  4631. break;
  4632. case TdsEnums.SQLINT8:
  4633. Debug.Assert(length == 8, "invalid length for SqlInt64 type!");
  4634. long longValue;
  4635. if (!stateObj.TryReadInt64(out longValue)) {
  4636. return false;
  4637. }
  4638. value.Int64 = longValue;
  4639. break;
  4640. case TdsEnums.SQLFLTN:
  4641. if (length == 4) {
  4642. goto case TdsEnums.SQLFLT4;
  4643. }
  4644. else {
  4645. goto case TdsEnums.SQLFLT8;
  4646. }
  4647. case TdsEnums.SQLFLT4:
  4648. Debug.Assert(length == 4, "invalid length for SqlSingle type!");
  4649. float singleValue;
  4650. if (!stateObj.TryReadSingle(out singleValue)) {
  4651. return false;
  4652. }
  4653. value.Single = singleValue;
  4654. break;
  4655. case TdsEnums.SQLFLT8:
  4656. Debug.Assert(length == 8, "invalid length for SqlDouble type!");
  4657. double doubleValue;
  4658. if (!stateObj.TryReadDouble(out doubleValue)) {
  4659. return false;
  4660. }
  4661. value.Double = doubleValue;
  4662. break;
  4663. case TdsEnums.SQLMONEYN:
  4664. if (length == 4) {
  4665. goto case TdsEnums.SQLMONEY4;
  4666. }
  4667. else {
  4668. goto case TdsEnums.SQLMONEY;
  4669. }
  4670. case TdsEnums.SQLMONEY:
  4671. {
  4672. int mid;
  4673. uint lo;
  4674. if (!stateObj.TryReadInt32(out mid)) {
  4675. return false;
  4676. }
  4677. if (!stateObj.TryReadUInt32(out lo)) {
  4678. return false;
  4679. }
  4680. long l = (((long)mid) << 0x20) + ((long)lo);
  4681. value.SetToMoney(l);
  4682. break;
  4683. }
  4684. case TdsEnums.SQLMONEY4:
  4685. if (!stateObj.TryReadInt32(out intValue)) {
  4686. return false;
  4687. }
  4688. value.SetToMoney(intValue);
  4689. break;
  4690. case TdsEnums.SQLDATETIMN:
  4691. if (length == 4) {
  4692. goto case TdsEnums.SQLDATETIM4;
  4693. }
  4694. else {
  4695. goto case TdsEnums.SQLDATETIME;
  4696. }
  4697. case TdsEnums.SQLDATETIM4:
  4698. ushort daypartShort, timepartShort;
  4699. if (!stateObj.TryReadUInt16(out daypartShort)) {
  4700. return false;
  4701. }
  4702. if (!stateObj.TryReadUInt16(out timepartShort)) {
  4703. return false;
  4704. }
  4705. value.SetToDateTime(daypartShort, timepartShort * SqlDateTime.SQLTicksPerMinute);
  4706. break;
  4707. case TdsEnums.SQLDATETIME:
  4708. int daypart;
  4709. uint timepart;
  4710. if (!stateObj.TryReadInt32(out daypart)) {
  4711. return false;
  4712. }
  4713. if (!stateObj.TryReadUInt32(out timepart)) {
  4714. return false;
  4715. }
  4716. value.SetToDateTime(daypart, (int)timepart);
  4717. break;
  4718. case TdsEnums.SQLUNIQUEID:
  4719. {
  4720. Debug.Assert(length == 16, "invalid length for SqlGuid type!");
  4721. byte[] b = new byte[length];
  4722. if (!stateObj.TryReadByteArray(b, 0, length)) {
  4723. return false;
  4724. }
  4725. value.SqlGuid = new SqlGuid(b, true); // doesn't copy the byte array
  4726. break;
  4727. }
  4728. case TdsEnums.SQLBINARY:
  4729. case TdsEnums.SQLBIGBINARY:
  4730. case TdsEnums.SQLBIGVARBINARY:
  4731. case TdsEnums.SQLVARBINARY:
  4732. case TdsEnums.SQLIMAGE:
  4733. {
  4734. // Note: Better not come here with plp data!!
  4735. Debug.Assert(length <= TdsEnums.MAXSIZE);
  4736. byte[] b = new byte[length];
  4737. if (!stateObj.TryReadByteArray(b, 0, length)) {
  4738. return false;
  4739. }
  4740. value.SqlBinary = new SqlBinary(b, true); // doesn't copy the byte array
  4741. break;
  4742. }
  4743. case TdsEnums.SQLVARIANT:
  4744. if (!TryReadSqlVariant(value, length, stateObj)) {
  4745. return false;
  4746. }
  4747. break;
  4748. default:
  4749. Debug.Assert(false, "Unknown SqlType!" + tdsType.ToString(CultureInfo.InvariantCulture));
  4750. break;
  4751. } // switch
  4752. return true;
  4753. }
  4754. //
  4755. // Read in a SQLVariant
  4756. //
  4757. // SQLVariant looks like:
  4758. // struct
  4759. // {
  4760. // BYTE TypeTag
  4761. // BYTE cbPropBytes
  4762. // BYTE[] Properties
  4763. // BYTE[] DataVal
  4764. // }
  4765. internal bool TryReadSqlVariant(SqlBuffer value, int lenTotal, TdsParserStateObject stateObj) {
  4766. Debug.Assert(_isShiloh == true, "Shouldn't be dealing with sql_variaint in pre-SQL2000 server!");
  4767. // get the SQLVariant type
  4768. byte type;
  4769. if (!stateObj.TryReadByte(out type)) {
  4770. return false;
  4771. }
  4772. ushort lenMax = 0; // maximum lenData of value inside variant
  4773. // read cbPropBytes
  4774. byte cbPropsActual;
  4775. if (!stateObj.TryReadByte(out cbPropsActual)) {
  4776. return false;
  4777. }
  4778. MetaType mt = MetaType.GetSqlDataType(type, 0 /*no user datatype*/, 0 /* no lenData, non-nullable type */);
  4779. byte cbPropsExpected = mt.PropBytes;
  4780. int lenConsumed = TdsEnums.SQLVARIANT_SIZE + cbPropsActual; // type, count of propBytes, and actual propBytes
  4781. int lenData = lenTotal - lenConsumed; // length of actual data
  4782. // read known properties and skip unknown properties
  4783. Debug.Assert(cbPropsActual >= cbPropsExpected, "cbPropsActual is less that cbPropsExpected!");
  4784. //
  4785. // now read the value
  4786. //
  4787. switch (type) {
  4788. case TdsEnums.SQLBIT:
  4789. case TdsEnums.SQLINT1:
  4790. case TdsEnums.SQLINT2:
  4791. case TdsEnums.SQLINT4:
  4792. case TdsEnums.SQLINT8:
  4793. case TdsEnums.SQLFLT4:
  4794. case TdsEnums.SQLFLT8:
  4795. case TdsEnums.SQLMONEY:
  4796. case TdsEnums.SQLMONEY4:
  4797. case TdsEnums.SQLDATETIME:
  4798. case TdsEnums.SQLDATETIM4:
  4799. case TdsEnums.SQLUNIQUEID:
  4800. if (!TryReadSqlValueInternal(value, type, lenData, stateObj)) {
  4801. return false;
  4802. }
  4803. break;
  4804. case TdsEnums.SQLDECIMALN:
  4805. case TdsEnums.SQLNUMERICN:
  4806. {
  4807. Debug.Assert(cbPropsExpected == 2, "SqlVariant: invalid PropBytes for decimal/numeric type!");
  4808. byte precision;
  4809. if (!stateObj.TryReadByte(out precision)) {
  4810. return false;
  4811. }
  4812. byte scale;
  4813. if (!stateObj.TryReadByte(out scale)) {
  4814. return false;
  4815. }
  4816. // skip over unknown properties
  4817. if (cbPropsActual > cbPropsExpected) {
  4818. if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected)) {
  4819. return false;
  4820. }
  4821. }
  4822. if (!TryReadSqlDecimal(value, TdsEnums.MAX_NUMERIC_LEN, precision, scale, stateObj)) {
  4823. return false;
  4824. }
  4825. break;
  4826. }
  4827. case TdsEnums.SQLBIGBINARY:
  4828. case TdsEnums.SQLBIGVARBINARY:
  4829. //Debug.Assert(TdsEnums.VARNULL == lenData, "SqlVariant: data length for Binary indicates null?");
  4830. Debug.Assert(cbPropsExpected == 2, "SqlVariant: invalid PropBytes for binary type!");
  4831. if (!stateObj.TryReadUInt16(out lenMax)) {
  4832. return false;
  4833. }
  4834. Debug.Assert(lenMax != TdsEnums.SQL_USHORTVARMAXLEN, "bigvarbinary(max) in a sqlvariant");
  4835. // skip over unknown properties
  4836. if (cbPropsActual > cbPropsExpected) {
  4837. if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected)) {
  4838. return false;
  4839. }
  4840. }
  4841. goto case TdsEnums.SQLBIT;
  4842. case TdsEnums.SQLBIGCHAR:
  4843. case TdsEnums.SQLBIGVARCHAR:
  4844. case TdsEnums.SQLNCHAR:
  4845. case TdsEnums.SQLNVARCHAR:
  4846. {
  4847. Debug.Assert(cbPropsExpected == 7, "SqlVariant: invalid PropBytes for character type!");
  4848. SqlCollation collation;
  4849. if (!TryProcessCollation(stateObj, out collation)) {
  4850. return false;
  4851. }
  4852. if (!stateObj.TryReadUInt16(out lenMax)) {
  4853. return false;
  4854. }
  4855. Debug.Assert(lenMax != TdsEnums.SQL_USHORTVARMAXLEN, "bigvarchar(max) or nvarchar(max) in a sqlvariant");
  4856. // skip over unknown properties
  4857. if (cbPropsActual > cbPropsExpected) {
  4858. if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected)) {
  4859. return false;
  4860. }
  4861. }
  4862. Encoding encoding = Encoding.GetEncoding(GetCodePage(collation, stateObj));
  4863. if (!TryReadSqlStringValue(value, type, lenData, encoding, false, stateObj)) {
  4864. return false;
  4865. }
  4866. break;
  4867. }
  4868. case TdsEnums.SQLDATE:
  4869. if (!TryReadSqlDateTime(value, type, lenData, 0, stateObj)) {
  4870. return false;
  4871. }
  4872. break;
  4873. case TdsEnums.SQLTIME:
  4874. case TdsEnums.SQLDATETIME2:
  4875. case TdsEnums.SQLDATETIMEOFFSET:
  4876. {
  4877. Debug.Assert(cbPropsExpected == 1, "SqlVariant: invalid PropBytes for time/datetime2/datetimeoffset type!");
  4878. byte scale;
  4879. if (!stateObj.TryReadByte(out scale)) {
  4880. return false;
  4881. }
  4882. // skip over unknown properties
  4883. if (cbPropsActual > cbPropsExpected) {
  4884. if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected)) {
  4885. return false;
  4886. }
  4887. }
  4888. if (!TryReadSqlDateTime(value, type, lenData, scale, stateObj)) {
  4889. return false;
  4890. }
  4891. break;
  4892. }
  4893. default:
  4894. Debug.Assert(false, "Unknown tds type in SqlVariant!" + type.ToString(CultureInfo.InvariantCulture));
  4895. break;
  4896. } // switch
  4897. return true;
  4898. }
  4899. //
  4900. // Translates a com+ object -> SqlVariant
  4901. // when the type is ambiguous, we always convert to the bigger type
  4902. // note that we also write out the maxlen and actuallen members (4 bytes each)
  4903. // in addition to the SQLVariant structure
  4904. //
  4905. internal Task WriteSqlVariantValue(object value, int length, int offset, TdsParserStateObject stateObj, bool canAccumulate = true) {
  4906. Debug.Assert(_isShiloh == true, "Shouldn't be dealing with sql_variant in pre-SQL2000 server!");
  4907. // handle null values
  4908. if (ADP.IsNull(value)) {
  4909. WriteInt(TdsEnums.FIXEDNULL, stateObj); //maxlen
  4910. WriteInt(TdsEnums.FIXEDNULL, stateObj); //actuallen
  4911. return null;
  4912. }
  4913. MetaType mt = MetaType.GetMetaTypeFromValue(value);
  4914. // Special case data type correction for SqlMoney inside a SqlVariant.
  4915. if ((TdsEnums.SQLNUMERICN == mt.TDSType) && (8 == length)) {
  4916. // The caller will coerce all SqlTypes to native CLR types, which means SqlMoney will
  4917. // coerce to decimal/SQLNUMERICN (via SqlMoney.Value call). In the case where the original
  4918. // value was SqlMoney the caller will also pass in the metadata length for the SqlMoney type
  4919. // which is 8 bytes. To honor the intent of the caller here we coerce this special case
  4920. // input back to SqlMoney from decimal/SQLNUMERICN.
  4921. mt = MetaType.GetMetaTypeFromValue(new SqlMoney((decimal)value));
  4922. }
  4923. if (mt.IsAnsiType) {
  4924. length = GetEncodingCharLength((string)value, length, 0, _defaultEncoding);
  4925. }
  4926. // max and actual len are equal to
  4927. // SQLVARIANTSIZE {type (1 byte) + cbPropBytes (1 byte)} + cbPropBytes + length (actual length of data in bytes)
  4928. WriteInt(TdsEnums.SQLVARIANT_SIZE + mt.PropBytes + length, stateObj); // maxLen
  4929. WriteInt(TdsEnums.SQLVARIANT_SIZE + mt.PropBytes + length, stateObj); // actualLen
  4930. // write the SQLVariant header (type and cbPropBytes)
  4931. stateObj.WriteByte(mt.TDSType);
  4932. stateObj.WriteByte(mt.PropBytes);
  4933. // now write the actual PropBytes and data
  4934. switch (mt.TDSType) {
  4935. case TdsEnums.SQLFLT4:
  4936. WriteFloat((Single)value, stateObj);
  4937. break;
  4938. case TdsEnums.SQLFLT8:
  4939. WriteDouble((Double)value, stateObj);
  4940. break;
  4941. case TdsEnums.SQLINT8:
  4942. WriteLong((Int64)value, stateObj);
  4943. break;
  4944. case TdsEnums.SQLINT4:
  4945. WriteInt((Int32)value, stateObj);
  4946. break;
  4947. case TdsEnums.SQLINT2:
  4948. WriteShort((Int16)value, stateObj);
  4949. break;
  4950. case TdsEnums.SQLINT1:
  4951. stateObj.WriteByte((byte)value);
  4952. break;
  4953. case TdsEnums.SQLBIT:
  4954. if ((bool)value == true)
  4955. stateObj.WriteByte(1);
  4956. else
  4957. stateObj.WriteByte(0);
  4958. break;
  4959. case TdsEnums.SQLBIGVARBINARY:
  4960. {
  4961. byte[] b = (byte[])value;
  4962. WriteShort(length, stateObj); // propbytes: varlen
  4963. return stateObj.WriteByteArray(b, length, offset, canAccumulate);
  4964. }
  4965. case TdsEnums.SQLBIGVARCHAR:
  4966. {
  4967. string s = (string)value;
  4968. WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
  4969. stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
  4970. WriteShort(length, stateObj); // propbyte: varlen
  4971. return WriteEncodingChar(s, _defaultEncoding, stateObj, canAccumulate);
  4972. }
  4973. case TdsEnums.SQLUNIQUEID:
  4974. {
  4975. System.Guid guid = (System.Guid)value;
  4976. byte[] b = guid.ToByteArray();
  4977. Debug.Assert((length == b.Length) && (length == 16), "Invalid length for guid type in com+ object");
  4978. stateObj.WriteByteArray(b, length, 0);
  4979. break;
  4980. }
  4981. case TdsEnums.SQLNVARCHAR:
  4982. {
  4983. string s = (string)value;
  4984. WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
  4985. stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
  4986. WriteShort(length, stateObj); // propbyte: varlen
  4987. // string takes cchar, not cbyte so convert
  4988. length >>= 1;
  4989. return WriteString(s, length, offset, stateObj, canAccumulate);
  4990. }
  4991. case TdsEnums.SQLDATETIME:
  4992. {
  4993. TdsDateTime dt = MetaType.FromDateTime((DateTime)value, 8);
  4994. WriteInt(dt.days, stateObj);
  4995. WriteInt(dt.time, stateObj);
  4996. break;
  4997. }
  4998. case TdsEnums.SQLMONEY:
  4999. {
  5000. WriteCurrency((Decimal)value, 8, stateObj);
  5001. break;
  5002. }
  5003. case TdsEnums.SQLNUMERICN:
  5004. {
  5005. stateObj.WriteByte(mt.Precision); //propbytes: precision
  5006. stateObj.WriteByte((byte)((Decimal.GetBits((Decimal)value)[3] & 0x00ff0000) >> 0x10)); // propbytes: scale
  5007. WriteDecimal((Decimal)value, stateObj);
  5008. break;
  5009. }
  5010. case TdsEnums.SQLTIME:
  5011. stateObj.WriteByte(mt.Scale); //propbytes: scale
  5012. WriteTime((TimeSpan)value, mt.Scale, length, stateObj);
  5013. break;
  5014. case TdsEnums.SQLDATETIMEOFFSET:
  5015. stateObj.WriteByte(mt.Scale); //propbytes: scale
  5016. WriteDateTimeOffset((DateTimeOffset)value, mt.Scale, length, stateObj);
  5017. break;
  5018. default:
  5019. Debug.Assert(false, "unknown tds type for sqlvariant!");
  5020. break;
  5021. } // switch
  5022. // return point for accumulated writes, note: non-accumulated writes returned from their case statements
  5023. return null;
  5024. }
  5025. // todo: since we now know the difference between SqlWriteVariantValue and SqlWriteRowDataVariant we should consider
  5026. // combining these tow methods.
  5027. //
  5028. // Translates a com+ object -> SqlVariant
  5029. // when the type is ambiguous, we always convert to the bigger type
  5030. // note that we also write out the maxlen and actuallen members (4 bytes each)
  5031. // in addition to the SQLVariant structure
  5032. //
  5033. // Devnote: DataRows are preceeded by Metadata. The Metadata includes the MaxLen value.
  5034. // Therefore the sql_variant value must not include the MaxLength. This is the major difference
  5035. // between this method and WriteSqlVariantValue above.
  5036. //
  5037. internal Task WriteSqlVariantDataRowValue(object value, TdsParserStateObject stateObj, bool canAccumulate = true) {
  5038. Debug.Assert(_isShiloh == true, "Shouldn't be dealing with sql_variant in pre-SQL2000 server!");
  5039. // handle null values
  5040. if ((null == value) || (DBNull.Value == value)) {
  5041. WriteInt(TdsEnums.FIXEDNULL, stateObj);
  5042. return null;
  5043. }
  5044. MetaType metatype = MetaType.GetMetaTypeFromValue(value);
  5045. int length = 0;
  5046. if (metatype.IsAnsiType) {
  5047. length = GetEncodingCharLength((string)value, length, 0, _defaultEncoding);
  5048. }
  5049. switch (metatype.TDSType) {
  5050. case TdsEnums.SQLFLT4:
  5051. WriteSqlVariantHeader(6, metatype.TDSType, metatype.PropBytes, stateObj);
  5052. WriteFloat((Single)value, stateObj);
  5053. break;
  5054. case TdsEnums.SQLFLT8:
  5055. WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
  5056. WriteDouble((Double)value, stateObj);
  5057. break;
  5058. case TdsEnums.SQLINT8:
  5059. WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
  5060. WriteLong((Int64)value, stateObj);
  5061. break;
  5062. case TdsEnums.SQLINT4:
  5063. WriteSqlVariantHeader(6, metatype.TDSType, metatype.PropBytes, stateObj);
  5064. WriteInt((Int32)value, stateObj);
  5065. break;
  5066. case TdsEnums.SQLINT2:
  5067. WriteSqlVariantHeader(4, metatype.TDSType, metatype.PropBytes, stateObj);
  5068. WriteShort((Int16)value, stateObj);
  5069. break;
  5070. case TdsEnums.SQLINT1:
  5071. WriteSqlVariantHeader(3, metatype.TDSType, metatype.PropBytes, stateObj);
  5072. stateObj.WriteByte((byte)value);
  5073. break;
  5074. case TdsEnums.SQLBIT:
  5075. WriteSqlVariantHeader(3, metatype.TDSType, metatype.PropBytes, stateObj);
  5076. if ((bool)value == true)
  5077. stateObj.WriteByte(1);
  5078. else
  5079. stateObj.WriteByte(0);
  5080. break;
  5081. case TdsEnums.SQLBIGVARBINARY:
  5082. {
  5083. byte[] b = (byte[])value;
  5084. length = b.Length;
  5085. WriteSqlVariantHeader(4 + length, metatype.TDSType, metatype.PropBytes, stateObj);
  5086. WriteShort(length, stateObj); // propbytes: varlen
  5087. return stateObj.WriteByteArray(b, length, 0, canAccumulate);
  5088. }
  5089. case TdsEnums.SQLBIGVARCHAR:
  5090. {
  5091. string s = (string)value;
  5092. length = s.Length;
  5093. WriteSqlVariantHeader(9 + length, metatype.TDSType, metatype.PropBytes, stateObj);
  5094. WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
  5095. stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
  5096. WriteShort(length, stateObj);
  5097. return WriteEncodingChar(s, _defaultEncoding, stateObj, canAccumulate);
  5098. }
  5099. case TdsEnums.SQLUNIQUEID:
  5100. {
  5101. System.Guid guid = (System.Guid)value;
  5102. byte[] b = guid.ToByteArray();
  5103. length = b.Length;
  5104. Debug.Assert(length == 16, "Invalid length for guid type in com+ object");
  5105. WriteSqlVariantHeader(18, metatype.TDSType, metatype.PropBytes, stateObj);
  5106. stateObj.WriteByteArray(b, length, 0);
  5107. break;
  5108. }
  5109. case TdsEnums.SQLNVARCHAR:
  5110. {
  5111. string s = (string)value;
  5112. length = s.Length * 2;
  5113. WriteSqlVariantHeader(9 + length, metatype.TDSType, metatype.PropBytes, stateObj);
  5114. WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
  5115. stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
  5116. WriteShort(length, stateObj); // propbyte: varlen
  5117. // string takes cchar, not cbyte so convert
  5118. length >>= 1;
  5119. return WriteString(s, length, 0, stateObj, canAccumulate);
  5120. }
  5121. case TdsEnums.SQLDATETIME:
  5122. {
  5123. TdsDateTime dt = MetaType.FromDateTime((DateTime)value, 8);
  5124. WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
  5125. WriteInt(dt.days, stateObj);
  5126. WriteInt(dt.time, stateObj);
  5127. break;
  5128. }
  5129. case TdsEnums.SQLMONEY:
  5130. {
  5131. WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
  5132. WriteCurrency((Decimal)value, 8, stateObj);
  5133. break;
  5134. }
  5135. case TdsEnums.SQLNUMERICN:
  5136. {
  5137. WriteSqlVariantHeader(21, metatype.TDSType, metatype.PropBytes, stateObj);
  5138. stateObj.WriteByte(metatype.Precision); //propbytes: precision
  5139. stateObj.WriteByte((byte)((Decimal.GetBits((Decimal)value)[3] & 0x00ff0000) >> 0x10)); // propbytes: scale
  5140. WriteDecimal((Decimal)value, stateObj);
  5141. break;
  5142. }
  5143. case TdsEnums.SQLTIME:
  5144. WriteSqlVariantHeader(8, metatype.TDSType, metatype.PropBytes, stateObj);
  5145. stateObj.WriteByte(metatype.Scale); //propbytes: scale
  5146. WriteTime((TimeSpan)value, metatype.Scale, 5, stateObj);
  5147. break;
  5148. case TdsEnums.SQLDATETIMEOFFSET:
  5149. WriteSqlVariantHeader(13, metatype.TDSType, metatype.PropBytes, stateObj);
  5150. stateObj.WriteByte(metatype.Scale); //propbytes: scale
  5151. WriteDateTimeOffset((DateTimeOffset)value, metatype.Scale, 10, stateObj);
  5152. break;
  5153. default:
  5154. Debug.Assert(false, "unknown tds type for sqlvariant!");
  5155. break;
  5156. } // switch
  5157. // return point for accumualated writes, note: non-accumulated writes returned from their case statements
  5158. return null;
  5159. }
  5160. internal void WriteSqlVariantHeader(int length, byte tdstype, byte propbytes, TdsParserStateObject stateObj) {
  5161. WriteInt(length, stateObj);
  5162. stateObj.WriteByte(tdstype);
  5163. stateObj.WriteByte(propbytes);
  5164. }
  5165. internal void WriteSqlVariantDateTime2(DateTime value, TdsParserStateObject stateObj)
  5166. {
  5167. MSS.SmiMetaData dateTime2MetaData = MSS.SmiMetaData.DefaultDateTime2;
  5168. // NOTE: 3 bytes added here to support additional header information for variant - internal type, scale prop, scale
  5169. WriteSqlVariantHeader((int)(dateTime2MetaData.MaxLength + 3), TdsEnums.SQLDATETIME2, 1 /* one scale prop */, stateObj);
  5170. stateObj.WriteByte(dateTime2MetaData.Scale); //scale property
  5171. WriteDateTime2(value, dateTime2MetaData.Scale, (int)(dateTime2MetaData.MaxLength), stateObj);
  5172. }
  5173. internal void WriteSqlVariantDate(DateTime value, TdsParserStateObject stateObj)
  5174. {
  5175. MSS.SmiMetaData dateMetaData = MSS.SmiMetaData.DefaultDate;
  5176. // NOTE: 2 bytes added here to support additional header information for variant - internal type, scale prop (ignoring scale here)
  5177. WriteSqlVariantHeader((int)(dateMetaData.MaxLength + 2), TdsEnums.SQLDATE, 0 /* one scale prop */, stateObj);
  5178. WriteDate(value, stateObj);
  5179. }
  5180. private byte[] SerializeSqlMoney(SqlMoney value, int length, TdsParserStateObject stateObj) {
  5181. return SerializeCurrency(value.Value, length, stateObj);
  5182. }
  5183. private void WriteSqlMoney(SqlMoney value, int length, TdsParserStateObject stateObj) {
  5184. //
  5185. int[] bits = Decimal.GetBits(value.Value);
  5186. // this decimal should be scaled by 10000 (regardless of what the incoming decimal was scaled by)
  5187. bool isNeg = (0 != (bits[3] & unchecked((int)0x80000000)));
  5188. long l = ((long)(uint)bits[1]) << 0x20 | (uint)bits[0];
  5189. if (isNeg)
  5190. l = -l;
  5191. if (length == 4) {
  5192. Decimal decimalValue = value.Value;
  5193. // validate the value can be represented as a small money
  5194. if (decimalValue < TdsEnums.SQL_SMALL_MONEY_MIN || decimalValue > TdsEnums.SQL_SMALL_MONEY_MAX) {
  5195. throw SQL.MoneyOverflow(decimalValue.ToString(CultureInfo.InvariantCulture));
  5196. }
  5197. WriteInt((int)l, stateObj);
  5198. }
  5199. else {
  5200. WriteInt((int)(l >> 0x20), stateObj);
  5201. WriteInt((int)l, stateObj);
  5202. }
  5203. }
  5204. private byte[] SerializeCurrency(Decimal value, int length, TdsParserStateObject stateObj) {
  5205. SqlMoney m = new SqlMoney(value);
  5206. int[] bits = Decimal.GetBits(m.Value);
  5207. // this decimal should be scaled by 10000 (regardless of what the incoming decimal was scaled by)
  5208. bool isNeg = (0 != (bits[3] & unchecked((int)0x80000000)));
  5209. long l = ((long)(uint)bits[1]) << 0x20 | (uint)bits[0];
  5210. if (isNeg)
  5211. l = -l;
  5212. if (length == 4) {
  5213. // validate the value can be represented as a small money
  5214. if (value < TdsEnums.SQL_SMALL_MONEY_MIN || value > TdsEnums.SQL_SMALL_MONEY_MAX) {
  5215. throw SQL.MoneyOverflow(value.ToString(CultureInfo.InvariantCulture));
  5216. }
  5217. // We normalize to allow conversion across data types. SMALLMONEY is serialized into a MONEY.
  5218. length = 8;
  5219. }
  5220. Debug.Assert (8 == length, "invalid length in SerializeCurrency");
  5221. if (null == stateObj._bLongBytes) {
  5222. stateObj._bLongBytes = new byte[8];
  5223. }
  5224. byte[] bytes = stateObj._bLongBytes;
  5225. int current = 0;
  5226. byte[] bytesPart = SerializeInt((int)(l >> 0x20), stateObj);
  5227. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5228. current += 4;
  5229. bytesPart = SerializeInt((int)l, stateObj);
  5230. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5231. return bytes;
  5232. }
  5233. private void WriteCurrency(Decimal value, int length, TdsParserStateObject stateObj) {
  5234. SqlMoney m = new SqlMoney(value);
  5235. int[] bits = Decimal.GetBits(m.Value);
  5236. // this decimal should be scaled by 10000 (regardless of what the incoming decimal was scaled by)
  5237. bool isNeg = (0 != (bits[3] & unchecked((int)0x80000000)));
  5238. long l = ((long)(uint)bits[1]) << 0x20 | (uint)bits[0];
  5239. if (isNeg)
  5240. l = -l;
  5241. if (length == 4) {
  5242. // validate the value can be represented as a small money
  5243. if (value < TdsEnums.SQL_SMALL_MONEY_MIN || value > TdsEnums.SQL_SMALL_MONEY_MAX) {
  5244. throw SQL.MoneyOverflow(value.ToString(CultureInfo.InvariantCulture));
  5245. }
  5246. WriteInt((int)l, stateObj);
  5247. }
  5248. else {
  5249. WriteInt((int)(l >> 0x20), stateObj);
  5250. WriteInt((int)l, stateObj);
  5251. }
  5252. }
  5253. private byte[] SerializeDate(DateTime value) {
  5254. long days = value.Subtract(DateTime.MinValue).Days;
  5255. return SerializePartialLong(days, 3);
  5256. }
  5257. private void WriteDate(DateTime value, TdsParserStateObject stateObj) {
  5258. long days = value.Subtract(DateTime.MinValue).Days;
  5259. WritePartialLong(days, 3, stateObj);
  5260. }
  5261. private byte[] SerializeTime(TimeSpan value, byte scale, int length) {
  5262. if (0 > value.Ticks || value.Ticks >= TimeSpan.TicksPerDay) {
  5263. throw SQL.TimeOverflow(value.ToString());
  5264. }
  5265. long time = value.Ticks / TdsEnums.TICKS_FROM_SCALE[scale];
  5266. // We normalize to maximum precision to allow conversion across different precisions.
  5267. time = time * TdsEnums.TICKS_FROM_SCALE[scale];
  5268. length = TdsEnums.MAX_TIME_LENGTH;
  5269. return SerializePartialLong(time, length);
  5270. }
  5271. private void WriteTime(TimeSpan value, byte scale, int length, TdsParserStateObject stateObj) {
  5272. if (0 > value.Ticks || value.Ticks >= TimeSpan.TicksPerDay) {
  5273. throw SQL.TimeOverflow(value.ToString());
  5274. }
  5275. long time = value.Ticks / TdsEnums.TICKS_FROM_SCALE[scale];
  5276. WritePartialLong(time, length, stateObj);
  5277. }
  5278. private byte[] SerializeDateTime2(DateTime value, byte scale, int length) {
  5279. long time = value.TimeOfDay.Ticks / TdsEnums.TICKS_FROM_SCALE[scale]; // DateTime.TimeOfDay always returns a valid TimeSpan for Time
  5280. // We normalize to maximum precision to allow conversion across different precisions.
  5281. time = time * TdsEnums.TICKS_FROM_SCALE[scale];
  5282. length = TdsEnums.MAX_DATETIME2_LENGTH;
  5283. byte[] bytes = new byte[length];
  5284. byte[] bytesPart;
  5285. int current = 0;
  5286. bytesPart = SerializePartialLong(time, length - 3);
  5287. Buffer.BlockCopy(bytesPart, 0, bytes, current, length - 3);
  5288. current += length - 3;
  5289. bytesPart = SerializeDate(value);
  5290. Buffer.BlockCopy(bytesPart, 0, bytes, current, 3);
  5291. return bytes;
  5292. }
  5293. private void WriteDateTime2(DateTime value, byte scale, int length, TdsParserStateObject stateObj) {
  5294. long time = value.TimeOfDay.Ticks / TdsEnums.TICKS_FROM_SCALE[scale]; // DateTime.TimeOfDay always returns a valid TimeSpan for Time
  5295. WritePartialLong(time, length - 3, stateObj);
  5296. WriteDate(value, stateObj);
  5297. }
  5298. private byte[] SerializeDateTimeOffset(DateTimeOffset value, byte scale, int length) {
  5299. byte[] bytesPart;
  5300. int current = 0;
  5301. bytesPart = SerializeDateTime2(value.UtcDateTime, scale, length - 2);
  5302. // We need to allocate the array after we have received the length of the serialized value
  5303. // since it might be higher due to normalization.
  5304. length = bytesPart.Length + 2;
  5305. byte[] bytes = new byte[length];
  5306. Buffer.BlockCopy(bytesPart, 0, bytes, current, length - 2);
  5307. current += length - 2;
  5308. Int16 offset = (Int16)value.Offset.TotalMinutes;
  5309. bytes[current++] = (byte)(offset & 0xff);
  5310. bytes[current++] = (byte)((offset >> 8) & 0xff);
  5311. return bytes;
  5312. }
  5313. private void WriteDateTimeOffset(DateTimeOffset value, byte scale, int length, TdsParserStateObject stateObj) {
  5314. WriteDateTime2(value.UtcDateTime, scale, length - 2, stateObj);
  5315. Int16 offset = (Int16)value.Offset.TotalMinutes;
  5316. stateObj.WriteByte((byte)(offset & 0xff));
  5317. stateObj.WriteByte((byte)((offset >> 8) & 0xff));
  5318. }
  5319. private bool TryReadSqlDecimal(SqlBuffer value, int length, byte precision, byte scale, TdsParserStateObject stateObj) {
  5320. byte byteValue;
  5321. if (!stateObj.TryReadByte(out byteValue)) {
  5322. return false;
  5323. }
  5324. bool fPositive = (1 == byteValue);
  5325. length = checked((int)length-1);
  5326. int[] bits;
  5327. if (!TryReadDecimalBits(length, stateObj, out bits)) {
  5328. return false;
  5329. }
  5330. value.SetToDecimal(precision, scale, fPositive, bits);
  5331. return true;
  5332. }
  5333. // @devnote: length should be size of decimal without the sign
  5334. // @devnote: sign should have already been read off the wire
  5335. private bool TryReadDecimalBits(int length, TdsParserStateObject stateObj, out int[] bits) {
  5336. bits = stateObj._decimalBits; // used alloc'd array if we have one already
  5337. int i;
  5338. if (null == bits)
  5339. bits = new int[4];
  5340. else {
  5341. for (i = 0; i < bits.Length; i++)
  5342. bits[i] = 0;
  5343. }
  5344. Debug.Assert((length > 0) &&
  5345. (length <= TdsEnums.MAX_NUMERIC_LEN - 1) &&
  5346. (length % 4 == 0), "decimal should have 4, 8, 12, or 16 bytes of data");
  5347. int decLength = length >> 2;
  5348. for (i = 0; i < decLength; i++) {
  5349. // up to 16 bytes of data following the sign byte
  5350. if (!stateObj.TryReadInt32(out bits[i])) {
  5351. return false;
  5352. }
  5353. }
  5354. return true;
  5355. }
  5356. static internal SqlDecimal AdjustSqlDecimalScale(SqlDecimal d, int newScale) {
  5357. if (d.Scale != newScale) {
  5358. return SqlDecimal.AdjustScale(d, newScale - d.Scale, false /* Don't round, truncate. MDAC 69229 */);
  5359. }
  5360. return d;
  5361. }
  5362. static internal decimal AdjustDecimalScale(decimal value, int newScale) {
  5363. int oldScale = (Decimal.GetBits(value)[3] & 0x00ff0000) >> 0x10;
  5364. if (newScale != oldScale) {
  5365. SqlDecimal num = new SqlDecimal(value);
  5366. num = SqlDecimal.AdjustScale(num, newScale - oldScale, false /* Don't round, truncate. MDAC 69229 */);
  5367. return num.Value;
  5368. }
  5369. return value;
  5370. }
  5371. internal byte[] SerializeSqlDecimal(SqlDecimal d, TdsParserStateObject stateObj) {
  5372. if (null == stateObj._bDecimalBytes) {
  5373. stateObj._bDecimalBytes = new byte[17];
  5374. }
  5375. byte[] bytes = stateObj._bDecimalBytes;
  5376. int current = 0;
  5377. // sign
  5378. if (d.IsPositive)
  5379. bytes[current++] = 1;
  5380. else
  5381. bytes[current++] = 0;
  5382. byte[] bytesPart = SerializeUnsignedInt(d.m_data1, stateObj);
  5383. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5384. current += 4;
  5385. bytesPart = SerializeUnsignedInt(d.m_data2, stateObj);
  5386. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5387. current += 4;
  5388. bytesPart = SerializeUnsignedInt(d.m_data3, stateObj);
  5389. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5390. current += 4;
  5391. bytesPart = SerializeUnsignedInt(d.m_data4, stateObj);
  5392. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5393. return bytes;
  5394. }
  5395. internal void WriteSqlDecimal(SqlDecimal d, TdsParserStateObject stateObj) {
  5396. // sign
  5397. if (d.IsPositive)
  5398. stateObj.WriteByte(1);
  5399. else
  5400. stateObj.WriteByte(0);
  5401. WriteUnsignedInt(d.m_data1, stateObj);
  5402. WriteUnsignedInt(d.m_data2, stateObj);
  5403. WriteUnsignedInt(d.m_data3, stateObj);
  5404. WriteUnsignedInt(d.m_data4, stateObj);
  5405. }
  5406. private byte[] SerializeDecimal(decimal value, TdsParserStateObject stateObj) {
  5407. int[] decimalBits = Decimal.GetBits(value);
  5408. if (null == stateObj._bDecimalBytes) {
  5409. stateObj._bDecimalBytes = new byte[17];
  5410. }
  5411. byte[] bytes = stateObj._bDecimalBytes;
  5412. int current = 0;
  5413. /*
  5414. Returns a binary representation of a Decimal. The return value is an integer
  5415. array with four elements. Elements 0, 1, and 2 contain the low, middle, and
  5416. high 32 bits of the 96-bit integer part of the Decimal. Element 3 contains
  5417. the scale factor and sign of the Decimal: bits 0-15 (the lower word) are
  5418. unused; bits 16-23 contain a value between 0 and 28, indicating the power of
  5419. 10 to divide the 96-bit integer part by to produce the Decimal value; bits 24-
  5420. 30 are unused; and finally bit 31 indicates the sign of the Decimal value, 0
  5421. meaning positive and 1 meaning negative.
  5422. SQLDECIMAL/SQLNUMERIC has a byte stream of:
  5423. struct {
  5424. BYTE sign; // 1 if positive, 0 if negative
  5425. BYTE data[];
  5426. }
  5427. For TDS 7.0 and above, there are always 17 bytes of data
  5428. */
  5429. // write the sign (note that COM and SQL are opposite)
  5430. if (0x80000000 == (decimalBits[3] & 0x80000000))
  5431. bytes[current++] = 0;
  5432. else
  5433. bytes[current++] = 1;
  5434. byte[] bytesPart = SerializeInt(decimalBits[0], stateObj);
  5435. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5436. current += 4;
  5437. bytesPart = SerializeInt(decimalBits[1], stateObj);
  5438. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5439. current += 4;
  5440. bytesPart = SerializeInt(decimalBits[2], stateObj);
  5441. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5442. current += 4;
  5443. bytesPart = SerializeInt(0, stateObj);
  5444. Buffer.BlockCopy(bytesPart, 0, bytes, current, 4);
  5445. return bytes;
  5446. }
  5447. private void WriteDecimal(decimal value, TdsParserStateObject stateObj) {
  5448. stateObj._decimalBits = Decimal.GetBits(value);
  5449. Debug.Assert(null != stateObj._decimalBits, "decimalBits should be filled in at TdsExecuteRPC time");
  5450. /*
  5451. Returns a binary representation of a Decimal. The return value is an integer
  5452. array with four elements. Elements 0, 1, and 2 contain the low, middle, and
  5453. high 32 bits of the 96-bit integer part of the Decimal. Element 3 contains
  5454. the scale factor and sign of the Decimal: bits 0-15 (the lower word) are
  5455. unused; bits 16-23 contain a value between 0 and 28, indicating the power of
  5456. 10 to divide the 96-bit integer part by to produce the Decimal value; bits 24-
  5457. 30 are unused; and finally bit 31 indicates the sign of the Decimal value, 0
  5458. meaning positive and 1 meaning negative.
  5459. SQLDECIMAL/SQLNUMERIC has a byte stream of:
  5460. struct {
  5461. BYTE sign; // 1 if positive, 0 if negative
  5462. BYTE data[];
  5463. }
  5464. For TDS 7.0 and above, there are always 17 bytes of data
  5465. */
  5466. // write the sign (note that COM and SQL are opposite)
  5467. if (0x80000000 == (stateObj._decimalBits[3] & 0x80000000))
  5468. stateObj.WriteByte(0);
  5469. else
  5470. stateObj.WriteByte(1);
  5471. WriteInt(stateObj._decimalBits[0], stateObj);
  5472. WriteInt(stateObj._decimalBits[1], stateObj);
  5473. WriteInt(stateObj._decimalBits[2], stateObj);
  5474. WriteInt(0, stateObj);
  5475. }
  5476. private void WriteIdentifier(string s, TdsParserStateObject stateObj) {
  5477. if (null != s) {
  5478. stateObj.WriteByte(checked((byte)s.Length));
  5479. WriteString(s, stateObj);
  5480. }
  5481. else {
  5482. stateObj.WriteByte((byte)0);
  5483. }
  5484. }
  5485. private void WriteIdentifierWithShortLength(string s, TdsParserStateObject stateObj) {
  5486. if (null != s) {
  5487. WriteShort(checked((short)s.Length), stateObj);
  5488. WriteString(s, stateObj);
  5489. }
  5490. else {
  5491. WriteShort(0, stateObj);
  5492. }
  5493. }
  5494. private Task WriteString(string s, TdsParserStateObject stateObj, bool canAccumulate = true) {
  5495. return WriteString(s, s.Length, 0, stateObj, canAccumulate);
  5496. }
  5497. internal byte[] SerializeCharArray(char[] carr, int length, int offset) {
  5498. int cBytes = ADP.CharSize * length;
  5499. byte[] bytes = new byte[cBytes];
  5500. CopyCharsToBytes(carr, offset, bytes, 0, length);
  5501. return bytes;
  5502. }
  5503. internal Task WriteCharArray(char[] carr, int length, int offset, TdsParserStateObject stateObj, bool canAccumulate = true) {
  5504. int cBytes = ADP.CharSize * length;
  5505. // Perf shortcut: If it fits, write directly to the outBuff
  5506. if(cBytes < (stateObj._outBuff.Length - stateObj._outBytesUsed)) {
  5507. CopyCharsToBytes(carr, offset, stateObj._outBuff, stateObj._outBytesUsed, length);
  5508. stateObj._outBytesUsed += cBytes;
  5509. return null;
  5510. }
  5511. else {
  5512. if (stateObj._bTmp == null || stateObj._bTmp.Length < cBytes) {
  5513. stateObj._bTmp = new byte[cBytes];
  5514. }
  5515. CopyCharsToBytes(carr, offset, stateObj._bTmp, 0, length);
  5516. return stateObj.WriteByteArray(stateObj._bTmp, cBytes, 0, canAccumulate);
  5517. }
  5518. }
  5519. internal byte[] SerializeString(string s, int length, int offset) {
  5520. int cBytes = ADP.CharSize * length;
  5521. byte[] bytes = new byte[cBytes];
  5522. CopyStringToBytes(s, offset, bytes, 0, length);
  5523. return bytes;
  5524. }
  5525. internal Task WriteString(string s, int length, int offset, TdsParserStateObject stateObj, bool canAccumulate = true) {
  5526. int cBytes = ADP.CharSize * length;
  5527. // Perf shortcut: If it fits, write directly to the outBuff
  5528. if(cBytes < (stateObj._outBuff.Length - stateObj._outBytesUsed)) {
  5529. CopyStringToBytes(s, offset, stateObj._outBuff, stateObj._outBytesUsed, length);
  5530. stateObj._outBytesUsed += cBytes;
  5531. return null;
  5532. }
  5533. else {
  5534. if (stateObj._bTmp == null || stateObj._bTmp.Length < cBytes) {
  5535. stateObj._bTmp = new byte[cBytes];
  5536. }
  5537. CopyStringToBytes(s, offset, stateObj._bTmp, 0, length);
  5538. return stateObj.WriteByteArray(stateObj._bTmp, cBytes, 0, canAccumulate);
  5539. }
  5540. }
  5541. private unsafe static void CopyCharsToBytes(char[] source, int sourceOffset, byte[] dest, int destOffset, int charLength) {
  5542. // DEVNOTE: BE EXTREMELY CAREFULL in this method. Since it pins the buffers and copies the memory
  5543. // directly, it bypasses all of the CLR's usual array-bounds checking. For maintainability, the checks
  5544. // here should NOT be removed just because some other code will check them ahead of time.
  5545. if (charLength < 0) {
  5546. throw ADP.InvalidDataLength(charLength);
  5547. }
  5548. if (checked(sourceOffset + charLength) > source.Length || sourceOffset < 0) {
  5549. throw ADP.IndexOutOfRange(sourceOffset);
  5550. }
  5551. // charLength >= 0 & checked conversion implies byteLength >= 0
  5552. int byteLength = checked(charLength * ADP.CharSize);
  5553. if (checked(destOffset + byteLength) > dest.Length || destOffset < 0) {
  5554. throw ADP.IndexOutOfRange(destOffset);
  5555. }
  5556. fixed (char* sourcePtr = source) {
  5557. char* srcPtr = sourcePtr; // Can't increment the target of a Fixed statement
  5558. srcPtr += sourceOffset; // char* increments by sizeof(char)
  5559. fixed (byte* destinationPtr = dest) {
  5560. byte* destPtr = destinationPtr;
  5561. destPtr += destOffset;
  5562. NativeOledbWrapper.MemoryCopy((IntPtr)destPtr, (IntPtr)srcPtr, byteLength);
  5563. }
  5564. }
  5565. }
  5566. private unsafe static void CopyStringToBytes(string source, int sourceOffset, byte[] dest, int destOffset, int charLength) {
  5567. // DEVNOTE: BE EXTREMELY CAREFULL in this method. Since it pins the buffers and copies the memory
  5568. // directly, it bypasses all of the CLR's usual array-bounds checking. For maintainability, the checks
  5569. // here should NOT be removed just because some other code will check them ahead of time.
  5570. if (charLength < 0) {
  5571. throw ADP.InvalidDataLength(charLength);
  5572. }
  5573. if (checked(sourceOffset + charLength) > source.Length || sourceOffset < 0) {
  5574. throw ADP.IndexOutOfRange(sourceOffset);
  5575. }
  5576. // charLength >= 0 & checked conversion implies byteLength >= 0
  5577. int byteLength = checked(charLength * ADP.CharSize);
  5578. if (checked(destOffset + byteLength) > dest.Length || destOffset < 0) {
  5579. throw ADP.IndexOutOfRange(destOffset);
  5580. }
  5581. fixed (char* sourcePtr = source) {
  5582. char* srcPtr = sourcePtr; // Can't increment the target of a Fixed statement
  5583. srcPtr += sourceOffset; // char* increments by sizeof(char)
  5584. fixed (byte* destinationPtr = dest) {
  5585. byte* destPtr = destinationPtr;
  5586. destPtr += destOffset;
  5587. NativeOledbWrapper.MemoryCopy((IntPtr)destPtr, (IntPtr)srcPtr, byteLength);
  5588. }
  5589. }
  5590. }
  5591. private Task WriteEncodingChar(string s, Encoding encoding, TdsParserStateObject stateObj, bool canAccumulate = true) {
  5592. return WriteEncodingChar(s, s.Length, 0, encoding, stateObj, canAccumulate);
  5593. }
  5594. private byte[] SerializeEncodingChar(string s, int numChars, int offset, Encoding encoding) {
  5595. char[] charData;
  5596. byte[] byteData = null;
  5597. // if hitting 7.0 server, encoding will be null in metadata for columns or return values since
  5598. // 7.0 has no support for multiple code pages in data - single code page support only
  5599. if (encoding == null)
  5600. encoding = _defaultEncoding;
  5601. charData = s.ToCharArray(offset, numChars);
  5602. byteData = new byte[encoding.GetByteCount(charData, 0, charData.Length)];
  5603. encoding.GetBytes(charData, 0, charData.Length, byteData, 0);
  5604. return byteData;
  5605. }
  5606. private Task WriteEncodingChar(string s, int numChars, int offset, Encoding encoding, TdsParserStateObject stateObj, bool canAccumulate = true) {
  5607. char[] charData;
  5608. byte[] byteData;
  5609. // if hitting 7.0 server, encoding will be null in metadata for columns or return values since
  5610. // 7.0 has no support for multiple code pages in data - single code page support only
  5611. if (encoding == null)
  5612. encoding = _defaultEncoding;
  5613. charData = s.ToCharArray(offset, numChars);
  5614. // Optimization: if the entire string fits in the current buffer, then copy it directly
  5615. int bytesLeft = stateObj._outBuff.Length - stateObj._outBytesUsed;
  5616. if ((numChars <= bytesLeft) && (encoding.GetMaxByteCount(charData.Length) <= bytesLeft)) {
  5617. int bytesWritten = encoding.GetBytes(charData, 0, charData.Length, stateObj._outBuff, stateObj._outBytesUsed);
  5618. stateObj._outBytesUsed += bytesWritten;
  5619. return null;
  5620. }
  5621. else {
  5622. byteData = encoding.GetBytes(charData, 0, numChars);
  5623. Debug.Assert(byteData != null, "no data from encoding");
  5624. return stateObj.WriteByteArray(byteData, byteData.Length, 0, canAccumulate);
  5625. }
  5626. }
  5627. internal int GetEncodingCharLength(string value, int numChars, int charOffset, Encoding encoding) {
  5628. //
  5629. if (value == null || value == ADP.StrEmpty) {
  5630. return 0;
  5631. }
  5632. // if hitting 7.0 server, encoding will be null in metadata for columns or return values since
  5633. // 7.0 has no support for multiple code pages in data - single code page support only
  5634. if (encoding == null) {
  5635. if (null == _defaultEncoding) {
  5636. ThrowUnsupportedCollationEncountered(null);
  5637. }
  5638. encoding = _defaultEncoding;
  5639. }
  5640. char[] charData = value.ToCharArray(charOffset, numChars);
  5641. return encoding.GetByteCount(charData, 0, numChars);
  5642. }
  5643. //
  5644. // Returns the data stream length of the data identified by tds type or SqlMetaData returns
  5645. // Returns either the total size or the size of the first chunk for partially length prefixed types.
  5646. //
  5647. internal bool TryGetDataLength(SqlMetaDataPriv colmeta, TdsParserStateObject stateObj, out ulong length) {
  5648. // Handle Yukon specific tokens
  5649. if (_isYukon && colmeta.metaType.IsPlp) {
  5650. Debug.Assert(colmeta.tdsType == TdsEnums.SQLXMLTYPE ||
  5651. colmeta.tdsType == TdsEnums.SQLBIGVARCHAR ||
  5652. colmeta.tdsType == TdsEnums.SQLBIGVARBINARY ||
  5653. colmeta.tdsType == TdsEnums.SQLNVARCHAR ||
  5654. // Large UDTs is WinFS-only
  5655. colmeta.tdsType == TdsEnums.SQLUDT,
  5656. "GetDataLength:Invalid streaming datatype");
  5657. return stateObj.TryReadPlpLength(true, out length);
  5658. }
  5659. else {
  5660. int intLength;
  5661. if (!TryGetTokenLength(colmeta.tdsType, stateObj, out intLength)) {
  5662. length = 0;
  5663. return false;
  5664. }
  5665. length = (ulong)intLength;
  5666. return true;
  5667. }
  5668. }
  5669. //
  5670. // returns the token length of the token or tds type
  5671. // Returns -1 for partially length prefixed (plp) types for metadata info.
  5672. // DOES NOT handle plp data streams correctly!!!
  5673. // Plp data streams length information should be obtained from GetDataLength
  5674. //
  5675. internal bool TryGetTokenLength(byte token, TdsParserStateObject stateObj, out int tokenLength) {
  5676. Debug.Assert(token != 0, "0 length token!");
  5677. switch (token) { // rules about SQLLenMask no longer apply to new tokens (as of 7.4)
  5678. case TdsEnums.SQLFEATUREEXTACK:
  5679. tokenLength = -1;
  5680. return true;
  5681. case TdsEnums.SQLSESSIONSTATE:
  5682. case TdsEnums.SQLFEDAUTHINFO:
  5683. return stateObj.TryReadInt32(out tokenLength);
  5684. }
  5685. if (_isYukon) { // Handle Yukon specific exceptions
  5686. if (token == TdsEnums.SQLUDT) { // special case for UDTs
  5687. tokenLength = -1; // Should we return -1 or not call GetTokenLength for UDTs?
  5688. return true;
  5689. }
  5690. else if (token == TdsEnums.SQLRETURNVALUE) {
  5691. tokenLength = -1; // In Yukon, the RETURNVALUE token stream no longer has length
  5692. return true;
  5693. }
  5694. else if (token == TdsEnums.SQLXMLTYPE) {
  5695. ushort value;
  5696. if (!stateObj.TryReadUInt16(out value)) {
  5697. tokenLength = 0;
  5698. return false;
  5699. }
  5700. tokenLength = (int)value;
  5701. Debug.Assert(tokenLength == TdsEnums.SQL_USHORTVARMAXLEN, "Invalid token stream for xml datatype");
  5702. return true;
  5703. }
  5704. }
  5705. switch (token & TdsEnums.SQLLenMask) {
  5706. case TdsEnums.SQLFixedLen:
  5707. tokenLength = ((0x01 << ((token & 0x0c) >> 2))) & 0xff;
  5708. return true;
  5709. case TdsEnums.SQLZeroLen:
  5710. tokenLength = 0;
  5711. return true;
  5712. case TdsEnums.SQLVarLen:
  5713. case TdsEnums.SQLVarCnt:
  5714. if (0 != (token & 0x80)) {
  5715. ushort value;
  5716. if (!stateObj.TryReadUInt16(out value)) {
  5717. tokenLength = 0;
  5718. return false;
  5719. }
  5720. tokenLength = value;
  5721. return true;
  5722. }
  5723. else if (0 == (token & 0x0c)) {
  5724. //
  5725. if (!stateObj.TryReadInt32(out tokenLength)) {
  5726. return false;
  5727. }
  5728. return true;
  5729. }
  5730. else {
  5731. byte value;
  5732. if (!stateObj.TryReadByte(out value)) {
  5733. tokenLength = 0;
  5734. return false;
  5735. }
  5736. tokenLength = value;
  5737. return true;
  5738. }
  5739. default:
  5740. Debug.Assert(false, "Unknown token length!");
  5741. tokenLength = 0;
  5742. return true;
  5743. }
  5744. }
  5745. private void ProcessAttention(TdsParserStateObject stateObj) {
  5746. if (_state == TdsParserState.Closed || _state == TdsParserState.Broken){
  5747. return;
  5748. }
  5749. Debug.Assert(stateObj._attentionSent, "invalid attempt to ProcessAttention, attentionSent == false!");
  5750. // Attention processing scenarios:
  5751. // 1) EOM packet with header ST_AACK bit plus DONE with status DONE_ATTN
  5752. // 2) Packet without ST_AACK header bit but has DONE with status DONE_ATTN
  5753. // 3) Secondary timeout occurs while reading, break connection
  5754. // Since errors can occur and we need to cancel prior to throwing those errors, we
  5755. // cache away error state and then process TDS for the attention. We restore those
  5756. // errors after processing.
  5757. stateObj.StoreErrorAndWarningForAttention();
  5758. try {
  5759. // Call run loop to process looking for attention ack.
  5760. Run(RunBehavior.Attention, null, null, null, stateObj);
  5761. }
  5762. catch (Exception e) {
  5763. //
  5764. if (!ADP.IsCatchableExceptionType(e)) {
  5765. throw;
  5766. }
  5767. // If an exception occurs - break the connection.
  5768. // Attention error will not be thrown in this case by Run(), but other failures may.
  5769. ADP.TraceExceptionWithoutRethrow(e);
  5770. _state = TdsParserState.Broken;
  5771. _connHandler.BreakConnection();
  5772. throw;
  5773. }
  5774. stateObj.RestoreErrorAndWarningAfterAttention();
  5775. Debug.Assert(!stateObj._attentionSent, "Invalid attentionSent state at end of ProcessAttention");
  5776. }
  5777. static private int StateValueLength(int dataLen) {
  5778. return dataLen < 0xFF ? (dataLen + 1) : (dataLen + 5);
  5779. }
  5780. internal int WriteSessionRecoveryFeatureRequest(SessionData reconnectData, bool write /* if false just calculates the length */) {
  5781. int len = 1;
  5782. if (write) {
  5783. _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_SRECOVERY);
  5784. }
  5785. if (reconnectData == null) {
  5786. if (write) {
  5787. WriteInt(0, _physicalStateObj);
  5788. }
  5789. len += 4;
  5790. }
  5791. else {
  5792. Debug.Assert(reconnectData._unrecoverableStatesCount == 0, "Unrecoverable state count should be 0");
  5793. int initialLength = 0; // sizeof(DWORD) - length itself
  5794. initialLength += 1 + 2 * TdsParserStaticMethods.NullAwareStringLength(reconnectData._initialDatabase);
  5795. initialLength += 1 + 2 * TdsParserStaticMethods.NullAwareStringLength(reconnectData._initialLanguage);
  5796. initialLength += (reconnectData._initialCollation == null) ? 1 : 6;
  5797. for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++) {
  5798. if (reconnectData._initialState[i] != null) {
  5799. initialLength += 1 /* StateId*/ + StateValueLength(reconnectData._initialState[i].Length);
  5800. }
  5801. }
  5802. int currentLength = 0; // sizeof(DWORD) - length itself
  5803. currentLength += 1 + 2 * (reconnectData._initialDatabase == reconnectData._database ? 0 : TdsParserStaticMethods.NullAwareStringLength(reconnectData._database));
  5804. currentLength += 1 + 2 * (reconnectData._initialLanguage == reconnectData._language ? 0 : TdsParserStaticMethods.NullAwareStringLength(reconnectData._language));
  5805. currentLength += (reconnectData._collation != null && !SqlCollation.AreSame(reconnectData._collation, reconnectData._initialCollation)) ? 6 : 1;
  5806. bool[] writeState = new bool[SessionData._maxNumberOfSessionStates];
  5807. for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++) {
  5808. if (reconnectData._delta[i] != null) {
  5809. Debug.Assert(reconnectData._delta[i]._recoverable, "State should be recoverable");
  5810. writeState[i] = true;
  5811. if (reconnectData._initialState[i] != null && reconnectData._initialState[i].Length == reconnectData._delta[i]._dataLength) {
  5812. writeState[i] = false;
  5813. for (int j = 0; j < reconnectData._delta[i]._dataLength; j++) {
  5814. if (reconnectData._initialState[i][j] != reconnectData._delta[i]._data[j]) {
  5815. writeState[i] = true;
  5816. break;
  5817. }
  5818. }
  5819. }
  5820. if (writeState[i]) {
  5821. currentLength += 1 /* StateId*/ + StateValueLength(reconnectData._delta[i]._dataLength);
  5822. }
  5823. }
  5824. }
  5825. if (write) {
  5826. WriteInt(8 + initialLength + currentLength, _physicalStateObj); // length of data w/o total length (initil+current+2*sizeof(DWORD))
  5827. WriteInt(initialLength, _physicalStateObj);
  5828. WriteIdentifier(reconnectData._initialDatabase, _physicalStateObj);
  5829. WriteCollation(reconnectData._initialCollation, _physicalStateObj);
  5830. WriteIdentifier(reconnectData._initialLanguage, _physicalStateObj);
  5831. for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++) {
  5832. if (reconnectData._initialState[i] != null) {
  5833. _physicalStateObj.WriteByte((byte)i);
  5834. if (reconnectData._initialState[i].Length < 0xFF) {
  5835. _physicalStateObj.WriteByte((byte)reconnectData._initialState[i].Length);
  5836. }
  5837. else {
  5838. _physicalStateObj.WriteByte(0xFF);
  5839. WriteInt(reconnectData._initialState[i].Length, _physicalStateObj);
  5840. }
  5841. _physicalStateObj.WriteByteArray(reconnectData._initialState[i], reconnectData._initialState[i].Length, 0);
  5842. }
  5843. }
  5844. WriteInt(currentLength, _physicalStateObj);
  5845. WriteIdentifier(reconnectData._database != reconnectData._initialDatabase ? reconnectData._database : null, _physicalStateObj);
  5846. WriteCollation(SqlCollation.AreSame(reconnectData._initialCollation, reconnectData._collation) ? null : reconnectData._collation, _physicalStateObj);
  5847. WriteIdentifier(reconnectData._language != reconnectData._initialLanguage ? reconnectData._language : null, _physicalStateObj);
  5848. for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++) {
  5849. if (writeState[i]) {
  5850. _physicalStateObj.WriteByte((byte)i);
  5851. if (reconnectData._delta[i]._dataLength < 0xFF) {
  5852. _physicalStateObj.WriteByte((byte)reconnectData._delta[i]._dataLength);
  5853. }
  5854. else {
  5855. _physicalStateObj.WriteByte(0xFF);
  5856. WriteInt(reconnectData._delta[i]._dataLength, _physicalStateObj);
  5857. }
  5858. _physicalStateObj.WriteByteArray(reconnectData._delta[i]._data, reconnectData._delta[i]._dataLength, 0);
  5859. }
  5860. }
  5861. }
  5862. len += initialLength + currentLength + 12 /* length fields (initial, current, total) */;
  5863. }
  5864. return len;
  5865. }
  5866. internal int WriteFedAuthFeatureRequest(FederatedAuthenticationFeatureExtensionData fedAuthFeatureData,
  5867. bool write /* if false just calculates the length */) {
  5868. Debug.Assert(fedAuthFeatureData.libraryType == TdsEnums.FedAuthLibrary.ADAL || fedAuthFeatureData.libraryType == TdsEnums.FedAuthLibrary.SecurityToken,
  5869. "only fed auth library type ADAL and Security Token are supported in writing feature request");
  5870. int dataLen = 0;
  5871. int totalLen = 0;
  5872. // set dataLen and totalLen
  5873. switch (fedAuthFeatureData.libraryType) {
  5874. case TdsEnums.FedAuthLibrary.ADAL:
  5875. dataLen = 2; // length of feature data = 1 byte for library and echo + 1 byte for workflow
  5876. break;
  5877. case TdsEnums.FedAuthLibrary.SecurityToken:
  5878. Debug.Assert(fedAuthFeatureData.accessToken != null, "AccessToken should not be null.");
  5879. dataLen = 1 + sizeof(int) + fedAuthFeatureData.accessToken.Length; // length of feature data = 1 byte for library and echo, security token length and sizeof(int) for token lengh itself
  5880. break;
  5881. default:
  5882. Debug.Assert(false, "Unrecognized library type for fedauth feature extension request");
  5883. break;
  5884. }
  5885. totalLen = dataLen + 5; // length of feature id (1 byte), data length field (4 bytes), and feature data (dataLen)
  5886. // write feature id
  5887. if (write) {
  5888. _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_FEDAUTH);
  5889. // set options
  5890. byte options = 0x00;
  5891. // set upper 7 bits of options to indicate fed auth library type
  5892. switch (fedAuthFeatureData.libraryType) {
  5893. case TdsEnums.FedAuthLibrary.ADAL:
  5894. Debug.Assert(_connHandler._federatedAuthenticationInfoRequested == true, "_federatedAuthenticationInfoRequested field should be true");
  5895. options |= TdsEnums.FEDAUTHLIB_ADAL << 1;
  5896. break;
  5897. case TdsEnums.FedAuthLibrary.SecurityToken:
  5898. Debug.Assert(_connHandler._federatedAuthenticationRequested == true, "_federatedAuthenticationRequested field should be true");
  5899. options |= TdsEnums.FEDAUTHLIB_SECURITYTOKEN << 1;
  5900. break;
  5901. default:
  5902. Debug.Assert(false, "Unrecognized FedAuthLibrary type for feature extension request");
  5903. break;
  5904. }
  5905. options |= (byte)(fedAuthFeatureData.fedAuthRequiredPreLoginResponse == true ? 0x01 : 0x00);
  5906. // write dataLen and options
  5907. WriteInt(dataLen, _physicalStateObj);
  5908. _physicalStateObj.WriteByte(options);
  5909. // write workflow for FedAuthLibrary.ADAL
  5910. // write accessToken for FedAuthLibrary.SecurityToken
  5911. switch (fedAuthFeatureData.libraryType) {
  5912. case TdsEnums.FedAuthLibrary.ADAL:
  5913. byte workflow = 0x00;
  5914. switch (fedAuthFeatureData.authentication) {
  5915. case SqlAuthenticationMethod.ActiveDirectoryPassword:
  5916. workflow = TdsEnums.ADALWORKFLOW_ACTIVEDIRECTORYPASSWORD;
  5917. break;
  5918. case SqlAuthenticationMethod.ActiveDirectoryIntegrated:
  5919. workflow = TdsEnums.ADALWORKFLOW_ACTIVEDIRECTORYINTEGRATED;
  5920. break;
  5921. default:
  5922. Debug.Assert(false, "Unrecognized Authentication type for fedauth ADAL request");
  5923. break;
  5924. }
  5925. _physicalStateObj.WriteByte(workflow);
  5926. break;
  5927. case TdsEnums.FedAuthLibrary.SecurityToken:
  5928. WriteInt(fedAuthFeatureData.accessToken.Length, _physicalStateObj);
  5929. _physicalStateObj.WriteByteArray(fedAuthFeatureData.accessToken, fedAuthFeatureData.accessToken.Length, 0);
  5930. break;
  5931. default:
  5932. Debug.Assert(false, "Unrecognized FedAuthLibrary type for feature extension request");
  5933. break;
  5934. }
  5935. }
  5936. return totalLen;
  5937. }
  5938. internal int WriteTceFeatureRequest (bool write /* if false just calculates the length */) {
  5939. int len = 6; // (1byte = featureID, 4bytes = featureData length, 1 bytes = Version
  5940. if (write) {
  5941. // Write Feature ID, legth of the version# field and TCE Version#
  5942. _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_TCE);
  5943. WriteInt (1, _physicalStateObj);
  5944. _physicalStateObj.WriteByte(TdsEnums.MAX_SUPPORTED_TCE_VERSION);
  5945. }
  5946. return len; // size of data written
  5947. }
  5948. internal int WriteGlobalTransactionsFeatureRequest(bool write /* if false just calculates the length */) {
  5949. int len = 5; // 1byte = featureID, 4bytes = featureData length
  5950. if (write) {
  5951. // Write Feature ID
  5952. _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS);
  5953. WriteInt(0, _physicalStateObj); // we don't send any data
  5954. }
  5955. return len;
  5956. }
  5957. internal void TdsLogin(SqlLogin rec,
  5958. TdsEnums.FeatureExtension requestedFeatures,
  5959. SessionData recoverySessionData,
  5960. FederatedAuthenticationFeatureExtensionData? fedAuthFeatureExtensionData) {
  5961. _physicalStateObj.SetTimeoutSeconds(rec.timeout);
  5962. Debug.Assert(recoverySessionData == null || (requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0, "Recovery session data without session recovery feature request");
  5963. Debug.Assert(TdsEnums.MAXLEN_HOSTNAME>=rec.hostName.Length, "_workstationId.Length exceeds the max length for this value");
  5964. Debug.Assert(!(rec.useSSPI && _connHandler._fedAuthRequired), "Cannot use SSPI when server has responded 0x01 for FedAuthRequired PreLogin Option.");
  5965. Debug.Assert(!rec.useSSPI || (requestedFeatures & TdsEnums.FeatureExtension.FedAuth) == 0, "Cannot use both SSPI and FedAuth");
  5966. Debug.Assert(fedAuthFeatureExtensionData == null || (requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0, "fedAuthFeatureExtensionData provided without fed auth feature request");
  5967. Debug.Assert(fedAuthFeatureExtensionData != null || (requestedFeatures & TdsEnums.FeatureExtension.FedAuth) == 0, "Fed Auth feature requested without specifying fedAuthFeatureExtensionData.");
  5968. Debug.Assert(rec.userName == null || (rec.userName != null && TdsEnums.MAXLEN_USERNAME >= rec.userName.Length), "_userID.Length exceeds the max length for this value");
  5969. Debug.Assert(rec.credential == null || (rec.credential != null && TdsEnums.MAXLEN_USERNAME >= rec.credential.UserId.Length), "_credential.UserId.Length exceeds the max length for this value");
  5970. Debug.Assert(rec.password == null || (rec.password != null && TdsEnums.MAXLEN_PASSWORD>=rec.password.Length), "_password.Length exceeds the max length for this value");
  5971. Debug.Assert(rec.credential == null || (rec.credential != null && TdsEnums.MAXLEN_PASSWORD >= rec.credential.Password.Length), "_credential.Password.Length exceeds the max length for this value");
  5972. Debug.Assert(rec.credential != null || rec.userName != null || rec.password != null, "cannot mix the new secure password system and the connection string based password");
  5973. Debug.Assert(rec.newSecurePassword != null || rec.newPassword != null, "cannot have both new secure change password and string based change password");
  5974. Debug.Assert(TdsEnums.MAXLEN_APPNAME>=rec.applicationName.Length, "_applicationName.Length exceeds the max length for this value");
  5975. Debug.Assert(TdsEnums.MAXLEN_SERVERNAME>=rec.serverName.Length, "_dataSource.Length exceeds the max length for this value");
  5976. Debug.Assert(TdsEnums.MAXLEN_LANGUAGE>=rec.language.Length, "_currentLanguage .Length exceeds the max length for this value");
  5977. Debug.Assert(TdsEnums.MAXLEN_DATABASE>=rec.database.Length, "_initialCatalog.Length exceeds the max length for this value");
  5978. Debug.Assert(TdsEnums.MAXLEN_ATTACHDBFILE>=rec.attachDBFilename.Length, "_attachDBFileName.Length exceeds the max length for this value");
  5979. Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point.");
  5980. _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.LoginBegin);
  5981. _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth);
  5982. // get the password up front to use in sspi logic below
  5983. byte[] encryptedPassword = null;
  5984. byte[] encryptedChangePassword = null;
  5985. int encryptedPasswordLengthInBytes;
  5986. int encryptedChangePasswordLengthInBytes;
  5987. bool useFeatureExt = (requestedFeatures != TdsEnums.FeatureExtension.None);
  5988. string userName;
  5989. if (rec.credential != null) {
  5990. userName = rec.credential.UserId;
  5991. encryptedPasswordLengthInBytes = rec.credential.Password.Length * 2;
  5992. }
  5993. else {
  5994. userName = rec.userName;
  5995. encryptedPassword = TdsParserStaticMethods.EncryptPassword(rec.password);
  5996. encryptedPasswordLengthInBytes = encryptedPassword.Length; // password in clear text is already encrypted and its length is in byte
  5997. }
  5998. if (rec.newSecurePassword != null) {
  5999. encryptedChangePasswordLengthInBytes = rec.newSecurePassword.Length * 2;
  6000. }
  6001. else {
  6002. encryptedChangePassword = TdsParserStaticMethods.EncryptPassword(rec.newPassword);
  6003. encryptedChangePasswordLengthInBytes = encryptedChangePassword.Length;
  6004. }
  6005. // set the message type
  6006. _physicalStateObj._outputMessageType = TdsEnums.MT_LOGIN7;
  6007. // length in bytes
  6008. int length = TdsEnums.YUKON_LOG_REC_FIXED_LEN;
  6009. string clientInterfaceName = TdsEnums.SQL_PROVIDER_NAME;
  6010. Debug.Assert(TdsEnums.MAXLEN_CLIENTINTERFACE >= clientInterfaceName.Length, "cchCltIntName can specify at most 128 unicode characters. See Tds spec");
  6011. // add up variable-len portions (multiply by 2 for byte len of char strings)
  6012. //
  6013. checked {
  6014. length += (rec.hostName.Length + rec.applicationName.Length +
  6015. rec.serverName.Length + clientInterfaceName.Length +
  6016. rec.language.Length + rec.database.Length +
  6017. rec.attachDBFilename.Length) * 2;
  6018. if (useFeatureExt) {
  6019. length += 4;
  6020. }
  6021. }
  6022. // allocate memory for SSPI variables
  6023. byte[] outSSPIBuff = null;
  6024. UInt32 outSSPILength = 0;
  6025. // only add lengths of password and username if not using SSPI or requesting federated authentication info
  6026. if (!rec.useSSPI && !(_connHandler._federatedAuthenticationInfoRequested || _connHandler._federatedAuthenticationRequested)) {
  6027. checked {
  6028. length += (userName.Length * 2) + encryptedPasswordLengthInBytes
  6029. + encryptedChangePasswordLengthInBytes;
  6030. }
  6031. }
  6032. else {
  6033. if (rec.useSSPI) {
  6034. // now allocate proper length of buffer, and set length
  6035. outSSPIBuff = new byte[s_maxSSPILength];
  6036. outSSPILength = s_maxSSPILength;
  6037. // Call helper function for SSPI data and actual length.
  6038. // Since we don't have SSPI data from the server, send null for the
  6039. // byte[] buffer and 0 for the int length.
  6040. Debug.Assert(SniContext.Snix_Login==_physicalStateObj.SniContext, String.Format((IFormatProvider)null, "Unexpected SniContext. Expecting Snix_Login, actual value is '{0}'", _physicalStateObj.SniContext));
  6041. _physicalStateObj.SniContext = SniContext.Snix_LoginSspi;
  6042. SSPIData(null, 0, outSSPIBuff, ref outSSPILength);
  6043. if (outSSPILength > Int32.MaxValue) {
  6044. throw SQL.InvalidSSPIPacketSize(); // SqlBu 332503
  6045. }
  6046. _physicalStateObj.SniContext=SniContext.Snix_Login;
  6047. checked {
  6048. length += (Int32)outSSPILength;
  6049. }
  6050. }
  6051. }
  6052. int feOffset = length;
  6053. if (useFeatureExt) {
  6054. checked {
  6055. if ((requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0) {
  6056. length += WriteSessionRecoveryFeatureRequest(recoverySessionData, false);
  6057. };
  6058. if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) {
  6059. Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null.");
  6060. length += WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write:false);
  6061. }
  6062. if ((requestedFeatures & TdsEnums.FeatureExtension.Tce) != 0) {
  6063. length += WriteTceFeatureRequest (false);
  6064. }
  6065. if ((requestedFeatures & TdsEnums.FeatureExtension.GlobalTransactions) != 0) {
  6066. length += WriteGlobalTransactionsFeatureRequest(false);
  6067. }
  6068. length++; // for terminator
  6069. }
  6070. }
  6071. try {
  6072. WriteInt(length, _physicalStateObj);
  6073. if (recoverySessionData == null) {
  6074. WriteInt((TdsEnums.DENALI_MAJOR << 24) | (TdsEnums.DENALI_INCREMENT << 16) | TdsEnums.DENALI_MINOR, _physicalStateObj);
  6075. }
  6076. else {
  6077. WriteUnsignedInt(recoverySessionData._tdsVersion, _physicalStateObj);
  6078. }
  6079. WriteInt(rec.packetSize, _physicalStateObj);
  6080. WriteInt(TdsEnums.CLIENT_PROG_VER, _physicalStateObj);
  6081. WriteInt(TdsParserStaticMethods.GetCurrentProcessIdForTdsLoginOnly(), _physicalStateObj); //MDAC 84718
  6082. WriteInt(0, _physicalStateObj); // connectionID is unused
  6083. // Log7Flags (DWORD)
  6084. int log7Flags = 0;
  6085. /*
  6086. Current snapshot from TDS spec with the offsets added:
  6087. 0) fByteOrder:1, // byte order of numeric data types on client
  6088. 1) fCharSet:1, // character set on client
  6089. 2) fFloat:2, // Type of floating point on client
  6090. 4) fDumpLoad:1, // Dump/Load and BCP enable
  6091. 5) fUseDb:1, // USE notification
  6092. 6) fDatabase:1, // Initial database fatal flag
  6093. 7) fSetLang:1, // SET LANGUAGE notification
  6094. 8) fLanguage:1, // Initial language fatal flag
  6095. 9) fODBC:1, // Set if client is ODBC driver
  6096. 10) fTranBoundary:1, // Transaction boundary notification
  6097. 11) fDelegatedSec:1, // Security with delegation is available
  6098. 12) fUserType:3, // Type of user
  6099. 15) fIntegratedSecurity:1, // Set if client is using integrated security
  6100. 16) fSQLType:4, // Type of SQL sent from client
  6101. 20) fOLEDB:1, // Set if client is OLEDB driver
  6102. 21) fSpare1:3, // first bit used for read-only intent, rest unused
  6103. 24) fResetPassword:1, // set if client wants to reset password
  6104. 25) fNoNBCAndSparse:1, // set if client does not support NBC and Sparse column
  6105. 26) fUserInstance:1, // This connection wants to connect to a SQL "user instance"
  6106. 27) fUnknownCollationHandling:1, // This connection can handle unknown collation correctly.
  6107. 28) fExtension:1 // Extensions are used
  6108. 32 - total
  6109. */
  6110. // first byte
  6111. log7Flags |= TdsEnums.USE_DB_ON << 5;
  6112. log7Flags |= TdsEnums.INIT_DB_FATAL << 6;
  6113. log7Flags |= TdsEnums.SET_LANG_ON << 7;
  6114. // second byte
  6115. log7Flags |= TdsEnums.INIT_LANG_FATAL << 8;
  6116. log7Flags |= TdsEnums.ODBC_ON << 9;
  6117. if (rec.useReplication) {
  6118. log7Flags |= TdsEnums.REPL_ON << 12;
  6119. }
  6120. if (rec.useSSPI) {
  6121. log7Flags |= TdsEnums.SSPI_ON << 15;
  6122. }
  6123. // third byte
  6124. if (rec.readOnlyIntent) {
  6125. log7Flags |= TdsEnums.READONLY_INTENT_ON << 21; // read-only intent flag is a first bit of fSpare1
  6126. }
  6127. // 4th one
  6128. if (!ADP.IsEmpty(rec.newPassword) || (rec.newSecurePassword != null && rec.newSecurePassword.Length != 0)) {
  6129. log7Flags |= 1 << 24;
  6130. }
  6131. if (rec.userInstance) {
  6132. log7Flags |= 1 << 26;
  6133. }
  6134. if (useFeatureExt) {
  6135. log7Flags |= 1 << 28;
  6136. }
  6137. WriteInt(log7Flags, _physicalStateObj);
  6138. if (Bid.AdvancedOn) {
  6139. Bid.Trace("<sc.TdsParser.TdsLogin|ADV> %d#, TDS Login7 flags = %d:\n", ObjectID, log7Flags);
  6140. }
  6141. WriteInt(0, _physicalStateObj); // ClientTimeZone is not used
  6142. WriteInt(0, _physicalStateObj); // LCID is unused by server
  6143. // Start writing offset and length of variable length portions
  6144. int offset = TdsEnums.YUKON_LOG_REC_FIXED_LEN;
  6145. // write offset/length pairs
  6146. // note that you must always set ibHostName since it indicaters the beginning of the variable length section of the login record
  6147. WriteShort(offset, _physicalStateObj); // host name offset
  6148. WriteShort(rec.hostName.Length, _physicalStateObj);
  6149. offset += rec.hostName.Length * 2;
  6150. // Only send user/password over if not fSSPI or fed auth ADAL... If both user/password and SSPI are in login
  6151. // rec, only SSPI is used. Confirmed same bahavior as in luxor.
  6152. if (!rec.useSSPI && !(_connHandler._federatedAuthenticationInfoRequested || _connHandler._federatedAuthenticationRequested)) {
  6153. WriteShort(offset, _physicalStateObj); // userName offset
  6154. WriteShort(userName.Length, _physicalStateObj);
  6155. offset += userName.Length * 2;
  6156. // the encrypted password is a byte array - so length computations different than strings
  6157. WriteShort(offset, _physicalStateObj); // password offset
  6158. WriteShort(encryptedPasswordLengthInBytes / 2, _physicalStateObj);
  6159. offset += encryptedPasswordLengthInBytes;
  6160. }
  6161. else {
  6162. // case where user/password data is not used, send over zeros
  6163. WriteShort(0, _physicalStateObj); // userName offset
  6164. WriteShort(0, _physicalStateObj);
  6165. WriteShort(0, _physicalStateObj); // password offset
  6166. WriteShort(0, _physicalStateObj);
  6167. }
  6168. WriteShort(offset, _physicalStateObj); // app name offset
  6169. WriteShort(rec.applicationName.Length, _physicalStateObj);
  6170. offset += rec.applicationName.Length * 2;
  6171. WriteShort(offset, _physicalStateObj); // server name offset
  6172. WriteShort(rec.serverName.Length, _physicalStateObj);
  6173. offset += rec.serverName.Length * 2;
  6174. WriteShort(offset, _physicalStateObj);
  6175. if (useFeatureExt) {
  6176. WriteShort(4, _physicalStateObj); // length of ibFeatgureExtLong (which is a DWORD)
  6177. offset += 4;
  6178. }
  6179. else {
  6180. WriteShort(0, _physicalStateObj); // unused (was remote password ?)
  6181. }
  6182. WriteShort(offset, _physicalStateObj); // client interface name offset
  6183. WriteShort(clientInterfaceName.Length, _physicalStateObj);
  6184. offset += clientInterfaceName.Length * 2;
  6185. WriteShort(offset, _physicalStateObj); // language name offset
  6186. WriteShort(rec.language.Length, _physicalStateObj);
  6187. offset += rec.language.Length * 2;
  6188. WriteShort(offset, _physicalStateObj); // database name offset
  6189. WriteShort(rec.database.Length, _physicalStateObj);
  6190. offset += rec.database.Length * 2;
  6191. //
  6192. if (null == s_nicAddress)
  6193. s_nicAddress = TdsParserStaticMethods.GetNetworkPhysicalAddressForTdsLoginOnly();
  6194. _physicalStateObj.WriteByteArray(s_nicAddress, s_nicAddress.Length, 0);
  6195. WriteShort(offset, _physicalStateObj); // ibSSPI offset
  6196. if (rec.useSSPI) {
  6197. WriteShort((int)outSSPILength, _physicalStateObj);
  6198. offset += (int)outSSPILength;
  6199. }
  6200. else {
  6201. WriteShort(0, _physicalStateObj);
  6202. }
  6203. WriteShort(offset, _physicalStateObj); // DB filename offset
  6204. WriteShort(rec.attachDBFilename.Length, _physicalStateObj);
  6205. offset += rec.attachDBFilename.Length * 2;
  6206. WriteShort(offset, _physicalStateObj); // reset password offset
  6207. WriteShort(encryptedChangePasswordLengthInBytes / 2, _physicalStateObj);
  6208. WriteInt(0, _physicalStateObj); // reserved for chSSPI
  6209. // write variable length portion
  6210. WriteString(rec.hostName, _physicalStateObj);
  6211. // if we are using SSPI or fed auth ADAL, do not send over username/password, since we will use SSPI instead
  6212. // same behavior as Luxor
  6213. if (!rec.useSSPI && !(_connHandler._federatedAuthenticationInfoRequested || _connHandler._federatedAuthenticationRequested)) {
  6214. WriteString(userName, _physicalStateObj);
  6215. // Cache offset in packet for tracing.
  6216. _physicalStateObj._tracePasswordOffset = _physicalStateObj._outBytesUsed;
  6217. _physicalStateObj._tracePasswordLength = encryptedPasswordLengthInBytes;
  6218. if (rec.credential != null) {
  6219. _physicalStateObj.WriteSecureString(rec.credential.Password);
  6220. }
  6221. else {
  6222. _physicalStateObj.WriteByteArray(encryptedPassword, encryptedPasswordLengthInBytes, 0);
  6223. }
  6224. }
  6225. WriteString(rec.applicationName, _physicalStateObj);
  6226. WriteString(rec.serverName, _physicalStateObj);
  6227. // write ibFeatureExtLong
  6228. if (useFeatureExt) {
  6229. WriteInt(feOffset, _physicalStateObj);
  6230. }
  6231. WriteString(clientInterfaceName, _physicalStateObj);
  6232. WriteString(rec.language, _physicalStateObj);
  6233. WriteString(rec.database, _physicalStateObj);
  6234. // send over SSPI data if we are using SSPI
  6235. if (rec.useSSPI)
  6236. _physicalStateObj.WriteByteArray(outSSPIBuff, (int)outSSPILength, 0);
  6237. WriteString(rec.attachDBFilename, _physicalStateObj);
  6238. if (!rec.useSSPI && !(_connHandler._federatedAuthenticationInfoRequested || _connHandler._federatedAuthenticationRequested)) {
  6239. // Cache offset in packet for tracing.
  6240. _physicalStateObj._traceChangePasswordOffset = _physicalStateObj._outBytesUsed;
  6241. _physicalStateObj._traceChangePasswordLength = encryptedChangePasswordLengthInBytes;
  6242. if (rec.newSecurePassword != null) {
  6243. _physicalStateObj.WriteSecureString(rec.newSecurePassword);
  6244. }
  6245. else {
  6246. _physicalStateObj.WriteByteArray(encryptedChangePassword, encryptedChangePasswordLengthInBytes, 0);
  6247. }
  6248. }
  6249. if (useFeatureExt) {
  6250. if ((requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0) {
  6251. WriteSessionRecoveryFeatureRequest(recoverySessionData, true);
  6252. };
  6253. if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) {
  6254. Bid.Trace("<sc.TdsParser.TdsLogin|SEC> Sending federated authentication feature request\n");
  6255. Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null.");
  6256. WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true);
  6257. };
  6258. if ((requestedFeatures & TdsEnums.FeatureExtension.Tce) != 0) {
  6259. WriteTceFeatureRequest (true);
  6260. };
  6261. if ((requestedFeatures & TdsEnums.FeatureExtension.GlobalTransactions) != 0) {
  6262. WriteGlobalTransactionsFeatureRequest(true);
  6263. };
  6264. _physicalStateObj.WriteByte(0xFF); // terminator
  6265. }
  6266. } // try
  6267. catch (Exception e) {
  6268. //
  6269. if (ADP.IsCatchableExceptionType(e)) {
  6270. // be sure to wipe out our buffer if we started sending stuff
  6271. _physicalStateObj._outputPacketNumber = 1; // end of message - reset to 1 - per ramas
  6272. _physicalStateObj.ResetBuffer();
  6273. }
  6274. throw;
  6275. }
  6276. _physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
  6277. _physicalStateObj.ResetSecurePasswordsInfomation(); // Password information is needed only from Login process; done with writing login packet and should clear information
  6278. _physicalStateObj._pendingData = true;
  6279. _physicalStateObj._messageStatus = 0;
  6280. }// tdsLogin
  6281. /// <summary>
  6282. /// Send the access token to the server.
  6283. /// </summary>
  6284. /// <param name="fedAuthToken">Type encapuslating a Federated Authentication access token.</param>
  6285. internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) {
  6286. Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null");
  6287. Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null");
  6288. Bid.Trace("<sc.TdsParser.SendFedAuthToken|SEC> Sending federated authentication token\n");
  6289. _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH;
  6290. byte[] accessToken = fedAuthToken.accessToken;
  6291. // Send total length (length of token plus 4 bytes for the token length field)
  6292. // If we were sending a nonce, this would include that length as well
  6293. WriteUnsignedInt((uint)accessToken.Length + sizeof(uint), _physicalStateObj);
  6294. // Send length of token
  6295. WriteUnsignedInt((uint)accessToken.Length, _physicalStateObj);
  6296. // Send federated authentication access token
  6297. _physicalStateObj.WriteByteArray(accessToken, accessToken.Length, 0);
  6298. _physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
  6299. _physicalStateObj._pendingData = true;
  6300. _physicalStateObj._messageStatus = 0;
  6301. _connHandler._federatedAuthenticationRequested = true;
  6302. }
  6303. private void SSPIData(byte[] receivedBuff, UInt32 receivedLength, byte[] sendBuff, ref UInt32 sendLength) {
  6304. SNISSPIData(receivedBuff, receivedLength, sendBuff, ref sendLength);
  6305. }
  6306. private void SNISSPIData(byte[] receivedBuff, UInt32 receivedLength, byte[] sendBuff, ref UInt32 sendLength)
  6307. {
  6308. if (receivedBuff == null)
  6309. {
  6310. // we do not have SSPI data coming from server, so send over 0's for pointer and length
  6311. receivedLength = 0;
  6312. }
  6313. // we need to respond to the server's message with SSPI data
  6314. if(0 != SNINativeMethodWrapper.SNISecGenClientContext(_physicalStateObj.Handle, receivedBuff, receivedLength, sendBuff, ref sendLength, _sniSpnBuffer))
  6315. {
  6316. SSPIError(SQLMessage.SSPIGenerateError(), TdsEnums.GEN_CLIENT_CONTEXT);
  6317. }
  6318. }
  6319. private void ProcessSSPI(int receivedLength) {
  6320. SniContext outerContext=_physicalStateObj.SniContext;
  6321. _physicalStateObj.SniContext = SniContext.Snix_ProcessSspi;
  6322. // allocate received buffer based on length from SSPI message
  6323. byte[] receivedBuff = new byte[receivedLength];
  6324. // read SSPI data received from server
  6325. Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  6326. bool result = _physicalStateObj.TryReadByteArray(receivedBuff, 0, receivedLength);
  6327. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  6328. // allocate send buffer and initialize length
  6329. byte[] sendBuff = new byte[s_maxSSPILength];
  6330. UInt32 sendLength = s_maxSSPILength;
  6331. // make call for SSPI data
  6332. SSPIData(receivedBuff, (UInt32)receivedLength, sendBuff, ref sendLength);
  6333. // DO NOT SEND LENGTH - TDS DOC INCORRECT! JUST SEND SSPI DATA!
  6334. _physicalStateObj.WriteByteArray(sendBuff, (int)sendLength, 0);
  6335. // set message type so server knows its a SSPI response
  6336. _physicalStateObj._outputMessageType = TdsEnums.MT_SSPI;
  6337. // send to server
  6338. _physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
  6339. _physicalStateObj.SniContext=outerContext;
  6340. }
  6341. private void SSPIError(string error, string procedure) {
  6342. Debug.Assert(!ADP.IsEmpty(procedure), "TdsParser.SSPIError called with an empty or null procedure string");
  6343. Debug.Assert(!ADP.IsEmpty(error), "TdsParser.SSPIError called with an empty or null error string");
  6344. _physicalStateObj.AddError(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, _server, error, procedure, 0));
  6345. ThrowExceptionAndWarning(_physicalStateObj);
  6346. }
  6347. private void LoadSSPILibrary() {
  6348. // Outer check so we don't acquire lock once once it's loaded.
  6349. if (!s_fSSPILoaded) {
  6350. lock (s_tdsParserLock) {
  6351. // re-check inside lock
  6352. if (!s_fSSPILoaded) {
  6353. // use local for ref param to defer setting s_maxSSPILength until we know the call succeeded.
  6354. UInt32 maxLength = 0;
  6355. if (0 != SNINativeMethodWrapper.SNISecInitPackage(ref maxLength))
  6356. SSPIError(SQLMessage.SSPIInitializeError(), TdsEnums.INIT_SSPI_PACKAGE);
  6357. s_maxSSPILength = maxLength;
  6358. s_fSSPILoaded = true;
  6359. }
  6360. }
  6361. }
  6362. if (s_maxSSPILength > Int32.MaxValue) {
  6363. throw SQL.InvalidSSPIPacketSize(); // SqlBu 332503
  6364. }
  6365. }
  6366. private void LoadADALLibrary() {
  6367. // Outer check so we don't acquire lock once once it's loaded.
  6368. if (!s_fADALLoaded) {
  6369. lock (s_tdsParserLock) {
  6370. // re-check inside lock
  6371. if (!s_fADALLoaded) {
  6372. int result = ADALNativeWrapper.ADALInitialize();
  6373. if (0 == result) {
  6374. s_fADALLoaded = true;
  6375. }
  6376. else {
  6377. s_fADALLoaded = false;
  6378. SqlAuthenticationMethod authentication = SqlAuthenticationMethod.NotSpecified;
  6379. if (_connHandler.ConnectionOptions != null)
  6380. {
  6381. authentication = _connHandler.ConnectionOptions.Authentication;
  6382. // Only the below connection string options should have ended up calling this function.
  6383. Debug.Assert(authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated || authentication == SqlAuthenticationMethod.ActiveDirectoryPassword);
  6384. }
  6385. _physicalStateObj.AddError(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, _server, Res.GetString(Res.SQL_ADALInitializeError, authentication.ToString("G"), result.ToString("X")), TdsEnums.INIT_ADAL_PACKAGE, 0));
  6386. ThrowExceptionAndWarning(_physicalStateObj);
  6387. }
  6388. }
  6389. }
  6390. }
  6391. }
  6392. internal byte[] GetDTCAddress(int timeout, TdsParserStateObject stateObj) {
  6393. // If this fails, the server will return a server error - Sameet Agarwal confirmed.
  6394. // Success: DTCAddress returned. Failure: SqlError returned.
  6395. byte[] dtcAddr = null;
  6396. using (SqlDataReader dtcReader = TdsExecuteTransactionManagerRequest(
  6397. null,
  6398. TdsEnums.TransactionManagerRequestType.GetDTCAddress,
  6399. null,
  6400. TdsEnums.TransactionManagerIsolationLevel.Unspecified,
  6401. timeout, null, stateObj, true)) {
  6402. Debug.Assert(SniContext.Snix_Read==stateObj.SniContext, String.Format((IFormatProvider)null, "The SniContext should be Snix_Read but it actually is {0}", stateObj.SniContext));
  6403. if (null != dtcReader && dtcReader.Read()) {
  6404. Debug.Assert(dtcReader.GetName(0) == "TM Address", "TdsParser: GetDTCAddress did not return 'TM Address'");
  6405. // DTCAddress is of variable size, and does not have a maximum. So we call GetBytes
  6406. // to get the length of the dtcAddress, then allocate a byte array of that length,
  6407. // then call GetBytes again on that byte[] with the length
  6408. long dtcLength = dtcReader.GetBytes(0, 0, null, 0, 0);
  6409. //
  6410. if (dtcLength <= Int32.MaxValue) {
  6411. int cb = (int)dtcLength;
  6412. dtcAddr = new byte[cb];
  6413. dtcReader.GetBytes(0, 0, dtcAddr, 0, cb);
  6414. }
  6415. #if DEBUG
  6416. else {
  6417. Debug.Assert(false, "unexpected length (> Int32.MaxValue) returned from dtcReader.GetBytes");
  6418. // if we hit this case we'll just return a null address so that the user
  6419. // will get a transcaction enlistment error in the upper layers
  6420. }
  6421. #endif
  6422. }
  6423. }
  6424. return dtcAddr;
  6425. }
  6426. // Propagate the dtc cookie to the server, enlisting the connection.
  6427. internal void PropagateDistributedTransaction(byte[] buffer, int timeout, TdsParserStateObject stateObj) {
  6428. // if this fails, the server will return a server error - Sameet Agarwal confirmed
  6429. // Success: server will return done token. Failure: SqlError returned.
  6430. TdsExecuteTransactionManagerRequest(buffer,
  6431. TdsEnums.TransactionManagerRequestType.Propagate, null,
  6432. TdsEnums.TransactionManagerIsolationLevel.Unspecified, timeout, null, stateObj, true);
  6433. }
  6434. internal SqlDataReader TdsExecuteTransactionManagerRequest(
  6435. byte[] buffer,
  6436. TdsEnums.TransactionManagerRequestType request,
  6437. string transactionName,
  6438. TdsEnums.TransactionManagerIsolationLevel isoLevel,
  6439. int timeout,
  6440. SqlInternalTransaction transaction,
  6441. TdsParserStateObject stateObj,
  6442. bool isDelegateControlRequest) {
  6443. Debug.Assert(this == stateObj.Parser, "different parsers");
  6444. if (TdsParserState.Broken == State || TdsParserState.Closed == State) {
  6445. return null;
  6446. }
  6447. // SQLBUDT #20010853 - Promote, Commit and Rollback requests for
  6448. // delegated transactions often happen while there is an open result
  6449. // set, so we need to handle them by using a different MARS session,
  6450. // otherwise we'll write on the physical state objects while someone
  6451. // else is using it. When we don't have MARS enabled, we need to
  6452. // lock the physical state object to syncronize it's use at least
  6453. // until we increment the open results count. Once it's been
  6454. // incremented the delegated transaction requests will fail, so they
  6455. // won't stomp on anything.
  6456. Debug.Assert(!_connHandler.ThreadHasParserLockForClose || _connHandler._parserLock.ThreadMayHaveLock(), "Thread claims to have parser lock, but lock is not taken");
  6457. bool callerHasConnectionLock = _connHandler.ThreadHasParserLockForClose; // If the thread already claims to have the parser lock, then we will let the caller handle releasing it
  6458. if (!callerHasConnectionLock) {
  6459. _connHandler._parserLock.Wait(canReleaseFromAnyThread:false);
  6460. _connHandler.ThreadHasParserLockForClose = true;
  6461. }
  6462. // Capture _asyncWrite (after taking lock) to restore it afterwards
  6463. bool hadAsyncWrites = _asyncWrite;
  6464. try {
  6465. // Temprarily disable async writes
  6466. _asyncWrite = false;
  6467. // This validation step MUST be done after locking the connection to guarantee we don't
  6468. // accidentally execute after the transaction has completed on a different thread.
  6469. if (!isDelegateControlRequest) {
  6470. _connHandler.CheckEnlistedTransactionBinding();
  6471. }
  6472. stateObj._outputMessageType = TdsEnums.MT_TRANS; // set message type
  6473. stateObj.SetTimeoutSeconds(timeout);
  6474. stateObj.SniContext = SniContext.Snix_Execute;
  6475. if (_isYukon) {
  6476. const int marsHeaderSize = 18; // 4 + 2 + 8 + 4
  6477. const int totalHeaderLength = 22; // 4 + 4 + 2 + 8 + 4
  6478. Debug.Assert(stateObj._outBytesUsed == stateObj._outputHeaderLen, "Output bytes written before total header length");
  6479. // Write total header length
  6480. WriteInt(totalHeaderLength, stateObj);
  6481. // Write mars header length
  6482. WriteInt(marsHeaderSize, stateObj);
  6483. WriteMarsHeaderData(stateObj, _currentTransaction);
  6484. }
  6485. WriteShort((short)request, stateObj); // write TransactionManager Request type
  6486. bool returnReader = false;
  6487. switch (request) {
  6488. case TdsEnums.TransactionManagerRequestType.GetDTCAddress:
  6489. WriteShort(0, stateObj);
  6490. returnReader = true;
  6491. break;
  6492. case TdsEnums.TransactionManagerRequestType.Propagate:
  6493. if (null != buffer) {
  6494. WriteShort(buffer.Length, stateObj);
  6495. stateObj.WriteByteArray(buffer, buffer.Length, 0);
  6496. }
  6497. else {
  6498. WriteShort(0, stateObj);
  6499. }
  6500. break;
  6501. case TdsEnums.TransactionManagerRequestType.Begin:
  6502. Debug.Assert(IsYukonOrNewer, "Should not be calling TdsExecuteTransactionManagerRequest on pre-Yukon clients for BeginTransaction!");
  6503. Debug.Assert(null != transaction, "Should have specified an internalTransaction when doing a BeginTransaction request!");
  6504. // Only assign the passed in transaction if it is not equal to the current transaction.
  6505. // And, if it is not equal, the current actually should be null. Anything else
  6506. // is a unexpected state. The concern here is mainly for the mixed use of
  6507. // T-SQL and API transactions. See SQL BU DT 345300 for full details and repro.
  6508. // Expected states:
  6509. // 1) _pendingTransaction = null, _currentTransaction = null, non null transaction
  6510. // passed in on BeginTransaction API call.
  6511. // 2) _currentTransaction != null, _pendingTransaction = null, non null transaction
  6512. // passed in but equivalent to _currentTransaction.
  6513. // #1 will occur on standard BeginTransactionAPI call. #2 should only occur if
  6514. // t-sql transaction started followed by a call to SqlConnection.BeginTransaction.
  6515. // Any other state is unknown.
  6516. if (_currentTransaction != transaction) {
  6517. Debug.Assert(_currentTransaction == null || true == _fResetConnection, "We should not have a current Tx at this point");
  6518. PendingTransaction = transaction;
  6519. }
  6520. stateObj.WriteByte((byte)isoLevel);
  6521. stateObj.WriteByte((byte)(transactionName.Length * 2)); // Write number of bytes (unicode string).
  6522. WriteString(transactionName, stateObj);
  6523. break;
  6524. case TdsEnums.TransactionManagerRequestType.Promote:
  6525. Debug.Assert(IsYukonOrNewer, "Should not be calling TdsExecuteTransactionManagerRequest on pre-Yukon clients for PromoteTransaction!");
  6526. // No payload - except current transaction in header
  6527. // Promote returns a DTC cookie. However, the transaction cookie we use for the
  6528. // connection does not change after a promote.
  6529. break;
  6530. case TdsEnums.TransactionManagerRequestType.Commit:
  6531. Debug.Assert(IsYukonOrNewer, "Should not be calling TdsExecuteTransactionManagerRequest on pre-Yukon clients for CommitTransaction!");
  6532. Debug.Assert(transactionName.Length == 0, "Should not have a transaction name on Commit");
  6533. stateObj.WriteByte((byte)0); // No xact name
  6534. stateObj.WriteByte(0); // No flags
  6535. Debug.Assert(isoLevel == TdsEnums.TransactionManagerIsolationLevel.Unspecified, "Should not have isolation level other than unspecified on Commit!");
  6536. // WriteByte((byte) 0, stateObj); // IsolationLevel
  6537. // WriteByte((byte) 0, stateObj); // No begin xact name
  6538. break;
  6539. case TdsEnums.TransactionManagerRequestType.Rollback:
  6540. Debug.Assert(IsYukonOrNewer, "Should not be calling TdsExecuteTransactionManagerRequest on pre-Yukon clients for RollbackTransaction!");
  6541. stateObj.WriteByte((byte)(transactionName.Length * 2)); // Write number of bytes (unicode string).
  6542. WriteString(transactionName, stateObj);
  6543. stateObj.WriteByte(0); // No flags
  6544. Debug.Assert(isoLevel == TdsEnums.TransactionManagerIsolationLevel.Unspecified, "Should not have isolation level other than unspecified on Commit!");
  6545. // WriteByte((byte) 0, stateObj); // IsolationLevel
  6546. // WriteByte((byte) 0, stateObj); // No begin xact name
  6547. break;
  6548. case TdsEnums.TransactionManagerRequestType.Save:
  6549. Debug.Assert(IsYukonOrNewer, "Should not be calling TdsExecuteTransactionManagerRequest on pre-Yukon clients for SaveTransaction!");
  6550. stateObj.WriteByte((byte)(transactionName.Length * 2)); // Write number of bytes (unicode string).
  6551. WriteString(transactionName, stateObj);
  6552. break;
  6553. default:
  6554. Debug.Assert(false, "Unexpected TransactionManagerRequest");
  6555. break;
  6556. }
  6557. Task writeTask = stateObj.WritePacket(TdsEnums.HARDFLUSH);
  6558. Debug.Assert(writeTask == null, "Writes should not pend when writing sync");
  6559. stateObj._pendingData = true;
  6560. stateObj._messageStatus = 0;
  6561. SqlDataReader dtcReader = null;
  6562. stateObj.SniContext = SniContext.Snix_Read;
  6563. if (returnReader) {
  6564. dtcReader = new SqlDataReader(null, CommandBehavior.Default);
  6565. Debug.Assert(this == stateObj.Parser, "different parser");
  6566. #if DEBUG
  6567. // Remove the current owner of stateObj - otherwise we will hit asserts
  6568. stateObj.Owner = null;
  6569. #endif
  6570. dtcReader.Bind(stateObj);
  6571. // force consumption of metadata
  6572. _SqlMetaDataSet metaData = dtcReader.MetaData;
  6573. }
  6574. else {
  6575. Run(RunBehavior.UntilDone, null, null, null, stateObj);
  6576. }
  6577. // If the retained ID is no longer valid (because we are enlisting in null or a new transaction) then it should be cleared
  6578. if (((request == TdsEnums.TransactionManagerRequestType.Begin) || (request == TdsEnums.TransactionManagerRequestType.Propagate)) && ((transaction == null) || (transaction.TransactionId != _retainedTransactionId))) {
  6579. _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
  6580. }
  6581. return dtcReader;
  6582. }
  6583. catch (Exception e) {
  6584. //
  6585. if (!ADP.IsCatchableExceptionType(e)) {
  6586. throw;
  6587. }
  6588. FailureCleanup(stateObj, e);
  6589. throw;
  6590. }
  6591. finally {
  6592. // SQLHotfix 50000518
  6593. // make sure we don't leave temporary fields set when leaving this function
  6594. _pendingTransaction = null;
  6595. _asyncWrite = hadAsyncWrites;
  6596. if (!callerHasConnectionLock) {
  6597. _connHandler.ThreadHasParserLockForClose = false;
  6598. _connHandler._parserLock.Release();
  6599. }
  6600. }
  6601. }
  6602. internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) {
  6603. int old_outputPacketNumber = stateObj._outputPacketNumber;
  6604. if (Bid.TraceOn) {
  6605. Bid.Trace("<sc.TdsParser.FailureCleanup|ERR> Exception caught on ExecuteXXX: '%ls' \n", e.ToString());
  6606. }
  6607. if (stateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount if operation failed.
  6608. stateObj.DecrementOpenResultCount();
  6609. }
  6610. // be sure to wipe out our buffer if we started sending stuff
  6611. stateObj.ResetBuffer();
  6612. stateObj._outputPacketNumber = 1; // end of message - reset to 1 - per ramas
  6613. if (old_outputPacketNumber != 1 && _state == TdsParserState.OpenLoggedIn) {
  6614. Debug.Assert(_connHandler._parserLock.ThreadMayHaveLock(), "Should not be calling into FailureCleanup without first taking the parser lock");
  6615. bool originalThreadHasParserLock = _connHandler.ThreadHasParserLockForClose;
  6616. try {
  6617. // Dev11 Bug 385286 : ExecuteNonQueryAsync hangs when trying to write a parameter which generates ArgumentException and while handling that exception the server disconnects the connection
  6618. // Need to set this to true such that if we have an error sending\processing the attention, we won't deadlock ourselves
  6619. _connHandler.ThreadHasParserLockForClose = true;
  6620. // If _outputPacketNumber prior to ResetBuffer was not equal to 1, a packet was already
  6621. // sent to the server and so we need to send an attention and process the attention ack.
  6622. stateObj.SendAttention();
  6623. ProcessAttention(stateObj);
  6624. }
  6625. finally {
  6626. // Reset the ThreadHasParserLock value incase our caller expects it to be set\not set
  6627. _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock;
  6628. }
  6629. }
  6630. Bid.Trace("<sc.TdsParser.FailureCleanup|ERR> Exception rethrown. \n");
  6631. }
  6632. internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool sync, bool callerHasConnectionLock = false) {
  6633. if (TdsParserState.Broken == State || TdsParserState.Closed == State) {
  6634. return null;
  6635. }
  6636. if (stateObj.BcpLock) {
  6637. throw SQL.ConnectionLockedForBcpEvent();
  6638. }
  6639. // SQLBUDT #20010853 - Promote, Commit and Rollback requests for
  6640. // delegated transactions often happen while there is an open result
  6641. // set, so we need to handle them by using a different MARS session,
  6642. // otherwise we'll write on the physical state objects while someone
  6643. // else is using it. When we don't have MARS enabled, we need to
  6644. // lock the physical state object to syncronize it's use at least
  6645. // until we increment the open results count. Once it's been
  6646. // incremented the delegated transaction requests will fail, so they
  6647. // won't stomp on anything.
  6648. // Only need to take the lock if neither the thread nor the caller claims to already have it
  6649. bool needToTakeParserLock = (!callerHasConnectionLock) && (!_connHandler.ThreadHasParserLockForClose);
  6650. Debug.Assert(!_connHandler.ThreadHasParserLockForClose || sync, "Thread shouldn't claim to have the parser lock if we are doing async writes"); // Since we have the possibility of pending with async writes, make sure the thread doesn't claim to already have the lock
  6651. Debug.Assert(needToTakeParserLock || _connHandler._parserLock.ThreadMayHaveLock(), "Thread or caller claims to have connection lock, but lock is not taken");
  6652. bool releaseConnectionLock = false;
  6653. if (needToTakeParserLock) {
  6654. _connHandler._parserLock.Wait(canReleaseFromAnyThread: !sync);
  6655. releaseConnectionLock = true;
  6656. }
  6657. // Switch the writing mode
  6658. // NOTE: We are not turning off async writes when we complete since SqlBulkCopy uses this method and expects _asyncWrite to not change
  6659. _asyncWrite = !sync;
  6660. try {
  6661. // Check that the connection is still alive
  6662. if ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken)) {
  6663. throw ADP.ClosedConnectionError();
  6664. }
  6665. // This validation step MUST be done after locking the connection to guarantee we don't
  6666. // accidentally execute after the transaction has completed on a different thread.
  6667. _connHandler.CheckEnlistedTransactionBinding();
  6668. stateObj.SetTimeoutSeconds(timeout);
  6669. if ((!_fMARS) && (_physicalStateObj.HasOpenResult))
  6670. {
  6671. Bid.Trace("<sc.TdsParser.TdsExecuteSQLBatch|ERR> Potential multi-threaded misuse of connection, non-MARs connection with an open result %d#\n", ObjectID);
  6672. }
  6673. stateObj.SniContext = SniContext.Snix_Execute;
  6674. if (_isYukon) {
  6675. WriteRPCBatchHeaders(stateObj, notificationRequest);
  6676. }
  6677. stateObj._outputMessageType = TdsEnums.MT_SQL;
  6678. WriteString(text, text.Length, 0, stateObj);
  6679. Task executeTask = stateObj.ExecuteFlush();
  6680. if (executeTask == null) {
  6681. stateObj.SniContext = SniContext.Snix_Read;
  6682. }
  6683. else {
  6684. Debug.Assert(!sync, "Should not have gotten a Task when writing in sync mode");
  6685. // Need to wait for flush - continuation will unlock the connection
  6686. bool taskReleaseConnectionLock = releaseConnectionLock;
  6687. releaseConnectionLock = false;
  6688. return executeTask.ContinueWith(t => {
  6689. Debug.Assert(!t.IsCanceled, "Task should not be canceled");
  6690. try {
  6691. if (t.IsFaulted) {
  6692. FailureCleanup(stateObj, t.Exception.InnerException);
  6693. throw t.Exception.InnerException;
  6694. }
  6695. else {
  6696. stateObj.SniContext = SniContext.Snix_Read;
  6697. }
  6698. }
  6699. finally {
  6700. if (taskReleaseConnectionLock) {
  6701. _connHandler._parserLock.Release();
  6702. }
  6703. }
  6704. }, TaskScheduler.Default);
  6705. }
  6706. // Finished [....]
  6707. return null;
  6708. }
  6709. catch (Exception e) {
  6710. //Debug.Assert(_state == TdsParserState.Broken, "Caught exception in TdsExecuteSQLBatch but connection was not broken!");
  6711. //
  6712. if (!ADP.IsCatchableExceptionType(e)) {
  6713. throw;
  6714. }
  6715. FailureCleanup(stateObj, e);
  6716. throw;
  6717. }
  6718. finally {
  6719. if (releaseConnectionLock) {
  6720. _connHandler._parserLock.Release();
  6721. }
  6722. }
  6723. }
  6724. internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, bool inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool isCommandProc, bool sync = true,
  6725. TaskCompletionSource<object> completion = null, int startRpc = 0, int startParam = 0) {
  6726. bool firstCall = (completion == null);
  6727. bool releaseConnectionLock = false;
  6728. Debug.Assert(cmd != null, @"cmd cannot be null inside TdsExecuteRPC");
  6729. Debug.Assert(!firstCall || startRpc == 0, "startRpc is not 0 on first call");
  6730. Debug.Assert(!firstCall || startParam == 0, "startParam is not 0 on first call");
  6731. Debug.Assert(!firstCall || !_connHandler.ThreadHasParserLockForClose, "Thread should not already have connection lock");
  6732. Debug.Assert(firstCall || _connHandler._parserLock.ThreadMayHaveLock(), "Connection lock not taken after the first call");
  6733. try {
  6734. _SqlRPC rpcext = null;
  6735. int tempLen;
  6736. // SQLBUDT #20010853 - Promote, Commit and Rollback requests for
  6737. // delegated transactions often happen while there is an open result
  6738. // set, so we need to handle them by using a different MARS session,
  6739. // otherwise we'll write on the physical state objects while someone
  6740. // else is using it. When we don't have MARS enabled, we need to
  6741. // lock the physical state object to syncronize it's use at least
  6742. // until we increment the open results count. Once it's been
  6743. // incremented the delegated transaction requests will fail, so they
  6744. // won't stomp on anything.
  6745. if (firstCall) {
  6746. _connHandler._parserLock.Wait(canReleaseFromAnyThread:!sync);
  6747. releaseConnectionLock = true;
  6748. }
  6749. try {
  6750. // Ensure that connection is alive
  6751. if ((TdsParserState.Broken == State) || (TdsParserState.Closed == State)) {
  6752. throw ADP.ClosedConnectionError();
  6753. }
  6754. // This validation step MUST be done after locking the connection to guarantee we don't
  6755. // accidentally execute after the transaction has completed on a different thread.
  6756. if (firstCall) {
  6757. _asyncWrite = !sync;
  6758. _connHandler.CheckEnlistedTransactionBinding();
  6759. stateObj.SetTimeoutSeconds(timeout);
  6760. if ((!_fMARS) && (_physicalStateObj.HasOpenResult))
  6761. {
  6762. Bid.Trace("<sc.TdsParser.TdsExecuteRPC|ERR> Potential multi-threaded misuse of connection, non-MARs connection with an open result %d#\n", ObjectID);
  6763. }
  6764. stateObj.SniContext = SniContext.Snix_Execute;
  6765. if (_isYukon) {
  6766. WriteRPCBatchHeaders(stateObj, notificationRequest);
  6767. }
  6768. stateObj._outputMessageType = TdsEnums.MT_RPC;
  6769. }
  6770. for (int ii = startRpc; ii < rpcArray.Length; ii++) {
  6771. rpcext = rpcArray[ii];
  6772. if (startParam == 0 || ii > startRpc) {
  6773. if (rpcext.ProcID != 0 && _isShiloh) {
  6774. // Perf optimization for Shiloh and later,
  6775. Debug.Assert(rpcext.ProcID < 255, "rpcExec:ProcID can't be larger than 255");
  6776. WriteShort(0xffff, stateObj);
  6777. WriteShort((short)(rpcext.ProcID), stateObj);
  6778. }
  6779. else {
  6780. Debug.Assert(!ADP.IsEmpty(rpcext.rpcName), "must have an RPC name");
  6781. tempLen = rpcext.rpcName.Length;
  6782. WriteShort(tempLen, stateObj);
  6783. WriteString(rpcext.rpcName, tempLen, 0, stateObj);
  6784. }
  6785. // Options
  6786. WriteShort((short)rpcext.options, stateObj);
  6787. }
  6788. // Stream out parameters
  6789. SqlParameter[] parameters = rpcext.parameters;
  6790. for (int i = (ii == startRpc) ? startParam : 0; i < parameters.Length; i++) {
  6791. // Debug.WriteLine("i: " + i.ToString(CultureInfo.InvariantCulture));
  6792. // parameters can be unnamed
  6793. SqlParameter param = parameters[i];
  6794. // Since we are reusing the parameters array, we cannot rely on length to indicate no of parameters.
  6795. if (param == null)
  6796. break; // End of parameters for this execute
  6797. // Throw an exception if ForceColumnEncryption is set on a parameter and the ColumnEncryption is not enabled on SqlConnection or SqlCommand
  6798. if (param.ForceColumnEncryption &&
  6799. !(cmd.ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled ||
  6800. (cmd.ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.UseConnectionSetting && cmd.Connection.IsColumnEncryptionSettingEnabled))) {
  6801. throw SQL.ParamInvalidForceColumnEncryptionSetting(param.ParameterName, rpcext.GetCommandTextOrRpcName());
  6802. }
  6803. // Check if the applications wants to force column encryption to avoid sending sensitive data to server
  6804. if (param.ForceColumnEncryption && param.CipherMetadata == null
  6805. && (param.Direction == ParameterDirection.Input || param.Direction == ParameterDirection.InputOutput)) {
  6806. // Application wants a parameter to be encrypted before sending it to server, however server doesnt think this parameter needs encryption.
  6807. throw SQL.ParamUnExpectedEncryptionMetadata(param.ParameterName, rpcext.GetCommandTextOrRpcName());
  6808. }
  6809. // Validate parameters are not variable length without size and with null value. MDAC 66522
  6810. param.Validate(i, isCommandProc);
  6811. // type (parameter record stores the MetaType class which is a helper that encapsulates all the type information we need here)
  6812. MetaType mt = param.InternalMetaType;
  6813. if (mt.IsNewKatmaiType) {
  6814. WriteSmiParameter(param, i, 0 != (rpcext.paramoptions[i] & TdsEnums.RPC_PARAM_DEFAULT), stateObj);
  6815. continue;
  6816. }
  6817. if ((!_isShiloh && !mt.Is70Supported) ||
  6818. (!_isYukon && !mt.Is80Supported) ||
  6819. (!_isKatmai && !mt.Is90Supported)) {
  6820. throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
  6821. }
  6822. object value = null;
  6823. bool isNull = true;
  6824. bool isSqlVal = false;
  6825. bool isDataFeed = false;
  6826. // if we have an output param, set the value to null so we do not send it across to the server
  6827. if (param.Direction == ParameterDirection.Output) {
  6828. isSqlVal = param.ParamaterIsSqlType; // We have to forward the TYPE info, we need to know what type we are returning. Once we null the paramater we will no longer be able to distinguish what type were seeing.
  6829. param.Value = null;
  6830. param.ParamaterIsSqlType = isSqlVal;
  6831. }
  6832. else {
  6833. value = param.GetCoercedValue();
  6834. isNull = param.IsNull;
  6835. if (!isNull) {
  6836. isSqlVal = param.CoercedValueIsSqlType;
  6837. isDataFeed = param.CoercedValueIsDataFeed;
  6838. }
  6839. }
  6840. WriteParameterName(param.ParameterNameFixed, stateObj);
  6841. // Write parameter status
  6842. stateObj.WriteByte(rpcext.paramoptions[i]);
  6843. // MaxLen field is only written out for non-fixed length data types
  6844. // use the greater of the two sizes for maxLen
  6845. int actualSize;
  6846. int size = mt.IsSizeInCharacters ? param.GetParameterSize() * 2 : param.GetParameterSize();
  6847. //for UDTs, we calculate the length later when we get the bytes. This is a really expensive operation
  6848. if (mt.TDSType != TdsEnums.SQLUDT)
  6849. // getting the actualSize is expensive, cache here and use below
  6850. actualSize = param.GetActualSize();
  6851. else
  6852. actualSize = 0; //get this later
  6853. byte precision = 0;
  6854. byte scale = 0;
  6855. // scale and precision are only relevant for numeric and decimal types
  6856. // adjust the actual value scale and precision to match the user specified
  6857. if (mt.SqlDbType == SqlDbType.Decimal) {
  6858. precision = param.GetActualPrecision();
  6859. scale = param.GetActualScale();
  6860. if (precision > TdsEnums.MAX_NUMERIC_PRECISION) {
  6861. throw SQL.PrecisionValueOutOfRange(precision);
  6862. }
  6863. // bug 49512, make sure the value matches the scale the user enters
  6864. if (!isNull) {
  6865. if (isSqlVal) {
  6866. value = AdjustSqlDecimalScale((SqlDecimal)value, scale);
  6867. // If Precision is specified, verify value precision vs param precision
  6868. if (precision != 0) {
  6869. if (precision < ((SqlDecimal)value).Precision) {
  6870. throw ADP.ParameterValueOutOfRange((SqlDecimal)value);
  6871. }
  6872. }
  6873. }
  6874. else {
  6875. value = AdjustDecimalScale((Decimal)value, scale);
  6876. SqlDecimal sqlValue = new SqlDecimal((Decimal)value);
  6877. // If Precision is specified, verify value precision vs param precision
  6878. if (precision != 0) {
  6879. if (precision < sqlValue.Precision) {
  6880. throw ADP.ParameterValueOutOfRange((Decimal)value);
  6881. }
  6882. }
  6883. }
  6884. }
  6885. }
  6886. bool isParameterEncrypted = 0 != (rpcext.paramoptions[i] & TdsEnums.RPC_PARAM_ENCRYPTED);
  6887. // Additional information we need to send over wire to the server when writing encrypted parameters.
  6888. SqlColumnEncryptionInputParameterInfo encryptedParameterInfoToWrite = null;
  6889. // If the parameter is encrypted, we need to encrypt the value.
  6890. if (isParameterEncrypted) {
  6891. Debug.Assert(mt.TDSType != TdsEnums.SQLVARIANT &&
  6892. mt.TDSType != TdsEnums.SQLUDT &&
  6893. mt.TDSType != TdsEnums.SQLXMLTYPE &&
  6894. mt.TDSType != TdsEnums.SQLIMAGE &&
  6895. mt.TDSType != TdsEnums.SQLTEXT &&
  6896. mt.TDSType != TdsEnums.SQLNTEXT, "Type unsupported for encryption");
  6897. byte[] serializedValue = null;
  6898. byte[] encryptedValue = null;
  6899. if (!isNull) {
  6900. try {
  6901. if (isSqlVal) {
  6902. serializedValue = SerializeUnencryptedSqlValue(value, mt, actualSize, param.Offset, param.NormalizationRuleVersion, stateObj);
  6903. }
  6904. else {
  6905. // for codePageEncoded types, WriteValue simply expects the number of characters
  6906. // For plp types, we also need the encoded byte size
  6907. serializedValue = SerializeUnencryptedValue(value, mt, param.GetActualScale(), actualSize, param.Offset, isDataFeed, param.NormalizationRuleVersion, stateObj);
  6908. }
  6909. Debug.Assert(serializedValue != null, "serializedValue should not be null in TdsExecuteRPC.");
  6910. encryptedValue = SqlSecurityUtility.EncryptWithKey(serializedValue, param.CipherMetadata, _connHandler.ConnectionOptions.DataSource);
  6911. }
  6912. catch (Exception e) {
  6913. throw SQL.ParamEncryptionFailed(param.ParameterName, null, e);
  6914. }
  6915. Debug.Assert(encryptedValue != null && encryptedValue.Length > 0,
  6916. "encryptedValue should not be null or empty in TdsExecuteRPC.");
  6917. }
  6918. else {
  6919. encryptedValue = null;
  6920. }
  6921. // Change the datatype to varbinary(max).
  6922. // Since we don't know the size of the encrypted parameter on the server side, always set to (max).
  6923. //
  6924. mt = MetaType.MetaMaxVarBinary;
  6925. size = -1;
  6926. actualSize = (encryptedValue == null) ? 0 : encryptedValue.Length;
  6927. encryptedParameterInfoToWrite = new SqlColumnEncryptionInputParameterInfo(param.GetMetadataForTypeInfo(),
  6928. param.CipherMetadata);
  6929. // Set the value to the encrypted value and mark isSqlVal as false for VARBINARY encrypted value.
  6930. value = encryptedValue;
  6931. isSqlVal = false;
  6932. }
  6933. Debug.Assert(isParameterEncrypted == (encryptedParameterInfoToWrite != null),
  6934. "encryptedParameterInfoToWrite can be not null if and only if isParameterEncrypted is true.");
  6935. Debug.Assert(!isSqlVal || !isParameterEncrypted, "isParameterEncrypted can be true only if isSqlVal is false.");
  6936. //
  6937. // fixup the types by using the NullableType property of the MetaType class
  6938. //
  6939. // following rules should be followed based on feedback from the M-SQL team
  6940. // 1) always use the BIG* types (ex: instead of SQLCHAR use SQLBIGCHAR)
  6941. // 2) always use nullable types (ex: instead of SQLINT use SQLINTN)
  6942. // 3) DECIMALN should always be sent as NUMERICN
  6943. //
  6944. stateObj.WriteByte(mt.NullableType);
  6945. // handle variants here: the SQLVariant writing routine will write the maxlen and actual len columns
  6946. if (mt.TDSType == TdsEnums.SQLVARIANT) {
  6947. // devnote: Do we ever hit this codepath? Yes, when a null value is being writen out via a sql variant
  6948. // param.GetActualSize is not used
  6949. WriteSqlVariantValue(isSqlVal ? MetaType.GetComValueFromSqlVariant(value) : value, param.GetActualSize(), param.Offset, stateObj);
  6950. continue;
  6951. }
  6952. int codePageByteSize = 0;
  6953. int maxsize = 0;
  6954. if (mt.IsAnsiType) {
  6955. // Avoid the following code block if ANSI but unfilled LazyMat blob
  6956. if ((!isNull) && (!isDataFeed)) {
  6957. string s;
  6958. if (isSqlVal) {
  6959. if (value is SqlString) {
  6960. s = ((SqlString)value).Value;
  6961. }
  6962. else {
  6963. Debug.Assert(value is SqlChars, "Unknown value for Ansi datatype");
  6964. s = new String(((SqlChars)value).Value);
  6965. }
  6966. }
  6967. else {
  6968. s = (string)value;
  6969. }
  6970. codePageByteSize = GetEncodingCharLength(s, actualSize, param.Offset, _defaultEncoding);
  6971. }
  6972. if (mt.IsPlp) {
  6973. WriteShort(TdsEnums.SQL_USHORTVARMAXLEN, stateObj);
  6974. }
  6975. else {
  6976. maxsize = (size > codePageByteSize) ? size : codePageByteSize;
  6977. if (maxsize == 0) {
  6978. // Yukon doesn't like 0 as MaxSize. Change it to 2 for unicode types (SQL9 - 682322)
  6979. if (mt.IsNCharType)
  6980. maxsize = 2;
  6981. else
  6982. maxsize = 1;
  6983. }
  6984. WriteParameterVarLen(mt, maxsize, false/*IsNull*/, stateObj);
  6985. }
  6986. }
  6987. else {
  6988. // If type timestamp - treat as fixed type and always send over timestamp length, which is 8.
  6989. // For fixed types, we either send null or fixed length for type length. We want to match that
  6990. // behavior for timestamps. However, in the case of null, we still must send 8 because if we
  6991. // send null we will not receive a output val. You can send null for fixed types and still
  6992. // receive a output value, but not for variable types. So, always send 8 for timestamp because
  6993. // while the user sees it as a fixed type, we are actually representing it as a bigbinary which
  6994. // is variable.
  6995. if (mt.SqlDbType == SqlDbType.Timestamp) {
  6996. WriteParameterVarLen(mt, TdsEnums.TEXT_TIME_STAMP_LEN, false, stateObj);
  6997. }
  6998. else if (mt.SqlDbType == SqlDbType.Udt) {
  6999. byte[] udtVal = null;
  7000. Microsoft.SqlServer.Server.Format format = Microsoft.SqlServer.Server.Format.Native;
  7001. Debug.Assert(_isYukon, "Invalid DataType UDT for non-Yukon or later server!");
  7002. if (!isNull) {
  7003. udtVal = _connHandler.Connection.GetBytes(value, out format, out maxsize);
  7004. Debug.Assert(null != udtVal, "GetBytes returned null instance. Make sure that it always returns non-null value");
  7005. size = udtVal.Length;
  7006. //it may be legitimate, but we dont support it yet
  7007. if (size < 0 || (size >= UInt16.MaxValue && maxsize != -1))
  7008. throw new IndexOutOfRangeException();
  7009. }
  7010. //if this is NULL value, write special null value
  7011. byte[] lenBytes = BitConverter.GetBytes((Int64)size);
  7012. if (ADP.IsEmpty(param.UdtTypeName))
  7013. throw SQL.MustSetUdtTypeNameForUdtParams();
  7014. // Split the input name. TypeName is returned as single 3 part name during DeriveParameters.
  7015. // NOTE: ParseUdtTypeName throws if format is incorrect
  7016. String[] names = SqlParameter.ParseTypeName(param.UdtTypeName, true /* is UdtTypeName */);
  7017. if (!ADP.IsEmpty(names[0]) && TdsEnums.MAX_SERVERNAME < names[0].Length) {
  7018. throw ADP.ArgumentOutOfRange("names");
  7019. }
  7020. if (!ADP.IsEmpty(names[1]) && TdsEnums.MAX_SERVERNAME < names[names.Length - 2].Length) {
  7021. throw ADP.ArgumentOutOfRange("names");
  7022. }
  7023. if (TdsEnums.MAX_SERVERNAME < names[2].Length) {
  7024. throw ADP.ArgumentOutOfRange("names");
  7025. }
  7026. WriteUDTMetaData(value, names[0], names[1], names[2], stateObj);
  7027. //
  7028. if (!isNull) {
  7029. WriteUnsignedLong((ulong)udtVal.Length, stateObj); // PLP length
  7030. if (udtVal.Length > 0) { // Only write chunk length if its value is greater than 0
  7031. WriteInt(udtVal.Length, stateObj); // Chunk length
  7032. stateObj.WriteByteArray(udtVal, udtVal.Length, 0); // Value
  7033. }
  7034. WriteInt(0, stateObj); // Terminator
  7035. }
  7036. else {
  7037. WriteUnsignedLong(TdsEnums.SQL_PLP_NULL, stateObj); // PLP Null.
  7038. }
  7039. continue; // End of UDT - continue to next parameter.
  7040. //
  7041. }
  7042. else if (mt.IsPlp) {
  7043. if (mt.SqlDbType != SqlDbType.Xml)
  7044. WriteShort(TdsEnums.SQL_USHORTVARMAXLEN, stateObj);
  7045. }
  7046. else if ((!mt.IsVarTime) && (mt.SqlDbType != SqlDbType.Date)) { // Time, Date, DateTime2, DateTimeoffset do not have the size written out
  7047. maxsize = (size > actualSize) ? size : actualSize;
  7048. if (maxsize == 0 && IsYukonOrNewer) {
  7049. // Yukon doesn't like 0 as MaxSize. Change it to 2 for unicode types (SQL9 - 682322)
  7050. if (mt.IsNCharType)
  7051. maxsize = 2;
  7052. else
  7053. maxsize = 1;
  7054. }
  7055. WriteParameterVarLen(mt, maxsize, false/*IsNull*/, stateObj);
  7056. }
  7057. }
  7058. // scale and precision are only relevant for numeric and decimal types
  7059. if (mt.SqlDbType == SqlDbType.Decimal) {
  7060. if (0 == precision) {
  7061. if (_isShiloh)
  7062. stateObj.WriteByte(TdsEnums.DEFAULT_NUMERIC_PRECISION);
  7063. else
  7064. stateObj.WriteByte(TdsEnums.SPHINX_DEFAULT_NUMERIC_PRECISION);
  7065. }
  7066. else
  7067. stateObj.WriteByte(precision);
  7068. stateObj.WriteByte(scale);
  7069. }
  7070. else if (mt.IsVarTime) {
  7071. stateObj.WriteByte(param.GetActualScale());
  7072. }
  7073. // write out collation or xml metadata
  7074. if (_isYukon && (mt.SqlDbType == SqlDbType.Xml)) {
  7075. if (((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != ADP.StrEmpty)) ||
  7076. ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != ADP.StrEmpty)) ||
  7077. ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != ADP.StrEmpty))) {
  7078. stateObj.WriteByte(1); //Schema present flag
  7079. if ((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != ADP.StrEmpty)) {
  7080. tempLen = (param.XmlSchemaCollectionDatabase).Length;
  7081. stateObj.WriteByte((byte)(tempLen));
  7082. WriteString(param.XmlSchemaCollectionDatabase, tempLen, 0, stateObj);
  7083. }
  7084. else {
  7085. stateObj.WriteByte(0); // No dbname
  7086. }
  7087. if ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != ADP.StrEmpty)) {
  7088. tempLen = (param.XmlSchemaCollectionOwningSchema).Length;
  7089. stateObj.WriteByte((byte)(tempLen));
  7090. WriteString(param.XmlSchemaCollectionOwningSchema, tempLen, 0, stateObj);
  7091. }
  7092. else {
  7093. stateObj.WriteByte(0); // no xml schema name
  7094. }
  7095. if ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != ADP.StrEmpty)) {
  7096. tempLen = (param.XmlSchemaCollectionName).Length;
  7097. WriteShort((short)(tempLen), stateObj);
  7098. WriteString(param.XmlSchemaCollectionName, tempLen, 0, stateObj);
  7099. }
  7100. else {
  7101. WriteShort(0, stateObj); // No xml schema collection name
  7102. }
  7103. }
  7104. else {
  7105. stateObj.WriteByte(0); // No schema
  7106. }
  7107. }
  7108. else if (_isShiloh && mt.IsCharType) {
  7109. // if it is not supplied, simply write out our default collation, otherwise, write out the one attached to the parameter
  7110. SqlCollation outCollation = (param.Collation != null) ? param.Collation : _defaultCollation;
  7111. Debug.Assert(_defaultCollation != null, "_defaultCollation is null!");
  7112. WriteUnsignedInt(outCollation.info, stateObj);
  7113. stateObj.WriteByte(outCollation.sortId);
  7114. }
  7115. if (0 == codePageByteSize)
  7116. WriteParameterVarLen(mt, actualSize, isNull, stateObj, isDataFeed);
  7117. else
  7118. WriteParameterVarLen(mt, codePageByteSize, isNull, stateObj, isDataFeed);
  7119. Task writeParamTask = null;
  7120. // write the value now
  7121. if (!isNull) {
  7122. if (isSqlVal) {
  7123. writeParamTask = WriteSqlValue(value, mt, actualSize, codePageByteSize, param.Offset, stateObj);
  7124. }
  7125. else {
  7126. // for codePageEncoded types, WriteValue simply expects the number of characters
  7127. // For plp types, we also need the encoded byte size
  7128. writeParamTask = WriteValue(value, mt, isParameterEncrypted ? (byte)0 : param.GetActualScale(), actualSize, codePageByteSize, isParameterEncrypted ? 0 : param.Offset, stateObj, isParameterEncrypted ? 0 : param.Size, isDataFeed);
  7129. }
  7130. }
  7131. // Send encryption metadata for encrypted parameters.
  7132. if (isParameterEncrypted) {
  7133. writeParamTask = WriteEncryptionMetadata(writeParamTask, encryptedParameterInfoToWrite, stateObj);
  7134. }
  7135. if (!sync) {
  7136. if (writeParamTask == null) {
  7137. writeParamTask = stateObj.WaitForAccumulatedWrites();
  7138. }
  7139. if (writeParamTask != null) {
  7140. Task task = null;
  7141. if (completion == null) {
  7142. completion = new TaskCompletionSource<object>();
  7143. task = completion.Task;
  7144. }
  7145. AsyncHelper.ContinueTask(writeParamTask, completion,
  7146. () => TdsExecuteRPC(cmd, rpcArray, timeout, inSchema, notificationRequest, stateObj, isCommandProc, sync, completion,
  7147. startRpc: ii, startParam: i + 1),
  7148. connectionToDoom: _connHandler,
  7149. onFailure: exc => TdsExecuteRPC_OnFailure(exc, stateObj));
  7150. // Take care of releasing the locks
  7151. if (releaseConnectionLock) {
  7152. task.ContinueWith(_ => {
  7153. _connHandler._parserLock.Release();
  7154. }, TaskScheduler.Default);
  7155. releaseConnectionLock = false;
  7156. }
  7157. return task;
  7158. }
  7159. }
  7160. #if DEBUG
  7161. else {
  7162. Debug.Assert(writeParamTask == null, "Should not have a task when executing sync");
  7163. }
  7164. #endif
  7165. } // parameter for loop
  7166. // If this is not the last RPC we are sending, add the batch flag
  7167. if (ii < (rpcArray.Length - 1)) {
  7168. if (_isYukon) {
  7169. stateObj.WriteByte(TdsEnums.YUKON_RPCBATCHFLAG);
  7170. }
  7171. else {
  7172. stateObj.WriteByte(TdsEnums.SHILOH_RPCBATCHFLAG);
  7173. }
  7174. }
  7175. } // rpc for loop
  7176. Task execFlushTask = stateObj.ExecuteFlush();
  7177. Debug.Assert(!sync || execFlushTask == null, "Should not get a task when executing sync");
  7178. if (execFlushTask != null) {
  7179. Task task = null;
  7180. if (completion == null) {
  7181. completion = new TaskCompletionSource<object>();
  7182. task = completion.Task;
  7183. }
  7184. bool taskReleaseConnectionLock = releaseConnectionLock;
  7185. execFlushTask.ContinueWith(tsk => ExecuteFlushTaskCallback(tsk, stateObj, completion, taskReleaseConnectionLock), TaskScheduler.Default);
  7186. // ExecuteFlushTaskCallback will take care of the locks for us
  7187. releaseConnectionLock = false;
  7188. return task;
  7189. }
  7190. }
  7191. catch (Exception e) {
  7192. //
  7193. if (!ADP.IsCatchableExceptionType(e)) {
  7194. throw;
  7195. }
  7196. FailureCleanup(stateObj, e);
  7197. throw;
  7198. }
  7199. FinalizeExecuteRPC(stateObj);
  7200. if (completion != null) {
  7201. completion.SetResult(null);
  7202. }
  7203. return null;
  7204. }
  7205. catch (Exception e) {
  7206. FinalizeExecuteRPC(stateObj);
  7207. if (completion != null) {
  7208. completion.SetException(e);
  7209. return null;
  7210. }
  7211. else {
  7212. throw e;
  7213. }
  7214. }
  7215. finally {
  7216. Debug.Assert(firstCall || !releaseConnectionLock, "Shouldn't be releasing locks synchronously after the first call");
  7217. if (releaseConnectionLock) {
  7218. _connHandler._parserLock.Release();
  7219. }
  7220. }
  7221. }
  7222. private void FinalizeExecuteRPC(TdsParserStateObject stateObj) {
  7223. stateObj.SniContext = SniContext.Snix_Read;
  7224. _asyncWrite = false;
  7225. }
  7226. private void TdsExecuteRPC_OnFailure(Exception exc, TdsParserStateObject stateObj) {
  7227. RuntimeHelpers.PrepareConstrainedRegions();
  7228. try {
  7229. #if DEBUG
  7230. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  7231. RuntimeHelpers.PrepareConstrainedRegions();
  7232. try {
  7233. tdsReliabilitySection.Start();
  7234. #else
  7235. {
  7236. #endif //DEBUG
  7237. FailureCleanup(stateObj, exc);
  7238. }
  7239. #if DEBUG
  7240. finally {
  7241. tdsReliabilitySection.Stop();
  7242. }
  7243. #endif //DEBUG
  7244. }
  7245. catch (System.OutOfMemoryException) {
  7246. _connHandler.DoomThisConnection();
  7247. throw;
  7248. }
  7249. catch (System.StackOverflowException) {
  7250. _connHandler.DoomThisConnection();
  7251. throw;
  7252. }
  7253. catch (System.Threading.ThreadAbortException) {
  7254. _connHandler.DoomThisConnection();
  7255. throw;
  7256. }
  7257. }
  7258. private void ExecuteFlushTaskCallback(Task tsk, TdsParserStateObject stateObj, TaskCompletionSource<object> completion, bool releaseConnectionLock) {
  7259. try {
  7260. FinalizeExecuteRPC(stateObj);
  7261. if (tsk.Exception != null) {
  7262. Exception exc = tsk.Exception.InnerException;
  7263. RuntimeHelpers.PrepareConstrainedRegions();
  7264. try {
  7265. #if DEBUG
  7266. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  7267. RuntimeHelpers.PrepareConstrainedRegions();
  7268. try {
  7269. tdsReliabilitySection.Start();
  7270. #else
  7271. {
  7272. #endif //DEBUG
  7273. FailureCleanup(stateObj, tsk.Exception);
  7274. }
  7275. #if DEBUG
  7276. finally {
  7277. tdsReliabilitySection.Stop();
  7278. }
  7279. #endif //DEBUG
  7280. }
  7281. catch (System.OutOfMemoryException e) {
  7282. _connHandler.DoomThisConnection();
  7283. completion.SetException(e);
  7284. throw;
  7285. }
  7286. catch (System.StackOverflowException e) {
  7287. _connHandler.DoomThisConnection();
  7288. completion.SetException(e);
  7289. throw;
  7290. }
  7291. catch (System.Threading.ThreadAbortException e) {
  7292. _connHandler.DoomThisConnection();
  7293. completion.SetException(e);
  7294. throw;
  7295. }
  7296. catch (Exception e) {
  7297. exc = e;
  7298. }
  7299. completion.SetException(exc);
  7300. }
  7301. else {
  7302. completion.SetResult(null);
  7303. }
  7304. }
  7305. finally {
  7306. if (releaseConnectionLock) {
  7307. _connHandler._parserLock.Release();
  7308. }
  7309. }
  7310. }
  7311. private void WriteParameterName(string parameterName, TdsParserStateObject stateObj) {
  7312. // paramLen
  7313. // paramName
  7314. if (!ADP.IsEmpty(parameterName)) {
  7315. Debug.Assert(parameterName.Length <= 0xff, "parameter name can only be 255 bytes, shouldn't get to TdsParser!");
  7316. int tempLen = parameterName.Length & 0xff;
  7317. stateObj.WriteByte((byte)tempLen);
  7318. WriteString(parameterName, tempLen, 0, stateObj);
  7319. }
  7320. else {
  7321. stateObj.WriteByte(0);
  7322. }
  7323. }
  7324. private static readonly IEnumerable<MSS.SqlDataRecord> __tvpEmptyValue = new List<MSS.SqlDataRecord>().AsReadOnly();
  7325. private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefault, TdsParserStateObject stateObj) {
  7326. //
  7327. // Determine Metadata
  7328. //
  7329. ParameterPeekAheadValue peekAhead;
  7330. MSS.SmiParameterMetaData metaData = param.MetaDataForSmi(out peekAhead);
  7331. if (!_isKatmai) {
  7332. MetaType mt = MetaType.GetMetaTypeFromSqlDbType(metaData.SqlDbType, metaData.IsMultiValued);
  7333. throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
  7334. }
  7335. //
  7336. // Determine value to send
  7337. //
  7338. object value;
  7339. MSS.ExtendedClrTypeCode typeCode;
  7340. // if we have an output or default param, set the value to null so we do not send it across to the server
  7341. if (sendDefault) {
  7342. // Value for TVP default is empty list, not NULL
  7343. if (SqlDbType.Structured == metaData.SqlDbType && metaData.IsMultiValued) {
  7344. value = __tvpEmptyValue;
  7345. typeCode = MSS.ExtendedClrTypeCode.IEnumerableOfSqlDataRecord;
  7346. }
  7347. else {
  7348. // Need to send null value for default
  7349. value = null;
  7350. typeCode = MSS.ExtendedClrTypeCode.DBNull;
  7351. }
  7352. }
  7353. else if (param.Direction == ParameterDirection.Output) {
  7354. bool isCLRType = param.ParamaterIsSqlType; // We have to forward the TYPE info, we need to know what type we are returning. Once we null the paramater we will no longer be able to distinguish what type were seeing.
  7355. param.Value = null;
  7356. value = null;
  7357. typeCode = MSS.ExtendedClrTypeCode.DBNull;
  7358. param.ParamaterIsSqlType = isCLRType;
  7359. }
  7360. else {
  7361. value = param.GetCoercedValue();
  7362. typeCode = MSS.MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(
  7363. metaData.SqlDbType, metaData.IsMultiValued, value, null, MSS.SmiContextFactory.KatmaiVersion);
  7364. }
  7365. if (Bid.AdvancedOn) {
  7366. Bid.Trace("<sc.TdsParser.WriteSmiParameter|ADV> %d#, Sending parameter '%ls', default flag=%d, metadata:\n", ObjectID, param.ParameterName, sendDefault?1:0);
  7367. Bid.PutStr(metaData.TraceString(3));
  7368. Bid.Trace("\n");
  7369. }
  7370. //
  7371. // Write parameter metadata
  7372. //
  7373. WriteSmiParameterMetaData(metaData, sendDefault, stateObj);
  7374. //
  7375. // Now write the value
  7376. //
  7377. TdsParameterSetter paramSetter = new TdsParameterSetter(stateObj, metaData);
  7378. MSS.ValueUtilsSmi.SetCompatibleValueV200(
  7379. new MSS.SmiEventSink_Default(), // TDS Errors/events dealt with at lower level for now, just need an object for processing
  7380. paramSetter,
  7381. 0, // ordinal. TdsParameterSetter only handles one parameter at a time
  7382. metaData,
  7383. value,
  7384. typeCode,
  7385. param.Offset,
  7386. 0 < param.Size ? param.Size : -1,
  7387. peekAhead);
  7388. }
  7389. // Writes metadata portion of parameter stream from an SmiParameterMetaData object.
  7390. private void WriteSmiParameterMetaData(MSS.SmiParameterMetaData metaData, bool sendDefault, TdsParserStateObject stateObj) {
  7391. // Determine status
  7392. byte status = 0;
  7393. if (ParameterDirection.Output == metaData.Direction || ParameterDirection.InputOutput == metaData.Direction) {
  7394. status |= TdsEnums.RPC_PARAM_BYREF;
  7395. }
  7396. if (sendDefault) {
  7397. status |= TdsEnums.RPC_PARAM_DEFAULT;
  7398. }
  7399. // Write everything out
  7400. WriteParameterName(metaData.Name, stateObj);
  7401. stateObj.WriteByte(status);
  7402. WriteSmiTypeInfo(metaData, stateObj);
  7403. }
  7404. // Write a TypeInfo stream
  7405. // Devnote: we remap the legacy types (text, ntext, and image) to SQLBIGVARCHAR, SQLNVARCHAR, and SQLBIGVARBINARY
  7406. private void WriteSmiTypeInfo(MSS.SmiExtendedMetaData metaData, TdsParserStateObject stateObj) {
  7407. switch(metaData.SqlDbType) {
  7408. case SqlDbType.BigInt:
  7409. stateObj.WriteByte(TdsEnums.SQLINTN);
  7410. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7411. break;
  7412. case SqlDbType.Binary:
  7413. stateObj.WriteByte(TdsEnums.SQLBIGBINARY);
  7414. WriteUnsignedShort(checked((ushort)metaData.MaxLength), stateObj);
  7415. break;
  7416. case SqlDbType.Bit:
  7417. stateObj.WriteByte(TdsEnums.SQLBITN);
  7418. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7419. break;
  7420. case SqlDbType.Char:
  7421. stateObj.WriteByte(TdsEnums.SQLBIGCHAR);
  7422. WriteUnsignedShort(checked((ushort)(metaData.MaxLength)), stateObj);
  7423. WriteUnsignedInt(_defaultCollation.info, stateObj); // TODO: Use metadata's collation??
  7424. stateObj.WriteByte(_defaultCollation.sortId);
  7425. break;
  7426. case SqlDbType.DateTime:
  7427. stateObj.WriteByte(TdsEnums.SQLDATETIMN);
  7428. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7429. break;
  7430. case SqlDbType.Decimal:
  7431. stateObj.WriteByte(TdsEnums.SQLNUMERICN);
  7432. stateObj.WriteByte(checked((byte)MetaType.MetaDecimal.FixedLength)); // SmiMetaData's length and actual wire format's length are different
  7433. stateObj.WriteByte(0 == metaData.Precision ? (byte)1 : metaData.Precision);
  7434. stateObj.WriteByte(metaData.Scale);
  7435. break;
  7436. case SqlDbType.Float:
  7437. stateObj.WriteByte(TdsEnums.SQLFLTN);
  7438. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7439. break;
  7440. case SqlDbType.Image:
  7441. stateObj.WriteByte(TdsEnums.SQLBIGVARBINARY);
  7442. WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
  7443. break;
  7444. case SqlDbType.Int:
  7445. stateObj.WriteByte(TdsEnums.SQLINTN);
  7446. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7447. break;
  7448. case SqlDbType.Money:
  7449. stateObj.WriteByte(TdsEnums.SQLMONEYN);
  7450. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7451. break;
  7452. case SqlDbType.NChar:
  7453. stateObj.WriteByte(TdsEnums.SQLNCHAR);
  7454. WriteUnsignedShort(checked((ushort)(metaData.MaxLength*2)), stateObj);
  7455. WriteUnsignedInt(_defaultCollation.info, stateObj); // TODO: Use metadata's collation??
  7456. stateObj.WriteByte(_defaultCollation.sortId);
  7457. break;
  7458. case SqlDbType.NText:
  7459. stateObj.WriteByte(TdsEnums.SQLNVARCHAR);
  7460. WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
  7461. WriteUnsignedInt(_defaultCollation.info, stateObj); // TODO: Use metadata's collation??
  7462. stateObj.WriteByte(_defaultCollation.sortId);
  7463. break;
  7464. case SqlDbType.NVarChar:
  7465. stateObj.WriteByte(TdsEnums.SQLNVARCHAR);
  7466. if (MSS.SmiMetaData.UnlimitedMaxLengthIndicator == metaData.MaxLength) {
  7467. WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
  7468. }
  7469. else {
  7470. WriteUnsignedShort(checked((ushort)(metaData.MaxLength*2)), stateObj);
  7471. }
  7472. WriteUnsignedInt(_defaultCollation.info, stateObj); // TODO: Use metadata's collation??
  7473. stateObj.WriteByte(_defaultCollation.sortId);
  7474. break;
  7475. case SqlDbType.Real:
  7476. stateObj.WriteByte(TdsEnums.SQLFLTN);
  7477. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7478. break;
  7479. case SqlDbType.UniqueIdentifier:
  7480. stateObj.WriteByte(TdsEnums.SQLUNIQUEID);
  7481. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7482. break;
  7483. case SqlDbType.SmallDateTime:
  7484. stateObj.WriteByte(TdsEnums.SQLDATETIMN);
  7485. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7486. break;
  7487. case SqlDbType.SmallInt:
  7488. stateObj.WriteByte(TdsEnums.SQLINTN);
  7489. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7490. break;
  7491. case SqlDbType.SmallMoney:
  7492. stateObj.WriteByte(TdsEnums.SQLMONEYN);
  7493. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7494. break;
  7495. case SqlDbType.Text:
  7496. stateObj.WriteByte(TdsEnums.SQLBIGVARCHAR);
  7497. WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
  7498. WriteUnsignedInt(_defaultCollation.info, stateObj); // TODO: Use metadata's collation??
  7499. stateObj.WriteByte(_defaultCollation.sortId);
  7500. break;
  7501. case SqlDbType.Timestamp:
  7502. stateObj.WriteByte(TdsEnums.SQLBIGBINARY);
  7503. WriteShort(checked((int)metaData.MaxLength), stateObj);
  7504. break;
  7505. case SqlDbType.TinyInt:
  7506. stateObj.WriteByte(TdsEnums.SQLINTN);
  7507. stateObj.WriteByte(checked((byte)metaData.MaxLength));
  7508. break;
  7509. case SqlDbType.VarBinary:
  7510. stateObj.WriteByte(TdsEnums.SQLBIGVARBINARY);
  7511. WriteUnsignedShort(unchecked((ushort)metaData.MaxLength), stateObj);
  7512. break;
  7513. case SqlDbType.VarChar:
  7514. stateObj.WriteByte(TdsEnums.SQLBIGVARCHAR);
  7515. WriteUnsignedShort(unchecked((ushort)metaData.MaxLength), stateObj);
  7516. WriteUnsignedInt(_defaultCollation.info, stateObj); // TODO: Use metadata's collation??
  7517. stateObj.WriteByte(_defaultCollation.sortId);
  7518. break;
  7519. case SqlDbType.Variant:
  7520. stateObj.WriteByte(TdsEnums.SQLVARIANT);
  7521. WriteInt(checked((int)metaData.MaxLength), stateObj);
  7522. break;
  7523. case SqlDbType.Xml:
  7524. stateObj.WriteByte(TdsEnums.SQLXMLTYPE);
  7525. // Is there a schema
  7526. if (ADP.IsEmpty(metaData.TypeSpecificNamePart1) && ADP.IsEmpty(metaData.TypeSpecificNamePart2) &&
  7527. ADP.IsEmpty(metaData.TypeSpecificNamePart3)) {
  7528. stateObj.WriteByte(0); // schema not present
  7529. }
  7530. else {
  7531. stateObj.WriteByte(1); // schema present
  7532. WriteIdentifier(metaData.TypeSpecificNamePart1, stateObj);
  7533. WriteIdentifier(metaData.TypeSpecificNamePart2, stateObj);
  7534. WriteIdentifierWithShortLength(metaData.TypeSpecificNamePart3, stateObj);
  7535. }
  7536. break;
  7537. case SqlDbType.Udt:
  7538. stateObj.WriteByte(TdsEnums.SQLUDT);
  7539. WriteIdentifier(metaData.TypeSpecificNamePart1, stateObj);
  7540. WriteIdentifier(metaData.TypeSpecificNamePart2, stateObj);
  7541. WriteIdentifier(metaData.TypeSpecificNamePart3, stateObj);
  7542. break;
  7543. case SqlDbType.Structured:
  7544. if (metaData.IsMultiValued) {
  7545. WriteTvpTypeInfo(metaData, stateObj);
  7546. }
  7547. else {
  7548. Debug.Assert(false, "SUDTs not yet supported.");
  7549. }
  7550. break;
  7551. case SqlDbType.Date:
  7552. stateObj.WriteByte(TdsEnums.SQLDATE);
  7553. break;
  7554. case SqlDbType.Time:
  7555. stateObj.WriteByte(TdsEnums.SQLTIME);
  7556. stateObj.WriteByte(metaData.Scale);
  7557. break;
  7558. case SqlDbType.DateTime2:
  7559. stateObj.WriteByte(TdsEnums.SQLDATETIME2);
  7560. stateObj.WriteByte(metaData.Scale);
  7561. break;
  7562. case SqlDbType.DateTimeOffset:
  7563. stateObj.WriteByte(TdsEnums.SQLDATETIMEOFFSET);
  7564. stateObj.WriteByte(metaData.Scale);
  7565. break;
  7566. default:
  7567. Debug.Assert(false, "Unknown SqlDbType should have been caught earlier!");
  7568. break;
  7569. }
  7570. }
  7571. private void WriteTvpTypeInfo(MSS.SmiExtendedMetaData metaData, TdsParserStateObject stateObj) {
  7572. Debug.Assert(SqlDbType.Structured == metaData.SqlDbType && metaData.IsMultiValued,
  7573. "Invalid metadata for TVPs. Type=" + metaData.SqlDbType);
  7574. // Type token
  7575. stateObj.WriteByte((byte)TdsEnums.SQLTABLE);
  7576. // 3-part name (DB, Schema, TypeName)
  7577. WriteIdentifier(metaData.TypeSpecificNamePart1, stateObj);
  7578. WriteIdentifier(metaData.TypeSpecificNamePart2, stateObj);
  7579. WriteIdentifier(metaData.TypeSpecificNamePart3, stateObj);
  7580. // TVP_COLMETADATA
  7581. if (0 == metaData.FieldMetaData.Count) {
  7582. WriteUnsignedShort((ushort)TdsEnums.TVP_NOMETADATA_TOKEN, stateObj);
  7583. }
  7584. else {
  7585. // COUNT of columns
  7586. WriteUnsignedShort(checked((ushort) metaData.FieldMetaData.Count), stateObj);
  7587. // TvpColumnMetaData for each column (look for defaults in this loop
  7588. MSS.SmiDefaultFieldsProperty defaults = (MSS.SmiDefaultFieldsProperty) metaData.ExtendedProperties[MSS.SmiPropertySelector.DefaultFields];
  7589. for(int i=0; i<metaData.FieldMetaData.Count; i++) {
  7590. WriteTvpColumnMetaData(metaData.FieldMetaData[i], defaults[i], stateObj);
  7591. }
  7592. // optional OrderUnique metadata
  7593. WriteTvpOrderUnique(metaData, stateObj);
  7594. }
  7595. // END of optional metadata
  7596. stateObj.WriteByte(TdsEnums.TVP_END_TOKEN);
  7597. }
  7598. // Write a single TvpColumnMetaData stream to the server
  7599. private void WriteTvpColumnMetaData(MSS.SmiExtendedMetaData md, bool isDefault, TdsParserStateObject stateObj) {
  7600. // User Type
  7601. if (SqlDbType.Timestamp == md.SqlDbType) {
  7602. WriteUnsignedInt(TdsEnums.SQLTIMESTAMP, stateObj);
  7603. } else {
  7604. WriteUnsignedInt(0, stateObj);
  7605. }
  7606. // Flags
  7607. ushort status = TdsEnums.Nullable;
  7608. if (isDefault) {
  7609. status |= TdsEnums.TVP_DEFAULT_COLUMN;
  7610. }
  7611. WriteUnsignedShort(status, stateObj);
  7612. // Type info
  7613. WriteSmiTypeInfo(md, stateObj);
  7614. // Column name
  7615. // per spec, "ColName is never sent to server or client for TVP, it is required within a TVP to be zero length."
  7616. WriteIdentifier(null, stateObj);
  7617. }
  7618. // temporary-results structure used only by WriteTvpOrderUnique
  7619. // use class to avoid List<T>'s per-struct-instantiated memory costs.
  7620. private class TdsOrderUnique {
  7621. internal short ColumnOrdinal;
  7622. internal byte Flags;
  7623. internal TdsOrderUnique(short ordinal, byte flags) {
  7624. ColumnOrdinal = ordinal;
  7625. Flags = flags;
  7626. }
  7627. }
  7628. private void WriteTvpOrderUnique(MSS.SmiExtendedMetaData metaData, TdsParserStateObject stateObj) {
  7629. // TVP_ORDER_UNIQUE token (uniqueness and sort order)
  7630. // Merge order and unique keys into a single token stream
  7631. MSS.SmiOrderProperty orderProperty = (MSS.SmiOrderProperty) metaData.ExtendedProperties[MSS.SmiPropertySelector.SortOrder];
  7632. MSS.SmiUniqueKeyProperty uniqueKeyProperty = (MSS.SmiUniqueKeyProperty) metaData.ExtendedProperties[MSS.SmiPropertySelector.UniqueKey];
  7633. // Build list from
  7634. List<TdsOrderUnique> columnList = new List<TdsOrderUnique>(metaData.FieldMetaData.Count);
  7635. for(int i=0; i<metaData.FieldMetaData.Count; i++) {
  7636. // Add appropriate SortOrder flag
  7637. byte flags = 0;
  7638. MSS.SmiOrderProperty.SmiColumnOrder columnOrder = orderProperty[i];
  7639. if (SortOrder.Ascending == columnOrder.Order) {
  7640. flags = TdsEnums.TVP_ORDERASC_FLAG;
  7641. }
  7642. else if (SortOrder.Descending == columnOrder.Order) {
  7643. flags = TdsEnums.TVP_ORDERDESC_FLAG;
  7644. }
  7645. // Add unique key flage if appropriate
  7646. if (uniqueKeyProperty[i]) {
  7647. flags |= TdsEnums.TVP_UNIQUE_FLAG;
  7648. }
  7649. // Remember this column if any flags were set
  7650. if (0 != flags) {
  7651. columnList.Add(new TdsOrderUnique(checked((short)(i+1)), flags));
  7652. }
  7653. }
  7654. // Write flagged columns to wire...
  7655. if (0 < columnList.Count) {
  7656. stateObj.WriteByte(TdsEnums.TVP_ORDER_UNIQUE_TOKEN);
  7657. WriteShort(columnList.Count, stateObj);
  7658. foreach(TdsOrderUnique column in columnList) {
  7659. WriteShort(column.ColumnOrdinal, stateObj);
  7660. stateObj.WriteByte(column.Flags);
  7661. }
  7662. }
  7663. }
  7664. internal Task WriteBulkCopyDone(TdsParserStateObject stateObj) {
  7665. // Write DONE packet
  7666. //
  7667. if (!(State == TdsParserState.OpenNotLoggedIn || State == TdsParserState.OpenLoggedIn)) {
  7668. throw ADP.ClosedConnectionError();
  7669. }
  7670. stateObj.WriteByte(TdsEnums.SQLDONE);
  7671. WriteShort(0, stateObj);
  7672. WriteShort(0, stateObj);
  7673. WriteInt(0, stateObj);
  7674. stateObj._pendingData = true;
  7675. stateObj._messageStatus = 0;
  7676. return stateObj.WritePacket(TdsEnums.HARDFLUSH);
  7677. }
  7678. /// <summary>
  7679. /// Loads the column encryptions keys into cache. This will read the master key info,
  7680. /// decrypt the CEK and keep it ready for encryption.
  7681. /// </summary>
  7682. /// <returns></returns>
  7683. internal void LoadColumnEncryptionKeys (_SqlMetaDataSet metadataCollection, string serverName) {
  7684. if (_serverSupportsColumnEncryption && ShouldEncryptValuesForBulkCopy()) {
  7685. for (int col = 0; col < metadataCollection.Length; col++) {
  7686. if (null != metadataCollection[col]) {
  7687. _SqlMetaData md = metadataCollection[col];
  7688. if (md.isEncrypted) {
  7689. SqlSecurityUtility.DecryptSymmetricKey(md.cipherMD, serverName);
  7690. }
  7691. }
  7692. }
  7693. }
  7694. }
  7695. /// <summary>
  7696. /// Writes a single entry of CEK Table into TDS Stream (for bulk copy).
  7697. /// </summary>
  7698. /// <returns></returns>
  7699. internal void WriteEncryptionEntries (ref SqlTceCipherInfoTable cekTable, TdsParserStateObject stateObj) {
  7700. for (int i =0; i < cekTable.Size; i++) {
  7701. // Write Db ID
  7702. WriteInt(cekTable[i].DatabaseId, stateObj);
  7703. // Write Key ID
  7704. WriteInt(cekTable[i].CekId, stateObj);
  7705. // Write Key Version
  7706. WriteInt(cekTable[i].CekVersion, stateObj);
  7707. // Write 8 bytes of key MD Version
  7708. Debug.Assert (8 == cekTable[i].CekMdVersion.Length);
  7709. stateObj.WriteByteArray (cekTable[i].CekMdVersion, 8, 0);
  7710. // We don't really need to send the keys
  7711. stateObj.WriteByte(0x00);
  7712. }
  7713. }
  7714. /// <summary>
  7715. /// Writes a CEK Table (as part of COLMETADATA token) for bulk copy.
  7716. /// </summary>
  7717. /// <returns></returns>
  7718. internal void WriteCekTable (_SqlMetaDataSet metadataCollection, TdsParserStateObject stateObj) {
  7719. if (!_serverSupportsColumnEncryption) {
  7720. return;
  7721. }
  7722. // If no cek table is present, send a count of 0 for table size
  7723. // Note- Cek table (with 0 entries) will be present if TCE
  7724. // was enabled and server supports it!
  7725. // OR if encryption was disabled in connection options
  7726. if (!metadataCollection.cekTable.HasValue ||
  7727. !ShouldEncryptValuesForBulkCopy()) {
  7728. WriteShort(0x00, stateObj);
  7729. return;
  7730. }
  7731. SqlTceCipherInfoTable cekTable = metadataCollection.cekTable.Value;
  7732. ushort count = (ushort)cekTable.Size;
  7733. WriteShort(count, stateObj);
  7734. WriteEncryptionEntries(ref cekTable, stateObj);
  7735. }
  7736. /// <summary>
  7737. /// Writes the UserType and TYPE_INFO values for CryptoMetadata (for bulk copy).
  7738. /// </summary>
  7739. /// <returns></returns>
  7740. internal void WriteTceUserTypeAndTypeInfo(SqlMetaDataPriv mdPriv, TdsParserStateObject stateObj) {
  7741. // Write the UserType (4 byte value)
  7742. WriteInt(0x0, stateObj); // TODO: fix this- timestamp columns have 0x50 value here
  7743. Debug.Assert(SqlDbType.Xml != mdPriv.type);
  7744. Debug.Assert(SqlDbType.Udt != mdPriv.type);
  7745. stateObj.WriteByte(mdPriv.tdsType);
  7746. switch (mdPriv.type) {
  7747. case SqlDbType.Decimal:
  7748. WriteTokenLength(mdPriv.tdsType, mdPriv.length, stateObj);
  7749. stateObj.WriteByte(mdPriv.precision);
  7750. stateObj.WriteByte(mdPriv.scale);
  7751. break;
  7752. case SqlDbType.Date:
  7753. // Nothing more to write!
  7754. break;
  7755. case SqlDbType.Time:
  7756. case SqlDbType.DateTime2:
  7757. case SqlDbType.DateTimeOffset:
  7758. stateObj.WriteByte(mdPriv.scale);
  7759. break;
  7760. default:
  7761. WriteTokenLength(mdPriv.tdsType, mdPriv.length, stateObj);
  7762. if (mdPriv.metaType.IsCharType && _isShiloh) {
  7763. WriteUnsignedInt(mdPriv.collation.info, stateObj);
  7764. stateObj.WriteByte(mdPriv.collation.sortId);
  7765. }
  7766. break;
  7767. }
  7768. }
  7769. /// <summary>
  7770. /// Writes the crypto metadata (as part of COLMETADATA token) for encrypted columns.
  7771. /// </summary>
  7772. /// <returns></returns>
  7773. internal void WriteCryptoMetadata(_SqlMetaData md, TdsParserStateObject stateObj) {
  7774. if (!_serverSupportsColumnEncryption || // TCE Feature supported
  7775. !md.isEncrypted || // Column is not encrypted
  7776. !ShouldEncryptValuesForBulkCopy()) { // TCE disabled on connection string
  7777. return;
  7778. }
  7779. // Write the ordinal
  7780. WriteShort (md.cipherMD.CekTableOrdinal, stateObj);
  7781. // Write UserType and TYPEINFO
  7782. WriteTceUserTypeAndTypeInfo(md.baseTI, stateObj);
  7783. // Write Encryption Algo
  7784. stateObj.WriteByte(md.cipherMD.CipherAlgorithmId);
  7785. if (TdsEnums.CustomCipherAlgorithmId == md.cipherMD.CipherAlgorithmId) {
  7786. // Write the algorithm name
  7787. Debug.Assert (md.cipherMD.CipherAlgorithmName.Length < 256);
  7788. stateObj.WriteByte((byte)md.cipherMD.CipherAlgorithmName.Length);
  7789. WriteString(md.cipherMD.CipherAlgorithmName, stateObj);
  7790. }
  7791. // Write Encryption Algo Type
  7792. stateObj.WriteByte(md.cipherMD.EncryptionType);
  7793. // Write Normalization Version
  7794. stateObj.WriteByte(md.cipherMD.NormalizationRuleVersion);
  7795. }
  7796. internal void WriteBulkCopyMetaData(_SqlMetaDataSet metadataCollection, int count, TdsParserStateObject stateObj) {
  7797. if (!(State == TdsParserState.OpenNotLoggedIn || State == TdsParserState.OpenLoggedIn)) {
  7798. throw ADP.ClosedConnectionError();
  7799. }
  7800. stateObj.WriteByte(TdsEnums.SQLCOLMETADATA);
  7801. WriteShort(count, stateObj);
  7802. // Write CEK table - 0 count
  7803. WriteCekTable(metadataCollection, stateObj);
  7804. for (int i = 0; i < metadataCollection.Length; i++) {
  7805. if (metadataCollection[i] != null) {
  7806. _SqlMetaData md = metadataCollection[i];
  7807. // read user type - 4 bytes Yukon, 2 backwards
  7808. if (IsYukonOrNewer) {
  7809. WriteInt(0x0, stateObj);
  7810. }
  7811. else {
  7812. WriteShort(0x0000, stateObj);
  7813. }
  7814. // Write the flags
  7815. UInt16 flags;
  7816. flags = (UInt16)(md.updatability << 2);
  7817. flags |= (UInt16)(md.isNullable ? (UInt16)TdsEnums.Nullable : (UInt16)0);
  7818. flags |= (UInt16)(md.isIdentity ? (UInt16)TdsEnums.Identity : (UInt16)0);
  7819. // Write the next byte of flags
  7820. if (_serverSupportsColumnEncryption) { // TCE Supported
  7821. if (ShouldEncryptValuesForBulkCopy()) { // TCE enabled on connection options
  7822. flags |= (UInt16)(md.isEncrypted ? (UInt16)(TdsEnums.IsEncrypted << 8) : (UInt16)0);
  7823. }
  7824. }
  7825. WriteShort(flags, stateObj);// write the flags
  7826. // todo:
  7827. // for xml WriteTokenLength results in a no-op
  7828. // discuss this with blaine ...
  7829. // ([....]) xml datatype does not have token length in its metadata. So it should be a noop.
  7830. switch (md.type) {
  7831. case SqlDbType.Decimal:
  7832. stateObj.WriteByte(md.tdsType);
  7833. WriteTokenLength(md.tdsType, md.length, stateObj);
  7834. stateObj.WriteByte(md.precision);
  7835. stateObj.WriteByte(md.scale);
  7836. break;
  7837. case SqlDbType.Xml:
  7838. //
  7839. stateObj.WriteByteArray(s_xmlMetadataSubstituteSequence, s_xmlMetadataSubstituteSequence.Length, 0);
  7840. break;
  7841. case SqlDbType.Udt:
  7842. stateObj.WriteByte(TdsEnums.SQLBIGVARBINARY);
  7843. WriteTokenLength(TdsEnums.SQLBIGVARBINARY, md.length, stateObj);
  7844. break;
  7845. case SqlDbType.Date:
  7846. stateObj.WriteByte(md.tdsType);
  7847. break;
  7848. case SqlDbType.Time:
  7849. case SqlDbType.DateTime2:
  7850. case SqlDbType.DateTimeOffset:
  7851. stateObj.WriteByte(md.tdsType);
  7852. stateObj.WriteByte(md.scale);
  7853. break;
  7854. default:
  7855. stateObj.WriteByte(md.tdsType);
  7856. WriteTokenLength(md.tdsType, md.length, stateObj);
  7857. if (md.metaType.IsCharType && _isShiloh) {
  7858. WriteUnsignedInt(md.collation.info, stateObj);
  7859. stateObj.WriteByte(md.collation.sortId);
  7860. }
  7861. break;
  7862. }
  7863. if (md.metaType.IsLong && !md.metaType.IsPlp) {
  7864. WriteShort(md.tableName.Length, stateObj);
  7865. WriteString(md.tableName, stateObj);
  7866. }
  7867. WriteCryptoMetadata(md, stateObj);
  7868. stateObj.WriteByte((byte)md.column.Length);
  7869. WriteString(md.column, stateObj);
  7870. }
  7871. } // end for loop
  7872. }
  7873. /// <summary>
  7874. /// Determines if a column value should be encrypted when using BulkCopy (based on connectionstring setting).
  7875. /// </summary>
  7876. /// <returns></returns>
  7877. internal bool ShouldEncryptValuesForBulkCopy () {
  7878. if (null != _connHandler &&
  7879. null != _connHandler.ConnectionOptions &&
  7880. SqlConnectionColumnEncryptionSetting.Enabled == _connHandler.ConnectionOptions.ColumnEncryptionSetting) {
  7881. return true;
  7882. }
  7883. return false;
  7884. }
  7885. /// <summary>
  7886. /// Encrypts a column value (for SqlBulkCopy)
  7887. /// </summary>
  7888. /// <returns></returns>
  7889. internal object EncryptColumnValue (object value, SqlMetaDataPriv metadata, string column, TdsParserStateObject stateObj, bool isDataFeed, bool isSqlType) {
  7890. Debug.Assert (_serverSupportsColumnEncryption, "Server doesn't support encryption, yet we received encryption metadata");
  7891. Debug.Assert (ShouldEncryptValuesForBulkCopy(), "Encryption attempted when not requested");
  7892. if (isDataFeed) { // can't encrypt a stream column
  7893. SQL.StreamNotSupportOnEncryptedColumn(column);
  7894. }
  7895. int actualLengthInBytes;
  7896. switch(metadata.baseTI.metaType.NullableType) {
  7897. case TdsEnums.SQLBIGBINARY:
  7898. case TdsEnums.SQLBIGVARBINARY:
  7899. case TdsEnums.SQLIMAGE:
  7900. // For some datatypes, engine does truncation before storing the value. (For example, when
  7901. // trying to insert a varbinary(7000) into a varbinary(3000) column). Since we encrypt the
  7902. // column values, engine has no way to tell the size of the plaintext datatype. Therefore,
  7903. // we truncate the values based on target column sizes here before encrypting them. This
  7904. // truncation is only needed if we exceed the max column length or if the target column is
  7905. // not a blob type (eg. varbinary(max)). The actual work of truncating the column happens
  7906. // when we normalize and serialize the data buffers. The serialization routine expects us
  7907. // to report the size of data to be copied out (for serialization). If we underreport the
  7908. // size, truncation will happen for us!
  7909. actualLengthInBytes = (isSqlType) ? ((SqlBinary)value).Length : ((byte[])value).Length;
  7910. if (metadata.baseTI.length > 0 &&
  7911. actualLengthInBytes > metadata.baseTI.length) { // see comments agove
  7912. actualLengthInBytes = metadata.baseTI.length;
  7913. }
  7914. break;
  7915. case TdsEnums.SQLUNIQUEID:
  7916. actualLengthInBytes = GUID_SIZE; // that's a constant for guid
  7917. break;
  7918. case TdsEnums.SQLBIGCHAR:
  7919. case TdsEnums.SQLBIGVARCHAR:
  7920. case TdsEnums.SQLTEXT:
  7921. if (null == _defaultEncoding)
  7922. {
  7923. ThrowUnsupportedCollationEncountered(null); // stateObject only when reading
  7924. }
  7925. string stringValue = (isSqlType) ? ((SqlString)value).Value : (string)value;
  7926. actualLengthInBytes = _defaultEncoding.GetByteCount(stringValue);
  7927. // If the string length is > max length, then use the max length (see comments above)
  7928. if (metadata.baseTI.length > 0 &&
  7929. actualLengthInBytes > metadata.baseTI.length) {
  7930. actualLengthInBytes = metadata.baseTI.length; // this ensure truncation!
  7931. }
  7932. break;
  7933. case TdsEnums.SQLNCHAR:
  7934. case TdsEnums.SQLNVARCHAR:
  7935. case TdsEnums.SQLNTEXT:
  7936. actualLengthInBytes = ((isSqlType) ? ((SqlString)value).Value.Length : ((string)value).Length) * 2;
  7937. if (metadata.baseTI.length > 0 &&
  7938. actualLengthInBytes > metadata.baseTI.length) { // see comments above
  7939. actualLengthInBytes = metadata.baseTI.length;
  7940. }
  7941. break;
  7942. default:
  7943. actualLengthInBytes = metadata.baseTI.length;
  7944. break;
  7945. }
  7946. byte[] serializedValue;
  7947. if (isSqlType) {
  7948. // SqlType
  7949. serializedValue = SerializeUnencryptedSqlValue (value,
  7950. metadata.baseTI.metaType,
  7951. actualLengthInBytes,
  7952. offset : 0,
  7953. normalizationVersion: metadata.cipherMD.NormalizationRuleVersion,
  7954. stateObj: stateObj);
  7955. }
  7956. else {
  7957. serializedValue = SerializeUnencryptedValue (value,
  7958. metadata.baseTI.metaType,
  7959. metadata.baseTI.scale,
  7960. actualLengthInBytes,
  7961. offset: 0,
  7962. isDataFeed: isDataFeed,
  7963. normalizationVersion: metadata.cipherMD.NormalizationRuleVersion,
  7964. stateObj: stateObj);
  7965. }
  7966. Debug.Assert(serializedValue != null, "serializedValue should not be null in TdsExecuteRPC.");
  7967. return SqlSecurityUtility.EncryptWithKey(
  7968. serializedValue,
  7969. metadata.cipherMD,
  7970. _connHandler.ConnectionOptions.DataSource);
  7971. }
  7972. internal Task WriteBulkCopyValue(object value, SqlMetaDataPriv metadata, TdsParserStateObject stateObj, bool isSqlType, bool isDataFeed, bool isNull) {
  7973. Debug.Assert(!isSqlType || value is INullable, "isSqlType is true, but value can not be type cast to an INullable");
  7974. Debug.Assert(!isDataFeed ^ value is DataFeed, "Incorrect value for isDataFeed");
  7975. Encoding saveEncoding = _defaultEncoding;
  7976. SqlCollation saveCollation = _defaultCollation;
  7977. int saveCodePage = _defaultCodePage;
  7978. int saveLCID = _defaultLCID;
  7979. Task resultTask = null;
  7980. Task internalWriteTask = null;
  7981. if (!(State == TdsParserState.OpenNotLoggedIn || State == TdsParserState.OpenLoggedIn)) {
  7982. throw ADP.ClosedConnectionError();
  7983. }
  7984. try {
  7985. if (metadata.encoding != null) {
  7986. _defaultEncoding = metadata.encoding;
  7987. }
  7988. if (metadata.collation != null) {
  7989. _defaultCollation = metadata.collation;
  7990. _defaultLCID = _defaultCollation.LCID;
  7991. }
  7992. _defaultCodePage = metadata.codePage;
  7993. MetaType metatype = metadata.metaType;
  7994. int ccb = 0;
  7995. int ccbStringBytes = 0;
  7996. if (isNull) {
  7997. // For UDT, remember we treat as binary even though it is a PLP
  7998. if (metatype.IsPlp && (metatype.NullableType != TdsEnums.SQLUDT || metatype.IsLong)) {
  7999. WriteLong(unchecked((long)TdsEnums.SQL_PLP_NULL), stateObj);
  8000. }
  8001. else if (!metatype.IsFixed && !metatype.IsLong && !metatype.IsVarTime) {
  8002. WriteShort(TdsEnums.VARNULL, stateObj);
  8003. }
  8004. else {
  8005. stateObj.WriteByte(TdsEnums.FIXEDNULL);
  8006. }
  8007. return resultTask;
  8008. }
  8009. if (!isDataFeed) {
  8010. switch (metatype.NullableType) {
  8011. case TdsEnums.SQLBIGBINARY:
  8012. case TdsEnums.SQLBIGVARBINARY:
  8013. case TdsEnums.SQLIMAGE:
  8014. case TdsEnums.SQLUDT:
  8015. ccb = (isSqlType) ? ((SqlBinary)value).Length : ((byte[])value).Length;
  8016. break;
  8017. case TdsEnums.SQLUNIQUEID:
  8018. ccb = GUID_SIZE; // that's a constant for guid
  8019. break;
  8020. case TdsEnums.SQLBIGCHAR:
  8021. case TdsEnums.SQLBIGVARCHAR:
  8022. case TdsEnums.SQLTEXT:
  8023. if (null == _defaultEncoding) {
  8024. ThrowUnsupportedCollationEncountered(null); // stateObject only when reading
  8025. }
  8026. string stringValue = null;
  8027. if (isSqlType) {
  8028. stringValue = ((SqlString)value).Value;
  8029. }
  8030. else {
  8031. stringValue = (string)value;
  8032. }
  8033. ccb = stringValue.Length;
  8034. ccbStringBytes = _defaultEncoding.GetByteCount(stringValue);
  8035. break;
  8036. case TdsEnums.SQLNCHAR:
  8037. case TdsEnums.SQLNVARCHAR:
  8038. case TdsEnums.SQLNTEXT:
  8039. ccb = ((isSqlType) ? ((SqlString)value).Value.Length : ((string)value).Length) * 2;
  8040. break;
  8041. case TdsEnums.SQLXMLTYPE:
  8042. // Value here could be string or XmlReader
  8043. if (value is XmlReader) {
  8044. value = MetaType.GetStringFromXml((XmlReader)value);
  8045. }
  8046. ccb = ((isSqlType) ? ((SqlString)value).Value.Length : ((string)value).Length) * 2;
  8047. break;
  8048. default:
  8049. ccb = metadata.length;
  8050. break;
  8051. }
  8052. }
  8053. else {
  8054. Debug.Assert(metatype.IsLong &&
  8055. ((metatype.SqlDbType == SqlDbType.VarBinary && value is StreamDataFeed) ||
  8056. ((metatype.SqlDbType == SqlDbType.VarChar || metatype.SqlDbType == SqlDbType.NVarChar) && value is TextDataFeed) ||
  8057. (metatype.SqlDbType == SqlDbType.Xml && value is XmlDataFeed)),
  8058. "Stream data feed should only be assigned to VarBinary(max), Text data feed should only be assigned to [N]VarChar(max), Xml data feed should only be assigned to XML(max)");
  8059. }
  8060. // Expected the text length in data stream for bulk copy of text, ntext, or image data.
  8061. //
  8062. if (metatype.IsLong) {
  8063. switch (metatype.SqlDbType) {
  8064. case SqlDbType.Text:
  8065. case SqlDbType.NText:
  8066. case SqlDbType.Image:
  8067. stateObj.WriteByteArray(s_longDataHeader, s_longDataHeader.Length, 0);
  8068. WriteTokenLength(metadata.tdsType, ccbStringBytes == 0 ? ccb : ccbStringBytes, stateObj);
  8069. break;
  8070. case SqlDbType.VarChar:
  8071. case SqlDbType.NVarChar:
  8072. case SqlDbType.VarBinary:
  8073. case SqlDbType.Xml:
  8074. case SqlDbType.Udt:
  8075. // plp data
  8076. WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, stateObj);
  8077. break;
  8078. }
  8079. }
  8080. else {
  8081. WriteTokenLength(metadata.tdsType, ccbStringBytes == 0 ? ccb : ccbStringBytes, stateObj);
  8082. }
  8083. if (isSqlType) {
  8084. internalWriteTask = WriteSqlValue(value, metatype, ccb, ccbStringBytes, 0, stateObj);
  8085. }
  8086. else if (metatype.SqlDbType != SqlDbType.Udt || metatype.IsLong) {
  8087. internalWriteTask = WriteValue(value, metatype, metadata.scale, ccb, ccbStringBytes, 0, stateObj, metadata.length, isDataFeed);
  8088. if ((internalWriteTask == null) && (_asyncWrite)) {
  8089. internalWriteTask = stateObj.WaitForAccumulatedWrites();
  8090. }
  8091. Debug.Assert(_asyncWrite || stateObj.WaitForAccumulatedWrites() == null, "Should not have accumulated writes when writing sync");
  8092. }
  8093. else {
  8094. WriteShort(ccb, stateObj);
  8095. internalWriteTask = stateObj.WriteByteArray((byte[])value, ccb, 0);
  8096. }
  8097. #if DEBUG
  8098. //In DEBUG mode, when SetAlwaysTaskOnWrite is true, we create a task. Allows us to verify async execution paths.
  8099. if (_asyncWrite && internalWriteTask == null && SqlBulkCopy.SetAlwaysTaskOnWrite == true) {
  8100. internalWriteTask = Task.FromResult<object>(null);
  8101. }
  8102. #endif
  8103. if (internalWriteTask != null) { //i.e. the write was async.
  8104. resultTask = WriteBulkCopyValueSetupContinuation(internalWriteTask, saveEncoding, saveCollation, saveCodePage, saveLCID);
  8105. }
  8106. }
  8107. finally {
  8108. if (internalWriteTask == null) {
  8109. _defaultEncoding = saveEncoding;
  8110. _defaultCollation = saveCollation;
  8111. _defaultCodePage = saveCodePage;
  8112. _defaultLCID = saveLCID;
  8113. }
  8114. }
  8115. return resultTask;
  8116. }
  8117. // This is in its own method to avoid always allocating the lambda in WriteBulkCopyValue
  8118. private Task WriteBulkCopyValueSetupContinuation(Task internalWriteTask, Encoding saveEncoding, SqlCollation saveCollation, int saveCodePage, int saveLCID) {
  8119. return internalWriteTask.ContinueWith<Task>(t => {
  8120. _defaultEncoding = saveEncoding;
  8121. _defaultCollation = saveCollation;
  8122. _defaultCodePage = saveCodePage;
  8123. _defaultLCID = saveLCID;
  8124. return t;
  8125. }, TaskScheduler.Default).Unwrap();
  8126. }
  8127. // Write mars header data, not including the mars header length
  8128. private void WriteMarsHeaderData(TdsParserStateObject stateObj, SqlInternalTransaction transaction) {
  8129. // Function to send over additional payload header data for Yukon and beyond only.
  8130. Debug.Assert(_isYukon, "WriteMarsHeaderData called on a non-Yukon server");
  8131. // These are not necessary - can have local started in distributed.
  8132. // Debug.Assert(!(null != sqlTransaction && null != distributedTransaction), "Error to have local (api started) and distributed transaction at the same time!");
  8133. // Debug.Assert(!(null != _userStartedLocalTransaction && null != distributedTransaction), "Error to have local (started outside of the api) and distributed transaction at the same time!");
  8134. // We may need to update the mars header length if mars header is changed in the future
  8135. WriteShort(TdsEnums.HEADERTYPE_MARS, stateObj);
  8136. if (null != transaction && SqlInternalTransaction.NullTransactionId != transaction.TransactionId) {
  8137. WriteLong(transaction.TransactionId, stateObj);
  8138. WriteInt(stateObj.IncrementAndObtainOpenResultCount(transaction), stateObj);
  8139. }
  8140. else {
  8141. // If no transaction, send over retained transaction descriptor (empty if none retained)
  8142. // and always 1 for result count.
  8143. WriteLong(_retainedTransactionId, stateObj);
  8144. WriteInt(stateObj.IncrementAndObtainOpenResultCount(null), stateObj);
  8145. }
  8146. }
  8147. private int GetNotificationHeaderSize(SqlNotificationRequest notificationRequest) {
  8148. if (null != notificationRequest) {
  8149. string callbackId = notificationRequest.UserData;
  8150. string service = notificationRequest.Options;
  8151. int timeout = notificationRequest.Timeout;
  8152. if (null == callbackId) {
  8153. throw ADP.ArgumentNull("CallbackId");
  8154. }
  8155. else if (UInt16.MaxValue < callbackId.Length) {
  8156. throw ADP.ArgumentOutOfRange("CallbackId");
  8157. }
  8158. if (null == service) {
  8159. throw ADP.ArgumentNull("Service");
  8160. }
  8161. else if (UInt16.MaxValue < service.Length) {
  8162. throw ADP.ArgumentOutOfRange("Service");
  8163. }
  8164. if (-1 > timeout) {
  8165. throw ADP.ArgumentOutOfRange("Timeout");
  8166. }
  8167. // Header Length (uint) (included in size) (already written to output buffer)
  8168. // Header Type (ushort)
  8169. // NotifyID Length (ushort)
  8170. // NotifyID UnicodeStream (unicode text)
  8171. // SSBDeployment Length (ushort)
  8172. // SSBDeployment UnicodeStream (unicode text)
  8173. // Timeout (uint) -- optional
  8174. // WEBDATA 102263: Don't send timeout value if it is 0
  8175. int headerLength = 4 + 2 + 2 + (callbackId.Length * 2) + 2 + (service.Length * 2);
  8176. if (timeout > 0)
  8177. headerLength += 4;
  8178. return headerLength;
  8179. }
  8180. else {
  8181. return 0;
  8182. }
  8183. }
  8184. // Write query notificaiton header data, not including the notificaiton header length
  8185. private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj) {
  8186. Debug.Assert(_isYukon, "WriteQueryNotificationHeaderData called on a non-Yukon server");
  8187. // We may need to update the notification header length if the header is changed in the future
  8188. Debug.Assert (null != notificationRequest, "notificaitonRequest is null");
  8189. string callbackId = notificationRequest.UserData;
  8190. string service = notificationRequest.Options;
  8191. int timeout = notificationRequest.Timeout;
  8192. // we did verification in GetNotificationHeaderSize, so just assert here.
  8193. Debug.Assert(null != callbackId, "CallbackId is null");
  8194. Debug.Assert(UInt16.MaxValue >= callbackId.Length, "CallbackId length is out of range");
  8195. Debug.Assert(null != service, "Service is null");
  8196. Debug.Assert(UInt16.MaxValue >= service.Length, "Service length is out of range");
  8197. Debug.Assert(-1 <= timeout, "Timeout");
  8198. Bid.NotificationsTrace("<sc.TdsParser.WriteQueryNotificationHeader|DEP> NotificationRequest: userData: '%ls', options: '%ls', timeout: '%d'\n", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout);
  8199. WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type
  8200. WriteShort(callbackId.Length * 2, stateObj); // Length in bytes
  8201. WriteString(callbackId, stateObj);
  8202. WriteShort(service.Length * 2, stateObj); // Length in bytes
  8203. WriteString(service, stateObj);
  8204. if (timeout > 0)
  8205. WriteInt(timeout, stateObj);
  8206. }
  8207. // Write the trace header data, not including the trace header length
  8208. private void WriteTraceHeaderData(TdsParserStateObject stateObj) {
  8209. Debug.Assert(this.IncludeTraceHeader, "WriteTraceHeaderData can only be called on a Denali or higher version server and bid trace with the control bit are on");
  8210. // We may need to update the trace header length if trace header is changed in the future
  8211. ActivityCorrelator.ActivityId actId = ActivityCorrelator.Current;
  8212. WriteShort(TdsEnums.HEADERTYPE_TRACE, stateObj); // Trace Header Type
  8213. stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid)
  8214. WriteUnsignedInt(actId.Sequence, stateObj); // sequence number
  8215. Bid.Trace("<sc.TdsParser.WriteTraceHeaderData|INFO> ActivityID %ls\n", actId.ToString());
  8216. }
  8217. private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest) {
  8218. Debug.Assert(_isYukon, "WriteRPCBatchHeaders can only be called on Yukon or higher version servers");
  8219. /* Header:
  8220. TotalLength - DWORD - including all headers and lengths, including itself
  8221. Each Data Session:
  8222. {
  8223. HeaderLength - DWORD - including all header length fields, including itself
  8224. HeaderType - USHORT
  8225. HeaderData
  8226. }
  8227. */
  8228. int notificationHeaderSize = GetNotificationHeaderSize(notificationRequest);
  8229. const int marsHeaderSize = 18; // 4 + 2 + 8 + 4
  8230. // Header Length (DWORD)
  8231. // Header Type (ushort)
  8232. // Trace Data Guid
  8233. // Trace Data Sequence Number (uint)
  8234. const int traceHeaderSize = 26; // 4 + 2 + GUID_SIZE + sizeof(UInt32);
  8235. // TotalLength - DWORD - including all headers and lengths, including itself
  8236. int totalHeaderLength = this.IncludeTraceHeader ? (4 + marsHeaderSize + notificationHeaderSize + traceHeaderSize) : (4 + marsHeaderSize + notificationHeaderSize);
  8237. Debug.Assert(stateObj._outBytesUsed == stateObj._outputHeaderLen, "Output bytes written before total header length");
  8238. // Write total header length
  8239. WriteInt(totalHeaderLength, stateObj);
  8240. // Write Mars header length
  8241. WriteInt(marsHeaderSize, stateObj);
  8242. // Write Mars header data
  8243. WriteMarsHeaderData(stateObj, CurrentTransaction);
  8244. if (0 != notificationHeaderSize) {
  8245. // Write Notification header length
  8246. WriteInt(notificationHeaderSize, stateObj);
  8247. // Write notificaiton header data
  8248. WriteQueryNotificationHeaderData(notificationRequest, stateObj);
  8249. }
  8250. if (IncludeTraceHeader) {
  8251. // Write trace header length
  8252. WriteInt(traceHeaderSize, stateObj);
  8253. // Write trace header data
  8254. WriteTraceHeaderData(stateObj);
  8255. }
  8256. }
  8257. //
  8258. // Reverse function of GetTokenLength
  8259. //
  8260. private void WriteTokenLength(byte token, int length, TdsParserStateObject stateObj) {
  8261. int tokenLength = 0;
  8262. Debug.Assert(token != 0, "0 length token!");
  8263. // For Plp fields, this should only be used when writing to metadata header.
  8264. // For actual data length, WriteDataLength should be used.
  8265. // For Xml fields, there is no token length field. For MAX fields it is 0xffff.
  8266. if (_isYukon) { // Handle Yukon specific exceptions
  8267. if (TdsEnums.SQLUDT == token) {
  8268. tokenLength = 8;
  8269. }
  8270. else if (token == TdsEnums.SQLXMLTYPE) {
  8271. tokenLength = 8;
  8272. }
  8273. }
  8274. if (tokenLength == 0) {
  8275. switch (token & TdsEnums.SQLLenMask) {
  8276. case TdsEnums.SQLFixedLen:
  8277. Debug.Assert(length == 0x01 << ((token & 0x0c) >> 2), "length does not match encoded length in token");
  8278. tokenLength = 0;
  8279. break;
  8280. case TdsEnums.SQLZeroLen:
  8281. tokenLength = 0;
  8282. break;
  8283. case TdsEnums.SQLVarLen:
  8284. case TdsEnums.SQLVarCnt:
  8285. if (0 != (token & 0x80))
  8286. tokenLength = 2;
  8287. else if (0 == (token & 0x0c))
  8288. //
  8289. tokenLength = 4;
  8290. else
  8291. tokenLength = 1;
  8292. break;
  8293. default:
  8294. Debug.Assert(false, "Unknown token length!");
  8295. break;
  8296. }
  8297. switch (tokenLength) {
  8298. case 1:
  8299. stateObj.WriteByte((byte)length);
  8300. break;
  8301. case 2:
  8302. WriteShort(length, stateObj);
  8303. break;
  8304. case 4:
  8305. WriteInt(length, stateObj);
  8306. break;
  8307. case 8:
  8308. // In the metadata case we write 0xffff for partial length prefixed types.
  8309. // For actual data length preceding data, WriteDataLength should be used.
  8310. WriteShort(TdsEnums.SQL_USHORTVARMAXLEN, stateObj);
  8311. break;
  8312. } // end switch
  8313. }
  8314. }
  8315. // Returns true if BOM byte mark is needed for an XML value
  8316. private bool IsBOMNeeded(MetaType type, object value) {
  8317. if (type.NullableType == TdsEnums.SQLXMLTYPE) {
  8318. Type currentType = value.GetType();
  8319. if(currentType == typeof(SqlString)) {
  8320. if (!((SqlString)value).IsNull && ((((SqlString)value).Value).Length > 0)) {
  8321. if ((((SqlString)value).Value[0] & 0xff) != 0xff)
  8322. return true;
  8323. }
  8324. }
  8325. else if ((currentType == typeof(String)) && (((String)value).Length > 0)) {
  8326. if ((value != null) && (((String)value)[0] & 0xff) != 0xff)
  8327. return true;
  8328. }
  8329. else if (currentType == typeof(SqlXml)) {
  8330. if (!((SqlXml)value).IsNull)
  8331. return true;
  8332. }
  8333. else if (currentType == typeof(XmlDataFeed)) {
  8334. return true; // Values will eventually converted to unicode string here
  8335. }
  8336. }
  8337. return false;
  8338. }
  8339. private Task GetTerminationTask(Task unterminatedWriteTask, object value, MetaType type, int actualLength, TdsParserStateObject stateObj, bool isDataFeed) {
  8340. if (type.IsPlp && ((actualLength > 0) || isDataFeed)) {
  8341. if (unterminatedWriteTask == null) {
  8342. WriteInt(0, stateObj);
  8343. return null;
  8344. }
  8345. else {
  8346. return AsyncHelper.CreateContinuationTask<int, TdsParserStateObject>(unterminatedWriteTask,
  8347. WriteInt, 0, stateObj,
  8348. connectionToDoom: _connHandler);
  8349. }
  8350. }
  8351. else {
  8352. return unterminatedWriteTask;
  8353. }
  8354. }
  8355. private Task WriteSqlValue(object value, MetaType type, int actualLength, int codePageByteSize, int offset, TdsParserStateObject stateObj) {
  8356. return GetTerminationTask(
  8357. WriteUnterminatedSqlValue(value, type, actualLength, codePageByteSize, offset, stateObj),
  8358. value, type, actualLength, stateObj, false);
  8359. }
  8360. // For MAX types, this method can only write everything in one big chunk. If multiple
  8361. // chunk writes needed, please use WritePlpBytes/WritePlpChars
  8362. private Task WriteUnterminatedSqlValue(object value, MetaType type, int actualLength, int codePageByteSize, int offset, TdsParserStateObject stateObj) {
  8363. Debug.Assert(((type.NullableType == TdsEnums.SQLXMLTYPE) ||
  8364. (value is INullable && !((INullable)value).IsNull)),
  8365. "unexpected null SqlType!");
  8366. // parameters are always sent over as BIG or N types
  8367. switch (type.NullableType) {
  8368. case TdsEnums.SQLFLTN:
  8369. if (type.FixedLength == 4)
  8370. WriteFloat(((SqlSingle)value).Value, stateObj);
  8371. else {
  8372. Debug.Assert(type.FixedLength == 8, "Invalid length for SqlDouble type!");
  8373. WriteDouble(((SqlDouble)value).Value, stateObj);
  8374. }
  8375. break;
  8376. case TdsEnums.SQLBIGBINARY:
  8377. case TdsEnums.SQLBIGVARBINARY:
  8378. case TdsEnums.SQLIMAGE:
  8379. {
  8380. if (type.IsPlp) {
  8381. WriteInt(actualLength, stateObj); // chunk length
  8382. }
  8383. if (value is SqlBinary) {
  8384. return stateObj.WriteByteArray(((SqlBinary)value).Value, actualLength, offset, canAccumulate:false);
  8385. }
  8386. else {
  8387. Debug.Assert(value is SqlBytes);
  8388. return stateObj.WriteByteArray(((SqlBytes)value).Value, actualLength, offset, canAccumulate:false);
  8389. }
  8390. }
  8391. case TdsEnums.SQLUNIQUEID:
  8392. {
  8393. byte[] b = ((SqlGuid)value).ToByteArray();
  8394. Debug.Assert((actualLength == b.Length) && (actualLength == 16), "Invalid length for guid type in com+ object");
  8395. stateObj.WriteByteArray(b, actualLength, 0);
  8396. break;
  8397. }
  8398. case TdsEnums.SQLBITN:
  8399. {
  8400. Debug.Assert(type.FixedLength == 1, "Invalid length for SqlBoolean type");
  8401. if (((SqlBoolean)value).Value == true)
  8402. stateObj.WriteByte(1);
  8403. else
  8404. stateObj.WriteByte(0);
  8405. break;
  8406. }
  8407. case TdsEnums.SQLINTN:
  8408. if (type.FixedLength == 1)
  8409. stateObj.WriteByte(((SqlByte)value).Value);
  8410. else
  8411. if (type.FixedLength == 2)
  8412. WriteShort(((SqlInt16)value).Value, stateObj);
  8413. else
  8414. if (type.FixedLength == 4)
  8415. WriteInt(((SqlInt32)value).Value, stateObj);
  8416. else {
  8417. Debug.Assert(type.FixedLength == 8, "invalid length for SqlIntN type: " + type.FixedLength.ToString(CultureInfo.InvariantCulture));
  8418. WriteLong(((SqlInt64)value).Value, stateObj);
  8419. }
  8420. break;
  8421. case TdsEnums.SQLBIGCHAR:
  8422. case TdsEnums.SQLBIGVARCHAR:
  8423. case TdsEnums.SQLTEXT:
  8424. if (type.IsPlp) {
  8425. WriteInt(codePageByteSize, stateObj); // chunk length
  8426. }
  8427. if (value is SqlChars) {
  8428. String sch = new String(((SqlChars)value).Value);
  8429. return WriteEncodingChar(sch, actualLength, offset, _defaultEncoding, stateObj, canAccumulate:false);
  8430. }
  8431. else {
  8432. Debug.Assert(value is SqlString);
  8433. return WriteEncodingChar(((SqlString)value).Value, actualLength, offset, _defaultEncoding, stateObj, canAccumulate:false);
  8434. }
  8435. case TdsEnums.SQLNCHAR:
  8436. case TdsEnums.SQLNVARCHAR:
  8437. case TdsEnums.SQLNTEXT:
  8438. case TdsEnums.SQLXMLTYPE:
  8439. if (type.IsPlp) {
  8440. if(IsBOMNeeded(type, value)) {
  8441. WriteInt(actualLength+2, stateObj); // chunk length
  8442. WriteShort(TdsEnums.XMLUNICODEBOM , stateObj);
  8443. } else {
  8444. WriteInt(actualLength, stateObj); // chunk length
  8445. }
  8446. }
  8447. // convert to cchars instead of cbytes
  8448. // Xml type is already converted to string through GetCoercedValue
  8449. if (actualLength != 0)
  8450. actualLength >>= 1;
  8451. if (value is SqlChars) {
  8452. return WriteCharArray(((SqlChars)value).Value, actualLength, offset, stateObj, canAccumulate:false);
  8453. }
  8454. else {
  8455. Debug.Assert(value is SqlString);
  8456. return WriteString(((SqlString)value).Value, actualLength, offset, stateObj, canAccumulate:false);
  8457. }
  8458. case TdsEnums.SQLNUMERICN:
  8459. Debug.Assert(type.FixedLength <= 17, "Decimal length cannot be greater than 17 bytes");
  8460. WriteSqlDecimal((SqlDecimal)value, stateObj);
  8461. break;
  8462. case TdsEnums.SQLDATETIMN:
  8463. SqlDateTime dt = (SqlDateTime)value;
  8464. if (type.FixedLength == 4) {
  8465. if (0 > dt.DayTicks || dt.DayTicks > UInt16.MaxValue)
  8466. throw SQL.SmallDateTimeOverflow(dt.ToString());
  8467. WriteShort(dt.DayTicks, stateObj);
  8468. WriteShort(dt.TimeTicks / SqlDateTime.SQLTicksPerMinute, stateObj);
  8469. }
  8470. else {
  8471. WriteInt(dt.DayTicks, stateObj);
  8472. WriteInt(dt.TimeTicks, stateObj);
  8473. }
  8474. break;
  8475. case TdsEnums.SQLMONEYN:
  8476. {
  8477. WriteSqlMoney((SqlMoney)value, type.FixedLength, stateObj);
  8478. break;
  8479. }
  8480. case TdsEnums.SQLUDT:
  8481. Debug.Assert(false, "Called WriteSqlValue on UDT param.Should have already been handled");
  8482. throw SQL.UDTUnexpectedResult(value.GetType().AssemblyQualifiedName);
  8483. default:
  8484. Debug.Assert(false, "Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
  8485. break;
  8486. } // switch
  8487. // return point for accumualated writes, note: non-accumulated writes returned from their case statements
  8488. return null;
  8489. }
  8490. private class TdsOutputStream : Stream {
  8491. TdsParser _parser;
  8492. TdsParserStateObject _stateObj;
  8493. byte[] _preambleToStrip;
  8494. public TdsOutputStream(TdsParser parser, TdsParserStateObject stateObj, byte[] preambleToStrip) {
  8495. _parser = parser;
  8496. _stateObj = stateObj;
  8497. _preambleToStrip = preambleToStrip;
  8498. }
  8499. public override bool CanRead {
  8500. get { return false; }
  8501. }
  8502. public override bool CanSeek {
  8503. get { return false; }
  8504. }
  8505. public override bool CanWrite {
  8506. get { return true; }
  8507. }
  8508. public override void Flush() {
  8509. // NOOP
  8510. }
  8511. public override long Length {
  8512. get { throw new NotSupportedException(); }
  8513. }
  8514. public override long Position {
  8515. get {
  8516. throw new NotSupportedException();
  8517. }
  8518. set {
  8519. throw new NotSupportedException();
  8520. }
  8521. }
  8522. public override int Read(byte[] buffer, int offset, int count) {
  8523. throw new NotSupportedException();
  8524. }
  8525. public override long Seek(long offset, SeekOrigin origin) {
  8526. throw new NotSupportedException();
  8527. }
  8528. public override void SetLength(long value) {
  8529. throw new NotSupportedException();
  8530. }
  8531. private void StripPreamble(byte[] buffer, ref int offset, ref int count) {
  8532. if (_preambleToStrip != null && count >= _preambleToStrip.Length) {
  8533. for (int idx = 0; idx < _preambleToStrip.Length; idx++) {
  8534. if (_preambleToStrip[idx] != buffer[idx]) {
  8535. _preambleToStrip = null;
  8536. return;
  8537. }
  8538. }
  8539. offset += _preambleToStrip.Length;
  8540. count -= _preambleToStrip.Length;
  8541. }
  8542. _preambleToStrip = null;
  8543. }
  8544. public override void Write(byte[] buffer, int offset, int count) {
  8545. Debug.Assert(!_parser._asyncWrite);
  8546. ValidateWriteParameters(buffer, offset, count);
  8547. StripPreamble(buffer, ref offset, ref count);
  8548. if (count > 0) {
  8549. _parser.WriteInt(count, _stateObj); // write length of chunk
  8550. _stateObj.WriteByteArray(buffer, count, offset);
  8551. }
  8552. }
  8553. public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) {
  8554. Debug.Assert(_parser._asyncWrite);
  8555. ValidateWriteParameters(buffer, offset, count);
  8556. StripPreamble(buffer, ref offset, ref count);
  8557. RuntimeHelpers.PrepareConstrainedRegions();
  8558. try {
  8559. #if DEBUG
  8560. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  8561. RuntimeHelpers.PrepareConstrainedRegions();
  8562. try {
  8563. tdsReliabilitySection.Start();
  8564. #else
  8565. {
  8566. #endif //DEBUG
  8567. Task task = null;
  8568. if (count > 0) {
  8569. _parser.WriteInt(count, _stateObj); // write length of chunk
  8570. task = _stateObj.WriteByteArray(buffer, count, offset, canAccumulate: false);
  8571. }
  8572. if (task == null) {
  8573. return CompletedTask;
  8574. }
  8575. else {
  8576. return task;
  8577. }
  8578. }
  8579. #if DEBUG
  8580. finally {
  8581. tdsReliabilitySection.Stop();
  8582. }
  8583. #endif //DEBUG
  8584. }
  8585. catch (System.OutOfMemoryException) {
  8586. _parser._connHandler.DoomThisConnection();
  8587. throw;
  8588. }
  8589. catch (System.StackOverflowException) {
  8590. _parser._connHandler.DoomThisConnection();
  8591. throw;
  8592. }
  8593. catch (System.Threading.ThreadAbortException) {
  8594. _parser._connHandler.DoomThisConnection();
  8595. throw;
  8596. }
  8597. }
  8598. internal static void ValidateWriteParameters(byte[] buffer, int offset, int count) {
  8599. if (buffer == null) {
  8600. throw ADP.ArgumentNull(ADP.ParameterBuffer);
  8601. }
  8602. if (offset < 0) {
  8603. throw ADP.ArgumentOutOfRange(ADP.ParameterOffset);
  8604. }
  8605. if (count < 0) {
  8606. throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
  8607. }
  8608. try {
  8609. if (checked(offset + count) > buffer.Length) {
  8610. throw ExceptionBuilder.InvalidOffsetLength();
  8611. }
  8612. }
  8613. catch (OverflowException) {
  8614. // If we've overflowed when adding offset and count, then they never would have fit into buffer anyway
  8615. throw ExceptionBuilder.InvalidOffsetLength();
  8616. }
  8617. }
  8618. }
  8619. private class ConstrainedTextWriter : TextWriter {
  8620. TextWriter _next;
  8621. int _size;
  8622. int _written;
  8623. public ConstrainedTextWriter(TextWriter next, int size) {
  8624. _next = next;
  8625. _size = size;
  8626. _written = 0;
  8627. if (_size < 1) {
  8628. _size = int.MaxValue;
  8629. }
  8630. }
  8631. public bool IsComplete {
  8632. get {
  8633. return _size > 0 && _written >= _size;
  8634. }
  8635. }
  8636. public override Encoding Encoding {
  8637. get { return _next.Encoding; }
  8638. }
  8639. public override void Flush() {
  8640. _next.Flush();
  8641. }
  8642. public override Task FlushAsync() {
  8643. return _next.FlushAsync();
  8644. }
  8645. public override void Write(char value) {
  8646. if (_written < _size) {
  8647. _next.Write(value);
  8648. _written++;
  8649. }
  8650. Debug.Assert(_size < 0 || _written <= _size, string.Format("Length of data written exceeds specified length. Written: {0}, specified: {1}", _written, _size));
  8651. }
  8652. public override void Write(char[] buffer, int index, int count) {
  8653. ValidateWriteParameters(buffer, index, count);
  8654. Debug.Assert(_size >= _written);
  8655. count = Math.Min(_size - _written, count);
  8656. if (count > 0) {
  8657. _next.Write(buffer, index, count);
  8658. }
  8659. _written += count;
  8660. }
  8661. public override Task WriteAsync(char value) {
  8662. if (_written < _size) {
  8663. _written++;
  8664. return _next.WriteAsync(value);
  8665. }
  8666. return CompletedTask;
  8667. }
  8668. public override Task WriteAsync(char[] buffer, int index, int count) {
  8669. ValidateWriteParameters(buffer, index, count);
  8670. Debug.Assert(_size >= _written);
  8671. count = Math.Min(_size - _written, count);
  8672. if (count > 0) {
  8673. _written += count;
  8674. return _next.WriteAsync(buffer, index, count);
  8675. }
  8676. return CompletedTask;
  8677. }
  8678. public override Task WriteAsync(string value) {
  8679. return WriteAsync(value.ToCharArray());
  8680. }
  8681. internal static void ValidateWriteParameters(char[] buffer, int offset, int count) {
  8682. if (buffer == null) {
  8683. throw ADP.ArgumentNull(ADP.ParameterBuffer);
  8684. }
  8685. if (offset < 0) {
  8686. throw ADP.ArgumentOutOfRange(ADP.ParameterOffset);
  8687. }
  8688. if (count < 0) {
  8689. throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
  8690. }
  8691. try {
  8692. if (checked(offset + count) > buffer.Length) {
  8693. throw ExceptionBuilder.InvalidOffsetLength();
  8694. }
  8695. }
  8696. catch (OverflowException) {
  8697. // If we've overflowed when adding offset and count, then they never would have fit into buffer anyway
  8698. throw ExceptionBuilder.InvalidOffsetLength();
  8699. }
  8700. }
  8701. }
  8702. private async Task WriteXmlFeed(XmlDataFeed feed, TdsParserStateObject stateObj, bool needBom, Encoding encoding, int size) {
  8703. byte[] preambleToSkip = null;
  8704. if (!needBom) {
  8705. preambleToSkip = encoding.GetPreamble();
  8706. }
  8707. ConstrainedTextWriter writer = new ConstrainedTextWriter(new StreamWriter(new TdsOutputStream(this, stateObj, preambleToSkip), encoding), size);
  8708. XmlWriterSettings writerSettings = new XmlWriterSettings();
  8709. writerSettings.CloseOutput = false; // don't close the memory stream
  8710. writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
  8711. if (_asyncWrite) {
  8712. writerSettings.Async = true;
  8713. }
  8714. XmlWriter ww = XmlWriter.Create(writer, writerSettings);
  8715. if (feed._source.ReadState == ReadState.Initial) {
  8716. feed._source.Read();
  8717. }
  8718. while (!feed._source.EOF && !writer.IsComplete) {
  8719. // We are copying nodes from a reader to a writer. This will cause the
  8720. // XmlDeclaration to be emitted despite ConformanceLevel.Fragment above.
  8721. // Therefore, we filter out the XmlDeclaration while copying.
  8722. if (feed._source.NodeType == XmlNodeType.XmlDeclaration) {
  8723. feed._source.Read();
  8724. continue;
  8725. }
  8726. if (_asyncWrite) {
  8727. await ww.WriteNodeAsync(feed._source, true).ConfigureAwait(false);
  8728. }
  8729. else {
  8730. ww.WriteNode(feed._source, true);
  8731. }
  8732. }
  8733. if (_asyncWrite) {
  8734. await ww.FlushAsync().ConfigureAwait(false);
  8735. }
  8736. else {
  8737. ww.Flush();
  8738. }
  8739. }
  8740. private async Task WriteTextFeed(TextDataFeed feed, Encoding encoding, bool needBom, TdsParserStateObject stateObj, int size) {
  8741. Debug.Assert(encoding == null || !needBom);
  8742. char[] inBuff = new char[constTextBufferSize];
  8743. encoding = encoding ?? new UnicodeEncoding(false, false);
  8744. ConstrainedTextWriter writer = new ConstrainedTextWriter(new StreamWriter(new TdsOutputStream(this, stateObj, null), encoding), size);
  8745. if (needBom) {
  8746. if (_asyncWrite) {
  8747. await writer.WriteAsync((char)TdsEnums.XMLUNICODEBOM).ConfigureAwait(false);
  8748. }
  8749. else {
  8750. writer.Write((char)TdsEnums.XMLUNICODEBOM);
  8751. }
  8752. }
  8753. int nWritten = 0;
  8754. do {
  8755. int nRead = 0;
  8756. if (_asyncWrite) {
  8757. nRead = await feed._source.ReadBlockAsync(inBuff, 0, constTextBufferSize).ConfigureAwait(false);
  8758. }
  8759. else {
  8760. nRead = feed._source.ReadBlock(inBuff, 0, constTextBufferSize);
  8761. }
  8762. if (nRead == 0) {
  8763. break;
  8764. }
  8765. if (_asyncWrite) {
  8766. await writer.WriteAsync(inBuff, 0, nRead).ConfigureAwait(false);
  8767. }
  8768. else {
  8769. writer.Write(inBuff, 0, nRead);
  8770. }
  8771. nWritten += nRead;
  8772. } while (!writer.IsComplete);
  8773. if (_asyncWrite) {
  8774. await writer.FlushAsync().ConfigureAwait(false);
  8775. }
  8776. else {
  8777. writer.Flush();
  8778. }
  8779. }
  8780. private async Task WriteStreamFeed(StreamDataFeed feed, TdsParserStateObject stateObj, int len) {
  8781. TdsOutputStream output = new TdsOutputStream(this, stateObj, null);
  8782. byte[] buff = new byte[constBinBufferSize];
  8783. int nWritten = 0;
  8784. do {
  8785. int nRead = 0;
  8786. int readSize = constBinBufferSize;
  8787. if (len > 0 && nWritten + readSize > len) {
  8788. readSize = len - nWritten;
  8789. }
  8790. Debug.Assert(readSize >= 0);
  8791. if (_asyncWrite) {
  8792. nRead = await feed._source.ReadAsync(buff, 0, readSize).ConfigureAwait(false);
  8793. }
  8794. else {
  8795. nRead = feed._source.Read(buff, 0, readSize);
  8796. }
  8797. if (nRead == 0) {
  8798. return;
  8799. }
  8800. if (_asyncWrite) {
  8801. await output.WriteAsync(buff, 0, nRead).ConfigureAwait(false);
  8802. }
  8803. else {
  8804. output.Write(buff, 0, nRead);
  8805. }
  8806. nWritten += nRead;
  8807. } while (len <= 0 || nWritten < len);
  8808. }
  8809. private Task NullIfCompletedWriteTask(Task task) {
  8810. if (task == null) {
  8811. return null;
  8812. }
  8813. switch (task.Status) {
  8814. case TaskStatus.RanToCompletion:
  8815. return null;
  8816. case TaskStatus.Faulted:
  8817. throw task.Exception.InnerException;
  8818. case TaskStatus.Canceled:
  8819. throw SQL.OperationCancelled();
  8820. default:
  8821. return task;
  8822. }
  8823. }
  8824. private Task WriteValue(object value, MetaType type, byte scale, int actualLength, int encodingByteSize, int offset, TdsParserStateObject stateObj, int paramSize, bool isDataFeed) {
  8825. return GetTerminationTask(WriteUnterminatedValue(value, type, scale, actualLength, encodingByteSize, offset, stateObj, paramSize, isDataFeed),
  8826. value, type, actualLength, stateObj, isDataFeed);
  8827. }
  8828. // For MAX types, this method can only write everything in one big chunk. If multiple
  8829. // chunk writes needed, please use WritePlpBytes/WritePlpChars
  8830. private Task WriteUnterminatedValue(object value, MetaType type, byte scale, int actualLength, int encodingByteSize, int offset, TdsParserStateObject stateObj, int paramSize, bool isDataFeed)
  8831. {
  8832. Debug.Assert((null != value) && (DBNull.Value != value), "unexpected missing or empty object");
  8833. // parameters are always sent over as BIG or N types
  8834. switch (type.NullableType) {
  8835. case TdsEnums.SQLFLTN:
  8836. if (type.FixedLength == 4)
  8837. WriteFloat((Single)value, stateObj);
  8838. else {
  8839. Debug.Assert(type.FixedLength == 8, "Invalid length for SqlDouble type!");
  8840. WriteDouble((Double)value, stateObj);
  8841. }
  8842. break;
  8843. case TdsEnums.SQLBIGBINARY:
  8844. case TdsEnums.SQLBIGVARBINARY:
  8845. case TdsEnums.SQLIMAGE:
  8846. case TdsEnums.SQLUDT: {
  8847. // An array should be in the object
  8848. Debug.Assert(isDataFeed || value is byte[], "Value should be an array of bytes");
  8849. Debug.Assert(!isDataFeed || value is StreamDataFeed, "Value should be a stream");
  8850. if (isDataFeed) {
  8851. Debug.Assert(type.IsPlp,"Stream assigned to non-PLP was not converted!");
  8852. return NullIfCompletedWriteTask(WriteStreamFeed((StreamDataFeed)value, stateObj, paramSize));
  8853. }
  8854. else {
  8855. if (type.IsPlp) {
  8856. WriteInt(actualLength, stateObj); // chunk length
  8857. }
  8858. return stateObj.WriteByteArray((byte[])value, actualLength, offset, canAccumulate: false);
  8859. }
  8860. }
  8861. case TdsEnums.SQLUNIQUEID: {
  8862. System.Guid guid = (System.Guid)value;
  8863. byte[] b = guid.ToByteArray();
  8864. Debug.Assert((actualLength == b.Length) && (actualLength == 16), "Invalid length for guid type in com+ object");
  8865. stateObj.WriteByteArray(b, actualLength, 0);
  8866. break;
  8867. }
  8868. case TdsEnums.SQLBITN: {
  8869. Debug.Assert(type.FixedLength == 1, "Invalid length for SqlBoolean type");
  8870. if ((bool)value == true)
  8871. stateObj.WriteByte(1);
  8872. else
  8873. stateObj.WriteByte(0);
  8874. break;
  8875. }
  8876. case TdsEnums.SQLINTN:
  8877. if (type.FixedLength == 1)
  8878. stateObj.WriteByte((byte)value);
  8879. else if (type.FixedLength == 2)
  8880. WriteShort((Int16)value, stateObj);
  8881. else if (type.FixedLength == 4)
  8882. WriteInt((Int32)value, stateObj);
  8883. else {
  8884. Debug.Assert(type.FixedLength == 8, "invalid length for SqlIntN type: " + type.FixedLength.ToString(CultureInfo.InvariantCulture));
  8885. WriteLong((Int64)value, stateObj);
  8886. }
  8887. break;
  8888. case TdsEnums.SQLBIGCHAR:
  8889. case TdsEnums.SQLBIGVARCHAR:
  8890. case TdsEnums.SQLTEXT: {
  8891. Debug.Assert(!isDataFeed || (value is TextDataFeed || value is XmlDataFeed), "Value must be a TextReader or XmlReader");
  8892. Debug.Assert(isDataFeed || (value is string || value is byte[]), "Value is a byte array or string");
  8893. if (isDataFeed) {
  8894. Debug.Assert(type.IsPlp, "Stream assigned to non-PLP was not converted!");
  8895. TextDataFeed tdf = value as TextDataFeed;
  8896. if (tdf == null) {
  8897. return NullIfCompletedWriteTask(WriteXmlFeed((XmlDataFeed)value, stateObj, needBom:true, encoding:_defaultEncoding, size:paramSize));
  8898. }
  8899. else {
  8900. return NullIfCompletedWriteTask(WriteTextFeed(tdf, _defaultEncoding, false, stateObj, paramSize));
  8901. }
  8902. }
  8903. else {
  8904. if (type.IsPlp) {
  8905. WriteInt(encodingByteSize, stateObj); // chunk length
  8906. }
  8907. if (value is byte[]) { // If LazyMat non-filled blob, send cookie rather than value
  8908. return stateObj.WriteByteArray((byte[])value, actualLength, 0, canAccumulate: false);
  8909. }
  8910. else {
  8911. return WriteEncodingChar((string)value, actualLength, offset, _defaultEncoding, stateObj, canAccumulate: false);
  8912. }
  8913. }
  8914. }
  8915. case TdsEnums.SQLNCHAR:
  8916. case TdsEnums.SQLNVARCHAR:
  8917. case TdsEnums.SQLNTEXT:
  8918. case TdsEnums.SQLXMLTYPE: {
  8919. Debug.Assert(!isDataFeed || (value is TextDataFeed || value is XmlDataFeed), "Value must be a TextReader or XmlReader");
  8920. Debug.Assert(isDataFeed || (value is string || value is byte[]), "Value is a byte array or string");
  8921. if (isDataFeed) {
  8922. Debug.Assert(type.IsPlp, "Stream assigned to non-PLP was not converted!");
  8923. TextDataFeed tdf = value as TextDataFeed;
  8924. if (tdf == null) {
  8925. return NullIfCompletedWriteTask(WriteXmlFeed((XmlDataFeed)value, stateObj, IsBOMNeeded(type, value), Encoding.Unicode, paramSize));
  8926. }
  8927. else {
  8928. return NullIfCompletedWriteTask(WriteTextFeed(tdf, null, IsBOMNeeded(type, value), stateObj, paramSize));
  8929. }
  8930. }
  8931. else {
  8932. if (type.IsPlp) {
  8933. if (IsBOMNeeded(type, value)) {
  8934. WriteInt(actualLength + 2, stateObj); // chunk length
  8935. WriteShort(TdsEnums.XMLUNICODEBOM, stateObj);
  8936. }
  8937. else {
  8938. WriteInt(actualLength, stateObj); // chunk length
  8939. }
  8940. }
  8941. if (value is byte[]) { // If LazyMat non-filled blob, send cookie rather than value
  8942. return stateObj.WriteByteArray((byte[])value, actualLength, 0, canAccumulate: false);
  8943. }
  8944. else {
  8945. // convert to cchars instead of cbytes
  8946. actualLength >>= 1;
  8947. return WriteString((string)value, actualLength, offset, stateObj, canAccumulate: false);
  8948. }
  8949. }
  8950. }
  8951. case TdsEnums.SQLNUMERICN:
  8952. Debug.Assert(type.FixedLength <= 17, "Decimal length cannot be greater than 17 bytes");
  8953. WriteDecimal((Decimal)value, stateObj);
  8954. break;
  8955. case TdsEnums.SQLDATETIMN:
  8956. Debug.Assert(type.FixedLength <= 0xff, "Invalid Fixed Length");
  8957. TdsDateTime dt = MetaType.FromDateTime((DateTime)value, (byte)type.FixedLength);
  8958. if (type.FixedLength == 4) {
  8959. if (0 > dt.days || dt.days > UInt16.MaxValue)
  8960. throw SQL.SmallDateTimeOverflow(MetaType.ToDateTime(dt.days, dt.time, 4).ToString(CultureInfo.InvariantCulture));
  8961. WriteShort(dt.days, stateObj);
  8962. WriteShort(dt.time, stateObj);
  8963. }
  8964. else {
  8965. WriteInt(dt.days, stateObj);
  8966. WriteInt(dt.time, stateObj);
  8967. }
  8968. break;
  8969. case TdsEnums.SQLMONEYN: {
  8970. WriteCurrency((Decimal)value, type.FixedLength, stateObj);
  8971. break;
  8972. }
  8973. case TdsEnums.SQLDATE: {
  8974. WriteDate((DateTime)value, stateObj);
  8975. break;
  8976. }
  8977. case TdsEnums.SQLTIME:
  8978. if (scale > TdsEnums.DEFAULT_VARTIME_SCALE) {
  8979. throw SQL.TimeScaleValueOutOfRange(scale);
  8980. }
  8981. WriteTime((TimeSpan)value, scale, actualLength, stateObj);
  8982. break;
  8983. case TdsEnums.SQLDATETIME2:
  8984. if (scale > TdsEnums.DEFAULT_VARTIME_SCALE) {
  8985. throw SQL.TimeScaleValueOutOfRange(scale);
  8986. }
  8987. WriteDateTime2((DateTime)value, scale, actualLength, stateObj);
  8988. break;
  8989. case TdsEnums.SQLDATETIMEOFFSET:
  8990. WriteDateTimeOffset((DateTimeOffset)value, scale, actualLength, stateObj);
  8991. break;
  8992. default:
  8993. Debug.Assert(false, "Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
  8994. break;
  8995. } // switch
  8996. // return point for accumualated writes, note: non-accumulated writes returned from their case statements
  8997. return null;
  8998. // Debug.WriteLine("value: " + value.ToString(CultureInfo.InvariantCulture));
  8999. }
  9000. /// <summary>
  9001. /// Write parameter encryption metadata and returns a task if necessary.
  9002. /// </summary>
  9003. private Task WriteEncryptionMetadata(Task terminatedWriteTask, SqlColumnEncryptionInputParameterInfo columnEncryptionParameterInfo, TdsParserStateObject stateObj) {
  9004. Debug.Assert(columnEncryptionParameterInfo != null, @"columnEncryptionParameterInfo cannot be null");
  9005. Debug.Assert(stateObj != null, @"stateObj cannot be null");
  9006. // If there is not task already, simply write the encryption metadata synchronously.
  9007. if (terminatedWriteTask == null) {
  9008. WriteEncryptionMetadata(columnEncryptionParameterInfo, stateObj);
  9009. return null;
  9010. }
  9011. else {
  9012. // Otherwise, create a continuation task to write the encryption metadata after the previous write completes.
  9013. return AsyncHelper.CreateContinuationTask<SqlColumnEncryptionInputParameterInfo, TdsParserStateObject>(terminatedWriteTask,
  9014. WriteEncryptionMetadata, columnEncryptionParameterInfo, stateObj,
  9015. connectionToDoom: _connHandler);
  9016. }
  9017. }
  9018. /// <summary>
  9019. /// Write parameter encryption metadata.
  9020. /// </summary>
  9021. private void WriteEncryptionMetadata(SqlColumnEncryptionInputParameterInfo columnEncryptionParameterInfo, TdsParserStateObject stateObj) {
  9022. Debug.Assert(columnEncryptionParameterInfo != null, @"columnEncryptionParameterInfo cannot be null");
  9023. Debug.Assert(stateObj != null, @"stateObj cannot be null");
  9024. // Write the TypeInfo.
  9025. WriteSmiTypeInfo(columnEncryptionParameterInfo.ParameterMetadata, stateObj);
  9026. // Write the serialized array in columnEncryptionParameterInfo.
  9027. stateObj.WriteByteArray(columnEncryptionParameterInfo.SerializedWireFormat,
  9028. columnEncryptionParameterInfo.SerializedWireFormat.Length,
  9029. offsetBuffer: 0);
  9030. }
  9031. // For MAX types, this method can only write everything in one big chunk. If multiple
  9032. // chunk writes needed, please use WritePlpBytes/WritePlpChars
  9033. private byte[] SerializeUnencryptedValue(object value, MetaType type, byte scale, int actualLength, int offset, bool isDataFeed, byte normalizationVersion, TdsParserStateObject stateObj) {
  9034. Debug.Assert((null != value) && (DBNull.Value != value), "unexpected missing or empty object");
  9035. if (normalizationVersion != 0x01) {
  9036. throw SQL.UnsupportedNormalizationVersion(normalizationVersion);
  9037. }
  9038. // parameters are always sent over as BIG or N types
  9039. switch (type.NullableType) {
  9040. case TdsEnums.SQLFLTN:
  9041. if (type.FixedLength == 4)
  9042. return SerializeFloat((Single)value);
  9043. else {
  9044. Debug.Assert(type.FixedLength == 8, "Invalid length for SqlDouble type!");
  9045. return SerializeDouble((Double)value);
  9046. }
  9047. case TdsEnums.SQLBIGBINARY:
  9048. case TdsEnums.SQLBIGVARBINARY:
  9049. case TdsEnums.SQLIMAGE:
  9050. case TdsEnums.SQLUDT: {
  9051. Debug.Assert(!isDataFeed, "We cannot seriliaze streams");
  9052. Debug.Assert(value is byte[], "Value should be an array of bytes");
  9053. byte[] b = new byte[actualLength];
  9054. Buffer.BlockCopy((byte[])value, offset, b, 0, actualLength);
  9055. return b;
  9056. }
  9057. case TdsEnums.SQLUNIQUEID: {
  9058. System.Guid guid = (System.Guid)value;
  9059. byte[] b = guid.ToByteArray();
  9060. Debug.Assert((actualLength == b.Length) && (actualLength == 16), "Invalid length for guid type in com+ object");
  9061. return b;
  9062. }
  9063. case TdsEnums.SQLBITN: {
  9064. Debug.Assert(type.FixedLength == 1, "Invalid length for SqlBoolean type");
  9065. // We normalize to allow conversion across data types. BIT is serialized into a BIGINT.
  9066. return SerializeLong((bool)value == true ? 1 : 0, stateObj);
  9067. }
  9068. case TdsEnums.SQLINTN:
  9069. if (type.FixedLength == 1)
  9070. return SerializeLong((byte)value, stateObj);
  9071. if (type.FixedLength == 2)
  9072. return SerializeLong((Int16)value, stateObj);
  9073. if (type.FixedLength == 4)
  9074. return SerializeLong((Int32)value, stateObj);
  9075. Debug.Assert(type.FixedLength == 8, "invalid length for SqlIntN type: " + type.FixedLength.ToString(CultureInfo.InvariantCulture));
  9076. return SerializeLong((Int64)value, stateObj);
  9077. case TdsEnums.SQLBIGCHAR:
  9078. case TdsEnums.SQLBIGVARCHAR:
  9079. case TdsEnums.SQLTEXT: {
  9080. Debug.Assert(!isDataFeed, "We cannot seriliaze streams");
  9081. Debug.Assert((value is string || value is byte[]), "Value is a byte array or string");
  9082. if (value is byte[]) { // If LazyMat non-filled blob, send cookie rather than value
  9083. byte[] b = new byte[actualLength];
  9084. Buffer.BlockCopy((byte[])value, 0, b, 0, actualLength);
  9085. return b;
  9086. }
  9087. else {
  9088. return SerializeEncodingChar((string)value, actualLength, offset, _defaultEncoding);
  9089. }
  9090. }
  9091. case TdsEnums.SQLNCHAR:
  9092. case TdsEnums.SQLNVARCHAR:
  9093. case TdsEnums.SQLNTEXT:
  9094. case TdsEnums.SQLXMLTYPE: {
  9095. Debug.Assert(!isDataFeed, "We cannot seriliaze streams");
  9096. Debug.Assert((value is string || value is byte[]), "Value is a byte array or string");
  9097. if (value is byte[]) { // If LazyMat non-filled blob, send cookie rather than value
  9098. byte[] b = new byte[actualLength];
  9099. Buffer.BlockCopy((byte[])value, 0, b, 0, actualLength);
  9100. return b;
  9101. }
  9102. else { // convert to cchars instead of cbytes
  9103. actualLength >>= 1;
  9104. return SerializeString((string)value, actualLength, offset);
  9105. }
  9106. }
  9107. case TdsEnums.SQLNUMERICN:
  9108. Debug.Assert(type.FixedLength <= 17, "Decimal length cannot be greater than 17 bytes");
  9109. return SerializeDecimal((Decimal)value, stateObj);
  9110. case TdsEnums.SQLDATETIMN:
  9111. Debug.Assert(type.FixedLength <= 0xff, "Invalid Fixed Length");
  9112. TdsDateTime dt = MetaType.FromDateTime((DateTime)value, (byte)type.FixedLength);
  9113. if (type.FixedLength == 4) {
  9114. if (0 > dt.days || dt.days > UInt16.MaxValue)
  9115. throw SQL.SmallDateTimeOverflow(MetaType.ToDateTime(dt.days, dt.time, 4).ToString(CultureInfo.InvariantCulture));
  9116. if (null == stateObj._bIntBytes) {
  9117. stateObj._bIntBytes = new byte[4];
  9118. }
  9119. byte[] b = stateObj._bIntBytes;
  9120. int current = 0;
  9121. byte[] bPart = SerializeShort(dt.days, stateObj);
  9122. Buffer.BlockCopy(bPart, 0, b, current, 2);
  9123. current += 2;
  9124. bPart = SerializeShort(dt.time, stateObj);
  9125. Buffer.BlockCopy(bPart, 0, b, current, 2);
  9126. return b;
  9127. }
  9128. else {
  9129. if (null == stateObj._bLongBytes) {
  9130. stateObj._bLongBytes = new byte[8];
  9131. }
  9132. byte[] b = stateObj._bLongBytes;
  9133. int current = 0;
  9134. byte[] bPart = SerializeInt(dt.days, stateObj);
  9135. Buffer.BlockCopy(bPart, 0, b, current, 4);
  9136. current += 4;
  9137. bPart = SerializeInt(dt.time, stateObj);
  9138. Buffer.BlockCopy(bPart, 0, b, current, 4);
  9139. return b;
  9140. }
  9141. case TdsEnums.SQLMONEYN: {
  9142. return SerializeCurrency((Decimal)value, type.FixedLength, stateObj);
  9143. }
  9144. case TdsEnums.SQLDATE: {
  9145. return SerializeDate((DateTime)value);
  9146. }
  9147. case TdsEnums.SQLTIME:
  9148. if (scale > TdsEnums.DEFAULT_VARTIME_SCALE) {
  9149. throw SQL.TimeScaleValueOutOfRange(scale);
  9150. }
  9151. return SerializeTime((TimeSpan)value, scale, actualLength);
  9152. case TdsEnums.SQLDATETIME2:
  9153. if (scale > TdsEnums.DEFAULT_VARTIME_SCALE) {
  9154. throw SQL.TimeScaleValueOutOfRange(scale);
  9155. }
  9156. return SerializeDateTime2((DateTime)value, scale, actualLength);
  9157. case TdsEnums.SQLDATETIMEOFFSET:
  9158. if (scale > TdsEnums.DEFAULT_VARTIME_SCALE) {
  9159. throw SQL.TimeScaleValueOutOfRange(scale);
  9160. }
  9161. return SerializeDateTimeOffset((DateTimeOffset)value, scale, actualLength);
  9162. default:
  9163. throw SQL.UnsupportedDatatypeEncryption(type.TypeName);
  9164. } // switch
  9165. // Debug.WriteLine("value: " + value.ToString(CultureInfo.InvariantCulture));
  9166. }
  9167. // For MAX types, this method can only write everything in one big chunk. If multiple
  9168. // chunk writes needed, please use WritePlpBytes/WritePlpChars
  9169. private byte[] SerializeUnencryptedSqlValue(object value, MetaType type, int actualLength, int offset, byte normalizationVersion, TdsParserStateObject stateObj) {
  9170. Debug.Assert(((type.NullableType == TdsEnums.SQLXMLTYPE) ||
  9171. (value is INullable && !((INullable)value).IsNull)),
  9172. "unexpected null SqlType!");
  9173. if (normalizationVersion != 0x01) {
  9174. throw SQL.UnsupportedNormalizationVersion(normalizationVersion);
  9175. }
  9176. // parameters are always sent over as BIG or N types
  9177. switch (type.NullableType) {
  9178. case TdsEnums.SQLFLTN:
  9179. if (type.FixedLength == 4)
  9180. return SerializeFloat(((SqlSingle)value).Value);
  9181. else {
  9182. Debug.Assert(type.FixedLength == 8, "Invalid length for SqlDouble type!");
  9183. return SerializeDouble(((SqlDouble)value).Value);
  9184. }
  9185. case TdsEnums.SQLBIGBINARY:
  9186. case TdsEnums.SQLBIGVARBINARY:
  9187. case TdsEnums.SQLIMAGE: {
  9188. byte[] b = new byte[actualLength];
  9189. if (value is SqlBinary) {
  9190. Buffer.BlockCopy(((SqlBinary)value).Value, offset, b, 0, actualLength);
  9191. }
  9192. else {
  9193. Debug.Assert(value is SqlBytes);
  9194. Buffer.BlockCopy(((SqlBytes)value).Value, offset, b, 0, actualLength);
  9195. }
  9196. return b;
  9197. }
  9198. case TdsEnums.SQLUNIQUEID: {
  9199. byte[] b = ((SqlGuid)value).ToByteArray();
  9200. Debug.Assert((actualLength == b.Length) && (actualLength == 16), "Invalid length for guid type in com+ object");
  9201. return b;
  9202. }
  9203. case TdsEnums.SQLBITN: {
  9204. Debug.Assert(type.FixedLength == 1, "Invalid length for SqlBoolean type");
  9205. // We normalize to allow conversion across data types. BIT is serialized into a BIGINT.
  9206. return SerializeLong(((SqlBoolean)value).Value == true ? 1 : 0, stateObj);
  9207. }
  9208. case TdsEnums.SQLINTN:
  9209. // We normalize to allow conversion across data types. All data types below are serialized into a BIGINT.
  9210. if (type.FixedLength == 1)
  9211. return SerializeLong(((SqlByte)value).Value, stateObj);
  9212. if (type.FixedLength == 2)
  9213. return SerializeLong(((SqlInt16)value).Value, stateObj);
  9214. if (type.FixedLength == 4)
  9215. return SerializeLong(((SqlInt32)value).Value, stateObj);
  9216. else {
  9217. Debug.Assert(type.FixedLength == 8, "invalid length for SqlIntN type: " + type.FixedLength.ToString(CultureInfo.InvariantCulture));
  9218. return SerializeLong(((SqlInt64)value).Value, stateObj);
  9219. }
  9220. case TdsEnums.SQLBIGCHAR:
  9221. case TdsEnums.SQLBIGVARCHAR:
  9222. case TdsEnums.SQLTEXT:
  9223. if (value is SqlChars) {
  9224. String sch = new String(((SqlChars)value).Value);
  9225. return SerializeEncodingChar(sch, actualLength, offset, _defaultEncoding);
  9226. }
  9227. else {
  9228. Debug.Assert(value is SqlString);
  9229. return SerializeEncodingChar(((SqlString)value).Value, actualLength, offset, _defaultEncoding);
  9230. }
  9231. case TdsEnums.SQLNCHAR:
  9232. case TdsEnums.SQLNVARCHAR:
  9233. case TdsEnums.SQLNTEXT:
  9234. case TdsEnums.SQLXMLTYPE:
  9235. // convert to cchars instead of cbytes
  9236. // Xml type is already converted to string through GetCoercedValue
  9237. if (actualLength != 0)
  9238. actualLength >>= 1;
  9239. if (value is SqlChars) {
  9240. return SerializeCharArray(((SqlChars)value).Value, actualLength, offset);
  9241. }
  9242. else {
  9243. Debug.Assert(value is SqlString);
  9244. return SerializeString(((SqlString)value).Value, actualLength, offset);
  9245. }
  9246. case TdsEnums.SQLNUMERICN:
  9247. Debug.Assert(type.FixedLength <= 17, "Decimal length cannot be greater than 17 bytes");
  9248. return SerializeSqlDecimal((SqlDecimal)value, stateObj);
  9249. case TdsEnums.SQLDATETIMN:
  9250. SqlDateTime dt = (SqlDateTime)value;
  9251. if (type.FixedLength == 4) {
  9252. if (0 > dt.DayTicks || dt.DayTicks > UInt16.MaxValue)
  9253. throw SQL.SmallDateTimeOverflow(dt.ToString());
  9254. if (null == stateObj._bIntBytes) {
  9255. stateObj._bIntBytes = new byte[4];
  9256. }
  9257. byte[] b = stateObj._bIntBytes;
  9258. int current = 0;
  9259. byte[] bPart = SerializeShort(dt.DayTicks, stateObj);
  9260. Buffer.BlockCopy(bPart, 0, b, current, 2);
  9261. current += 2;
  9262. bPart = SerializeShort(dt.TimeTicks / SqlDateTime.SQLTicksPerMinute, stateObj);
  9263. Buffer.BlockCopy(bPart, 0, b, current, 2);
  9264. return b;
  9265. }
  9266. else {
  9267. if (null == stateObj._bLongBytes) {
  9268. stateObj._bLongBytes = new byte[8];
  9269. }
  9270. byte[] b = stateObj._bLongBytes;
  9271. int current = 0;
  9272. byte[] bPart = SerializeInt(dt.DayTicks, stateObj);
  9273. Buffer.BlockCopy(bPart, 0, b, current, 4);
  9274. current += 4;
  9275. bPart = SerializeInt(dt.TimeTicks, stateObj);
  9276. Buffer.BlockCopy(bPart, 0, b, current, 4);
  9277. return b;
  9278. }
  9279. case TdsEnums.SQLMONEYN: {
  9280. return SerializeSqlMoney((SqlMoney)value, type.FixedLength, stateObj);
  9281. }
  9282. default:
  9283. throw SQL.UnsupportedDatatypeEncryption(type.TypeName);
  9284. } // switch
  9285. }
  9286. //
  9287. // we always send over nullable types for parameters so we always write the varlen fields
  9288. //
  9289. internal void WriteParameterVarLen(MetaType type, int size, bool isNull, TdsParserStateObject stateObj, bool unknownLength=false) {
  9290. if (type.IsLong) { // text/image/SQLVariant have a 4 byte length, plp datatypes have 8 byte lengths
  9291. if (isNull) {
  9292. if (type.IsPlp) {
  9293. WriteLong(unchecked((long)TdsEnums.SQL_PLP_NULL), stateObj);
  9294. }
  9295. else {
  9296. WriteInt(unchecked((int)TdsEnums.VARLONGNULL), stateObj);
  9297. }
  9298. }
  9299. else if (type.NullableType == TdsEnums.SQLXMLTYPE || unknownLength) {
  9300. WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, stateObj);
  9301. }
  9302. else if (type.IsPlp) {
  9303. // Non-xml plp types
  9304. WriteLong((long)size, stateObj);
  9305. }
  9306. else {
  9307. WriteInt(size, stateObj);
  9308. }
  9309. }
  9310. else if (type.IsVarTime) {
  9311. if (isNull) {
  9312. stateObj.WriteByte(TdsEnums.FIXEDNULL);
  9313. }
  9314. else {
  9315. stateObj.WriteByte((byte)size);
  9316. }
  9317. }
  9318. else if (false == type.IsFixed) { // non-long but variable length column, must be a BIG* type: 2 byte length
  9319. if (isNull) {
  9320. WriteShort(TdsEnums.VARNULL, stateObj);
  9321. }
  9322. else {
  9323. WriteShort(size, stateObj);
  9324. }
  9325. }
  9326. else {
  9327. if (isNull) {
  9328. stateObj.WriteByte(TdsEnums.FIXEDNULL);
  9329. }
  9330. else {
  9331. Debug.Assert(type.FixedLength <= 0xff, "WriteParameterVarLen: invalid one byte length!");
  9332. stateObj.WriteByte((byte)(type.FixedLength & 0xff)); // 1 byte for everything else
  9333. }
  9334. }
  9335. }
  9336. // Reads the next chunk in a nvarchar(max) data stream.
  9337. // This call must be preceeded by a call to ReadPlpLength or ReadDataLength.
  9338. // Will not start reading into the next chunk if bytes requested is larger than
  9339. // the current chunk length. Do another ReadPlpLength, ReadPlpUnicodeChars in that case.
  9340. // Returns the actual chars read
  9341. private bool TryReadPlpUnicodeCharsChunk(char[] buff, int offst, int len, TdsParserStateObject stateObj, out int charsRead) {
  9342. Debug.Assert((buff == null && len == 0) || (buff.Length >= offst + len), "Invalid length sent to ReadPlpUnicodeChars()!");
  9343. Debug.Assert((stateObj._longlen != 0) && (stateObj._longlen != TdsEnums.SQL_PLP_NULL),
  9344. "Out of sync plp read request");
  9345. if (stateObj._longlenleft == 0) {
  9346. Debug.Assert(false, "Out of sync read request");
  9347. charsRead = 0;
  9348. return true;
  9349. }
  9350. charsRead = len;
  9351. // stateObj._longlenleft is in bytes
  9352. if ((stateObj._longlenleft >> 1) < (ulong)len)
  9353. charsRead = (int)(stateObj._longlenleft >> 1);
  9354. for (int ii = 0; ii < charsRead; ii++) {
  9355. if (!stateObj.TryReadChar(out buff[offst + ii])) {
  9356. return false;
  9357. }
  9358. }
  9359. stateObj._longlenleft -= ((ulong)charsRead << 1);
  9360. return true;
  9361. }
  9362. internal int ReadPlpUnicodeChars(ref char[] buff, int offst, int len, TdsParserStateObject stateObj) {
  9363. int charsRead;
  9364. Debug.Assert(stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  9365. bool result = TryReadPlpUnicodeChars(ref buff, offst, len, stateObj, out charsRead);
  9366. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  9367. return charsRead;
  9368. }
  9369. // Reads the requested number of chars from a plp data stream, or the entire data if
  9370. // requested length is -1 or larger than the actual length of data. First call to this method
  9371. // should be preceeded by a call to ReadPlpLength or ReadDataLength.
  9372. // Returns the actual chars read.
  9373. internal bool TryReadPlpUnicodeChars(ref char[] buff, int offst, int len, TdsParserStateObject stateObj, out int totalCharsRead) {
  9374. int charsRead = 0;
  9375. int charsLeft = 0;
  9376. char[] newbuf;
  9377. if (stateObj._longlen == 0) {
  9378. Debug.Assert(stateObj._longlenleft == 0);
  9379. totalCharsRead = 0;
  9380. return true; // No data
  9381. }
  9382. Debug.Assert(((ulong)stateObj._longlen != TdsEnums.SQL_PLP_NULL),
  9383. "Out of sync plp read request");
  9384. Debug.Assert((buff == null && offst == 0) || (buff.Length >= offst + len), "Invalid length sent to ReadPlpUnicodeChars()!");
  9385. charsLeft = len;
  9386. // If total length is known up front, allocate the whole buffer in one shot instead of realloc'ing and copying over each time
  9387. if (buff == null && stateObj._longlen != TdsEnums.SQL_PLP_UNKNOWNLEN) {
  9388. buff = new char[(int)Math.Min((int)stateObj._longlen, len)];
  9389. }
  9390. if (stateObj._longlenleft == 0) {
  9391. ulong ignored;
  9392. if (!stateObj.TryReadPlpLength(false, out ignored)) {
  9393. totalCharsRead = 0;
  9394. return false;
  9395. }
  9396. if (stateObj._longlenleft == 0) { // Data read complete
  9397. totalCharsRead = 0;
  9398. return true;
  9399. }
  9400. }
  9401. totalCharsRead = 0;
  9402. while (charsLeft > 0) {
  9403. charsRead = (int)Math.Min((stateObj._longlenleft + 1) >> 1, (ulong)charsLeft);
  9404. if ((buff == null) || (buff.Length < (offst + charsRead))) {
  9405. // Grow the array
  9406. newbuf = new char[offst + charsRead];
  9407. if (buff != null) {
  9408. Buffer.BlockCopy(buff, 0, newbuf, 0, offst*2);
  9409. }
  9410. buff = newbuf;
  9411. }
  9412. if (charsRead > 0) {
  9413. if (!TryReadPlpUnicodeCharsChunk(buff, offst, charsRead, stateObj, out charsRead)) {
  9414. return false;
  9415. }
  9416. charsLeft -= charsRead;
  9417. offst += charsRead;
  9418. totalCharsRead += charsRead;
  9419. }
  9420. // Special case single byte left
  9421. if (stateObj._longlenleft == 1 && (charsLeft > 0)) {
  9422. byte b1;
  9423. if (!stateObj.TryReadByte(out b1)) {
  9424. return false;
  9425. }
  9426. stateObj._longlenleft--;
  9427. ulong ignored;
  9428. if (!stateObj.TryReadPlpLength(false, out ignored)) {
  9429. return false;
  9430. }
  9431. Debug.Assert((stateObj._longlenleft != 0), "ReadPlpUnicodeChars: Odd byte left at the end!");
  9432. byte b2;
  9433. if (!stateObj.TryReadByte(out b2)) {
  9434. return false;
  9435. }
  9436. stateObj._longlenleft--;
  9437. // Put it at the end of the array. At this point we know we have an extra byte.
  9438. buff[offst] = (char)(((b2 & 0xff) << 8) + (b1 & 0xff));
  9439. offst = checked((int)offst + 1);
  9440. charsRead++;
  9441. charsLeft--;
  9442. totalCharsRead++;
  9443. }
  9444. if (stateObj._longlenleft == 0) { // Read the next chunk or cleanup state if hit the end
  9445. ulong ignored;
  9446. if (!stateObj.TryReadPlpLength(false, out ignored)) {
  9447. return false;
  9448. }
  9449. }
  9450. if (stateObj._longlenleft == 0) // Data read complete
  9451. break;
  9452. }
  9453. return true;
  9454. }
  9455. internal int ReadPlpAnsiChars(ref char[] buff, int offst, int len, SqlMetaDataPriv metadata, TdsParserStateObject stateObj) {
  9456. int charsRead = 0;
  9457. int charsLeft = 0;
  9458. int bytesRead = 0;
  9459. int totalcharsRead = 0;
  9460. if (stateObj._longlen == 0) {
  9461. Debug.Assert(stateObj._longlenleft == 0);
  9462. return 0; // No data
  9463. }
  9464. Debug.Assert(((ulong)stateObj._longlen != TdsEnums.SQL_PLP_NULL),
  9465. "Out of sync plp read request");
  9466. Debug.Assert((buff == null && offst == 0) || (buff.Length >= offst + len), "Invalid length sent to ReadPlpAnsiChars()!");
  9467. charsLeft = len;
  9468. if (stateObj._longlenleft == 0) {
  9469. stateObj.ReadPlpLength(false);
  9470. if (stateObj._longlenleft == 0) {// Data read complete
  9471. stateObj._plpdecoder = null;
  9472. return 0;
  9473. }
  9474. }
  9475. if (stateObj._plpdecoder == null) {
  9476. Encoding enc = metadata.encoding;
  9477. if (enc == null)
  9478. {
  9479. if (null == _defaultEncoding) {
  9480. ThrowUnsupportedCollationEncountered(stateObj);
  9481. }
  9482. enc = _defaultEncoding;
  9483. }
  9484. stateObj._plpdecoder = enc.GetDecoder();
  9485. }
  9486. while (charsLeft > 0) {
  9487. bytesRead = (int)Math.Min(stateObj._longlenleft, (ulong)charsLeft);
  9488. if ((stateObj._bTmp == null) || (stateObj._bTmp.Length < bytesRead)) {
  9489. // Grow the array
  9490. stateObj._bTmp = new byte[bytesRead];
  9491. }
  9492. bytesRead = stateObj.ReadPlpBytesChunk(stateObj._bTmp, 0, bytesRead);
  9493. charsRead = stateObj._plpdecoder.GetChars(stateObj._bTmp, 0, bytesRead, buff, offst);
  9494. charsLeft -= charsRead;
  9495. offst += charsRead;
  9496. totalcharsRead += charsRead;
  9497. if (stateObj._longlenleft == 0) // Read the next chunk or cleanup state if hit the end
  9498. stateObj.ReadPlpLength(false);
  9499. if (stateObj._longlenleft == 0) { // Data read complete
  9500. stateObj._plpdecoder = null;
  9501. break;
  9502. }
  9503. }
  9504. return (totalcharsRead);
  9505. }
  9506. // ensure value is not null and does not have an NBC bit set for it before using this method
  9507. internal ulong SkipPlpValue(ulong cb, TdsParserStateObject stateObj) {
  9508. ulong skipped;
  9509. Debug.Assert(stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  9510. bool result = TrySkipPlpValue(cb, stateObj, out skipped);
  9511. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  9512. return skipped;
  9513. }
  9514. internal bool TrySkipPlpValue(ulong cb, TdsParserStateObject stateObj, out ulong totalBytesSkipped) {
  9515. // Read and skip cb bytes or until ReadPlpLength returns 0.
  9516. int bytesSkipped;
  9517. totalBytesSkipped = 0;
  9518. if (stateObj._longlenleft == 0) {
  9519. ulong ignored;
  9520. if (!stateObj.TryReadPlpLength(false, out ignored)) {
  9521. return false;
  9522. }
  9523. }
  9524. while ((totalBytesSkipped < cb) &&
  9525. (stateObj._longlenleft > 0)) {
  9526. if (stateObj._longlenleft > Int32.MaxValue)
  9527. bytesSkipped = Int32.MaxValue;
  9528. else
  9529. bytesSkipped = (int)stateObj._longlenleft;
  9530. bytesSkipped = ((cb - totalBytesSkipped) < (ulong) bytesSkipped) ? (int)(cb - totalBytesSkipped) : bytesSkipped;
  9531. if (!stateObj.TrySkipBytes(bytesSkipped)) {
  9532. return false;
  9533. }
  9534. stateObj._longlenleft -= (ulong)bytesSkipped;
  9535. totalBytesSkipped += (ulong)bytesSkipped;
  9536. if (stateObj._longlenleft == 0) {
  9537. ulong ignored;
  9538. if (!stateObj.TryReadPlpLength(false, out ignored)) {
  9539. return false;
  9540. }
  9541. }
  9542. }
  9543. return true;
  9544. }
  9545. internal ulong PlpBytesLeft(TdsParserStateObject stateObj) {
  9546. if ((stateObj._longlen != 0) && (stateObj._longlenleft == 0))
  9547. stateObj.ReadPlpLength(false);
  9548. return stateObj._longlenleft;
  9549. }
  9550. internal bool TryPlpBytesLeft(TdsParserStateObject stateObj, out ulong left) {
  9551. if ((stateObj._longlen != 0) && (stateObj._longlenleft == 0)) {
  9552. if (!stateObj.TryReadPlpLength(false, out left)) {
  9553. return false;
  9554. }
  9555. }
  9556. left = stateObj._longlenleft;
  9557. return true;
  9558. }
  9559. private const ulong _indeterminateSize = 0xffffffffffffffff; // Represents unknown size
  9560. internal ulong PlpBytesTotalLength(TdsParserStateObject stateObj) {
  9561. if (stateObj._longlen == TdsEnums.SQL_PLP_UNKNOWNLEN)
  9562. return _indeterminateSize;
  9563. else if (stateObj._longlen == TdsEnums.SQL_PLP_NULL)
  9564. return 0;
  9565. return stateObj._longlen;
  9566. }
  9567. const string StateTraceFormatString = "\n\t"
  9568. + " _physicalStateObj = {0}\n\t"
  9569. + " _pMarsPhysicalConObj = {1}\n\t"
  9570. + " _state = {2}\n\t"
  9571. + " _server = {3}\n\t"
  9572. + " _fResetConnection = {4}\n\t"
  9573. + " _defaultCollation = {5}\n\t"
  9574. + " _defaultCodePage = {6}\n\t"
  9575. + " _defaultLCID = {7}\n\t"
  9576. + " _defaultEncoding = {8}\n\t"
  9577. + " _encryptionOption = {10}\n\t"
  9578. + " _currentTransaction = {11}\n\t"
  9579. + " _pendingTransaction = {12}\n\t"
  9580. + " _retainedTransactionId = {13}\n\t"
  9581. + " _nonTransactedOpenResultCount = {14}\n\t"
  9582. + " _connHandler = {15}\n\t"
  9583. + " _fMARS = {16}\n\t"
  9584. + " _sessionPool = {17}\n\t"
  9585. + " _isShiloh = {18}\n\t"
  9586. + " _isShilohSP1 = {19}\n\t"
  9587. + " _isYukon = {20}\n\t"
  9588. + " _sniSpnBuffer = {21}\n\t"
  9589. + " _errors = {22}\n\t"
  9590. + " _warnings = {23}\n\t"
  9591. + " _attentionErrors = {24}\n\t"
  9592. + " _attentionWarnings = {25}\n\t"
  9593. + " _statistics = {26}\n\t"
  9594. + " _statisticsIsInTransaction = {27}\n\t"
  9595. + " _fPreserveTransaction = {28}"
  9596. + " _fParallel = {29}"
  9597. ;
  9598. internal string TraceString() {
  9599. return String.Format(/*IFormatProvider*/ null,
  9600. StateTraceFormatString,
  9601. null == _physicalStateObj,
  9602. null == _pMarsPhysicalConObj,
  9603. _state,
  9604. _server,
  9605. _fResetConnection,
  9606. null == _defaultCollation ? "(null)" : _defaultCollation.TraceString(),
  9607. _defaultCodePage,
  9608. _defaultLCID,
  9609. TraceObjectClass(_defaultEncoding),
  9610. "",
  9611. _encryptionOption,
  9612. null == _currentTransaction ? "(null)" : _currentTransaction.TraceString(),
  9613. null == _pendingTransaction ? "(null)" : _pendingTransaction.TraceString(),
  9614. _retainedTransactionId,
  9615. _nonTransactedOpenResultCount,
  9616. null == _connHandler ? "(null)" : _connHandler.ObjectID.ToString((IFormatProvider)null),
  9617. _fMARS,
  9618. null == _sessionPool ? "(null)" : _sessionPool.TraceString(),
  9619. _isShiloh,
  9620. _isShilohSP1,
  9621. _isYukon,
  9622. null == _sniSpnBuffer ? "(null)" : _sniSpnBuffer.Length.ToString((IFormatProvider)null),
  9623. _physicalStateObj != null ? "(null)" : _physicalStateObj.ErrorCount.ToString((IFormatProvider)null),
  9624. _physicalStateObj != null ? "(null)" : _physicalStateObj.WarningCount.ToString((IFormatProvider)null),
  9625. _physicalStateObj != null ? "(null)" : _physicalStateObj.PreAttentionErrorCount.ToString((IFormatProvider)null),
  9626. _physicalStateObj != null ? "(null)" : _physicalStateObj.PreAttentionWarningCount.ToString((IFormatProvider)null),
  9627. null == _statistics,
  9628. _statisticsIsInTransaction,
  9629. _fPreserveTransaction,
  9630. null == _connHandler ? "(null)" : _connHandler.ConnectionOptions.MultiSubnetFailover.ToString((IFormatProvider)null),
  9631. null == _connHandler ? "(null)" : _connHandler.ConnectionOptions.TransparentNetworkIPResolution.ToString((IFormatProvider)null));
  9632. }
  9633. private string TraceObjectClass(object instance) {
  9634. if (null == instance) {
  9635. return "(null)";
  9636. }
  9637. else {
  9638. return instance.GetType().ToString();
  9639. }
  9640. }
  9641. } // tdsparser
  9642. }//namespace