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