1//
2// This file is part of the aMule Project.
3//
4// Copyright (c) 2004-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5// Copyright (c) 2004-2011 Angel Vidal ( kry@amule.org )
6//
7// Any parts of this program derived from the xMule, lMule or eMule project,
8// or contributed by third-party developers are copyrighted by their
9// respective authors.
10//
11// This program is free software; you can redistribute it and/or modify
12// it under the terms of the GNU General Public License as published by
13// the Free Software Foundation; either version 2 of the License, or
14// (at your option) any later version.
15//
16// This program is distributed in the hope that it will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19// GNU General Public License for more details.
20//
21// You should have received a copy of the GNU General Public License
22// along with this program; if not, write to the Free Software
23// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
24//
25
26#ifndef REMOTECONNECT_H
27#define REMOTECONNECT_H
28
29
30#include "ECMuleSocket.h"
31#include "ECPacket.h"		// Needed for CECPacket
32
33class CECPacketHandlerBase {
34	public:
35		virtual ~CECPacketHandlerBase() { }
36		virtual void HandlePacket(const CECPacket *) = 0;
37};
38
39class CECLoginPacket : public CECPacket {
40	public:
41		CECLoginPacket(const wxString& client, const wxString& version,
42						bool canZLIB = true, bool canUTF8numbers = true, bool canNotify = false);
43};
44
45class CECAuthPacket : public CECPacket {
46	public:
47		CECAuthPacket(const wxString& pass);
48};
49
50//#warning Kry TODO - move to abstract layer.
51class CRemoteConnect : public CECMuleSocket {
52private:
53	// State enums for connection SM ( client side ) in case of async processing
54	enum {
55		EC_INIT,         // initial state
56		EC_CONNECT_SENT, // socket connect request sent
57		EC_REQ_SENT,     // sent auth request to core, waiting for reply
58		EC_SALT_RECEIVED,// received salt from core
59		EC_PASSWD_SENT,  // sent password to core, waiting for OK
60		EC_OK,           // core replied "ok"
61		EC_FAIL          // core replied "bad"
62	} m_ec_state;
63
64	// fifo of handlers for on-the-air requests. all EC concept is working in fcfs
65	// order, so it is ok to assume that order of replies is same as order of requests
66	std::list<CECPacketHandlerBase *> m_req_fifo;
67	int m_req_count;
68	int m_req_fifo_thr;
69
70	wxEvtHandler* m_notifier;
71
72	wxString m_connectionPassword;
73	wxString m_server_reply;
74	wxString m_client;
75	wxString m_version;
76
77	bool m_canZLIB;
78	bool m_canUTF8numbers;
79	bool m_canNotify;
80
81	void WriteDoneAndQueueEmpty();
82public:
83	// The event handler is used for notifying connect/close
84	CRemoteConnect(wxEvtHandler* evt_handler);
85
86	void SetCapabilities(bool canZLIB, bool canUTF8numbers, bool canNotify);
87
88	bool ConnectToCore(
89		const wxString &host, int port,
90		const wxString& login, const wxString &pass,
91		const wxString& client, const wxString& version);
92
93	const wxString& GetServerReply() const { return m_server_reply; }
94
95	bool RequestFifoFull()
96	{
97		return m_req_count > m_req_fifo_thr;
98	}
99
100	virtual void OnConnect(); // To override connection events
101	virtual void OnLost(); // To override close events
102
103	void SendRequest(CECPacketHandlerBase *handler, const CECPacket *request);
104	void SendPacket(const CECPacket *request);
105
106	/********************* EC API ********************/
107
108
109	/* Misc */
110
111	// Shuts down aMule
112	void ShutDown();
113
114	// Handles a ED2K link
115	void Ed2kLink(wxString* link);
116
117
118	/* Kad */
119
120	// Connects Kad network
121	void StartKad();
122
123	// Disconnects Kad network
124	void StopKad();
125
126
127	/* ED2K */
128
129	// Connects to ED2K. If ip and port are not 0, connect
130	// to the specific port. Otherwise, connect to any.
131	void ConnectED2K(uint32 ip, uint16 port);
132
133	// Disconnects from ED2K
134	void DisconnectED2K();
135
136
137	/* Servers */
138
139	// Adds a server
140	void AddServer(uint32 ip,
141		       uint16 port);
142
143	// Remove specific server
144	// Returns: Error message or empty string for no error
145	void RemoveServer(uint32 ip,
146			  uint16 port);
147
148	// Returns ED2K server list
149	void GetServerList();
150
151	// Updates ED2K server from a URL
152	void UpdateServerList(wxString url);
153
154
155	/* Search */
156
157	// Starts new search
158	void StartSearch();
159
160	// Stops current search
161	void StopSearch();
162
163	// Returns search progress in %%
164	void GetSearchProgress();
165
166	// Add 1 or more of found files to download queue
167	void DownloadSearchResult(uint32* file);
168
169
170	/* Statistics */
171
172	// Returns aMule statistics
173	void GetStatistics();
174
175	// Returns aMule connection status
176	void GetConnectionState();
177
178
179	/* Queue/File handling */
180
181	// Returns downloads queue
182	void GetDlQueue(CMD4Hash* file);
183
184	// Returns uploads queue
185	void GetUpQueue(CMD4Hash* file);
186
187	// Returns waiting queue
188	void GetWtQueue(CMD4Hash* file);
189
190	// Drops no needed sources
191	void DropNoNeededSources(CMD4Hash* file);
192
193	// Drops full queue sources
194	void DropFullQueueSources(CMD4Hash* file);
195
196	// Drops high queue rating sources
197	void DropHighQueueSources(CMD4Hash* file);
198
199	// Cleans up sources
200	void CleanUpSources(CMD4Hash* file);
201
202	// Swaps A4AF to a file
203	void SwapA4AFThis(CMD4Hash* file);
204
205	// Swaps A4AF to a file (auto)
206	void SwapA4AFThisAuto(CMD4Hash* file);
207
208	// Swaps A4AF to any other files
209	void SwapA4AFOthers(CMD4Hash* file);
210
211	// Pauses download(s)
212	void Pause(CMD4Hash* file);
213
214	// Resumes download(s)
215	void Resume(CMD4Hash* file);
216
217	// Stops download(s)
218	void Stop(CMD4Hash* file);
219
220	// Sets priority for a download
221	void SetPriority(CMD4Hash* file,
222			 uint8 priority);
223
224	// Deletes a download
225	void Delete(CMD4Hash* file);
226
227	// Sets category for a download
228	void SetCategory(CMD4Hash* file,
229			 wxString category);
230
231
232	/* Shared files */
233
234	// Returns a list of shared files
235	void GetSharedFiles();
236
237	// Sets priority for 1 or more shared files
238	void SetSharedPriority(CMD4Hash* file,
239			       uint8 priority);
240
241	// Reloads shared file list
242	void ReloadSharedFiles();
243
244	// Adds a directory to shared file list
245	void AddDirectoryToSharedFiles(wxString dir);
246
247	// Renames a file
248	void RenameFile(CMD4Hash file,
249			wxString name);
250
251
252	/* Logging */
253
254	// Adds a new debug log line
255	void AddLogline();
256
257	// Adds a new debug log line
258	void AddDebugLogLine();
259
260	// Retrieves the log
261	void GetLog();
262
263	// Returns the last log line.
264	void GetLastLogLine();
265
266	// Retrieves the debug log
267	void GetDebugLog();
268
269	// Retrieves the server info log
270	void GetServerInfo();
271
272	// Clears the log
273	void ClearLog();
274
275	// Clears the debug log
276	void ClearDebugLog();
277
278	// Clears server info log
279	void ClearServerInfo();
280
281
282	/* Preferences */
283
284	// Request for Preferences
285	void GetPreferences();
286
287	// Setting the preferences
288	void SetPreferencesCategories();
289	void SetPreferencesGeneral(wxString userNick,
290				   CMD4Hash userHash);
291	void SetPreferencesConnections(uint32 LineDownloadCapacity,
292				       uint32 LineUploadCapacity,
293				       uint16 MaxDownloadSpeed,
294				       uint16 MaxUploadSpeed,
295				       uint16 UploadSlotAllocation,
296				       uint16 TCPPort,
297				       uint16 UDPPort,
298				       bool DisableUDP,
299				       uint16 MaxSourcesPerFile,
300				       uint16 MaxConnections,
301				       bool EnableAutoConnect,
302				       bool EnableReconnect,
303				       bool EnableNetworkED2K,
304				       bool EnableNetworkKademlia);
305	void SetPreferencesMessageFilter(bool Enabled,
306					 bool FilterAll,
307					 bool AllowFromFriends,
308					 bool FilterFromUnknownClients,
309					 bool FilterByKeyword,
310					 wxString Keywords);
311	void SetPreferencesRemoteCrtl(bool RunOnStartup,
312				      uint16 Port,
313				      bool Guest,
314				      CMD4Hash GuestPasswdHash,
315				      bool UseGzip,
316				      uint32 RefreshInterval,
317				      wxString Template);
318	void SetPreferencesOnlineSig(bool Enabled);
319	void SetPreferencesServers(bool RemoveDeadServers,
320				   uint16 RetriesDeadServers,
321				   bool AutoUpdate,
322				   // bool URLList, TODO: Implement this!
323				   bool AddFromServer,
324				   bool AddFromClient,
325				   bool UsePrioritySystem,
326				   bool SmartLowIDCheck,
327				   bool SafeServerConnection,
328				   bool AutoConnectStaticOnly,
329				   bool ManualHighPriority);
330	void SetPreferencesFiles(bool ICHEnabled,
331				 bool AIHCTrust,
332				 bool NewPaused,
333				 bool NewDownloadAutoPriority,
334				 bool PreviewPriority,
335				 bool NewAutoULPriotiry,
336				 bool UploadFullChunks,
337				 bool StartNextPaused,
338				 bool ResumeSameCategory,
339				 bool SaveSources,
340				 bool ExtractMetadata,
341				 bool AllocateFullChunks,
342				 bool AllocateFullSize,
343				 bool CheckFreeSpace,
344				 uint32 MinFreeSpace);
345	void SetPreferencesSrcDrop(uint8 NoNeeded,
346				   bool DropFQS,
347				   bool DropHQRS,
348				   uint16 HQRSValue,
349				   uint16 AutodropTimer);
350	void SetPreferencesDirectories();
351	void SetPreferencesStatistics();
352	void SetPreferencesSecurity(uint8 CanSeeShares,
353				    uint32 FilePermissions,
354				    uint32 DirPermissions,
355				    bool IPFilterEnabled,
356				    bool IPFilterAutoUpdate,
357				    wxString IPFilterUpdateURL,
358				    uint8 IPFilterLevel,
359				    bool IPFilterFilterLAN,
360				    bool UseSecIdent);
361	void SetPreferencesCoreTweaks(uint16 MaxConnectionsPerFive,
362				      bool Verbose,
363				      uint32 FileBuffer,
364				      uint32 ULQueue,
365				      uint32 SRVKeepAliveTimeout);
366
367	// Creates new category
368	void CreateCategory(uint32 category,
369			    wxString title,
370			    wxString folder,
371			    wxString comment,
372			    uint32 color,
373			    uint8 priority);
374
375	// Updates existing category
376	void UpdateCategory(uint32 category,
377			    wxString title,
378			    wxString folder,
379			    wxString comment,
380			    uint32 color,
381			    uint8 priority);
382
383	// Deletes existing category
384	void DeleteCategory(uint32 category);
385
386	// Retrieves the statistics graphs
387	void GetStatsGraphs();
388
389	// Retrieves the statistics tree
390	void GetStatsTree();
391
392	// Check if connection goes to local machine
393	bool IsConnectedToLocalHost();
394
395private:
396	virtual const CECPacket *OnPacketReceived(const CECPacket *packet, uint32 trueSize);
397	bool ProcessAuthPacket(const CECPacket *reply);
398};
399
400DECLARE_LOCAL_EVENT_TYPE(wxEVT_EC_CONNECTION, wxEVT_USER_FIRST + 1000)
401
402class wxECSocketEvent : public wxEvent {
403public:
404	wxECSocketEvent(int id, int event_id)	: wxEvent(event_id, id) {}
405	wxECSocketEvent(int id)			: wxEvent(-1, id) {}
406	wxECSocketEvent(int id, bool result, const wxString& reply) : wxEvent(-1, id)
407	{
408		m_value = result;
409		m_server_reply = reply;
410	}
411	wxEvent *Clone(void) const		{ return new wxECSocketEvent(*this); }
412	bool GetResult() const			{ return m_value; }
413	const wxString& GetServerReply() const	{ return m_server_reply; }
414private:
415	bool m_value;
416	wxString m_server_reply;
417};
418
419#endif // REMOTECONNECT_H
420
421// File_checked_for_headers
422