version 0.0.4
[fms.git] / src / freenet / identityintroductionrequester.cpp
1 #include "../../include/freenet/identityintroductionrequester.h"\r
2 #include "../../include/freenet/identityintroductionxml.h"\r
3 #include "../../include/freenet/freenetssk.h"\r
4 #include "../../include/option.h"\r
5 #include "../../include/stringfunctions.h"\r
6 #include "../../include/xyssl/sha1.h"\r
7 #include "../../include/hex.h"\r
8 \r
9 #ifdef XMEM\r
10         #include <xmem.h>\r
11 #endif\r
12 \r
13 IdentityIntroductionRequester::IdentityIntroductionRequester()\r
14 {\r
15         Initialize();\r
16 }\r
17 \r
18 IdentityIntroductionRequester::IdentityIntroductionRequester(FCPv2 *fcp):IFCPConnected(fcp)\r
19 {\r
20         Initialize();\r
21 }\r
22 \r
23 void IdentityIntroductionRequester::FCPConnected()\r
24 {\r
25         m_requesting.clear();\r
26         PopulateIDList();\r
27 }\r
28 \r
29 void IdentityIntroductionRequester::FCPDisconnected()\r
30 {\r
31         \r
32 }\r
33 \r
34 const bool IdentityIntroductionRequester::HandleAllData(FCPMessage &message)\r
35 {\r
36         FreenetSSK ssk;\r
37         DateTime date;\r
38         std::vector<std::string> idparts;\r
39         std::vector<char> data;\r
40         long datalength;\r
41         IdentityIntroductionXML xml;\r
42 \r
43         StringFunctions::Split(message["Identifier"],"|",idparts);\r
44         StringFunctions::Convert(message["DataLength"],datalength);\r
45 \r
46         // wait for all data to be received from connection\r
47         while(m_fcp->Connected() && m_fcp->ReceiveBufferSize()<datalength)\r
48         {\r
49                 m_fcp->Update(1);\r
50         }\r
51 \r
52         // if we got disconnected- return immediately\r
53         if(m_fcp->Connected()==false)\r
54         {\r
55                 return false;\r
56         }\r
57 \r
58         // receive the file\r
59         data.resize(datalength);\r
60         m_fcp->ReceiveRaw(&data[0],datalength);\r
61 \r
62         // parse file into xml and update the database\r
63         if(xml.ParseXML(std::string(data.begin(),data.end()))==true)\r
64         {\r
65 \r
66                 ssk.SetPublicKey(xml.GetIdentity());\r
67 \r
68                 // mark puzzle found\r
69                 SQLite3DB::Statement st=m_db->Prepare("UPDATE tblIntroductionPuzzleInserts SET FoundSolution='true' WHERE UUID=?;");\r
70                 st.Bind(0,idparts[3]);\r
71                 st.Step();\r
72                 st.Finalize();\r
73 \r
74                 if(ssk.ValidPublicKey()==true)\r
75                 {\r
76                         // try to find existing identity with this SSK\r
77                         st=m_db->Prepare("SELECT IdentityID FROM tblIdentity WHERE PublicKey=?;");\r
78                         st.Bind(0,xml.GetIdentity());\r
79                         st.Step();\r
80                         if(st.RowReturned()==false)\r
81                         {\r
82                                 // we don't already know about this id - add it\r
83                                 st.Finalize();\r
84                                 date.SetToGMTime();\r
85                                 st=m_db->Prepare("INSERT INTO tblIdentity(PublicKey,DateAdded) VALUES(?,?);");\r
86                                 st.Bind(0,xml.GetIdentity());\r
87                                 st.Bind(1,date.Format("%Y-%m-%d %H:%M:%S"));\r
88                                 st.Step();\r
89                         }\r
90                         st.Finalize();\r
91                 }\r
92                 else\r
93                 {\r
94                         m_log->WriteLog(LogFile::LOGLEVEL_ERROR,"IdentityIntroductionRequester::HandleAllData parsed public SSK key was not valid.");\r
95                 }\r
96 \r
97                 m_log->WriteLog(LogFile::LOGLEVEL_DEBUG,"IdentityIntroductionRequester::HandleAllData parsed IdentityIntroduction XML file : "+message["Identifier"]);\r
98         }\r
99         else\r
100         {\r
101 \r
102                 SQLite3DB::Statement st=m_db->Prepare("UPDATE tblIntroductionPuzzleInserts SET FoundSolution='true' WHERE UUID=?;");\r
103                 st.Bind(0,idparts[3]);\r
104                 st.Step();\r
105                 st.Finalize();          \r
106 \r
107                 m_log->WriteLog(LogFile::LOGLEVEL_ERROR,"IdentityIntroductionRequester::HandleAllData error parsing IdentityIntroduction XML file : "+message["Identifier"]);\r
108         }\r
109 \r
110         // remove UUID from request list\r
111         RemoveFromRequestList(idparts[3]);\r
112 \r
113         return true;\r
114 }\r
115 \r
116 const bool IdentityIntroductionRequester::HandleGetFailed(FCPMessage &message)\r
117 {\r
118         std::vector<std::string> idparts;\r
119 \r
120         StringFunctions::Split(message["Identifier"],"|",idparts);\r
121 \r
122         // fatal error - don't try to download again\r
123         if(message["Fatal"]=="true")\r
124         {\r
125                 SQLite3DB::Statement st=m_db->Prepare("UPDATE tblIntroductionPuzzleInserts SET FoundSolution='true' WHERE UUID=?;");\r
126                 st.Bind(0,idparts[3]);\r
127                 st.Step();\r
128                 st.Finalize();\r
129 \r
130                 m_log->WriteLog(LogFile::LOGLEVEL_DEBUG,"IdentityIntroductionRequester::HandleAllData Fatal GetFailed for "+message["Identifier"]);\r
131         }\r
132 \r
133         // remove UUID from request list\r
134         RemoveFromRequestList(idparts[3]);\r
135 \r
136         return true;\r
137 }\r
138 \r
139 const bool IdentityIntroductionRequester::HandleMessage(FCPMessage &message)\r
140 {\r
141 \r
142         if(message["Identifier"].find("IdentityIntroductionRequester")==0)\r
143         {\r
144                 \r
145                 // ignore DataFound\r
146                 if(message.GetName()=="DataFound")\r
147                 {\r
148                         return true;\r
149                 }\r
150 \r
151                 if(message.GetName()=="AllData")\r
152                 {\r
153                         return HandleAllData(message);\r
154                 }\r
155 \r
156                 if(message.GetName()=="GetFailed")\r
157                 {\r
158                         return HandleGetFailed(message);\r
159                 }\r
160 \r
161                 if(message.GetName()=="IdentifierCollision")\r
162                 {\r
163                         // remove one of the ids from the requesting list\r
164                         std::vector<std::string> idparts;\r
165                         StringFunctions::Split(message["Identifier"],"|",idparts);\r
166                         RemoveFromRequestList(idparts[3]);\r
167                         return true;\r
168                 }\r
169 \r
170         }\r
171 \r
172         return false;\r
173 }\r
174 \r
175 void IdentityIntroductionRequester::Initialize()\r
176 {\r
177         std::string tempval="";\r
178         Option::instance()->Get("MaxIdentityIntroductionRequests",tempval);\r
179         StringFunctions::Convert(tempval,m_maxrequests);\r
180         if(m_maxrequests<1)\r
181         {\r
182                 m_maxrequests=1;\r
183                 m_log->WriteLog(LogFile::LOGLEVEL_ERROR,"Option MaxIdentityIntroductionRequests is currently set at "+tempval+".  It must be 1 or greater.");\r
184         }\r
185         if(m_maxrequests>100)\r
186         {\r
187                 m_log->WriteLog(LogFile::LOGLEVEL_WARNING,"Option MaxIdentityIntroductionRequests is currently set at "+tempval+".  This value might be incorrectly configured.");\r
188         }\r
189         Option::instance()->Get("MessageBase",m_messagebase);\r
190         m_tempdate.SetToGMTime();\r
191 }\r
192 \r
193 void IdentityIntroductionRequester::PopulateIDList()\r
194 {\r
195         DateTime date;\r
196         int id;\r
197 \r
198         date.SetToGMTime();\r
199         date.Add(0,0,0,-1);\r
200 \r
201         // get all identities that have unsolved puzzles from yesterday or today\r
202         SQLite3DB::Statement st=m_db->Prepare("SELECT LocalIdentityID FROM tblIntroductionPuzzleInserts WHERE Day>='"+date.Format("%Y-%m-%d")+"' AND FoundSolution='false' GROUP BY LocalIdentityID;");\r
203         st.Step();\r
204 \r
205         m_ids.clear();\r
206 \r
207         while(st.RowReturned())\r
208         {\r
209                 st.ResultInt(0,id);\r
210                 m_ids[id]=false;\r
211                 st.Step();\r
212         }\r
213 \r
214 }\r
215 \r
216 void IdentityIntroductionRequester::Process()\r
217 {\r
218         // max is the smaller of the config value or the total number of identities we will request from\r
219         long max=m_maxrequests>m_ids.size() ? m_ids.size() : m_maxrequests;\r
220 \r
221                 // try to keep up to max requests going\r
222         if(m_requesting.size()<max)\r
223         {\r
224                 std::map<long,bool>::iterator i=m_ids.begin();\r
225                 while(i!=m_ids.end() && (*i).second==true)\r
226                 {\r
227                         i++;\r
228                 }\r
229 \r
230                 if(i!=m_ids.end())\r
231                 {\r
232                         StartRequests((*i).first);\r
233                 }\r
234                 else\r
235                 {\r
236                         // we requested from all ids in the list, repopulate the list\r
237                         PopulateIDList();\r
238                 }\r
239         }\r
240         // special case - if there were 0 identities on the list when we started then we will never get a chance to repopulate the list\r
241         // this will recheck for ids every minute\r
242         DateTime now;\r
243         now.SetToGMTime();\r
244         if(m_tempdate<(now-(1.0/1440.0)))\r
245         {\r
246                 PopulateIDList();\r
247                 m_tempdate=now;\r
248         }\r
249 }\r
250 \r
251 void IdentityIntroductionRequester::RegisterWithThread(FreenetMasterThread *thread)\r
252 {\r
253         thread->RegisterFCPConnected(this);\r
254         thread->RegisterFCPMessageHandler(this);\r
255         thread->RegisterPeriodicProcessor(this);\r
256 }\r
257 \r
258 void IdentityIntroductionRequester::RemoveFromRequestList(const std::string &UUID)\r
259 {\r
260         std::vector<std::string>::iterator i=m_requesting.begin();\r
261         while(i!=m_requesting.end() && (*i)!=UUID)\r
262         {\r
263                 i++;\r
264         }\r
265         if(i!=m_requesting.end())\r
266         {\r
267                 m_requesting.erase(i);\r
268         }\r
269 }\r
270 \r
271 void IdentityIntroductionRequester::StartRequest(const std::string &UUID)\r
272 {\r
273         std::string day;\r
274         std::string solution;\r
275         std::vector<unsigned char> solutionhash;\r
276         std::string encodedhash;\r
277         FCPMessage message;\r
278         SQLite3DB::Statement st=m_db->Prepare("SELECT Day, PuzzleSolution FROM tblIntroductionPuzzleInserts WHERE FoundSolution='false' AND UUID=?;");\r
279         st.Bind(0,UUID);\r
280         st.Step();\r
281 \r
282         if(st.RowReturned())\r
283         {\r
284                 st.ResultText(0,day);\r
285                 st.ResultText(1,solution);\r
286 \r
287                 // get the hash of the solution\r
288                 solutionhash.resize(20);\r
289                 sha1((unsigned char *)solution.c_str(),solution.size(),&solutionhash[0]);\r
290                 Hex::Encode(solutionhash,encodedhash);\r
291 \r
292                 //start request for the solution\r
293                 message.SetName("ClientGet");\r
294                 message["URI"]="KSK@"+m_messagebase+"|"+day+"|"+UUID+"|"+encodedhash+".xml";\r
295                 message["Identifier"]="IdentityIntroductionRequester|"+message["URI"];\r
296                 message["ReturnType"]="direct";\r
297                 message["MaxSize"]="10000";\r
298 \r
299                 m_fcp->SendMessage(message);\r
300 \r
301                 m_requesting.push_back(UUID);\r
302 \r
303         }\r
304 \r
305 }\r
306 \r
307 void IdentityIntroductionRequester::StartRequests(const long localidentityid)\r
308 {\r
309         DateTime date;\r
310         std::string localidentityidstr;\r
311         std::string uuid;\r
312 \r
313         date.SetToGMTime();\r
314         date.Add(0,0,0,-1);\r
315         StringFunctions::Convert(localidentityid,localidentityidstr);\r
316 \r
317         // get all non-solved puzzles from yesterday and today for this identity\r
318         SQLite3DB::Statement st=m_db->Prepare("SELECT UUID FROM tblIntroductionPuzzleInserts WHERE LocalIdentityID="+localidentityidstr+" AND Day>='"+date.Format("%Y-%m-%d")+"' AND FoundSolution='false';");\r
319         st.Step();\r
320 \r
321         // start requests for all non-solved puzzles\r
322         while(st.RowReturned())\r
323         {\r
324                 uuid="";\r
325                 st.ResultText(0,uuid);\r
326                 StartRequest(uuid);\r
327                 st.Step();\r
328         }\r
329 \r
330         m_ids[localidentityid]=true;\r
331 \r
332 }\r