f7d53174354ee0b7ad30b0765aacf8b162a10553
[fms.git] / src / freenet / introductionpuzzlerequester.cpp
1 #include "../../include/freenet/introductionpuzzlerequester.h"\r
2 #include "../../include/freenet/introductionpuzzlexml.h"\r
3 #include "../../include/option.h"\r
4 #include "../../include/stringfunctions.h"\r
5 #include "../../include/bitmapvalidator.h"\r
6 #include "../../include/base64.h"\r
7 \r
8 #include <Poco/DateTime.h>\r
9 #include <Poco/Timespan.h>\r
10 #include <Poco/Timestamp.h>\r
11 #include <Poco/DateTimeFormatter.h>\r
12 \r
13 #ifdef XMEM\r
14         #include <xmem.h>\r
15 #endif\r
16 \r
17 IntroductionPuzzleRequester::IntroductionPuzzleRequester()\r
18 {\r
19         Initialize();\r
20 }\r
21 \r
22 IntroductionPuzzleRequester::IntroductionPuzzleRequester(FCPv2 *fcp):IFCPConnected(fcp)\r
23 {\r
24         Initialize();\r
25 }\r
26 \r
27 void IntroductionPuzzleRequester::FCPConnected()\r
28 {\r
29         m_requesting.clear();\r
30         PopulateIDList();\r
31 }\r
32 \r
33 void IntroductionPuzzleRequester::FCPDisconnected()\r
34 {\r
35         \r
36 }\r
37 \r
38 const bool IntroductionPuzzleRequester::HandleAllData(FCPMessage &message)\r
39 {\r
40         Poco::DateTime now;\r
41         SQLite3DB::Statement st;\r
42         std::vector<std::string> idparts;\r
43         long datalength;\r
44         std::vector<char> data;\r
45         IntroductionPuzzleXML xml;\r
46         long identityid;\r
47         long index;\r
48         bool validmessage=true;\r
49 \r
50         StringFunctions::Split(message["Identifier"],"|",idparts);\r
51         StringFunctions::Convert(message["DataLength"],datalength);\r
52         StringFunctions::Convert(idparts[1],identityid);\r
53         StringFunctions::Convert(idparts[2],index);\r
54 \r
55         // wait for all data to be received from connection\r
56         while(m_fcp->Connected() && m_fcp->ReceiveBufferSize()<datalength)\r
57         {\r
58                 m_fcp->Update(1);\r
59         }\r
60 \r
61         // if we got disconnected- return immediately\r
62         if(m_fcp->Connected()==false)\r
63         {\r
64                 return false;\r
65         }\r
66 \r
67         // receive the file\r
68         data.resize(datalength);\r
69         m_fcp->ReceiveRaw(&data[0],datalength);\r
70 \r
71         // parse file into xml and update the database\r
72         if(xml.ParseXML(std::string(data.begin(),data.end()))==true)\r
73         {\r
74 \r
75                 // check if last part of UUID matches first part of public key of identity who inserted it\r
76                 st=m_db->Prepare("SELECT PublicKey FROM tblIdentity WHERE IdentityID=?;");\r
77                 st.Bind(0,identityid);\r
78                 st.Step();\r
79                 if(st.RowReturned())\r
80                 {\r
81                         std::vector<std::string> uuidparts;\r
82                         std::vector<std::string> keyparts;\r
83                         std::string keypart="";\r
84                         std::string publickey="";\r
85 \r
86                         st.ResultText(0,publickey);\r
87 \r
88                         StringFunctions::SplitMultiple(publickey,"@,",keyparts);\r
89                         StringFunctions::SplitMultiple(xml.GetUUID(),"@",uuidparts);\r
90 \r
91                         if(uuidparts.size()>1 && keyparts.size()>1)\r
92                         {\r
93                                 keypart=StringFunctions::Replace(StringFunctions::Replace(keyparts[1],"-",""),"~","");\r
94                                 if(keypart!=uuidparts[1])\r
95                                 {\r
96                                         m_log->error("IntroductionPuzzleRequester::HandleAllData UUID in IntroductionPuzzle doesn't match public key of identity : "+message["Identifier"]);\r
97                                         validmessage=false;\r
98                                 }\r
99                         }\r
100                         else\r
101                         {\r
102                                 m_log->error("IntroductionPuzzleRequester::HandleAllData Error with identity's public key or UUID : "+message["Identifier"]);\r
103                                 validmessage=false;\r
104                         }\r
105 \r
106                 }\r
107                 else\r
108                 {\r
109                         m_log->error("IntroductionPuzzleRequester::HandleAllData Error couldn't find identity : "+message["Identifier"]);\r
110                         validmessage=false;\r
111                 }\r
112 \r
113                 // we can only validate bitmaps for now\r
114                 BitmapValidator val;\r
115                 std::vector<unsigned char> puzzledata;\r
116                 Base64::Decode(xml.GetPuzzleData(),puzzledata);\r
117                 if(xml.GetMimeType()!="image/bmp" || val.Validate(puzzledata)==false)\r
118                 {\r
119                         m_log->error("IntroductionPuzzleRequester::HandleAllData received bad mime type and/or data for "+message["Identifier"]);\r
120                         validmessage=false;\r
121                 }\r
122 \r
123                 st=m_db->Prepare("INSERT INTO tblIntroductionPuzzleRequests(IdentityID,Day,RequestIndex,Found,UUID,Type,MimeType,PuzzleData) VALUES(?,?,?,?,?,?,?,?);");\r
124                 st.Bind(0,identityid);\r
125                 st.Bind(1,idparts[4]);\r
126                 st.Bind(2,index);\r
127                 if(validmessage)\r
128                 {\r
129                         st.Bind(3,"true");\r
130                         st.Bind(4,xml.GetUUID());\r
131                         st.Bind(5,xml.GetType());\r
132                         st.Bind(6,xml.GetMimeType());\r
133                         st.Bind(7,xml.GetPuzzleData());\r
134                 }\r
135                 else\r
136                 {\r
137                         st.Bind(3,"false");\r
138                         st.Bind(4);\r
139                         st.Bind(5);\r
140                         st.Bind(6);\r
141                         st.Bind(7);\r
142                 }\r
143                 st.Step();\r
144                 st.Finalize();\r
145 \r
146                 m_log->debug("IntroductionPuzzleRequester::HandleAllData parsed IntroductionPuzzle XML file : "+message["Identifier"]);\r
147         }\r
148         else\r
149         {\r
150                 // bad data - mark index\r
151                 st=m_db->Prepare("INSERT INTO tblIntroductionPuzzleRequests(IdentityID,Day,RequestIndex,Found) VALUES(?,?,?,'false');");\r
152                 st.Bind(0,identityid);\r
153                 st.Bind(1,idparts[4]);\r
154                 st.Bind(2,index);\r
155                 st.Step();\r
156                 st.Finalize();\r
157 \r
158                 m_log->error("IntroductionPuzzleRequester::HandleAllData error parsing IntroductionPuzzle XML file : "+message["Identifier"]);\r
159         }\r
160 \r
161         // remove this identityid from request list\r
162         RemoveFromRequestList(identityid);\r
163 \r
164         return true;\r
165 \r
166 }\r
167 \r
168 const bool IntroductionPuzzleRequester::HandleGetFailed(FCPMessage &message)\r
169 {\r
170         SQLite3DB::Statement st;\r
171         std::vector<std::string> idparts;\r
172         long identityid;\r
173         long index;\r
174 \r
175         StringFunctions::Split(message["Identifier"],"|",idparts);\r
176         StringFunctions::Convert(idparts[1],identityid);\r
177         StringFunctions::Convert(idparts[2],index);     \r
178 \r
179         // if this is a fatal error - insert index into database so we won't try to download this index again\r
180         if(message["Fatal"]=="true")\r
181         {\r
182                 st=m_db->Prepare("INSERT INTO tblIntroductionPuzzleRequests(IdentityID,Day,RequestIndex,Found) VALUES(?,?,?,'false');");\r
183                 st.Bind(0,identityid);\r
184                 st.Bind(1,idparts[4]);\r
185                 st.Bind(2,index);\r
186                 st.Step();\r
187                 st.Finalize();\r
188 \r
189                 m_log->error("IntroductionPuzzleRequester::HandleGetFailed fatal error requesting "+message["Identifier"]);\r
190         }\r
191 \r
192         // remove this identityid from request list\r
193         RemoveFromRequestList(identityid);\r
194 \r
195         return true;\r
196 \r
197 }\r
198 \r
199 const bool IntroductionPuzzleRequester::HandleMessage(FCPMessage &message)\r
200 {\r
201 \r
202         if(message["Identifier"].find("IntroductionPuzzleRequester")==0)\r
203         {\r
204                 if(message.GetName()=="DataFound")\r
205                 {\r
206                         return true;\r
207                 }\r
208 \r
209                 if(message.GetName()=="AllData")\r
210                 {\r
211                         return HandleAllData(message);\r
212                 }\r
213 \r
214                 if(message.GetName()=="GetFailed")\r
215                 {\r
216                         return HandleGetFailed(message);\r
217                 }\r
218                 \r
219                 if(message.GetName()=="IdentifierCollision")\r
220                 {\r
221                         // remove one of the ids from the requesting list\r
222                         long identityid=0;\r
223                         std::vector<std::string> idparts;\r
224                         StringFunctions::Split(message["Identifier"],"|",idparts);\r
225                         StringFunctions::Convert(idparts[1],identityid);\r
226                         RemoveFromRequestList(identityid);\r
227                         return true;\r
228                 }\r
229         }\r
230 \r
231         return false;\r
232 }\r
233 \r
234 void IntroductionPuzzleRequester::Initialize()\r
235 {\r
236         std::string tempval="";\r
237         Option::Instance()->Get("MaxIntroductionPuzzleRequests",tempval);\r
238         StringFunctions::Convert(tempval,m_maxrequests);\r
239         if(m_maxrequests<1)\r
240         {\r
241                 m_maxrequests=1;\r
242                 m_log->error("Option MaxIntroductionPuzzleRequests is currently set at "+tempval+".  It must be 1 or greater.");\r
243         }\r
244         if(m_maxrequests>100)\r
245         {\r
246                 m_log->warning("Option MaxIntroductionPuzzleRequests is currently set at "+tempval+".  This value might be incorrectly configured.");\r
247         }\r
248         Option::Instance()->Get("MessageBase",m_messagebase);\r
249         m_tempdate=Poco::Timestamp();\r
250 }\r
251 \r
252 void IntroductionPuzzleRequester::PopulateIDList()\r
253 {\r
254         Poco::DateTime now;\r
255         int id;\r
256         std::string limitnum="30";\r
257 \r
258         // if we don't have an identity that we haven't seen yet, then set limit to 5\r
259         SQLite3DB::Statement st=m_db->Prepare("SELECT tblLocalIdentity.LocalIdentityID FROM tblLocalIdentity LEFT JOIN tblIdentity ON tblLocalIdentity.PublicKey=tblIdentity.PublicKey WHERE tblIdentity.IdentityID IS NULL;");\r
260         st.Step();\r
261         if(!st.RowReturned())\r
262         {\r
263                 limitnum="5";\r
264         }\r
265         st.Finalize();\r
266 \r
267         // select identities that aren't single use, are publishing a trust list, and have been seen today ( order by trust DESC and limit to limitnum )\r
268         st=m_db->Prepare("SELECT IdentityID FROM tblIdentity WHERE PublishTrustList='true' AND PublicKey IS NOT NULL AND PublicKey <> '' AND SingleUse='false' AND LastSeen>='"+Poco::DateTimeFormatter::format(now,"%Y-%m-%d")+"' ORDER BY LocalMessageTrust DESC LIMIT 0,"+limitnum+";");\r
269         st.Step();\r
270 \r
271         m_ids.clear();\r
272 \r
273         while(st.RowReturned())\r
274         {\r
275                 st.ResultInt(0,id);\r
276                 m_ids[id]=false;\r
277                 st.Step();\r
278         }\r
279 }\r
280 \r
281 void IntroductionPuzzleRequester::Process()\r
282 {\r
283         // max is the smaller of the config value or the total number of identities we will request from\r
284         long max=m_maxrequests>m_ids.size() ? m_ids.size() : m_maxrequests;\r
285 \r
286         // try to keep up to max requests going\r
287         if(m_requesting.size()<max)\r
288         {\r
289                 std::map<long,bool>::iterator i=m_ids.begin();\r
290                 while(i!=m_ids.end() && (*i).second==true)\r
291                 {\r
292                         i++;\r
293                 }\r
294 \r
295                 if(i!=m_ids.end())\r
296                 {\r
297                         StartRequest((*i).first);\r
298                 }\r
299                 else\r
300                 {\r
301                         // we requested from all ids in the list, repopulate the list\r
302                         PopulateIDList();\r
303                 }\r
304         }\r
305         // 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
306         // this will recheck for ids every minute\r
307         Poco::DateTime now;\r
308         if(m_ids.size()==0 && m_tempdate<(now-Poco::Timespan(0,0,1,0,0)))\r
309         {\r
310                 PopulateIDList();\r
311                 m_tempdate=now;\r
312         }\r
313 }\r
314 \r
315 void IntroductionPuzzleRequester::RegisterWithThread(FreenetMasterThread *thread)\r
316 {\r
317         thread->RegisterFCPConnected(this);\r
318         thread->RegisterFCPMessageHandler(this);\r
319         thread->RegisterPeriodicProcessor(this);\r
320 }\r
321 \r
322 void IntroductionPuzzleRequester::RemoveFromRequestList(const long identityid)\r
323 {\r
324         std::vector<long>::iterator i=m_requesting.begin();\r
325         while(i!=m_requesting.end() && (*i)!=identityid)\r
326         {\r
327                 i++;\r
328         }\r
329         if(i!=m_requesting.end())\r
330         {\r
331                 m_requesting.erase(i);\r
332         }\r
333 }\r
334 \r
335 void IntroductionPuzzleRequester::StartRequest(const long identityid)\r
336 {\r
337         Poco::DateTime now;\r
338         FCPMessage message;\r
339         std::string publickey;\r
340         int index;\r
341         std::string indexstr;\r
342         std::string identityidstr;\r
343 \r
344         SQLite3DB::Statement st=m_db->Prepare("SELECT PublicKey FROM tblIdentity WHERE IdentityID=?;");\r
345         st.Bind(0,identityid);\r
346         st.Step();\r
347 \r
348         if(st.RowReturned())\r
349         {\r
350                 st.ResultText(0,publickey);\r
351 \r
352                 now=Poco::Timestamp();\r
353 \r
354                 SQLite3DB::Statement st2=m_db->Prepare("SELECT MAX(RequestIndex) FROM tblIntroductionPuzzleRequests WHERE Day=? AND IdentityID=?;");\r
355                 st2.Bind(0,Poco::DateTimeFormatter::format(now,"%Y-%m-%d"));\r
356                 st2.Bind(1,identityid);\r
357                 st2.Step();\r
358 \r
359                 index=0;\r
360                 if(st2.RowReturned())\r
361                 {\r
362                         if(st2.ResultNull(0)==false)\r
363                         {\r
364                                 st2.ResultInt(0,index);\r
365                                 index++;\r
366                         }\r
367                 }\r
368                 st2.Finalize();\r
369 \r
370                 StringFunctions::Convert(index,indexstr);\r
371                 StringFunctions::Convert(identityid,identityidstr);\r
372 \r
373                 message.SetName("ClientGet");\r
374                 message["URI"]=publickey+m_messagebase+"|"+Poco::DateTimeFormatter::format(now,"%Y-%m-%d")+"|IntroductionPuzzle|"+indexstr+".xml";\r
375                 message["Identifier"]="IntroductionPuzzleRequester|"+identityidstr+"|"+indexstr+"|"+message["URI"];\r
376                 message["ReturnType"]="direct";\r
377                 message["MaxSize"]="1000000";           // 1 MB\r
378 \r
379                 m_fcp->SendMessage(message);\r
380                 \r
381                 m_requesting.push_back(identityid);\r
382         }\r
383 \r
384         m_ids[identityid]=true;\r
385 }\r