IdTCPConnection.pas 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. {
  2. $Project$
  3. $Workfile$
  4. $Revision$
  5. $DateUTC$
  6. $Id$
  7. This file is part of the Indy (Internet Direct) project, and is offered
  8. under the dual-licensing agreement described on the Indy website.
  9. (http://www.indyproject.org/)
  10. Copyright:
  11. (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
  12. $Log$
  13. //TODO: Elim read/write methods - they are duped
  14. //TODO: See second uses comment
  15. Rev 1.68 3/7/2005 5:48:18 PM JPMugaas
  16. Made a backdoor so we can adjust command output in specific ways.
  17. Rev 1.67 1/15/2005 6:02:02 PM JPMugaas
  18. These should compile again.
  19. Rev 1.66 1/15/05 2:16:04 PM RLebeau
  20. Misc. tweaks
  21. Rev 1.65 12/21/04 3:20:54 AM RLebeau
  22. Removed compiler warning
  23. Rev 1.64 12/12/04 2:24:28 PM RLebeau
  24. Updated WriteRFCStrings() to call new method in the IOHandler.
  25. Rev 1.63 10/26/2004 8:43:02 PM JPMugaas
  26. Should be more portable with new references to TIdStrings and TIdStringList.
  27. Rev 1.62 6/11/2004 8:48:36 AM DSiders
  28. Added "Do not Localize" comments.
  29. Rev 1.61 2004.06.07 1:34:20 PM czhower
  30. OnWork fix now sends running total as it should.
  31. Rev 1.60 2004.06.06 5:18:04 PM czhower
  32. OnWork bug fix
  33. Rev 1.59 2004.06.05 9:46:30 AM czhower
  34. IOHandler OnWork fix
  35. Rev 1.58 11/05/2004 17:13:32 HHariri
  36. Fix brought from IW for overflow of DoWork
  37. Rev 1.57 4/19/2004 9:50:08 AM BGooijen
  38. Fixed AV in .Disconnect
  39. Rev 1.56 2004.04.18 12:52:04 AM czhower
  40. Big bug fix with server disconnect and several other bug fixed that I found
  41. along the way.
  42. Rev 1.55 2004.03.06 10:40:30 PM czhower
  43. Changed IOHandler management to fix bug in server shutdowns.
  44. Rev 1.54 2004.03.06 1:32:58 PM czhower
  45. -Change to disconnect
  46. -Addition of DisconnectNotifyPeer
  47. -WriteHeader now write bufers
  48. Rev 1.53 3/1/04 7:12:00 PM RLebeau
  49. Bug fix for SetIOHandler() not updating the FSocket member correctly.
  50. Rev 1.52 2004.02.03 4:16:56 PM czhower
  51. For unit name changes.
  52. Rev 1.51 1/29/04 9:37:18 PM RLebeau
  53. Added setter method for Greeting property
  54. Rev 1.50 2004.01.28 9:42:32 PM czhower
  55. Now checks for connection.
  56. Rev 1.49 2004.01.20 10:03:36 PM czhower
  57. InitComponent
  58. Rev 1.48 2003.12.31 3:47:44 PM czhower
  59. Changed to use TextIsSame
  60. Rev 1.47 12/28/2003 4:47:40 PM BGooijen
  61. Removed ChangeReplyClass
  62. Rev 1.46 14/12/2003 18:14:54 CCostelloe
  63. Added ChangeReplyClass procedure.
  64. Rev 1.45 11/4/2003 10:28:34 PM DSiders
  65. Removed exceptions moved to IdException.pas.
  66. Rev 1.44 2003.10.18 9:33:28 PM czhower
  67. Boatload of bug fixes to command handlers.
  68. Rev 1.43 10/15/2003 7:32:48 PM DSiders
  69. Added a resource string for the exception raised in
  70. TIdTCPConnection.CreateIOHandler.
  71. Rev 1.42 2003.10.14 1:27:02 PM czhower
  72. Uupdates + Intercept support
  73. Rev 1.41 10/10/2003 11:00:36 PM BGooijen
  74. Added GetReplyClass
  75. Rev 1.40 2003.10.02 8:29:40 PM czhower
  76. Added IdReply back
  77. Rev 1.39 2003.10.02 8:08:52 PM czhower
  78. Removed unneeded unit in uses.
  79. Rev 1.38 2003.10.01 9:11:28 PM czhower
  80. .Net
  81. Rev 1.37 2003.10.01 5:05:18 PM czhower
  82. .Net
  83. Rev 1.36 2003.10.01 2:30:42 PM czhower
  84. .Net
  85. Rev 1.35 2003.10.01 11:16:38 AM czhower
  86. .Net
  87. Rev 1.34 2003.09.30 1:23:06 PM czhower
  88. Stack split for DotNet
  89. Rev 1.33 2003.09.18 7:12:42 PM czhower
  90. AV Fix in SetIOHandler
  91. Rev 1.32 2003.09.18 5:18:00 PM czhower
  92. Implemented OnWork
  93. Rev 1.31 2003.06.30 6:17:48 PM czhower
  94. Moved socket property to public. Dont know how/why it got protected.
  95. Rev 1.30 2003.06.30 5:41:56 PM czhower
  96. -Fixed AV that occurred sometimes when sockets were closed with chains
  97. -Consolidated code that was marked by a todo for merging as it no longer
  98. needed to be separate
  99. -Removed some older code that was no longer necessary
  100. Passes bubble tests.
  101. Rev 1.29 2003.06.05 10:08:52 AM czhower
  102. Extended reply mechanisms to the exception handling. Only base and RFC
  103. completed, handing off to J Peter.
  104. Rev 1.28 6/4/2003 03:54:42 PM JPMugaas
  105. Now should compile.
  106. Rev 1.27 2003.06.04 8:10:00 PM czhower
  107. Modified CheckResponse string version to allow ''
  108. Rev 1.26 2003.06.04 12:02:30 PM czhower
  109. Additions for text code and command handling.
  110. Rev 1.25 2003.06.03 3:44:26 PM czhower
  111. Removed unused variable.
  112. Rev 1.24 2003.05.30 10:25:58 PM czhower
  113. Implemented IsEndMarker
  114. Rev 1.23 5/26/2003 04:29:52 PM JPMugaas
  115. Removed GenerateReply and ParseReply. Those are now obsolete duplicate
  116. functions in the new design.
  117. Rev 1.22 5/26/2003 12:19:56 PM JPMugaas
  118. Rev 1.21 2003.05.26 11:38:20 AM czhower
  119. Rev 1.20 5/25/2003 03:34:54 AM JPMugaas
  120. Rev 1.19 5/25/2003 03:16:22 AM JPMugaas
  121. Rev 1.18 5/20/2003 02:40:10 PM JPMugaas
  122. Rev 1.17 5/20/2003 12:43:50 AM BGooijen
  123. changeable reply types
  124. Rev 1.16 4/4/2003 8:10:14 PM BGooijen
  125. procedure CreateIOHandler is now public
  126. Rev 1.15 3/27/2003 3:17:32 PM BGooijen
  127. Removed MaxLineLength, MaxLineAction, SendBufferSize, RecvBufferSize,
  128. ReadLnSplit, ReadLnTimedOut
  129. Rev 1.14 3/19/2003 1:04:16 PM BGooijen
  130. changed procedure CreateIOHandler a little (default parameter, and other
  131. behavour when parameter = nil (constructs default now))
  132. Rev 1.13 3/5/2003 11:07:18 PM BGooijen
  133. removed intercept from this file
  134. Rev 1.12 2003.02.25 7:28:02 PM czhower
  135. Fixed WriteRFCReply
  136. Rev 1.11 2003.02.25 1:36:20 AM czhower
  137. Rev 1.10 2/13/2003 02:14:44 PM JPMugaas
  138. Now calls ReadLn in GetInternelResponse so a space is not dropped. Dropping
  139. a space throws off some things in FTP such as the FEAT reply.
  140. Rev 1.9 2003.01.18 12:29:52 PM czhower
  141. Rev 1.8 1-17-2003 22:22:08 BGooijen
  142. new design
  143. Rev 1.7 12-16-2002 20:44:38 BGooijen
  144. Added procedure CreateIOHandler(....)
  145. Rev 1.6 12-15-2002 23:32:32 BGooijen
  146. Added RecvBufferSize
  147. Rev 1.5 12-14-2002 22:16:32 BGooijen
  148. improved method to detect timeouts in ReadLn.
  149. Rev 1.4 12/6/2002 02:11:46 PM JPMugaas
  150. Protected Port and Host properties added to TCPClient because those are
  151. needed by protocol implementations. Socket property added to TCPConnection.
  152. Rev 1.3 6/12/2002 11:00:16 AM SGrobety
  153. Rev 1.0 21/11/2002 12:36:48 PM SGrobety Version: Indy 10
  154. Rev 1.2 11/15/2002 01:26:42 PM JPMugaas
  155. Restored Trim to ReadLnWait and changed GetInternelResponse to use ReadLn
  156. instead of ReadLn wait.
  157. Rev 1.1 11/14/2002 06:44:54 PM JPMugaas
  158. Removed Trim from ReadLnWait. It was breaking the new RFC Reply parsing code
  159. by removing the space at the beggining of a line.
  160. Rev 1.0 11/13/2002 09:00:30 AM JPMugaas
  161. }
  162. unit IdTCPConnection;
  163. interface
  164. {$i IdCompilerDefines.inc}
  165. {
  166. 2003-12-14 - Ciaran Costelloe
  167. - Added procedure ChangeReplyClass, because in .NET, you cannot set FReplyClass
  168. before calling the constructor, so call this procedure after the constructor
  169. to set FReplyClass to (say) TIdReplyIMAP4.
  170. 2002-06 -Andrew P.Rybin
  171. -WriteStream optimization and new "friendly" interface, InputLn fix (CrLf only if AEcho)
  172. 2002-04-12 - Andrew P.Rybin
  173. - ReadLn bugfix and optimization
  174. 2002-01-20 - Chad Z. Hower a.k.a Kudzu
  175. -WriteBuffer change was not correct. Removed. Need info on original problem to fix properly.
  176. -Modified ReadLnWait
  177. 2002-01-19 - Grahame Grieve
  178. - Fix to WriteBuffer to accept -1 from the stack.
  179. Also fixed to clean up FWriteBuffer if connection lost.
  180. 2002-01-19 - Chad Z. Hower a.k.a Kudzu
  181. -Fix to ReadLn
  182. 2002-01-16 - Andrew P.Rybin
  183. -ReadStream optimization, TIdManagedBuffer new
  184. 2002-01-03 - Chad Z. Hower a.k.a Kudzu
  185. -Added MaxLineAction
  186. -Added ReadLnSplit
  187. 2001-12-27 - Chad Z. Hower a.k.a Kudzu
  188. -Changes and bug fixes to InputLn
  189. -Modifed how buffering works
  190. -Added property InputBuffer
  191. -Moved some things to TIdBuffer
  192. -Modified ReadLn
  193. -Added LineCount to Capture
  194. 2001-12-25 - Andrew P.Rybin
  195. -MaxLineLength,ReadLn,InputLn and Merry Christmas!
  196. Original Author and Maintainer:
  197. -Chad Z. Hower a.k.a Kudzu
  198. }
  199. uses
  200. Classes,
  201. IdComponent,
  202. IdException,
  203. IdExceptionCore,
  204. IdGlobal,
  205. IdIntercept,
  206. IdIOHandler,
  207. IdIOHandlerSocket,
  208. IdReply,
  209. IdBaseComponent;
  210. type
  211. TIdTCPConnection = class(TIdComponent)
  212. protected
  213. FGreeting: TIdReply; // TODO: Only TIdFTP uses it, so it should be moved!
  214. {$IFDEF USE_OBJECT_ARC}[Weak]{$ENDIF} FIntercept: TIdConnectionIntercept;
  215. {$IFDEF USE_OBJECT_ARC}[Weak]{$ENDIF} FIOHandler: TIdIOHandler;
  216. FLastCmdResult: TIdReply;
  217. FManagedIOHandler: Boolean;
  218. FOnDisconnected: TNotifyEvent;
  219. {$IFDEF USE_OBJECT_ARC}[Weak]{$ENDIF} FSocket: TIdIOHandlerSocket;
  220. FReplyClass: TIdReplyClass;
  221. //
  222. procedure CheckConnected;
  223. procedure DoOnDisconnected; virtual;
  224. procedure InitComponent; override;
  225. function GetIntercept: TIdConnectionIntercept; virtual;
  226. function GetReplyClass: TIdReplyClass; virtual;
  227. procedure Notification(AComponent: TComponent; Operation: TOperation); override;
  228. procedure SetIntercept(AValue: TIdConnectionIntercept); virtual;
  229. procedure SetIOHandler(AValue: TIdIOHandler); virtual;
  230. procedure SetGreeting(AValue: TIdReply);
  231. procedure WorkBeginEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
  232. procedure WorkEndEvent(ASender: TObject; AWorkMode: TWorkMode);
  233. procedure WorkEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
  234. procedure PrepareCmd(var aCmd: string); virtual;
  235. public
  236. procedure CreateIOHandler(ABaseType: TIdIOHandlerClass = nil);
  237. procedure CheckForGracefulDisconnect(ARaiseExceptionIfDisconnected: Boolean = True); virtual;
  238. //
  239. function CheckResponse(const AResponse: Int16;
  240. const AAllowedResponses: array of Int16): Int16; overload; virtual;
  241. function CheckResponse(const AResponse, AAllowedResponse: string): string; overload; virtual;
  242. //
  243. function Connected: Boolean; virtual;
  244. destructor Destroy; override;
  245. // Dont allow override of this one, its for overload only
  246. procedure Disconnect; overload; // .Net overload
  247. procedure Disconnect(ANotifyPeer: Boolean); overload; virtual;
  248. // This is called when a protocol sends a command to tell the other side (typically client to
  249. // server) that it is about to disconnect. The implementation should go here.
  250. procedure DisconnectNotifyPeer; virtual;
  251. // GetInternalResponse is not in IOHandler as some protocols may need to
  252. // override it. It could be still moved and proxied from here, but at this
  253. // point it is here.
  254. procedure GetInternalResponse(AEncoding: IIdTextEncoding = nil); virtual;
  255. // Reads response using GetInternalResponse which each reply type can define
  256. // the behaviour. Then checks against expected Code.
  257. //
  258. // Seperate one for singles as one of the older Delphi compilers cannot
  259. // match a single number into an array. IIRC newer ones do.
  260. function GetResponse(const AAllowedResponse: Int16 = -1;
  261. AEncoding: IIdTextEncoding = nil): Int16; overload;
  262. function GetResponse(const AAllowedResponses: array of Int16;
  263. AEncoding: IIdTextEncoding = nil): Int16; overload; virtual;
  264. // No array type for strings as ones that use strings are usually bastard
  265. // protocols like POP3/IMAP which dont include proper substatus anyways.
  266. //
  267. // If a case can be made for some other condition this may be expanded
  268. // in the future
  269. function GetResponse(const AAllowedResponse: string;
  270. AEncoding: IIdTextEncoding = nil): string; overload; virtual;
  271. //
  272. property Greeting: TIdReply read FGreeting write SetGreeting;
  273. // RaiseExceptionForCmdResult - Overload necesary as a exception as a default param doesnt work
  274. procedure RaiseExceptionForLastCmdResult; overload; virtual;
  275. procedure RaiseExceptionForLastCmdResult(AException: TClassIdException);
  276. overload; virtual;
  277. // These are extended GetResponses, so see the comments for GetResponse
  278. function SendCmd(AOut: string; const AResponse: Int16 = -1;
  279. AEncoding: IIdTextEncoding = nil): Int16; overload;
  280. function SendCmd(AOut: string; const AResponse: array of Int16;
  281. AEncoding: IIdTextEncoding = nil): Int16; overload; virtual;
  282. function SendCmd(AOut: string; const AResponse: string;
  283. AEncoding: IIdTextEncoding = nil): string; overload;
  284. //
  285. procedure WriteHeader(AHeader: TStrings);
  286. procedure WriteRFCStrings(AStrings: TStrings);
  287. //
  288. property LastCmdResult: TIdReply read FLastCmdResult;
  289. property ManagedIOHandler: Boolean read FManagedIOHandler write FManagedIOHandler;
  290. property Socket: TIdIOHandlerSocket read FSocket;
  291. published
  292. property Intercept: TIdConnectionIntercept read GetIntercept write SetIntercept;
  293. property IOHandler: TIdIOHandler read FIOHandler write SetIOHandler;
  294. // Events
  295. property OnDisconnected: TNotifyEvent read FOnDisconnected write FOnDisconnected;
  296. property OnWork;
  297. property OnWorkBegin;
  298. property OnWorkEnd;
  299. end;
  300. implementation
  301. uses
  302. IdAntiFreezeBase, IdResourceStringsCore, IdStackConsts, IdReplyRFC,
  303. SysUtils;
  304. function TIdTCPConnection.GetIntercept: TIdConnectionIntercept;
  305. var
  306. // under ARC, convert a weak reference to a strong reference before working with it
  307. LIOHandler: TIdIOHandler;
  308. begin
  309. LIOHandler := IOHandler;
  310. if LIOHandler <> nil then begin
  311. Result := LIOHandler.Intercept;
  312. end else begin
  313. Result := FIntercept;
  314. end;
  315. end;
  316. function TIdTCPConnection.GetReplyClass:TIdReplyClass;
  317. begin
  318. Result := TIdReplyRFC;
  319. end;
  320. procedure TIdTCPConnection.CreateIOHandler(ABaseType:TIdIOHandlerClass=nil);
  321. begin
  322. if Connected then begin
  323. raise EIdException.Create(RSIOHandlerCannotChange); // TODO: create a new Exception class for this
  324. end;
  325. if Assigned(ABaseType) then begin
  326. IOHandler := TIdIOHandler.MakeIOHandler(ABaseType, Self);
  327. end else begin
  328. IOHandler := TIdIOHandler.MakeDefaultIOHandler(Self);
  329. end;
  330. ManagedIOHandler := True;
  331. end;
  332. function TIdTCPConnection.Connected: Boolean;
  333. var
  334. // under ARC, convert a weak reference to a strong reference before working with it
  335. LIOHandler: TIdIOHandler;
  336. begin
  337. // Its been changed now that IOHandler is not usually nil, but can be before the initial connect
  338. // and also this keeps it here so the user does not have to access the IOHandler for this and
  339. // also to allow future control from the connection.
  340. LIOHandler := IOHandler;
  341. Result := Assigned(LIOHandler);
  342. if Result then begin
  343. Result := LIOHandler.Connected;
  344. end;
  345. end;
  346. destructor TIdTCPConnection.Destroy;
  347. var
  348. // under ARC, convert a weak reference to a strong reference before working with it
  349. LIOHandler: TIdIOHandler;
  350. begin
  351. // Just close IOHandler directly. Dont call Disconnect - Disconnect may be override and
  352. // try to read/write to the socket.
  353. LIOHandler := IOHandler;
  354. if Assigned(LIOHandler) then begin
  355. LIOHandler.Close;
  356. // This will free any managed IOHandlers
  357. {$IFDEF USE_OBJECT_ARC}LIOHandler := nil;{$ENDIF}
  358. SetIOHandler(nil);
  359. end;
  360. FreeAndNil(FLastCmdResult);
  361. FreeAndNil(FGreeting);
  362. inherited Destroy;
  363. end;
  364. procedure TIdTCPConnection.Disconnect(ANotifyPeer: Boolean);
  365. var
  366. // under ARC, convert a weak reference to a strong reference before working with it
  367. LIOHandler: TIdIOHandler;
  368. begin
  369. try
  370. // Separately to avoid calling .Connected unless needed
  371. if ANotifyPeer then begin
  372. // TODO: do not call Connected() here if DisconnectNotifyPeer() is not
  373. // overriden. Ideally, Connected() should be called by overridden
  374. // DisconnectNotifyPeer() implementations if they really need it. But
  375. // to avoid any breakages in third-party overrides, we could check here
  376. // if DisconnectNotifyPeer() has been overridden and then call Connected()
  377. // to maintain existing behavior...
  378. //
  379. try
  380. if Connected then begin
  381. DisconnectNotifyPeer;
  382. end;
  383. except
  384. // TODO: maybe allow only EIdConnClosedGracefully and EIdSocketError?
  385. end;
  386. end;
  387. finally
  388. {
  389. there are a few possible situations here:
  390. 1) we are still connected, then everything works as before,
  391. status disconnecting, then disconnect, status disconnected
  392. 2) we are not connected, and this is just some "rogue" call to
  393. disconnect(), then nothing happens
  394. 3) we are not connected, because ClosedGracefully, then
  395. LConnected will be false, but the implicit call to
  396. CheckForDisconnect (inside Connected) will call the events
  397. }
  398. // We dont check connected here - we realy dont care about actual socket state
  399. // Here we just want to close the actual IOHandler. It is very possible for a
  400. // socket to be disconnected but the IOHandler still open. In this case we only
  401. // care of the IOHandler is still open.
  402. //
  403. // This is especially important if the socket has been disconnected with error, at this
  404. // point we just want to ignore it and checking .Connected would trigger this. We
  405. // just want to close. For some reason NS 7.1 (And only 7.1, not 7.0 or Mozilla) cause
  406. // CONNABORTED. So its extra important we just disconnect without checking socket state.
  407. LIOHandler := IOHandler;
  408. if Assigned(LIOHandler) then begin
  409. if LIOHandler.Opened then begin
  410. DoStatus(hsDisconnecting);
  411. LIOHandler.Close;
  412. DoOnDisconnected;
  413. DoStatus(hsDisconnected);
  414. //LIOHandler.InputBuffer.Clear;
  415. end;
  416. end;
  417. end;
  418. end;
  419. procedure TIdTCPConnection.DoOnDisconnected;
  420. begin
  421. if Assigned(OnDisconnected) then begin
  422. OnDisconnected(Self);
  423. end;
  424. end;
  425. function TIdTCPConnection.GetResponse(const AAllowedResponses: array of Int16;
  426. AEncoding: IIdTextEncoding = nil): Int16;
  427. begin
  428. GetInternalResponse(AEncoding);
  429. Result := CheckResponse(LastCmdResult.NumericCode, AAllowedResponses);
  430. end;
  431. procedure TIdTCPConnection.RaiseExceptionForLastCmdResult(
  432. AException: TClassIdException);
  433. begin
  434. raise AException.Create(LastCmdResult.Text.Text);
  435. end;
  436. procedure TIdTCPConnection.RaiseExceptionForLastCmdResult;
  437. begin
  438. LastCmdResult.RaiseReplyError;
  439. end;
  440. function TIdTCPConnection.SendCmd(AOut: string; const AResponse: Array of Int16;
  441. AEncoding: IIdTextEncoding = nil): Int16;
  442. begin
  443. CheckConnected;
  444. PrepareCmd(AOut);
  445. IOHandler.WriteLn(AOut, AEncoding);
  446. Result := GetResponse(AResponse, AEncoding);
  447. end;
  448. // under ARC, all weak references to a freed object get nil'ed automatically
  449. // so this is mostly redundant
  450. procedure TIdTCPConnection.Notification(AComponent: TComponent; Operation: TOperation);
  451. begin
  452. if (Operation = opRemove) then begin
  453. {$IFNDEF USE_OBJECT_ARC}
  454. if (AComponent = FIntercept) then begin
  455. FIntercept := nil;
  456. end else
  457. {$ENDIF}
  458. if (AComponent = FIOHandler) then begin
  459. FIOHandler := nil;
  460. FSocket := nil;
  461. FManagedIOHandler := False;
  462. end;
  463. end;
  464. inherited Notification(AComponent, Operation);
  465. end;
  466. procedure TIdTCPConnection.SetIntercept(AValue: TIdConnectionIntercept);
  467. var
  468. // under ARC, convert weak references to strong references before working with them
  469. LIntercept: TIdConnectionIntercept;
  470. LIOHandler: TIdIOHandler;
  471. begin
  472. LIntercept := FIntercept;
  473. if LIntercept <> AValue then
  474. begin
  475. LIOHandler := IOHandler;
  476. // RLebeau 8/25/09 - normally, short-circuit logic should skip all subsequent
  477. // evaluations in a multi-condition statement once one of the conditions
  478. // evaluates to False. However, a user just ran into a situation where that
  479. // was not the case! It caused an AV in SetIOHandler() further below when
  480. // AValue was nil (from Destroy() further above) because Assigned(AValue.Intercept)
  481. // was still being evaluated even though Assigned(AValue) was returning False.
  482. // SetIntercept() is using the same kind of short-circuit logic here as well.
  483. // Let's not rely on short-circuiting anymore, just to be on the safe side.
  484. //
  485. // old code: if Assigned(IOHandler) and Assigned(IOHandler.Intercept) and Assigned(AValue) and (AValue <> IOHandler.Intercept) then begin
  486. //
  487. if Assigned(LIOHandler) and Assigned(AValue) then begin
  488. if Assigned(LIOHandler.Intercept) and (LIOHandler.Intercept <> AValue) then begin
  489. raise EIdException.Create(RSInterceptIsDifferent); // TODO: create a new Exception class for this
  490. end;
  491. end;
  492. // TODO: should LIntercept.Connection be set to nil here if LIntercept
  493. // is not nil and LIntercept.Connection is set to Self?
  494. {$IFDEF USE_OBJECT_ARC}
  495. // under ARC, all weak references to a freed object get nil'ed automatically
  496. FIntercept := AValue;
  497. {$ELSE}
  498. // remove self from the Intercept's free notification list
  499. if Assigned(LIntercept) then begin
  500. LIntercept.RemoveFreeNotification(Self);
  501. end;
  502. FIntercept := AValue;
  503. // add self to the Intercept's free notification list
  504. if Assigned(AValue) then begin
  505. AValue.FreeNotification(Self);
  506. end;
  507. {$ENDIF}
  508. if Assigned(LIOHandler) then begin
  509. LIOHandler.Intercept := AValue;
  510. end;
  511. // TODO: should FIntercept.Connection be set to Self here if FIntercept
  512. // is not nil?
  513. end;
  514. end;
  515. procedure TIdTCPConnection.SetIOHandler(AValue: TIdIOHandler);
  516. var
  517. // under ARC, convert weak references to strong references before working with them
  518. LIOHandler: TIdIOHandler;
  519. LIntercept, LOtherIntercept: TIdConnectionIntercept;
  520. begin
  521. LIOHandler := FIOHandler;
  522. if LIOHandler <> AValue then begin
  523. LIntercept := FIntercept;
  524. // RLebeau 8/25/09 - normally, short-circuit logic should skip all subsequent
  525. // evaluations in a multi-condition statement once one of the conditions
  526. // evaluates to False. However, a user just ran into a situation where that
  527. // was not the case! It caused an AV when AValue was nil (from Destroy()
  528. // further above) because Assigned(AValue.Intercept) was still being evaluated
  529. // even though Assigned(AValue) was returning False. Let's not rely on
  530. // short-circuiting anymore, just to be on the safe side.
  531. //
  532. // old code: if Assigned(AValue) and Assigned(AValue.Intercept) and Assigned(FIntercept) and (AValue.Intercept <> FIntercept) then begin
  533. //
  534. if Assigned(AValue) and Assigned(LIntercept) then begin
  535. LOtherIntercept := AValue.Intercept;
  536. if Assigned(LOtherIntercept) then begin
  537. if LOtherIntercept <> LIntercept then begin
  538. raise EIdException.Create(RSInterceptIsDifferent); // TODO: create a new Exception class for this
  539. end;
  540. {$IFDEF USE_OBJECT_ARC}LOtherIntercept := nil;{$ENDIF}
  541. end;
  542. end;
  543. if ManagedIOHandler then begin
  544. if Assigned(LIOHandler) then begin
  545. FIOHandler := nil;
  546. IdDisposeAndNil(LIOHandler);
  547. end;
  548. ManagedIOHandler := False;
  549. end;
  550. // under ARC, all weak references to a freed object get nil'ed automatically
  551. // Reset this if nil (to match nil, but not needed) or when a new IOHandler is specified
  552. // If true, code must set it after the IOHandler is set
  553. // Must do after call to FreeManagedIOHandler
  554. FSocket := nil;
  555. // Clear out old values whether setting AValue to nil, or setting a new value
  556. if Assigned(LIOHandler) then begin
  557. LIOHandler.WorkTarget := nil;
  558. {$IFNDEF USE_OBJECT_ARC}
  559. LIOHandler.RemoveFreeNotification(Self);
  560. {$ENDIF}
  561. end;
  562. if Assigned(AValue) then begin
  563. {$IFNDEF USE_OBJECT_ARC}
  564. // add self to the IOHandler's free notification list
  565. AValue.FreeNotification(Self);
  566. {$ENDIF}
  567. // Must set to handlers and not events directly as user may change
  568. // the events of TCPConnection after we have initialized these and then
  569. // these would point to old values
  570. AValue.WorkTarget := Self;
  571. if Assigned(LIntercept) then begin
  572. AValue.Intercept := LIntercept;
  573. end;
  574. if AValue is TIdIOHandlerSocket then begin
  575. FSocket := TIdIOHandlerSocket(AValue);
  576. end;
  577. end;
  578. // Last as some code uses FIOHandler to finalize items
  579. FIOHandler := AValue;
  580. end;
  581. end;
  582. procedure TIdTCPConnection.WriteHeader(AHeader: TStrings);
  583. var
  584. i: Integer;
  585. LBufferingStarted: Boolean;
  586. // under ARC, convert a weak reference to a strong reference before working with it
  587. LIOHandler: TIdIOHandler;
  588. begin
  589. CheckConnected;
  590. LIOHandler := IOHandler;
  591. LBufferingStarted := not LIOHandler.WriteBufferingActive;
  592. if LBufferingStarted then begin
  593. LIOHandler.WriteBufferOpen;
  594. end;
  595. try
  596. for i := 0 to AHeader.Count -1 do begin
  597. // No ReplaceAll flag - we only want to replace the first one
  598. LIOHandler.WriteLn(ReplaceOnlyFirst(AHeader[i], '=', ': '));
  599. end;
  600. LIOHandler.WriteLn;
  601. if LBufferingStarted then begin
  602. LIOHandler.WriteBufferClose;
  603. end;
  604. except
  605. if LBufferingStarted then begin
  606. LIOHandler.WriteBufferCancel;
  607. end;
  608. raise;
  609. end;
  610. end;
  611. function TIdTCPConnection.SendCmd(AOut: string; const AResponse: Int16 = -1;
  612. AEncoding: IIdTextEncoding = nil): Int16;
  613. begin
  614. if AResponse < 0 then begin
  615. Result := SendCmd(AOut, [], AEncoding);
  616. end else begin
  617. Result := SendCmd(AOut, [AResponse], AEncoding);
  618. end;
  619. end;
  620. procedure TIdTCPConnection.CheckForGracefulDisconnect(ARaiseExceptionIfDisconnected: Boolean);
  621. var
  622. // under ARC, convert a weak reference to a strong reference before working with it
  623. LIOHandler: TIdIOHandler;
  624. begin
  625. LIOHandler := IOHandler;
  626. if Assigned(LIOHandler) then begin
  627. LIOHandler.CheckForDisconnect(ARaiseExceptionIfDisconnected);
  628. end else if ARaiseExceptionIfDisconnected then begin
  629. raise EIdException.Create(RSNotConnected); // TODO: create a new Exception class for this
  630. end;
  631. end;
  632. function TIdTCPConnection.CheckResponse(const AResponse: Int16;
  633. const AAllowedResponses: array of Int16): Int16;
  634. begin
  635. if High(AAllowedResponses) > -1 then begin
  636. if PosInSmallIntArray(AResponse, AAllowedResponses) = -1 then begin
  637. RaiseExceptionForLastCmdResult;
  638. end;
  639. end;
  640. Result := AResponse;
  641. end;
  642. procedure TIdTCPConnection.GetInternalResponse(AEncoding: IIdTextEncoding = nil);
  643. var
  644. LLine: string;
  645. LResponse: TStringList;
  646. // under ARC, convert a weak reference to a strong reference before working with it
  647. LIOHandler: TIdIOHandler;
  648. begin
  649. CheckConnected;
  650. LResponse := TStringList.Create;
  651. try
  652. // Some servers with bugs send blank lines before reply. Dont remember which
  653. // ones, but I do remember we changed this for a reason
  654. // RLebeau 9/14/06: this can happen in between lines of the reply as well
  655. LIOHandler := IOHandler;
  656. repeat
  657. LLine := LIOHandler.ReadLnWait(MaxInt, AEncoding);
  658. LResponse.Add(LLine);
  659. until FLastCmdResult.IsEndMarker(LLine);
  660. //Note that FormattedReply uses an assign in it's property set method.
  661. FLastCmdResult.FormattedReply := LResponse;
  662. finally
  663. FreeAndNil(LResponse);
  664. end;
  665. end;
  666. procedure TIdTCPConnection.WriteRFCStrings(AStrings: TStrings);
  667. begin
  668. CheckConnected;
  669. IOHandler.WriteRFCStrings(AStrings, True);
  670. end;
  671. function TIdTCPConnection.GetResponse(const AAllowedResponse: Int16 = -1;
  672. AEncoding: IIdTextEncoding = nil): Int16;
  673. begin
  674. if AAllowedResponse < 0 then begin
  675. Result := GetResponse([], AEncoding);
  676. end else begin
  677. Result := GetResponse([AAllowedResponse], AEncoding);
  678. end;
  679. end;
  680. function TIdTCPConnection.GetResponse(const AAllowedResponse: string;
  681. AEncoding: IIdTextEncoding = nil): string;
  682. begin
  683. GetInternalResponse(AEncoding);
  684. Result := CheckResponse(LastCmdResult.Code, AAllowedResponse);
  685. end;
  686. function TIdTCPConnection.SendCmd(AOut: string; const AResponse: string;
  687. AEncoding: IIdTextEncoding = nil): string;
  688. begin
  689. CheckConnected;
  690. PrepareCmd(AOut);
  691. IOHandler.WriteLn(AOut, AEncoding);
  692. Result := GetResponse(AResponse, AEncoding);
  693. end;
  694. function TIdTCPConnection.CheckResponse(const AResponse, AAllowedResponse: string): string;
  695. begin
  696. if (AAllowedResponse <> '')
  697. and (not TextIsSame(AResponse, AAllowedResponse)) then begin
  698. RaiseExceptionForLastCmdResult;
  699. end;
  700. Result := AResponse;
  701. end;
  702. procedure TIdTCPConnection.WorkBeginEvent(ASender: TObject; AWorkMode: TWorkMode;
  703. AWorkCountMax: Int64);
  704. begin
  705. BeginWork(AWorkMode, AWorkCountMax)
  706. end;
  707. procedure TIdTCPConnection.WorkEndEvent(ASender: TObject; AWorkMode: TWorkMode);
  708. begin
  709. EndWork(AWorkMode)
  710. end;
  711. procedure TIdTCPConnection.WorkEvent(ASender: TObject; AWorkMode: TWorkMode;
  712. AWorkCount: Int64);
  713. begin
  714. DoWork(AWorkMode, AWorkCount)
  715. end;
  716. procedure TIdTCPConnection.InitComponent;
  717. begin
  718. inherited InitComponent;
  719. FReplyClass := GetReplyClass;
  720. FGreeting := FReplyClass.CreateWithReplyTexts(nil, nil);
  721. FLastCmdResult := FReplyClass.CreateWithReplyTexts(nil, nil);
  722. end;
  723. procedure TIdTCPConnection.CheckConnected;
  724. begin
  725. if not Assigned(IOHandler) then begin
  726. raise EIdNotConnected.Create(RSNotConnected);
  727. end;
  728. end;
  729. procedure TIdTCPConnection.SetGreeting(AValue: TIdReply);
  730. begin
  731. FGreeting.Assign(AValue);
  732. end;
  733. procedure TIdTCPConnection.Disconnect;
  734. begin
  735. // The default should be to tell the other side we are disconnecting
  736. Disconnect(True);
  737. end;
  738. procedure TIdTCPConnection.DisconnectNotifyPeer;
  739. begin
  740. end;
  741. procedure TIdTCPConnection.PrepareCmd(var aCmd: string);
  742. begin
  743. //Leave this empty here. It's for cases where we may need to
  744. // override what is sent to a server in a transparent manner.
  745. end;
  746. end.