version 0.0.4
[fms.git] / src / freenet / trustlistrequester.cpp
1 #include "../../include/freenet/trustlistrequester.h"\r
2 #include "../../include/option.h"\r
3 #include "../../include/stringfunctions.h"\r
4 #include "../../include/freenet/trustlistxml.h"\r
5 \r
6 #ifdef XMEM\r
7         #include <xmem.h>\r
8 #endif\r
9 \r
10 TrustListRequester::TrustListRequester()\r
11 {\r
12         Initialize();\r
13 }\r
14 \r
15 TrustListRequester::TrustListRequester(FCPv2 *fcp):IFCPConnected(fcp)\r
16 {\r
17         Initialize();\r
18 }\r
19 \r
20 void TrustListRequester::FCPConnected()\r
21 {\r
22         m_requesting.clear();\r
23         PopulateIDList();\r
24 }\r
25 \r
26 void TrustListRequester::FCPDisconnected()\r
27 {\r
28         \r
29 }\r
30 \r
31 const bool TrustListRequester::HandleAllData(FCPMessage &message)\r
32 {\r
33         DateTime now;\r
34         SQLite3DB::Statement st;\r
35         SQLite3DB::Statement trustst;\r
36         std::vector<std::string> idparts;\r
37         long datalength;\r
38         std::vector<char> data;\r
39         TrustListXML xml;\r
40         long identityid;\r
41         long index;\r
42 \r
43         now.SetToGMTime();\r
44         StringFunctions::Split(message["Identifier"],"|",idparts);\r
45         StringFunctions::Convert(message["DataLength"],datalength);\r
46         StringFunctions::Convert(idparts[1],identityid);\r
47         StringFunctions::Convert(idparts[2],index);\r
48 \r
49         // wait for all data to be received from connection\r
50         while(m_fcp->Connected() && m_fcp->ReceiveBufferSize()<datalength)\r
51         {\r
52                 m_fcp->Update(1);\r
53         }\r
54 \r
55         // if we got disconnected- return immediately\r
56         if(m_fcp->Connected()==false)\r
57         {\r
58                 return false;\r
59         }\r
60 \r
61         // receive the file\r
62         data.resize(datalength);\r
63         m_fcp->ReceiveRaw(&data[0],datalength);\r
64 \r
65         // parse file into xml and update the database\r
66         if(xml.ParseXML(std::string(data.begin(),data.end()))==true)\r
67         {\r
68 \r
69                 // drop all existing peer trust from this identity - we will rebuild it when we go through each trust in the xml file\r
70                 st=m_db->Prepare("DELETE FROM tblPeerTrust WHERE IdentityID=?;");\r
71                 st.Bind(0,identityid);\r
72                 st.Step();\r
73                 st.Finalize();\r
74 \r
75                 st=m_db->Prepare("SELECT IdentityID FROM tblIdentity WHERE PublicKey=?;");\r
76                 trustst=m_db->Prepare("INSERT INTO tblPeerTrust(IdentityID,TargetIdentityID,MessageTrust,TrustListTrust) VALUES(?,?,?,?);");\r
77                 // loop through all trust entries in xml and add to database if we don't already know them\r
78                 for(long i=0; i<xml.TrustCount(); i++)\r
79                 {\r
80                         int id;\r
81                         std::string identity;\r
82                         identity=xml.GetIdentity(i);\r
83 \r
84                         st.Bind(0,identity);\r
85                         st.Step();\r
86                         if(st.RowReturned()==false)\r
87                         {\r
88                                 m_db->ExecuteInsert("INSERT INTO tblIdentity(PublicKey,DateAdded) VALUES('"+identity+"','"+now.Format("%Y-%m-%d %H:%M:%S")+"');",(long &)id);\r
89                         }\r
90                         else\r
91                         {\r
92                                 st.ResultInt(0,id);\r
93                         }\r
94                         st.Reset();\r
95 \r
96                         //insert trust for this identity\r
97                         trustst.Bind(0,identityid);\r
98                         trustst.Bind(1,id);\r
99                         trustst.Bind(2,xml.GetMessageTrust(i));\r
100                         trustst.Bind(3,xml.GetTrustListTrust(i));\r
101                         trustst.Step();\r
102                         trustst.Reset();\r
103 \r
104                 }\r
105                 trustst.Finalize();\r
106                 st.Finalize();\r
107 \r
108                 st=m_db->Prepare("INSERT INTO tblTrustListRequests(IdentityID,Day,RequestIndex,Found) VALUES(?,?,?,'true');");\r
109                 st.Bind(0,identityid);\r
110                 st.Bind(1,idparts[4]);\r
111                 st.Bind(2,index);\r
112                 st.Step();\r
113                 st.Finalize();\r
114 \r
115                 m_log->WriteLog(LogFile::LOGLEVEL_DEBUG,"TrustListRequester::HandleAllData parsed TrustList XML file : "+message["Identifier"]);\r
116         }\r
117         else\r
118         {\r
119                 // bad data - mark index\r
120                 st=m_db->Prepare("INSERT INTO tblTrustListRequests(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,"TrustListRequester::HandleAllData error parsing TrustList XML file : "+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 TrustListRequester::HandleGetFailed(FCPMessage &message)\r
138 {\r
139         DateTime now;\r
140         SQLite3DB::Statement st;\r
141         std::vector<std::string> idparts;\r
142         long identityid;\r
143         long index;\r
144 \r
145         now.SetToGMTime();\r
146         StringFunctions::Split(message["Identifier"],"|",idparts);\r
147         StringFunctions::Convert(idparts[1],identityid);\r
148         StringFunctions::Convert(idparts[2],index);     \r
149 \r
150         // if this is a fatal error - insert index into database so we won't try to download this index again\r
151         if(message["Fatal"]=="true")\r
152         {\r
153                 st=m_db->Prepare("INSERT INTO tblTrustListRequests(IdentityID,Day,RequestIndex,Found) VALUES(?,?,?,'false');");\r
154                 st.Bind(0,identityid);\r
155                 st.Bind(1,idparts[4]);\r
156                 st.Bind(2,index);\r
157                 st.Step();\r
158                 st.Finalize();\r
159 \r
160                 m_log->WriteLog(LogFile::LOGLEVEL_ERROR,"TrustListRequester::HandleGetFailed fatal error requesting "+message["Identifier"]);\r
161         }\r
162 \r
163         // remove this identityid from request list\r
164         RemoveFromRequestList(identityid);\r
165 \r
166         return true;\r
167 \r
168 }\r
169 \r
170 const bool TrustListRequester::HandleMessage(FCPMessage &message)\r
171 {\r
172 \r
173         if(message["Identifier"].find("TrustListRequester")==0)\r
174         {\r
175                 if(message.GetName()=="DataFound")\r
176                 {\r
177                         return true;\r
178                 }\r
179 \r
180                 if(message.GetName()=="AllData")\r
181                 {\r
182                         return HandleAllData(message);\r
183                 }\r
184 \r
185                 if(message.GetName()=="GetFailed")\r
186                 {\r
187                         return HandleGetFailed(message);\r
188                 }\r
189 \r
190                 if(message.GetName()=="IdentifierCollision")\r
191                 {\r
192                         // remove one of the ids from the requesting list\r
193                         long identityid=0;\r
194                         std::vector<std::string> idparts;\r
195                         StringFunctions::Split(message["Identifier"],"|",idparts);\r
196                         StringFunctions::Convert(idparts[1],identityid);\r
197                         RemoveFromRequestList(identityid);\r
198                         return true;\r
199                 }\r
200         }\r
201 \r
202         return false;\r
203 }\r
204 \r
205 void TrustListRequester::Initialize()\r
206 {\r
207         std::string tempval="";\r
208         Option::instance()->Get("MaxIdentityRequests",tempval);\r
209         StringFunctions::Convert(tempval,m_maxrequests);\r
210         if(m_maxrequests<1)\r
211         {\r
212                 m_maxrequests=1;\r
213                 m_log->WriteLog(LogFile::LOGLEVEL_ERROR,"Option MaxTrustListRequests is currently set at "+tempval+".  It must be 1 or greater.");\r
214         }\r
215         if(m_maxrequests>100)\r
216         {\r
217                 m_log->WriteLog(LogFile::LOGLEVEL_WARNING,"Option MaxTrustListRequests is currently set at "+tempval+".  This value might be incorrectly configured.");\r
218         }\r
219         Option::instance()->Get("MessageBase",m_messagebase);\r
220         m_tempdate.SetToGMTime();\r
221 }\r
222 \r
223 void TrustListRequester::PopulateIDList()\r
224 {\r
225         DateTime date;\r
226         int id;\r
227 \r
228         date.SetToGMTime();\r
229 \r
230         // select identities we want to query (we've seen them today and they are publishing trust list) - sort by their trust level (descending) with secondary sort on how long ago we saw them (ascending)\r
231         SQLite3DB::Statement st=m_db->Prepare("SELECT IdentityID FROM tblIdentity WHERE PublicKey IS NOT NULL AND PublicKey <> '' AND LastSeen>='"+date.Format("%Y-%m-%d")+"' AND PublishTrustList='true' AND LocalTrustListTrust>=(SELECT OptionValue FROM tblOption WHERE Option='MinLocalTrustListTrust') ORDER BY LocalMessageTrust+LocalTrustListTrust DESC, LastSeen;");\r
232         st.Step();\r
233 \r
234         m_ids.clear();\r
235 \r
236         while(st.RowReturned())\r
237         {\r
238                 st.ResultInt(0,id);\r
239                 m_ids[id]=false;\r
240                 st.Step();\r
241         }\r
242 }\r
243 \r
244 void TrustListRequester::Process()\r
245 {\r
246         // max is the smaller of the config value or the total number of identities we will request from\r
247         long max=m_maxrequests>m_ids.size() ? m_ids.size() : m_maxrequests;\r
248 \r
249         // try to keep up to max requests going\r
250         if(m_requesting.size()<max)\r
251         {\r
252                 std::map<long,bool>::iterator i=m_ids.begin();\r
253                 while(i!=m_ids.end() && (*i).second==true)\r
254                 {\r
255                         i++;\r
256                 }\r
257 \r
258                 if(i!=m_ids.end())\r
259                 {\r
260                         StartRequest((*i).first);\r
261                 }\r
262                 else\r
263                 {\r
264                         // we requested from all ids in the list, repopulate the list\r
265                         PopulateIDList();\r
266                 }\r
267         }\r
268         // 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
269         // this will recheck for ids every minute\r
270         DateTime now;\r
271         now.SetToGMTime();\r
272         if(m_tempdate<(now-(1.0/1440.0)))\r
273         {\r
274                 PopulateIDList();\r
275                 m_tempdate=now;\r
276         }\r
277 \r
278 }\r
279 \r
280 void TrustListRequester::RegisterWithThread(FreenetMasterThread *thread)\r
281 {\r
282         thread->RegisterFCPConnected(this);\r
283         thread->RegisterFCPMessageHandler(this);\r
284         thread->RegisterPeriodicProcessor(this);\r
285 }\r
286 \r
287 void TrustListRequester::RemoveFromRequestList(const long identityid)\r
288 {\r
289         std::vector<long>::iterator i=m_requesting.begin();\r
290         while(i!=m_requesting.end() && (*i)!=identityid)\r
291         {\r
292                 i++;\r
293         }\r
294         if(i!=m_requesting.end())\r
295         {\r
296                 m_requesting.erase(i);\r
297         }\r
298 }\r
299 \r
300 void TrustListRequester::StartRequest(const long identityid)\r
301 {\r
302         DateTime now;\r
303         FCPMessage message;\r
304         std::string publickey;\r
305         int index;\r
306         std::string indexstr;\r
307         std::string identityidstr;\r
308 \r
309         SQLite3DB::Statement st=m_db->Prepare("SELECT PublicKey FROM tblIdentity WHERE IdentityID=?;");\r
310         st.Bind(0,identityid);\r
311         st.Step();\r
312 \r
313         if(st.RowReturned())\r
314         {\r
315                 st.ResultText(0,publickey);\r
316 \r
317                 now.SetToGMTime();\r
318 \r
319                 SQLite3DB::Statement st2=m_db->Prepare("SELECT MAX(RequestIndex) FROM tblTrustListRequests WHERE Day=? AND IdentityID=?;");\r
320                 st2.Bind(0,now.Format("%Y-%m-%d"));\r
321                 st2.Bind(1,identityid);\r
322                 st2.Step();\r
323 \r
324                 index=0;\r
325                 if(st2.RowReturned())\r
326                 {\r
327                         if(st2.ResultNull(0)==false)\r
328                         {\r
329                                 st2.ResultInt(0,index);\r
330                                 index++;\r
331                         }\r
332                 }\r
333                 st2.Finalize();\r
334 \r
335                 StringFunctions::Convert(index,indexstr);\r
336                 StringFunctions::Convert(identityid,identityidstr);\r
337 \r
338                 message.SetName("ClientGet");\r
339                 message["URI"]=publickey+m_messagebase+"|"+now.Format("%Y-%m-%d")+"|TrustList|"+indexstr+".xml";\r
340                 message["Identifier"]="TrustListRequester|"+identityidstr+"|"+indexstr+"|"+message["URI"];\r
341                 message["ReturnType"]="direct";\r
342                 message["MaxSize"]="1000000";                   // 1 MB\r
343 \r
344                 m_fcp->SendMessage(message);\r
345 \r
346                 m_requesting.push_back(identityid);\r
347         }\r
348         st.Finalize();\r
349 \r
350         m_ids[identityid]=true;\r
351 \r
352 }\r