version 0.1.7
[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         std::string sql;\r
228 \r
229         date.SetToGMTime();\r
230 \r
231         // 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
232         sql="SELECT IdentityID FROM tblIdentity ";\r
233         sql+="WHERE Name IS NOT NULL AND Name <> '' AND 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') AND ( PeerTrustListTrust IS NULL OR PeerTrustListTrust>=(SELECT OptionValue FROM tblOption WHERE Option='MinPeerTrustListTrust') )";\r
234         sql+="ORDER BY LocalMessageTrust+LocalTrustListTrust DESC, LastSeen;";\r
235 \r
236         SQLite3DB::Statement st=m_db->Prepare(sql);\r
237         st.Step();\r
238 \r
239         m_ids.clear();\r
240 \r
241         while(st.RowReturned())\r
242         {\r
243                 st.ResultInt(0,id);\r
244                 m_ids[id]=false;\r
245                 st.Step();\r
246         }\r
247 }\r
248 \r
249 void TrustListRequester::Process()\r
250 {\r
251         // max is the smaller of the config value or the total number of identities we will request from\r
252         long max=m_maxrequests>m_ids.size() ? m_ids.size() : m_maxrequests;\r
253 \r
254         // try to keep up to max requests going\r
255         if(m_requesting.size()<max)\r
256         {\r
257                 std::map<long,bool>::iterator i=m_ids.begin();\r
258                 while(i!=m_ids.end() && (*i).second==true)\r
259                 {\r
260                         i++;\r
261                 }\r
262 \r
263                 if(i!=m_ids.end())\r
264                 {\r
265                         StartRequest((*i).first);\r
266                 }\r
267                 else\r
268                 {\r
269                         // we requested from all ids in the list, repopulate the list\r
270                         PopulateIDList();\r
271                 }\r
272         }\r
273         // 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
274         // this will recheck for ids every minute\r
275         DateTime now;\r
276         now.SetToGMTime();\r
277         if(m_ids.size()==0 && m_tempdate<(now-(1.0/1440.0)))\r
278         {\r
279                 PopulateIDList();\r
280                 m_tempdate=now;\r
281         }\r
282 \r
283 }\r
284 \r
285 void TrustListRequester::RegisterWithThread(FreenetMasterThread *thread)\r
286 {\r
287         thread->RegisterFCPConnected(this);\r
288         thread->RegisterFCPMessageHandler(this);\r
289         thread->RegisterPeriodicProcessor(this);\r
290 }\r
291 \r
292 void TrustListRequester::RemoveFromRequestList(const long identityid)\r
293 {\r
294         std::vector<long>::iterator i=m_requesting.begin();\r
295         while(i!=m_requesting.end() && (*i)!=identityid)\r
296         {\r
297                 i++;\r
298         }\r
299         if(i!=m_requesting.end())\r
300         {\r
301                 m_requesting.erase(i);\r
302         }\r
303 }\r
304 \r
305 void TrustListRequester::StartRequest(const long identityid)\r
306 {\r
307         DateTime now;\r
308         FCPMessage message;\r
309         std::string publickey;\r
310         int index;\r
311         std::string indexstr;\r
312         std::string identityidstr;\r
313 \r
314         SQLite3DB::Statement st=m_db->Prepare("SELECT PublicKey FROM tblIdentity WHERE IdentityID=?;");\r
315         st.Bind(0,identityid);\r
316         st.Step();\r
317 \r
318         if(st.RowReturned())\r
319         {\r
320                 st.ResultText(0,publickey);\r
321 \r
322                 now.SetToGMTime();\r
323 \r
324                 SQLite3DB::Statement st2=m_db->Prepare("SELECT MAX(RequestIndex) FROM tblTrustListRequests WHERE Day=? AND IdentityID=?;");\r
325                 st2.Bind(0,now.Format("%Y-%m-%d"));\r
326                 st2.Bind(1,identityid);\r
327                 st2.Step();\r
328 \r
329                 index=0;\r
330                 if(st2.RowReturned())\r
331                 {\r
332                         if(st2.ResultNull(0)==false)\r
333                         {\r
334                                 st2.ResultInt(0,index);\r
335                                 index++;\r
336                         }\r
337                 }\r
338                 st2.Finalize();\r
339 \r
340                 StringFunctions::Convert(index,indexstr);\r
341                 StringFunctions::Convert(identityid,identityidstr);\r
342 \r
343                 message.SetName("ClientGet");\r
344                 message["URI"]=publickey+m_messagebase+"|"+now.Format("%Y-%m-%d")+"|TrustList|"+indexstr+".xml";\r
345                 message["Identifier"]="TrustListRequester|"+identityidstr+"|"+indexstr+"|"+message["URI"];\r
346                 message["ReturnType"]="direct";\r
347                 message["MaxSize"]="1000000";                   // 1 MB\r
348 \r
349                 m_fcp->SendMessage(message);\r
350 \r
351                 m_requesting.push_back(identityid);\r
352         }\r
353         st.Finalize();\r
354 \r
355         m_ids[identityid]=true;\r
356 \r
357 }\r