version 0.3.20
[fms.git] / src / freenet / introductionpuzzleinserter.cpp
1 #include "../../include/freenet/introductionpuzzleinserter.h"\r
2 #include "../../include/freenet/introductionpuzzlexml.h"\r
3 #include "../../include/stringfunctions.h"\r
4 #include "../../include/option.h"\r
5 #include "../../include/freenet/captcha/simplecaptcha.h"\r
6 #ifdef ALTERNATE_CAPTCHA\r
7 #include "../../include/freenet/captcha/alternatecaptcha1.h"\r
8 #include "../../include/freenet/captcha/alternatecaptcha2.h"\r
9 #endif\r
10 #include "../../include/base64.h"\r
11 \r
12 #include <Poco/DateTimeFormatter.h>\r
13 #include <Poco/UUIDGenerator.h>\r
14 #include <Poco/UUID.h>\r
15 \r
16 #ifdef XMEM\r
17         #include <xmem.h>\r
18 #endif\r
19 \r
20 IntroductionPuzzleInserter::IntroductionPuzzleInserter():IIndexInserter<long>()\r
21 {\r
22         Initialize();\r
23 }\r
24 \r
25 IntroductionPuzzleInserter::IntroductionPuzzleInserter(FCPv2 *fcp):IIndexInserter<long>(fcp)\r
26 {\r
27         Initialize();\r
28 }\r
29 \r
30 void IntroductionPuzzleInserter::CheckForNeededInsert()\r
31 {\r
32         // only do 1 insert at a time\r
33         if(m_inserting.size()==0)\r
34         {\r
35                 // select all local ids that aren't single use and that aren't currently inserting a puzzle and are publishing a trust list\r
36                 SQLite3DB::Recordset rs=m_db->Query("SELECT LocalIdentityID FROM tblLocalIdentity WHERE PublishTrustList='true' AND SingleUse='false' AND PrivateKey IS NOT NULL AND PrivateKey <> '' ORDER BY LastInsertedPuzzle;");\r
37                 \r
38                 while(!rs.AtEnd())\r
39                 {\r
40                         int localidentityid=0;\r
41                         std::string localidentityidstr="";\r
42                         Poco::DateTime now;\r
43                         float minutesbetweeninserts=0;\r
44                         minutesbetweeninserts=1440.0/(float)m_maxpuzzleinserts;\r
45                         Poco::DateTime lastinsert=now;\r
46                         lastinsert-=Poco::Timespan(0,0,minutesbetweeninserts,0,0);\r
47 \r
48                         if(rs.GetField(0))\r
49                         {\r
50                                 localidentityidstr=rs.GetField(0);\r
51                         }\r
52 \r
53                         // if this identity has any non-solved puzzles for today, we don't need to insert a new puzzle\r
54                         SQLite3DB::Recordset rs2=m_db->Query("SELECT UUID FROM tblIntroductionPuzzleInserts WHERE Day='"+Poco::DateTimeFormatter::format(now,"%Y-%m-%d")+"' AND FoundSolution='false' AND LocalIdentityID="+localidentityidstr+";");\r
55 \r
56                         // identity doesn't have any non-solved puzzles for today - start a new insert\r
57                         if(rs2.Empty()==true)\r
58                         {\r
59                                 // make sure we are on the next day or the appropriate amount of time has elapsed since the last insert\r
60                                 if(m_lastinserted.find(rs.GetInt(0))==m_lastinserted.end() || m_lastinserted[rs.GetInt(0)]<=lastinsert || m_lastinserted[rs.GetInt(0)].day()!=now.day())\r
61                                 {\r
62                                         m_lastinserted[rs.GetInt(0)]=now;\r
63                                 }\r
64                                 else\r
65                                 {\r
66                                         m_log->trace("IntroductionPuzzleInserter::CheckForNeededInsert waiting to insert puzzle for "+localidentityidstr);\r
67                                 }\r
68                         }\r
69 \r
70                         rs.Next();\r
71                 }\r
72         }\r
73 }\r
74 \r
75 void IntroductionPuzzleInserter::GenerateCaptcha(std::string &encodeddata, std::string &solution)\r
76 {\r
77         ICaptcha *cap=0;\r
78 #ifdef ALTERNATE_CAPTCHA\r
79         if(rand()%2==0)\r
80         {\r
81                 cap=new AlternateCaptcha1();\r
82         }\r
83         else\r
84         {\r
85                 cap=new AlternateCaptcha2();\r
86         }\r
87         m_log->trace("IntroductionPuzzleInserter::GenerateCaptcha using alternate captcha generator");\r
88 #else\r
89         cap=new SimpleCaptcha();\r
90 #endif\r
91         std::vector<unsigned char> puzzle;\r
92         std::vector<unsigned char> puzzlesolution;\r
93 \r
94         cap->Generate();\r
95         cap->GetPuzzle(puzzle);\r
96         cap->GetSolution(puzzlesolution);\r
97 \r
98         encodeddata.clear();\r
99         solution.clear();\r
100 \r
101         Base64::Encode(puzzle,encodeddata);\r
102         solution.insert(solution.begin(),puzzlesolution.begin(),puzzlesolution.end());\r
103 \r
104         delete cap;\r
105 \r
106 }\r
107 \r
108 const bool IntroductionPuzzleInserter::HandlePutFailed(FCPMessage &message)\r
109 {\r
110         SQLite3DB::Statement st;\r
111         std::vector<std::string> idparts;\r
112         long localidentityid;\r
113 \r
114         StringFunctions::Split(message["Identifier"],"|",idparts);\r
115         StringFunctions::Convert(idparts[1],localidentityid);\r
116 \r
117         // non USK\r
118         if(idparts[0]==m_fcpuniquename)\r
119         {\r
120                 // if fatal error or collision - mark index\r
121                 if(message["Fatal"]=="true" || message["Code"]=="9")\r
122                 {\r
123                         m_db->Execute("UPDATE tblIntroductionPuzzleInserts SET Day='"+idparts[5]+"', InsertIndex="+idparts[2]+", FoundSolution='true' WHERE UUID='"+idparts[3]+"';");\r
124                 }\r
125 \r
126                 RemoveFromInsertList(localidentityid);\r
127 \r
128                 m_log->debug("IntroductionPuzzleInserter::HandlePutFailed failed to insert puzzle "+idparts[3]);\r
129         }\r
130 \r
131         return true;\r
132 }\r
133 \r
134 const bool IntroductionPuzzleInserter::HandlePutSuccessful(FCPMessage &message)\r
135 {\r
136         Poco::DateTime now;\r
137         SQLite3DB::Statement st;\r
138         std::vector<std::string> idparts;\r
139         long localidentityid;\r
140         long insertindex;\r
141 \r
142         StringFunctions::Split(message["Identifier"],"|",idparts);\r
143 \r
144         // non USK\r
145         if(idparts[0]==m_fcpuniquename)\r
146         {\r
147                 StringFunctions::Convert(idparts[1],localidentityid);\r
148                 StringFunctions::Convert(idparts[2],insertindex);\r
149 \r
150                 st=m_db->Prepare("UPDATE tblIntroductionPuzzleInserts SET Day=?, InsertIndex=? WHERE UUID=?;");\r
151                 st.Bind(0,idparts[5]);\r
152                 st.Bind(1,insertindex);\r
153                 st.Bind(2,idparts[3]);\r
154                 st.Step();\r
155                 st.Finalize();\r
156 \r
157                 st=m_db->Prepare("UPDATE tblLocalIdentity SET LastInsertedPuzzle=? WHERE LocalIdentityID=?;");\r
158                 st.Bind(0,Poco::DateTimeFormatter::format(now,"%Y-%m-%d %H:%M:%S"));\r
159                 st.Bind(1,localidentityid);\r
160                 st.Step();\r
161                 st.Finalize();\r
162 \r
163                 RemoveFromInsertList(localidentityid);\r
164 \r
165                 m_log->debug("IntroductionPuzzleInserter::HandlePutSuccessful inserted puzzle "+idparts[3]);\r
166         }\r
167 \r
168         return true;\r
169 }\r
170 \r
171 void IntroductionPuzzleInserter::Initialize()\r
172 {\r
173         m_fcpuniquename="IntroductionPuzzleInserter";\r
174         m_maxpuzzleinserts=50;\r
175 }\r
176 \r
177 const bool IntroductionPuzzleInserter::StartInsert(const long &localidentityid)\r
178 {\r
179         Poco::DateTime now;\r
180         std::string idstring="";\r
181         long index=0;\r
182         std::string indexstr="";\r
183         Poco::UUIDGenerator uuidgen;\r
184         Poco::UUID uuid;\r
185         std::string messagebase="";\r
186         IntroductionPuzzleXML xml;\r
187         std::string encodedpuzzle="";\r
188         std::string solutionstring="";\r
189         FCPMessage message;\r
190         std::string xmldata="";\r
191         std::string xmldatasizestr="";\r
192         std::string privatekey="";\r
193         std::string publickey="";\r
194         std::string keypart="";\r
195 \r
196         StringFunctions::Convert(localidentityid,idstring);\r
197         SQLite3DB::Recordset rs=m_db->Query("SELECT MAX(InsertIndex) FROM tblIntroductionPuzzleInserts WHERE Day='"+Poco::DateTimeFormatter::format(now,"%Y-%m-%d")+"' AND LocalIdentityID="+idstring+";");\r
198 \r
199         if(rs.Empty() || rs.GetField(0)==NULL)\r
200         {\r
201                 index=0;\r
202         }\r
203         else\r
204         {\r
205                 index=rs.GetInt(0)+1;\r
206         }\r
207         StringFunctions::Convert(index,indexstr);\r
208 \r
209         if(index<m_maxpuzzleinserts)\r
210         {\r
211                 SQLite3DB::Recordset rs2=m_db->Query("SELECT PrivateKey,PublicKey FROM tblLocalIdentity WHERE LocalIdentityID="+idstring+";");\r
212                 if(rs2.Empty()==false && rs2.GetField(0)!=NULL)\r
213                 {\r
214                         privatekey=rs2.GetField(0);\r
215                         if(rs2.GetField(1))\r
216                         {\r
217                                 publickey=rs2.GetField(1);\r
218                         }\r
219                         if(publickey.size()>=50)\r
220                         {\r
221                                 // remove - and ~\r
222                                 keypart=StringFunctions::Replace(StringFunctions::Replace(publickey.substr(4,43),"-",""),"~","");\r
223                         }\r
224                 }\r
225 \r
226                 Option::Instance()->Get("MessageBase",messagebase);\r
227 \r
228                 GenerateCaptcha(encodedpuzzle,solutionstring);\r
229                 if(encodedpuzzle.size()==0)\r
230                 {\r
231                         m_log->fatal("IntroductionPuzzleInserter::StartInsert could not create introduction puzzle");\r
232                         return false;\r
233                 }\r
234 \r
235                 try\r
236                 {\r
237                         uuid=uuidgen.createRandom();\r
238                 }\r
239                 catch(...)\r
240                 {\r
241                         m_log->fatal("IntroductionPuzzleInserter::StartInsert could not create UUID");\r
242                 }\r
243 \r
244                 xml.SetType("captcha");\r
245                 std::string uuidstr=uuid.toString();\r
246                 StringFunctions::UpperCase(uuidstr,uuidstr);\r
247                 xml.SetUUID(uuidstr+"@"+keypart);\r
248                 xml.SetPuzzleData(encodedpuzzle);\r
249                 xml.SetMimeType("image/bmp");\r
250 \r
251                 xmldata=xml.GetXML();\r
252                 StringFunctions::Convert(xmldata.size(),xmldatasizestr);\r
253 \r
254                 message.SetName("ClientPut");\r
255                 message["URI"]=privatekey+messagebase+"|"+Poco::DateTimeFormatter::format(now,"%Y-%m-%d")+"|IntroductionPuzzle|"+indexstr+".xml";\r
256                 message["Identifier"]=m_fcpuniquename+"|"+idstring+"|"+indexstr+"|"+xml.GetUUID()+"|"+message["URI"];\r
257                 message["UploadFrom"]="direct";\r
258                 message["DataLength"]=xmldatasizestr;\r
259                 m_fcp->SendMessage(message);\r
260                 m_fcp->SendRaw(xmldata.c_str(),xmldata.size());\r
261 \r
262                 // insert to USK\r
263                 message.Reset();\r
264                 message.SetName("ClientPutComplexDir");\r
265                 message["URI"]="USK"+privatekey.substr(3)+messagebase+"|"+Poco::DateTimeFormatter::format(now,"%Y.%m.%d")+"|IntroductionPuzzle/0/";\r
266                 message["Identifier"]=m_fcpuniquename+"USK|"+message["URI"];\r
267                 message["DefaultName"]="IntroductionPuzzle.xml";\r
268                 message["Files.0.Name"]="IntroductionPuzzle.xml";\r
269                 message["Files.0.UplaodFrom"]="direct";\r
270                 message["Files.0.DataLength"]=xmldatasizestr;\r
271                 m_fcp->SendMessage(message);\r
272                 m_fcp->SendRaw(xmldata.c_str(),xmldata.size());\r
273 \r
274                 m_db->Execute("INSERT INTO tblIntroductionPuzzleInserts(UUID,Type,MimeType,LocalIdentityID,PuzzleData,PuzzleSolution) VALUES('"+xml.GetUUID()+"','captcha','image/bmp',"+idstring+",'"+encodedpuzzle+"','"+solutionstring+"');");\r
275 \r
276                 m_inserting.push_back(localidentityid);\r
277 \r
278                 m_log->debug("IntroductionPuzzleInserter::StartInsert started insert for id "+idstring);\r
279         }\r
280         else\r
281         {\r
282                 m_log->warning("IntroductionPuzzleInserter::StartInsert already inserted max puzzles for "+idstring);\r
283         }\r
284 \r
285         return true;\r
286 \r
287 }\r