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